text:
from gdata.youtube.service import YouTubeService, YOUTUBE_PLAYLIST_FEED_URI
from massmedia import settings
from django.http import QueryDict
from urlparse import urlparse

class YouTubeBase(object):
    """
    A simple class to get the info for a youtube feed
    """

    def __init__(self, url=None):
        self.url = url
        self._service = None
        self.metadata = {}
        self.entries = []
        self.process_url()

    def process_url(self):
        """
        Overridden by subclasses
        """
        pass

    def get_service(self):
        """
        Return the cached service object or get it and cache it.
        """
        if self._service is None:
            self._service = YouTubeService()
            if settings.SERVICES['YOUTUBE']['EMAIL'] != '' and settings.SERVICES['YOUTUBE']['PASSWORD'] != '':
                self._service.email = settings.SERVICES['YOUTUBE']['EMAIL']
                self._service.password = settings.SERVICES['YOUTUBE']['PASSWORD']
                self._service.ProgrammaticLogin()
        return self._service

    @staticmethod
    def get_url_from_links(link_list, rel):
        """
        From a list of link elements, return the url for the given rel type
        """
        for item in link_list:
            if item.rel == rel:
                return item.href

    @staticmethod
    def get_default_content(content_list):
        """
        return the default content from a content list
        """
        for fmt in content_list:
            if 'isDefault' in fmt.extension_attributes:
                return fmt

    @staticmethod
    def get_biggest_thumbnail(thumb_list):
        """
        return the biggest thumbnail item
        """
        biggest = None
        big_size = 0
        for item in thumb_list:
            if biggest is None:
                biggest = item
                big_size = int(item.width) * int(item.height)
            else:
                item_size = int(item.width) * int(item.height)
                if item_size > big_size:
                    biggest = item
                    big_size = item_size
        return biggest

    @staticmethod
    def convert_to_python(element):
        """
        Convert to base python structures
        """
        from atom.core import XmlElement
        from atom import AtomBase

        ignorable_keys = ['scheme', 'namespace']
        if isinstance(element, (list, tuple)):
            output = []
            for item in element:
                output.append(YouTubeBase.convert_to_python(item))
        elif isinstance(element, dict):
            output = {}
            for key, val in element.items():
                if key.startswith("_") or key in ignorable_keys or val is None:
                    continue
                elif key == 'extension_attributes':
                    output.update(val)
                elif key == 'extension_elements':
                    for item in val:
                        # Do something with item.attributes?
                        # if item.attributes:
                        #     print item
                        #     raise
                        if item.children:
                            output[item.tag] = YouTubeBase.convert_to_python(item.children)
                        else:
                            output[item.tag] = item.text
                elif isinstance(val, (tuple, list)):
                    if len(val) == 0:
                        continue
                    output[key] = []
                    for item in val:
                        output[key].append(YouTubeBase.convert_to_python(item))
                elif isinstance(val, (basestring, int, float, bool)):
                    output[key] = val
                elif isinstance(val, dict):
                    output[key] = YouTubeBase.convert_to_python(val)
                elif issubclass(val.__class__, (XmlElement, AtomBase)):
                    output[key] = YouTubeBase.convert_to_python(val.__dict__)
                else:
                    output[key] = val
                    print "Unkonwn type: ", type(val), val.__class__
            if len(output.keys()) == 1:
                return output.values()[0]
            elif set(output.keys()) == set(('text', 'type')):
                return output['text']
            else:
                return output
        else:
            return YouTubeBase.convert_to_python(element.__dict__)

class YouTubeFeed(YouTubeBase):
    """
    A YouTube feed
    """
    def process_url(self):
        """
        Process the feed url and set the metadata and entries
        """
        if 'gdata.youtube.com' not in self.url:
            playlist_id = QueryDict(urlparse(self.url).query)['list']
            self.url = "%s/%s" % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id)
        feed = self.get_service().GetYouTubeVideoFeed(uri=self.url)
        self.metadata = self.convert_to_python(feed.__dict__)
        self.entries = self.metadata['entry'][:]
        del self.metadata['entry']


text:
layout: page
subheadline: Chip Mounters Tray
title:  "STF-100N (2007)"
breadcrumb: true
tags:
    - Samsung
    - Samsung Chip Mounters
categories:
    - chip-mounters
header: no
image:
    title:

permalink: "/smt-equipment/chip-mounters/samsung/:title/"
---

- Vintage: 2007

### Other Chip Mounters ###
{: .t60 }
{% include list-posts category='chip-mounters' %}

redpajama_set_name: RedPajamaGithub


text:
css

main.css

img

program-or-be-programmed.jpg

the-book-of-trees.jpg

index.html

js

app.js

controllers

MainController.js

shared

angular-mocks.js

angular-route.min.js

angular.min.js
html, body {
 margin: 0;
 padding: 0;
 font-family: 'Roboto', sans-serif;
 width:100%;
}

.header {
 padding: 15px;
}

.header img {
   display: inline-block;
}

.header h1 {
   display: inline-block;
}

.main {
 background-color: #f2f2f2 ;
 padding: 40px 0;
}

.main h1 {
 color: #F65A5B ;
 font-size: 64px;
 margin: 0 0 80px 0;
 padding: 20px 0;
   line-height: 60px;
   width: 50%;
}

.main h2 {
 background-color: #DDDDDD ;
 color: #999999 ;
 font-size: 20px;
 margin: 0 0 40px 0;
 padding: 20px 0;
}

.thumbnail {
 border: 0px;
 position: relative;
 padding: 50px;
   border-radius: 0;
   margin-bottom:50px;
}

.thumbnail img {
   margin-top: 10px;
 margin-bottom: 30px;
 max-width: 100%;
}

.title,
.date {
 color: #444;
 margin: 0;
 font-size: 18px;
   font-weight: 800;
}

.date {
   color: #a3a3a3 ;
   font-size: 14px;
   font-weight: 200;
}

.price {
 background-color: #39D1B4 ;
 color: #fff;
 font-size: 18px;
   border-radius: 50%;
   box-shadow: 0 2px 5px rgba(0,0,0,0.2);
   font-weight: 200;
   height: 80px;
   line-height: 80px;
   text-align: center;
   width: 80px;
 position: absolute;
 top: -40px;
 right: 20px;
}

.rating {
 text-align: right;
 -webkit-user-select: none;
    -moz-user-select: none;
     -ms-user-select: none;
 margin: 30px 0 -30px 20px;
}

.likes,
.dislikes {
   background: #F65A5B ;
 color: #fff;
 cursor: pointer;
 display: inline-block;
 font-size: 15px;
   line-height: 40px;
   min-width: 40px;
   height: 40px;
   border-radius: 50%;
 margin: 0 -30px 0 40px;
   text-align: center;
   font-weight: 200;
   box-shadow: 0 2px 5px rgba(0,0,0,0.2);
   transition: background 500ms;
}

.likes:hover,
.dislikes:hover {
 color: #F65A5B ;
   background: rgba(246, 90, 91, 0.25);
   transition: background 500ms;
}

.footer {
 text-align: center;
 margin: 80px 0 110px;
}

.footer h2 {
 font-size: 24px;
 margin-bottom: 25px;
}

.footer img {
   margin: 0 10px;
}
Open
index.html
MainController.js

1
<!doctype html>
2

3

4
      <link href="https://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css" rel="stylesheet" />
5
    <link href='https://fonts.googleapis.com/css?family=Roboto:500,300,700,400' rel='stylesheet' type='text/css'>
6
    <link href="css/main.css" rel="stylesheet" />
7

8

9

10

11

12

13

Book End

14

15

16

17

18

19

20

{{ title }}

21

{{ promo }}

22

23

24

25

{{ product.name }}

26

{{ product.price | currency }}

27

{{ product.pubdate | date }}

28

29

 {{ product.likes }}

30

31

32

33

34

35

36

37

38

Available for iPhone and Android.

39

40

41

42

43

44

45

46

47

48

49

50

51

Run

https://localhost:8000/

So far we've made a static AngularJS app by adding properties in the controller and displaying them in the view. AngularJS is a framework for building dynamic web apps, so let's start to make this app interactive.
1.
In the controller in the $scope.products array, add a new property named likes to each element. Set all likes properties to 0.
2.
In the view under
, type in a rating element:

+

Inside
, display a product's likes using an expression.
3.
Back in the controller after $scope.products, attach a new property to $scope named plusOne. Set it equal to function. Type in the contents exactly as you see here:

function(index) {
  $scope.products[index].likes += 1;
};

4.
In the view modify
 to look like this:

View the AngularJS app in the browser. Click on the +0 in each product tile.
Report a Bug
If you see a bug, please report it using the form below.

I don't understand this error message

There's a problem with the interface

There's something wrong with the instructions

Other

Please describe your problem.
SUBMIT
Report a Bug
Learn
Instructions
Learn AngularJS - Your First App
1
Hello AngularJS I
2
Hello AngularJS II
3
Workflow
4
Filters I
5
Filters II
6
ng-repeat I
7
ng-repeat II
8
Directives
9
ng-click I
10
ng-click II
11
Generalizations
View All Exercises
Back
30%
Next
Get Help

ng-click I
Saving workspace


text: A simple emacs lisp package to load local conf automatically


text:
<?php

/**
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/blob/master/pubsub/api/README.md
 */
namespace Google\Cloud\Samples\PubSub;

# [START pubsub_get_schema]
use Google\Cloud\PubSub\PubSubClient;

/**
 * Get a schema.
 *
 * @param string $projectId
 * @param string $schemaId
 */
function get_schema($projectId, $schemaId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);

    $schema = $pubsub->schema($schemaId);
    $schema->info();

    printf('Schema %s retrieved', $schema->name());
}
# [END pubsub_get_schema]
require_once __DIR__ . '/../../../testing/sample_helpers.php';
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>mlens.visualization package — mlens 0.2.0 documentation</title>

    <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato" type="text/css" />

    <link rel="stylesheet" href="../_static/css/pygments.css" type="text/css" />

    <link rel="stylesheet" href="../_static/css/mlens-theme.css" type="text/css" />

    <link rel="stylesheet" href="../_static/css/sphinx-glr.css" type="text/css" />

        <link rel="index" title="Index"
              href="../genindex.html"/>
        <link rel="search" title="Search" href="../search.html"/>
    <link rel="top" title="mlens 0.2.0 documentation" href="../index.html"/>

                0.2.0

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Installation

Install

Bleeding edge

Dependencies

Test build

High-level API

Getting started

Preliminaries

Ensemble guide

Building an ensemble

Multi-layer ensembles

Model selection guide

The scoring function

A simple evaluation

Preprocessing

Model Selection across preprocessing pipelines

