text:
var Immutable = require('immutable');
var SlideshowImage = require('SlideshowImage');
var Observable = require('Observable');
var $__0=    Immutable,List=$__0.List;

var EVENTS = [
  'ImageChanged'
];

  function SlideshowImageStore(images                          ) {"use strict";
    this.$SlideshowImageStore_index = 0;
    this.$SlideshowImageStore_images = new List(images);
    this['_observable'] = new Observable();
  }

  Object.defineProperty(SlideshowImageStore.prototype,"getImage",{writable:true,configurable:true,value:function()                 {"use strict";
    return this.$SlideshowImageStore_images.get(this.$SlideshowImageStore_index);
  }});

  Object.defineProperty(SlideshowImageStore.prototype,"nextImage",{writable:true,configurable:true,value:function()                      {"use strict";
    var index = this.$SlideshowImageStore_index + 1;
    if (index === this.$SlideshowImageStore_images.size) {
      index = 0;
    }
    this.$SlideshowImageStore_index = index;
    this.triggerImageChanged(
      this.$SlideshowImageStore_images.get(index),
      index
    );
    return this;
  }});

  Object.defineProperty(SlideshowImageStore.prototype,"previousImage",{writable:true,configurable:true,value:function()                      {"use strict";
    var index = this.$SlideshowImageStore_index - 1;
    if (index < 0) {
      index = this.$SlideshowImageStore_images.size - 1;
    }
    this.$SlideshowImageStore_index = index;
    this.triggerImageChanged(
      this.$SlideshowImageStore_images.get(index),
      index
    );
    return this;
  }});

Observable.withEventMethods(EVENTS, SlideshowImageStore);

module.exports = SlideshowImageStore;


text:
'use strict';
angular.module('uql.orgs')
  .controller('uqlOrgsPaperFullCtrl', ['$scope', 'UqlOrgsApplicationService', 'UqlTextService', 'UQL_CONFIG_ORGS', function ($scope, UqlOrgsApplicationService, UqlTextService, UQL_CONFIG_ORGS) {
    $scope.scopusUpdate = UqlTextService.formatDate(UQL_CONFIG_ORGS.scopusUpdate);
    $scope.espaceAttr = UQL_CONFIG_ORGS.espaceAttr;
    $scope.incitesAttr = UQL_CONFIG_ORGS.incitesAttr;
    $scope.scopusAttr = UQL_CONFIG_ORGS.scopusAttr;
  }])
  .directive('uqlOrgsPaperFull', ['UqlOrgsApplicationService', 'UQL_CONFIG_ORGS', function (UqlOrgsApplicationService, UQL_CONFIG_ORGS) {
    return {
      restrict: 'E',
      controller: 'uqlOrgsPaperFullCtrl',
      templateUrl: UQL_CONFIG_ORGS.viewsBaseUrl + '/partials/paper-full.html',
      scope: {
        paper: '='
      },
      link: function postLink(scope) {
        /*
         * http://stackoverflow.com/questions/822452/strip-html-from-text-javascript
         */
        function strip(html) {
          var tmp = document.createElement('DIV');
          tmp.innerHTML = html;
          return tmp.textContent || tmp.innerText || '';
        }

        /**
         * Takes the paper and reformats fields ready for display
         *
         * @param paper
         */
        function formatPaper(paper) {
          var returnVal = {};

          var scopusPaper = paper[0];
          var espacePaper = paper[1];

          returnVal.pid = espacePaper.id;
          returnVal.title = espacePaper.title_t;
          returnVal.citations = espacePaper.scopus_citation_count_i;
          returnVal.incites_citations = espacePaper.thomson_citation_count_i;
          returnVal.citation = strip(espacePaper.citation_t);
          returnVal.abstract = espacePaper.description_t;
          returnVal.doi = espacePaper.doi_t;

          if (angular.isObject(scopusPaper)) {
            for (var i in scopusPaper) {
              if (!returnVal.hasOwnProperty(i)) {
                returnVal[i] = scopusPaper[i];
              }
            }
            returnVal.showAsjcPercentiles = scopusPaper.citation_type_raw === 'cp' || scopusPaper.citation_type_raw === 're' || scopusPaper.citation_type_raw === 'ar';
            // this is done to make the incites data appear similar to the
            // asjc data, which is an array, for displaying in a graph
            if (scopusPaper.hasOwnProperty('incites_crown_index')) {
              returnVal.incites_crown_indices = [
                {'incites_crown_index': parseFloat(scopusPaper.incites_crown_index)}
              ];
            }
            if (scopusPaper.hasOwnProperty('incites_citation_impact')) {
              returnVal.incites_citation_impact = [
                {'incites_citation_impact': parseFloat(scopusPaper.incites_citation_impact)}
              ];
            }
          }

          returnVal.other_details = [
            {
              name: 'Published year',
              source: UQL_CONFIG_ORGS.espaceAttr,
              value: espacePaper.date_year_t + '' || 'N/A'
            },
            {
              name: 'Document type',
              source: UQL_CONFIG_ORGS.espaceAttr,
              value: espacePaper.subtype_t || 'N/A'
            },
            {
              name: 'Journal',
              source: UQL_CONFIG_ORGS.espaceAttr,
              value: espacePaper.journal_name_t || 'N/A'
            },
            {
              name: 'Journal Impact Factor',
              source: UQL_CONFIG_ORGS.incitesAttr,
              value: angular.isObject(scopusPaper) && scopusPaper.incites_impact && scopusPaper.incites_impact !== -1 ? scopusPaper.incites_impact + '' : 'Null'
            }
          ];

          returnVal.identifiers = [
            {
              name: 'eSpace PID',
              source: UQL_CONFIG_ORGS.espaceAttr,
              value: espacePaper.id ? '' + espacePaper.id + '' : 'N/A'
            },
            {
              name: 'Document DOI',
              source: UQL_CONFIG_ORGS.espaceAttr,
              value: espacePaper.doi_t || 'N/A'
            },
            {
              name: 'Scopus EID',
              source: UQL_CONFIG_ORGS.espaceAttr,
              value: espacePaper.scopus_id_t ? '' + espacePaper.scopus_id_t + '' : 'N/A'
            },
            {
              name: 'ISI LOC',
              source: UQL_CONFIG_ORGS.espaceAttr,
              value: espacePaper.isi_loc_t ? '' + espacePaper.isi_loc_t + '' : 'N/A'
            }
          ];

          return returnVal;
        }

        $('#citation-copy').click(function () {
          UqlOrgsApplicationService.selectText('citation');
        });

        scope.$watch('paper', function () {
          if (angular.isArray(scope.paper) && (scope.paper.length === 2)) {
            scope.details = formatPaper(scope.paper);
          }
        }, true);
      }
    };
  }]);

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="scaffolded-by" content="https://github.com/google/stagehand">
    <title>Party</title>
    <link rel="stylesheet" href="styles.css">

        <input id="input" name="precision" type="text">
        <input id="button" name="change" value="Set Precision" type="button">


text:
<!DOCTYPE html>
<html class="reftest-wait">
  <link rel='stylesheet' type='text/css' href='style.css'>
  <body onload="document.getElementById('i').checked = true;
                if (document.getElementById('i').mozMatchesSelector(':-moz-ui-invalid')) {
                  document.body.textContent='FAIL';
                } else {
                  document.body.textContent='SUCCESS';
                }
                document.documentElement.className='';">
    <input id='i' type='radio' required>
  </body>
</html>


text:
<?php

namespace Nathanmac\Utilities\Responder\Formats;

/**
 * Formatter Interface
 *
 * @package    Nathanmac\Utilities\Responder\Formats
 * @author     Nathan Macnamara <nathan.macnamara@outlook.com>
 * @license    https://github.com/nathanmac/Responder/blob/master/LICENSE.md  MIT
 */
interface FormatInterface
{

    /**
     * Generate Payload Data
     *
     * @param array  $payload
     * @param string $container
     *
     * @throws ResponderException
     *
     * @return string
     */
    public function generate($payload, $container = 'data');
}


text:
gridview_example
================

Simple Image Gallery
Varsha M Pathak
IMR Jalgaon
Grid View Application download from repository


text:
package com.denker.updater.display;

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JPanel;

public class UpdaterPanel extends JPanel
{
    private static UpdaterPanel instance;
    private final SplashPanel splashPanel;
    private final StatusPanel statusPanel;

    private UpdaterPanel()
    {
        super(new BorderLayout());
        setBackground(new Color(255, 255, 255, 0));

        splashPanel =   new SplashPanel();
        statusPanel =   new StatusPanel();

        add(splashPanel, BorderLayout.CENTER);
        add(statusPanel, BorderLayout.SOUTH);
    }

    public SplashPanel getSplashPanel()
    {
        return splashPanel;
    }

    public StatusPanel getStatusPanel()
    {
        return statusPanel;
    }

    public static UpdaterPanel getInstance()
    {
        if(instance == null) instance = new UpdaterPanel();
        return instance;
    }
}


text:
from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm
from django import forms
from django.utils.translation import ugettext as _
from django.contrib.auth import authenticate
from pretix.base.models import User

class AuthenticationForm(BaseAuthenticationForm):
    """
    The login form, providing an email and password field. The form already implements
    validation for correct user data.
    """
    email = forms.EmailField(label=_("Email address"), max_length=254)
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
    username = None

    error_messages = {
        'invalid_login': _("Please enter a correct e-mail address and password."),
        'inactive': _("This account is inactive.")
    }

    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        self.user_cache = None
        super(forms.Form, self).__init__(*args, **kwargs)

    def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')

        if email and password:
            self.user_cache = authenticate(identifier=email.lower(),
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login'
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

class GlobalRegistrationForm(forms.Form):
    error_messages = {
        'duplicate_email': _("You already registered with that e-mail address, please use the login form."),
        'pw_mismatch': _("Please enter the same password twice")
    }
    email = forms.EmailField(
        label=_('Email address'),
        required=True
    )
    password = forms.CharField(
        label=_('Password'),
        widget=forms.PasswordInput,
        required=True
    )
    password_repeat = forms.CharField(
        label=_('Repeat password'),
        widget=forms.PasswordInput
    )

    def clean(self):
        password1 = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password_repeat')

        if password1 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['pw_mismatch'],
                code='pw_mismatch',
            )

        return self.cleaned_data

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(identifier=email).exists():
            raise forms.ValidationError(
                self.error_messages['duplicate_email'],
                code='duplicate_email',
            )
        return email


text:
from __future__ import division, print_function

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

import TestSCons
import re
import time

_python_ = TestSCons._python_

test = TestSCons.TestSCons()

test.write('sleep_cat.py', """\
import sys
import time
time.sleep(int(sys.argv[1]))
fp = open(sys.argv[2], 'wb')
for arg in sys.argv[3:]:
    fp.write(open(arg, 'rb').read())
fp.close()
sys.exit(0)
""")

