text:
EnumExt extends rails enum with localization/translation and it's helpers, mass-assign on scopes with bang, advanced sets logic over existing enum.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'enum_ext', '~> 0.3'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install enum_ext

## Usage
 To use enum extension extend main model class with EnumExt module,
 and customize your enums the way you need:

    class SomeModel
      extend EnumExt

      enum_i ...
      humanize_enum ...
      translate_enum ...
      ext_enum_sets ...
      mass_assign_enum ...
    end

 Let's assume that we have model Request representing some buying requests with enum **status**, and we have model Order with requests,
 representing single purchase, like this:

     class Request
       extend EnumExt
       belongs_to :order
       enum status: [ :in_cart, :waiting_for_payment, :paid, :ready_for_shipment, :on_delivery, :delivered ]
     end

     class Order
       has_many :requests
     end

 Now let's review some examples of possible enum extensions

### Humanization (humanize_enum)

  if app doesn't need internationalization, it may use humanize_enum to make enum user friendly

  ```
  humanize_enum :status, {
      #locale dependent example with pluralization and lambda:
      in_cart: -> (t_self) { I18n.t("request.status.in_cart", count: t_self.sum ) }

      #locale dependent example with pluralization and proc:
      paid: Proc.new{ I18n.t("request.status.paid", count: self.sum ) }

      #locale independent:
      ready_for_shipment: "Ready to go!"
    }
  end
  ```

  This humanize_enum adds to instance:
   - t_in_cart, t_paid, t_ready_for_shipment

  and to class:
   - t_statuses - as given or generated values
   - t_statuses_options - translated enum values options for select input
   - t_statuses_options_i - same as above but use int values with translations works for ActiveAdmin filters for instance

  Example with block:

  ```
  humanize_enum :status do
   I18n.t("scope.#{status}")
  end
  ```

  Example for select:

  ```
    f.select :status, Request.t_statuses_options
  ```

  in Active Admin filters
  ```
    filter :status, as: :select, label: 'Status', collection: Request.t_statuses_options_i
  ```

  Rem: select options may break when using lambda() or proc with instance method, but will survive with block

  Console:
  ```
    request.sum = 3
    request.paid!
    request.status     # >> paid
    request.t_status   # >> "paid 3 dollars"
    Request.t_statuses # >> { in_cart: -> { I18n.t("request.status.in_cart") }, ....  }
  ```

  Could be called multiple times, all humanization definitions will be merged under the hood.

### Translate (translate_enum)

Enum is translated using scope 'active_record.attributes.class_name_underscore.enum_plural', or the given one:

       translate_enum :status, 'active_record.request.enum'

Or it can be done with block either with translate or humanize:

       translate_enum :status do
         I18n.t( "active_record.request.enum.#{status}" )
       end

### Enum to_i shortcut ( enum_i )

Defines method enum_name_i shortcut for Model.enum_names[elem.enum_name]

**Ex**
  enum_i :status
  ...
  request.paid_i # 10

### Enum Sets (ext_enum_sets)

 **Use-case** For example you have pay bills of different types, and you want to group some types in debit and credit "super-types",
 and have scope PayBill.debit, instance method with question mark as usual enum does pay_bill.debit?.

 You can do this with method **ext_enum_sets** it creates:  scopes for subsets, instance method with ? and some class methods helpers

   For this call:
   ```
     ext_enum_sets :status, {
                     delivery_set: [:ready_for_shipment, :on_delivery, :delivered] # for shipping department for example
                     in_warehouse: [:ready_for_shipment]  # this just for superposition example  below
                   }
   ```
it will generate:
```
instance:
    - methods: delivery_set?, in_warehouse?

class:
    - named scopes: delivery_set, in_warehouse
    - parametrized scopes: with_statuses, without_statuses
    class helpers:
        - delivery_set_statuses (=[:ready_for_shipment, :on_delivery, :delivered] ), in_warehouse_statuses
        - delivery_set_statuses_i (= [3,4,5]), in_warehouse_statuses_i (=[3])

     class translation helpers ( started with t_... ):
        - t_delivery_set_statuses_options (= [['translation or humanization', :ready_for_shipment] ...] ) for select inputs purposes
        - t_delivery_set_statuses_options_i (= [['translation or humanization', 3] ...]) same as above but with integer as value ( for example to use in Active admin filters )
```

 ```
   Console:
    request.on_delivery!
    request.delivery_set?                    # >> true

    Request.delivery_set.exists?(request)    # >> true
    Request.in_warehouse.exists?(request)    # >> false

    Request.delivery_set_statuses            # >> [:ready_for_shipment, :on_delivery, :delivered]

    Request.with_statuses( :payed, :delivery_set )    # >> :payed and [:ready_for_shipment, :on_delivery, :delivered] requests
    Request.without_statuses( :payed )                # >> scope for all requests with statuses not eq to :payed
    Request.without_statuses( :payed, :in_warehouse ) # >> scope all requests with statuses not eq to :payed or :ready_for_shipment
 ```

   Rem:
    ext_enum_sets can be called twice defining a superposition of already defined sets ( considering previous example ):

```
    ext_enum_sets :status, {
                outside_wharehouse: ( delivery_set_statuses - in_warehouse_statuses )... any other array operations like &, + and so can be used
              }
```

### Mass-assign ( mass_assign_enum )

 Syntax sugar for mass-assigning enum values.

 **Use-case:** it's often case when I need bulk update without callbacks, so it's gets frustrating to repeat:
 ```
    some_scope.update_all(status: Request.statuses[:new_status], update_at: Time.now)
 ```
 If you need callbacks you can do like this: some_scope.each(&:new_stat!) but if you don't need callbacks and you
 have hundreds and thousands of records to change at once you need update_all

 ```
    mass_assign_enum( :status )
 ```

 Console:

```
    request1.in_cart!
    request2.waiting_for_payment!
    Request.non_paid.paid!
    request1.paid?                         # >> true
    request2.paid?                         # >> true
    request1.updated_at                     # >> ~ Time.now

    order.requests.already_paid.count          # >> N
    order.requests.delivered.count              # >> M
    order.requests.already_paid.delivered!
    order.requests.already_paid.count          # >> 0
    order.requests.delivered.count              # >> N + M
```

## Tests
   rake test

## Development

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/alekseyl/enum_ext or by email: leshchuk@gmail.com

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

### Thanks

Thanks for the star vzamanillo, it inspires me to do mass refactor and gracefully cover code in this gem by tests.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

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

-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean name="manageArchive" class="com.francetelecom.clara.cloud.archive.ManageArchiveImpl">
			<property name="configuration">
			<bean class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
				<property name="templateLoaderPaths">
					<list>
						<value>classpath:#{ T(com.francetelecom.clara.cloud.archive.ManageArchiveImpl).TEMPLATE_WAR_DIR}</value>
						<value>classpath:#{ T(com.francetelecom.clara.cloud.archive.ManageArchiveImpl).TEMPLATE_EAR_DIR}</value>
					</list>
				</property>
				<property name="freemarkerSettings">
					<props>
						<prop key="datetime_format">MM/dd/yyyy hh:mm:ss a</prop>
						<prop key="number_format">0.######</prop>
					</props>
				</property>
			</bean>
		</property>
	</bean>

</beans>

redpajama_set_name: RedPajamaGithub


text:
DROP TRIGGER IF EXISTS users_search_vector_refresh on membership.users;
CREATE TRIGGER users_search_vector_refresh
BEFORE INSERT OR UPDATE ON membership.users
FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(search, 'pg_catalog.english',  email, first, last);


text: Scripts created to achieve tasks for the MEMEX program


text:
package group.idealworld.dew.devops.kernel.flow.release;

import group.idealworld.dew.devops.kernel.config.FinalProjectConfig;
import group.idealworld.dew.devops.kernel.flow.BasicFlow;
import group.idealworld.dew.devops.kernel.function.VersionController;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.models.V1ConfigMap;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * Maven release flow.
 * <p>
 * Maven的部署由Maven自身实现,pom.xml中需要配置 distributionManagement
 *
 * @author gudaoxuri
 */
public class MavenReleaseFlow extends BasicFlow {

    @Override
    protected void process(FinalProjectConfig config, String flowBasePath) throws ApiException, IOException {
        VersionController.addNewVersion(config, config.getAppVersion(), config.getGitCommit(), false, new HashMap<>(), new HashMap<>());
        List<V1ConfigMap> versions = VersionController.getVersionHistory(config.getId(), config.getAppName(), config.getNamespace(), false);
        for (V1ConfigMap version : versions) {
            String appVersion = VersionController.getAppVersion(version);
            // Maven项目只需要保留一个最新版本
            if (!appVersion.equalsIgnoreCase(config.getAppVersion())) {
                VersionController.deleteVersion(config, appVersion);
            }
        }
    }

}


text:
using System;
using System.Runtime.InteropServices;
using Avalonia.Platform;
using Avalonia.Platform.Interop;

namespace Avalonia.OpenGL.Egl
{
    public class EglInterface : GlInterfaceBase
    {
        public EglInterface() : base(Load())
        {

        }

        public EglInterface(Func<Utf8Buffer,IntPtr> getProcAddress) : base(getProcAddress)
        {

        }

        public EglInterface(Func<string, IntPtr> getProcAddress) : base(getProcAddress)
        {

        }

        public EglInterface(string library) : base(Load(library))
        {
        }

        static Func<string, IntPtr> Load()
        {
            var os = AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem;
            if(os == OperatingSystemType.Linux)
                return Load("libEGL.so.1");
            if (os == OperatingSystemType.Android)
                return Load("libEGL.so");

            throw new PlatformNotSupportedException();
        }

        static Func<string, IntPtr> Load(string library)
        {
            var dyn = AvaloniaLocator.Current.GetService<IDynamicLibraryLoader>();
            var lib = dyn.LoadLibrary(library);
            return (s) => dyn.GetProcAddress(lib, s, true);
        }

