text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class UriExtensions
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class UriExtensions
   ">
    <meta name="generator" content="docfx 2.16.2.2">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class UriExtensions

Extension methods for URLs

Inheritance

Object

UriExtensions

Inherited Members

                  Object.Equals(Object)

                  Object.Equals(Object, Object)

                  Object.GetHashCode()

                  Object.GetType()

                  Object.MemberwiseClone()

                  Object.ReferenceEquals(Object, Object)

                  Object.ToString()

Namespace:FubarDev.WebDavServer

Assembly:FubarDev.WebDavServer.dll

Syntax

public static class UriExtensions

Methods

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_UriExtensions_Append_System_Uri_FubarDev_WebDavServer_FileSystem_ICollection_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.UriExtensions.Append(System.Uri%2CFubarDev.WebDavServer.FileSystem.ICollection)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

Append(Uri, ICollection)

Appends the name of a collection to the baseUri

Declaration

public static Uri Append(this Uri baseUri, ICollection entry)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    baseUri

The base URL to append the entry name to

                    ICollection
                    entry

The ICollection whose name to append to the baseUri

Returns

                    Type
                    Description

                    Uri

The baseUri with the entry name appended.

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_UriExtensions_Append_System_Uri_FubarDev_WebDavServer_FileSystem_IDocument_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.UriExtensions.Append(System.Uri%2CFubarDev.WebDavServer.FileSystem.IDocument)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

Append(Uri, IDocument)

Appends the name of a document to the baseUri

Declaration

public static Uri Append(this Uri baseUri, IDocument entry)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    baseUri

The base URL to append the entry name to

                    IDocument
                    entry

The IDocument whose name to append to the baseUri

Returns

                    Type
                    Description

                    Uri

The baseUri with the entry name appended.

                |
                Improve this Doc

                View Source

Append(Uri, IEntry)

Append the name of an entry to the baseUri

Declaration

public static Uri Append(this Uri baseUri, IEntry entry)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    baseUri

The base URL to append the entry name to

                    IEntry
                    entry

The IEntry whose name to append to the baseUri

Returns

                    Type
                    Description

                    Uri

The baseUri with the entry name appended.

                |
                Improve this Doc

                View Source

Append(Uri, String, Boolean)

Append a relative URL to the baseUri

Declaration

public static Uri Append(this Uri baseUri, string relative, bool isEscaped)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    baseUri

The base URL to append the relative URI to

                    String
                    relative

The relative URL to append to the baseUri

                    Boolean
                    isEscaped

Is the relative URL already escaped?

Returns

                    Type
                    Description

                    Uri

The baseUri with the appended relative URL.

Remarks

When the relative URL isn't escaped, then it MUST NOT contain a path separator.

                |
                Improve this Doc

                View Source

Append(Uri, Uri)

Append a relative URI to the baseUri

Declaration

public static Uri Append(this Uri baseUri, Uri relativeUri)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    baseUri

The base URL to append the relativeUri to

                    Uri
                    relativeUri

The relative URL to append to the baseUri

Returns

                    Type
                    Description

                    Uri

The baseUri with the appended relativeUri.

                |
                Improve this Doc

                View Source

AppendDirectory(Uri, String)

Appends a collection name to the baseUri

Declaration

public static Uri AppendDirectory(this Uri baseUri, string collectionName)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    baseUri

The base URL to append the name to

                    String
                    collectionName

The collection name to append

Returns

                    Type
                    Description

                    Uri

The baseUri with the appended name.

                |
                Improve this Doc

                View Source

GetCollectionUri(Uri)

Gets the collection URL.

Declaration

public static Uri GetCollectionUri(this Uri url)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    url

The URL to get the collection for

Returns

                    Type
                    Description

                    Uri

The collection URL

Remarks

This is different from GetParent(Uri), because this function returns
the same URL if the url is already an URL to a collection.

                |
                Improve this Doc

                View Source

GetName(Uri)

Gets the name of the collection or document URL

Declaration

public static string GetName(this Uri url)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    url

The collection or document URL

Returns

                    Type
                    Description

                    String

The name of the collection or document URL

                |
                Improve this Doc

                View Source

GetParent(Uri)

Gets the URL of the containing collection of a collection or document URL

Declaration

public static Uri GetParent(this Uri url)

Parameters

                    Type
                    Name
                    Description

                    Uri
                    url

The URL to get the parent URL for

Returns

                    Type
                    Description

                    Uri

The URL of the containing collection

                |
                Improve this Doc

                View Source

UriEscape(String)

Escapes the string in a WebDAV compatible way

Declaration

public static string UriEscape(this string s)

Parameters

                    Type
                    Name
                    Description

                    String
                    s

The string to escape

Returns

                    Type
                    Description

                    String

The escaped string

                    Improve this Doc

                    View Source

              Back to top

            Copyright © 2016-2017 Fubar Development Junker
Generated by DocFX

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.devopsguru.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Information about an Amazon Web Services resource that emitted and event that is related to a recommendation in an
 * insight.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RecommendationRelatedEventResource implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The name of the resource that emitted the event. This corresponds to the Name field in an
     * EventResource object.
     *

     */
    private String name;
    /**
     *

     * The type of the resource that emitted the event. This corresponds to the Type field in an
     * EventResource object.
     *

     */
    private String type;

    /**
     *

     * The name of the resource that emitted the event. This corresponds to the Name field in an
     * EventResource object.
     *

     *
     * @param name
     *        The name of the resource that emitted the event. This corresponds to the Name field in an
     *        EventResource object.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * The name of the resource that emitted the event. This corresponds to the Name field in an
     * EventResource object.
     *

     *
     * @return The name of the resource that emitted the event. This corresponds to the Name field in an
     *         EventResource object.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * The name of the resource that emitted the event. This corresponds to the Name field in an
     * EventResource object.
     *

     *
     * @param name
     *        The name of the resource that emitted the event. This corresponds to the Name field in an
     *        EventResource object.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public RecommendationRelatedEventResource withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * The type of the resource that emitted the event. This corresponds to the Type field in an
     * EventResource object.
     *

     *
     * @param type
     *        The type of the resource that emitted the event. This corresponds to the Type field in an
     *        EventResource object.
     */

    public void setType(String type) {
        this.type = type;
    }

    /**
     *

     * The type of the resource that emitted the event. This corresponds to the Type field in an
     * EventResource object.
     *

     *
     * @return The type of the resource that emitted the event. This corresponds to the Type field in an
     *         EventResource object.
     */

    public String getType() {
        return this.type;
    }

    /**
     *

     * The type of the resource that emitted the event. This corresponds to the Type field in an
     * EventResource object.
     *

     *
     * @param type
     *        The type of the resource that emitted the event. This corresponds to the Type field in an
     *        EventResource object.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public RecommendationRelatedEventResource withType(String type) {
        setType(type);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getType() != null)
            sb.append("Type: ").append(getType());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof RecommendationRelatedEventResource == false)
            return false;
        RecommendationRelatedEventResource other = (RecommendationRelatedEventResource) obj;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getType() == null ^ this.getType() == null)
            return false;
        if (other.getType() != null && other.getType().equals(this.getType()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode());
        return hashCode;
    }

    @Override
    public RecommendationRelatedEventResource clone() {
        try {
            return (RecommendationRelatedEventResource) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.devopsguru.model.transform.RecommendationRelatedEventResourceMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
/**
 * @file libsvm_analyzer.cpp
 * @author Sean Massung
 */

#include <sstream>

#include "corpus/document.h"
#include "io/libsvm_parser.h"
#include "analyzers/libsvm_analyzer.h"

namespace meta
{
namespace analyzers
{

const std::string libsvm_analyzer::id = "libsvm";

void libsvm_analyzer::tokenize(corpus::document& doc)
{
    for (auto& count_pair : io::libsvm_parser::counts(doc.content(), false))
        doc.increment(std::to_string(count_pair.first), count_pair.second);

    // label info is inside the document content for libsvm format; the line
    // corpus will not set it since it's not in a separate file
    doc.label(io::libsvm_parser::label(doc.content()));
}
}
}


text:
Given /^debugging the external server is activated$/ do
  @debugging = true
end

Given /^an external XML\-RPC server is running$/ do
  @server = XMLRPC::Server.new(8080)
  @service_thread = Thread.new {
    puts @server.serve()
  }
end

Given /^the external server has a method "([^\"]*)" defined following this scheme:$/ do |name, table|
  headers = table.headers
  n_arguments = headers.length - 1
  interface_table = {}
  table.rows.each do |row|
    args = row[0...n_arguments].map { |cell| process_arg(cell) }
    interface_table[args] = process_arg(row[n_arguments])
  end

  puts interface_table.inspect
  interface = Class.new do
    define_method(name) do |*args|
      interface_table[args]
    end
  end
  @server.add_handler("test", interface.new)
end


text:
set -xe

./prepare_node_devstack.sh

# Install Xen and update the kernel
sudo apt-get -y install htop vim git pwgen xen-hypervisor-4.4

