text:
import os
from functools import partial

from kivy.properties import ObjectProperty, StringProperty, NumericProperty, BooleanProperty
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.logger import Logger
from kivy.uix.relativelayout import RelativeLayout

from .context_menu import ContextMenuItem, ContextMenuTextItem, ContextMenuHoverableItem
from .ffmpeg_cli import FFmpegCLI

_path = os.path.dirname(os.path.realpath(__file__))

class DesktopVideoPlayer(RelativeLayout):

    _video = ObjectProperty(None)
    _notify_bubble = ObjectProperty(None)
    _volume_slider = ObjectProperty(None)
    _volume_btn = ObjectProperty(None)
    _info_box = ObjectProperty(None)

    _show_info_menu_option = ObjectProperty(None)
    _take_screenshot_menu_option = ObjectProperty(None)

    context_menu = ObjectProperty(None)
    # _advanced_options = kp.ObjectProperty(None)

    remaining_label = ObjectProperty(None)
    play_btn = ObjectProperty(None)
    bottom_layout = ObjectProperty(None)

    # path = kp.StringProperty(_path)
    current_play_btn_image = StringProperty('')
    current_volume_btn_image = StringProperty('')

    source = StringProperty('')
    volume = NumericProperty(1.0)

    mouse_hover = BooleanProperty(False)
    auto_play = BooleanProperty(True)
    show_elapsed_time = BooleanProperty(True)
    volume_muted = BooleanProperty(False)
    check_mouse_hover = BooleanProperty(False)

    _initialized = BooleanProperty(False)

    # last_file_selected = StringProperty('')

    def __init__(self, **kwargs):
        super(DesktopVideoPlayer, self).__init__(**kwargs)

        # self.register_event_type('on_context_menu_show')
        # self.register_event_type('on_context_menu_hide')

        self._bubble_anim = None
        self._bubble_timeout = None
        self._mouse_check_timer = None
        self._advanced_options_parent = None
        self._update_play_btn_image()
        self._update_volume_btn_image()

        self.check_mouse_hover = True
        Window.bind(on_key_down=self._on_key_down)

        # self.video.bind(duration=self.setter('duration'),
        #                 position=self.setter('position'),
        #                 volume=self.setter('volume'),
        #                 source=self.setter('source'),
        #                 state=self.setter('state'))

    def _init(self, *args):
        self.context_menu.visible = False
        # self.context_menu.add_item("Jump to", on_release=self._context_item_release)
        self.remove_widget(self._notify_bubble)
        self.remove_widget(self._info_box)

        # self._advanced_options_parent = self._advanced_options.parent
        # self._advanced_options.parent.remove_widget(self._advanced_options)

        self._ffmpeg = FFmpegCLI()
        self._ffmpeg.is_available(lambda result: self._toggle_video_menu_options(result))
        self._initialized = True

    def _toggle_video_menu_options(self, available):
        self._show_info_menu_option.disabled = not available
        self._take_screenshot_menu_option.disabled = not available

    @property
    def context_menu_visible(self):
        return bool(self.context_menu)

    def on_check_mouse_hover(self, obj, new_value):
        if new_value:
            self._mouse_check_timer = Clock.schedule_interval(partial(self._check_mouse_hover), 0.1)
        else:
            self._mouse_check_timer.cancel()

    def show_notify_bubble(self, text, timeout=None):
        if not self._notify_bubble.parent:
            self.add_widget(self._notify_bubble)

        if self._bubble_anim:
            self._bubble_anim.cancel(self._notify_bubble)

        self._notify_bubble.text = text
        self._bubble_anim = Animation(opacity=1.0, duration=0.25)
        self._bubble_anim.start(self._notify_bubble)

        if self._bubble_timeout:
            self._bubble_timeout.cancel()
        if timeout:
            self._bubble_timeout = Clock.schedule_once(partial(self.hide_notify_bubble), timeout)

    def hide_notify_bubble(self, *args):
        def _hide(*args):
            self.remove_widget(self._notify_bubble)
            self._bubble_timeout = None

        self._bubble_anim = Animation(opacity=0.0, duration=0.25)
        self._bubble_anim.bind(on_complete=_hide)
        self._bubble_anim.start(self._notify_bubble)

    def _loaded(self):
        if self._video.duration != -1:
            Logger.info('Loaded %s, duration %d', self._video.source, self._video.duration)
            # self._video.seek(0)
            self.ids.progress_bar.max = self._video.duration
            if self._video.duration != 1:
                self._video.opacity = 1.0
            if self.auto_play:
                self._video.state = 'play'

    def _update_progress(self, val):
        self._update_remaining_time()
        self.ids.progress_bar.value = val

    def _update_remaining_time(self):
        duration = self._video.duration
        progress = self._video.position
        if self.show_elapsed_time:
            self.remaining_label.text = self.sec_to_time_str(progress, force_hours=duration > 3600)
        else:
            self.remaining_label.text = '-' + self.sec_to_time_str(duration - progress, force_hours=duration > 3600)

    def sec_to_time_str(self, sec, force_hours=False, force_decimals=False):
        hours = int(sec / 3600) if sec >= 3600 else 0
        minutes = int((sec - (hours * 3600)) / 60)
        seconds = int(sec - hours * 3600 - minutes * 60)

        time_str = '%02d:%02d:%02d' % (hours, minutes, seconds) if force_hours or hours > 0 else \
            '%02d:%02d' % (minutes, seconds)
        if force_decimals:
            time_str += str(sec - int(sec))[1:]

        return time_str

    def seek(self, instance, pos):
        self._video.seek = pos

    def toggle_video(self):
        """
        Play/Pause video
        """
        if self._video.duration == -1:
            return

        if self._video.state == 'play':
            self._video.state = 'pause'
        else:
            self._video.state = 'play'

    def _video_state_changed(self):
        self._update_play_btn_image()

    def _check_mouse_hover(self, *args):
        widget_pos = self.to_window(0, 0)
        # p = self.to_local(*Window.mouse_pos)
        # print(p, self.pos, self.to_local(*p), self.to_window(*p))
        # print(self.to_window(*p))
        p = Window.mouse_pos[0] - widget_pos[0], Window.mouse_pos[1] - widget_pos[1]
        # print(mouse_pos, p)

        if (self.x < p[0] - 1 and p[0] + 1 < self.right) and (self.y < p[1] - 2 and p[1] < self.top):
        # if self.collide_point(*p):
            self.bottom_layout.opacity = 1
            self.mouse_hover = True
        else:
            self.bottom_layout.opacity = 0
            self.mouse_hover = False

        if self._volume_btn.collide_point(*p):
            self._volume_slider.opacity = 1
            self._volume_slider.disabled = False
            self._volume_slider.y = self._volume_slider.parent.pos[1] + self._volume_slider.parent.height
        elif not self._volume_btn.collide_point(*p) and not self._volume_slider.collide_point(*p):
            self._volume_slider.opacity = 0
            self._volume_slider.disabled = True
            self._volume_slider.y = -100000

    def toggle_remaining_time(self, label_obj):
        self.show_elapsed_time = False if self.show_elapsed_time else True
        self._update_remaining_time()

    def on_source(self, obj, value):
        Logger.info('Opening "%s"', value)
        self._video.source = value

    def on_volume(self, obj, new_value):
        self._video.volume = new_value
        self._update_volume_btn_image()

    def _on_key_down(self, *args):
        keycode = args[1]
        if keycode == 32:
            self.toggle_video()

    def _on_touch_down(self, obj, click_event):
        if self.collide_point(*click_event.pos):
            if click_event.button == 'left':
                if self.context_menu.visible:
                    self.context_menu.visible = False
                else:
                    self.toggle_video()
            elif click_event.button == 'right':
                p = self._mouse_pos_to_widget_relative(click_event.pos)
                self.context_menu.show(*p)
        else:
            self.context_menu.visible = False

    def _get_play_image(self):
        if self._video is None or (self._video and (self._video.state == 'pause' or self._video.state == 'stop')):
            return os.path.join(_path, "imgs/play.png")
        else:
            return os.path.join(_path, "imgs/pause.png")

    def _get_volume_image(self):
        if not self._video:
            return os.path.join(_path, "imgs/volume_on.png")

        if self._video.volume == 0.0:
            return os.path.join(_path, "imgs/volume_off.png")
        if self._volume_slider.value_normalized > 0.5:
            return os.path.join(_path, "imgs/volume_on.png")
        else:
            return os.path.join(_path, "imgs/volume_on_50.png")

    def _update_play_btn_image(self):
        self.current_play_btn_image = self._get_play_image()

    def _update_volume_btn_image(self):
        self.current_volume_btn_image = self._get_volume_image()

    def toggle_muted(self):
        # negate boolean value represented as BooleanProperty
        # @todo: There might be an easier way
        # self.volume_muted = True if not self.volume_muted else False
        self.volume_muted = not bool(self.volume_muted)
        if self.volume_muted:
            self._video.volume = 0
        else:
            self._video.volume = self._volume_slider.value_normalized
        self._update_volume_btn_image()

    def _mouse_pos_to_widget_relative(self, pos):
        return pos[0] - self.pos[0], pos[1] - self.pos[1]

    def jump_to(self, hours, minutes, seconds):
        total_seconds = hours * 3600 + minutes * 60 + seconds
        if total_seconds > self._video.duration:
            self._video.seek(1)
        else:
            self._video.seek(float(total_seconds) / self._video.duration)
        self.context_menu.visible = False

    def take_screenshot(self, position, dest_dir):
        time_str = self.sec_to_time_str(round(position, 3), force_decimals=True, force_hours=True)
        frames = self._advanced_options.get_frames()
        file_format = self._advanced_options.get_selected_format()
        destination_file = os.path.join(dest_dir, os.path.splitext(os.path.basename(self.source))[0] + '-' +
                                 time_str.replace(':', '-'))
        counter_format = None

        if frames > 1:
            counter_format = '%0' + str(int(frames / 10.0) + 1) + 'd'
            destination_file += '_' + counter_format
        destination_file += '.' + file_format

        Logger.info('Saving screenshot from %s (%d frames) to "%s"', time_str, frames,  destination_file)

        self.show_notify_bubble('Taking screenshot' + ('s' if frames > 1 else '') + ' ...')

        def _show_notify(code, out, err):
            if counter_format:
                human_file_name = destination_file.replace(counter_format, '[0-' + str(frames - 1) + ']')
            else:
                human_file_name = destination_file
            self.show_notify_bubble('Saved to {path}'.format(path=human_file_name), 5)

        self._ffmpeg.take_screenshot(self.source, self._video.position, destination_file, _show_notify, frames=frames)
        self.context_menu.visible = False

    # def save_screenshot_to_desktop(self):
    #     pass

    def save_screenshot_to_home_dir(self):
        self.take_screenshot(self._video.position, os.path.expanduser('~'))

    def save_screenshot_to_the_same_dir(self):
        self.take_screenshot(self._video.position, os.path.dirname(os.path.realpath(self.source)))

    def save_screenshot_to_dir(self, dir):
        if not os.path.exists(dir):
            return
        self.take_screenshot(self._video.position, dir)

    def show_info(self):
        print(self._ffmpeg)

        def _show_info(code, out, err):
            self.show_info_box(err)

        self._ffmpeg.get_info(self.source, _show_info, True)
        self.context_menu.visible = False

    def hide_info_box(self):
        def _hide(*args):
            self.remove_widget(self._info_box)

        self.check_mouse_hover = True
        anim = Animation(opacity=0, duration=0.25)
        anim.bind(on_complete=_hide)
        anim.start(self._info_box)

    def show_info_box(self, text):
        self._info_box.content.text = text
        self.check_mouse_hover = False

        if not self._info_box.parent:
            self.add_widget(self._info_box)

        anim = Animation(opacity=1, duration=0.25)
        anim.start(self._info_box)

