text:
package org.apache.camel.component.irc;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.camel.RuntimeCamelException;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriParams;
import org.apache.camel.spi.UriPath;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
import org.apache.camel.util.jsse.SSLContextParameters;
import org.schwering.irc.lib.ssl.SSLDefaultTrustManager;
import org.schwering.irc.lib.ssl.SSLTrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@UriParams
public class IrcConfiguration implements Cloneable {
    private static final Logger LOG = LoggerFactory.getLogger(IrcConfiguration.class);

    private List<IrcChannel> channels = new ArrayList<IrcChannel>();
    @UriPath @Metadata(required = "true")
    private String hostname;
    @UriPath(defaultValue = "6667,6668,6669")
    private int port;
    private int[] ports = {6667, 6668, 6669};
    @UriParam
    private String password;
    @UriParam
    private String nickname;
    @UriParam
    private String realname;
    @UriParam
    private String username;
    private SSLTrustManager trustManager = new SSLDefaultTrustManager();
    private boolean usingSSL;
    @UriParam(defaultValue = "true")
    private boolean persistent = true;
    @UriParam(defaultValue = "true")
    private boolean colors = true;
    @UriParam(defaultValue = "true")
    private boolean onNick = true;
    @UriParam(defaultValue = "true")
    private boolean onQuit = true;
    @UriParam(defaultValue = "true")
    private boolean onJoin = true;
    @UriParam(defaultValue = "true")
    private boolean onKick = true;
    @UriParam(defaultValue = "true")
    private boolean onMode = true;
    @UriParam(defaultValue = "true")
    private boolean onPart = true;
    @UriParam
    private boolean onReply;
    @UriParam(defaultValue = "true")
    private boolean onTopic = true;
    @UriParam(defaultValue = "true")
    private boolean onPrivmsg = true;
    @UriParam(defaultValue = "true")
    private boolean autoRejoin = true;
    private SSLContextParameters sslContextParameters;

    public IrcConfiguration() {
    }

    public IrcConfiguration(String hostname, String nickname, String displayname, List<IrcChannel> channels) {
        this(hostname, null, null, nickname, displayname, channels);
    }

    public IrcConfiguration(String hostname, String username, String password, String nickname, String displayname, List<IrcChannel> channels) {
        this.channels = channels;
        this.hostname = hostname;
        this.username = username;
        this.password = password;
        this.nickname = nickname;
        this.realname = displayname;
    }

    public IrcConfiguration copy() {
        try {
            return (IrcConfiguration) clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeCamelException(e);
        }
    }

    public String getCacheKey() {
        return hostname + ":" + nickname;
    }

    /*
     * Return space separated list of channel names without pwd
     */
    public String getListOfChannels() {
        String retval = "";
        for (IrcChannel channel : channels) {
            retval += (retval.isEmpty() ? "" : " ") + channel.getName();
        }
        return retval;
    }

    public void configure(String uriStr) throws URISyntaxException, UnsupportedEncodingException  {
        // fix provided URI and handle that we can use # to indicate the IRC room
        if (uriStr.startsWith("ircs")) {
            setUsingSSL(true);
            if (!uriStr.startsWith("ircs://")) {
                uriStr = uriStr.replace("ircs:", "ircs://");
            }
        } else if (!uriStr.startsWith("irc://")) {
            uriStr = uriStr.replace("irc:", "irc://");
        }

        if (uriStr.contains("?")) {
            uriStr = ObjectHelper.before(uriStr, "?");
        }

        URI uri = new URI(uriStr);

        // Because we can get a "sanitized" URI, we need to deal with the situation where the
        // user info includes the username and password together or else we get a mangled username
        // that includes the user's secret being sent to the server.
        String userInfo = uri.getUserInfo();
        String username = null;
        String password = null;
        if (userInfo != null) {
            int colonIndex = userInfo.indexOf(":");
            if (colonIndex != -1) {
                username = userInfo.substring(0, colonIndex);
                password = userInfo.substring(colonIndex + 1);
            } else {
                username = userInfo;
            }
        }

        if (uri.getPort() != -1) {
            setPorts(new int[] {uri.getPort()});
            setPort(uri.getPort());
        }

        setNickname(username);
        setUsername(username);
        setRealname(username);
        setPassword(password);
        setHostname(uri.getHost());

        String path = uri.getPath();
        if (path != null && !path.isEmpty()) {
            LOG.warn("Channel {} should not be specified in the URI path. Use an @channel query parameter instead.", path);
        }
    }

    public void setChannel(String channel) {
        channels.add(createChannel(channel));
    }

    public void setChannel(List<String> channels) {
        for (String ci : channels) {
            this.channels.add(createChannel(ci));
        }
    }

    public List<IrcChannel> getChannels() {
        return channels;
    }

    public IrcChannel findChannel(String name) {
        for (IrcChannel channel : channels) {
            if (channel.getName().equals(name)) {
                return channel;
            }
        }
        return null;
    }

    /**
     * The trust manager used to verify the SSL server's certificate.
     */
    public void setTrustManager(SSLTrustManager trustManager) {
        this.trustManager = trustManager;
    }

    public SSLTrustManager getTrustManager() {
        return trustManager;
    }

    public boolean getUsingSSL() {
        return usingSSL;
    }

    private void setUsingSSL(boolean usingSSL) {
        this.usingSSL = usingSSL;
    }

    public String getHostname() {
        return hostname;
    }

    /**
     * Hostname for the IRC chat server
     */
    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public String getPassword() {
        return password;
    }

    /**
     * The IRC server password.
     */
    public void setPassword(String password) {
        this.password = password;
    }

    public String getNickname() {
        return nickname;
    }

    /**
     * The nickname used in chat.
     */
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getRealname() {
        return realname;
    }

    /**
     * The IRC user's actual name.
     */
    public void setRealname(String realname) {
        this.realname = realname;
    }

    public String getUsername() {
        return username;
    }

    /**
     * The IRC server user name.
     */
    public void setUsername(String username) {
        this.username = username;
    }

    public int[] getPorts() {
        return ports;
    }

    /**
     * Port numbers for the IRC chat server
     */
    public void setPorts(int[] ports) {
        this.ports = ports;
    }

    public int getPort() {
        return port;
    }

    /**
     * Port number for the IRC chat server
     */
    public void setPort(int port) {
        this.port = port;
    }

    public boolean isPersistent() {
        return persistent;
    }

    /**
     * Use persistent messages.
     * @deprecated not in use
     */
    @Deprecated
    public void setPersistent(boolean persistent) {
        this.persistent = persistent;
    }

    public boolean isColors() {
        return colors;
    }

    /**
     * Whether or not the server supports color codes.
     */
    public void setColors(boolean colors) {
        this.colors = colors;
    }

    public boolean isOnNick() {
        return onNick;
    }

    /**
     * Handle nickname change events.
     */
    public void setOnNick(boolean onNick) {
        this.onNick = onNick;
    }

    public boolean isOnQuit() {
        return onQuit;
    }

    /**
     * Handle user quit events.
     */
    public void setOnQuit(boolean onQuit) {
        this.onQuit = onQuit;
    }

    public boolean isOnJoin() {
        return onJoin;
    }

    /**
     * Handle user join events.
     */
    public void setOnJoin(boolean onJoin) {
        this.onJoin = onJoin;
    }

    public boolean isOnKick() {
        return onKick;
    }

    /**
     * Handle kick events.
     */
    public void setOnKick(boolean onKick) {
        this.onKick = onKick;
    }

    public boolean isOnMode() {
        return onMode;
    }

    /**
     * Handle mode change events.
     */
    public void setOnMode(boolean onMode) {
        this.onMode = onMode;
    }

    public boolean isOnPart() {
        return onPart;
    }

    /**
     * Handle user part events.
     */
    public void setOnPart(boolean onPart) {
        this.onPart = onPart;
    }

    public boolean isOnReply() {
        return onReply;
    }

    /**
     * Whether or not to handle general responses to commands or informational messages.
     */
    public void setOnReply(boolean onReply) {
        this.onReply = onReply;
    }

    public boolean isOnTopic() {
        return onTopic;
    }

    /**
     * Handle topic change events.
     */
    public void setOnTopic(boolean onTopic) {
        this.onTopic = onTopic;
    }

    public boolean isOnPrivmsg() {
        return onPrivmsg;
    }

    /**
     * Handle private message events.
     */
    public void setOnPrivmsg(boolean onPrivmsg) {
        this.onPrivmsg = onPrivmsg;
    }

    public boolean isAutoRejoin() {
        return autoRejoin;
    }

    /**
     * Whether to auto re-join when being kicked
     */
    public void setAutoRejoin(boolean autoRejoin) {
        this.autoRejoin = autoRejoin;
    }

    public SSLContextParameters getSslContextParameters() {
        return sslContextParameters;
    }

    /**
     * Used for configuring security using SSL.
     * Reference to a org.apache.camel.util.jsse.SSLContextParameters in the Registry.
     * This reference overrides any configured SSLContextParameters at the component level.
     * Note that this setting overrides the trustManager option.
     */
    public void setSslContextParameters(SSLContextParameters sslContextParameters) {
        this.sslContextParameters = sslContextParameters;
    }

    public String toString() {
        return "IrcConfiguration[hostname: " + hostname + ", ports=" + Arrays.toString(ports) + ", username=" + username + "]";
    }

    private static IrcChannel createChannel(String channelInfo) {
        String[] pair = channelInfo.split("!");
        return new IrcChannel(pair[0], pair.length > 1 ? pair[1] : null);
    }

    @Deprecated
    public static String sanitize(String uri) {
        // may be removed in camel-3.0.0
        // make sure it's an URL first
        int colon = uri.indexOf(':');
        if (colon != -1 && uri.indexOf("://") != colon) {
            uri = uri.substring(0, colon) + "://" + uri.substring(colon + 1);
        }

        try {
            URI u = new URI(UnsafeUriCharactersEncoder.encode(uri));
            String[] userInfo = u.getUserInfo() != null ? u.getUserInfo().split(":") : null;
            String username = userInfo != null ? userInfo[0] : null;
            String password = userInfo != null && userInfo.length > 1 ? userInfo[1] : null;

            String path = URLDecoder.decode(u.getPath() != null ? u.getPath() : "", "UTF-8");
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            if (path.startsWith("#") && !path.startsWith("##")) {
                path = path.substring(1);
            }

            Map<String, Object> parameters = URISupport.parseParameters(u);
            String user = (String)parameters.get("username");
            String nick = (String)parameters.get("nickname");
            // not specified in authority
            if (user != null) {
                if (username == null) {
                    username = user;
                } else if (!username.equals(user)) {
                    LOG.warn("Username specified twice in endpoint URI with different values. "
                        + "The userInfo value ('{}') will be used, paramter ('{}') ignored", username, user);
                }
                parameters.remove("username");
            }
            if (nick != null) {
                if (username == null) {
                    username = nick;
                }
                if (username.equals(nick)) {
                    parameters.remove("nickname");      // redundant
                }
            }
            if (username == null) {
                throw new RuntimeCamelException("IrcEndpoint URI with no user/nick specified is invalid");
            }

            String pwd = (String)parameters.get("password");
            if (pwd != null) {
                password = pwd;
                parameters.remove("password");
            }

            // Remove unneeded '#' channel prefixes per convention
            // and replace ',' separators and merge channel and key using convention "channel!key"
            List<String> cl = new ArrayList<String>();
            String channels = (String)parameters.get("channels");
            String keys =  (String)parameters.get("keys");
            keys = keys == null ? keys : keys + " ";    // if @keys ends with a ',' it will miss the last empty key after split(",")
            if (channels != null) {
                String[] chs = channels.split(",");
                String[] ks = keys != null ? keys.split(",") : null;
                parameters.remove("channels");
                int count = chs.length;
                if (ks != null) {
                    parameters.remove("keys");
                    if (!path.isEmpty()) {
                        LOG.warn("Specifying a channel '{}' in the URI path is ambiguous"
                            + " when @channels and @keys are provided and will be ignored", path);
                        path = "";
                    }
                    if (ks.length != chs.length) {
                        count = count < ks.length ? count : ks.length;
                        LOG.warn("Different count of @channels and @keys. Only the first {} are used.", count);
                    }
                }
                for (int i = 0; i < count; i++) {
                    String channel = chs[i].trim();
                    String key = ks != null ? ks[i].trim() : null;
                    if (channel.startsWith("#") && !channel.startsWith("##")) {
                        channel = channel.substring(1);
                    }
                    if (key != null && !key.isEmpty()) {
                        channel += "!" + key;
                    }
                    cl.add(channel);
                }
            } else {
                if (path.isEmpty()) {
                    LOG.warn("No channel specified for the irc endpoint");
                }
                cl.add(path);
            }
            parameters.put("channel", cl);

            StringBuilder sb = new StringBuilder();
            sb.append(u.getScheme());
            sb.append("://");
            sb.append(username);
            sb.append(password == null ? "" : ":" + password);
            sb.append("@");
            sb.append(u.getHost());
            sb.append(u.getPort() == -1 ? "" : ":" + u.getPort());
            // ignore the path we have it as a @channel now
            String query = formatQuery(parameters);
            if (!query.isEmpty()) {
                sb.append("?");
                sb.append(query);
            }
            // make things a bit more predictable
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeCamelException(e);
        }
    }

