text:
<!DOCTYPE HTML>

        <title>My Artical</title>
        <link rel="stylesheet" type="text/css" href="<?php echo base_url('css/bootstrap.css')?>" />
        <link rel="stylesheet" type="text/css" href="<?php echo base_url().'css/bootstrap.min.css'?>" />
        <link rel="stylesheet" type="text/css" href="<?php echo base_url().'css/bootstrap-theme.css'?>" />
        <link rel="stylesheet" type="text/css" href="<?php echo base_url().'css/my_style_sheet.css'?>" />
        <link rel="stylesheet" type="text/css" href="<?php echo base_url().'js/jquery-3.2.1.js'?>" />
        <link rel="stylesheet" type="text/css" href="<?php echo base_url().'js/jquery-3.2.1.min.js'?>" />
        <link rel="stylesheet" type="text/css" href="<?php echo base_url().'js/script.js'?>" />

My Article

redpajama_set_name: RedPajamaGithub


text:
import unittest

from pymatgen.ext.jhu import get_kpoints
from pymatgen.io.vasp.sets import MPRelaxSet
from pymatgen.util.testing import PymatgenTest

__author__ = "Joseph Montoya"
__copyright__ = "Copyright 2017, The Materials Project"
__maintainer__ = "Joseph Montoya"
__email__ = "montoyjh@lbl.gov"
__date__ = "June 22, 2017"

@unittest.skipIf(True, "This code is way too buggy to be tested.")
class JhuTest(PymatgenTest):
    _multiprocess_shared_ = True

    def test_get_kpoints(self):
        si = PymatgenTest.get_structure("Si")
        input_set = MPRelaxSet(si)
        kpoints = get_kpoints(si, incar=input_set.incar)

if __name__ == "__main__":
    unittest.main()


text:
package com.taobao.weex.ui.animation;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;

import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.WXSDKManager;
import com.taobao.weex.common.WXModule;
import com.taobao.weex.common.WXModuleAnno;
import com.taobao.weex.dom.WXDomHandler;
import com.taobao.weex.dom.WXDomTask;
import com.taobao.weex.ui.component.WXComponent;
import com.taobao.weex.ui.view.WXBackgroundDrawable;
import com.taobao.weex.utils.WXLogUtils;
import com.taobao.weex.utils.WXResourceUtils;

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

public class WXAnimationModule extends WXModule {

  @WXModuleAnno
  public void transition(@Nullable String ref, @Nullable String animation, @Nullable String callBack) {
    if(!TextUtils.isEmpty(ref)&&!TextUtils.isEmpty(animation)) {
      Message msg = Message.obtain();
      WXDomTask task = new WXDomTask();
      task.instanceId = mWXSDKInstance.getInstanceId();
      task.args = new ArrayList<>();
      task.args.add(ref);
      task.args.add(animation);
      task.args.add(callBack);
      msg.what = WXDomHandler.MsgType.WX_ANIMATION;
      msg.obj = task;
      WXSDKManager.getInstance().getWXDomManager().sendMessage(msg);
    }
  }

  public static void startAnimation(WXSDKInstance mWXSDKInstance, WXComponent component,
                                    @NonNull WXAnimationBean animationBean, @Nullable String callback) {
    if(component == null){
      return;
    }
    try {
      Animator animator = createAnimator(animationBean, component.getHostView());
      if (animator != null) {
        Animator.AnimatorListener animatorCallback = createAnimatorListener(mWXSDKInstance, callback);
        component.getHostView().setLayerType(View.LAYER_TYPE_HARDWARE,null);
        Interpolator interpolator = createTimeInterpolator(animationBean);
        if (animatorCallback != null) {
          animator.addListener(animatorCallback);
        }
        if (interpolator != null) {
          animator.setInterpolator(interpolator);
        }
        animator.setDuration(animationBean.duration);
        animator.start();
      }
    } catch (RuntimeException e) {
      e.printStackTrace();
      WXLogUtils.e("", e);
    }
  }

  private static @Nullable
  ObjectAnimator createAnimator(@NonNull WXAnimationBean animation, @NonNull View target) {
    if(animation == null || target == null){
      return null;
    }
    WXAnimationBean.Style style = animation.styles;
    if (style != null) {
      ObjectAnimator animator;
      List<PropertyValuesHolder> holders =style.getHolders();
      if (!TextUtils.isEmpty(style.backgroundColor)) {
        if (target.getBackground() instanceof WXBackgroundDrawable) {
          holders.add(PropertyValuesHolder.ofObject(
              WXAnimationBean.Style.BACKGROUND_COLOR, new ArgbEvaluator(),
              ((WXBackgroundDrawable) target.getBackground()).getColor(),
              WXResourceUtils.getColor(style.backgroundColor)));
        } else if (target.getBackground() instanceof ColorDrawable) {
          holders.add(PropertyValuesHolder.ofObject(
              WXAnimationBean.Style.BACKGROUND_COLOR, new ArgbEvaluator(),
              ((ColorDrawable) target.getBackground()).getColor(),
              WXResourceUtils.getColor(style.backgroundColor)));
        }
      }
      if (style.getPivot() != null) {
        Pair<Float, Float> pair = style.getPivot();
        target.setPivotX(pair.first);
        target.setPivotY(pair.second);
      }
      animator = ObjectAnimator.ofPropertyValuesHolder(
          target, holders.toArray(new PropertyValuesHolder[holders.size()]));
      animator.setStartDelay(animation.delay);
      return animator;
    } else {
      return null;
    }
  }

  public static
  @Nullable
  Animator.AnimatorListener createAnimatorListener(final WXSDKInstance mWXSDKInstance, @Nullable final String callBack) {
    if (!TextUtils.isEmpty(callBack)) {
      return new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
          if (mWXSDKInstance == null) {
            WXLogUtils.e("WXRenderStatement-onAnimationEnd mWXSDKInstance == null NPE");
          } else {
            WXSDKManager.getInstance().callback(mWXSDKInstance.getInstanceId(),
                                                callBack,
                                                new HashMap<String, Object>());
          }
        }
      };
    } else {
      return null;
    }
  }

  private static Animator.AnimatorListener prepareLayerType(final View target){
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
      final int originalLayerType=target.getLayerType();
      target.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
      return new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
          target.setLayerType(originalLayerType, null);
        }
      };
    }
    else{
      return null;
    }
  }

  private static @Nullable
  Interpolator createTimeInterpolator(@NonNull WXAnimationBean animation) {
    String interpolator = animation.timingFunction;
    if (!TextUtils.isEmpty(interpolator)) {
      switch (interpolator) {
        case WXAnimationBean.EASE_IN:
          return new AccelerateInterpolator();
        case WXAnimationBean.EASE_OUT:
          return new DecelerateInterpolator();
        case WXAnimationBean.EASE_IN_OUT:
          return new AccelerateDecelerateInterpolator();
        case WXAnimationBean.LINEAR:
          return new LinearInterpolator();
      }
    }
    return null;
  }

}


text:
package org.jhw.keep.db;

import android.database.sqlite.SQLiteDatabase;

public abstract class BaseDao {

	SQLiteDatabase db;

	public BaseDao(SQLiteDatabase db) {
		super();
		this.db = db;
	}
}


text:
package com.danny_oh.reddit.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.danny_oh.reddit.R;
import com.danny_oh.reddit.activities.MainActivity;
import com.danny_oh.reddit.util.Constants;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;

/**
 * Created by danny on 8/2/14.
 *
 * A fragment that is responsible solely for displaying YouTube based submissions.
 */
public class YouTubeSubmissionFragment extends Fragment implements YouTubePlayer.OnInitializedListener,
        YouTubePlayer.PlayerStateChangeListener
{
    // newInstance constructor argument key
    private static final String ARG_VIDEO_ID = "youtube_video_id";
    private static final String ARG_VIDEO_OFFSET_MILLIS = "youtube_video_offset_millis";
    private static final String ARG_SUBMISSION_TITLE = "youtube_submission_title";

    private static final String YOUTUBE_FRAGMENT_BUNDLE_KEY = "youtube_fragment_bundle_key";

    private static final String YOUTUBE_FRAGMENT_TRANSACTION_TAG = "youtube_fragment_transaction_tag";

    private String mVideoId;
    private String mTitle;
    private int mVideoOffsetMillis;

    private YouTubePlayer mYouTubePlayer;

    public static YouTubeSubmissionFragment newInstance(String videoId, String title, int offsetMillis) {
        YouTubeSubmissionFragment fragment = new YouTubeSubmissionFragment();

        Bundle args = new Bundle();
        args.putString(ARG_VIDEO_ID, videoId);
        args.putString(ARG_SUBMISSION_TITLE, title);
        args.putInt(ARG_VIDEO_OFFSET_MILLIS, offsetMillis);

        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mVideoId = getArguments().getString(ARG_VIDEO_ID);
            mTitle = getArguments().getString(ARG_SUBMISSION_TITLE);
            mVideoOffsetMillis = getArguments().getInt(ARG_VIDEO_OFFSET_MILLIS);
        } else {
            throw new InstantiationException("Fragments must be instantiated using factory method newInstance.", new Exception());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_youtube_submission, container, false);

        YouTubePlayerSupportFragment youTubePlayerFragment;

        if (savedInstanceState != null) {
            Log.d("YouTubeSubmissionFragment", "savedInstanceState is not null. Restoring fragment.");
            youTubePlayerFragment = (YouTubePlayerSupportFragment)getFragmentManager().getFragment(savedInstanceState, YOUTUBE_FRAGMENT_BUNDLE_KEY);

        } else {
            Log.d("YouTubeSubmissionFragment", "savedInstanceState is null. Initializing fragment.");
            youTubePlayerFragment = new YouTubePlayerSupportFragment();

            getFragmentManager().beginTransaction()
                    .replace(R.id.youtube_container, youTubePlayerFragment, YOUTUBE_FRAGMENT_TRANSACTION_TAG)
                    .commit();
        }

        youTubePlayerFragment.initialize(Constants.GOOGLE_API_KEY, this);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.d("YouTubeSubmissionFragment", "onSaveInstanceState(). Saving YouTubePlayerSupportFragment.");
        super.onSaveInstanceState(outState);

        YouTubePlayerSupportFragment fragment = (YouTubePlayerSupportFragment)getFragmentManager().findFragmentByTag(YOUTUBE_FRAGMENT_TRANSACTION_TAG);

        if (fragment != null)
            getFragmentManager().putFragment(outState, YOUTUBE_FRAGMENT_BUNDLE_KEY, fragment);
    }

    @Override
    public void onDestroyView() {
        mYouTubePlayer.setFullscreen(false);
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();

        ((MainActivity)getActivity()).getSupportActionBar().setTitle(mTitle);
    }

    /*
 * YouTubePlayer Interface Implementations
 */

/* OnInitializedListener */
    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
        mYouTubePlayer = youTubePlayer;

//        youTubePlayer.setPlayerStateChangeListener(this);

        if (!wasRestored) {
            Log.d("YouTubeSubmissionFragment", "YouTubePlayer was not restored. Initializing video.");
            youTubePlayer.loadVideo(mVideoId, mVideoOffsetMillis);

        } else {
            Log.d("YouTubeSubmissionFragment", "YouTubePlayer was restored. Resuming video.");
        }
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        Log.d("SubmissionFragment", "Failed to initialize YouTubePlayer.");

        Toast.makeText(getActivity(), "Failed to initialize YouTube Player. Please try again later.", Toast.LENGTH_SHORT).show();
    }

/* OnPlayerStateChangeListener */

    @Override
    public void onAdStarted() {

    }

    @Override
    public void onError(YouTubePlayer.ErrorReason errorReason) {

    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoaded(String s) {
        // auto play
        mYouTubePlayer.play();
    }

    @Override
    public void onVideoStarted() {

    }

    @Override
    public void onVideoEnded() {

    }
}


text:
import request from 'superagent'
import { push } from 'react-router-redux'
import { api, error } from '../../helpers'
import { enableMainLoader, disableMainLoader } from '../../base/actions/spinner'
import {
  REQUEST_PRODUCT_CATEGORIES,
  RECEIVE_PRODUCT_CATEGORIES,
  DROP_FILE_PRODUCT_CATEGORIES,
  REQUEST_PRODUCT_CATEGORY,
  RECEIVE_PRODUCT_CATEGORY
} from '../constants'

function requestProductCategories(options) {
  return {
    type: REQUEST_PRODUCT_CATEGORIES,
    ...options
  }
}

function requestProductCategory(id) {
  return {
    type: REQUEST_PRODUCT_CATEGORY,
    id
  }
}

function requestCreateProductCategory() {
  return {
    type: REQUEST_PRODUCT_CATEGORY
  }
}

function receiveProductCategories(list) {
  return {
    type: RECEIVE_PRODUCT_CATEGORIES,
    list
  }
}

