text:
module Spree
  class Taxonomy < Spree::Base
    acts_as_list

    validates :name, presence: true

    has_many :taxons, inverse_of: :taxonomy
    has_one :root, -> { where parent_id: nil }, class_name: "Spree::Taxon", dependent: :destroy

    after_create :set_root
    after_save :set_root_taxon_name

    default_scope { order("#{self.table_name}.position, #{self.table_name}.created_at") }

    private
      def set_root
        self.root ||= Taxon.create!(taxonomy_id: id, name: name)
      end

      def set_root_taxon_name
        root.update_attributes(name: name)
      end
  end
end


text:
require 'tww/client'

module TWW
  class Testing < Client
    attr_reader :sent

    def initialize(config)
      super
      @sent = []
    end

    def clear!
      sent.clear
    end

    def size
      sent.size
    end

    def deliver(phone, message, extras = {})
      request(phone, message, extras)
    end

    def call(phone, message, extras = {})
      request(phone, message, extras)
    end

    private

    def request(phone, message, _extras)
      Response.parse("<string>#{status(phone)}</string>").tap do |response|
        sent.push(phone: phone, message: message, response: response)
      end
    end

    def status(phone)
      phone =~ /^\d{10,}$/ ? 'OK' : 'NOK'
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import _ from 'underscore';

import {Object} from 'pageflow/ui';

export const CommonPageConfigurationTabs = Object.extend({
  initialize: function() {
    this.configureFns = {};
  },

  register: function(name, configureFn) {
    this.configureFns[name] = configureFn;
  },

  apply: function(configurationEditorView) {
    _.each(this.configureFns, function(configureFn, name) {
      configurationEditorView.tab(name, function() {
        configureFn.call(prefixInputDecorator(name, this));
      });
    });

    function prefixInputDecorator(name, dsl) {
      return {
        input: function(propertyName, view, options) {
          return dsl.input(name + '_' + propertyName, view, options);
        }
      };
    }
  }
});


text:
#include "ieee80211_radiotap.h"

/* Radiotap header iteration
 *   implemented in net/wireless/radiotap.c
 *   docs in Documentation/networking/radiotap-headers.txt
 */
/**
 * struct ieee80211_radiotap_iterator - tracks walk thru present radiotap args
 * @rtheader: pointer to the radiotap header we are walking through
 * @max_length: length of radiotap header in cpu byte ordering
 * @this_arg_index: IEEE80211_RADIOTAP_... index of current arg
 * @this_arg: pointer to current radiotap arg
 * @arg_index: internal next argument index
 * @arg: internal next argument pointer
 * @next_bitmap: internal pointer to next present u32
 * @bitmap_shifter: internal shifter for curr u32 bitmap, b0 set == arg present
 */

struct ieee80211_radiotap_iterator {
	struct ieee80211_radiotap_header *rtheader;
	int max_length;
	int this_arg_index;
    uint8_t *this_arg;

	int arg_index;
    uint8_t *arg;
	__le32 *next_bitmap;
    uint32_t bitmap_shifter;
};

extern int ieee80211_radiotap_iterator_init(
   struct ieee80211_radiotap_iterator *iterator,
   struct ieee80211_radiotap_header *radiotap_header,
   int max_length);

extern int ieee80211_radiotap_iterator_next(
   struct ieee80211_radiotap_iterator *iterator);


text:
date: 2015-07-28
layout: post
title: VEGAS accepted to IEEE TKDE as a regular paper
thread: 4
categories: News
tags: [vegas]
excerpt:
---

Lei Shi, Hanghang Tong, Jie Tang and Chuang Lin, " VEGAS: Visual influEnce GrAph Summarization on Citation Networks", accepted by *IEEE Transactions on Knowledge and Data Engineering*.[[pdf](http://lcs.ios.ac.cn/~shil/paper/TKDE_2015.pdf)][[video](http://lcs.ios.ac.cn/~shil/video/VEGAS_demo.mp4)]


text:
// Problem 1. Leap year

// Write a program that reads a year from the console and checks whether it is a leap one.
// Use System.DateTime.

namespace P01_LeapYear
{
    using System;

    class LeapYear
    {
        static void Main()
        {
            Console.Write("Please enter an year: ");
            int input = int.Parse(Console.ReadLine());
            if (input % 4 == 0)
                Console.WriteLine("This year is leap.");
            else Console.WriteLine("This year isn't leap.");
        }
    }
}


text:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["ReactLazyCache"] = factory();
	else
		root["ReactLazyCache"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

	var _lazyCache = __webpack_require__(1);

	var _lazyCache2 = _interopRequireDefault(_lazyCache);

	exports['default'] = _lazyCache2['default'];
	module.exports = exports['default'];

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;
	exports['default'] = lazyCache;

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

	var _deepEqual = __webpack_require__(2);

	var _deepEqual2 = _interopRequireDefault(_deepEqual);

	function lazyCache(component, calculators) {
	  var allProps = [];
	  var cache = {};
	  var api = {};
	  var uncache = function uncache(changedProp) {
	    Object.keys(cache).forEach(function (key) {
	      if (~cache[key].props.indexOf(changedProp)) {
	        delete cache[key].value;
	        uncache(key);
	      }
	    });
	  };

	  Object.keys(calculators).forEach(function (key) {
	    var fn = calculators[key].fn;
	    var props = calculators[key].params;
	    props.forEach(function (param) {
	      if (! ~allProps.indexOf(param)) {
	        allProps.push(param);
	      }
	    });
	    cache[key] = { props: props };
	    Object.defineProperty(api, key, {
	      get: function get() {
	        var cached = cache[key];
	        if (cached && cached.value !== undefined) {
	          return cached.value;
	        }
	        var params = props.map(function (prop) {
	          return component.props[prop] || api[prop];
	        });
	        var value = fn.apply(undefined, params);
	        cache[key] = { props: props, value: value };
	        return value;
	      }
	    });
	  });
	  api.componentWillReceiveProps = function (nextProps) {
	    var diffProps = [];
	    allProps.forEach(function (prop) {
	      if (!_deepEqual2['default'](component.props[prop], nextProps[prop])) {
	        diffProps.push(prop);
	      }
	    });
	    diffProps.forEach(uncache);
	  };
	  return api;
	}

	module.exports = exports['default'];

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	var pSlice = Array.prototype.slice;
	var objectKeys = __webpack_require__(4);
	var isArguments = __webpack_require__(3);

	var deepEqual = module.exports = function (actual, expected, opts) {
	  if (!opts) opts = {};
	  // 7.1. All identical values are equivalent, as determined by ===.
	  if (actual === expected) {
	    return true;

	  } else if (actual instanceof Date && expected instanceof Date) {
	    return actual.getTime() === expected.getTime();

	  // 7.3. Other pairs that do not both pass typeof value == 'object',
	  // equivalence is determined by ==.
	  } else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') {
	    return opts.strict ? actual === expected : actual == expected;

	  // 7.4. For all other Object pairs, including Array objects, equivalence is
	  // determined by having the same number of owned properties (as verified
	  // with Object.prototype.hasOwnProperty.call), the same set of keys
	  // (although not necessarily the same order), equivalent values for every
	  // corresponding key, and an identical 'prototype' property. Note: this
	  // accounts for both named and indexed properties on Arrays.
	  } else {
	    return objEquiv(actual, expected, opts);
	  }
	}

	function isUndefinedOrNull(value) {
	  return value === null || value === undefined;
	}

	function isBuffer (x) {
	  if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
	  if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
	    return false;
	  }
	  if (x.length > 0 && typeof x[0] !== 'number') return false;
	  return true;
	}

	function objEquiv(a, b, opts) {
	  var i, key;
	  if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
	    return false;
	  // an identical 'prototype' property.
	  if (a.prototype !== b.prototype) return false;
	  //~~~I've managed to break Object.keys through screwy arguments passing.
	  //   Converting to array solves the problem.
	  if (isArguments(a)) {
	    if (!isArguments(b)) {
	      return false;
	    }
	    a = pSlice.call(a);
	    b = pSlice.call(b);
	    return deepEqual(a, b, opts);
	  }
	  if (isBuffer(a)) {
	    if (!isBuffer(b)) {
	      return false;
	    }
	    if (a.length !== b.length) return false;
	    for (i = 0; i < a.length; i++) {
	      if (a[i] !== b[i]) return false;
	    }
	    return true;
	  }
	  try {
	    var ka = objectKeys(a),
	        kb = objectKeys(b);
	  } catch (e) {//happens when one is a string literal and the other isn't
	    return false;
	  }
	  // having the same number of owned properties (keys incorporates
	  // hasOwnProperty)
	  if (ka.length != kb.length)
	    return false;
	  //the same set of keys (although not necessarily the same order),
	  ka.sort();
	  kb.sort();
	  //~~~cheap key test
	  for (i = ka.length - 1; i >= 0; i--) {
	    if (ka[i] != kb[i])
	      return false;
	  }
	  //equivalent values for every corresponding key, and
	  //~~~possibly expensive deep test
	  for (i = ka.length - 1; i >= 0; i--) {
	    key = ka[i];
	    if (!deepEqual(a[key], b[key], opts)) return false;
	  }
	  return typeof a === typeof b;
	}

/***/ },
/* 3 */
/***/ function(module, exports) {

	var supportsArgumentsClass = (function(){
	  return Object.prototype.toString.call(arguments)
	})() == '[object Arguments]';

	exports = module.exports = supportsArgumentsClass ? supported : unsupported;

	exports.supported = supported;
	function supported(object) {
	  return Object.prototype.toString.call(object) == '[object Arguments]';
	};

	exports.unsupported = unsupported;
	function unsupported(object){
	  return object &&
	    typeof object == 'object' &&
	    typeof object.length == 'number' &&
	    Object.prototype.hasOwnProperty.call(object, 'callee') &&
	    !Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
	    false;
	};

/***/ },
/* 4 */
/***/ function(module, exports) {

	exports = module.exports = typeof Object.keys === 'function'
	  ? Object.keys : shim;

	exports.shim = shim;
	function shim (obj) {
	  var keys = [];
	  for (var key in obj) keys.push(key);
	  return keys;
	}

/***/ }
/******/ ])
});
;