    private static String formatQuery(Map<String, Object> params) {
        if (params == null || params.size() == 0) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, Object> pair : params.entrySet()) {
            Object value = pair.getValue();
            // the value may be a list since the same key has multiple values
            if (value instanceof List) {
                List<?> list = (List<?>)value;
                for (Object s : list) {
                    addQueryParameter(result, pair.getKey(), s);
                }
            } else {
                addQueryParameter(result, pair.getKey(), value);
            }
        }
        return result.toString();
    }

    private static void addQueryParameter(StringBuilder sb, String key, Object value) {
        sb.append(sb.length() == 0 ? "" : "&");
        sb.append(key);
        if (value != null) {
            String s = value.toString();
            sb.append(s.isEmpty() ? "" : "=" + UnsafeUriCharactersEncoder.encode(s));
        }
    }
}


text:
"use strict";

module.exports = {
  "es7.classProperties": require("./es7/class-properties"),
  "es7.trailingFunctionCommas": require("./es7/trailing-function-commas"),
  "es7.asyncFunctions": require("./es7/async-functions"),
  "es7.decorators": require("./es7/decorators"),

  strict: require("./other/strict"),

  _validation: require("./internal/validation"),

  "validation.undeclaredVariableCheck": require("./validation/undeclared-variable-check"),
  "validation.react": require("./validation/react"),

  // this goes at the start so we only transform the original user code
  "spec.functionName": require("./spec/function-name"),

  // needs to be before `_shadowFunctions`
  "es6.arrowFunctions": require("./es6/arrow-functions"),

  "spec.blockScopedFunctions": require("./spec/block-scoped-functions"),

  "optimisation.react.constantElements": require("./optimisation/react.constant-elements"),
  "optimisation.react.inlineElements": require("./optimisation/react.inline-elements"),
  reactCompat: require("./other/react-compat"),
  react: require("./other/react"),

  _modules: require("./internal/modules"),

  // needs to be before `regenerator` due to generator comprehensions
  // needs to be before `_shadowFunctions`
  "es7.comprehensions": require("./es7/comprehensions"),

  "es6.classes": require("./es6/classes"),

  asyncToGenerator: require("./other/async-to-generator"),
  bluebirdCoroutines: require("./other/bluebird-coroutines"),

  "es6.objectSuper": require("./es6/object-super"),
  "es7.objectRestSpread": require("./es7/object-rest-spread"),
  "es7.exponentiationOperator": require("./es7/exponentiation-operator"),

  "es6.spec.templateLiterals": require("./es6/spec.template-literals"),
  "es6.templateLiterals": require("./es6/template-literals"),

  "es5.properties.mutators": require("./es5/properties.mutators"),
  "es6.properties.shorthand": require("./es6/properties.shorthand"),

  // needs to be before `_shadowFunctions` due to define property closure
  "es6.properties.computed": require("./es6/properties.computed"),

  "optimisation.flow.forOf": require("./optimisation/flow.for-of"),
  "es6.forOf": require("./es6/for-of"),

  "es6.regex.sticky": require("./es6/regex.sticky"),
  "es6.regex.unicode": require("./es6/regex.unicode"),

  "es6.constants": require("./es6/constants"),

  // needs to be before `es6.parameters.default` as default parameters will destroy the rest param
  "es6.parameters.rest": require("./es6/parameters.rest"),

  // needs to be after `es6.parameters.rest` as we use `toArray` and avoid turning an already known array into one
  "es6.spread": require("./es6/spread"),

  // needs to be before `es6.blockScoping` as default parameters have a TDZ
  "es6.parameters.default": require("./es6/parameters.default"),

  // needs to be before `es6.blockScoping` as let variables may be produced
  "es6.destructuring": require("./es6/destructuring"),

  // needs to be before `_shadowFunctions` due to block scopes sometimes being wrapped in a
  // closure
  "es6.blockScoping": require("./es6/block-scoping"),

  // needs to be after `es6.blockScoping` due to needing `letReferences` set on blocks
  "es6.spec.blockScoping": require("./es6/spec.block-scoping"),

  // needs to be after `es6.parameters.*` and `es6.blockScoping` due to needing pure
  // identifiers in parameters and variable declarators
  "es6.tailCall": require("./es6/tail-call"),

  regenerator: require("./other/regenerator"),

  // needs to be after `regenerator` due to needing `regeneratorRuntime` references
  // needs to be after `es6.forOf` due to needing `Symbol.iterator` references
  // needs to be before `es6.modules` due to dynamic imports
  runtime: require("./other/runtime"),

  // needs to be before `_blockHoist` due to function hoisting etc
  "es7.exportExtensions": require("./es7/export-extensions"),
  "es6.modules": require("./es6/modules"),

  _blockHoist: require("./internal/block-hoist"),

  "spec.protoToAssign": require("./spec/proto-to-assign"),

  _declarations: require("./internal/declarations"),

  _shadowFunctions: require("./internal/shadow-functions"),

  "es7.doExpressions": require("./es7/do-expressions"),

  "es6.spec.symbols": require("./es6/spec.symbols"),
  ludicrous: require("./other/ludicrous"),
  "spec.undefinedToVoid": require("./spec/undefined-to-void"),

  _strict: require("./internal/strict"),
  _moduleFormatter: require("./internal/module-formatter"),

  "es3.propertyLiterals": require("./es3/property-literals"),
  "es3.memberExpressionLiterals": require("./es3/member-expression-literals"),

  "utility.removeDebugger": require("./utility/remove-debugger"),
  "utility.removeConsole": require("./utility/remove-console"),

  "utility.inlineEnvironmentVariables": require("./utility/inline-environment-variables"),
  "utility.inlineExpressions": require("./utility/inline-expressions"),
  "utility.deadCodeElimination": require("./utility/dead-code-elimination"),

  flow: require("./other/flow"),
  _cleanUp: require("./internal/cleanup")
};

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Property editor</title>

  <button>Cancel</button>

    <textarea id='edit-editor' style='width:98%; height:300px; border:1px solid #ccc'></textarea>


text:
<?php

namespace MewesK\TwigSpreadsheetBundle\Tests\Twig;

/**
 * Class CsvOdsXlsXlsxErrorTwigTest.
 */
class CsvOdsXlsXlsxErrorTwigTest extends BaseTwigTest
{
    /**
     * @return array
     */
    public function formatProvider(): array
    {
        return [['csv'], ['ods'], ['xls'], ['xlsx']];
    }

    //
    // Tests
    //

    /**
     * @param string $format
     *
     * @throws \Exception
     *
     * @dataProvider formatProvider
     */
    public function testDocumentError($format)
    {
        $this->expectException(\Twig_Error_Syntax::class);
        $this->expectExceptionMessage('Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode" is not allowed inside of Node "MewesK\TwigSpreadsheetBundle\Twig\Node\SheetNode"');

        $this->getDocument('documentError', $format);
    }

    /**
     * @param string $format
     *
     * @throws \Exception
     *
     * @dataProvider formatProvider
     */
    public function testDocumentErrorTextAfter($format)
    {
        $this->expectException(\Twig_Error_Syntax::class);
        $this->expectExceptionMessage('Node "Twig_Node_Text" is not allowed after Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode"');

        $this->getDocument('documentErrorTextAfter', $format);
    }

    /**
     * @param string $format
     *
     * @throws \Exception
     *
     * @dataProvider formatProvider
     */
    public function testDocumentErrorTextBefore($format)
    {
        $this->expectException(\Twig_Error_Syntax::class);
        $this->expectExceptionMessage('Node "Twig_Node_Text" is not allowed before Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode"');

        $this->getDocument('documentErrorTextBefore', $format);
    }

    /**
     * @param string $format
     *
     * @throws \Exception
     *
     * @dataProvider formatProvider
     */
    public function testStartCellIndexError($format)
    {
        $this->expectException(\TypeError::class);
        $this->expectExceptionMessage('Argument 1 passed to MewesK\TwigSpreadsheetBundle\Wrapper\PhpSpreadsheetWrapper::startCell() must be of the type integer');

        $this->getDocument('cellIndexError', $format);
    }

    /**
     * @param string $format
     *
     * @throws \Exception
     *
     * @dataProvider formatProvider
     */
    public function testStartRowIndexError($format)
    {
        $this->expectException(\TypeError::class);
        $this->expectExceptionMessage('Argument 1 passed to MewesK\TwigSpreadsheetBundle\Wrapper\PhpSpreadsheetWrapper::startRow() must be of the type integer');

        $this->getDocument('rowIndexError', $format);
    }

    /**
     * @param string $format
     *
     * @throws \Exception
     *
     * @dataProvider formatProvider
     */
    public function testSheetError($format)
    {
        $this->expectException(\Twig_Error_Syntax::class);
        $this->expectExceptionMessage('Node "MewesK\TwigSpreadsheetBundle\Twig\Node\RowNode" is not allowed inside of Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode"');

        $this->getDocument('sheetError', $format);
    }
}


text:
using System;

namespace ManneDoForms.Droid.Common.PhotoViewDroid
{
	public interface IOnGestureListener
	{
		void OnDrag(float dx, float dy);
		void OnFling(float startX, float startY, float velocityX,float velocityY);
		void OnScale(float scaleFactor, float focusX, float focusY);
	}
}


text:
"""
Copyright 2020 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://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.
"""
from flask import Flask
import random
import time
from opentelemetry import metrics
from opentelemetry.exporter.cloud_monitoring import (
    CloudMonitoringMetricsExporter,
)
from opentelemetry.sdk.metrics import Counter, MeterProvider

# set up exporter
metrics.set_meter_provider(MeterProvider())
meter = metrics.get_meter(__name__)
metrics.get_meter_provider().start_pipeline(
    meter, CloudMonitoringMetricsExporter("stack-doctor"), 5
)