sudo mv /etc/default/grub{,.bak}
sudo tee /etc/default/grub << EOC
GRUB_DEFAULT=0
GRUB_TIMEOUT=30
GRUB_DISTRIBUTOR=\`lsb_release -i -s 2> /dev/null || echo Debian\`
GRUB_CMDLINE_LINUX_DEFAULT="debug loglevel=7"
GRUB_CMDLINE_LINUX=""
GRUB_TERMINAL=console
GRUB_DISABLE_LINUX_UUID="false"
EOC

sudo mv /etc/default/grub.d/xen.cfg{,.bak}
sudo tee /etc/default/grub.d/xen.cfg << EOC
echo "Including Xen overrides from /etc/default/grub.d/xen.cfg"
GRUB_CMDLINE_XEN="dom0_mem=7680M,max:7680M dom0_max_vcpus=4 max-console=vga"
GRUB_DEFAULT="Ubuntu GNU/Linux, with Xen hypervisor"
EOC

sudo update-grub

# Disable cloud-init - it doesn't work in dom0 Xen
for i in /etc/init/cloud-*; do echo manual | sudo tee ${i%.conf}.override; done

# Install Monty's config drive network setup (from https://review.openstack.org/#/c/154132/5)
# ./read-vendor-json/install.d/05-read-vendor-json
sudo cp read-vendor-json.py /usr/local/bin
sudo cp static-network-config /etc/init.d

# ./read-vendor-json/install.d/10-static-network-config
sudo tee /etc/init/write-network-interfaces.conf <<EOF
start on starting networking
task
exec /etc/init.d/static-network-config
EOF

# ./read-vendor-json/install.d/15-write-interfaces
sudo rm -rf /etc/network/interfaces.d
sudo tee /etc/network/interfaces <<EOF
auto lo
iface lo inet loopback
EOF

# Create a swap file
sudo dd if=/dev/zero of=/swapfile bs=1024 count=524288
sudo chown root:root /swapfile
sudo chmod 0600 /swapfile
sudo mkswap /swapfile
echo "/swapfile	none	swap	sw	0	0" | sudo tee -a /etc/fstab

sync
sleep 5


text:
'use strict';

const Joi = require('joi');

const base = {
  'PBFPubKey': Joi.string().required(),
  'amount': Joi.number().allow(''),
  'customer_email': Joi.string().email().allow(''),
  'currency': Joi.string().empty('').default('NGN'),
  'country': Joi.string().empty('').default('NG'),
  'custom_title': Joi.string().allow(''),
  'custom_description': Joi.string().allow(''),
  'redirect_url': Joi.string().uri().empty('').default(''),
  'payment_plan_id': Joi.number().allow('').default(''),
  'payment_options': Joi.string().empty('').allow(''),
  'subaccounts': Joi.array().allow('',[]).default([]),
  'custom_logo': Joi.string().uri().empty('').default(''),
  'liveMode': Joi.string() // not saved intentionally since it's only used on "npm start"
};

const dynamicFields = {
  'customer_email': Joi.string().email()
};

module.exports = {
  base, dynamicFields
};


text:
package flex.management.runtime.messaging.endpoints;

import java.util.Date;

import flex.management.BaseControl;
import flex.management.runtime.AdminConsoleTypes;
import flex.messaging.endpoints.BaseStreamingHTTPEndpoint;

/**
 * The StreamingEndpointControl class is the base MBean implementation
 * for monitoring and managing a BaseStreamingHTTPEndpoint at runtime.
 */
public abstract class StreamingEndpointControl extends EndpointControl implements
        StreamingEndpointControlMBean
{
    private int pushCount;
    private Date lastPushTimeStamp;
    private long pushStart;

    /**
     * Constructs a StreamingEndpointControl, assigning managed message
     * endpoint and parent MBean.
     *
     * @param endpoint The BaseStreamingHTTPEndpoint managed by this MBean.
     * @param parent The parent MBean in the management hierarchy.
     */
    public StreamingEndpointControl(BaseStreamingHTTPEndpoint endpoint, BaseControl parent)
    {
        super(endpoint, parent);
    }

    protected void onRegistrationComplete()
    {
        super.onRegistrationComplete();

        String name = this.getObjectName().getCanonicalName();
        String[] generalPollables = { "LastPushTimestamp", "PushCount", "PushFrequency", "StreamingClientsCount"};

        getRegistrar().registerObjects(AdminConsoleTypes.ENDPOINT_POLLABLE, name, generalPollables);
        getRegistrar().registerObject(AdminConsoleTypes.ENDPOINT_SCALAR, name, "MaxStreamingClients");
    }

    /*
     *  (non-Javadoc)
     * @see flex.management.runtime.messaging.endpoints.StreamingEndpointControlMBean#getMaxStreamingClients()
     */
    public Integer getMaxStreamingClients()
    {
        int maxStreamingClientsCount = ((BaseStreamingHTTPEndpoint)endpoint).getMaxStreamingClients();
        return new Integer(maxStreamingClientsCount);
    }

    /*
     *  (non-Javadoc)
     * @see flex.management.runtime.messaging.endpoints.StreamingEndpointControlMBean#getPushCount()
     */
    public Integer getPushCount()
    {
        return new Integer(pushCount);
    }

    /*
     *  (non-Javadoc)
     * @see flex.management.runtime.messaging.endpoints.StreamingEndpointControlMBean#resetPushCount()
     */
    public void resetPushCount()
    {
        pushStart = System.currentTimeMillis();
        pushCount = 0;
        lastPushTimeStamp = null;
    }

    /**
     * Increments the count of messages pushed by the endpoint.
     */
    public void incrementPushCount()
    {
        ++pushCount;
        lastPushTimeStamp = new Date();
    }

    /*
     *  (non-Javadoc)
     * @see flex.management.runtime.messaging.endpoints.StreamingEndpointControlMBean#getLastPushTimestamp()
     */
    public Date getLastPushTimestamp()
    {
        return lastPushTimeStamp;
    }

    /*
     *  (non-Javadoc)
     * @see flex.management.runtime.messaging.endpoints.StreamingEndpointControlMBean#getPushFrequency()
     */
    public Double getPushFrequency()
    {
        if (pushCount > 0)
        {
            double runtime = differenceInMinutes(pushStart, System.currentTimeMillis());
            return new Double(pushCount/runtime);
        }
        else
        {
            return new Double(0);
        }
    }

    /*
     *  (non-Javadoc)
     * @see flex.management.runtime.messaging.endpoints.StreamingEndpointControlMBean#isRunning()
     */
    public Integer getStreamingClientsCount()
    {
        int streamingClientsCount = ((BaseStreamingHTTPEndpoint)endpoint).getStreamingClientsCount();
        return new Integer(streamingClientsCount);
    }
}


text:
package com.amazonaws.services.ec2.model;

/**
 *

 *
 *

 */
public class DescribeCustomerGatewaysResult {

    /**
     *
     */
    private java.util.List<CustomerGateway> customerGateways;

    /**
     *
     *
     * @return
     */
    public java.util.List<CustomerGateway> getCustomerGateways() {

        if (customerGateways == null) {
            customerGateways = new java.util.ArrayList<CustomerGateway>();
        }
        return customerGateways;
    }

    /**
     *
     *
     * @param customerGateways
     */
    public void setCustomerGateways(java.util.Collection<CustomerGateway> customerGateways) {
        if (customerGateways == null) {
            this.customerGateways = null;
            return;
        }

        java.util.List<CustomerGateway> customerGatewaysCopy = new java.util.ArrayList<CustomerGateway>(customerGateways.size());
        customerGatewaysCopy.addAll(customerGateways);
        this.customerGateways = customerGatewaysCopy;
    }

    /**
     *
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param customerGateways
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DescribeCustomerGatewaysResult withCustomerGateways(CustomerGateway... customerGateways) {
        if (getCustomerGateways() == null) setCustomerGateways(new java.util.ArrayList<CustomerGateway>(customerGateways.length));
        for (CustomerGateway value : customerGateways) {
            getCustomerGateways().add(value);
        }
        return this;
    }

    /**
     *
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param customerGateways
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DescribeCustomerGatewaysResult withCustomerGateways(java.util.Collection<CustomerGateway> customerGateways) {
        if (customerGateways == null) {
            this.customerGateways = null;
        } else {
            java.util.List<CustomerGateway> customerGatewaysCopy = new java.util.ArrayList<CustomerGateway>(customerGateways.size());
            customerGatewaysCopy.addAll(customerGateways);
            this.customerGateways = customerGatewaysCopy;
        }

        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (customerGateways != null) sb.append("CustomerGateways: " + customerGateways + ", ");
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getCustomerGateways() == null) ? 0 : getCustomerGateways().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof DescribeCustomerGatewaysResult == false) return false;
        DescribeCustomerGatewaysResult other = (DescribeCustomerGatewaysResult)obj;

        if (other.getCustomerGateways() == null ^ this.getCustomerGateways() == null) return false;
        if (other.getCustomerGateways() != null && other.getCustomerGateways().equals(this.getCustomerGateways()) == false) return false;
        return true;
    }

}


text:
echo ""
echo "============== USAGE =============="
echo ""
echo ". deploy.sh"
echo ""
echo "==================================="
echo ""

git checkout master
git pull --rebase
make dist
git checkout dev5-deploy
git rebase master
git push --force

tar czf olgm.tar.gz \
  node_modules/openlayers/build/ol.js \
  node_modules/openlayers/build/ol.css \
  node_modules/openlayers/css/ol.css \
  css \
  dist/ol3gm.js \
  examples

scp olgm.tar.gz dev5.mapgears.com:
rm olgm.tar.gz

git checkout master


text:
@interface NSObject
- (id)copy; // expected-note {{method 'copy' declared here}}
- (id) test __attribute__((ns_returns_retained)); // expected-note {{method 'test' declared here}}
+ (id) new ; // expected-note {{method 'new' declared here}}
- (id) init __attribute__((ns_returns_not_retained));
- (id)PlusZero;
- (id)PlusOne __attribute__((ns_returns_retained)); // expected-note {{method 'PlusOne' declared here}}
@end

@interface I : NSObject
{
  SEL sel1;
}
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
@end

@implementation I
- (id) Meth {
  return [self performSelector : @selector(copy)]; // expected-error {{performSelector names a selector which retains the object}}
  return [self performSelector : @selector(test)]; // expected-error {{performSelector names a selector which retains the object}}
  return [self performSelector : @selector(new)]; // expected-error {{performSelector names a selector which retains the object}}
  return [self performSelector : @selector(init)];
  return [self performSelector : sel1]; // expected-warning {{performSelector may cause a leak because its selector is unknown}} \
					// expected-note {{used here}}

  return [self performSelector : @selector(PlusZero)];
  return [self performSelector : @selector(PlusOne)]; // expected-error {{performSelector names a selector which retains the object}}
}

- (id)performSelector:(SEL)aSelector { return 0; }
- (id)performSelector:(SEL)aSelector withObject:(id)object { return 0; }
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2 { return 0; }
@end


text:
/*
 * DocuSign REST API
 *
 * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
 *
 * OpenAPI spec version: v2
 * Contact: devcenter@docusign.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;

namespace DocuSign.eSign.Model
{
    /// <summary>
    /// Contains information about mutiple API request logs.
    /// </summary>
    [DataContract]
    public partial class ApiRequestLogsResult :  IEquatable<ApiRequestLogsResult>, IValidatableObject
    {
        public ApiRequestLogsResult()
        {
            // Empty Constructor
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ApiRequestLogsResult" /> class.
        /// </summary>
        /// <param name="ApiRequestLogs">Reserved: TBD.</param>
        public ApiRequestLogsResult(List<ApiRequestLog> ApiRequestLogs = default(List<ApiRequestLog>))
        {
            this.ApiRequestLogs = ApiRequestLogs;
        }

        /// <summary>
        /// Reserved: TBD
        /// </summary>
        /// <value>Reserved: TBD</value>
        [DataMember(Name="apiRequestLogs", EmitDefaultValue=false)]
        public List<ApiRequestLog> ApiRequestLogs { get; set; }
        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class ApiRequestLogsResult {\n");
            sb.Append("  ApiRequestLogs: ").Append(ApiRequestLogs).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as ApiRequestLogsResult);
        }

        /// <summary>
        /// Returns true if ApiRequestLogsResult instances are equal
        /// </summary>
        /// <param name="other">Instance of ApiRequestLogsResult to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(ApiRequestLogsResult other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return
                (
                    this.ApiRequestLogs == other.ApiRequestLogs ||
                    this.ApiRequestLogs != null &&
                    this.ApiRequestLogs.SequenceEqual(other.ApiRequestLogs)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)
                if (this.ApiRequestLogs != null)
                    hash = hash * 59 + this.ApiRequestLogs.GetHashCode();
                return hash;
            }
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            yield break;
        }
    }

}


text:
@implementation DoraemonNetFlowDataSource{
    dispatch_semaphore_t semaphore;
}

+ (DoraemonNetFlowDataSource *)shareInstance{
    static dispatch_once_t once;
    static DoraemonNetFlowDataSource *instance;
    dispatch_once(&once, ^{
        instance = [[DoraemonNetFlowDataSource alloc] init];
    });
    return instance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        _httpModelArray = [NSMutableArray array];
        semaphore = dispatch_semaphore_create(1);
    }
    return self;
}

- (void)addHttpModel:(DoraemonNetFlowHttpModel *)httpModel{
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    [_httpModelArray insertObject:httpModel atIndex:0];
    dispatch_semaphore_signal(semaphore);
}

- (void)clear{
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    [_httpModelArray removeAllObjects];
    dispatch_semaphore_signal(semaphore);
}

@end


text:
<?php
 if(!isset($_SESSION)){
    session_start();
}
session_destroy();
header("Location: ../../../login.php");
exit;


text:
package org.metaworks.widget;

public class Accordion {

	private String title;
	private Object content;
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public Object getContent() {
		return content;
	}
	public void setContent(Object content) {
		this.content = content;
	}

	public Accordion(){}

	public Accordion(String title){
		this.title = title;
	}

	public Accordion(String title,Object content) {
		this.title = title;
		this.content = content;
	}

}


text:
using content::DownloadManager;
using content::WebContents;

namespace {

ChromeWebUIDataSource* CreateDownloadsUIHTMLSource() {
  ChromeWebUIDataSource* source =
      new ChromeWebUIDataSource(chrome::kChromeUIDownloadsHost);

  source->AddLocalizedString("title", IDS_DOWNLOAD_TITLE);
  source->AddLocalizedString("searchbutton", IDS_DOWNLOAD_SEARCH_BUTTON);
  source->AddLocalizedString("searchresultsfor", IDS_DOWNLOAD_SEARCHRESULTSFOR);
  source->AddLocalizedString("downloads", IDS_DOWNLOAD_TITLE);
  source->AddLocalizedString("clear_all", IDS_DOWNLOAD_LINK_CLEAR_ALL);
  source->AddLocalizedString("open_downloads_folder",
                             IDS_DOWNLOAD_LINK_OPEN_DOWNLOADS_FOLDER);

  // Status.
  source->AddLocalizedString("status_cancelled", IDS_DOWNLOAD_TAB_CANCELED);
  source->AddLocalizedString("status_removed", IDS_DOWNLOAD_FILE_REMOVED);
  source->AddLocalizedString("status_paused", IDS_DOWNLOAD_PROGRESS_PAUSED);
  source->AddLocalizedString("status_interrupted",
                             IDS_DOWNLOAD_PROGRESS_INTERRUPTED);

  // Dangerous file.
  source->AddLocalizedString("danger_file_desc", IDS_PROMPT_DANGEROUS_DOWNLOAD);
  source->AddLocalizedString("danger_url_desc",
                             IDS_PROMPT_MALICIOUS_DOWNLOAD_URL);
  source->AddLocalizedString("danger_content_desc",
                             IDS_PROMPT_MALICIOUS_DOWNLOAD_CONTENT);
  source->AddLocalizedString("danger_uncommon_desc",
                             IDS_PROMPT_UNCOMMON_DOWNLOAD_CONTENT);
  source->AddLocalizedString("danger_save", IDS_CONFIRM_DOWNLOAD);
  source->AddLocalizedString("danger_discard", IDS_DISCARD_DOWNLOAD);

  // Controls.
  source->AddLocalizedString("control_pause", IDS_DOWNLOAD_LINK_PAUSE);
  if (browser_defaults::kDownloadPageHasShowInFolder) {
    source->AddLocalizedString("control_showinfolder", IDS_DOWNLOAD_LINK_SHOW);
  }
  source->AddLocalizedString("control_retry", IDS_DOWNLOAD_LINK_RETRY);
  source->AddLocalizedString("control_cancel", IDS_DOWNLOAD_LINK_CANCEL);
  source->AddLocalizedString("control_resume", IDS_DOWNLOAD_LINK_RESUME);
  source->AddLocalizedString("control_removefromlist",
                             IDS_DOWNLOAD_LINK_REMOVE);

  source->set_json_path("strings.js");
  source->add_resource_path("downloads.css", IDR_DOWNLOADS_CSS);
  source->add_resource_path("downloads.js", IDR_DOWNLOADS_JS);
  source->set_default_resource(IDR_DOWNLOADS_HTML);

  return source;
}

}  // namespace

///////////////////////////////////////////////////////////////////////////////
//
// DownloadsUI
//
///////////////////////////////////////////////////////////////////////////////

DownloadsUI::DownloadsUI(content::WebUI* web_ui) : WebUIController(web_ui) {
  Profile* profile = Profile::FromWebUI(web_ui);
  DownloadManager* dlm =
      DownloadServiceFactory::GetForProfile(profile)->GetDownloadManager();

  DownloadsDOMHandler* handler = new DownloadsDOMHandler(dlm);
  web_ui->AddMessageHandler(handler);

  // Set up the chrome://downloads/ source.
  profile->GetChromeURLDataManager()->AddDataSource(
      CreateDownloadsUIHTMLSource());
}

// static
RefCountedMemory* DownloadsUI::GetFaviconResourceBytes() {
  return ResourceBundle::GetSharedInstance().
      LoadDataResourceBytes(IDR_DOWNLOADS_FAVICON);
}


text:
using System;

namespace Tamir.SharpSsh.java.lang
{
	/// <summary>
	/// Summary description for Runnable.
	/// </summary>
	public interface Runnable
	{
		void run();
	}
}


text:
<!doctype html>
<html>
  <head>
    <title>
      Test Basic Oscillator Sine Wave Test
    </title>
    <script src="/resources/testharness.js"></script>
    <script src="/resources/testharnessreport.js"></script>
    <script src="/webaudio/resources/audit-util.js"></script>
    <script src="/webaudio/resources/audit.js"></script>
  </head>

  <body>
    <script>
      // Don't change the sample rate.  The tests below depend on this sample
      // rate to cover all the cases in Chrome's implementation.  But the tests
      // are general and apply to any browser.
      const sampleRate = 44100;

      // Only need a few samples for testing, so just use two renders.
      const durationFrames = 2 * RENDER_QUANTUM_FRAMES;

      let audit = Audit.createTaskRunner();

      // The following tests verify that the oscillator produces the same
      // results as the mathematical oscillators.  We choose sine wave and a
      // custom wave because we know they're bandlimited and won't change with
      // the frequency.
      //
      // The tests for 1 and 2 Hz are intended to test Chrome's interpolation
      // algorithm, but are still generally applicable to any browser.

      audit.define(
          {label: 'Test 0', description: 'Sine wave: 100 Hz'},
          async (task, should) => {
            let context = new OfflineAudioContext(
                {length: durationFrames, sampleRate: sampleRate});

            const freqHz = 100;

            let src =
                new OscillatorNode(context, {type: 'sine', frequency: freqHz});
            src.connect(context.destination);

            src.start();

            let renderedBuffer = await context.startRendering();
            checkResult(should, renderedBuffer, context, {
              freqHz: freqHz,
              a1: 0,
              b1: 1,
              prefix: 'Sine',
              threshold: 1.8045e-6,
              snrThreshold: 118.91
            });
            task.done();
          });

      audit.define(
          {label: 'Test 1', description: 'Sine wave: -100 Hz'},
          async (task, should) => {
            let context = new OfflineAudioContext(
                {length: durationFrames, sampleRate: sampleRate});

            const freqHz = -100;

            let src =
                new OscillatorNode(context, {type: 'sine', frequency: freqHz});
            src.connect(context.destination);

            src.start();

            let renderedBuffer = await context.startRendering();
            checkResult(should, renderedBuffer, context, {
              freqHz: freqHz,
              a1: 0,
              b1: 1,
              prefix: 'Sine',
              threshold: 4.7684e-7,
              snrThreshold: 130.95
            });
            task.done();
          });

      audit.define(
          {label: 'Test 2', description: 'Sine wave: 2 Hz'},
          async (task, should) => {
            let context = new OfflineAudioContext(
                {length: durationFrames, sampleRate: sampleRate});

            const freqHz = 2;

            let src =
                new OscillatorNode(context, {type: 'sine', frequency: freqHz});
            src.connect(context.destination);

            src.start();

            let renderedBuffer = await context.startRendering();
            checkResult(should, renderedBuffer, context, {
              freqHz: freqHz,
              a1: 0,
              b1: 1,
              prefix: 'Sine',
              threshold: 1.4516e-7,
              snrThreshold: 119.93
            });
            task.done();
          });

      audit.define(
          {label: 'Test 3', description: 'Sine wave: 1 Hz'},
          async (task, should) => {
            let context = new OfflineAudioContext(
                {length: durationFrames, sampleRate: sampleRate});

            const freqHz = 1;

            let src =
                new OscillatorNode(context, {type: 'sine', frequency: freqHz});
            src.connect(context.destination);

            src.start();

            let renderedBuffer = await context.startRendering();
            checkResult(should, renderedBuffer, context, {
              freqHz: freqHz,
              a1: 0,
              b1: 1,
              prefix: 'Sine',
              threshold: 1.4157e-7,
              snrThreshold: 112.22
            });
            task.done();
          });

      audit.define(
          {label: 'Test 4', description: 'Custom wave: 100 Hz'},
          async (task, should) => {
            let context = new OfflineAudioContext(
                {length: durationFrames, sampleRate: sampleRate});

            const freqHz = 100;

            let wave = new PeriodicWave(
                context,
                {real: [0, 1], imag: [0, 1], disableNormalization: true});
            let src = new OscillatorNode(
                context,
                {type: 'custom', frequency: freqHz, periodicWave: wave});
            src.connect(context.destination);

            src.start();

            let renderedBuffer = await context.startRendering();
            checkResult(should, renderedBuffer, context, {
              freqHz: freqHz,
              a1: 1,
              b1: 1,
              prefix: 'Custom',
              threshold: 1.8478e-6,
              snrThreshold: 122.43
            });
            task.done();
          });

      audit.define(
          {label: 'Test 5', description: 'Custom wave: 1 Hz'},
          async (task, should) => {
            let context = new OfflineAudioContext(
                {length: durationFrames, sampleRate: sampleRate});

            const freqHz = 1;

            let wave = new PeriodicWave(
                context,
                {real: [0, 1], imag: [0, 1], disableNormalization: true});
            let src = new OscillatorNode(
                context,
                {type: 'custom', frequency: freqHz, periodicWave: wave});
            src.connect(context.destination);

            src.start();

            let renderedBuffer = await context.startRendering();
            checkResult(should, renderedBuffer, context, {
              freqHz: freqHz,
              a1: 1,
              b1: 1,
              prefix: 'Custom',
              threshold: 4.7684e-7,
              snrThreshold: 138.76
            });
            task.done();
          });

      audit.run();

      function waveForm(context, freqHz, a1, b1, nsamples) {
        let buffer =
            new AudioBuffer({length: nsamples, sampleRate: context.sampleRate});
        let signal = buffer.getChannelData(0);
        const omega = 2 * Math.PI * freqHz / context.sampleRate;
        for (let k = 0; k < nsamples; ++k) {
          signal[k] = a1 * Math.cos(omega * k) + b1 * Math.sin(omega * k);
        }

        return buffer;
      }

      function checkResult(should, renderedBuffer, context, options) {
        let {freqHz, a1, b1, prefix, threshold, snrThreshold} = options;

        let actual = renderedBuffer.getChannelData(0);

        let expected =
            waveForm(context, freqHz, a1, b1, actual.length).getChannelData(0);

        should(actual, `${prefix}: ${freqHz} Hz`).beCloseToArray(expected, {
          absoluteThreshold: threshold
        });

        let snr = 10 * Math.log10(computeSNR(actual, expected));

        should(snr, `${prefix}: SNR (db)`).beGreaterThanOrEqualTo(snrThreshold);
      }
    </script>
  </body>
</html>


text:
namespace g{namespace Fuse{namespace Animations{struct Keyframe;}}}

namespace g{
namespace Fuse{
namespace Animations{

// internal abstract interface KeyframeTrack :2771
// {
uInterfaceType* KeyframeTrack_typeof();

struct KeyframeTrack
{
    void(*fp_get_Interpolation)(uObject*, int*);
    void(*fp_set_Interpolation)(uObject*, int*);
    void(*fp_get_Keyframes)(uObject*, uObject**);
    static int Interpolation(const uInterface& __this) { int __retval; return __this.VTable<KeyframeTrack>()->fp_get_Interpolation(__this, &__retval), __retval; }
    static void Interpolation(const uInterface& __this, int value) { __this.VTable<KeyframeTrack>()->fp_set_Interpolation(__this, &value); }
    static uObject* Keyframes(const uInterface& __this) { uObject* __retval; return __this.VTable<KeyframeTrack>()->fp_get_Keyframes(__this, &__retval), __retval; }
};
// }

}}} // ::g::Fuse::Animations


text:
<?php

namespace Metrique\Plonk\Support;

class PlonkMime
{
    public static function toExtension($mimeType)
    {
        switch ($mimeType) {
            case 'image/gif':
                return 'gif';
            break;

            case 'image/jpeg':
                return 'jpg';
            break;

            case 'image/png':
                return 'png';
            break;
        }

        return false;
    }

    public static function toMime($extension)
    {
        switch ($mimeType) {
            case 'gif':
                return 'image/gif';
            break;

            case 'jpg':
            case 'jpeg':
                return 'image/jpeg';
            break;

            case 'png':
                return 'image/png';
            break;
        }

        return false;
    }
}


text:
package org.eclipse.php.internal.server.core;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.*;

/**
 * Server helper class.
 */
public class ServerHelper {
	protected Map map;

	// property change listeners
	private transient List propertyListeners;
	private Server server;

	public ServerHelper(Server server) {
		this.map = new HashMap();
		this.server = server;
	}

	public void setAttribute(String attributeName, String value) {
		String current = getAttribute(attributeName, (String) null);
		if (current != null && current.equals(value))
			return;

		if (value == null)
			map.remove(attributeName);
		else
			map.put(attributeName, value);
		firePropertyChangeEvent(attributeName, current, value);
	}

	/**
	 * Add a property change listener to this server.
	 *
	 * @param listener
	 *            java.beans.PropertyChangeListener
	 */
	public void addPropertyChangeListener(PropertyChangeListener listener) {
		if (propertyListeners == null) {
			propertyListeners = new ArrayList(2);
		}
		propertyListeners.add(listener);
	}

	/**
	 * Remove a property change listener from this server.
	 *
	 * @param listener
	 *            java.beans.PropertyChangeListener
	 */
	public void removePropertyChangeListener(PropertyChangeListener listener) {
		if (propertyListeners != null) {
			propertyListeners.remove(listener);
		}
	}

	/**
	 * Fire a property change event.
	 *
	 * @param propertyName
	 *            a property name
	 * @param oldValue
	 *            the old value
	 * @param newValue
	 *            the new value
	 */
	public void firePropertyChangeEvent(String propertyName, Object oldValue,
			Object newValue) {
		if (propertyListeners == null)
			return;

		PropertyChangeEvent event = new PropertyChangeEvent(server,
				propertyName, oldValue, newValue);
		try {
			Iterator iterator = propertyListeners.iterator();
			while (iterator.hasNext()) {
				try {
					PropertyChangeListener listener = (PropertyChangeListener) iterator
							.next();
					listener.propertyChange(event);
				} catch (Exception e) {
					Logger
							.logException("Error firing property change event", //$NON-NLS-1$
									e);
				}
			}
		} catch (Exception e) {
			Logger.logException("Error in property event", e); //$NON-NLS-1$
		}
	}

	public String getAttribute(String attributeName, String defaultValue) {
		try {
			Object obj = map.get(attributeName);
			if (obj == null)
				return defaultValue;
			return (String) obj;
		} catch (Exception e) {
			// ignore
		}
		return defaultValue;
	}

	public void removeAttribute(String attributeName) {
		map.remove(attributeName);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((server == null) ? 0 : server.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ServerHelper other = (ServerHelper) obj;
		if (server == null) {
			if (other.server != null)
				return false;
		} else if (!server.equals(other.server))
			return false;
		return true;
	}
}


text:
package edu.uw.zookeeper.common;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.common.primitives.Shorts;

public class Hex {

    public static String toPaddedHexString(long value) {
        return toPaddedHexString(Long.toHexString(value), Longs.BYTES*2);
    }

    public static String toPaddedHexString(int value) {
        return toPaddedHexString(Integer.toHexString(value), Ints.BYTES*2);
    }

    public static String toPaddedHexString(short value) {
        return toPaddedHexString(Integer.toHexString(((int) value) & 0xffff), Shorts.BYTES*2);
    }

    public static String toPaddedHexString(String value, int length) {
        checkArgument(value.length() <= length);
        StringBuilder sb = new StringBuilder(length);
        for (int toPrepend=sb.capacity()-value.length(); toPrepend>0; --toPrepend) {
            sb.append('0');
        }
        sb.append(value);
        return sb.toString();
    }

    public static long parseLong(String string) {
        return Long.parseLong(string, 16);
    }

    public static int parseInt(String string) {
        return Integer.parseInt(string, 16);
    }

    public static short parseShort(String string) {
        return Short.parseShort(string, 16);
    }
}


text:
describe("unittests:: evaluation:: autoAccessors", () => {
    const editions = [
        { name: "es2022", target: ts.ScriptTarget.ES2022 },
        { name: "es2015", target: ts.ScriptTarget.ES2015 },
    ];
    for (const { name, target } of editions) {
        describe(name, () => {
            it("generates accessor pair", async () => {
                const { C } = evaluator.evaluateTypeScript(`
                    export class C {
                        accessor x;
                    }
                `, { target });

                const desc = Object.getOwnPropertyDescriptor(C.prototype, "x");
                assert.isDefined(desc);
                assert.isFunction(desc!.get);
                assert.isFunction(desc!.set);
            });

            it("storage is private", async () => {
                const { C } = evaluator.evaluateTypeScript(`
                    export class C {
                        accessor x;
                    }
                `, { target });

                const desc = Object.getOwnPropertyDescriptor(C.prototype, "x");
                const obj = Object.create(C.prototype);
                assert.throws(() => desc!.get!.call(obj), /private/);
            });

            it("getter and setter wrap same field", async () => {
                const { C } = evaluator.evaluateTypeScript(`
                    export class C {
                        accessor x;
                    }
                `, { target });
                const obj = new C();
                obj.x = 1;
                assert.equal(obj.x, 1);

                obj.x = 2;
                assert.equal(obj.x, 2);
            });

            it("supports initializer", async () => {
                const { C } = evaluator.evaluateTypeScript(`
                    export class C {
                        accessor x = 1;
                    }
                `, { target });
                const obj = new C();
                assert.equal(obj.x, 1);
            });

            it("legacy decorator can intercept getter/setter", async () => {
                const { actions, C } = evaluator.evaluateTypeScript(`
                    function dec(target, key, descriptor) {
                        const { get, set } = descriptor;
                        actions.push({ kind: "decorate", target, key });
                        descriptor.get = function() {
                            actions.push({ kind: "get", this: this });
                            return get.call(this);
                        };
                        descriptor.set = function(value) {
                            actions.push({ kind: "set", this: this, value });
                            set.call(this, value);
                        };
                    }
                    export const actions = [];
                    export class C {
                        @dec
                        accessor x;
                    }
                `, { target, experimentalDecorators: true });

                assert.deepEqual(actions, [
                    { kind: "decorate", target: C.prototype, key: "x" }
                ]);
                const obj = new C();
                obj.x = 1;
                assert.equal(obj.x, 1);
                assert.deepEqual(actions, [
                    { kind: "decorate", target: C.prototype, key: "x" },
                    { kind: "set", this: obj, value: 1 },
                    { kind: "get", this: obj },
                ]);
            });

            it("legacy decorator cannot intercept initializer", async () => {
                const { actions, C } = evaluator.evaluateTypeScript(`
                    function dec(target, key, descriptor) {
                        const { get, set } = descriptor;
                        descriptor.set = function(value) {
                            actions.push({ kind: "set", this: this, value });
                            set.call(this, value);
                        };
                    }
                    export const actions = [];
                    export class C {
                        @dec
                        accessor x = 1;
                    }
                `, { target, experimentalDecorators: true });

                const obj = new C();
                assert.equal(obj.x, 1);
                assert.deepEqual(actions, []);
            });
        });
    }
});


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    /// <summary>
    /// The interface IDirectoryObjectRequestBuilder.
    /// </summary>
    public partial interface IDirectoryObjectRequestBuilder : IEntityRequestBuilder
    {
        /// <summary>
        /// Builds the request.
        /// </summary>
        /// <returns>The built request.</returns>
        new IDirectoryObjectRequest Request();

        /// <summary>
        /// Builds the request.
        /// </summary>
        /// <param name="options">The query and header options for the request.</param>
        /// <returns>The built request.</returns>
        new IDirectoryObjectRequest Request(IEnumerable<Option> options);

        /// <summary>
        /// Gets the request builder for DirectoryObjectCheckMemberGroups.
        /// </summary>
        /// <returns>The <see cref="IDirectoryObjectCheckMemberGroupsRequestBuilder"/>.</returns>
        IDirectoryObjectCheckMemberGroupsRequestBuilder CheckMemberGroups(
            IEnumerable<string> groupIds);

        /// <summary>
        /// Gets the request builder for DirectoryObjectGetMemberGroups.
        /// </summary>
        /// <returns>The <see cref="IDirectoryObjectGetMemberGroupsRequestBuilder"/>.</returns>
        IDirectoryObjectGetMemberGroupsRequestBuilder GetMemberGroups(
            bool? securityEnabledOnly = null);

        /// <summary>
        /// Gets the request builder for DirectoryObjectGetMemberObjects.
        /// </summary>
        /// <returns>The <see cref="IDirectoryObjectGetMemberObjectsRequestBuilder"/>.</returns>
        IDirectoryObjectGetMemberObjectsRequestBuilder GetMemberObjects(
            bool? securityEnabledOnly = null);

    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?=$da['title']?></title>
<link rel="stylesheet" type="text/css" href="mode/bootstrap3.3/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="web/res/fontawesome/css/font-awesome.min.css">

<link rel="stylesheet" type="text/css" href="<?=$da['p']?>/css/webmain.css"/>
<link rel="stylesheet" type="text/css" href="<?=$da['p']?>/css/style<?=$da['style']?>.css" id="mainstylecss"/>
<link rel="stylesheet" type="text/css" href="web/res/mode/menu/jquery-rockmenu.css"/>
<link rel="stylesheet" type="text/css" href="mode/plugin/css/jquery-rockdatepicker.css"/>
<link rel="shortcut icon" href="favicon.ico" />

<?php if(isempt($da['homeurl'])){?>

				<?=TITLE?>

				<?php foreach($da['topmenu'] as $k=>$rs){?>
				<span pmenuid="<?=$rs['id']?>"><?php if($rs['icons']){?><i class="icon-<?=$rs['icons']?>"> <?php }?><?=$rs['name']?>
				<?php }?>

	<img src="<?=$da['face']?>" style="border:1px #cccccc solid;background:#ffffff;border-radius:15px;cursor:pointer;margin-right:10px" align="absmiddle" id="myface" height="30" width="30"><?=$da['adminname']?>
	<?php
	if(getconfig('reim_show',true))echo ' REIM ';
	if(getconfig('mobile_show', true))echo ' 手机版';
	?>

<?php }?>

	<?php if(isempt($da['homeurl'])){?>

							 栏目导航

打
开
导
航

	<?php }?>

>

<

<link rel="stylesheet" type="text/css" href="<?=$da['p']?>/css/animate.css"/>


text:
import pytest
import tempfile
import shutil
import io
import os
import sys
from contextlib import contextmanager

if sys.version_info >= (2,7):
    import subprocess
else:
    import subprocess32 as subprocess

# VERY important in this module to always pass the env kwarg
# to subprocesses. Somehow there are race conditions associated with
# modifying environment variables in the working environment

UN1 = 'baldwint'
PW1 = u'password'
TEST_CFG = u"""[login]
username=%s
url=http://localhost/~tkb/phplans/
"""
DEVNULL = io.open(os.devnull, 'w')

@contextmanager
def temp_clansdir(cfg=None, pwd=None, activate=True):
    """
    context for a throwaway clans directory.

    """
    clansdir = tempfile.mkdtemp(suffix='.clansprofile')
    env = make_env(clansdir)
    if cfg is not None:
        # if cfg is provided, pre-fill 'clans.cfg'
        clans_cfg = os.path.join(clansdir, 'clans.cfg')
        with io.open(clans_cfg, 'w') as f:
            f.write(cfg)
    if pwd is not None:
        # if password is given, log us in
        rc = subprocess.call(['clans', '-p', pwd, 'list'],
                env=env, stdout=DEVNULL)
    if activate:
        # make this the default clans directory
        environ_bak = os.environ.copy()
        os.environ['CLANS_DIR'] = clansdir

    yield clansdir

    # now tear down
    if activate:
        os.environ = environ_bak
    shutil.rmtree(clansdir)

def make_env(clansdir):
    myenv = os.environ.copy()
    myenv['CLANS_DIR'] = clansdir
    return myenv

def test_login():
    with temp_clansdir(TEST_CFG % UN1) as cd:
        env = make_env(cd)
        assert '%s.cookie' % UN1 not in os.listdir(cd)
        # log us in
        rc = subprocess.call(['clans', '-p', PW1, 'list'], env=env)
        assert rc == 0
        assert '%s.cookie' % UN1 in os.listdir(cd)
        # no password necessary
        rc = subprocess.call(['clans', 'list'], env=env)
        assert rc == 0
        # log us out
        rc = subprocess.call(['clans', 'list', '--logout'], env=env)
        assert rc == 0
        assert '%s.cookie' % UN1 not in os.listdir(cd)

def test_extension_loading():
    # load the backup extension just to see if it works
    with temp_clansdir(TEST_CFG % UN1, PW1) as cd:
        env = make_env(cd)
        stdout = subprocess.check_output('clans edit --help'.split(),
            stderr=subprocess.STDOUT, env=env)
        assert '--backup' not in str(stdout)
    # if we load the extension, it should modify the help list
    extend_cfg = TEST_CFG + "[extensions]\nbackup="
    with temp_clansdir(extend_cfg % UN1, PW1) as cd:
        env = make_env(cd)
        stdout = subprocess.check_output('clans edit --help'.split(),
            stderr=subprocess.STDOUT, env=env)
        assert '--backup' in str(stdout)

def test_newlove_breakage():
    # there was a bug where the newlove ext would break regular search
    with temp_clansdir(TEST_CFG % UN1, PW1) as cd:
        env = make_env(cd)
        rc = subprocess.call(['clans', 'search', 'term'], env=env)
        assert rc == 0
    extend_cfg = TEST_CFG + "[extensions]\nnewlove="
    with temp_clansdir(extend_cfg % UN1, PW1) as cd:
        env = make_env(cd)
        rc = subprocess.call(['clans', 'search', 'term'], env=env)
        assert rc == 0

@pytest.mark.parametrize("content", [
    "foobar",
    "barfoo\r\n"*20,  #TODO: what about \n?
])
def test_backup_restore(content):
    extend_cfg = TEST_CFG + "[extensions]\nbackup="
    with temp_clansdir(extend_cfg % UN1, PW1) as cd:
        env = make_env(cd)
        # set plan contents
        with tempfile.NamedTemporaryFile('w+') as tf:
            tf.write(content)
            tf.flush()
            stdout = subprocess.check_output(['clans', 'edit',
                '--from-file', tf.name], stderr=subprocess.STDOUT, env=env)
            assert 'Plan changed successfully' in str(stdout)
        # back plan up to file
        bakfile = os.path.join(cd, 'planbak.txt')
        rc = subprocess.call(['clans', 'edit',
            '--backup', bakfile, '--skip-update'], env=env)
        # check that it matches our contents
        with io.open(bakfile, 'r', encoding='utf8', newline='') as bak:
            backup = bak.read()
            assert backup == content
            # diff against stdout method
            stdout = subprocess.check_output(['clans', 'edit',
                '--backup', '--skip-update'], env=env)
            assert stdout.decode('utf8') == backup
        # verify the restore: if it matches, clans won't update
        stdout = subprocess.check_output(['clans', 'edit',
            '--from-file', bakfile], stderr=subprocess.STDOUT, env=env)
        assert 'plan unchanged, aborting update' in stdout.decode('utf8')

def test_editing():
    content = 'bar foo baz\r\n'
    expect = 'bar FOO baz\r\n'
    editor = 'vim -c s/foo/FOO/g -c wq'
    # subtle points: -c arguments to vim should NOT be quoted, as they
    # would be in a shell. Also, vim will insist that files end in
    # newlines if they don't already, so test values should accomodate
    # this ahead of time if our comparisons are going to match.
    # Finally, if the percent sign character appears anywhere in our
    # editor definition, all hell will break loose since both python
    # and ConfigParser can interpret that as part of a formatting
    # mini-language.
    extend_cfg = (TEST_CFG + "[extensions]\nbackup=")
    with temp_clansdir(extend_cfg % UN1, PW1) as cd:
        env = make_env(cd)
        env['EDITOR'] = editor
        # set plan contents
        with tempfile.NamedTemporaryFile('w+') as tf:
            tf.write(content)
            tf.flush()
            stdout = subprocess.check_output(['clans', 'edit',
                '--from-file', tf.name], stderr=subprocess.STDOUT, env=env)
        # do edit
        #with tempfile.NamedTemporaryFile() as tf:
        #    stdout = subprocess.check_output(['clans', 'edit'],
        #        stderr=subprocess.STDOUT, env=env)
        #    assert 'Plan changed successfully' in stdout
        # do edit, with backup extension
        with tempfile.NamedTemporaryFile('w+b') as tf:
            stdout = subprocess.check_output(['clans', 'edit',
                '--save', tf.name], stderr=subprocess.STDOUT, env=env)
            assert 'Plan changed successfully' in stdout.decode('utf8')
            # edit should have been saved by the backup extension
            tf.flush()
            tf.seek(0)
            assert expect == tf.read().decode('utf8')


text:
'use strict';

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(str) {
    return this.substr(0, str.length) === str;
  };
}

exports.sha = function(partialSha) {
  var self = {};

  self.equals = function(commit) {
    return commit.sha().startsWith(partialSha);
  };

  return self;
};

exports.constant = function(constant) {
  var self = {};

  self.equals = function(commit) {
    return constant;
  };

  return self;
};


text:
/* Getting Started */

/* nested links */
.gs-sidebar .nav .nav>li>a {
    font-size: 12px;
    padding: 4px 0 4px 15px;
    opacity: 0.8;
    font-weight: bold;
}/* nested navs */
.gs-sidebar .nav .nav {
    display: none;
}
/* nested active navs */
.gs-sidebar .nav .active .nav {
    display: block;
}
/* nested link icons */
.gs-sidebar .nav .nav>li>a i {
    display: none;
}
/* nested active link icons */
.gs-sidebar .nav .nav>.active>a i {
    display: inline-block;
}
/* active & hover links */
.gs-sidebar .nav>.active>a {
    font-weight: bold;
}
/* nested active links */
.gs-sidebar .nav .nav>.active>a {
    font-weight: bold;
}
/* affixed sidebar */
.gs-sidebar,
.gs-sidebar.affix,
.gs-sidebar.affix-top {
    position: fixed;
    top: 70px;
}
.affix-bottom {
    position: relative;
}

/* embedded video */
.gs-video {
    margin-top: 25px;
    margin-bottom: 25px;
    margin-left: auto;
    margin-right: auto;
    border: solid 1px #ddd;
    z-index: 99;
}

/* phase number counters */
.gs-count {
    margin-bottom: 20px;
    margin-top: 50px;
}


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.structuralsearch.plugin.ui;

import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * This is a temporary solution to extract Java-specific implementation from platform code. In order to implement creation of SSR templates
 * from code properly, we probably need to implement language-specific extensions.
 */
public class StructuralSearchTemplateBuilder {
  public static StructuralSearchTemplateBuilder getInstance() {
    return ApplicationManager.getApplication().getService(StructuralSearchTemplateBuilder.class);
  }

  public @Nullable TemplateBuilder buildTemplate(@NotNull PsiFile psiFile) {
    return null;
  }
}


text:
<?php

namespace Neducatio\TestBundle\Utility;

/**
 * Description of Registry
 */
class Registry
{
  private $store = array();

  /**
   * Store some value
   *
   * @param string $key   key
   * @param mixed  $value value
   */
  public function set($key, $value)
  {
    $this->store[$key] = $value;
  }

  /**
   * Get stored value
   *
   * @param string $key          key
   * @param mixed  $defaultValue default value
   *
   * @return mixed
   */
  public function get($key, $defaultValue = null)
  {
    if (array_key_exists($key, $this->store)) {

      return $this->store[$key];
    }

    return $defaultValue;
  }

  /**
   * Add value
   *
   * @param string $key   key
   * @param mixed  $value value
   */
  public function add($key, $value)
  {
    if (!array_key_exists($key, $this->store) || !is_array($this->store[$key])) {
      $this->store[$key] = array();
    }
    $this->store[$key][] = $value;
  }
  /**
   * Set or get value.
   *
   * @param string $key   key
   * @param mixed  $value value
   *
   * @return mixed
   */
  public function access($key, $value = null)
  {
    if (func_num_args() === 2) {
      $this->set($key, $value);

      return $value;
    }
    if (array_key_exists($key, $this->store)) {
      return $this->store[$key];
    }
    throw new \RuntimeException("Value under key {$key} not found.");
  }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta name="MobileOptimized" content="320″>

    <link rel="shortcut icon" type="image/x-icon" href="static/favicon.ico">
    <title>玖点e学</title>


text:
<?php

set_include_path(dirname(__DIR__) . '/src:' . get_include_path());

$loader = require_once dirname(__DIR__) . '/vendor/autoload.php';
$loader->setUseIncludePath(true);


text:
package main

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"

	"github.com/lxc/lxd/client"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	cli "github.com/lxc/lxd/shared/cmd"
	"github.com/lxc/lxd/shared/i18n"
	"github.com/lxc/lxd/shared/termios"
)

type cmdConfig struct {
	global *cmdGlobal

	flagTarget string
}

func (c *cmdConfig) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = usage("config")
	cmd.Short = i18n.G("Manage instance and server configuration options")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Manage instance and server configuration options`))

	// Device
	configDeviceCmd := cmdConfigDevice{global: c.global, config: c}
	cmd.AddCommand(configDeviceCmd.Command())

	// Edit
	configEditCmd := cmdConfigEdit{global: c.global, config: c}
	cmd.AddCommand(configEditCmd.Command())

	// Get
	configGetCmd := cmdConfigGet{global: c.global, config: c}
	cmd.AddCommand(configGetCmd.Command())

	// Metadata
	configMetadataCmd := cmdConfigMetadata{global: c.global, config: c}
	cmd.AddCommand(configMetadataCmd.Command())

	// Profile
	configProfileCmd := cmdProfile{global: c.global}
	profileCmd := configProfileCmd.Command()
	profileCmd.Hidden = true
	profileCmd.Deprecated = i18n.G("please use `lxc profile`")
	cmd.AddCommand(profileCmd)

	// Set
	configSetCmd := cmdConfigSet{global: c.global, config: c}
	cmd.AddCommand(configSetCmd.Command())

	// Show
	configShowCmd := cmdConfigShow{global: c.global, config: c}
	cmd.AddCommand(configShowCmd.Command())

	// Template
	configTemplateCmd := cmdConfigTemplate{global: c.global, config: c}
	cmd.AddCommand(configTemplateCmd.Command())

	// Trust
	configTrustCmd := cmdConfigTrust{global: c.global, config: c}
	cmd.AddCommand(configTrustCmd.Command())

	// Unset
	configUnsetCmd := cmdConfigUnset{global: c.global, config: c, configSet: &configSetCmd}
	cmd.AddCommand(configUnsetCmd.Command())

	// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
	cmd.Args = cobra.NoArgs
	cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
	return cmd
}

