text:
namespace ppapi {
namespace proxy {

namespace {

typedef PluginProxyTest FileChooserResourceTest;

void* GetFileRefDataBuffer(void* user_data,
                           uint32_t element_count,
                           uint32_t element_size) {
  EXPECT_TRUE(element_size == sizeof(PP_Resource));
  std::vector<PP_Resource>* output =
      static_cast<std::vector<PP_Resource>*>(user_data);
  output->resize(element_count);
  if (element_count > 0)
    return &(*output)[0];
  return NULL;
}

void DoNothingCallback(void* user_data, int32_t result) {
}

// Calls PopulateAcceptTypes and verifies that the resulting array contains
// the given values. The values may be NULL if there aren't expected to be
// that many results.
bool CheckParseAcceptType(const std::string& input,
                          const char* expected1,
                          const char* expected2) {
  std::vector<std::string> output;
  FileChooserResource::PopulateAcceptTypes(input, &output);

  const size_t kCount = 2;
  const char* expected[kCount] = { expected1, expected2 };

  for (size_t i = 0; i < kCount; i++) {
    if (!expected[i])
      return i == output.size();
    if (output.size() <= i)
      return false;
    if (output[i] != expected[i])
      return false;
  }

  return output.size() == kCount;
}

}  // namespace

// Does a full test of Show() and reply functionality in the plugin side using
// the public C interfaces.
TEST_F(FileChooserResourceTest, Show) {
  const PPB_FileChooser_Dev_0_6* chooser_iface =
      thunk::GetPPB_FileChooser_Dev_0_6_Thunk();
  ScopedPPResource res(ScopedPPResource::PassRef(),
      chooser_iface->Create(pp_instance(), PP_FILECHOOSERMODE_OPEN,
                            PP_MakeUndefined()));

  std::vector<PP_Resource> dest;
  PP_ArrayOutput output;
  output.GetDataBuffer = &GetFileRefDataBuffer;
  output.user_data = &dest;

  int32_t result = chooser_iface->Show(
      res, output, PP_MakeCompletionCallback(&DoNothingCallback, NULL));
  ASSERT_EQ(PP_OK_COMPLETIONPENDING, result);

  // Should have sent a "show" message.
  ResourceMessageCallParams params;
  IPC::Message msg;
  ASSERT_TRUE(sink().GetFirstResourceCallMatching(
      PpapiHostMsg_FileChooser_Show::ID, &params, &msg));

  ResourceMessageReplyParams reply_params(params.pp_resource(),
                                          params.sequence());
  reply_params.set_result(PP_OK);

  // Synthesize a response with one file ref in it. Note that it must have a
  // host resource value set or deserialization will fail. Since there isn't
  // actually a host, this can be whatever we want.
  std::vector<PPB_FileRef_CreateInfo> create_info_array;
  PPB_FileRef_CreateInfo create_info;
  create_info.resource.SetHostResource(pp_instance(), 123);
  create_info.path = "foo/bar";
  create_info.name = "baz";
  create_info_array.push_back(create_info);
  ASSERT_TRUE(plugin_dispatcher()->OnMessageReceived(
      PpapiPluginMsg_ResourceReply(reply_params,
          PpapiPluginMsg_FileChooser_ShowReply(create_info_array))));

  // Should have populated our vector.
  ASSERT_EQ(1u, dest.size());
  ScopedPPResource dest_deletor(dest[0]);  // Ensure it's cleaned up.

  const PPB_FileRef_1_0* file_ref_iface = thunk::GetPPB_FileRef_1_0_Thunk();
  EXPECT_EQ(PP_FILESYSTEMTYPE_EXTERNAL,
            file_ref_iface->GetFileSystemType(dest[0]));

  ScopedPPVar name_var(ScopedPPVar::PassRef(),
                       file_ref_iface->GetName(dest[0]));
  EXPECT_VAR_IS_STRING(create_info.name, name_var.get());

  // Path should be undefined since it's external filesystem.
  ScopedPPVar path_var(ScopedPPVar::PassRef(),
                       file_ref_iface->GetPath(dest[0]));
  EXPECT_EQ(PP_VARTYPE_UNDEFINED, path_var.get().type);
}

TEST_F(FileChooserResourceTest, PopulateAcceptTypes) {
  EXPECT_TRUE(CheckParseAcceptType(std::string(), NULL, NULL));
  EXPECT_TRUE(CheckParseAcceptType("/", NULL, NULL));
  EXPECT_TRUE(CheckParseAcceptType(".", NULL, NULL));
  EXPECT_TRUE(CheckParseAcceptType(",, , ", NULL, NULL));

  EXPECT_TRUE(CheckParseAcceptType("app/txt", "app/txt", NULL));
  EXPECT_TRUE(CheckParseAcceptType("app/txt,app/pdf", "app/txt", "app/pdf"));
  EXPECT_TRUE(CheckParseAcceptType(" app/txt , app/pdf ",
                                   "app/txt", "app/pdf"));

  // No dot or slash ones should be skipped.
  EXPECT_TRUE(CheckParseAcceptType("foo", NULL, NULL));
  EXPECT_TRUE(CheckParseAcceptType("foo,.txt", ".txt", NULL));
}

}  // namespace proxy
}  // namespace ppapi


text:
jQuery(document).ready(function( $ ) {

  // Preloader
  $(window).load(function(){
    $('#preloader').delay(100).fadeOut('slow',function(){$(this).remove();});
  });

  //Limittext synopsis to 260 char - changed to 225 after adding imdb/trailer img's
  $(".limittext").each(function(){
    len=$(this).text().length;
    if(len>225)
    {
      $(this).text($(this).text().substr(0,225)+'...');
    }
  });

  // Hero rotating texts
  $("#hero .rotating").Morphext({
    animation: "flipInX",
    separator: ",",
    speed: 3000
  });

  // Initiate the wowjs
  new WOW().init();

  // Initiate superfish on nav menu
  $('.nav-menu').superfish({
    animation: {opacity:'show'},
    speed: 400
  });

  // Mobile Navigation
  if( $('#nav-menu-container').length ) {
      var $mobile_nav = $('#nav-menu-container').clone().prop({ id: 'mobile-nav'});
      $mobile_nav.find('> ul').attr({ 'class' : '', 'id' : '' });
      $('body').append( $mobile_nav );
      $('body').prepend( '<button type="button" id="mobile-nav-toggle"></button>' );
      $('body').append( '

' );
      $('#mobile-nav').find('.menu-has-children').prepend('');

      $(document).on('click', '.menu-has-children i', function(e){
          $(this).next().toggleClass('menu-item-active');
          $(this).nextAll('ul').eq(0).slideToggle();
          $(this).toggleClass("fa-chevron-up fa-chevron-down");
      });

      $(document).on('click', '#mobile-nav-toggle', function(e){
          $('body').toggleClass('mobile-nav-active');
          $('#mobile-nav-toggle i').toggleClass('fa-times fa-bars');
          $('#mobile-body-overly').toggle();
      });

      $(document).click(function (e) {
          var container = $("#mobile-nav, #mobile-nav-toggle");
          if (!container.is(e.target) && container.has(e.target).length === 0) {
             if ( $('body').hasClass('mobile-nav-active') ) {
                  $('body').removeClass('mobile-nav-active');
                  $('#mobile-nav-toggle i').toggleClass('fa-times fa-bars');
                  $('#mobile-body-overly').fadeOut();
              }
          }
      });
  } else if ( $("#mobile-nav, #mobile-nav-toggle").length ) {
      $("#mobile-nav, #mobile-nav-toggle").hide();
  }

  // Stick the header at top on scroll
  $("#header").sticky({topSpacing:0, zIndex: '50'});

  // Smoth scroll on page hash links
  $('a[href*="#"]:not([href="#"])').on('click', function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          if (target.length) {

              var top_space = 0;

              if( $('#header').length ) {
                top_space = $('#header').outerHeight();
              }

              $('html, body').animate({
                  scrollTop: target.offset().top - top_space
              }, 1500, 'easeInOutExpo');

              if ( $(this).parents('.nav-menu').length ) {
                $('.nav-menu .menu-active').removeClass('menu-active');
                $(this).closest('li').addClass('menu-active');
              }

              if ( $('body').hasClass('mobile-nav-active') ) {
                  $('body').removeClass('mobile-nav-active');
                  $('#mobile-nav-toggle i').toggleClass('fa-times fa-bars');
                  $('#mobile-body-overly').fadeOut();
              }

              return false;
          }
      }
  });

  // Back to top button
  $(window).scroll(function() {

      if ($(this).scrollTop() > 100) {
          $('.back-to-top').fadeIn('slow');
      } else {
          $('.back-to-top').fadeOut('slow');
      }

  });

  $('.back-to-top').click(function(){
      $('html, body').animate({scrollTop : 0},1500, 'easeInOutExpo');
      return false;
  });

	  var $videoSrc;
	$('.video-btn').click(function() {
		$videoSrc = $(this).data( "src" );
		console.log($videoSrc);
	});

	// when the modal is opened autoplay it
	$('#myModal').on('shown.bs.modal', function (e) {

	// set the video src to autoplay and not to show related video. Youtube related video is like a box of chocolates... you never know what you're gonna get
	$("#video").attr('src',$videoSrc + "?rel=0&showinfo=0&modestbranding=1&autoplay=1" );
	})

	// stop playing the youtube video when I close the modal
	$('#myModal').on('hide.bs.modal', function (e) {
		// a poor man's stop video
		$("#video").attr('src',$videoSrc);
	})

});

//$(document).ready(function() {

// Gets the video src from the data-src on each button

// document ready
// });

redpajama_set_name: RedPajamaGithub


