text:
var event = require('./event')

// FluffBot class initialisation
var FluffBot = function Constructor() {
	this.settings = require('../config/settings')
	this.commands = require('../config/commands')
}

// Check if message is a command
FluffBot.prototype._runCommand = function(message) {

	var content = message.content

	if (typeof(message.mentions[0]) == 'undefined') {
		var mention = ''
	} else {
		var mention = message.mentions[0].username
	}

	var command = content.split(' ')[0].replace('!', '')
	this.getCommand(message, command, this._needsHelp(content), this._mentionsOwner(mention), this._mentionsFluffBot(mention))
}

// Check if FluffBot is mentioned
FluffBot.prototype._mentionsFluffBot = function(message) {
	return message.indexOf(this.settings.name) > -1
}

// Check if owner is mentioned
FluffBot.prototype._mentionsOwner = function(message) {
	return message.indexOf(this.settings.owner) > -1
}

// Check if help is needed
FluffBot.prototype._needsHelp = function(message) {
	return message.indexOf('help') > -1
}

// Get the current command / expand for DB at a later date
FluffBot.prototype.getCommand = function(message, command, help, owner, bot) {

	var inFile = typeof(this.commands[command])

	if (inFile != 'undefined' && !help) {
		this.getResponse(message, command, owner, bot)
	}

	if (inFile != 'undefined' && help) {
		this.getHelp(message, command)
	}

}

// Grab the response to send back
FluffBot.prototype.getResponse = function(message, command, owner, bot) {

	var hasFile = typeof(this.commands[command]['file'])

	if (hasFile == 'undefined') {
		event.bus.sendEvent('response', message, this.commands[command]['response'])
	}

	if (hasFile != 'undefined') {
		var commands = require(this.commands[command]['file'])
		commands = new commands(message, owner, bot, this.settings)
		commands.run()
	}

}

// Help is handled here
FluffBot.prototype.getHelp = function(message, command) {
	 event.bus.sendEvent('response', message, this.commands[command]['help']+' | '+this.commands[command]['description'])
}

module.exports = FluffBot


text:
import os
import skimage as si
import skimage.io as sio
import numpy as np

from numpy.testing import *
from numpy.testing.decorators import skipif
from tempfile import NamedTemporaryFile

try:
    import skimage.io._plugins.freeimage_plugin as fi
    FI_available = True
    sio.use_plugin('freeimage')
except RuntimeError:
    FI_available = False

np.random.seed(0)

def setup_module(self):
    """The effect of the `plugin.use` call may be overridden by later imports.
    Call `use_plugin` directly before the tests to ensure that freeimage is
    used.

    """
    try:
        sio.use_plugin('freeimage')
    except RuntimeError:
        pass

def teardown():
    sio.reset_plugins()

@skipif(not FI_available)
def test_imread():
    img = sio.imread(os.path.join(si.data_dir, 'color.png'))
    assert img.shape == (370, 371, 3)
    assert all(img[274, 135] == [0, 130, 253])

@skipif(not FI_available)
def test_imread_truncated_jpg():
    assert_raises((RuntimeError, ValueError),
                  sio.imread,
                  os.path.join(si.data_dir, 'truncated.jpg'))

@skipif(not FI_available)
def test_imread_uint16():
    expected = np.load(os.path.join(si.data_dir, 'chessboard_GRAY_U8.npy'))
    img = sio.imread(os.path.join(si.data_dir, 'chessboard_GRAY_U16.tif'))
    assert img.dtype == np.uint16
    assert_array_almost_equal(img, expected)

@skipif(not FI_available)
def test_imread_uint16_big_endian():
    expected = np.load(os.path.join(si.data_dir, 'chessboard_GRAY_U8.npy'))
    img = sio.imread(os.path.join(si.data_dir, 'chessboard_GRAY_U16B.tif'))
    assert img.dtype == np.uint16
    assert_array_almost_equal(img, expected)

@skipif(not FI_available)
def test_write_multipage():
    shape = (64, 64, 64)
    x = np.ones(shape, dtype=np.uint8) * np.random.rand(*shape) * 255
    x = x.astype(np.uint8)
    f = NamedTemporaryFile(suffix='.tif')
    fname = f.name
    f.close()
    fi.write_multipage(x, fname)
    y = fi.read_multipage(fname)
    assert_array_equal(x, y)

class TestSave:
    def roundtrip(self, dtype, x, suffix):
        f = NamedTemporaryFile(suffix='.' + suffix)
        fname = f.name
        f.close()
        sio.imsave(fname, x)
        y = sio.imread(fname)
        assert_array_equal(y, x)

    @skipif(not FI_available)
    def test_imsave_roundtrip(self):
        for shape, dtype, format in [
              [(10, 10), (np.uint8, np.uint16), ('tif', 'png')],
              [(10, 10), (np.float32,), ('tif',)],
              [(10, 10, 3), (np.uint8, np.uint16), ('png',)],
              [(10, 10, 4), (np.uint8, np.uint16), ('png',)]
            ]:
            tests = [(d, f) for d in dtype for f in format]
            for d, f in tests:
                x = np.ones(shape, dtype=d) * np.random.rand(*shape)
                if not np.issubdtype(d, float):
                    x = (x * 255).astype(d)
                yield self.roundtrip, d, x, f

@skipif(not FI_available)
def test_metadata():
    meta = fi.read_metadata(os.path.join(si.data_dir, 'multipage.tif'))
    assert meta[('EXIF_MAIN', 'Orientation')] == 1
    assert meta[('EXIF_MAIN', 'Software')].startswith('I')

    meta = fi.read_multipage_metadata(os.path.join(si.data_dir,
                                                   'multipage.tif'))
    assert len(meta) == 2
    assert meta[0][('EXIF_MAIN', 'Orientation')] == 1
    assert meta[1][('EXIF_MAIN', 'Software')].startswith('I')

if __name__ == "__main__":
    run_module_suite()

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using System.Collections.Generic;

namespace NetCoreStack.Hisar
{
    internal class NameSpaceRoutingConvention : IApplicationModelConvention
    {
        private readonly RunningComponentHelper _componentHelper;
        public NameSpaceRoutingConvention(RunningComponentHelper componentHelper)
        {
            _componentHelper = componentHelper;
        }

        public void Apply(ApplicationModel application)
        {
            foreach (var controllerModel in application.Controllers)
            {
                var componentId = controllerModel.ControllerType.Assembly.GetComponentId();
                if (_componentHelper.ComponentId == componentId)
                    continue;

                var attribute = new HisarRouteAttribute(componentId);
                var routeModel = new AttributeRouteModel(attribute)
                {
                    Name = componentId
                };

                controllerModel.Selectors[0].AttributeRouteModel = routeModel;
                if (controllerModel.Attributes is List<object> attributes)
                {
                    attributes.Add(attribute);
                }

                if (!controllerModel.RouteValues.ContainsKey("area"))
                {
                    controllerModel.RouteValues.Add("area", componentId);
                }
            }
        }
    }
}


text:
package org.apereo.cas.services;

import org.apereo.cas.support.events.service.CasRegisteredServiceLoadedEvent;

import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Collection;
import java.util.regex.Pattern;

/**
 *
Implementation of {@code ServiceRegistry} that uses a MongoDb repository as the backend
 * persistence mechanism. The repository is configured by the Spring application context.

 *
The class will automatically create a default collection to use with services. The name
 * of the collection may be specified.
 * It also presents the ability to drop an existing collection and start afresh.
 *
 * @author Misagh Moayyed
 * @since 4.1
 */
@Slf4j
@ToString
@RequiredArgsConstructor
public class MongoDbServiceRegistry extends AbstractServiceRegistry {

    private final MongoOperations mongoTemplate;
    private final String collectionName;

    @Override
    public boolean delete(final RegisteredService svc) {
        if (this.findServiceById(svc.getId()) != null) {
            this.mongoTemplate.remove(svc, this.collectionName);
            LOGGER.debug("Removed registered service: [{}]", svc);
            return true;
        }
        return false;
    }

    @Override
    public RegisteredService findServiceById(final long svcId) {
        return this.mongoTemplate.findOne(new Query(Criteria.where("id").is(svcId)), RegisteredService.class, this.collectionName);
    }

    @Override
    public RegisteredService findServiceById(final String id) {
        val pattern = Pattern.compile(id, Pattern.CASE_INSENSITIVE);
        return this.mongoTemplate.findOne(new Query(Criteria.where("serviceId").regex(pattern)), RegisteredService.class, this.collectionName);
    }

    @Override
    public Collection<RegisteredService> load() {
        val list = this.mongoTemplate.findAll(RegisteredService.class, this.collectionName);
        list.forEach(s -> publishEvent(new CasRegisteredServiceLoadedEvent(this, s)));
        return list;
    }

    @Override
    public RegisteredService save(final RegisteredService svc) {
        if (svc.getId() == AbstractRegisteredService.INITIAL_IDENTIFIER_VALUE) {
            svc.setId(svc.hashCode());
        }
        this.mongoTemplate.save(svc, this.collectionName);
        LOGGER.debug("Saved registered service: [{}]", svc);
        return this.findServiceById(svc.getId());
    }

    @Override
    public long size() {
        return this.mongoTemplate.count(new Query(), RegisteredService.class, this.collectionName);
    }
}


text:
package com.cscs.model.util;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletResponse;

public class CacheControlPhaseListener implements PhaseListener {
	private static final long serialVersionUID = 1L;

	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

	public void afterPhase(PhaseEvent event) {
	}

	public void beforePhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		HttpServletResponse response = (HttpServletResponse) facesContext
				.getExternalContext().getResponse();
		response.addHeader("Pragma", "no-cache");
		response.addHeader("Cache-Control", "no-cache");
		// Stronger according to blog comment below that references HTTP spec
		response.addHeader("Cache-Control", "no-store");
		response.addHeader("Cache-Control", "must-revalidate");
		// some date in the past
		response.addHeader("Expires", "Mon, 31 Jan 2011 12:00:00 GMT");
	}

}


text:
.. VoiceBase documentation master file, created by jbocharov on 2016-12-01

Welcome to VoiceBase /v3 API Docs
=======================================

Please access our most up to date documentation `here <https://docs.voicebase.com>`_

`VoiceBase <https://www.voicebase.com>`_ provides an API for speech recognition and analytics for developers looking to get the most from their audio and video data.

If you are getting started, we recommend the `Hello World Developer guide <how-to-guides/hello-world.html>`_  as a practical primer, and the `API Overview <overview/api_overview.html>`_ as a high-level introduction.

More information and guidance can be found in the:

* :ref:`how-to-guides`
* :ref:`api-reference`
* `VoiceBase account <https://app.voicebase.com>`_

.. _overview-section:

.. toctree::
  :maxdepth: 2
  :caption: Overview

  overview/api_overview

.. _how-to-guides:

.. toctree::
  :maxdepth: 2
  :caption: How-To Guides

  how-to-guides/hello-world
  how-to-guides/transcripts
  how-to-guides/aligner
  how-to-guides/analytics-workbench
  how-to-guides/callbacks
  how-to-guides/categories
  how-to-guides/closed-captioning
  how-to-guides/conversation-metrics
  how-to-guides/custom-vocabulary
  how-to-guides/entities
  how-to-guides/formatting
  how-to-guides/keywords-and-topics
  how-to-guides/keyword-spotting
  how-to-guides/languages
  how-to-guides/metadata
  how-to-guides/pci-ssn-pii-detection
  how-to-guides/pci-ssn-pii-redaction
  how-to-guides/player
  how-to-guides/predictions
  how-to-guides/priority
  how-to-guides/reprocessing
  how-to-guides/search
  how-to-guides/sentiment-by-turn
  how-to-guides/speech-engine
  how-to-guides/stereo
  how-to-guides/swagger-codegen
  how-to-guides/swearwords
  how-to-guides/ttl
  how-to-guides/transcoding
  how-to-guides/verb-noun
  how-to-guides/voice-features

.. _security-how-to:

.. toctree::
  :maxdepth: 2
  :caption: Security Reference

  how-to-guides/client-supplied-encryption
  how-to-guides/https-request-security

.. _api-reference:

.. toctree::
   :maxdepth: 3
   :caption: API Reference

   api-reference/media
   api-reference/definitions
   api-reference/profile

.. _data-formats:

.. toctree::
   :maxdepth: 3
   :caption: Data Formats

   data-formats/configuration
   data-formats/media

.. _api-error-codes:

.. toctree::
   :maxdepth: 2
   :caption: API Error Codes

   errors/errors

.. _developer-portal:

.. toctree::
   :maxdepth: 2
   :caption: Developer Portal

   Create Account<https://www.voicebase.com/request-api-access/>
   US Customer login<https://developer.voicebase.com>
   EU Customer login<https://developer.eu.voicebase.com>

.. _help-center:

.. toctree::
   :maxdepth: 2
   :caption: Help Center

   FAQ<https://support.voicebase.com/>

.. _license-:

.. toctree::
   :maxdepth: 2
   :caption: License

   license


text:
#ifndef __MDP5_KMS_H__
#define __MDP5_KMS_H__

#include "msm_drv.h"
#include "msm_kms.h"
#include "mdp/mdp_kms.h"
#include "mdp5_cfg.h"	/* must be included before mdp5.xml.h */
#include "mdp5.xml.h"
#include "mdp5_ctl.h"
#include "mdp5_smp.h"

struct mdp5_kms {
	struct mdp_kms base;

	struct drm_device *dev;

	struct mdp5_cfg_handler *cfg;
	uint32_t caps;	/* MDP capabilities (MDP_CAP_XXX bits) */

	/* mapper-id used to request GEM buffer mapped for scanout: */
	int id;
	struct msm_mmu *mmu;

	struct mdp5_smp *smp;
	struct mdp5_ctl_manager *ctlm;

	/* io/register spaces: */
	void __iomem *mmio, *vbif;

	struct regulator *vdd;

	struct clk *axi_clk;
	struct clk *ahb_clk;
	struct clk *src_clk;
	struct clk *core_clk;
	struct clk *lut_clk;
	struct clk *vsync_clk;

	/*
	 * lock to protect access to global resources: ie., following register:
	 *	- REG_MDP5_MDP_DISP_INTF_SEL
	 */
	spinlock_t resource_lock;

	struct mdp_irq error_handler;

	struct {
		volatile unsigned long enabled_mask;
		struct irq_domain *domain;
	} irqcontroller;
};
#define to_mdp5_kms(x) container_of(x, struct mdp5_kms, base)

struct mdp5_plane_state {
	struct drm_plane_state base;

	/* aligned with property */
	uint8_t premultiplied;
	uint8_t zpos;
	uint8_t alpha;

	/* assigned by crtc blender */
	enum mdp_mixer_stage_id stage;

	/* some additional transactional status to help us know in the
	 * apply path whether we need to update SMP allocation, and
	 * whether current update is still pending:
	 */
	bool mode_changed : 1;
	bool pending : 1;
};
#define to_mdp5_plane_state(x) \
		container_of(x, struct mdp5_plane_state, base)

enum mdp5_intf_mode {
	MDP5_INTF_MODE_NONE = 0,

	/* Modes used for DSI interface (INTF_DSI type): */
	MDP5_INTF_DSI_MODE_VIDEO,
	MDP5_INTF_DSI_MODE_COMMAND,

	/* Modes used for WB interface (INTF_WB type):  */
	MDP5_INTF_WB_MODE_BLOCK,
	MDP5_INTF_WB_MODE_LINE,
};

struct mdp5_interface {
	int num; /* display interface number */
	enum mdp5_intf_type type;
	enum mdp5_intf_mode mode;
};

static inline void mdp5_write(struct mdp5_kms *mdp5_kms, u32 reg, u32 data)
{
	msm_writel(data, mdp5_kms->mmio + reg);
}

static inline u32 mdp5_read(struct mdp5_kms *mdp5_kms, u32 reg)
{
	return msm_readl(mdp5_kms->mmio + reg);
}

static inline const char *pipe2name(enum mdp5_pipe pipe)
{
	static const char *names[] = {
#define NAME(n) [SSPP_ ## n] = #n
		NAME(VIG0), NAME(VIG1), NAME(VIG2),
		NAME(RGB0), NAME(RGB1), NAME(RGB2),
		NAME(DMA0), NAME(DMA1),
		NAME(VIG3), NAME(RGB3),
#undef NAME
	};
	return names[pipe];
}

static inline int pipe2nclients(enum mdp5_pipe pipe)
{
	switch (pipe) {
	case SSPP_RGB0:
	case SSPP_RGB1:
	case SSPP_RGB2:
	case SSPP_RGB3:
		return 1;
	default:
		return 3;
	}
}

static inline uint32_t intf2err(int intf_num)
{
	switch (intf_num) {
	case 0:  return MDP5_IRQ_INTF0_UNDER_RUN;
	case 1:  return MDP5_IRQ_INTF1_UNDER_RUN;
	case 2:  return MDP5_IRQ_INTF2_UNDER_RUN;
	case 3:  return MDP5_IRQ_INTF3_UNDER_RUN;
	default: return 0;
	}
}

#define GET_PING_PONG_ID(layer_mixer)	((layer_mixer == 5) ? 3 : layer_mixer)
static inline uint32_t intf2vblank(int lm, struct mdp5_interface *intf)
{
	/*
	 * In case of DSI Command Mode, the Ping Pong's read pointer IRQ
	 * acts as a Vblank signal. The Ping Pong buffer used is bound to
	 * layer mixer.
	 */

	if ((intf->type == INTF_DSI) &&
			(intf->mode == MDP5_INTF_DSI_MODE_COMMAND))
		return MDP5_IRQ_PING_PONG_0_RD_PTR << GET_PING_PONG_ID(lm);

	if (intf->type == INTF_WB)
		return MDP5_IRQ_WB_2_DONE;

	switch (intf->num) {
	case 0:  return MDP5_IRQ_INTF0_VSYNC;
	case 1:  return MDP5_IRQ_INTF1_VSYNC;
	case 2:  return MDP5_IRQ_INTF2_VSYNC;
	case 3:  return MDP5_IRQ_INTF3_VSYNC;
	default: return 0;
	}
}

static inline uint32_t lm2ppdone(int lm)
{
	return MDP5_IRQ_PING_PONG_0_DONE << GET_PING_PONG_ID(lm);
}

int mdp5_disable(struct mdp5_kms *mdp5_kms);
int mdp5_enable(struct mdp5_kms *mdp5_kms);

void mdp5_set_irqmask(struct mdp_kms *mdp_kms, uint32_t irqmask,
		uint32_t old_irqmask);
void mdp5_irq_preinstall(struct msm_kms *kms);
int mdp5_irq_postinstall(struct msm_kms *kms);
void mdp5_irq_uninstall(struct msm_kms *kms);
irqreturn_t mdp5_irq(struct msm_kms *kms);
int mdp5_enable_vblank(struct msm_kms *kms, struct drm_crtc *crtc);
void mdp5_disable_vblank(struct msm_kms *kms, struct drm_crtc *crtc);
int mdp5_irq_domain_init(struct mdp5_kms *mdp5_kms);
void mdp5_irq_domain_fini(struct mdp5_kms *mdp5_kms);

uint32_t mdp5_plane_get_flush(struct drm_plane *plane);
void mdp5_plane_complete_flip(struct drm_plane *plane);
void mdp5_plane_complete_commit(struct drm_plane *plane,
	struct drm_plane_state *state);
enum mdp5_pipe mdp5_plane_pipe(struct drm_plane *plane);
struct drm_plane *mdp5_plane_init(struct drm_device *dev,
		enum mdp5_pipe pipe, bool private_plane,
		uint32_t reg_offset, uint32_t caps);

uint32_t mdp5_crtc_vblank(struct drm_crtc *crtc);

int mdp5_crtc_get_lm(struct drm_crtc *crtc);
void mdp5_crtc_cancel_pending_flip(struct drm_crtc *crtc, struct drm_file *file);
void mdp5_crtc_set_pipeline(struct drm_crtc *crtc,
		struct mdp5_interface *intf, struct mdp5_ctl *ctl);
void mdp5_crtc_wait_for_commit_done(struct drm_crtc *crtc);
struct drm_crtc *mdp5_crtc_init(struct drm_device *dev,
		struct drm_plane *plane, int id);

struct drm_encoder *mdp5_encoder_init(struct drm_device *dev,
		struct mdp5_interface *intf, struct mdp5_ctl *ctl);
int mdp5_encoder_set_split_display(struct drm_encoder *encoder,
					struct drm_encoder *slave_encoder);

#ifdef CONFIG_DRM_MSM_DSI
struct drm_encoder *mdp5_cmd_encoder_init(struct drm_device *dev,
		struct mdp5_interface *intf, struct mdp5_ctl *ctl);
int mdp5_cmd_encoder_set_split_display(struct drm_encoder *encoder,
					struct drm_encoder *slave_encoder);
#else
static inline struct drm_encoder *mdp5_cmd_encoder_init(struct drm_device *dev,
		struct mdp5_interface *intf, struct mdp5_ctl *ctl)
{
	return ERR_PTR(-EINVAL);
}
static inline int mdp5_cmd_encoder_set_split_display(
	struct drm_encoder *encoder, struct drm_encoder *slave_encoder)
{
	return -EINVAL;
}
#endif