text:
START_ATF_NAMESPACE
    typedef tagVARDESC *LPVARDESC;
END_ATF_NAMESPACE


text:
import sys

if sys.version_info < (3, 5, 2):
    raise SystemExit('ERROR: Tried to install Meson with an unsupported Python version: \n{}'
                     '\nMeson requires Python 3.5.2 or greater'.format(sys.version))

from mesonbuild.coredata import version
from setuptools import setup

# On windows, will create Scripts/meson.exe and Scripts/meson-script.py
# Other platforms will create bin/meson
entries = {'console_scripts': ['meson=mesonbuild.mesonmain:main']}
packages = ['mesonbuild',
            'mesonbuild.ast',
            'mesonbuild.backend',
            'mesonbuild.cmake',
            'mesonbuild.compilers',
            'mesonbuild.compilers.mixins',
            'mesonbuild.dependencies',
            'mesonbuild.modules',
            'mesonbuild.scripts',
            'mesonbuild.templates',
            'mesonbuild.wrap']
package_data = {
    'mesonbuild.dependencies': ['data/CMakeLists.txt', 'data/CMakeListsLLVM.txt', 'data/CMakePathInfo.txt'],
    'mesonbuild.cmake': ['data/run_ctgt.py', 'data/preload.cmake'],
}
data_files = []
if sys.platform != 'win32':
    # Only useful on UNIX-like systems
    data_files = [('share/man/man1', ['man/meson.1']),
                  ('share/polkit-1/actions', ['data/com.mesonbuild.install.policy'])]

if __name__ == '__main__':
    setup(name='meson',
          version=version,
          packages=packages,
          package_data=package_data,
          entry_points=entries,
          data_files=data_files,)


text:
package com.google.api.ads.adwords.jaxws.v201601.cm;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Gets ad group level criterion bid modifiers.
 *
 *             @param selector The selector specifying the {@link AdGroupBidModifier}s to return.
 *             @return A list of ad group bid modifiers.
 *             @throws ApiException when there is at least one error with the request.
 *
 *
 *
Java class for get element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="get">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element name="selector" type="{https://adwords.google.com/api/adwords/cm/v201601}Selector" minOccurs="0"/>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "selector"
})
@XmlRootElement(name = "get")
public class AdGroupBidModifierServiceInterfaceget {

    protected Selector selector;

    /**
     * Gets the value of the selector property.
     *
     * @return
     *     possible object is
     *     {@link Selector }
     *
     */
    public Selector getSelector() {
        return selector;
    }

    /**
     * Sets the value of the selector property.
     *
     * @param value
     *     allowed object is
     *     {@link Selector }
     *
     */
    public void setSelector(Selector value) {
        this.selector = value;
    }

}