function receiveProductCategory(data) {
  return {
    type: RECEIVE_PRODUCT_CATEGORY,
    data
  }
}

function receiveCreateProductCategory(options) {
  return {
    type: RECEIVE_PRODUCT_CATEGORY,
    ...options
  }
}

export function fetchProductCategories({ page = 1, limit = 10, order = '-_id', callback = null, search = null, filter = 'name' }) {
  return (dispatch) => {
    enableMainLoader()
    if (!callback) {
      dispatch(requestProductCategories({ page: page, search: search }))
    }
    request
      .post(api.url('/product_categories'))
      .query(api.params({
        page: page,
        limit: limit,
        order: order,
        search: search,
        filter: filter
      }))
      .set('Accept', 'application/json')
      .end((err, res) => {
        if (err) {
          error.handleAjax(err, res, dispatch)
        } else {
          if (!callback) {
            const list = {
              data: res.body.data,
              paging: res.body.paging
            }
            dispatch(receiveProductCategories(list))
          } else {
            callback(res.body)
          }
        }
        disableMainLoader()
      })
  }
}

export function dropFile(file) {
  return {
    type: DROP_FILE_PRODUCT_CATEGORIES,
    file
  }
}

export function createProductCategory(data) {
  return (dispatch) => {
    dispatch(requestCreateProductCategory())
    let post_data = api.params({ name: data.name })
    let req = request
      .post(api.url('/product_categories/add'))
    for (let i in post_data) {
      req.field(i, post_data[i])
    }
    if (data.image) req.attach('image', data.image)
    req
      .set('Accept', 'application/json')
      .end((err, res) => {
        if (err) {
          error.handleAjax(err, res, dispatch)
        } else {
          if (res.body.status) {
            dispatch(push('/product_categories'))
          } else {
            alert('error')
          }
          dispatch(receiveCreateProductCategory({
            message: res.body.message,
            plain_message: true
          }))
        }
      })
  }
}

export function fetchProductCategory(id) {
  return (dispatch) => {
    dispatch(requestProductCategory(id))
    request
      .post(api.url(`/product_categories/${id}`))
      .query(api.params())
      .set('Accept', 'application/json')
      .end((err, res) => {
        if (err) {
          error.handleAjax(err, res, dispatch)
        } else {
          if (res.body.status) {
            dispatch(receiveProductCategory(res.body.data))
          } else {
            // error
          }
        }
      })
  }
}

export function updateProductCategory(id, data) {
  return (dispatch) => {
    dispatch(requestCreateProductCategory())
    let post_data = api.params({ name: data.name })
    let req = request
      .post(api.url(`/product_categories/${id}/edit`))
    for (let i in post_data) {
      req.field(i, post_data[i])
    }
    if (data.image) req.attach('image', data.image)
    req
      .set('Accept', 'application/json')
      .end((err, res) => {
        if (err) {
          error.handleAjax(err, res, dispatch)
        } else {
          if (res.body.status) {
            dispatch(push('/product_categories'))
          } else {
            alert('error')
          }
          dispatch(receiveCreateProductCategory({
            message: res.body.message,
            plain_message: true
          }))
        }
      })
  }
}

export function deleteProductCategory(id) {
  return (dispatch) => {
    dispatch(requestCreateProductCategory())
    let req = request
      .post(api.url(`/product_categories/${id}/remove`))
      .send(api.params())
      .set('Accept', 'application/json')
      .end((err, res) => {
        if (err) {
          error.handleAjax(err, res, dispatch)
        } else {
          if (res.body.status) {
            dispatch(fetchProductCategories({ page: 1 }))
          } else {
            alert('error')
          }
          dispatch(receiveCreateProductCategory({
            message: res.body.message,
            plain_message: true
          }))
        }
      })
  }
}


text:
package me.chanjar.weixin.cp.bean.license;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * The type Wx cp tp license account duration.
 *
 * @author Totoro  created on  2022-6-27 11:22:53
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WxCpTpLicenseAccountDuration implements Serializable {
  private static final long serialVersionUID = 7960912263908286975L;

  private Integer months;

}


text:
require 'bigdecimal'
require 'bigdecimal/util'
require 'bigdecimal/math'

require File.expand_path('../../core', __FILE__)

module Drone

  ##
  # An exponentially-decaying random sample
  #
  class ExponentiallyDecayingSample
    # 1 hour
    RESCALE_THRESHOLD = (1 * 60 * 60).freeze

    ##
    # Create a new dataset, if the decay factor is too big
    # the flt ruby library is used for internal computations
    # to allow greater precision, the performance impact should be
    # minimal.
    #
    # @param [String] id A unique id representing this
    #   dataset.
    # @param [Integer] reservoir_size the number of samples
    #   to keep.
    # @param [Number] alpha the decay factor, the higher this
    #   number, the more biased the sample will be towards
    #   newer values.
    #
    def initialize(id, reservoir_size, alpha)
      @id = id
      @values = Drone::request_hash("#{@id}:values")
      @count = Drone::request_number("#{@id}:count", 0)
      @start_time = Drone::request_number("#{@id}:start_time", current_time())
      @next_scale_time = Drone::request_number("#{@id}:next_scale_time", current_time() + RESCALE_THRESHOLD)

      @alpha = alpha
      @reservoir_size = reservoir_size
    end

    def clear
      @values.clear()
      @count.set(0)
      @start_time.set(current_time())
      @next_scale_time.set( current_time() + RESCALE_THRESHOLD )
    end

    def size
      count =  @count.get
      (@values.size < count) ? @values.size : count
    end

    def update(val, time = current_time)
      priority = weight(time - @start_time.get) / generate_random()
      new_count = @count.inc

      if new_count <= @reservoir_size
        @values[priority] = val
      else
        first = @values.keys[0]
        if first < priority
          old_val, @values[priority] = @values[priority], val
          unless old_val
            while @values.delete(first) == nil
              first = @values.keys[0]
            end
          end
        end
      end

      now = current_time()
      next_scale = @next_scale_time.get
      if now >= next_scale
        rescale(now, next_scale)
      end
    end

    def values
      @values.keys.sort.inject([]) do |buff, key|
        buff << @values[key]
      end
    end

    def rescale(now, next_scale)
      if @next_scale_time.compare_and_set(next_scale, now + RESCALE_THRESHOLD)
        new_start = current_time()
        old_start = @start_time.get_and_set( new_start )
        time_diff = new_start - old_start

        coeff = math_exp(-@alpha * time_diff)

        @values = Hash[ @values.map{ |k,v|
            [k * coeff, v]
          }]

      end
    end

  private

    def use_flt?
      true
    end

    def math_exp(n)
      if use_flt?
        BigMath.exp( BigDecimal(n.to_s), 2 )
      else
        Math.exp(n)
      end
    end

    ##
    # Generates a non-zero random number
    # According to the ruby documentation rand() could return 0
    # so we ensure this will never happen
    #
    # @return [Float] The random number
    #
    def generate_random()
      begin
        r = Kernel.rand()
      end while r == 0.0

      if use_flt?
        BigDecimal(r.to_s)
      else
        r
      end
    end

    def current_time
      Time.now.to_f
    end

    def weight(n)
      math_exp(@alpha * n)
    end

  end
end


text:
define([
    "qasht/package/Unit",
    "blocks/HashTable"
], function (TestPackage, HashTable) {
    return new TestPackage({
        module: "blocks/HashTable",
        tests: [
            {
                name: "add: stores object and returns a key",
                exec: function (test) {
                    var value = {
                        property: "value"
                    };
                    var key = test.hash.add(value);

                    test.assertNotEqual(key, value, "key is not value");
                    test.assertIsString(key, "Key is a string");
                    test.assertEqual(value, test.hash.get(key), "Get(key) returns original value");

                    test.complete();
                }
            },
            {
                name: "lookup: returns key from value",
                exec: function (test) {
                    var value = {
                        property: "value"
                    };
                    var key = test.hash.add(value);
                    var lookup = test.hash.lookup(value);

                    test.assertEqual(key, lookup, "Lookup matches original generated key");

                    test.complete();
                }
            },
            {
                name: "remove: removes value from table",
                exec: function (test) {
                    var value = {
                        property: "value"
                    };
                    var key = test.hash.add(value);
                    test.hash.remove(key);

                    test.assertUndefined(test.hash.get(key), "get does not return value");

                    test.complete();
                }
            },
            {
                name: "remove: removes value from lookup",
                exec: function (test) {
                    var value = {
                        property: "value"
                    };
                    var key = test.hash.add(value);
                    test.hash.remove(key);
                    var lookup = test.hash.lookup(value);

                    test.assertUndefined(lookup, "Lookup does not return value");

                    test.complete();
                }
            },
            {
                name: "keys: returns list of keys generated from adding values",
                exec: function(test){
                    var value = {
                        property: "value"
                    };
                    var key1 = test.hash.add("value1");
                    var key2 = test.hash.add("value2");
                    var key3 = test.hash.add("value3");
                    var key4 = test.hash.add("value4");
                    var key5 = test.hash.add("value5");

                    var match = {};
                    test.hash.keys().forEach(function(key){
                        match[key] = true;
                    });
                    test.assertTrue(match[key1]);
                    test.assertTrue(match[key2]);
                    test.assertTrue(match[key3]);
                    test.assertTrue(match[key4]);
                    test.assertTrue(match[key5]);

                    test.complete();
                }
            },
            {
                name: "forEach: loops through all stored values",
                exec: function(test){
                    var value = {
                        property: "value"
                    };
                    var key1 = test.hash.add("value1");
                    var key2 = test.hash.add("value2");
                    var key3 = test.hash.add("value3");
                    var key4 = test.hash.add("value4");
                    var key5 = test.hash.add("value5");

                    var match = {};
                    test.hash.forEach(function(value, key, self){
                        test.assertEqual(self, test.hash);
                        match[key] = value;
                    });
                    test.assertEqual("value1", match[key1]);
                    test.assertEqual("value2", match[key2]);
                    test.assertEqual("value3", match[key3]);
                    test.assertEqual("value4", match[key4]);
                    test.assertEqual("value5", match[key5]);

                    test.complete();
                }
            },
            {
                name: "genHash: can pass custom has method",
                setUp: function(test){
                    test.hash = new HashTable({
                        genHash: function(){
                            return "custom";
                        }
                    })
                },
                exec: function (test) {
                    var value = {
                        property: "value"
                    };
                    var key = test.hash.add(value);

                    test.assertNotEqual("custom", key, "key is custom value");

                    test.complete();
                }
            }
        ],
        setUp: function (test) {
            test.hash = new HashTable();
        }
    });
});


text:
"""
Tests for `jukedj` module.
"""

class TestJukedj(object):

    @classmethod
    def setup_class(cls):
        pass

    def test_something(self):
        pass

    @classmethod
    def teardown_class(cls):
        pass


text:
/*
 * Dynamic linked library for the olsr.org olsr daemon
 */

#include <sys/types.h>
#include <sys/socket.h>
#ifndef _WIN32
#include <sys/select.h>
#endif /* _WIN32 */
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <libgen.h>

#ifdef __linux__
#include <fcntl.h>
#endif /* __linux__ */

#include "ipcalc.h"
#include "olsr.h"
#include "olsr_types.h"
#include "neighbor_table.h"
#include "two_hop_neighbor_table.h"
#include "mpr_selector_set.h"
#include "tc_set.h"
#include "hna_set.h"
#include "mid_set.h"
#include "link_set.h"
#include "net_olsr.h"
#include "lq_plugin.h"
#include "common/autobuf.h"
#include "gateway.h"

#include "olsrd_jsoninfo.h"
#include "olsrd_plugin.h"

#ifdef _WIN32
#define close(x) closesocket(x)
#endif /* _WIN32 */

static int ipc_socket;

/* IPC initialization function */
static int plugin_ipc_init(void);

static int read_uuid_from_file(const char *file);

static void abuf_json_open_object(struct autobuf *abuf, const char* header);
static void abuf_json_close_object(struct autobuf *abuf);
static void abuf_json_open_array(struct autobuf *abuf, const char* header);
static void abuf_json_close_array(struct autobuf *abuf);
static void abuf_json_open_array_entry(struct autobuf *abuf);
static void abuf_json_close_array_entry(struct autobuf *abuf);
static void abuf_json_boolean(struct autobuf *abuf, const char* key, int value);
static void abuf_json_string(struct autobuf *abuf, const char* key, const char* value);
static void abuf_json_int(struct autobuf *abuf, const char* key, long value);
static void abuf_json_float(struct autobuf *abuf, const char* key, float value);

static void send_info(unsigned int /*send_what*/, int /*socket*/);
static void ipc_action(int, void *, unsigned int);
static void ipc_print_neighbors(struct autobuf *);
static void ipc_print_links(struct autobuf *);
static void ipc_print_routes(struct autobuf *);
static void ipc_print_topology(struct autobuf *);
static void ipc_print_hna(struct autobuf *);
static void ipc_print_mid(struct autobuf *);
static void ipc_print_gateways(struct autobuf *);
static void ipc_print_config(struct autobuf *);
static void ipc_print_interfaces(struct autobuf *);
static void ipc_print_plugins(struct autobuf *);
static void ipc_print_olsrd_conf(struct autobuf *abuf);

