text:
package CTBNCToolkit.tests;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.junit.Test;

import CTBNCToolkit.CTBNClassifier;
import CTBNCToolkit.IClassificationResult;
import CTBNCToolkit.ITrajectory;
import CTBNCToolkit.NodeIndexing;

/**
 * @author Daniele Codecasa <danielecdcs@gmail.com>
 *
 */
public class ZJTESTCTBNClassifierFactory {

	/**
	 * Test method for {@link CTBNCToolkit.tests.CTBNClassifierFactory#CTBNClassifierFactory(int[], double[][], double)}.
	 */
	@Test
	public void testCTBNClassifierFactoryIntArrayDoubleArrayArrayDouble() {
		System.out.println("TEST ZJTESTCTBNClassifierFactory.testCTBNClassifierFactoryIntArrayDoubleArrayArrayDouble");

		// Number of variables
		int N = 3;
		// Number of states
		int[] nStates = new int[N];
		nStates[0] = 3;
		nStates[1] = 2;
		nStates[2] = 3;
		// Lambda ranges
		double[][] lambdaRanges = new double[2][N];
		lambdaRanges[0][0] = 0; lambdaRanges[1][0] = 0;
		lambdaRanges[0][1] = 2; lambdaRanges[1][1] = 4;
		lambdaRanges[0][2] = 10; lambdaRanges[1][2] = 15;

		CTBNClassifierFactory factory = new CTBNClassifierFactory("model", nStates, lambdaRanges);
		//assertTrue( factory.getTrajectoryLength() == (40*2/(3*1 + 12.5*2)));

		CTBNClassifier nbModel = factory.newInstance("testModel");
		assertTrue(nbModel.getName().equals("testModel"));
		System.out.println(nbModel.toString());
		System.out.println(nbModel.generateTrajectory(factory.getTrajectoryLength()).getTransitionsNumber());
	}

	/**
	 * Test method for {@link CTBNCToolkit.tests.CTBNClassifierFactory#CTBNClassifierFactory(int[], double[][], double, boolean[][])}.
	 */
	@Test
	public void testCTBNClassifierFactoryIntArrayDoubleArrayArrayDoubleBooleanArrayArray() {
		System.out.println("TEST ZJTESTCTBNClassifierFactory.testCTBNClassifierFactoryIntArrayDoubleArrayArrayDoubleBooleanArrayArray");

		// Number of variables
		int N = 3;
		// Number of states
		int[] nStates = new int[N];
		nStates[0] = 3;
		nStates[1] = 2;
		nStates[2] = 3;
		// Lambda ranges
		double[][] lambdaRanges = new double[2][N];
		lambdaRanges[0][0] = 0; lambdaRanges[1][0] = 0;
		lambdaRanges[0][1] = 2; lambdaRanges[1][1] = 4;
		lambdaRanges[0][2] = 10; lambdaRanges[1][2] = 15;
		// Structure
		boolean[][] adjMatrix = new boolean[N][N];
		for(int i = 0; i < adjMatrix.length; ++i)
			for(int j = 0; j < adjMatrix.length; ++j)
				adjMatrix[i][j] = (i == 0 && i != j);
		adjMatrix[1][2] = true;

		CTBNClassifierFactory factory = new CTBNClassifierFactory("testModel", nStates, lambdaRanges, adjMatrix);
		//assertTrue( factory.getTrajectoryLength() == (40*2/(3*1 + 12.5*2)));

		CTBNClassifier nbModel = factory.newInstance();
		assertTrue(nbModel.getName().equals("testModel-1"));
		System.out.println(nbModel.toString());
		System.out.println(nbModel.generateTrajectory(factory.getTrajectoryLength()).getTransitionsNumber());
		assertTrue(factory.newInstance().getName().equals("testModel-2"));
	}

	/**
	 * Test method for {@link CTBNCToolkit.tests.CTBNClassifierFactory#partitionDataset}.
	 * @throws Exception
	 */
	//! only with the files @Test
	public void testPartitionDataset() throws Exception {
		System.out.println("TEST ZJTESTCTBNClassifierFactory.partitionDataset");

		List<ITrajectory<Double>> dataset = new ArrayList<ITrajectory<Double>>();
		Set<String> validColumns = new TreeSet<String>();
		validColumns.add("t");validColumns.add("Class");validColumns.add("N01");
		CTBNCTestFactory.loadDataset("testloadPartitioning", dataset,
				"/home/daniele/Documents/CTBN-Dataset/SyntheticTest/VM/naiveBayes1/dataset/", ".txt", ',',
				"Class", "t", null, validColumns, 1, 0);

		List<List<ITrajectory<Double>>> partitionedDataset1 = CTBNCTestFactory.partitionDataset(
				"/home/daniele/Documents/CTBN-Dataset/SyntheticTest/VM/naiveBayes1/dataset/DBN-NB2_dT0.2/TestPartitioning",
				dataset, null, ".txt");
		List<List<ITrajectory<Double>>> partitionedDataset2 = CTBNCTestFactory.partitionDataset(
				"/home/daniele/Documents/CTBN-Dataset/SyntheticTest/VM/naiveBayes1/NB-results.txt",
				dataset, "naiveBayes1-1-", ".txt");

		/*
		List<ITrajectory<Double>> dataset = new ArrayList<ITrajectory<Double>>();
		Set<String> validColumns = new TreeSet<String>();
		validColumns.add("class");
		validColumns.add("A1");validColumns.add("A2");validColumns.add("A3");validColumns.add("A4");validColumns.add("A5");
		validColumns.add("A6");validColumns.add("A7");validColumns.add("A8");validColumns.add("A9");validColumns.add("A10");
		validColumns.add("A11");validColumns.add("A12");validColumns.add("A13");validColumns.add("A14");validColumns.add("A15");
		validColumns.add("A16");validColumns.add("A17");validColumns.add("A18");validColumns.add("A19");validColumns.add("A20");
		validColumns.add("A21");validColumns.add("A22");validColumns.add("A23");validColumns.add("A24");validColumns.add("A25");
		validColumns.add("A26");validColumns.add("A27");validColumns.add("A28");
		CTBNCTestFactory.loadDataset("testloadPartitioning", dataset,
				"/home/daniele/Documents/CTBN-Dataset/Sensors-Stroke/6 classes Full/movement1/", ".csv", ',',
				"class", validColumns, 1);

		List<List<ITrajectory<Double>>> partitionedDataset1 = CTBNCTestFactory.partitionDataset(
				"/home/daniele/Documents/CTBN-Dataset/Sensors-Stroke/6 classes Full/movement1/test-results-OLD/NB-results.txt",
				dataset, null, ".csv");
		List<List<ITrajectory<Double>>> partitionedDataset2 = CTBNCTestFactory.partitionDataset(
				"/home/daniele/Documents/CTBN-Dataset/Sensors-Stroke/6 classes Full/movement1/test-results-OLD/NB-results.txt",
				dataset, null, ".csv");
		*/
		// Partitioning print
		for( int i = 0; i < partitionedDataset1.size(); ++i) {
			System.out.println( "Partition " + i + ":");
			for( int j = 0; j < partitionedDataset1.get(i).size(); ++j) {
				System.out.println( partitionedDataset1.get(i).get(j).getName() + " - " + partitionedDataset2.get(i).get(j).getName());
				assertTrue(partitionedDataset1.get(i).get(j).getName().equals( partitionedDataset2.get(i).get(j).getName()));
			}
		}
	}

	/**
	 * Test method for {@link CTBNCToolkit.tests.CTBNClassifierFactory#partitionResultDataset}.
	 * @throws Exception
	 */
	//! only with the files @Test
	public void testPartitionResultDataset() throws Exception {
		System.out.println("TEST ZJTESTCTBNClassifierFactory.partitionResultDatset");

		List<IClassificationResult<Double>> dataset1 = new ArrayList<IClassificationResult<Double>>();
		Set<String> validColumns1 = new TreeSet<String>();
		validColumns1.add("time");validColumns1.add("realClass");
		CTBNCTestFactory.loadResultsDataset("loadResultsDataset",
				"/home/daniele/Documents/CTBN-Dataset/SyntheticTest/VM/naiveBayes1/dataset/DBN-NB2_dT0.2/",
				".txt", ',', "realClass", "t", null, validColumns1, dataset1);
		List<List<IClassificationResult<Double>>> partitionedDataset1 = CTBNCTestFactory.partitionResultDataset(
				"/home/daniele/Documents/CTBN-Dataset/SyntheticTest/VM/naiveBayes1/dataset/DBN-NB2_dT0.2/TestPartitioning",
				dataset1, null, ".txt");

		List<ITrajectory<Double>> dataset2 = new ArrayList<ITrajectory<Double>>();
		Set<String> validColumns2 = new TreeSet<String>();
		validColumns2.add("t");validColumns2.add("Class");validColumns2.add("N01");
		CTBNCTestFactory.loadDataset("testloadPartitioning", dataset2,
				"/home/daniele/Documents/CTBN-Dataset/SyntheticTest/VM/naiveBayes1/dataset/", ".txt", ',',
				"Class", "t", null, validColumns2, 1, 0);
		List<List<ITrajectory<Double>>> partitionedDataset2 = CTBNCTestFactory.partitionDataset(
				"/home/daniele/Documents/CTBN-Dataset/SyntheticTest/VM/naiveBayes1/NB-results.txt",
				dataset2, "naiveBayes1-1-", ".txt");

		// Partitioning print
		for( int i = 0; i < partitionedDataset1.size(); ++i) {
			System.out.println( "Partition " + i + ":");
			for( int j = 0; j < partitionedDataset1.get(i).size(); ++j) {
				System.out.println( partitionedDataset1.get(i).get(j).getName() + " - " + partitionedDataset2.get(i).get(j).getName());
				assertTrue(partitionedDataset1.get(i).get(j).getName().equals( partitionedDataset2.get(i).get(j).getName()));
			}
		}
	}

	/**
	 * Test method for {@link CTBNCToolkit.tests.CTBNClassifierFactory#loadResultsDataset}.
	 * @throws Exception
	 */
	//! only with the files @Test
	public void testLoadResultsDataset() throws Exception {
		System.out.println("TEST ZJTESTCTBNClassifierFactory.loadResultsDataset");

		List<IClassificationResult<Double>> dataset = new ArrayList<IClassificationResult<Double>>();
		Set<String> validColumns = new TreeSet<String>();
		validColumns.add("time");validColumns.add("realClass");
		CTBNCTestFactory.loadResultsDataset("loadResultsDataset",
				"/home/daniele/Documents/CTBN-Dataset/SyntheticTest/VM/naiveBayes1/dataset/DBN-NB2_dT0.2/",
				".txt", ',', "realClass", "t", null, validColumns, dataset);

		// Partitioning print
		NodeIndexing nodesIndexing = NodeIndexing.getNodeIndexing("loadResultsDataset");
		assertTrue(dataset.size() == 1000);
		for( int i = 0; i < dataset.size(); ++i) {
			System.out.println( dataset.get(i).getName() + " - " + dataset.get(i).getNodeValue(0, nodesIndexing.getIndex("realClass")) + " - " + dataset.get(i).getClassification());
			double[] pI = dataset.get(0).getPDistribution(0);
			double[] p = dataset.get(i).getPDistribution(3);
			for( int j = 0; j < p.length; ++j) {
				assertTrue(pI[j] == 0.25);
				System.out.print( p[j] + "  ");
			}
			System.out.println();
		}
	}
}


text:
@interface TNSViewController ()
@property (strong, nonatomic) IBOutlet UIPageControl *colorPage;
 @property (nonatomic, strong) AVAudioPlayer *audioPlayer; // The audio player itself
 @property (nonatomic) int playingNow; // The current sound index playng
 @property (nonatomic) int currentBackground; // The current backgorund index playng
