text:
// The MIT License
//
// Copyright (c) 2014 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>
#import "GRMustacheAvailabilityMacros.h"

@protocol GRMustacheTagDelegate;

/**
 * The GRMustacheContext represents a Mustache rendering context: it internally
 * maintains three stacks:
 *
 * - a *context stack*, that makes it able to provide the current context
 *   object, and to perform key lookup.
 *
 * - a *priority context stack*, whose objects define important keys that
 *   should not be overriden.
 *
 * - a *tag delegate stack*, so that tag delegates are notified when a Mustache
 *   tag is rendered.
 *
 * **Companion guides:**
 *
 * - https://github.com/groue/GRMustache/blob/master/Guides/view_model.md
 * - https://github.com/groue/GRMustache/blob/master/Guides/delegate.md
 * - https://github.com/groue/GRMustache/blob/master/Guides/rendering_objects.md
 * - https://github.com/groue/GRMustache/blob/master/Guides/security.md
 *
 * @warning GRMustacheContext is not suitable for subclassing.
 *
 * @see GRMustacheRendering protocol
 */
@interface GRMustacheContext : NSObject {
@private
#define GRMUSTACHE_STACK_TOP_IVAR(stackName) _ ## stackName ## Object
#define GRMUSTACHE_STACK_PARENT_IVAR(stackName) _ ## stackName ## Parent
#define GRMUSTACHE_STACK_DECLARE_IVARS(stackName, type) \
    GRMustacheContext *GRMUSTACHE_STACK_PARENT_IVAR(stackName); \
    type GRMUSTACHE_STACK_TOP_IVAR(stackName)

    GRMUSTACHE_STACK_DECLARE_IVARS(contextStack, id);
    GRMUSTACHE_STACK_DECLARE_IVARS(protectedContextStack, id);
    GRMUSTACHE_STACK_DECLARE_IVARS(hiddenContextStack, id);
    GRMUSTACHE_STACK_DECLARE_IVARS(tagDelegateStack, id<GRMustacheTagDelegate>);
    GRMUSTACHE_STACK_DECLARE_IVARS(inheritedPartialNodeStack, id);

    BOOL _unsafeKeyAccess;
}

////////////////////////////////////////////////////////////////////////////////
/// @name Creating Rendering Contexts
////////////////////////////////////////////////////////////////////////////////

/**
 * Returns an initialized empty rendering context.
 *
 * Empty contexts do not provide any value for any key.
 *
 * If you wish to use the services provided by the GRMustache standard library,
 * you should create a context with the +[GRMustacheContext contextWithObject:]
 * method, like this:
 *
 * ```
 * [GRMustacheContext contextWithObject:[GRMustache standardLibrary]]
 * ```
 *
 * @return A rendering context.
 *
 * @see +[GRMustache standardLibrary]
 */
- (instancetype)init;

/**
 * Returns an empty rendering context.
 *
 * Empty contexts do not provide any value for any key.
 *
 * If you wish to use the services provided by the GRMustache standard library,
 * you should create a context with the +[GRMustacheContext contextWithObject:]
 * method, like this:
 *
 * ```
 * [GRMustacheContext contextWithObject:[GRMustache standardLibrary]]
 * ```
 *
 * @return A rendering context.
 *
 * @see contextWithObject:
 * @see +[GRMustache standardLibrary]
 *
 * @since v6.4
 */
+ (instancetype)context AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Returns a rendering context containing a single object.
 *
 * Keys defined by _object_ gets available for template rendering.
 *
 * ```
 * context = [GRMustacheContext contextWithObject:@{ @"name": @"Arthur" }];
 * [context valueForMustacheKey:@"name"];   // @"Arthur"
 * ```
 *
 * If _object_ conforms to the GRMustacheTemplateDelegate protocol, it is also
 * made the top of the tag delegate stack.
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/delegate.md
 *
 * @param object  An object
 *
 * @return A rendering context.
 *
 * @see contextByAddingObject:
 *
 * @see GRMustacheTemplateDelegate
 *
 * @since v6.4
 */
+ (instancetype)contextWithObject:(id)object AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Returns a context containing a single priority object.
 *
 * Keys defined by _object_ are given priority, which means that they can not be
 * overriden by other objects that will eventually enter the context stack.
 *
 * ```
 * // Create a context with a priority `precious` key
 * context = [GRMustacheContext contextWithProtectedObject:@{ @"precious": @"gold" }];
 *
 * // Derive a new context by attempting to override the `precious` key:
 * context = [context contextByAddingObject:@{ @"precious": @"lead" }];
 *
 * // Priority keys can't be overriden
 * [context valueForMustacheKey:@"precious"];   // @"gold"
 * ```
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/security.md#priority-keys
 *
 * @param object  An object
 *
 * @return A rendering context.
 *
 * @see contextByAddingProtectedObject:
 *
 * @since v6.4
 */
+ (instancetype)contextWithProtectedObject:(id)object AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Returns a context containing a single tag delegate.
 *
 * _tagDelegate_ will be notified of the rendering of all tags rendered from the
 * receiver or from contexts derived from the receiver.
 *
 * Unlike contextWithObject: and contextWithProtectedObject:, _tagDelegate_ will
 * not provide any key to the templates. It will only be notified of the
 * rendering of tags.
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/delegate.md
 *
 * @param tagDelegate  A tag delegate
 *
 * @return A rendering context.
 *
 * @see GRMustacheTagDelegate
 *
 * @since v6.4
 */
+ (instancetype)contextWithTagDelegate:(id<GRMustacheTagDelegate>)tagDelegate AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

////////////////////////////////////////////////////////////////////////////////
/// @name Deriving New Contexts
////////////////////////////////////////////////////////////////////////////////

/**
 * Returns a new rendering context that is the copy of the receiver, and the
 * given object added at the top of the context stack.
 *
 * Keys defined by _object_ gets available for template rendering, and override
 * the values defined by objects already contained in the context stack. Keys
 * unknown to _object_ will be looked up deeper in the context stack.
 *
 * ```
 * context = [GRMustacheContext contextWithObject:@{ @"a": @"ignored", @"b": @"foo" }];
 * context = [context contextByAddingObject:@{ @"a": @"bar" }];
 *
 * // `a` is overriden
 * [context valueForMustacheKey:@"a"];   // @"bar"
 *
 * // `b` is inherited
 * [context valueForMustacheKey:@"b"];   // @"foo"
 * ```
 *
 * _object_ can not override keys defined by the objects of the priority
 * context stack, though. See contextWithProtectedObject: and
 * contextByAddingProtectedObject:.
 *
 * If _object_ conforms to the GRMustacheTemplateDelegate protocol, it is also
 * added at the top of the tag delegate stack.
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/delegate.md
 *
 * @param object  An object
 *
 * @return A new rendering context.
 *
 * @see GRMustacheTemplateDelegate
 *
 * @since v6.0
 */
- (instancetype)contextByAddingObject:(id)object AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Returns a new rendering context that is the copy of the receiver, and the
 * given object added at the top of the priority context stack.
 *
 * Keys defined by _object_ are given priority, which means that they can not be
 * overriden by other objects that will eventually enter the context stack.
 *
 * ```
 * // Derive a context with a priority `precious` key
 * context = [context contextByAddingProtectedObject:@{ @"precious": @"gold" }];
 *
 * // Derive a new context by attempting to override the `precious` key:
 * context = [context contextByAddingObject:@{ @"precious": @"lead" }];
 *
 * // Priority keys can't be overriden
 * [context valueForMustacheKey:@"precious"];   // @"gold"
 * ```
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/security.md#priority-keys
 *
 * @param object  An object
 *
 * @return A new rendering context.
 *
 * @since v6.0
 */
- (instancetype)contextByAddingProtectedObject:(id)object AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Returns a new rendering context that is the copy of the receiver, and the
 * given object added at the top of the tag delegate stack.
 *
 * _tagDelegate_ will be notified of the rendering of all tags rendered from the
 * receiver or from contexts derived from the receiver.
 *
 * Unlike contextByAddingObject: and contextByAddingProtectedObject:,
 * _tagDelegate_ will not provide any key to the templates. It will only be
 * notified of the rendering of tags.
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/delegate.md
 *
 * @param tagDelegate  A tag delegate
 *
 * @return A new rendering context.
 *
 * @see GRMustacheTagDelegate
 *
 * @since v6.0
 */
- (instancetype)contextByAddingTagDelegate:(id<GRMustacheTagDelegate>)tagDelegate AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

////////////////////////////////////////////////////////////////////////////////
/// @name Fetching Values from the Context Stack
////////////////////////////////////////////////////////////////////////////////

/**
 * Returns the object at the top of the receiver's context stack.
 *
 * The returned object is the same as the one that would be rendered by a
 * `{{ . }}` tag.
 *
 * ```
 * user = ...;
 * context = [GRMustacheContext contextWithObject:user];
 * context.topMustacheObject;  // user
 * ```
 *
 * @return The object at the top of the receiver's context stack.
 *
 * @see contextWithObject:
 * @see contextByAddingObject:
 *
 * @since v6.7
 */
@property (nonatomic, readonly) id topMustacheObject AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Returns the value stored in the context stack for the given key.
 *
 * If you want the value for an full expression such as `user.name` or
 * `uppercase(user.name)`, use the hasValue:forMustacheExpression:error:
 * method.
 *
 * ### Search Pattern for valueForMustacheKey
 *
 * The Mustache value of any object for a given key is defined as:
 *
 * 1. If the object responds to the `objectForKeyedSubscript:` instance method,
 *    return the result of this method.
 *
 * 2. Otherwise, build the list of safe keys:
 *    a. If the object responds to the `safeMustacheKeys` class method defined
 *       by the `GRMustacheSafeKeyAccess` protocol, use this method.
 *    b. Otherwise, use the list of Objective-C properties declared with
 *       `@property`.
 *    c. If object is an instance of NSManagedObject, add all the attributes of
 *       its Core Data entity.
 *
 * 3. If the key belongs to the list of safe keys, return the result of the
 *    `valueForKey:` method, unless this method throws NSUndefinedKeyException.
 *
 * 4. Otherwise, return nil.
 *
 * Contexts with unsafe key access skip the key validation step.
 *
 * In this method, the following search pattern is used:
 *
 * 1. Searches the priority context stack for an object that has a non-nil
 *    Mustache value for the key.
 *
 * 2. Otherwise (irrelevant priority context stack), search the context stack
 *    for an object that has a non-nil Mustache value for the key.
 *
 * 3. If none of the above situations occurs, returns nil.
 *
 * **Companion guides:** https://github.com/groue/GRMustache/blob/master/Guides/runtime.md,
 * https://github.com/groue/GRMustache/blob/master/Guides/view_model.md
 *
 * @param key  a key such as @"name"
 *
 * @return The value found in the context stack for the given key.
 *
 * @see contextWithUnsafeKeyAccess
 * @see hasValue:forMustacheExpression:error:
 *
 * @since v6.6
 */