text:
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
 * @name parseJSON
 * @category Common Helpers
 * @summary Parse a JSON date string
 *
 * @description
 * Converts a complete ISO date string in UTC time, the typical format for transmitting
 * a date in JSON, to a JavaScript `Date` instance.
 *
 * This is a minimal implementation for converting dates retrieved from a JSON API to
 * a `Date` instance which can be used with other functions in the `date-fns` library.
 * The following formats are supported:
 *
 *     - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())`
 *     - `2000-03-15T05:20:10Z`: Without milliseconds
 *     - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages
 *     - `2000-03-15T05:20:10+0000`: With a zero offset without a colon
 *     - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol
 *     - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds
 *     - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting
 *
 * For convenience and ease of use these other input types are also supported
 * via [toDate]{@link https://date-fns.org/docs/toDate}:
 *
 *     - A `Date` instance will be cloned
 *     - A `number` will be treated as a timestamp
 *
 * Any other input type or invalid date strings will return an `Invalid Date`.
 *
 * @param {String|Number|Date} argument A fully formed ISO8601 date string to convert
 * @returns {Date} the parsed date in the local time zone
 * @throws {TypeError} 1 argument required
 */

export default function parseJSON(argument) {
  requiredArgs(1, arguments);

  if (typeof argument === 'string') {
    var parts = argument.match(/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|\+00:?00)?/);

    if (parts) {
      return new Date(Date.UTC(+parts[1], parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6], +((parts[7] || '0') + '00').substring(0, 3)));
    }

    return new Date(NaN);
  }

  return toDate(argument);
}


text:
layout: post
title: "Higher Education"
date: 2017-05-16 3:33:18
categories: learning college university
---

"Self-education is, I firmly believe, the only kind of education there is." - Isaac Asimov

- [Hacking Higher Education](https://joshkaufman.net/hacking-higher-education-clep/)
- [MIT Challenge](https://www.scotthyoung.com/blog/myprojects/mit-challenge-2/)
- [Saylor Academy](https://www.saylor.org/)
- [Thomas Edison University](http://www.tesu.edu)
- [MIT OpenCourseWare](https://ocw.mit.edu/)
- [Excelsior College](http://www.excelsior.edu)


text:
#include "implementation.hpp"

int EXAMPLE_MAIN (int argc, char *argv[])
{
  return examples::protobuf::isocpp::publisher(argc, argv);
}


text:
package org.wso2.carbon.cassandra.search.data.json;

import java.util.ArrayList;
import java.util.List;

public class Events {
    private List<Event> results = null;

    public Events() {
        results = new ArrayList<Event>();
    }

    public void addEvent(Event record) {
        results.add(record);
    }

    public void setResults(List<Event> results) {
        this.results = results;
    }
}


text:
class Operators {
    static get pop():string {
        return "pop";
    }

    static get push():string {
        return "push";
    }

    static get add():string {
        return "add";
    }

    static get sub():string {
        return "sub";
    }
}
class MemoryStack {
    private ram:RAM;
    private start_address:Word;
    private end_address:Word;
    private pointer:Word;

    constructor(ram:RAM,start:Word,end:Word){
        this.ram = ram;
        this.start_address =start;
        this.pointer = this.start_address;
        this.end_address = end;
    }
    pop():Word {
        if (this.pointer.value <= this.start_address.value) {
            throw new Error("Attempt to pop an empty stack ");
        }
        let res = this.ram.run(null, true, this.pointer);
        this.pointer = new Word(this.pointer.value);
        return res;
    }

    push(w:Word) {
        if (this.pointer.value >= this.end_address.value - 1) {
            throw new Error("Attempt to push on a full stack ");
        }
        this.ram.run(w, false, this.pointer);
        this.pointer = new Word(this.pointer.value + 1);
    }
}
class VM{
    _localStack:MemoryStack;
    _staticStack:MemoryStack;
    _thisStack:MemoryStack;
    _thatStack:MemoryStack;
    _argumentStack:MemoryStack;
    _pointerStack:MemoryStack;
    _constantStack:MemoryStack;
    _tempStack:MemoryStack;
    myStacks:{ [name : string]: MemoryStack; };
    initStacks(ram:RAM){
        this._staticStack = new MemoryStack(ram,Word.Zero,new Word(314));
        this.myStacks ={
            "static":this._staticStack
        }
    }

}


text:
FROM imageintelligence/scala:965dea1bee3b910262bd2b7a6a48af6cbbc54cee
MAINTAINER David Vuong <david@imageintelligence.com>

COPY . /root/app
WORKDIR /root/app

RUN mkdir build && \
  sbt compile universal:packageBin && \
  unzip target/universal/pix-api.zip -d build && \
  sbt clean && \
  rm -rf ~/.ivy2

CMD bash -lc "./build/pix-api/bin/pix-api \
  -J-Xms96M \
  -J-Xmx512M \
  -J-server \
  -J-XX:MaxMetaspaceSize=128M \
  -J-XX:+CMSClassUnloadingEnabled \
  -J-XX:+UseConcMarkSweepGC \
  -J-XX:+CMSParallelRemarkEnabled"


text:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import shap
from scipy.stats import poisson as dist
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

from ngboost import NGBRegressor
from ngboost.distns import Poisson

if __name__ == "__main__":

    SEED = 12345
    np.random.seed(SEED)

    """
    This NFL dataset comprises season-long rolling averages of passing stats. It's not an expanding window, so early season games
    rely on data from the previous year. NFL passing touchdowns closely mimic a Poisson distribution. There is plenty of room for
    improvement, this is just an example.

    For more detailed NFL data, visit https://github.com/mrcaseb/nflfastR
    """

    url = "https://raw.githubusercontent.com/btatkinson/sample-data/master/nfl_tds.csv"
    df = pd.read_csv(url, error_bad_lines=False)

    x = df.pass_touchdown.values

    mean = np.mean(x)
    variance = np.var(x)

    print("Passing touchdowns mean: {:.4f}".format(mean))
    print("Passing touchdowns variance: {:.4f}".format(variance))

    k = np.arange(x.max() + 1)

    plt.plot(k, dist.pmf(k, mean) * len(x), "bo", markersize=9, label="expected tds")
    sns.distplot(x, kde=False, label="actual tds")
    plt.title("Naive Poisson Dist Using the Mean")
    plt.legend(loc="upper right")
    plt.show()

    # drop non-feature cols
    df = df.drop(
        columns=[
            "season",
            "game_id",
            "posteam",
            "passer_player_name",
            "passer_player_id",
            "defteam",
        ]
    )

    target = "pass_touchdown"
    X = df.drop(columns=[target]).values
    Y = df[target].values

    X_train, X_test, Y_train, Y_test = train_test_split(
        X, Y, test_size=0.2, random_state=SEED
    )

    # baseline not using predictor data
    avg_tds = np.mean(Y_train)
    y_dist = dist(avg_tds)
    naive_NLL = -y_dist.logpmf(Y_test).mean()

    print(
        "Mean squared error using only the mean: {:.4f}".format(
            mean_squared_error(np.repeat(avg_tds, len(Y_test)), Y_test)
        )
    )
    print(
        "Poisson negative log liklihood without using predictor variables: {:.4f}".format(
            naive_NLL
        )
    )

    ngb = NGBRegressor(Dist=Poisson)

    ngb.fit(X_train, Y_train)

    Y_preds = ngb.predict(X_test)
    Y_dists = ngb.pred_dist(X_test)

    # test Mean Squared Error
    test_MSE = mean_squared_error(Y_preds, Y_test)
    print("NGBoost MSE: {:.4f}".format(test_MSE))

    # test Negative Log Likelihood
    test_NLL = -Y_dists.logpmf(Y_test.flatten()).mean()
    print("NGBoost NLL: {:.4f}".format(test_NLL))

    # Let's see if we can improve by dropping confounding variables
    ## Feature importance for loc trees
    feature_importance_mu = ngb.feature_importances_[0]
    feature_columns = list(df.drop(columns=[target]))

    df_mu = pd.DataFrame(
        {"feature": feature_columns, "importance": feature_importance_mu}
    ).sort_values("importance", ascending=False)

    fig, ax = plt.subplots(1, 1, figsize=(13, 6))
    fig.suptitle("Feature importance plot for distribution parameters", fontsize=17)
    sns.barplot(
        x="importance", y="feature", ax=ax, data=df_mu, color="skyblue"
    ).set_title("mu param")
    plt.show()

    shap.initjs()

    ## SHAP plot for loc trees
    explainer = shap.TreeExplainer(ngb, model_output=0)
    shap_values = explainer.shap_values(X)
    shap.summary_plot(shap_values, X, feature_names=feature_columns)
    plt.show()

    print("Fitting NGBoost again after dropping unused vars...")

    confounding_vars = ["roof"]

    print("PREVIOUS MSE: {:.4f}".format(test_MSE))
    print("PREVIOUS NLL: {:.4f}".format(test_NLL))

    df = df.drop(columns=confounding_vars)
    X = df.drop(columns=[target]).values
    Y = df[target].values

    ngb = NGBRegressor(Dist=Poisson)

    ngb.fit(X_train, Y_train)

    Y_preds = ngb.predict(X_test)
    Y_dists = ngb.pred_dist(X_test)

    # test Mean Squared Error
    new_MSE = mean_squared_error(Y_preds, Y_test)
    print("NEW MSE AFTER DROPPING CONFOUNDING VARS: {:.4f}".format(new_MSE))

    # test Negative Log Likelihood
    new_NLL = -Y_dists.logpmf(Y_test.flatten()).mean()
    print("NEW NLL AFTER DROPPING CONFOUNDING VARS: {:.4f}".format(new_NLL))


text:
layout: default
title: Links
comment: true
keywords: Java blog,Links
---

{{ page.title }}

        {% for i in site.customLinks %}

{{ i.message }}

                {% for link in i.item %}

{{ link.text }}

                {% endfor %}

        {% endfor %}

        {% if site.disqus.config %}

        {% else %}
            {% if site.duoshuo.config %}

            {% endif %}
        {% endif %}


text:
package org.johnywith1n.main

import scala.util.Failure
import scala.util.Success

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.actorRef2Scala
import dispatch.Defaults.executor
import dispatch.Http
import dispatch.as
import dispatch.implyRequestHandlerTuple
import dispatch.url

object HttpRequestMaker {
  case class Request(link: String)
  case class Done(link: String, response: String)
  case class Failed(link: String, e: Throwable)
}
class HttpRequestMaker extends Actor with ActorLogging {
  import HttpRequestMaker._

  def receive = {
    case Request(link) =>
      val http = Http
      val _sender = sender

      try {
        val res = http(url(link) OK as.String)
        res onComplete {
          case Success(s) =>
            _sender ! Done(link, s)
            http.shutdown
          case Failure(e) =>
            _sender ! Failed(link, e)
            http.shutdown
        }
      } catch {
        case e: Exception =>
          _sender ! Failed(link, e)
          http.shutdown
      }
  }
}


text:
import unittest
import requests
import os
import os.path

class GeoMOOSETest(unittest.TestCase):
	host = "localhost:8080"
	geomoose_base = "/geomoose"
	mapserver_base = "/cgi-bin/mapserv"
	temp_dir = '/tmp/gm_tests/'

	def setUp(self):
		if(not os.path.isdir(self.temp_dir)):
			os.mkdir(self.temp_dir)

	def get(self, url, **kwargs):
		return requests.get(url, **kwargs)

	def post(self, url, **kwargs):
		return requests.post(url, **kwargs)


text:
package edu.upc.eetac.dsa.rate.client.entity;

import java.util.List;

import javax.ws.rs.core.*;
import javax.ws.rs.core.Link;

/**
 * Created by tono on 05/01/2016.
 */
public class Likes {
    private List<Link> links;
    private String userid;
    private String revid;
    private Boolean likes;

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public String getRevid() {
        return revid;
    }

    public void setRevid(String revid) {
        this.revid = revid;
    }

    public Boolean getLikes() {
        return likes;
    }

    public void setLikes(Boolean likes) {
        this.likes = likes;
    }
}


text:
package org.apache.yoko.orb.OB;

public class PIArgsDowncall extends PIDowncall {
    //
    // Argument, result and exception list description provided by the
    // static stubs
    //
    protected ParameterDesc[] argDesc_;

    protected ParameterDesc retDesc_;

    protected org.omg.CORBA.TypeCode[] exceptionTC_;

    // ----------------------------------------------------------------------
    // PIArgsDowncall private and protected member implementations
    // ----------------------------------------------------------------------

    // ----------------------------------------------------------------------
    // PIArgsDowncall public member implementations
    // ----------------------------------------------------------------------

    public PIArgsDowncall(ORBInstance orbInstance, Client client,
            org.apache.yoko.orb.OCI.ProfileInfo profileInfo,
            RefCountPolicyList policies, String op, boolean resp,
            org.omg.IOP.IOR IOR, org.omg.IOP.IOR origIOR,
            /**/PIManager piManager, ParameterDesc[] argDesc,
            ParameterDesc retDesc, org.omg.CORBA.TypeCode[] exceptionTC) {
        super(orbInstance, client, profileInfo, policies, op, resp, IOR,
                origIOR, piManager);
        argDesc_ = argDesc;
        retDesc_ = retDesc;
        exceptionTC_ = exceptionTC;
    }

    public org.apache.yoko.orb.CORBA.OutputStream preMarshal()
            throws LocationForward, FailureException {
        requestInfo_ = piManager_.clientSendRequest(op_, responseExpected_,
                IOR_, origIOR_, profileInfo_, policies_.value, requestSCL_,
                replySCL_, argDesc_, retDesc_, exceptionTC_);

        return preMarshalBase(); // Equivalent to Downcall::preMarshal()
    }
}


text:
order: 5
title:
  zh-CN: 自定义关闭
  en-US: Customized Close Text
---

## zh-CN

可以自定义关闭,自定义的文字会替换原先的关闭 `Icon`。

## en-US

Replace the default icon with customized text.

```tsx
import { Alert } from 'antd';
import React from 'react';

