text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class io.doov.core.dsl.field.DelegatingFieldInfoImpl (dOOv Core 1.4.10 API)</title>
<meta name="date" content="2018-06-01">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
io.doov.core.dsl.field.DelegatingFieldInfoImpl

Packages that use DelegatingFieldInfoImpl

Package
Description

io.doov.core.dsl.field.types

Uses of DelegatingFieldInfoImpl in io.doov.core.dsl.field.types

Subclasses of DelegatingFieldInfoImpl in io.doov.core.dsl.field.types

Modifier and Type
Class and Description

class
BooleanFieldInfo

class
CharacterFieldInfo

class
DateIsoFieldInfo

class
DoubleFieldInfo

class
EnumFieldInfo<E extends Enum<E>>

class
FloatFieldInfo

class
IntegerFieldInfo

class
IterableFieldInfo<T,C extends Iterable<T>>

class
LocalDateFieldInfo

class
LocalDateTimeFieldInfo

class
LocalTimeFieldInfo

class
LongFieldInfo

class
StringFieldInfo

class
TimeIsoFieldInfo

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2018. All rights reserved.


text:
<rd-widget><rd-widget-body classes=" padding">

          <form ng-submit="editProduct()">

              Nama Produk
              <input type="text" class="form-control" ng-model="postData.product_nama">

              Merk
              <select class="form-control" ng-model="postData.merk_id" ng-options="merk.merk_id as merk.merk_nama for merk in data_merk">
                <option value="">Pilih Merk</option>
              </select>

              Satuan
              <select class="form-control" ng-model="postData.satuan_id" ng-options="satuan.satuan_id as satuan.satuan_nama for satuan in data_satuan">
                <option value="">Pilih Satuan</option>
              </select>

              Harga Eceran
              <input type="text" class="form-control" ng-model="postData.default_price">

              Harga Supplier
              <input type="text" class="form-control" ng-model="postData.supplier_price">

              Stok
              <input type="text" class="form-control" ng-model="postData.stock">

              Minimal Stok
              <input type="text" class="form-control" ng-model="postData.min_stock">

              Keterangan
              <input type="text" class="form-control" ng-model="postData.remarks">

            <button type="submit" class="btn btn-primary btn-lg">Update Produk</button>
            <button type="button" class="btn btn-default btn-lg" onclick="window.history.back()">Kembali</button>
          </form>
      </rd-widget-body>
    </rd-widget>

redpajama_set_name: RedPajamaGithub


text:
package hm

import (
	"fmt"
	"net/url"
	"strconv"
	"time"

	"code.cloudfoundry.org/clock"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/workpool"
	"github.com/cloudfoundry/hm9000/config"
	"github.com/cloudfoundry/hm9000/helpers/metricsaccountant"
	"github.com/cloudfoundry/hm9000/store"
	"github.com/cloudfoundry/storeadapter"
	"github.com/cloudfoundry/storeadapter/etcdstoreadapter"
	"github.com/cloudfoundry/yagnats"
	"github.com/nats-io/nats"

	"os"
)

func buildClock(l lager.Logger) clock.Clock {
	if os.Getenv("HM9000_FAKE_TIME") == "" {
		return clock.NewClock()
	} else {
		timestamp, err := strconv.Atoi(os.Getenv("HM9000_FAKE_TIME"))
		if err != nil {
			l.Error("Failed to load timestamp", err)
			os.Exit(1)
		}
		return NewFixedClock(time.Unix(int64(timestamp), 0))
	}
}

func connectToMessageBus(l lager.Logger, conf *config.Config) yagnats.NATSConn {
	members := make([]string, len(conf.NATS))

	for _, natsConf := range conf.NATS {
		uri := url.URL{
			Scheme: "nats",
			User:   url.UserPassword(natsConf.User, natsConf.Password),
			Host:   fmt.Sprintf("%s:%d", natsConf.Host, natsConf.Port),
		}
		members = append(members, uri.String())
	}

	opts := yagnats.DefaultOptions()
	opts.PingInterval = time.Duration(conf.NatsClientPingInterval) * time.Second

	natsClient, err := yagnats.ConnectWithOptions(members, opts)
	if err != nil {
		l.Error("Failed to connect to the message bus", err)
		os.Exit(1)
	}

	natsClient.AddReconnectedCB(func(conn *nats.Conn) {
		l.Info(fmt.Sprintf("NATS Client Reconnected. Server URL: %s", conn.Opts.Url))
	})

	natsClient.AddClosedCB(func(conn *nats.Conn) {
		err := fmt.Errorf("NATS Client Closed. nats.Conn: %+v", conn)
		l.Error("NATS Closed", err)
		os.Exit(1)
	})

	return natsClient
}

func connectToStoreAdapter(l lager.Logger, conf *config.Config) storeadapter.StoreAdapter {
	var adapter storeadapter.StoreAdapter
	workPool, err := workpool.NewWorkPool(conf.StoreMaxConcurrentRequests)
	if err != nil {
		l.Error("Failed to create workpool", err)
		os.Exit(1)
	}

	var options *etcdstoreadapter.ETCDOptions

	if conf.ETCDRequireSSL {
		options = &etcdstoreadapter.ETCDOptions{
			ClusterUrls: conf.StoreURLs,
			CertFile:    conf.ETCDSSLOptions.CertFile,
			KeyFile:     conf.ETCDSSLOptions.KeyFile,
			CAFile:      conf.ETCDSSLOptions.CACertFile,
			IsSSL:       true,
		}
	} else {
		options = &etcdstoreadapter.ETCDOptions{
			ClusterUrls: conf.StoreURLs,
		}
	}
	options.MaxIdleConns = conf.StoreMaxConcurrentRequests + 5

	adapter, err = etcdstoreadapter.New(options, workPool)
	if err != nil {
		l.Error("Failed to create the store adapter", err)
		os.Exit(1)
	}

	err = adapter.Connect()
	if err != nil {
		l.Error("Failed to connect to the store", err)
		os.Exit(1)
	}

	return adapter
}

func connectToStore(l lager.Logger, conf *config.Config) store.Store {
	adapter := connectToStoreAdapter(l, conf)
	return store.NewStore(conf, adapter, l)
}

func connectToStoreAndTrack(l lager.Logger, conf *config.Config) (store.Store, metricsaccountant.UsageTracker) {
	tracker := newUsageTracker(conf.StoreMaxConcurrentRequests)
	adapter := connectToStoreAdapter(l, conf)
	return store.NewStore(conf, adapter, l), tracker
}

type fixedClock struct {
	now   time.Time
	clock clock.Clock
}

func NewFixedClock(now time.Time) clock.Clock {
	return &fixedClock{
		now:   now,
		clock: clock.NewClock(),
	}
}

func (fixed *fixedClock) Now() time.Time {
	return fixed.now
}

func (fixed *fixedClock) Since(t time.Time) time.Duration {
	return fixed.now.Sub(t)
}

func (fixed *fixedClock) Sleep(d time.Duration) {
	<-fixed.clock.NewTimer(d).C()
}

func (fixed *fixedClock) NewTimer(d time.Duration) clock.Timer {
	return fixed.clock.NewTimer(d)
}

func (fixed *fixedClock) NewTicker(d time.Duration) clock.Ticker {
	return fixed.clock.NewTicker(d)
}


text:
package org.keycloak.testsuite.adapter.page;

import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.keycloak.testsuite.page.AbstractPageWithInjectedUrl;

import java.net.URL;

/**
 *
 * @author tkyjovsk
 */
public class ProductPortal extends AbstractPageWithInjectedUrl {

    public static final String DEPLOYMENT_NAME = "product-portal";

    @ArquillianResource
    @OperateOnDeployment(DEPLOYMENT_NAME)
    private URL url;

    @Override
    public URL getInjectedUrl() {
        return url;
    }

}


text:
layout: page
title: Delta Entertainment Conference
date: 2016-05-24
author: Jerry Glenn
tags: weekly links, java
status: published
summary: Phasellus eu turpis dapibus lorem placerat luctus. Proin id dui.
banner: images/banner/people.jpg
booking:
  startDate: 04/11/2019
  endDate: 04/12/2019
  ctyhocn: BILMTHX
  groupCode: DEC
published: true
---
Nunc sed ipsum lorem. Vestibulum rhoncus nisl vel purus cursus mattis. Cras tristique ligula sit amet aliquam dictum. Pellentesque dui lacus, viverra eget magna eget, consectetur viverra mauris. Ut dapibus massa non tellus pulvinar, eu semper nisi mattis. Aenean euismod in odio a varius. In vehicula felis et est venenatis, ac pulvinar mi finibus. Donec eu orci vestibulum, mollis lectus eu, fermentum erat. Morbi sed augue rhoncus, eleifend erat vitae, convallis arcu.

1 Sed a diam non nisl auctor tincidunt
1 Curabitur rutrum libero quis ultricies consequat
1 Vestibulum pretium velit at neque congue, eu scelerisque tellus convallis.

Praesent mollis felis velit, vitae aliquet risus gravida in. Pellentesque et tincidunt metus. Sed a hendrerit nisi, eget vestibulum eros. Maecenas luctus justo eros, et hendrerit eros placerat ut. In condimentum venenatis dui, quis porta enim imperdiet nec. Sed fringilla leo lorem, et auctor nisi bibendum ac. Nulla placerat eleifend mauris, quis pretium dolor posuere at. Praesent dignissim venenatis purus, in luctus quam vulputate a. Etiam egestas massa nulla, ut mollis libero lobortis eget. In sit amet nunc ultricies, molestie ipsum nec, sollicitudin dui.