text:
[![GoDoc](https://godoc.org/github.com/docker/libkv?status.png)](https://godoc.org/github.com/docker/libkv)
[![Build Status](https://travis-ci.org/docker/libkv.svg?branch=master)](https://travis-ci.org/docker/libkv)
[![Coverage Status](https://coveralls.io/repos/docker/libkv/badge.svg)](https://coveralls.io/r/docker/libkv)

`libkv` provides a `Go` native library to store metadata.

The goal of `libkv` is to abstract common store operations for multiple distributed and/or local Key/Value store backends.

For example, you can use it to store your metadata or for service discovery to register machines and endpoints inside your cluster.

You can also easily implement a generic *Leader Election* on top of it (see the [docker/leadership](https://github.com/docker/leadership) repository).

As of now, `libkv` offers support for `Consul`, `Etcd`, `Zookeeper` (**Distributed** store) and `BoltDB` (**Local** store).

## Usage

`libkv` is meant to be used as an abstraction layer over existing distributed Key/Value stores. It is especially useful if you plan to support `consul`, `etcd` and `zookeeper` using the same codebase.

It is ideal if you plan for something written in Go that should support:

- A simple metadata storage, distributed or local
- A lightweight discovery service for your nodes
- A distributed lock mechanism

You can find examples of usage for `libkv` under in `docs/examples.go`. Optionally you can also take a look at the `docker/swarm` or `docker/libnetwork` repositories which are using `docker/libkv` for all the use cases listed above.

## Supported versions

`libkv` supports:
- Consul versions >= `0.5.1` because it uses Sessions with `Delete` behavior for the use of `TTLs` (mimics zookeeper's Ephemeral node support), If you don't plan to use `TTLs`: you can use Consul version `0.4.0+`.
- Etcd versions >= `2.0` because it uses the new `coreos/etcd/client`, this might change in the future as the support for `APIv3` comes along and adds mor capabilities.
- Zookeeper versions >= `3.4.5`. Although this might work with previous version but this remains untested as of now.
- Boltdb, which shouldn't be subject to any version dependencies.

## Interface

A **storage backend** in `libkv` should implement (fully or partially) this interface:

```go
type Store interface {
	Put(key string, value []byte, options *WriteOptions) error
	Get(key string) (*KVPair, error)
	Delete(key string) error
	Exists(key string) (bool, error)
	Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error)
	WatchTree(directory string, stopCh <-chan struct{}) (<-chan []*KVPair, error)
	NewLock(key string, options *LockOptions) (Locker, error)
	List(directory string) ([]*KVPair, error)
	DeleteTree(directory string) error
	AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error)
	AtomicDelete(key string, previous *KVPair) (bool, error)
	Close()
}
```

## Compatibility matrix

Backend drivers in `libkv` are generally divided between **local drivers** and **distributed drivers**. Distributed backends offer enhanced capabilities like `Watches` and/or distributed `Locks`.

Local drivers are usually used in complement to the distributed drivers to store informations that only needs to be available locally.

| Calls                 |   Consul   |  Etcd  |  Zookeeper  |  BoltDB  |
|-----------------------|:----------:|:------:|:-----------:|:--------:|
| Put                   |     X      |   X    |      X      |    X     |
| Get                   |     X      |   X    |      X      |    X     |
| Delete                |     X      |   X    |      X      |    X     |
| Exists                |     X      |   X    |      X      |    X     |
| Watch                 |     X      |   X    |      X      |          |
| WatchTree             |     X      |   X    |      X      |          |
| NewLock (Lock/Unlock) |     X      |   X    |      X      |          |
| List                  |     X      |   X    |      X      |    X     |
| DeleteTree            |     X      |   X    |      X      |    X     |
| AtomicPut             |     X      |   X    |      X      |    X     |
| Close                 |     X      |   X    |      X      |    X     |

## Limitations

Distributed Key/Value stores often have different concepts for managing and formatting keys and their associated values. Even though `libkv` tries to abstract those stores aiming for some consistency, in some cases it can't be applied easily.

Please refer to the `docs/compatibility.md` to see what are the special cases for cross-backend compatibility.

Other than those special cases, you should expect the same experience for basic operations like `Get`/`Put`, etc.

Calls like `WatchTree` may return different events (or number of events) depending on the backend (for now, `Etcd` and `Consul` will likely return more events than `Zookeeper` that you should triage properly). Although you should be able to use it successfully to watch on events in an interchangeable way (see the **docker/leadership** repository or the **pkg/discovery/kv** package in **docker/docker**).

## TLS

Only `Consul` and `etcd` have support for TLS and you should build and provide your own `config.TLS` object to feed the client. Support is planned for `zookeeper`.

##Roadmap

- Make the API nicer to use (using `options`)
- Provide more options (`consistency` for example)
- Improve performance (remove extras `Get`/`List` operations)
- Better key formatting
- New backends?

##Contributing

Want to hack on libkv? [Docker's contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) apply.

##Copyright and license

Copyright © 2014-2016 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. The README.md file, and files in the "docs" folder are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file "LICENSE.docs". You may obtain a duplicate copy of the same license, titled CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/.


text:
cd

(change directory)

There are 2 other ways that we could have gotten to our home directory...what are they?


text:
namespace wtaf {
namespace net {

Poller::Poller(uint32 num)
{
    m_scheduler.reset(new wtaf::task::Scheduler(num));

    for(uint32 i = 0; i < num; ++i)
    {
        auto *poller_task = new Poller_Task(i);
        m_poller_tasks.push_back(poller_task);
        m_scheduler->schedule_task(poller_task);
    }
}

void Poller::start()
{
    m_scheduler->start();
}

void Poller::wait()
{
    m_scheduler->wait();

    for(auto poll_task : m_poller_tasks)
    {
        delete poll_task;
    }
}

void Poller::register_connection(std::shared_ptr<Connection> connection)
{
    static auto num = m_poller_tasks.size();
    m_poller_tasks[connection->id() % num]->register_connection(connection);
}

}
}


text:
from os import linesep
from extension import Sanitize, CmdRun
from extension import ToolKit, Constants
from extension import ParamHandle as Param

# Spawn Instances
p = Param()                       # <class> Parameter manipulation
real_escape_string = Sanitize()   # <class> Escape Routines
toolkit = ToolKit()               # <class> Misc. functions
params = p.list()                 # <dict>   Input params list
run = CmdRun()                    # <class> Runs the query

# ************************************
# *  DEFINE PARAMETERS AND VALIDATE  *
# ************************************
sanitized_arguement = {} # The actual API params we pass to psql

param = "role"
role = Param()
role.value = params[param]
role.name = param
role.max_length = Constants.POSTGRES_NAMEDATA_LEN
role.require = True
role.sanitizier = "sql"
sanitized_arguement[param] = role.get()

param = "password"
password = Param()
password.value = params[param]
password.name = param
password.max_length = Constants.POSTGRES_NAMEDATA_LEN
password.require = True
password.sanitizier = "sql"
sanitized_arguement[param] = password.get()

param = "createrole"
sql_when_true = " {verb} ".format(verb=param.upper())
sql_when_false = " NO{verb} ".format(verb=param.upper())
createrole = Param()
createrole.value = params[param]
createrole.name = param
createrole.max_length = Constants.POSTGRES_NAMEDATA_LEN
createrole.sanitizier = "sql"
createrole.convert_to_bool(sql_when_true, sql_when_false, sql_when_false)
sanitized_arguement[param] = createrole.get()

param = "createuser"
sql_when_true = " {verb} ".format(verb=param.upper())
sql_when_false = " NO{verb} ".format(verb=param.upper())
createuser = Param()
createuser.value = params[param]
createuser.name = param
createuser.max_length = Constants.POSTGRES_NAMEDATA_LEN
createuser.sanitizier = "sql"
createuser.convert_to_bool(sql_when_true, sql_when_false, sql_when_false)
sanitized_arguement[param] = createuser.get()

param = "createdb"
sql_when_true = " {verb} ".format(verb=param.upper())
sql_when_false = " NO{verb} ".format(verb=param.upper())
createdb = Param()
createdb.value = params[param]
createdb.name = param
createdb.max_length = Constants.POSTGRES_NAMEDATA_LEN
createdb.sanitizier = "sql"
createdb.convert_to_bool(sql_when_true, sql_when_false, sql_when_false)
sanitized_arguement[param] = createdb.get()

param = "inherit"
sql_when_true = " {verb} ".format(verb=param.upper())
sql_when_false = " NO{verb} ".format(verb=param.upper())
inherit = Param()
inherit.value = params[param]
inherit.name = param
inherit.max_length = Constants.POSTGRES_NAMEDATA_LEN
inherit.sanitizier = "sql"
inherit.convert_to_bool(sql_when_true, sql_when_false, sql_when_false)
sanitized_arguement[param] = inherit.get()

param = "login"
sql_when_true = " {verb} ".format(verb=param.upper())
sql_when_false = " NO{verb} ".format(verb=param.upper())
login = Param()
login.value = params[param]
login.name = param
login.max_length = Constants.POSTGRES_NAMEDATA_LEN
login.sanitizier = "sql"
login.convert_to_bool(sql_when_true, sql_when_false, sql_when_false)
sanitized_arguement[param] = login.get()

param = "encrypted"
sql_when_true = " {verb} ".format(verb=param.upper())
sql_when_false = " UN{verb} ".format(verb=param.upper())
encrypted = Param()
encrypted.value = params[param]
encrypted.name = param
encrypted.max_length = Constants.POSTGRES_NAMEDATA_LEN
encrypted.sanitizier = "sql"
encrypted.convert_to_bool(sql_when_true, sql_when_false, sql_when_false)
sanitized_arguement[param] = encrypted.get()

param = "rolename"
sql_when_true = " IN ROLE {rolename} ".format(rolename=params[param])
sql_when_false = ""
rolename = Param()
rolename.value = params[param]
rolename.name = param
rolename.max_length = Constants.POSTGRES_NAMEDATA_LEN
rolename.sanitizier = "sql"
rolename.set_value_if_defined(sql_when_true, sql_when_false)
sanitized_arguement[param] = rolename.get()

param = "groupname"
sql_when_true = " IN GROUP {groupname} ".format(groupname=params[param])
sql_when_false = ""
groupname = Param()
groupname.value = params[param]
groupname.name = param
groupname.max_length = Constants.POSTGRES_NAMEDATA_LEN
groupname.sanitizier = "sql"
groupname.set_value_if_defined(sql_when_true, sql_when_false)
sanitized_arguement[param] = groupname.get()

param = "connection_limit"
connection_limit = Param()
connection_limit.value = params[param]
connection_limit.name = param
connection_limit.max_length = 3
connection_limit.sanitizier = "sql"
sanitized_arguement[param] = connection_limit.get()

param = "connection_limit_bust"
connection_limit_bust = Param()
connection_limit_bust.value = params[param]
connection_limit_bust.name = param
connection_limit_bust.sanitizier = "sql"
# Set to True is defined for bool comparisons
connection_limit_bust.set_value_if_defined(True)
sanitized_arguement[param] = connection_limit_bust.get()

# Handling connection limit parsing requires advanced work
#  While imposing limits and limit busting...
thisparam = Param()  # Using the parameter instance tools for validation.
if thisparam.is_nil(sanitized_arguement['connection_limit']):
    # If no input, we plan on just setting 10 sockets.
    connection_limit = 10
elif sanitized_arguement['connection_limit_bust']:
    # Limit busting has been toggled
    if int(sanitized_arguement['connection_limit']) > Constants.POSTGRES_MAXIMUM_CONNECTION_LIMIT:
        # If the proposed limit is not beyond the POSTGRES_MAXIMUM_CONNECTION_LIMIT, stop
        # We expect a smaller value.
        msg = "value <{max}".format(
            max=Constants.POSTGRES_MAXIMUM_CONNECTION_LIMIT)
        thisparam.raise_error(
            keyname='connection_limit',
            value=sanitized_arguement['connection_limit'],
            expected_msg=msg
        )
    # Set the busted limit
    connection_limit = sanitized_arguement['connection_limit']
else:
    # User-submitted connection limit (no limit busting)
    if int(sanitized_arguement['connection_limit']) > Constants.POSTGRES_CONNECTION_LIMIT:
        # If the proposed limit is beyond the POSTGRES_CONNECTION_LIMIT, stop
        # We expect a smaller value.
        msg = "value <{max}".format(max=Constants.POSTGRES_CONNECTION_LIMIT)
        thisparam.raise_error(
            keyname='connection_limit',
            value=sanitized_arguement['connection_limit'],
            expected_msg=msg
        )
    # Set the requested limit
    connection_limit = sanitized_arguement['connection_limit']
arg_connlimit = " CONNECTION LIMIT {max} ".format(max=connection_limit)

# ******************
# *  SQL SENTENCE  *
# ******************
clean_sql = ("BEGIN; CREATE ROLE {username} WITH {connection_limit}{createuser}"
             "{createrole}{createdb}{inherit}{login}{encrypted} PASSWORD '{password}'"
             " {inrole}{ingroup}; END;"
             ).format(
    username=real_escape_string.sql(sanitized_arguement['role']),
    password=real_escape_string.sql(sanitized_arguement['password']),
    createuser=real_escape_string.sql(sanitized_arguement['createuser']),
    createrole=real_escape_string.sql(sanitized_arguement['createrole']),
    createdb=real_escape_string.sql(sanitized_arguement['createdb']),
    inherit=real_escape_string.sql(sanitized_arguement['inherit']),
    login=real_escape_string.sql(sanitized_arguement['login']),
    connection_limit=real_escape_string.sql(arg_connlimit),
    encrypted=real_escape_string.sql(sanitized_arguement['encrypted']),
    inrole=real_escape_string.sql(sanitized_arguement['rolename']),
    ingroup=real_escape_string.sql(sanitized_arguement['groupname']),
)
# Fail if SQL overruns 2000 bytes
toolkit.fail_beyond_maxlength(maxlength=2000, string=clean_sql)
sql_code = toolkit.write_temp(clean_sql)

# ****************
# *  SQL RUNNER  *
# ****************
output = run.sql(sql_code)

# **********************
# *  OUTPUT PROCESSOR  *
# **********************
print(output)
exitcode = 0
error_scenario_1 = False
error_scenario_2 = False
error_scenario_3 = False
error_scenario_4 = False
error_scenario_5 = False

# Parse Output
for line in output.split(linesep):
    if ("ERROR:" in line) and (" role " in line) and ("already exists" in line):
        toolkit.print_stderr(line)
        error_scenario_1 = True
        exitcode = 1  # Parse Errors should flag an API error code.
    if (line == "ROLLBACK") or ("transaction is aborted, commands ignored" in line):
        toolkit.print_stderr(line)
        error_scenario_2 = True
        exitcode = 1  # Rollbacks should flag an API error code.
    if ("psql:/tmp/" in line) and (" ERROR:  " in line):
        toolkit.print_stderr(line)
        error_scenario_3 = True
        exitcode = 1  # Parse Errors should flag an API error code.
    if " FATAL: " in line:
        toolkit.print_stderr(line)
        error_scenario_4 = True
        exitcode = 1  # Parse Errors should flag an API error code.
    if "syntax error" in line and "ERROR" in line:
        toolkit.print_stderr(line)
        error_scenario_5 = True
        exitcode = 1  # Parse Errors should flag an API error code.

# Report Output
if exitcode == 0:
    # We good
    print("{status}=ok".format(status=Constants.API_SUMMARY_STRING))
else:
    # Errors should flag an API error code.
    error_hint = []
    if error_scenario_1:
        error_hint.append('ROLE_ALREADY_EXIST')
    if error_scenario_2:
        error_hint.append('TRANSACTION_ROLLBACK')
    if error_scenario_3:
        error_hint.append('SQL_ERROR')
    if error_scenario_4:
        error_hint.append('FATAL_ERROR')
    if error_scenario_5:
        error_hint.append('SYNTAX_ERROR')
    if len(error_hint) == 0:
        error_hint = ['UNKNOWN']
    print("{status}=rollback".format(status=Constants.API_SUMMARY_STRING))
    print("{errors}={reasons}".format(reasons=error_hint,
        errors=Constants.API_ERROR_STRING))

toolkit.exit(exitcode)


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

       <context:annotation-config/>
       <context:component-scan base-package="com.tk.cn"/>

         <!--
       <context:component-scanbase-packagecontext:component-scanbase-package="com.tk.cn"/>
  -->
       <!-- 引入properties 文件 -->
       <bean   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          <property name="locations">
             <list>
                <value>classpath:jdbc.properties</value>
             </list>
          </property>
       </bean>
       <!-- datasource -->
       <!-- BoneCP 配置数据源 -->
         <bean  id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
         <property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="partitionCount" value="${jdbc.partitionCount}" />
		<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
		<property name="statementsCacheSize" value="${jdbc.statementsCacheSize}" />
		<property name="idleMaxAgeInMinutes" value="${jdbc.idleMaxAgeInMinutes}" />
		<property name="releaseHelperThreads" value="${jdbc.releaseHelperThreads}" />
		<property name="minConnectionsPerPartition" value="${jdbc.minConnectionsPerPartition}" />
		<property name="maxConnectionsPerPartition" value="${jdbc.maxConnectionsPerPartition}" />
		<property name="idleConnectionTestPeriodInMinutes" value="${jdbc.idleConnectionTestPeriodInMinutes}" />
         </bean>

    <!-- =====mybatis 与 spring 配置====== -->
         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
             <property name="configLocation" value="classpath:configuration.xml"></property>
             <property name="dataSource" ref="dataSource"></property>
         </bean>

       	<!-- MyBatis 接口编程配置  -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	    <property name="basePackage" value="com.tk.cn.mapper" />
	    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />

	</bean>

      <!-- ***************事务配置************** -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<aop:config>
             <aop:advisor pointcut="execution(* service.*.*(..))"  advice-ref="txAdvice" />
    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="load*" read-only="true" />
            <tx:method name="select*" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>
	         <aop:aspectj-autoproxy/>

</beans>


text:
package org.keycloak.protocol.cas.endpoints;

import org.keycloak.events.EventBuilder;
import org.keycloak.models.*;
import org.keycloak.protocol.ProtocolMapper;
import org.keycloak.protocol.cas.mappers.CASAttributeMapper;
import org.keycloak.protocol.cas.representations.CASServiceResponse;
import org.keycloak.protocol.cas.utils.CASValidationException;
import org.keycloak.protocol.cas.utils.ContentTypeHelper;
import org.keycloak.protocol.cas.utils.ServiceResponseHelper;
import org.keycloak.services.managers.ClientSessionCode;
import org.keycloak.services.util.DefaultClientSessionContext;

import javax.ws.rs.core.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ServiceValidateEndpoint extends ValidateEndpoint {
    @Context
    private Request restRequest;

    public ServiceValidateEndpoint(RealmModel realm, EventBuilder event) {
        super(realm, event);
    }

    @Override
    protected Response successResponse() {
        UserSessionModel userSession = clientSession.getUserSession();
        Map<String, Object> attributes = getUserAttributes();
        CASServiceResponse serviceResponse = ServiceResponseHelper.createSuccess(userSession.getUser().getUsername(), attributes);
        return prepare(Response.Status.OK, serviceResponse);
    }

    @Override
    protected Response errorResponse(CASValidationException e) {
        CASServiceResponse serviceResponse = ServiceResponseHelper.createFailure(e.getError(), e.getErrorDescription());
        return prepare(e.getStatus(), serviceResponse);
    }

    private Response prepare(Response.Status status, CASServiceResponse serviceResponse) {
        MediaType responseMediaType = new ContentTypeHelper(request, restRequest, session.getContext().getUri()).selectResponseType();
        return ServiceResponseHelper.createResponse(status, responseMediaType, serviceResponse);
    }
}


text:
package harvester

import (
	"io"
	"os"
)

type Source interface {
	io.ReadCloser
	Name() string
	Stat() (os.FileInfo, error)
	Continuable() bool // can we continue processing after EOF?
	HasState() bool    // does this source have a state?
}


text:
. ..\utils\make-exercise-repo.ps1

Set-Content -Value "library-1.2.3" -Path lib.txt
Set-Content -Value "module using library-1.2.3" -Path mymodule.txt

git add lib.txt mymodule.txt
git commit -m "Adding module with its library"

git branch integrate-library-1.2.4
git checkout integrate-library-1.2.4

Set-Content -Value "library-1.2.4" -Path lib.txt
Add-Content -Value "New library functionality" -Path lib.txt
Set-Content -Value "module using library-1.2.4" -Path mymodule.txt

git add lib.txt
git add mymodule.txt
git commit -m "Update to library version 1.2.4"

Add-Content -Value "Use new library functionality" -Path mymodule.txt

git add mymodule.txt
git commit -m "Use new functionality in mymodule"

git checkout master

Add-Content -Value "Promising feature X" -Path mymodule.txt

git add mymodule.txt
git commit -m "Add feature X"

git merge integrate-library-1.2.4 --no-edit

# deal with merge conflict
Set-Content -Value "module using library-1.2.4" -Path mymodule.txt
Add-Content -Value "Promising feature X" -Path mymodule.txt
Add-Content -Value "Use new library functionality" -Path mymodule.txt

git add mymodule.txt
git commit -m "Merge integrate-library-1.2.4" --no-edit

Add-Content -Value "Useful feature Y" -Path mymodule.txt

git add mymodule.txt
git commit -m "Add feature Y"


text:
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Marklight.Themes
{
    [Serializable]
    public class StyleClass
    {
        #region Private Fields

        private static readonly char[] StyleSeperator = new char[] { ' ' };

        [SerializeField]
        private string _className;

        [NonSerialized]
        private string[] _classNames;

        [NonSerialized]
        private string _selector;

        #endregion

        #region Constructors

        public StyleClass()
        {
        }

        public StyleClass(string className)
        {
            _className = SortClassNames(className ?? "");
        }

        #endregion

        #region Methods

        public override int GetHashCode()
        {
            return _className.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            var other = obj as StyleClass;
            if (other == null)
                return false;

            return other._className == _className;
        }

        /// <summary>
        /// Sort a space delimited string of style class names alphabetically.
        /// </summary>
        public static string SortClassNames(string className)
        {

            if (string.IsNullOrEmpty(className))
                return className;

            var names = new List<string>(className.Split(StyleSeperator, StringSplitOptions.RemoveEmptyEntries));
            if (names.Count == 1)
                return names[0];

            names.Sort(StringComparer.Ordinal);
            return string.Join(" ", names.ToArray());
        }

        #endregion

        #region Property

        public bool IsSet
        {
            get { return !string.IsNullOrEmpty(_className); }
        }

        public string ClassName
        {
            get { return _className; }
        }

        public string[] ClassNames
        {
            get { return _classNames ?? (_classNames = _className.Split(' ')); }
        }

        public string Selector
        {
            get { return _selector ?? (_selector = "." + string.Join(".", ClassNames)); }
        }

        #endregion
    }
}


text:
<?php

namespace Zend\Cache\Storage\Adapter;

use Zend\Cache\Storage\IteratorInterface;
use APCuIterator as BaseApcuIterator;

class ApcuIterator implements IteratorInterface
{
    /**
     * The storage instance
     *
     * @var Apcu
     */
    protected $storage;

    /**
     * The iterator mode
     *
     * @var int
     */
    protected $mode = IteratorInterface::CURRENT_AS_KEY;

    /**
     * The base APCIterator instance
     *
     * @var APCIterator
     */
    protected $baseIterator;

    /**
     * The length of the namespace prefix
     *
     * @var int
     */
    protected $prefixLength;

    /**
     * Constructor
     *
     * @param Apcu             $storage
     * @param BaseApcuIterator $baseIterator
     * @param string           $prefix
     */
    public function __construct(Apcu $storage, BaseApcuIterator $baseIterator, $prefix)
    {
        $this->storage      = $storage;
        $this->baseIterator = $baseIterator;
        $this->prefixLength = strlen($prefix);
    }

    /**
     * Get storage instance
     *
     * @return Apcu
     */
    public function getStorage()
    {
        return $this->storage;
    }

    /**
     * Get iterator mode
     *
     * @return int Value of IteratorInterface::CURRENT_AS_*
     */
    public function getMode()
    {
        return $this->mode;
    }

    /**
     * Set iterator mode
     *
     * @param int $mode
     * @return ApcuIterator Provides a fluent interface
     */
    public function setMode($mode)
    {
        $this->mode = (int) $mode;
        return $this;
    }

    /* Iterator */

    /**
     * Get current key, value or metadata.
     *
     * @return mixed
     */
    public function current()
    {
        if ($this->mode == IteratorInterface::CURRENT_AS_SELF) {
            return $this;
        }

        $key = $this->key();

        if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) {
            return $this->storage->getItem($key);
        } elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) {
            return $this->storage->getMetadata($key);
        }

        return $key;
    }

    /**
     * Get current key
     *
     * @return string
     */
    public function key()
    {
        $key = $this->baseIterator->key();

        // remove namespace prefix
        return substr($key, $this->prefixLength);
    }

    /**
     * Move forward to next element
     *
     * @return void
     */
    public function next()
    {
        $this->baseIterator->next();
    }

    /**
     * Checks if current position is valid
     *
     * @return bool
     */
    public function valid()
    {
        return $this->baseIterator->valid();
    }

    /**
     * Rewind the Iterator to the first element.
     *
     * @return void
     */
    public function rewind()
    {
        return $this->baseIterator->rewind();
    }
}


text:
package org.apache.spark.scheduler.cluster

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.{Future, ExecutionContext}

import org.apache.spark.{Logging, SparkContext}
import org.apache.spark.rpc._
import org.apache.spark.scheduler.cluster.CoarseGrainedClusterMessages._
import org.apache.spark.scheduler._
import org.apache.spark.ui.JettyUtils
import org.apache.spark.util.{ThreadUtils, RpcUtils}

import scala.util.control.NonFatal

/**
 * Abstract Yarn scheduler backend that contains common logic
 * between the client and cluster Yarn scheduler backends.
 */
private[spark] abstract class YarnSchedulerBackend(
    scheduler: TaskSchedulerImpl,
    sc: SparkContext)
  extends CoarseGrainedSchedulerBackend(scheduler, sc.env.rpcEnv) {

  if (conf.getOption("spark.scheduler.minRegisteredResourcesRatio").isEmpty) {
    minRegisteredRatio = 0.8
  }

  protected var totalExpectedExecutors = 0

  private val yarnSchedulerEndpoint = new YarnSchedulerEndpoint(rpcEnv)

  private val yarnSchedulerEndpointRef = rpcEnv.setupEndpoint(
    YarnSchedulerBackend.ENDPOINT_NAME, yarnSchedulerEndpoint)

  private implicit val askTimeout = RpcUtils.askRpcTimeout(sc.conf)

  /**
   * Request executors from the ApplicationMaster by specifying the total number desired.
   * This includes executors already pending or running.
   */
  override def doRequestTotalExecutors(requestedTotal: Int): Boolean = {
    yarnSchedulerEndpointRef.askWithRetry[Boolean](
      RequestExecutors(requestedTotal, localityAwareTasks, hostToLocalTaskCount))
  }

  /**
   * Request that the ApplicationMaster kill the specified executors.
   */
  override def doKillExecutors(executorIds: Seq[String]): Boolean = {
    yarnSchedulerEndpointRef.askWithRetry[Boolean](KillExecutors(executorIds))
  }

  override def sufficientResourcesRegistered(): Boolean = {
    totalRegisteredExecutors.get() >= totalExpectedExecutors * minRegisteredRatio
  }

  /**
   * Add filters to the SparkUI.
   */
  private def addWebUIFilter(
      filterName: String,
      filterParams: Map[String, String],
      proxyBase: String): Unit = {
    if (proxyBase != null && proxyBase.nonEmpty) {
      System.setProperty("spark.ui.proxyBase", proxyBase)
    }

    val hasFilter =
      filterName != null && filterName.nonEmpty &&
      filterParams != null && filterParams.nonEmpty
    if (hasFilter) {
      logInfo(s"Add WebUI Filter. $filterName, $filterParams, $proxyBase")
      conf.set("spark.ui.filters", filterName)
      filterParams.foreach { case (k, v) => conf.set(s"spark.$filterName.param.$k", v) }
      scheduler.sc.ui.foreach { ui => JettyUtils.addFilters(ui.getHandlers, conf) }
    }
  }

  override def createDriverEndpoint(properties: Seq[(String, String)]): DriverEndpoint = {
    new YarnDriverEndpoint(rpcEnv, properties)
  }

  /**
   * Override the DriverEndpoint to add extra logic for the case when an executor is disconnected.
   * This endpoint communicates with the executors and queries the AM for an executor's exit
   * status when the executor is disconnected.
   */
  private class YarnDriverEndpoint(rpcEnv: RpcEnv, sparkProperties: Seq[(String, String)])
      extends DriverEndpoint(rpcEnv, sparkProperties) {

    /**
     * When onDisconnected is received at the driver endpoint, the superclass DriverEndpoint
     * handles it by assuming the Executor was lost for a bad reason and removes the executor
     * immediately.
     *
     * In YARN's case however it is crucial to talk to the application master and ask why the
     * executor had exited. If the executor exited for some reason unrelated to the running tasks
     * (e.g., preemption), according to the application master, then we pass that information down
     * to the TaskSetManager to inform the TaskSetManager that tasks on that lost executor should
     * not count towards a job failure.
     */
    override def onDisconnected(rpcAddress: RpcAddress): Unit = {
      addressToExecutorId.get(rpcAddress).foreach { executorId =>
        if (disableExecutor(executorId)) {
          yarnSchedulerEndpoint.handleExecutorDisconnectedFromDriver(executorId, rpcAddress)
        }
      }
    }
  }

  /**
   * An [[RpcEndpoint]] that communicates with the ApplicationMaster.
   */
  private class YarnSchedulerEndpoint(override val rpcEnv: RpcEnv)
    extends ThreadSafeRpcEndpoint with Logging {
    private var amEndpoint: Option[RpcEndpointRef] = None

    private val askAmThreadPool =
      ThreadUtils.newDaemonCachedThreadPool("yarn-scheduler-ask-am-thread-pool")
    implicit val askAmExecutor = ExecutionContext.fromExecutor(askAmThreadPool)

    private[YarnSchedulerBackend] def handleExecutorDisconnectedFromDriver(
        executorId: String,
        executorRpcAddress: RpcAddress): Unit = {
      amEndpoint match {
        case Some(am) =>
          val lossReasonRequest = GetExecutorLossReason(executorId)
          val future = am.ask[ExecutorLossReason](lossReasonRequest, askTimeout)
          future onSuccess {
            case reason: ExecutorLossReason => {
              driverEndpoint.askWithRetry[Boolean](RemoveExecutor(executorId, reason))
            }
          }
          future onFailure {
            case NonFatal(e) => {
              logWarning(s"Attempted to get executor loss reason" +
                s" for executor id ${executorId} at RPC address ${executorRpcAddress}," +
                s" but got no response. Marking as slave lost.", e)
              driverEndpoint.askWithRetry[Boolean](RemoveExecutor(executorId, SlaveLost()))
            }
            case t => throw t
          }
        case None =>
          logWarning("Attempted to check for an executor loss reason" +
            " before the AM has registered!")
      }
    }

    override def receive: PartialFunction[Any, Unit] = {
      case RegisterClusterManager(am) =>
        logInfo(s"ApplicationMaster registered as $am")
        amEndpoint = Option(am)

      case AddWebUIFilter(filterName, filterParams, proxyBase) =>
        addWebUIFilter(filterName, filterParams, proxyBase)

      case RemoveExecutor(executorId, reason) =>
        logWarning(reason.toString)
        removeExecutor(executorId, reason)
    }

    override def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {
      case r: RequestExecutors =>
        amEndpoint match {
          case Some(am) =>
            Future {
              context.reply(am.askWithRetry[Boolean](r))
            } onFailure {
              case NonFatal(e) =>
                logError(s"Sending $r to AM was unsuccessful", e)
                context.sendFailure(e)
            }
          case None =>
            logWarning("Attempted to request executors before the AM has registered!")
            context.reply(false)
        }

      case k: KillExecutors =>
        amEndpoint match {
          case Some(am) =>
            Future {
              context.reply(am.askWithRetry[Boolean](k))
            } onFailure {
              case NonFatal(e) =>
                logError(s"Sending $k to AM was unsuccessful", e)
                context.sendFailure(e)
            }
          case None =>
            logWarning("Attempted to kill executors before the AM has registered!")
            context.reply(false)
        }
    }

    override def onDisconnected(remoteAddress: RpcAddress): Unit = {
      if (amEndpoint.exists(_.address == remoteAddress)) {
        logWarning(s"ApplicationMaster has disassociated: $remoteAddress")
      }
    }

    override def onStop(): Unit = {
      askAmThreadPool.shutdownNow()
    }
  }
}

private[spark] object YarnSchedulerBackend {
  val ENDPOINT_NAME = "YarnScheduler"
}


text:
<?php
/*
Plugin Name: Kirki Framework
Plugin URI: http://kirki.org
Description: An options framework using and extending the WordPress Customizer
Author: Aristeides Stathopoulos
Author URI: http://wpmu.io/
Version: 0.4
*/

/**
* The main Kirki class
*/
if ( ! class_exists( 'Kirki' ) ) :
class Kirki {

	function __construct() {

		$this->options = apply_filters( 'kirki/config', array() );
		$options = $this->options;

		// Include files
		if ( ! isset( $options['live_css'] ) || true == $options['live_css'] ) {
			include_once( dirname( __FILE__ ) . '/includes/functions/background-css.php' );
		}
		include_once( dirname( __FILE__ ) . '/includes/functions/required.php' );
		include_once( dirname( __FILE__ ) . '/includes/functions/class-Kirki_Fonts.php' );
		include_once( dirname( __FILE__ ) . '/includes/functions/controls-init.php' );
		include_once( dirname( __FILE__ ) . '/includes/functions/transport.php' );
		include_once( dirname( __FILE__ ) . '/includes/functions/color-functions.php' );

		add_action( 'customize_register', array( $this, 'include_files' ), 1 );
		add_action( 'customize_controls_print_styles', array( $this, 'styles' ) );
		add_action( 'customize_controls_print_styles', array( $this, 'googlefonts' ) );
		add_action( 'customize_controls_print_styles', array( $this, 'custom_css' ), 999 );
		add_action( 'customize_controls_print_scripts', array( $this, 'custom_js' ), 999 );

	}

	/**
	 * Include the necessary files
	 */
	function include_files() {

		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Checkbox_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Color_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Image_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Multicheck_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Number_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Radio_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Sliderui_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Text_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Textarea_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Upload_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Select_Control.php' );
		include_once( dirname( __FILE__ ) . '/includes/controls/class-Kirki_Customize_Group_Title_Control.php' );

	}

	/**
	 * Enqueue the stylesheets and scripts required.
	 */
	function styles() {

		$options = apply_filters( 'kirki/config', array() );

		$kirki_url = isset( $options['url_path'] ) ? $options['url_path'] : plugin_dir_url( __FILE__ );

		wp_enqueue_style( 'kirki-customizer-css', $kirki_url . 'assets/css/customizer.css', NULL, '0.3' );
		wp_enqueue_style( 'kirki-customizer-ui',  $kirki_url . 'assets/css/jquery-ui-1.10.0.custom.css', NULL, '0.3' );

		wp_enqueue_script( 'kirki_customizer_js', $kirki_url . 'assets/js/customizer.js');
		wp_enqueue_script( 'tipsy', $kirki_url . 'assets/js/tooltipsy.min.js', array( 'jquery' ) );

	}

	/**
	 * Use the Roboto font on the customizer.
	 */
	function googlefonts() { ?>
		<link href='http://fonts.googleapis.com/css?family=Roboto:100,400|Roboto+Slab:700,400&subset=latin,cyrillic-ext,greek,vietnamese,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
		<?php
	}

	/**
	 * Add custom CSS rules to the head, applying our custom styles
	 */
	function custom_css() {

		// Get the active admin theme
		global $_wp_admin_css_colors;

		// Get the user's admin colors
		$color = get_user_option( 'admin_color' );
		// If no theme is active set it to 'fresh'
		if ( empty( $color ) || ! isset( $_wp_admin_css_colors[$color] ) ) {
			$color = 'fresh';
		}

		$color = (array) $_wp_admin_css_colors[$color];

		$admin_theme = get_user_meta( get_current_user_id(), 'admin_color', true ); //Find out which theme the user has selected.

		$options = apply_filters( 'kirki/config', array() );

		$color_font    = false;
		$color_active  = isset( $options['color_active'] )  ? $options['color_active']  : $color['colors'][3];
		$color_light   = isset( $options['color_light'] )   ? $options['color_light']   : $color['colors'][2];
		$color_select  = isset( $options['color_select'] )  ? $options['color_select']  : $color['colors'][3];
		$color_accent  = isset( $options['color_accent'] )  ? $options['color_accent']  : $color['icon_colors']['focus'];
		$color_back    = isset( $options['color_back'] )    ? $options['color_back']    : false;

		if ( $color_back ) {
			$color_font = ( 170 > kirki_get_brightness( $color_back ) ) ? '#f2f2f2' : '#222';
		}

		?>

		<?php

	}

	/**
	 * If we've specified an image to be used as logo, replace the default theme description with a div that will have our logo as background.
	 */
	function custom_js() {

		$options = apply_filters( 'kirki/config', array() ); ?>

		<?php if ( isset( $options['logo_image'] ) ) : ?>

		<?php endif;

	}

}

$kirki = new Kirki();

endif;


text:
using System;
using System.Drawing;
using System.Windows.Forms;
using Crownwood.Magic.Common;

namespace Crownwood.Magic.Docking
{
    public class HotZoneNull : HotZone
    {
        public HotZoneNull(Rectangle hotArea)
            : base(hotArea, hotArea)
        {
        }

        public override void DrawIndicator(Point mousePos) {}
        public override void RemoveIndicator(Point mousePos) {}
    }
}


text: Video game developed from scratch in 48 hours for Ludum Dare 33 "You are the monster"


text:
Profiler
========

Features
--------

  - Expose information about the current request
  - Memory Usage / Profiling ...

Configuration
-------------

You need to enable the plugin by adding this line into the IoC configuration file.

.. code-block:: yaml

    element.plugins.profiler:

Also, you need to expose the profiler's controllers

.. code-block:: yaml

    # profiler.yaml
    title: Profiler
    type: action.collection
    actions:
        element_profiler_home:
            type: action.raw
            path: /<token>
            methods: ['GET']
            defaults:
                _controller: element.plugins.profiler.view:home

        element_profiler_view:
            type: action.raw
            path: /<token>
            methods: ['GET']
            defaults:
                _controller: element.plugins.profiler.view:view

        element_profiler_wdt:
            type: action.raw
            path: /wdt/<token>
            methods: ['GET']
            defaults:
                _controller: element.plugins.profiler.view:wdt

        element_profiler_pyinfo:
            type: action.raw
            path: /pyinfo
            methods: ['GET']
            defaults:
                _controller: element.plugins.profiler.view:pyinfo

        element_profiler_import:
            type: action.raw
            path: /import
            methods: ['GET']
            defaults:
                _controller: element.plugins.profiler.view:import_run

        element_profiler_export:
            type: action.raw
            path: /<token>/export
            methods: ['GET']
            defaults:
                _controller: element.plugins.profiler.view:export_run

        element_profiler_purge:
            type: action.raw
            path: /<token>/purge
            methods: ['GET']
            defaults:
                _controller: element.plugins.profiler.view:purge_run

Usage
-----

The feature is enabled on dev mode, it does not work for threaded environment.

Preview
-------

.. figure:: ../images/profiler_wdt.png
   :align: center

   The wdt displays memory usage, processing time, controller and python version

.. figure:: ../images/profiler_view_config.png
   :align: center

   Display more detailed information profiling panel: config, request, etc ..

Credits
-------

The WDT is a python port of the `Symfony2 Profiler <http://symfony.com>`_.
Icons created by `Sensio <http://sensio.com>`_ are shared under a `Creative Commons Attribution license <http://creativecommons.org/licenses/by-sa/3.0/>`_.


text:
<?php

/* Prototype  : string ltrim  ( string $str  [, string $charlist  ] )
 * Description: Strip whitespace (or other characters) from the beginning of a string.
 * Source code: ext/standard/string.c
*/

echo "*** Testing ltrim() : error conditions ***\n";

echo "\n-- Testing ltrim() function with no arguments --\n";
var_dump( ltrim() );

echo "\n-- Testing ltrim() function with more than expected no. of arguments --\n";
$extra_arg = 10;
var_dump( ltrim("Hello World",  "Heo", $extra_arg) );

$hello = "  Hello World\n";
echo "\n-- Test ltrim function with various invalid charlists\n";
var_dump(ltrim($hello, "..a"));
var_dump(ltrim($hello, "a.."));
var_dump(ltrim($hello, "z..a"));
var_dump(ltrim($hello, "a..b..c"));

?>
===DONE===


text:
from model.group import Group
import random

def test_update_some_group(app, db, check_ui):
    if len(db.get_group_list()) == 0:
        app.group.create(Group(name="if no group exists"))
    old_groups = db.get_group_list()
    group = random.choice(old_groups)                 # выбрали группу для модификации
    updatedgroup = Group(name="Group name modified")  # выбрали параметр, который будет изменен
    updatedgroup.id = group.id                        # присваиваем значение id для группы, которую будем модифицировать, чтобы потом передать в old_groups.append(updatedgroup), иначе id будет None
    app.group.update_group_by_id(group.id, updatedgroup) # модифицируем группу выбранную по id
    new_groups = db.get_group_list()
#   assert len(old_groups) == len(new_groups)
    old_groups.remove(group)                             # удаляем объект со старым именем из старого списка
    old_groups.append(updatedgroup)                      # добавляем модифицированный объект в старый список
    assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
    if check_ui:
        groups_from_ui = app.group.get_group_list()
        def clean(group):
            return Group(id=group.id, name=group.name.strip())
        groups_from_db = map(clean, new_groups)
        assert sorted(groups_from_db, key=Group.id_or_max) == sorted(groups_from_ui, key=Group.id_or_max)

#def test_update_some_group(app, db):
    #if len(db.get_group_list()) == 0:
        #app.group.create(Group(name="if no group exists"))
    #old_groups = app.group.get_group_list()
    #index = randrange(len(old_groups))
    #group = Group(name="Group name modified")
    #group.id = old_groups[index].id      # присваиваем значение id для группы, которую будем модифицировать, чтобы потом передать в old_groups[index] = group, иначе id будет None
    #app.group.update_group_by_index(group, index)
    #new_groups = app.group.get_group_list()
    #assert len(old_groups) == len(new_groups)
    #old_groups[index] = group
    #assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)

#def test_update_group_header(app):
    #if app.group.count() == 0:
        #app.group.create(Group(name="if no group exists"))
    #old_groups = app.group.get_group_list()
    #app.group.update_first_group(Group(header ="Group header modified"))
    #new_groups = app.group.get_group_list()
    #assert len(old_groups) == len(new_groups)

#def test_update_group_footer(app):
    #if app.group.count() == 0:
        #app.group.create(Group(name="if no group exists"))
    #old_groups = app.group.get_group_list()
    #app.group.update_first_group(Group(footer = "Group footer modified"))
    #new_groups = app.group.get_group_list()
    #assert len(old_groups) == len(new_groups)


text:
/*
 * rtlib.h
 *
 * Initial Author: Jeff Pang <jeffpang+441@cs.cmu.edu>
 * Class: 15-441 (Spring 2005)
 *
 * Some library routines that you may find useful for
 * Project 1: Routing Protocols.
 */

#ifndef __RTLIB_H__
#define __RTLIB_H__

/**
 * The maximum number of nodes that will be defined in a single config file.
 */
#define MAX_CONFIG_FILE_LINES 32
/**
 * The maximum number of characters of any line in the config file.
 */
#define MAX_CONFIG_FILE_LINE_LEN 255

/**
 * A single entry in the config file which describes a node.
 * All elements in this struct are in host byte-order.
 */
struct rt_config_entry_s {
    unsigned long nodeID; /* the nodeID of the node */
    unsigned long ipaddr; /* the IP address of the node */
    unsigned short routing_port; /* the routing port of the routing daemon */
    unsigned short local_port; /* the local port of the routing daemon */
    unsigned short irc_port; /* the IRC and forwarding port of the IRC Serv */
};
typedef struct rt_config_entry_s rt_config_entry_t;

/**
 * This structure contains an entire configuration file parsed in the
 * function rt_parse_command_line(...).
 */
struct rt_config_file_s {
    int size; /* the number of entries in the entries field */
    struct rt_config_entry_s entries[MAX_CONFIG_FILE_LINES];
    /* all the entries in the configuration file; only the entries [0,size-1]
       are valid, the remainder should be ignored */
};
typedef struct rt_config_file_s rt_config_file_t;

/**
 * This structure is what is filled by rt_parse_command_line(...). It
 * contains all the command line arguments your routing daemon must know about.
 * All elements of this struct are in host byte-order.
 */
struct rt_args_s {
    /* ===== GENERAL OPTIONS ===== */
    unsigned long nodeID; /* nodeID of the current node */
    struct rt_config_file_s config_file; /* configuration file structure */

    /* ===== OSPF OPTIONS ===== */
    unsigned long advertisement_cycle_time; /* -a advertisement cycle */
    unsigned long neighbor_timeout;         /* -n timeout for dead neighbors */
    unsigned long retransmission_timeout;   /* -r timeout for retransmission */
    unsigned long lsa_timeout;              /* -t timeout to expire an LSA */
};
typedef struct rt_args_s rt_args_t;

#ifdef __cplusplus
extern "C" {
#endif

/**
 * Parse the required command line arguments for the routing daemon
 * into the struct pointed to by rt_args_t *args. This function also opens
 * and parses the configuration file defined by the command line. If there is
 * an error parsing the command line, this function prints the error to
 * stderr and exits.
 *
 * Arguments:
 * args       - the rt_args_t structure that the function will fill in.
 *              The caller should allocate it and pass in a pointer.
 * argc       - the original argc passed into srouted's main() function.
 * argv       - the original argv passed into srouted's main() function.
 */
void rt_parse_command_line(rt_args_t *args, int argc, char * const*argv);

/**
 * Parse the config file into the structure config_file_t *config. This
 * function is called automatically by the rt_parse_command_line function,
 * but you can call it separately in your IRC Server. If there is an error
 * parsing the file, this function prints the error to stderr and exits.
 *
 * Arguments:
 * cmd        - a string that will be used as a prefix to all error messages.
 * config     - the rt_config_file_t structure the function will fill in.
 * filename   - the name of the config file to open and parse.
 */
void rt_parse_config_file(const char *cmd, rt_config_file_t *config,
			  const char *filename);

#ifdef __cplusplus
}
#endif

#endif


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

#include <map>
#include <memory>
#include <string>
#include <utility>

namespace crypto {
namespace tink {
namespace {

// A Prf that always returns a kInternal status on API calls.
class AlwaysFailPrf : public Prf {
 public:
  explicit AlwaysFailPrf(std::string message) : message_(std::move(message)) {}

  util::StatusOr<std::string> Compute(absl::string_view /*input*/,
                                      size_t /*output_length*/) const override {
    return util::Status(
        absl::StatusCode::kInternal,
        absl::StrCat(
            "AlwaysFailPrf will always fail on Compute (msg=", message_, ")"));
  }

 private:
  const std::string message_;
};

// A PrfSet that always returns a kInternal status on API calls.
class AlwaysFailPrfSet : public PrfSet {
 public:
  explicit AlwaysFailPrfSet(std::string message)
      : message_(std::move(message)),
        always_fail_prf_0_(absl::make_unique<AlwaysFailPrf>(message_)),
        always_fail_prf_1_(absl::make_unique<AlwaysFailPrf>(message_)),
        always_fail_prf_2_(absl::make_unique<AlwaysFailPrf>(message_)),
        prfs_({{0, always_fail_prf_0_.get()},
               {1, always_fail_prf_1_.get()},
               {2, always_fail_prf_2_.get()}}) {}

  uint32_t GetPrimaryId() const override { return 0; }

  // A map of the PRFs represented by the keys in this keyset.
  // The map is guaranteed to contain getPrimaryId() as a key.
  const std::map<uint32_t, Prf*>& GetPrfs() const override { return prfs_; };

  util::StatusOr<std::string> ComputePrimary(absl::string_view /*input*/,
                                             size_t /*output_length*/) const {
    return util::Status(
        absl::StatusCode::kInternal,
        absl::StrCat(
            "AlwaysFailPrfSet will always fail on ComputePrimary (msg=",
            message_, ")"));
  }

 private:
  const std::string message_;
  std::unique_ptr<AlwaysFailPrf> always_fail_prf_0_;
  std::unique_ptr<AlwaysFailPrf> always_fail_prf_1_;
  std::unique_ptr<AlwaysFailPrf> always_fail_prf_2_;
  std::map<uint32_t, Prf*> prfs_;
};
}  // namespace

std::unique_ptr<Prf> CreateAlwaysFailingPrf(std::string message) {
  return absl::make_unique<AlwaysFailPrf>(std::move(message));
}

std::unique_ptr<PrfSet> CreateAlwaysFailingPrfSet(std::string message) {
  return absl::make_unique<AlwaysFailPrfSet>(std::move(message));
}

}  // namespace tink
}  // namespace crypto


text:
package com.example.vaibhavchellani.my_timetable;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.vaibhavchellani.my_timetable.database.AttedanceDB;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private Spinner spinner_year,spinner_branch,spinner_shift;

/*
    SharedPreferences sharedPreferences=this.getSharedPreferences("data", Context.MODE_PRIVATE);
*/

    private TextView textview;

    AttedanceDB db;

    private Button button_contact,start_notif_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.landingpage);
        db = new AttedanceDB(this);
        db.addrow_check_class();
        db.make_attendance_table();
        SharedPreferences sharedPreferences=getSharedPreferences("data", Context.MODE_PRIVATE);
        String username=sharedPreferences.getString("username",null);
        TextView user=(TextView)findViewById(R.id.textView);
        user.setText("Welcome "+username);

        findViewById(R.id.startnotifs_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createAlarms();
                Toast.makeText(MainActivity.this, " Notification Service Activated For Today", Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.button_view_timetable).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent opentimetable=new Intent(MainActivity.this,showtimetable.class);
                startActivity(opentimetable);
            }
        });

        findViewById(R.id.button_view_attendance).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent opentimetable=new Intent(MainActivity.this,showattendance.class);
                startActivity(opentimetable);

            }
        });

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.landingpge_menu, menu);
        return true;
    }

    public void deleteDatabase(View view) {

        db.deleteTable(AttedanceDB.TABLE_CHECK_CLASS);
        String dbstring = db.getTableAsString(AttedanceDB.TABLE_CHECK_CLASS);
        textview = (TextView) findViewById(R.id.newText);
        textview.setText(dbstring);
    }

    public void viewDatabase(View view) {

        Toast.makeText(this, "we are inside view", Toast.LENGTH_SHORT).show();
        textview=(TextView)findViewById(R.id.newText);
        String dbstring = db.getTableAsString(AttedanceDB.TABLE_ATTENDANCE);
        textview.setText(dbstring);
        Toast.makeText(this, "no of coumns are " + db.numberOfColumns(AttedanceDB.TABLE_CHECK_CLASS), Toast.LENGTH_LONG).show();

    }
    public void composeEmail( String subject) {
        String[] addresses={"vaibhavchellani223@gmail.com"};
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:")); // only email apps should handle this
        intent.putExtra(Intent.EXTRA_EMAIL, addresses);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);

        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.contactus:
                composeEmail("Timetable app feedback");
                return true;
            case R.id.resetDatabse:
                db.deleteTable(db.TABLE_ATTENDANCE);
                return true;
            case R.id.personalize:
                Intent i=new Intent(this,personalise.class);
                startActivity(i);
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void createAlarms(){

        Calendar calendar=Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        AlarmManager alarm_manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        //lecture 1 alarm
        Calendar timeOff1 = Calendar.getInstance();
        Intent intent1 = new Intent(this, Notification_reciever.class);
        intent1.setAction("lecture 1");
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this,0,intent1,0);
        timeOff1.set(Calendar.HOUR_OF_DAY,10);
        timeOff1.set(Calendar.MINUTE, 10);
        timeOff1.set(Calendar.SECOND, 0);
        //todo change this so that notification doesnt display on other day
        if(timeOff1.before(calendar)==false) {
            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff1.getTimeInMillis(), pendingIntent1);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff1.getTimeInMillis(), pendingIntent1);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff1.getTimeInMillis(), pendingIntent1);
            }
        }

        //second intent for second lecture
        Intent intent2 = new Intent(this, Notification_reciever.class);
        intent2.setAction("lecture 2");
        Calendar timeOff2 = Calendar.getInstance();
        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 0, intent2 , 0);
        timeOff2.set(Calendar.HOUR_OF_DAY,11);
        timeOff2.set(Calendar.MINUTE,5);
        timeOff2.set(Calendar.SECOND, 0);
        //todo edit the time here
        if(timeOff2.before(calendar)==false) {
        if (Build.VERSION.SDK_INT >= 23) {
            // Wakes up the device in Doze Mode
            alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff2.getTimeInMillis(), pendingIntent2);
        } else if (Build.VERSION.SDK_INT >= 19) {
            // Wakes up the device in Idle Mode
            alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff2.getTimeInMillis(), pendingIntent2);
        } else {
            // Old APIs
            alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff2.getTimeInMillis(), pendingIntent2);
        }
        }

        //third intent for 3 lecture
        Intent intent3 = new Intent(this, Notification_reciever.class);
        intent3.setAction("lecture 3");
        PendingIntent pendingIntent3 = PendingIntent.getBroadcast(this, 0, intent3, 0);
        Calendar timeOff3 = Calendar.getInstance();
        timeOff3.set(Calendar.HOUR_OF_DAY,12);
        timeOff3.set(Calendar.MINUTE, 0);
        timeOff3.set(Calendar.SECOND, 0);
        if(timeOff3.before(calendar)==false) {
            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff3.getTimeInMillis(), pendingIntent3);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff3.getTimeInMillis(), pendingIntent3);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff3.getTimeInMillis(), pendingIntent3);
            }
        }

        //FOURTH INTENT
        Intent intent4 = new Intent(this, Notification_reciever.class);
        intent4.setAction("lecture 4");
        PendingIntent pendingIntent4 = PendingIntent.getBroadcast(this, 0, intent4, 0);
        Calendar timeOff4 = Calendar.getInstance();
        timeOff4.set(Calendar.HOUR_OF_DAY,12);
        timeOff4.set(Calendar.MINUTE, 30);
        timeOff4.set(Calendar.SECOND, 0);
        if(timeOff4.before(calendar)==false) {
            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff4.getTimeInMillis(), pendingIntent4);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff4.getTimeInMillis(), pendingIntent1);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff4.getTimeInMillis(), pendingIntent4);
            }
        }

        //FIFTH INTENT
        Intent intent5 = new Intent(this, Notification_reciever.class);
        intent5.setAction("lecture 5");
        PendingIntent pendingIntent5 = PendingIntent.getBroadcast(this, 0, intent5, 0);
        Calendar timeOff5 = Calendar.getInstance();
        timeOff5.set(Calendar.HOUR_OF_DAY,13);
        timeOff5.set(Calendar.MINUTE,25);
        timeOff5.set(Calendar.SECOND, 0);
        if(timeOff5.before(calendar)==false) {
            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff5.getTimeInMillis(), pendingIntent5);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff5.getTimeInMillis(), pendingIntent5);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff5.getTimeInMillis(), pendingIntent5);
            }
        }
        //SIXTH INTENT
        Intent intent6 = new Intent(this, Notification_reciever.class);
        intent6.setAction("lecture 6");
        PendingIntent pendingIntent6 = PendingIntent.getBroadcast(this, 0, intent6, 0);
        Calendar timeOff6 = Calendar.getInstance();
        timeOff6.set(Calendar.HOUR_OF_DAY,14);
        timeOff6.set(Calendar.MINUTE,25);
        timeOff6.set(Calendar.SECOND,0);
        if(timeOff6.before(calendar)==false) {
            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff6.getTimeInMillis(), pendingIntent6);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff6.getTimeInMillis(), pendingIntent6);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff6.getTimeInMillis(), pendingIntent6);
            }
        }
        //SEVENTH INTENT
        Intent intent7 = new Intent(this, Notification_reciever.class);
        intent7.setAction("lecture 7");
        PendingIntent pendingIntent7 = PendingIntent.getBroadcast(this, 0, intent7, 0);
        Calendar timeOff7 = Calendar.getInstance();
        timeOff7.set(Calendar.HOUR_OF_DAY,15);
        timeOff7.set(Calendar.MINUTE,5);
        timeOff7.set(Calendar.SECOND, 0);
        if(timeOff7.before(calendar)==false) {
            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff7.getTimeInMillis(), pendingIntent7);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff7.getTimeInMillis(), pendingIntent7);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff7.getTimeInMillis(), pendingIntent7);
            }
        }

        //EIGHTH INTENT
        Intent intent8 = new Intent(this, Notification_reciever.class);
        intent8.setAction("lecture 8");
        PendingIntent pendingIntent8 = PendingIntent.getBroadcast(this, 0, intent8, 0);
        Calendar timeOff8 = Calendar.getInstance();
        timeOff8.set(Calendar.HOUR_OF_DAY,16);
        timeOff8.set(Calendar.MINUTE, 0);
        timeOff8.set(Calendar.SECOND, 0);
        if(timeOff8.before(calendar)==false) {
            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff8.getTimeInMillis(), pendingIntent8);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff8.getTimeInMillis(), pendingIntent8);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff8.getTimeInMillis(), pendingIntent8);
            }
        }

        //NINTH INTENT
        Intent intent9 = new Intent(this, Notification_reciever.class);
        intent9.setAction("lecture 9");
        PendingIntent pendingIntent9 = PendingIntent.getBroadcast(this, 0, intent9, 0);
        Calendar timeOff9 = Calendar.getInstance();
        timeOff9.set(Calendar.HOUR_OF_DAY,16);
        timeOff9.set(Calendar.MINUTE,35);
        timeOff9.set(Calendar.SECOND, 0);
        if(timeOff9.before(calendar)==false) {

            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff9.getTimeInMillis(), pendingIntent9);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff9.getTimeInMillis(), pendingIntent9);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff9.getTimeInMillis(), pendingIntent9);
            }
        }

        //TENTH INTENT
        Intent intent10 = new Intent(this, Notification_reciever.class);
        intent10.setAction("lecture 10");
        PendingIntent pendingIntent10 = PendingIntent.getBroadcast(this, 0, intent10, 0);
        Calendar timeOff10 = Calendar.getInstance();
        timeOff10.set(Calendar.HOUR_OF_DAY,17);
        timeOff10.set(Calendar.MINUTE,0);
        timeOff10.set(Calendar.SECOND, 0);
        if(timeOff10.before(calendar)==false) {
            if (Build.VERSION.SDK_INT >= 23) {
                // Wakes up the device in Doze Mode
                alarm_manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeOff10.getTimeInMillis(), pendingIntent10);
            } else if (Build.VERSION.SDK_INT >= 19) {
                // Wakes up the device in Idle Mode
                alarm_manager.setExact(AlarmManager.RTC_WAKEUP, timeOff10.getTimeInMillis(), pendingIntent10);
            } else {
                // Old APIs
                alarm_manager.set(AlarmManager.RTC_WAKEUP, timeOff10.getTimeInMillis(), pendingIntent10);
            }
        }
    }

}


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