const App: React.FC = () => <Alert message="Info Text" type="info" closeText="Close Now" />;

export default App;
```


text:
import * as React from 'react'
import {Card, Box, Text, Code} from '@sanity/ui'

type Props = {error: Error; isAuthError: false} | {isAuthError: true}

export function LoadError(props: Props) {
  return (
    <Card tone="critical" radius={1}>
      <Box as="header" paddingX={4} paddingTop={4} paddingBottom={1}>
        <Text as="h2" weight="bold">
          Google Maps failed to load
        </Text>
      </Box>

      <Box paddingX={4} paddingTop={4} paddingBottom={1}>
        {props.isAuthError ? (
          <AuthError />
        ) : (
          <>
            <Text as="h3">Error details:</Text>

              {props.error?.message}

          </>
        )}
      </Box>
    </Card>
  )
}

function AuthError() {
  return (
    <Text>

The error appears to be related to authentication

Common causes include:

Incorrect API key

Referer not allowed

Missing authentication scope

Check the browser developer tools for more information.

    </Text>
  )
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <link href="http://gmpg.org/xfn/11" rel="profile">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      European amphioxus genome · F. Marlétaz

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/atom+xml" title="F. Marlétaz" href="/atom.xml">

          F. Marlétaz

                 About

                 Research

                 Publications

                 Amphioxus

                 Feed

European amphioxus genome

  Disclaimer: This data is made available to the members of the european amphioxus genome consortium as collaborative material. These datasets are not to be used for whole genome analyses unless otherwise agreed for, and not to be redistributed to anybody outside the consortium without prior arrangements.

Datasets

The genome of the european amphioxus Branchiostoma lancealatum was generated from 150x Illumina coverage sequenced by Génoscope. In the Bl71nemr assembly, haplotypes were reconcilied using haplomerger.

This assembly spans 495.3Mb (N50: 1.29Mb) split in 10,247 scaffolds with 4% of residual gaps. Masked regions are represented with lowercase characters (soft-masking); gaps in the assembly are represented with Ns.

The genome was annotated using both EVM/PASA pipeline and cufflinks/transdecoder. Both these annotation have their strength. Cufflinks provides a better representation of transcript diversity, limits and TSSs positions. Conversely, EVM generates more robust predicted proteins, especially in regard to frameshifts, etc… A final annotation with unified IDs (BL00000) was subsequently built by merging the two annotations with a suffix indicative of their origin (BL00000_evm0 or BL00000_cuff0). All three annotations are available as GTFs.

      File
      Dataset
      Format

      Bl71nemr.fa
      Genome assembly
      Fasta

      Bla_annot-FINAL_v4_names.gtf
      Merged  final annotation (EVM/PASA+cufflinks)
      GTF format

       EVM/PASA annotation
      GTF format

      Cufflinks annotation
      GTF format

      Reference transcripts (most expressed transcript for each locus)
      Fasta

      Reference proteins (longest protein for each locus)
      Fasta

Genome browser

The european amphioxus genome assembly and annotation are available as a UCSC track hub. The RNA-seq, ATAC-seq and Chip-seq available in the browser is not part of the bulk of genome data provided to the consortium and is a courtesy of JL Skarmeta's lab. To enable access, you can either:

Use the following link to a UCSC session which also includes functional genomics data.

set up the hub by adding the hub address http://zoo-animalia.zoo.ox.ac.uk/braLan/hub.txt to My Data > Track Hubs > My hubs in UCSC menu.

Contacts

Please do not hesitate to contact us if you have a specific question:

Hector Escriva, Observatoire Océanologique de Banyuls-sur-Mer, France

Ferdinand Marlétaz, Department of Zoology, University of Oxford, UK

Nacho Maeso, Juan Tena & José-Luis Skarmeta, CABD, Universidad Pablo de Olavide, Sevilla, Spain

Manuel Irimia, CRG, Barcelona, Spain

          © 2015. All rights reserved.


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="bc.css">

### WorksharingUtils

Rudolf [Revitalizer](http://forums.autodesk.com/t5/user/viewprofilepage/user-id/1103138) Honke
has frequently requested better documentation of the Revit API `*Utils` classes, e.g., when he pointed out
the [handy utility classes](http://thebuildingcoder.typepad.com/blog/2013/04/handy-utility-classes.html) back in 2013.

This is still an interesting and somewhat poorly documented area in the Revit API, as we can see from the discussion below:

- [WorksharingUtils and the WorksharingTooltipInfo class](#2)
- [Ten interesting C# features](#3)
- [A new acronym – TL;DR](#4)

#### WorksharingUtils and the WorksharingTooltipInfo Class

The development team answered the following recent Revit API forum thread
on [API access to the workshared element user history](http://forums.autodesk.com/t5/revit-api/workshared-element-user-history/m-p/5896907):

**Question:** Is there any access at all to Workshared Element User History?

If I turn on one of the worksharing display modes and hover my mouse over any element, I get a popup like this advising me of who that element was originally created by and who last updated it in the central model:

Is it possible to programmatically access these fields?

**Answer:** I was unable to find any information about this, so I passed on the question to the Revit development team.

Their answer is short, succinct and to the point: this is in the `WorksharingTooltipInfo` class acquired from the `WorksharingUtils.GetWorksharingTooltipInfo` method.

So we are saved once again by our beloved `Utils` classes.

They and the important functionality they provide are apparently still hard to find.

Many thanks to Scott and Arnošt for pointing this out, and the importance of improving their visibility.

#### Ten Interesting C# Features

My colleague [Augusto Gonçalves](http://adndevblog.typepad.com/aec/augusto-goncalves.html) recently pointed out an article
on [10 features in C# that you really should learn (and use!)](http://www.codeaddiction.net/articles/15/10-features-in-c-that-you-really-should-learn-and-use).

While I do not totally agree with them all, similarly to some of the options voiced in
the comments section, it is still definitely an interesting and worthwhile quick read.

**Addendum:** In
his [comment](http://thebuildingcoder.typepad.com/blog/2015/11/worksharingutils.html#comment-2350844009) below,
Guy Robinson points out another interesting related link to the MSDN article
on [new features in C# 6](http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx),
which is actually more structured and in-depth than the former.

#### A New Acronym – TL;DR

I really dislike acronyms that I do not know the meaning of.

I quite like them when I do, though, and I am certain that my communication partner knows them as well.

I just discovered this one that I like, since it expresses a sentiment I often share: TL;DR – too long; didn't read.

Of course, this leads back to the first topic again: the `*Utils` classes are all documented in the Revit API help file RevitAPI.chm... all you have to do is read it   :-)


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SysUt14Gr03 {

    public partial class OversiktOverTeam {

        /// <summary>
        /// PlaceHolderTable control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.PlaceHolder PlaceHolderTable;
    }
}


text:
package com.vividsolutions.jts.triangulate.quadedge;

import java.util.Collection;
import java.util.LinkedList;

/**
 * A framework to visit sets of edge-connected {@link QuadEdgeTriangle}s in breadth-first order
 *
 * @author Martin Davis
 * @version 1.0
 */
public class EdgeConnectedTriangleTraversal {
    private LinkedList triQueue = new LinkedList();

    public EdgeConnectedTriangleTraversal() {}

    public void init(QuadEdgeTriangle tri) {
        triQueue.addLast(tri);
    }

    /**
     * Called to initialize the traversal queue with a given set of {@link QuadEdgeTriangle}s
     *
     * @param tris a collection of QuadEdgeTriangle
     */
    public void init(Collection tris) {
        triQueue.addAll(tris);
    }

    /**
     * Subclasses can call this method to add a triangle to the end of the queue. This is useful for
     * initializing the queue to a chosen set of triangles.
     *
     * @param tri a triangle
     */
    /*
     * protected void addLast(QuadEdgeTriangle tri) { triQueue.addLast(tri); }
     */

    /**
     * Subclasses call this method to perform the visiting process.
     */
    public void visitAll(TraversalVisitor visitor) {
        while (!triQueue.isEmpty()) {
            QuadEdgeTriangle tri = (QuadEdgeTriangle) triQueue.removeFirst();
            process(tri, visitor);
        }
    }

    private void process(QuadEdgeTriangle currTri, TraversalVisitor visitor) {
        currTri.getNeighbours();
        for (int i = 0; i < 3; i++) {
            QuadEdgeTriangle neighTri = (QuadEdgeTriangle) currTri.getEdge(i).sym().getData();
            if (neighTri == null)
                continue;
            if (visitor.visit(currTri, i, neighTri))
                triQueue.addLast(neighTri);
        }
    }

}


text:
class Vtlink::MerchantController < ApplicationController

  # show checkout-form
  def checkout
  end

end


text:
START_ATF_NAMESPACE
    #pragma pack(push, 1)
    struct  _darkhole_real_add_time_inform_zocl
    {
        int nAddSec;
        unsigned int dwTotalLimSec;
        char szMsg[17];
    public:
        int size();
    };
    #pragma pack(pop)
    static_assert(ATF::checkSize<_darkhole_real_add_time_inform_zocl, 25>(), "_darkhole_real_add_time_inform_zocl");
END_ATF_NAMESPACE


text:
require 'rails_helper'

RSpec.describe TargetParam, type: :model do
  it 'has a valid factory' do
    expect(FactoryGirl.build_stubbed(:target_param)).to be_valid
  end

  it 'can be instantiated' do
    expect(FactoryGirl.build_stubbed(:target_param)).to be_an_instance_of(described_class)
  end
  #
  it 'is invalid with invalid data' do
    expect(FactoryGirl.build_stubbed(:target_param, name: nil)).to be_invalid
    expect(FactoryGirl.build_stubbed(:target_param, category: nil)).to be_invalid
    expect(FactoryGirl.build_stubbed(:target_param, possible_values: nil)).to be_invalid
  end
end


text:
<?xml version="1.0" ?><component loc="64:/opt/tinyos-release-tinyos-2_1_2//tos/system/StateImplC.nc" nicename="StateImplC" qname="StateImplC">
      <documentation loc="32:/opt/tinyos-release-tinyos-2_1_2//tos/types/State.h">
        <short>
 </short>
        <long>
 @author David Moss
</long>
      </documentation>
      <configuration/>
      <wiring>
        <wire loc="75:/opt/tinyos-release-tinyos-2_1_2//tos/system/StateImplC.nc">
          <from><interface-ref name="State" ref="0x2b61067ed280" scoped=""/></from>
          <to><interface-ref name="State" ref="0x2b61067e8b70" scoped=""/></to>
        </wire>
        <wire loc="74:/opt/tinyos-release-tinyos-2_1_2//tos/system/StateImplC.nc">
          <from><interface-ref name="SoftwareInit" ref="0x2b6105d641b0" scoped=""/></from>
          <to><interface-ref name="Init" ref="0x2b61067e8020" scoped=""/></to>
        </wire>
      </wiring>
    <specification><interface loc="66:/opt/tinyos-release-tinyos-2_1_2//tos/system/StateImplC.nc" name="State" provided="1" ref="0x2b61067ed280">
      <component-ref nicename="StateImplC" qname="StateImplC"/>
      <type-interface alignment="I:2" size="I:2"><interface-ref name="State" ref="0x2b61067ed280" scoped=""/></type-interface>
      <instance>
        <interfacedef-ref nicename="State" qname="State"/>
      </instance>
      <interface-parameters>
        <type-int alignment="I:1" cname="unsigned char" size="I:1" unsigned="">
          <typename><typedef-ref name="uint8_t" ref="0x2b6104f08160"/></typename>
        </type-int>
      </interface-parameters>
      <interface-functions>
        <function-ref name="getState" ref="0x2b61067ed600" scoped=""/>
        <function-ref name="toIdle" ref="0x2b61067ed790" scoped=""/>
        <function-ref name="isState" ref="0x2b61067ed920" scoped=""/>
        <function-ref name="isIdle" ref="0x2b61067edab0" scoped=""/>
        <function-ref name="requestState" ref="0x2b61067edc40" scoped=""/>
        <function-ref name="forceState" ref="0x2b61067eddd0" scoped=""/>
      </interface-functions>
    </interface></specification><referenced><interface loc="58:/opt/tinyos-release-tinyos-2_1_2//tos/system/MainC.nc" name="SoftwareInit" provided="0" ref="0x2b6105d641b0">
      <component-ref nicename="MainC" qname="MainC"/>
      <type-interface alignment="I:2" size="I:2"><interface-ref name="SoftwareInit" ref="0x2b6105d641b0" scoped=""/></type-interface>
      <instance>
        <interfacedef-ref nicename="Init" qname="Init"/>
      </instance>
      <interface-functions>
        <function-ref name="init" ref="0x2b6105d64530" scoped=""/>
      </interface-functions>
    </interface><interface loc="67:/opt/tinyos-release-tinyos-2_1_2//tos/system/StateImplP.nc" name="State" provided="1" ref="0x2b61067e8b70">
      <component-ref nicename="StateImplP" qname="StateImplP"/>
      <type-interface alignment="I:2" size="I:2"><interface-ref name="State" ref="0x2b61067e8b70" scoped=""/></type-interface>
      <instance>
        <interfacedef-ref nicename="State" qname="State"/>
      </instance>
      <interface-parameters>
        <type-int alignment="I:1" cname="unsigned char" size="I:1" unsigned="">
          <typename><typedef-ref name="uint8_t" ref="0x2b6104f08160"/></typename>
        </type-int>
      </interface-parameters>
      <interface-functions>
        <function-ref name="getState" ref="0x2b61067e7020" scoped=""/>
        <function-ref name="toIdle" ref="0x2b61067e71b0" scoped=""/>
        <function-ref name="isState" ref="0x2b61067e7340" scoped=""/>
        <function-ref name="isIdle" ref="0x2b61067e74d0" scoped=""/>
        <function-ref name="requestState" ref="0x2b61067e7660" scoped=""/>
        <function-ref name="forceState" ref="0x2b61067e77f0" scoped=""/>
      </interface-functions>
    </interface><interface loc="66:/opt/tinyos-release-tinyos-2_1_2//tos/system/StateImplP.nc" name="Init" provided="1" ref="0x2b61067e8020">
      <component-ref nicename="StateImplP" qname="StateImplP"/>
      <type-interface alignment="I:2" size="I:2"><interface-ref name="Init" ref="0x2b61067e8020" scoped=""/></type-interface>
      <instance>
        <interfacedef-ref nicename="Init" qname="Init"/>
      </instance>
      <interface-functions>
        <function-ref name="init" ref="0x2b61067e83a0" scoped=""/>
      </interface-functions>
    </interface><component loc="56:/opt/tinyos-release-tinyos-2_1_2//tos/system/MainC.nc" nicename="MainC" qname="MainC">
      <documentation loc="45:/opt/tinyos-release-tinyos-2_1_2//tos/system/MainC.nc">
        <short>
 MainC is the system interface the TinyOS boot sequence.</short>
        <long>
 MainC is the system interface the TinyOS boot sequence. It wires the
 boot sequence implementation to the scheduler and hardware resources.

 @author Philip Levis
 @date   August 6 2005
 @see    TEP 107: Boot Sequence
</long>
      </documentation>
      <configuration/>
      <wiring>
        <wire loc="72:/opt/tinyos-release-tinyos-2_1_2//tos/system/MainC.nc">
          <from><interface-ref name="Boot" ref="0x2b6105d69c20" scoped=""/></from>
          <to><interface-ref name="Boot" ref="0x2b6105f1a590" scoped=""/></to>
        </wire>
        <wire loc="67:/opt/tinyos-release-tinyos-2_1_2//tos/system/MainC.nc">
          <from><interface-ref name="Scheduler" ref="0x2b6105f1ac00" scoped=""/></from>
          <to><interface-ref name="Scheduler" ref="0x2b61058673a0" scoped=""/></to>
        </wire>
        <wire loc="68:/opt/tinyos-release-tinyos-2_1_2//tos/system/MainC.nc">
          <from><interface-ref name="PlatformInit" ref="0x2b6105f336c0" scoped=""/></from>
          <to><interface-ref name="Init" ref="0x2b6105d63190" scoped=""/></to>
        </wire>
        <wire loc="71:/opt/tinyos-release-tinyos-2_1_2//tos/system/MainC.nc">
          <from><interface-ref name="SoftwareInit" ref="0x2b6105f33dc0" scoped=""/></from>
          <to><interface-ref name="SoftwareInit" ref="0x2b6105d641b0" scoped=""/></to>
        </wire>
      </wiring>
    </component><component loc="64:/opt/tinyos-release-tinyos-2_1_2//tos/system/StateImplP.nc" nicename="StateImplP" qname="StateImplP" safe="">
      <documentation loc="32:/opt/tinyos-release-tinyos-2_1_2//tos/types/State.h">
        <short>
 </short>
        <long>
 @author David Moss
</long>
      </documentation>
      <module/>
    </component></referenced></component>


text:
/*
 *  Created on: November 12, 2012
 *      Author: Gil Mizrahi
 */

// --------------- Generic Int Functions ----------------
#include "gen_int.h"

// Swaps indexes i and j's values in array
void IntSwap(void* array, int i, int j)
{
	int temp = ((int*)array)[i];
	((int*)array)[i] = ((int*)array)[j];
	((int*)array)[j] = temp;
}
// compare 2 cells in array
int IntCompare(void* array, int i, int j)
{
	return (((int*)array)[i] <= ((int*)array)[j]);
}
// compare a cell in 1 array to a cell in another array
int IntCompare2(void* array1, void* array2, int i, int j)
{
	return (((int*)array1)[i] <= ((int*)array2)[j]);
}
// assign value from one array to another
void IntAssign(void* array1, void* array2, int i, int j)
{
	((int*)array1)[i] = ((int*)array2)[j];
}

// returns sizeof(int)
int IntSize(void)
{
	return sizeof(int);
}


text:
package main

import (
	"database/sql"
	"encoding/json"
	"os"

	_ "github.com/lib/pq"
)

// SeenAds is the type used to represent seen ad ids
type SeenAds map[string]bool

const filename = "./seen_ad_ids"

// ReadSeenAdIds returns a map of ad ids we've already seen.
// Not an array since Go doesn't have `contains` for arrays out the box 😬 😎
func ReadSeenAdIds() (SeenAds, error) {
	db, connectionError := sql.Open("postgres", os.Getenv("DATABASE_URL"))
	if connectionError != nil {
		return nil, connectionError
	}
	defer db.Close()

	var data []byte
	queryError := db.QueryRow("SELECT last_seen_ids FROM state").Scan(&data)
	if queryError != nil {
		return nil, queryError
	}

	var ids SeenAds
	jsonError := json.Unmarshal(data, &ids)

	if jsonError != nil {
		return nil, jsonError
	}
	return ids, nil
}

// WriteSeenAdIds writes the list of ids to Postgres.
func WriteSeenAdIds(seenAds SeenAds) error {
	json, jsonError := json.Marshal(seenAds)
	if jsonError != nil {
		return jsonError
	}

	db, connectionError := sql.Open("postgres", os.Getenv("DATABASE_URL"))
	if connectionError != nil {
		return connectionError
	}
	defer db.Close()

	_, deleteError := db.Exec("DELETE FROM state")
	if deleteError != nil {
		return deleteError
	}

	stmt, prepareError := db.Prepare("INSERT INTO state(last_seen_ids) VALUES($1)")
	if prepareError != nil {
		return prepareError
	}

	_, insertError := stmt.Exec(json)
	return insertError
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Tests the prototype Trust Token API's functionality through its Fetch interface.</title>
<link rel="help" href="https://github.com/WICG/trust-token-api#trust-token-redemption" />
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>

<script>
  'use strict';

  promise_test((t) => promise_rejects_dom(t, 'InvalidStateError', (() => {
      t.add_cleanup(async () => {
        if (window.testRunner)
          await new Promise(res => window.testRunner.clearTrustTokenState(res));
      });
      return fetch('https://trusttoken.test', {
        trustToken: {
          type: 'token-request'
        }
      });
    })(), 'Trust Token issuance should error.'),
    'No keys for the issuer -> expect issuance to fail');

  promise_test((t) => promise_rejects_dom(t, 'InvalidStateError', (() => {
      t.add_cleanup(async () => {
        if (window.testRunner)
          await new Promise(res => window.testRunner.clearTrustTokenState(res));
      });
      return fetch('https://trusttoken.test', {
        trustToken: {
          type: 'token-redemption'
        }
      });
    })(), 'Trust Token redemption should error.'),
    'No token for the issuer -> expect redemption to fail');

  promise_test((t) => promise_rejects_js(t, TypeError, (() => {
      t.add_cleanup(async () => {
        if (window.testRunner)
          await new Promise(res => window.testRunner.clearTrustTokenState(res));
      });
      return fetch('https://destination.test', {
        trustToken: {
          type: 'send-redemption-record',
          issuers: ['https://issuer.test']
        }
      });
    })(), 'Trust Token signing should not fail a request.'),
    'No RR for the issuer -> expect signing to fail, but an error while' +
    ' signing shouldn\'t result in the request being aborted');
</script>


text:
using System;

using UIKit;
using Demo.Core.ViewModels.Pay;
using Demo.iOS.Controls;
using MvvmCross.Binding.BindingContext;
using CoreGraphics;

namespace Demo.iOS.Views.Pay
{
    public partial class PayViewController : CommonViewController<PayViewModel>
    {
        private YaMoneyView _webView;

        public PayViewController()
        {
        }

        protected override void BindControls()
        {
            var set = this.CreateBindingSet<PayViewController, PayViewModel>();
            set.Bind(_webView).For("Text").To(vm => vm.HtmlText);
            set.Apply();

            _webView.Successed += ViewModel.PaymentSucceeded;
            _webView.Failed += ViewModel.PaymentFailed;
        }

        protected override void InitializeControls()
        {
            Title = "Оплата";

            _webView = new YaMoneyView () {
                Frame = new CoreGraphics.CGRect (0f, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height - 64f)
            };

            View.AddSubview (_webView);
        }
    }
}


text:
namespace bbv.Examples.SOLID._1_SRP.II_Solution
{
    using System;

    public class AreaCalculator
    {
        private readonly object[] shapes;

        public AreaCalculator(object[] shapes)
        {
            this.shapes = shapes;
        }

        public double Sum()
        {
            double result = 0;

            foreach (var shape in this.shapes)
            {
                if (shape is Circle)
                {
                    var circle = (Circle)shape;
                    result += circle.Radius * circle.Radius * Math.PI;
                }
                else if (shape is Square)
                {
                    var square = (Square)shape;
                    result += square.Length * square.Length;
                }
                else
                {
                    throw new InvalidOperationException("Unknown shape type for " + shape);
                }
            }

            return result;
        }
    }
}


text:
require 'test_helper'

class Kaui::SubscriptionsControllerTest < Kaui::FunctionalTestHelper

  test 'should handle Kill Bill errors in new screen' do
    bundle_id = SecureRandom.uuid.to_s
    get :new, :bundle_id => bundle_id, :account_id => @account.account_id, :product_category => 'ADD_ON'
    assert_redirected_to account_path(@account.account_id)
    assert_equal "Error while communicating with the Kill Bill server: Error 404: Object id=#{bundle_id} type=BUNDLE doesn't exist!", flash[:error]
  end

  test 'should get new page for base plan' do
    get :new,
        :account_id => @account.account_id,
        :product_category => 'BASE'
    assert assigns(:plans).size > 0
  end

  test 'should get new page for base addon' do
    get :new,
        :base_product_name => 'Sports',
        :bundle_id => @bundle.bundle_id,
        :account_id => @account.account_id,
        :product_category => 'ADD_ON'
    assert assigns(:plans).size > 0, 'Plans were not created'
  end

  test 'should handle errors during creation' do
    post :create,
         :subscription => {
             :bundle_id => @bundle.bundle_id,
             :account_id => @account.account_id,
             :product_category => 'ADD_ON'
         },
         :base_product_name => 'Sports'
    assert_redirected_to account_path(@account.account_id)
    assert_equal 'Required parameter missing: plan_name', flash[:error]

    post :create,
         :subscription => {
             :bundle_id => @bundle.bundle_id,
             :account_id => @account.account_id,
             :product_category => 'ADD_ON'
         },
         :base_product_name => 'Sports',
         :plan_name => 'not-exists'
    assert_template :new
    assert_equal 'Error while creating the subscription: Unable to find plan not-exists', flash[:error]
  end

  test 'should create a new base subscription' do
    post :create,
         :subscription => {
             :account_id => @account.account_id,
             :external_key => SecureRandom.uuid,
         },
         :plan_name => 'standard-monthly'
    assert_response 302
  end

  test 'should create a new addon subscription' do
    post :create,
         :subscription => {
             :bundle_id => @bundle.bundle_id,
             :account_id => @account.account_id,
             :product_category => 'ADD_ON'
         },
         :base_product_name => 'Sports',
         :plan_name => 'oilslick-monthly'
    assert_includes((200..399), response.code.to_i)
  end

  test 'should handle Kill Bill errors in edit screen' do
    subscription_id = SecureRandom.uuid.to_s
    get :edit, :id => subscription_id
    assert_redirected_to home_path
    assert_equal "Error while communicating with the Kill Bill server: Error 404: Object id=#{subscription_id} type=SUBSCRIPTION doesn't exist!", flash[:error]
  end

  test 'should get edit page' do
    get :edit, :id => @bundle.subscriptions.first.subscription_id
    assert_response 200
    assert_not_nil assigns(:subscription)
    assert_not_nil assigns(:plans)
    assert_not_nil assigns(:current_plan)
  end

  test 'should handle errors during update' do
    post :update, :id => @bundle.subscriptions.first.subscription_id
    assert_redirected_to home_path
    assert_equal 'Required parameter missing: plan_name', flash[:error]

    subscription_id = SecureRandom.uuid.to_s
    post :update, :id => subscription_id, :plan_name => 'super-monthly'
    assert_redirected_to home_path
    assert_equal "Error while communicating with the Kill Bill server: Error 404: Object id=#{subscription_id} type=SUBSCRIPTION doesn't exist!", flash[:error]

    post :update, :id => @bundle.subscriptions.first.subscription_id, :plan_name => 'not-exists'
    assert_redirected_to home_path
    assert_equal "Error while communicating with the Kill Bill server: Error 400: Could not find a plan matching spec: (plan: 'not-exists', product: 'undefined', billing period: 'undefined', pricelist 'undefined')", flash[:error]
  end

  test 'should update' do
    post :update,
         :id => @bundle.subscriptions.first.subscription_id,
         :plan_name => 'super-monthly'
    assert_response 302
  end

  test 'should handle errors during destroy' do
    subscription_id = SecureRandom.uuid.to_s
    delete :destroy, :id => subscription_id, :plan_name => 'super-monthly'
    assert_redirected_to home_path
    assert_equal "Error while communicating with the Kill Bill server: Error 404: Object id=#{subscription_id} type=SUBSCRIPTION doesn't exist!", flash[:error]
  end

  test 'should handle errors during reinstate' do
    subscription_id = SecureRandom.uuid.to_s
    put :reinstate, :id => subscription_id
    assert_redirected_to home_path
    assert_equal "Error while communicating with the Kill Bill server: Error 404: Object id=#{subscription_id} type=SUBSCRIPTION doesn't exist!", flash[:error]
  end

  test 'should cancel and reinstate subscription' do
    delete :destroy,
           :id => @bundle.subscriptions.first.subscription_id,
           :requested_date => (Date.today >> 1).to_time.utc.iso8601,
           :use_requested_date_for_billing => '1'
    assert_response 302

    put :reinstate, :id => @bundle.subscriptions.first.subscription_id
    assert_response 302
  end

  test 'should get show' do
    get :show, :id => @bundle.subscriptions.first.subscription_id
    assert_redirected_to account_bundles_path(@bundle.subscriptions.first.account_id)
  end

  test 'should get edit bcd' do
    get :edit_bcd, :id => @bundle.subscriptions.first.subscription_id
    assert_response :success
    assert_equal get_value_from_input_field('subscription_account_id'), @bundle.subscriptions.first.account_id
    assert_equal get_value_from_input_field('subscription_bill_cycle_day_local'), @bundle.subscriptions.first.bill_cycle_day_local.to_s
    assert_equal get_value_from_input_field('effective_from_date'), Date.parse(Time.now.to_s).to_s
  end

  test 'should update bcd' do
    bundle = create_bundle(@account, @tenant)
    parameters = {
        :id => bundle.subscriptions.first.subscription_id,
        :subscription => { :account_id => bundle.subscriptions.first.account_id,
                           :bill_cycle_day_local =>	bundle.subscriptions.first.bill_cycle_day_local
        },
        :effective_from_date => (Date.today >> 1).to_s
    }

    put :update_bcd, parameters
    assert_redirected_to account_bundles_path(bundle.subscriptions.first.account_id)
    assert_equal 'Subscription BCD was successfully changed', flash[:notice]
  end

  test 'should validate external key if found' do
    get :validate_external_key, :external_key => 'foo'
    assert_response :success
    assert_equal JSON[@response.body]['is_found'], false

    get :validate_external_key, :external_key => @bundle.subscriptions.first.external_key
    assert_response :success
    assert_equal JSON[@response.body]['is_found'], true
  end

end


text:
module Spree
  class StorePaymentMethod < ActiveRecord::Base
    belongs_to :store, inverse_of: :store_payment_methods
    belongs_to :payment_method, inverse_of: :store_payment_methods
  end
end


text:
from create_database_utils import *

os.mkdir('bin')
runSuccessfully(["javac", "Test.java", "-d", "bin"])
run_codeql_database_create(["kotlinc user.kt -cp bin"], lang="java")


text:
"""
Tools for working with dates and times in Excel files.

The conversion from ``days`` to ``(year, month, day)`` starts with
an integral "julian day number" aka JDN.
FWIW:

- JDN 0 corresponds to noon on Monday November 24 in Gregorian year -4713.

More importantly:

- Noon on Gregorian 1900-03-01 (day 61 in the 1900-based system) is JDN 2415080.0
- Noon on Gregorian 1904-01-02 (day  1 in the 1904-based system) is JDN 2416482.0

"""
import datetime

_JDN_delta = (2415080 - 61, 2416482 - 1)
assert _JDN_delta[1] - _JDN_delta[0] == 1462

# Pre-calculate the datetime epochs for efficiency.
epoch_1904 = datetime.datetime(1904, 1, 1)
epoch_1900 = datetime.datetime(1899, 12, 31)
epoch_1900_minus_1 = datetime.datetime(1899, 12, 30)

# This is equivalent to 10000-01-01:
_XLDAYS_TOO_LARGE = (2958466, 2958466 - 1462)

class XLDateError(ValueError):
    "A base class for all datetime-related errors."

class XLDateNegative(XLDateError):
    "``xldate < 0.00``"

class XLDateAmbiguous(XLDateError):
    "The 1900 leap-year problem ``(datemode == 0 and 1.0 <= xldate < 61.0)``"

class XLDateTooLarge(XLDateError):
    "Gregorian year 10000 or later"

class XLDateBadDatemode(XLDateError):
    "``datemode`` arg is neither 0 nor 1"

class XLDateBadTuple(XLDateError):
    pass

def xldate_as_tuple(xldate, datemode):
    """
    Convert an Excel number (presumed to represent a date, a datetime or a time) into
    a tuple suitable for feeding to datetime or mx.DateTime constructors.

    :param xldate: The Excel number
    :param datemode: 0: 1900-based, 1: 1904-based.
    :raises xlrd.xldate.XLDateNegative:
    :raises xlrd.xldate.XLDateAmbiguous:

    :raises xlrd.xldate.XLDateTooLarge:
    :raises xlrd.xldate.XLDateBadDatemode:
    :raises xlrd.xldate.XLDateError:
    :returns: Gregorian ``(year, month, day, hour, minute, nearest_second)``.

    .. warning::

      When using this function to interpret the contents of a workbook, you
      should pass in the :attr:`~xlrd.book.Book.datemode`
      attribute of that workbook. Whether the workbook has ever been anywhere
      near a Macintosh is irrelevant.

    .. admonition:: Special case

        If ``0.0 <= xldate < 1.0``, it is assumed to represent a time;
        ``(0, 0, 0, hour, minute, second)`` will be returned.

    .. note::

        ``1904-01-01`` is not regarded as a valid date in the ``datemode==1``
        system; its "serial number" is zero.
    """
    if datemode not in (0, 1):
        raise XLDateBadDatemode(datemode)
    if xldate == 0.00:
        return (0, 0, 0, 0, 0, 0)
    if xldate < 0.00:
        raise XLDateNegative(xldate)
    xldays = int(xldate)
    frac = xldate - xldays
    seconds = int(round(frac * 86400.0))
    assert 0 <= seconds <= 86400
    if seconds == 86400:
        hour = minute = second = 0
        xldays += 1
    else:
        # second = seconds % 60; minutes = seconds // 60
        minutes, second = divmod(seconds, 60)
        # minute = minutes % 60; hour    = minutes // 60
        hour, minute = divmod(minutes, 60)
    if xldays >= _XLDAYS_TOO_LARGE[datemode]:
        raise XLDateTooLarge(xldate)

    if xldays == 0:
        return (0, 0, 0, hour, minute, second)

    if xldays < 61 and datemode == 0:
        raise XLDateAmbiguous(xldate)

    jdn = xldays + _JDN_delta[datemode]
    yreg = ((((jdn * 4 + 274277) // 146097) * 3 // 4) + jdn + 1363) * 4 + 3
    mp = ((yreg % 1461) // 4) * 535 + 333
    d = ((mp % 16384) // 535) + 1
    # mp /= 16384
    mp >>= 14
    if mp >= 10:
        return ((yreg // 1461) - 4715, mp - 9, d, hour, minute, second)
    else:
        return ((yreg // 1461) - 4716, mp + 3, d, hour, minute, second)

def xldate_as_datetime(xldate, datemode):
    """
    Convert an Excel date/time number into a :class:`datetime.datetime` object.

    :param xldate: The Excel number
    :param datemode: 0: 1900-based, 1: 1904-based.

    :returns: A :class:`datetime.datetime` object.
    """

    # Set the epoch based on the 1900/1904 datemode.
    if datemode:
        epoch = epoch_1904
    else:
        if xldate < 60:
            epoch = epoch_1900
        else:
            # Workaround Excel 1900 leap year bug by adjusting the epoch.
            epoch = epoch_1900_minus_1

    # The integer part of the Excel date stores the number of days since
    # the epoch and the fractional part stores the percentage of the day.
    days = int(xldate)
    fraction = xldate - days

    # Get the the integer and decimal seconds in Excel's millisecond resolution.
    seconds = int(round(fraction * 86400000.0))
    seconds, milliseconds = divmod(seconds, 1000)

    return epoch + datetime.timedelta(days, seconds, 0, milliseconds)

# === conversions from date/time to xl numbers

def _leap(y):
    if y % 4: return 0
    if y % 100: return 1
    if y % 400: return 0
    return 1

_days_in_month = (None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

def xldate_from_date_tuple(date_tuple, datemode):
    """
    Convert a date tuple (year, month, day) to an Excel date.

    :param year: Gregorian year.
    :param month: ``1 <= month <= 12``
    :param day: ``1 <= day <= last day of that (year, month)``
    :param datemode: 0: 1900-based, 1: 1904-based.
    :raises xlrd.xldate.XLDateAmbiguous:
    :raises xlrd.xldate.XLDateBadDatemode:
    :raises xlrd.xldate.XLDateBadTuple:
      ``(year, month, day)`` is too early/late or has invalid component(s)
    :raises xlrd.xldate.XLDateError:
    """
    year, month, day = date_tuple

    if datemode not in (0, 1):
        raise XLDateBadDatemode(datemode)

    if year == 0 and month == 0 and day == 0:
        return 0.00

    if not (1900 <= year <= 9999):
        raise XLDateBadTuple("Invalid year: %r" % ((year, month, day),))
    if not (1 <= month <= 12):
        raise XLDateBadTuple("Invalid month: %r" % ((year, month, day),))
    if  (day < 1 or
         (day > _days_in_month[month] and not(day == 29 and month == 2 and _leap(year)))):
        raise XLDateBadTuple("Invalid day: %r" % ((year, month, day),))

    Yp = year + 4716
    M = month
    if M <= 2:
        Yp = Yp - 1
        Mp = M + 9
    else:
        Mp = M - 3
    jdn = (1461 * Yp // 4) + ((979 * Mp + 16) // 32) + \
        day - 1364 - (((Yp + 184) // 100) * 3 // 4)
    xldays = jdn - _JDN_delta[datemode]
    if xldays <= 0:
        raise XLDateBadTuple("Invalid (year, month, day): %r" % ((year, month, day),))
    if xldays < 61 and datemode == 0:
        raise XLDateAmbiguous("Before 1900-03-01: %r" % ((year, month, day),))
    return float(xldays)

def xldate_from_time_tuple(time_tuple):
    """
    Convert a time tuple ``(hour, minute, second)`` to an Excel "date" value
    (fraction of a day).

    :param hour: ``0 <= hour < 24``
    :param minute: ``0 <= minute < 60``
    :param second: ``0 <= second < 60``
    :raises xlrd.xldate.XLDateBadTuple: Out-of-range hour, minute, or second
    """
    hour, minute, second = time_tuple
    if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60:
        return ((second / 60.0 + minute) / 60.0 + hour) / 24.0
    raise XLDateBadTuple("Invalid (hour, minute, second): %r" % ((hour, minute, second),))

def xldate_from_datetime_tuple(datetime_tuple, datemode):
    """
    Convert a datetime tuple ``(year, month, day, hour, minute, second)`` to an
    Excel date value.
    For more details, refer to other xldate_from_*_tuple functions.

    :param datetime_tuple: ``(year, month, day, hour, minute, second)``
    :param datemode: 0: 1900-based, 1: 1904-based.
    """
    return (
        xldate_from_date_tuple(datetime_tuple[:3], datemode) +
        xldate_from_time_tuple(datetime_tuple[3:])
    )


text:
import './foo.css'
import bar from './bar.module.css'
import './nested'
import component from './component'

console.log(bar, component)


text:
package com.roncoo.pay.controller.common;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;

import com.roncoo.pay.common.core.dwz.DWZ;
import com.roncoo.pay.common.core.dwz.DwzAjax;
import com.roncoo.pay.permission.entity.PmsOperator;

/**
 * controller基类
 * 龙果学院:www.roncoo.com
 * @author zenghao
 */
public abstract class BaseController {

	/**
	 * 获取shiro 的session
	 *
	 * @return
	 */
	protected Session getSession() {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		return session;
	}

	/**
	 * 获取当前用户信息
	 *
	 * @return
	 */
	protected PmsOperator getPmsOperator() {
		PmsOperator operator = (PmsOperator) this.getSession().getAttribute("PmsOperator");
		return operator;
	}

	/**
	 * 响应DWZ的ajax失败请求,跳转到ajaxDone视图.
	 *
	 * @param message
	 *            提示消息.
	 * @param model
	 *            model.
	 * @return ajaxDone .
	 */
	protected String operateError(String message, Model model) {
		DwzAjax dwz = new DwzAjax();
		dwz.setStatusCode(DWZ.ERROR);
		dwz.setMessage(message);
		model.addAttribute("dwz", dwz);
		return "common/ajaxDone";
	}

	/**
	 * 响应DWZ的ajax失败成功,跳转到ajaxDone视图.
	 *
	 * @param model
	 *            model.
	 * @param dwz
	 *            页面传过来的dwz参数
	 * @return ajaxDone .
	 */
	protected String operateSuccess(Model model, DwzAjax dwz) {
		dwz.setStatusCode(DWZ.SUCCESS);
		dwz.setMessage("操作成功");
		model.addAttribute("dwz", dwz);
		return "common/ajaxDone";
	}

}


text:
package com.pedrogomez.renderers.ui.renderers;

import android.content.Context;
import com.pedrogomez.renderers.R;
import com.pedrogomez.renderers.model.Video;

/**
 * Favorite video renderer created to implement the presentation logic for videos. This
 * VideoRenderer subtype only
 * override renderLabel and renderMarker methods.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FavoriteVideoRenderer extends VideoRenderer {

  public FavoriteVideoRenderer(Context context) {
    super(context);
  }

  @Override protected void renderLabel() {
    String label = getContext().getString(R.string.favorite_label);
    getLabel().setText(label);
  }

  @Override protected void renderMarker(Video video) {
    getMarker().setImageResource(R.drawable.fav_active);
  }
}


text:
package ons

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// TagResource is a nested struct in ons response
type TagResource struct {
	ResourceType string `json:"ResourceType" xml:"ResourceType"`
	InstanceId   string `json:"InstanceId" xml:"InstanceId"`
	TagValue     string `json:"TagValue" xml:"TagValue"`
	ResourceId   string `json:"ResourceId" xml:"ResourceId"`
	TagKey       string `json:"TagKey" xml:"TagKey"`
}


text:
<?php

namespace Iodev\Whois\Modules\Asn;

use Iodev\Whois\DataObject;

/**
 * @property string $query
 * @property string $text
 * @property string $host
 * @property string $asn
 */
class AsnResponse extends DataObject
{
    use AsnResponseDeprected;

    /** @var string */
    protected $dataDefault = [
        'query' => '',
        'text' => '',
        'host' => '',
        'asn' => '',
    ];
}


text:
import {MoveEnnemies} from './move.js';
import {TirEnnemi} from './tirs.js';
import {SpawnAtome} from './spawn.js';

// SWITCH ENTRE VERTICAL ET HORIZONTAL
function update() {
	if (camera.rotation < Math.PI/2){
		camera.rotation += 0.01;
	}

	if (joueur.x >= 30 && joueur.y >= 30) {
		joueur.x-=3;
		joueur.y-=3;
		aze.style.display = "initial";
		setTimeout(function(){ aze.style.display = "none"; }, 3000);
		imgFond.src = './img/Fond_Veine2.png';
		imgFond2.src = './img/Fond_Veine2.png';
		fondy = 0;
		fondx = 0;
		ennemi = [];
		tirs = [];
		tirEnnemis = [];
	}
}

// CALCUL DU SCORE + AFFICHAGE
export function Scoring(){
	context.font = "bold 30px Verdana";
	context.textAlign = "end";
	var gradient=context.createLinearGradient(0,0,canvas.width,0);
	gradient.addColorStop("0","white");
	// Fill with gradient
	context.fillStyle=gradient;
	context.fillText(score,440,50);
	context.drawImage(text, 450, 10, 677/5, 246/5);
	if (game == "horizontal") {
		context.fillText("Vous avez "+nbAtome+" atome(s)",440,750);
	}
}

// CHANGEMENT DU MODE DE JEU
export function changeGame(){
	window.game = "horizontal";
	update();
}

// NETTOYAGE DU TERRAIN QUAND LE BOSS APPARAIT
export function Nettoyage(){
	if (boss === false) {
		MoveEnnemies();
		TirEnnemi();
		SpawnAtome();
	}
}

export function alpha(){
	context.globalAlpha = 1;
}


text:
WordPress Packagist by WordPress Sweden
===

> This is a fork of [WPackagist.org](https://github.com/outlandishideas/wpackagist) that aims to provide an up-to-date and highly available alternative and to contribute patches upstream. Feel free to use our repository by changing your repository URL in `composer.json` to https://wpackagist.wpsv.se/

This is the repository for [wpackagist.wpsv.se](https://wpackagist.wpsv.se/) which allows WordPress plugins and themes to be
managed along with other dependencies using [Composer](https://getcomposer.org).

More info and usage instructions at [wpackagist.wpsv.se](https://wpackagist.wpsv.se/) or follow us on
Twitter [@WPSverige](https://twitter.com/wpackagist).

For support and discussion, please use the issue tracker above.

## Usage

Example composer.json:

```json
{
    "name": "acme/brilliant-wordpress-site",
    "description": "My brilliant WordPress site",
    "repositories":[
        {
            "type":"composer",
            "url":"https://wpackagist.wpsv.se/"
        }
    ],
    "require": {
        "aws/aws-sdk-php":"*",
        "wpackagist-plugin/akismet":"dev-trunk",
        "wpackagist-plugin/wordpress-seo":">=7.0.2",
        "wpackagist-theme/hueman":"*"
    },
    "autoload": {
        "psr-0": {
            "Acme": "src/"
        }
    }
}
```

## WordPress core

This does not provide WordPress itself.

See https://github.com/fancyguy/webroot-installer or https://github.com/johnpbloch/wordpress.

## How it works

WPackagist implements the `wordpress-plugin` and `wordpress-theme` Composer Installers (https://github.com/composer/installers).

It essentially provides a lookup table from plugin name to WordPress.org SVN repository. Plugin versions correspond to different tags in their repository, with the special `dev-master` version being mapped to `trunk`.

The lookup table is provided as many static JSON files. The entry point to these files can be found at https://wpackagist.org/packages.json. Each plugin and theme has its own JSON file detailing its versions; these can be found in https://wpackagist.org/p/wpackagist-plugin/ and https://wpackagist.org/p/wpackagist-theme/.

## Running Wpackagist

### Installing

1. Make sure you have PDO with sqlite support enabled.
2. Make sure [`data`](data/) is writable. Do NOT create `data/packages.sqlite`, it will be created automatically.
3. Run `composer install`.
4. Point your Web server to [`web`](web/). A [`.htaccess`](web/.htaccess) is provided for Apache.

### Updating the database

The first database fetch may easily take 30-60 minutes, be patient.

1. `bin/cmd refresh`: Query the WordPress.org SVN in order to find new and updated packages.
2. `bin/cmd update`: Update the version information for packages identified in `1`. Uses the WordPress.org API.
3. `bin/cmd build`: Rebuild all `.json` files in `web/`.

### CRON job

The CRON job runs the three commands above. We recommend fetching new packages every 30 minutes. Add this to your crontab to set that up:

```
0,30 * * * * cd /var/www/your-wpackagist-location && ./run-cron.sh >> /var/log/wpackagist-update.log
```


text:
<?php

namespace Tmdb\Tests\Factory;

use Tmdb\Factory\TvFactory;
use Tmdb\Model\Tv;

class TvFactoryTest extends TestCase
{
    /**
     * @var Tv
     */
    private $tv;

    public function setUp()
    {
        /**
         * @var TvFactory $factory
         */
        $factory = $this->getFactory();
        $data    = $this->loadByFile('tv/all.json');

        $data['overview'] = 'external';

        /**
         * @var Tv $this->tv
         */
        $this->tv = $factory->create($data);
    }

    /**
     * @test
     */
    public function shouldConstructTv()
    {
        $this->setUp();

        $this->assertInstanceOf('Tmdb\Model\Tv', $this->tv);

        $this->assertInstanceOf('\DateTime', $this->tv->getLastAirDate());
        $this->assertInstanceOf('Tmdb\Model\Image\BackdropImage', $this->tv->getBackdropImage());
        $this->assertInstanceOf('Tmdb\Model\Collection\Genres', $this->tv->getGenres());
        $this->assertInstanceOf('Tmdb\Model\Image\PosterImage', $this->tv->getPosterImage());
    }

    /**
     * @test
     */
    public function shouldBeAbleToSetFactories()
    {
        $this->setUp();

        $factory = new TvFactory();
        $class  = new \stdClass();

        $factory->setCastFactory($class);
        $factory->setCrewFactory($class);
        $factory->setGenreFactory($class);
        $factory->setImageFactory($class);
        $factory->setTvSeasonFactory($class);

        $this->assertInstanceOf('stdClass', $factory->getCastFactory());
        $this->assertInstanceOf('stdClass', $factory->getCrewFactory());
        $this->assertInstanceOf('stdClass', $factory->getGenreFactory());
        $this->assertInstanceOf('stdClass', $factory->getImageFactory());
        $this->assertInstanceOf('stdClass', $factory->getTvSeasonFactory());

        $model = new Tv();
        $model->setCredits($class);

        $this->assertInstanceOf('stdClass', $model->getCredits());
    }

    /**
     * @test
     * @todo see comments
     */
    public function shouldBeFunctional()
    {
        $this->setUp();

        $this->assertEquals('/sIJyCJedGlZf1TId41gCtkblBGo.jpg', $this->tv->getBackdropPath());
        // created by
        $this->assertEquals(2, count($this->tv->getEpisodeRunTime()));
        $this->assertEquals(new \DateTime('2008-01-19'), $this->tv->getFirstAirDate());
        // genres
        $this->assertEquals('http://www.amctv.com/shows/breaking-bad', $this->tv->getHomepage());
        $this->assertEquals(1396, $this->tv->getId());
        $this->assertEquals(false, $this->tv->getInProduction());
        // languages
        $this->assertEquals(new \DateTime('2013-09-29'), $this->tv->getLastAirDate());
        $this->assertEquals('Breaking Bad', $this->tv->getName());
        // networks
        $this->assertEquals(62, $this->tv->getNumberOfEpisodes());
        $this->assertEquals(5, $this->tv->getNumberOfSeasons());
        $this->assertEquals('Breaking Bad', $this->tv->getOriginalName());
        // origin_country
        $this->assertEquals('external', $this->tv->getOverview());
        $this->assertEquals(8.14745667435, $this->tv->getPopularity());
        $this->assertEquals('/iRDNn9EHKuBhGa77UBteazvsZa1.jpg', $this->tv->getPosterPath());
        // seasons
        $this->assertEquals('Ended', $this->tv->getStatus());
        $this->assertEquals(8.9, $this->tv->getVoteAverage());
        $this->assertEquals(37, $this->tv->getVoteCount());
        // credits
        // external_ids
        // images
        // translations
    }

    /**
     * @test
     */
    public function shouldBeAbleToDissectResults()
    {
        $factory = $this->getFactory();

        $data = array('results' => array(
            array('id' => 1),
            array('id' => 2),
        ));

        $collection = $factory->createCollection($data);

        $this->assertEquals(2, count($collection));
    }

    protected function getFactoryClass()
    {
        return 'Tmdb\Factory\TvFactory';
    }
}


text:
using System.Diagnostics.CodeAnalysis;
using TM.Shared;

namespace TM.Data
{
   [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")]
   [SuppressMessage("ReSharper", "ClassWithVirtualMembersNeverInherited.Global")]
   public class CourseSpecialization
   {
      public int CourseId { get; set; }
      public Specializations Specialization { get; set; }

      public static CourseSpecialization Create(Course course, Specializations specialization)
      {
         return new CourseSpecialization
         {
            CourseId = course.Id,
            Course = course,
            Specialization = specialization
         };
      }

      public virtual Course Course { get; set; }
   }
}


text:
import { Action } from "../preferences-model";

const SWITCH_THEME = "SWITCH_THEME";

export interface ThemeAction extends Action<"SWITCH_THEME", "light" | "dark"> {}

export { SWITCH_THEME };


text:
This gem provides a client and a server middlewares for Sidekiq to work with the tenantify gem

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'tenantify-sidekiq'
```