- (id)valueForMustacheKey:(NSString *)key AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Evaluates an expression such as `name`, or `uppercase(user.name)`.
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/view_model.md
 *
 * @param value       Upon return contains the value of the expression.
 * @param expression  An expression.
 * @param error       If there is an error computing the value, upon return
 *                    contains an NSError object that describes the problem.
 *
 * @return YES if the value could be computed.
 *
 * @see valueForMustacheKey:
 *
 * @since v6.8
 */
- (BOOL)hasValue:(id *)value forMustacheExpression:(NSString *)expression error:(NSError **)error AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

////////////////////////////////////////////////////////////////////////////////
/// @name Unsafe Key Access
////////////////////////////////////////////////////////////////////////////////

/**
 * Returns whether this context allows unsafe key access or not.
 *
 * @since v7.0
 */
@property (nonatomic, readonly) BOOL unsafeKeyAccess AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Returns a new context with unsafe key access.
 *
 * Unsafe key access allows this context, and all contexts derived from it, to
 * access keys that are normally forbidden: keys that are not declared as
 * Objective-C properties, or keys that do not belong to the result of the
 * `safeMustacheKeys` method.
 *
 * Compare:
 *
 * ```
 * @interface DBRecord : NSObject
 * - (void)deleteRecord;
 * @end
 *
 * @implementation DBRecord
 * - (void)deleteRecord
 * {
 *     NSLog(@"Oooops, your record was just deleted!");
 * }
 * @end
 *
 * DBRecord *record = ...;
 * NSString *templateString = @"{{ deleteRecord }}";
 * GRMustacheTemplate * template = [GRMustacheTemplate templateWithString:templateString error:NULL];
 *
 * // Safe rendering of the dangerous template: record is not deleted.
 * [template renderObject:record error:NULL];
 *
 * // Unsafe rendering of the dangerous template: record is deleted.
 * template.baseContext = [GRMustacheContext contextWithUnsafeKeyAccess];
 * [template renderObject:record error:NULL];
 * ```
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/security.md
 *
 * @see GRMustacheSafeKeyAccess
 *
 * @since v7.0
 */
+ (instancetype)contextWithUnsafeKeyAccess AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

/**
 * Returns a new rendering context that is the copy of the receiver, with unsafe
 * key access.
 *
 * Unsafe key access allows this context, and all contexts derived from it, to
 * access keys that are normally forbidden: keys that are not declared as
 * Objective-C properties, or keys that do not belong to the result of the
 * `safeMustacheKeys` method.
 *
 * Compare:
 *
 * ```
 * @interface DBRecord : NSObject
 * - (void)deleteRecord;
 * @end
 *
 * @implementation DBRecord
 * - (void)deleteRecord
 * {
 *     NSLog(@"Oooops, your record was just deleted!");
 * }
 * @end
 *
 * DBRecord *record = ...;
 * NSString *templateString = @"{{ deleteRecord }}";
 * GRMustacheTemplate * template = [GRMustacheTemplate templateWithString:templateString error:NULL];
 *
 * // Safe rendering of the dangerous template: record is not deleted.
 * [template renderObject:record error:NULL];
 *
 * // Unsafe rendering of the dangerous template: record is deleted.
 * template.baseContext = [template.baseContext contextWithUnsafeKeyAccess];
 * [template renderObject:record error:NULL];
 * ```
 *
 * **Companion guide:** https://github.com/groue/GRMustache/blob/master/Guides/security.md
 *
 * @see GRMustacheSafeKeyAccess
 *
 * @since v7.0
 */
- (instancetype)contextWithUnsafeKeyAccess AVAILABLE_GRMUSTACHE_VERSION_7_0_AND_LATER;

@end


text:
function ready() {
    /*
    var closeBtn = new Image();
    closeBtn.style.width = "30";
    closeBtn.style.height = "30";
    closeBtn.src = "../sad-web-root/images/closebtn.png";

    var closeDiv = document.getElementById("close");
    closeDiv.appendChild(closeBtn);
    */
}

function clickCloseButton() {
    ormma.hide();
}

function clickImage() {
    ormma.open("%@", false);
//    window.location.href = "%@";

}

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::accessor Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

tbb

interface5

concurrent_hash_map

accessor

Public Types |
Public Member Functions |
List of all members

tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::accessor Class Reference

Allows write access to elements and combines data access, locking, and garbage collection.
 More...

#include <concurrent_hash_map.h>

Inheritance diagram for tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::accessor:

  <map id="tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::accessor_map" name="tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::accessor_map">
<area href="a00053.html" title="Combines data access, locking, and garbage collection. " alt="tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::const_accessor" shape="rect" coords="0,56,488,80"/>
</map>

Public Types

typedef

concurrent_hash_map::value_type 	value_type

 	Type of value.

 Public Types inherited from tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::const_accessor

typedef const

concurrent_hash_map::value_type 	value_type

 	Type of value.

Public Member Functions

reference 	operator* () const

 	Return reference to associated value in hash table.

pointer 	operator-> () const

 	Return pointer to associated value in hash table.

 Public Member Functions inherited from tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::const_accessor

bool 	empty () const

 	True if result is empty.

void 	release ()

 	Set to null.

const_reference 	operator* () const

 	Return reference to associated value in hash table.

const_pointer 	operator-> () const

 	Return pointer to associated value in hash table.

 	const_accessor ()

 	Create empty result.

 	~const_accessor ()

 	Destroy result after releasing the underlying reference.

Additional Inherited Members

 Protected Member Functions inherited from tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::const_accessor

bool 	is_writer ()

 Protected Attributes inherited from tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::const_accessor

node * 	my_node

hashcode_t 	my_hash

Detailed Description

template<typename Key, typename T, typename HashCompare = tbb_hash_compare<Key>, typename A = tbb_allocator<std::pair<Key, T> >>

class tbb::interface5::concurrent_hash_map< Key, T, HashCompare, A >::accessor

Allows write access to elements and combines data access, locking, and garbage collection.

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

concurrent_hash_map.h

Copyright © 2005-2018 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
'use strict';

jest.unmock('../Button.tsx');

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as TestUtils from 'react-addons-test-utils';

import Button from '../Button.tsx';

describe('Button', () => {

  const button = TestUtils.renderIntoDocument(
    <Button>foo</Button>
  );

  const buttonNode = ReactDOM.findDOMNode(button);

  it('renders button', () => {
    expect(buttonNode).not.toBeNull();
  });

  it('should print correct text', () => {
    expect(buttonNode.textContent).toBe('foo');
  });
});


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {
	public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
		$this->load->model('m_home');
		//$this->load->model('m_access');

    }

	public function index(){
		if(!isset($this->session->userdata['data'])){
			redirect(base_url('index.php/admin/home/login'));
		}else{
			redirect(base_url('index.php/admin/home/home'));
		}
	}

	public function login(){
		$this->load->view('admin/pages/login');
	}

	public function home(){
		redirect(base_url('index.php/admin/product/list_product '));
	}

	public function validasi(){

		$this->m_home->login_validation($_POST);
	}

    public function table_dinamic(){
        $data['view'] = 'pages/simpledinamic_pages';
        $this->load->view('admin/index', $data);
	}

    public function table_jgrid(){
        $data['view'] = 'pages/jgrid_pages';
        $this->load->view('admin/index', $data);
	}
}


text:
namespace sharpbox.Common.Io
{
    /// <summary>
    /// @CREDIT: Code and notes from http://blog.danskingdom.com/saving-and-loading-a-c-objects-data-to-an-xml-json-or-binary-file/
    /// </summary>
    public interface IStrategy
    {
        /// <summary>
        /// Writes the given object instance to an XML file.
        /// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
        /// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
        /// <para>Object type must have a parameterless constructor.</para>
        /// </summary>
        /// <typeparam name="T">The type of object being written to the file.</typeparam>
        /// <param name="filePath">The file path to write the object instance to.</param>
        /// <param name="objectToWrite">The object instance to write to the file.</param>
        /// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
        void Write<T>(string filePath, T objectToWrite, bool append = false) where T : new();

        /// <summary>
        /// Reads an object instance from an XML file.
        /// <para>Object type must have a parameterless constructor.</para>
        /// </summary>
        /// <typeparam name="T">The type of object to read from the file.</typeparam>
        /// <param name="dispatcher"></param>
        /// <param name="filePath">The file path to read the object instance from.</param>
        /// <returns>Returns a new instance of the object read from the XML file.</returns>
        T Read<T>(string filePath) where T : new();

        void Delete<T>(string filePath) where T : new();

        void Replace<T>(string originalFile, string newFile, string backupFile, T objectToWrite) where T : new();
    }
}


text:
require 'morpheus/api/api_client'
# There is no authentication required for this API.
class Morpheus::SetupInterface < Morpheus::APIClient

  # no Authorization header is required
  def authorization_required?
    false
  end

  # health checks use a relatively small timeout by default
  def default_timeout
    5
  end

  def get(params={})
    headers = {params: params}
    # use access token if authenticated
    headers[:authorization] = "Bearer #{@access_token}" if @access_token
    execute(method: :get, url: "/api/setup", headers: headers)
  end

  #this should go away and just use
  def check(params={}, timeout=5)
    headers = {params: params}
    # use access token if authenticated
    headers[:authorization] = "Bearer #{@access_token}" if @access_token
    execute(method: :get, url: "/api/setup/check", headers: headers, timeout: timeout)
  end

  # you can only use this successfully one time on a fresh install.
  def init(payload={})
    headers = { 'Content-Type' => 'application/json' }
    execute(method: :post, url: "/api/setup/init", headers: headers, payload: payload.to_json)
  end

  def hub_register(payload={})
    headers = { 'Content-Type' => 'application/json' }
    execute(method: :post, url: "/api/setup/hub-register", headers: headers, payload: payload.to_json)
  end

  def hub_login(payload={})
    headers = { 'Content-Type' => 'application/json' }
    execute(method: :post, url: "/api/setup/hub-login", headers: headers, payload: payload.to_json)
  end

end


text:
const AWS = require('aws-sdk')
const NodeClient = require('aws-mqtt/lib/NodeClient')
const config = require('../config') // NOTE: make sure to copy config.example.js to config.js and fill in your values
const { logEventsToConsole } = require('./utils')

// Initialize the Amazon Cognito credentials provider
AWS.config.region = config.aws.region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: config.aws.cognito.identityPoolId,
})