#define TXT_IPC_BUFSIZE 256

/* these provide all of the runtime status info */
#define SIW_NEIGHBORS 0x0001
#define SIW_LINKS 0x0002
#define SIW_ROUTES 0x0004
#define SIW_HNA 0x0008
#define SIW_MID 0x0010
#define SIW_TOPOLOGY 0x0020
#define SIW_GATEWAYS 0x0040
#define SIW_INTERFACES 0x0080
#define SIW_RUNTIME_ALL 0x00FF

/* these only change at olsrd startup */
#define SIW_CONFIG 0x0100
#define SIW_PLUGINS 0x0200
#define SIW_STARTUP_ALL 0x0F00

/* this is everything in JSON format */
#define SIW_ALL 0x0FFF

/* this data is not JSON format but olsrd.conf format */
#define SIW_OLSRD_CONF 0x1000

#define MAX_CLIENTS 3

static char *outbuffer[MAX_CLIENTS];
static size_t outbuffer_size[MAX_CLIENTS];
static size_t outbuffer_written[MAX_CLIENTS];
static int outbuffer_socket[MAX_CLIENTS];
static int outbuffer_count;

char uuid[UUIDLEN + 1];
char uuidfile[FILENAME_MAX];

static struct timeval start_time;
static struct timer_entry *writetimer_entry;

/* JSON support functions */

/* JSON does not allow commas dangling at the end of arrays, so we need to
 * count which entry number we're at in order to make sure we don't tack a
 * dangling comma on at the end */
static int entrynumber[5] = {0,0,0,0,0};
static int currentjsondepth = 0;

static void
abuf_json_open_object(struct autobuf *abuf, const char* header)
{
  abuf_appendf(abuf, "\"%s\": {", header);
  entrynumber[currentjsondepth]++;
  currentjsondepth++;
  entrynumber[currentjsondepth] = 0;
}

static void
abuf_json_close_object(struct autobuf *abuf)
{
  abuf_appendf(abuf, "\t}\n");
  currentjsondepth--;
}

static void
abuf_json_open_array(struct autobuf *abuf, const char* header)
{
  if (entrynumber[currentjsondepth])
    abuf_appendf(abuf, ",\n\t");
  abuf_appendf(abuf, "\"%s\": [\n", header);
  entrynumber[currentjsondepth]++;
  currentjsondepth++;
  entrynumber[currentjsondepth] = 0;
}

static void
abuf_json_close_array(struct autobuf *abuf)
{
  abuf_appendf(abuf, "]\n");
  entrynumber[currentjsondepth] = 0;
  currentjsondepth--;
}

static void
abuf_json_open_array_entry(struct autobuf *abuf)
{
  if (entrynumber[currentjsondepth])
    abuf_appendf(abuf, ",\n{");
  else
    abuf_appendf(abuf, "{");
  entrynumber[currentjsondepth]++;
  currentjsondepth++;
  entrynumber[currentjsondepth] = 0;
}

static void
abuf_json_close_array_entry(struct autobuf *abuf)
{
  abuf_appendf(abuf, "}");
  entrynumber[currentjsondepth] = 0;
  currentjsondepth--;
}

static void
abuf_json_insert_comma(struct autobuf *abuf)
{
  if (entrynumber[currentjsondepth])
    abuf_appendf(abuf, ",\n");
  else
    abuf_appendf(abuf, "\n");
  entrynumber[currentjsondepth]++;
}

static void
abuf_json_boolean(struct autobuf *abuf, const char* key, int value)
{
  abuf_json_insert_comma(abuf);
  abuf_appendf(abuf, "\t\"%s\": %s", key, value ? "true" : "false");
}

static void
abuf_json_string(struct autobuf *abuf, const char* key, const char* value)
{
  abuf_json_insert_comma(abuf);
  abuf_appendf(abuf, "\t\"%s\": \"%s\"", key, value);
}

static void
abuf_json_int(struct autobuf *abuf, const char* key, long value)
{
  abuf_json_insert_comma(abuf);
  abuf_appendf(abuf, "\t\"%s\": %li", key, value);
}

static void
abuf_json_float(struct autobuf *abuf, const char* key, float value)
{
  abuf_json_insert_comma(abuf);
  abuf_appendf(abuf, "\t\"%s\": %.03f", key, (double)value);
}

/* Linux specific functions for getting system info */

#ifdef __linux__
static int get_string_from_file(const char* filename, char* buf, int len)
{
  int bytes = -1;
  int fd = open(filename, O_RDONLY);
  if (fd > -1) {
    bytes = read(fd, buf, len);
    if (bytes < len)
      buf[bytes-1] = '\0'; // remove trailing \n
    else
      buf[len-1] = '\0';
    close(fd);
  }
  return bytes;
}

static int
abuf_json_sysdata(struct autobuf *abuf, const char* key, const char* syspath)
{
  int ret = -1;
  char buf[256];
  *buf = 0;
  ret = get_string_from_file(syspath, buf, 256);
  if (*buf != 0)
    abuf_json_string(abuf, key, buf);
  return ret;
}

static void
abuf_json_sys_class_net(struct autobuf *abuf, const char* key,
                        const char* ifname, const char* datapoint)
{
  char filename[256];
  snprintf(filename, 255, "/sys/class/net/%s/%s", ifname, datapoint);
  abuf_json_sysdata(abuf, key, filename);
}

#endif /* __linux__ */

/**
 *Do initialization here
 *
 *This function is called by the my_init
 *function in uolsrd_plugin.c
 */
int
olsrd_plugin_init(void)
{
  /* Initial IPC value */
  ipc_socket = -1;

  /* Get start time */
  gettimeofday(&start_time, NULL);

  if (!strlen(uuidfile))
    strscpy(uuidfile, "uuid.txt", sizeof(uuidfile));
  read_uuid_from_file(uuidfile);

  plugin_ipc_init();
  return 1;
}

/**
 * destructor - called at unload
 */
void
olsr_plugin_exit(void)
{
  if (ipc_socket != -1)
    close(ipc_socket);
}

static int
plugin_ipc_init(void)
{
  union olsr_sockaddr sst;
  uint32_t yes = 1;
  socklen_t addrlen;

  /* Init ipc socket */
  if ((ipc_socket = socket(olsr_cnf->ip_version, SOCK_STREAM, 0)) == -1) {
#ifndef NODEBUG
    olsr_printf(1, "(JSONINFO) socket()=%s\n", strerror(errno));
#endif /* NODEBUG */
    return 0;
  } else {
    if (setsockopt(ipc_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes)) < 0) {
#ifndef NODEBUG
      olsr_printf(1, "(JSONINFO) setsockopt()=%s\n", strerror(errno));
#endif /* NODEBUG */
      return 0;
    }
#if (defined __FreeBSD__ || defined __FreeBSD_kernel__) && defined SO_NOSIGPIPE
    if (setsockopt(ipc_socket, SOL_SOCKET, SO_NOSIGPIPE, (char *)&yes, sizeof(yes)) < 0) {
      perror("SO_REUSEADDR failed");
      return 0;
    }
#endif /* (defined __FreeBSD__ || defined __FreeBSD_kernel__) && defined SO_NOSIGPIPE */
    /* Bind the socket */

    /* complete the socket structure */
    memset(&sst, 0, sizeof(sst));
    if (olsr_cnf->ip_version == AF_INET) {
      sst.in4.sin_family = AF_INET;
      addrlen = sizeof(struct sockaddr_in);
#ifdef SIN6_LEN
      sst.in4.sin_len = addrlen;
#endif /* SIN6_LEN */
      sst.in4.sin_addr.s_addr = jsoninfo_listen_ip.v4.s_addr;
      sst.in4.sin_port = htons(ipc_port);
    } else {
      sst.in6.sin6_family = AF_INET6;
      addrlen = sizeof(struct sockaddr_in6);
#ifdef SIN6_LEN
      sst.in6.sin6_len = addrlen;
#endif /* SIN6_LEN */
      sst.in6.sin6_addr = jsoninfo_listen_ip.v6;
      sst.in6.sin6_port = htons(ipc_port);
    }

    /* bind the socket to the port number */
    if (bind(ipc_socket, &sst.in, addrlen) == -1) {
#ifndef NODEBUG
      olsr_printf(1, "(JSONINFO) bind()=%s\n", strerror(errno));
#endif /* NODEBUG */
      return 0;
    }

    /* show that we are willing to listen */
    if (listen(ipc_socket, 1) == -1) {
#ifndef NODEBUG
      olsr_printf(1, "(JSONINFO) listen()=%s\n", strerror(errno));
#endif /* NODEBUG */
      return 0;
    }

    /* Register with olsrd */
    add_olsr_socket(ipc_socket, &ipc_action, NULL, NULL, SP_PR_READ);

#ifndef NODEBUG
    olsr_printf(2, "(JSONINFO) listening on port %d\n", ipc_port);
#endif /* NODEBUG */
  }
  return 1;
}

static int
read_uuid_from_file(const char *file)
{
  FILE *f;
  char* end;
  int r = 0;
  size_t chars;

  memset(uuid, 0, sizeof(uuid));

  f = fopen(file, "r");
  olsr_printf(1, "(JSONINFO) Reading UUID from '%s'\n", file);
  if (f == NULL ) {
    olsr_printf(1, "(JSONINFO) Could not open '%s': %s\n",
                file, strerror(errno));
    return -1;
  }
  chars = fread(uuid, 1, UUIDLEN, f);
  if (chars > 0) {
    uuid[chars] = '\0'; /* null-terminate the string */

    /* we only use the first line of the file */
    end = strchr(uuid, '\n');
    if(end)
      *end = 0;
    r = 0;
  } else {
    olsr_printf(1, "(JSONINFO) Could not read UUID from '%s': %s\n",
                file, strerror(errno));
    r = -1;
  }

  fclose(f);
  return r;
}

static void
ipc_action(int fd, void *data __attribute__ ((unused)), unsigned int flags __attribute__ ((unused)))
{
  union olsr_sockaddr pin;

  char addr[INET6_ADDRSTRLEN];
  fd_set rfds;
  struct timeval tv;
  unsigned int send_what = 0;
  int ipc_connection;

  socklen_t addrlen = sizeof(pin);

  if ((ipc_connection = accept(fd, &pin.in, &addrlen)) == -1) {
#ifndef NODEBUG
    olsr_printf(1, "(JSONINFO) accept()=%s\n", strerror(errno));
#endif /* NODEBUG */
    return;
  }

  tv.tv_sec = tv.tv_usec = 0;
  if (olsr_cnf->ip_version == AF_INET) {
    if (inet_ntop(olsr_cnf->ip_version, &pin.in4.sin_addr, addr, INET6_ADDRSTRLEN) == NULL)
      addr[0] = '\0';
    if (!ip4equal(&pin.in4.sin_addr, &jsoninfo_accept_ip.v4) && jsoninfo_accept_ip.v4.s_addr != INADDR_ANY) {
#ifdef JSONINFO_ALLOW_LOCALHOST
      if (pin.in4.sin_addr.s_addr != INADDR_LOOPBACK) {
#endif /* JSONINFO_ALLOW_LOCALHOST */
        olsr_printf(1, "(JSONINFO) From host(%s) not allowed!\n", addr);
        close(ipc_connection);
        return;
#ifdef JSONINFO_ALLOW_LOCALHOST
      }
#endif /* JSONINFO_ALLOW_LOCALHOST */
    }
  } else {
    if (inet_ntop(olsr_cnf->ip_version, &pin.in6.sin6_addr, addr, INET6_ADDRSTRLEN) == NULL)
      addr[0] = '\0';
    /* Use in6addr_any (::) in olsr.conf to allow anybody. */
    if (!ip6equal(&in6addr_any, &jsoninfo_accept_ip.v6) && !ip6equal(&pin.in6.sin6_addr, &jsoninfo_accept_ip.v6)) {
      olsr_printf(1, "(JSONINFO) From host(%s) not allowed!\n", addr);
      close(ipc_connection);
      return;
    }
  }

#ifndef NODEBUG
  olsr_printf(2, "(JSONINFO) Connect from %s\n", addr);
#endif /* NODEBUG */

  /* purge read buffer to prevent blocking on linux */
  FD_ZERO(&rfds);
  FD_SET((unsigned int)ipc_connection, &rfds);  /* Win32 needs the cast here */
  if (0 <= select(ipc_connection + 1, &rfds, NULL, NULL, &tv)) {
    char requ[128];
    ssize_t s = recv(ipc_connection, (void *)&requ, sizeof(requ), 0);   /* Win32 needs the cast here */
    if (0 < s) {
      requ[s] = 0;
      /* print out the requested tables */
      if (0 != strstr(requ, "/olsrd.conf"))
        send_what |= SIW_OLSRD_CONF;
      else if (0 != strstr(requ, "/all"))
        send_what = SIW_ALL;
      else {
        // these are the two overarching categories
        if (0 != strstr(requ, "/runtime")) send_what |= SIW_RUNTIME_ALL;
        if (0 != strstr(requ, "/startup")) send_what |= SIW_STARTUP_ALL;
        // these are the individual sections
        if (0 != strstr(requ, "/neighbors")) send_what |= SIW_NEIGHBORS;
        if (0 != strstr(requ, "/links")) send_what |= SIW_LINKS;
        if (0 != strstr(requ, "/routes")) send_what |= SIW_ROUTES;
        if (0 != strstr(requ, "/hna")) send_what |= SIW_HNA;
        if (0 != strstr(requ, "/mid")) send_what |= SIW_MID;
        if (0 != strstr(requ, "/topology")) send_what |= SIW_TOPOLOGY;
        if (0 != strstr(requ, "/gateways")) send_what |= SIW_GATEWAYS;
        if (0 != strstr(requ, "/interfaces")) send_what |= SIW_INTERFACES;
        if (0 != strstr(requ, "/config")) send_what |= SIW_CONFIG;
        if (0 != strstr(requ, "/plugins")) send_what |= SIW_PLUGINS;
      }
    }
    if ( send_what == 0 ) send_what = SIW_ALL;
  }

  send_info(send_what, ipc_connection);
}

