text:
namespace ExcelPostJsonAddIn
{
    partial class PostJsonRibbon : Microsoft.Office.Tools.Ribbon.RibbonBase
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        public PostJsonRibbon()
            : base(Globals.Factory.GetRibbonFactory())
        {
            InitializeComponent();
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.tab1 = this.Factory.CreateRibbonTab();
            this.groupPostJson = this.Factory.CreateRibbonGroup();
            this.editBoxUrl = this.Factory.CreateRibbonEditBox();
            this.editBoxUser = this.Factory.CreateRibbonEditBox();
            this.buttonSubmit = this.Factory.CreateRibbonButton();
            this.editBoxPass = this.Factory.CreateRibbonEditBox();
            this.tab1.SuspendLayout();
            this.groupPostJson.SuspendLayout();
            //
            // tab1
            //
            this.tab1.ControlId.ControlIdType = Microsoft.Office.Tools.Ribbon.RibbonControlIdType.Office;
            this.tab1.Groups.Add(this.groupPostJson);
            this.tab1.Label = "TabAddIns";
            this.tab1.Name = "tab1";
            //
            // groupPostJson
            //
            this.groupPostJson.Items.Add(this.editBoxUrl);
            this.groupPostJson.Items.Add(this.editBoxUser);
            this.groupPostJson.Items.Add(this.editBoxPass);
            this.groupPostJson.Items.Add(this.buttonSubmit);
            this.groupPostJson.Label = "Post JSON";
            this.groupPostJson.Name = "groupPostJson";
            //
            // editBoxUrl
            //
            this.editBoxUrl.Label = "URL";
            this.editBoxUrl.Name = "editBoxUrl";
            this.editBoxUrl.ScreenTip = "URL to post JSON data to";
            //
            // editBoxUser
            //
            this.editBoxUser.Label = "User";
            this.editBoxUser.Name = "editBoxUser";
            this.editBoxUser.ScreenTip = "HTTP Auth Username (Optional)";
            //
            // buttonSubmit
            //
            this.buttonSubmit.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
            this.buttonSubmit.Enabled = false;
            this.buttonSubmit.Image = global::ExcelPostJsonAddIn.Properties.Resources.icon64;
            this.buttonSubmit.Label = "Submit";
            this.buttonSubmit.Name = "buttonSubmit";
            this.buttonSubmit.ShowImage = true;
            this.buttonSubmit.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.buttonSubmit_Click);
            //
            // editBoxPass
            //
            this.editBoxPass.Label = "Pass";
            this.editBoxPass.Name = "editBoxPass";
            this.editBoxPass.ScreenTip = "HTTP Auth Password (Optional)";
            //
            // PostJsonRibbon
            //
            this.Name = "PostJsonRibbon";
            this.RibbonType = "Microsoft.Excel.Workbook";
            this.Tabs.Add(this.tab1);
            this.Load += new Microsoft.Office.Tools.Ribbon.RibbonUIEventHandler(this.PostJsonRibbon_Load);
            this.tab1.ResumeLayout(false);
            this.tab1.PerformLayout();
            this.groupPostJson.ResumeLayout(false);
            this.groupPostJson.PerformLayout();

        }

        #endregion

        internal Microsoft.Office.Tools.Ribbon.RibbonTab tab1;
        internal Microsoft.Office.Tools.Ribbon.RibbonGroup groupPostJson;
        internal Microsoft.Office.Tools.Ribbon.RibbonButton buttonSubmit;
        internal Microsoft.Office.Tools.Ribbon.RibbonEditBox editBoxUrl;
        internal Microsoft.Office.Tools.Ribbon.RibbonEditBox editBoxUser;
        internal Microsoft.Office.Tools.Ribbon.RibbonEditBox editBoxPass;
    }

    partial class ThisRibbonCollection
    {
        internal PostJsonRibbon PostJsonRibbon
        {
            get { return this.GetRibbon<PostJsonRibbon>(); }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@null"
        android:icon="@drawable/ani_setting_menu_open"
        app:showAsAction="always"/>
</menu>

redpajama_set_name: RedPajamaGithub


text:
import { errors } from "@ts-morph/common";
import { changeChildOrder, getGeneralFormatting } from "../../../manipulation";
import { Constructor } from "../../../types";
import { Node } from "../common";

export type ChildOrderableNodeExtensionType = Node;

export interface ChildOrderableNode {
    /**
     * Sets the child order of the node within the parent.
     */
    setOrder(order: number): this;
}

export function ChildOrderableNode<T extends Constructor<ChildOrderableNodeExtensionType>>(Base: T): Constructor<ChildOrderableNode> & T {
    return class extends Base implements ChildOrderableNode {
        setOrder(order: number) {
            const childIndex = this.getChildIndex();
            const parent = this.getParentSyntaxList() || this.getParentSyntaxListOrThrow();
            errors.throwIfOutOfRange(order, [0, parent.getChildCount() - 1], nameof(order));

            if (childIndex === order)
                return this;

            changeChildOrder({
                parent,
                getSiblingFormatting: getGeneralFormatting,
                oldIndex: childIndex,
                newIndex: order,
            });
            return this;
        }
    };
}


text:
layout: post
title: "Setup a Ruby on Rails 6 API project with Docker Compose"
description: "How to setup a Ruby on Rails 6 API project with Docker Compose."
categories: [tutorials]
tags: [api, docker, ruby on rails]
redirect_from:
  - /2019/11/09/
---
Here is a quick rundown on how to setup a Ruby on Rails 6 API project with Docker Compose.

* Kramdown table of contents
{:toc .toc}

## Prerequisites

### Docker and Docker Compose

Docker: [https://www.docker.com/get-started][Docker]{:target="_blank"}

Docker Compose: [https://docs.docker.com/compose/install/][Docker Compose Install]{:target="_blank"}

For example, I have:

>$ docker -v

>$ Docker version 19.03.2, build 6a30dfc
>
>$ docker-compose -v

>$ docker-compose version 1.24.1, build 4667896b

### Ruby

Rails 6 requires Ruby 2.5.0 or newer[^1].

If the local machine hasn't got Ruby installed,
[RVM][RVM]{:target="_blank"} would be a common solution to consider.

For installing RVM with default Ruby and Rails in one command, run:

```bash
\curl -sSL https://get.rvm.io | bash -s stable --rails
```

To verify the successful installation:

>$ ruby -v

>$ ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin18]
>
>$ rails -v

>$ Rails 6.0.2.1

## Create a Rails 6 API project

To create a new Ruby on Rails 6 API project, run:

```bash
rails new rails-6-api-docker-demo --api --database=postgresql -T -C
```

- `rails-6-api-docker-demo`: The name of the new project.
- `--api`: Create an API only project.
- `--database=postgresql`: Use [PostgresQL][PostgresQL]{:target="_blank"} as the default database adapter.
- `-T`: (Optional) Skip test files. [RSpec][Rspec]{:target="_blank"} would be a more common option.
- `-C`: (Optional) Skip ActionCable if no WebSockets is needed for the project.

## Setup Docker

### Create .dockerignore

```bash
cd rails-6-api-docker-demo
touch .dockerignore
```

[`.dockerignore`][.dockerignore]{:target="_blank"}
files essentially works the same way as `.gitignore`, but for docker containers.
You may just use the content from `.gitignore` file plus the `.git` folder and `.gitignore` itself.

[gitignore.io][gitignore.io]{:target="_blank"} can be handy for generating the desired `.gitignore` file.
For example, <https://www.gitignore.io/api/git,rails,rubymine>{:target="_blank"}
gives an example of `.gitignore` file for git, rails and rubymine IDE.

**Here's a complete example**: <https://gist.github.com/yizeng/eeeb48d6823801061791cc5581f7e1fc>{:target="_blank"}

### Create Dockerfile

```bash
touch Dockerfile
```

A Dockerfile is a text document that contains all the commands
a user could call on the command line to assemble an image.
Using docker build users can create an automated build
that executes several command-line instructions in succession.

Full documentation can be found [here][Dockerfile reference]{:target="_blank"}.

```bash
FROM ruby:alpine

RUN apk update && apk add bash build-base nodejs postgresql-dev tzdata

RUN mkdir /project
WORKDIR /project

COPY Gemfile Gemfile.lock ./
RUN gem install bundler --no-document
RUN bundle install --no-binstubs --jobs $(nproc) --retry 3

COPY . .

CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
```

- `FROM ruby:alpine`: Select the base image to build from.
Here uses the latest alpine version of Ruby.
Note that the version needs to match the Ruby version in `Gemfile`.
If there is a mismatch (e.g. `ruby '2.6.5'` in `Gemfile`), then here would be `FROM ruby:2.6.5-alpine`.
More versions can be found at the [Docker Hub](https://hub.docker.com/_/ruby){:target="_blank"}.
- `RUN apk update && apk add build-base nodejs postgresql-dev tzdata`: Install the required packages inside Docker.
- `RUN mkdir /project`: Create a folder called `project` to host the codebase.
- `WORKDIR /project`: Set the working directory to `project` folder.
- `COPY Gemfile Gemfile.lock ./`: Copy the files to the working directory.
- `RUN gem install bundler`: Install the bundler gem.
It needs to match the version in `Gemfile.lock`,
A specific version can be set like `RUN gem install bundler -v 2.0.2`.
- `COPY . .`: Copy the codebase into Docker.
- `CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]`: Set the start command.

## Setup Docker Compose

### Create docker-compose.yml

```bash
touch docker-compose.yml
```

Docker compose is a tool to build a multi-container application,
where `docker-compose.yml` is the YAML config file that
tells Docker Compose how to build the containers together.

A more detailed documentation can be found [here][Compose File Reference]{:target="_blank"}.

```yaml
version: '3'

services:
  db:
    image: 'postgres:10-alpine'
    volumes:
      - 'postgres:/var/lib/postgresql/data'
    ports:
      - '5432:5432'
    environment:
      - POSTGRES_HOST_AUTH_METHOD=trust

  redis:
    image: 'redis:5-alpine'
    command: redis-server
    ports:
      - '6379:6379'
    volumes:
      - 'redis:/data'

  web:
    depends_on:
      - 'db'
      - 'redis'
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    ports:
      - '3000:3000'
    environment:
      - DATABASE_HOST=db

volumes:
  redis:
  postgres:
```

Here defines 3 services in order to run the Rails application:
- `db`: The PostgreSQL database service, which uses `postgres:10-alpine` here for example.
It maps port 5432 inside Docker to the same port on local host machine.
- `redis`: The Redis caching service, which uses `redis:5-alpine` here for example.
It maps port 6379 inside Docker to the same port on local host machine.
This is needed if Sidekiq is used for job processing
or Rails caching is set to Redis instead of memcache.
- `web`: This is how the Rails API is composed.
It depends on `db` and `redis` with port 3000 exposed on host machine.

### Config database.yml

The default Ruby on Rails' `database.yml` needs to be configed with
the Docker database URL by adding `host`, `username` and `password` to it.

```yaml
default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: <%= ENV.fetch("DATABASE_HOST") { "localhost" } %>
  port: <%= ENV.fetch("DATABASE_PORT") { 5432 } %>
  username: <%= ENV.fetch("DATABASE_USERNAME") { "postgres" } %>
  password: <%= ENV.fetch("DATABASE_PASSWORD") { "" } %>

development:
  <<: *default
  database: rails_6_api_docker_demo_development

test:
  <<: *default
  database: rails_6_api_docker_demo_test

production:
  <<: *default
  database: rails_6_api_docker_demo_production
  username: <%= ENV.fetch("DATABASE_USERNAME") { "rails_6_api_docker_demo" } %>
  password: <%= ENV.fetch("DATABASE_PASSWORD") { "" } %>
```

## Start Rails Server

Build the containers

```bash
docker-compose build
```

Before starting the server, Rails databases need to be created first.

```bash
docker-compose run web bundle exec rails db:create
docker-compose run web bundle exec rails db:migrate
```

Finally, to build and spin up the Rails 6 API server:

```bash
docker-compose up --build
```

Head over to <http://localhost:3000>{:target="_blank"} to test it out and start building the real API!

## Install RSpec (Optional)

If the project was initialized with `-T` option that no tests are generated,
a testing framework would be needed for the project.

Here is how to add [RSpec][RSpec]{:target="_blank"} support.

1. Add rspec-rails to Gemfile

   ```ruby
   # Add it inside group :development, :test
   group :development, :test do
     # some existing gems...
     # ...

     gem 'rspec-rails'
   end
   ```

2. Rebuild the containers

   ```bash
   docker-compose build
   ```

3. Install RSpec

   ```bash
   docker-compose run web bundle exec rails generate rspec:install
   ```

4. Run the tests

   ```bash
   docker-compose run web bundle exec rspec
   ```

## Troubleshooting

> Error starting userland proxy: listen tcp 0.0.0.0:6379: bind: address already in use

- **Reason**: Port 6379 is already in use on local machine.This is most likely that there is another Redis server running locally.

- **Solution**: Either stop the Redis on local machine or map to another port in `docker-compose.yml`, like `- '6380:6379'`.

> Error starting userland proxy: listen tcp 0.0.0.0:5432: bind: address already in use

- **Reason**: Port 5432 is already in use on local machine. This is most likely that there is another PostgreSQL server running locally.

- **Solution**: Either stop the PostgreSQL on local machine or map to another port in `docker-compose.yml`, like `- '5434:5432'`.

> Your Ruby version is 2.6.5, but your Gemfile specified 2.6.3

> ERROR: Service 'web' failed to build: The command '/bin/sh -c bundle install' returned a non-zero code: 18

- **Reason**: There is a Ruby version mismatch between `Gemfile` and Docker container.

- **Solution**: Either update the Ruby version in `Gemfile` to `2.6.5`, or pull explicitly Ruby `2.6.3` image in `Dockerfile` like `FROM ruby:2.6.3-alpine`.

> /usr/local/bundle/ruby/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/railtie.rb:39:in

> rescue in block in \<class:Railtie\>': tzinfo-data is not present.

> Please add gem 'tzinfo-data' to your Gemfile and run bundle install (TZInfo::DataSourceNotFound)

> /usr/local/bundle/ruby/2.6.0/gems/tzinfo-1.2.5/lib/tzinfo/zoneinfo_data_source.rb:180:in `initialize':

> None of the paths included in TZInfo::ZoneinfoDataSource.search_path are valid zoneinfo directories. (TZInfo::ZoneinfoDirectoryNotFound)

- **Reason**: Required `tzdata` package was not installed in Docker container.

- **Solution**: Include `tzdata` in `Dockerfile`'s `RUN apk add` command (see details above).

> /usr/local/lib/ruby/2.6.0/rubygems.rb:283:in `find_spec_for_exe':

> Could not find 'bundler' (2.0.2) required by your /project/Gemfile.lock. (Gem::GemNotFoundException)

> ERROR: Service 'web' failed to build: The command '/bin/sh -c bundle install' returned a non-zero code: 1

- **Reason**: Required gem bundler was not installed in Docker container.

- **Solution**: Include `RUN gem install bundler` command in `Dockerfile` (see details above).

[^1]: https://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#ruby-versions

[Docker]: https://www.docker.com/get-started
[Docker Compose Install]: https://docs.docker.com/compose/install
[RVM]: https://rvm.io/
[PostgreSQL]:https://www.postgresql.org/
[RSpec]:https://rspec.info/
[.dockerignore]: https://docs.docker.com/engine/reference/builder/#dockerignore-file
[gitignore.io]: https://www.gitignore.io/
[Dockerfile reference]: https://docs.docker.com/engine/reference/builder/
[Compose File Reference]: https://docs.docker.com/compose/compose-file/


text:
import React from "react";
import { AccountMenuProps } from "./interfaces";
import { Link } from "../link";
import { shortRevision } from "../util";
import { t } from "../i18next_wrapper";
import { ExternalUrl } from "../external_urls";
import { Icon, iconFile } from "../farm_designer/panel_header";

export const AdditionalMenu = (props: AccountMenuProps) => {
  return

      <Link to="/app/designer/settings?highlight=account"
        onClick={props.close("accountMenuOpen")}>

        {t("Account Settings")}
      </Link>

      <Link to="/app/logs" onClick={props.close("accountMenuOpen")}>

        {t("Logs")}
      </Link>

      <Link to="/app/designer/setup" onClick={props.close("accountMenuOpen")}>

        {t("Setup")}
      </Link>

      <Link to="/app/designer/help" onClick={props.close("accountMenuOpen")}>

        {t("Help")}
      </Link>

        {t("Logout")}

      {t("APP VERSION")}:

        {shortRevision().slice(0, 8)}

;
};


text:
import unittest
from unittest.mock import MagicMock
from datetime import datetime

import six

from airflow import configuration, models
from airflow.contrib.operators.bigquery_get_data import BigQueryGetDataOperator
from airflow.contrib.operators.bigquery_operator import \
    BigQueryCreateExternalTableOperator, BigQueryCreateEmptyTableOperator, \
    BigQueryDeleteDatasetOperator, BigQueryCreateEmptyDatasetOperator, \
    BigQueryOperator, BigQueryConsoleLink
from airflow.contrib.operators.bigquery_table_delete_operator import \
    BigQueryTableDeleteOperator
from airflow.contrib.operators.bigquery_to_bigquery import \
    BigQueryToBigQueryOperator
from airflow.contrib.operators.bigquery_to_gcs import BigQueryToCloudStorageOperator
from airflow.models import DAG, TaskFail, TaskInstance
from airflow.settings import Session
from tests.compat import mock

TASK_ID = 'test-bq-create-table-operator'
TEST_DATASET = 'test-dataset'
TEST_GCP_PROJECT_ID = 'test-project'
TEST_TABLE_ID = 'test-table-id'
TEST_GCS_BUCKET = 'test-bucket'
TEST_GCS_DATA = ['dir1/*.csv']
TEST_SOURCE_FORMAT = 'CSV'
DEFAULT_DATE = datetime(2015, 1, 1)
TEST_DAG_ID = 'test-bigquery-operators'

class BigQueryCreateEmptyTableOperatorTest(unittest.TestCase):

    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryCreateEmptyTableOperator(task_id=TASK_ID,
                                                    dataset_id=TEST_DATASET,
                                                    project_id=TEST_GCP_PROJECT_ID,
                                                    table_id=TEST_TABLE_ID)

        operator.execute(None)
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .create_empty_table \
            .assert_called_once_with(
                dataset_id=TEST_DATASET,
                project_id=TEST_GCP_PROJECT_ID,
                table_id=TEST_TABLE_ID,
                schema_fields=None,
                time_partitioning={},
                labels=None
            )

class BigQueryCreateExternalTableOperatorTest(unittest.TestCase):

    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryCreateExternalTableOperator(
            task_id=TASK_ID,
            destination_project_dataset_table='{}.{}'.format(
                TEST_DATASET, TEST_TABLE_ID
            ),
            schema_fields=[],
            bucket=TEST_GCS_BUCKET,
            source_objects=TEST_GCS_DATA,
            source_format=TEST_SOURCE_FORMAT
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .create_external_table \
            .assert_called_once_with(
                external_project_dataset_table='{}.{}'.format(
                    TEST_DATASET, TEST_TABLE_ID
                ),
                schema_fields=[],
                source_uris=['gs://{}/{}'.format(TEST_GCS_BUCKET, source_object)
                             for source_object in TEST_GCS_DATA],
                source_format=TEST_SOURCE_FORMAT,
                compression='NONE',
                skip_leading_rows=0,
                field_delimiter=',',
                max_bad_records=0,
                quote_character=None,
                allow_quoted_newlines=False,
                allow_jagged_rows=False,
                src_fmt_configs={},
                labels=None
            )

class BigQueryDeleteDatasetOperatorTest(unittest.TestCase):
    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryDeleteDatasetOperator(
            task_id=TASK_ID,
            dataset_id=TEST_DATASET,
            project_id=TEST_GCP_PROJECT_ID
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .delete_dataset \
            .assert_called_once_with(
                dataset_id=TEST_DATASET,
                project_id=TEST_GCP_PROJECT_ID
            )

class BigQueryCreateEmptyDatasetOperatorTest(unittest.TestCase):
    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryCreateEmptyDatasetOperator(
            task_id=TASK_ID,
            dataset_id=TEST_DATASET,
            project_id=TEST_GCP_PROJECT_ID
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .create_empty_dataset \
            .assert_called_once_with(
                dataset_id=TEST_DATASET,
                project_id=TEST_GCP_PROJECT_ID,
                dataset_reference={}
            )

class BigQueryOperatorTest(unittest.TestCase):
    def setUp(self):
        configuration.conf.load_test_config()
        self.dagbag = models.DagBag(
            dag_folder='/dev/null', include_examples=True)
        self.args = {'owner': 'airflow', 'start_date': DEFAULT_DATE}
        self.dag = DAG(TEST_DAG_ID, default_args=self.args)

    def tearDown(self):
        session = Session()
        session.query(models.TaskInstance).filter_by(
            dag_id=TEST_DAG_ID).delete()
        session.query(TaskFail).filter_by(
            dag_id=TEST_DAG_ID).delete()
        session.commit()
        session.close()

    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        operator = BigQueryOperator(
            task_id=TASK_ID,
            sql='Select * from test_table',
            destination_dataset_table=None,
            write_disposition='WRITE_EMPTY',
            allow_large_results=False,
            flatten_results=None,
            bigquery_conn_id='google_cloud_default',
            udf_config=None,
            use_legacy_sql=True,
            maximum_billing_tier=None,
            maximum_bytes_billed=None,
            create_disposition='CREATE_IF_NEEDED',
            schema_update_options=(),
            query_params=None,
            labels=None,
            priority='INTERACTIVE',
            time_partitioning=None,
            api_resource_configs=None,
            cluster_fields=None,
        )

        operator.execute(MagicMock())
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .run_query \
            .assert_called_once_with(
                sql='Select * from test_table',
                destination_dataset_table=None,
                write_disposition='WRITE_EMPTY',
                allow_large_results=False,
                flatten_results=None,
                udf_config=None,
                maximum_billing_tier=None,
                maximum_bytes_billed=None,
                create_disposition='CREATE_IF_NEEDED',
                schema_update_options=(),
                query_params=None,
                labels=None,
                priority='INTERACTIVE',
                time_partitioning=None,
                api_resource_configs=None,
                cluster_fields=None,
            )

    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_bigquery_operator_defaults(self, mock_hook):

        operator = BigQueryOperator(
            task_id=TASK_ID,
            sql='Select * from test_table',
            dag=self.dag, default_args=self.args
        )

        operator.execute(MagicMock())
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .run_query \
            .assert_called_once_with(
                sql='Select * from test_table',
                destination_dataset_table=None,
                write_disposition='WRITE_EMPTY',
                allow_large_results=False,
                flatten_results=None,
                udf_config=None,
                maximum_billing_tier=None,
                maximum_bytes_billed=None,
                create_disposition='CREATE_IF_NEEDED',
                schema_update_options=(),
                query_params=None,
                labels=None,
                priority='INTERACTIVE',
                time_partitioning=None,
                api_resource_configs=None,
                cluster_fields=None,
            )

        self.assertTrue(isinstance(operator.sql, six.string_types))
        ti = TaskInstance(task=operator, execution_date=DEFAULT_DATE)
        ti.render_templates()
        self.assertTrue(isinstance(ti.task.sql, six.string_types))

    @mock.patch('airflow.contrib.operators.bigquery_operator.BigQueryHook')
    def test_bigquery_operator_extra_link(self, mock_hook):
        bigquery_task = BigQueryOperator(
            task_id=TASK_ID,
            sql='SELECT * FROM test_table',
            dag=self.dag,
        )
        self.dag.clear()

        ti = TaskInstance(
            task=bigquery_task,
            execution_date=DEFAULT_DATE,
        )

        job_id = '12345'
        ti.xcom_push(key='job_id', value=job_id)

        self.assertEquals(
            'https://console.cloud.google.com/bigquery?j={job_id}'.format(job_id=job_id),
            bigquery_task.get_extra_links(DEFAULT_DATE, BigQueryConsoleLink.name),
        )

        self.assertEquals(
            '',
            bigquery_task.get_extra_links(datetime(2019, 1, 1), BigQueryConsoleLink.name),
        )

class BigQueryGetDataOperatorTest(unittest.TestCase):

    @mock.patch('airflow.contrib.operators.bigquery_get_data.BigQueryHook')
    def test_execute(self, mock_hook):

        max_results = '100'
        selected_fields = 'DATE'
        operator = BigQueryGetDataOperator(task_id=TASK_ID,
                                           dataset_id=TEST_DATASET,
                                           table_id=TEST_TABLE_ID,
                                           max_results=max_results,
                                           selected_fields=selected_fields,
                                           )
        operator.execute(None)
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .get_tabledata \
            .assert_called_once_with(
                dataset_id=TEST_DATASET,
                table_id=TEST_TABLE_ID,
                max_results=max_results,
                selected_fields=selected_fields,
            )

class BigQueryTableDeleteOperatorTest(unittest.TestCase):
    @mock.patch('airflow.contrib.operators.bigquery_table_delete_operator.BigQueryHook')
    def test_execute(self, mock_hook):
        ignore_if_missing = True
        deletion_dataset_table = '{}.{}'.format(TEST_DATASET, TEST_TABLE_ID)

        operator = BigQueryTableDeleteOperator(
            task_id=TASK_ID,
            deletion_dataset_table=deletion_dataset_table,
            ignore_if_missing=ignore_if_missing
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .run_table_delete \
            .assert_called_once_with(
                deletion_dataset_table=deletion_dataset_table,
                ignore_if_missing=ignore_if_missing
            )

class BigQueryToBigQueryOperatorTest(unittest.TestCase):
    @mock.patch('airflow.contrib.operators.bigquery_to_bigquery.BigQueryHook')
    def test_execute(self, mock_hook):
        source_project_dataset_tables = '{}.{}'.format(
            TEST_DATASET, TEST_TABLE_ID)
        destination_project_dataset_table = '{}.{}'.format(
            TEST_DATASET + '_new', TEST_TABLE_ID)
        write_disposition = 'WRITE_EMPTY'
        create_disposition = 'CREATE_IF_NEEDED'
        labels = {'k1': 'v1'}

        operator = BigQueryToBigQueryOperator(
            task_id=TASK_ID,
            source_project_dataset_tables=source_project_dataset_tables,
            destination_project_dataset_table=destination_project_dataset_table,
            write_disposition=write_disposition,
            create_disposition=create_disposition,
            labels=labels
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .run_copy \
            .assert_called_once_with(
                source_project_dataset_tables=source_project_dataset_tables,
                destination_project_dataset_table=destination_project_dataset_table,
                write_disposition=write_disposition,
                create_disposition=create_disposition,
                labels=labels
            )

class BigQueryToCloudStorageOperatorTest(unittest.TestCase):
    @mock.patch('airflow.contrib.operators.bigquery_to_gcs.BigQueryHook')
    def test_execute(self, mock_hook):
        source_project_dataset_table = '{}.{}'.format(
            TEST_DATASET, TEST_TABLE_ID)
        destination_cloud_storage_uris = ['gs://some-bucket/some-file.txt']
        compression = 'NONE'
        export_format = 'CSV'
        field_delimiter = ','
        print_header = True
        labels = {'k1': 'v1'}

        operator = BigQueryToCloudStorageOperator(
            task_id=TASK_ID,
            source_project_dataset_table=source_project_dataset_table,
            destination_cloud_storage_uris=destination_cloud_storage_uris,
            compression=compression,
            export_format=export_format,
            field_delimiter=field_delimiter,
            print_header=print_header,
            labels=labels
        )

        operator.execute(None)
        mock_hook.return_value \
            .get_conn.return_value \
            .cursor.return_value \
            .run_extract \
            .assert_called_once_with(
                source_project_dataset_table=source_project_dataset_table,
                destination_cloud_storage_uris=destination_cloud_storage_uris,
                compression=compression,
                export_format=export_format,
                field_delimiter=field_delimiter,
                print_header=print_header,
                labels=labels
            )


text:
package org.jboss.logmanager.handlers;

import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * An output stream that writes data to a {@link java.net.DatagramSocket DatagramSocket}.
 *
 * @author James R. Perkins
 */
public class UdpOutputStream extends OutputStream implements FlushableCloseable {
    private final DatagramSocket socket;

    public UdpOutputStream(final InetAddress address, final int port) throws IOException {
        socket = new DatagramSocket();
        socket.connect(address, port);
    }

    @Override
    public void write(final int b) throws IOException {
        final byte[] msg = new byte[] {(byte) b};
        final DatagramPacket packet = new DatagramPacket(msg, 1);
        socket.send(packet);
    }

    @Override
    public void write(final byte[] b) throws IOException {
        if (b != null) {
            final DatagramPacket packet = new DatagramPacket(b, b.length);
            socket.send(packet);
        }
    }

    @Override
    public void write(final byte[] b, final int off, final int len) throws IOException {
        if (b != null) {
            final DatagramPacket packet = new DatagramPacket(b, off, len);
            socket.send(packet);
        }
    }

    @Override
    public void close() throws IOException {
        socket.close();
    }
}


text:
<?php

Yii::setAlias('common', __DIR__ . '/../');
Yii::setAlias('frontend', __DIR__ . '/../../frontend');
Yii::setAlias('backend', __DIR__ . '/../../backend');

return array(
	'adminEmail' => 'admin@example.com',
	'supportEmail' => 'support@example.com',

	'components.cache' => array(
		'class' => 'yii\caching\FileCache',
	),

	'components.db' => array(
		'class' => 'yii\db\Connection',
		'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
		'username' => 'root',
		'password' => '',
		'charset' => 'utf8',
	),
);


text:
<?php

/**
 * @file
 * Contains \Drupal\video\StreamWrapper\DailymotionStream.
 */

namespace Drupal\video\StreamWrapper;

use Drupal\Core\StreamWrapper\ReadOnlyStream;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;

/**
 * Defines a Dailymotion (dailymotion://) stream wrapper class.
 */
class DailymotionStream extends VideoRemoteStreamWrapper {

  protected static $base_url = 'http://www.dailymotion.com/video';

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return t('Dailymotion');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return t('Video served by the Dailymotion services.');
  }

  /**
   * {@inheritdoc}
   */
  public static function baseUrl() {
    return self::$base_url;
  }
}


text:
function getImageTags(imgurl) {

    console.log(imgurl);

  if (Math.floor(Date.now() / 1000) - localStorage.getItem('tokenTimeStamp') > 86400 || localStorage.getItem('accessToken') === null) {
    getCredentials(function() {
      postImage(imgurl);
    });
  } else {
    postImage(imgurl);
  }
}

function getCredentials(cb) {
  var data = {
    'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET
  };
  var url = 'https://api.clarifai.com/v1/token';

  return axios.post(url, data, {
    'transformRequest': [
      function() {
        return transformDataToParams(data);
      }
    ]
  }).then(function(r) {
    localStorage.setItem('accessToken', r.data.access_token);
    localStorage.setItem('tokenTimestamp', Math.floor(Date.now() / 1000));
    cb();
  }, function(err) {
    console.log(err);
  });
}

function transformDataToParams(data) {
  var str = [];
  for (var p in data) {
    if (data.hasOwnProperty(p) && data[p]) {
      if (typeof data[p] === 'string'){
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]));
      }
      if (typeof data[p] === 'object'){
        for (var i in data[p]) {
          str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p][i]));
        }
      }
    }
  }
  return str.join('&');
}

function postImage(imgurl) {
  var accessToken = localStorage.getItem('accessToken');
  var data = {
    'url': imgurl
  };
  var url = 'https://api.clarifai.com/v1/tag';
  return axios.post(url, data, {
    'headers': {
      'Authorization': 'Bearer ' + accessToken
    }
    /*'content-type': 'application/x-www-form-urlencoded'*/
  }).then(function(r) {
    console.log(r.data);
    /*parseResponse(r.data, r.data.results[0].result.tag.probs);
  }, function(err) {
    console.log('Sorry, something is wrong: ' + err);
  });*/
    parseResponse(r.data);
    }, function(err) {
      console.log('Sorry, something is wrong: ' + err);
    });
}
//function parseResponse(resp, probs) {
  function parseResponse(resp){
  var tags = [];
  if (resp.status_code === 'OK') {
    var results = resp.results;
    tags = results[0].result.tag.classes;

    numTagsOutputted = 3;
    if (tags.length < numTagsOutputted)
      numTagsOutputted = tags.length;
    var prompt = "Ahead I see";
    for (var i = 0; i < numTagsOutputted; i++) {
      prompt += ", " + tags[i];
    }

    textToVoice(prompt);

  } else {
    console.log('Sorry, something is wrong.');
  }
/*  var i = 0;
  while (probs[i] > 0.8 && i < probs.length) {i++;
    console.log(probs[i]);
  }
  tags = tags.slice(0,i);*/
  textToSpeechImageTags(tags);
  return tags;
}


text:
#pragma once

#include <opcua.h>
#include <opcua_builtintypes.h>

namespace opcua {

template <class T>
inline const OpcUa_EncodeableType& GetEncodableType();

}

#define OpcUa_Guid_CopyTo(xSource, xDestination) \
  OpcUa_MemCpy(xDestination, sizeof(OpcUa_Guid), xSource, sizeof(OpcUa_Guid))

#define OPCUA_DEFINE_METHODS(Name)              \
  inline void Initialize(OpcUa_##Name& value) { \
    OpcUa_##Name##_Initialize(&value);          \
  }                                             \
                                                \
  inline void Clear(OpcUa_##Name& value) { OpcUa_##Name##_Clear(&value); }

#define OPCUA_DEFINE_MEMBERS_EX(Name, OpcUa_Name)  \
  Name() { ::OpcUa_Name##_Initialize(this); }      \
  ~Name() { ::OpcUa_Name##_Clear(this); }          \
                                                   \
  Name(Name&& source) : OpcUa_Name{source} {       \
    ::OpcUa_Name##_Initialize(&source);            \
  }                                                \
                                                   \
  Name(OpcUa_Name&& source) : OpcUa_Name{source} { \
    ::OpcUa_Name##_Initialize(&source);            \
  }                                                \
                                                   \
  Name& operator=(Name&& source) {                 \
    if (&source != this) {                         \
      static_cast<::OpcUa_Name&>(*this) = source;  \
      ::OpcUa_Name##_Initialize(&source);          \
    }                                              \
    return *this;                                  \
  }                                                \
                                                   \
  Name& operator=(OpcUa_Name&& source) {           \
    if (&source != this) {                         \
      static_cast<::OpcUa_Name&>(*this) = source;  \
      ::OpcUa_Name##_Initialize(&source);          \
    }                                              \
    return *this;                                  \
  }

#define OPCUA_DEFINE_MEMBERS(Name) OPCUA_DEFINE_MEMBERS_EX(Name, OpcUa_##Name)

#define OPCUA_DEFINE_STRUCT_EX(Name, OpcUa_Name) \
  struct Name : OpcUa_Name {                     \
    OPCUA_DEFINE_MEMBERS_EX(Name, OpcUa_Name)    \
                                                 \
    Name(const Name&) = delete;                  \
    Name& operator=(const Name&) = delete;       \
                                                 \
    void release(OpcUa_Name& target) {           \
      ::OpcUa_Name##_Clear(&target);             \
      target = *this;                            \
      ::OpcUa_Name##_Initialize(this);           \
    }                                            \
  };                                             \
                                                 \
  OPCUA_DEFINE_METHODS(Name)

#define OPCUA_DEFINE_STRUCT(Name) OPCUA_DEFINE_STRUCT_EX(Name, OpcUa_##Name)

#define OPCUA_DEFINE_ENCODEABLE(Name)                                    \
  struct Name : OpcUa_##Name {                                           \
    using OpcUa_Type = OpcUa_##Name;                                     \
                                                                         \
    Name(const Name& source) {                                           \
      CopyEncodeable(type(), &source, static_cast<OpcUa_Type*>(this));   \
    }                                                                    \
                                                                         \
    Name& operator=(const Name& source) {                                \
      if (&source != this) {                                             \
        ::OpcUa_##Name##_Clear(this);                                    \
        CopyEncodeable(type(), &source, static_cast<OpcUa_Type*>(this)); \
      }                                                                  \
      return *this;                                                      \
    }                                                                    \
                                                                         \
    OPCUA_DEFINE_MEMBERS(Name)                                           \
                                                                         \
    static const OpcUa_EncodeableType& type() {                          \
      return OpcUa_##Name##_EncodeableType;                              \
    }                                                                    \
                                                                         \
    void release(OpcUa_##Name& target) {                                 \
      ::OpcUa_##Name##_Clear(&target);                                   \
      target = *this;                                                    \
      ::OpcUa_##Name##_Initialize(this);                                 \
    }                                                                    \
  };                                                                     \
                                                                         \
  template <>                                                            \
  inline const OpcUa_EncodeableType& GetEncodableType<OpcUa_##Name>() {  \
    return OpcUa_##Name##_EncodeableType;                                \
  }                                                                      \
                                                                         \
  OPCUA_DEFINE_METHODS(Name)

/*============================================================================
 * OpcUa_NodeId_CopyTo
 *===========================================================================*/
inline OpcUa_StatusCode OpcUa_NodeId_CopyTo(const OpcUa_NodeId* a_pSource,
                                            OpcUa_NodeId* a_pDestination) {
  OpcUa_InitializeStatus(OpcUa_Module_ProxyStub, "OpcUa_NodeId_CopyTo");

  OpcUa_ReturnErrorIfArgumentNull(a_pSource);
  OpcUa_ReturnErrorIfArgumentNull(a_pDestination);

  OpcUa_NodeId_Clear(a_pDestination);

  a_pDestination->IdentifierType = a_pSource->IdentifierType;
  a_pDestination->NamespaceIndex = a_pSource->NamespaceIndex;

  switch (a_pSource->IdentifierType) {
    case OpcUa_IdentifierType_Numeric: {
      a_pDestination->Identifier.Numeric = a_pSource->Identifier.Numeric;
      break;
    }
    case OpcUa_IdentifierType_String: {
      OpcUa_String_StrnCpy(&a_pDestination->Identifier.String,
                           &a_pSource->Identifier.String,
                           OPCUA_STRING_LENDONTCARE);
      break;
    }
    case OpcUa_IdentifierType_Opaque: {
      a_pDestination->Identifier.ByteString.Length =
          a_pSource->Identifier.ByteString.Length;

      if (a_pDestination->Identifier.ByteString.Length > 0) {
        a_pDestination->Identifier.ByteString.Data =
            (OpcUa_Byte*)OpcUa_Alloc(a_pSource->Identifier.ByteString.Length);
        OpcUa_GotoErrorIfAllocFailed(
            a_pDestination->Identifier.ByteString.Data);
        OpcUa_MemCpy(a_pDestination->Identifier.ByteString.Data,
                     a_pDestination->Identifier.ByteString.Length,
                     a_pSource->Identifier.ByteString.Data,
                     a_pSource->Identifier.ByteString.Length);
      } else {
        a_pDestination->Identifier.ByteString.Data = OpcUa_Null;
      }
      break;
    }
    case OpcUa_IdentifierType_Guid: {
      if (a_pSource->Identifier.Guid != OpcUa_Null) {
        a_pDestination->Identifier.Guid =
            (OpcUa_Guid*)OpcUa_Alloc(sizeof(OpcUa_Guid));
        OpcUa_GotoErrorIfAllocFailed(a_pDestination->Identifier.Guid);
        OpcUa_Guid_CopyTo(a_pSource->Identifier.Guid,
                          a_pDestination->Identifier.Guid);
      } else {
        a_pDestination->Identifier.Guid = OpcUa_Null;
      }
      break;
    }
    default: {
      OpcUa_GotoErrorWithStatus(OpcUa_BadInvalidArgument);
    }
  }

  OpcUa_ReturnStatusCode;
  OpcUa_BeginErrorHandling;

  OpcUa_NodeId_Clear(a_pDestination);

  OpcUa_FinishErrorHandling;
}


text:
    <title>Topics | St John Ambulance Braintree and Bocking</title>

    <link rel="stylesheet" type="text/css" href="./css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">
    <link rel="stylesheet/less" type="text/css" href="./css/bootswatch.less" />
    <link rel="stylesheet/less" type="text/css" href="./css/variables.less" />

    <meta name="ROBOTS" content="NOINDEX, NOFOLLOW">

SJA Braintree Badgers Topic Site

Legal Declaration:

Reproduction of the content on this website is strictly prohibited. Topic books are copyright of St John Ambulance.

If there are any issuses please contact me using this link.

Hello There

You can use this site to download and view the St John Ambulance Badgers Topic Books.

Download:

Active Badger

Adventure Badger

Badger First Aider

Caring Badger

Communicate Badger

Creative Badger

Eco Badger

Entertain Badger

Global Badger

Healthy Badger

Hungry Badger

My-World Badger

Safety Badger

St John Family Badger

Wild Badger

© St John Ambulance Braintree and Bocking Badgers Unit 2015

Reproduction of the content on this website is strictly prohibited.

Topic Booklets - © St John Ambulance 2015


text:
define(function(require, exports, module) { // jshint ignore:line
    'use strict';

    var demoTemplate = require('text!./demoTemplate.html');
    var SearchView = require('./../search/searchView');

    /**
     * The Demo view class.
     *
     * @class DemoView
     * @param {jQuery<HTMLObject>} $element
     * @constructor
     */
    var DemoView = function($element) {
        /**
         * The DOM element the component is attached too.
         *
         * @property $element
         * @type jQuery<HTMLObject>
         */
        this.$element = $element;

        /**
         * Flag that checks whether or not this component
         * is currently enabled.
         *
         * @property isEnabled
         * @type Boolean
         */
        this.isEnabled = false;

        this.init();
    };

    var proto = DemoView.prototype;

    /**
     * Initializes all the view. This method should setup all
     * event handlers, children and layout manipulations. Once
     * everything has been setup it will promptly enable the
     * component.
     *
     * @method init
     * @returns {DemoView}
     * @private
     */
    proto.init = function() {
        this.setupEventHandlers()
            .setupChildren()
            .setupLayout()
            .enable();

        return this;
    };

    /**
     * Links up the handlers to their events.
     *
     * @method setupEventHandlers
     * @returns {DemoView}
     * @private
     */
    proto.setupEventHandlers = function() {
        return this;
    };

    /**
     * Creates/assigns the children objects
     * of the component.
     *
     * @method setupChildren
     * @returns {DemoView}
     * @private
     */
    proto.setupChildren = function() {
        this.searchView = new SearchView();

        return this;
    };

    /**
     * Removes the children objects of the component.
     *
     * @method removeChildren
     * @returns {DemoView}
     * @private
     */
    proto.removeChildren = function() {
        this.searchView.destroy();
        this.searchView = null;

        return this;
    };

    /**
     * Handles any manipulate of the component element.
     *
     * @method setupLayout
     * @returns {DemoView}
     * @private
     */
    proto.setupLayout = function() {
        this.$element.html(demoTemplate);
        this.searchView.layout();

        return this;
    };

    /**
     * Enables the component and all of the events.
     *
     * @method enable
     * @returns {DemoView}
     * @private
     */
    proto.enable = function() {
        if (this.isEnabled) {
            return this;
        }

        this.searchView.enable();

        this.isEnabled = true;
        return this;
    };

    /**
     * Disables the component and all events associated
     * with the component.
     *
     * @method disable
     * @returns {DemoView}
     * @private
     */
    proto.disable = function() {
        if (!this.isEnabled) {
            return this;
        }

        this.searchView.disable();

        this.isEnabled = false;
        return this;
    };

    /**
     * Disables/removes all children objects created/assigned
     * by the component.
     *
     * @method destroy
     * @returns {DemoView}
     * @private
     */
    proto.destroy = function() {
        return this;
    };

    ///////////////////////////////////////////////////////////////////////////
    // EVENTS
    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////
    // HELPERS
    ///////////////////////////////////////////////////////////////////////////

    return DemoView;
});


text: more in http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/sample-templates-services-us-east-1.html


text:
namespace aura {

// static
scoped_ptr<InputStateLookup> InputStateLookup::Create() {
  return scoped_ptr<InputStateLookup>(new InputStateLookupWin);
}

InputStateLookupWin::InputStateLookupWin() {
}

InputStateLookupWin::~InputStateLookupWin() {
}

bool InputStateLookupWin::IsMouseButtonDown() const {
  return (GetKeyState(VK_LBUTTON) & 0x80) ||
    (GetKeyState(VK_RBUTTON) & 0x80) ||
    (GetKeyState(VK_MBUTTON) & 0x80) ||
    (GetKeyState(VK_XBUTTON1) & 0x80) ||
    (GetKeyState(VK_XBUTTON2) & 0x80);
}

}  // namespace aura


text:
title: Taking Charge of Your Diabetes
date: '2018-03-01'
area: research
subdomain: Diabetes
authors:
  - authorimage: /img/uploads/aysola.jpg
    authorname: 'Jaya Aysola, MD, DTMH, MPH'
    authorrole: Investigator
  - authorimage: /img/uploads/troxel-hi-res1-292x300.jpg
    authorname: 'Andrea B. Troxel, ScD'
    authorrole: Investigator
summary: >-
  Examine the effect of an opt-out default recruitment strategy compared to a
  conventional opt-in strategy on enrollment and adherence to a behavioral
  intervention for poorly controlled diabetic patients
results:
  - result: Enrollment rates were 38% in the opt-out arm and 13% in the opt-in arm
  - result: 496 were randomized to the opt-in arm and 73 to the opt-out arm
features:
  - feature: Glycemic Monitoring Device Configuration
  - feature: Enrollment
spotlight: true
pubs:
  - pubURL: ' https://www.ncbi.nlm.nih.gov/pubmed/28281353'
    pubname: >-
      A Randomized Controlled Trial of Opt-In Versus Opt-Out Enrollment Into a
      Diabetes Behavioral Intervention.
---
## Aim

To examine the effect of an opt-out default recruitment strategy compared to a conventional opt-in strategy on enrollment and adherence to a behavioral intervention for poorly controlled diabetic patients.

## Intervention and Design:

This was a randomized controlled trial looking at University of Pennsylvania primary care practices. Participants of this trial included those with (1) age 18 to 80 years; (2) diabetes diagnosis; and (3) a measured hemoglobin A1c (HbA1c) greater than 8% in the past 12 months.

**Intervention** - They randomized eligible patients into opt-in and opt-out arms prior to enrollment. Those in the opt-out arm received a letter stating that they were enrolled into a diabetes research study with the option to opt out, and those in the opt-in arm received a standard recruitment letter.

**Main Outcomes and Measures** - Main end points include enrollment rate, defined as the proportion of participants who attended the baseline visit, and adherence to daily glycemic monitoring.

## Way to Health Use

- **Study Enrollment**: Enroll and randomize participants in the study

- **Enrollment Tracking**: Track enrollment numbers across all arms

## Findings and Conclusions

Of the 569 eligible participants who received a recruitment letter, 496 were randomized to the opt-in arm and 73 to the opt-out arm. Enrollment rates were 38% in the opt-out arm and 13% in the opt-in arm ( P < .001).

Opt-out defaults, where clinically appropriate, could be a useful approach for increasing the generalizability of low-risk trials testing behavioral interventions in clinical settings.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Areas.Admin.Controllers
{
    /// <summary>
    /// 栏目管理
    /// </summary>
    public class ColumnController : Controller
    {
        #region 展示界面
        /// <summary>
        /// 主界面
        /// </summary>
        [HttpGet]
        public ActionResult Index()
        {
            var columns = Services.Database.Entiyies.Columns.Where(d => d.ParentId == null && d.Type != 1).ToList();
            return View(columns);
        }

        /// <summary>
        /// 新增界面
        /// </summary>
        [HttpGet]
        public ActionResult Add()
        {
            var models = Services.Database.Entiyies.Columns.Where(d => d.Type == Models.ColumnType.Page || d.Type == Models.ColumnType.UrlPage).ToList();
            return View(models);
        }
        [HttpGet]
        [ValidateInput(false)]
        public ActionResult Edit(int id)
        {
            var model = Services.Database.Entiyies.Columns.FirstOrDefault(d => d.Id == id);
            if (model == null)
                return Redirect(Url.Action("Index", "Column"));
            ViewBag.Cols = Services.Database.Entiyies.Columns.Where(d => d.Type == Models.ColumnType.Page || d.Type == Models.ColumnType.UrlPage).ToList();
            return View(model);
        }
        #endregion

        #region 获取数据
        [HttpPost]
        public ActionResult Index(int iDisplayStart, int iDisplayLength, string sEcho, int? parentId)
        {
            var count = Services.Database.Entiyies.Columns
                .Count(d => (d.ParentId == parentId || (parentId == null && d.ParentId == null)) && d.Type != Models.ColumnType.ColumnList);
            var dataList = Services.Database.Entiyies.Columns
                .Where(d => (d.ParentId == parentId || (parentId == null && d.ParentId == null)) && d.Type != Models.ColumnType.ColumnList)
                .OrderByDescending(d => d.Id)
                .Skip(iDisplayStart)
                .Take(iDisplayLength)
                .ToList();
            return Json(new
            {
                sEcho = sEcho,
                iTotalRecords = count,
                iTotalDisplayRecords = count,
                aaData = dataList
            });
        }

        [HttpPost]
        public ActionResult List(int? parentId)
        {
            var datas = Services.Database.Entiyies.Columns.Where(d => (d.ParentId == parentId || (parentId == null && d.ParentId == null)) && d.Type != Models.ColumnType.ColumnList).ToList();
            return Json(datas);
        }

        [HttpPost]
        public ActionResult Templates(byte type)
        {
            switch (type)
            {
                case Models.ColumnType.Content:
                    return Json(new {
                        Small = Common.Template.SmallScreen.ContentTemplate,
                        Big = Common.Template.BigScreen.ContentTemplate
                    });
                case Models.ColumnType.Hiring:
                    return Json(new
                    {
                        Small = Common.Template.SmallScreen.HiringTemplate,
                        Big = Common.Template.BigScreen.HiringTemplate
                    });
                case Models.ColumnType.Page:
                    return Json(new
                    {
                        Small = Common.Template.SmallScreen.PageTemplate,
                        Big = Common.Template.BigScreen.PageTemplate
                    });
                case Models.ColumnType.Product:
                    return Json(new
                    {
                        Small = Common.Template.SmallScreen.ProductTemplate,
                        Big = Common.Template.BigScreen.ProductTemplate
                    });
            }
            return null;
        }
        #endregion

        #region 提交数据
        [HttpPost]
        public ActionResult Add(Model.Column col, HttpPostedFileBase fileImg)
        {

            if (fileImg != null && fileImg.ContentLength > 0)
            {
                string filename = Guid.NewGuid().ToString();
                filename += System.IO.Path.GetExtension(fileImg.FileName);
                fileImg.SaveAs(HttpContext.Server.MapPath("/FileImg/") + filename);
                col.Img = filename;
            }
            Services.Database.Entiyies.Columns.Add(col);
            Services.Database.Entiyies.SaveChanges();
            return Redirect(Url.Action("Index", "Column"));
        }
        [ValidateInput(false)]
        public ActionResult Edit(Model.Column col, HttpPostedFileBase fileImg)
        {
            if (fileImg != null && fileImg.ContentLength > 0)
            {
                string filename = Guid.NewGuid().ToString();
                filename += System.IO.Path.GetExtension(fileImg.FileName);
                fileImg.SaveAs(HttpContext.Server.MapPath("/FileImg/") + filename);
                col.Img = filename;
            }
            System.Data.Entity.Infrastructure.DbEntityEntry entry = Services.Database.Entiyies.Entry(col);
            entry.State = System.Data.EntityState.Modified;
            Services.Database.Entiyies.SaveChanges();
            return Redirect(Url.Action("Index", "Column"));
        }

        [HttpPost]
        public void Delete(int id)
        {
            Services.Database.Entiyies.Columns.Where(d => d.Id == id).ToList().ForEach(d =>
            {
                Services.Database.Entiyies.Columns.Remove(d);
            });
            Services.Database.Entiyies.SaveChanges();
        }
        #endregion
    }
}


text:
package org.apache.causeway.extensions.secman.applib.tenancy.menu;

import java.util.Collection;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.causeway.applib.annotation.Action;
import org.apache.causeway.applib.annotation.ActionLayout;
import org.apache.causeway.applib.annotation.DomainService;
import org.apache.causeway.applib.annotation.DomainServiceLayout;
import org.apache.causeway.applib.annotation.MemberSupport;
import org.apache.causeway.applib.annotation.MinLength;
import org.apache.causeway.applib.annotation.NatureOfService;
import org.apache.causeway.applib.annotation.ObjectSupport;
import org.apache.causeway.applib.annotation.Optionality;
import org.apache.causeway.applib.annotation.Parameter;
import org.apache.causeway.applib.annotation.ParameterLayout;
import org.apache.causeway.applib.annotation.PriorityPrecedence;
import org.apache.causeway.applib.annotation.SemanticsOf;
import org.apache.causeway.applib.services.factory.FactoryService;
import org.apache.causeway.extensions.secman.applib.CausewayModuleExtSecmanApplib;
import org.apache.causeway.extensions.secman.applib.tenancy.dom.ApplicationTenancy;
import org.apache.causeway.extensions.secman.applib.tenancy.dom.ApplicationTenancyRepository;
import org.apache.causeway.extensions.secman.applib.tenancy.man.ApplicationTenancyManager;

/**
 *
 * @since 2.0 {@index}
 */
@Named(ApplicationTenancyMenu.LOGICAL_TYPE_NAME)
@DomainService(
        nature = NatureOfService.VIEW
)
@DomainServiceLayout(
        named = "Security",
        menuBar = DomainServiceLayout.MenuBar.SECONDARY
)
@javax.annotation.Priority(PriorityPrecedence.EARLY)
public class ApplicationTenancyMenu {

    public static final String LOGICAL_TYPE_NAME = CausewayModuleExtSecmanApplib.NAMESPACE + ".ApplicationTenancyMenu";

    public static abstract class ActionDomainEvent<T> extends CausewayModuleExtSecmanApplib.ActionDomainEvent<T> {}

    @Inject private ApplicationTenancyRepository applicationTenancyRepository;
    @Inject private FactoryService factory;

    @ObjectSupport public String iconName() {
        return "applicationTenancy";
    }

    // -- TENANCY MANAGER

    @Action(
            domainEvent = tenancyManager.ActionDomainEvent.class,
            semantics = SemanticsOf.IDEMPOTENT
    )
    @ActionLayout(
            sequence = "100.30.1",
            cssClassFa = "globe"
    )
    public class tenancyManager{

        public class ActionDomainEvent extends ApplicationTenancyMenu.ActionDomainEvent<tenancyManager> { }

        @MemberSupport public ApplicationTenancyManager act(){
            return factory.viewModel(new ApplicationTenancyManager());
        }

    }

    // -- FIND TENANCIES

    @Action(
            domainEvent = findTenancies.ActionDomainEvent.class,
            semantics = SemanticsOf.SAFE
            )
    @ActionLayout(sequence = "100.30.2")
    public class findTenancies{

        public class ActionDomainEvent extends ApplicationTenancyMenu.ActionDomainEvent<findTenancies> {}

        @MemberSupport public Collection<? extends ApplicationTenancy> act(
                @Parameter(optionality = Optionality.OPTIONAL)
                @ParameterLayout(named = "Partial Name Or Path", describedAs = "String to search for, wildcard (*) can be used")
                @MinLength(1) // for auto-complete
                final String partialNameOrPath) {
            return applicationTenancyRepository.findByNameOrPathMatchingCached(partialNameOrPath);
        }
    }

}


text:
namespace http2 {
namespace test {
class WindowUpdatePayloadDecoderPeer;
}  // namespace test

class QUICHE_EXPORT WindowUpdatePayloadDecoder {
 public:
  // Starts decoding a WINDOW_UPDATE frame's payload, and completes it if
  // the entire payload is in the provided decode buffer.
  DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);

  // Resumes decoding a WINDOW_UPDATE frame's payload that has been split across
  // decode buffers.
  DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
                                     DecodeBuffer* db);

 private:
  friend class test::WindowUpdatePayloadDecoderPeer;

  DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);

  Http2WindowUpdateFields window_update_fields_;
};

}  // namespace http2