        // ReSharper disable UnassignedGetOnlyAutoProperty
        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate int EglGetError();
        [GlEntryPoint("eglGetError")]
        public EglGetError GetError { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglGetDisplay(IntPtr nativeDisplay);
        [GlEntryPoint("eglGetDisplay")]
        public EglGetDisplay GetDisplay { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglGetPlatformDisplayEXT(int platform, IntPtr nativeDisplay, int[] attrs);
        [GlEntryPoint("eglGetPlatformDisplayEXT")]
        [GlOptionalEntryPoint]
        public EglGetPlatformDisplayEXT GetPlatformDisplayEXT { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglInitialize(IntPtr display, out int major, out int minor);
        [GlEntryPoint("eglInitialize")]
        public EglInitialize Initialize { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglGetProcAddress(Utf8Buffer proc);
        [GlEntryPoint("eglGetProcAddress")]
        public EglGetProcAddress GetProcAddress { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglBindApi(int api);
        [GlEntryPoint("eglBindAPI")]
        public EglBindApi BindApi { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglChooseConfig(IntPtr display, int[] attribs,
            out IntPtr surfaceConfig, int numConfigs, out int choosenConfig);
        [GlEntryPoint("eglChooseConfig")]
        public EglChooseConfig ChooseConfig { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglCreateContext(IntPtr display, IntPtr config,
            IntPtr share, int[] attrs);
        [GlEntryPoint("eglCreateContext")]
        public EglCreateContext CreateContext { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglDestroyContext(IntPtr display, IntPtr context);
        [GlEntryPoint("eglDestroyContext")]
        public EglDestroyContext DestroyContext { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglCreatePBufferSurface(IntPtr display, IntPtr config, int[] attrs);
        [GlEntryPoint("eglCreatePbufferSurface")]
        public EglCreatePBufferSurface CreatePBufferSurface { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglMakeCurrent(IntPtr display, IntPtr draw, IntPtr read, IntPtr context);
        [GlEntryPoint("eglMakeCurrent")]
        public EglMakeCurrent MakeCurrent { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglGetCurrentContext();
        [GlEntryPoint("eglGetCurrentContext")]
        public EglGetCurrentContext GetCurrentContext { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglGetCurrentDisplay();
        [GlEntryPoint("eglGetCurrentDisplay")]
        public EglGetCurrentContext GetCurrentDisplay { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglGetCurrentSurface(int readDraw);
        [GlEntryPoint("eglGetCurrentSurface")]
        public EglGetCurrentSurface GetCurrentSurface { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate void EglDisplaySurfaceVoidDelegate(IntPtr display, IntPtr surface);
        [GlEntryPoint("eglDestroySurface")]
        public EglDisplaySurfaceVoidDelegate DestroySurface { get; }

        [GlEntryPoint("eglSwapBuffers")]
        public EglDisplaySurfaceVoidDelegate SwapBuffers { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr
            EglCreateWindowSurface(IntPtr display, IntPtr config, IntPtr window, int[] attrs);
        [GlEntryPoint("eglCreateWindowSurface")]
        public EglCreateWindowSurface CreateWindowSurface { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglGetConfigAttrib(IntPtr display, IntPtr config, int attr, out int rv);
        [GlEntryPoint("eglGetConfigAttrib")]
        public EglGetConfigAttrib GetConfigAttrib { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglWaitGL();
        [GlEntryPoint("eglWaitGL")]
        public EglWaitGL WaitGL { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglWaitClient();
        [GlEntryPoint("eglWaitClient")]
        public EglWaitGL WaitClient { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglWaitNative(int engine);
        [GlEntryPoint("eglWaitNative")]
        public EglWaitNative WaitNative { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglQueryString(IntPtr display, int i);

        [GlEntryPoint("eglQueryString")]
        public EglQueryString QueryStringNative { get; }

        public string QueryString(IntPtr display, int i)
        {
            var rv = QueryStringNative(display, i);
            if (rv == IntPtr.Zero)
                return null;
            return Marshal.PtrToStringAnsi(rv);
        }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate IntPtr EglCreatePbufferFromClientBuffer(IntPtr display, int buftype, IntPtr buffer, IntPtr config, int[] attrib_list);
        [GlEntryPoint("eglCreatePbufferFromClientBuffer")]

        public EglCreatePbufferFromClientBuffer CreatePbufferFromClientBuffer { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglQueryDisplayAttribEXT(IntPtr display, int attr, out IntPtr res);

        [GlEntryPoint("eglQueryDisplayAttribEXT"), GlOptionalEntryPoint]
        public EglQueryDisplayAttribEXT QueryDisplayAttribExt { get; }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool EglQueryDeviceAttribEXT(IntPtr display, int attr, out IntPtr res);

        [GlEntryPoint("eglQueryDeviceAttribEXT"), GlOptionalEntryPoint]
        public EglQueryDisplayAttribEXT QueryDeviceAttribExt { get; }

        // ReSharper restore UnassignedGetOnlyAutoProperty
    }
}


text:
"""Abstract TFX executor class for Beam powered components."""

import sys
from typing import Any, Callable, List, Optional, Union

from absl import flags
from absl import logging
from tfx.dsl.components.base.base_executor import BaseExecutor
from tfx.dsl.placeholder import placeholder
from tfx.proto.orchestration import pipeline_pb2
from tfx.utils import name_utils
from tfx.utils import telemetry_utils
from tfx.utils import dependency_utils

try:
  import apache_beam as beam  # pytype: disable=import-error  # pylint: disable=g-import-not-at-top
  _BeamPipeline = beam.Pipeline
except ModuleNotFoundError:
  beam = None
  _BeamPipeline = Any

class BaseBeamExecutor(BaseExecutor):
  """Abstract TFX executor class for Beam powered components."""

  class Context(BaseExecutor.Context):
    """Context class for base Beam excecutor."""

    def __init__(
        self,
        beam_pipeline_args: Optional[List[Union[
            str, placeholder.Placeholder]]] = None,
        extra_flags: Optional[List[str]] = None,
        tmp_dir: Optional[str] = None,
        unique_id: Optional[str] = None,
        executor_output_uri: Optional[str] = None,
        stateful_working_dir: Optional[str] = None,
        pipeline_node: Optional[pipeline_pb2.PipelineNode] = None,
        pipeline_info: Optional[pipeline_pb2.PipelineInfo] = None,
        pipeline_run_id: Optional[str] = None,
        make_beam_pipeline_fn: Optional[Callable[[], _BeamPipeline]] = None):
      super().__init__(
          extra_flags=extra_flags,
          tmp_dir=tmp_dir,
          unique_id=unique_id,
          executor_output_uri=executor_output_uri,
          stateful_working_dir=stateful_working_dir,
          pipeline_node=pipeline_node,
          pipeline_info=pipeline_info,
          pipeline_run_id=pipeline_run_id)
      self.beam_pipeline_args = beam_pipeline_args
      self.make_beam_pipeline_fn = make_beam_pipeline_fn

  def __init__(self, context: Optional[Context] = None):
    """Constructs a beam based executor."""
    super().__init__(context)

    self._beam_pipeline_args = None
    self._make_beam_pipeline_fn = None
    if context:
      if isinstance(context, BaseBeamExecutor.Context):
        self._beam_pipeline_args = context.beam_pipeline_args
        self._make_beam_pipeline_fn = context.make_beam_pipeline_fn
      else:
        raise ValueError('BaseBeamExecutor found initialized with '
                         'BaseExecutorSpec. Please use BeamExecutorSpec for '
                         'Beam Components instead.')

    if self._beam_pipeline_args:
      self._beam_pipeline_args = dependency_utils.make_beam_dependency_flags(
          self._beam_pipeline_args)
      executor_class_path = name_utils.get_full_name(self.__class__)
      # TODO(zhitaoli): Rethink how we can add labels and only normalize them
      # if the job is submitted against GCP.
      with telemetry_utils.scoped_labels(
          {telemetry_utils.LABEL_TFX_EXECUTOR: executor_class_path}):
        self._beam_pipeline_args.extend(
            telemetry_utils.make_beam_labels_args())

      # TODO(b/174174381): Don't use beam_pipeline_args to set ABSL flags.
      flags.FLAGS(sys.argv + self._beam_pipeline_args, known_only=True)

  # TODO(b/126182711): Look into how to support fusion of multiple executors
  # into same pipeline.
  def _make_beam_pipeline(self) -> _BeamPipeline:
    """Makes beam pipeline."""
    if self._make_beam_pipeline_fn is not None:
      return self._make_beam_pipeline_fn()
    if not beam:
      raise Exception(
          'Apache Beam must be installed to use this functionality.')

    result = beam.Pipeline(argv=self._beam_pipeline_args)

    # TODO(b/159468583): Obivate this code block by moving the warning to Beam.
    #
    # pylint: disable=g-import-not-at-top
    # pytype: disable=import-error
    from apache_beam.options.pipeline_options import DirectOptions
    from apache_beam.options.pipeline_options import PipelineOptions
    # pytype: enable=import-error
    options = PipelineOptions(self._beam_pipeline_args)
    direct_running_mode = options.view_as(DirectOptions).direct_running_mode
    direct_num_workers = options.view_as(DirectOptions).direct_num_workers
    if direct_running_mode == 'in_memory' and direct_num_workers != 1:
      logging.warning(
          'If direct_num_workers is not equal to 1, direct_running_mode should '
          'be `multi_processing` or `multi_threading` instead of `in_memory` '
          'in order for it to have the desired worker parallelism effect.')

    return result


text:
using UnityEngine;
using System.Collections;

namespace Managers
{
    public class GameManagerPauseBehaviour : MonoBehaviour
    {
        //---------------------------------------------------------------------------------------------------------------
        // Propriedades da Classe

        private bool isPaused;                                                      // Estado do Jogo

        //---------------------------------------------------------------------------------------------------------------
        // Métodos herdados de MonoBehaviour

        private void OnEnable()
        {
            // Atribui os métodos aos Callbacks
            GameManagerMain.GetInstance().GameMenuEvent               += OnGamePause;
            GameManagerMain.GetInstance().ActorItemGlossaryEvent      += OnGamePause;
            GameManagerMain.GetInstance().MasterPowersGlossaryEvent   += OnGamePause;
            //GameManagerMain.GetInstance().MatchSummaryEvent           += OnGamePause;
        }

        private void OnDisable()
        {
            // Retira os métodos dos referêntes Callbacks
            GameManagerMain.GetInstance().GameMenuEvent               -= OnGamePause;
            GameManagerMain.GetInstance().ActorItemGlossaryEvent      -= OnGamePause;
            GameManagerMain.GetInstance().MasterPowersGlossaryEvent   -= OnGamePause;
            //GameManagerMain.GetInstance().MatchSummaryEvent           -= OnGamePause;
        }

        //---------------------------------------------------------------------------------------------------------------
        // Método responsável pelo comportamento GamePause

        private void OnGamePause()
        {
            if(isPaused)
            {
                Time.timeScale = 1;                                                 // Configura a escala de tempo para tempo real.
                isPaused = false;                                                   // Atualiza o estado do jogo.
            }
            else
            {
                Time.timeScale = 0;                                                 // Configura a escala de tempo para congelado.
                isPaused = true;                                                    // Atualiza o estado do jogo.
            }
        }

        //---------------------------------------------------------------------------------------------------------------
    }

    //-------------------------------------------------------------------------------------------------------------------
}


text:
// Copyright 2014-2015, Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.

var AbstractLoader = require('../abstractLoader');
var fs = require('fs');
var Promise = require('promise');
var _ = require('underscore');

/**
 * @class IstanbulLoader
 * @extends AbstractLoader
 * @constructor
 */
var IstanbulLoader = AbstractLoader.extend(

	{
		/**
		 * Has mapping turned on?
		 *
		 * @method hasMapping
		 * @return {string}
		 */
		hasMapping: function () {
			return !!this.getConfiguration().mapping;
		},

		/**
		 * Get mapping
		 *
		 * @method getMapping
		 * @return {object[]} Of `{from:<string>, to:<string>}`
		 */
		getMapping: function () {
			return this.getConfiguration().mapping;
		},

		/**
		 * Processes a single file
		 *
		 * @method _processFile
		 * @param {string} parentId
		 * @param {string} file
		 * @return {Promise}
		 * @private
		 */
		_processFile: function (parentId, file) {

			return new Promise(function (resolve, reject) {

				fs.readFile(file, function (err, data) {

					var cov;

					if (err) {
						reject(err);

					} else {
						cov = data.toString('utf8');
						cov = JSON.parse(cov);

						// Mapping
						if (this.hasMapping()) {
							cov = this._mapCoverage(cov, this.getMapping());
						}

						this.coverage(cov);
						resolve(cov);
					}

				}.bind(this));
			}.bind(this));
		},

		/**
		 * Maps coverage paths to a new path
		 *
		 * @param {object} coverage
		 * @param {object[]} mappingList
		 * @returns {object}
		 * @private
		 */
		_mapCoverage: function (coverage, mappingList) {
			var keys = _.keys(coverage), result = {};

			keys.forEach(function (key) {
				var path = key;

				// Update paths
				(mappingList || []).forEach(function (mapping) {
					path = path.replace(new RegExp(mapping.from), mapping.to);
				});

				// Copy coverage
				result[path] = coverage[key];

				// Replace path in child
				if (result[path].path) {
					result[path].path = path;
				}
			});

			return result;
		}
	}
);

module.exports = IstanbulLoader;


text:
<!DOCTYPE HTML>

    <title>admin</title>
    <meta name="description" content="website description" />
    <meta name="keywords" content="website keywords, website keywords" />
    <meta http-equiv="content-type" content="text/html; charset=windows-1252" />

	<link rel="stylesheet" href="../../css/normalize.min.css">
    <link rel="stylesheet" href="../../css/main-1.6.css">

HOME

RESERVASI

CUSTOMER

PEMESANAN

LAPORAN

GUEST BOOK

LOGOUT


text:
package com.dremio.telemetry.impl.config.metrics;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jmx.JmxReporter;
import com.dremio.telemetry.api.config.ConfigModule;
import com.dremio.telemetry.api.config.ReporterConfigurator;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * Configurator for JMX
 */
@JsonTypeName("jmx")
public class JmxConfigurator extends ReporterConfigurator {

  private final TimeUnit rateUnit;
  private final TimeUnit durationUnit;
  private volatile JmxReporter reporter;

  @JsonCreator
  public JmxConfigurator(
      @JsonProperty("rate") TimeUnit rateUnit,
      @JsonProperty("duration") TimeUnit durationUnit) {
    super();
    this.rateUnit = Optional.ofNullable(rateUnit).orElse(TimeUnit.SECONDS);
    this.durationUnit = Optional.ofNullable(durationUnit).orElse(TimeUnit.MILLISECONDS);
  }

  @Override
  public void configureAndStart(String name, MetricRegistry registry, MetricFilter filter) {
    reporter = JmxReporter.forRegistry(registry).convertRatesTo(rateUnit).convertDurationsTo(durationUnit).filter(filter).build();
    reporter.start();
  }

  @Override
  public int hashCode() {
    return Objects.hash(rateUnit, durationUnit);
  }

  @Override
  public boolean equals(Object other) {
    if(other == null) {
      return false;
    }
    if(!other.getClass().equals(this.getClass())) {
      return false;
    }
    JmxConfigurator o = (JmxConfigurator) other;
    return Objects.equals(rateUnit, o.rateUnit)
        && Objects.equals(durationUnit, o.durationUnit);
  }

  @Override
  public void close() {
    if(reporter != null) {
      reporter.close();
    }
  }

  /**
   * Module that may be added to a jackson object mapper
   * so it can parse jmx config.
   */
  public static class Module extends ConfigModule {
    @Override
    public void setupModule(SetupContext context) {
      context.registerSubtypes(JmxConfigurator.class);
    }
  }
}


text:
import {bootstrap} from '@angular/platform-browser-dynamic';
import {enableProdMode} from '@angular/core';
import {ROUTER_PROVIDERS} from '@angular/router';
import {AppComponent} from './app.component';
import {LoggerService} from './blocks/logger.service';
import {HTTP_PROVIDERS} from '@angular/http';

declare var ENV: string;

if (ENV === 'production') {
    enableProdMode();
}

bootstrap(AppComponent, [
    LoggerService, ROUTER_PROVIDERS, HTTP_PROVIDERS
]);


text:
package java.awt.dnd.peer;

import java.awt.Cursor;
import java.awt.Image;
import java.awt.Point;
import java.awt.dnd.DragSourceContext;
import java.awt.dnd.InvalidDnDOperationException;

/**
 * <p>
 * This interface is supplied by the underlying window system platform to
 * expose the behaviors of the Drag and Drop system to an originator of
 * the same
 * </p>
 *
 * @since 1.2
 *
 */

public interface DragSourceContextPeer {

    /**
     * start a drag
     */

    void startDrag(DragSourceContext dsc, Cursor c, Image dragImage, Point imageOffset) throws InvalidDnDOperationException;

    /**
     * return the current drag cursor
     */

    Cursor getCursor();

    /**
     * set the current drag cursor
     */

    void setCursor(Cursor c) throws InvalidDnDOperationException;

    /**
     * notify the peer that the Transferables DataFlavors have changed
     */

    void transferablesFlavorsChanged();
}


text:
A prototype of a Cyber Security Game that is meant for two players

README file is best viewed through gedit for Linux or in notepad for Windows

Based off the content found in this github repository: https://github.com/m3doc/Cyber

Instructions for installing the game
Step 1. Install Xampp server on your machine
	1a) Go to https://www.apachefriends.org/download.html
	1b) Download Xampp version no greater than 5.6 with a PHP version no greater than 5.6
	For Linux:
	1c) In the terminal give the xampp-linux-x64-5.6.3-0-installer.run file permission by entering command: "sudo chmod +x xampp-linux-x64-5.6.3-0-installer.run
	1d) Then enter the command: "sudo ./xampp-linux-x64-5.6.3-0-installer.run"
	1e) After running the installer setup the xampp server
	1f) Enter the command: "sudo /opt/lampp/lampp start" to start the Xampp service
	1g) Then in your browser enter http://localhost/ to verify that the server is running
	1h) Enter the command: "sudo /opt/lampp/lampp security" to configure the security settings of the server
	1i) The Xampp server has now been succesfully installed
	For Windows:
	1j) Open the CD or DVD drive from My Computer, install the program, and click on run
	1k) When given the initial installation prompt just hit the enter key and accept the default settings
	1l) Once the installation is finished start the Xampp control panel
	1m) Start the Apache and MYSQL services
	1n) Verify the Apache and MYSQL installations by clickling on the administration link for both
	1o) Then enter http://localhost/ to verify that the server is running
	1p) The Xampp server has now been succesfully installed
Step 2. Copy the folder "cyber" into the root directory of your xampp server. For Windows C:\\xampp\htdocs\
	For Linux \opt\lampp\htdocs
Step 3. For Linux: give the folder root permission by doing the command: chmod 777 -R /opt/lampp/htdocs/cyber/
	For Windows: Not required
Step 4. Install the database in the xampp server
	4a) Start xampp server with apache and mysq service
	4b) Go to browser open localhost/phpmyadmin
	4c) Create a database named "acs_cyber" or any name of your choice
	4d) Open the Sql prompt on the same page in the "acs_cyber" database
	4e) Paste the content of the file acs_cyber.sql provided in the cyber_master folder
	4f) Enter Go.