text:
module Jetpants
  class DB

    ##### JETCOLLINS MIX-IN ####################################################

    include Plugin::JetCollins

    collins_attr_accessor :slave_weight

    # Because we only support 1 mysql instance per machine for now, we can just
    # delegate this over to the host
    def collins_asset
      @host.collins_asset
    end

    ##### METHOD OVERRIDES #####################################################

    # Add an actual collins check to confirm a machine is a standby
    def is_standby?
      !(running?) || (is_slave? && !taking_connections? && collins_secondary_role == 'standby_slave')
    end

    # Treat any node outside of current data center as being for backups.
    # This prevents inadvertent cross-data-center master promotion.
    def for_backups?
      hostname.start_with?('backup') || in_remote_datacenter?
    end

    ##### CALLBACKS ############################################################

    # Determine master from Collins if machine is unreachable or MySQL isn't running.
    def after_probe_master
      unless @running
        if collins_secondary_role == 'master'
          @master = false
        else
          pool = Jetpants.topology.pool(collins_pool)
          @master = pool.master if pool
        end
      end

      # We completely ignore cross-data-center master unless inter_dc_mode is enabled.
      # This may change in a future Jetpants release, once we support tiered replication more cleanly.
      if @master && @master.in_remote_datacenter? && !Jetpants::Plugin::JetCollins.inter_dc_mode?
        @remote_master = @master # keep track of it, in case we need to know later
        @master = false
      elsif !@master
        in_remote_datacenter? # just calling to cache for current node, before we probe its slaves, so that its slaves don't need to query Collins
      end
    end

    # Determine slaves from Collins if machine is unreachable or MySQL isn't running
    def after_probe_slaves
      # If this machine has a master AND has slaves of its own AND is in another data center,
      # ignore its slaves entirely unless inter_dc_mode is enabled.
      # This may change in a future Jetpants release, once we support tiered replication more cleanly.
      @slaves = [] if @running && @master && @slaves.count > 0 && in_remote_datacenter? && !Jetpants::Plugin::JetCollins.inter_dc_mode?

      unless @running
        p = Jetpants.topology.pool(self)
        @slaves = (p ? p.slaves_according_to_collins : [])
      end
    end

    ##### NEW METHODS ##########################################################

    # Returns true if this database is located in the same datacenter as jetpants_collins
    # has been figured for, false otherwise.
    def in_remote_datacenter?
      @host.collins_location != Plugin::JetCollins.datacenter
    end

    # Returns true if this database is a spare node and looks ready for use, false otherwise.
    # Normally no need for plugins to override this (as of Jetpants 0.8.1), they should
    # override DB#validate_spare instead.
    def usable_spare?
      if @spare_validation_errors.nil?
        @spare_validation_errors = []

        # The order of checks is important -- if the node isn't even reachable by SSH,
        # don't run any of the other checks, for example.
        if available?
          if running?
            @spare_validation_errors << 'Node already has a pool' if pool
            validate_spare
          else
            @spare_validation_errors << 'MySQL is not running'
          end
        else
          @spare_validation_errors << 'Node is not reachable via SSH'
        end

        unless @spare_validation_errors.empty?
          error_text = @spare_validation_errors.join '; '
          output "Removed from spare pool for failing checks: #{error_text}"
        end
      end
      @spare_validation_errors.empty?
    end

    # Performs validation checks on this node to see whether it is a usable spare.
    # The default implementation just ensures a collins status of Allocated and state
    # of SPARE.
    # Downstream plugins may override this to do additional checks to ensure the node is
    # in a sane condition.
    # No need to check whether the node is SSHable, MySQL is running, or not already in
    # a pool -- DB#usable_spare? already does that automatically.
    def validate_spare
      # Confirm node is in Allocated:SPARE status:state. (Because Collins find API hits a
      # search index which isn't synchronously updated with all writes, there's potential
      # for a find call to return assets that just transitioned to a different status or state.)
      status_state = collins_status_state
      @spare_validation_errors << "Unexpected status:state value: #{status_state}" unless status_state == 'allocated:spare'
    end
  end
end


text:
namespace RapidVulkan
{
  namespace Debug
  {
    inline const char* TryToString(const VkOpacityMicromapFormatEXT& value)
    {
      switch(value)
      {
#if VK_HEADER_VERSION >= 231
      case VK_OPACITY_MICROMAP_FORMAT_2_STATE_EXT:
        return "VK_OPACITY_MICROMAP_FORMAT_2_STATE_EXT";
#endif
#if VK_HEADER_VERSION >= 231
      case VK_OPACITY_MICROMAP_FORMAT_4_STATE_EXT:
        return "VK_OPACITY_MICROMAP_FORMAT_4_STATE_EXT";
#endif
      default:
        return nullptr;
      }
    };

    inline const char* ToString(const VkOpacityMicromapFormatEXT& value)
    {
      auto result = TryToString(value);
      return (result != nullptr ? result : "*Unknown*");
    };
  }
}

#endif
#endif


text:
<bill session="110" type="hr" number="704" updated="2009-01-09T09:19:39-05:00">
	<status><vote date="1191553440" datetime="2007-10-04T12:04:00-04:00" where="h" result="pass" how="roll" roll="942"/></status>

	<introduced date="1191297600" datetime="2007-10-02"/>
	<titles>
		<title type="official" as="introduced">Providing for consideration of the bill (H.R. 3246) to amend title 40, United States Code, to provide a comprehensive regional approach to economic and infrastructure development in the most severely economically distressed regions in the Nation.</title>
	</titles>
	<sponsor id="412224"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1191361680" datetime="2007-10-02T18:48:00-04:00"><text>The House Committee on Rules reported an original measure, H. Rept. 110-361, by Mr. Arcuri.</text></action>
		<action date="1191361680" datetime="2007-10-02T18:48:00-04:00"><text>The amendment in the nature of a substitute recommended by the Committee on Transportation and Infrastructure now printed in the bill, modified by the amendment printed in the report of the Committee on Rules accompanying this resolution, shall be considered as adopted.</text></action>
		<calendar date="1191361740" datetime="2007-10-02T18:49:00-04:00" ><text>Placed on the House Calendar, Calendar No. 130.</text></calendar>
		<action date="1191505620" datetime="2007-10-04T10:47:00-04:00"><text>Considered as privileged matter.</text><reference label="consideration" ref="CR H11259-11261"/></action>
		<action date="1191505740" datetime="2007-10-04T10:49:00-04:00"><text>DEBATE - The House proceeded with one hour of debate on H. Res. 704.</text></action>
		<action date="1191506580" datetime="2007-10-04T11:03:00-04:00"><text>POSTPONED PROCEEDINGS - At the conclusion of debate on H.Res. 704, the Chair put the question on ordering the previous question and by voice vote announced that the ayes had prevailed. Mr. Hastings (WA) demanded the yeas and nays and the Chair postponed further proceedings on ordering the previous question until later in the legislative day.</text></action>
		<action date="1191509400" datetime="2007-10-04T11:50:00-04:00"><text>Considered as unfinished business.</text><reference label="consideration" ref="CR H11267-11268"/></action>
		<action date="1191509820" datetime="2007-10-04T11:57:00-04:00"><text>On ordering the previous question Agreed to by the Yeas and Nays: 224 - 194 (Roll no. 941).</text><reference label="consideration" ref="CR H11261, H11267-11268"/></action>
		<vote date="1191553440" how="roll" roll="942" datetime="2007-10-04T12:04:00-04:00" where="h" type="vote" result="pass" ><text>On agreeing to the resolution Agreed to by the Yeas and Nays: 227 - 188 (Roll no. 942).</text><reference label="text" ref="CR H11259"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	10/4/2007--Passed House without amendment. Sets forth the rule for consideration of H.R. 3246 (Regional Economic and Infrastructure Development Act of 2007).<br/>
	</summary>
</bill>


text:
package br.com.autonomiccs.autonomic.administration.algorithms.profilers;

import java.util.List;

import br.com.autonomiccs.autonomic.administration.algorithms.beans.ClusterVmProfile;
import br.com.autonomiccs.autonomic.administration.algorithms.beans.HostProfile;
import br.com.autonomiccs.autonomic.algorithms.commons.beans.HostResources;
import br.com.autonomiccs.autonomic.algorithms.commons.beans.VmResources;

/**
 * This class calculates Hosts and VMs profiles from a cluster, those profiles are used by
 * algorithms from LRG; thus, this class is not necessary for every algorithm. It creates host
 * {@link HostProfile} and cluster profiles {@link ClusterVmProfile}.
 */
public class HostProfiler {

    protected final static int BYTES_TO_MEGA_BYTES = 1000000;
    private List<HostResources> hosts;

    public HostProfiler(List<HostResources> hosts) {
        this.hosts = hosts;
    }

    /**
     * It divides each host resource (number of CPUs, CPU frequency and memory) by cluster's VMs
     * profile for the same resource. Gives a proportion of VMs this host can support.
     *
     * @param host
     * @param vmsProfile
     * @return {@link HostProfile}
     */
    public HostProfile hostVMsResourceProportion(HostResources host) {
        ClusterVmProfile clusterVmsProfile = createClusterVmsProfile(getHostsVmsResources());
        HostProfile hostProfile = new HostProfile();

        hostProfile.setCpusProfile(host.getCpus() / clusterVmsProfile.getCpusProfile());
        hostProfile.setCpuSpeedProfile((host.getSpeed() * host.getCpuOverprovisioning()) / clusterVmsProfile.getCpuSpeedProfile());
        hostProfile.setMemoryProfile(((host.getTotalMemoryInBytes() / BYTES_TO_MEGA_BYTES) * host.getMemoryOverprovisioning()) / clusterVmsProfile.getMemoryProfile());

        return hostProfile;
    }

    /**
     * It calculates the average CPU and memory usage of VMs.
     *
     * @param vmsProfile
     * @return {@link ClusterVmProfile}
     */
    public ClusterVmProfile createClusterVmsProfile(ClusterVmProfile vmsProfile) {
        double numberOfInstances = vmsProfile.getNumberOfInstances();
        vmsProfile.setCpusProfile(vmsProfile.getTotalCpus() / numberOfInstances);
        vmsProfile.setCpuSpeedProfile(vmsProfile.getTotalCpuSpeed() / numberOfInstances);
        vmsProfile.setMemoryProfile(vmsProfile.getTotalMemory() / numberOfInstances);

        return vmsProfile;
    }

    /**
     * It calculates the sum of VMs resources from the list of hosts. It creates a
     * {@link ClusterVmProfile} summing the {@link VmResources}. It contains the number of VMs,
     * number of cpus, the cpu speed and memory size.
     *
     * @return {@link ClusterVmProfile}
     */
    public ClusterVmProfile getHostsVmsResources() {
        ClusterVmProfile vmsProfile = new ClusterVmProfile();
        for(HostResources host : hosts) {
            List<VmResources> vmsOnHost = host.getVmsResources();
            for(VmResources vmResources : vmsOnHost) {
                vmsProfile.setNumberOfInstances(vmsProfile.getNumberOfInstances() + 1);
                vmsProfile.setTotalCpus(vmsProfile.getTotalCpus() + vmResources.getNumberOfCpus());
                vmsProfile.setTotalCpuSpeed((int) (vmsProfile.getTotalCpuSpeed() + vmResources.getCpuSpeed()));
                vmsProfile.setTotalMemory((int) (vmsProfile.getTotalMemory() + vmResources.getMemoryInMegaBytes()));
            }
        }
        return vmsProfile;
    }

}


text:
package org.wso2.carbon.identity.claim.service;

import org.wso2.carbon.identity.claim.exception.ProfileMgtServiceException;
import org.wso2.carbon.identity.claim.mapping.profile.ClaimConfigEntry;
import org.wso2.carbon.identity.claim.mapping.profile.ProfileEntry;

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

/**
 *
 */
public interface ProfileMgtService {

