text:
<?php

class Twig_Tests_Node_Expression_FilterTest extends Twig_Test_NodeTestCase
{
    public function testConstructor()
    {
        $expr = new Twig_Node_Expression_Constant('foo', 1);
        $name = new Twig_Node_Expression_Constant('upper', 1);
        $args = new Twig_Node();
        $node = new Twig_Node_Expression_Filter($expr, $name, $args, 1);

        $this->assertEquals($expr, $node->getNode('node'));
        $this->assertEquals($name, $node->getNode('filter'));
        $this->assertEquals($args, $node->getNode('arguments'));
    }

    public function getTests()
    {
        $environment = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock());
        $environment->addFilter(new Twig_SimpleFilter('bar', 'bar', array('needs_environment' => true)));
        $environment->addFilter(new Twig_SimpleFilter('barbar', 'twig_tests_filter_barbar', array('needs_context' => true, 'is_variadic' => true)));

        $tests = array();

        $expr = new Twig_Node_Expression_Constant('foo', 1);
        $node = $this->createFilter($expr, 'upper');
        $node = $this->createFilter($node, 'number_format', array(new Twig_Node_Expression_Constant(2, 1), new Twig_Node_Expression_Constant('.', 1), new Twig_Node_Expression_Constant(',', 1)));

        if (function_exists('mb_get_info')) {
            $tests[] = array($node, 'twig_number_format_filter($this->env, twig_upper_filter($this->env, "foo"), 2, ".", ",")');
        } else {
            $tests[] = array($node, 'twig_number_format_filter($this->env, strtoupper("foo"), 2, ".", ",")');
        }

        // named arguments
        $date = new Twig_Node_Expression_Constant(0, 1);
        $node = $this->createFilter($date, 'date', array(
            'timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1),
            'format' => new Twig_Node_Expression_Constant('d/m/Y H:i:s P', 1),
        ));
        $tests[] = array($node, 'twig_date_format_filter($this->env, 0, "d/m/Y H:i:s P", "America/Chicago")');

        // skip an optional argument
        $date = new Twig_Node_Expression_Constant(0, 1);
        $node = $this->createFilter($date, 'date', array(
            'timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1),
        ));
        $tests[] = array($node, 'twig_date_format_filter($this->env, 0, null, "America/Chicago")');

        // underscores vs camelCase for named arguments
        $string = new Twig_Node_Expression_Constant('abc', 1);
        $node = $this->createFilter($string, 'reverse', array(
            'preserve_keys' => new Twig_Node_Expression_Constant(true, 1),
        ));
        $tests[] = array($node, 'twig_reverse_filter($this->env, "abc", true)');
        $node = $this->createFilter($string, 'reverse', array(
            'preserveKeys' => new Twig_Node_Expression_Constant(true, 1),
        ));
        $tests[] = array($node, 'twig_reverse_filter($this->env, "abc", true)');

        // filter as an anonymous function
        if (PHP_VERSION_ID >= 50300) {
            $node = $this->createFilter(new Twig_Node_Expression_Constant('foo', 1), 'anonymous');
            $tests[] = array($node, 'call_user_func_array($this->env->getFilter(\'anonymous\')->getCallable(), array("foo"))');
        }

        // needs environment
        $node = $this->createFilter($string, 'bar');
        $tests[] = array($node, 'bar($this->env, "abc")', $environment);

        $node = $this->createFilter($string, 'bar', array(new Twig_Node_Expression_Constant('bar', 1)));
        $tests[] = array($node, 'bar($this->env, "abc", "bar")', $environment);

        // arbitrary named arguments
        $node = $this->createFilter($string, 'barbar');
        $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc")', $environment);

        $node = $this->createFilter($string, 'barbar', array('foo' => new Twig_Node_Expression_Constant('bar', 1)));
        $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", null, null, array("foo" => "bar"))', $environment);

        $node = $this->createFilter($string, 'barbar', array('arg2' => new Twig_Node_Expression_Constant('bar', 1)));
        $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", null, "bar")', $environment);

        $node = $this->createFilter($string, 'barbar', array(
            new Twig_Node_Expression_Constant('1', 1),
            new Twig_Node_Expression_Constant('2', 1),
            new Twig_Node_Expression_Constant('3', 1),
            'foo' => new Twig_Node_Expression_Constant('bar', 1),
        ));
        $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", "1", "2", array(0 => "3", "foo" => "bar"))', $environment);

        return $tests;
    }

    /**
     * @expectedException        Twig_Error_Syntax
     * @expectedExceptionMessage Unknown argument "foobar" for filter "date(format, timezone)" at line 1.
     */
    public function testCompileWithWrongNamedArgumentName()
    {
        $date = new Twig_Node_Expression_Constant(0, 1);
        $node = $this->createFilter($date, 'date', array(
            'foobar' => new Twig_Node_Expression_Constant('America/Chicago', 1),
        ));

        $compiler = $this->getCompiler();
        $compiler->compile($node);
    }

    /**
     * @expectedException        Twig_Error_Syntax
     * @expectedExceptionMessage Value for argument "from" is required for filter "replace" at line 1.
     */
    public function testCompileWithMissingNamedArgument()
    {
        $value = new Twig_Node_Expression_Constant(0, 1);
        $node = $this->createFilter($value, 'replace', array(
            'to' => new Twig_Node_Expression_Constant('foo', 1),
        ));

        $compiler = $this->getCompiler();
        $compiler->compile($node);
    }

    protected function createFilter($node, $name, array $arguments = array())
    {
        $name = new Twig_Node_Expression_Constant($name, 1);
        $arguments = new Twig_Node($arguments);

        return new Twig_Node_Expression_Filter($node, $name, $arguments, 1);
    }

    protected function getEnvironment()
    {
        if (PHP_VERSION_ID >= 50300) {
            return include 'PHP53/FilterInclude.php';
        }

        return parent::getEnvironment();
    }
}

function twig_tests_filter_barbar($context, $string, $arg1 = null, $arg2 = null, array $args = array())
{
}


text: Sample Project:try something interesting

redpajama_set_name: RedPajamaGithub


text:
<?php

	defined('BASEPATH') OR exit('No direct script access allowed');

	class Outlets extends MY_Controller{

		function __construct(){
			parent::__construct();
			$this->load->model('outlets_model');
			if($this->session_role != 'admin'){
				redirect('home');
			}
		}

		public function index(){

			$data['title'] = 'Outlet';
			$data['is_mobile'] = $this->is_mobile;
			$data['outlets'] = $this->crud_model->get_data('outlets')->result();
			$this->template->load($this->default,'outlets/list_outlet',$data);

		}

		public function add_outlet(){

			//process the insertion
			if($this->input->post()){
				$data_outlet = array(
						'name'			=> $this->input->post('outlet_name'),
						'code'			=> $this->input->post('outlet_code'),
						'phone'			=> $this->input->post('outlet_phone'),
						'store_manager'	=> $this->input->post('outlet_manager'),
						'address'		=> $this->input->post('outlet_address'),
						'margin'		=> $this->input->post('outlet_margin')
					);

				//insert the outlet
				if($this->db->insert('outlets',$data_outlet)){

					//if success get the outlet_id
					$outlet_id = $this->db->insert_id();

					$data_account = array(
						'username'		=> $this->input->post('outlet_username'),
						'name'			=> $this->input->post('outlet_manager'),
						'password'		=> hash_password($this->input->post('outlet_password')),
						'role'			=> 'manager',
						'outlet_id'		=> $outlet_id
					);

					//insert the manager account
					$this->crud_model->insert_data('accounts',$data_account);

					//success notification
					$this->session->set_flashdata('outlet',"$.gritter.add({
						class_name : 'gritter-light',
				 		title:	'Berhasil!',
				 		text:	'Toko berhasil dibuat!',
				 		time: 2000
				 	});");

				}else{
					$this->session->set_flashdata('outlet',
						"$.gritter.add({
				 		title:	'Toko gagal dibuat',
				 		text:	'Periksa kembali data toko',
				 		time: 2000
				 	});");
				}

				redirect('outlets/add_outlet');
			}
			//show the form view
			else{
				$data['title'] = 'Outlet';
				$this->template->load($this->default,'outlets/add_outlet',$data);
			}

		}

		public function edit_outlet($outlet_id = ''){

			//process the edit if there is posts from the view
			if($this->input->post()){
				$data_outlet = array(
						'name'			=> $this->input->post('outlet_name'),
						'code'			=> $this->input->post('outlet_code'),
						'phone'			=> $this->input->post('outlet_phone'),
						'store_manager'	=> $this->input->post('outlet_manager'),
						'address'		=> $this->input->post('outlet_address'),
						'margin'		=> $this->input->post('outlet_margin')
					);

				//update the outlet information
				$this->crud_model->update_data('outlets',$data_outlet,array('id' => $outlet_id));

				$data_account = array(
					'username'		=> $this->input->post('outlet_username'),
					'password'		=> hash_password($this->input->post('outlet_password')),
					'name'			=> $this->input->post('outlet_manager'),
				);

				//check if user input new password or not
				if($this->input->post('outlet_password') != ''){
						//update the password
						$data_account['password'] = hash_password($this->input->post('outlet_password'));
					}

				//update the manager account
				$this->crud_model->update_data('accounts',$data_account,array('outlet_id' => $outlet_id,'role' => 'manager'));

				//success notification
				$this->session->set_flashdata('outlet', "$.gritter.add({
						class_name : 'gritter-light',
				 		title:	'Berhasil!',
				 		text:	'Toko berhasil diubah!',
				 		time: 2000
				 	});");

				redirect('outlets');

			}
			//show the edit page
			else{
				$data['title'] = 'Outlet';
				$data['outlet']	= $this->outlets_model->get_outlet($outlet_id);
				$this->template->load($this->default,'outlets/edit_outlet',$data);
			}
		}

		public function delete_outlet($outlet_id = ''){

			//update the sales' outlet_id
			$this->crud_model->update_data('accounts',array('outlet_id' => $outlet_id, 'role' => 'sales'), array('outlet_id' => 0));
			//delete the manager acount
			$this->crud_model->delete_data('accounts',array('outlet_id' => $outlet_id,'role' => 'manager'));
			//delete the outlet
			$this->crud_model->delete_data('outlets',array('id' => $outlet_id));
			//give notification
			$this->session->set_flashdata('outlet',"$.gritter.add({
						class_name : 'gritter-light',
				 		title:	'Berhasil!',
				 		text:	'Toko berhasil dihapus!',
				 		time: 2000
				 	});");
			redirect('outlets');
		}

	}

 ?>


text:
package io.confluent.kafkarest.entities;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

public class ConsumerSubscriptionResponse {

  @JsonProperty
  public List<String> topics;
}


text:
var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  resolve: {
    extensions: ["", ".js", ".jsx"],
    alias: {
      'redux-act': path.join(__dirname, '..', '..', 'lib')
    }
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        loaders: [ 'babel' ],
        exclude: /node_modules/,
        include: __dirname
      }
    ]
  }
}


text:
package com.iluwatar.model.view.presenter;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * This class is the GUI implementation of the View component in the Model-View-Presenter pattern.
 */