Step 5. Now you are ready with the deployment
	Register at least two players and start playing with each other.


text:
package com.itude.mobile.web.mail;

import java.util.Properties;

import com.itude.mobile.web.environment.ItudeEnvironment;

public class MailConfig
{
  public static int NO_DEFAULTS        = 0;
  public static int SMTP_DEFAULTS      = 1;
  public static int IMAP_DEFAULTS      = 2;

  private boolean   _debug             = false;
  private String    _host              = null;
  private boolean   _auth              = false;
  private int       _port              = 0;
  private boolean   _startTls          = false;
  private String    _userid            = null;
  private String    _password          = null;

  private boolean   _ssl               = false;
  private int       _sslPort           = 0;
  private String    _sslSocketFactory  = null;
  private boolean   _sslFallback       = false;

  private int       _timeout           = 0;
  private int       _connectionTimeout = 0;

  public MailConfig()
  {
    this(NO_DEFAULTS);
  }

  public MailConfig(int mode)
  {
    _debug = ItudeEnvironment.getMailDebug();
    if (mode == IMAP_DEFAULTS)
    {
      _host = ItudeEnvironment.getMailImapHost();
      _auth = ItudeEnvironment.getMailImapAuth();
      _port = Integer.parseInt(ItudeEnvironment.getMailImapPort());
      _startTls = ItudeEnvironment.getMailImapTls();
      _userid = ItudeEnvironment.getMailImapAccount();
      _password = ItudeEnvironment.getMailImapPassword();

      _ssl = ItudeEnvironment.getMailImapSsl();
      _sslPort = Integer.parseInt(ItudeEnvironment.getMailImapPort());
      _sslSocketFactory = ItudeEnvironment.getMailSSLFactory();
      _timeout = ItudeEnvironment.getMailImapTimeout();
      _connectionTimeout = ItudeEnvironment.getMailImapConnectionTimeout();
      _sslFallback = false;
    }
    if (mode == SMTP_DEFAULTS)
    {
      _host = ItudeEnvironment.getMailSmtpHost();
      _auth = ItudeEnvironment.getMailSmtpAuth();
      _port = Integer.parseInt(ItudeEnvironment.getMailSmtpPort());
      _startTls = ItudeEnvironment.getMailSmtpTls();
      _userid = ItudeEnvironment.getMailSmtpAccount();
      _password = ItudeEnvironment.getMailSmtpPassword();
      _timeout = ItudeEnvironment.getMailSmtpTimeout();
      _connectionTimeout = ItudeEnvironment.getMailSmtpConnectionTimeout();

      _ssl = ItudeEnvironment.getMailSmtpSsl();
      _sslPort = Integer.parseInt(ItudeEnvironment.getMailSmtpPort());
      _sslSocketFactory = ItudeEnvironment.getMailSSLFactory();
      _sslFallback = false;
    }
  }

