text:
 module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    simplemocha: {
      options: {
        globals: ['should'],
        timeout: 3000,
        ignoreLeaks: false,
        // grep: '*-test',
        ui: 'bdd',
        reporter: 'tap'
      },

      all: { src: ['test/**/*.js'] }
    },

    concat: {
      options: {
        separator: "\n\n\n"
      },
      css: {
        src: [
          'client-src/css/responsive.gs.12col.css',
          'client-src/css/app.css',
          'bower_components/AngularJS-Toaster/toaster.css'
        ],
        dest: 'client/css/app.css'
      },
      js: {
        src: [
          'client-src/js/chat.js',
          'client-src/js/controllers.js',
          'client-src/js/directives.js',
          'client-src/js/filters.js',
          'client-src/js/services.js',
        ],
        dest: 'client/js/chat.js'
      }
    },

    copy: {
      main: {
        files: [
          {src: 'client-src/js/app.js', dest: 'client/js/app.min.js' },
          {
            expand: true,
            src: ['client-src/directives/**.html'],
            dest: 'client/directives/',
            flatten: true,
            filter: 'isFile'
          },

          {
            src: 'bower_components/angular/angular.js',
            dest: 'client/js/angular.js'
          },
          {
            src: 'bower_components/angular/angular.min.js',
            dest: 'client/js/angular.min.js'
          },
          {
            src: 'bower_components/angular/angular.min.js.map',
            dest: 'client/js/angular.min.js.map'
          },
          {
            src: 'bower_components/angular-animate/angular-animate.js',
            dest: 'client/js/angular-animate.js'
          },
          {
            src: 'bower_components/angular-animate/angular-animate.min.js',
            dest: 'client/js/angular-animate.min.js'
          },
          {
            src: 'bower_components/angular-animate/angular-animate.min.js.map',
            dest: 'client/js/angular-animate.min.js.map'
          },
          {
            src: 'bower_components/angular-socket-io/socket.js',
            dest: 'client/js/socket.js' },
          {
            src: 'bower_components/AngularJS-Toaster/toaster.js',
            dest: 'client/js/toaster.js'
          },
          {
            src: 'node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js',
            dest: 'client/js/socket.io.js'
          },

        ]
      }
    }
  });

  // Load plugins.
  //grunt.loadNpmTasks('grunt-contrib-uglify');
  //grunt.loadNpmTasks('grunt-contrib-jade');
  //grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-simple-mocha');

  // Tasks
  grunt.registerTask('default', ['simplemocha', 'copy', 'concat']);
};


text:
using Bridge;
using Bridge.Html5;

using System;
using System.Collections.Generic;

namespace Mandelbrot.Canvas
{

    class Drawer
    {
        private CanvasRenderingContext2D CanvasRenderingContext;
        private ImageData Image;
        private HTMLButtonElement DrawButton;
        private HTMLInputElement IterationCountElement;
        private HTMLInputElement RadiusElement;

        private HTMLInputElement ColorMapCheckbox;
        private HTMLInputElement ColorOffsetElement;
        private HTMLInputElement ColorScaleElement;

        private HTMLInputElement JuliaSetCheckbox;
        private HTMLInputElement JuliaReElement;
        private HTMLInputElement JuliaImElement;

        private HTMLInputElement XMinElement;
        private HTMLInputElement XMaxElement;
        private HTMLInputElement YMinElement;
        private HTMLInputElement YMaxElement;

        private int CurrentY;
        private Mandelbrot Calculator;
        private Options Settings;

        public Drawer(Options settings, Mandelbrot calculator)
        {
            this.Settings = settings;
            this.Calculator = calculator;

            // the actual canvas element
            var canvas = new HTMLCanvasElement();
            canvas.Width = 900;
            canvas.Height = 500;

            DrawButton = new HTMLButtonElement
            {
                InnerHTML = "Draw the Mandelbrot fractal",
                OnClick = (ev) =>
                {
                    StartDraw(canvas);
                }
            };

            DrawButton.SetAttribute("style", "font-size:18px;height: 60px;  width:95%; border: 2px solid black; cursor: pointer");

            // Iteration controls
            RadiusElement = GetInputNumberElement(null, this.Settings.MaxRadius, 3, 0.5);
            IterationCountElement = GetInputNumberElement(null, this.Settings.MaxIterations, 4, 100, 0, 100000);
            // Color controls
            ColorMapCheckbox = GetCheckboxElement(this.Settings.UseColorMap);
            ColorScaleElement = GetInputNumberElement(ColorMapCheckbox, this.Settings.ColorScale, 5, 1000);
            ColorOffsetElement = GetInputNumberElement(ColorMapCheckbox, this.Settings.ColorOffset, 4, 10);

            // Julia sets
            JuliaSetCheckbox = GetCheckboxElement(this.Settings.UseJuliaSet);
            JuliaImElement = GetInputNumberElement(JuliaSetCheckbox, this.Settings.JuliaSetParameter.Im, 5, 0.005, null);
            JuliaReElement = GetInputNumberElement(JuliaSetCheckbox, this.Settings.JuliaSetParameter.Re, 5,  0.005, null);

            // Viewport controls
            XMinElement = GetInputNumberElement(null, this.Settings.XMin, 5, 0.005, -5.0);
            XMaxElement = GetInputNumberElement(null, this.Settings.XMax, 5, 0.005, 0.0);
            YMinElement = GetInputNumberElement(null, this.Settings.YMin, 5, 0.005, -5.0);
            YMaxElement = GetInputNumberElement(null, this.Settings.YMax, 5, 0.005, 0.0);

            var paramsColumn = new HTMLTableDataCellElement();
            var canvasColumn = new HTMLTableDataCellElement();
            paramsColumn.SetAttribute("valign", "top");
            canvasColumn.SetAttribute("valign", "top");
            canvasColumn.AppendChild(canvas);

            var layoutRow = new HTMLTableRowElement();
            layoutRow.AppendChildren(paramsColumn, canvasColumn);

            var layout = new HTMLTableElement();

            var paramsTable = new HTMLTableElement();
            paramsTable.AppendChildren(
                Row(Label("XMin: "), XMinElement),
                Row(Label("XMax: "), XMaxElement),
                Row(Label("YMin: "), YMinElement),
                Row(Label("YMax: "), YMaxElement),
                Row(Label("Escape radius: "), RadiusElement),
                Row(Label("Iteration count: "), IterationCountElement),
                Row(Label("Use color map: "), ColorMapCheckbox),
                Row(Label("Color scale: "), ColorScaleElement),
                Row(Label("Color offset: "), ColorOffsetElement),
                Row(Label("Use Julia set: "), JuliaSetCheckbox),
                Row(Label("Im: "), JuliaImElement),
                Row(Label("Re: "), JuliaReElement),
                Row(new HTMLHRElement(), 2),
                Row(DrawButton, 2)
            );

            paramsColumn.AppendChild(paramsTable);

            layout.AppendChild(layoutRow);
            Document.Body.AppendChild(layout);
        }

        private HTMLLabelElement Label(string value)
        {
            var lbl = new HTMLLabelElement();
            lbl.InnerHTML = value;
            lbl.Style.Margin = "5px";
            lbl.Style.FontSize = "18px";
            return lbl;
        }
        private HTMLTableRowElement Row(params HTMLElement[] elements)
        {
            var row = new HTMLTableRowElement();
            foreach(var el in elements)
                row.AppendChild(el.WithinTableDataCell());
            return row;
        }

        private HTMLTableRowElement Row(HTMLElement el, int colspan)
        {
            var row = new HTMLTableRowElement();
            var td = new HTMLTableDataCellElement();
            td.SetAttribute("colspan", colspan.ToString());
            td.AppendChild(el);
            row.AppendChild(td);
            return row;
        }

        private HTMLInputElement GetCheckboxElement(bool isChecked)
        {
            var checkbox = new HTMLInputElement
            {
                Type = InputType.Checkbox,
                Checked = isChecked,
            };

            // Extend the checkbox
            var elements = GetElementListToEnable(checkbox);

            Action<Event<HTMLInputElement>> enableInputs = (ev) =>
            {
                foreach (var control in elements)
                {
                    control.Disabled = !checkbox.Checked;
                }
            };
            checkbox.OnChange = enableInputs;

            //var label = new HTMLLabelElement
            //{
            //    InnerHTML = title
            //};

            //label.Style.Margin = "5px";
            //label.AppendChild(checkbox);

            //if (container != null)
            //{
            //    container.AppendChild(label);
            //}

            return checkbox;
        }

        private List<HTMLInputElement> GetElementListToEnable(HTMLInputElement element)
        {
            var ce = element["toEnable"];
            List<HTMLInputElement> elements;

            if (ce == null || (elements = ce as List<HTMLInputElement>) == null)
            {
                elements = new List<HTMLInputElement>();
                element["toEnable"] = elements;
            }

            return elements;
        }

        private HTMLInputElement GetInputNumberElement(HTMLInputElement enableElement, double initialValue, int widthInDigits, double? step = 1, double? min = 0, double? max = null)
        {
            var element = new HTMLInputElement()
            {
                Type = InputType.Number,
                Value = initialValue.ToString(),
                OnKeyUp = (ev) =>
                {
                    if (ev.IsKeyboardEvent())
                    {
                        var kev = ev as KeyboardEvent<HTMLInputElement>;

                        if (kev != null)
                        {
                            if (object.Equals(kev["keyCode"], 13))
                            {
                                ev.PreventDefault();
                                DrawButton.Click();
                            }
                        }
                    }
                }
            };

            if (enableElement != null)
            {
                element.Disabled = !enableElement.Checked;

                var elements = GetElementListToEnable(enableElement);
                elements.Add(element);
            }

            if (step.HasValue)
            {
                element.Step = step.ToString();
            }

            if (min.HasValue)
            {
                element.Min = min.ToString();
            }

            if (max.HasValue)
            {
                element.Max = max.ToString();
            }

            element.Style.Width = widthInDigits + "em";
            element.Style.Margin = "5px";

            return element;
        }