#endif /* __MDP5_KMS_H__ */


text:
<?php

namespace PhpBench\Tests\Functional\Report\Generator;

use PhpBench\Benchmark\SuiteDocument;

class ConsoleTabularCustomGeneratorTest extends ConsoleTestCase
{
    protected function getGenerator()
    {
        $generator = $this->getContainer()->get('report_generator.tabular_custom');
        $generator->setOutput($this->getOutput());

        return $generator;
    }

    /**
     * It should generate a report from a Tabular JSON file.
     */
    public function testDefault()
    {
        $this->generate(
            $this->getSuiteDocument(),
            array('file' => __DIR__ . '/reports/test.json')
        );

        $output = $this->getOutput()->fetch();
        $this->assertContains('This is a test', $output);
    }

    /**
     * It should throw an exception if the file is not found.
     *
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage not exist
     */
    public function testNotFoundFile()
    {
        $this->generate(
            $this->getSuiteDocument(),
            array('file' => __DIR__ . '/reports/not_existing_test.json')
        );
    }

    /**
     * It should thow an exception if no file is provided.
     *
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage You must provide the path
     */
    public function testNoPathGiven()
    {
        $this->generate(
            $this->getSuiteDocument(),
            array()
        );
    }

    private function getSuiteDocument()
    {
        $suite = new SuiteDocument();
        $suite->loadXml(<<<EOT
<?xml version="1.0"?>
<phpbench version="0.x">
    <benchmark class="Foobar">
        <subject name="mySubject">
            <variant>
                <parameter name="foo" value="bar" />
                <parameter name="array" type="collection">
                    <parameter name="0" value="one" />
                    <parameter name="1" value="two" />
                </parameter>
                <parameter name="assoc_array" type="collection">
                    <parameter name="one" value="two" />
                    <parameter name="three" value="four" />
                </parameter>
                <iteration time="100" memory="100" revs="1" />
                <iteration time="75" memory="100" revs="1" />
           </variant>
        </subject>
    </benchmark>
</phpbench>
EOT
        );

        return $suite;
    }
}


text:
//Write an expression that calculates rectangle's perimeter and area by given width and height.

using System;

class Rectangles
{
    static void Main()
    {
        Console.Write("Enter rectangle width:");
        double width = double.Parse(Console.ReadLine());
        Console.Write("Enter rectagle height:");
        double height = double.Parse(Console.ReadLine());
        double perimeter = (2 * width) + (2 * height);
        double area = width * height;
        Console.WriteLine("The rectangle perimeter is {0}", perimeter);
        Console.WriteLine("The rectangle area is {0}", area);
    }
}


text:
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Media;
using ICSharpCode.WpfDesign;
using ICSharpCode.WpfDesign.Extensions;
using Xamarin.Forms;
using Xamarin.Forms.Helper;
using XamarinFormsClasses.Base;

namespace XamarinFormsClasses.Controls
{
    [ExtensionFor(typeof(Grid))]
    public class Grid_Extension : ViewExtension
    {
        public override FrameworkElement CreateView(DesignItem item)
        {
            var grid = new System.Windows.Controls.Grid();
	        grid.Background = TransparentBrush.GetTransparentBrush();

	        foreach (var collectionElement in item.ContentProperty.CollectionElements)
	        {
		        grid.Children.Add(collectionElement.View);
	        }

            item.ContentProperty.CollectionElements.CollectionChanged += (sender, args) =>
            {
                if (args.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (DesignItem newItem in args.NewItems)
                    {
                        grid.Children.Add(newItem.View);
                    }
                }
                else if (args.Action == NotifyCollectionChangedAction.Remove)
                {
                    foreach (DesignItem oldItem in args.OldItems)
                    {
                        grid.Children.Remove(oldItem.View);
                    }
                }
            };

            return grid;
        }

        public override void SetBindings(DesignItem item, FrameworkElement view)
        {
            base.SetBindings(item, view);
        }
    }
}


text:
<?php

use kartik\helpers\Html;
use kartik\widgets\Select2;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

use app\models\general\GeneralMessage;
use app\models\general\GeneralLabel;
use app\models\general\Placeholder;
use common\models\general\GeneralFunction;

use app\models\RefStatusTawaran;

/* @var $this yii\web\View */
/* @var $searchModel app\models\AtletSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = GeneralLabel::agenda_perbincangan;
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

<?= GeneralLabel::atlet ?>
            <button type="button" class="close" data-target="#atlet-list" data-dismiss="alert"> ×Close</button>

                <?php Pjax::begin(['timeout' => false, 'enablePushState' => false,]); ?>
        <?php //echo Html::beginForm(['atlet/bulk'],'post');?>
        <?= GridView::widget([
            'dataProvider' => $dataProviderAtlet,
            //'filterModel' => $searchModelAtlet,
            'columns' => [
                /*[
                    'class' => 'yii\grid\CheckboxColumn',
                ],*/
                ['class' => 'yii\grid\SerialColumn'],
                //'atlet_id',
                [
                    'attribute' => 'ic_no',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::ic_no,
                    ]
                ],
                [
                    'attribute' => 'name_penuh',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::name_penuh,
                    ]
                ],
                /*[
                    'attribute' => 'tawaran',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tawaran,
                    ]
                ],*/
                /*[
                    'attribute' => 'tawaran',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tawaran,
                    ],
                    'value' => function ($model) {
                        return $model->tawaran == 1 ? GeneralLabel::yes : GeneralLabel::no;
                    },
                ],*/
                [
                    'attribute' => 'tawaran',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tawaran,
                    ],
                    'filter'=>false,
                    'value' => 'refStatusTawaran.desc'
                ],
                /*[
                    'attribute' => 'tarikh_lahir',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tarikh_lahir,
                    ]
                ],*/
                /*[
                    'attribute' => 'umur',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::umur,
                    ]
                ],*/
                ['class' => 'yii\grid\ActionColumn',
                    'buttons' => [
                        'view' => function ($url, $model) use($mesyuarat_id) {
                            return Html::a('', '', ['value'=>Url::to(['/atlet/view', 'id' => $model->atlet_id, 'mesyuarat_id' => $mesyuarat_id]), 'class' => 'custom_button']);
                        },
                    ],
                    'template' => '{view}',
                ],
            ],
        ]); ?>

                        <?php
                //echo Html::dropDownList('action','',ArrayHelper::map(RefStatusTawaran::find()->all(),'id', 'desc'),['class'=>'dropdown',]);

            /*echo Select2::widget([
            'name' => 'action',
            'data' => ArrayHelper::map(RefStatusTawaran::find()->where('id <> :id', [':id' => RefStatusTawaran::DALAM_PROSES])->all(),'id', 'desc'),
            'options' => [
                'placeholder' => Placeholder::tindakan,
            ],
        ]);*/
            ?>

                        <?php //echo Html::submitButton(GeneralLabel::send, ['class' => 'btn btn-info',]);?>

                    <?php //echo Html::endForm();?>

                    <?php Pjax::end(); ?>

<?= GeneralLabel::jurulatih ?>
            <button type="button" class="close" data-target="#jurulatih-list" data-dismiss="alert"> ×Close</button>

                <?= GridView::widget([
            'dataProvider' => $dataProviderJurulatih,
            //'filterModel' => $searchModelJurulatih,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                [
                    'attribute' => 'ic_no',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::ic_no,
                    ]
                ],
                [
                    'attribute' => 'nama',
                    'filterInputOptions' => [
                        'class'       => 'form-control',
                        'placeholder' => GeneralLabel::filter.' '.GeneralLabel::nama,
                    ]
                ],
                [
                'attribute' => 'status_tawaran',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::status_tawaran,
                ],
                'value' => 'refStatusTawaran.desc'
            ],
                ['class' => 'yii\grid\ActionColumn',
                    'buttons' => [
                        'view' => function ($url, $model) use($mesyuarat_id){
                            return Html::a('', '', ['value'=>Url::to(['/jurulatih/view', 'id' => $model->jurulatih_id, 'mesyuarat_id' => $mesyuarat_id]), 'class' => 'custom_button']);
                        },
                    ],
                    'template' => '{view}',
                ],
            ],
        ]); ?>

<?= GeneralLabel::program_binaan ?>
            <button type="button" class="close" data-target="#program_binaan-list" data-dismiss="alert"> ×Close</button>

                <?= GridView::widget([
            'dataProvider' => $dataProviderPengurusanProgramBinaan,
            //'filterModel' => $searchModelPengurusanProgramBinaan,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                /*[
                'attribute' => 'aktiviti',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::aktiviti,
                ],
                'value' => 'refPerancanganProgram.nama_program'
            ],*/
            [
                'attribute' => 'nama_aktiviti',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::nama_aktiviti,
                ]
            ],
             [
                'attribute' => 'tarikh_mula',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tarikh_mula,
                ],
                 'value'=>function ($model) {
                    return GeneralFunction::convert($model->tarikh_mula, GeneralFunction::TYPE_DATE);
                },
            ],
             [
                'attribute' => 'tarikh_tamat',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tarikh_tamat,
                ],
                 'value'=>function ($model) {
                    return GeneralFunction::convert($model->tarikh_tamat, GeneralFunction::TYPE_DATE);
                },
            ],
            [
                'attribute' => 'status_permohonan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::status_permohonan,
                ],
                'value' => 'refStatusPermohonanProgramBinaan.desc'
            ],
                ['class' => 'yii\grid\ActionColumn',
                    'buttons' => [
                        'view' => function ($url, $model) {
                            return Html::a('', '', ['value'=>Url::to(['/pengurusan-program-binaan/view', 'id' => $model->pengurusan_program_binaan_id]), 'class' => 'custom_button']);
                        },
                    ],
                    'template' => '{view}',
                ],
            ],
        ]); ?>

<?= GeneralLabel::permohonan_peralatan ?>
            <button type="button" class="close" data-target="#permohonan_peralatan-list" data-dismiss="alert"> ×Close</button>

                <?= GridView::widget([
            'dataProvider' => $dataProviderPermohonanPeralatan,
            //'filterModel' => $searchModelPermohonanPeralatan,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                /*[
                'attribute' => 'cawangan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::cawangan,
                ],
                'value' => 'refCawangan.desc'
            ],
            [
                'attribute' => 'sukan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::sukan,
                ],
                'value' => 'refSukan.desc'
            ],
            [
                'attribute' => 'program',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::program,
                ],
                'value' => 'refProgram.desc'
            ],*/
             [
                'attribute' => 'tarikh',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tarikh,
                ],
                 'value'=>function ($model) {
                    return GeneralFunction::convert($model->tarikh, GeneralFunction::TYPE_DATETIME);
                },
            ],
             [
                'attribute' => 'jumlah_peralatan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::jumlah_peralatan,
                ]
            ],
            [
                'attribute' => 'kelulusan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::kelulusan,
                ],
                'value' => 'refKelulusan.desc'
            ],
                ['class' => 'yii\grid\ActionColumn',
                    'buttons' => [
                        'view' => function ($url, $model) {
                            return Html::a('', '', ['value'=>Url::to(['/permohonan-peralatan/view', 'id' => $model->permohonan_peralatan_id]), 'class' => 'custom_button']);
                        },
                    ],
                    'template' => '{view}',
                ],
            ],
        ]); ?>