  public Properties getImapProperties()
  {
    Properties props = new Properties();
    props.put("mail.debug", String.valueOf(isDebug()));
    props.put("mail.imap.host", getHost());
    props.put("mail.imap.auth", String.valueOf(isAuth()));
    props.put("mail.imap.port", String.valueOf(getPort()));
    props.put("mail.imap.starttls.enable", String.valueOf(isStartTls()));

    if (getTimeout() != 0) props.put("mail.imap.timeout", String.valueOf(getTimeout()));
    if (getConnectionTimeout() != 0) props.put("mail.imap.connectiontimeout", String.valueOf(getConnectionTimeout()));

    if (isSsl())
    {
      props.put("mail.store.protocol", "imaps");
      props.put("mail.imap.socketFactory.port", String.valueOf(getPort()));

      if (getSslSocketFactory() != null) props.put("mail.imap.socketFactory.class", getSslSocketFactory());
      else props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.imap.socketFactory.fallback", String.valueOf(isSslFallback()));
    }
    return props;
  }

  public Properties getSmtpProperties()
  {
    Properties props = new Properties();
    props.put("mail.debug", String.valueOf(isDebug()));

    props.put("mail.smtp.host", getHost());
    props.put("mail.smtp.auth", String.valueOf(isAuth()));
    props.put("mail.smtp.port", String.valueOf(getPort()));
    props.put("mail.smtp.starttls.enable", String.valueOf(isStartTls()));
    props.put("mail.smtp.quitwait", "false");

    if (getTimeout() != 0) props.put("mail.smtp.timeout", String.valueOf(getTimeout()));
    if (getConnectionTimeout() != 0) props.put("mail.smtp.connectiontimeout", String.valueOf(getConnectionTimeout()));

    if (isSsl())
    {
      props.put("mail.smtp.socketFactory.port", String.valueOf(getPort()));
      if (getSslSocketFactory() != null) props.put("mail.smtp.socketFactory.class", getSslSocketFactory());
      else props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.socketFactory.fallback", String.valueOf(isSslFallback()));
    }

    return props;
  }

  public boolean isDebug()
  {
    return _debug;
  }

  public void setDebug(boolean debug)
  {
    _debug = debug;
  }

  public String getHost()
  {
    return _host;
  }

  public void setHost(String host)
  {
    _host = host;
  }

  public boolean isAuth()
  {
    return _auth;
  }

  public void setAuth(boolean auth)
  {
    _auth = auth;
  }

  public int getPort()
  {
    return _port;
  }

  public void setPort(int port)
  {
    _port = port;
  }

  public boolean isStartTls()
  {
    return _startTls;
  }

  public void setStartTls(boolean startTls)
  {
    _startTls = startTls;
  }

  public String getUserid()
  {
    return _userid;
  }

  public void setUserid(String userid)
  {
    _userid = userid;
  }

  public String getPassword()
  {
    return _password;
  }

  public void setPassword(String password)
  {
    _password = password;
  }

  public boolean isSsl()
  {
    return _ssl;
  }

  public void setSsl(boolean ssl)
  {
    _ssl = ssl;
  }

  public int getSslPort()
  {
    return _sslPort;
  }

  public void setSslPort(int sslPort)
  {
    _sslPort = sslPort;
  }

  public String getSslSocketFactory()
  {
    return _sslSocketFactory;
  }

  public void setSslSocketFactory(String sslSocketFactory)
  {
    _sslSocketFactory = sslSocketFactory;
  }

  public boolean isSslFallback()
  {
    return _sslFallback;
  }

  public void setSslFallback(boolean sslFallback)
  {
    _sslFallback = sslFallback;
  }

  public void setTimeout(int timeout)
  {
    _timeout = timeout;
  }

  public int getTimeout()
  {
    return _timeout;
  }

  public void setConnectionTimeout(int connectionTimeout)
  {
    _connectionTimeout = connectionTimeout;
  }

  public int getConnectionTimeout()
  {
    return _connectionTimeout;
  }
}


text:
// .NAME vtkContourTriangulator - Fill all 2D contours to create polygons
// .SECTION Description
// vtkContourTriangulator will generate triangles to fill all of the 2D
// contours in its input.  The contours may be concave, and may even
// contain holes i.e. a contour may contain an internal contour that
// is wound in the opposite direction to indicate that it is a hole.
// .SECTION Caveats
// The triangulation of is done in O(n) time for simple convex
// inputs, but for non-convex inputs the worst-case time is O(n^2*m^2)
// where n is the number of points and m is the number of holes.
// The best triangulation algorithms, in contrast, are O(n log n).
// The resulting triangles may be quite narrow, the algorithm does
// not attempt to produce high-quality triangles.
// .SECTION Thanks
// Thanks to David Gobbi for contributing this class to VTK.

#ifndef vtkContourTriangulator_h
#define vtkContourTriangulator_h

#include "vtkFiltersGeneralModule.h" // For export macro
#include "vtkPolyDataAlgorithm.h"

class vtkCellArray;
class vtkIdList;

class VTKFILTERSGENERAL_EXPORT vtkContourTriangulator : public vtkPolyDataAlgorithm
{
public:
  static vtkContourTriangulator *New();
  vtkTypeMacro(vtkContourTriangulator,vtkPolyDataAlgorithm);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Check if there was a triangulation failure in the last update.
  vtkGetMacro(TriangulationError, int);

  // Description:
  // Generate errors when the triangulation fails.
  // Note that triangulation failures are often minor, because they involve
  // tiny triangles that are too small to see.
  vtkSetMacro(TriangulationErrorDisplay, int);
  vtkBooleanMacro(TriangulationErrorDisplay, int);
  vtkGetMacro(TriangulationErrorDisplay, int);

  // Description:
  // A robust method for triangulating a polygon.
  // It cleans up the polygon and then applies the ear-cut triangulation.
  // A zero return value indicates that triangulation failed.
  static int TriangulatePolygon(
    vtkIdList *polygon, vtkPoints *points, vtkCellArray *triangles);

  // Description:
  // Given some closed contour lines, create a triangle mesh that
  // fills those lines.  The input lines must be single-segment lines,
  // not polylines.  The input lines do not have to be in order.
  // Only numLines starting from firstLine will be used.
  static int TriangulateContours(
    vtkPolyData *data, vtkIdType firstLine, vtkIdType numLines,
    vtkCellArray *outputPolys, const double normal[3]);

protected:
  vtkContourTriangulator();
  ~vtkContourTriangulator();

  virtual int RequestData(
    vtkInformation* request, vtkInformationVector** inputVector,
    vtkInformationVector* outputVector);

  int TriangulationError;
  int TriangulationErrorDisplay;

private:
  vtkContourTriangulator(const vtkContourTriangulator&) VTK_DELETE_FUNCTION;
  void operator=(const vtkContourTriangulator&) VTK_DELETE_FUNCTION;
};

#endif


text:
"""
author: Lalit Jain, lalitkumarjj@gmail.com
modified: Chris Fernandez, chris2fernandez@gmail.com
last updated: 05/27/2015

A module for replicating the dueling bandits pure exploration experiments from the NEXT paper.

Usage:
python experiment_dueling.py
"""
import os, sys
from boto.s3.connection import S3Connection
from boto.s3.key import Key

# import launch_experiment. We assume that it is located in the next-discovery top level directory.
sys.path.append("../")
from launch_experiment import *

curr_dir = os.path.dirname(os.path.abspath(__file__))
experiment_list = []
# A list of the currently available Stochastic Dueling Borda Bandit Pure Exploration algorithms
supported_alg_ids = ['BR_LilUCB','BR_Random','BR_SuccElim','BeatTheMean', 'BR_Thompson']

# Create common alg_list
alg_list = []
for alg_id in supported_alg_ids:
  alg_item = {}
  alg_item['alg_id'] = alg_id
  alg_item['alg_label'] = alg_id
  alg_item['params'] = {}
  alg_list.append(alg_item)

# Create common algorithm management settings
algorithm_management_settings = {}
params = {}
params['proportions'] = []
for algorithm in alg_list:
    params['proportions'].append(  { 'alg_label': algorithm['alg_label'] , 'proportion':1./len(alg_list) }  )

# Run algorithms here in fixed proportions
algorithm_management_settings['mode'] = 'fixed_proportions'
algorithm_management_settings['params'] = params

# Create experiment dictionary
cap = 'cap436'
initExp = {}
initExp['args'] = {}
initExp['args']['n'] = 25
initExp['args']['failure_probability'] = .01
initExp['args']['participant_to_algorithm_management'] = 'one_to_many'
initExp['args']['algorithm_management_settings'] = algorithm_management_settings
initExp['args']['alg_list'] = alg_list
# initExp['args']['instructions'] = ''
# initExp['args']['debrief'] = ''
initExp['args']['num_tries'] = 50
initExp['app_id'] = 'DuelingBanditsPureExploration'
initExp['site_id'] = 'replace this with working site id'
initExp['site_key'] = 'replace this with working site key'

# Set the context
experiment = {}
experiment['initExp'] = initExp
experiment['target_file'] = curr_dir+"/cap436.txt"
experiment['context'] = curr_dir+"/cap436.jpg"
experiment['context_type'] = 'image'
experiment_list.append(experiment)

# Launch the experiment
try:
  AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
  AWS_ACCESS_ID = os.environ['AWS_ACCESS_KEY_ID']
  AWS_BUCKET_NAME = os.environ['AWS_BUCKET_NAME']
  host = os.environ['NEXT_BACKEND_GLOBAL_HOST']+":"+os.environ.get('NEXT_BACKEND_GLOBAL_PORT', '8000')

except:
  print "You must set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, NEXT_BACKEND_GLOBAL_HOST as environment variables"
  sys.exit()

# Call launch_experiment module found in NEXT/lauch_experiment.py
exp_uid_list, exp_key_list, widget_key_list = launch_experiment(host, experiment_list, AWS_ACCESS_ID, AWS_SECRET_ACCESS_KEY, AWS_BUCKET_NAME)

