text:
module Alfred
  module Storage

    def self.create_ecosystem(name)
      Ecosystem.create(:name => name)
    end

    def self.create_project(ecosystem, repository, category_name, parent)
      project = Project.first_or_create(
        {:github_url => Github.project_url(repository['owner'], repository['name'])},
        {:parent => parent}
      )
      project.project_translations.create({
        :language    => Language['en_US'],
        :description => repository['description']
      })
      EcosystemProject.create(
        :ecosystem => ecosystem,
        :project => project
      )
      tag = Tag.first_or_create(:name => category_name)
      ProjectTag.first_or_create(:project => project, :tag => tag)
      ProjectCategory.first_or_create(:project => project, :tag => tag)
      project
    end

    def self.integrate_user(ecosystem, github_name, project, kind, commit_count = 0)
      user = create_user(github_name)
      create_ecosystem_member(ecosystem, user)
      create_involvement(project, user, kind, commit_count)
      user
    end

    def self.create_user(github_name)
      user = Person.first_or_new(:github_name => github_name)
      return user if user.saved?

      details       = fetch_json(Github.user_url(github_name), 1)

      user.email    = details['user']['email']
      user.name     = details['user']['name']
      user.company  = details['user']['company']
      user.location = details['user']['location']
      user.blog     = details['user']['blog']

      user.save
      puts "ALFRED: --> created user #{github_name}"
      user
    end

    def self.create_involvement(project, user, kind, commit_count = 0)
      Involvement.first_or_create(
        {:project => project, :user => user, :kind => kind},
        {:commit_count => commit_count}
      )
    end

    def self.create_ecosystem_member(ecosystem, user)
      user = user.is_a?(String) ? create_user(user) : user
      EcosystemMember.first_or_create(:ecosystem => ecosystem, :user => user)
    end

  end # module Storage
end # module Alfred


text:
Configuration is accomplished by modifying the **appsettings.json** file that comes with the InEngine.NET binary distribution.
The **-c, --configuration** argument can also be used to specify an alternate configuration file.

```json
{
  "InEngine": {
    "Plugins": {
      "MyPlugin": "/path/to/plugin/assembly"
    },
    "ExecWhitelist": {
      "foo": "/path/to/foo.exe"
    },
    "Mail": {
      "Host": "localhost",
      "Port": 25,
      "From": "no-reply@inengine.net"
    },
    "Queue": {
      "UseCompression": false,
      "PrimaryQueueConsumers": 4,
      "SecondaryQueueConsumers": 2,
      "QueueDriver": "rabbitmq",
      "QueueName": "InEngineQueue",
      "Redis": {
        "Host": "127.0.0.1",
        "Port": 6379,
        "Database": 0,
        "Password": ""
      },
      "RabbitMQ": {
        "Host": "localhost",
        "Port": 5672,
        "Username": "",
        "Password": ""
      },
      "File": {
        "BasePath": "../"
      }
    }
  }
}

```

## Top-level Settings

| Setting                   | Type              | Description                                                                                |
| ------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Plugins                   | object            | A set of key/value pairs, where the value is the directory where the plugin is located and the key is the plugin name sans .dll extension. |
| ExecWhitelist             | object            | A set of key/value pairs, where the value is the file system path of an executable and the key is a command alias.                         |

## Mail Settings

| Setting   | Type      | Description                                           |
| --------- | --------- | ----------------------------------------------------- |
| Host      | string    | The hostname of an SMTP server.                       |
| Port      | integer   | The port of an SMTP server.                           |
| From      | string    | The default email address used to send email from.    |

## Queue Settings

### General Settings

| Setting                   | Type      | Description                                                           |
| ------------------------- | --------- | --------------------------------------------------------------------- |
| UseCompression            | bool      | A situation performance optimization that compresses queued messages. |
| PrimaryQueueConsumers     | string    | The number of consumers to schedule for the secondary queue.          |
| SecondaryQueueConsumers   | string    | The number of consumers to schedule for the secondary queue.          |
| QueueDriver               | string    | The driver to use to interact with a queue data store.                |
| QueueName                 | string    | The base name of the queue, used to form the Redis Queue keys.        |

### RabbitMQ

| Setting                   | Type      | Description                                                           |
| ------------------------- | --------- | --------------------------------------------------------------------- |
| Host                      | string    | The RabbitMQ hostname to connect to.                                  |
| Port                      | integer   | RabbitMQ's port.                                                      |
| Username                  | string    | The RabbitMQ username to authenticate with.                           |
| Password                  | string    | The RabbitMQ password to authenticate with.                           |

### Redis

| Setting                   | Type      | Description                                                           |
| ------------------------- | --------- | --------------------------------------------------------------------- |
| Host                      | string    | The Redis hostname to connect to.                                     |
| Port                      | integer   | Redis's port.                                                         |
| Database                  | integer   | The Redis database - 0-15.                                            |
| Password                  | string    | The Redis auth password.                                              |

### File

| Setting                   | Type      | Description                                                           |
| ------------------------- | --------- | --------------------------------------------------------------------- |
| BasePath                  | string    | The file system path where the queue directories should be located.   |

## Logging Settings