test.write('SConstruct', """
env = Environment(PYTHON = r'%(_python_)s',
                  SLEEP_CAT = r'sleep_cat.py',
                  CATCOM = '$PYTHON $SLEEP_CAT $SECONDS $TARGET $SOURCES',
                  SECONDS = ARGUMENTS.get('SLEEP', '0'))
f1 = env.Command('f1.out', 'f1.in', '$CATCOM')
f2 = env.Command('f2.out', 'f2.in', '$CATCOM')
f3 = env.Command('f3.out', 'f3.in', '$CATCOM')
f4 = env.Command('f4.out', 'f4.in', '$CATCOM')
env.Command('output', [f1, f2, f3, f4], '$CATCOM')
""" % locals())

test.write('f1.in', "f1.in\n")
test.write('f2.in', "f2.in\n")
test.write('f3.in', "f3.in\n")
test.write('f4.in', "f4.in\n")

expected_targets = ['f1.out', 'f2.out', 'f3.out', 'f4.out', 'output', '.']

# Before anything else, make sure we get valid --debug=time results
# when just running the help option.
test.run(arguments = "-h --debug=time")

def num(s, match):
    return float(re.search(match, s).group(1))

def within_tolerance(expected, actual, tolerance):
    return abs((expected-actual)/actual) <= tolerance

def get_total_time(stdout):
    return num(stdout, r'Total build time: (\d+\.\d+) seconds')

def get_sconscript_time(stdout):
    return num(stdout, r'Total SConscript file execution time: (\d+\.\d+) seconds')

def get_scons_time(stdout):
    return num(stdout, r'Total SCons execution time: (\d+\.\d+) seconds')

def get_command_time(stdout):
    return num(stdout, r'Total command execution time: (\d+\.\d+) seconds')

# Try to make our results a little more accurate and repeatable by
# measuring Python overhead executing a minimal file, and reading the
# scons.py script itself from disk so that it's already been cached.
test.write('pass.py', "pass\n")
test.read(test.program)

start_time = time.time()
test.run(program=TestSCons.python, arguments=test.workpath('pass.py'))
overhead = time.time() - start_time

start_time = time.time()
test.run(arguments = "-j1 --debug=time . SLEEP=0")
complete_time = time.time() - start_time

expected_total_time = complete_time - overhead

pattern = r'Command execution time: (.*): (\d+\.\d+) seconds'
targets = []
times = []
for target,time in re.findall(pattern, test.stdout()):
    targets.append(target)
    times.append(float(time))
expected_command_time = 0.0
for t in times:
    expected_command_time += t

stdout = test.stdout()

total_time      = get_total_time(stdout)
sconscript_time = get_sconscript_time(stdout)
scons_time      = get_scons_time(stdout)
command_time    = get_command_time(stdout)

failures = []
warnings = []

if  targets != expected_targets:
    failures.append("""\
Scons reported the targets of timing information as %(targets)s,
but the actual targets should have been %(expected_targets)s.
""" %locals())

if not within_tolerance(expected_command_time, command_time, 0.01):
    failures.append("""\
SCons -j1 reported a total command execution time of %(command_time)s,
but command execution times really totalled %(expected_command_time)s,
outside of the 1%% tolerance.
""" % locals())

added_times = sconscript_time+scons_time+command_time
if not within_tolerance(total_time, added_times, 0.01):
    failures.append("""\
SCons -j1 reported a total build time of %(total_time)s,
but the various execution times actually totalled %(added_times)s,
outside of the 1%% tolerance.
""" % locals())

if not within_tolerance(total_time, expected_total_time, 0.20):
    # This tolerance check seems empirically to work fine if there's
    # a light load on the system, but on a heavily loaded system the
    # timings get screwy and it can fail frequently.  Some obvious
    # attempts to work around the problem didn't, so just treat it as
    # a warning for now.
    warnings.append("""\
Warning:  SCons -j1 reported total build time of %(total_time)s,
but the actual measured build time was %(expected_total_time)s
(end-to-end time of %(complete_time)s less Python overhead of %(overhead)s),
outside of the 15%% tolerance.
""" % locals())

if failures or warnings:
    print('\n'.join([test.stdout()] + failures + warnings))
if failures:
    test.fail_test(1)

test.run(arguments = "--debug=time . SLEEP=0")

command_time = get_command_time(test.stdout())
if command_time != 0.0:
    print("Up-to-date run received non-zero command time of %s" % command_time)
    test.fail_test()

test.run(arguments = "-c")

test.run(arguments = "-j4 --debug=time . SLEEP=1")

stdout = test.stdout()

total_time      = get_total_time(stdout)
sconscript_time = get_sconscript_time(stdout)
scons_time      = get_scons_time(stdout)
command_time    = get_command_time(stdout)

failures = []

added_times = sconscript_time+scons_time+command_time
if not within_tolerance(total_time, added_times, 0.01):
    failures.append("""\
SCons -j4 reported a total build time of %(total_time)s,
but the various execution times actually totalled %(added_times)s,
outside of the 1%% tolerance.
""" % locals())

if failures:
    print('\n'.join([test.stdout()] + failures))
    test.fail_test(1)

test.run(arguments = "-j4 --debug=time . SLEEP=1")

command_time = get_command_time(test.stdout())
if command_time != 0.0:
    print("Up-to-date run received non-zero command time of %s" % command_time)
    test.fail_test()

test.pass_test()

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
import qiime2.core.archive.format.v1 as v1

class ArchiveFormat(v1.ArchiveFormat):
    # Exactly the same as v1, but in provenance, when the action type isn't
    # import, there is an `output-name` key in the action section with that
    # node's output name according to the action's signature object. Also has
    # pipeline action types.
    pass


text: export { ClipboardModule } from './clipboard.module';


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>Medama Library: Class Index</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Medama Library

Class Index

b | c | g | o | s | u

  b

  g

	ObservableSSHBehaviour (Medama.Arbor)

  u

ObservableSSHInitializeBehaviour (Medama.Arbor)

Buffer (Medama.ObservableSsh)   	GameObjectExtensions (Medama.EUGML)   	ObservableSSHMonoBehaviour (Medama.ObservableSsh)   	UIManager (Medama.EUGML)

  c

  o

  s

Const (Medama.ObservableSsh)   	ObservableSSH (Medama.ObservableSsh)   	StringExtensions (Medama.EUGML)

b | c | g | o | s | u

<address class="footer">
Generated by

 1.8.13
</address>


text:
package install

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
	"time"

	"github.com/spf13/cobra"
	"helm.sh/helm/v3/pkg/action"
	"helm.sh/helm/v3/pkg/chart"
	"helm.sh/helm/v3/pkg/chart/loader"
	"helm.sh/helm/v3/pkg/cli"
	"helm.sh/helm/v3/pkg/cli/values"
	"helm.sh/helm/v3/pkg/getter"
	"helm.sh/helm/v3/pkg/release"
	"k8s.io/cli-runtime/pkg/genericclioptions"

	"github.com/cert-manager/cert-manager/cmd/ctl/pkg/build"
	"github.com/cert-manager/cert-manager/cmd/ctl/pkg/install/helm"
)

type InstallOptions struct {
	settings  *cli.EnvSettings
	client    *action.Install
	cfg       *action.Configuration
	valueOpts *values.Options

	ChartName string
	DryRun    bool
	Wait      bool

	genericclioptions.IOStreams
}

const (
	installCRDsFlagName         = "installCRDs"
	defaultCertManagerNamespace = "cert-manager"
)

func installDesc() string {
	return build.WithTemplate(`This command installs cert-manager. It uses the Helm libraries to do so.

The latest published cert-manager chart in the "https://charts.jetstack.io" repo is used.
Most of the features supported by 'helm install' are also supported by this command.
In addition, this command will always correctly install the required CRD resources.

Some example uses:
	$ {{.BuildName}} x install
or
	$ {{.BuildName}} x install -n new-cert-manager
or
	$ {{.BuildName}} x install --version v1.4.0
or
	$ {{.BuildName}} x install --set prometheus.enabled=false

To override values in the cert-manager chart, use either the '--values' flag and
pass in a file or use the '--set' flag and pass configuration from the command line.
`)
}

func NewCmdInstall(ctx context.Context, ioStreams genericclioptions.IOStreams) *cobra.Command {
	settings := cli.New()
	cfg := new(action.Configuration)

	options := &InstallOptions{
		settings:  settings,
		cfg:       cfg,
		client:    action.NewInstall(cfg),
		valueOpts: &values.Options{},

		IOStreams: ioStreams,
	}

	cmd := &cobra.Command{
		Use:   "install",
		Short: "Install cert-manager",
		Long:  installDesc(),
		RunE: func(cmd *cobra.Command, args []string) error {
			options.client.Namespace = settings.Namespace()

			rel, err := options.runInstall(ctx)
			if err != nil {
				return err
			}

			if options.DryRun {
				fmt.Fprintf(ioStreams.Out, "%s", rel.Manifest)
				return nil
			}

			printReleaseSummary(ioStreams.Out, rel)
			return nil
		},
		SilenceUsage:  true,
		SilenceErrors: true,
	}

	settings.AddFlags(cmd.Flags())

	// The Helm cli.New function does not provide an easy way to
	// override the default of the namespace flag.
	// See https://github.com/helm/helm/issues/9790
	//
	// Here we set the default value shown in the usage message.
	cmd.Flag("namespace").DefValue = defaultCertManagerNamespace
	// Here we set the default value.
	// The returned error is ignored because
	// pflag.stringValue.Set always returns a nil.
	cmd.Flag("namespace").Value.Set(defaultCertManagerNamespace)

	addInstallUninstallFlags(cmd.Flags(), &options.client.Timeout, &options.Wait)

	addInstallFlags(cmd.Flags(), options.client)
	addValueOptionsFlags(cmd.Flags(), options.valueOpts)
	addChartPathOptionsFlags(cmd.Flags(), &options.client.ChartPathOptions)

	cmd.Flags().BoolVar(&options.client.CreateNamespace, "create-namespace", true, "Create the release namespace if not present")
	cmd.Flags().MarkHidden("create-namespace")
	cmd.Flags().StringVar(&options.ChartName, "chart-name", "cert-manager", "Name of the chart to install")
	cmd.Flags().MarkHidden("chart-name")
	cmd.Flags().BoolVar(&options.DryRun, "dry-run", false, "Simulate install and output manifest")

	return cmd
}

