text:
{% extends 'base.html' %}

{% load i18n %}
{% load bootstrap3 %}
{% load embed_video_tags %}

{% block head %}
{{ form.media }}
{% endblock %}

{% block breadcrumb %}

 Dashboard

 Content

 Stories

        {% if facet %}

 {{ facet.story.name }}

 {{ facet.name }}

        {% else %}

 {{ form.instance.story.name }}

        {% endif %}

{% endblock breadcrumb %}

{% block content %}

Story Detail

 |

        {% for facet in facet.story.facet_set.all %}
        {% if facet.id|stringformat:"s" == view.facet_kwargs %}

{{ facet.name }}

        {% else %}

{{ facet.name }}

        {% endif %}
        {% endfor %}

 Add Facet

Details
      {% if facet %}
      <form class="facet-delete sameline" method="GET"
            action="{% url 'facet_delete' pk=facet.id story=facet.story.id %}">

            {% csrf_token %}

      </form>
        {% if facet.template.organization %}

        {% else %}

        {% endif %}

      {% endif %}

        <form method="POST" class="post-form">
            {% csrf_token %}

                    <fieldset class="form-group m-b-20">
                        {{ form.template.label_tag }}
                        {{ form.template }}
                        {% if form.template.errors %}
                          {{ form.template.errors }}
                        {% endif %}
                    </fieldset>

                    <fieldset class="form-group m-b-20">
                        {{ form.status.label_tag }}
                        {{ form.status }}
                        {% if form.status.errors %}
                          {{ form.status.errors }}
                        {% endif %}
                    </fieldset>

                    <fieldset class="form-group m-b-10">
                       Label:
                      {{ form.name }}
                      {% if form.name.errors %}
                        {{ form.name.errors }}
                      {% endif %}
                    </fieldset>

                    <fieldset class="form-group m-b-10">
                      Description
                      {{ form.description }}
                      {% if form.description.errors %}
                        {{ form.description.errors }}
                      {% endif %}
                    </fieldset>

                    <fieldset class="form-group m-b-10">
                      {{ form.due_edit.label_tag }}
                      {{ form.due_edit }}
                      {% if form.due_edit.errors %}
                      {{ form.due_edit.errors }}
                      {% endif %}
                    </fieldset>

                    <fieldset class="form-group m-b-10">
                      {{ form.run_date.label_tag }}
                      {{ form.run_date }}
                      {% if form.run_date.errors %}
                      {{ form.run_date.errors }}
                      {% endif %}
                    </fieldset>

                    <fieldset class="form-group m-b-10">
                      {{ form.credit.label_tag }}
                      {{ form.credit }}
                      {% if form.credit.errors %}
                        {{ form.credit.errors }}
                      {% endif %}
                    </fieldset>

                    <fieldset class="form-group m-b-10">
                      {{ form.editor.label_tag }}
                      {{ form.editor }}
                      {% if form.editor.errors %}
                        {{ form.editor.errors }}
                      {% endif %}
                    </fieldset>

                            {% if not facet %}

 Add a headline and click save to complete creation of this facet.

                            {% endif %}

                            <fieldset class="form-group">
                              {% comment %}
                              {{ form.headline.label_tag }}
                              {% endcomment %}
                              {{ form.headline }}
                              {% if form.headline.errors %}
                                {{ form.headline.errors }}
                              {% endif %}
                            </fieldset>

                            <button type="submit" class="btn btn-info btn-sm btn-block" name="form">Save Changes</button>

                    <fieldset class="form-group m-b-10">
                      {{ form.content }}
                      {% if form.content.errors %}
                        {{ form.content.errors }}
                      {% endif %}
                    </fieldset>

                    <fieldset class="form-group m-b-10">
                      {% comment %}{{ form.keywords.label_tag }}{% endcomment %}
                      {{ form.keywords }}
                      {% if form.keywords.errors %}
                        {{ form.keywords.errors }}
                      {% endif %}
                    </fieldset>

            {% if facet %}

                      {% with view.facet_image_assets as facet_images %}

Images

                            {% for image in facet_images.images %}
                              {% if image.display_photo %}

                                  <button type="button" class="btn btn-sm clear-button f-r-6 subtle" title="Remove this image" data-toggle="modal" data-target="#removeImageModal" data-imageid="{{ image.id }}" data-imageurl="{{ image.display_photo.url }}" data-actionurl="{% url 'image_asset_remove' image=image.id facet=facet.id %}">Remove</button>

                                {% comment %}

                                {% endcomment %}
                                {% if forloop.counter|divisibleby:"3" and not forloop.last %}

                                {% endif %}
                              {% endif %}
                            {% endfor %}

                      {% endwith %}

                      {% with view.facet_document_assets as facet_documents %}

Documents

                        {% for document in facet_documents.documents %}

                            {% if document.asset_type == 'OTHER' %}

 {{ document.title }}

                            {% endif %}
                            {% if document.asset_type == 'TEXT' %}

 {{ document.title }}

                            {% endif %}
                            {% if document.asset_type == 'WORD DOC' %}

 {{ document.title }}

                            {% endif %}
                            {% if document.asset_type == 'EXCEL' %}

 {{ document.title }}

                            {% endif %}
                            {% if document.asset_type == 'PDF' %}

 {{ document.title }}

                            {% endif %}
                            {% if document.asset_type == 'COMMA SEPARATED' %}

 {{ document.title }}

                            {% endif %}

                            <button type="button"
                                    class="btn btn-sm clear-button f-r-6 subtle m-b-10"
                                    title="Remove this document"
                                    data-toggle="modal"
                                    data-target="#removeDocumentModal"
                                    data-detailurl="{% url 'document_asset_detail' document.id %}"
                                    data-actionurl="{% url 'document_asset_remove' document=document.id facet=facet.id %}"
                                    data-doctitle="{{ document.title }}"
                                    data-doctype="{{ document.asset_type }}">
                                    Remove
                            </button>
                          {% if forloop.counter|divisibleby:"2" and not forloop.last %}

                          {% endif %}

                        {% endfor %}

                      {% endwith %}

                      {% with view.facet_audio_assets as facet_audio %}