Any exceptions thrown by a command will be logged, provided NLog is configured to log exceptions.
The [NLog configuration](https://github.com/NLog/NLog/wiki/Tutorial#configuration) file needs to be setup with something like this:

```xml
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="logfile" xsi:type="File" fileName="inengine.log" />
    </targets>

    <rules>
        <logger name="*" minlevel="Error" writeTo="logfile" />
    </rules>
</nlog>
```

InEngine.Core does not depend explicitly on NLog, but rather [Common.Logging](http://net-commons.github.io/common-logging/).
This means that any logging framework that Common.Logging supports can be used.
Configuring Common.Logging to use a different logging framework is out of the scope of this documentation.

redpajama_set_name: RedPajamaGithub


text:
module Gollum
=begin
  FileView requires that:
    - All files in root dir are processed first
    - Then all the folders are sorted and processed
=end
  class FileView
    # common use cases:
    # set pages to wiki.pages and show_all to false
    # set pages to wiki.pages + wiki.files and show_all to true
    def initialize pages, options = {}
      @pages    = pages
      @show_all = options[:show_all] || false
      @checked  = options[:collapse_tree] ? '' : "checked"
    end

    def enclose_tree string
      %Q(
\n) + string + %Q(
)
    end

    def new_page page
      name = page.name
      url  = url_for_page page
      %Q(
#{name}
)
    end

    def new_folder folder_path
      new_sub_folder folder_path
    end

    def new_sub_folder path
      <<-HTML

        #{path} <input type="checkbox" #{@checked} />

      HTML
    end

    def end_folder
      "

\n"
    end

    def url_for_page page
      url = ''
      dir = ::File.join(::File.dirname(page.path).split('/').map { |d| CGI.escape(d) })
      if @show_all
        # Remove ext for valid pages.
        filename = page.filename
        filename = Page::valid_page_name?(filename) ? filename.chomp(::File.extname(filename)) : filename

        url = ::File.join(dir, CGI.escape(filename))
      else
        url = ::File.join(dir, CGI.escape(page.filename_stripped))
      end
      url = url[2..-1] if url[0, 2] == './'
      url
    end

    def render_files
      html         = ''

      # keep track of folder depth, 0 = at root.
      prev_folders = ['.']

      # process rest of folders
      @pages.each do |page|
        path   = page.path
        folder = ::File.dirname path

        current_folders = folder.split '/'
        max_depth = [prev_folders.size, current_folders.size].max - 1
        (0..max_depth).each do |depth|
          next if prev_folders[depth] == current_folders[depth]

          if prev_folders[depth].nil?
            (max_depth - depth + 1).times do |index|
              html += new_sub_folder current_folders[depth + index]
            end
            break
          end

          if current_folders[depth].nil?
            (max_depth - depth + 1).times do
              html += end_folder
            end
            break
          end

          if prev_folders[depth] != '.'
            (prev_folders.size - depth).times do
              html += end_folder
            end
          end
          if current_folders[depth] != '.'
            (current_folders.size - depth).times do |index|
              html += new_sub_folder current_folders[depth + index]
            end
          end
          break
        end

        html         += new_page page
        prev_folders  = current_folders
      end

      # return the completed html
      enclose_tree html
    end # end render_files
  end # end FileView class
end # end Gollum module


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using OrchardCore.Recipes.Models;
using OrchardCore.Recipes.Services;
using OrchardCore.Security;
using OrchardCore.Security.Permissions;

namespace OrchardCore.Roles.Recipes
{
    /// <summary>
    /// This recipe step creates a set of roles.
    /// </summary>
    public class RolesStep : IRecipeStepHandler
    {
        private readonly RoleManager<IRole> _roleManager;

        public RolesStep(RoleManager<IRole> roleManager)
        {
            _roleManager = roleManager;
        }

        public async Task ExecuteAsync(RecipeExecutionContext context)
        {
            if (!String.Equals(context.Name, "Roles", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var model = context.Step.ToObject<RolesStepModel>();

            foreach (var importedRole in model.Roles)
            {
                if (String.IsNullOrWhiteSpace(importedRole.Name))
                    continue;

                var role = (Role)await _roleManager.FindByNameAsync(importedRole.Name);
                var isNewRole = role == null;

                if (isNewRole)
                {
                    role = new Role { RoleName = importedRole.Name };
                }

                role.RoleDescription = importedRole.Description;
                role.RoleClaims.RemoveAll(c => c.ClaimType == Permission.ClaimType);
                role.RoleClaims.AddRange(importedRole.Permissions.Select(p => new RoleClaim { ClaimType = Permission.ClaimType, ClaimValue = p }));

                if (isNewRole)
                {
                    await _roleManager.CreateAsync(role);
                }
                else
                {
                    await _roleManager.UpdateAsync(role);
                }
            }
        }

        public class RolesStepModel
        {
            public RolesStepRoleModel[] Roles { get; set; }
        }
    }

    public class RolesStepRoleModel
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string[] Permissions { get; set; }
    }
}


text:
<?php

namespace Symfony\Tests\Component\HttpKernel\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MemoryDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    public function testCollect()
    {
        $c = new MemoryDataCollector();

        $c->collect(new Request(), new Response());

        $this->assertInternalType('integer',$c->getMemory());
        $this->assertSame('memory',$c->getName());
    }

}


text:
import os
import jinja2
from copy import copy
from termcolor import colored

from nepho.core import provider_factory

class Scenario:
    """
    A scenario is an ephemeral amalgamation of a cloudlet blueprint, collected
    parameters, and the "live" filesystem, suitable for bringing up a stack.
    """

    def __init__(self, blueprint, stored_params, user_params, name):
        self.blueprint = blueprint
        self.stored_params = stored_params.to_dict()
        self.user_params = user_params
        self.name = name

        try:
            self.cloudlet = self.blueprint.cloudlet
        except AttributeError:
            print colored('Error: ', 'red') + 'could not find specified cloudlet and blueprint.'
            exit(1)
        self.provider_name = self.blueprint.provider_name

        pfactory = provider_factory.ProviderFactory()
        self.provider = pfactory.init(self.provider_name, self.stored_params, self)

    @property
    def context(self):
        """
        Generates a context object to be injected into the templating engine.
        """
        self.context = dict()
        self.context['parameters'] = dict()

        # Inheritance is Provider -> Cloudlet -> Blueprint -> Stored -> User
        # Only parameters defined by the provider, cloudlet, or blueprint are
        # passed into the context, even if they are stored or passed by the user.
        if self.provider.params is not None:
            for (k, v) in self.provider.params.items():
                self.context['parameters'][k] = v
        if "parameters" in self.cloudlet.definition:
            try:
                for (k, v) in self.cloudlet.definition['parameters'].items():
                    self.context['parameters'][k] = v
            except:
                pass
        if "parameters" in self.blueprint.definition:
            try:
                for (k, v) in self.blueprint.definition['parameters'].items():
                    self.context['parameters'][k] = v
            except:
                pass

        if self.stored_params is not None:
            try:
                for (k, v) in self.stored_params.items():
                    if k in self.context['parameters']:
                        self.context['parameters'][k] = v
            except:
                pass
        if self.user_params is not None:
            try:
                for (k, v) in self.user_params.items():
                    if k in self.context['parameters']:
                        self.context['parameters'][k] = v
            except:
                pass

        # Provide a limited/cleaned set of values from cloudlet.yaml and blueprint.yaml
        if self.blueprint is not None:
            c = self.cloudlet.definition
            b = self.blueprint.definition

            self.context['cloudlet'] = {
                'name': c['name'],
                'format': c['format'],
                'path': c['path'],
                'version': c['version'],
            }
            self.context['blueprint'] = {
                'name': b['name'],
                'provider': b['provider'],
            }

            # Backwards compatibility
            self.context['scripts'] = None

        return self.context

    @property
    def template(self):
        """
        Load a blueprint template, generate a context, and return the rendered
        Jinja2 template.
        """

        # Templates may be composed of multiple files in the template_path
        # location as well as a provider-specific common template location
        template_path = os.path.join(
            self.cloudlet.path, 'resources', self.blueprint.name,
            self.provider.TEMPLATE_FILENAME)
        template_common_dir = os.path.join(
            self.cloudlet.path, 'resources', 'common', self.provider.PROVIDER_ID)

        template_filename = os.path.basename(template_path)
        template_dirs = [template_common_dir, os.path.dirname(template_path)]

        # Initialize Jinja2
        jinjaFSloader = jinja2.FileSystemLoader(template_dirs)
        jinja_env = jinja2.Environment(loader=jinjaFSloader)

        # Output parameters as env variables
        @jinja2.contextfunction
        def export_env_vars(context):
            p = context['parameters'].copy()
            # Don't include secret key
            if 'AWSSecretAccessKey' in p:
                del p['AWSSecretAccessKey']
            return p

        jinja_env.globals['env_vars'] = export_env_vars
        jinja_env.globals['callable'] = callable

        jinja_template = jinja_env.get_template(template_filename)

        # Render the template
        self.template = None
        try:
            self.template = jinja_template.render(self.context)
        except jinja2.TemplateNotFound as e:
            print colored('Error: ', 'red') + 'could not find template file "%s"' % (e)
            print "Template search path is:"
            for dir in template_dirs:
                print "    " + dir
            exit(1)

        return self.template


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Anchorific Test Suite</title>
 <link rel="stylesheet" href="vendor/qunit.css">

Hello World!

Header with existing ID

The Lannisters

Tywin Lannister

Cersei Lannister

Joffrey Baratheon

Ser Boros Blount

Kingsguard

Ser Arthur Dayne

Ashara Dayne

Myrcella Baratheon

The Starks

Ned Stark

Jon Snow

Catelyn Stark


text:
import {
    DeclarativeMutationConfig,
    Disposable,
    GraphQLTaggedNode,
    IEnvironment,
    MutationConfig,
    MutationParameters,
    PayloadError,
    SelectorStoreUpdater,
    UploadableMap,
    VariablesOf,
} from 'relay-runtime';

export interface UseMutationConfig<TMutation extends MutationParameters> {
    variables: VariablesOf<TMutation>;
    updater?: SelectorStoreUpdater<TMutation['response']> | null | undefined;
    uploadables?: UploadableMap | undefined;
    optimisticUpdater?: SelectorStoreUpdater<TMutation['response']> | null | undefined;
    optimisticResponse?: TMutation['rawResponse'] | undefined;
    configs?: DeclarativeMutationConfig[] | undefined;
    onError?: ((error: Error) => void | null) | undefined;
    onCompleted?: ((response: TMutation['response'], errors: PayloadError[]) => void | null) | undefined;
    onUnsubscribe?: (() => void | null) | undefined;
}

export function useMutation<TMutation extends MutationParameters>(
    mutation: GraphQLTaggedNode,
    commitMutationFn?: (environment: IEnvironment, config: MutationConfig<TMutation>) => Disposable,
): [(config: UseMutationConfig<TMutation>) => Disposable, boolean];


text:
/*global Backbone */
var app = app || {};

(function () {
    'use strict';

    // Labels
    // -------------------------
    app.Labels = Backbone.Collection.extend({
        model: app.Label,

        initialize: function() {
            _.bindAll(this, 'isDupe', 'addLabelsFromIssues');
        },

        isDupe: function(name) {
            var self = this;
            return self.any(function(issue) {
                return issue.get('name') === name;
            });
        },

        addLabelsFromIssues: function(issues) {
            var self = this;

            // Iterate through each issue's label array.
            _.each(issues, function(issue) {
                _.each((issue.get('labels') || []), function(label) {
                    // If the label has a name and is not in the collection
                    // yet, add it!
                    if (label.name && !self.isDupe(label.name)) {
                        self.add(new app.Label(label));
                    }
                });
            });
        }
    });
})();


text:
package docker

import (
	"fmt"
	"github.com/dotcloud/docker/utils"
	"os"
	"os/exec"
	"path/filepath"
	"syscall"
	"time"
)

func Unmount(target string) error {
	if err := exec.Command("auplink", target, "flush").Run(); err != nil {
		utils.Errorf("[warning]: couldn't run auplink before unmount: %s", err)
	}
	if err := syscall.Unmount(target, 0); err != nil {
		return err
	}
	// Even though we just unmounted the filesystem, AUFS will prevent deleting the mntpoint
	// for some time. We'll just keep retrying until it succeeds.
	for retries := 0; retries < 1000; retries++ {
		err := os.Remove(target)
		if err == nil {
			// rm mntpoint succeeded
			return nil
		}
		if os.IsNotExist(err) {
			// mntpoint doesn't exist anymore. Success.
			return nil
		}
		// fmt.Printf("(%v) Remove %v returned: %v\n", retries, target, err)
		time.Sleep(10 * time.Millisecond)
	}
	return fmt.Errorf("Umount: Failed to umount %v", target)
}

func Mounted(mountpoint string) (bool, error) {
	mntpoint, err := os.Stat(mountpoint)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
	parent, err := os.Stat(filepath.Join(mountpoint, ".."))
	if err != nil {
		return false, err
	}
	mntpointSt := mntpoint.Sys().(*syscall.Stat_t)
	parentSt := parent.Sys().(*syscall.Stat_t)
	return mntpointSt.Dev != parentSt.Dev, nil
}


text:
""" View for cleaner buildout calls """
from pyramid.view import view_config
from pyramid_duh import addslash

from pypicloud.route import PackagesResource
from pypicloud.views.simple import packages_to_dict

@view_config(context=PackagesResource, request_method='GET', subpath=(),
             renderer='packages.jinja2')
@addslash
def list_packages(request):
    """ Render the list for all versions of all packages """
    names = request.db.distinct()
    # remove the ones that you are not allowed to see
    names = filter(lambda x: request.access.has_permission(x, 'read'),
                   names)
    packages = []
    for package_name in names:
        packages += request.db.all(package_name)
    return {'pkgs': packages_to_dict(request, packages)}


text:
import { CashFlowPage } from './app.po';

describe('cash-flow App', () => {
  let page: CashFlowPage;

  beforeEach(() => {
    page = new CashFlowPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('cf works!');
  });
});


text:
- I've been accepted as a student volunteer for [PLDI!](https://pldi18.sigplan.org/).
- This is *fantastic* news, as the conference is all about optimization of compilers, correctness, verfication
  and implementation of programming langauges and compiler design!
- It's also in Philadelphia, a city I've never visited! :D

## And...A little Haskell
- A brief post about this, since it was a little annoying.
- Over the next week, I'm working through [LYAH](http://learnyouahaskell.com/chapters) (I did it last year, but it's surprising how much it looked
  like Greek back then compared to now!) and then continuing with [Haskellbook](http://haskellbook.com/).
- In between, I'll be making simple things like Text games that can be run on the command line and stuff like that in Haskell.
- The goal is to work on buildable stuff in Haskell, and eventually work my way up to larger and larger code-bases in Haskell.
- Oh, I also got [Snoyman's Yesod book](https://www.amazon.com/Developing-Web-Applications-Haskell-Yesod/dp/1449316972), so I may post some of my work on that as well.

## I was Haskelling along...
- When suddenly...

## DUN DUN DUN!!!!!

- Ahh..ahh..panic! What's the first thing you do!?
- [You ](https://groups.google.com/forum/#!topic/leksah/GTorsYE4E2M)[Read](https://www.haskell.org/cabal/FAQ.html) [a](https://www.reddit.com/r/haskell/comments/54caag/help_understanding_hidden_modules/) [gajillion](https://www.reddit.com/r/haskell/comments/3v490e/could_not_find_module_datatext/) [GSearches](https://stackoverflow.com/questions/39683998/could-not-find-module-data-map) [on](https://downloads.haskell.org/~ghc/master/users-guide/packages.html) [how](https://stackoverflow.com/questions/31593438/how-can-packages-be-unhidden-when-using-only-stack) [to](https://stackoverflow.com/questions/39683998/could-not-find-module-data-map) [solve](https://stackoverflow.com/questions/46534212/can-not-find-module-after-installing-it) [it]()[!](https://stackoverflow.com/questions/16565880/where-can-i-find-a-complete-list-of-the-haskell-modules)
- Actually *no*...don't do that. That's what I'd do! Read the error message again.
- Take a deep breath

## Ohh....
- I have to change the cabal file (note my project's name is "my-haskell")

- Like so. ```Data.Map``` is part of a module called "containers", so we'll need to add *that* to our cabal build file.

- Then ```stack build```

- Then ```stack ghci```

- Then...look at that...looks like it's Chocolate Lambdas again! :D

## I've actually discovered
- I'm happiest working with FP languages, particularly with Haskell.
  When I'm stuck, I'm willing to spend the time to figure things out. It's challenging but fun!
- Oh, you can laugh at me all you like, this *is* using Stack on Windows :D
- I have another machine at home that has Stack and Cabal on Linux, but this one has a nice big screen
  and it works, so...
- Also, yeah, that *is* notepad++. It's a stripped-down version of learning Haskell, which I'm OK with doing.

## And so...
- I have some stuff in the works, but I'll roll them out as I find out more.
- I'm spending my entire weekend doing Haskell. Next Saturday I have race training, but otherwise it's all Haskell
  and preparing for my GRE.
- Oh, there's the [LA PureScript meetup!](https://www.meetup.com/LA-PureScript/events/249209149/) I'm going to that on the 10th!
- And I plan on attending both BayHac and LambdaConf, of course :D

## Things of Note
- [Hackage](https://hackage.haskell.org/package/containers-0.5.11.0/docs/Data-Map-Strict.html), [Hoogle](https://www.haskell.org/hoogle/?hoogle=nub) and [HaskellWiki](https://wiki.haskell.org/Haskell) really helped, as did [SO](https://stackoverflow.com/questions/tagged/haskell).

## And that's about it!


text:
namespace ui {
class OverlaySurfaceCandidate;

// Ozone DRM extension of the OverlayManagerOzone interface. It queries the
// DrmDevice to see if an overlay configuration will work and keeps an MRU cache
// of recent configurations.
class DrmOverlayManager : public OverlayManagerOzone {
 public:
  explicit DrmOverlayManager(
      bool allow_sync_and_real_buffer_page_flip_testing = true);

  DrmOverlayManager(const DrmOverlayManager&) = delete;
  DrmOverlayManager& operator=(const DrmOverlayManager&) = delete;

  ~DrmOverlayManager() override;

  // OverlayManagerOzone:
  std::unique_ptr<OverlayCandidatesOzone> CreateOverlayCandidates(
      gfx::AcceleratedWidget w) override;

  // Called when notified by the DRM thread of a display configuration change.
  // Resets the cache of OverlaySurfaceCandidates and if they can be displayed
  // as an overlay. Requests an updated HardwareCapabilities for any observing
  // OverlayProcessors.
  void DisplaysConfigured();

  // Checks if overlay candidates can be displayed as overlays. Modifies
  // |candidates| to indicate if they can.
  void CheckOverlaySupport(std::vector<OverlaySurfaceCandidate>* candidates,
                           gfx::AcceleratedWidget widget);

  void StartObservingHardwareCapabilities(
      gfx::AcceleratedWidget widget,
      HardwareCapabilitiesCallback receive_callback);
  void StopObservingHardwareCapabilities(gfx::AcceleratedWidget widget);

  virtual void GetHardwareCapabilities(
      gfx::AcceleratedWidget widget,
      HardwareCapabilitiesCallback& receive_callback) = 0;

  // Should be called by the overlay processor to indicate if a widget has a
  // candidate that requires an overlay. This is to prioritize which display
  // gets the overlay in a multiple display environment.
  void RegisterOverlayRequirement(gfx::AcceleratedWidget widget,
                                  bool requires_overlay);

 protected:
  // Sends a request to see if overlay configuration will work. Implementations
  // should call UpdateCacheForOverlayCandidates() with the response.
  virtual void SendOverlayValidationRequest(
      const std::vector<OverlaySurfaceCandidate>& candidates,
      gfx::AcceleratedWidget widget) = 0;

  // Similar to SendOverlayValidationRequest() but instead of calling
  // UpdateCacheForOverlayCandidates(), returns the result synchronously.
  virtual std::vector<OverlayStatus> SendOverlayValidationRequestSync(
      const std::vector<OverlaySurfaceCandidate>& candidates,
      gfx::AcceleratedWidget widget) = 0;

  // Perform basic validation to see if |candidate| is a valid request.
  bool CanHandleCandidate(const OverlaySurfaceCandidate& candidate,
                          gfx::AcceleratedWidget widget) const;

  // Updates the MRU cache for overlay configuration |candidates| with |status|.
  void UpdateCacheForOverlayCandidates(
      const std::vector<OverlaySurfaceCandidate>& candidates,
      const gfx::AcceleratedWidget widget,
      const std::vector<OverlayStatus>& status);

 private:
  // Value for the request cache, that keeps track of how many times a
  // specific validation has been requested, if there is a GPU validation
  // in flight, and at last the result of the validation.
  struct OverlayValidationCacheValue {
    OverlayValidationCacheValue();
    OverlayValidationCacheValue(OverlayValidationCacheValue&& other);
    ~OverlayValidationCacheValue();
    OverlayValidationCacheValue& operator=(OverlayValidationCacheValue&& other);

    int request_num = 0;
    std::vector<OverlayStatus> status;
  };

  using OverlayCandidatesListCache =
      base::LRUCache<std::vector<OverlaySurfaceCandidate>,
                     OverlayValidationCacheValue>;

  // Map of each widget to the cache of list of all OverlaySurfaceCandidate
  // instances which have been requested for validation and/or validated.
  std::map<gfx::AcceleratedWidget, OverlayCandidatesListCache>
      widget_cache_map_;

  base::flat_set<gfx::AcceleratedWidget> widgets_with_required_overlays_;

  std::map<gfx::AcceleratedWidget, HardwareCapabilitiesCallback>
      hardware_capabilities_callbacks_;

  THREAD_CHECKER(thread_checker_);
};

}  // namespace ui

#endif  // UI_OZONE_PLATFORM_DRM_GPU_DRM_OVERLAY_MANAGER_H_


text:
use render::uniform_wrappers::{UMatrix4};
use render::uniforms::{ShadowUniforms};

#[derive(Clone)]
pub struct RenderUniforms {
	pub shadow:                UMatrix4,
	pub model:                 UMatrix4,
	pub model_view_projection: UMatrix4,
}

impl ShadowUniforms for RenderUniforms {
	fn shadow_matrix(&self) -> &UMatrix4 { &self.shadow }
}


text:
package me.qyh.blog.plugin.comment.data;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import me.qyh.blog.core.context.Environment;
import me.qyh.blog.core.exception.LogicException;
import me.qyh.blog.plugin.comment.entity.Comment.CommentStatus;
import me.qyh.blog.plugin.comment.entity.CommentMode;
import me.qyh.blog.plugin.comment.entity.CommentModule;
import me.qyh.blog.plugin.comment.service.CommentService;
import me.qyh.blog.plugin.comment.vo.CommentPageResult;
import me.qyh.blog.plugin.comment.vo.CommentQueryParam;
import me.qyh.blog.template.render.data.DataTagProcessor;

public class CommentsDataTagProcessor extends DataTagProcessor<CommentPageResult> {
	@Autowired
	private CommentService commentService;

	public CommentsDataTagProcessor(String name, String dataName) {
		super(name, dataName);
	}

	@Override
	protected CommentPageResult query(Attributes attributes) throws LogicException {
		CommentQueryParam param = new CommentQueryParam();

		String moduleTypeStr = attributes.getString("moduleType").orElse(null);
		String moduleIdStr = attributes.getString("moduleId").orElse(null);
		if (moduleIdStr != null && moduleTypeStr != null) {
			try {
				param.setModule(new CommentModule(moduleTypeStr, Integer.parseInt(moduleIdStr)));
			} catch (Exception e) {
				LOGGER.debug(e.getMessage(), e);
			}
		}

		param.setMode(attributes.getEnum("mode", CommentMode.class).orElse(CommentMode.LIST));
		param.setAsc(attributes.getBoolean("asc").orElse(true));
		param.setCurrentPage(attributes.getInteger("currentPage").orElse(0));
		param.setPageSize(attributes.getInteger("pageSize").orElse(0));

		if (param.getCurrentPage() < 0) {
			param.setCurrentPage(0);
		}

		int pageSize = commentService.getCommentConfig().getPageSize();
		if (param.getPageSize() < 1 || param.getPageSize() > pageSize) {
			param.setPageSize(pageSize);
		}

		param.setStatus(!Environment.isLogin() ? CommentStatus.NORMAL : null);

		return commentService.queryComment(param);
	}

	@Override
	public List<String> getAttributes() {
		return List.of("moduleType", "moduleId", "mode", "asc", "currentPage", "pageSize");
	}

}


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
null

#### Original name
Centaurea pythiae Azn. & Bornm.

### Remarks
null


text: sudo apt-get -y install goofile


text:
package org.seasar.doma.internal.expr.node;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.seasar.doma.internal.expr.EvaluationResult;
import org.seasar.doma.internal.expr.ExpressionEvaluator;

public class OrOperatorNodeTest {

  protected final ExpressionLocation location = new ExpressionLocation("", 0);

  protected final LiteralNode trueLiteral = new LiteralNode(location, "true", true, boolean.class);

  protected final LiteralNode falseLiteral =
      new LiteralNode(location, "false", false, boolean.class);

  protected final LiteralNode nullLiteral = new LiteralNode(location, "null", null, Object.class);

  @Test
  public void test_true_true() {
    OrOperatorNode node = new OrOperatorNode(location, "||");
    node.setLeftNode(trueLiteral);
    node.setRightNode(trueLiteral);
    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    EvaluationResult evaluationResult = evaluator.evaluate(node);
    assertTrue(evaluationResult.getBooleanValue());
  }

  @Test
  public void test_true_false() {
    OrOperatorNode node = new OrOperatorNode(location, "||");
    node.setLeftNode(trueLiteral);
    node.setRightNode(falseLiteral);
    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    EvaluationResult evaluationResult = evaluator.evaluate(node);
    assertTrue(evaluationResult.getBooleanValue());
  }

  @Test
  public void test_false_true() {
    OrOperatorNode node = new OrOperatorNode(location, "||");
    node.setLeftNode(falseLiteral);
    node.setRightNode(trueLiteral);
    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    EvaluationResult evaluationResult = evaluator.evaluate(node);
    assertTrue(evaluationResult.getBooleanValue());
  }

  @Test
  public void test_false_false() {
    OrOperatorNode node = new OrOperatorNode(location, "||");
    node.setLeftNode(falseLiteral);
    node.setRightNode(falseLiteral);
    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    EvaluationResult evaluationResult = evaluator.evaluate(node);
    assertFalse(evaluationResult.getBooleanValue());
  }

  @Test
  public void test_null_null() {
    OrOperatorNode node = new OrOperatorNode(location, "||");
    node.setLeftNode(nullLiteral);
    node.setRightNode(nullLiteral);
    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    EvaluationResult evaluationResult = evaluator.evaluate(node);
    assertFalse(evaluationResult.getBooleanValue());
  }

  @Test
  public void test_null_true() {
    OrOperatorNode node = new OrOperatorNode(location, "||");
    node.setLeftNode(nullLiteral);
    node.setRightNode(trueLiteral);
    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    EvaluationResult evaluationResult = evaluator.evaluate(node);
    assertTrue(evaluationResult.getBooleanValue());
  }

  @Test
  public void test_true_null() {
    OrOperatorNode node = new OrOperatorNode(location, "||");
    node.setLeftNode(trueLiteral);
    node.setRightNode(nullLiteral);
    ExpressionEvaluator evaluator = new ExpressionEvaluator();
    EvaluationResult evaluationResult = evaluator.evaluate(node);
    assertTrue(evaluationResult.getBooleanValue());
  }
}


text:
package io.druid.indexing.common.actions;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import io.druid.indexing.common.TaskLock;
import io.druid.indexing.common.task.Task;
import org.joda.time.Interval;

public class LockTryAcquireAction implements TaskAction<TaskLock>
{
  @JsonIgnore
  private final Interval interval;

  @JsonCreator
  public LockTryAcquireAction(
      @JsonProperty("interval") Interval interval
  )
  {
    this.interval = interval;
  }

  @JsonProperty
  public Interval getInterval()
  {
    return interval;
  }

  @Override
  public TypeReference<TaskLock> getReturnTypeReference()
  {
    return new TypeReference<TaskLock>()
    {
    };
  }

  @Override
  public TaskLock perform(Task task, TaskActionToolbox toolbox)
  {
    return toolbox.getTaskLockbox().tryLock(task, interval).orNull();
  }

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

  @Override
  public String toString()
  {
    return "LockTryAcquireAction{" +
           "interval=" + interval +
           '}';
  }
}


text:
starter.controller('TimeLineController', function (getsetDashboard,$rootScope, $scope, $ionicSlideBoxDelegate, $ionicModal, $ionicHistory, notification, $location, $timeout, getsetService, authService, localStorageService, $window, $ionicPopup, XrmServiceToolkit_Soap) {
    $scope.authentication = localStorageService.get('LoggedUser');
    $scope.showAlert = function () {
        $rootScope.hide();
        var alertPopup = $ionicPopup.alert({
            title: 'attention!',
            template: 'Token expire Log in again'
        });
        alertPopup.then(function (res) {
            $scope.Session = {
                "url": $scope.authentication.url, "username": $scope.authentication.username, "password": $scope.authentication.password, "customername": $scope.authentication.customername, "email": $scope.authentication.email, "mobile": $scope.authentication.mobile, "Active": $scope.authentication.Active, "rememberme": true
            };
            localStorageService.remove('LoggedUser');
            localStorageService.set('LoggedUser', $scope.Session);
            $window.location.href = ('#/app/signin');
            $rootScope.hide();
        });
        $timeout(function () {
            alertPopup.close();
        }, 3000);
    };
    var pagecount = 1;
    $scope.Data = [];
    try {
        if ($scope.authentication.isvisible == true) {
            $rootScope.show('Please wait..');
            Personalwall();
        }
        else {
            $scope.showAlert();
        }
        function Personalwall() {
            var strVar = "";
            strVar += " <request xmlns:a=\"http:\/\/schemas.microsoft.com\/xrm\/2011\/Contracts\" xmlns:i=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" i:type=\"a:OrganizationRequest\">";
            strVar += "            <a:Parameters xmlns:b=\"http:\/\/schemas.datacontract.org\/2004\/07\/System.Collections.Generic\">";
            strVar += "               <a:KeyValuePairOfstringanyType>";
            strVar += "                  <b:key>PageSize<\/b:key>";
            strVar += "                  <b:value xmlns:d=\"http:\/\/www.w3.org\/2001\/XMLSchema\" i:type=\"d:int\">20<\/b:value>";
            strVar += "               <\/a:KeyValuePairOfstringanyType>";
            strVar += "               <a:KeyValuePairOfstringanyType>";
            strVar += "                  <b:key>PageNumber<\/b:key>";
            strVar += "                  <b:value xmlns:d=\"http:\/\/www.w3.org\/2001\/XMLSchema\" i:type=\"d:int\">"+pagecount+"<\/b:value>";
            strVar += "               <\/a:KeyValuePairOfstringanyType>";
            strVar += "               <a:KeyValuePairOfstringanyType>";
            strVar += "                  <b:key>CommentsPerPost<\/b:key>";
            strVar += "                  <b:value xmlns:d=\"http:\/\/www.w3.org\/2001\/XMLSchema\" i:type=\"d:int\">5<\/b:value>";
            strVar += "               <\/a:KeyValuePairOfstringanyType>";
            strVar += "            <\/a:Parameters>";
            strVar += "            <a:RequestId i:nil=\"true\" \/>";
            strVar += "            <a:RequestName>RetrievePersonalWall<\/a:RequestName>";
            strVar += "         <\/request>";
            $scope.Data = XrmServiceToolkit_Soap.Execute(strVar, true);
            console.log($scope.Data);
            $timeout(function () {
                $rootScope.hide();
            }, 2000);
        }

    } catch (error)
    { $rootScope.hide(); }
    finally {
    }
    $scope.Refresh = function () {
        $rootScope.show('Refreshing..');
        pagecount = 1;
        Personalwall();
    }
    $scope.loadMore = function () {
        $timeout(function () {
          pagecount = pagecount + 1;
          Personalwall();
        }, 1000);
        $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    $scope.$on('$stateChangeSuccess', function () {
        //$scope.loadMore();
    });
})


text:
package org.dcm4chee.web.common.util;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.dcm4che2.audit.message.ActiveParticipant;
import org.dcm4che2.audit.message.AuditEvent;
import org.dcm4che2.audit.message.AuditEvent.ActionCode;
import org.dcm4che2.audit.message.AuditEvent.TypeCode;
import org.dcm4che2.audit.message.AuditMessage;
import org.dcm4che2.audit.message.DataExportMessage;
import org.dcm4che2.audit.message.InstancesAccessedMessage;
import org.dcm4che2.audit.message.ParticipantObject;
import org.dcm4che2.audit.message.ParticipantObjectDescription;
import org.dcm4che2.audit.message.ParticipantObjectDescription.SOPClass;
import org.dcm4che2.audit.message.PatientRecordMessage;
import org.dcm4che2.audit.message.ProcedureRecordMessage;
import org.dcm4che2.audit.message.QueryMessage;
import org.dcm4che2.audit.message.SecurityAlertMessage;
import org.dcm4che2.audit.message.StudyDeletedMessage;
import org.dcm4che2.audit.util.InstanceSorter;
import org.dcm4che2.data.DicomElement;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4che2.io.DicomOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Franz Willer <franz.willer@gmail.com>
 * @version $Revision$ $Date$
 * @since Sep 15, 2011
 */
public class Auditlog {
    private static Logger auditLog = LoggerFactory.getLogger("auditlog");
    private static Logger log = LoggerFactory.getLogger(Auditlog.class);

    public static void logQuery(boolean success, String cuid, DicomObject query) {
        HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
        try {
            QueryMessage msg = new QueryMessage();
            msg.setOutcomeIndicator(success ? AuditEvent.OutcomeIndicator.SUCCESS : AuditEvent.OutcomeIndicator.MINOR_FAILURE);
            msg.addDestinationProcess(AuditMessage.getProcessID(), null,
                    AuditMessage.getProcessName(), userInfo.getHostName(), false);

            msg.addSourceProcess(AuditMessage.getProcessID(), null, AuditMessage.getProcessName(), AuditMessage.getLocalHostName(), true);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DicomOutputStream dos = new DicomOutputStream(bos);
            dos.writeDataset(query, UID.ExplicitVRLittleEndian);
            msg.addQuerySOPClass(cuid, UID.ExplicitVRLittleEndian, bos.toByteArray());
            msg.validate();
            auditLog.info(msg.toString());
        } catch (Exception x) {
            log.warn("Audit Log 'Query' failed:", x);
        }
    }

    public static void logInstancesAccessed(AuditEvent.ActionCode actionCode, boolean success, DicomObject kos, boolean addIUID, String detailMessage) {
        HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
        try {
            InstancesAccessedMessage msg = new InstancesAccessedMessage(actionCode);
            msg.setOutcomeIndicator(success ? AuditEvent.OutcomeIndicator.SUCCESS : AuditEvent.OutcomeIndicator.MINOR_FAILURE);
            msg.addUserPerson(userInfo.getUserId(), null, null, userInfo
                    .getHostName(), true);
            msg.addPatient(kos.getString(Tag.PatientID), kos.getString(Tag.PatientName));
            ParticipantObject study;
            DicomElement crpeSeq = kos.get(Tag.CurrentRequestedProcedureEvidenceSequence);
            DicomObject item;
            for ( int i = 0, len = crpeSeq.countItems() ; i < len ; i++ ) {
                item = crpeSeq.getDicomObject(i);
                study = msg.addStudy(item.getString(Tag.StudyInstanceUID),
                        getStudyDescription(item, addIUID));
                if ( detailMessage != null )
                    study.addParticipantObjectDetail("Description", getStudySeriesDetail(detailMessage, item));
            }
            msg.validate();
            auditLog.info(msg.toString());
        } catch (Exception x) {
            log.warn("Audit Log 'Instances Accessed' (actionCode:" + actionCode
                    + ") failed:", x);
        }
    }

    public static void logStudyDeleted(DicomObject kos, boolean success) {
        HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
        try {
            String patId = kos.getString(Tag.PatientID);
            String patName = kos.getString(Tag.PatientName);
            StudyDeletedMessage msg;
            DicomElement crpeSeq = kos.get(Tag.CurrentRequestedProcedureEvidenceSequence);
            for ( int i = 0, len = crpeSeq.countItems() ; i < len ; i++ ) {
                msg = new StudyDeletedMessage();
                msg.addUserPerson(userInfo.getUserId(), null, null, userInfo
                        .getHostName(), true);
                msg.addPatient(patId, patName);
                DicomObject crpeSeqItem = kos.get(Tag.CurrentRequestedProcedureEvidenceSequence).getDicomObject(i);
                msg.addStudy(crpeSeqItem.getString(Tag.StudyInstanceUID),
                        getStudyDescription(crpeSeqItem, true));
                msg.setOutcomeIndicator(success ? AuditEvent.OutcomeIndicator.SUCCESS : AuditEvent.OutcomeIndicator.MINOR_FAILURE);
                msg.validate();
                auditLog.info(msg.toString());
            }
        } catch (Exception x) {
            log.warn("Audit Log 'Study Deleted' failed:", x);
        }
    }

    public static void logDicomObjectUpdated(boolean success, String patId, String patName, String[] studyIUIDs, DicomObject obj, String detailMessage) {
        HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
        try {
            InstancesAccessedMessage msg = new InstancesAccessedMessage(InstancesAccessedMessage.UPDATE);
            msg.setOutcomeIndicator(success ? AuditEvent.OutcomeIndicator.SUCCESS : AuditEvent.OutcomeIndicator.MINOR_FAILURE);
            msg.addUserPerson(userInfo.getUserId(), null, null, userInfo.getHostName(), true);
            msg.addPatient(patId, patName);
            ParticipantObject study;
            for ( int i = 0; i < studyIUIDs.length ; i++ ) {
                study = msg.addStudy(studyIUIDs[i], getStudyDescription(obj));
                if ( detailMessage != null )
                    study.addParticipantObjectDetail("Description", detailMessage);
            }
            msg.validate();
            auditLog.info(msg.toString());
        } catch (Exception x) {
            log.warn("Audit Log 'Instances Accessed' (actionCode:U) failed:", x);
        }
    }

    public static void logPatientRecord(AuditEvent.ActionCode actionCode, boolean success, String patId, String patName) {
        HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
        try {
            PatientRecordMessage msg = new PatientRecordMessage(actionCode);
            msg.setOutcomeIndicator(success ? AuditEvent.OutcomeIndicator.SUCCESS : AuditEvent.OutcomeIndicator.MINOR_FAILURE);
            msg.addUserPerson(userInfo.getUserId(), null, null, userInfo
                    .getHostName(), true);
            msg.addPatient(patId, patName);
            msg.validate();
            auditLog.info(msg.toString());
        } catch (Exception x) {
            log.warn("Audit Log 'Patient Record' (actionCode:" + actionCode + ") failed:", x);
        }
    }

    public static void logExport(String mediaType, List<DicomObject> objs, boolean success) {
        try {
            HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
            String user = userInfo.getUserId();
            String host = userInfo.getHostName();
            DataExportMessage msg = new DataExportMessage();
            msg.setOutcomeIndicator( AuditEvent.OutcomeIndicator.SUCCESS );
            msg.addExporterProcess(AuditMessage.getProcessID(),
                    AuditMessage.getLocalAETitles(),
                    AuditMessage.getProcessName(), false,
                    AuditMessage.getLocalHostName());
            msg.addDataRepository(userInfo.getURL());
            msg.addDestinationMedia(host, null, mediaType, user == null, host );
            if (user != null) {
                ActiveParticipant ap = ActiveParticipant.createActivePerson(user, null, user, null, true);
                msg.addActiveParticipant(ap);

            }
            HashSet<String> pats = new HashSet<String>();
            HashMap<String, HashMap<String, int[]>> studies = new HashMap<String, HashMap<String, int[]>>(); //studyIuid, sopClassUID, nrOfInstances
            String patID, patName;
            HashMap<String, int[]> sopClasses;
            int[] noi;
            for (DicomObject obj : objs) {
                patID = obj.getString(Tag.PatientID);
                patName = obj.getString(Tag.PatientName);
                if (pats.add(patID+"_"+patName)) {
                    msg.addPatient(patID, patName);
                }
                sopClasses = studies.get(obj.getString(Tag.StudyInstanceUID));
                if (sopClasses == null) {
                    sopClasses = new HashMap<String, int[]>();
                    studies.put(obj.getString(Tag.StudyInstanceUID), sopClasses);
                }
                noi = sopClasses.get(obj.getString(Tag.SOPClassUID));
                if (noi == null) {
                    sopClasses.put(obj.getString(Tag.SOPClassUID), new int[]{1});
                } else {
                    noi[0]++;
                }
            }
            for (Map.Entry<String, HashMap<String, int[]>> study : studies.entrySet()) {
                ParticipantObjectDescription desc = new ParticipantObjectDescription();
                for (Map.Entry<String, int[]> sopCl : study.getValue().entrySet()) {
                    SOPClass sopClass = new SOPClass(sopCl.getKey());
                    sopClass.setNumberOfInstances(sopCl.getValue()[0]);
                    desc.addSOPClass(sopClass);
                }
                msg.addStudy(study.getKey(), desc);
            }
            msg.validate();
            auditLog.info(msg.toString());
        } catch (Exception x) {
            log.warn("Audit Log 'Data Export' failed:", x);
        }
    }

    public static void logProcedureRecord(ActionCode actionCode, boolean success, DicomObject patAttrs, String studyIuid, String accNr, String desc) {
        HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
        try {
            ProcedureRecordMessage msg = new ProcedureRecordMessage(actionCode);
            msg.setOutcomeIndicator(success ? AuditEvent.OutcomeIndicator.SUCCESS : AuditEvent.OutcomeIndicator.MINOR_FAILURE);
            msg.addUserPerson(userInfo.getUserId(), null, null, userInfo
                    .getHostName(), true);
            msg.addPatient(patAttrs.getString(Tag.PatientID), patAttrs.getString(Tag.PatientName));
            if (studyIuid != null) {
                ParticipantObjectDescription poDesc = new ParticipantObjectDescription();
                if (accNr != null)
                    poDesc.addAccession(accNr);
                ParticipantObject study = msg.addStudy(studyIuid, poDesc);
                if (desc != null)
                    study.addParticipantObjectDetail("Description", desc);
            }
            msg.validate();
            auditLog.info(msg.toString());
        } catch (Exception x) {
            log.warn("Audit Log 'Procedure Record' failed:", x);
        }
    }

    public static void logSecurityAlert(TypeCode code, boolean success, String desc) {
        try {
            SecurityAlertMessage msg = getSecurityAlertMessage(code, success, desc);
            msg.validate();
            auditLog.info(msg.toString());
        } catch (Exception e) {
            log.warn("Failed to log ActorConfig:", e);
        }
    }

    public static void logSecurityAlert(TypeCode code, boolean success, String desc, String patID, String patName, String studyIUID ) {
        try {
            SecurityAlertMessage msg = getSecurityAlertMessage(code, success, desc);
            msg.addParticipantObject(ParticipantObject.createPatient(patID, patName));
            if (studyIUID != null) {
                msg.addParticipantObject(ParticipantObject.createStudy(studyIUID, null));
            }
            msg.validate();
            auditLog.info(msg.toString());
        } catch (Exception e) {
            log.warn("Failed to log ActorConfig:", e);
        }
    }

    public static SecurityAlertMessage getSecurityAlertMessage(TypeCode code, boolean success, String desc) {
        HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
        SecurityAlertMessage msg = new SecurityAlertMessage(code);
        msg.setOutcomeIndicator(success ? AuditEvent.OutcomeIndicator.SUCCESS : AuditEvent.OutcomeIndicator.MINOR_FAILURE);
        msg.addReportingProcess(AuditMessage.getProcessID(),
                AuditMessage.getLocalAETitles(),
                AuditMessage.getProcessName(),
                AuditMessage.getLocalHostName());
        if ( userInfo.getHostName() != null ) {
                msg.addPerformingPerson(userInfo.getUserId(), null, null, userInfo.getHostName());
        } else {
            msg.addPerformingNode(AuditMessage.getLocalHostName());
        }
        msg.addAlertSubjectWithNodeID(AuditMessage.getLocalNodeID(), desc);
        return msg;
    }

    public static void logSoftwareConfiguration(boolean success, String desc) {
        logSecurityAlert(SecurityAlertMessage.SOFTWARE_CONFIGURATION, success, desc);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static boolean addChangeOfCollection(StringBuilder sb, boolean changed, String valueName,
            Collection oldValue, Collection newValue) {
        if (oldValue == null && newValue == null) {
            return false;
        }
        Collection addedValues = null;
        Collection removedValues = null;
        if (oldValue == null) {
            addedValues = newValue;
        } else if (newValue == null) {
            removedValues = oldValue;
        } else {
            if (newValue.size() >= oldValue.size() && newValue.containsAll(oldValue)) {
                if (newValue.size() == oldValue.size()) {
                    return false;
                } else {
                    addedValues = new ArrayList(newValue.size());
                    addedValues.addAll(newValue);
                    addedValues.removeAll(oldValue);
                }
            } else {
                addedValues = new ArrayList(newValue.size());
                addedValues.addAll(newValue);
                addedValues.removeAll(oldValue);
                removedValues = new ArrayList(oldValue.size());
                addedValues.addAll(oldValue);
                addedValues.removeAll(newValue);
            }
        }
        sb.append(changed ? " ; " : "Change ").append(valueName).append(":");
        if (removedValues != null && removedValues.size() > 0) {
            sb.append(" removed:[");
            for (Object o : removedValues) {
                sb.append(o).append(',');
            }
            sb.setLength(sb.length()-1);
            sb.append("]");
        }
        if (addedValues != null && addedValues.size() > 0) {
            sb.append(" added:[");
            for (Object o : addedValues) {
                sb.append(o).append(',');
            }
            sb.setLength(sb.length()-1);
            sb.append("]");
        }
        return true;
    }

    public static boolean addChange(StringBuilder sb, boolean changed, String valueName, Object oldValue, Object newValue) {
        if (oldValue == newValue || oldValue!= null && oldValue.equals(newValue)) {
            return false;
        }
        sb.append(changed ? " ; " : "Change ").append(valueName).append(" from ").append(oldValue).append(" to ").append(newValue);
        return true;
    }

    private static ParticipantObjectDescription getStudyDescription(DicomObject obj) {
        ParticipantObjectDescription desc = new ParticipantObjectDescription();
        if (obj.containsValue(Tag.AccessionNumber)) {
            desc.addAccession(obj.getString(Tag.AccessionNumber));
        }
        if (obj.containsValue(Tag.SOPClassUID)) {
            ParticipantObjectDescription.SOPClass sopClass =
                new ParticipantObjectDescription.SOPClass(obj.getString(Tag.SOPClassUID));
            sopClass.addInstance(obj.getString(Tag.SOPInstanceUID));
            desc.addSOPClass(sopClass);
        }
        return desc;
    }

    private static ParticipantObjectDescription getStudyDescription(DicomObject crpeSeqItem, boolean addIUID) {
        ParticipantObjectDescription desc = new ParticipantObjectDescription();
        String accNr = crpeSeqItem.getString(Tag.AccessionNumber);
        if (accNr != null)
            desc.addAccession(accNr);
        addSOPClassInfo(desc, crpeSeqItem, addIUID);
        return desc;
    }

    private static String getStudySeriesDetail(String detailMessage, DicomObject crpeSeqItem) {
        DicomElement refSeries = crpeSeqItem.get(Tag.ReferencedSeriesSequence);
        StringBuffer sb = new StringBuffer();
        sb.append(detailMessage);
        int len = refSeries.countItems();
        if ( len > 0 ) {
            sb.append(refSeries.getDicomObject(0).getString(Tag.SeriesInstanceUID));
            for (int i = 1; i < len; i++) {
                sb.append(", ").append(refSeries.getDicomObject(i).getString(Tag.SeriesInstanceUID));
            }
        }
        return sb.toString();
    }

    private static void addSOPClassInfo(ParticipantObjectDescription desc,
            DicomObject studyMgtDs, boolean addIUID) {
        DicomElement refSeries = studyMgtDs.get(Tag.ReferencedSeriesSequence);
        if (refSeries == null)
            return;
        String suid = studyMgtDs.getString(Tag.StudyInstanceUID);
        InstanceSorter sorter = new InstanceSorter();
        DicomObject ds;
        DicomElement refSopSeq;
        for (int i = 0, len = refSeries.countItems(); i < len; i++) {
            refSopSeq = refSeries.getDicomObject(i).get(Tag.ReferencedSOPSequence);
            if (refSopSeq != null) {
                for (int j = 0, jlen = refSopSeq.countItems(); j < jlen; j++) {
                    ds = refSopSeq.getDicomObject(j);
                    sorter.addInstance(suid,
                            ds.getString(Tag.ReferencedSOPClassUID),
                            ds.getString(Tag.ReferencedSOPInstanceUID), null);
                }
            }
        }

        for (String cuid : sorter.getCUIDs(suid)) {
            ParticipantObjectDescription.SOPClass sopClass = new ParticipantObjectDescription.SOPClass(cuid);
            sopClass.setNumberOfInstances(sorter.countInstances(suid, cuid));
            if ( addIUID ) {
                for ( String iuid : sorter.getIUIDs(suid, cuid) ) {
                    sopClass.addInstance(iuid);
                }
            }
            desc.addSOPClass(sopClass);
        }
    }

}


text:
namespace sp { namespace graphics { namespace API {

	GLIndexBuffer::GLIndexBuffer(uint16* data, uint count)
		: m_Count(count)
	{
		GLCall(glGenBuffers(1, &m_Handle));
		GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Handle));
		GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(uint16), data, GL_STATIC_DRAW));
	}

	GLIndexBuffer::GLIndexBuffer(uint* data, uint count)
		: m_Count(count)
	{
		GLCall(glGenBuffers(1, &m_Handle));
		GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Handle));
		GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(uint), data, GL_STATIC_DRAW));
	}

	GLIndexBuffer::~GLIndexBuffer()
	{
		GLCall(glDeleteBuffers(1, &m_Handle));
	}

	void GLIndexBuffer::Bind() const
	{
		GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Handle));
	}

	void GLIndexBuffer::Unbind() const
	{
		GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
	}

	uint GLIndexBuffer::GetCount() const
	{
		return m_Count;
	}

} } }


