text:
import {Type} from '../interface/type';
import {stringify} from '../util/stringify';

import {InjectionToken} from './injection_token';
import {Injector} from './injector';
import {InjectableDef, getInjectableDef} from './interface/defs';
import {InjectFlags} from './interface/injector';
import {Inject, Optional, Self, SkipSelf} from './metadata';

/**
 * Current injector value used by `inject`.
 * - `undefined`: it is an error to call `inject`
 * - `null`: `inject` can be called but there is no injector (limp-mode).
 * - Injector instance: Use the injector for resolution.
 */
let _currentInjector: Injector|undefined|null = undefined;

export function setCurrentInjector(injector: Injector | null | undefined): Injector|undefined|null {
  const former = _currentInjector;
  _currentInjector = injector;
  return former;
}

/**
 * Current implementation of inject.
 *
 * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
 * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
 * way for two reasons:
 *  1. `Injector` should not depend on ivy logic.
 *  2. To maintain tree shake-ability we don't want to bring in unnecessary code.
 */
let _injectImplementation: (<T>(token: Type<T>| InjectionToken<T>, flags: InjectFlags) => T | null)|
    undefined;

/**
 * Sets the current inject implementation.
 */
export function setInjectImplementation(
    impl: (<T>(token: Type<T>| InjectionToken<T>, flags?: InjectFlags) => T | null) | undefined):
    (<T>(token: Type<T>| InjectionToken<T>, flags?: InjectFlags) => T | null)|undefined {
  const previous = _injectImplementation;
  _injectImplementation = impl;
  return previous;
}

export function injectInjectorOnly<T>(token: Type<T>| InjectionToken<T>): T;
export function injectInjectorOnly<T>(token: Type<T>| InjectionToken<T>, flags?: InjectFlags): T|
    null;
export function injectInjectorOnly<T>(
    token: Type<T>| InjectionToken<T>, flags = InjectFlags.Default): T|null {
  if (_currentInjector === undefined) {
    throw new Error(`inject() must be called from an injection context`);
  } else if (_currentInjector === null) {
    return injectRootLimpMode(token, undefined, flags);
  } else {
    return _currentInjector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
  }
}

/**
 * Injects a token from the currently active injector.
 *
 * This function must be used in the context of a factory function such as one defined for an
 * `InjectionToken`, and will throw an error if not called from such a context.
 *
 * @usageNotes
 * ### Example
 *
 * {@example core/di/ts/injector_spec.ts region='ShakeableInjectionToken'}
 *
 * Within such a factory function `inject` is utilized to request injection of a dependency, instead
 * of providing an additional array of dependencies as was common to do with `useFactory` providers.
 * `inject` is faster and more type-safe.
 *
 * @publicApi
 */
export function inject<T>(token: Type<T>| InjectionToken<T>): T;
export function inject<T>(token: Type<T>| InjectionToken<T>, flags?: InjectFlags): T|null;
export function inject<T>(token: Type<T>| InjectionToken<T>, flags = InjectFlags.Default): T|null {
  return (_injectImplementation || injectInjectorOnly)(token, flags);
}

/**
 * Injects `root` tokens in limp mode.
 *
 * If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
 * `"root"`. This is known as the limp mode injection. In such case the value is stored in the
 * `InjectableDef`.
 */
export function injectRootLimpMode<T>(
    token: Type<T>| InjectionToken<T>, notFoundValue: T | undefined, flags: InjectFlags): T|null {
  const injectableDef: InjectableDef<T>|null = getInjectableDef(token);
  if (injectableDef && injectableDef.providedIn == 'root') {
    return injectableDef.value === undefined ? injectableDef.value = injectableDef.factory() :
                                               injectableDef.value;
  }
  if (flags & InjectFlags.Optional) return null;
  if (notFoundValue !== undefined) return notFoundValue;
  throw new Error(`Injector: NOT_FOUND [${stringify(token)}]`);
}

export function injectArgs(types: (Type<any>| InjectionToken<any>| any[])[]): any[] {
  const args: any[] = [];
  for (let i = 0; i < types.length; i++) {
    const arg = types[i];
    if (Array.isArray(arg)) {
      if (arg.length === 0) {
        throw new Error('Arguments array must have arguments.');
      }
      let type: Type<any>|undefined = undefined;
      let flags: InjectFlags = InjectFlags.Default;

      for (let j = 0; j < arg.length; j++) {
        const meta = arg[j];
        if (meta instanceof Optional || meta.ngMetadataName === 'Optional') {
          flags |= InjectFlags.Optional;
        } else if (meta instanceof SkipSelf || meta.ngMetadataName === 'SkipSelf') {
          flags |= InjectFlags.SkipSelf;
        } else if (meta instanceof Self || meta.ngMetadataName === 'Self') {
          flags |= InjectFlags.Self;
        } else if (meta instanceof Inject) {
          type = meta.token;
        } else {
          type = meta;
        }
      }

      args.push(inject(type !, flags));
    } else {
      args.push(inject(arg));
    }
  }
  return args;
}


text:
package ryrycipe.model.wrapper;

import ryrycipe.model.Component;
import ryrycipe.model.Material;

import java.util.List;

/**
 * Helper class to wrap a {@link ryrycipe.controller.RecipeComponentController}.
 */
public class ComponentWrapper {

    /**
     * Name of the RecipeComponent.
     */
    private Component component;

    /**
     * List of materials within the RecipeComponent.
     */
    private List<Material> materials;

    public ComponentWrapper() {}

    public Component getComponent() {
        return component;
    }

    public void setComponent(Component component) {
        this.component = component;
    }

    public List<Material> getMaterials() {
        return materials;
    }