    /**
     * Get the claims set of profiles.
     *
     * @return Map(ProfileName, List of claim entries of the profile) with the set of claims and their
     * properties.
     * @throws ProfileMgtServiceException : Error in getting the profiles.
     */
    Map<String, ProfileEntry> getProfiles() throws ProfileMgtServiceException;

    /**
     * Get the names of available profiles.
     *
     * @return a set with all the available profile names.
     * @throws ProfileMgtServiceException
     */
    Set<String> getProfileNames() throws ProfileMgtServiceException;

    /**
     * Get the claims set of a profile.
     *
     * @param profileName : Uniquely identifying name of the profile.
     * @return ProfileEntry with the set of claims and their properties.
     * @throws ProfileMgtServiceException : Error in getting the profile.
     */
    ProfileEntry getProfile(String profileName) throws ProfileMgtServiceException;

    /**
     * Get the properties of a particular claim of a profile.
     *
     * @param profileName : Uniquely identifying name of the profile.
     * @param claim       : Root claim URI for the properties to be retrieved.
     * @return Map(Property Key : Property Value)
     * @throws ProfileMgtServiceException : Error in getting the properties of a claim.
     */
    ClaimConfigEntry getClaimAttributes(String profileName, String claim) throws ProfileMgtServiceException;

    /**
     * Get the claims marked as required for a particular profile.
     *
     * @param profileName : Uniquely identifying name of the profile.
     * @return List(Root claim URIs)
     * @throws ProfileMgtServiceException : Error in getting the claims with required property.
     */
    List<String> getRequiredClaims(String profileName) throws ProfileMgtServiceException;

    /**
     * Get the claims marked as read-only for a particular profile.
     *
     * @param profileName : Uniquely identifying name of the profile.
     * @return List(Root claim URIs)
     * @throws ProfileMgtServiceException : Error in getting the claims with read-only property.
     */
    List<String> getReadOnlyClaims(String profileName) throws ProfileMgtServiceException;

    /**
     * Get the claims marked as unique for a particular profile.
     *
     * @param profileName : Uniquely identifying name of the profile.
     * @return List(Root claim URIs)
     * @throws ProfileMgtServiceException : Error in getting the claims with unique property.
     */
    List<String> getUniqueClaims(String profileName) throws ProfileMgtServiceException;

    /**
     * Get the claims marked as verify for a particular profile.
     *
     * @param profileName : Uniquely identifying name of the profile.
     * @return List(Root claim URIs)
     * @throws ProfileMgtServiceException : Error in getting the claims with 'verify' property.
     */
    List<String> getVerifyingClaims(String profileName) throws ProfileMgtServiceException;

    /**
     * Get the claims marked as verify with the verifying mechanism for a particular profile.
     *
     * @param profileName : Uniquely identifying name of the profile.
     * @return Map(Claim : Verifying mechanism)
     * @throws ProfileMgtServiceException : Error in getting the claims with verifying mechanism.
     */
    List<String> getValidatingClaims(String profileName) throws ProfileMgtServiceException;

    /**
     * Get the claims marked for regex validations.
     *
     * @param profileName : Uniquely identifying name of the profile.
     * @return Map(Claim : Regex)
     * @throws ProfileMgtServiceException : Error in getting the claims with regex validations.
     */
    List<String> getTransformingClaims(String profileName) throws ProfileMgtServiceException;
}


text:
class Note < ActiveRecord::Base
  belongs_to :noteable, polymorphic: true, counter_cache: true

  validates_presence_of :notes_message, :creator_id, :noteable

  belongs_to :user, foreign_key: :creator_id, counter_cache: true
  validates_associated :user

  NOTEABLES = %w(Grouping Student Assignment)

  def user_can_modify?(current_user)
    current_user.admin? || user == current_user
  end

  def format_date
    I18n.l(created_at, format: :long_date)
  end

  def self.noteables_exist?
    NOTEABLES.each do |classname|
      unless Kernel.const_get(classname).all.empty?
        return true
      end
    end
    false
  end
end


text:
package cn.edu.nju.software.jksc.symys.common.exception;

import cn.edu.nju.software.jksc.symys.common.Bobble;

/**
 * Created by 缪晓伟 on 2015/6/16.
 */
public class CannotMixException extends GameLogicException
{
	private Bobble bobble1,bobble2;

	public CannotMixException(Bobble bobble1,Bobble bobble2)
	{
		this.bobble1=bobble1;
		this.bobble2=bobble2;
	}

	@Override
	public String toString()
	{
		return bobble1+" and "+bobble2+" cannot be mixed!";
	}
}


text:
<?php

namespace Dm\DecimalCalculator\Calculator\BnPhp\Bridge;

class NumberFactory {

    /**
     * Creates a number
     *
     * @param mixed $number
     * @throws \InvalidArgumentException
     * @return Number
     */
    public function createNumber($number)
    {
        if ($this->isValidNumber($number)) {
            if (is_string($number)) {
                $number = trim($number);
            }
            return new Number((string) $number);
        } else {
            throw new \InvalidArgumentException('Argument must be numeric string, int, float, object with __toString');
        }
    }

    /**
     * Checks if arg can be converted to Number object
     *
     * @param mixed $number
     * @return bool
     */
    protected function isValidNumber($number)
    {
        return is_string($number) || is_int($number) || is_float($number)
        || $this->canBeObjectConvertedToString($number);
    }

    /**
     * Checks if object can be converted to string
     *
     * @param mixed $object
     * @return bool
     */
    protected function canBeObjectConvertedToString($object)
    {
        return is_object($object) && method_exists($object, '__toString');
    }

}


text:
Attributes

<variable-race-bonus></variable-race-bonus>{{variableThemeBonus}}{{variableClassBonus}}

score

modifier

upgraded score

upgraded modifier

        = 0">🔑

            STR

{{strScore()}}

={{calcAttribModifier(strScore())}}

+

+

        = 0">🔑

            DEX

{{dexScore()}}

={{calcAttribModifier(dexScore)}}

+

+

        = 0">🔑

            CON

{{conScore()}}

={{calcAttribModifier(conScore())}}

+

+

        = 0">🔑

            INT

{{intScore()}}

={{calcAttribModifier(intScore())}}

+

+

        = 0">🔑

            WIS

{{wisScore()}}

={{calcAttribModifier(wisScore())}}

+

+

        = 0">🔑

            CHA

{{chaScore()}}

={{calcAttribModifier(chaScore())}}

+

+


text:
module.exports = function Reply(){
  this.status = arguments[0] || "ok";
  this.info = arguments[1] || "";
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class gov.nih.nci.cabig.caaers.domain.ajax.StudySiteAjaxableDomainObject
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
gov.nih.nci.cabig.caaers.domain.ajax.StudySiteAjaxableDomainObject

Packages that use StudySiteAjaxableDomainObject

gov.nih.nci.cabig.caaers.domain.ajax

gov.nih.nci.cabig.caaers.domain.repository.ajax

gov.nih.nci.cabig.caaers.web.ae

gov.nih.nci.cabig.caaers.web.study

Uses of StudySiteAjaxableDomainObject in gov.nih.nci.cabig.caaers.domain.ajax

Methods in gov.nih.nci.cabig.caaers.domain.ajax that return types with arguments of type StudySiteAjaxableDomainObject

 java.util.List<StudySiteAjaxableDomainObject>
StudySearchableAjaxableDomainObject.getAssignedStudySites()

          Gets the assigned study sites.

 java.util.List<StudySiteAjaxableDomainObject>
StudySearchableAjaxableDomainObject.getStudySites()

          Gets the study sites.

Methods in gov.nih.nci.cabig.caaers.domain.ajax with parameters of type StudySiteAjaxableDomainObject

 void
StudySearchableAjaxableDomainObject.addAssignedStudySite(StudySiteAjaxableDomainObject studySiteAjaxableDomainObject)

          Adds the assigned study site.

 void
StudySearchableAjaxableDomainObject.addStudySite(StudySiteAjaxableDomainObject studySiteAjaxableDomainObject)

          Adds the study site.

Uses of StudySiteAjaxableDomainObject in gov.nih.nci.cabig.caaers.domain.repository.ajax

Methods in gov.nih.nci.cabig.caaers.domain.repository.ajax that return types with arguments of type StudySiteAjaxableDomainObject

 java.util.List<StudySiteAjaxableDomainObject>
StudySiteAjaxableDomainObjectRepository.findStudySites(StudySiteAjaxableDomainObjectQuery query)

          Find study sites.

Uses of StudySiteAjaxableDomainObject in gov.nih.nci.cabig.caaers.web.ae

Methods in gov.nih.nci.cabig.caaers.web.ae that return types with arguments of type StudySiteAjaxableDomainObject

 java.util.List<StudySiteAjaxableDomainObject>
RoutingAndReviewAjaxFacade.matchSites(java.lang.String text,
           java.lang.Integer studyId)

Uses of StudySiteAjaxableDomainObject in gov.nih.nci.cabig.caaers.web.study

Methods in gov.nih.nci.cabig.caaers.web.study that return types with arguments of type StudySiteAjaxableDomainObject

 java.util.List<StudySiteAjaxableDomainObject>
SearchStudyAjaxFacade.getTableForAssignParticipant(java.util.Map parameterMap,
                             java.lang.String type,
                             java.lang.String text,
                             javax.servlet.http.HttpServletRequest request)

 java.util.List<StudySiteAjaxableDomainObject>
CreateStudyAjaxFacade.matchSites(java.lang.String text,
           java.lang.Integer studyId)

          Retrieves Sites for the autocompleter through AJAX

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
package parser

import (
	"fmt"
	"github.com/awalterschulze/gographviz/ast"
	"github.com/awalterschulze/gographviz/scanner"
	"github.com/awalterschulze/gographviz/token"
	"io"
	"io/ioutil"
	"os"
)

//Parses a DOT string and outputs the
//abstract syntax tree representing the graph.
func ParseString(dotString string) (*ast.Graph, error) {
	return ParseBytes([]byte(dotString))
}

//Parses the bytes representing a DOT string
//and outputs the abstract syntax tree representing the graph.
func ParseBytes(dotBytes []byte) (*ast.Graph, error) {
	lex := &scanner.Scanner{}
	lex.Init(dotBytes, token.DOTTokens)
	parser := NewParser(ActionTable, GotoTable, ProductionsTable, token.DOTTokens)
	st, err := parser.Parse(lex)
	if err != nil {
		return nil, err
	}
	g, ok := st.(*ast.Graph)
	if !ok {
		panic(fmt.Sprintf("Parser did not return an *ast.Graph, but rather a %T", st))
	}
	return g, err
}

//Parses a reader which contains a DOT string
//and outputs the abstract syntax tree representing the graph.
func Parse(r io.Reader) (*ast.Graph, error) {
	bytes, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	return ParseBytes(bytes)
}

//Parses a file which contains a DOT string
//and outputs the abstract syntax tree representing the graph.
func ParseFile(filename string) (*ast.Graph, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	return Parse(f)
}


text:
layout: quickstart
title: Spoken Keywords
navtitle: Spoken Keywords

languages:
- curl

order: 3
---

The Spoken Keywords insight contains track-level data.
track_data is an array containing an object for each track. Each object contains the track_id and track_label of the track, as well as the following:

keywords

Keywords are important terms spoken in the audio.

The keywords list contains objects with:

term - the word

weight - a score which signifies the term's relevance

count - the number of times which the term was spoken

entities (invite only)

Named entities are proper nouns or other entities spoken in the audio. These include people's names, place names, organization names, dates, currency amounts etc.

The entities list contains objects with:

term - the entity

weight - a score which signifies the term's relevance

type - the type of entity

The possible type values are:

person - a person's name. This may be full name or just first or last name

location - a geographical location such as country, state, city, etc.

product - a product or brand name

organization - any type of organization or group

date - a full date or partial date such as a month, a year, a day of the week etc.

money - a monetary value spoken in the audio, for example "100 dollars"

percent - a percentage value spoken in the audio

Sample Response

An example insight:spoken_keywords response:

{% include /source/json/insights_keywords.md %}


text:
package org.apache.commons.net.telnet;

/***
 * JUnit test class for EchoOptionHandler
 * <p>
 * @author Bruno D'Avanzo
 ***/
public class EchoOptionHandlerTest extends TelnetOptionHandlerTestAbstract
{
    /***
     * main for running the test.
     ***/
    public static void main(String args[])
    {
        junit.textui.TestRunner.run(EchoOptionHandlerTest.class);
    }

    /***
     * setUp for the test.
     ***/
    @Override
    protected void setUp()
    {
        opthand1 = new EchoOptionHandler();
        opthand2 = new EchoOptionHandler(true, true, true, true);
        opthand3 = new EchoOptionHandler(false, false, false, false);
    }

    /***
     * test of the constructors.
     ***/
    @Override
    public void testConstructors()
    {
        assertEquals(opthand1.getOptionCode(), TelnetOption.ECHO);
        super.testConstructors();
    }

    /***
     * test of client-driven subnegotiation.
     * Checks that no subnegotiation is made.
     ***/
    @Override
    public void testStartSubnegotiation()
    {
        int resp1[] = opthand1.startSubnegotiationLocal();
        int resp2[] = opthand1.startSubnegotiationRemote();

        assertEquals(resp1, null);
        assertEquals(resp2, null);
    }

    /***
     * test of server-driven subnegotiation.
     * Checks that no subnegotiation is made.
     ***/
    @Override
    public void testAnswerSubnegotiation()
    {
        int subn[] =
        {
            TelnetCommand.IAC, TelnetCommand.SB, TelnetOption.ECHO,
            1, TelnetCommand.IAC, TelnetCommand.SE,
        };

        int resp1[] = opthand1.answerSubnegotiation(subn, subn.length);

        assertEquals(resp1, null);
    }
}


text:
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
   L203 compiler service.
*/
var http = require('http');
var express = require('express')
var app = express();
app.set('port', (process.env.PORT || 5203));
app.use(express.static(__dirname + '/pub'));
app.get('/', function(req, res) {
  res.send("Hello, L203!");
});
var compiler = require("./lib/compile.js");
// Graffiti Code will load the version of itself that matches the graffiti
// version. The compiler should use a version of itself that is compatible
// with the language version. This version object is returned along with
// the result of each /compile.
var version = {
  compiler: "v0.0.0",
  language: "v0.0.0",
  graffiti: "v0.0.0",
};
app.get('/version', function(req, res) {
  res.send(version);
});
app.get('/compile', function(req, res) {
  var data = "";
  req.on("data", function (chunk) {
    data += chunk;
  });
  req.on('end', function () {
    var src = JSON.parse(data).src;
    var obj = compiler.compile(src, function (err, val) {
      if (err.length) {
        res.send({
          error: err,
        });
      } else {
        res.send({
          data: val,
        });
      }
    });
  });
  req.on('error', function(e) {
    console.log(e);
    res.send(e);
  });
});
app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
});
process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
});