text:
package com.twitter.finagle.postgresql.transport

import com.twitter.finagle.postgresql.BackendMessage
import com.twitter.finagle.postgresql.PgSqlClientError
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationCleartextPassword
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationGSS
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationGSSContinue
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationKerberosV5
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationMD5Password
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationMessage
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationOk
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationSASL
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationSASLContinue
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationSASLFinal
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationSCMCredential
import com.twitter.finagle.postgresql.BackendMessage.AuthenticationSSPI
import com.twitter.finagle.postgresql.BackendMessage.BackendKeyData
import com.twitter.finagle.postgresql.BackendMessage.BindComplete
import com.twitter.finagle.postgresql.BackendMessage.CloseComplete
import com.twitter.finagle.postgresql.BackendMessage.CommandComplete
import com.twitter.finagle.postgresql.BackendMessage.CommandTag
import com.twitter.finagle.postgresql.BackendMessage.CopyData
import com.twitter.finagle.postgresql.BackendMessage.CopyDone
import com.twitter.finagle.postgresql.BackendMessage.CopyInResponse
import com.twitter.finagle.postgresql.BackendMessage.CopyOutResponse
import com.twitter.finagle.postgresql.BackendMessage.DataRow
import com.twitter.finagle.postgresql.BackendMessage.EmptyQueryResponse
import com.twitter.finagle.postgresql.BackendMessage.ErrorResponse
import com.twitter.finagle.postgresql.BackendMessage.FailedTx
import com.twitter.finagle.postgresql.BackendMessage.Field
import com.twitter.finagle.postgresql.BackendMessage.InTx
import com.twitter.finagle.postgresql.BackendMessage.NoData
import com.twitter.finagle.postgresql.BackendMessage.NoTx
import com.twitter.finagle.postgresql.BackendMessage.NoticeResponse
import com.twitter.finagle.postgresql.BackendMessage.Parameter
import com.twitter.finagle.postgresql.BackendMessage.ParameterDescription
import com.twitter.finagle.postgresql.BackendMessage.ParameterStatus
import com.twitter.finagle.postgresql.BackendMessage.ParseComplete
import com.twitter.finagle.postgresql.BackendMessage.PortalSuspended
import com.twitter.finagle.postgresql.BackendMessage.ReadyForQuery
import com.twitter.finagle.postgresql.BackendMessage.RowDescription
import com.twitter.finagle.postgresql.Types.AttributeId
import com.twitter.finagle.postgresql.Types.FieldDescription
import com.twitter.finagle.postgresql.Types.Format
import com.twitter.finagle.postgresql.Types.Oid
import com.twitter.io.Buf
import scala.annotation.tailrec

