text:
package com.netcetera.trema.maven;

/**
 * Export data from a Trema file into property files.
 *
 * @goal exportProperties
 * @phase process-sources
 * @threadSafe
 */
public class ExportPropertiesMojo extends AbstractExportMojo {

  /**
   * Basename for the export. Path and beginning of the filename to be used for
   * the properties.
   *
   * @parameter property="basename"
   * default-value="${project.build.directory}/classes/text"
   */
  private String basename;

  /**
   * Defaultlanguage. If specified, this language will be exported into a
   * default properties file without the language in the filename, eg.
   * text.properties.
   *
   * @parameter property="defaultlanguage"
   */
  private String defaultlanguage;

  /**
   * Export filters. Filters to be applied for transformation of the text values
   * during properties file exporting. Possible values are: 'messageformat'
   * (converts one singlequote into two singlequotes) 'addkeytovalue' (appends
   * the key to each value for debugging purposes, resulting in: key=value
   * [key])
   *
   * @parameter property="filters"
   */
  private String[] filters;

  /**
   * Sets the basename.
   *
   * @param basename the basename to set
   */
  public void setBasename(String basename) {
    this.basename = basename;
  }

  /**
   * Sets the defaultlanguage.
   *
   * @param defaultlanguage the defaultlanguage to set
   */
  public void setDefaultlanguage(String defaultlanguage) {
    this.defaultlanguage = defaultlanguage;
  }

  /**
   * Sets the filters.
   *
   * @param filters the filters to set
   */
  public void setFilters(String[] filters) {
    this.filters = filters;
  }

  @Override
  protected ExportType getExportType() {
    return ExportType.PROPERTIES;
  }

  @Override
  protected String getBasename() {
    return basename;
  }

  @Override
  protected String getDefaultlanguage() {
    return defaultlanguage;
  }

  @Override
  protected String[] getFilters() {
    return filters;
  }

}


text:
package io.github.factoryfx.microservice;

public class DummyFileForSpotbugs {
}

redpajama_set_name: RedPajamaGithub


text:
import buildFormatLongFn from '../../../_lib/buildFormatLongFn/index.js';
var dateFormats = {
  full: 'EEEE, MMMM do, y',
  long: 'MMMM do, y',
  medium: 'MMM d, y',
  short: 'MM/dd/yyyy'
};
var timeFormats = {
  full: 'h:mm:ss a zzzz',
  long: 'h:mm:ss a z',
  medium: 'h:mm:ss a',
  short: 'h:mm a'
};
var dateTimeFormats = {
  full: "{{date}} 'عند' {{time}}",
  long: "{{date}} 'عند' {{time}}",
  medium: '{{date}}, {{time}}',
  short: '{{date}}, {{time}}'
};
var formatLong = {
  date: buildFormatLongFn({
    formats: dateFormats,
    defaultWidth: 'full'
  }),
  time: buildFormatLongFn({
    formats: timeFormats,
    defaultWidth: 'full'
  }),
  dateTime: buildFormatLongFn({
    formats: dateTimeFormats,
    defaultWidth: 'full'
  })
};
export default formatLong;


text:
package logger

import (
	"fmt"
	"log"
	"os"
	"regexp"
)

const calldepth = 3

var (
	Silent           bool
	Verbose          bool
	Color            bool
	stdOutLogger     = log.New(os.Stdout, "", 0)
	stdOutWarnLogger = log.New(os.Stdout, "WARNING: ", 0)
	stdErrLogger     = log.New(os.Stderr, "ERROR: ", 0)
)

func StdErrOutput(b []byte) (n int, err error) {
	if Color {
		b = append([]byte(ColorRed), b...)
		b = append(b, ColorNC...)
	}
	return os.Stderr.Write([]byte(b))
}

// io.Writer interface implementation. To use with error logs, pass StdErrOutput func:
// Writer(StdErrOutput) <- implements io.Writer
type Writer func(b []byte) (n int, err error)

func (w Writer) Write(b []byte) (n int, err error) {
	return w(b)
}

func Error(v ...interface{}) {
	Log(stdErrLogger, ColorRed, v...)
}

func Errorf(format string, v ...interface{}) {
	Logf(stdErrLogger, ColorRed, format, v...)
}

func Warn(v ...interface{}) {
	Log(stdOutWarnLogger, ColorLightRed, v...)
}

func Warnf(format string, v ...interface{}) {
	Logf(stdOutWarnLogger, ColorLightRed, format, v...)
}

func Heading(v ...interface{}) {
	if !Silent {
		Log(stdOutLogger, ColorGreen, v...)
	}
}

func Headingf(format string, v ...interface{}) {
	if !Silent {
		Logf(stdOutLogger, ColorGreen, format, v...)
	}
}

func Info(v ...interface{}) {
	if !Silent {
		Log(stdOutLogger, ColorCyan, v...)
	}
}

func Infof(format string, v ...interface{}) {
	if !Silent {
		Logf(stdOutLogger, ColorCyan, format, v...)
	}
}

func Debug(v ...interface{}) {
	if Verbose && !Silent {
		Log(stdOutLogger, ColorLightGrey, v...)
	}
}

func Debugf(format string, v ...interface{}) {
	if Verbose && !Silent {
		Logf(stdOutLogger, ColorLightGrey, format, v...)
	}
}

func Log(l *log.Logger, color string, v ...interface{}) {
	msg := fmt.Sprint(v...)
	if Color {
		msg = colorizeMessage(color, msg)
	}
	l.Output(calldepth, msg)
}

func Logf(l *log.Logger, color, format string, v ...interface{}) {
	msg := fmt.Sprintf(format, v...)
	if Color {
		msg = colorizeMessage(color, msg)
	}
	l.Output(calldepth, msg)
}

func colorizeMessage(color, s string) string {
	whitespace := regexp.MustCompile(`\s*$`)
	trimmed := whitespace.ReplaceAllString(s, "")
	trailing := whitespace.FindString(s)

	return color + trimmed + ColorNC + trailing
}


text:
(function () {
  'use strict';

  angular
    .module('horizon.app.core.openstack-service-api')
    .service('horizon.app.core.openstack-service-api.heat', heatAPI);

  heatAPI.$inject = [
    'horizon.framework.util.http.service',
    'horizon.framework.widgets.toast.service'
  ];

  /**
   * @ngdoc service
   * @name horizon.app.core.openstack-service-api.heat
   * @description Provides direct pass through to Heat with NO abstraction.
   */
  function heatAPI(apiService, toastService) {
    var service = {
      validate: validate,
      getServices: getServices
    };

    return service;

    /**
     * @name horizon.app.core.openstack-service-api.heat.validate
     * @description
     * Validate a template.
     *
     * The result is an object.
     *
     * @param {string} params.template_url
     * Specifies the template to validate.
     *
     * @param {boolean} suppressError
     * If passed in, this will not show the default error handling
     * (horizon alert).
     */
    function validate(params, suppressError) {
      var promise = apiService.post('/api/heat/validate/', params);
      return suppressError ? promise : promise.error(function() {
        toastService.add('error', gettext('Unable to validate the template.'));
      });
    }

    /**
     * @name horizon.openstack-service-api.heat.getServices
     * @description Get the list of heat services.
     *
     * @returns The listing result is an object with property "services." Each item is
     * a service.
     */
    function getServices() {
      return apiService.get('/api/heat/services/')
        .error(function () {
          toastService.add('error', gettext('Unable to retrieve the heat services.'));
        });
    }
  }

}());


text:
@interface CXReadSetupView : UIView

@property (nonatomic, strong) UIWebView *webView;

+ (instancetype)loadFromXib;
@end


text:
var Engine = function() {
	this.$id = "engine";
	this.$init = "init";
	this.$async = true;
}

Engine.prototype.init = function(cb) {
	console.log('engine init');
	cb();
}

Engine.prototype.run = function() {
	console.log('run engine...');
	return 'engine';
}

module.exports = Engine;


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace BlogRunnerGui
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}


text:
namespace extensions {
namespace image_writer {

using ::testing::_;
using ::testing::NiceMock;
using ::testing::SaveArg;
using ::testing::StrictMock;

class ExtractorBrowserTest : public InProcessBrowserTest {
 protected:
  ExtractorBrowserTest() = default;
  ~ExtractorBrowserTest() override = default;

  void SetUpOnMainThread() override {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

    properties_.temp_dir_path = temp_dir_.GetPath();
    properties_.open_callback = open_callback_.Get();
    properties_.complete_callback = complete_callback_.Get();
    properties_.failure_callback = failure_callback_.Get();
    properties_.progress_callback = progress_callback_.Get();
  }

 protected:
  StrictMock<base::MockCallback<ExtractionProperties::OpenCallback>>
      open_callback_;
  StrictMock<base::MockCallback<ExtractionProperties::CompleteCallback>>
      complete_callback_;
  StrictMock<base::MockCallback<ExtractionProperties::FailureCallback>>
      failure_callback_;
  NiceMock<base::MockCallback<ExtractionProperties::ProgressCallback>>
      progress_callback_;

  ExtractionProperties properties_;
  base::ScopedTempDir temp_dir_;
};

IN_PROC_BROWSER_TEST_F(ExtractorBrowserTest, ExtractTarXz) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  base::FilePath test_data_dir;
  ASSERT_TRUE(GetTestDataDirectory(&test_data_dir));
  properties_.image_path = test_data_dir.AppendASCII("test.tar.xz");

  base::FilePath out_path;
  base::RunLoop run_loop;
  EXPECT_CALL(open_callback_, Run(_)).WillOnce(SaveArg<0>(&out_path));
  EXPECT_CALL(complete_callback_, Run())
      .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  XzExtractor::Extract(std::move(properties_));
  run_loop.Run();

  std::string contents;
  ASSERT_TRUE(base::ReadFileToString(out_path, &contents));
  EXPECT_EQ("foo\n", contents);
}

IN_PROC_BROWSER_TEST_F(ExtractorBrowserTest, ExtractNonExistentTarXz) {
  base::ScopedAllowBlockingForTesting allow_blocking;

  base::FilePath test_data_dir;
  ASSERT_TRUE(GetTestDataDirectory(&test_data_dir));
  properties_.image_path = test_data_dir.AppendASCII("non_existent.tar.xz");

  base::RunLoop run_loop;
  EXPECT_CALL(failure_callback_, Run(error::kUnzipGenericError))
      .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  XzExtractor::Extract(std::move(properties_));
  run_loop.Run();
}

}  // namespace image_writer
}  // namespace extensions


text:
Alignment.LEFT   = 0
Alignment.RIGHT  = 1
Alignment.TOP    = 2
Alignment.BOTTOM = 3
Alignment.CENTER = 4


text:
using NUnit.Framework;
using Solyutor.EventPublisher.Impl;

