text:
package org.osgl.util;

/*-
 * #%L
 * Java Tool
 * %%
 * Copyright (C) 2014 - 2017 OSGL (Open Source General Library)
 * %%
 * 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.
 * #L%
 */

import org.osgl.exception.UnexpectedException;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.UUID;
import javax.xml.bind.DatatypeConverter;

/**
 * Utility class for encoding and decoding
 *
Part of the code comes from play!framework under apache license

 */
public class Codec {

    public static final char URL_SAFE_BASE64_PADDING_CHAR = UrlSafeBase64.CHAR_PADDING;

    /**
     * @return an UUID String
     */
    public static String UUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * Alias of {@link #UUID()}
     * @return an UUID string
     */
    public static String uuid() {
        return UUID();
    }

    /**
     * Encode a String to base64
     *
     * @param value The plain String
     * @return The base64 encoded String
     * @deprecated Use {@link #encodeBase64(String)} instead
     */
    @Deprecated
    public static String encodeBASE64(String value) {
        return new String(Base64.encode(value.getBytes(Charsets.UTF_8)));
    }

    /**
     * Encode a String to base64
     *
     * @param value The plain String
     * @return The base64 encoded String
     */
    public static String encodeBase64(String value) {
        return new String(Base64.encode(value.getBytes(Charsets.UTF_8)));
    }

    /**
     * Encode a String to base64 using variant URL safe encode scheme
     * @param value the plain string
     * @return the base64 encoded String that is URL safe
     */
    public static String encodeUrlSafeBase64(String value) {
        return new String(UrlSafeBase64.encode(value.getBytes(Charsets.UTF_8)));
    }

    /**
     * Encode binary data to base64
     *
     * @param value The binary data
     * @return The base64 encoded String
     * @deprecated  Use {@link #encodeBase64(byte[])} instead
     */
    @Deprecated
    public static String encodeBASE64(byte[] value) {
        return encodeBase64(value);
    }

    /**
     * Encode binary data to base64
     *
     * @param value The binary data
     * @return The base64 encoded String
     */
    public static String encodeBase64(byte[] value) {
        return new String(Base64.encode(value));
    }

    /**
     * Encode binary data to base64 use Url safe variant
     *
     * @param value The binary data
     * @return The base64 encoded String that is URL safe
     */
    public static String encodeUrlSafeBase64(byte[] value) {
        return new String(UrlSafeBase64.encode(value));
    }

    /**
     * Decode a base64 value
     *
     * @param value The base64 encoded String
     * @return decoded binary data
     * @deprecated Use {@link #decodeBase64(String)} instead
     */
    @Deprecated
    public static byte[] decodeBASE64(String value) {
        return Base64.decode(value);
    }

    /**
     * Decode a base64 value
     *
     * @param value The base64 encoded String
     * @return decoded binary data
     */
    public static byte[] decodeBase64(String value) {
        return Base64.decode(value);
    }

    /**
     * Decode a URL safe base64 value
     *
     * @param value The base64 encoded String that is encoded using {@link #encodeUrlSafeBase64(String)}
     * @return decoded binary data
     */
    public static byte[] decodeUrlSafeBase64(String value) {
        return UrlSafeBase64.decode(value);
    }

    /**
     * Build an hexadecimal MD5 hash for a String
     *
     * @param value The String to hash
     * @return An hexadecimal Hash
     */
    public static String hexMD5(String value) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(value.getBytes("utf-8"));
            byte[] digest = messageDigest.digest();
            return byteToHexString(digest);
        } catch (Exception ex) {
            throw new UnexpectedException(ex);
        }
    }

    /**
     * Build an hexadecimal SHA1 hash for a String
     *
     * @param value The String to hash
     * @return An hexadecimal Hash
     */
    public static String hexSHA1(String value) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            md.update(value.getBytes("utf-8"));
            byte[] digest = md.digest();
            return byteToHexString(digest);
        } catch (Exception ex) {
            throw new UnexpectedException(ex);
        }
    }

    /**
     * Write a byte array as hexadecimal String.
     * @return bytes
     */
    public static String byteToHexString(byte[] bytes) {
        return DatatypeConverter.printHexBinary(bytes);
    }

    /**
     * Transform an hexadecimal String to a byte array.
     * @param hexString the string
     * @return the byte array of the hex string
     */
    public static byte[] hexStringToByte(String hexString) {
        return DatatypeConverter.parseHexBinary(hexString);
    }

    public static String encodeUrl(String s, Charset enc) {
        try {
            return URLEncoder.encode(s, enc.name());
        } catch (UnsupportedEncodingException e) {
            throw E.encodingException(e);
        }
    }

    public static String encodeUrl(String s) {
        try {
            return URLEncoder.encode(s, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw E.encodingException(e);
        }
    }

    public static String decodeUrl(String s, Charset enc) {
        try {
            return URLDecoder.decode(s, enc.name());
        } catch (UnsupportedEncodingException e) {
            throw E.encodingException(e);
        }
    }

    public static String decodeUrl(String s) {
        try {
            return URLDecoder.decode(s, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw E.encodingException(e);
        }
    }

}


text:
extern "C" {
#endif

#include "tilebase.h"

struct nd_subarray_t
{ nd_t     shape; // must be free'd with ndfree()
  size_t  *ori;   // owned by the tile used in construction, do not free.
};

aabb_t AABBToPx(tile_t self, aabb_t box_nm); ///< caller must free returned value with AABBFree

struct nd_subarray_t AABBToSubarray(tile_t self, aabb_t box_nm); ///< caller must use ndfree to release shape field in returned struct.

#ifdef __cplusplus
} //extern "C"
#endif

redpajama_set_name: RedPajamaGithub


text:
  <form name="addr1.1" id="form1" action="https://example.com/" method="post">
    Name: <input type="text" name="firstname" id="firstname">

    Address: <input type="text" name="address1" id="address1">

    City: <input type="text" name="city" id="city">

    State: <select name="state">
      <option value="CA">CA</option>
      <option value="MA">MA</option>
      <option value="NY">NY</option>
      <option value="MD">MD</option>
      <option value="OR">OR</option>
      <option value="OH">OH</option>
      <option value="IL">IL</option>
      <option value="DC">DC</option>
    </select>

    Zip: <input name="zip" id="zip">

    Country: <select name="country" id="country" onchange="CountryChanged()">
      <option value="CA">Canada</option>
      <option value="US">United States</option>
    </select>

    Company: <input name="company" id="company">

    Email: <input name="email" id="email">

    Phone: <input name="phone" id="phone">

    <input type="reset" value="Reset">
    <input type="submit" value="Submit" id="profile_submit">
  </form>


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="@string/title_fragment_translate"/>
</menu>


text:
import unittest
from functools import wraps

import jsonstreamer

json_file_name = lambda test_fn: 'tests/json_files/' + test_fn.__name__[5:] + '.json'

def load_test_data(func):
    """loads some json from a file with the same name as the test"""

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        with open(json_file_name(func), encoding='utf-8') as json_file:
            json_input = json_file.read()
        return func(self, json_input)

    return wrapper

class JSONStreamerTests(unittest.TestCase):
    def setUp(self):
        self._assertions = []
        self._streamer = jsonstreamer.JSONStreamer()
        self._streamer.add_catch_all_listener(self._catch_all)

    def tearDown(self):
        self._streamer.close()
        self.assertEqual(len(self._assertions), 0)

    def _catch_all(self, event_name, *args):
        value = args[0] if args else None
        # print('Asserting event_name: {} , value : {}'.format(event_name,value))
        try:
            e, v = self._assertions.pop(0)
        except IndexError:
            raise AssertionError('not enough asserts')
        self.assertEqual(event_name, e)
        self.assertEqual(value, v)

    @load_test_data
    def test_simple_object(self, json_input):

        self._assertions = [('doc_start', None),
                            ('object_start', None),
                            ('key', 'apple'),
                            ('value', 8),
                            ('key', 'banana'),
                            ('value', 'many'),
                            ('object_end', None),
                            ('doc_end', None)]

        self._streamer.consume(json_input)

class ObjectStreamerTests(unittest.TestCase):
    def setUp(self):
        self._assertions = []
        self._streamer = jsonstreamer.ObjectStreamer()
        self._streamer.add_catch_all_listener(self._catch_all)

    def tearDown(self):
        self._streamer.close()
        self.assertEqual(len(self._assertions), 0)

    def _catch_all(self, event_name, *args):
        value = args[0] if args else None
        # print('\nAsserting event_name: {} , value : {}'.format(event_name, value))
        try:
            expected_event, expected_value = self._assertions.pop(0)
        except IndexError:
            raise AssertionError('not enough asserts')
        self.assertEqual(event_name, expected_event)
        self._assert_value(expected_value, value)

    def _assert_value(self, expected_value, value):
        if value and isinstance(value, tuple) and len(value) == 2:
            if isinstance(value[1], dict):
                self.assertDictEqual(value[1], expected_value[1])
                self.assertEqual(expected_value[0], value[0])
            elif isinstance(value[1], list):
                self.assertListEqual(value[1], expected_value[1])
                self.assertEqual(expected_value[0], value[0])
            else:
                self.assertEqual(value, expected_value)
        else:
            self.assertEqual(value, expected_value)

    @load_test_data
    def test_nested_dict(self, json_input):
        self._assertions = [('object_stream_start', None),
                            ('pair', ('params', {'dependencies': [{'app': 'Example'}]})),
                            ('object_stream_end', None)]
        self._streamer.consume(json_input)

    @load_test_data
    def test_array(self, json_input):
        self._assertions = [('array_stream_start', None),
                            ('element', "a"),
                            ('element', 2),
                            ('element', True),
                            ('element', {"apple": "fruit"}),
                            ('array_stream_end', None)]
        self._streamer.consume(json_input)

    @load_test_data
    def test_spl_chars_in_value(self, json_input):
        self._assertions = [('object_stream_start', None),
                            ('pair',
                             ('employees',
                              [
                                  {"first Name": "Jo:hn", "lastName": "Doe,Foe"},
                                  {"firstName": "An\\na", "lastName": "Smith Jack"},
                                  {"firstName": "Peter", "lastName": "Jones"},
                                  True,
                                  745
                              ]
                              )
                             ),
                            ('object_stream_end', None)]
        self._streamer.consume(json_input)

    @load_test_data
    def test_space_preservation(self, json_input):
        self._assertions = [('object_stream_start', None),
                            ('pair', ('between space', ' before space')),
                            ('pair', ('after space  ', '  all spaces ')),
                            ('object_stream_end', None)
                            ]
        self._streamer.consume(json_input)

    @load_test_data
    def test_arbit_1(self, json_input):
        self._assertions = [('object_stream_start', None),
                            ('pair', ('to', '8743d93a')),
                            ('pair', ('type', 'response')),
                            ('pair', ('payload',
                                      {'request_id': '0f2d9b9c',
                                       'result':
                                           {'type': 'allopathy',
                                            'manufacturer': {'url': 'johnsons.com', 'id': 5, 'name': 'johnsons'},
                                            'name': 'crocin 200 mg',
                                            'brand': 'crocin',
                                            'image_urls': ['http//1example.com/3', 'http//1example.com/2'],
                                            'price': 200.0,
                                            'attributes': [
                                                {'value': 'strip', 'key': 'pack_form', 'display_name': 'pack form'},
                                                {'value': 'tablet', 'key': 'drug_form', 'display_name': 'drug form'},
                                                {'value': '200 mg', 'key': 'strength', 'display_name': 'strength'},
                                                {'value': 'paracetamol', 'key': 'name', 'display_name': 'name'},
                                                {'value': 30, 'key': 'units_in_pack', 'display_name': 'units in pack'}],
                                            'sku_id': 91,
                                            'units_in_pack': 30
                                            }
                                       }
                                      )
                             ),
                            ('pair', ('entity', None)),
                            ('pair', ('pid', '43abc6be')),
                            ('object_stream_end', None)]
        self._streamer.consume(json_input)

class ObjectStreamerListenerTests(unittest.TestCase):
    def setUp(self):
        self._streamer = jsonstreamer.ObjectStreamer()

    def tearDown(self):
        self._streamer.close()
        self.assertEqual(len(self._assertions), 0)

    @load_test_data
    def test_on_element(self, json_input):
        self._assertions = ["a", 2, True, {"apple": "fruit"}]

        def _on_element(value):
            try:
                expected_value = self._assertions.pop(0)
            except IndexError:
                raise AssertionError('not enough asserts')

            self.assertEqual(expected_value, value)

        self._streamer.add_listener('element', _on_element)
        self._streamer.consume(json_input)

    @load_test_data
    def test_on_element_multiple_parses(self, json_input):
        self._assertions = ["a", 2, True, {"apple": "fruit"}, ]

        def _on_element(value):
            try:
                expected_value = self._assertions.pop(0)
            except IndexError:
                raise AssertionError('not enough asserts')

            self.assertEqual(expected_value, value)

        self._streamer.add_listener('element', _on_element)
        self._streamer.consume(json_input[0:8])
        self._streamer.consume(json_input[8:])

if __name__ == '__main__':
    unittest.main(verbosity=2)


text:
package org.apache.hadoop.hdfs.server.namenode.metrics;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.metrics.*;
import org.apache.hadoop.metrics.jvm.JvmMetrics;
import org.apache.hadoop.metrics.util.MetricsBase;
import org.apache.hadoop.metrics.util.MetricsIntValue;
import org.apache.hadoop.metrics.util.MetricsLongValue;
import org.apache.hadoop.metrics.util.MetricsRegistry;
import org.apache.hadoop.metrics.util.MetricsTimeVaryingLong;
import org.apache.hadoop.metrics.util.MetricsTimeVaryingRate;

/**
 *
 * This class is for maintaining  the various NameNode activity statistics
 * and publishing them through the metrics interfaces.
 * This also registers the JMX MBean for RPC.
 * <p>
 * This class has a number of metrics variables that are publicly accessible;
 * these variables (objects) have methods to update their values;
 *  for example:
 *  <p> {@link #syncs}.inc()
 *
 */
public class NameNodeMetrics implements Updater {
    private static Log log = LogFactory.getLog(NameNodeMetrics.class);
    private final MetricsRecord metricsRecord;
    public MetricsRegistry registry = new MetricsRegistry();

    private NameNodeActivtyMBean namenodeActivityMBean;

    public MetricsTimeVaryingLong numReportedCorruptReplicas =
               new MetricsTimeVaryingLong("CorruptReplicasReported", registry);
    public MetricsTimeVaryingLong numFilesCreated =
                          new MetricsTimeVaryingLong("FilesCreated", registry);
    public MetricsTimeVaryingLong numFilesAppended =
                          new MetricsTimeVaryingLong("FilesAppended", registry);
    public MetricsTimeVaryingLong numGetBlockLocations =
                    new MetricsTimeVaryingLong("GetBlockLocations", registry);
    public MetricsTimeVaryingLong numFilesRenamed =
                    new MetricsTimeVaryingLong("FilesRenamed", registry);
    public MetricsTimeVaryingLong numFilesMerged =
                    new MetricsTimeVaryingLong("FileMerged", registry);
    public MetricsTimeVaryingLong numFilesDeleted =
                    new MetricsTimeVaryingLong("FilesDeleted", registry,
                    "The number of files/dirs deleted by delete or rename operations");
    public MetricsTimeVaryingLong numFilesRaided =
                    new MetricsTimeVaryingLong("FileRaided", registry,
                    "The number of files raided by raidFile operations");
    public MetricsTimeVaryingLong numGetListingOps =
                    new MetricsTimeVaryingLong("GetListingOps", registry);
    public MetricsTimeVaryingLong numCreateFileOps =
                    new MetricsTimeVaryingLong("CreateFileOps", registry);
    public MetricsTimeVaryingLong numDeleteFileOps =
                          new MetricsTimeVaryingLong("DeleteFileOps", registry);
    public MetricsTimeVaryingLong numRaidFileOps =
                          new MetricsTimeVaryingLong("RaidFileOps", registry);
    public MetricsTimeVaryingLong numFileInfoOps =
                          new MetricsTimeVaryingLong("FileInfoOps", registry);
    public MetricsTimeVaryingLong numAddBlockOps =
                          new MetricsTimeVaryingLong("AddBlockOps", registry);
    public MetricsTimeVaryingLong numSetReplication =
                          new MetricsTimeVaryingLong("SetReplication", registry);
    public MetricsTimeVaryingLong numSetPermission =
                          new MetricsTimeVaryingLong("SetPermission", registry);
    public MetricsTimeVaryingLong numSetOwner =
                          new MetricsTimeVaryingLong("SetOwner", registry);
    public MetricsTimeVaryingLong numAbandonBlock =
                          new MetricsTimeVaryingLong("numAbandonBlock", registry);
    public MetricsTimeVaryingLong numCompleteFile =
                          new MetricsTimeVaryingLong("numCompleteFile", registry);
    public MetricsTimeVaryingLong numReportBadBlocks =
                          new MetricsTimeVaryingLong("numReportBadBlocks", registry);
    public MetricsTimeVaryingLong numNextGenerationStamp =
                          new MetricsTimeVaryingLong("numNextGenerationStamp", registry);
    public MetricsTimeVaryingLong numMkdirs =
                          new MetricsTimeVaryingLong("numMkdirs", registry);
    public MetricsTimeVaryingLong numRenewLease =
                          new MetricsTimeVaryingLong("numRenewLease", registry);
    public MetricsTimeVaryingLong numSaveNamespace =
                          new MetricsTimeVaryingLong("numSaveNamespace", registry);
    public MetricsTimeVaryingLong numRefreshNodes =
                          new MetricsTimeVaryingLong("numRefreshNodes", registry);
    public MetricsTimeVaryingLong numSetQuota =
                          new MetricsTimeVaryingLong("numSetQuota", registry);
    public MetricsTimeVaryingLong numFsync =
                          new MetricsTimeVaryingLong("numFsync", registry);
    public MetricsTimeVaryingLong numSetTimes =
                          new MetricsTimeVaryingLong("numSetTimes", registry);
    public MetricsTimeVaryingLong numRegister =
                          new MetricsTimeVaryingLong("numRegister", registry);
    public MetricsTimeVaryingLong numHeartbeat =
                          new MetricsTimeVaryingLong("numHeartbeat", registry);
    public MetricsTimeVaryingLong numBlockReport =
                          new MetricsTimeVaryingLong("numBlockReport", registry);
    public MetricsTimeVaryingLong numBlockReceived =
                          new MetricsTimeVaryingLong("numBlockReceived", registry);
    public MetricsTimeVaryingLong numVersionRequest =
                          new MetricsTimeVaryingLong("numVersionRequest", registry);
    public MetricsTimeVaryingLong numGetContentSummary =
                          new MetricsTimeVaryingLong("numGetContentSummary", registry,
                          "The number of get content summary operations");

    // hftp related metrics
    public MetricsTimeVaryingLong numFileDataServletDoGet =
        new MetricsTimeVaryingLong("numFileDataServletDoGet", registry);
    public MetricsTimeVaryingLong numListPathsServletDoGet =
        new MetricsTimeVaryingLong("numListPathsServletDoGet", registry);
    public MetricsTimeVaryingLong numRedirectServletDoGet =
        new MetricsTimeVaryingLong("numRedirectServletDoGet", registry);
    public MetricsTimeVaryingLong numFsckDoGet =
        new MetricsTimeVaryingLong("numFsckDoGet", registry);

    public MetricsTimeVaryingRate transactions =
                    new MetricsTimeVaryingRate("Transactions", registry, "Journal Transaction");
    public MetricsTimeVaryingRate syncs =
                    new MetricsTimeVaryingRate("Syncs", registry, "Journal Sync");
    public MetricsTimeVaryingLong transactionsBatchedInSync =
                    new MetricsTimeVaryingLong("JournalTransactionsBatchedInSync", registry, "Journal Transactions Batched In Sync");
    public MetricsLongValue currentTxnId =
                    new MetricsLongValue("CurrentTxId", registry, "Last Written Transaction Id");
    public MetricsTimeVaryingLong rollEditLogTime =
                    new MetricsTimeVaryingLong("RollEditLogTime", registry, "Roll Edit Log Time");
    public MetricsTimeVaryingLong rollFsImageTime =
                    new MetricsTimeVaryingLong("RollFSImageTime", registry, "Roll FSImage Time");

    public MetricsTimeVaryingRate blockReport =
                    new MetricsTimeVaryingRate("blockReport", registry, "Block Report");
    public MetricsIntValue safeModeTime =
                    new MetricsIntValue("SafemodeTime", registry, "Duration in SafeMode at Startup");
    public MetricsIntValue fsImageLoadTime =
                    new MetricsIntValue("fsImageLoadTime", registry, "Time loading FS Image at Startup");
    public MetricsIntValue numBlocksCorrupted =
                    new MetricsIntValue("BlocksCorrupted", registry);
    public MetricsIntValue numBufferedTransactions =
                    new MetricsIntValue("numBufferedTransactions", registry);
    public MetricsLongValue numOverReplicatedBlocks =
                    new MetricsLongValue("numOverReplicatedBlocks", registry);
    public MetricsLongValue numRaidEncodingTasks =
                    new MetricsLongValue("numRaidEncodingTasks", registry);
    public MetricsIntValue imagesFailed =
                    new MetricsIntValue("imagesFailed", registry,
                        "Number of failed image directories");
    public MetricsIntValue journalsFailed =
                    new MetricsIntValue("journalsFailed", registry,
                        "Number of failed journals");
    public MetricsLongValue tsLastEditsRoll = new MetricsLongValue(
        "tsLastEditsRoll", registry, "Timestamp of last edits rolling");

    public NameNodeMetrics(Configuration conf, NameNode nameNode) {
      String sessionId = conf.get("session.id");
      // Initiate Java VM metrics
      JvmMetrics.init("NameNode", sessionId);

      // Now the Mbean for the name node - this alos registers the MBean
      namenodeActivityMBean = new NameNodeActivtyMBean(registry);

      // Create a record for NameNode metrics
      MetricsContext metricsContext = MetricsUtil.getContext("dfs");
      metricsRecord = MetricsUtil.createRecord(metricsContext, "namenode");
      metricsRecord.setTag("sessionId", sessionId);
      metricsContext.registerUpdater(this);
      log.info("Initializing NameNodeMeterics using context object:" +
                metricsContext.getClass().getName());
    }

    public void shutdown() {
      if (namenodeActivityMBean != null)
        namenodeActivityMBean.shutdown();
    }

    /**
     * Since this object is a registered updater, this method will be called
     * periodically, e.g. every 5 seconds.
     */
    public void doUpdates(MetricsContext unused) {
      synchronized (this) {
        for (MetricsBase m : registry.getMetricsList()) {
          m.pushMetric(metricsRecord);
        }
      }
      metricsRecord.update();
    }

    public void resetAllMinMax() {
      transactions.resetMinMax();
      syncs.resetMinMax();
      blockReport.resetMinMax();
    }
}


text:
#ifndef __ITABDIALOG_H_
#define __ITABDIALOG_H_

#include "maxheap.h"
#include "3dsmaxport.h"

class ITabbedDialog;
class ITabPage;

class ITabRegister;

class ITabDialogProc;
class ITabPageProc;
class ITabDialogFilter;

class IRollupWindow;

class ITabDialogPluginTab;

/***********************************************************************
 *
 * ITabDialogManager
 *
 * This interface is used to create tabbed dialogs and to register
 * tabs with dialogs that are created by the system or other plugins
 *
 **********************************************************************/
class ITabDialogManager : public FPStaticInterface {
public:

   // Create a tabbed dialog. Parent is the parent window of the dialog,
   // Instance is the instance where the dialog tempate is stored, and dlg
   // is the name of the dialog template resource. If instance is NULL,
   // then dlg is a pointer to the dialog template in memory. MainProc is
   // the object that is used to handle messages for the dialog. Mult is
   // true if the tab control should be multiline and is only applicable
   // when tabID is -1. TabID is the ID of a tab control in the dialog
   // template, that is to be used. If tabID is -1, then a tab control
   // is created. HelpID is used to bring up context sensitive help
   // when the F1 key is pressed.
   virtual ITabbedDialog* CreateTabbedDialog(
      HWND        parent,
      HINSTANCE      instance,
      LPCTSTR        dlg,
      ITabDialogProc*   mainProc,
      bool        multiline,
      DWORD       helpID=0,
      int            tabID = -1,
      const Class_ID&   dialogID = Class_ID(0,0)
   ) = 0;

   // Register/UnRegister a tab for a dialog, DialogID is the id of the dialog
   // this tab is to be used with. Tab is the address of an object that is used
   // to add the tab when the dialog is created. Tab must remain valid while
   // it is registered.
   virtual bool RegisterTab(const Class_ID& dialogID, ITabDialogPluginTab* tab) = 0;
   virtual void UnRegisterTab(const Class_ID& dialogID, ITabDialogPluginTab* tab) = 0;

   // Set/Get the current plugin tab filter for a dialog. This filter is
   // used to determine which tabs will be present when the dialog is created.
   virtual void SetTabFilter(const Class_ID& dialogID, ITabDialogFilter* filter) = 0;
   virtual ITabDialogFilter* GetTabFilter(const Class_ID& dialogID) = 0;

   // Get the ITabbedDialog for the dialog id. Returns NULL if dialog not
   // present. Assumes that only one dialog is present for a dialog id at a time.
   // Note: NOTIFY_TABBED_DIALOG_CREATED and NOTIFY_TABBED_DIALOG_DELETED sent when
   // a tabbed dialog is created or deleted. callparam is point to dialogID
   virtual ITabbedDialog* GetTabbedDialog(const Class_ID& dialogID) = 0;

   // The return value can be a combination of TAB_DIALOG_REMOVE_TAB and
   // TAB_DIALOG_ADD_TAB
   static int AcceptTab(
      ITabDialogFilter*    filter,
      ITabDialogPluginTab* tab
   );
};

// These are some internally defined dialog ids
// Preferences dialog
#define TAB_DIALOG_PREFERENCES_ID   Class_ID(0x16d416fb, 0x1cdd4da5)
// Object Properties dialog
#define TAB_DIALOG_PROPERTIES_ID Class_ID(0x777f709b, 0x44404554)
// Configure Path dilaog
#define TAB_DIALOG_PATH_ID       Class_ID(0x2c863840, 0x67b1202f)
// Render dialogs
#define TAB_DIALOG_RENDER_ID     Class_ID(0x648636a0, 0xe52086b)
#define TAB_DIALOG_VIDEO_POST_ID Class_ID(0x41be0fad, 0x160c099c)
// Environment Dialog
#if defined(ENVIRONMENT_DIALOG_IN_RENDER_DIALOG)
#define TAB_DIALOG_ENVIRONMENT_ID   TAB_DIALOG_RENDER_ID
#else // defined(environment_dialog_in_render_dialog)
#define TAB_DIALOG_ENVIRONMENT_ID   Class_ID(0x447f2d77, 0x781268a7)
#endif   // defined(environment_dialog_in_render_dialog)
// Customize dialog...
#define TAB_DIALOG_CUSTOMIZE_ID     Class_ID(0x27A3F8FB, 0x8D294d77)

// These are the results of accepting a tab for a dialog
enum {
   TAB_DIALOG_REMOVE_TAB = 1,
   TAB_DIALOG_ADD_TAB = 2
};

#define TAB_DIALOG_MANAGER_INTERFACE_ID Interface_ID(0x46465ead, 0x6e3cbb)

// This inline will return the ITabDialogManager.
inline ITabDialogManager* GetTabDialogManager()
{
   return static_cast<ITabDialogManager*>(
      GetCOREInterface(TAB_DIALOG_MANAGER_INTERFACE_ID));
}

/***********************************************************************
 *
 * ITabDialogPluginTab
 *
 * This interface is used to add plugin tabs to a tabbed dialog.
 *
 **********************************************************************/
class ITabDialogPluginTab : public BaseInterface {
public:
   // Add your tab(s) to the dialog. This will only be called if
   // both this object and the dialog agree that the tab should
   // be added. Dialog is the address of the dialog.
   virtual void AddTabToDialog(ITabbedDialog* dialog) = 0;

   // Accept this tab in this dialog. Dialog is the address of the
   // dialog. Return true if the tab should be added. Return false
   // if the tab should not be added or should be removed if it
   // was added previously. Filter is the dialog filter.
   virtual int AcceptDialog(
      ITabDialogFilter* filter
   ) { return TAB_DIALOG_ADD_TAB; }

   // These return various information that is likely to be interesting
   // when deciding whether or not to use this tab.

   // If this tab is the UI for a ReferenceMaker, return it here.
   virtual ReferenceMaker* GetReferenceMaker() { return NULL; }

   // Otherwise, if this tab is the UI for an Animatable, return it here
   virtual Animatable* GetAnimatable() { return GetReferenceMaker(); }

   // Otherwise, If this tab has some known class ID and super class ID
   virtual Class_ID GetClassID() {
      Animatable* a = GetAnimatable();
      return a ? a->ClassID() : Class_ID(0, 0);
   }
   virtual SClass_ID GetSuperClassID() {
      Animatable* a = GetAnimatable();
      return a ? a->SuperClassID() : 0;
   }

   // Otherwise, you will need to define a special interface
   virtual BaseInterface* GetInterface(const Interface_ID& id) { return NULL; }
};

/***********************************************************************
 *
 * TabDialogFilter
 *
 * This interface is used to filter plugin tabs in a tabbed dialog.
 *
 **********************************************************************/
class ITabDialogFilter : public BaseInterface {
public:
   // Return true if the tabs added by the ITabDialogPluginTab tab
   // are acceptable for this dialog. Dialog is the dialog being
   // filtered.
   virtual int AcceptTab(
      ITabDialogPluginTab* tab
   ) { return TAB_DIALOG_ADD_TAB; }

   // Launch the dialog for this filter, open the dialog at a specific page
   virtual int LaunchDialog(const Class_ID& page = Class_ID(0,0)) { return IDOK; }

   // These return various information that is likely to be interesting
   // when deciding whether or not to add a tab.

   // If this dialog is the UI for a ReferenceMaker, return it here.
   virtual ReferenceMaker* GetReferenceMaker() { return NULL; }

   // Otherwise, if this dialog is the UI for an Animatable, return it here
   virtual Animatable* GetAnimatable() { return GetReferenceMaker(); }

   // Otherwise, If this dialog has some known class ID and super class ID
   virtual Class_ID GetClassID() {
      Animatable* a = GetAnimatable();
      return a ? a->ClassID() : Class_ID(0, 0);
   }
   virtual SClass_ID GetSuperClassID() {
      Animatable* a = GetAnimatable();
      return a ? a->SuperClassID() : 0;
   }

   // Otherwise, you will need to define a special interface
   virtual BaseInterface* GetInterface(const Interface_ID& id) { return NULL; }
};

/***********************************************************************
 *
 * TabDialogMessages
 *
 * Messages used by the tab dialog class
 *
 **********************************************************************/
enum TabDialogMessages {
   TABDLG_SWITCH_FROM   = WM_USER + 1, // Switching from this page
   TABDLG_SWITCH_TO  = WM_USER + 2, // Switching to this page
   TABDLG_COMMIT     = WM_USER + 3, // Commit the page's working values for real
   TABDLG_PRECOMMIT  = WM_USER + 4, // Check your values, but don't close the dialog;
                              // if your page needs to reject an OK, set the
                              // bool* in LPARAM to false.
   TABDLG_CANCEL     = WM_USER + 5, // User is cancelling out of the dialog
   TABDLG_CLOSE      = WM_USER + 6, // User is closing a modeless dialog
   TABDLG_INVALIDATE = WM_USER + 7, // The underlying data has changed
   TABDLGNOTIFY_GETINITINFO   = WM_USER + 8, // WE need to get init, see struct TABDLG_NMHDR
   TABDLG_RESIZE_DIALOG= WM_USER + 9   // The tab is too small for the content
};

// The address of this struct passed in LPARAM when
// you get a WM_NOTIFY, with TABDLGNOTIFY_GETINITINFO
// as the notify code. This notification is sent to
// the tab dialog before each page is created. hdr.idFrom
// is the index of the page about to be created. The
// value stored in dwInitParam is passed to the InitPage
// method as lparam.
struct TABDLG_NMHDR: public MaxHeapOperators
{
   NMHDR hdr;//the common denominator
            //we use the
   LPARAM dwInitParam; //this out param contains the ptr to initialization data for the page.
};

/***********************************************************************
 *
 * ITabbedDialog
 *
 * This interface is used to manage a tabbed dialog. You can add pages
 * and either display a modal or modeless dialog.
 * You can add a rollout page, that can contain MAX rollouts
 *
 **********************************************************************/

#define TABBED_DIALOG_INTERFACE_ID Interface_ID(0x4128621b, 0x744d5789)

class ITabbedDialog: public MaxHeapOperators {
public:
   enum {
      kSystemPage = 20,
      kNormalPage = 50,
      kMaxPage = 100
   };

   static ITabbedDialog* GetPointer(HWND dialog) {
      return DLGetWindowLongPtr<ITabbedDialog*>(dialog);
   }

   // Delete yourself
   virtual void DeleteThis() = 0;

   // Return the dialogID for this dialog
   virtual Class_ID GetDialogID() const = 0;

   // Add a page to the dialog. Text is the tab text. Instance and
   // tmplt are the instance and resource for the dialog template
   // for the page. If instance is NULL, the tmplt is a pointer to
   // the dialog template in memory. Proc is the message handler for
   // the page. Image is an image for the tab in the image list set
   // by SetImageList. Order is the order that the tab will appear
   // in the tabs. Two pages with the same order are ordered
   // by the order they are added. HelpID is ID used for context
   // sensitive help.
   virtual ITabPage* AddPage(
      LPCTSTR              text,
      HINSTANCE            instance,
      LPCTSTR              tmplt,
      ITabPageProc*        proc,
      const Class_ID&         pageID,
      ITabDialogPluginTab* plugin = NULL,
      DWORD             helpID = 0,
      int                  order = kNormalPage,
      int                  image = -1
   ) = 0;

   // Add a rollout page to the dialog. Text is the tab text. Proc is
   // the message handler for the page. The margins give additional
   // space between the rollout control and the client are of the tab.
   // Image is an image for the tab in the image list set by SetImageList.
   // Order is the order that the tab will appear in the tabs. Two
   // pages with the same order are ordered by the order they are added.
   // HelpID is ID used for context sensitive help.
   virtual ITabPage* AddRollout(
      LPCTSTR              text,
      ITabPageProc*        proc,
      const Class_ID&         pageID,
      ITabDialogPluginTab* plugin = NULL,
      int                  controlID = -1,
      int                  width = 0,
      int                  bottomMargin = 0,
      DWORD             helpID = 0,
      int                  order = kNormalPage,
      int                  image = -1
   ) = 0;

   // Add and remove registered tabs to the dialog.
   virtual void SyncRegisteredTabs() = 0;

   // Get the filter for this dialog
   virtual ITabDialogFilter* GetTabFilter() const = 0;

   // Get/Set the dialog proc. The previous
   // value is returned when setting the proc
   virtual ITabDialogProc* GetProc() const = 0;
   virtual ITabDialogProc* SetProc(ITabDialogProc* newProc) = 0;

   // Display and process modal dialog
   virtual INT_PTR DoModal(const Class_ID& page) = 0;

   // Display and process modeless dialog
   virtual bool DoFloater(const Class_ID& page) = 0;

   // Switch to the given page.
   virtual void Switch(const Class_ID& page) = 0;

   // Invalidate all pages in the dialog.
   virtual void Invalidate() = 0;

   // Set the image list for the tab control
   virtual void SetImageList(HIMAGELIST list) = 0;

   // Get the index of the current page
   virtual int CurrentPage() const = 0;

   // Set the margins for the tab in the dialog. This is
   // only applicable if the tabCtrl is not part of the
   // dialog template. If SetTabbedRect is called with
   // a nonempty rectangle, it is used, otherwise the
   // margins are used.
   virtual void SetMargins(int left, int top, int right, int bottom) = 0;
   virtual void SetTabbedRect(const RECT& rect) = 0;

   // Convert indices to pages
   virtual int GetNbPages() const = 0;
   virtual ITabPage* GetPage(int index) const = 0;
   virtual ITabPage* GetPage(const Class_ID& id) const = 0;

   // Get the window for the tabbed dialog
   virtual HWND GetHWND() const = 0;

   // Used for modal dialogs with IDOK and IDCANCEL
   virtual bool OkToCommit() = 0;
   virtual bool CommitPages() = 0;

   // Used for modeless dialogs; note that if the user hits the X in the upper right
   // corner, a cancel message will be sent.
   virtual void CloseDialog() = 0;
   virtual void ClosePages() = 0;

   // Used for both.
   virtual void CancelDialog() = 0;
   virtual void CancelPages() =0;

   // Get the window for the tab control
   virtual HWND GetTabHWND() const = 0;

protected:
   // Don't allow it to be deleted except through DeleteThis
   ~ITabbedDialog() {}
};

/***********************************************************************
 *
 * TabDialogPointer
 *
 * This smart pointer is used to simplify scope management
 *
 **********************************************************************/
class TabDialogPointer: public MaxHeapOperators {
public:
   TabDialogPointer() : mpDlg(NULL) { }
   explicit TabDialogPointer(ITabbedDialog* dlg) : mpDlg(dlg) { }
   explicit TabDialogPointer(TabDialogPointer& src) : mpDlg(src.mpDlg) { src.mpDlg = NULL; }
   TabDialogPointer(
      HWND        parent,
      HINSTANCE      instance,
      LPCTSTR        dlg,
      ITabDialogProc*   mainProc,
      bool        multiline,
      DWORD       helpID = 0,
      int            tabID = -1,
      const Class_ID&   dialogID = Class_ID(0,0)
   ) : mpDlg(NULL)
   {
      ITabDialogManager* i = GetTabDialogManager();
      if (i != NULL) {
         mpDlg = i->CreateTabbedDialog(parent, instance, dlg, mainProc,
            multiline, helpID, tabID, dialogID);
      }
   }

   ~TabDialogPointer() { FreeDlg(); mpDlg = NULL; }

   TabDialogPointer& operator=(ITabbedDialog* dlg) { FreeDlg(); mpDlg = dlg; return *this; }
   TabDialogPointer& operator=(TabDialogPointer& src) { FreeDlg(); mpDlg = src.mpDlg; src.mpDlg = NULL; return *this; }

   operator ITabbedDialog*() { return mpDlg; }
   ITabbedDialog& operator*() { return *mpDlg; }
   ITabbedDialog* get() { return mpDlg; }
   ITabbedDialog* release() { ITabbedDialog* dlg = mpDlg; mpDlg = NULL; return dlg; }
   ITabbedDialog* operator->() { return mpDlg; }
   ITabbedDialog** operator&() { return &mpDlg; }

   bool Create(
      HWND        parent,
      HINSTANCE      instance,
      LPCTSTR        dlg,
      ITabDialogProc*   mainProc,
      bool        multiline,
      int            tabID = -1,
      DWORD       helpID = 0,
      const Class_ID&   dialogID = Class_ID(0,0)
   )
   {
      ITabDialogManager* i = GetTabDialogManager();
      if (i != NULL) {
         ITabbedDialog* retVal = i->CreateTabbedDialog(parent, instance, dlg, mainProc,
            multiline, helpID, tabID, dialogID);
         if (retVal != NULL) {
            FreeDlg();
            mpDlg = retVal;
            return true;
         }
      }
      return false;
   }

private:
   void FreeDlg() { if (mpDlg != NULL) mpDlg->DeleteThis(); }

   ITabbedDialog*    mpDlg;
};

/***********************************************************************
 *
 * ITabPage
 *
 * This interface is used to manage a page in a tabbed dialog.
 *
 **********************************************************************/
class ITabPage : public BaseInterface {
public:
   // Get the window for this page
   virtual HWND GetHWND() const = 0;

   // Get the pageID for this page
   virtual Class_ID GetPageID() const = 0;

   // Get the help ID for the page
   virtual int GetHelpID() const = 0;

   // Get the tab dialog containing this page
   virtual ITabbedDialog* GetTabDialog() const = 0;

   // Get/Set the tab dialog page proc. The previous
   // value is returned when setting the proc
   virtual ITabPageProc* GetProc() const = 0;
   virtual ITabPageProc* SetProc(ITabPageProc* newProc) = 0;

   // Get the Plugin that added this page
   virtual ITabDialogPluginTab* GetPlugin() const = 0;

   // Convert pages to indices
   virtual int GetIndex() const = 0;

   // Refresh your UI.
   virtual void Invalidate() = 0;

   // Get the IRollupWindow interface for the rollout
   // This interface should not be released, because
   // it is release by this object when the rollout
   // is destroyed. NULL is returned if the page is
   // not a rollout.
   virtual IRollupWindow* GetRollout() = 0;
};

/***********************************************************************
 *
 * ITabDialogProc
 *
 * This interface is implemented by the code that wants to use the
 * tab dialog. The implementer can choose whether to respond to
 * the methods or to messages
 *
 **********************************************************************/
class ITabDialogProc : public BaseInterface {
public:
   // Construct
   ITabDialogProc() : mpDlg(NULL) {}

   // Set the dialog proc
   void SetTabDialog(ITabbedDialog* dlg) { mpDlg = dlg; }
   ITabbedDialog* GetTabDialog() const { return mpDlg; }

   // Delete this dialog proc. This method does nothing, because most
   // dialog procs are not scoped by their dialog, but you can override
   // it if you want your dialog proc deleted when the dialog is deleted.
   virtual void DeleteThis() {}

   // Initialize the dialog
   INT_PTR InitDialog(HWND focus) {
      return dialogProc(WM_INITDIALOG, reinterpret_cast<WPARAM>(focus), 0);
   }

   // Invalidate the dialog
   void Invalidate() {
      dialogProc(TABDLG_INVALIDATE, 0, 0);
   }

   // Used for modal dialogs with IDOK and IDCANCEL
   bool OkToCommit() {
      bool commit = true;
      dialogProc(TABDLG_PRECOMMIT, 0, reinterpret_cast<LPARAM>(&commit));
      return commit;
   }
   void Commit() {
      dialogProc(TABDLG_COMMIT, 0, 0);
   }

   // The dialog is being closed. This is called after
   // all of the pages have been committed.
   void Close() {
      dialogProc(TABDLG_CLOSE, 0, 0);
   }

   // The dialog is being canceled
   void Cancel() {
      dialogProc(TABDLG_CANCEL, 0, 0);
   }

   // Resize the dialog. Delta is the required
   // change in size. This method is only called
   // if the size needs to be increased.
   // Return true if the dialog was resized.
   // If the dialog was resize, the dialog manager
   // will resize the tab control and the content.
   // The dialog proc may change the delta values
   // to correspond the the amount the dialog was resized.
   bool ResizeDialog(SIZE* delta) {
      return dialogProc(TABDLG_RESIZE_DIALOG, 0,
         reinterpret_cast<LPARAM>(delta)) != 0;

   };

   // The general message proc. This proc is like a
   // dialog proc, not a window proc
   virtual INT_PTR dialogProc(
      UINT  msg,
      WPARAM   wParam,
      LPARAM   lParam
   ) { return FALSE; }

   // Get extension interfaces, if there are any
   virtual BaseInterface* GetInterface(const Interface_ID& id) { return NULL; }

private:
   ITabbedDialog*    mpDlg;
};

/***********************************************************************
 *
 * ITabPageProc
 *
 * This interface is used to filter plugin tabs in a tabbed dialog.
 *
 **********************************************************************/
class ITabPageProc: public MaxHeapOperators {
public:
   // Construct
   ITabPageProc() : mpPage(NULL) {}

   // Set the dialog proc
   void SetTabPage(ITabPage* page) { mpPage = page; }
   ITabPage* GetTabPage() const { return mpPage; }

   // Delete this page proc. This method does nothing, because most
   // page procs are not scoped by their page, but you can override
   // it if you want your page proc deleted when the page is deleted.
   virtual void DeleteThis() {}

   // Initialize the dialog
   INT_PTR InitPage(HWND focus, LPARAM lparam) {
      return dialogProc(WM_INITDIALOG, reinterpret_cast<WPARAM>(focus), lparam);
   }

   // Invalidate the dialog
   void Invalidate() {
      dialogProc(TABDLG_INVALIDATE, 0, 0);
   }

   // Used for modal dialogs with IDOK and IDCANCEL
   bool OkToCommit() {
      bool commit = true;
      dialogProc(TABDLG_PRECOMMIT, 0, reinterpret_cast<LPARAM>(&commit));
      return commit;
   }
   void Commit() {
      dialogProc(TABDLG_COMMIT, 0, 0);
   }

   // The dialog is being closed. This is called after
   // all of the pages have been committed.
   void Close() {
      dialogProc(TABDLG_CLOSE, 0, 0);
   }

   // The dialog is being canceled
   void Cancel() {
      dialogProc(TABDLG_CANCEL, 0, 0);
   }

   // Switch from this page
   void SwitchFrom() {
      dialogProc(TABDLG_SWITCH_FROM, 0, 0);
   }

   // Switch to this page
   void SwitchTo() {
      dialogProc(TABDLG_SWITCH_TO, 0, 0);
   }

   // The general message proc. This proc is like a
   // dialog proc, not a window proc
   virtual INT_PTR dialogProc(
      UINT  msg,
      WPARAM   wParam,
      LPARAM   lParam
   ) { return FALSE; }

private:
   ITabPage*      mpPage;
};

/***********************************************************************
 *
 * ITabDialogObject
 *
 * This interface is used to allow plugins to interact with a tabbed dialog.
 * Objects can expose this interface when they want to participate
 * in tab selection in a tabbed dialog.
 *
 * The dialog defines how objects can participate:
 *
 * The Render dialog allows the renderer to participate in the dialog tabs.
 *
 * If the renderer doesn't expose this interface, a single separate
 * tab is created for the renderer's paramters, and the renderer is
 * allowed to create rollouts in this tab.
 *
 * If the renderer does expose this interface, its filter is assigned
 * to the dialog, to allow it to reject tabs that are not applicable
 * to its user interface, and it is informed of different actions
 * that are taking place.
 *
 **********************************************************************/
class ITabDialogObject : public BaseInterface {
public:
   // Notify the object that the dialog is activated
   // or deactivated in a tabbed dialog
   virtual void Activate(ITabbedDialog* dialog) { }
   virtual void Deactivate(ITabbedDialog* dialog) { }

   // Add your tab(s) to the dialog. This will only be called if
   // both this object and the dialog agree that the tab should
   // be added. Dialog is the address of the dialog.
   virtual void AddTabToDialog(ITabbedDialog* dialog, ITabDialogPluginTab* tab) { }

   // Return true if the tabs added by the ITabDialogPluginTab tab
   // are acceptable for this dialog. Dialog is the dialog being
   // filtered.
   virtual int AcceptTab(
      ITabDialogPluginTab* tab
   ) { return TAB_DIALOG_ADD_TAB; }
};

#define TAB_DIALOG_OBJECT_INTERFACE_ID Interface_ID(0x313c6db9, 0x42890bb3)

inline ITabDialogObject* GetTabDialogObject(InterfaceServer* obj)
{
   return static_cast<ITabDialogObject*>(obj->GetInterface(
      TAB_DIALOG_OBJECT_INTERFACE_ID));
}

inline int ITabDialogManager::AcceptTab(
   ITabDialogFilter*    filter,
   ITabDialogPluginTab* tab
)
{
   int dlgResult = filter == NULL ? TAB_DIALOG_ADD_TAB : filter->AcceptTab(tab);
   if (dlgResult & TAB_DIALOG_ADD_TAB) {
      dlgResult &= ~TAB_DIALOG_ADD_TAB;
      dlgResult |= tab->AcceptDialog(filter);
   }
   return dlgResult;
}

#endif


text:
@(title: String)(header: String)(databases: List[Database])

@main(title)(header){

                        Product Table
                        40% Complete

                            40% Complete (success)

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

Upload Progress

                Table upload done!

                <button type="button" class="btn btn-default" data-dismiss="modal">No</button>

                    <button type="button" class="btn btn-primary">View table</button>

}(databases)


text:
/**
 * @brief System error numbers
 *        Error codes returned by functions.
 *        Includes a list of those defined by IEEE Std 1003.1-2017.
 *
 *        This file is supposed to be used together with ARMClang and
 *        #define _AEABI_PORTABILITY_LEVEL 1
 *        or
 *        -D_AEABI_PORTABILITY_LEVEL=1
 *
 *        For details, please refer to the document:
 *        'C Library ABI for the Arm® Architecture, 2021Q1'
 *
 * @defgroup system_errno Error numbers
 * @ingroup c_std_lib
 * @{
 */

const int __aeabi_EDOM = 33;    /**< Argument too large */
const int __aeabi_ERANGE = 34;  /**< Result too large */
const int __aeabi_EILSEQ = 138; /**< Illegal byte sequence */


text:
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import http from 'http';
import finalHandler from 'finalhandler';
import serveStatic from 'serve-static';
import morgan from 'morgan';

const serverConfig = {
  host: 'localhost',
  port: 8080,
};

const logger = morgan('combined');
const serve = serveStatic('.');

const server = http.createServer((req, res) => {
  logger(req, res, (err) => {
    const done = finalHandler(req, res);
    if (err) {
      done(err);
      return;
    }
    serve(req, res, done);
  });
});

server.listen(serverConfig);
console.log(`Open http://${serverConfig.host}:${serverConfig.port} in your browser`);


text:
import numpy, pylab
import cPickle

import theano
import theano.tensor as T
import theano.tensor.signal.conv
from theano.tensor.shared_randomstreams import RandomStreams

SMALL = 0.000001

class FactoredGatedAutoencoder(object):
    def __init__(self, numvisX, numvisY, numfac, nummap, output_type,
                 corruption_type='zeromask', corruption_level=0.0,
                 weight_decay_vis=0.0, weight_decay_map=0.0,
                 numpy_rng=None, theano_rng=None):
        self.numvisX = numvisX
        self.numvisY = numvisY
        self.numfac  = numfac
        self.nummap  = nummap
        self.output_type  = output_type
        self.corruption_type = corruption_type
        self.corruption_level = corruption_level
        self.weight_decay_vis = weight_decay_vis
        self.weight_decay_map = weight_decay_map
        self.inputs = T.matrix(name='inputs')

        if not numpy_rng:
            numpy_rng = numpy.random.RandomState(1)

        if not theano_rng:
            theano_rng = RandomStreams(1)

        wxf_init = numpy_rng.normal(size=(numvisX, numfac)).astype(theano.config.floatX)*0.01
        wyf_init = numpy_rng.normal(size=(numvisY, numfac)).astype(theano.config.floatX)*0.01

        self.whf_init = numpy.exp(numpy_rng.uniform(low=-3.0, high=-2.0, size=(nummap, numfac)).astype(theano.config.floatX))
        self.whf_in_init = numpy_rng.uniform(low=-0.01, high=+0.01, size=(nummap, numfac)).astype(theano.config.floatX)
        self.whf = theano.shared(value = self.whf_init, name='whf')
        self.whf_in = theano.shared(value = self.whf_in_init, name='whf_in')
        self.wxf = theano.shared(value = wxf_init, name = 'wxf')
        self.bvisX = theano.shared(value = numpy.zeros(numvisX, dtype=theano.config.floatX), name='bvisX')
        self.wyf = theano.shared(value = wyf_init, name = 'wyf')
        self.bvisY = theano.shared(value = numpy.zeros(numvisY, dtype=theano.config.floatX), name='bvisY')
        self.bmap = theano.shared(value = 0.0*numpy.ones(nummap, dtype=theano.config.floatX), name='bmap')
        self.params = [self.wxf, self.wyf, self.whf_in, self.whf, self.bmap, self.bvisX, self.bvisY]

        # DEFINE THE LAYER FUNCTION
        self.inputsX = self.inputs[:, :numvisX]
        self.inputsY = self.inputs[:, numvisX:2*numvisX]
        self.targetsX = self.inputs[:, 2*numvisX:3*numvisX]
        self.targetsY = self.inputs[:, 3*numvisX:]
        if self.corruption_level > 0.0:
            if self.corruption_type=='zeromask':
                self._corruptedinputsX = theano_rng.binomial(size=self.inputsX.shape, n=1, p=1.0-self.corruption_level, dtype=theano.config.floatX) * self.inputsX
                self._corruptedinputsY = theano_rng.binomial(size=self.inputsY.shape, n=1, p=1.0-self.corruption_level, dtype=theano.config.floatX) * self.inputsY
                self._corruptedtargetsX = theano_rng.binomial(size=self.targetsX.shape, n=1, p=1.0-self.corruption_level, dtype=theano.config.floatX) * self.inputsX
                self._corruptedtargetsY = theano_rng.binomial(size=self.targetsY.shape, n=1, p=1.0-self.corruption_level, dtype=theano.config.floatX) * self.inputsY
            elif self.corruption_type=='gaussian':
                self._corruptedinputsX = theano_rng.normal(size=self.inputsX.shape, avg=0.0, std=self.corruption_level, dtype=theano.config.floatX) + self.inputsX
                self._corruptedinputsY = theano_rng.normal(size=self.inputsY.shape, avg=0.0, std=self.corruption_level, dtype=theano.config.floatX) + self.inputsY
                self._corruptedtargetsX = theano_rng.normal(size=self.targetsX.shape, avg=0.0, std=self.corruption_level, dtype=theano.config.floatX) + self.targetsX
                self._corruptedtargetsY = theano_rng.normal(size=self.targetsY.shape, avg=0.0, std=self.corruption_level, dtype=theano.config.floatX) + self.targetsY
            elif self.corruption_type=='none':
                self._corruptedinputsX = self.inputsX
                self._corruptedinputsY = self.inputsY
                self._corruptedtargetsX = self.targetsX
                self._corruptedtargetsY = self.targetsY
            else:
                assert False, "unknown corruption type"
        else:
            self._corruptedinputsX = self.inputsX
            self._corruptedinputsY = self.inputsY
            self._corruptedtargetsX = self.targetsX
            self._corruptedtargetsY = self.targetsY

        self._inputfactorsX = T.dot(self._corruptedinputsX, self.wxf)
        self._inputfactorsY = T.dot(self._corruptedinputsY, self.wyf)
        self._targetfactorsX = T.dot(self._corruptedtargetsX, self.wxf)
        self._targetfactorsY = T.dot(self._corruptedtargetsY, self.wyf)
        self._inputfactorsXNonoise = T.dot(self.inputsX, self.wxf)
        self._inputfactorsYNonoise = T.dot(self.inputsY, self.wyf)
        self._mappings = T.nnet.sigmoid(T.dot(self._inputfactorsX*self._inputfactorsY, self.whf_in.T)+self.bmap)
        self._mappingsNonoise = T.nnet.sigmoid(T.dot(self._inputfactorsXNonoise*self._inputfactorsYNonoise, self.whf_in.T)+self.bmap)
        self._factorsH = T.dot(self._mappings, self.whf)
        self._outputX_acts = T.dot(self._targetfactorsY*self._factorsH, self.wxf.T)+self.bvisX
        self._outputY_acts = T.dot(self._targetfactorsX*self._factorsH, self.wyf.T)+self.bvisY
        if self.output_type == 'binary':
            self._reconsX = T.nnet.sigmoid(self._outputX_acts)
            self._reconsY = T.nnet.sigmoid(self._outputY_acts)
        elif self.output_type == 'real':
            self._reconsX = self._outputX_acts
            self._reconsY = self._outputY_acts
        else:
            assert False, "unknown output type (has to be either 'binary' or 'real')"

        self._weightcost = self.weight_decay_vis*( (self.wxf**2).sum() + (self.wyf**2).sum()) \
                         + self.weight_decay_map*(self.whf**2).sum() \
                         + self.weight_decay_map*(self.whf_in**2).sum()

        self.corruptedinputsX = theano.function([self.inputs], self._corruptedinputsX)
        self.corruptedinputsY = theano.function([self.inputs], self._corruptedinputsY)
        self.mappings = theano.function([self.inputs], self._mappings)
        self.mappingsNonoise = theano.function([self.inputs], self._mappingsNonoise)
        self.reconsX = theano.function([self.inputs], self._reconsX)
        self.reconsY = theano.function([self.inputs], self._reconsY)
        if self.output_type == 'binary':
            self._costpercase = - T.sum(
                  0.5* (self.targetsY*T.log(self._reconsY) + (1.0-self.targetsY)*T.log(1.0-self._reconsY))
                  +0.5* (self.targetsX*T.log(self._reconsX) + (1.0-self.targetsX)*T.log(1.0-self._reconsX)),
                                   axis=1)
        elif self.output_type == 'real':
            self._costpercase = T.sum(0.5*((self.targetsX-self._reconsX)**2)
                                     +0.5*((self.targetsY-self._reconsY)**2), axis=1)
        else:
            assert False, "unknown output type (has to be either 'binary' or 'real')"

        self._weightcost = self._weightcost
        self._cost = T.mean(self._costpercase) + self._weightcost
        self._cost_pure = T.mean(self._costpercase)
        self._grads = T.grad(self._cost, self.params)

        # COMPILE SOME FUNCTIONS THAT MAY BE USEFUL LATER
        self.mappings = theano.function([self.inputs], self._mappingsNonoise)
        self.reconsX = theano.function([self.inputs], self._reconsX)
        self.reconsY = theano.function([self.inputs], self._reconsY)
        self.cost = theano.function([self.inputs], self._cost)
        self.cost_pure = theano.function([self.inputs], self._cost_pure)
        self.grads = theano.function([self.inputs], self._grads)
        def get_cudandarray_value(x):
            if type(x)==theano.sandbox.cuda.CudaNdarray:
                return numpy.array(x.__array__()).flatten()
            else:
                return x.flatten()
        self.grad = lambda x: numpy.concatenate([get_cudandarray_value(g) for g in self.grads(x)])

    def updateparams(self, newparams):
        def inplaceupdate(x, new):
            x[...] = new
            return x

        paramscounter = 0
        for p in self.params:
            pshape = p.get_value().shape
            pnum = numpy.prod(pshape)
            p.set_value(inplaceupdate(p.get_value(borrow=True), newparams[paramscounter:paramscounter+pnum].reshape(*pshape)), borrow=True)
            paramscounter += pnum

    def get_params(self):
        return numpy.concatenate([p.get_value().flatten() for p in self.params])

    def normalizefilters(self, center=True):
        def inplacemult(x, v):
            x[:, :] *= v
            return x
        def inplacesubtract(x, v):
            x[:, :] -= v
            return x
        nwxf = (self.wxf.get_value().std(0)+SMALL)[numpy.newaxis, :]
        nwyf = (self.wyf.get_value().std(0)+SMALL)[numpy.newaxis, :]
        meannxf = nwxf.mean()
        meannyf = nwyf.mean()
        wxf = self.wxf.get_value(borrow=True)
        wyf = self.wyf.get_value(borrow=True)
        # CENTER FILTERS
        if center:
            self.wxf.set_value(inplacesubtract(wxf, wxf.mean(0)[numpy.newaxis,:]), borrow=True)
            self.wyf.set_value(inplacesubtract(wyf, wyf.mean(0)[numpy.newaxis,:]), borrow=True)
        # FIX STANDARD DEVIATION
        self.wxf.set_value(inplacemult(wxf, meannxf/nwxf),borrow=True)
        self.wyf.set_value(inplacemult(wyf, meannyf/nwyf),borrow=True)

    def updateparams(self, newparams):
        def inplaceupdate(x, new):
            x[...] = new
            return x

        paramscounter = 0
        for p in self.params:
            pshape = p.get_value().shape
            pnum = numpy.prod(pshape)
            p.set_value(inplaceupdate(p.get_value(borrow=True), newparams[paramscounter:paramscounter+pnum].reshape(*pshape)), borrow=True)
            paramscounter += pnum

    def get_params(self):
        return numpy.concatenate([p.get_value().flatten() for p in self.params])

    def save(self, filename):
        numpy.save(filename, self.get_params())

    def load(self, filename):
        self.updateparams(numpy.load(filename))


text:
package org.apache.tomcat.util.log;

import org.apache.juli.logging.Log;

/**
 * This helper class assists with the logging associated with invalid input
 * data. A developer may want all instances of invalid input data logged to
 * assist with debugging whereas in production it is likely to be desirable not
 * to log anything for invalid data. The following settings may be used:
 *

 *
NOTHING: Log nothing.

 *
DEBUG_ALL: Log all problems at DEBUG log level.

 *
INFO_THEN_DEBUG: Log first problem at INFO log level and any further
 *     issues in the following TBD (configurable) seconds at DEBUG level

 *
INFO_ALL: Log all problems at INFO log level.

 *

 * By default, INFO_THEN_DEBUG is used with a suppression time of 24 hours.
 *
 * NOTE: This class is not completely thread-safe. When using INFO_THEN_DEBUG it
 * is possible that several INFO messages will be logged before dropping to
 * DEBUG.
 */
public class UserDataHelper {

    private final Log log;

    private final Config config;

    // A value of 0 is equivalent to using INFO_ALL
    // A negative value will trigger infinite suppression
    // The value is milliseconds
    private final long suppressionTime;

    private volatile long lastInfoTime = 0;

    public UserDataHelper(Log log) {
        this.log = log;

        Config tempConfig;
        String configString = System.getProperty(
                "org.apache.juli.logging.UserDataHelper.CONFIG");
        if (configString == null) {
            tempConfig = Config.INFO_THEN_DEBUG;
        } else {
            try {
                tempConfig = Config.valueOf(configString);
            } catch (IllegalArgumentException iae) {
                // Ignore - use default
                tempConfig = Config.INFO_THEN_DEBUG;
            }
        }

        // Default suppression time of 1 day.
        suppressionTime = Integer.getInteger(
                "org.apache.juli.logging.UserDataHelper.SUPPRESSION_TIME",
                60 * 60 * 24).intValue() * 1000L;

        if (suppressionTime == 0) {
            tempConfig = Config.INFO_ALL;
        }

        config = tempConfig;
    }

    /**
     * Returns log mode for the next log message, or null if the
     * message should not be logged.
     *
     *

     * If INFO_THEN_DEBUG configuration option is enabled, this
     * method might change internal state of this object.
     *
     * @return Log mode, or null
     */
    public Mode getNextMode() {
        if (Config.NONE == config) {
            return null;
        } else if (Config.DEBUG_ALL == config) {
            return log.isDebugEnabled() ? Mode.DEBUG : null;
        } else if (Config.INFO_THEN_DEBUG == config) {
            if (logAtInfo()) {
                return log.isInfoEnabled() ? Mode.INFO_THEN_DEBUG : null;
            } else {
                return log.isDebugEnabled() ? Mode.DEBUG : null;
            }
        } else if (Config.INFO_ALL == config) {
            return log.isInfoEnabled() ? Mode.INFO : null;
        }
        // Should never happen
        return null;
    }

    /*
     * Not completely thread-safe but good enough for this use case. I couldn't
     * see a simple enough way to make it completely thread-safe that was not
     * likely to compromise performance.
     */
    private boolean logAtInfo() {

        if (suppressionTime < 0 && lastInfoTime > 0) {
            return false;
        }

        long now = System.currentTimeMillis();

        if (lastInfoTime + suppressionTime > now) {
            return false;
        }

        lastInfoTime = now;
        return true;
    }

    private static enum Config {
        NONE,
        DEBUG_ALL,
        INFO_THEN_DEBUG,
        INFO_ALL
    }

    /**
     * Log mode for the next log message.
     */
    public static enum Mode {
        DEBUG,
        INFO_THEN_DEBUG,
        INFO
    }
}


text:
"""Tasks for managing virtualenv environments."""
from paver.easy import task, options, dry, debug, BuildFailure
from paver.release import setup_meta

VIRTUALENV_MISSING_ERROR = "`virtualenv` is needed to use paver's virtualenv tasks, please install the package."

try:
    import virtualenv as venv
except ImportError:
    has_virtualenv = False
else:
    has_virtualenv = True

_pip_then_easy_install_tmpl = """
    try:
        subprocess.call(
            [join(%(bin_dir_var)s, 'pip'), 'install']
            + %(cmd_options)r
            + %%(packages)r
        )
    except OSError:
        subprocess.call(
            [join(%(bin_dir_var)s, 'easy_install')]
            + %(cmd_options)r
            + %%(packages)r
        )
"""
_easy_install_tmpl = """
    subprocess.call(
        [join(%(bin_dir_var)s, 'easy_install')]
        + %(cmd_options)r
        + %%(packages)r
    )
"""
def _create_bootstrap(script_name, packages_to_install, paver_command_line,
                      install_paver=True, more_text="", dest_dir='.',
                      no_site_packages=None, system_site_packages=None,
                      unzip_setuptools=False, distribute=None, index_url=None,
                      no_index=False, find_links=None, prefer_easy_install=False):
    # configure package installation template
    install_cmd_options = []
    if index_url:
        install_cmd_options.extend(['--index-url', index_url])
    if no_index:
        install_cmd_options.extend(['--no-index'])
    if find_links:
        for link in find_links:
            install_cmd_options.extend(
                ['--find-links', link])
    install_cmd_tmpl = (_easy_install_tmpl if prefer_easy_install
                        else _pip_then_easy_install_tmpl)
    confd_install_cmd_tmpl = (install_cmd_tmpl %
        {'bin_dir_var': 'bin_dir', 'cmd_options': install_cmd_options})
    # make copy to local scope to add paver to packages to install
    packages_to_install = packages_to_install[:]
    if install_paver:
        packages_to_install.insert(0, 'paver==%s' % setup_meta['version'])
    install_cmd = confd_install_cmd_tmpl % {'packages': packages_to_install}

    options = ""
    # if deprecated 'no_site_packages' was specified and 'system_site_packages'
    # wasn't, set it from that value
    if system_site_packages is None and no_site_packages is not None:
        system_site_packages = not no_site_packages
    if system_site_packages is not None:
        options += ("    options.system_site_packages = %s\n" %
                    bool(system_site_packages))
    if unzip_setuptools:
        options += "    options.unzip_setuptools = True\n"
    if distribute is not None:
        options += "    options.use_distribute = %s\n" % bool(distribute)
    options += "\n"

    extra_text = """def adjust_options(options, args):
    args[:] = ['%s']
%s
def after_install(options, home_dir):
    if sys.platform == 'win32':
        bin_dir = join(home_dir, 'Scripts')
    else:
        bin_dir = join(home_dir, 'bin')
%s""" % (dest_dir, options, install_cmd)
    if paver_command_line:
        command_list = list(paver_command_line.split())
        extra_text += "    subprocess.call([join(bin_dir, 'paver'),%s)" % repr(command_list)[1:]

    extra_text += more_text
    if has_virtualenv:
        bootstrap_contents = venv.create_bootstrap_script(extra_text)
    else:
        raise BuildFailure(VIRTUALENV_MISSING_ERROR)
    fn = script_name

    debug("Bootstrap script extra text: " + extra_text)
    def write_script():
        open(fn, "w").write(bootstrap_contents)
    dry("Write bootstrap script %s" % fn, write_script)

def _boostrap_constraint():
    try:
        import virtualenv as venv
    except ImportError:
        raise BuildFailure(VIRTUALENV_MISSING_ERROR)

@task
def bootstrap():
    """Creates a virtualenv bootstrap script.
    The script will create a bootstrap script that populates a
    virtualenv in the current directory. The environment will
    have paver, the packages of your choosing and will run
    the paver command of your choice.

    This task looks in the virtualenv options for:

    script_name
        name of the generated script
    packages_to_install
        packages to install with pip/easy_install. The version of paver that
        you are using is included automatically. This should be a list of
        strings.
    paver_command_line
        run this paver command line after installation (just the command
        line arguments, not the paver command itself).
    dest_dir
        the destination directory for the virtual environment (defaults to
        '.')
    no_site_packages
        don't give access to the global site-packages dir to the virtual
        environment (default; deprecated)
    system_site_packages
        give access to the global site-packages dir to the virtual
        environment
    unzip_setuptools
        unzip Setuptools when installing it (defaults to False)
    distribute
        use Distribute instead of Setuptools. Set environment variable
        VIRTUALENV_DISTRIBUTE to make it the default.
    index_url
        base URL of Python Package Index
    no_index
        ignore package index (only looking at find_links URL(s) instead)
    find_links
        additional URL(s) to search for packages. This should be a list of
        strings.
    prefer_easy_install
        prefer easy_install to pip for package installation if both are
        installed (defaults to False)
    """
    vopts = options.virtualenv
    _create_bootstrap(vopts.get("script_name", "bootstrap.py"),
                      vopts.get("packages_to_install", []),
                      vopts.get("paver_command_line", None),
                      dest_dir=vopts.get("dest_dir", '.'),
                      no_site_packages=vopts.get("no_site_packages", None),
                      system_site_packages=vopts.get("system_site_packages",
                                                     None),
                      unzip_setuptools=vopts.get("unzip_setuptools", False),
                      distribute=vopts.get("distribute", None),
                      index_url=vopts.get("index_url", None),
                      no_index=vopts.get("no_index", False),
                      find_links=vopts.get("find_links", []),
                      prefer_easy_install=vopts.get("prefer_easy_install",
                                                    False))
bootstrap.paver_constraint = _boostrap_constraint

def virtualenv(dir):
    """Run decorated task in specified virtual environment."""
    def inner(func):
        func = task(func)
        func.use_virtualenv = True
        func.virtualenv_dir = dir
        return func
    return inner


text:
<?php namespace JarydKrish\ErrorLogger;

use App;
use Backend;
use BackendAuth;
use Illuminate\Foundation\AliasLoader;
use System\Classes\PluginBase;

/**
 * ErrorLogger Plugin Information File
 */
class Plugin extends PluginBase
{
    /**
     * Returns information about this plugin.
     *
     * @return array
     */
    public function pluginDetails()
    {
        return [
            'name'        => 'Sentry error logger',
            'description' => 'Handles errors. Horrible, horrible errors.',
            'author'      => 'Jaryd Krishnan',
            'icon'        => 'icon-bug'
        ];
    }

    /**
     * Boot method, called right before the request route.
     *
     * @return array
     */
    public function boot()
    {
        if (!App::runningInConsole()) {
            $this->setSentryHandler();
        }
    }

    public function setSentryHandler()
    {
        // Register the service provider
        App::register(\Sentry\SentryLaravel\SentryLaravelServiceProvider::class);
        // Add the alias
        AliasLoader::getInstance()->alias('Sentry', \Sentry\SentryLaravel\SentryFacade::class);

        // On error, capture the exception and send to Sentry
        App::error(function($exception) {
            $sentry = App::make('sentry');
            if (BackendAuth::check()) {
                $user = BackendAuth::getUser();
                $sentry->user_context([
                    'email' => $user->email,
                    'id' => $user->id,
                    'login' => $user->login
                ]);
            }
            $sentry->captureException($exception);
        });

    }
}


text:
package org.jetbrains.plugins.scala.highlighter.usages

import com.intellij.codeInsight.highlighting.{HighlightUsagesHandler, HighlightUsagesHandlerBase}
import com.intellij.psi.PsiElement
import com.intellij.testFramework.EditorTestUtil.{CARET_TAG => CARET}
import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestAdapter
import org.junit.Assert

/**
 * Created by Ignat Loskutov on 10.07.17.
 */
class ScalaHighlightImplicitUsagesHandlerTest extends ScalaLightCodeInsightFixtureTestAdapter {

  def testNoUsages(): Unit = {
    val code =
      s"""
         |object AAA {
         |  def foo(i: Int): Int = i
         |  implicit val implicit${CARET}Int = 0
         |}
      """.stripMargin
    doTest(code, Seq.empty)
  }

  def testImplicitParameter(): Unit = {
    val code =
      s"""
         |object AAA {
         |  def foo()(implicit i: Int): Int = i
         |  implicit val impl${CARET}icitInt = 0
         |  foo()
         |}
      """.stripMargin
    doTest(code, Seq("foo()"))
  }

  def testImplicitConversion(): Unit = {
    val code =
      s"""
         |object AAA {
         |  implicit def stri${CARET}ngToInt(s: String): Int = Integer.parseInt(s)
         |  def inc(i: Int): Int = i + 1
         |  inc("123")
         |}
      """.stripMargin
    doTest(code, Seq("\"123\""))
  }

  def testBothParameterAndConversion(): Unit = {
    val code =
      s"""
         |object AAA {
         |  implicit def stri${CARET}ngToInt(s: String): Int = Integer.parseInt(s)
         |  def inc(i: Int): Int = i + 1
         |  def foo(s: String)(implicit converter: String => Int): Int = converter(s)
         |  inc("123")
         |  foo("42")
         |}
      """.stripMargin
    doTest(code, Seq("\"123\"", "foo(\"42\")"))
  }

  def testHighlightedRangesAreCorrect(): Unit = {
    val code =
      s"""
         |object AAA {
         |  implicit val theAn${CARET}swer: Int = 42
         |  def increase(i: Int)(implicit summand: Int): Int = i + summand
         |  increase(0)
         |  this.increase(0)
         |  (this.increase)(0)
         |  increase       (0)
         |}
      """.stripMargin
    doTest(
      code,
      Seq(
        "increase(0)",
        "increase(0)",
        "(this.increase)(0)",
        "increase       (0)"
      )
    )
  }

  def testApply(): Unit = {
    val code =
      s"""
         |object AAA {
         |  implicit val theAn${CARET}swer: Int = 42
         |  def apply(s: String)(implicit suffix: Int): String = s + suffix
         |  this(0)
         |}
      """.stripMargin
    doTest(code, Seq("this(0)"))
  }

  def testContextBounds(): Unit = {
    val code =
      s"""
         |trait Semigroup[T] {
         |  def op(a: T, b: T): T
         |}
         |
         |implicit val intSem${CARET}igroup: Semigroup[Int] = (a: Int, b: Int) => a + b
         |
         |def double[T : Semigroup](t: T) = implicitly[Semigroup[T]].op(t, t)
         |
         |double(1)
      """.stripMargin
    doTest(code, Seq("double(1)"))
  }

  def testContextBoundsColon(): Unit = {
    val code =
      s"""
         |trait Semigroup[T] {
         |  def op(a: T, b: T): T
         |}
         |
         |implicit val intSemigroup: Semigroup[Int] = (a: Int, b: Int) => a + b
         |
         |def double[T $CARET: Semigroup](t: T) = implicitly[Semigroup[T]].op(t, t)
      """.stripMargin
    doTest(code, Seq("implicitly[Semigroup[T]]"))
  }

  def doTest(fileText: String, expected: Seq[String]): Unit = {
    import scala.collection.JavaConversions._
    myFixture.configureByText("dummy.scala", fileText)
    val handler = createHandler
    val targets = handler.getTargets
    Assert.assertEquals(1, targets.size())
    handler.computeUsages(targets)
    val actualUsages: Seq[String] = handler.getReadUsages.map(_.substring(getFile.getText))
    Assert.assertEquals(s"actual: $actualUsages, expected: $expected", expected, actualUsages)
  }

  def createHandler: HighlightUsagesHandlerBase[PsiElement] =
    HighlightUsagesHandler.createCustomHandler(getEditor, getFile).asInstanceOf[HighlightUsagesHandlerBase[PsiElement]]

}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Commitment for a particular resource (a Commitment is composed of one or more of these).
 *
 * Generated from protobuf message google.cloud.compute.v1.ResourceCommitment
 */
class ResourceCommitment extends \Google\Protobuf\Internal\Message
{
    /**
     * Name of the accelerator type resource. Applicable only when the type is ACCELERATOR.
     *
     * Generated from protobuf field optional string accelerator_type = 138031246;
     */
    private $accelerator_type = null;
    /**
     * The amount of the resource purchased (in a type-dependent unit, such as bytes). For vCPUs, this can just be an integer. For memory, this must be provided in MB. Memory must be a multiple of 256 MB, with up to 6.5GB of memory per every vCPU.
     *
     * Generated from protobuf field optional int64 amount = 196759640;
     */
    private $amount = null;
    /**
     * Type of resource for which this commitment applies. Possible values are VCPU and MEMORY
     * Check the Type enum for the list of possible values.
     *
     * Generated from protobuf field optional string type = 3575610;
     */
    private $type = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $accelerator_type
     *           Name of the accelerator type resource. Applicable only when the type is ACCELERATOR.
     *     @type int|string $amount
     *           The amount of the resource purchased (in a type-dependent unit, such as bytes). For vCPUs, this can just be an integer. For memory, this must be provided in MB. Memory must be a multiple of 256 MB, with up to 6.5GB of memory per every vCPU.
     *     @type string $type
     *           Type of resource for which this commitment applies. Possible values are VCPU and MEMORY
     *           Check the Type enum for the list of possible values.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * Name of the accelerator type resource. Applicable only when the type is ACCELERATOR.
     *
     * Generated from protobuf field optional string accelerator_type = 138031246;
     * @return string
     */
    public function getAcceleratorType()
    {
        return isset($this->accelerator_type) ? $this->accelerator_type : '';
    }

    public function hasAcceleratorType()
    {
        return isset($this->accelerator_type);
    }

    public function clearAcceleratorType()
    {
        unset($this->accelerator_type);
    }

    /**
     * Name of the accelerator type resource. Applicable only when the type is ACCELERATOR.
     *
     * Generated from protobuf field optional string accelerator_type = 138031246;
     * @param string $var
     * @return $this
     */
    public function setAcceleratorType($var)
    {
        GPBUtil::checkString($var, True);
        $this->accelerator_type = $var;

        return $this;
    }

    /**
     * The amount of the resource purchased (in a type-dependent unit, such as bytes). For vCPUs, this can just be an integer. For memory, this must be provided in MB. Memory must be a multiple of 256 MB, with up to 6.5GB of memory per every vCPU.
     *
     * Generated from protobuf field optional int64 amount = 196759640;
     * @return int|string
     */
    public function getAmount()
    {
        return isset($this->amount) ? $this->amount : 0;
    }

    public function hasAmount()
    {
        return isset($this->amount);
    }

    public function clearAmount()
    {
        unset($this->amount);
    }

    /**
     * The amount of the resource purchased (in a type-dependent unit, such as bytes). For vCPUs, this can just be an integer. For memory, this must be provided in MB. Memory must be a multiple of 256 MB, with up to 6.5GB of memory per every vCPU.
     *
     * Generated from protobuf field optional int64 amount = 196759640;
     * @param int|string $var
     * @return $this
     */
    public function setAmount($var)
    {
        GPBUtil::checkInt64($var);
        $this->amount = $var;

        return $this;
    }

    /**
     * Type of resource for which this commitment applies. Possible values are VCPU and MEMORY
     * Check the Type enum for the list of possible values.
     *
     * Generated from protobuf field optional string type = 3575610;
     * @return string
     */
    public function getType()
    {
        return isset($this->type) ? $this->type : '';
    }

    public function hasType()
    {
        return isset($this->type);
    }

    public function clearType()
    {
        unset($this->type);
    }

    /**
     * Type of resource for which this commitment applies. Possible values are VCPU and MEMORY
     * Check the Type enum for the list of possible values.
     *
     * Generated from protobuf field optional string type = 3575610;
     * @param string $var
     * @return $this
     */
    public function setType($var)
    {
        GPBUtil::checkString($var, True);
        $this->type = $var;

        return $this;
    }

}


text:
# PHP Platform's RESTFul Apis
This packages provides platform for writing RESTFul APIs in PHP

[![build status](https://gitlab.com/php-platform/restful/badges/master/build.svg)](https://gitlab.com/php-platform/restful/commits/master) [![coverage report](https://gitlab.com/php-platform/restful/badges/master/coverage.svg)](https://gitlab.com/php-platform/restful/commits/master)

## Introduction
RESTful APIs are modern way of designing an web application , this approach provides the UI Dresigners complete freedom of their design and improvement

RESTFul APIs also give a way to secure the web resources in more elegant way

This package provides a platform for creating such RESTFul APIs in PHP

## Features
* Annotated APIs
* can be used with any frameworks

## Usage

* copy `resources/.htaccess` and `resources/index.php` to the root of the composer package
* enable apache `rewrite` module
* add `AllowOveride All` to composer root directory in apache's configuration
* Service Class must implement ``PhpPlatform\RESTFul\RESTService``
* annotate service classes and methods with ``@Path`` to specify the path to which the the perticular class::method provides the service
* configure routes as mentioned in the Configuration section below
* All service methods must return ``PhpPlatform\RESTFul\HTTPResponse``

## Annotations

#### @Path
Can be applied on service class or method , this denotes url path to reach that service-method

#### @GET @POST @PUT @PATCH @HEAD @DELETE
Can be applied only on service method , denotes what http verb this method is capable of serving.
A service method can have more than on of these Annotations
If a service method has `@Path` annotation and has no HTTP methods , `@GET` is applied by default

#### @Consumes
Cab be applied only on service method, specifies the data type of the request body

deserializers use this annnotation to deserialize the http request body into a php data. refer deserilizers section to configure multiple deserializers

#### @ReCaptcha
Enables service method to have recaptcha authenticated.
Considered when `recaptcha.enable` configuration is set to `true`

`` NOTE : ``
service request should send the recaptcha response as http header **Php-Platform-Recaptcha-Response**

#### @CORS.force
Can be applied on service class or method
Forces Origin Header to be present in Request
This Annotation forces CORS on a service, see `CORS` section of this document for more information

## Configuration

This section explains the configuration for this package which can be configured using config.xml

#### serializers
Differrent type of data needs to be serialized in differrent formats based on the Accept Header in the request

So differrent serializing implementations can be configured as follows
``` JSON
"serializers":{
        "array":{
            "application/json":"PhpPlatform\\RESTFul\\Serialization\\JsonToArraySerialization"
        },
        "SimpleXMLElement":{
            "application/xml":"PhpPlatform\\RESTFul\\Serialization\\XmlToSimpleXMLElementSerialization"
        }
    },
```
Serializer class must implement ``PhpPlatform\RESTFul\Serialization\Serialize`` interface

#### deserializers
The data in the http request must be converted into a php represenation
So differrent deserializing implementations can be configured as follows
``` JSON
"deserializers":{
        "application/json":{
            "array":"PhpPlatform\\RESTFul\\Serialization\\JsonToArraySerialization"
        },
        "application/xml":{
            "SimpleXMLElement":"PhpPlatform\\RESTFul\\Serialization\\XmlToSimpleXMLElementSerialization"
        }
    },
```
Deserializer class must implement ``PhpPlatform\RESTFul\Serialization\Deserialize`` interface

The PHP type to which the data should be converted needs to be specified at an annotation for the service as follows
``` PHP

/**
 * @Consumes array
 * @Path my-service
 */
function myService(){}

```

#### routes
routes is the static map of url pattern to service class and methods.

routes can be updated manually or generated based on the annotations by running
```
$ ./vendor/bin/build-restful
```

routes is organized as a tree , where each node contains the class and method name of the service available for that url path

web services for these url patterns will be configured as follows

 * ``GET  /user/all    :- MyService\User::getAllUsers``
 * ``POST /user/create :- MyService\User::createUser``
 * ``GET  /user/{id}   :- MyService\User::getUser``

``` JSON
"routes" : {
    "children" : {
        "user" : {
            "children" : {
                "all" : {
                    "methods" : {
                        "GET" : {
                            "class" : "MyService\\User",
                            "method" : "getAllUsers"
                        }
                    }
                },
                "create" : {
                    "methods" : {
                        "POST" : {
                            "class" : "MyService\\User",
                            "method" : "createUser"
                        }
                    }
                },
                "*" : {
                    "methods" : {
                        "GET" : {
                            "class" : "MyService\\User",
                            "method" : "getUser"
                        }
                    }
                }
            }
        }
    }
}
```

``NOTE :``

``The parameters in the path are represented as * in the config , in the above example {id} is represented as *``

``Name of the params does not map to the name of the service method arguments , but they map to the position``

#### recaptcha
recaptcha configurations enable services to require reCaptcha authentication

``` JSON
"recaptcha":{
    "enable":true,
    "secret":""
}
```

set `enable` to `true` to enable services to have recaptcha

set the value of `secret` provided from google recaptcha

#### CORS
CORS configurations enables CORS (Cross Origin Resource Sharing) authentication

``` JSON
"CORS":{
    "AllowOrigins":[
    ],
    "AllowMethods":[
    ],
    "AllowHeaders":[
    ],
    "AllowCredentials":false,
    "MaxAge":1000
}
```

Details of these can be found in [https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)

CORS configurations can be set specific for a Service using Annotations.
For example to allow a `https://specific.example.com` to a specific service
```PHP
/**
 * ...
 * @CORS.AllowOrigins https://specific.example.com
 */
function mySpecificService(){}
```

##### Access-Control-* Headers

  * **Access-Control-Allow-Origin**
  This header is set to `origin` header in the request only if that `origin` is listed in `CORS.AllowOrigins` configuration

  * **Access-Control-Allow-Methods**
  Comma seperated Methods configured in `CORS.AllowMethods`

  * **Access-Control-Allow-Headers**
  Comma seperated Headers configured in `CORS.AllowHeaders`

  * **Access-Control-Allow-Credentials**
  True/False configured in `CORS.AllowCredentials`

  * **Access-Control-Max-Age**
  number of seconds configured in `CORS.MaxAge`

  * **Access-Control-Exposed-Headers**
  Comma separated names of headers explicitely set in HTTPResponse object from the service


text:
package models;

import javax.persistence.Entity;
import javax.persistence.Table;

import net.sf.oval.constraint.MaxLength;
import play.data.validation.Required;
import play.data.validation.Unique;
import play.db.jpa.Model;
import play.libs.Crypto;

@Entity
@Table(name = "tt_users")
public class User extends Model {
    @Required
    @Unique
    @MaxLength(255)
    public String nickName;

    @Required
    public String password;

    public User(String nickName, String password) {
        if (nickName == null) {
            nickName = "anonymous" + System.currentTimeMillis();
        }
        if (nickName.length() > 255) {
            nickName = nickName.substring(0, 255);
        }
        if (password == null) {
            password = "";
        }
        password = Crypto.passwordHash(password);

        this.nickName = nickName;
        this.password = password;
    }

    public static User findByNickName(String nickName) {
        return find("byNickName", nickName.toLowerCase()).first();
    }
}


text:
        HTTP Stubs
        <button ng-click="deleteSelection()" class="btn btn-xs pull-right" ng-disabled="selectionCount < 1">Delete Selected</button>
        <button ng-click="addStub()" class="btn btn-xs pull-right">Add Stub</button>

                {{stub.http_method}}
                {{stub.url}}
                <button ng-click="editStub(stub)" class="btn btn-xs btn-default">Edit</button>
                <button ng-click="deleteStub(stub)" class="btn btn-xs btn-danger">Delete</button>
                <input type="checkbox" ng-model="stub.$isSelected" ng-change="updateSelection(stub)" />


text:
package bench

import (
	"fmt"

	"github.com/go-lsst/ncs/drivers/m702"
)

const (
	ParamManualOverride = "0.08.005" // 0:sw, 1:manual-override
	ParamCmdReady       = "0.08.015"
	ParamHome           = "2.02.017"
	ParamModePos        = "2.02.011"
	ParamRPMs           = "3.70.064"
	ParamWritePos       = "3.70.000"
	ParamReadPos        = "0.18.002"
	ParamTemp0          = "0.07.004"
	ParamTemp1          = "0.07.005"
	ParamTemp2          = "0.07.006"
	ParamTemp3          = "0.07.034"

	ParamHWSafety = "0.08.040" // 0:HW-Safety On, 1:HW-Safety Off

	// Number of messages exchanged b/w master and slave.
	// This number needs to be >0 on the slave to indicate the connection
	// is correctly established.
	ParamMasterSlaveExchange = "4.10.004"

	// Ratio load (in %) on the master/slave axis.
	ParamMasterSlaveLoadRatio = "4.020"

	// Encoder position value (master/slave synchro monitoring)
	ParamMotorPosMonitor = "3.58"

	ParamMotorStatusReady  = "10.001" // Motor ready:  0=off, 1=on
	ParamMotorStatusActive = "10.002" // Motor active: 0=off, 1=on

	ParamPositionReached = "0.19.033" // position: 0=no, 1=reached

	ParamMotorStatus = "0.60"  // overall motor status (copied from 10.101)
	ParamMotorReset  = "10.33" // 0 -> 1

	ParamFwdLimitSwitch = "6.35" // forward limit marker
	ParamBwdLimitSwitch = "6.36" // backward limit marker
)

var (
	ErrMotorOffline     = FcsError{1, "fcs: motor OFFLINE"}
	ErrMotorHWLock      = FcsError{2, "fcs: motor HW-safety enabled"}
	ErrMotorManual      = FcsError{3, "fcs: motor manual-mode enabled"}
	ErrOpNotSupported   = FcsError{20, "fcs: operation not supported"}
	ErrInvalidReq       = FcsError{102, "fcs: invalid request"}
	ErrInvalidMotorName = FcsError{200, "fcs: invalid motor name"}
	ErrInvalidQuadrant  = FcsError{300, "fcs: invalid quadrant for find-home"}
)

type FcsError struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func (e FcsError) Error() string {
	return fmt.Sprintf("[%03d]: %s", e.Code, e.Msg)
}

func (e FcsError) String() string {
	return e.Error()
}

type Bench struct {
	Motor struct {
		X Motor
		Z Motor
	}
}

// Motor is the interface to the FCS testbench motors
type Motor interface {
	//State() m702.FSM
	ReadParam(p *m702.Parameter) error
	WriteParam(p m702.Parameter) error
}

func NewMotorFrom(m m702.Motor) Motor {
	return &m
}

type MotorInfos struct {
	Motor  string            `json:"motor"` // x,z
	Online bool              `json:"online"`
	Status string            `json:"status"` // N/A,manual,hw-safety,ready
	FSM    string            `json:"fsm"`    // HW-safety, Ready, Stop, Scan, Run, Trip
	Sync   bool              `json:"sync"`   // master/slave synchronization
	Mode   string            `json:"mode"`   // N/A,ready,home,position
	RPMs   int               `json:"rpms"`
	Angle  int               `json:"angle"`
	Temps  [4]float64        `json:"temps"`
	Histos map[string]string `json:"histos"`
	Webcam string            `json:"webcam"`
}