    public void setMaterials(List<Material> materials) {
        this.materials = materials;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
function html_end()
{

	global $admin_email;
?>

Weblogen - Part of the
ASAP Project.
		Problems? Contact the
		<a href="mailto: <?php echo $admin_email; ?>">System Administrator.

Please read the Weblogen Manual.

<?php
}
?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<broker>
    <plugin-directory>${QPID_HOME}/lib/plugins</plugin-directory>
    <cache-directory>${QPID_HOME}/cache</cache-directory>
	<connector>
		<ssl>
			<enabled>false</enabled>
		</ssl>
	</connector>
	<management>
		<enabled>true</enabled>
		<ssl>
			<enabled>false</enabled>
		</ssl>
	</management>
	<security>
		<pd-auth-manager>
			<principal-database>
				<class>org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase
				</class>
				<attributes>
					<attribute>
						<name>passwordFile</name>
						<value>${QPID_HOME}/etc/passwd</value>
					</attribute>
				</attributes>
			</principal-database>
		</pd-auth-manager>
		<allow-all />
		<msg-auth>false</msg-auth>
	</security>
	<virtualhosts>
		<default>localhost</default>
		<virtualhost>
			<name>localhost</name>
			<localhost>
                <custom-exchanges>
                    <class-name>monterey.qpid.plugin.exchanges.switcher.SwitcherExchangeType</class-name>
                </custom-exchanges>
				<store>
					<class>org.apache.qpid.server.store.MemoryMessageStore</class>
				</store>
			</localhost>
		</virtualhost>
	</virtualhosts>
	<queue>
		<auto_register>true</auto_register>
	</queue>
	<status-updates>ON</status-updates>
</broker>


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

namespace OrionLib.CommonContracts
{
    public class ContextElementDto
    {
        public string Type { get; set; }
        public string IsPattern { get; set; }
        public string Id { get; set; }
        public List<GetAttributeDto> Attributes { get; set; }
    }

    public static class ContextElementDtoExtensions
    {
        public static OrionEntity ToEntity(this ContextElementDto contextElement)
        {
            var entityAttributes = contextElement.Attributes.Select(attribute => attribute.ToEntityAttribute());

            return new OrionEntity(contextElement.Type, contextElement.Id, entityAttributes);
        }
    }
}


text:
package org.elasticsearch.rest.action.document;

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestActions;
import org.elasticsearch.rest.action.RestStatusToXContentListener;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;

import java.io.IOException;

import static org.elasticsearch.rest.RestRequest.Method.POST;

public class RestUpdateAction extends BaseRestHandler {
    private static final DeprecationLogger DEPRECATION_LOGGER =
        new DeprecationLogger(Loggers.getLogger(RestUpdateAction.class));

    @Inject
    public RestUpdateAction(Settings settings, RestController controller) {
        super(settings);
        controller.registerHandler(POST, "/{index}/{type}/{id}/_update", this);
    }

    @Override
    public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(request.param("index"), request.param("type"), request.param("id"));
        updateRequest.routing(request.param("routing"));
        updateRequest.parent(request.param("parent"));
        updateRequest.timeout(request.paramAsTime("timeout", updateRequest.timeout()));
        updateRequest.setRefreshPolicy(request.param("refresh"));
        String waitForActiveShards = request.param("wait_for_active_shards");
        if (waitForActiveShards != null) {
            updateRequest.waitForActiveShards(ActiveShardCount.parseString(waitForActiveShards));
        }
        updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert()));
        FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
        String sField = request.param("fields");
        if (sField != null && fetchSourceContext != null) {
            throw new IllegalArgumentException("[fields] and [_source] cannot be used in the same request");
        }
        if (sField != null) {
            DEPRECATION_LOGGER.deprecated("Deprecated field [fields] used, expected [_source] instead");
            String[] sFields = Strings.splitStringByCommaToArray(sField);
            updateRequest.fields(sFields);
        } else if (fetchSourceContext != null) {
            updateRequest.fetchSource(fetchSourceContext);
        }

        updateRequest.retryOnConflict(request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));
        updateRequest.version(RestActions.parseVersion(request));
        updateRequest.versionType(VersionType.fromString(request.param("version_type"), updateRequest.versionType()));

        request.applyContentParser(parser -> {
            updateRequest.fromXContent(parser);
            IndexRequest upsertRequest = updateRequest.upsertRequest();
            if (upsertRequest != null) {
                upsertRequest.routing(request.param("routing"));
                upsertRequest.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
                upsertRequest.version(RestActions.parseVersion(request));
                upsertRequest.versionType(VersionType.fromString(request.param("version_type"), upsertRequest.versionType()));
            }
            IndexRequest doc = updateRequest.doc();
            if (doc != null) {
                doc.routing(request.param("routing"));
                doc.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
                doc.version(RestActions.parseVersion(request));
                doc.versionType(VersionType.fromString(request.param("version_type"), doc.versionType()));
            }
        });

        return channel ->
            client.update(updateRequest, new RestStatusToXContentListener<>(channel, r -> r.getLocation(updateRequest.routing())));
    }
}


text:
package com.couchbase.mock.memcached;

import com.couchbase.mock.Info;
import com.couchbase.mock.memcached.protocol.BinaryCommand;
import com.couchbase.mock.memcached.protocol.BinaryResponse;
import com.couchbase.mock.memcached.protocol.BinaryVersionResponse;

/**
 * Implementation of version command
 *
 * @author Trond Norbye
 */