public class FileSelectorJFrame extends JFrame implements FileSelectorView, ActionListener {

  /**
   * Default serial version ID.
   */
  private static final long serialVersionUID = 1L;

  /**
   * The "OK" button for loading the file.
   */
  private JButton ok;

  /**
   * The cancel button.
   */
  private JButton cancel;

  /**
   * The information label.
   */
  private JLabel info;

  /**
   * The contents label.
   */
  private JLabel contents;

  /**
   * The text field for giving the name of the file that we want to open.
   */
  private JTextField input;

  /**
   * A text area that will keep the contents of the file opened.
   */
  private JTextArea area;

  /**
   * The panel that will hold our widgets.
   */
  private JPanel panel;

  /**
   * The Presenter component that the frame will interact with
   */
  private FileSelectorPresenter presenter;

  /**
   * The name of the file that we want to read it's contents.
   */
  private String fileName;

  /**
   * Constructor.
   */
  public FileSelectorJFrame() {
    super("File Loader");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(null);
    this.setBounds(100, 100, 500, 200);

    /*
     * Add the panel.
     */
    this.panel = new JPanel();
    panel.setLayout(null);
    this.add(panel);
    panel.setBounds(0, 0, 500, 200);
    panel.setBackground(Color.LIGHT_GRAY);

    /*
     * Add the info label.
     */
    this.info = new JLabel("File Name :");
    this.panel.add(info);
    info.setBounds(30, 10, 100, 30);

    /*
     * Add the contents label.
     */
    this.contents = new JLabel("File contents :");
    this.panel.add(contents);
    this.contents.setBounds(30, 100, 120, 30);

    /*
     * Add the text field.
     */
    this.input = new JTextField(100);
    this.panel.add(input);
    this.input.setBounds(150, 15, 200, 20);

    /*
     * Add the text area.
     */
    this.area = new JTextArea(100, 100);
    JScrollPane pane = new JScrollPane(area);
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    this.panel.add(pane);
    this.area.setEditable(false);
    pane.setBounds(150, 100, 250, 80);

    /*
     * Add the OK button.
     */
    this.ok = new JButton("OK");
    this.panel.add(ok);
    this.ok.setBounds(250, 50, 100, 25);
    this.ok.addActionListener(this);

    /*
     * Add the cancel button.
     */
    this.cancel = new JButton("Cancel");
    this.panel.add(this.cancel);
    this.cancel.setBounds(380, 50, 100, 25);
    this.cancel.addActionListener(this);

    this.presenter = null;
    this.fileName = null;
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (this.ok.equals(e.getSource())) {
      this.fileName = this.input.getText();
      presenter.fileNameChanged();
      presenter.confirmed();
    } else if (this.cancel.equals(e.getSource())) {
      presenter.cancelled();
    }
  }

  @Override
  public void open() {
    this.setVisible(true);
  }

  @Override
  public void close() {
    this.dispose();
  }

  @Override
  public boolean isOpened() {
    return this.isVisible();
  }

  @Override
  public void setPresenter(FileSelectorPresenter presenter) {
    this.presenter = presenter;
  }

  @Override
  public FileSelectorPresenter getPresenter() {
    return this.presenter;
  }

  @Override
  public void setFileName(String name) {
    this.fileName = name;
  }

  @Override
  public String getFileName() {
    return this.fileName;
  }

  @Override
  public void showMessage(String message) {
    JOptionPane.showMessageDialog(null, message);
  }

  @Override
  public void displayData(String data) {
    this.area.setText(data);
  }
}


text:
include_recipe 'pivotal_ci::jenkins'

directory "#{node["jenkins"]["home"]}/plugins" do
  owner "jenkins"
end

jenkins_plugin = Proc.new do |resource, plugin, url|
  resource.command "curl -Lsf #{url} -o #{node["jenkins"]["home"]}/plugins/#{plugin}.hpi"
  resource.not_if { File.exists?("#{node["jenkins"]["home"]}/plugins/#{plugin}.hpi") }
  resource.user "jenkins"
  resource.notifies :restart, "service[jenkins]"
end

execute "download lobot plugin" do
  jenkins_plugin.call(self, "lobot", "http://cheffiles.pivotallabs.com/lobot/lobot.hpi")
end

['git-client', 'git', 'ansicolor', 'xvfb', 'greenballs'].each do |plugin|
  execute "download #{plugin} plugin" do
    jenkins_plugin.call(self, plugin, "http://mirrors.jenkins-ci.org/plugins/#{plugin}/latest/#{plugin}.hpi")
  end
end

template "#{node["jenkins"]["home"]}/org.jenkinsci.plugins.xvfb.XvfbBuildWrapper.xml" do
  source "org.jenkinsci.plugins.xvfb.XvfbBuildWrapper.xml.erb"
  owner "jenkins"
  notifies :restart, "service[jenkins]"
end

node["jenkins"]["builds"].each do |build|
  directory "#{node["jenkins"]["home"]}/jobs/#{build['name']}" do
    owner "jenkins"
  end

  require "cgi"
  template "#{node["jenkins"]["home"]}/jobs/#{build['name']}/config.xml" do
    source "jenkins-job-config.xml.erb"
    owner "jenkins"
    notifies :restart, "service[jenkins]"
    junit_publisher = build['junit_publisher'].nil? ? true : build['junit_publisher']
    variables(
      :branch => build['branch'],
      :command => build['command'],
      :repository => build['repository'],
      :junit_publisher => junit_publisher
    )
  end
end


text:
import * as React from 'react';
import FormControl from '@mui/joy/FormControl';
import FormLabel from '@mui/joy/FormLabel';
import FormHelperText from '@mui/joy/FormHelperText';
import Autocomplete from '@mui/joy/Autocomplete';

