text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import json
import os
import random

import numpy as np

import ray
from ray.tune import Trainable, run, sample_from
from ray.tune.schedulers import AsyncHyperBandScheduler

class MyTrainableClass(Trainable):
    """Example agent whose learning curve is a random sigmoid.

    The dummy hyperparameters "width" and "height" determine the slope and
    maximum reward value reached.
    """

    def _setup(self, config):
        self.timestep = 0

    def _train(self):
        self.timestep += 1
        v = np.tanh(float(self.timestep) / self.config["width"])
        v *= self.config["height"]

        # Here we use `episode_reward_mean`, but you can also report other
        # objectives such as loss or accuracy.
        return {"episode_reward_mean": v}

    def _save(self, checkpoint_dir):
        path = os.path.join(checkpoint_dir, "checkpoint")
        with open(path, "w") as f:
            f.write(json.dumps({"timestep": self.timestep}))
        return path

    def _restore(self, checkpoint_path):
        with open(checkpoint_path) as f:
            self.timestep = json.loads(f.read())["timestep"]

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--smoke-test", action="store_true", help="Finish quickly for testing")
    args, _ = parser.parse_known_args()
    ray.init()

    # asynchronous hyperband early stopping, configured with
    # `episode_reward_mean` as the
    # objective and `training_iteration` as the time unit,
    # which is automatically filled by Tune.
    ahb = AsyncHyperBandScheduler(
        time_attr="training_iteration",
        metric="episode_reward_mean",
        mode="max",
        grace_period=5,
        max_t=100)

    run(MyTrainableClass,
        name="asynchyperband_test",
        scheduler=ahb,
        **{
            "stop": {
                "training_iteration": 1 if args.smoke_test else 99999
            },
            "num_samples": 20,
            "resources_per_trial": {
                "cpu": 1,
                "gpu": 0
            },
            "config": {
                "width": sample_from(
                    lambda spec: 10 + int(90 * random.random())),
                "height": sample_from(lambda spec: int(100 * random.random())),
            },
        })


text:
package com.qiniu.rtc.model;

import lombok.Data;

@Data
public class CallbackParam {
    private String eventCbUrl;
    private String eventCbSecret;
    private int eventCbVersion;
}

redpajama_set_name: RedPajamaGithub


text:
@interface HGoToApp () <SKStoreProductViewControllerDelegate>

@property (nonatomic) id mHolder;
@property (nonatomic, weak) SKStoreProductViewController *mSkStoreProductViewController;
@end

@implementation HGoToApp

HGotoReg(@"app")

+ (void)hgoto_schema:(NSString *)schema url:(NSString *)url
{
    if (schema)
    {
        NSURL *schemaURL = [NSURL URLWithString:schema];
        if ([[UIApplication sharedApplication] canOpenURL:schemaURL])
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:schema]];
        }
        else if (url)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[url decode]]];
        }
    }
    else
    {
        if (url)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[url decode]]];
        }
    }
}

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title data-role="dummy">S-RAMP Repository Browser - Artifacts (Dialogs)</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>
    <link href="../../../../../../../../../webapp/bootstrap-2.3.1/css/bootstrap.min.css" rel="stylesheet" media="screen"></link>
    <link href="../../../../../../../../../webapp/bootstrap-2.3.1/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen"></link>
    <link href="../../../../../../../../../webapp/bootstrap-2.3.1/css/bootstrap-datepicker.css" rel="stylesheet" media="screen"></link>
    <link href="../../../../../../../../../webapp/bootstrap-2.3.1/css/bootstrap-fileupload.min.css" rel="stylesheet" media="screen"></link>
    <link href="../../../../../../../../../webapp/css/s-ramp-ui.css" rel="stylesheet"></link>
    <link href="../../../../../../../../../webapp/css/s-ramp-ui-responsive.css" rel="stylesheet"></link>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Create Artifact

        <form data-field="create-dialog-form" method="post">
          <fieldset>
            Provide a custom (alphanumerical) artifact type:
            <input data-field="create-dialog-type" type="text" name="artifactType" value="" placeholder="e.g. FooType"/>
            Provide an artifact name:
            <input data-field="create-dialog-name" type="text" name="artifactName" value=""/>
            Provide a description (optional):
            <textarea data-field="create-dialog-description" name="artifactDescription" class="input-value" rows="5" cols=""></textarea>
          </fieldset>
        </form>

        <button class="btn" data-dismiss="modal" data-i18n-key="cancel">Cancel</button>
        <button data-field="create-dialog-submit-button" class="btn btn-focus" data-i18n-key="create">Create</button>


text:
using extensions::NativeHandler;

ChromeExtensionsDispatcherDelegate::ChromeExtensionsDispatcherDelegate()
    : webrequest_used_(false) {
}

ChromeExtensionsDispatcherDelegate::~ChromeExtensionsDispatcherDelegate() {
}

scoped_ptr<extensions::ScriptContext>
ChromeExtensionsDispatcherDelegate::CreateScriptContext(
    const v8::Handle<v8::Context>& v8_context,
    blink::WebFrame* frame,
    const extensions::Extension* extension,
    extensions::Feature::Context context_type) {
  return scoped_ptr<extensions::ScriptContext>(new extensions::ChromeV8Context(
      v8_context, frame, extension, context_type));
}

void ChromeExtensionsDispatcherDelegate::InitOriginPermissions(
    const extensions::Extension* extension,
    bool is_extension_active) {
  // TODO(jstritar): We should try to remove this special case. Also, these
  // whitelist entries need to be updated when the kManagement permission
  // changes.
  if (is_extension_active &&
      extension->permissions_data()->HasAPIPermission(
          extensions::APIPermission::kManagement)) {
    blink::WebSecurityPolicy::addOriginAccessWhitelistEntry(
        extension->url(),
        blink::WebString::fromUTF8(content::kChromeUIScheme),
        blink::WebString::fromUTF8(chrome::kChromeUIExtensionIconHost),
        false);
  }
}

void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers(
    extensions::Dispatcher* dispatcher,
    extensions::ModuleSystem* module_system,
    extensions::ScriptContext* context) {
#if !defined(ENABLE_EXTENSIONS)
  return;
#endif
  module_system->RegisterNativeHandler(
      "app",
      scoped_ptr<NativeHandler>(
          new extensions::AppBindings(dispatcher, context)));
  module_system->RegisterNativeHandler(
      "app_window_natives",
      scoped_ptr<NativeHandler>(
          new extensions::AppWindowCustomBindings(dispatcher, context)));
  module_system->RegisterNativeHandler(
      "sync_file_system",
      scoped_ptr<NativeHandler>(
          new extensions::SyncFileSystemCustomBindings(context)));
  module_system->RegisterNativeHandler(
      "enterprise_platform_keys_natives",
      scoped_ptr<NativeHandler>(
          new extensions::EnterprisePlatformKeysNatives(context)));
  module_system->RegisterNativeHandler(
      "file_browser_handler",
      scoped_ptr<NativeHandler>(
          new extensions::FileBrowserHandlerCustomBindings(context)));
  module_system->RegisterNativeHandler(
      "file_browser_private",
      scoped_ptr<NativeHandler>(
          new extensions::FileBrowserPrivateCustomBindings(context)));
  module_system->RegisterNativeHandler(
      "notifications_private",
      scoped_ptr<NativeHandler>(
          new extensions::NotificationsNativeHandler(context)));
  module_system->RegisterNativeHandler(
      "mediaGalleries",
      scoped_ptr<NativeHandler>(
          new extensions::MediaGalleriesCustomBindings(context)));
  module_system->RegisterNativeHandler(
      "page_actions",
      scoped_ptr<NativeHandler>(
          new extensions::PageActionsCustomBindings(dispatcher, context)));
  module_system->RegisterNativeHandler(
      "page_capture",
      scoped_ptr<NativeHandler>(
          new extensions::PageCaptureCustomBindings(context)));
  module_system->RegisterNativeHandler(
      "tabs",
      scoped_ptr<NativeHandler>(new extensions::TabsCustomBindings(context)));
  module_system->RegisterNativeHandler(
      "webstore",
      scoped_ptr<NativeHandler>(new extensions::WebstoreBindings(context)));
#if defined(ENABLE_WEBRTC)
  module_system->RegisterNativeHandler(
      "cast_streaming_natives",
      scoped_ptr<NativeHandler>(
          new extensions::CastStreamingNativeHandler(context)));
#endif
  module_system->RegisterNativeHandler(
      "automationInternal",
      scoped_ptr<NativeHandler>(
          new extensions::AutomationInternalCustomBindings(context)));
}

