text:
var Dota2 = require("../index"),
    util = require("util");

var cacheTypeIDs = {
    LOBBY: 2004,
    PARTY: 2003,
    PARTY_INVITE: 2006,
    LOBBY_INVITE: 2011
};

// Handlers
function handleSubscribedType(obj_type, object_data) {
    switch (obj_type) {
        // Lobby snapshot.
        case cacheTypeIDs.LOBBY:
            var lobby = Dota2.schema.CSODOTALobby.decode(object_data);
            if (this.debug) util.log("Received lobby snapshot for lobby ID " + lobby.lobby_id);
            this.emit("practiceLobbyUpdate", lobby);
            this.Lobby = lobby;
            break;
        // Lobby invite snapshot.
        case cacheTypeIDs.LOBBY_INVITE:
            var lobby = Dota2.schema.CSODOTALobbyInvite.decode(object_data);
            if (this.debug) util.log("Received lobby invite snapshot for group ID " + lobby.group_id);
            this.emit("lobbyInviteUpdate", lobby);
            this.LobbyInvite = lobby;
            break;
        // Party snapshot.
        case cacheTypeIDs.PARTY:
            var party = Dota2.schema.CSODOTAParty.decode(object_data);
            if (this.debug) util.log("Received party snapshot for party ID " + party.party_id);
            this.emit("partyUpdate", party);
            this.Party = party;
            break;
        // Party invite snapshot.
        case cacheTypeIDs.PARTY_INVITE:
            var party = Dota2.schema.CSODOTAPartyInvite.decode(object_data);
            if (this.debug) util.log("Received party invite snapshot for group ID " + party.group_id);
            this.emit("partyInviteUpdate", party);
            this.PartyInvite = party;
            break;
        default:
            if (this.debug) util.log("Unknown cache ID: " + obj_type);
            break;
    }
};

Dota2.Dota2Client.prototype._handleWelcomeCaches = function handleWelcomeCaches(message) {
    var welcome = Dota2.schema.CMsgClientWelcome.decode(message);
    var _self = this;

    if (welcome.outofdate_subscribed_caches)
        welcome.outofdate_subscribed_caches.forEach(function(cache) {
            cache.objects.forEach(function(obj) {
                handleSubscribedType.call(_self, obj.type_id, obj.object_data[0]);
            });
        });
};

var handlers = Dota2.Dota2Client.prototype._handlers;

var onCacheSubscribed = function onCacheSubscribed(message) {
    var subscribe = Dota2.schema.CMsgSOCacheSubscribed.decode(message);
    var _self = this;

    if (this.debug) {
        util.log("Cache subscribed, type " + subscribe.objects[0].type_id);
    }

    subscribe.objects.forEach(function(obj) {
        handleSubscribedType.call(_self, obj.type_id, obj.object_data[0]);
    });
};
handlers[Dota2.schema.ESOMsg.k_ESOMsg_CacheSubscribed] = onCacheSubscribed;

var onUpdateMultiple = function onUpdateMultiple(message) {
    var multi = Dota2.schema.CMsgSOMultipleObjects.decode(message);
    var _self = this;

    if (multi.objects_modified)
        multi.objects_modified.forEach(function(obj) {
            handleSubscribedType.call(_self, obj.type_id, obj.object_data);
        });
};
handlers[Dota2.schema.ESOMsg.k_ESOMsg_UpdateMultiple] = onUpdateMultiple;

var onCreate = function onCreate(message) {
    var single = Dota2.schema.CMsgSOSingleObject.decode(message);
    var _self = this;

    if (this.debug) {
        util.log("Create, type " + single.type_id);
    }
    handleSubscribedType.call(_self, single.type_id, single.object_data);
}
handlers[Dota2.schema.ESOMsg.k_ESOMsg_Create] = onCreate;

var onCacheUnsubscribed = function onCacheUnsubscribed(message) {
    var unsubscribe = Dota2.schema.CMsgSOCacheUnsubscribed.decode(message);
    var _self = this;

    if (this.debug) util.log("Cache unsubscribed, " + unsubscribe.owner_soid.id);

    if (this.Lobby && "" + unsubscribe.owner_soid.id === "" + this.Lobby.lobby_id) {
        this.Lobby = null;
        this.emit("practiceLobbyCleared");
    } else if (this.LobbyInvite && "" + unsubscribe.owner_soid.id === "" + this.LobbyInvite.group_id) {
        this.LobbyInvite = null;
        this.emit("lobbyInviteCleared");
    } else if (this.Party && "" + unsubscribe.owner_soid.id === "" + this.Party.party_id) {
        this.Party = null;
        this.emit("partyCleared");
    } else if (this.PartyInvite && "" + unsubscribe.owner_soid.id === "" + this.PartyInvite.group_id) {
        this.PartyInvite = null;
        this.emit("partyInviteCleared");
    }
};
handlers[Dota2.schema.ESOMsg.k_ESOMsg_CacheUnsubscribed] = onCacheUnsubscribed;

var onCacheDestroy = function onCacheDestroy(message) {
    var destroy = Dota2.schema.CMsgSOSingleObject.decode(message);
    var _self = this;

    if (this.debug) util.log("Cache destroy, " + destroy.type_id);

    if (destroy.type_id === cacheTypeIDs.PARTY_INVITE) {
        this.PartyInvite = null;
        this.emit("partyInviteCleared");
    }
    if (destroy.type_id === cacheTypeIDs.LOBBY_INVITE) {
        this.LobbyInvite = null;
        this.emit("lobbyInviteCleared");
    }
};
handlers[Dota2.schema.ESOMsg.k_ESOMsg_Destroy] = onCacheDestroy;


