text:
<?php
    $page = 'home';
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>M.B. Driveways</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

    <link href="css/stylesheet.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>

                    <li<?php if ($page == 'home') { echo ' class="tab-active"'; } ?>>
                        Home

                        Services

                        Gallery

                        Contact

                         01207 582 712

For a driveway to be proud of

from a company you can trust..

                Tell Me More
                Get a Quote

Services

Lorem ipsum dolor sit amet consectetur.

E-Commerce

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Responsive Design

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Web Security

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Portfolio

Lorem ipsum dolor sit amet consectetur.

Round Icons

Graphic Design

Startup Framework

Website Design

Treehouse

Website Design

Golden

Website Design

Escape

Website Design

Dreams

Website Design

About

Lorem ipsum dolor sit amet consectetur.

2009-2011

Our Humble Beginnings

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

March 2011

An Agency is Born

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

December 2012

Transition to Full Service

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

July 2014

Phase Two Expansion

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

Be Part

Of Our

Story!

Our Amazing Team

Lorem ipsum dolor sit amet consectetur.

Kay Garland

Lead Designer

Larry Parker

Lead Marketer

Diana Pertersen

Lead Developer

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut eaque, laboriosam veritatis, quos non quis ad perspiciatis, totam corporis ea, alias ut unde.

Contact Us

Lorem ipsum dolor sit amet consectetur.

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                    <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Message</button>

                    </form>

                    Copyright © Your Website 2016

Privacy Policy

Terms of Use

Project Name

Lorem ipsum dolor sit amet consectetur.

Use this area to describe your project. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est blanditiis dolorem culpa incidunt minus dignissimos deserunt repellat aperiam quasi sunt officia expedita beatae cupiditate, maiores repudiandae, nostrum, reiciendis facere nemo!

                                    Want these icons in this portfolio item sample?You can download 60 of them for free, courtesy of RoundIcons.com, or you can purchase the 1500 icon set here.

Date: July 2014

Client: Round Icons

Category: Graphic Design

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Heading

Lorem ipsum dolor sit amet consectetur.

Startup Framework is a website builder for professionals. Startup Framework contains components and complex blocks (PSD+HTML Bootstrap themes and templates) which can easily be integrated into almost any design. All of these components are made in the same style, and can easily be integrated into projects, allowing you to create hundreds of solutions for your future projects.

You can preview Startup Framework here.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Treehouse is a free PSD web template built by Mathavan Jaya. This is bright and spacious design perfect for people or startup companies looking to showcase their apps or other projects.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Start Bootstrap's Agency theme is based on Golden, a free PSD website template built by Mathavan Jaya. Golden is a modern and clean one page web template that was made exclusively for Best PSD Freebies. This template has a great portfolio, timeline, and meet your team sections that can be easily modified to fit your needs.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Escape is a free PSD web template built by Mathavan Jaya. Escape is a one page web template that was designed with agencies in mind. This template is ideal for those looking for a simple one page solution to describe your business and offer your services.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Dreams is a free PSD web template built by Mathavan Jaya. Dreams is a modern one page web template designed for almost any purpose. It's a beautiful template that's designed with the Bootstrap framework in mind.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>


text:
@implementation BYSwitchBorderLayer

+(UIBezierPath*)borderPathForBounds:(CGRect)bounds andBorder:(BYBorder*)border {
    CGRect frameInsideBorder = CGRectInset(bounds, border.width/2, border.width/2);
    UIBezierPath* borderPath;
    if(border.cornerRadius > 0) {
        borderPath = [UIBezierPath bezierPathWithRoundedRect:frameInsideBorder cornerRadius:border.cornerRadius];
    }
    else {
        borderPath = [UIBezierPath bezierPathWithRect:frameInsideBorder];
    }
    return borderPath;
}

