text:
require 'redisse'
require 'goliath/api'
require 'rack/accept_media_types'
require 'goliath/runner'
require 'em-hiredis'

module Redisse

  # Public: Run the server.
  #
  # If you use the provided binary you don't need to call this method.
  #
  # By default, the {#channels} method is called directly.
  #
  # If {#nginx_internal_url} is set, the channels will actually come from the
  # internal redirect URL generated in the Rack app by {#redirect_endpoint}.
  def run
    run_as_standalone if nginx_internal_url
    server = Server.new(self)
    runner = Goliath::Runner.new(ARGV, server)
    runner.app = Goliath::Rack::Builder.build(self, server)
    runner.load_plugins([Server::Stats] + plugins)
    runner.run
  end

private

  # Internal: Redefine {#channels} to find channels in the redirect URL.
  def run_as_standalone
    channels do |env|
      query_string = env['QUERY_STRING'] || ''
      channels = query_string.split('&').map { |channel|
        URI.decode_www_form_component(channel)
      }
      channels.delete('polling')
      channels.delete_if {|channel| channel.start_with?('lastEventId=') }
    end
  end

  # Internal: Goliath::API class that defines the server.
  #
  # See {Redisse#run}.
  class Server < Goliath::API
    require 'redisse/server/stats'
    include Stats::Endpoint
    require 'redisse/server/responses'
    include Responses
    require 'redisse/server/redis'
    include Redis

    # Public: Delay between receiving a message and closing the connection.
    #
    # Closing the connection is necessary when using long polling, because the
    # client is not able to read the data before the connection is closed. But
    # instead of closing immediately, we delay a bit closing the connection to
    # give a chance for several messages to be sent in a row.
    LONG_POLLING_DELAY = 1

    # Public: The period between heartbeats in seconds.
    HEARTBEAT_PERIOD = 15

    def initialize(redisse)
      @redisse = redisse
      super()
    end

    def response(env)
      return server_stats(env) if server_stats?(env)
      return not_acceptable unless acceptable?(env)
      channels = Array(redisse.channels(env))
      return not_found if channels.empty?
      subscribe(env, channels) or return service_unavailable
      history_events(env, channels)
      heartbeat(env)
      streaming_response(200, {
        'Content-Type' => 'text/event-stream',
        'Cache-Control' => 'no-cache',
        'X-Accel-Buffering' => 'no',
      })
    end

    def on_close(env)
      unsubscribe(env)
      stop_heartbeat(env)
    end

  private

    attr_reader :redisse

    def subscribe(env, channels)
      return unless pubsub { env.stream_close }
      env.status[:stats][:connected] += 1
      env.logger.debug { "Subscribing to #{channels}" }
      env_sender = -> event { send_event(env, event) }
      pubsub_subcribe(channels, env_sender)
      env['redisse.unsubscribe'.freeze] = -> do
        pubsub_unsubscribe_proc(channels, env_sender)
      end
      true
    end

    def heartbeat(env)
      env['redisse.heartbeat_timer'.freeze] = EM.add_periodic_timer(HEARTBEAT_PERIOD) do
        env.logger.debug "Sending heartbeat".freeze
        env.stream_send(": hb\n".freeze)
      end
    end

    def stop_heartbeat(env)
      return unless timer = env['redisse.heartbeat_timer'.freeze]
      env.logger.debug "Stopping heartbeat".freeze
      timer.cancel
    end

    def unsubscribe(env)
      return unless unsubscribe = env['redisse.unsubscribe'.freeze]
      env['redisse.unsubscribe'.freeze] = nil
      env.logger.debug "Unsubscribing".freeze
      env.status[:stats][:connected] -= 1
      env.status[:stats][:served]    += 1
      unsubscribe.call
    end

    def send_event(env, event, polling = long_polling?(env))
      env.status[:stats][:events] += 1
      env.logger.debug { "Sending:\n#{event.chomp.chomp}" }
      env.stream_send(event)
      return unless polling
      env["redisse.long_polling_timer".freeze] ||= EM.add_timer(LONG_POLLING_DELAY) do
        env.stream_close
      end
    end

    def long_polling?(env)
      key = "redisse.long_polling".freeze
      env.fetch(key) do
        env[key] = Rack::Request.new(env).GET.keys.include?('polling')
      end
    end

    def history_events(env, channels)
      EM::Synchrony.next_tick do
        send_history_events(env, channels)
      end
    end

    def send_history_events(env, channels)
      last_event_id = last_event_id(env)
      events = events_for_channels(channels, last_event_id) if last_event_id
      first = events.first if events
      id = redis_last_event_id unless first
      send_event(env, LAST_EVENT_ID_EVENT % id, false) if id
      return unless first
      if first.start_with?('event: missedevents')
        env.status[:stats][:missing] += 1
      end
      env.logger.debug { "Sending #{events.size} history events" }
      events.each { |event| send_event(env, event) }
    end

    LAST_EVENT_ID_EVENT = ServerSentEvents.server_sent_event(nil,
      type: :lastEventId, id: '%s').freeze

    def redis_last_event_id
      df = redis.get(RedisPublisher::REDISSE_LAST_EVENT_ID)
      EM::Synchrony.sync(df)
    end

    def last_event_id(env)
      last_event_id = env['HTTP_LAST_EVENT_ID'.freeze] ||
        Rack::Request.new(env).GET['lastEventId'.freeze]
      last_event_id = last_event_id.to_i
      last_event_id.nonzero? && last_event_id
    end

    def events_for_channels(channels, last_event_id)
      events_with_ids = channels.each_with_object([]) { |channel, events|
        channel_events = events_for_channel(channel, last_event_id)
        events.concat(channel_events)
      }.sort_by!(&:last)
      handle_missing_events(events_with_ids, last_event_id)
      events_with_ids.map(&:first)
    end

    def handle_missing_events(events_with_ids, last_event_id)
      first_event, first_event_id = events_with_ids.first
      return unless first_event
      if first_event_id == last_event_id
        events_with_ids.shift
      else
        event = ServerSentEvents.server_sent_event(nil, type: :missedevents)
        events_with_ids.unshift([event])
      end
    end

    def events_for_channel(channel, last_event_id)
      df = redis.zrangebyscore(channel, last_event_id, '+inf', 'withscores')
      events_scores = EM::Synchrony.sync(df)
      events_scores.each_slice(2).map do |event, score|
        [event, score.to_i]
      end
    end

    def acceptable?(env)
      accept_media_types(env).include? 'text/event-stream'
    end

    def accept_media_types(env)
      key = 'accept_media_types'.freeze
      env.fetch(key) do
        env[key] = Rack::AcceptMediaTypes.new(env['HTTP_ACCEPT'])
      end
    end

  public

    def options_parser(opts, options)
      opts.on '--redis REDIS_URL', 'URL of the Redis connection' do |url|
        redisse.redis_server = url
      end
      default_port = redisse.default_port
      return unless default_port
      options[:port] = default_port
    end

  end
end


text:
package com.multipathp.pprogram.ast;

import com.multipathp.pprogram.types.IPTypeGetItemable;
import com.multipathp.pprogram.types.PType;
import com.multipathp.pprogram.types.PTypeSeq;
import org.inferred.freebuilder.FreeBuilder;

/**
 * Created by jianqiaoyang on 5/29/17.
 */
@FreeBuilder
public abstract class GetItemExp extends Exp {
    public abstract Exp getTargetExpression();
    public abstract Exp getIndexerExpression();

    @Override
    public PType getExpressionType() {
        return ((IPTypeGetItemable) getTargetExpression().getExpressionType()).getIndexedInnerType();
    }

    @Override
    public int getChildrenCount() {
        return 2;
    }

    @Override
    public PASTNode getChild(int i) {
        switch (i) {
            case 0: return getTargetExpression();
            case 1: return getIndexerExpression();
            default: throw new IndexOutOfBoundsException();
        }
    }

    @Override
    public <T> T accept(PASTVisitor<T> visitor) {
        return visitor.visit(this);
    }

    public static class Builder extends GetItemExp_Builder {

    }
}

redpajama_set_name: RedPajamaGithub


text:
module RCons
  # The version of RCons
  VERSION = '0.0.1'
end


text:
package com.kanven.schedual.transport.client.api;

import com.kanven.schedual.transport.client.PoolConfig;

public interface Client<C> extends Sender<C> {

	void setConfig(PoolConfig config);

	/**
	 * 服务是否关闭
	 *
	 * @return
	 */
	boolean isClosed();

	/**
	 * 关闭服务
	 */
	void close();

}


text:
/**
 * @description
 *
 * A humpback-view created at Mon Sep 28 2015 10:41:40 GMT-0400 (EDT).
 */

angular.module( 'humpback.views.AdminWebhook.states', [

])
.config(function config( $stateProvider, $urlRouterProvider) {
	$stateProvider
		.state( 'admin.webhook', {
			url: '/webhook?skip?sort?limit?criteria?page',
			reloadOnSearch: false,
			ncyBreadcrumb: {
          		label: 'Webhook Management'
        	},
			views: {
				"admin": {
					controller: 'AdminWebhookCtrl',
					templateUrl: 'app/views/admin/webhook/index.html'
				}
			}
		})
		;
});


text:
/*****************************************************
 * ±¾Àà¿âµÄºËÐÄϵ AderTemplates
 * (C) Andrew Deren 2004
 * http://www.adersoftware.com
 *****************************************************/

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace SiteGroupCms.TEngine.Parser.AST
{
    public class BinaryExpression : Expression
    {
        Expression lhs;
        Expression rhs;

        TokenKind op;

        public BinaryExpression(int line, int col, Expression lhs, TokenKind op, Expression rhs)
            : base(line, col)
        {
            this.lhs = lhs;
            this.rhs = rhs;
            this.op = op;
        }

        public Expression Lhs
        {
            get { return this.lhs; }
        }

        public Expression Rhs
        {
            get { return this.rhs; }
        }

        public TokenKind Operator
        {
            get { return this.op; }
        }

    }
}


text:
"""
**Site Checker with Time Scheduling** - An application that attempts to connect to a website or server every so many minutes or a given time and check if it is up. If it is down, it will notify you by email or by posting a notice on screen.
"""

import os,time
print("Look up every hour if a site is up.")
hostname = raw_input("Please enter the website you want to look up in the derp.com format. >> ") #example
response = os.system("ping -c 1 " + hostname)

while True:
    if response == 0:
      print hostname, 'is up!'
    else:
      print hostname, 'is down!'
    time.sleep(3600)


text:
require 'spec_helper'
require 'omniauth/strategies/headquarters'

module OmniAuth
  module Strategies
    describe Headquarters do
      let(:request) { double('Request', params: {}, cookies: {}, env: {}) }

      subject do
        args = ['appid', 'secret', @options || {}].compact
        OmniAuth::Strategies::Headquarters.new(*args).tap do |strategy|
          allow(strategy).to receive(:request) {
            request
          }
        end
      end

      describe 'client options' do
        it 'should have correct name' do
          expect(subject.options.name).to eq(:headquarters)
        end

        it 'should have correct site' do
          expect(subject.options.client_options.site).to eq('https://hq.subvisual.co')
        end
      end
    end
  end