@end

@implementation TNSViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Adding Listeners to swipe
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];

    // Setting the swipe direction.
    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];

    // Adding the swipe gesture on view
    [self.view addGestureRecognizer:swipeLeft];
    [self.view addGestureRecognizer:swipeRight];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    // Adding first-responders to view
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    // Releasing first-responders to view
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

// Events handling for iPhone's audio control
- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    if (event.type == UIEventTypeRemoteControl && self.playingNow >= 3000) {
        if (event.subtype == UIEventSubtypeRemoteControlPlay) {
            [self.audioPlayer play];
        } else if (event.subtype == UIEventSubtypeRemoteControlPause) {
            [self.audioPlayer pause];
        } else if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) {
            if(self.audioPlayer.playing)
                [self.audioPlayer pause];
            else
                [self.audioPlayer play];
        }
    }
}

// Change the background when swiping, loop through colors array
- (void)handleSwipe:(UISwipeGestureRecognizer *)swipe {

    if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
        int futureIndex = self.currentBackground - 1;
        if(futureIndex < 0){
            futureIndex = [[self getBackgroundColors] count] - 1;
        }
        [self setBackground:futureIndex];
        NSLog(@"Left Swipe");
    }

    if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
        int futureIndex = self.currentBackground + 1;
        if(futureIndex > ([[self getBackgroundColors] count] - 1)){
            futureIndex = 0;
        }
        [self setBackground:futureIndex];
        NSLog(@"Right Swipe");
    }

}

// Set The background with a smooth animation
- (void)setBackground:(int)backgroundIndex{
    [UIView animateWithDuration:0.5 animations:^{
        [self.view setBackgroundColor:[self.getBackgroundColors objectAtIndex: backgroundIndex]];
    }];
    self.currentBackground = backgroundIndex;
    self.colorPage.currentPage = backgroundIndex;
    NSLog(@"Background color is now set to %i", backgroundIndex);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

// Init a sound by the UIButton tag, we use this tag as an index of a dictionary of sounds
- (IBAction)didTapSound:(UIButton *)sender {
    [self playSound:sender.tag];
}

// Display an about message when tap the app title
- (IBAction)didTapTitle:(UIButton *)sender {
    NSString *aboutMessage = @"Sounds: freesound.org\nIcons: flaticon.com\nApp Dev: rafaismy.name";
    UIAlertView *about = [[UIAlertView alloc] initWithTitle:@"About"
                                                    message:aboutMessage
                                                   delegate:nil
                                          cancelButtonTitle:@"Roger That! :)"
                                          otherButtonTitles:nil];
    [about show];
    NSLog(@"About message show");
}

// The sounds dictionary
- (NSDictionary *)getSounds{
    return @{@3000: @"Thunderstorm_with_heavy_Rain", @3001: @"cafe_brazil_walla", @3002: @"whiteNoise", @3003: @"henne_beach", @3004: @"fireplace", @3005: @"antony_creek"};
}

// The background colors dictionary
- (NSArray *)getBackgroundColors{
    UIColor *green = [UIColor colorWithRed:0/255.0f green:212/255.0f blue:150/255.0f alpha:1.0f];
    UIColor *blue = [UIColor colorWithRed:0/255.0f green:196/255.0f blue:214/255.0f alpha:1.0f];
    UIColor *darkBlue = [UIColor colorWithRed:0/255.0f green:137/255.0f blue:133/255.0f alpha:1.0f];
    UIColor * yellow = [UIColor colorWithRed:243/255.0f green:194/255.0f blue:66/255.0f alpha:1.0f];
    UIColor *orange = [UIColor colorWithRed:222/255.0f green:109/255.0f blue:39/255.0f alpha:1.0f];
    UIColor *white = [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f];
    return @[green, blue, darkBlue, yellow, orange, white];
}

// The sound controls of the app
- (void)playSound:(int)soundIndex{
    NSString *sound = [self.getSounds objectForKey:[NSNumber numberWithInt:soundIndex]];

    NSString *filePath = [[NSBundle mainBundle] pathForResource:sound ofType:@"mp3"];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];

    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    [self.audioPlayer setNumberOfLoops:-1];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];

    [self.audioPlayer prepareToPlay];

    if (self.playingNow >= 3000)
    {
        self.audioPlayer.currentTime = 0;
        [self toggleSoundButton:self.playingNow];
        if(soundIndex == self.playingNow){
            [self.audioPlayer stop];
            self.playingNow = -1;
            NSLog(@"Stopped sound index %i", soundIndex);
        }else{
            [self.audioPlayer play];
            [self toggleSoundButton:soundIndex];
            self.playingNow = soundIndex;
            NSLog(@"Playng sound index %i", soundIndex);
        }

    }
    else
    {
        [self.audioPlayer play];
        [self toggleSoundButton:soundIndex];
        self.playingNow = soundIndex;
        NSLog(@"Playng sound index %i", soundIndex);
    }
}

// Toggle sound buttons states (on/off)
- (void)toggleSoundButton:(int)btnTag{
    UIButton *soundButton = (UIButton *)[self.view viewWithTag:btnTag];
    if (soundButton.isSelected)
        [soundButton setSelected:NO];
    else
        [soundButton setSelected:YES];
}

#pragma mark iAd Delegate Methods
// Method is called when the iAd is loaded.
-(void)bannerViewDidLoadAd:(ADBannerView *)banner {

    // Creates animation.
    [UIView beginAnimations:nil context:nil];

    // Sets the duration of the animation to 1.
    [UIView setAnimationDuration:1];

    // Sets the alpha to 1.
    // We do this because we are going to have it set to 0 to start and setting it to 1 will cause the iAd to fade into view.
    [banner setAlpha:1];

    //  Performs animation.
    [UIView commitAnimations];

}

// Method is called when the iAd fails to load.
-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error {

    // Creates animation.
    [UIView beginAnimations:nil context:nil];

    // Sets the duration of the animation to 1.
    [UIView setAnimationDuration:1];

    // Sets the alpha to 0.
    // We do this because we are going to have it set to 1 to start and setting it to 0 will cause the iAd to fade out of view.
    [banner setAlpha:0];

    //  Performs animation.
    [UIView commitAnimations];

}
@end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe "clients_companies/edit" do
  before(:each) do
    @clients_company = assign(:clients_company, stub_model(ClientsCompany,
      :client_id => 1,
      :company_id => 1,
      :weight => 1
    ))
  end

  it "renders the edit clients_company form" do
    render

    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "form[action=?][method=?]", clients_company_path(@clients_company), "post" do
      assert_select "input#clients_company_client_id[name=?]", "clients_company[client_id]"
      assert_select "input#clients_company_company_id[name=?]", "clients_company[company_id]"
      assert_select "input#clients_company_weight[name=?]", "clients_company[weight]"
    end
  end
end


text:
package org.cuacfm.members.web.support;

import java.io.Serializable;

/**
 * A message to be displayed in web context. Depending on the type, different style will be applied.
 */

public class Message implements Serializable {

	private static final long serialVersionUID = 1L;

	/** Name of the flash attribute. */
	public static final String MESSAGE_ATTRIBUTE = "message";

	/**
	 * The type of the message to be displayed. The type is used to show message in a different style.
	 */
	public static enum Type {
		DANGER, WARNING, INFO, SUCCESS;
	}

	/** The message. */
	private final String message;

	/** The type. */
	private final Type type;

	/** The args. */
	private final transient Object[] args;

	/**
	 * Instantiates a new message.
	 *
	 * @param message the message
	 * @param type the type
	 */
	public Message(String message, Type type) {
		this.message = message;
		this.type = type;
		this.args = null;

	}

	/**
	 * Instantiates a new message.
	 *
	 * @param message the message
	 * @param type the type
	 * @param args the args
	 */
	public Message(String message, Type type, Object... args) {
		this.message = message;
		this.type = type;
		this.args = args;
	}

	public String getMessage() {
		return message;
	}

	public Type getType() {
		return type;
	}

	public Object[] getArgs() {
		return args.clone();
	}
}


text:
package com.centurylink.mdw.model.listener;

import java.io.Serializable;

import com.centurylink.mdw.common.MdwException;

public class ListenerException extends MdwException implements Serializable {

    public ListenerException(String message){
        super(message);
    }

    public ListenerException(int code, String message){
        super(code, message);

    }

    public ListenerException(int code, String message, Throwable cause){
        super(code, message, cause);

    }
}


text:
from coyote_framework.config.abstract_config import ConfigBase

class ConstantsConfig(ConfigBase):

    def __init__(self):
        super(ConstantsConfig, self).__init__('constants')


text:
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace Geco.Tests.Database.Model
{
    [GeneratedCode("Geco", "1.0.5.0")]
    public partial class Vendor
    {
        // Key Properties
        public int BusinessEntityID { get; set; }

        // Scalar Properties
        public string AccountNumber { get; set; }
        public string Name { get; set; }
        public byte CreditRating { get; set; }
        public bool PreferredVendorStatus { get; set; }
        public bool ActiveFlag { get; set; }
        public string PurchasingWebServiceURL { get; set; }
        public DateTime ModifiedDate { get; set; }

        // Foreign keys
        public BusinessEntity BusinessEntity { get; set; }

        // Reverse navigation
        public List<ProductVendor> ProductVendors { get; set; }
        public List<PurchaseOrderHeader> PurchaseOrderHeaders { get; set; }

        public Vendor()
        {
            this.ProductVendors = new List<ProductVendor>();
            this.PurchaseOrderHeaders = new List<PurchaseOrderHeader>();
        }
    }
}


text:
<?php

// No direct access.
defined('_HZEXEC_') or die();

$base = rtrim(Request::base(true), '/');

$this->css('create.css')
	->css('autocompleter.css')
	->js('create.js');
?>

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

			<a class="icon-add add btn" href="<?php echo Route::url('index.php?option=' . $this->option . '&task=draft'); ?>">
				<?php echo Lang::txt('COM_CONTRIBUTE_NEW_SUBMISSION'); ?>

	<?php
		$this->view('steps')
		     ->set('option', $this->option)
		     ->set('step', $this->step)
		     ->set('steps', $this->steps)
		     ->set('id', $this->id)
		     ->set('resource', $this->row)
		     ->set('progress', $this->progress)
		     ->display();
	?>
<?php if ($this->getError()) { ?>

<?php echo $this->getError(); ?>

<?php } ?>
	<form action="<?php echo Route::url('index.php?option=' . $this->option . '&task=draft&step=' . $this->next_step . '&id=' . $this->id); ?>" method="post" id="hubForm">

<?php echo Lang::txt('COM_CONTRIBUTE_ATTACH_WHAT_ARE_ATTACHMENTS'); ?>

<?php echo Lang::txt('COM_CONTRIBUTE_ATTACH_EXPLANATION'); ?>

<?php echo Lang::txt('COM_CONTRIBUTE_ACCESS'); ?>

				<?php echo Lang::txt('COM_CONTRIBUTE_ACCESS_PUBLIC'); ?> = <?php echo Lang::txt('COM_CONTRIBUTE_ACCESS_PUBLIC_EXPLANATION'); ?>

				<?php echo Lang::txt('COM_CONTRIBUTE_ACCESS_REGISTERED'); ?> = <?php echo Lang::txt('COM_CONTRIBUTE_ACCESS_REGISTERED_EXPLANATION'); ?>

		<fieldset>
			<legend><?php echo Lang::txt('COM_CONTRIBUTE_ATTACH_ATTACHMENTS'); ?></legend>

						<?php if (!$this->row->type->get('collection')): ?>
							<?php
							$this->js('jquery.fileuploader.js', 'system')
								->js('fileupload.js');
							echo $this->loadTemplate('fileuploader');
							?>
						<?php else: ?>
							<?php
							$this->js('addchild.js');
							echo $this->loadTemplate('addchild');
							?>
						<?php endif; ?>

					<iframe width="100%" height="500" frameborder="0" name="attaches" id="attaches" src="index.php?option=<?php echo $this->option; ?>&controller=attachments&id=<?php echo $this->id; ?>&tmpl=component">

			<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
			<input type="hidden" name="controller" value="<?php echo $this->controller; ?>" />
			<input type="hidden" name="task" value="<?php echo $this->task; ?>" />
			<input type="hidden" name="step" value="<?php echo $this->next_step; ?>" />
			<input type="hidden" name="id" value="<?php echo $this->id; ?>" />
		</fieldset>

			<input class="btn btn-success" type="submit" value="<?php echo Lang::txt('COM_CONTRIBUTE_NEXT'); ?>" />

	</form>