        private void GetImageData(HTMLCanvasElement canvas)
        {
            int height = canvas.Height;
            int width = canvas.Width;

            if (CanvasRenderingContext == null)
            {
                CanvasRenderingContext = canvas.GetContext(CanvasTypes.CanvasContext2DType.CanvasRenderingContext2D);
            }

            if (Image == null)
            {
                // the data to manipulate
                Image = CanvasRenderingContext.CreateImageData(width, height);
            }
            else
            {
                //var color = new Color() { Red = 0, Green = 0, Blue = 0 };

                //for (int y = 0; y < height; y++)
                //{
                //    for (int x = 0; x < width; x++)
                //    {
                //        Image.SetPixel(x, y, color);
                //    }
                //}
            }
        }

        private void StartDraw(HTMLCanvasElement canvas)
        {
            if (!GetInputValue(IterationCountElement, out this.Settings.MaxIterations))
            {
                Window.Alert("Iteration count should be positive integer");
                return;
            }

            if (!GetInputValue(RadiusElement, out this.Settings.MaxRadius))
            {
                Window.Alert("Escape radius should be positive integer");
                return;
            }

            if (!GetInputValue(XMinElement, out this.Settings.XMin))
            {
                Window.Alert("XMin should be a number");
                return;
            }

            if (!GetInputValue(XMaxElement, out this.Settings.XMax))
            {
                Window.Alert("XMax should be a number");
                return;
            }

            if (!GetInputValue(YMinElement, out this.Settings.YMin))
            {
                Window.Alert("YMin should be a number");
                return;
            }

            if (!GetInputValue(YMaxElement, out this.Settings.YMax))
            {
                Window.Alert("YMax should be a number");
                return;
            }

            this.Settings.UseColorMap = ColorMapCheckbox.Checked;
            if (this.Settings.UseColorMap)
            {
                if (!GetInputValue(ColorScaleElement, out this.Settings.ColorScale))
                {
                    Window.Alert("Color scale should be positive integer");
                    return;
                }

                if (!GetInputValue(ColorOffsetElement, out this.Settings.ColorOffset))
                {
                    Window.Alert("Color offset should be positive integer");
                    return;
                }
            }

            this.Settings.UseJuliaSet = JuliaSetCheckbox.Checked;
            if (this.Settings.UseJuliaSet)
            {
                if (!GetInputValue(JuliaImElement, out this.Settings.JuliaSetParameter.Im))
                {
                    Window.Alert("Julia Im should be a number");
                    return;
                }

                if (!GetInputValue(JuliaReElement, out this.Settings.JuliaSetParameter.Re))
                {
                    Window.Alert("Julia Re should be a number");
                    return;
                }
            }

            GetImageData(canvas);

            CurrentY = 0;
            DrawPart();
        }

        private void DrawPart()
        {
            int height = CanvasRenderingContext.Canvas.Height;
            int width = CanvasRenderingContext.Canvas.Width;

            if (CurrentY < height)
            {
                for (int x = 0; x < width; x++)
                {
                    var color = this.Calculator.CalculatePoint(x, CurrentY, height, width);

                    Image.SetPixel(x, CurrentY, color);
                }

                CanvasRenderingContext.PutImageData(Image, 0, 0);
                CurrentY++;
            }

            if (CurrentY < height)
            {
                Window.SetTimeout(DrawPart, 0);
            }
        }

        private static bool GetInputValue(HTMLInputElement source, out int number)
        {
            var d = Script.ParseFloat(source.Value);
            if (double.IsNaN(d))
            {
                number = 0;
                return false;
            }

            number = (int)Math.Round(d);
            return true;
        }