Visualization guide

Advanced features tutorial

Propagating input features

Probabilistic ensemble learning

Advanced Subsemble techniques

General multi-layer ensemble learning

Passing file paths as data input

Ensemble model selection

Ready-made ensemble classes

Super Learner

References

Notes

Subsemble

References

Notes

Blend Ensemble

Sequential Ensemble

Mechanics

Learner Mechanics

The Learner API

Basics

Partitioning

Preprocessing

Parallel estimation

Layer Mechanics

The Layer API

Basics

Parallel Mechanics

Sequential Mechanics

Details

Memory consumption

Memory mapping

ML-Ensemble memory profiling

Memory performance benchmark

Gotcha's

Performance benchmarks

MNIST

Benchmark

The Friedman Regression Problem 1

Benchmark

References

Scale benchmarks

Single process vs multi-process

Ensemble comparison

Hacking ML-Ensemble

Troubleshooting

Bad interaction with third-party packages

Array copying during fitting

Documentation

API

Front-end API

Ensemble estimators

Model Selection

Preprocessing

Visualization

Low-level API

Parallel estimation API

Ensemble Base classes

Indexers

Global configurations

Additional Information

License

Change log

Package index

mlens

mlens package

Subpackages

mlens.ensemble package

mlens.estimators package

mlens.index package

mlens.metrics package

mlens.model_selection package

mlens.parallel package

mlens.preprocessing package

mlens.testing package

mlens.utils package

mlens.visualization package

Submodules

mlens.config module

Module contents

          mlens

Docs »

mlens.visualization package

             View page source

mlens.visualization package¶

Submodules¶

mlens.visualization.correlations module¶

ML-ENSEMBLE

<col class="field-name" />
<col class="field-body" />

author:	Sebastian Flennerhag

copyright:	2017

licence:	MIT

Correlation plots.

mlens.visualization.correlations.clustered_corrmap(corr, cls, label_attr_name='labels_', figsize=(10, 8), annotate=False, inflate=False, linewidths=0.5, cbar_kws='default', show=True, title_fontsize=14, title_name='Clustered correlation heatmap', ax=None, **kwargs)[source]¶

Function for plotting a clustered correlation heatmap.

<col class="field-name" />
<col class="field-body" />

Parameters:

corr (array-like of shape = [n_features, n_features]) – Input correlation matrix. Pass a pandas DataFrame for axis labels.

cls (instance) – cluster estimator with a fit method and cluster labels stored as an
attribute as specified by the label_attr_name parameter.

label_attr_name (str) – name of attribute that contains cluster labels.

figsize (tuple (default = (10, 8))) – Size of figure.

annotate (bool (default = True)) – Whether to print the correlation coefficients.

inflate (bool (default = True)) – Whether to inflate correlation coefficients to a 0-100 scale.
Avoids decimal points in the figure, which often appears very cluttered
otherwise.

linewidths (float (default = .5)) – with of line separating each coordinate square.

cbar_kws (dict, str (default = 'default')) – Optional arguments to color bar.

title_name (str) – Figure title.

title_fontsize (int) – size of title.

show (bool (default = True)) – whether to print figure using matplotlib.pyplot.show.

ax (object, optional) – axis to attach plot to.

**kwargs (optional) – Other optional arguments to sns heatmap.

See also

mlens.visualization.corrmat

mlens.visualization.correlations.corr_X_y(X, y, top=5, figsize=(10, 8), fontsize=12, hspace=None, no_ticks=True, label_rotation=0, show=True)[source]¶

Function for plotting input feature correlations with output.

Output figure shows all correlations as well as top pos and neg.

<col class="field-name" />
<col class="field-body" />

Parameters:

X (pandas DataFrame of shape = [n_samples, n_features]) – Input data.

y (pandas Series of shape = [n_samples,]) – training labels.

top (int) – number of features to show in top pos and neg graphs.

figsize (tuple (default = (10, 8))) – Size of figure.

hspace (float, optional) – whitespace between top row of figures and bottom figure.

fontsize (int) – font size of subplot titles.

no_ticks (bool (default = False)) – whether to remove ticklabels from full correlation plot.

label_rotation (float (default = 0)) – rotation of labels

show (bool (default = True)) – whether to print figure using matplotlib.pyplot.show.

Returns:
ax – axis object.

Return type:
object

mlens.visualization.correlations.corrmat(corr, figsize=(11, 9), annotate=True, inflate=True, linewidths=0.5, cbar_kws='default', show=True, ax=None, title='Correlation Matrix', title_font_size=14, **kwargs)[source]¶

Function for generating color-coded correlation triangle.

<col class="field-name" />
<col class="field-body" />

Parameters:

corr (array-like of shape = [n_features, n_features]) – Input correlation matrix. Pass a pandas DataFrame for axis labels.

figsize (tuple (default = (11, 9))) – Size of printed figure.

annotate (bool (default = True)) – Whether to print the correlation coefficients.

inflate (bool (default = True)) – Whether to inflate correlation coefficients to a 0-100 scale.
Avoids decimal points in the figure, which often appears very cluttered
otherwise.

linewidths (float) – with of line separating each coordinate square.

cbar_kws (dict, str (default = 'default')) – Optional arguments to color bar. The default options, 'default',
passes the shrink parameter to fit colorbar standard figure frame.

show (bool (default = True)) – whether to print figure using matplotlib.pyplot.show.

title (str) – figure title if shown.

title_font_size (int) – title font size.

ax (object, optional) – axis to attach plot to.

**kwargs (optional) – Other optional arguments to sns heatmap.

Returns:
ax – axis object.

Return type:
object

See also

mlens.visualization.clustered_corrmap

mlens.visualization.var_analysis module¶

ML-ENSEMBLE

<col class="field-name" />
<col class="field-body" />

author:	Sebastian Flennerhag

copyright:	2017

licence:	MIT

Explained variance plots.

mlens.visualization.var_analysis.exp_var_plot(X, estimator, figsize=(10, 8), buffer=0.01, set_labels=True, title='Explained variance ratio', title_font_size=14, show=True, ax=None, **kwargs)[source]¶

Function to plot the explained variance using PCA.

<col class="field-name" />
<col class="field-body" />

Parameters:

X (array-like of shape = [n_samples, n_features]) – input matrix to be used for prediction.

estimator (class) – PCA estimator, not initiated, assumes a Scikit-learn API.

figsize (tuple (default = (10, 8))) – Size of figure.

buffer (float (default = 0.01)) – For creating a buffer around the edges of the graph. The buffer
added is calculated as num_components * buffer,
where num_components determine the length of the x-axis.

set_labels (bool) – whether to set axis labels.

title (str) – figure title if shown.

title_font_size (int) – title font size.

show (bool (default = True)) – whether to print figure using matplotlib.pyplot.show.

ax (object, optional) – axis to attach plot to.

**kwargs (optional) – optional arguments passed to the matplotlib.pyplot.step
function.

Returns:
ax – if ax was specified, returns ax with plot attached.

Return type:
optional

mlens.visualization.var_analysis.pca_comp_plot(X, y=None, figsize=(10, 8), title='Principal Components Comparison', title_font_size=14, show=True, **kwargs)[source]¶

Function for comparing PCA analysis.

Function compares across 2 and 3 dimensions and
linear and rbf kernels.

<col class="field-name" />
<col class="field-body" />

Parameters:

X (array-like of shape = [n_samples, n_features]) – input matrix to be used for prediction.

y (array-like of shape = [n_samples, ] or None (default = None)) – training labels to be used for color highlighting.

figsize (tuple (default = (10, 8))) – Size of figure.

title (str) – figure title if shown.

title_font_size (int) – title font size.

show (bool (default = True)) – whether to print figure matplotlib.pyplot.show.

**kwargs (optional) – optional arguments to pass to mlens.visualization.pca_plot.

Returns:
axis object.

Return type:
ax

See also

mlens.visualization.pca_plot

mlens.visualization.var_analysis.pca_plot(X, estimator, y=None, cmap=None, figsize=(10, 8), title='Principal Components Analysis', title_font_size=14, show=True, ax=None, **kwargs)[source]¶

Function to plot a PCA analysis of 1, 2, or 3 dims.

<col class="field-name" />
<col class="field-body" />

Parameters:

X (array-like of shape = [n_samples, n_features]) – matrix to perform PCA analysis on.

estimator (instance) – PCA estimator. Assumes a Scikit-learn API.

y (array-like of shape = [n_samples, ] or None (default = None)) – training labels to be used for color highlighting.

cmap (object, optional) – cmap object to pass to matplotlib.pyplot.scatter.

figsize (tuple (default = (10, 8))) – Size of figure.

title (str) – figure title if shown.

title_font_size (int) – title font size.

show (bool (default = True)) – whether to print figure matplotlib.pyplot.show.

ax (object, optional) – axis to attach plot to.

**kwargs (optional) – arguments to pass to matplotlib.pyplot.scatter.

Returns:
ax – if ax was specified, returns ax with plot attached.

Return type:
optional

Module contents¶

ML-ENSEMBLE

<col class="field-name" />
<col class="field-body" />

author:	Sebastian Flennerhag

copyright:	2017

license:	MIT

mlens.visualization.corrmat(corr, figsize=(11, 9), annotate=True, inflate=True, linewidths=0.5, cbar_kws='default', show=True, ax=None, title='Correlation Matrix', title_font_size=14, **kwargs)[source]¶

Function for generating color-coded correlation triangle.

<col class="field-name" />
<col class="field-body" />

Parameters:

corr (array-like of shape = [n_features, n_features]) – Input correlation matrix. Pass a pandas DataFrame for axis labels.

figsize (tuple (default = (11, 9))) – Size of printed figure.

annotate (bool (default = True)) – Whether to print the correlation coefficients.

inflate (bool (default = True)) – Whether to inflate correlation coefficients to a 0-100 scale.
Avoids decimal points in the figure, which often appears very cluttered
otherwise.

linewidths (float) – with of line separating each coordinate square.

cbar_kws (dict, str (default = 'default')) – Optional arguments to color bar. The default options, 'default',
passes the shrink parameter to fit colorbar standard figure frame.

show (bool (default = True)) – whether to print figure using matplotlib.pyplot.show.

title (str) – figure title if shown.

title_font_size (int) – title font size.

ax (object, optional) – axis to attach plot to.

**kwargs (optional) – Other optional arguments to sns heatmap.

Returns:
ax – axis object.

Return type:
object

See also

mlens.visualization.clustered_corrmap

mlens.visualization.clustered_corrmap(corr, cls, label_attr_name='labels_', figsize=(10, 8), annotate=False, inflate=False, linewidths=0.5, cbar_kws='default', show=True, title_fontsize=14, title_name='Clustered correlation heatmap', ax=None, **kwargs)[source]¶