# set up metrics
# total requests
requests_counter = meter.create_counter(
    name="total_requests_python",
    description="number of requests",
    unit="1",
    value_type=int,
)
# errors
errors_counter = meter.create_counter(
    name="total_errors_python",
    description="number of errors",
    unit="1",
    value_type=int,
)
# latency
# waiting for https://github.com/GoogleCloudPlatform/opentelemetry-operations-python/issues/67
# to be resolved to use valuerecorder

metric_labels = {}

app = Flask(__name__)

@app.route('/')
def homePage():
    # start timer
    start_time = time.perf_counter()
    # count request
    requests_counter.add(1, metric_labels)
    # fail 10% of the time
    if random.randint(0, 100) > 90:
        errors_counter.add(1, metric_labels)
        latency = time.perf_counter() - start_time
        # no way to record a histogram at present - see above
        return("error!", 500)
    else:
        random_delay = random.randint(0,5000)/1000
        # delay for a bit to vary latency measurement
        time.sleep(random_delay)
        # record latency
        latency = time.perf_counter() - start_time
        # no way to record a histogram at present - see above
        return ("Responding in " + str(latency) + "ms")

if __name__ == '__main__':
    app.run()


text:
import { Meteor } from 'meteor/meteor';
import { ServiceEntrances } from '../../../both/collections/service-entrances.collection'

Meteor.publish('service_entrance', function(place_id: string) {
  return ServiceEntrances.find({place_ids: place_id}, {sort: {updated_at: -1}});
});


text:
/* =================================================================== */
/* CSS for sap_hcb theme of sap.suite.ui.commons/FacetOverview.control */
/* =================================================================== */

.sapSuiteFovHoverIcon {
	color: @sapHCStandardFG;
	opacity: 1;
}

.sapSuiteFov {
	background-color: @sapHCStandardBG;
	border: 1px solid @sapHCStandardFG;
	border-radius: 6px;
	margin: 1px;
}

.sapSuiteFovSelected {
	background-color: @sapHCHighlightBG;
	color: @sapHCStandardFG;
}

.sap-desktop .sapSuiteFovActiveCont:focus,
.sap-desktop .sapSuiteFovClickable:focus {
	outline: 0.125rem dotted @sapHCStandardFG;
	outline-offset: -0.125rem;
	border-color: transparent;
}

.sapSuiteFovTitle {
    font-size: @sapMFontHeader4Size;
}

.sapSuiteFov > .sapSuiteFovContent .sapMLabel {
    color: @sapHCStandardFG;
}

.sapSuiteFov.sapSuiteFovSelected {
    .sapSuiteFovHoverIcon,
    .sapMLabel {
        color: @sapHCStandardFG;
    }
}

.sapSuiteFov.sapSuiteFovSelected > .sapSuiteFovContent {
    .sapMLabel,
    .sapMText,
    .sapMLnk {
        color: @sapHCStandardFG;
   }
}

.sapSuiteFovSelected .sapUiForm {
    background-color: transparent;
}

.sapSuiteFovClickable {
	box-shadow: 0;
}

.sap-desktop .sapSuiteFov.sapSuiteFovClickable:hover {
	box-shadow: 0px 0px 0px 1px @sapHCStandardFG;
}


text:
<?php
/**
 * @package WordPress
 * @subpackage NotesIL
 */

/*
This file is part of SANDBOX.

SANDBOX is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.

SANDBOX is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with SANDBOX. If not, see http://www.gnu.org/licenses/.
*/

$content_width = 530;

$themecolors = array(
	'bg' => 'ffffff',
	'border' => 'bc0404',
	'text' => '000000',
	'link' => 'bc0404',
	'url' => '00447c',
);

function notes_comments( $comment, $args, $depth ) {

	$GLOBALS['comment'] = $comment;
	extract( $args, EXTR_SKIP );
	global $notes_comments_alt;
	?>
						<li id="comment-<?php comment_ID(); ?>" class="<?php notesil_comment_class(); ?>">
							<div class="singlecomment" id="div-comment-<?php comment_ID(); ?>">

<?php notesil_commenter_link(); ?>
									 <?php printf( __( 'On %1$s at %2$s', 'notesil' ), get_comment_date(), get_comment_time() ); ?>

<?php printf( __( 'Permalink', 'notesil' ), '#comment-' . get_comment_ID() );
												echo comment_reply_link(array( 'depth' => $depth, 'max_depth' => $args['max_depth'], 'before' => ' | ' ) );
												edit_comment_link( __( 'Edit', 'notesil' ), ' | ', '' ); ?>

<?php if ( $comment->comment_approved == '0' ) _e("\t\t\t\t\tYour comment is awaiting moderation.\n", 'notesil' ); ?>
							<?php comment_text(); ?>

<?php }

function notes_trackbacks( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	extract( $args, EXTR_SKIP );
	global $notes_comments_alt;
	?>
    <li id="comment-<?php comment_ID(); ?>" class="<?php notesil_comment_class(); ?>">

<?php printf( __( 'By %1$s on %2$s at %3$s', 'notesil' ),
	    			get_comment_author_link(),
	    			get_comment_date(),
	    			get_comment_time() );
	    			edit_comment_link( __( 'Edit', 'notesil' ), ' | ', '' ); ?>

	    	<?php if ( $comment->comment_approved == '0' ) _e( '\t\t\t\t\tYour trackback is awaiting moderation.\n', 'notesil' ); ?>
	    	<?php comment_text(); ?>

<?php }

function notesil_globalnav() {
	if ( $menu = str_replace( array( "\r", "\n", "\t" ), '', wp_list_pages( 'title_li=&sort_column=menu_order&echo=0' ) ) )
		$menu = '
' . $menu . '
';
	$menu = '
' . $menu . "
\n";
	echo apply_filters( 'globalnav_menu', $menu ); // Filter to override default globalnav: globalnav_menu
}

// Generates semantic classes for BODY element
function notesil_body_class( $print = true ) {
	global $wp_query, $current_user;

	// It's surely a WordPress blog, right?
	$c = array( 'wordpress' );

	// Applies the time- and date-based classes (below) to BODY element
	notesil_date_classes( time(), $c );

	// Generic semantic classes for what type of content is displayed
	is_front_page()  ? $c[] = 'home'       : null; // For the front page, if set
	is_home()        ? $c[] = 'blog'       : null; // For the blog posts page, if set
	is_archive()     ? $c[] = 'archive'    : null;
	is_date()        ? $c[] = 'date'       : null;
	is_search()      ? $c[] = 'search'     : null;
	is_paged()       ? $c[] = 'paged'      : null;
	is_attachment()  ? $c[] = 'attachment' : null;
	is_404()         ? $c[] = 'four04'     : null; // CSS does not allow a digit as first character

	// Special classes for BODY element when a single post
	if ( is_single() ) {
		$postID = $wp_query->post->ID;
		the_post();

		// Adds 'single' class and class with the post ID
		$c[] = 'single postid-' . $postID;

		// Adds classes for the month, day, and hour when the post was published
		if ( isset( $wp_query->post->post_date ) )
			notesil_date_classes( mysql2date( 'U', $wp_query->post->post_date ), $c, 's-' );

		// Adds category classes for each category on single posts
		if ( $cats = get_the_category() )
			foreach ( $cats as $cat )
				$c[] = 's-category-' . $cat->slug;

		// Adds tag classes for each tags on single posts
		if ( $tags = get_the_tags() )
			foreach ( $tags as $tag )
				$c[] = 's-tag-' . $tag->slug;

		// Adds MIME-specific classes for attachments
		if ( is_attachment() ) {
			$mime_type = get_post_mime_type();
			$mime_prefix = array( 'application/', 'image/', 'text/', 'audio/', 'video/', 'music/' );
				$c[] = 'attachmentid-' . $postID . ' attachment-' . str_replace( $mime_prefix, "", "$mime_type" );
		}

		// Adds author class for the post author
		$c[] = 's-author-' . sanitize_title_with_dashes(strtolower(get_the_author_meta( 'login' )) );
		rewind_posts();
	}

	// Author name classes for BODY on author archives
	elseif ( is_author() ) {
		$author = $wp_query->get_queried_object();
		$c[] = 'author';
		$c[] = 'author-' . $author->user_nicename;
	}

	// Category name classes for BODY on category archvies
	elseif ( is_category() ) {
		$cat = $wp_query->get_queried_object();
		$c[] = 'category';
		$c[] = 'category-' . $cat->slug;
	}

	// Tag name classes for BODY on tag archives
	elseif ( is_tag() ) {
		$tags = $wp_query->get_queried_object();
		$c[] = 'tag';
		$c[] = 'tag-' . $tags->slug;
	}

	// Page author for BODY on 'pages'
	elseif ( is_page() ) {
		$pageID = $wp_query->post->ID;
		$page_children = wp_list_pages("child_of=$pageID&echo=0");
		the_post();
		$c[] = 'page pageid-' . $pageID;
		$c[] = 'page-author-' . sanitize_title_with_dashes(strtolower(get_the_author_meta( 'login' )) );
		// Checks to see if the page has children and/or is a child page; props to Adam
		if ( $page_children )
			$c[] = 'page-parent';
		if ( $wp_query->post->post_parent )
			$c[] = 'page-child parent-pageid-' . $wp_query->post->post_parent;
		if ( is_page_template() ) // Hat tip to Ian, themeshaper.com
			$c[] = 'page-template page-template-' . str_replace( '.php', '-php', get_post_meta( $pageID, '_wp_page_template', true ) );
		rewind_posts();
	}

	// Search classes for results or no results
	elseif ( is_search() ) {
		the_post();
		if ( have_posts() ) {
			$c[] = 'search-results';
		} else {
			$c[] = 'search-no-results';
		}
		rewind_posts();
	}

	// For when a visitor is logged in while browsing
	if ( $current_user->ID )
		$c[] = 'loggedin';

	// Paged classes; for 'page X' classes of index, single, etc.
	if ( ( ( $page = $wp_query->get( 'paged' ) ) || ( $page = $wp_query->get( 'page' ) ) ) && $page > 1 ) {
		// Thanks to Prentiss Riddle, twitter.com/pzriddle, for the security fix below.
		$page = intval( $page ); // Ensures that an integer (not some dangerous script) is passed for the variable
		$c[] = 'paged-' . $page;
		if ( is_single() ) {
			$c[] = 'single-paged-' . $page;
		} elseif ( is_page() ) {
			$c[] = 'page-paged-' . $page;
		} elseif ( is_category() ) {
			$c[] = 'category-paged-' . $page;
		} elseif ( is_tag() ) {
			$c[] = 'tag-paged-' . $page;
		} elseif ( is_date() ) {
			$c[] = 'date-paged-' . $page;
		} elseif ( is_author() ) {
			$c[] = 'author-paged-' . $page;
		} elseif ( is_search() ) {
			$c[] = 'search-paged-' . $page;
		}
	}

	// Separates classes with a single space, collates classes for BODY
	$c = join( ' ', apply_filters( 'body_class',  $c ) ); // Available filter: body_class

	// And tada!
	return $print ? print( $c ) : $c;
}