/**
 * A typeclass for decoding [[BackendMessage]] from a [[Packet]].
 *
 * @see [[MessageEncoder]]
 * @see [[PgBuf.Reader]]
 */
trait MessageDecoder[M <: BackendMessage] {
  def decode(b: PgBuf.Reader): M
}

object MessageDecoder {

  def decode[M <: BackendMessage](reader: PgBuf.Reader)(implicit decoder: MessageDecoder[M]): M =
    decoder.decode(reader)

  def fromBuf(buf: Buf): BackendMessage = {
    val reader = PgBuf.reader(buf)
    val cmd = reader.byte()

    if (reader.remaining >= 4) {
      // skip the 4 byte packet length
      reader.skip(4)
    }

    val ret = cmd match {
      case '1' => ParseComplete
      case '2' => BindComplete
      case '3' => CloseComplete
      case 'c' => CopyDone
      case 'C' => decode[CommandComplete](reader)
      case 'd' => decode[CopyData](reader)
      case 'D' => decode[DataRow](reader)
      case 'E' => decode[ErrorResponse](reader)
      case 'G' => decode[CopyInResponse](reader)
      case 'H' => decode[CopyOutResponse](reader)
      case 'I' => EmptyQueryResponse
      case 'K' => decode[BackendKeyData](reader)
      case 'n' => NoData
      case 'N' => decode[NoticeResponse](reader)
      case 'R' => decode[AuthenticationMessage](reader)
      case 's' => PortalSuspended
      case 'S' => decode[ParameterStatus](reader)
      case 't' => decode[ParameterDescription](reader)
      case 'T' => decode[RowDescription](reader)
      case 'Z' => decode[ReadyForQuery](reader)
      case byte => throw new PgSqlClientError(s"unimplemented message '${byte.toChar}'")
    }
    if (reader.remaining != 0) {
      throw new PgSqlClientError("message decoding did not consume the entire packet")
    }
    ret
  }