namespace Solyutor.EventPublisher.Tests.Impl
{
    [TestFixture]
    public class SimplePublishWayTest
    {
        [Test]
        public void Publish_calls_the_method_on_subscriber()
        {
            var simplePublishWay = new SimpleDispatcher();
            var message = new TestMessage();
            var handler = new TestHandler();

            simplePublishWay.Invoke(message, handler);

            Assert.That(handler.TestMessage, Is.SameAs(message));
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface DoraemonStartTimeProfilerViewController : DoraemonBaseViewController

@end

NS_ASSUME_NONNULL_END


text:
<?php

require_once (dirname(__FILE__).'/ns-log-utils.php');

/*
 * Get the uploads folder for the site passed in with $id
 *
 * HANDLE 2 POTENTIAL SCENARIOS:
 * 1) WP Install originated before 3.5 and has legacy /wp-content/blogs.dir/ storage
 * 2) WP Install originated with 3.5 or later and has /wp-content/uploads/sites/ storage
 *
 * ADD-ON MAYBE NEEDED TO HANDLE POTENTIAL 3rd SCENARIO:
 * 3) WP Install has custom uploads storage in which case it might be difficult to handle
 * 	  Add-on has options:
 *    - use strict wp_upload_dir()
 * 	  - set manual upload_path at clone time (auto-fill from query on option_value in
 *  	wp_##_options where option_name = 'upload_path')
 *    - TODO: might need to add a filter to this to allow add-ons to modify
 *
 * NEW ALGORITHM:
 * - use 2 factors and 3 tests per factor to determine confidence level of accurate detection
 * - 2 factors: pre (test_1) or post (test_2) version 3.5 of WP Installation Origin
 * - 3 tests per factor:
 * 	 - does the base uploads directory of the factor exist?
 *   - does a hypothetical site uploads dir of the factor based on $id exist?
 *   - does the hypothetical site uploads dir of the factor match the result of wp_uploads_dir()?
 * - establish and return an $upload_dir in descending order of confidence based on how many
 *   tests per fact are true
 */

function ns_get_upload_dir( $id, $logfile=false ) {
// ---------------------------------------------------------------------------------------------------------------------
//										T E S T I N G  	 N E W    C O D E
// ---------------------------------------------------------------------------------------------------------------------
	// initialize
	switch_to_blog($id);
	$wp_upload_dir_a = wp_upload_dir();
	restore_current_blog();
	$wp_upload_dir = ns_norm_winpath($wp_upload_dir_a['basedir']);
	$upload_dir = ''; // eventual return value

	// handle difference between ID = 1 and everything else
	// in ID = 1 test_1 and test_2 are identical
	if ($id == 1) {
		$test_1_base = ns_norm_winpath(WP_CONTENT_DIR . '/uploads');
		$test_1_upload_dir = ns_norm_winpath($test_1_base);
		$test_2_base = ns_norm_winpath(WP_CONTENT_DIR . '/uploads');
		$test_2_upload_dir = ns_norm_winpath($test_2_base);
	} else {
		$test_1_base = ns_norm_winpath(WP_CONTENT_DIR . '/blogs.dir');
		$test_1_upload_dir = ns_norm_winpath($test_1_base . '/' . $id);
		$test_2_base = ns_norm_winpath(WP_CONTENT_DIR . '/uploads/sites');
		$test_2_upload_dir = ns_norm_winpath($test_2_base . '/' . $id);
	}

	// compare and set conditions for determining confidence level
	$test_1_base_exists = (file_exists($test_1_base) ? true : false);
	$test_1_upload_dir_exists = (file_exists($test_1_upload_dir) ? true : false);
	$test_1_matches_wp = ($test_1_upload_dir == $wp_upload_dir ? true : false);
	$test_2_base_exists = (file_exists($test_2_base) ? true : false);
	$test_2_upload_dir_exists = (file_exists($test_2_upload_dir) ? true : false);
	$test_2_matches_wp = ($test_2_upload_dir == $wp_upload_dir ? true : false);
	$wp_upload_dir_exists = (file_exists($wp_upload_dir) ? true : false);

	// cascade in order of confidence
	// HIGH CONFIDENCE ----------------------------------------------------------------------------------
	// WP Origin < 3.5
	if ($test_1_base_exists && $test_1_upload_dir_exists && $test_1_matches_wp) {
		$upload_dir = $test_1_upload_dir;
		$confidence = 'HIGH CONFIDENCE';
	}
	// WP Origin > 3.5 (fall through if $upload_dir already set)
	if ($upload_dir == '' && $test_2_base_exists && $test_2_upload_dir_exists && $test_2_matches_wp) {
		$upload_dir = $test_2_upload_dir;
		$confidence = 'HIGH CONFIDENCE';
	}
	// MEDIUM CONFIDENCE --------------------------------------------------------------------------------
	// WP Origin < 3.5 (fall through if $upload_dir already set)
	if ($upload_dir == '' && $test_1_base_exists && $test_1_matches_wp) {
		$upload_dir = $test_1_upload_dir;
		$confidence = 'MEDIUM CONFIDENCE';
	}
	// WP Origin > 3.5 (fall through if $upload_dir already set)
	if ($upload_dir == '' && $test_2_base_exists && $test_2_matches_wp) {
		$upload_dir = $test_2_upload_dir;
		$confidence = 'MEDIUM CONFIDENCE';
	}
	// LOW CONFIDENCE -----------------------------------------------------------------------------------
	// WP Origin < 3.5 (fall through if $upload_dir already set)
	if ($upload_dir == '' && $test_1_base_exists) {
		$upload_dir = $test_1_upload_dir;
		$confidence = 'LOW CONFIDENCE';
	}
	// WP Origin > 3.5 (fall through if $upload_dir already set)
	if ($upload_dir == '' && $test_2_base_exists) {
		$upload_dir = $test_2_upload_dir;
		$confidence = 'LOW CONFIDENCE';
	}
	// FAIL SAFE ----------------------------------------------------------------------------------------
	if ($upload_dir == '') {
		$upload_dir = $wp_upload_dir;
		$confidence = 'FAIL SAFE';
	}

	// log results for debugging
	ns_log_section_break($logfile);
	ns_log_write('TESTING UPLOAD LOCATION for ID = ' . $id, $logfile);
	ns_log_section_break($logfile);
	ns_log_write('wp_upload_dir	     = ' . $wp_upload_dir . ns_t2e($wp_upload_dir_exists), $logfile);
	ns_log_write('test_1_base        = ' . $test_1_base . ns_t2e($test_1_base_exists), $logfile);
	ns_log_write('test_1_upload_dir  = ' . $test_1_upload_dir . ns_t2e($test_1_upload_dir_exists), $logfile);
	ns_log_write('test_1_matches_wp  = ' . ns_t2e($test_1_matches_wp), $logfile);
	ns_log_write('test_2_base        = ' . $test_2_base . ns_t2e($test_2_base_exists), $logfile);
	ns_log_write('test_2_upload_dir  = ' . $test_2_upload_dir . ns_t2e($test_2_upload_dir_exists), $logfile);
	ns_log_write('test_2_matches_wp  = ' . ns_t2e($test_2_matches_wp), $logfile);
	ns_log_write('upload_dir = ' . $upload_dir . ' with ' . $confidence, $logfile);
	ns_log_section_break ($logfile);

	return $upload_dir ;
}

/*
 * Get the URL for uploads for a site - V2 didn't have advanced checking like above on this so not adding it for now
 */
function ns_get_upload_url( $id, $logfile=false ){
	switch_to_blog($id);
	$wp_upload_dir_a = wp_upload_dir();
	restore_current_blog();
	return $wp_upload_dir_a['baseurl'];
}

/**
 * Check for windows-based systems and normalize if necessary
 */
function ns_norm_winpath( $path ) {
	if (strpos($path ,'/') !== false && strpos($path ,'\\') !== false ) {
		return str_replace('/', '\\', $path );
	} else {
		return $path;
	}
}

/**
 * Translate boolean to exists or not exists
 */
function ns_t2e( $bool ) {
	if ($bool) {
		return ' (EXISTS)';
	} else {
		return ' (NOT EXISTS)';
	}
}

/**
 * Copy directories and files recursively and return number of copies executed
 * Skip directories called 'sites' to avoid copying all sites storage in WP > 3.5
 * @return int number of files copied
 */
function ns_recursive_dir_copy( $src, $dst, $num=0 ) {
	$num = $num + 1;
	if( is_dir($src) ){
		if( !file_exists($dst) ){
			mkdir($dst);
		}
		$files = scandir($src);
		foreach ($files as $file){
			if ($file != "." && $file != ".." && $file != 'sites'){
				$num = ns_recursive_dir_copy("$src/$file", "$dst/$file", $num);
			}
		}
	}
	elseif( file_exists($src) ){
		copy($src, $dst);
	}
	return $num;
}

/**
 * Return an array of all blog upload dir paths
 */
function ns_get_multisite_upload_paths( $args=array('limit'=>9999) ){
	$upload_paths = array();
	$sites = function_exists('wp_get_sites')? wp_get_sites($args) : get_blog_list(0,'all');
	foreach( $sites as $site ){
		switch_to_blog($site['blog_id']);
		$wp_upload_dir = wp_upload_dir();
		$upload_paths[ $site['blog_id'] ] = $wp_upload_dir['basedir'];
		restore_current_blog();
	}
	return $upload_paths;
}

?>


text:
require 'blazing/recipe'

class Blazing::Recipe::PrecompileAssets < Blazing::Recipe

  def run(target_options = {})
    super target_options

    info 'precompiling assets'
    system 'bundle exec rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile'
  end

end


text:
using System.Diagnostics;
using Microsoft.Build.Evaluation;

namespace TheCsprojLibrary.ItemTypes
{
    [DebuggerDisplay("{UnevaluatedInclude}")]
    [DebuggerTypeProxy(typeof(WCFMetadataStorageDisplayProxy))]
    public class WCFMetadataStorage : ItemTypeBase
    {

        public WCFMetadataStorage(ProjectItem item)
            : base(item)
        {

        }

    }
}


text:
<!-- example(dl-overview) -->

### Horizontal
<!-- example(dl-horizontal-overview) -->

### Vertical
<!-- example(dl-vertical-overview) -->


text:
package com.github.dockerjava.api.command;

import com.github.dockerjava.api.model.Config;

import java.util.List;
import java.util.Map;

/**
 * Command to list all configs in a docker swarm. Only applicable if docker runs in swarm mode.
 *
 * @since {@link RemoteApiVersion#VERSION_1_30}
 */
public interface ListConfigsCmd extends SyncDockerCmd<List<Config>> {

    Map<String, List<String>> getFilters();

    ListConfigsCmd withFilters(Map<String, List<String>> filters);

    interface Exec extends DockerCmdSyncExec<ListConfigsCmd, List<Config>> {
    }
}


text:
package org.locationtech.geowave.adapter.raster.adapter;

import org.locationtech.geowave.core.store.data.field.FieldReader;

public class RasterTileReader implements FieldReader<RasterTile<?>> {

  @Override
  public RasterTile<?> readField(final byte[] fieldData) {

    // the class name is not prefaced in the payload, we are assuming it is
    // a raster tile implementation and instantiating it directly

    final RasterTile retVal = new RasterTile();
    if (retVal != null) {
      retVal.fromBinary(fieldData);
    }
    return retVal;
  }
}


text:
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ether_types

class L2Switch(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(L2Switch, self).__init__(*args, **kwargs)
        self.mac_to_port = {}

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.
        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions)

    def add_flow(self, datapath, priority, match, actions, buffer_id=None):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
                                             actions)]
        if buffer_id:
            mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
                                    priority=priority, match=match,
                                    instructions=inst)
        else:
            mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                                    match=match, instructions=inst)
        datapath.send_msg(mod)

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        # If you hit this you might want to increase
        # the "miss_send_length" of your switch
        if ev.msg.msg_len < ev.msg.total_len:
            self.logger.debug("packet truncated: only %s of %s bytes",
                              ev.msg.msg_len, ev.msg.total_len)
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        in_port = msg.match['in_port']

        pkt = packet.Packet(msg.data)
        eth = pkt.get_protocols(ethernet.ethernet)[0]

        if eth.ethertype == ether_types.ETH_TYPE_LLDP:
            # ignore lldp packet
            return
        dst = eth.dst
        src = eth.src

        dpid = datapath.id
        self.mac_to_port.setdefault(dpid, {})

        # self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)

        # learn a mac address to avoid FLOOD next time.
        self.mac_to_port[dpid][src] = in_port

        if dst in self.mac_to_port[dpid]:
            out_port = self.mac_to_port[dpid][dst]
        else:
            out_port = ofproto.OFPP_FLOOD

        actions = [parser.OFPActionOutput(out_port)]

        # install a flow to avoid packet_in next time
        if out_port != ofproto.OFPP_FLOOD:
            match = parser.OFPMatch(in_port=in_port, eth_dst=dst)
            # verify if we have a valid buffer_id, if yes avoid to send both
            # flow_mod & packet_out
            if msg.buffer_id != ofproto.OFP_NO_BUFFER:
                self.add_flow(datapath, 1, match, actions, msg.buffer_id)
                return
            else:
                self.add_flow(datapath, 1, match, actions)
        data = None
        if msg.buffer_id == ofproto.OFP_NO_BUFFER:
            data = msg.data

        out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
                                  in_port=in_port, actions=actions, data=data)
        datapath.send_msg(out)