text:
using LiveSplit.Model;
using LiveSplit.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace LiveSplit.UI.Components
{
    public class ComponentManager
    {
        public const string PATH_COMPONENTS = "Components\\";
        public static string BasePath { get; set; }
        public static IDictionary<string, IComponentFactory> ComponentFactories { get; protected set; }

        public static ILayoutComponent LoadLayoutComponent(string path, LiveSplitState state)
        {
            if (ComponentFactories == null)
                LoadAllFactories();
            IComponent component = null;

            if (string.IsNullOrEmpty(path))
                component = new SeparatorComponent();
            else if (!ComponentFactories.ContainsKey(path))
                return null;
            else
                component = ComponentFactories[path].Create(state);

            return new LayoutComponent(path, component);
        }

        public static IDictionary<string, IComponentFactory> LoadAllFactories()
        {
            var path = Path.GetFullPath(Path.Combine(BasePath ?? "", PATH_COMPONENTS));
            ComponentFactories = Directory
                .EnumerateFiles(path, "*.dll")
                .Select(x =>
                    {
                        var factory = LoadFactory(x);
                        return new KeyValuePair<string, IComponentFactory>(Path.GetFileName(x),factory);
                    })
                .Where(x => x.Value != null)
                .ToDictionary(x => x.Key, x => x.Value);

            return ComponentFactories;
        }

        public static IComponentFactory LoadFactory(string path)
        {
            IComponentFactory factory = null;
            try
            {
                var attr = (ComponentFactoryAttribute)Attribute
                	.GetCustomAttribute(Assembly.UnsafeLoadFrom(path), typeof(ComponentFactoryAttribute));

                if (attr != null)
                {
                    factory = (IComponentFactory)(attr.
                        ComponentFactoryClassType.
                        GetConstructor(new Type[0]).
                        Invoke(null));
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            return factory;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * This file contains various common stuff used by UBI utilities.
 *
 * Authors: Artem Bityutskiy
 *          Adrian Hunter
 */

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

/**
 * get_multiplier - convert size specifier to an integer multiplier.
 * @str: the size specifier string
 *
 * This function parses the @str size specifier, which may be one of
 * 'KiB', 'MiB', or 'GiB' into an integer multiplier. Returns positive
 * size multiplier in case of success and %-1 in case of failure.
 */
static int get_multiplier(const char *str)
{
	if (!str)
		return 1;

	/* Remove spaces before the specifier */
	while (*str == ' ' || *str == '\t')
		str += 1;

	if (!strcmp(str, "KiB"))
		return 1024;
	if (!strcmp(str, "MiB"))
		return 1024 * 1024;
	if (!strcmp(str, "GiB"))
		return 1024 * 1024 * 1024;

	/* Handle deprecated stuff */
	if (!strcmp(str, "KB") || !strcmp(str, "Kib") || !strcmp(str, "kib") ||
	    !strcmp(str, "kiB")) {
		fprintf(stderr, "Warning: use \"KiB\" instead of \"%s\" to "
			"specify Kilobytes - support will be removed\n", str);
		return 1024;
	}
	if (!strcmp(str, "MB") || !strcmp(str, "Mib") || !strcmp(str, "mb")) {
		fprintf(stderr, "Warning: use \"MiB\" instead of \"%s\", "
			"this support will be removed\n", str);
		return 1024*1024;
	}
	if (!strcmp(str, "GB") || !strcmp(str, "Gib") || !strcmp(str, "gb")) {
		fprintf(stderr, "Warning: use \"GiB\" instead of \"%s\", "
			"this support will be removed\n", str);
		return 1024*1024*1024;
	}

	return -1;
}

/**
 * ubiutils_get_bytes - convert a string containing amount of bytes into an
 * integer
 * @str: string to convert
 *
 * This function parses @str which may have one of 'KiB', 'MiB', or 'GiB'
 * size specifiers. Returns positive amount of bytes in case of success and %-1
 * in case of failure.
 */
long long ubiutils_get_bytes(const char *str)
{
	char *endp;
	long long bytes = strtoull(str, &endp, 0);

	if (endp == str || bytes < 0) {
		fprintf(stderr, "incorrect amount of bytes: \"%s\"\n", str);
		return -1;
	}

	if (*endp != '\0') {
		int mult = get_multiplier(endp);

		if (mult == -1) {
			fprintf(stderr, "bad size specifier: \"%s\" - "
			        "should be 'KiB', 'MiB' or 'GiB'\n", endp);
			return -1;
		}
		bytes *= mult;
	}

	return bytes;
}

/**
 * ubiutils_print_bytes - print bytes.
 * @bytes: variable to print
 * @bracket: whether brackets have to be put or not
 *
 * This is a helper function which prints amount of bytes in a human-readable
 * form, i.e., it prints the exact amount of bytes following by the approximate
 * amount of Kilobytes, Megabytes, or Gigabytes, depending on how big @bytes
 * is.
 */
void ubiutils_print_bytes(long long bytes, int bracket)
{
	const char *p;

	if (bracket)
		p = " (";
	else
		p = ", ";

	printf("%lld bytes", bytes);

	if (bytes > 1024 * 1024 * 1024)
		printf("%s%.1f GiB", p, (double)bytes / (1024 * 1024 * 1024));
	else if (bytes > 1024 * 1024)
		printf("%s%.1f MiB", p, (double)bytes / (1024 * 1024));
	else if (bytes > 1024 && bytes != 0)
		printf("%s%.1f KiB", p, (double)bytes / 1024);
	else
		return;

	if (bracket)
		printf(")");
}

/**
 * ubiutils_print_text - print text and fold it.
 * @stream: file stream to print to
 * @text: text to print
 * @width: maximum allowed text width
 *
 * Print text and fold it so that each line would not have more then @width
 * characters.
 */
void ubiutils_print_text(FILE *stream, const char *text, int width)
{
	int pos, bpos = 0;
	const char *p;
	char line[1024];

	if (width > 1023) {
		fprintf(stream, "%s\n", text);
		return;
	}
	p = text;
	pos = 0;
	while (p[pos]) {
		while (!isspace(p[pos])) {
			line[pos] = p[pos];
			if (!p[pos])
				break;
			++pos;
			if (pos == width) {
				line[pos] = '\0';
				fprintf(stream, "%s\n", line);
				p += pos;
				pos = 0;
			}
		}
		while (pos < width) {
			line[pos] = p[pos];
			if (!p[pos]) {
				bpos = pos;
				break;
			}
			if (isspace(p[pos]))
				bpos = pos;
			++pos;
		}
		line[bpos] = '\0';
		fprintf(stream, "%s\n", line);
		p += bpos;
		pos = 0;
		while (p[pos] && isspace(p[pos]))
			++p;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ztiany.androidaspectj03.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn_sample_1"
            style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="around 调用拦截"
            android:textAllCaps="false"
            tools:ignore="HardcodedText"/>

        <Button
            android:id="@+id/btn_sample_2"
            style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="throw error 异常处理"
            android:textAllCaps="false"
            tools:ignore="HardcodedText"/>

        <Button
            android:id="@+id/btn_sample_3"
            style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="with code in 应用"
            android:textAllCaps="false"
            tools:ignore="HardcodedText"/>

        <Button
            android:id="@+id/btn_sample_4"
            style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="with in 应用"
            android:textAllCaps="false"
            tools:ignore="HardcodedText"/>

        <Button
            android:id="@+id/btn_sample_5"
            style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="call 和 execution 的区别"
            android:textAllCaps="false"
            tools:ignore="HardcodedText"/>

        <Button
            android:id="@+id/btn_sample_6"
            style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="字段你的 getter 和 setter"
            android:textAllCaps="false"
            tools:ignore="HardcodedText"/>

        <Button
            android:id="@+id/btn_sample_7"
            style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="应用注解的aspect"
            android:textAllCaps="false"
            tools:ignore="HardcodedText"/>

        <Button
            android:id="@+id/btn_sample_8"
            style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="cflow 使用"
            android:textAllCaps="false"
            tools:ignore="HardcodedText"/>

    </LinearLayout>

</ScrollView>


text:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
  private MathApplication mathApplication;
  private CalculatorService calculatorService;

  @Before
  public void setUp() {
    mathApplication = new MathApplication();
    calculatorService = mock(CalculatorService.class);
    mathApplication.setCalculatorService(calculatorService);
  }

  @Test
  public void testAddAndSubtract() {
    when(calculatorService.add(20.0,10.0)).thenReturn(30.0);
    when(calculatorService.subtract(20.0,10.0)).thenReturn(10.0);

    Assert.assertEquals(mathApplication.subtract(20.0,10.0),10.0,0);
    Assert.assertEquals(mathApplication.add(20.0,10.0),30.0,0);

    verify(calculatorService).add(20.0,10.0);
    verify(calculatorService).subtract(20.0,10.0);
  }
}


text:
import React from 'react';
import CommentForm from 'components/CommentForm';
import { initialize } from 'redux-form';
import { connect } from 'react-redux';
import { addComment } from 'actions';
import { FORM_COMMENT_ID } from 'constants';

@connect(state => ({
  dispatch: state
}))
export class newComment extends React.Component {

  static propTypes = {
    dispatch: React.PropTypes.func,
    history: React.PropTypes.object
  }

  constructor () {
    super();
  }

  handleSubmit(data) {
    // save form
    this.props.dispatch(addComment(data));
    // clear form inputs
    this.props.dispatch(initialize( FORM_COMMENT_ID, {}));
    // show comments
    this.props.history.pushState(null, '/');
  }

  handleReset() {
    // clear form inputs
    this.props.dispatch(initialize( FORM_COMMENT_ID, {}));
  }

  render () {
    return (

New comment

        <CommentForm onSubmit={this.handleSubmit.bind(this)} handleReset={this.handleReset.bind(this)}/>

    );
  }
}

export default newComment;


text:
/*
 * This is a set of routines for allocating large-sized mbuf payload
 * areas, and is primarily intended for use in receive side mbuf
 * allocation.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/types.h>
#include <sys/sockio.h>
#include <sys/uio.h>
#include <sys/lock.h>
#include <sys/kernel.h>
#include <sys/mutex.h>
#include <sys/malloc.h>
#include <vm/vm.h>
#include <vm/pmap.h>
#include <vm/vm_extern.h>
#include <vm/pmap.h>
#include <vm/vm_map.h>
#include <vm/vm_map.h>
#include <vm/vm_param.h>
#include <vm/vm_pageout.h>
#include <sys/vmmeter.h>
#include <vm/vm_page.h>
#include <vm/vm_object.h>
#include <vm/vm_kern.h>
#include <sys/proc.h>
#include <sys/jumbo.h>

/*
 * XXX this may be too high or too low.
 */
#define JUMBO_MAX_PAGES 3072

struct jumbo_kmap {
	vm_offset_t kva;
	SLIST_ENTRY(jumbo_kmap) entries;     /* Singly-linked List. */
};

static SLIST_HEAD(jumbo_kmap_head, jumbo_kmap) jumbo_kmap_free,
					       jumbo_kmap_inuse;

static struct mtx jumbo_mutex;
MTX_SYSINIT(jumbo_lock, &jumbo_mutex, "jumbo mutex", MTX_DEF);

static struct vm_object *jumbo_vm_object;
static unsigned long jumbo_vmuiomove_pgs_freed = 0;
#if 0
static int jumbo_vm_wakeup_wanted = 0;
#endif
vm_offset_t jumbo_basekva;

int
jumbo_vm_init(void)
{
	int i;
	struct jumbo_kmap *entry;

	mtx_lock(&jumbo_mutex);

	if (jumbo_vm_object != NULL) {
		mtx_unlock(&jumbo_mutex);
		return (1);
	}

	/* allocate our object */
	jumbo_vm_object = vm_object_allocate_wait(OBJT_DEFAULT, JUMBO_MAX_PAGES,
						  M_NOWAIT);

	if (jumbo_vm_object == NULL) {
		mtx_unlock(&jumbo_mutex);
		return (0);
	}

	SLIST_INIT(&jumbo_kmap_free);
	SLIST_INIT(&jumbo_kmap_inuse);

	/* grab some kernel virtual address space */
	jumbo_basekva = kmem_alloc_pageable(kernel_map,
		PAGE_SIZE * JUMBO_MAX_PAGES);
	if (jumbo_basekva == 0) {
		vm_object_deallocate(jumbo_vm_object);
		jumbo_vm_object = NULL;
		mtx_unlock(&jumbo_mutex);
		return 0;
	}
	for (i = 0; i < JUMBO_MAX_PAGES; i++) {
		entry = malloc(sizeof(struct jumbo_kmap), M_TEMP, M_NOWAIT);
		if (!entry && !i)  {
			mtx_unlock(&jumbo_mutex);
			panic("jumbo_vm_init: unable to allocated kvas");
		} else if (!entry) {
			printf("warning: jumbo_vm_init allocated only %d kva\n",
			       i);
			mtx_unlock(&jumbo_mutex);
			return 1;
		}
		entry->kva = jumbo_basekva + (vm_offset_t)i * PAGE_SIZE;
		SLIST_INSERT_HEAD(&jumbo_kmap_free, entry, entries);
	}
	mtx_unlock(&jumbo_mutex);
	return 1;
}

void
jumbo_freem(void *addr, void *args)
{
	vm_page_t frame;

	frame = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)addr));

	/*
	 * Need giant for looking at the hold count below.  Convert this
	 * to the vm mutex once the VM code has been moved out from under
	 * giant.
	 */
	GIANT_REQUIRED;

	if (frame->hold_count == 0)
		jumbo_pg_free((vm_offset_t)addr);
	else
		printf("jumbo_freem: hold count for %p is %d!!??\n",
		       frame, frame->hold_count);
}

void
jumbo_pg_steal(vm_page_t pg)
{
	vm_offset_t addr;
	struct jumbo_kmap *entry;

	addr = ptoa(pg->pindex) + jumbo_basekva;

	if (pg->object != jumbo_vm_object)
		panic("stealing a non jumbo_vm_object page");
	vm_page_remove(pg);

	mtx_lock(&jumbo_mutex);

	pmap_qremove(addr,1);
	entry = SLIST_FIRST(&jumbo_kmap_inuse);
	entry->kva = addr;
	SLIST_REMOVE_HEAD(&jumbo_kmap_inuse, entries);
	SLIST_INSERT_HEAD(&jumbo_kmap_free, entry, entries);

	mtx_unlock(&jumbo_mutex);

#if 0
	if (jumbo_vm_wakeup_wanted)
		wakeup(jumbo_vm_object);
#endif
}

vm_page_t
jumbo_pg_alloc(void)
{
	vm_page_t pg;
	vm_pindex_t pindex;
	struct jumbo_kmap *entry;

 	pg = NULL;
	mtx_lock(&jumbo_mutex);

	entry = SLIST_FIRST(&jumbo_kmap_free);
	if (entry != NULL){
		pindex = atop(entry->kva - jumbo_basekva);
		pg = vm_page_alloc(jumbo_vm_object, pindex, VM_ALLOC_INTERRUPT);
		if (pg != NULL) {
			SLIST_REMOVE_HEAD(&jumbo_kmap_free, entries);
			SLIST_INSERT_HEAD(&jumbo_kmap_inuse, entry, entries);
			pmap_qenter(entry->kva, &pg, 1);
		}
	}
	mtx_unlock(&jumbo_mutex);
	return(pg);
}

void
jumbo_pg_free(vm_offset_t addr)
{
	struct jumbo_kmap *entry;
	vm_offset_t paddr;
	vm_page_t pg;

	paddr = pmap_kextract((vm_offset_t)addr);
	pg = PHYS_TO_VM_PAGE(paddr);

	if (pg->object != jumbo_vm_object) {
		jumbo_vmuiomove_pgs_freed++;
/*		if(vm_page_lookup(jumbo_vm_object, atop(addr - jumbo_basekva)))
			panic("vm_page_rename didn't");
		printf("freeing uiomoved pg:\t pindex = %d, padd = 0x%lx\n",
		       atop(addr - jumbo_basekva), paddr);
*/
	} else {
		vm_page_lock_queues();
		vm_page_busy(pg); /* vm_page_free wants pages to be busy*/
		vm_page_free(pg);
		vm_page_unlock_queues();
	}

	mtx_lock(&jumbo_mutex);

	pmap_qremove(addr,1);
	entry = SLIST_FIRST(&jumbo_kmap_inuse);
	entry->kva = addr;
	SLIST_REMOVE_HEAD(&jumbo_kmap_inuse, entries);
	SLIST_INSERT_HEAD(&jumbo_kmap_free, entry, entries);

	mtx_unlock(&jumbo_mutex);

#if 0
	if (jumbo_vm_wakeup_wanted)
		wakeup(jumbo_vm_object);
#endif
}


text:
Products

        <?php  if($this->session->userdata('userdetails')){?>

<a href="<?php echo site_url('user/dashboard'); ?>">Home

		<?php } else{ ?>

<a href="<?php echo site_url('user/login'); ?>">Home

	  <?php } ?>

<a href="<?php echo site_url('product/lists'); ?>">Products

Products

		 <a class="btn btn-sm btn-inverse btn-round" href="<?php echo site_url('product/add'); ?>">

          Add Product

        <button type="button" class="btn btn-sm btn-icon btn-inverse btn-round" data-toggle="tooltip" data-original-title="Export to CSV">

        </button>
        <button type="button" class="btn btn-sm btn-icon btn-inverse btn-round" data-toggle="tooltip" data-original-title="Export to PDF">

        </button>
        <button type="button" class="btn btn-sm btn-icon btn-inverse btn-round" data-toggle="tooltip" data-original-title="Export to Word">

        </button>

		<?php if($this->session->flashdata('updatemessage')): ?>

<?php echo $this->session->flashdata('updatemessage');?>

		<?php endif; ?>
		<?php if($this->session->flashdata('addproduct')): ?>

<?php echo $this->session->flashdata('addproduct');?>

		<?php endif; ?>
		<?php if($this->session->flashdata('editsuucess')): ?>

<?php echo $this->session->flashdata('editsuucess');?>

		<?php endif; ?>
		<?php if($this->session->flashdata('editerror')): ?>

<?php echo $this->session->flashdata('editerror');?>

		<?php endif; ?>

                Product Name
                price
                Create Date
                Valididty Period
                Status
                Action

                Product Name
                price
                Create Date
                Valididty Period
                Status
                Action

             <?php
			if(count($productlist) > 0){
			foreach ($productlist as $product){
				//echo '
';print_r($product);exit;?>

                <?php echo htmlentities($product['product_name']);?>
                <?php echo htmlentities($product['price']);?>
                <?php echo htmlentities($product['created_at']);?>
                <?php echo htmlentities($product['valididty_period']);?>
                <?php if(htmlentities($product['status'])==1){ echo "Active";}else{ echo "Deactive";} ?>
                <a href="<?php echo base_url('product/edit'); ?>?id=<?php echo  base64_encode($product['product_id']);?>" style="text-decoration:none;">Edit  |  <a href="<?php echo base_url('product/delproduct'); ?>?id=<?php echo  base64_encode($product['product_id']).'__'.base64_encode($product['status']);?>" style="text-decoration:none;">Activate/Deactivate

              <?php } } else { echo '
No Orders
';} ?>


text:
#ifndef _DILITHIUM_STRING_VIEW_HPP
#define _DILITHIUM_STRING_VIEW_HPP

#pragma once

#include <Dilithium/Compiler.hpp>

#ifdef DILITHIUM_CXX17_LIBRARY_STRING_VIEW_SUPPORT
	#include <string_view>
#else
	#include <boost/utility/string_view.hpp>

	namespace std
	{
		using boost::basic_string_view;
		using boost::string_view;
		using boost::wstring_view;
	}
#endif

#endif		// _DILITHIUM_STRING_VIEW_HPP


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.11"/>
<title>NATS C Client with Streaming support: Streaming Connection Options</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="customdoxygen.css" rel="stylesheet" type="text/css" />

NATS C Client with Streaming support
    2.4.0

The nats.io C Client, Supported by Synadia Communications Inc.

Main Page

Related Pages

Modules

Files

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

Functions

Streaming Connection Options
Functions

Functions

NATS_EXTERN natsStatus 	stanConnOptions_Create (stanConnOptions **newOpts)

 	Creates a stanConnOptions object.  More...

NATS_EXTERN natsStatus 	stanConnOptions_SetURL (stanConnOptions *opts, const char *url)

 	Sets the URL to connect to.  More...

NATS_EXTERN natsStatus 	stanConnOptions_SetNATSOptions (stanConnOptions *opts, natsOptions *nOpts)

 	Sets the NATS Options to use to create the connection.  More...

NATS_EXTERN natsStatus 	stanConnOptions_SetConnectionWait (stanConnOptions *opts, int64_t wait)

 	Sets the timeout for establishing a connection.  More...

NATS_EXTERN natsStatus 	stanConnOptions_SetPubAckWait (stanConnOptions *opts, int64_t wait)

 	Sets the timeout for waiting for an ACK for a published message.  More...

NATS_EXTERN natsStatus 	stanConnOptions_SetDiscoveryPrefix (stanConnOptions *opts, const char *prefix)

 	Sets the subject prefix the library sends the connect request to.  More...

NATS_EXTERN natsStatus 	stanConnOptions_SetMaxPubAcksInflight (stanConnOptions *opts, int maxPubAcksInflight, float percentage)

 	Sets the maximum number of published messages without outstanding ACKs from the server.  More...

NATS_EXTERN natsStatus 	stanConnOptions_SetPings (stanConnOptions *opts, int interval, int maxOut)

 	Sets the ping interval and max out values.  More...

NATS_EXTERN natsStatus 	stanConnOptions_SetConnectionLostHandler (stanConnOptions *opts, stanConnectionLostHandler handler, void *closure)

 	Sets the connection lost handler.  More...

NATS_EXTERN void 	stanConnOptions_Destroy (stanConnOptions *opts)

 	Destroys a stanConnOptions object.  More...

Detailed Description

NATS Streaming Connection Options.

Function Documentation

          NATS_EXTERN natsStatus stanConnOptions_Create
          (
          stanConnOptions **
          newOpts	)

Creates a stanConnOptions object. This object is used when one wants to set specific options prior to connecting to the NATS Streaning Server.

After making the appropriate stanConnOptions_SetXXX() calls, this object is passed to the stanConnection_Connect() call, which will clone this object. After stanConnection_Connect() returns, modifications to the options object will not affect the connection.

The default options set in this call are: url: nats://localhost:4222 connection wait: 2 seconds publish ack wait: 30 seconds discovery prefix: _STAN.discovery maximum publish acks inflight and percentage: 16384, 50% ping interval: 5 seconds max ping out without response: 3

Note

The object needs to be destroyed when no longer needed.

See also

stanConnection_Connect()

stanConnOptions_Destroy()

Parameters

newOpts	the location where store the pointer to the newly created stanConnOptions object.

          NATS_EXTERN natsStatus stanConnOptions_SetURL
          (
          stanConnOptions *
          opts,

          const char *
          url

          )

Sets the URL of the NATS Streaming Server the client should try to connect to. The URL can contain optional user name and password. You can provide a comma separated list of URLs too.

Some valid URLS:

nats://localhost:4222

nats://user@localhost:4222

nats://user:password@localhost:4222

nats://host1:4222,nats://host2:4222,nats://host3:4222

Note

This option takes precedence over natsOptions_SetURL when NATS options are passed with stanConnOptions_SetNATSOptions.

Parameters

opts	the pointer to the stanConnOptions object.

url	the string representing the URL the connection should use to connect to the server.

          NATS_EXTERN natsStatus stanConnOptions_SetNATSOptions
          (
          stanConnOptions *
          opts,

          natsOptions *
          nOpts

          )

The Streaming client connects to the NATS Streaming Server through a regular NATS Connection (natsConnection). To configure this connection create a natsOptions and configure it as needed, then call this function.

This function clones the passed options, so after this call, any changes to the given natsOptions will not affect the stanConnOptions.

Note

If both natsOptions_SetURL and stanConnOptions_SetURL are used the URL(s) set in the later take precedence.

Parameters

opts	the pointer to the stanConnOptions object.

nOpts	the pointer to the natsOptions object to use to create the connection to the server.

          NATS_EXTERN natsStatus stanConnOptions_SetConnectionWait
          (
          stanConnOptions *
          opts,

          int64_t
          wait

          )

Value expressed in milliseconds.

Default is 2000 milliseconds (2 seconds).

Parameters

opts	the pointer to the stanConnOptions object.

wait	how long to wait for a response from the streaming server.

          NATS_EXTERN natsStatus stanConnOptions_SetPubAckWait
          (
          stanConnOptions *
          opts,

          int64_t
          wait

          )

Value expressed in milliseconds.

Default is 30000 milliseconds (30 seconds).

Parameters

opts	the pointer to the stanConnOptions object.

wait	how long to wait for a response from the streaming server.

          NATS_EXTERN natsStatus stanConnOptions_SetDiscoveryPrefix
          (
          stanConnOptions *
          opts,

          const char *
          prefix

          )

Default is _STAN.discovery

Parameters

opts	the pointer to the stanConnOptions object.

prefix	the subject prefix the library sends the connect request to.

          NATS_EXTERN natsStatus stanConnOptions_SetMaxPubAcksInflight
          (
          stanConnOptions *
          opts,

          int
          maxPubAcksInflight,

          float
          percentage

          )

A connection will block stanConnection_Publish() or stanConnection_PublishAsync calls if the number of outstanding published messages has reached this number.

When the connection receives ACKs, the number of outstanding messages will decrease. If the number falls between maxPubAcksInflight * percentage, then the blocked publish calls will be released.

Parameters

opts	the pointer to the stanConnOptions object.

maxPubAcksInflight	the maximum number of published messages without ACKs from the server.

percentage	the percentage (expressed as a float between ]0.0 and 1.0]) of the maxPubAcksInflight number below which a blocked publish call is released.

          NATS_EXTERN natsStatus stanConnOptions_SetPings
          (
          stanConnOptions *
          opts,

          int
          interval,

          int
          maxOut

          )

Value expressed in number of seconds.

Default is 5 seconds and 3 missed PONGs.

The interval needs to be at least 1 and represents the number of seconds. The maxOut needs to be at least 2, since the count of sent PINGs increase whenever a PING is sent and reset to 0 when a response is received. Setting to 1 would cause the library to close the connection right away.

Parameters

opts	the pointer to the stanConnOptions object.

interval	the number of seconds between each PING.

maxOut	the maximum number of PINGs without receiving a PONG back.

          NATS_EXTERN natsStatus stanConnOptions_SetConnectionLostHandler
          (
          stanConnOptions *
          opts,

          stanConnectionLostHandler
          handler,

          void *
          closure

          )

This callback will be invoked should the client permanently lose contact with the server (or another client replaces it while being disconnected). The callback will not be invoked on normal stanConnection_Close().

Parameters

opts	the pointer to the stanConnOptions object.

handler	the handler to be invoked when the connection to the streaming server is lost.

closure	the closure the library will pass to the callback.

          NATS_EXTERN void stanConnOptions_Destroy
          (
          stanConnOptions *
          opts	)

Destroys the stanConnOptions object, freeing used memory. See the note in the stanConnOptions_Create() call.

Parameters

opts	the pointer to the stanConnOptions object to destroy.

NATS.IO Supported By Synadia Communications Inc.


text:
package Calculator;

import java.awt.event.*;

public class CalcController {

    // There is a reference to both the view and the model
    private static CalcView view = new CalcView();
    private static CalcModel model = new CalcModel();

    public static void main(String[] args) {
        /**
        * Create and set the listeners to the view
        */
        // Addition
        view.setAddListener ( new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                view.setResult( model.addValues ( view.getOperand1(), view.getOperand2()) );
            }
        });

        // Subtraction
        view.setSubtractListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                view.setResult(
                    model.subtractValues(
                        view.getOperand1(),
                        view.getOperand2())
                    );
                }
            }
        );

        // Multiplication
        view.setMultiplyListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                view.setResult(
                    model.multiplyValues(
                        view.getOperand1(),
                        view.getOperand2())
                    );
                }
            }
        );

        // Multiplication
        view.setDivideListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(view.getOperand2() == 0) {
                    view.resultText.setText("Err");
                } else {
                    view.setResult(
                        model.divideValues(
                            view.getOperand1(),
                            view.getOperand2())
                        );
                    }
                }
            }
        );
    }

    CalcController controller = new CalcController();
};