// The overall strategy is to install the CRDs first, and not as part of a Helm
// release, and then to install a Helm release without the CRDs.  This is to
// ensure that CRDs are not removed by a subsequent helm uninstall or by a
// future cmctl uninstall. We want the removal of CRDs to only be performed by
// an administrator who understands that the consequences of removing CRDs will
// be the garbage collection of all the related CRs in the cluster.  We first
// do a dry-run install of the chart (effectively helm template
// --validate=false) to render the CRDs from the CRD templates in the Chart.
// The ClientOnly option is required, otherwise Helm will return an error in
// case the CRDs are already installed in the cluster.  We then extract the
// CRDs from the resulting dry-run manifests and install those first.  Finally,
// we perform a helm install to install the remaining non-CRD resources and
// wait for those to be "Ready".
// This creates a Helm "release" artifact in a Secret in the target namespace, which contains
// a record of all the resources installed by Helm (except the CRDs).
func (o *InstallOptions) runInstall(ctx context.Context) (*release.Release, error) {
	log.SetFlags(0)         // Disable prefixing logs with timestamps.
	log.SetOutput(o.ErrOut) // Log everything to stderr so dry-run output does not get corrupted.

	// Find chart
	cp, err := o.client.ChartPathOptions.LocateChart(o.ChartName, o.settings)
	if err != nil {
		return nil, err
	}

	chart, err := loader.Load(cp)
	if err != nil {
		return nil, err
	}

	// Check if chart is installable
	if err := checkIfInstallable(chart); err != nil {
		return nil, err
	}

	// Console print if chart is deprecated
	if chart.Metadata.Deprecated {
		log.Printf("This chart is deprecated")
	}

	// Merge all values flags
	p := getter.All(o.settings)
	chartValues, err := o.valueOpts.MergeValues(p)
	if err != nil {
		return nil, err
	}

	// Dryrun template generation (used for rendering the CRDs in /templates)
	o.client.DryRun = true                  // Do not apply install
	o.client.ClientOnly = true              // Do not validate against cluster (otherwise double CRDs can cause error)
	chartValues[installCRDsFlagName] = true // Make sure to render CRDs
	dryRunResult, err := o.client.Run(chart, chartValues)
	if err != nil {
		return nil, err
	}

	if o.DryRun {
		return dryRunResult, nil
	}

	if err := o.cfg.Init(o.settings.RESTClientGetter(), o.settings.Namespace(), os.Getenv("HELM_DRIVER"), log.Printf); err != nil {
		return nil, err
	}

	// Extract the resource.Info objects from the manifest
	resources, err := helm.ParseMultiDocumentYAML(dryRunResult.Manifest, o.cfg.KubeClient)
	if err != nil {
		return nil, err
	}

	// Filter resource.Info objects and only keep the CRDs
	crds := helm.FilterCrdResources(resources)

	// Abort in case CRDs were not found in chart
	if len(crds) == 0 {
		return nil, fmt.Errorf("Found no CRDs in provided cert-manager chart.")
	}

	// Make sure that no CRDs are currently installed
	originalCRDs, err := helm.FetchResources(crds, o.cfg.KubeClient)
	if err != nil {
		return nil, err
	}

	if len(originalCRDs) > 0 {
		return nil, fmt.Errorf("Found existing installed cert-manager CRDs! Cannot continue with installation.")
	}

	// Install CRDs
	if err := helm.CreateCRDs(crds, o.cfg); err != nil {
		return nil, err
	}

	// Install chart
	o.client.DryRun = false     // Apply DryRun cli flags
	o.client.ClientOnly = false // Perform install against cluster

	o.client.Wait = o.Wait // Wait for resources to be ready
	// If part of the install fails and the Atomic option is set to True,
	// all resource installs are reverted. Atomic cannot be enabled without
	// waiting (if Atomic=True is set, the value for Wait is overwritten with True),
	// so only enable Atomic if we are waiting.
	o.client.Atomic = o.Wait
	// The cert-manager chart currently has only a startupapicheck hook,
	// if waiting is disabled, this hook should be disabled too; otherwise
	// the hook will still wait for the installation to succeed.
	o.client.DisableHooks = !o.Wait

	chartValues[installCRDsFlagName] = false // Do not render CRDs, as this might cause problems when uninstalling using helm

	return o.client.Run(chart, chartValues)
}

func printReleaseSummary(out io.Writer, rel *release.Release) {
	fmt.Fprintf(out, "NAME: %s\n", rel.Name)
	if !rel.Info.LastDeployed.IsZero() {
		fmt.Fprintf(out, "LAST DEPLOYED: %s\n", rel.Info.LastDeployed.Format(time.ANSIC))
	}
	fmt.Fprintf(out, "NAMESPACE: %s\n", rel.Namespace)
	fmt.Fprintf(out, "STATUS: %s\n", rel.Info.Status.String())
	fmt.Fprintf(out, "REVISION: %d\n", rel.Version)
	fmt.Fprintf(out, "DESCRIPTION: %s\n", rel.Info.Description)

	if len(rel.Info.Notes) > 0 {
		fmt.Fprintf(out, "NOTES:\n%s\n", strings.TrimSpace(rel.Info.Notes))
	}
}

// Only Application chart type are installable.
func checkIfInstallable(ch *chart.Chart) error {
	switch ch.Metadata.Type {
	case "", "application":
		return nil
	}
	return fmt.Errorf("%s charts are not installable", ch.Metadata.Type)
}


text:
MapGenerator::MapGenerator()
{
}

MapGenerator::~MapGenerator()
{
}


text:
package com.azure.resourcemanager.machinelearning.generated;

import com.azure.core.util.BinaryData;
import com.azure.resourcemanager.machinelearning.models.CustomTargetLags;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public final class CustomTargetLagsTests {
    @Test
    public void testDeserialize() {
        CustomTargetLags model =
            BinaryData
                .fromString("{\"mode\":\"Custom\",\"values\":[915823701,1407190218,425904374]}")
                .toObject(CustomTargetLags.class);
        Assertions.assertEquals(915823701, model.values().get(0));
    }

    @Test
    public void testSerialize() {
        CustomTargetLags model = new CustomTargetLags().withValues(Arrays.asList(915823701, 1407190218, 425904374));
        model = BinaryData.fromObject(model).toObject(CustomTargetLags.class);
        Assertions.assertEquals(915823701, model.values().get(0));
    }
}


text:
PDI=GEN002718

#Start-Lockdown
for AUDITFILE in /sbin/auditctl /sbin/auditd /sbin/ausearch /sbin/aureport /sbin/autrace /sbin/audispd
do
    ACLOUT=`getfacl --skip-base $AUDITFILE 2>/dev/null`;
    if [ "$ACLOUT" != "" ]
      then
      setfacl --remove-all $AUDITFILE
    fi
done


text:
package edu.cs4730.dialogviewmodeldemo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ContextThemeWrapper;
import androidx.fragment.app.Fragment;

/**
 * Shows how to build and call a support alert dialog and set the listeners for it.
 * Also shows a list dialog and listeners as well.
 */
public class SupportDialogFragment extends Fragment {
    Button btn;
    TextView logger;
    String TAG = "SuppportDialogFragment";

    public SupportDialogFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View myView = inflater.inflate(R.layout.fragment_support_dialog, container, false);
        btn = myView.findViewById(R.id.btn_support_AlertDialog);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showdialog("Demo Dialog");
            }
        });
        logger = myView.findViewById(R.id.logger_support);
        myView.findViewById(R.id.btn_support_ListDialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showlistdialog("Demo List Dialog");
            }
        });
        return myView;
    }

    void displaylog(String item) {
        Log.v(TAG, item);
        logger.append(item + "\n");
    }

    /*
     *  The method is not necessary.
     *
     *  This builds an alert dialog, with the positive button set to Yes, Negative button set to NO.
     *  There is a listener if the dialog is canceled (ie the back button is used)
     */

    void showdialog(String title) {

        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(requireActivity(), R.style.ThemeOverlay_AppCompat_Dialog));
        builder.setTitle(title);
        builder.setMessage("Play again?");
        //Button Button
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                displaylog("play again");

            }
        });
        //Negative button
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                displaylog("exit");

            }
        });
        //If the user uses the back button instead.
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                displaylog("canceled ");

            }
        });
        builder.show();
    }

    /**
     * This shows a list and the use is to select one of them.
     * Note, this dialog doesn't set a cancel listener, like the one above.  so if the user
     * cancels, nothing happens.
     */
    void showlistdialog(String title) {
        final String[] items = {"Remove Walls", "Add Walls",
            "Add/Remove Objects", "Add/Remove Score"};
        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(requireActivity(), R.style.ThemeOverlay_AppCompat_Dialog));
        builder.setTitle(title);
        builder.setSingleChoiceItems(items, -1,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    dialog.dismiss();  //the dismiss is needed here or the dialog stays showing.
                    displaylog(items[item]);
                }
            });
        builder.show();
    }
}


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
A monograph of the acritarchs and Chitinozoa from the Wenlock and Ludlow Series of the Ludlow and Millichope areas, Shropshire. Part 1. Palaeontogr. Soc. (Monogr. ) 124 (No. 528): 96.

#### Original name
null

### Remarks
null


text:
package reborncore.common.fluid;

import net.minecraft.fluid.Fluid;
import net.minecraft.item.BucketItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Identifier;
import net.minecraft.util.Lazy;
import net.minecraft.util.registry.Registry;
import reborncore.common.fluid.container.ItemFluidInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

public class RebornFluidManager {

	private static final HashMap<Identifier, RebornFluid> fluids = new HashMap<>();

	private static Lazy<Map<Fluid, BucketItem>> bucketMap;

	public static void register(RebornFluid rebornFluid, Identifier identifier){
		fluids.put(identifier, rebornFluid);
		Registry.register(Registry.FLUID, identifier, rebornFluid);
	}

	public static void setupBucketMap(){
		bucketMap = new Lazy<>(() -> {
			Map<Fluid, BucketItem> map = new HashMap<>();
			Registry.ITEM.stream().filter(item -> item instanceof BucketItem).forEach(item -> {
				BucketItem bucketItem = (BucketItem) item;
				//We can be sure of this as we add this via a mixin
				ItemFluidInfo fluidInfo = (ItemFluidInfo) bucketItem;
				Fluid fluid = fluidInfo.getFluid(new ItemStack(item));
				if(!map.containsKey(fluid)){
					map.put(fluid, bucketItem);
				}
			});
			return map;
		});
	}

	public static Map<Fluid, BucketItem> getBucketMap(){
		return bucketMap.get();
	}

	public static HashMap<Identifier, RebornFluid> getFluids() {
		return fluids;
	}

	public static Stream<RebornFluid> getFluidStream(){
		return fluids.values().stream();
	}
}


text:
<?php

error_reporting(E_STRICT | E_ALL);

// You can set the include path to src directory or reference
// DfpUser.php directly via require_once.
// $path = '/path/to/dfp_api_php_lib/src';
$path = dirname(__FILE__) . '/../../../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';
require_once 'Google/Api/Ads/Common/Util/MapUtils.php';