# Update the cartoon_dueling.html file wit the exp_uid_list and widget_key_list
# with open('cartoon_dueling.html','r') as page:
#   print "opended file"
#   page_string = page.read()
#   page_string = page_string.replace("{{exp_uid_list}}", str(exp_uid_list))
#   page_string = page_string.replace("{{widget_key_list}}", str(widget_key_list))
#   with open('../../next_frontend_base/next_frontend_base/templates/cartoon_dueling.html','w') as out:
#     out.write(page_string)
#     out.flush()
#     out.close()


text:
using Discord.Commands;
using WizBot.Classes;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace WizBot.Modules.Games.Commands
{
    class BetrayGame : DiscordCommand
    {
        public BetrayGame(DiscordModule module) : base(module) { }

        private enum Answers
        {
            Cooperate,
            Betray
        }
        internal override void Init(CommandGroupBuilder cgb)
        {
            cgb.CreateCommand(Module.Prefix + "betray")
                .Description("BETRAY GAME. Betray WizBot next turn." +
                             "If WizBot cooperates - you get extra points, WizBot loses a LOT." +
                             $"If WizBot betrays - you both lose some points. | `{Prefix}betray`")
                .Do(async e =>
                {
                    await ReceiveAnswer(e, Answers.Betray).ConfigureAwait(false);
                });

            cgb.CreateCommand(Module.Prefix + "cooperate")
                .Description("BETRAY GAME. Cooperate with WizBot next turn." +
                             "If WizBot cooperates - you both get bonus points." +
                             $"If WizBot betrays - you lose A LOT, WizBot gets extra. | `{Prefix}cooperater`")
                .Do(async e =>
                {

                    await ReceiveAnswer(e, Answers.Cooperate).ConfigureAwait(false);
                });
        }

        private int userPoints = 0;

        private int UserPoints {
            get { return userPoints; }
            set {
                if (value < 0)
                    userPoints = 0;
                userPoints = value;
            }
        }
        private int WizPoints = 0;
        private int wizPoints {
            get { return wizPoints; }
            set {
                if (value < 0)
                    wizPoints = 0;
                wizPoints = value;
            }
        }

        private int round = 0;
        private Answers NextAnswer = Answers.Cooperate;
        private async Task ReceiveAnswer(CommandEventArgs e, Answers userAnswer)
        {
            var response = userAnswer == Answers.Betray
                ? ":no_entry: `You betrayed WizBot` - you monster."
                : ":ok: `You cooperated with WizBot.` ";
            var currentAnswer = NextAnswer;
            var wizResponse = currentAnswer == Answers.Betray
                ? ":no_entry: `aww WizBot betrayed you` - she is so cute"
                : ":ok: `WizBot cooperated.`";
            NextAnswer = userAnswer;
            if (userAnswer == Answers.Betray && currentAnswer == Answers.Betray)
            {
                WizPoints--;
                UserPoints--;
            }
            else if (userAnswer == Answers.Cooperate && currentAnswer == Answers.Cooperate)
            {
                WizPoints += 2;
                UserPoints += 2;
            }
            else if (userAnswer == Answers.Betray && currentAnswer == Answers.Cooperate)
            {
                WizPoints -= 3;
                UserPoints += 3;
            }
            else if (userAnswer == Answers.Cooperate && currentAnswer == Answers.Betray)
            {
                WizPoints += 3;
                UserPoints -= 3;
            }

            await e.Channel.SendMessage($"**ROUND {++round}**\n" +
                                        $"{response}\n" +
                                        $"{wizResponse}\n" +
                                        $"--------------------------------\n" +
                                        $"WizBot has {WizPoints} points." +
                                        $"You have {UserPoints} points." +
                                        $"--------------------------------\n")
                                            .ConfigureAwait(false);
            if (round < 10) return;
            if (wizPoints == userPoints)
                await e.Channel.SendMessage("Its a draw").ConfigureAwait(false);
            else if (wizPoints > userPoints)
                await e.Channel.SendMessage("WizBot won.").ConfigureAwait(false);
            else
                await e.Channel.SendMessage("You won.").ConfigureAwait(false);
            wizPoints = 0;
            userPoints = 0;
            round = 0;
        }
    }

    public class BetraySetting
    {
        private string Story = $"{0} have robbed a bank and got captured by a police." +
                               $"Investigators gave you a choice:\n" +
                               $"You can either >COOPERATE with your friends and " +
                               $"not tell them who's idea it was, OR you can >BETRAY your" +
                               $"friends. Depending on their answers your penalty will vary.";

        public int DoubleCoop = 1;
        public int DoubleBetray = -1;
        public int BetrayCoop_Betrayer = 3;
        public int BetrayCoop_Cooperater = -3;

        public string GetStory(IEnumerable<string> names) => String.Format(Story, string.Join(", ", names));
    }
}


text:
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.contrib.hooks.bigquery_hook import BigQueryHook
from airflow.utils.decorators import apply_defaults

class BigQueryTableSensor(BaseSensorOperator):
    """
    Checks for the existence of a table in Google Bigquery.

    :param project_id: The Google cloud project in which to look for the table.
        The connection supplied to the hook must provide
        access to the specified project.
    :type project_id: str
    :param dataset_id: The name of the dataset in which to look for the table.
        storage bucket.
    :type dataset_id: str
    :param table_id: The name of the table to check the existence of.
    :type table_id: str
    :param bigquery_conn_id: The connection ID to use when connecting to
        Google BigQuery.
    :type bigquery_conn_id: str
    :param delegate_to: The account to impersonate, if any.
        For this to work, the service account making the request must
        have domain-wide delegation enabled.
    :type delegate_to: str
    """
    template_fields = ('project_id', 'dataset_id', 'table_id',)
    ui_color = '#f0eee4'

    @apply_defaults
    def __init__(self,
                 project_id,
                 dataset_id,
                 table_id,
                 bigquery_conn_id='bigquery_default_conn',
                 delegate_to=None,
                 *args, **kwargs):

        super(BigQueryTableSensor, self).__init__(*args, **kwargs)
        self.project_id = project_id
        self.dataset_id = dataset_id
        self.table_id = table_id
        self.bigquery_conn_id = bigquery_conn_id
        self.delegate_to = delegate_to

    def poke(self, context):
        table_uri = '{0}:{1}.{2}'.format(self.project_id, self.dataset_id, self.table_id)
        self.log.info('Sensor checks existence of table: %s', table_uri)
        hook = BigQueryHook(
            bigquery_conn_id=self.bigquery_conn_id,
            delegate_to=self.delegate_to)
        return hook.table_exists(self.project_id, self.dataset_id, self.table_id)


text:
This is my wrestling choose your own adventure story.
You will need ruby. or for windows you need to look up ruby for windows
**_THIS IS NOT THE FINAL BUILD._**
but after the final build there will still be updates

## TO DO:
* Finish all of the WWE Storylines from beginning to the end.
* Work on TNA, I will do this a bit when I am still making the WWE Storylines
but after I do WWE then TNA is my main project.
* Add More features
* Fix the ending feature, I have to figure out how to fix the error message it shows.
If anyone wants to help then you are welcome to help.
**YOU NEED RUBY EXPERIENCE**

Go to the ending branch to get the ending feature that doesn't Work
for now. I will make branches for new Features
* Switch Companies from big leagues to big leagues, indie to big leagues or big leagues to indie


text:
/**
 * Deals with printing
 *
 * @module print
 */

import $ from 'jquery';

let dpi, printStyleSheet;
let printStyleSheetLink;
import dialog from 'enketo/dialog';

// make sure setDpi is not called until DOM is ready
$( document ).ready( () => {
    setDpi();
} );

/**
 * @typedef PaperObj
 * @property {string} format
 * @property {string} margin
 * @property {string} orientation
 */

/**
 * Calculates the dots per inch and sets the dpi property
 */
function setDpi() {
    const dpiO = {};
    const e = document.body.appendChild( document.createElement( 'DIV' ) );
    e.style.width = '1in';
    e.style.padding = '0';
    dpiO.v = e.offsetWidth;
    e.parentNode.removeChild( e );
    dpi = dpiO.v;
}

/**
 * Gets a single print stylesheet
 *
 * @return {Element|null}
 */
function getPrintStyleSheet() {
    // document.styleSheets is an Object not an Array!
    for ( const i in document.styleSheets ) {
        if ( Object.prototype.hasOwnProperty.call( document.styleSheets, i ) ) {
            const sheet = document.styleSheets[ i ];
            if ( sheet.media.mediaText === 'print' ) {
                return sheet;
            }
        }
    }
    return null;
}

/**
 * Obtains a link element with a reference to the print stylesheet.
 *
 * @return {Element}
 */
function getPrintStyleSheetLink() {
    return document.querySelector( 'link[media="print"]' );
}

/**
 * Applies the print stylesheet to the current view by changing stylesheets media property to 'all'
 *
 * @static
 * @return {boolean}
 */
function styleToAll() {
    // sometimes, setStylesheet fails upon loading
    printStyleSheet = printStyleSheet || getPrintStyleSheet();
    printStyleSheetLink = printStyleSheetLink || getPrintStyleSheetLink();
    // Chrome:
    printStyleSheet.media.mediaText = 'all';
    // Firefox:
    printStyleSheetLink.setAttribute( 'media', 'all' );
    return !!printStyleSheet;
}

/**
 * Resets the print stylesheet to only apply to media 'print'
 *
 * @static
 */
function styleReset() {
    printStyleSheet.media.mediaText = 'print';
    printStyleSheetLink.setAttribute( 'media', 'print' );
    $( '.print-height-adjusted, .print-width-adjusted, .main' )
        .removeAttr( 'style' )
        .removeClass( 'print-height-adjusted print-width-adjusted' );
    $( '.back-to-screen-view' ).off( 'click' ).remove();
}

/**
 * Tests if the form element is set to use the Grid Theme.
 *
 * @static
 * @return {boolean}
 */
function isGrid() {
    return /theme-.*grid.*/.test( document.querySelector( 'form.or' ).getAttribute( 'class' ) );
}

/**
 * Fixes a Grid Theme layout programmatically by imitating CSS multi-line flexbox in JavaScript.
 *
 * @static
 * @param {PaperObj} paper
 * @return {Promise}
 */