text:
using System;
using System.ComponentModel.DataAnnotations;

namespace Demo.Domain
{
    /// <summary>
    /// A validator that checks if a property is before today.
    /// </summary>
    /// <remarks>
    /// This was based on a sample found online in an article by Scott K. Allen at
    /// http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx
    /// </remarks>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class AfterTodayAttribute : ValidationAttribute
    {
        public AfterTodayAttribute()
            : base("{0} must be after today")
        { }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null) return ValidationResult.Success;

            var firstComparable = value as IComparable;
            var secondComparable = DateTime.Now as IComparable;

            return firstComparable.CompareTo(secondComparable) < 0
                ? new ValidationResult(FormatErrorMessage(validationContext.DisplayName))
                : ValidationResult.Success;
        }
    }
}


text:
//
//  Copyright © 2015 Claus Christmann <hcc |ä| gatech.edu>.
//
//  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.
//

#ifndef LOCATIONID_H
#define LOCATIONID_H

#include "IDL/data.h"
#include <limits>

/** \brief A class representing an identifyer for locations.
 * \note An ElementId is not necessarily unique.
 * \internal This type should be compatible to the Qt qHash() function return so
 * that Location can be used in QHash containers. */
using LocationId = IDL::Data::LocationId;

/** \brief A value representing an invalid LocationId. */
const LocationId NULL_LOCATION_ID = std::numeric_limits<LocationId>::max(); // FIXME: Magic Numbers

#endif // LOCATIONID_H


text:
<?xml version="1.0" encoding="utf-8"?>

<title>Usage</title>

<title>Paginating data collections</title>

        <para>
            In order to paginate items into pages, <classname>Zend_Paginator</classname>
            must have a generic way of accessing that data. For that reason,
            all data access takes place through data source adapters. Several
            adapters ship with Zend Framework by default:
        </para>

<title>Adapters for Zend_Paginator</title>

            <tgroup cols="2">

                    <row>
                        <entry>Adapter</entry>
                        <entry>Description</entry>
                    </row>

                    <row>
                        <entry>Array</entry>
                        <entry>Use a <acronym>PHP</acronym> array</entry>
                    </row>

                    <row>
                        <entry>DbSelect</entry>

                        <entry>
                            Use a <link linkend="zend.db.select"><classname>Zend_Db_Select</classname></link>
                            instance, which will return an array
                        </entry>
                    </row>

                    <row>
                        <entry>DbTableSelect</entry>

                        <entry>
                            Use a <link linkend="zend.db.table.fetch-all"><classname>Zend_Db_Table_Select</classname></link>
                            instance, which will return an instance of
                            <classname>Zend_Db_Table_Rowset_Abstract</classname>.
                            This provides additional information about the
                            result set, such as column names.
                        </entry>
                    </row>

                    <row>
                        <entry>Iterator</entry>

                        <entry>
                            Use an <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.php.net/~helly/php/ext/spl/interfaceIterator.html"><classname>Iterator</classname></link>
                            instance
                        </entry>
                    </row>

                    <row>
                        <entry>Null</entry>

                        <entry>
                            Do not use <classname>Zend_Paginator</classname> to manage
                            data pagination. You can still take advantage of
                            the pagination control feature.
                        </entry>
                    </row>

            </tgroup>

        <note>
            <para>
                Instead of selecting every matching row of a given query, the
                DbSelect and DbTableSelect adapters retrieve only the smallest
                amount of data necessary for displaying the current page.
            </para>

            <para>
                Because of this, a second query is dynamically generated to
                determine the total number of matching rows. However, it is
                possible to directly supply a count or count query yourself.
                See the <methodname>setRowCount()</methodname> method in the DbSelect
                adapter for more information.
            </para>
        </note>

        <para>
            To create an instance of <classname>Zend_Paginator</classname>, you must
            supply an adapter to the constructor:
        </para>

        <programlisting language="php"><![CDATA[
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($array));
]]></programlisting>

        <para>
            For convenience, you may take advantage of the static
            <methodname>factory()</methodname> method for the adapters packaged with Zend
            Framework:
        </para>

        <programlisting language="php"><![CDATA[
$paginator = Zend_Paginator::factory($array);
]]></programlisting>

        <note>
            <para>
                In the case of the <classname>Null</classname> adapter, in lieu of a data collection
                you must supply an item count to its constructor.
            </para>
        </note>

        <para>
            Although the instance is technically usable in this state, in your
            controller action you'll need to tell the paginator what page
            number the user requested. This allows him to advance through the
            paginated data.
        </para>

        <programlisting language="php"><![CDATA[
$paginator->setCurrentPageNumber($page);
]]></programlisting>

        <para>
            The simplest way to keep track of this value is through a <acronym>URL</acronym>.
            Although we recommend using a
            <classname>Zend_Controller_Router_Interface</classname>-compatible
            router to handle this, it is not a requirement.
        </para>

        <para>
            The following is an example route you might use in an <acronym>INI</acronym>
            configuration file:
        </para>

        <programlisting language="php"><![CDATA[
routes.example.route = articles/:articleName/:page
routes.example.defaults.controller = articles
routes.example.defaults.action = view
routes.example.defaults.page = 1
routes.example.reqs.articleName = \w+
routes.example.reqs.page = \d+
]]></programlisting>

        <para>
            With the above route (and using Zend Framework <acronym>MVC</acronym> components),
            you might set the current page number like this:
        </para>

        <programlisting language="php"><![CDATA[
$paginator->setCurrentPageNumber($this->_getParam('page'));
]]></programlisting>

        <para>
            There are other options available; see
            <link linkend="zend.paginator.configuration">Configuration</link>
            for more on them.
        </para>

        <para>
            Finally, you'll need to assign the paginator instance to your view.
            If you're using <classname>Zend_View</classname> with the ViewRenderer action
            helper, the following will work:
        </para>

        <programlisting language="php"><![CDATA[
$this->view->paginator = $paginator;
]]></programlisting>

<title>The DbSelect and DbTableSelect adapter</title>

        <para>
            The usage of most adapters is pretty straight-forward. However, the
            database adapters require a more detailed explanation regarding
            the retrieval and count of the data from the database.
        </para>

        <para>
            To use the DbSelect and DbTableSelect adapters you don't have to retrieve the data
            upfront from the database. Both adapters do the retrieval for you, aswell as the
            counting of the total pages. If additional work has to be done on the database results
            the adapter <methodname>getItems()</methodname> method has to be extended in your
            application.
        </para>

        <para>
            Additionally these adapters do <emphasis>not</emphasis> fetch all records from the
            database in order to count them. Instead, the adapters manipulates the original query to
            produce the corresponding COUNT query. Paginator then executes that COUNT query to get
            the number of rows. This does require an extra round-trip to the database, but this is
            many times faster than fetching an entire result set and using
            <methodname>count()</methodname>. Especially with large collections of data.
        </para>

        <para>
            The database adapters will try and build the most efficient query that will execute
            on pretty much all modern databases. However, depending on your database or even your
            own schema setup, there might be more efficient ways to get a rowcount. For this
            scenario the database adapters allow you to set a custom COUNT query. For example,
            if you keep track of the count of blog posts in a separate table, you could achieve a
            faster count query with the following setup:
        </para>

        <programlisting language="php"><![CDATA[
$adapter = new Zend_Paginator_Adapter_DbSelect($db->select()->from('posts'));
$adapter->setRowCount(
    $db->select()
       ->from(
            'item_counts',
            array(
               Zend_Paginator_Adapter_DbSelect::ROW_COUNT_COLUMN => 'post_count'
            )
         )
);

$paginator = new Zend_Paginator($adapter);
]]></programlisting>

        <para>
            This approach will probably not give you a huge performance gain on
            small collections and/or simple select queries. However, with complex
            queries and large collections, a similar approach could give you a
            significant performance boost.
        </para>

<title>Rendering pages with view scripts</title>

        <para>
            The view script is used to render the page items (if you're using
            <classname>Zend_Paginator</classname> to do so) and display the pagination
            control.
        </para>

        <para>
            Because <classname>Zend_Paginator</classname> implements the <acronym>SPL</acronym>
            interface <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.php.net/~helly/php/ext/spl/interfaceIteratorAggregate.html"><classname>IteratorAggregate</classname></link>,
            looping over your items and displaying them is simple.
        </para>

        <programlisting language="php"><![CDATA[

Example

<?php if (count($this->paginator)): ?>

<?php foreach ($this->paginator as $item): ?>

<?php echo $item; ?>

<?php endforeach; ?>

<?php endif; ?>

<?php echo $this->paginationControl($this->paginator,
                                    'Sliding',
                                    'my_pagination_control.phtml'); ?>

]]></programlisting>

        <para>
            Notice the view helper call near the end. PaginationControl
            accepts up to four parameters: the paginator instance, a scrolling
            style, a view partial, and an array of additional parameters.
        </para>

        <para>
            The second and third parameters are very important. Whereas the
            view partial is used to determine how the pagination control should
            <emphasis>look</emphasis>, the scrolling style is used to control
            how it should <emphasis>behave</emphasis>. Say the view partial is
            in the style of a search pagination control, like the one below:
        </para>

        <para>
            <inlinemediaobject><imageobject><imagedata align="center" valign="middle" fileref="figures/zend.paginator.usage.rendering.control.png" format="PNG"/></imageobject></inlinemediaobject>
        </para>

        <para>
            What happens when the user clicks the "next" link a few times?
            Well, any number of things could happen. The current page number
            could stay in the middle as you click through (as it does on
            Yahoo!), or it could advance to the end of the page range and then
            appear again on the left when the user clicks "next" one more time.
            The page numbers might even expand and contract as the user
            advances (or "scrolls") through them (as they do on Google).
        </para>

        <para>
            There are four scrolling styles packaged with Zend Framework:
        </para>

<title>Scrolling styles for Zend_Paginator</title>

            <tgroup cols="2">

                    <row>
                        <entry>Scrolling style</entry>
                        <entry>Description</entry>
                    </row>

                    <row>
                        <entry>All</entry>

                        <entry>
                            Returns every page. This is useful for dropdown
                            menu pagination controls with relatively few
                            pages. In these cases, you want all pages
                            available to the user at once.
                        </entry>
                    </row>

                    <row>
                        <entry>Elastic</entry>

                        <entry>
                            A Google-like scrolling style that expands and
                            contracts as a user scrolls through the pages.
                        </entry>
                    </row>

                    <row>
                        <entry>Jumping</entry>

                        <entry>
                            As users scroll through, the page number advances
                            to the end of a given range, then starts again at
                            the beginning of the new range.
                        </entry>
                    </row>

                    <row>
                        <entry>Sliding</entry>

                        <entry>
                            A Yahoo!-like scrolling style that positions the
                            current page number in the center of the page
                            range, or as close as possible. This is the
                            default style.
                        </entry>
                    </row>

            </tgroup>

        <para>
            The fourth and final parameter is reserved for an optional
            associative array of additional variables that you want available
            in your view partial (available via <varname>$this</varname>). For
            instance, these values could include extra <acronym>URL</acronym> parameters for
            pagination links.
        </para>

        <para>
            By setting the default view partial, default
            scrolling style, and view instance, you can eliminate the calls to
            PaginationControl completely:
        </para>

        <programlisting language="php"><![CDATA[
Zend_Paginator::setDefaultScrollingStyle('Sliding');
Zend_View_Helper_PaginationControl::setDefaultViewPartial(
    'my_pagination_control.phtml'
);
$paginator->setView($view);
]]></programlisting>

        <para>
            When all of these values are set, you can render the pagination
            control inside your view script with a simple echo statement:
        </para>

        <programlisting language="php"><![CDATA[
<?php echo $this->paginator; ?>
]]></programlisting>

        <note>
            <para>
                Of course, it's possible to use <classname>Zend_Paginator</classname>
                with other template engines. For example, with Smarty you
                might do the following:
            </para>

            <programlisting language="php"><![CDATA[
$smarty->assign('pages', $paginator->getPages());
]]></programlisting>

            <para>
                You could then access paginator values from a template like so:
            </para>

            <programlisting language="php"><![CDATA[
{$pages->pageCount}
]]></programlisting>
        </note>