And then execute:

    $ bundle

## Usage

Just add the client and the server middlewares to its respective middleware chains:

```ruby
require 'tenantify-sidekiq'

Sidekiq.configure_client do |config|
  config.client_middleware do |chain|
    chain.add Tenantify::Sidekiq::Middlewares::Client
  end
end

Sidekiq.configure_server do |config|
  config.server_middleware do |chain|
    chain.add Tenantify::Sidekiq::Middlewares::Server
  end
end
```

## Contributing

1. Fork it ( https://github.com/[my-github-username]/tenantify-sidekiq/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif

.PHONY: $(BUILD) clean all

all: nat_patch.bin agb_patch.bin twl_patch.bin

nat_patch.bin:
	@cd native_firm && make
	@cp native_firm/patch.bin $@

agb_patch.bin:
	@cd agb_firm && make
	@cp agb_firm/patch.bin $@

twl_patch.bin:
	@cd twl_firm && make
	@cp twl_firm/patch.bin $@

clean:
	@echo clean ...
	@cd native_firm && make clean
	@cd agb_firm && make clean
	@cd twl_firm && make clean
	@rm -fr $(BUILD) *.bin


text: package fake_handlers // import "code.cloudfoundry.org/diego-ssh/handlers/fake_handlers"


text:
package org.libj.xquery.xml;

public class NoXMLFactory implements XMLFactory {
    public XML toXML(String xml) {
        return new NoXML(xml);
    }

    public void registerNamespace(String prefix, String namespace) {
        throw new UnsupportedOperationException("registerNamespace");
    }
}


text:
angular.
    module('example', ['angular-bacon']).
    controller('form', function($scope) {
        $scope.username = ''

        var longerThan = function(num) {
            return function(it) {
                return it && it.length > num;
            }
        }
        var longerThanOrEqual = function(num) {
            return function(it) {
                return it && it.length >= num;
            }
        }
        var shorterThan = function (num) {
            return function (it) {
                return typeof it === "string" && it.length < num;
            }
        }
        var identity = function(it) {
            return it;
        }
        var passwordInput = $scope
                .$watchAsProperty('password')

        var passwordsEqual = passwordInput
                .combine(
                    $scope.$watchAsProperty('passwordConfirm'),
                    function(pass, confirm) {
                        return {
                            password: pass,
                            confirm: confirm
                        }
                    }
                )
                .map(function(it) {
                    return it.password === it.confirm
                })
                .toProperty()

        var usernameInput = $scope
                .$watchAsProperty('username')

        var passwordIsValid = passwordInput
                .map(longerThanOrEqual(5))

        var usernameIsFree = usernameInput
                .changes()
                .filter(longerThan(2))
                .flatMapLatest(function(it) { return Bacon.later(2000, it === "user"); })
                .merge(usernameInput.map(false).changes())
                .toProperty(false)

        usernameIsFree
            .and(passwordIsValid)
            .and(passwordsEqual)
            .digest($scope, 'formValid')

        usernameIsFree
            .changes()
            .filter(identity)
            .map(Bacon.constant("free"))
            .merge(usernameIsFree.changes().not().filter(identity).map(Bacon.constant("taken")))
            .merge(usernameInput.map(Bacon.constant("loading")).changes())
            .merge(
                usernameInput
                    .filter(shorterThan(2))
                    .map(Bacon.constant("empty"))
                    .changes()
                )
            .digest($scope, 'usernameState')

        passwordIsValid
            .changes()
            .not()
            .digest($scope, 'passwordInvalid')

        passwordsEqual
            .changes()
            .not()
            .digest($scope, 'passwordsDontMatch')

    })


text:
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/gotye_btn_to_text_normal" android:state_pressed="false"/>
    <item android:drawable="@drawable/gotye_btn_to_text_pressed" android:state_pressed="true" />
</selector>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zadacha_04
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal lectures = decimal.Parse(Console.ReadLine());
            decimal budget = decimal.Parse(Console.ReadLine());

            decimal money = budget / lectures;

            int Jelev = 0;
            int RoYaL = 0;
            int Roli = 0;
            int Trofon = 0;
            int Sino = 0;
            int Guest = 0;

            for (int cycle = 0; cycle < lectures; cycle++)
            {
                string person = Console.ReadLine();

                if (person == "Jelev")
                {
                    Jelev++;
                }
                else if (person == "RoYaL")
                {
                    RoYaL++;
                }
                else if (person == "Roli")
                {
                    Roli++;
                }
                else if (person == "Trofon")
                {
                    Trofon++;
                }
                else if (person == "Sino")
                {
                    Sino++;
                }
                else
                {
                    Guest++;
                }
            }

            Console.WriteLine("Jelev salary: {0:f2} lv", Jelev * money);
            Console.WriteLine("RoYaL salary: {0:f2} lv", RoYaL * money);
            Console.WriteLine("Roli salary: {0:f2} lv", Roli * money);
            Console.WriteLine("Trofon salary: {0:f2} lv", Trofon * money);
            Console.WriteLine("Sino salary: {0:f2} lv", Sino * money);
            Console.WriteLine("Others salary: {0:f2} lv", Guest * money);

        }
    }
}