static void
ipc_print_neighbors(struct autobuf *abuf)
{
  struct ipaddr_str buf1;
  struct neighbor_entry *neigh;
  struct neighbor_2_list_entry *list_2;
  int thop_cnt;

  abuf_json_open_array(abuf, "neighbors");

  /* Neighbors */
  OLSR_FOR_ALL_NBR_ENTRIES(neigh) {
    abuf_json_open_array_entry(abuf);
    abuf_json_string(abuf, "ipv4Address",
                     olsr_ip_to_string(&buf1, &neigh->neighbor_main_addr));
    abuf_json_boolean(abuf, "symmetric", (neigh->status == SYM));
    abuf_json_boolean(abuf, "multiPointRelay", neigh->is_mpr);
    abuf_json_boolean(abuf, "multiPointRelaySelector",
                      olsr_lookup_mprs_set(&neigh->neighbor_main_addr) != NULL);
    abuf_json_int(abuf, "willingness", neigh->willingness);
    abuf_appendf(abuf, ",\n");

    thop_cnt = 0;
    if (neigh->neighbor_2_list.next) {
      abuf_appendf(abuf, "\t\"twoHopNeighbors\": [");
      for (list_2 = neigh->neighbor_2_list.next; list_2 != &neigh->neighbor_2_list; list_2 = list_2->next) {
        if (thop_cnt)
          abuf_appendf(abuf, ", ");
        abuf_appendf(abuf,
                     "\"%s\"",
                     olsr_ip_to_string(&buf1, &list_2->neighbor_2->neighbor_2_addr));
        thop_cnt++;
      }
    }
    abuf_appendf(abuf, "]");
    abuf_json_int(abuf, "twoHopNeighborCount", thop_cnt);
    abuf_json_close_array_entry(abuf);
  }
  OLSR_FOR_ALL_NBR_ENTRIES_END(neigh);
  abuf_json_close_array(abuf);
}

static void
ipc_print_links(struct autobuf *abuf)
{
  struct ipaddr_str buf1, buf2;
  struct lqtextbuffer lqbuffer1;

  struct link_entry *my_link = NULL;

  abuf_json_open_array(abuf, "links");
  OLSR_FOR_ALL_LINK_ENTRIES(my_link) {
    const char* lqs;
    int diff = (unsigned int)(my_link->link_timer->timer_clock - now_times);

    abuf_json_open_array_entry(abuf);
    abuf_json_string(abuf, "localIP",
                     olsr_ip_to_string(&buf1, &my_link->local_iface_addr));
    abuf_json_string(abuf, "remoteIP",
                     olsr_ip_to_string(&buf2, &my_link->neighbor_iface_addr));
    abuf_json_int(abuf, "validityTime", diff);
    lqs = get_link_entry_text(my_link, '\t', &lqbuffer1);
    abuf_json_float(abuf, "linkQuality", atof(lqs));
    abuf_json_float(abuf, "neighborLinkQuality", atof(strrchr(lqs, '\t')));
    if (my_link->linkcost >= LINK_COST_BROKEN)
      abuf_json_int(abuf, "linkCost", LINK_COST_BROKEN);
    else
      abuf_json_int(abuf, "linkCost", my_link->linkcost);
    abuf_json_close_array_entry(abuf);
  }
  OLSR_FOR_ALL_LINK_ENTRIES_END(my_link);
  abuf_json_close_array(abuf);
}

static void
ipc_print_routes(struct autobuf *abuf)
{
  struct ipaddr_str buf1, buf2;
  struct rt_entry *rt;

  abuf_json_open_array(abuf, "routes");

  /* Walk the route table */
  OLSR_FOR_ALL_RT_ENTRIES(rt) {
    abuf_json_open_array_entry(abuf);
    abuf_json_string(abuf, "destination",
                     olsr_ip_to_string(&buf1, &rt->rt_dst.prefix));
    abuf_json_int(abuf, "genmask", rt->rt_dst.prefix_len);
    abuf_json_string(abuf, "gateway",
                     olsr_ip_to_string(&buf2, &rt->rt_best->rtp_nexthop.gateway));
    abuf_json_int(abuf, "metric", rt->rt_best->rtp_metric.hops);
    if (rt->rt_best->rtp_metric.cost >= ROUTE_COST_BROKEN)
      abuf_json_int(abuf, "rtpMetricCost", ROUTE_COST_BROKEN);
    else
      abuf_json_int(abuf, "rtpMetricCost", rt->rt_best->rtp_metric.cost);
    abuf_json_string(abuf, "networkInterface",
                     if_ifwithindex_name(rt->rt_best->rtp_nexthop.iif_index));
    abuf_json_close_array_entry(abuf);
  }
  OLSR_FOR_ALL_RT_ENTRIES_END(rt);

  abuf_json_close_array(abuf);
}

static void
ipc_print_topology(struct autobuf *abuf)
{
  struct tc_entry *tc;

  abuf_json_open_array(abuf, "topology");

  /* Topology */
  OLSR_FOR_ALL_TC_ENTRIES(tc) {
    struct tc_edge_entry *tc_edge;
    OLSR_FOR_ALL_TC_EDGE_ENTRIES(tc, tc_edge) {
      if (tc_edge->edge_inv) {
        struct ipaddr_str dstbuf, addrbuf;
        struct lqtextbuffer lqbuffer1;
        uint32_t vt = tc->validity_timer != NULL ? (tc->validity_timer->timer_clock - now_times) : 0;
        int diff = (int)(vt);
        const char* lqs;
        abuf_json_open_array_entry(abuf);
        abuf_json_string(abuf, "destinationIP",
                         olsr_ip_to_string(&dstbuf, &tc_edge->T_dest_addr));
        abuf_json_string(abuf, "lastHopIP",
                         olsr_ip_to_string(&addrbuf, &tc->addr));
        lqs = get_tc_edge_entry_text(tc_edge, '\t', &lqbuffer1);
        abuf_json_float(abuf, "linkQuality", atof(lqs));
        abuf_json_float(abuf, "neighborLinkQuality", atof(strrchr(lqs, '\t')));
        if (tc_edge->cost >= LINK_COST_BROKEN)
          abuf_json_int(abuf, "tcEdgeCost", LINK_COST_BROKEN);
        else
          abuf_json_int(abuf, "tcEdgeCost", tc_edge->cost);
        abuf_json_int(abuf, "validityTime", diff);
        abuf_json_close_array_entry(abuf);
      }
    }
    OLSR_FOR_ALL_TC_EDGE_ENTRIES_END(tc, tc_edge);
  }
  OLSR_FOR_ALL_TC_ENTRIES_END(tc);

  abuf_json_close_array(abuf);
}

static void
ipc_print_hna(struct autobuf *abuf)
{
  struct hna_entry *tmp_hna;
  struct hna_net *tmp_net;
  struct ipaddr_str buf, mainaddrbuf;

  abuf_json_open_array(abuf, "hna");

  OLSR_FOR_ALL_HNA_ENTRIES(tmp_hna) {

    /* Check all networks */
    for (tmp_net = tmp_hna->networks.next; tmp_net != &tmp_hna->networks; tmp_net = tmp_net->next) {
      uint32_t vt = tmp_net->hna_net_timer != NULL ? (tmp_net->hna_net_timer->timer_clock - now_times) : 0;
      int diff = (int)(vt);
      abuf_json_open_array_entry(abuf);
      abuf_json_string(abuf, "destination",
                       olsr_ip_to_string(&buf, &tmp_net->hna_prefix.prefix)),
      abuf_json_int(abuf, "genmask", tmp_net->hna_prefix.prefix_len);
      abuf_json_string(abuf, "gateway",
                       olsr_ip_to_string(&mainaddrbuf, &tmp_hna->A_gateway_addr));
      abuf_json_int(abuf, "validityTime", diff);
      abuf_json_close_array_entry(abuf);
    }
  }
  OLSR_FOR_ALL_HNA_ENTRIES_END(tmp_hna);

  abuf_json_close_array(abuf);
}

static void
ipc_print_mid(struct autobuf *abuf)
{
  int idx;
  struct mid_entry *entry;
  struct mid_address *alias;

  abuf_json_open_array(abuf, "mid");

  /* MID */
  for (idx = 0; idx < HASHSIZE; idx++) {
    entry = mid_set[idx].next;

    while (entry != &mid_set[idx]) {
      struct ipaddr_str buf, buf2;
      abuf_json_open_array_entry(abuf);
      abuf_json_string(abuf, "ipAddress",
                       olsr_ip_to_string(&buf, &entry->main_addr));

      abuf_json_open_array(abuf, "aliases");
      alias = entry->aliases;
      while (alias) {
        uint32_t vt = alias->vtime - now_times;
        int diff = (int)(vt);

        abuf_json_open_array_entry(abuf);
        abuf_json_string(abuf, "ipAddress",
                         olsr_ip_to_string(&buf2, &alias->alias));
        abuf_json_int(abuf, "validityTime", diff);
        abuf_json_close_array_entry(abuf);

        alias = alias->next_alias;
      }
      abuf_json_close_array(abuf); // aliases
      abuf_json_close_array_entry(abuf);
      entry = entry->next;
    }
  }
  abuf_json_close_array(abuf); // mid
}

static void
ipc_print_gateways(struct autobuf *abuf)
{
#ifndef __linux__
  abuf_json_string(abuf, "error", "Gateway mode is only supported in Linux");
#else /* __linux__ */

  struct ipaddr_str buf;
  struct gateway_entry *gw;

  abuf_json_open_array(abuf, "gateways");
  OLSR_FOR_ALL_GATEWAY_ENTRIES(gw) {
    const char *v4 = "", *v6 = "";
    bool autoV4 = false, autoV6 = false;
    const char *ipType = "";
    struct tc_entry *tc;

    if ((tc = olsr_lookup_tc_entry(&gw->originator)) == NULL) {
      continue;
    }

    if (gw == olsr_get_inet_gateway(false)) {
      v4 = "s";
    } else if (gw->ipv4 && (olsr_cnf->ip_version == AF_INET || olsr_cnf->use_niit)
               && (olsr_cnf->smart_gw_allow_nat || !gw->ipv4nat)) {
      v4 = "u";
    }

    if (gw == olsr_get_inet_gateway(true)) {
      v6 = "s";
    } else if (gw->ipv6 && olsr_cnf->ip_version == AF_INET6) {
      v6 = "u";
    }

    abuf_json_open_array_entry(abuf);
    if (gw->ipv4) {
      ipType = "ipv4";
      abuf_json_string(abuf, "ipv4Status", v4);
    } else if (gw->ipv6) {
      ipType = "ipv6";
      abuf_json_string(abuf, "ipv6Status", v6);
    }
    abuf_json_string(abuf, "ipType", ipType);
    abuf_json_boolean(abuf, "ipv4", gw->ipv4);
    abuf_json_boolean(abuf, "ipv4Nat", gw->ipv4nat);
    abuf_json_boolean(abuf, "ipv6", gw->ipv6);
    abuf_json_boolean(abuf, "autoIpv4", autoV4);
    abuf_json_boolean(abuf, "autoIpv6", autoV6);
    abuf_json_string(abuf, "ipAddress",
                     olsr_ip_to_string(&buf, &gw->originator));
    if (tc->path_cost >= ROUTE_COST_BROKEN)
      abuf_json_int(abuf, "tcPathCost", ROUTE_COST_BROKEN);
    else
      abuf_json_int(abuf, "tcPathCost", tc->path_cost);
    abuf_json_int(abuf, "hopCount", tc->hops);
    abuf_json_int(abuf, "uplinkSpeed", gw->uplink);
    abuf_json_int(abuf, "downlinkSpeed", gw->downlink);
    if(gw->external_prefix.prefix_len == 0)
      abuf_json_string(abuf, "externalPrefix",
                       olsr_ip_prefix_to_string(&gw->external_prefix));
    abuf_json_close_array_entry(abuf);
  }
  OLSR_FOR_ALL_GATEWAY_ENTRIES_END(gw)
  abuf_json_close_array(abuf);
#endif /* __linux__ */
}