try {
  // Get DfpUser from credentials in "../auth.ini"
  // relative to the DfpUser.php file's directory.
  $user = new DfpUser();

  // Log SOAP XML request and response.
  $user->LogDefaults();

  // Get the LineItemService.
  $lineItemService = $user->GetService('LineItemService', 'v201505');

  // Set the IDs of the custom fields, custom field option, and line item.
  $customFieldId = "INSERT_CUSTOM_FIELD_ID_HERE";
  $dropDownCustomFieldId = "INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE";
  $customFieldOptionId = "INSERT_CUSTOM_FIELD_OPTION_ID_HERE";
  $lineItemId = "INSERT_LINE_ITEM_ID_HERE";

  // Create a statement to select a single line item by ID.
  $vars =
      MapUtils::GetMapEntries(array('id' => new NumberValue($lineItemId)));
  $filterStatement = new Statement("WHERE id = :id ORDER BY id ASC LIMIT 1",
      $vars);

  // Get the line item.
  $page = $lineItemService->getLineItemsByStatement($filterStatement);
  $lineItem = $page->results[0];

  // Create custom field values.
  $customFieldValues = array();

  $customFieldValue = new CustomFieldValue();
  $customFieldValue->customFieldId = $customFieldId;
  $customFieldValue->value = new TextValue("Custom field value");
  $customFieldValues[] = $customFieldValue;

  $dropDownCustomFieldValue = new DropDownCustomFieldValue();
  $dropDownCustomFieldValue->customFieldId = $dropDownCustomFieldId;
  $dropDownCustomFieldValue->customFieldOptionId = $customFieldOptionId;
  $customFieldValues[] = $dropDownCustomFieldValue;

  // Only add existing custom field values for different custom fields than
  // the ones you are setting.
  if (isset($lineItem->customFieldValues)) {
    foreach ($lineItem->customFieldValues as $oldCustomFieldValue) {
      if (($oldCustomFieldValue->customFieldId != $customFieldId) &&
          ($oldCustomFieldValue->customFieldId != $dropDownCustomFieldId)) {
        $customFieldValues[] = $oldCustomFieldValue;
      }
    }
  }

  $lineItem->customFieldValues = $customFieldValues;

  // Update the line item on the server.
  $lineItems = $lineItemService->updateLineItems(array($lineItem));

  foreach ($lineItems as $lineItem) {
    $customFieldValueStrings = array();
    foreach ($lineItem->customFieldValues as $baseCustomFieldValue) {
      if (($baseCustomFieldValue instanceof CustomFieldValue)) {
        $customFieldValueStrings[] = sprintf("{ID: '%d', value: '%s'}",
            $baseCustomFieldValue->customFieldId,
            $baseCustomFieldValue->value->value);
      } else if ($baseCustomFieldValue instanceof DropDownCustomFieldValue) {
        $customFieldValueStrings[] = sprintf("{ID: '%d', custom field option "
            . "ID: '%d'}", $baseCustomFieldValue->customFieldId,
            $baseCustomFieldValue->customFieldOptionId);
      }
    }
    printf("A line item with ID '%s' was set with custom field values '%s'\n.",
        $lineItem->id, join(",", $customFieldValueStrings));
  }
} catch (OAuth2Exception $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
  printf("%s\n", $e->getMessage());
}


text:
require 'whois/record/parser/base'

module Whois
  class Record
    class Parser

      #
      # = whois.nic.org.uy parser
      #
      # Parser for the whois.nic.org.uy server.
      #
      # NOTE: This parser is just a stub and provides only a few basic methods
      # to check for domain availability and get domain status.
      # Please consider to contribute implementing missing methods.
      # See WhoisNicIt parser for an explanation of all available methods
      # and examples.
      #
      class WhoisNicOrgUy < Base

        property_supported :status do
          if content_for_scanner =~ /Estatus del dominio: (.+?)\n/
            case $1.downcase
              when "activo" then :registered
              else
                Whois.bug!(ParserError, "Unknown status `#{$1}'.")
            end
          else
            :available
          end
        end

        property_supported :available? do
          !!(content_for_scanner =~ /No match for "(.*?)"/)
        end

        property_supported :registered? do
          !available?
        end

        property_supported :created_on do
          if content_for_scanner =~ /Fecha de Creacion: (.*)\n/
            Time.parse($1)
          end
        end

        property_supported :updated_on do
          if content_for_scanner =~ /Ultima Actualizacion: (.*)\n/
            Time.parse($1)
          end
        end

        property_not_supported :expires_on

        property_supported :nameservers do
          if content_for_scanner =~ /Servidor\(es\) de Nombres de Dominio:\n\n((.+\n)+)\n/
            $1.scan(/-\s(.*?)\n/).flatten.map do |name|
              Record::Nameserver.new(:name => name)
            end
          end
        end

      end

    end
  end
end