text:
<!DOCTYPE html>

    <title>Example</title>

    <link rel="stylesheet" type="text/css" href="jquery-ui-1.8.16.custom.css"/>

    <form>

            <input type="submit" value="Submit"/>
            <input type="reset" value="Reset"/>
            <input type="button" value="Press Me"/>
            Visit Apress

    </form>


text:
package org.apache.sling.fsprovider.internal.mapper;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.BitSet;

import org.apache.commons.lang3.CharEncoding;

/**
 * Manages deescaping for platform file names to resource names.
 */
public final class Escape {

    /**
     * List of characters typically prohibited on unix and windows file systems.
     * "/" is not included because it is neither allowed in resource nor in file names on any system.
     */
    private static final char[] RESERVED_CHARS = {
            '<',
            '>',
            ':',
            '"',
            '\\',
            '|',
            '?',
            '*',
            0x00
    };
    private static final BitSet RESERVED_CHARS_SET = new BitSet();
    static {
        for (int i=0; i<RESERVED_CHARS.length; i++) {
            RESERVED_CHARS_SET.set(RESERVED_CHARS[i]);
        }
    }

    private Escape() {
        // static methods only
    }

    /**
     * Convert file name to resource name.
     * Applies same rules as Apache Sling JCR ContentLoader.
     * @param path File name or path
     * @return Resource name or path
     */
    public static String fileToResourceName(String path) {
        // check for encoded characters (%xx)
        // has encoded characters, need to decode
        if (path.indexOf('%') >= 0) {
            try {
                return URLDecoder.decode(path, "UTF-8");
            }
            catch (UnsupportedEncodingException ex) {
                throw new RuntimeException("Unsupported encoding.", ex);
            }
        }
        return path;
    }