text:
'use strict';

define([
    'states/BaseState',
    'states/Menu',
    'states/Fight',
    'states/Inventory',
    'states/Friendlist',
    'states/Connect',
    'states/NoConnection',
    'states/RoboConfig'

], function(BaseState, Menu, Fight, Inventory, Friendlist, Connect, NoConnection,RoboConfig){

    function Boot(){
        BaseState.call(this);
        this.busy = true;
    }

    Boot.prototype = Object.create(BaseState.prototype);
    Boot.prototype.constructor = Boot;

    Boot.prototype.preload = function(){
        this.app.loadRoboParts();
        this.load.spritesheet('progressbar','assets/spritesheets/progress__bar.png',120,40);
        this.load.spritesheet('buttonOK','assets/spritesheets/OK.png',84,40);
        this.load.spritesheet('buttonCancel','assets/spritesheets/nein.png',84,40);
        this.load.spritesheet('buttonCancel2','assets/spritesheets/abbruch.png',84,40);
        this.load.spritesheet('buttonBattle','assets/spritesheets/battle.png',30,30);
        this.load.spritesheet('buttonDelete','assets/spritesheets/bucket.png',30,30);
    };

    Boot.prototype.init = function(){
        BaseState.prototype.init.call(this);

        console.log(this.app);
        this.app.canvas = document.getElementsByTagName('canvas')[0];
        this.app.game.scale.scaleMode = Phaser.ScaleManager.NO_SCALE;
        this.app.game.scale.pageAlignVertically = true;
        this.app.game.scale.pageAlignHorizontally = true;

        if(this.app.game.context != null){
            Phaser.Canvas.setSmoothingEnabled(this.game.context, false);
        }

        Phaser.Canvas.setImageRenderingCrisp(this.app.game.canvas);
        PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST;
        document.body.style.height = this.app.height + 'px';

        console.log(this);
    };

    Boot.prototype.create = function(){
        this.app.game.state.add('Connect', Connect);
        this.app.game.state.add('NoConnection', NoConnection);
        this.app.game.state.add('Menu', Menu);
        this.app.game.state.add('Fight', Fight);
        this.app.game.state.add('Inventory', Inventory);
        this.app.game.state.add('Friendlist', Friendlist);
        this.app.game.state.add('RoboConfig', RoboConfig);

        this.app.game.state.start('Connect');
    };

    return new Boot();
});