void ChromeExtensionsDispatcherDelegate::PopulateSourceMap(
    extensions::ResourceBundleSourceMap* source_map) {
  // Custom bindings.
  source_map->RegisterSource("app", IDR_APP_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("automation", IDR_AUTOMATION_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("automationEvent", IDR_AUTOMATION_EVENT_JS);
  source_map->RegisterSource("automationNode", IDR_AUTOMATION_NODE_JS);
  source_map->RegisterSource("browserAction",
                             IDR_BROWSER_ACTION_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("declarativeContent",
                             IDR_DECLARATIVE_CONTENT_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("declarativeWebRequest",
                             IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("desktopCapture",
                             IDR_DESKTOP_CAPTURE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("developerPrivate",
                             IDR_DEVELOPER_PRIVATE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("downloads", IDR_DOWNLOADS_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("enterprise.platformKeys",
                             IDR_ENTERPRISE_PLATFORM_KEYS_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("enterprise.platformKeys.internalAPI",
                             IDR_ENTERPRISE_PLATFORM_KEYS_INTERNAL_API_JS);
  source_map->RegisterSource("enterprise.platformKeys.Key",
                             IDR_ENTERPRISE_PLATFORM_KEYS_KEY_JS);
  source_map->RegisterSource("enterprise.platformKeys.KeyPair",
                             IDR_ENTERPRISE_PLATFORM_KEYS_KEY_PAIR_JS);
  source_map->RegisterSource("enterprise.platformKeys.SubtleCrypto",
                             IDR_ENTERPRISE_PLATFORM_KEYS_SUBTLE_CRYPTO_JS);
  source_map->RegisterSource("enterprise.platformKeys.Token",
                             IDR_ENTERPRISE_PLATFORM_KEYS_TOKEN_JS);
  source_map->RegisterSource("enterprise.platformKeys.utils",
                             IDR_ENTERPRISE_PLATFORM_KEYS_UTILS_JS);
  source_map->RegisterSource("feedbackPrivate",
                             IDR_FEEDBACK_PRIVATE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("fileBrowserHandler",
                             IDR_FILE_BROWSER_HANDLER_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("fileBrowserPrivate",
                             IDR_FILE_BROWSER_PRIVATE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("fileSystem", IDR_FILE_SYSTEM_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("fileSystemProvider",
                             IDR_FILE_SYSTEM_PROVIDER_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("gcm", IDR_GCM_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("identity", IDR_IDENTITY_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("imageWriterPrivate",
                             IDR_IMAGE_WRITER_PRIVATE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("input.ime", IDR_INPUT_IME_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("mediaGalleries",
                             IDR_MEDIA_GALLERIES_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("notifications",
                             IDR_NOTIFICATIONS_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("omnibox", IDR_OMNIBOX_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("pageActions",
                             IDR_PAGE_ACTIONS_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("pageAction", IDR_PAGE_ACTION_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("pageCapture",
                             IDR_PAGE_CAPTURE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("syncFileSystem",
                             IDR_SYNC_FILE_SYSTEM_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("systemIndicator",
                             IDR_SYSTEM_INDICATOR_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("tabCapture", IDR_TAB_CAPTURE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("tabs", IDR_TABS_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("tts", IDR_TTS_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("ttsEngine", IDR_TTS_ENGINE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("webRequest", IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("webRequestInternal",
                             IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS);
#if defined(ENABLE_WEBRTC)
  source_map->RegisterSource("cast.streaming.rtpStream",
                             IDR_CAST_STREAMING_RTP_STREAM_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("cast.streaming.session",
                             IDR_CAST_STREAMING_SESSION_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource(
      "cast.streaming.udpTransport",
      IDR_CAST_STREAMING_UDP_TRANSPORT_CUSTOM_BINDINGS_JS);
#endif
  source_map->RegisterSource("webstore", IDR_WEBSTORE_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("windowControls", IDR_WINDOW_CONTROLS_JS);

  // Custom types sources.
  source_map->RegisterSource("ChromeSetting", IDR_CHROME_SETTING_JS);
  source_map->RegisterSource("ContentSetting", IDR_CONTENT_SETTING_JS);
  source_map->RegisterSource("ChromeDirectSetting",
                             IDR_CHROME_DIRECT_SETTING_JS);

  // Platform app sources that are not API-specific..
  source_map->RegisterSource("appView", IDR_APP_VIEW_JS);
  source_map->RegisterSource("tagWatcher", IDR_TAG_WATCHER_JS);
  source_map->RegisterSource("webViewInternal",
                             IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS);
  // Note: webView not webview so that this doesn't interfere with the
  // chrome.webview API bindings.
  source_map->RegisterSource("webView", IDR_WEB_VIEW_JS);
  source_map->RegisterSource("webViewEvents", IDR_WEB_VIEW_EVENTS_JS);
  source_map->RegisterSource("webViewExperimental",
                             IDR_WEB_VIEW_EXPERIMENTAL_JS);
  source_map->RegisterSource("webViewRequest",
                             IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS);
  source_map->RegisterSource("denyAppView", IDR_APP_VIEW_DENY_JS);
  source_map->RegisterSource("denyWebView", IDR_WEB_VIEW_DENY_JS);
  source_map->RegisterSource("injectAppTitlebar", IDR_INJECT_APP_TITLEBAR_JS);
}

void ChromeExtensionsDispatcherDelegate::RequireAdditionalModules(
    extensions::ModuleSystem* module_system,
    const extensions::Extension* extension,
    extensions::Feature::Context context_type,
    bool is_within_platform_app) {
  // TODO(kalman, fsamuel): Eagerly calling Require on context startup is
  // expensive. It would be better if there were a light way of detecting when
  // a webview or appview is created and only then set up the infrastructure.
  if (context_type == extensions::Feature::BLESSED_EXTENSION_CONTEXT &&
      is_within_platform_app &&
      extensions::GetCurrentChannel() <= chrome::VersionInfo::CHANNEL_DEV &&
      CommandLine::ForCurrentProcess()->HasSwitch(
          ::switches::kEnableAppWindowControls)) {
    module_system->Require("windowControls");
  }

  // We used to limit WebView to |BLESSED_EXTENSION_CONTEXT| within platform
  // apps. An ext/app runs in a blessed extension context, if it is the active
  // extension in the current process, in other words, if it is loaded in a top
  // frame. To support webview in a non-frame extension, we have to allow
  // unblessed extension context as well.
  // Note: setting up the WebView class here, not the chrome.webview API.
  // The API will be automatically set up when first used.
  if (context_type == extensions::Feature::BLESSED_EXTENSION_CONTEXT ||
      context_type == extensions::Feature::UNBLESSED_EXTENSION_CONTEXT) {
    if (extension->permissions_data()->HasAPIPermission(
            extensions::APIPermission::kWebView)) {
      module_system->Require("webView");
      if (extensions::GetCurrentChannel() <= chrome::VersionInfo::CHANNEL_DEV) {
        module_system->Require("webViewExperimental");
      } else {
        // TODO(asargent) We need a whitelist for webview experimental.
        // crbug.com/264852
        std::string id_hash = base::SHA1HashString(extension->id());
        std::string hexencoded_id_hash =
            base::HexEncode(id_hash.c_str(), id_hash.length());
        if (hexencoded_id_hash == "8C3741E3AF0B93B6E8E0DDD499BB0B74839EA578" ||
            hexencoded_id_hash == "E703483CEF33DEC18B4B6DD84B5C776FB9182BDB" ||
            hexencoded_id_hash == "1A26E32DE447A17CBE5E9750CDBA78F58539B39C" ||
            hexencoded_id_hash == "59048028102D7B4C681DBC7BC6CD980C3DC66DA3") {
          module_system->Require("webViewExperimental");
        }
      }
    } else {
      module_system->Require("denyWebView");
    }
  }

  if (context_type == extensions::Feature::BLESSED_EXTENSION_CONTEXT) {
    if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppView) &&
        extension->permissions_data()->HasAPIPermission(
            extensions::APIPermission::kAppView)) {
      module_system->Require("appView");
    } else {
      module_system->Require("denyAppView");
    }
  }
}

void ChromeExtensionsDispatcherDelegate::OnActiveExtensionsUpdated(
    const std::set<std::string>& extension_ids) {
  // In single-process mode, the browser process reports the active extensions.
  if (CommandLine::ForCurrentProcess()->HasSwitch(::switches::kSingleProcess))
    return;
  crash_keys::SetActiveExtensions(extension_ids);
}

void ChromeExtensionsDispatcherDelegate::SetChannel(int channel) {
  extensions::SetCurrentChannel(
      static_cast<chrome::VersionInfo::Channel>(channel));
}

void ChromeExtensionsDispatcherDelegate::ClearTabSpecificPermissions(
    const extensions::Dispatcher* dispatcher,
    int tab_id,
    const std::vector<std::string>& extension_ids) {
  for (std::vector<std::string>::const_iterator it = extension_ids.begin();
       it != extension_ids.end();
       ++it) {
    const extensions::Extension* extension =
        dispatcher->extensions()->GetByID(*it);
    if (extension)
      extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
  }
}

void ChromeExtensionsDispatcherDelegate::UpdateTabSpecificPermissions(
    const extensions::Dispatcher* dispatcher,
    const GURL& url,
    int tab_id,
    const std::string& extension_id,
    const extensions::URLPatternSet& origin_set) {
  content::RenderView* view = extensions::TabFinder::Find(tab_id);

  // For now, the message should only be sent to the render view that contains
  // the target tab. This may change. Either way, if this is the target tab it
  // gives us the chance to check against the URL to avoid races.
  DCHECK(view);
  GURL active_url(view->GetWebView()->mainFrame()->document().url());
  if (active_url != url)
    return;

  const extensions::Extension* extension =
      dispatcher->extensions()->GetByID(extension_id);
  if (!extension)
    return;

  extension->permissions_data()->UpdateTabSpecificPermissions(
      tab_id,
      new extensions::PermissionSet(extensions::APIPermissionSet(),
                                    extensions::ManifestPermissionSet(),
                                    origin_set,
                                    extensions::URLPatternSet()));
}

void ChromeExtensionsDispatcherDelegate::HandleWebRequestAPIUsage(
    bool webrequest_used) {
  webrequest_used_ = webrequest_used;
}


text:
<?php
namespace AppBundle\Events\Listeners;

use AppBundle\Events\ResaDoneEvent;

use AppBundle\Entity\Resa;

class ResaDoneListener
{
	protected $confirmationSender;

	// public function construct($confirmationSender)
	public function setConfirmationSender($confirmationSender)
	{
		$this->confirmationSender = $confirmationSender;
	}

    public function sendMail(ResaDoneEvent $resaDoneEvent)
    {
        $resa = $resaDoneEvent->getResa();

        // only act on some "Resa" entity
        if (!$resa instanceof Resa) {
            return;
        }

		$total = '10000';

		$this->confirmationSender->send($resa, $total);
    }
}


text:
namespace network {

bool IsURLHandledByNetworkService(const GURL& url) {
  return (url.SchemeIsHTTPOrHTTPS() || url.SchemeIsWSOrWSS());
}

}  // namespace network


text:
var __ = require('underscore'),
    Backbone = require('backbone'),
    $ = require('jquery'),
    loadTemplate = require('../utils/loadTemplate');
Backbone.$ = $;

module.exports = Backbone.View.extend({

  className: "flexRow custCol-border",

  tagName: "li",

  initialize: function(options){
    this.options = options || {};
    this.model.set('selected', this.options.selected);
  },

  render: function(){
    var self = this;
    loadTemplate('./js/templates/chooseCurrency.html', function(loadedTemplate) {
      self.$el.html(loadedTemplate(self.model.toJSON()));
    });
    return this;
  },

  close: function(){
    __.each(this.subViews, function(subView) {
      if(subView.close){
        subView.close();
      }else{
        subView.unbind();
        subView.remove();
      }
    });
    this.unbind();
    this.remove();
  }

});


text:
require("babel-polyfill");
if(process.env.NODE_ENV !== 'production'){
  require('dotenv').config();
}
import {resolvePort, env, onError} from './utils';
import * as socketIO from 'socket.io';
import * as http from 'http';

const iconvLite = require('iconv-lite');
iconvLite.encodingExists('foo');

const app = require('./app');
const models = require('./models');

process.on('SIGINT', () => {
  process.exit(0);
});

const IS_TEST = process.env.NODE_ENV === 'test';
const portCandidate = IS_TEST ? env('TEST_PORT') : env('PORT');

const port: number = resolvePort(portCandidate);

async function dbInit(){
  await models.sequelize.sync();
}

const server = new http.Server(app);
if(process.env.NODE_ENV !== 'test'){
  dbInit();
}
server.listen(port, () => {
  if(! IS_TEST){
    console.log(`Listening at http://localhost:${port}`);
  }
});
server.on('error', onError.bind(port));

const io = socketIO(server);

module.exports = server;


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Enhancing OpenStack Projects with Advanced SLA and Scheduling</title>

		<meta name="description" content="Description">
		<meta name="author" content="Author">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">

		<link rel="stylesheet" href="css/theme/night-rh.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Cells

Experimental

Experimental

Experimental

Did I say, experimental ?

Teasing Cells V2 : http://docs.openstack.org/developer/nova/devref/cells.html#manifesto


text:
\documentclass{article}

% Packages used
\usepackage{longtable}
\usepackage{amsmath}
\usepackage{authblk}

% Author information
\title{Reproducing and extending the analysis of Lloyd et al (2013) with the \texttt{Lloyd.et.al.Cell.abundance.metaanalysis} package}
\author[1,2]{Andrew D. Steen}
\author[2,3,4]{Megan K. May}
\author[2]{Karen G. Lloyd}
\affil[1]{\texttt{andrew.decker.steen@gmail.com}}
\affil[2]{Department of Microbiology, University of Tennesse, Knoxville}
\affil[3]{DePauw University}
\affil[4]{Present address: Woods Hole Oceanographic Institution}

\date{11 November 2013}

% Vignette index entry
%\VignetteIndexEntry{Reproduce and extend the analysis of Lloyd et al 2013}

\usepackage{Sweave}
\begin{document}
\input{Lloyd_et_al_vignette-concordance}
\maketitle

\section{Introduction}
This package allows users to reproduce, and more importantly to extend, the data analysis from the paper by Karen G. Lloyd, Megan K. May, Richard T. Kevorkian, and Andrew D. Steen (2013), ``Meta-analysis of quantification methods shows archaea and bacteria to be similarly abundant in the subseafloor'', Applied and Environmental Microbiology, doi: 10.1128/AEM.02090-13.

\section{Reproducing the analysis}

The simplest way to reproduce the entire analysis is to use

\begin{Schunk}
\begin{Sinput}
> invisible(reproduce_research,
+           print_plots=TRUE,
+           save_plots=TRUE,
+           fast_calc=FALSE)
\end{Sinput}
\end{Schunk}
This will create all of the analysis in the paper, print and save plots and certain tables, and display some tables in the console output.

This is a fine way to check our work, and we encourage it. However, the purpose of writing this package is to encourage \textbf{extensions} of our analysis, either by adding data to the database as it becomes avaialable, or by applying new analyses to the existing data set or to new data sets.

\section{Extending the analysis}
In order to extend the analysis, it is useful to be able to:

\begin{itemize}
  \item Add data to our database
  \item Run functions on our database (or an extended database) in isolation
\end{itemize}

\subsection{Working with our database}

This package is built on two central databases, containing data from the water column and from sediments. These databases are similar, but not identical. These are included as two Microsoft Excel (\texttt{.xlsx}) files included as supplemental files to the journal article. Somewhat confusingly, they are encoded as three R objects (each included with the package as an \texttt{.RData} file). These files are:

\begin{itemize}
  \item \texttt{corrected\_sw} containing seawater data, and
  \item \texttt{corrected\_seds} containing sediments data.
  \item \texttt{all\_data}, containing concatenated seawater and sediments data, with a somewhat reduced set of columns.
\end{itemize}

For most of the analysis, the more limited data frame is used when possible; the \texttt{all\_data} data frame is only used when necessary.

The original versions of these data sets are loaded (via lazy loading) when the package is loaded. Thus, to access the original dataset you may call \texttt{all\_data}, \texttt{corrected\_sw}, or \texttt{corrected\_seds} once the package is loaded.

You may create versions of these data frames based on new underlying databases. To do this, use the function \texttt{read\_data()}. By default, this function will load the database that the paper is based on. Depending on the function arguments, it can be used to read data from an Excel file (which should have the same columns as the Excel file supplied with the paper), or from a different \texttt{.RData} file, if you have extended the databse. For instance, it might be easiest to add data to our database by extending the Microsoft Excel file supplied in the paper's supplemental, and saving the excel file with a new filename. Then, you would read that file into R using

\begin{Schunk}
\begin{Sinput}
> # Read in the modified database
> new_data_list <- read_data(reload.from.xlsx=TRUE,
+                            seds_fn="myPath/mySeds.xlsx",
+                            seds_sheet_name="Sheet1",
+                            sw_fn="myPath/mySw.xlsx",
+                            sw_sheet_name="Sheet1")
\end{Sinput}
\end{Schunk}

Note that \texttt{read\_data()} does some processing of the Excel files in addition to reading them in, so you don't want to load the data simply using \texttt{read.xlsx()}.

Ideally you should only read from Excel files when you have to, because reading Excel files into R is slow (ca. 4 minutes on my machine for both Excel files.) Therefore, once you have read in your modified database, save \texttt{corrected\_sw}, \texttt{corrected\_seds}, and \texttt{all\_data} as \texttt{.RData} files:

\begin{Schunk}
\begin{Sinput}
> save(all_data, file="myPath/all_data_modified.RData")
> save(corrected_sw, file="myPath/corrected_sw_modified.RData")
> save(corrected_seds, file="myPath/corrected_seds_modified.RData")
\end{Sinput}
\end{Schunk}

From now on, you can load your modified database using

\begin{Schunk}
\begin{Sinput}
> new_data_list <- read_data(reload.from.xlsx=FALSE,
+                            all_data_fn="myPath/all_data_modified.RData",
+                            corrected_sw_fn="myPath/ccorrected_sw_modified.RData",
+                            corrected_seds_fn="myPath/corrected_seds_modified")
\end{Sinput}
\end{Schunk}

\subsection{Performing one analysis at a time}
Once the three central data frames are loaded using \texttt{read\_data()}, you can use or modify the functions included with the package to run one analysis at a time, or to write/extend your own analyses. In many cases, it may be simplest to call thes functions by stepping through \texttt{reproduce\_research()}; i.e. by opening the file and running it line-by-line as a script.

The full list of functions included in the package follows. Each is documented separately. Access the documentation for each function using \texttt{?}.

\begin{itemize}
  \item \texttt{AIC\_lik()}: Calculates log-liklihoods using the output of \texttt{AIC}
  \item \texttt{aov\_perm\_test()}: Performs permutation test using Analysis of Variance
  \item \texttt{boxplots\_by\_perm()}: Creates the plots in Fig 3, and calculates relevant statistics
  \item \texttt{intertidal\_yield\_fig()}: Makes a figure of yields of FISH/CARD-FISH for intertidal sediments, analogous to Fig 2
  \item \texttt{lm\_stats()}: A particularly useful function which returns a single-row data frame containing slope, intercept, standard errors, p-values, and more for a linear model of the form \texttt{yvar\textasciitilde xvar}
  \item \texttt{make\_qPCR\_plots()}: Creates figure 4, about qPCR methods
  \item \texttt{make\_sed\_yield\_boxplots()}: Makes boxplots of yield for sediments data (included in the supplemental), split by various methodological factors
  \item \texttt{make\_sw\_yield\_boxplots()}: Makes boxplots of yield for seawater data (included in the supplemental), split by various methodological factors
  \item \texttt{plot\_cell\_vs\_fish()}: Makes Figure 1
  \item \texttt{qPCR\_516\_evaluation()}: Makes plot and calculates summary stats for qPCR using or not using 516 as a primer
  \item \texttt{read\_data()}: Reads and formats cell abundance database
  \item \texttt{reproduce\_research()}: Master function to reproduce all analysis in the paper
  \item \texttt{sed\_bac\_and\_arc\_v\_depth()}: Makes plots and models of sediments bac and arc concentrations vs depth
  \item \texttt{sed\_percent\_arc\_v\_depth()}: Make depth profiles and calculate linear models for sediment percent Archaea vs depth
  \item \texttt{significance\_labeller()}: Create 'significance code' based on p values
  \item \texttt{single\_sw\_yield\_boxplot()}: Function to make generic boxplots as in the supplemental figures
  \item \texttt{sw\_depth\_profiles()}: Creates depth profiles in figures 5 a-c: Bacteria, Archaea, and Also performs breakpoint analysis
  \item \texttt{yield\_by\_core()}: Create a boxplot of yield (total cells by *-FISH relative to total cells by direct count) for each core in the database
\end{itemize}

\section{Appendix: Columns in each data frame}
\begin{longtable}{ccc}
\caption{Columns and data types for the \textbf{all\_data} data frame.} \\
%\begin{tabular}
\hline
column name & data type & notes \\ \hline
paper & factor & abbreviated text name of the reference \\
depth & numeric & depth, m \\
totalcells & numeric & cells per cm\textsuperscript{3} \footnote{When reported in other units (e.g. per gram sediment dry weight), these were adjusted to per cc.}\\
qPCRtotal & numeric & 16s copies per cm\textsuperscript{3} \\
Cell.stain & factor & \\
CARDFISH.Bac.per.cc & numeric & cells per cm\textsuperscript{3} \\
FISH.yield & numeric & *.FISH-counted cells / general-stain-counted cells \\
Fraction.Arc.CARDFISH & numeric & $\text{Archaea} / (\text{Archaea}+\text{Bacteria})$ by CARDFISH \\
Fish.or.CARDFISH & factor & also includes \texttt{"Polyribonucleotide FISH"} \\
Fixative & factor & \\
Bac.permeabilization & factor & \\
Arc.permeabilization & factor & \\
environment & factor & \texttt{"seawater"} or \texttt{"sediments"} \\
qPCRbac & numeric &  \\
qPCRarc & numeric &  \\
Cell.stain.1 & factor & \\
Bac.probe & factor & \\
Arc.probe & factor & \\
core & character & sediment core label \\
qPCR.Bac.per.cc & numeric & copy number of Bacteria per cc by qPCR \\
qPCR.Arc.per.cc & numeric & copy number of Archaea per cc by qPCR \\
qPCRuniversal & numeric & copy number by qPCR using `universal' primers \\
percentqPCR & numeric & fraction (not percent) of Archaea by qPCR \\
SYBR.vs.Taqman & factor & qPCR probe \\
DNA.extraction.procedure & factor & \\
%\end{tabular}
\end{longtable}

\begin{longtable}{lll}%{l >{\raggedright}p{0.75\textwidth} }
\caption{Columns and data types for the \textbf{corrected\_sw} data frame - only listing those columns that are not present in \texttt{all\_data} } \\
\hline
column name & data type & notes \\ \hline
Sample & factor & identifier for samples within the paper\\
Date & factor & mixed formats due to bad Excel entry \\
qPCR.MCG..copies.mL.water. & numeric & \\
Counting.method & factor & \texttt{"Microscope\-eye"} or \texttt{"Microscopy\-automated"}\\
depth\_log10 & numeric & log 10-transformed depth\\
\hline
\end{longtable}

\begin{longtable}{ccc}
\caption{Columns and data types for the \textbf{corrected\_seds} data frame - only listing those columns that are not present in in \texttt{all\_data}} \\
\hline
column name & data type & notes \\
\hline
sulfate & factor & mostly numeric in mM, some text\\
CARDFISH.Arc.nd & logical & were Archaea detected by CARDFISH?\\
Bac.formamide & numeric & concentration formamide for Bacteria\\
Arc.formamide & factor & concentration formamide for Archaea\\
Sonication & factor & sonication protocol \\
Average.cells.per.field & factor & includes text and numbers\\
Filter & factor & filter type\\
Bac.Probe & factor & Bacterial *-FISH probe\\
Arc.Probe & factor & Archaeal *-FISH probe\\
Arc.forward & factor & \\
Arc.reverse & factor & \\
TaqMan.Arc & factor & TaqMan probe for Archaea\\
Bac.forward & factor & Bac.forward \\
Bac.reverse & factor & \\
Taqman.Bac & factor & \\
Universal.forward & factor & \\
Universal.reverse & factor & \\
Taqman.Universal & factor & \\
Arc.standard & factor & qPCR standard, Archaea\\
Bac.standard & factor & qPCR standard, Bacteria\\
Mud.volcano.or.seep. & logical & samples come from a mud volcano or seep\\
Water.depth & numeric & water depth at sediment surface\\
Environment.Type & character & \\
Non.intertidal.marine... & logical & full name is much longer\\
DNA.extraction.efficiency... & factor & full name is much longer\\
Template.DNA.dilution.factor & factor & \\
Uses.516.for.Arc & logical & \\
Uses.349.for.Arc & logical & \\
Uses.806.for.Arc & logical & \\
Uses.331.for.Bac & logical & \\
Uses.340.for.Bac & logical & \\
Uses.515.for.Bac & logical & \\
paperNumber & numeric & numeric label for each paper\\
\end{longtable}
\end{document}


text:
[![Build Status](https://secure.travis-ci.org/graphite-project/whisper.png)](http://travis-ci.org/graphite-project/whisper)

Whisper is one of the components of [Graphite][], and is responsible for
the backend storage of incoming metrics from the network.
Currently [Whisper][] is our stable, supported backend and
[Ceres][] is the work-in-progress future replacement for Whisper.

[Graphite]: https://github.com/graphite-project
[Graphite Web]: https://github.com/graphite-project/graphite-web
[Whisper]: https://github.com/graphite-project/whisper
[Ceres]: https://github.com/graphite-project/ceres

## Overview

Whisper is a fixed-size database, similar in design and purpose to RRD
(round-robin-database). It provides fast, reliable storage of numeric data over
time. Whisper allows for higher resolution (seconds per point) of recent data
to degrade into lower resolutions for long-term retention of historical data.

## Whisper Scripts

rrd2whisper.py
--------------
Convert a rrd file into a whisper (.wsp) file.

```
Usage: rrd2whisper.py rrd_path

Options:
  -h, --help            show this help message and exit
  --xFilesFactor=XFILESFACTOR
                        The xFilesFactor to use in the output file. Defaults
                        to the input RRD's xFilesFactor
  --aggregationMethod=AGGREGATIONMETHOD
                        The consolidation function to fetch from on input and
                        aggregationMethod to set on output. One of: average,
                        last, max, min
```

whisper-create.py
-----------------
Create a new whisper database file.

```
Usage: whisper-create.py path timePerPoint:timeToStore [timePerPoint:timeToStore]*

timePerPoint and timeToStore specify lengths of time, for example:

60:1440      60 seconds per datapoint, 1440 datapoints = 1 day of retention
15m:8        15 minutes per datapoint, 8 datapoints = 2 hours of retention
1h:7d        1 hour per datapoint, 7 days of retention
12h:2y       12 hours per datapoint, 2 years of retention

Options:
  -h, --help            show this help message and exit
  --xFilesFactor=XFILESFACTOR
  --aggregationMethod=AGGREGATIONMETHOD
                        Function to use when aggregating values (average, sum,
                        last, max, min)
  --overwrite
```

whisper-dump.py
---------------
Dump the metadata about a whisper file to stdout.

```
Usage: whisper-dump.py path

Options:
  -h, --help  show this help message and exit
```

whisper-fetch.py
----------------
Fetch all the metrics stored in a whisper file to stdout.

```
Usage: whisper-fetch.py [options] path

Options:
  -h, --help     show this help message and exit
  --from=_FROM   Unix epoch time of the beginning of your requested interval
                 (default: 24 hours ago)
  --until=UNTIL  Unix epoch time of the end of your requested interval
                 (default: now)
  --json         Output results in JSON form
  --pretty       Show human-readable timestamps instead of unix times
```

whisper-info.py
---------------

```
Usage: whisper-info.py path [field]

Options:
  -h, --help  show this help message and exit
```

whisper-merge.py
----------------
Join two existing whisper files together.

```
Usage: whisper-merge.py [options] from_path to_path

Options:
  -h, --help  show this help message and exit
```

whisper-resize.py
-----------------
Change the retention rates of an existing whisper file.

```
Usage: whisper-resize.py path timePerPoint:timeToStore [timePerPoint:timeToStore]*

timePerPoint and timeToStore specify lengths of time, for example:

60:1440      60 seconds per datapoint, 1440 datapoints = 1 day of retention
15m:8        15 minutes per datapoint, 8 datapoints = 2 hours of retention
1h:7d        1 hour per datapoint, 7 days of retention
12h:2y       12 hours per datapoint, 2 years of retention

Options:
  -h, --help            show this help message and exit
  --xFilesFactor=XFILESFACTOR
                        Change the xFilesFactor
  --aggregationMethod=AGGREGATIONMETHOD
                        Change the aggregation function (average, sum, last,
                        max, min)
  --force               Perform a destructive change
  --newfile=NEWFILE     Create a new database file without removing the
                        existing one
  --nobackup            Delete the .bak file after successful execution
  --aggregate           Try to aggregate the values to fit the new archive
                        better. Note that this will make things slower and use
                        more memory.
```

whisper-set-aggregation-method.py
---------------------------------
Change the aggregation method of an existing whisper file.

```
Usage: whisper-set-aggregation-method.py path <average|sum|last|max|min>

Options:
  -h, --help  show this help message and exit
```

whisper-update.py
-----------------
Update a whisper file with 1 or many values, must provide a time stamp with the value.

```
Usage: whisper-update.py [options] path timestamp:value [timestamp:value]*

Options:
  -h, --help  show this help message and exit
```

whisper-diff.py
---------------
Check the differences between whisper files.  Use sanity check before merging.

```
Usage: whisper-diff.py [options] path_a path_b

Options:
  -h, --help      show this help message and exit
  --summary       show summary of differences
  --ignore-empty  skip comparison if either value is undefined
  --columns       print output in simple columns
  --no-headers    do not print column headers
```


text:
$.noConflict();     //  to avoid jQuery
  // Code that uses other library's $ can follow here.
  var meeting_day = '';
  var end_time_clone = '';
  var event;
  jQuery(document).ready(function($) {
    if (!window.console) console = {log: function() {}}; //work around for errors in IE if the console is not open
    end_time_clone = $('#end_time option').clone();
    /*
      Author: shiju@qburst.com
      Description: get events in json format
    */
    getEventsJSON = function(){
      meeting_room = $('#meeting_rooms').val();   //  selected meeting room
      $.ajax({
        url: '/issues.json',
        dataType: 'json',
        data: 'project_id='+project_id+'&cf_5='+meeting_room+'&limit='+50,
        beforeSend: function ( xhr ) {
          showSpinner();
        },
        success: function ( data ) {
          console.log('Get JSON success');
          if(buildEventsJSON(data)){
          $('#calendar').fullCalendar('removeEvents');
          $('#calendar').fullCalendar('addEventSource', eventsJSON);
          $('#calendar').fullCalendar('rerenderEvents');
          hideSpinner();
        }
        }
      });
      return true;
    }

    /*
      Author: shiju@qburst.com
      Description: build events json for fullcalendar
    */
    var buildEventsJSON = function(eventsRawJSON){
      window.console.log('Building Meetings JSON');
      count = eventsRawJSON.issues.length;
      event = eventsRawJSON.issues;
      eventsJSON = [];    //  events to be rendered on fullcalendar
      // building events json for fullcalendar
      for(var i=0; i<count; i++) {
        var eventClassName = '';
        if (isCurrentUser(event[i].author.id)){
          eventClassName ='myEvents';
        }
        var event_id      =event[i].id;
        author_name   =event[i].author.name;
        start_time_arr=event[i].custom_fields[0].value.split(':');
        end_time_arr  =event[i].custom_fields[1].value.split(':');
        meeting_room  =event[i].custom_fields[2].value;
        meeting_day_arr=event[i].custom_fields[3].value.split('-');
        var start_time    = new Date(meeting_day_arr[0],meeting_day_arr[1]-1, meeting_day_arr[2] ,start_time_arr[0], start_time_arr[1]);
        var end_time      = new Date(meeting_day_arr[0],meeting_day_arr[1]-1,meeting_day_arr[2] ,end_time_arr[0],end_time_arr[1]);
        var eventsub ='';
        var repl
        var limit
        if(event[i].subject.length>='36'){
          event[i].subject=stripSubject(event[i].subject,36)+" ...";
        }
        eventsJSON.push({title: event[i].subject,author:author_name, start: start_time,end: end_time,priority:event[i].priority.id, status:event[i].status.id, subject:event[i].subject, starttime: +start_time_arr[0]+':'+start_time_arr[1],endtime: +end_time_arr[0]+':'+end_time_arr[1],event_id:event_id,meeting_day:event[i].custom_fields[3].value,event_author_id: event[i].author.id,className: eventClassName, cache: true, allDay: false});
      }
      return true;
    }

  /*
    Author: shiju@qburst.com
    Description: checking whether event overlaps with exisiting events
  */
    var isOverlapping = function(eventStart, eventEnd) {
      var event_id = $("#event_id") .val();
      var events = $('#calendar').fullCalendar('clientEvents');
      if(events.length == 0){
        return false;
      }
      if ($("#recurCheckbox").is(':checked')){
          var recur = $("input:radio[name=Week]:checked").val();
          if(recur == 5){
            recur_days = parseInt(recur)+2; // adding 2 to accomodate Saturday N Sunday of a week
          }else{
            recur_days = parseInt(recur)+4;  // adding 4 to accomodate Saturday N Sunday of 2 weeks
          }

      }else{
        var recur_days =1;
      }
         for(i in events){
          var temp_meeting_day=meeting_day.split("-")
          if(temp_meeting_day[1].count=1){
            temp_meeting_day[1]="0"+temp_meeting_day[1]
          }
          meeting_book_day  = new Date(temp_meeting_day[0],temp_meeting_day[1]-1,temp_meeting_day[2]);
          if (events[i].meeting_day != undefined){
            var temp_events_meeting_day=events[i].meeting_day.split('-');
            if(temp_events_meeting_day[1].count=1){
              temp_events_meeting_day[1]="0"+temp_events_meeting_day[1];
            }
            event_meeting_day = new Date(temp_events_meeting_day[0],temp_events_meeting_day[1]-1,temp_events_meeting_day[2]);
          }
          if(event_meeting_day != undefined || meeting_book_day != undefined){
            var difference =Math.abs(event_meeting_day - meeting_book_day);
          }
            if (difference != undefined){
            var days =Math.round(difference/(1000*60*60*24))
          }
            if(days >= 0 && days<recur_days){
              eventStartDay =  new Date(eventStart.getTime() + (24 * 60 * 60 * 1000*(days)));
              eventEndDay = new Date(eventEnd.getTime() + (24 * 60 * 60 * 1000*(days)));
              if(event_id == 0){
                console.log('Create')
                // start-time in between any of the events
                if(eventStartDay > events[i].start && eventStartDay < events[i].end){
                  return true;
                }
                //end-time in between any of the events
                if(eventEndDay > events[i].start && eventEndDay < events[i].end){
                  return true;
                }
                //any of the events in between/on the start-time and end-time
                if(eventStartDay <= events[i].start && eventEndDay >= events[i].end){
                  return true;
                }
              }
              else if(event_id != 0 && events[i].event_id != event_id){
                console.log('Update')
                // start-time in between any of the events
                if(eventStartDay > events[i].start && eventStartDay < events[i].end){
                  return true;
                }
                //end-time in between any of the events
                if(eventEndDay > events[i].start && eventEndDay < events[i].end){
                  return true;
                }
                //any of the events in between/on the start-time and end-time
                if(eventStartDay <= events[i].start && eventEndDay >= events[i].end){
                  return true;
                }
              }
            }
      }
      return false;
    }

    /*
      Author: shiju@qburst.com
      Description: stripping the subject text to fit into the calendar event and tooltip
    */
    var stripSubject = function (eventsub,limit){
      var strlen = eventsub.length
      if(strlen > limit)
      {
        return eventsub.substr(0,limit)   //.repl;
      }
      else
      {
        return eventsub;
      }
    }

    /*
      Author: shiju@qburst.com
      Description: checking whether the current user is same as the author of event
    */
    var isCurrentUser = function(event_author_id ){
      var current_user_id = $('#author_id').val();
      if((event_author_id==current_user_id)){
        return true;
      }
      else{
        return false;
      }
    }

    /*
      Author: shiju@qburst.com
      Description: checking whether the event start date is past today
    */
    var isPastDay = function(calDate){
      var current_date = new Date();
      if (calDate <= current_date){
        return true;
      }
      else{
        return false;
      }
    }

    /*
      Author: shiju@qburst.com
      Description: intialising fullcalendar to render events
    */
    var loadCalendar = function() {
      if(getEventsJSON()){
        console.log('Loading Meeting Calendar')
        $('#calendar').fullCalendar({
          allDaySlot: false,
          header: {
            left: 'today prev next',
            center: 'title',
            right: 'agendaWeek,agendaDay'
          },
          axisFormat: 'HH:mm',
          timeFormat: {agenda: 'HH:mm{ - HH:mm}'},
          defaultView: 'agendaWeek',
          editable: false,
          minTime: '8:30am',
          maxTime: '10:00pm',
          weekends: false,
          eventRender: function(event, element) {
              element.qtip({
                content: {
                  // Set the text and title fot the tooltip
                text: '
'+'Booked By: '+event.author+'
Start Time: '+event.starttime+'
End Time: '+event.endtime+'
',
                title: {
                   text:  event.subject, // Give the tooltip a title using each elements text
                  }
                },
                position: {
                  corner: {
                     target: 'bottomMiddle', // Position the tooltip above the link
                     tooltip: 'topMiddle'
                  },
                  adjust: {
                     screen: true // Keep the tooltip on-screen at all times
                  }
                },
                show: {
                  when: 'mouseover',
                  solo: true // Only show one tooltip at a time
                },
                hide: {
                  when: 'mouseout',
                  solo: true // Hide tooltip
                },
                style: {
                  tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
                  border: {
                     width: 0,
                     radius: 4
                  },
                  name: 'cream', // Use the default light style
                  width: 330 // Set the tooltip width
                }
            });
          },
          eventClick: function(calEvent, jsEvent, view) {
            var event_author_id = calEvent.event_author_id;
            isCurrentUser(event_author_id);
            $('input:checkbox').removeAttr('checked');
            meeting_day = calEvent.meeting_day;
            if (isPastDay(calEvent.start)){
              jAlert('You cannot edit past meetings','Info');
              return false;
            }
            else if(!(isCurrentUser(event_author_id))){
              console.log('It is an event created by another user');
              return false;
            }
            else{
              $('#subject').val(calEvent.subject);
              $('#issue_status_id').val(calEvent.status);
              $('#issue_priority_id').val(calEvent.priority);
              $('#event_id').val(calEvent.event_id);
              var x = calEvent.starttime.split(':');
              if(x[0].length== '1'){
              x[0]='0'+x[0];
              calEvent.starttime=x[0]+':'+x[1];
              }
              var y = calEvent.endtime.split(':')
              if(y[0].length=='1'){
              y[0]='0'+y[0];
              calEvent.endtime=y[0]+':'+y[1];
              }
              $('#start_time').val(calEvent.starttime);
              $('#end_time').val(calEvent.endtime);
              $('.saveMeetingModal').dialog({ title: 'Update an Event', modal: true, resizable: false, draggable: false, width: 400, show: 'blind', hide: 'explode'});
              $('.saveMeetingModal').dialog('open');
              $('.recurfield').hide();
              $('#recur_div').hide();
            }
          },
          dayClick: function(date, jsEvent, calEvent) {

              meeting_day = $.fullCalendar.formatDate( date, 'yyyy-MM-dd');
              if (isPastDay(date)){
                jAlert('You cannot book a meeting in past','Info');
                return false;
              }
              else
              {
                // clear field values
                $('#event_id').val(0);
                $('#subject').val('');
                $('#start_time').val('');
                $('#end_time').val('');
                $('input:checkbox').removeAttr('checked');
                // new meeting start time
                var start_time=$.fullCalendar.formatDate( date, 'HH:mm');
                // new meeting end time
                var end_time=$.fullCalendar.formatDate( new Date(date.setHours(date.getHours()+1)), 'HH:mm');
                $('#issue_status_id').val(1);   // Hard coded the status 'New' as default value
                $('#issue_priority_id').val(4); // Hard coded the priority 'Normal' as default value
                $('#start_time').val(start_time);
                $('#end_time').val(end_time);
                $('.saveMeetingModal').dialog({ title: 'Create an Event', modal: true, resizable: false, draggable: false, width: 400, show: 'blind', hide: 'explode'});
                $('.saveMeetingModal').dialog('open');
                $('.recurfield').show();
                $('#Week_5').attr( 'checked', true )
                $('#recur_div').hide();
                setEndTime();
              }
          }
        });
      }
    }
    $('#recurCheckbox').click(function() {
      showHiderecurdiv();
    });

     /*
      Author: shiju@qburst.com
      Description: toggle show and hide of reccur checkbox
    */
    var showHiderecurdiv =function(){
      if ($('#recurCheckbox').is(':checked')){
        $('#recur_div').show('blind', {}, 500);
         var checked_value= $('input:radio[name=Week]:checked').val();
      }else{
        $('#recur_div').hide('blind', {}, 500);
        var checked_value= $('input:radio[name=Week]:checked').val();
        checked_value='';
      }
      return checked_value;
    }

    /*
      Author: shiju@qburst.com
      Description: show spinner
    */
   var  showSpinner = function(){
      $('#loading').show();
    }

    /*
      Author: shiju@qburst.com
      Description: hide spinner
    */
    var hideSpinner = function(){
      $('#loading').hide();
    }

    /*
      Author: shiju@qburst.com
      Description: reload calendar
    */
    var reloadCalendar = function(){
      if(getEventsJSON()){
        console.log('Reload Calender');
      }
    }

    $('#meeting_rooms').change(function() {
      reloadCalendar();
    });

    $('#start_time').change (function() {
      setEndTime();
    });

    /*
      Author: shiju@qburst.com
      Description: set end-time wrt the selected start-time
    */
    var setEndTime = function(){
      $('#end_time').empty().append(end_time_clone);
      var start_time_sel_index = '';
      start_time_sel_index = $('#start_time').prop('selectedIndex')-1;
      for(var j=start_time_sel_index; j>=0; j--){
        $('#end_time option:eq('+j+')').remove();
      }
      $('#end_time option:eq(1)').prop('selected', true);
      return true;
    }

    /*
      Author: shiju@qburst.com
      Description: validation to avaoid special characters in subject field
    */
      var validate = function(){
        var special_char = /[0-9a-zA-Z',-]+/;
        if (special_char.test($('#subject').val())){
          return true;
        }
        return false;
      }

    /*
      Author: shiju@qburst.com
      Description: go-to datepicker
    */
    $('#datepicker').datepicker({
      inline: true,
      minDate: 0, // past days disabled
      onSelect: function(dateText, inst) {
        var goto_date = new Date(dateText);
        $('#calendar').fullCalendar('changeView', 'agendaDay');
        $('#calendar').fullCalendar('gotoDate', goto_date);
      }
    });

    /*
      Author: shiju@qburst.com
      Description: create/update event
    */
    $('#save_meeting').click(function() {

      var start_time = $('#start_time').val();
      var end_time   = $('#end_time').val()

      if ($('#subject').val()==''){
        jAlert('All fields are mandatory','Info');
      }
      else{
        if ($('#recurCheckbox').is(':checked')){
          var checked_value= $('input:radio[name=Week]:checked').val();

        }else{

         var checked_value =1;
        }
        temp_meeting_day = meeting_day.replace(/\-/g,'/');
        var eventStart = new Date(temp_meeting_day+ ' ' + start_time+":00");
        var eventEnd = new Date(temp_meeting_day + ' ' + end_time+":00");
        if (isPastDay(eventStart)){
          jAlert('You cannot update meetings to past','Info');
          return false;
        }
        if(!(isOverlapping(eventStart, eventEnd))){
          if (validate()){
            console.log('No overlapping');
            $('.saveMeetingModal' ).dialog( 'close' );
            //setting the variable for update or create as required
            if($('#event_id').val()==0) {
              var action = 'create';
            }
            else {
              var action ='update';
            }
            $.ajax({
              url: 'meeting_calendars/'+action,
              data: {priority_id:$('#issue_priority_id').val(),
                    author_id:$('#author_id').val(),
                    status_id:$('#issue_status_id').val(),
                    subject:$('#subject').val(),
                    custom_field_values:{'6':meeting_day,'3':start_time, '4':end_time, '5':$('#meeting_rooms').val()},
                    event_id:$('#event_id').val(),
                    recur:checked_value},
              success: function(data){
                $('#event_id').val(0);
                reloadCalendar();
              }
            });
          }
          else {
            jAlert('Please enter a valid subject','Info');
          }
        }
        else {
          jAlert('Meeting room already booked','Alert');
        }
        $('#recur_meeting').val('');
      }
    });

    /*
      Author: shiju@qburst.com
      Description: Save the meeting on stroke of ENTER button
    */
    $('.saveMeetingModal').keypress(function(e) {
      if(e.which == 13) {
        jQuery('#save_meeting').focus().click();
        e.preventDefault();
        return false;
      }
    });

    loadCalendar(); // intial load calendar

  });


text:
namespace NetSpell.SpellChecker.Dictionary.Affix
{
    /// <summary>
    ///		Rule Entry for expanding base words
    /// </summary>
    public class AffixEntry
    {
        private string _AddCharacters = "";
        private int[] _Condition = new int[256];
        private string _StripCharacters = "";

        /// <summary>
        ///     The characters to add to the string
        /// </summary>
        public string AddCharacters
        {
            get { return _AddCharacters; }
            set { _AddCharacters = value; }
        }

        /// <summary>
        ///     The condition to be met in order to add characters
        /// </summary>
        public int[] Condition
        {
            get { return _Condition; }
            set { _Condition = value; }
        }

        /// <summary>
        ///     The characters to remove before adding characters
        /// </summary>
        public string StripCharacters
        {
            get { return _StripCharacters; }
            set { _StripCharacters = value; }
        }

        /// <summary>
        ///     The number of conditions that must be met
        /// </summary>
        public int ConditionCount { get; set; }
    }
}


text:
import _root_.io.gatling.core.scenario.Simulation
import ch.qos.logback.classic.{Level, LoggerContext}
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import org.slf4j.LoggerFactory

import scala.concurrent.duration._

/**
 * Performance test for the ProgrammingExercise entity.
 */
class ProgrammingExerciseGatlingTest extends Simulation {

    val context: LoggerContext = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext]
    // Log all HTTP requests
    //context.getLogger("io.gatling.http").setLevel(Level.valueOf("TRACE"))
    // Log failed HTTP requests
    //context.getLogger("io.gatling.http").setLevel(Level.valueOf("DEBUG"))

    val baseURL = Option(System.getProperty("baseURL")) getOrElse """http://127.0.0.1:8080"""

    val httpConf = http
        .baseURL(baseURL)
        .inferHtmlResources()
        .acceptHeader("*/*")
        .acceptEncodingHeader("gzip, deflate")
        .acceptLanguageHeader("fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3")
        .connectionHeader("keep-alive")
        .userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:33.0) Gecko/20100101 Firefox/33.0")

    val headers_http = Map(
        "Accept" -> """application/json"""
    )

    val headers_http_authenticated = Map(
        "Accept" -> """application/json""",
        "X-XSRF-TOKEN" -> "${xsrf_token}"
    )

    val scn = scenario("Test the ProgrammingExercise entity")
        .exec(http("First unauthenticated request")
        .get("/api/account")
        .headers(headers_http)
        .check(status.is(401))
        .check(headerRegex("Set-Cookie", "XSRF-TOKEN=(.*);[\\s]").saveAs("xsrf_token"))).exitHereIfFailed
        .pause(10)
        .exec(http("Authentication")
        .post("/api/authentication")
        .headers(headers_http_authenticated)
        .formParam("j_username", "admin")
        .formParam("j_password", "admin")
        .formParam("remember-me", "true")
        .formParam("submit", "Login")
        .check(headerRegex("Set-Cookie", "XSRF-TOKEN=(.*);[\\s]").saveAs("xsrf_token"))).exitHereIfFailed
        .pause(1)
        .exec(http("Authenticated request")
        .get("/api/account")
        .headers(headers_http_authenticated)
        .check(status.is(200)))
        .pause(10)
        .repeat(2) {
            exec(http("Get all programmingExercises")
            .get("/api/programming-exercises")
            .headers(headers_http_authenticated)
            .check(status.is(200)))
            .pause(10 seconds, 20 seconds)
            .exec(http("Create new programmingExercise")
            .post("/api/programming-exercises")
            .headers(headers_http_authenticated)
            .body(StringBody("""{"id":null, "baseRepositoryUrl":"SAMPLE_TEXT", "baseBuildPlanId":"SAMPLE_TEXT", "publishBuildPlanUrl":null, "allowOnlineEditor":null}""")).asJSON
            .check(status.is(201))
            .check(headerRegex("Location", "(.*)").saveAs("new_programmingExercise_url"))).exitHereIfFailed
            .pause(10)
            .repeat(5) {
                exec(http("Get created programmingExercise")
                .get("${new_programmingExercise_url}")
                .headers(headers_http_authenticated))
                .pause(10)
            }
            .exec(http("Delete created programmingExercise")
            .delete("${new_programmingExercise_url}")
            .headers(headers_http_authenticated))
            .pause(10)
        }

    val users = scenario("Users").exec(scn)

    setUp(
        users.inject(rampUsers(Integer.getInteger("users", 100)) over (Integer.getInteger("ramp", 1) minutes))
    ).protocols(httpConf)
}


text:
package v1alpha1

const (
	AWSProviderGroupName   = "awsprovider"
	AWSProviderApiVersion  = "v1alpha1"
	AWSClusterProviderKind = "AWSClusterProviderSpec"
	AWSMachineProviderKind = "AWSMachineProviderSpec"

	AzureProviderGroupName   = "azureprovider"
	AzureProviderMachineKind = "AzureMachineProviderSpec"
	AzureProviderClusterKind = "AzureClusterProviderSpec"
	AzureProviderApiVersion  = "v1alpha1"
)


text:
#region Foreign-License

#endregion
using System;
namespace Tcl.Lang
{

    /// <summary> This class implements the built-in "variable" command in Tcl.</summary>

    class VariableCmd : ICommand
    {
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] objv)
        {

            string varName;
            int tail, cp;
            Var var, array;
            TclObject varValue;
            int i;

            for (i = 1; i < objv.Length; i = i + 2)
            {
                // Look up each variable in the current namespace context, creating
                // it if necessary.

                varName = objv[i].ToString();
                Var[] result = Var.LookupVar(interp, varName, null, (TCL.VarFlag.NAMESPACE_ONLY | TCL.VarFlag.LEAVE_ERR_MSG), "define", true, false);
                if (result == null)
                {
                    // FIXME:
                    throw new TclException(interp, "");
                }

                var = result[0];
                array = result[1];

                // Mark the variable as a namespace variable and increment its
                // reference count so that it will persist until its namespace is
                // destroyed or until the variable is unset.

                if ((var.Flags & VarFlags.NAMESPACE_VAR) == 0)
                {
                    var.Flags |= VarFlags.NAMESPACE_VAR;
                    var.RefCount++;
                }

                // If a value was specified, set the variable to that value.
                // Otherwise, if the variable is new, leave it undefined.
                // (If the variable already exists and no value was specified,
                // leave its value unchanged; just create the local link if
                // we're in a Tcl procedure).

                if (i + 1 < objv.Length)
                {
                    // a value was specified
                    varValue = Var.SetVar(interp, objv[i], null, objv[i + 1], (TCL.VarFlag.NAMESPACE_ONLY | TCL.VarFlag.LEAVE_ERR_MSG));

                    if (varValue == null)
                    {
                        // FIXME:
                        throw new TclException(interp, "");
                    }
                }

                // If we are executing inside a Tcl procedure, create a local
                // variable linked to the new namespace variable "varName".

                if ((interp.VarFrame != null) && interp.VarFrame.IsProcCallFrame)
                {

                    // varName might have a scope qualifier, but the name for the
                    // local "link" variable must be the simple name at the tail.
                    //
                    // Locate tail in one pass: drop any prefix after two *or more*
                    // consecutive ":" characters).

                    int len = varName.Length;

                    for (tail = cp = 0; cp < len; )
                    {
                        if (varName[cp++] == ':')
                        {
                            while ((cp < len) && (varName[cp++] == ':'))
                            {
                                tail = cp;
                            }
                        }
                    }

                    // Create a local link "tail" to the variable "varName" in the
                    // current namespace.

                    Var.makeUpvar(interp, null, varName, null, TCL.VarFlag.NAMESPACE_ONLY, varName.Substring(tail), 0);
                }
            }
            return TCL.CompletionCode.RETURN;
        }
    }
}


text:
/**
 *	about.conf.js
 */

(function () {

	'use strict';

	var about = angular.module('about',  []);

	about.config(['$routeProvider', function ($routeProvider) {

		$routeProvider.when('/about/:id?', {
			'templateUrl': 'app/sections/about/about.tpl.html',
			'controller': 'AboutCtrl',
			'active': 'about'
		});
	}]);
}());


text:
@echo off

@cd /d %~dp0
@set JFlexHome=%cd%
@cd ..
@set ParentHome=%cd%

@set JFlexSourceFile=%JFlexHome%\Lexer.jflex
@set TargetDirectory=%ParentHome%\main\java\org\boilit\bsl\core

@rem set JAVA_HOME=D:\Java\jdk7u25
@rem set PATH=.;%JAVA_HOME%\bin;%PATH%
@rem set CLASSPATH=%JAVA_HOME%\lib\tools.jar;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\jre\lib\rt.jar;%CLASSPATH%

@set JFlexJar=%JFlexHome%\jflex-1.4.3.jar
@java -Dfile.encoding=UTF-8 -jar %JFlexJar% -d %TargetDirectory% %JFlexSourceFile%

@pause


text:
import { Component, OnInit } from '@angular/core';
import { switchMap } from "rxjs/operators";
import { Observable } from "rxjs/Observable";

import { ShoppingListService } from "../shopping-list.service";
import { UserService } from "app/user/user.service";

@Component({
  selector: 'shopping-list-master',
  templateUrl: './shopping-list-master.component.html',
  styleUrls: ['./shopping-list-master.component.sass']
})
export class ShoppingListMasterComponent implements OnInit {
  listIds: Observable<string[]>;

  constructor(
    private listService: ShoppingListService,
    private userService: UserService
  ) { }

  ngOnInit() {
    this.listIds = this.userService.userIdSubject.pipe(
      switchMap(userId => this.listService.getIdsOfViewableLists(userId))
    )
  }

  newList() {
    this.listService.newList(this.userService.userId);
  }

}


text:
package com.thoughtworks.go.config.materials;

import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.domain.PersistentObject;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.util.CachedDigestUtils;
import com.thoughtworks.go.util.ListUtil;
import com.thoughtworks.go.util.StringUtil;

import java.util.*;

/**
 * @understands material configuration
 */
public abstract class AbstractMaterial extends PersistentObject implements Material {
    /**
     * CAREFUL!, this should be the same as the one used in migration 47_create_new_materials.sql
     */
    public static final String FINGERPRINT_DELIMITER = "<|>";
    public static final String SQL_CRITERIA_TYPE = "type";
    private static final int TRUNCATED_NAME_MAX_LENGTH = 20;

    protected CaseInsensitiveString name;
    protected String type;
    private Map<String, Object> sqlCriteria;
    private Map<String, Object> attributesForXml;
    private String pipelineUniqueFingerprint;
    protected String fingerprint;

    public AbstractMaterial(String typeName) {
        type = typeName;
    }

    public CaseInsensitiveString getName() {
        return name;
    }

    public final Map<String, Object> getSqlCriteria() {
        if (sqlCriteria == null) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("type", type);
            appendCriteria(map);
            sqlCriteria = Collections.unmodifiableMap(map);
        }
        return sqlCriteria;
    }

    public final Map<String, Object> getAttributesForXml() {
        if (attributesForXml == null) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("type", type);
            appendAttributes(map);
            attributesForXml = Collections.unmodifiableMap(map);
        }
        return attributesForXml;
    }

    public String getFingerprint() {
        if (fingerprint == null) {
            fingerprint = generateFingerprintFromCriteria(getSqlCriteria());
        }
        return fingerprint;
    }

    public String getPipelineUniqueFingerprint() {
        if (pipelineUniqueFingerprint == null) {
            Map<String, Object> basicCriteria = new LinkedHashMap<>(getSqlCriteria());
            appendPipelineUniqueCriteria(basicCriteria);
            pipelineUniqueFingerprint = generateFingerprintFromCriteria(basicCriteria);
        }
        return pipelineUniqueFingerprint;
    }

    private String generateFingerprintFromCriteria(Map<String, Object> sqlCriteria) {
        List<String> list = new ArrayList<>();
        for (Map.Entry<String, Object> criteria : sqlCriteria.entrySet()) {
            list.add(new StringBuilder().append(criteria.getKey()).append("=").append(criteria.getValue()).toString());
        }
        String fingerprint = ListUtil.join(list, FINGERPRINT_DELIMITER);
        // CAREFUL! the hash algorithm has to be same as the one used in 47_create_new_materials.sql
        return CachedDigestUtils.sha256Hex(fingerprint);
    }

    public String getTruncatedDisplayName() {
        String displayName = getDisplayName();
        if (displayName.length() > TRUNCATED_NAME_MAX_LENGTH) {
            StringBuffer buffer = new StringBuffer();
            buffer.append(displayName.substring(0, TRUNCATED_NAME_MAX_LENGTH / 2));
            buffer.append("...");
            buffer.append(displayName.substring(displayName.length() - TRUNCATED_NAME_MAX_LENGTH / 2));
            displayName = buffer.toString();
        }
        return displayName;
    }

    protected abstract void appendCriteria(Map<String, Object> parameters);

    protected abstract void appendAttributes(Map<String,Object> parameters);

    protected abstract void appendPipelineUniqueCriteria(Map<String, Object> basicCriteria);

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

    public String getType() {
        return type;
    }

    public String getShortRevision(String revision) {
        return revision;
    }

    public boolean isSameFlyweight(Material other) {
        return getFingerprint().equals(other.getFingerprint());
    }

    @Override
    public boolean hasSameFingerprint(MaterialConfig materialConfig) {
        return getFingerprint().equals(materialConfig.getFingerprint());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        AbstractMaterial that = (AbstractMaterial) o;

        if (name != null ? !name.equals(that.name) : that.name != null) {
            return false;
        }
        if (type != null ? !type.equals(that.type) : that.type != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (type != null ? type.hashCode() : 0);
        return result;
    }

    @Override public String toString() {
        return String.format("AbstractMaterial{name=%s, type=%s}", name, type);
    }

    protected void resetCachedIdentityAttributes() {
        sqlCriteria = null;
        attributesForXml = null;
        pipelineUniqueFingerprint = null;
    }

    @Override
    public MaterialConfig config() {
        throw new RuntimeException("You need to implement this");
    }

    @Override
    public Map<String, Object> getAttributes(boolean addSecureFields) {
        throw new RuntimeException("You need to implement this");
    }

    protected boolean hasDestinationFolder() {
        return !StringUtil.isBlank(getFolder());
    }

    public boolean supportsDestinationFolder() {
        return false;
    }

    @Override
    public void updateFromConfig(MaterialConfig materialConfig) {
        if(materialConfig instanceof PasswordAwareMaterial) {
            PasswordAwareMaterial passwordConfig = (PasswordAwareMaterial) materialConfig;
            ((PasswordAwareMaterial) this).setPassword(passwordConfig.getPassword());
        }
    }
}


text:
<action>
    <field name="string">Fixed Assets</field>
    <field name="view">multi_view</field>
    <field name="model">account.fixed.asset</field>
    <field name="tabs">[["All",[]],["Pending",[["state","=","pending"]]],["Registered",[["state","=","registered"]]],["Sold and Disposed",[["state","in",["disposed","sold"]]]]]</field>
    <field name="menu">account_menu</field>
    <field name="modes">list,page,form</field>
</action>


text:
@interface DRThemedNavigationController : DRNavigationController
@property (assign) UIStatusBarStyle defaultStatusBarStyle;
@end


text:
package AnyJob::Crontab::Set::Base;

###############################################################################
# Arbitrary set of integers designated by specification string in crontab-based format and some bounded range.
# Specification string is comma-separated list of numbers and ranges (in <min>-<max> form or just '*' character to
# designate entire range). Ranges can also have optional step designated by slash character and number.
# Example: 3,5,8-10,*/5
#
# This class is used as base for all other crontab set classes.
#
# Author:       LightStar
# Created:      25.01.2019
# Last update:  25.01.2019
#

use strict;
use warnings;
use utf8;

use AnyJob::Constants::Functions qw(IDENTITY_FN TRUE_FN);

###############################################################################
# Construct new AnyJob::Crontab::Set::Base object.
#
# Arguments:
#     spec   - specification string in crontab-based format.
#     range  - array of integers used as total range for resulting set.
#     mapper - optional function used to map each value in specification string to corresponding number.
#     filter - optional function used to additionally filter out numbers from set.
# Returns:
#     AnyJob::Crontab::Set::Base object.
#
sub new {
    my $class = shift;
    my %args = @_;
    my $self = bless \%args, $class;

    unless (defined($self->{spec}) and $self->{spec} ne '') {
        require Carp;
        Carp::confess('No specification');
    }

    unless (defined($self->{range}) and ref($self->{range}) eq 'ARRAY' and scalar(@{$self->{range}}) > 0) {
        require Carp;
        Carp::confess('No range');
    }

    unless (defined($self->{mapper})) {
        $self->{mapper} = IDENTITY_FN;
    }

    unless (defined($self->{filter})) {
        $self->{filter} = TRUE_FN;
    }

    $self->init();

    return $self;
}

###############################################################################
# Get set data.
#
# Returns:
#     set data as array of integers.
#
sub getData {
    my $self = shift;
    return $self->{data};
}

###############################################################################
# Initialize set data. Throw exception if it is not possible or set is empty.
#
sub init {
    my $self = shift;

    my $range = $self->{range};
    my $filter = $self->{filter};

    if ($self->{spec} eq '*' and $filter == TRUE_FN) {
        $self->{data} = $range;
        return;
    }

    my %hash;
    my %rangeHash = map {$_ => 1} @{$range};

    foreach my $item (grep {$_ ne ''} split(/\s*,\s*/, $self->{spec})) {
        my ($spec, $step) = $self->parseItem($item);

        if ($spec eq '*') {
            for my $value (@{$range}) {
                if ($value % $step == 0 and $filter->($value)) {
                    $hash{$value} = 1;
                }
            }
        } elsif ($spec =~ /^([^\-]+)-([^\-]+)$/) {
            my ($begin, $end) = ($self->parseValue($1), $self->parseValue($2));
            for my $value ($begin .. $end) {
                if (exists($rangeHash{$value}) and $value % $step == 0 and $filter->($value)) {
                    $hash{$value} = 1;
                }
            }
        } else {
            my $value = $self->parseValue($spec);
            if (exists($rangeHash{$value}) and $filter->($value)) {
                $hash{$value} = 1;
            }
        }
    }

    if (scalar(keys(%hash)) == 0) {
        require Carp;
        Carp::confess('No values');
    }

    $self->{data} = [ sort {$a <=> $b} keys(%hash) ];
}

###############################################################################
# Parse one item from specification string. Throw exception if it is not possible.
#
# Arguments:
#     item - string with just one item in comma-separated input list optionally with step.
# Returns:
#     string with that same item excluding step part.
#     integer step or number '1' if step is absent.
#
sub parseItem {
    my $self = shift;
    my $item = shift;

    my ($spec, $step) = ($item =~ /^([^\/]+)(?:\/(\d+))?$/);

    unless (defined($spec)) {
        require Carp;
        Carp::confess('Wrong specification format');
    }

    if (defined($step)) {
        $step = int($step);
    }
    $step ||= 1;

    return +($spec, $step);
}

###############################################################################
# Parse value from specification string which should be integer number (possibly after mapping).
# Throw exception if it is not the case.
#
# Arguments:
#     value - string with value in specification string.
# Returns:
#     integer value.
#
sub parseValue {
    my $self = shift;
    my $value = shift;

    $value = $self->{mapper}->($value);

    if ($value !~ /^\d+$/) {
        require Carp;
        Carp::confess('Wrong specification format');
    }

    return int($value);
}

1;


text:
package com.navercorp.pinpoint.collector.mapper.grpc.stat;

import com.navercorp.pinpoint.common.server.bo.stat.AgentStatBo;
import com.navercorp.pinpoint.common.server.bo.stat.CpuLoadBo;
import com.navercorp.pinpoint.grpc.trace.PAgentStat;
import com.navercorp.pinpoint.grpc.trace.PCpuLoad;
import org.springframework.stereotype.Component;

/**
 * @author HyunGil Jeong
 */
@Component
public class GrpcCpuLoadBoMapper implements GrpcStatMapper {

    public CpuLoadBo map(final PCpuLoad cpuLoad) {
        final CpuLoadBo cpuLoadBo = new CpuLoadBo();
        cpuLoadBo.setJvmCpuLoad(cpuLoad.getJvmCpuLoad());
        cpuLoadBo.setSystemCpuLoad(cpuLoad.getSystemCpuLoad());
        return cpuLoadBo;
    }

    @Override
    public void map(AgentStatBo.Builder.StatBuilder builder, PAgentStat agentStat) {
        // cpuLoad
        if (agentStat.hasCpuLoad()) {
            final PCpuLoad cpuLoad = agentStat.getCpuLoad();
            final CpuLoadBo cpuLoadBo = this.map(cpuLoad);
            builder.addCpuLoad(cpuLoadBo);
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="author" content="Petri Lehtinen">
  <title>Cube.js Demo</title>
  <meta name="description" content="Cube.js : Rubik's cube solver and scrambler">

  <link rel="stylesheet" href="./css/html5reset-1.6.css">
  <link rel="stylesheet" href="./css/base.css">
  <link rel="stylesheet" href="./css/pygments.css">

cube.js random-state scrambler demo

      This is a simple random state scrambler created with cube.js. After the initialization is complete, click on the "generate random scramble" button to generate a random-state scramble.

      Graphics are generated using Conrad Rider's VisualCube.

      The demo scrambler and its code are presented below. Click here for a standalone page.

The scrambler

      <button>Generate random scramble</button>

The code

      demo.html:

        <!DOCTYPE html>
        <head>
          <style>
            #randomstate { visibility: hidden; }
          </style>
        </head>

        <body>
          <p id="status"></p>
          <p id="randomstate">
            <button>Generate random scramble</button><br>
            <span class="result"></span>
          </p>

          <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
          <script src="/cubejs/lib/cube.js"></script>
          <script src="/cubejs/lib/async.js"></script>
          <script src="demo.js"></script>
        </body>

      demo.js:

        (function() {
        var start, progressHandle;

        var progress = function() {
            // Add a dot each second
            $('#status').text(function(index, text) { return text + '.'; });
        };

        var initialized = function() {
            // Precomputing finished, stop adding dots
            clearInterval(progressHandle);

            // Show the duration of initialization
            var end = new Date,
                duration = (end - start) / 1000;
            $('#status').text('Initialization done in ' + duration + ' seconds.');

            // Show the scrambler
            $('#randomstate').css('visibility', 'visible');
            $('#randomstate button').on('click', generateScramble);
        };

        var generateScramble = function() {
            // Hide the initialization status on first scramble
            $('#status').hide();

            // Generate a scramble
            Cube.asyncScramble(function(alg) {
                var s = alg.replace(/\s+/g, ''),  // remove spaces
                    url = "http://cube.crider.co.uk/visualcube.png?size=150&alg=" + s;
                $('#randomstate .result').html(alg + "<br><img src=\"" + url + "\">");
            });
        };

        $(function() {
            $('#status').text('Initializing');

            // Start measuring time
            start = new Date;

            // Start adding dots
            progressHandle = setInterval(progress, 1000);

            // Start precomputing
            Cube.asyncInit('/cubejs/lib/worker.js', initialized);
        });
        })();


text:
package org.apache.geode.connectors.jdbc.internal.cli;

import java.util.List;

import org.apache.geode.annotations.Experimental;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.connectors.jdbc.internal.JdbcConnectorService;
import org.apache.geode.connectors.jdbc.internal.RegionMappingNotFoundException;
import org.apache.geode.connectors.jdbc.internal.configuration.ConnectorService;
import org.apache.geode.management.cli.CliFunction;
import org.apache.geode.management.internal.cli.functions.CliFunctionResult;

@Experimental
public class AlterMappingFunction extends CliFunction<ConnectorService.RegionMapping> {

  @Override
  public CliFunctionResult executeFunction(FunctionContext<ConnectorService.RegionMapping> context)
      throws Exception {
    JdbcConnectorService service = FunctionContextArgumentProvider.getJdbcConnectorService(context);
    ConnectorService.RegionMapping mapping = context.getArguments();
    ConnectorService.RegionMapping existingMapping =
        service.getMappingForRegion(mapping.getRegionName());
    if (existingMapping == null) {
      throw new RegionMappingNotFoundException(
          "RegionMapping for region " + mapping.getRegionName() + " was not found");
    }

    // action
    ConnectorService.RegionMapping alteredMapping = alterRegionMapping(mapping, existingMapping);
    service.replaceRegionMapping(alteredMapping);

    // output
    return new CliFunctionResult(context.getMemberName(), alteredMapping, null);
  }

  ConnectorService.RegionMapping alterRegionMapping(ConnectorService.RegionMapping regionMapping,
      ConnectorService.RegionMapping existingMapping) {
    String connectionName = getValue(regionMapping.getConnectionConfigName(),
        existingMapping.getConnectionConfigName());
    String table = getValue(regionMapping.getTableName(), existingMapping.getTableName());
    String pdxClassName =
        getValue(regionMapping.getPdxClassName(), existingMapping.getPdxClassName());
    Boolean keyInValue = regionMapping.isPrimaryKeyInValue() == null
        ? existingMapping.isPrimaryKeyInValue() : regionMapping.isPrimaryKeyInValue();

    List<ConnectorService.RegionMapping.FieldMapping> fieldMappings =
        regionMapping.getFieldMapping();
    if (!regionMapping.isFieldMappingModified()) {
      fieldMappings = existingMapping.getFieldMapping();
    }
    ConnectorService.RegionMapping alteredMapping = new ConnectorService.RegionMapping(
        existingMapping.getRegionName(), pdxClassName, table, connectionName, keyInValue);
    alteredMapping.getFieldMapping().addAll(fieldMappings);
    return alteredMapping;
  }

  private String getValue(String newValue, String existingValue) {
    // if newValue is null use the value already in the config
    // if newValue is the empty string, then "unset" it by returning null
    if (newValue == null) {
      return existingValue;
    }
    return newValue.isEmpty() ? null : newValue;
  }
}


text:
class VotesController < ApplicationController
    before_action :require_sign_in

    def up_vote
       update_vote(1)
       redirect_to :back
    end

    def down_vote
       update_vote(-1)
       redirect_to :back
    end

    private

    def update_vote(new_value)
       @post = Post.find(params[:post_id])
       @vote = @post.votes.where(user_id: current_user.id).first

       if @vote
           @vote.update_attribute(:value, new_value)
       else
           @vote = current_user.votes.create(value: new_value, post: @post)
       end
    end
end


text:
package io.undertow.websockets.jsr.test.annotated;

import javax.websocket.DecodeException;
import javax.websocket.EncodeException;
import javax.websocket.EndpointConfig;

/**
 * @author Stuart Douglas
 */
public class EncodableObject {

    private final String value;

    public EncodableObject(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public static class Encoder implements javax.websocket.Encoder.Text<EncodableObject> {

        boolean initalized = false;
        public static volatile boolean destroyed = false;

        @Override
        public String encode(final EncodableObject object) throws EncodeException {
            if (!initalized) {
                return "not initialized";
            }
            return object.value;
        }

        @Override
        public void init(final EndpointConfig config) {
            initalized = true;
        }

        @Override
        public void destroy() {

        }
    }

    public static class Decoder implements javax.websocket.Decoder.Text<EncodableObject> {

        boolean initalized = false;
        public static volatile boolean destroyed = false;

        @Override
        public void init(final EndpointConfig config) {
            initalized = true;
        }

        @Override
        public void destroy() {
            destroyed = true;
        }

        @Override
        public EncodableObject decode(final String s) throws DecodeException {
            if(!initalized) {
                throw new DecodeException(s, "not initialized");
            }
            return new EncodableObject(s);
        }

        @Override
        public boolean willDecode(final String s) {
            return true;
        }
    }
}


text:
layout: post
comments: true
title: "Script para verificar o status da conexão PPPoE"
date: 2008-11-24
tags: [Ubuntu, Linux, Internet, networks, PPPoE, scripts, Shell, portuguese]
---
No meu computador pessoal, o acesso a Internet é através de um link de rádio. A autenticação no provedor utiliza PPPoE. Para configurar a autenticação no Windows XP, basta usar o cliente PPPoE que vem por padrão. No Ubuntu também é muito simples, basta executar o comando `pppoeconf`, e seguir os passos de configuração. Na maioria das perguntas só precisei selecionar a opção default. Fora isso, são solicitados username e senha do provedor. Ao término da configuração, a interface PPP já está configurada, e é ativada automaticamente na inicialização.

Apesar de a configuração acima ter funcionado no Ubuntu, a conexão parava de funcionar com frequência (a cada 20 ou 30 minutos, aproximadamente). Apesar de continuar aparecendo como ativa, eu não conseguia acessar nada. Quando isto ocorria, eu precisava executar o comando `poff` para encerrar a conexão e, em seguida, `pon dsl-provider` para restabelecê-la. A princípio, achei que fosse algum problema do provedor; porém, isso não ocorre no Windows XP.

Encontrei algumas referências a esse problema nos forums do Ubuntu, mas nenhuma solução definitiva. Para resolver, criei um script que verifica periodicamente se a conexão está ativa (na verdade, tenta pingar o site do provedor 3 vezes, aumentando o timeout a cada tentativa). Em caso negativo, executa os comandos `poff` e `pon`, conforme descrito acima, e repete o procedimento. Segue o script abaixo (salvei-o como `/home/guilherme/scripts/internet.sh`):

```sh
#!/bin/bash

cmd_ping="/bin/ping"
cmd_pon="/usr/bin/pon"
cmd_poff="/usr/bin/poff"
provider="dsl-provider"
host="www.radlink.com.br"
frequency="10s"
verbose=0

while [ true ]
do
    ok=0
    for timeout in 1 2 3
    do
        `$cmd_ping -q -c 1 -W $timeout $host > /dev/null 2>&1`
        if [ $? -eq 0 ]
        then
            ok=1
            break
        fi
    done

    if [ $ok -eq 1 ]
    then
        sleep $frequency
        continue
    fi

    `$cmd_poff $provider > /dev/null 2>&1`
    `$cmd_pon $provider > /dev/null 2>&1`
    if [ $? -ne 0 ]
    then
        $verbose && echo "Erro na conexão com o provedor"
        exit 1
    fi

    sleep $frequency
done

exit 0
```

Os parâmetros no início do script definem os paths para os comandos utilizados (`ping`, `pon` e `poff`), o nome do provedor, conforme foi especificado no comando `pppoeconf` (o default é `dsl-provider`), o host que será pingado e a frequência de execução do loop.

Para completar, coloquei este script na inicialização. Primeiro é necessário criar um script shell e salvá-lo no diretório `/etc/init.d` (usei [este artigo](http://articles.slicehost.com/2007/10/17/ubuntu-lts-adding-an-nginx-init-script) como modelo):

```sh
#! /bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/home/guilherme/scripts/internet.sh
PIDFILE=/home/guilherme/scripts/internet.pid
NAME=internetd
DESC="Internet"

test -f $DAEMON || exit 0

set -e

. /lib/lsb/init-functions

case "$1" in
  start)
    log_begin_msg "Starting $DESC: $NAME"
    start-stop-daemon --start --quiet --background -m --pidfile "$PIDFILE" --exec $DAEMON
    log_end_msg $?
    ;;
  stop)
    log_begin_msg "Stopping $DESC: $NAME"
    start-stop-daemon --stop --quiet --pidfile $PIDFILE
    rm -f $PIDFILE
    log_end_msg $?
    ;;

  restart|force-reload)
    log_begin_msg "Restarting $DESC: $NAME"
    if start-stop-daemon --stop --quiet --pidfile $PIDFILE; then
        start-stop-daemon --start --quiet --background -m --pidfile "$PIDFILE" --exec $DAEMON
    fi
    log_end_msg $?
    ;;
  status)
    echo -n "Status of $DESC: "
    if [ ! -r "$PIDFILE" ]; then
        echo "$NAME is not running."
        exit 3
    fi
    if read pid < "$PIDFILE" && ps -p "$pid" > /dev/null 2>&1; then
        echo "$NAME is running."
        exit 0
    else
        echo "$NAME is not running but $PIDFILE exists."
        exit 1
    fi
    ;;
  *)
    N=/etc/init.d/${0##*/}
    echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
    exit 1
    ;;
esac

exit 0
```

Em seguida, dê permissão de execução ao script (salvei o arquivo com o nome `internetd`):

```sh
sudo chmod +x /etc/init.d/internetd
```

Finalmente, para colocar o script na inicialização, o comando é:

```sh
sudo /usr/sbin/update-rc.d -f internetd defaults
```

Caso seja necessário interromper ou reiniciar o script, use o comando `sudo /etc/init.d/internetd start/stop/restart`.

Depois que atualizei o Ubuntu para 8.04 não tive mais esse problema, porém no Ubuntu 7.10 acontecia constantemente. Além disso, este procedimento só é necessário caso o seu ponto de Internet esteja conectado diretamente ao micro, o que era o meu caso na época. Como posteriormente comprei um roteador com Wi-Fi, todo esse procedimento tornou-se desnecessário, pois o próprio roteador passou a fazer a autenticação PPPoE. Para desfazer as configurações, primeiramente retire o script do init.d com o comando:

```sh
sudo /usr/sbin/update-rc.d -f internetd remove
```

Em seguida, remova a interface PPP que foi criada pelo `pppoeconf` editando o arquivo `/etc/network/interfaces` e removendo ou comentando as linhas correspondentes a essa interface. No meu caso, as linhas eram as seguintes:

```sh
auto dsl-provider
iface dsl-provider inet ppp
pre-up /sbin/ifconfig eth0 up # line maintained by pppoeconf
provider dsl-provider
```

**UPDATE:** os scripts acima estão disponíveis no [meu GitHub](http://github.com/ggarnier/pppoe-connection).


text:
package org.nextime.ion.backoffice.action.resource;

import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.nextime.ion.backoffice.action.BaseAction;
import org.nextime.ion.backoffice.bean.ResourceXmlBean;
import org.nextime.ion.backoffice.bean.Resources;
import org.nextime.ion.common.ResourceServlet;

public class ViewResourceAction extends BaseAction {

    public ActionForward perform(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        // check if user is correctly logged
        checkUser(request);

        // retrieve resources selected
        String id = request.getSession().getAttribute("selectedResources") + "";
        String path = null;
        try {
            ResourceXmlBean bean = Resources.getResourceXmlBean(servlet, id);
            path = bean.getDirectory();
        } catch (Exception e) {
            throw new ServletException(e);
        }

        String realPath = servlet.getServletContext().getRealPath("/");
        File resources = new File(realPath, ResourceServlet.relativePath);
        File tresources = new File(resources, path);

        File[] files = tresources.listFiles();
        Vector mfiles = new Vector();
        for (int i = 0; i < files.length; i++) {
            mfiles.add(new org.nextime.ion.backoffice.bean.File(files[i]));
        }

        request.setAttribute("files", mfiles);

        // Forward to the next page
        return (mapping.findForward("view"));

    }

}