export default function InputAppearance() {
  return (
    <FormControl error>
      <FormLabel>Invalid</FormLabel>
      <Autocomplete placeholder="Error" options={top100Films} sx={{ width: 300 }} />
      <FormHelperText>Opps! something went wrong.</FormHelperText>
    </FormControl>
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { label: 'The Shawshank Redemption', year: 1994 },
  { label: 'The Godfather', year: 1972 },
  { label: 'The Godfather: Part II', year: 1974 },
  { label: 'The Dark Knight', year: 2008 },
  { label: '12 Angry Men', year: 1957 },
  { label: "Schindler's List", year: 1993 },
  { label: 'Pulp Fiction', year: 1994 },
  {
    label: 'The Lord of the Rings: The Return of the King',
    year: 2003,
  },
  { label: 'The Good, the Bad and the Ugly', year: 1966 },
  { label: 'Fight Club', year: 1999 },
  {
    label: 'The Lord of the Rings: The Fellowship of the Ring',
    year: 2001,
  },
  {
    label: 'Star Wars: Episode V - The Empire Strikes Back',
    year: 1980,
  },
  { label: 'Forrest Gump', year: 1994 },
  { label: 'Inception', year: 2010 },
  {
    label: 'The Lord of the Rings: The Two Towers',
    year: 2002,
  },
  { label: "One Flew Over the Cuckoo's Nest", year: 1975 },
  { label: 'Goodfellas', year: 1990 },
  { label: 'The Matrix', year: 1999 },
  { label: 'Seven Samurai', year: 1954 },
  {
    label: 'Star Wars: Episode IV - A New Hope',
    year: 1977,
  },
  { label: 'City of God', year: 2002 },
  { label: 'Se7en', year: 1995 },
  { label: 'The Silence of the Lambs', year: 1991 },
  { label: "It's a Wonderful Life", year: 1946 },
  { label: 'Life Is Beautiful', year: 1997 },
  { label: 'The Usual Suspects', year: 1995 },
  { label: 'Léon: The Professional', year: 1994 },
  { label: 'Spirited Away', year: 2001 },
  { label: 'Saving Private Ryan', year: 1998 },
  { label: 'Once Upon a Time in the West', year: 1968 },
  { label: 'American History X', year: 1998 },
  { label: 'Interstellar', year: 2014 },
  { label: 'Casablanca', year: 1942 },
  { label: 'City Lights', year: 1931 },
  { label: 'Psycho', year: 1960 },
  { label: 'The Green Mile', year: 1999 },
  { label: 'The Intouchables', year: 2011 },
  { label: 'Modern Times', year: 1936 },
  { label: 'Raiders of the Lost Ark', year: 1981 },
  { label: 'Rear Window', year: 1954 },
  { label: 'The Pianist', year: 2002 },
  { label: 'The Departed', year: 2006 },
  { label: 'Terminator 2: Judgment Day', year: 1991 },
  { label: 'Back to the Future', year: 1985 },
  { label: 'Whiplash', year: 2014 },
  { label: 'Gladiator', year: 2000 },
  { label: 'Memento', year: 2000 },
  { label: 'The Prestige', year: 2006 },
  { label: 'The Lion King', year: 1994 },
  { label: 'Apocalypse Now', year: 1979 },
  { label: 'Alien', year: 1979 },
  { label: 'Sunset Boulevard', year: 1950 },
  {
    label: 'Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb',
    year: 1964,
  },
  { label: 'The Great Dictator', year: 1940 },
  { label: 'Cinema Paradiso', year: 1988 },
  { label: 'The Lives of Others', year: 2006 },
  { label: 'Grave of the Fireflies', year: 1988 },
  { label: 'Paths of Glory', year: 1957 },
  { label: 'Django Unchained', year: 2012 },
  { label: 'The Shining', year: 1980 },
  { label: 'WALL·E', year: 2008 },
  { label: 'American Beauty', year: 1999 },
  { label: 'The Dark Knight Rises', year: 2012 },
  { label: 'Princess Mononoke', year: 1997 },
  { label: 'Aliens', year: 1986 },
  { label: 'Oldboy', year: 2003 },
  { label: 'Once Upon a Time in America', year: 1984 },
  { label: 'Witness for the Prosecution', year: 1957 },
  { label: 'Das Boot', year: 1981 },
  { label: 'Citizen Kane', year: 1941 },
  { label: 'North by Northwest', year: 1959 },
  { label: 'Vertigo', year: 1958 },
  {
    label: 'Star Wars: Episode VI - Return of the Jedi',
    year: 1983,
  },
  { label: 'Reservoir Dogs', year: 1992 },
  { label: 'Braveheart', year: 1995 },
  { label: 'M', year: 1931 },
  { label: 'Requiem for a Dream', year: 2000 },
  { label: 'Amélie', year: 2001 },
  { label: 'A Clockwork Orange', year: 1971 },
  { label: 'Like Stars on Earth', year: 2007 },
  { label: 'Taxi Driver', year: 1976 },
  { label: 'Lawrence of Arabia', year: 1962 },
  { label: 'Double Indemnity', year: 1944 },
  {
    label: 'Eternal Sunshine of the Spotless Mind',
    year: 2004,
  },
  { label: 'Amadeus', year: 1984 },
  { label: 'To Kill a Mockingbird', year: 1962 },
  { label: 'Toy Story 3', year: 2010 },
  { label: 'Logan', year: 2017 },
  { label: 'Full Metal Jacket', year: 1987 },
  { label: 'Dangal', year: 2016 },
  { label: 'The Sting', year: 1973 },
  { label: '2001: A Space Odyssey', year: 1968 },
  { label: "Singin' in the Rain", year: 1952 },
  { label: 'Toy Story', year: 1995 },
  { label: 'Bicycle Thieves', year: 1948 },
  { label: 'The Kid', year: 1921 },
  { label: 'Inglourious Basterds', year: 2009 },
  { label: 'Snatch', year: 2000 },
  { label: '3 Idiots', year: 2009 },
  { label: 'Monty Python and the Holy Grail', year: 1975 },
];


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>org.libra</groupId>
  <artifactId>mybatis-generator-gradle-plugin</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <versioning>
    <snapshot>
      <timestamp>20170918.034419</timestamp>
      <buildNumber>3</buildNumber>
    </snapshot>
    <lastUpdated>20170918034419</lastUpdated>
  </versioning>
</metadata>


text:
class InvalidReport(Exception):
    pass

class InvalidPcap(Exception):
    pass


text:
layout: page
title: "James Mcgoodwin"
comments: true
description: "blanks"
keywords: "James Mcgoodwin,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: ANTH 1180, ANTH 3110, ANTH 4020, ANTH 4570

#### ANTH 1180: MARITIME PEOPLE

**Terms taught**: Fall 2006, Fall 2007, Fall 2008, Fall 2009

**Instructor rating**: 5.21

**Standard deviation in instructor rating**: 0.17

**Average grade** (4.0 scale): 2.45

**Standard deviation in grades** (4.0 scale): 0.18

**Average workload** (raw): 1.87

**Standard deviation in workload** (raw): 0.01

#### ANTH 3110: ETHNOG MEX/CENTRAL AMER

**Terms taught**: Spring 2007, Spring 2008, Spring 2009, Spring 2010

**Instructor rating**: 5.07

**Standard deviation in instructor rating**: 0.32

**Average grade** (4.0 scale): 2.42

**Standard deviation in grades** (4.0 scale): 0.23

**Average workload** (raw): 2.19

**Standard deviation in workload** (raw): 0.07

#### ANTH 4020: TPC-ANTHRO OF HUNTING

**Terms taught**: Fall 2007, Fall 2008, Fall 2009

**Instructor rating**: 5.76

**Standard deviation in instructor rating**: 0.11

**Average grade** (4.0 scale): 3.23

**Standard deviation in grades** (4.0 scale): 0.18

**Average workload** (raw): 2.61

**Standard deviation in workload** (raw): 0.4

#### ANTH 4570: ANTHROPOLOGY OF FISHING

**Terms taught**: Spring 2007, Spring 2008, Spring 2009, Spring 2010

**Instructor rating**: 5.39

**Standard deviation in instructor rating**: 0.23

**Average grade** (4.0 scale): 2.51

**Standard deviation in grades** (4.0 scale): 0.41

**Average workload** (raw): 2.0

**Standard deviation in workload** (raw): 0.12


text:
package org.smartplatforms.oauth2;

import com.google.common.base.Joiner;
import org.mitre.oauth2.model.ClientDetailsEntity;
import org.mitre.oauth2.service.ClientDetailsEntityService;
import org.mitre.openid.connect.config.ConfigurationPropertiesBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@SessionAttributes("authorizationRequest")
public class SmartAuthorizationEndpoint extends AuthorizationEndpoint implements
        InitializingBean {

	@Autowired
	private SmartLaunchContextResolver smartLaunchContextResolver;

	@Autowired
	private ConfigurationPropertiesBean configBean;

	@Autowired
	private ClientDetailsEntityService clientService;

	private static Logger logger = LoggerFactory
			.getLogger(SmartAuthorizationEndpoint.class);

	private String getCurrentRequestUrl(AuthorizationRequest r) {
		ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = sra.getRequest();
		String ret = request.getQueryString();
		if (!request.getParameterMap().containsKey("scope")){
			ret += "&scope=" + Joiner.on(" ").join(r.getScope());
		}
		return ret;
	}

    @RequestMapping(value = "/authorize")
    @Override
	public ModelAndView authorize(Map<String, Object> model,
			@RequestParam Map<String, String> parameters,
			SessionStatus sessionStatus, Principal principal) {

        model.remove("authorizationRequest");
		ModelAndView mv = super.authorize(model, parameters, sessionStatus,
				principal);

		AuthorizationRequest authorizationRequest = (AuthorizationRequest) model
				.get("authorizationRequest");

		// TODO if launch context is needed, redirect to an external service to
		// go and get it
		if (authorizationRequest != null&& authorizationRequest.getExtensions().containsKey(
						"external_launch_required")) {
			logger.warn("About to redirect to context resolver UI");

			HashMap<String, String> launchReqs = (HashMap<String, String>) authorizationRequest.getExtensions().get("external_launch_required");
			String goals = Joiner.on(",").join(launchReqs.keySet());

			ClientDetailsEntity client = clientService.loadClientByClientId(authorizationRequest.getClientId());
			String url = smartLaunchContextResolver.getResolveEndpoint();
			url += "#/resolve/";
			url += doubleEncode(goals)+ "/against/";
			url += doubleEncode(smartLaunchContextResolver.getFhirEndpoint())+ "/for/";
			url += doubleEncode(client.getClientName())+ "/then/";
			url += doubleEncode(configBean.getIssuer() + "authorize?" + getCurrentRequestUrl(authorizationRequest));

			return new ModelAndView(new RedirectView(url));
		}

		// Plan: for SMART requests that need patient-level context, redirect to
		// a patient-picker, passing CSRF token
		// For SMART request that don't need patient-level context, redirect to
		// a simplified approval screen
		// be sure to have automatic approval of the trusted context-picking
		// app, so it always knows the current user.

		return mv;
	}

	private String doubleEncode(String s) {
		try {
			return URLEncoder.encode(URLEncoder.encode(s, "UTF-8"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

    @RequestMapping(value = "/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
    @Override
    public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model,
                              SessionStatus sessionStatus, Principal principal) {
        return super.approveOrDeny(approvalParameters, model, sessionStatus, principal);
    }
}


text:
// -----------------------------------------------------------------------
//  <copyright file="ServiceCollectionExtensions.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2019 OSharp. All rights reserved.
//  </copyright>
//  <site>http://www.osharp.org</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2019-03-27 13:23</last-date>
// -----------------------------------------------------------------------

using System;
using System.Data.Common;
using System.Linq;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

using OSharp.Core.Options;
using OSharp.Dependency;
using OSharp.Entity;
using OSharp.Exceptions;
using OSharp.Reflection;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// 依赖注入服务集合扩展
    /// </summary>
    public static class ServiceExtensions
    {
        /// <summary>
        /// 将基于Osharp数据上下文基类<see cref="DbContextBase"/>上下文类型添加到服务集合中
        /// </summary>
        /// <typeparam name="TDbContext">基于Osharp数据上下文基类<see cref="DbContextBase"/>上下文类型</typeparam>
        /// <param name="services">依赖注入服务集合</param>
        /// <param name="optionsAction">数据库选项创建配置,将在内置配置后运行</param>
        /// <returns>依赖注入服务集合</returns>
        public static IServiceCollection AddOsharpDbContext<TDbContext>(this IServiceCollection services, Action<IServiceProvider, DbContextOptionsBuilder> optionsAction = null) where TDbContext : DbContextBase
        {
            services.AddDbContext<TDbContext>((provider, builder) =>
            {
                Type dbContextType = typeof(TDbContext);
                OsharpOptions osharpOptions = provider.GetOSharpOptions();
                OsharpDbContextOptions osharpDbContextOptions = osharpOptions?.GetDbContextOptions(dbContextType);
                if (osharpDbContextOptions == null)
                {
                    throw new OsharpException($"无法找到数据上下文"{dbContextType.DisplayName()}"的配置信息");
                }

                //启用延迟加载
                if (osharpDbContextOptions.LazyLoadingProxiesEnabled)
                {
                    builder = builder.UseLazyLoadingProxies();
                }
                DatabaseType databaseType = osharpDbContextOptions.DatabaseType;

                //处理数据库驱动差异处理
                IDbContextOptionsBuilderDriveHandler driveHandler = provider.GetServices<IDbContextOptionsBuilderDriveHandler>()
                    .FirstOrDefault(m => m.Type == databaseType);
                if (driveHandler == null)
                {
                    throw new OsharpException($"无法解析类型为"{databaseType}"的 {typeof(IDbContextOptionsBuilderDriveHandler).DisplayName()} 实例");
                }

                ScopedDictionary scopedDictionary = provider.GetService<ScopedDictionary>();
                string key = $"DnConnection_{osharpDbContextOptions.ConnectionString}";
                DbConnection existingDbConnection = scopedDictionary.GetValue<DbConnection>(key);
                builder = driveHandler.Handle(builder, osharpDbContextOptions.ConnectionString, existingDbConnection);

                //使用模型缓存
                DbContextModelCache modelCache = provider.GetService<DbContextModelCache>();
                IModel model = modelCache?.Get(dbContextType);
                if (model != null)
                {
                    builder = builder.UseModel(model);
                }

                //额外的选项
                optionsAction?.Invoke(provider, builder);
            });
            return services;
        }
    }
}


text:
test_description='CRLF conversion'

. ./test-lib.sh

has_cr() {
	tr '\015' Q <"$1" | grep Q >/dev/null
}

test_expect_success setup '

	git config core.autocrlf false &&

	for w in Hello world how are you; do echo $w; done >one &&
	for w in I am very very fine thank you; do echo ${w}Q; done | q_to_cr >two &&
	for w in Oh here is a QNUL byte how alarming; do echo ${w}; done | q_to_nul >three &&
	git add . &&

	git commit -m initial &&

	one=`git rev-parse HEAD:one` &&
	two=`git rev-parse HEAD:two` &&
	three=`git rev-parse HEAD:three` &&

	echo happy.
'

test_expect_success 'default settings cause no changes' '

	rm -f .gitattributes tmp one two three &&
	git read-tree --reset -u HEAD &&

	! has_cr one &&
	has_cr two &&
	onediff=`git diff one` &&
	twodiff=`git diff two` &&
	threediff=`git diff three` &&
	test -z "$onediff" -a -z "$twodiff" -a -z "$threediff"
'

test_expect_success 'crlf=true causes a CRLF file to be normalized' '

	# Backwards compatibility check
	rm -f .gitattributes tmp one two three &&
	echo "two crlf" > .gitattributes &&
	git read-tree --reset -u HEAD &&

	# Note, "normalized" means that git will normalize it if added
	has_cr two &&
	twodiff=`git diff two` &&
	test -n "$twodiff"
'

test_expect_success 'text=true causes a CRLF file to be normalized' '

	rm -f .gitattributes tmp one two three &&
	echo "two text" > .gitattributes &&
	git read-tree --reset -u HEAD &&

	# Note, "normalized" means that git will normalize it if added
	has_cr two &&
	twodiff=`git diff two` &&
	test -n "$twodiff"
'

test_expect_success 'eol=crlf gives a normalized file CRLFs with autocrlf=false' '

	rm -f .gitattributes tmp one two three &&
	git config core.autocrlf false &&
	echo "one eol=crlf" > .gitattributes &&
	git read-tree --reset -u HEAD &&

	has_cr one &&
	onediff=`git diff one` &&
	test -z "$onediff"
'

test_expect_success 'eol=crlf gives a normalized file CRLFs with autocrlf=input' '

	rm -f .gitattributes tmp one two three &&
	git config core.autocrlf input &&
	echo "one eol=crlf" > .gitattributes &&
	git read-tree --reset -u HEAD &&

	has_cr one &&
	onediff=`git diff one` &&
	test -z "$onediff"
'

test_expect_success 'eol=lf gives a normalized file LFs with autocrlf=true' '

	rm -f .gitattributes tmp one two three &&
	git config core.autocrlf true &&
	echo "one eol=lf" > .gitattributes &&
	git read-tree --reset -u HEAD &&

	! has_cr one &&
	onediff=`git diff one` &&
	test -z "$onediff"
'

test_expect_success 'autocrlf=true does not normalize CRLF files' '

	rm -f .gitattributes tmp one two three &&
	git config core.autocrlf true &&
	git read-tree --reset -u HEAD &&

	has_cr one &&
	has_cr two &&
	onediff=`git diff one` &&
	twodiff=`git diff two` &&
	threediff=`git diff three` &&
	test -z "$onediff" -a -z "$twodiff" -a -z "$threediff"
'

test_expect_success 'text=auto, autocrlf=true _does_ normalize CRLF files' '

	rm -f .gitattributes tmp one two three &&
	git config core.autocrlf true &&
	echo "* text=auto" > .gitattributes &&
	git read-tree --reset -u HEAD &&

	has_cr one &&
	has_cr two &&
	onediff=`git diff one` &&
	twodiff=`git diff two` &&
	threediff=`git diff three` &&
	test -z "$onediff" -a -n "$twodiff" -a -z "$threediff"
'

test_expect_success 'text=auto, autocrlf=true does not normalize binary files' '

	rm -f .gitattributes tmp one two three &&
	git config core.autocrlf true &&
	echo "* text=auto" > .gitattributes &&
	git read-tree --reset -u HEAD &&

	! has_cr three &&
	threediff=`git diff three` &&
	test -z "$threediff"
'

test_expect_success 'eol=crlf _does_ normalize binary files' '

	rm -f .gitattributes tmp one two three &&
	echo "three eol=crlf" > .gitattributes &&
	git read-tree --reset -u HEAD &&

	has_cr three &&
	threediff=`git diff three` &&
	test -z "$threediff"
'

test_done


text:
package org.apache.datasketches.hll;

/**
 * Specifies the target type of HLL sketch to be created. It is a target in that the actual
 * allocation of the HLL array is deferred until sufficient number of items have been received by
 * the warm-up phases.
 *
 *
These three target types are isomorphic representations of the same underlying HLL algorithm.
 * Thus, given the same value of lgConfigK and the same input, all three HLL target types
 * will produce identical estimates and have identical error distributions.

 *
 *
The memory (and also the serialization) of the sketch during this early warmup phase starts
 * out very small (8 bytes, when empty) and then grows in increments of 4 bytes as required
 * until the full HLL array is allocated.  This transition point occurs at about 10% of K for
 * sketches where lgConfigK is > 8.

 *
 *

 *
HLL_8 This uses an 8-bit byte per HLL bucket. It is generally the
 * fastest in terms of update time, but has the largest storage footprint of about
 * K bytes.

 *
 *
HLL_6 This uses a 6-bit field per HLL bucket. It is the generally the next fastest
 * in terms of update time with a storage footprint of about 3/4 * K bytes.

 *
 *
HLL_4 This uses a 4-bit field per HLL bucket and for large counts may require
 * the use of a small internal auxiliary array for storing statistical exceptions, which are rare.
 * For the values of lgConfigK > 13 (K = 8192),
 * this additional array adds about 3% to the overall storage. It is generally the slowest in
 * terms of update time, but has the smallest storage footprint of about
 * K/2 * 1.03 bytes.

 *

 * @author Lee Rhodes
 */
@SuppressWarnings("javadoc")
public enum TgtHllType { HLL_4, HLL_6, HLL_8;

  private static final TgtHllType values[] = values();

  public static final TgtHllType fromOrdinal(final int typeId) {
    return values[typeId];
  }
}


text: Demos for embedding


text:
package com.bonsaimanager.backend.domain;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.bonsaimanager.common.persistence.model.INameableEntity;
import com.bonsaimanager.enums.PlansEnum;

/*
 * Role Domain Class - 25/01/2017
 * id 		- 	id of the role
 * name 	- 	name of the role
 *
 */
@Entity
@Table(name = "plan")
public class Plan implements Serializable, INameableEntity{

	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "plan_id")
	private Long id;

	private String name;

	private String description;

	@OneToMany(mappedBy = "role", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
	private Set<UserRole> userRoles = new HashSet<>();

	public Plan(){

	}

	public Plan(PlansEnum plansEnum){
		this.id = plansEnum.getId();
		this.name = plansEnum.getPlanName();
		this.description = plansEnum.getPlanDescription();
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set<UserRole> getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(Set<UserRole> userRoles) {
		this.userRoles = userRoles;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((description == null) ? 0 : description.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((userRoles == null) ? 0 : userRoles.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Plan other = (Plan) obj;
		if (description == null) {
			if (other.description != null)
				return false;
		} else if (!description.equals(other.description))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (userRoles == null) {
			if (other.userRoles != null)
				return false;
		} else if (!userRoles.equals(other.userRoles))
			return false;
		return true;
	}

}


text:
'use strict';

var Stripe = require('stripe'),
stripe;

module.exports = exports = function stripeCustomer (schema, options) {
  stripe = Stripe(options.apiKey);

  schema.add({
    stripe: {
      customerId: String,
      subscriptionId: String,
      last4: String,
      plan: {
        type: String,
        default: options.defaultPlan
      }
    }
  });

  schema.pre('save', function (next) {
    var user = this;
    if(!user.isNew || user.stripe.customerId) return next();
    user.createCustomer(function(err){
      if (err) return next(err);
      next();
    });
  });

  schema.statics.getPlans = function () {
    return options.planData;
  };

  schema.methods.createCustomer = function(cb) {
    var user = this;

    stripe.customers.create({
      email: user.email
    }, function(err, customer){
      if (err) return cb(err);

      user.stripe.customerId = customer.id;

      user.save(function(err){
        if (err) return cb(err);
        return cb(null);
      });
    });
  };

  schema.methods.setCard = function(stripe_token, cb) {
    var user = this;

    var cardHandler = function(err, customer) {
      if (err) return cb(err);

      if(!user.stripe.customerId){
        user.stripe.customerId = customer.id;
      }

      var card = customer.sources.data[0];
      user.stripe.last4 = card.last4;
      user.save(function(err){
        if (err) return cb(err);
        return cb(null);
      });
    };

    if(user.stripe.customerId){
      stripe.customers.update(user.stripe.customerId, {card: stripe_token}, cardHandler);
    } else {
      stripe.customers.create({
        email: user.email,
        card: stripe_token
      }, cardHandler);
    }
  };

  schema.methods.setPlan = function(plan, stripe_token, cb) {
    var user = this,
    customerData = {
      plan: plan
    };

    var subscriptionHandler = function(err, subscription) {
      if(err) return cb(err);

      user.stripe.plan = plan;
      user.stripe.subscriptionId = subscription.id;
      user.save(function(err){
        if (err) return cb(err);
        return cb(null);
      });
    };

    var createSubscription = function(){
      stripe.customers.createSubscription(
        user.stripe.customerId,
        {plan: plan},
        subscriptionHandler
      );
    };

    if(stripe_token) {
      user.setCard(stripe_token, function(err){
        if (err) return cb(err);
        createSubscription();
      });

    } else {
      if (user.stripe.subscriptionId){
        // update subscription
        stripe.customers.updateSubscription(
          user.stripe.customerId,
          user.stripe.subscriptionId,
          { plan: plan },
          subscriptionHandler
        );
      } else {
        createSubscription();
      }
    }
  };

  schema.methods.updateStripeEmail = function(cb){
    var user = this;

    if(!user.stripe.customerId) return cb();

    stripe.customers.update(user.stripe.customerId, {email: user.email}, function(err, customer) {
      cb(err);
    });
  };

  schema.methods.cancelStripe = function(cb){
    var user = this;

    if(user.stripe.customerId){
      stripe.customers.del(
        user.stripe.customerId
      ).then(function(confirmation) {
        cb();
      }, function(err) {
        return cb(err);
      });
    } else {
      cb();
    }
  };
};


text:
/*
 * client.c -- a simple client to investigate select() with pthreads
 *
 * Antony Courtney,	14/4/95
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#include "anp_wrappers.h"
#include "anp_test.h"

/* just use loopback interface: */

extern unsigned short serv_port;

#define BUFSIZE 256

void dump_bytes(char *buf,int nbytes)
{
     char *s;
     char *nilp;

     /* find next NUL, if any */
     s=buf;
     nilp=buf;
     while (nilp < buf + nbytes) {
	  while ((nilp < buf + nbytes) && (*nilp!='\0'))
	       nilp++;
	  if (nilp < buf + nbytes) {
	       printf("[%s] ",s);
	       s=nilp+1;
	       nilp++;
	  }
     }
     printf("\n");
}

/* client_loop() -- simple loop around a select() checking for data to read
 * on the connection to the server
 */
void client_loop(int fd)
{
     static char buf[BUFSIZE];
     int nbytes;
     int old_flags;
     struct timeval timeout={3600, 0};

     while (1) {
	  if ((nbytes=read(fd,buf,BUFSIZE)) < 0) {
	       err_sys("client read");
	  } else {
	       if (nbytes==0) {
		    printf("server closed connection.\n");
		    close(fd);
		    return;
	       }
	       printf("client read %d bytes from server: ",nbytes);
	       dump_bytes(buf,nbytes);
	  }
     }
}

void clitest(char *dst_addr)
{
     int sockfd;
     struct sockaddr_in serv_addr;
     unsigned short portno;

     if (port_num==0) {
	  /* loopback test */
	  portno=(short) serv_port;
     } else {
	  /* take port number from command line */
	  portno=(short) port_num;
     }

     printf("client: attempting to connect to server %s:%d\n", dst_addr,portno);
     memset(&serv_addr,0,sizeof(serv_addr));
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr=inet_addr(dst_addr);
     serv_addr.sin_port=htons(portno);

     if ((sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0) {
	  err_sys("client socket");
     }

     /* connect to server */
     if (connect(sockfd,(struct sockaddr *) &serv_addr,
		 sizeof(serv_addr)) < 0) {
	  err_sys("client connect");
     }
     printf("client: server contacted, entering read loop...\n");

     client_loop(sockfd);
}


text:
OK, this is just some :mod:react-dom/server

:mod:react-dom/start start

In between :mod:between ok...


text:
<?php
use dosamigos\fileupload\FileUploadUI;
use fabiomlferreira\filemanager\Module;
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $searchModel fabiomlferreira\filemanager\models\Mediafile */

?>

 <?= Module::t('main', 'Upload manager') ?>

<?= Html::a('← ' . Module::t('main', 'Back to file manager'), ['file/filemanager']) ?>

    <?= FileUploadUI::widget([
        'model' => $model,
        'attribute' => 'file',
        'clientOptions' => [
            'autoUpload'=> Yii::$app->getModule('filemanager')->autoUpload,
        ],
        'clientEvents' => [
            'fileuploadsubmit' => "function (e, data) { data.formData = [{name: 'tagIds', value: $('#filemanager-tagIds').val()}]; }",
        ],
        'url' => ['upload'],
        'gallery' => false,
        'formView' => '/file/_upload_form',
    ]) ?>


text:
package com.infinityraider.infinitylib.render.model;

import com.google.common.collect.*;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.infinityraider.infinitylib.InfinityLib;
import com.infinityraider.infinitylib.block.tile.TileEntityDynamicTexture;
import com.infinityraider.infinitylib.item.BlockItemDynamicTexture;
import com.infinityraider.infinitylib.render.IRenderUtilities;
import com.mojang.datafixers.util.Pair;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.*;
import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.model.IModelConfiguration;
import net.minecraftforge.client.model.data.IModelData;
import net.minecraftforge.client.model.data.ModelProperty;
import net.minecraftforge.client.model.geometry.IModelGeometry;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import java.util.function.Function;

@OnlyIn(Dist.CLIENT)
public class InfModelLoaderDynamicTexture implements InfModelLoader<InfModelLoaderDynamicTexture.Geometry> {
    private static final ResourceLocation ID = new ResourceLocation(InfinityLib.instance.getModId(), "dynamic_texture");
    private static final String DYNAMIC_TEXTURE = "dynamic";

    private static final InfModelLoaderDynamicTexture INSTANCE = new InfModelLoaderDynamicTexture();

    public static InfModelLoaderDynamicTexture getInstance() {
        return INSTANCE;
    }

    private InfModelLoaderDynamicTexture() {}

    @Override
    public ResourceLocation getId() {
        return ID;
    }

    @Override
    public void onResourceManagerReload(@Nonnull ResourceManager resourceManager) {}

    @Nonnull
    @Override
    public Geometry read(@Nonnull JsonDeserializationContext context, JsonObject modelContents) {
        // Fetch default texture
        if(!modelContents.has("textures")) {
            throw new RuntimeException("Dynamic texture model needs a \"textures\" field.");
        }
        JsonObject textureJson = modelContents.getAsJsonObject("textures");
        if(!textureJson.has("default")) {
            throw new RuntimeException("Dynamic texture model needs a \"default\" texture in the textures.");
        }
        String defaultTexture = textureJson.get("default").getAsString();
        // Fetch model parts
        List<BlockElement> parts = Lists.newArrayList();
        if(modelContents.has("elements")) {
            for(JsonElement jsonelement : GsonHelper.getAsJsonArray(modelContents, "elements")) {
                parts.add(context.deserialize(jsonelement, BlockElement.class));
            }
        }
        // Fetch Item Model transforms
        ItemTransforms itemCameraTransforms = ItemTransforms.NO_TRANSFORMS;
        if (modelContents.has("display")) {
            JsonObject transforms = GsonHelper.getAsJsonObject(modelContents, "display");
            itemCameraTransforms = context.deserialize(transforms, ItemTransforms.class);
        }
        // Return geometry
        return new Geometry(this.flagDynamicTextures(parts), defaultTexture, itemCameraTransforms);
    }

    private List<BlockElement> flagDynamicTextures(List<BlockElement> parts) {
        parts.forEach(part -> part.faces.replaceAll((dir, face) -> {
            if(DYNAMIC_TEXTURE.equals(face.texture)) {
                return new DynamicFace(face);
            } else {
                return face;
            }
        }));
        return parts;
    }

    private static class DynamicFace extends BlockElementFace {
        public DynamicFace(BlockElementFace parent) {
            super(parent.cullForDirection, parent.tintIndex, parent.texture, parent.uv);
        }
    }

    public static class Geometry implements IModelGeometry<Geometry>, IRenderUtilities {
        private final List<BlockElement> parts;
        private final String defaultTexture;
        private final ItemTransforms transforms;

        private Geometry(List<BlockElement> parts, String defaultTexture, ItemTransforms transforms) {
            this.parts = parts;
            this.defaultTexture = defaultTexture;
            this.transforms = transforms;
        }

        @Override
        public BakedModel bake(IModelConfiguration owner, ModelBakery bakery, Function<Material, TextureAtlasSprite> spriteGetter,
                               ModelState transform, ItemOverrides overrides, ResourceLocation modelLocation) {
            return new DynamicTextureModel(
                    this.parts, owner, this.transforms, spriteGetter, transform, overrides, modelLocation, this.defaultTexture);
        }

        @Override
        public Collection<Material> getTextures(IModelConfiguration owner, Function<ResourceLocation, UnbakedModel> modelGetter,
                                                      Set<Pair<String, String>> missingTextureErrors) {
            // Create new set
            Set<Material> textures = Sets.newHashSet();
            // Add textures for the parts
            for(BlockElement part : this.parts) {
                for(BlockElementFace face : part.faces.values()) {
                    // Skip if it is a dynamic texture
                    if(face instanceof DynamicFace) {
                        continue;
                    }
                    // Add otherwise
                    Material texture = owner.resolveTexture(face.texture);
                    if (Objects.equals(texture.texture(), MissingTextureAtlasSprite.getLocation())) {
                        missingTextureErrors.add(Pair.of(face.texture, owner.getModelName()));
                    }
                    textures.add(texture);
                }
            }
            // Add the default texture
            Material texture = this.getRenderMaterial(this.defaultTexture);
            if (Objects.equals(texture.texture(), MissingTextureAtlasSprite.getLocation())) {
                missingTextureErrors.add(Pair.of(this.defaultTexture, owner.getModelName()));
            }
            textures.add(owner.resolveTexture(this.defaultTexture));
            // Return the textures
            return textures;
        }
    }

    public static class DynamicTextureModel implements BakedModel, IRenderUtilities {
        private static final ModelProperty<ItemStack> PROPERTY_MATERIAL = TileEntityDynamicTexture.PROPERTY_MATERIAL;

        private final Map<TextureAtlasSprite, BakedModel> quadCache;

        private final BakedModel defaultModel;
        private final TextureAtlasSprite defaultSprite;

        private final List<BlockElement> parts;
        private final IModelConfiguration owner;
        private final ItemTransforms transforms;
        private final Function<Material, TextureAtlasSprite> spriteGetter;
        private final ModelState transform;
        private final ItemOverrides overrides;
        private final ResourceLocation modelLocation;

        private DynamicTextureModel(List<BlockElement> parts, IModelConfiguration owner, ItemTransforms transforms,
                                    Function<Material, TextureAtlasSprite> spriteGetter, ModelState transform,
                                    ItemOverrides overrides, ResourceLocation modelLocation, String defaultTexture) {
            this.quadCache = Maps.newConcurrentMap();
            this.parts = parts;
            this.owner = owner;
            this.transforms = transforms;
            this.spriteGetter = spriteGetter;
            this.transform = transform;
            this.overrides = overrides;
            this.modelLocation = modelLocation;
            this.defaultSprite = this.spriteGetter.apply(this.getRenderMaterial(defaultTexture));
            this.defaultModel = this.bakeSubModel(this.getDefaultSprite());
        }

        public BakedModel getDefaultModel() {
            return this.defaultModel;
        }

        @Nonnull
        public TextureAtlasSprite getDefaultSprite() {
            return this.defaultSprite;
        }

        @Nonnull
        @SuppressWarnings("deprecation")
        protected TextureAtlasSprite getMaterialSprite(@Nullable ItemStack material) {
            if(material == null || material.isEmpty()) {
                return this.getDefaultSprite();
            }
            if(material.getItem() instanceof BlockItem) {
                Block block = ((BlockItem) material.getItem()).getBlock();
                return this.getModelForState(block.defaultBlockState()).getParticleIcon();
            }
            return this.getDefaultSprite();
        }

        @Nonnull
        @Override
        public IModelData getModelData(@Nonnull BlockAndTintGetter world, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nonnull IModelData modelData) {
            return modelData;
        }

        @Nonnull
        @Override
        public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @Nonnull Random rand) {
            return this.getQuads(state, side, rand, this.getDefaultSprite());
        }

        @Nonnull
        @Override
        public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @Nonnull Random rand, @Nonnull IModelData extraData) {
            if (!extraData.hasProperty(PROPERTY_MATERIAL)) {
                return this.getQuads(state, side, rand);
            }
            TextureAtlasSprite sprite = this.getMaterialSprite(extraData.getData(PROPERTY_MATERIAL));
            return this.getQuads(state, side, rand, sprite);
        }

        @Nonnull
        @SuppressWarnings("deprecation")
        public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @Nonnull Random rand, @Nonnull TextureAtlasSprite material) {
            return this.getSubModel(material).getQuads(state, side, rand);
        }

        public BakedModel getSubModel(@Nonnull TextureAtlasSprite material) {
            if(material.getName().equals(this.getDefaultSprite().getName())) {
                return this.getDefaultModel();
            }
            return this.quadCache.computeIfAbsent(material, this::bakeSubModel);
        }

        protected BakedModel bakeSubModel(@Nonnull TextureAtlasSprite material) {
            // Initialize quad lists
            List<BakedQuad> generalQuads = Lists.newArrayList();
            Map<Direction, List<BakedQuad>> faceQuads = Maps.newEnumMap(Direction.class);
            Arrays.stream(Direction.values()).forEach((dir) -> faceQuads.put(dir, Lists.newArrayList()));
            // Iterate over all parts
            for (BlockElement part : this.parts) {
                // Iterate over the faces
                for (Direction direction : part.faces.keySet()) {
                    BlockElementFace face = part.faces.get(direction);
                    // Fetch the necessary texture
                    TextureAtlasSprite sprite;
                    if (face instanceof DynamicFace) {
                        sprite = material;
                    } else {
                        sprite = this.spriteGetter.apply(this.owner.resolveTexture(face.texture));
                    }
                    // Add the quad to the model builder
                    if (face.cullForDirection == null) {
                        generalQuads.add(BlockModel.makeBakedQuad(part, face, sprite, direction, this.transform, this.modelLocation));
                    } else {
                        faceQuads.get(this.transform.getRotation().rotateTransform(face.cullForDirection))
                                .add(BlockModel.makeBakedQuad(part, face, sprite, direction, this.transform, this.modelLocation));
                    }
                }
            }
            // Build the model
            return new SimpleBakedModel(
                    ImmutableList.copyOf(generalQuads),
                    ImmutableMap.copyOf(Maps.transformValues(faceQuads, ImmutableList::copyOf)),
                    this.owner.useSmoothLighting(), this.owner.isSideLit(), this.owner.isShadedInGui(),
                    material, this.getTransforms(), this.getOverrides());
        }

        @Override
        public boolean useAmbientOcclusion() {
            return true;
        }

        @Override
        public boolean isGui3d() {
            return true;
        }

        @Override
        public boolean usesBlockLight() {
            return false;
        }

        @Override
        public boolean isCustomRenderer() {
            return false;
        }

        @Nonnull
        @Override
        public TextureAtlasSprite getParticleIcon() {
            return this.getDefaultSprite();
        }

        @Nonnull
        @Override
        public TextureAtlasSprite getParticleIcon(@Nonnull IModelData extraData) {
            if (!extraData.hasProperty(PROPERTY_MATERIAL)) {
                return this.getParticleIcon();
            }
            return this.getMaterialSprite(extraData.getData(PROPERTY_MATERIAL));
        }

        @Nonnull
        @Override
        @Deprecated
        @SuppressWarnings("deprecation")
        public ItemTransforms getTransforms() {
            return this.transforms;
        }

        @Nonnull
        @Override
        public ItemOverrides getOverrides() {
            return this.overrides;
        }

        @Override
        public boolean isLayered() {
            return true;
        }

        @Override
        public List<Pair<BakedModel, RenderType>> getLayerModels(ItemStack stack, boolean fabulous) {
            return Collections.singletonList(Pair.of(
                    this.getSubModel(this.getMaterialSprite(this.getMaterialFromStack(stack))),
                    ItemBlockRenderTypes.getRenderType(stack, fabulous)));
        }

        @Nonnull
        protected ItemStack getMaterialFromStack(@Nonnull ItemStack stack) {
            if(stack.getItem() instanceof BlockItemDynamicTexture) {
                return ((BlockItemDynamicTexture) stack.getItem()).getMaterial(stack);
            }
            return ItemStack.EMPTY;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Recording Self Talk • Habitry Source</title>
    <meta name="description" content="In order to become more aware of our thoughts, we're going to practice recording our self-talk.

">
    <meta name="keywords" content="health, fitness, awareness, mindfullness, mindset">

	<meta name="twitter:title" content="Recording Self Talk">
	<meta name="twitter:description" content="In order to become more aware of our thoughts, we're going to practice recording our self-talk.

">

	<meta name="twitter:creator" content="@thecoachstevo">

	<meta name="twitter:card" content="summary">
	<meta name="twitter:image" content="http://localhost:4000/images/Habitry-120x120-transparent.png">

	<meta property="og:locale" content="en">
	<meta property="og:type" content="article">
	<meta property="og:title" content="Recording Self Talk">
	<meta property="og:description" content="In order to become more aware of our thoughts, we're going to practice recording our self-talk.

">
	<meta property="og:url" content="http://localhost:4000/habits/recordselftalk/">
	<meta property="og:site_name" content="Habitry Source">

    <link rel="canonical" href="http://localhost:4000/habits/recordselftalk/">

    <link href="http://localhost:4000/atom.xml" type="application/atom+xml" rel="alternate" title="Habitry Source Atom Feed">
    <link href="http://localhost:4000/sitemap.xml" type="application/xml" rel="sitemap" title="Sitemap">

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="cleartype" content="on">

    <link rel="stylesheet" href="http://localhost:4000/css/main.css">

    Habitry Source

Habitry Source

About

Habits

Habitry Source Table of Contents

About

Habits

<button type="button" id="js-menu-trigger" class="sliding-menu-button lines-button x2" role="button" aria-label="Toggle Navigation">

</button>

Recording Self Talk

In order to become more aware of our thoughts, we're going to practice recording our self-talk.

Why

One of the most vicious saboteurs of a fat loss program can be the little voice inside your head. So start writing down what it says, when it says it, and how it makes you feel. Learning under what conditions that voice pops up might be the first step in quieting him or her down.

How

One way would be to set aside some time every day to write down what your self-talk is. For example, you could journal for 5 mins every day. And then increase the minutes you spend if you feel the need.

When

If you are going to do this habit every day, pick an event that you do every day that will remind you. For example, you could journal before going to bed every night.

Level: 5

Skills

mindfullness

mindset

Tags

health

fitness

awareness

mindfullness

mindset

Written by Steven M. Ledbetter

Coach Stevo is the CEO of Habitry

	 Share on Twitter
	 Share on Facebook
	 Share on Google+

Updated <time datetime="2016-03-19T14:35:40Z" itemprop="datePublished">March 19, 2016</time>

Please enable JavaScript to view the comments powered by Disqus.

© 2016 Habitry Source powered by Jekyll + Skinny Bones.


text:
package org.wso2.carbon.identity.application.mgt.internal;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.wso2.carbon.identity.application.mgt.listener.ApplicationMgtListener;
import org.wso2.carbon.identity.application.mgt.listener.ApplicationResourceManagementListener;
import org.wso2.carbon.identity.application.mgt.validator.ApplicationValidator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;

/**
 * OSGI service component for Aplication management listeners.
 *
 */
@Component(
        name = "org.wso2.carbon.identity.application.mgt.listener",
        immediate = true
)
public class ApplicationMgtListenerServiceComponent {

    private static List<ApplicationMgtListener> applicationMgtListeners = new ArrayList<>();
    private static List<ApplicationResourceManagementListener> applicationResourceMgtListeners = new ArrayList<>();
    private static List<ApplicationValidator> applicationValidators = new ArrayList<>();

    @Reference(
            name = "application.mgt.event.listener.service",
            service = ApplicationMgtListener.class,
            cardinality = ReferenceCardinality.MULTIPLE,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "unsetApplicationMgtListenerService"
    )
    protected synchronized void setApplicationMgtListenerService(ApplicationMgtListener applicationMgtListenerService) {

        applicationMgtListeners.add(applicationMgtListenerService);
        applicationMgtListeners.sort(appMgtListenerComparator);
    }

    protected synchronized void unsetApplicationMgtListenerService(
            ApplicationMgtListener applicationMgtListenerService) {

        applicationMgtListeners.remove(applicationMgtListenerService);
    }

    public static synchronized Collection<ApplicationMgtListener> getApplicationMgtListeners() {

        return applicationMgtListeners;
    }

    @Reference(
            name = "application.resource.mgt.event.listener.service",
            service = ApplicationResourceManagementListener.class,
            cardinality = ReferenceCardinality.MULTIPLE,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "unsetApplicationResourceMgtListener"
    )
    protected synchronized void setApplicationResourceMgtListener(ApplicationResourceManagementListener listener) {

        applicationResourceMgtListeners.add(listener);
        applicationResourceMgtListeners.sort(appResourceMgtListenerComparator);
    }

    protected synchronized void unsetApplicationResourceMgtListener(ApplicationResourceManagementListener listener) {

        applicationResourceMgtListeners.remove(listener);
    }

    public static Collection<ApplicationResourceManagementListener> getApplicationResourceMgtListeners() {

        return applicationResourceMgtListeners;
    }

    @Reference(
            name = "application.validator.service",
            service = ApplicationValidator.class,
            cardinality = ReferenceCardinality.MULTIPLE,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "unsetApplicationValidator"
    )
    protected synchronized void setApplicationValidator(ApplicationValidator listener) {

        applicationValidators.add(listener);
        applicationValidators.sort(applicationValidatorComparator);
    }

    protected synchronized void unsetApplicationValidator(ApplicationValidator listener) {

        applicationValidators.remove(listener);
    }

    public static Collection<ApplicationValidator> getApplicationValidators() {

        return applicationValidators;
    }

    private static Comparator<ApplicationMgtListener> appMgtListenerComparator =
            Comparator.comparingInt(ApplicationMgtListener::getExecutionOrderId);

    private static Comparator<ApplicationResourceManagementListener> appResourceMgtListenerComparator =
            Comparator.comparingInt(ApplicationResourceManagementListener::getExecutionOrderId);

    private static Comparator<ApplicationValidator> applicationValidatorComparator =
            Comparator.comparingInt(ApplicationValidator::getOrderId);
}


text:
id: bad87fee1348bd9aed508826
title: Clone an Element Using jQuery
challengeType: 6
isHidden: false
forumTopicId: 16780
---

## Description

In addition to moving elements, you can also copy them from one place to another.
jQuery has a function called clone() that makes a copy of an element.
For example, if we wanted to copy target2 from our left-well to our right-well, we would use:
$("#target2").clone().appendTo("#right-well");
Did you notice this involves sticking two jQuery functions together? This is called <dfn>function chaining</dfn> and it's a convenient way to get things done with jQuery.
Clone your target5 element and append it to your left-well.

## Instructions

## Tests

```yml
tests:
  - text: Your <code>target5</code> element should be inside your <code>right-well</code>.
    testString: assert($("#right-well").children("#target5").length > 0);
  - text: A copy of your <code>target5</code> element should also be inside your <code>left-well</code>.
    testString: assert($("#left-well").children("#target5").length > 0);
  - text: You should only use jQuery to move these elements.
    testString: assert(!code.match(/class.*animated/g));

```

## Challenge Seed

```html
<script>
  $(document).ready(function() {
    $("#target1").css("color", "red");
    $("#target1").prop("disabled", true);
    $("#target4").remove();
    $("#target2").appendTo("#right-well");

  });
</script>

<!-- Only change code above this line. -->

<div class="container-fluid">
  <h3 class="text-primary text-center">jQuery Playground</h3>
  <div class="row">
    <div class="col-xs-6">
      <h4>#left-well</h4>
      <div class="well" id="left-well">
        <button class="btn btn-default target" id="target1">#target1</button>
        <button class="btn btn-default target" id="target2">#target2</button>
        <button class="btn btn-default target" id="target3">#target3</button>
      </div>
    </div>
    <div class="col-xs-6">
      <h4>#right-well</h4>
      <div class="well" id="right-well">
        <button class="btn btn-default target" id="target4">#target4</button>
        <button class="btn btn-default target" id="target5">#target5</button>
        <button class="btn btn-default target" id="target6">#target6</button>
      </div>
    </div>
  </div>
</div>
```

## Solution

```html
<script>
  $(document).ready(function() {
    $("#target1").css("color", "red");
    $("#target1").prop("disabled", true);
    $("#target4").remove();
    $("#target2").appendTo("#right-well");
    $("#target5").clone().appendTo("#left-well");
  });
</script>

<!-- Only change code above this line. -->

<div class="container-fluid">
  <h3 class="text-primary text-center">jQuery Playground</h3>
  <div class="row">
    <div class="col-xs-6">
      <h4>#left-well</h4>
      <div class="well" id="left-well">
        <button class="btn btn-default target" id="target1">#target1</button>
        <button class="btn btn-default target" id="target2">#target2</button>
        <button class="btn btn-default target" id="target3">#target3</button>
      </div>
    </div>
    <div class="col-xs-6">
      <h4>#right-well</h4>
      <div class="well" id="right-well">
        <button class="btn btn-default target" id="target4">#target4</button>
        <button class="btn btn-default target" id="target5">#target5</button>
        <button class="btn btn-default target" id="target6">#target6</button>
      </div>
    </div>
  </div>
</div>
```


text:
using System;
using System.Windows.Forms;
using AR.Drone.Video;
using System.Drawing;
using AR.Drone.Data;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Diagnostics;

namespace UAV.Vision
{
    public partial class MainForm : Form
    {
        // Video related members.
        Bitmap frameBitmap;
        TcpClient videoClient;
        DateTime last;
        int bytes;
        bool running;
        VideoPacketDecoderWorker videoDecoder;
        uint lastFrameNumber;

        public MainForm()
        {
            InitializeComponent();

            last = DateTime.UtcNow;
            bytes = 0;
            running = true;

            // initialize video packet decoder.
            videoDecoder = new VideoPacketDecoderWorker(PixelFormat.BGR24, true, OnFrameDecoded);
            videoDecoder.UnhandledException += (delegate(object sender, Exception ex)
            {
					Console.WriteLine(ex);
                Process.GetCurrentProcess().Kill();
            });
            videoDecoder.Start();

            videoClient = new TcpClient(Environment.GetCommandLineArgs()[1], 1994);
            new Thread(VideoRecvLoop).Start();

            videoTimer.Enabled = true;
        }

        void OnFrameDecoded(VideoFrame frame)
        {
            //Console.WriteLine("On frame decoded.");

            if (frame == null || frame.Number == lastFrameNumber)
                return;

            lastFrameNumber = frame.Number;

            // If we already have a bitmap, update it, else, create new one.
            if (frameBitmap == null)
                frameBitmap = VideoHelper.CreateBitmap(ref frame);
            else
                VideoHelper.UpdateBitmap(ref frameBitmap, ref frame);
        }

        void VideoTimer_Tick(object sender, EventArgs e)
        {
			if (frameBitmap != null) {
				videoPictureBox.Image = frameBitmap.Clone () as Image;

				if (DateTime.UtcNow - last >= new TimeSpan (0, 0, 1)) { // if time passed is >= 1 sec.
					Console.WriteLine ("Bitrate: {0} MB/s", (double)bytes / (1024.0 * 1024));
					last = DateTime.UtcNow;
					bytes = 0;
				}
			}
        }

        void Form_Closing(object sender, EventArgs e)
        {
            running = false;
        }

        void VideoRecvLoop()
        {
            var stream = videoClient.GetStream();

            while (running)
            {
                try
                {
                    // Read packet size.
                    var szbuf = ReadBytes(stream, 4);
                    int total_size = BitConverter.ToInt32(szbuf, 0);
                    bytes += total_size;

                    // Read data.
                    var databuf = ReadBytes(stream, total_size);
                    var packet = ConvertVideoPacket(databuf);

                    videoDecoder.EnqueuePacket(packet);

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        static byte[] ReadBytes(Stream stream, int count)
        {
            var buffer = new byte[count];

            int offset = 0;
            while (offset < count)
            {
                int read = stream.Read(buffer, offset, count - offset);
                if (read == 0)
                    throw new EndOfStreamException();
                offset += read;
            }

            return buffer;
        }

        VideoPacket ConvertVideoPacket(byte[] data)
        {
            long timestamp = BitConverter.ToInt64(data, 0);
            uint framenumber = BitConverter.ToUInt32(data, 8);
            ushort height = BitConverter.ToUInt16(data, 8 + 4);
            ushort width = BitConverter.ToUInt16(data, 8 + 4 + 2);
            VideoFrameType ft = (VideoFrameType)BitConverter.ToInt32(data, 8 + 4 + 2 + 2);

            var viddata = new byte[data.Length - (8 + 4 + 2 + 2 + 4)];
            Array.Copy(data, 8 + 4 + 2 + 2 + 4, viddata, 0, viddata.Length);

            var packet = new VideoPacket
            {
                Timestamp = timestamp,
                FrameNumber = framenumber,
                Height = height,
                Width = width,
                FrameType = ft,
                Data = viddata
            };

            return packet;
        }
    }
}


text:
Each library has its own, language preferred way, to pass connection options. One of the most common options is a connection timeout. To set the maximum time to connect to a server to 10 seconds:

!INCLUDE "../../_examples/connect_options.html"


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 6(1): 29 (1977)

#### Original name
Glomus etunicatum W.N. Becker & Gerd., 1977

### Remarks
null


text:
BEGIN TRANSACTION;
INSERT INTO users VALUES(2000,'joe.blow@anywhere.com',NULL,'2017-06-13 15:29:42.114265','2017-06-13 15:29:42.114265','Joe','Blow',1,0,NULL,NULL,NULL,NULL,0);
INSERT INTO clauses VALUES(1,'While the most common way is to use the flask command , you can also make your own " driver scripts " .',5);
INSERT INTO clauses VALUES(2,'While the most common way is to use the flask command , you can also make your own " driver scripts " .',13);
INSERT INTO clauses VALUES(3,'Since Flask uses click for the scripts there is no reason you cannot hook these scripts into any click application .',2);
INSERT INTO clauses VALUES(4,'Since Flask uses click for the scripts there is no reason you cannot hook these scripts into any click application .',8);
INSERT INTO clauses VALUES(5,'Since Flask uses click for the scripts there is no reason you cannot hook these scripts into any click application .',12);
INSERT INTO annotations VALUES(1,1,2000,'2017-06-13 15:30:00.468096','false','true','false','false','false');
INSERT INTO annotations VALUES(2,1,2000,'2017-06-13 15:31:25.195165','false','false','false','false','false');
INSERT INTO annotations VALUES(3,1,2000,'2017-06-13 15:31:25.272268','false','true','false','false','false');
INSERT INTO annotations VALUES(4,2,2000,'2017-06-13 15:31:25.555555','false','false','false','false','false');
INSERT INTO aspinds VALUES(1,'advp_for',4,7,3);
INSERT INTO synargs VALUES(1,'subj',1,5,1);
INSERT INTO synargs VALUES(2,'subj',12,13,2);
INSERT INTO synargs VALUES(3,'subj',1,2,3);
INSERT INTO synargs VALUES(4,'obj',3,4,3);
INSERT INTO synargs VALUES(5,'subj',7,8,4);
INSERT INTO synargs VALUES(6,'subj',11,12,5);
COMMIT;


text:
@charset "utf-8";

/* fonts */
@import url(http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,400italic,700,700italic|Merriweather:400,700,400italic,700italic,300,300italic|Crimson+Text:400,400italic,600italic,600&subset=latin,latin-ext);

/* general style */
body    { font: 17px/25px 'Merriweather', serif;
          margin: 0; padding: 0; font-weight: 400; color: #c5c5c5;
          background: black}

a       { color: #398ad5; font-weight: 400; }
a:hover { color: #2771b5; }

/* headlines */
h1, h2, h3, h4, h5, h6      { font-family: 'Crimson Text', serif;
                              font-weight: 400; color: #2771b5; font-style: italic }
h1 a, h2 a, h3 a, h4 a,
h5 a, h6 a                  { text-decoration: none; }
h1 a:hover, h2 a:hover,
h3 a:hover, h4 a:hover      { text-decoration: underline; }
h1                          { margin: 15px 0 25px 0; }
h2                          { margin: 25px 0 10px 0; }
h3                          { margin: 35px 0 10px 0; }
h1                          { font-size: 52px; line-height: 56px; }
h2                          { font-size: 42px; line-height: 44px; }
h3                          { font-size: 36px; line-height: 38px; }

h1 em                       { color: #bdbdbd; font-size: 32px; display: block;
                              margin-left: 25px; margin-top: -15px; }

/* layout elements */
div.container               { max-width: 880px; margin: 48px auto; padding: 0 40px; }
div.header                  { float: left; }
div.navigation              { float: right; }
div.header, div.navigation  { height: 25px; margin-bottom: 42px; }
div.navigation ul           { margin: 0; padding: 0; list-style: none; }
div.navigation ul li        { display: inline; margin: 0 2px; padding: 0; }
div.body                    { clear: both; margin: 0 30px; line-height: 1.6; }
div.footer                  { margin-top: 55px; font-size: 16px;
                              text-align: right; color: #7b8894; }
div.footer p                { margin: 0; }
div.footer a                { color: #7b8894; }

/* margins and stuff */
p, div.line-block, ul, ol, pre,
    table                       { margin: 15px 0 15px 0; }
dt                              { margin: 25px 0 16px 0; padding: 0; }
dd                              { margin: 16px 0 25px 40px; padding: 0; }
ul ol, ol ul, ul ul, ol ol      { margin: 10px 0; padding: 0 0 0 40px; }
li                              { padding: 0; }
h1 + p.date                     { margin-top: -25px; font-style: italic; }
blockquote                      { font-style: italic; }

/* code formatting.  no monospace because of webkit (bug?) */
pre, code, tt   { font-family: 'Ubuntu Mono', 'Consolas', 'Deja Vu Sans Mono',
                  'Bitstream Vera Sans Mono', 'Monaco', 'Courier New';
                  font-size: 1.01em; }
pre             { line-height: 1.45; background: none; padding: 0; }
code, tt        { color: #8c3d0e; }

/* tables */
table           { border: 1px solid #ddd; border-collapse: collapse;
                  background: #f5f5f5; }
td, th          { padding: 2px 12px; border: 1px solid #ddd; }

/* footnotes */
table.footnote          { margin: 25px 0; background: transparent; border: none; }
table.footnote + table.footnote { margin-top: -35px; }
table.footnote td       { border: none; padding: 9px 0 0 0; font-size: 15px; }
table.footnote td.label { padding-right: 10px; }
table.footnote td p     { margin: 0; }
table.footnote td p + p { margin-top: 15px; }

/* blog overview */
div.entry-overview                  { margin: 25px 122px 25px 102px; }
div.entry-overview h1,
div.entry-overview div.summary,
div.entry-overview div.summary p    { display: inline; line-height: 25px; }
div.entry-overview h1               { margin: 0; font-size: 17px; font-weight: 700;
                                      font-family: 'Merriweather', serif; }
div.entry-overview h1:after         { content: " —"; color: #b1b1b1; }
div.entry-overview h1 a             { color: #2771b5; }
div.entry-overview div.summary,
div.entry-overview div.date,
div.entry-overview div.summary p    { margin: 0; padding: 0; }
div.entry-overview div.detail       { margin-left: 140px; }
div.entry-overview div.date         { float: left; width: 120px; color: #7b8894;
                                      text-align: right; font-style: italic;
                                      font-size: 14px; }

/* other alignment things */
img.align-center        { margin: 15px auto; display: block; }

/* pagination */
div.pagination          { margin: 36px 0 0 0; text-align: center; }
div.pagination strong   { font-weight: normal; font-style: italic; }

/* tags */
p.tags          { text-align: right; margin-top: 35px; }
ul.tagcloud     { font-size: 16px; margin: 36px 0; padding: 0;
                  list-style: none; line-height: 1.45; text-align: justify }
ul.tagcloud li  { margin: 0; padding: 0 10px; display: inline; }

/* latex math */
span.math img   { margin-bottom: -7px; }

/* ads */
div.adspace {
    text-align: center;
}

div.adspace iframe {
    margin: 25px auto 25px auto;
}


text:
package com.sap.tools.jpicus.impl.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import com.sap.tools.jpicus.Agent;
import com.sap.tools.jpicus.impl.serializable.Options;

public class Util {

	private static Executor exec = Executors.newSingleThreadExecutor();
	public static final String SEP = System.getProperty("line.separator");

	public static String getCannonical(Object path) {

		File file = null;

		if(path instanceof String){
			file = new File( (String)path);
		}

		if(path instanceof File){

			file = (File)path;
		}

		if(file != null){

			String cannonicalPath;

			try {
				cannonicalPath = file.getCanonicalPath();
			} catch (IOException e) {

				e.printStackTrace();
				// fall back to the method that does not throw an exception
				cannonicalPath = file.getAbsolutePath();
			}
			return cannonicalPath;

		}

		if(path instanceof FileDescriptor){
			FileDescriptor fd = (FileDescriptor)path;
			String result = fd.toString();
			return result;
		}

		throw new IllegalArgumentException("Unknown path type: " + path);

	}

	public static void executeAndWait(final Runnable r){
		final CountDownLatch countDown = new CountDownLatch(1);
		Runnable task = new Runnable(){

			public void run() {

				try {
					r.run();
				} finally{
					System.err.println("scheduled");
					countDown.countDown();
				}

			}
		};

		exec.execute(task);

		try {
			countDown.await();
		} catch (InterruptedException e) {

			e.printStackTrace();
			return;
		}

	}

	public static StackTraceElement [] cleanStackTrace(
			StackTraceElement[] stackTrace) {

		StackTraceElement [] result = new StackTraceElement[stackTrace.length -3];
		System.arraycopy(stackTrace, 3, result, 0, result.length);
		return result;

	}

	public static void stackTraceToString(StackTraceElement[] stackTrace, StringBuilder buf) {

		String sep = System.getProperty("line.separator");

		for (int i = 0; i < stackTrace.length; i++){
			StackTraceElement element = stackTrace[i];
			buf.append(sep + "\tat " + element.toString() );
		}

	}

	public static OSType getOSType(){

		String os = System.getProperty("os.name");
		if(os.contains("nux") || os.contains("nix") ){

			return OSType.NIX;
		}

		if(os.contains("laris")){
			return OSType.SOLARIS;
		}

		if(os.contains("indows")){
			return OSType.WINDOWS;
		}
		return OSType.UNKNOWN;
	}

	public static String getExternalOwners(String canonical) {

		// *nix systems normally have lsof
		if( OSType.WINDOWS != getOSType()){

//			try {
//				// TODO create synchronous process executor utility
//				Process p = Runtime.getRuntime().exec("lsof | grep " + canonical);
//				return null;
//			} catch (IOException e) {
//				e.printStackTrace();
//				return null;
//
//			}
		} else {
			// TODO windows
//			try {
//				Process p = Runtime.getRuntime().exec("handle.exe");
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			return null;
		}

		return null;
	}

	/**
	 * Iterate over the classes and for each of them
	 * 1.Find the all parents up to the limit
	 * 2.Add them to the result
	 * @param limit
	 * @param classes
	 */
	public static void addSuperClasses(Class<?> limit,	Set<Class<?>> classes) {

		Set<Class<?>> parents = new HashSet<Class<?>>(4);

		for(Class<?> cls:classes){
			// find all parents of this class until the limiting class is reached
			while(true){
				Class<?> parent = cls.getSuperclass();
				if(parent == null || parent.equals(limit)){
					break;
				}
				parents.add(parent);
				cls = parent;
			}
		}
		if(Options.getInstance().isVerbose()){
			System.out.println("Util.addSuperClasses(). Source= " + classes + ", parents=" + parents );
		}

		classes.addAll(parents);

	}

	/**
	 * Since the particular implementations of FileChannel are not known in
	 * advance, find out which are they
	 * @return
	 * @throws IOException
	 */
	public static Map<Class<?>,Set<Class<?>>> getNIOPrivateImplementationClasses() throws IOException {

		Map<Class<?>, Set<Class<?>>> result = new HashMap<Class<?>, Set<Class<?>>>(2);
		result.put(FileChannel.class, new HashSet<Class<?>>(4));
		result.put(MappedByteBuffer.class, new HashSet<Class<?>>(4));

		File file = new File(Agent.CALIBRATION_FILE);

		if(!file.exists()){
			file.createNewFile();
		}

		byte [] buf = new byte [4096];

		FileOutputStream fos = new FileOutputStream(file);

		result.get(FileChannel.class).add (fos.getChannel().getClass());
		// intentionally commented. There isn't a map mode corresponding to
		// FileOutputStream
		//		result.get(MappedByteBuffer.class).add(fos.getChannel().map(MapMode.PRIVATE, 0, buf.length).getClass());

		fos.write(buf);
		fos.close();

		FileInputStream fis = new FileInputStream(file);
		result.get(FileChannel.class).add(fis.getChannel().getClass());
		result.get(MappedByteBuffer.class).add(fis.getChannel().map(MapMode.READ_ONLY, 0, buf.length).getClass());
		fis.close();

		Map<String,MapMode> mapModes = new HashMap<String, MapMode>(4);
		mapModes.put("r", MapMode.READ_ONLY);
		mapModes.put("rw", MapMode.READ_WRITE);
		mapModes.put("rws", MapMode.PRIVATE);
		mapModes.put("rwd", MapMode.PRIVATE);

		for(String mode:mapModes.keySet()){
			RandomAccessFile raf = new RandomAccessFile(file, mode);
			result.get(FileChannel.class).add(raf.getChannel().getClass());

			result.get(MappedByteBuffer.class).add(raf.getChannel().map(mapModes.get(mode),0,buf.length).getClass());
			raf.close();

		}

		file.delete();

		addSuperClasses(FileChannel.class, result.get(FileChannel.class));
		addSuperClasses(MappedByteBuffer.class, result.get(MappedByteBuffer.class));

		if(Options.getInstance().isVerbose()){
			System.out.println("NIO private implementation classes: " + result);
		}

		return result;
	}

	public static byte[] getBytes(Class<?> clazz) throws IOException {

		String resourcePath = clazz.getName().replace('.', '/') + ".class";

//		System.out.println("Util.getBytes():" + resourcePath);
		ClassLoader loader = clazz.getClassLoader();
		InputStream in;

		if(loader == null){
			in = ClassLoader.getSystemResourceAsStream(resourcePath);
		} else {
			in = loader.getResourceAsStream(resourcePath);
		}

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte [] buf = new byte [100];
		while( true ){
			int len = in.read(buf);
			if(len < 0){
				break;
			}
			out.write(buf,0,len);
		}

		in.close();

		return out.toByteArray();

	}

}


text:
layout: post
title:  "More is coming"
date:   2015-02-15 14:34:25
categories:
tags: featured
image: /assets/images/night-track.jpg
---
Nothing here for now.

More is coming.


text:
'''
This module extends practical.Node to support external failure detection.
'''
from paxos import practical

from paxos.practical import ProposalID

class ExternalMessenger (practical.Messenger):

    def send_leadership_proclamation(self):
        '''
        Sends a leadership proclamation to all nodes
        '''

    def on_leadership_lost(self):
        '''
        Called when loss of leadership is detected
        '''

    def on_leadership_change(self, prev_leader_uid, new_leader_uid):
        '''
        Called when a change in leadership is detected. Either UID may
        be None.
        '''

class ExternalNode (practical.Node):
    '''
    This implementation is completely passive. An external entity must monitor peer nodes
    for failure and call prepare() when the node should attempt to acquire leadership
    of the Paxos instance. Continual polling of the prepare() function and prevention
    of eternal leadership battles is also the responsibility of the caller.

    When leadership is acquired, the node will broadcast a leadership proclamation,
    delcaring itself the leader of the instance. This relieves peer nodes of the
    responsibility of tracking promises for all prepare messages.
    '''

    def __init__(self, messenger, my_uid, quorum_size, leader_uid=None):

        super(ExternalNode, self).__init__(messenger, my_uid, quorum_size)

        self.leader_uid          = leader_uid
        self.leader_proposal_id  = ProposalID(1, leader_uid)
        self._nacks              = set()

        if self.node_uid == leader_uid:
            self.leader                = True
            self.proposal_id           = ProposalID(self.next_proposal_number, self.node_uid)
            self.next_proposal_number += 1

    def prepare(self, *args, **kwargs):
        self._nacks.clear()
        return super(ExternalNode, self).prepare(*args, **kwargs)

    def recv_leadership_proclamation(self, from_uid, proposal_id):
        if proposal_id > self.leader_proposal_id:
            old_leader_uid = self.leader_uid

            self.leader_uid         = from_uid
            self.leader_proposal_id = proposal_id

            self.observe_proposal( from_uid, proposal_id )

            if old_leader_uid == self.node_uid:
                self.messenger.on_leadership_lost()

            self.messenger.on_leadership_change( old_leader_uid, from_uid )

    def recv_promise(self, acceptor_uid, proposal_id, prev_proposal_id, prev_proposal_value):

        pre_leader = self.leader

        super(ExternalNode, self).recv_promise(acceptor_uid, proposal_id, prev_proposal_id, prev_proposal_value)

        if not pre_leader and self.leader:
            old_leader_uid = self.leader_uid

            self.leader_uid         = self.node_uid
            self.leader_proposal_id = self.proposal_id

            self.messenger.send_leadership_proclamation( proposal_id )

            self.messenger.on_leadership_change( old_leader_uid, self.node_uid )

    def recv_accept_nack(self, from_uid, proposal_id, promised_id):
        if proposal_id == self.proposal_id:
            self._nacks.add(from_uid)

        if self.leader and len(self._nacks) >= self.quorum_size:
            self.leader             = False
            self.promises_rcvd      = set()
            self.leader_uid         = None
            self.leader_proposal_id = None
            self.messenger.on_leadership_lost()
            self.messenger.on_leadership_change(self.node_uid, None)
            self.observe_proposal( from_uid, promised_id )


text:
package uk.ac.ed.learn9.bb.timetabling.data;

/**
 * Type-safe object for wrapping course codes as used in Learn. Used to help
 * differentiate from course codes in Timetabling.
 */
public class TimetablingCourseCode extends AbstractCourseCode<TimetablingCourseCode> {
    /**
     * A regular expression used to validate timetabling course codes.
     */
    public static final String TT_COURSE_CODE_REGEXP = "[A-Z]+[0-9]+_[A-Z][A-Z0-9]+_[A-Z][A-Z0-9\\+]+";

    /**
     * Constructs the timetabling course code with the given value.
     *
     * @param setValue the course code value.
     * @throws IllegalArgumentException if the course code is invalid.
     */
    public              TimetablingCourseCode(final String setValue) {
        super(setValue);

        if (!setValue.matches(TT_COURSE_CODE_REGEXP)) {
            throw new IllegalArgumentException("Course code \""
                + setValue + "\" is invalid; does not match expected format.");
        }
    }

    /**
     * Builds the course code for a course in Timetabling, based on the component parts
     * of the code.
     *
     * @param courseCode the course code for the course in general, for example "PLIT08005".
     * @param occurrence the occurrence of the course, for example "SV1".
     * @param semester the semester the course is running in, for example "SEM1".
     * @return the course code as used in timetabling.
     * @throws IllegalArgumentException if the resulting course code is invalid.
     */
    public static TimetablingCourseCode buildCode(final String courseCode,
            final String occurrence, final String semester)
            throws IllegalArgumentException {
        assert null != courseCode;
        assert null != occurrence;
        assert null != semester;

        return new TimetablingCourseCode(courseCode + "_"
            + occurrence + "_"
            + semester);
    }
}