  def apply[M <: BackendMessage](f: PgBuf.Reader => M): MessageDecoder[M] = reader => f(reader)

  def readFields(reader: PgBuf.Reader): Map[Field, String] = {
    import Field._
    def nextField: Option[Field] =
      reader.byte().toChar match {
        case 0 => None
        case 'S' => Some(LocalizedSeverity)
        case 'V' => Some(Severity)
        case 'C' => Some(Code)
        case 'M' => Some(Message)
        case 'D' => Some(Detail)
        case 'H' => Some(Hint)
        case 'P' => Some(Position)
        case 'p' => Some(InternalPosition)
        case 'q' => Some(InternalQuery)
        case 'W' => Some(Where)
        case 's' => Some(Schema)
        case 't' => Some(Table)
        case 'c' => Some(Column)
        case 'd' => Some(DataType)
        case 'n' => Some(Constraint)
        case 'F' => Some(File)
        case 'L' => Some(Line)
        case 'R' => Some(Routine)
        case unk => Some(Unknown(unk))
      }

    @tailrec
    def loop(fields: Map[Field, String]): Map[Field, String] =
      nextField match {
        case None => fields
        case Some(field) =>
          val value = reader.cstring()
          loop(fields + (field -> value))
      }

    loop(Map.empty)
  }