class JumpToMenu(ContextMenuHoverableItem):

    def __init__(self, *args, **kwargs):
        super(JumpToMenu, self).__init__(*args, **kwargs)
        self.register_event_type('on_jump_button_released')

    def on_touch_down(self, click_event):
        super(JumpToMenu, self).on_touch_down(click_event)
        return self.collide_point(click_event.x, click_event.y)

    def get_time_str(self):
        return self.hours_input.text + ':' + self.minutes_input.text + ':' + self.seconds_input.text

    def on_jump_button_released(self, hours, minutes, seconds):
        pass

    def _dispatch_jump_event(self, hours, minutes, seconds):
        def _str_to_int(s):
            try:
                return int(s.strip())
            except ValueError:
                return 0

        hours = abs(_str_to_int(hours))
        minutes = abs(_str_to_int(minutes)) % 60
        seconds = abs(_str_to_int(seconds)) % 60
        self.dispatch('on_jump_button_released', hours, minutes, seconds)

class TakeScreenshotSaveTo(ContextMenuTextItem):
    def __init__(self, **kwargs):
        super(TakeScreenshotSaveTo, self).__init__(**kwargs)
        self.register_event_type('on_save_released')

    def on_save_released(self, text):
        pass

class AdvancedOptions(ContextMenuItem):
    _format_png_btn = ObjectProperty(None)
    _format_jpg_btn = ObjectProperty(None)
    _frames_input = ObjectProperty(None)

    def on_touch_down(self, click_event):
        super(AdvancedOptions, self).on_touch_down(click_event)
        return self.collide_point(click_event.x, click_event.y)

    def get_selected_format(self):
        if self._format_png_btn.state == 'down':
            return 'png'
        elif self._format_jpg_btn.state == 'down':
            return 'jpg'

    def get_frames(self):
        try:
            return int(self._frames_input.text.strip())
        except:
            return 1

# class CustomVideoPlayerProgressBar(VideoPlayerProgressBar):
#     def _update_bubble(self, *l):
#         seek = self.seek
#         if self.seek is None:
#             if self.video.duration == 0:
#                 seek = 0
#             else:
#                 seek = self.video.position / self.video.duration
#         # convert to minutes:seconds
#         d = self.video.duration * seek
#         minutes = int(d / 60)
#         seconds = int(d - (minutes * 60))
#         # fix bubble label & position
#         self.bubble_label.text = '%d:%02d' % (minutes, seconds)
#         self.bubble.center_x = self.x + seek * self.width
#         self.bubble.y = self.top / 2 + 5

Builder.load_file(os.path.join(_path, 'desktop_video_player.kv'))


text:
typedef int Py_ssize_t;
#endif

using std::cout;
using std::endl;

using std::exception;

using PyPlanner::PyVectorFieldFunction;

using Math::Vector;
using Math::ConvergenceResult;
using Optimization::NewtonRoot;

double rootTolF = 1e-4;
double rootTolX = 1e-7;
NewtonRoot* root = NULL;
PyVectorFieldFunction* theFn = NULL;

// TODO: Python exceptions

void setFTolerance(double tolf)
{
  rootTolF = tolf;
  if(root) root->tolf=tolf;
}

void setXTolerance(double tolx)
{
  rootTolX = tolx;
  if(root) root->tolx=tolx;
}

// Instance of subclass of Python VectorFieldFunction object
// (see vectorfield.py) - pVFObj
int setVectorField(PyObject* pVFObj) {
	destroy();

	theFn = new PyVectorFieldFunction(pVFObj);
	if(!theFn->is_init()) {
		delete theFn;
		theFn = NULL;
		return 0;
	}

	root = new NewtonRoot(theFn);
	root->tolf = rootTolF;
	root->tolx = rootTolX;
	return 1;
}

PyObject* PyListFromVector(const Vector& x) {
	// HACK: gcc doesn't recognize the existence of x.size() (?!)
	PyObject* ls = PyList_New(x.n);
	PyObject* pItem;
	if(ls == NULL) {
		goto fail;
	}

	for(Py_ssize_t i = 0; i < PySequence_Size(ls); i++) {
		pItem = PyFloat_FromDouble(x[(int)i]);
		if(pItem == NULL)
			goto fail;
		PyList_SetItem(ls, i, pItem);
	}

	return ls;

	fail:
		Py_XDECREF(ls);
		return NULL;
}

PyObject* findRoots(PyObject* startVals, int iter) {
	if(root == NULL) {
	  throw PyException("rootfind.findRoots: no vector field set");
	  return NULL;
	}

	if(!PySequence_Check(startVals)) {
	  throw PyException("rootfind.findRoots: starting value is not a sequence");
	  return NULL;
	}
	if(PySequence_Size(startVals) != theFn->NumVariables()) {
	  throw PyException("rootfind.findRoots: starting value has incorrect size");
	}

	root->x.resize(theFn->NumVariables());
	for(Py_ssize_t i = 0; i < PySequence_Size(startVals); i++) {
		(root->x)[(int)i] = PyFloat_AsDouble(PySequence_GetItem(startVals, i));
	}

	ConvergenceResult conv = root->Solve(iter);

	//HACK
	PyObject* tuple,*ls,*code,*usedIters;
	ls = PyListFromVector(root->x);
	if(ls == NULL) {
	  throw PyException("rootfind.findRoots: unable to allocate return value");
	}
	tuple = PyTuple_New(3);
	if(tuple == NULL) {
	  Py_XDECREF(ls);
	  throw PyException("rootfind.findRoots: unable to allocate return value");
	  return NULL;
	}
	switch(conv) {
		case Math::ConvergenceX:
			code = PyInt_FromLong(0);
			break;
		case Math::ConvergenceF:
			code = PyInt_FromLong(1);
			break;
		case Math::Divergence:
			code = PyInt_FromLong(2);
			break;
		case Math::LocalMinimum:
			code = PyInt_FromLong(3);
			break;
		case Math::MaxItersReached:
			code = PyInt_FromLong(4);
			break;
		case Math::ConvergenceError:
		default:
			code = PyInt_FromLong(5);
			break;
	}
	usedIters = PyInt_FromLong(iter);
	PyTuple_SetItem(tuple, 0, code);
	PyTuple_SetItem(tuple, 1, ls);
	PyTuple_SetItem(tuple, 2, usedIters);
	return tuple;
}

PyObject* findRootsBounded(PyObject* startVals, PyObject* boundVals, int iter) {
	if(root == NULL) {
	  throw PyException("rootfind.findRootsBounded: no vector field set");
	  return NULL;
	}

	if(!PySequence_Check(boundVals)) {
	  throw PyException("rootfind.findRootsBounded: bounds are not a sequence");
	  return NULL;
	}
	if(PySequence_Size(boundVals) != theFn->NumVariables()) {
	  throw PyException("rootfind.findRootsBounded: bounds have incorrect size");
	  return NULL;
	}

	root->bmin.resize(theFn->NumVariables());
	root->bmax.resize(theFn->NumVariables());
	for(int i = 0; i < root->bmin.n; i++) {
	  PyObject* tup = PySequence_GetItem(boundVals, (Py_ssize_t)i);
	  if(!PySequence_Check(tup) || PySequence_Size(tup) != (Py_ssize_t)2) {
	    throw PyException("rootfind.findRootsBounded: bound element is not a pair");
	    return NULL;
	  }
	  root->bmin[i] = PyFloat_AsDouble(PySequence_GetItem(tup, 0));
	  root->bmax[i] = PyFloat_AsDouble(PySequence_GetItem(tup, 1));
	}
	//cout<<"Parsed bounds:"<<endl;
	//cout<<root->bmin<<endl;
	//cout<<root->bmax<<endl;
	//getchar();
	return findRoots(startVals, iter);
}