// Edit.
type cmdConfigEdit struct {
	global *cmdGlobal
	config *cmdConfig
}

func (c *cmdConfigEdit) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = usage("edit", i18n.G("[<remote>:][<instance>[/<snapshot>]]"))
	cmd.Short = i18n.G("Edit instance or server configurations as YAML")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Edit instance or server configurations as YAML`))
	cmd.Example = cli.FormatSection("", i18n.G(
		`lxc config edit <instance> < instance.yaml
    Update the instance configuration from config.yaml.`))

	cmd.Flags().StringVar(&c.config.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
	cmd.RunE = c.Run

	return cmd
}

func (c *cmdConfigEdit) helpTemplate() string {
	return i18n.G(
		`### This is a YAML representation of the configuration.
### Any line starting with a '# will be ignored.
###
### A sample configuration looks like:
### name: instance1
### profiles:
### - default
### config:
###   volatile.eth0.hwaddr: 00:16:3e:e9:f8:7f
### devices:
###   homedir:
###     path: /extra
###     source: /home/user
###     type: disk
### ephemeral: false
###
### Note that the name is shown but cannot be changed`)
}

func (c *cmdConfigEdit) Run(cmd *cobra.Command, args []string) error {
	// Quick checks.
	exit, err := c.global.CheckArgs(cmd, args, 0, 1)
	if exit {
		return err
	}

	// Parse remote
	remote := ""
	if len(args) > 0 {
		remote = args[0]
	}

	resources, err := c.global.ParseServers(remote)
	if err != nil {
		return err
	}

	resource := resources[0]

	fields := strings.SplitN(resource.name, "/", 2)
	isSnapshot := len(fields) == 2

	// Edit the config
	if resource.name != "" {
		// Quick checks.
		if c.config.flagTarget != "" {
			return fmt.Errorf(i18n.G("--target cannot be used with instances"))
		}

		// If stdin isn't a terminal, read text from it
		if !termios.IsTerminal(getStdinFd()) {
			contents, err := io.ReadAll(os.Stdin)
			if err != nil {
				return err
			}

			var op lxd.Operation

			if isSnapshot {
				newdata := api.InstanceSnapshotPut{}

				err = yaml.Unmarshal(contents, &newdata)
				if err != nil {
					return err
				}

				op, err = resource.server.UpdateInstanceSnapshot(fields[0], fields[1], newdata, "")
				if err != nil {
					return err
				}
			} else {
				newdata := api.InstancePut{}
				err = yaml.Unmarshal(contents, &newdata)
				if err != nil {
					return err
				}

				op, err = resource.server.UpdateInstance(resource.name, newdata, "")
				if err != nil {
					return err
				}
			}

			return op.Wait()
		}

		var data []byte
		var etag string

		// Extract the current value
		if isSnapshot {
			var inst *api.InstanceSnapshot

			inst, etag, err = resource.server.GetInstanceSnapshot(fields[0], fields[1])
			if err != nil {
				return err
			}

			// Empty expanded config so it isn't shown in edit screen (relies on omitempty tag).
			inst.ExpandedConfig = nil
			inst.ExpandedDevices = nil

			data, err = yaml.Marshal(&inst)
			if err != nil {
				return err
			}
		} else {
			var inst *api.Instance

			inst, etag, err = resource.server.GetInstance(resource.name)
			if err != nil {
				return err
			}

			// Empty expanded config so it isn't shown in edit screen (relies on omitempty tag).
			inst.ExpandedConfig = nil
			inst.ExpandedDevices = nil

			data, err = yaml.Marshal(&inst)
			if err != nil {
				return err
			}
		}

		// Spawn the editor
		content, err := shared.TextEditor("", []byte(c.helpTemplate()+"\n\n"+string(data)))
		if err != nil {
			return err
		}

		for {
			// Parse the text received from the editor
			if isSnapshot {
				newdata := api.InstanceSnapshotPut{}
				err = yaml.Unmarshal(content, &newdata)
				if err == nil {
					var op lxd.Operation
					op, err = resource.server.UpdateInstanceSnapshot(fields[0], fields[1],
						newdata, etag)
					if err == nil {
						err = op.Wait()
					}
				}
			} else {
				newdata := api.InstancePut{}
				err = yaml.Unmarshal(content, &newdata)
				if err == nil {
					var op lxd.Operation
					op, err = resource.server.UpdateInstance(resource.name, newdata, etag)
					if err == nil {
						err = op.Wait()
					}
				}
			}

			// Respawn the editor
			if err != nil {
				fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err)
				fmt.Println(i18n.G("Press enter to open the editor again or ctrl+c to abort change"))

				_, err := os.Stdin.Read(make([]byte, 1))
				if err != nil {
					return err
				}

				content, err = shared.TextEditor("", content)
				if err != nil {
					return err
				}

				continue
			}

			break
		}

		return nil
	}

	// Targeting
	if c.config.flagTarget != "" {
		if !resource.server.IsClustered() {
			return fmt.Errorf(i18n.G("To use --target, the destination remote must be a cluster"))
		}

		resource.server = resource.server.UseTarget(c.config.flagTarget)
	}

	// If stdin isn't a terminal, read text from it
	if !termios.IsTerminal(getStdinFd()) {
		contents, err := io.ReadAll(os.Stdin)
		if err != nil {
			return err
		}

		newdata := api.ServerPut{}
		err = yaml.Unmarshal(contents, &newdata)
		if err != nil {
			return err
		}

		return resource.server.UpdateServer(newdata, "")
	}

	// Extract the current value
	server, etag, err := resource.server.GetServer()
	if err != nil {
		return err
	}

	brief := server.Writable()
	data, err := yaml.Marshal(&brief)
	if err != nil {
		return err
	}

	// Spawn the editor
	content, err := shared.TextEditor("", data)
	if err != nil {
		return err
	}

	for {
		// Parse the text received from the editor
		newdata := api.ServerPut{}
		err = yaml.Unmarshal(content, &newdata)
		if err == nil {
			err = resource.server.UpdateServer(newdata, etag)
		}

		// Respawn the editor
		if err != nil {
			fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err)
			fmt.Println(i18n.G("Press enter to open the editor again or ctrl+c to abort change"))

			_, err := os.Stdin.Read(make([]byte, 1))
			if err != nil {
				return err
			}

			content, err = shared.TextEditor("", content)
			if err != nil {
				return err
			}

			continue
		}

		break
	}

	return nil
}