static void
ipc_print_plugins(struct autobuf *abuf)
{
  struct plugin_entry *pentry;
  struct plugin_param *pparam;
  abuf_json_open_array(abuf, "plugins");
  if (olsr_cnf->plugins)
    for (pentry = olsr_cnf->plugins; pentry; pentry = pentry->next) {
      abuf_json_open_array_entry(abuf);
      abuf_json_string(abuf, "plugin", pentry->name);
      for (pparam = pentry->params; pparam; pparam = pparam->next) {
        int i, keylen = strlen(pparam->key);
        char key[keylen + 1];
        long value;
        char valueTest[256];
        strcpy(key, pparam->key);
        for (i = 0; i < keylen; i++)
          key[i] = tolower(key[i]);

        // test if a int/long and set as such in JSON
        value = atol(pparam->value);
        snprintf(valueTest, 255, "%li", value);
        if (strcmp(valueTest, pparam->value) == 0)
          abuf_json_int(abuf, key, value);
        else
          abuf_json_string(abuf, key, pparam->value);
      }
      abuf_json_close_array_entry(abuf);
    }
  abuf_json_close_array(abuf);
}

static void
ipc_print_config(struct autobuf *abuf)
{
  struct ip_prefix_list *hna;
  struct ipaddr_str buf, mainaddrbuf;
  struct ip_prefix_list *ipcn;
  struct olsr_lq_mult *mult;
  char ipv6_buf[INET6_ADDRSTRLEN];                  /* buffer for IPv6 inet_htop */

  abuf_json_open_object(abuf, "config");

  abuf_json_int(abuf, "olsrPort", olsr_cnf->olsrport);
  abuf_json_int(abuf, "debugLevel", olsr_cnf->debug_level);
  abuf_json_boolean(abuf, "noFork", olsr_cnf->no_fork);
  abuf_json_boolean(abuf, "hostEmulation", olsr_cnf->host_emul);
  abuf_json_int(abuf, "ipVersion", olsr_cnf->ip_version);
  abuf_json_boolean(abuf, "allowNoInterfaces", olsr_cnf->allow_no_interfaces);
  abuf_json_int(abuf, "typeOfService", olsr_cnf->tos);
  abuf_json_int(abuf, "rtProto", olsr_cnf->rt_proto);
  abuf_json_int(abuf, "rtTable", olsr_cnf->rt_table);
  abuf_json_int(abuf, "rtTableDefault", olsr_cnf->rt_table_default);
  abuf_json_int(abuf, "rtTableTunnel", olsr_cnf->rt_table_tunnel);
  abuf_json_int(abuf, "rtTablePriority", olsr_cnf->rt_table_pri);
  abuf_json_int(abuf, "rtTableTunnelPriority", olsr_cnf->rt_table_tunnel_pri);
  abuf_json_int(abuf, "rtTableDefauiltOlsrPriority", olsr_cnf->rt_table_defaultolsr_pri);
  abuf_json_int(abuf, "rtTableDefaultPriority", olsr_cnf->rt_table_default_pri);
  abuf_json_int(abuf, "willingness", olsr_cnf->willingness);
  abuf_json_boolean(abuf, "willingnessAuto", olsr_cnf->willingness_auto);

  abuf_json_int(abuf, "brokenLinkCost", LINK_COST_BROKEN);
  abuf_json_int(abuf, "brokenRouteCost", ROUTE_COST_BROKEN);

  abuf_json_string(abuf, "fibMetrics", FIB_METRIC_TXT[olsr_cnf->fib_metric]);

  abuf_json_string(abuf, "defaultIpv6Multicast",
                   inet_ntop(AF_INET6, &olsr_cnf->interface_defaults->ipv6_multicast.v6,
                             ipv6_buf, sizeof(ipv6_buf)));
  if (olsr_cnf->interface_defaults->ipv4_multicast.v4.s_addr)
    abuf_json_string(abuf, "defaultIpv4Broadcast",
                     inet_ntoa(olsr_cnf->interface_defaults->ipv4_multicast.v4));
  else
    abuf_json_string(abuf, "defaultIpv4Broadcast", "auto");

  if (olsr_cnf->interface_defaults->mode==IF_MODE_ETHER)
    abuf_json_string(abuf, "defaultInterfaceMode", "ether");
  else
    abuf_json_string(abuf, "defaultInterfaceMode", "mesh");

  abuf_json_float(abuf, "defaultHelloEmissionInterval",
                  olsr_cnf->interface_defaults->hello_params.emission_interval);
  abuf_json_float(abuf, "defaultHelloValidityTime",
                  olsr_cnf->interface_defaults->hello_params.validity_time);
  abuf_json_float(abuf, "defaultTcEmissionInterval",
                  olsr_cnf->interface_defaults->tc_params.emission_interval);
  abuf_json_float(abuf, "defaultTcValidityTime",
                  olsr_cnf->interface_defaults->tc_params.validity_time);
  abuf_json_float(abuf, "defaultMidEmissionInterval",
                  olsr_cnf->interface_defaults->mid_params.emission_interval);
  abuf_json_float(abuf, "defaultMidValidityTime",
                  olsr_cnf->interface_defaults->mid_params.validity_time);
  abuf_json_float(abuf, "defaultHnaEmissionInterval",
                  olsr_cnf->interface_defaults->hna_params.emission_interval);
  abuf_json_float(abuf, "defaultHnaValidityTime",
                  olsr_cnf->interface_defaults->hna_params.validity_time);
  abuf_json_boolean(abuf, "defaultAutoDetectChanges",
                    olsr_cnf->interface_defaults->autodetect_chg);

  abuf_json_open_array(abuf, "defaultLinkQualityMultipliers");
  for (mult = olsr_cnf->interface_defaults->lq_mult; mult != NULL; mult = mult->next) {
    abuf_json_open_array_entry(abuf);
    abuf_json_string(abuf, "route",
                     inet_ntop(olsr_cnf->ip_version, &mult->addr, ipv6_buf, sizeof(ipv6_buf)));
    abuf_json_float(abuf, "multiplier", mult->value / 65535.0);
    abuf_json_close_array_entry(abuf);
  }
  abuf_json_close_array(abuf);

  abuf_json_open_array(abuf, "hna");
  for (hna = olsr_cnf->hna_entries; hna != NULL; hna = hna->next) {
    abuf_json_open_array_entry(abuf);
    abuf_json_string(abuf, "destination",
                     olsr_ip_to_string(&buf, &hna->net.prefix));
    abuf_json_int(abuf, "genmask", hna->net.prefix_len);
    abuf_json_string(abuf, "gateway",
                     olsr_ip_to_string(&mainaddrbuf, &olsr_cnf->main_addr));
    abuf_json_close_array_entry(abuf);
  }
  abuf_json_close_array(abuf);

  abuf_json_int(abuf, "totalIpcConnectionsAllowed", olsr_cnf->ipc_connections);
  abuf_json_open_array(abuf, "ipcAllowedAddresses");
  if (olsr_cnf->ipc_connections) {
    for (ipcn = olsr_cnf->ipc_nets; ipcn != NULL; ipcn = ipcn->next) {
      abuf_json_open_array_entry(abuf);
      abuf_json_string(abuf, "ipAddress",
                       olsr_ip_to_string(&mainaddrbuf, &ipcn->net.prefix));
      abuf_json_int(abuf, "netmask", ipcn->net.prefix_len);
      abuf_json_close_array_entry(abuf);
    }
  }
  abuf_json_close_array(abuf);

  // keep all time in ms, so convert these two, which are in seconds
  abuf_json_int(abuf, "pollRate", olsr_cnf->pollrate * 1000);
  abuf_json_int(abuf, "nicChangePollInterval", olsr_cnf->nic_chgs_pollrate * 1000);
  abuf_json_boolean(abuf, "clearScreen", olsr_cnf->clear_screen);
  abuf_json_int(abuf, "tcRedundancy", olsr_cnf->tc_redundancy);
  abuf_json_int(abuf, "mprCoverage", olsr_cnf->mpr_coverage);

  if (olsr_cnf->lq_level == 0) {
    abuf_json_boolean(abuf, "useHysteresis", olsr_cnf->use_hysteresis);
    if (olsr_cnf->use_hysteresis) {
      abuf_json_float(abuf, "hysteresisScaling", olsr_cnf->hysteresis_param.scaling);
      abuf_json_float(abuf, "hysteresisLowThreshold", olsr_cnf->hysteresis_param.thr_low);
      abuf_json_float(abuf, "hysteresisHighThreshold", olsr_cnf->hysteresis_param.thr_high);
    }
  }
  abuf_json_int(abuf, "linkQualityLevel", olsr_cnf->lq_level);
  abuf_json_float(abuf, "linkQualityAging", olsr_cnf->lq_aging);
  abuf_json_boolean(abuf, "linkQualityFisheye", olsr_cnf->lq_fish);
  abuf_json_string(abuf, "linkQualityAlgorithm", olsr_cnf->lq_algorithm);
  // keep all time in ms, so convert this from seconds
  abuf_json_int(abuf, "minTcValidTime", olsr_cnf->min_tc_vtime * 1000);
  abuf_json_boolean(abuf, "setIpForward", olsr_cnf->set_ip_forward);
  abuf_json_string(abuf, "lockFile", olsr_cnf->lock_file);
  abuf_json_boolean(abuf, "useNiit", olsr_cnf->use_niit);

#ifdef __linux__
  abuf_json_boolean(abuf, "smartGateway", olsr_cnf->smart_gw_active);
  if (olsr_cnf->smart_gw_active) {
    abuf_json_boolean(abuf, "smartGatewayAlwaysRemoveServerTunnel", olsr_cnf->smart_gw_always_remove_server_tunnel);
    abuf_json_int(abuf, "smartGatewayUseCount", olsr_cnf->smart_gw_use_count);
    abuf_json_string(abuf, "smartGatewayPolicyRoutingScript", olsr_cnf->smart_gw_policyrouting_script);
    {
      struct autobuf egressbuf;
      struct sgw_egress_if * egressif = olsr_cnf->smart_gw_egress_interfaces;

      abuf_init(&egressbuf, (olsr_cnf->smart_gw_egress_interfaces_count * IFNAMSIZ) /* interface names */
          + (olsr_cnf->smart_gw_egress_interfaces_count - 1) /* commas */);
      while (egressif) {
        if (egressbuf.len) {
          abuf_puts(&egressbuf, ",");
        }
        abuf_appendf(&egressbuf, "%s", egressif->name);
        egressif = egressif->next;
      }
      abuf_json_string(abuf, "smartGatewayEgressInterfaces", egressbuf.buf);
      abuf_free(&egressbuf);
    }
    abuf_json_int(abuf, "smartGatewayMarkOffsetEgress", olsr_cnf->smart_gw_mark_offset_egress);
    abuf_json_int(abuf, "smartGatewayMarkOffsetTunnels", olsr_cnf->smart_gw_mark_offset_tunnels);
    abuf_json_boolean(abuf, "smartGatewayAllowNat", olsr_cnf->smart_gw_allow_nat);
    abuf_json_boolean(abuf, "smartGatewayUplinkNat", olsr_cnf->smart_gw_uplink_nat);
    abuf_json_int(abuf, "smartGatewayPeriod", olsr_cnf->smart_gw_period);
    abuf_json_int(abuf, "smartGatewayStableCount", olsr_cnf->smart_gw_stablecount);
    abuf_json_int(abuf, "smartGatewayThreshold", olsr_cnf->smart_gw_thresh);
    abuf_json_int(abuf, "smartGatewayUplink", olsr_cnf->smart_gw_uplink);
    abuf_json_int(abuf, "smartGatewayDownlink", olsr_cnf->smart_gw_downlink);
    abuf_json_int(abuf, "smartGatewayType", olsr_cnf->smart_gw_type);
    abuf_json_string(abuf, "smartGatewayPrefix",
                     olsr_ip_to_string(&mainaddrbuf, &olsr_cnf->smart_gw_prefix.prefix));
    abuf_json_int(abuf, "smartGatewayPrefixLength", olsr_cnf->smart_gw_prefix.prefix_len);
  }
#endif /* __linux__ */

  abuf_json_string(abuf, "mainIpAddress",
                   olsr_ip_to_string(&mainaddrbuf, &olsr_cnf->main_addr));
  abuf_json_string(abuf, "unicastSourceIpAddress",
                   olsr_ip_to_string(&mainaddrbuf, &olsr_cnf->unicast_src_ip));

  abuf_json_boolean(abuf, "useSourceIpRoutes", olsr_cnf->use_src_ip_routes);

  abuf_json_int(abuf, "maxPrefixLength", olsr_cnf->maxplen);
  abuf_json_int(abuf, "ipSize", olsr_cnf->ipsize);
  abuf_json_boolean(abuf, "deleteInternetGatewaysAtStartup", olsr_cnf->del_gws);
  // keep all time in ms, so convert this from seconds
  abuf_json_int(abuf, "willingnessUpdateInterval", olsr_cnf->will_int * 1000);
  abuf_json_float(abuf, "maxSendMessageJitter", olsr_cnf->max_jitter);
  abuf_json_int(abuf, "exitValue", olsr_cnf->exit_value);
  // keep all time in ms, so convert this from seconds
  abuf_json_int(abuf, "maxTcValidTime", olsr_cnf->max_tc_vtime * 1000);

  abuf_json_int(abuf, "niit4to6InterfaceIndex", olsr_cnf->niit4to6_if_index);
  abuf_json_int(abuf, "niit6to4InterfaceIndex", olsr_cnf->niit6to4_if_index);

  abuf_json_boolean(abuf, "hasIpv4Gateway", olsr_cnf->has_ipv4_gateway);
  abuf_json_boolean(abuf, "hasIpv6Gateway", olsr_cnf->has_ipv6_gateway);

  abuf_json_int(abuf, "ioctlSocket", olsr_cnf->ioctl_s);
#ifdef __linux__
  abuf_json_int(abuf, "routeNetlinkSocket", olsr_cnf->rtnl_s);
  abuf_json_int(abuf, "routeMonitorSocket", olsr_cnf->rt_monitor_socket);
#endif /* __linux__ */

#if defined __FreeBSD__ || defined __FreeBSD_kernel__ || defined __APPLE__ || defined __NetBSD__ || defined __OpenBSD__
  abuf_json_int(abuf, "routeChangeSocket", olsr_cnf->rts);
#endif /* defined __FreeBSD__ || defined __FreeBSD_kernel__ || defined __APPLE__ || defined __NetBSD__ || defined __OpenBSD__ */
  abuf_json_float(abuf, "linkQualityNatThreshold", olsr_cnf->lq_nat_thresh);

  abuf_json_string(abuf, "olsrdVersion", olsrd_version);
  abuf_json_string(abuf, "olsrdBuildDate", build_date);
  abuf_json_string(abuf, "olsrdBuildHost", build_host);

#if defined _WIN32 || defined _WIN64
  abuf_json_string(abuf, "os", "Windows");
#elif defined __gnu_linux__
  abuf_json_string(abuf, "os", "GNU/Linux");
#elif defined __ANDROID__
  abuf_json_string(abuf, "os", "Android");
#elif defined __APPLE__
  abuf_json_string(abuf, "os", "Mac OS X");
#elif defined __NetBSD__
  abuf_json_string(abuf, "os", "NetBSD");
#elif defined __OpenBSD__
  abuf_json_string(abuf, "os", "OpenBSD");
#elif defined __FreeBSD__ || defined __FreeBSD_kernel__
  abuf_json_string(abuf, "os", "FreeBSD");
#else /* OS detection */
  abuf_json_string(abuf, "os", "Undefined");
#endif /* OS detection */

  abuf_json_int(abuf, "startTime", start_time.tv_sec);

  abuf_json_close_object(abuf);
}