#endif  // QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_WINDOW_UPDATE_PAYLOAD_DECODER_H_


text:
<resources>
    <string name="app_name">PullRefreshView</string>
</resources>


text:
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/i2c-isa.h>
#include <linux/hwmon.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
#include <asm/io.h>

/* Address is autodetected, there is no default value */
static unsigned short address;

/* Super-I/0 registers and commands */

#define	REG	0x2e	/* The register to read/write */
#define	VAL	0x2f	/* The value to read/write */

static inline void
superio_outb(int reg, int val)
{
	outb(reg, REG);
	outb(val, VAL);
}

static inline int
superio_inb(int reg)
{
	outb(reg, REG);
	return inb(VAL);
}

/* logical device for fans is 0x0A */
#define superio_select() superio_outb(0x07, 0x0A)

static inline void
superio_enter(void)
{
	outb(0x55, REG);
}

static inline void
superio_exit(void)
{
	outb(0xAA, REG);
}

#define SUPERIO_REG_ACT		0x30
#define SUPERIO_REG_BASE	0x60
#define SUPERIO_REG_DEVID	0x20

/* Logical device registers */

#define SMSC_EXTENT		0x80

/* nr is 0 or 1 in the macros below */
#define SMSC47M1_REG_ALARM		0x04
#define SMSC47M1_REG_TPIN(nr)		(0x34 - (nr))
#define SMSC47M1_REG_PPIN(nr)		(0x36 - (nr))
#define SMSC47M1_REG_PWM(nr)		(0x56 + (nr))
#define SMSC47M1_REG_FANDIV		0x58
#define SMSC47M1_REG_FAN(nr)		(0x59 + (nr))
#define SMSC47M1_REG_FAN_PRELOAD(nr)	(0x5B + (nr))