text:
<ion-view title="{{confirmation.phone}}">
  <ion-nav-buttons side="right">
    <button ng-click="confirm()" ng-disabled="!confirmation.code || confirmation.code.length === 0" class="button button-clear button-positive">Done</button>
  </ion-nav-buttons>

  <ion-content>

      We have sent you an SMS with a code to the number above

      To complete your phone number verification WhatsApp, please enter the 4-digit activation code.

        <input ng-model="confirmation.code" on-return="confirm()" type="text" placeholder="Code">

  </ion-content>
</ion-view>


text:
module GeographicApiClient
  #
  class LiteLocation < BaseObject
    attr_accessor :position, :vicinity
    # attribute mapping from ruby-style variable name to JSON key
    def self.attribute_map
      {

        # Position defined by latitude and longitude
        :'position' => :'position',

        # Vicinity description
        :'vicinity' => :'vicinity'

      }
    end

    # attribute type
    def self.swagger_types
      {
        :'position' => :'Position',
        :'vicinity' => :'string'

      }
    end

    def initialize(attributes = {})
      return if !attributes.is_a?(Hash) || attributes.empty?

      # convert string to symbol for hash key
      attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}

      if attributes[:'position']
        @position = attributes[:'position']
      end

      if attributes[:'vicinity']
        @vicinity = attributes[:'vicinity']
      end

    end
  end
end


text:
This app is an extension of the barebones application provided together with the University of Coventry 302CEM 2017 coursework assignment.

The app can be directly accessed from Heroku at the following URLS:

https://theta-web.herokuapp.com/ (for students)

https://theta-web.herokuapp.com/indexLecturer.html (for lecturers)

Additional features for students include the ability to view and download resource files as well as to book one-to-one appointments based on lecturer availability.

Additional features for lecturers include the ability to view student appointments, as well as to upload worksheets and other resource materials to the system.

The system is implemented in PHP using PostgreSQL as the database server, and hosted on the Heroku cloud application platform.

Git is used as the software version control tool, both on the local Heroku git repository, and also for version control of the codes on github.