namespace Microsoft.WindowsAzure.Management.Storage.Blob.Cmdlet
{
    using System;
    using System.Collections.Generic;
    using System.Management.Automation;
    using System.Security.Permissions;
    using Microsoft.WindowsAzure.Management.Storage.Common;
    using Microsoft.WindowsAzure.Management.Storage.Model.Contract;
    using Microsoft.WindowsAzure.Management.Storage.Model.ResourceModel;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;

    /// <summary>
    /// list azure blobs in specified azure container
    /// </summary>
    [Cmdlet(VerbsCommon.Get, StorageNouns.Blob, DefaultParameterSetName = NameParameterSet),
        OutputType(typeof(AzureStorageBlob))]
    public class GetAzureStorageBlobCommand : StorageCloudBlobCmdletBase
    {
        /// <summary>
        /// default parameter set name
        /// </summary>
        private const string NameParameterSet = "BlobName";

        /// <summary>
        /// prefix parameter set name
        /// </summary>
        private const string PrefixParameterSet = "BlobPrefix";

        [Parameter(Position = 0, HelpMessage = "Blob name", ParameterSetName = NameParameterSet)]
        public string Blob
        {
            get
            {
                return blobName;
            }
            set
            {
                blobName = value;
            }
        }
        private string blobName = String.Empty;