<?= GeneralLabel::kejohanan ?>
            <button type="button" class="close" data-target="#kejohanan-list" data-dismiss="alert"> ×Close</button>

                <?= GridView::widget([
            'dataProvider' => $dataProviderKejohanan,
            //'filterModel' => $searchModelKejohanan,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                /*[
                'attribute' => 'nama_sukan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::nama_sukan,
                ],
                'value' => 'refSukan.desc'
            ],*/
            [
                'attribute' => 'tempat_penginapan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tempat_penginapan,
                ]
            ],
            [
                'attribute' => 'tempat_latihan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tempat_latihan,
                ]
            ],
                ['class' => 'yii\grid\ActionColumn',
                    'buttons' => [
                        'view' => function ($url, $model) {
                            return Html::a('', '', ['value'=>Url::to(['/penyertaan-sukan/view', 'id' => $model->penyertaan_sukan_id]), 'class' => 'custom_button']);
                        },
                    ],
                    'template' => '{view}',
                ],
            ],
        ]); ?>

<?= GeneralLabel::pusat_latihan ?>
            <button type="button" class="close" data-target="#pusat_latihan-list" data-dismiss="alert"> ×Close</button>

                <?= GridView::widget([
            'dataProvider' => $dataProviderPusatLatihan,
            //'filterModel' => $searchModelPusatLatihan,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                [
                'attribute' => 'nama_pusat_latihan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::nama_pusat_latihan,
                ],
            ],
            [
                'attribute' => 'alamat_negeri',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::alamat_negeri,
                ],
                'value' => 'refNegeri.desc'
            ],
            [
                'attribute' => 'no_telefon',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::no_telefon,
                ],
            ],
            [
                'attribute' => 'no_faks',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::no_faks,
                ],
            ],
            [
                'attribute' => 'tarikh_program_bermula',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tarikh_program_bermula,
                ],
                 'value'=>function ($model) {
                    return GeneralFunction::convert($model->tarikh_program_bermula, GeneralFunction::TYPE_DATE);
                },
            ],
                ['class' => 'yii\grid\ActionColumn',
                    'buttons' => [
                        'view' => function ($url, $model) {
                            return Html::a('', '', ['value'=>Url::to(['/profil-pusat-latihan/view', 'id' => $model->profil_pusat_latihan_id]), 'class' => 'custom_button']);
                        },
                    ],
                    'template' => '{view}',
                ],
            ],
        ]); ?>

<?= GeneralLabel::program ?>
            <button type="button" class="close" data-target="#program-list" data-dismiss="alert"> ×Close</button>

                <?= GridView::widget([
            'dataProvider' => $dataProviderProgram,
            //'filterModel' => $searchModelProgram,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
            [
                'attribute' => 'cawangan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::cawangan             ],
                    'value' => 'refCawangan.desc'
            ],
            [
                'attribute' => 'sukan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::sukan,
                ],
                    'value' => 'refSukan.desc'
            ],
            [
                'attribute' => 'program',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::program,
                ],
                'value' => 'refProgramSemasaSukanAtlet.desc'
            ],
            [
                'attribute' => 'tarikh_mula',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tarikh_mula,
                ],
                 'value'=>function ($model) {
                    return GeneralFunction::convert($model->tarikh_mula);
                },
            ],
            [
                'attribute' => 'tarikh_tamat',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tarikh_tamat,
                ],
                 'value'=>function ($model) {
                    return GeneralFunction::convert($model->tarikh_tamat);
                },
            ],

            //'muat_naik',
            /*[
                'attribute' => 'muat_naik',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::muat_naik,
                ],
                'format' => 'raw',
                'value'=>function ($model) {
                    if($model->muat_naik){
                        return Html::a(GeneralLabel::viewAttachment, 'javascript:void(0);',
                                        [
                                            'onclick' => 'viewUpload("'.\Yii::$app->request->BaseUrl.'/' . $model->muat_naik .'");'
                                        ]);
                    } else {
                        return "";
                    }
                },
            ],*/
            /*[
                'attribute' => 'status_program',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::status_program,
                ],
                    'value' => 'refStatusProgram.desc'
            ],*/
                ['class' => 'yii\grid\ActionColumn',
                    'buttons' => [
                        'view' => function ($url, $model) {
                            return Html::a('', '', ['value'=>Url::to(['/perancangan-program-plan/view', 'id' => $model->perancangan_program_plan_master_id]), 'class' => 'custom_button']);
                        },
                    ],
                    'template' => '{view}',
                ],
            ],
        ]); ?>

<?php
$script = <<< JS

$(function(){
$('.custom_button').click(function(){
        window.open($(this).attr('value'), "PopupWindow", "width=1300,height=800,scrollbars=yes,resizable=no");
        return false;
});});

JS;

$this->registerJs($script);
?>


text:
PRIMARY_IP=$(cat /tmp/primary_ip | tr -d '\n')

echo "Joining cluster..."
sleep 20
sudo riak-admin cluster join riak@$PRIMARY_IP


text:
This repository contains the Flask and client-side code for a database for multiple bacterial
genomes.  The data model is held in MongoDB, and any rich, annotated sequence format that can
be read by Biopython's SeqIO module can be imported into the database.  As well as a web
presentation layer, the site also implements a RESTful-style interface to access the underlying
data in JSON format; this is in fact the method used by the client-side javascript to retreive
data from the server.

## Prerequisites

The following software need to be installed on your system:
* a web server (e.g., apache)
* Python
* MongoDB
* Python modules:
  * Flask
  * pymongo (include bson module, don't install bson using pip or easy_install!!)
  * biopython (only required to import data)
* BLAST+ from [NCBI](http://www.ncbi.nlm.nih.gov) (only required to generate BLAST matches between genomes)

## Installation

All that is required to install the software for a local server is:

```bash
$ git clone https://github.com/peteashton/symbiont.org.git
```

To run using the (insecure) Flask web server, you just need to the main Flask application:

```bash
$ python symbiont.py
```

The database will then be available at http://localhost:5000/

### Running as a WSGI Application

Instructions for doing this will vary depending on the web server used, and the operating system
on which the software is installed.  For Apache, it is a matter of setting up a virtual host in the
`httpd.conf` file which points to the `symbionts.wsgi` file and editing the `symbionts.wsgi`
file to add the location of the software into the Python search path.

## Importing Data

Genbank and EMBL rich, annotated sequence files can be loaded into the database using the
`importSequence.py` script in the tools folder. By default, the data will be imported into
the MongoDB instance that is running on the default port, and into a database called "symbiont".
The genome sequence and metadata will be stored in the "genome" collection and data on genes and
other sequence features in the "genome.features" collection.  Genome IDs (as specified in the
sequence file) must be unique.  If the file contains multiple sequences, the first is assumed
to be the genome, and subsequent sequences are treated as associated plasmids.

## Web interface

Coming soon...

## RESTful interface

Coming soon...

### License

The source code for the symbionts.org website is provided under the MIT license.


text:
package biz.meetmatch.modules.util

import biz.meetmatch.modules.Module
import biz.meetmatch.util.Utils
import com.google.gson.Gson
import org.apache.spark.sql.SparkSession
import org.rogach.scallop.Scallop
import org.slf4j.LoggerFactory

import scalaj.http.Http

object WarmupZeppelin extends Module {

  override def execute(scallopts: Scallop)(implicit sparkSession: SparkSession): Unit = {
    val interpreterId = Utils.getConfig("zeppelin.interpreter.id")

    logger.info(s"Restarting the spark interpreter using url http://localhost:8080/api/interpreter/setting/restart/$interpreterId...")
    val interpreterResponse = Http(s"http://localhost:8080/api/interpreter/setting/restart/$interpreterId")
      .method("put")
      .timeout(connTimeoutMs = 10000, readTimeoutMs = 60000)
      .asParamMap
    logger.info("Response code: " + interpreterResponse.code)

    if (interpreterResponse.code == 200) {
      val bootstrapNotebookId = Utils.getConfig("zeppelin.bootstrapNotebookId.id")

      logger.info(s"Executing the Bootstrap notebook using url http://localhost:8080/api/notebook/job/$bootstrapNotebookId...")
      val notebookResponse = Http(s"http://localhost:8080/api/notebook/job/$bootstrapNotebookId")
        .postForm
        .timeout(connTimeoutMs = 10000, readTimeoutMs = 60000)
        .asParamMap
      logger.info("Response code: " + notebookResponse.code)

      if (notebookResponse.code == 200) {
        def stillRunningParagraphs(): Boolean = {
          logger.info("Checking if the Bootstrap notebook has finished...")
          val checkNotebookResponse = Http("http://localhost:8080/api/notebook/job/2BKFC4D5W")
            .timeout(connTimeoutMs = 10000, readTimeoutMs = 120000)
            .asString
          logger.info("Response code: " + checkNotebookResponse.code)
          val notebookJobResponse = new Gson().fromJson(checkNotebookResponse.body, classOf[GetNotebookJobResponse])
          notebookJobResponse.body.exists(_.status != "FINISHED")
        }

        while (stillRunningParagraphs()) {
          logger.info("Keep on polling...")
          Thread.sleep(5000)
        }
        logger.info("The Bootstrap notebook has finished.")
      }
    }
  }

  case class GetNotebookJobResponse(status: String, body: Array[ParagraphStatus])

  case class ParagraphStatus(id: String, started: String, finished: String, status: String)

  override protected val logger = LoggerFactory.getLogger(this.getClass)
}


text:
module Squishable
  module SquishesHelper
  end
end


text:
// ======================================
// Author: Ebenezer Monney
// Email:  info@ebenmonney.com
// Copyright (c) 2017 www.ebenmonney.com
// ======================================

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'groupBy' })
export class GroupByPipe implements PipeTransform {