// Get.
type cmdConfigGet struct {
	global *cmdGlobal
	config *cmdConfig

	flagExpanded bool
}

func (c *cmdConfigGet) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = usage("get", i18n.G("[<remote>:][<instance>] <key>"))
	cmd.Short = i18n.G("Get values for instance or server configuration keys")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Get values for instance or server configuration keys`))

	cmd.Flags().BoolVarP(&c.flagExpanded, "expanded", "e", false, i18n.G("Access the expanded configuration"))
	cmd.Flags().StringVar(&c.config.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
	cmd.RunE = c.Run

	return cmd
}

func (c *cmdConfigGet) Run(cmd *cobra.Command, args []string) error {
	// Quick checks.
	exit, err := c.global.CheckArgs(cmd, args, 1, 2)
	if exit {
		return err
	}

	// Parse remote
	remote := ""
	if len(args) > 1 {
		remote = args[0]
	}

	resources, err := c.global.ParseServers(remote)
	if err != nil {
		return err
	}

	resource := resources[0]

	// Get the config key
	if resource.name != "" {
		// Quick checks.
		if c.config.flagTarget != "" {
			return fmt.Errorf(i18n.G("--target cannot be used with instances"))
		}

		resp, _, err := resource.server.GetInstance(resource.name)
		if err != nil {
			return err
		}

		if c.flagExpanded {
			fmt.Println(resp.ExpandedConfig[args[len(args)-1]])
		} else {
			fmt.Println(resp.Config[args[len(args)-1]])
		}
	} else {
		// Quick check.
		if c.flagExpanded {
			return fmt.Errorf(i18n.G("--expanded cannot be used with a server"))
		}

		// Targeting
		if c.config.flagTarget != "" {
			if !resource.server.IsClustered() {
				return fmt.Errorf(i18n.G("To use --target, the destination remote must be a cluster"))
			}

			resource.server = resource.server.UseTarget(c.config.flagTarget)
		}

		resp, _, err := resource.server.GetServer()
		if err != nil {
			return err
		}

		value := resp.Config[args[len(args)-1]]
		if value == nil {
			value = ""
		} else if value == true {
			value = "true"
		} else if value == false {
			value = "false"
		}

		fmt.Println(value)
	}

	return nil
}

// Set.
type cmdConfigSet struct {
	global *cmdGlobal
	config *cmdConfig
}

func (c *cmdConfigSet) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = usage("set", i18n.G("[<remote>:][<instance>] <key>=<value>..."))
	cmd.Short = i18n.G("Set instance or server configuration keys")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Set instance or server configuration keys

For backward compatibility, a single configuration key may still be set with:
    lxc config set [<remote>:][<instance>] <key> <value>`))
	cmd.Example = cli.FormatSection("", i18n.G(
		`lxc config set [<remote>:]<instance> limits.cpu=2
    Will set a CPU limit of "2" for the instance.

lxc config set core.https_address=[::]:8443
    Will have LXD listen on IPv4 and IPv6 port 8443.

lxc config set core.trust_password=blah
    Will set the server's trust password to blah.`))

	cmd.Flags().StringVar(&c.config.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
	cmd.RunE = c.Run

	return cmd
}