static void
ipc_print_interfaces(struct autobuf *abuf)
{
#ifdef __linux__
  int linklen;
  char path[PATH_MAX], linkpath[PATH_MAX];
#endif /* __linux__ */
  char ipv6_buf[INET6_ADDRSTRLEN];                  /* buffer for IPv6 inet_htop */
  struct olsr_lq_mult *mult;
  const struct olsr_if *ifs;
  abuf_json_open_array(abuf, "interfaces");
  for (ifs = olsr_cnf->interfaces; ifs != NULL; ifs = ifs->next) {
    const struct interface *const rifs = ifs->interf;
    abuf_json_open_array_entry(abuf);
    abuf_json_string(abuf, "name", ifs->name);

    abuf_json_open_array(abuf, "linkQualityMultipliers");
    for (mult = ifs->cnf->lq_mult; mult != NULL; mult = mult->next) {
      abuf_json_open_array_entry(abuf);
      abuf_json_string(abuf, "route",
                       inet_ntop(olsr_cnf->ip_version, &mult->addr, ipv6_buf, sizeof(ipv6_buf)));
      abuf_json_float(abuf, "multiplier", mult->value / 65535.0);
      abuf_json_close_array_entry(abuf);
    }
    abuf_json_close_array(abuf);

    if (!rifs) {
      abuf_json_string(abuf, "state", "down");
    } else {
      abuf_json_string(abuf, "state", "up");
      abuf_json_string(abuf, "nameFromKernel", rifs->int_name);
      abuf_json_int(abuf, "interfaceMode", rifs->mode);
      abuf_json_boolean(abuf, "emulatedHostClientInterface", rifs->is_hcif);
      abuf_json_boolean(abuf, "sendTcImmediately", rifs->immediate_send_tc);
      abuf_json_int(abuf, "fishEyeTtlIndex", rifs->ttl_index);
      abuf_json_int(abuf, "olsrForwardingTimeout", rifs->fwdtimer);
      abuf_json_int(abuf, "olsrMessageSequenceNumber", rifs->olsr_seqnum);
      abuf_json_int(abuf, "olsrInterfaceMetric", rifs->int_metric);
      abuf_json_int(abuf, "olsrMTU", rifs->int_mtu);
      abuf_json_int(abuf, "helloEmissionInterval", rifs->hello_etime);
      abuf_json_int(abuf, "helloValidityTime", rifs->valtimes.hello);
      abuf_json_int(abuf, "tcValidityTime", rifs->valtimes.tc);
      abuf_json_int(abuf, "midValidityTime", rifs->valtimes.mid);
      abuf_json_int(abuf, "hnaValidityTime", rifs->valtimes.hna);
      abuf_json_boolean(abuf, "wireless", rifs->is_wireless);

#ifdef __linux__
      abuf_json_boolean(abuf, "icmpRedirect", rifs->nic_state.redirect);
      abuf_json_boolean(abuf, "spoofFilter", rifs->nic_state.spoof);
#endif /* __linux__ */

      if (olsr_cnf->ip_version == AF_INET) {
        struct ipaddr_str addrbuf, maskbuf, bcastbuf;
        abuf_json_string(abuf, "ipv4Address",
                             ip4_to_string(&addrbuf, rifs->int_addr.sin_addr));
        abuf_json_string(abuf, "netmask",
                             ip4_to_string(&maskbuf, rifs->int_netmask.sin_addr));
        abuf_json_string(abuf, "broadcast",
                             ip4_to_string(&bcastbuf, rifs->int_broadaddr.sin_addr));
      } else {
        struct ipaddr_str addrbuf, maskbuf;
        abuf_json_string(abuf, "ipv6Address",
                             ip6_to_string(&addrbuf, &rifs->int6_addr.sin6_addr));
        abuf_json_string(abuf, "multicast",
                             ip6_to_string(&maskbuf, &rifs->int6_multaddr.sin6_addr));
      }
    }
#ifdef __linux__
    snprintf(path, PATH_MAX, "/sys/class/net/%s/device/driver/module", ifs->name);
    linklen = readlink(path, linkpath, PATH_MAX - 1);
    if (linklen > 1) {
      linkpath[linklen] = '\0';
      abuf_json_string(abuf, "kernelModule", basename(linkpath));
    }

    abuf_json_sys_class_net(abuf, "addressLength", ifs->name, "addr_len");
    abuf_json_sys_class_net(abuf, "carrier", ifs->name, "carrier");
    abuf_json_sys_class_net(abuf, "dormant", ifs->name, "dormant");
    abuf_json_sys_class_net(abuf, "features", ifs->name, "features");
    abuf_json_sys_class_net(abuf, "flags", ifs->name, "flags");
    abuf_json_sys_class_net(abuf, "linkMode", ifs->name, "link_mode");
    abuf_json_sys_class_net(abuf, "macAddress", ifs->name, "address");
    abuf_json_sys_class_net(abuf, "ethernetMTU", ifs->name, "mtu");
    abuf_json_sys_class_net(abuf, "operationalState", ifs->name, "operstate");
    abuf_json_sys_class_net(abuf, "txQueueLength", ifs->name, "tx_queue_len");
    abuf_json_sys_class_net(abuf, "collisions", ifs->name, "statistics/collisions");
    abuf_json_sys_class_net(abuf, "multicastPackets", ifs->name, "statistics/multicast");
    abuf_json_sys_class_net(abuf, "rxBytes", ifs->name, "statistics/rx_bytes");
    abuf_json_sys_class_net(abuf, "rxCompressed", ifs->name, "statistics/rx_compressed");
    abuf_json_sys_class_net(abuf, "rxCrcErrors", ifs->name, "statistics/rx_crc_errors");
    abuf_json_sys_class_net(abuf, "rxDropped", ifs->name, "statistics/rx_dropped");
    abuf_json_sys_class_net(abuf, "rxErrors", ifs->name, "statistics/rx_errors");
    abuf_json_sys_class_net(abuf, "rxFifoErrors", ifs->name, "statistics/rx_fifo_errors");
    abuf_json_sys_class_net(abuf, "rxFrameErrors", ifs->name, "statistics/rx_frame_errors");
    abuf_json_sys_class_net(abuf, "rxLengthErrors", ifs->name, "statistics/rx_length_errors");
    abuf_json_sys_class_net(abuf, "rxMissedErrors", ifs->name, "statistics/rx_missed_errors");
    abuf_json_sys_class_net(abuf, "rxOverErrors", ifs->name, "statistics/rx_over_errors");
    abuf_json_sys_class_net(abuf, "rxPackets", ifs->name, "statistics/rx_packets");
    abuf_json_sys_class_net(abuf, "txAbortedErrors", ifs->name, "statistics/tx_aborted_errors");
    abuf_json_sys_class_net(abuf, "txBytes", ifs->name, "statistics/tx_bytes");
    abuf_json_sys_class_net(abuf, "txCarrierErrors", ifs->name, "statistics/tx_carrier_errors");
    abuf_json_sys_class_net(abuf, "txCompressed", ifs->name, "statistics/tx_compressed");
    abuf_json_sys_class_net(abuf, "txDropped", ifs->name, "statistics/tx_dropped");
    abuf_json_sys_class_net(abuf, "txErrors", ifs->name, "statistics/tx_errors");
    abuf_json_sys_class_net(abuf, "txFifoErrors", ifs->name, "statistics/tx_fifo_errors");
    abuf_json_sys_class_net(abuf, "txHeartbeatErrors", ifs->name, "statistics/tx_heartbeat_errors");
    abuf_json_sys_class_net(abuf, "txPackets", ifs->name, "statistics/tx_packets");
    abuf_json_sys_class_net(abuf, "txWindowErrors", ifs->name, "statistics/tx_window_errors");
    abuf_json_sys_class_net(abuf, "beaconing", ifs->name, "wireless/beacon");
    abuf_json_sys_class_net(abuf, "encryptionKey", ifs->name, "wireless/crypt");
    abuf_json_sys_class_net(abuf, "fragmentationThreshold", ifs->name, "wireless/fragment");
    abuf_json_sys_class_net(abuf, "signalLevel", ifs->name, "wireless/level");
    abuf_json_sys_class_net(abuf, "linkQuality", ifs->name, "wireless/link");
    abuf_json_sys_class_net(abuf, "misc", ifs->name, "wireless/misc");
    abuf_json_sys_class_net(abuf, "noiseLevel", ifs->name, "wireless/noise");
    abuf_json_sys_class_net(abuf, "nwid", ifs->name, "wireless/nwid");
    abuf_json_sys_class_net(abuf, "wirelessRetries", ifs->name, "wireless/retries");
    abuf_json_sys_class_net(abuf, "wirelessStatus", ifs->name, "wireless/status");
#endif /* __linux__ */
    abuf_json_close_array_entry(abuf);
  }
  abuf_json_close_array(abuf);
}

static void
ipc_print_olsrd_conf(struct autobuf *abuf)
{
  olsrd_write_cnf_autobuf(abuf, olsr_cnf);
}