    transform(value: Array<any>, field: string): Array<any> {

        if (!value)
            return value;

        const groupedObj = value.reduce((prev, cur) => {
            if (!prev[cur[field]]) {
                prev[cur[field]] = [cur];
            }
            else {
                prev[cur[field]].push(cur);
            }

            return prev;
        }, {});

        return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="theme" content="hugo-academic">
  <meta name="generator" content="Hugo 0.26" />
  <meta name="author" content="Matt Bianchi">
  <meta name="description" content="Senior Software Engineer">

    <link rel="stylesheet" href="/css/highlight.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha512-6MXa8B6uaO18Hid6blRMetEIoPqHf7Ux1tnyIQdpt9qI5OACx7C+O3IVTr98vwGnlcg0LOLa02i9Y1HpVhlfiw==" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.0/css/academicons.min.css" integrity="sha512-GGGNUPDhnG8LEAEDsjqYIQns+Gu8RBs4j5XGlxl7UfRaZBhCCm5jenJkeJL8uPuOXGqgl8/H1gjlWQDRjd3cUQ==" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous">

  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:400,700%7CMerriweather%7CRoboto+Mono">
  <link rel="stylesheet" href="/css/hugo-academic.css">

  <link rel="alternate" href="http://blog.mattrbianchi.com/books/index.xml" type="application/rss+xml" title="">
  <link rel="feed" href="http://blog.mattrbianchi.com/books/index.xml" type="application/rss+xml" title="">

  <link rel="icon" type="image/png" href="/img/icon.png">
  <link rel="apple-touch-icon" type="image/png" href="/img/apple-touch-icon.png">

  <link rel="canonical" href="http://blog.mattrbianchi.com/books/">

  <title>Books | </title>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
              data-target=".navbar-collapse" aria-expanded="false">
        Toggle navigation

      </button>

            Home

            About

            Posts

            Reading

            Resources

            Setup

Books

100 Ways to Improve Your Writing

      I’m terrible at writing. I have a lot to make up for and the faster the better. This book is great for giving small nuggets of advice that you can immediately use in your writing. The author, Gary Provost, does a brilliant job of making it a pleasure to read the book. Most of the time, he crafts his own writing to be examples of the very thing he is teaching at that very moment.

Go In Action

      After taking the Tour of Go, I bought Go in Action and haven’t regretted it. It’s great for someone who already knows how to program, but wants to get up to speed on the details and inner workings of Go. The authors, William Kennedy, Brian Ketelsen, and Erik St. Martin, did a great job of giving examples I could expand into a practical applications while keeping them concise (which keep the book light, in both reading and weight).

Just for Fun

      Just For Fun was a biography about Linus Torvalds’ life up until about 2002. I believe it is important for programmers to understand how humankind has gotten to this point in technology and to understand the mindset behind the people who pushed it. Just like how we must study all history in order to strive to do better on behalf of our predecessors, programmers should get a solid course in how the fantastic machine they carry around in their pockets came to be.

Table of Contents

The Pragmatic Programmer

      This book has left a lasting impression and was a great starting place to continue my learning after college. Instead of teaching an algorithm or some abstract theory, the authors give you their advice composed from years of experience as established professionals in our field. This was a priceless insight into things like working with a team, handling a real world project, and how to choose the best tools and libraries that will make your life easier.

      © 2017 Matthew Bianchi ·

      Powered by the Academic
      theme for Hugo.


text:
/**
 * BatchID is a locally assigned ID for a batch of mutations that have been
 * applied.
 */
export declare type BatchId = number;
/**
 * A locally-assigned ID used to refer to a target being watched via the
 * Watch service.
 */
export declare type TargetId = number;
export declare type ProtoByteString = Uint8Array | string;
/** Describes the online state of the Firestore client */
export declare enum OnlineState {
    /**
     * The Firestore client is in an unknown online state. This means the client
     * is either not actively trying to establish a connection or it was
     * previously in an unknown state and is trying to establish a connection.
     */
    Unknown = 0,
    /**
     * The client is connected and the connections are healthy. This state is
     * reached after a successful connection and there has been at least one
     * succesful message received from the backends.
     */
    Healthy = 1,
    /**
     * The client has tried to establish a connection but has failed.
     * This state is reached after either a connection attempt failed or a
     * healthy stream was closed for unexpected reasons.
     */
    Failed = 2,
}


text:
template<char const * name,typename T>
class attribute
{
public:
	attribute(std::string value) :
		_value(convert<T>(value))
	{}

	T get() {
		return _value;
	}
private:
	T _value;
};


text:
Self Assessment
===============

I believe that I have completed all aspects of this project except for the
extra credit cloisters.
I think that I did fairly well at implementing good Object Oriented
design. I considered creating a completely separate controller class
to implement the MVC design, but instead I ended up putting that
functionality inside of the View class. I also wished that my View
and Model were a little less tightly coupled. I think they were sufficiently
loosely coupled but I think slight improvements could have been made.

I believe that my choice of data structure was sufficient. It wasn't the most
elegant or sophistaced but it got the job done without a lot of overhead.
I also customized my data structure by creating my own Tile class.
I had considered adding pointers to the Tiles around a given Tile object
in order to emulate a graph, but that didn't seem necessary with specialized
methods to access those adjacent tiles in my Game class.

I am really proud of my algorithms. I think that they are pretty nice and
rather small. There aren't any special cases. My algorithms can handle
any type of road or city. I would appreciate any feedback, while I think my
methods work well, I went back and forth on doing things one way or the other.
A lot of the time I was unsure about what was convention in java.

Overall I felt like this project went well. I thought it was a little harder
than I expected. I figured that this project would come more easily, but it
definately had its challenges.

Images
======

One image from Iconify.it was used. This image is located at
src/resources/rotateCW.png.
This image was licensed for free public use with a Creative Commons
(Attribution 3.0 Unported) license.
This image was modified and built upon.
A derivative of this image is located at src/resources/rotateCCW.png.

See Iconify.it page at https://www.iconfinder.com/iconify


text:
@implementation BSCircularProgressView

- (void)awakeFromNib
{
    [self setup];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup
{
    self.roundedCorners = 2.0f;
    self.progressLabel.textColor = [UIColor whiteColor];
}

- (void)setProgress:(CGFloat)progress animated:(BOOL)animated
{
    [super setProgress:progress animated:animated];
    NSString *text = [NSString stringWithFormat:@"%.0f%%", progress * 100];
    if ([text rangeOfString:@"-"].location != NSNotFound) {
        text = [text stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    self.progressLabel.text = text;

}

@end


text:
/* Automatically generated by shapeshifter. Do not modify! */
/* eslint-disable */

import PropTypes from 'prop-types';
import ArrayDefault from '../stub';
import DefaultName from '../stub';
import AnotherDefault, { Baz, Qux } from '../stub';
import InstanceDefault, { InstanceClassName } from '../stub';
import ObjectDefault from '../stub';
import ShapeDefault, { ShapeClassName } from '../stub';
import UnionDefault, { UnionClassName } from '../stub';

export const ARRAY_NUM = 123;
export const CONST_STRING = 'string';
export const STATUS_NUMBER = 123;
export const MAGIC_FLOAT = 456.78;
export const IS_ENABLED = true;
export const EMPTY_VALUE = null;
export const PRIMITIVE_LIST = ['foo', 123, 456.78, false];
export const INST_STR = 'foobar';
export const INST_ENABLED = true;
export const PRIMITIVE_VALUES = ['string', 123, true];
export const PRIMITIVE_STR = 'primitive';

export const KeyShape = PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number,
]);

export const ArrayShape = PropTypes.shape({
  arrayField: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.string)),
  boolField: PropTypes.arrayOf(PropTypes.bool),
  enumField: PropTypes.arrayOf(PropTypes.oneOf([
    'foo',
    'bar',
    'baz',
  ])),
  instanceField: PropTypes.arrayOf(PropTypes.instanceOf(ArrayDefault)),
  numberField: PropTypes.arrayOf(PropTypes.number),
  objectField: PropTypes.arrayOf(PropTypes.objectOf(PropTypes.number)),
  shapeField: PropTypes.arrayOf(PropTypes.shape({
    foo: PropTypes.string,
    bar: PropTypes.bool,
  })),
  stringField: PropTypes.arrayOf(PropTypes.string),
  unionField: PropTypes.arrayOf(PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.oneOf([
      1,
      2,
      3,
    ]),
  ])),
});

export const ConstantsShape = PropTypes.shape({
  numberField: PropTypes.number,
});

export const EnumShape = PropTypes.shape({
  boolField: PropTypes.oneOf([
    true,
    false,
  ]),
  booleanField: PropTypes.oneOf([
    false,
    true,
  ]),
  intField: PropTypes.oneOf([
    123,
  ]).isRequired,
  integerField: PropTypes.oneOf([
    1,
    2,
    3,
  ]),
  numField: PropTypes.oneOf([
    123,
    456,
    789,
  ]),
  numberField: PropTypes.oneOf([
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
  ]),
  floatField: PropTypes.oneOf([
    12.34,
    56.78,
    9,
    65.4,
  ]),
  strField: PropTypes.oneOf([
    'foo',
    'bar',
  ]),
  stringField: PropTypes.oneOf([
    'baz',
    'qux',
  ]),
});

export const ImportsShape = PropTypes.shape({
  stringField: PropTypes.string,
});

export const InstanceShape = PropTypes.shape({
  instField: PropTypes.instanceOf(InstanceClassName),
  instanceField: PropTypes.instanceOf(InstanceDefault),
});

export const ObjectShape = PropTypes.shape({
  arrayField: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),
  boolField: PropTypes.objectOf(PropTypes.bool),
  enumField: PropTypes.objectOf(PropTypes.oneOf([
    'foo',
    'bar',
    'baz',
  ])),
  instanceField: PropTypes.objectOf(PropTypes.instanceOf(ObjectDefault)),
  numberField: PropTypes.objectOf(PropTypes.number),
  objectField: PropTypes.objectOf(PropTypes.objectOf(PropTypes.number)),
  shapeField: PropTypes.objectOf(PropTypes.shape({
    foo: PropTypes.string,
    bar: PropTypes.bool,
  })),
  stringField: PropTypes.objectOf(PropTypes.string),
  unionField: PropTypes.objectOf(PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.arrayOf(PropTypes.string),
  ])),
  objShorthandField: PropTypes.objectOf(PropTypes.string),
  objKeyTypeField: PropTypes.objectOf(PropTypes.string),
});

export const PolymorphVideoShape = PropTypes.shape({
  path: PropTypes.string,
});

export const PolymorphImageShape = PropTypes.shape({
  url: PropTypes.string,
});

export const PolymorphShape = PropTypes.shape({
  item: PropTypes.oneOfType([
    PolymorphImageShape,
    PolymorphVideoShape,
  ]),
  item_id: KeyShape,
  item_type: PropTypes.string,
  product: PropTypes.oneOfType([
    PolymorphImageShape,
    PolymorphVideoShape,
  ]),
  product_key: KeyShape,
  product_model: PropTypes.string,
});