        private static bool GetInputValue(HTMLInputElement source, out double number)
        {
            number = Script.ParseFloat(source.Value);
            if (double.IsNaN(number))
            {
                return false;
            }

            return true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""SCons.Tool.pdf

Common PDF Builder definition for various other Tool modules that use it.

"""

#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "src/engine/SCons/Tool/pdf.py 3603 2008/10/10 05:46:45 scons"

import SCons.Builder
import SCons.Tool

PDFBuilder = None

def generate(env):
    try:
        env['BUILDERS']['PDF']
    except KeyError:
        global PDFBuilder
        if PDFBuilder is None:
            PDFBuilder = SCons.Builder.Builder(action = {},
                                               source_scanner = SCons.Tool.PDFLaTeXScanner,
                                               prefix = '$PDFPREFIX',
                                               suffix = '$PDFSUFFIX',
                                               emitter = {},
                                               source_ext_match = None)
        env['BUILDERS']['PDF'] = PDFBuilder

    env['PDFPREFIX'] = ''
    env['PDFSUFFIX'] = '.pdf'

def exists(env):
    # This only puts a skeleton Builder in place, so if someone
    # references this Tool directly, it's always "available."
    return 1


text:
/// <amd-module name="@angular/core/schematics/migrations/static-queries/angular/query-definition" />
import * as ts from 'typescript';
import { NgDecorator } from '../../../utils/ng_decorators';
/** Timing of a given query. Either static or dynamic. */
export declare enum QueryTiming {
    STATIC = 0,
    DYNAMIC = 1
}
/** Type of a given query. */
export declare enum QueryType {
    ViewChild = 0,
    ContentChild = 1
}
export interface NgQueryDefinition {
    /** Name of the query. Set to "null" in case the query name is not statically analyzable. */
    name: string | null;
    /** Type of the query definition. */
    type: QueryType;
    /** Node that declares this query. */
    node: ts.Node;
    /**
     * Property declaration that refers to the query value. For accessors there
     * is no property that is guaranteed to access the query value.
     */
    property: ts.PropertyDeclaration | null;
    /** Decorator that declares this as a query. */
    decorator: NgDecorator;
    /** Class declaration that holds this query. */
    container: ts.ClassDeclaration;
}


text:
import astropy.units as u
import numpy as np
import pytest

from astromodels.core.spectral_component import SpectralComponent
from astromodels.functions.functions import Powerlaw, Log_parabola
from astromodels.functions.functions_2D import *
from astromodels.functions.functions_3D import *
from astromodels.sources.extended_source import ExtendedSource
from astromodels.core.model import Model
from astromodels.core.model_parser import clone_model

from astromodels.functions.priors import *
from astromodels.functions.function import _known_functions

__author__ = 'henrikef'

def make_test_template( ra, dec, fitsfile):

#Test template function: 40 pixel (0.8 deg) wide square centered approximately around a given ra, dec.

  cards = {
    "SIMPLE": "T",
    "BITPIX": -32,
    "NAXIS" : 2,
    "NAXIS1": 200,
    "NAXIS2": 200,
    "DATE": '2018-11-13',
    "CUNIT1": 'deg',
    "CRVAL1":  ra,
    "CRPIX1": 100,
    "CDELT1": -0.02,
    "CUNIT2": 'deg',
    "CRVAL2": dec,
    "CRPIX2": 100,
    "CDELT2": 0.02,
    "CTYPE1": 'RA---TAN',
    "CTYPE2": 'DEC--TAN' }

  data = np.zeros([200,200])
  data[80:120,80:120] = 1

  total = np.sum(data)
  dOmega = (abs( cards["CDELT1"] * cards["CDELT2"])*u.degree*u.degree).to(u.steradian).value
  data=data/ total / dOmega

  hdu = fits.PrimaryHDU(data=data, header=fits.Header(cards))
  hdu.writeto(fitsfile, overwrite=True)

def test_constructor():

    # RA, Dec and L,B of the same point in the sky

    ra, dec = (125.6, -75.3)
    l, b = (288.44190139183564, -20.717313145391525)

    # This should throw an error as we are using Powerlaw instead of Powerlaw()
    with pytest.raises(RuntimeError):

        _ = ExtendedSource("my_source", Gaussian_on_sphere, Powerlaw)

    # This should throw an error because we should use a 2D function for the spatial shape
    with pytest.raises(RuntimeError):

        _ = ExtendedSource("my_source", Powerlaw(), Powerlaw())

    # Init with RA, Dec

    shape = Gaussian_on_sphere()
    source1 = ExtendedSource('my_source', shape, Powerlaw())
    shape.lon0=ra*u.degree
    shape.lat0=dec*u.degree

    assert source1.spatial_shape.lon0.value == ra
    assert source1.spatial_shape.lat0.value == dec

    # Verify that the position is free by default
    assert source1.spatial_shape.lon0.free
    assert source1.spatial_shape.lon0.free

def test_call():

    # Multi-component

    po1 = Powerlaw()
    po2 = Powerlaw()

    c1 = SpectralComponent("component1", po1)
    c2 = SpectralComponent("component2", po2)

    ra, dec = (125.6, -75.3)

    def test_one(class_type, name ):

      print("testing %s ..." % name)

      shape = class_type()
      source = ExtendedSource('test_source_%s' % name, shape, components=[c1, c2])

      if name != "SpatialTemplate_2D":
        shape.lon0=ra*u.degree
        shape.lat0=dec*u.degree

      else:
        make_test_template(ra, dec, "__test.fits")
        shape.load_file( "__test.fits" )
        shape.K = 1.0

      assert np.all(source.spectrum.component1([1, 2, 3]) == po1([1, 2, 3]))
      assert np.all(source.spectrum.component2([1, 2, 3]) == po2([1, 2, 3]))

      one = source.spectrum.component1([1, 2, 3])
      two = source.spectrum.component2([1, 2, 3])

      #check spectral components
      assert np.all( np.abs(one + two - source.get_spatially_integrated_flux([1,2,3])) == 0 )

      #check spectral and spatial components
      total = source( [ra, ra, ra], [dec, dec, dec], [1,2,3])
      spectrum = one + two
      spatial = source.spatial_shape( [ra, ra, ra], [dec, dec, dec] )
      assert np.all( np.abs( total - spectrum*spatial ) == 0 )

      total = source( [ra*1.01]*3, [dec*1.01]*3, [1,2,3])
      spectrum = one + two
      spatial = source.spatial_shape( [ra*1.01]*3, [dec*1.01]*3 )
      assert np.all( np.abs( total - spectrum*spatial ) == 0 )

    for key in _known_functions:

        if key in [ "Latitude_galactic_diffuse"]:
        #not testing latitude galactic diffuse for now.
            continue

        this_function = _known_functions[key]

        if this_function._n_dim == 2  and not this_function().is_prior:

            test_one(this_function, key)

    with pytest.raises(AssertionError):
        #this will fail because the Latitude_galactic_diffuse function isn't normalized.
        test_one(_known_functions["Latitude_galactic_diffuse"], "Latitude_galactic_diffuse")

def test_call_with_units():

    # Multi-component

    po1 = Powerlaw()
    po2 = Powerlaw()

    c1 = SpectralComponent("component1", po1)
    c2 = SpectralComponent("component2", po2)

    ra, dec = (125.6, -75.3)

    def test_one(class_type, name ):

      print("testing %s ..." % name)

      shape = class_type()
      source = ExtendedSource('test_source_%s' % name, spatial_shape = shape, components=[c1, c2])

      if name != "SpatialTemplate_2D":
        shape.lon0=ra*u.degree
        shape.lat0=dec*u.degree

      else:
        make_test_template(ra, dec, "__test.fits")
        shape.load_file( "__test.fits" )
        shape.K = 1.0

      assert np.all(source.spectrum.component1([1, 2, 3]*u.keV) == po1([1, 2, 3]*u.keV))
      assert np.all(source.spectrum.component2([1, 2, 3]*u.keV) == po2([1, 2, 3]*u.keV))

      one = source.spectrum.component1([1, 2, 3]*u.keV)
      two = source.spectrum.component2([1, 2, 3]*u.keV)

      #check spectral components
      assert np.all( np.abs(one + two - source.get_spatially_integrated_flux([1,2,3]*u.keV)) == 0 )

      #check spectral and spatial components
      spatial = source.spatial_shape( ra*u.deg,dec*u.deg )
      spatial = source.spatial_shape( [ra, ra, ra]*u.deg, [dec, dec, dec]*u.deg )

      total = source( [ra, ra, ra]*u.deg, [dec, dec, dec]*u.deg, [1,2,3]*u.keV)
      spectrum = one + two
      assert np.all( np.abs( total - spectrum*spatial ) == 0 )

      total = source( [ra*1.01]*3*u.deg, [dec*1.01]*3*u.deg, [1,2,3]*u.keV)
      spectrum = one + two
      spatial = source.spatial_shape( [ra*1.01]*3*u.deg, [dec*1.01]*3*u.deg )
      assert np.all( np.abs( total - spectrum*spatial ) == 0 )

      model = Model( source )
      new_model = clone_model( model )

      new_total = new_model['test_source_%s' % name]( [ra*1.01]*3*u.deg, [dec*1.01]*3*u.deg, [1,2,3]*u.keV)
      assert np.all( np.abs( total - new_total ) == 0 )

    for key in _known_functions:

        if key in ["Latitude_galactic_diffuse" ]:
        #not testing latitude galactic diffuse for now.
            continue

        this_function = _known_functions[key]

        if this_function._n_dim == 2  and not this_function().is_prior:

            test_one(this_function, key)

    with pytest.raises(AssertionError):
        #this will fail because the Latitude_galactic_diffuse function isn't normalized.
        test_one(_known_functions["Latitude_galactic_diffuse"], "Latitude_galactic_diffuse")

def test_free_param():

    spectrum = Log_parabola()
    source = ExtendedSource("test_source", spatial_shape=Gaussian_on_sphere(), spectral_shape=spectrum)

    parameters = [spectrum.alpha, spectrum.beta, spectrum.piv, spectrum.K, source.spatial_shape.lat0, source.spatial_shape.lon0, source.spatial_shape.sigma]

    for param in parameters:
        param.free = False

    assert len(source.free_parameters) == 0

    for i, param in enumerate(parameters):
        param.free = True
        assert len(source.free_parameters) == i+1


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CAT2 Peripheral Driver Library: cy_stc_msclp_mrss_config_t Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

CAT2 Peripheral Driver Library

Data Fields

cy_stc_msclp_mrss_config_t Struct Reference
MSCLP        (Multi-Sense Converter Low-Power) » Data Structures

Description

MRSS configuration structure.

This structure contains values needed for MRSS configuring.

Data Fields

uint8_t 	imoFreq

 	The clk_imo_msc frequency, CY_MSCLP_IMO_24_MHZ, CY_MSCLP_IMO_36_MHZ or CY_MSCLP_IMO_48_MHZ.

uint8_t 	syncDiv

 	Clock division for clk_imo_msc to clk_sync, CY_MSCLP_SYNC_DIV_1...CY_MSCLP_SYNC_DIV_8.

uint16_t 	mscDiv

 	The clk_msc divider, i.e.  More...

uint16_t 	vdda

 	System VDDA value in millivolts.

Field Documentation

◆ mscDiv

          uint16_t cy_stc_msclp_mrss_config_t::mscDiv

The clk_msc divider, i.e.

the ratio between clk_imo_msc and clk_msc. Valid range: 1...1024


text:
package android.orm.util;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Pair;

public abstract class Future<V> {

    private static final String TAG = Future.class.getSimpleName();
    private static final Handler MAIN_THREAD = new Handler(Looper.getMainLooper());

    protected Future() {
        super();
    }

    public abstract void onComplete(@Nullable final Handler handler,
                                    @NonNull final Callback<? super V> callback);

    @NonNull
    public abstract <T> Future<T> map(@NonNull final Function<? super V, ? extends T> function);

    @NonNull
    public abstract <T> Future<T> flatMap(@NonNull final Function<? super V, Future<T>> function);

    public final void onComplete(@NonNull final Callback<? super V> callback) {
        onComplete(getHandler(), callback);
    }

    @NonNull
    public final <T> Future<Pair<V, T>> and(@NonNull final Future<? extends T> other) {
        return flatMap(new Function<V, Future<Pair<V, T>>>() {
            @NonNull
            @Override
            public Future<Pair<V, T>> invoke(@NonNull final V v) {
                return other.map(new Function<T, Pair<V, T>>() {
                    @NonNull
                    @Override
                    public Pair<V, T> invoke(@NonNull final T t) {
                        return Pair.create(v, t);
                    }
                });
            }
        });
    }

    @NonNull
    private static Handler getHandler() {
        final Handler result;

        final Looper looper = Looper.myLooper();
        if (looper == null) {
            Log.w(TAG, "Future callback registered on a non-looper thread. Using main thread to execute task, which might not be optimal!", new Throwable()); //NON-NLS
            result = MAIN_THREAD;
        } else {
            result = new Handler();
        }

        return result;
    }

    public interface Callback<V> {

        void onResult(@NonNull final V v);

        void onError(@NonNull final Throwable error);
    }
}


text:
import os, sys, re
from xml.etree.ElementTree import fromstring

import fiona
from fiona.crs import from_epsg
from shapely.geometry import mapping, Point, LineString
import pyproj
import datetime as dt
from datetime import timedelta,datetime

#--------------------------------------------------------------------------------------------------
#                 Set Parameters for Geographic Transformation
#--------------------------------------------------------------------------------------------------

geod = pyproj.Geod(ellps='WGS84')

#function to return the data in the specific TCX tags - code from https://github.com/jhofman/fitnesshacks
def findtext(e, name, default=None):
    """
    findtext
    helper function to find sub-element of e with given name and
    return text value
    returns default=None if sub-element isn't found
    """
    try:
        return e.find(name).text
    except:
        return default

#Set input data path
path = ''

listing = os.listdir(path)

for infile in listing:

    #build empty list
    datalist = []

    #Input file TCX file
    inputFile = infile
    outputShapefileName = shapeName = (infile.split("."))[0]

    print("Building "+outputShapefileName + " Shapefile")

    #output folder location
    outpath =  ''

    istream = open(path+'/'+inputFile,'r')

    #initialize an ID counter
    idval = 0

    # read xml contents
    xml = istream.read()

    # parse tcx file
    xml = re.sub('xmlns=".*?"','',xml)

    # parse xml
    tcx=fromstring(xml)

    #pull the activity type from the TCX file
    activity = tcx.find('.//Activity').attrib['Sport']

    #output shapefile
    outShape = 'rBr_'+outputShapefileName+'_shape.shp'

    print("    Final Shapefile: "+ outShape)

    #output crs
    crs = fiona.crs.from_epsg(4326)

    #output shapefile schema

    schema = {
        'geometry': 'LineString',
        'properties': {'id': 'int','distMeters':'float','MpS':'float','TtlMtrs':'float','TtlFt':'float','TtlMile':'float','TtlTime':'str:50','FlagDist':'float','FlagTime':'str:50',},
    }

    print ("    Start TCX Extraction")
    print( "    Full Path: "+ outpath+outShape)

    #build a list for all the points from the TCX file
    for lap in tcx.findall('.//Lap/'):

        for point in lap.findall('.//Trackpoint'):

            idval = idval + 1
            timestamp = findtext(point, 'Time')
            AltitudeMeters = float(findtext(point, 'AltitudeMeters'))
            DistanceMeters = float(findtext(point, 'DistanceMeters'))

            LatitudeDegrees = float(findtext(point, 'Position/LatitudeDegrees'))
            LongitudeDegrees = float(findtext(point, 'Position/LongitudeDegrees'))

            datalist.append((idval,timestamp,AltitudeMeters,DistanceMeters,LatitudeDegrees,LongitudeDegrees))

    #--------------------------------------------------------------------------------------------------
    #set counters as global variables
    distanceCounter = 0.0
    timeCounter = datetime.strptime(str("0.0"), "%S.%f")
    timeCounterSecs = 0
    #--------------------------------------------------------------------------------------------------

    #using Fiona, create a new shapefile and then populate it with data from the tcx file
    with fiona.open(outpath+outShape, 'w', driver='ESRI Shapefile',crs = crs, schema = schema) as c:
        for i in range(len(datalist)):
            if i < (len(datalist))-1:
                idvalList = datalist[i][0]
                timestampList = datalist[i][1]
                timestampList2 = datalist[i+1][1]
                AltitudeMetersList = datalist[i][2]
                DistanceMetersList  = datalist[i][3]

                #set coordinates for first point
                LatitudeDegreesList = datalist[i][4]
                LongitudeDegreesList = datalist[i][5]

                #set coordinates for next point
                LatitudeDegrees2List = datalist[i+1][4]
                LongitudeDegrees2List = datalist[i+1][5]

                #build shapely point
                latlonPoint = Point([LongitudeDegreesList,LatitudeDegreesList])

                #generate Shapely Points
                Point1 = Point(LongitudeDegreesList,LatitudeDegreesList)
                Point2 = Point(LongitudeDegrees2List,LatitudeDegrees2List)

                timeHolder1 = (timestampList.split("T")[1]).replace("Z","")
                timeHolder2 = (timestampList2.split("T")[1]).replace("Z","")

                #Set timestamps - no need to worry about the dates, since all runs take place in the same day
                if len(datalist[i][1]) == 8:
                    timestep1 = datetime.strptime(timeHolder1,'%H:%M:%S')
                else:
                    timestep1 = datetime.strptime(timeHolder1,'%H:%M:%S.%f')

                if len(datalist[i+1][1]) == 8:
                    timestep2 = datetime.strptime(timeHolder2,'%H:%M:%S')

                else:
                    timestep2 = datetime.strptime(timeHolder2,'%H:%M:%S.%f')

                #fine time difference between the two steps
                timedif = timestep2-timestep1

                #using pyproj, calculate geodesic distance
                distance = geod.inv(Point1.x, Point1.y, Point2.x, Point2.y)

                #Calculate distance between points
                distancebtwPoints = round(float(distance[2]),2)

                #Calculate time between points
                timebtwnPoints = round(float(timedif.total_seconds()),2)

                if abs(timebtwnPoints) >=86000:
                    timebtwnPoints = round(float(timebtwnPoints+86400),2)

                timebtwnPoints_time = datetime.strptime(str(abs(timebtwnPoints)), "%S.%f")

                #calculate speed - meters per second
                speed = timebtwnPoints*distancebtwPoints

                #calculate cumulative distance - in meters
                distanceCounter = round((distanceCounter+distancebtwPoints),4)
                distanceCounterFeet = round(((distanceCounter+distancebtwPoints)*3.28084),4)
                distanceCounterMiles = round((distanceCounterFeet/5280),4)

                #calculate cumlative time- in seconds
                timeCounter = timeCounter + timedelta(seconds=(timebtwnPoints))

                timeCounterSecs = timeCounterSecs+timebtwnPoints

                #set time and distance flags - based on quarter miles
                if (round((distanceCounterMiles),2)%0.2500/0.25 == 0.0) & (distanceCounterMiles >= 0.25):
                    SplitFlagDist = round((distanceCounterMiles),2)
                    SplitFlagTime = datetime.time(timeCounter)
                    finalSplitFlagTime = str(datetime.time(timeCounter))
                else:
                    SplitFlagDist = 0
                    SplitFlagTime = 0
                    finalSplitFlagTime = '0'

                #build linestring
                linestring = LineString([Point1,Point2])

                #set final variable
                finaldistancebtwPoints = round(distancebtwPoints,2)
                finalSpeed = round(speed,2)
                finaldistanceCounter = round(distanceCounter,2)
                finaldistanceCounterFeet = round(distanceCounterFeet,2)
                finaldistanceCounterMiles = round(distanceCounterMiles,2)
                finaltimeCounter = str(datetime.time(timeCounter))
                finalSplitFlagDist = round(SplitFlagDist,2)

                # Write a new Shapefile
                c.write({
                        'geometry': mapping(linestring),
                        'properties': {'id': idvalList,'distMeters':finaldistancebtwPoints,'MpS':finalSpeed,'TtlMtrs':finaldistanceCounter,'TtlFt':finaldistanceCounterFeet,'TtlMile':finaldistanceCounterMiles,'TtlTime':finaltimeCounter, 'FlagDist':finalSplitFlagDist,'FlagTime':finalSplitFlagTime, },
                        })

    outpath = ""
    outShape = ""
    c.close()
    print ("    Extraction Complete")
    print()
print('Script Complete')


text:
import copy

case_data_dict = {
    "category": u"blah blah",
    "facts": {
        "is_you_or_your_partner_over_60": False,
        "on_passported_benefits": False,
        "on_nass_benefits": False,
        "has_partner": False,
        "is_partner_opponent": False,
        "dependants_young": 0,
        "dependants_old": 0,
    },
    "you": {
        "income": {
            "earnings": 0,
            "self_employment_drawings": 0,
            "benefits": 0,
            "tax_credits": 0,
            "child_benefits": 0,
            "maintenance_received": 0,
            "pension": 0,
            "other_income": 0,
            "self_employed": False,
        },
        "savings": {"bank_balance": 0, "investment_balance": 0, "credit_balance": 0, "asset_balance": 0},
        "deductions": {
            "income_tax": 0,
            "national_insurance": 0,
            "maintenance": 0,
            "mortgage": 0,
            "rent": 0,
            "childcare": 0,
            "criminal_legalaid_contributions": 0,
        },
    },
    "property_data": [],
    # 'property_data': [(22, 0, 100)],
}

def get_default_case_data(**kwargs):
    """
    gives default case_data with each kwarg
    overridden, use __ to access nested dictionaries
    e.g. you__income__earnings

    :param kwargs: things to overwrite in the default case_data
    :return: CaseData object with default values
    """
    defaults = copy.deepcopy(case_data_dict)
    if len(kwargs):
        keys_vals = sorted([(kw.split("__"), v) for kw, v in kwargs.items()], key=lambda x: len(x[0]))
        for (k, v) in keys_vals:
            level = defaults
            for i in range(0, len(k)):
                if k[0 : i + 1] == k:
                    level[k[i]] = v
                else:
                    new_level = level.get(k[i])
                    if new_level is None and i != len(k):
                        level[k[i]] = {}
                    level = level[k[i]]

    return defaults


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.PooledObjects;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static partial class IParameterSymbolExtensions
    {
        public static IParameterSymbol RenameParameter(this IParameterSymbol parameter, string parameterName)
        {
            return parameter.Name == parameterName
                ? parameter
                : CodeGenerationSymbolFactory.CreateParameterSymbol(
                        parameter.GetAttributes(),
                        parameter.RefKind,
                        parameter.IsParams,
                        parameter.Type,
                        parameterName,
                        parameter.IsOptional,
                        parameter.HasExplicitDefaultValue,
                        parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null);
        }

        public static IParameterSymbol WithAttributes(this IParameterSymbol parameter, ImmutableArray<AttributeData> attributes)
        {
            return parameter.GetAttributes() == attributes
                ? parameter
                : CodeGenerationSymbolFactory.CreateParameterSymbol(
                        attributes,
                        parameter.RefKind,
                        parameter.IsParams,
                        parameter.Type,
                        parameter.Name,
                        parameter.IsOptional,
                        parameter.HasExplicitDefaultValue,
                        parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null);
        }

        public static ImmutableArray<IParameterSymbol> RenameParameters(this IList<IParameterSymbol> parameters, ImmutableArray<string> parameterNames)
        {
            var result = ArrayBuilder<IParameterSymbol>.GetInstance();
            for (var i = 0; i < parameterNames.Length; i++)
            {
                result.Add(parameters[i].RenameParameter(parameterNames[i]));
            }

            return result.ToImmutableAndFree();
        }

        public static IPropertySymbol? GetAssociatedSynthesizedRecordProperty(this IParameterSymbol parameter, CancellationToken cancellationToken)
        {
            if (parameter is
                {
                    DeclaringSyntaxReferences.Length: > 0,
                    ContainingSymbol: IMethodSymbol
                    {
                        MethodKind: MethodKind.Constructor,
                        DeclaringSyntaxReferences.Length: > 0,
                        ContainingType: { IsRecord: true } containingType,
                    } constructor,
                })
            {
                // ok, we have a record constructor.  This might be the primary constructor or not.
                var parameterSyntax = parameter.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken);
                var constructorSyntax = constructor.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken);
                if (containingType.DeclaringSyntaxReferences.Any(static (r, arg) => r.GetSyntax(arg.cancellationToken) == arg.constructorSyntax, (constructorSyntax, cancellationToken)))
                {
                    // this was a primary constructor. see if we can map this parameter to a corresponding synthesized property
                    foreach (var member in containingType.GetMembers(parameter.Name))
                    {
                        if (member is IPropertySymbol { DeclaringSyntaxReferences.Length: > 0 } property &&
                            property.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken) == parameterSyntax)
                        {
                            return property;
                        }
                    }
                }
            }

            return null;
        }
    }
}


text:
`PuGo` 0.10.0 **Beta** is released. There are many major changes:

## TOML support

`PuGo` support `TOML` to define meta and front-matter. And now, `PuGo` converts all default data to TOML instead of INI. But INI is continuing supporting.

You can read the new default `meta.toml` to learn about the TOML format.

<!--more-->

## International

`PuGo` add language files supports in `source/lang` directory. The default language files contains basic translated values for site. Language files support TOML and INI format.

Read [Languages](/en/docs/cnt/i18n.html) to learn how to write language file.

Then the global translation tool is added in template render.

Read [International](/en/docs/tpl/i18n.html) to use `{{.I18n}}`.

## Deploy to Cloud Storage

`deploy` command add [AWS S3](https://aws.amazon.com/s3/) and [Qiniu](http://www.qiniu.com/) method. In cloud storage service, you can upload static files to serve public, and bind your domain to the cloud bucket. So just like running static website.

Read [AWS S3 and Qiniu](/en/docs/deploy/cloud.html) to try how to deploy.

## Upgrade Changes

- `Comment` setting changes:

```toml
; comment settings
[comment.disqus]
site = your-site
```

Change to:

```toml
; comment settings
[comment]
disqus = your-site
```

- Template changes:

Some data objects and functions are changed. You need update your template in many cases.

Read this [issue](https://github.com/go-xiaohei/pugo/issues/20) to learn details.

- `Meta` data:

Now you **must** add an author in meta data. Read [guide](en/guide/create-new-site) to get the data struct of author.

- Command `build` flag value changes:

`pugo build --theme="default"` changes to `pugo build --theme="theme/default"`. You need set full relative path to refer to theme.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Testing the Mobilization Filter</title>
<meta name="robots" content="index, nofollow"/>
<meta name="description" content="This page is for testing the mobilization filter […]"/>
<meta name="viewport" content="width=100px;"/>
<link rel="stylesheet" href="http://test.com/not-a-valid-stylesheet.css" type="text/css" media="screen, projection"/>

<link rel="stylesheet" href="http://anothersite.com/style.css" type="text/css" media="screen, projection"/>

<link media="screen, projection" type="text/css" href="http://content.site.com/not-valid.css" rel="stylesheet"/>

Home

About

Articles

RSS

Mobilize all the Things

Foobar

      Way Cool

first

second

third

      Mondo
      Outrageous
      Funky

      <form action="http://test.com/form/" method="get">

Months

            <select name="archive">
              <option value="">Select Month</option>
              <option value='http://test.com/m=apr'>April</option>
              <option value='http://test.com/m=may'>May</option>
              <option value='http://test.com/m=jun'>June</option>
            </select>

Categories

            <select name='cat' id='cat'>
              <option value="">Select Category</option>
              <option value='http://test.com/c=gnarly'>Gnarly</option>
              <option value='http://test.com/c=tubular'>Tubular</option>
              <option value='http://test.com/c=groovy'>Awesome</option>
            </select>

      </form>

Isn't Mobilization Cool!?

              Foobar

              2014-01-01

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur mi est, pulvinar id euismod non, aliquam non dui.

              Quisque vehicula luctus magna vitae lobortis. Suspendisse lacinia enim nisl. In id euismod augue, at consequat justo
              vestibulum mollis porta leo sed placerat. Aenean consectetur
              tristique dolor vel interdum. Fusce blandit blandit dolor non dignissim.

Vivamus vel odio gravida felis malesuada luctus. Quisque sit amet eros ipsum. Nunc id enim non justo lobortis gravida. Aenean
              hendrerit mollis velit, eget sollicitudin magna malesuada porttitor. Nam molestie lorem enim, sit amet imperdiet odio dapibus eu.
              Phasellus nec feugiat sem. Etiam elit ligula, tincidunt lobortis sodales nec, laoreet in orci.

Vivamus dapibus dictum neque et adipiscing. Suspendisse sit amet purus lacinia, feugiat turpis eget, viverra libero.

// my first program in C++
#include <iostream>

int main()
{
  std::cout << "Hello World!";
}

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc eu turpis lorem.

Vestibulum ut justo nulla. Sed condimentum nunc ante, vestibulum mollis
              eget convallis nibh sodales eu. Praesent eget eleifend mi, ut ullamcorper justo.

Nunc eu turpis lorem

Nunc ut pulvinar turpis. In lacinia arcu eget augue lacinia, et consectetur quam interdum.

Aenean nec lacus ac sapien ultrices placerat non ac sem.

Aenean nec lacus ac sapien ultrices placerat non ac sem. Quisque accumsan porta tortor semper egestas.

    Nulla ac elit sed urna molestie iaculis. Morbi posuere ac libero in fringilla.


text:
var moment = require('../../moment');

exports.is_moment = {
    "is moment object": function (test) {
        test.expect(13);

        var MyObj = function () {},
            extend = function (a, b) {
                var i;
                for (i in b) {
                    a[i] = b[i];
                }
                return a;
            };
        MyObj.prototype.toDate = function () {
            return new Date();
        };

        test.ok(moment.isMoment(moment()), 'simple moment object');
        test.ok(moment.isMoment(moment('invalid date')), 'invalid moment object');
        test.ok(moment.isMoment(extend({}, moment())), 'externally cloned moments are moments');
        test.ok(moment.isMoment(extend({}, moment.utc())), 'externally cloned utc moments are moments');

        test.ok(!moment.isMoment(new MyObj()), 'myObj is not moment object');
        test.ok(!moment.isMoment(moment), 'moment function is not moment object');
        test.ok(!moment.isMoment(new Date()), 'date object is not moment object');
        test.ok(!moment.isMoment(Object), 'Object is not moment object');
        test.ok(!moment.isMoment('foo'), 'string is not moment object');
        test.ok(!moment.isMoment(1), 'number is not moment object');
        test.ok(!moment.isMoment(NaN), 'NaN is not moment object');
        test.ok(!moment.isMoment(null), 'null is not moment object');
        test.ok(!moment.isMoment(undefined), 'undefined is not moment object');

        test.done();
    }
};


text:
package fi.markoa.tfb.servlet3;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;

import java.util.List;

public interface MessageDAO {
  void init(ListeningExecutorService executorService);
  ListenableFuture<World> read(int id);
  ListenableFuture<List<World>> read(List<Integer> ids);
  ListenableFuture<Void> update(List<World> worlds);
  void destroy();
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MaterialWinforms.Controls.Settings
{
    public partial class MaterialThemeSettings : MaterialUserControl
    {
        private MaterialForm _BaseForm;
        private MaterialSettings _Parent;
        private bool Ignore;
        private ColorSchemePresetCollection Presets;
        public MaterialThemeSettings(MaterialForm pBaseForm, MaterialSettings pSettings)
        {
            InitializeComponent();
            _Parent = pSettings;
            _BaseForm = pBaseForm;
            tgl_Theme.Checked = SkinManager.Theme == MaterialSkinManager.Themes.DARK;
            Ignore = tgl_Theme.Checked;
            foreach (ColorSchemePreset objPrest in SkinManager.ColorSchemes.List())
            {
                ThemePreview objPreview = new ThemePreview(objPrest);
                objPreview.Click += objPreview_Click;
                flowLayoutPanel1.Controls.Add(objPreview);
            }
            Bitmap bmp = new Bitmap(materialFloatingActionButton1.Width, materialFloatingActionButton1.Height);
            Graphics g = Graphics.FromImage(bmp);
            Pen p = new Pen(Brushes.White, 6);
            g.DrawLine(p, new Point(0, bmp.Height / 2), new Point(bmp.Width, bmp.Height / 2));
            g.DrawLine(p, new Point(bmp.Width / 2, 0), new Point(bmp.Width / 2, bmp.Height));
            materialFloatingActionButton1.Icon = bmp;
        }

        void objPreview_Click(object sender, EventArgs e)
        {
            ThemePreview objPreview =(ThemePreview) sender;

            Point OverlayOrigin = new Point();
            OverlayOrigin = Cursor.Position;
            ColorOverlay objOverlay = new ColorOverlay(OverlayOrigin,objPreview.getColorSchemePreset(), _BaseForm,_Parent);
            objOverlay.FormClosed += objOverlay_FormClosed;
            objOverlay.Show();

        }

        void objOverlay_FormClosed(object sender, FormClosedEventArgs e)
        {
            tgl_Theme.Focus();
        }

        private void tgl_Theme_onAnimationFinished()
        {
            if (Ignore)
            {
                Ignore = false;
                return;
            }
            Point OverlayOrigin = new Point();
            OverlayOrigin.X = tgl_Theme.Checked ? tgl_Theme.Right - tgl_Theme.Height / 2 : tgl_Theme.Left + tgl_Theme.Height / 2;
            OverlayOrigin.Y = tgl_Theme.Location.Y + tgl_Theme.Height / 3;
            ColorOverlay objOverlay = new ColorOverlay(PointToScreen(OverlayOrigin), (tgl_Theme.Checked ? MaterialSkinManager.Themes.DARK : MaterialSkinManager.Themes.LIGHT), _BaseForm,_Parent);
            objOverlay.FormClosed += objOverlay_FormClosed;
            objOverlay.Show();
        }

        private void materialFloatingActionButton1_Click(object sender, EventArgs e)
        {
            Point OverlayOrigin = new Point();
            OverlayOrigin = Cursor.Position;
            SchemeCreator objScheme = new SchemeCreator(OverlayOrigin, _BaseForm);
            objScheme.FormClosed += newColorScheme;
            objScheme.Show();
        }

        private void newColorScheme(object sender, FormClosedEventArgs e)

        {

            flowLayoutPanel1.Controls.Clear();
            foreach (ColorSchemePreset objPrest in SkinManager.ColorSchemes.List())
            {
                ThemePreview objPreview = new ThemePreview(objPrest);
                objPreview.Click += objPreview_Click;
                flowLayoutPanel1.Controls.Add(objPreview);
            }
        }
    }

     class ThemePreview : Control,IMaterialControl
    {
        [Browsable(false)]
        public int Depth { get; set; }
        [Browsable(false)]
        public MaterialSkinManager SkinManager { get { return MaterialSkinManager.Instance; } }
        [Browsable(false)]
        public MouseState MouseState { get; set; }

        private ColorSchemePreset PreviewPreset;
        private Rectangle TopDark,TopDefault,Fab;
        private SolidBrush PrimaryDark, Primary, Accent,Text;
        public ThemePreview(ColorSchemePreset SchemeToPreview)
        {
            PreviewPreset = SchemeToPreview;

            DoubleBuffered = true;
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            Size = new Size(200, 110);
            TopDark = new Rectangle(0, 0, 200, 20);
            TopDefault = new Rectangle(0, TopDark.Bottom, 200,60);
            Fab = new Rectangle(Width - 60, TopDefault.Bottom - 20, 40, 40);
            PrimaryDark = new SolidBrush(((int)PreviewPreset.DarkPrimaryColor).ToColor());
            Primary = new SolidBrush(((int)PreviewPreset.PrimaryColor).ToColor());
            Accent = new SolidBrush(((int)PreviewPreset.AccentColor).ToColor());
            Text = new SolidBrush(((int)PreviewPreset.TextShade).ToColor());
        }

        public ColorSchemePreset getColorSchemePreset()
        {
            return PreviewPreset;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            GraphicsPath objPath = new GraphicsPath();
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            g.Clear(SkinManager.GetApplicationBackgroundColor());
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.FillRectangle(PrimaryDark, TopDark);
            g.FillRectangle(Primary, TopDefault);
            DrawHelper.drawShadow(g, DrawHelper.CreateCircle(Fab.X-1, Fab.Y-1, 20), 2, Color.Black);
            g.FillEllipse(Accent, Fab);

            g.DrawString(
                PreviewPreset.Name,
                 SkinManager.ROBOTO_REGULAR_11,
                 Text, TopDefault);
            g.ResetClip();

        }

    }

}


text:
options="$*"
#if [ -z $options ] ; then options="-O";fi
../../bin/pyjsbuild --print-statements $options GWTCanvasDemo
../../bin/pyjsbuild --print-statements $options SVGCanvasDemo


text:
'use strict';

/**
* Test if a value is a string.
*
* @module @stdlib/assert/is-string
*
* @example
* var isString = require( '@stdlib/assert/is-string' );
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 5 );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isObject;
*
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 'beep' );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns false
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var main = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );

// MAIN //

setReadOnly( main, 'isPrimitive', isPrimitive );
setReadOnly( main, 'isObject', isObject );

// EXPORTS //

module.exports = main;


text:
import django

# Django 1.5 add support for custom auth user model
if django.VERSION >= (1, 5):
    from django.contrib.auth import get_user_model
    User = get_user_model()
else:
    try:
        from django.contrib.auth.models import User
    except ImportError:
        raise ImportError(u"User model is not to be found.")

# location of patterns, url, include changes in 1.4 onwards
try:
    from django.conf.urls import patterns, url, include
except:
    from django.conf.urls.defaults import patterns, url, include


text:
/*
 * CLOUD API
 *
 * IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool.    Both methods employ consistent concepts and features, deliver similar power and flexibility, and can be used to perform a multitude of management tasks, including adding servers, volumes, configuring networks, and so on.
 *
 * API version: 6.0
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package ionoscloud

import (
	"encoding/json"
)

// BackupUnit struct for BackupUnit
type BackupUnit struct {
	// The resource's unique identifier.
	Id *string `json:"id,omitempty"`
	// The type of object that has been created.
	Type *string `json:"type,omitempty"`
	// URL to the object representation (absolute path).
	Href       *string                    `json:"href,omitempty"`
	Metadata   *DatacenterElementMetadata `json:"metadata,omitempty"`
	Properties *BackupUnitProperties      `json:"properties"`
}

// NewBackupUnit instantiates a new BackupUnit object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewBackupUnit(properties BackupUnitProperties) *BackupUnit {
	this := BackupUnit{}

	this.Properties = &properties

	return &this
}

// NewBackupUnitWithDefaults instantiates a new BackupUnit object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewBackupUnitWithDefaults() *BackupUnit {
	this := BackupUnit{}
	return &this
}

// GetId returns the Id field value
// If the value is explicit nil, the zero value for string will be returned
func (o *BackupUnit) GetId() *string {
	if o == nil {
		return nil
	}

	return o.Id

}

// GetIdOk returns a tuple with the Id field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *BackupUnit) GetIdOk() (*string, bool) {
	if o == nil {
		return nil, false
	}

	return o.Id, true
}

// SetId sets field value
func (o *BackupUnit) SetId(v string) {

	o.Id = &v

}

// HasId returns a boolean if a field has been set.
func (o *BackupUnit) HasId() bool {
	if o != nil && o.Id != nil {
		return true
	}

	return false
}

// GetType returns the Type field value
// If the value is explicit nil, the zero value for string will be returned
func (o *BackupUnit) GetType() *string {
	if o == nil {
		return nil
	}

	return o.Type

}

// GetTypeOk returns a tuple with the Type field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *BackupUnit) GetTypeOk() (*string, bool) {
	if o == nil {
		return nil, false
	}

	return o.Type, true
}

// SetType sets field value
func (o *BackupUnit) SetType(v string) {

	o.Type = &v

}

// HasType returns a boolean if a field has been set.
func (o *BackupUnit) HasType() bool {
	if o != nil && o.Type != nil {
		return true
	}

	return false
}

// GetHref returns the Href field value
// If the value is explicit nil, the zero value for string will be returned
func (o *BackupUnit) GetHref() *string {
	if o == nil {
		return nil
	}

	return o.Href

}

// GetHrefOk returns a tuple with the Href field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *BackupUnit) GetHrefOk() (*string, bool) {
	if o == nil {
		return nil, false
	}

	return o.Href, true
}

// SetHref sets field value
func (o *BackupUnit) SetHref(v string) {

	o.Href = &v

}

// HasHref returns a boolean if a field has been set.
func (o *BackupUnit) HasHref() bool {
	if o != nil && o.Href != nil {
		return true
	}

	return false
}

// GetMetadata returns the Metadata field value
// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned
func (o *BackupUnit) GetMetadata() *DatacenterElementMetadata {
	if o == nil {
		return nil
	}

	return o.Metadata

}

// GetMetadataOk returns a tuple with the Metadata field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *BackupUnit) GetMetadataOk() (*DatacenterElementMetadata, bool) {
	if o == nil {
		return nil, false
	}

	return o.Metadata, true
}

// SetMetadata sets field value
func (o *BackupUnit) SetMetadata(v DatacenterElementMetadata) {

	o.Metadata = &v

}

// HasMetadata returns a boolean if a field has been set.
func (o *BackupUnit) HasMetadata() bool {
	if o != nil && o.Metadata != nil {
		return true
	}

	return false
}

// GetProperties returns the Properties field value
// If the value is explicit nil, the zero value for BackupUnitProperties will be returned
func (o *BackupUnit) GetProperties() *BackupUnitProperties {
	if o == nil {
		return nil
	}

	return o.Properties

}

// GetPropertiesOk returns a tuple with the Properties field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *BackupUnit) GetPropertiesOk() (*BackupUnitProperties, bool) {
	if o == nil {
		return nil, false
	}

	return o.Properties, true
}

// SetProperties sets field value
func (o *BackupUnit) SetProperties(v BackupUnitProperties) {

	o.Properties = &v

}

// HasProperties returns a boolean if a field has been set.
func (o *BackupUnit) HasProperties() bool {
	if o != nil && o.Properties != nil {
		return true
	}

	return false
}

func (o BackupUnit) MarshalJSON() ([]byte, error) {
	toSerialize := map[string]interface{}{}
	if o.Id != nil {
		toSerialize["id"] = o.Id
	}
	if o.Type != nil {
		toSerialize["type"] = o.Type
	}
	if o.Href != nil {
		toSerialize["href"] = o.Href
	}
	if o.Metadata != nil {
		toSerialize["metadata"] = o.Metadata
	}
	if o.Properties != nil {
		toSerialize["properties"] = o.Properties
	}
	return json.Marshal(toSerialize)
}

type NullableBackupUnit struct {
	value *BackupUnit
	isSet bool
}

func (v NullableBackupUnit) Get() *BackupUnit {
	return v.value
}

func (v *NullableBackupUnit) Set(val *BackupUnit) {
	v.value = val
	v.isSet = true
}

func (v NullableBackupUnit) IsSet() bool {
	return v.isSet
}

func (v *NullableBackupUnit) Unset() {
	v.value = nil
	v.isSet = false
}

func NewNullableBackupUnit(val *BackupUnit) *NullableBackupUnit {
	return &NullableBackupUnit{value: val, isSet: true}
}

func (v NullableBackupUnit) MarshalJSON() ([]byte, error) {
	return json.Marshal(v.value)
}

func (v *NullableBackupUnit) UnmarshalJSON(src []byte) error {
	v.isSet = true
	return json.Unmarshal(src, &v.value)
}


text:
The cookbook is simply a set of LWRPs that you can use in your own cookbook. A simple example follows.

    psql_user "myuser" do
      host node['fqdn']
      port node['postgresql']['config']['port']
      admin_username 'postgres'
      admin_password node['postgresql']['password']['postgres']
      password 'secret'
    end

    psql_database "mydatabase" do
      host node['fqdn']
      port node['postgresql']['config']['port']
      admin_username 'postgres'
      admin_password node['postgresql']['password']['postgres']
      owner 'myuser'
      template 'template_postgis'
      encoding 'DEFAULT'
      tablespace 'MyTablespace'
      collation 'fr_FR'
      connection_limit -1
    end

    psql_permission "myuser@mydatabase => all" do
      host node['fqdn']
      port node['postgresql']['config']['port']
      admin_username 'postgres'
      admin_password node['postgresql']['password']['postgres']
      username 'myuser'
      database 'mydatabase'
      permissions ['ALL']
    end


text:
module Refinery
  module Core
    class Engine < ::Rails::Engine
      include Refinery::Engine

      isolate_namespace Refinery
      engine_name :refinery

      class << self
        # Register all decorators from app/decorators/ and registered plugins' paths.
        def register_decorators!
          require 'decorators'
          Decorators.register! Rails.root, Refinery::Plugins.registered.pathnames
        end

        # Performs the Refinery inclusion process which extends the currently loaded Rails
        # applications with Refinery's controllers and helpers. The process is wrapped by
        # a before_inclusion and after_inclusion step that calls procs registered by the
        # Refinery::Engine#before_inclusion and Refinery::Engine#after_inclusion class methods
        def refinery_inclusion!
          before_inclusion_procs.each(&:call)

          Refinery.include_once(::ApplicationController, Refinery::ApplicationController)
          ::ApplicationController.send :helper, Refinery::Core::Engine.helpers

          after_inclusion_procs.each(&:call)
        end
      end

      config.autoload_paths += %W( #{config.root}/lib )

      # Include the refinery controllers and helpers dynamically
      config.to_prepare &method(:refinery_inclusion!).to_proc

      after_inclusion &method(:register_decorators!).to_proc

      # Wrap errors in spans
      config.to_prepare do
        ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
          "#{html_tag}".html_safe
        end
      end

      initializer "refinery.will_paginate" do
        WillPaginate.per_page = 20
      end

      initializer "register refinery_core plugin" do
        Refinery::Plugin.register do |plugin|
          plugin.pathname = root
          plugin.name = 'refinery_core'
          plugin.class_name = 'RefineryEngine'
          plugin.hide_from_menu = true
          plugin.always_allow_access = true
          plugin.menu_match = /refinery\/(refinery_)?core$/
        end
      end

      initializer "register refinery_dialogs plugin" do
        Refinery::Plugin.register do |plugin|
          plugin.pathname = root
          plugin.name = 'refinery_dialogs'
          plugin.hide_from_menu = true
          plugin.always_allow_access = true
          plugin.menu_match = /refinery\/(refinery_)?dialogs/
        end
      end

      initializer "refinery.routes", :after => :set_routes_reloader_hook do |app|
        Refinery::Core::Engine.routes.append do
          get '/refinery/*path' => 'admin/base#error_404'
        end
      end

      initializer "refinery.autoload_paths" do |app|
        app.config.autoload_paths += [
          Rails.root.join('app', 'presenters'),
          Rails.root.join('vendor', '**', '**', 'app', 'presenters'),
          Refinery.roots.map{|r| r.join('**', 'app', 'presenters')}
        ].flatten
      end

      # set the manifests and assets to be precompiled
      initializer "refinery.assets.precompile" do |app|
        app.config.assets.precompile += [
          "refinery/*",
          "refinery/icons/*",
          "wymeditor/lang/*",
          "wymeditor/skins/refinery/*",
          "wymeditor/skins/refinery/**/*",
          "modernizr-min.js",
          "admin.js"
        ]
      end

      # active model fields which may contain sensitive data to filter
      initializer "refinery.params.filter" do |app|
        app.config.filter_parameters += [:password, :password_confirmation]
      end

      initializer "refinery.encoding" do |app|
        app.config.encoding = 'utf-8'
      end

      initializer "refinery.memory_store" do |app|
        app.config.cache_store = :memory_store
      end

      config.after_initialize do
        Refinery.register_extension(Refinery::Core)
      end
    end
  end
end


text:
"use strict";

var vows = require('vows');
var assert = require('assert');
var URL = require('../../src/URL.js');

/* */
vows.describe('Testing URL').addBatch({
	"URL": {
		topic: function() { return URL; },
		'is function': function(o) { assert.isFunction(o); },
		'has .create()': function(o) { assert.isFunction(o.create); },
		'has .parse()': function(o) { assert.isFunction(o.parse); },
		'has .format()': function(o) { assert.isFunction(o.format); },
		'has .prototype.toString()': function(o) { assert.isFunction(o.prototype.toString); },
		'has .prototype.toJSON()': function(o) { assert.isFunction(o.prototype.toJSON); },
		'has .prototype.resolve()': function(o) { assert.isFunction(o.prototype.resolve); },
		'has .prototype.parse()': function(o) { assert.isFunction(o.prototype.parse); },
    },
	"Testing URL constuctor": {
		"new URL() throws TypeError": function() { assert.throws(function () { new URL(); }, TypeError); },
		"new URL([]) throws TypeError": function() { assert.throws(function () { new URL([]); }, TypeError); },
		"new URL({}) throws TypeError": function() { assert.throws(function () { new URL({}); }, TypeError); },
		"new URL(1234) throws TypeError": function() { assert.throws(function () { new URL(1234); }, TypeError); },
		"new URL(null) throws TypeError": function() { assert.throws(function () { new URL(null); }, TypeError); },
		"new URL(true) throws TypeError": function() { assert.throws(function () { new URL(true); }, TypeError); },
		"new URL('http://www.jhh.me/foo/bar') does not throw Error": function() { assert.doesNotThrow(function () { new URL('http://www.jhh.me/foo/bar'); }, Error); },
		"URL(URL('http://www.jhh.me/foo/bar')) does not throw Error": function() { assert.doesNotThrow(function () { URL(URL('http://www.jhh.me/foo/bar')); }, Error); },
		"URL(new URL('http://www.jhh.me/foo/bar')) does not throw Error": function() { assert.doesNotThrow(function () { URL(new URL('http://www.jhh.me/foo/bar')); }, Error); },
		"new URL(URL('http://www.jhh.me/foo/bar')) does not throw Error": function() { assert.doesNotThrow(function () { new URL(URL('http://www.jhh.me/foo/bar')); }, Error); },
		"new URL(new URL('http://www.jhh.me/foo/bar')) does not throw Error": function() { assert.doesNotThrow(function () { new URL(new URL('http://www.jhh.me/foo/bar')); }, Error); },
		"URL('http://www.jhh.me/foo/bar').value equals": function() { assert.equal( URL('http://www.jhh.me/foo/bar').value, 'http://www.jhh.me/foo/bar'); },
	},
	"new URL('http://www.jhh.me/foo/bar')": {
		topic: function() { return new URL('http://www.jhh.me/foo/bar'); },
		'is instance of URL': function(o) { assert.instanceOf(o, URL); },
		'is immutable': function(o) { assert.throws(function () { o.foo = '/foo/bar'; assert.equal(o.foo, undefined);  }, TypeError); },
		'.value equals "http://www.jhh.me/foo/bar"': function(o) { assert.equal(o.value, 'http://www.jhh.me/foo/bar'); },
		'.value is immutable': function(o) { assert.throws(function () { o.value = '/foo/bar'; assert.equal(o.value, 'http://www.jhh.me/foo/bar');  }, TypeError); },
		'.toJSON() works': function(o) { assert.equal(o.toJSON(), 'http://www.jhh.me/foo/bar'); },
		'.toJSON() is immutable': function(o) { var foo = o.toJSON(); foo = '/foo/bar'; assert.equal(foo, '/foo/bar'); assert.equal(o.value, 'http://www.jhh.me/foo/bar'); },
		'.toString() works': function(o) { assert.equal(o.toString(), 'http://www.jhh.me/foo/bar'); },
		'.toString() is immutable': function(o) { var foo = o.toString(); foo = '/foo/bar'; assert.equal(foo, '/foo/bar'); assert.equal(o.value, 'http://www.jhh.me/foo/bar'); },
	},
	"URL(new URL('http://www.jhh.me/foo/bar'))": {
		topic: function() { return URL(new URL('http://www.jhh.me/foo/bar')); },
		'is instance of URL': function(o) { assert.instanceOf(o, URL); },
		'.value equals "http://www.jhh.me/foo/bar"': function(o) { assert.equal(o.value, 'http://www.jhh.me/foo/bar'); },
	},
	"new URL(new URL('http://www.jhh.me/foo/bar'))": {
		topic: function() { return new URL(new URL('http://www.jhh.me/foo/bar')); },
		'is instance of URL': function(o) { assert.instanceOf(o, URL); },
		'.value equals "http://www.jhh.me/foo/bar"': function(o) { assert.equal(o.value, 'http://www.jhh.me/foo/bar'); },
	},
	"Testing methods": {
		"URL('http://www.jhh.me').resolve('/foo/bar') works": function() { assert.equal( URL('http://www.jhh.me').resolve('/foo/bar').value, 'http://www.jhh.me/foo/bar' ); },
		"URL.format({'host':'example.com:80','protocol':'http:','pathname':'/resources/foo.html'}) works": function() {
			assert.equal( URL.format({'host':'example.com:80','protocol':'http:','pathname':'/resources/foo.html'}).value, 'http://example.com:80/resources/foo.html' ); },
	},
	"Testing manual parse": {
		topic: function() { return new URL('http://user:pass@host.com:8080/p/a/t/h?query=string#hash').parse(); },
		'is instance of URL': function(o) { assert.instanceOf(o, URL); },
		'key length is correct': function(o) { assert.lengthOf(Object.keys(o), 15); },
		'.formated === false': function(o) { assert.equal(o.formated, false); },
		'.parsed === true': function(o) { assert.equal(o.parsed, true); },
		'.slashes === true': function(o) { assert.equal(o.slashes, true); },
		'.href === "http://user:pass@host.com:8080/p/a/t/h?query=string#hash"': function(o) { assert.equal(o.href, 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'); },
		'.protocol === "http:"': function(o) { assert.equal(o.protocol, 'http:'); },
		'.host === "host.com:8080"': function(o) { assert.equal(o.host, 'host.com:8080'); },
		'.auth === "user:pass"': function(o) { assert.equal(o.auth, 'user:pass'); },
		'.hostname === "host.com"': function(o) { assert.equal(o.hostname, 'host.com'); },
		'.port === "8080"': function(o) { assert.equal(o.port, '8080'); },
		'.pathname === "/p/a/t/h"': function(o) { assert.equal(o.pathname, '/p/a/t/h'); },
		'.search === "?query=string"': function(o) { assert.equal(o.search, '?query=string'); },
		'.path === "/p/a/t/h?query=string"': function(o) { assert.equal(o.path, '/p/a/t/h?query=string'); },
		'.query === "query=string"': function(o) { assert.equal(o.query, 'query=string'); },
		'.hash === "#hash"': function(o) { assert.equal(o.hash, '#hash'); },
	},
	"Testing magic parse": {
		topic: function() { return new URL('http://user:pass@host.com:8080/p/a/t/h?query=string#hash'); },
		'is instance of URL': function(o) { assert.instanceOf(o, URL); },
		'key length is correct': function(o) { assert.lengthOf(Object.keys(o), 15); },
		'.formated === false': function(o) { assert.equal(o.formated, false); },
		'.parsed === false': function(o) { assert.equal(o.parsed, false); },
		'.slashes === true': function(o) { assert.equal(o.slashes, true); },
		'.href === "http://user:pass@host.com:8080/p/a/t/h?query=string#hash"': function(o) { assert.equal(o.href, 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'); },
		'.protocol === "http:"': function(o) { assert.equal(o.protocol, 'http:'); },
		'.host === "host.com:8080"': function(o) { assert.equal(o.host, 'host.com:8080'); },
		'.auth === "user:pass"': function(o) { assert.equal(o.auth, 'user:pass'); },
		'.hostname === "host.com"': function(o) { assert.equal(o.hostname, 'host.com'); },
		'.port === "8080"': function(o) { assert.equal(o.port, '8080'); },
		'.pathname === "/p/a/t/h"': function(o) { assert.equal(o.pathname, '/p/a/t/h'); },
		'.search === "?query=string"': function(o) { assert.equal(o.search, '?query=string'); },
		'.path === "/p/a/t/h?query=string"': function(o) { assert.equal(o.path, '/p/a/t/h?query=string'); },
		'.query === "query=string"': function(o) { assert.equal(o.query, 'query=string'); },
		'.hash === "#hash"': function(o) { assert.equal(o.hash, '#hash'); },
	},
}).export(module);

/* EOF */


text:
class TemplateURL;

using GUIDToTURLMap = std::map<std::string, const TemplateURL*>;

namespace search_engines_helper {

// Used to access the search engines within a particular sync profile.
TemplateURLService* GetServiceForBrowserContext(int profile_index);

// Used to access the search engines within the verifier sync profile.
TemplateURLService* GetVerifierService();

// Compared a single TemplateURLService for a given profile to the verifier.
// Retrns true iff their user-visible fields match.
bool ServiceMatchesVerifier(int profile_index);

// Returns true iff all TemplateURLServices match with the verifier.
bool AllServicesMatch();
bool AllServicesMatch(std::ostream* os);

// Builder class that by default infers all fields from |keyword| and allows
// overriding those default values.
class TemplateURLBuilder {
 public:
  explicit TemplateURLBuilder(const std::string& keyword);
  ~TemplateURLBuilder();

  TemplateURLData* data() { return &data_; }
  std::unique_ptr<TemplateURL> Build();

 private:
  TemplateURLData data_;
};

// Add a search engine based on a keyword to the service at index
// |profile_index| and the verifier if it is used.
void AddSearchEngine(int profile_index, const std::string& keyword);

// Retrieves a search engine from the service at index |profile_index| with
// original keyword |keyword| and changes its user-visible fields. Does the same
// to the verifier, if it is used.
void EditSearchEngine(int profile_index,
                      const std::string& keyword,
                      const std::u16string& short_name,
                      const std::string& new_keyword,
                      const std::string& url);

// Deletes a search engine from the service at index |profile_index| with
// |keyword|.
void DeleteSearchEngine(int profile_index, const std::string& keyword);

// Changes the search engine with |keyword| to be the new default for
// |profile_index|. Does the same to the verifier, if it is used.
void ChangeDefaultSearchProvider(int profile_index, const std::string& keyword);

// Returns true if the profile at |profile_index| has a search engine matching
// |keyword|.
bool HasSearchEngine(int profile_index, const std::string& keyword);

// Returns the keyword for the default search engine at |profile_index|.
std::string GetDefaultSearchEngineKeyword(int profile_index);

// Checker that blocks until all services have the same search engine data.
class SearchEnginesMatchChecker : public StatusChangeChecker,
                                  public TemplateURLServiceObserver {
 public:
  SearchEnginesMatchChecker();
  ~SearchEnginesMatchChecker() override;

  // StatusChangeChecker overrides.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // TemplateURLServiceObserver overrides.
  void OnTemplateURLServiceChanged() override;

 private:
  base::ScopedMultiSourceObservation<TemplateURLService,
                                     TemplateURLServiceObserver>
      observations_{this};
};

// Checker that blocks until |profile_index| has a search engine matching the
// search engine generated with |keyword|.
class HasSearchEngineChecker : public StatusChangeChecker,
                               public TemplateURLServiceObserver {
 public:
  HasSearchEngineChecker(int profile_index, const std::string& keyword);
  ~HasSearchEngineChecker() override;

  // StatusChangeChecker overrides.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // TemplateURLServiceObserver overrides.
  void OnTemplateURLServiceChanged() override;

 private:
  const raw_ptr<TemplateURLService> service_;
  const std::u16string keyword_;
  base::ScopedMultiSourceObservation<TemplateURLService,
                                     TemplateURLServiceObserver>
      observations_{this};
};

}  // namespace search_engines_helper

#endif  // CHROME_BROWSER_SYNC_TEST_INTEGRATION_SEARCH_ENGINES_HELPER_H_


text:
using System;

namespace Picums.Mvc.Navigation
{
	public sealed class AnonumousOnlyAttribute : Attribute
	{
	}
}


text:
// run-rustfix
#![deny(rust_2021_incompatible_closure_captures)]
//~^ NOTE: the lint level is defined here

use std::thread;

#[derive(Debug)]
struct Foo(i32);
impl Drop for Foo {
    fn drop(&mut self) {
        println!("{:?} dropped", self.0);
    }
}

/* Test Send Trait Migration */
struct SendPointer(*mut i32);
unsafe impl Send for SendPointer {}

fn test_send_trait() {
    let mut f = 10;
    let fptr = SendPointer(&mut f as *mut i32);
    thread::spawn(move || unsafe {
        //~^ ERROR: changes to closure capture
        //~| NOTE: in Rust 2018, this closure implements `Send`
        //~| NOTE: for more information, see
        //~| HELP: add a dummy let to cause `fptr` to be fully captured
        *fptr.0 = 20;
        //~^ NOTE: in Rust 2018, this closure captures all of `fptr`, but in Rust 2021, it will only capture `fptr.0`
    });
}

/* Test Sync Trait Migration */
struct CustomInt(*mut i32);
struct SyncPointer(CustomInt);
unsafe impl Sync for SyncPointer {}
unsafe impl Send for CustomInt {}

fn test_sync_trait() {
    let mut f = 10;
    let f = CustomInt(&mut f as *mut i32);
    let fptr = SyncPointer(f);
    thread::spawn(move || unsafe {
        //~^ ERROR: changes to closure capture
        //~| NOTE: in Rust 2018, this closure implements `Sync`
        //~| NOTE: in Rust 2018, this closure implements `Send`
        //~| NOTE: for more information, see
        //~| HELP: add a dummy let to cause `fptr` to be fully captured
        *fptr.0.0 = 20;
        //~^ NOTE: in Rust 2018, this closure captures all of `fptr`, but in Rust 2021, it will only capture `fptr.0.0`
    });
}

/* Test Clone Trait Migration */
struct S(Foo);
struct T(i32);

struct U(S, T);

impl Clone for U {
    fn clone(&self) -> Self {
        U(S(Foo(0)), T(0))
    }
}

fn test_clone_trait() {
    let f = U(S(Foo(0)), T(0));
    let c = || {
        //~^ ERROR: changes to closure capture in Rust 2021 will affect drop order and which traits the closure implements
        //~| NOTE: in Rust 2018, this closure implements `Clone`
        //~| NOTE: for more information, see
        //~| HELP: add a dummy let to cause `f` to be fully captured
        let f_1 = f.1;
        //~^ NOTE: in Rust 2018, this closure captures all of `f`, but in Rust 2021, it will only capture `f.1`
        println!("{:?}", f_1.0);
    };

    let c_clone = c.clone();

    c_clone();
}
//~^ NOTE: in Rust 2018, `f` is dropped here, but in Rust 2021, only `f.1` will be dropped here as part of the closure

fn main() {
    test_send_trait();
    test_sync_trait();
    test_clone_trait();
}