func (c *cmdConfigSet) Run(cmd *cobra.Command, args []string) error {
	// Quick checks.
	exit, err := c.global.CheckArgs(cmd, args, 1, -1)
	if exit {
		return err
	}

	hasKeyValue := func(args []string) bool {
		for _, arg := range args {
			if strings.Contains(arg, "=") {
				return true
			}
		}

		return false
	}

	onlyKeyValue := func(args []string) bool {
		for _, arg := range args {
			if !strings.Contains(arg, "=") {
				return false
			}
		}

		return true
	}

	isConfig := func(value string) bool {
		fields := strings.SplitN(value, ":", 2)
		key := fields[len(fields)-1]
		return strings.Contains(key, ".")
	}

	// Parse remote
	remote := ""
	if onlyKeyValue(args) || isConfig(args[0]) {
		// server set with: <key>=<value>...
		remote = ""
	} else if len(args) == 2 && !hasKeyValue(args) {
		// server set with: <key> <value>
		remote = ""
	} else {
		remote = args[0]
	}

	resources, err := c.global.ParseServers(remote)
	if err != nil {
		return err
	}

	resource := resources[0]

	// Set the config keys
	if resource.name != "" {
		// Quick checks.
		if c.config.flagTarget != "" {
			return fmt.Errorf(i18n.G("--target cannot be used with instances"))
		}

		keys, err := getConfig(args[1:]...)
		if err != nil {
			return err
		}

		inst, etag, err := resource.server.GetInstance(resource.name)
		if err != nil {
			return err
		}

		for k, v := range keys {
			if cmd.Name() == "unset" {
				_, ok := inst.Config[k]
				if !ok {
					return fmt.Errorf(i18n.G("Can't unset key '%s', it's not currently set"), k)
				}

				delete(inst.Config, k)
			} else {
				inst.Config[k] = v
			}
		}

		op, err := resource.server.UpdateInstance(resource.name, inst.Writable(), etag)
		if err != nil {
			return err
		}

		return op.Wait()
	}

	// Targeting
	if c.config.flagTarget != "" {
		if !resource.server.IsClustered() {
			return fmt.Errorf(i18n.G("To use --target, the destination remote must be a cluster"))
		}

		resource.server = resource.server.UseTarget(c.config.flagTarget)
	}

	// Server keys
	server, etag, err := resource.server.GetServer()
	if err != nil {
		return err
	}

	var keys map[string]string
	if remote == "" {
		keys, err = getConfig(args[0:]...)
		if err != nil {
			return err
		}
	} else {
		keys, err = getConfig(args[1:]...)
		if err != nil {
			return err
		}
	}

	for k, v := range keys {
		server.Config[k] = v
	}

	return resource.server.UpdateServer(server.Writable(), etag)
}

