text:
require 'spec_helper'

describe Traktr::Show do
  context 'GET methods' do
    context 'with valid api_key' do
      before :all do
        @trakt = Traktr::Client.new(API_KEY)
      end

      context 'with valid query' do
        it '#comments' do
          expect( @trakt.show.comments('dexter').size ).to be > 0
        end

        it '#season' do
          expect( @trakt.show.season('dexter', 1).size ).to eql(12)
        end

        it '#seasons' do
          expect( @trakt.show.seasons('dexter').size ).to eql(9)
        end

        it '#summary' do
          expect( @trakt.show.summary('dexter').imdb_id ).to eql('tt0773262')
        end

        it '#summaries' do
          expect( @trakt.show.summaries(['dexter', 'the-walking-dead']).size ).to eql(2)
        end

        it '#watchingnow' do
          expect( @trakt.show.watchingnow('dexter').size ).to be >= 0
        end

        it '#related' do
          expect( @trakt.show.related('dexter').size ).to eql(10)
        end

        it '#stats' do
          expect( @trakt.show.stats('dexter').size ).to eql(8)
        end
      end

      context 'with invalid query' do
        it '#comments' do
          expect { @trakt.show.comments('blah') }.to raise_error(Traktr::ResponseError)
        end

        it '#season' do
          expect { @trakt.show.season('blah', 1) }.to raise_error(Traktr::ResponseError)
          expect { @trakt.show.season('dexter') }.to raise_error(ArgumentError)
        end

        it '#seasons' do
          expect { @trakt.show.seasons('blah') }.to raise_error(Traktr::ResponseError)
        end

        it '#summary' do
          expect { @trakt.show.summary('blah') }.to raise_error(Traktr::ResponseError)
        end

        it '#summaries' do
          expect { @trakt.show.summaries(['blah', 'blah-blah']) }.to raise_error(Traktr::ResponseError)
        end

        it '#watchingnow' do
          expect { @trakt.show.watchingnow('blah') }.to raise_error(Traktr::ResponseError)
        end

        it '#related' do
          expect { @trakt.show.related('blah') }.to raise_error(Traktr::ResponseError)
        end

        it '#stats' do
          expect { @trakt.show.stats('blah') }.to raise_error(Traktr::ResponseError)
        end
      end

    end

    context 'without valid api_key' do
      before :all do
        @trakt = Traktr::Client.new(nil)
      end

      it '#comments' do
        expect { @trakt.show.comments('the-walking-dead') }.to raise_error(Traktr::ResponseError)
      end

      it '#season' do
        expect { @trakt.show.season('the-walking-dead', 1) }.to raise_error(Traktr::ResponseError)
      end

      it '#seasons' do
        expect { @trakt.show.seasons('the-walking-dead') }.to raise_error(Traktr::ResponseError)
      end

      it '#summary' do
        expect { @trakt.show.summary('the-walking-dead') }.to raise_error(Traktr::ResponseError)
      end

      it '#summaries' do
        expect { @trakt.show.summaries(['the-walking-dead', 'dexter']) }.to raise_error(Traktr::ResponseError)
      end

      it '#watchingnow' do
        expect { @trakt.show.watchingnow('the-walking-dead') }.to raise_error(Traktr::ResponseError)
      end

      it '#related' do
        expect { @trakt.show.related('the-walking-dead') }.to raise_error(Traktr::ResponseError)
      end

      it '#stats' do
        expect { @trakt.show.stats('the-walking-dead') }.to raise_error(Traktr::ResponseError)
      end
    end
  end

  context 'POST methods' do
    before :all do
      trakt = Traktr::Client.new(API_KEY)
      @show = trakt.show.summary('dexter')
    end

    context 'with valid api_key and auth credentials' do
      before :all do
        @trakt = Traktr::Client.new(API_KEY, USERNAME, PASSWORD)
      end

      it '#library' do
        expect( @trakt.show.library(@show).status ).to eql('success')
      end

      it '#unlibrary' do
        expect( @trakt.show.unlibrary(@show).status ).to eql('success')
      end

      it '#watchlist' do
        expect( @trakt.show.watchlist(@show).status ).to eql('success')
      end

      it '#unwatchlist' do
        expect( @trakt.show.unwatchlist(@show).status ).to eql('success')
      end

      it '#seen' do
        expect( @trakt.show.seen(@show).status ).to eql('success')
      end
    end

    context 'without valid api_key' do
      before :all do
        @trakt = Traktr::Client.new(nil, USERNAME, PASSWORD)
      end

      it '#library' do
        expect { @trakt.show.library(@show) }.to raise_error(Traktr::ResponseError)
      end

      it '#unlibrary' do
        expect { @trakt.show.unlibrary(@show) }.to raise_error(Traktr::ResponseError)
      end

      it '#watchlist' do
        expect { @trakt.show.watchlist(@show) }.to raise_error(Traktr::ResponseError)
      end

      it '#unwatchlist' do
        expect { @trakt.show.unwatchlist(@show) }.to raise_error(Traktr::ResponseError)
      end

      it '#seen' do
        expect { @trakt.show.seen(@show) }.to raise_error(Traktr::ResponseError)
      end
    end

    context 'without valid auth credentials' do
      before :all do
        @trakt = Traktr::Client.new(API_KEY)
      end

      it '#library' do
        expect { @trakt.show.library(@show) }.to raise_error(Traktr::ResponseError)
      end

      it '#unlibrary' do
        expect { @trakt.show.unlibrary(@show) }.to raise_error(Traktr::ResponseError)
      end

      it '#watchlist' do
        expect { @trakt.show.watchlist(@show) }.to raise_error(Traktr::ResponseError)
      end

      it '#unwatchlist' do
        expect { @trakt.show.unwatchlist(@show) }.to raise_error(Traktr::ResponseError)
      end

      it '#seen' do
        expect { @trakt.show.seen(@show) }.to raise_error(Traktr::ResponseError)
      end
    end
  end
end


text:
var gutil = require('gulp-util');
var through = require('through2');
var preprocessor = require('suitcss-preprocessor');

module.exports = suitcss;

var PLUGIN_NAME = 'gulp-suitcss';

function suitcss(opts) {
  opts = opts || {};

  return through.obj(function(file, enc, cb) {
    if (file.isNull()) {
      cb(null, file);
      return;
    }

    if (file.isStream()) {
      cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
      return;
    }

    preprocessor(file.contents.toString(), opts, file.path)
      .then(function(result) {
        file.contents = new Buffer(result.css);

        var warnings = result.warnings();
        if (warnings.length > 0) {
          gutil.log(PLUGIN_NAME, ':\n  ' + warnings.join('\n  '));
        }

        setImmediate(cb, null, file);
      })
      .catch(function(err) {
        var cssError = err.name === 'CssSyntaxError';
        if (cssError) {
          err.message += err.showSourceCode();
        }

        // Prevent stream's unhandled exception from being suppressed by Promise
        // https://git.io/vihyQ
        setImmediate(cb, new gutil.PluginError(PLUGIN_NAME, err, {
          fileName: file.path,
          showStack: !cssError,
        }));
      });
  });
}

redpajama_set_name: RedPajamaGithub


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    collapseLeft: function() {
      this.get('leftChild').collapse();
    },
    collapseRight: function() {
      this.get('rightChild').collapse();
    }
  }
});


text:
/* globals exports */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['exports'], factory);
    } else if (typeof exports !== 'undefined') {
        factory(exports);
    } else {
        factory((root.dragscroll = {}));
    }
}(this, function (exports) {
    var _window = window;
    var _document = document;
    var mousemove = 'mousemove';
    var mouseup = 'mouseup';
    var mousedown = 'mousedown';
    var EventListener = 'EventListener';
    var addEventListener = 'add' + EventListener;
    var removeEventListener = 'remove' + EventListener;

    var dragged = [];
    var reset = function (i, el) {
        for (i = 0; i < dragged.length;) {
            el = dragged[i++];
            el = el.container || el;
            el[removeEventListener](mousedown, el.md, 0);
            _window[removeEventListener](mouseup, el.mu, 0);
            _window[removeEventListener](mousemove, el.mm, 0);
        }

        // cloning into array since HTMLCollection is updated dynamically
        dragged = [].slice.call(_document.getElementsByClassName('dragscroll'));
        for (i = 0; i < dragged.length;) {
            (function (el, lastClientX, lastClientY, pushed, scroller, cont) {
                (cont = el.container || el)[addEventListener](
                    mousedown,
                    cont.md = function (e) {
                        if (!el.hasAttribute('nochilddrag') ||
                            _document.elementFromPoint(
                                e.pageX, e.pageY
                            ) === cont
                        ) {
                            pushed = 1;
                            lastClientX = e.clientX;
                            lastClientY = e.clientY;

                            // monkeypatch
                            if (!($(e.srcElement).hasClass('form-control') || $(e.target).hasClass('form-control'))) {
                                e.preventDefault();
                                $('.form-control').blur();
                            }

                        }
                    }, 0
                );

                _window[addEventListener](
                    mouseup, cont.mu = function () {pushed = 0;}, 0
                );

                _window[addEventListener](
                    mousemove,
                    cont.mm = function (e) {
                        if (pushed) {
                            (scroller = el.scroller || el).scrollLeft -=
                                (- lastClientX + (lastClientX = e.clientX));
                            scroller.scrollTop -=
                                (- lastClientY + (lastClientY = e.clientY));
                        }
                    }, 0
                );
            })(dragged[i++]);
        }
    };

    if (_document.readyState === 'complete') {
        reset();
    } else {
        _window[addEventListener]('load', reset, 0);
    }

    exports.reset = reset;
}));


text:
require 'test_helper'

class TestNSIndexSet < MiniTest::Unit::TestCase
  def test_post_creation
    p = NSMutableURLRequest.post("http://example.com")

    assert_equal "POST", p.HTTPMethod
    assert_equal "http://example.com", p.URL.absoluteString
  end

  def test_providing_body
    p = NSMutableURLRequest.post("http://example.com", :body => "My Body")
    assert_equal "My Body", p.HTTPBody.to_str
  end

  def test_providing_headers
    p = NSMutableURLRequest.post("http://example.com",
                  :head => { :first => "one",
                             "second" => 2 })
    assert_equal "one", p.valueForHTTPHeaderField("first")
    assert_equal "2", p.valueForHTTPHeaderField("second")
  end
end


text:
package org.eclipse.jetty.client;

import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jetty.client.security.Realm;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.security.Constraint;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;