    /**
     * Converts resource name to file name.
     * Allows all characters, but URL-encodes characters that are in the list of {@link #RESERVED_CHARS}.
     * @param path Resource name or path
     * @return File name or path
     */
    public static String resourceToFileName(String path) {
        try {
            StringBuilder result = new StringBuilder();
            for (int i=0; i<path.length(); i++) {
                char c = path.charAt(i);
                if (RESERVED_CHARS_SET.get(c)) {
                    result.append(URLEncoder.encode(String.valueOf(c), CharEncoding.UTF_8));
                }
                else {
                    result.append(c);
                }
            }
            return result.toString();
        }
        catch (UnsupportedEncodingException ex) {
            throw new RuntimeException("Unsupported encoding.", ex);
        }
    }

}


text:
package org.apache.lucene.analysis.shingle;

import java.io.IOException;
import java.io.Reader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.util.Version;

/**
 * A ShingleAnalyzerWrapper wraps a {@link ShingleFilter} around another {@link Analyzer}.
 *

 * A shingle is another name for a token based n-gram.
 *

 */
public final class ShingleAnalyzerWrapper extends Analyzer {

  private final Analyzer defaultAnalyzer;
  private int maxShingleSize = ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE;
  private int minShingleSize = ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE;
  private String tokenSeparator = ShingleFilter.TOKEN_SEPARATOR;
  private boolean outputUnigrams = true;
  private boolean outputUnigramsIfNoShingles = false;

  public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer) {
    this(defaultAnalyzer, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE);
  }

  public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer, int maxShingleSize) {
    this(defaultAnalyzer, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, maxShingleSize);
  }

  public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer, int minShingleSize, int maxShingleSize) {
    this(defaultAnalyzer, minShingleSize, maxShingleSize, ShingleFilter.TOKEN_SEPARATOR, true, false);
  }

  /**
   * Creates a new ShingleAnalyzerWrapper
   *
   * @param defaultAnalyzer Analyzer whose TokenStream is to be filtered
   * @param minShingleSize Min shingle (token ngram) size
   * @param maxShingleSize Max shingle size
   * @param tokenSeparator Used to separate input stream tokens in output shingles
   * @param outputUnigrams Whether or not the filter shall pass the original
   *        tokens to the output stream
   * @param outputUnigramsIfNoShingles Overrides the behavior of outputUnigrams==false for those
   *        times when no shingles are available (because there are fewer than
   *        minShingleSize tokens in the input stream)?
   *        Note that if outputUnigrams==true, then unigrams are always output,
   *        regardless of whether any shingles are available.
   */
  public ShingleAnalyzerWrapper(
      Analyzer defaultAnalyzer,
      int minShingleSize,
      int maxShingleSize,
      String tokenSeparator,
      boolean outputUnigrams,
      boolean outputUnigramsIfNoShingles) {
    this.defaultAnalyzer = defaultAnalyzer;

    if (maxShingleSize < 2) {
      throw new IllegalArgumentException("Max shingle size must be >= 2");
    }
    this.maxShingleSize = maxShingleSize;

    if (minShingleSize < 2) {
      throw new IllegalArgumentException("Min shingle size must be >= 2");
    }
    if (minShingleSize > maxShingleSize) {
      throw new IllegalArgumentException
        ("Min shingle size must be <= max shingle size");
    }
    this.minShingleSize = minShingleSize;

    this.tokenSeparator = (tokenSeparator == null ? "" : tokenSeparator);
    this.outputUnigrams = outputUnigrams;
    this.outputUnigramsIfNoShingles = outputUnigramsIfNoShingles;
  }

  /**
   * Wraps {@link StandardAnalyzer}.
   */
  public ShingleAnalyzerWrapper(Version matchVersion) {
    this(matchVersion, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE);
  }

  /**
   * Wraps {@link StandardAnalyzer}.
   */
  public ShingleAnalyzerWrapper(Version matchVersion, int minShingleSize, int maxShingleSize) {
    this(new StandardAnalyzer(matchVersion), minShingleSize, maxShingleSize);
  }

  /**
   * The max shingle (token ngram) size
   *
   * @return The max shingle (token ngram) size
   */
  public int getMaxShingleSize() {
    return maxShingleSize;
  }

  /**
   * Set the maximum size of output shingles (default: 2)
   *
   * @param maxShingleSize max shingle size
   * @deprecated Setting maxShingleSize after Analyzer instantiation prevents reuse.
   *             Confgure maxShingleSize during construction.
   */
  @Deprecated
  public void setMaxShingleSize(int maxShingleSize) {
    if (maxShingleSize < 2) {
      throw new IllegalArgumentException("Max shingle size must be >= 2");
    }
    this.maxShingleSize = maxShingleSize;
  }

  /**
   * The min shingle (token ngram) size
   *
   * @return The min shingle (token ngram) size
   */
  public int getMinShingleSize() {
    return minShingleSize;
  }

  /**
   *
Set the min shingle size (default: 2).
   *
This method requires that the passed in minShingleSize is not greater
   * than maxShingleSize, so make sure that maxShingleSize is set before
   * calling this method.
   *
   * @param minShingleSize min size of output shingles
   * @deprecated Setting minShingleSize after Analyzer instantiation prevents reuse.
   *             Confgure minShingleSize during construction.
   */
  @Deprecated
  public void setMinShingleSize(int minShingleSize) {
    if (minShingleSize < 2) {
      throw new IllegalArgumentException("Min shingle size must be >= 2");
    }
    if (minShingleSize > maxShingleSize) {
      throw new IllegalArgumentException
        ("Min shingle size must be <= max shingle size");
    }
    this.minShingleSize = minShingleSize;
  }

  public String getTokenSeparator() {
    return tokenSeparator;
  }

  /**
   * Sets the string to use when joining adjacent tokens to form a shingle
   * @param tokenSeparator used to separate input stream tokens in output shingles
   * @deprecated Setting tokenSeparator after Analyzer instantiation prevents reuse.
   *             Confgure tokenSeparator during construction.
   */
  @Deprecated
  public void setTokenSeparator(String tokenSeparator) {
    this.tokenSeparator = (tokenSeparator == null ? "" : tokenSeparator);
  }

  public boolean isOutputUnigrams() {
    return outputUnigrams;
  }

  /**
   * Shall the filter pass the original tokens (the "unigrams") to the output
   * stream?
   *
   * @param outputUnigrams Whether or not the filter shall pass the original
   *        tokens to the output stream
   * @deprecated Setting outputUnigrams after Analyzer instantiation prevents reuse.
   *             Confgure outputUnigrams during construction.
   */
  @Deprecated
  public void setOutputUnigrams(boolean outputUnigrams) {
    this.outputUnigrams = outputUnigrams;
  }

  public boolean isOutputUnigramsIfNoShingles() {
    return outputUnigramsIfNoShingles;
  }

  /**
   *
Shall we override the behavior of outputUnigrams==false for those
   * times when no shingles are available (because there are fewer than
   * minShingleSize tokens in the input stream)? (default: false.)
   *
Note that if outputUnigrams==true, then unigrams are always output,
   * regardless of whether any shingles are available.
   *
   * @param outputUnigramsIfNoShingles Whether or not to output a single
   *  unigram when no shingles are available.
   * @deprecated Setting outputUnigramsIfNoShingles after Analyzer instantiation prevents reuse.
   *             Confgure outputUnigramsIfNoShingles during construction.
   */
  @Deprecated
  public void setOutputUnigramsIfNoShingles(boolean outputUnigramsIfNoShingles) {
    this.outputUnigramsIfNoShingles = outputUnigramsIfNoShingles;
  }

  @Override
  public TokenStream tokenStream(String fieldName, Reader reader) {
    TokenStream wrapped;
    try {
      wrapped = defaultAnalyzer.reusableTokenStream(fieldName, reader);
    } catch (IOException e) {
      wrapped = defaultAnalyzer.tokenStream(fieldName, reader);
    }
    ShingleFilter filter = new ShingleFilter(wrapped, minShingleSize, maxShingleSize);
    filter.setMinShingleSize(minShingleSize);
    filter.setMaxShingleSize(maxShingleSize);
    filter.setTokenSeparator(tokenSeparator);
    filter.setOutputUnigrams(outputUnigrams);
    filter.setOutputUnigramsIfNoShingles(outputUnigramsIfNoShingles);
    return filter;
  }

  private class SavedStreams {
    TokenStream wrapped;
    ShingleFilter shingle;
  }

  @Override
  public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException {
    SavedStreams streams = (SavedStreams) getPreviousTokenStream();
    if (streams == null) {
      streams = new SavedStreams();
      streams.wrapped = defaultAnalyzer.reusableTokenStream(fieldName, reader);
      streams.shingle = new ShingleFilter(streams.wrapped);
      setPreviousTokenStream(streams);
    } else {
      TokenStream result = defaultAnalyzer.reusableTokenStream(fieldName, reader);
      if (result != streams.wrapped) {
        /* the wrapped analyzer did not, create a new shingle around the new one */
        streams.wrapped = result;
        streams.shingle = new ShingleFilter(streams.wrapped);
      }
    }
    streams.shingle.setMaxShingleSize(maxShingleSize);
    streams.shingle.setMinShingleSize(minShingleSize);
    streams.shingle.setTokenSeparator(tokenSeparator);
    streams.shingle.setOutputUnigrams(outputUnigrams);
    streams.shingle.setOutputUnigramsIfNoShingles(outputUnigramsIfNoShingles);
    return streams.shingle;
  }
}