// Show.
type cmdConfigShow struct {
	global *cmdGlobal
	config *cmdConfig

	flagExpanded bool
}

func (c *cmdConfigShow) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = usage("show", i18n.G("[<remote>:][<instance>[/<snapshot>]]"))
	cmd.Short = i18n.G("Show instance or server configurations")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Show instance or server configurations`))

	cmd.Flags().BoolVarP(&c.flagExpanded, "expanded", "e", false, i18n.G("Show the expanded configuration"))
	cmd.Flags().StringVar(&c.config.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
	cmd.RunE = c.Run

	return cmd
}

func (c *cmdConfigShow) Run(cmd *cobra.Command, args []string) error {
	// Quick checks.
	exit, err := c.global.CheckArgs(cmd, args, 0, 1)
	if exit {
		return err
	}

	// Parse remote
	remote := ""
	if len(args) > 0 {
		remote = args[0]
	}

	resources, err := c.global.ParseServers(remote)
	if err != nil {
		return err
	}

	resource := resources[0]

	// Show configuration
	var data []byte

	if resource.name == "" {
		// Quick check.
		if c.flagExpanded {
			return fmt.Errorf(i18n.G("--expanded cannot be used with a server"))
		}

		// Targeting
		if c.config.flagTarget != "" {
			if !resource.server.IsClustered() {
				return fmt.Errorf(i18n.G("To use --target, the destination remote must be a cluster"))
			}

			resource.server = resource.server.UseTarget(c.config.flagTarget)
		}

		// Server config
		server, _, err := resource.server.GetServer()
		if err != nil {
			return err
		}

		brief := server.Writable()
		data, err = yaml.Marshal(&brief)
		if err != nil {
			return err
		}
	} else {
		// Quick checks.
		if c.config.flagTarget != "" {
			return fmt.Errorf(i18n.G("--target cannot be used with instances"))
		}

		// Instance or snapshot config
		var brief any

		if shared.IsSnapshot(resource.name) {
			// Snapshot
			fields := strings.Split(resource.name, shared.SnapshotDelimiter)

			snap, _, err := resource.server.GetInstanceSnapshot(fields[0], fields[1])
			if err != nil {
				return err
			}

			brief = snap
			if c.flagExpanded {
				brief.(*api.InstanceSnapshot).Config = snap.ExpandedConfig
				brief.(*api.InstanceSnapshot).Devices = snap.ExpandedDevices
			}
		} else {
			// Instance
			inst, _, err := resource.server.GetInstance(resource.name)
			if err != nil {
				return err
			}

			writable := inst.Writable()
			brief = &writable

			if c.flagExpanded {
				brief.(*api.InstancePut).Config = inst.ExpandedConfig
				brief.(*api.InstancePut).Devices = inst.ExpandedDevices
			}
		}

		data, err = yaml.Marshal(&brief)
		if err != nil {
			return err
		}
	}

	fmt.Printf("%s", data)

	return nil
}

// Unset.
type cmdConfigUnset struct {
	global    *cmdGlobal
	config    *cmdConfig
	configSet *cmdConfigSet
}

func (c *cmdConfigUnset) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = usage("unset", i18n.G("[<remote>:][<instance>] <key>"))
	cmd.Short = i18n.G("Unset instance or server configuration keys")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Unset instance or server configuration keys`))

	cmd.Flags().StringVar(&c.config.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
	cmd.RunE = c.Run

	return cmd
}