#define MIN_FROM_REG(reg,div)		((reg)>=192 ? 0 : \
					 983040/((192-(reg))*(div)))
#define FAN_FROM_REG(reg,div,preload)	((reg)<=(preload) || (reg)==255 ? 0 : \
					 983040/(((reg)-(preload))*(div)))
#define DIV_FROM_REG(reg)		(1 << (reg))
#define PWM_FROM_REG(reg)		(((reg) & 0x7E) << 1)
#define PWM_EN_FROM_REG(reg)		((~(reg)) & 0x01)
#define PWM_TO_REG(reg)			(((reg) >> 1) & 0x7E)

struct smsc47m1_data {
	struct i2c_client client;
	struct class_device *class_dev;
	struct mutex lock;

	struct mutex update_lock;
	unsigned long last_updated;	/* In jiffies */

	u8 fan[2];		/* Register value */
	u8 fan_preload[2];	/* Register value */
	u8 fan_div[2];		/* Register encoding, shifted right */
	u8 alarms;		/* Register encoding */
	u8 pwm[2];		/* Register value (bit 7 is enable) */
};

static int smsc47m1_detect(struct i2c_adapter *adapter);
static int smsc47m1_detach_client(struct i2c_client *client);

static int smsc47m1_read_value(struct i2c_client *client, u8 reg);
static void smsc47m1_write_value(struct i2c_client *client, u8 reg, u8 value);