Audio

                        {% for audio in facet_audio.audio %}

                          {% if audio.asset_type == 'MP3' or audio.asset_type == 'WAV' %}

                                  <button class="jp-play jp-button" role="button" aria-label="play" tabindex="0"></button>

                                  Media Player Error

                                  Update your browser or Flash plugin

                            {% endif %}
                            {% if audio.asset_type == 'SC' %}
                                 {{ audio.title }}
                            {% endif %}

                            <button type="button"
                                    class="btn btn-sm clear-button f-r-6 subtle"
                                    title="Remove this audio"
                                    data-toggle="modal"
                                    data-target="#removeAudioModal"
                                    data-actionurl="{% url 'audio_asset_remove' audio=audio.id facet=facet.id %}"
                                    data-audiotitle="{{ audio.title }}"
                                    data-audiotype="{{ audio.asset_type }}"
                                    data-audioid="{{audio.id}}"
                                    data-audiourl="{{audio.audio.url}}">
                                    Remove
                            </button>
                          {% if forloop.counter|divisibleby:"2" and not forloop.last %}

                          {% endif %}

                        {% endfor %}

                      {% endwith %}

                      {% with view.facet_video_assets as facet_video %}

Video

                        {% for video in facet_video.videos %}

                              {% if video.asset_type == 'MP4' %}

                                        <button class="jp-play jp-button" role="button" aria-label="play" tabindex="0"></button>

                                        <button class="jp-full-screen jp-button" role="button" aria-label="full screen" tabindex="0"></button>

                                      Media Player Error

                                      Update your browser or Flash plugin

                              {% endif %}
                              {% if video.asset_type == 'YOUTUBE' %}

 {{ video.title }}

                              {% endif %}
                              {% if video.asset_type == 'VIMEO' %}

 {{ video.title }}

                              {% endif %}
                              <button type="button"
                                      class="btn btn-sm clear-button f-r-6 subtle"
                                      title="Remove this video"
                                      data-toggle="modal"
                                      data-target="#removeVideoModal"
                                      data-actionurl="{% url 'video_asset_remove' video=video.id facet=facet.id %}"
                                      data-videotitle="{{ video.title }}"
                                      data-videotype="{{ video.asset_type }}"
                                      data-videoid="{{video.id}}">
                                      Remove
                              </button>
                            {% if forloop.counter|divisibleby:"2" and not forloop.last %}

                            {% endif %}

                        {% endfor %}

                      {% endwith %}

            {% else %}

Click 'Save Changes' to complete creating this facet and start adding media assets.

Images

Documents

Audio

Video

            {% endif %}

            {% if facet.template.name != "Base" %}

Additional Information

              {% for f in form.get_fields_to_show %}

                    <fieldset class="form-group m-b-10">
                    {{ f.label_tag }}
                    {{ f }}
                    {% if f.errors %}
                      {{ f.errors }}
                    {% endif %}
                  </fieldset>

              {% endfor %}

            {% endif %}

        </form>

        {% if facet %}

Discussion

        {% with view.facet_discussion as discussion %}

              {% if discussion.comments %}
                {% for comment in discussion.comments %}

{{ comment.text }} | {{ comment.date|date:'D, M j g:i a' }}

                    {% if comment.user.display_photo %}

                    {% else %}
                    {% endif %}

                {% endfor %}
              {% else %}

This is where you will see comments
 from the facet discussion.

Add a comment below to
start the conversation.

              {% endif %}

              <form action="{% url 'create_facetcomment' %}" method="POST" class="post-form" role="form">

                    {% csrf_token %}

                      {{ discussion.form.text }}

                      {% if discussion.form.text.errors %}

                        {{ discussion.form.text.errors }}

                      {% endif %}

                      <input type="hidden" name="association" value="facet" />
                      <input type="hidden" name="facet" value="{{ facet.pk }}" />

                        <button id="facetcommentbutton" class="btn btn-default btn-lg" type="submit" name="facetcommentform"></button>

              </form>

        {% endwith %}
        {% else %}

Discussion

Click 'Save Changes' to complete creating this facet and start a discussion.

        {% endif %}

        {% comment %}

Edit History

        {% endcomment %}

{% endblock %}

{% block modals %}

Remove Image

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

        <form id="removeform" action="#" method="POST" class="post-form">
        {% csrf_token %}
        <button type="submit" class="btn btn-primary btn-sm f-r-8 m-t-20" title="Remove this image">Remove</button>
      </form>

Remove Document

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

  .pdf

   .docx

   .txt

   .csv

   .xls

   other

        <form id="removeform" action="#" method="POST" class="post-form">
        {% csrf_token %}
        <button type="submit" class="remove-document-link-{{document.id}} btn btn-primary btn-sm f-r-8 m-t-20" title="Remove this document">Remove</button>
      </form>

Remove Audio

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

        {% comment %}

            <button class="jp-play jp-button" role="button" aria-label="play" tabindex="0"></button>

            Media Player Error

            Update your browser or Flash plugin

        {% endcomment %}

        <form id="removeform" action="#" method="POST" class="post-form">
        {% csrf_token %}
        <button type="submit" class="btn btn-primary btn-sm f-r-8 m-t-20" title="Remove this audio">Remove</button>
      </form>

Remove Video

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

        <form id="removeform" action="#" method="POST" class="post-form">
        {% csrf_token %}
        <button type="submit" class="btn btn-primary btn-sm f-r-8 m-t-20" title="Remove this video">Remove</button>
      </form>

  {% include "editorial/facet/_facet_precreatemodal.html" %}

  {% include "editorial/facet/_facet_imageassetmodal.html" %}

  {% include "editorial/facet/_facet_documentassetmodal.html" %}

  {% include "editorial/facet/_facet_audioassetmodal.html" %}

  {% include "editorial/facet/_facet_videoassetmodal.html" %}