text: YUI.add("axis-stacked",function(e,t){e.StackedAxis=e.Base.create("stackedAxis",e.NumericAxis,[e.StackedImpl])},"3.17.0",{requires:["axis-numeric","axis-stacked-base"]});


text:
START_ATF_NAMESPACE
    struct  DispHTMLTableRow : IDispatch
    {
    };
END_ATF_NAMESPACE


text:
package core.kibana;

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

/**
 * @author neo
 */
public class TSVB {
    public String title;
    public String type = "metrics";
    public Params params = new Params();

    public TSVB(String id, String index) {
        title = id;
        params.id = id;
        params.index_pattern = index + "-*";
    }

    public static class Params {
        public String id;
        public String type = "timeseries";
        public String time_field = "@timestamp";
        public String index_pattern;
        public String axis_scale = "normal";
        public String axis_position = "left";
        public int show_legend = 0;
        public int show_grid = 1;
        public List<Series> series = new ArrayList<>();
        public String time_range_mode;
    }

    public static class Series {
        public String id;
        public String label;
        public String color;
        public String split_mode = "everything";
        public String terms_field;
        public String terms_order_by;
        public String split_color_mode;
        public int separate_axis = 0;
        public String axis_position;
        public String formatter = "number";
        public String chart_type = "line";
        public int line_width = 1;
        public int point_size = 1;
        public double fill = 0.5;
        public String value_template;
        public String stacked = "none";
        public List<Metric> metrics = new ArrayList<>();
    }

    public static class Metric {
        public String id;
        public String type;
        public String field;
        public List<Percentile> percentiles;

        public Metric(String type, String field) {
            this.id = type;
            this.type = type;
            this.field = field;
        }
    }

    public static class Percentile {
        public String id;
        public String mode = "line";
        public String value;
        public double shade = 0.2;
        public String percentile = "";

        public Percentile(String value) {
            this.id = value;
            this.value = value;
        }
    }
}


text:
require "spec_helper"

describe GraphQL::Schema::MiddlewareChain do
  let(:step_1) { -> (step_values, next_step) { step_values << 1; next_step.call } }
  let(:step_2) { -> (step_values, next_step) { step_values << 2; next_step.call } }
  let(:step_3) { -> (step_values, next_step) { step_values << 3; :return_value } }
  let(:steps) { [step_1, step_2, step_3] }
  let(:step_values) { [] }
  let(:arguments) { [step_values] }
  let(:middleware_chain) { GraphQL::Schema::MiddlewareChain.new(steps: steps, arguments: arguments)}

  describe "#call" do
    it "runs steps in order" do
      middleware_chain.call
      assert_equal([1,2,3], step_values)
    end

    it "returns the value of the last middleware" do
      assert_equal(:return_value, middleware_chain.call)
    end

    describe "when a step returns early" do
      let(:early_return_step) { -> (step_values, next_step) { :early_return } }
      it "doesn't continue the chain" do
        steps.insert(2, early_return_step)
        assert_equal(:early_return, middleware_chain.call)
        assert_equal([1,2], step_values)
      end
    end

    describe "when a step provides alternate arguments" do
      it "passes the new arguments to the next step" do
        step_1 = -> (test_arg, next_step) { assert_equal(test_arg, 'HELLO'); next_step.call(['WORLD']) }
        step_2 = -> (test_arg, next_step) { assert_equal(test_arg, 'WORLD'); test_arg }

        chain = GraphQL::Schema::MiddlewareChain.new(steps: [step_1, step_2], arguments: ['HELLO'])
        result = chain.call
        assert_equal(result, 'WORLD')
      end
    end
  end
end


text:
using System;
using UIKit;
using Foundation;
using CoreLocation;
using Example_CoreLocation.MainScreen;

namespace Example_CoreLocation
{
	public class MainViewController : UIViewController
	{
		#region -= declarations =-

		MainViewController_iPhone mainViewController_iPhone;
		MainViewController_iPad mainViewController_iPad;

		IMainScreen mainScreen = null;

		// location stuff
		CLLocationManager iPhoneLocationManager = null;
		// uncomment this if you want to use the delegate pattern
		//LocationDelegate locationDelegate = null;

		#endregion

		#region -= constructors =-
		//
		// Constructor invoked from the NIB loader
		//
		public MainViewController (IntPtr p) : base(p)
		{
		}

		public MainViewController () : base()
		{
		}
		#endregion

		public override void ViewDidLoad ()
		{
			// all your base
			base.ViewDidLoad ();

			// load the appropriate view, based on the device type
			this.LoadViewForDevice ();

			// initialize our location manager and callback handler
			iPhoneLocationManager = new CLLocationManager ();

			// uncomment this if you want to use the delegate pattern:
			//locationDelegate = new LocationDelegate (mainScreen);
			//iPhoneLocationManager.Delegate = locationDelegate;

			// you can set the update threshold and accuracy if you want:
			//iPhoneLocationManager.DistanceFilter = 10; // move ten meters before updating
			//iPhoneLocationManager.HeadingFilter = 3; // move 3 degrees before updating

			// you can also set the desired accuracy:
			iPhoneLocationManager.DesiredAccuracy = 1000; // 1000 meters/1 kilometer
			// you can also use presets, which simply evalute to a double value:
			//iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

			// handle the updated location method and update the UI
			if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
				iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
					UpdateLocation (mainScreen, e.Locations [e.Locations.Length - 1]);
				};
			} else {
				#pragma warning disable 618
				// this won't be called on iOS 6 (deprecated)
				iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => {
					UpdateLocation (mainScreen, e.NewLocation);
				};
				#pragma warning restore 618
			}

            //iOS 8 requires you to manually request authorization now - Note the Info.plist file has a new key called requestWhenInUseAuthorization added to.
		    if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
		    {
		        iPhoneLocationManager.RequestWhenInUseAuthorization();
		    }

			// handle the updated heading method and update the UI
			iPhoneLocationManager.UpdatedHeading += (object sender, CLHeadingUpdatedEventArgs e) => {
				mainScreen.LblMagneticHeading.Text = e.NewHeading.MagneticHeading.ToString () + "º";
				mainScreen.LblTrueHeading.Text = e.NewHeading.TrueHeading.ToString () + "º";
			};