static struct smsc47m1_data *smsc47m1_update_device(struct device *dev,
		int init);

static struct i2c_driver smsc47m1_driver = {
	.driver = {
		.owner	= THIS_MODULE,
		.name	= "smsc47m1",
	},
	.attach_adapter	= smsc47m1_detect,
	.detach_client	= smsc47m1_detach_client,
};

/* nr is 0 or 1 in the callback functions below */

static ssize_t get_fan(struct device *dev, char *buf, int nr)
{
	struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
	/* This chip (stupidly) stops monitoring fan speed if PWM is
	   enabled and duty cycle is 0%. This is fine if the monitoring
	   and control concern the same fan, but troublesome if they are
	   not (which could as well happen). */
	int rpm = (data->pwm[nr] & 0x7F) == 0x00 ? 0 :
		  FAN_FROM_REG(data->fan[nr],
			       DIV_FROM_REG(data->fan_div[nr]),
			       data->fan_preload[nr]);
	return sprintf(buf, "%d\n", rpm);
}

static ssize_t get_fan_min(struct device *dev, char *buf, int nr)
{
	struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
	int rpm = MIN_FROM_REG(data->fan_preload[nr],
			       DIV_FROM_REG(data->fan_div[nr]));
	return sprintf(buf, "%d\n", rpm);
}