class VersionCommandExecutor implements CommandExecutor {
    @Override
    public BinaryResponse execute(BinaryCommand cmd, MemcachedServer server, MemcachedConnection client) {
        return new BinaryVersionResponse(cmd, Info.getFullVersion());
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Merpati;

import merpati.Merpati;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Mahdiar Naufal
 */
public class MerpatiTest {

    public MerpatiTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of Eat method, of class Merpati.
     */
    @Test
    public void testEat() {
        System.out.println("Eat");
        Merpati instance = new Merpati();
        instance.Eat();
        // TODO review the generated test code and remove the default call to fail.
    }

    /**
     * Test of Interact method, of class Merpati.
     */
    @Test
    public void testInteract() {
        System.out.println("Interact");
        Merpati instance = new Merpati();
        instance.Interact();
        // TODO review the generated test code and remove the default call to fail.
    }

    @Test
    /**
     * Testing Default parameter, of class Merpati.
     */
    public void testDefault() {
        System.out.println("Test Default Parameter");
        Merpati instance;
        instance = new Merpati ();
        assertTrue(instance.getWeight() == 0);
        assertTrue(instance.getTipe() == 0);
        assertTrue(instance.getTamed() == false);
        assertTrue(instance.getX() == -1);
        assertTrue(instance.getY() == -1);
    }

    @Test
    /**
     * Testing parameter, of class Merpati.
     */
    public void testParameter() {
        System.out.println("Test Parameter");
        Merpati instance;
        instance = new Merpati(100,1,true,10,5);
        assertTrue(instance.getWeight() == 100);
        assertTrue(instance.getTipe() == 1);
        assertTrue(instance.getTamed() == true);
        assertTrue(instance.getX() == 10);
        assertTrue(instance.getY() == 5);
    }

    @Test
    /**
     * Test copy constructor
     *
     */
    public void testCopyConstructor() {
        System.out.println("Test Copy constructor");
        Merpati instance1,instance2;
        instance1 = new Merpati(100,1,true,10,5);
        instance2 = new Merpati(instance1);
        assertTrue(instance2.getWeight() == 100);
        assertTrue(instance2.getTipe() == 1);
        assertTrue(instance2.getTamed() == true);
        assertTrue(instance2.getX() == 10);
        assertTrue(instance2.getY() == 5);
    }

    @Test
    /**
     * Testing setter, of class Merpati.
     */
    public void testSetter() {
        Merpati instance;
        instance = new Merpati();
        instance.setWeight(200);
        instance.setTipe(2);
        instance.setTamed(true);
        instance.setX(100);
        instance.setY(1000);
        assertTrue(instance.getWeight() == 200);
        assertTrue(instance.getTipe() == 2);
        assertTrue(instance.getTamed() == true);
        assertTrue(instance.getX() == 100);
        assertTrue(instance.getY() == 1000);
    }
}


text:
namespace headless {

namespace {

template <class T>
const T& ReturnOverriddenValue(const base::Optional<T>& value,
                               const T& default_value) {
  if (value) {
    return *value;
  } else {
    return default_value;
  }
}

}  // namespace

HeadlessBrowserContextOptions::HeadlessBrowserContextOptions(
    HeadlessBrowserContextOptions&& options) = default;

HeadlessBrowserContextOptions::~HeadlessBrowserContextOptions() = default;

HeadlessBrowserContextOptions& HeadlessBrowserContextOptions::operator=(
    HeadlessBrowserContextOptions&& options) = default;

HeadlessBrowserContextOptions::HeadlessBrowserContextOptions(
    HeadlessBrowser::Options* options)
    : browser_options_(options) {}

const std::string& HeadlessBrowserContextOptions::user_agent() const {
  return ReturnOverriddenValue(user_agent_, browser_options_->user_agent);
}

const net::HostPortPair& HeadlessBrowserContextOptions::proxy_server() const {
  return ReturnOverriddenValue(proxy_server_, browser_options_->proxy_server);
}

const std::string& HeadlessBrowserContextOptions::host_resolver_rules() const {
  return ReturnOverriddenValue(host_resolver_rules_,
                               browser_options_->host_resolver_rules);
}

const gfx::Size& HeadlessBrowserContextOptions::window_size() const {
  return ReturnOverriddenValue(window_size_, browser_options_->window_size);
}

const base::FilePath& HeadlessBrowserContextOptions::user_data_dir() const {
  return ReturnOverriddenValue(user_data_dir_, browser_options_->user_data_dir);
}

bool HeadlessBrowserContextOptions::incognito_mode() const {
  return ReturnOverriddenValue(incognito_mode_,
                               browser_options_->incognito_mode);
}

const ProtocolHandlerMap& HeadlessBrowserContextOptions::protocol_handlers()
    const {
  return protocol_handlers_;
}

ProtocolHandlerMap HeadlessBrowserContextOptions::TakeProtocolHandlers() {
  return std::move(protocol_handlers_);
}

const base::Callback<void(WebPreferences*)>&
HeadlessBrowserContextOptions::override_web_preferences_callback() const {
  return override_web_preferences_callback_;
}

}  // namespace headless


text:
[View Javadoc](../../../../../../apidocs/org/apache/strutsel/taglib/logic/ELRedirectTagBeanInfo.html.md)

    1
    21  package org.apache.strutsel.taglib.logic;
    22
    23  import java.beans.IntrospectionException;
    24  import java.beans.PropertyDescriptor;
    25  import java.beans.SimpleBeanInfo;
    26
    27  import java.util.ArrayList;
    28
    29  /**
    30   * This is the BeanInfo descriptor for the
    31   * org.apache.strutsel.taglib.logic.ELRedirectTag class.  It is
    32   * needed to override the default mapping of custom tag attribute names to
    33   * class attribute names.
 This is because the value of the unevaluated EL
    34   * expression has to be kept separately from the evaluated value, which is
    35   * stored in the base class. This is related to the fact that the JSP compiler
    36   * can choose to reuse different tag instances if they received the same
    37   * original attribute values, and the JSP compiler can choose to not re-call
    38   * the setter methods, because it can assume the same values are already set.
    39   */
    40  public class ELRedirectTagBeanInfo extends SimpleBeanInfo {
    41      public PropertyDescriptor[] getPropertyDescriptors() {
    42          ArrayList proplist = new ArrayList();
    43
    44          try {
    45              proplist.add(new PropertyDescriptor("action", ELRedirectTag.class,
    46                      null, "setActionExpr"));
    47          } catch (IntrospectionException ex) {
    48          }
    49
    50          try {
    51              proplist.add(new PropertyDescriptor("anchor", ELRedirectTag.class,
    52                      null, "setAnchorExpr"));
    53          } catch (IntrospectionException ex) {
    54          }
    55
    56          try {
    57              proplist.add(new PropertyDescriptor("forward", ELRedirectTag.class,
    58                      null, "setForwardExpr"));
    59          } catch (IntrospectionException ex) {
    60          }
    61
    62          try {
    63              proplist.add(new PropertyDescriptor("href", ELRedirectTag.class,
    64                      null, "setHrefExpr"));
    65          } catch (IntrospectionException ex) {
    66          }
    67
    68          try {
    69              proplist.add(new PropertyDescriptor("name", ELRedirectTag.class,
    70                      null, "setNameExpr"));
    71          } catch (IntrospectionException ex) {
    72          }
    73
    74          try {
    75              proplist.add(new PropertyDescriptor("page", ELRedirectTag.class,
    76                      null, "setPageExpr"));
    77          } catch (IntrospectionException ex) {
    78          }
    79
    80          try {
    81              proplist.add(new PropertyDescriptor("paramId", ELRedirectTag.class,
    82                      null, "setParamIdExpr"));
    83          } catch (IntrospectionException ex) {
    84          }
    85
    86          try {
    87              proplist.add(new PropertyDescriptor("paramName",
    88                      ELRedirectTag.class, null, "setParamNameExpr"));
    89          } catch (IntrospectionException ex) {
    90          }
    91
    92          try {
    93              proplist.add(new PropertyDescriptor("paramProperty",
    94                      ELRedirectTag.class, null, "setParamPropertyExpr"));
    95          } catch (IntrospectionException ex) {
    96          }
    97
    98          try {
    99              proplist.add(new PropertyDescriptor("paramScope",
    100                     ELRedirectTag.class, null, "setParamScopeExpr"));
    101         } catch (IntrospectionException ex) {
    102         }
    103
    104         try {
    105             proplist.add(new PropertyDescriptor("property",
    106                     ELRedirectTag.class, null, "setPropertyExpr"));
    107         } catch (IntrospectionException ex) {
    108         }
    109
    110         try {
    111             proplist.add(new PropertyDescriptor("scope", ELRedirectTag.class,
    112                     null, "setScopeExpr"));
    113         } catch (IntrospectionException ex) {
    114         }
    115
    116         try {
    117             proplist.add(new PropertyDescriptor("transaction",
    118                     ELRedirectTag.class, null, "setTransactionExpr"));
    119         } catch (IntrospectionException ex) {
    120         }
    121
    122         try {
    123             proplist.add(new PropertyDescriptor("useLocalEncoding",
    124                     ELRedirectTag.class, null, "setUseLocalEncodingExpr"));
    125         } catch (IntrospectionException ex) {
    126         }
    127
    128         PropertyDescriptor[] result = new PropertyDescriptor[proplist.size()];
    129
    130         return ((PropertyDescriptor[]) proplist.toArray(result));
    131     }
    132 }

------------------------------------------------------------------------

This page was automatically generated by [Maven](http://maven.apache.org/)


text:
<?xml version="1.0" encoding="UTF-8"?>

<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <mapped-superclass name="DCS\TagBundle\Entity\Tag">

        <field name="name" column="name" type="string" length="100" nullable="false" />

        <field name="code" column="code" length="100" type="string" nullable="false" unique="true" />

        <field name="slug" column="slug" length="100" type="string" nullable="false" />

    </mapped-superclass>

</doctrine-mapping>


text:
YUI.add('cssgrids-magazine-tests', function(Y) {

    var suite = new Y.Test.Suite('cssgrids-magazine example test suite'),
        Assert = Y.Assert;

    suite.add(new Y.Test.Case({
        name: 'Responsive tests',
        'images have max-widths defined': function() {
            var headlineImg = Y.one('.left-bar .article img');
            Assert.isNotUndefined(headlineImg.getComputedStyle('maxWidth'), 'maxWidth undefined on images');
        }
    }));

    Y.Test.Runner.add(suite);

}, '', { requires: [ 'node', 'node-event-simulate' ] });


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Pap. 137: 7 (1974)

#### Original name
Cercodeuterospora trichophila Curzi, 1932

### Remarks
null


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Step 8: Iterate - to refine your index</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Boost.AutoIndex">
<link rel="up" href="../tut.html" title="Getting Started and Tutorial">
<link rel="prev" href="build_docs.html" title="Step 7: Build the Docs">
<link rel="next" href="../script_ref.html" title="Script File (.idx) Reference">

Home
Libraries
People
FAQ
More

Step 8: Iterate - to refine
      your index

        Creating a good index is an iterative process, often the first step is just
        to add a header scanning rule to the script file and then generate the documentation
        and see:

            What's missing.

            What's been included that shouldn't be.

            What's been included under a poor name.

        Further rules can then be added to the script to handle these cases and the
        next iteration examined, and so on.

Tip

          If you don't understand why a particular term is (or is not) present in
          the index, try adding a !debug regular-expression
          directive to the script file.

        Restricting
        which Sections are indexed for a particular term

        You can restrict which sections are indexed for a particular term. So assuming
        that the docbook document has the usual hierarchical names for section ID's
        (as Quickbook generates, for example), you can easily place a constraint
        on which sections are examined for a particular term.

        For example, if you want to index occurrences of Lord Kelvin's name, but
        only in the introduction section, you might then add:

Kelvin "" ".*introduction.*"

        to the script file, assuming that the section ID of the intro is "some_library_or_chapter_name.introduction".

        This would avoid an index entry every time 'Kelvin' is found, something the
        user is unlikely to find helpful.

Copyright © 2008, 2011 John Maddock

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
@interface PodsDummy_Pods_MYSGravityActionSheetDemo_DDPopoverBackgroundView : NSObject
@end
@implementation PodsDummy_Pods_MYSGravityActionSheetDemo_DDPopoverBackgroundView
@end


text:
""" This file contains defines parameters for regreg that we use to fill
settings in setup.py, the regreg top-level docstring, and for building the docs.
In setup.py in particular, we exec this file, so it cannot import regreg
"""

# regreg version information.  An empty _version_extra corresponds to a
# full release.  '.dev' as a _version_extra string means this is a development
# version
_version_major = 0
_version_minor = 0
_version_micro = 1
_version_extra = '.dev'

# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
__version__ = "%s.%s.%s%s" % (_version_major,
                              _version_minor,
                              _version_micro,
                              _version_extra)

CLASSIFIERS = ["Development Status :: 3 - Alpha",
               "Environment :: Console",
               "Intended Audience :: Science/Research",
               "License :: OSI Approved :: BSD License",
               "Operating System :: OS Independent",
               "Programming Language :: Python",
               "Topic :: Scientific/Engineering"]

description  = 'Testing a fixed value of lambda'

# Note: this long_description is actually a copy/paste from the top-level
# README.txt, so that it shows up nicely on PyPI.  So please remember to edit
# it only in one place and sync it correctly.
long_description = \
"""
============
Fixed lambda
============

This mini-package contains a module to perform
a fixed lambda test for the LASSO.
"""

# versions
NUMPY_MIN_VERSION='1.3'
SCIPY_MIN_VERSION = '0.7'
CYTHON_MIN_VERSION = '0.11.1'
SKLEARN_MIN_VERSION = "0.14.1"
MPMATH_MIN_VERSION = "0.18"
PYINTER_MIN_VERSION = "0.1.6"

NAME                = 'selection'
MAINTAINER          = "Jonathan Taylor"
MAINTAINER_EMAIL    = ""
DESCRIPTION         = description
LONG_DESCRIPTION    = long_description
URL                 = "http://github.org/jonathan.taylor/fixed_lambda"
DOWNLOAD_URL        = ""
LICENSE             = "BSD license"
CLASSIFIERS         = CLASSIFIERS
AUTHOR              = "fixed_lambda developers"
AUTHOR_EMAIL        = ""
PLATFORMS           = "OS Independent"
MAJOR               = _version_major
MINOR               = _version_minor
MICRO               = _version_micro
ISRELEASE           = _version_extra == ''
VERSION             = __version__
STATUS              = 'alpha'
PROVIDES            = ["fixed_lambda"]
REQUIRES            = ["numpy (>=%s)" % NUMPY_MIN_VERSION,
                       "scipy (>=%s)" % SCIPY_MIN_VERSION,
                       "sklearn (>=%s)" % SKLEARN_MIN_VERSION,
                       "mpmath (>=%s)" % MPMATH_MIN_VERSION,
                       "pyinter"]


text:
import { Component } from '@angular/core';

import './styles.css';
import '../styles/reset.scss';
import moment from 'moment';

@Component({
  selector: 'my-app',
  styleUrls: [ './app.component.css' ],
  template: `<my-htree></my-htree><my-htree></my-htree><h1>{{title}}</h1>
  <router-outlet></router-outlet>`
})
export class AppComponent  {
  constructor(){
    moment.locale('zh-cn');
  }

  public title: string = 'My Components';
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using com.riotgames.platform.harassment;
using com.riotgames.platform.summoner;
using Lollipop.Session;

namespace Lollipop.Services
{
    public class SummonerService : ISummonerService
    {
        private const string Endpoint = "summonerService";

        private readonly ILeagueAccount _conn;

        public SummonerService(ILeagueAccount connection)
        {
            _conn = connection;
        }

        public async Task<string[]> NamesById(params int[] summonerIds)
        {
            var values = await _conn.Call<List<string>>(Endpoint, "getSummonerNames", summonerIds);
            return values.ToArray();
        }

        public Task<string> InternalName(string name)
        {
            return _conn.Call<string>(Endpoint, "getSummonerInternalNameByName", name);
        }

        public Task<PublicSummoner> Get(string name)
        {
            return _conn.Call<PublicSummoner>(Endpoint, "getSummonerByName", name);
        }

        public Task<AllSummonerData> Data(int accountId)
        {
            return _conn.Call<AllSummonerData>(Endpoint, "getAllSummonerDataByAccount", accountId);
        }

        public Task<AllPublicSummonerDataDTO> PublicData(int accountId)
        {
            return _conn.Call<AllPublicSummonerDataDTO>(Endpoint, "getAllPublicSummonerDataByAccount", accountId);
        }

//        public Task<SummonerRuneInventory> GetRuneInventory(int summonerId)
//        {
//            return _conn.Call<SummonerRuneInventory>("summonerRuneService", "getSummonerRuneInventory", summonerId);
//        }
//
//        public Task<SpellBookDTO> GetRunes(int summonerId)
//        {
//            return _conn.Call<SpellBookDTO>("spellBookService", "getSpellBook", summonerId);
//        }
//
//        public Task<MasteryBookDTO> GetMasteries(int summonerId)
//        {
//            return _conn.Call<MasteryBookDTO>("masteryBookService", "getMasteryBook", summonerId);
//        }

        public async Task<Kudos> Kudos(int summonerId)
        {
            var payload = string.Format("{{\"commandName\":\"{0}\",\"summonerId\":{1}}}", "TOTALS", summonerId);
            var result = await _conn.Call<LcdsResponseString>("clientFacadeService", "callKudos", payload);
            if (result == null || string.IsNullOrWhiteSpace(result.value))
                return null;

            return com.riotgames.platform.harassment.Kudos.Parse(result.value);
        }
    }
}


text:
package com.mossle.scope.support;

import java.io.IOException;

import javax.annotation.Resource;

import com.mossle.api.scope.ScopeCache;
import com.mossle.api.scope.ScopeDTO;

import com.mossle.core.mapper.JsonMapper;

import com.mossle.ext.message.Subscribable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

@Component
public class ScopeSubscriber implements Subscribable<String> {
    private static Logger logger = LoggerFactory
            .getLogger(ScopeSubscriber.class);
    private JsonMapper jsonMapper = new JsonMapper();
    private ScopeCache scopeCache;
    private String destinationName = "topic.scope.update";

    public void handleMessage(String message) {
        try {
            ScopeDTO scopeDto = jsonMapper.fromJson(message, ScopeDTO.class);

            if (scopeDto.getName() == null) {
                scopeCache.removeScope(scopeDto);
                logger.info("remove scopeDto : {}", message);
            } else {
                scopeCache.updateScope(scopeDto);
                logger.info("update scopeDto : {}", message);
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    public boolean isTopic() {
        return true;
    }

    public String getName() {
        return destinationName;
    }

    @Resource
    public void setScopeCache(ScopeCache scopeCache) {
        this.scopeCache = scopeCache;
    }

    public void setDestinationName(String destinationName) {
        this.destinationName = destinationName;
    }
}


text:
package net.sf.jasperreports.data.provider;

import java.util.Map;

import net.sf.jasperreports.data.AbstractClasspathAwareDataAdapterService;
import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JRDataSourceProvider;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.util.JRClassLoader;

/**
 * @author Teodor Danciu (teodord@users.sourceforge.net)
 * @version $Id: DataSourceProviderDataAdapterService.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class DataSourceProviderDataAdapterService extends AbstractClasspathAwareDataAdapterService
{
	private JRDataSourceProvider provider = null;

	/**
	 *
	 */
	public DataSourceProviderDataAdapterService(
		JasperReportsContext jasperReportsContext,
		DataSourceProviderDataAdapter dsDataAdapter
		)
	{
		super(jasperReportsContext, dsDataAdapter);
	}

	/**
	 * @deprecated Replaced by {@link #DataSourceProviderDataAdapterService(JasperReportsContext, DataSourceProviderDataAdapter)}.
	 */
	public DataSourceProviderDataAdapterService(DataSourceProviderDataAdapter dsDataAdapter)
	{
		this(DefaultJasperReportsContext.getInstance(), dsDataAdapter);
	}

	public DataSourceProviderDataAdapter getDataSourceProviderDataAdapter() {
		return (DataSourceProviderDataAdapter) getDataAdapter();
	}

	public JRDataSourceProvider getProvider() throws JRException
	{
		if (provider == null)
		{
			DataSourceProviderDataAdapter dsDataAdapter = getDataSourceProviderDataAdapter();
			if (dsDataAdapter != null)
			{
				ClassLoader oldThreadClassLoader = Thread.currentThread().getContextClassLoader();

				try
				{
//					ClassLoader cloader = oldThreadClassLoader;
//					Object obj = getJasperReportsContext().getValue(CURRENT_CLASS_LOADER);
//					if(obj != null && obj instanceof ClassLoader)
//						cloader = (ClassLoader)obj ;
//					Thread.currentThread().setContextClassLoader(
//						new CompositeClassloader(getClassLoader(), cloader)
//						);
					Thread.currentThread().setContextClassLoader(getClassLoader(oldThreadClassLoader));

					Class<?> clazz = JRClassLoader.loadClassForRealName(dsDataAdapter.getProviderClass());
					provider = (JRDataSourceProvider) clazz.newInstance();
					// FIXME: I don't have a report, why I need a report??!
				} catch (ClassNotFoundException e) {
					throw new JRException(e);
				} catch (IllegalAccessException e) {
					throw new JRException(e);
				} catch (InstantiationException e) {
					throw new JRException(e);
				}
				finally
				{
					Thread.currentThread().setContextClassLoader(oldThreadClassLoader);
				}
			}
		}

		return provider;
	}

	@Override
	public void contributeParameters(Map<String, Object> parameters) throws JRException
	{
		JRDataSourceProvider dsProvider = getProvider();
		if (dsProvider != null)
		{
			JasperReport jr = (JasperReport) parameters.get(JRParameter.JASPER_REPORT);
			parameters.put(JRParameter.REPORT_DATA_SOURCE, dsProvider.create(jr));
		}
	}

}


text:
<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Tutto\SecurityBundle\Configuration\Authorization;

/**
 * Class WelcomeController
 * @package Acme\DemoBundle\Controller
 * @Authorization(omit=true)
 */
class WelcomeController extends Controller
{
    public function indexAction()
    {
        /*
         * The action's view can be rendered using render() method
         * or @Template annotation as demonstrated in DemoController.
         *
         */
        return $this->render('AcmeDemoBundle:Welcome:index.html.twig');
    }
}


text:
package backtype.storm.topology;

import backtype.storm.task.IBolt;

/**
 * When writing topologies using Java, {@link IRichBolt} and {@link IRichSpout}
 * are the main interfaces to use to implement components of the topology.
 *
 */
public interface IRichBolt extends IBolt, IComponent {

}


text:
<?php
namespace chilimatic\lib\Route\Map;

use chilimatic\lib\Route\Exception\RouteException;
use chilimatic\lib\Route\parser\RouteMethodAnnotationParser;

/**
 * Class MapObject
 *
 * @package chilimatic\lib\Route\Map
 */
class MapObject extends Generic
{

    const NAMESPACE_DELIMITER = '\\';

    /**
     * @var string
     */
    const SETTER_PREFIX = 'set';

    /**
     * object / class to be called
     *
     * @var string
     */
    public $class;

    /**
     * method of the object to be called
     *
     * @var string
     */
    public $method;

    /**
     * @var null
     */
    public $param;

    /**
     * @var \ReflectionClass
     */
    public $reflection;

    /**
     * @return mixed|void
     * @throws RouteException
     */
    public function init()
    {

        // numeric array
        if (!empty($this->config) && is_object($this->config)) {
            $this->class      = (string)$this->config->object;
            $this->method     = (string)$this->config->method;
            $this->param      = !empty($this->config->param) ? $this->config->param : false;
            $this->reflection = new \ReflectionClass($this->class);
        } elseif (!empty($this->config[0])) {
            $this->class      = (string)$this->config [0];
            $this->method     = (string)!empty($this->config[1]) ? $this->config[1] : '';
            $this->param      = !empty($this->config[2]) ? $this->config[2] : false;
            $this->reflection = new \ReflectionClass($this->class);
        } elseif (!empty($this->config['object'])) {
            $this->class      = (string)$this->config['object'];
            $this->method     = (string)!empty($this->config['method']) ? $this->config['method'] : '';
            $this->param      = !empty($this->config['param']) ? $this->config['param'] : false;
            $this->reflection = new \ReflectionClass($this->class);
        } // invalid
        else {
            throw new RouteException(sprintf(_('The Callback was not proper defined %s'), print_r($this->config, true)));
        }
    }

    /**
     * executes route
     *
     * @param null $param
     *
     * @return mixed
     */
    public function call($param = null)
    {
        // get the class within the correct namespace
        // initiate object
        $object = $this->prepareObject(new $this->class());

        $return    = new \SplFixedArray(2);
        $return[1] = $object;

        if (!empty($this->method)) {
            if (!empty($param) && !empty($this->param)) {
                $return[0] = $object->{$this->method}(array_merge((array)$this->param, (array)$param));

                return $return;
            }
            $return[0] = $object->{$this->method}();

            return $return;
        }

        return $return;
    }

    /**
     * @param $object
     *
     * @return mixed
     */
    public function prepareObject($object)
    {
        $tokenList = $this->getMethodTokenList();

        for ($i = 0, $c = count($tokenList); $i < $c; $i++) {
            if ($this->reflection->hasMethod(self::SETTER_PREFIX . ucfirst($tokenList[$i]['property']))) {
                $m = self::SETTER_PREFIX . ucfirst($tokenList[$i]['property']);
                if ($tokenList[$i]['type'] == RouteMethodAnnotationParser::TYPE_CLASS) {
                    $value = new $tokenList[$i]['value']();
                } else {
                    $value = $tokenList[$i]['value'];
                }
                $object->$m($value);
            }
        }

        return $object;
    }

    /**
     * @return mixed
     */
    public function getMethodTokenList()
    {
        $reflectionMethod = $this->reflection->getMethod($this->method);
        $doc              = $reflectionMethod->getDocComment();

        if (!$doc || !$this->parser) {
            return [];
        }

        return $this->parser->parse($doc);
    }

}


text:
require 'spec_helper'

describe DefCache::ClassMethods do

  subject(:klass) { stub_const 'SampleClass', Class.new { extend DefCache::ClassMethods } }

  describe '.cache_method' do
    it 'should call .define_cache_method for each method with the passed options' do
      methods = [:foo, :bar, :baz]
      options = { option: :value }
      methods.each do |method|
        expect(klass).to receive(:define_cache_method).with(method, options)
      end
      klass.send :cache_method, *methods, options
    end
  end

  describe '.define_cache_method' do
    it 'should call .stub_cache_method_original with the method' do
      expect(klass).to receive(:stub_cache_method_original).at_least(:once).with(:foo).and_call_original
      klass.send :define_cache_method, :foo
    end

    it 'should call .define_cache_handler_method with the method' do
      options = { option: :value }
      expect(klass).to receive(:define_cache_handler_method).at_least(:once).with(:foo, options).and_call_original
      klass.send :define_cache_handler_method, :foo, options
    end

    it 'should call .define_cache_with_method' do
      expect(klass).to receive(:define_cache_with_method).at_least(:once).with(:foo).and_call_original
      klass.send :define_cache_method, :foo
    end

    it 'should call alias_method_chain with the method and :cache' do
      expect(klass).to receive(:alias_method_chain).at_least(:once).with(:foo, :cache).and_call_original
      klass.send :define_cache_method, :foo
    end
  end

  describe '.define_cache_with_method' do
    it 'should define the cache with method' do
      expect(klass).to receive(:method_added).with(:foo_with_cache)
      klass.send :define_cache_with_method, :foo
    end

    context 'if the method is already defined' do
      it 'should not define the method' do
        klass.send(:define_method, :foo_with_cache) { 'value' }
        expect(klass).to_not receive(:method_added).with(:foo_with_cache)
        klass.send :define_cache_with_method, :foo
      end
    end
  end

  describe '#cache_with_method' do
    let(:instance) { klass.new }

    before(:each) do
      klass.send :cache_method, :foo, with: :memory_store, logger: Logger.new('/dev/null')
    end

    it 'should cache miss once' do
      expect(instance).to receive(:foo_without_cache).exactly(:once)
      2.times { instance.foo }
    end
  end

  describe '.define_cache_handler_method' do
    it 'should define the cache handler method' do
      expect(klass).to receive(:method_added).with(:cache_handler_for_foo)
      klass.send :define_cache_handler_method, :foo
    end

    it 'should create a cache handler with the proper options' do
      options = { foo: :bar }
      klass.send :define_cache_handler_method, :foo, options
      instance = klass.new
      expect(DefCache::CacheHandler).to receive(:new).with :foo, instance, options
      instance.cache_handler_for_foo
    end

    it 'should define a method that returns a cache handler' do
      options = { foo: :bar }
      klass.send :define_cache_handler_method, :foo, options
      instance = klass.new
      handler = instance.cache_handler_for_foo
      handler.should be_a DefCache::CacheHandler
      handler.instance.should eq instance
      handler.cache_options.should eq options
    end

    context 'if the method is already defined' do
      it 'should not define the method' do
        klass.send(:define_method, :cache_handler_for_foo) { 'value' }
        expect(klass).to_not receive(:method_added).with(:cache_handler_for_foo)
        klass.send :define_cache_handler_method, :foo
      end
    end
  end

  describe '.stub_cache_method_original' do
    it 'should stub the original method' do
      expect(klass).to receive(:method_added).with(:foo)
      klass.send :stub_cache_method_original, :foo
    end

    it 'should define a method that raises an error' do
      klass.send :stub_cache_method_original, :foo
      expect { klass.new.foo }.to raise_error NoMethodError
    end

    context 'if the method is already defined' do
      it 'should not stub the method' do
        klass.send(:define_method, :foo) { 'value' }
        expect(klass).to_not receive(:method_added).with(:foo)
        klass.send :stub_cache_method_original, :foo
      end
    end
  end

end


text:
import React, { Component } from 'react'
import MediaQuery from 'react-responsive'
import {Glyphicon} from "react-bootstrap"

class Navbar extends Component {
	render(){
		return (

			<MediaQuery query='(min-width: 1024px)'>

<Glyphicon glyph="time" />

<Glyphicon glyph="earphone" />

<Glyphicon glyph="map-marker" />

<Glyphicon glyph="search" />

			</MediaQuery>
			<MediaQuery query='(max-width: 1023px)'>

<Glyphicon glyph="earphone" />

<Glyphicon glyph="map-marker" />

			</MediaQuery>

		)
	}
}

export default Navbar


text:
layout: page
title: Mason 40th Anniversary
date: 2016-05-24
author: Marilyn Hill
tags: weekly links, java
status: published
summary: Suspendisse nisi tellus, malesuada ac egestas non, sagittis at.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 07/08/2019
  endDate: 07/10/2019
  ctyhocn: SGVPAHX
  groupCode: M4A
published: true
---
Quisque ultrices molestie quam ullamcorper faucibus. Nullam venenatis nulla id sapien placerat fermentum. Mauris nec pretium mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lacinia non nibh in commodo. Phasellus euismod, mi quis blandit sagittis, leo nunc vehicula odio, vel sodales nisl turpis vitae est. Cras in pharetra dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam et placerat lacus. Nam sed ex ornare, efficitur libero nec, commodo neque. Cras efficitur urna id sapien ullamcorper dictum. Maecenas imperdiet lectus vitae dolor consectetur convallis.

* Nulla vel augue porta, ultrices arcu a, tincidunt arcu
* Praesent tempus enim pretium, vehicula est convallis, consectetur urna
* Ut ac urna id nisi venenatis mattis nec a purus
* Proin sit amet arcu nec lacus porta tristique
* Mauris iaculis eros in mauris porta sagittis.

Nulla facilisi. Mauris et eros id augue tristique porttitor. Vivamus purus ante, finibus posuere lectus nec, tempus egestas tortor. Sed nec semper nunc. Donec pulvinar lacus eu feugiat lacinia. Vestibulum quis semper quam, vitae mollis arcu. Proin sed dictum dolor. Fusce viverra sem nulla, id varius mi molestie tincidunt. Mauris erat magna, accumsan et dictum vel, sodales eget ex. Curabitur dictum rhoncus erat vitae consectetur. Aenean vel vulputate nunc, semper facilisis mi.
Nullam vehicula lectus congue nisi tempus tincidunt. Curabitur egestas scelerisque eleifend. Suspendisse convallis quis ante laoreet scelerisque. Duis iaculis id sem vitae scelerisque. Morbi nibh arcu, pellentesque vitae sagittis vitae, efficitur sed enim. Proin convallis felis ut justo mollis, sed finibus velit ullamcorper. Proin pharetra at nibh scelerisque dictum. Praesent tincidunt, ipsum vitae eleifend fringilla, ipsum velit eleifend dui, vel bibendum justo velit nec velit. Donec ultricies lorem vitae sagittis vehicula. Curabitur metus quam, bibendum sit amet magna vitae, euismod pretium risus.


text:
#include "InstructionFactory.h"
#include "BasicBlock.h"
#include "ReportIdents.h"
#include "Exception.h"
#include "Helper.h"
#include "Float16Compressor.h"

using namespace spv;

namespace Xsc
{

static Instruction* FindInstruction(const std::vector<Instruction*>& instrList, const Op opCode, const std::vector<std::uint32_t>& operands)
{
    for (auto inst : instrList)
    {
        if (inst->opCode == opCode && inst->EqualsOperands(operands))
            return inst;
    }
    return nullptr;
}

void InstructionFactory::Push(BasicBlock* basicBlock)
{
    basicBlockStack_.push(basicBlock);
}

void InstructionFactory::Pop()
{
    if (basicBlockStack_.empty())
        RuntimeErr(R_StackUnderflow(R_InstructionFactory));
    else
        basicBlockStack_.pop();
}

Id InstructionFactory::UniqueId()
{
    return (++uniqueId_);
}

/* ----- Instruction creation functions ----- */

void InstructionFactory::MakeNop()
{
    Put(Op::OpNop);
}

Id InstructionFactory::MakeUndefined(Id type)
{
    return Put(Op::OpUndef, type, UniqueId()).result;
}

void InstructionFactory::MakeName(Id id, const std::string& name)
{
    Put(Op::OpName)
        .AddOperandUInt32(id)
        .AddOperandASCII(name)
    ;
}

void InstructionFactory::MakeMemberName(Id id, Id memberId, const std::string& name)
{
    Put(Op::OpName)
        .AddOperandUInt32(id)
        .AddOperandUInt32(memberId)
        .AddOperandASCII(name)
    ;
}

Id InstructionFactory::MakeTypeVoid()
{
    if (!bufferedTypeVoidInstr_)
        bufferedTypeVoidInstr_ = &(Put(Op::OpTypeVoid, 0, UniqueId()));
    return bufferedTypeVoidInstr_->result;
}

Id InstructionFactory::MakeTypeBool()
{
    if (!bufferedTypeBoolInstr_)
        bufferedTypeBoolInstr_ = &(Put(Op::OpTypeBool, 0, UniqueId()));
    return bufferedTypeBoolInstr_->result;
}

Id InstructionFactory::MakeTypeSampler()
{
    if (!bufferedTypeSamplerInstr_)
        bufferedTypeSamplerInstr_ = &(Put(Op::OpTypeSampler, 0, UniqueId()));
    return bufferedTypeSamplerInstr_->result;
}

Id InstructionFactory::MakeTypeInt(std::uint32_t width)
{
    return MakeTypeIntPrimary(width, true);
}

Id InstructionFactory::MakeTypeUInt(std::uint32_t width)
{
    return MakeTypeIntPrimary(width, false);
}

Id InstructionFactory::MakeTypeFloat(std::uint32_t width)
{
    /* If type was already created, return its result ID */
    if (auto inst = FindInstruction(bufferedTypeInstrs_, Op::OpTypeFloat, { width }))
        return inst->result;

    /* Otherwise, create and buffer new type instruction */
    auto& inst = PutAndBuffer(bufferedTypeInstrs_, Op::OpTypeFloat, 0, UniqueId())
        .AddOperandUInt32(width)
    ;

    /* Store required capabilites */
    if (width == 16)
        AddCapability(Capability::Float16);
    else if (width == 64)
        AddCapability(Capability::Float64);

    return inst.result;
}

Id InstructionFactory::MakeTypeStruct(const std::vector<Id>& memberTypes, const std::string& name)
{
    /* Always create new struct type with all members */
    auto& inst = Put(Op::OpTypeStruct, 0, UniqueId());

    for (auto id : memberTypes)
        inst.AddOperandUInt32(id);

    /* Add name to type */
    MakeName(inst.result, name);

    return inst.result;
}

Id InstructionFactory::MakeTypeVector(Id componentScalarType, std::uint32_t size)
{
    /* If type was already created, return its result ID */
    if (auto inst = FindInstruction(bufferedTypeInstrs_, Op::OpTypeVector, { componentScalarType, size }))
        return inst->result;

    /* Otherwise, create and buffer new type instruction */
    return PutAndBuffer(bufferedTypeInstrs_, Op::OpTypeVector, 0, UniqueId())
        .AddOperandUInt32(componentScalarType)
        .AddOperandUInt32(size)
        .result
    ;
}

Id InstructionFactory::MakeTypeMatrix(Id componentScalarType, std::uint32_t rows, std::uint32_t cols)
{
    /* Make column vector type */
    auto columnType = MakeTypeVector(componentScalarType, rows);

    /* If type was already created, return its result ID */
    if (auto inst = FindInstruction(bufferedTypeInstrs_, Op::OpTypeMatrix, { columnType, cols }))
        return inst->result;

    /* Otherwise, create and buffer new type instruction */
    return PutAndBuffer(bufferedTypeInstrs_, Op::OpTypeMatrix, 0, UniqueId())
        .AddOperandUInt32(columnType)
        .AddOperandUInt32(cols)
        .result
    ;
}

Id InstructionFactory::MakeTypeArray(Id elementType, std::uint32_t length)
{
    /* If type was already created, return its result ID */
    if (auto inst = FindInstruction(bufferedTypeInstrs_, Op::OpTypeArray, { elementType, length }))
        return inst->result;

    /* Otherwise, create and buffer new type instruction */
    return PutAndBuffer(bufferedTypeInstrs_, Op::OpTypeArray, 0, UniqueId())
        .AddOperandUInt32(elementType)
        .AddOperandUInt32(length)
        .result
    ;
}

Id InstructionFactory::MakeTypeRuntimeArray(Id elementType)
{
    /* If type was already created, return its result ID */
    if (auto inst = FindInstruction(bufferedTypeInstrs_, Op::OpTypeRuntimeArray, { elementType }))
        return inst->result;

    /* Otherwise, create and buffer new type instruction */
    return PutAndBuffer(bufferedTypeInstrs_, Op::OpTypeRuntimeArray, 0, UniqueId())
        .AddOperandUInt32(elementType)
        .result
    ;
}

Id InstructionFactory::MakeTypeFunction(Id returnType, const std::vector<Id>& paramTypes)
{
    /* If type was already created, return its result ID */
    for (auto inst : bufferedTypeInstrs_)
    {
        if ( inst->opCode              == Op::OpTypeFunction &&
             inst->GetOperandUInt32(0) == returnType         &&
             inst->EqualsOperands(paramTypes, 1) )
        {
            return inst->result;
        }
    }

    /* Always create new struct type with all members */
    auto& inst = Put(Op::OpTypeFunction, 0, UniqueId());

    inst.AddOperandUInt32(returnType);
    for (auto id : paramTypes)
        inst.AddOperandUInt32(id);

    return inst.result;
}

Id InstructionFactory::MakeTypePointer(spv::StorageClass storageClass, Id subType)
{
    const auto storageClassWord = static_cast<std::uint32_t>(storageClass);

    /* If type was already created, return its result ID */
    if (auto inst = FindInstruction(bufferedTypeInstrs_, Op::OpTypePointer, { storageClassWord, subType }))
        return inst->result;

    /* Otherwise, create and buffer new type instruction */
    return PutAndBuffer(bufferedTypeInstrs_, Op::OpTypePointer, 0, UniqueId())
        .AddOperandUInt32(storageClassWord)
        .AddOperandUInt32(subType)
        .result
    ;
}

Id InstructionFactory::MakeConstantInt16(std::int16_t value, bool uniqueInst)
{
    return MakeConstantUInt32Primary(MakeTypeInt(16), static_cast<std::uint32_t>(static_cast<std::int32_t>(value)), uniqueInst);
}

Id InstructionFactory::MakeConstantUInt16(std::uint16_t value, bool uniqueInst)
{
    return MakeConstantUInt32Primary(MakeTypeUInt(16), static_cast<std::uint32_t>(value), uniqueInst);
}

Id InstructionFactory::MakeConstantInt32(std::int32_t value, bool uniqueInst)
{
    return MakeConstantUInt32Primary(MakeTypeInt(32), static_cast<std::uint32_t>(value), uniqueInst);
}

Id InstructionFactory::MakeConstantUInt32(std::uint32_t value, bool uniqueInst)
{
    return MakeConstantUInt32Primary(MakeTypeUInt(32), value, uniqueInst);
}

Id InstructionFactory::MakeConstantInt64(std::int64_t value, bool uniqueInst)
{
    return MakeConstantUInt64Primary(MakeTypeInt(65), static_cast<std::uint64_t>(value), uniqueInst);
}

Id InstructionFactory::MakeConstantUInt64(std::uint64_t value, bool uniqueInst)
{
    return MakeConstantUInt64Primary(MakeTypeUInt(65), value, uniqueInst);
}

Id InstructionFactory::MakeConstantFloat16(float value, bool uniqueInst)
{
    /* Generate opcode and type */
    auto opCode = (uniqueInst ? Op::OpSpecConstant : Op::OpConstant);
    auto type   = MakeTypeFloat(16);

    /* Convert float to bitmask */
    auto f16 = CompressFloat16(value);

    /* Check if this constant is already defined */
    if (!uniqueInst)
    {
        if (auto inst = FetchConstant(opCode, type, f16))
            return inst->result;
    }

    /* Create new constant instruction */
    return PutAndBuffer(bufferedConstantInstrs_, opCode, type, UniqueId())
        .AddOperandUInt32(f16)
        .result
    ;
}

Id InstructionFactory::MakeConstantFloat32(float value, bool uniqueInst)
{
    /* Generate opcode and type */
    auto opCode = (uniqueInst ? Op::OpSpecConstant : Op::OpConstant);
    auto type   = MakeTypeFloat(32);

    /* Convert float to bitmask */
    union
    {
        std::uint32_t   ui32;
        float           f32;
    }
    data;

    data.f32 = value;

    /* Check if this constant is already defined */
    if (!uniqueInst)
    {
        if (auto inst = FetchConstant(opCode, type, data.ui32))
            return inst->result;
    }

    /* Create new constant instruction */
    return PutAndBuffer(bufferedConstantInstrs_, opCode, type, UniqueId())
        .AddOperandUInt32(data.ui32)
        .result
    ;
}

Id InstructionFactory::MakeConstantFloat64(double value, bool uniqueInst)
{
    /* Generate opcode and type */
    auto opCode = (uniqueInst ? Op::OpSpecConstant : Op::OpConstant);
    auto type   = MakeTypeFloat(64);

    /* Convert float to bitmask */
    union
    {
        std::uint32_t   ui32[2];
        double          f64;
    }
    data;

    data.f64 = value;

    /* Check if this constant is already defined */
    if (!uniqueInst)
    {
        if (auto inst = FetchConstant(opCode, type, data.ui32[0], data.ui32[1]))
            return inst->result;
    }

    /* Create new constant instruction */
    return PutAndBuffer(bufferedConstantInstrs_, opCode, type, UniqueId())
        .AddOperandUInt32(data.ui32[0])
        .AddOperandUInt32(data.ui32[1])
        .result
    ;
}

/*
 * ======= Private: =======
 */

BasicBlock& InstructionFactory::BB()
{
    if (basicBlockStack_.empty())
        RuntimeErr(R_NoActiveBasicBlock);
    return *(basicBlockStack_.top());
}

Instruction& InstructionFactory::Put(const Op opCode, const Id type, const Id result)
{
    auto& bb = BB();

    Instruction inst(opCode);
    {
        inst.type   = type;
        inst.result = result;
    }
    bb.instructions.push_back(inst);

    return bb.instructions.back();
}

Instruction& InstructionFactory::PutAndBuffer(std::vector<Instruction*>& buffer, const Op opCode, const Id type, const Id result)
{
    auto& inst = Put(opCode, type, result);
    buffer.push_back(&inst);
    return inst;
}

Instruction* InstructionFactory::FetchConstant(const Op opCode, const Id type, std::uint32_t value0) const
{
    for (auto inst : bufferedConstantInstrs_)
    {
        if ( inst->opCode              == opCode &&
             inst->type                == type   &&
             inst->NumOperands()       == 1      &&
             inst->GetOperandUInt32(0) == value0 )
        {
            return inst;
        }
    }
    return nullptr;
}

Instruction* InstructionFactory::FetchConstant(const Op opCode, const Id type, std::uint32_t value0, std::uint32_t value1) const
{
    for (auto inst : bufferedConstantInstrs_)
    {
        if ( inst->opCode              == opCode &&
             inst->type                == type   &&
             inst->NumOperands()       == 2      &&
             inst->GetOperandUInt32(0) == value0 &&
             inst->GetOperandUInt32(1) == value1 )
        {
            return inst;
        }
    }
    return nullptr;
}

void InstructionFactory::AddCapability(const Capability cap)
{
    capabilites_.insert(cap);
}

/* ----- Instruction creation functions ----- */

Id InstructionFactory::MakeTypeIntPrimary(std::uint32_t width, bool sign)
{
    /* If type was already created, return its result ID */
    const std::uint32_t signWord = (sign ? 1 : 0);

    if (auto inst = FindInstruction(bufferedTypeInstrs_, Op::OpTypeInt, { width, signWord }))
        return inst->result;

    /* Otherwise, create and buffer new type instruction */
    auto& inst = PutAndBuffer(bufferedTypeInstrs_, Op::OpTypeInt, 0, UniqueId())
        .AddOperandUInt32(width)
        .AddOperandUInt32(signWord)
    ;

    /* Store required capabilites */
    if (width == 16)
        AddCapability(Capability::Int16);
    else if (width == 64)
        AddCapability(Capability::Int64);

    return inst.result;
}

Id InstructionFactory::MakeConstantUInt32Primary(Id type, std::uint32_t value, bool uniqueInst)
{
    /* Generate opcode */
    auto opCode = (uniqueInst ? Op::OpSpecConstant : Op::OpConstant);

    /* Check if this constant is already defined */
    if (!uniqueInst)
    {
        if (auto inst = FetchConstant(opCode, type, value))
            return inst->result;
    }

    /* Create new constant instruction */
    return PutAndBuffer(bufferedConstantInstrs_, opCode, type, UniqueId())
        .AddOperandUInt32(value)
        .result
    ;
}

Id InstructionFactory::MakeConstantUInt64Primary(Id type, std::uint64_t value, bool uniqueInst)
{
    /* Generate opcode */
    auto opCode = (uniqueInst ? Op::OpSpecConstant : Op::OpConstant);

    /* Convert float to bitmask */
    union
    {
        std::uint32_t ui32[2];
        std::uint64_t ui64;
    }
    data;

    data.ui64 = value;

    /* Check if this constant is already defined */
    if (!uniqueInst)
    {
        if (auto inst = FetchConstant(opCode, type, data.ui32[0], data.ui32[1]))
            return inst->result;
    }

    /* Create new constant instruction */
    return PutAndBuffer(bufferedConstantInstrs_, opCode, type, UniqueId())
        .AddOperandUInt32(data.ui32[0])
        .AddOperandUInt32(data.ui32[1])
        .result
    ;
}

} // /namespace Xsc

// ================================================================================