			// start updating our location, et. al.
			if (CLLocationManager.LocationServicesEnabled)
				iPhoneLocationManager.StartUpdatingLocation ();
			if (CLLocationManager.HeadingAvailable)
				iPhoneLocationManager.StartUpdatingHeading ();
		}

		static public void UpdateLocation (IMainScreen ms, CLLocation newLocation)
		{
			ms.LblAltitude.Text = newLocation.Altitude.ToString () + " meters";
			ms.LblLongitude.Text = newLocation.Coordinate.Longitude.ToString () + "º";
			ms.LblLatitude.Text = newLocation.Coordinate.Latitude.ToString () + "º";
			ms.LblCourse.Text = newLocation.Course.ToString () + "º";
			ms.LblSpeed.Text = newLocation.Speed.ToString () + " meters/s";

			// get the distance from here to paris
			ms.LblDistanceToParis.Text = (newLocation.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000).ToString() + " km";
		}

		#region -= protected methods =-

		// Loads either the iPad or iPhone view, based on the current device
		protected void LoadViewForDevice()
		{
			// load the appropriate view based on the device
			if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
					mainViewController_iPad = new MainViewController_iPad ();
					this.View.AddSubview (mainViewController_iPad.View);
					mainScreen = mainViewController_iPad as IMainScreen;
			} else {
					mainViewController_iPhone = new MainViewController_iPhone ();
					var b = this.View.Bounds;
					this.View.AddSubview (mainViewController_iPhone.View);
					mainViewController_iPhone.View.Frame = b; // for 4 inch iPhone5 screen
					mainScreen = mainViewController_iPhone as IMainScreen;
			}
		}

		#endregion

		// If you don't want to use events, you could define a delegate to do the
		// updates as well, as shown here.
		public class LocationDelegate : CLLocationManagerDelegate
		{
			IMainScreen ms;

			public LocationDelegate (IMainScreen mainScreen) : base()
			{
				ms = mainScreen;
			}

			// called for iOS6 and later
			public override void LocationsUpdated (CLLocationManager manager, CLLocation[] locations)
			{
				MainViewController.UpdateLocation (ms, locations [locations.Length - 1]);
			}

			public override void UpdatedHeading (CLLocationManager manager, CLHeading newHeading)
			{
				ms.LblMagneticHeading.Text = newHeading.MagneticHeading.ToString () + "º";
				ms.LblTrueHeading.Text = newHeading.TrueHeading.ToString () + "º";
			}
		}
	}
}


text:
using System;
using System.Management.Automation;
using System.Xml.Linq;
namespace PetSerAl.PowerShell.Xml.Linq {
    [Cmdlet(VerbsCommon.New, nameof(XDocument), DefaultParameterSetName = ParameterSetNames.New), OutputType(typeof(XDocument))]
    public sealed class NewXDocumentCmdlet : PSCmdlet {
        public NewXDocumentCmdlet() { }
        [Parameter(ParameterSetName = ParameterSetNames.New, Position = 1)]
        public XDeclaration Declaration { private get; set; }
        [Parameter(ParameterSetName = ParameterSetNames.New, ValueFromRemainingArguments = true)]
        public object Content { private get; set; }
        [Parameter(Mandatory = true, ParameterSetName = ParameterSetNames.Parse)]
        public string Text { private get; set; }
        [Parameter(Mandatory = true, ParameterSetName = ParameterSetNames.Load)]
        public string Uri { private get; set; }
        [Parameter(ParameterSetName = ParameterSetNames.Parse, Position = 1), Parameter(ParameterSetName = ParameterSetNames.Load, Position = 1)]
        public LoadOptions Options { private get; set; }
        [Parameter(Mandatory = true, ParameterSetName = ParameterSetNames.Copy, Position = 1)]
        public XDocument Other { private get; set; }
        protected override void BeginProcessing() {
            XDocument result;
            switch(ParameterSetName) {
                case ParameterSetNames.New:
                    result=new XDocument(Declaration, Utility.UnwrapPSObjects(Content));
                    break;
                case ParameterSetNames.Parse:
                    result=XDocument.Parse(Text, Options);
                    break;
                case ParameterSetNames.Load:
                    result=XDocument.Load(Uri, Options);
                    break;
                case ParameterSetNames.Copy:
                    result=new XDocument(Other);
                    break;
                default:
                    throw new Exception("Invalid ParameterSetName.");
            }
            WriteObject(result);
        }
    }
}


text:
import argparse
import os
import imp
import gevent
from .mail import SSLEmail

def read_sample_config(filename='sample-config.py'):
    """
    Read the sample config
    """
    filename = os.path.dirname(__file__) + os.path.sep + filename
    try:
        with open(filename) as f:
            for line in f.readlines():
                print(line.split('\n')[0])
    except IOError:
        raise IOError("Sample file not found")

def valid_config(config):
    for item in config.config:
        if not ('username' in item and 'password' in item and 'host' in item and 'service' in item and 'path' in item):
            return False
    return True

def read_config_file(filepath):
    """
    Read configuration file and return details.
    Configuration file should be python file.
    """
    if os.path.exists(filepath):
        filename = os.path.join(filepath)
        if filename.endswith(".py"):
            try:
                d = imp.load_source("config", filepath)
                return d
            except Exception, e:
                raise Exception(e.msg)
    else:
        raise IOError("Path %s doesn't exist" % (filepath))

def main():
    """
    Main entry for command line application
    """
    parser = argparse.ArgumentParser(
        description="Maildir configuration details")
    parser.add_argument('-config', type=unicode, help='config file path which should be python file')
    parser.add_argument('-format', action='store_true', default='py', help='print sample config file')
    args = parser.parse_args()
    if args.config is None and args.format is not True:
        print(parser.format_help())
    elif args.config:
        config = read_config_file(args.config)
        if valid_config(config):
            emails = [SSLEmail(config=c) for c in config.config]
            try:
                # Concurrency
                jobs = [gevent.spawn(email.run_forever) for email in emails]
                gevent.joinall(jobs)
            except (KeyboardInterrupt, SystemExit):
                print("Shutting down")
        else:
            print("config file is out of format")
            print(read_sample_config())
    elif args.format:
        read_sample_config()

if __name__ == "__main__":
    main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YapperChat.Common;
using YapperChat.Controls.Interactions;
using YapperChat.Database;
using YapperChat.Sync;

namespace YapperChat.Models
{
    class TaskMessageCreator<T> : IItemManager<T> where T : class, IItem
    {
        public bool HasChanged
        {
            get;
            set;
        }

        public bool IsDeleted
        {
            get;
            set;
        }

        public T CreateItem()
        {
            T task;
            if (typeof(T).Equals(typeof(MessageModel)))
            {
                MessageModel message = new MessageModel();
                message.MessageId = Guid.NewGuid();
                message.ClientMessageId = Guid.NewGuid();
                message.TaskName = null;
                message.Sender = UserSettingsModel.Instance.Me;
                message.SenderId = UserSettingsModel.Instance.Me.Id;
                message.TaskItemList = new ObservableSortedList<MessageModel>(4, new TaskListComparer<MessageModel>());
                message.MessageType = MessageType.Message;
                message.MessageFlags = MessageFlags.Task;
                message.PostDateTimeUtcTicks = DateTime.UtcNow.Ticks;
                message.LastReadTime = new DateTime(1970, 1, 1);
                message.LastUpdateTime = DateTime.Now;
                message.LastTaskUpdaterId = UserSettingsModel.Instance.Me.Id;

                DataSync.Instance.CreateTask(message);
                task = message as T;
            }
            else
            {
                task = Activator.CreateInstance<T>();
            }

            return task;
        }

        public void CompleteItem(T item)
        {
            item.IsCompleted = true;
            if (typeof(T).Equals(typeof(MessageModel)))
            {
                MessageModel message = item as MessageModel;
                if (message == null)
                {
                    return;
                }

                using (DataContextWrapper<YapperDataContext> context = new DataContextWrapper<YapperDataContext>())
                {
                    List<MessageModel> taskList = new List<MessageModel>(message.TaskItemList);
                    foreach (MessageModel taskItem in taskList)
                    {
                        context.Attach<MessageModel>(taskItem);
                        taskItem.IsCompleted = true;
                    }

                    context.Attach<MessageModel>(message);
                    message.IsCompleted = true;
                    context.SubmitChanges();

                    if (message.Recipient != null)
                    {
                        this.SendChanges(message);
                    }
                }
            }
        }

        public void DeleteItem(T item)
        {
            if (typeof(T).Equals(typeof(MessageModel)))
            {
                MessageModel message = item as MessageModel;
                if (message == null)
                {
                    return;
                }

                using (DataContextWrapper<YapperDataContext> context = new DataContextWrapper<YapperDataContext>())
                {
                    if (message.TaskItemList != null)
                    {
                        foreach (MessageModel taskItem in message.TaskItemList)
                        {
                            context.Attach<MessageModel>(taskItem);
                            context.DeleteOnSubmit<MessageModel>(taskItem);
                        }
                    }

                    var existingQuery = from m in context.Table<MessageModel>()
                                        where m.MessageId == message.MessageId
                                        select m;

                    MessageModel existing = existingQuery.FirstOrDefault();

                    if (existing != null)
                    {
                        context.DeleteOnSubmit<MessageModel>(existing);
                    }

                    context.SubmitChanges();
                    // send a message only if it is shared
                    if (message.Recipient != null)
                    {
                        this.SendChanges(message, true);
                    }
                }
            }
        }

        public void SetItemOrder(T itemToSet, T itemBefore, T itemAfter, bool save = false)
        {
            return;
        }

        public string GetItemOrder(T itemBefore, T itemAfter)
        {
            string beforeLabel = null;
            string afterLabel = null;

            if (itemBefore != null)
            {
                beforeLabel = itemBefore.ItemOrder;
            }

            if (itemAfter != null)
            {
                afterLabel = itemAfter.ItemOrder;
            }

            return TaskMessageCreator<T>.CalculateItemOrder(beforeLabel, afterLabel);
        }

        private void SendChanges(MessageModel m, bool isDeleted = false)
        {
            MessageModel clone = m.Clone() as MessageModel;
            if (isDeleted)
            {
                clone.IsTaskDeleted = true;
                clone.TaskItemList = null;
            }

            if (clone.IsGroup)
            {
                clone.Sender = UserSettingsModel.Instance.Me;
                clone.SenderId = clone.Sender.Id;
            }

            if (clone.RecipientId == UserSettingsModel.Instance.Me.Id)
            {
                clone.Recipient = m.Sender;
                clone.RecipientId = clone.Recipient.Id;
                clone.Sender = UserSettingsModel.Instance.Me;
                clone.SenderId = clone.Sender.Id;
            }

            if (clone.Recipient != null)
            {
                DataSync.Instance.SendMessage(clone);
            }
        }