void destroy() {
	if(theFn != NULL) {
		delete theFn;
	}
	if(root != NULL) {
		delete root;
	}
	theFn = NULL;
	root = NULL;
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.tabmodel.document;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.util.SparseArray;

import org.chromium.base.ActivityState;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.ApplicationStatus.ActivityStateListener;
import org.chromium.base.ThreadUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.Tab;
import org.chromium.chrome.browser.UrlConstants;
import org.chromium.chrome.browser.document.DocumentUtils;
import org.chromium.chrome.browser.document.PendingDocumentData;
import org.chromium.chrome.browser.tab.TabIdManager;
import org.chromium.chrome.browser.tabmodel.OffTheRecordTabModel.OffTheRecordTabModelDelegate;
import org.chromium.chrome.browser.tabmodel.TabCreatorManager;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.TabModelSelectorBase;
import org.chromium.content_public.browser.LoadUrlParams;

/**
 * Stores DocumentTabModels for Chrome Activities running in Document-mode.
 * Also manages the transfer of data from one DocumentActivity to another, e.g. WebContents that are
 * created by one Activity but need to be loaded in another Tab.
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class DocumentTabModelSelector extends TabModelSelectorBase
        implements ActivityStateListener, TabCreatorManager {
    public static final String PREF_PACKAGE = "com.google.android.apps.chrome.document";
    public static final String PREF_IS_INCOGNITO_SELECTED = "is_incognito_selected";

    /**
     * Overrides Delegates used by the DocumentTabModels.
     */
    private static final Object ACTIVITY_DELEGATE_FOR_TESTS_LOCK = new Object();
    private static final Object STORAGE_DELEGATE_FOR_TESTS_LOCK = new Object();
    private static ActivityDelegate sActivityDelegateForTests;
    private static StorageDelegate sStorageDelegateForTests;

    /**
     * ID of the Tab to prioritize when initializing the TabState.
     */
    private static int sPrioritizedTabId = Tab.INVALID_TAB_ID;

    /**
     * Interacts with DocumentActivities.
     */
    private final ActivityDelegate mActivityDelegate;

    /**
     * Interacts with the file system.
     */
    private final StorageDelegate mStorageDelegate;

    /**
     * Creates new Tabs.
     */
    private final TabDelegate mRegularTabDelegate;
    private final TabDelegate mIncognitoTabDelegate;

    /**
     * TabModel that keeps track of regular tabs. This is always not null.
     */
    private final DocumentTabModel mRegularTabModel;

    /**
     * TabModel that keeps track of incognito tabs. This may be null if no incognito tabs exist.
     */
    private final OffTheRecordDocumentTabModel mIncognitoTabModel;

    /**
     * A map of tab IDs to PendingDocumentData to be consumed by opening activities.
     */
    private final SparseArray<PendingDocumentData> mPendingDocumentData =
            new SparseArray<PendingDocumentData>();

    /**
     * If the TabModels haven't been initialized yet, prioritize the correct one to load the Tab.
     * @param prioritizedTabId ID of the tab to prioritize.
     */
    public static void setPrioritizedTabId(int prioritizedTabId) {
        sPrioritizedTabId = prioritizedTabId;
    }

    public DocumentTabModelSelector(ActivityDelegate activityDelegate,
            StorageDelegate storageDelegate, TabDelegate regularTabDelegate,
            TabDelegate incognitoTabDelegate) {
        mActivityDelegate =
                sActivityDelegateForTests == null ? activityDelegate : sActivityDelegateForTests;
        mStorageDelegate =
                sStorageDelegateForTests == null ? storageDelegate : sStorageDelegateForTests;
        mRegularTabDelegate = regularTabDelegate;
        mIncognitoTabDelegate = incognitoTabDelegate;

        final Context context = ApplicationStatus.getApplicationContext();
        mRegularTabModel = new DocumentTabModelImpl(
                mActivityDelegate, mStorageDelegate, this, false, sPrioritizedTabId, context);
        mIncognitoTabModel = new OffTheRecordDocumentTabModel(new OffTheRecordTabModelDelegate() {
            @Override
            public TabModel createTabModel() {
                DocumentTabModel incognitoModel = new DocumentTabModelImpl(mActivityDelegate,
                        mStorageDelegate, DocumentTabModelSelector.this, true, sPrioritizedTabId,
                        context);
                if (mRegularTabModel.isNativeInitialized()) {
                    incognitoModel.initializeNative();
                }
                return incognitoModel;
            }

            @Override
            public boolean doOffTheRecordTabsExist() {
                // TODO(dfalcantara): Devices in document mode do not trigger the TabWindowManager.
                //                    Revisit this when we have a Samsung L multi-instance device.
                return mIncognitoTabModel.getCount() > 0;
            }
        }, mActivityDelegate);
        initializeTabIdCounter();

        // Re-select the previously selected TabModel.
        SharedPreferences prefs = context.getSharedPreferences(PREF_PACKAGE, Context.MODE_PRIVATE);
        boolean startIncognito = prefs.getBoolean(PREF_IS_INCOGNITO_SELECTED, false);
        initialize(startIncognito, mRegularTabModel, mIncognitoTabModel);

        ApplicationStatus.registerStateListenerForAllActivities(this);
    }

    @Override
    public TabDelegate getTabCreator(boolean incognito) {
        return incognito ? mIncognitoTabDelegate : mRegularTabDelegate;
    }

    private void initializeTabIdCounter() {
        int biggestId = getLargestTaskIdFromRecents();
        biggestId = getMaxTabId(mRegularTabModel, biggestId);
        biggestId = getMaxTabId(mIncognitoTabModel, biggestId);
        TabIdManager.getInstance().incrementIdCounterTo(biggestId + 1);
    }

    private int getMaxTabId(DocumentTabModel tabModel, int min) {
        int biggestId = min;
        int numTabs = tabModel.getCount();
        for (int tabIndex = 0; tabIndex < numTabs; tabIndex++) {
            biggestId = Math.max(biggestId, tabModel.getTabAt(tabIndex).getId());
        }
        return biggestId;
    }

    private int getLargestTaskIdFromRecents() {
        int biggestId = Tab.INVALID_TAB_ID;
        Context context = ApplicationStatus.getApplicationContext();
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.AppTask task : activityManager.getAppTasks()) {
            RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task);
            if (info == null) continue;
            biggestId = Math.max(biggestId, info.persistentId);
        }
        return biggestId;
    }

    @Override
    public void onActivityStateChange(Activity activity, int newState) {
        if (!mActivityDelegate.isDocumentActivity(activity)) return;

        // Tabs swiped away when their Activity is dead don't trigger destruction notifications.
        if (newState == ActivityState.STARTED || newState == ActivityState.DESTROYED) {
            mRegularTabModel.updateRecentlyClosed();
            mIncognitoTabModel.updateRecentlyClosed();
        }
    }

    @Override
    public Tab openNewTab(LoadUrlParams loadUrlParams, TabLaunchType type, Tab parent,
            boolean incognito) {
        TabDelegate delegate = getTabCreator(incognito);
        delegate.createNewTab(loadUrlParams, type, parent);
        return null;
    }

    @Override
    public void selectModel(boolean incognito) {
        super.selectModel(incognito);

        Context context = ApplicationStatus.getApplicationContext();
        SharedPreferences prefs = context.getSharedPreferences(PREF_PACKAGE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(PREF_IS_INCOGNITO_SELECTED, incognito);
        editor.apply();
    }

    @Override
    public DocumentTabModel getModel(boolean incognito) {
        return (DocumentTabModel) super.getModel(incognito);
    }

    @Override
    public DocumentTabModel getModelForTabId(int id) {
        return (DocumentTabModel) super.getModelForTabId(id);
    }

    /**
     * Alerts the TabModels that the native library is ready.
     */
    public void onNativeLibraryReady() {
        mRegularTabModel.initializeNative();
        mIncognitoTabModel.initializeNative();
    }

    /**
     * Generates an ID for a new Tab.  Makes sure the DocumentTabModels are loaded beforehand to
     * ensure that the ID counter is properly initialized.
     * @return ID to use for the new Tab.
     */
    public int generateValidTabId() {
        return TabIdManager.getInstance().generateValidId(Tab.INVALID_TAB_ID);
    }

    /**
     * Stores PendingUrlParams to be used when the tab with the given ID is launched via intent.
     * @param tabId The ID of the tab that will be launched via intent.
     * @param params The PendingUrlParams to use when loading the URL in the tab.
     */
    public void addPendingDocumentData(int tabId, PendingDocumentData params) {
        ThreadUtils.assertOnUiThread();
        mPendingDocumentData.put(tabId, params);
    }

    /**
     * @return Retrieves and removes PendingDocumentData for a particular tab id.
     */
    public PendingDocumentData removePendingDocumentData(int tabId) {
        ThreadUtils.assertOnUiThread();
        PendingDocumentData data = mPendingDocumentData.get(tabId);
        mPendingDocumentData.remove(tabId);
        return data;
    }

    /**
     * Creates a data string which stores the base information we need to relaunch a task: a unique
     * identifier and the URL to load.
     * @param id ID of the tab in the DocumentActivity.
     * @param initialUrl URL to load in the DocumentActivity.
     * @return a Uri that has the identifier and the URL mashed together.
     */
    public static Uri createDocumentDataString(int id, String initialUrl) {
        return new Uri.Builder().scheme(UrlConstants.DOCUMENT_SCHEME).authority(String.valueOf(id))
                .query(initialUrl).build();
    }

    /**
     * Overrides the regular ActivityDelegate in the constructor.  MUST be called before the
     * DocumentTabModelSelector instance is created to take effect.
     */
    @VisibleForTesting
    public static void setActivityDelegateForTests(ActivityDelegate delegate) {
        synchronized (ACTIVITY_DELEGATE_FOR_TESTS_LOCK) {
            sActivityDelegateForTests = delegate;
        }
    }

    /**
     * Overrides the regular StorageDelegate in the constructor.  MUST be called before the
     * DocumentTabModelSelector instance is created to take effect.
     */
    @VisibleForTesting
    public static void setStorageDelegateForTests(StorageDelegate delegate) {
        synchronized (STORAGE_DELEGATE_FOR_TESTS_LOCK) {
            sStorageDelegateForTests = delegate;
        }
    }
}


text: If you want to add an example file in the language of your choice feel free to send a pull request.


text:
type: tutorial
layout: tutorial
title:  "Working with Build Tools"
description:
authors: Hadi Hariri
showAuthorInfo: true
---
In addition to the command line compiler and IntelliJ IDEA, you can also use Ant, Maven, Gradle and Griffon to build Kotlin projects.

For information on how to do use each of these tutorials refer to the corresponding section:

- [Ant](/docs/reference/using-ant.html)
- [Maven](/docs/reference/using-maven.html)
- [Gradle](/docs/reference/using-gradle.html)
- [Griffon (external support)](https://github.com/griffon/griffon-kotlin-plugin)


text:
package de.peeeq.wurstscript.translation.imtranslation;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import de.peeeq.wurstscript.jassIm.*;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import static de.peeeq.wurstscript.translation.imtranslation.FunctionFlagEnum.IS_VARARG;

/**
 * Takes a program and eliminates vararg functions, replacing them with
 * generated functions with the appropriate amount of parameters.
 */
public class VarargEliminator {

    private ImProg prog;
    // original + number of args --> new function
    private Table<ImFunction, Integer, ImFunction> varargFuncs = HashBasedTable.create();

    public VarargEliminator(ImProg prog) {
        this.prog = prog;
    }

    public void run() {
        // create new vararg functions
        for (ImFunctionCall c : collectVarargCalls()) {
            if (c.getFunc().hasFlag(IS_VARARG)) {
                generateVarargFunc(c.getFunc(), c.getArguments().size());
            }
        }

        // remove original vararg functions:
        prog.getFunctions().removeIf(f -> f.hasFlag(IS_VARARG));

        // rewrite calls to use new functions:
        // (need to collect vararg calls again, because first phase can create copies of calls)
        for (ImFunctionCall call : collectVarargCalls()) {
            redirectCall(call, varargFuncs.get(call.getFunc(), call.getArguments().size()));
        }
    }

    @NotNull
    private Collection<ImFunctionCall> collectVarargCalls() {
        // Collect all calls to vararg functions
        final Collection<ImFunctionCall> calls = new ArrayList<>();
        prog.accept(new ImProg.DefaultVisitor() {

            @Override
            public void visit(ImFunctionCall c) {
                super.visit(c);
                if (c.getFunc().hasFlag(IS_VARARG)) {
                    calls.add(c);
                }
            }

        });
        return calls;
    }

    /**
     * Generates a function based on the vararg function with the appropriate amount of parameters
     * for the function call.
     */
    private void generateVarargFunc(ImFunction func, int numberOfParams) {
        if (varargFuncs.contains(func, numberOfParams)) {
            // already generated
            return;
        }

        // how many vararg-parameters should we generate?
        // ==> number of parameters in call minus non-vararg parameters in the definition
        int argumentSize = 1 + numberOfParams - func.getParameters().size();

        // Create new function
        ImFunction newFunc = ReferenceRewritingCopy.copy(func);
        newFunc.setName(func.getName() + "_" + argumentSize);
        // replace vararg with special parameters:
        ImVar varargParam = newFunc.getParameters().remove(newFunc.getParameters().size() - 1);
        ImType type = varargParam.getType();
        List<ImVar> newParams = new ArrayList<>();
        for (int i = 0; i < argumentSize; i++) {
            ImVar param = JassIm.ImVar(func.getTrace(), type, varargParam.getName() + "_" + i, false);
            newParams.add(param);
            newFunc.getParameters().add(param);
        }

        // Visit all vararg loop statements inside the new function
        newFunc.getBody().accept(new Element.DefaultVisitor() {
            @Override
            public void visit(ImVarargLoop imLoop) {
                super.visit(imLoop);
                unrollVarargLoop(imLoop, newParams);
            }

        });

        // Visit all remaining uses of the vararg-parameter
        // this must be calls to other vararg functions, so unfold the parameters
        List<ImVarAccess> varargParamUses = collectUsesOfVar(newFunc, varargParam);

        for (ImVarAccess va : varargParamUses) {
            ImExprs params = (ImExprs) va.getParent();
            ImFunctionCall call = (ImFunctionCall) params.getParent();

            params.remove(va);
            params.addAll(newParams.stream().map(JassIm::ImVarAccess).collect(Collectors.toList()));

            // generate function for this new call
            generateVarargFunc(call.getFunc(), call.getArguments().size());
        }

        // Remove vararg flag
        newFunc.setFlags(newFunc.getFlags().stream().filter(flag -> flag != IS_VARARG).collect(Collectors.toList()));
        // Add new function to prog
        prog.getFunctions().add(newFunc);
        varargFuncs.put(func, numberOfParams, newFunc);
    }

    @NotNull
    private List<ImVarAccess> collectUsesOfVar(ImFunction newFunc, ImVar varargParam) {
        List<ImVarAccess> varargParamUses = new ArrayList<>();
        newFunc.getBody().accept(new Element.DefaultVisitor() {

            @Override
            public void visit(ImVarAccess va) {
                super.visit(va);
                if (va.getVar() == varargParam) {
                    varargParamUses.add(va);
                }
            }
        });
        return varargParamUses;
    }

    private void redirectCall(ImFunctionCall call, ImFunction newFunc) {
        // Redirect call to new function
        ImFunctionCall newCall = JassIm.ImFunctionCall(call.getTrace(), newFunc, JassIm.ImTypeArguments(), JassIm.ImExprs(call.getArguments().removeAll()), call.getTuplesEliminated(), call.getCallType());
        call.replaceBy(newCall);
    }

    private void unrollVarargLoop(ImVarargLoop imLoop, List<ImVar> newParams) {
        ImStatementExpr stmtExpr = ImHelper.statementExprVoid(JassIm.ImStmts());

        for (int i = 0; i < newParams.size(); i++) {
            ImStmts bodyCopy = imLoop.getBody().copy();
            int finalI = i;
            bodyCopy.accept(new Element.DefaultVisitor() {
                @Override
                public void visit(ImVarAccess access) {
                    super.visit(access);
                    if (access.getVar() == imLoop.getLoopVar()) {
                        access.setVar(newParams.get(finalI));
                    }
                }

            });
            stmtExpr.getStatements().addAll(bodyCopy.removeAll());
        }

        imLoop.replaceBy(stmtExpr);
    }

}


text:
require 'spec_helper'
require 'set'

describe Arrangement  do

  it "requires a name to be valid" do
    subject.should_not be_valid
    subject.name = "Test"
    subject.should be_valid
  end

  describe "total_expenses" do
    it "should return the sum the total_expenses of each participant" do
      participants = [double(:total_expenses => 250),
                      double(:total_expenses => 320)]
      subject.stub(:participants => participants)
      subject.total_expenses.should == 570
    end

    it "should return zero when no expenses are present" do
      subject.stub(:participants => [])
      subject.total_expenses.should == 0
    end
  end

  describe "average_expenses" do
    it "should return the average expenses over all the participants" do
      participants = [double(:total_expenses => 251),
                      double(:total_expenses => 320)]
      subject.stub(:participants => participants)
      subject.average_expenses.should == 285.5
    end

    it "should return zero when no expenses are present" do
      subject.stub(:participants => [])
      subject.average_expenses.should == 0
    end
  end

  describe "debitors" do
    let(:participants) do
      participants = [double(:name => "Participant 1", :in_debt? => true,  :debt => 123),
                      double(:name => "Participant 2", :in_debt? => false, :debt => 0),
                      double(:name => "Participant 3", :in_debt? => true,  :debt => 23)]
    end

    it "is empty when there are no participants" do
      subject.stub(:participants => [])
      subject.debitors.should be_empty
    end

    it "it contains the participants with debt" do
      subject.stub(:participants => participants)
      expected = ["Participant 1", "Participant 3"]
      subject.debitors.map(&:name).should == expected
    end
  end

  describe "creditors" do
    let(:participants) do
      participants = [double(:name => "Participant 1", :has_claim? => true,  :claim => 123),
                      double(:name => "Participant 2", :has_claim? => false, :claim => 0),
                      double(:name => "Participant 3", :has_claim? => true,  :claim => 23)]
    end

    it "is empty when there are no participants" do
      subject.stub(:participants => [])
      subject.debitors.should be_empty
    end

    it "it contains the participants with claim" do
      subject.stub(:participants => participants)
      expected = ["Participant 1", "Participant 3"]
      subject.creditors.map(&:name).should == expected
    end
  end

  describe "settle_debt" do
    let(:ethan) {double(:name => "Ethan", :in_debt? => false, :has_claim? => true,  :claim => 40)}
    let(:michael) {double(:name => "Michael", :in_debt? => false, :has_claim? => true,  :claim => 100)}
    let(:john) {double(:name => "John", :has_claim? => false, :in_debt? => true, :debt => 60)}
    let(:piet) {double(:name => "Piet", :has_claim? => false, :in_debt? => true, :debt => 40)}
    let(:daniel) {double(:name => "Daniel", :has_claim? => false, :in_debt? => true,  :debt => 40)}

    let(:jane) {double(:name => "Jane", :in_debt? => true, :has_claim? => false,  :debt => 33.33)}
    let(:charles) {double(:name => "Charles", :in_debt? => true, :has_claim? => false,  :debt => 33.33)}
    let(:julia) {double(:name => "Julia", :in_debt? => false, :has_claim? => true,  :claim => 66.67)}

    it "should return no transfers if there are no participants" do
      subject.stub(:participants => [])
      subject.settle_debt.empty?.should be_true
    end

    it "all debt should be settled by returned transfers" do
      subject.stub(:participants => [michael, ethan, john, piet, daniel])
      transfers = subject.settle_debt

      transfers.amount.should == 140

      transfers.from(john).amount.should == 60
      transfers.from(daniel).amount.should == 40
      transfers.from(piet).amount.should == 40
      transfers.to(ethan).amount.should == 40
      transfers.to(michael).amount.should == 100
    end

    it "can floats correctly" do
      subject.stub(:participants => [julia, jane, charles])
      transfers = subject.settle_debt

      transfers.amount.should == 66.67
      transfers.from(jane).amount.should == 33.34
      transfers.from(charles).amount.should == 33.33
      transfers.to(julia).amount.should == 66.67
    end

    it "throws an error if the claim is bigger than the debt" do
      pending
    end

    it "throws an error if the debt is bigger than the claim" do
      pending
    end
  end
end


text:
package org.cobbzilla.util.mq.kestrel;

import org.cobbzilla.util.mq.MqProducer;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class KestrelProducer implements MqProducer {

    private static final Logger LOG = LoggerFactory.getLogger(KestrelProducer.class);

    private KestrelClient client;
    private String queueName;

    public KestrelProducer(KestrelClient client, String queueName) {
        this.client = client;
        this.queueName = queueName;
    }

    @Override
    public void send(Object message) throws IOException, InterruptedException {
        boolean sent = false;
        int i = 0;
        while (!sent) {
            i++;
            final String msgString = message.toString();
            final int len = msgString.length();
            final String msg = len > 100 ? msgString.substring(0, 100)+"..." : msgString;
            try {
                LOG.info("send: sending to " + queueName + " (try #" + i + "): " + msg);
                client.set(queueName, message);
                LOG.info("send: send succeeded to "+queueName+" (on try #"+i+")");
                sent = true;

            } catch (InterruptedException e) {
                LOG.warn("send: interrupted while trying to send message ("+ msg +") to queue "+queueName);
                throw e;

            } catch (TimeoutException e) {
                LOG.warn("send: timed out sending message ("+ msg +") to queue "+queueName+", retrying");
                Thread.yield();
                Thread.sleep(50);

            } catch (MemcachedException e) {
                LOG.warn("send: error sending message ("+ msg +") to queue "+queueName+", retrying: "+e, e);
                Thread.yield();
                Thread.sleep(50);
            }
        }
    }

}


text:
spring-data-rest-acl
====================

## Spring Security ACL with Spring Data REST

This is a sample project to illustrate how to use ACL-based Authorization for entities exposed by Spring Data REST.
This is referred by:
http://stackoverflow.com/questions/26546072/using-spring-security-acl-with-spring-data-rest

#### Steps to deploy and run Bookstore sample:

Note that "conf" directory contains config files that needs to be placed at /etc/bookstore/.
	- bookstore.properties for configuring database, hibernate, connection-pooling
	- logback.xml for setting log levels. Set log file location - /var/log/bookstore/bookstore.log

1. create db user book with password book:
	createuser --createdb --no-createrole -P book

2. create db:
	createdb bookstore -O book -E 'UTF8'

3. Run Spring Security ACL schema -  bookstore/src/scripts/sql/createAclSchemaPostgres.sql

4. Do a maven build and copy bookstore.war under tomcat/webapps.

5. Run tomcat

6. Run bookstore config sql - bookstore/src/scripts/sql/bookstoreConfig.sql

7. Go over the curl samples in bookstore/src/test/curl/bookstorecurl.txt to see how it works.


text:
package com.glaf.core.service.impl;

import com.glaf.core.domain.WorkCalendar;
import com.glaf.core.id.IdGenerator;
import com.glaf.core.mapper.WorkCalendarMapper;
import com.glaf.core.query.WorkCalendarQuery;
import com.glaf.core.service.WorkCalendarService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service("workCalendarService")
@Transactional(readOnly = true)
public class WorkCalendarServiceImpl implements WorkCalendarService {
	private final static Log logger = LogFactory.getLog(WorkCalendarServiceImpl.class);

	private IdGenerator idGenerator;

	private SqlSessionTemplate sqlSessionTemplate;

	private WorkCalendarMapper workCalendarMapper;

	private static final List<Integer> workDateList = new java.util.ArrayList<Integer>();

	public boolean checkWorkDate(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DAY_OF_MONTH);
		logger.info("year:" + year + ", month:" + month + ", day:" + day);
		WorkCalendar bean = find(year, month + 1, day);
		return bean == null;
	}

	public int count(WorkCalendarQuery query) {
		return workCalendarMapper.getWorkCalendarCount(query);
	}

	@Transactional
	public boolean create(WorkCalendar bean) {
		StringBuilder buffer = new StringBuilder();
		buffer.append(bean.getFreeYear());
		if (bean.getFreeMonth() <= 9) {
			buffer.append("0");
		}
		buffer.append(bean.getFreeMonth());
		if (bean.getFreeDay() <= 9) {
			buffer.append("0");
		}
		buffer.append(bean.getFreeDay());
		bean.setId(Long.parseLong(buffer.toString()));
		this.workCalendarMapper.insertWorkCalendar(bean);
		return false;
	}

	@Transactional
	public boolean delete(long id) {
		this.deleteById(id);
		return true;
	}

	@Transactional
	public boolean delete(WorkCalendar bean) {
		this.deleteById(bean.getId());
		return true;
	}

	@Transactional
	public void deleteById(Long id) {
		if (id != null) {
			workCalendarMapper.deleteWorkCalendarById(id);
		}
	}

	@Transactional
	public void deleteByIds(List<Long> rowIds) {
		if (rowIds != null && !rowIds.isEmpty()) {
			WorkCalendarQuery query = new WorkCalendarQuery();
			query.rowIds(rowIds);
			workCalendarMapper.deleteWorkCalendars(query);
		}
	}

	public WorkCalendar find(int freeYear, int freeMonth, int freeDay) {
		WorkCalendarQuery query = new WorkCalendarQuery();
		query.freeYear(freeYear);
		query.freeMonth(freeMonth);
		query.freeDay(freeDay);
		List<WorkCalendar> list = this.list(query);
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}

	public WorkCalendar findById(long id) {
		return this.getWorkCalendar(id);
	}

	private WorkCalendar getWorkCalendar(Long id) {
		if (id == null) {
			return null;
		}
		return workCalendarMapper.getWorkCalendarById(id);
	}

	public int getWorkCalendarCountByQueryCriteria(WorkCalendarQuery query) {
		return workCalendarMapper.getWorkCalendarCount(query);
	}

	public List<WorkCalendar> getWorkCalendarsByQueryCriteria(int start, int pageSize, WorkCalendarQuery query) {
		RowBounds rowBounds = new RowBounds(start, pageSize);
		return sqlSessionTemplate.selectList("getWorkCalendars", query, rowBounds);
	}

	public Date getWorkDate(Date startDate, int interval) {
		if (startDate == null) {
			return null;
		}
		Date endDate;

		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);

		List<Date> noneWorkDays = new java.util.ArrayList<Date>();
		if (workDateList.size() == 0)
			initWorkDate();
		if (!workDateList.isEmpty()) {
			Iterator<?> iter = workDateList.iterator();
			cal.set(Calendar.YEAR, year);
			cal.set(Calendar.MONTH, month);
			cal.set(Calendar.DAY_OF_MONTH, ((Integer) iter.next()).intValue());
			noneWorkDays.add(cal.getTime());
		}

		endDate = getWorkDate(startDate, interval, noneWorkDays);
		return endDate;
	}

	public Date getWorkDate(Date startDate, int interval, List<Date> noneWorkDays) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);

		// 按照间隔天数,循环
		for (int i = 1; i <= interval; i++) {
			cal.add(Calendar.DAY_OF_MONTH, 1);
			Date nextDate = cal.getTime();
			if (noneWorkDays.contains(nextDate)) {// 下一天是非工作日,则往后移
				return getWorkDate(nextDate, interval + 1 - i, noneWorkDays);
			}
		}
		return cal.getTime();
	}

	public Date getWorkDate2(Date startDate, int interval) {
		if (startDate == null) {
			return null;
		}
		Date endDate;

		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);

		List<Date> noneWorkDays = new java.util.ArrayList<Date>();

		// 取连续2个月的非工作日
		List<Integer> list = getWorkDateList(year, month + 1);
		if (list != null) {
			Iterator<Integer> iter = list.iterator();
			while (iter.hasNext()) {
				cal.set(Calendar.YEAR, year);
				cal.set(Calendar.MONTH, month);
				cal.set(Calendar.DAY_OF_MONTH, iter.next().intValue());
				noneWorkDays.add(cal.getTime());
			}
		}
		list = getWorkDateList(year, month + 2);
		if (list != null) {
			Iterator<Integer> iter = list.iterator();
			while (iter.hasNext()) {
				cal.set(Calendar.YEAR, year);
				cal.set(Calendar.MONTH, month + 1);
				cal.set(Calendar.DAY_OF_MONTH, iter.next().intValue());
				noneWorkDays.add(cal.getTime());
			}
		}

		endDate = getWorkDate(startDate, interval, noneWorkDays);
		return endDate;
	}

	public List<Integer> getWorkDateList(int freeYear, int freeMonth) {
		WorkCalendarQuery query = new WorkCalendarQuery();
		query.freeYear(freeYear);
		query.freeMonth(freeMonth);

		List<WorkCalendar> list = this.list(query);
		List<Integer> days = new java.util.ArrayList<Integer>();
		if (list != null && !list.isEmpty()) {
			for (WorkCalendar cal : list) {
				days.add(cal.getFreeDay());
			}
		}

		return days;
	}

	private void initWorkDate() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int year = cal.get(Calendar.YEAR);

		workDateList.addAll(getWorkDateList(year - 1, 12));
		for (int i = 1; i <= 12; i++) {
			workDateList.addAll(getWorkDateList(year, i));
		}
		workDateList.addAll(getWorkDateList(year + 1, 1));
	}

	private List<WorkCalendar> list(WorkCalendarQuery query) {
		return workCalendarMapper.getWorkCalendars(query);
	}

	@Transactional
	public void save(WorkCalendar workCalendar) {
		if (workCalendar.getId() == 0) {
			workCalendar.setId(idGenerator.nextId());
			// workCalendar.setCreateDate(new Date());
			workCalendarMapper.insertWorkCalendar(workCalendar);
		} else {
			workCalendarMapper.updateWorkCalendar(workCalendar);
		}
	}

	@javax.annotation.Resource
	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	@javax.annotation.Resource
	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	@javax.annotation.Resource
	public void setWorkCalendarMapper(WorkCalendarMapper workCalendarMapper) {
		this.workCalendarMapper = workCalendarMapper;
	}

	@Transactional
	public boolean update(WorkCalendar bean) {
		workCalendarMapper.updateWorkCalendar(bean);
		return true;
	}

}