{% endblock modals %}


text:
package com.test.sharksharding.core.shard;

import org.junit.Test;
import com.sharksharding.core.shard.ResolveIndex;
import junit.framework.Assert;

public class ResolveIndexTest {
	public @Test void testGetIndex() {
		Assert.assertEquals(0, ResolveIndex.getBeginIndex("r1024w0", true));
		Assert.assertEquals(1024, ResolveIndex.getBeginIndex("r1024w0", false));
		Assert.assertEquals(0, ResolveIndex.getBeginIndex("R1024W0", true));
		Assert.assertEquals(1024, ResolveIndex.getBeginIndex("R0w1024", true));
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.hazelcast.spi.impl.eventservice.impl.operations;

import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.spi.impl.SpiDataSerializerHook;
import com.hazelcast.spi.impl.eventservice.impl.EventServiceImpl;
import com.hazelcast.spi.impl.eventservice.impl.EventServiceSegment;

import java.io.IOException;

public class DeregistrationOperation extends AbstractRegistrationOperation {

    private String topic;
    private String id;

    public DeregistrationOperation() {
    }

    public DeregistrationOperation(String topic, String id, int memberListVersion) {
        super(memberListVersion);
        this.topic = topic;
        this.id = id;
    }

    @Override
    protected void runInternal() throws Exception {
        EventServiceImpl eventService = (EventServiceImpl) getNodeEngine().getEventService();
        EventServiceSegment segment = eventService.getSegment(getServiceName(), false);
        if (segment != null) {
            segment.removeRegistration(topic, id);
        }
    }

    @Override
    public Object getResponse() {
        return true;
    }

    @Override
    protected void writeInternalImpl(ObjectDataOutput out) throws IOException {
        out.writeUTF(topic);
        out.writeUTF(id);
    }

    @Override
    protected void readInternalImpl(ObjectDataInput in) throws IOException {
        topic = in.readUTF();
        id = in.readUTF();
    }

    @Override
    public int getId() {
        return SpiDataSerializerHook.DEREGISTRATION;
    }
}


text:
namespace base {
class WaitableEvent;
}  // namespace base

namespace media {
class AudioBus;
}  // namespace media

namespace chromecast {

class TaskRunnerImpl;

namespace media {

class CmaAudioOutput;
class CmaBackendFactory;

class CmaAudioOutputStream : public CmaBackend::Decoder::Delegate {
 public:
  CmaAudioOutputStream(const ::media::AudioParameters& audio_params,
                       base::TimeDelta buffer_duration,
                       const std::string& device_id,
                       CmaBackendFactory* cma_backend_factory);

  CmaAudioOutputStream(const CmaAudioOutputStream&) = delete;
  CmaAudioOutputStream& operator=(const CmaAudioOutputStream&) = delete;

  ~CmaAudioOutputStream() override;

  void SetRunning(bool running);
  void Initialize(const std::string& application_session_id,
                  chromecast::mojom::MultiroomInfoPtr multiroom_info);
  void Start(::media::AudioOutputStream::AudioSourceCallback* source_callback);
  void Stop(base::WaitableEvent* finished);
  void Flush(base::WaitableEvent* finished);
  void Close(base::OnceClosure closure);
  void SetVolume(double volume);

 private:
  enum class CmaBackendState {
    kUninitialized,
    kStopped,
    kPaused,
    kStarted,
    kPendingClose,
  };

  void PushBuffer();

  // CmaBackend::Decoder::Delegate implementation:
  void OnEndOfStream() override {}
  void OnDecoderError() override;
  void OnKeyStatusChanged(const std::string& key_id,
                          CastKeyStatus key_status,
                          uint32_t system_code) override {}
  void OnVideoResolutionChanged(const Size& size) override {}
  void OnPushBufferComplete(BufferStatus status) override;

  const bool is_audio_prefetch_;

  const ::media::AudioParameters audio_params_;
  const std::string device_id_;
  CmaBackendFactory* const cma_backend_factory_;
  std::unique_ptr<CmaAudioOutput> output_;

  base::Lock running_lock_;
  bool running_ = true;
  CmaBackendState cma_backend_state_ = CmaBackendState::kUninitialized;
  const base::TimeDelta buffer_duration_;
  std::unique_ptr<::media::AudioBus> audio_bus_;
  base::OneShotTimer push_timer_;
  bool push_in_progress_ = false;
  bool encountered_error_ = false;
  base::TimeTicks next_push_time_;
  base::TimeTicks last_push_complete_time_;
  base::TimeDelta last_rendering_delay_;
  base::TimeDelta render_buffer_size_estimate_;
  ::media::AudioOutputStream::AudioSourceCallback* source_callback_ = nullptr;

  THREAD_CHECKER(media_thread_checker_);
};

}  // namespace media
}  // namespace chromecast

#endif  // CHROMECAST_MEDIA_AUDIO_CMA_AUDIO_OUTPUT_STREAM_H_


text:
Pattern: YAML parsing vulnerability

Issue: -

## Description

Checks for YAML parsing vulnerabilities (CVE-2013-0156).


text:
using System;
using HtmlAgilityPack;

namespace WebsiteRipper.Parsers.Html.References
{
    [ReferenceAttribute("manifest")]
    public sealed class Html : HtmlReference
    {
        public Html(ReferenceArgs<HtmlNode, HtmlAttribute> referenceArgs) : base(referenceArgs) { }

        protected override Uri GetBaseUri(Resource resource)
        {
            return resource.OriginalUri;
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#pragma once

#include "orttraining/core/graph/optimizer_graph_builder.h"

namespace onnxruntime {
namespace training {

class ZeROOptimizerGraphBuilder : public OptimizerGraphBuilder {
 public:
  ZeROOptimizerGraphBuilder(
      const OptimizerBuilderRegistry& opt_builder_registry,
      const OptimizerGraphConfig& opt_graph_config,
      const std::unordered_map<std::string, OptimizerNodeConfig>& weight_names_to_opt_configs,
      std::unordered_map<std::string, std::string>& updated_weight_names_map,
      std::unordered_map<std::string, TrainingSession::PartitionInfo>& weight_partition_info);

 protected:
  virtual Status BuildInternal(
      bool should_add_gradient_norm,
      bool should_add_gradient_finite_check,
      Graph& graph,
      GraphAugmenter::GraphDefs& graph_defs,
      std::vector<ArgDef>& weight_argdefs,
      std::vector<ArgDef>& gradient_argdefs,
      std::unordered_map<std::string, std::unordered_map<std::string, std::string>>& optimizer_state_initializer_names,
      OptimizerOutputKeyMap<std::string>& optimizer_graph_outputs) override;
};

 /**
   * Partitions the initial states according to the offset and
   * size provided when the optimizer state for a weight is to be
   * partitioned in Zero stage 1.
   *
   * @param partition_offset The offset for start of partition
   * @param partition_size The size(number of elements) of the partition
   * @param[out] initial_states The optimizer initial states modified in-place.
   */
void PartitionOptimizerState(
    const int64_t partition_offset,
    const int64_t partition_size,
    NameMLValMap& initial_states);

}  // namespace training
}  // namespace onnxruntime


text:
package com.adgear.anoa.write;

import org.apache.avro.generic.IndexedRecord;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Encoder;

import java.io.IOException;

class AvroWriteConsumer<R extends IndexedRecord> implements WriteConsumer<R> {

  final DatumWriter<R> writer;
  final Encoder encoder;

  AvroWriteConsumer(DatumWriter<R> writer, Encoder encoder) {
    this.writer = writer;
    this.encoder = encoder;
  }

  @Override
  public void acceptChecked(R record) throws IOException {
    writer.write(record, encoder);
  }

  @Override
  public void flush() throws IOException {
    encoder.flush();
  }
}


text:
#pragma once

#include <optional>
#include <string>

#include "Attributes.hpp"

namespace werk
{

CHECKED bool parseBool(const std::string value);

CHECKED std::optional<bool> tryParseBool(const std::string &value);

}


text:
from os.path import abspath, join, dirname
from preggy import expect
import mock
# from tornado.concurrent import Future
import tornado.web
from tests.base import PythonTestCase, TestCase
from tornado.concurrent import Future

import thumbor.loaders.http_loader as loader
from thumbor.context import Context
from thumbor.config import Config
from thumbor.loaders import LoaderResult

fixture_for = lambda filename: abspath(join(dirname(__file__), 'fixtures', filename))

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('Hello')

class EchoUserAgentHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(self.request.headers['User-Agent'])

class HandlerMock(object):
    def __init__(self, headers):
        self.request = RequestMock(headers)

class RequestMock(object):
    def __init__(self, headers):
        self.headers = headers

class ResponseMock:
    def __init__(self, error=None, content_type=None, body=None, code=None):
        self.error = error
        self.code = code
        self.time_info = None

        self.headers = {
            'Content-Type': 'image/jpeg'
        }

        if content_type:
            self.headers['Content-Type'] = content_type

        self.body = body

class ReturnContentTestCase(PythonTestCase):

    def test_return_none_on_error(self):
        response_mock = ResponseMock(error='Error', code=599)
        callback_mock = mock.Mock()
        ctx = Context(None, None, None)
        loader.return_contents(response_mock, 'some-url', callback_mock, ctx)
        result = callback_mock.call_args[0][0]
        expect(result).to_be_instance_of(LoaderResult)
        expect(result.buffer).to_be_null()
        expect(result.successful).to_be_false()

    def test_return_body_if_valid(self):
        response_mock = ResponseMock(body='body', code=200)
        callback_mock = mock.Mock()
        ctx = Context(None, None, None)
        loader.return_contents(response_mock, 'some-url', callback_mock, ctx)
        result = callback_mock.call_args[0][0]
        expect(result).to_be_instance_of(LoaderResult)
        expect(result.buffer).to_equal('body')

    def test_return_upstream_error_on_body_none(self):
        response_mock = ResponseMock(body=None, code=200)
        callback_mock = mock.Mock()
        ctx = Context(None, None, None)
        loader.return_contents(response_mock, 'some-url', callback_mock, ctx)
        result = callback_mock.call_args[0][0]
        expect(result).to_be_instance_of(LoaderResult)
        expect(result.buffer).to_be_null()
        expect(result.successful).to_be_false()
        expect(result.error).to_equal(LoaderResult.ERROR_UPSTREAM)

    def test_return_upstream_error_on_body_empty(self):
        response_mock = ResponseMock(body='', code=200)
        callback_mock = mock.Mock()
        ctx = Context(None, None, None)
        loader.return_contents(response_mock, 'some-url', callback_mock, ctx)
        result = callback_mock.call_args[0][0]
        expect(result).to_be_instance_of(LoaderResult)
        expect(result.buffer).to_be_null()
        expect(result.successful).to_be_false()
        expect(result.error).to_equal(LoaderResult.ERROR_UPSTREAM)

class ValidateUrlTestCase(PythonTestCase):

    def test_with_allowed_sources(self):
        config = Config()
        config.ALLOWED_SOURCES = ['s.glbimg.com']
        ctx = Context(None, config, None)
        expect(
            loader.validate(
                ctx,
                'http://www.google.com/logo.jpg'
            )
        ).to_be_false()
        expect(
            loader.validate(
                ctx,
                'http://s2.glbimg.com/logo.jpg'
            )
        ).to_be_false()
        expect(
            loader.validate(
                ctx,
                '/glob=:sfoir%20%20%3Co-pmb%20%20%20%20_%20%20%20%200%20%20g.-%3E%3Ca%20hplass='
            )
        ).to_be_false()
        expect(
            loader.validate(ctx, 'http://s.glbimg.com/logo.jpg')).to_be_true()

    def test_without_allowed_sources(self):
        config = Config()
        config.ALLOWED_SOURCES = []
        ctx = Context(None, config, None)
        is_valid = loader.validate(ctx, 'http://www.google.com/logo.jpg')
        expect(is_valid).to_be_true()

class NormalizeUrlTestCase(PythonTestCase):

    def test_should_normalize_url(self):
        for url in ['http://some.url', 'some.url']:
            expect(loader._normalize_url(url)).to_equal('http://some.url')

    def test_should_normalize_url_but_keep_quotes_after_the_domain(self):
        for url in ['http://some.url/my image', 'some.url/my%20image']:
            expect(loader._normalize_url(url)).to_equal('http://some.url/my%20image')

    def test_should_normalize_unicode_urls(self):
        for url in [
            u'https://s3.amazonaws.com/game-screenshots/star_wars\u2122_kotor_cover.png',
            u'https://s3.amazonaws.com/game-screenshots/star_wars™_kotor_cover.png'
        ]:
            expect(loader._normalize_url(url)).\
                to_equal('https://s3.amazonaws.com/game-screenshots/star_wars%E2%84%A2_kotor_cover.png')

    def test_should_normalize_quoted_url(self):
        url = 'https%3A//www.google.ca/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'
        expected = 'https://www.google.ca/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'
        result = loader._normalize_url(url)
        expect(result).to_equal(expected)

class HttpLoaderTestCase(TestCase):

    def get_app(self):
        application = tornado.web.Application([
            (r"/", MainHandler),
        ])

        return application

    def test_load_with_callback(self):
        url = self.get_url('/')
        config = Config()
        ctx = Context(None, config, None)

        loader.load(ctx, url, self.stop)
        result = self.wait()
        expect(result).to_be_instance_of(LoaderResult)
        expect(result.buffer).to_equal('Hello')
        expect(result.successful).to_be_true()

    def test_load_with_curl(self):
        url = self.get_url('/')
        config = Config()
        config.HTTP_LOADER_CURL_ASYNC_HTTP_CLIENT = True
        ctx = Context(None, config, None)

        loader.load(ctx, url, self.stop)
        result = self.wait()
        expect(result).to_be_instance_of(LoaderResult)
        expect(result.buffer).to_equal('Hello')
        expect(result.successful).to_be_true()

    def test_should_return_a_future(self):
        url = self.get_url('/')
        config = Config()
        ctx = Context(None, config, None)

        future = loader.load(ctx, url)
        expect(isinstance(future, Future)).to_be_true()

class HttpLoaderWithUserAgentForwardingTestCase(TestCase):

    def get_app(self):
        application = tornado.web.Application([
            (r"/", EchoUserAgentHandler),
        ])

        return application

    def test_load_with_user_agent(self):
        url = self.get_url('/')
        config = Config()
        config.HTTP_LOADER_FORWARD_USER_AGENT = True
        ctx = Context(None, config, None, HandlerMock({"User-Agent": "test-user-agent"}))

        loader.load(ctx, url, self.stop)
        result = self.wait()
        expect(result).to_be_instance_of(LoaderResult)
        expect(result.buffer).to_equal('test-user-agent')

    def test_load_with_default_user_agent(self):
        url = self.get_url('/')
        config = Config()
        config.HTTP_LOADER_FORWARD_USER_AGENT = True
        config.HTTP_LOADER_DEFAULT_USER_AGENT = "DEFAULT_USER_AGENT"
        ctx = Context(None, config, None, HandlerMock({}))

        loader.load(ctx, url, self.stop)
        result = self.wait()
        expect(result).to_be_instance_of(LoaderResult)
        expect(result.buffer).to_equal('DEFAULT_USER_AGENT')


text:
import * as Preact from '../../../../src/preact';
import {
  Accordion,
  AccordionContent,
  AccordionHeader,
  AccordionSection,
} from '../../../amp-accordion/1.0/accordion';
import {VideoIframe} from '../video-iframe';
import {VideoWrapper} from '../video-wrapper';
import {boolean, text, withKnobs} from '@storybook/addon-knobs';
import {createCustomEvent} from '../../../../src/event-helper';
import {useCallback} from '../../../../src/preact';
import {withA11y} from '@storybook/addon-a11y';

export default {
  title: 'VideoIframe',
  component: VideoIframe,
  decorators: [withA11y, withKnobs],
};

const AmpVideoIframeLike = (props) => {
  const onMessage = useCallback((e) => {
    // Expect HTMLMediaElement events from document in `src` as
    // `{event: 'playing'}`
    // (video-iframe-integration-v0.js talks similarly to HTMLMediaElement,
    // so amp-video-iframe samples already mostly work).
    if (e.data?.event) {
      e.currentTarget.dispatchEvent(
        createCustomEvent(window, e.data.event, /* detail */ null, {
          bubbles: true,
          cancelable: true,
        })
      );
    }
  }, []);

  const makeMethodMessage = useCallback(
    (method) =>
      JSON.stringify({
        // Like amp-video-iframe
        'event': 'method',
        'method': method.toLowerCase(),
      }),
    []
  );

  return (
    <VideoWrapper
      {...props}
      component={VideoIframe}
      allow="autoplay" // this is not safe for a generic frame
      onMessage={onMessage}
      makeMethodMessage={makeMethodMessage}
    />
  );
};

export const UsingVideoIframe = () => {
  const width = text('width', '640px');
  const height = text('height', '360px');

  const ariaLabel = text('aria-label', 'Video Player');
  const autoplay = boolean('autoplay', true);
  const controls = boolean('controls', true);
  const mediasession = boolean('mediasession', true);
  const noaudio = boolean('noaudio', false);
  const loop = boolean('loop', false);
  const poster = text(
    'poster',
    'https://amp.dev/static/samples/img/amp-video-iframe-sample-placeholder.jpg'
  );

  const artist = text('artist', '');
  const album = text('album', '');
  const artwork = text('artwork', '');
  const title = text('title', '');

  const src = text(
    'src',
    'https://amp.dev/static/samples/files/amp-video-iframe-videojs.html'
  );
  return (
    <AmpVideoIframeLike
      ariaLabel={ariaLabel}
      autoplay={autoplay}
      controls={controls}
      mediasession={mediasession}
      noaudio={noaudio}
      loop={loop}
      poster={poster}
      artist={artist}
      album={album}
      artwork={artwork}
      title={title}
      style={{width, height}}
      src={src}
    />
  );
};

export const InsideAccordion = () => {
  const width = text('width', '640px');
  const height = text('height', '360px');
  const autoplay = boolean('autoplay', false);
  const controls = boolean('controls', true);
  const src = text(
    'src',
    'https://amp.dev/static/samples/files/amp-video-iframe-videojs.html'
  );
  return (
    <Accordion expandSingleSection>
      <AccordionSection key={1} expanded>
        <AccordionHeader>

Controls

        </AccordionHeader>
        <AccordionContent>
          <AmpVideoIframeLike
            controls={controls}
            autoplay={autoplay}
            loop={true}
            style={{width, height}}
            src={src}
          />
        </AccordionContent>
      </AccordionSection>
    </Accordion>
  );
};


text:
/*
 * social network for event visiting logs
 */

var mongoose = require('mongoose');

var schema = module.exports = new mongoose.Schema({
  type: String,
  geometry: {
    type: String,
    coordinates: Array
  },
  center: { type: [Number], index: '2d'},
	id: { type: String, required: true },
  size: Number, //visits
  label: String,
  x: Number,
  y: Number
 });

schema.pre('save', function(next) {
  next();
});

if (!schema.options.toJSON) schema.options.toJSON = {};
schema.options.toJSON.transform = function (doc, ret) {
  ret.id = ret._id;
  delete ret._id;
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OldSkull;
using Monocle;

namespace Iseult.UI
{
    public class GameOver:Scene
    {
        public GameOver()
            : base()
        {
            SetLayer(0, new Layer());

            Image BackGround = new Image(new Texture(OldSkullGame.Path+"Content/Gfx/backgrounds/gameOver.png", true));
            Entity e = new Entity();
            e.Add(BackGround);
            Add(e);
        }

        public override void Update()
        {
            base.Update();

            KeyboardInput.Update();
            if (KeyboardInput.pressedAny())
            {
                Engine.Instance.Scene = new MainMenu();
            }
        }
    }
}


text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0022_auto_20160917_1241'),
    ]

    operations = [
        migrations.AddField(
            model_name='eventpage',
            name='location',
            field=models.CharField(default='Department of Computer Science', max_length=50),
        ),
        migrations.AlterField(
            model_name='eventpage',
            name='finish',
            field=models.DateTimeField(default=datetime.datetime(2016, 9, 17, 13, 43, 11, 659956)),
        ),
    ]


text:
package griffon.core.injection;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;

import static java.util.Objects.requireNonNull;

/**
 * @author Andres Almiray
 * @since 2.0.0
 */
public final class Qualified<T> {
    private Annotation qualifier;
    private final T instance;

    public Qualified(@Nonnull T instance, @Nullable Annotation qualifier) {
        this.instance = requireNonNull(instance, "Argument 'instance' must not be null");
        this.qualifier = qualifier;
    }

    @Nullable
    public Annotation getQualifier() {
        return qualifier;
    }

    @Nonnull
    public T getInstance() {
        return instance;
    }

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

        Qualified that = (Qualified) o;

        return instance.equals(that.instance) &&
            !(qualifier != null ? !qualifier.equals(that.qualifier) : that.qualifier != null);
    }

    @Override
    public int hashCode() {
        int result = qualifier != null ? qualifier.hashCode() : 0;
        result = 31 * result + instance.hashCode();
        return result;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Qualified{");
        sb.append("qualifier=").append(qualifier);
        sb.append(", instance=").append(instance);
        sb.append('}');
        return sb.toString();
    }
}


text:
FROM debian:jessie

VOLUME /var/lib/docker
VOLUME /resin-data

ENV DEBIAN_FRONTEND noninteractive
ENV TERM xterm
ENV DOCKER_VERSION 1.6.2

COPY ./config/01_nodoc /etc/dpkg/dpkg.cfg.d/
COPY ./config/01_buildconfig /etc/apt/apt.conf.d/

RUN apt-get update \
	&& apt-get dist-upgrade \
	&& apt-get install -y \
		apt-transport-https \
		build-essential \
		ca-certificates \
		curl \
		dbus \
		git \
		htop \
		iptables \
		less \
		libpq-dev \
		libsqlite3-dev \
		jq \
		nano \
		netcat \
		ifupdown \
		openssh-client \
		openssh-server \
		openvpn \
		parted \
		python \
		python-dev \
		rsyslog \
		rsyslog-gnutls \
		socat \
		vim \
		wget \
	&& rm -rf /var/lib/apt/lists/*

ENV CONFD_VERSION 0.10.0

RUN wget -O /usr/local/bin/confd https://github.com/kelseyhightower/confd/releases/download/v${CONFD_VERSION}/confd-${CONFD_VERSION}-linux-amd64 \
	&& chmod a+x /usr/local/bin/confd \
	&& ln -s /usr/src/app/config/confd /etc/confd

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# systemd configuration

ENV container lxc

# We never want these to run in a container
RUN systemctl mask \
	dev-hugepages.mount \
	dev-mqueue.mount \
	sys-fs-fuse-connections.mount \
	sys-kernel-config.mount \
	sys-kernel-debug.mount \

	display-manager.service \
	getty@.service \
	systemd-logind.service \
	systemd-remount-fs.service \

	getty.target \
	graphical.target

RUN systemctl disable ssh.service

# From get.docker.com script
RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9 \
	&& echo deb https://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list \
	&& apt-get update && apt-get install -y lxc-docker-${DOCKER_VERSION} \
	&& rm -rf /var/lib/apt/lists/*

COPY config/openvpn/ /etc/openvpn/
COPY config/services/ /etc/systemd/system/
COPY resin-vars vpn-init /usr/src/app/

RUN systemctl enable resin-supervisor-dind
RUN systemctl enable resin-supervisor-host-socket

CMD env > /etc/docker.env; exec /sbin/init


text:
const tape = require('tape-catch');

tape('Utilities', { skip: false }, (describe) => {
  const lib = require('../lib');
  const path = require('path');

  describe.test('* Config - Get', (assert) => {
    const value = lib.config.get('supportedFileTypes.photo');
    assert.ok(value, 'Retrieve value');
    assert.ok(value.length, 'Get array type');
    assert.ok(value[0], 'jpg', 'Read array index 0');
    assert.ok(value[1], 'jpeg', 'Read array index 1');
    assert.end();
  });

  describe.test('* File - Get File Type', (assert) => {
    assert.equal(lib.file.type(), false, 'No argument');
    assert.equal(lib.file.type('file.type'), 'type', 'Normal type');
    assert.equal(lib.file.type('.gitignore'), 'gitignore', 'Dot file');
    assert.equal(lib.file.type('test.eslintrc'), 'eslintrc', 'Long type');
    assert.equal(lib.file.type('jquery.min.js'), 'js', 'Double type');
    assert.equal(lib.file.type('image.JPG'), 'jpg', 'Uppercase type');
    assert.equal(lib.file.type('image.JPeG'), 'jpeg', 'Mixed case type');
    assert.equal(lib.file.type('word.'), '', 'No type (w/ dot)');
    assert.equal(lib.file.type('word'), '', 'No type');
    assert.equal(lib.file.type('folder/file.type'), 'type', 'Normal type with relative path (forward slash)');
    assert.equal(lib.file.type('folder\file.type'), 'type', 'Normal type with relative path (back slash)');
    assert.end();
  });

  describe.test('* File - Get Mime Type', (assert) => {
    assert.equal(lib.file.mimeType(), false, 'No argument');
    assert.equal(lib.file.mimeType('test.eslintrc'), false, 'Unsupported type');
    assert.equal(lib.file.mimeType('jquery.min.js'), 'application/javascript', 'JavaScript');
    assert.equal(lib.file.mimeType('image.JPG'), 'image/jpeg', 'Uppercase JPEG');
    assert.equal(lib.file.mimeType('image.JPeG'), 'image/jpeg', 'Mixed case JPEG');
    assert.equal(lib.file.mimeType('word'), false, 'No type');
    assert.equal(lib.file.mimeType('folder/file.mp4'), 'video/mp4', 'Video type with relative path (forward slash)');
    assert.equal(lib.file.mimeType('folder\file.webm'), 'video/webm', 'Video type with relative path (back slash)');
    assert.end();
  });

  describe.test('* File - Extension to Mime type', (assert) => {
    ['raw', 'arw'].forEach((type) => {
      const mime = lib.file.mimeType(type);
      assert.equal(mime, 'image/raw', `Image (${type})`);
    });

    ['m2ts', 'mts'].forEach((type) => {
      const mime = lib.file.mimeType(type);
      assert.equal(mime, 'video/mp2t', `Video (${type})`);
    });

    assert.end();
  });

  describe.test('* File - Get Medium Type', (assert) => {
    assert.equal(lib.file.mediumType(), false, 'No argument');
    assert.equal(lib.file.mediumType(''), false, 'Blank type');
    assert.equal(lib.file.mediumType('FAKE'), false, 'Fake type');
    assert.equal(lib.file.mediumType('image/jpeg'), 'image', 'JPEG is image');
    assert.equal(lib.file.mediumType('video/mp4'), 'video', 'MP4 is video');
    assert.equal(lib.file.mediumType('video/webm'), 'video', 'WebM is video');
    assert.end();
  });

  describe.test('* File - Extension to Medium type', (assert) => {
    lib.config.get('rawFileTypes.photo').forEach((type) => {
      const medium = lib.file.mediumType(lib.file.mimeType(type));
      assert.equal(medium, 'image', `Image (${type})`);
    });

    lib.config.get('rawFileTypes.video').forEach((type) => {
      const medium = lib.file.mediumType(lib.file.mimeType(type));
      assert.equal(medium, 'video', `Video (${type})`);
    });

    assert.end();
  });

  describe.test('* File - Ensure absolute path', (assert) => {
    const test = lib.file.absolutePath;
    assert.equal(test('./plugins/utils/test'), __dirname,
      'Relative resolved to Absolute folder');
    assert.equal(test('./plugins/utils/test/fixtures/aitch.html'), path.join(__dirname, './fixtures/aitch.html'),
      'Relative resolved to Absolute file');
    assert.equal(test('./plugins/utils/test/'), path.join(__dirname, '/'),
      'Relative resolved to Absolute folder trailing slash');
    if (lib.platform === 'windows') {
      assert.equal(test('./plugins/utils/test/'), path.join(__dirname, '\\'),
        'Relative resolved to Absolute folder trailing backslash');
    }
    assert.equal(test(__dirname), __dirname,
      'Absolute resolved to folder');
    assert.equal(test(path.join(__dirname, './fixtures/aitch.html')), path.join(__dirname, './fixtures/aitch.html'),
      'Absolute to file');
    assert.end();
  });

  describe.test('* File - Convert thumbs path to photos path', (assert) => {
    const test = lib.file.photoPath;
    assert.equal(test(), undefined, 'Missing path arg');
    assert.equal(test('media/thumbs/2001/2001-03-21-01.jpg'), 'media/photos/2001/2001-03-21-01.jpg', 'Normal path');
    assert.equal(test('media/thumbs/2001/2001-thumbs.jpg'), 'media/photos/2001/2001-thumbs.jpg', 'Thumbs in path');
    assert.end();
  });

  describe.test('* File - Convert video filename to thumbs path', (assert) => {
    const test = lib.file.videoToThumbsPath;
    assert.equal(test(), undefined, 'Missing path arg');
    assert.equal(test('2001-video-description.mp4'), undefined, 'Missing gallery');
    assert.equal(test('2001-video-description.mp4', 'demo'),
      '/static/gallery-demo/media/thumbs/2001/2001-video-description.jpg', 'Single Video');
    assert.equal(test('2002-03-21-01.mp4', 'demo'),
      '/static/gallery-demo/media/thumbs/2002/2002-03-21-01.jpg', 'Single Video as Year');
    assert.equal(test('2003-video.avi,2004-video.mts', 'demo'),
      '/static/gallery-demo/media/thumbs/2003/2003-video.jpg', 'Multiple videos');
    assert.end();
  });

  describe.test('* File - Glob', (assert) => {
    assert.plan(8);

    lib.file.glob('./plugins/utils/test/fixtures', '*.fake')
      .then(files => assert.equal(files.length, [].length, 'Find nothing (*.fake)'))
      .catch(error => assert.fail(error));

    lib.file.glob('./plugins/utils/test/fixtures', '*.htm')
      .then(files => assert.equal(path.resolve(files[0]), path.join(__dirname, './fixtures/aitch.htm'), 'Find HTM (*.htm)'))
      .catch(error => assert.fail(error));

    lib.file.glob('./plugins/utils/test/fixtures', '*.html')
      .then(files => assert.equal(path.resolve(files[0]), path.join(__dirname, './fixtures/aitch.html'), 'Find HTML (*.html)'))
      .catch(error => assert.fail(error));

    lib.file.glob('./plugins/utils/test/fixtures', '*.htm*')
      .then((files) => {
        assert.equal(path.resolve(files[0]), path.join(__dirname, './fixtures/aitch.htm'), 'Find HTM (*.htm*)');
        assert.equal(path.resolve(files[1]), path.join(__dirname, './fixtures/aitch.html'), 'Find HTML (*.htm*)');
      })
      .catch(error => assert.fail(error));

    lib.file.glob('./plugins/utils/test/fixtures', '*.*')
      .then((files) => {
        assert.equal(path.resolve(files[0]), path.join(__dirname, './fixtures/aitch.htm'), 'Find HTM (*.*)');
        assert.equal(path.resolve(files[1]), path.join(__dirname, './fixtures/aitch.html'), 'Find HTML (*.*)');
      })
      .catch(error => assert.fail(error));

    lib.file.glob('./plugins/utils/test/fixtures/aitch.html', '.htm', { ignoreExtension: true })
      .then(files => assert.equal(path.resolve(files[0]), path.join(__dirname, './fixtures/aitch.htm'), 'Find HTM (.htm)'))
      .catch(error => assert.fail(error));
  });
});


text:
package org.bouncycastle.jcajce.provider.digest;

import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.crypto.CipherKeyGenerator;
import org.bouncycastle.crypto.digests.RIPEMD128Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.jcajce.provider.config.ConfigurableProvider;
import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator;
import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac;

public class RIPEMD128
{
    private RIPEMD128()
    {

    }

    static public class Digest
        extends BCMessageDigest
        implements Cloneable
    {
        public Digest()
        {
            super(new RIPEMD128Digest());
        }

        public Object clone()
            throws CloneNotSupportedException
        {
            Digest d = (Digest)super.clone();
            d.digest = new RIPEMD128Digest((RIPEMD128Digest)digest);

            return d;
        }
    }

    /**
     * RIPEMD128 HashMac
     */
    public static class HashMac
        extends BaseMac
    {
        public HashMac()
        {
            super(new HMac(new RIPEMD128Digest()));
        }
    }

    public static class KeyGenerator
        extends BaseKeyGenerator
    {
        public KeyGenerator()
        {
            super("HMACRIPEMD128", 128, new CipherKeyGenerator());
        }
    }

    public static class Mappings
        extends DigestAlgorithmProvider
    {
        private static final String PREFIX = RIPEMD128.class.getName();

        public Mappings()
        {
        }

        public void configure(ConfigurableProvider provider)
        {
            provider.addAlgorithm("MessageDigest.RIPEMD128", PREFIX + "$Digest");
            provider.addAlgorithm("Alg.Alias.MessageDigest." + TeleTrusTObjectIdentifiers.ripemd128, "RIPEMD128");

            addHMACAlgorithm(provider, "RIPEMD128", PREFIX + "$HashMac", PREFIX + "$KeyGenerator");
        }
    }
}


text:
'use strict'

var Promise = require('pinkie-promise')
var exec = require('child_process').exec

module.exports = function (cmd, opts) {
	if (typeof cmd !== 'string') {
		throw new TypeError('Expected a string')
	}

	return new Promise(function (resolve) {
		exec(cmd, opts, function (error, stdout, stderr) {
			resolve({
				error: error,
				stdout: stdout,
				stderr: stderr
			})
		})
	})
}


text:
package main

import (
	"fmt"
	"runtime"
)

func say(s string) {
	for i := 0; i < 5; i++ {
		// Let the CPU execute other goroutines and come back at this point
		runtime.Gosched()
		fmt.Println(s)
	}
}

func main() {
	go say("world") // create a new goroutine
	say("hello")    // current goroutine
}