  implicit lazy val errorResponseDecoder: MessageDecoder[ErrorResponse] = MessageDecoder { reader =>
    ErrorResponse(readFields(reader))
  }

  implicit lazy val noticeResponseDecoder: MessageDecoder[NoticeResponse] = MessageDecoder {
    reader =>
      NoticeResponse(readFields(reader))
  }

  implicit lazy val backendKeyDataDecoder: MessageDecoder[BackendKeyData] = MessageDecoder {
    reader =>
      BackendKeyData(reader.int(), reader.int())
  }

  def commandTag(value: String): CommandTag =
    value.split(" ", 3).toList match {
      case "INSERT" :: _ :: rows :: Nil => CommandTag.AffectedRows(CommandTag.Insert, rows.toInt)
      case "DELETE" :: rows :: Nil => CommandTag.AffectedRows(CommandTag.Delete, rows.toInt)
      case "UPDATE" :: rows :: Nil => CommandTag.AffectedRows(CommandTag.Update, rows.toInt)
      case "SELECT" :: rows :: Nil => CommandTag.AffectedRows(CommandTag.Select, rows.toInt)
      case "MOVE" :: rows :: Nil => CommandTag.AffectedRows(CommandTag.Move, rows.toInt)
      case "FETCH" :: rows :: Nil => CommandTag.AffectedRows(CommandTag.Fetch, rows.toInt)
      case _ => CommandTag.Other(value)
    }

  implicit lazy val commandCompleteDecoder: MessageDecoder[CommandComplete] = MessageDecoder {
    reader =>
      CommandComplete(commandTag(reader.cstring()))
  }

  implicit lazy val authenticationMessageDecoder: MessageDecoder[AuthenticationMessage] =
    MessageDecoder { reader =>
      reader.int() match {
        case 0 => AuthenticationOk
        case 2 => AuthenticationKerberosV5
        case 3 => AuthenticationCleartextPassword
        case 5 => AuthenticationMD5Password(reader.buf(4))
        case 6 => AuthenticationSCMCredential
        case 7 => AuthenticationGSS
        case 8 => AuthenticationGSSContinue(reader.remainingBuf())
        case 9 => AuthenticationSSPI
        case 10 => AuthenticationSASL(reader.cstring())
        case 11 => AuthenticationSASLContinue(reader.remainingBuf())
        case 12 => AuthenticationSASLFinal(reader.remainingBuf())
      }
    }

  implicit lazy val parameterStatusDecoder: MessageDecoder[ParameterStatus] = MessageDecoder {
    reader =>
      val parameter = reader.cstring() match {
        case "server_version" => Parameter.ServerVersion
        case "server_encoding" => Parameter.ServerEncoding
        case "client_encoding" => Parameter.ClientEncoding
        case "application_name" => Parameter.ApplicationName
        case "is_superuser" => Parameter.IsSuperUser
        case "session_authorization" => Parameter.SessionAuthorization
        case "DateStyle" => Parameter.DateStyle
        case "IntervalStyle" => Parameter.IntervalStyle
        case "TimeZone" => Parameter.TimeZone
        case "integer_datetimes" => Parameter.IntegerDateTimes
        case "standard_conforming_strings" => Parameter.StandardConformingStrings
        case other => Parameter.Other(other)
      }
      ParameterStatus(parameter, reader.cstring())
  }