text:
Package.describe({
  name: 'gsma-4g',
  version: '0.0.1',
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.3');

  api.use(['widget', 'underscore', 'country-info', 'momentjs:moment', 'gsma-data']);
  api.use(['templating', 'epoch'], 'client');

  api.addFiles('gsma.js');
  api.addFiles([
    'client/info.html',
    'client/settings.html',
    'client/settings.js',
    'client/widget.html',
    'client/widget.js',
    'client/widget.css'
  ], 'client');

  api.export('GSMA4G');
});


text:
package credentials

import "docker.io/go-docker/api/types"

// Store is the interface that any credentials store must implement.
type Store interface {
	// Erase removes credentials from the store for a given server.
	Erase(serverAddress string) error
	// Get retrieves credentials from the store for a given server.
	Get(serverAddress string) (types.AuthConfig, error)
	// GetAll retrieves all the credentials from the store.
	GetAll() (map[string]types.AuthConfig, error)
	// Store saves credentials in the store.
	Store(authConfig types.AuthConfig) error
}


text:
<?php

namespace ExtendsFramework\Command\Handler\Exception;

use Exception;
use ExtendsFramework\Command\Message\CommandMessage;

class MethodNotFound extends Exception
{
    /**
     * @param CommandMessage $message
     * @return static
     */
    public static function forMessage(CommandMessage $message)
    {
        return new static(sprintf('No handle method for command "%s".', $message->type()->name()));
    }
}


text:
module MintOrder
  class Order < ActiveRecord::Base
    attr_accessible :customer_id, :merchant_id, :status, :total
    has_many :order_items
    has_many :order_notes
    before_create :set_defaults

    validates_presence_of :customer_id
    validates_presence_of :merchant_id

    STATES = [
    	NEW = "New",
    	INPROGRESS = "InPorgress",
    	CANCELED = 'Cancelled',
    	COMPLETED = 'Completed'
    ]

    def set_defaults
    	self.status = NEW
    	self.total = order_items.collect(&:amount).inject(:+) || 0
    end
  end
end


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use App\CourseSelection\Models\Professor;

class ProfessorController extends Controller
{
    public function __construct () {
        parent::__construct();
        $this->general->identity = "professor";
        $this->general->title = "professor";
        $this->general->view_path .= "/professor";
    }

    public function index(Request $request) {
        $this->general->info = User::find(Auth::user()->id);

        return view('professor/index', ['general' => $this->general]);
    }
}