text:
<?php

namespace SaM\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return array();
    }
}


text:
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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.
package com.google.devtools.build.lib.skylarkbuildapi.android;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.skylarkbuildapi.FileApi;
import com.google.devtools.build.lib.skylarkbuildapi.ProviderApi;
import com.google.devtools.build.lib.skylarkbuildapi.StructApi;
import com.google.devtools.build.lib.skylarkinterface.Param;
import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable;
import com.google.devtools.build.lib.skylarkinterface.SkylarkConstructor;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.SkylarkList;

/** A target that can provide local proguard specifications. */
@SkylarkModule(
    name = "AndroidProguardInfo",
    doc =
        "Do not use this module. It is intended for migration purposes only. If you depend on it, "
            + "you will be broken when it is removed.",
    documented = false)
public interface AndroidProguardInfoApi<FileT extends FileApi> extends StructApi {
  /** The name of the provider for this info object. */
  String NAME = "AndroidProguardInfo";

  @SkylarkCallable(
      name = "local_proguard_specs",
      structField = true,
      doc = "Returns the local proguard specs defined by this target.",
      documented = false)
  ImmutableList<FileT> getLocalProguardSpecs();

  /** The provider implementing this can construct the AndroidProguardInfo provider. */
  @SkylarkModule(
      name = "Provider",
      doc =
          "Do not use this module. It is intended for migration purposes only. If you depend on "
              + "it, you will be broken when it is removed.",
      documented = false)
  public interface Provider<FileT extends FileApi> extends ProviderApi {

    @SkylarkCallable(
        name = NAME,
        doc = "The AndroidProguardInfo constructor.",
        documented = false,
        parameters = {
          @Param(
              name = "local_proguard_specs",
              doc = "A list of local proguard specs.",
              positional = true,
              named = false,
              type = SkylarkList.class,
              generic1 = FileApi.class)
        },
        selfCall = true)
    @SkylarkConstructor(objectType = AndroidProguardInfoApi.class)
    AndroidProguardInfoApi<FileT> createInfo(SkylarkList<?> localProguardSpecs /* <FileT> */)
        throws EvalException;
  }
}


text:
package org.apache.asterix.common.context;

import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndex;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTracker;
import org.apache.hyracks.storage.am.lsm.common.api.LSMOperationType;
import org.apache.hyracks.storage.common.IModificationOperationCallback;
import org.apache.hyracks.storage.common.ISearchOperationCallback;

public class BaseOperationTracker implements ILSMOperationTracker {

    protected final int datasetID;
    protected final DatasetInfo dsInfo;

    public BaseOperationTracker(int datasetID, DatasetInfo dsInfo) {
        this.datasetID = datasetID;
        this.dsInfo = dsInfo;
    }

    @Override
    public void beforeOperation(ILSMIndex index, LSMOperationType opType, ISearchOperationCallback searchCallback,
            IModificationOperationCallback modificationCallback) throws HyracksDataException {
        if (opType == LSMOperationType.FLUSH || opType == LSMOperationType.MERGE
                || opType == LSMOperationType.REPLICATE) {
            dsInfo.declareActiveIOOperation();
        }
    }

    @Override
    public void afterOperation(ILSMIndex index, LSMOperationType opType, ISearchOperationCallback searchCallback,
            IModificationOperationCallback modificationCallback) throws HyracksDataException {
        if (opType == LSMOperationType.FLUSH || opType == LSMOperationType.MERGE
                || opType == LSMOperationType.REPLICATE) {
            dsInfo.undeclareActiveIOOperation();
        }
    }

    @Override
    public void completeOperation(ILSMIndex index, LSMOperationType opType, ISearchOperationCallback searchCallback,
            IModificationOperationCallback modificationCallback) throws HyracksDataException {
    }

    public void exclusiveJobCommitted() throws HyracksDataException {
    }
}


text:
FROM ubuntu:18.04

RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
    && localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8
ENV LANG en_US.utf8

RUN apt-get update && apt-get install -y \
    git \
    autoconf \
    pkg-config \
    build-essential \
    libtool \
    python3 \
    wget \
    jq \
    bc

RUN apt-get install -y nodejs npm
RUN npm install n -g
RUN n stable
RUN apt purge -y nodejs npm

COPY . ptarmigan

WORKDIR ptarmigan

RUN make full

RUN cd ./ptarmapi/ && npm install

RUN cp ./tests/BTCPayServer.Lightning/ptarm/docker-entrypoint.sh ./
RUN chmod +x docker-entrypoint.sh

ENTRYPOINT ["./docker-entrypoint.sh"]


text:
local function printf(fmt, ...)
	io.write(string.format(fmt, ...))
end

local function fprintf(f, fmt, ...)
	io.write(string.format(fmt, ...));
end

local exports = {
	fprintf = fprintf;
	printf = printf;
}

setmetatable(exports, {
	__call = function(self, ...)
		for k,v in pairs(exports) do
			_G[k] = v;
		end

		return self
	end,
})

return exports


text:
<?php

namespace Zend\Markup\Parser\Exception;

class RuntimeException
    extends \RuntimeException
    implements \Zend\Markup\Parser\Exception
{}


text:
"""
Service object
"""

from oslo_versionedobjects import base
from oslo_versionedobjects import fields

from heat.db import api as db_api

class Service(base.VersionedObject,
              base.VersionedObjectDictCompat,
              base.ComparableVersionedObject):
    fields = {
        'id': fields.StringField(),
        'engine_id': fields.StringField(),
        'host': fields.StringField(),
        'hostname': fields.StringField(),
        'binary': fields.StringField(),
        'topic': fields.StringField(),
        'report_interval': fields.IntegerField(),
        'created_at': fields.DateTimeField(read_only=True),
        'updated_at': fields.DateTimeField(nullable=True),
        'deleted_at': fields.DateTimeField(nullable=True)
    }

    @staticmethod
    def _from_db_object(context, service, db_service):
        for field in service.fields:
            service[field] = db_service[field]
        service._context = context
        service.obj_reset_changes()
        return service

    @classmethod
    def _from_db_objects(cls, context, list_obj):
        return map(lambda obj: cls._from_db_object(context,
                                                   cls(context),
                                                   obj),
                   list_obj)

    @classmethod
    def get_by_id(cls, context, service_id):
        service_db = db_api.service_get(context, service_id)
        service = cls._from_db_object(context, cls(), service_db)
        return service

    @classmethod
    def create(cls, context, values):
        return cls._from_db_object(
            context,
            cls(),
            db_api.service_create(context, values))

    @classmethod
    def update_by_id(cls, context, service_id, values):
        return cls._from_db_object(
            context,
            cls(),
            db_api.service_update(context, service_id, values))

    @classmethod
    def delete(cls, context, service_id, soft_delete=True):
        return db_api.service_delete(context, service_id, soft_delete)

    @classmethod
    def get_all(cls, context):
        return cls._from_db_objects(context,
                                    db_api.service_get_all(context))

    @classmethod
    def get_all_by_args(cls, context, host, binary, hostname):
        return cls._from_db_objects(
            context,
            db_api.service_get_all_by_args(context,
                                           host,
                                           binary,
                                           hostname))


text:
package com.jassmp.MainMenu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.jassmp.GuiHelper.UIElementsHelper;
import com.jassmp.MainActivity.MainActivity;
import com.jassmp.R;
import com.jassmp.SettingsActivity.SettingsActivity;
import com.jassmp.Utils.Common;

public class MainMenuDrawerFragment extends Fragment {

    //
    // defines

    public static enum MenuItem {
        NOW_PLAYING( 0, MainActivity.FragmentId.NOW_PLAYING ),
        SONGS( 1, MainActivity.FragmentId.SONGS ),
        GENRES( 2, MainActivity.FragmentId.GENRES ),
        ARTISTS( 3, MainActivity.FragmentId.ARTISTS ),
        ALBUMS( 4, MainActivity.FragmentId.ALBUMS ),
        SETTINGS( 5, SettingsActivity.class );

        public final int                     position;
        public final MainActivity.FragmentId fragmentId;
        public final Class<?>                activity;

        public         String     title      = null;
        public static  String[]   titles     = null;
        private static MenuItem[] byPosition = null;

        private MenuItem( final int position, final MainActivity.FragmentId fragmentId ) {
            this( position, fragmentId, null );
        }

        private MenuItem( final int position, final Class<?> activity ) {
            this( position, MainActivity.FragmentId.NONE, activity );
        }

        private MenuItem( final int position, final MainActivity.FragmentId fragmentId, final Class<?> activity ) {
            this.position = position;
            this.fragmentId = fragmentId;
            this.activity = activity;
        }

        public static void init( final Activity activity ) {
            final MenuItem[] items = MenuItem.values();
            byPosition = new MenuItem[ items.length ];
            for( final MenuItem item : items ) {
                byPosition[ item.position ] = item;
            }

            titles = activity.getResources().getStringArray( R.array.sliding_menu_array );
            for( MenuItem item : MenuItem.values() ) {
                item.title = titles[ item.position ];
            }
        }

        public boolean isFragment() {
            return fragmentId != MainActivity.FragmentId.NONE;
        }

        public static MenuItem getByPosition( final int position ) {
            return byPosition[ position ];
        }
    }

    //
    // private members

    private ListView mmMenuItemsView;
    private Handler  mHandler;

    @SuppressWarnings( "deprecation" )
    @SuppressLint( "NewApi" )
    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
        final Context context = getActivity();
        mHandler = new Handler();

        MenuItem.init( getActivity() );

        final View rootView = inflater.inflate( R.layout.navigation_drawer_layout, null );
        rootView.setBackgroundColor( UIElementsHelper.getBackgroundColor( context ) );

        mmMenuItemsView = (ListView) rootView.findViewById( R.id.browsers_list_view );
        resetAdapter( getActivity() );
        mmMenuItemsView.setOnItemClickListener( mMenuItemsClickListener );
        //setListViewHeightBasedOnChildren( mmMenuItemsView );