        public static string CalculateItemOrder(string beforeLabel, string afterLabel)
        {
            if (string.IsNullOrEmpty(beforeLabel) && string.IsNullOrEmpty(afterLabel))
            {
                int label = (int)Math.Ceiling(((double)(Int32.MaxValue - 0)) / 2);

                return label.ToString("D10");
            }

            if (string.IsNullOrEmpty(beforeLabel))
            {
                string[] afterNumbers = afterLabel.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                int afterNumber = Int32.Parse(afterNumbers[0]);

                int label = (int)Math.Ceiling(((double)(afterNumber - 0)) / 2);
                return label.ToString("D10");
            }

            if (string.IsNullOrEmpty(afterLabel))
            {
                string[] beforeNumbers = beforeLabel.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                int beforeNumber = Int32.Parse(beforeNumbers[0]);

                int label = (int)Math.Ceiling(beforeNumber + ((double)(Int32.MaxValue - beforeNumber)) / 2);
                return label.ToString("D10");
            }

            string[] after= afterLabel.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string[] before = beforeLabel.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            int i = 0;

            while (i < after.Count() &&
                   i < before.Count() &&
                   Int32.Parse(before[i]) == Int32.Parse(after[i]))
            {
                i++;
            }

            int newNumber = 0;
            int ithBefore = 0;
            int ithAfter = 0;
            if (i >= after.Count())
            {
                ithAfter = Int32.MaxValue;
                ithBefore = Int32.Parse(before[i]);
            }
            else if (i >= before.Count())
            {
                ithAfter = Int32.Parse(after[i]);
                ithBefore = 0;
            }
            else if (Int32.Parse(before[i]) + 1 == Int32.Parse(after[i]))
            {
                i++;
                ithBefore = (i == after.Count()) ? 0 : Int32.Parse(before[i]);
                ithAfter = (i == after.Count()) ? Int32.MaxValue : Int32.Parse(after[i]);
            }
            else
            {
                ithBefore = Int32.Parse(before[i]);
                ithAfter = Int32.Parse(after[i]);
            }

            newNumber = (int)Math.Ceiling(ithBefore + ((double)(ithAfter - ithBefore)) / 2);

            StringBuilder newLabel = new StringBuilder();

            for (int j = 0; j < i; j++)
            {
                newLabel.Append(before[j]);
                newLabel.Append(";");
            }

            newLabel.Append(newNumber.ToString("D10"));

            return newLabel.ToString();
        }
    }
}


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

 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you 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.

-->

<executionPlan name="AverageHeathRequest" statistics="disable"
  trace="enable" xmlns="http://wso2.org/carbon/eventprocessor">
  <description>This will average health stats of an instance over a minute.</description>
  <siddhiConfiguration>
    <property name="siddhi.enable.distributed.processing">RedundantNode</property>
    <property name="siddhi.persistence.snapshot.time.interval.minutes">0</property>
  </siddhiConfiguration>
  <importedStreams>
    <stream as="health_avg_processsor" name="cartridge_agent_health_stats" version="1.0.0"/>
  </importedStreams>
  <queryExpressions><![CDATA[
 	from health_avg_processsor [health_description == 'ports_not_open']
		select cluster_id, cluster_instance_id, network_partition_id, member_id, partition_id insert into fault_message;
	from health_avg_processsor
  		select cluster_id, cluster_instance_id, network_partition_id, member_id, partition_id, health_description, value,
		stratos:concat(cluster_id, '-' , cluster_instance_id) as health_grad_cluster_network
  		insert into health_avg_concatinator;
  	define partition health_avg_cluster_partition by   health_avg_concatinator.health_grad_cluster_network;
  	define partition member_health_avg_cluster_partition by  health_avg_processsor.member_id;
  	from health_avg_concatinator [health_description == 'load_average']
		#window.timeBatch(1 min) select cluster_id, cluster_instance_id, network_partition_id, avg(value) as average_load_average, stratos:now() as timestamp
		insert into average_load_average_stats
		partition by health_avg_cluster_partition;
  	from health_avg_processsor [health_description == 'load_average']
		#window.timeBatch(1 min) select member_id, cluster_id, cluster_instance_id, network_partition_id, avg(value) as member_average_load_average, stratos:now() as timestamp
		insert into member_average_load_average_stats
		partition by member_health_avg_cluster_partition;
  	from health_avg_processsor [health_description == 'memory_consumption']
		#window.timeBatch(1 min) select member_id, cluster_id, cluster_instance_id, network_partition_id, avg(value) as member_average_memory_consumption, stratos:now() as timestamp
		insert into member_average_memory_consumption_stats
		partition by member_health_avg_cluster_partition;
  	from health_avg_concatinator [health_description == 'memory_consumption']
		#window.timeBatch(1 min) select cluster_id, cluster_instance_id, network_partition_id, avg(value) as average_memory_consumption, stratos:now() as timestamp
		insert into average_memory_consumption_stats
		partition by health_avg_cluster_partition;
  ]]></queryExpressions>
  <exportedStreams>
    <stream name="average_load_average_stats" passthroughFlow="disable"
      valueOf="average_load_average_stats" version="1.0.0"/>
    <stream name="member_average_load_average_stats" passthroughFlow="disable"
      valueOf="member_average_load_average_stats" version="1.0.0"/>
    <stream name="member_average_memory_consumption_stats" passthroughFlow="disable"
      valueOf="member_average_memory_consumption_stats" version="1.0.0"/>
    <stream name="average_memory_consumption_stats" passthroughFlow="disable"
      valueOf="average_memory_consumption_stats" version="1.0.0"/>
    <stream name="fault_message" passthroughFlow="disable"
      valueOf="fault_message" version="1.0.0"/>
  </exportedStreams>
</executionPlan>