text:
    <input type="text" name="username" class="form-control user-create-name" placeholder="Enter Username">

    <input type="text" name="email" class="form-control user-create-email" placeholder="Enter Email">

    <input type="password" name="password" class="form-control user-create-passwd" placeholder="Enter Password">

    <input type="password" name="passrep" class="form-control user-create-passwd-repeat" placeholder="Re-Enter Password">

    <button class="btn btn-info user-create-submit">OK</button>


text:
Javascript adaptor for api.Formagg.io

Based on the js factory model using in Backbone.js.


text:
set -ev

pip install -r requirements_dev.txt
pip install tensorflow==1.6.0
pip install -e .

pip install pipdeptree
pipdeptree

mkdir data

echo "\nDownloading and processing emnist data..."
time python scripts/download.py emnist data -q
rm data/gzip.zip

echo "\nDownloading and processing omniglot data..."
time python scripts/download.py omniglot data -q

echo "\nDownloading and installing gnu-parallel..."
wget https://mirror.csclub.uwaterloo.ca/gnu/parallel/parallel-20170622.tar.bz2
tar -xjvf parallel-20170622.tar.bz2
cd parallel-20170622
./configure --prefix="$TRAVIS_BUILD_DIR" && make && make install
cd ..
rm -rf parallel-20170622.tar.bz2 parallel-20170622


text:
/**
*	@file xlinq_reverse.h
*	Reversing collection elements order.
*	@author TrolleY
*/
#ifndef XLINQ_REVERSE_H_
#define XLINQ_REVERSE_H_

#include <memory>
#include <list>
#include "xlinq_base.h"
#include "xlinq_from.h"

namespace xlinq
{
	/*@cond XLINQ_INTERNAL*/
	namespace internal
	{
		template<typename TElem>
		class _ReverseBidirectionalEnumerator : public IBidirectionalEnumerator<TElem>
		{
		private:
			std::shared_ptr<IBidirectionalEnumerator<TElem>> _source;

		public:
			_ReverseBidirectionalEnumerator(std::shared_ptr<IBidirectionalEnumerator<TElem>> source)
				: _source(source)
			{
			}

			bool next() override
			{
				return _source->back();
			}

			bool back() override
			{
				return _source->next();
			}

			TElem current() override
			{
				return _source->current();
			}

			bool equals(std::shared_ptr<IEnumerator<TElem>> other) const override
			{
				auto pother = std::dynamic_pointer_cast<_ReverseBidirectionalEnumerator<TElem>>(other);
				if (!pother)
					return false;
				return _source->equals(pother->_source);
			}

			std::shared_ptr<IEnumerator<TElem>> clone() const override
			{
				return std::shared_ptr<IEnumerator<TElem>>(new _ReverseBidirectionalEnumerator<TElem>(std::dynamic_pointer_cast<IBidirectionalEnumerator<TElem>>(_source->clone())));
			}
		};

		template<typename TElem>
		class _ReverseBidirectionalEnumerable : public IBidirectionalEnumerable<TElem>
		{
		private:
			std::shared_ptr<IBidirectionalEnumerable<TElem>> _source;
		public:
			_ReverseBidirectionalEnumerable(std::shared_ptr<IBidirectionalEnumerable<TElem>> source)
				: _source(source)
			{
			}

			std::shared_ptr<IEnumerator<TElem>> createEnumerator() override
			{
				return std::shared_ptr<IEnumerator<TElem>>(new _ReverseBidirectionalEnumerator<TElem>(_source->getEndEnumerator()));
			}

			std::shared_ptr<IBidirectionalEnumerator<TElem>> createEndEnumerator() override
			{
				return std::shared_ptr<IBidirectionalEnumerator<TElem>>(new _ReverseBidirectionalEnumerator<TElem>(_source->getEnumerator()));
			}
		};

		template<typename TElem>
		class _ReverseRandomAccessEnumerator : public IRandomAccessEnumerator<TElem>
		{
		private:
			std::shared_ptr<IRandomAccessEnumerator<TElem>> _source;

		public:
			_ReverseRandomAccessEnumerator(std::shared_ptr<IRandomAccessEnumerator<TElem>> source)
				: _source(source)
			{
			}

			bool next() override
			{
				return _source->back();
			}

			bool back() override
			{
				return _source->next();
			}

			bool advance(int step) override
			{
				return _source->advance(-step);
			}

			TElem current() override
			{
				return _source->current();
			}

			bool equals(std::shared_ptr<IEnumerator<TElem>> other) const override
			{
				auto pother = std::dynamic_pointer_cast<_ReverseRandomAccessEnumerator<TElem>>(other);
				if (!pother)
					return false;
				return _source->equals(pother->_source);
			}

			std::shared_ptr<IEnumerator<TElem>> clone() const override
			{
				return std::shared_ptr<IEnumerator<TElem>>(new _ReverseRandomAccessEnumerator<TElem>(std::dynamic_pointer_cast<IRandomAccessEnumerator<TElem>>(_source->clone())));
			}

			int distance_to(std::shared_ptr<IRandomAccessEnumerator<TElem>> other) const override
			{
				auto pother = std::dynamic_pointer_cast<_ReverseRandomAccessEnumerator<TElem>>(other);
				assert(pother);
				return pother->_source->distance_to(this->_source);
			}

			bool less_than(std::shared_ptr<IRandomAccessEnumerator<TElem>> other) const override
			{
				auto pother = std::dynamic_pointer_cast<_ReverseRandomAccessEnumerator<TElem>>(other);
				assert(pother);
				return this->distance_to(pother) > 0;
			}

			bool greater_than(std::shared_ptr<IRandomAccessEnumerator<TElem>> other) const override
			{
				auto pother = std::dynamic_pointer_cast<_ReverseRandomAccessEnumerator<TElem>>(other);
				assert(pother);
				return this->distance_to(pother) < 0;
			}
		};

		template<typename TElem>
		class _ReverseRandomAccessEnumerable : public IRandomAccessEnumerable<TElem>
		{
		private:
			std::shared_ptr<IRandomAccessEnumerable<TElem>> _source;
		public:
			_ReverseRandomAccessEnumerable(std::shared_ptr<IRandomAccessEnumerable<TElem>> source)
				: _source(source)
			{
			}

			std::shared_ptr<IEnumerator<TElem>> createEnumerator() override
			{
				return std::shared_ptr<IEnumerator<TElem>>(new _ReverseRandomAccessEnumerator<TElem>(_source->getEndEnumerator()));
			}

			std::shared_ptr<IBidirectionalEnumerator<TElem>> createEndEnumerator() override
			{
				return std::shared_ptr<IBidirectionalEnumerator<TElem>>(new _ReverseRandomAccessEnumerator<TElem>(_source->getEnumerator()));
			}

			std::shared_ptr<IRandomAccessEnumerator<TElem>> createEnumeratorAt(int elementIndex) override
			{
				return std::shared_ptr<IRandomAccessEnumerator<TElem>>(new _ReverseRandomAccessEnumerator<TElem>(_source->getEnumeratorAt(_source->size() - elementIndex - 1)));
			}

			int size() override
			{
				return _source->size();
			}
		};

		class _ReverseBuilder
		{
		public:
			template<typename TElem>
			std::shared_ptr<IBidirectionalEnumerable<TElem>> build(std::shared_ptr<IEnumerable<TElem>> enumerable)
			{
				auto vec = std::shared_ptr<std::list<TElem>>(new std::list<TElem>());
				for (auto it = enumerable->getEnumerator(); it->next();)
				{
					vec->push_front(it->current());
				}
				return from(vec);
			}

			template<typename TElem>
			std::shared_ptr<IBidirectionalEnumerable<TElem>> build(std::shared_ptr<IBidirectionalEnumerable<TElem>> enumerable)
			{
				return std::shared_ptr<IBidirectionalEnumerable<TElem>>(new _ReverseBidirectionalEnumerable<TElem>(enumerable));
			}

			template<typename TElem>
			std::shared_ptr<IRandomAccessEnumerable<TElem>> build(std::shared_ptr<IRandomAccessEnumerable<TElem>> enumerable)
			{
				return std::shared_ptr<IRandomAccessEnumerable<TElem>>(new _ReverseRandomAccessEnumerable<TElem>(enumerable));
			}
		};
	}
	/*@endcond*/

	/**
	*	Reversees order of collection elements.
	*	This function may be used to reverse collection elements. The function is O(1)
	*	and does not gather collection elements until IEnumerable<T> is passed.
	*	If so, the function operates in O(n), where n is number of collection elements.
	*	@return Builder of skip_while expression.
	*/
	XLINQ_INLINE internal::_ReverseBuilder reverse()
	{
		return internal::_ReverseBuilder();
	}
}

#endif


text:
@echo off
:: Copyright (c) 2011 The Chromium Authors. All rights reserved.
:: Use of this source code is governed by a BSD-style license that can be
:: found in the LICENSE file.

setlocal

set THISDIR=%~dp0
set TOOL_NAME="unknown"

:: Get the tool name and put it into TOOL_NAME {{{1
:: NB: SHIFT command doesn't modify %*
:PARSE_ARGS_LOOP
  if %1 == () GOTO:TOOLNAME_NOT_FOUND
  if %1 == --tool GOTO:TOOLNAME_FOUND
  SHIFT
  goto :PARSE_ARGS_LOOP

:TOOLNAME_NOT_FOUND
echo "Please specify a tool (e.g. drmemory) by using --tool flag"
exit /B 1

:TOOLNAME_FOUND
SHIFT
set TOOL_NAME=%1
:: }}}
if "%TOOL_NAME%" == "drmemory"          GOTO :SETUP_DRMEMORY
if "%TOOL_NAME%" == "drmemory_light"    GOTO :SETUP_DRMEMORY
if "%TOOL_NAME%" == "drmemory_full"     GOTO :SETUP_DRMEMORY
if "%TOOL_NAME%" == "drmemory_pattern"  GOTO :SETUP_DRMEMORY
echo "Unknown tool: `%TOOL_NAME%`! Only drmemory is supported right now"
exit /B 1

:SETUP_DRMEMORY
:: Set up DRMEMORY_COMMAND to invoke Dr. Memory {{{1
set DRMEMORY_PATH=%THISDIR%..\..\third_party\drmemory
set DRMEMORY_SFX=%DRMEMORY_PATH%\drmemory-windows-sfx.exe
if EXIST %DRMEMORY_SFX% GOTO DRMEMORY_BINARY_OK
echo "Can't find Dr. Memory executables."
echo "See http://www.chromium.org/developers/how-tos/using-valgrind/dr-memory"
echo "for the instructions on how to get them."
exit /B 1

:DRMEMORY_BINARY_OK
%DRMEMORY_SFX% -o%DRMEMORY_PATH%\unpacked -y
set DRMEMORY_COMMAND=%DRMEMORY_PATH%\unpacked\bin\drmemory.exe
:: }}}
goto :RUN_TESTS