// Generates semantic classes for each post DIV element
function notesil_post_class( $print = true ) {
	global $post, $notesil_post_alt;

	// hentry for hAtom compliace, gets 'alt' for every other post DIV, describes the post type and p[n]
	$c = array( 'hentry', "p$notesil_post_alt", $post->post_type, $post->post_status );

	// Author for the post queried
	$c[] = 'author-' . sanitize_title_with_dashes(strtolower(get_the_author_meta( 'login' )) );

	// Category for the post queried
	foreach ( (array) get_the_category() as $cat )
		$c[] = 'category-' . $cat->slug;

	// Tags for the post queried; if not tagged, use .untagged
	if ( get_the_tags() == null ) {
		$c[] = 'untagged';
	} else {
		foreach ( (array) get_the_tags() as $tag )
			$c[] = 'tag-' . $tag->slug;
	}

	// For password-protected posts
	if ( $post->post_password )
		$c[] = 'protected';

	// Applies the time- and date-based classes (below) to post DIV
	notesil_date_classes( mysql2date( 'U', $post->post_date ), $c );

	// If it's the other to the every, then add 'alt' class
	if ( ++$notesil_post_alt % 2 )
		$c[] = 'alt';

	// Separates classes with a single space, collates classes for post DIV
	$c = join( ' ', apply_filters( 'post_class', $c ) ); // Available filter: post_class

	// And tada!
	return $print ? print( $c ) : $c;
}

// Define the num val for 'alt' classes (in post DIV and comment LI)
$notesil_post_alt = 1;

// Generates semantic classes for each comment LI element
function notesil_comment_class( $print = true ) {
	global $comment, $post, $notesil_comment_alt;

	// Collects the comment type (comment, trackback),
	$c = array( $comment->comment_type );

	// Counts trackbacks (t[n]) or comments (c[n])
	if ( $comment->comment_type == 'comment' ) {
		$c[] = "c$notesil_comment_alt";
	} else {
		$c[] = "t$notesil_comment_alt";
	}

	// If the comment author has an id (registered), then print the log in name
	if ( $comment->user_id > 0 ) {
		$user = get_userdata( $comment->user_id );
		// For all registered users, 'byuser'; to specificy the registered user, 'commentauthor+[log in name]'
		$c[] = 'byuser comment-author-' . sanitize_title_with_dashes(strtolower( $user->user_login ) );
		// For comment authors who are the author of the post
		if ( $comment->user_id === $post->post_author )
			$c[] = 'bypostauthor';
	}

	// If it's the other to the every, then add 'alt' class; collects time- and date-based classes
	notesil_date_classes( mysql2date( 'U', $comment->comment_date ), $c, 'c-' );
	if ( ++$notesil_comment_alt % 2 )
		$c[] = 'alt';

	// Separates classes with a single space, collates classes for comment LI
	$c = join( ' ', apply_filters( 'comment_class', $c ) ); // Available filter: comment_class

	// Tada again!
	return $print ? print( $c ) : $c;
}

// Generates time- and date-based classes for BODY, post DIVs, and comment LIs; relative to GMT (UTC)
function notesil_date_classes( $t, &$c, $p = '' ) {
	$t = $t + ( get_option( 'gmt_offset' ) * 3600 );
	$c[] = $p . 'y' . gmdate( 'Y', $t ); // Year
	$c[] = $p . 'm' . gmdate( 'm', $t ); // Month
	$c[] = $p . 'd' . gmdate( 'd', $t ); // Day
	$c[] = $p . 'h' . gmdate( 'H', $t ); // Hour
}

// For category lists on category archives: Returns other categories except the current one (redundant)
function notesil_cats_meow( $glue ) {
	$current_cat = single_cat_title( '', false );
	$separator = "\n";
	$cats = explode( $separator, get_the_category_list( $separator ) );
	foreach ( $cats as $i => $str ) {
		if ( strstr( $str, ">$current_cat<" ) ) {
			unset( $cats[$i] );
			break;
		}
	}
	if ( empty( $cats ) )
		return false;

	return trim( join( $glue, $cats ) );
}

// For tag lists on tag archives: Returns other tags except the current one (redundant)
function notesil_tag_ur_it( $glue ) {
	$current_tag = single_tag_title( '', '',  false );
	$separator = "\n";
	$tags = explode( $separator, get_the_tag_list( "", "$separator", "" ) );
	foreach ( $tags as $i => $str ) {
		if ( strstr( $str, ">$current_tag<" ) ) {
			unset( $tags[$i] );
			break;
		}
	}
	if ( empty( $tags ) )
		return false;

	return trim( join( $glue, $tags ) );
}

// Produces an avatar image with the hCard-compliant photo class
function notesil_commenter_link() {
	$commenter = get_comment_author_link();
	if ( ereg( ']* class=[^>]+>', $commenter ) ) {
		$commenter = ereg_replace( '(]* class=[\'"]?)', '\\1url ' , $commenter );
	} else {
		$commenter = ereg_replace( '(<a )/', '\\1class="url "' , $commenter );
	}
	$avatar_size = apply_filters( 'avatar_size', '32' ); // Available filter: avatar_size
	$avatar = str_replace( "class='avatar", "class='photo avatar", get_avatar( $GLOBALS['comment'], $avatar_size ) );
	echo $avatar . ' ' . $commenter . '';
}

// Widgets plugin: intializes the plugin after the widgets above have passed snuff
function notes_sidebar_init() {
	// Formats the Sandbox widgets, adding readability-improving whitespace
	register_sidebar( array(
		'before_widget'  =>   "\n\t\t\t" . '
',
		'after_widget'   =>   "\n\t\t\t
\n",
		'before_title'   =>   "\n\t\t\t\t". '
',
		'after_title'    =>   "
\n"
	) );
}
add_action( 'init', 'notes_sidebar_init' );

// Translate, if applicable
load_theme_textdomain( 'notesil', get_template_directory() . '/languages' );

// Adds filters for the description/meta content in archives.php
add_filter( 'archive_meta', 'wptexturize' );
add_filter( 'archive_meta', 'convert_smilies' );
add_filter( 'archive_meta', 'convert_chars' );
add_filter( 'archive_meta', 'wpautop' );

//Notes color customizer, inspired by Toni's

function get_notes_colors() {
	return array(
		'default' => 'BC0404',
		'black' => '000',
		'darkblue' => '213970',
		'darkgreen' => '3D750B',
		'darkpurple' => '660066',
		'grey' => '6B6B6B',
		'lightblue' => 'BAC5D2',
		'lightgreen' => '749881',
		'lightorange' => 'DC6700',
		'lightpurple' => '9999CC',
		'olive' => '660',
		'strongbrown' => '950'
		);
}

function get_notes_color() {
	$notes_color = get_option( 'notes_color' );
	if ( $notes_color == '' )
		$notes_color = 'default';
	return clean_notes_color( $notes_color );
}

function notes_color_select() {
	echo "<select id='notes_color' name='notes_color' size='4'>";
	$colors = get_notes_colors();
	$current_color = get_notes_color();
	foreach ( $colors as $name => $value ) {
		$selected = ( $current_color == $value ) ? " selected='selected'" : '';
		echo "<option value='$value'$selected>$name</option>";
	}
	echo "</select>\n";
}

function notes_color_radios() {
	$colors = get_notes_colors();
	$current_color = get_notes_color();
	$theme_uri = get_template_directory_uri();
	$i = 0;
	foreach ( $colors as $name => $value ) {
		$checked = ( $current_color == $name ) ? " checked='checked'" : '';
		echo "
<input type='radio' name='notes_color' id='notes_color_{$i}' value='{$name}'$checked />

\n";
		++$i;
	}
}

function clean_notes_color( $notes_color ) {
	$notes_colors = get_notes_colors();
	if ( array_key_exists( $notes_color, $notes_colors ) )
		return $notes_color;
	else
		return '';
}

function notes_color() {
	echo get_notes_color();
}

function notes_css( $body_class ) {
	$notes_color = get_notes_color();
	if ( !empty( $notes_color ) )
		$body_class[]= $notes_color;
	return( $body_class );
}
add_filter( 'body_class', 'notes_css' );

add_action( 'admin_menu', 'notes_add_theme_page' );

function notes_add_theme_page() {
	global $notes_message;
	if ( isset( $_POST['action']) && 'notes_update' == $_POST['action'] ) {
		$color = clean_notes_color( $_POST['notes_color'] );
		update_option( 'notes_color', $color);
		$message = __("Color changed.", 'notesil' );
		$notes_message = "

$message

";
	}

	add_theme_page("Theme Options", __("Theme Options", 'notesil' ), 'edit_theme_options', basename(__FILE__), 'notes_theme_page' );
}

function notes_theme_page() {
	global $notes_message;
	echo $notes_message;
?>

<?php _e( 'Color selection', 'notesil' ); ?>

<?php _e( 'Please select the primary color of your blog theme', 'notesil' ); ?>

  <form method="post">

<?php notes_color_radios(); ?>

<input type="submit" name="Submit" value="<?php esc_attr_e( 'Apply Color »', 'notesil' ); ?>" />

  <input type="hidden" name="action" value="notes_update" />
  </form>

<?php
}

class Notes_Author_Widget extends WP_Widget {

	function Notes_Author_Widget() {
		$widget_ops = array( 'classname' => 'widget_notes_author', 'description' => __( 'The author Name, Gravatar, and description', 'notesil' ) );
		$this->WP_Widget( 'notes_author', __( 'Notes Author', 'notesil' ), $widget_ops);
	}

	function widget( $args, $instance ) {
		extract( $args );
		$title = '';
		echo $before_widget;
		if ( $title )
			echo $before_title . $title . $after_title;
					echo get_avatar(get_the_author_meta( 'user_email' ), $size = '60', $default = get_template_directory_uri() . '/i/default-avatar.gif' );
				 	echo '
' . get_the_author_meta( 'display_name' ) . '
';
					echo '
' . get_the_author_meta( 'description' ) . '
';
		echo $after_widget;
	}

	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = strip_tags( $new_instance['title'] );

		return $instance;
	}

	function form( $instance ) {
		$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
		$title = strip_tags( $instance['title'] );
?>

<?php _e( 'Display your Gravatar, and your name and description from your user profile', 'notesil' ); ?>.

<?php _e( 'Don\'t have a Gravatar? Get one now.', 'notesil' ); ?>

<?php
	}
}

if ( ! defined( 'IS_WPCOM' ) && ! 'IS_WPCOM' ) {
	//only activate the authors widget on when not on WPCOM.
	add_action( 'widgets_init', create_function( '', 'return register_widget("Notes_Author_Widget");' ) );
}

add_theme_support( 'automatic-feed-links' );

add_custom_background();


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

namespace Google\Cloud\Dataproc\V1;

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

/**
 * Optional. The config settings for Google Compute Engine resources in
 * an instance group, such as a master or worker group.
 *
 * Generated from protobuf message google.cloud.dataproc.v1.InstanceGroupConfig
 */