const client = new NodeClient({
  region: AWS.config.region,
  endpoint: config.aws.iot.endpoint,
  credentials: AWS.config.credentials,
  clientId: 'mqtt-time-publisher-' + Math.floor(Math.random() * 100000 + 1),
})

const Timer = (fn, interval) => {
  let t
  return {
    start: () => {
      t = setInterval(fn, interval)
    },
    stop: () => {
      clearInterval(t)
    },
  }
}

client.on('connect', () => {
  console.log('Successfully connected to AWS IoT Broker!  :-)')
  client.subscribe(config.topics.chat)
})
client.on('message', (topic, message) => {
  console.log(`Incoming message from ${topic}: ${message}`)
})

const timeAnnouncer = Timer(() => {
  client.publish(config.topics.time, `Time now is ${Date.now()}`)
}, 3000)

client.on('connect', timeAnnouncer.start)
client.on('close', timeAnnouncer.stop)
client.on('offline', timeAnnouncer.stop)

logEventsToConsole(client)


text:
Hello, Rails!

## Initialization

```bash
gem install bundler
gem install rails -v 4.2.2
rails _4.2.2_ new /path/to/rails-playground
```

## Scaffolding

```bash
rails generate scaffold User name:string email:string
```


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Ike.io  — Humility </title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="alternate" type="application/atom+xml" title="Ike.io" href="http://ike.io/feed.xml">

        <meta name="description" content="nadjetey's blog on wangana - jekyll theme" />

        <meta name="keywords" content="thoughts">

        <link rel="icon" type="image/png" href="http://ike.io/favicon.png">

        <link rel="stylesheet" href="/assets/css/main.css">
        <link href='http://fonts.googleapis.com/css?family=Poly:400,400italic' rel='stylesheet' type='text/css'>

Close

                        Close

Isaac Lewis

Home

About

Tags

Menu

                    navigation

    		Humility

    			Posted

                by Isaac Lewis,

    			<time class="timeago" datetime="Thursday 9 October 2014">9 October 2014</time>

For the record, I'm still learning how to do this whole "life" thing.

Recently, I made the really invigorating discovery that I can be a grade-A asshole while simultaneously thinking that I am helping those around me.

In continuing to examine my assumptions, I've started to see the "black boxes" in my thinking – swaths of my perception that I'm blind to. Sometimes, they exist because I have inaccurate data about a project that keeps me from seeing the reality of whats going on, but other times it's myself that I can't see, which keeps me from being in-tune with how my actions affect what I'm doing or the people around me.

Recently, I had one of those big black blind boxes planted directly over a particular relationship with a teammate. I was completely unable to see that I had done nothing to build trust with them, but was instead micromanaging their portion of the project, and making them feel disempowered to bring their expertise to the table. The surprising thing to me wasn't that I was basically managing the project very poorly – I am very aware of my baby-level management skills – what surprised me was that, yet again, I couldn't see it. It was only after my interactions were played back to me by another teammate that I saw how incredibly rude and arrogant I had been – in what I thought was the best interest of the project.

Black boxes are sneaky – they don't show themselves on their own, until it's too late. I need to learn how to hold a mental candle up to everything I do, so that I can see, if not the actual wrong-ness of my actions, at least the black boxes themselves. If I can see the boxes, I'll be able to work backwards and find out what I'm missing.

But that's not the point.

We all have black boxes in our minds. We all struggle to see how our actions affect others, how they affect projects we're working on, and how they affect our own selves. That's something I will always struggle with, and I hope I'll continue to make progress and get better at uncovering those boxes.

The point is: what do you do once you've found them? That's where humility becomes the most crucial thing of all.

My actions towards my teammate were really wrong. I felt I was in the right, arguing for the betterment of the project at hand, but in the process, I really hurt someone by making them feel that they had nothing to contribute. I walked all over them in the interest of "making things better". At the time, I didn't think that it would be possible to heal that relationship in a way that wouldn't leave a long, awkward aftertaste.

After some wonderful soul-searching with another teammate, I was counseled to simply humbly make amends, let that feeling of asshole-being really sink in and sting, think of the situation from the other's perspective, and genuinely admit to being that asshole that I never wanted to be.

Super simple, kindergarten human-being 101, there.

All I can say is that genuine humility, without expectation of forgiveness or "results", is miraculous. The amount of healing that can be had, both for your own being and for a relationship, by simply getting down and being vulnerable in your own shortcomings, is incredible. My teammate and I are on much better terms than we ever had been.

By focusing on humility in my management and relationships, I hope I'll be able to more clearly see the black boxes. At this point, I'm pretty confident that humility is the secret to the whole "life" thing.

Go forth and be humble, folks.

Posted

            Thursday 9 October 2014

            by @_crossdiver

             Share

You might also like:

                    Assumptions

                    Thanksgiving

                    The indieweb

Please enable JavaScript to view the comments powered by Disqus.

            3


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Anansi: inc/PortIPAddr.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Anansi

Main Page

Classes

Files

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

File List

File Members

 All Classes Files Functions Variables Typedefs Macros

PortIPAddr.h

Go to the documentation of this file.

    1 #ifndef PortIPAddr_h

    2 #define PortIPAddr_h

    3 #include <iterator>

    4 #include <vector>

    5 #include <string>

    6 #include <Types.h>

    7 #include <Port.h>

    8 #include <Comms.h>

    9

   10 class PortIPAddr : public Port {

   11

   12 public:

   13      PortIPAddr(int id);

   14     void read();

   15     void handleData(char *data, int dataSize);

   16     void write(vector<byte> serializedPacket);

   17

   18     packet_t getPacketFromBuffer();

   19

   20 };

   21

   22 #endif

Port

Definition: Port.h:6

Types.h

PortIPAddr::write

void write(vector< byte > serializedPacket)

Definition: PortIPAddr.cpp:146

PortIPAddr::getPacketFromBuffer

packet_t getPacketFromBuffer()

Definition: PortIPAddr.cpp:150

PortIPAddr::handleData

void handleData(char *data, int dataSize)

Definition: PortIPAddr.cpp:68

PortIPAddr

Definition: PortIPAddr.h:10

PortIPAddr::PortIPAddr

PortIPAddr(int id)

Definition: PortIPAddr.cpp:22

Comms.h

Port.h

packet_t

Definition: Types.h:26

PortIPAddr::read

void read()

Definition: PortIPAddr.cpp:48

inc

PortIPAddr.h

Generated on Thu May 4 2017 13:21:41 for Anansi by

     1.8.6


text:
package pl.srw.todos.di.component;

import javax.inject.Singleton;

import dagger.Component;
import pl.srw.todos.di.module.ApplicationModule;

@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent{

    MainActivityComponent getMainActivityComponent();
}


text:
import React from 'react';
import {useSelector} from 'react-redux';

import {
  CircularProgress,
  IconButton,
  Switch,
  Tooltip,
} from '@material-ui/core';
import {
  CheckCircleOutline,
  Sync,
} from '@material-ui/icons';

import { ICategoryModel, IUserModel } from '../../../../models';
import { ContainerHeader, OverflowContainer } from '../../../components/OverflowContainer';
import { activateCommentSource, syncCommentSource } from '../../../platform/dataService';
import { getCategories } from '../../../stores/categories';
import { flexCenter, GUTTER_DEFAULT_SPACING, PALE_COLOR, SCRIM_Z_INDEX } from '../../../styles';
import { css, stylesheet } from '../../../utilx';

const STYLES = stylesheet({
  heading: {
    fontSize: '18px',
  },

  subheading: {
    fontSize: '16px',
    marginTop: `${36}px`,
  },

  headerRow: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
  },

  row: {
    marginTop: `${12}px`,
    marginBottom: `${12}px`,
    overflow: 'hidden',
    display: 'flex',
    alignItems: 'center',
  },

  label: {
    fontWeight: 'bold',
    marginRight: '24px',
    minWidth: '120px',
    display: 'flex',
    alignItems: 'left',
  },

  closeButton: {
    background: 'none',
    border: 'none',
    position: 'absolute',
    right: GUTTER_DEFAULT_SPACING,
    top: GUTTER_DEFAULT_SPACING,
    cursor: 'pointer',
    zIndex: SCRIM_Z_INDEX,
    ':focus': {
      outline: 'none',
      background: PALE_COLOR,
    },
  },

  userTableCell: {
    textAlign: 'left',
    padding: '5px 20px 5px 0',
  },

  userTableCellButton: {
    width: '49px',
    height: '49px',
    ...flexCenter,
  },
});

interface IYoutubeCategoryProps {
  category: ICategoryModel;
}

function YoutubeCategory(props: IYoutubeCategoryProps) {
  const {
    category,
  } = props;

  const [changingActive, setChangingActive] = React.useState<boolean>(false);
  const [syncingComments, setSyncingComments] = React.useState<boolean>(false);

  async function activate() {
    setChangingActive(true);
    await activateCommentSource(category.id, !category.isActive);
    setChangingActive(false);
  }

  async function sync() {
    setSyncingComments(true);
    await syncCommentSource(category.id);
    setTimeout(() => setSyncingComments(false), 3000);
  }

  return (

      {category.label}
      {category.sourceId}

        <Tooltip
          title={category.isActive ? 'Comments will sync every 5 minute' : 'Automatic comment sync is disabled'}
        >
          <Switch color="primary" checked={category.isActive} onChange={activate} disabled={changingActive}/>
        </Tooltip>

          <Tooltip title="Load recent articles and comments">
            {syncingComments ?
              <CircularProgress color="primary" size={30}/> :
              <IconButton onClick={sync}><Sync/></IconButton>
            }
          </Tooltip>

  );
}

export interface IEditYouTubeUserProps {
  onClickClose(e: React.FormEvent<any>): any;
  onUserUpdate(user: IUserModel): Promise<void>;
  user?: IUserModel;
}

export function EditYouTubeUser(props: IEditYouTubeUserProps) {
  const [changingActive, setChangingActive] = React.useState<boolean>(false);

  async function onIsActiveChange() {
    setChangingActive(true);
    await props.onUserUpdate({...user, isActive: !user.isActive});
    setChangingActive(false);
  }

  const {
    user,
    onClickClose,
  } = props;

  const hasError = !!user.extra.lastError;
  const categories = useSelector(getCategories);
  const relevant = categories.filter((c) => c.ownerId === user.id);

  return (
    <OverflowContainer
      header={<ContainerHeader onClickClose={onClickClose}>Settings for YouTube account</ContainerHeader>}
      body={(

            Youtube Name

{user.name}

            Youtube ID

{user.email}

            Is Active

              <Switch
                checked={user.isActive}
                color="primary"
                disabled={hasError || changingActive}
                onChange={onIsActiveChange}
              />

            Last Error

              {hasError ? user.extra.lastError.message : 'No error'}
              {hasError && (
                <Tooltip title="Reset errors and reactivate" style={{marginLeft: '20px'}}>
                  <IconButton color="primary" onClick={onIsActiveChange}><CheckCircleOutline/></IconButton>
                </Tooltip>
              )}

Channels

                Name

                YouTube ID

                Is Active

              {relevant.map((c) => (<YoutubeCategory key={c.id} category={c}/>))}

          <p style={{marginTop: `${31}px`}}>
            Activating moderation of a YouTube channel puts it into post-moderation mode.
            Comments will not be visible to users until you mark them as approved.

            Syncing history data will make sure the last few hundred comments are available
            in Moderator, even if they've already been published.

      )}
    />
  );
}