:RUN_TESTS
set PYTHONPATH=%THISDIR%../python/google
set RUNNING_ON_VALGRIND=yes
python %THISDIR%/chrome_tests.py %*


text:
@interface VVSPopoverViewController : UIViewController

@end


text:
BaseEventFactory::BaseEventFactory(): EventFactory()
{
    eventList[SDL_QUIT] = new EventQuit();
    eventList[SDL_WINDOWEVENT] = new WindowEvent();
    eventList[SDL_MOUSEBUTTONDOWN] = new MouseButtonEvent(SDL_MOUSEBUTTONDOWN);
    eventList[SDL_MOUSEBUTTONUP] = new MouseButtonEvent(SDL_MOUSEBUTTONUP);
    eventList[SDL_MOUSEMOTION] = new MouseMotionEvent();
}

BaseEventFactory::~BaseEventFactory()
{

}


text:
package org.eclipse.net4j.util.concurrent;

import java.util.concurrent.Executor;

public class OnePendingExecutor implements Executor
{
  private Runnable command;

  private Thread thread;

  public OnePendingExecutor()
  {
  }

  public synchronized void execute(Runnable command)
  {
    if (this.command != null)
    {
      throw new IllegalStateException("One command already pending"); //$NON-NLS-1$
    }

    this.command = command;
    if (thread == null)
    {
      thread = new Thread()
      {
        @Override
        public void run()
        {
          for (;;)
          {
            Runnable command;
            synchronized (OnePendingExecutor.this)
            {
              if (OnePendingExecutor.this.command == null)
              {
                thread = null;
                return;
              }

              command = OnePendingExecutor.this.command;
              OnePendingExecutor.this.command = null;
            }

            command.run();
          }
        }
      };

      thread.setDaemon(true);
      thread.start();
    }
  }
}


text:
Actively read the Mozilla Developer Network's tutorial on [Getting Started with CSS](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started). You are responsible for sections 1 through 14 (i.e., **What is CSS** through **Media**) by Tuesday.