class InstanceGroupConfig extends \Google\Protobuf\Internal\Message
{
    /**
     * Optional. The number of VM instances in the instance group.
     * For master instance groups, must be set to 1.
     *
     * Generated from protobuf field int32 num_instances = 1;
     */
    private $num_instances = 0;
    /**
     * Optional. The list of instance names. Cloud Dataproc derives the names from
     * `cluster_name`, `num_instances`, and the instance group if not set by user
     * (recommended practice is to let Cloud Dataproc derive the name).
     *
     * Generated from protobuf field repeated string instance_names = 2;
     */
    private $instance_names;
    /**
     * Output-only. The Google Compute Engine image resource used for cluster
     * instances. Inferred from `SoftwareConfig.image_version`.
     *
     * Generated from protobuf field string image_uri = 3;
     */
    private $image_uri = '';
    /**
     * Optional. The Google Compute Engine machine type used for cluster instances.
     * A full URL, partial URI, or short name are valid. Examples:
     * * `https://www.googleapis.com/compute/v1/projects/[project_id]/zones/us-east1-a/machineTypes/n1-standard-2`
     * * `projects/[project_id]/zones/us-east1-a/machineTypes/n1-standard-2`
     * * `n1-standard-2`
     *
     * Generated from protobuf field string machine_type_uri = 4;
     */
    private $machine_type_uri = '';
    /**
     * Optional. Disk option config settings.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.DiskConfig disk_config = 5;
     */
    private $disk_config = null;
    /**
     * Optional. Specifies that this instance group contains preemptible instances.
     *
     * Generated from protobuf field bool is_preemptible = 6;
     */
    private $is_preemptible = false;
    /**
     * Output-only. The config for Google Compute Engine Instance Group
     * Manager that manages this group.
     * This is only used for preemptible instance groups.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.ManagedGroupConfig managed_group_config = 7;
     */
    private $managed_group_config = null;
    /**
     * Optional. The Google Compute Engine accelerator configuration for these
     * instances.
     * **Beta Feature**: This feature is still under development. It may be
     * changed before final release.
     *
     * Generated from protobuf field repeated .google.cloud.dataproc.v1.AcceleratorConfig accelerators = 8;
     */
    private $accelerators;

    public function __construct() {
        \GPBMetadata\Google\Cloud\Dataproc\V1\Clusters::initOnce();
        parent::__construct();
    }

    /**
     * Optional. The number of VM instances in the instance group.
     * For master instance groups, must be set to 1.
     *
     * Generated from protobuf field int32 num_instances = 1;
     * @return int
     */
    public function getNumInstances()
    {
        return $this->num_instances;
    }

    /**
     * Optional. The number of VM instances in the instance group.
     * For master instance groups, must be set to 1.
     *
     * Generated from protobuf field int32 num_instances = 1;
     * @param int $var
     * @return $this
     */
    public function setNumInstances($var)
    {
        GPBUtil::checkInt32($var);
        $this->num_instances = $var;

        return $this;
    }

    /**
     * Optional. The list of instance names. Cloud Dataproc derives the names from
     * `cluster_name`, `num_instances`, and the instance group if not set by user
     * (recommended practice is to let Cloud Dataproc derive the name).
     *
     * Generated from protobuf field repeated string instance_names = 2;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getInstanceNames()
    {
        return $this->instance_names;
    }

    /**
     * Optional. The list of instance names. Cloud Dataproc derives the names from
     * `cluster_name`, `num_instances`, and the instance group if not set by user
     * (recommended practice is to let Cloud Dataproc derive the name).
     *
     * Generated from protobuf field repeated string instance_names = 2;
     * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setInstanceNames($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
        $this->instance_names = $arr;

        return $this;
    }

    /**
     * Output-only. The Google Compute Engine image resource used for cluster
     * instances. Inferred from `SoftwareConfig.image_version`.
     *
     * Generated from protobuf field string image_uri = 3;
     * @return string
     */
    public function getImageUri()
    {
        return $this->image_uri;
    }

    /**
     * Output-only. The Google Compute Engine image resource used for cluster
     * instances. Inferred from `SoftwareConfig.image_version`.
     *
     * Generated from protobuf field string image_uri = 3;
     * @param string $var
     * @return $this
     */
    public function setImageUri($var)
    {
        GPBUtil::checkString($var, True);
        $this->image_uri = $var;

        return $this;
    }

    /**
     * Optional. The Google Compute Engine machine type used for cluster instances.
     * A full URL, partial URI, or short name are valid. Examples:
     * * `https://www.googleapis.com/compute/v1/projects/[project_id]/zones/us-east1-a/machineTypes/n1-standard-2`
     * * `projects/[project_id]/zones/us-east1-a/machineTypes/n1-standard-2`
     * * `n1-standard-2`
     *
     * Generated from protobuf field string machine_type_uri = 4;
     * @return string
     */
    public function getMachineTypeUri()
    {
        return $this->machine_type_uri;
    }

    /**
     * Optional. The Google Compute Engine machine type used for cluster instances.
     * A full URL, partial URI, or short name are valid. Examples:
     * * `https://www.googleapis.com/compute/v1/projects/[project_id]/zones/us-east1-a/machineTypes/n1-standard-2`
     * * `projects/[project_id]/zones/us-east1-a/machineTypes/n1-standard-2`
     * * `n1-standard-2`
     *
     * Generated from protobuf field string machine_type_uri = 4;
     * @param string $var
     * @return $this
     */
    public function setMachineTypeUri($var)
    {
        GPBUtil::checkString($var, True);
        $this->machine_type_uri = $var;

        return $this;
    }

    /**
     * Optional. Disk option config settings.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.DiskConfig disk_config = 5;
     * @return \Google\Cloud\Dataproc\V1\DiskConfig
     */
    public function getDiskConfig()
    {
        return $this->disk_config;
    }

    /**
     * Optional. Disk option config settings.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.DiskConfig disk_config = 5;
     * @param \Google\Cloud\Dataproc\V1\DiskConfig $var
     * @return $this
     */
    public function setDiskConfig($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dataproc\V1\DiskConfig::class);
        $this->disk_config = $var;