text:
package com.mongodb.async.client;

import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.annotations.Immutable;
import com.mongodb.annotations.NotThreadSafe;
import com.mongodb.connection.ClusterSettings;
import com.mongodb.connection.ConnectionPoolSettings;
import com.mongodb.connection.SslSettings;
import com.mongodb.connection.ServerSettings;
import com.mongodb.connection.SocketSettings;
import org.bson.codecs.configuration.CodecRegistry;

import java.util.Collections;
import java.util.List;

import static com.mongodb.assertions.Assertions.notNull;

/**
 * Various settings to control the behavior of a {@code MongoClient}.
 *
 * @since 3.0
 */
@Immutable
public final class MongoClientSettings {
    private final ReadPreference readPreference;
    private final WriteConcern writeConcern;
    private final List<MongoCredential> credentialList;

    private final CodecRegistry codecRegistry;

    private final ClusterSettings clusterSettings;
    private final SocketSettings socketSettings;
    private final SocketSettings heartbeatSocketSettings;
    private final ConnectionPoolSettings connectionPoolSettings;
    private final ServerSettings serverSettings;
    private final SslSettings sslSettings;

    /**
     * Convenience method to create a Builder.
     *
     * @return a builder
     */
    public static Builder builder() {
        return new Builder();
    }

    /**
     * Convenience method to create a from an existing {@code MongoClientSettings}.
     *
     * @param settings create a builder from existing settings
     * @return a builder
     */
    public static Builder builder(final MongoClientSettings settings) {
        return new Builder(settings);
    }