public class SecuredErrorStatusTest
    extends ErrorStatusTest
{
    private Realm _testRealm;
    private Realm _dummyRealm;

    @Override
    public void testPutUnauthorized()
        throws Exception
    {
        setRealm(null);

        doPutFail(HttpStatus.UNAUTHORIZED_401);

        setRealm(_testRealm);
    }

    public void testPutWrongPassword()
        throws Exception
    {
        setRealm(_dummyRealm);

        doPutFail(HttpStatus.UNAUTHORIZED_401);

        setRealm(_testRealm);
    }

    @Override
    public void testGetUnauthorized()
        throws Exception
    {
        setRealm(null);

        doGetFail(HttpStatus.UNAUTHORIZED_401);

        setRealm(_testRealm);
    }

    public void testGetWrongPassword()
        throws Exception
    {
        setRealm(_dummyRealm);

        doGetFail(HttpStatus.UNAUTHORIZED_401);

        setRealm(_testRealm);
    }

    @Override
    protected void configureServer(Server server)
        throws Exception
    {
        setProtocol("http");

        _testRealm = new Realm()
                         {
                             public String getId()
                             {
                                 return "MyRealm";
                             }

                             public String getPrincipal()
                             {
                                 return "jetty";
                             }

                             public String getCredentials()
                             {
                                 return "jetty";
                             }
                         };

        _dummyRealm = new Realm()
                          {
                              public String getId()
                              {
                                  return "MyRealm";
                              }

                              public String getPrincipal()
                              {
                                  return "jetty";
                              }

                              public String getCredentials()
                              {
                                  return "dummy";
                              }
                          };

        setRealm(_testRealm);

        SelectChannelConnector connector = new SelectChannelConnector();
        server.addConnector(connector);

        File realmPropFile = MavenTestingUtils.getTestResourceFile("realm.properties");
        LoginService loginService = new HashLoginService("MyRealm",realmPropFile.getAbsolutePath());
        server.addBean(loginService);

        ConstraintSecurityHandler security = new ConstraintSecurityHandler();
        server.setHandler(security);

        Constraint constraint = new Constraint();
        constraint.setName("auth");
        constraint.setAuthenticate( true );
        constraint.setRoles(new String[]{"user", "admin"});

        ConstraintMapping mapping = new ConstraintMapping();
        mapping.setPathSpec( "/*" );
        mapping.setConstraint( constraint );

        Set<String> knownRoles = new HashSet<String>();
        knownRoles.add("user");
        knownRoles.add("admin");

        security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
        security.setAuthenticator(new BasicAuthenticator());
        security.setLoginService(loginService);
        security.setStrict(false);

        ServletContextHandler root = new ServletContextHandler();
        root.setContextPath("/");
        root.setResourceBase(getBasePath());
        ServletHolder servletHolder = new ServletHolder( new DefaultServlet() );
        servletHolder.setInitParameter( "gzip", "true" );
        root.addServlet( servletHolder, "/*" );

        Handler status = new StatusHandler();
        Handler test = new TestHandler(getBasePath());

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[]{status, test, root});
        security.setHandler(handlers);
    }
}


text:
// getsomefeedback.js
// february, 2012.
//
// Copyright (c) 2012 lorenzo puccetti
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// This Software shall be used for doing good things, not bad things.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

(function(window,document,undefined) {
   //
   // Define the HTML elements.
   //
   var divFeedback = document.createElement('div');
   var divDialog = document.createElement('div');
   var txtName = document.createElement('input');
   var divName = document.createElement('div');
   var divMessage = document.createElement('div');
   var taMessage = document.createElement('textarea');
   var btnSubmit = document.createElement('input');
   var divThanks = document.createElement('div');

   //
   // Styling the HTML elements
   //
   divFeedback.style.position ='fixed';
   divFeedback.style.cursor = 'pointer';
   divFeedback.style.color ='#FFF';
   divFeedback.style.backgroundColor ='#000';
   divFeedback.style.zIndex = 1000;
   divFeedback.style.padding = '8px';
   divFeedback.style.fontSize = '32px';
   divFeedback.style.bottom = '1px';
   divFeedback.style.right = '1px';
   divFeedback.innerHTML = 'Feedback';
   divDialog.style.position = 'fixed';
   divDialog.style.display = 'none';
   divDialog.style.zIndex = 1000;
   divDialog.style.left = '10%';
   divDialog.style.right = '10%';
   divDialog.style.top = '10%';
   divDialog.style.padding = '10px';
   divDialog.style.backgroundColor = '#eee';
   divDialog.style.color = '#333';
   divDialog.style.border = '1px solid #333';
   divDialog.style.borderRadius = '8px';
   txtName.type = 'input';
   txtName.style.width = '100%';
   divName.innerHTML = 'Your name:';
   divMessage.innerHTML = 'Your message:';
   btnSubmit.type = 'button';
   btnSubmit.value = 'Submit Your Feedback';
   taMessage.style.width = '100%';
   taMessage.style.height = '96px';
   divThanks.style.position = 'fixed';
   divThanks.style.display = 'none';
   divThanks.style.zIndex = 1000;
   divThanks.style.left = '10%';
   divThanks.style.right = '10%';
   divThanks.style.top = '10%';
   divThanks.style.padding = '10px';
   divThanks.style.backgroundColor = '#eee';
   divThanks.style.color = '#333';
   divThanks.style.border = '1px solid #333';
   divThanks.style.borderRadius = '8px';
   divThanks.style.fontSize = '24px';
   divThanks.style.display = 'none';
   divThanks.style.textAlign = 'center';
   divThanks.innerHTML = 'Thank you for submitting your feedback';
   divDialog.appendChild(divName);
   divDialog.appendChild(txtName);
   divDialog.appendChild(divMessage);
   divDialog.appendChild(taMessage);
   divDialog.appendChild(btnSubmit);

   // registering events:
   // onclick on the feedback button toggles the feedback dialog.
   // onclick on the submit button sends the message to the server.
   divFeedback.onmouseover = function() { divFeedback.style.borderBottom ='4px solid #800' };
   divFeedback.onmouseout =  function() { divFeedback.style.borderBottom ='0px solid #000' };
   divFeedback.onclick = function() {
      divDialog.style.display = (divDialog.style.display === 'block') ? 'none' : 'block';
   };
   btnSubmit.onclick = function() {
      var name = txtName.value;
      var message = taMessage.value;

      /**
       * add here any validation on the input parameters.
       * e.g. alert message is too short.
       * ...
      **/

      // This is the main logic to send the message to the feedback.
      // a new script is created and asynchronously requested.
      var script = document.createElement("script");
      script.src="do.not.ignore.feedback.js?name="+encodeURIComponent(name)+'&message='+encodeURIComponent(message);
      document.body.appendChild(script);

      // Displays the thank you message.
      // Removes the feedback button
      // sets a timeout function to remove the thank you message in a few seconds.
      divDialog.style.display = 'none';
      divThanks.style.display = 'block';
      divFeedback.style.display = 'none';
      setTimeout(function() {
         divThanks.style.display = 'none';
      }, 3000);
   }
   document.body.appendChild(divFeedback);
   document.body.appendChild(divDialog);
   document.body.appendChild(divThanks);
})(this,this.document); // avoid polluting the global scope


text:
<?php

declare(strict_types=1);

namespace Ramsey\Uuid\Codec;

/**
 * TimestampLastCombCodec encodes and decodes COMBs, with the timestamp as the
 * last 48 bits
 *
 * The CombGenerator when used with the StringCodec (and, by proxy, the
 * TimestampLastCombCodec) adds the timestamp to the last 48 bits of the COMB.
 * The TimestampLastCombCodec is provided for the sake of consistency. In
 * practice, it is identical to the standard StringCodec but, it may be used
 * with the CombGenerator for additional context when reading code.
 *
 * Consider the following code. By default, the codec used by UuidFactory is the
 * StringCodec, but here, we explicitly set the TimestampLastCombCodec. It is
 * redundant, but it is clear that we intend this COMB to be generated with the
 * timestamp appearing at the end.
 *
 * ``` php
 * $factory = new UuidFactory();
 *
 * $factory->setCodec(new TimestampLastCombCodec($factory->getUuidBuilder()));
 *
 * $factory->setRandomGenerator(new CombGenerator(
 *     $factory->getRandomGenerator(),
 *     $factory->getNumberConverter()
 * ));
 *
 * $timestampLastComb = $factory->uuid4();
 * ```
 *
 * @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys
 *
 * @psalm-immutable
 */
class TimestampLastCombCodec extends StringCodec
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:background="@drawable/bg_top" >

        <TextView
            android:id="@+id/top_title_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/meishi"
            android:textColor="@color/font_color"
            android:textSize="18sp" />

        <Button
            android:id="@+id/top_bak_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="19dp"
            android:background="@drawable/bg_back"
            android:text="@string/fanhui"
            android:textColor="@color/font_color" />

        <Button
            android:id="@+id/top_btn_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="19dp"
            android:background="@drawable/bg_back"
            android:text="@string/dummy"
            android:textColor="@color/font_color" />

</RelativeLayout>


text:
{% extends 'admin/master.html' %}
{% import 'admin/lib.html' as lib with context %}

{% block head %}
    {{ super() }}
    {{ lib.form_css() }}
{% endblock %}