-(void)drawInContext:(CGContextRef)ctx {

    UIImage* borderLayerImage = [self.renderer propertyValueForNameWithCurrentState:@"borderLayerImage"];

    if (borderLayerImage != nil) {
        // flip the context, see
        // http://stackoverflow.com/questions/506622/cgcontextdrawimage-draws-image-upside-down-when-passed-uiimage-cgimage
        CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
        CGContextScaleCTM(ctx, 1.0, -1.0);

        CGContextDrawImage(ctx, self.bounds, borderLayerImage.CGImage);
    }
    else {
        BYBorder* border = [self.renderer propertyValueForNameWithCurrentState:@"border"];
        UIBezierPath *borderPath = [BYSwitchBorderLayer borderPathForBounds:self.bounds andBorder:border];

        BYShadow* innerShadow = [self.renderer propertyValueForNameWithCurrentState:@"innerShadow"];
        UIColor* highlightColor = [self.renderer propertyValueForNameWithCurrentState:@"highlightColor"];

        if(highlightColor) {
            CGRect rect = CGRectMake(border.cornerRadius/2, self.frame.size.height/2,
                                     self.frame.size.width - border.cornerRadius, self.frame.size.height/2);
            UIBezierPath* highlightPath = [UIBezierPath bezierPathWithRoundedRect:rect
                                                                     cornerRadius:border.cornerRadius];
            CGContextAddPath(ctx, highlightPath.CGPath);
            CGContextSetFillColorWithColor(ctx, highlightColor.CGColor);
            CGContextFillPath(ctx);
        }

        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:border.cornerRadius];
        RenderInnerShadow(ctx, innerShadow, path);

        if (border.width > 0) {
            UISwitch *view = self.renderer.adaptedView;
            NSString *propName = view.on ? @"onState" : @"offState";
            BYSwitchState *state = [self.renderer propertyValueForNameWithCurrentState:propName];
            // Use the state's border color if it has one - otherwise use the borders own color.
            UIColor *borderColor = state.borderColor != nil ? state.borderColor : border.color;

            // render the border
            CGContextAddPath(ctx, borderPath.CGPath);
            CGContextSetStrokeColorWithColor(ctx, borderColor.CGColor);
            CGContextSetLineWidth(ctx, border.width);
            CGContextStrokePath(ctx);
        }
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
import numpy as np
import pandas as pd

import pytest

@pytest.fixture(autouse=True)
def close_figs():
    yield
    import matplotlib.pyplot as plt
    plt.close("all")

@pytest.fixture(autouse=True)
def random_seed():
    seed = sum(map(ord, "seaborn random global"))
    np.random.seed(seed)

@pytest.fixture()
def rng():
    seed = sum(map(ord, "seaborn random object"))
    return np.random.RandomState(seed)

@pytest.fixture
def wide_df(rng):

    columns = list("abc")
    index = pd.RangeIndex(10, 50, 2, name="wide_index")
    values = rng.normal(size=(len(index), len(columns)))
    return pd.DataFrame(values, index=index, columns=columns)

@pytest.fixture
def wide_array(wide_df):

    return wide_df.to_numpy()

# TODO s/flat/thin?
@pytest.fixture
def flat_series(rng):

    index = pd.RangeIndex(10, 30, name="t")
    return pd.Series(rng.normal(size=20), index, name="s")

@pytest.fixture
def flat_array(flat_series):

    return flat_series.to_numpy()

@pytest.fixture
def flat_list(flat_series):

    return flat_series.to_list()

@pytest.fixture(params=["series", "array", "list"])
def flat_data(rng, request):

    index = pd.RangeIndex(10, 30, name="t")
    series = pd.Series(rng.normal(size=20), index, name="s")
    if request.param == "series":
        data = series
    elif request.param == "array":
        data = series.to_numpy()
    elif request.param == "list":
        data = series.to_list()
    return data

@pytest.fixture
def wide_list_of_series(rng):

    return [pd.Series(rng.normal(size=20), np.arange(20), name="a"),
            pd.Series(rng.normal(size=10), np.arange(5, 15), name="b")]

@pytest.fixture
def wide_list_of_arrays(wide_list_of_series):

    return [s.to_numpy() for s in wide_list_of_series]

@pytest.fixture
def wide_list_of_lists(wide_list_of_series):

    return [s.to_list() for s in wide_list_of_series]

@pytest.fixture
def wide_dict_of_series(wide_list_of_series):

    return {s.name: s for s in wide_list_of_series}

@pytest.fixture
def wide_dict_of_arrays(wide_list_of_series):

    return {s.name: s.to_numpy() for s in wide_list_of_series}

@pytest.fixture
def wide_dict_of_lists(wide_list_of_series):

    return {s.name: s.to_list() for s in wide_list_of_series}

@pytest.fixture
def long_df(rng):

    n = 100
    df = pd.DataFrame(dict(
        x=rng.uniform(0, 20, n).round().astype("int"),
        y=rng.normal(size=n),
        z=rng.lognormal(size=n),
        a=rng.choice(list("abc"), n),
        b=rng.choice(list("mnop"), n),
        c=rng.choice([0, 1], n, [.3, .7]),
        d=rng.choice(np.arange("2004-07-30", "2007-07-30", dtype="datetime64[Y]"), n),
        t=rng.choice(np.arange("2004-07-30", "2004-07-31", dtype="datetime64[m]"), n),
        s=rng.choice([2, 4, 8], n),
        f=rng.choice([0.2, 0.3], n),
    ))

    a_cat = df["a"].astype("category")
    new_categories = np.roll(a_cat.cat.categories, 1)
    df["a_cat"] = a_cat.cat.reorder_categories(new_categories)

    df["s_cat"] = df["s"].astype("category")
    df["s_str"] = df["s"].astype(str)

    return df

@pytest.fixture
def long_dict(long_df):

    return long_df.to_dict()

@pytest.fixture
def repeated_df(rng):

    n = 100
    return pd.DataFrame(dict(
        x=np.tile(np.arange(n // 2), 2),
        y=rng.normal(size=n),
        a=rng.choice(list("abc"), n),
        u=np.repeat(np.arange(2), n // 2),
    ))

@pytest.fixture
def missing_df(rng, long_df):

    df = long_df.copy()
    for col in df:
        idx = rng.permutation(df.index)[:10]
        df.loc[idx, col] = np.nan
    return df

@pytest.fixture
def object_df(rng, long_df):

    df = long_df.copy()
    # objectify numeric columns
    for col in ["c", "s", "f"]:
        df[col] = df[col].astype(object)
    return df

@pytest.fixture
def null_series(flat_series):

    return pd.Series(index=flat_series.index, dtype='float64')


text:
namespace Google.Cloud.Recommender.V1.Snippets
{
    // [START recommender_v1_generated_Recommender_ListInsights_sync]
    using Google.Api.Gax;
    using Google.Cloud.Recommender.V1;
    using System;

    public sealed partial class GeneratedRecommenderClientSnippets
    {
        /// <summary>Snippet for ListInsights</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void ListInsightsRequestObject()
        {
            // Create client
            RecommenderClient recommenderClient = RecommenderClient.Create();
            // Initialize request argument(s)
            ListInsightsRequest request = new ListInsightsRequest
            {
                ParentAsInsightTypeName = InsightTypeName.FromProjectLocationInsightType("[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]"),
                Filter = "",
            };
            // Make the request
            PagedEnumerable<ListInsightsResponse, Insight> response = recommenderClient.ListInsights(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Insight item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListInsightsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Insight item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Insight> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Insight item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END recommender_v1_generated_Recommender_ListInsights_sync]
}


text:
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package java

import (
	"bytes"
	"log"

	"v.io/x/ref/lib/vdl/compile"
)

const setTmpl = header + `
// Source: {{.SourceFile}}

package {{.Package}};

{{ .Doc }}
@io.v.v23.vdl.GeneratedFromVdl(name = "{{.VdlTypeName}}")
{{ .AccessModifier }} class {{.Name}} extends io.v.v23.vdl.VdlSet<{{.KeyType}}> {
    private static final long serialVersionUID = 1L;

    /**
     * Vdl type for {@link {{.Name}}}.
     */
    public static final io.v.v23.vdl.VdlType VDL_TYPE =
            io.v.v23.vdl.Types.getVdlTypeFromReflect({{.Name}}.class);

    /**
     * Creates a new instance of {@link {{.Name}}} with the given underlying value.
     *
     * @param impl underlying value
     */
    public {{.Name}}(java.util.Set<{{.KeyType}}> impl) {
        super(VDL_TYPE, impl);
    }

    /**
     * Creates a new zero-value instance of {@link {{.Name}}}.
     */
    public {{.Name}}() {
        this(new java.util.HashSet<{{.KeyType}}>());
    }
}
`

// genJavaSetFile generates the Java class file for the provided named set type.
func genJavaSetFile(tdef *compile.TypeDef, env *compile.Env) JavaFileInfo {
	name, access := javaTypeName(tdef, env)
	data := struct {
		AccessModifier string
		Doc            string
		FileDoc        string
		KeyType        string
		Name           string
		Package        string
		SourceFile     string
		VdlTypeName    string
		VdlTypeString  string
	}{
		AccessModifier: access,
		Doc:            javaDoc(tdef.Doc, tdef.DocSuffix),
		FileDoc:        tdef.File.Package.FileDoc,
		KeyType:        javaType(tdef.Type.Key(), true, env),
		Name:           name,
		Package:        javaPath(javaGenPkgPath(tdef.File.Package.GenPath)),
		SourceFile:     tdef.File.BaseName,
		VdlTypeName:    tdef.Type.Name(),
		VdlTypeString:  tdef.Type.String(),
	}
	var buf bytes.Buffer
	err := parseTmpl("set", setTmpl).Execute(&buf, data)
	if err != nil {
		log.Fatalf("vdl: couldn't execute set template: %v", err)
	}
	return JavaFileInfo{
		Name: name + ".java",
		Data: buf.Bytes(),
	}
}


text:
// This file is required by app.js.
// It handles all the server-side socketIO logic for CifraChat, interacting
// with the client-side code in /public/js/chat.js.

// discussion: https://github.com/Automattic/socket.io/issues/1450
var roomCount = function(room)
{
	var localCount = 0;
	if (room)
		for (var id in room)
			localCount ++;
	return localCount;
}

// messages must be numbered to notify each client when their message is decrypted
var messageNum = 1;
var MAX_ALLOWED_CLIENTS = 2;

module.exports = function(app, io)
{
	var chat = io.of('/chat').on('connection', function(clntSocket)
	{
	  // each client is put into a chat room restricted to max 2 clients
	  clntSocket.on('joinRoom', function(room_id)
	  {
	  	var clients_in_room = roomCount(chat.adapter.rooms[room_id]);
		// client may only join room only if it's not full
		if (clients_in_room >= MAX_ALLOWED_CLIENTS)
		{
			clntSocket.emit('serverMessage', {
				message: 'This room is full.'
			});
			// force client to disconnect
			clntSocket.disconnect();
		}
		else
		{
			// client joins room specified in URL
			clntSocket.join(room_id);

			clients_in_room++;

			// welcome client on succesful connection
			clntSocket.emit('serverMessage', {
				message: 'Welcome to  CifraChat. Send someone a link to this room to start chatting. Max 2 people per room.'
			});

			// let other user know that client joined
			clntSocket.broadcast.to(room_id).emit('serverMessage', {
				message: 'Other has joined.'
			});

			if (clients_in_room == MAX_ALLOWED_CLIENTS){
				// let everyone know that the max amount of users (2) has been reached
				chat.in(room_id).emit('serverMessage', {
					message: 'This room is now full. There are 2 users present.'
				});
			}

		    /** sending encrypted **/
			clntSocket.on('cryptSend', function (data) {
				// all data sent by client is sent to room
				clntSocket.broadcast.to(room_id).emit('cryptMessage', {
					message: data.message,
					hint: data.hint,
					sender: 'Other',
					number: messageNum
				});
				// and then shown to client
				clntSocket.emit('cryptMessage', {
					message: data.message,
					hint: data.hint,
					sender: 'Self',
					number: messageNum
				});

				messageNum++;
			});

			/** sending unencrypted **/
			clntSocket.on('noncryptSend', function (text) {
				// all data sent by client is sent to room
				clntSocket.broadcast.to(room_id).emit('noncryptMessage', {
					message: text.message,
					sender: 'Other'
				});
				// and then shown to client
				clntSocket.emit('noncryptMessage', {
					message: text.message,
					sender: 'Self'
				});

				// unencrypted messages don't increment messageNum because messageNum is only used to identify which message was decrypted
			});

			/** notifying clients of decryption **/
			clntSocket.on('confirmDecrypt', function(id) {
				// let room know which particular message was decrypted
				chat.in(room_id).emit('markDecryption', id);
			});

			clntSocket.on('confirmMessageDestroy', function(id) {
				chat.in(room_id).emit('markMessageDestroy', id)
			});
		};

		/** disconnect listener **/
		// notify others that somebody left the chat
		clntSocket.on('disconnect', function() {
			// let room know that this client has left
			clntSocket.broadcast.to(room_id).emit('serverMessage', {
					message: 'Other has left.'
				});
		});
	  }); // end joinRoom listener
	});
};


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

  <title>AWS CIS Audit tool</title>

  <meta name="HandheldFriendly" content="True" />
  <meta name="referrer" content="origin" />
  <meta name="generator" content="Pelican" />

  <link href="https://www.duncan.dickinson.name/atom.xml" type="application/atom+xml" rel="alternate"
    title="Prag-o-matic Atom Feed" />

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
    integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <link rel="stylesheet" href="https://www.duncan.dickinson.name/theme/css/highlight/vs.css">

  <link rel="stylesheet" href="https://www.duncan.dickinson.name/theme/css/site.css">

<link href="https://www.duncan.dickinson.name/2017/07/AwsCisAudit.html" rel="canonical" />

<meta name="description" content="A set of Behave features to track an AWS environment against the CIS benchmarks">

<meta name="author" content="Duncan Dickinson">

<meta name="tags" content="aws">
<meta name="tags" content="api">
<meta name="tags" content="python">
<meta name="tags" content="cis">
<meta name="tags" content="security">

Prag-o-matic

A blog.

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01"
        aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Home

                    About

                Tags

                Archives

                LinkedIn

                Github

AWS CIS Audit tool

Posted on
      <time datetime="Thu 06 July 2017">Thu 06 July 2017</time>

The Center for Internet Security (CIS) released
guidelines for AWS and I
thought it’d be interesting to describe these in Gherkin.
I could then back the statements with small Python scripts to run the checks through the use of the
the Behave package.

As you can see in the example feature below, the Gherkin syntax is reasonably readable:

@kms
Feature: AWS Key Management Services

  @cis @level_2
  Scenario: CIS 2.8 Ensure rotation for customer created CMKs is enabled
    Then all KMS keys must be set to rotate annually

The statements then map to Python functions that do the actual work. Calling behave against the
set of tests generates JUnit-based XML output so I then pass them through junit2html
for easier reviews.

Overall it’s an interesting approach and gives you a user-friendly description of the tests and
output that could be analysed by non-developers. Better yet, failed tests could raise an alarm.

A good chunk of the tests work but it’s definitely not finished.
Check out the code.

Tags:

api

aws

cis

python

security

      ©2017 Duncan Dickinson

        Back to top


text:
using System;

namespace Sixeyed.HadoopSuccinctly.Streaming.Mapper
{
    class Program
    {
        static void Main(string[] args)
        {
            string line;
            while ((line = Console.ReadLine()) != null)
            {
                line = line.Trim();
                var words = line.Split(' ');
                foreach (var word in words)
                {
                    if (word.Contains("dfs"))
                    {
                        Console.WriteLine(string.Format("{0}\t1", word));
                    }
                }
            }
        }
    }
}


text:
package org.apache.flink.runtime.state;

import org.apache.flink.api.common.typeutils.BackwardsCompatibleSerializerSnapshot;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerSnapshotSerializationUtil;
import org.apache.flink.api.common.typeutils.TypeSerializerSerializationUtil;
import org.apache.flink.api.common.typeutils.TypeSerializerSnapshot;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.core.io.VersionedIOReadableWritable;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.runtime.state.metainfo.StateMetaInfoReader;
import org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshot;
import org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshotReadersWriters;
import org.apache.flink.util.Preconditions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshotReadersWriters.CURRENT_STATE_META_INFO_SNAPSHOT_VERSION;

/**
 * Serialization proxy for all meta data in keyed state backends. In the future we might also requiresMigration the actual state
 * serialization logic here.
 */
public class KeyedBackendSerializationProxy<K> extends VersionedIOReadableWritable {

	public static final int VERSION = 6;

	private static final Map<Integer, Integer> META_INFO_SNAPSHOT_FORMAT_VERSION_MAPPER = new HashMap<>();
	static {
		META_INFO_SNAPSHOT_FORMAT_VERSION_MAPPER.put(1, 1);
		META_INFO_SNAPSHOT_FORMAT_VERSION_MAPPER.put(2, 2);
		META_INFO_SNAPSHOT_FORMAT_VERSION_MAPPER.put(3, 3);
		META_INFO_SNAPSHOT_FORMAT_VERSION_MAPPER.put(4, 4);
		META_INFO_SNAPSHOT_FORMAT_VERSION_MAPPER.put(5, 5);
		META_INFO_SNAPSHOT_FORMAT_VERSION_MAPPER.put(6, CURRENT_STATE_META_INFO_SNAPSHOT_VERSION);
	}

	//TODO allow for more (user defined) compression formats + backwards compatibility story.
	/** This specifies if we use a compressed format write the key-groups */
	private boolean usingKeyGroupCompression;

	// TODO the keySerializer field should be removed, once all serializers have the restoreSerializer() method implemented
	private TypeSerializer<K> keySerializer;
	private TypeSerializerSnapshot<K> keySerializerConfigSnapshot;

	private List<StateMetaInfoSnapshot> stateMetaInfoSnapshots;

	private ClassLoader userCodeClassLoader;

	public KeyedBackendSerializationProxy(ClassLoader userCodeClassLoader) {
		this.userCodeClassLoader = Preconditions.checkNotNull(userCodeClassLoader);
	}

	public KeyedBackendSerializationProxy(
			TypeSerializer<K> keySerializer,
			List<StateMetaInfoSnapshot> stateMetaInfoSnapshots,
			boolean compression) {

		this.usingKeyGroupCompression = compression;

		this.keySerializer = Preconditions.checkNotNull(keySerializer);
		this.keySerializerConfigSnapshot = Preconditions.checkNotNull(keySerializer.snapshotConfiguration());

		Preconditions.checkNotNull(stateMetaInfoSnapshots);
		Preconditions.checkArgument(stateMetaInfoSnapshots.size() <= Short.MAX_VALUE);
		this.stateMetaInfoSnapshots = stateMetaInfoSnapshots;
	}

	public List<StateMetaInfoSnapshot> getStateMetaInfoSnapshots() {
		return stateMetaInfoSnapshots;
	}

	public TypeSerializerSnapshot<K> getKeySerializerConfigSnapshot() {
		return keySerializerConfigSnapshot;
	}

	public boolean isUsingKeyGroupCompression() {
		return usingKeyGroupCompression;
	}

	@Override
	public int getVersion() {
		return VERSION;
	}

	@Override
	public int[] getCompatibleVersions() {
		return new int[]{VERSION, 5, 4, 3, 2, 1};
	}

	@Override
	public void write(DataOutputView out) throws IOException {
		super.write(out);

		// write the compression format used to write each key-group
		out.writeBoolean(usingKeyGroupCompression);

		TypeSerializerSnapshotSerializationUtil.writeSerializerSnapshot(out, keySerializerConfigSnapshot, keySerializer);

		// write individual registered keyed state metainfos
		out.writeShort(stateMetaInfoSnapshots.size());
		for (StateMetaInfoSnapshot metaInfoSnapshot : stateMetaInfoSnapshots) {
			StateMetaInfoSnapshotReadersWriters.getWriter().writeStateMetaInfoSnapshot(metaInfoSnapshot, out);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void read(DataInputView in) throws IOException {
		super.read(in);

		final int readVersion = getReadVersion();

		if (readVersion >= 4) {
			usingKeyGroupCompression = in.readBoolean();
		} else {
			usingKeyGroupCompression = false;
		}

		// only starting from version 3, we have the key serializer and its config snapshot written
		if (readVersion >= 6) {
			this.keySerializerConfigSnapshot = TypeSerializerSnapshotSerializationUtil.readSerializerSnapshot(
				in, userCodeClassLoader, null);
		} else if (readVersion >= 3) {
			Tuple2<TypeSerializer<?>, TypeSerializerSnapshot<?>> keySerializerAndConfig =
					TypeSerializerSerializationUtil.readSerializersAndConfigsWithResilience(in, userCodeClassLoader).get(0);
			this.keySerializerConfigSnapshot = (TypeSerializerSnapshot<K>) keySerializerAndConfig.f1;
		} else {
			this.keySerializerConfigSnapshot = new BackwardsCompatibleSerializerSnapshot<>(
				TypeSerializerSerializationUtil.tryReadSerializer(in, userCodeClassLoader, true));
		}
		this.keySerializer = null;

		Integer metaInfoSnapshotVersion = META_INFO_SNAPSHOT_FORMAT_VERSION_MAPPER.get(readVersion);
		if (metaInfoSnapshotVersion == null) {
			// this should not happen; guard for the future
			throw new IOException("Cannot determine corresponding meta info snapshot version for keyed backend serialization readVersion=" + readVersion);
		}
		final StateMetaInfoReader stateMetaInfoReader = StateMetaInfoSnapshotReadersWriters.getReader(
			metaInfoSnapshotVersion,
			StateMetaInfoSnapshotReadersWriters.StateTypeHint.KEYED_STATE);

		int numKvStates = in.readShort();
		stateMetaInfoSnapshots = new ArrayList<>(numKvStates);
		for (int i = 0; i < numKvStates; i++) {
			StateMetaInfoSnapshot snapshot = stateMetaInfoReader.readStateMetaInfoSnapshot(in, userCodeClassLoader);

			stateMetaInfoSnapshots.add(snapshot);
		}
	}
}


text:
/**
 * @flow
 */

import { AppRegistry } from 'react-native';
import CallMyReps from './js/CallMyReps';

AppRegistry.registerComponent('CallMyReps', () => CallMyReps);


text:
<?php

namespace Synapse\Cmf\Framework\Theme\Template\Domain;

use Synapse\Cmf\Framework\Theme\Content\Model\ContentInterface;
use Synapse\Cmf\Framework\Theme\Template\Model\TemplateInterface;
use Synapse\Cmf\Framework\Theme\Zone\Entity\ZoneCollection;

/**
 * Interface for Template domain use cases.
 */
interface DomainInterface
{
    /**
     * Create a local template linked to given content only, on given template type.
     *
     * @param ContentInterface|Content     $content
     * @param string|TemplateTypeInterface $templateType template type object or template type name
     * @param ZoneCollection               $zones
     *
     * @return TemplateInterface
     */
    public function createLocal($content, $templateType, ZoneCollection $zones = null);

    /**
     * Create a global template for given content type, on given template type.
     *
     * @param ContentInterface|Content|ContentType|string $content      content, internal content,
     *                                                                  content type object or content type name
     * @param string|TemplateTypeInterface                $templateType template type object or template type name
     * @param ZoneCollection                              $zones
     *
     * @return TemplateInterface
     */
    public function createGlobal($content, $templateType, ZoneCollection $zones = null);

    /**
     * Update given template with given parameters.
     *
     * @param TemplateInterface $template
     */
    public function edit(TemplateInterface $template);

    /**
     * Delete given template.
     *
     * @param TemplateInterface $template
     */
    public function delete(TemplateInterface $template);
}


text:
require 'capistrano/recipes/deploy/strategy/copy'
require 'erb'

module Capistrano
  module Deploy
    module Strategy
      class S3Copy < Copy

        def initialize(config={})
          super(config)

          s3cmd_vars = []
          ["aws_access_key_id", "aws_secret_access_key"].each do |var|
            value = configuration[var.to_sym]
            raise Capistrano::Error, "Missing configuration[:#{var}] setting" if value.nil?
            s3cmd_vars << "#{var.upcase}=#{value}"
          end
          @aws_environment = s3cmd_vars.join(" ")

          @bucket_name = configuration[:aws_releases_bucket]
          raise Capistrano::Error, "Missing configuration[:aws_releases_bucket]" if @bucket_name.nil?
        end

        def check!
          super.check do |d|
            d.local.command("s3cmd")
            d.remote.command("s3cmd")
          end
        end

        # Distributes the file to the remote servers
        def distribute!
          package_path = filename
          package_name = File.basename(package_path)
          s3_push_cmd = "#{aws_environment} s3cmd put #{bucket_name}:#{rails_env}/#{package_name} #{package_path} x-amz-server-side-encryption:AES256 2>&1"

          if configuration.dry_run
            logger.debug s3_push_cmd
          else
            system(s3_push_cmd)
            raise Capistrano::Error, "shell command failed with return code #{$?}" if $? != 0
          end

          run "#{aws_environment} s3cmd get #{bucket_name}:#{rails_env}/#{package_name} #{remote_filename} 2>&1"
          run "cd #{configuration[:releases_path]} && #{decompress(remote_filename).join(" ")} && rm #{remote_filename}"
          logger.debug "done!"

          build_aws_install_script
        end

        def build_aws_install_script
          template_text = configuration[:aws_install_script]
          template_text = File.read(File.join(File.dirname(__FILE__), "aws_install.sh.erb")) if template_text.nil?
          template_text = template_text.gsub("\r\n?", "\n")
          template = ERB.new(template_text, nil, '<>-')
          output = template.result(self.binding)
          local_output_file = File.join(copy_dir, "aws_install.sh")
          File.open(local_output_file, "w") do  |f|
            f.write(output)
          end
          configuration[:s3_copy_aws_install_cmd] = "#{aws_environment} s3cmd put #{bucket_name}:#{rails_env}/aws_install.sh #{local_output_file} x-amz-server-side-encryption:AES256 2>&1"
        end

        def binding
          super
        end

        def aws_environment
          @aws_environment
        end

        def bucket_name
          @bucket_name
        end
      end
    end
  end
end


text:
package com.huawei.streaming.expression;

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

import com.huawei.streaming.event.IEvent;
import com.huawei.streaming.exception.ErrorCode;
import com.huawei.streaming.exception.StreamingException;

/**
 * <属性值表达式>
 *
 */
public class PropertyValueExpression extends PropertyBasedExpression
{
    /**
     * 序列化id
     */
    private static final long serialVersionUID = -6772060263353223976L;

    private static final Logger LOG = LoggerFactory.getLogger(PropertyValueExpression.class);

    private int streamIndex;

    private int propertyIndex = -1;

    /**
     * <默认构造函数>
     *
     */
    public PropertyValueExpression(int id, String propertyName, Class< ? > type)
        throws StreamingException
    {
        super(propertyName, type);

        if (id < 0)
        {
            LOG.error("Schema index in property value expression must bigger than 0.");
            throw new StreamingException(ErrorCode.UNKNOWN_SERVER_COMMON_ERROR);
        }

        this.streamIndex = id;
    }

    /**
     * <默认构造函数>
     *
     */
    public PropertyValueExpression(String propertyName, Class< ? > type)
    {
        super(propertyName, type);
        this.streamIndex = 0;
    }

    /**
     * 返回 streamIndex
     *
     */
    public final int getStreamIndex()
    {
        return streamIndex;
    }

    public void setStreamIndex(int streamIndex)
    {
        this.streamIndex = streamIndex;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object evaluate(IEvent theEvent)
    {
        if (null == theEvent)
        {
            String msg = "Event is null!";
            LOG.error(msg);
            throw new RuntimeException(msg);
        }

        if (propertyIndex == -1)
        {
            propertyIndex = theEvent.getIndexByPropertyName(getPropertyName());
        }

        return theEvent.getValue(propertyIndex);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object evaluate(IEvent[] eventsPerStream)
    {
        if (null == eventsPerStream || 0 == eventsPerStream.length)
        {
            LOG.error("Streams events are null.");
            throw new RuntimeException("Streams events are null.");
        }

        String propertyName = getPropertyName();
        return eventsPerStream[streamIndex].getValue(propertyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Class< ? > getType()
    {
        return getPropertyType();
    }

}


text:
<?php if ( 'pfca_podcast' == get_post_type() ): ?>
<?php get_template_part('templates/content', 'podcast'); ?>

<?php elseif ( 'pfca_member' == get_post_type() ): ?>
<?php get_template_part('templates/content', 'member'); ?>

<?php else: ?>
<?php get_template_part('templates/content', 'single'); ?>

<?php endif; ?>


text:
package jft.mantis.tests;

import jft.mantis.appmanager.ApplicationManager;
import org.openqa.selenium.remote.BrowserType;
import org.testng.SkipException;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;

import javax.xml.rpc.ServiceException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;

/**
 * Created by Anna on 17.04.16.
 */
public class TestBase {

    protected static final ApplicationManager app =
            new ApplicationManager(System.getProperty("browser", BrowserType.CHROME));

    @BeforeSuite
    public void setUp() throws Exception {
        app.init();
    }

    @AfterSuite (alwaysRun = true)
    public void tearDown() {
        app.stop();
    }

    public void skipIfNotFixed(int issueId) throws RemoteException, ServiceException, MalformedURLException {
        if (app.soap().isIssueOpen(issueId)) {
            throw new SkipException("Ignored because of issue " + issueId);
        }
    }
}


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json.Linq;

namespace AzureStorageFileHost.ConfigurationStorage
{
    public class UploadConfigurationStore
    {
        private const string TableName = "uploadconfigs";
        public async Task<JObject> GetConfiguration(Guid apiKey)
        {
            var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("ConfigurationStore"));
            var tableClient = storageAccount.CreateCloudTableClient();
            var table = tableClient.GetTableReference(TableName);
            await table.CreateIfNotExistsAsync().ConfigureAwait(false);

            var retrieveConfigResult = await table.ExecuteAsync(
                TableOperation.Retrieve<ConfigurationEntity>("JsonConfig", apiKey.ToString("N"))).ConfigureAwait(false);
            if ((retrieveConfigResult.Result as ConfigurationEntity) == null)
            {
                throw new ArgumentOutOfRangeException("apiKey", "Provided API value does not match an upload configuration");
            }
            return JObject.Parse(((ConfigurationEntity)retrieveConfigResult.Result).Config);
        }

        public async Task<bool> AtLeastOneConfigExists()
        {
            try
            {
                var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("ConfigurationStore"));
                var tableClient = storageAccount.CreateCloudTableClient();
                var table = tableClient.GetTableReference(TableName);
                await table.CreateIfNotExistsAsync().ConfigureAwait(false);
                var configQuery = new TableQuery<ConfigurationEntity>().Where(
                    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "JsonConfig"));
                var resultSet = table.ExecuteQuery(configQuery);
                return resultSet.Any();
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}


text:
/*

What this code is about:

      This code example explores the screen capture API on Mac. It seems
      that we can either use AVFoundation or CGDsiplayStream* . The CGDisplayStream*
      is promoted by the `WWDC2012 506` video and seems to be -the- solution for
      high performance screenccapture where color conversion, scaling is done on the gpu.

Loose remarks:

      - it looks like We need to create a dispatch_queue which is serial (instead of concurrent)
      - there are a couple of different output formats (we want 420 full video range) see docs of `CGDisplayStreamCreate`

Frame callback:

        typedef void (^CGDisplayStreamFrameAvailableHandler)(
           CGDisplayStreamFrameStatus status,
           uint64_t displayTime,
           IOSurfaceRef frameSurface,
           CGDisplayStreamUpdateRef updateRef
        );

IOSurface info in your callback:

        This contains the pixels from the display. If you want to keep it for a longer period
        then the callback you need to:

          CFRetain()
          IOSurfaceIncrementUseCount()
          ..
          when ready ..
          ...
          CFRelease()
          IOSurfaceDecrementUseCount()

CGDisplayStreamCreate* properties:

        const CFStringRef kCGDisplayStreamSourceRect;
        const CFStringRef kCGDisplayStreamDestinationRect;
        const CFStringRef kCGDisplayStreamPreserveAspectRatio;
        const CFStringRef kCGDisplayStreamColorSpace;
        const CFStringRef kCGDisplayStreamMinimumFrameTime;
        const CFStringRef kCGDisplayStreamShowCursor;
        const CFStringRef kCGDisplayStreamQueueDepth;
        const CFStringRef kCGDisplayStreamYCbCrMatrix;

 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <CoreGraphics/CGDisplayStream.h>

int main() {
  printf("\n\ntest_api_research\n\n");

  size_t output_width = 1280;
  size_t output_height = 720;
  uint32_t pixel_format = '420f';
  pixel_format = 'BGRA';
  dispatch_queue_t dq = dispatch_queue_create("com.domain.screengrabber", DISPATCH_QUEUE_SERIAL);

  /* List displays. */
  CGDirectDisplayID display_ids[5]; /* just a typedef'd uint32_t */
  uint32_t found_displays = 0;
  CGError err = CGGetActiveDisplayList(5, display_ids, &found_displays); /* more values at: https://developer.apple.com/library/mac/documentation/CoreGraphics/Reference/CoreGraphicsConstantsRef/index.html#//apple_ref/c/tdef/CGError */

  if (kCGErrorSuccess != err) {
    printf("Error: failed to retrieve displays.\n");
    exit(EXIT_FAILURE);
  }

  if (0 == found_displays) {
    printf("Error: no active displays found.\n");
    exit(EXIT_FAILURE);
  }

  for (uint32_t i = 0; i < found_displays; ++i) {
    printf("Display: #%u, id: %u\n", i, display_ids[i]);
  }

  CGDisplayStreamRef sref;
  __block uint64_t prev_time = 0; /* because this variable is used in a dispatch_queue we need to use __block because we change it's value inside the block. */

  sref = CGDisplayStreamCreateWithDispatchQueue(display_ids[0],
                                                output_width,
                                                output_height,
                                                pixel_format,
                                                NULL,
                                                dq,
                                                ^(CGDisplayStreamFrameStatus status,    /* kCGDisplayStreamFrameComplete, *FrameIdle, *FrameBlank, *Stopped */
                                                  uint64_t time,                        /* Mach absolute time when the event occurred. */
                                                  IOSurfaceRef frame,                   /* opaque pixel buffer, can be backed by GL, CL, etc.. This may be NULL in some cases. See the docs if you want to keep access to this. */
                                                  CGDisplayStreamUpdateRef ref)
                                                {
                                                  printf("Got frame: %llu, ", time);

                                                  if (0 != prev_time) {
                                                    uint64_t d = time - prev_time;
                                                    printf("took: %llu ms.", (d / 1000000ull));
                                                  }

                                                  if (kCGDisplayStreamFrameStatusFrameComplete == status
                                                      && NULL != frame)
                                                    {

                                                      /*
                                                        IMPORTANT: w/o locking the surface the pixel buffer
                                                         seems to be overwritten by the OS, therefore we lock
                                                         it.
                                                      */
                                                      IOSurfaceLock(frame, kIOSurfaceLockReadOnly, NULL);

                                                      uint8_t* pix = (uint8_t*)IOSurfaceGetBaseAddress(frame);
                                                      if (NULL != pix) {
                                                        /* Now you can use the pixels. */
                                                      }

                                                      IOSurfaceUnlock(frame, kIOSurfaceLockReadOnly, NULL);
                                                    }
                                                  printf("\n");
                                                  prev_time = time;
                                                }
                                                );

  err = CGDisplayStreamStart(sref);

  if (kCGErrorSuccess != err) {
    printf("Error: failed to start streaming the display.\n");
    exit(EXIT_FAILURE);
  }

  while (true) {
    usleep(1e5);
  }

  err = CGDisplayStreamStop(sref);
  if (kCGErrorSuccess != err) {
    printf("Error: failed to stop streaming the display.\n");
    exit(EXIT_FAILURE);
  }

  printf("\n\n");
  return 0;
}


text:
namespace content {
class NotificationSource;
}

class Profile;

namespace extensions {

// This class caches tokens for the current user.  It will clear tokens out
// when the user logs out or after the specified timeout interval, or when
// the instance of chrome shuts down.
class TokenCacheService : public ProfileKeyedService,
                          public content::NotificationObserver {
 public:
  explicit TokenCacheService(Profile* profile);
  virtual ~TokenCacheService();

  // Store a token for the currently logged in user. We will look it up later by
  // the name given here, and we will expire the token after the timeout.  For a
  // timeout of 0, we never expire the token.  After time_to_live expires, the
  // token will be expired.
  void StoreToken(const std::string& token_name, const std::string& token_value,
                  base::TimeDelta time_to_live);

  // Retrieve a token for the currently logged in user.  This returns an empty
  // string if the token was not found or timed out.
  std::string RetrieveToken(const std::string& token_name);

  // Inherited from NotificationObserver.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

 private:
  friend class TokenCacheTest;

  struct TokenCacheData {
    std::string token;
    base::Time expiration_time;
  };

  // Map the token name (string) to token data.
  std::map<std::string, TokenCacheData> token_cache_;
  content::NotificationRegistrar registrar_;
  const Profile* const profile_;

  DISALLOW_COPY_AND_ASSIGN(TokenCacheService);
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_TOKEN_CACHE_TOKEN_CACHE_SERVICE_H_


text:
let Gibber, genAbstract, __ugenproto__

module.exports = function( _Gibber, _genAbstract, proto ) {
  Gibber = _Gibber
  genAbstract = _genAbstract
  waveObjects.saw = waveObjects.line
  __ugenproto__ = proto

  return waveObjects
}

const waveObjects = {
  lfo( freq=.5, bias=.5, amp=.5, phase=0 ) {
    const initPhase = phase
    const __cycle = genAbstract.ugens.cycle( freq, 0, { initialValue:phase })

    const sine = __cycle
    const ugen = genAbstract.ugens.add( bias, genAbstract.ugens.mul( sine, amp ) )
    ugen.__phase = initPhase

    ugen.__onrender = ()=> {

      ugen.frequency = v => {
        if( v === undefined ) {
          return freq
        }else{
          freq = v
          __cycle[0]( freq )
          //ugen.phase( initPhase )
        }
      }

      Gibber.addSequencingToMethod( ugen, 'frequency' )

      ugen.bias = v => {
        if( v === undefined ) {
          return bias
        }else{
          bias = v
          ugen[0]( bias )
          //ugen.phase( initPhase )
        }
      }

      Gibber.addSequencingToMethod( ugen, 'bias' )
    }

    ugen.phase = (value) => {
      if( value === undefined ) return ugen.__phase

      ugen.__phase = value
      if( ugen.rendered !== undefined ) {
        ugen.rendered.inputs[1].inputs[0].inputs[0].value = ugen.__phase
        ugen.rendered.shouldNotAdjust = true
      }
    }

    Gibber.addSequencingToMethod( ugen, 'phase' )

    return ugen
  },

  fade( measures=4, from=0, to=1 ) {

    const g = genAbstract.ugens
    const amt = to - from
    const incr = 1 / ((Gibber.Utility.beatsToMs( measures * 4 ) / 1000) * 44100) * amt
    const psr =  g.accum( incr, 0, { max:Infinity, min:-Infinity, shouldWrap:false, initialValue:0 })
    const min = from < to ? from : to
    const max = to > from ? to : from
    const fade = g.clamp( g.add( from, psr ), min, max )

    //debugger

    fade.shouldKill = {
      after: measures,
      final: to
    }

    return fade
  },

  beats( ...inputs ) {
    const ugen = Object.create( __ugenproto__ )
    ugen.name = 'phasor'
    ugen.inputs = inputs
    let numBeats = inputs[0]

    ugen.inputs[0] = Gibber.Utility.beatsToFrequency( inputs[0], 120 )
    inputs[2] = {min:0}

   ugen.__onrender = ()=> {
      // store original param change function for wrapping with btof value
      ugen.__frequency = ugen[0]

      ugen[0] = v => {
        if( v === undefined ) {
          return numBeats
        }else{
          numBeats = v
          const frequency = Gibber.Utility.beatsToFrequency( v, 120 )

          // reset phase
          ugen.rendered.value = 0
          ugen.rendered.shouldNotAdjust = true

          // pass btof value to phasor frequency via stored reference
          return ugen.__frequency( frequency )
        }
      }

      Gibber.addSequencingToMethod( ugen, '0' )
    }

    //console.log( 'beats:', ugen )

    return ugen
  },

  sine( periodInMeasures=1, center=0, amp=7, phase=0 )  {
    const freq = btof( periodInMeasures * 4, 120 )
    const initPhase = phase
    const __cycle = genAbstract.ugens.cycle( freq,0,{initialValue:phase} )

    const sine = __cycle
    const scalar = genAbstract.ugens.mul( amp, sine )
    const ugen = genAbstract.ugens.add( center, scalar )
    ugen.__phase = initPhase

    ugen.__onrender = ()=> {

      ugen[0] = v => {
        if( v === undefined ) {
          return periodInMeasures
        }else{
          periodInMeasures = v
          const freq = btof( periodInMeasures * 4, 120 )
          __cycle[0]( freq )
          ugen.phase( initPhase )
        }
      }

      Gibber.addSequencingToMethod( ugen, '0' )

      ugen[1] = v => {
        if( v === undefined ) {
          return center
        }else{
          center = v
          ugen[0]( center )
        }
      }

      Gibber.addSequencingToMethod( ugen, '1' )

      ugen[2] = v => {
        if( v === undefined ) {
          return amp
        }else{
          amp = v
          scalar[0]( amp )
        }
      }

      Gibber.addSequencingToMethod( ugen, '2' )
    }

    ugen.phase = value => {
      if( value === undefined ) return ugen.__phase

      ugen.__phase = value
      if( ugen.rendered !== undefined ) {
        ugen.rendered.inputs[1].inputs[1].inputs[0].value = ugen.__phase
        ugen.rendered.shouldNotAdjust = true
      }

      return ugen
    }

    Gibber.addSequencingToMethod( ugen, 'phase' )

    return ugen
  },

  siner( periodInMeasures=1, center=0, amp=7 ) {
    const freq = btof( periodInMeasures * 4, 120 )
    const __cycle = genAbstract.ugens.cycle( freq )

    const sine = __cycle
    const ugen = genAbstract.ugens.round( genAbstract.ugens.add( center, genAbstract.ugens.mul( sine, amp ) ) )

    ugen.sine = sine

    ugen.__onrender = ()=> {

      ugen[0] = v => {
        if( v === undefined ) {
          return periodInMeasures
        }else{
          periodInMeasures = v
          __cycle[0]( btof( periodInMeasures * 4, 120 ) )
        }
      }

      Gibber.addSequencingToMethod( ugen, '0' )
    }

    return ugen
  },

  cos( periodInMeasures=1, center=0, amp=7 )  {
    const freq = btof( periodInMeasures * 4, 120 )
    const __cycle = genAbstract.ugens.cycle( freq, 0, { initialValue:1 })

    const sine = __cycle
    const ugen = genAbstract.ugens.add( center, genAbstract.ugens.mul( sine, amp ) )

    ugen[0] = v => {
      if( v === undefined ) {
        return periodInMeasures
      }else{
        periodInMeasures = v
        __cycle[0]( btof( periodInMeasures * 4, 120 ) )
      }
    }

    Gibber.addSequencingToMethod( ugen, '0' )

    return ugen
  },

  cosr( periodInMeasures=1, center=0, amp=7 )  {
    const freq = btof( periodInMeasures * 4, 120 )
    const __cycle = genAbstract.ugens.cycle( freq, 0, { initialValue:1 })

    const sine = __cycle
    const ugen = genAbstract.ugens.round( genAbstract.ugens.add( center, genAbstract.ugens.mul( sine, amp ) ) )

    ugen[0] = v => {
      if( v === undefined ) {
        return periodInMeasures
      }else{
        periodInMeasures = v
        __cycle[0]( btof( periodInMeasures * 4, 120 ) )
      }
    }

    Gibber.addSequencingToMethod( ugen, '0' )

    return ugen
  },

  liner( periodInMeasures=1, min=0, max=7 )  {
    const line = genAbstract.ugens.beats( periodInMeasures * 4 )

    const ugen = genAbstract.ugens.round( genAbstract.ugens.add( min, genAbstract.ugens.mul( line, max-min ) ) )

    ugen.__onrender = ()=> {

      ugen[0] = v => {
        if( v === undefined ) {
          return periodInMeasures
        }else{
          periodInMeasures = v
          line[0]( v * 4 )
        }
      }

      Gibber.addSequencingToMethod( ugen, '0' )
    }

    return ugen
  },

  line( periodInMeasures=1, min=0, max=1 ) {
    const line = genAbstract.ugens.beats( periodInMeasures * 4 )

    // note messages are rounded in note filter, found in seq.js
    const ugen = genAbstract.ugens.add( min, genAbstract.ugens.mul( line, max-min ) )

    ugen.__onrender = ()=> {

      ugen[0] = v => {
        if( v === undefined ) {
          return periodInMeasures
        }else{
          periodInMeasures = v
          line[0]( v * 4 )
        }
      }

      Gibber.addSequencingToMethod( ugen, '0' )
    }

    return ugen
  }
}


text:
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
    Microsoft.CodeQuality.Analyzers.QualityGuidelines.MarkMembersAsStaticAnalyzer,
    Microsoft.CodeQuality.CSharp.Analyzers.QualityGuidelines.CSharpMarkMembersAsStaticFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
    Microsoft.CodeQuality.Analyzers.QualityGuidelines.MarkMembersAsStaticAnalyzer,
    Microsoft.CodeQuality.VisualBasic.Analyzers.QualityGuidelines.BasicMarkMembersAsStaticFixer>;

namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests
{
    public class MarkMembersAsStaticTests
    {
        [Fact]
        public async Task CSharpSimpleMembers()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
public class MembersTests
{
    internal static int s_field;
    public const int Zero = 0;

    public int Method1(string name)
    {
        return name.Length;
    }

    public void Method2() { }

    public void Method3()
    {
        s_field = 4;
    }

    public int Method4()
    {
        return Zero;
    }

    public int Property
    {
        get { return 5; }
    }

    public int Property2
    {
        set { s_field = value; }
    }

    public int MyProperty
    {
        get { return 10; }
        set { System.Console.WriteLine(value); }
    }

    public event System.EventHandler<System.EventArgs> CustomEvent { add {} remove {} }
}",
                GetCSharpResultAt(7, 16, "Method1"),
                GetCSharpResultAt(12, 17, "Method2"),
                GetCSharpResultAt(14, 17, "Method3"),
                GetCSharpResultAt(19, 16, "Method4"),
                GetCSharpResultAt(24, 16, "Property"),
                GetCSharpResultAt(29, 16, "Property2"),
                GetCSharpResultAt(34, 16, "MyProperty"),
                GetCSharpResultAt(40, 56, "CustomEvent"));
        }

        [Fact]
        public async Task BasicSimpleMembers()
        {
            await VerifyVB.VerifyAnalyzerAsync(@"
Imports System

Public Class MembersTests
    Shared s_field As Integer
    Public Const Zero As Integer = 0

    Public Function Method1(name As String) As Integer
        Return name.Length
    End Function

    Public Sub Method2()
    End Sub

    Public Sub Method3()
        s_field = 4
    End Sub

    Public Function Method4() As Integer
        Return Zero
    End Function

    Public ReadOnly Property Property1 As Integer
        Get
            Return 5
        End Get
    End Property

    Public WriteOnly Property Property2 As Integer
        Set
            s_field = Value
        End Set
    End Property

    Public Property MyProperty As Integer
        Get
            Return 10
        End Get
        Set
            System.Console.WriteLine(Value)
        End Set
    End Property

    Public Custom Event CustomEvent As EventHandler(Of EventArgs)
        AddHandler(value As EventHandler(Of EventArgs))
        End AddHandler
        RemoveHandler(value As EventHandler(Of EventArgs))
        End RemoveHandler
        RaiseEvent(sender As Object, e As EventArgs)
        End RaiseEvent
    End Event
End Class
",
                GetBasicResultAt(8, 21, "Method1"),
                GetBasicResultAt(12, 16, "Method2"),
                GetBasicResultAt(15, 16, "Method3"),
                GetBasicResultAt(19, 21, "Method4"),
                GetBasicResultAt(23, 30, "Property1"),
                GetBasicResultAt(29, 31, "Property2"),
                GetBasicResultAt(35, 21, "MyProperty"),
                GetBasicResultAt(44, 25, "CustomEvent"));
        }

        [Fact]
        public async Task CSharpSimpleMembers_Internal_DiagnosticsOnlyForInvokedMethods()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
internal class MembersTests
{
    internal static int s_field;
    public const int Zero = 0;

    public int Method1(string name)
    {
        return name.Length;
    }

    public void Method2() { }

    public void Method3()
    {
        s_field = 4;
    }

    public int Method4()
    {
        return Zero;
    }

    public int Property
    {
        get { return 5; }
    }

    public int Property2
    {
        set { s_field = value; }
    }

    public int MyProperty
    {
        get { return 10; }
        set { System.Console.WriteLine(value); }
    }

    public event System.EventHandler<System.EventArgs> CustomEvent { add {} remove {} }

    public void Common(string arg)
    {
        // Invoked, hence must be flagged.
        Method1(arg);

        // Invoked via delegate - should not be flagged.
        System.Action<System.Action> a = (System.Action m) => m();
        a(Method2);

        // Method3 is dead code that is never invoked - it should still be flagged.
        // Method3();

        // Invoked within a lambda - must be flagged.
        System.Func<int> b = () => Method4();

        // Candidate accessors/properties/events are always flagged, regardless of them being used or not.
        int x = Property;
        // int y = Property2;
        MyProperty = 10; // getter not accessed.
    }
}",
                GetCSharpResultAt(7, 16, "Method1"),
                GetCSharpResultAt(14, 17, "Method3"),
                GetCSharpResultAt(19, 16, "Method4"),
                GetCSharpResultAt(24, 16, "Property"),
                GetCSharpResultAt(29, 16, "Property2"),
                GetCSharpResultAt(34, 16, "MyProperty"),
                GetCSharpResultAt(40, 56, "CustomEvent"));
        }

        [Fact]
        public async Task BasicSimpleMembers_Internal_DiagnosticsOnlyForInvokedMethods()
        {
            await VerifyVB.VerifyAnalyzerAsync(@"
Imports System

Friend Class MembersTests
    Shared s_field As Integer
    Public Const Zero As Integer = 0

    Public Function Method1(name As String) As Integer
        Return name.Length
    End Function

    Public Sub Method2()
    End Sub

    Public Sub Method3()
        s_field = 4
    End Sub

    Public Function Method4() As Integer
        Return Zero
    End Function

    Public ReadOnly Property Property1 As Integer
        Get
            Return 5
        End Get
    End Property

    Public WriteOnly Property Property2 As Integer
        Set
            s_field = Value
        End Set
    End Property

    Public Property MyProperty As Integer
        Get
            Return 10
        End Get
        Set
            System.Console.WriteLine(Value)
        End Set
    End Property

    Public Custom Event CustomEvent As EventHandler(Of EventArgs)
        AddHandler(value As EventHandler(Of EventArgs))
        End AddHandler
        RemoveHandler(value As EventHandler(Of EventArgs))
        End RemoveHandler
        RaiseEvent(sender As Object, e As EventArgs)
        End RaiseEvent
    End Event

    Public Sub Common(ByVal arg As String)
        ' Invoked, hence must be flagged.
        Method1(arg)

        ' Invoked via delegate - should not be flagged.
        Dim a As System.Action(Of System.Action) = Sub(ByVal m As System.Action) m()
        a(AddressOf Method2)

        ' Method3 is dead code that is never invoked - it should still be flagged.
        'Method3()

        ' Invoked within a lambda - must be flagged.
        Dim b As System.Func(Of Integer) = Function() Method4()

        ' Candidate accessors/properties/events are always flagged, regardless of them being used or not.
        Dim x As Integer = Property1
        'Dim y As Integer = Property2
        MyProperty = 10
End Sub

End Class
",
                GetBasicResultAt(8, 21, "Method1"),
                GetBasicResultAt(15, 16, "Method3"),
                GetBasicResultAt(19, 21, "Method4"),
                GetBasicResultAt(23, 30, "Property1"),
                GetBasicResultAt(29, 31, "Property2"),
                GetBasicResultAt(35, 21, "MyProperty"),
                GetBasicResultAt(44, 25, "CustomEvent"));
        }

        [Fact]
        public async Task CSharpSimpleMembers_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
public class MembersTests
{
    public MembersTests() { }

    ~MembersTests() { }

    public int x;

    public int Method1(string name)
    {
        return x;
    }

    public int Method2()
    {
        MembersTests temp = this;
        return temp.x;
    }

    private int backingField;
    public int Prop1
    {
        get { return backingField; }
        set { backingField = value; }
    }

    public int AutoProp { get; set; }
    public int GetterOnlyAutoProp { get; }

    public void SomeEventHandler(object sender, System.EventArgs args) { }

    public void SomeNotImplementedMethod() => throw new System.NotImplementedException();

    public void SomeNotSupportedMethod() => throw new System.NotSupportedException();

    public int this[int x] => 42;
}

public class Generic<T>
{
    public void Method1() { }

    public int Property
    {
        get { return 5; }
    }
}
");
        }

        [Fact]
        public async Task BasicSimpleMembers_NoDiagnostic()
        {
            await VerifyVB.VerifyAnalyzerAsync(@"
Public Class MembersTests
    Public Sub New()
    End Sub

    Protected Overrides Sub Finalize()
    End Sub

    Public x As Integer

    Public Function Method1(name As String) As Integer
        Return x
    End Function

    Public Function Method2() As Integer
        Dim temp As MembersTests = Me
        Return temp.x
    End Function

    Private backingField As Integer
    Public Property Prop1 As Integer
        Get
            Return backingField
        End Get
        Set
            backingField = Value
        End Set
    End Property

    Public Property AutoProp As Integer
    Public ReadOnly Property GetterOnlyAutoProp As Integer

    Public Sub SomeEventHandler(sender As Object, args As System.EventArgs)
    End Sub

    Public Sub SomeNotImplementedMethod()
        Throw New System.NotImplementedException()
    End Sub

    Public Sub SomeNotSupportedMethod()
        Throw New System.NotSupportedException()
    End Sub

    Default Public ReadOnly Property Item(x As Integer) As Integer
        Get
            Return 42
        End Get
    End Property
End Class

Public Class Generic(Of T)
    Public Sub Method1()
    End Sub

    Public ReadOnly Property Property1 As Integer
        Get
            Return 5
        End Get
    End Property
End Class
");
        }

        [Fact]
        public async Task CSharpOverrides_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
public abstract class SpecialCasesTest1
{
    public abstract void AbstractMethod();
}

public interface ISpecialCasesTest
{
    int Calculate(int arg);
}

public class SpecialCasesTest2 : SpecialCasesTest1, ISpecialCasesTest
{
    public virtual void VirtualMethod() {}

    public override void AbstractMethod() { }

    public int Calculate(int arg) { return arg/2; }
}");
        }

        [Fact]
        public async Task BasicOverrides_NoDiagnostic()
        {
            await VerifyVB.VerifyAnalyzerAsync(@"
Public MustInherit Class SpecialCasesTest1
    Public MustOverride Sub AbstractMethod()
End Class

Public Interface ISpecialCasesTest
    Function Calculate(arg As Integer) As Integer
End Interface

Public Class SpecialCasesTest2
    Inherits SpecialCasesTest1
    Implements ISpecialCasesTest

    Public Overridable Sub VirtualMethod()
    End Sub

    Public Overrides Sub AbstractMethod()
    End Sub
    Public Function Calculate(arg As Integer) As Integer Implements ISpecialCasesTest.Calculate
        Return arg / 2
    End Function
End Class
");
        }

        [Fact]
        public async Task CSharpNoDiagnostic_ComVisibleAttribute()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Runtime.InteropServices;

public class Test
{
    [ComVisible(true)]
    public void Method2() { }
}

[ComVisible(true)]
public class ComVisibleClass
{
    public void Method1() { }
}
");
        }

        [Fact]
        public async Task BasicNoDiagnostic_ComVisibleAttribute()
        {
            await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Imports System.Runtime.InteropServices

Public Class Test
    <ComVisible(True)>
    Public Sub Method2()
    End Sub
End Class

<ComVisible(True)>
Public Class ComVisibleClass
    Public Sub Method1()
    End Sub
End Class
");
        }

        [Theory]
        [InlineData("Microsoft.VisualStudio.TestTools.UnitTesting.TestInitialize", true, false, false)]
        [InlineData("Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod", true, false, false)]
        [InlineData("Microsoft.VisualStudio.TestTools.UnitTesting.DataTestMethod", true, false, false)]
        [InlineData("Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanup", true, false, false)]
        [InlineData("Xunit.Fact", false, false, true)]
        [InlineData("Xunit.Theory", false, false, true)]
        [InlineData("CustomxUnit.WpfFact", false, false, true)]
        [InlineData("NUnit.Framework.OneTimeSetUp", false, true, false)]
        [InlineData("NUnit.Framework.OneTimeTearDown", false, true, false)]
        [InlineData("NUnit.Framework.SetUp", false, true, false)]
        [InlineData("NUnit.Framework.TearDown", false, true, false)]
        [InlineData("NUnit.Framework.Test", false, true, false)]
        [InlineData("NUnit.Framework.TestCase(\"asdf\")", false, true, false)]
        [InlineData("NUnit.Framework.TestCaseSource(\"asdf\")", false, true, false)]
        [InlineData("NUnit.Framework.Theory", false, true, false)]
        public async Task NoDiagnostic_TestAttributes(string testAttributeData, bool isMSTest, bool isNUnit, bool isxunit)
        {
            var referenceAssemblies = (isMSTest, isNUnit, isxunit) switch
            {
                (true, false, false) => AdditionalMetadataReferences.DefaultWithMSTest,
                (false, true, false) => AdditionalMetadataReferences.DefaultWithNUnit,
                (false, false, true) => AdditionalMetadataReferences.DefaultWithXUnit,
                _ => throw new InvalidOperationException("Invalid combination of test framework")
            };

            await new VerifyCS.Test
            {
                ReferenceAssemblies = referenceAssemblies,
                TestState =
                {
                    Sources =
                    {
                        $@"
using System;

public class Test
{{
    [{testAttributeData}]
    public void Method1() {{}}
}}
",
                        !isxunit ? "" : @"
namespace CustomxUnit
{
    using System;
    using Xunit;

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class WpfFactAttribute : FactAttribute
    {
    }
}",
                    },
                },
            }.RunAsync();

            await new VerifyVB.Test
            {
                ReferenceAssemblies = referenceAssemblies,
                TestState =
                {
                    Sources =
                    {
                        $@"
Imports System

Public Class Test
    <{testAttributeData}>
    Public Sub Method1()
    End Sub
End Class
",
                        !isxunit ? "" : @"
Imports System

Namespace CustomxUnit

    <AttributeUsage(AttributeTargets.Method, AllowMultiple:=False)>
    Public Class WpfFactAttribute
        Inherits Xunit.FactAttribute
    End Class
End Namespace
",
                    },
                },
            }.RunAsync();
        }

        [Fact, WorkItem(3019, "https://github.com/dotnet/roslyn-analyzers/issues/3019")]
        public async Task PrivateMethodOnlyCalledByASkippedMethod_Diagnostic()
        {
            await new VerifyCS.Test
            {
                ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithXUnit,
                TestState =
                {
                    Sources =
                    {
                        @"
using Xunit;

public class Program
{
    [Fact]
    private void M()
    {
        N();
    }

    private void N()
    {
    }
}",
                    },
                    ExpectedDiagnostics =
                    {
                        GetCSharpResultAt(12, 18, "N")
                    }
                }
            }.RunAsync();
        }

        [Fact, WorkItem(3019, "https://github.com/dotnet/roslyn-analyzers/issues/3019")]
        public async Task PrivateMethodOnlyReferencedByASkippedMethod_NoDiagnostic()
        {
            await new VerifyCS.Test
            {
                ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithXUnit,
                TestState =
                {
                    Sources =
                    {
                        @"
using Xunit;

public class Program
{
    [Fact]
    private void M()
    {
        var x = nameof(N);
    }

    private void [|N|]()
    {
    }
}",
                    }
                }
            }.RunAsync();
        }

        [Fact, WorkItem(1865, "https://github.com/dotnet/roslyn-analyzers/issues/1865")]
        public async Task CSharp_InstanceReferenceInObjectInitializer_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
public class A
{
    public void M()
    {
        var x = new B() { P = true };
    }
}

public class B
{
    public bool P { get; set; }
}",
            // Test0.cs(4,17): warning CA1822: Member M does not access instance data and can be marked as static (Shared in VisualBasic)
            GetCSharpResultAt(4, 17, "M"));
        }

        [Fact, WorkItem(1865, "https://github.com/dotnet/roslyn-analyzers/issues/1865")]
        public async Task Basic_InstanceReferenceInObjectInitializer_Diagnostic()
        {
            await VerifyVB.VerifyAnalyzerAsync(@"
Public Class A
    Public Sub M()
        Dim x = New B With {.P = True}
    End Sub
End Class

Public Class B
    Public Property P As Boolean
End Class
",
            // Test0.vb(3,16): warning CA1822: Member M does not access instance data and can be marked as static (Shared in VisualBasic)
            GetBasicResultAt(3, 16, "M"));
        }

        [Fact, WorkItem(1933, "https://github.com/dotnet/roslyn-analyzers/issues/1933")]
        public async Task CSharpPropertySingleAccessorAccessingInstance_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
public class MyClass
{
    private static bool StaticThing;
    private bool InstanceThing;

    public bool Thing1
    {
        get { return StaticThing; }
        set
        {
            StaticThing = value;
            InstanceThing = value;
        }
    }

    public bool Thing2
    {
        get { return InstanceThing && StaticThing; }
        set
        {
            StaticThing = value;
        }
    }
}");
        }

        [Fact, WorkItem(1933, "https://github.com/dotnet/roslyn-analyzers/issues/1933")]
        public async Task CSharpEventWithSingleAccessorAccessingInstance_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;

public class MyClass
{
    private static bool StaticThing;
    private bool InstanceThing;

    event EventHandler MyEvent1
    {
        add
        {
            StaticThing = true;
            InstanceThing = true;
        }
        remove
        {
            StaticThing = true;
        }
    }

    event EventHandler MyEvent2
    {
        add
        {
            StaticThing = true;
        }
        remove
        {
            StaticThing = true;
            InstanceThing = true;
        }
    }
}");
        }

        [Fact, WorkItem(2414, "https://github.com/dotnet/roslyn-analyzers/issues/2414")]
        public async Task CSharp_ErrorCase_MethodWithThrowNotInCatch()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;

class C
{
    private void [|Validate|]()
    {
        {|CS0156:throw|};
    }
}");
        }

        [Fact, WorkItem(2785, "https://github.com/dotnet/roslyn-analyzers/issues/2785")]
        public async Task CSharp_CustomTestMethodAttribute_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;

namespace Microsoft.VisualStudio.TestTools.UnitTesting
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
    public class TestMethodAttribute : Attribute
    {
        public TestMethodAttribute() {}
    }
}

namespace SomeNamespace
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [AttributeUsage(AttributeTargets.Method)]
    public sealed class CustomTestAttribute : TestMethodAttribute
    {
        public CustomTestAttribute() {}
    }

    public class C
    {
        [CustomTest]
        public void Test()
        {
            Console.WriteLine();
        }
    }
}");
        }

        [Theory, WorkItem(3835, "https://github.com/dotnet/roslyn-analyzers/issues/3835")]
        [InlineData("build_property.UsingMicrosoftNETSdkWeb = true")]
        [InlineData("build_property.ProjectTypeGuids = {349C5851-65DF-11DA-9384-00065B846F21}")]
        [InlineData("build_property.ProjectTypeGuids = {e24c65dc-7377-472B-9ABA-BC803B73C61A}")]
        [InlineData("build_property.ProjectTypeGuids = {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}")]
        [InlineData("build_property.ProjectTypeGuids = {349c5851-65df-11da-9384-00065b846f21} ; {fae04ec0-301f-11d3-bf4b-00c04f79efbc}")]
        [InlineData("dotnet_code_quality.api_surface = private, internal")]
        public async Task WebSpecificControllerMethods_NoDiagnostic(string editorConfigText)
        {
            var csSource = @"
using System;

namespace System.Web
{
    public class HttpApplication {}
}

public class C : System.Web.HttpApplication
{
    // The following methods are detected as event handler and so won't
    // trigger a diagnostic
    protected void Application_Start(object sender, EventArgs e) { }
    protected void Application_AuthenticateRequest(object sender, EventArgs e) { }
    protected void Application_BeginRequest(object sender, EventArgs e) { }
    protected void Application_EndRequest(object sender, EventArgs e) { }
    protected void Application_Error(object sender, EventArgs e) { }
    protected void Application_End(object sender, EventArgs e) { }
    protected void Application_Init(object sender, EventArgs e) { }
    protected void Session_End(object sender, EventArgs e) { }
    protected void Session_Start(object sender, EventArgs e) { }

    // The following controller methods can't be made static
    protected void Application_Start() { }
    protected void Application_End() { }
}";

            await new VerifyCS.Test()
            {
                TestCode = csSource,
                AnalyzerConfigDocument = editorConfigText,
            }.RunAsync();

            var vbSource = @"
Imports System

Namespace System.Web
    Public Class HttpApplication
    End Class
End Namespace

Public Class C
    Inherits System.Web.HttpApplication

    Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Application_Init(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Protected Sub Application_Start()
    End Sub

    Protected Sub Application_End()
    End Sub
End Class
";
            await new VerifyVB.Test()
            {
                TestCode = vbSource,
                AnalyzerConfigDocument = editorConfigText,
            }.RunAsync();
        }

        [Fact]
        public async Task MethodsWithOptionalParameter()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
internal class C
{
    private int x;

    public int M1(int y = 0)
    {
        return x;
    }

    public int [|M2|](int y = 0)
    {
        return 0;
    }
}");

            await VerifyVB.VerifyAnalyzerAsync(@"
Imports System

Friend Class C
    Private x As Integer

    Public Function M1(Optional y As Integer = 0) As Integer
        Return x
    End Function

    Public Function [|M2|](Optional y As Integer = 0) As Integer
        Return 0
    End Function
End Class
");
        }

        [Fact, WorkItem(3857, "https://github.com/dotnet/roslyn-analyzers/issues/3857")]
        public async Task CA1822_ObsoleteAttribute_NoDiagnostic()
        {
            await new VerifyCS.Test
            {
                LanguageVersion = LanguageVersion.CSharp8,
                TestCode = @"
using System;

public class C
{
    [Obsolete]
    public void M1() {}

    [Obsolete(""Some reason"")]
    public void M2() {}

    [Obsolete(""Some reason"", false)]
    public void M3() {}

    [Obsolete]
    public int P1
    {
        get { return 10; }
        set { Console.WriteLine(""""); }
    }

    public int P2
    {
        [Obsolete]
        get { return 10; }
        set { Console.WriteLine(""""); }
    }

    public int P3
    {
        get { return 10; }
        [Obsolete]
        set { Console.WriteLine(""""); }
    }

    [Obsolete]
    public event EventHandler<EventArgs> E1 { add {} remove {} }
}

[Obsolete]
public class C2
{
    public void M1() {}

    public int P1
    {
        get { return 10; }
        set { Console.WriteLine(""""); }
    }

    public event EventHandler<EventArgs> E1 { add {} remove {} }
}

[Obsolete]
public class C3
{
    public class C4
    {
        public void M1() {}

        public int P1
        {
            get { return 10; }
            set { Console.WriteLine(""""); }
        }

        public event EventHandler<EventArgs> E1 { add {} remove {} }
    }
}",
            }.RunAsync();

            await VerifyVB.VerifyAnalyzerAsync(@"
Imports System

Public Class C
    <Obsolete>
    Public Sub M1()
    End Sub

    <Obsolete(""Some reason"")>
    Public Sub M2()
    End Sub

    <Obsolete(""Some reason"", False)>
    Public Sub M3()
    End Sub

    <Obsolete>
    Public Property P1 As Integer
        Get
            Return 10
        End Get
        Set(ByVal value As Integer)
            Console.WriteLine("""")
        End Set
    End Property

    Public Property P2 As Integer
        <Obsolete>
        Get
            Return 10
        End Get
        Set(ByVal value As Integer)
            Console.WriteLine("""")
        End Set
    End Property

    Public Property P3 As Integer
        Get
            Return 10
        End Get
        <Obsolete>
        Set(ByVal value As Integer)
            Console.WriteLine("""")
        End Set
    End Property

    <Obsolete>
    Public Custom Event CustomEvent As EventHandler(Of EventArgs)
        AddHandler(value As EventHandler(Of EventArgs))
        End AddHandler
        RemoveHandler(value As EventHandler(Of EventArgs))
        End RemoveHandler
        RaiseEvent(sender As Object, e As EventArgs)
        End RaiseEvent
    End Event
End Class

<Obsolete>
Public Class C2
    Public Sub M1()
    End Sub

    Public Property P1 As Integer
        Get
            Return 10
        End Get
        Set(ByVal value As Integer)
            Console.WriteLine("""")
        End Set
    End Property

    Public Custom Event CustomEvent As EventHandler(Of EventArgs)
        AddHandler(value As EventHandler(Of EventArgs))
        End AddHandler
        RemoveHandler(value As EventHandler(Of EventArgs))
        End RemoveHandler
        RaiseEvent(sender As Object, e As EventArgs)
        End RaiseEvent
    End Event
End Class

<Obsolete>
Public Class C3
    Public Class C4
        Public Sub M1()
        End Sub

        Public Property P1 As Integer
            Get
                Return 10
            End Get
            Set(ByVal value As Integer)
                Console.WriteLine("""")
            End Set
        End Property

        Public Custom Event CustomEvent As EventHandler(Of EventArgs)
            AddHandler(value As EventHandler(Of EventArgs))
            End AddHandler
            RemoveHandler(value As EventHandler(Of EventArgs))
            End RemoveHandler
            RaiseEvent(sender As Object, e As EventArgs)
            End RaiseEvent
        End Event
    End Class
End Class
");
        }

        [Theory, WorkItem(3835, "https://github.com/dotnet/roslyn-analyzers/issues/3835")]
        [InlineData("build_property.UsingMicrosoftNETSdkWeb = true")]
        [InlineData("build_property.ProjectTypeGuids = {349C5851-65DF-11DA-9384-00065B846F21}")]
        [InlineData("build_property.ProjectTypeGuids = {e24c65dc-7377-472B-9ABA-BC803B73C61A}")]
        [InlineData("build_property.ProjectTypeGuids = {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}")]
        [InlineData("build_property.ProjectTypeGuids = {349c5851-65df-11da-9384-00065b846f21} ; {fae04ec0-301f-11d3-bf4b-00c04f79efbc}")]
        [InlineData("dotnet_code_quality.api_surface = private, internal")]
        public async Task TestWebProject(string editorConfigText)
        {
            var csSource = @"
public class Test
{
    public int PublicMethod() => 0;
    protected int ProtectedMethod() => 0;
    internal int [|InternalMethod|]() => 0;
    private int [|PrivateMethod|]() => 0;
}";
            await new VerifyCS.Test()
            {
                TestCode = csSource,
                AnalyzerConfigDocument = editorConfigText,
            }.RunAsync();

            var vbSource = @"
Public Class Test
    Public Function PublicMethod() As Integer
        Return 0
    End Function

    Protected Function ProtectedMethod() As Integer
        Return 0
    End Function

    Friend Function [|FriendMethod|]() As Integer
        Return 0
    End Function

    Private Function [|PrivateMethod|]() As Integer
        Return 0
    End Function
End Class";
            await new VerifyVB.Test()
            {
                TestCode = vbSource,
                AnalyzerConfigDocument = editorConfigText,
            }.RunAsync();
        }

        [Fact, WorkItem(2834, "https://github.com/dotnet/roslyn-analyzers/issues/2834")]
        public async Task FullProperties_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
    private int field;

    public int P1
    {
        get { return field; }
        set { field = value; }
    }

    public int P2
    {
        get { return field; }
    }

    public int P3 => field;

    public int P4
    {
        get => field;
        set => field = value;
    }
}");
        }

        [Fact, WorkItem(2834, "https://github.com/dotnet/roslyn-analyzers/issues/2834")]
        public async Task AutoProperties_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.Diagnostics;
using System.Runtime.CompilerServices;

public class C1
{
    public string P1 { get; set; }

    public string P2 { get; }

    public string P3
    {
        [DebuggerStepThrough]
        get;
    }

    public string [|P4|] // Because of the error there is no generated field
    {
        [DebuggerStepThrough]
        {|CS8051:set|};
    }

    public string P5
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        get;
    }
}");
        }

        [Fact, WorkItem(2834, "https://github.com/dotnet/roslyn-analyzers/issues/2834")]
        public async Task Properties_StaticField_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
public class C1
{
    private static int s_field;

    public int [|P1|]
    {
        get { return s_field; }
        set { s_field = value; }
    }

    public int [|P2|]
    {
        get { return s_field; }
    }

    public int [|P3|]
    {
        set { s_field = value; }
    }
}");
        }

        [Fact, WorkItem(4304, "https://github.com/dotnet/roslyn-analyzers/pull/4304")]
        public async Task SkippableFactAttribute()
        {
            await new VerifyCS.Test
            {
                ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithXUnit,
                TestCode = @"
using Xunit;

public class SkippableFactAttribute : FactAttribute {}

public class C
{
    [SkippableFact]
    public void M() {}
}",
            }.RunAsync();
        }

        [Fact, WorkItem(4623, "https://github.com/dotnet/roslyn-analyzers/issues/4623")]
        public async Task AwaiterPattern_INotifyCompletion_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Runtime.CompilerServices;

public class DummyAwaiter : INotifyCompletion
{
    public void GetResult()
    {
    }

    public bool IsCompleted => false;

    public void OnCompleted(Action continuation) => throw null;
}");
        }

        [Fact, WorkItem(4623, "https://github.com/dotnet/roslyn-analyzers/issues/4623")]
        public async Task AwaiterPattern_ICriticalNotifyCompletion_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Runtime.CompilerServices;

public class DummyAwaiter : ICriticalNotifyCompletion
{
    public void GetResult()
    {
    }

    public bool IsCompleted => false;

    public void OnCompleted(Action continuation) => throw null;
    public void UnsafeOnCompleted(Action continuation) => throw null;
}");
        }

        [Fact, WorkItem(4623, "https://github.com/dotnet/roslyn-analyzers/issues/4623")]
        public async Task AwaitablePattern_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Runtime.CompilerServices;

public class DummyAwaitable
{
    public DummyAwaiter GetAwaiter() => new DummyAwaiter();
}

public class DummyAwaiter : INotifyCompletion
{
    public void GetResult()
    {
    }

    public bool IsCompleted => false;

    public void OnCompleted(Action continuation) => throw null;
}");
        }

        private DiagnosticResult GetCSharpResultAt(int line, int column, string symbolName)
#pragma warning disable RS0030 // Do not used banned APIs
            => VerifyCS.Diagnostic()
                .WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
                .WithArguments(symbolName);

        private static DiagnosticResult GetBasicResultAt(int line, int column, string symbolName)
#pragma warning disable RS0030 // Do not used banned APIs
            => VerifyVB.Diagnostic()
                .WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
                .WithArguments(symbolName);
    }
}