    /**
     * A builder for {@code MongoClientSettings} so that {@code MongoClientSettings} can be immutable, and to support easier construction
     * through chaining.
     */
    @NotThreadSafe
    public static final class Builder {
        private ReadPreference readPreference = ReadPreference.primary();
        private WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED;
        private CodecRegistry codecRegistry = MongoClients.getDefaultCodecRegistry();

        private ClusterSettings clusterSettings;
        private SocketSettings socketSettings = SocketSettings.builder().build();
        private SocketSettings heartbeatSocketSettings = SocketSettings.builder().build();
        private ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings.builder()
                                                                                .maxSize(100)
                                                                                .maxWaitQueueSize(500)
                                                                                .build();
        private ServerSettings serverSettings = ServerSettings.builder().build();
        private SslSettings sslSettings = SslSettings.builder().build();
        private List<MongoCredential> credentialList = Collections.emptyList();

        private Builder() {
        }

        /**
         * Creates a Builder from an existing {@code MongoClientSettings}.
         *
         * @param settings create a builder from existing settings
         */
        private Builder(final MongoClientSettings settings) {
            readPreference = settings.getReadPreference();
            writeConcern = settings.getWriteConcern();
            credentialList = settings.getCredentialList();
            codecRegistry = settings.getCodecRegistry();
            clusterSettings = settings.getClusterSettings();
            serverSettings = settings.getServerSettings();
            socketSettings = settings.getSocketSettings();
            heartbeatSocketSettings = settings.getHeartbeatSocketSettings();
            connectionPoolSettings = settings.getConnectionPoolSettings();
            sslSettings = settings.getSslSettings();
        }