static ssize_t get_fan_div(struct device *dev, char *buf, int nr)
{
	struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
	return sprintf(buf, "%d\n", DIV_FROM_REG(data->fan_div[nr]));
}

static ssize_t get_pwm(struct device *dev, char *buf, int nr)
{
	struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
	return sprintf(buf, "%d\n", PWM_FROM_REG(data->pwm[nr]));
}

static ssize_t get_pwm_en(struct device *dev, char *buf, int nr)
{
	struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
	return sprintf(buf, "%d\n", PWM_EN_FROM_REG(data->pwm[nr]));
}

static ssize_t get_alarms(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct smsc47m1_data *data = smsc47m1_update_device(dev, 0);
	return sprintf(buf, "%d\n", data->alarms);
}

static ssize_t set_fan_min(struct device *dev, const char *buf,
		size_t count, int nr)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct smsc47m1_data *data = i2c_get_clientdata(client);
	long rpmdiv, val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	rpmdiv = val * DIV_FROM_REG(data->fan_div[nr]);

	if (983040 > 192 * rpmdiv || 2 * rpmdiv > 983040) {
		mutex_unlock(&data->update_lock);
		return -EINVAL;
	}

	data->fan_preload[nr] = 192 - ((983040 + rpmdiv / 2) / rpmdiv);
	smsc47m1_write_value(client, SMSC47M1_REG_FAN_PRELOAD(nr),
			     data->fan_preload[nr]);
	mutex_unlock(&data->update_lock);

	return count;
}