        [Parameter(HelpMessage = "Blob Prefix", ParameterSetName = PrefixParameterSet)]
        public string Prefix
        {
            get
            {
                return blobPrefix;
            }
            set
            {
                blobPrefix = value;
            }
        }
        private string blobPrefix = String.Empty;

        [Alias("N", "Name")]
        [Parameter(Position = 1, Mandatory = true, HelpMessage = "Container name",
            ValueFromPipelineByPropertyName = true)]
        [ValidateNotNullOrEmpty]
        public string Container
        {
            get
            {
                return containerName;
            }
            set
            {
                containerName = value;
            }
        }
        private string containerName = String.Empty;

        /// <summary>
        /// Initializes a new instance of the GetAzureStorageBlobCommand class.
        /// </summary>
        public GetAzureStorageBlobCommand()
            : this(null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the GetAzureStorageBlobCommand class.
        /// </summary>
        /// <param name="channel">IStorageBlobManagement channel</param>
        public GetAzureStorageBlobCommand(IStorageBlobManagement channel)
        {
            Channel = channel;
        }

        /// <summary>
        /// get the CloudBlobContianer object by name if container exists
        /// </summary>
        /// <param name="containerName">container name</param>
        /// <returns>return CloudBlobContianer object if specified container exists, otherwise throw an exception</returns>
        internal CloudBlobContainer GetCloudBlobContainerByName(string containerName, bool skipCheckExists = false)
        {
            if (!NameUtil.IsValidContainerName(containerName))
            {
                throw new ArgumentException(String.Format(Resources.InvalidContainerName, containerName));
            }

            BlobRequestOptions requestOptions = null;
            CloudBlobContainer container = Channel.GetContainerReference(containerName);

            if (!skipCheckExists && !Channel.DoesContainerExist(container, requestOptions, OperationContext))
            {
                throw new ArgumentException(String.Format(Resources.ContainerNotFound, containerName));
            }

            return container;
        }

        /// <summary>
        /// list blobs by blob name and container name
        /// </summary>
        /// <param name="containerName">container name</param>
        /// <param name="blobName">blob name pattern</param>
        /// <returns>An enumerable collection of IListBlobItem</returns>
        internal IEnumerable<IListBlobItem> ListBlobsByName(string containerName, string blobName)
        {
            CloudBlobContainer container = null;
            BlobRequestOptions requestOptions = null;
            AccessCondition accessCondition = null;

            bool useFlatBlobListing = true;
            string prefix = string.Empty;
            BlobListingDetails details = BlobListingDetails.Snapshots | BlobListingDetails.Metadata | BlobListingDetails.Copy;

            if (String.IsNullOrEmpty(blobName) || WildcardPattern.ContainsWildcardCharacters(blobName))
            {
                container = GetCloudBlobContainerByName(containerName);

                IEnumerable<IListBlobItem> blobs = Channel.ListBlobs(container, prefix, useFlatBlobListing, details, requestOptions, OperationContext);
                WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.Compiled;
                WildcardPattern wildcard = null;

                if (!String.IsNullOrEmpty(blobName))
                {
                    wildcard = new WildcardPattern(blobName, options);
                }

                foreach (IListBlobItem blobItem in blobs)
                {
                    ICloudBlob blob = blobItem as ICloudBlob;

                    if (blob == null)
                    {
                        continue;
                    }

                    if (wildcard == null || wildcard.IsMatch(blob.Name))
                    {
                        yield return blob;
                    }
                }
            }
            else
            {
                container = GetCloudBlobContainerByName(containerName, true);

                if (!NameUtil.IsValidBlobName(blobName))
                {
                    throw new ArgumentException(String.Format(Resources.InvalidBlobName, blobName));
                }

                ICloudBlob blob = Channel.GetBlobReferenceFromServer(container, blobName, accessCondition, requestOptions, OperationContext);

                if (null == blob)
                {
                    throw new ResourceNotFoundException(String.Format(Resources.BlobNotFound, blobName, containerName));
                }
                else
                {
                    yield return blob;
                }
            }
        }

        /// <summary>
        /// list blobs by blob prefix and container name
        /// </summary>
        /// <param name="containerName">container name</param>
        /// <param name="prefix">blob preifx</param>
        /// <returns>An enumerable collection of IListBlobItem</returns>
        internal IEnumerable<IListBlobItem> ListBlobsByPrefix(string containerName, string prefix)
        {
            CloudBlobContainer container = GetCloudBlobContainerByName(containerName);

            BlobRequestOptions requestOptions = null;
            bool useFlatBlobListing = true;
            BlobListingDetails details = BlobListingDetails.Snapshots | BlobListingDetails.Metadata | BlobListingDetails.Copy;

            return Channel.ListBlobs(container, prefix, useFlatBlobListing, details, requestOptions, OperationContext);
        }

        /// <summary>
        /// write blobs with storage context
        /// </summary>
        /// <param name="blobList">An enumerable collection of IListBlobItem</param>
        internal void WriteBlobsWithContext(IEnumerable<IListBlobItem> blobList)
        {
            if (null == blobList)
            {
                return;
            }

            foreach (IListBlobItem blobItem in blobList)
            {
                ICloudBlob blob = blobItem as ICloudBlob;

                if (blob == null)
                {
                    continue;
                }

                AzureStorageBlob azureBlob = new AzureStorageBlob(blob);
                WriteObjectWithStorageContext(azureBlob);
            }
        }

        /// <summary>
        /// execute command
        /// </summary>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public override void ExecuteCmdlet()
        {
            IEnumerable<IListBlobItem> blobList = null;

            if (PrefixParameterSet == ParameterSetName)
            {
                blobList = ListBlobsByPrefix(containerName, blobPrefix);
            }
            else
            {
                blobList = ListBlobsByName(containerName, blobName);
            }

            WriteBlobsWithContext(blobList);
        }
    }
}


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.RecoveryServicesSiteRecovery.Models
{
    /// <summary> Recovery plan update properties. </summary>
    internal partial class UpdateRecoveryPlanInputProperties
    {
        /// <summary> Initializes a new instance of UpdateRecoveryPlanInputProperties. </summary>
        public UpdateRecoveryPlanInputProperties()
        {
            Groups = new ChangeTrackingList<RecoveryPlanGroup>();
        }

        /// <summary> The recovery plan groups. </summary>
        public IList<RecoveryPlanGroup> Groups { get; }
    }
}