text:
Using a Bitcoind Wallet
========================
The default openbazaar-go wallet uses [simplified payment verification](https://bitcoin.org/en/developer-guide#simplified-payment-verification-spv) (SPV) to validate incoming bitcoin payments.
The benefit of this operating mode is that it achieves a high level of security without much overhead (bandwidth, CPU, etc) and is suitable for the average user. However, there are some downsides
to SPV that might warrant switching to a different wallent:

1. **Lack of full validation**

  SPV wallets only download the bitcoin block headers (not the full contents of the block) and validate that the proof of work is correct. Additionally, they validate a cryptographic
proof which proves an incoming transaction is in the block. However, since the contents of the blocks are neither downloaded nor validated, an attacker (with a sizable amount of mining power)
could create an invalid block header that appears valid to the SPV wallet and trick it into accepting an invalid payment. The saving grace here is that such blocks are very likely to be orphaned
by the wallet when bitcoin miners fail to build on such block. Unless the attacker controls a majority of the mining power (ie, a 51% attack), simply waiting for a number of confirmations before
treating a payment as valid should be enough to foil this attack. But it should be noted that low confirmation payments are less secure in SPV mode than normal.

2. **Privacy leaks**

  SPV wallets use bloom filters to avoid downloading all transactions and instead download (mostly) only those transactions relevant to the wallet. In theory bloom filers
  should provide decent privacy since they don't reveal exactly which transactions your wallet is interested in, however in practice the need to continually update and
  resize the filters causes privacy leaks.

  Upon each start up the wallet makes random outgoing connections to the bitcoin network (and does not accept incoming connections). If these random peers are running patched software which logs
  your activity, they can deduce which bitcoin addresses (and hence transactions) belong to your wallet. There are a few things to say about this:

  - The leaks are limited to only those peers you connect to, not the entire world. Unlike the blockchain, there isn't any public database where someone can look up your transaciton history.
  - The leaks don't per se reveal your identity. You can still, theoretically, remain pseudonymous while using an SPV wallet. However, your IP address is visible to the peers which see your bloom
  filters meaning you would need to take additional steps to conceal your identity (such as using a VPN or Tor).
  - Finally, if any one of your transactions can be independently linked to your real
  world identity (such as through an in-person trade, or by revealing your shipping address) then you must assume your identity can be linked to all transactions made through the wallet.

The bitcoind wallet, by downloading, validating, and relaying all transactions that come across the network solves both of the above problems. The downside is it's a much more heavyweight application
and consumes a good amount of CPU, memory, storage, and bandwidth. Therefore it is not suitable for all users.

**WARNING**: If you are using Tor for anonymity it is *highly* recommend you also use bitcoind to avoid any possible privacy leaks through bloom filters.

### Setting Up Bitcoind

The first thing you need to do is get a copy of bitcoind. Any of the competing implementations (Core, Unlimited, Classic) will work for this purpose.
You can downloaded a pre-compiled Core binary [here](https://bitcoin.org/en/download) or build it from source from the github repo.

Next, if you haven't already down so, create a bitcoind config file. Download the following file and save it in the bitcoind data folder: https://github.com/bitcoin/bitcoin/blob/master/contrib/debian/examples/bitcoin.conf

Edit the config file to set a username and password:
```
#rpcuser=alice
#rpcpassword=DONT_USE_THIS_YOU_WILL_GET_ROBBED_8ak1gI25KFTvjovL3gAM967mies3E=
```
Note: you must remove the # before saving.

Next, edit the following fields in the openbazaar-go config file found in the openbazaar2.0 data folder:
```
"Wallet": {
    "Binary": "/path/to/bitcoind",
    "RPCPassword": "DONT_USE_THIS_YOU_WILL_GET_ROBBED_8ak1gI25KFTvjovL3gAM967mies3E=",
    "RPCUser": "alice",
    "Type": "bitcoind"
  }
```
Obviously replacing the username and password with the username and password you set in the bitcoind config file.

That's it! Just start openbazaar-go.

### Things to consider
- If bitcoind is running when you start openbazaar-go, it will shut it down and restart it. This is done because bitcoind needs to be run
with a specific set of options so that openbazaar-go can detect incoming payments.
- It's highly recommended you do not run bitcoind independently of openbazaar-go. If you receive a transaction while openbazaar-go is not
running, it will not be passed into openbazaar-go. Next time you start openbazaar-go it will not detect the payment. You can force it detect
the payment by running the resync blockchain API call, but it's a very heavyweight operation.


text:
from datetime import date

VALID_USER, VALID_PASSWORD = 'testuser', 'password'

def ffd(date):
    """
    Form-friendly date formatter
    """
    return date.strftime('%Y-%m-%d %H:%M')


text:
<?php

namespace JLP\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class JLPAdminBundle extends Bundle
{
}


text:
"use strict";

var bbm = require('../../index.js');

var util = require('../lib/util');
var samples = require('../samples/section/vitals');

describe('vitals section tests', function () {
  it('sample valid_0', function () {
    var valid = bbm.validator.validate(samples.valid_0, 'vitals');
    expect(valid).toBe(true);
  });

  it('sample invalid_0', function () {
    var valid = bbm.validator.validate(samples.invalid_0, 'vitals');
    expect(valid).toBe(false);
    var result = bbm.validator.getLastError();
    var al = util.errorsToArrayIndices(result);
    expect(al).toEqual([0, 1]);
  });
});


text:
describe RuboCop::Cop::Style::BlockComments do
  subject(:cop) { described_class.new }

  it 'registers an offense for block comments' do
    expect_offense(<<-RUBY.strip_indent)
      =begin
      ^^^^^^ Do not use block comments.
      comment
      =end
    RUBY
  end

  it 'accepts regular comments' do
    expect_no_offenses('# comment')
  end

  it 'auto-corrects a block comment into a regular comment' do
    new_source = autocorrect_source(cop, <<-END.strip_indent)
      =begin
      comment line 1

      comment line 2
      =end
      def foo
      end
    END
    expect(new_source).to eq(<<-END.strip_indent)
      # comment line 1
      #
      # comment line 2
      def foo
      end
    END
  end

  it 'auto-corrects an empty block comment by removing it' do
    new_source = autocorrect_source(cop, <<-END.strip_indent)
      =begin
      =end
      def foo
      end
    END
    expect(new_source).to eq(<<-END.strip_indent)
      def foo
      end
    END
  end
end


text:
//
//  IQNetworkUploadTask.h
// https://github.com/hackiftekhar/IQNetworkKit
// Copyright (c) 2013-14 Iftekhar Qurashi.
//
// 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.

#import "IQNetworkDataTask.h"

@interface IQNetworkUploadTask : IQNetworkDataTask

/* Creates an upload task with the given request.  The body of the request will be created from the file referenced by fileURL */
-(instancetype)initWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;

/* Creates an upload task with the given request.  The body of the request is provided from the bodyData. */
-(instancetype)initWithRequest:(NSURLRequest *)request bodyData:(NSData *)bodyData;

+(NSURLRequest*)expectedRequestForRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;
+(NSURLRequest*)expectedRequestForRequest:(NSURLRequest *)request bodyData:(NSData *)bodyData;

@end


text:
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

NCGA: Summary Info for Representative Michael V. Lee (R) - District 9

Sponsored Bills (27 total)

Bill Keywords

Co-Sponsors


text:
layout: post
title:  Latent Dirichlet Allocation
date:   2017-04-12 16:43:00 +0800
categories: Model
tag: Machine Learning
---

* content
{:toc}

先挖个坑

Latent Dirichlet Allocation
===============
this is a topic model

Application
===============


text:
package com.featurefm.util.urls

import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{Matchers, FlatSpec}

/**
 * Created by yardena on 11/19/15.
 */
class ValidatorSpec extends FlatSpec with Matchers {

  import UrlValidator._

  UrlValidator.getClass.getSimpleName should "accept twitter handle @EricPClapton" in {
    validTwitterHandle_?("@EricPClapton") shouldBe true
  }

  it should "accept twitter url https://twitter.com/EricPClapton" in {
    validTwitterHandle_?("https://twitter.com/EricPClapton") shouldBe true
  }

  it should "accept facebook url https://www.facebook.com/ericclapton" in {
    validFacebookUrl_?("https://www.facebook.com/ericclapton") shouldBe true
  }

  it should "accept facebook url with '-' in the page" in {
    validFacebookUrl_?("https://www.facebook.com/Featurefm-497931363607317?ref=aymt_homepage_panel") shouldBe true
  }

  it should "accept various flavors of youtube urls" in {

    validYouTubeUrl_?("https://www.youtube.com/user/ericclapton") shouldBe true
    validYouTubeUrl_?("https://www.youtube.com/channel/ericclapton") shouldBe true
    validYouTubeUrl_?("https://www.youtube.com/c/ericclapton") shouldBe true
    validYouTubeUrl_?("https://www.youtube.com/ericclapton") shouldBe true
  }

  it should "accept a url 'http://www.ericclapton.com'" in {
    validUrl_?("http://www.ericclapton.com") shouldBe true
  }

  it should "accept urls with trailing /" in {
    validTwitterHandle_?("https://twitter.com/EricPClapton/") shouldBe true

    validFacebookUrl_?("https://www.facebook.com/ericclapton/") shouldBe true

    validYouTubeUrl_?("https://www.youtube.com/user/ericclapton/") shouldBe true
    validYouTubeUrl_?("https://www.youtube.com/ericclapton/") shouldBe true

    validUrl_?("http://www.ericclapton.com/") shouldBe true
  }

  it should "not accept email as url" in {
    validUrl_?("fourthrealmmusic@gmail.com") shouldBe false
  }

  it should "accept url with numbers as first word" in {
    validUrl_?("https://5113.hearnow.com/") shouldBe true
  }

  it should "accept url parameters" in {
    validUrl_?("http://itunes.apple.com/album/id1083744262?ls=1&app=itunes") shouldBe true
    validUrl_?("https://www.instagram.com/whagiy/?hl=en")
  }

  it should "accept underscore in twitter handle" in {
    validTwitterHandle_?("@I_Has_Under") shouldBe true
    validTwitterHandle_?("https://twitter.com/I_Has_Under") shouldBe true
  }

  it should "succeed to update artist with empty string url" in {
    validTwitterHandle_?("") shouldBe true

    validFacebookUrl_?("") shouldBe true

    validYouTubeUrl_?("") shouldBe true

    validUrl_?("") shouldBe true
  }

  it should "fail twitter with 'ssasasdad'" in {
    validTwitterHandle_?("ssasasdad") shouldBe false
  }
  it should "fail twitter with 'ssas@asdad'" in {
    validTwitterHandle_?("ssas@asdad") shouldBe false
  }

  it should "fail youtube with 'ssasasdad'" in {
    validYouTubeUrl_?("ssasasdad") shouldBe false
  }

  it should "fail facebook with 'ssasasdad'" in {
    validFacebookUrl_?("ssasasdad") shouldBe false
  }

  it should "fail website with 'ssasasdad'" in {
    validUrl_?("ssasasdad") shouldBe false
  }

  it should "accept website with 'https://www.youtube.com/shared?ci=FcjfNRXks-k'" in {
    validUrl_?("https://www.youtube.com/shared?ci=FcjfNRXks-k") shouldBe true
  }

  it should "accept website with 'https://www.spinninrecords.com/profile/dima_zill#contests'" in {
    validUrl_?("https://www.spinninrecords.com/profile/dima_zill#contests") shouldBe true
  }

  it should "extract correct facebook id" in new TableDrivenPropertyChecks {

    val data = Table(
      ("url",                                                                        "id"                                     ),
//     ------------------------------------------------------------------            ------------------------------------------
      ("https://www.facebook.com/ericclapton",                                       "ericclapton"                            ),
      ("https://www.facebook.com/Featurefm-497931363607317/?fref=ts",                "Featurefm-497931363607317"              ),
      ("http://www.facebook.com/#!/my_page_id",                                      "my_page_id"                             ),
      ("http://www.facebook.com/pages/Paris-France/Vanity-Url/123456?v=app_555",     "123456"                                 ),
      ("http://www.facebook.com/pages/Vanity-Url/45678",                             "45678"                                  ),
      ("http://www.facebook.com/#!/page_with_1_number",                              "page_with_1_number"                     ),
      ("http://www.facebook.com/bounce_page#!/pages/Vanity-Url/45678",               "45678"                                  ),
      ("http://www.facebook.com/bounce_page#!/my_page_id?v=app_166292090072334",     "my_page_id"                             ),
      ("https://www.facebook.com/Featurefm-497931363607317?ref=aymt_homepage_panel", "Featurefm-497931363607317"              ),
      ("http://www.facebook.com/my.page.is.great",                                   "my.page.is.great"                       ),
      ("https://m.facebook.com/ATM-TRILL-1519253188329468/",                         "ATM-TRILL-1519253188329468"             ),
      ("https://www.facebook.com/Tony-Montanez-Music-1177639645599236/",             "Tony-Montanez-Music-1177639645599236"   ),
      ("https://www.facebook.com/Malick-Da-1da",                                     "Malick-Da-1da"                          ),
      ("https://www.facebook.com/JulianCherkinsky-Band-1630144687252083/?fref=ts",   "JulianCherkinsky-Band-1630144687252083" ),
      ("https://www.facebook.com/Jerk-in-the-can-1542108192679526/",                 "Jerk-in-the-can-1542108192679526"       ),
      ("https://www.facebook.com/Black-Sea-Storm-203236457751/",                     "Black-Sea-Storm-203236457751"           ),
      ("https://www.facebook.com/Tony-Montanez-Music-1177639645599236/",             "Tony-Montanez-Music-1177639645599236"   )
    )

    forAll(data) { (url: String, id: String) =>
      val Facebook(extract) = url
      extract shouldBe id
    }

  }

}


text:
import pickle
import redis

from pod_manager.settings import REDIS_HOST, REDIS_PORT, REDIS_DB

__all__ = [
    'get_client',
    'cache_object',
    'get_object'
]

def get_client():
    client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
    return client

def cache_object(client, key, obj, ttl=60):
    pipe = client.pipeline()
    data = pickle.dumps(obj)
    pipe.set(key, data)

    if ttl:
        pipe.expire(key, ttl)

    pipe.execute()

def get_object(client, key):
    data = client.get(key)

    if not data:
        return None

    obj = pickle.loads(data)
    return obj


text:
docker-postgis
==============

Docker PostGIS Image with working PostGIS enabled database.

How to use
==========

```bash
./build # if you want to rebuild the image
./run_localhost # run PostgreSQL on local port 5432
```

The commands do the following:

```bash
#./build
sudo docker build -t denz/postgis .
```

```bash
#./run_localhost
sudo docker run -p 5432:5432 -d denz/postgis
```


text:
package org.keycloak.authentication.authenticators.directgrant;

import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.CredentialValidator;
import org.keycloak.credential.CredentialProvider;
import org.keycloak.credential.PasswordCredentialProvider;
import org.keycloak.events.Errors;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.representations.idm.CredentialRepresentation;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class ValidatePassword extends AbstractDirectGrantAuthenticator {

    public static final String PROVIDER_ID = "direct-grant-validate-password";

    @Override
    public void authenticate(AuthenticationFlowContext context) {
        String password = retrievePassword(context);
        boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), UserCredentialModel.password(password));
        if (!valid) {
            context.getEvent().user(context.getUser());
            context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
            Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_grant", "Invalid user credentials");
            context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
            return;
        }

        context.success();
    }

    @Override
    public boolean requiresUser() {
        return true;
    }

    @Override
    public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
        return true;
    }

    @Override
    public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {

    }

    @Override
    public boolean isUserSetupAllowed() {
        return false;
    }

    @Override
    public String getDisplayType() {
        return "Password";
    }

    @Override
    public String getReferenceCategory() {
        return null;
    }

    @Override
    public boolean isConfigurable() {
        return false;
    }

    @Override
    public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
        return REQUIREMENT_CHOICES;
    }

    @Override
    public String getHelpText() {
        return "Validates the password supplied as a 'password' form parameter in direct grant request";
    }

    @Override
    public List<ProviderConfigProperty> getConfigProperties() {
        return new LinkedList<>();
    }

    @Override
    public String getId() {
        return PROVIDER_ID;
    }

    protected String retrievePassword(AuthenticationFlowContext context) {
        MultivaluedMap<String, String> inputData = context.getHttpRequest().getDecodedFormParameters();
        return inputData.getFirst(CredentialRepresentation.PASSWORD);
    }
}


text:
<?php
namespace Acelaya\Service;

use Acelaya\Entity\Item;