Function for plotting a clustered correlation heatmap.

<col class="field-name" />
<col class="field-body" />

Parameters:

corr (array-like of shape = [n_features, n_features]) – Input correlation matrix. Pass a pandas DataFrame for axis labels.

cls (instance) – cluster estimator with a fit method and cluster labels stored as an
attribute as specified by the label_attr_name parameter.

label_attr_name (str) – name of attribute that contains cluster labels.

figsize (tuple (default = (10, 8))) – Size of figure.

annotate (bool (default = True)) – Whether to print the correlation coefficients.

inflate (bool (default = True)) – Whether to inflate correlation coefficients to a 0-100 scale.
Avoids decimal points in the figure, which often appears very cluttered
otherwise.

linewidths (float (default = .5)) – with of line separating each coordinate square.

cbar_kws (dict, str (default = 'default')) – Optional arguments to color bar.

title_name (str) – Figure title.

title_fontsize (int) – size of title.

show (bool (default = True)) – whether to print figure using matplotlib.pyplot.show.

ax (object, optional) – axis to attach plot to.

**kwargs (optional) – Other optional arguments to sns heatmap.

See also

mlens.visualization.corrmat

mlens.visualization.corr_X_y(X, y, top=5, figsize=(10, 8), fontsize=12, hspace=None, no_ticks=True, label_rotation=0, show=True)[source]¶

Function for plotting input feature correlations with output.

Output figure shows all correlations as well as top pos and neg.

<col class="field-name" />
<col class="field-body" />

Parameters:

X (pandas DataFrame of shape = [n_samples, n_features]) – Input data.

y (pandas Series of shape = [n_samples,]) – training labels.

top (int) – number of features to show in top pos and neg graphs.

figsize (tuple (default = (10, 8))) – Size of figure.

hspace (float, optional) – whitespace between top row of figures and bottom figure.

fontsize (int) – font size of subplot titles.

no_ticks (bool (default = False)) – whether to remove ticklabels from full correlation plot.

label_rotation (float (default = 0)) – rotation of labels

show (bool (default = True)) – whether to print figure using matplotlib.pyplot.show.

Returns:
ax – axis object.

Return type:
object

mlens.visualization.pca_comp_plot(X, y=None, figsize=(10, 8), title='Principal Components Comparison', title_font_size=14, show=True, **kwargs)[source]¶

Function for comparing PCA analysis.

Function compares across 2 and 3 dimensions and
linear and rbf kernels.

<col class="field-name" />
<col class="field-body" />

Parameters:

X (array-like of shape = [n_samples, n_features]) – input matrix to be used for prediction.

y (array-like of shape = [n_samples, ] or None (default = None)) – training labels to be used for color highlighting.

figsize (tuple (default = (10, 8))) – Size of figure.

title (str) – figure title if shown.

title_font_size (int) – title font size.

show (bool (default = True)) – whether to print figure matplotlib.pyplot.show.

**kwargs (optional) – optional arguments to pass to mlens.visualization.pca_plot.

Returns:
axis object.

Return type:
ax

See also

mlens.visualization.pca_plot

mlens.visualization.pca_plot(X, estimator, y=None, cmap=None, figsize=(10, 8), title='Principal Components Analysis', title_font_size=14, show=True, ax=None, **kwargs)[source]¶

Function to plot a PCA analysis of 1, 2, or 3 dims.

<col class="field-name" />
<col class="field-body" />

Parameters:

X (array-like of shape = [n_samples, n_features]) – matrix to perform PCA analysis on.

estimator (instance) – PCA estimator. Assumes a Scikit-learn API.

y (array-like of shape = [n_samples, ] or None (default = None)) – training labels to be used for color highlighting.

cmap (object, optional) – cmap object to pass to matplotlib.pyplot.scatter.

figsize (tuple (default = (10, 8))) – Size of figure.

title (str) – figure title if shown.

title_font_size (int) – title font size.

show (bool (default = True)) – whether to print figure matplotlib.pyplot.show.

ax (object, optional) – axis to attach plot to.

**kwargs (optional) – arguments to pass to matplotlib.pyplot.scatter.

Returns:
ax – if ax was specified, returns ax with plot attached.

Return type:
optional

mlens.visualization.exp_var_plot(X, estimator, figsize=(10, 8), buffer=0.01, set_labels=True, title='Explained variance ratio', title_font_size=14, show=True, ax=None, **kwargs)[source]¶

Function to plot the explained variance using PCA.

<col class="field-name" />
<col class="field-body" />

Parameters:

X (array-like of shape = [n_samples, n_features]) – input matrix to be used for prediction.

estimator (class) – PCA estimator, not initiated, assumes a Scikit-learn API.

figsize (tuple (default = (10, 8))) – Size of figure.

buffer (float (default = 0.01)) – For creating a buffer around the edges of the graph. The buffer
added is calculated as num_components * buffer,
where num_components determine the length of the x-axis.

set_labels (bool) – whether to set axis labels.

title (str) – figure title if shown.

title_font_size (int) – title font size.

show (bool (default = True)) – whether to print figure using matplotlib.pyplot.show.

ax (object, optional) – axis to attach plot to.

**kwargs (optional) – optional arguments passed to the matplotlib.pyplot.step
function.

Returns:
ax – if ax was specified, returns ax with plot attached.

Return type:
optional

        © Copyright 2017, Sebastian Flennerhag.

  Built with Sphinx using a theme provided by Read the Docs.


text:
require 'spec_helper'

describe ChunkyPNG::Canvas::Resampling do

  subject { reference_canvas('clock') }

  describe '#resample_nearest_neighbor' do

    it "should downscale from 2x2 to 1x1 correctly" do
      canvas = ChunkyPNG::Canvas.new(2, 2, [1, 2, 3, 4])
      canvas.resample_nearest_neighbor(1, 1).should == ChunkyPNG::Canvas.new(1, 1, [4])
    end

    it "should upscale from 2x2 to 4x4 correctly" do
      canvas = ChunkyPNG::Canvas.new(2, 2, [1, 2, 3, 4])
      canvas.resample_nearest_neighbor(4, 4).should == ChunkyPNG::Canvas.new(4, 4, [1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4])
    end

    it "should upscale both axis of the image" do
      subject.resample_nearest_neighbor(45, 45).should == reference_canvas('clock_nn_xup_yup')
    end

    it "should downscale both axis of the image" do
      subject.resample_nearest_neighbor(12, 12).should == reference_canvas('clock_nn_xdown_ydown')
    end

    it "should downscale the x-axis and upscale the y-axis of the image" do
      subject.resample_nearest_neighbor(20, 50).should == reference_canvas('clock_nn_xdown_yup')
    end

    it "should not return itself" do
      subject.resample_nearest_neighbor(1, 1).should_not equal(subject)
    end

    it "should not change the original image's dimensions" do
      lambda { subject.resample_nearest_neighbor(1, 1) }.should_not change(subject, :dimension)
    end
  end

  describe '#resample_nearest_neighbor!' do
    it "should upscale both axis of the image" do
      subject.resample_nearest_neighbor!(45, 45)
      subject.should == reference_canvas('clock_nn_xup_yup')
    end

    it "should downscale both axis of the image" do
      subject.resample_nearest_neighbor!(12, 12)
      subject.should == reference_canvas('clock_nn_xdown_ydown')
    end

    it "should downscale the x-axis and upscale the y-axis of the image" do
      subject.resample_nearest_neighbor!(20, 50)
      subject.should == reference_canvas('clock_nn_xdown_yup')
    end

    it "should return itself" do
      subject.resample_nearest_neighbor!(1, 1).should equal(subject)
    end

    it "should change the original image's dimensions" do
      lambda { subject.resample_nearest_neighbor!(1, 1) }.should change(subject, :dimension).to(ChunkyPNG::Dimension('1x1'))
    end
  end

  describe "#resample_bilinear" do
    it "should downscale from 2x2 to 1x1 correctly" do
      canvas = ChunkyPNG::Canvas.new(2, 2, [1, 2, 3, 4])
      canvas.resample_bilinear(1, 1).should == ChunkyPNG::Canvas.new(1, 1, [2])
    end

    it "should upscale from 2x2 to 4x4 correctly" do
      canvas = ChunkyPNG::Canvas.new(2, 2, [1, 2, 3, 4])
      canvas.resample_bilinear(4, 4).should == ChunkyPNG::Canvas.new(4, 4, [1, 2, 1, 2, 2, 2, 2, 2, 2, 3, 3, 4, 3, 3, 4, 4])
    end

    it "should upscale both axis of the image" do
      subject.resample_bilinear(45, 45).should == reference_canvas('clock_bl_xup_yup')
    end

    it "should downscale both axis of the image" do
      subject.resample_bilinear(12, 12).should == reference_canvas('clock_bl_xdown_ydown')
    end

    it "should downscale the x-axis and upscale the y-axis of the image" do
      subject.resample_bilinear(20, 50).should == reference_canvas('clock_bl_xdown_yup')
    end

    it "should not return itself" do
      subject.resample_bilinear(1, 1).should_not equal(subject)
    end

    it "should not change the original image's dimensions" do
      lambda { subject.resample_bilinear(1, 1) }.should_not change(subject, :dimension)
    end
  end

  describe '#resample_bilinear!' do
    it "should upscale both axis of the image" do
      subject.resample_bilinear!(45, 45)
      subject.should == reference_canvas('clock_bl_xup_yup')
    end

    it "should downscale both axis of the image" do
      subject.resample_bilinear!(12, 12)
      subject.should == reference_canvas('clock_bl_xdown_ydown')
    end

    it "should downscale the x-axis and upscale the y-axis of the image" do
      subject.resample_bilinear!(20, 50)
      subject.should == reference_canvas('clock_bl_xdown_yup')
    end

    it "should return itself" do
      subject.resample_bilinear!(1, 1).should equal(subject)
    end

    it "should change the original image's dimensions" do
      lambda { subject.resample_bilinear!(1, 1) }.should change(subject, :dimension).to(ChunkyPNG::Dimension('1x1'))
    end
  end
end


text:
const fetch = require('node-fetch')
const handleErrors = require('../handle-errors')
const {USER_AGENT, CORE_API} = require('../constants')

/**
 * **Undocumented:** Gets a logged-in user's capes for a given profile.
 *
 * **I have no idea what this endpoint returns!** I just saw the official website try to use it.
 *
 * @param {Object} session - object from authentication
 * @param {string} session.accessToken - valid access token for the user's account
 * @param {string} profileId - game profile UUID to look for capes in
 * @returns {Promise<Array>} resolves with an array of something
 */