        mmMenuItemsView.setDividerHeight( 0 );

        //KitKat translucent navigation/status bar.
        if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ) {
            int navBarHeight = Common.getNavigationBarHeight( context );
            if( mmMenuItemsView != null ) {
                mmMenuItemsView.setPadding( 0, 0, 0, navBarHeight );
                mmMenuItemsView.setClipToPadding( false );
            }

        }

        return rootView;
    }

    private OnItemClickListener mMenuItemsClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick( final AdapterView<?> adapterView, final View view, final int position,
                                 final long dbID ) {
            final MenuItem menuItem = MenuItem.values()[ position ];
            if( menuItem.isFragment() ) {
                ( (MainActivity) getActivity() ).switchFragment( menuItem.fragmentId );
            } else {
                Intent intent = new Intent( getActivity(), SettingsActivity.class );
                startActivity( intent );
            }

            resetAdapter( getActivity() );
        }

    };

    public void resetAdapter( final Activity activity ) {
        MainActivity.FragmentId currentFragment = MainActivity.FragmentId.NONE;
        if( activity instanceof MainActivity ) {
            currentFragment = ( (MainActivity) activity ).getCurrentFragmentId();

        }
        mmMenuItemsView.setAdapter( new MainMenuDrawerAdapter( activity, currentFragment ) );
    }

}


text:
Sending Mail
============

Djrill handles **all** outgoing email sent through Django's standard
:mod:`django.core.mail` package, including :func:`~django.core.mail.send_mail`,
:func:`~django.core.mail.send_mass_mail`, the :class:`~django.core.mail.EmailMessage` class,
and even :func:`~django.core.mail.mail_admins`.

If you'd like to selectively send only some messages through Mandrill,
there is a way to :ref:`use multiple email backends <multiple-backends>`.

.. _django-send-support:

Django Email Support
--------------------

Djrill supports most of the functionality of Django's :class:`~django.core.mail.EmailMessage`
and :class:`~django.core.mail.EmailMultiAlternatives` classes.

Some notes and limitations:

**Display Names**
    All email addresses (from, to, cc, bcc) can be simple
    ("email\@example.com") or can include a display name
    ("Real Name <email\@example.com>").

**CC and BCC Recipients**
    Djrill properly identifies "cc" and "bcc" recipients to Mandrill.

    Note that you may need to set the Mandrill option :attr:`preserve_recipients`
    to `!True` if you want recipients to be able to see who else was included
    in the "to" list.

.. _sending-html:

**HTML/Alternative Parts**
    To include an HTML version of a message, use
    :meth:`~django.core.mail.EmailMultiAlternatives.attach_alternative`:

    .. code-block:: python

        from django.core.mail import EmailMultiAlternatives

        msg = EmailMultiAlternatives("Subject", "text body",
                                     "from@example.com", ["to@example.com"])
        msg.attach_alternative("<html>html body</html>", "text/html")

    Djrill allows a maximum of one
    :meth:`~django.core.mail.EmailMultiAlternatives.attach_alternative`
    on a message, and it must be ``mimetype="text/html"``.
    Otherwise, Djrill will raise :exc:`~djrill.NotSupportedByMandrillError` when you
    attempt to send the message. (Mandrill doesn't support sending multiple html
    alternative parts, or any non-html alternatives.)

.. _sending-attachments:

**Attachments**
    Djrill will send a message's attachments. (Note that Mandrill may impose limits
    on size and type of attachments.)

    Also, if an image attachment has a Content-ID header, Djrill will tell Mandrill
    to treat that as an embedded image rather than an ordinary attachment.
    (For an example, see :meth:`~DjrillBackendTests.test_embedded_images`
    in :file:`tests/test_mandrill_send.py`.)

.. _message-headers:

**Headers**
    Djrill accepts additional headers and passes them along to Mandrill:

    .. code-block:: python

        msg = EmailMessage( ...
            headers={'Reply-To': "reply@example.com", 'List-Unsubscribe': "..."}
        )

    .. note::

       Djrill also supports the `reply_to` param added to
       :class:`~django.core.mail.EmailMessage` in Django 1.8.
       (If you provide *both* a 'Reply-To' header and the `reply_to` param,
       the header will take precedence.)

.. _mandrill-send-support:

Mandrill-Specific Options
-------------------------

Most of the options from the Mandrill
`messages/send API <https://mandrillapp.com/api/docs/messages.html#method=send>`_
`message` struct can be set directly on an :class:`~django.core.mail.EmailMessage`
(or subclass) object.

.. note::

    You can set global defaults for common options with the
    :setting:`MANDRILL_SETTINGS` setting, to avoid having to
    set them on every message.

.. These attributes are in the same order as they appear in the Mandrill API docs...

.. attribute:: important

    ``Boolean``: whether Mandrill should send this message ahead of non-important ones.

.. attribute:: track_opens

    ``Boolean``: whether Mandrill should enable open-tracking for this message.
    Default from your Mandrill account settings. ::

        message.track_opens = True

.. attribute:: track_clicks

    ``Boolean``: whether Mandrill should enable click-tracking for this message.
    Default from your Mandrill account settings.

    .. note::

        Mandrill has an option to track clicks in HTML email but not plaintext, but
        it's *only* available in your Mandrill account settings. If you want to use that
        option, set it at Mandrill, and *don't* set the ``track_clicks`` attribute here.

.. attribute:: auto_text

    ``Boolean``: whether Mandrill should automatically generate a text body from the HTML.
    Default from your Mandrill account settings.

.. attribute:: auto_html

    ``Boolean``: whether Mandrill should automatically generate an HTML body from the plaintext.
    Default from your Mandrill account settings.

.. attribute:: inline_css

    ``Boolean``: whether Mandrill should inline CSS styles in the HTML.
    Default from your Mandrill account settings.

.. attribute:: url_strip_qs

    ``Boolean``: whether Mandrill should ignore any query parameters when aggregating
    URL tracking data. Default from your Mandrill account settings.

.. attribute:: preserve_recipients

    ``Boolean``: whether Mandrill should include all recipients in the "to" message header.
    Default from your Mandrill account settings.

.. attribute:: view_content_link

    ``Boolean``: set False on sensitive messages to instruct Mandrill not to log the content.

.. attribute:: tracking_domain

    ``str``: domain Mandrill should use to rewrite tracked links and host tracking pixels
    for this message. Useful if you send email from multiple domains.
    Default from your Mandrill account settings.

.. attribute:: signing_domain

    ``str``: domain Mandrill should use for DKIM signing and SPF on this message.
    Useful if you send email from multiple domains.
    Default from your Mandrill account settings.

.. attribute:: return_path_domain

    ``str``: domain Mandrill should use for the message's return-path.

.. attribute:: merge_language

    ``str``: the merge tag language if using merge tags -- e.g., "mailchimp" or "handlebars".
    Default from your Mandrill account settings.

.. attribute:: global_merge_vars

    ``dict``: merge variables to use for all recipients (most useful with :ref:`mandrill-templates`). ::

        message.global_merge_vars = {'company': "ACME", 'offer': "10% off"}

    Merge data must be strings or other JSON-serializable types.
    (See :ref:`formatting-merge-data` for details.)

.. attribute:: merge_vars

    ``dict``: per-recipient merge variables (most useful with :ref:`mandrill-templates`). The keys
    in the dict are the recipient email addresses, and the values are dicts of merge vars for
    each recipient::

        message.merge_vars = {
            'wiley@example.com': {'offer': "15% off anvils"},
            'rr@example.com':    {'offer': "instant tunnel paint"}
        }

    Merge data must be strings or other JSON-serializable types.
    (See :ref:`formatting-merge-data` for details.)

.. attribute:: tags

    ``list`` of ``str``: tags to apply to the message, for filtering reports in the Mandrill
    dashboard. (Note that Mandrill prohibits tags longer than 50 characters or starting with
    underscores.) ::

        message.tags = ["Order Confirmation", "Test Variant A"]

.. attribute:: subaccount

    ``str``: the ID of one of your subaccounts to use for sending this message.

.. attribute:: google_analytics_domains

    ``list`` of ``str``: domain names for links where Mandrill should add Google Analytics
    tracking parameters. ::

        message.google_analytics_domains = ["example.com"]

.. attribute:: google_analytics_campaign

    ``str`` or ``list`` of ``str``: the utm_campaign tracking parameter to attach to links
    when adding Google Analytics tracking. (Mandrill defaults to the message's from_email as
    the campaign name.)

.. attribute:: metadata

    ``dict``: metadata values Mandrill should store with the message for later search and
    retrieval. ::

        message.metadata = {'customer': customer.id, 'order': order.reference_number}

    Mandrill restricts metadata keys to alphanumeric characters and underscore, and
    metadata values to numbers, strings, boolean values, and None (null).

.. attribute:: recipient_metadata

    ``dict``: per-recipient metadata values. Keys are the recipient email addresses,
    and values are dicts of metadata for each recipient (similar to
    :attr:`merge_vars`)

    Mandrill restricts metadata keys to alphanumeric characters and underscore, and
    metadata values to numbers, strings, boolean values, and None (null).

.. attribute:: async

    ``Boolean``: whether Mandrill should use an async mode optimized for bulk sending.

.. attribute:: ip_pool

    ``str``: name of one of your Mandrill dedicated IP pools to use for sending this message.