static void
jsoninfo_write_data(void *foo __attribute__ ((unused)))
{
  fd_set set;
  int result, i, j, max;
  struct timeval tv;

  FD_ZERO(&set);
  max = 0;
  for (i=0; i<outbuffer_count; i++) {
    /* And we cast here since we get a warning on Win32 */
    FD_SET((unsigned int)(outbuffer_socket[i]), &set);

    if (outbuffer_socket[i] > max) {
      max = outbuffer_socket[i];
    }
  }

  tv.tv_sec = 0;
  tv.tv_usec = 0;

  result = select(max + 1, NULL, &set, NULL, &tv);
  if (result <= 0) {
    return;
  }

  for (i=0; i<outbuffer_count; i++) {
    if (FD_ISSET(outbuffer_socket[i], &set)) {
      result = send(outbuffer_socket[i],
                    outbuffer[i] + outbuffer_written[i],
                    outbuffer_size[i] - outbuffer_written[i],
                    0);
      if (result > 0) {
        outbuffer_written[i] += result;
      }

      if (result <= 0 || outbuffer_written[i] == outbuffer_size[i]) {
        /* close this socket and cleanup*/
        close(outbuffer_socket[i]);
        free (outbuffer[i]);

        for (j=i+1; j<outbuffer_count; j++) {
          outbuffer[j-1] = outbuffer[j];
          outbuffer_size[j-1] = outbuffer_size[j];
          outbuffer_socket[j-1] = outbuffer_socket[j];
          outbuffer_written[j-1] = outbuffer_written[j];
        }
        outbuffer_count--;
      }
    }
  }
  if (outbuffer_count == 0) {
    olsr_stop_timer(writetimer_entry);
  }
}

static void
send_info(unsigned int send_what, int the_socket)
{
  struct autobuf abuf;

  /* global variables for tracking when to put a comma in for JSON */
  entrynumber[0] = 0;
  currentjsondepth = 0;

  abuf_init(&abuf, 32768);

 // only add if outputing JSON
  if (send_what & SIW_ALL) abuf_puts(&abuf, "{\n");

  if ((send_what & SIW_LINKS) == SIW_LINKS) ipc_print_links(&abuf);
  if ((send_what & SIW_NEIGHBORS) == SIW_NEIGHBORS) ipc_print_neighbors(&abuf);
  if ((send_what & SIW_TOPOLOGY) == SIW_TOPOLOGY) ipc_print_topology(&abuf);
  if ((send_what & SIW_HNA) == SIW_HNA) ipc_print_hna(&abuf);
  if ((send_what & SIW_MID) == SIW_MID) ipc_print_mid(&abuf);
  if ((send_what & SIW_ROUTES) == SIW_ROUTES) ipc_print_routes(&abuf);
  if ((send_what & SIW_GATEWAYS) == SIW_GATEWAYS) ipc_print_gateways(&abuf);
  if ((send_what & SIW_INTERFACES) == SIW_INTERFACES) ipc_print_interfaces(&abuf);
  if ((send_what & SIW_CONFIG) == SIW_CONFIG) {
    if (send_what != SIW_CONFIG) abuf_puts(&abuf, ",");
    ipc_print_config(&abuf);
  }
  if ((send_what & SIW_PLUGINS) == SIW_PLUGINS) ipc_print_plugins(&abuf);

  /* output overarching meta data last so we can use abuf_json_* functions, they add a comma at the beginning */
  if (send_what & SIW_ALL) {
    abuf_json_int(&abuf, "systemTime", time(NULL));
    abuf_json_int(&abuf, "timeSinceStartup", now_times);
    if(*uuid != 0)
      abuf_json_string(&abuf, "uuid", uuid);
    abuf_puts(&abuf, "}\n");
  }

  /* this outputs the olsrd.conf text directly, not JSON */
  if ((send_what & SIW_OLSRD_CONF) == SIW_OLSRD_CONF) {
    ipc_print_olsrd_conf(&abuf);
  }

  outbuffer[outbuffer_count] = olsr_malloc(abuf.len, "txt output buffer");
  outbuffer_size[outbuffer_count] = abuf.len;
  outbuffer_written[outbuffer_count] = 0;
  outbuffer_socket[outbuffer_count] = the_socket;

  memcpy(outbuffer[outbuffer_count], abuf.buf, abuf.len);
  outbuffer_count++;

  if (outbuffer_count == 1) {
    writetimer_entry = olsr_start_timer(100,
                                        0,
                                        OLSR_TIMER_PERIODIC,
                                        &jsoninfo_write_data,
                                        NULL,
                                        0);
  }

  abuf_free(&abuf);
}

/*
 * Local Variables:
 * mode: c
 * style: linux
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * End:
 */


text:
<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword ;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [ "fullname", "username", "email", "gender", "position", "level" , "password" ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

	function assessment()
	{
		return $this->hasMany('App\Assessment' , 'user_id');
	}
}


text:
<?php

class Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentTrainingPhrase extends Google_Collection
{
  protected $collection_key = 'parts';
  public $name;
  protected $partsType = 'Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart';
  protected $partsDataType = 'array';
  public $timesAddedCount;
  public $type;

  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart[]
   */
  public function setParts($parts)
  {
    $this->parts = $parts;
  }
  /**
   * @return Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart[]
   */
  public function getParts()
  {
    return $this->parts;
  }
  public function setTimesAddedCount($timesAddedCount)
  {
    $this->timesAddedCount = $timesAddedCount;
  }
  public function getTimesAddedCount()
  {
    return $this->timesAddedCount;
  }
  public function setType($type)
  {
    $this->type = $type;
  }
  public function getType()
  {
    return $this->type;
  }
}


text:
load 'lib/Base.rb'

class Dashboard < Base

  def initialize
    super("dashboard")
  end

end


text:
<?php

namespace Base\TemplateBundle\Repository;

use Doctrine\ORM\EntityRepository;

class TemplateRepository extends EntityRepository
{
}

?>


text:
Advent of Code 2015

What is this?

Advent of Code is a series of small programming puzzles for a variety of skill levels by Eric Wastl.

This repository contains the solutions for Advent of Code that I've come up with.

They're written in C# and might not be the most optimal solution at all but hey! It's chritmas time and I'm having fun.

I strongly encourage you to check out Advent of Code for yourself if you haven't already.

How to run a solution?

All solutions are written using Visual Studio Code using .NET Core v. 1.0. Please refer to the offical install instructions at Microsoft.com.

NuGet packages must be restored prior to running the tests or solutions.

Restore NuGet packages

dotnet restore

Run solution

dotnet run

Run unit tests

dotnet run

Merry Christmas!


text:
define(['rickshaw'], function(Rickshaw) {
	var CorrelateHoverDetail = Rickshaw.Class.create(Rickshaw.Graph.HoverDetail, {
		initialize: function(args) {
			this.vent = args.vent;
			Rickshaw.Graph.HoverDetail.prototype.initialize.apply(this, arguments);
		},
		hide: function() {
			Rickshaw.Graph.HoverDetail.prototype.hide.apply(this, arguments);
			this.vent.trigger('stop-hover', this.graph.lastActivePoint);
		},
		formatter: function(series, x, y) {
			var resource = series.display_name+'
';
			var swatch = '';
			var content = resource+swatch + series.metric_name + ": " + formatVal(y, series.unit) +'
';// + date;
			return content;
		},
		xFormatter: function(x) {
			return moment.unix(x).format('MM/D/YYYY HH:mm [GMT]ZZ')
		},
		render: function(args) {
			var graph = this.graph;
			var points = args.points.filter(function(d){return d.value.y !== null});

			var point = _.filter(_.sortBy(points, function(p){return p.distance}),
				function(d){return d.value.y !== null}).shift();

			if (!point) {
				// use the null point if no real points are present
				point = args.points.filter( function(p) { return p.active } ).shift();
			}

			// store the currently-hovered x coordinate
			graph.activePoint = point.value.x;

			var point_position = point.value.y

			var close_points = points.filter(function(p) {
				return Math.abs(graph.y(point_position) - graph.y(p.value.y)) < 30
			});

			this.element.innerHTML = '';

			this.element.style.left = graph.x(point.value.x) + 'px';

			var xLabel = document.createElement('div');

			xLabel.className = 'x_label';
			xLabel.innerHTML = point.formattedXValue;
			this.element.appendChild(xLabel);

			if (point.value.y === null) {
				this.element.classList.remove('inactive');
				this.vent.trigger('stop-hover', this.graph.lastActivePoint);
				var alignables = [xLabel];

			} else {

				var item = document.createElement('div');
				item.className = 'item';

				_.each(close_points, function(point) {

					// invert the scale if this series displays using a scale
					var series = point.series;
					var actualY = series.scale ? series.scale.invert(point.value.y) : point.value.y;

					var formattedXValue = point.formattedXValue;
					var formattedYValue = point.formattedYValue;

					item.innerHTML += this.formatter(series, point.value.x, actualY, formattedXValue, formattedYValue, point);
					item.style.top = this.graph.y(point.value.y0 + point.value.y) + 'px';

					var dot = document.createElement('div');
					dot.className = 'dot';

					dot.style.borderColor = series.color;
					dot.style.top = item.style.top;
					dot.classList.add('active');

					this.element.appendChild(dot);

				}, this);

				this.element.appendChild(item);
				item.classList.add('active');

				var alignables = [xLabel, item];
			}

			// Assume left alignment until the element has been displayed and
			// bounding box calculations are possible.
			alignables.forEach(function(el) {
				el.classList.add('left');
			});

			this.show();

			// If left-alignment results in any error, try right-alignment.
			var leftAlignError = this._calcLayoutError(alignables);
			if (leftAlignError > 0) {
				alignables.forEach(function(el) {
					el.classList.remove('left');
					el.classList.add('right');
				});

				// If right-alignment is worse than left alignment, switch back.
				var rightAlignError = this._calcLayoutError(alignables);
				if (rightAlignError > leftAlignError) {
					alignables.forEach(function(el) {
						el.classList.remove('right');
						el.classList.add('left');
					});
				}
			}

			this.vent.trigger('hover-time', point.value.x);

		}
	});

	return CorrelateHoverDetail;
});


text:
require 'nokogiri'
require 'open-uri'
require 'ruby-progressbar'
require_relative '../spec_helper'
require_relative '../../app/scrapers/scraper_common'

# FIXME: fails with 'undefined method get_page for ScraperCommon:Module' and I'm not sure why
class FakeScraper
  include ScraperCommon

  def scrape(*args)
    args
  end
end