function getUserCapeData ({accessToken}, profileId) {
  return fetch(`${CORE_API}/user/profile/${profileId}/cape`, {
    headers: {
      'user-agent': USER_AGENT,
      'authorization': `Bearer ${accessToken}`,
      'accept': 'application/json'
    }
  })
    .then(handleErrors)
    .then(res => res.json())
}

module.exports = getUserCapeData


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.elasticsan.generated;

import com.azure.resourcemanager.elasticsan.models.SourceCreationData;
import com.azure.resourcemanager.elasticsan.models.VolumeCreateOption;
import java.util.HashMap;
import java.util.Map;

/** Samples for Volumes Create. */
public final class VolumesCreateSamples {
    /*
     * x-ms-original-file: specification/elasticsan/resource-manager/Microsoft.ElasticSan/preview/2021-11-20-preview/examples/Volumes_Create_MaximumSet_Gen.json
     */
    /**
     * Sample code: Volumes_Create_MaximumSet_Gen.
     *
     * @param manager Entry point to ElasticSanManager.
     */
    public static void volumesCreateMaximumSetGen(com.azure.resourcemanager.elasticsan.ElasticSanManager manager) {
        manager
            .volumes()
            .define("9132y")
            .withExistingVolumegroup("rgelasticsan", "ti7q-k952-1qB3J_5", "u_5I_1j4t3")
            .withTags(mapOf("key7423", "aaaa"))
            .withCreationData(
                new SourceCreationData().withCreateSource(VolumeCreateOption.NONE).withSourceUri("aaaaaa"))
            .withSizeGiB(22L)
            .create();
    }

    /*
     * x-ms-original-file: specification/elasticsan/resource-manager/Microsoft.ElasticSan/preview/2021-11-20-preview/examples/Volumes_Create_MinimumSet_Gen.json
     */
    /**
     * Sample code: Volumes_Create_MinimumSet_Gen.
     *
     * @param manager Entry point to ElasticSanManager.
     */
    public static void volumesCreateMinimumSetGen(com.azure.resourcemanager.elasticsan.ElasticSanManager manager) {
        manager
            .volumes()
            .define("9132y")
            .withExistingVolumegroup("rgelasticsan", "ti7q-k952-1qB3J_5", "u_5I_1j4t3")
            .create();
    }

    @SuppressWarnings("unchecked")
    private static <T> Map<String, T> mapOf(Object... inputs) {
        Map<String, T> map = new HashMap<>();
        for (int i = 0; i < inputs.length; i += 2) {
            String key = (String) inputs[i];
            T value = (T) inputs[i + 1];
            map.put(key, value);
        }
        return map;
    }
}


text:
package drum