end


text:
// Copyright 2013 Room77 Inc. All Rights Reserved.
// Author: pramodg@room77.com (Pramod Gupta)

#ifndef _META_SUGGEST_COMMON_RANKERS_SUGGEST_COMPARATOR_H_
#define _META_SUGGEST_COMMON_RANKERS_SUGGEST_COMPARATOR_H_

#include <functional>

#include "base/common.h"
#include "meta/suggest/common/suggest_datatypes.h"

namespace suggest {
namespace rank {

// The basic comparator for completions based on score.
struct greater_score : std::binary_function <Completion, Completion, bool> {
  bool operator() (const Completion& left, const Completion& right) const {
    if (left.score != right.score) return left.score > right.score;

    // Break ties (arbitrarily) based on the src type. This ensures the order to be stable.
    return left.suggestion->src_type < right.suggestion->src_type;
  }
};

// The main comparator used to rank completions.
struct better_completion : greater_score {
  typedef greater_score super;
  bool operator() (const Completion& left, const Completion& right) const {
    /* For now we simply compute by score. All other static fixing is severely error prone.
     * It would be great if we can keep it this way.
     *
     * Old Comments:
    // The basic logic we follow here is as follows:
    // 1. Prefix suggestions are always ranked above everything except
    //    (child suggestions). i.e. if one is a prefix and other is a child
    //    they are compared based on the score or other parameters.
    int prefix_algo_comp = bitwise_diff(left.algo_type, right.algo_type,
                                        kCompletionAlgoTypePrefix);

    if (prefix_algo_comp != 0) {
      int child_comp = child_diff(left, right);
      if (!(prefix_algo_comp * child_comp < 0))
        return prefix_algo_comp > 0 ? true : false;
    }*/

    return super::operator()(left, right);
  }

 private:
  // Returns the bitwise diff for the algo type.
  // The values are:
  //   +ve: If left has 'bit' set and right does not.
  //   -ve: If right has 'bit' set and left does not.
  //   0: Both left and right have same value for 'bit' (either set or unset).
  int bitwise_diff(SugggestionAlgoType left, SugggestionAlgoType right,
                   SugggestionAlgoType bit) const {
    return (left & bit) - (right & bit);
  }

  // Returns the diff based on whether one is child or not.
  // The values are:
  //   +ve: If left is a child but right is not.
  //   -ve: If right is child but left is not.
  //   0: If right and left are either both chidren or none of them are.
  int child_diff(const Completion& left, const Completion& right) const {
    return (left.parent_id.empty() ? 0 : 1) - (right.parent_id.empty() ? 0 : 1);
  }
};

}  // namespace rank
}  // namespace suggest

#endif  // _META_SUGGEST_COMMON_RANKERS_SUGGEST_COMPARATOR_H_