function fixGrid( paper ) {
    // to ensure cells grow correctly with text-wrapping before fixing heights and widths.
    const main = document.querySelector( '.main' );
    main.style.width = getPaperPixelWidth( paper );
    main.classList.add( 'print-width-adjusted' );
    // wait for browser repainting after width change
    return new Promise( resolve => {
        setTimeout( () => {
            let $row;
            let rowTop;
            // the -1px adjustment is necessary because the h3 element width is calc(100% + 1px)
            const maxWidth = $( '#form-title' ).outerWidth() - 1;
            const els = document.querySelectorAll( '.question:not(.draft), .trigger:not(.draft)' );

            els.forEach( ( el, index ) => {
                const lastElement = index === els.length - 1;
                const $el = $( el );
                const top = $el.offset().top;
                rowTop = ( rowTop || rowTop === 0 ) ? rowTop : top;
                $row = $row || $el;

                if ( top === rowTop ) {
                    $row = $row.add( $el );
                }

                if ( top > rowTop || lastElement ) {
                    const widths = [];
                    let cumulativeWidth = 0;
                    let maxHeight = 0;

                    $row.each( function() {
                        const width = Number( $( this ).css( 'width' ).replace( 'px', '' ) );
                        widths.push( width );
                        cumulativeWidth += width;
                    } );

                    // adjusts widths if w-values don't add up to 100%
                    if ( cumulativeWidth < maxWidth ) {
                        const diff = maxWidth - cumulativeWidth;
                        $row.each( function( index ) {
                            const width = widths[ index ] + ( widths[ index ] / cumulativeWidth ) * diff;
                            // round down to 2 decimals to avoid 100.001% totals
                            $( this )
                                .css( 'width', `${Math.floor( ( width * 100 / maxWidth ) * 100 ) / 100}%` )
                                .addClass( 'print-width-adjusted' );
                        } );
                    }

                    $row.each( function() {
                        const height = $( this ).outerHeight();
                        maxHeight = ( height > maxHeight ) ? height : maxHeight;
                    } );

                    $row.addClass( 'print-height-adjusted' ).css( 'height', `${maxHeight}px` );

                    // start a new row
                    $row = $el;
                    rowTop = $el.offset().top;
                } else if ( rowTop < top ) {
                    console.error( 'unexpected question top position: ', top, 'for element:', $el, 'expected >=', rowTop );
                }
            } );

            // In case anybody is using this event.
            $( window ).trigger( 'printviewready' );
            resolve();
        }, 800 );
    } );
}

/**
 * Returns a CSS width value in px (e.g. `"100px"`) for a provided paper format, orientation (`"portrait"` or `"landscape"`) and margin (as any valid CSS value).
 *
 * @param {PaperObj} paper
 * @return {string}
 */
function getPaperPixelWidth( paper ) {
    let printWidth;
    const FORMATS = {
        Letter: [ 8.5, 11 ],
        Legal: [ 8.5, 14 ],
        Tabloid: [ 11, 17 ],
        Ledger: [ 17, 11 ],
        A0: [ 33.1, 46.8 ],
        A1: [ 23.4, 33.1 ],
        A2: [ 16.5, 23.4 ],
        A3: [ 11.7, 16.5 ],
        A4: [ 8.27, 11.7 ],
        A5: [ 5.83, 8.27 ],
        A6: [ 4.13, 5.83 ],
    };
    paper.landscape = typeof paper.landscape === 'boolean' ? paper.landscape : paper.orientation === 'landscape';
    delete paper.orientation;

    if ( typeof paper.margin === 'undefined' ) {
        paper.margin = 0.4;
    } else if ( /^[\d.]+in$/.test( paper.margin.trim() ) ) {
        paper.margin = parseFloat( paper.margin, 10 );
    } else if ( /^[\d.]+cm$/.test( paper.margin.trim() ) ) {
        paper.margin = parseFloat( paper.margin, 10 ) / 2.54;
    } else if ( /^[\d.]+mm$/.test( paper.margin.trim() ) ) {
        paper.margin = parseFloat( paper.margin, 10 ) / 25.4;
    }

    paper.format = typeof paper.format === 'string' && typeof FORMATS[ paper.format ] !== 'undefined' ? paper.format : 'A4';
    printWidth = ( paper.landscape === true ) ? FORMATS[ paper.format ][ 1 ] : FORMATS[ paper.format ][ 0 ];

    return `${( printWidth - ( 2 * paper.margin ) ) * dpi}px`;
}

/**
 * @static
 */
function openAllDetails() {
    document.querySelectorAll( 'details.or-form-guidance.active' )
        .forEach( details => {
            if ( details.open ) {
                details.dataset.previousOpen = true;
            } else {
                details.open = true;
            }
        } );
}

/**
 * @static
 */
function closeAllDetails() {
    document.querySelectorAll( 'details.or-form-guidance.active' )
        .forEach( details => {
            if ( details.dataset.previousOpen ) {
                delete details.dataset.previousOpen;
            } else {
                details.open = false;
            }
        } );
}

/**
 * Prints the form after first preparing the Grid (every time it is called).
 *
 * It's just a demo function that only collects paper format and should be replaced
 * in your app with a dialog that collects a complete paper format (size, margin, orientation);
 *
 * @static
 * @param {string} theme
 */
function print( theme ) {
    if ( theme === 'grid' || ( !theme && isGrid() ) ) {
        let swapped = false;
        dialog.prompt( 'Enter valid paper format', 'A4' )
            .then( format => {
                if ( !format ) {
                    throw new Error( 'Print cancelled by user.' );
                }
                swapped = styleToAll();
                return fixGrid( {
                    format
                } );
            } )
            .then( window.print )
            .catch( console.error )
            .then( () => {
                if ( swapped ) {
                    setTimeout( styleReset, 500 );
                }
            } );
    } else {
        window.print();
    }
}

export { print, fixGrid, styleToAll, styleReset, isGrid, openAllDetails, closeAllDetails };