<title>Example pagination controls</title>

            <para>
                The following example pagination controls will hopefully help
                you get started:
            </para>

            <para>
                Search pagination:
            </para>

            <programlisting language="php"><![CDATA[

<?php if ($this->pageCount): ?>

<?php if (isset($this->previous)): ?>
  <a href="<?php echo $this->url(array('page' => $this->previous)); ?>">
    < Previous
   |
<?php else: ?>
  < Previous |
<?php endif; ?>

<?php foreach ($this->pagesInRange as $page): ?>
  <?php if ($page != $this->current): ?>
    <a href="<?php echo $this->url(array('page' => $page)); ?>">
        <?php echo $page; ?>
     |
  <?php else: ?>
    <?php echo $page; ?> |
  <?php endif; ?>
<?php endforeach; ?>

<?php if (isset($this->next)): ?>
  <a href="<?php echo $this->url(array('page' => $this->next)); ?>">
    Next >

<?php else: ?>
  Next >
<?php endif; ?>

<?php endif; ?>
]]></programlisting>

            <para>
                Item pagination:
            </para>

            <programlisting language="php"><![CDATA[

<?php if ($this->pageCount): ?>

<?php echo $this->firstItemNumber; ?> - <?php echo $this->lastItemNumber; ?>
of <?php echo $this->totalItemCount; ?>

<?php if (isset($this->previous)): ?>
  <a href="<?php echo $this->url(array('page' => $this->first)); ?>">
    First
   |
<?php else: ?>
  First |
<?php endif; ?>

<?php if (isset($this->previous)): ?>
  <a href="<?php echo $this->url(array('page' => $this->previous)); ?>">
    < Previous
   |
<?php else: ?>
  < Previous |
<?php endif; ?>

<?php if (isset($this->next)): ?>
  <a href="<?php echo $this->url(array('page' => $this->next)); ?>">
    Next >
   |
<?php else: ?>
  Next > |
<?php endif; ?>

<?php if (isset($this->next)): ?>
  <a href="<?php echo $this->url(array('page' => $this->last)); ?>">
    Last

<?php else: ?>
  Last
<?php endif; ?>

<?php endif; ?>
]]></programlisting>

            <para>
                Dropdown pagination:
            </para>

            <programlisting language="php"><![CDATA[
<?php if ($this->pageCount): ?>
<select id="paginationControl" size="1">
<?php foreach ($this->pagesInRange as $page): ?>
  <?php $selected = ($page == $this->current) ? ' selected="selected"' : ''; ?>
  <option value="<?php
        echo $this->url(array('page' => $page));?>"<?php echo $selected ?>>
    <?php echo $page; ?>
  </option>
<?php endforeach; ?>
</select>
<?php endif; ?>

]]></programlisting>

<title>Listing of properties</title>

            <para>
                The following options are available to pagination control
                view partials:
            </para>

<title>Properties available to view partials</title>

                <tgroup cols="3">

                        <row>
                            <entry>Property</entry>
                            <entry>Type</entry>
                            <entry>Description</entry>
                        </row>

                        <row>
                            <entry>first</entry>
                            <entry>integer</entry>
                            <entry>First page number (i.e., 1)</entry>
                        </row>

                        <row>
                            <entry>firstItemNumber</entry>
                            <entry>integer</entry>
                            <entry>Absolute number of the first item on this page</entry>
                        </row>

                        <row>
                            <entry>firstPageInRange</entry>
                            <entry>integer</entry>
                            <entry>First page in the range returned by the scrolling style</entry>
                        </row>

                        <row>
                            <entry>current</entry>
                            <entry>integer</entry>
                            <entry>Current page number</entry>
                        </row>

                        <row>
                            <entry>currentItemCount</entry>
                            <entry>integer</entry>
                            <entry>Number of items on this page</entry>
                        </row>

                        <row>
                            <entry>itemCountPerPage</entry>
                            <entry>integer</entry>
                            <entry>Maximum number of items available to each page</entry>
                        </row>

                        <row>
                            <entry>last</entry>
                            <entry>integer</entry>
                            <entry>Last page number</entry>
                        </row>

                        <row>
                            <entry>lastItemNumber</entry>
                            <entry>integer</entry>
                            <entry>Absolute number of the last item on this page</entry>
                        </row>

                        <row>
                            <entry>lastPageInRange</entry>
                            <entry>integer</entry>
                            <entry>Last page in the range returned by the scrolling style</entry>
                        </row>

                        <row>
                            <entry>next</entry>
                            <entry>integer</entry>
                            <entry>Next page number</entry>
                        </row>

                        <row>
                            <entry>pageCount</entry>
                            <entry>integer</entry>
                            <entry>Number of pages</entry>
                        </row>

                        <row>
                            <entry>pagesInRange</entry>
                            <entry>array</entry>
                            <entry>Array of pages returned by the scrolling style</entry>
                        </row>

                        <row>
                            <entry>previous</entry>
                            <entry>integer</entry>
                            <entry>Previous page number</entry>
                        </row>

                        <row>
                            <entry>totalItemCount</entry>
                            <entry>integer</entry>
                            <entry>Total number of items</entry>
                        </row>

                </tgroup>