Read the Web Accessibility Initiative's section on [Designing for Inclusion](http://www.w3.org/WAI/users/Overview.html). After, peruse the W3C's document on [How to Meet WCAG 2.0](http://www.w3.org/WAI/WCAG20/quickref/Overview.php) customized for HTML and CSS only.

### Part 2

Your task is to produce a data visualization using the Wheaton College [course schedule](https://weblprod1.wheatonma.edu/PROD/bzcrschd.P_ListSection) as source material.

To build your data visualization, use HTML5, CSS, and SVG.

Create a folder named `hw06` in your course repository that contains at least the following files (use appropriate filenames and extensions):

* `README.md`, a README Markdown file that includes references to the WCAG 2.0
* Source and/or description of what you used to extract data from the course schedule
* `schedule.html`, the HTML file containing your visualization and all SVG content


text:
angular.module('duScroll', ['duScroll.scroller', 'duScroll.scrollPosition', 'duScroll.scrollspy', 'duScroll.requestAnimation', 'duScroll.smoothScroll']);

angular.module('duScroll.requestAnimation', []).
factory('requestAnimation', function($window, $timeout) {
  return $window.requestAnimationFrame  ||
    $window.webkitRequestAnimationFrame ||
    $window.mozRequestAnimationFrame    ||
    $window.oRequestAnimationFrame      ||
    $window.msRequestAnimationFrame     ||
    function fallback( callback ){
      $timeout(callback, 1000 / 60);
    };
});

angular.module('duScroll.scrollPosition', ['duScroll.requestAnimation']).
factory('scrollPosition',
  function($document, $window, $rootScope, requestAnimation) {
    var observers = [];
    var lastScrollY = 0;
    var currentScrollY = 0;

    var executeCallbacks = function(){
      $rootScope.$emit('$duScrollChanged', currentScrollY);
      currentScrollY = lastScrollY;
      for(var i = 0; i < observers.length; i++){
        observers[i](currentScrollY);
      }
    };

    var getScrollY = function() {
      return $window.scrollY || document.documentElement.scrollTop || document.body.scrollTop;
    };

    var getScrollX = function() {
      return $window.scrollX || document.documentElement.scrollLeft || document.body.scrollLeft;
    };

    angular.element($document).on('scroll', function(){
      lastScrollY = getScrollY();

      if(lastScrollY !== currentScrollY){
        requestAnimation(executeCallbacks);
      }
    });
    var deprecationWarned = false;
    return {
      observe : function(cb){
        if(!deprecationWarned && console && console.warn) {
          console.warn('scrollPosition.observe is deprecated, use $rootScope.$on(\'$duScrollChanged\') instead');
          deprecationWarned = true;
        }
        observers.push(cb);
      },
      x: getScrollX,
      y: getScrollY
    };
  }
);

angular.module('duScroll.scroller', ['duScroll.requestAnimation']).
factory('scroller',
  function($window, requestAnimation, scrollPosition) {

    function easeout(x) {
      return Math.pow(x, 0.7);
    }

    function scrollTo(x, y, duration){
      if(!duration) {
        $window.scrollTo(x, y);
        return;
      }
      var start = {
        y: scrollPosition.y(),
        x: scrollPosition.x()
      };
      var delta = {
        y: Math.round(y - start.y),
        x: Math.round(x - start.x)
      };
      if(!delta.x && !delta.y) return;

      var frame = 0;
      var frames = Math.ceil(duration/60);
      var animate = function() {
        frame++;
        var percent = (frame === frames ? 1 : easeout(frame/frames));
        $window.scrollTo(
          start.x + Math.ceil(delta.x * percent),
          start.y + Math.ceil(delta.y * percent)
        );
        if(frame<frames) {
          requestAnimation(animate);
        }
      };
      animate();
    }

    function scrollDelta(x, y, duration){
      scrollTo(scrollPosition.x() + (x || 0), scrollPosition.y() + (y || 0), duration);
    }

    function scrollToElement(element, offset, duration){
      if(!angular.isElement(element)) { return; }
      //Remove jQuery wrapper (if any)
      element = element[0] || element;
      if(!element.getBoundingClientRect) return;

      var pos = element.getBoundingClientRect();

      scrollDelta(0, pos.top + (!offset || isNaN(offset) ? 0 : -offset), duration);
    }

    return {
      scrollTo:         scrollTo,
      scrollToElement:  scrollToElement,
      scrollDelta:      scrollDelta
    };
  }
);

angular.module('duScroll.smoothScroll', ['duScroll.scroller']).
directive('duSmoothScroll', function(scroller){

  return {
    link : function($scope, $element, $attr){
      var element = angular.element($element[0]);
      element.on('click', function(e){
        if(!$attr.href || $attr.href.indexOf('#') === -1) return;
        var elem = document.getElementById($attr.href.replace(/.*(?=#[^\s]+$)/, '').substring(1));
        if(!elem || !elem.getBoundingClientRect) return;

        if (e.stopPropagation) e.stopPropagation();
        if (e.preventDefault) e.preventDefault();

        var offset = -($attr.offset ? parseInt($attr.offset, 10) : 0);
        var pos = elem.getBoundingClientRect();

        scroller.scrollDelta(0, pos.top + (isNaN(offset) ? 0 : offset), 1000);
      });
    }
  };
});

angular.module('duScroll.scrollspy', ['duScroll.scrollPosition']).
directive('duScrollspy', function($rootScope, scrollPosition) {
  var spies = [];
  var currentlyActive;
  var isObserving = false;

  var Spy = function(targetElementOrId, $element, offset) {
    if(angular.isElement(targetElementOrId)) {
      this.target = targetElementOrId;
    } else if(angular.isString(targetElementOrId)) {
      this.targetId = targetElementOrId;
    }
    this.$element = $element;
    this.offset = offset;
  };

  Spy.prototype.getTargetElement = function() {
    if (!this.target && this.targetId) {
      this.target = document.getElementById(this.targetId);
    }
    return this.target;
  };

  Spy.prototype.getTargetPosition = function() {
    var target = this.getTargetElement();
    if(target) {
      return target.getBoundingClientRect();
    }
  };

  function gotScroll($event, scrollY) {
    var toBeActive;
    for(var spy, scroll, pos, i = 0; i < spies.length; i++) {
      spy = spies[i];
      pos = spy.getTargetPosition();
      if (!pos) continue;

      if(pos.top + spy.offset < 20 && pos.top*-1 < pos.height) {
        if(!toBeActive || toBeActive.top < pos.top) {
          toBeActive = {
            top: pos.top,
            spy: spy
          };
        }
      }
    }
    if(toBeActive) {
      toBeActive = toBeActive.spy;
    }
    if(currentlyActive === toBeActive) return;
    if(currentlyActive) currentlyActive.$element.removeClass('active');
    if(toBeActive) toBeActive.$element.addClass('active');
    currentlyActive = toBeActive;
  }

  function addSpy(spy) {
    if(!isObserving) {
      $rootScope.$on('$duScrollChanged', gotScroll);
      isObserving = true;
    }
    spies.push(spy);
  }

  function removeSpy(spy) {
    if(spy === currentlyActive) {
      currentlyActive = null;
    }
    var i = spies.indexOf(spy);
    if(i !== -1) {
      spies.splice(i, 1);
    }
  }

  return {
    link: function ($scope, $element, $attr) {
      if (!$attr.href || $attr.href.indexOf('#') === -1) return;
      var targetId = $attr.href.replace(/.*(?=#[^\s]+$)/, '').substring(1);
      if(!targetId) return;

      var spy = new Spy(targetId, $element, -($attr.offset ? parseInt($attr.offset, 10) : 0));
      addSpy(spy);

      $scope.$on('$destroy', function() {
        removeSpy(spy);
      });
    }
  };
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>LPM: Lagrangian Particle Methods: spherebvesolvermodule Module Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

LPM: Lagrangian Particle Methods
    2.0

PDE solver

Main Page

Related Pages

Modules

Data Types List

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Types List

Data Types

Data Fields

 All Classes Files Functions Variables Modules Pages

Data Types |
Private Member Functions |
Private Attributes |
List of all members

spherebvesolvermodule Module Reference

Detailed Description

Definition at line 1 of file SphereBVESolver.f90.

Data Types

type  	bvesolver

interface  	delete

interface  	new

interface  	timestep

Private Member Functions

subroutine 	newprivate (self, sphereBVE)

 	Allocates memory for a new BVE Solver. Initializes the solver to match the current mesh.  More...

subroutine 	deleteprivate (self)

 	Deletes and frees memory associated with a BVE Solver.  More...

subroutine 	timestepprivate (self, sphereBVE, dt)

 	Advances a BVE mesh forward in time by one timestep using 4th order Runge-Kutta.  More...

subroutine 	bvespherevelocity (u, v, w, x, y, z, relVortIn, areaIn, sphereRadius, rotationRate, activeMask, mpiParticles)

 	Computes velocity based on the given vorticity of all point vortices (particles) using the Biot-Savart integral. Integral is computed in parallel as a direct summation.  More...

subroutine 	initlogger (aLog, rank)

 	Initializes a logger for the SphereBVE solver module.  More...

Private Attributes

logical(klog), save 	loginit = .FALSE.

type(logger) 	log

character(len=28), save 	logkey = 'BVESolver'

integer(kint), parameter 	loglevel = DEBUG_LOGGING_LEVEL

The documentation for this module was generated from the following file:

/Users/pabosle/lpm-v2/SphereBVESolver.f90

<address class="footer">
Generated on Tue Jan 12 2016 10:09:31 for LPM: Lagrangian Particle Methods by

 1.8.8
</address>


text:
namespace blink {

class BLINK_COMMON_EXPORT IndexedDBKeyPath {
 public:
  IndexedDBKeyPath();  // Defaults to blink::WebIDBKeyPathTypeNull.
  explicit IndexedDBKeyPath(const base::string16&);
  explicit IndexedDBKeyPath(const std::vector<base::string16>&);
  IndexedDBKeyPath(const IndexedDBKeyPath& other);
  IndexedDBKeyPath(IndexedDBKeyPath&& other);
  ~IndexedDBKeyPath();
  IndexedDBKeyPath& operator=(const IndexedDBKeyPath& other);
  IndexedDBKeyPath& operator=(IndexedDBKeyPath&& other);

  bool IsNull() const { return type_ == blink::mojom::IDBKeyPathType::Null; }
  bool operator==(const IndexedDBKeyPath& other) const;

  mojom::IDBKeyPathType type() const { return type_; }
  const std::vector<base::string16>& array() const;
  const base::string16& string() const;

 private:
  mojom::IDBKeyPathType type_;
  base::string16 string_;
  std::vector<base::string16> array_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_PUBLIC_COMMON_INDEXEDDB_INDEXEDDB_KEY_PATH_H_


text:
Amp

Support

Privacy policy

Open source licenses

GitHub

RIP Winamp


text:
@interface MODesignersModuleCollectionViewCell : UICollectionViewCell

+ (CGFloat)cellHeight;

- (void)configure;

@end


text:
A Simple Text Adventure System
==============================

To Run:

  - `stack build`
  - `stack exec htads-exe`

Notable features are:

  - A flexible object description parser.
  - An alias system for command abbreviations

Includes some work in progress reading YAML adventure definition files.


text:
ActiveRecord::Schema.define(version: 20150927191915) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "artists", force: :cascade do |t|
    t.string   "name",               null: false
    t.string   "real_name"
    t.text     "profile"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
  end

  add_index "artists", ["name"], name: "index_artists_on_name", unique: true, using: :btree

  create_table "comments", force: :cascade do |t|
    t.integer  "author_id"
    t.text     "body",             null: false
    t.integer  "commentable_id"
    t.string   "commentable_type"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
  end

  add_index "comments", ["author_id"], name: "index_comments_on_author_id", using: :btree
  add_index "comments", ["commentable_type", "commentable_id"], name: "index_comments_on_commentable_type_and_commentable_id", using: :btree

  create_table "countries", force: :cascade do |t|
    t.string   "code",       null: false
    t.string   "name",       null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "friendly_id_slugs", force: :cascade do |t|
    t.string   "slug",                      null: false
    t.integer  "sluggable_id",              null: false
    t.string   "sluggable_type", limit: 50
    t.string   "scope"
    t.datetime "created_at"
  end

  add_index "friendly_id_slugs", ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true, using: :btree
  add_index "friendly_id_slugs", ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type", using: :btree
  add_index "friendly_id_slugs", ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id", using: :btree
  add_index "friendly_id_slugs", ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type", using: :btree

  create_table "genre_taggings", force: :cascade do |t|
    t.integer  "genre_id",   null: false
    t.integer  "record_id",  null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "genre_taggings", ["genre_id", "record_id"], name: "index_genre_taggings_on_genre_id_and_record_id", unique: true, using: :btree
  add_index "genre_taggings", ["genre_id"], name: "index_genre_taggings_on_genre_id", using: :btree
  add_index "genre_taggings", ["record_id"], name: "index_genre_taggings_on_record_id", using: :btree

  create_table "genres", force: :cascade do |t|
    t.string   "name",       null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "genres", ["name"], name: "index_genres_on_name", unique: true, using: :btree

  create_table "labels", force: :cascade do |t|
    t.string   "title",              null: false
    t.text     "profile"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
  end

  add_index "labels", ["title"], name: "index_labels_on_title", unique: true, using: :btree

  create_table "pg_search_documents", force: :cascade do |t|
    t.text     "content"
    t.integer  "searchable_id"
    t.string   "searchable_type"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  add_index "pg_search_documents", ["searchable_type", "searchable_id"], name: "index_pg_search_documents_on_searchable_type_and_searchable_id", using: :btree

  create_table "records", force: :cascade do |t|
    t.string   "title",                              null: false
    t.string   "cat_no"
    t.integer  "year"
    t.text     "notes"
    t.datetime "created_at",                         null: false
    t.datetime "updated_at",                         null: false
    t.integer  "artist_id",                          null: false
    t.integer  "label_id"
    t.integer  "country_id"
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
    t.integer  "discogs_id"
    t.integer  "user_wants_count",       default: 0
    t.integer  "user_collections_count", default: 0
  end

  add_index "records", ["artist_id"], name: "index_records_on_artist_id", using: :btree
  add_index "records", ["country_id"], name: "index_records_on_country_id", using: :btree
  add_index "records", ["label_id"], name: "index_records_on_label_id", using: :btree

  create_table "tracks", force: :cascade do |t|
    t.integer  "record_id",  null: false
    t.string   "title",      null: false
    t.string   "duration"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "position"
    t.integer  "ord",        null: false
  end

  add_index "tracks", ["record_id"], name: "index_tracks_on_record_id", using: :btree

  create_table "user_activities", force: :cascade do |t|
    t.integer  "user_id",         null: false
    t.integer  "activity_id",     null: false
    t.string   "activity_class",  null: false
    t.string   "activity_action", null: false
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  add_index "user_activities", ["user_id"], name: "index_user_activities_on_user_id", using: :btree

  create_table "user_collections", force: :cascade do |t|
    t.integer  "user_id",    null: false
    t.integer  "record_id",  null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "user_collections", ["record_id"], name: "index_user_collections_on_record_id", using: :btree
  add_index "user_collections", ["user_id", "record_id"], name: "index_user_collections_on_user_id_and_record_id", unique: true, using: :btree
  add_index "user_collections", ["user_id"], name: "index_user_collections_on_user_id", using: :btree

  create_table "user_contributions", force: :cascade do |t|
    t.integer  "user_id",            null: false
    t.integer  "contributable_id",   null: false
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.string   "contributable_type"
  end

  add_index "user_contributions", ["contributable_id"], name: "index_user_contributions_on_contributable_id", using: :btree
  add_index "user_contributions", ["user_id", "contributable_id", "contributable_type"], name: "index_user_contributions_on_user_id_and_contributable", unique: true, using: :btree
  add_index "user_contributions", ["user_id"], name: "index_user_contributions_on_user_id", using: :btree

  create_table "user_wants", force: :cascade do |t|
    t.integer  "user_id",    null: false
    t.integer  "record_id",  null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "user_wants", ["record_id"], name: "index_user_wants_on_record_id", using: :btree
  add_index "user_wants", ["user_id", "record_id"], name: "index_user_wants_on_user_id_and_record_id", unique: true, using: :btree
  add_index "user_wants", ["user_id"], name: "index_user_wants_on_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string   "username",                             null: false
    t.string   "email",                                null: false
    t.string   "password_digest",                      null: false
    t.string   "session_token",                        null: false
    t.string   "location"
    t.string   "url"
    t.text     "profile"
    t.datetime "created_at",                           null: false
    t.datetime "updated_at",                           null: false
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
    t.string   "provider"
    t.string   "uid"
    t.string   "slug"
    t.integer  "comments_count",           default: 0
    t.integer  "user_contributions_count", default: 0
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["session_token"], name: "index_users_on_session_token", unique: true, using: :btree
  add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree

end


text:
using System.Collections.Generic;

namespace System.Net.Http.Headers
{
	public sealed class TransferCodingWithQualityHeaderValue : TransferCodingHeaderValue
	{
		public TransferCodingWithQualityHeaderValue (string value)
			: base (value)
		{
		}

		public TransferCodingWithQualityHeaderValue (string value, double quality)
			: this (value)
		{
			Quality = quality;
		}

		private TransferCodingWithQualityHeaderValue ()
		{
		}

		public double? Quality {
			get {
				return QualityValue.GetValue (parameters);
			}
			set {
				QualityValue.SetValue (ref parameters, value);
			}
		}

		public new static TransferCodingWithQualityHeaderValue Parse (string input)
		{
			TransferCodingWithQualityHeaderValue value;
			if (TryParse (input, out value))
				return value;

			throw new FormatException ();
		}

		public static bool TryParse (string input, out TransferCodingWithQualityHeaderValue parsedValue)
		{
			var lexer = new Lexer (input);
			Token token;
			if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
				return true;

			parsedValue = null;
			return false;
		}

		internal static bool TryParse (string input, int minimalCount, out List<TransferCodingWithQualityHeaderValue> result)
		{
			return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
		}

		static bool TryParseElement (Lexer lexer, out TransferCodingWithQualityHeaderValue parsedValue, out Token t)
		{
			parsedValue = null;

			t = lexer.Scan ();
			if (t != Token.Type.Token)
				return false;

			var result = new TransferCodingWithQualityHeaderValue ();
			result.value = lexer.GetStringValue (t);

			t = lexer.Scan ();

			// Parameters parsing
			if (t == Token.Type.SeparatorSemicolon && (!NameValueHeaderValue.TryParseParameters (lexer, out result.parameters, out t) || t != Token.Type.End))
				return false;

			parsedValue = result;
			return true;
		}
	}
}