        return $this;
    }

    /**
     * Optional. Specifies that this instance group contains preemptible instances.
     *
     * Generated from protobuf field bool is_preemptible = 6;
     * @return bool
     */
    public function getIsPreemptible()
    {
        return $this->is_preemptible;
    }

    /**
     * Optional. Specifies that this instance group contains preemptible instances.
     *
     * Generated from protobuf field bool is_preemptible = 6;
     * @param bool $var
     * @return $this
     */
    public function setIsPreemptible($var)
    {
        GPBUtil::checkBool($var);
        $this->is_preemptible = $var;

        return $this;
    }

    /**
     * Output-only. The config for Google Compute Engine Instance Group
     * Manager that manages this group.
     * This is only used for preemptible instance groups.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.ManagedGroupConfig managed_group_config = 7;
     * @return \Google\Cloud\Dataproc\V1\ManagedGroupConfig
     */
    public function getManagedGroupConfig()
    {
        return $this->managed_group_config;
    }

    /**
     * Output-only. The config for Google Compute Engine Instance Group
     * Manager that manages this group.
     * This is only used for preemptible instance groups.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.ManagedGroupConfig managed_group_config = 7;
     * @param \Google\Cloud\Dataproc\V1\ManagedGroupConfig $var
     * @return $this
     */
    public function setManagedGroupConfig($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dataproc\V1\ManagedGroupConfig::class);
        $this->managed_group_config = $var;

        return $this;
    }

    /**
     * Optional. The Google Compute Engine accelerator configuration for these
     * instances.
     * **Beta Feature**: This feature is still under development. It may be
     * changed before final release.
     *
     * Generated from protobuf field repeated .google.cloud.dataproc.v1.AcceleratorConfig accelerators = 8;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getAccelerators()
    {
        return $this->accelerators;
    }

    /**
     * Optional. The Google Compute Engine accelerator configuration for these
     * instances.
     * **Beta Feature**: This feature is still under development. It may be
     * changed before final release.
     *
     * Generated from protobuf field repeated .google.cloud.dataproc.v1.AcceleratorConfig accelerators = 8;
     * @param \Google\Cloud\Dataproc\V1\AcceleratorConfig[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setAccelerators($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dataproc\V1\AcceleratorConfig::class);
        $this->accelerators = $arr;

        return $this;
    }

}


text:
(function() {

  var dojo = {};
  exports.dojo = dojo;

	var _getParts = function(arr, obj, cb){
		return [
			(dojo.isString(arr) ? arr.split("") : arr),
			(obj||dojo.global),
			// FIXME: cache the anonymous functions we create here?
			(dojo.isString(cb) ? (new Function("item", "index", "array", cb)) : cb)
		];
	}

  dojo.isString = function(/*anything*/ it){
    // summary:	Return true if it is a String
    return typeof it == "string" || it instanceof String; // Boolean
  }

  dojo.isArray = function(/*anything*/ it){
    // summary: Return true if it is an Array
    return it && it instanceof Array || typeof it == "array" ||
      (dojo.NodeList && it instanceof dojo.NodeList); // Boolean
  }

  /*=====
  dojo.isFunction = function(it){
    // summary: Return true if it is a Function
    // it: anything
  }
  =====*/

  dojo.isFunction = (function(){
    var _isFunction = function(/*anything*/ it){
      return typeof it == "function" || it instanceof Function; // Boolean
    };

    return dojo.isSafari ?
      // only slow this down w/ gratuitious casting in Safari since it's what's b0rken
      function(/*anything*/ it){
        if(typeof it == "function" && it == "[object NodeList]"){ return false; }
        return _isFunction(it); // Boolean
      } : _isFunction;
  })();

  dojo.isObject = function(/*anything*/ it){
    // summary:
    //		Returns true if it is a JavaScript object (or an Array, a Function or null)
    return it !== undefined &&
      (it === null || typeof it == "object" || dojo.isArray(it) || dojo.isFunction(it)); // Boolean
  }

  dojo.isArrayLike = function(/*anything*/ it){
    // return:
    //		If it walks like a duck and quicks like a duck, return true
    var d = dojo;
    return it && it !== undefined &&
      // keep out built-in constructors (Number, String, ...) which have length
      // properties
      !d.isString(it) && !d.isFunction(it) &&
      !(it.tagName && it.tagName.toLowerCase() == 'form') &&
      (d.isArray(it) || isFinite(it.length)); // Boolean
  }

  dojo.isAlien = function(/*anything*/ it){
    // summary:
    //		Returns true if it is a built-in function or some other kind of
    //		oddball that *should* report as a function but doesn't
    return it && !dojo.isFunction(it) && /\{\s*\[native code\]\s*\}/.test(String(it)); // Boolean
  }

  dojo._mixin = function(/*Object*/ obj, /*Object*/ props){
    // summary:
    //		Adds all properties and methods of props to obj. This addition is
    //		"prototype extension safe", so that instances of objects will not
    //		pass along prototype defaults.
    var tobj = {};
    for(var x in props){
      // the "tobj" condition avoid copying properties in "props"
      // inherited from Object.prototype.  For example, if obj has a custom
      // toString() method, don't overwrite it with the toString() method
      // that props inherited from Object.prototype
      if(tobj[x] === undefined || tobj[x] != props[x]){
        obj[x] = props[x];
      }
    }
    // IE doesn't recognize custom toStrings in for..in
    if(dojo.isIE && props){
      var p = props.toString;
      if(typeof p == "function" && p != obj.toString && p != tobj.toString &&
        p != "\nfunction toString() {\n    [native code]\n}\n"){
          obj.toString = props.toString;
      }
    }
    return obj; // Object
  }

  dojo.mixin = function(/*Object*/obj, /*Object...*/props){
    // summary:	Adds all properties and methods of props to obj.
    for(var i=1, l=arguments.length; i<l; i++){
      dojo._mixin(obj, arguments[i]);
    }
    return obj; // Object
  }

  dojo.extend = function(/*Object*/ constructor, /*Object...*/ props){
    // summary:
    //		Adds all properties and methods of props to constructor's
    //		prototype, making them available to all instances created with
    //		constructor.
    for(var i=1, l=arguments.length; i<l; i++){
      dojo._mixin(constructor.prototype, arguments[i]);
    }
    return constructor; // Object
  }

  dojo._hitchArgs = function(scope, method /*,...*/){
    var pre = dojo._toArray(arguments, 2);
    var named = dojo.isString(method);
    return function(){
      // arrayify arguments
      var args = dojo._toArray(arguments);
      // locate our method
      var f = named ? (scope||dojo.global)[method] : method;
      // invoke with collected args
      return f && f.apply(scope || this, pre.concat(args)); // Any
    } // Function
  }

  dojo.hitch = function(/*Object*/scope, /*Function|String*/method /*,...*/){
    // summary:
    //		Returns a function that will only ever execute in the a given scope.
    //		This allows for easy use of object member functions
    //		in callbacks and other places in which the "this" keyword may
    //		otherwise not reference the expected scope.
    //		Any number of default positional arguments may be passed as parameters
    //		beyond "method".
    //		Each of these values will be used to "placehold" (similar to curry)
    //		for the hitched function.
    // scope:
    //		The scope to use when method executes. If method is a string,
    //		scope is also the object containing method.
    // method:
    //		A function to be hitched to scope, or the name of the method in
    //		scope to be hitched.
    // usage:
    //		dojo.hitch(foo, "bar")(); // runs foo.bar() in the scope of foo
    //		dojo.hitch(foo, myFunction); // returns a function that runs myFunction in the scope of foo
    if(arguments.length > 2){
      return dojo._hitchArgs.apply(dojo, arguments); // Function
    }
    if(!method){
      method = scope;
      scope = null;
    }
    if(dojo.isString(method)){
      scope = scope || dojo.global;
      if(!scope[method]){ throw(['dojo.hitch: scope["', method, '"] is null (scope="', scope, '")'].join('')); }
      return function(){ return scope[method].apply(scope, arguments || []); }; // Function
    }
    return !scope ? method : function(){ return method.apply(scope, arguments || []); }; // Function
  }

  dojo._delegate = function(obj, props){
    // boodman/crockford delegation
    function TMP(){};
    TMP.prototype = obj;
    var tmp = new TMP();
    if(props){
      dojo.mixin(tmp, props);
    }
    return tmp; // Object
  }

  dojo.partial = function(/*Function|String*/method /*, ...*/){
    // summary:
    //		similar to hitch() except that the scope object is left to be
    //		whatever the execution context eventually becomes. This is the
    //		functional equivalent of calling:
    //		dojo.hitch(null, funcName, ...);
    var arr = [ null ];
    return dojo.hitch.apply(dojo, arr.concat(dojo._toArray(arguments))); // Function
  }

  dojo._toArray = function(/*Object*/obj, /*Number?*/offset){
    // summary:
    //		Converts an array-like object (i.e. arguments, DOMCollection)
    //		to an array. Returns a new Array object.
    var arr = [];
    for(var x = offset || 0; x < obj.length; x++){
      arr.push(obj[x]);
    }
    return arr; // Array
  }

  dojo.clone = function(/*anything*/ o){
    // summary:
    //		Clones objects (including DOM nodes) and all children.
    //		Warning: do not clone cyclic structures.
    if(!o){ return o; }
    if(dojo.isArray(o)){
      var r = [];
      for(var i = 0; i < o.length; ++i){
        r.push(dojo.clone(o[i]));
      }
      return r; // Array
    }else if(dojo.isObject(o)){
      if(o.nodeType && o.cloneNode){ // isNode
        return o.cloneNode(true); // Node
      }else{
        var r = new o.constructor(); // specific to dojo.declare()'d classes!
        for(var i in o){
          if(!(i in r) || r[i] != o[i]){
            r[i] = dojo.clone(o[i]);
          }
        }
        return r; // Object
      }
    }
    return o; /*anything*/
  }

  dojo.trim = function(/*String*/ str){
    // summary: trims whitespaces from both sides of the string
    // description:
    //	This version of trim() was selected for inclusion into the base
    //	due to its compact size and relatively good performance (see Steven Levithan's blog:
    //	http://blog.stevenlevithan.com/archives/faster-trim-javascript).
    //	The fastest but longest version of this function is going to be placed in dojo.string.
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');	// String
  }

	dojo.mixin(dojo, {
		indexOf: function(	/*Array*/		array,
							/*Object*/		value,
							/*Integer?*/	fromIndex,
							/*Boolean?*/	findLast){
			// summary:
			//		locates the first index of the provided value in the
			//		passed array. If the value is not found, -1 is returned.
			// description:
			//		For details on this method, see:
			// 			http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf

			var i = 0, step = 1, end = array.length;
			if(findLast){
				i = end - 1;
				step = end = -1;
			}
			for(i = fromIndex || i; i != end; i += step){
				if(array[i] == value){ return i; }
			}
			return -1;	// number
		},

		lastIndexOf: function(/*Array*/array, /*Object*/value, /*Integer?*/fromIndex){
			// summary:
			//		locates the last index of the provided value in the passed array.
			//		If the value is not found, -1 is returned.
			// description:
			//		For details on this method, see:
			// 			http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:lastIndexOf
			return dojo.indexOf(array, value, fromIndex, true); // number
		},

		forEach: function(/*Array*/arr, /*Function*/callback, /*Object?*/obj){
			// summary:
			//		for every item in arr, call callback with that item as its
			//		only parameter.
			// description:
			//		Return values are ignored. This function
			//		corresponds (and wraps) the JavaScript 1.6 forEach method. For
			//		more details, see:
			//			http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:forEach

			// match the behavior of the built-in forEach WRT empty arrs
			if(!arr || !arr.length){ return; }

			// FIXME: there are several ways of handilng thisObject. Is
			// dojo.global always the default context?
			var _p = _getParts(arr, obj, callback); arr = _p[0];
			for(var i=0,l=_p[0].length; i<l; i++){
				_p[2].call(_p[1], arr[i], i, arr);
			}
		},

		_everyOrSome: function(/*Boolean*/every, /*Array*/arr, /*Function*/callback, /*Object?*/obj){
			var _p = _getParts(arr, obj, callback); arr = _p[0];
			for(var i = 0, l = arr.length; i < l; i++){
				var result = !!_p[2].call(_p[1], arr[i], i, arr);
				if(every ^ result){
					return result; // Boolean
				}
			}
			return every; // Boolean
		},

		every: function(/*Array*/arr, /*Function*/callback, /*Object?*/thisObject){
			// summary:
			//		determines whether or not every item in the array satisfies the
			//		condition implemented by callback. thisObject may be used to
			//		scope the call to callback. The function signature is derived
			//		from the JavaScript 1.6 Array.every() function. More
			//		information on this can be found here:
			//			http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:every
			// usage:
			//		dojo.every([1, 2, 3, 4], function(item){ return item>1; });
			//		// returns false
			//		dojo.every([1, 2, 3, 4], function(item){ return item>0; });
			//		// returns true
			return this._everyOrSome(true, arr, callback, thisObject); // Boolean
		},

		some: function(/*Array*/arr, /*Function*/callback, /*Object?*/thisObject){
			// summary:
			//		determines whether or not any item in the array satisfies the
			//		condition implemented by callback. thisObject may be used to
			//		scope the call to callback. The function signature is derived
			//		from the JavaScript 1.6 Array.some() function. More
			//		information on this can be found here:
			//			http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:some
			// examples:
			//		dojo.some([1, 2, 3, 4], function(item){ return item>1; });
			//		// returns true
			//		dojo.some([1, 2, 3, 4], function(item){ return item<1; });
			//		// returns false
			return this._everyOrSome(false, arr, callback, thisObject); // Boolean
		},

		map: function(/*Array*/arr, /*Function*/func, /*Function?*/obj){
			// summary:
			//		applies a function to each element of an Array and creates
			//		an Array with the results
			// description:
			//		Returns a new array constituted from the return values of
			//		passing each element of arr into unary_func. The obj parameter
			//		may be passed to enable the passed function to be called in
			//		that scope.  In environments that support JavaScript 1.6, this
			//		function is a passthrough to the built-in map() function
			//		provided by Array instances. For details on this, see:
			// 			http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:map
			// usage:
			//		dojo.map([1, 2, 3, 4], function(item){ return item+1 });
			//		// returns [2, 3, 4, 5]
			var _p = _getParts(arr, obj, func); arr = _p[0];
			var outArr = ((arguments[3]) ? (new arguments[3]()) : []);
			for(var i=0;i<arr.length;++i){
				outArr.push(_p[2].call(_p[1], arr[i], i, arr));
			}
			return outArr; // Array
		},

		filter: function(/*Array*/arr, /*Function*/callback, /*Object?*/obj){
			// summary:
			//		returns a new Array with those items from arr that match the
			//		condition implemented by callback. ob may be used to
			//		scope the call to callback. The function signature is derived
			//		from the JavaScript 1.6 Array.filter() function.
			//
			//		More information on the JS 1.6 API can be found here:
			//			http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:filter
			// examples:
			//		dojo.filter([1, 2, 3, 4], function(item){ return item>1; });
			//		// returns [2, 3, 4]

			var _p = _getParts(arr, obj, callback); arr = _p[0];
			var outArr = [];
			for(var i = 0; i < arr.length; i++){
				if(_p[2].call(_p[1], arr[i], i, arr)){
					outArr.push(arr[i]);
				}
			}
			return outArr; // Array
		}
	});

  dojo.fromJson = function(/*String*/ json){
    // summary:
    // 		evaluates the passed string-form of a JSON object
    // json:
    //		a string literal of a JSON item, for instance:
    //			'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'
    // return:
    //		the result of the evaluation

    // FIXME: should this accept mozilla's optional second arg?
    try {
      return eval("(" + json + ")");
    }catch(e){
      console.debug(e);
      return json;
    }
  }

  dojo._escapeString = function(/*String*/str){
    //summary:
    //		Adds escape sequences for non-visual characters, double quote and
    //		backslash and surrounds with double quotes to form a valid string
    //		literal.
    return ('"' + str.replace(/(["\\])/g, '\\$1') + '"'
      ).replace(/[\f]/g, "\\f"
      ).replace(/[\b]/g, "\\b"
      ).replace(/[\n]/g, "\\n"
      ).replace(/[\t]/g, "\\t"
      ).replace(/[\r]/g, "\\r"); // string
  }

  dojo.toJsonIndentStr = "\t";
  dojo.toJson = function(/*Object*/ it, /*Boolean?*/ prettyPrint, /*String?*/ _indentStr){
    // summary:
    //		Create a JSON serialization of an object.
    //		Note that this doesn't check for infinite recursion, so don't do that!
    //
    // it:
    //		an object to be serialized. Objects may define their own
    //		serialization via a special "__json__" or "json" function
    //		property. If a specialized serializer has been defined, it will
    //		be used as a fallback.
    //
    // prettyPrint:
    //		if true, we indent objects and arrays to make the output prettier.
    //		The variable dojo.toJsonIndentStr is used as the indent string
    //		-- to use something other than the default (tab),
    //		change that variable before calling dojo.toJson().
    //
    // _indentStr:
    //		private variable for recursive calls when pretty printing, do not use.
    //
    // return:
    //		a String representing the serialized version of the passed object.

    _indentStr = _indentStr || "";
    var nextIndent = (prettyPrint ? _indentStr + dojo.toJsonIndentStr : "");
    var newLine = (prettyPrint ? "\n" : "");
    var objtype = typeof(it);
    if(objtype == "undefined"){
      return "undefined";
    }else if((objtype == "number")||(objtype == "boolean")){
      return it + "";
    }else if(it === null){
      return "null";
    }
    if(objtype == "string"){ return dojo._escapeString(it); }
    // recurse
    var recurse = arguments.callee;
    // short-circuit for objects that support "json" serialization
    // if they return "self" then just pass-through...
    var newObj;
    if(typeof it.__json__ == "function"){
      newObj = it.__json__();
      if(it !== newObj){
        return recurse(newObj, prettyPrint, nextIndent);
      }
    }
    if(typeof it.json == "function"){
      newObj = it.json();
      if(it !== newObj){
        return recurse(newObj, prettyPrint, nextIndent);
      }
    }
    // array
    if(dojo.isArray(it)){
      var res = [];
      for(var i = 0; i < it.length; i++){
        var val = recurse(it[i], prettyPrint, nextIndent);
        if(typeof(val) != "string"){
          val = "undefined";
        }
        res.push(newLine + nextIndent + val);
      }
      return "[" + res.join(", ") + newLine + _indentStr + "]";
    }
    /*
    // look in the registry
    try {
      window.o = it;
      newObj = dojo.json.jsonRegistry.match(it);
      return recurse(newObj, prettyPrint, nextIndent);
    }catch(e){
      // console.debug(e);
    }
    // it's a function with no adapter, skip it
    */
    if(objtype == "function"){
      return null;
    }
    // generic object code path
    var output = [];
    for(var key in it){
      var keyStr;
      if(typeof(key) == "number"){
        keyStr = '"' + key + '"';
      }else if(typeof(key) == "string"){
        keyStr = dojo._escapeString(key);
      }else{
        // skip non-string or number keys
        continue;
      }
      val = recurse(it[key], prettyPrint, nextIndent);
      if(typeof(val) != "string"){
        // skip non-serializable values
        continue;
      }
      // FIXME: use += on Moz!!
      //	 MOW NOTE: using += is a pain because you have to account for the dangling comma...
      output.push(newLine + nextIndent + keyStr + ": " + val);
    }
    return "{" + output.join(", ") + newLine + _indentStr + "}";
  }
})();


text:
""" Presenter views, Html BluesteelWorker page functions """

import os
import zipfile
import json
from django.conf import settings
from django.http import HttpResponse
from app.logic.httpcommon import res
from app.presenter.views.helpers import ViewUrlGenerator

def zip_folder_and_return_path(path_to_compress, path_destination, name_destination, settings_obj):
    """ Compress a folder and return the path of the resulting zip file """
    if not os.path.exists(path_destination):
        os.makedirs(path_destination)

    path_final = os.path.join(path_destination, name_destination)

    rel_root = os.path.abspath(path_to_compress)
    with zipfile.ZipFile(path_final, "w", zipfile.ZIP_DEFLATED) as zip_file:
        zip_file.writestr(os.path.join('core', 'settings.json'), json.dumps(settings_obj))
        exclude = set(['tmp'])
        for root, dirs, files in os.walk(path_to_compress, topdown=True):
            dirs[:] = [exc_d for exc_d in dirs if exc_d not in exclude]
            zip_file.write(root, os.path.relpath(root, rel_root))
            for fil in files:
                file_name = os.path.join(root, fil)
                if os.path.isfile(file_name) and file_name.endswith('.py'):
                    archive_name = os.path.join(os.path.relpath(root, rel_root), fil)
                    zip_file.write(file_name, archive_name)

    return path_final

def get_worker(request):
    """ Returns the worker scripts compressed in a zip file """
    if request.method != 'GET':
        return res.get_template_data(request, 'presenter/not_found.html', {})

    settings_obj = {}
    settings_obj['entry_point'] = ViewUrlGenerator.get_worker_entry_point_full_url(request.get_host())
    settings_obj['tmp_path'] = ['..', 'tmp', 'worker_tmp']

    path_final = zip_folder_and_return_path(
        os.path.join(settings.BASE_DIR, '..', 'app', 'logic', 'bluesteelworker', 'download'),
        os.path.join(settings.TMP_ROOT, 'zip'),
        'BluesteelWorker.zip',
        settings_obj
    )

    myfile = open(path_final, "rb")

    # print('----> type:',type(myfile.read()))

    response = HttpResponse(myfile.read(), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=BluesteelWorker.zip'
    myfile.close()
    return response


text:
package com.fteams.siftrain.screens;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.fteams.siftrain.assets.Assets;
import com.fteams.siftrain.assets.GlobalConfiguration;
import com.fteams.siftrain.assets.SimpleSongLoader;
import com.fteams.siftrain.entities.SimpleSong;

public class BeatmapLoadingScreen implements Screen {
    private Image backgroundImage = new Image(Assets.mainMenuBackgroundTexture);
    private Stage stage = new Stage();
    private Label validationResult = new Label("Loaded Beatmap Successfully!", Assets.menuSkin, "song_style_result");
    private Label errorLabel = new Label("Errors:", Assets.menuSkin, "song_style_result");
    private Label warningsLabel = new Label("Warnings:", Assets.menuSkin, "song_style_result");
    private TextButton back = new TextButton("Back", Assets.menuSkin, "item1");
    private TextButton play = new TextButton("Play", Assets.menuSkin, "item1");

    float loadingTime = 2f;
    boolean valid;
    boolean warnings;

    @Override
    public void show() {
        float scaleFactor = stage.getHeight() / GlobalConfiguration.BASE_HEIGHT;
        warnings = false;
        backgroundImage.setHeight(stage.getHeight());
        backgroundImage.setWidth(stage.getWidth());
        stage.addActor(backgroundImage);

        SimpleSongLoader loader = new SimpleSongLoader();
        SimpleSong song = loader.loadSong(Assets.selectedBeatmap);

        Table table = new Table();
        table.setX(stage.getWidth() * 0.15f);
        table.setY(stage.getHeight() * 0.15f);

        table.setWidth(stage.getWidth() * 0.7f);
        table.setHeight(stage.getHeight() * 0.7f);
        valid = song.getValid();

        if (song.getValid()) {
            table.add(validationResult).colspan(2).padBottom(stage.getHeight() * 0.04f).row();

            if (!loader.getWarnings().isEmpty()) {
                warnings = true;
                Table warningTable = new Table(Assets.menuSkin);
                warningTable.setWidth(stage.getWidth() * 0.7f);
                warningTable.setHeight(stage.getHeight() * 0.25f);
                table.add(warningsLabel).left().fillX().row();
                for (String warning : loader.getWarnings()) {
                    Label warningLabel = new Label(warning, Assets.menuSkin, "song_style_result");
                    warningLabel.setFontScale(scaleFactor);
                    errorLabel.setWrap(true);
                    warningTable.add(warningLabel).width(stage.getWidth() * 0.7f).left().fillX().row();
                }
                ScrollPane warningPane = new ScrollPane(warningTable);
                table.add(warningPane).row();
            }
            Assets.setSelectedSong(song);

            table.add(play).row();
            table.add(back).row();
        } else {
            table.add(errorLabel).left().fillX().colspan(2).row();
            Table errorTable = new Table(Assets.menuSkin);
            errorTable.setWidth(stage.getWidth() * 0.7f);
            errorTable.setHeight(stage.getHeight() * 0.25f);
            for (String error : loader.getErrors()) {
                Label errorLabel = new Label(error, Assets.menuSkin, "song_style_result");
                errorLabel.setFontScale(scaleFactor);
                errorLabel.setWrap(true);
                errorTable.add(errorLabel).width(stage.getWidth() * 0.7f).left().fillX().row();
            }
            ScrollPane errorPane = new ScrollPane(errorTable);
            table.add(errorPane).width(stage.getWidth() * 0.7f).height(stage.getHeight() * 0.25f).row();

            if (!loader.getWarnings().isEmpty()) {
                Table warningTable = new Table(Assets.menuSkin);
                warningTable.setWidth(stage.getWidth() * 0.7f);
                warningTable.setHeight(stage.getHeight() * 0.25f);
                table.add(warningsLabel).left().fillX().row();
                for (String warning : loader.getWarnings()) {
                    Label warningLabel = new Label(warning, Assets.menuSkin, "song_style_result");
                    warningLabel.setFontScale(scaleFactor);
                    warningLabel.setWrap(true);
                    warningTable.add(warningLabel).width(stage.getWidth() * 0.7f).left().fillX().row();
                }
                ScrollPane warningPane = new ScrollPane(warningTable);
                table.add(warningPane).width(stage.getWidth() * 0.7f).height(stage.getHeight() * 0.25f).row();
            }

            table.add(back).width(stage.getWidth() * 0.2f).height(stage.getHeight() * 0.1f).row();
            table.add().fill().expand();

        }

        back.addListener(new ClickListener() {
            public void clicked(InputEvent event, float x, float y) {
                ((Game) Gdx.app.getApplicationListener()).setScreen(new SongSelectionScreen());
            }
        });

        play.addListener(new ClickListener() {
            public void clicked(InputEvent event, float x, float y) {
                ((Game) Gdx.app.getApplicationListener()).setScreen(new SongScreen());
            }
        });

        stage.addActor(table);
        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        loadingTime -= delta;
        if (loadingTime <= 0 && !warnings) {
            if (valid) {
                ((Game) Gdx.app.getApplicationListener()).setScreen(new SongScreen());

            }
        }

        stage.act();
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
    }

}


text:
package azgo

// JobPriorityType is a structure to represent a job-priority ZAPI object
type JobPriorityType = string


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Leptostroma avellanense Tognini

### Remarks
null


text:
package util

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"reflect"
	"regexp"
	"strconv"
	"strings"
)

// Takes a list of strings and compiles them into a list of regular expressions
func CompileRegexps(regexpStrings []string) ([]*regexp.Regexp, error) {
	regexps := []*regexp.Regexp{}
	for _, regexpStr := range regexpStrings {
		r, err := regexp.Compile(regexpStr)
		if err != nil {
			return []*regexp.Regexp{}, err
		}
		regexps = append(regexps, r)
	}
	return regexps, nil
}

// Detects if using systemd as the init system
// Please note that simply reading /proc/1/cmdline can be misleading because
// some installation of various init programs can automatically make /sbin/init
// a symlink or even a renamed version of their main program.
// TODO(dchen1107): realiably detects the init system using on the system:
// systemd, upstart, initd, etc.
func UsingSystemdInitSystem() bool {
	if _, err := os.Stat("/run/systemd/system"); err == nil {
		return true
	}

	return false
}

// Tests whether all pointer fields in a struct are nil.  This is useful when,
// for example, an API struct is handled by plugins which need to distinguish
// "no plugin accepted this spec" from "this spec is empty".
//
// This function is only valid for structs and pointers to structs.  Any other
// type will cause a panic.  Passing a typed nil pointer will return true.
func AllPtrFieldsNil(obj interface{}) bool {
	v := reflect.ValueOf(obj)
	if !v.IsValid() {
		panic(fmt.Sprintf("reflect.ValueOf() produced a non-valid Value for %#v", obj))
	}
	if v.Kind() == reflect.Ptr {
		if v.IsNil() {
			return true
		}
		v = v.Elem()
	}
	for i := 0; i < v.NumField(); i++ {
		if v.Field(i).Kind() == reflect.Ptr && !v.Field(i).IsNil() {
			return false
		}
	}
	return true
}

func FileExists(filename string) (bool, error) {
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return false, nil
	} else if err != nil {
		return false, err
	}
	return true, nil
}