text:
package com.amazonaws.services.amplify.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.amplify.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CustomRuleMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CustomRuleMarshaller {

    private static final MarshallingInfo<String> SOURCE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("source").build();
    private static final MarshallingInfo<String> TARGET_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("target").build();
    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("status").build();
    private static final MarshallingInfo<String> CONDITION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("condition").build();

    private static final CustomRuleMarshaller instance = new CustomRuleMarshaller();

    public static CustomRuleMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CustomRule customRule, ProtocolMarshaller protocolMarshaller) {

        if (customRule == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(customRule.getSource(), SOURCE_BINDING);
            protocolMarshaller.marshall(customRule.getTarget(), TARGET_BINDING);
            protocolMarshaller.marshall(customRule.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(customRule.getCondition(), CONDITION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
/* eslint-env mocha */
import { assert } from 'chai';
import { create as createJss } from 'jss';
import DomRenderer from 'jss/lib/backends/DomRenderer';
import preset from 'jss-preset-default';
import { createStyleManager, createStyleSheet } from 'src';

describe('theme update', () => {
  let themeObj;
  let themeObjNew;
  let styleManager;
  let styleSheet;

  before(() => {
    themeObj = {
      fontFamily: 'Roboto',
      fontSize: 12,
      color: 'red',
    };
    themeObjNew = {
      fontFamily: 'Arial',
      fontSize: 14,
      color: 'blue',
    };
    styleManager = createStyleManager({
      jss: createJss(preset()),
      theme: themeObj,
    });
    styleSheet = createStyleSheet('button', (theme) => ({
      root: {
        color: theme.color,
        fontSize: theme.fontSize,
        fontFamily: theme.fontFamily,
      },
    }), { Renderer: DomRenderer });
  });

  afterEach(() => {
    styleManager.reset();
  });

  it('should start with no stylesheets in the DOM', () => {
    const styleElements = document.querySelectorAll('style');
    assert.strictEqual(styleElements.length, 0, 'should have no style tags');
  });

  describe('rendering to the DOM', () => {
    let styleElement;

    beforeEach(() => {
      styleManager.render(styleSheet);
    });

    it('should render the stylesheet to the DOM', () => {
      const styleElements = document.querySelectorAll('style');
      assert.strictEqual(styleElements.length, 1, 'should have 1 style tag');
      styleElement = styleElements[0];

      assert.strictEqual(
        styleElement.getAttribute('data-meta'),
        `button-${themeObj.id}`,
        'should have the stylesheet name as the data-meta attribute',
      );

      const { style } = styleElement.sheet.cssRules[0];

      assert.strictEqual(style.color, themeObj.color);
      assert.strictEqual(style['font-size'], `${themeObj.fontSize}px`);
      assert.strictEqual(style['font-family'], themeObj.fontFamily);
    });

    it('should change theme', () => {
      styleManager.updateTheme(themeObjNew);
      const styleElements = document.querySelectorAll('style');
      assert.strictEqual(styleElements.length, 1, 'should have 1 style tag');
      styleElement = styleElements[0];

      assert.strictEqual(
        styleElement.getAttribute('data-meta'),
        `button-${themeObjNew.id}`,
        'should have the stylesheet name as the data-meta attribute',
      );

      const { style } = styleElement.sheet.cssRules[0];

      assert.strictEqual(style.color, themeObjNew.color);
      assert.strictEqual(style['font-size'], `${themeObjNew.fontSize}px`);
      assert.strictEqual(style['font-family'], themeObjNew.fontFamily);
    });

    it('should change theme twice', () => {
      styleManager.updateTheme(themeObjNew);
      styleManager.updateTheme(themeObj);
      const styleElements = document.querySelectorAll('style');
      assert.strictEqual(styleElements.length, 1, 'should have 1 style tag');
      styleElement = styleElements[0];

      assert.strictEqual(
        styleElement.getAttribute('data-meta'),
        `button-${themeObj.id}`,
        'should have the stylesheet name as the data-meta attribute',
      );

      const { style } = styleElement.sheet.cssRules[0];

      assert.strictEqual(style.color, themeObj.color);
      assert.strictEqual(style['font-size'], `${themeObj.fontSize}px`);
      assert.strictEqual(style['font-family'], themeObj.fontFamily);
    });
  });
});


text:
from .prodigy import upload_dataset

__all__ = ["upload_dataset"]


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="MavenProjectsManager">
    <option name="originalFiles">
      <list>
        <option value="$PROJECT_DIR$/pom.xml" />
      </list>
    </option>
  </component>
  <component name="ProjectRootManager" version="2" assert-keyword="false" jdk-15="false" />
</project>


text:
class AddNameToWishes < ActiveRecord::Migration
  def change
    add_column :wishes, :name, :string, default: " "
  end
end


text:
package org.ardverk.enums;

/**
 * An interface for {@link Enum}'s that provide an alternative value
 * of themselves.
 *
 * @see PrimitiveEnum.Int
 */
public interface PrimitiveEnum {

  /**
   * An {@link PrimitiveEnum} that is backed by {@code int} values.
   */
  public static interface Int extends PrimitiveEnum {

    /**
     * Returns the {@link Enum}'s alternative {@code int} value.
     */
    public int convert();
  }
}


text:
title: "About me"
template: "page"
socialImage: "/photo.jpg"
---

I am a single dad living with my boys in Kuala Lumpur.

I created this blog for quite a while ago to capture and share my thoughts on mainly programming and software. I would
consider myself to be lucky to be able to work on something on my interest since I was a kid. It's pretty much working
with computers: coding, system architecture, building great products and more importantly, People.
There is less impact on working with computers alone, but if you're not dealing with people. It feels great to work on
something that has positive impact for people.

I enjoy planning (most of it adhoc planning) for weekend getaways with my boys. And to my boys, if you're reading this,
I'd treasure all the memories spend with you guys since you're still babies. I hope that when you grow older we can
watch all the videos and photos that we took together on our adventures!

Life isn't easy for the past few years, and I have been focusing on different parts of life. I honestly feel like sharing
my life learning, experiences with dealing with people and legal stuff. Maybe some other day I will... I really feel that
people should know a bit about legal and your rights, so to ensure that people do not take advantage of your lack of
knowledge. I aim to write some thoughts on this, maybe a bit later. When things settle down a bit...


text:
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Common.Configuration
{
    public class Config
    {
        private static IConfigurationRoot _configuration;

        private static IConfigurationRoot Configuration
        {
            get
            {
                return _configuration ??
                    (_configuration = ConfigBuilder());
            }
        }

        private static IConfigurationRoot ConfigBuilder()
        {
            var directoryString = Directory.GetCurrentDirectory();

            var builder = new ConfigurationBuilder()
                .SetBasePath(String.Format("{0}{1}", directoryString, "/Config/"))
                .AddJsonFile("appsettings.config");

            return builder.Build();
        }

        public static string Get(string key)
        {
            return Configuration[key];
        }

        public static string GetConnectionString()
        {
            return Configuration["connectionstring"];
        }

        public static byte[] GetSecretKey()
        {
            var key = Convert.FromBase64String(Configuration["SecretKeyBase64"]);
            return key;
        }
    }
}


text:
SRCS += index.html manifest.webapp LICENSE js/app.js js/WISPr.js style/* img/icons/*.png

all:
	zip -r package.zip $(SRCS)

clean:
	rm package.zip


text:
<?php

    Yii::import('core.widgets.TWidget');
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */

    class TMarkdownEditor extends TWidget {

        public $content;

        /**
         * 帮助model
         */
        public $model;
        public $scriptFile = array(
            'markdown/codemirror-2.34/lib/codemirror.js',
            'markdown/codemirror-2.34/lib/util/overlay.js',
            'markdown/codemirror-2.34/mode/xml/xml.js',
            'markdown/codemirror-2.34/mode/markdown/markdown.js',
            'markdown/codemirror-2.34/mode/gfm/gfm.js',
            'markdown/codemirror-2.34/mode/javascript/javascript.js',
            'markdown/marked/marked.js',
            'markdown/highlight.js/highlight.pack.js',
            'markdown/app.js',
        );
        public $cssFile = array(
            'markdown/vendor/normalize.css',
            'markdown/vendor/bootstrap.min.css',
            'markdown/codemirror-custom.css',
            'markdown/github-style.css',
            'markdown/vendor/styles/github.css',
            'markdown/style.css',
        );

        public function init() {
            parent::init();
            if (isset($model)) {
                $this->model = $model;
            }
        }

        public function run() {
            parent::run();
            $this->renderHeader();
            $this->renderSection();
        }

        public function renderHeader() {
            echo CHtml::openTag('header', array('id' => 'header'));
            echo CHtml::openTag('div', array('class' => 'navbar navbar-fixed-top'));
            echo CHtml::openTag('div', array('class' => 'navbar-inner'));
            echo CHtml::openTag('a', array('class' => 'brand', 'style' => 'font-size:14px;margin-top:5px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'));
            echo $this->model->getAttributeLabel('title');
            echo CHtml::textField('title', $this->model->title, array('style' => 'margin-left:36px;margin-bottom:0px;'));
            echo CHtml::closeTag('a');
            echo CHtml::openTag('a', array('class' => 'brand', 'style' => 'font-size:14px;margin-top:5px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'));
            echo $this->model->getAttributeLabel('main_id') . '        ';
            $this->widget('core.widgets.TTreeDropdown', array(
                'treeId' => 'main_id',
                'data' => HelpCategory::getHelpTree(),
                'options' => array(
                    'view' => array(
                        'showLine' => false,
                        'showIcon' => true,
                    )
                ),
                'defaultText' => $this->model->main->name ? $this->model->main->name : '未分类',
                'selectNode' => $this->model->main_id ? $this->model->main_id : ''
            ));
            echo CHtml::closeTag('a');

            //置顶
            echo CHtml::openTag('a', array('class' => 'brand', 'style' => 'font-size:14px;margin-top:5px;margin-right:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'));
            echo CHtml::checkBox('top', $checked = $this->model->top ? true : false, array('style' => 'margin-left:36px;margin-bottom:0px;margin-right:0px'));
            echo CHtml::closeTag('a');
            echo CHtml::openTag('a', array('class' => 'brand', 'style' => 'font-size:14px;margin-top:8px;margin-left:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'));
            echo $this->model->getAttributeLabel('top');
            echo CHtml::closeTag('a');

            $this->controller->widget('bootstrap.widgets.TbButton', array(
                'label' => '关闭',
                'type' => 'primary',
                'htmlOptions' => array(
                    'class' => 'pull-right',
                    'style' => 'margin-left:6px;',
                    'id' => 'btnCancel'
                )
            ));
            $this->controller->widget('bootstrap.widgets.TbButton', array(
                'label' => '保存',
                'type' => 'danger',
                'htmlOptions' => array(
                    'style' => 'margin-left:6px;',
                    'class' => 'pull-right',
                    'id' => 'btnSave'
                )
            ));
            $this->controller->widget('bootstrap.widgets.TbButton', array(
                'label' => '预览',
                'htmlOptions' => array(
                    'class' => 'pull-right',
                    'id' => 'btnPrev'
                )
            ));
            echo CHtml::closeTag('div');
            echo CHtml::closeTag('div');
            echo CHtml::closeTag('header');
        }

        public function renderSection() {
            echo CHtml::openTag('section', array('id' => 'main'));
            echo CHtml::tag('textarea', array('id' => 'in'), $this->model->content);
            echo CHtml::tag('div', array('id' => 'out', 'class' => 'markdown-body'), '');
            echo CHtml::closeTag('section');
            echo CHtml::hiddenField('help_id', $this->model->id);
        }

    }

?>


text:
from django.db import migrations, models

DEMOTE_STREAMS_AUTOMATIC = 1
class Migration(migrations.Migration):

    dependencies = [
        ('zerver', '0227_inline_url_embed_preview_default_off'),
    ]

    operations = [
        migrations.AddField(
            model_name='userprofile',
            name='demote_inactive_streams',
            field=models.PositiveSmallIntegerField(default=DEMOTE_STREAMS_AUTOMATIC),
        ),
    ]


text:
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>

#include "cr.h"
#include "libpill.h"
#include "ip.h"
#include "poller.h"
#include "stack.h"
#include "utils.h"
#include "worker.h"
#include "waitgroup.h"
#include "timer.h"

void *(*mill_realloc_func)(void *ptr, size_t size) = realloc;

__thread mill_t *mill = NULL;

volatile __thread int mill_unoptimisable1 = 1;
volatile __thread void *mill_unoptimisable2 = NULL;

static void *mill_getvalbuf(struct mill_cr *cr) {
    if(mill_fast(cr != &mill->main)) {
        return (void*)(((char*)cr) - mill->valbuf_size);
    }
    return (void*)mill->main_valbuf;
}

int mill_suspend(void) {
    /* Even if process never gets idle, we have to process external events
       once in a while. The external signal may very well be a deadline or
       a user-issued command that cancels the CPU intensive operation. */
    struct mill_cr *mill_running = mill->running;

    if(mill->counter >= 103) {
        mill_wait(0);
        mill->counter = 0;
    }
    if(mill_running && mill_running->suspend_hook)
        mill_running->suspend_hook(mill_running->cls, 0);
    /* Store the context of the current coroutine, if any. */
    if(mill_running && sigsetjmp(mill_running->ctx, 0))
        return mill_running->result;
    while(1) {
        /* If there's a coroutine ready to be executed go for it. */
        if(!mill_slist_empty(&mill->ready)) {
            ++mill->counter;
            struct mill_slist_item *it = mill_slist_pop(&mill->ready);
            mill->running = mill_running = mill_cont(it, struct mill_cr, ready);
            mill_running->state = 0;
            if(mill_slow(mill_running->resume_hook))
                mill_running->resume_hook(mill_running->cls);
            siglongjmp(mill_running->ctx, 1);
        }
        /* Otherwise, we are going to wait for sleeping coroutines
           and for external events. */
        mill_wait(1);
        /* XXX: not true, See mill_task_timedout() in task.c.
         mill_assert(!mill_slist_empty(&mill->ready)); */
        mill->counter = 0;
    }
}

void mill_resume(struct mill_cr *cr, int result) {
    mill_assert(cr->state != MILL_READY);
    cr->result = result;
    cr->state = MILL_READY;
    mill_slist_push_back(&mill->ready, &cr->ready);
}

void *mill_allocstack(void) {
    if(!mill_slist_empty(&mill->cached_stacks)) {
        --mill->num_cached_stacks;
        return (void*)(mill_slist_pop(&mill->cached_stacks) + 1);
    }
    return mill_allocstackmem();
}

sigjmp_buf *mill_getctx(void) {
    return &mill->running->ctx;
}

/* The intial part of go(). Starts the new coroutine.
   Returns the pointer to the top of its stack. */
void *mill_go_prologue(void *stackmem) {
    mill_assert(mill != NULL);
    /* Allocate and initialise new stack. */
    struct mill_cr *cr = stackmem;
    if(!cr) {
        cr = mill_allocstack();
        if(!cr)
            mill_panic("not enough memory to allocate coroutine stack");
    }
    cr = cr - 1;
    mill_list_insert(&mill->all_crs, &cr->item, NULL);
    cr->cls = NULL;
    cr->resume_hook = NULL;
    cr->suspend_hook = NULL;
    cr->wg = NULL;
    cr->state = 0;
    memset(&cr->timer, '\0', sizeof (struct mill_timer));
    cr->mfd = NULL;
    mill_slist_set_detached(&cr->ready);
    mill_list_set_detached(&cr->wgitem);
    mill->num_cr++;
    /* Suspend the parent coroutine and make the new one running. */
    if(mill_slow(mill->running->suspend_hook))
        mill->running->suspend_hook(mill->running->cls, 0);
    mill_resume(mill->running, 0);
    mill->running = cr;
    /* Return pointer to the top of the stack. There's valbuf interposed
       between the mill_cr structure and the stack itself. */
    return (void*)(((char*)cr) - mill->valbuf_size);
}

/* The final part of go(). Cleans up after the coroutine is finished. */
void mill_go_epilogue(void) {
    struct mill_cr *mill_running = mill->running;
    if(mill_running->suspend_hook)
        mill_running->suspend_hook(mill_running->cls, 1);
    if(mill_slow(mill_running->wg)) {
        mill_wgroup_rm(mill_running);
    }

    mill_list_erase(&mill->all_crs, &mill_running->item);

    /* Make sure coroutine timer isn't in the min-heap */
    mill_timer_cancel(&mill_running->timer);

    mill_freestack(mill_running + 1);
    mill->num_cr--;
    mill->running = NULL;
    if(mill_slow(mill->do_waitall && mill->num_cr == 0)) {
        struct mill_cr *cr = &mill->main;
        mill_assert(mill->num_tasks == 0);
        mill->do_waitall = 0;
        if(mill_timer_enabled(&cr->timer))
            mill_timer_rm(&cr->timer);
        mill_resume(cr, 0);
    }

    /* Given that there's no running coroutine at this point
       this call will never return. */
    mill_suspend();
}

void mill_yield(void) {
    /* This looks fishy, but yes, we can resume the coroutine even before
       suspending it. */
    mill_resume(mill->running, 0);
    mill_suspend();
}

int iscrmain(void) {
    mill_assert(mill != NULL);
    return (mill->running == &mill->main);
}

void *mill_valbuf(struct mill_cr *cr, size_t size) {
    assert(size <= 128);
    return mill_getvalbuf(cr);
}

void mill_sethook(void *data,
        void (*resume_hook)(void *), void (*suspend_hook)(void *, int)) {
    mill->running->cls = data;
    mill->running->resume_hook = resume_hook;
    mill->running->suspend_hook = suspend_hook;
}

/* default stack size */
#define MILL_STACK_SIZE (64 * 1024)

mill_t *mill_init__p(int stacksize) {
    mill = mill_malloc(sizeof (mill_t));
    if(!mill) {
        errno = ENOMEM;
        return NULL;
    }
    memset(mill, '\0', sizeof (mill_t));
    mill->task_fd[0] = mill->task_fd[1] = -1;   /* not used in worker threads */

    if(-1 == mill_timers_init()) {
        mill_free(mill);
        return NULL;
    }
    struct mill_cr *mill_main = & mill->main;
    memset(&mill_main->timer, '\0', sizeof (struct mill_timer));
    mill_main->mfd = NULL;
    mill_main->state = 0;
    mill->valbuf_size = 128;
    mill->all_crs.first = &mill_main->item;
    mill->all_crs.last = &mill_main->item;
    mill->running = mill_main;

    mill_dns_init();
    mill_poller_init();
    if(errno) {
        mill_free(mill);
        mill = NULL;
    }
    if(stacksize < 0)
        stacksize = MILL_STACK_SIZE;
    mill->stack_size = mill_get_stack_size(stacksize);
    return mill;
}

void *mill_init(int stacksize, int nworkers) {
    if(mill_init__p(stacksize))
        init_workers(nworkers);
    return mill;
}

void mill_fini(void) {
    if(mill) {
        mill_waitall(-1);
        close_task_fds();
        mill_poller_fini();
        mill_purgestacks();
        mill_timers_fini();
        mill_free(mill);
        mill = NULL;
    }
}

/* returns number of coroutines excluding main */
int gocount(void) {
    return mill->num_cr;
}

int taskcount(void) {
    return mill->num_tasks;
}

void mill_panic(const char *text) {
    fprintf(stderr, "panic: %s\n", text);
    abort();
}


text:
package name.atsushieno.midi;

public interface IMidiPlayerStatus
{
	PlayerState getState();
	int getTempo();
	int getPlayDeltaTime();
	int getTotalPlayTimeMilliseconds();
}


text:
/*
    nanogui/button.h -- [Normal/Toggle/Radio/Popup] Button widget

    NanoGUI was developed by Wenzel Jakob <wenzel.jakob@epfl.ch>.
    The widget drawing code is based on the NanoVG demo application
    by Mikko Mononen.

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE.txt file.
*/
/** \file */

#pragma once

#include <nanogui/widget.h>

NAMESPACE_BEGIN(nanogui)
/**
 * \class Button button.h nanogui/button.h
 *
 * \brief [Normal/Toggle/Radio/Popup] Button widget.
 */
class NANOGUI_EXPORT Button : public Widget {
public:
    /// Flags to specify the button behavior (can be combined with binary OR)
    enum Flags {
        NormalButton = (1 << 0), // 1
        RadioButton  = (1 << 1), // 2
        ToggleButton = (1 << 2), // 4
        PopupButton  = (1 << 3)  // 8
    };

    /// The available icon positions.
    enum class IconPosition {
        Left,
        LeftCentered,
        RightCentered,
        Right
    };

    Button(Widget *parent, const std::string &caption = "Untitled", int icon = 0);

    const std::string &caption() const { return mCaption; }
    void setCaption(const std::string &caption) { mCaption = caption; }

    const Color &backgroundColor() const { return mBackgroundColor; }
    void setBackgroundColor(const Color &backgroundColor) { mBackgroundColor = backgroundColor; }

    const Color &textColor() const { return mTextColor; }
    void setTextColor(const Color &textColor) { mTextColor = textColor; }

    int icon() const { return mIcon; }
    void setIcon(int icon) { mIcon = icon; }

    int flags() const { return mFlags; }
    void setFlags(int buttonFlags) { mFlags = buttonFlags; }

    IconPosition iconPosition() const { return mIconPosition; }
    void setIconPosition(IconPosition iconPosition) { mIconPosition = iconPosition; }

    bool pushed() const { return mPushed; }
    void setPushed(bool pushed) { mPushed = pushed; }

    /// Set the push callback (for any type of button)
    std::function<void()> callback() const { return mCallback; }
    void setCallback(const std::function<void()> &callback) { mCallback = callback; }

    /// Set the change callback (for toggle buttons)
    std::function<void(bool)> changeCallback() const { return mChangeCallback; }
    void setChangeCallback(const std::function<void(bool)> &callback) { mChangeCallback = callback; }

    /// Set the button group (for radio buttons)
    void setButtonGroup(const std::vector<Button *> &buttonGroup) { mButtonGroup = buttonGroup; }
    const std::vector<Button *> &buttonGroup() const { return mButtonGroup; }

    virtual Vector2i preferredSize(NVGcontext *ctx) const override;
    virtual bool mouseButtonEvent(const Vector2i &p, int button, bool down, int modifiers) override;
    virtual void draw(NVGcontext *ctx) override;

    virtual void save(Serializer &s) const override;
    virtual bool load(Serializer &s) override;
protected:
    std::string mCaption;
    int mIcon;
    IconPosition mIconPosition;
    bool mPushed;
    int mFlags;
    Color mBackgroundColor;
    Color mTextColor;
    std::function<void()> mCallback;
    std::function<void(bool)> mChangeCallback;
    std::vector<Button *> mButtonGroup;
public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

NAMESPACE_END(nanogui)


text:
#ifndef RF12_h
#define RF12_h

#include <stdint.h>
#include "wirish.h"  //
// version 1 did not include the group code in the crc
// version 2 does include the group code in the crc
#define RF12_VERSION    2

#define rf12_grp        rf12_buf[0]
#define rf12_hdr        rf12_buf[1]
#define rf12_len        rf12_buf[2]
#define rf12_data       (rf12_buf + 3)

#define RF12_HDR_CTL    0x80
#define RF12_HDR_DST    0x40
#define RF12_HDR_ACK    0x20
#define RF12_HDR_MASK   0x1F

#define RF12_MAXDATA    66

#define RF12_433MHZ     1
#define RF12_868MHZ     2
#define RF12_915MHZ     3

// EEPROM address range used by the rf12_config() code
#define RF12_EEPROM_ADDR ((uint8_t*) 0x20)
#define RF12_EEPROM_SIZE 32
#define RF12_EEPROM_EKEY (RF12_EEPROM_ADDR + RF12_EEPROM_SIZE)
#define RF12_EEPROM_ELEN 16

// shorthand to simplify sending out the proper ACK when requested
#define RF12_WANTS_ACK ((rf12_hdr & RF12_HDR_ACK) && !(rf12_hdr & RF12_HDR_CTL))
#define RF12_ACK_REPLY (rf12_hdr & RF12_HDR_DST ? RF12_HDR_CTL : \
            RF12_HDR_CTL | RF12_HDR_DST | (rf12_hdr & RF12_HDR_MASK))

// options fro RF12_sleep()
#define RF12_SLEEP 0
#define RF12_WAKEUP -1

//define spi ports //currently a bit of a hack
//#define HARDWARESPIPORT 1 //the connected hardware spi port.

extern volatile uint16_t rf12_crc;  // running crc value, should be zero at end
extern volatile uint8_t rf12_buf[]; // recv/xmit buf including hdr & crc bytes
//TODO: try to debug reception
extern volatile uint16_t rf12_statusbuf[]; // recv/xmit buf including hdr & crc bytes
extern long rf12_seq;               // seq number of encrypted packet (or -1)

extern volatile int testvar; // a debugging variable

   //lets try use the hardware spi class, a bit of a hack
//HardwareSPI myspi(HARDWARESPIPORT);
//spi.begin(SPI_1_125MHZ,MSBFIRST,0); //ok must keep below 2.25Mhz therefore lests start at 1.125Mhz.  It is also big endian (MSBFIRST) and mode 0, ie data on first clock pulse

// call this once with the node ID, frequency band, and optional group
void rf12_initialize(uint8_t id, uint8_t band, uint8_t group=0xD4);

// initialize the RF12 module from settings stored in EEPROM by "RF12demo"
// don't call rf12_initialize() if you init the hardware with rf12_config()
// returns the node ID as 1..31 value (1..26 correspond to nodes 'A'..'Z')
uint8_t rf12_config(uint8_t show =1);

// call this frequently, returns true if a packet has been received
uint8_t rf12_recvDone(void);

// call this to check whether a new transmission can be started
// returns true when a new transmission may be started with rf12_sendStart()
uint8_t rf12_canSend(void);

// call this only when rf12_recvDone() or rf12_canSend() return true
void rf12_sendStart(uint8_t hdr);
void rf12_sendStart(uint8_t hdr, const void* ptr, uint8_t len);
// deprecated: use rf12_sendStart(hdr,ptr,len) followed by rf12_sendWait(sync)
void rf12_sendStart(uint8_t hdr, const void* ptr, uint8_t len, uint8_t sync);

/// This variant loops on rf12_canSend() and then calls rf12_sendStart() asap.
void rf12_sendNow(uint8_t hdr, const void* ptr, uint8_t len);

// wait for send to finish, sleep mode: 0=none, 1=idle, 2=standby, 3=powerdown
void rf12_sendWait (uint8_t mode);

// this simulates OOK by turning the transmitter on and off via SPI commands
// use this only when the radio was initialized with a fake zero node ID
void rf12_onOff(uint8_t value);

// power off the RF12, ms > 0 sets watchdog to wake up again after N * 32 ms
// note: once off, calling this with -1 can be used to bring the RF12 back up
void rf12_sleep(char n);

// returns true of the supply voltage is below 3.1V
char rf12_lowbat(void);

// set up the easy tranmission mode, arg is number of seconds between packets
void rf12_easyInit(uint8_t secs);

// call this often to keep the easy transmission mode going
char rf12_easyPoll(void);

// send new data using the easy transmission mode, buffer gets copied to driver
char rf12_easySend(const void* data, uint8_t size);

// enable encryption (null arg disables it again)
//~ void rf12_encrypt(const uint8_t*);

// low-level control of the RFM12B via direct register access
uint16_t rf12_control(uint16_t cmd);

//void rf12_interrupt(void);

// crc16 used for jeenode communication, and configuration storage
uint16_t _crc16_update(uint16_t crc, uint8_t a);

#endif


text: /path-to-electron/electron /path-to-repo/app-dev


text:
package org.onosproject.bgpio.types;

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

import org.junit.Test;

import com.google.common.testing.EqualsTester;

/**
 * Test for As4Path BGP Path Attribute.
 */
public class As4PathTest {
    //Two scenarios as4path set and sequence
    private final List<Integer> as4pathSet1 = new ArrayList<>();
    private final List<Integer> as4pathSeq1 = new ArrayList<>();
    private final List<Integer> as4pathSet2 = new ArrayList<>();
    private final List<Integer> as4pathSeq2 = new ArrayList<>();
    private final As4Path attr1 = new As4Path(as4pathSet1, null);
    private final As4Path sameAsAttr1 = new As4Path(as4pathSet1, null);
    private final As4Path attr2 = new As4Path(as4pathSet2, null);
    private final As4Path attr3 = new As4Path(null, as4pathSeq1);
    private final As4Path sameAsAttr3 = new As4Path(null, as4pathSeq1);
    private final As4Path attr4 = new As4Path(null, as4pathSeq2);

    @Test
    public void basics() {
        as4pathSet1.add(197358);
        as4pathSet1.add(12883);
        as4pathSet2.add(2008989);
        as4pathSeq1.add(3009009);
        as4pathSeq2.add(409900);
        new EqualsTester()
        .addEqualityGroup(attr1, sameAsAttr1)
        .addEqualityGroup(attr2)
        .addEqualityGroup(attr3, sameAsAttr3)
        .addEqualityGroup(attr4)
        .testEquals();
    }
}


text:
"use strict";

/* @ngInject */
function AddParticipantController($stateParams, $modalInstance, Participants, Expenses) {
  var model = this;

  model.participant = {email: "", share: 1};

  model.add = add;
  model.cancel = cancel;

  activate();

  function add(participant) {
    delete model.errors;
    model.loading = true;
    return Participants.add($stateParams.id, participant)
      .then(function (data) {
        participant.id = data.id;
        $modalInstance.close(participant);
      })
      .catch(function (errors) {
        model.errors = errors;
      })
      .finally(function () {
        model.loading = false;
      });
  }

  function cancel() {
    $modalInstance.close(null);
  }

  function activate() {
    model.activation = Expenses.metadata($stateParams.id).then(function (data) {
      model.expensesMetadata = data;
    });
  }
}

Object.defineProperty(AddParticipantController.prototype,
  "hasExpenses", {
    enumerable: true,
    configurable: false,
    get: function () {
      return this.expensesMetadata && this.expensesMetadata.length > 0;
    }
  }
);

module.exports = AddParticipantController;


text:
describe Cask::Artifact::Artifact, :cask do
  let(:cask) { Cask::CaskLoader.load(cask_path("with-generic-artifact")) }

  let(:install_phase) {
    lambda do
      cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
        artifact.install_phase(command: NeverSudoSystemCommand, force: false)
      end
    end
  }

  let(:source_path) { cask.staged_path.join("Caffeine.app") }
  let(:target_path) { cask.config.appdir.join("Caffeine.app") }

  before do
    InstallHelper.install_without_artifacts(cask)
  end

  context "without target" do
    it "fails to load" do
      expect {
        Cask::CaskLoader.load(cask_path("invalid/invalid-generic-artifact-no-target"))
      }.to raise_error(Cask::CaskInvalidError, /target required for Generic Artifact/)
    end
  end

  it "moves the artifact to the proper directory" do
    install_phase.call

    expect(target_path).to be_a_directory
    expect(source_path).to be_a_symlink
  end

  it "avoids clobbering an existing artifact" do
    target_path.mkpath

    expect {
      install_phase.call
    }.to raise_error(Cask::CaskError)

    expect(source_path).to be_a_directory
    expect(target_path).to be_a_directory
    expect(File.identical?(source_path, target_path)).to be false
  end
end


text:
<?php

defined('_JEXEC') or die;

// Include the component HTML helpers.
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html');

JHtml::_('bootstrap.tooltip');
JHtml::_('behavior.multiselect');
JHtml::_('formbehavior.chosen', 'select');

$user		= JFactory::getUser();
$listOrder	= $this->escape($this->state->get('list.ordering'));
$listDirn	= $this->escape($this->state->get('list.direction'));
$canOrder	= $user->authorise('core.edit.state',	'com_plugins');
$saveOrder	= $listOrder == 'ordering';
if ($saveOrder)
{
	$saveOrderingUrl = 'index.php?option=com_plugins&task=plugins.saveOrderAjax&tmpl=component';
	JHtml::_('sortablelist.sortable', 'articleList', 'adminForm', strtolower($listDirn), $saveOrderingUrl);
}
$sortFields = $this->getSortFields();
?>

<form action="<?php echo JRoute::_('index.php?option=com_plugins&view=plugins'); ?>" method="post" name="adminForm" id="adminForm">
<?php if (!empty( $this->sidebar)) : ?>

		<?php echo $this->sidebar; ?>

<?php else : ?>

<?php endif;?>

				<?php echo JText::_('COM_CONTENT_FILTER_SEARCH_DESC');?>
				<input type="text" name="filter_search" id="filter_search" placeholder="<?php echo JText::_('JSEARCH_FILTER'); ?>" value="<?php echo $this->escape($this->state->get('filter.search')); ?>" class="hasTooltip" title="<?php echo JHtml::tooltipText('COM_PLUGINS_SEARCH_IN_TITLE'); ?>" />

				<button type="submit" class="btn hasTooltip" title="<?php echo JHtml::tooltipText('JSEARCH_FILTER_SUBMIT'); ?>"></button>
				<button type="button" class="btn hasTooltip" title="<?php echo JHtml::tooltipText('JSEARCH_FILTER_CLEAR'); ?>" onclick="document.id('filter_search').value='';this.form.submit();"></button>

				<?php echo JText::_('JFIELD_PLG_SEARCH_SEARCHLIMIT_DESC');?>
				<?php echo $this->pagination->getLimitBox(); ?>

				<?php echo JText::_('JFIELD_ORDERING_DESC');?>
				<select name="directionTable" id="directionTable" class="input-medium" onchange="Joomla.orderTable()">
					<option value=""><?php echo JText::_('JFIELD_ORDERING_DESC');?></option>
					<option value="asc" <?php if ($listDirn == 'asc') echo 'selected="selected"'; ?>><?php echo JText::_('JGLOBAL_ORDER_ASCENDING');?></option>
					<option value="desc" <?php if ($listDirn == 'desc') echo 'selected="selected"'; ?>><?php echo JText::_('JGLOBAL_ORDER_DESCENDING');?></option>
				</select>

				<?php echo JText::_('JGLOBAL_SORT_BY');?>
				<select name="sortTable" id="sortTable" class="input-medium" onchange="Joomla.orderTable()">
					<option value=""><?php echo JText::_('JGLOBAL_SORT_BY');?></option>
					<?php echo JHtml::_('select.options', $sortFields, 'value', 'text', $listOrder);?>
				</select>

						<?php echo JHtml::_('grid.sort', '', 'ordering', $listDirn, $listOrder, null, 'asc', 'JGRID_HEADING_ORDERING'); ?>

						<?php echo JHtml::_('grid.checkall'); ?>

						<?php echo JHtml::_('grid.sort', 'JSTATUS', 'enabled', $listDirn, $listOrder); ?>

						<?php echo JHtml::_('grid.sort', 'COM_PLUGINS_NAME_HEADING', 'name', $listDirn, $listOrder); ?>

						<?php echo JHtml::_('grid.sort', 'COM_PLUGINS_FOLDER_HEADING', 'folder', $listDirn, $listOrder); ?>

						<?php echo JHtml::_('grid.sort', 'COM_PLUGINS_ELEMENT_HEADING', 'element', $listDirn, $listOrder); ?>

						<?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ACCESS', 'access', $listDirn, $listOrder); ?>

						<?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ID', 'extension_id', $listDirn, $listOrder); ?>

						<?php echo $this->pagination->getListFooter(); ?>

			<?php foreach ($this->items as $i => $item) :
				$ordering   = ($listOrder == 'ordering');
				$canEdit    = $user->authorise('core.edit',       'com_plugins');
				$canCheckin = $user->authorise('core.manage',     'com_checkin') || $item->checked_out == $user->get('id') || $item->checked_out == 0;
				$canChange  = $user->authorise('core.edit.state', 'com_plugins') && $canCheckin;
				?>
				<tr class="row<?php echo $i % 2; ?>" sortable-group-id="<?php echo $item->folder?>">

						<?php
						$iconClass = '';
						if (!$canChange)
						{
							$iconClass = ' inactive';
						}
						elseif (!$saveOrder)
						{
							$iconClass = ' inactive tip-top hasTooltip" title="' . JHtml::tooltipText('JORDERINGDISABLED');
						}
						?>
						<span class="sortable-handler<?php echo $iconClass ?>">

						<?php if ($canChange && $saveOrder) : ?>
							<input type="text" style="display:none" name="order[]" size="5" value="<?php echo $item->ordering;?>" class="width-20 text-area-order " />
						<?php endif; ?>

						<?php echo JHtml::_('grid.id', $i, $item->extension_id); ?>

						<?php echo JHtml::_('jgrid.published', $item->enabled, $i, 'plugins.', $canChange); ?>

						<?php if ($item->checked_out) : ?>
							<?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'plugins.', $canCheckin); ?>
						<?php endif; ?>
						<?php if ($canEdit) : ?>
							<a href="<?php echo JRoute::_('index.php?option=com_plugins&task=plugin.edit&extension_id='.(int) $item->extension_id); ?>">
								<?php echo $item->name; ?>
						<?php else : ?>
								<?php echo $item->name; ?>
						<?php endif; ?>

						<?php echo $this->escape($item->folder);?>

						<?php echo $this->escape($item->element);?>

						<?php echo $this->escape($item->access_level); ?>

						<?php echo (int) $item->extension_id;?>

			<?php endforeach; ?>

		<input type="hidden" name="task" value="" />
		<input type="hidden" name="boxchecked" value="0" />
		<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" />
		<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" />
		<?php echo JHtml::_('form.token'); ?>

</form>


text:
layout: post
title: Polyglot 1.2.0
lang: en
---

A new version of Polyglot has been released! Give it a try!

{% highlight yaml %}
gem install jekyll-polyglot
{% endhighlight %}

and list `jekyll-polyglot` among your listed gems in your `_config.yml`

It involves mostly groundwork to prepare for new features and better multilingual content management. It does have a new feature:

## {% raw %} {% I18n_Headers %} {% endraw %}

Put this tag with the [url of your website](https://github.com/untra/polyglot/blob/site/_includes/head.html#L6) in your `head.html` includes file to get the maximum SEO provided by having a multilingual website. It's the same as the following liquid code:

{% highlight html %}{% raw %}
<meta http-equiv="Content-Language" content="{{site.active_lang}}">
<link rel="alternate"
      hreflang="{{site.default_lang}}"
      href="http://yoursite.com{{page.permalink}}" />
{% for lang in site.languages %}
{% if lang == site.default_lang %}
  {% continue %}
{% endif %}
<link rel="alternate"
    hreflang="{{lang}}"
    href="http://yoursite.com/{{lang}}{{page.permalink}}" />
{% endfor %}
{% endraw %}
{% endhighlight %}

In your header, but faster and cleaner! For more information, see [the SEO page](/seo)


text:
class FieldTest
  include Mongoid::Document
  include Mongoid::Paperclip
  include ActiveModel::ForbiddenAttributesProtection
  extend Dragonfly::Model

  field :name, type: String
  field :title, type: String
  field :subject, type: String
  field :short_text, type: String

  field :array_field, type: Array
  field :big_decimal_field, type: BigDecimal
  field :boolean_field, type: Boolean
  field :bson_object_id_field, type: RailsAdmin::Adapters::Mongoid::ObjectId
  field :bson_binary_field, type: BSON::Binary
  field :date_field, type: Date
  field :datetime_field, type: DateTime
  field :time_with_zone_field, type: ActiveSupport::TimeWithZone
  field :default_field
  field :float_field, type: Float
  field :hash_field, type: Hash
  field :integer_field, type: Integer
  field :object_field, type: Object
  field :range_field, type: Range
  field :string_field, type: String
  field :symbol_field, type: Symbol
  field :text_field, type: String
  field :time_field, type: Time

  field :format, type: String
  field :restricted_field, type: String
  field :protected_field, type: String
  has_mongoid_attached_file :paperclip_asset, styles: {thumb: '100x100>'}

  has_many :nested_field_tests, dependent: :destroy, inverse_of: :field_test, autosave: true
  accepts_nested_attributes_for :nested_field_tests, allow_destroy: true

  # on creation, comment is not saved without autosave: true
  has_one :comment, as: :commentable, autosave: true
  accepts_nested_attributes_for :comment, allow_destroy: true

  embeds_many :embeds
  accepts_nested_attributes_for :embeds, allow_destroy: true

  attr_accessor :delete_paperclip_asset
  before_validation { self.paperclip_asset = nil if delete_paperclip_asset == '1' }

  field :dragonfly_asset_name
  field :dragonfly_asset_uid
  dragonfly_accessor :dragonfly_asset
  mount_uploader :carrierwave_asset, CarrierwaveUploader

  validates :short_text, length: {maximum: 255}
end


text:
Semantic Tile API client library.

Serves vector tiles containing geospatial data.

## Installation

Install this package from [Hex](https://hex.pm) by adding
`google_api_vector_tile` to your list of dependencies in `mix.exs`:

```elixir
def deps do
  [{:google_api_vector_tile, "~> 0.5"}]
end
```

## For more information

Product documentation is available at [https://developers.google.com/maps/contact-sales/](https://developers.google.com/maps/contact-sales/).

Library reference documentation is published on Hexdocs at
[https://hexdocs.pm/google_api_vector_tile](https://hexdocs.pm/google_api_vector_tile).


text:
#include "JavaInputStreamAdaptor.h"
#include "SkPostConfig.h"

static jclass findClassCheck(JNIEnv* env, const char classname[]) {
    jclass clazz = env->FindClass(classname);
    SkASSERT(!env->ExceptionCheck());
    return clazz;
}

static jmethodID getMethodIDCheck(JNIEnv* env, jclass clazz,
                                  const char methodname[], const char type[]) {
    jmethodID id = env->GetMethodID(clazz, methodname, type);
    SkASSERT(!env->ExceptionCheck());
    return id;
}

static jmethodID    gInputStream_readMethodID;
static jmethodID    gInputStream_skipMethodID;

static JNIEnv* get_env_or_die(JavaVM* jvm) {
    JNIEnv* env;
    if (jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
        char errorMessage[256];
        sprintf(errorMessage, "Failed to get JNIEnv for JavaVM: %p", jvm);
        SK_ABORT(errorMessage);
    }
    return env;
}

/**
 *  Wrapper for a Java InputStream.
 */
class JavaInputStreamAdaptor : public SkStream {
    JavaInputStreamAdaptor(JavaVM* jvm, jobject js, jbyteArray ar, jint capacity,
                           bool swallowExceptions)
            : fJvm(jvm)
            , fJavaInputStream(js)
            , fJavaByteArray(ar)
            , fCapacity(capacity)
            , fBytesRead(0)
            , fIsAtEnd(false)
            , fSwallowExceptions(swallowExceptions) {}

public:
    static JavaInputStreamAdaptor* Create(JNIEnv* env, jobject js, jbyteArray ar,
                                          bool swallowExceptions) {
        JavaVM* jvm;
        if (env->GetJavaVM(&jvm) != JNI_OK) {
            SK_ABORT("Failed to get JavaVM");
        }

        js = env->NewGlobalRef(js);
        if (!js) {
            return nullptr;
        }

        ar = (jbyteArray) env->NewGlobalRef(ar);
        if (!ar) {
            env->DeleteGlobalRef(js);
            return nullptr;
        }

        jint capacity = env->GetArrayLength(ar);
        return new JavaInputStreamAdaptor(jvm, js, ar, capacity, swallowExceptions);
    }

    ~JavaInputStreamAdaptor() override {
        auto* env = get_env_or_die(fJvm);
        env->DeleteGlobalRef(fJavaInputStream);
        env->DeleteGlobalRef(fJavaByteArray);
    }

    size_t read(void* buffer, size_t size) override {
        auto* env = get_env_or_die(fJvm);
        if (!fSwallowExceptions && checkException(env)) {
            // Just in case the caller did not clear from a previous exception.
            return 0;
        }
        if (NULL == buffer) {
            if (0 == size) {
                return 0;
            } else {
                /*  InputStream.skip(n) can return <=0 but still not be at EOF
                    If we see that value, we need to call read(), which will
                    block if waiting for more data, or return -1 at EOF
                 */
                size_t amountSkipped = 0;
                do {
                    size_t amount = this->doSkip(size - amountSkipped, env);
                    if (0 == amount) {
                        char tmp;
                        amount = this->doRead(&tmp, 1, env);
                        if (0 == amount) {
                            // if read returned 0, we're at EOF
                            fIsAtEnd = true;
                            break;
                        }
                    }
                    amountSkipped += amount;
                } while (amountSkipped < size);
                return amountSkipped;
            }
        }
        return this->doRead(buffer, size, env);
    }

    bool isAtEnd() const override { return fIsAtEnd; }

private:
    size_t doRead(void* buffer, size_t size, JNIEnv* env) {
        size_t bytesRead = 0;
        // read the bytes
        do {
            jint requested = 0;
            if (size > static_cast<size_t>(fCapacity)) {
                requested = fCapacity;
            } else {
                // This is safe because requested is clamped to (jint)
                // fCapacity.
                requested = static_cast<jint>(size);
            }

            jint n = env->CallIntMethod(fJavaInputStream,
                                        gInputStream_readMethodID, fJavaByteArray, 0, requested);
            if (checkException(env)) {
                SkDebugf("---- read threw an exception\n");
                return bytesRead;
            }

            if (n < 0) { // n == 0 should not be possible, see InputStream read() specifications.
                fIsAtEnd = true;
                break;  // eof
            }

            env->GetByteArrayRegion(fJavaByteArray, 0, n,
                                    reinterpret_cast<jbyte*>(buffer));
            if (checkException(env)) {
                SkDebugf("---- read:GetByteArrayRegion threw an exception\n");
                return bytesRead;
            }

            buffer = (void*)((char*)buffer + n);
            bytesRead += n;
            size -= n;
            fBytesRead += n;
        } while (size != 0);

        return bytesRead;
    }

    size_t doSkip(size_t size, JNIEnv* env) {
        jlong skipped = env->CallLongMethod(fJavaInputStream,
                                            gInputStream_skipMethodID, (jlong)size);
        if (checkException(env)) {
            SkDebugf("------- skip threw an exception\n");
            return 0;
        }
        if (skipped < 0) {
            skipped = 0;
        }

        return (size_t)skipped;
    }

    bool checkException(JNIEnv* env) {
        if (!env->ExceptionCheck()) {
            return false;
        }

        env->ExceptionDescribe();
        if (fSwallowExceptions) {
            env->ExceptionClear();
        }

        // There is no way to recover from the error, so consider the stream
        // to be at the end.
        fIsAtEnd = true;

        return true;
    }

    JavaVM*     fJvm;
    jobject     fJavaInputStream;
    jbyteArray  fJavaByteArray;
    const jint  fCapacity;
    size_t      fBytesRead;
    bool        fIsAtEnd;
    const bool  fSwallowExceptions;
};

static SkStream* CreateJavaInputStreamAdaptor(JNIEnv* env, jobject stream, jbyteArray storage,
                                       bool swallowExceptions = true) {
    return JavaInputStreamAdaptor::Create(env, stream, storage, swallowExceptions);
}

static SkMemoryStream* adaptor_to_mem_stream(SkStream* stream) {
    SkASSERT(stream != NULL);
    size_t bufferSize = 4096;
    size_t streamLen = 0;
    size_t len;
    char* data = (char*)sk_malloc_throw(bufferSize);

    while ((len = stream->read(data + streamLen,
                               bufferSize - streamLen)) != 0) {
        streamLen += len;
        if (streamLen == bufferSize) {
            bufferSize *= 2;
            data = (char*)sk_realloc_throw(data, bufferSize);
        }
    }
    data = (char*)sk_realloc_throw(data, streamLen);

    SkMemoryStream* streamMem = new SkMemoryStream();
    streamMem->setMemoryOwned(data, streamLen);
    return streamMem;
}

SkStreamRewindable* CopyJavaInputStream(JNIEnv* env, jobject stream,
                                        jbyteArray storage) {
    std::unique_ptr<SkStream> adaptor(CreateJavaInputStreamAdaptor(env, stream, storage));
    if (NULL == adaptor.get()) {
        return NULL;
    }
    return adaptor_to_mem_stream(adaptor.get());
}

extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return -1;
    }

    jclass inputStream_Clazz = findClassCheck(env, "java/io/InputStream");
    gInputStream_readMethodID = getMethodIDCheck(env, inputStream_Clazz, "read", "([BII)I");
    gInputStream_skipMethodID = getMethodIDCheck(env, inputStream_Clazz, "skip", "(J)J");

    return JNI_VERSION_1_6;
}


text:
SOURCES = main.c

APPMOD = App

PROJDIR = $(CURDIR)
ifndef MOSROOT
  MOSROOT = $(PROJDIR)/../../../..
endif

include ${MOSROOT}/mos/make/Makefile


text:
namespace extractor {

class MockRuleExtractor : public RuleExtractor {
 public:
  MOCK_CONST_METHOD2(ExtractRules, vector<Rule>(const Phrase&,
      const PhraseLocation&));
};

} // namespace extractor


text:
Points to the path where the web static and views folders are located.
Default value: `../../web`


text:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import permission_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib import messages
from django.db.models import Q
from django.utils.translation import ugettext as _

from wagtail.wagtailadmin.forms import SearchForm
from wagtail.wagtailusers.forms import UserCreationForm, UserEditForm

User = get_user_model()

@permission_required('auth.change_user')
def index(request):
    q = None
    p = request.GET.get("p", 1)
    is_searching = False

    if 'q' in request.GET:
        form = SearchForm(request.GET, placeholder=_("Search users"))
        if form.is_valid():
            q = form.cleaned_data['q']

            is_searching = True
            users = User.objects.filter(Q(username__icontains=q) | Q(first_name__icontains=q) | Q(last_name__icontains=q) | Q(email__icontains=q))
    else:
        form = SearchForm(placeholder=_("Search users"))

    if not is_searching:
        users = User.objects

    users = users.order_by('last_name', 'first_name')

    if 'ordering' in request.GET:
        ordering = request.GET['ordering']

        if ordering in ['name', 'username']:
            if ordering != 'name':
                users = users.order_by(ordering)
    else:
        ordering = 'name'

    paginator = Paginator(users, 20)

    try:
        users = paginator.page(p)
    except PageNotAnInteger:
        users = paginator.page(1)
    except EmptyPage:
        users = paginator.page(paginator.num_pages)

    if request.is_ajax():
        return render(request, "wagtailusers/results.html", {
            'users': users,
            'is_searching': is_searching,
            'query_string': q,
            'ordering': ordering,
        })
    else:
        return render(request, "wagtailusers/index.html", {
            'search_form': form,
            'users': users,
            'is_searching': is_searching,
            'ordering': ordering,
            'query_string': q,
        })

@permission_required('auth.change_user')
def create(request):
    if request.POST:
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, _("User '{0}' created.").format(user))
            return redirect('wagtailusers_index')
        else:
            messages.error(request, _("The user could not be created due to errors.") )
    else:
        form = UserCreationForm()

    return render(request, 'wagtailusers/create.html', {
        'form': form,
    })

@permission_required('auth.change_user')
def edit(request, user_id):
    user = get_object_or_404(User, id=user_id)
    if request.POST:
        form = UserEditForm(request.POST, instance=user)
        if form.is_valid():
            user = form.save()
            messages.success(request, _("User '{0}' updated.").format(user))
            return redirect('wagtailusers_index')
        else:
            messages.error(request, _("The user could not be saved due to errors."))
    else:
        form = UserEditForm(instance=user)

    return render(request, 'wagtailusers/edit.html', {
        'user': user,
        'form': form,
    })


text:
import React from 'react'
import { render } from 'react-dom'

import App from './components/App'

import 'normalize.css'
import 'font-awesome/css/font-awesome.min.css'
import 'roboto-fontface/css/roboto/roboto-fontface.css'
import './index.css'

render(
  <App />,
  document.getElementById('root')
)


text:
package net.tiger.star.nsen.service;

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

import javax.annotation.Generated;
import javax.annotation.Resource;

import net.tiger.star.nsen.dto.UserDataDto;
import net.tiger.star.nsen.entity.AbstractBaseEntity;

import org.seasar.extension.jdbc.Where;

/**
 * サービスの抽象クラスです。
 *
 * @param <ENTITY>
 *            エンティティの型
 */
@Generated(value = {"S2JDBC-Gen 2.4.45", "org.seasar.extension.jdbc.gen.internal.model.AbstServiceModelFactoryImpl"}, date = "2013/04/05 16:56:14")
public abstract class AbstractService<ENTITY extends AbstractBaseEntity> extends AbstractBaseService<ENTITY> {

    @Resource
    protected UserDataDto userDataDto;

    /**
    *
    */
   @Override
   protected void setEntityClass(Class<ENTITY> entityClass) {
         this.entityClass = entityClass;
         sqlFilePathPrefix = "";
   }
    /**
     * エンティティを挿入します。
     *
     * @param entity
     *            エンティティ
     * @return 更新した行数
     */
    @Override
    public int insert(ENTITY entity) {
        setRegistFootterData(entity);
        return super.insert(entity);
    }

    /**
     * エンティティを更新します。
     *
     * @param entity
     *            エンティティ
     * @return 更新した行数
     */
    @Override
    public int update(ENTITY entity) {
        setUpdateFootterData(entity);
        return jdbcManager.update(entity).execute();
    }

    /**
     * フッター情報をセットしてNull項目以外を更新する
     * @return
     */
    public int updateExcludesNull(ENTITY entity) {
        setUpdateFootterData(entity);
        return jdbcManager
                .update(entity)
                .excludesNull()
                .execute();
    }

    /**
     * エンティティのリストを一括で登録する
     * @param list エンティティリスト
     * @return 登録した行数
     */
    public int[] insertBatch(List<ENTITY>list) {
        if (list == null || list.isEmpty()) {
            return new int[0];
        } else {
            return jdbcManager.insertBatch(getRegistFootterDataList(list)).execute();
        }
    }

    /**
     * エンティティのリストを一括で登録する
     * フッター情報はつけない
     * @param list エンティティリスト
     * @return 登録した行数
     */
    public int[] insertBatchNonFooter(List<ENTITY>list) {
        if (list == null || list.isEmpty()) {
            return new int[0];
        } else {
            return jdbcManager.insertBatch(list).execute();
        }
    }

    /**
     * エンティティのリストを一括で更新する
     * @param list エンティティリスト
     * @return 更新した行数
     */
    public int[] updateBatch(List<ENTITY>list) {
        if (list == null || list.isEmpty()) {
            return new int[0];
        } else {
            return jdbcManager.updateBatch(getUpdateFootterDataList(list)).execute();
        }
    }

    /**
     * エンティティのリストを一括で更新する
     * @param list エンティティリスト
     * @return 更新した行数
     */
    public int[] updateExcludesNullBatch(List<ENTITY>list) {
        if (list == null || list.isEmpty()) {
            return new int[0];
        } else {
            int[]ret = new int[list.size()];

            for(int i = 0; i < ret.length ; i++) {
                ret[i] = updateExcludesNull(list.get(i));
            }
            return ret;
        }
    }

    /**
     * テーブル共通のフッター情報をセットしたエンティティリストを取得する
     * 更新日時 更新者ID
     * @return エンティティのリスト
     */
    protected List<ENTITY> getUpdateFootterDataList(List<ENTITY>list) {
        List<ENTITY> ret = new ArrayList<ENTITY>();
        for(ENTITY row : list) {
            setUpdateFootterData(row);
            ret.add(row);
        }
        return ret;
    }

    /**
     * テーブル共通のフッター情報をセットしたエンティティリストを取得する
     * 登録日時 登録者ID
     * @return エンティティのリスト
     */
    protected List<ENTITY> getRegistFootterDataList(List<ENTITY>list) {
        List<ENTITY> ret = new ArrayList<ENTITY>();
        for(ENTITY row : list) {
            setRegistFootterData(row);
            ret.add(row);
        }
        return ret;
    }

    /**
     * Where区を指定して削除を行う
     * @param simpleWhere
     * @return 削除件数
     */
    protected int deleteWhere(final Where simpleWhere) {
        int ret = 0;
        // 検索を実行して削除
        for (ENTITY t : select().where(simpleWhere).getResultList()) {
            delete(t);
            ret++;
        }
        return ret;
    }

    @Override
    public String getUserName() {
        try {
            return userDataDto.nsenUser.userId.toString();
        } catch(Exception e) {
            return "";
        }
    }
}


text:
/* pinmux_dev_k64.c - Pinmux dev driver for Freescale K64 */

/*
 * Copyright (c) 2016 Intel Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <device.h>
#include <init.h>
#include <kernel.h>
#include <pinmux.h>
#include <soc.h>
#include <sys_io.h>
#include <pinmux/k64/pinmux.h>

static int fsl_k64_dev_set(struct device *dev, uint32_t pin,
				uint32_t func)
{
	ARG_UNUSED(dev);

	return _fsl_k64_set_pin(pin, func);
}

static int fsl_k64_dev_get(struct device *dev, uint32_t pin,
				uint32_t *func)
{
	ARG_UNUSED(dev);

	return _fsl_k64_get_pin(pin, func);
}

static const struct pinmux_driver_api api_funcs = {
	.set = fsl_k64_dev_set,
	.get = fsl_k64_dev_get
};

int pinmux_fsl_k64_initialize(struct device *port)
{
	ARG_UNUSED(port);

	return 0;
}

/* must be initialized after GPIO */
DEVICE_AND_API_INIT(pmux, CONFIG_PINMUX_DEV_NAME, &pinmux_fsl_k64_initialize,
		    NULL, NULL,
		    POST_KERNEL, CONFIG_PINMUX_INIT_PRIORITY,
		    &api_funcs);


text:
set -e

# Figure out where ENDIVE is installed
ENDIVE_REPO="$(cd `dirname $0`/..; pwd)"

CLASSPATH="$(. "$ENDIVE_REPO"/bin/compute-endive-classpath.sh)"

# list of jars to ship with spark; trim off the first from the CLASSPATH --> this is /etc
ENDIVE_JARS="$(echo "$CLASSPATH" | tr ":" "\n" | tail -n +2 | perl -pe 's/\n/,/ unless eof' )"

echo "$ENDIVE_JARS"


text:
package com.composum.sling.core.util;

import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.SlingConstants;

/**
 * Some Composum core-wide constants - mostly node types, property names etc.
 */
public interface CoreConstants extends JcrConstants {

    String DEFAULT_OVERRIDE_ROOT = "/mnt/override";
    String DEFAULT_OVERLAY_ROOT = "/mnt/overlay";

    /**
     * sling:resourceType
     */
    String PROP_RESOURCE_TYPE =
            SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_TYPE;
    /**
     * sling:resourceSuperType
     */
    String PROP_RESOURCE_SUPER_TYPE =
            SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_SUPER_TYPE;
    /**
     * jcr:content
     */
    String CONTENT_NODE = JCR_CONTENT;

    /**
     * mix:created
     */
    String MIX_CREATED = "mix:created";
    /**
     * mix:lastModified
     */
    String MIX_LAST_MODIFIED = "mix:lastModified";
    /**
     * mix:title
     */
    String MIX_TITLE = "mix:title";

    /**
     * jcr:title
     */
    String JCR_TITLE = "jcr:title";
    /**
     * jcr:description
     */
    String JCR_DESCRIPTION = "jcr:description";

    String TYPE_OAKINDEX = "oak:QueryIndexDefinition";
    String TYPE_FOLDER = NT_FOLDER;
    String TYPE_FILE = NT_FILE;
    String TYPE_LINKED_FILE = NT_LINKEDFILE;
    String TYPE_RESOURCE = NT_RESOURCE;
    String TYPE_UNSTRUCTURED = NT_UNSTRUCTURED;

    String TYPE_SLING_RESOURCE = "sling:Resource";
    String TYPE_SLING_FOLDER = "sling:Folder";
    String TYPE_SLING_ORDERED_FOLDER = "sling:OrderedFolder";

    String TYPE_LOCKABLE = MIX_LOCKABLE;
    String TYPE_REFERENCEABLE = MIX_REFERENCEABLE;
    String TYPE_LAST_MODIFIED = MIX_LAST_MODIFIED;
    String TYPE_CREATED = MIX_CREATED;
    String TYPE_TITLE = MIX_TITLE;
    String TYPE_VERSIONABLE = MIX_VERSIONABLE;

    String PROP_UUID = JCR_UUID;
    String PROPO_FROZEN_UUID = JCR_FROZENUUID;
    String PROP_TITLE = JCR_TITLE;
    String PROP_DESCRIPTION = JCR_DESCRIPTION;

    String PROP_DATA = JCR_DATA;
    String PROP_MIME_TYPE = JCR_MIMETYPE;
    String PROP_ENCODING = JCR_ENCODING;
    String PROP_PRIMARY_TYPE = JCR_PRIMARYTYPE;
    String PROP_MIXINTYPES = JCR_MIXINTYPES;
    String PROP_JCR_CONTENT = JCR_CONTENT;
    String PROP_CREATED = JCR_CREATED;
    String PROP_LAST_MODIFIED = JCR_LASTMODIFIED;
    String PROP_FILE_REFERENCE = "fileReference";

    String JCR_LASTMODIFIED_BY = "jcr:lastModifiedBy";
    String JCR_CREATED_BY = "jcr:createdBy";

    String PROP_ROOT_VERSION = JCR_ROOTVERSION;
    String PROP_BASE_VERSION = JCR_BASEVERSION;
    String PROP_VERSION_HISTORY = JCR_VERSIONHISTORY;
    String PROP_PREDECESSORS = JCR_PREDECESSORS;
    String PROP_SUCCESSORS = JCR_SUCCESSORS;
}


text:
function exists($tool) {
  Write-Host "Searching for $tool ..."
  $cmd = gcm $tool -ErrorAction SilentlyContinue
  if ($cmd -ne $Null) {
    Write-Host "Found $($cmd.Path)" -ForegroundColor Green
    return $True
  } else {
    Write-Host "$tool could not be found" -ForegroundColor Red
    return $False
  }
}

function Start-Boot2Docker {
  if ((exists boot2docker) -and (exists docker) -and (exists ssh)) {
    Write-Host "Starting boot2docker ..." -ForegroundColor Yellow
    & boot2docker start
    Write-Host "Setting environment variables ..." -ForegroundColor Yellow
    & boot2docker shellinit | % { $_ -replace "^\s*set\s+(DOCKER_[A-Z_]+)\s*=\s*(.*)\s*$", "`$Env:`$1 = '`$2'" } | iex
    & boot2docker ip | % { Write-Host "Docker host is running on IP $_" -ForegroundColor Green }
  }
}

function Stop-Boot2Docker {
  if (exists boot2docker) {
    Write-Host "Stopping boot2docker ..." -ForegroundColor Yellow
    & boot2docker stop
  }
}

Export-ModuleMember -Function Start-Boot2Docker, Stop-Boot2Docker


text:
layout: page
title: "William Kenneth Peters"
comments: true
description: "blanks"
keywords: "William Kenneth Peters,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**: CHEM 3341

#### CHEM 3341: LAB/ORGANIC CHEMISTRY 2

**Terms taught**: Fall 2006, Fall 2006, Fall 2006, Spring 2007, Spring 2007, Spring 2007

**Instructor rating**: 4.72

**Standard deviation in instructor rating**: 0.5

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

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

**Average workload** (raw): 2.46

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


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.astefanutti.cdeye</groupId>
        <artifactId>cdeye-envs</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>cdeye-servlet</artifactId>
    <name>CDEye Java Servlet Environment</name>

    <dependencies>

        <!-- provided dependencies -->

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
        </dependency>

        <!-- test dependencies -->

        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.shrinkwrap.resolver</groupId>
            <artifactId>shrinkwrap-resolver-depchain</artifactId>
            <type>pom</type>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.shrinkwrap.descriptors</groupId>
            <artifactId>shrinkwrap-descriptors-depchain</artifactId>
            <type>pom</type>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <profiles>

        <profile>
            <id>jetty</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>

            <dependencies>

                <!-- provided dependencies -->

                <!-- test dependencies -->

                <dependency>
                    <groupId>org.eclipse.jetty</groupId>
                    <artifactId>jetty-webapp</artifactId>
                </dependency>

                <dependency>
                    <groupId>org.eclipse.jetty</groupId>
                    <artifactId>jetty-annotations</artifactId>
                </dependency>

                <dependency>
                    <groupId>org.jboss.arquillian.container</groupId>
                    <artifactId>arquillian-jetty-embedded-9</artifactId>
                </dependency>

                <dependency>
                    <groupId>org.jboss.arquillian.testenricher</groupId>
                    <artifactId>arquillian-testenricher-resource</artifactId>
                </dependency>

            </dependencies>
        </profile>

    </profiles>

</project>


text:
import * as R_gte from '../ramda/dist/src/gte';

declare const string: string;
declare const number: number;

// @dts-jest:pass -> (b: string) => boolean
R_gte(string);
// @dts-jest:pass -> boolean
R_gte(string, string);
// @dts-jest:pass -> boolean
R_gte(number, number);


text:
"""
.. _ex-envelope-correlation:

=============================================
Compute envelope correlations in source space
=============================================

Compute envelope correlations of orthogonalized activity [1]_ [2]_ in source
space using resting state CTF data.
"""
# sphinx_gallery_thumbnail_number = 2

# Authors: Eric Larson <larson.eric.d@gmail.com>
#          Sheraz Khan <sheraz@khansheraz.com>
#          Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

import os.path as op

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.connectivity import envelope_correlation
from mne.minimum_norm import make_inverse_operator, apply_inverse_epochs
from mne.preprocessing import compute_proj_ecg, compute_proj_eog

data_path = mne.datasets.brainstorm.bst_resting.data_path()
subjects_dir = op.join(data_path, 'subjects')
subject = 'bst_resting'
trans = op.join(data_path, 'MEG', 'bst_resting', 'bst_resting-trans.fif')
src = op.join(subjects_dir, subject, 'bem', subject + '-oct-6-src.fif')
bem = op.join(subjects_dir, subject, 'bem', subject + '-5120-bem-sol.fif')
raw_fname = op.join(data_path, 'MEG', 'bst_resting',
                    'subj002_spontaneous_20111102_01_AUX.ds')

##############################################################################
# Here we do some things in the name of speed, such as crop (which will
# hurt SNR) and downsample. Then we compute SSP projectors and apply them.

raw = mne.io.read_raw_ctf(raw_fname, verbose='error')
raw.crop(0, 60).load_data().pick_types(meg=True, eeg=False).resample(80)
raw.apply_gradient_compensation(3)
projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2)
projs_eog, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='MLT31-4407')
raw.info['projs'] += projs_ecg
raw.info['projs'] += projs_eog
raw.apply_proj()
cov = mne.compute_raw_covariance(raw)  # compute before band-pass of interest

##############################################################################
# Now we band-pass filter our data and create epochs.

raw.filter(14, 30)
events = mne.make_fixed_length_events(raw, duration=5.)
epochs = mne.Epochs(raw, events=events, tmin=0, tmax=5.,
                    baseline=None, reject=dict(mag=8e-13), preload=True)
del raw

##############################################################################
# Compute the forward and inverse
# -------------------------------

src = mne.read_source_spaces(src)
fwd = mne.make_forward_solution(epochs.info, trans, src, bem)
inv = make_inverse_operator(epochs.info, fwd, cov)
del fwd, src

##############################################################################
# Compute label time series and do envelope correlation
# -----------------------------------------------------

labels = mne.read_labels_from_annot(subject, 'aparc_sub',
                                    subjects_dir=subjects_dir)
epochs.apply_hilbert()  # faster to apply in sensor space
stcs = apply_inverse_epochs(epochs, inv, lambda2=1. / 9., pick_ori='normal',
                            return_generator=True)
label_ts = mne.extract_label_time_course(
    stcs, labels, inv['src'], return_generator=True)
corr = envelope_correlation(label_ts, verbose=True)

# let's plot this matrix
fig, ax = plt.subplots(figsize=(4, 4))
ax.imshow(corr, cmap='viridis', clim=np.percentile(corr, [5, 95]))
fig.tight_layout()

##############################################################################
# Compute the degree and plot it
# ------------------------------

threshold_prop = 0.15  # percentage of strongest edges to keep in the graph
degree = mne.connectivity.degree(corr, threshold_prop=threshold_prop)
stc = mne.labels_to_stc(labels, degree)
stc = stc.in_label(mne.Label(inv['src'][0]['vertno'], hemi='lh') +
                   mne.Label(inv['src'][1]['vertno'], hemi='rh'))
brain = stc.plot(
    clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot',
    subjects_dir=subjects_dir, views='dorsal', hemi='both',
    smoothing_steps=25, time_label='Beta band')

##############################################################################
# References
# ----------
# .. [1] Hipp JF, Hawellek DJ, Corbetta M, Siegel M, Engel AK (2012)
#        Large-scale cortical correlation structure of spontaneous
#        oscillatory activity. Nature Neuroscience 15:884–890
# .. [2] Khan S et al. (2018). Maturation trajectories of cortical
#        resting-state networks depend on the mediating frequency band.
#        Neuroimage 174:57–68


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@mipmap/normal_cancel_hover" android:state_focused="true"/>
    <item android:drawable="@mipmap/normal_cancel_hover" android:state_pressed="true"/>
    <item android:drawable="@mipmap/normal_cancel_normal"></item>

</selector>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven>
		<message-converters>
			<!--<beans:bean class="org.springframework.http.converter.StringHttpMessageConverter"/> -->
			<!--<beans:bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> -->
			<beans:bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<beans:property name="objectMapper">
					<beans:bean
						class="com.knappsack.swagger4springweb.util.ScalaObjectMapper" />
				</beans:property>
			</beans:bean>
		</message-converters>
	</annotation-driven>
	<default-servlet-handler />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />
	<resources mapping="images/**" location="/resources/swagger-ui/images/" />
	<resources location="/view-resources/" mapping="/view-resources/**" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<context:component-scan base-package="com.coderspp.schedulepredict" />

</beans:beans>


text:
var persist = require("./persist.js");

/*
 * Fritter is a class that is the abstract data representation of freets
 * the methods it contains are essentailly getting and setting tweets and tweeters
*/
var Fritter = function() {
     var that = Object.create(Fritter.prototype);
     var tweeters = {};
     var tweets = {};
     var currentUser;

     /*
      * helper method to update dictionaries by loading from json
     */
     var updateDictionaries = function() {
         persist.load(function(err, data) {
          if (err) {
            console.log("err" + err);
          } else {
            tweeters = data[0];
            tweets = data[1];
          }
         });
     };
     /*
      * helper method to update the json from the dictionaries
     */
     var persistDictionaries = function() {
         persist.persist([tweeters, tweets], function(err, data){
             if (err) {
                 console.log("err" + err);
             }
         });
     };

     updateDictionaries();
     /*
      * method to add user onto database
      * @param user to add
     */
     that.addUser = function(user) {
         updateDictionaries();
         if (! (user in tweeters)) {
             tweeters[user] = [];
             persistDictionaries();
         }
     };
     /*
      * return the current user
      * @returns the currentUser
     */
     that.getUser = function() {
         return currentUser;
     };
     /*
      * switch user to another user
      * @param newUser to switch to
      * @return returns the newUser we just added
     */
     that.switchUser = function(newUser) {
         currentUser = newUser;
         that.addUser(newUser);
         return newUser;
     }
     /*
      * clear the dictionaries for easy testing
     */
     that.clearDictionaries = function() {
         tweeters = {};
         tweets = {};
         persistDictionaries();
     }
     /*
      * get all the tweet tuples of [tweetkey, author, tweet]
      * @return returns the tweet tuples
     */
     that.getAllTweetTuples = function() {
         updateDictionaries();
         if (tweeters === null) {
             return [];
         }
         var tweetTuples = [];
         for (var t in tweeters) {
             if (tweeters.hasOwnProperty(t)) {
                 var tweetKeyList = tweeters[t];
                 for (var i = 0; i < tweetKeyList.length; i++) {
                     var key = tweetKeyList[i];
                     tweetTuples.push([key, t, tweets[key]]);
                 }
              }
         }
         return tweetTuples;
     };
     /*
      * get all the user tweetkeys
      * @param author to search with
      * @return a list of tweetKeys associated with author
     */
     that.getAllUserTweetKeys = function(author) {
         updateDictionaries();
         var tweetKeys = tweeters[author];
         var tweetList = tweetKeys.map(function(tweetKey) {
             return tweets[tweetKey];
         });
         return tweetList;
     };
    /*
     * gets all the users
     * @return a list of all the users
    */
     that.getAllUsers = function() {
         updateDictionaries();
         return Object.keys(tweeters);
     };
    /*
     * get a tweet from a tweetkey
     * @param tweetKey of the tweet
     * @return the tweet associated with tweetKey
    */
     that.getTweet = function(tweetKey) {
         updateDictionaries();
         return tweets[tweetKey];
     };
    /*
     * adds a tweet
     * @param author the author of that tweet
     * @param tweet the tweet to add
     * @return the tweet tuple
    */
     that.addTweet = function(author, tweet) {
         updateDictionaries();
         var counter = Math.floor(Math.random() * 1000000).toString();
         if (tweeters[author].length > 0) {
             tweeters[author].push(counter);
         } else {
             tweeters[author] = [counter];
         }
         tweets[counter] = tweet;
         persistDictionaries();
         return [counter, author, tweet];
     };
    /*
     * deletes a tweet
     * @param author of the to be deleted tweet
     * @param tweetKey the key of the tweet to be deleted
     * @return the tweetkey of the deleted tweet
    */
     that.deleteTweet = function(author, tweetKey) {

         updateDictionaries();
         if (tweeters[author].length > 0) {
             tweetKey = tweetKey.slice(0, -1);
             delete tweets[tweetKey];
             var authortweetkeys = tweeters[author];
             var tweetIndex = authortweetkeys.indexOf(tweetKey);
             authortweetkeys.splice(tweetIndex, 1);
             tweeters[author] = authortweetkeys;

         } else {
             console.log("delete tweet doesn't exist");
         }
         persistDictionaries();
         return tweetKey;
     };
    Object.freeze(that);
    return that;
  };

module.exports = Fritter();