export const PrimitiveShape = PropTypes.shape({
  boolField: PropTypes.bool,
  boolFieldExpanded: PropTypes.bool,
  booleanField: PropTypes.bool,
  booleanFieldExpanded: PropTypes.bool,
  intField: PropTypes.number,
  intFieldExpanded: PropTypes.number,
  integerField: PropTypes.number,
  integerFieldExpanded: PropTypes.number,
  numField: PropTypes.number,
  numFieldExpanded: PropTypes.number,
  numberField: PropTypes.number,
  numberFieldExpanded: PropTypes.number,
  floatField: PropTypes.number,
  floatFieldExpanded: PropTypes.number,
  strField: PropTypes.string,
  strFieldExpanded: PropTypes.string,
  stringField: PropTypes.string,
  stringFieldExpanded: PropTypes.string,
});

export const ReferenceBarShape = PropTypes.shape({
  boolField: PropTypes.bool,
});

export const ReferenceFooShape = PropTypes.shape({
  numberField: PropTypes.number,
  refField: ReferenceBarShape,
});

export const ReferenceSelfBasicShape = PropTypes.shape({
  stringField: PropTypes.string,
});

export const ReferenceSelfShape = PropTypes.shape({
  stringField: PropTypes.string,
  referenceField: (...args) => ReferenceSelfShape(...args),
  requiredRefField: (...args) => ReferenceSelfShape(...args),
  subsetRefField: PropTypes.arrayOf(ReferenceSelfBasicShape).isRequired,
});

export const ReferenceSetOnlyStringShape = PropTypes.shape({
  stringField: PropTypes.string,
});

export const ReferenceSetShape = PropTypes.shape({
  boolField: PropTypes.bool,
  stringField: PropTypes.string,
  numberField: PropTypes.number,
});

export const ReferenceShape = PropTypes.shape({
  stringField: PropTypes.string,
  refField: ReferenceFooShape,
  referenceField: ReferenceFooShape,
  subsetRefField: ReferenceSetOnlyStringShape,
});

export const SetsBasicShape = PropTypes.shape({
  foo: PropTypes.string,
  baz: PropTypes.bool,
});

export const SetsWithNullShape = PropTypes.shape({
  foo: PropTypes.string,
  qux: PropTypes.string,
});

export const SetsShape = PropTypes.shape({
  foo: PropTypes.string,
  bar: PropTypes.number,
  baz: PropTypes.bool,
  qux: PropTypes.string,
});

export const ShapeReferencePriceShape = PropTypes.shape({
  amount: PropTypes.number,
  nativeAmount: PropTypes.number,
  exchangeRate: PropTypes.number,
});

export const ShapeReferenceShape = PropTypes.shape({
  fees: ShapeReferencePriceShape,
  taxes: ShapeReferencePriceShape,
  total: ShapeReferencePriceShape,
});

export const ShapeShape = PropTypes.shape({
  structAlias: PropTypes.shape({
    foo: PropTypes.string,
  }),
  primitiveFields: PropTypes.shape({
    string: PropTypes.string,
    bool: PropTypes.bool,
    number: PropTypes.number,
  }),
  arrayFields: PropTypes.shape({
    numberArray: PropTypes.arrayOf(PropTypes.number),
    stringArray: PropTypes.arrayOf(PropTypes.string),
    shapeArray: PropTypes.arrayOf(PropTypes.shape({
      foo: PropTypes.string,
    })),
  }),
  enumFields: PropTypes.shape({
    stringEnum: PropTypes.oneOf([
      'foo',
      'bar',
      'baz',
    ]),
    intEnum: PropTypes.oneOf([
      1,
      2,
      3,
    ]),
  }),
  instanceFields: PropTypes.shape({
    instOf: PropTypes.instanceOf(ShapeClassName),
    instanceOf: PropTypes.instanceOf(ShapeDefault),
  }),
  objectFields: PropTypes.shape({
    numberObj: PropTypes.objectOf(PropTypes.number),
    boolObject: PropTypes.objectOf(PropTypes.bool),
    intStringObject: PropTypes.objectOf(PropTypes.string),
    unionObject: PropTypes.objectOf(PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string,
      PropTypes.shape({
        foo: PropTypes.string,
      }),
    ])).isRequired,
  }),
  unionFields: PropTypes.shape({
    multiUnion: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.bool,
      PropTypes.instanceOf(ShapeClassName),
      PropTypes.objectOf(PropTypes.string),
      PropTypes.shape({
        string: PropTypes.string,
        enum: PropTypes.oneOf([
          123,
          456,
          789,
        ]),
      }),
    ]),
  }),
});

export const UnionShape = PropTypes.shape({
  arrayField: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.string),
    PropTypes.arrayOf(PropTypes.objectOf(PropTypes.string)),
  ]),
  primitiveFields: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.number,
  ]),
  enumField: PropTypes.oneOfType([
    PropTypes.oneOf([
      'foo',
      'bar',
      'baz',
    ]),
    PropTypes.oneOf([
      789,
      456,
      123,
    ]),
  ]),
  instanceField: PropTypes.oneOfType([
    PropTypes.instanceOf(UnionClassName),
    PropTypes.instanceOf(UnionDefault),
  ]),
  objectField: PropTypes.oneOfType([
    PropTypes.objectOf(PropTypes.number),
    PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),
  ]),
  shapeField: PropTypes.oneOfType([
    PropTypes.shape({
      foo: PropTypes.string,
      bar: PropTypes.bool,
    }),
    PropTypes.shape({
      qux: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.bool,
      ]),
    }),
  ]),
  unionField: PropTypes.oneOfType([
    PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.oneOf([
        1,
        2,
        3,
      ]),
    ]),
    PropTypes.oneOfType([
      PropTypes.bool,
      PropTypes.number,
    ]),
  ]),
});


text:
import os
import random
from argparse import ArgumentParser, Namespace

import numpy as np
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
from PIL import Image
from torch.utils.data import DataLoader, Dataset

import pytorch_lightning as pl
from pl_examples import cli_lightning_logo
from pl_examples.domain_templates.unet import UNet
from pytorch_lightning.loggers import WandbLogger

DEFAULT_VOID_LABELS = (0, 1, 2, 3, 4, 5, 6, 9, 10, 14, 15, 16, 18, 29, 30, -1)
DEFAULT_VALID_LABELS = (7, 8, 11, 12, 13, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 31, 32, 33)

def _create_synth_kitti_dataset(path_dir: str, image_dims: tuple = (1024, 512)):
    """Create synthetic dataset with random images, just to simulate that the dataset have been already downloaded."""
    path_dir_images = os.path.join(path_dir, KITTI.IMAGE_PATH)
    path_dir_masks = os.path.join(path_dir, KITTI.MASK_PATH)
    for p_dir in (path_dir_images, path_dir_masks):
        os.makedirs(p_dir, exist_ok=True)
    for i in range(3):
        path_img = os.path.join(path_dir_images, f"dummy_kitti_{i}.png")
        Image.new("RGB", image_dims).save(path_img)
        path_mask = os.path.join(path_dir_masks, f"dummy_kitti_{i}.png")
        Image.new("L", image_dims).save(path_mask)