text:
using System;
using System.Linq;
using Telerik.Data.Core;
using Telerik.UI.Xaml.Controls.Primitives.DragDrop;
using Telerik.UI.Xaml.Controls.Primitives.DragDrop.Reorder;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Telerik.UI.Xaml.Controls.Grid.Primitives
{
    /// <summary>
    /// Represents the UI on the left edge of a <see cref="RadDataGrid"/> instance. Used to access the Grouping Flyout.
    /// </summary>
    public partial class DataGridColumnsFlyout : IDragDropElement
    {
        internal override void SetupDragDropProperties(IReorderItem item, int logicalIndex)
        {
            base.SetupDragDropProperties(item, logicalIndex);
            if (this.Owner.Owner.Columns.Count > 1)
            {
                DragDrop.SetAllowDrag(item.Visual, true);
            }
        }

        internal override void CommitReorderOperation(int sourceIndex, int destinationIndex)
        {
            this.Owner.Owner.DragBehavior.ReorderColumn(sourceIndex, destinationIndex);
        }

        internal override bool CanStartDrag(DragDropTrigger trigger, object initializeContext)
        {
            return this.Owner.Owner.DragBehavior != null && this.Owner.Owner.DragBehavior.CanStartDragInFlyout(this.DataContext as DataGridColumn);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 18(4): 165 (1926)

#### Original name
Scolecodothis pinicola Miles

### Remarks
null


text:
"""
   Copyright 2016 The Trustees of Princeton University

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""

import os
import sys
import subprocess
import random
import time

import testlib
import testconf
import shutil

REPL_PATH = os.path.join(testconf.SYNDICATE_UG_ROOT, "syndicate-repl")
MKDIR_PATH = os.path.join(testconf.SYNDICATE_UG_ROOT, "syndicate-mkdir")
RG_PATH = os.path.join(testconf.SYNDICATE_RG_ROOT, "syndicate-rg")
RG_DRIVER = os.path.join(testconf.SYNDICATE_PYTHON_ROOT, "syndicate/rg/drivers/disk" )
NUM_FILES = 2

def stop_and_save( output_dir, proc, out_path, save_name ):
    exitcode, out = testlib.stop_gateway( proc, out_path )
    testlib.save_output( output_dir, save_name, out )
    return exitcode, out

if __name__ == "__main__":

    local_path = testlib.make_random_file(16384)
    local_fd = open(local_path, "r")
    write_data = local_fd.read()
    local_fd.close()

    local_path_2 = testlib.make_random_file(16384)
    local_fd_2 = open(local_path_2, "r")
    write_data_2 = local_fd_2.read()
    local_fd_2.close()

    config_dir, output_dir = testlib.test_setup()
    volume_name = testlib.add_test_volume( config_dir, blocksize=1024 )

    RG_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "RG", caps="NONE", email=testconf.SYNDICATE_ADMIN )
    testlib.update_gateway( config_dir, RG_gateway_name, "port=31112", "driver=%s" % RG_DRIVER )

    rg_proc, rg_out_path = testlib.start_gateway( config_dir, RG_PATH, testconf.SYNDICATE_ADMIN, volume_name, RG_gateway_name, valgrind=True )
    if not testlib.gateway_ping(31112, 15):
        raise Exception("%s exited %s" % (RG_PATH, rg_proc.poll()))

    # should cause the RG to get updated that there's a new gateway
    gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN )
    cat_gateway_name = testlib.add_test_gateway( config_dir, volume_name, "UG", caps="ALL", email=testconf.SYNDICATE_ADMIN )

    # look up reader gateway
    cat_gateway_info = testlib.read_gateway( config_dir, cat_gateway_name )
    cat_gateway_id = cat_gateway_info['g_id']

    # look up RG
    rg_gateway_info = testlib.read_gateway( config_dir, RG_gateway_name )
    rg_gateway_id = rg_gateway_info['g_id']

    volume_info = testlib.read_volume( config_dir, volume_name )
    volume_id = volume_info['volume_id']

    random_part = hex(random.randint(0, 2**32-1))[2:]
    output_paths = []

    # make target directory
    exitcode, out = testlib.run( MKDIR_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), '-u', testconf.SYNDICATE_ADMIN, '-v', volume_name, '-g', gateway_name, "/newdir", valgrind=True )
    testlib.save_output( output_dir, "syndicate-mkdir", out )

    if exitcode != 0:
        stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg")
        raise Exception("%s exited %s" % (PUT_PATH, exitcode))

    # generate the commands to feed into the REPL
    repl_cmd = ""
    for i in xrange(0, NUM_FILES):
        output_path = "/put-%s-%s" % (random_part, i)
        output_paths.append(output_path)

        repl_cmd += "create %s 0644\n" % output_path
        repl_cmd += "write 0 0 %s %s\n" % (len(write_data), write_data)

        # truncate while open
        # make smaller
        repl_cmd += "ftrunc 0 %s\n" % (len(write_data)/2)

        # write it again
        repl_cmd += "write 0 0 %s %s\n" % (len(write_data_2), write_data_2)

        # truncate again
        repl_cmd += "ftrunc 0 %s\n" % (len(write_data_2)/2)

        # now close
        repl_cmd += "close 0\n"

        # read it back
        repl_cmd += "open %s 2\n" % output_path
        repl_cmd += "read 0 0 %s\n" % len(write_data_2)
        repl_cmd += "close 0\n"

    print "\n".join( ["< %s" % l[:min(80, len(l))] + "..."[:min(max(0, len(l)-80), 3)] for l in repl_cmd.split("\n")] )

    # open the syndicate REPL
    ug_proc, ug_out_path = testlib.start_gateway( config_dir, REPL_PATH, testconf.SYNDICATE_ADMIN, volume_name, gateway_name, valgrind=True, stdin=True)
    if not testlib.gateway_ping( 31111, 15 ):
        stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg")
        raise Exception("%s exited %s" % (REPL_PATH, repl_proc.poll()))

    out, exit_rc = testlib.finish( ug_proc, stdin=repl_cmd, out_path=ug_out_path, valgrind=True )
    testlib.save_output( output_dir, "syndicate-repl", out )

    if exit_rc != 0:
        stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg")
        raise Exception("%s exited %s" % (REPL_PATH, exit_rc))

    rg_exitcode, rg_out = stop_and_save( output_dir, rg_proc, rg_out_path, "syndicate-rg")
    if rg_exitcode != 0:
        raise Exception("%s exited %s" % (RG_PATH, rg_exitcode))

    # search for the expected data
    # should show up in the read commands
    # expect only the first half
    off = 0
    expected_data = write_data_2[:(len(write_data_2)/2)]
    for i in xrange(0, NUM_FILES):
        off = out[off:].find(expected_data)
        if off < 0:
            # not found!
            print expected_data
            raise Exception("Missing count %s of expected data" % i)

        off += len(expected_data)

    sys.exit(0)


text:
set -e
set -x

CURDIR="$(dirname $BASH_SOURCE)"

. $CURDIR/_build-lib.sh

# Setup a temp docker build context dir
WKDIR=$(mktemp -d docker-build.XXXX)
cp $CURDIR/Dockerfile.runtime $WKDIR

# Hard code the platform dir here
cp $CURDIR/../_docker_workspace/out/$RELEASE_PLATFORM/bin/* $WKDIR/
mkdir -p $WKDIR/python
cp python/*.py $WKDIR/python/
cp python/cf-runtime-requirements.txt $WKDIR/

echo "Docker build context:"
ls -la $WKDIR

docker build --force-rm ${NO_CACHE_ARGS} \
  -t $IMG_TAG \
  --label BUILD_STAMP=$BUILD_STAMP \
  -f $WKDIR/Dockerfile.runtime \
  $WKDIR

docker history $IMG_TAG
echo "Built docker image $IMG_TAG"

rm -rf docker-build.????


text:
from gi.repository import Gio # pylint: disable=E0611

from locale import gettext as _

import logging
logger = logging.getLogger('jekyll_helper')

from jekyll_helper_lib.PreferencesDialog import PreferencesDialog

class PreferencesJekyllHelperDialog(PreferencesDialog):
    __gtype_name__ = "PreferencesJekyllHelperDialog"

    def finish_initializing(self, builder): # pylint: disable=E1002
        """Set up the preferences dialog"""
        super(PreferencesJekyllHelperDialog, self).finish_initializing(builder)

        # Bind each preference widget to gsettings
        settings = Gio.Settings("net.launchpad.jekyll-helper")
        # Serve command
        widget = self.builder.get_object('serve_command_entry')
        settings.bind("serve-command", widget, "text", Gio.SettingsBindFlags.DEFAULT)
        # Build command
        widget = self.builder.get_object('build_command_entry')
        settings.bind("build-command", widget, "text", Gio.SettingsBindFlags.DEFAULT)
        # Push command
        widget = self.builder.get_object('push_command_entry')
        settings.bind("push-command", widget, "text", Gio.SettingsBindFlags.DEFAULT)
        # New command
        widget = self.builder.get_object('new_command_entry1')
        settings.bind("new-command1", widget, "text", Gio.SettingsBindFlags.DEFAULT)
        widget = self.builder.get_object('new_command_entry2')
        settings.bind("new-command2", widget, "text", Gio.SettingsBindFlags.DEFAULT)

        # Code for other initialization actions should be added here.


text:
package org.apache.calcite.rel.core;

import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelInput;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.hint.RelHint;
import org.apache.calcite.rel.metadata.RelMdUtil;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.sql.SqlKind;

import java.util.Collections;
import java.util.List;

/**
 * Relational expression that returns the union of the rows of its inputs,
 * optionally eliminating duplicates.
 *
 * <p>Corresponds to SQL {@code UNION} and {@code UNION ALL}.
 */
public abstract class Union extends SetOp {
  //~ Constructors -----------------------------------------------------------

  protected Union(
      RelOptCluster cluster,
      RelTraitSet traits,
      List<RelHint> hints,
      List<RelNode> inputs,
      boolean all) {
    super(cluster, traits, hints, inputs, SqlKind.UNION, all);
  }

  protected Union(
      RelOptCluster cluster,
      RelTraitSet traits,
      List<RelNode> inputs,
      boolean all) {
    super(cluster, traits, Collections.emptyList(), inputs, SqlKind.UNION, all);
  }

  /**
   * Creates a Union by parsing serialized output.
   */
  protected Union(RelInput input) {
    super(input);
  }

  //~ Methods ----------------------------------------------------------------

  @Override public double estimateRowCount(RelMetadataQuery mq) {
    double dRows = RelMdUtil.getUnionAllRowCount(mq, this);
    if (!all) {
      dRows *= 0.5;
    }
    return dRows;
  }

  @Deprecated // to be removed before 2.0
  public static double estimateRowCount(RelNode rel) {
    final RelMetadataQuery mq = rel.getCluster().getMetadataQuery();
    return RelMdUtil.getUnionAllRowCount(mq, (Union) rel);
  }
}


text:
class College < ActiveRecord::Base

  # relationship
  belongs_to :alumni
  has_many :trainings
  has_many :organizations
  accepts_nested_attributes_for :trainings
  accepts_nested_attributes_for :organizations

  validates_presence_of :join_year

end


text:
template <class T>
void test_is_unsigned()
{
    static_assert( std::is_unsigned<T>::value, "");
    static_assert( std::is_unsigned<const T>::value, "");
    static_assert( std::is_unsigned<volatile T>::value, "");
    static_assert( std::is_unsigned<const volatile T>::value, "");
#if TEST_STD_VER > 14
    static_assert( std::is_unsigned_v<T>, "");
    static_assert( std::is_unsigned_v<const T>, "");
    static_assert( std::is_unsigned_v<volatile T>, "");
    static_assert( std::is_unsigned_v<const volatile T>, "");
#endif
}

template <class T>
void test_is_not_unsigned()
{
    static_assert(!std::is_unsigned<T>::value, "");
    static_assert(!std::is_unsigned<const T>::value, "");
    static_assert(!std::is_unsigned<volatile T>::value, "");
    static_assert(!std::is_unsigned<const volatile T>::value, "");
#if TEST_STD_VER > 14
    static_assert(!std::is_unsigned_v<T>, "");
    static_assert(!std::is_unsigned_v<const T>, "");
    static_assert(!std::is_unsigned_v<volatile T>, "");
    static_assert(!std::is_unsigned_v<const volatile T>, "");
#endif
}

class Class
{
public:
    ~Class();
};

struct A; // incomplete

int main(int, char**)
{
    test_is_not_unsigned<void>();
    test_is_not_unsigned<int&>();
    test_is_not_unsigned<Class>();
    test_is_not_unsigned<int*>();
    test_is_not_unsigned<const int*>();
    test_is_not_unsigned<char[3]>();
    test_is_not_unsigned<char[]>();
    test_is_not_unsigned<int>();
    test_is_not_unsigned<double>();
    test_is_not_unsigned<A>();

    test_is_unsigned<bool>();
    test_is_unsigned<unsigned>();

#ifndef _LIBCPP_HAS_NO_INT128
    test_is_unsigned<__uint128_t>();
    test_is_not_unsigned<__int128_t>();
#endif

  return 0;
}


text:
using namespace IFC4X3;

class MyIfcTreeItem
{
public:
	MyIfcTreeItem() {}
	std::string m_name;
	std::string m_description;
	std::string m_entity_guid;
	std::string m_ifc_class_name;
	std::vector<shared_ptr<MyIfcTreeItem> > m_children;
};

static std::map<std::string, int> mapProgressChars;
class MessageHandler
{
public:
	MessageHandler()
	{

	}

	static void slotMessageWrapper(void* ptr, shared_ptr<StatusCallback::Message> m)
	{
		MessageHandler* myself = (MessageHandler*)ptr;
		if( myself )
		{
			// log file etc can be implemented here
#ifdef IFCPP_OPENMP
			ScopedLock lock(myself->m_mutex_messages);
#endif

			StatusCallback::MessageType mType = m->m_message_type;
			if( mType == StatusCallback::MESSAGE_TYPE_PROGRESS_VALUE )
			{
				std::string progressType = m->m_progress_type;

#ifdef _MSC_VER
				int progressChars = 0;
				if( mapProgressChars.find(progressType) == mapProgressChars.end() )
				{
					mapProgressChars[progressType] = 0;
				}
				else
				{
					progressChars = mapProgressChars[progressType];
				}

				int progressPercent = int(m->m_progress_value * 100);
				for( int ii = 0; ii < progressChars; ++ii )
				{
					std::cout << '\b';
				}

				std::stringstream strs;
				strs << progressPercent << "%";

				mapProgressChars[progressType] = strs.str().size();
				std::cout << strs.str();
#endif
			}
		}
	}

#ifdef IFCPP_OPENMP
	Mutex m_mutex_messages;
#endif
};

shared_ptr<MyIfcTreeItem> resolveTreeItems(shared_ptr<BuildingObject> obj, std::unordered_set<int>& set_visited)
{
	shared_ptr<MyIfcTreeItem> item;

	shared_ptr<IfcObjectDefinition> obj_def = dynamic_pointer_cast<IfcObjectDefinition>(obj);
	if (obj_def)
	{
		if (set_visited.find(obj_def->m_tag) != set_visited.end())
		{
			return nullptr;
		}
		set_visited.insert(obj_def->m_tag);

		item = std::shared_ptr<MyIfcTreeItem>(new MyIfcTreeItem());
		item->m_ifc_class_name = EntityFactory::getStringForClassID(obj_def->classID());

		// access some attributes of IfcObjectDefinition
		if (obj_def->m_GlobalId)
		{
			item->m_entity_guid = obj_def->m_GlobalId->m_value;
		}

		if (obj_def->m_Name)
		{
			item->m_name = obj_def->m_Name->m_value;
		}

		if (obj_def->m_Description)
		{
			item->m_description = obj_def->m_Description->m_value;
		}

		// check if there are child elements of current IfcObjectDefinition
		// child elements can be related to current IfcObjectDefinition either by IfcRelAggregates, or IfcRelContainedInSpatialStructure, see IFC doc
		if (obj_def->m_IsDecomposedBy_inverse.size() > 0)
		{
			// use inverse attribute to navigate to child elements:
			std::vector<weak_ptr<IfcRelAggregates> >& vec_IsDecomposedBy = obj_def->m_IsDecomposedBy_inverse;
			for ( auto it = vec_IsDecomposedBy.begin(); it != vec_IsDecomposedBy.end(); ++it)
			{
				shared_ptr<IfcRelAggregates> rel_agg(*it);
				std::vector<shared_ptr<IfcObjectDefinition> >& vec_related_objects = rel_agg->m_RelatedObjects;
				for (shared_ptr<IfcObjectDefinition> child_obj_def : vec_related_objects)
				{
					shared_ptr<MyIfcTreeItem> child_tree_item = resolveTreeItems(child_obj_def, set_visited);
					if (child_tree_item)
					{
						item->m_children.push_back(child_tree_item);
					}
				}
			}
		}

		shared_ptr<IfcSpatialStructureElement> spatial_ele = dynamic_pointer_cast<IfcSpatialStructureElement>(obj_def);
		if (spatial_ele)
		{
			// use inverse attribute to navigate to child elements:
			std::vector<weak_ptr<IfcRelContainedInSpatialStructure> >& vec_contained = spatial_ele->m_ContainsElements_inverse;
			if (vec_contained.size() > 0)
			{
				for (auto it_rel_contained = vec_contained.begin(); it_rel_contained != vec_contained.end(); ++it_rel_contained)
				{
					shared_ptr<IfcRelContainedInSpatialStructure> rel_contained(*it_rel_contained);
					std::vector<shared_ptr<IfcProduct> >& vec_related_elements = rel_contained->m_RelatedElements;

					for (shared_ptr<IfcProduct> related_product : vec_related_elements)
					{
						shared_ptr<MyIfcTreeItem> child_tree_item = resolveTreeItems(related_product, set_visited);
						if (child_tree_item)
						{
							item->m_children.push_back(child_tree_item);
						}
					}
				}
			}
		}
	}

	return item;
}

int main()
{
	// 1: create an IFC model and a reader for IFC files in STEP format:
	shared_ptr<BuildingModel> ifc_model(new BuildingModel());
	MessageHandler mh;

	shared_ptr<ReaderSTEP> step_reader(new ReaderSTEP());
	step_reader->setMessageCallBack(&mh, &MessageHandler::slotMessageWrapper);

	// 2: load the model:
	std::cout << "Loading IFC model: ";
	step_reader->loadModelFromFile( "example.ifc", ifc_model);

	shared_ptr<GeometryConverter> geometry_converter(new GeometryConverter(ifc_model));
	geometry_converter->setMessageCallBack(&mh, &MessageHandler::slotMessageWrapper);
	shared_ptr<GeometrySettings> geom_settings = geometry_converter->getGeomSettings();

	// the number of vertices per circle can be changed here: (default is 14)
	int numVerticesPerCircle = geom_settings->getNumVerticesPerCircle();
	std::cout << std::endl << "numVerticesPerCircle: " << numVerticesPerCircle << std::endl;
	geom_settings->setNumVerticesPerCircle(numVerticesPerCircle);

	// adjust epsilon for boolean operations
	geometry_converter->setCsgEps(1.5e-9);

	// convert IFC geometry representations to Carve meshes
#ifdef _DEBUG
	GeomDebugDump::clearMeshsetDump();
#endif
	std::cout << "Converting IFC geometry: ";
	geometry_converter->convertGeometry();

	// 3: get a flat map of all loaded IFC entities with geometry:
	const std::map<std::string, shared_ptr<ProductShapeData> >& map_entities = geometry_converter->getShapeInputData();

	for (auto it : map_entities)
	{
		shared_ptr<ProductShapeData> shapeData = it.second;

		shared_ptr<IfcObjectDefinition> ifcObject;
		if( !shapeData->m_ifc_object_definition.expired() )
		{
			ifcObject = shared_ptr<IfcObjectDefinition>(shapeData->m_ifc_object_definition);
		}

		// check for certain type of the entity:
		shared_ptr<IfcRoot> ifc_root = dynamic_pointer_cast<IfcRoot>(ifcObject);
		if (ifc_root)
		{
			// access attributes:
			if (ifc_root->m_GlobalId)
			{
				std::cout << "Entity with GUID: " << ifc_root->m_GlobalId->m_value << std::endl;
			}
		}

		carve::math::Matrix localTransform = shapeData->getTransform();

		// traverse geometry
		for( auto representation : shapeData->m_vec_representations )
		{
			// representation can be a bounding box, text, 2D geometry, or 3D geometry
			for( auto representationItem : representation->m_vec_item_data )
			{
				// closed meshes
				for( auto meshset : representationItem->m_meshsets )
				{
					std::vector<carve::mesh::Vertex<3> >& vertexData = meshset->vertex_storage;
					for( auto mesh : meshset->meshes )
					{
						for( auto face : mesh->faces )
						{
							carve::mesh::Edge<3>* edge = face->edge;
							for( size_t ii = 0; ii < face->n_edges; ++ii )
							{
								carve::mesh::Vertex<3>* vertex = edge->vert;
								carve::geom::vector<3> pointLocal = vertex->v;
								carve::geom::vector<3> pointGlobal = localTransform*pointLocal;
								double x = pointGlobal.x;
								double y = pointGlobal.y;
								double z = pointGlobal.z;
								std::cout << "point in mesh: (" << x << "/" << y << "/" << z << ")" << std::endl;
							}
						}
					}
				}

				// open meshes
				for( auto meshset : representationItem->m_meshsets_open )
				{
					std::vector<carve::mesh::Vertex<3> >& vertexData = meshset->vertex_storage;
					for( auto mesh : meshset->meshes )
					{
						for( auto face : mesh->faces )
						{
							carve::mesh::Edge<3>* edge = face->edge;
							for( size_t ii = 0; ii < face->n_edges; ++ii )
							{
								carve::mesh::Vertex<3>* vertex = edge->vert;
								carve::geom::vector<3> pointLocal = vertex->v;
								carve::geom::vector<3> pointGlobal = localTransform * pointLocal;
								double x = pointGlobal.x;
								double y = pointGlobal.y;
								double z = pointGlobal.z;
								std::cout << "point in mesh: (" << x << "/" << y << "/" << z << ")" << std::endl;
							}
						}
					}
				}
			}
		}

	}

	// 4: traverse tree structure of model, starting at root object (IfcProject)
	shared_ptr<IfcProject> ifc_project = ifc_model->getIfcProject();
	std::unordered_set<int> set_visited;
	shared_ptr<MyIfcTreeItem> root_item = resolveTreeItems(ifc_project, set_visited);

	// you can access the model as a flat map (step 3), or a tree (step 4), depending on your requirements
}


text:
import * as Constants from './constants';
angular.module(Constants.ModuleName, []);

export {validateDirective, ValidateDirectiveController} from './validate-directive';
export {ValidationConfigService} from './validation-config';
export {validationElementDirective} from './validation-element-directive';
export {validatorDirective} from './validator-directive';


text:
@interface FPLocalDaoImpl : PELocalDaoImpl <FPLocalDao>

@end


text:
namespace Envoy {
namespace Api {

SysCallIntResult OsSysCallsImpl::bind(int sockfd, const sockaddr* addr, socklen_t addrlen) {
  const int rc = ::bind(sockfd, addr, addrlen);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::chmod(const std::string& path, mode_t mode) {
  const int rc = ::chmod(path.c_str(), mode);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::ioctl(int sockfd, unsigned long int request, void* argp) {
  const int rc = ::ioctl(sockfd, request, argp);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::close(int fd) {
  const int rc = ::close(fd);
  return {rc, errno};
}

SysCallSizeResult OsSysCallsImpl::writev(int fd, const iovec* iovec, int num_iovec) {
  const ssize_t rc = ::writev(fd, iovec, num_iovec);
  return {rc, errno};
}

SysCallSizeResult OsSysCallsImpl::readv(int fd, const iovec* iovec, int num_iovec) {
  const ssize_t rc = ::readv(fd, iovec, num_iovec);
  return {rc, errno};
}

SysCallSizeResult OsSysCallsImpl::recv(int socket, void* buffer, size_t length, int flags) {
  const ssize_t rc = ::recv(socket, buffer, length, flags);
  return {rc, errno};
}

SysCallSizeResult OsSysCallsImpl::recvmsg(int sockfd, struct msghdr* msg, int flags) {
  const ssize_t rc = ::recvmsg(sockfd, msg, flags);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::ftruncate(int fd, off_t length) {
  const int rc = ::ftruncate(fd, length);
  return {rc, errno};
}

SysCallPtrResult OsSysCallsImpl::mmap(void* addr, size_t length, int prot, int flags, int fd,
                                      off_t offset) {
  void* rc = ::mmap(addr, length, prot, flags, fd, offset);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::stat(const char* pathname, struct stat* buf) {
  const int rc = ::stat(pathname, buf);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::setsockopt(int sockfd, int level, int optname, const void* optval,
                                            socklen_t optlen) {
  const int rc = ::setsockopt(sockfd, level, optname, optval, optlen);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::getsockopt(int sockfd, int level, int optname, void* optval,
                                            socklen_t* optlen) {
  const int rc = ::getsockopt(sockfd, level, optname, optval, optlen);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::socket(int domain, int type, int protocol) {
  const int rc = ::socket(domain, type, protocol);
  return {rc, errno};
}

SysCallSizeResult OsSysCallsImpl::sendmsg(int fd, const msghdr* message, int flags) {
  const int rc = ::sendmsg(fd, message, flags);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::getsockname(int sockfd, sockaddr* addr, socklen_t* addrlen) {
  const int rc = ::getsockname(sockfd, addr, addrlen);
  return {rc, errno};
}

SysCallIntResult OsSysCallsImpl::gethostname(char* name, size_t length) {
  const int rc = ::gethostname(name, length);
  return {rc, errno};
}

} // namespace Api
} // namespace Envoy