interface ItemServiceInterface
{
    /**
     * @return Item[]
     */
    public function getItems();

    /**
     * @param $itemId
     * @return Item
     */
    public function getItem($itemId);

    /**
     * @param Item $item
     * @return mixed
     */
    public function createItem(Item $item);

    /**
     * @param Item $item
     * @return mixed
     */
    public function updateItem(Item $item);

    /**
     * @param Item|int $item
     * @return mixed
     */
    public function deleteItem($item);
}


text:
package com.alibaba.cobar.client;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.testng.TestNG;

public class CobarTestNGTestsRunner {

    /**
     * @param args
     */
    public static void main(String[] args) {
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);

        TestNG testng = new TestNG();

        List<String> suites = new ArrayList<String>();
        suites.add("src/test/resources/testng.xml");
        testng.setTestSuites(suites);
        testng.setOutputDirectory("target/test-output");
        testng.run();
    }

}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('example', '0004_mylocationcomplex'),
    ]

    operations = [
        migrations.CreateModel(
            name='MyLocationInlineNotPlace',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(blank=True, max_length=100)),
                ('parent_location', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='example.MyLocation')),
            ],
        ),
    ]


text:
package app.book;

import com.google.common.collect.*;
import java.util.*;

public class BookDao {

    private final List<Book> books = ImmutableList.of(
            new Book("Moby Dick", "Herman Melville", "9789583001215"),
            new Book("A Christmas Carol", "Charles Dickens", "9780141324524"),
            new Book("Pride and Prejudice", "Jane Austen", "9781936594290"),
            new Book("The Fellowship of The Ring", "J. R. R. Tolkien", "0007171978"),
            new Book("Harry Potter", "J. K. Rowling", "0747532699"),
            new Book("War and Peace", "Leo Tolstoy", "9780060798871"),
            new Book("Don Quixote", "Miguel Cervantes", "9789626345221"),
            new Book("Ulysses", "James Joyce", "9780394703800"),
            new Book("The Great Gatsby", "F. Scott Fitzgerald", "9780743273565"),
            new Book("One Hundred Years of Solitude", "Gabriel Garcia Marquez", "9780060531041"),
            new Book("The adventures of Huckleberry Finn", "Mark Twain", "9781591940296"),
            new Book("Alice In Wonderland", "Lewis Carrol", "9780439291491")
    );

    public Iterable<Book> getAllBooks() {
        return books;
    }

    public Book getBookByIsbn(String isbn) {
        return books.stream().filter(b -> b.getIsbn().equals(isbn)).findFirst().orElse(null);
    }

    public Book getRandomBook() {
        return books.get(new Random().nextInt(books.size()));
    }
}


text:
/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'wadachi-fighter',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      EXTEND_PROTOTYPES: {
        Array: false,  // BabylonJS'Ì•´'ˆ
        Function: true,
        String: true,
      },

      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      facebookInit: {
        appId: "",
        cookie: false,
        status: true,
        xfbml: false,
        version: "v2.2"
      },

      googleAnalytics: {
        account: ""
      },

      googlePlusSignin: {
        clientid: "",
        cookiepolicy: "single_host_origin",
        scope: "profile",
        height: "tall",
        width: "wide"
      }
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};


text:
require 'rails_helper'