text:
class SketchfabsController < ApplicationController
  before_action :set_sketchfab, only: [:show, :edit, :update, :destroy]
  before_action :require_admin!, only: [:destroy]
  before_action :authenticate_user!, except: [:show, :index]
  before_action :set_reconstruction, only: [:new, :create, :update]

  def new
    @sketchfab = @reconstruction.sketchfabs.build
  end

  def create
    if @reconstruction.sketchfabs.create(sketchfab_params)
      redirect_to location_reconstruction_path(@reconstruction.location, @reconstruction)
    else

    end
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_sketchfab
    @sketchfab = Sketchfab.find(params[:id])
  end

  def set_reconstruction
    @reconstruction = Reconstruction.friendly.find(params[:reconstruction_id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def sketchfab_params
    params.require(:sketchfab).permit(:bbcode).merge(user_id: current_user.id)
  end
end


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" />
<meta property="og:title" content="David Brown" />
<meta name="twitter:title" content="David Brown"/>
<meta itemprop="name" content="David Brown"><meta property="og:description" content="David has spent the last two years working for Red Hat on Openstack deployments for private cloud solutions, and have run into some amazing problems and integration issues with different software used to manage different resources. You never know what is going to trip you up. Talking to storage solutions, integrating a directory solution, integrating with a network vendor, meeting security auditing and compliance requirements. So often those parts of a project are not fully scoped and don't have the time or resources to resolve the interaction of those items." />
  <meta name="twitter:description" content="David has spent the last two years working for Red Hat on Openstack deployments for private cloud solutions, and have run into some amazing problems and integration issues with different software used to manage different resources. You never know what is going to trip you up. Talking to storage solutions, integrating a directory solution, integrating with a network vendor, meeting security auditing and compliance requirements. So often those parts of a project are not fully scoped and don't have the time or resources to resolve the interaction of those items." />
  <meta itemprop="description" content="David has spent the last two years working for Red Hat on Openstack deployments for private cloud solutions, and have run into some amazing problems and integration issues with different software used to manage different resources. You never know what is going to trip you up. Talking to storage solutions, integrating a directory solution, integrating with a network vendor, meeting security auditing and compliance requirements. So often those parts of a project are not fully scoped and don't have the time or resources to resolve the interaction of those items."><meta name="twitter:site" content="@devopsdays">
<meta property="og:type" content="speaker" />
<meta property="og:url" content="/events/2017-dallas/speakers/david-brown/" /><meta name="twitter:creator" content="@devopsdaysdfw" /><meta name="twitter:label1" value="Event" />
  <meta name="twitter:data1" value="devopsdays Dallas 2017" /><meta name="twitter:label2" value="Dates" />
    <meta name="twitter:data2" value="August 28 - 30, 2017" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="223">
<title>David Brown - devopsdays Dallas 2017
</title>

<link href="/css/site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

      <link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" />
      <link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" />

  DevOpsDays

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

events

blog

sponsor

speaking

organizing

about

  Dallas
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2">

</button>

                  propose

                  location

                  program

                  registration

                  speakers

                  sponsor

                  contact

                  conduct

David Brown

David has spent the last two years working for Red Hat on Openstack deployments for private cloud solutions, and have run into some amazing problems and integration issues with different software used to manage different resources. You never know what is going to trip you up. Talking to storage solutions, integrating a directory solution, integrating with a network vendor, meeting security auditing and compliance requirements. So often those parts of a project are not fully scoped and don't have the time or resources to resolve the interaction of those items.

As a am Senior Platform Consultant at Red Hat, David has over 20 years of experience in the IT, software, and manufacturing industries. He has worked as a Senior Linux Engineer for ViaWest Inc, and worked as the UNIX and Storage systems team lead for 12 years for DaVita Inc, prior to Red Hat. He has had responsibility for architecture and design review of systems put into the production environments, as well as done project management, with mentoring and training of support staff.

Highlights of relevant Red Hat professional experience include the following. Deployment of Openstack director has been the primary focus of the customers he has worked with since July of 2015. The deployments include OSP7, OSP8, OSP9, and OSP10, and also involved building and supporting Satellite, RHEV, KVM, IDM, and RHEL.

David Brown at Dallas 2017

                Openstack and DevOps / What you don't want in your infrastructure templates

Location & Platinum Sponsors

Platinum Sponsors

Gold Sponsors

Silver Sponsors
Join as Silver Sponsor!

Workshop Sponsors
Join as Workshop Sponsor!

Media Sponsors
Join as Media Sponsor!

Community Sponsors

@DEVOPSDAYS

BLOG

10 years of devopsdays

by Kris Buytaert - 10 May, 2019

It’s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery.
Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.

Blogs

10 May, 2019

Feed

CFP OPEN
Campinas
Macapá
Shanghai
Recife
Charlotte
Prague
Tokyo
Salt Lake City

Propose a talk at an event near you!

About

    devopsdays is a worldwide community conference series for anyone interested in IT improvement.

    About devopsdays

    Privacy Policy

    Code of Conduct


text:
<?php namespace App\Http\Controllers;

use App\Http\Requests\CreatePageRequest as CreateRequest;
use App\Http\Requests\CreatePageRequest as UpdateRequest;
use App\Page as Model;

class PageController extends ResourceController
{
	/**
	 * Class constructor.
	 *
	 * @param  Model
	 * @return void
	 */
	public function __construct(Model $resource)
	{
		parent::__construct($resource);
		$this->setEagerLoadedRelationships('category');
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		// Make sure resource exists
		$this->resource = $this->resource->findOrFail($id);
		$this->subtitle = $this->resource;

		return parent::show($id);
	}

	/**
	 * Create a new resource.
	 *
	 * @param  CreateRequest
	 * @return Response
	 */
	public function store(CreateRequest $request)
	{
		return parent::_store($request);
	}

	/**
	 * Update an exsiting resource.
	 *
	 * @param  UpdateRequest
	 * @param  int $id
	 * @return Response
	 */
	public function update(UpdateRequest $request, $id)
	{
		return parent::_update($request, $id);
	}

	/**
	 * Display a form for saving a resource.
	 *
	 * @param  string $subtitle Page subtitle.
	 * @param  string $action   Form route sufix.
	 * @param  string $method   Form method.
	 * @return Response
	 */
	protected function showForm($subtitle, $action, $method = 'POST')
	{
		view()->share('categories', \App\Category::dropdown());

		return parent::showForm($subtitle, $action, $method);
	}

	/**
	 * Get the 'return to index' URL.
	 *
	 * @return string
	 */
	protected function getReturnUrl()
	{
		if($this->resource->category and $this->resource->category->getKey())
			return route('category.show', [$this->resource->category->getKey()]);

		return parent::getReturnUrl();
	}
}


text:
declare -a JDKS_DIRECTORIES_TO_REMOVE=()

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# OS X

if [ "$TRAVIS_OS_NAME" = "osx" ]; then

    # Install `ShellCheck` (required for testing)
    brew install shellcheck

    # To better simulate a clean macOS install, remove certain things
    # included by default by Travis CI with brew
    brew cask uninstall java6
    brew cask uninstall java7
    brew cask uninstall java

    # Export directory where Java binaries are located in linux
    JDKS_DIRECTORIES_TO_REMOVE=(
        /Library/Java/JavaVirtualMachines/*.jdk
    )

fi

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# To better simulate a clean OS install, remove certain things
# included by default by Travis CI

rm -rf "$NVM_DIR"
for i in "${JDKS_DIRECTORIES_TO_REMOVE[@]}"; do
    sudo rm -rf "${i}"
done


text:
using LR.WebUI.Infrastructure;
using SX.WebCore.MvcControllers;

namespace LR.WebUI.Areas.Admin.Controllers
{
    public sealed class UserRolesController : SxUserRolesController
    {

    }
}


text:
package aspguidc.helper;

import aspguidc.exception.parsing.InvalidIdentifierFormatException;
import aspguidc.exception.parsing.InvalidPropertyTypeException;
import com.google.gson.JsonElement;

import java.util.regex.Pattern;

/**
 * Helper class which provides static methods regarding to the handling of json elements.
 */
public class JsonHelper {
    /**
     * Throw a {@link InvalidPropertyTypeException} if the given property value is not of the type string.
     *
     * @param objectName    name of the parent object of the property which is passed to the exception
     * @param propertyName  name of the property which is passed to the exception
     * @param propertyValue value which is checked
     * @throws InvalidPropertyTypeException
     */
    public static void assertPropertyIsString(String objectName, String propertyName, JsonElement propertyValue) throws InvalidPropertyTypeException {
        if (!propertyValue.isJsonPrimitive() || !propertyValue.getAsJsonPrimitive().isString()) {
            throw new InvalidPropertyTypeException(objectName, propertyName, "string");
        }
    }

    /**
     * Throw a {@link InvalidPropertyTypeException} if the given property value is not of the type integer.
     *
     * @param objectName    name of the parent object of the property which is passed to the exception
     * @param propertyName  name of the property which is passed to the exception
     * @param propertyValue value which is checked
     * @throws InvalidPropertyTypeException
     */
    public static void assertPropertyIsInteger(String objectName, String propertyName, JsonElement propertyValue) throws InvalidPropertyTypeException {
        if (!propertyValue.isJsonPrimitive() || !propertyValue.getAsJsonPrimitive().isNumber()) {
            throw new InvalidPropertyTypeException(objectName, propertyName, "integer");
        }
    }

    /**
     * Throw a {@link InvalidIdentifierFormatException} if the given identifier is not a valid identifier.
     *
     * @param objectName name of the object assigned to the identifier which is passed to the exception
     * @param identifier identifier which is checked
     * @throws InvalidIdentifierFormatException
     */
    public static void assertIdentifierIsValid(String objectName, String identifier) throws InvalidIdentifierFormatException {
        if (!Pattern.matches("^[a-z][a-zA-Z0-9_]+$", identifier)) {
            throw new InvalidIdentifierFormatException(objectName, identifier);
        }
    }
}


text:
package com.cisco.db;

import com.cisco.api.Note;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;

import java.util.List;

@RegisterMapper(NotesMapper.class)
public interface NotesDao {
    @SqlUpdate("insert into notes (note) values (:note)")
    @GetGeneratedKeys
    long insert(@Bind("note") String note);

    @SqlQuery("select * from notes order by creationDate DESC")
    List<Note> findAll();
}


text:
import { pick, forEach, omit } from '../src/index';
import { map } from '../src/common/common';

const stateProps = ['resolve', 'resolvePolicy', 'data', 'template', 'templateUrl', 'url', 'name', 'params'];

const initialUrl = document.location.href;
export const resetBrowserUrl = () => history.replaceState(null, null, initialUrl);

export const delay = ms => new Promise<any>(resolve => setTimeout(resolve, ms));
export const _delay = ms => () => delay(ms);

export function tree2Array(tree, inheritName) {
  function processState(parent, state, name) {
    const substates: any = omit(state, stateProps);
    const thisState: any = pick(state, stateProps);
    thisState.name = name;
    if (!inheritName) thisState.parent = parent;

    return [thisState].concat(processChildren(thisState, substates));
  }

  function processChildren(parent, substates) {
    let states = [];
    forEach(substates, function(value, key) {
      if (inheritName && parent.name) key = `${parent.name}.${key}`;
      states = states.concat(processState(parent, value, key));
    });
    return states;
  }

  return processChildren('', tree);
}

export function PromiseResult(promise?) {
  let self = this,
    _promise: Promise<any>;
  let resolve, reject, complete;

  this.setPromise = function(promise) {
    if (_promise) {
      throw new Error("Already have with'd a promise.");
    }

    const onfulfilled = data => (resolve = data || true);
    const onrejected = err => (reject = err || true);
    const done = () => (complete = true);

    _promise = promise;
    _promise
      .then(onfulfilled)
      .catch(onrejected)
      .then(done, done);
  };

  this.get = () => ({ resolve: resolve, reject: reject, complete: complete });

  this.called = () => map(self.get(), (val, key) => val !== undefined);

  if (promise) {
    this.setPromise(promise);
  }
}

export const awaitTransition = router =>
  new Promise(resolve => {
    const dereg = router.transitionService.onSuccess({}, trans => {
      dereg();
      resolve(trans);
    });
  });


text:
//
//  DrawerViewController.h
//  Drawer
//
//  Created by 侯宝伟 on 15/10/6.
//  Copyright © 2015年 ZHUNJIEE. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface DrawerViewController : UIViewController

/** 左视图 */
@property (nonatomic, weak, readonly) UIView *leftView;
/** 右视图 */
@property (nonatomic, weak, readonly) UIView *rightView;
/** 主视图 */
@property (nonatomic, weak, readonly) UIView *mainView;

@end


text:
package ca

import (
	"bytes"
	"context"
	"fmt"
	"reflect"
	"sync"
	"time"

	"github.com/cloudflare/cfssl/helpers"
	"github.com/moby/swarmkit/v2/api"
	"github.com/moby/swarmkit/v2/api/equality"
	"github.com/moby/swarmkit/v2/log"
	"github.com/moby/swarmkit/v2/manager/state/store"
	"github.com/pkg/errors"
)

// IssuanceStateRotateMaxBatchSize is the maximum number of nodes we'll tell to rotate their certificates in any given update
const IssuanceStateRotateMaxBatchSize = 30

func hasIssuer(n *api.Node, info *IssuerInfo) bool {
	if n.Description == nil || n.Description.TLSInfo == nil {
		return false
	}
	return bytes.Equal(info.Subject, n.Description.TLSInfo.CertIssuerSubject) && bytes.Equal(info.PublicKey, n.Description.TLSInfo.CertIssuerPublicKey)
}

var errRootRotationChanged = errors.New("target root rotation has changed")

// rootRotationReconciler keeps track of all the nodes in the store so that we can determine which ones need reconciliation when nodes are updated
// or the root CA is updated.  This is meant to be used with watches on nodes and the cluster, and provides functions to be called when the
// cluster's RootCA has changed and when a node is added, updated, or removed.
type rootRotationReconciler struct {
	mu                  sync.Mutex
	clusterID           string
	batchUpdateInterval time.Duration
	ctx                 context.Context
	store               *store.MemoryStore

	currentRootCA    *api.RootCA
	currentIssuer    IssuerInfo
	unconvergedNodes map[string]*api.Node

	wg     sync.WaitGroup
	cancel func()
}

// IssuerFromAPIRootCA returns the desired issuer given an API root CA object
func IssuerFromAPIRootCA(rootCA *api.RootCA) (*IssuerInfo, error) {
	wantedIssuer := rootCA.CACert
	if rootCA.RootRotation != nil {
		wantedIssuer = rootCA.RootRotation.CACert
	}
	issuerCerts, err := helpers.ParseCertificatesPEM(wantedIssuer)
	if err != nil {
		return nil, errors.Wrap(err, "invalid certificate in cluster root CA object")
	}
	if len(issuerCerts) == 0 {
		return nil, errors.New("invalid certificate in cluster root CA object")
	}
	return &IssuerInfo{
		Subject:   issuerCerts[0].RawSubject,
		PublicKey: issuerCerts[0].RawSubjectPublicKeyInfo,
	}, nil
}

// assumption:  UpdateRootCA will never be called with a `nil` root CA because the caller will be acting in response to
// a store update event
func (r *rootRotationReconciler) UpdateRootCA(newRootCA *api.RootCA) {
	issuerInfo, err := IssuerFromAPIRootCA(newRootCA)
	if err != nil {
		log.G(r.ctx).WithError(err).Error("unable to update process the current root CA")
		return
	}

	var (
		shouldStartNewLoop, waitForPrevLoop bool
		loopCtx                             context.Context
	)
	r.mu.Lock()
	defer func() {
		r.mu.Unlock()
		if shouldStartNewLoop {
			if waitForPrevLoop {
				r.wg.Wait()
			}
			r.wg.Add(1)
			go r.runReconcilerLoop(loopCtx, newRootCA)
		}
	}()

	// check if the issuer has changed, first
	if reflect.DeepEqual(&r.currentIssuer, issuerInfo) {
		r.currentRootCA = newRootCA
		return
	}
	// If the issuer has changed, iterate through all the nodes to figure out which ones need rotation
	if newRootCA.RootRotation != nil {
		var nodes []*api.Node
		r.store.View(func(tx store.ReadTx) {
			nodes, err = store.FindNodes(tx, store.All)
		})
		if err != nil {
			log.G(r.ctx).WithError(err).Error("unable to list nodes, so unable to process the current root CA")
			return
		}

		// from here on out, there will be no more errors that cause us to have to abandon updating the Root CA,
		// so we can start making changes to r's fields
		r.unconvergedNodes = make(map[string]*api.Node)
		for _, n := range nodes {
			if !hasIssuer(n, issuerInfo) {
				r.unconvergedNodes[n.ID] = n
			}
		}
		shouldStartNewLoop = true
		if r.cancel != nil { // there's already a loop going, so cancel it
			r.cancel()
			waitForPrevLoop = true
		}
		loopCtx, r.cancel = context.WithCancel(r.ctx)
	} else {
		r.unconvergedNodes = nil
	}
	r.currentRootCA = newRootCA
	r.currentIssuer = *issuerInfo
}

// assumption:  UpdateNode will never be called with a `nil` node because the caller will be acting in response to
// a store update event
func (r *rootRotationReconciler) UpdateNode(node *api.Node) {
	r.mu.Lock()
	defer r.mu.Unlock()
	// if we're not in the middle of a root rotation ignore the update
	if r.currentRootCA == nil || r.currentRootCA.RootRotation == nil {
		return
	}
	if hasIssuer(node, &r.currentIssuer) {
		delete(r.unconvergedNodes, node.ID)
	} else {
		r.unconvergedNodes[node.ID] = node
	}
}

// assumption:  DeleteNode will never be called with a `nil` node because the caller will be acting in response to
// a store update event
func (r *rootRotationReconciler) DeleteNode(node *api.Node) {
	r.mu.Lock()
	delete(r.unconvergedNodes, node.ID)
	r.mu.Unlock()
}

func (r *rootRotationReconciler) runReconcilerLoop(ctx context.Context, loopRootCA *api.RootCA) {
	defer r.wg.Done()
	for {
		r.mu.Lock()
		if len(r.unconvergedNodes) == 0 {
			r.mu.Unlock()

			err := r.store.Update(func(tx store.Tx) error {
				return r.finishRootRotation(tx, loopRootCA)
			})
			if err == nil {
				log.G(r.ctx).Info("completed root rotation")
				return
			}
			log.G(r.ctx).WithError(err).Error("could not complete root rotation")
			if err == errRootRotationChanged {
				// if the root rotation has changed, this loop will be cancelled anyway, so may as well abort early
				return
			}
		} else {
			var toUpdate []*api.Node
			for _, n := range r.unconvergedNodes {
				iState := n.Certificate.Status.State
				if iState != api.IssuanceStateRenew && iState != api.IssuanceStatePending && iState != api.IssuanceStateRotate {
					n = n.Copy()
					n.Certificate.Status.State = api.IssuanceStateRotate
					toUpdate = append(toUpdate, n)
					if len(toUpdate) >= IssuanceStateRotateMaxBatchSize {
						break
					}
				}
			}
			r.mu.Unlock()

			if err := r.batchUpdateNodes(toUpdate); err != nil {
				log.G(r.ctx).WithError(err).Errorf("store error when trying to batch update %d nodes to request certificate rotation", len(toUpdate))
			}
		}

		select {
		case <-ctx.Done():
			return
		case <-time.After(r.batchUpdateInterval):
		}
	}
}

// This function assumes that the expected root CA has root rotation.  This is intended to be used by
// `reconcileNodeRootsAndCerts`, which uses the root CA from the `lastSeenClusterRootCA`, and checks
// that it has a root rotation before calling this function.
func (r *rootRotationReconciler) finishRootRotation(tx store.Tx, expectedRootCA *api.RootCA) error {
	cluster := store.GetCluster(tx, r.clusterID)
	if cluster == nil {
		return fmt.Errorf("unable to get cluster %s", r.clusterID)
	}

	// If the RootCA object has changed (because another root rotation was started or because some other node
	// had finished the root rotation), we cannot finish the root rotation that we were working on.
	if !equality.RootCAEqualStable(expectedRootCA, &cluster.RootCA) {
		return errRootRotationChanged
	}

	var signerCert []byte
	if len(cluster.RootCA.RootRotation.CAKey) > 0 {
		signerCert = cluster.RootCA.RootRotation.CACert
	}
	// we don't actually have to parse out the default node expiration from the cluster - we are just using
	// the ca.RootCA object to generate new tokens and the digest
	updatedRootCA, err := NewRootCA(cluster.RootCA.RootRotation.CACert, signerCert, cluster.RootCA.RootRotation.CAKey,
		DefaultNodeCertExpiration, nil)
	if err != nil {
		return errors.Wrap(err, "invalid cluster root rotation object")
	}
	cluster.RootCA = api.RootCA{
		CACert:     cluster.RootCA.RootRotation.CACert,
		CAKey:      cluster.RootCA.RootRotation.CAKey,
		CACertHash: updatedRootCA.Digest.String(),
		JoinTokens: api.JoinTokens{
			Worker:  GenerateJoinToken(&updatedRootCA, cluster.FIPS),
			Manager: GenerateJoinToken(&updatedRootCA, cluster.FIPS),
		},
		LastForcedRotation: cluster.RootCA.LastForcedRotation,
	}
	return store.UpdateCluster(tx, cluster)
}

func (r *rootRotationReconciler) batchUpdateNodes(toUpdate []*api.Node) error {
	if len(toUpdate) == 0 {
		return nil
	}
	err := r.store.Batch(func(batch *store.Batch) error {
		// Directly update the nodes rather than get + update, and ignore version errors.  Since
		// `rootRotationReconciler` should be hooked up to all node update/delete/create events, we should have
		// close to the latest versions of all the nodes.  If not, the node will updated later and the
		// next batch of updates should catch it.
		for _, n := range toUpdate {
			if err := batch.Update(func(tx store.Tx) error {
				return store.UpdateNode(tx, n)
			}); err != nil && err != store.ErrSequenceConflict {
				log.G(r.ctx).WithError(err).Errorf("unable to update node %s to request a certificate rotation", n.ID)
			}
		}
		return nil
	})
	return err
}


text:
Recognitation and transformation procedures for boolean functions written in Go.

## Installation
First you have to install [lpsolve](http://lpsolve.sourceforge.net/) (the linear program solver) and the Go bindings for lpsolve. Due to copyright problems lpsolve is not shipped with boolrecognition. You can find the installation instructions [here](https://github.com/draffensperger/golp/). After this just use `go get github.com/FabianWe/boolrecognition/...` and then build the binary with `go build cmd/benchmarklpb/benchmarklpb.go` (from the directory `FabianWe/boolrecognition`).

## Usage
Currenty benchmarklp accepts text files where each line contains an LPB in the format:
First all the coefficients are separated by a space, then the threshold follows, also separated by a space.

So the LPB 2 ⋅ x1 + 1 ⋅ x2 + 1 ⋅ x3 ≥ 2 is represented by "2 1 1 2".

You can find benchmarks [here](https://github.com/FabianWe/lpb_benchmarks).  Example:

    ./benchmarklpb -lpb lpb_benchmarks/full/lpb/full_6.lpb -verify

(adjust the path to the lpb file). This uses the combinatorial solver (known to be not complete). To use the linear program solver use

    ./benchmarklpb -lpb lpb_benchmarks/full/lpb/full_6.lpb -verify -solver lp

For more options see `./benchmarklpb -help`.


text:
<?php
/**
 * Team template config helpers.
 */

// File Security Check
if ( ! defined( 'ABSPATH' ) ) { exit; }

////////////////////////
// TEAM POST SETTINGS //
////////////////////////

if ( ! function_exists( 'presscore_populate_team_config' ) ) :

	function presscore_populate_team_config( $target_post_id = 0 ) {

		global $post;

		if ( $target_post_id ) {
			$post_id = $target_post_id;

		} elseif ( $post && !empty( $post->ID ) ) {
			$post_id = $post->ID;

		} else {
			return false;

		}

		$config = Presscore_Config::get_instance();
		$prefix = '_dt_teammate_options_';

		// open as
		$open_as = get_post_meta( $post_id, "{$prefix}go_to_single", true );
		$config->set( 'post.open_as', ( $open_as ? 'post' : 'none' ) );

		// position
		$config->set( 'post.member.position', get_post_meta( $post_id, "{$prefix}position", true ), '' );

		// links
		$teammate_links = presscore_get_team_links_array();
		$links = array();
		foreach ( $teammate_links as $id=>$data ) {
			$link = get_post_meta( $post_id, "{$prefix}{$id}", true );
			if ( $link ) {
				$links[ $id ] = $link;
			}
		}
		$config->set( 'post.preview.links', $links, array() );

		return true;
	}

endif;

///////////////////
// TEAM TEMPLATE //
///////////////////

if ( ! function_exists( 'presscore_congif_populate_team_vars' ) ) :

	function presscore_congif_populate_team_vars() {

		$config = presscore_config();
		$post_id = $config->get( 'post_id' );

		$prefix = '_dt_team_options_';

		// for categorizer compatibility
		if ( ! $config->get('order') ) {
			$config->set( 'order', get_post_meta( $post_id, "{$prefix}order", true ) );
		}

		if ( ! $config->get('orderby') ) {
			$config->set( 'orderby', get_post_meta( $post_id, "{$prefix}orderby", true ) );
		}

		$config->set( 'display', get_post_meta( $post_id, "_dt_team_display", true ) );

		////////////////////
		// Image sizing //
		////////////////////

		$config->set( 'image_layout', get_post_meta( $post_id, "{$prefix}image_layout", true ) );
		$config->set( 'thumb_proportions', get_post_meta( $post_id, "{$prefix}thumb_proportions", true ) );

		$config->set( 'show_excerpts', get_post_meta( $post_id, "{$prefix}show_exerpts", true ) );

		//////////////
		// Layout //
		//////////////

		$config->set( 'layout', get_post_meta( $post_id, "{$prefix}masonry_layout", true ) );
		$config->set( 'full_width', get_post_meta( $post_id, "{$prefix}full_width", true ) );

		$config->set( 'posts_per_page', get_post_meta( $post_id, "{$prefix}ppp", true ) );
		$config->set( 'post.preview.description.style', 'under_image' );

		///////////////////
		// Items style //
		///////////////////

		$config->set( 'item_padding', get_post_meta( $post_id, "{$prefix}item_padding", true ), 20 );
		$config->set( 'post.preview.width.min', get_post_meta( $post_id, "{$prefix}target_width", true ), 370 );
		$config->set( 'template.columns.number', get_post_meta( $post_id, "{$prefix}columns_number", true ), 3 );
		$config->set( 'post.preview.background.enabled', get_post_meta( $post_id, "{$prefix}bg_under_posts", true ) );
	}

endif;