func (c *cmdConfigUnset) Run(cmd *cobra.Command, args []string) error {
	// Quick checks.
	exit, err := c.global.CheckArgs(cmd, args, 1, 2)
	if exit {
		return err
	}

	args = append(args, "")
	return c.configSet.Run(cmd, args)
}


text:
from ip_addresses.models import *
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
import subprocess

# NETWORKADDRESS view functions

def networkaddress_display(request, address=None):
    parent = get_network_object_from_address(address)
    addr_list = NetworkAddress.objects.filter(parent=parent)
    has_subnets = False
    for address in addr_list:
        if address.network_size != 32:
            has_subnets = True
    try:
        dhcp_net = DHCPNetwork.objects.get(physical_net=parent)
    except:
        dhcp_net = None
    return render_to_response('ip_addresses/display.html', {'parent': parent,
                                               'addresses_list': addr_list,
                                               'has_subnets': has_subnets,
                                               'dhcp_net': dhcp_net,})

def networkaddress_delete(request, address=None):
    address_obj = get_network_object_from_address(address)
    parent = address_obj.parent
    address_obj.delete()
    redirect_to = '../../../'
    if parent:
        redirect_to = parent.get_absolute_url()
    return HttpResponseRedirect(redirect_to)

def networkaddress_add(request, address=None):
    if request.method == 'POST':
        parent = get_network_object_from_address(address)
        new_address = NetworkAddress(parent=parent)
        form = NetworkAddressAddForm(request.POST, instance=new_address)
        if form.is_valid():
            form.save()
            url = parent.get_absolute_url() if parent else reverse('networkaddress-displaytop')
            return HttpResponseRedirect(url)
    else:
        form = NetworkAddressAddForm()
    return render_to_response('ip_addresses/add.html', {'form': form,}, context_instance=RequestContext(request))