// borrowed from ioutil.ReadDir
// ReadDir reads the directory named by dirname and returns
// a list of directory entries, minus those with lstat errors
func ReadDirNoExit(dirname string) ([]os.FileInfo, []error, error) {
	if dirname == "" {
		dirname = "."
	}

	f, err := os.Open(dirname)
	if err != nil {
		return nil, nil, err
	}
	defer f.Close()

	names, err := f.Readdirnames(-1)
	list := make([]os.FileInfo, 0, len(names))
	errs := make([]error, 0, len(names))
	for _, filename := range names {
		fip, lerr := os.Lstat(dirname + "/" + filename)
		if os.IsNotExist(lerr) {
			// File disappeared between readdir + stat.
			// Just treat it as if it didn't exist.
			continue
		}

		list = append(list, fip)
		errs = append(errs, lerr)
	}

	return list, errs, nil
}

// IntPtr returns a pointer to an int
func IntPtr(i int) *int {
	o := i
	return &o
}

// IntPtrDerefOr dereference the int ptr and returns it i not nil,
// else returns def.
func IntPtrDerefOr(ptr *int, def int) int {
	if ptr != nil {
		return *ptr
	}
	return def
}

// Convert cpu from string to hex
// e.g.
// 			   Binary       Hex
//    CPU 0    0001         1
//    CPU 1    0010         2
//    CPU 2    0100         4
//    CPU 3    1000         8
func HexCpuSet(cpuSet string) (string, error) {
	if cpuSet == "" {
		return "", fmt.Errorf("Cpu Set must be not null")
	}
	var value uint64 = 0
	for _, core := range strings.Split(cpuSet, ",") {
		fCore, err := strconv.ParseFloat(core, 64)
		if err != nil {
			return "", err
		}
		value ^= uint64(math.Pow(2, fCore))
	}

	return strconv.FormatUint(value, 16), nil
}