.. attribute:: send_at

    `datetime` or `date` or ``str``: instructs Mandrill to delay sending this message
    until the specified time. Example::

        msg.send_at = datetime.utcnow() + timedelta(hours=1)

    Mandrill requires a UTC string in the form ``YYYY-MM-DD HH:MM:SS``.
    Djrill will convert python dates and datetimes to this form.
    (Dates will be given a time of 00:00:00.)

    .. note:: Timezones

        Mandrill assumes :attr:`!send_at` is in the UTC timezone,
        which is likely *not* the same as your local time.

        Djrill will convert timezone-*aware* datetimes to UTC for you.
        But if you format your own string, supply a date, or a
        *naive* datetime, you must make sure it is in UTC.
        See the python `datetime` docs for more information.

        For example, ``msg.send_at = datetime.now() + timedelta(hours=1)``
        will try to schedule the message for an hour from the current time,
        but *interpreted in the UTC timezone* (which isn't what you want).
        If you're more than an hour west of the prime meridian, that will
        be in the past (and the message will get sent immediately). If
        you're east of there, the message might get sent quite a bit later
        than you intended. One solution is to use `utcnow` as shown in
        the earlier example.

    .. note::

        Scheduled sending is a paid Mandrill feature. If you are using
        a free Mandrill account, :attr:`!send_at` won't work.

All the Mandrill-specific attributes listed above work with *any*
:class:`~django.core.mail.EmailMessage`-derived object, so you can use them with
many other apps that add Django mail functionality.

If you have questions about the python syntax for any of these properties,
see :class:`DjrillMandrillFeatureTests` in :file:`tests/test_mandrill_send.py` for examples.

.. _mandrill-response:

Response from Mandrill
----------------------

.. attribute:: mandrill_response

Djrill adds a :attr:`!mandrill_response` attribute to each :class:`~django.core.mail.EmailMessage`
as it sends it. This allows you to retrieve message ids, initial status information and more.

For an EmailMessage that is successfully sent to one or more email addresses, :attr:`!mandrill_response` will
be set to a ``list`` of ``dict``, where each entry has info for one email address. See the Mandrill docs for the
`messages/send API <https://mandrillapp.com/api/docs/messages.html#method=send>`_ for full details.

For example, to get the Mandrill message id for a sent email you might do this::

        msg = EmailMultiAlternatives(subject="subject", body="body",
                                     from_email="sender@example.com",to=["someone@example.com"])
        msg.send()
        response = msg.mandrill_response[0]
        mandrill_id = response['_id']

For this example, msg.mandrill_response might look like this::

        msg.mandrill_response = [
            {
                "email": "someone@example.com",
                "status": "sent",
                "_id": "abc123abc123abc123abc123abc123"
            }
        ]

If an error is returned by Mandrill while sending the message then :attr:`!mandrill_response` will be set to None.

.. _djrill-exceptions:

Exceptions
----------

.. exception:: djrill.NotSupportedByMandrillError

    If the email tries to use features that aren't supported by Mandrill, the send
    call will raise a :exc:`~!djrill.NotSupportedByMandrillError` exception (a subclass
    of :exc:`ValueError`).

.. exception:: djrill.MandrillRecipientsRefused

    If *all* recipients (to, cc, bcc) of a message are invalid or rejected by Mandrill
    (e.g., because they are your Mandrill blacklist), the send call will raise a
    :exc:`~!djrill.MandrillRecipientsRefused` exception.
    You can examine the message's :attr:`mandrill_response` attribute
    to determine the cause of the error.

    If a single message is sent to multiple recipients, and *any* recipient is valid
    (or the message is queued by Mandrill because of rate limiting or :attr:`send_at`), then
    this exception will not be raised. You can still examine the mandrill_response
    property after the send to determine the status of each recipient.

    You can disable this exception by setting :setting:`MANDRILL_IGNORE_RECIPIENT_STATUS`
    to True in your settings.py, which will cause Djrill to treat any non-API-error response
    from Mandrill as a successful send.

    .. versionadded:: 2.0
       Djrill 1.x behaved as if ``MANDRILL_IGNORE_RECIPIENT_STATUS = True``.

.. exception:: djrill.MandrillAPIError

    If the Mandrill API fails or returns an error response, the send call will
    raise a :exc:`~!djrill.MandrillAPIError` exception (a subclass of :exc:`requests.HTTPError`).
    The exception's :attr:`status_code` and :attr:`response` attributes may
    help explain what went wrong. (Tip: you can also check Mandrill's
    `API error log <https://mandrillapp.com/settings/api>`_ to view the full API
    request and error response.)

.. exception:: djrill.NotSerializableForMandrillError

    The send call will raise a :exc:`~!djrill.NotSerializableForMandrillError` exception
    if the message has attached data which cannot be serialized to JSON for the Mandrill API.

    See :ref:`formatting-merge-data` for more information.

    .. versionadded:: 2.0
       Djrill 1.x raised a generic `TypeError` in this case.
       :exc:`~!djrill.NotSerializableForMandrillError` is a subclass of `TypeError`
       for compatibility with existing code.


text:
Buffer POST requests in batches. Flush when buffer is full or when N seconds have elapsed. Threadsafe.
The server/endpoint must support multiline POST requests.

### use case

Google Analytics, but useful for any endpoint that supports multiline POST

### installation

  go get -u github.com/DapperDodo/batchposter

### example

    func main() {

    	errorlogger := log.New(os.Stderr, "[GA BATCH ERROR] ", log.Llongfile)

    	// "http://www.google-analytics.com/batch" 	: the url to POST to
    	// 20										: the maximum batch size (`flush immediately when 20 POSTS are buffered`)
    	// time.Second*30							: the maximum time between flushes (`at least flush every N seconds`)
    	// errorlogger 								: logger where errors are reported to

    	ga := batchposter.New("http://www.google-analytics.com/batch", 20, time.Second*30, errorlogger)

    	for {
    		uuid := strconv.Itoa(1000000 + rand.Intn(8999999))

    		payload := "v=1&tid=UA-XXXXXXX-1&cid=" + uuid + "&t=event&ec=accounts&ea=create&aip=1&ds=api&uid=" + uuid
    		fmt.Println(payload)
    		err := ga.Post(payload)
    		if err != nil {
    			fmt.Println(err)
    		}
    		time.Sleep(time.Second)

    	}
    }


text:
from yapsy.IPlugin import IPlugin
from yapsy.PluginManager import PluginManager
from django.template import loader, Context
from django.db.models import Count
from server.models import *
from django.shortcuts import get_object_or_404
import server.utils as utils

class DiskSpace(IPlugin):
    def widget_width(self):
        return 4

    def plugin_type(self):
        return 'builtin'

    def get_description(self):
        return 'Available disk space'

    def widget_content(self, page, machines=None, theid=None):
        # The data is data is pulled from the database and passed to a template.

        # There are three possible views we're going to be rendering to - front, bu_dashbaord and group_dashboard. If page is set to bu_dashboard, or group_dashboard, you will be passed a business_unit or machine_group id to use (mainly for linking to the right search).
        if page == 'front':
            t = loader.get_template('plugins/traffic_lights_front.html')

        if page == 'bu_dashboard':
            t = loader.get_template('plugins/traffic_lights_id.html')

        if page == 'group_dashboard':
            t = loader.get_template('plugins/traffic_lights_id.html')

        try:
            disk_ok = machines.filter(hd_percent__lt=80).count()
        except:
            disk_ok = 0

        try:
            disk_warning = machines.filter(hd_percent__range=["80", "89"]).count()
        except:
            disk_warning = 0

        try:
            disk_alert = machines.filter(hd_percent__gte=90).count()
        except:
            disk_alert = 0

        c = Context({
            'title': 'Disk Space',
            'ok_label': '< 80%',
            'ok_count': disk_ok,
            'warning_label': '80% +',
            'warning_count': disk_warning,
            'alert_label': '90% +',
            'alert_count': disk_alert,
            'plugin': 'DiskSpace',
            'theid': theid,
            'page': page
        })
        return t.render(c)

    def filter_machines(self, machines, data):
        if data == 'ok':
            machines = machines.filter(hd_percent__lt=80)
            title = 'Machines with less than 80% disk utilization'

        elif data == 'warning':
            machines = machines.filter(hd_percent__range=["80", "89"])
            title = 'Machines with 80%-90% disk utilization'

        elif data == 'alert':
            machines = machines.filter(hd_percent__gte=90)
            title = 'Machines with more than 90% disk utilization'

        else:
            machines = None

        return machines, title


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class us.codecraft.webmagic.downloader.HttpClientRequestContext (webmagic-parent 0.7.3 API)</title>
<meta name="date" content="2017-08-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
us.codecraft.webmagic.downloader.HttpClientRequestContext

Packages that use HttpClientRequestContext

Package
Description

us.codecraft.webmagic.downloader

Downloader is the part that downloads web pages and store in Page object.

Uses of HttpClientRequestContext in us.codecraft.webmagic.downloader

Methods in us.codecraft.webmagic.downloader that return HttpClientRequestContext

Modifier and Type
Method and Description

HttpClientRequestContext
HttpUriRequestConverter.convert(Request request,
       Site site,
       Proxy proxy)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2017. All rights reserved.


text:
<?php

require_once 'PHPUnit/Framework/TestCase.php';
include_once 'phing/system/io/UnixFileSystem.php';

/**
 * Unit test for UnixFileSystem
 *
 * @author Michiel Rook <mrook@php.net>
 * @package phing.system.io
 */
class UnixFileSystemTest extends PHPUnit_Framework_TestCase {

    /**
     * @var FileSystem
     */
    private $fs;

    public function setUp() {
        $this->fs = new UnixFileSystem();
    }

    public function tearDown() {
    }

    public function testCompare() {
        $f1 = new PhingFile(__FILE__);
        $f2 = new PhingFile(__FILE__);

        $this->assertEquals($this->fs->compare($f1, $f2), 0);
    }
}


text:
import json
import os
import subprocess

from .model import (Group, Node, Call, Variable, BaseLanguage,
                    OWNER_CONST, GROUP_TYPE, is_installed, flatten, djoin)

def lineno(tree):
    """
    Return the line number of the AST
    :param tree ast:
    :rtype: int
    """
    return tree['attributes']['startLine']

def get_name(tree, from_='name'):
    """
    Get the name (token) of the AST node.
    :param tree ast:
    :rtype: str|None
    """
    # return tree['name']['name']
    if 'name' in tree and isinstance(tree['name'], str):
        return tree['name']

    if 'parts' in tree:
        return djoin(tree['parts'])

    if from_ in tree:
        return get_name(tree[from_])

    return None

def get_call_from_expr(func_expr):
    """
    Given an ast that represents a send call, clear and create our
    generic Call object. Some calls have no chance at resolution (e.g. array[2](param))
    so we return nothing instead.

    :param func_expr ast:
    :rtype: Call|None
    """
    if func_expr['nodeType'] == 'Expr_FuncCall':
        token = get_name(func_expr)
        owner_token = None
    elif func_expr['nodeType'] == 'Expr_New' and func_expr['class'].get('parts'):
        token = '__construct'
        owner_token = get_name(func_expr['class'])
    elif func_expr['nodeType'] == 'Expr_MethodCall':
        # token = func_expr['name']['name']
        token = get_name(func_expr)
        if 'var' in func_expr['var']:
            owner_token = OWNER_CONST.UNKNOWN_VAR
        else:
            owner_token = get_name(func_expr['var'])
    elif func_expr['nodeType'] == 'Expr_BinaryOp_Concat' and func_expr['right']['nodeType'] == 'Expr_FuncCall':
        token = get_name(func_expr['right'])
        if 'class' in func_expr['left']:
            owner_token = get_name(func_expr['left']['class'])
        else:
            owner_token = get_name(func_expr['left'])
    elif func_expr['nodeType'] == 'Expr_StaticCall':
        token = get_name(func_expr)
        owner_token = get_name(func_expr['class'])
    else:
        return None

    if owner_token and token == '__construct':
        # Taking out owner_token for constructors as a little hack to make it work
        return Call(token=owner_token,
                    line_number=lineno(func_expr))
    ret = Call(token=token,
               owner_token=owner_token,
               line_number=lineno(func_expr))
    return ret

def walk(tree):
    """
    Given an ast tree walk it to get every node. For PHP, the exception
    is that we return Expr_BinaryOp_Concat which has internal nodes but
    is important to process as a whole.

    :param tree_el ast:
    :rtype: list[ast]
    """

    if isinstance(tree, list):
        ret = []
        for el in tree:
            if isinstance(el, dict) and el.get('nodeType'):
                ret += walk(el)
        return ret

    assert isinstance(tree, dict)
    assert tree['nodeType']
    ret = [tree]

    if tree['nodeType'] == 'Expr_BinaryOp_Concat':
        return ret

    for v in tree.values():
        if isinstance(v, list) or (isinstance(v, dict) and v.get('nodeType')):
            ret += walk(v)
    return ret

def children(tree):
    """
    Given an ast tree get all children. For PHP, children are anything
    with a nodeType.

    :param tree_el ast:
    :rtype: list[ast]
    """
    assert isinstance(tree, dict)
    ret = []
    for v in tree.values():
        if isinstance(v, list):
            for el in v:
                if isinstance(el, dict) and el.get('nodeType'):
                    ret.append(el)
        elif isinstance(v, dict) and v.get('nodeType'):
            ret.append(v)
    return ret

def make_calls(body_el):
    """
    Given a list of lines, find all calls in this list.

    :param body_el ast:
    :rtype: list[Call]
    """
    calls = []
    for expr in walk(body_el):
        call = get_call_from_expr(expr)
        calls.append(call)
    ret = list(filter(None, calls))

    return ret

def process_assign(assignment_el):
    """
    Given an assignment statement, return a
    Variable that points_to the type of object being assigned.

    :param assignment_el ast:
    :rtype: Variable
    """
    assert assignment_el['nodeType'] == 'Expr_Assign'
    if 'name' not in assignment_el['var']:
        return None

    varname = assignment_el['var']['name']
    call = get_call_from_expr(assignment_el['expr'])
    if call:
        return Variable(varname, call, line_number=lineno(assignment_el))
    # else is something like `varname = num`
    return None

def make_local_variables(tree_el, parent):
    """
    Given an ast of all the lines in a function, generate a list of
    variables in that function. Variables are tokens and what they link to.

    :param tree_el ast:
    :param parent Group:
    :rtype: list[Variable]
    """
    variables = []
    for el in walk(tree_el):
        if el['nodeType'] == 'Expr_Assign':
            variables.append(process_assign(el))
        if el['nodeType'] == 'Stmt_Use':
            for use in el['uses']:
                owner_token = djoin(use['name']['parts'])
                token = use['alias']['name'] if use['alias'] else owner_token
                variables.append(Variable(token, points_to=owner_token,
                                          line_number=lineno(el)))

    # Make a 'this'/'self' variable for use anywhere we need it that points to the class
    if isinstance(parent, Group) and parent.group_type in GROUP_TYPE.CLASS:
        variables.append(Variable('this', parent, line_number=parent.line_number))
        variables.append(Variable('self', parent, line_number=parent.line_number))

    return list(filter(None, variables))

def get_inherits(tree):
    """
    Get the various types of inheritances this class/namespace/trait can have

    :param tree ast:
    :rtype: list[str]
    """
    ret = []

    if tree.get('extends', {}):
        ret.append(djoin(tree['extends']['parts']))

    for stmt in tree.get('stmts', []):
        if stmt['nodeType'] == 'Stmt_TraitUse':
            for trait in stmt['traits']:
                ret.append(djoin(trait['parts']))
    return ret

def run_ast_parser(filename):
    """
    Parse the php file and return the output + the returncode
    Separate function b/c unittesting and asserting php-parser installation.
    :param filename str:
    :type: str, int
    """

    script_loc = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                              "get_ast.php")
    cmd = ["php", script_loc, filename]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return proc.communicate()[0], proc.returncode