{# Modify original macro for add id to form #}
{% macro form_tag(form=None, action=None) %}
    <form id="model_form" action="{{ action or '' }}" method="POST" role="form" class="admin-form form-horizontal" enctype="multipart/form-data">
      {{ caller() }}
    </form>
{% endmacro %}

{# Modify original call form for remove buttons #}
{% block body %}
    {% call form_tag(form) %}
        {{ lib.render_form_fields(form, form_opts=form_opts) }}
    {% endcall %}
{% endblock %}

{% block tail %}
    {{ super() }}
    {{ lib.form_js() }}

	<script type="text/javascript">
	$(document).ready(function() {
		$('#model_form :enabled').attr('disabled', 'disabled');
		$('#model_form :button, #model_form :submit, #model_form :reset, #model_form .btn').hide();
		/*
		TODO: Remplacer les cache coché/non coché par icon
		TODO: remplacer textarea par plain text ou change style
		*/
	});
	</script>
{% endblock %}


text:
<?php
namespace exchangecore\webprint\src\printers\interfaces;

interface NetworkPrinterInterface extends PrinterInterface
{

    /**
     * Creates a connection to the network printer
     * @param string $host
     * @return $this|bool Returns $this if connected successfully, returns false if unable to connect
     */
    public function connect($host);

    /**
     * Disconnects from the current network connection
     * @return bool
     */
    public function disconnect();

}


text:
package com.yodiwo.plegma;

/**
 * Created by ApiGenerator Tool (Java) on 28/08/2015 18:35:01.
 */

public class ThingTypes {

    public static final String Yodiwo_Logic_BlockLibrary_Button;

    public static final String Yodiwo_Logic_BlockLibrary_FfmpegSource;

    public static final String Yodiwo_Logic_BlockLibrary_SipThingOut;

    public static final String Yodiwo_Logic_BlockLibrary_ScreenStreamerThing;

    static {
        Yodiwo_Logic_BlockLibrary_Button = "Actuators.Buttons.Yodiwo.Button";
        Yodiwo_Logic_BlockLibrary_FfmpegSource = "VideoSources.Yodiwo.FfmpegSource";
        Yodiwo_Logic_BlockLibrary_SipThingOut = "Yodiwo.Logic.BlockLibrary.SipThingOut";
        Yodiwo_Logic_BlockLibrary_ScreenStreamerThing = "Yodiwo.Logic.BlockLibrary.ScreenStreamerThing";
    }
}


text:
'use strict';

import React from 'react';
// import {Link} from 'react-router';

class FormTextArea extends React.Component {

    constructor(props) {
        super(props);
    }

    static propTypes = {
        id: React.PropTypes.string.isRequired,
        label: React.PropTypes.string.isRequired,
        value: React.PropTypes.string.isRequired,
        onChange: React.PropTypes.func.isRequired,
        className: React.PropTypes.any
    };

    shouldComponentUpdate(nextProps) {
      return this.props.value !== nextProps.value;
    }

    render() {
        const {id, label, value, onChange, className} = this.props;
        const [name, placeholder] = [id, label];
        const withProps = {name, value, onChange, placeholder};

        return (

                  {label}
                    <textarea {...withProps}/>

        );
    }

}

export default FormTextArea;


text:
#include "packet.h"
#include "avutils.h"

using namespace std;

namespace av {

Packet::Packet()
{
#if DEPRECATED_INIT_PACKET
    m_raw = av_packet_alloc();
#else
    av_init_packet(raw());
#endif

    raw()->stream_index = -1; // no stream

    m_completeFlag = false;
    m_timeBase     = Rational(0, 0);

}

Packet::Packet(const Packet &packet)
    : Packet(packet, throws())
{
}

Packet::Packet(const Packet &packet, OptionalErrorCode ec)
    : Packet()
{
    initFromAVPacket(packet.raw(), false, ec);
    m_completeFlag = packet.m_completeFlag;
    m_timeBase = packet.m_timeBase;
}

Packet::Packet(Packet &&packet)
    : Packet()
{
    m_completeFlag = packet.m_completeFlag;
    m_timeBase = packet.m_timeBase;
    av_packet_move_ref(raw(), packet.raw());
}

Packet::Packet(const AVPacket *packet, OptionalErrorCode ec)
    : Packet()
{
    initFromAVPacket(packet, false, ec);
}

Packet::Packet(const vector<uint8_t> &data)
    : Packet(data.data(), data.size(), true)
{
}

Packet::Packet(const uint8_t *data, size_t size, bool /*doAllign*/)
    : Packet()
{
    auto pkt_data = av::memdup<uint8_t>(data, size);
    if (!pkt_data) {
        return;
    }

    auto sts = av_packet_from_data(raw(), pkt_data.get(), size);
    if (sts < 0)
        return;

    pkt_data.release();

    m_completeFlag = true;
}

Packet::Packet(uint8_t *data, size_t size, Packet::wrap_data, OptionalErrorCode ec)
    : Packet()
{
    auto sts = av_packet_from_data(raw(), data, size);
    if (sts < 0) {
        throws_if(ec, sts, ffmpeg_category());
        return;
    }
    m_completeFlag = true;
}

static void dummy_buffer_free(void */*opaque*/, uint8_t */*ptr*/)
{}

Packet::Packet(uint8_t *data, size_t size, Packet::wrap_data_static, OptionalErrorCode ec)
    : Packet()
{
    auto buf = av_buffer_create(data, size, dummy_buffer_free, nullptr, 0);
    if (!buf) {
        throws_if(ec, AVERROR(ENOMEM), ffmpeg_category());
        return;
    }

    raw()->buf = buf;
    raw()->data = data;
    raw()->size = size;
    m_completeFlag = true;
}

Packet::~Packet()
{
#if DEPRECATED_INIT_PACKET
    av_packet_free(&m_raw);
#else
    avpacket_unref(&m_raw);
#endif
}

void Packet::initFromAVPacket(const AVPacket *src, bool deepCopy, OptionalErrorCode ec)
{
    clear_if(ec);

    if (!src || src->size <= 0)
    {
        return;
    }

    if (raw())
        avpacket_unref(raw());

    if (deepCopy) {
#if DEPRECATED_INIT_PACKET
        if (!m_raw)
            m_raw = av_packet_alloc();

        // Copy properties first
        av_packet_copy_props(m_raw, src);

        // Referecen to the same data as src
        m_raw->data = src->data;
        m_raw->size = src->size;

        // Make new package reference counted: this allocates pkt->buf, copy data from the pkt->data
        // to the pkt->buf->data and setup pkt->data to the pkt->buf->data
        av_packet_make_refcounted(m_raw);
#else
        m_raw = *src;
        raw()->buf = nullptr;
        raw()->size = 0;
        raw()->data = nullptr;

        auto data = av::memdup<uint8_t>(src->data, src->size);
        if (!data) {
            throws_if(ec, AVERROR(ENOMEM), ffmpeg_category());
            return;
        }

        auto sts = av_packet_from_data(raw(), data.get(), src->size);
        if (sts < 0) {
            throws_if(ec, sts, ffmpeg_category());
            return;
        }

        // all ok, packet now own data, drop owning
        data.release();
#endif
    } else {
        auto sts = av_packet_ref(raw(), src);
        if (sts < 0) {
            throws_if(ec, sts, ffmpeg_category());
            return;
        }
    }

    m_completeFlag = raw()->size > 0;
}

bool Packet::setData(const vector<uint8_t> &newData, OptionalErrorCode ec)
{
    return setData(newData.data(), newData.size(), ec);
}

bool Packet::setData(const uint8_t *newData, size_t size, OptionalErrorCode ec)
{
    clear_if(ec);
    av_packet_unref(raw());

    auto data = av::memdup<uint8_t>(newData, size);
    if (!data) {
        throws_if(ec, AVERROR(ENOMEM), ffmpeg_category());
        return false;
    }

    auto sts = av_packet_from_data(raw(), data.get(), size);
    if (sts < 0) {
        throws_if(ec, sts, ffmpeg_category());
        return false;
    }

    data.release();

    m_completeFlag = true;

    return true;
}

const uint8_t *Packet::data() const
{
    return raw()->data;
}

uint8_t *Packet::data()
{
    return raw()->data;
}

Timestamp Packet::pts() const
{
    return {raw()->pts, m_timeBase};
}

Timestamp Packet::dts() const
{
    return {raw()->dts, m_timeBase};
}

Timestamp Packet::ts() const
{
    return {raw()->pts != av::NoPts ? raw()->pts : raw()->dts, m_timeBase};
}

size_t Packet::size() const
{
    return raw()->size < 0 ? 0 : (size_t)raw()->size;
}

void Packet::setPts(int64_t pts, const Rational &tsTimeBase)
{
    if (tsTimeBase == Rational(0,0))
        raw()->pts = pts;
    else
        raw()->pts = tsTimeBase.rescale(pts, m_timeBase);
}

void Packet::setDts(int64_t dts, const Rational &tsTimeBase)
{
    if (tsTimeBase == Rational(0,0))
        raw()->dts = dts;
    else
        raw()->dts = tsTimeBase.rescale(dts, m_timeBase);
}

void Packet::setPts(const Timestamp &pts)
{
    if (m_timeBase == Rational())
        m_timeBase = pts.timebase();
    raw()->pts = pts.timestamp(m_timeBase);
}

void Packet::setDts(const Timestamp &dts)
{
    if (m_timeBase == Rational())
        m_timeBase = dts.timebase();
    raw()->dts = dts.timestamp(m_timeBase);
}

int Packet::streamIndex() const
{
    return  raw()->stream_index;
}

int Packet::flags() const
{
    return raw()->flags;
}

bool Packet::isKeyPacket() const
{
    return (raw()->flags & AV_PKT_FLAG_KEY);
}

int Packet::duration() const
{
    return raw()->duration;
}

bool Packet::isComplete() const
{
    return m_completeFlag && raw()->data && raw()->size;
}

bool Packet::isNull() const
{
    return raw()->data == nullptr || raw()->size == 0;
}

void Packet::setStreamIndex(int idx)
{
    raw()->stream_index = idx;
}

void Packet::setKeyPacket(bool keyPacket)
{
    if (keyPacket)
        raw()->flags |= AV_PKT_FLAG_KEY;
    else
        raw()->flags &= ~AV_PKT_FLAG_KEY;
}

void Packet::setFlags(int flags)
{
    raw()->flags = flags;
}

void Packet::addFlags(int flags)
{
    raw()->flags |= flags;
}

void Packet::clearFlags(int flags)
{
    raw()->flags &= ~flags;
}

void Packet::dump(const Stream &st, bool dumpPayload) const
{
    if (!st.isNull())
    {
        const AVStream *stream = st.raw();
        av_pkt_dump2(stdout, raw(), dumpPayload ? 1 : 0, stream);
    }
}

void Packet::setTimeBase(const Rational &tb)
{
    if (m_timeBase == tb)
        return;

    if (m_timeBase != Rational())
        av_packet_rescale_ts(raw(),
                             m_timeBase.getValue(),
                             tb.getValue());

    m_timeBase = tb;
}

bool Packet::isReferenced() const
{
    return raw()->buf;
}

int Packet::refCount() const
{
    if (raw()->buf)
        return av_buffer_get_ref_count(raw()->buf);
    else
        return 0;
}

#if DEPRECATED_INIT_PACKET
AVPacket *Packet::makeRef(OptionalErrorCode ec) const
{
    clear_if(ec);
    AVPacket *pkt = av_packet_alloc();
    if (!pkt) {
        throws_if(ec, AVERROR(ENOMEM), ffmpeg_category());
        return nullptr;
    }

    auto const sts = av_packet_ref(pkt, raw());
    if (sts < 0) {
        av_packet_free(&pkt);
        throws_if(ec, sts, ffmpeg_category());
        return nullptr;
    }

    return pkt;
}

#else

AVPacket Packet::makeRef(OptionalErrorCode ec) const
{
    clear_if(ec);
    AVPacket pkt;
    auto sts = av_packet_ref(&pkt, &m_raw);
    if (sts < 0) {
        throws_if(ec, sts, ffmpeg_category());
    }
    return pkt;
}
#endif

Packet Packet::clone(OptionalErrorCode ec) const
{
    Packet pkt;
    pkt.initFromAVPacket(raw(), true, ec);
    pkt.m_timeBase = m_timeBase;
    return pkt;
}

void Packet::setComplete(bool complete)
{
    m_completeFlag = complete;
}

Packet &Packet::operator=(const Packet &rhs)
{
    if (&rhs == this)
        return *this;

    Packet(rhs).swap(*this);

    return *this;
}

Packet &Packet::operator=(Packet &&rhs)
{
    if (&rhs == this)
        return *this;

    Packet(std::move(rhs)).swap(*this); // move ctor

    return *this;
}

#if DEPRECATED_INIT_PACKET
Packet &Packet::operator=(const AVPacket *rhs)
{
    if (rhs == raw())
        return *this;

    initFromAVPacket(rhs, false, throws());
    m_timeBase = Rational();
    return *this;
}
#else
Packet &Packet::operator=(const AVPacket &rhs)
{
    if (&rhs == raw())
        return *this;

    initFromAVPacket(&rhs, false, throws());
    m_timeBase = Rational();
    return *this;
}
#endif

void Packet::swap(Packet &other)
{
    using std::swap;
    swap(m_raw,          other.m_raw);
    swap(m_completeFlag, other.m_completeFlag);
    swap(m_timeBase,     other.m_timeBase);
}

void Packet::setDuration(int duration, const Rational &durationTimeBase)
{
    if (durationTimeBase == Rational())
        raw()->duration = duration;
    else
        raw()->duration = durationTimeBase.rescale(duration, m_timeBase);
}

} // ::av


text:
listRemove() with all positive arguments

--DESCRIPTION--
This testcase will remove the element from the list at the given index.

--FILE--
<?php
include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc";
aerospike_phpt_runtest("ListRemove", "normal_001");
--EXPECT--
OK


text:
using System;

namespace Dnn.PersonaBar.Pages.Components.Exceptions
{
    public class BulkPagesException : Exception
    {
        public string Field { get; set; }

        public BulkPagesException(string field, string message) : base(message)
        {
            Field = field;
        }
    }
}


text:
layout: service-standard
title: Digital by Default Service Standard Beta Assessments
phase: beta
version: 2
---


text:
/**
 * @class MainController
 */
module.exports = function MainController( caminio, policies, middleware ){

  return {

    _before: {
      // set up your before filters here
      // typical before filters are policies.ensureLogin or
      // policies.requireAdmin
      //
      // e.g.: '*': policies.ensureLogin,
      //       'index,show': [ policies.requireAdmin, myCustomCheck ]
      //
    },

    /**
     * @method index
     */
    'index': [
      function( req, res ){
        // this tries to find a template file in any of api/views directory
        // named [controller_namespace]/<controller_name>/<action_name>
        // here this would be main_controller/index
        res.caminio.render();
      }
    ]

  }

}


text:
quail.documentTitleIsShort = function(quail, test, Case) {
  var $title = test.get('$scope').find('head title:first');
  var _case = Case({
    element: $title,
    expected: $title.closest('.quail-test').data('expected')
  });
  test.add(_case);
  if (!$title.length) {
    _case.set({
      element: test.get('$scope'),
      'status' : 'inapplicable'
    });
    return;
  }
  _case.set({
    'status': $title.text().length > 150 ?
      'failed' :
      'passed'
  });
};


text:
import sys
sys.path += ['../']
import torch
from torch import nn
from transformers import (
    RobertaConfig,
    RobertaModel,
    RobertaForSequenceClassification,
    RobertaTokenizer,
    BertModel,
    BertTokenizer,
    BertConfig
)
import torch.nn.functional as F
from data.process_fn import triple_process_fn, triple2dual_process_fn

class EmbeddingMixin:
    """
    Mixin for common functions in most embedding models. Each model should define its own bert-like backbone and forward.
    We inherit from RobertaModel to use from_pretrained
    """
    def __init__(self, model_argobj):
        if model_argobj is None:
            self.use_mean = False
        else:
            self.use_mean = model_argobj.use_mean
        print("Using mean:", self.use_mean)

    def _init_weights(self, module):
        """ Initialize the weights """
        if isinstance(module, (nn.Linear, nn.Embedding, nn.Conv1d)):
            # Slightly different from the TF version which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            module.weight.data.normal_(mean=0.0, std=0.02)

    def masked_mean(self, t, mask):
        s = torch.sum(t * mask.unsqueeze(-1).float(), axis=1)
        d = mask.sum(axis=1, keepdim=True).float()
        return s / d

    def masked_mean_or_first(self, emb_all, mask):
        # emb_all is a tuple from bert - sequence output, pooler
        assert isinstance(emb_all, tuple)
        if self.use_mean:
            return self.masked_mean(emb_all[0], mask)
        else:
            return emb_all[0][:, 0]

    def query_emb(self, input_ids, attention_mask):
        raise NotImplementedError("Please Implement this method")

    def body_emb(self, input_ids, attention_mask):
        raise NotImplementedError("Please Implement this method")

class NLL(EmbeddingMixin):
    def forward(
            self,
            query_ids,
            attention_mask_q,
            input_ids_a=None,
            attention_mask_a=None,
            input_ids_b=None,
            attention_mask_b=None,
            is_query=True):
        if input_ids_b is None and is_query:
            return self.query_emb(query_ids, attention_mask_q)
        elif input_ids_b is None:
            return self.body_emb(query_ids, attention_mask_q)

        q_embs = self.query_emb(query_ids, attention_mask_q)
        a_embs = self.body_emb(input_ids_a, attention_mask_a)
        b_embs = self.body_emb(input_ids_b, attention_mask_b)

        logit_matrix = torch.cat([(q_embs * a_embs).sum(-1).unsqueeze(1),
                                  (q_embs * b_embs).sum(-1).unsqueeze(1)], dim=1)  # [B, 2]
        lsm = F.log_softmax(logit_matrix, dim=1)
        loss = -1.0 * lsm[:, 0]
        return (loss.mean(),)

class NLL_MultiChunk(EmbeddingMixin):
    def forward(
            self,
            query_ids,
            attention_mask_q,
            input_ids_a=None,
            attention_mask_a=None,
            input_ids_b=None,
            attention_mask_b=None,
            is_query=True):
        if input_ids_b is None and is_query:
            return self.query_emb(query_ids, attention_mask_q)
        elif input_ids_b is None:
            return self.body_emb(query_ids, attention_mask_q)

        q_embs = self.query_emb(query_ids, attention_mask_q)
        a_embs = self.body_emb(input_ids_a, attention_mask_a)
        b_embs = self.body_emb(input_ids_b, attention_mask_b)

        [batchS, full_length] = input_ids_a.size()
        chunk_factor = full_length // self.base_len

        # special handle of attention mask -----
        attention_mask_body = attention_mask_a.reshape(
            batchS, chunk_factor, -1)[:, :, 0]  # [batchS, chunk_factor]
        inverted_bias = ((1 - attention_mask_body) * (-9999)).float()

        a12 = torch.matmul(
            q_embs.unsqueeze(1), a_embs.transpose(
                1, 2))  # [batch, 1, chunk_factor]
        logits_a = (a12[:, 0, :] + inverted_bias).max(dim=-
                                                      1, keepdim=False).values  # [batch]
        # -------------------------------------

        # special handle of attention mask -----
        attention_mask_body = attention_mask_b.reshape(
            batchS, chunk_factor, -1)[:, :, 0]  # [batchS, chunk_factor]
        inverted_bias = ((1 - attention_mask_body) * (-9999)).float()

        a12 = torch.matmul(
            q_embs.unsqueeze(1), b_embs.transpose(
                1, 2))  # [batch, 1, chunk_factor]
        logits_b = (a12[:, 0, :] + inverted_bias).max(dim=-
                                                      1, keepdim=False).values  # [batch]
        # -------------------------------------

        logit_matrix = torch.cat(
            [logits_a.unsqueeze(1), logits_b.unsqueeze(1)], dim=1)  # [B, 2]
        lsm = F.log_softmax(logit_matrix, dim=1)
        loss = -1.0 * lsm[:, 0]
        return (loss.mean(),)

class RobertaDot_NLL_LN(NLL, RobertaForSequenceClassification):
    """None
    Compress embedding to 200d, then computes NLL loss.
    """

    def __init__(self, config, model_argobj=None):
        NLL.__init__(self, model_argobj)
        RobertaForSequenceClassification.__init__(self, config)
        self.embeddingHead = nn.Linear(config.hidden_size, 768)
        self.norm = nn.LayerNorm(768)
        self.apply(self._init_weights)

    def query_emb(self, input_ids, attention_mask):
        outputs1 = self.roberta(input_ids=input_ids,
                                attention_mask=attention_mask)
        full_emb = self.masked_mean_or_first(outputs1, attention_mask)
        query1 = self.norm(self.embeddingHead(full_emb))
        return query1

    def body_emb(self, input_ids, attention_mask):
        return self.query_emb(input_ids, attention_mask)

class RobertaDot_CLF_ANN_NLL_MultiChunk(NLL_MultiChunk, RobertaDot_NLL_LN):
    def __init__(self, config):
        RobertaDot_NLL_LN.__init__(self, config)
        self.base_len = 512

    def body_emb(self, input_ids, attention_mask):
        [batchS, full_length] = input_ids.size()
        chunk_factor = full_length // self.base_len

        input_seq = input_ids.reshape(
            batchS,
            chunk_factor,
            full_length //
            chunk_factor).reshape(
            batchS *
            chunk_factor,
            full_length //
            chunk_factor)
        attention_mask_seq = attention_mask.reshape(
            batchS,
            chunk_factor,
            full_length //
            chunk_factor).reshape(
            batchS *
            chunk_factor,
            full_length //
            chunk_factor)

        outputs_k = self.roberta(input_ids=input_seq,
                                 attention_mask=attention_mask_seq)

        compressed_output_k = self.embeddingHead(
            outputs_k[0])  # [batch, len, dim]
        compressed_output_k = self.norm(compressed_output_k[:, 0, :])

        [batch_expand, embeddingS] = compressed_output_k.size()
        complex_emb_k = compressed_output_k.reshape(
            batchS, chunk_factor, embeddingS)

        return complex_emb_k  # size [batchS, chunk_factor, embeddingS]

class HFBertEncoder(BertModel):
    def __init__(self, config):
        BertModel.__init__(self, config)
        assert config.hidden_size > 0, 'Encoder hidden_size can\'t be zero'
        self.init_weights()
    @classmethod
    def init_encoder(cls, args, dropout: float = 0.1):
        cfg = BertConfig.from_pretrained("bert-base-uncased")
        if dropout != 0:
            cfg.attention_probs_dropout_prob = dropout
            cfg.hidden_dropout_prob = dropout
        return cls.from_pretrained("bert-base-uncased", config=cfg)
    def forward(self, input_ids, attention_mask):
        hidden_states = None
        sequence_output, pooled_output = super().forward(input_ids=input_ids,
                                                         attention_mask=attention_mask)
        pooled_output = sequence_output[:, 0, :]
        return sequence_output, pooled_output, hidden_states
    def get_out_size(self):
        if self.encode_proj:
            return self.encode_proj.out_features
        return self.config.hidden_size

class BiEncoder(nn.Module):
    """ Bi-Encoder model component. Encapsulates query/question and context/passage encoders.
    """
    def __init__(self, args):
        super(BiEncoder, self).__init__()
        self.question_model = HFBertEncoder.init_encoder(args)
        self.ctx_model = HFBertEncoder.init_encoder(args)
    def query_emb(self, input_ids, attention_mask):
        sequence_output, pooled_output, hidden_states = self.question_model(input_ids, attention_mask)
        return pooled_output
    def body_emb(self, input_ids, attention_mask):
        sequence_output, pooled_output, hidden_states = self.ctx_model(input_ids, attention_mask)
        return pooled_output
    def forward(self, query_ids, attention_mask_q, input_ids_a = None, attention_mask_a = None, input_ids_b = None, attention_mask_b = None):
        if input_ids_b is None:
            q_embs = self.query_emb(query_ids, attention_mask_q)
            a_embs = self.body_emb(input_ids_a, attention_mask_a)
            return (q_embs, a_embs)
        q_embs = self.query_emb(query_ids, attention_mask_q)
        a_embs = self.body_emb(input_ids_a, attention_mask_a)
        b_embs = self.body_emb(input_ids_b, attention_mask_b)
        logit_matrix = torch.cat([(q_embs*a_embs).sum(-1).unsqueeze(1), (q_embs*b_embs).sum(-1).unsqueeze(1)], dim=1) #[B, 2]
        lsm = F.log_softmax(logit_matrix, dim=1)
        loss = -1.0*lsm[:,0]
        return (loss.mean(),)

# --------------------------------------------------
ALL_MODELS = sum(
    (
        tuple(conf.pretrained_config_archive_map.keys())
        for conf in (
            RobertaConfig,
        )
    ),
    (),
)

default_process_fn = triple_process_fn

class MSMarcoConfig:
    def __init__(self, name, model, process_fn=default_process_fn, use_mean=True, tokenizer_class=RobertaTokenizer, config_class=RobertaConfig):
        self.name = name
        self.process_fn = process_fn
        self.model_class = model
        self.use_mean = use_mean
        self.tokenizer_class = tokenizer_class
        self.config_class = config_class

configs = [
    MSMarcoConfig(name="rdot_nll",
                model=RobertaDot_NLL_LN,
                use_mean=False,
                ),
    MSMarcoConfig(name="rdot_nll_multi_chunk",
                model=RobertaDot_CLF_ANN_NLL_MultiChunk,
                use_mean=False,
                ),
    MSMarcoConfig(name="dpr",
                model=BiEncoder,
                tokenizer_class=BertTokenizer,
                config_class=BertConfig,
                use_mean=False,
                ),
]

MSMarcoConfigDict = {cfg.name: cfg for cfg in configs}


text: Spree::ShippingCategory.create!(:name => "Default")


text:
package org.apache.storm.daemon.metrics;

import org.apache.storm.metric.api.CountMetric;

public class SpoutThrottlingMetrics extends BuiltinMetrics {
    private final CountMetric skippedMaxSpoutMs = new CountMetric();
    private final CountMetric skippedThrottleMs = new CountMetric();
    private final CountMetric skippedInactiveMs = new CountMetric();

    public SpoutThrottlingMetrics() {
        metricMap.put("skipped-max-spout-ms", skippedMaxSpoutMs);
        metricMap.put("skipped-throttle-ms", skippedThrottleMs);
        metricMap.put("skipped-inactive-ms", skippedInactiveMs);
    }

    public void skippedMaxSpoutMs(long ms) {
        this.skippedMaxSpoutMs.incrBy(ms);
    }

    public void skippedThrottleMs(long ms) {
        this.skippedThrottleMs.incrBy(ms);
    }

    public void skippedInactiveMs(long ms) {
        this.skippedInactiveMs.incrBy(ms);
    }
}


text:
package main

import "reflect"

func main() {
	a := &struct{ x int }{}
	b := &struct{ x int "" }{}

	ta := reflect.TypeOf(a)
	tb := reflect.TypeOf(b)

	// Ensure cmd/compile treats absent and empty tags as equivalent.
	a = b

	// Ensure package reflect treats absent and empty tags as equivalent.
	if !tb.AssignableTo(ta) {
		panic("fail")
	}
}


text:
/** Automatically generated file. DO NOT MODIFY */
package com.nikhilparanjape.rhsmaps;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
`Specification`_
================

Purpose
-------

Builds a clear specification of business rules, where objects can be
checked against. The composite specification class has one method called
``isSatisfiedBy`` that returns either true or false depending on whether
the given object satisfies the specification.

UML Diagram
-----------

.. image:: uml/uml.png
   :alt: Alt Specification UML Diagram
   :align: center

Code
----

You can also find these code on `GitHub`_

Item.php

.. literalinclude:: Item.php
   :language: php
   :linenos:

SpecificationInterface.php

.. literalinclude:: SpecificationInterface.php
   :language: php
   :linenos:

AbstractSpecification.php

.. literalinclude:: AbstractSpecification.php
   :language: php
   :linenos:

Either.php

.. literalinclude:: Either.php
   :language: php
   :linenos:

PriceSpecification.php

.. literalinclude:: PriceSpecification.php
   :language: php
   :linenos:

Plus.php

.. literalinclude:: Plus.php
   :language: php
   :linenos:

Not.php

.. literalinclude:: Not.php
   :language: php
   :linenos:

Test
----

Tests/SpecificationTest.php

.. literalinclude:: Tests/SpecificationTest.php
   :language: php
   :linenos:

.. _`GitHub`: https://github.com/domnikl/DesignPatternsPHP/tree/master/Behavioral/Specification
.. _`Specification`: http://en.wikipedia.org/wiki/Specification_pattern


text:
import React from 'react';
import {Link, RouteHandler} from 'react-router';

var App = React.createClass({
  render: function() {
    return (

Search Engine

          <RouteHandler />

    );
  }
});

module.exports = App;


text:
import urllib

from lib.actions import AuthBaseAction

class AuthAuthAction(AuthBaseAction):
    def run(self, username, factor,
            ipaddr, device, push_type, passcode, pushinfo):
        """
        Auth against the Duo Platorm.

        Returns: An dict with info returned by Duo.

        Raises:
          ValueError: 'Duo config not found in config' or 'Invalid factor'
          RuntimeError: 'Failed auth.'
        """

        auth_kargs = {}

        if factor == "auto" or factor == "push":
            auth_kargs['type'] = push_type
            auth_kargs['device'] = device

            if ipaddr is not None:
                auth_kargs['ipaddr'] = ipaddr

            if pushinfo is not None:
                encoded = urllib.urlencode(pushinfo)
                auth_kargs['pushinfo'] = encoded
        elif factor == "passcode":
            auth_kargs['passcode'] = passcode
        elif factor == "phone":
            auth_kargs['device'] = device
        elif factor == "sms":
            # As 'sms' just denies and then we do not support it
            # requires re-authentication.

            raise ValueError("Denied, we do not support SMS!")
        else:
            raise ValueError("Invalid factor!")

        try:
            data = self.duo_auth.auth(factor=factor,
                                      username=username,
                                      **auth_kargs)
        except RuntimeError, e:
            raise RuntimeError("Error: %s" % e)
        else:
            if data['result'] == "allow":
                return data
            elif data['result'] == "deny":
                self.send_user_error(data['status_msg'])
                raise RuntimeError("{}".format(
                    data['status_msg']))
            else:
                raise RuntimeError("Invalid status")


text:
package org.cinnamon.core.util;

import java.lang.reflect.Field;
import java.util.Date;

/**
 *
 * create date: 2015. 6. 17.
 * @author 신동성
 *
 */
public class ObjectMerger {

//	private static Map<String, Void> availableTypeMap = new LinkedHashMap<String, Void>();
//
//	static {
//		availableTypeMap.put(String.class.getName(), null);
//		availableTypeMap.put(Float.class.getName(), null);
//		availableTypeMap.put(Date.class.getName(), null);
//		availableTypeMap.put(Integer.class.getName(), null);
//		availableTypeMap.put(Boolean.class.getName(), null);
//	}

//	public static void merge(Object source, Object target) throws Exception {
//		copyFields(source.getClass().getDeclaredFields(), source, target);
////
////		Class<?> superClass = source.getClass().getSuperclass();
////		while (superClass != null) {
////			copyFields(superClass.getDeclaredFields(), source, target);
////
////			superClass = superClass.getSuperclass();
////		}
//
//
//
//
//	}
//
//	private static void copyFields(Field[] fields, Object source, Object target) throws Exception {
//		for (Field field: fields) {
//			field.setAccessible(true);
//			Object fieldValue = field.get(source);
//			if (fieldValue == null) {
//				continue;
//			}
//
//			if (!isAvailableType(fieldValue)) {
//				continue;
//			}
//
//
////			System.out.println(field.getName() + ": " + fieldValue);
//
//			try {
//				Field targetField = target.getClass().getDeclaredField(field.getName());
//				if (targetField != null) {
//					if (!targetField.isAccessible()) {
//						targetField.setAccessible(true);
//					}
//
//					System.out.println("copy field: " + field.getName());
//					targetField.set(target, fieldValue);
//					return;
//				}
//			} catch (NoSuchFieldException e) {
////				e.printStackTrace();
//				continue;
//			}
//
//			Class<?> superClass = target.getClass().getSuperclass();
//			while (superClass != null) {
//				copyFields(fields, source, target);
//
//				superClass = superClass.getSuperclass();
//			}
//
//
//
////			String methodName = field.getName();
////			methodName = "set" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
////
////			try {
////				Method method = target.getClass().getMethod(methodName, field.getType());
////				if (method != null) {
////					method.invoke(target, field.get(source));
////				}
////			} catch (Exception e) {
//////				e.printStackTrace();
////				continue;
////			}
//		};
//	}

	private static boolean isAvailableType(Object value) {
		if (value.getClass().getSuperclass().equals(Object.class)) {
			return true;
		}

		return false;
	}

	private static boolean isPrimitiveType(Object value) {
		if (value.getClass().isPrimitive()) {
			return true;
		}
		if (value instanceof Number) {
			return true;
		}
		if (value instanceof CharSequence) {
			return true;
		}
		if (value instanceof Enum) {
			return true;
		}
		if (value instanceof Date) {
			return true;
		}

		return false;
	}

	/**
	 * source객체의 필드에 값이 있는 부분만 target 객체로 값 셋팅
	 * @param source
	 * @param target
	 * @throws Exception
	 */
	public static void merge(Object source, Object target) throws Exception {
		exploreSourceFeild(source, target, source.getClass());

		Class<?> superClass = source.getClass().getSuperclass();
		while (superClass != null) {
			exploreSourceFeild(source, target, superClass);

			superClass = superClass.getSuperclass();
		}
	}

	private static void exploreSourceFeild(Object source, Object target, Class<?> sourceCalss) throws Exception {
		for (Field field: sourceCalss.getDeclaredFields()) {
			field.setAccessible(true);
			Object fieldValue = field.get(source);
			if (fieldValue == null) {
				continue;
			}

			if (!isAvailableType(fieldValue)) {
				continue;
			}

//			target.getClass();
			applyField(source, target, target.getClass(), field.getName(), fieldValue);

			Class<?> superClass = target.getClass().getSuperclass();
//			while (superClass != null) {
			while (!superClass.equals(Object.class)) {
				applyField(source, target, superClass, field.getName(), fieldValue);

				superClass = superClass.getSuperclass();
			}
		}
	}

	private static void applyField(Object source, Object target, Class<?> targetCalss, String fieldName, Object fieldValue) throws Exception {
		if (!isPrimitiveType(fieldValue)) {
			try {
				Field targetField = targetCalss.getDeclaredField(fieldName);
				if (targetField != null) {
					if (!targetField.isAccessible()) {
						targetField.setAccessible(true);
					}

					System.out.println("copy field: " + fieldName);
					targetField.set(target, fieldValue);
					return;
				}
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
				return;
			}
		} else {
			applyObjectField(source, target, target.getClass(), fieldName, fieldValue);
		}
	}

	private static void applyObjectField(Object source, Object target, Class<?> targetCalss, String fieldName, Object fieldValue) throws Exception {
		try {
			Field targetField = targetCalss.getDeclaredField(fieldName);
			if (targetField != null) {
				if (targetField.getType().equals(fieldValue.getClass())) {
					if (!targetField.isAccessible()) {
						targetField.setAccessible(true);
					}

					System.out.println("copy field: " + fieldName);
					Object newFieldValue = targetField.getType().newInstance();
					exploreSourceFeild(fieldValue, newFieldValue, targetField.getType());

					targetField.set(target, newFieldValue);
					return;
				}
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
			return;
		}
	}

	public static void main(String[] args) throws Exception {
//		A a = new A();
//		a.f = 134F;
//
//
//		Field f = a.getClass().getDeclaredField("f");
//		System.out.println(f.get(a) instanceof Number);

	}
}

class A {
	String s;
	Float f;
}


text:
FROM python:3.10.1-slim-bullseye

WORKDIR /app/

# Copy requirements and install.
COPY ./Pipfile* /app/
RUN python3 -m pip install --no-cache-dir --upgrade pip pipenv && \
    pipenv install --deploy --system

# Copy the needed files.
COPY . /app/

# Run with -u $(id -u):$(id -g) to avoid file permission issues.
ENTRYPOINT ["python3", "-m", "playstoredownloader.cli"]


text:
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  MCLDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$MCLDIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
PROJECT_ROOT="$( cd -P "$( dirname "$SOURCE" )"/.. && pwd )"

# Actually run script
cd $PROJECT_ROOT && bundle exec ruby elch_scan.rb "$@"


text:
---
id: issues
title: Common Issues
---
- Be sure to include `<!DOCTYPE html>` at the top of your HTML file, as
  otherwise your browser will render in "[quirks mode](https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode)"
  which can cause KaTeX to sometimes render incorrectly.
  This header is needed even inside `<iframe>`s
  (which don't inherit the parent document's doctype).
- Many Markdown preprocessors, such as the one that Jekyll and GitHub Pages use,
  have a "smart quotes" feature.  This changes `'` to `'` which is an issue for
  math containing primes, e.g. `f'`.  This can be worked around by defining a
  single character macro which changes them back, e.g. `{"'", "'"}`.
- KaTeX follows LaTeX's rendering of `aligned` and `matrix` environments unlike
  MathJax.  When displaying fractions one above another in these vertical
  layouts there may not be enough space between rows for people who are used to
  MathJax's rendering.  The distance between rows can be adjusted by using
  `\\[0.1em]` instead of the standard line separator distance.
- KaTeX does not support the `align` environment because LaTeX doesn't support
  `align` in math mode.  The `aligned` environment offers the same functionality
  but in math mode, so use that instead.
- MathJax defines `\color` to be like `\textcolor` by default; set KaTeX's
  `colorIsTextColor` option to `true` for this behavior.  KaTeX's default
  behavior matches MathJax with its `color.js` extension enabled.
- Equivalents of MathJax `\class`, `\cssId`, and `\style` are `\htmlClass`,
  `\htmlId`, and `\htmlStyle`, respectively, to avoid ambiguity.
- Some symbols are defined using macro instead of `\DeclareMathSymbol` or similar
  as in LaTeX. This may cause different behavior in expansion. They may expand
  into multiple tokens and be affected by `\expandafter` and `\noexpand`.

## Troubleshooting

To check the stylesheet (katex.css) is properly loaded, add following code to
anywhere in the document:

```html
<style>
  .katex-version {display: none;}
  .katex-version::after {content:"0.10.2 or earlier";}
</style>
<span class="katex">
  <span class="katex-mathml">The KaTeX stylesheet is not loaded!</span>
  <span class="katex-version rule">KaTeX stylesheet version: </span>
</span>
```

If it is loaded properly, it'll show its version. Make sure its version matches
the version of the JavaScript file (katex.js), which is defined in `katex.version`.
If it is not loaded properly, it'll show:

> The KaTeX stylesheet is not loaded!

## CSS customization

KaTeX's CSS is customizable to some extent. For example, to make individual
display equations scrollable horizontally:

```css
.katex-display { overflow: auto hidden }
```

To allow line breaks in display equations (unlike LaTeX):

```css
.katex-display > .katex { white-space: normal }
/* Add space between broken lines: */
.katex-display > .base { margin: 0.25em 0 }
/* Compensate by reducing space around display math */
.katex-display { margin: 0.5em 0; }
```


text:
package repo

import (
	"path"
	"strings"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/base"
	"code.gitea.io/gitea/modules/charset"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/git"
	"code.gitea.io/gitea/modules/gitgraph"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/services/gitdiff"
)

const (
	tplCommits    base.TplName = "repo/commits"
	tplGraph      base.TplName = "repo/graph"
	tplCommitPage base.TplName = "repo/commit_page"
)

// RefCommits render commits page
func RefCommits(ctx *context.Context) {
	switch {
	case len(ctx.Repo.TreePath) == 0:
		Commits(ctx)
	case ctx.Repo.TreePath == "search":
		SearchCommits(ctx)
	default:
		FileHistory(ctx)
	}
}

// Commits render branch's commits
func Commits(ctx *context.Context) {
	ctx.Data["PageIsCommits"] = true
	if ctx.Repo.Commit == nil {
		ctx.NotFound("Commit not found", nil)
		return
	}
	ctx.Data["PageIsViewCode"] = true

	commitsCount, err := ctx.Repo.GetCommitsCount()
	if err != nil {
		ctx.ServerError("GetCommitsCount", err)
		return
	}

	page := ctx.QueryInt("page")
	if page <= 1 {
		page = 1
	}

	pageSize := ctx.QueryInt("limit")
	if pageSize <= 0 {
		pageSize = git.CommitsRangeSize
	}

	// Both `git log branchName` and `git log commitId` work.
	commits, err := ctx.Repo.Commit.CommitsByRange(page, pageSize)
	if err != nil {
		ctx.ServerError("CommitsByRange", err)
		return
	}
	commits = models.ValidateCommitsWithEmails(commits)
	commits = models.ParseCommitsWithSignature(commits, ctx.Repo.Repository)
	commits = models.ParseCommitsWithStatus(commits, ctx.Repo.Repository)
	ctx.Data["Commits"] = commits

	ctx.Data["Username"] = ctx.Repo.Owner.Name
	ctx.Data["Reponame"] = ctx.Repo.Repository.Name
	ctx.Data["CommitCount"] = commitsCount
	ctx.Data["Branch"] = ctx.Repo.BranchName

	pager := context.NewPagination(int(commitsCount), git.CommitsRangeSize, page, 5)
	pager.SetDefaultParams(ctx)
	ctx.Data["Page"] = pager

	ctx.HTML(200, tplCommits)
}

// Graph render commit graph - show commits from all branches.
func Graph(ctx *context.Context) {
	ctx.Data["PageIsCommits"] = true
	ctx.Data["PageIsViewCode"] = true

	commitsCount, err := ctx.Repo.GetCommitsCount()
	if err != nil {
		ctx.ServerError("GetCommitsCount", err)
		return
	}

	allCommitsCount, err := ctx.Repo.GitRepo.GetAllCommitsCount()
	if err != nil {
		ctx.ServerError("GetAllCommitsCount", err)
		return
	}

	page := ctx.QueryInt("page")

	graph, err := gitgraph.GetCommitGraph(ctx.Repo.GitRepo, page)
	if err != nil {
		ctx.ServerError("GetCommitGraph", err)
		return
	}

	ctx.Data["Graph"] = graph
	ctx.Data["Username"] = ctx.Repo.Owner.Name
	ctx.Data["Reponame"] = ctx.Repo.Repository.Name
	ctx.Data["CommitCount"] = commitsCount
	ctx.Data["Branch"] = ctx.Repo.BranchName
	ctx.Data["Page"] = context.NewPagination(int(allCommitsCount), setting.UI.GraphMaxCommitNum, page, 5)
	ctx.HTML(200, tplGraph)
}

// SearchCommits render commits filtered by keyword
func SearchCommits(ctx *context.Context) {
	ctx.Data["PageIsCommits"] = true
	ctx.Data["PageIsViewCode"] = true

	query := strings.Trim(ctx.Query("q"), " ")
	if len(query) == 0 {
		ctx.Redirect(ctx.Repo.RepoLink + "/commits/" + ctx.Repo.BranchNameSubURL())
		return
	}

	all := ctx.QueryBool("all")
	opts := git.NewSearchCommitsOptions(query, all)
	commits, err := ctx.Repo.Commit.SearchCommits(opts)
	if err != nil {
		ctx.ServerError("SearchCommits", err)
		return
	}
	commits = models.ValidateCommitsWithEmails(commits)
	commits = models.ParseCommitsWithSignature(commits, ctx.Repo.Repository)
	commits = models.ParseCommitsWithStatus(commits, ctx.Repo.Repository)
	ctx.Data["Commits"] = commits

	ctx.Data["Keyword"] = query
	if all {
		ctx.Data["All"] = "checked"
	}
	ctx.Data["Username"] = ctx.Repo.Owner.Name
	ctx.Data["Reponame"] = ctx.Repo.Repository.Name
	ctx.Data["CommitCount"] = commits.Len()
	ctx.Data["Branch"] = ctx.Repo.BranchName
	ctx.HTML(200, tplCommits)
}

// FileHistory show a file's reversions
func FileHistory(ctx *context.Context) {
	ctx.Data["IsRepoToolbarCommits"] = true

	fileName := ctx.Repo.TreePath
	if len(fileName) == 0 {
		Commits(ctx)
		return
	}

	branchName := ctx.Repo.BranchName
	commitsCount, err := ctx.Repo.GitRepo.FileCommitsCount(branchName, fileName)
	if err != nil {
		ctx.ServerError("FileCommitsCount", err)
		return
	} else if commitsCount == 0 {
		ctx.NotFound("FileCommitsCount", nil)
		return
	}

	page := ctx.QueryInt("page")
	if page <= 1 {
		page = 1
	}

	commits, err := ctx.Repo.GitRepo.CommitsByFileAndRange(branchName, fileName, page)
	if err != nil {
		ctx.ServerError("CommitsByFileAndRange", err)
		return
	}
	commits = models.ValidateCommitsWithEmails(commits)
	commits = models.ParseCommitsWithSignature(commits, ctx.Repo.Repository)
	commits = models.ParseCommitsWithStatus(commits, ctx.Repo.Repository)
	ctx.Data["Commits"] = commits

	ctx.Data["Username"] = ctx.Repo.Owner.Name
	ctx.Data["Reponame"] = ctx.Repo.Repository.Name
	ctx.Data["FileName"] = fileName
	ctx.Data["CommitCount"] = commitsCount
	ctx.Data["Branch"] = branchName

	pager := context.NewPagination(int(commitsCount), git.CommitsRangeSize, page, 5)
	pager.SetDefaultParams(ctx)
	ctx.Data["Page"] = pager

	ctx.HTML(200, tplCommits)
}

// Diff show different from current commit to previous commit
func Diff(ctx *context.Context) {
	ctx.Data["PageIsDiff"] = true
	ctx.Data["RequireHighlightJS"] = true
	ctx.Data["RequireSimpleMDE"] = true
	ctx.Data["RequireTribute"] = true

	userName := ctx.Repo.Owner.Name
	repoName := ctx.Repo.Repository.Name
	commitID := ctx.Params(":sha")
	var (
		gitRepo  *git.Repository
		err      error
		repoPath string
	)

	if ctx.Data["PageIsWiki"] != nil {
		gitRepo, err = git.OpenRepository(ctx.Repo.Repository.WikiPath())
		if err != nil {
			ctx.ServerError("Repo.GitRepo.GetCommit", err)
			return
		}
		repoPath = ctx.Repo.Repository.WikiPath()
	} else {
		gitRepo = ctx.Repo.GitRepo
		repoPath = models.RepoPath(userName, repoName)
	}

	commit, err := gitRepo.GetCommit(commitID)
	if err != nil {
		if git.IsErrNotExist(err) {
			ctx.NotFound("Repo.GitRepo.GetCommit", err)
		} else {
			ctx.ServerError("Repo.GitRepo.GetCommit", err)
		}
		return
	}
	if len(commitID) != 40 {
		commitID = commit.ID.String()
	}

	statuses, err := models.GetLatestCommitStatus(ctx.Repo.Repository, commitID, 0)
	if err != nil {
		log.Error("GetLatestCommitStatus: %v", err)
	}

	ctx.Data["CommitStatus"] = models.CalcCommitStatus(statuses)

	diff, err := gitdiff.GetDiffCommit(repoPath,
		commitID, setting.Git.MaxGitDiffLines,
		setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
	if err != nil {
		ctx.NotFound("GetDiffCommit", err)
		return
	}

	parents := make([]string, commit.ParentCount())
	for i := 0; i < commit.ParentCount(); i++ {
		sha, err := commit.ParentID(i)
		if err != nil {
			ctx.NotFound("repo.Diff", err)
			return
		}
		parents[i] = sha.String()
	}

	ctx.Data["CommitID"] = commitID
	ctx.Data["AfterCommitID"] = commitID
	ctx.Data["Username"] = userName
	ctx.Data["Reponame"] = repoName

	var parentCommit *git.Commit
	if commit.ParentCount() > 0 {
		parentCommit, err = gitRepo.GetCommit(parents[0])
		if err != nil {
			ctx.NotFound("GetParentCommit", err)
			return
		}
	}
	setImageCompareContext(ctx, parentCommit, commit)
	headTarget := path.Join(userName, repoName)
	setPathsCompareContext(ctx, parentCommit, commit, headTarget)
	ctx.Data["Title"] = commit.Summary() + " · " + base.ShortSha(commitID)
	ctx.Data["Commit"] = commit
	verification := models.ParseCommitWithSignature(commit)
	ctx.Data["Verification"] = verification
	ctx.Data["Author"] = models.ValidateCommitWithEmail(commit)
	ctx.Data["Diff"] = diff
	ctx.Data["Parents"] = parents
	ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0

	if err := models.CalculateTrustStatus(verification, ctx.Repo.Repository, nil); err != nil {
		ctx.ServerError("CalculateTrustStatus", err)
		return
	}

	note := &git.Note{}
	err = git.GetNote(ctx.Repo.GitRepo, commitID, note)
	if err == nil {
		ctx.Data["Note"] = string(charset.ToUTF8WithFallback(note.Message))
		ctx.Data["NoteCommit"] = note.Commit
		ctx.Data["NoteAuthor"] = models.ValidateCommitWithEmail(note.Commit)
	}

	ctx.Data["BranchName"], err = commit.GetBranchName()
	if err != nil {
		ctx.ServerError("commit.GetBranchName", err)
		return
	}
	ctx.HTML(200, tplCommitPage)
}

// RawDiff dumps diff results of repository in given commit ID to io.Writer
func RawDiff(ctx *context.Context) {
	var repoPath string
	if ctx.Data["PageIsWiki"] != nil {
		repoPath = ctx.Repo.Repository.WikiPath()
	} else {
		repoPath = models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
	}
	if err := git.GetRawDiff(
		repoPath,
		ctx.Params(":sha"),
		git.RawDiffType(ctx.Params(":ext")),
		ctx.Resp,
	); err != nil {
		ctx.ServerError("GetRawDiff", err)
		return
	}
}


text:
/*!
*  \file File tileSet.cpp
*  \brief Implementation of the class TileSet
*
*  Auxiliary documentation
*  \sa tileSet.hpp
*/
#include <tileSet.hpp>
#include <assert.h>

/*!
	@class TileSet
	@brief This class provides the tile sets to the game
*/

//! A constructor.
/*!
*	This is a constructor method of TileSet class
*	\param width
*	\brief A positive integer, that represents width of a tile
*	\param height
*	\brief A positive integer, that represents height of a tile
*	\param file_path
*	\brief A string, that represents path of the file with the tile set
*/
TileSet::TileSet(int width, int height, string file_path) {
	LOG_METHOD_START("TileSet::TileSet");
	assert(width > 0);
	LOG_VARIABLE("width",width);
	assert(height > 0);
	LOG_VARIABLE("height",height);
	assert(file_path != "");
	LOG_VARIABLE("file_path",file_path);
	load(width, height, file_path);
	LOG_METHOD_CLOSE("TileSet::TileSet","constructor");
}

//! A constructor.
    /*!
    This is a empty constructor method of TileSet class
    */
TileSet::TileSet() {
	LOG_METHOD_START("TileSet::TileSet");
	LOG_METHOD_CLOSE("TileSet::TileSet","constructor");
}

/*!
	@fn void TileSet::render(unsigned int index,float position_x,float position_y, float extended_scale)
	@brief Method that renders the tile set
	@param index
	@brief A unsigned integer
	@param position_x
	@brief A float
	@param position_y
	@brief A float
	@param extended_scale
	@brief A float
	@return The execution of this method returns no value
	@warning Method that requires review of comment
*/
void TileSet::render(unsigned int index, float position_x, float position_y,
											float extended_scale) {
	LOG_METHOD_START("TileSet::render");
	LOG_VARIABLE("index",index);
	LOG_VARIABLE("position_x",position_x);
	LOG_VARIABLE("position_y",position_y);
	LOG_VARIABLE("extended_scale",extended_scale);
	//! Checks if the number of tiles is bigger that the index
	if ((int)index < (rows * columns)) {
		//! var sprite_start_x
		//!< A positive integer that represents the start of the sprite in x
		int setclip_start_x = tile_width * (index % columns);
		//! var sprite_start_y
		//!< A positive integer that represents the start of the sprite in y
		int setclip_start_y = tile_height*(index/columns);
		tileSet.SetClip(setclip_start_x, setclip_start_y,tile_width, tile_height);
		tileSet.render(position_x, position_y, 0, extended_scale);
	}
	else{
		// do nothing
	}
	LOG_METHOD_CLOSE("TileSet::render","void");
}

/*!
	@fn void TileSet::load(int  width, int height, string file_path)
	@brief Method that loads the tile set from the file
	@param width
	@brief A positive integer, that represents width of a tile
	@param height
	@brief A positive integer, that represents height of a tile
	@param file_path
	@brief A string, that represents path of the file with the tile set
	@return The execution of this method returns no value
*/
void TileSet::load(int  width, int height, string file_path) {
	LOG_METHOD_START("TileSet::load");
	assert(width > 0);
	LOG_VARIABLE("width",width);
	assert(height > 0);
	LOG_VARIABLE("height",height);
	LOG_VARIABLE("file_path",file_path);
  //! Attributes the value of the width and height of a tile
	tile_width = width;
	tile_height = height;

	//! Opens the file with the tile set
  tileSet.Open(file_path);

  //! Defines the numbers of rows and columns of the tile set
  rows = tileSet.GetHeight() / tile_height;
	assert(rows >= 0);
	columns = tileSet.GetWidth() / tile_width;
	assert(columns >= 0);
	LOG_METHOD_CLOSE("TileSet::load","void");
}

/*!
	@fn int TileSet::get_width()
	@brief A getter of the attribute tileWidth
	@return A positive integer, that represents the width of a tile
*/
int TileSet::get_width() {
	LOG_METHOD_START("TileSet::get_width");
	LOG_METHOD_CLOSE("TileSet::get_width",tile_width);
	assert(tile_width >= 0);
	return tile_width;
}

/*!
	@fn int TileSet::get_height()
	@brief A getter of the attribute tileHeight
	@return A positive integer, that represents the height of a tile
*/
int TileSet::get_height() {
	LOG_METHOD_START("TileSet::get_height");
	LOG_METHOD_CLOSE("TileSet::get_height",tile_height);
	assert(tile_height >= 0);
	return tile_height;
}

/*!
	@fn int TileSet::get_tile_count()
	@brief Method that returns the number of tiles in the tile set
	@return A positive integer, that number of tiles in the tile set
*/
int TileSet::get_tile_count() {
	LOG_METHOD_START("TileSet::get_tile_count");
	LOG_METHOD_CLOSE("TileSet::get_tile_count",rows*columns);
	assert(rows * columns >= 0);
	return rows * columns;
}


text:
"""
=====================================
SGDOneClassSVM benchmark
=====================================
This benchmark compares the :class:`SGDOneClassSVM` with :class:`OneClassSVM`.
The former is an online One-Class SVM implemented with a Stochastic Gradient
Descent (SGD). The latter is based on the LibSVM implementation. The
complexity of :class:`SGDOneClassSVM` is linear in the number of samples
whereas the one of :class:`OneClassSVM` is at best quadratic in the number of
samples. We here compare the performance in terms of AUC and training time on
classical anomaly detection datasets.

The :class:`OneClassSVM` is applied with a Gaussian kernel and we therefore
use a kernel approximation prior to the application of :class:`SGDOneClassSVM`.
"""

from time import time
import numpy as np

from scipy.interpolate import interp1d

from sklearn.metrics import roc_curve, auc
from sklearn.datasets import fetch_kddcup99, fetch_covtype
from sklearn.preprocessing import LabelBinarizer, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.utils import shuffle
from sklearn.kernel_approximation import Nystroem
from sklearn.svm import OneClassSVM
from sklearn.linear_model import SGDOneClassSVM

import matplotlib.pyplot as plt
import matplotlib

font = {"weight": "normal", "size": 15}

matplotlib.rc("font", **font)

print(__doc__)

def print_outlier_ratio(y):
    """
    Helper function to show the distinct value count of element in the target.
    Useful indicator for the datasets used in bench_isolation_forest.py.
    """
    uniq, cnt = np.unique(y, return_counts=True)
    print("----- Target count values: ")
    for u, c in zip(uniq, cnt):
        print("------ %s -> %d occurrences" % (str(u), c))
    print("----- Outlier ratio: %.5f" % (np.min(cnt) / len(y)))

# for roc curve computation
n_axis = 1000
x_axis = np.linspace(0, 1, n_axis)

datasets = ["http", "smtp", "SA", "SF", "forestcover"]

novelty_detection = False  # if False, training set polluted by outliers

random_states = [42]
nu = 0.05

results_libsvm = np.empty((len(datasets), n_axis + 5))
results_online = np.empty((len(datasets), n_axis + 5))

for dat, dataset_name in enumerate(datasets):

    print(dataset_name)

    # Loading datasets
    if dataset_name in ["http", "smtp", "SA", "SF"]:
        dataset = fetch_kddcup99(
            subset=dataset_name, shuffle=False, percent10=False, random_state=88
        )
        X = dataset.data
        y = dataset.target

    if dataset_name == "forestcover":
        dataset = fetch_covtype(shuffle=False)
        X = dataset.data
        y = dataset.target
        # normal data are those with attribute 2
        # abnormal those with attribute 4
        s = (y == 2) + (y == 4)
        X = X[s, :]
        y = y[s]
        y = (y != 2).astype(int)

    # Vectorizing data
    if dataset_name == "SF":
        # Casting type of X (object) as string is needed for string categorical
        # features to apply LabelBinarizer
        lb = LabelBinarizer()
        x1 = lb.fit_transform(X[:, 1].astype(str))
        X = np.c_[X[:, :1], x1, X[:, 2:]]
        y = (y != b"normal.").astype(int)

    if dataset_name == "SA":
        lb = LabelBinarizer()
        # Casting type of X (object) as string is needed for string categorical
        # features to apply LabelBinarizer
        x1 = lb.fit_transform(X[:, 1].astype(str))
        x2 = lb.fit_transform(X[:, 2].astype(str))
        x3 = lb.fit_transform(X[:, 3].astype(str))
        X = np.c_[X[:, :1], x1, x2, x3, X[:, 4:]]
        y = (y != b"normal.").astype(int)

    if dataset_name in ["http", "smtp"]:
        y = (y != b"normal.").astype(int)

    print_outlier_ratio(y)

    n_samples, n_features = np.shape(X)
    if dataset_name == "SA":  # LibSVM too long with n_samples // 2
        n_samples_train = n_samples // 20
    else:
        n_samples_train = n_samples // 2

    n_samples_test = n_samples - n_samples_train
    print("n_train: ", n_samples_train)
    print("n_features: ", n_features)

    tpr_libsvm = np.zeros(n_axis)
    tpr_online = np.zeros(n_axis)
    fit_time_libsvm = 0
    fit_time_online = 0
    predict_time_libsvm = 0
    predict_time_online = 0

    X = X.astype(float)

    gamma = 1 / n_features  # OCSVM default parameter

    for random_state in random_states:

        print("random state: %s" % random_state)

        X, y = shuffle(X, y, random_state=random_state)
        X_train = X[:n_samples_train]
        X_test = X[n_samples_train:]
        y_train = y[:n_samples_train]
        y_test = y[n_samples_train:]

        if novelty_detection:
            X_train = X_train[y_train == 0]
            y_train = y_train[y_train == 0]

        std = StandardScaler()

        print("----------- LibSVM OCSVM ------------")
        ocsvm = OneClassSVM(kernel="rbf", gamma=gamma, nu=nu)
        pipe_libsvm = make_pipeline(std, ocsvm)

        tstart = time()
        pipe_libsvm.fit(X_train)
        fit_time_libsvm += time() - tstart

        tstart = time()
        # scoring such that the lower, the more normal
        scoring = -pipe_libsvm.decision_function(X_test)
        predict_time_libsvm += time() - tstart
        fpr_libsvm_, tpr_libsvm_, _ = roc_curve(y_test, scoring)

        f_libsvm = interp1d(fpr_libsvm_, tpr_libsvm_)
        tpr_libsvm += f_libsvm(x_axis)

        print("----------- Online OCSVM ------------")
        nystroem = Nystroem(gamma=gamma, random_state=random_state)
        online_ocsvm = SGDOneClassSVM(nu=nu, random_state=random_state)
        pipe_online = make_pipeline(std, nystroem, online_ocsvm)

        tstart = time()
        pipe_online.fit(X_train)
        fit_time_online += time() - tstart

        tstart = time()
        # scoring such that the lower, the more normal
        scoring = -pipe_online.decision_function(X_test)
        predict_time_online += time() - tstart
        fpr_online_, tpr_online_, _ = roc_curve(y_test, scoring)

        f_online = interp1d(fpr_online_, tpr_online_)
        tpr_online += f_online(x_axis)

    tpr_libsvm /= len(random_states)
    tpr_libsvm[0] = 0.0
    fit_time_libsvm /= len(random_states)
    predict_time_libsvm /= len(random_states)
    auc_libsvm = auc(x_axis, tpr_libsvm)

    results_libsvm[dat] = [
        fit_time_libsvm,
        predict_time_libsvm,
        auc_libsvm,
        n_samples_train,
        n_features,
    ] + list(tpr_libsvm)

    tpr_online /= len(random_states)
    tpr_online[0] = 0.0
    fit_time_online /= len(random_states)
    predict_time_online /= len(random_states)
    auc_online = auc(x_axis, tpr_online)

    results_online[dat] = [
        fit_time_online,
        predict_time_online,
        auc_online,
        n_samples_train,
        n_features,
    ] + list(tpr_libsvm)

# -------- Plotting bar charts -------------
fit_time_libsvm_all = results_libsvm[:, 0]
predict_time_libsvm_all = results_libsvm[:, 1]
auc_libsvm_all = results_libsvm[:, 2]
n_train_all = results_libsvm[:, 3]
n_features_all = results_libsvm[:, 4]

fit_time_online_all = results_online[:, 0]
predict_time_online_all = results_online[:, 1]
auc_online_all = results_online[:, 2]

width = 0.7
ind = 2 * np.arange(len(datasets))
x_tickslabels = [
    (name + "\n" + r"$n={:,d}$" + "\n" + r"$d={:d}$").format(int(n), int(d))
    for name, n, d in zip(datasets, n_train_all, n_features_all)
]

def autolabel_auc(rects, ax):
    """Attach a text label above each bar displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.text(
            rect.get_x() + rect.get_width() / 2.0,
            1.05 * height,
            "%.3f" % height,
            ha="center",
            va="bottom",
        )

def autolabel_time(rects, ax):
    """Attach a text label above each bar displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.text(
            rect.get_x() + rect.get_width() / 2.0,
            1.05 * height,
            "%.1f" % height,
            ha="center",
            va="bottom",
        )

fig, ax = plt.subplots(figsize=(15, 8))
ax.set_ylabel("AUC")
ax.set_ylim((0, 1.3))
rect_libsvm = ax.bar(ind, auc_libsvm_all, width=width, color="r")
rect_online = ax.bar(ind + width, auc_online_all, width=width, color="y")
ax.legend((rect_libsvm[0], rect_online[0]), ("LibSVM", "Online SVM"))
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(x_tickslabels)
autolabel_auc(rect_libsvm, ax)
autolabel_auc(rect_online, ax)
plt.show()

fig, ax = plt.subplots(figsize=(15, 8))
ax.set_ylabel("Training time (sec) - Log scale")
ax.set_yscale("log")
rect_libsvm = ax.bar(ind, fit_time_libsvm_all, color="r", width=width)
rect_online = ax.bar(ind + width, fit_time_online_all, color="y", width=width)
ax.legend((rect_libsvm[0], rect_online[0]), ("LibSVM", "Online SVM"))
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(x_tickslabels)
autolabel_time(rect_libsvm, ax)
autolabel_time(rect_online, ax)
plt.show()

fig, ax = plt.subplots(figsize=(15, 8))
ax.set_ylabel("Testing time (sec) - Log scale")
ax.set_yscale("log")
rect_libsvm = ax.bar(ind, predict_time_libsvm_all, color="r", width=width)
rect_online = ax.bar(ind + width, predict_time_online_all, color="y", width=width)
ax.legend((rect_libsvm[0], rect_online[0]), ("LibSVM", "Online SVM"))
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(x_tickslabels)
autolabel_time(rect_libsvm, ax)
autolabel_time(rect_online, ax)
plt.show()