import (
	"bufio"
	"bytes"
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

type header struct {
	ChunkID         [6]byte
	Padding1        [7]byte
	Unknown1        [1]byte
	HardwareVersion [31]byte
	Unknown2        [2]byte
	TempoDecimal    byte
	Tempo           byte
	Unknown3        byte
}

// Pattern is the high level representation of the
// drum pattern contained in a .splice file.
type Pattern struct {
	Tempo           int
	TempoDecimal    int
	HardwareVersion string
	Tracks
}

// NewPattern returns an empty pattern.
func NewPattern() *Pattern {
	p := new(Pattern)
	p.Tracks = make([]Track, 0)
	return p
}

func (p Pattern) String() string {
	bpm := fmt.Sprint(p.Tempo)
	if p.TempoDecimal != 0 {
		bpm = fmt.Sprintf("%v.%v", p.Tempo, p.TempoDecimal)
	}
	s := fmt.Sprintf("Saved with HW Version: %s\nTempo: %v\n%v", p.HardwareVersion, bpm, p.Tracks)
	return s
}

func (p Pattern) header() header {
	h := header{}
	h.ChunkID = [6]byte{'S', 'P', 'L', 'I', 'C', 'E'}
	for i, r := range p.HardwareVersion {
		h.HardwareVersion[i] = byte(r)
	}
	if p.HardwareVersion == "0.808-alpha" {
		if p.TempoDecimal != 0 {
			h.TempoDecimal = byte(p.TempoDecimal + 200)
		}
		h.Tempo = byte(p.Tempo * 2)
	}
	return h
}

// NewPatternFromBackup creates a pattern structure by parsing
// a backup file's human-readible text data.
func NewPatternFromBackup(s string) (*Pattern, error) {
	scanner := bufio.NewScanner(strings.NewReader(s))
	p := NewPattern()
	for lineNum := 0; scanner.Scan(); lineNum++ {
		line := scanner.Text()
		switch lineNum {
		case 0:
			p.HardwareVersion = parseHardwareVersion(line)
		case 1:
			var err error
			p.Tempo, p.TempoDecimal, err = parseTempo(line)
			if err != nil {
				return p, err
			}
		default:
			t, err := parseTrack(line)
			if err != nil {
				return p, err
			}
			p.Tracks = append(p.Tracks, t)
		}
	}
	return p, nil
}

func parseHardwareVersion(line string) string {
	s := strings.TrimLeft(line, "Saved with HW Version: ")
	return s
}

func parseTempo(line string) (tempo, tempoDecimal int, err error) {
	s := strings.TrimLeft(line, "Tempo: ")
	match := tempoRe.FindStringSubmatch(s)
	tempo, err = strconv.Atoi(match[1])
	if err != nil {
		return 0, 0, err
	}
	tempoDecimal, err = strconv.Atoi(match[2])
	if err != nil {
		return tempo, 0, nil
	}
	return tempo, tempoDecimal, nil
}

var idRe = regexp.MustCompile(`\((\d+)\) `)
var tempoRe = regexp.MustCompile("(\\d+).?(\\d+)?")
var beatRe = regexp.MustCompile(`([x-]{4})\|`)

func parseTrack(line string) (Track, error) {
	id, line, err := parseTrackID(line)
	if err != nil {
		return Track{}, err
	}
	name, line := parseTrackName(line)
	bars, line, err := parseBar(line, 4)
	if err != nil {
		return Track{}, err
	}
	return Track{Name: name, ID: id, Sequence: bars}, nil
}

func parseTrackID(line string) (id byte, leftTrimmedLine string, err error) {
	idMatch := idRe.FindStringSubmatch(line)
	if len(idMatch) != 2 {
		return 0, "", fmt.Errorf("No track ID parsed from line: '%v'", line)
	}
	n, err := strconv.Atoi(idMatch[1])
	if err != nil {
		return id, leftTrimmedLine, err
	}
	leftTrimmedLine = strings.TrimLeft(line, idMatch[0])
	return byte(n), leftTrimmedLine, nil
}

var nameRe = regexp.MustCompile(`([\w-]+)\s+\|`)

func parseTrackName(line string) (name, leftTrimmedLine string) {
	s := strings.SplitN(line, "|", 2)
	name = strings.TrimRight(s[0], " \t")
	return name, s[1]
}

func parseBar(line string, numMeasures int) (bar []byte, leftTrimmedLine string, err error) {
	measureMatches := beatRe.FindAllStringSubmatch(line, numMeasures)
	for i := 0; i < numMeasures; i++ {
		measure := measureMatches[i][1]
		beats, err := parseBeats(measure)
		if err != nil {
			return beats, leftTrimmedLine, err
		}
		bar = append(bar, beats...)
		line = strings.TrimLeft(line, measureMatches[i][0])
	}
	return bar, line, nil
}

func parseBeats(measure string) ([]byte, error) {
	var beats []byte
	for _, beat := range measure {
		switch beat {
		case onBeat:
			beats = append(beats, 1)
		case offBeat:
			beats = append(beats, 0)
		default:
			return beats, fmt.Errorf("Unknown beat character '%v' encountered parsing measure '%v'", beat, measure)
		}
	}
	return beats, nil
}

// A Track represents a named, identified drum sequence.
type Track struct {
	ID       byte
	Name     string
	Sequence []byte
}

// NewTrack returns an empty, initialized track.
func NewTrack() *Track {
	t := new(Track)
	t.Sequence = make([]byte, 16)
	return t
}

func (t Track) encode() []byte {
	b := []byte{t.ID, 0, 0, 0}
	b = append(b, byte(len(t.Name)))
	b = append(b, []byte(t.Name)...)
	b = append(b, t.Sequence...)
	return b
}

const (
	separator rune = '|'
	onBeat    rune = 'x'
	offBeat   rune = '-'
	errorRune rune = '?'
)

func (t Track) String() string {
	var b bytes.Buffer
	b.WriteString(fmt.Sprintf("(%d) %s\t", t.ID, t.Name))
	for i := 0; i < len(t.Sequence); i++ {
		if i%4 == 0 {
			b.WriteString(string(separator))
		}
		switch t.Sequence[i] {
		case 1:
			b.WriteString(string(onBeat))
		case 0:
			b.WriteString(string(offBeat))
		default:
			b.WriteString(string(errorRune))
		}
	}
	b.WriteString(string(separator))
	return b.String()
}


text:
#region Copyright
// Copyright 2017 Gigya Inc.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Gigya.Common.Contracts;
using Gigya.Common.Contracts.Exceptions;
using Gigya.Common.Contracts.HttpService;
using Gigya.Microdot.Configuration.Objects;
using Gigya.Microdot.Hosting.Events;
using Gigya.Microdot.Hosting.HttpService.Endpoints;
using Gigya.Microdot.Hosting.Service;
using Gigya.Microdot.Interfaces.Logging;
using Gigya.Microdot.Interfaces.SystemWrappers;
using Gigya.Microdot.SharedLogic;
using Gigya.Microdot.SharedLogic.Configurations;
using Gigya.Microdot.SharedLogic.Events;
using Gigya.Microdot.SharedLogic.Exceptions;
using Gigya.Microdot.SharedLogic.HttpService;
using Gigya.Microdot.SharedLogic.Measurement;
using Gigya.Microdot.SharedLogic.Security;
using Gigya.Microdot.SharedLogic.Utils;
using Gigya.ServiceContract.Exceptions;
using Metrics;
using Newtonsoft.Json;
using Timer = Metrics.Timer;

// ReSharper disable ConsiderUsingConfigureAwait

namespace Gigya.Microdot.Hosting.HttpService
{
    public interface IRequestListener : IDisposable
    {
        Task Listen();
        void Stop();
    }

    public sealed class HttpServiceListener : IRequestListener
    {
        private readonly IServerRequestPublisher _serverRequestPublisher;

        private Task listeningTask;

        private static JsonSerializerSettings JsonSettings { get; } = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            NullValueHandling = NullValueHandling.Ignore,
            Formatting = Formatting.Indented,
            DateParseHandling = DateParseHandling.None
        };

        private static JsonSerializerSettings JsonSettingsWeak { get; } = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.None,
            NullValueHandling = NullValueHandling.Ignore,
            Formatting = Formatting.Indented,
            DateParseHandling = DateParseHandling.None
        };
        private byte[] ServerRootCertHash { get; }

        private IActivator Activator { get; }
        private IWorker Worker { get; }
        private IServiceEndPointDefinition ServiceEndPointDefinition { get; }
        private HttpListener Listener { get; }
        private ILog Log { get; }
        private IEnumerable<ICustomEndpoint> CustomEndpoints { get; }
        private IEnvironment Environment { get; }
        private JsonExceptionSerializer ExceptionSerializer { get; }
        private Func<LoadShedding> LoadSheddingConfig { get; }
        private CurrentApplicationInfo AppInfo { get; }

        private ServiceSchema ServiceSchema { get; }

        private readonly Timer _serializationTime;
        private readonly Timer _deserializationTime;
        private readonly Timer _roundtripTime;
        private readonly Counter _successCounter;
        private readonly Counter _failureCounter;
        private readonly Timer _activeRequestsCounter;
        private readonly Timer _metaEndpointsRoundtripTime;
        private readonly MetricsContext _endpointContext;
        private DataAnnotationsValidator _validator = new DataAnnotationsValidator();
        private TaskCompletionSource<int> _ReadyToGetTraffic = new TaskCompletionSource<int>();
        private List<string> _uriPrefixes;
        public void StartGettingTraffic()
        {
            _ReadyToGetTraffic.TrySetResult(1);
        }

        public HttpServiceListener(
            IActivator activator,
            IWorker worker,
            IServiceEndPointDefinition serviceEndPointDefinition,
            ICertificateLocator certificateLocator,
            ILog log,
            IEnumerable<ICustomEndpoint> customEndpoints,
            IEnvironment environment,
            JsonExceptionSerializer exceptionSerializer,
            ServiceSchema serviceSchema,
            Func<LoadShedding> loadSheddingConfig,
            IServerRequestPublisher serverRequestPublisher,
            CurrentApplicationInfo appInfo,
            Func<MicrodotHostingConfig> microdotHostingConfigFactory,
            IMicrodotTypePolicySerializationBinder serializationBinder)
        {
            ServiceSchema = serviceSchema;
            _serverRequestPublisher = serverRequestPublisher;

            ServiceEndPointDefinition = serviceEndPointDefinition;
            Worker = worker;
            Activator = activator;
            Log = log;
            CustomEndpoints = customEndpoints.ToArray();
            Environment = environment;
            ExceptionSerializer = exceptionSerializer;
            LoadSheddingConfig = loadSheddingConfig;
            AppInfo = appInfo;

            JsonSettings.SerializationBinder = serializationBinder;

            if (ServiceEndPointDefinition.HttpsPort != null && ServiceEndPointDefinition.ClientCertificateVerification != ClientCertificateVerificationMode.Disable)
            {
                var serviceCertificate = certificateLocator.GetCertificate("Service");
                Log.Info(_ => _($"Service certificate loaded: {serviceCertificate.FriendlyName}",
                   unencryptedTags: new
                   {
                       Thumbprint = serviceCertificate.Thumbprint.Substring(serviceCertificate.Thumbprint.Length - 5),
                   }));
                ServerRootCertHash = serviceCertificate.GetHashOfRootCertificate();
            }

            Listener = new HttpListener { IgnoreWriteExceptions = true };

            _uriPrefixes = new List<string>();

            if (ServiceEndPointDefinition.HttpsPort != null)
                _uriPrefixes.Add($"https://+:{ServiceEndPointDefinition.HttpsPort}/");
            if (ServiceEndPointDefinition.HttpPort != null)
                _uriPrefixes.Add($"http://+:{ServiceEndPointDefinition.HttpPort}/");
            if (!_uriPrefixes.Any())
                Log.Warn(_ => _("HttpServiceListener is not listening on any ports, no HTTP or HTTPS ports in ServiceEndPointDefinition"));
            else
            {
                foreach (string prefix in _uriPrefixes)
                    Listener.Prefixes.Add(prefix);
            }

            var context = Metric.Context("Service").Context(AppInfo.Name);
            _serializationTime = context.Timer("Serialization", Unit.Calls);
            _deserializationTime = context.Timer("Deserialization", Unit.Calls);
            _roundtripTime = context.Timer("Roundtrip", Unit.Calls);
            _metaEndpointsRoundtripTime = context.Timer("MetaRoundtrip", Unit.Calls);
            _successCounter = context.Counter("Success", Unit.Calls);
            _failureCounter = context.Counter("Failed", Unit.Calls);
            _activeRequestsCounter = context.Timer("ActiveRequests", Unit.Requests);
            _endpointContext = context.Context("Endpoints");
        }

        public Task Listen()
        {
            this.listeningTask = this.Start();

            this.StartGettingTraffic();

            return this.listeningTask;
        }

        public async Task Start()
        {
            try
            {
                Listener.Start();
                Log.Info(_ => _("HttpServiceListener started", unencryptedTags: new { prefixes = string.Join(",", _uriPrefixes) }));
            }
            catch (HttpListenerException ex)
            {
                if (ex.ErrorCode != 5)
                {
                    if (ServiceEndPointDefinition.HttpPort != null)
                        ex.Data["HttpPort"] = $"{ServiceEndPointDefinition.HttpPort}";
                    if (ServiceEndPointDefinition.HttpsPort != null)
                        ex.Data["HttpsPort"] = $"{ServiceEndPointDefinition.HttpsPort}";

                    ex.Data["Prefixes"] = string.Join(",", _uriPrefixes);
                    ex.Data["User"] = AppInfo.OsUser;
                    throw;
                }

                throw new Exception(
                    "One or more of the specified HTTP listen ports wasn't configured to run without administrative permissions.\n" +
                    "To configure them, run the following commands in an elevated (administrator) command prompt:\n" +
                    string.Join("\n", _uriPrefixes.Select(prefix => $"netsh http add urlacl url={prefix} user={AppInfo.OsUser}")));
            }

            StartListening();
        }

        private readonly ObjectPool<Stopwatch> _stopwatchPool = new ObjectPool<Stopwatch>(() => new Stopwatch(), 4096);

        private async Task StartListening()
        {

            await _ReadyToGetTraffic.Task;

            while (Listener.IsListening)
            {
                HttpListenerContext context;

                try
                {
                    context = await Listener.GetContextAsync();

                    Worker.FireAndForget(() => HandleRequest(context));
                }
                catch (ObjectDisposedException)
                {
                    break; // Listener has been stopped, GetContextAsync() is aborted.
                }
                catch (HttpListenerException ex)
                {
                    if (ex.ErrorCode == 995)
                        break;

                    Log.Error(_ => _("An error has occured during HttpListener.GetContextAsync(). Stopped listening to additional requests.", exception: ex));
                }
                catch (Exception ex)
                {
                    Log.Error(_ => _("An error has occured during HttpListener.GetContextAsync(). Stopped listening to additional requests.", exception: ex));
                    throw;
                }
            }
        }

        private async Task HandleRequest(HttpListenerContext context)
        {
            var sw = _stopwatchPool.Get();
            try
            {
                sw.Restart();
                RequestTimings.ClearCurrentTimings();
                using (context.Response)
                {
                    // Special endpoints should not be logged/measured/traced like regular endpoints
                    // Access is allowed without HTTPS verifications since they don't expose anything sensitive (e.g. config values are encrypted)
                    if (await TryHandleSpecialEndpoints(context)) return;

                    // Regular endpoint handling
                    using (_activeRequestsCounter.NewContext("Request"))
                    {
                        RequestTimings.GetOrCreate(); // initialize request timing context

                        string methodName = null;
                        // Initialize with empty object for protocol backwards-compatibility.

                        var requestData = new HttpServiceRequest { TracingData = new TracingData() };
                        object[] argumentsWithDefaults = null;
                        ServiceMethod serviceMethod = null;
                        ServiceCallEvent callEvent = _serverRequestPublisher.GetNewCallEvent();
                        try
                        {
                            try
                            {
                                await CheckSecureConnection(context);

                                ValidateRequest(context);

                                requestData = await ParseRequest(context);

                                //-----------------------------------------------------------------------------------------
                                // Don't move TracingContext writes main flow, IT have to be here, to avoid side changes
                                //-----------------------------------------------------------------------------------------
                                TracingContext.SetRequestID(requestData.TracingData.RequestID);
                                TracingContext.SpanStartTime = requestData.TracingData.SpanStartTime;
                                TracingContext.AbandonRequestBy = requestData.TracingData.AbandonRequestBy;
                                TracingContext.SetParentSpan(
                                    requestData.TracingData.SpanID ?? Guid.NewGuid().ToString("N"));
                                TracingContext.SetOverrides(requestData.Overrides);
                                if (requestData.TracingData.Tags != null)
                                    TracingContext.Tags = new ContextTags(requestData.TracingData.Tags);
                                TracingContext.AdditionalProperties = requestData.TracingData.AdditionalProperties;

                                callEvent.ServiceMethodSchema = context.Request.IsSecureConnection ? "HTTPS" : "HTTP";
                                SetCallEventRequestData(callEvent, requestData);

                                serviceMethod = ServiceEndPointDefinition.Resolve(requestData.Target);
                                callEvent.CalledServiceName = serviceMethod.GrainInterfaceType.Name;
                                methodName = serviceMethod.ServiceInterfaceMethod.Name;
                                var arguments = requestData.Target.IsWeaklyTyped
                                    ? GetParametersByName(serviceMethod, requestData.Arguments)
                                    : requestData.Arguments.Values.Cast<object>().ToArray();
                                argumentsWithDefaults =
                                    GetConvertedAndDefaultArguments(serviceMethod.ServiceInterfaceMethod, arguments);
                            }
                            catch (Exception e)
                            {
                                callEvent.Exception = e;
                                if (e is RequestException)
                                    throw;

                                throw new RequestException("Invalid request", e);
                            }

                            RejectRequestIfLateOrOverloaded();

                            var responseJson = await GetResponse(context, serviceMethod, requestData,
                                argumentsWithDefaults);
                            if (await TryWriteResponse(context, responseJson, serviceCallEvent: callEvent))
                            {
                                callEvent.ErrCode = 0;
                                _successCounter.Increment();
                            }
                            else _failureCounter.Increment();
                        }
                        catch (Exception e)
                        {
                            callEvent.Exception = callEvent.Exception ?? e;
                            _failureCounter.Increment();
                            Exception ex = GetRelevantException(e);
                            string json = _serializationTime.Time(() => ExceptionSerializer.Serialize(ex));
                            await TryWriteResponse(context, json, GetExceptionStatusCode(ex),
                                serviceCallEvent: callEvent);
                        }
                        finally
                        {
                            sw.Stop();
                            callEvent.ActualTotalTime = sw.Elapsed.TotalMilliseconds;

                            _roundtripTime.Record((long)(sw.Elapsed.TotalMilliseconds * 1000000),
                                TimeUnit.Nanoseconds);
                            if (methodName != null)
                                _endpointContext.Timer(methodName, Unit.Requests)
                                    .Record((long)(sw.Elapsed.TotalMilliseconds * 1000000), TimeUnit.Nanoseconds);

                            _serverRequestPublisher.TryPublish(callEvent, argumentsWithDefaults, serviceMethod);
                        }
                    }
                }
            }
            finally
            {
                _stopwatchPool.Return(sw);
            }
        }

        private static object[] GetConvertedAndDefaultArguments(MethodInfo method, object[] arguments)
        {
            var parameters = method.GetParameters();

            object[] argumentsWithDefaults = new object[parameters.Length];

            for (int i = 0; i < parameters.Length; i++)
            {
                object argument = null;
                var param = parameters[i];

                if (i < arguments.Length)
                {
                    argument = JsonHelper.ConvertWeaklyTypedValue(arguments[i], param.ParameterType);
                }
                else
                {
                    if (param.IsOptional)
                    {
                        if (param.HasDefaultValue)
                            argument = param.DefaultValue;
                        else if (param.ParameterType.IsValueType)
                            argument = System.Activator.CreateInstance(param.ParameterType);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Call to method {method.Name} is missing argument for {param.Name} and this paramater is not optional.");
                    }
                }

                argumentsWithDefaults[i] = argument;
            }

            return argumentsWithDefaults;
        }

        private void SetCallEventRequestData(ServiceCallEvent callEvent, HttpServiceRequest requestData)
        {
            callEvent.ClientMetadata = requestData.TracingData;
            callEvent.ServiceMethod = requestData.Target?.MethodName;
            callEvent.RequestId = requestData.TracingData?.RequestID;
            callEvent.SpanId = requestData.TracingData?.SpanID;
            callEvent.ParentSpanId = requestData.TracingData?.ParentSpanID;
            callEvent.ContextUnencryptedTags = requestData.TracingData?.Tags?.GetUnencryptedTags();
            callEvent.ContextTagsEncrypted = requestData.TracingData?.Tags?.GetEncryptedTags();
            callEvent.UnknownTracingData = requestData.TracingData?.AdditionalProperties;
            callEvent.SuppressCaching = requestData.Overrides?.SuppressCaching;
        }

        private async Task<bool> TryHandleSpecialEndpoints(HttpListenerContext context)
        {
            try
            {
                foreach (var customEndpoint in CustomEndpoints)
                {
                    if (await customEndpoint.TryHandle(context,
                        (data, status, type) => TryWriteResponse(context, data, status, type)))
                    {
                        if (RequestTimings.Current.Request.ElapsedMS != null)
                            _metaEndpointsRoundtripTime.Record((long)RequestTimings.Current.Request.ElapsedMS,
                                TimeUnit.Milliseconds);
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                var ex = GetRelevantException(e);
                await TryWriteResponse(context, ExceptionSerializer.Serialize(ex), GetExceptionStatusCode(ex));
                return true;
            }

            return false;
        }

        private void RejectRequestIfLateOrOverloaded()
        {
            var config = LoadSheddingConfig();
            var now = DateTimeOffset.UtcNow;

            // Too much time passed since our direct caller made the request to us; something's causing a delay. Log or reject the request, if needed.
            if (config.DropMicrodotRequestsBySpanTime != LoadShedding.Toggle.Disabled
                && TracingContext.SpanStartTime != null
                && TracingContext.SpanStartTime.Value + config.DropMicrodotRequestsOlderThanSpanTimeBy < now)
            {

                if (config.DropMicrodotRequestsBySpanTime == LoadShedding.Toggle.LogOnly)
                    Log.Warn(_ => _("Accepted Microdot request despite that too much time passed since the client sent it to us.", unencryptedTags: new
                    {
                        clientSendTime = TracingContext.SpanStartTime,
                        currentTime = now,
                        maxDelayInSecs = config.DropMicrodotRequestsOlderThanSpanTimeBy.TotalSeconds,
                        actualDelayInSecs = (now - TracingContext.SpanStartTime.Value).TotalSeconds,
                    }));

                else if (config.DropMicrodotRequestsBySpanTime == LoadShedding.Toggle.Drop)
                    throw new EnvironmentException("Dropping Microdot request since too much time passed since the client sent it to us.", unencrypted: new Tags
                    {
                        ["clientSendTime"] = TracingContext.SpanStartTime.ToString(),
                        ["currentTime"] = now.ToString(),
                        ["maxDelayInSecs"] = config.DropMicrodotRequestsOlderThanSpanTimeBy.TotalSeconds.ToString(),
                        ["actualDelayInSecs"] = (now - TracingContext.SpanStartTime.Value).TotalSeconds.ToString(),
                    });
            }

            // Too much time passed since the API gateway initially sent this request till it reached us (potentially
            // passing through other micro-services along the way). Log or reject the request, if needed.
            if (config.DropRequestsByDeathTime != LoadShedding.Toggle.Disabled
                && TracingContext.AbandonRequestBy != null
                && now > TracingContext.AbandonRequestBy.Value - config.TimeToDropBeforeDeathTime)
            {
                if (config.DropRequestsByDeathTime == LoadShedding.Toggle.LogOnly)
                    Log.Warn(_ => _("Accepted Microdot request despite exceeding the API gateway timeout.", unencryptedTags: new
                    {
                        requestDeathTime = TracingContext.AbandonRequestBy,
                        currentTime = now,
                        overTimeInSecs = (now - TracingContext.AbandonRequestBy.Value).TotalSeconds,
                    }));

                else if (config.DropRequestsByDeathTime == LoadShedding.Toggle.Drop)
                    throw new EnvironmentException("Dropping Microdot request since the API gateway timeout passed.", unencrypted: new Tags
                    {
                        ["requestDeathTime"] = TracingContext.AbandonRequestBy.ToString(),
                        ["currentTime"] = now.ToString(),
                        ["overTimeInSecs"] = (now - TracingContext.AbandonRequestBy.Value).TotalSeconds.ToString(),
                    });
            }
        }

        private static Exception GetRelevantException(Exception e)
        {
            if (e is RequestException)
                return e;

            var ex = GetAllExceptions(e).FirstOrDefault(x => (x is TargetInvocationException || x is AggregateException) == false);

            return ex;
        }

        private static IEnumerable<Exception> GetAllExceptions(Exception ex)
        {
            while (ex != null)
            {
                yield return ex;
                ex = ex.InnerException;
            }
        }

        private void ValidateRequest(HttpListenerContext context)
        {
            var clientVersion = context.Request.Headers[GigyaHttpHeaders.ProtocolVersion];

            if (clientVersion != null && clientVersion != HttpServiceRequest.ProtocolVersion)
            {
                _failureCounter.Increment("ProtocolVersionMismatch");
                throw new RequestException($"Client protocol version {clientVersion} is not supported by the server protocol version {HttpServiceRequest.ProtocolVersion}.");
            }

            if (context.Request.HttpMethod != "POST")
            {
                context.Response.Headers.Add("Allow", "POST");
                _failureCounter.Increment("NonPostRequest");
                throw new RequestException("Only POST calls are allowed.");
            }

            if (context.Request.ContentType == null || context.Request.ContentType.StartsWith("application/json") == false)
            {
                context.Response.Headers.Add("Accept", "application/json");
                _failureCounter.Increment("NonJsonRequest");
                throw new RequestException("Only requests with content type 'application/json' are supported.");
            }

            if (context.Request.ContentLength64 == 0)
            {
                _failureCounter.Increment("EmptyRequest");
                throw new RequestException("Only requests with content are supported.");
            }

        }

        private async Task CheckSecureConnection(HttpListenerContext context)
        {
            if (!context.Request.IsSecureConnection)
            {
                // If a non-secure request reaches the HTTP port, we are safe
                if (context.Request.LocalEndPoint?.Port == ServiceEndPointDefinition.HttpPort)
                {
                    return;
                }

                _failureCounter.Increment("IncorrectSecurityType");
                throw new SecureRequestException("Incompatible channel security - both client and server must be either secure or insecure.",
                    unencrypted: new Tags { { "requestIsSecure", context.Request.IsSecureConnection.ToString() }, { "requestedUrl", context.Request.Url.ToString() } });
            }

            if (ServiceEndPointDefinition.ClientCertificateVerification == ClientCertificateVerificationMode.Disable)
            {
                return;
            }

            var clientCertificate = await context.Request.GetClientCertificateAsync();

            if (clientCertificate == null)
            {
                _failureCounter.Increment("MissingClientCertificate");
                throw new SecureRequestException("Client certificate is not present.");
            }

            var isValid = clientCertificate.HasSameRootCertificateHash(ServerRootCertHash);

            if (!isValid) // Invalid certificate
            {
                _failureCounter.Increment("InvalidClientCertificate");
                throw new SecureRequestException("Client certificate is not valid.");
            }
        }

        /// <summary>
        /// Writes to response output stream and returns response time
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <param name="httpStatus"></param>
        /// <param name="contentType"></param>
        /// <returns>double? - response time</returns>
        private async Task<bool> TryWriteResponse(HttpListenerContext context, string data, HttpStatusCode httpStatus = HttpStatusCode.OK, string contentType = "application/json", ServiceCallEvent serviceCallEvent = null)
        {
            context.Response.Headers.Add(GigyaHttpHeaders.ProtocolVersion, HttpServiceRequest.ProtocolVersion);

            var body = Encoding.UTF8.GetBytes(data ?? "");

            context.Response.StatusCode = (int)httpStatus;
            context.Response.ContentLength64 = body.Length;
            context.Response.ContentType = contentType;
            context.Response.Headers.Add(GigyaHttpHeaders.DataCenter, Environment.Zone);
            context.Response.Headers.Add(GigyaHttpHeaders.Environment, Environment.DeploymentEnvironment);
            context.Response.Headers.Add(GigyaHttpHeaders.ServiceVersion, AppInfo.Version.ToString());
            context.Response.Headers.Add(GigyaHttpHeaders.ServerHostname, CurrentApplicationInfo.HostName);
            context.Response.Headers.Add(GigyaHttpHeaders.SchemaHash, ServiceSchema.Hash);

            try
            {
                await WriteResponseAndMeasureTime(context, body, serviceCallEvent);
                return true;
            }
            catch (HttpListenerException writeEx)
            {
                if (serviceCallEvent != null)
                    serviceCallEvent.Exception = writeEx;
                // For some reason, HttpListener.IgnoreWriteExceptions doesn't work here.
                Log.Warn(_ => _("HttpServiceListener: Failed to write the response of a service call. See exception and tags for details.",
                    exception: writeEx,
                    unencryptedTags: new
                    {
                        remoteEndpoint = context.Request.RemoteEndPoint,
                        rawUrl = context.Request.RawUrl,
                        status = httpStatus
                    },
                    encryptedTags: new { response = data }));
                return false;
            }
        }

        private async Task WriteResponseAndMeasureTime(HttpListenerContext context, byte[] body, ServiceCallEvent serviceCallEvent = null)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            await context.Response.OutputStream.WriteAsync(body, 0, body.Length);
            sw.Stop();

            if (serviceCallEvent != null)
                serviceCallEvent.ClientResponseTime = sw.Elapsed.TotalMilliseconds;
        }

        private async Task<HttpServiceRequest> ParseRequest(HttpListenerContext context)
        {
            var request = await _deserializationTime.Time(async () =>
            {
                using (var streamReader = new StreamReader(context.Request.InputStream))
                {
                    var json = await streamReader.ReadToEndAsync();
                    return JsonConvert.DeserializeObject<HttpServiceRequest>(json, JsonSettings);
                }
            });

            // TODO: We have an issue when calling from Legacy:
            // http://kibana.gigya.net/kibana3/#/dashboard/elasticsearch/logdog_dashboard?query=callID:8f74364e9cab4aa4954374b8064155a1&from=2019-07-23T10:29:15.218Z&to=2019-07-23T10:31:15.220Z

            // var errors = new List<ValidationResult>();
            //
            // if (   !_validator.TryValidateObjectRecursive(request.Overrides, errors)
            //     || !_validator.TryValidateObjectRecursive(request.TracingData, errors)
            //     )
            // {
            //     _failureCounter.Increment("InvalidRequestFormat");
            //     throw new RequestException("Invalid request format: " + string.Join("\n", errors.Select(a => a.MemberNames + ": " + a.ErrorMessage)));
            // }

            request.TracingData = request.TracingData ?? new TracingData();
            request.TracingData.RequestID = request.TracingData.RequestID ?? Guid.NewGuid().ToString("N");

            return request;
        }

        private async Task<string> GetResponse(HttpListenerContext context, ServiceMethod serviceMethod, HttpServiceRequest requestData, object[] arguments)
        {
            var taskType = serviceMethod.ServiceInterfaceMethod.ReturnType;
            var resultType = taskType.IsGenericType ? taskType.GetGenericArguments().First() : null;
            var settings = requestData.Target.IsWeaklyTyped ? JsonSettingsWeak : JsonSettings;

            var invocationResult = await Activator.Invoke(serviceMethod, arguments);
            string response = _serializationTime.Time(() => JsonConvert.SerializeObject(invocationResult.Result, resultType, settings));
            context.Response.Headers.Add(GigyaHttpHeaders.ExecutionTime, invocationResult.ExecutionTime.ToString());

            return response;
        }

        private static object[] GetParametersByName(ServiceMethod serviceMethod, IDictionary args)
        {
            return serviceMethod.ServiceInterfaceMethod
                .GetParameters()
                .Select(p =>
                    {
                        try
                        {
                            return JsonHelper.ConvertWeaklyTypedValue(args[p.Name], p.ParameterType);
                        }
                        catch (InvalidParameterValueException ex)
                        {
                            if (ex.parameterName != null)
                                throw;

                            throw new InvalidParameterValueException(p.Name, ex.ErrorPath, ex.Message, ex);
                        }
                    }).
                    ToArray();
        }

        internal static HttpStatusCode GetExceptionStatusCode(Exception exception)
        {
            if (exception is SecureRequestException)
                return HttpStatusCode.Forbidden;
            if (exception is MissingMethodException)
                return HttpStatusCode.NotFound;
            if (exception is RequestException || exception is JsonException)
                return HttpStatusCode.BadRequest;
            if (exception is EnvironmentException)
                return HttpStatusCode.ServiceUnavailable;

            return HttpStatusCode.InternalServerError;
        }

        public void Dispose()
        {
            Worker.Dispose();
            Listener.Close();
        }

        public void Stop()
        {

        }
    }
}