func ChangeXFSProject(filtPath, stringToAppend, filter string) error {
	var lines []string
	rf, err := os.OpenFile(filtPath, os.O_RDONLY|os.O_CREATE, 0600)
	defer rf.Close()
	if err != nil {
		return err
	}
	buf := bufio.NewReader(rf)
	for {
		line, _ := buf.ReadString('\n')
		line = strings.Trim(line, "\r\n")
		if line == "" {
			break
		}
		if ok, _ := regexp.MatchString(filter, line); !ok {
			lines = append(lines, line)
		}
	}
	if stringToAppend != "" {
		lines = append(lines, stringToAppend)
	}
	wf, err := os.OpenFile(filtPath, os.O_WRONLY|os.O_TRUNC|os.O_SYNC, 0600)
	defer wf.Close()
	if err != nil {
		return err
	}
	_, err = wf.WriteString(strings.Join(lines, "\n"))
	if err != nil {
		return err
	}

	return nil
}


text:
(function () {
var advlist = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var applyListFormat = function (editor, listName, styleValue) {
    var cmd = listName === 'UL' ? 'InsertUnorderedList' : 'InsertOrderedList';
    editor.execCommand(cmd, false, styleValue === false ? null : { 'list-style-type': styleValue });
  };
  var $_331vcs7sjfjlpc8y = { applyListFormat: applyListFormat };

  var register = function (editor) {
    editor.addCommand('ApplyUnorderedListStyle', function (ui, value) {
      $_331vcs7sjfjlpc8y.applyListFormat(editor, 'UL', value['list-style-type']);
    });
    editor.addCommand('ApplyOrderedListStyle', function (ui, value) {
      $_331vcs7sjfjlpc8y.applyListFormat(editor, 'OL', value['list-style-type']);
    });
  };
  var $_8d0pha7rjfjlpc8x = { register: register };

  var getNumberStyles = function (editor) {
    var styles = editor.getParam('advlist_number_styles', 'default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman');
    return styles ? styles.split(/[ ,]/) : [];
  };
  var getBulletStyles = function (editor) {
    var styles = editor.getParam('advlist_bullet_styles', 'default,circle,disc,square');
    return styles ? styles.split(/[ ,]/) : [];
  };
  var $_1ru1s7ujfjlpc93 = {
    getNumberStyles: getNumberStyles,
    getBulletStyles: getBulletStyles
  };

  var isChildOfBody = function (editor, elm) {
    return editor.$.contains(editor.getBody(), elm);
  };
  var isTableCellNode = function (node) {
    return node && /^(TH|TD)$/.test(node.nodeName);
  };
  var isListNode = function (editor) {
    return function (node) {
      return node && /^(OL|UL|DL)$/.test(node.nodeName) && isChildOfBody(editor, node);
    };
  };
  var getSelectedStyleType = function (editor) {
    var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
    return editor.dom.getStyle(listElm, 'listStyleType') || '';
  };
  var $_fiqopu7vjfjlpc94 = {
    isTableCellNode: isTableCellNode,
    isListNode: isListNode,
    getSelectedStyleType: getSelectedStyleType
  };

  var styleValueToText = function (styleValue) {
    return styleValue.replace(/\-/g, ' ').replace(/\b\w/g, function (chr) {
      return chr.toUpperCase();
    });
  };
  var toMenuItems = function (styles) {
    return global$1.map(styles, function (styleValue) {
      var text = styleValueToText(styleValue);
      var data = styleValue === 'default' ? '' : styleValue;
      return {
        text: text,
        data: data
      };
    });
  };
  var $_ditb7e7wjfjlpc96 = { toMenuItems: toMenuItems };

  var findIndex = function (list, predicate) {
    for (var index = 0; index < list.length; index++) {
      var element = list[index];
      if (predicate(element)) {
        return index;
      }
    }
    return -1;
  };
  var listState = function (editor, listName) {
    return function (e) {
      var ctrl = e.control;
      editor.on('NodeChange', function (e) {
        var tableCellIndex = findIndex(e.parents, $_fiqopu7vjfjlpc94.isTableCellNode);
        var parents = tableCellIndex !== -1 ? e.parents.slice(0, tableCellIndex) : e.parents;
        var lists = global$1.grep(parents, $_fiqopu7vjfjlpc94.isListNode(editor));
        ctrl.active(lists.length > 0 && lists[0].nodeName === listName);
      });
    };
  };
  var updateSelection = function (editor) {
    return function (e) {
      var listStyleType = $_fiqopu7vjfjlpc94.getSelectedStyleType(editor);
      e.control.items().each(function (ctrl) {
        ctrl.active(ctrl.settings.data === listStyleType);
      });
    };
  };
  var addSplitButton = function (editor, id, tooltip, cmd, nodeName, styles) {
    editor.addButton(id, {
      active: false,
      type: 'splitbutton',
      tooltip: tooltip,
      menu: $_ditb7e7wjfjlpc96.toMenuItems(styles),
      onPostRender: listState(editor, nodeName),
      onshow: updateSelection(editor),
      onselect: function (e) {
        $_331vcs7sjfjlpc8y.applyListFormat(editor, nodeName, e.control.settings.data);
      },
      onclick: function () {
        editor.execCommand(cmd);
      }
    });
  };
  var addButton = function (editor, id, tooltip, cmd, nodeName, styles) {
    editor.addButton(id, {
      active: false,
      type: 'button',
      tooltip: tooltip,
      onPostRender: listState(editor, nodeName),
      onclick: function () {
        editor.execCommand(cmd);
      }
    });
  };
  var addControl = function (editor, id, tooltip, cmd, nodeName, styles) {
    if (styles.length > 0) {
      addSplitButton(editor, id, tooltip, cmd, nodeName, styles);
    } else {
      addButton(editor, id, tooltip, cmd, nodeName, styles);
    }
  };
  var register$1 = function (editor) {
    addControl(editor, 'numlist', 'Numbered list', 'InsertOrderedList', 'OL', $_1ru1s7ujfjlpc93.getNumberStyles(editor));
    addControl(editor, 'bullist', 'Bullet list', 'InsertUnorderedList', 'UL', $_1ru1s7ujfjlpc93.getBulletStyles(editor));
  };
  var $_41xwzu7tjfjlpc8z = { register: register$1 };

  global.add('advlist', function (editor) {
    var hasPlugin = function (editor, plugin) {
      var plugins = editor.settings.plugins ? editor.settings.plugins : '';
      return global$1.inArray(plugins.split(/[ ,]/), plugin) !== -1;
    };
    if (hasPlugin(editor, 'lists')) {
      $_41xwzu7tjfjlpc8z.register(editor);
      $_8d0pha7rjfjlpc8x.register(editor);
    }
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


text:
<?php

namespace Phine\Example;

use ArrayIterator;
use DateTime;
use Phine\Example\Exception\ExampleException;

/**
 * This is an example class that fills in the blanks left by `AbstractExample`.
 *
 * @author Kevin Herrera <kevin@herrera.io>
 */
final class Example extends AbstractExample
{
    /**
     * The "on" or "off" flag.
     *
     * This property accepts either the `ON` or `OFF` constants from the
     * `ExampleInterface` interface. It also solely exists to demonstrate
     * what a long description for a property will look like in the
     * documentation.
     *
     * @var boolean[]|integer
     */
    public $state;

    /**
     * The arguments provided.
     *
     * @var array
     */
    private $args = array(null, null, null);

    /**
     * {@inheritDoc}
     */
    public function count()
    {
        return 123;
    }

    /**
     * {@inheritDoc}
     */
    final public static function create()
    {
        return new self();
    }

    /**
     * {@inheritDoc}
     */
    public function getArgs()
    {
        return $this->args;
    }

    /**
     * Returns an array of `DateTime` instances.
     *
     * @return DateTime[] The dates.
     */
    public function getDates()
    {
        return array(
            new DateTime(),
            new DateTime(),
            new DateTime(),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function getIterator()
    {
        return new ArrayIterator(array());
    }

    /**
     * Returns a random argument.
     *
     * @return boolean|integer|string A random argument.
     */
    public function getRandom()
    {
        return $this->args[rand(0, count($this->args) - 1)];
    }

    /**
     * {@inheritDoc}
     */
    public function setArgs($boolean, $integer, $string)
    {
        $this->args = array($boolean, $integer, $string);
    }

    /**
     * {@inheritDoc}
     */
    protected function doSetCreatedDate($created)
    {
        if (is_integer($created)) {
            $created = new DateTime("@$created");
        } elseif (!($created instanceof DateTime)) {
            throw new ExampleException(
                '$created must be an integer or instance of DateTime.'
            );
        }

        $this->created = $created;
    }
}


text:
using FMStudio.App.Interfaces;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace FMStudio.App.Controls
{
    public partial class ProjectTree : UserControl
    {
        public ProjectTree()
        {
            InitializeComponent();
        }

        private void trvProjects_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var dependencyObject = (DependencyObject)e.OriginalSource;
                var treeViewItem = dependencyObject.FindAncestor<TreeViewItem>();

                if (treeViewItem != null)
                {
                    var projectItem = treeViewItem.Header as ICanBeDragged;

                    if (projectItem != null)
                    {
                        var dragData = new DataObject(EventConstants.DRAGDROP_DATA, projectItem);
                        DragDrop.DoDragDrop(treeViewItem, dragData, DragDropEffects.Move);
                    }
                }
            }
        }

        private void trvProjects_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(EventConstants.DRAGDROP_DATA))
            {
                var draggable = e.Data.GetData(EventConstants.DRAGDROP_DATA) as ICanBeDragged;
                var dependencyObject = (DependencyObject)e.OriginalSource;
                var treeViewItem = dependencyObject.FindAncestor<TreeViewItem>();

                if (treeViewItem != null)
                {
                    var dropTarget = treeViewItem.Header as ICanBeDroppedUpon;
                    if (dropTarget != null && dropTarget != draggable)
                        dropTarget.Drop(draggable);
                }
                else
                {
                    var root = DataContext as ICanBeDroppedUpon;
                    if (root != null)
                        root.Drop(draggable);
                }
            }
        }

        private void trvProjects_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var treeViewItem = ((DependencyObject)e.OriginalSource).FindAncestor<TreeViewItem>();

            if (treeViewItem != null)
            {
                treeViewItem.Focus();
                e.Handled = true;
            }
        }
    }
}