text:
<!DOCTYPE html>
<html>
  <head>
    <title>WebRTC workshop: step 1</title>

    <!-- CSS will go here -->
    <style></style>
  </head>

  <body>
    <!-- HTML will go here -->

    <!-- JavaScript will go here -->
    <script></script>
  </body>
</html>


text:
require 'spec_helper'

require 'vigilem/win32_api'

# @todo brittle and hags, need to use a double for the brittle calls, and
# seperate out teh os specific stuff
describe Vigilem::Win32API::Rubyized do

  after(:example) do
    flush
  end

  let(:handler_class) { ::Vigilem::Win32API::InputSystemHandler }
  let(:handler) { handler_class.new }

  let(:adapt) do
    class WinRubyAPIAdapter
      include Vigilem::Core::Adapters::Adapter
      include Vigilem::Win32API::Rubyized
      def initialize(lnk=Vigilem::Win32API::InputSystemHandler.new)
        initialize_adapter(lnk)
        self.win32_api_rubyized_source = lnk
      end
    end
    WinRubyAPIAdapter.new.attach(handler)
  end

  describe '#get_std_handle' do
    it 'calls link.GetStdHandle' do
      expect(adapt.send(:win32_api_rubyized_source)).to receive(:GetStdHandle).with(Vigilem::Win32API::STD_INPUT_HANDLE)
      adapt.get_std_handle()
    end
  end

  context 'methods except #get_std_handle,' do
    let(:pointer_args) do
      {
        :lpBuffer => Vigilem::Win32API::PINPUT_RECORD.new(1),
        :lpNumberOfEventsRead => FFI::MemoryPointer.new(:DWORD, 1)
      }
    end

    let(:non_pointer_args) do
      {
        :hConsoleInput => adapt.get_std_handle,
        :nLength => 1,
      }
    end

    let(:all_non_pointer_args) do
      non_pointer_args.merge( :blocking => nil )
    end

    let(:all_args) do
      non_pointer_args.merge(pointer_args)
    end

    context 'private' do
      describe '#_options' do
        it 'returns default arguments' do
          arg = adapt.send(:_options)

          # @todo
          expect(arg).to match a_hash_including(
              #{ :lpBuffer => instance_of(Vigilem::Win32API::PINPUT_RECORD),
              #  :lpNumberOfEventsRead => kind_of(FFI::MemoryPointer)
              #}.merge(non_pointer_args)
              non_pointer_args
            )

          #expect(arg).to include(:lpBuffer => instance_of(Vigilem::Win32API::PINPUT_RECORD))
          #expect(arg).to include(non_pointer_args)
            # a_kind_of/instance_of(FFI::MemoryPointer) throws `Invalid Memory'
          #expect(arg[:lpNumberOfEventsRead]).to be_a(FFI::MemoryPointer)
        end

        it 'configures the default lpBuffer based on nLength' do
          args = adapt.send(:_options, :nLength => 3)
          expect([args[:lpBuffer].max_size, args[:nLength]]).to eql([3, 3])
        end

        it 'configures the default nLength based on lpBuffer.size' do
          args = adapt.send(:_options, :lpBuffer => [nil] * 4)
          expect([args[:lpBuffer].size, args[:nLength]]).to eql([4, 4])
        end
      end
    end

    describe '#peek_console_input' do
      it %q(won't block when the queue is empty) do
        flush
        expect do
          Timeout::timeout(5) do
            adapt.peek_console_input()
          end
        end.to_not raise_error
      end

      it 'calls link.PeekConsoleInput' do
        expect(adapt.send(:win32_api_rubyized_source)).to receive(:PeekConsoleInput)
        adapt.peek_console_input()
      end
    end

    describe '#read_console_input' do
      # need to allocConsole so it's isolated
=begin
      it %q(will block when the queue is empty) do
        flush
        expect do
          Timeout::timeout(5) do
            adapt.read_console_input()
          end
        end.to raise_error(Timeout::Error)
      end
=end
      it %q(won't block when the buffer has somthing in it) do
        write_console_input_test
        expect do
          Timeout::timeout(5) do
            adapt.read_console_input()
          end
        end.to_not raise_error
      end

      it 'calls link.ReadConsoleInput' do
        expect(adapt.send(:win32_api_rubyized_source)).to receive(:ReadConsoleInput)
        adapt.read_console_input()
      end
    end

  end

end


text: package connectcases


text:
from py2neo.compat import xstr
from py2neo.database.status import GraphError
from py2neo.types import Relatable

class NodePointer(Relatable):
    """ Pointer to a :class:`Node` object. This can be used in a batch
    context to point to a node not yet created.
    """

    #: The address or index to which this pointer points.
    address = None

    def __init__(self, address):
        self.address = address

    def __repr__(self):
        return "<NodePointer address=%s>" % self.address

    def __str__(self):
        return xstr(self.__unicode__())

    def __unicode__(self):
        return "{%s}" % self.address

    def __eq__(self, other):
        return self.address == other.address

    def __ne__(self, other):
        return not self.__eq__(other)

    def __hash__(self):
        return hash(self.address)

class BatchError(GraphError):
    """ Wraps a base :class:`py2neo.GraphError` within a batch context.
    """

    batch = None
    job_id = None
    status_code = None
    uri = None
    location = None

    def __init__(self, message, batch, job_id, status_code, uri, location=None, **kwargs):
        GraphError.__init__(self, message, **kwargs)
        self.batch = batch
        self.job_id = job_id
        self.status_code = status_code
        self.uri = uri
        self.location = location


text:
<?php
/**
 * The contents of this file was generated using the WSDLs as provided by eBay.
 *
 * DO NOT EDIT THIS FILE!
 */

namespace DTS\eBaySDK\Trading\Enums;

/**
 *
 */
class SellingManagerSearchTypeCodeType
{
    const C_BUYER_EMAIL = 'BuyerEmail';
    const C_BUYER_FULL_NAME = 'BuyerFullName';
    const C_BUYER_USERID = 'BuyerUserID';
    const C_CUSTOM_CODE = 'CustomCode';
    const C_CUSTOM_LABEL = 'CustomLabel';
    const C_ITEMID = 'ItemID';
    const C_PRODUCTID = 'ProductID';
    const C_PRODUCT_NAME = 'ProductName';
    const C_SALE_RECORDID = 'SaleRecordID';
    const C_TITLE = 'Title';
}


text:
/* $Id: UsbTest.cpp $ */
/** @file
 * UsbTest - User frontend for the Linux usbtest USB test and benchmarking module.
 *           Integrates with our test framework for nice outputs.
 */

/*
 * Copyright (C) 2014-2015 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include <iprt/err.h>
#include <iprt/getopt.h>
#include <iprt/path.h>
#include <iprt/param.h>
#include <iprt/process.h>
#include <iprt/stream.h>
#include <iprt/string.h>
#include <iprt/test.h>
#include <iprt/file.h>

#include <unistd.h>
#include <errno.h>
#include <limits.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <sys/ioctl.h>
#include <linux/usbdevice_fs.h>

/*******************************************************************************
*   Defined Constants And Macros                                               *
*******************************************************************************/

/** Number of tests implemented at the moment. */
#define USBTEST_TEST_CASES      25

/*******************************************************************************
*   Structures and Typedefs                                                    *
*******************************************************************************/

/**
 * USB test request data.
 * There is no public header with this information so we define it ourself here.
 */
typedef struct USBTESTPARMS
{
    /** Specifies the test to run. */
    uint32_t        idxTest;
    /** How many iterations the test should be executed. */
    uint32_t        cIterations;
    /** Size of the data packets. */
    uint32_t        cbData;
    /** Size of  */
    uint32_t        cbVariation;
    /** Length of the S/G list for the test. */
    uint32_t        cSgLength;
    /** Returned time data after completing the test. */
    struct timeval  TimeTest;
} USBTESTPARAMS;
/** Pointer to a test parameter structure. */
typedef USBTESTPARAMS *PUSBTESTPARAMS;

/**
 * USB device descriptor. Used to search for the test device based
 * on the vendor and product id.
 */
#pragma pack(1)
typedef struct USBDEVDESC
{
    uint8_t  bLength;
    uint8_t  bDescriptorType;
    uint16_t bcdUSB;
    uint8_t  bDeviceClass;
    uint8_t  bDeviceSubClass;
    uint8_t  bDeviceProtocol;
    uint8_t  bMaxPacketSize0;
    uint16_t idVendor;
    uint16_t idProduct;
    uint16_t bcdDevice;
    uint8_t  iManufacturer;
    uint8_t  iProduct;
    uint8_t  iSerialNumber;
    uint8_t  bNumConfigurations;
} USBDEVDESC;
#pragma pack()

#define USBTEST_REQUEST _IOWR('U', 100, USBTESTPARMS)

/*******************************************************************************
*   Global Variables                                                           *
*******************************************************************************/

/** Command line parameters */
static const RTGETOPTDEF g_aCmdOptions[] =
{
    {"--device",           'd', RTGETOPT_REQ_STRING },
    {"--help",             'h', RTGETOPT_REQ_NOTHING}
};

/** (Sort of) Descriptive test descriptions. */
static const char *g_apszTests[] =
{
    "NOP",
    "Non-queued Bulk write",
    "Non-queued Bulk read",
    "Non-queued Bulk write variabe size",
    "Non-queued Bulk read variabe size",
    "Queued Bulk write",
    "Queued Bulk read",
    "Queued Bulk write variabe size",
    "Queued Bulk read variabe size",
    "Chapter 9 Control Test",
    "Queued control messaging",
    "Unlink reads",
    "Unlink writes",
    "Set/Clear halts",
    "Control writes",
    "Isochronous write",
    "Isochronous read",
    "Bulk write unaligned (DMA)",
    "Bulk read unaligned (DMA)",
    "Bulk write unaligned (no DMA)",
    "Bulk read unaligned (no DMA)",
    "Control writes unaligned",
    "Isochronous write unaligned",
    "Isochronous read unaligned",
    "Unlink queued Bulk"
};
AssertCompile(RT_ELEMENTS(g_apszTests) == USBTEST_TEST_CASES);

/** The test handle. */
static RTTEST g_hTest;

static void usbTestUsage(PRTSTREAM pStrm)
{
    char szExec[RTPATH_MAX];
    RTStrmPrintf(pStrm, "usage: %s [options]\n",
                 RTPathFilename(RTProcGetExecutablePath(szExec, sizeof(szExec))));
    RTStrmPrintf(pStrm, "\n");
    RTStrmPrintf(pStrm, "options: \n");

    for (unsigned i = 0; i < RT_ELEMENTS(g_aCmdOptions); i++)
    {
        const char *pszHelp;
        switch (g_aCmdOptions[i].iShort)
        {
            case 'h':
                pszHelp = "Displays this help and exit";
                break;
            case 'd':
                pszHelp = "Use the specified test device";
                break;
            default:
                pszHelp = "Option undocumented";
                break;
        }
        char szOpt[256];
        RTStrPrintf(szOpt, sizeof(szOpt), "%s, -%c", g_aCmdOptions[i].pszLong, g_aCmdOptions[i].iShort);
        RTStrmPrintf(pStrm, "  %-20s%s\n", szOpt, pszHelp);
    }
}

/**
 * Search for a USB test device and return the device path.
 *
 * @returns Path to the USB test device or NULL if none was found.
 */
static char *usbTestFindDevice(void)
{
    /*
     * Very crude and quick way to search for the correct test device.
     * Assumption is that the path looks like /dev/bus/usb/%3d/%3d.
     */
    uint8_t uBus = 1;
    bool fBusExists = false;
    char aszDevPath[64];

    RT_ZERO(aszDevPath);

    do
    {
        RTStrPrintf(aszDevPath, sizeof(aszDevPath), "/dev/bus/usb/%03d", uBus);

        fBusExists = RTPathExists(aszDevPath);

        if (fBusExists)
        {
            /* Check every device. */
            bool fDevExists = false;
            uint8_t uDev = 1;

            do
            {
                RTStrPrintf(aszDevPath, sizeof(aszDevPath), "/dev/bus/usb/%03d/%03d", uBus, uDev);

                fDevExists = RTPathExists(aszDevPath);

                if (fDevExists)
                {
                    RTFILE hFileDev;
                    int rc = RTFileOpen(&hFileDev, aszDevPath, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
                    if (RT_SUCCESS(rc))
                    {
                        USBDEVDESC DevDesc;

                        rc = RTFileRead(hFileDev, &DevDesc, sizeof(DevDesc), NULL);
                        RTFileClose(hFileDev);

                        if (   RT_SUCCESS(rc)
                            && DevDesc.idVendor == 0x0525
                            && DevDesc.idProduct == 0xa4a0)
                            return RTStrDup(aszDevPath);
                    }
                }

                uDev++;
            } while (fDevExists);
        }

        uBus++;
    } while (fBusExists);

    return NULL;
}

static int usbTestIoctl(int iDevFd, int iInterface, PUSBTESTPARAMS pParams)
{
    struct usbdevfs_ioctl IoCtlData;

    IoCtlData.ifno = iInterface;
    IoCtlData.ioctl_code = (int)USBTEST_REQUEST;
    IoCtlData.data = pParams;
    return ioctl(iDevFd, USBDEVFS_IOCTL, &IoCtlData);
}

/**
 * Test execution worker.
 *
 * @returns nothing.
 * @param   pszDevice    The device to use for testing.
 */
static void usbTestExec(const char *pszDevice)
{
    int iDevFd;

    RTTestSub(g_hTest, "Opening device");
    iDevFd = open(pszDevice, O_RDWR);
    if (iDevFd != -1)
    {
        USBTESTPARAMS Params;

        RTTestPassed(g_hTest, "Opening device successful\n");

        /*
         * Fill params with some defaults.
         * @todo: Make them configurable.
         */
        Params.cIterations = 1000;
        Params.cbData = 512;
        Params.cbVariation = 512;
        Params.cSgLength = 32;

        for (unsigned i = 0; i < USBTEST_TEST_CASES; i++)
        {
            RTTestSub(g_hTest, g_apszTests[i]);

            Params.idxTest = i;

            /* Assume the test interface has the number 0 for now. */
            int rcPosix = usbTestIoctl(iDevFd, 0, &Params);
            if (rcPosix < 0 && errno == EOPNOTSUPP)
            {
                RTTestSkipped(g_hTest, "Not supported");
                continue;
            }

            if (rcPosix < 0)
                RTTestFailed(g_hTest, "Test failed with %Rrc\n", RTErrConvertFromErrno(errno));
            else
            {
                uint64_t u64Ns = Params.TimeTest.tv_sec * RT_NS_1SEC + Params.TimeTest.tv_usec * RT_NS_1US;
                RTTestValue(g_hTest, "Runtime", u64Ns, RTTESTUNIT_NS);
            }
            RTTestSubDone(g_hTest);
        }

        close(iDevFd);
    }
    else
        RTTestFailed(g_hTest, "Opening device failed with %Rrc\n", RTErrConvertFromErrno(errno));

}

int main(int argc, char *argv[])
{
    /*
     * Init IPRT and globals.
     */
    int rc = RTTestInitAndCreate("UsbTest", &g_hTest);
    if (rc)
        return rc;

    /*
     * Default values.
     */
    const char *pszDevice = NULL;

    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, argc, argv, g_aCmdOptions, RT_ELEMENTS(g_aCmdOptions), 1, 0 /* fFlags */);
    while ((rc = RTGetOpt(&GetState, &ValueUnion)))
    {
        switch (rc)
        {
            case 'h':
                usbTestUsage(g_pStdOut);
                return RTEXITCODE_SUCCESS;
            case 'd':
                pszDevice = ValueUnion.psz;
                break;
            default:
                return RTGetOptPrintError(rc, &ValueUnion);
        }
    }

    /*
     * Start testing.
     */
    RTTestBanner(g_hTest);

    /* Find the first test device if none was given. */
    if (!pszDevice)
        pszDevice = usbTestFindDevice();

    if (pszDevice)
        usbTestExec(pszDevice);
    else
    {
        RTTestPrintf(g_hTest, RTTESTLVL_FAILURE, "Failed to find a test device\n");
        RTTestErrorInc(g_hTest);
    }

    RTEXITCODE rcExit = RTTestSummaryAndDestroy(g_hTest);
    return rcExit;
}


text:
<?php

namespace NEM\Mosaics\Dim;

use NEM\Models\MosaicDefinition;
use NEM\Models\MosaicProperties;
use NEM\Models\MosaicProperty;
use NEM\Models\MosaicLevy;
use NEM\Models\Mosaic;

/**
 * This is the Dim\Eur class
 *
 * This class defines the parameters of mosaic
 * definition of the asset `dim:eur` on the
 * NEM Mainnet Network.
 *
 * @link https://dimcoin.io
 */
class Eur
    extends MosaicDefinition
{
    /**
     * The `dim:eur` Total Coins Supply
     *
     * @var integer
     */
    const TOTAL_SUPPLY = 1000000000;

    /**
     * The `dim:eur` mosaics creator public key
     * in hexadecimal format.
     *
     * @var string
     */
    public $creator = "a1df5306355766bd2f9a64efdc089eb294be265987b3359093ae474c051d7d5a";

    /**
     * Overload of the getTotalSupply() method for fast
     * tracking with preconfigured mosaics.
     *
     * @return integer
     */
    public function getTotalSupply()
    {
        return self::TOTAL_SUPPLY;
    }

    /**
     * Mutator for `mosaic` relation.
     *
     * This will return a NIS compliant [MosaicId](https://bob.nem.ninja/docs/#mosaicId) object.
     *
     * @param   array   $mosaidId       Array should contain offsets `namespaceId` and `name`.
     * @return  \NEM\Models\Mosaic
     */
    public function id(array $mosaicId = null)
    {
        return new Mosaic($mosaicId ?: ["namespaceId" => "dim", "name" => "eur"]);
    }

    /**
     * Mutator for `levy` relation.
     *
     * This will return a NIS compliant [MosaicLevy](https://bob.nem.ninja/docs/#mosaicLevy) object.
     *
     * @param   array   $mosaidId       Array should contain offsets `type`, `recipient`, `mosaicId` and `fee`.
     * @return  \NEM\Models\MosaicLevy
     */
    public function levy(array $levy = null)
    {
        $data = $levy ?: [];
        return new MosaicLevy($data);
    }

    /**
     * Mutator for `properties` relation.
     *
     * This will return a NIS compliant collection of [MosaicProperties](https://bob.nem.ninja/docs/#mosaicProperties) object.
     *
     * @param   array   $properties       Array of MosaicProperty instances
     * @return  \NEM\Models\MosaicProperties
     */
    public function properties(array $properties = null)
    {
        $data = [
            new MosaicProperty(["name" => "divisibility", "value" => 2]),
            new MosaicProperty(["name" => "initialSupply", "value" => 1000000000]),
            new MosaicProperty(["name" => "supplyMutable", "value" => true]),
            new MosaicProperty(["name" => "transferable", "value" => true]),
        ];

        return new MosaicProperties($data);
    }
}


text:
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `sys_group`
-- ----------------------------
DROP TABLE IF EXISTS `sys_group`;
CREATE TABLE `sys_group` (
  `group_code` varchar(32) COLLATE utf8_bin NOT NULL,
  `description` varchar(256) COLLATE utf8_bin DEFAULT NULL,
  `group_name` varchar(32) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`group_code`),
  UNIQUE KEY `UK_hjt6w1tlr96fhnsbx7b0pv07d` (`group_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Table structure for `sys_rel_group_role`
-- ----------------------------
DROP TABLE IF EXISTS `sys_rel_group_role`;
CREATE TABLE `sys_rel_group_role` (
  `group_code` varchar(32) COLLATE utf8_bin NOT NULL,
  `role_code` varchar(32) COLLATE utf8_bin NOT NULL,
  KEY `FK_ltuphr8swtb08nojxqb0qsqy7` (`role_code`),
  KEY `FK_abr7r4mqxqu8u99kubu8drbok` (`group_code`),
  CONSTRAINT `FK_abr7r4mqxqu8u99kubu8drbok` FOREIGN KEY (`group_code`) REFERENCES `sys_group` (`group_code`),
  CONSTRAINT `FK_ltuphr8swtb08nojxqb0qsqy7` FOREIGN KEY (`role_code`) REFERENCES `sys_role` (`role_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Table structure for `sys_rel_group_user`
-- ----------------------------
DROP TABLE IF EXISTS `sys_rel_group_user`;
CREATE TABLE `sys_rel_group_user` (
  `group_code` varchar(32) COLLATE utf8_bin NOT NULL,
  `username` varchar(32) COLLATE utf8_bin NOT NULL,
  KEY `FK_a26na12qn944wp1dcyemh0qrb` (`username`),
  KEY `FK_a1144tm1abqqk6rfjgxe1k9yn` (`group_code`),
  CONSTRAINT `FK_a1144tm1abqqk6rfjgxe1k9yn` FOREIGN KEY (`group_code`) REFERENCES `sys_group` (`group_code`),
  CONSTRAINT `FK_a26na12qn944wp1dcyemh0qrb` FOREIGN KEY (`username`) REFERENCES `sys_user` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Table structure for `sys_rel_role_user`
-- ----------------------------
DROP TABLE IF EXISTS `sys_rel_role_user`;
CREATE TABLE `sys_rel_role_user` (
  `role_code` varchar(32) COLLATE utf8_bin NOT NULL,
  `username` varchar(32) COLLATE utf8_bin NOT NULL,
  KEY `FK_4n0mnot1nlftple5ume16nknt` (`username`),
  KEY `FK_atr0vutj85qvmn6otk13gtxu4` (`role_code`),
  CONSTRAINT `FK_atr0vutj85qvmn6otk13gtxu4` FOREIGN KEY (`role_code`) REFERENCES `sys_role` (`role_code`),
  CONSTRAINT `FK_4n0mnot1nlftple5ume16nknt` FOREIGN KEY (`username`) REFERENCES `sys_user` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Table structure for `sys_role`
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
  `role_code` varchar(32) COLLATE utf8_bin NOT NULL,
  `description` varchar(256) COLLATE utf8_bin DEFAULT NULL,
  `role_name` varchar(32) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`role_code`),
  UNIQUE KEY `UK_7kwex0745q0eycdwi4d2yihi3` (`role_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Table structure for `sys_user`
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
  `username` varchar(32) COLLATE utf8_bin NOT NULL,
  `email` varchar(32) COLLATE utf8_bin NOT NULL,
  `enabled` tinyint(4) NOT NULL,
  `password` varchar(32) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`username`),
  UNIQUE KEY `UK_ahtq5ew3v0kt1n7hf1sgp7p8l` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;


text:
require "test_helper"

class ArtifactMailerTest < ActionMailer::TestCase

end


text:
package com.agileEAP.workflow.repository;

import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Param;

import com.agileEAP.data.MyBatisRepository;
import com.agileEAP.workflow.entity.AgentItem;

/**
* 代理项Repository
* 通过@MapperScannerConfigurer扫描目录中的所有接口, 动态在Spring Context中生成实现.
* 方法名称必须与Mapper.xml中保持一致.
*
* @author trh
*/
@MyBatisRepository
public interface AgentItemRepository {
    AgentItem get(String id);

    List<AgentItem> search(Map<String, Object> parameters);

    List<AgentItem> searchByPage(Map<String, Object> parameters);

    long count(Map<String, Object> parameters);

    void save(AgentItem agentItem);

    void update(AgentItem agentItem);

    void updateByWhere(@Param("entity")AgentItem agentItem,@Param("parameters")Map<String, Object> parameters);

    void delete(String id);

    void deleteByWhere(Map<String, Object> parameters);

    void batchDelete(List<String> ids);
}


text:
namespace py = pybind11;

void EmitterModule(py::module m_sub){
    // ---------------------------------------
    // Emitter Class
    // ---------------------------------------
    py::class_<SPH::Emitter>(m_sub, "Emitter")
            .def(py::init<>([](SPH::FluidModel *model,
                               const unsigned int width, const unsigned int height,
                               const Vector3r &pos, const Matrix3r & rotation,
                               const Real velocity,
                               const unsigned int type = 0){
                return SPH::Emitter(model, width, height, pos, rotation, velocity, type);
            }))
            .def("emitParticles", &SPH::Emitter::emitParticles)
            .def("emitParticlesCircle", &SPH::Emitter::emitParticlesCircle)
            .def("getNextEmitTime", &SPH::Emitter::getNextEmitTime)
            .def("setNextEmitTime", &SPH::Emitter::setNextEmitTime)
            .def("setEmitStartTime", &SPH::Emitter::setEmitStartTime)
            .def("setEmitEndTime", &SPH::Emitter::setEmitEndTime)
            .def("getPosition", &SPH::Emitter::getPosition)
            .def("setPosition", &SPH::Emitter::setPosition)
            .def("getRotation", &SPH::Emitter::getRotation)
            .def("setRotation", &SPH::Emitter::setRotation)
            .def("getVelocity", &SPH::Emitter::getVelocity)
            .def("setVelocity", &SPH::Emitter::setVelocity)
            .def_static("getSize", &SPH::Emitter::getSize)
            .def("step", &SPH::Emitter::step)
            .def("reset", &SPH::Emitter::reset)
            .def("saveState", &SPH::Emitter::saveState)
            .def("loadState", &SPH::Emitter::loadState);

    py::bind_pointer_vector<std::vector<SPH::Emitter*>>(m_sub, "EmitterVector");

    // ---------------------------------------
    // Emitter System Class
    // ---------------------------------------
    py::class_<SPH::EmitterSystem>(m_sub, "EmitterSystem")
            .def(py::init<>([](SPH::FluidModel* model){
                return SPH::EmitterSystem(model);
            }))
            .def("enableReuseParticles", &SPH::EmitterSystem::enableReuseParticles)
            .def("disableReuseParticles", &SPH::EmitterSystem::disableReuseParticles)
            .def("addEmitter", &SPH::EmitterSystem::addEmitter)
            .def("numEmitters", &SPH::EmitterSystem::numEmitters)
            .def("getEmitters", &SPH::EmitterSystem::getEmitters, py::return_value_policy::reference_internal)
            .def("numReusedParticles", &SPH::EmitterSystem::numReusedParticles)
            .def("numEmittedParticles", &SPH::EmitterSystem::numEmittedParticles)
            .def("step", &SPH::EmitterSystem::step)
            .def("reset", &SPH::EmitterSystem::reset)
            .def("saveState", &SPH::EmitterSystem::saveState)
            .def("loadState", &SPH::EmitterSystem::loadState);

}


text:
package com.mongodb.internal.connection;

import com.mongodb.ServerAddress;

import javax.net.ssl.SSLParameters;

interface SniSslHelper {

    /**
     * Enable SNI.
     *
     * @param address       the server address
     * @param sslParameters the SSL parameters
     */
    void enableSni(ServerAddress address, SSLParameters sslParameters);
}


text:
layout:     post
author:     Christoph Broschinski
author_lnk: https://github.com/cbroschinski
title:      Leipzig University reports its 2017 APC expenditures
date:       2018-04-17 08:00:00
summary:
categories: [general, openAPC]
comments: true
---

[Leipzig University](https://www.uni-leipzig.de/) has updated its APC expenditures, the latest contribution provides data for the 2017 period.

[Leipzig University Library](http://www.ub.uni-leipzig.de) is in charge of the University's [Open Access Publishing Fund](https://www.ub.uni-leipzig.de/en/open-science/publishing-fund/), which is supported by the DFG under its [Open-Access Publishing Programme](http://www.dfg.de/en/research_funding/programmes/infrastructure/lis/funding_opportunities/open_access/).

Contact person is [Dr. Astrid Vieler](mailto:openaccess@ub.uni-leipzig.de).

## Cost data

The new dataset covers publication fees for 145 articles. Total expenditure amounts to 225 015€ and the average fee is 1 552€.

The following table shows the payments Leipzig University Library has made to publishers in 2017.

|                                                      | Articles| Fees paid in EURO| Mean Fee paid|
|:-----------------------------------------------------|--------:|-----------------:|-------------:|
|Springer Nature                                       |       64|            102890|          1608|
|Frontiers Media SA                                    |       20|             35795|          1790|
|Public Library of Science (PLoS)                      |       18|             28631|          1591|
|MDPI AG                                               |       14|             19967|          1426|
|Elsevier BV                                           |        5|              5209|          1042|
|Wiley-Blackwell                                       |        5|              6012|          1202|
|Copernicus GmbH                                       |        3|              3118|          1039|
|BMJ                                                   |        2|              3451|          1726|
|Dove Medical Press Ltd.                               |        2|              3651|          1825|
|Impact Journals, LLC                                  |        2|              3645|          1822|
|Ovid Technologies (Wolters Kluwer Health)             |        2|              2362|          1181|
|S. Karger AG                                          |        2|              2297|          1148|
|Hindawi Publishing Corporation                        |        1|               406|           406|
|Informa UK Limited                                    |        1|              1333|          1333|
|IOP Publishing                                        |        1|              1392|          1392|
|Journal of Artificial Societies and Social Simulation |        1|              1190|          1190|
|Oxford University Press (OUP)                         |        1|              1901|          1901|
|Schattauer GmbH                                       |        1|              1767|          1767|

## Overview

With the recent contribution included, the overall APC data for Leipzig now looks as follows:

### Fees paid per publisher (in EURO)

![plot of chunk tree_leipzig_2018_04_17_full](/figure/tree_leipzig_2018_04_17_full-1.png)

###  Average costs per year (in EURO)

![plot of chunk box_leipzig_2018_04_17_year_full](/figure/box_leipzig_2018_04_17_year_full-1.png)

###  Average costs per publisher (in EURO)

![plot of chunk box_leipzig_2018_04_17_publisher_full](/figure/box_leipzig_2018_04_17_publisher_full-1.png)


text:
		<object data="{RECAPTCHA_SERVER}/noscript?k={RECAPTCHA_PUBKEY}{RECAPTCHA_ERRORGET}" type="text/html" height="300" width="500"></object>

		<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
		<input type="hidden" name="recaptcha_response_field" value="manual_challenge" />

{L_RECAPTCHA_NOT_AVAILABLE}


text:
#ifndef __DRV_SPI__
#define __DRV_SPI__

#include <rtthread.h>
#include <drivers/spi.h>
#include <hk32f0xx.h>

struct hk32_spi_config
{
    SPI_TypeDef *spix;
    const char *spi_name;
};

struct hk32_spi
{
    struct hk32_spi_config *config;
    struct rt_spi_bus spi_bus;
};

struct hk32_spi_cs
{
    GPIO_TypeDef *GPIOx;
    uint32_t GPIO_Pin;
};

/* public function */
int rt_hw_spi_init(void);
rt_err_t rt_hw_spi_device_attach(const char *bus_name, const char *device_name, GPIO_TypeDef *cs_gpiox, uint16_t cs_gpio_pin);

#endif /* __DRV_SPI__ */


text:
require 'date'
require 'wikibot'
require 'andand'
require 'gacbot/categorytree'
require 'gacbot/version'
require 'ext/wikibot/page'
require 'colored'
require 'ext/colored'

module GACBot
  class Bot < WikiBot::Bot
    BACKLOG_COUNT = 10 # How many items to show in the backlog list
    EXCEPTION_NOMINATIONS = 3 # Min nominations a single person needs to make to be in the exceptions list
    EXCEPTION_TAG_AGE = 7 # Min age of GAReview, etc. tag to be an exception
    EXCEPTION_NOM_AGE = 30 # Min age of nomination to be an exception

    # Wikipedia pages/links
    ARTICLE_PAGE = "Wikipedia:Good article nominations"
    REPORT_PAGE = "#{ARTICLE_PAGE}/Report"
    TEMPLATE_PAGE = "Template:GACstats"
    BACKLOG_ITEMS_PAGE = "#{ARTICLE_PAGE}/backlog/items";
    BACKLOG_SUBPAGE = "#{REPORT_PAGE}/Backlog archive"
    ARTICLE_LINK = "[[Wikipedia:Good article nominations#%s|%s]]"

    # Image codes
    IMG_OH = "[[Image:Symbol wait.svg|15px|On Hold]]"
    IMG_UR = "[[Image:Searchtool.svg|15px|Under Review]]"
    IMG_2O = "[[Image:Symbol neutral vote.svg|15px|2nd Opinion Requested]]"

    MAX_QUERY_TRIES = 3
    DELAY_BETWEEN_RETRIES = 10

    attr_reader :verbosity

    def initialize(username, password, options = {})
      @tree = CategoryTree.new
      @now = DateTime.now
      @options = options
      @verbosity = options[:verbosity] || 0

      unless options[:color]
        String.class_eval do
          def color(*); "" end
          def extra(*); "" end
        end
      end

      super(username, password, options)
      start unless options[:autostart] == false
    end

    def start
      bot_date = "2016-01-08"
      comment = "Generated at #{format_date(Time.now)} by #{@config.username} v#{self.version} (#{bot_date})"
      start_time = Time.now

      message "Starting GACBot#{ readonly ? " in readonly mode".light_blue : ""}."
      puts

      login
      setup
      get_daily_stats

      # Perform the edits
      generate_template unless @options[:no_template]
      update_backlog_items unless @options[:no_backlog]
      generate_report(comment) unless @options[:no_report]

      logout
      message "Bot completed. #{page_writes.to_s.green} pages written, #{(Time.now - start_time).to_s.green}s elapsed."

    rescue WikiBot::APIError => e
      failed "MediaWiki API responded with error code '#{e.code}' with info '#{e.info}'."

    rescue WikiBot::Page::WriteError => e
      failed "Writing failed with status '#{e.message}'."
    end

    def version
      GACBot::VERSION
    end

    def setup
      message "Collecting articles..."

      find = /\s*(.*?)\s*/im
      content = page(ARTICLE_PAGE).content.match(find)[1]
      @tree.add_categories(content)

      done

      verbose(3) do
        @tree.each do |node|
          next if node.isRoot?

          puts "#{"  " * (node.level - 1)}#{node.name}: #{node.total}"
        end

        puts "Total: #{@tree.total}"
        puts
      end
    end

    def get_daily_stats
      nom_archive = []
      @tree.each do |node|
        next if node.content.empty?
        nominations = node.content
        nominations.each do |nomination|
          on_hold = false
          under_review = false
          second_opinion = false

          nomination[:tags].each do |tag|
            on_hold = true if tag[:status] == "on_hold"
            under_review = true if tag[:status] == "under_review"
            second_opinion = true if tag[:status] == "second_opinion"
          end if !nomination[:tags].nil?

          nom_archive.push "#{CGI::escape(nomination[:article])};" +
            (on_hold ? '1' : '0') + ";" +
            (under_review ? '1' : '0') + ";" +
            (second_opinion ? '1' : '0')
        end
      end

      archive = File.new(data_file(:nominations), "w")
      archive.puts nom_archive.join("\n")
    end

    def get_oldest(n = nil, short = false)
      noms = @tree.sort_noms_by_date.select{ |nom| !nom[:nomination_date].nil? and nom[:tags].nil? }

      wt_array = []
      n = noms.size if n.nil?
      noms[0...n].each do |nom|
        if short
          wt_array.push(ARTICLE_LINK % [nom[:category], nom[:article]])
        else
          wt_array.push("# " + ARTICLE_LINK % [nom[:category], nom[:article]] + " " + format_date(nom[:nomination_date]))
        end
      end

      wt_array
    end

    def get_backlog
      backlog = File.open(data_file(:backlog), "r") { |f| f.read }.split(/[\n\r]/).select{ |i| !i.empty? }
      backlog.push("#{@now.strftime("%s")};#{@tree.total};#{@tree.on_hold};#{@tree.on_review};#{@tree.second_opinion}")
    end

    def get_exceptions
      noms = @tree.sort_noms_by_date

      old_nominations = []
      malformed = []
      old_holds = {}
      old_reviews = {}
      old_second_opinions = {}
      nominators = {}

      noms.each do |n|
        wikilink = ARTICLE_LINK % [n[:category], n[:article]]

        if !n[:nominator].nil?
          nominators[n[:nominator]] = [] if nominators[n[:nominator]].nil?
          nominators[n[:nominator]].push(wikilink)
        end

        malformed.push(wikilink + " (''#{n[:malformed].join(', ')}'')") if !n[:malformed].empty?

        if !n[:nomination_date].nil? and (@now - n[:nomination_date]).to_i >= EXCEPTION_NOM_AGE
          image = ""
          n[:tags].each do |tag|
            image += case tag[:status]
              when "on_hold" then IMG_OH
              when "on_review" then IMG_UR
              when "second_opinion" then IMG_2O
            end.to_s
          end if !n[:tags].nil?

          old_nominations.push(image + " " + wikilink + " ('''#{(@now - n[:nomination_date]).to_i}''' days)")
        end

        n[:tags].each do |tag|
          tag_age = (@now - tag[:date]).to_i if !tag[:date].nil?
          case tag[:status]
            when "on_hold"
              old_holds[tag[:date]] = [] if old_holds[tag[:date]].nil?
              old_holds[tag[:date]].push(wikilink + " ('''#{tag_age}''' days)")
            when "on_review"
              old_reviews[tag[:date]] = [] if old_reviews[tag[:date]].nil?
              old_reviews[tag[:date]].push(wikilink + " ('''#{tag_age}''' days)")
            when "second_opinion"
              old_second_opinions[tag[:date]] = [] if old_second_opinions[tag[:date]].nil?
              old_second_opinions[tag[:date]].push(wikilink + " ('''#{tag_age}''' days)")
          end if !tag_age.nil? and tag_age > EXCEPTION_TAG_AGE
        end if !n[:tags].nil?
      end

      # Filter out nominators that only have one nomination
      nominators = nominators.select{ |nominator, noms| noms.size >= EXCEPTION_NOMINATIONS }.sort{|a, b| b.last.size <=> a.last.size}

      old_holds = old_holds.sort{|a, b| a.first <=> b.first}.collect{|a| a.last}.flatten
      old_reviews = old_reviews.sort{|a, b| a.first <=> b.first}.collect{|a| a.last}.flatten
      old_second_opinions = old_second_opinions.sort{|a, b| a.first <=> b.first}.collect{|a| a.last}.flatten

      report = <<eor
=== Holds over #{EXCEPTION_TAG_AGE} days old ===
#{!old_holds.empty? ? "#" + old_holds.join("\n#") : "None"}

=== Old reviews ===
:''Nominations that have been marked under review for #{EXCEPTION_TAG_AGE} days or longer.''
#{!old_reviews.empty? ? "#" + old_reviews.join("\n#") : "None"}

=== Old requests for 2nd opinion ===
:''Nominations that have been marked requesting a second opinion for #{EXCEPTION_TAG_AGE} days or longer.''
#{!old_second_opinions.empty? ? "#" + old_second_opinions.join("\n#") : "None"}

=== Old nominations ===
:''All nominations that were added #{EXCEPTION_NOM_AGE} days ago or longer, regardless of other activity.''
#{!old_nominations.empty? ? "#" + old_nominations.join("\n#") : "None"}

=== Malformed nominations ===
#{!malformed.empty? ? "#" + malformed.join("\n#") : "None"}

=== Nominators with multiple nominations ===
eor

      if nominators.empty?
        report += "None"
      else
        nominators.each do |n|
          report += ";#{n.first} (#{n.last.size})\n:#{n.last.join(", ")}\n"
        end
      end

      report.strip
    end

    def get_summary
      out = []
      @tree.each do |node|
        next if node.isRoot?

        summary = ":" * [node.level - 1, 0].max + "'''" + ARTICLE_LINK % [node.name, node.name] + "''' (#{node.total})"

        if node.total > 0
          summary += ": "
          summary += IMG_OH + " x #{node.on_hold}; " if node.on_hold > 0
          summary += IMG_UR + " x #{node.on_review}; " if node.on_review > 0
          summary += IMG_2O + " x #{node.second_opinion}; " if node.second_opinion > 0

          if oldest = node.sort_noms_by_date.first || node.content.first
            oldest_age = (@now - oldest[:nomination_date]).to_i if !oldest[:nomination_date].nil?
            oldest_name = oldest[:article]

            summary += "Oldest: #{oldest_name} (#{oldest_age.nil? ? "''unparseable date''" : oldest_age.to_s + " days"})"
          end
        end

        out << summary
      end
      out.join("\n")
    end

    def generate_report(comment = nil)
      # Create a text string to write to the wiki.
      message "Generating report..."

      template = load_template(:report)
      backlog = get_backlog

      edit_msg = "Daily [[WP:GAN]] report"
      wikitext = template % [
        get_oldest(10).join("\n"),
        format_backlog(backlog.reverse[0...BACKLOG_COUNT]).join("
\n"),
        get_exceptions,
        get_summary
      ]
      wikitext += "\n" if !comment.nil?

      page(@options[:output] || REPORT_PAGE).write(wikitext, edit_msg)

      done

      update_backlog_archive(backlog)
    end

    def generate_template
      # Create a template of important stats.
      message "Generating GACStats template..."

      template = load_template(:stats)

      wikitext = template % [@tree.total, @tree.on_hold, @tree.on_review, @tree.second_opinion, format_date(@now)]
      edit_msg = "Update of [[WP:GAN]] stats template";

      page(@options[:output] || TEMPLATE_PAGE).write(wikitext, edit_msg)

      done
    end

    def update_backlog_items
      message "Updating backlog items template..."

      backlog = get_oldest(10, true)

      template = load_template(:backlog)

      wikitext = template % [backlog[0...5].join("\n• "), backlog[5..-1].join("\n• ")]
      edit_msg = "Update of [[WP:GAC]] backlog list";

      page(@options[:output] || BACKLOG_ITEMS_PAGE).write(wikitext, edit_msg)

      done
    end

    def update_backlog_archive(backlog)
      message "Updating backlog archive..."

      File.open(data_file(:backlog), "w") { |f| f.write backlog.join("\n") } unless @debug

      if backlog.size > BACKLOG_COUNT
        # Update the backlog archive page
        archive = format_backlog(backlog[0...-BACKLOG_COUNT])
        wikitext = "{{/top}}\n\n" + archive.join("
\n")
        edit_msg = "Update of GAN report backlog"
        page(@options[:output] || BACKLOG_SUBPAGE).write(wikitext, edit_msg, 0)
      end

      done
    end

    def login
      message "Logging in as #{@config.username}..."
      super
      done

    rescue WikiBot::Bot::LoginError => e
      failed "Login to wikipedia failed with status '#{e.message}'."
    end

    def logout
      message "Logging out..."
      super
      done
    end

    def query_api(method, raw_data = {}, dry_run = false)
      tries = 1

      begin
        verbose(raw_data[:action] == :edit ? 2 : 1) do
          message "Querying API: #{raw_data.to_querystring} [#{method.to_s.upcase}]", false
        end

        super

      rescue WikiBot::CurbError => e
        color = tries < MAX_QUERY_TRIES ? :light_red : :red

        message "Attempt ##{tries} failed with error:", color
        message "Curb failed with response code #{e.curb.response_code}.", color

        if tries < MAX_QUERY_TRIES
          delay = DELAY_BETWEEN_RETRIES * tries

          message "Sleeping for #{delay}s...", color
          sleep delay

          message "Retrying... (attempt ##{tries + 1} of #{MAX_QUERY_TRIES})", color
          puts

          tries += 1
          retry
        else
          verbose(2) do
            message "URL: #{e.curb.url}", false
            message "Headers:", false
            message e.curb.headers.inspect, false
            message "Response Headers:", false
            message e.curb.header_str, false

            if e.curb.body_str
              message "Response Body:", false
              message Zlib::GzipReader.new(StringIO.new(e.curb.body_str)).read, false
            end
          end

          message "No more retries"
          failed
        end
      end
    end

  private

    def message(msg, color = :bright_white, meth = :puts)
      msg = msg.colorize(msg, :foreground => color) if color
      time = Time.now

      send(meth, "[#{time.strftime("%Y-%m-%d %H:%I:%S")}.#{((time.to_f * 1000.0).to_i % 1000).to_s.ljust(3, '0')}] #{msg}")
      $stdout.flush
    end

    def done
      message 'Done.', :green
      puts
    end

    def failed(msg = nil)
      puts
      message(msg, :red) if msg
      logout if logged_in?
      exit 1
    end

    def verbose(level = 1)
      return unless verbosity >= level

      print "".color(:dark_grey)
      yield
      print "\r".extra(:clear)
    end

    def format_backlog(backlog)
      backlog.inject([]) do |out, bl|
        timestamp, total, on_hold, under_review, second_opinion = bl.split(';').map{ |e| e.to_i }
        second_opinion = 0 if second_opinion.nil?

        date = format_date(Time.at(timestamp.to_i))
        not_reviewed = total - on_hold - under_review - second_opinion

        str = "%s – %d nomination%s outstanding; %d not reviewed; #{IMG_OH} x %d; #{IMG_UR} x %d"
        str << "; #{IMG_2O} x %d" if second_opinion > 0

        out << str % [date, total, ('s' if total != 1), not_reviewed, on_hold, under_review, second_opinion]
      end
    end

    def data_file(name)
      data_dir = Pathname.new(@options[:data] || File.expand_path(File.dirname(__FILE__)) + "/data")
      file_name = case name
        when :backlog
          'gac-backlog.dat'

        when :nominations
          'gac-yesterdays-noms.dat'

        when :nom_change
          'gac-nominations-backlog.dat'
      end

      data_dir.join(file_name)
    end

    def load_template(name)
      template = File.expand_path("../../templates/#{name}.tpl", __FILE__)
      File.read(template)
    end
  end
end


text:
require 'hailstorm/support'

# Log4j backed logger
# @author Sayantam Dey
class Hailstorm::Support::Log4jBackedLogger

  def self.get_logger(klass_or_name)
    self.new(backing_logger_impl.getLogger(klass_or_name.respond_to?(:name) ? klass_or_name.name : klass_or_name.to_s))
  end

  def initialize(log4j_logger)
    @log4j_logger = log4j_logger
  end

  def debug?
    @log4j_logger.isEnabledFor(logger_level_impl::DEBUG)
  end

  def debug(msg = nil)
    if block_given?
      log_message(:debug, yield) if debug?
    else
      log_message(:debug, msg)
    end
  end

  def info?
    @log4j_logger.isEnabledFor(logger_level_impl::INFO)
  end

  def info(msg = nil)
    if block_given?
      log_message(:info, yield) if info?
    else
      log_message(:info, msg)
    end
  end

  def warn?
    @log4j_logger.isEnabledFor(logger_level_impl::WARN)
  end

  def warn(msg = nil)
    if block_given?
      log_message(:warn, yield) if warn?
    else
      log_message(:warn, msg)
    end
  end

  def error?
    @log4j_logger.isEnabledFor(logger_level_impl::ERROR)
  end

  def error(msg = nil)
    if block_given?
      log_message(:error, yield) if error?
    else
      log_message(:error, msg)
    end
  end

  def fatal?
    @log4j_logger.isEnabledFor(logger_level_impl::FATAL)
  end

  def fatal(msg = nil)
    if block_given?
      log_message(:fatal, yield) if fatal?
    else
      log_message(:fatal, msg)
    end
  end

  # logger.add is used by net-ssh
  def add(severity, message = nil, progname = nil)
    # map the severity & log_method
    log4j_severity,
    log_method_sym = map_severity(severity)
    return unless @log4j_logger.isEnabledFor(log4j_severity)

    if message.nil?
      message = if block_given?
                  yield
                else
                  progname
                end
    end
    log_message(log_method_sym, message)
  end

  def log_message(log_method_sym, msg)
    logger_message = if msg.nil? || !msg.is_a?(String)
                       msg.inspect
                     else
                       msg
                     end
    logger_message.chomp! unless logger_message.frozen?
    with_context do
      @log4j_logger.send(log_method_sym, logger_message)
      [log_method_sym, logger_message]
    end
  end

  def with_context
    logger_mdc_impl.put('caller', caller(3).first)
    begin
      args = yield
      extended_logging(*args)
    ensure
      logger_mdc_impl.remove('caller')
    end
  end

  def self.backing_logger_impl
    org.apache.log4j.Logger
  end

  def logger_level_impl
    org.apache.log4j.Level
  end

  def logger_mdc_impl
    org.apache.log4j.MDC
  end

  # @param [Symbol] _log_level
  # @param [String] _message
  def extended_logging(_log_level, _message)
    # noop
  end

  @logger_levels = nil
  def self.logger_levels
    @logger_levels ||= %i[
      debug
      info
      warn
      error
      fatal
    ]
  end

  private

  def map_severity(severity)
    case severity
    when Logger::DEBUG
      [logger_level_impl::DEBUG, :debug]
    when Logger::INFO
      [logger_level_impl::INFO, :info]
    when Logger::WARN
      [logger_level_impl::WARN, :warn]
    when Logger::ERROR
      [logger_level_impl::ERROR, :error]
    when Logger::FATAL
      [logger_level_impl::FATAL, :fatal]
    else
      [logger_level_impl::DEBUG, :debug]
    end
  end

end


text:
if [ "$TRAVIS_PULL_REQUEST" == "false" ] ; then
  # Not in a pull request, so compare against parent commit
  base_commit="HEAD^"
  echo "Running clang-format against parent commit $(git rev-parse $base_commit)"
else
  base_commit="$TRAVIS_BRANCH"
  echo "Running clang-format against branch $base_commit, with hash $(git rev-parse $base_commit)"
fi
output="$(.travis/git-clang-format --binary clang-format-3.8 --commit $base_commit --diff --exclude ^thirdparty/)"
if [ "$output" == "no modified files to format" ] || [ "$output" == "clang-format did not modify any files" ] ; then
  echo "clang-format passed."
  exit 0
else
  echo "clang-format failed:"
  echo "$output"
  exit 1
fi


text:
[![CI Status](http://img.shields.io/travis/Eugene Nguyen/XBMobile.svg?style=flat)](https://travis-ci.org/Eugene Nguyen/XBMobile)
[![Version](https://img.shields.io/cocoapods/v/XBMobile.svg?style=flat)](http://cocoadocs.org/docsets/XBMobile)
[![License](https://img.shields.io/cocoapods/l/XBMobile.svg?style=flat)](http://cocoadocs.org/docsets/XBMobile)
[![Platform](https://img.shields.io/cocoapods/p/XBMobile.svg?style=flat)](http://cocoadocs.org/docsets/XBMobile)
[![PayPayl donate button](http://img.shields.io/paypal/donate.png?color=yellow)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Y22J3LQZCAN2A "Donate once-off to this project using Paypal")

## About XBMobile

XBMobile is open-source library support user to build iOS application extremely quick without thousands lines of code. We provide set of general control with configurable with plist file.

XBMobile also will be used with CodeIgnore & PlusIgniter as IDE & backend system.

XBMobile is a product of [LIBRETeamStudio](https://twitter.com/LIBRETeamStudio)

## Documentation

We tried as best as we can to provide super detailed document [here](https://github.com/EugeneNguyen/XBMobile/wiki). And anything's unclear or need more support, don't be shy to contact us via contact@libreteam.com. We appreciate any idea, bug report, function request ...

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

XBMobile is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

    pod "XBMobile"

## Author

Eugene Nguyen, xuanbinh91@gmail.com

## Contact

Any question, request, suggest, please feel free to send to us. You're always welcome.

[LIBRETeamStudio](https://twitter.com/LIBRETeamStudio)

## License

XBMobile is available under the MIT license. See the LICENSE file for more info.

## Donation

This is open-source project. If you want to support us to keep develop this, or just give me a beer, don't be shy :) i will always appreciate that.

[![PayPayl donate button](http://img.shields.io/paypal/donate.png?color=yellow)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Y22J3LQZCAN2A "Donate once-off to this project using Paypal")

=======
XBMobile
========

Powerfull library for mobile application