        /**
         * Sets the cluster settings.
         *
         * @param clusterSettings the cluster settings
         * @return {@code this}
         * @see MongoClientSettings#getClusterSettings()
         */
        public Builder clusterSettings(final ClusterSettings clusterSettings) {
            this.clusterSettings = notNull("clusterSettings", clusterSettings);
            return this;
        }

        /**
         * Sets the socket settings.
         *
         * @param socketSettings the socket settings
         * @return {@code this}
         * @see MongoClientSettings#getSocketSettings()
         */
        public Builder socketSettings(final SocketSettings socketSettings) {
            this.socketSettings = notNull("socketSettings", socketSettings);
            return this;
        }

        /**
         * Sets the heartbeat socket settings.
         *
         * @param heartbeatSocketSettings the socket settings
         * @return {@code this}
         * @see MongoClientSettings#getHeartbeatSocketSettings()
         */
        public Builder heartbeatSocketSettings(final SocketSettings heartbeatSocketSettings) {
            this.heartbeatSocketSettings = notNull("heartbeatSocketSettings", heartbeatSocketSettings);
            return this;
        }

        /**
         * Sets the connection pool settings.
         *
         * @param connectionPoolSettings the connection settings
         * @return {@code this}
         * @see MongoClientSettings#getConnectionPoolSettings() ()
         */
        public Builder connectionPoolSettings(final ConnectionPoolSettings connectionPoolSettings) {
            this.connectionPoolSettings = notNull("connectionPoolSettings", connectionPoolSettings);
            return this;
        }

        /**
         * Sets the server settings.
         *
         * @param serverSettings the server settings
         * @return {@code this}
         * @see MongoClientSettings#getServerSettings() ()
         */
        public Builder serverSettings(final ServerSettings serverSettings) {
            this.serverSettings = notNull("serverSettings", serverSettings);
            return this;
        }

        /**
         * Sets the socket settings.
         *
         * @param sslSettings the SSL settings
         * @return {@code this}
         * @see MongoClientSettings#getSslSettings() ()
         */
        public Builder sslSettings(final SslSettings sslSettings) {
            this.sslSettings = notNull("sslSettings", sslSettings);
            return this;
        }

        /**
         * Sets the read preference.
         *
         * @param readPreference read preference
         * @return {@code this}
         * @see MongoClientSettings#getReadPreference()
         */
        public Builder readPreference(final ReadPreference readPreference) {
            this.readPreference = notNull("readPreference", readPreference);
            return this;
        }

        /**
         * Sets the write concern.
         *
         * @param writeConcern the write concern
         * @return {@code this}
         * @see MongoClientSettings#getWriteConcern()
         */
        public Builder writeConcern(final WriteConcern writeConcern) {
            this.writeConcern = notNull("writeConcern", writeConcern);
            return this;
        }

        /**
         * Sets the credential list.
         *
         * @param credentialList the credential list
         * @return {@code this}
         * @see MongoClientSettings#getCredentialList()
         */
        public Builder credentialList(final List<MongoCredential> credentialList) {
            this.credentialList = Collections.unmodifiableList(notNull("credentialList", credentialList));
            return this;
        }

        /**
         * Sets the codec registry
         *
         * @param codecRegistry the codec registry
         * @return {@code this}
         * @see MongoClientSettings#getCodecRegistry()
         * @since 3.0
         */
        public Builder codecRegistry(final CodecRegistry codecRegistry) {
            this.codecRegistry = notNull("codecRegistry", codecRegistry);
            return this;
        }

        /**
         * Build an instance of {@code MongoClientSettings}.
         *
         * @return the settings from this builder
         */
        public MongoClientSettings build() {
            return new MongoClientSettings(this);
        }
    }

    /**
     * The read preference to use for queries, map-reduce, aggregation, and count.
     *
     *
Default is {@code ReadPreference.primary()}.

     *
     * @return the read preference
     * @see com.mongodb.ReadPreference#primary()
     */
    public ReadPreference getReadPreference() {
        return readPreference;
    }

    /**
     * Gets the credential list.
     *
     * @return the credential list
     */
    public List<MongoCredential> getCredentialList() {
        return credentialList;
    }

    /**
     * The write concern to use.
     *
     *
Default is {@code WriteConcern.ACKNOWLEDGED}.

     *
     * @return the write concern
     * @see com.mongodb.WriteConcern#ACKNOWLEDGED
     */
    public WriteConcern getWriteConcern() {
        return writeConcern;
    }

    /**
     * The codec registry to use.  By default, a {@code MongoClient} will be able to encode and decode instances of {@code
     * Document}.
     *
     * @return the codec registry
     * @see MongoClient#getDatabase
     * @since 3.0
     */
    public CodecRegistry getCodecRegistry() {
        return codecRegistry;
    }

    /**
     * Gets the cluster settings.
     *
     * @return the cluster settings
     */
    public ClusterSettings getClusterSettings() {
        return clusterSettings;
    }

    /**
     * Gets the SSL settings.
     *
     * @return the SSL settings
     */
    public SslSettings getSslSettings() {
        return sslSettings;
    }

    /**
     * Gets the connection-specific settings wrapped in a settings object.   This settings object uses the values for connectTimeout,
     * socketTimeout and socketKeepAlive.
     *
     * @return a SocketSettings object populated with the connection settings from this {@code MongoClientSettings} instance.
     * @see com.mongodb.connection.SocketSettings
     */
    public SocketSettings getSocketSettings() {
        return socketSettings;
    }

    /**
     * Gets the connection settings for the heartbeat thread (the background task that checks the state of the cluster) wrapped in a
     * settings object. This settings object uses the values for heartbeatConnectTimeout, heartbeatSocketTimeout and socketKeepAlive.
     *
     * @return a SocketSettings object populated with the heartbeat connection settings from this {@code MongoClientSettings} instance.
     * @see com.mongodb.connection.SocketSettings
     */
    public SocketSettings getHeartbeatSocketSettings() {
        return heartbeatSocketSettings;
    }

    /**
     * Gets the settings for the connection provider in a settings object.  This settings object wraps the values for minConnectionPoolSize,
     * maxConnectionPoolSize, maxWaitTime, maxConnectionIdleTime and maxConnectionLifeTime, and uses maxConnectionPoolSize and
     * threadsAllowedToBlockForConnectionMultiplier to calculate maxWaitQueueSize.
     *
     * @return a ConnectionPoolSettings populated with the settings from this {@code MongoClientSettings} instance that relate to the
     * connection provider.
     * @see com.mongodb.connection.ConnectionPoolSettings
     */
    public ConnectionPoolSettings getConnectionPoolSettings() {
        return connectionPoolSettings;
    }

    /**
     * Gets the server-specific settings wrapped in a settings object.  This settings object uses the heartbeatFrequency and
     * minHeartbeatFrequency values from this {@code MongoClientSettings} instance.
     *
     * @return a ServerSettings
     * @see com.mongodb.connection.ServerSettings
     */
    public ServerSettings getServerSettings() {
        return serverSettings;
    }

    private MongoClientSettings(final Builder builder) {
        readPreference = builder.readPreference;
        writeConcern = builder.writeConcern;
        credentialList = builder.credentialList;
        codecRegistry = builder.codecRegistry;
        clusterSettings = builder.clusterSettings;
        serverSettings = builder.serverSettings;
        socketSettings = builder.socketSettings;
        heartbeatSocketSettings = builder.heartbeatSocketSettings;
        connectionPoolSettings = builder.connectionPoolSettings;
        sslSettings = builder.sslSettings;
    }
}