text:
/*
* = require rhinoart/base
* = require rhinoart/core
* = require rhinoart/app
*/


text:
title: About me
layout: default
description: >
    Hi, I'm Benji. I like programming and playing piano.
image:
    src: /assets/retrato-1-1.jpeg
    alt: Benji
scripts:
    - async: true
      src: "https://platform.twitter.com/widgets.js"
    - async: true
      src: "/scripts/audio-player.js"
afterHead: >

---

# Hi, I'm Benji.
I like programming and playing piano. I should probably be studying.

Projects

Some projects I've worked on.

    {% include scroller.html %}

## About me

Hi, I'm Benji. You might know me as [@MindfulMinun][twitter] online. I graduated from both [Legacy ECHS](https://lechs.taylorisd.org) and [Temple College](https://templejc.edu) late this spring with my HS diploma and an Associate of Arts respectively. I'm currently a first-year sophomore at [UT Dallas](https://utdallas.edu), majoring in Computer Science. I like to write code and play the piano.

{% include image.html
    caption="This is what I look like."
    id="pfp" class="small"
    suppressLink="true"
    src="/assets/retrato-1-1.jpeg"
    style="padding-top: 100%; background: #759b86; background: radial-gradient(#a06642, #306bad);" %}

In my leisure time, I like to [write code][github], [tweet tweets][twitter], and play piano and Smash. I can solve a Rubik's cube under 2 minutes, and I speak both English and Spanish fluently.

        <xyz-player
            srcset="
                https://benjic.xyz/assets/goodbye/goodbye.webm video/webm,
                https://benjic.xyz/assets/goodbye/goodbye.mp4 video/mp4"
        ></xyz-player>

JavaScript must be enabled to play this video

An excerpt of Don't Ever Forget.

        <audio>
            <source src="/assets/goodbye/Don't_Ever_Forget--Musescore-2018-11-23.ogg" type="audio/ogg">
            <source src="/assets/goodbye/Don't_Ever_Forget--Musescore-2018-11-23.mp3" type="audio/mpeg">
        </audio>

            Don't Ever Forget — Arata Iiyoshi

                    View in Musescore
                    open_in_new

                    .mp3
                    get_app

                    .ogg
                    get_app

JavaScript must be enabled to play audio.

## Code & stuff

I love to code. It's my dream to write code for a living. I picked up JavaScript during my freshman year of high school while messing around with Firefox Scratchpad. I naturally went on to learn the other two web languages: HTML and CSS. I'm now fluent in front-end workflow, combining technologies ranging from ServiceWorker, Jekyll, Vue, GitHub, Netlify, Heroku, you name it.

The [video](https://github.com/MindfulMinun/xyz-custom-elements) and [audio](https://codepen.io/MindfulMinun/pen/vRjPwP) players above were both created by yours truly. I've also made [layouts][layout] and other [HTML things][projects].

Near the end of my Sophomore year, I went on to focus on Node.js, a back-end JavaScript runtime. Here, I picked up CoffeeScript, a Python-esque language that transpiles to JavaScript. With these, I created [Haruka][haruka], a Discord bot.

Last summer, I've worked some more with Node.js and created [@NichijouEbooks][NichijouEbooks], a Twitter bot that posts randomly-formulated strings from quotes taken from the Nichijou anime. [Her repository is also on GitHub.](https://github.com/MindfulMinun/nichijouebooks)

## Contact

You can find me all over the Internet as MindfulMinun, I can [prove it][keybase]. For business inquiries, [send me an email](mailto:benji@utdallas.edu). For pretty much anything else, get it touch with me via [Twitter][twitter] or Discord (MindfulMinun#3386). I'm also on [GitHub][github], [CodePen][codepen], [Glitch][glitch], [Keybase][keybase], [Mastodon][mastodon], and many other places. Feel free to say hi.

[Tweet to @MindfulMinun][twitter-intent]

[twitter]: https://twitter.com/MindfulMinun

[twitter-intent]: https://twitter.com/intent/tweet?screen_name=MindfulMinun&ref_src=twsrc%5Etfw "Tweet to @MindfulMinun"
{: class="twitter-mention-button" data-size="large" data-show-count="true" }

[haruka]: https://github.com/MindfulMinun/discord-haruka
[NichijouEbooks]: https://twitter.com/NichijouEbooks
[github]: https://github.com/MindfulMinun
{: rel="me" }
[codepen]: https://codepen.io/MindfulMinun
[glitch]: https://glitch.com/@MindfulMinun
{: rel="me" }
[keybase]: https://keybase.io/mindfulminun
{: rel="me" }
[mastodon]: https://mastodon.social/@mindfulminun
{: rel="me" }
[projects]: /p/
[layout]: /p/default/

redpajama_set_name: RedPajamaGithub


text:
package mmap

// Sync flushes all changes to the map out to the backing file.
func (m *Map) Sync(wait bool) error {
	if !m.write {
		return errors.New("cannot sync read-only map").Set("name", m.name)
	}

	m.Lock()
	defer m.Unlock()

	err := m.sync(wait)
	if err != nil {
		return errors.Wrap(err, "error syncing map").Set("name", m.name)
	}

	return nil
}

// sync assumes the map is locked and writeable.
func (m *Map) sync(wait bool) error {
	if m.data == nil {
		return errors.New("mmap closed")
	}
	return msync(m.data, wait)
}


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

    <application
        android:allowBackup="true"
        android:icon="@drawable/league_icon"
        android:label="LoLQuizz"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activitys.SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activitys.MainMenu" />
        <activity android:name=".activitys.MainActivity" />
        <activity android:name=".activitys.FinalScreenActivity" />
    </application>
</manifest>


text:
using System;
using System.Collections.Generic;
using POESKillTree.SkillTreeFiles;

namespace POESKillTree.TreeGenerator.Settings
{
    /// <summary>
    /// Data class for the settings shared by all tree generator solvers.
    /// </summary>
    public class SolverSettings
    {

        /// <summary>
        /// Character Level that calculations are based on.
        /// </summary>
        public readonly int Level;

        /// <summary>
        /// Maximum for points spent in the result tree.
        /// May be ignored if the only goal of the solver is to minimize point count.
        /// </summary>
        public readonly int TotalPoints;

        /// <summary>
        /// Set of Nodes that must be included in the result tree.
        /// </summary>
        public readonly ISet<SkillNode> Checked;

        /// <summary>
        /// Set of Nodes that must not be included in the result tree.
        /// </summary>
        public readonly ISet<SkillNode> Crossed;

        /// <summary>
        /// Nodes the result tree must be a subset of. (empty means no restriction)
        /// </summary>
        public readonly ISet<SkillNode> SubsetTree;

        /// <summary>
        /// Tree for the initial configuration. (empty means starting from scratch)
        /// </summary>
        public readonly ISet<SkillNode> InitialTree;

        /// <summary>
        /// The number of iterations the solver should run. Each iteration is independent of each other
        /// and the best solution over all iterations is kept.
        /// </summary>
        public readonly int Iterations;

        /// <summary>
        /// Creates new SolverSettings.
        /// </summary>
        /// <param name="level">Character Level that calculations are based on. (>= 0)</param>
        /// <param name="totalPoints">Maximum for points spent in the result tree. (>= 0)</param>
        /// <param name="checked">Set of Nodes that must be included in the result tree.</param>
        /// <param name="crossed">Set of Nodes that must not be included in the result tree.</param>
        /// <param name="subsetTree">Nodes the result tree must be a subset of. (empty means no restriction)</param>
        /// <param name="initialTree">Tree for the initial configuration. (empty means starting from scratch)</param>
        /// <param name="iterations">The number of iterations the solver should run. (>= 1)</param>
        public SolverSettings(int level, int totalPoints, ISet<SkillNode> @checked, ISet<SkillNode> crossed,
            ISet<SkillNode> subsetTree, ISet<SkillNode> initialTree, int iterations)
        {
            if (level < 0) throw new ArgumentOutOfRangeException("level", level, "must be >= 0");
            if (totalPoints < 0) throw new ArgumentOutOfRangeException("totalPoints", totalPoints, "must be >= 0");
            if (iterations < 1) throw new ArgumentOutOfRangeException("iterations", iterations, "must be >= 1");

            Level = level;
            TotalPoints = totalPoints;
            Checked = @checked ?? new HashSet<SkillNode>();
            Crossed = crossed ?? new HashSet<SkillNode>();
            SubsetTree = subsetTree ?? new HashSet<SkillNode>();
            InitialTree = initialTree ?? new HashSet<SkillNode>();
            Iterations = iterations;
        }
    }
}


text:
namespace llvm {
  class MipsSubtarget;

class MipsFrameLowering : public TargetFrameLowering {
protected:
  const MipsSubtarget &STI;

public:
  explicit MipsFrameLowering(const MipsSubtarget &sti, unsigned Alignment)
    : TargetFrameLowering(StackGrowsDown, Alignment, 0, Alignment), STI(sti) {}

  static const MipsFrameLowering *create(const MipsSubtarget &ST);

  bool hasFP(const MachineFunction &MF) const override;

  bool hasBP(const MachineFunction &MF) const;

  bool isFPCloseToIncomingSP() const override { return false; }

  void
  eliminateCallFramePseudoInstr(MachineFunction &MF,
                                MachineBasicBlock &MBB,
                                MachineBasicBlock::iterator I) const override;

protected:
  uint64_t estimateStackSize(const MachineFunction &MF) const;
};

/// Create MipsFrameLowering objects.
const MipsFrameLowering *createMips16FrameLowering(const MipsSubtarget &ST);
const MipsFrameLowering *createMipsSEFrameLowering(const MipsSubtarget &ST);

} // End llvm namespace

#endif


text:
<?php
require_once 'PHPUnit/Framework.php';

require_once 'recess/RecessAllTests.php';

class AllTests {

	public static function suite() {
		$suite = new PHPUnit_Framework_TestSuite('recess');

		$suite->addTestSuite(RecessAllTests::suite());

		return $suite;
	}

}
?>


text:
module Admin
  class UsersController < AdminApplicationController
    before_action :set_user, only: [:show, :edit, :update, :destroy]
    before_action :set_admin_user_custom_fields, only: [:show, :edit]
    before_action :set_unique_key, only: [:new, :edit]

    respond_to :html
    def index
      @users = AdminUser.all.page(params[:page])
      respond_with(@users)
    end

    def show
    end

    def new
      @user = AdminUser.new
      set_sites
      respond_with(@user)
    end

    def edit
      @user.uuid = @uuid
    end

    def create
      @user = AdminUser.new(user_params)
      set_sites
      flash[:notice] = t("views.common.create_complete_message") if @user.save
      respond_with(@user, location: admin_users_url)
    end

    def update
      begin
        ActiveRecord::Base.transaction do
          @user.assign_attributes(user_params)
          AdminUserAttachment.where(["token = ?", @user.uuid]).each do |attach|
            attach.admin_user = @user
            attach.save!
          end
        end
        ActiveRecord::Base.transaction do
          @user.save!
          flash[:notice] = t("views.common.update_complete_message")
        end
        respond_with(@user, location: admin_users_url)
      rescue ActiveRecord::RecordInvalid => e
        respond_with(@user, location: edit_admin_user_path(@user))
      rescue => e
        STDERR.puts e.backtrace.join("\n")
        set_sites
        respond_with(@user, location: edit_admin_user_path(@user))
      end
    end

    def destroy
      flash[:notice] = t("views.common.destroy_complete_message") if @user.destroy
      respond_with(@user, location: admin_users_url)
    end

    private
    def set_user
      @user = AdminUser.find(params[:id])
      set_sites
    end

    def user_params
      params.require(:admin_user).permit!
    end

    def set_admin_user_custom_fields
      @custom_fields = CustomField.admin_users
      @custom_fields.each do |custom_field|
        @user.admin_user_custom_fields << AdminUserCustomField.new(custom_field_id: custom_field.id) unless @user.admin_user_custom_fields.map(&:custom_field_id).include?(custom_field.id)
      end
    end

    def set_unique_key
      @uuid = Report.set_unique_key
    end

    public

  end
end


text:
from collections import OrderedDict

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.conf import settings
from django.db.models import F
from django.urls import reverse
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView

from .forms import UploadForm, FILE_TYPE_CHOICES
from .utils import Headline, highlight_matching_substring, run_shell_command
from mpages.models import Page

def list_uploads():
    cwd = settings.BASE_DIR
    uploads = []
    for upload_type in FILE_TYPE_CHOICES:
        for filename in run_shell_command(
            f"ls media/{upload_type.directory}/*.*", cwd
        ).split():
            uploads.append(
                {
                    "type": upload_type.label,
                    "directory": upload_type.directory,
                    "filename": filename.split("/")[2],
                }
            )
    return uploads

class SearchView(TemplateView):
    template_name = "core/search.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        search_string = self.request.GET.get("search", "")
        results = OrderedDict()
        if len(search_string) >= 3:
            search_query = SearchQuery(search_string)
            title_vector = SearchVector("title", weight="A")

            content_vector = SearchVector("content", weight="B")
            page_vectors = title_vector + content_vector

            pages = (Page.objects.annotate(search=page_vectors)
                .filter(search=search_query)
                .annotate(rank=SearchRank(page_vectors, search_query))
                .order_by("-rank")
                .annotate(title_highlight=Headline(F("title"), search_query))
                .annotate(content_highlight=Headline(F("content"), search_query)))

            for page in pages:
                results[page.slug] = {
                    "slug": page.slug,
                    "title_highlight": page.title_highlight,
                    "content_highlight": page.content_highlight,
                }

            pages = Page.objects.filter(title__icontains=search_string)
            for page in pages:
                if page.slug not in results:
                    results[page.slug] = {
                        "slug": page.slug,
                        "title_highlight": highlight_matching_substring(page.title, search_string),
                        "content_highlight": highlight_matching_substring(page.content, search_string),
                    }

            pages = Page.objects.filter(content__icontains=search_string)
            for page in pages:
                if page.slug not in results:
                    results[page.slug] = {
                        "slug": page.slug,
                        "title_highlight": highlight_matching_substring(page.title, search_string),
                        "content_highlight": highlight_matching_substring(page.content, search_string),
                    }

            context["results"] = list(results.values())

            uploads = [upload for upload in list_uploads() if search_string.lower() in upload["filename"].lower()]
            for upload in uploads:
                upload["filename_highlight"] = highlight_matching_substring(upload["filename"], search_string)
            context["uploads"] = uploads
        else:
            context["error"] = "Search term must be at least 3 characters"
        context["search_string"] = search_string
        return context

class UploadView(LoginRequiredMixin, FormView):
    template_name = "core/upload.html"
    form_class = UploadForm

    def form_valid(self, form):
        upload_file = form.cleaned_data["upload_file"]
        upload_file_type = form.cleaned_data["upload_type"]
        with open(
            f"{settings.MEDIA_ROOT}/{upload_file_type}/{upload_file.name}", "wb+"
        ) as destination:
            for chunk in upload_file.chunks():
                destination.write(chunk)
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context["uploads"] = list_uploads()

        return context

    def get_success_url(self):
        return reverse("upload")


text:
#ifndef CRIMILD_SCENEGRAPH_LIGHT_
#define CRIMILD_SCENEGRAPH_LIGHT_

#include "Foundation/Containers/Array.hpp"
#include "Mathematics/ColorRGB.hpp"
#include "Node.hpp"
#include "Rendering/Catalog.hpp"

namespace crimild {

    class ShadowMap;
    class DescriptorSet;

    /**
       Attenuation values:
       | Distance | Constant | Linear | Quadratic
       | 7	      | 1.0	     | 0.7    | 1.8
       | 13       | 1.0	     | 0.35   | 0.44
       | 20       | 1.0      | 0.22   | 0.20
       | 32       | 1.0	     | 0.14   | 0.07
       | 50	      | 1.0      | 0.09   | 0.032
       | 65	      | 1.0      | 0.07   | 0.017
       | 100	  | 1.0	     | 0.045  | 0.0075
       | 160	  | 1.0      | 0.027  | 0.0028
       | 200	  | 1.0      | 0.022  | 0.0019
       | 325	  | 1.0      | 0.014  | 0.0007
       | 600	  | 1.0      | 0.007  | 0.0002
       | 3250	  | 1.0      | 0.0014 | 0.000007
     */
    class Light : public Node, public Catalog< Light >::Resource {
        CRIMILD_IMPLEMENT_RTTI( crimild::Light )

    public:
        enum class Type {
            AMBIENT,
            POINT,
            DIRECTIONAL,
            SPOT,
        };

    public:
        Light( Type type = Type::POINT );
        virtual ~Light( void );

        const Type &getType( void ) const noexcept { return _type; }

        [[nodiscard]] Point3 getPosition( void ) const noexcept;
        [[nodiscard]] Vector3 getDirection( void ) const noexcept;

        void setAttenuation( const Vector3f &attenuation ) { _attenuation = attenuation; }
        const Vector3f &getAttenuation( void ) const { return _attenuation; }

        void setColor( const ColorRGB &color ) { _color = color; }
        const ColorRGB &getColor( void ) const { return _color; }

        void setOuterCutoff( float value ) { _outerCutoff = value; }
        float getOuterCutoff( void ) const { return _outerCutoff; }

        void setInnerCutoff( float value ) { _innerCutoff = value; }
        float getInnerCutoff( void ) const { return _innerCutoff; }

        void setExponent( float value ) { _exponent = value; }
        float getExponent( void ) const { return _exponent; }

        const ColorRGB &getAmbient( void ) const { return _ambient; }
        void setAmbient( const ColorRGB &ambient ) { _ambient = ambient; }

        inline Real32 getEnergy( void ) const noexcept { return m_energy; }
        inline void setEnergy( Real32 energy ) noexcept { m_energy = energy; }

        void setRadius( Real32 radius ) noexcept;
        Real32 getRadius( void ) const noexcept;

        DescriptorSet *getDescriptors( void ) noexcept;

    private:
        Type _type;
        Vector3f _attenuation;
        ColorRGB _color;
        float _outerCutoff;
        float _innerCutoff;
        float _exponent;
        ColorRGB _ambient;
        SharedPointer< DescriptorSet > m_descriptors;
        Real32 m_energy = 1.0f;
        Real32 m_radius = -1.0f; // compute radius based on energy by default

    public:
        virtual void accept( NodeVisitor &visitor ) override;

    public:
        void setCastShadows( crimild::Bool enabled );
        inline crimild::Bool castShadows( void ) const { return _shadowMap != nullptr; }

        [[deprecated]] Matrix4f computeLightSpaceMatrix( void ) const noexcept;

        [[deprecated]] void setShadowMap( SharedPointer< ShadowMap > const &shadowMap ) { _shadowMap = shadowMap; }
        [[deprecated]] inline ShadowMap *getShadowMap( void ) { return crimild::get_ptr( _shadowMap ); }

        /**
           \brief Get descriptors used for computing the shadow atlas

           For most lights, we will need only one. But point lights will require
           up to six (one for each face of the cubemap)
         */
        [[deprecated]] Array< SharedPointer< DescriptorSet > > &getShadowAtlasDescriptors( void ) noexcept;

    private:
        [[deprecated]] SharedPointer< ShadowMap > _shadowMap;
        [[deprecated]] Array< SharedPointer< DescriptorSet > > m_shadowAtlasDescriptors;

        /**
            \name Coding
         */
        //@{

    public:
        virtual void encode( coding::Encoder &encoder ) override;
        virtual void decode( coding::Decoder &decoder ) override;

        //@}
    };

}

#endif


text:
from m5.objects import *
from arm_generic import *

root = LinuxArmFSSystem(mem_mode='timing',
                        mem_class=DDR3_1600_x64,
                        cpu_class=MinorCPU,
                        num_cpus=2).create_root()


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <!--
  Sample project for demonstrating the health check feature

  Call it with 'mvn install'.

  -->

  <parent>
    <groupId>io.fabric8.dmp.samples</groupId>
    <artifactId>dmp-sample-parent</artifactId>
    <version>0.34-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>dmp-sample-healthcheck</artifactId>
  <version>0.34-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>io.fabric8</groupId>
        <artifactId>docker-maven-plugin</artifactId>
        <configuration>
          <watchInterval>500</watchInterval>
          <logDate>default</logDate>
          <verbose>true</verbose>
          <autoPull>always</autoPull>
          <images>
            <image>
              <alias>healthybox1</alias>
              <name>busybox1</name>
              <build>
                <from>busybox</from>
                <healthCheck>
                  <cmd>curl -f http://localhost/ || exit 1</cmd>
                </healthCheck>
                <cmd>
                  <shell>sleep 2</shell>
                </cmd>
              </build>
              <run>
                <wait>
                  <healthy>true</healthy>
                </wait>
              </run>
            </image>
            <image>
              <alias>healthybox2</alias>
              <name>busybox2</name>
              <build>
                <from>busybox</from>
                <healthCheck>
                  <interval>5m</interval>
                  <timeout>3s</timeout>
                  <retries>3</retries>
                  <cmd>curl -f http://localhost/ || exit 1</cmd>
                </healthCheck>
              </build>
            </image>
            <image>
              <alias>healthybox3</alias>
              <name>busybox3</name>
              <build>
                <from>busybox</from>
                <healthCheck>
                  <interval>5m</interval>
                  <retries>3</retries>
                  <cmd>
                    <shell>curl -f http://localhost/ || exit 1</shell>
                  </cmd>
                </healthCheck>
              </build>
              <run>
                <wait>
                  <healthy>true</healthy>
                </wait>
              </run>
            </image>
            <image>
              <alias>healthybox4</alias>
              <name>busybox4</name>
              <build>
                <from>busybox</from>
                <healthCheck>
                  <mode>cmd</mode>
                  <interval>5m</interval>
                  <cmd>
                    <exec>
                      <args>curl</args>
                      <args>-f</args>
                      <args>http://localhost/</args>
                      <args>||</args>
                      <args>exit 1</args>
                    </exec>
                  </cmd>
                </healthCheck>
              </build>
            </image>
            <image>
              <alias>healthybox5</alias>
              <name>busybox5</name>
              <build>
                <from>busybox</from>
                <healthCheck>
                  <interval>5m</interval>
                  <timeout>3s</timeout>
                  <startPeriod>30m</startPeriod>
                  <retries>3</retries>
                  <cmd>curl -f http://localhost/ || exit 1</cmd>
                </healthCheck>
              </build>
            </image>
            <image>
              <alias>unhealthybox6</alias>
              <name>busybox5</name>
              <build>
                <from>busybox</from>
                <healthCheck>
                  <mode>none</mode>
                </healthCheck>
              </build>
            </image>
          </images>
        </configuration>
        <executions>
          <execution>
            <id>start</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>start</goal>
            </goals>
          </execution>
          <execution>
            <id>stop</id>
            <phase>post-integration-test</phase>
            <goals>
              <goal>stop</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>


text:
/* xhrq.js is MIT licensed (c) 2012 Jon Buckley. github.com/jbuck/xhrq */

( function() {
  "use strict";

  var maxActive = 4,
      active = [],
      queued = [],
      queuedData = [];

  function cleanUpXHR() {
    active.splice( active.indexOf( this ), 1 );

    var xhr = queued.shift(),
        data = queuedData.shift();
    if ( xhr ) {
      active.push( xhr );
      xhr.send( data );
    }
  }

  XMLHttpRequest.prototype.queue = function queue( data ) {
    this.addEventListener("loadend", cleanUpXHR, false);

    if ( active.length < maxActive ) {
      active.push( this );
      this.send( data );
      return;
    }

    queued.push( this );
    queuedData.push( data );
  };
})();


text:
package org.dkpro.lab.engine.impl;

import java.util.HashMap;
import java.util.Map;

import org.dkpro.lab.engine.TaskContext;

/**
 * Helper-class to allow injecting {@link TaskContext} instances into UIMA components. This is
 * actually a bad hack that will not work if the components are deployed in another Java VM.
 */
public class StaticContext
{
	private static Map<String, Object> context = new HashMap<String, Object>();

	public static void bind(String key, Object object)
	{
		context.put(key, object);
	}

	public static void unbind(String key)
	{
		context.remove(key);
	}

	public static Object lookup(String key)
	{
		return context.get(key);
	}
}


text:
function smoothed_image = gaussiansmoothing(image, sigma)

    shape = size(image);
    w = shape(1);
    h = shape(2);
    b = 1;

    if ( length(shape) == 3 )
        b = shape(3);
    end

    smoothed_image = zeros(w,h,b,'single');

    for i=1:b
        smoothed_image(:,:,i) = gaussiansmoothing_band(image(:,:,i), sigma);
    end

end

function smoothed_image_band = gaussiansmoothing_band(image_band, sigma)

    shape = size(image_band);
    w = shape(1);
    h = shape(2);

    ptr = libpointer('singlePtr',image_band);

    smoothed_image_band = zeros(w,h,'single');
    smooth_ptr = libpointer('singlePtr',smoothed_image_band);

    result = calllib('libvigra_c','vigra_gaussiansmoothing_c', ptr, smooth_ptr, w,h, single(sigma));

    switch result
        case 0
            smoothed_image_band = smooth_ptr.Value;
        case 1
            error('Error in vigramatlab.filters.gaussiansmoothing: Gaussian smoothing failed!')
    end
end


text:
module Aws::SagemakerEdgeManager

  class Resource

    # @param options ({})
    # @option options [Client] :client
    def initialize(options = {})
      @client = options[:client] || Client.new(options)
    end

    # @return [Client]
    def client
      @client
    end

  end
end


text:
import {createStore} from 'redux'
import root from './reducers/root'

export default createStore(root);


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.DependencyInjection
{
    using System;

    using Microsoft.Extensions.DependencyInjection;

    /// <summary>
    /// An interface for adding extension points to the DNN Startup Logic.
    /// </summary>
    [CLSCompliant(false)]
    public interface IDnnStartup
    {
        /// <summary>
        /// Configure additional services for the host or web application.
        /// This method will be called during the Application Startup phase
        /// and services will be available anywhere in the application.
        /// </summary>
        /// <param name="services">
        /// Service Collection used to registering services in the container.
        /// </param>
        [CLSCompliant(false)]
        void ConfigureServices(IServiceCollection services);
    }
}


text:
import * as React from 'react';
import { Grid } from 'react-bootstrap';
const s = require('./style.css');

class Loader extends React.Component<void, void> {
  render() {
    return (
      <Grid>

      </Grid>
    );
  }
}

export { Loader }


text:
'use strict';

var util = require('util');
var http = require('http');
var connect = require('connect');
var PORT = 9012;
var hitNum = 0;

http.createServer(function(req, res) {
  var resp = util.format('target: %d request: %s', ++hitNum, req.url);
  util.log(resp);
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end(resp);
}).listen(PORT);

util.log('target: started on port ' + PORT);

module.exports.port = PORT;


text:
var spine = require('../SpineUtil');
spine.TrackEntry = function ()
{};
spine.TrackEntry.prototype = {
    next: null, previous: null,
    animation: null,
    loop: false,
    delay: 0, time: 0, lastTime: -1, endTime: 0,
    timeScale: 1,
    mixTime: 0, mixDuration: 0, mix: 1,
    onStart: null, onEnd: null, onComplete: null, onEvent: null
};
module.exports = spine.TrackEntry;


text:
from siuba.dply.across import across, _get_name_template, _across_setup_fns, ctx_verb_data, ctx_verb_window
from siuba.dply.tidyselect import var_select, var_create
from siuba.siu import FormulaContext, Call, FormulaArg
from siuba.siu.calls import str_to_getitem_call
from siuba.siu.visitors import CallListener

from .backend import LazyTbl
from .utils import _sql_select, _sql_column_collection

from sqlalchemy import sql

class ReplaceFx(CallListener):
    def __init__(self, replacement):
        self.replacement = replacement

    def exit(self, node):
        res = super().exit(node)
        if isinstance(res, FormulaArg):
            return str_to_getitem_call(self.replacement)

        return res

@across.register(LazyTbl)
def _across_lazy_tbl(__data: LazyTbl, cols, fns, names: "str | None" = None) -> LazyTbl:
    raise NotImplementedError(
        "across() cannot called directly on a LazyTbl. Please use it inside a verb, "
        "like mutate(), summarize(), filter(), arrange(), group_by(), etc.."
    )
    #selectable = __data.last_op
    #
    #columns = selectable.alias().columns
    #if not isinstance(columns, ImmutableColumnCollection):
    #    raise TypeError(str(type(columns)))

    #res_cols = across(columns, cols, fns, names)

    #return __data.append_op(_sql_select(res_cols))

@across.register(sql.base.ImmutableColumnCollection)
def _across_sql_cols(
    __data: sql.base.ImmutableColumnCollection,
    cols,
    fns,
    names: "str | None" = None
) -> sql.base.ImmutableColumnCollection:

    lazy_tbl = ctx_verb_data.get()
    window = ctx_verb_window.get()

    name_template = _get_name_template(fns, names)
    selected_cols = var_select(__data, *var_create(cols), data=__data)

    fns_map = _across_setup_fns(fns)

    results = []

    # iterate over columns ----
    for new_name, old_name in selected_cols.items():
        if old_name is None:
            old_name = new_name

        crnt_col = __data[old_name]
        #context = FormulaContext(Fx=crnt_col, _=__data)

        # iterate over functions ----
        for fn_name, fn in fns_map.items():
            fmt_pars = {"fn": fn_name, "col": new_name}

            fn_replaced = ReplaceFx(old_name).enter(fn)
            new_call = lazy_tbl.shape_call(
                fn_replaced,
                window,
                verb_name="Across",
                arg_name = f"function {fn_name} of {len(fns_map)}"
            )

            res, windows, _ = lazy_tbl.track_call_windows(new_call, __data)

            #res = new_call(context)
            res_name = name_template.format(**fmt_pars)
            results.append(res.label(res_name))

    return _sql_column_collection(results)


text:
package htmldoc

import (
	"os"
	"path"
	"regexp"

	"github.com/wjdp/htmltest/output"
)

// DocumentStore struct, store of Documents including Document discovery
type DocumentStore struct {
	BasePath           string               // Path, relative to cwd, the site is located in
	IgnorePatterns     []interface{}        // Regexes of directories to ignore
	Documents          []*Document          // All of the documents, used to iterate over
	DocumentPathMap    map[string]*Document // Maps slash separated paths to documents
	DocumentExtension  string               // File extension to look for
	DirectoryIndex     string               // What file is the index of the directory
	IgnoreTagAttribute string               // Attribute to ignore element and children if found on element
}

// NewDocumentStore : Create and return a new Document store.
func NewDocumentStore() DocumentStore {
	return DocumentStore{
		Documents:       make([]*Document, 0),
		DocumentPathMap: make(map[string]*Document),
	}
}

// AddDocument : Add a document to the document store.
func (dS *DocumentStore) AddDocument(doc *Document) {
	// Save reference to document to various data stores
	dS.Documents = append(dS.Documents, doc)
	dS.DocumentPathMap[doc.SitePath] = doc
	// Pass some vars on
	doc.ignoreTagAttribute = dS.IgnoreTagAttribute
}

// Discover : Discover all documents within DocumentStore.BasePath.
func (dS *DocumentStore) Discover() {
	dS.discoverRecurse(".")
}

// Does dir match one of the IgnorePatterns?
func (dS *DocumentStore) isDirIgnored(dir string) bool {
	for _, item := range dS.IgnorePatterns {
		if ok, _ := regexp.MatchString(item.(string), dir+"/"); ok {
			return true
		}
	}
	return false
}

// Recursive function to discover documents by walking the file tree
func (dS *DocumentStore) discoverRecurse(dPath string) {
	// Open directory to scan
	f, err := os.Open(path.Join(dS.BasePath, dPath))
	output.CheckErrorPanic(err)
	defer f.Close()

	// Get FileInfo of directory (scan it)
	fi, err := f.Stat()
	output.CheckErrorPanic(err)

	if fi.IsDir() { // Double check we're dealing with a directory
		// Read all FileInfo-s from directory, Readdir(count int)
		fis, err := f.Readdir(-1)
		output.CheckErrorPanic(err)

		// Iterate over contents of directory
		for _, fileinfo := range fis {
			fPath := path.Join(dPath, fileinfo.Name())
			if fileinfo.IsDir() {
				// If item is a dir, we delve deeper
				dS.discoverRecurse(fPath)
			} else if path.Ext(fileinfo.Name()) == dS.DocumentExtension {
				// If a file, create and save document
				newDoc := &Document{
					FilePath:   path.Join(dS.BasePath, fPath),
					SitePath:   fPath,
					BasePath:   dPath,
					IgnoreTest: dS.isDirIgnored(dPath),
				}
				newDoc.Init()
				dS.AddDocument(newDoc)
			}
		}
	} else { // It's a file, return single file
		panic("discoverRecurse encountered a file: " + dPath)
	}

}

// ResolvePath : Resolves internal absolute paths to documents.
func (dS *DocumentStore) ResolvePath(refPath string) (*Document, bool) {
	// Match root document
	if refPath == "/" {
		d0, b0 := dS.DocumentPathMap[dS.DirectoryIndex]
		return d0, b0
	}

	if refPath[0] == '/' && len(refPath) > 1 {
		// Is an absolute link, remove the leading slash for map lookup
		refPath = refPath[1:]
	}

	// Try path as-is, path.ext
	d1, b1 := dS.DocumentPathMap[refPath]
	if b1 {
		// as-is worked, return that
		return d1, b1
	}

	// Try as a directory, path.ext/index.html
	d2, b2 := dS.DocumentPathMap[path.Join(refPath, dS.DirectoryIndex)]
	return d2, b2
}

// ResolveRef : Proxy to ResolvePath via ref.RefSitePath()
func (dS *DocumentStore) ResolveRef(ref *Reference) (*Document, bool) {
	return dS.ResolvePath(ref.RefSitePath())
}


text:
package com.box.l10n.mojito.service.tm;

import com.box.l10n.mojito.entity.Asset;
import com.box.l10n.mojito.entity.Repository;
import com.box.l10n.mojito.json.ObjectMapper;
import com.box.l10n.mojito.okapi.ImportExportTextUnitUtils;
import com.box.l10n.mojito.okapi.RawDocument;
import com.box.l10n.mojito.service.asset.AssetRepository;
import com.box.l10n.mojito.service.asset.AssetService;
import com.box.l10n.mojito.service.locale.LocaleService;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.pipelinedriver.IPipelineDriver;
import net.sf.okapi.common.pipelinedriver.PipelineDriver;
import net.sf.okapi.filters.xliff.XLIFFFilter;
import net.sf.okapi.steps.common.RawDocumentToFilterEventsStep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/** @author jaurambault */
@Component
public class TMImportService {

  /** logger */
  static Logger logger = LoggerFactory.getLogger(TMImportService.class);

  @Autowired LocaleService localeService;

  @Autowired TMService tmService;

  @Autowired AssetRepository assetRepository;

  @Autowired AssetService assetService;

  @Autowired TMTextUnitRepository tmTextUnitRepository;

  @Autowired ObjectMapper objectMapper;

  @Autowired ImportExportTextUnitUtils importExportTextUnitUtils;

  /**
   * Import the exported XLIFF using Okapi driver into repository.
   *
   * @param repository
   * @param xliffContent
   * @param updateTM indicates if the TM should be updated or if the translation can be imported
   *     assuming that there is no translation yet.
   */
  public void importXLIFF(Repository repository, String xliffContent, boolean updateTM) {

    ImportExportedXliffStep importExportedXliffStep =
        new ImportExportedXliffStep(repository, xliffContent, updateTM);
    importXLIFF(importExportedXliffStep, xliffContent);
  }

  /**
   * Import the exported XLIFF using Okapi driver for a specific asset.
   *
   * @param assetId
   * @param xliffContent
   * @param updateTM
   */
  public void importXLIFF(Long assetId, String xliffContent, boolean updateTM) {

    Asset asset = assetRepository.findById(assetId).orElse(null);
    ImportExportedXliffStep importExportedXliffStep =
        new ImportExportedXliffStep(asset, xliffContent, updateTM);
    importXLIFF(importExportedXliffStep, xliffContent);
  }

  @Transactional
  private void importXLIFF(ImportExportedXliffStep importExportedXliffStep, String xliffContent) {

    IPipelineDriver driver = new PipelineDriver();
    XLIFFFilter xliffFilter = new XLIFFFilter();
    driver.addStep(new RawDocumentToFilterEventsStep(xliffFilter));

    importExportedXliffStep.setXliffFilter(xliffFilter);
    driver.addStep(importExportedXliffStep);

    RawDocument rawDocument = new RawDocument(xliffContent, LocaleId.ENGLISH);

    driver.addBatchItem(rawDocument);

    logger.debug("Start importing XLIFF");
    driver.processBatch();
  }
}


text:
Python class to parse common long names used in Puerto Rico.

This class is a quick solution to parse most of the long compound names I have encountered in my data wrangling adventures.

This class was designed to deal with name prefixes common in Puerto Rico like "de", "de la", "de los", "de las" and breaks names into these components:

  1. first name
  2. initial
  3. last name (spanish: apellido paterno)
  4. mother's maiden name (spanish: apellido materno)

It is not a full name parser, like [python-nameparser](https://github.com/derek73/python-nameparser), which I highly recommend for handling English names with titles and other suffixes and prefixes.

This work is licensed under the BSD License.


text:
from oslo import messaging
from oslo.config import cfg

from mistral.openstack.common import log as logging

LOG = logging.getLogger(__name__)

class EngineClient(object):
    """
    RPC client for the Engine.
    """

    def __init__(self, transport):
        """Construct an RPC client for the Engine.

        :param transport: a messaging transport handle
        :type transport: Transport
        """
        target = messaging.Target(topic=cfg.CONF.engine.topic)
        self._client = messaging.RPCClient(transport, target)

    def start_workflow_execution(self, workbook_name, task_name, context=None):
        """Starts a workflow execution based on the specified workbook name
        and target task.

        :param workbook_name: Workbook name
        :param task_name: Target task name
        :param context: Execution context which defines a workflow input
        :return: Workflow execution.
        """
        # TODO(m4dcoder): refactor auth context
        cntx = {}
        kwargs = {'workbook_name': workbook_name,
                  'task_name': task_name,
                  'context': context}
        return self._client.call(cntx, 'start_workflow_execution', **kwargs)

    def stop_workflow_execution(self, workbook_name, execution_id):
        """Stops the workflow execution with the given id.

        :param workbook_name: Workbook name.
        :param execution_id: Workflow execution id.
        :return: Workflow execution.
        """
        # TODO(m4dcoder): refactor auth context
        cntx = {}
        kwargs = {'workbook_name': workbook_name,
                  'execution_id': execution_id}
        return self._client.call(cntx, 'stop_workflow_execution', **kwargs)

    def convey_task_result(self, workbook_name, execution_id,
                           task_id, state, result):
        """Conveys task result to Mistral Engine.

        This method should be used by clients of Mistral Engine to update
        state of a task once task action has been performed. One of the
        clients of this method is Mistral REST API server that receives
        task result from the outside action handlers.

        Note: calling this method serves an event notifying Mistral that
        it possibly needs to move the workflow on, i.e. run other workflow
        tasks for which all dependencies are satisfied.

        :param workbook_name: Workbook name.
        :param execution_id: Workflow execution id.
        :param task_id: Task id.
        :param state: New task state.
        :param result: Task result data.
        :return: Task.
        """
        # TODO(m4dcoder): refactor auth context
        cntx = {}
        kwargs = {'workbook_name': workbook_name,
                  'execution_id': execution_id,
                  'task_id': task_id,
                  'state': state,
                  'result': result}
        return self._client.call(cntx, 'convey_task_result', **kwargs)

    def get_workflow_execution_state(self, workbook_name, execution_id):
        """Gets the workflow execution state.

        :param workbook_name: Workbook name.
        :param execution_id: Workflow execution id.
        :return: Current workflow state.
        """
        # TODO(m4dcoder): refactor auth context
        cntx = {}
        kwargs = {'workbook_name': workbook_name,
                  'execution_id': execution_id}
        return self._client.call(
            cntx, 'get_workflow_execution_state', **kwargs)

    def get_task_state(self, workbook_name, execution_id, task_id):
        """Gets task state.

        :param workbook_name: Workbook name.
        :param execution_id: Workflow execution id.
        :param task_id: Task id.
        :return: Current task state.
        """
        # TODO(m4dcoder): refactor auth context
        cntx = {}
        kwargs = {'workbook_name': workbook_name,
                  'executioin_id': execution_id,
                  'task_id': task_id}
        return self._client.call(cntx, 'get_task_state', **kwargs)


text:
"""
    femagtools.job
    ~~~~~~~~~~~~~~

    Creating and managing calculation jobs.

"""
import os
import platform
import shutil
import pathlib
import femagtools.bch
import femagtools.airgap
import femagtools.config as cfg
import logging
import uuid
import importlib

logger = logging.getLogger(__name__)

# lines that contains this words are detected as error messages
protfile_error = ['Model has no field sources']
femagfile_error = ['ms_error',
                   'unexpected terminal input in quiet mode',
                   'Fortran runtime error',
                   'Exception system errors']

# https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html

class TaskFactory:
    factories = {}

    def addFactory(typename, taskFactory):
        TaskFactory.factories.put[typename] = taskFactory
    addFactory = staticmethod(addFactory)

    def createTask(typename, taskid, dir, result_func):
        if typename not in TaskFactory.factories:
            try:
                TaskFactory.factories[typename] = \
                    eval(typename + '.Factory()')
            except NameError:
                modname, classname = typename.split('.')
                mod = importlib.import_module(modname)
                TaskFactory.factories[typename] = getattr(mod,
                                                          classname).Factory()
        return TaskFactory.factories[typename].create(taskid, dir, result_func)
    createTask = staticmethod(createTask)

class Task(object):
    """represents a single execution unit that may include data files"""

    def __init__(self, id, directory, result_func=None):
        self.result_func = result_func
        self.directory = directory
        try:
            os.makedirs(self.directory)
        except OSError as e:
            if e.errno != 17:
                e.args += self.directory
                raise
            pass
        self.transfer_files = []
        self.status = None
        self.fsl_file = None
        self.id = id
        self.stateofproblem = 'mag_static'

    def set_stateofproblem(self, stateofproblem):
        self.stateofproblem = stateofproblem

    def add_file(self, fname, content=None):
        """adds a file required by this task

        Args:
            fname: file name
            content: list of str written to file if not None"""
        base = os.path.basename(fname)
        self.transfer_files.append(fname)
        if os.path.splitext(base)[-1] == '.fsl':
            self.fsl_file = base

        if content is None:
            dest = os.path.join(self.directory, base)
            if not os.access(dest, os.R_OK):
                shutil.copy(fname, dest)
            return

        # this file has to be created
        with open(os.path.join(self.directory, base), 'w') as f:
            f.writelines('\n'.join(content))

    def get_results(self):
        """returns result of most recent BCH or ASM file
        (or project specific results if result_func is set)"""
        if self.result_func:
            return self.result_func(self)

        # read latest bch file if any
        basedir = pathlib.Path(self.directory)
        bchfile_list = sorted(basedir.glob(
            '*_[0-9][0-9][0-9].B*CH'))
        # check airgap induction file exists
        bagdat = basedir / 'bag.dat'
        if bchfile_list:
            result = femagtools.bch.Reader()
            with open(bchfile_list[-1]) as f:
                logger.info("Reading %s",
                            bchfile_list[-1])
                result.read(f)
            if bagdat.exists():
                result.airgap = femagtools.airgap.read(bagdat)
            return result
            # logger.info("%s %s", result.version, result.type),
        else:
            asm_list = sorted(basedir.glob(
                '*_[0-9][0-9][0-9].ASM'))
            if asm_list:
                logger.info("Reading %s",
                            asm_list[-1])
                result = femagtools.asm.read(asm_list[-1])
                if bagdat.exists():
                    result['airgap'] = femagtools.airgap.read(bagdat)
                return result
            msg = 'no BCH (or ASM) files in {}'.format(self.directory)
            logger.error(msg)
        result = dict(error=msg)
        return result

    def readErrorMessage(self, html=True):
        errstr = ""
        if html:
            sepIn = '
{}
'
            sepOut = '
'
            newLine = '
'
        else:
            sepIn = '=== {} ===\n'
            sepOut = '\n\n'
            newLine = '\n'

        errstr += sepIn.format(self.directory)

        # read latest prot file
        protfile_list = sorted(pathlib.Path(self.directory).glob('*.PROT'))
        if protfile_list:
            with open(protfile_list[-1], encoding='latin1') as f:
                e = [em in l for em in protfile_error for l in f.readlines()]
                if sum(e):
                    logger.info("Prot Files Message.\n '%s'\n\nDirectory '%s'.",
                                e, self.directory)
                    errstr += "ProtFile: {}{}".format(e, newLine)

        # read femag.err file
        try:
            with open(os.path.join(self.directory, 'femag.err'), 'r') as file:
                e = [em in l for em in femagfile_error for l in file.readlines()]
                if sum(e):
                    logger.error("Femag Error detected\n '%s'\n\nDirectory '%s'.",
                                 e, self.directory)
                    errstr += "{}{}".format(e, newLine)
        except Exception as e:
            logger.debug("Exception: %s", e)
            pass
        errstr += sepOut
        return errstr

    def __eq__(self, other):
        return isinstance(other, type(self)) and \
            self.directory == other.directory

    class Factory:
        def create(self, id, dir, result_func): return Task(
            id, dir, result_func)

class CloudTask(Task):
    def __init__(self, id, directory, result_func=None):
        super(self.__class__, self).__init__(id, directory, result_func)
        import tarfile
        self.file = "{}.tar.gz".format(self.directory)
        self.tar_file = tarfile.open(self.file, "w:gz")
        # Used for amazon
        self.ec2_instance = None

    def add_file(self, fname, content=None):
        base = os.path.basename(fname)
        self.transfer_files.append(fname)
        if os.path.splitext(base)[-1] == '.fsl':
            self.fsl_file = base

        info = self.tar_file.tarinfo()
        info.name = base
        if content is None:
            info.size = os.path.getsize(fname)
            self.tar_file.addfile(info, open(fname, 'rb'))
            return

        import io
        if type(content) is list:
            content = '\n'.join(content)
        info.size = len(content)
        data = io.BytesIO(str.encode(content))
        self.tar_file.addfile(info, data)

    class Factory:
        def create(self, id, dir, result_func): return CloudTask(
            id, dir, result_func)

class Job(object):
    """represents a FEMAG job consisting of one or more tasks
    each to be executed by a dedicated process
    """

    def __init__(self, basedir):
        self.runDirPrefix = ''
        self.basedir = basedir
        self.tasks = []
        self.num_cur_steps = 0

    def cleanup(self):
        """removes all task directories of previous run"""
        for task in self.tasks:
            logger.debug("rm %s", task.directory)
            shutil.rmtree(task.directory, ignore_errors=True)
        self.tasks = []

    def add_task(self, result_func=None):
        "adds a new task to this job"
        taskid = "{}-{}".format(
            str(uuid.uuid4()).split('-')[0], len(self.tasks))
        dir = os.path.join(self.basedir,
                           '{}{:d}'.format(self.runDirPrefix,
                                           len(self.tasks)))
        t = TaskFactory.createTask('Task', taskid, dir, result_func)
        self.tasks.append(t)
        return t

    def setExitStatus(self, taskid, status):
        "set exit status of task"
        self.tasks[taskid].status = status

    def get_results(self):
        for t in self.tasks:
            yield t.get_results()

class CondorJob(Job):
    """represents a femag job that is to be run in HT Condor"""

    def __init__(self, basedir):
        super(self.__class__, self).__init__(basedir)

    def prepareDescription(self):
        # create a flatten list of all files to be transferred
        transfer_files = [item for sublist in
                          [t.transfer_files for t in self.tasks]
                          for item in sublist]

        OpSys = "WINDOWS" if platform.system() == "Windows" else "LINUX"

        fslFilename = ''
        for f in transfer_files:
            b, ext = os.path.splitext(f)
            if ext == '.fsl':
                fslFilename = f
                break
        numRuns = len(self.tasks)
# $(Process)                os.path.join(self.basedir, self.runDirPrefix)),
        submit = [
            'InitialDir   = {}/{}$(Process)'.format(
                self.basedir, self.runDirPrefix),
            'Universe     = vanilla',
            'Executable   = {}'.format(cfg.get_executable()),
            'Arguments    = -b {}'.format(fslFilename),
            'Output       = femag.out',
            'Log          = femag.log',
            'Error        = femag.err',
            'Notification = never',
            'input        = /dev/null',
            'transfer_input_files = {}'.format(','.join(set(transfer_files))),
            'requirements = (OpSys=="{}") && Arch=="x86_64"'.format(OpSys),
            'Queue {}'.format(numRuns), '']
        filename = os.path.join(self.basedir, "femag.submit")
        with open(os.path.join(self.basedir,
                               "femag.submit"), 'w') as submitFile:
            submitFile.writelines('\n'.join(submit))
        return filename

class CloudJob(Job):
    """Inheritance of :py:class:`Job`

    Represents a femag amazon job"""

    def __init__(self, basedir):
        super(self.__class__, self).__init__(basedir)

    def add_task(self, result_func=None):
        "adds a new :py:class:`CloudTask` to this job"
        taskid = "{}-{}".format(str(uuid.uuid4()), len(self.tasks))
        dir = os.path.join(self.basedir,
                           '{}{:d}'.format(self.runDirPrefix,
                                           len(self.tasks)))
        t = TaskFactory.createTask('CloudTask', taskid, dir, result_func)
        self.tasks.append(t)
        return t


text:
import EditFormController from 'ember-flexberry/controllers/edit-form';

export default EditFormController.extend({
  /**
    Route name for transition after close edit form.

    @property parentRoute
    @type String
   */
  parentRoute: 'integration-examples/odata-examples/get-masters/ember-flexberry-dummy-vid-departamenta-l',
});


text:
<!DOCTYPE html>

    <title>TachiWeb - Reader</title>

    <link href="bower_components/featherlight/release/featherlight.min.css" type="text/css" rel="stylesheet"/>

    <link href="css/material.min.css" type="text/css" rel="stylesheet"/>

    <link href="bower_components/material-design-icons/iconfont/material-icons.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="css/core.css">

    <link rel="stylesheet" type="text/css" href="css/reader.css">

Back

arrow_back

Download

file_download

Refresh Image

refresh

Fullscreen

fullscreen

Rotate 90°

rotate_right

Loading...

<input id="page_slider" class="mdl-slider mdl-js-slider" type="range" min="0" max="0" value="0" tabindex="0">


text:
"""
Tests For PickledScheduler.
"""

import datetime

from oslo_serialization import jsonutils
import six

from nova.scheduler import scheduler_options
from nova import test

class FakeSchedulerOptions(scheduler_options.SchedulerOptions):
    def __init__(self, last_checked, now, file_old, file_now, data, filedata):
        super(FakeSchedulerOptions, self).__init__()
        # Change internals ...
        self.last_modified = file_old
        self.last_checked = last_checked
        self.data = data

        # For overrides ...
        self._time_now = now
        self._file_now = file_now
        self._file_data = filedata

        self.file_was_loaded = False

    def _get_file_timestamp(self, filename):
        return self._file_now

    def _get_file_handle(self, filename):
        self.file_was_loaded = True
        if six.PY3:
            return six.BytesIO(self._file_data.encode('utf-8'))
        return six.StringIO(self._file_data)

    def _get_time_now(self):
        return self._time_now

class SchedulerOptionsTestCase(test.NoDBTestCase):
    def test_get_configuration_first_time_no_flag(self):
        last_checked = None
        now = datetime.datetime(2012, 1, 1, 1, 1, 1)
        file_old = None
        file_now = datetime.datetime(2012, 1, 1, 1, 1, 1)

        data = dict(a=1, b=2, c=3)
        jdata = jsonutils.dumps(data)

        fake = FakeSchedulerOptions(last_checked, now, file_old, file_now,
                                    {}, jdata)
        self.assertIsNone(fake.last_checked)
        self.assertEqual({}, fake.get_configuration())
        self.assertFalse(fake.file_was_loaded)
        self.assertIsNone(fake.last_checked)

    def test_get_configuration_first_time_empty_file(self):
        last_checked = None
        now = datetime.datetime(2012, 1, 1, 1, 1, 1)
        file_old = None
        file_now = datetime.datetime(2012, 1, 1, 1, 1, 1)

        jdata = ""

        fake = FakeSchedulerOptions(last_checked, now, file_old, file_now,
                                    {}, jdata)

        self.assertIsNone(fake.last_checked)
        self.assertEqual({}, fake.get_configuration('foo.json'))
        self.assertTrue(fake.file_was_loaded)
        self.assertEqual(now, fake.last_checked)

    def test_get_configuration_first_time_happy_day(self):
        last_checked = None
        now = datetime.datetime(2012, 1, 1, 1, 1, 1)
        file_old = None
        file_now = datetime.datetime(2012, 1, 1, 1, 1, 1)

        data = dict(a=1, b=2, c=3)
        jdata = jsonutils.dumps(data)

        fake = FakeSchedulerOptions(last_checked, now, file_old, file_now,
                                    {}, jdata)
        self.assertIsNone(fake.last_checked)
        self.assertEqual(data, fake.get_configuration('foo.json'))
        self.assertTrue(fake.file_was_loaded)
        self.assertEqual(now, fake.last_checked)

    def test_get_configuration_second_time_no_change(self):
        last_checked = datetime.datetime(2011, 1, 1, 1, 1, 1)
        now = datetime.datetime(2012, 1, 1, 1, 1, 1)
        file_old = datetime.datetime(2012, 1, 1, 1, 1, 1)
        file_now = datetime.datetime(2012, 1, 1, 1, 1, 1)

        data = dict(a=1, b=2, c=3)
        jdata = jsonutils.dumps(data)

        fake = FakeSchedulerOptions(last_checked, now, file_old, file_now,
                                    data, jdata)

        self.assertEqual(last_checked, fake.last_checked)
        self.assertEqual(data, fake.get_configuration('foo.json'))
        self.assertFalse(fake.file_was_loaded)
        self.assertEqual(now, fake.last_checked)

    def test_get_configuration_second_time_too_fast(self):
        # first check
        last_checked = None
        fisrt_now = datetime.datetime(2013, 1, 1, 1, 1, 2)
        file_old = datetime.datetime(2012, 1, 1, 1, 1, 1)
        file_now = datetime.datetime(2013, 1, 1, 1, 1, 1)
        old_data = dict(a=1, b=2, c=3)
        data = dict(a=11, b=12, c=13)
        jdata = jsonutils.dumps(data)
        fake = FakeSchedulerOptions(last_checked, fisrt_now, file_old,
                                    file_now, old_data, jdata)
        self.assertIsNone(fake.last_checked)
        self.assertEqual(data, fake.get_configuration('foo.json'))
        self.assertTrue(fake.file_was_loaded)
        self.assertEqual(fisrt_now, fake.last_checked)

        # second time too fast, so won't check/load again
        sec_now = datetime.datetime(2013, 1, 1, 1, 1, 3)
        fake.file_was_loaded = False
        fake._time_now = sec_now
        fake._file_data = dict(a=21, b=22, c=23)

        self.assertEqual(data, fake.get_configuration('foo.json'))
        self.assertFalse(fake.file_was_loaded)
        self.assertEqual(fisrt_now, fake.last_checked)

    def test_get_configuration_second_time_change(self):
        last_checked = datetime.datetime(2011, 1, 1, 1, 1, 1)
        now = datetime.datetime(2012, 1, 1, 1, 1, 1)
        file_old = datetime.datetime(2012, 1, 1, 1, 1, 1)
        file_now = datetime.datetime(2013, 1, 1, 1, 1, 1)

        old_data = dict(a=1, b=2, c=3)
        data = dict(a=11, b=12, c=13)
        jdata = jsonutils.dumps(data)

        fake = FakeSchedulerOptions(last_checked, now, file_old, file_now,
                                    old_data, jdata)
        self.assertEqual(last_checked, fake.last_checked)
        self.assertEqual(data, fake.get_configuration('foo.json'))
        self.assertTrue(fake.file_was_loaded)
        self.assertEqual(now, fake.last_checked)


text:
_.templateSettings.variable = "rc";
// game render
var game_template = _.template(
    $("script#game_area_template").html()
);
var game_template_data = {
    height: 640,
    width: 1136,
    ch_version: 3670
};
$('#game_template_anchor').after(game_template(game_template_data));

// load rler ancient's calc and output area
var calc_config_template = _.template(
    $("script#calc_config_template").html()
);
var calc_template = _.template(
    $("script#calc_area_template").html()
);
var calc_template_data = {};
$('#calc_template_anchor').after(calc_template(calc_template_data));
var calc_config_template_data = {};
$('#calc_config_anchor').after(calc_config_template(calc_config_template_data));

// load hero tab
var hero_template = _.template(
    $("script#hero_area_template").html()
);
var hero_template_data = {};
$('#hero_template_anchor').after(hero_template(hero_template_data));

// load chat tab
var chat_template = _.template($("script#chat_template").html());
$('#chat_template_anchor').append(chat_template());

// set up on-click for game reload button
$('#reload_flash').click(function() {
     var clone = $('#flashContent object').clone();
      $('#flashContent object').remove();
     $('#flashContent').append(clone);
});

$("#idlemode").change(function() {
  if (this.checked) {
    $("#nonidle").slideUp();
  } else {
    $("#nonidle").slideDown();
  }
});

// tryhard functioning
function hide_flash() {
  $("#flash_container").css('visibility', 'hidden');
  toggle_flash = show_flash;
}
function show_flash() {
  $("#flash_container").css('visibility', 'visible');
  toggle_flash = hide_flash;
}
var toggle_flash = hide_flash;
function toggle_flash_fn() {
  toggle_flash();
}

$("button#flash_visibility_toggle").click(toggle_flash_fn);


text:
[![Build Status](https://travis-ci.org/arnesson/cordova-plugin-firebase.svg?branch=master)](https://travis-ci.org/arnesson/cordova-plugin-firebase)

# cordova-plugin-firebase
This plugin brings push notifications, analytics, event tracking, crash reporting and more from Google Firebase to your Cordova project!  Android and iOS supported.

## Supported Cordova Versions
- cordova: `>= 6`
- cordova-android: `>= 6.4`
- cordova-ios: `>= 4`

## Installation
Install the plugin by adding it to your project's config.xml:
```
<plugin name="cordova-plugin-firebase" spec="^2.0.0" />
```
or by running:
```
cordova plugin add cordova-plugin-firebase --save
```

### Guides
Great installation and setup guide by Medium.com - [https://medium.com/@felipepucinelli/how-to-add-push...](https://medium.com/@felipepucinelli/how-to-add-push-notifications-in-your-cordova-application-using-firebase-69fac067e821)

### Setup
Download your Firebase configuration files, GoogleService-Info.plist for iOS and google-services.json for android, and place them in the root folder of your cordova project.  Check out this [firebase article](https://support.google.com/firebase/answer/7015592) for details on how to download the files.

```
- My Project/
    platforms/
    plugins/
    www/
    config.xml
    google-services.json       <--
    GoogleService-Info.plist   <--
    ...
```

###### IMPORTANT NOTES
- This plugin uses a hook (after prepare) that copies the configuration files to the right place, namely `platforms/ios/\<My Project\>/Resources` for ios and `platforms/android` for android.
- Firebase SDK requires the configuration files to be present and valid, otherwise your app will crash on boot or Firebase features won't work.

### PhoneGap Build
Hooks do not work with PhoneGap Build. This means you will have to manually make sure the configuration files are included. One way to do that is to make a private fork of this plugin and replace the placeholder config files (see `src/ios` and `src/android`) with your actual ones, as well as hard coding your app id and api key in `plugin.xml`.

### Google Play Services
Your build may fail if you are installing multiple plugins that use Google Play Services.  This is caused by the plugins installing different versions of the Google Play Services library.  This can be resolved by installing [cordova-android-play-services-gradle-release](https://github.com/dpa99c/cordova-android-play-services-gradle-release).

If your build is still failing, you can try installing [cordova-android-firebase-gradle-release](https://github.com/dpa99c/cordova-android-firebase-gradle-release).  For more info, read the following [comment](https://github.com/dpa99c/cordova-plugin-request-location-accuracy/issues/50#issuecomment-390025013) about locking down the specific versions for play services and firebase. It is suggested to use `+` instead of `15.+` to ensure the correct versions are used.

## Google Tag Manager

Checkout our [guide](docs/GOOGLE_TAG_MANAGER.md) for info on setting up Google Tag Manager.

## Configuring Notifications

Checkout our [guide](docs/NOTIFICATIONS.md) for info on configuring notification icons and colors.

## API

See the full [API](docs/API.md) available for this plugin.


text:
<?php
/**
 * Examples
 * CoreORM\Framework
 *
 */
use CoreORM\Utility\Config;
// show errors
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
// include config
$config = require_once __DIR__ . '/config.php';
Config::set($config);
debug(Config::get('debug'));


text:
package com.calendarfx.demo.entries;

import com.calendarfx.model.Entry;
import com.calendarfx.view.EntryViewBase;
import com.calendarfx.view.MonthEntryView;

import java.time.LocalDate;

public class HelloMonthEntryView extends HelloEntryViewBase {

    public HelloMonthEntryView() {
        super();

        entry.setInterval(LocalDate.now(), LocalDate.now().plusDays(5));
    }

    @Override
    protected EntryViewBase<?> createEntryView(Entry<?> entry) {
        MonthEntryView view = new MonthEntryView(entry);
        view.setPrefSize(400, 20);
        return view;
    }

    @Override
    public String getSampleName() {
        return "Month Entry View";
    }

    @Override
    protected Class<?> getJavaDocClass() {
        return MonthEntryView.class;
    }

    @Override
    public String getSampleDescription() {
        return "This view is used to display a single entry in a month view.";
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
package com.github.twitch4j.pubsub.events;

import com.github.twitch4j.common.events.TwitchEvent;
import com.github.twitch4j.pubsub.domain.PointsSpent;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
public class PointsSpentEvent extends TwitchEvent {
    private final PointsSpent data;
}


text:
package com.ickstream.protocol.service.content;

import java.util.List;

public abstract class AbstractPreferredMenu {
    private List<PreferredMenuItem> childItems;
    private PreferredMenuRequest childRequest;

    protected AbstractPreferredMenu() {
    }

    protected AbstractPreferredMenu(List<PreferredMenuItem> childItems) {
        this.childItems = childItems;
    }

    protected AbstractPreferredMenu(PreferredMenuRequest childRequest) {
        this.childRequest = childRequest;
    }

    public List<PreferredMenuItem> getChildItems() {
        return childItems;
    }

    public void setChildItems(List<PreferredMenuItem> childItems) {
        this.childItems = childItems;
    }

    public PreferredMenuRequest getChildRequest() {
        return childRequest;
    }

    public void setChildRequest(PreferredMenuRequest childRequest) {
        this.childRequest = childRequest;
    }
}


text:
Then(/^the following packages should not be installed:$/) do |table|
  table.raw.each do |row|
    row.each do |pkg|
      expect(Serverspec::Type::Package.new("#{pkg}").installed?).to equal false
    end
  end
end


text:
<?php if (!$found): ?>

Menu not found

<a href="<?php echo PathMap::build_path('sitemenus', 'index'); ?>">Return to menu list

<?php else: ?>

Create menu item

<?php
if (Messaging::has_messages()) {
	Messaging::display_messages();
}

if (!$submitted || ($submitted && Messaging::has_messages())):
?>

<a href="<?php echo PathMap::build_path('sitemenus', 'items', 'index', $menu->id); ?>">Return to menu items list

<form method="post" action="<?php echo PathMap::build_path('sitemenus', 'items', 'create', $menu->id); ?>">

		<label for="<?php echo $moduleName; ?>_itemName">
			Item name:

		<input type="text" name="<?php echo $moduleName; ?>_itemName" size="35" maxlength="100"<?php if ($submitted) { echo " value=\"{$menuItem->itemName}\""; } ?> />

		<label for="<?php echo $moduleName; ?>_path">
			Path:

		<input type="text" name="<?php echo $moduleName; ?>_path" size="35" maxlength="100"<?php if ($submitted) { echo " value=\"{$menuItem->path}\""; } ?> />

For paths local to this web site/application, the system can automatically map them. Start the path with a single / and do NOT include the application path (The application path is the part of the URL between your domain name and the start of requests if your web site/application is not at the root of the URL. ex: if the site/application was located at http://example.com/apppath, a path for http://example.com/apppath/blog/view/1 would be /blog/view/1).

		<label for="<?php echo $moduleName; ?>_weight">
			Weight:

		<select name="<?php echo $moduleName; ?>_weight">
		<?php
		for ($i = -20; $i <= 20; $i++) {
			echo "\t\t\t<option value=\"{$i}\"";
			if ($submitted && ($i == $menuItem->weight)) {
				echo ' selected="selected"';
			}
			echo ">{$i}</option>\n";
		}
		?>
		</select>

The lower the weight, the higher an item is in the menu.

		<label for="<?php echo $moduleName; ?>_parentItem">
			Parent item:

		<select name="<?php echo $moduleName; ?>_parentItem">
			<option value="">Top level</option>
			<?php
				for ($i = 0; $i < count($menu->items); $i++) {
					echo $menu->items[$i]->getItemSelectOption();
				}
			?>
		</select>

		<label for="<?php echo $moduleName; ?>_newWindow">
			Open in new window:

		<input type="checkbox" value="1" name="<?php echo $moduleName; ?>_newWindow" />

		<input type="submit" name="submitted" value="Add item" />

</form>
<?php else: ?>

Menu item "<?php echo $menuItem->itemName; ?>" has been added.

<a href="<?php echo PathMap::build_path('sitemenus', 'items', 'index', $menu->id); ?>">Return to menu items list

<?php
	endif;
endif;
?>


text:
package org.eclipse.jdt.internal.corext.refactoring.changes;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;

import org.eclipse.core.resources.IResource;

import org.eclipse.ltk.core.refactoring.Change;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;

import org.eclipse.jdt.internal.corext.refactoring.AbstractJavaElementRenameChange;
import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
import org.eclipse.jdt.internal.corext.util.Messages;

import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;

public final class RenameCompilationUnitChange extends AbstractJavaElementRenameChange {

	public RenameCompilationUnitChange(ICompilationUnit unit, String newName) {
		this(unit.getResource().getFullPath(), unit.getElementName(), newName, IResource.NULL_STAMP);
		Assert.isTrue(!unit.isReadOnly(), "compilation unit must not be read-only"); //$NON-NLS-1$
	}

	private RenameCompilationUnitChange(IPath resourcePath, String oldName, String newName, long stampToRestore) {
		super(resourcePath, oldName, newName, stampToRestore);

		setValidationMethod(VALIDATE_NOT_READ_ONLY | SAVE_IF_DIRTY);
	}

	@Override
	protected IPath createNewPath() {
		final IPath path= getResourcePath();
		if (path.getFileExtension() != null)
			return path.removeFileExtension().removeLastSegments(1).append(getNewName());
		else
			return path.removeLastSegments(1).append(getNewName());
	}

	@Override
	protected Change createUndoChange(long stampToRestore) throws JavaModelException {
		return new RenameCompilationUnitChange(createNewPath(), getNewName(), getOldName(), stampToRestore);
	}

	@Override
	protected void doRename(IProgressMonitor pm) throws CoreException {
		ICompilationUnit cu= (ICompilationUnit) getModifiedElement();
		if (cu != null)
			cu.rename(getNewName(), false, pm);
	}

	@Override
	public String getName() {
		String[] keys= new String[] { BasicElementLabels.getJavaElementName(getOldName()), BasicElementLabels.getJavaElementName(getNewName())};
		return Messages.format(RefactoringCoreMessages.RenameCompilationUnitChange_name, keys);
	}
}


text:
{% extends 'layout/styleguide.html' %}

{% set page_title = 'Support' %}

{% block content %}

{{page_title}}

This page provides info about how to get in contact with the team about the design system.

Channels

Information about the channels like Slack, e-mail or other.

Contribution

If you want to contribute on the project, just get in touch.

{% endblock %}


text:
#include <stdexcept>
#include <string>
class CMegaEyesException:public std::exception
{
public:
	CMegaEyesException(const std::string& msg, int code = 0):m_strMsg(msg),m_nCode(code)
	{

	}
	~CMegaEyesException() throw()
	{

	}
	const std::string& message() const
	{
		return m_strMsg;
	}
	const char* what() const throw()
	{
		return m_strMsg.c_str();
	}
public:
	std::string m_strMsg;
	int m_nCode;
};
#endif


text:
package api_tests

import (
	"fmt"
	"github.com/satori/go.uuid"
	. "github.com/smartystreets/goconvey/convey"
	"github.com/verdverm/frisby"
	"gopkg.in/olivere/elastic.v3"
	. "github.com/eywa/models"
	"log"
	"net/http"
	"os"
	"testing"
	"time"
)

func HttpUploadPath(channelId, deviceId string) string {
	return fmt.Sprintf("%s/channels/%s/devices/%s/upload", DeviceServer, channelId, deviceId)
}

func HttpPollingPath(channelId, deviceId string) string {
	return fmt.Sprintf("%s/channels/%s/devices/%s/poll", DeviceServer, channelId, deviceId)
}

func GetRawIndexPath(channelId string) string {
	return fmt.Sprintf("%s/channels/%s/raw", ApiServer, channelId)
}

func TestHttpConnection(t *testing.T) {

	InitializeDB()
	DB.LogMode(true)
	DB.SetLogger(log.New(os.Stdout, "", log.LstdFlags))
	DB.DropTableIfExists(&Channel{})
	DB.AutoMigrate(&Channel{})

	InitializeIndexClient()

	chId, _ := CreateTestChannel()

	Convey("successfully uploads the structed data and indexed into ES via http", t, func() {

		deviceId := "abc"
		tag1 := uuid.NewV4().String()
		data := map[string]interface{}{
			"tag1":   tag1,
			"tag2":   "monday",
			"field1": 100,
		}
		f := frisby.Create("http upload").Post(HttpUploadPath(chId, deviceId)).
			SetHeader("AccessToken", "token1").SetJson(data).Send()
		f.ExpectStatus(http.StatusOK)

		IndexClient.Refresh().Do()
		time.Sleep(3 * time.Second)

		searchRes, err := IndexClient.Search().Index("_all").Query(elastic.NewTermQuery("tag1", tag1)).Do()
		So(err, ShouldBeNil)
		So(searchRes.TotalHits(), ShouldEqual, 1)
	})

	Convey("data won't be indexed if indices.disable is enabled", t, func() {
		f := frisby.Create("disable index").SetHeader("Authentication", authStr()).
			Put(ConfigsPath()).SetJson(map[string]interface{}{"indices": map[string]interface{}{"disable": true}}).Send()
		f.ExpectStatus(http.StatusOK)

		deviceId := "abc"
		tag1 := uuid.NewV4().String()
		data := map[string]interface{}{
			"tag1":   tag1,
			"tag2":   "monday",
			"field1": 100,
		}
		f = frisby.Create("http upload").Post(HttpUploadPath(chId, deviceId)).
			SetHeader("AccessToken", "token1").SetJson(data).Send()
		f.ExpectStatus(http.StatusOK)

		IndexClient.Refresh().Do()
		time.Sleep(3 * time.Second)

		searchRes, err := IndexClient.Search().Index("_all").Query(elastic.NewTermQuery("tag1", tag1)).Do()
		So(err, ShouldBeNil)
		So(searchRes.TotalHits(), ShouldEqual, 0)

		f = frisby.Create("enable index").SetHeader("Authentication", authStr()).
			Put(ConfigsPath()).SetJson(map[string]interface{}{"indices": map[string]interface{}{"disable": false}}).Send()
		f.ExpectStatus(http.StatusOK)
	})

	DeleteTestChannel(chId)

	frisby.Global.PrintReport()
}


text:
New Features / Enhancements:

 * #190 - nsq_tail generates a random #ephemeral channel

Bug Fixes:

 * #203 - diskqueue depth accounting consistency
 * #207 - failure to write a heartbeat is fatal / reduce error log noise
 * #208 - fix travis build script
 * #206 - use broadcast address for statsd prefix
 * #205 - cleanup example utils exit

### 0.2.20 - 2013-05-13

New Features / Enhancements:

 * #197 - nsqadmin nodes list improvements (show nsqd -> lookupd conns)
 * #192 - add golang runtime version to daemon version output
 * #183 - ability to empty a topic
 * #176 - optimizations to reduce garbage, copying, locking
 * #184 - add table headers to nsqadmin channel view (thanks @elubow)
 * #174/#186 - nsq_to_http hostpool mode and backoff control
 * #173/#187 - nsq_stat utility for command line introspection
 * #175 - add nsqd --max-rdy-count configuration option
 * #178 - add nsqd --max-heartbeat-interval configuration option

Bug Fixes:

 * #198 - fix fatal errors not actually being fatal
 * #195 - fix delete topic does not delete all diskqueue files
 * #193 - fix data race in channel requeue
 * #185 - ensure that --data-path is writable on startup
 * #182 - fix topic deletion ordering to prevent race conditions with lookupd/diskqueue
 * #179 - deferred_count as gauge for statsd
 * #173/#188/#191 - fix nsqadmin counter template error; fix nsqadmin displaying negative rates

### 0.2.19 - 2013-04-11

**Upgrading from 0.2.18**: there are no backward incompatible changes in this release.

New Features / Enhancements:

 * #167 - 'go get' compatibility
 * #158 - allow nsqd clients to configure (or disable) heartbeats

Bug Fixes:

 * #171 - fix race conditions identified testing against go 1.1 (scheduler improvements)
 * #160 - empty channel left in-flight count inconsistent

### 0.2.18 - 2013-02-28

**Upgrading from 0.2.17**: all V2 clients of nsqd now receive heartbeats (previously only clients
that subscribed would receive heartbeats, excluding TCP *producers*).

**Upgrading from 0.2.16**: follow the notes in the 0.2.17 changelog for upgrading from 0.2.16.

New Features / Enhancements:

 * #131 - all V2 nsqd clients get heartbeats
 * #154 - nsq_tail example reader
 * #143 - display message rates in nsqadmin

Bug Fixes:

 * #148 - store tombstone data per registration in nsqlookupd
 * #153 - fix large graph formulas in nsqadmin
 * #150/#151 - fix topics disappearing from nsqlookupd when channels are deleted

### 0.2.17 - 2013-02-07

**Upgrading from 0.2.16**: IDENTIFY and SUB now return success responses (they previously only
responded to errors). The official Go and Python libraries are forwards/backwards compatible with
this change however 3rd party client libraries may not be.

**Upgrading from 0.2.15**: in #132 deprecations in SUB were removed as well as support for the old,
line oriented, `nsqd` metadata file format. For these reasons you should upgrade to `0.2.16` first.

New Features / Enhancements:

 * #119 - add TOUCH command to nsqd
 * #142 - add --broadcast-address flag to nsqd/nsqadmin (thanks @dustismo)
 * #135 - atomic MPUB
 * #133 - improved protocol fatal error handling and responses; IDENTIFY/SUB success responses
 * #118 - switch nsqadmin actions to POST and require confirmation
 * #117/#147 - nsqadmin action POST notifications
 * #122 - configurable msg size limits
 * #132 - deprecate identify in SUB and old nsqd metadata file format

Bug Fixes:

 * #144 - empty channel should clear inflight/deferred messages
 * #140 - fix MPUB protocol documentation
 * #139 - fix nsqadmin handling of legacy statsd prefixes for graphs
 * #138/#145 - fix nsqadmin action redirect handling
 * #134 - nsqd to nsqlookupd registration fixes
 * #129 - nsq_to_file gzip file versioning
 * #106 - nsqlookupd topic producer tombstones
 * #100 - sane handling of diskqueue read errors
 * #123/#125 - fix notify related exit deadlock

### 0.2.16 - 2013-01-07

**Upgrading from 0.2.15**: there are no backward incompatible changes in this release.

However, this release introduces the `IDENTIFY` command (which supersedes sending
metadata along with `SUB`) for clients of `nsqd`.  The old functionality will be
removed in a future release.

 * #114 persist paused channels through restart
 * #121 fix typo preventing compile of bench_reader (thanks @datastream)
 * #120 fix nsqd crash when empty command is sent (thanks @michaelhood)
 * #115 nsq_to_file --filename-format --datetime-format parameter and fix
 * #101 fix topic/channel delete operations ordering
 * #98 nsqadmin fixes when not using lookupd
 * #90/#108 performance optimizations / IDENTIFY protocol support in nsqd. For
   a single consumer of small messages (< 4k) increases throughput ~400% and
   reduces # of allocations ~30%.
 * #105 strftime compatible datetime format
 * #103 nsq_to_http handler logging
 * #102 compatibility with Go tip
 * #99 nsq_to_file --gzip flag
 * #95 proxy graphite requests through nsqadmin
 * #93 fix nqd API response for no topics
 * #92 graph rendering options
 * #86 nsq_to_http Content-Length headers
 * #89 gopkg doc updates
 * #88 move pynsq to it's own repo
 * #81/#87 reader improvements / introduced MPUB. Fix bug for mem-queue-size < 10
 * #76 statsd/graphite support
 * #75 administrative ability to create topics and channels

### 0.2.15 - 2012-10-25

 * #84 fix lookupd hanging on to ephemeral channels w/ no producers
 * #82 add /counter page to nsqadmin
 * #80 message size benchmark
 * #78 send Content-Length for nsq_to_http requests
 * #57/#83 documentation updates

### 0.2.14 - 2012-10-19

 * #77 ability to pause a channel (includes bugfix for message pump/diskqueue)
 * #74 propagate all topic changes to lookupd
 * #65 create binary releases

### 0.2.13 - 2012-10-15

 * #70 deadlined nsq_to_http outbound requests
 * #69/#72 improved nsq_to_file sync strategy
 * #58 diskqueue metadata bug and refactoring

### 0.2.12 - 2012-10-10

 * #63 consolidated protocol V1 into V2 and fixed PUB bug
 * #61 added a makefile for simpler building
 * #55 allow topic/channel names with `.`
 * combined versions for all binaries

### 0.2.7 - 0.2.11

 * Initial public release.

## Go Client Library

### 0.3.2-alpha

 * #204 - fix early termination block
 * #186 - max backoff duration of 0 disables backoff
 * #164/#202 - add Writer
 * #175 - support server side configurable max RDY count
 * #177 - support broadcast_address
 * #161 - connection pool goroutine safety

### 0.3.1 - 2013-02-07

**Upgrading from 0.3.0**: This release requires NSQ binary version `0.2.17+` for `TOUCH` support.

 * #119 - add TOUCH command
 * #133 - improved handling of errors/magic
 * #127 - send IDENTIFY (missed in #90)
 * #16 - add backoff to Reader

### 0.3.0 - 2013-01-07

**Upgrading from 0.2.4**: There are no backward incompatible changes to applications
written against the public `nsq.Reader` API.

However, there *are* a few backward incompatible changes to the API for applications that
directly use other public methods, or properties of a few NSQ data types:

`nsq.Message` IDs are now a type `nsq.MessageID` (a `[16]byte` array).  The signatures of
`nsq.Finish()` and `nsq.Requeue()` reflect this change.

`nsq.SendCommand()` and `nsq.Frame()` were removed in favor of `nsq.SendFramedResponse()`.

`nsq.Subscribe()` no longer accepts `shortId` and `longId`.  If upgrading your consumers
before upgrading your `nsqd` binaries to `0.2.16-rc.1` they will not be able to send the
optional custom identifiers.

 * #90 performance optimizations
 * #81 reader performance improvements / MPUB support

### 0.2.4 - 2012-10-15

 * #69 added IsStarved() to reader API

### 0.2.3 - 2012-10-11

 * #64 timeouts on reader queries to lookupd
 * #54 fix crash issue with reader cleaning up from unexpectedly closed nsqd connections

### 0.2.2 - 2012-10-09

 * Initial public release

## pynsq Python Client Library

 * #88 moved **pynsq** to its own [repository](https://github.com/bitly/pynsq).


text:
package com.xti.jenkins.plugin.awslambda.exception;

public class AWSLambdaPluginException extends RuntimeException {
    public AWSLambdaPluginException(String message) {
        super(message);
    }

    public AWSLambdaPluginException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
import React from "react"

import LoginTooltip from "./LoginTooltip"

import { preventDefaultAndInvoke, userIsAnonymous } from "../lib/util"

import type { Post } from "../flow/discussionTypes"

type Props = {
  post: Post,
  toggleFollowPost: Post => void
}

const FollowButton = ({ toggleFollowPost, post }: Props) => (
  <LoginTooltip>
    {post.subscribed ? (

 {
          toggleFollowPost(post)
        })}
      >
        rss_feed
        Unfollow

    ) : (

 {
          userIsAnonymous() ? null : toggleFollowPost(post)
        })}
      >
        rss_feed
        Follow

    )}
  </LoginTooltip>
)

export default FollowButton


text:
package components

import (
	"k8s.io/kops/pkg/apis/kops"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/upup/pkg/fi/loader"
)

// DockerOptionsBuilder adds options for docker to the model
type DockerOptionsBuilder struct {
	*OptionsContext
}

var _ loader.OptionsBuilder = &DockerOptionsBuilder{}

// BuildOptions is responsible for filling in the default setting for docker daemon
func (b *DockerOptionsBuilder) BuildOptions(o interface{}) error {
	clusterSpec := o.(*kops.ClusterSpec)

	if clusterSpec.Docker == nil {
		clusterSpec.Docker = &kops.DockerConfig{}
	}

	docker := clusterSpec.Docker

	// Container runtime is not Docker, should not install
	if clusterSpec.ContainerRuntime != "docker" {
		docker.SkipInstall = true
		return nil
	}

	// Set the Docker version for known Kubernetes versions
	if fi.ValueOf(clusterSpec.Docker.Version) == "" {
		docker.Version = fi.PtrTo("20.10.17")
	}

	if len(clusterSpec.Docker.LogOpt) == 0 && clusterSpec.Docker.LogDriver == nil {
		// Use built-in docker logging, if not configured otherwise (by the user)
		logDriver := "json-file"
		clusterSpec.Docker.LogDriver = &logDriver
		clusterSpec.Docker.LogOpt = append(clusterSpec.Docker.LogOpt, "max-size=10m")
		clusterSpec.Docker.LogOpt = append(clusterSpec.Docker.LogOpt, "max-file=5")
	}

	docker.LogLevel = fi.PtrTo("info")
	docker.IPTables = fi.PtrTo(false)
	docker.IPMasq = fi.PtrTo(false)

	// Note the alternative syntax... with a comma nodeup will try each of the filesystems in turn
	// TODO(justinsb): The ContainerOS image now has docker configured to use overlay2 out-of-the-box
	// and it is an error to specify the flag twice.
	docker.Storage = fi.PtrTo("overlay2,overlay,aufs")

	// Set systemd as the default cgroup driver in docker from k8s 1.20.
	if getDockerCgroupDriver(docker.ExecOpt) == "" {
		docker.ExecOpt = append(docker.ExecOpt, "native.cgroupdriver=systemd")
	}

	return nil
}

// checks if cgroup-driver is configured or not for docker or not.
func getDockerCgroupDriver(execOpts []string) string {
	for _, value := range execOpts {
		if value == "native.cgroupdriver=systemd" {
			return "systemd"
		} else if value == "native.cgroupdriver=cgroupfs" {
			return "cgroupfs"
		}
	}

	return ""
}


text:
<?php
/**
 * BjyAuthorize Module (https://github.com/bjyoungblood/BjyAuthorize)
 *
 * @link https://github.com/bjyoungblood/BjyAuthorize for the canonical source repository
 * @license http://framework.zend.com/license/new-bsd New BSD License
 */

namespace BjyAuthorize\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use BjyAuthorize\Service\Authorize;

/**
 * Role View helper. Allows checking access to a resource/privilege in views.
 *
 * @author Ben Youngblood <bx.youngblood@gmail.com>
 */
class Role extends AbstractPlugin
{
    /**
     * @var Authorize
     */
    protected $authorizeService;

    /**
     * @param Authorize $authorizeService
     */
    public function __construct(Authorize $authorizeService)
    {
        $this->authorizeService = $authorizeService;
    }

    /**
     * @param mixed      $resource
     * @param mixed|null $privilege
     *
     * @return bool
     */
    public function __invoke()
    {
		$role = $this->authorizeService->getIdentityProvider()->getIdentityRoles();
		return $role[0];
    }
}


text:
#ifndef __SEMT_DIFFERENTIABLE_VECTOR_EXPR__H__
#define __SEMT_DIFFERENTIABLE_VECTOR_EXPR__H__

#include "Forwards.h"
#if 0

namespace SEMT
{
namespace intern
{
/*!
 * @addtogroup dev
 * @{
 */

/*!
 * Bridge between template expressions and homogeneous function objects.
 * Employed by VectorExpr to store different expressions in a homogeneous container.
 * Instantiated by DVEHelper and DifferentiableVectorExpr.\ņ
 * Carries no value, only the virtual table.
 * @tparam expr The expression this object will evaluate.
 */
template<typename expr>
struct ConcreteFunctionObject : public AbstractFunctionObject
{
    /// Virtual cloning.
    virtual SEMT_INLINE_VIRTUAL std::auto_ptr<AbstractFunctionObject> duplicate() const
    {
        return std::auto_ptr<AbstractFunctionObject>(new ConcreteFunctionObject<expr>);
    }

    /// Evaluation is forwarded to expr's Expr::apply(Array).
    virtual SEMT_INLINE_VIRTUAL SEMT_PRECISION operator()(CAR x) const
                                                          {
        return expr::apply(x);
    }

#if SEMT_DISABLE_PRINT == 0
    /// Forward to expr's static Expr::toString().
    virtual SEMT_INLINE_VIRTUAL std::string toString() const
    {
        return expr::toString();
    }
#endif // SEMT_DISABLE_PRINT
};

/*!
 * Helper to instantiate all derivatives of a single expression.
 * This is done by a two-step recursion and here is the main case:
 * recurse over vars and differentiation depth.
 * @tparam  e       Expression to differentiate.
 * @tparam  vars    Number of variables to be differentiated for.
 * @tparam  deriv_order Maximum differentiation order.
 * @attention   If current_depth > deriv_order or current_var > vars,
 *              we'll end up in an infinite recursion.
 * @see     DifferentiableVectorExpr
 */
template<typename e, size_t vars, size_t deriv_order,
        size_t current_var = 0, size_t current_depth = 1>
struct DVEHelper
{
    /// Differentiate e in respect to Variable<current_var>.
    typedef SEMT_SIMPLE_TYPE2(e::template partial<Variable<current_var> >::deriv) e_d_;
    typedef typename RecursiveSimplifier<e_d_>::Result e_d;
    /*!
     * Append derivatives in appropriate order into data.
     * @param   data    Size must be greater or equal deriv_order.
     */
    static SEMT_INLINE_STATIC void push_back(std::vector<VectorExpr>& data)
    {
        // push back current derivative
        data[current_depth].push_back(new ConcreteFunctionObject<e_d>);
        // start recursion to push back higher derivatives
        DVEHelper<e_d, vars, deriv_order, 0, current_depth + 1 >::push_back(data);
        // start recursion to push back derivatives with respect to next variables
        DVEHelper<e, vars, deriv_order, current_var + 1, current_depth>::push_back(data);
    }
};

/*!
 * Stop recursing the variables.
 * @see DVEHelper
 */
template<typename e, size_t vars, size_t deriv_order, size_t current_depth>
struct DVEHelper<e, vars, deriv_order, vars, current_depth>
{
    static SEMT_INLINE_STATIC void push_back(std::vector<VectorExpr>& data)
    {
    }
    //The Variables are counted from 0 to end-1, while the user will count them from
    //1 to end, so at this point there is nothing left to be done.
};

/*!
 * Stop recursing differentiation depth.
 * @see DVEHelper
 */
template<typename e, size_t vars, size_t deriv_order, size_t current_var>
struct DVEHelper<e, vars, deriv_order, current_var, deriv_order>
{
    typedef SEMT_SIMPLE_TYPE2(e::template partial<Variable<current_var> >::deriv) e_d_;
    typedef typename RecursiveSimplifier<e_d_>::Result e_d;
    static SEMT_INLINE_STATIC void push_back(std::vector<VectorExpr>& data)
    {
        // push back current derivative
        data[deriv_order].push_back(new ConcreteFunctionObject<e_d>);
        // this is the highest differentiation order, so we only need to push back
        // the derivatives with respect to the remaining variables
        DVEHelper<e, vars, deriv_order, current_var + 1, deriv_order>::push_back(data);
    }
};

/*!
 * Stop whole recursion.
 * @see DVEHelper
 */
template<typename e, size_t vars, size_t deriv_order>
struct DVEHelper<e, vars, deriv_order, vars, deriv_order>
{
    static SEMT_INLINE_STATIC void push_back(std::vector<VectorExpr>& data)
    {
    }
};

/*!
 * Special case if differentiation order is zero.
 * @see DVEHelper
 */
template<typename e, size_t vars>
struct DVEHelper<e, vars, 0, 0>
{
    static SEMT_INLINE_STATIC void push_back(std::vector<VectorExpr>& data)
    {
    }
};

/// @}

}// namespace intern

/*!
 * Construct mappings R^n --> R^m and their derivatives step by step.
 * This class is the gateway to the non-template realms of VectorExpr.\n
 * The first derivative is stored in the form: (Jacobian expanded row by row)\n
 * (df0/dx0, df0/dx1, ..., df0/dxn, df1/dx0, df2/dx1. ..., df2/dxn, ... ..., dfm/dx0, ..., dfm/dxn).\n
 * Take this as a map R^n --> R^(n*m) and obtain the form of 2nd derivative by the same rule and so on.
 * @tparam  vars    Number of variables to differentiate for. ( = n)
 * @tparam  deriv_order Number of derivatives to calculate.
 * @note    Be aware of the complexity you demand: template instantiation depth may increase
 *          rapidly for certain expressions.
 * @see     @ref example
 * @ingroup api
 */
template<size_t vars, size_t deriv_order = 1>
class DifferentiableVectorExpr
{
    // _data[i] contains the i-th derivative of this function
    std::vector<VectorExpr> _data;
    DifferentiableVectorExpr& operator=(const DifferentiableVectorExpr& rhs);
    public:
    DifferentiableVectorExpr() :
            _data(deriv_order + 1, VectorExpr(vars))
    {
    }

    /*!
     * Set to a single expression, also used for comma initialization.
     */
    template<typename expr>
    DifferentiableVectorExpr& operator=(const Expr<expr>& ex)
    {
        _data = std::vector<VectorExpr>(deriv_order + 1, VectorExpr(vars));
        push_back(ex);
        return *this;
    }

    /*!
     * Append a component to this vector, as a side effect, the derivatives are also appended.
     * @tparam  e   The type of the component.
     * @param   ex  An instance of this type.
     * @attention   If you put more variables in the expressions then you told me,
     *              I don't care. It's your fault.
     */
    template<typename expr>
    SEMT_INLINE void push_back(const Expr<expr>& ex = Expr<expr>())
    {
        typedef typename RecursiveSimplifier<expr>::Result e_simpl;
        //push back this expression:
        _data[0].push_back(new intern::ConcreteFunctionObject<SEMT_SIMPLE_TYPE(e_simpl)>);
        //start recursion to push back the derivatives:
        intern::DVEHelper<SEMT_SIMPLE_TYPE(e_simpl), vars, deriv_order>::push_back(_data);
    }

    /*!
     * After you're done appending components, get all the derivatives you want.
     * @param   i   The derivatives order, default is the function itself.
     * @return  A reference to a VectorExpr, which hould be valid as long as this object.
     * @attention   Thou shall not ask for more than deriv_order.
     * @note    You are leaving the template realms.
     */
    const VectorExpr& get_derivative(size_t i = 0)
    {
        assert((i <= deriv_order) && "Increase template argument to obtain higher derivatives.");
        return _data[i];
    }

    const VectorExpr& get_function()
    {
        return _data[0];
    }

    /*!
     * Calculate all the expressions for a given vector of unknowns.
     * @param   x       Values for the unknown.
     * @param   res     Vector to store results. Size must be at least size().
     */
    SEMT_INLINE void eval(CAR x, Array& res) const
    {
        _data[0].eval(x, res);
    }

    /*!
     * Calculate all the expressions for a given vector of unknowns.
     * @param   x       Values for the unknown.
     * @return  Vector with the results.
     */
    SEMT_INLINE Array operator()(CAR x) const
    {
        return _data[0](x);
    }

    /*!
     * Syntactic sugar, see the Example for usage.
     */
    template<typename expr>
    DifferentiableVectorExpr& operator ,(const Expr<expr>& e)
    {
        push_back(e);
        return *this;
    }
};

} // namesapce SEMT

#endif // __SEMT_DIFFERENTIABLE_VECTOR_EXPR__H__
#endif