def networkaddress_modify(request, address=None):
    address_obj = get_network_object_from_address(address)
    if request.method == 'POST':
        # submitting changes
        form = NetworkAddressModifyForm(request.POST, instance=address_obj)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(address_obj.parent.get_absolute_url())
    else:
        # first time display
        form = NetworkAddressModifyForm(initial={ 'description': address_obj.description, })
    return render_to_response('ip_addresses/add.html', {'form': form,}, context_instance=RequestContext(request))

def networkaddress_ping(request, address=None):
    if responding_to_ping(address):
        msg = "Ping OK"
    else:
        msg = "No response"
    return HttpResponse(msg)

# NETWORKDEVICE view functions

def networkdevice_display(request, device=None):
    ##parent = get_network_object_from_device(device)
    device_list = NetworkDevice.objects.all()
    return render_to_response('ip_addresses/display_device.html', {'device_list': device_list,})

def networkdevice_delete(request, device=None):
    device_obj = get_network_object_from_device(device)
    parent = device_obj.parent
    device_obj.delete()
    redirect_to = '../../../'
    if parent:
        redirect_to = parent.get_absolute_url()
    return HttpResponseRedirect(redirect_to)

def networkdevice_add(request, device=None):
    if request.method == 'POST':
        ##parent = get_network_object_from_device(device)
        new_device = NetworkDevice()
        form = NetworkDeviceAddForm(request.POST, instance=new_device)
        if form.is_valid():
            form.save()
            url = reverse('networkdevice-displaytop')
            return HttpResponseRedirect(url)
    else:
        form = NetworkDeviceAddForm()
    return render_to_response('ip_addresses/add.html', {'form': form,}, context_instance=RequestContext(request))

def networkdevice_modify(request, device=None):
    device_obj = NetworkDevice(device)
    if request.method == 'POST':
        form = NetworkDeviceModifyForm(request.POST, instance=device_obj)
        if form.is_valid():
            form.save()
            url = reverse('networkdevice-displaytop')
            return HttpResponseRedirect(url)
    else:
        # first time display
        form = NetworkDeviceModifyForm(initial={ 'description': device_obj.description, })
    return render_to_response('ip_addresses/add.html', {'form': form,}, context_instance=RequestContext(request))

############################################################################
# helper functions

def get_network_object_from_address(address):
    if address:
        ip, net_size = address.split('/')
        object = NetworkAddress.objects.get(address=ip, network_size=int(net_size))
    else:
        object = None
    return object

def responding_to_ping(address, timeout=1):
    rc = subprocess.call("ping -c 1 -W %d %s" % (timeout, address),
                         shell=True, stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT)
    if rc == 0:
        return True
    else:
        return False


text:
class ConfigItemsController < ApplicationController
  before_filter :require_user

  def index
    @config_items = ConfigItem.all
  end

  def new
    @config_item = ConfigItem.new
    @config_groups = ConfigItem.all
  end

  def create
    @config_item = ConfigItem.new(params[:config_item])

    if @config_item.save
      flash[:notice] = "Config item created!"
      redirect_to config_items_path
    else
      render :action => :new
    end
  end

  def show
    @config_item = ConfigItem.find(params[:id])
  end

  def edit
    @config_item = ConfigItem.find(params[:id])
    @config_groups = ConfigItem.all
    @config_groups.delete(@config_item)
  end

  def update
    @config_item = ConfigItem.find(params[:id])
    if @config_item.update_attributes(params[:config_item])
      flash[:notice] = "Config item updated!"
      redirect_to config_items_path
    else
      render :action => :edit
    end
  end

  def destroy
    @config_item = ConfigItem.find(params[:id])
    if request.delete?
      @config_item.destroy
    end
    respond_to do |format|
      format.html { redirect_to config_items_path }
      format.xml  { head :ok }
    end
  end
end


text:
#ifndef BASE2_XML_XML_ATTRIBUTES_H_
#define BASE2_XML_XML_ATTRIBUTES_H_
#pragma once

#include <string>
#include <map>
#include <set>

#include "base/basictypes.h"
#include "base/strings/string_piece.h"

namespace base {

class XMLAttributes {
public:
	XMLAttributes(void) {}
	virtual ~XMLAttributes(void) {}

	void Add(const StringPiece& attr_name, const StringPiece& attr_val);
	void Remove(const StringPiece& attr_name);
	bool Exists(const StringPiece& attr_name) const;
	size_t GetCount(void) const;

	bool GetName(size_t index, std::string* val) const;
  std::string GetName(size_t index) const;
	bool GetValue(size_t index, std::string* val) const;
  std::string GetValue2(size_t index) const;

	bool GetValue(const StringPiece& attr_name, std::string* val) const;
  bool GetValueAsBool(const StringPiece& attr_name, bool* val) const;
  bool GetValueAsInt(const StringPiece& attr_name, int* val) const;
  bool GetValueAsInt64(const StringPiece& attr_name, int64* val) const;
  bool GetValueAsFloat(const StringPiece& attr_name, float* val) const;

  std::string GetValueByName(const char* attr_name) const;

  void ToNames(std::set<StringPiece>* names) const;

  inline const std::map<StringPiece, StringPiece>& GetAttributes() const {
    return attrs_;
  }

protected:
	typedef std::map<StringPiece, StringPiece> AttributeMap;
	AttributeMap  attrs_;
};

}

#endif


text:
/**
 * WordPress dependencies
 */
import { useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import CreateAccountField from './CreateAccountField';
import Data from 'googlesitekit-data';
import { FORM_ACCOUNT_CREATE } from '../../../datastore/constants';
import { CORE_FORMS } from '../../../../../googlesitekit/datastore/forms/constants';

const { useSelect, useDispatch } = Data;

export default function PropertyField() {
	const value = useSelect( ( select ) =>
		select( CORE_FORMS ).getValue( FORM_ACCOUNT_CREATE, 'propertyName' )
	);
	const { setValues } = useDispatch( CORE_FORMS );

	const setValue = useCallback(
		( propertyName ) => {
			setValues( FORM_ACCOUNT_CREATE, { propertyName } );
		},
		[ setValues ]
	);

	return (
		<CreateAccountField
			label={ __( 'Property', 'google-site-kit' ) }
			value={ value }
			hasError={ ! value }
			setValue={ setValue }
			name="property"
		/>
	);
}


text:
<?php

namespace MessageContext\InfrastructureBundle\RequestHandler;

interface RequestHandler
{
    /**
     * @param Request $request
     * @return Response
     */
    public function handle(Request $request);
}


text:
from xml.dom.minidom import parseString

def get_xml_schema(dataset):
    '''Create XML schema from list of columns in dicts. It's used to create
    MAQL through the Java Client.
    '''
    dom = parseString('<schema><name>%s</name><columns></columns></schema>' % dataset.schema_name)
    for column in dataset.get_columns():
        xmlcol = dom.createElement('column')
        for key, val in column.get_schema_values():
            k = dom.createElement(key)
            v = dom.createTextNode(val)
            k.appendChild(v)
            xmlcol.appendChild(k)
        dom.childNodes[0].childNodes[1].appendChild(xmlcol)
    return dom.toxml()