class KITTI(Dataset):
    """
    Class for KITTI Semantic Segmentation Benchmark dataset
    Dataset link - http://www.cvlibs.net/datasets/kitti/eval_semseg.php?benchmark=semantics2015

    There are 34 classes in the given labels. However, not all of them are useful for training
    (like railings on highways, road dividers, etc.).
    So, these useless classes (the pixel values of these classes) are stored in the `void_labels`.
    The useful classes are stored in the `valid_labels`.

    The `encode_segmap` function sets all pixels with any of the `void_labels` to `ignore_index`
    (250 by default). It also sets all of the valid pixels to the appropriate value between 0 and
    `len(valid_labels)` (since that is the number of valid classes), so it can be used properly by
    the loss function when comparing with the output.

    The `get_filenames` function retrieves the filenames of all images in the given `path` and
    saves the absolute path in a list.

    In the `get_item` function, images and masks are resized to the given `img_size`, masks are
    encoded using `encode_segmap`, and given `transform` (if any) are applied to the image only
    (mask does not usually require transforms, but they can be implemented in a similar way).

    >>> from pl_examples import _DATASETS_PATH
    >>> dataset_path = os.path.join(_DATASETS_PATH, "Kitti")
    >>> _create_synth_kitti_dataset(dataset_path, image_dims=(1024, 512))
    >>> KITTI(dataset_path, 'train')  # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
    <...semantic_segmentation.KITTI object at ...>
    """

    IMAGE_PATH = os.path.join("training", "image_2")
    MASK_PATH = os.path.join("training", "semantic")

    def __init__(
        self,
        data_path: str,
        split: str,
        img_size: tuple = (1242, 376),
        void_labels: list = DEFAULT_VOID_LABELS,
        valid_labels: list = DEFAULT_VALID_LABELS,
        transform=None,
    ):
        self.img_size = img_size
        self.void_labels = void_labels
        self.valid_labels = valid_labels
        self.ignore_index = 250
        self.class_map = dict(zip(self.valid_labels, range(len(self.valid_labels))))
        self.transform = transform

        self.split = split
        self.data_path = data_path
        self.img_path = os.path.join(self.data_path, self.IMAGE_PATH)
        self.mask_path = os.path.join(self.data_path, self.MASK_PATH)
        self.img_list = self.get_filenames(self.img_path)
        self.mask_list = self.get_filenames(self.mask_path)

        # Split between train and valid set (80/20)
        random_inst = random.Random(12345)  # for repeatability
        n_items = len(self.img_list)
        idxs = random_inst.sample(range(n_items), n_items // 5)
        if self.split == "train":
            idxs = [idx for idx in range(n_items) if idx not in idxs]
        self.img_list = [self.img_list[i] for i in idxs]
        self.mask_list = [self.mask_list[i] for i in idxs]

    def __len__(self):
        return len(self.img_list)

    def __getitem__(self, idx):
        img = Image.open(self.img_list[idx])
        img = img.resize(self.img_size)
        img = np.array(img)

        mask = Image.open(self.mask_list[idx]).convert("L")
        mask = mask.resize(self.img_size)
        mask = np.array(mask)
        mask = self.encode_segmap(mask)

        if self.transform:
            img = self.transform(img)

        return img, mask

    def encode_segmap(self, mask):
        """
        Sets void classes to zero so they won't be considered for training
        """
        for voidc in self.void_labels:
            mask[mask == voidc] = self.ignore_index
        for validc in self.valid_labels:
            mask[mask == validc] = self.class_map[validc]
        # remove extra idxs from updated dataset
        mask[mask > 18] = self.ignore_index
        return mask

    def get_filenames(self, path):
        """
        Returns a list of absolute paths to images inside given `path`
        """
        files_list = []
        for filename in os.listdir(path):
            files_list.append(os.path.join(path, filename))
        return files_list

class SegModel(pl.LightningModule):
    """
    Semantic Segmentation Module

    This is a basic semantic segmentation module implemented with Lightning.
    It uses CrossEntropyLoss as the default loss function. May be replaced with
    other loss functions as required.
    It is specific to KITTI dataset i.e. dataloaders are for KITTI
    and Normalize transform uses the mean and standard deviation of this dataset.
    It uses the FCN ResNet50 model as an example.

    Adam optimizer is used along with Cosine Annealing learning rate scheduler.

    >>> from pl_examples import _DATASETS_PATH
    >>> dataset_path = os.path.join(_DATASETS_PATH, "Kitti")
    >>> _create_synth_kitti_dataset(dataset_path, image_dims=(1024, 512))
    >>> SegModel(dataset_path)  # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
    SegModel(
      (net): UNet(
        (layers): ModuleList(
          (0): DoubleConv(...)
          (1): Down(...)
          (2): Down(...)
          (3): Up(...)
          (4): Up(...)
          (5): Conv2d(64, 19, kernel_size=(1, 1), stride=(1, 1))
        )
      )
    )
    """

    def __init__(
        self,
        data_path: str,
        batch_size: int = 4,
        lr: float = 1e-3,
        num_layers: int = 3,
        features_start: int = 64,
        bilinear: bool = False,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.data_path = data_path
        self.batch_size = batch_size
        self.lr = lr
        self.num_layers = num_layers
        self.features_start = features_start
        self.bilinear = bilinear

        self.net = UNet(
            num_classes=19, num_layers=self.num_layers, features_start=self.features_start, bilinear=self.bilinear
        )
        self.transform = transforms.Compose(
            [
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.35675976, 0.37380189, 0.3764753], std=[0.32064945, 0.32098866, 0.32325324]
                ),
            ]
        )
        self.trainset = KITTI(self.data_path, split="train", transform=self.transform)
        self.validset = KITTI(self.data_path, split="valid", transform=self.transform)

    def forward(self, x):
        return self.net(x)

    def training_step(self, batch, batch_nb):
        img, mask = batch
        img = img.float()
        mask = mask.long()
        out = self(img)
        loss = F.cross_entropy(out, mask, ignore_index=250)
        log_dict = {"train_loss": loss}
        return {"loss": loss, "log": log_dict, "progress_bar": log_dict}

    def validation_step(self, batch, batch_idx):
        img, mask = batch
        img = img.float()
        mask = mask.long()
        out = self(img)
        loss_val = F.cross_entropy(out, mask, ignore_index=250)
        return {"val_loss": loss_val}

    def validation_epoch_end(self, outputs):
        loss_val = torch.stack([x["val_loss"] for x in outputs]).mean()
        log_dict = {"val_loss": loss_val}
        return {"log": log_dict, "val_loss": log_dict["val_loss"], "progress_bar": log_dict}

    def configure_optimizers(self):
        opt = torch.optim.Adam(self.net.parameters(), lr=self.learning_rate)
        sch = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10)
        return [opt], [sch]

    def train_dataloader(self):
        return DataLoader(self.trainset, batch_size=self.batch_size, shuffle=True)

    def val_dataloader(self):
        return DataLoader(self.validset, batch_size=self.batch_size, shuffle=False)

    @staticmethod
    def add_model_specific_args(parent_parser):  # pragma: no-cover
        parser = parent_parser.add_argument_group("SegModel")
        parser.add_argument("--data_path", type=str, help="path where dataset is stored")
        parser.add_argument("--batch_size", type=int, default=16, help="size of the batches")
        parser.add_argument("--lr", type=float, default=0.001, help="adam: learning rate")
        parser.add_argument("--num_layers", type=int, default=5, help="number of layers on u-net")
        parser.add_argument("--features_start", type=float, default=64, help="number of features in first layer")
        parser.add_argument(
            "--bilinear", action="store_true", default=False, help="whether to use bilinear interpolation or transposed"
        )
        return parent_parser

def main(hparams: Namespace):
    # ------------------------
    # 1 INIT LIGHTNING MODEL
    # ------------------------
    model = SegModel(**vars(hparams))

    # ------------------------
    # 2 SET LOGGER
    # ------------------------
    logger = False
    if hparams.log_wandb:
        logger = WandbLogger()

        # optional: log model topology
        logger.watch(model.net)

    # ------------------------
    # 3 INIT TRAINER
    # ------------------------
    trainer = pl.Trainer.from_argparse_args(hparams)

    # ------------------------
    # 5 START TRAINING
    # ------------------------
    trainer.fit(model)

if __name__ == "__main__":
    cli_lightning_logo()
    parser = ArgumentParser(add_help=False)
    parser = SegModel.add_model_specific_args(parser)
    hparams = parser.parse_args()

    main(hparams)


text:
/**
 * A dropped piece of resource.
 * It will decay after a while if not picked up.
 * Dropped resource pile decays for ceil(amount/1000) units per tick.
 *
 * @class
 * @extends {RoomObject}
 *
 * @see {@link http://support.screeps.com/hc/en-us/articles/203016362-Resource}
 */
Resource = function() { };

Resource.prototype =
{
    /**
     * The amount of resource units containing.
     *
     * @see {@link http://support.screeps.com/hc/en-us/articles/203016362-Resource#amount}
     *
     * @type {number}
     */
    amount: 0,

    /**
     * A unique object identificator.
     * You can use Game.getObjectById method to retrieve an object instance by its id.
     *
     * @see {@link http://support.screeps.com/hc/en-us/articles/203016362-Resource#id}
     *
     * @type {string}
     */
    id: "",

    /**
     * One of the RESOURCE_* constants.
     *
     * @see {@link http://support.screeps.com/hc/en-us/articles/203016362-Resource#resourceType}
     *
     * @type {string}
     */
    resourceType: ""
};


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim:expandtab:shiftwidth=4:tabstop=4:
 */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsDragService_h__
#define nsDragService_h__

#include "nsBaseDragService.h"
#include "nsIObserver.h"
#include <gtk/gtk.h>

class nsWindow;

#ifndef HAVE_NSGOBJECTREFTRAITS
#define HAVE_NSGOBJECTREFTRAITS
template <class T>
class nsGObjectRefTraits : public nsPointerRefTraits<T> {
public:
    static void Release(T *aPtr) { g_object_unref(aPtr); }
    static void AddRef(T *aPtr) { g_object_ref(aPtr); }
};
#endif

#ifndef HAVE_NSAUTOREFTRAITS_GTKWIDGET
#define HAVE_NSAUTOREFTRAITS_GTKWIDGET
template <>
class nsAutoRefTraits<GtkWidget> : public nsGObjectRefTraits<GtkWidget> { };
#endif

#ifndef HAVE_NSAUTOREFTRAITS_GDKDRAGCONTEXT
#define HAVE_NSAUTOREFTRAITS_GDKDRAGCONTEXT
template <>
class nsAutoRefTraits<GdkDragContext> :
    public nsGObjectRefTraits<GdkDragContext> { };
#endif

/**
 * Native GTK DragService wrapper
 */

class nsDragService : public nsBaseDragService,
                      public nsIObserver
{
public:
    nsDragService();
    virtual ~nsDragService();

    NS_DECL_ISUPPORTS_INHERITED

    NS_DECL_NSIOBSERVER

    // nsIDragService
    NS_IMETHOD InvokeDragSession (nsIDOMNode *aDOMNode,
                                  nsISupportsArray * anArrayTransferables,
                                  nsIScriptableRegion * aRegion,
                                  uint32_t aActionType);
    NS_IMETHOD StartDragSession();
    NS_IMETHOD EndDragSession(bool aDoneDrag);

    // nsIDragSession
    NS_IMETHOD SetCanDrop            (bool             aCanDrop);
    NS_IMETHOD GetCanDrop            (bool            *aCanDrop);
    NS_IMETHOD GetNumDropItems       (uint32_t * aNumItems);
    NS_IMETHOD GetData               (nsITransferable * aTransferable,
                                      uint32_t aItemIndex);
    NS_IMETHOD IsDataFlavorSupported (const char *aDataFlavor, bool *_retval);

    // Methods called from nsWindow to handle responding to GTK drag
    // destination signals

    static nsDragService* GetInstance();

    void TargetDataReceived          (GtkWidget         *aWidget,
                                      GdkDragContext    *aContext,
                                      gint               aX,
                                      gint               aY,
                                      GtkSelectionData  *aSelection_data,
                                      guint              aInfo,
                                      guint32            aTime);

    gboolean ScheduleMotionEvent(nsWindow *aWindow,
                                 GdkDragContext *aDragContext,
                                 nsIntPoint aWindowPoint,
                                 guint aTime);
    void ScheduleLeaveEvent();
    gboolean ScheduleDropEvent(nsWindow *aWindow,
                               GdkDragContext *aDragContext,
                               nsIntPoint aWindowPoint,
                               guint aTime);

    nsWindow* GetMostRecentDestWindow()
    {
        return mScheduledTask == eDragTaskNone ? mTargetWindow
            : mPendingWindow;
    }

    //  END PUBLIC API

    // These methods are public only so that they can be called from functions
    // with C calling conventions.  They are called for drags started with the
    // invisible widget.
    void           SourceEndDragSession(GdkDragContext *aContext,
                                        gint            aResult);
    void           SourceDataGet(GtkWidget        *widget,
                                 GdkDragContext   *context,
                                 GtkSelectionData *selection_data,
                                 guint             info,
                                 guint32           aTime);

    // set the drag icon during drag-begin
    void SetDragIcon(GdkDragContext* aContext);

private:

    // mScheduledTask indicates what signal has been received from GTK and
    // so what needs to be dispatched when the scheduled task is run.  It is
    // eDragTaskNone when there is no task scheduled (but the
    // previous task may still not have finished running).
    enum DragTask {
        eDragTaskNone,
        eDragTaskMotion,
        eDragTaskLeave,
        eDragTaskDrop,
        eDragTaskSourceEnd
    };
    DragTask mScheduledTask;
    // mTaskSource is the GSource id for the task that is either scheduled
    // or currently running.  It is 0 if no task is scheduled or running.
    guint mTaskSource;

    // target/destination side vars
    // These variables keep track of the state of the current drag.

    // mPendingWindow, mPendingWindowPoint, mPendingDragContext, and
    // mPendingTime, carry information from the GTK signal that will be used
    // when the scheduled task is run.  mPendingWindow and mPendingDragContext
    // will be NULL if the scheduled task is eDragTaskLeave.
    nsRefPtr<nsWindow> mPendingWindow;
    nsIntPoint mPendingWindowPoint;
    nsCountedRef<GdkDragContext> mPendingDragContext;
    guint mPendingTime;

    // mTargetWindow and mTargetWindowPoint record the position of the last
    // eDragTaskMotion or eDragTaskDrop task that was run or is still running.
    // mTargetWindow is cleared once the drag has completed or left.
    nsRefPtr<nsWindow> mTargetWindow;
    nsIntPoint mTargetWindowPoint;
    // mTargetWidget and mTargetDragContext are set only while dispatching
    // motion or drop events.  mTime records the corresponding timestamp.
    nsCountedRef<GtkWidget> mTargetWidget;
    nsCountedRef<GdkDragContext> mTargetDragContext;
    guint           mTargetTime;

    // is it OK to drop on us?
    bool            mCanDrop;

    // have we received our drag data?
    bool            mTargetDragDataReceived;
    // last data received and its length
    void           *mTargetDragData;
    uint32_t        mTargetDragDataLen;
    // is the current target drag context contain a list?
    bool           IsTargetContextList(void);
    // this will get the native data from the last target given a
    // specific flavor
    void           GetTargetDragData(GdkAtom aFlavor);
    // this will reset all of the target vars
    void           TargetResetData(void);

    // source side vars

    // the source of our drags
    GtkWidget     *mHiddenWidget;
    // our source data items
    nsCOMPtr<nsISupportsArray> mSourceDataItems;

    nsCOMPtr<nsIScriptableRegion> mSourceRegion;

    // get a list of the sources in gtk's format
    GtkTargetList *GetSourceList(void);

    // attempts to create a semi-transparent drag image. Returns TRUE if
    // successful, FALSE if not
    bool SetAlphaPixmap(gfxASurface     *aPixbuf,
                          GdkDragContext  *aContext,
                          int32_t          aXOffset,
                          int32_t          aYOffset,
                          const nsIntRect &dragRect);

    gboolean Schedule(DragTask aTask, nsWindow *aWindow,
                      GdkDragContext *aDragContext,
                      nsIntPoint aWindowPoint, guint aTime);

    // Callback for g_idle_add_full() to run mScheduledTask.
    static gboolean TaskDispatchCallback(gpointer data);
    gboolean RunScheduledTask();
    void UpdateDragAction();
    void DispatchMotionEvents();
    void ReplyToDragMotion();
    gboolean DispatchDropEvent();
};