describe ScraperCommon, :scraper, :util do
  let(:common) { Class.new { extend ScraperCommon } }

  # get_semesters
  context '#get_semesters' do
    context '#get_semesters(["2018"])' do
      let(:actual) { common.get_semesters(['2018']) }

      it '=> ["201801", "201805", "201808", "201812"]' do
        expect(actual).to eq(%w[201801 201805 201808 201812])
      end

      it 'contains only strings' do
        expect(actual).to all be_a String
      end
    end

    context 'get_semesters(["2018", "2019", "2020"])' do
      let(:actual) { common.get_semesters(%w[2018 2019 2020]) }

      it '=> ["201801", "201805", "201808", "201812", "201901", "201905", "201908", "201912", "202001", "202005", "202008", "202012"]' do
        expect(actual).to eq(%w[201801 201805 201808 201812
                                201901 201905 201908 201912
                                202001 202005 202008 202012])
      end

      it 'contains only strings' do
        expect(actual).to all be_a String
      end
    end

    context 'when passed a single year instead of an array of years' do
      let(:actual) { common.get_semesters('2020') }
      it 'behaves the same as if a similar one-element array was passed' do
        expect(common.get_semesters('2020')).to eq(common.get_semesters(['2020']))
        expect(common.get_semesters('2018')).to eq(common.get_semesters(['2018']))
      end
      it 'may be either a number of a string' do
        expect(common.get_semesters(2019)).to eq common.get_semesters('2019')
        expect(common.get_semesters(2020)).to eq common.get_semesters('2020')
      end
    end

    context 'bad input raises an ArgumentError' do
      it 'get_semesters()' do
        expect { common.get_semesters }.to raise_error ArgumentError
      end
      it 'get_semesters(false)' do
        expect { common.get_semesters(false) }.to raise_error ArgumentError
      end
      it 'get_semesters(-1)' do
        expect { common.get_semesters(-1) }.to raise_error ArgumentError
      end
      it 'get_semesters(nil)' do
        expect { common.get_semesters(nil) }.to raise_error ArgumentError
      end
      it 'get_semesters(1492)' do
        expect { common.get_semesters(1492) }.to raise_error ArgumentError
      end
      it 'get_semesters("300")' do
        expect { common.get_semesters(300) }.to raise_error ArgumentError
      end
      it 'get_semesters(2019.0)' do
        expect { common.get_semesters(2019.0) }.to raise_error ArgumentError
      end
      it 'get_semesters("Hello, world!")' do
        expect { common.get_semesters('Hello, world!') }.to raise_error ArgumentError
      end
    end
  end

  # get_page
  context '#get_page(url, prog_name)' do
    let(:valid_url) { 'https://umd.edu' }
    let(:bad_url_404) { 'https://www.cs.umd.edu/foobarbaz' }

    context 'when given a valid page url' do
      context 'to a page which exists' do
        let(:doc) do
          common.logger.level = :fatal
          common.get_page(valid_url, 'foo_scraper')
        end

        it 'returns a document' do
          expect(doc.class).to be Nokogiri::HTML::Document
        end
      end

      context 'to a page which does not exist' do
        let(:actual) do
          common.logger.level = :fatal
          common.get_page(bad_url_404, 'foo_scraper')
        end

        it 'raises an HTTPError' do
          expect { actual }.to raise_error(OpenURI::HTTPError)
        end

        it 'specifies the correct error code' do
          begin
            actual
            fail 'An HTTPError should have been raised'
          rescue OpenURI::HTTPError => e
            expect(e).to respond_to :io
            expect(e.io.status).to eq ["404", "Not Found"]
          end
        end
      end
    end

  end

  # logger
  context '#logger' do
    let(:logger) { common.logger }

    it 'is an instance of the built-in ruby logger' do
      expect(logger).to be_a Logger
    end

    it 'only creates one logger instance, no matter how many times it is called' do
      new_logger = common.logger
      expect(logger).to eq new_logger
    end

    it 'responds to #debug' do
      expect(logger).to respond_to :debug
    end

    it 'responds to #info' do
      expect(logger).to respond_to :info
    end

    it 'responds to #warn' do
      expect(logger).to respond_to :warn
    end

    it 'responds to #error' do
      expect(logger).to respond_to :error
    end

    it 'responds to #fatal' do
      expect(logger).to respond_to :fatal
    end

    it 'responds to #unknown' do
      expect(logger).to respond_to :fatal
    end
  end

  context '#log' do
    let(:bar) { common.get_progress_bar }

    it 'raises an ArgumentError when not provided a block' do
      expect { common.log(bar, :info) }.to raise_error ArgumentError
    end

    context 'when no log level is provided' do
      let(:actual) { common.logger.level = :fatal; common.log(bar) { 'some message' } }

      it 'returns nil' do
        expect(actual).to be_nil
      end

      it 'defaults to info' do
        # TODO how would you check it uses info?
        expect(actual).to be_nil
      end
    end

    context 'when a log level is provided' do
      it 'returns nil' do
        expect(common.log(bar, :debug) { 'message' }).to be_nil
      end

      it 'may be a string or a symbol' do
        common.logger.level = :fatal
        expect(common.log(bar, :debug) { 'message' }).to be_nil
        expect(common.log(bar, 'debug') { 'message' }).to be_nil
      end

      context 'with an invalid log level' do
        it 'raises an ArgumentError' do
          expect { common.log(bar, :foobarbaz) { 'msg' }}.to raise_error ArgumentError
          expect { common.log(bar, :verbose) { 'msg' }}.to raise_error ArgumentError
          expect { common.log(bar, false) { 'msg' }}.to raise_error ArgumentError
        end
      end

      context 'with a valid log level' do
        [:debug, :info, :warn, :error, :fatal, :unknown].each do |lvl|
          context "with log level #{lvl.to_s}" do
            let(:actual) do
              common.logger.level = :fatal
              common.log(bar, lvl) { 'some msg' }
            end

            it 'does not throw' do
              # expect { common.log(bar, lvl) { 'some msg' }}.not_to raise_error
              expect { actual }.not_to raise_error
            end

            it 'returns nil' do
              expect(actual).to be_nil
            end
          end
        end
      end # !valid log level
    end
  end

  describe '#utf_safe(text)' do
    before :all do
      @text = 'hi, mom!'
    end

    # let(:actual) { scraper.utf_safe text }

    context 'when given a UTF-8 encoded string' do
      it 'has no effect' do
        expect(@text.encoding).to be Encoding::UTF_8
        expect(common.utf_safe(@text)).to be @text
      end
    end

    context 'when given a non-UTF-8 encoded string' do
      context 'when the encoding is valid' do
        let(:actual) { common.utf_safe(@text.encode(Encoding::ISO_8859_1)) }

        it 'has no effect' do
          expect(actual.encoding).to be Encoding::ISO_8859_1
          expect(actual).to eq @text
        end
      end

      context 'when the encoding is not valid' do
        before :all do
          @text = "\xc2".force_encoding('UTF-8')
          expect(@text).not_to be_valid_encoding
        end

        let(:actual) { common.utf_safe @text }

        it 'result is encoded with UTF-8' do
          expect(actual.encoding).to be Encoding::UTF_8
        end

        it 'result has a valid encoding' do
          expect(actual).to be_valid_encoding
        end

        it 'replaces invalid characters with the empty string' do
          expect(actual).to eq ''
        end
      end
    end
  end

  context '#get_progress_bar' do
    let(:bar) { common.get_progress_bar }

    it 'returns a progress bar' do
      pending 'ruby does not recognize ProgressBar being imported??'
      expect(bar).to be_an_instance_of ProgressBar
    end

    it 'is not finished' do
      expect(bar.finished?).to be_falsey
    end
  end

  context '#run_scraper' do

    # let(:mock_scraper) { instance_double(FakeScraper) }
    before(:each) do
      @mock_scraper = FakeScraper.new
      @mock_scraper.logger.level = :warn
    end

    it 'is an instance method' do
      expect(common).to respond_to :run_scraper
    end

    it 'throws if #scrape is not defined' do
      expect { common.run_scraper }.to raise_error StandardError
    end

    it 'returns the scrape duration in seconds' do
      expect(@mock_scraper.run_scraper).to be_a_kind_of Float
    end

    it 'forwards arguments to #scrape' do
      @mock_scraper.stub(:scrape) { |arg| arg }
      @mock_scraper.run_scraper('some args')
      expect(@mock_scraper).to have_received(:scrape).with('some args')
    end

    it 'takes any number of arguments' do
      # @mock_scraper.stub(:scrape) { |arg| arg }
      @mock_scraper.logger.level = :error
      expect { @mock_scraper.run_scraper() }.to_not raise_error
      expect { @mock_scraper.run_scraper(5) }.to_not raise_error
      expect { @mock_scraper.run_scraper(:foo, 'bar') }.to_not raise_error
      expect { @mock_scraper.run_scraper([1, 2, 3]) }.to_not raise_error
      expect { @mock_scraper.run_scraper(foo: 'foo', bar: :baz)}.to_not raise_error
    end

  end
end


text:
<meta http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<meta name=ProgId content=Word.Document>
<meta name=Generator content="Microsoft Word 9">
<meta name=Originator content="Microsoft Word 9">
<link rel=File-List href="./simplex_files/filelist.xml">
<link rel=Edit-Time-Data href="./simplex_files/editdata.mso">

<title>Compaq Code Wars IV</title>

<link rel=Stylesheet type="text/css" media=all href=cw4task.css>

<![if !supportEmptyParas]> <![endif]><o:p></o:p>

  <o:p></o:p>

P <o:p></o:p>

R <o:p></o:p>

O <o:p></o:p>

G <o:p></o:p>

R <o:p></o:p>

A <o:p></o:p>

M <o:p></o:p>

M <o:p></o:p>

I <o:p></o:p>

N <o:p></o:p>

G <o:p></o:p>

  <o:p></o:p>

C <o:p></o:p>

O <o:p></o:p>

M <o:p></o:p>

P <o:p></o:p>

E <o:p></o:p>

T <o:p></o:p>

I <o:p></o:p>

T <o:p></o:p>

I <o:p></o:p>

O <o:p></o:p>

N <o:p></o:p>

  <o:p></o:p>

Simplex Manufacturing

Task #14
  <o:p></o:p>

Advanced <o:p></o:p>

15
  Points <o:p></o:p>

Task Description

Computers can aided greatly in the
analysis of critical business factors in order to make optimum business
operations decisions.  Your task is to determine the optimum product mix in order
to achieve total optimum revenue each week for a given set of variable
operational factors and variables market conditions for Compaq Computer
Corporation.

There is a given set of fixed factors that will be the
same every week.  The fixed factors
are as follows:<o:p></o:p>

<![if !supportLists]>§
<![endif]>There are 40 worker-hours available per
manufacturing employee to build product each week.<o:p></o:p>

<![if !supportLists]>§
<![endif]>It takes 3 hours for 1 manufacturing employee to
assemble a Compaq ProLiant Server.<o:p></o:p>

<![if !supportLists]>§
<![endif]>It takes 1 hours for 1 manufacturing employee to
assemble a Compaq Laptop computer.<o:p></o:p>

<![if !supportLists]>§
<![endif]>It takes 20 lbs. of sheet metal to build one Compaq
ProLiant Server.<o:p></o:p>

<![if !supportLists]>§
<![endif]>It takes 2 lb. Of sheet metal to build one Compaq
Laptop computer.<o:p></o:p>

<![if !supportLists]>§
<![endif]>It takes 1 lb. of plastic to build one Compaq ProLiant
Server.<o:p></o:p>

<![if !supportLists]>§
<![endif]>It takes 3 lbs. of plastic to build one Compaq
Laptop Computer.<o:p></o:p>

<![if !supportLists]>§
<![endif]>Demand for Compaq products is such that every
server or laptop assembled is immediately considered sold and included in that
week’s revenue <o:p></o:p>

The
weekly fluctuating factors, which will be the Program Input are as follows:<o:p></o:p>

<![if !supportLists]>§
<![endif]>Number of Manufacturing employees available to work
for a given week.<o:p></o:p>

<![if !supportLists]>§
<![endif]>Lbs. of plastic on hand for a given week.<o:p></o:p>

<![if !supportLists]>§
<![endif]>Lbs. of sheet metal available for a given week.<o:p></o:p>

<![if !supportLists]>§
<![endif]>Selling Price of a Compaq ProLiant Server.<o:p></o:p>

<![if !supportLists]>§
<![endif]>Selling Price of a Compaq Laptop Computer.<o:p></o:p>

Program Input

The input file will contain 12
lines that correspond to 12 different weeks.  Each line will consist of 5 numbers that are separated by
commas: # of employees, # of Lbs. of Sheet metal available, # of Lbs. of
plastic available, Server Selling Price, Laptop Selling Price.

For example the input on one line would be:<o:p></o:p>

511,
4025, 3000, 6400, 2350

<![if !supportLineBreakNewLine]>

<![endif]><o:p></o:p>

Program
Output

The program must respond to each
week’s input line by generating one output line that has 3 numbers separated by
commas: optimum # of servers to manufacture, optimum # of laptops to
manufacture, Optimum Total Revenue generated (in dollars, rounded to the
nearest dollar).  Compaq can’t ship
partially assembled units so only count the # of whole units that can be
manufactured when outputting the optimum #’s of servers and laptops.  Since the Program Input will have 12
lines, the Program Output should also have 12 lines. <o:p></o:p>

The
example single input line given above would generate the following output example:
<o:p></o:p>

104,
965, 2933350<o:p></o:p>

This
signifies that to achieve the optimum revenue for the given example week,
Compaq manufacturing should assemble 104 servers and 965 laptops for total
revenue of $2,933,350 dollars.  <o:p></o:p>

<![if !supportEmptyParas]> <![endif]><o:p></o:p>


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

    <string name="app_name">Route Finder</string>
    <string name="title_activity_maps">Map</string>
    <string name="find_route">Find route</string>
    <string name="finding_route">Finding route</string>
    <string name="please_wait">Please wait</string>
    <string name="find_transit">Find transit</string>
    <string name="error_unknown">Unknown error</string>
    <string name="main_address_from_hint">From</string>
    <string name="main_address_target_hint">Target</string>
    <string name="drive">Drive</string>
    <string name="transit">Transit</string>
    <string name="minutes">minutes</string>
    <string name="km">km</string>
    <string name="arrival_time">Arrival time</string>
    <string name="date_time_title">Select date/time</string>
    <string name="error_server">Server couldn\'t find desired route</string>
    <string name="error_parse_server">Server returned malformed data</string>
    <string name="transfer">Transfer</string>

</resources>


text:
var childProcess = require('child_process'),
    fs = require('fs');

module.exports = function(grunt) {
  grunt.registerTask('test:bin', function() {
    var done = this.async();

    childProcess.exec('./bin/handlebars -a spec/artifacts/empty.handlebars', function(err, stdout) {
      if (err) {
        throw err;
      }

      var expected = fs.readFileSync('./spec/expected/empty.amd.js');
      if (stdout.toString() !== expected.toString()) {
        throw new Error('Expected binary output differed:\n\n"' + stdout + '"\n\n"' + expected + '"');
      }

      done();
    });
  });
  grunt.registerTask('test:mocha', function() {
    var done = this.async();

    var runner = childProcess.fork('./spec/env/runner', [], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal(code + ' tests failed');
      }
      done();
    });
  });
  grunt.registerTask('test', ['test:bin', 'test:mocha']);
};