For creating the Heroku git application, a sample Heroku PHP git project was cloned and modified, as explained in [Getting Started with PHP on Heroku](https://devcenter.heroku.com/articles/getting-started-with-php) article.

## Deploying

Install the [Heroku Toolbelt](https://toolbelt.heroku.com/).

```sh
$ git clone git@github.com:heroku/php-getting-started.git # or clone your own fork
$ cd php-getting-started
$ heroku create
$ git push heroku master
$ heroku open
```

or

[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

## Documentation

For more information about using PHP on Heroku, see these Dev Center articles:

- [Getting Started with PHP on Heroku](https://devcenter.heroku.com/articles/getting-started-with-php)
- [PHP on Heroku](https://devcenter.heroku.com/categories/php)


text:
package trunk.parallel.engine.opt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import trunk.graph.Edge;
import trunk.graph.SimpleGraph;
import trunk.graph.Vertex;
import trunk.parallel.engine.exec.operator.BindJoin;
import trunk.parallel.engine.exec.operator.EdgeOperator;
import trunk.parallel.engine.exec.operator.HashJoin;

public class GrdyOptimiser extends Optimiser {

	private Set<Vertex> remainVertices;
	private int edgepertime = 4;

	public GrdyOptimiser(SimpleGraph g) {
		super(g);
		remainVertices = new HashSet<Vertex>();
		remainVertices.addAll(g.getVertices());
	}

	@Override
	public List<EdgeOperator> nextStage() {
		if(g.getEdges().isEmpty())
			return null;
		List<EdgeOperator> operators = new ArrayList<EdgeOperator>();
		int size = Integer.MAX_VALUE;
		Vertex mini = null;
		for(Vertex v:g.getVertices()) {
			if(v.getNumber()<size) {
				mini = v;
				size = v.getNumber();
			}
		}

		remainVertices.remove(mini);
		Set<Edge> edges = new HashSet<Edge>(mini.getEdges());
		for(Edge e:edges) {
			g.removeEdge(e);
			if(e.getV1().getNode().isConcrete() || e.getV2().getNode().isConcrete()) {
				operators.add(new HashJoin((Edge) e));
			} else {
				operators.add(new BindJoin(mini,(Edge) e));
			}
		}
		return operators;
	}

	@Override
	public Set<Vertex> getRemainVertices() {
		return remainVertices;
	}

	public Edge nextEdge(){
		List<Edge> edges = g.getEdges();
		Edge e = null;
		double min = Double.MAX_VALUE;
		for(Edge edge:edges) {
			if(((Edge) edge).estimatedCard() < min) {
				min = ((Edge) edge).estimatedCard();
				e = (Edge) edge;
			}
		}

		return e;
	}

	public Map<Edge,Vertex> nextEdges() {
		Map<Edge,Vertex> next = new HashMap<Edge,Vertex>();

		Set<Vertex> starts = new HashSet<Vertex>();
		Set<Vertex> ends = new HashSet<Vertex>();
		for(int i = 0; i < edgepertime && remainVertices.size() > 1
				&& !g.getEdges().isEmpty();i++) {
			Edge e = nextEdge();
			Vertex start = e.getV1();
			Vertex end = e.getV2();
			if(start.getNumber()>end.getNumber()) {
				Vertex temp = start;
				start = end;
				end = temp;
			}

			if(starts.contains(end) || ends.contains(start)) {
				Vertex temp = start;
				start = end;
				end = temp;
				if(starts.contains(end) || ends.contains(start)) {
					start = null;
					end = null;
				}
			}

			if(start == null)
				break;
			starts.add(start);
			Set<Edge> adj = start.getEdges();
			for(Edge edge:adj) {
				if(edge.getV1().equals(start)) {
					ends.add(edge.getV2());
				}else {
					ends.add(edge.getV1());
				}
			}
			remainVertices.remove(start);
			remainVertices.add(end);
			g.removeEdge(e);
			next.put(e, start);
		}

		/*for(int i = 0;i < edgepertime && remainVertices.size() > 1;) {

			//select the minimum vertex that is not connected with any vertex that has been selected
			//this is to make sure that a vertex won't be the start point in the evaluation of one edge,
			//and at the same time the end point of another. For example, {a p1 ?o, ?o p2 b} should be evaluated
			//sequentially rather than in parallel.
			List<CostObject> costs = new ArrayList<CostObject>();
			for(Vertex v:g.getVertices())
				costs.add(new CostObject(g,v));
			Collections.sort(costs);

			Vertex v = null;
			Iterator<Edge> iter = next.keySet().iterator();
			int k = 0;
			do {
				v = costs.get(k).getV();
				//check whether v is connected by vertices that have been selected
				while(iter.hasNext()) {
					Edge edg = iter.next();
					if(edg.getV1().equals(v) || edg.getV2().equals(v)) {
						v = null;
						break;
					}
				}
				k++;
			} while (k<costs.size() && v == null);

			if(v == null) {
				break;//break when no vertex is available
			}
			remainVertices.remove(v);
			List<Edge> edges = g.asList().get(v);
			Collections.sort(edges);
			for(int j = 0;j < edgepertime && j < edges.size();j++) {
				next.put((Edge) edges.get(j), v);
				g.removeEdge(edges.get(j));
				i++;
			}
			if(g.getEdges().isEmpty()) {
				break;
			}
		}*/
		return next;
	}

}


text:
<meta property="fb:app_id" content="{{ env('FACEBOOK_CLIENT_ID') }}" />
<meta property="og:url" content="{{ route('proposition', [$proposition['propositionId']]) }}" />
<meta property="og:title" content="{{ $proposition['propositionSort'] }}" />
@if (empty($proposition['propositionLong']) == false) <meta property="og:description" content="{{ $proposition['propositionLong'] }}" />
@else <meta property="og:description" content="You have finally got the power to change things! Take part in your school's decision making" />
@endif
<meta property="og:image" content="{{ asset('img/logo.png') }}" />
<meta property="og:site_name" content="DirectDemocracy.Online">


text:
IMPLEMENT_CONOBJECT( VMotionTrack );
//-----------------------------------------------------------------------------

VMotionTrack::VMotionTrack( void ) :
        mDataReference( String::EmptyString ),
        mOrientationMode( "FREE" ),
        mOrientationData( String::EmptyString ),
        mRelative( false )
{
    setLabel( "MotionTrack" );
}

void VMotionTrack::initPersistFields( void )
{
    Parent::initPersistFields();

    addField( "Reference", TypeRealString, Offset( mDataReference, VMotionTrack ), "The name of the data field referencing the object to be attached to the path." );

    addProtectedField( "OrientationMode", TypeRealString, Offset( mOrientationMode, VMotionTrack ), &setOrientationMode, &defaultProtectedGetFn, "The orientation mode of the object attached to the path." );
    addProtectedField( "OrientationData", TypeRealString, Offset( mOrientationData, VMotionTrack ), &setOrientationData, &defaultProtectedGetFn, "The name of the data field holding the orientation data (used for Orientation Modes, ToObject & ToPoint)." );
    addField( "Relative",                 TypeBool,       Offset( mRelative,        VMotionTrack ), "Attach the object with an offset based on its initial position." );
}

//-----------------------------------------------------------------------------
//
// Controller Methods.
//
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//
// VMotionTrack::onControllerEvent( pEvent );
//
// When the controller's state changes, this method is called. If the
// controller is paused, then the path object will cease to move. If the
// controller resumes play, the object will continue on its path.
//
// For a full list of possible events, see the 'eControllerEventType'
// declaration in VController.h.
//
//-----------------------------------------------------------------------------
bool VMotionTrack::onControllerEvent( VController::eControllerEventType pEvent )
{
    if ( !Parent::onControllerEvent( pEvent ) )
    {
        // Skip.
        return false;
    }

    // Enabled?
    if ( !isEnabled() )
    {
        // Continue Processing Events.
        return true;
    }

    // Fetch Path & Reference Object.
    VTorque::PathObjectType  *path   = getPath();
    VTorque::SceneObjectType *object = getSceneObject();
    if ( !path || !object || !VTorque::isPathObjectAttached( path, object ) )
    {
        // Invalid.
        return true;
    }

    switch ( pEvent )
    {
        case VController::k_EventPlay :
            {

                // Continue Advancing.
                VTorque::setPathObjectActive( path, object, true );

            } break;

        case VController::k_EventPause :
            {

                // Stop Advancing.
                VTorque::setPathObjectActive( path, object, false );

            } break;

        case VController::k_EventStop :
            {

                // Detach the Object.
                detachObject();

            } break;
    }

    return true;
}

//-----------------------------------------------------------------------------
//
// VMotionTrack::onControllerReset( pTime, pForward );
//
// Reposition the path object on the path appropriately. The position is
// interpolated between two nodes, the last node and the next node. These
// correspond to the last and current events.
//
//-----------------------------------------------------------------------------
void VMotionTrack::onControllerReset( const S32 &pTime, const bool &pForward )
{
    // Parent Reset.
    Parent::onControllerReset( pTime, pForward );

    // Valid Track?
    // Note: We must have at least 2 Events/Nodes to path.
    if ( size() < 2 )
    {
        // Invalid.
        return;
    }

    // Get Object References.
    VController              *controller = getController();
    VTorque::PathObjectType  *path       = getPath();
    VTorque::SceneObjectType *object     = getSceneObject();
    if ( !controller || !path || !object )
    {
        // Invalid Object(s).
        return;
    }

    // Attached?
    if ( !VTorque::isPathObjectAttached( path, object ) )
    {
        // No, Attach Now.
        attachObject();
    }

    // Reset Object.
    resetObject( pTime );
}

//-----------------------------------------------------------------------------
//
// Reference Methods.
//
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//
// VMotionTrack::getPath();
//
// Returns the path that this track is referencing.
//
//-----------------------------------------------------------------------------
VTorque::PathObjectType *VMotionTrack::getPath( void )
{
    // Fetch the Controller.
    VController *controller = getController();
    if ( !controller )
    {
        // Invalid Controller.
        return NULL;
    }

    // Evalulate the Data Field.
    String fieldValue;
    if ( controller->getDataValue( mDataReference, fieldValue ) )
    {
        // Return Object.
        return dynamic_cast<VTorque::PathObjectType*>( Sim::findObject( fieldValue ) );
    }

    // No Data!
    return NULL;
}

//-----------------------------------------------------------------------------
//
// VMotionTrack::attachObject();
//
// Attach the underlying Scene Object to the target Path at the first Node.
// Default settings are applied and must be updated after the object is
// attached.
//
//-----------------------------------------------------------------------------
void VMotionTrack::attachObject( void )
{
    // Get Object References.
    VTorque::PathObjectType  *path   = getPath();
    VTorque::SceneObjectType *object = getSceneObject();
    if ( !path || !object )
    {
        // Invalid Object(s).
        return;
    }

    // Object Attached?
    if ( VTorque::isPathObjectAttached( path, object ) )
    {
        // Already Attached.
        return;
    }

    // Fetch Forwards.
    const bool &forward = isControllerPlayingForward();
    // Select the Node.
    const S32 node = ( forward ) ? 0 : ( size() - 1 );

    // Fetch the value from the controller data table.
    String orientationDataValue = String::EmptyString;
    if ( mOrientationData != String::EmptyString
         && !getController()->getDataValue( mOrientationData, orientationDataValue ) )
    {
        // Sanity!
        Con::warnf( "Unable to located the value for the given orientation data key, '%s'", mOrientationData );
        // Clear.
        orientationDataValue = String::EmptyString;
    }

    // Attach Object.
    VTorque::attachPathObject( path, object, forward, mRelative, node, -1, mOrientationMode, orientationDataValue );
}

//-----------------------------------------------------------------------------
//
// VMotionTrack::detachObject( void );
//
//
//
//-----------------------------------------------------------------------------
void VMotionTrack::detachObject( void )
{
    // Get Object References.
    VTorque::PathObjectType  *path   = getPath();
    VTorque::SceneObjectType *object = getSceneObject();
    if ( !path || !object )
    {
        // Invalid Object(s).
        return;
    }

    // Object Attached?
    if ( !VTorque::isPathObjectAttached( path, object ) )
    {
        // Not Attached.
        return;
    }

    // Detach.
    VTorque::detachPathObject( path, object );
}

//-----------------------------------------------------------------------------
//
// VMotionTrack::resetObject( pTime );
//
//
//
//-----------------------------------------------------------------------------
void VMotionTrack::resetObject( const S32 &pTime )
{
    // Get Object References.
    VTorque::PathObjectType  *path   = getPath();
    VTorque::SceneObjectType *object = getSceneObject();
    if ( !path || !object )
    {
        // Invalid Object(s).
        return;
    }

    // Fetch Controller Info.
    const bool &isPlaying        = isControllerPlaying();
    const bool &isPlayingForward = isControllerPlayingForward();
    const bool &isLooping        = isControllerLooping();

    // Init Variables.
    bool objectActive = false;
    F32  objectInterp = 0.f;
    F32  objectSpeed  = 0.f;
    S32  srcNodeIndex = 0;
    S32  dstNodeIndex = 0;

    VMotionEvent *event;
    if ( !getNextEvent( event ) || event->getTriggerTime() == pTime )
    {
        // Note: This case deals with a target time that is greater than the
        //       trigger time of the Last Event on this track. It will clamp
        //       the position of the object to the corresponding node of the
        //       Last Event.

        // Note: If pTime is exactly equal to the Next Event's trigger time,
        //       then it will set the Source Node to the Last Node and
        //       set its Interp to 0.f - which is incorrect!
        if ( !event || event->getTriggerTime() != pTime  )
        {
            // Fetch the Last Event.
            getPreviousEvent( event );
        }

        // Set the Info.
        objectInterp = 0.f;
        objectSpeed  = event->getObjectSpeed();
        srcNodeIndex = event->getNodeIndex();
        dstNodeIndex = srcNodeIndex;
    }
    else if ( !event->getPreviousEvent() )
    {
        // Note: This case deals with a target time that is less than the
        //       trigger time of the First Event on this track. It will clamp
        //       the position of the object to the corresponding node of the
        //       First Event.

        // Set the Info.
        objectInterp = 0.f;
        objectSpeed  = event->getObjectSpeed();
        srcNodeIndex = event->getNodeIndex();
        dstNodeIndex = srcNodeIndex;
    }
    else
    {
        // Note: This case deals with a target time that is between two Events
        //       on this track. It will position the object on the path,
        //       between the two nodes corresponding to the Events.

        // Fetch the Last Event.
        VMotionEvent *lastEvent;
        getPreviousEvent( lastEvent );

        // Set the Info.
        objectActive = isPlaying;
        objectInterp = calculateInterp( pTime );
        objectSpeed  = lastEvent->getObjectSpeed();
        srcNodeIndex = event->getNodeIndex( ( isPlayingForward ) ? -1 : 1 );
        dstNodeIndex = event->getNodeIndex();
    }

    // Set Active.
    VTorque::setPathObjectActive( path, object, objectActive );

    // Set Forward.
    VTorque::setPathObjectForward( path, object, isPlayingForward );

    // Set Speed.
    VTorque::setPathObjectSpeed( path, object, objectSpeed );

    // Set Current Node.
    VTorque::setPathObjectNode( path, object, srcNodeIndex );

    // Set End Node.
    VTorque::setPathObjectEndNode( path, object, ( ( isLooping ) ? -1 : ( size() - 1 ) ) );

    // Set Interp.
    VTorque::setPathObjectInterp( path, object, objectInterp );
}

//-----------------------------------------------------------------------------
//
// Static Field Methods.
//
//-----------------------------------------------------------------------------

bool VMotionTrack::setOrientationMode( void *pObject, const char *pArray, const char *pData )
{
    // Fetch Track.
    VMotionTrack *track = static_cast<VMotionTrack*>( pObject );

    // Store Data.
    track->mOrientationMode = pData;

    VTorque::PathObjectType  *path   = track->getPath();
    VTorque::SceneObjectType *object = track->getSceneObject();
    if ( VTorque::isPathObjectAttached( path, object ) )
    {
        // Set Orientation Mode.
        VTorque::setPathObjectOrientation( path, object, track->mOrientationMode, track->mOrientationData );
    }

    return false;
}

bool VMotionTrack::setOrientationData( void *pObject, const char *pArray, const char *pData )
{
    // Fetch Track.
    VMotionTrack *track = static_cast<VMotionTrack*>( pObject );

    // Store Data.
    track->mOrientationData = pData;

    VTorque::PathObjectType  *path   = track->getPath();
    VTorque::SceneObjectType *object = track->getSceneObject();
    if ( VTorque::isPathObjectAttached( path, object ) )
    {
        // Set Orientation Mode.
        VTorque::setPathObjectOrientation( path, object, track->mOrientationMode, track->mOrientationData );
    }

    return false;
}

#ifdef VT_EDITOR
//-----------------------------------------------------------------------------
//
// Debug Methods.
//
//-----------------------------------------------------------------------------

ConsoleMethod( VMotionTrack, getPath, S32, 2, 2, "( void ) - Get the path object this track references.\n"
                                                 "@return Returns the SimObjectID for the object." )
{
    // Fetch Path.
    SimObject *pathReference = object->getPath();

    // Return.
    return ( pathReference ) ? pathReference->getId() : 0;
}
#endif


text:
<?php namespace VKBot;

abstract class Command
{
    public $name = '';
    public $aliases = [];

    abstract public function execute($message);

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    public function setAliases($aliases)
    {
        if (is_array($aliases)) {
            $this->aliases = $aliases;
        } else {
            $this->aliases[] = $aliases;
        }
        return $this;
    }
}


text:
import os
from secrets import token_hex
from alembic import command
from alembic.config import Config
from jawaf.management.base import TemplateCommand

METADATA_CODE = '''# Use Jawaf to retrieve metadata for all installed apps.
from jawaf.conf import settings
from jawaf.db import get_metadata
target_metadata = get_metadata(settings.INSTALLED_APPS)'''

SQL_CONNECT_OVERRIDE = '''config = context.config

# Override SQL Alchemy connection string in `ini` file using
`default` db connect string.
from jawaf.db import get_engine_url
config.set_main_option('sqlalchemy.url', get_engine_url())'''

class Command(TemplateCommand):
    """Start a new jawaf project."""

    def handle(self, **options):
        options['secret_key'] = token_hex(60)
        options['template'] = 'project_template'
        base_dir, name = super(Command, self).handle(**options)
        # Setup Alembic Migrations
        alembic_dir = os.path.join(base_dir, name, 'migrations')
        cfg = Config(os.path.join(alembic_dir, 'alembic.ini'))
        command.init(config=cfg, directory=alembic_dir)
        with open(os.path.join(alembic_dir, 'env.py'), 'r') as f:
            env_py = f.read()
        env_py = env_py.replace('target_metadata = None', METADATA_CODE)
        env_py = env_py.replace('config = context.config', SQL_CONNECT_OVERRIDE)
        with open(os.path.join(alembic_dir, 'env.py'), 'w') as f:
            f.write(env_py)


text:
FDPrivateMessageBundle
====================

# Requirements
* Symfony >= 2.8
* A user class implementing ```Symfony\Component\Security\Core\User\UserInterface```

# Translations
If you wish to use default texts provided in this bundle, you have to make sure you have translator enabled in your config.
```
# app/config/config.yml
framework:
    translator: ~
```

# Installation
## Step 1: Download FDPrivateMessageBundle using composer
Require the bundle with composer:
```
composer require firediy/private-message-bundle dev-master
```

## Step 2:  Enable the bundle
Enable the bundle in the kernel:
```php
<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new FD\PrivateMessageBundle\FDPrivateMessageBundle(),
        // ...
    );
}
```

## Step 3: Create your own User class
The goal of this bundle is to provide a private message system to allow users communicating between them.
FDPrivateMessageBundle does not provide a ready-to-use User entity but uses Symfony's UserInterface.

So, you just have to create your own User class implementing ```Symfony\Component\Security\Core\User\UserInterface```.
You can heaven use FOSUserBundle.

## Step 4: Configure your application's config.yml
Now you have your User entity, you just have to tell FDPrivateMessageBundle to use it :
```
# app/config/config.yml
doctrine:
    orm:
        resolve_target_entities:
            Symfony\Component\Security\Core\User\UserInterface: AcmeBundle\Entity\YourUserEntiy
```

## Step 5: Import FDPrivateMessageBundle routing files
Now that you have activated and configured the bundle, all that is left to do is import the FDPrivateMessageBundle routing files.

```
# app/config/routing.yml
fd_private_message:
    resource: "@FDPrivateMessageBundle/Resources/config/routing.yml"
```

## Step 6: Update your database schema
Finally, just update your database schema :
```
php bin/console doctrine:schema:update --force
```

# Form
You are able to override FDPrivateMessageBundle's forms.

In example, you're using FOSUserBundle and want to load only recipients being NOT locked :

```php
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;
use FD\PrivateMessageBundle\Form\ConversationType as BaseType;

// Make your form extends FDPrivateMessageBunde::ConversationType.
class ConversationType extends BaseType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Call parent's builder.
        parent::buildForm($builder, $options);

        // Load only users being enabled.
        $builder->add('recipients', EntityType::class, array(
            'class'         => 'AcmeBundle:YourUserEntity',
            'multiple'      => true,
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('u')
                    ->where('u.locked', false);
            },
        ));

    }
}
```

# Override default FDPrivateMessageBundle templates
## Example: Override the conversation's show.html.twig template
Just create a new file in ```app/Resources/FDPrivateMessageBundle/views/Conversation/show.html.twig```
```twig
<h1>Overridden template</h1>

<h2>{{ conversation.subject }}</h2>

<ul>
    {% for message in conversation.messages %}
        <li>
            <p>{{ message.author }}, {{ message.created | date('Y-m-d H:i:s') }}</p>
            <div>{{ message.body | raw }}</div>
        </li>
    {% endfor %}
</ul>
```


text:
/* (c) 2014 LinkedIn Corp. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 * this file except in compliance with the License. You may obtain a copy of the
 * License at  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied.
 */

package com.linkedin.cubert.operator.aggregate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.pig.data.Tuple;
import org.codehaus.jackson.JsonNode;

import com.linkedin.cubert.block.Block;
import com.linkedin.cubert.block.BlockSchema;
import com.linkedin.cubert.operator.PreconditionException;
import com.linkedin.cubert.operator.PreconditionExceptionType;
import com.linkedin.cubert.utils.JsonUtils;

/**
 *
 * An aggregation operator to create an ArrayList of values of a field.
 *
 * @author Krishna Puttaswamy
 *
 */

public class ArrayListAggregation implements AggregationFunction
{
    private int inputColumnIndex;
    private int outputColumnIndex;
    private List<Object> outputList;

    @Override
    public void setup(Block block, BlockSchema outputSchema, JsonNode json) throws IOException
    {
        BlockSchema aggOutputSchema = new BlockSchema(JsonUtils.getText(json, "output"));
        String outputColumnName = aggOutputSchema.getName(0);
        outputColumnIndex = outputSchema.getIndex(outputColumnName);

        BlockSchema inputSchema = block.getProperties().getSchema();
        String inputColumnName = JsonUtils.asArray(json, "input")[0];
        inputColumnIndex = inputSchema.getIndex(inputColumnName);

        outputList = new ArrayList<Object>();
        resetState();
    }

    @Override
    public void resetState()
    {
        outputList.clear();
    }

    @Override
    public void aggregate(Tuple inputTuple) throws IOException
    {
        Object obj = inputTuple.get(inputColumnIndex);
        outputList.add(obj);
    }

    @Override
    public void output(Tuple outputTuple) throws IOException
    {
        outputTuple.set(outputColumnIndex, outputList);
    }

    @Override
    public void resetTuple(Tuple outputTuple) throws IOException
    {
        outputTuple.set(outputColumnIndex, null);
    }

    @Override
    public BlockSchema outputSchema(BlockSchema inputSchema, JsonNode json) throws PreconditionException
    {
        String[] inputColNames = JsonUtils.asArray(json, "input");
        if (inputColNames.length != 1)
            throw new PreconditionException(PreconditionExceptionType.INVALID_CONFIG,
                                            "Only one column expected for MAX. Found: "
                                                    + JsonUtils.get(json, "input"));
        // TODO
        return null;
    }

}


text:
namespace webkit {
namespace npapi {

namespace {

bool Equals(const WebPluginInfo& a, const WebPluginInfo& b) {
  return (a.name == b.name &&
          a.path == b.path &&
          a.version == b.version &&
          a.desc == b.desc);
}

bool Contains(const std::vector<WebPluginInfo>& list,
              const WebPluginInfo& plugin) {
  for (std::vector<WebPluginInfo>::const_iterator it = list.begin();
       it != list.end(); ++it) {
    if (Equals(*it, plugin))
      return true;
  }
  return false;
}

base::FilePath::CharType kFooPath[] = FILE_PATH_LITERAL("/plugins/foo.plugin");
base::FilePath::CharType kBarPath[] = FILE_PATH_LITERAL("/plugins/bar.plugin");
const char* kFooName = "Foo Plugin";

}  // namespace

class PluginListTest : public testing::Test {
 public:
  PluginListTest()
      : foo_plugin_(ASCIIToUTF16(kFooName),
                    base::FilePath(kFooPath),
                    ASCIIToUTF16("1.2.3"),
                    ASCIIToUTF16("foo")),
        bar_plugin_(ASCIIToUTF16("Bar Plugin"),
                    base::FilePath(kBarPath),
                    ASCIIToUTF16("2.3.4"),
                    ASCIIToUTF16("bar")) {
  }

  virtual void SetUp() {
    plugin_list_.AddPluginToLoad(bar_plugin_);
    plugin_list_.AddPluginToLoad(foo_plugin_);
  }

 protected:
  MockPluginList plugin_list_;
  WebPluginInfo foo_plugin_;
  WebPluginInfo bar_plugin_;
};

TEST_F(PluginListTest, GetPlugins) {
  std::vector<WebPluginInfo> plugins;
  plugin_list_.GetPlugins(&plugins);
  EXPECT_EQ(2u, plugins.size());
  EXPECT_TRUE(Contains(plugins, foo_plugin_));
  EXPECT_TRUE(Contains(plugins, bar_plugin_));
}

TEST_F(PluginListTest, BadPluginDescription) {
  WebPluginInfo plugin_3043(
      base::string16(), base::FilePath(FILE_PATH_LITERAL("/myplugin.3.0.43")),
      base::string16(), base::string16());
  // Simulate loading of the plugins.
  plugin_list_.ClearPluginsToLoad();
  plugin_list_.AddPluginToLoad(plugin_3043);
  // Now we should have them in the state we specified above.
  plugin_list_.RefreshPlugins();
  std::vector<WebPluginInfo> plugins;
  plugin_list_.GetPlugins(&plugins);
  ASSERT_TRUE(Contains(plugins, plugin_3043));
}

#if defined(OS_POSIX) && !defined(OS_MACOSX)

// Test parsing a simple description: Real Audio.
TEST(MIMEDescriptionParse, Simple) {
  std::vector<WebPluginMimeType> types;
  PluginList::ParseMIMEDescription(
      "audio/x-pn-realaudio-plugin:rpm:RealAudio document;",
      &types);
  ASSERT_EQ(1U, types.size());
  const WebPluginMimeType& type = types[0];
  EXPECT_EQ("audio/x-pn-realaudio-plugin", type.mime_type);
  ASSERT_EQ(1U, type.file_extensions.size());
  EXPECT_EQ("rpm", type.file_extensions[0]);
  EXPECT_EQ(ASCIIToUTF16("RealAudio document"), type.description);
}

// Test parsing a multi-entry description: QuickTime as provided by Totem.
TEST(MIMEDescriptionParse, Multi) {
  std::vector<WebPluginMimeType> types;
  PluginList::ParseMIMEDescription(
      "video/quicktime:mov:QuickTime video;video/mp4:mp4:MPEG-4 "
      "video;image/x-macpaint:pntg:MacPaint Bitmap image;image/x"
      "-quicktime:pict, pict1, pict2:QuickTime image;video/x-m4v"
      ":m4v:MPEG-4 video;",
      &types);

  ASSERT_EQ(5U, types.size());

  // Check the x-quicktime one, since it looks tricky with spaces in the
  // extension list.
  const WebPluginMimeType& type = types[3];
  EXPECT_EQ("image/x-quicktime", type.mime_type);
  ASSERT_EQ(3U, type.file_extensions.size());
  EXPECT_EQ("pict2", type.file_extensions[2]);
  EXPECT_EQ(ASCIIToUTF16("QuickTime image"), type.description);
}

// Test parsing a Japanese description, since we got this wrong in the past.
// This comes from loading Totem with LANG=ja_JP.UTF-8.
TEST(MIMEDescriptionParse, JapaneseUTF8) {
  std::vector<WebPluginMimeType> types;
  PluginList::ParseMIMEDescription(
      "audio/x-ogg:ogg:Ogg \xe3\x82\xaa\xe3\x83\xbc\xe3\x83\x87"
      "\xe3\x82\xa3\xe3\x83\xaa",
      &types);

  ASSERT_EQ(1U, types.size());
  // Check we got the right number of Unicode characters out of the parse.
  EXPECT_EQ(9U, types[0].description.size());
}

// Test that we handle corner cases gracefully.
TEST(MIMEDescriptionParse, CornerCases) {
  std::vector<WebPluginMimeType> types;
  PluginList::ParseMIMEDescription("mime/type:", &types);
  EXPECT_TRUE(types.empty());

  types.clear();
  PluginList::ParseMIMEDescription("mime/type:ext1:", &types);
  ASSERT_EQ(1U, types.size());
  EXPECT_EQ("mime/type", types[0].mime_type);
  EXPECT_EQ(1U, types[0].file_extensions.size());
  EXPECT_EQ("ext1", types[0].file_extensions[0]);
  EXPECT_EQ(base::string16(), types[0].description);
}

// This Java plugin has embedded semicolons in the mime type.
TEST(MIMEDescriptionParse, ComplicatedJava) {
  std::vector<WebPluginMimeType> types;
  PluginList::ParseMIMEDescription(
      "application/x-java-vm:class,jar:IcedTea;application/x-java"
      "-applet:class,jar:IcedTea;application/x-java-applet;versio"
      "n=1.1:class,jar:IcedTea;application/x-java-applet;version="
      "1.1.1:class,jar:IcedTea;application/x-java-applet;version="
      "1.1.2:class,jar:IcedTea;application/x-java-applet;version="
      "1.1.3:class,jar:IcedTea;application/x-java-applet;version="
      "1.2:class,jar:IcedTea;application/x-java-applet;version=1."
      "2.1:class,jar:IcedTea;application/x-java-applet;version=1."
      "2.2:class,jar:IcedTea;application/x-java-applet;version=1."
      "3:class,jar:IcedTea;application/x-java-applet;version=1.3."
      "1:class,jar:IcedTea;application/x-java-applet;version=1.4:"
      "class,jar:IcedTea",
      &types);

  ASSERT_EQ(12U, types.size());
  for (size_t i = 0; i < types.size(); ++i)
    EXPECT_EQ(ASCIIToUTF16("IcedTea"), types[i].description);

  // Verify that the mime types with semis are coming through ok.
  EXPECT_TRUE(types[4].mime_type.find(';') != std::string::npos);
}

// Make sure we understand how to get the version numbers for common Linux
// plug-ins.
TEST(PluginDescriptionParse, ExtractVersion) {
  WebPluginInfo info;
  PluginList::ExtractVersionString("Shockwave Flash 10.1 r102", &info);
  EXPECT_EQ(ASCIIToUTF16("10.1 r102"), info.version);
  PluginList::ExtractVersionString("Java(TM) Plug-in 1.6.0_22", &info);
  EXPECT_EQ(ASCIIToUTF16("1.6.0_22"), info.version);
  // It's actually much more likely for a modern Linux distribution to have
  // IcedTea.
  PluginList::ExtractVersionString(
      "IcedTea-Web Plugin "
      "(using IcedTea-Web 1.2 (1.2-2ubuntu0.10.04.2))",
      &info);
  EXPECT_EQ(ASCIIToUTF16("1.2"), info.version);
}

#endif  // defined(OS_POSIX) && !defined(OS_MACOSX)

}  // namespace npapi
}  // namespace webkit


text:
#include "lullaby/modules/render/vertex_format_util.h"

namespace lull {

// Shader attribute hashes.
constexpr HashValue kAttributeHashPosition = ConstHash("ATTR_POSITION");
constexpr HashValue kAttributeHashUV = ConstHash("ATTR_UV");
constexpr HashValue kAttributeHashColor = ConstHash("ATTR_COLOR");
constexpr HashValue kAttributeHashNormal = ConstHash("ATTR_NORMAL");
constexpr HashValue kAttributeHashOrientation = ConstHash("ATTR_ORIENTATION");
constexpr HashValue kAttributeHashTangent = ConstHash("ATTR_TANGENT");
constexpr HashValue kAttributeHashBoneIndices = ConstHash("ATTR_BONE_INDICES");
constexpr HashValue kAttributeHashBoneWeights = ConstHash("ATTR_BONE_WEIGHTS");

// Shader feature hashes.
constexpr HashValue kFeatureHashTransform = ConstHash("Transform");
constexpr HashValue kFeatureHashVertexColor = ConstHash("VertexColor");
constexpr HashValue kFeatureHashTexture = ConstHash("Texture");
constexpr HashValue kFeatureHashTexture1 = ConstHash("Texture1");
constexpr HashValue kFeatureHashLight = ConstHash("Light");
constexpr HashValue kFeatureHashSkin = ConstHash("Skin");

void SetFeatureFlags(const VertexFormat& vertex_format,
                     std::set<HashValue>* flags) {
  int texture_count = 0;
  for (size_t i = 0; i < vertex_format.GetNumAttributes(); ++i) {
    const VertexAttribute* attrib = vertex_format.GetAttributeAt(i);
    switch (attrib->usage()) {
      case VertexAttributeUsage_Position:
        flags->insert(kFeatureHashTransform);
        break;
      default:
        break;
      case VertexAttributeUsage_TexCoord:
        flags->insert(texture_count ? kFeatureHashTexture1
                                    : kFeatureHashTexture);
        ++texture_count;
        break;
      case VertexAttributeUsage_Color:
        flags->insert(kFeatureHashVertexColor);
        break;
      case VertexAttributeUsage_Normal:
        flags->insert(kFeatureHashLight);
        break;
      case VertexAttributeUsage_BoneIndices:
        flags->insert(kFeatureHashSkin);
        break;
    }
  }
}

void SetEnvironmentFlags(const VertexFormat& vertex_format,
                         std::set<HashValue>* flags) {
  for (size_t i = 0; i < vertex_format.GetNumAttributes(); ++i) {
    const VertexAttribute* attrib = vertex_format.GetAttributeAt(i);
    switch (attrib->usage()) {
      case VertexAttributeUsage_Position:
        flags->insert(kAttributeHashPosition);
        break;
      case VertexAttributeUsage_TexCoord:
        flags->insert(kAttributeHashUV);
        break;
      case VertexAttributeUsage_Color:
        flags->insert(kAttributeHashColor);
        break;
      case VertexAttributeUsage_Normal:
        flags->insert(kAttributeHashNormal);
        break;
      case VertexAttributeUsage_Orientation:
        flags->insert(kAttributeHashOrientation);
        break;
      case VertexAttributeUsage_Tangent:
        flags->insert(kAttributeHashTangent);
        break;
      case VertexAttributeUsage_BoneIndices:
        flags->insert(kAttributeHashBoneIndices);
        break;
      case VertexAttributeUsage_BoneWeights:
        flags->insert(kAttributeHashBoneWeights);
        break;
      default:
        break;
    }
  }
}

}  // namespace lull


text:
using System;
using Microsoft.AspNetCore.Mvc;
using Rnwood.Smtp4dev.Server;
using Microsoft.Extensions.Options;
using System.Text.Json;
using MailKit.Security;
using Microsoft.Extensions.Hosting;
using Rnwood.Smtp4dev.Service;

namespace Rnwood.Smtp4dev.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ServerController : Controller
    {
        public ServerController(ISmtp4devServer server, ImapServer imapServer, IOptionsMonitor<ServerOptions> serverOptions,
            IOptionsMonitor<RelayOptions> relayOptions, IHostingEnvironmentHelper hostingEnvironmentHelper)
        {
            this.server = server;
            this.imapServer = imapServer;
            this.serverOptions = serverOptions;
            this.relayOptions = relayOptions;
            this.hostingEnvironmentHelper = hostingEnvironmentHelper;
        }

        private ISmtp4devServer server;
        private ImapServer imapServer;
        private IOptionsMonitor<ServerOptions> serverOptions;
        private IOptionsMonitor<RelayOptions> relayOptions;
        private readonly IHostingEnvironmentHelper hostingEnvironmentHelper;

        [HttpGet]
        public ApiModel.Server GetServer()
        {
            return new ApiModel.Server()
            {
                IsRunning = server.IsRunning,
                PortNumber = serverOptions.CurrentValue.Port,
                ImapPortNumber = serverOptions.CurrentValue.ImapPort,
                HostName = serverOptions.CurrentValue.HostName,
                AllowRemoteConnections = serverOptions.CurrentValue.AllowRemoteConnections,
                NumberOfMessagesToKeep = serverOptions.CurrentValue.NumberOfMessagesToKeep,
                NumberOfSessionsToKeep = serverOptions.CurrentValue.NumberOfSessionsToKeep,
                Exception = server.Exception?.Message,
                RelayOptions = new ApiModel.ServerRelayOptions
                {
                    SmtpServer = relayOptions.CurrentValue.SmtpServer,
                    TlsMode = relayOptions.CurrentValue.TlsMode.ToString(),
                    SmtpPort = relayOptions.CurrentValue.SmtpPort,
                    Login = relayOptions.CurrentValue.Login,
                    Password = relayOptions.CurrentValue.Password,
                    AutomaticEmails = relayOptions.CurrentValue.AutomaticEmails,
                    SenderAddress = relayOptions.CurrentValue.SenderAddress
                },
                SettingsAreEditable = hostingEnvironmentHelper.SettingsAreEditable,
                DisableMessageSanitisation = serverOptions.CurrentValue.DisableMessageSanitisation

            };
        }

        [HttpPost]
        public ActionResult UpdateServer(ApiModel.Server serverUpdate)
        {
            if (!hostingEnvironmentHelper.SettingsAreEditable)
            {
                return Forbid();
            }
            ServerOptions newSettings = serverOptions.CurrentValue;
            RelayOptions newRelaySettings = relayOptions.CurrentValue;

            newSettings.Port = serverUpdate.PortNumber;
            newSettings.HostName = serverUpdate.HostName;
            newSettings.AllowRemoteConnections = serverUpdate.AllowRemoteConnections;
            newSettings.NumberOfMessagesToKeep = serverUpdate.NumberOfMessagesToKeep;
            newSettings.NumberOfSessionsToKeep = serverUpdate.NumberOfSessionsToKeep;
            newSettings.ImapPort = serverUpdate.ImapPortNumber;
            newSettings.DisableMessageSanitisation = serverUpdate.DisableMessageSanitisation;

            newRelaySettings.SmtpServer = serverUpdate.RelayOptions.SmtpServer;
            newRelaySettings.SmtpPort = serverUpdate.RelayOptions.SmtpPort;
            newRelaySettings.TlsMode = Enum.Parse<SecureSocketOptions>(serverUpdate.RelayOptions.TlsMode);
            newRelaySettings.SenderAddress = serverUpdate.RelayOptions.SenderAddress;
            newRelaySettings.Login = serverUpdate.RelayOptions.Login;
            newRelaySettings.Password = serverUpdate.RelayOptions.Password;
            newRelaySettings.AutomaticEmails = serverUpdate.RelayOptions.AutomaticEmails;

            System.IO.File.WriteAllText(hostingEnvironmentHelper.GetEditableSettingsFilePath(),
                JsonSerializer.Serialize(new { ServerOptions = newSettings, RelayOptions = newRelaySettings },
                    new JsonSerializerOptions { WriteIndented = true }));

            if (!serverUpdate.IsRunning && this.server.IsRunning)
            {
                this.server.Stop();
            }
            else if (serverUpdate.IsRunning && !this.server.IsRunning)
            {
                this.server.TryStart();
            }

            if (!serverUpdate.IsRunning && this.imapServer.IsRunning)
            {
                this.imapServer.Stop();
            }
            else if (serverUpdate.IsRunning && !this.imapServer.IsRunning)
            {
                this.imapServer.TryStart();
            }

            return Ok();
        }
    }
}


text:
from flask import flash, current_app, Flask, url_for, Blueprint, jsonify, abort, request
from flask_httpauth import HTTPBasicAuth
from ..models import *
from .. import db
from .db_queries import *

api = Blueprint('api', __name__, url_prefix='/api')
# This is used only for api authorization. This is a special case because resful APIs do not allow for state tracking.
# Each api call needs to send the authorization.
auth = HTTPBasicAuth()

@auth.verify_password
def authenticate(username, password):
	user = User.query.filter(User.email == username).first()
	if user is not None:
		return user.verify_password(password)
	return False

def make_public_query(query, type):
	new_query_data = {}
	for field in query:
		if field == 'id':
			new_query_data['uri'] = url_for('api.{0}'.format(type), id=query['id'], _external=True)
		else:
			new_query_data[field] = query[field]
	return new_query_data

@api.route('/stores/', methods=['GET'])
@auth.login_required
def stores():
	q = get_stores()
	return jsonify({'stores': [make_public_query(e.as_dict(), 'store') for e in q]})

@api.route('/store/<int:id>', methods=['GET'])
@auth.login_required
def store(id):
	q = get_store(id)
	if q == None:
		print("request: {0}".format(request))
		print("accept_mimetypes: {0}".format(request.accept_mimetypes))
		abort(404)
	return jsonify({'store': make_public_query(q.as_dict(), 'store')})

@api.route('/store/', methods=['POST'])
@auth.login_required
def store_create():
	json_data = request.get_json()
	if json_data is None or not 'name' in json_data:
		abort(400)

	name = json_data['name']
	if isinstance(name, str) is False:
		abort(404)

	query = create_store(name)
	if query is None:
		abort(500)
	return jsonify({'store': make_public_query(query.as_dict(), 'store')}), 201

@api.route('/store/<int:id>', methods=['PUT'])
@auth.login_required
def store_edit(id):
	json_data = request.get_json()
	if json_data is None or not 'name' in json_data:
		abort(400)

	name = json_data['name']
	query = edit_store(id, name)

	if query is None:
		abort(404)

	return jsonify({'store': make_public_query(query.as_dict(), 'store')})

@api.route('/store/<int:id>', methods=['DELETE'])
@auth.login_required
def store_delete(id):
	query = delete_store(id)
	return jsonify({'store': make_public_query(query.as_dict(), 'store')})

@api.route('/products/', methods=['GET'])
@auth.login_required
def products():
	query = get_products()
	json_products = jsonify({'products': [make_public_query(entry.as_dict(), 'product') for entry in query]})
	return json_products

@api.route('/product/<int:id>', methods=['GET'])
@auth.login_required
def product(id):
	query = get_product(id)
	if query == None:
		abort(404)
	return jsonify({'product': make_public_query(query.as_dict(), 'product')})

@api.route('/product/', methods=['POST'])
@auth.login_required
def products_create():
	json_data = request.get_json()
	verify_keys = ['name', 'upc', 'quantity', 'units']
	if (json_data is None) or not all(k in json_data for k in verify_keys):
		abort(400)

	name        = json_data['name']
	upc         = json_data['upc']
	quantity    = json_data['quantity']
	units       = json_data['units']
	brand_id    = json_data['brand_id']
	category_id = json_data['category_id']

	query    = create_product(name, upc, quantity, units, brand_id, category_id)

	if query is None:
		abort(500)
	return jsonify({'product': make_public_query(query.as_dict(), 'product')}), 201

@api.route('/product/<int:id>', methods=['PUT'])
@auth.login_required
def products_edit(id):
	json_data = request.get_json()
	verify_keys = ['name', 'upc', 'quantity', 'units']
	if (json_data is None) or not all(k in json_data for k in verify_keys):
		abort(404)

	name        = json_data['name']
	upc         = json_data['upc']
	quantity    = json_data['quantity']
	units       = json_data['units']
	brand_id    = json_data['brand_id']
	category_id = json_data['category_id']

	query = edit_product(id, name, upc, quantity, units, brand_id, category_id)

	if query is None:
		abort(500)

	return jsonify({'product': make_public_query(query.as_dict(), 'product')})

@api.route('/product/<int:id>', methods=['DELETE'])
@auth.login_required
def products_delete(id):
	query = delete_product(id)
	return jsonify({'product': make_public_query(query.as_dict(), 'product')})

# Price Listings do not allow for editing, however it can be created and deleted.

@api.route('/product_prices/', methods = ['GET'])
@auth.login_required
def product_prices():
	product_prices = get_product_prices()
	return jsonify({'product_prices': [make_public_query(product_price.as_dict(), 'product_price') for product_price in product_prices]})

@api.route('/product_price/<int:id>', methods = ['GET'])
@auth.login_required
def product_price(id):
	product_price = get_product_price(id)
	if product_price == None:
		abort(404)
	return jsonify({'product_price': make_public_query(product_price.as_dict(), 'product_price')})

@api.route('/product_price/', methods = ['POST'])
@auth.login_required
def product_price_create():
	json_data = request.get_json()
	verify_keys = ['store_id', 'product_id', 'date', 'price']
	if (json_data is None) or not all(k in json_data for k in verify_keys):
		print("Error out because a lot of things aren't quite right")
		abort(400)

	store_id=json_data['store_id']
	product_id=json_data['product_id']
	date=json_data['date']
	price=json_data['price']

	product_price = create_product_price(store_id, product_id, date, price)
	if product_price is None:
		abort(500)

	return jsonify({'product_price': make_public_query(product_price.as_dict(), 'product_price')}), 201

@api.route('/product_price/<int:id>', methods = ['DELETE'])
@auth.login_required
def product_price_delete(id):
	product_price = delete_product_price(id)
	return jsonify({'product_price': make_public_query(product_price.as_dict(), 'product_price')})


text:
package org.lumongo.filter;

import com.google.common.io.Resources;
import org.apache.lucene.analysis.CharArrayMap;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.glassfish.grizzly.utils.Charsets;

import java.io.IOException;
import java.net.URL;

/**
 * Created by Matt Davis on 9/22/16.
 * @author mdavis
 * Matt Davis
 */
public class BritishUSFilter extends TokenFilter {

	private static final CharArrayMap<char[]> britishToUs = initializeDictHash();

	private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);

	private static CharArrayMap<char[]> initializeDictHash() {
		CharArrayMap<char[]> charMap = new CharArrayMap<>(2000, false);

		try {
			URL url = Resources.getResource(BritishUSFilter.class, "british.txt");
			String text = Resources.toString(url, Charsets.UTF8_CHARSET);
			String[] lines = text.split("\n");
			for (String line : lines) {
				if (!line.startsWith("UK\tUS")) {
					String[] parts = line.split("\t");
					if (parts.length == 2) {
						charMap.put(parts[0].toCharArray(), parts[1].toCharArray());
					}
				}
			}

		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
		return charMap;

	}

	public BritishUSFilter(TokenStream in) {
		super(in);
	}

	@Override
	public final boolean incrementToken() throws IOException {
		if (!input.incrementToken()) {
			return false;
		}

		char[] replacement = britishToUs.get(termAtt.buffer(), 0, termAtt.length());
		if (replacement != null) {
			termAtt.copyBuffer(replacement, 0, replacement.length);
		}
		return true;
	}

}


text:
Blog based on Hugo

## Sync

Sync recursively or update submodule

```
git clone --recursive https://github.com/sickyoon/sickyoon.com.git
```

```
git submodule init
git submodule update
```

## Docker run
```
docker build -t blog:latest .
docker run --rm -it -v $PWD:/src -p 1313:1313 blog:latest --bind=0.0.0.0
```

## Github Publishing
Push `/public/` directory to sickyoon.github.io

## Libraries

* Minify (https://dl.equinox.io/tdewolff/minify/stable)


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>Hui</title>
    <link href="../../../css/Hui.css" rel="stylesheet" type="text/css" />

            用户中心


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Google Maps JavaScript API v3 Example: Street View Layer</title>
    <link href="default.css" rel="stylesheet">


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://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.

// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/binaryauthorization/v1/service.proto

#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BINARYAUTHORIZATION_MOCKS_MOCK_BINAUTHZ_MANAGEMENT_SERVICE_V1_CONNECTION_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BINARYAUTHORIZATION_MOCKS_MOCK_BINAUTHZ_MANAGEMENT_SERVICE_V1_CONNECTION_H

#include "google/cloud/binaryauthorization/binauthz_management_service_v1_connection.h"
#include <gmock/gmock.h>

namespace google {
namespace cloud {
namespace binaryauthorization_mocks {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

/**
 * A class to mock `BinauthzManagementServiceV1Connection`.
 *
 * Application developers may want to test their code with simulated responses,
 * including errors, from an object of type `BinauthzManagementServiceV1Client`.
 * To do so, construct an object of type `BinauthzManagementServiceV1Client`
 * with an instance of this class. Then use the Google Test framework functions
 * to program the behavior of this mock.
 *
 * @see [This example][bq-mock] for how to test your application with
 * GoogleTest. While the example showcases types from the BigQuery library, the
 * underlying principles apply for any pair of `*Client` and `*Connection`.
 *
 * [bq-mock]: @googleapis_dev_link{bigquery,bigquery-read-mock.html}
 */
class MockBinauthzManagementServiceV1Connection
    : public binaryauthorization::BinauthzManagementServiceV1Connection {
 public:
  MOCK_METHOD(Options, options, (), (override));

  MOCK_METHOD(
      StatusOr<google::cloud::binaryauthorization::v1::Policy>, GetPolicy,
      (google::cloud::binaryauthorization::v1::GetPolicyRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::cloud::binaryauthorization::v1::Policy>, UpdatePolicy,
      (google::cloud::binaryauthorization::v1::UpdatePolicyRequest const&
           request),
      (override));

  MOCK_METHOD(
      StatusOr<google::cloud::binaryauthorization::v1::Attestor>,
      CreateAttestor,
      (google::cloud::binaryauthorization::v1::CreateAttestorRequest const&
           request),
      (override));

  MOCK_METHOD(StatusOr<google::cloud::binaryauthorization::v1::Attestor>,
              GetAttestor,
              (google::cloud::binaryauthorization::v1::GetAttestorRequest const&
                   request),
              (override));

  MOCK_METHOD(
      StatusOr<google::cloud::binaryauthorization::v1::Attestor>,
      UpdateAttestor,
      (google::cloud::binaryauthorization::v1::UpdateAttestorRequest const&
           request),
      (override));

  MOCK_METHOD(
      StreamRange<google::cloud::binaryauthorization::v1::Attestor>,
      ListAttestors,
      (google::cloud::binaryauthorization::v1::ListAttestorsRequest request),
      (override));

  MOCK_METHOD(
      Status, DeleteAttestor,
      (google::cloud::binaryauthorization::v1::DeleteAttestorRequest const&
           request),
      (override));
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace binaryauthorization_mocks
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BINARYAUTHORIZATION_MOCKS_MOCK_BINAUTHZ_MANAGEMENT_SERVICE_V1_CONNECTION_H


text:
**Buzz Referee** is a Google Buzz bot a user can @-mention for a reasoned, but random, arbitration to decide who "wins" the discussion/argument/thread.

Just @-mention buzzreferee in a public post or comment by including:
    @buzzreferee@gmail.com

* Buzz Referee runs on Google App Engine at <http://buzz-referee.appspot.com/>
* Comments made by the bot can be found on its Google Profile: <https://www.google.com/profiles/buzzreferee#buzz>
* This project uses the buzz-python-client from Google found at: <http://code.google.com/p/buzz-python-client/>

----
The license (for the non-third-party code) is found in the LICENSE file - MIT License.

Mitchell Bowden <mitchellbowden AT gmail DOT com>
<http://github.com/msbmsb/buzz-referee>


text:
<?php
include_once 'RGB.class.php';
include_once 'SpatialExtent.class.php';
include_once 'Colors.class.php';
?>


text:
package container

import (
	"context"
	"fmt"
	"strings"

	"github.com/docker/cli/cli"
	"github.com/docker/cli/cli/command"
	"github.com/docker/cli/cli/command/completion"
	"github.com/docker/cli/cli/command/formatter/tabwriter"
	"github.com/spf13/cobra"
)

type topOptions struct {
	container string

	args []string
}

// NewTopCommand creates a new cobra.Command for `docker top`
func NewTopCommand(dockerCli command.Cli) *cobra.Command {
	var opts topOptions

	cmd := &cobra.Command{
		Use:   "top CONTAINER [ps OPTIONS]",
		Short: "Display the running processes of a container",
		Args:  cli.RequiresMinArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.container = args[0]
			opts.args = args[1:]
			return runTop(dockerCli, &opts)
		},
		Annotations: map[string]string{
			"aliases": "docker container top, docker top",
		},
		ValidArgsFunction: completion.ContainerNames(dockerCli, false),
	}

	flags := cmd.Flags()
	flags.SetInterspersed(false)

	return cmd
}

func runTop(dockerCli command.Cli, opts *topOptions) error {
	ctx := context.Background()

	procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args)
	if err != nil {
		return err
	}

	w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
	fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))

	for _, proc := range procList.Processes {
		fmt.Fprintln(w, strings.Join(proc, "\t"))
	}
	w.Flush()
	return nil
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**elements_in_workspace_limit** | **int** |  | [optional]
**cpp_server_limit** | **int** |  | [optional]
**thumbnail_cpp_server_limit** | **int** |  | [optional]
**linked_cpp_server_limit** | **int** |  | [optional]
**drawing_server_memory** | **int** |  | [optional]
**cpp_server_default_element_limit** | **int** |  | [optional]
**document_memory** | **int** |  | [optional]
**skip_retrieval_test** | **bool** |  | [optional]
**cpp_server_memory** | **int** |  | [optional]
**enable_cpp_server_memory_diagnostics** | **bool** |  | [optional]
**extended_display_check** | **bool** |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
uid: FAQ.Glossary
title: Common Terminologies / Glossary
---

# Glossary

This is an additional chapter for quick references to various common
types that you may see within Discord.Net. To see more information
regarding each type of object, click on the object to navigate
to our API documentation page where you might find more explanation
about it.

## Common Types

* A **Guild** ([IGuild]) is an isolated collection of users and
channels, and are often referred to as "servers".
	- Example: [Discord API](https://discord.gg/jkrBmQR)
* A **Channel** ([IChannel]) represents a generic channel.
	- Example: #dotnet_discord-net
	- See [Channel Types](#channel-types)

[IGuild]: xref:Discord.IGuild
[IChannel]: xref:Discord.IChannel

## Channel Types

### Message Channels
* A **Text Channel** ([ITextChannel]) is a message channel from a
Guild.
* A **DM Channel** ([IDMChannel]) is a message channel from a DM.
* A **Group Channel** ([IGroupChannel]) is a message channel from a
Group.
	- This is rarely used due to the bot's inability to join groups.
* A **Private Channel** ([IPrivateChannel]) is a DM or a Group.
* A **Message Channel** ([IMessageChannel]) can be any of the above.

### Misc Channels
* A **Guild Channel** ([IGuildChannel]) is a guild channel in a guild.
	- This can be any channels that may exist in a guild.
* A **Voice Channel** ([IVoiceChannel]) is a voice channel in a guild.
* A **Category Channel** ([ICategoryChannel]) (2.0+) is a category that
holds one or more sub-channels.
* A **Nested Channel** ([INestedChannel]) (2.0+) is a channel that can
exist under a category.

[INestedChannel]: xref:Discord.INestedChannel
[IGuildChannel]: xref:Discord.IGuildChannel
[IMessageChannel]: xref:Discord.IMessageChannel
[ITextChannel]: xref:Discord.ITextChannel
[IGroupChannel]: xref:Discord.IGroupChannel
[IDMChannel]: xref:Discord.IDMChannel
[IPrivateChannel]: xref:Discord.IPrivateChannel
[IVoiceChannel]: xref:Discord.IVoiceChannel
[ICategoryChannel]: xref:Discord.ICategoryChannel

## Emoji Types

* An **Emote** ([Emote]) is a custom emote from a guild.
	- Example: `<:dotnet:232902710280716288>`
* An **Emoji** ([Emoji]) is a Unicode emoji.
	- Example: `👍`

[Emote]: xref:Discord.Emote
[Emoji]: xref:Discord.Emoji

## Activity Types

* A **Game** ([Game]) refers to a user's game activity.
* A **Rich Presence** ([RichGame]) refers to a user's detailed
gameplay status.
	- Visit [Rich Presence Intro] on Discord docs for more info.
* A **Streaming Status** ([StreamingGame]) refers to user's activity
for streaming on services such as Twitch.
* A **Spotify Status** ([SpotifyGame]) (2.0+) refers to a user's
activity for listening to a song on Spotify.

[Game]: xref:Discord.Game
[RichGame]: xref:Discord.RichGame
[StreamingGame]: xref:Discord.StreamingGame
[SpotifyGame]: xref:Discord.SpotifyGame
[Rich Presence Intro]: https://discordapp.com/developers/docs/rich-presence/best-practices


text:
agentkeepalive
==============

[![Build Status](https://secure.travis-ci.org/TBEDP/agentkeepalive.png?branch=master)](http://travis-ci.org/TBEDP/agentkeepalive)

The nodejs's missing `keep alive` `http.Agent`. Support `http` and `https`.

jscoverage: [**93%**](http://fengmk2.github.com/coverage/agentkeepalive.html)

## Install

```bash
$ npm install agentkeepalive
```

## Usage

```js
var http = require('http');
var Agent = require('agentkeepalive');

var keepaliveAgent = new Agent({
  maxSockets: 10,
  maxKeepAliveRequests: 0, // max requests per keepalive socket, default is 0, no limit.
  maxKeepAliveTime: 30000 // keepalive for 30 seconds
});

var options = {
  host: 'cnodejs.org',
  port: 80,
  path: '/',
  method: 'GET',
  agent: keepaliveAgent
};

var req = http.request(options, function (res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function (e) {
  console.log('problem with request: ' + e.message);
});
req.end();

setTimeout(function () {
  console.log('keep alive sockets:');
  console.log(keepaliveAgent.unusedSockets);
}, 2000);

```

### Support `https`

```js
var https = require('https');
var HttpsAgent = require('agentkeepalive').HttpsAgent;

var keepaliveAgent = new HttpsAgent();
// https://www.google.com/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8
var options = {
  host: 'www.google.com',
  port: 443,
  path: '/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8',
  method: 'GET',
  agent: keepaliveAgent
};

var req = https.request(options, function (res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function (e) {
  console.log('problem with request: ' + e.message);
});
req.end();

setTimeout(function () {
  console.log('keep alive sockets:');
  console.log(keepaliveAgent.unusedSockets);
  process.exit();
}, 2000);
```

## [Benchmark](https://github.com/TBEDP/agentkeepalive/tree/master/benchmark)

run the benchmark:

```bash
cd benchmark
sh start.sh
```

Intel(R) Core(TM)2 Duo CPU     P8600  @ 2.40GHz

node@v0.8.9

50 maxSockets, 60 concurrent, 1000 requests per concurrent, 5ms delay

Keep alive agent (30 seconds):

```js
Transactions:          60000 hits
Availability:         100.00 %
Elapsed time:          29.70 secs
Data transferred:        14.88 MB
Response time:            0.03 secs
Transaction rate:      2020.20 trans/sec
Throughput:           0.50 MB/sec
Concurrency:           59.84
Successful transactions:       60000
Failed transactions:             0
Longest transaction:          0.15
Shortest transaction:         0.01
```

Normal agent:

```js
Transactions:          60000 hits
Availability:         100.00 %
Elapsed time:          46.53 secs
Data transferred:        14.88 MB
Response time:            0.05 secs
Transaction rate:      1289.49 trans/sec
Throughput:           0.32 MB/sec
Concurrency:           59.81
Successful transactions:       60000
Failed transactions:             0
Longest transaction:          0.45
Shortest transaction:         0.00
```

Socket created:

```
[proxy.js:120000] keepalive, 50 created, 60000 requestFinished, 1200 req/socket, 0 requests, 0 sockets, 0 unusedSockets, 50 timeout
{" <10ms":662," <15ms":17825," <20ms":20552," <30ms":17646," <40ms":2315," <50ms":567," <100ms":377," <150ms":56," <200ms":0," >=200ms+":0}
----------------------------------------------------------------
[proxy.js:120000] normal   , 53866 created, 84260 requestFinished, 1.56 req/socket, 0 requests, 0 sockets
{" <10ms":75," <15ms":1112," <20ms":10947," <30ms":32130," <40ms":8228," <50ms":3002," <100ms":4274," <150ms":181," <200ms":18," >=200ms+":33}
```

## Authors

Below is the output from `git-summary`.

```
 project: agentkeepalive
 commits: 24
 active : 10 days
 files  : 20
 authors:
    22  fengmk2                 91.7%
     2  Will White              8.3%
```

Ordered by date of first contribution.

- [fengmk2](https://github.com/fengmk2)
- [Will White](https://github.com/willwhite)

## License

(The MIT License)

Copyright (c) 2012 fengmk2 <fengmk2@gmail.com>;

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
/* Script Generado por Evolution - Editor de Formulación de Planillas. 16-01-2017 12:13 PM */

begin transaction

delete from [sal].[fcu_formulacion_cursores] where [fcu_codpai] = 'pa' and [fcu_nombre] = 'Datos_Renta_Gastos_Rep';

insert into [sal].[fcu_formulacion_cursores] ([fcu_codpai],[fcu_proceso],[fcu_nombre],[fcu_descripcion],[fcu_select_edit],[fcu_select_run],[fcu_field_codemp],[fcu_field_codppl],[fcu_modo_asociacion_tpl],[fcu_loop_calculo],[fcu_updatable]) values ('pa','Planilla','Datos_Renta_Gastos_Rep','Datos_Renta_Gastos_Rep','select * from sal.rag_renta_anual_panama_gr where 1 = 2','select * from sal.rag_renta_anual_panama_gr
where rag_codcia = $$CODCIA$$
and rag_codppl = $$CODPPL$$','rag_codemp','rag_codppl','TodosExcluyendo',0,1);

commit transaction;


text:
export class GarbageType {
    constructor(public id?: number,
        public label?: string) {
    }
}