#endif // nsDragService_h__


text:
title: Glossary
description: A glossary of common Istio terms.
weight: 30
type: glossary
aliases:
  - /glossary
  - /docs/welcome/glossary.html
---

Common Istio words and phrases. Please [let us know](https://github.com/istio/istio.github.io/issues/new?title=Missing%20Glossary%20Entry) if you
came here looking for a definition and didn't find it.


text:
package team.unstudio.udpl.conversation.request;

import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

import team.unstudio.udpl.util.PluginUtils;

import java.math.BigDecimal;
import java.util.Optional;

public class RequestBigDecimal extends RequestBase<BigDecimal>{

	public static RequestBigDecimal newRequestBigDecimal(){
		return new RequestBigDecimal();
	}

	public static RequestBigDecimal create(){
		return new RequestBigDecimal();
	}

	private final Listener listener = new RequestListener();

	private BigDecimal result;

	@Override
	public void start() {
		super.start();
		PluginUtils.registerEvents(listener, getConversation().getPlugin());
		setStarted(true);
		sendPrompt();
	}

	@Override
	public void dispose() {
		super.dispose();
		AsyncPlayerChatEvent.getHandlerList().unregister(listener);
		PlayerCommandPreprocessEvent.getHandlerList().unregister(listener);
	}

	@Override
	public void reset() {
		result = null;
	}

	@Override
	public Optional<BigDecimal> getResult() {
		if(!isCompleted())
			return Optional.empty();
		return Optional.of(result);
	}

	private class RequestListener implements Listener{
		@EventHandler(priority = EventPriority.LOWEST)
		public void onChat(AsyncPlayerChatEvent event) {
			if(!event.getPlayer().equals(getConversation().getPlayer()))
				return;

			event.setCancelled(true);

			try{
				BigDecimal invalidate = new BigDecimal(event.getMessage());

				if(!validate(invalidate))
					return;

				result = invalidate;
				Bukkit.getScheduler().runTask(getConversation().getPlugin(), () -> setCompleted(true));
			}catch(NumberFormatException ignored){
			}
		}

		@EventHandler(priority = EventPriority.LOWEST)
		public void onCommand(PlayerCommandPreprocessEvent event) {
			if(!event.getPlayer().equals(getConversation().getPlayer()))
				return;

			event.setCancelled(true);

			try{
				BigDecimal invalidate = new BigDecimal(event.getMessage());

				if(!validate(invalidate))
					return;

				result = invalidate;
				setCompleted(true);
			}catch(NumberFormatException ignored){
			}
		}
	}
}


text:
//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 License
//
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
//    implied. See the License for the specific language governing
//    permissions and limitations under the License.
//
//*********************************************************//

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Microsoft.NodejsTools.Jade {
    class ReadOnlyTextRangeCollection<T> : IEnumerable<T>, IEnumerable where T : ITextRange {
        TextRangeCollection<T> _collection;

        public ReadOnlyTextRangeCollection(TextRangeCollection<T> collection) {
            _collection = collection;
        }

        public int Start { get { return _collection.Start; } }
        public int End { get { return _collection.End; } }

        public int Length { get { return _collection.Length; } }

        public bool Contains(int position) { return _collection.Contains(position); }

        public IList<T> ItemsInRange(ITextRange range) {
            return _collection.ItemsInRange(range);
        }

        public IList<T> ItemsInRange(int start) {
            return _collection.ItemsInRange(TextRange.FromBounds(start, start));
        }

        public IList<int> GetItemsContainingInclusiveEnd(int position) {
            return _collection.GetItemsContainingInclusiveEnd(position);
        }

        public int Count { get { return _collection.Count; } }

        /// <summary>
        /// Sorted list of comment tokens in the document.
        /// A new readonly collection is generated on every call to this method
        /// </summary>
        public ReadOnlyCollection<T> Items { get { return new ReadOnlyCollection<T>(_collection.Items); } }

        /// <summary>
        /// Retrieves Nth item in the collection
        /// </summary>
        public T this[int index] { get { return _collection[index]; } }

        /// <summary>
        /// Returns index of item that starts at the given position if exists, -1 otherwise.
        /// </summary>
        /// <param name="position">Position in a text buffer</param>
        /// <returns>Item index or -1 if not found</returns>
        public int GetItemAtPosition(int position) {
            return _collection.GetItemAtPosition(position);
        }

        public virtual int GetItemContaining(int position) {
            return _collection.GetItemContaining(position);
        }

        public virtual int GetFirstItemBeforePosition(int position) {
            return _collection.GetFirstItemBeforePosition(position);
        }

        public virtual int GetFirstItemAfterPosition(int position) {
            return _collection.GetFirstItemAfterPosition(position);
        }

        public T[] ToArray() {
            return _collection.ToArray();
        }

        //class RangeItemComparer : IComparer<T>
        //{
        //    #region IComparer<T> Members
        //    public int Compare(T x, T y)
        //    {
        //        return x.Start - y.Start;
        //    }
        //    #endregion
        //}

        #region IEnumerable<T> Members
        public IEnumerator<T> GetEnumerator() {
            return _collection.GetEnumerator();
        }
        #endregion

        #region IEnumerable Members
        IEnumerator IEnumerable.GetEnumerator() {
            return _collection.GetEnumerator();
        }
        #endregion
    }
}


text:
FROM kreczko/perfsonar/base

MAINTAINER Luke Kreczko <kreczko@cern.ch>


text:
This inspection reports any instances of the uses of java.lang.ProcessBuilder.
Uses of ProcessBuilder are inherently unportable between operating systems.

  Powered by InspectionGadgets


text:
---

---

document.addEventListener("DOMContentLoaded", function(event) {
    var hidden = true;
    var menu = document.querySelector(".main-nav");
    var opener = document.querySelector(".opener");
    opener.addEventListener("click", function(e){
        e.preventDefault();
        if(hidden){
            menu.setAttribute("class", "main-nav active-menu");
        }else{
            menu.setAttribute("class", "main-nav");
        }
        hidden = !hidden;
    });

    var cmtBtn = document.getElementById("showComments");
    if(!cmtBtn){
        return;
    }

    var commentHidden = true;
    var disqus_shortname = '';
    var dt = document.getElementById("disqus_thread");

    function loadDisqus() {
        if(disqus_shortname === ''){
            disqus_shortname = '{{ site.disqus }}';
            dt.innerHTML = 'Loading comments...';
            (function() {
                var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
                dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
                (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
            })();
        }
        if(commentHidden){
            dt.setAttribute('style','display:block');
            this.innerHTML = 'Hide Comments';
        }else{
            dt.setAttribute('style','display:none');
            this.innerHTML = 'Comments';
        }
        commentHidden = !commentHidden;
    }

    cmtBtn.addEventListener("click", function(e){
        e.preventDefault();
        loadDisqus();
    });

    var scrolling = false;

    function isElementInViewport (el) {
        if (typeof jQuery === "function" && el instanceof jQuery) {
            el = el[0];
        }

        var rect = el.getBoundingClientRect();

        scrolling = false;
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
        );
    }

    function enableScrolling(e) {
        scrolling = true;
    }

    window.addEventListener('scroll', enableScrolling);

    var interval = setInterval(function() {
        if(!scrolling) {
            return false;
        }
        if(isElementInViewport(cmtBtn)) {
            loadDisqus();
            clearInterval(interval);
            window.removeEventListener('scroll', enableScrolling);
        }
    }, 400);
});


text:
'use strict';

/**
 * Register a new task with Elixir.
 *
 * @param {string}   name
 * @param {Function} callback
 */
Elixir.extend = function (name, callback) {
    // If we've already registered a mixin of this name
    // we'll return early. This way, extensions can
    // override default behavior.
    if (this.mixins[name]) return;

    this.mixins[name] = function () {
        callback.apply(this, arguments);

        return this.mixins;
    }.bind(this);
};

/**
 * Register an external dependency install instruction.
 *
 * @param  {string} name
 * @param  {string} command
 */
Elixir.registerInstallInstruction = function (name, command) {
    Elixir.extend(name, function () {
        new Elixir.Task(name, function () {
            Elixir.log.error('Installation Required').error('To use "mix.' + name + '()", please run the following command, and then trigger gulp again.').command(command);

            process.exit(1);
        });
    });
};


text:
@implementation CDLiveItem

@dynamic name;
@dynamic url;
@dynamic rank;

@end