text:
Windows 10 x64 (18362.449)

_EVENT_INFO_CLASS

   EventProviderBinaryTrackInfo = 0n0

   EventProviderSetReserved1 = 0n1

   EventProviderSetTraits = 0n2

   EventProviderUseDescriptorType = 0n3

   MaxEventInfo = 0n4


text:
package org.eclipse.collections.impl.map.fixed;

import org.eclipse.collections.impl.factory.Maps;
import org.eclipse.collections.impl.test.Verify;
import org.junit.Test;

public class DoubletonMapSerializationTest
{
    @Test
    public void serializedForm()
    {
        Verify.assertSerializedForm(
                1L,
                "rO0ABXNyADNvcmcuZWNsaXBzZS5jb2xsZWN0aW9ucy5pbXBsLm1hcC5maXhlZC5TaW5nbGV0b25N\n"
                        + "YXAAAAAAAAAAAQwAAHhwcHB4",
                Maps.fixedSize.of(null, null, null, null));
    }
}


text:
using System;
using System.Timers;
using GameplayContext.Ports;

namespace PackDrop.PortAdapters
{
    public class GameTimer : IGameTimer
    {
        private Timer _timer = new Timer();

        public GameTimer()
        {
            _timer.Elapsed += (sender, args) => Tick?.Invoke(sender, args);
        }