text:
Free, best practice document templates as used in [Documize](https://documize.com).

Just download the .DOCX file or click on the .MD file for a preview.


text:
class RemoveConfirmableFromUsers < ActiveRecord::Migration

  # the opposite of https://github.com/plataformatec/devise/wiki/How-To:-Add-:confirmable-to-Users

  def up
    remove_columns :users, :confirmation_token, :confirmed_at, :confirmation_sent_at
  end

  def down
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime
    # add_column :users, :unconfirmed_email, :string # Only if using reconfirmable
    add_index :users, :confirmation_token, :unique => true
    # User.reset_column_information # Need for some types of updates, but not for update_all.
    # To avoid a short time window between running the migration and updating all existing
    # users as confirmed, do the following
    User.update_all(:confirmed_at => Time.now)
    # All existing user accounts should be able to log in after this.
  end

end


text:
/*
 * The code contained herein is licensed under the GNU General Public
 * License. You may obtain a copy of the GNU General Public License
 * Version 2 or later at the following locations:
 *
 * http://www.opensource.org/licenses/gpl-license.html
 * http://www.gnu.org/copyleft/gpl.html
 */

////////////////////////////////////////////////////////////////////////////////
//   Includes and external references
////////////////////////////////////////////////////////////////////////////////
#include "types.h"
#include "hw/lradc/hw_lradc.h"
#include "registers/regs.h"
#include "registers/regslradc.h"
#include "error.h"
#include "hw/digctl/hw_digctl.h"

////////////////////////////////////////////////////////////////////////////////
// Definitions
////////////////////////////////////////////////////////////////////////////////
#define TEMP_SENSOR_CURRENT_RAMP_DELAY 300
#define NUM_TEMP_READINGS_TO_AVG 5
#define TEMP_SENSOR_CONVERSION_CONSTANT 1104

////////////////////////////////////////////////////////////////////////////////
// Code
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//! See hw_lradc.h for details.
////////////////////////////////////////////////////////////////////////////////
bool hw_lradc_GetTempSensorPresent(hw_lradc_TempSensor_t eSensor)
{
    bool bRtn;
    // Read a bit field of HW_LRADC_STATUS register
    switch (eSensor)
    {
        case TEMP_SENSOR0:
            bRtn  =  BF_RD(LRADC_STATUS, TEMP0_PRESENT);
            break;
        case TEMP_SENSOR1:
            bRtn =  BF_RD(LRADC_STATUS, TEMP1_PRESENT);
            break;
        default:
            bRtn = 0;
        break;
    }
    return bRtn;
}

////////////////////////////////////////////////////////////////////////////////
//! See hw_lradc.h for details.
////////////////////////////////////////////////////////////////////////////////
void hw_lradc_SetTempSensorCurrentValue(hw_lradc_TempSensor_t       eSensor,
                                        hw_lradc_CurrentMagnitude_t eValue)
{
    switch (eSensor)
    {
        case TEMP_SENSOR0:
            // Set the sensor current value
            BF_WR(LRADC_CTRL2, TEMP_ISRC0, eValue);
            break;
        case TEMP_SENSOR1:
            // Set the sensor current value
            BF_WR(LRADC_CTRL2, TEMP_ISRC1, eValue);
            break;
        default:
            break;
    }
}

////////////////////////////////////////////////////////////////////////////////
//! See hw_lradc.h for details.
////////////////////////////////////////////////////////////////////////////////
void hw_lradc_EnableTempSensorCurrent(hw_lradc_TempSensor_t  eSensor,
                                      bool                   bValue)
{
    switch (eSensor)
    {
        case TEMP_SENSOR0:
            if(bValue)
            {// Enable the sensor current source
                BF_SET(LRADC_CTRL2, TEMP_SENSOR_IENABLE0);
            }
            else
            {// Disable the sensor current source
                BF_CLR(LRADC_CTRL2, TEMP_SENSOR_IENABLE0);
            }
            break;
        case TEMP_SENSOR1:
            if(bValue)
            {// Enable the sensor current source
                BF_SET(LRADC_CTRL2, TEMP_SENSOR_IENABLE1);
            }
            else
            {// Disable the sensor current source
                BF_CLR(LRADC_CTRL2, TEMP_SENSOR_IENABLE1);
            }
            break;
        default:
            break;
    }
}

////////////////////////////////////////////////////////////////////////////////
//! See hw_lradc.h for details.
////////////////////////////////////////////////////////////////////////////////
uint16_t hw_lradc_MeasureInternalDieTemperature(hw_lradc_Channel_t eChannel0,
                                                hw_lradc_Channel_t eChannel1)
{

    uint16_t  ch8Value, ch9Value;

    // Clear the Soft Reset for normal operation
    BF_CLR(LRADC_CTRL0, SFTRST);
    // Clear the Clock Gate for normal operation
    BF_CLR(LRADC_CTRL0, CLKGATE);

    // connect to internal temp sensing
    BF_CLR(LRADC_CTRL2, TEMPSENSE_PWD);
    switch (eChannel0)
    {
        case LRADC_CH0:
            BF_WR(LRADC_CTRL4, LRADC0SELECT, 8);
            break;
        case LRADC_CH1:
            BF_WR(LRADC_CTRL4, LRADC1SELECT, 8);
            break;
        case LRADC_CH2:
            BF_WR(LRADC_CTRL4, LRADC2SELECT, 8);
            break;
        case LRADC_CH3:
            BF_WR(LRADC_CTRL4, LRADC3SELECT, 8);
            break;
        case LRADC_CH4:
            BF_WR(LRADC_CTRL4, LRADC4SELECT, 8);
            break;
        case LRADC_CH5:
            BF_WR(LRADC_CTRL4, LRADC5SELECT, 8);
            break;
        case LRADC_CH6:
            BF_WR(LRADC_CTRL4, LRADC6SELECT, 8);
            break;
        case LRADC_CH7:
            BF_WR(LRADC_CTRL4, LRADC7SELECT, 8);
            break;
        default:
            break;

    }

    switch (eChannel1)
    {
        case LRADC_CH0:
            BF_WR(LRADC_CTRL4, LRADC0SELECT, 9);
            break;
        case LRADC_CH1:
            BF_WR(LRADC_CTRL4, LRADC1SELECT, 9);
            break;
        case LRADC_CH2:
            BF_WR(LRADC_CTRL4, LRADC2SELECT, 9);
            break;
        case LRADC_CH3:
            BF_WR(LRADC_CTRL4, LRADC3SELECT, 9);
            break;
        case LRADC_CH4:
            BF_WR(LRADC_CTRL4, LRADC4SELECT, 9);
            break;
        case LRADC_CH5:
            BF_WR(LRADC_CTRL4, LRADC5SELECT, 9);
            break;
        case LRADC_CH6:
            BF_WR(LRADC_CTRL4, LRADC6SELECT, 9);
            break;
        case LRADC_CH7:
            BF_WR(LRADC_CTRL4, LRADC7SELECT, 9);
            break;
        default:
            break;
    }

    hw_lradc_ScheduleChannel(eChannel0);
    // Wait for conversion complete
    while(hw_lradc_GetInterruptFlag(eChannel0) == 0);
    //Clear interrupt flag
    hw_lradc_ClearInterruptFlag(eChannel0);
    // read temperature value
    ch8Value = hw_lradc_GetAccumValue(eChannel0);
    hw_lradc_ClearAccum(eChannel0);

    hw_lradc_ScheduleChannel(eChannel1);
    // Wait for conversion complete
    while(hw_lradc_GetInterruptFlag(eChannel1) == 0);
    //Clear interrupt flag
    hw_lradc_ClearInterruptFlag(eChannel1);
    // read temperature value
    ch9Value = hw_lradc_GetAccumValue(eChannel1);
    hw_lradc_ClearAccum(eChannel1);

    BF_SET(LRADC_CTRL2, TEMPSENSE_PWD);

    return (uint16_t)((ch9Value-ch8Value)*GAIN_CORRECTION/4000);

}

////////////////////////////////////////////////////////////////////////////////
//! See hw_lradc.h for details.
////////////////////////////////////////////////////////////////////////////////
uint16_t hw_lradc_MeasureBatteryTemperature(hw_lradc_Channel_t BattTempChannel)
{
    uint32_t u32HighCurrentReading = 0;
    uint32_t u32LowCurrentReading = 0;
    uint16_t u16Temp;
    uint16_t i;
    hw_lradc_TempSensor_t TempSensor;

    //--------------------------------------------------------------------------
    // Check the channel.  Only channel 0 or 1 should be used since the others
    // are reserved or cannot induce current.
    //--------------------------------------------------------------------------
    if(BattTempChannel == LRADC_CH0)
    {
        TempSensor = TEMP_SENSOR0;
    }
    else if(BattTempChannel == LRADC_CH1)
    {
        TempSensor = TEMP_SENSOR1;
    }
    else
    {
        return 0;
    }

    //--------------------------------------------------------------------------
    // Enable the temperature sensor.
    //--------------------------------------------------------------------------
    hw_lradc_EnableTempSensor(true);

    //--------------------------------------------------------------------------
    // Setup the temperature sensor for high current measurement.  Wait while
    // the current ramps up.
    //--------------------------------------------------------------------------
    hw_lradc_SetTempSensorCurrent(TempSensor,TEMP_SENSOR_CURRENT_HIGH_READING);
    hw_digctl_MicrosecondWait(TEMP_SENSOR_CURRENT_RAMP_DELAY);

    //--------------------------------------------------------------------------
    // Set up a loop to take a specified number of samples.  Then take the
    // average of the samples.
    //--------------------------------------------------------------------------
    for(i=0;i<NUM_TEMP_READINGS_TO_AVG;i++)
    {
        // Schedule the measurement and wait for it to complete.
        hw_lradc_ScheduleChannel(BattTempChannel);
        while(hw_lradc_GetInterruptFlag(BattTempChannel) == 0);
        hw_lradc_ClearInterruptFlag( BattTempChannel );

        // Read the measurement and then clear the accumulator to prepare
        // for the next reading.
        u32HighCurrentReading += hw_lradc_GetAccumValue(BattTempChannel);
        hw_lradc_ClearAccum( BattTempChannel );
    }
    // Take the average the high current readings.
    u32HighCurrentReading /= NUM_TEMP_READINGS_TO_AVG;

    //--------------------------------------------------------------------------
    // Setup the temperature sensor for low current measurement.  Wait while
    // the current ramps up.
    //--------------------------------------------------------------------------
    hw_lradc_SetTempSensorCurrent(TempSensor,TEMP_SENSOR_CURRENT_LOW_READING);
    hw_digctl_MicrosecondWait(TEMP_SENSOR_CURRENT_RAMP_DELAY);

    //--------------------------------------------------------------------------
    // Set up a loop to take a specified number of samples.  Then take the
    // average of the samples.
    //--------------------------------------------------------------------------
    for(i=0;i<NUM_TEMP_READINGS_TO_AVG;i++)
    {
        // Schedule the measurement and wait for it to complete.
        hw_lradc_ScheduleChannel(BattTempChannel);
        while(hw_lradc_GetInterruptFlag(BattTempChannel) == 0);
        hw_lradc_ClearInterruptFlag( BattTempChannel );

        // Read the measurement and then clear the accumulator to prepare
        // for the next reading.
        u32LowCurrentReading += hw_lradc_GetAccumValue(BattTempChannel);
        hw_lradc_ClearAccum( BattTempChannel );
    }
    // Take the average the low current readings.
    u32LowCurrentReading /= NUM_TEMP_READINGS_TO_AVG;

    //--------------------------------------------------------------------------
    // Turn off the current to the temperature sensor to save power, and disable
    // the temperature sensing block.
    //--------------------------------------------------------------------------
    hw_lradc_SetTempSensorCurrent(TempSensor,TEMP_SENSOR_CURRENT_0UA);
    hw_lradc_EnableTempSensor(false);

    //--------------------------------------------------------------------------
    // Do any LRADC reading to temperature conversions here...
    // Then return the temperature.
    //--------------------------------------------------------------------------
    {
        //----------------------------------------------------------------------
        // This is the conversion if using a 1N4148 diode without compensating
        // for any routing impedance to the diode.
        //----------------------------------------------------------------------
        {
            u16Temp = ((u32HighCurrentReading-u32LowCurrentReading) *
                        TEMP_SENSOR_CONVERSION_CONSTANT)/1000;
        }

    }

    return u16Temp;
}

////////////////////////////////////////////////////////////////////////////////
//! See hw_lradc.h for details.
////////////////////////////////////////////////////////////////////////////////
void hw_lradc_SetTempSensorCurrent(hw_lradc_TempSensor_t TempSensor,
                                   hw_lradc_CurrentMagnitude_t Current)
{
    //--------------------------------------------------------------------------
    // Set channel 0 temperature sensor current.  Turn temp sensor on or off
    // depending on the current magnitude.
    //--------------------------------------------------------------------------
    if(TempSensor == TEMP_SENSOR0)
    {
        HW_LRADC_CTRL2.B.TEMP_ISRC0 = Current;

        if(Current > TEMP_SENSOR_CURRENT_0UA)
        {
            HW_LRADC_CTRL2.B.TEMP_SENSOR_IENABLE0 = 1;
        }
        else
        {
            HW_LRADC_CTRL2.B.TEMP_SENSOR_IENABLE0 = 0;
        }

    }

    //--------------------------------------------------------------------------
    // Set channel 1 temperature sensor current.  Turn temp sensor on or off
    // depending on the current magnitude.
    //--------------------------------------------------------------------------
    if(TempSensor == TEMP_SENSOR1)
    {
        HW_LRADC_CTRL2.B.TEMP_ISRC1 = Current;

        if(Current > TEMP_SENSOR_CURRENT_0UA)
        {
            HW_LRADC_CTRL2.B.TEMP_SENSOR_IENABLE1 = 1;
        }
        else
        {
            HW_LRADC_CTRL2.B.TEMP_SENSOR_IENABLE1 = 0;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
//! See hw_lradc.h for details.
////////////////////////////////////////////////////////////////////////////////
void hw_lradc_EnableTempSensor(bool bEnable)
{
    HW_LRADC_CTRL2.B.TEMPSENSE_PWD = !bEnable;
}


text:
static Window *window;

SimpleMenuLayer *top_menu_layer;

void top_menu_callback(int index, void *context);
static SimpleMenuItem top_menu_items[] = {
    {"Light off", "Toggle raise for light", NULL, (SimpleMenuLayerSelectCallback)top_menu_callback},
    {"Set Start", NULL, NULL, (SimpleMenuLayerSelectCallback)top_menu_callback},
    {"Set Stop", NULL, NULL, (SimpleMenuLayerSelectCallback)top_menu_callback},
};
#define num_top_menu_items (sizeof(top_menu_items) / sizeof(*top_menu_items))

const SimpleMenuSection top_menu_sections = {
    .title="Main menu",
    .items=top_menu_items,
    .num_items=num_top_menu_items
};

Window *time_window=NULL;
TextLayer *time_layer=NULL;

char time_select_text[30];
int time_select_pointer;
int time_select_hours;
int time_select_minutes;
int time_setting;
char *which[2] = {"start", "stop"};
int start_hour;
int start_min;
int stop_hour;
int stop_min;
WakeupId start_alarm_id;
WakeupId stop_alarm_id;

void schedule_wakeup(WakeupId *alarm_id, int hour, int min, int which, int which_mem) {
    time_t now;
    struct tm *now_tick;
    time_t alarm_time;
    int32_t time_inc;

    now = time(0L);
    now_tick = localtime(&now);

    wakeup_cancel(*alarm_id);
    time_inc = ((hour - now_tick->tm_hour) * HOURS) +
               ((min - now_tick->tm_hour) * MINUTES) -
               now_tick->tm_sec;
    alarm_time = now + time_inc;
    *alarm_id = wakeup_schedule(alarm_time, which, false);
    persist_write_int(which_mem, (uint32_t)(*alarm_id));
}

void save_and_initiate_timer(int which) {
    if (which == TIME_START) {
    	persist_write_int(START_HOUR, (uint32_t)start_hour);
    	persist_write_int(START_MINUTE, (uint32_t)start_min);
    	schedule_wakeup(&start_alarm_id, start_hour, start_min, TIME_START, START_ALARM);
    } else {
    	persist_write_int(STOP_HOUR, (uint32_t)stop_hour);
    	persist_write_int(STOP_MINUTE, (uint32_t)stop_min);
    	schedule_wakeup(&stop_alarm_id, stop_hour, stop_min, TIME_STOP, STOP_ALARM);
    }
}

void format_time(void) {
    snprintf(time_select_text, sizeof(time_select_text),
             "Setting\n%s\n%02u:%02u",
             which[time_setting],
             time_select_hours,
             time_select_minutes);
}

static void select_time_handler(ClickRecognizerRef recognizer, void *context) {
    app_log(APP_LOG_LEVEL_WARNING,
            __FILE__,
            __LINE__,
            "Time Click select");

    if (time_select_pointer == TIME_SELECT_HOURS) {
    	time_select_pointer = TIME_SELECT_MINUTES;
    } else {
        app_log(APP_LOG_LEVEL_WARNING,
    	        __FILE__,
    	        __LINE__,
    	        "Time selected is '%s'", time_select_text);
    	if (time_setting == TIME_START) {
    	    start_hour = time_select_hours;
    	    start_min = time_select_minutes;
    	    save_and_initiate_timer(TIME_START);
    	} else {
    	    stop_hour = time_select_hours;
    	    stop_min = time_select_minutes;
    	    save_and_initiate_timer(TIME_START);
    	}

    	window_stack_pop(true);
    }
}

static void up_time_handler(ClickRecognizerRef recognizer, void *context) {
    if (time_select_pointer == TIME_SELECT_HOURS) {
    	time_select_hours++;
    	if (time_select_hours > 23) {
    	    time_select_hours = 0;
    	} else if (time_select_hours < 0) {
    	    time_select_hours = 23;
        }
    } else {
    	time_select_minutes++;
    	if (time_select_minutes > 59) {
    	    time_select_minutes = 0;
    	} else if (time_select_minutes < 0) {
    	    time_select_minutes = 59;
        }
    }
    format_time();
    text_layer_set_text(time_layer, time_select_text);
}

static void down_time_handler(ClickRecognizerRef recognizer, void *context) {
    if (time_select_pointer == TIME_SELECT_HOURS) {
    	time_select_hours--;
    	if (time_select_hours > 23) {
    	    time_select_hours = 0;
    	} else if (time_select_hours < 0) {
    	    time_select_hours = 23;
        }
    } else {
    	time_select_minutes--;
    	if (time_select_minutes > 59) {
    	    time_select_minutes = 0;
        } else if (time_select_minutes < 0) {
    	    time_select_minutes = 59;
        }
    }

    format_time();
    text_layer_set_text(time_layer, time_select_text);
}

static void time_config_provider(void *context) {
    window_single_click_subscribe(BUTTON_ID_SELECT, select_time_handler);
    window_single_click_subscribe(BUTTON_ID_UP, up_time_handler);
    window_single_click_subscribe(BUTTON_ID_DOWN, down_time_handler);

    window_single_repeating_click_subscribe(BUTTON_ID_UP, 100, up_time_handler);
    window_single_repeating_click_subscribe(BUTTON_ID_DOWN, 100, down_time_handler);
}

void set_time(int which) {

    if (!time_window) {
    	time_window = window_create();
    }

    if (!time_layer) {
    	time_layer = text_layer_create(GRect(0, 0, 144, 168));
    }

    text_layer_set_text_alignment(time_layer, GTextAlignmentCenter);
    layer_add_child(window_get_root_layer(time_window), (Layer *)time_layer);

    time_setting = which;
    time_select_pointer = TIME_SELECT_HOURS;
    time_select_hours = (which == TIME_START) ? start_hour : stop_hour;
    time_select_minutes = (which == TIME_START) ? start_min : stop_min;
    format_time();
    text_layer_set_text(time_layer, time_select_text);
    window_set_click_config_provider(time_window, time_config_provider);

    window_stack_push(time_window, true);
}

void top_menu_callback(int index, void *context) {
    app_log(APP_LOG_LEVEL_WARNING,
            __FILE__,
            __LINE__,
            "Main Menu callback on row %d\n", index);

    switch (index) {
        case 0: // toggle auto-backlight
        	if (app_worker_is_running()) {
                app_log(APP_LOG_LEVEL_DEBUG, __FILE__, __LINE__, "Lights off");
        	    top_menu_items[index].title = "Light off";
                layer_mark_dirty(simple_menu_layer_get_layer(top_menu_layer));
        	    app_worker_kill();
        	} else {
                app_log(APP_LOG_LEVEL_DEBUG, __FILE__, __LINE__, "Lights on");
        	    top_menu_items[index].title = "Light on";
                layer_mark_dirty(simple_menu_layer_get_layer(top_menu_layer));
        	    app_worker_launch();
        	}
        	break;
        case 1: // Set Start Time
        	set_time(TIME_START);
        	return;
        case 2: // Set Start Time
        	set_time(TIME_STOP);
        	return;
    }
}

static void window_load(Window *window) {
    Layer *window_layer = window_get_root_layer(window);
    GRect bounds = layer_get_bounds(window_layer);

    if (app_worker_is_running()) {
        top_menu_items[0].title = "Light on";
    } else {
        top_menu_items[0].title = "Light off";
    }

    top_menu_layer = simple_menu_layer_create(layer_get_frame(window_layer), window, &top_menu_sections, num_top_menu_sections, NULL);
    #ifdef PBL_COLOR
        menu_layer_set_normal_colors(simple_menu_layer_get_menu_layer(top_menu_layer), GColorBlack, GColorWhite);
        menu_layer_set_highlight_colors(simple_menu_layer_get_menu_layer(top_menu_layer), GColorGreen, GColorBlack);
    #endif
    layer_add_child(window_layer, simple_menu_layer_get_layer(top_menu_layer));
}

static void window_unload(Window *window) {
    simple_menu_layer_destroy(top_menu_layer);
}

void read_alarm_data(void) {
    uint32_t val;

    val = persist_read_int(START_ALARM);
    if (val) {
    	start_alarm_id = (WakeupId)val;
    	APP_LOG(APP_LOG_LEVEL_DEBUG, "start_alarm_id=%u", (uint)val);
    }

    val = persist_read_int(STOP_ALARM);
    if (val) {
    	stop_alarm_id = (WakeupId)val;
    	APP_LOG(APP_LOG_LEVEL_DEBUG, "stop_alarm_id=%u", (uint)val);
    }

    val = persist_read_int(START_HOUR);
    if (val) {
    	start_hour = (int)val;
    	APP_LOG(APP_LOG_LEVEL_DEBUG, "start_hour=%u", (uint)val);
    }
    val = persist_read_int(START_MINUTE);
    if (val) {
    	start_min = (int)val;
    	APP_LOG(APP_LOG_LEVEL_DEBUG, "start_min=%u", (uint)val);
    }

    val = persist_read_int(STOP_HOUR);
    if (val) {
    	stop_hour = (int)val;
    	APP_LOG(APP_LOG_LEVEL_DEBUG, "stop_hour=%u", (uint)val);
    }

    val = persist_read_int(STOP_MINUTE);
    if (val) {
    	stop_min = (int)val;
    	APP_LOG(APP_LOG_LEVEL_DEBUG, "stop_min=%u", (uint)val);
    }
}

void handle_wakeup(WakeupId id, int32_t cookie) {
    if (cookie == TIME_START) {
    	app_worker_launch();
    	wakeup_cancel(start_alarm_id);
    	schedule_wakeup(&start_alarm_id, start_hour, start_min, TIME_START, START_ALARM);
    } else {
    	app_worker_kill();
    	wakeup_cancel(stop_alarm_id);
    	schedule_wakeup(&stop_alarm_id, stop_hour, stop_min, TIME_STOP, STOP_ALARM);
    }
}

static void init(void) {
    window = window_create();
    window_set_window_handlers(window, (WindowHandlers) {
    	.load = window_load,
    	.unload = window_unload,
    });
    #ifdef PBL_COLOR
        window_set_background_color(window, GColorBlack);
    #endif
    window_stack_push(window, true);
}

static void deinit(void) {
    window_destroy(window);
}

int main(void) {
    AppLaunchReason reason;
    WakeupId id = 0;
    int32_t cookie;
    reason = launch_reason();

    if (reason == APP_LAUNCH_WAKEUP) {
    	wakeup_get_launch_event(&id, &cookie);
    	read_alarm_data();
    	handle_wakeup(id, cookie);
    } else {
    	init();
    	APP_LOG(APP_LOG_LEVEL_DEBUG, "Done initializing, pushed window: %p", window);
    	app_event_loop();
    	deinit();
    }
}


text:
// Copyright (c) Benjamin Proemmer. All rights reserved.
// See License in the project root for license information.

using System;

namespace Dacs7
{
    public class Dacs7ReadTimeoutException : Exception
    {
        public Dacs7ReadTimeoutException(ushort id) : base($"Read operation timeout for job {id}")
        {
        }

        public Dacs7ReadTimeoutException()
        {
        }

        public Dacs7ReadTimeoutException(string message) : base(message)
        {
        }

        public Dacs7ReadTimeoutException(string message, Exception innerException) : base(message, innerException)
        {
        }
    }
}


text:
package org.jsmiparser;

import org.jsmiparser.smi.*;
import org.junit.Test;

import java.net.URISyntaxException;
import java.util.List;

import static org.junit.Assert.*;

public class IfMibTest extends AbstractMibTestCase {

    public IfMibTest() {
        super(SmiVersion.V2, "libsmi-0.4.5/mibs/iana/IANAifType-MIB",
                "libsmi-0.4.5/mibs/ietf/IF-MIB");
    }

    @Test
    public void testSizes() {
        assertEquals(44, getMib().getScalars().size());
        assertEquals(57, getMib().getColumns().size());

        SmiModule ifMib = getMib().findModule("IF-MIB");
        assertNotNull(ifMib);

        assertEquals(3, ifMib.getScalars().size());
        assertEquals(22 + 19 + 3 + 3 + 6, ifMib.getColumns().size());

        assertNotNull(ifMib.findScalar("ifNumber"));
        assertNull(ifMib.findColumn("ifNumber"));

        assertNotNull(ifMib.findColumn("ifName"));
        assertNull(ifMib.findScalar("ifName"));
    }

    @Test
    public void testInterfaceIndex() {
        assertEquals(7, getMib().getModules().size());

        SmiTextualConvention interfaceIndex = getMib().getTextualConventions()
                .find("InterfaceIndex");
        assertNotNull(interfaceIndex);
        assertEquals("InterfaceIndex", interfaceIndex.getId());
        assertEquals("IF-MIB", interfaceIndex.getModule().getId());
        String source = interfaceIndex.getModule().getIdToken().getLocation()
                .getSource();
        assertTrue(source.contains("IF-MIB"));
        assertEquals(SmiTextualConvention.class, interfaceIndex.getClass());
        assertNotNull(interfaceIndex.getRangeConstraints());
        assertEquals(1, interfaceIndex.getRangeConstraints().size());
        assertSame(getInteger32(), interfaceIndex.getBaseType());
        assertEquals(SmiPrimitiveType.INTEGER_32,
                interfaceIndex.getPrimitiveType());
        assertEquals(SmiConstants.INTEGER_TYPE, interfaceIndex.getBaseType()
                .getBaseType());
        assertNull(interfaceIndex.getBaseType().getBaseType().getBaseType());
        assertEquals("d", interfaceIndex.getDisplayHint());
        assertEquals(StatusV2.CURRENT, interfaceIndex.getStatusV2());
        assertTrue(interfaceIndex.getDescription().startsWith("A unique value"));
        assertFalse(interfaceIndex.getDescription().endsWith("\""));
        assertNull(interfaceIndex.getReference());

        assertNull(interfaceIndex.getEnumValues());
        assertNull(interfaceIndex.getBitFields());
        assertNull(interfaceIndex.getFields());
        assertNull(interfaceIndex.getSizeConstraints());
    }

    @Test
    public void testIfTable() throws URISyntaxException {

        SmiMib mib = getMib();

        SmiTable ifTable = mib.getTables().find("ifTable");
        assertNotNull(ifTable);
        assertEquals("1.3.6.1.2.1.2.2", ifTable.getOidStr());

        SmiRow ifEntry = mib.getRows().find("ifEntry");
        assertNotNull(ifEntry);
        assertSame(ifTable.getNode(), ifEntry.getNode().getParent());
        assertSame(ifTable, ifEntry.getTable());
        assertSame(ifEntry, ifTable.getRow());
        assertEquals("1.3.6.1.2.1.2.2.1", ifEntry.getOidStr());
        assertSame(ifTable, ifEntry.getTable());

        SmiVariable ifIndex = mib.getVariables().find("ifIndex");
        assertNotNull(ifIndex);
        assertSame(ifEntry.getNode(), ifIndex.getNode().getParent());
        assertSame(ifTable.getNode(), ifIndex.getNode().getParent().getParent());
        assertEquals("1.3.6.1.2.1.2.2.1.1", ifIndex.getOidStr());
        SmiTextualConvention interfaceIndex = getMib().getTextualConventions()
                .find("InterfaceIndex");
        assertNotNull(interfaceIndex);
        assertSame(interfaceIndex, ifIndex.getType());

        List<SmiIndex> ifIndexes = ifEntry.getIndexes();
        assertEquals(1, ifIndexes.size());
        SmiIndex index = ifIndexes.get(0);
        assertSame(ifIndex, index.getColumn());
        assertSame(ifEntry, index.getRow());
        assertEquals(false, index.isImplied());

        SmiVariable ifAdminStatus = mib.getVariables().find("ifAdminStatus");
        assertNotNull(ifAdminStatus);
        assertEquals(ifEntry, ifAdminStatus.getRow());
        assertEquals(ifTable, ifAdminStatus.getTable());
        assertEquals("1.3.6.1.2.1.2.2.1.7", ifAdminStatus.getOidStr());
        assertSame(ifEntry.getNode(), ifAdminStatus.getNode().getParent());

        SmiType ifAdminStatusType = ifAdminStatus.getType();
        assertSame(SmiPrimitiveType.ENUM, ifAdminStatusType.getPrimitiveType());
        assertEquals(SmiConstants.INTEGER_TYPE, ifAdminStatusType.getBaseType());
        assertNull(ifAdminStatusType.getBaseType().getBaseType());
        assertEquals(3, ifAdminStatusType.getEnumValues().size());
        assertEquals("up", ifAdminStatusType.getEnumValues().get(0).getId());
        assertEquals(1, ifAdminStatusType.getEnumValues().get(0).getValue()
                .intValue());
        assertEquals("down", ifAdminStatusType.getEnumValues().get(1).getId());
        assertEquals(2, ifAdminStatusType.getEnumValues().get(1).getValue()
                .intValue());
        assertEquals("testing", ifAdminStatusType.getEnumValues().get(2)
                .getId());
        assertEquals(3, ifAdminStatusType.getEnumValues().get(2).getValue()
                .intValue());

        // mib.getRootNode().dumpTree(System.out, "");

        List<SmiVariable> columns = ifTable.getRow().getColumns();
        assertEquals(22, columns.size());
        assertTrue(columns.contains(ifIndex));
        assertTrue(columns.contains(ifAdminStatus));

        SmiModule ifMib = mib.findModule("IF-MIB");
        assertNotNull(ifMib);
        System.out.println(mib.getVariables().size() + mib.getTables().size()
                + mib.getRows().size());

        checkOidTree(mib);
    }

    @Test
    public void testFindByOidPrefix() {
        SmiMib mib = getMib();

        SmiVariable ifAdminStatus = mib.getVariables().find("ifAdminStatus");
        assertNotNull(ifAdminStatus);
        assertEquals("1.3.6.1.2.1.2.2.1.7", ifAdminStatus.getOidStr());

        int[] adminStatusOfInterface0x1101 = new int[]{1, 3, 6, 1, 2, 1, 2,
                2, 1, 7, 0x1101};
        SmiOidNode result = mib.findByOidPrefix(adminStatusOfInterface0x1101);
        assertSame(ifAdminStatus.getNode(), result);
        assertEquals(adminStatusOfInterface0x1101.length,
                result.getOid().length + 1);
    }

    @Test
    public void testFindByOid() {
        SmiMib mib = getMib();

        SmiVariable ifAdminStatus = mib.getVariables().find("ifAdminStatus");
        assertNotNull(ifAdminStatus);
        assertEquals("1.3.6.1.2.1.2.2.1.7", ifAdminStatus.getOidStr());

        SmiOidNode result = mib.findByOid(1, 3, 6, 1, 2, 1, 2, 2, 1, 7);
        assertNotNull(result);
        assertSame(ifAdminStatus.getNode(), result);

        result = mib.findByOid(1, 3);
        assertNotNull(result);
        assertEquals(1, result.getValues().size());
        assertEquals("org", result.getValues().get(0).getId());
    }

}


text:
package com.google.javascript.jscomp;

import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;

/**
 * Rewrite block-scoped function declarations as "let"s.  This pass must happen before
 * Es6RewriteBlockScopedDeclaration, which rewrites "let" to "var".
 */
public final class Es6RewriteBlockScopedFunctionDeclaration extends AbstractPostOrderCallback
    implements HotSwapCompilerPass {

  private final AbstractCompiler compiler;
  private static final FeatureSet transpiledFeatures =
      FeatureSet.BARE_MINIMUM.with(Feature.BLOCK_SCOPED_FUNCTION_DECLARATION);

  public Es6RewriteBlockScopedFunctionDeclaration(AbstractCompiler compiler) {
    this.compiler = compiler;
  }

  @Override
  public void process(Node externs, Node root) {
    TranspilationPasses.processTranspile(compiler, root, transpiledFeatures, this);
    TranspilationPasses.maybeMarkFeaturesAsTranspiledAway(compiler, transpiledFeatures);
  }

  @Override
  public void hotSwapScript(Node scriptRoot, Node originalRoot) {
    TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, transpiledFeatures, this);
    TranspilationPasses.maybeMarkFeaturesAsTranspiledAway(compiler, transpiledFeatures);
  }

  @Override
  public void visit(NodeTraversal t, Node n, Node parent) {
    if (n.isFunction()
        && parent != null
        && parent.isBlock()
        && !parent.getParent().isFunction()) {
      // Only consider declarations (all expressions have non-block parents) that are not directly
      // within a function or top-level.
      visitBlockScopedFunctionDeclaration(t, n, parent);
    }
  }

  /**
   * Rewrite the function declaration from:
   *
   *

   *   function f() {}
   *   FUNCTION
   *     NAME x
   *     PARAM_LIST
   *     BLOCK
   *

   *
   * to
   *
   *

   *   let f = function() {};
   *   LET
   *     NAME f
   *       FUNCTION
   *         NAME (w/ empty string)
   *         PARAM_LIST
   *         BLOCK
   *

   *
   * This is similar to {@link Normalize.NormalizeStatements#rewriteFunctionDeclaration} but
   * rewrites to "let" instead of "var".
   */
  private void visitBlockScopedFunctionDeclaration(NodeTraversal t, Node n, Node parent) {
    // Prepare a spot for the function.
    Node oldNameNode = n.getFirstChild();
    Node fnNameNode = oldNameNode.cloneNode();
    Node let = IR.declaration(fnNameNode, Token.LET).srcref(n);
    NodeUtil.addFeatureToScript(t.getCurrentScript(), Feature.LET_DECLARATIONS, compiler);

    // Prepare the function.
    oldNameNode.setString("");
    compiler.reportChangeToEnclosingScope(oldNameNode);

    // Move the function to the front of the parent.
    parent.removeChild(n);
    parent.addChildToFront(let);
    compiler.reportChangeToEnclosingScope(let);
    fnNameNode.addChildToFront(n);
  }
}


text:
import { DateFormat, DATE_FORMAT, formatDate } from "common/format/datetime";
import React from "react";
import { injectIntl, IntlShape } from "react-intl";

class CustomDate extends React.PureComponent<Props> {
  render() {
    const { intl, date, format = DATE_FORMAT } = this.props;

    const dateObject = new Date(date);
    if (!dateObject) {
      return null;
    }

    if (!dateObject.getTime || isNaN(dateObject.getTime())) {
      console.warn("CustomDate was passed an invalid date: ", this.props.date);
      return null;
    }

    return <>{formatDate(dateObject, intl.locale, format)}</>;
  }
}

interface Props {
  date: Date | string;
  format?: DateFormat;
  intl: IntlShape;
}

export default injectIntl(CustomDate);


text:
<?php
namespace observr\Subject {
    use observr\Observer as Observer;

    trait FixtureTrait {
        /**
         * Check if subject has observers
         * @return boolean
         */
        public function isWatched() {
            return Observer::hasObservers($this);
        }

        /**
         * Check if subject state is valid
         * @param string $name
         * @return boolean
         */
        public function isState($name) {
            return Observer::isState($this,$name);
        }

        /**
         * Retrieve subject states
         * @return type
         */
        public function getState() {
            return Observer::getState($this);
        }

        /**
         * Update subject states and notifies observers
         * @param string $name
         * @param mixed $e
         * @return mixed
         */
        public function setState($name,$e=null) {
            return Observer::setState($this,$name,$e);
        }

        /**
         * Remove subject state container
         * @param mixed $name
         */
        public function unsetState($name = null) {
            Observer::unsetState($this,$name);
        }
    }
}


text:
#include <stdio.h>
#include <string.h>

#include "oauth.h" // base64 encode fn's.
#include "xmalloc.h"
#ifndef PSP
	#include "sha1.h"
	typedef SHA1Context SHA1Context_t;
#else
	#include <psputils.h>
	typedef SceKernelUtilsSha1Context SHA1Context_t;
	#define SHA1Reset(ctx) 				sceKernelUtilsSha1BlockInit(ctx)
	#define SHA1Input(ctx, key, len)	sceKernelUtilsSha1BlockUpdate(ctx, (u8 *)key, (u32)len)
	#define SHA1Result(ctx, digest) 	sceKernelUtilsSha1BlockResult(ctx, (u8 *)digest)
#endif

static
void hmac_sha1(const unsigned char *key, size_t keylen, const unsigned char *in, size_t inlen, unsigned char *resbuf)
{
	const int IPAD = 0x36;
	const int OPAD = 0x5c;

	SHA1Context_t inner;
	SHA1Context_t outer;
	SHA1Context_t keyhash;
	unsigned char tmpkey[20];
	unsigned char digest[20];
	unsigned char block[64];
	size_t i;

	if (keylen > 64) {
		SHA1Reset(&keyhash);
		SHA1Input(&keyhash, key, keylen);
		SHA1Result(&keyhash, tmpkey);
		key = tmpkey;
		keylen = 20;
	}

	for (i = 0; i < sizeof(block); i++) {
		block[i] = IPAD ^ (i < keylen ? key[i] : 0);
	}

	SHA1Reset(&inner);
	SHA1Input(&inner, block, 64);
	SHA1Input(&inner, in, inlen);
	SHA1Result(&inner, digest);

	for (i = 0; i < sizeof(block); i++) {
		block[i] = OPAD ^ (i < keylen ? key[i] : 0);
	}

	SHA1Reset(&outer);
	SHA1Input(&outer, block, 64);
	SHA1Input(&outer, digest, 20);
	SHA1Result(&outer, resbuf);
}

char *oauth_sign_hmac_sha1_raw(const char *m, size_t ml, const char *k, size_t kl)
{
	unsigned char result[20];
	hmac_sha1((unsigned char *)k, kl, (unsigned char *)m, ml, result);
	return oauth_encode_base64(20, result);
}

char *oauth_sign_hmac_sha1(const char *m, const char *k)
{
	return oauth_sign_hmac_sha1_raw(m, strlen(m), k, strlen(k));
}

char *oauth_body_hash_file(char *filename)
{
	size_t len = 0;
	char data[4096];
	SHA1Context_t ctx;
	FILE *fp = NULL;
	unsigned char *digest;

#ifdef WIN32
	fp = fopen(filename, "rb");
#else
	fp = fopen(filename, "r");
#endif
	if (!fp) {
		return NULL;
	}

	SHA1Reset(&ctx); // init sha1

	// read file
	while ((len = fread(data, sizeof(unsigned char), sizeof data, fp)) > 0) {
		SHA1Input(&ctx, data, len);
	}

	fclose(fp);

	digest = (unsigned char *)xmalloc(20 * sizeof(unsigned char));
	SHA1Result(&ctx, digest);
	return oauth_body_hash_encode(20, digest);
}

char *oauth_body_hash_data(size_t length, const char *data)
{
	SHA1Context_t ctx;
	unsigned char *digest;

	SHA1Reset(&ctx);

/*	while( length-- > 0 ) {
		SHA1Input(&ctx, *data++, 1);
	}
*/
	SHA1Input(&ctx, data, length);

	digest = (unsigned char *)xmalloc(20 * sizeof(unsigned char));
	SHA1Result(&ctx, digest);
	return oauth_body_hash_encode(20, digest);
}

char *oauth_sign_rsa_sha1(const char *m, const char *k)
{
	/* NOT RSA/PK11 support */
	return xstrdup("---RSA/PK11-is-not-supported-by-this-version-of-liboauth---");
}

int oauth_verify_rsa_sha1(const char *m, const char *c, const char *sig)
{
	/* NOT RSA/PK11 support */
	return -1; // mismatch , error
}


text:
#import <Foundation/Foundation.h>

@class NuMethod;
@class NuBlock;

/*!
    @class NuClass
    @abstract A Nu wrapper for class representations in the Objective-C runtime.
    @discussion NuClass provides an object wrapper for classes that are represented in the Objective-C runtime.
    NuClass objects are used in the Nu language to manipulate and extend Objective-C classes.
 */
@interface NuClass : NSObject
{
    Class c;
    BOOL isRegistered;
}

/*! Create a class wrapper for the specified class (used from Objective-C). */
+ (NuClass *) classWithClass:(Class) class;
/*! Create a class wrapper for the named Objective-C class. */
+ (NuClass *) classWithName:(NSString *)string;
/*! Initialize a class wrapper for the specified class (used from Objective-C). */
- (id) initWithClass:(Class) class;
/*! Initialize a class wrapper for the named Objective-C class. */
- (id) initWithClassNamed:(NSString *) name;
/*! Get the class corresponding to the NuClass wrapper (used from Objective-C). */
- (Class) wrappedClass;
/*! Get an array of all classes known to the Objective-C runtime.
Beware, some of these classes may be deprecated, undocumented, or otherwise unsafe to use. */
+ (NSArray *) all;
/*! Get the name of a class. */
- (NSString *) name;
/*! Get an array containing NuMethod representations of the class methods of a class. */
- (NSArray *) classMethods;
/*! Get an array containing NuMethod representations of the instance methods of a class. */
- (NSArray *) instanceMethods;
/*! Get an array containing the names of the class methods of a class. */
- (NSArray *) classMethodNames;
/*! Get an array containing the names of the instance methods of a class. */
- (NSArray *) instanceMethodNames;
/*! Determine whether a class is derived from another class. */
- (BOOL) isDerivedFromClass:(Class) parent;
/*! Compare a class with another class by name.  This allows arrays of classes to be easily sorted. */
- (NSComparisonResult) compare:(NuClass *) anotherClass;
/*! Get a class method by name. */
- (NuMethod *) classMethodWithName:(NSString *) methodName;
/*! Get an instance method by name. */
- (NuMethod *) instanceMethodWithName:(NSString *) methodName;
/*! Compare two classes for equality. */
- (BOOL) isEqual:(NuClass *) anotherClass;
/*! Change the superclass of a class. Be careful with this. */
- (void) setSuperclass:(NuClass *) newSuperclass;
/*! Add an instance method to a class with the specified name, type signature, and body. */
- (id) addInstanceMethod:(NSString *) methodName signature:(NSString *)signature body:(NuBlock *) block;
/*! Add a class method to a class with the specified name, type signature, and body. */
- (id) addClassMethod:(NSString *) methodName signature:(NSString *)signature body:(NuBlock *) block;
/*! Add an instance variable to the receiving class. This will cause problems if there are already instances of the receiving class. */
- (id) addInstanceVariable:(NSString *)variableName signature:(NSString *) signature;

- (BOOL) isRegistered;
- (void) setRegistered:(BOOL) value;
- (void) registerClass;
@end

@class NuBlock;

id add_method_to_class(Class c, NSString *methodName, NSString *signature, NuBlock *block);


text:
package com.skf.mokao.serviceImpl;

import com.skf.mokao.dao.ProxyipsMapper;
import com.skf.mokao.pojo.Proxyips;
import com.skf.mokao.service.ProxyipsService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Koofun on 2017/9/14.
 */
@Service
public class ProxyipsImpl implements ProxyipsService {

    @Autowired
    private ProxyipsMapper proxyipsMapper;

    @Override
    public Proxyips selectByRandom() {
        Proxyips proxyips = null;
        try {
            proxyips = proxyipsMapper.selectByRandom();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //TODO 同步redis

        return proxyips;
    }

    @Override
    public Proxyips selectById(int id) {
        Proxyips proxyips = null;
        try {
            proxyips = proxyipsMapper.selectById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return proxyips;
    }

    @Override
    public List<Proxyips> selectAll() {
        List<Proxyips> proxyipsList = null;
        try {
            proxyipsList = proxyipsMapper.selectAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return proxyipsList;
    }

    /**
     *
     * @return
     */
    @Override
    public Integer selectCount() {
        int count = 0;
        try {
            count = proxyipsMapper.selectCount();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 插入新代理
     * @param proxyips 代理实体
     * @return 0:插入失败 1:插入成功
     */
    @Override
    public int insert(Proxyips proxyips) {
        int insert = 0;
        try {
            insert = proxyipsMapper.insert(proxyips);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return insert;
    }

    /**
     *
     * @param proxyips 代理IP
     * @param proxyips 代理实体
     * @return 0:更新失败 1:更新成功
     */
    @Override
    public int update(Proxyips proxyips) {
        int update = 0;
        //
        try {
            if (proxyips != null && proxyips.getId() != null) {
                update = proxyipsMapper.update(proxyips);
            }
            //有则更新 无则插入
            else if (proxyips != null){
                update = proxyipsMapper.insert(proxyips);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return update;
    }

    /**
     *
     * @param id 代理IP
     * @return 0:删除失败 1:删除成功
     */
    @Override
    public int deleteById(int id) {
        int delete = 0;
        try {
            delete = proxyipsMapper.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return delete;
    }
}


text:
<?php
class Kwc_Cc_PageTree_Master_Category_PagesModel extends Kwc_Root_Category_GeneratorModel
{
    public function __construct($config = array())
    {
        $config['proxyModel'] = new Kwf_Model_FnF(array(
            'data' => array(
                array('id'=>1, 'pos'=>1, 'visible'=>true, 'name'=>'Seite 1', 'filename' => '1', 'parent_id'=>'root-master-main',   'component'=>'none', 'is_home'=>true,  'hide'=>false, 'custom_filename' => false),
                array('id'=>2, 'pos'=>2, 'visible'=>true, 'name'=>'Seite 2', 'filename' => '2', 'parent_id'=>'root-master-main',   'component'=>'none', 'is_home'=>false, 'hide'=>false, 'custom_filename' => false),
                array('id'=>3, 'pos'=>3, 'visible'=>true, 'name'=>'Seite 3', 'filename' => '3', 'parent_id'=>'root-master-main',   'component'=>'none', 'is_home'=>false, 'hide'=>false, 'custom_filename' => false),
                array('id'=>4, 'pos'=>1, 'visible'=>true, 'name'=>'Seite 4', 'filename' => '4', 'parent_id'=>'1',                  'component'=>'none', 'is_home'=>false, 'hide'=>false, 'custom_filename' => false),
                array('id'=>5, 'pos'=>1, 'visible'=>true, 'name'=>'Seite 5', 'filename' => '5', 'parent_id'=>'root-master-bottom', 'component'=>'none', 'is_home'=>false, 'hide'=>false, 'custom_filename' => false),
            )
        ));
        parent::__construct($config);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
All Classes (developers-notification 0.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2018-01-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Config

Constants

DevelopersNotification

DevelopersNotificationAppender

DevelopersNotificationLogger

DevelopersNotificationMessenger

DevelopersNotificationUtil

FrequencyOfSending

HttpClient

HttpResponse

Integration

InternalUtil

Lifetime

MessageTypes

Messenger

Monitoring

MonitorProcessor

SentMessage

SlackImpl

SpamProtection

Task

TelegramImpl


text:
import Bill from './common/models/BillModel'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import AppComponent from './main/AppComponent'
import { initDb } from './common/providers/dbProvider'
import { get } from './common/providers/settingsProvider'
import { init as initBillsRepo } from './common/repositories/billsRepository'
import { init as initExpensesRepo } from './common/repositories/expensesRepository'
import { init as initCustomersRepo } from './common/repositories/customersRepository'
import { init as initBillFilesRepo } from './common/repositories/billFilesRepository'
import { init as initExpenseFilesRepo } from './common/repositories/expenseFilesRepository'
import { init as initBillTypesRepo } from './common/repositories/billTypesRepository'
import { init as initBillItemsRepo } from './common/repositories/billItemsRepository'
import { init as initExpenseItemsRepo } from './common/repositories/expenseItemsRepository'
import { init as initExpenseTypesRepo } from './common/repositories/expenseTypesRepository'
import { listBills } from './common/services/billsService'
import { listExpenses } from './common/services/expensesService'

async function init() {
  let bills, expenses

  try {
    const knexConfig = await get('knex')
    const knexInstance = await initDb(knexConfig)
    initBillsRepo(knexInstance)
    initExpensesRepo(knexInstance)
    initCustomersRepo(knexInstance)
    initBillFilesRepo(knexInstance)
    initExpenseFilesRepo(knexInstance)
    initBillTypesRepo(knexInstance)
    initBillItemsRepo(knexInstance)
    initExpenseItemsRepo(knexInstance)
    initExpenseTypesRepo(knexInstance); // semicolon intended

    [bills, expenses] = await Promise.all([
      listBills(),
      listExpenses()
    ])
  } catch (err) {
    alert('Could not load initial data: ' + err.message)
    return
  }

  ReactDOM.render(
    <div>
      <AppComponent bills={bills} expenses={expenses} />
    </div>,
    document.getElementById('app')
  )
}

init()


text:
package provider

import "errors"

var (
	ErrInstanceNotExist   = errors.New("instance does not exist")
	ErrHostnameDuplicated = errors.New("instance hostname duplicated")
	ErrDiskNotExist       = errors.New("disk does not exist")
	ErrDiskTagDuplicated  = errors.New("disk tags duplicated")
)


text:
class FacebookAccountsController < ApplicationController
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spark.Modules;

namespace Modular.Common.Services
{
    public interface IHighScoreRepository : IService
    {
        void AddHighScore(DateTime victoryUtc, string name, int score, object gameState, object reviewLinkValues);
        IEnumerable<HighScoreEntry> ListScores();
    }

    public class HighScoreRepository : IHighScoreRepository
    {
        private IEnumerable<HighScoreEntry> _entries = new HighScoreEntry[0];

        public void AddHighScore(DateTime victoryUtc, string name, int score, object gameState, object reviewLinkValues)
        {
            var entries = new List<HighScoreEntry>
                              {
                                  new HighScoreEntry
                                      {
                                          VictoryUrc = victoryUtc,
                                          Name = name,
                                          Score = score,
                                          GameState = gameState,
                                          ReviewLinkValues = reviewLinkValues
                                      }
                              };
            entries.AddRange(_entries);
            _entries = entries.Take(50);
        }

        public IEnumerable<HighScoreEntry> ListScores()
        {
            return _entries;
        }
    }

    public class HighScoreEntry
    {
        public DateTime VictoryUrc { get; set; }
        public string Name { get; set; }
        public int Score { get; set; }
        public object GameState { get; set; }
        public object ReviewLinkValues { get; set; }
    }
}