/* Note: we save and restore the fan minimum here, because its value is
   determined in part by the fan clock divider.  This follows the principle
   of least surprise; the user doesn't expect the fan minimum to change just
   because the divider changed. */
static ssize_t set_fan_div(struct device *dev, const char *buf,
		size_t count, int nr)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct smsc47m1_data *data = i2c_get_clientdata(client);

	long new_div = simple_strtol(buf, NULL, 10), tmp;
	u8 old_div = DIV_FROM_REG(data->fan_div[nr]);

	if (new_div == old_div) /* No change */
		return count;

	mutex_lock(&data->update_lock);
	switch (new_div) {
	case 1: data->fan_div[nr] = 0; break;
	case 2: data->fan_div[nr] = 1; break;
	case 4: data->fan_div[nr] = 2; break;
	case 8: data->fan_div[nr] = 3; break;
	default:
		mutex_unlock(&data->update_lock);
		return -EINVAL;
	}

	tmp = smsc47m1_read_value(client, SMSC47M1_REG_FANDIV) & 0x0F;
	tmp |= (data->fan_div[0] << 4) | (data->fan_div[1] << 6);
	smsc47m1_write_value(client, SMSC47M1_REG_FANDIV, tmp);

	/* Preserve fan min */
	tmp = 192 - (old_div * (192 - data->fan_preload[nr])
		     + new_div / 2) / new_div;
	data->fan_preload[nr] = SENSORS_LIMIT(tmp, 0, 191);
	smsc47m1_write_value(client, SMSC47M1_REG_FAN_PRELOAD(nr),
			     data->fan_preload[nr]);
	mutex_unlock(&data->update_lock);

	return count;
}

static ssize_t set_pwm(struct device *dev, const char *buf,
		size_t count, int nr)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct smsc47m1_data *data = i2c_get_clientdata(client);

	long val = simple_strtol(buf, NULL, 10);

	if (val < 0 || val > 255)
		return -EINVAL;

	mutex_lock(&data->update_lock);
	data->pwm[nr] &= 0x81; /* Preserve additional bits */
	data->pwm[nr] |= PWM_TO_REG(val);
	smsc47m1_write_value(client, SMSC47M1_REG_PWM(nr),
			     data->pwm[nr]);
	mutex_unlock(&data->update_lock);

	return count;
}

static ssize_t set_pwm_en(struct device *dev, const char *buf,
		size_t count, int nr)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct smsc47m1_data *data = i2c_get_clientdata(client);

	long val = simple_strtol(buf, NULL, 10);

	if (val != 0 && val != 1)
		return -EINVAL;

	mutex_lock(&data->update_lock);
	data->pwm[nr] &= 0xFE; /* preserve the other bits */
	data->pwm[nr] |= !val;
	smsc47m1_write_value(client, SMSC47M1_REG_PWM(nr),
			     data->pwm[nr]);
	mutex_unlock(&data->update_lock);

	return count;
}

#define fan_present(offset)						\
static ssize_t get_fan##offset (struct device *dev, struct device_attribute *attr, char *buf)		\
{									\
	return get_fan(dev, buf, offset - 1);				\
}									\
static ssize_t get_fan##offset##_min (struct device *dev, struct device_attribute *attr, char *buf)	\
{									\
	return get_fan_min(dev, buf, offset - 1);			\
}									\
static ssize_t set_fan##offset##_min (struct device *dev, struct device_attribute *attr,		\
		const char *buf, size_t count)				\
{									\
	return set_fan_min(dev, buf, count, offset - 1);		\
}									\
static ssize_t get_fan##offset##_div (struct device *dev, struct device_attribute *attr, char *buf)	\
{									\
	return get_fan_div(dev, buf, offset - 1);			\
}									\
static ssize_t set_fan##offset##_div (struct device *dev, struct device_attribute *attr,		\
		const char *buf, size_t count)				\
{									\
	return set_fan_div(dev, buf, count, offset - 1);		\
}									\
static ssize_t get_pwm##offset (struct device *dev, struct device_attribute *attr, char *buf)		\
{									\
	return get_pwm(dev, buf, offset - 1);				\
}									\
static ssize_t set_pwm##offset (struct device *dev, struct device_attribute *attr,			\
		const char *buf, size_t count)				\
{									\
	return set_pwm(dev, buf, count, offset - 1);			\
}									\
static ssize_t get_pwm##offset##_en (struct device *dev, struct device_attribute *attr, char *buf)	\
{									\
	return get_pwm_en(dev, buf, offset - 1);			\
}									\
static ssize_t set_pwm##offset##_en (struct device *dev, struct device_attribute *attr,		\
		const char *buf, size_t count)				\
{									\
	return set_pwm_en(dev, buf, count, offset - 1);			\
}									\
static DEVICE_ATTR(fan##offset##_input, S_IRUGO, get_fan##offset,	\
		NULL);							\
static DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR,		\
		get_fan##offset##_min, set_fan##offset##_min);		\