        public event EventHandler Tick;
        public void Start (int gameSpeed)
        {
            _timer.Interval = gameSpeed;
            _timer.Start();
        }

        public void UpdateInterval(int newSpeed)
        {
            _timer.Interval = newSpeed;
        }

        public void Stop()
        {
            _timer.Stop();
        }
    }
}


text:
package com.jonathancolt.nicity.view.core;

/*
 * #%L
 * nicity-view
 * %%
 * Copyright (C) 2013 Jonathan Colt
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import com.jonathancolt.nicity.core.memory.struct.XY_I;
import com.jonathancolt.nicity.view.interfaces.IPopup;
import com.jonathancolt.nicity.view.interfaces.IView;

/**
 *
 * @author Administrator
 */
public class NullPopup implements IPopup {

    /**
     *
     */
    public static final IPopup cNull = new NullPopup();

    /**
     *
     * @param popupParent
     */
    public void setPopupParent(IView popupParent) {
    }

    /**
     *
     * @return
     */
    public IView getPopupParent() {
        return NullView.cNull;
    }

    @Override
    public void showPopup(XY_I locationOnScreen, IView popupParent) {
    }

    @Override
    public void hidePopup() {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StatusCake.Client.Models
{
    /// <summary>
    /// Auth details class
    /// </summary>
    public class AuthDetails
    {
        /// <summary>
        /// The username of the authenticated user
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// The first name of the authenticated user
        /// </summary>
        public string FirstName { get; set; }

        /// <summary>
        /// The last name of the authenticated user
        /// </summary>
        public string LastName { get; set; }

        /// <summary>
        /// The plan type of the authenticated account
        /// </summary>
        public string Plan { get; set; }

        /// <summary>
        /// The timezone of the authenticated user
        /// </summary>
        public string Timezone { get; set; }

        /// <summary>
        /// The country code of the authenticated user
        /// </summary>
        public string CountryCode { get; set; }
    }
}


text:
from eventlet import semaphore
import heatclient.client as hclient
import keystoneclient
import keystoneclient.auth.identity.access as access
import muranoclient.v1.client as muranoclient
import neutronclient.v2_0.client as nclient
from oslo_config import cfg

from murano.common import auth_utils
from murano.dsl import helpers
from murano.engine import environment

try:
    # integration with congress is optional
    import congressclient.v1.client as congress_client
except ImportError as congress_client_import_error:
    congress_client = None
try:
    import mistralclient.api.client as mistralclient
except ImportError as mistral_import_error:
    mistralclient = None

CONF = cfg.CONF

class ClientManager(object):
    def __init__(self):
        self._trusts_keystone_client = None
        self._token_keystone_client = None
        self._cache = {}
        self._semaphore = semaphore.BoundedSemaphore()

    def _get_environment(self, context):
        if isinstance(context, environment.Environment):
            return context
        return helpers.get_environment(context)

    def get_client(self, context, name, use_trusts, client_factory):
        if not CONF.engine.use_trusts:
            use_trusts = False

        keystone_client = None if name == 'keystone' else \
            self.get_keystone_client(context, use_trusts)

        self._semaphore.acquire()
        try:
            client, used_token = self._cache.get(
                (name, use_trusts), (None, None))
            fresh_token = None if keystone_client is None \
                else keystone_client.auth_token
            if use_trusts and used_token != fresh_token:
                client = None
            if not client:
                token = fresh_token
                if not use_trusts:
                    env = self._get_environment(context)
                    token = env.token
                client = client_factory(keystone_client, token)
                self._cache[(name, use_trusts)] = (client, token)
            return client
        finally:
            self._semaphore.release()

    def get_keystone_client(self, context, use_trusts=True):
        if not CONF.engine.use_trusts:
            use_trusts = False
        env = self._get_environment(context)
        factory = lambda _1, _2: \
            auth_utils.get_client_for_trusts(env.trust_id) \
            if use_trusts else auth_utils.get_client(env.token, env.tenant_id)

        return self.get_client(context, 'keystone', use_trusts, factory)

    def get_congress_client(self, context, use_trusts=True):
        """Client for congress services

        :return: initialized congress client
        :raise ImportError: in case that python-congressclient
        is not present on python path
        """

        if not congress_client:
            # congress client was not imported
            raise congress_client_import_error
        if not CONF.engine.use_trusts:
            use_trusts = False

        def factory(keystone_client, auth_token):
            auth = access.AccessInfoPlugin(keystone_client.auth_ref)
            session = keystoneclient.session.Session(auth=auth)
            return congress_client.Client(session=session,
                                          service_type='policy')

        return self.get_client(context, 'congress', use_trusts, factory)

    def get_heat_client(self, context, use_trusts=True):
        if not CONF.engine.use_trusts:
            use_trusts = False

        def factory(keystone_client, auth_token):
            heat_settings = CONF.heat

            heat_url = keystone_client.service_catalog.url_for(
                service_type='orchestration',
                endpoint_type=heat_settings.endpoint_type)

            kwargs = {
                'token': auth_token,
                'ca_file': heat_settings.ca_file or None,
                'cert_file': heat_settings.cert_file or None,
                'key_file': heat_settings.key_file or None,
                'insecure': heat_settings.insecure
            }

            if not CONF.engine.use_trusts:
                kwargs.update({
                    'username': 'badusername',
                    'password': 'badpassword'
                })
            return hclient.Client('1', heat_url, **kwargs)

        return self.get_client(context, 'heat', use_trusts, factory)

    def get_neutron_client(self, context, use_trusts=True):
        if not CONF.engine.use_trusts:
            use_trusts = False

        def factory(keystone_client, auth_token):
            neutron_settings = CONF.neutron

            neutron_url = keystone_client.service_catalog.url_for(
                service_type='network',
                endpoint_type=neutron_settings.endpoint_type)

            return nclient.Client(
                endpoint_url=neutron_url,
                token=auth_token,
                ca_cert=neutron_settings.ca_cert or None,
                insecure=neutron_settings.insecure)

        return self.get_client(context, 'neutron', use_trusts, factory)

    def get_murano_client(self, context, use_trusts=True):
        if not CONF.engine.use_trusts:
            use_trusts = False

        def factory(keystone_client, auth_token):
            murano_settings = CONF.murano

            murano_url = \
                murano_settings.url or keystone_client.service_catalog.url_for(
                    service_type='application_catalog',
                    endpoint_type=murano_settings.endpoint_type)

            return muranoclient.Client(
                endpoint=murano_url,
                key_file=murano_settings.key_file or None,
                cacert=murano_settings.cacert or None,
                cert_file=murano_settings.cert_file or None,
                insecure=murano_settings.insecure,
                auth_url=keystone_client.auth_url,
                token=auth_token)

        return self.get_client(context, 'murano', use_trusts, factory)

    def get_mistral_client(self, context, use_trusts=True):
        if not mistralclient:
            raise mistral_import_error

        if not CONF.engine.use_trusts:
            use_trusts = False

        def factory(keystone_client, auth_token):
            mistral_settings = CONF.mistral

            endpoint_type = mistral_settings.endpoint_type
            service_type = mistral_settings.service_type

            mistral_url = keystone_client.service_catalog.url_for(
                service_type=service_type,
                endpoint_type=endpoint_type)

            return mistralclient.client(mistral_url=mistral_url,
                                        project_id=keystone_client.tenant_id,
                                        endpoint_type=endpoint_type,
                                        service_type=service_type,
                                        auth_token=auth_token,
                                        user_id=keystone_client.user_id)

        return self.get_client(context, 'mistral', use_trusts, factory)


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

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Request;
import com.amazonaws.services.ec2.model.transform.DeleteNetworkInsightsAccessScopeRequestMarshaller;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteNetworkInsightsAccessScopeRequest extends AmazonWebServiceRequest implements Serializable, Cloneable,
        DryRunSupportedRequest<DeleteNetworkInsightsAccessScopeRequest> {

    /**
     *

     * The ID of the Network Access Scope.
     *

     */
    private String networkInsightsAccessScopeId;

    /**
     *

     * The ID of the Network Access Scope.
     *

     *
     * @param networkInsightsAccessScopeId
     *        The ID of the Network Access Scope.
     */

    public void setNetworkInsightsAccessScopeId(String networkInsightsAccessScopeId) {
        this.networkInsightsAccessScopeId = networkInsightsAccessScopeId;
    }

    /**
     *

     * The ID of the Network Access Scope.
     *

     *
     * @return The ID of the Network Access Scope.
     */

    public String getNetworkInsightsAccessScopeId() {
        return this.networkInsightsAccessScopeId;
    }

    /**
     *

     * The ID of the Network Access Scope.
     *

     *
     * @param networkInsightsAccessScopeId
     *        The ID of the Network Access Scope.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DeleteNetworkInsightsAccessScopeRequest withNetworkInsightsAccessScopeId(String networkInsightsAccessScopeId) {
        setNetworkInsightsAccessScopeId(networkInsightsAccessScopeId);
        return this;
    }

    /**
     * This method is intended for internal use only. Returns the marshaled request configured with additional
     * parameters to enable operation dry-run.
     */
    @Override
    public Request<DeleteNetworkInsightsAccessScopeRequest> getDryRunRequest() {
        Request<DeleteNetworkInsightsAccessScopeRequest> request = new DeleteNetworkInsightsAccessScopeRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

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

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

        if (obj instanceof DeleteNetworkInsightsAccessScopeRequest == false)
            return false;
        DeleteNetworkInsightsAccessScopeRequest other = (DeleteNetworkInsightsAccessScopeRequest) obj;
        if (other.getNetworkInsightsAccessScopeId() == null ^ this.getNetworkInsightsAccessScopeId() == null)
            return false;
        if (other.getNetworkInsightsAccessScopeId() != null && other.getNetworkInsightsAccessScopeId().equals(this.getNetworkInsightsAccessScopeId()) == false)
            return false;
        return true;
    }

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

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

    @Override
    public DeleteNetworkInsightsAccessScopeRequest clone() {
        return (DeleteNetworkInsightsAccessScopeRequest) super.clone();
    }
}


text:
module.exports = function (api) {
  api.cache(true);

  const nonDevPlugins = [
    'transform-remove-console',
    'transform-remove-debugger',
  ];
  const transpilePlugins = [...nonDevPlugins];

  return {
    presets: [
      [
        '@babel/preset-env',
        {
          // Don't include any polyfill
          useBuiltIns: false,
        },
      ],
      [
        '@babel/preset-react',
        {
          runtime: 'automatic',
        },
      ],
    ],

    plugins: [
      'transform-property-literals',
      'transform-member-expression-literals',
      '@babel/plugin-proposal-export-namespace-from',
      '@babel/plugin-proposal-export-default-from',
      '@babel/plugin-proposal-class-properties',
      [
        '@babel/plugin-transform-runtime',
        {
          corejs: false,
          helpers: true,
          regenerator: true,
          useESModules: false,
        },
      ],
    ],

    env: {
      production: {
        plugins: nonDevPlugins,
      },

      // Output using commonjs module
      transpile: {
        plugins: transpilePlugins,
      },

      // Output using ES module
      es: {
        presets: [
          [
            '@babel/preset-env',
            {
              // Don't include any polyfill
              useBuiltIns: false,

              // Don't transform modules
              modules: false,
            },
          ],
        ],

        plugins: [
          ...transpilePlugins,
          [
            '@babel/plugin-transform-runtime',
            {
              corejs: false,
              helpers: true,
              regenerator: true,

              // Use ES module
              useESModules: true,
            },
          ],
        ],
      },
    },
  };
};


text:
// BEGIN LICENSE BLOCK
// Version: CMPL 1.1
//
// The contents of this file are subject to the Cisco-style Mozilla Public
// License Version 1.1 (the "License"); you may not use this file except
// in compliance with the License.  You may obtain a copy of the License
// at www.eclipse-clp.org/license.
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
// the License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is  CPViz Constraint Visualization System
// The Initial Developer of the Original Code is  Helmut Simonis
// Portions created by the Initial Developer are
// Copyright (C) 2009-2010 Helmut Simonis
//
// Contributor(s): 	Helmut Simonis, 4C, Univerity College Cork, Cork
//
//
// END LICENSE BLOCK
// ----------------------------------------------------------------------
package ie.ucc.cccc.viz;

/**
 * Description of a tool which defines how visualizations should be drawn, where
 * the results are stored, etc
 * @author hsimonis
 *
 */
public class Tool {
	private Tools tools;
	private String show;
	private String type;
	private String display;
	private String repeat;
	private int width;
	private int height;
	private String fileroot;

	@Override public String toString(){
		return "Tool "+show+" type "+type+" display "+display+
		" repeat "+repeat+" width "+width+" height "+height+
		" fileroot "+fileroot;
	}
	public Tool(Tools tools,String show,String type, String display, String repeat,
			int width,int height,String fileroot){
		this.tools = tools;
		this.show = show;
		this.type = type;
		this.display= display;
		this.repeat = repeat;
		this.width =width;
		this.height= height;
		this.fileroot=fileroot;
	}

	/**
	 * This code decides how trees are drawn
	 * @param tree Tree, tree structure to display
	 */
	public void handleTree(Tree tree){
		if (show.equals("tree") && type.equals("layout")) {
			boolean compact= display.equals("compact");
			if (repeat.equals("final")) {
				Layout layout = Layout.layoutNode(tree.getRootNode(),
						compact,tree.getNrNodes()+1,1);
				layout.draw(this,layout.getBox(),compact,tree.getNrNodes()+1,
						getFileroot()+".svg");
			} else if (repeat.equals("all")) {
				for(int i=0; i< tree.getNrNodes();i++) {
					Layout layout = Layout.layoutNode(tree.getRootNode(),compact,i,1);
					layout.draw(this,layout.getBox(),compact,i,getFileroot()+i+".svg");
				}
			} else {
				int k =Integer.parseInt(repeat);
				if (k < 0) {
					// repeat = "-n"
					for(int i=0; i< Math.min(-k,tree.getNrNodes());i++) {
						Layout layout = Layout.layoutNode(tree.getRootNode(),compact,i,1);
						layout.draw(this,layout.getBox(),compact,i,getFileroot()+i+".svg");
					}
				} else {
					// repeat = "n"
					Layout layout = Layout.layoutNode(tree.getRootNode(),
							compact,k,1);
					layout.draw(this,layout.getBox(),compact,k,getFileroot()+".svg");

				}
			}
		} else if (show.equals("tree") && type.equals("graph")) {
			TreeGraph treeGraph = TreeGraph.graph(tree.getRootNode());
			treeGraph.plot(getDirectory(),getFileroot()+".dat");

		} else if (show.equals("tree") && type.equals("values")) {
			TreeValues treeValues = TreeValues.graph(tree.getRootNode());
			treeValues.plot(getDirectory(),getFileroot()+".tm3");

		} else {
			System.out.println("skip tool "+this);
		}
	}

	/**
	 * This decides how States are drawn, where the output goes, etc.
	 * @param state State, describes the state to be displayed
	 * @param box Box, the enclosing box containing all visual information
	 */
	public void handleState(State state,Box box){
		if (show.equals("viz") && type.equals("layout")) {
			state.draw(this,box);
		} else {
			System.out.println("Skipping tool "+ this);
		}

	}

	public String getShow() {
		return show;
	}
	public String getType() {
		return type;
	}
	public String getDisplay() {
		return display;
	}
	public String getRepeat() {
		return repeat;
	}
	public int getWidth() {
		return width;
	}
	public int getHeight() {
		return height;
	}
	public String getDirectory() {
		return tools.getDirectory();
	}
	public String getFileroot() {
		return fileroot;
	}

}