class PHP(BaseLanguage):
    @staticmethod
    def assert_dependencies():
        """Assert that php and php-parser are installed"""
        assert is_installed('php'), "No php installation could be found"
        self_ref = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                "get_ast.php")
        outp, returncode = run_ast_parser(self_ref)
        path = os.path.dirname(os.path.realpath(__file__))
        assert_msg = 'Error running the PHP parser. From the `%s` directory, run ' \
                     '`composer require nikic/php-parser "^4.10"`.' % path
        assert not returncode, assert_msg
        return outp

    @staticmethod
    def get_tree(filename, lang_params):
        """
        Get the entire AST for this file

        :param filename str:
        :param lang_params LanguageParams:
        :rtype: ast
        """

        outp, returncode = run_ast_parser(filename)
        if returncode:
            raise AssertionError(
                "Could not parse file %r. You may have a syntax error. "
                "For more detail, try running with `php %s`. " %
                (filename, filename))

        tree = json.loads(outp)
        assert isinstance(tree, list)
        if len(tree) == 1 and tree[0]['nodeType'] == 'Stmt_InlineHTML':
            raise AssertionError("Tried to parse a file that is not likely PHP")
        return tree

    @staticmethod
    def separate_namespaces(tree):
        """
        Given a tree element, recursively separate that AST into lists of ASTs for the
        subgroups, nodes, and body. This is an intermediate step to allow for
        cleaner processing downstream

        :param tree ast:
        :returns: tuple of group, node, and body trees. These are processed
                  downstream into real Groups and Nodes.
        :rtype: (list[ast], list[ast], list[ast])
        """
        tree = tree or []  # if its abstract, it comes in with no body

        groups = []
        nodes = []
        body = []
        for el in tree:
            if el['nodeType'] in ('Stmt_Function', 'Stmt_ClassMethod', 'Expr_Closure'):
                nodes.append(el)
            elif el['nodeType'] in ('Stmt_Class', 'Stmt_Namespace', 'Stmt_Trait'):
                groups.append(el)
            else:
                tup = PHP.separate_namespaces(children(el))
                if tup[0] or tup[1]:
                    groups += tup[0]
                    nodes += tup[1]
                    body += tup[2]
                else:
                    body.append(el)
        return groups, nodes, body

    @staticmethod
    def make_nodes(tree, parent):
        """
        Given a tree element of all the lines in a function, create the node along
        with the calls and variables internal to it.
        Also make the nested subnodes

        :param tree ast:
        :param parent Group:
        :rtype: list[Node]
        """
        assert tree['nodeType'] in ('Stmt_Function', 'Stmt_ClassMethod', 'Expr_Closure')

        if tree['nodeType'] == 'Expr_Closure':
            token = '(Closure)'
        else:
            token = tree['name']['name']
        is_constructor = token == '__construct' and parent.group_type == GROUP_TYPE.CLASS

        tree_body = tree['stmts']
        subgroup_trees, subnode_trees, this_scope_body = PHP.separate_namespaces(tree_body)
        assert not subgroup_trees
        calls = make_calls(this_scope_body)
        variables = make_local_variables(this_scope_body, parent)

        if parent.group_type == GROUP_TYPE.CLASS and parent.parent.group_type == GROUP_TYPE.NAMESPACE:
            import_tokens = [djoin(parent.parent.token, parent.token, token)]
        if parent.group_type in (GROUP_TYPE.NAMESPACE, GROUP_TYPE.CLASS):
            import_tokens = [djoin(parent.token, token)]
        else:
            import_tokens = [token]

        node = Node(token, calls, variables, parent, import_tokens=import_tokens,
                    is_constructor=is_constructor, line_number=lineno(tree))

        subnodes = flatten([PHP.make_nodes(t, parent) for t in subnode_trees])
        return [node] + subnodes

    @staticmethod
    def make_root_node(lines, parent):
        """
        The "root_node" is an implict node of lines which are executed in the global
        scope on the file itself and not otherwise part of any function.

        :param lines list[ast]:
        :param parent Group:
        :rtype: Node
        """
        token = "(global)"
        line_number = lineno(lines[0]) if lines else 0
        calls = make_calls(lines)
        variables = make_local_variables(lines, parent)
        root_node = Node(token, calls, variables, parent,
                         line_number=line_number)
        return root_node

    @staticmethod
    def make_class_group(tree, parent):
        """
        Given an AST for the subgroup (a class), generate that subgroup.
        In this function, we will also need to generate all of the nodes internal
        to the group.

        Specific to PHP, this can also be a namespace or class.

        :param tree ast:
        :param parent Group:
        :rtype: Group
        """
        assert tree['nodeType'] in ('Stmt_Class', 'Stmt_Namespace', 'Stmt_Trait')
        subgroup_trees, node_trees, body_trees = PHP.separate_namespaces(tree['stmts'])

        token = get_name(tree['name'])
        display_type = tree['nodeType'][5:]

        inherits = get_inherits(tree)

        group_type = GROUP_TYPE.CLASS
        if display_type == 'Namespace':
            group_type = GROUP_TYPE.NAMESPACE

        import_tokens = [token]
        if display_type == 'Class' and parent.group_type == GROUP_TYPE.NAMESPACE:
            import_tokens = [djoin(parent.token, token)]

        class_group = Group(token, group_type, display_type, import_tokens=import_tokens,
                            parent=parent, inherits=inherits, line_number=lineno(tree))

        for subgroup_tree in subgroup_trees:
            class_group.add_subgroup(PHP.make_class_group(subgroup_tree, class_group))

        for node_tree in node_trees:
            for new_node in PHP.make_nodes(node_tree, parent=class_group):
                class_group.add_node(new_node)

        if group_type == GROUP_TYPE.NAMESPACE:
            class_group.add_node(PHP.make_root_node(body_trees, class_group))
            for node in class_group.nodes:
                node.variables += [Variable(n.token, n, line_number=n.line_number)
                                   for n in class_group.nodes]

        return class_group

    @staticmethod
    def file_import_tokens(filename):
        """
        Returns the token(s) we would use if importing this file from another.

        :param filename str:
        :rtype: list[str]
        """
        return []


text:
<?php

namespace Grav\Common\Service;

use Grav\Common\Config\Setup;
use Pimple\Container;
use RocketTheme\Toolbox\DI\ServiceProviderInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RocketTheme\Toolbox\StreamWrapper\ReadOnlyStream;
use RocketTheme\Toolbox\StreamWrapper\Stream;
use RocketTheme\Toolbox\StreamWrapper\StreamBuilder;

/**
 * Class StreamsServiceProvider
 * @package Grav\Common\Service
 */
class StreamsServiceProvider implements ServiceProviderInterface
{
    /**
     * @param Container $container
     * @return void
     */
    public function register(Container $container)
    {
        $container['locator'] = function (Container $container) {
            $locator = new UniformResourceLocator(GRAV_WEBROOT);

            /** @var Setup $setup */
            $setup = $container['setup'];
            $setup->initializeLocator($locator);

            return $locator;
        };

        $container['streams'] = function (Container $container) {
            /** @var Setup $setup */
            $setup = $container['setup'];

            /** @var UniformResourceLocator $locator */
            $locator = $container['locator'];

            // Set locator to both streams.
            Stream::setLocator($locator);
            ReadOnlyStream::setLocator($locator);

            return new StreamBuilder($setup->getStreams());
        };
    }
}


text:
require_relative 'merge_payloads'
module Grape
  module Sideload
    class PresentMany
      def initialize(input, block)
        @input = input
        @block = block
      end

      def self.call(*input, block)
        new(input, block).merge_presenters
      end

      def merge_presenters
        merged_payload
      end

      private
      attr_reader :input, :block

      def merged_payload
        MergePayloads.(*presented)
      end

      def presented
        # call #present on Grape::API to format the resoruces using the entity passed by the user
        input.map do |payload|
          block.(
            payload[:present],
            with: payload[:with]
          )
        end
      end
    end
  end
end