  implicit lazy val readyForQueryDecoder: MessageDecoder[ReadyForQuery] = MessageDecoder { reader =>
    val state = reader.byte().toChar match {
      case 'I' => NoTx
      case 'T' => InTx
      case 'F' => FailedTx
    }
    ReadyForQuery(state)
  }

  implicit lazy val rowDescriptionDecoder: MessageDecoder[RowDescription] = MessageDecoder {
    reader =>
      RowDescription(
        reader.collect { r =>
          FieldDescription(
            name = r.cstring(),
            tableOid = r.unsignedInt() match {
              case 0 => None
              case oid => Some(Oid(oid))
            },
            tableAttributeId = r.short() match {
              case 0 => None
              case attrId => Some(AttributeId(attrId))
            },
            dataType = Oid(r.unsignedInt()),
            dataTypeSize = r.short(),
            typeModifier = r.int(),
            format = r.format()
          )
        }
      )
  }

  implicit lazy val dataRowDecoder: MessageDecoder[DataRow] = MessageDecoder { reader =>
    DataRow(
      reader.collect(_.value())
    )
  }

  implicit lazy val parameterDescriptionDecoder: MessageDecoder[ParameterDescription] =
    MessageDecoder { reader =>
      ParameterDescription(
        reader.collect(r => Oid(r.unsignedInt()))
      )
    }

  implicit lazy val copyInResponseDecoder: MessageDecoder[CopyInResponse] = MessageDecoder {
    reader =>
      CopyInResponse(
        overallFormat = reader.byte() match {
          case 0 => Format.Text
          case 1 => Format.Binary
        },
        columnsFormat = reader.collect(_.format()),
      )
  }

  implicit lazy val copyOutResponseDecoder: MessageDecoder[CopyOutResponse] = MessageDecoder {
    reader =>
      CopyOutResponse(
        overallFormat = reader.byte() match {
          case 0 => Format.Text
          case 1 => Format.Binary
        },
        columnsFormat = reader.collect(_.format()),
      )
  }

  implicit lazy val copyDataDecoder: MessageDecoder[CopyData] = MessageDecoder { reader =>
    CopyData(reader.remainingBuf())
  }

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Soc. Bot. France 21:164. 1874

#### Original name
null

### Remarks
null


text:
namespace com.tinylabproductions.TLPLib.Concurrent {
}


text:
/*	$OpenBSD: stdd.h,v 1.6 2010/09/07 19:58:09 marco Exp $	*/
/*	$NetBSD: stdd.h,v 1.2 1995/09/28 05:37:50 tls Exp $	*/

/*-
 * Copyright (c) 1991, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ozan Yigit at York University.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)stdd.h	8.1 (Berkeley) 6/6/93
 * $FreeBSD: soc2013/dpl/head/usr.bin/m4/stdd.h 228344 2011-11-28 13:32:39Z bapt $
 */

/*
 * standard defines
 */

#define max(a,b) ((a) > (b)? (a): (b))
#define min(a,b) ((a) < (b)? (a): (b))

#define iswhite(c) ((c) == ' ' || (c) == '\t')

/*
 * STREQ is an optimised strcmp(a,b)==0
 * STREQN is an optimised strncmp(a,b,n)==0; assumes n > 0
 */
#define STREQ(a, b) ((a)[0] == (b)[0] && strcmp(a, b) == 0)
#define STREQN(a, b, n) ((a)[0] == (b)[0] && strncmp(a, b, n) == 0)

#define YES 1
#define NO 0


text:
/*global MM, _, observable*/
MM.MeasuresModel = function (configAttributeName, valueAttrName, activeContentListener, defaultFilter) {
	'use strict';
	var self = observable(this),
		measures = [],
		latestMeasurementValues = [],
		filter,
		onActiveContentChange = function (activeContent, isNew) {
			if (isNew) {
				self.dispatchEvent('startFromScratch');
			}
			var measuresBefore = measures;
			measures = getActiveContentMeasures();
			if (self.listeners('measureRemoved').length > 0) {
				_.each(_.difference(measuresBefore, measures), function (measure) {
					self.dispatchEvent('measureRemoved', measure);
				});
			}
			if (self.listeners('measureAdded').length > 0) {
				_.each(_.difference(measures, measuresBefore), function (measure) {
					self.dispatchEvent('measureAdded', measure, measures.indexOf(measure));
				});
			}
			dispatchMeasurementChangedEvents();
		},
		onFilterChanged = function () {
			self.dispatchEvent('measureRowsChanged');
		},
		getActiveContentMeasures = function () {
			var activeContent = activeContentListener.getActiveContent(),
				value = activeContent && activeContent.getAttr(configAttributeName);
			if (!_.isArray(value)) {
				return [];
			}
			return value;
		},
		mapMeasurements = function (measurements) {
			var map = {};
			_.each(measurements, function (measurement) {
				map[measurement.id] = measurement;
			});
			return map;
		},
		measurementValueDifferences = function (measurement, baseline) {
			var difference = [];
			_.each(measurement.values, function (value, key) {
				var baselineValue = (baseline && baseline.values && baseline.values[key]) || 0;
				if (value !== baselineValue) {
					difference.push(['measureValueChanged', measurement.id, key, value || 0]);
				}
			});
			if (baseline) {
				_.each(baseline.values, function (value, key) {
					var noNewValue = !measurement || !measurement.values || !measurement.values[key];
					if (noNewValue) {
						difference.push(['measureValueChanged', baseline.id, key, 0]);
					}
				});
			}
			return difference;
		},
		measurementDifferences = function (measurements, baslineMeasurements) {
			/*{id: 11, title: 'with values', values: {'Speed': 1, 'Efficiency': 2}}*/
			var baslineMeasurementsMap = mapMeasurements(baslineMeasurements),
				differences = [];
			_.each(measurements, function (measurement) {
				var baseline = baslineMeasurementsMap[measurement.id];
				differences = differences.concat(measurementValueDifferences(measurement, baseline));
			});
			return differences;
		},
		dispatchMeasurementChangedEvents = function () {
			if (self.listeners('measureValueChanged').length === 0) {
				return;
			}
			var oldMeasurementValues = latestMeasurementValues,
				differences = measurementDifferences(self.getMeasurementValues(), oldMeasurementValues);
			_.each(differences, function (changeArgs) {
				self.dispatchEvent.apply(self, changeArgs);
			});
		};

	self.editingMeasure = function (isEditing, nodeId) {

		self.dispatchEvent('measureEditing', isEditing, nodeId);
	};
	self.getMeasures = function () {
		return measures.slice(0);
	};
	self.editWithFilter = function (newFilter) {
		if (filter) {
			self.removeFilter();
		}
		filter = newFilter;
		if (filter && filter.addEventListener) {
			filter.addEventListener('filteredRowsChanged', onFilterChanged);
		}
	};
	self.addUpMeasurementForAllNodes = function (measurementName) {
		var activeContent = activeContentListener.getActiveContent(),
			result = {},
			addUpMeasure = function (idea) {
				var measures = idea.getAttr(valueAttrName), sum = 0, hasValue = false;
				if (measures && measures[measurementName]) {
					sum = parseFloat(measures[measurementName]);
					hasValue = true;
				}
				if (idea.ideas) {
					_.each(idea.ideas, function (subIdea) {
						if (result[subIdea.id] !== undefined) {
							hasValue = true;
							sum += result[subIdea.id];
						}
					});
				}
				if (hasValue) {
					result[idea.id] = sum;
				}
			};

		if (!activeContent || !measurementName) {
			return {};
		}
		activeContent.traverse(addUpMeasure, true);
		return result;
	};
	self.getMeasurementValues = function () {
		var activeContent = activeContentListener.getActiveContent(),
			result = [];
		if (!activeContent) {
			return result;
		}
		activeContent.traverse(function (idea) {
			if (!filter || filter.predicate(idea)) {
				var newVals = {};
				_.each(_.extend({}, idea.getAttr(valueAttrName)), function (val, key) {
					if (val === undefined) {
						return;
					}
					if (!isNaN(parseFloat(val))) {
						newVals[key] = val;
					}
				});
				result.push({
					id: idea.id,
					title: idea.title,
					values: newVals
				});
			}
		});
		latestMeasurementValues = result.slice(0);
		return result;
	};
	self.addMeasure = function (measureName) {
		if (!measureName || measureName.trim() === '') {
			return false;
		}
		measureName = measureName.trim();

		if (_.find(measures, function (measure) {
			return measure.toUpperCase() === measureName.toUpperCase();
		})) {
			return false;
		}
		var activeContent = activeContentListener.getActiveContent();
		activeContent.updateAttr(activeContent.id, configAttributeName, measures.concat([measureName]));
	};
	self.removeMeasure = function (measureName) {
		if (!measureName || measureName.trim() === '') {
			return false;
		}
		var updated = _.without(measures, measureName),
			activeContent;
		if (_.isEqual(updated, measures)) {
			return;
		}
		activeContent = activeContentListener.getActiveContent();
		activeContent.startBatch();
		activeContent.updateAttr(activeContent.id, configAttributeName, updated);
		activeContent.traverse(function (idea) {
			activeContent.mergeAttrProperty(idea.id, valueAttrName, measureName,  false);
		});
		activeContent.endBatch();
	};
	self.validate = function (value) {
		return !isNaN(parseFloat(value)) && isFinite(value);
	};
	self.setValue = function (nodeId, measureName, value) {
		if (!self.validate(value)) {
			return false;
		}
		return activeContentListener.getActiveContent().mergeAttrProperty(nodeId, valueAttrName, measureName, value);
	};
	self.getRawData = function (ignoreFilter) {
		var activeContent = activeContentListener.getActiveContent(),
			data = [];
		if (!activeContent) {
			return data;
		}
		data.push(['Name'].concat(measures));
		activeContent.traverse(function (idea) {
			if (ignoreFilter || !filter || filter.predicate(idea)) {
				data.push(
					[idea.title].concat(_.map(measures,
							function (measure) {
								var ideaMeasures = idea.getAttr(valueAttrName) || {},
									floatVal = ideaMeasures[measure] && parseFloat(ideaMeasures[measure]);
								if (floatVal !== undefined && !isNaN(floatVal)) {
									return floatVal;
								}
							})
						)
				);
			}
		});

		return data;
	};
	self.removeFilter = function () {
		if (filter && filter.cleanup) {
			filter.cleanup();
		}
		if (filter && filter.removeEventListener) {
			filter.removeEventListener('filteredRowsChanged', onFilterChanged);
		}
		filter = undefined;
	};
	activeContentListener.addListener(onActiveContentChange);
	self.editWithFilter(defaultFilter);
};
MM.MeasuresModel.filterByIds = function (ids) {
	'use strict';
	return {
		predicate: function (idea) {
			return _.include(ids, idea.id);
		}
	};
};

MM.MeasuresModel.ActivatedNodesFilter = function (mapModel) {
	'use strict';
	var self = observable(this),
		ids = mapModel.getActivatedNodeIds(),
		onFilteredResultsChange = function (force) {
			var newIds = mapModel.getActivatedNodeIds();
			if (force || ids !== newIds) {
				ids = newIds;
				self.dispatchEvent('filteredRowsChanged');
			}
		},
		onFilteredResultsChangeForced = onFilteredResultsChange.bind(self, true);
	mapModel.addEventListener('activatedNodesChanged', onFilteredResultsChange);
	mapModel.addEventListener('nodeTitleChanged', onFilteredResultsChangeForced);
	self.predicate = function (idea) {
		return _.include(ids, idea.id);
	};
	self.cleanup = function () {
		mapModel.removeEventListener('activatedNodesChanged', onFilteredResultsChange);
		mapModel.removeEventListener('nodeTitleChanged', onFilteredResultsChangeForced);
	};
};

MM.measuresModelMediator = function (mapModel, measuresModel) {
	'use strict';
	measuresModel.addEventListener('measureEditing', function (isEditing, nodeId) {
		if (isEditing && nodeId) {
			mapModel.selectNode(nodeId, true, true);
		}
		mapModel.setInputEnabled(!isEditing, true);
	});
};


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <base href="/">
    <title>Allison & Joe — #nomorekiddingaround</title>
    <meta name="description" content="November 11, 2018 — The wedding of Allison Kidd & Joe Garber.">

    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="manifest" href="/site.webmanifest">
    <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#405a41">
    <meta name="apple-mobile-web-app-title" content="Allison & Joe">
    <meta name="application-name" content="Allison & Joe">
    <meta name="msapplication-TileColor" content="#603cba">
    <meta name="theme-color" content="#000000">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" href="shared/styles/bundle.css" inline>