static DEVICE_ATTR(fan##offset##_div, S_IRUGO | S_IWUSR,		\
		get_fan##offset##_div, set_fan##offset##_div);		\
static DEVICE_ATTR(pwm##offset, S_IRUGO | S_IWUSR,			\
		get_pwm##offset, set_pwm##offset);			\
static DEVICE_ATTR(pwm##offset##_enable, S_IRUGO | S_IWUSR,		\
		get_pwm##offset##_en, set_pwm##offset##_en);

fan_present(1);
fan_present(2);

static DEVICE_ATTR(alarms, S_IRUGO, get_alarms, NULL);

/* Almost all sysfs files may or may not be created depending on the chip
   setup so we create them individually. It is still convenient to define a
   group to remove them all at once. */
static struct attribute *smsc47m1_attributes[] = {
	&dev_attr_fan1_input.attr,
	&dev_attr_fan1_min.attr,
	&dev_attr_fan1_div.attr,
	&dev_attr_fan2_input.attr,
	&dev_attr_fan2_min.attr,
	&dev_attr_fan2_div.attr,

	&dev_attr_pwm1.attr,
	&dev_attr_pwm1_enable.attr,
	&dev_attr_pwm2.attr,
	&dev_attr_pwm2_enable.attr,

	&dev_attr_alarms.attr,
	NULL
};

static const struct attribute_group smsc47m1_group = {
	.attrs = smsc47m1_attributes,
};

static int __init smsc47m1_find(unsigned short *addr)
{
	u8 val;

	superio_enter();
	val = superio_inb(SUPERIO_REG_DEVID);

	/*
	 * SMSC LPC47M10x/LPC47M112/LPC47M13x (device id 0x59), LPC47M14x
	 * (device id 0x5F) and LPC47B27x (device id 0x51) have fan control.
	 * The LPC47M15x and LPC47M192 chips "with hardware monitoring block"
	 * can do much more besides (device id 0x60).
	 * The LPC47M997 is undocumented, but seems to be compatible with
	 * the LPC47M192, and has the same device id.
	 */
	if (val == 0x51)
		printk(KERN_INFO "smsc47m1: Found SMSC LPC47B27x\n");
	else if (val == 0x59)
		printk(KERN_INFO "smsc47m1: Found SMSC "
		       "LPC47M10x/LPC47M112/LPC47M13x\n");
	else if (val == 0x5F)
		printk(KERN_INFO "smsc47m1: Found SMSC LPC47M14x\n");
	else if (val == 0x60)
		printk(KERN_INFO "smsc47m1: Found SMSC "
		       "LPC47M15x/LPC47M192/LPC47M997\n");
	else {
		superio_exit();
		return -ENODEV;
	}

	superio_select();
	*addr = (superio_inb(SUPERIO_REG_BASE) << 8)
	      |  superio_inb(SUPERIO_REG_BASE + 1);
	val = superio_inb(SUPERIO_REG_ACT);
	if (*addr == 0 || (val & 0x01) == 0) {
		printk(KERN_INFO "smsc47m1: Device is disabled, will not use\n");
		superio_exit();
		return -ENODEV;
	}

	superio_exit();
	return 0;
}

static int smsc47m1_detect(struct i2c_adapter *adapter)
{
	struct i2c_client *new_client;
	struct smsc47m1_data *data;
	int err = 0;
	int fan1, fan2, pwm1, pwm2;

	if (!request_region(address, SMSC_EXTENT, smsc47m1_driver.driver.name)) {
		dev_err(&adapter->dev, "Region 0x%x already in use!\n", address);
		return -EBUSY;
	}

	if (!(data = kzalloc(sizeof(struct smsc47m1_data), GFP_KERNEL))) {
		err = -ENOMEM;
		goto error_release;
	}

	new_client = &data->client;
	i2c_set_clientdata(new_client, data);
	new_client->addr = address;
	mutex_init(&data->lock);
	new_client->adapter = adapter;
	new_client->driver = &smsc47m1_driver;
	new_client->flags = 0;

	strlcpy(new_client->name, "smsc47m1", I2C_NAME_SIZE);
	mutex_init(&data->update_lock);

	/* If no function is properly configured, there's no point in
	   actually registering the chip. */
	fan1 = (smsc47m1_read_value(new_client, SMSC47M1_REG_TPIN(0)) & 0x05)
	       == 0x05;
	fan2 = (smsc47m1_read_value(new_client, SMSC47M1_REG_TPIN(1)) & 0x05)
	       == 0x05;
	pwm1 = (smsc47m1_read_value(new_client, SMSC47M1_REG_PPIN(0)) & 0x05)
	       == 0x04;
	pwm2 = (smsc47m1_read_value(new_client, SMSC47M1_REG_PPIN(1)) & 0x05)
	       == 0x04;
	if (!(fan1 || fan2 || pwm1 || pwm2)) {
		dev_warn(&adapter->dev, "Device at 0x%x is not configured, "
			 "will not use\n", new_client->addr);
		err = -ENODEV;
		goto error_free;
	}

	if ((err = i2c_attach_client(new_client)))
		goto error_free;

	/* Some values (fan min, clock dividers, pwm registers) may be
	   needed before any update is triggered, so we better read them
	   at least once here. We don't usually do it that way, but in
	   this particular case, manually reading 5 registers out of 8
	   doesn't make much sense and we're better using the existing
	   function. */
	smsc47m1_update_device(&new_client->dev, 1);

	/* Register sysfs hooks */
	if (fan1) {
		if ((err = device_create_file(&new_client->dev,
					      &dev_attr_fan1_input))
		 || (err = device_create_file(&new_client->dev,
					      &dev_attr_fan1_min))
		 || (err = device_create_file(&new_client->dev,
					      &dev_attr_fan1_div)))
			goto error_remove_files;
	} else
		dev_dbg(&new_client->dev, "Fan 1 not enabled by hardware, "
			"skipping\n");

	if (fan2) {
		if ((err = device_create_file(&new_client->dev,
					      &dev_attr_fan2_input))
		 || (err = device_create_file(&new_client->dev,
					      &dev_attr_fan2_min))
		 || (err = device_create_file(&new_client->dev,
					      &dev_attr_fan2_div)))
			goto error_remove_files;
	} else
		dev_dbg(&new_client->dev, "Fan 2 not enabled by hardware, "
			"skipping\n");

	if (pwm1) {
		if ((err = device_create_file(&new_client->dev,
					      &dev_attr_pwm1))
		 || (err = device_create_file(&new_client->dev,
					      &dev_attr_pwm1_enable)))
			goto error_remove_files;
	} else
		dev_dbg(&new_client->dev, "PWM 1 not enabled by hardware, "
			"skipping\n");
	if (pwm2) {
		if ((err = device_create_file(&new_client->dev,
					      &dev_attr_pwm2))
		 || (err = device_create_file(&new_client->dev,
					      &dev_attr_pwm2_enable)))
			goto error_remove_files;
	} else
		dev_dbg(&new_client->dev, "PWM 2 not enabled by hardware, "
			"skipping\n");

	if ((err = device_create_file(&new_client->dev, &dev_attr_alarms)))
		goto error_remove_files;

	data->class_dev = hwmon_device_register(&new_client->dev);
	if (IS_ERR(data->class_dev)) {
		err = PTR_ERR(data->class_dev);
		goto error_remove_files;
	}

	return 0;

error_remove_files:
	sysfs_remove_group(&new_client->dev.kobj, &smsc47m1_group);
	i2c_detach_client(new_client);
error_free:
	kfree(data);
error_release:
	release_region(address, SMSC_EXTENT);
	return err;
}

static int smsc47m1_detach_client(struct i2c_client *client)
{
	struct smsc47m1_data *data = i2c_get_clientdata(client);
	int err;

	hwmon_device_unregister(data->class_dev);
	sysfs_remove_group(&client->dev.kobj, &smsc47m1_group);

	if ((err = i2c_detach_client(client)))
		return err;

	release_region(client->addr, SMSC_EXTENT);
	kfree(data);

	return 0;
}

static int smsc47m1_read_value(struct i2c_client *client, u8 reg)
{
	int res;

	mutex_lock(&((struct smsc47m1_data *) i2c_get_clientdata(client))->lock);
	res = inb_p(client->addr + reg);
	mutex_unlock(&((struct smsc47m1_data *) i2c_get_clientdata(client))->lock);
	return res;
}

static void smsc47m1_write_value(struct i2c_client *client, u8 reg, u8 value)
{
	mutex_lock(&((struct smsc47m1_data *) i2c_get_clientdata(client))->lock);
	outb_p(value, client->addr + reg);
	mutex_unlock(&((struct smsc47m1_data *) i2c_get_clientdata(client))->lock);
}

static struct smsc47m1_data *smsc47m1_update_device(struct device *dev,
		int init)
{
 	struct i2c_client *client = to_i2c_client(dev);
	struct smsc47m1_data *data = i2c_get_clientdata(client);

	mutex_lock(&data->update_lock);

	if (time_after(jiffies, data->last_updated + HZ + HZ / 2) || init) {
		int i;

		for (i = 0; i < 2; i++) {
			data->fan[i] = smsc47m1_read_value(client,
				       SMSC47M1_REG_FAN(i));
			data->fan_preload[i] = smsc47m1_read_value(client,
					       SMSC47M1_REG_FAN_PRELOAD(i));
			data->pwm[i] = smsc47m1_read_value(client,
				       SMSC47M1_REG_PWM(i));
		}

		i = smsc47m1_read_value(client, SMSC47M1_REG_FANDIV);
		data->fan_div[0] = (i >> 4) & 0x03;
		data->fan_div[1] = i >> 6;

		data->alarms = smsc47m1_read_value(client,
			       SMSC47M1_REG_ALARM) >> 6;
		/* Clear alarms if needed */
		if (data->alarms)
			smsc47m1_write_value(client, SMSC47M1_REG_ALARM, 0xC0);

		data->last_updated = jiffies;
	}

	mutex_unlock(&data->update_lock);
	return data;
}

static int __init sm_smsc47m1_init(void)
{
	if (smsc47m1_find(&address)) {
		return -ENODEV;
	}

	return i2c_isa_add_driver(&smsc47m1_driver);
}

static void __exit sm_smsc47m1_exit(void)
{
	i2c_isa_del_driver(&smsc47m1_driver);
}

MODULE_AUTHOR("Mark D. Studebaker <mdsxyz123@yahoo.com>");
MODULE_DESCRIPTION("SMSC LPC47M1xx fan sensors driver");
MODULE_LICENSE("GPL");

module_init(sm_smsc47m1_init);
module_exit(sm_smsc47m1_exit);


text:
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Prometheus.Client.MetricsWriter;

namespace Prometheus.Client
{
    public sealed class CounterInt64 : MetricBase<MetricConfiguration>, ICounter<long>
    {
        private ThreadSafeLong _value  = default;

        public CounterInt64(MetricConfiguration configuration, IReadOnlyList<string> labels)
            : base(configuration, labels)
        {
        }

        public void Inc()
        {
            IncInternal(1, null);
        }

        public void Inc(long increment)
        {
            Inc(increment, null);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Inc(long increment, long? timestamp)
        {
            if (increment < 0)
                throw new ArgumentOutOfRangeException(nameof(increment), "Counter cannot go down");

            IncInternal(increment, timestamp);
        }

        public void IncTo(long value)
            => IncTo(value, null);

        public void IncTo(long value, long? timestamp)
        {
            _value.IncTo(value);
            TrackObservation(timestamp);
        }

        public long Value => _value.Value;

        public void Reset()
        {
            _value.Value = default;
        }

        protected internal override void Collect(IMetricsWriter writer)
        {
            writer.WriteSample(Value, string.Empty, Configuration.LabelNames, LabelValues, Timestamp);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void IncInternal(long increment, long? timestamp)
        {
            _value.Add(increment);
            TrackObservation(timestamp);
        }
    }
}


text:
using DataExplorer.Domain.Columns;
using DataExplorer.Domain.Filters;
using DataExplorer.Domain.FilterTrees.BooleanFilterTrees;
using DataExplorer.Domain.Tests.Columns;
using NUnit.Framework;

namespace DataExplorer.Domain.Tests.FilterTrees.BooleanFilterTrees
{
    [TestFixture]
    public class BooleanFilterTreeLeafTests
    {
        private BooleanFilterTreeLeaf _leaf;
        private Column _column;

        [SetUp]
        public void SetUp()
        {
            _column = new ColumnBuilder().Build();
            _leaf = new BooleanFilterTreeLeaf("Test", _column, true);
        }

        [Test]
        public void TestConstructorShouldSetValue()
        {
            Assert.That(_leaf.Value, Is.EqualTo(true));
        }

        [Test]
        public void TestCreateChildrenShouldReturnEmptyList()
        {
            var result = _leaf.CreateChildren();
            Assert.That(result, Is.Empty);
        }

        [Test]
        public void TestCreateFilterShouldReturnFilter()
        {
            _leaf = new BooleanFilterTreeLeaf(string.Empty, _column, true);
            var result = (BooleanFilter) _leaf.CreateFilter();
            Assert.That(result.IncludeTrue, Is.True);
            Assert.That(result.IncludeFalse, Is.False);
        }
    }
}


text:
package sched

import (
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"sync"
	"time"

	"bosun.org/cmd/bosun/expr"
	"bosun.org/opentsdb"
)

type Silence struct {
	Start, End time.Time
	Alert      string
	Tags       opentsdb.TagSet
	Forget     bool
	User       string
	Message    string
}

func (s *Silence) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Start, End time.Time
		Alert      string
		Tags       string
		Forget     bool
		User       string
		Message    string
	}{
		Start:   s.Start,
		End:     s.End,
		Alert:   s.Alert,
		Tags:    s.Tags.Tags(),
		Forget:  s.Forget,
		User:    s.User,
		Message: s.Message,
	})
}

func (s *Silence) Silenced(now time.Time, alert string, tags opentsdb.TagSet) bool {
	if !s.ActiveAt(now) {
		return false
	}
	return s.Matches(alert, tags)
}

func (s *Silence) ActiveAt(now time.Time) bool {
	if now.Before(s.Start) || now.After(s.End) {
		return false
	}
	return true
}

func (s *Silence) Matches(alert string, tags opentsdb.TagSet) bool {
	if s.Alert != "" && s.Alert != alert {
		return false
	}
	for k, pattern := range s.Tags {
		tagv, ok := tags[k]
		if !ok {
			return false
		}
		matched, _ := Match(pattern, tagv)
		if !matched {
			return false
		}
	}
	return true
}

func (s Silence) ID() string {
	h := sha1.New()
	fmt.Fprintf(h, "%s|%s|%s%s", s.Start, s.End, s.Alert, s.Tags)
	return fmt.Sprintf("%x", h.Sum(nil))
}

// Silenced returns all currently silenced AlertKeys and the time they will be
// unsilenced.
func (s *Schedule) Silenced() map[expr.AlertKey]Silence {
	aks := make(map[expr.AlertKey]Silence)
	now := time.Now()
	silenceLock.RLock()
	defer silenceLock.RUnlock()
	for _, si := range s.Silence {
		if !si.ActiveAt(now) {
			continue
		}
		s.Lock("Silence")
		for ak := range s.status {
			if si.Silenced(now, ak.Name(), ak.Group()) {
				if aks[ak].End.Before(si.End) {
					aks[ak] = *si
				}
			}
		}
		s.Unlock()
	}
	return aks
}

var silenceLock = sync.RWMutex{}

func (s *Schedule) AddSilence(start, end time.Time, alert, tagList string, forget, confirm bool, edit, user, message string) (map[expr.AlertKey]bool, error) {
	if start.IsZero() || end.IsZero() {
		return nil, fmt.Errorf("both start and end must be specified")
	}
	if start.After(end) {
		return nil, fmt.Errorf("start time must be before end time")
	}
	if time.Since(end) > 0 {
		return nil, fmt.Errorf("end time must be in the future")
	}
	if alert == "" && tagList == "" {
		return nil, fmt.Errorf("must specify either alert or tags")
	}
	si := &Silence{
		Start:   start,
		End:     end,
		Alert:   alert,
		Tags:    make(opentsdb.TagSet),
		Forget:  forget,
		User:    user,
		Message: message,
	}
	if tagList != "" {
		tags, err := opentsdb.ParseTags(tagList)
		if err != nil && tags == nil {
			return nil, err
		}
		si.Tags = tags
	}
	silenceLock.Lock()
	defer silenceLock.Unlock()
	if confirm {
		delete(s.Silence, edit)
		s.Silence[si.ID()] = si
		return nil, nil
	}
	aks := make(map[expr.AlertKey]bool)
	for ak := range s.status {
		if si.Matches(ak.Name(), ak.Group()) {
			aks[ak] = s.status[ak].IsActive()
		}
	}
	return aks, nil
}

func (s *Schedule) ClearSilence(id string) error {
	silenceLock.Lock()
	defer silenceLock.Unlock()
	delete(s.Silence, id)
	return nil
}


text:
[![Build Status](https://travis-ci.org/tubbo/mass.svg?branch=master)](https://travis-ci.org/tubbo/mass)
[![Code Climate](https://codeclimate.com/github/tubbo/mass/badges/gpa.svg)](https://codeclimate.com/github/tubbo/mass)
[![Test Coverage](https://codeclimate.com/github/tubbo/mass/badges/coverage.svg)](https://codeclimate.com/github/tubbo/mass/coverage)
[![Inline docs](http://inch-ci.org/github/tubbo/mass.svg?branch=master)](http://inch-ci.org/github/tubbo/mass)

Mass is a Ruby framework for building MIDI synthesizer controls.

## Installation

On Linux, the **libasound** and **libasound-dev** are required for use.

Add this line to your application's Gemfile:

```ruby
gem 'mass'
```

And then execute:

```bash
$ bundle
```

Or install it yourself:

```bash
$ gem install mass
```

## Usage

To create a new pattern, use the DSL methods that Mass gives you upon
mixing it into whatever namespace you're dealing with.

```ruby
require 'mass'

include Mass

bpm 128
pattern bars: 4 do
  note 4, pitch: 'C2'
  note 4, pitch: 'C3'
  note 4, pitch: 'C4'
  note 4, pitch: 'C3'
end
```

You can also use this syntax to also name the sequence and keep it out
of the main namespace:

```ruby
MS20 = 'KORG INC. MS-20M Kit'
TEMPEST = 'Dave Smith Instruments Tempest'

Mass.sequence name: 'Your Love', bpm: 125, bars: 32 do
  pattern name: 'Arpeggio', repeat: true, device: MS20 do
    note 8, pitch: 'G4'
    note 8, pitch: 'E4'
    note 8, pitch: 'C4'
  end

  pattern name: 'Bass Line', repeat: true, device: TEMPEST do
    note 8, pitch: 'G4'
    note 4, pitch: 'E4'
    note 8, pitch: 'C4'
    note 4, pitch: 'C4'
    note 4, pitch: 'C4'
  end
end
```

This is useful for more complex patterns with names. Read the
[RDoc documentation][rdoc] for more information on each component and what
each DSL method does.

## Development

Mass was created by [Tom Scott][tubbo] and is published under
the [MIT License][mit]. All contributions are welcome as long
as they are submitted via pull request, include tests that
describe your change and prove what you did works, and do not
break the CI build.

To get started with contributing, clone down this repo and run the
following command within its root directory:

```bash
$ bin/setup
```

If you need to install this gem onto your local machine, run:

```bash
$ bin/rake install
```

To release a new version, update the version number in
**lib/mass/version.rb**, then run the following command to create a Git
tag for the release, push all commits & tags to the repo, and upload the
newly built `.gem` file to [RubyGems][gem]:

```bash
$ bin/rake release
```

[tubbo]: https://github.com/tubbo
[rdoc]: http://www.rubydoc.info/github/tubbo/mass/master/frames
[gem]: https://rubygems.org
[mit]: https://github.com/tubbo/mass/blob/master/LICENSE.txt


text:
namespace Sitecore.Octopus.Business.Domain
{
    public class ArtifactDetails
    {
        public string ItemsToPublishFilePath { get; set; }
        public string ContentPackageFilePath { get; set; }
        public string ReleaseNotesFilePath { get; set; }
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;

namespace Analyzer.Utilities
{
    public static class SyntaxGeneratorExtensions
    {
        private static readonly OperatorKind[] s_comparisonOperators =
        {
            OperatorKind.Equality,
            OperatorKind.Inequality,
            OperatorKind.GreaterThan,
            OperatorKind.GreaterThanOrEqual,
            OperatorKind.LessThan,
            OperatorKind.LessThanOrEqual
        };

        /// <summary>
        /// Creates a declaration for a comparison operator overload.
        /// </summary>
        /// <param name="generator">
        /// The <see cref="SyntaxGenerator"/> used to create the declaration.
        /// </param>
        /// <param name="operatorKind">
        /// A value specifying which operator overload is to be declared. Must be one of
        /// Equality, Inequality, GreaterThan, GreaterThanOrEqual, LessThan, or LessThanOrEqual.
        /// </param>
        /// <param name="containingType">
        /// A symbol specifying the type of the operands of the comparison operator.
        /// </param>
        /// <param name="compilation">The compilation</param>
        /// <returns>
        /// A <see cref="SyntaxNode"/> representing the declaration.
        /// </returns>
        /// <remarks>
        /// A comparison operator is a public, static (Shared in VB) method with two operands,
        /// each of the containing type, and a return type of bool (Boolean in VB).
        /// </remarks>
        public static SyntaxNode ComparisonOperatorDeclaration(
            this SyntaxGenerator generator, OperatorKind operatorKind,
            INamedTypeSymbol containingType, Compilation compilation)
        {
            if (!s_comparisonOperators.Contains(operatorKind))
            {
                throw new ArgumentException($"{operatorKind} is not a comparison operator", nameof(operatorKind));
            }

            return generator.OperatorDeclaration(
                operatorKind,
                new SyntaxNode[]
                {
                        generator.ParameterDeclaration("left", generator.TypeExpression(containingType)),
                        generator.ParameterDeclaration("right", generator.TypeExpression(containingType)),
                },
                generator.TypeExpression(SpecialType.System_Boolean),
                Accessibility.Public,
                DeclarationModifiers.Static,
                generator.DefaultMethodBody(compilation));
        }

        /// <summary>
        /// Creates a declaration for an override of <see cref="object.Equals(object)"/>.
        /// </summary>
        /// <param name="generator">
        /// The <see cref="SyntaxGenerator"/> used to create the declaration.
        /// </param>
        /// <param name="compilation">The compilation</param>
        /// <returns>
        /// A <see cref="SyntaxNode"/> representing the declaration.
        /// </returns>
        public static SyntaxNode EqualsOverrideDeclaration(this SyntaxGenerator generator, Compilation compilation)
        {
            return generator.MethodDeclaration(
                WellKnownMemberNames.ObjectEquals,
                new SyntaxNode[]
                {
                    generator.ParameterDeclaration("obj", generator.TypeExpression(SpecialType.System_Object))
                },
                returnType: generator.TypeExpression(SpecialType.System_Boolean),
                accessibility: Accessibility.Public,
                modifiers: DeclarationModifiers.Override,
                statements: generator.DefaultMethodBody(compilation));
        }

        /// <summary>
        /// Creates a declaration for an override of <see cref="object.GetHashCode()"/>.
        /// </summary>
        /// <param name="generator">
        /// The <see cref="SyntaxGenerator"/> used to create the declaration.
        /// </param>
        /// <param name="compilation">The compilation</param>
        /// <returns>
        /// A <see cref="SyntaxNode"/> representing the declaration.
        /// </returns>
        public static SyntaxNode GetHashCodeOverrideDeclaration(
            this SyntaxGenerator generator, Compilation compilation)
        {
            return generator.MethodDeclaration(
                WellKnownMemberNames.ObjectGetHashCode,
                returnType: generator.TypeExpression(SpecialType.System_Int32),
                accessibility: Accessibility.Public,
                modifiers: DeclarationModifiers.Override,
                statements: generator.DefaultMethodBody(compilation));
        }

        /// <summary>
        /// Creates a default set of statements to place within a generated method body.
        /// </summary>
        /// <param name="generator">
        /// The <see cref="SyntaxGenerator"/> used to create the statements.
        /// </param>
        /// <param name="compilation">The compilation</param>
        /// <returns>
        /// An sequence containing a single statement that throws <see cref="System.NotImplementedException"/>.
        /// </returns>
        public static IEnumerable<SyntaxNode> DefaultMethodBody(
            this SyntaxGenerator generator, Compilation compilation)
        {
            yield return DefaultMethodStatement(generator, compilation);
        }

        public static SyntaxNode DefaultMethodStatement(this SyntaxGenerator generator, Compilation compilation)
        {
            return generator.ThrowStatement(generator.ObjectCreationExpression(
                            generator.TypeExpression(
                                compilation.GetTypeByMetadataName("System.NotImplementedException"))));
        }
    }
}


text:
<Record>
<Term>Omeprazole</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Prilosec</Synonym>
<Synonym>Omeprazole</Synonym>
<Source>FDA Registry</Source>
</Record>