describe Doorkeeper::OpenidConnect::OAuth::PreAuthorization do
  subject { Doorkeeper::OAuth::PreAuthorization.new server, attrs }

  let(:server) { Doorkeeper.configuration }
  let(:attrs) {}

  describe '#initialize' do
    context 'with nonce parameter' do
      let(:attrs) { { nonce: '123456' } }

      it 'stores the nonce attribute' do
        expect(subject.nonce).to eq '123456'
      end
    end
  end

  describe '#error_response' do
    context 'with response_type = code' do
      let(:attrs) { { response_type: 'code', redirect_uri: 'client.com/callback' } }

      it 'redirects to redirect_uri with query parameter' do
        expect(subject.error_response.redirect_uri).to match(/#{attrs[:redirect_uri]}\?/)
      end
    end

    context 'with response_type = token' do
      let(:attrs) { { response_type: 'token', redirect_uri: 'client.com/callback' } }

      it 'redirects to redirect_uri with fragment' do
        expect(subject.error_response.redirect_uri).to match(/#{attrs[:redirect_uri]}#/)
      end
    end

    context 'with response_type = id_token' do
      let(:attrs) { { response_type: 'id_token', redirect_uri: 'client.com/callback' } }

      it 'redirects to redirect_uri with fragment' do
        expect(subject.error_response.redirect_uri).to match(/#{attrs[:redirect_uri]}#/)
      end
    end

    context 'with response_type = id_token token' do
      let(:attrs) { { response_type: 'id_token token', redirect_uri: 'client.com/callback' } }

      it 'redirects to redirect_uri with fragment' do
        expect(subject.error_response.redirect_uri).to match(/#{attrs[:redirect_uri]}#/)
      end
    end
  end
end


text:
'use strict';
angular.module('dockerUiApp').directive('ngAppendHtml', [
    '$compile', function ($compile) {
        return function (scope, element, attr) {
            /** @namespace attr.ngAppendHtml */
            element.append($compile(angular.element(scope.$eval(attr.ngAppendHtml)))(scope));
        };
    }
]);
angular.module('dockerUiApp').directive('dcGrid', [
    '$compile', '$parse', '$rootScope', '$filter',
    function ($compile, $parse, $rootScope, $filter) {
        //noinspection JSLint
        return {
            templateUrl: 'views/dc-grid.html',
            restrict: 'E',
            replace: true,
            scope   : {
                options: '=',
                items: '='
            },
            link: function postLink(scope) {
                scope.currentPage = 1;
                scope.maxSize = scope.options.maxSize || 10;
                scope.nested = !!scope.options.nested;
                scope.active = null;
                scope.rows = [];

                var filtered = [],
                    progress = false;

                function init(rows) {
                    if (!rows.length) {
                        scope.rows = [];
                        return;
                    }
                    scope.totalItems = rows.length;
                    if (scope.sortBy && angular.isDefined(scope.sortOrder)) {
                        rows = $filter('orderBy')(rows, scope.sortBy, scope.sortOrder);
                    }
                    scope.rows = rows.slice((scope.currentPage - 1) * scope.maxSize, scope.currentPage * scope.maxSize);
                    progress = false;
                }
                scope.$watchCollection('items', function (rows) {
                    progress = true;
                    scope.currentPage = 1;
                    filtered = rows || [];
                    init(filtered);
                });
                scope.$watch('currentPage', function () {
                    if (progress) {
                        return;
                    }
                    init(filtered);
                });
                scope.sortBy = scope.options.sortBy;
                scope.sortOrder = !!scope.options.sortBy;
                scope.sort = function (field) {
                    if (scope.sortBy !== field) {
                        scope.sortBy = field;
                        scope.sortOrder = true;
                    } else {
                        if (scope.sortOrder) {
                            scope.sortOrder = false;
                        } else {
                            scope.sortOrder = null;
                            scope.sortBy = null;
                        }
                    }
                    init(filtered);
                };

                scope.sortUp = function (field) {
                    return scope.sortBy === field && scope.sortOrder === true;
                };

                scope.sortDown = function (field) {
                    return scope.sortBy === field && scope.sortOrder === false;
                };

                if (scope.options.globalFilter) {
                    $rootScope.$watch('search.value', function (value) {
                        if (progress) {
                            return;
                        }
                        filtered = $filter('filter')(scope.items, value);
                        init(filtered);
                    });
                }

                scope.rowClass = function (data) {
                    if (scope.options.rowClass) {
                        return scope.options.rowClass(data);
                    }
                    return '';
                };

                scope.get = function (data, def) {
                    var getter = $parse(def.field),
                        value = getter(scope, data),
                        el = null;

                    data.$watch = function (interpolateFn, setter) {
                        setter(interpolateFn(data), null);
                    };

                    if (Array.isArray(def.buttons)) {
                        el = '';
                        def.buttons.forEach(function (button, i) {
                            el += '<button class="btn ' + button.class +
                            '" data-ng-click="def.buttons[' + i + '].click(row)">' + button.name + '</button>';
                        });
                        return el;
                    }

                    if (typeof def.map === 'function') {
                        value = def.map(value, data);
                    } else if (typeof def.map === 'string') {
                        el = angular.element('
' + def.map + '
');
                        value = $compile(el)(data).html();
                    }

                    if (def.filter) {
                        if (typeof def.filter === 'string') {
                            value = $filter(def.filter)(value);
                        } else {
                            value = $filter(def.filter.name)(value, def.filter.options);
                        }
                    }

                    if (def.link) {
                        el = angular.element('
' + value + '
');
                        el = $compile(el)(data).html();
                    } else {
                        el = value;
                    }

                    if (el === undefined) {
                        el = '';
                    }

                    return '' + el + '';
                };
            }
        };
    }]);


text:
#include <core/session.hpp>

namespace decentralised
{
	namespace core
	{
		using std::placeholders::_1;
		using std::placeholders::_2;
		using std::placeholders::_3;
		using std::placeholders::_4;

		session::session(threadpool& pool, const session_params& params)
			: strand_(pool.service()),
			handshake_(params.handshake_), protocol_(params.protocol_),
			chain_(params.blockchain_), poll_(params.poller_),
			tx_pool_(params.transaction_pool_),
			grabbed_invs_(20)
		{
		}

		void handle_set_start_height(const std::error_code&)
		{
			// Set start height in handshake
			// Do nothing
		}
		void session::start(completion_handler handle_complete, bool isSeedOnly)
		{
			protocol_.start(handle_complete, isSeedOnly);
			protocol_.subscribe_channel(
				[this](const std::error_code& ec, channel_ptr node)
			{
				BITCOIN_ASSERT(!ec || ec == error::service_stopped);
				if (!ec)
					poll_.query(node);
			});
			protocol_.subscribe_channel(
				std::bind(&session::new_channel, this, _1, _2));
			chain_.fetch_last_height(
				std::bind(&handshake::set_start_height,
				&handshake_, _2, handle_set_start_height));
			chain_.subscribe_reorganize(
				std::bind(&session::set_start_height,
				this, _1, _2, _3, _4));
		}

		void session::stop(completion_handler handle_complete)
		{
			protocol_.stop(handle_complete);
		}

		void session::new_channel(const std::error_code& ec, channel_ptr node)
		{
			if (ec)
			{
				log_warning(LOG_SESSION) << "New channel: " << ec.message();
				return;
			}
			BITCOIN_ASSERT(node);
			node->subscribe_inventory(
				std::bind(&session::inventory, this, _1, _2, node));
			node->subscribe_get_data(
				std::bind(&session::get_data, this, _1, _2, node));
			node->subscribe_get_blocks(
				std::bind(&session::get_blocks, this, _1, _2, node));
			// tx
			// block
			protocol_.subscribe_channel(
				std::bind(&session::new_channel, this, _1, _2));
			poll_.monitor(node);
		}

		void session::set_start_height(const std::error_code& ec, size_t fork_point,
			const blockchain::block_list& new_blocks,
			const blockchain::block_list& /* replaced_blocks */)
		{
			if (ec)
			{
				BITCOIN_ASSERT(ec == error::service_stopped);
				return;
			}
			size_t last_height = fork_point + new_blocks.size();
			handshake_.set_start_height(last_height, handle_set_start_height);
			chain_.subscribe_reorganize(
				std::bind(&session::set_start_height,
				this, _1, _2, _3, _4));
			// Broadcast invs of new blocks
			inventory_type blocks_inv;
			for (auto block : new_blocks)
			{
				blocks_inv.inventories.push_back({
					inventory_type_id::block,
					hash_block_header(block->header) });
			}
			auto ignore_handler = [](const std::error_code&, size_t) {};
			protocol_.broadcast(blocks_inv, ignore_handler);
		}

		void session::inventory(const std::error_code& ec,
			const inventory_type& packet, channel_ptr node)
		{
			if (ec)
			{
				log_error(LOG_SESSION) << "inventory: " << ec.message();
				return;
			}
			for (const inventory_vector_type& ivec : packet.inventories)
			{
				if (ivec.type == inventory_type_id::transaction)
					strand_.post(
					std::bind(&session::new_tx_inventory,
					this, ivec.hash, node));
				else if (ivec.type == inventory_type_id::block);
				// Do nothing. Handled by poller.
				else
					log_warning(LOG_SESSION) << "Ignoring unknown inventory type";
			}
			node->subscribe_inventory(
				std::bind(&session::inventory, this, _1, _2, node));
		}

		void session::new_tx_inventory(const hash_digest& tx_hash, channel_ptr node)
		{
			if (grabbed_invs_.exists(tx_hash))
				return;
			log_debug(LOG_SESSION)
				<< "Transaction inventory: " << encode_hex(tx_hash);
			// does it exist already
			// if not then issue getdata
			tx_pool_.exists(tx_hash,
				std::bind(&session::request_tx_data,
				this, _1, tx_hash, node));
			grabbed_invs_.store(tx_hash);
		}

		void session::get_data(const std::error_code& ec,
			const get_data_type& packet, channel_ptr node)
		{
			if (ec)
			{
				log_error(LOG_SESSION) << "get_data: " << ec.message();
				return;
			}
			// TODO: Implement.
			// simple stuff
			node->subscribe_get_data(
				std::bind(&session::get_data, this, _1, _2, node));
		}

		void session::get_blocks(const std::error_code& ec,
			const get_blocks_type& packet, channel_ptr node)
		{
			if (ec)
			{
				log_error(LOG_SESSION) << "get_blocks: " << ec.message();
				return;
			}
			// TODO: Implement.
			// send 500 invs from last fork point
			// have memory of last inv, ready to trigger send next 500 once
			// getdata done for it.
			node->subscribe_get_blocks(
				std::bind(&session::get_blocks, this, _1, _2, node));
		}

		void handle_send_get_data(const std::error_code& ec)
		{
			if (ec)
				log_error(LOG_SESSION) << "Requesting data: " << ec.message();
		}
		void session::request_tx_data(bool tx_exists,
			const hash_digest& tx_hash, channel_ptr node)
		{
			if (tx_exists)
				return;
			get_data_type request_tx;
			request_tx.inventories.push_back(
			{ inventory_type_id::transaction, tx_hash });
			node->send(request_tx, handle_send_get_data);
		}

	}
}


text:
package org.jivesoftware.smackx.iot.provisioning.element;

import javax.xml.namespace.QName;

import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.Objects;
import org.jivesoftware.smack.util.XmlStringBuilder;

import org.jxmpp.jid.BareJid;

public class Friend implements ExtensionElement {

    public static final String ELEMENT = "friend";
    public static final String NAMESPACE = Constants.IOT_PROVISIONING_NAMESPACE;
    public static final QName QNAME = new QName(NAMESPACE, ELEMENT);

    private final BareJid friend;

    public Friend(BareJid friend) {
        this.friend = Objects.requireNonNull(friend, "Friend must not be null");
    }

    @Override
    public String getElementName() {
        return ELEMENT;
    }

    @Override
    public String getNamespace() {
        return NAMESPACE;
    }

    @Override
    public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
        XmlStringBuilder xml = new XmlStringBuilder(this);
        xml.attribute("jid", friend);
        xml.closeEmptyElement();
        return xml;
    }

    public BareJid getFriend() {
        return friend;
    }

    public static Friend from(Message message) {
        return message.getExtension(Friend.class);
    }
}


text:
<?php
use Aluc\Common\Tools;

echo Tools::generarQr($get('reserva')->getCodigoSecreto());


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Microsoft.Extensions.DependencyInjection;
using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Domain.Apps.Entities.Contents.Commands;
using Squidex.Domain.Apps.Entities.Schemas;
using Squidex.Infrastructure;

namespace Squidex.Domain.Apps.Entities.Contents.DomainObject;

public sealed class ContentOperation : OperationContextBase<ContentCommand, IContentEntity>
{
    public ISchemaEntity Schema { get; init; }

    public ResolvedComponents Components { get; init; }

    public Schema SchemaDef
    {
        get => Schema.SchemaDef;
    }

    public ContentOperation(IServiceProvider serviceProvider, Func<IContentEntity> snapshot)
        : base(serviceProvider, snapshot)
    {
    }

    public static async Task<ContentOperation> CreateAsync(IServiceProvider services, ContentCommand command, Func<IContentEntity> snapshot)
    {
        var appProvider = services.GetRequiredService<IAppProvider>();

        var (app, schema) = await appProvider.GetAppWithSchemaAsync(command.AppId.Id, command.SchemaId.Id);

        if (app == null)
        {
            throw new DomainObjectNotFoundException(command.AppId.Id.ToString());
        }

        if (schema == null)
        {
            throw new DomainObjectNotFoundException(command.SchemaId.Id.ToString());
        }

        var components = await appProvider.GetComponentsAsync(schema);

        return new ContentOperation(services, snapshot)
        {
            App = app,
            Command = command,
            CommandId = command.ContentId,
            Components = components,
            Schema = schema
        };
    }
}


text:
var __decorate = this.__decorate || function (decorators, target, key, value) {
    var kind = typeof (arguments.length == 2 ? value = target : value);
    for (var i = decorators.length - 1; i >= 0; --i) {
        var decorator = decorators[i];
        switch (kind) {
            case "function": value = decorator(value) || value; break;
            case "number": decorator(target, key, value); break;
            case "undefined": decorator(target, key); break;
            case "object": value = decorator(target, key, value) || value; break;
        }
    }
    return value;
};
define(["require", "exports"], function (require, exports) {
    exports.data = {
        settings: {
            'numericRegex': /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/
        },
        messages: {
            'isRequired': 'wird benötigt',
            'AlphaNumericOrWhitespaceValidationRule': function (newValue, threshold) {
                return "darf nur alphanumerische Zeichen oder Leerzeichen beinhalten";
            },
            'AlphaNumericValidationRule': function (newValue, threshold) {
                return "darf nur alphanumerische Zeichen beinhalten";
            },
            'BetweenLengthValidationRule': function (newValue, threshold) {
                return "muss zwischen " + threshold.minimumLength + " und " + threshold.maximumLength + " Zeichen lang sein";
            },
            'BetweenValueValidationRule': function (newValue, threshold) {
                return "muss zwischen " + threshold.minimumValue + " und " + threshold.maximumValue + " sein";
            },
            'CustomFunctionValidationRule': function (newValue, threshold) {
                return "ist kein g\u00FCltiger Wert";
            },
            'DigitValidationRule': function (newValue, threshold) {
                return "darf nur Zahlen beinhalten";
            },
            'EmailValidationRule': function (newValue, threshold) {
                return "ist keine g\u00FCltige Email-Adresse";
            },
            'EqualityValidationRule': function (newValue, threshold) {
                if (threshold.otherValueLabel)
                    if (threshold.equality)
                        return "entspricht nicht " + threshold.otherValueLabel;
                    else
                        return "darf nicht mit " + threshold.otherValueLabel + " \u00FCbereinstimmen";
                else if (threshold.equality)
                    return "sollte " + threshold.otherValue + " sein";
                else
                    return "sollte nicht " + threshold.otherValue + " sein";
            },
            'InCollectionValidationRule': function (newValue, threshold) {
                return "ist kein g\u00FCltiger Wert";
            },
            'MinimumLengthValidationRule': function (newValue, threshold) {
                return "muss mindestens " + threshold + " Zeichen lang sein";
            },
            'MinimumValueValidationRule': function (newValue, threshold) {
                return "sollte " + threshold + " oder mehr sein";
            },
            'MaximumLengthValidationRule': function (newValue, threshold) {
                return "darf nicht l\u00E4nger als " + threshold + " Zeichen sein";
            },
            'MaximumValueValidationRule': function (newValue, threshold) {
                return "muss geringer als " + threshold + " sein";
            },
            'NumericValidationRule': function (newValue, threshold) {
                return "muss eine Nummer sein";
            },
            'RegexValidationRule': function (newValue, threshold) {
                return "ist kein g\u00FCltiger Wert";
            },
            'StrongPasswordValidationRule': function (newValue, threshold) {
                if (threshold == 4)
                    return "sollte eine Kombination aus Gro\u00DF- und Kleinbuchstaben, sowie Zahlen und Sonderzeichen enthalten";
                else
                    return "sollte zumindest " + threshold + " der folgenden Gruppen enthalten: Kleinbuchstaben, Gro\u00DFbuchstaben, Zahlen oder Sonderzeichen";
            }
        }
    };
});


text:
Domgen::Generator.define([:jackson],
                         "#{File.dirname(__FILE__)}/templates",
                         [Domgen::Java::Helper]) do |g|
  g.template_set(:jackson_date_util) do |template_set|
    template_set.erb_template(:repository,
                              'date_util.java.erb',
                              'main/java/#{repository.jackson.qualified_date_util_name.gsub(".","/")}.java')
  end

  g.template_set(:jackson_marshalling_tests) do |template_set|
    template_set.erb_template(:repository,
                              'marshalling_test.java.erb',
                              'test/java/#{repository.jackson.qualified_marshalling_test_name.gsub(".","/")}.java')
  end

  g.template_set(:jackson => [:jackson_date_util, :jackson_marshalling_tests])
end


text:
namespace {
const int kKeyboardHeightForTest = 100;
}  // namespace

class VirtualKeyboardWebContentTest : public InProcessBrowserTest {
 public:
  VirtualKeyboardWebContentTest() {}
  ~VirtualKeyboardWebContentTest() override {}

  void SetUp() override {
    ui::SetUpInputMethodFactoryForTesting();
    InProcessBrowserTest::SetUp();
  }

  // Ensure that the virtual keyboard is enabled.
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(
        keyboard::switches::kEnableVirtualKeyboard);
  }

  keyboard::KeyboardControllerProxy* proxy() {
    return keyboard::KeyboardController::GetInstance()->proxy();
  }

 protected:
  void FocusEditableNodeAndShowKeyboard(const gfx::Rect& init_bounds) {
    client.reset(new ui::DummyTextInputClient(ui::TEXT_INPUT_TYPE_TEXT));
    ui::InputMethod* input_method = proxy()->GetInputMethod();
    input_method->SetFocusedTextInputClient(client.get());
    input_method->ShowImeIfNeeded();
    // Mock window.resizeTo that is expected to be called after navigate to a
    // new virtual keyboard.
    proxy()->GetKeyboardWindow()->SetBounds(init_bounds);
  }

  void FocusNonEditableNode() {
    client.reset(new ui::DummyTextInputClient(ui::TEXT_INPUT_TYPE_NONE));
    ui::InputMethod* input_method = proxy()->GetInputMethod();
    input_method->SetFocusedTextInputClient(client.get());
  }

  void MockEnableIMEInDifferentExtension(const std::string& url,
                                         const gfx::Rect& init_bounds) {
    keyboard::SetOverrideContentUrl(GURL(url));
    keyboard::KeyboardController::GetInstance()->Reload();
    // Mock window.resizeTo that is expected to be called after navigate to a
    // new virtual keyboard.
    proxy()->GetKeyboardWindow()->SetBounds(init_bounds);
  }

  bool IsKeyboardVisible() const {
    return keyboard::KeyboardController::GetInstance()->keyboard_visible();
  }

 private:
  scoped_ptr<ui::DummyTextInputClient> client;

  DISALLOW_COPY_AND_ASSIGN(VirtualKeyboardWebContentTest);
};

// Test for crbug.com/404340. After enabling an IME in a different extension,
// its virtual keyboard should not become visible if previous one is not.
IN_PROC_BROWSER_TEST_F(VirtualKeyboardWebContentTest,
                       EnableIMEInDifferentExtension) {
  gfx::Rect test_bounds(0, 0, 0, kKeyboardHeightForTest);
  FocusEditableNodeAndShowKeyboard(test_bounds);
  EXPECT_TRUE(IsKeyboardVisible());
  FocusNonEditableNode();
  EXPECT_FALSE(IsKeyboardVisible());

  MockEnableIMEInDifferentExtension("chrome-extension://domain-1", test_bounds);
  // Keyboard should not become visible if previous keyboard is not.
  EXPECT_FALSE(IsKeyboardVisible());

  FocusEditableNodeAndShowKeyboard(test_bounds);
  // Keyboard should become visible after focus on an editable node.
  EXPECT_TRUE(IsKeyboardVisible());

  // Simulate hide keyboard by pressing hide key on the virtual keyboard.
  keyboard::KeyboardController::GetInstance()->HideKeyboard(
      keyboard::KeyboardController::HIDE_REASON_MANUAL);
  EXPECT_FALSE(IsKeyboardVisible());

  MockEnableIMEInDifferentExtension("chrome-extension://domain-2", test_bounds);
  // Keyboard should not become visible if previous keyboard is not, even if it
  // is currently focused on an editable node.
  EXPECT_FALSE(IsKeyboardVisible());
}

// Test for crbug.com/489366. In FLOATING mode, switch to a new IME in a
// different extension should exist FLOATIN mode and position the new IME in
// FULL_WIDTH mode.
IN_PROC_BROWSER_TEST_F(VirtualKeyboardWebContentTest,
                       IMEInDifferentExtensionNotCentered) {
  gfx::Rect test_bounds(0, 0, 0, kKeyboardHeightForTest);
  FocusEditableNodeAndShowKeyboard(test_bounds);
  keyboard::KeyboardController* controller =
      keyboard::KeyboardController::GetInstance();
  const gfx::Rect& screen_bounds = ash::Shell::GetPrimaryRootWindow()->bounds();
  gfx::Rect keyboard_bounds = controller->GetContainerWindow()->bounds();
  EXPECT_EQ(kKeyboardHeightForTest, keyboard_bounds.height());
  EXPECT_EQ(screen_bounds.height(),
            keyboard_bounds.height() + keyboard_bounds.y());
  controller->SetKeyboardMode(keyboard::FLOATING);
  // Move keyboard to a random place.
  proxy()->GetKeyboardWindow()->SetBounds(gfx::Rect(50, 50, 50, 50));
  EXPECT_EQ(gfx::Rect(50, 50, 50, 50),
            controller->GetContainerWindow()->bounds());

  MockEnableIMEInDifferentExtension("chrome-extension://domain-1", test_bounds);
  keyboard_bounds = controller->GetContainerWindow()->bounds();
  EXPECT_EQ(kKeyboardHeightForTest, keyboard_bounds.height());
  EXPECT_EQ(screen_bounds.height(),
            keyboard_bounds.height() + keyboard_bounds.y());
}


text:
Blesses css files using [blesscss](http://blesscss.com/)

Options for bless can be setup in your `Brocfile.js`

```js
var app = new EmberApp({
  bless: {
    enabled: true,
    cacheBuster: true,
    compress: false,
    force: false,
    imports: true
    // log: true  }
});
```

## Use in broccoli

```js
var bless = require('ember-cli-bless').blessCss;

tree = bless(inputTree, options);
```

## Installation

`ember install:npm ember-cli-bless`

## Running Tests

* `npm test`

[travis-badge]: https://travis-ci.org/jschilli/ember-cli-bless.svg?branch=master
[travis-badge-url]: https://travis-ci.org/jschilli/ember-cli-bless


text:
from unittest import TestCase
from rapt.treebrd.grammars.syntax import Syntax

class TestSyntax(TestCase):
    def test___init__when_operator_is_changed(self):
        new_op = 'test_op'
        self.assertEqual(new_op, Syntax(and_op=new_op).and_op)

    def test___init__cannot_set_unknown_attributes(self):
        self.assertFalse(hasattr(Syntax(foo='bar'), 'foo'))


text:
#include "handlers.hpp"
#include "../singleton.hpp"
#include "../packet.hpp"
#include "../const/account.hpp"

void Account_Reply(PacketReader reader)
{
    AccountReply reply = static_cast<AccountReply>(reader.GetShort());
    std::string reply_str = reader.GetEndString();

    if(reply_str == "OK")
    {
        if(reply == AccountReply::Continue)
        {
            puts("OK: Account name approved");

        }
        else if(reply == AccountReply::Created)
        {
            puts("OK: Account created");
        }
    }
    else if(reply_str == "NO")
    {
        std::string title =  "Could not create account";
        std::string message = "The reason is unknown.";

        if(reply == AccountReply::Exists)
        {
            puts("NO: Such account already exists");
            message = "Account with given name already exists.";
        }
        else if(reply == AccountReply::NotApproved)
        {
            puts("NO: account not approved");
            message = "Account has not been approved.";
        }
    }
}


text:
<?php

class model_users extends CI_Model {

	public function getUsers()
	{
	   return 'Sahil';
	}
}

?>


text:
package com.apexmob.skink.examples.helloworld;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import com.apexmob.skink.DefaultParser;
import com.apexmob.skink.Parser;
import com.apexmob.skink.Text;
import com.apexmob.skink.listeners.AbstractNodeListener;
import com.apexmob.skink.listeners.NodeListenerBuilder;

public class HelloWorldNode {

	public static void main(String[] args) {
		String html = "<!DOCTYPE html>
Hello World!
";
		InputStream htmlStream = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));

		Parser parser = new DefaultParser();
		parser.registerListener(
				NodeListenerBuilder.builder() //build the listener tree that will process node events
				.filterToAllTagsWithName("h1") //filter to just the "h1" element
				.addListener(new AbstractNodeListener() { //listen for the elements that make it past the filter
					@Override
					public void onText(Text text) {
						System.out.println(text.getContent());	//print the contents of the element to the System.out
					}
				})
				.build());

		try {
			parser.parse(htmlStream); //tell the parser to go!
		} catch (IOException e) {
			e.printStackTrace(); //do something better than this with exceptions
		} finally {
			try {
				htmlStream.close();
			} catch (IOException e) {
				//do nothing
			}
		}
	}
}


text:
package aho.uozu.uozubot.utils;

import bwapi.Game;
import bwapi.Player;
import bwapi.Unit;
import bwapi.UnitType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Set;

/**
 * Game state info in addition to / in a more useful format
 * than that available through BWAPI.
 */
public class GameState {
    private Game game;
    private Player player;
    private Map<UnitType, Set<Unit>> unitMap;
    private Map<UnitType, Set<Unit>> unitsUnderConstruction;
    private static GameState instance;

    private static final Logger log = LoggerFactory.getLogger(GameState.class);

    private GameState() {}

    /**
     * There's only one game state. Get it with this.
     */
    public static GameState getInstance(Game game, Player player) {
        if (instance == null) {
            instance = new GameState();
            instance.game = game;
            instance.player = player;
        }
        return instance;
    }

    public void update() {
        unitMap = Units.getUnitMap(player.getUnits());
        Set<Unit> eggs = unitMap.get(UnitType.Zerg_Egg);
        if (null != eggs) {
            unitsUnderConstruction = Units.getUnitsUnderConstruction(eggs);
        }
    }

    /**
     * Get all your units, mapped by UnitType. Includes buildings.
     */
    public Map<UnitType, Set<Unit>> getUnitMap() {
        return unitMap;
    }

    /**
     * Get all units under construction, mapped by UnitType.
     */
    public Map<UnitType, Set<Unit>> getUnitsUnderConstruction() {
        return unitsUnderConstruction;
    }
}


text:
class CreateTopics < ActiveRecord::Migration
  def change
    create_table :topics do |t|
      t.string :name
    end
  end
end


text:
/**
 * Контроллер меню для кнопки table.
 *
 * @author dew1983@mail.ru <Suvorov Andrey M.>
 */

Ext.define(
	'FBEditor.view.panel.main.editor.button.table.menu.MenuController',
	{
		extend: 'Ext.app.ViewController',
		alias: 'controller.main.editor.button.table.menu',

		/**
		 * Синхронизирует пункты меню с контекстом редактора текста.
		 */
		onSync: function ()
		{
			var me = this,
				view = me.getView(),
				menuItems;

			menuItems = view.query('main-editor-button-table-menu-item');

			Ext.Array.each(
				menuItems,
			    function (item)
			    {
				    item.fireEvent('sync');
			    }
			);
		}
	}
);