    Home
    Our Story
    Our Entourage
    The Wedding
    Travel & Lodging
    Things To Do
    Registry
    Credits

<ng-view></ng-view>


text:
title: "Consultation"
tags: []
---

Consultation, n.:

    Medical term meaning "to share the wealth."


text:
import React, { Component } from 'react';

import Helmet from 'react-helmet';

import Header from 'shared/containers/App/Header';

import CSSModules from 'react-css-modules';
import './global.scss';
import styles from './App.scss';

class App extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (

        <Helmet
            title="React Redux Universal Starter Kit"
        />

            { this.props.children }

    );
  }
}

module.exports = CSSModules(App, styles);


text:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="chrome=1">

    <title>An example of the Pie chart</title>

    <meta name="keywords" content="rgraph html5 canvas example pie charts" />
    <meta name="description" content="An example of the type of Pie chart that RGraph can produce" />
    <meta name="googlebot" content="NOODP">

    <meta property="og:title" content="RGraph: HTML5 Javascript charts library" />
    <meta property="og:description" content="A charts library based on the HTML5 canvas tag" />
    <meta property="og:image" content="http://www.rgraph.net/images/logo.png"/>

    <link rel="stylesheet" href="../css/website.css" type="text/css" media="screen" />
    <link rel="icon" type="image/png" href="../images/favicon.png">

    <?php PrintAnalyticsCode() ?>

        <?php
            $prefix = substr($_SERVER['SERVER_NAME'], 0, 3);
            require("/rgraph.{$prefix}/social.html");
        ?>

    RGraph: HTML5 Javascript charts library
    >
    Examples
    >
    Pie charts example

Pie charts

            Pie charts can be used when you need to represent a value as part of a whole. It is commonly used to represent
            percentages, relative magnitudes or relative frequencies. If your intent is to compare a particular value (slice)
            against the whole of the Pie chart, then it can be quite effective. If however you want to compare two seperate
            segments, then it can get more difficult. If this is the case, you may want to consider bar charts or perhaps line charts.

            The colours can be customised, as can the borders (using the same color as the background. The charts can also have
            a drop shadow if you want one.

Pie charts API documentation

        <canvas id="pie2" width="550" height="300">[No canvas support]</canvas>


text:
hide:
  - toc
---

# GitHub Self-Hosted Agent Setup

We are using GitHub Self-Hosted Agents for Windows and macOS testing. The build machines and agents must be set up before use.

## Windows Agent Setup

1. Create the user "testbot" on the machine. Use the password for `testbot@drud.com`, available in 1Password.
2. In admin PowerShell, `Set-ExecutionPolicy -Scope "CurrentUser" -ExecutionPolicy "RemoteSigned"`.
3. In admin Powershell, download and run [windows_buildkite_start.ps1](scripts/windows_buildkite_start.ps1) with `curl <url> -O windows_buildkite_start.ps1`.
4. After restart, in administrative Git Bash window, `Rename-Computer <testbot-win10(home|pro)-<description>-1`.
5. Now download and run [windows_github_agent_setup.sh](scripts/windows_github_agent_setup.sh).
6. Launch Docker. It may require you to take further actions.
7. Log into Chrome with the user `testbot@drud.com` and enable Chrome Remote Desktop.
8. Enable `gd`, `fileinfo`, and `curl` extensions in `/c/tools/php*/php.ini`.
9. If a laptop, set the "lid closing" setting in settings to do nothing.
10. Set the "Sleep after time" setting in settings to never.
11. Install [`winaero tweaker`](https://winaero.com/request.php?1796) and "Enable user autologin checkbox". Set up the machine to [automatically log in on boot](https://www.cnet.com/how-to/automatically-log-in-to-your-windows-10-pc/).  Then run `netplwiz`, provide the password for the main user, uncheck the "require a password to log in".
12. Add the path `C:\Program Files\git\bin` to the very front of the *system* environment variables. Otherwise Windows will try to use its own `bash.exe` or PowerShell.
13. Install the GitHub self-hosted runner software using the "Add New" instructions on <https://github.com/organizations/drud/settings/actions>. When it asks if you want it as a service: yes, you do.
14. Run `.buildkite/sanetestbot.sh` to check your work.
15. Reboot the machine and do a test run. (On Windows, the machine name only takes effect on reboot.)


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

using System;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;

namespace WcfService
{
    [TestServiceDefinition(Schema = ServiceSchema.NETTCP, BasePath = "Duplex.svc")]
    public class DuplexTestServiceHost : TestServiceHostBase<IWcfDuplexService>
    {
        protected override string Address { get { return "tcp-nosecurity-callback"; } }

        protected override Binding GetBinding()
        {
            return new NetTcpBinding(SecurityMode.None) { PortSharingEnabled = false };
        }

        public DuplexTestServiceHost(params Uri[] baseAddresses)
            : base(typeof(WcfDuplexService), baseAddresses)
        {
        }
    }

    [TestServiceDefinition(Schema = ServiceSchema.NETTCP, BasePath = "DuplexCallback.svc")]
    public class DuplexCallbackTestServiceHost : TestServiceHostBase<IDuplexChannelService>
    {
        protected override string Address { get { return "tcp-nosecurity-typedproxy-duplexcallback"; } }

        protected override Binding GetBinding()
        {
            return new NetTcpBinding(SecurityMode.None) { PortSharingEnabled = false };
        }

        public DuplexCallbackTestServiceHost(params Uri[] baseAddresses)
            : base(typeof(DuplexCallbackService), baseAddresses)
        {
        }
    }

    [TestServiceDefinition(Schema = ServiceSchema.NETTCP, BasePath = "DuplexChannelCallbackReturn.svc")]
    public class DuplexChannelCallbackReturnTestServiceHost : TestServiceHostBase<IWcfDuplexTaskReturnService>
    {
        protected override string Address { get { return "tcp-nosecurity-taskreturn"; } }

        protected override Binding GetBinding()
        {
            return new NetTcpBinding(SecurityMode.None) { PortSharingEnabled = false };
        }

        public DuplexChannelCallbackReturnTestServiceHost(params Uri[] baseAddresses)
            : base(typeof(DuplexChannelCallbackReturnService), baseAddresses)
        {
        }
    }

    [TestServiceDefinition(Schema = ServiceSchema.NETTCP, BasePath = "DuplexCallbackDataContractComplexType.svc")]
    public class DuplexCallbackDataContractComplexTypeTestServiceHost : TestServiceHostBase<IWcfDuplexService_DataContract>
    {
        protected override string Address { get { return "tcp-nosecurity-callback"; } }

        protected override Binding GetBinding()
        {
            return new NetTcpBinding(SecurityMode.None) { PortSharingEnabled = false };
        }

        public DuplexCallbackDataContractComplexTypeTestServiceHost(params Uri[] baseAddresses)
            : base(typeof(WcfDuplexService), baseAddresses)
        {
        }
    }

    [TestServiceDefinition(Schema = ServiceSchema.NETTCP, BasePath = "DuplexCallbackXmlComplexType.svc")]
    public class DuplexCallbackXmlComplexTypeTestServiceHost : TestServiceHostBase<IWcfDuplexService_Xml>
    {
        protected override string Address { get { return "tcp-nosecurity-callback"; } }

        protected override Binding GetBinding()
        {
            return new NetTcpBinding(SecurityMode.None) { PortSharingEnabled = false };
        }

        public DuplexCallbackXmlComplexTypeTestServiceHost(params Uri[] baseAddresses)
            : base(typeof(WcfDuplexService), baseAddresses)
        {
        }
    }

    [TestServiceDefinition(Schema = ServiceSchema.NETTCP, BasePath = "DuplexCallbackTcpCertificateCredential.svc")]
    public class DuplexCallbackTcpCertificateCredentialTestServiceHost : TestServiceHostBase<IWcfDuplexService>
    {
        protected override string Address { get { return "tcp-certificate-callback"; } }

        protected override Binding GetBinding()
        {
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;
            return binding;
        }

        protected override void ApplyConfiguration()
        {
            base.ApplyConfiguration();
            // Ensure the https certificate is installed before this endpoint resource is used
            string thumbprint = TestHost.CertificateFromFriendlyName(StoreName.My, StoreLocation.LocalMachine, "WCF Bridge - Machine certificate generated by the CertificateManager").Thumbprint;

            this.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            this.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine,
                                                      StoreName.My,
                                                      X509FindType.FindByThumbprint,
                                                      thumbprint);
        }

        public DuplexCallbackTcpCertificateCredentialTestServiceHost(params Uri[] baseAddresses)
            : base(typeof(WcfDuplexService), baseAddresses)
        {
        }
    }

    [TestServiceDefinition(Schema = ServiceSchema.NETTCP, BasePath = "DuplexCallbackConcurrencyMode.svc")]
    public class DuplexCallbackConcurrencyModeServiceHost : TestServiceHostBase<IWcfDuplexService_CallbackConcurrencyMode>
    {
        protected override string Address { get { return "tcp"; } }

        protected override Binding GetBinding()
        {
            return new NetTcpBinding(SecurityMode.None) { PortSharingEnabled = false };
        }

        public DuplexCallbackConcurrencyModeServiceHost(params Uri[] baseAddresses)
            : base(typeof(WcfDuplexService_CallbackConcurrenyMode), baseAddresses)
        {
        }
    }
}