text:
import {DateTimeObject, getDiffInMinutes, TWO_WEEKS} from 'app/components/charts/utils';
import {t} from 'app/locale';
import {GlobalSelection, NewQuery, Organization} from 'app/types';
import {escapeDoubleQuotes} from 'app/utils';
import {getUtcDateString} from 'app/utils/dates';
import EventView from 'app/utils/discover/eventView';
import {getAggregateAlias, WebVital} from 'app/utils/discover/fields';
import {formatVersion} from 'app/utils/formatters';
import {QueryResults, stringifyQueryObject} from 'app/utils/tokenizeSearch';
import {WEB_VITAL_DETAILS} from 'app/views/performance/transactionVitals/constants';

import {EventType, YAxis} from './releaseChartControls';

export function getInterval(datetimeObj: DateTimeObject) {
  const diffInMinutes = getDiffInMinutes(datetimeObj);

  if (diffInMinutes > TWO_WEEKS) {
    return '6h';
  } else {
    return '1h';
  }
}

export function getReleaseEventView(
  selection: GlobalSelection,
  version: string,
  yAxis?: YAxis,
  eventType?: EventType,
  organization?: Organization,
  /**
   * Indicates that we're only interested in the current release.
   * This is useful for the event meta end point where we don't want
   * to include the other releases.
   */
  currentOnly?: boolean
): EventView {
  const {projects, environments, datetime} = selection;
  const {start, end, period} = datetime;
  const releaseFilter = currentOnly ? `release:${version}` : '';
  const toOther = `to_other(release,"${escapeDoubleQuotes(version)}",others,current)`;
  // this orderby ensures that the order is [others, current]
  const toOtherAlias = getAggregateAlias(toOther);

  const baseQuery: Omit<NewQuery, 'query'> = {
    id: undefined,
    version: 2,
    name: `${t('Release')} ${formatVersion(version)}`,
    fields: [`count()`, toOther],
    orderby: toOtherAlias,
    range: period,
    environment: environments,
    projects,
    start: start ? getUtcDateString(start) : undefined,
    end: end ? getUtcDateString(end) : undefined,
  };

  switch (yAxis) {
    case YAxis.FAILED_TRANSACTIONS:
      const statusFilters = ['ok', 'cancelled', 'unknown'].map(
        s => `!transaction.status:${s}`
      );
      return EventView.fromSavedQuery({
        ...baseQuery,
        query: stringifyQueryObject(
          new QueryResults(
            ['event.type:transaction', releaseFilter, ...statusFilters].filter(Boolean)
          )
        ),
      });
    case YAxis.COUNT_LCP:
    case YAxis.COUNT_DURATION:
      const column =
        yAxis === YAxis.COUNT_DURATION ? 'transaction.duration' : 'measurements.lcp';
      const threshold =
        yAxis === YAxis.COUNT_DURATION
          ? organization?.apdexThreshold
          : WEB_VITAL_DETAILS[WebVital.LCP].failureThreshold;
      return EventView.fromSavedQuery({
        ...baseQuery,
        query: stringifyQueryObject(
          new QueryResults(
            [
              'event.type:transaction',
              releaseFilter,
              threshold ? `${column}:>${threshold}` : '',
            ].filter(Boolean)
          )
        ),
      });
    case YAxis.EVENTS:
      if (organization?.features?.includes('release-performance-views')) {
        const eventTypeFilter = eventType === 'all' ? '' : `event.type:${eventType}`;
        return EventView.fromSavedQuery({
          ...baseQuery,
          query: stringifyQueryObject(
            new QueryResults([releaseFilter, eventTypeFilter].filter(Boolean))
          ),
        });
      } else {
        // TODO(tonyx): Delete this else once the feature flags are removed
        return EventView.fromSavedQuery({
          ...baseQuery,
          fields: ['title', 'count()', 'event.type', 'issue', 'last_seen()'],
          query: stringifyQueryObject(
            new QueryResults([`release:${version}`, '!event.type:transaction'])
          ),
          orderby: '-last_seen',
        });
      }
    default:
      return EventView.fromSavedQuery({
        ...baseQuery,
        fields: ['title', 'count()', 'event.type', 'issue', 'last_seen()'],
        query: stringifyQueryObject(
          new QueryResults([`release:${version}`, '!event.type:transaction'])
        ),
        orderby: '-last_seen',
      });
  }
}


text:
import ns from 'ima/namespace';

ns.namespace('app.base');

/**
 * Base class for Resource.
 * @class Resource
 * @namespace app.base
 * @module app.base
 *
 * @requires ima.http.HttpAgent
 */
export default class Resource {

	/**
	 * @method constructor
	 * @constructor
	 * @param {ima.http.HttpAgent} http
	 * @param {string} url - API URL (Base server + api specific path.)
	 * @param {app.base.EntityFactory} entityFactory
	 * @param {ima.cache.Cache} cache
	 */
	constructor(http, url, entityFactory, cache) {

		/**
		 * Handler for HTTP requests.
		 *
		 * @property _http
		 * @private
		 * @type {ima.http.HttpAgent}
		 */
		this._http = http;

		/**
		 * API URL for specific resource.
		 *
		 * @property _apiUrl
		 * @private
		 * @type {string}
		 */
		this._apiUrl = url;

		/**
		 * Cache for caching parts of request response.
		 *
		 * @property _cache
		 * @private
		 * @type {ima.cache.Cache}
		 */
		this._cache = cache;

		/**
		 * Factory for creating entities.
		 *
		 * @property _entityFactory
		 * @private
		 * @type {app.base.EntityFactory}
		 */
		this._entityFactory = entityFactory;

		/**
		 * @property _defaultOptions
		 * @type {Object<string, number>}
		 * @default { ttl: 3600000, timeout: 2000, repeatRequest: 1 }
		 * */
		this._defaultOptions = { ttl: 3600000, timeout: 2000, repeatRequest: 1 };

	}

	/**
	 * Gets 1 entity from http and returns Entity.
	 *
	 * @method getEntity
	 * @param {String} [id=null] ID for get entity from API.
	 * @param {Object} [data={}]
	 * @param {Object} [options={}] Possible keys { ttl: {number}(in ms), timeout: {number}(in ms), repeatRequest: {number} }
	 * @param {Boolean} [force=false] Forces request, doesn't use cache.
	 * @return {Array<app.base.BaseEntity>}
	 */
	getEntity(id = null, data = {}, options = {}, force = false) {
		var url = this._getUrl(id);
		options = this._getOptions(options);

		if (force) {
			this._clearCacheForRequest(url, data);
		}

		return this._http
			.get(url, data, options)
			.then((result) => {
				return this._entityFactory.createEntityList(result.body);
			}, (error) => {
				throw error;
			});
	}

	/**
	 * Posts data to http and returns new Entity.
	 *
	 * @method createEntity
	 * @param {Object} [data={}]
	 * @param {Object} [options={}] Possible keys { ttl: {number}(in ms), timeout: {number}(in ms), repeatRequest: {number} }
	 * @return {app.base.BaseEntity}
	 */
	createEntity(data = {}, options = {}) {
		var url = this._getUrl();
		options = this._getOptions(options);

		return this._http
			.post(url, data, options)
			.then((result) => {
				return this._entityFactory.createEntity(result.body);
			}, (error) => {
				throw error;
			});
	}

	/**
	 * Return request url.
	 *
	 * @method _getUrl
	 * @private
	 * @param {String} [id=null]
	 * @return {String}
	 */
	_getUrl(id = null) {
		var url = this._apiUrl;

		if (id) {
			url += '/' + id;
		}

		return url;
	}

	/**
	 * Return request options.
	 *
	 * @method _getOptions
	 * @private
	 * @param {Object} options
	 * @return {Object}
	 */
	_getOptions(options) {
		return Object.assign(this._defaultOptions, options);
	}

	/**
	 * Clear data in cache for request.
	 *
	 * @method _clearCacheForRequest
	 * @param {String} url
	 * @param {Object} data
	 */
	_clearCacheForRequest(url, data) {
		var cacheKey = this._http.getCacheKey(url, data);
		this._cache.delete(cacheKey);
	}
}

ns.app.base.Resource = Resource;

redpajama_set_name: RedPajamaGithub


text:
//
//  SACalendarConstants.h
//  SACalendar
//
//  User Interface constants. Customize your calendar here.
//
//  Created by Nop Shusang on 7/14/14.
//  Copyright (c) 2014 SyncoApp. All rights reserved.
//
//  Distributed under MIT License

#import <Foundation/Foundation.h>

/**
 *  Constants. Do not change
 */
#define MAX_MONTH 12
#define MIN_MONTH 1
#define MAX_CELL 42
#define DESELECT_ROW -1
#define DAYS_IN_WEEK 7
#define MAX_WEEK 6

/**
 *  Calendar's proportion
 */
#define calendarToHeaderRatio 7
#define headerFontRatio 0.4
#define pagingHeaderFontRatio 0.6

#define cellFontRatio 0.3
#define labelToCellRatio 0.7
#define circleToCellRatio 0.8

#define TITLE_MONTH_LABEL_HEIGHT_PAGING 25.0
#define TITLE_WEEKDAY_LABELS_HEIGHT 25.0

/**
 * Font sizes
 */
#define MONTH_NAME_FONT_SIZE 12.0
#define WEEK_DAY_FONT_SIZE 11.0

/**
 * Calendar colors
 */

// There are 3 layered views in SACalendar, the default UIView, the scroll view, and the collection view.
// Change their colors here

#define viewBackgroundColor [UIColor whiteColor]
#define scrollViewBackgroundColor [UIColor whiteColor]
#define calendarBackgroundColor [UIColor whiteColor]

#define headerTextColor [UIColor redColor]

#define titleBackgroundColor [UIColor colorWithRed:250./255. green:250./255 blue:250./255 alpha:1];

/**
 *  Cell properties
 */

// All cells
#define cellFont [UIFont systemFontOfSize:desiredFontSize * cellFontRatio]
#define cellBoldFont [UIFont boldSystemFontOfSize:desiredFontSize * cellFontRatio]

#define cellBackgroundColor [UIColor whiteColor]
#define cellTopLineColor [UIColor lightGrayColor]

#define dateTextColor [UIColor blackColor]

// Current date's cell
#define currentDateCircleColor [UIColor blackColor]
#define currentDateCircleLineWidth 2

// Selected date's cell
#define selectedDateCircleColor [UIColor blackColor]
#define selectedDateCircleLineWidth 1

/*
 * Loading states for infinite scroll view is to load the scroll view on the left (previous) first
 * then load the scroll view on the right (next) and finally load the scroll view in the middle (current)
 */
typedef enum {LOADSTATESTART = -1, LOADSTATEPREVIOUS = 0, LOADSTATENEXT, LOADSTATECURRENT} SALoadStates;

/*
 * Since we are reusing the scroll views, we need to define the three possible scroll views' positions
 * Assuming that the scroll views are called 0,1,2 then the three states are
 * 0 1 2, 2 0 1 and 1 2 0
 */
typedef enum {SCROLLSTATE_120 = 0, SCROLLSTATE_201 = 1, SCROLLSTATE_012} SAScrollStates;

/**
 *  Scroll view's scroll direction
 */
typedef enum {ScrollDirectionHorizontal = 0, ScrollDirectionVertical = 1} SAScrollDirection;

/**
* Calendar event types to be highlighted with different background images
* Event types can be renamed and added here
*
* Use the bit shift operator for further events (1 << 2, 1 << 3, and so on)
* and add them to SACalendarEventAll using the binary OR operator
* to be able to assign multiple events to the same date
*/
typedef enum {
    SACalendarEventType1 = 1 << 0,
    SACalendarEventType2 = 1 << 1,
    SACalendarEventAll = SACalendarEventType1 | SACalendarEventType2
} SACalendarEventType;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProtoBuf;

namespace OsEngine.Market.Servers.Livecoin.LivecoinEntity
{
    //public class Info
    //{
    //    public string name { get; set; }
    //    public string symbol { get; set; }
    //    public string walletStatus { get; set; }
    //    public string withdrawFee { get; set; }
    //    public string difficulty { get; set; }
    //    public string minDepositAmount { get; set; }
    //    public string minWithdrawAmount { get; set; }
    //    public string minOrderAmount { get; set; }
    //}

    //public class BalancesInfo
    //{
    //    public bool success { get; set; }
    //    public string minimalOrderBTC { get; set; }
    //    public List<Info> info { get; set; }

    //    public RestrictionSecurities Restriction;
    //}

    public class Restriction
    {
        public string currencyPair { get; set; }
        public string priceScale { get; set; }
        public string minLimitQuantity { get; set; }
    }

    public class RestrictionSecurities
    {
        public bool success { get; set; }
        public string minBtcVolume { get; set; }
        public List<Restriction> restrictions { get; set; }
    }

    public class Balance
    {
        public string type { get; set; }
        public string currency { get; set; }
        public string value { get; set; }
    }

    public class BalanceInfo
    {
        public string Name { get; set; }
        public List<Balance> Balances { get; set; }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Septoria evansi Syd.

### Remarks
null


text:
import os
import json
import requests
from test import CollectorTestCase
from test import get_collector_config
from test import unittest

from diamond.collector import Collector
from fluentd import FluentdCollector

dirname = os.path.dirname(__file__)
fixtures_path = os.path.join(dirname, 'fixtures/')

class TestFluentdCollector(CollectorTestCase):

    def setUp(self):
        config = get_collector_config('FluentdCollector', {
            'interval': 10,
            'collect': {
                'kinesis': [
                    'buffer_queue_length',
                    'buffer_total_queued_size',
                    'retry_count'
                    ]
                }
        })

        self.collector = FluentdCollector(config, None)

    def test_import(self):
        self.assertTrue(FluentdCollector)

    def test_api_output_parse(self):
        f = open(os.path.join(fixtures_path, "example.stat")).read()
        stat = json.loads(f)
        self.assertTrue(len(self.collector.parse_api_output(stat)) is 3)

    def test_api_output_parse_empty(self):
        f = open(os.path.join(fixtures_path, "example_empty.stat")).read()
        stat = json.loads(f)
        self.assertTrue(len(self.collector.parse_api_output(stat)) is 0)

if __name__ == "__main__":
    unittest.main()


text:
from ply import lex

class Lexer(object):
    reserved = {
        # Top level fields
        "SPDXVersion": "DOC_VERSION",
        "DataLicense": "DOC_LICENSE",
        "DocumentName": "DOC_NAME",
        "SPDXID": "SPDX_ID",
        "DocumentComment": "DOC_COMMENT",
        "DocumentNamespace": "DOC_NAMESPACE",
        "ExternalDocumentRef": "EXT_DOC_REF",
        # Creation info
        "Creator": "CREATOR",
        "Created": "CREATED",
        "CreatorComment": "CREATOR_COMMENT",
        "LicenseListVersion": "LIC_LIST_VER",
        # Review info
        "Reviewer": "REVIEWER",
        "ReviewDate": "REVIEW_DATE",
        "ReviewComment": "REVIEW_COMMENT",
        # Annotation info
        "Annotator": "ANNOTATOR",
        "AnnotationDate": "ANNOTATION_DATE",
        "AnnotationComment": "ANNOTATION_COMMENT",
        "AnnotationType": "ANNOTATION_TYPE",
        "SPDXREF": "ANNOTATION_SPDX_ID",
        # Relationships
        "Relationship": "RELATIONSHIP",
        "RelationshipComment": "RELATIONSHIP_COMMENT",
        # Package Fields
        "PackageName": "PKG_NAME",
        "PackageVersion": "PKG_VERSION",
        "PackageDownloadLocation": "PKG_DOWN",
        "FilesAnalyzed": "PKG_FILES_ANALYZED",
        "PackageSummary": "PKG_SUM",
        "PackageSourceInfo": "PKG_SRC_INFO",
        "PackageFileName": "PKG_FILE_NAME",
        "PackageSupplier": "PKG_SUPPL",
        "PackageOriginator": "PKG_ORIG",
        "PackageChecksum": "PKG_CHKSUM",
        "PackageVerificationCode": "PKG_VERF_CODE",
        "PackageDescription": "PKG_DESC",
        "PackageComment": "PKG_COMMENT",
        "PackageLicenseDeclared": "PKG_LICS_DECL",
        "PackageLicenseConcluded": "PKG_LICS_CONC",
        "PackageLicenseInfoFromFiles": "PKG_LICS_FFILE",
        "PackageLicenseComments": "PKG_LICS_COMMENT",
        "PackageCopyrightText": "PKG_CPY_TEXT",
        "PackageHomePage": "PKG_HOME",
        "ExternalRef": "PKG_EXT_REF",
        "ExternalRefComment": "PKG_EXT_REF_COMMENT",
        "PackageAttributionText": "PKG_ATTRIBUTION_TEXT",
        "PrimaryPackagePurpose": "PRIMARY_PACKAGE_PURPOSE",
        "BuiltDate": "BUILT_DATE",
        "ReleaseDate": "RELEASE_DATE",
        "ValidUntilDate": "VALID_UNTIL_DATE",
        # Files
        "FileName": "FILE_NAME",
        "FileType": "FILE_TYPE",
        "FileChecksum": "FILE_CHKSUM",
        "LicenseConcluded": "FILE_LICS_CONC",
        "LicenseInfoInFile": "FILE_LICS_INFO",
        "FileCopyrightText": "FILE_CR_TEXT",
        "LicenseComments": "FILE_LICS_COMMENT",
        "FileComment": "FILE_COMMENT",
        "FileNotice": "FILE_NOTICE",
        "FileContributor": "FILE_CONTRIB",
        "FileDependency": "FILE_DEP",
        "ArtifactOfProjectName": "ART_PRJ_NAME",
        "ArtifactOfProjectHomePage": "ART_PRJ_HOME",
        "ArtifactOfProjectURI": "ART_PRJ_URI",
        "FileAttributionText": "FILE_ATTRIBUTION_TEXT",
        # License
        "LicenseID": "LICS_ID",
        "ExtractedText": "LICS_TEXT",
        "LicenseName": "LICS_NAME",
        "LicenseCrossReference": "LICS_CRS_REF",
        "LicenseComment": "LICS_COMMENT",
        # Snippet
        "SnippetSPDXID": "SNIPPET_SPDX_ID",
        "SnippetName": "SNIPPET_NAME",
        "SnippetComment": "SNIPPET_COMMENT",
        "SnippetCopyrightText": "SNIPPET_CR_TEXT",
        "SnippetLicenseComments": "SNIPPET_LICS_COMMENT",
        "SnippetFromFileSPDXID": "SNIPPET_FILE_SPDXID",
        "SnippetLicenseConcluded": "SNIPPET_LICS_CONC",
        "LicenseInfoInSnippet": "SNIPPET_LICS_INFO",
        "SnippetAttributionText": "SNIPPET_ATTRIBUTION_TEXT",
        "SnippetByteRange": "SNIPPET_BYTE_RANGE",
        "SnippetLineRange": "SNIPPET_LINE_RANGE",
        # Common
        "NOASSERTION": "NO_ASSERT",
        "UNKNOWN": "UN_KNOWN",
        "NONE": "NONE",
        "SOURCE": "SOURCE",
        "BINARY": "BINARY",
        "ARCHIVE": "ARCHIVE",
        "APPLICATION": "APPLICATION",
        "AUDIO": "AUDIO",
        "IMAGE": "IMAGE",
        "VIDEO": "VIDEO",
        "DOCUMENTATION": "DOCUMENTATION",
        "SPDX": "SPDX",
        "OTHER": "OTHER",
        "REVIEW": "REVIEW",
        "FRAMEWORK": "FRAMEWORK",
        "LIBRARY": "LIBRARY",
        "CONTAINER": "CONTAINER",
        "OPERATING-SYSTEM": "OPERATING_SYSTEM",
        "DEVICE": "DEVICE",
        "FIRMWARE": "FIRMWARE",
        "FILE": "FILE",
        "INSTALL": "INSTALL"
    }
    states = (("text", "exclusive"),)

    tokens = [
        "TEXT",
        "TOOL_VALUE",
        "UNKNOWN_TAG",
        "ORG_VALUE",
        "PERSON_VALUE",
        "DATE",
        "LINE",
        "RANGE",
        "CHKSUM",
        "DOC_REF_ID",
        "DOC_URI",
        "EXT_DOC_REF_CHKSUM",
    ] + list(reserved.values())

    def t_text(self, t):
        r":\s*<text>"
        t.lexer.text_start = t.lexer.lexpos - len("<text>")
        t.lexer.begin("text")

    def t_text_end(self, t):
        r"</text>\s*"
        t.type = "TEXT"
        t.value = t.lexer.lexdata[t.lexer.text_start : t.lexer.lexpos]
        t.lexer.lineno += t.value.count("\n")
        t.value = t.value.strip()
        t.lexer.begin("INITIAL")
        return t

    def t_text_any(self, t):
        r".|\n"
        pass

    def t_text_error(self, t):
        print("Lexer error in text state")

    def t_CHKSUM(self, t):
        r":\s*SHA1:\s*[a-f0-9]{40,40}"
        t.value = t.value[1:].strip()
        return t

    def t_RANGE(self, t):
        r":\s*\d+:\d+"
        t.value = t.value[1:].strip()
        return t

    def t_DOC_REF_ID(self, t):
        r":\s*DocumentRef-([A-Za-z0-9\+\.\-]+)"
        t.value = t.value[1:].strip()
        return t

    def t_DOC_URI(self, t):
        r"\s*((ht|f)tps?:\/\/\S*)"
        t.value = t.value.strip()
        return t

    def t_EXT_DOC_REF_CHKSUM(self, t):
        r"\s*SHA1:\s*[a-f0-9]{40,40}"
        t.value = t.value[1:].strip()
        return t

    def t_TOOL_VALUE(self, t):
        r":\s*Tool:.+"
        t.value = t.value[1:].strip()
        return t

    def t_ORG_VALUE(self, t):
        r":\s*Organization:.+"
        t.value = t.value[1:].strip()
        return t

    def t_PERSON_VALUE(self, t):
        r":\s*Person:.+"
        t.value = t.value[1:].strip()
        return t

    def t_DATE(self, t):
        r":\s*\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ"
        t.value = t.value[1:].strip()
        return t

    def t_KEYWORD_AS_TAG(self, t):
        r"[a-zA-Z]+"
        t.type = self.reserved.get(t.value, "UNKNOWN_TAG")
        t.value = t.value.strip()
        return t

    def t_LINE_OR_KEYWORD_VALUE(self, t):
        r":.+"
        t.value = t.value[1:].strip()
        if t.value in self.reserved.keys():
            t.type = self.reserved[t.value]
        else:
            t.type = "LINE"
        return t

    def t_comment(self, t):
        r"\#.*"
        pass

    def t_newline(self, t):
        r"\n+"
        t.lexer.lineno += len(t.value)

    def t_whitespace(self, t):
        r"\s+"
        pass

    def build(self, **kwargs):
        self.lexer = lex.lex(module=self, **kwargs)

    def token(self):
        return self.lexer.token()

    def input(self, data):
        self.lexer.input(data)

    def t_error(self, t):
        t.lexer.skip(1)
        t.value = "Lexer error"
        return t


text:
<?php

namespace Katana\Sdk\Api\Value;

use Katana\Sdk\Exception\InvalidValueException;

class ReturnValue
{
    /**
     * @var bool
     */
    private $exists = false;

    /**
     * @var mixed
     */
    private $value;

    /**
     * @param null $value
     * @param bool $nullValue Pass true if the value is null, ignored otherwise.
     */
    public function __construct($value = null, $nullValue = false)
    {
        $this->exists = !is_null($value) || $nullValue;
        $this->value = $value;
    }

    /**
     * @return bool
     */
    public function exists()
    {
        return $this->exists;
    }

    /**
     * @return mixed
     * @throws InvalidValueException
     */
    public function getValue()
    {
        if (!$this->exists) {
            throw new InvalidValueException('Invalid return');
        }
        return $this->value;
    }
}


text:
* Adds the ability to select previously created Edgenotes from a list and reattach them to a new part of the text (#218)
* Redesigns the card formatting toolbar (#222)
* Allows cases to be published as "shared cases" outside any particular library. This will be the default status of user-submitted cases (#188)
* Makes it possible to list the institutional affiliation of case authors (#205)
* Redesigns the admin panel's case index and readers index to make them fast and easy to use (#208)
* Begins tracking how long users spend answering questions on the pre and post quizzes (#198)
* Translates the UI into Spanish (#221)

### Bugfixes

* Fixes a presentation bug in the content items selection view that instructors using our cases with Canvas see when creating an assignment (#190, #210, #211)
* Fixes bugs with our maps that prevented scrolling and made the pins disappear (#183)
* Fixes an authorization bug that could have allowed non-editors to change the order of case elements (#212)
* Fixes a presentational bug in the weekly report email (#215)

### Improvements

* Refactors and cleans up the codebase (#209)
* Documents every ruby object 🤓 (#217)


text:
package jp.osd.doce.internal;

import static jp.osd.doce.DomaProperties.DOMA_BATCH_SIZE;
import static jp.osd.doce.DomaProperties.DOMA_FETCH_SIZE;
import static jp.osd.doce.DomaProperties.DOMA_MAX_ROWS;
import static jp.osd.doce.DomaProperties.DOMA_QUERY_TIMEOUT;

import javax.sql.DataSource;

import jp.osd.doce.Doma;

import org.seasar.doma.jdbc.Config;
import org.seasar.doma.jdbc.DomaAbstractConfig;
import org.seasar.doma.jdbc.ExceptionSqlLogType;
import org.seasar.doma.jdbc.JdbcLogger;
import org.seasar.doma.jdbc.SqlFileRepository;
import org.seasar.doma.jdbc.dialect.Dialect;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Names;

/**
 * Guice で管理される Doma 設定クラスです。
 *

 * Guice の定数バインドで設定値を指定することができます。
 *

 *

 *

 *

 * Named
 * 必須
 * 説明

 *

 * Doma.maxRows
 *

 *
 * 最大行数制限。{@link Config#getMaxRows()} の戻り値に使用。
 *

 *

 * Doma.fetchSize
 *

 *
 * フェッチサイズ。{@link Config#getFetchSize()} の戻り値に使用。
 *

 *

 * Doma.queryTimeout
 *

 *
 * クエリタイムアウト(秒)。{@link Config#getQueryTimeout()} の戻り値に使用。
 *

 *

 * Doma.batchSize
 *

 *
 * バッチサイズ。{@link Config#getBatchSize()} の戻り値に使用。
 *

 *

 *

 *
 * @author asuka
 */
public class GuiceManagedConfig extends DomaAbstractConfig {
	private final DbNamedProperties properties;
	private Injector injector;
	private DataSource dataSource;
	private Dialect dialect;
	private SqlFileRepository sqlFileRepository;
	private JdbcLogger jdbcLogger;
	private int maxRows = 0;
	private int fetchSize = 0;
	private int queryTimeout = 0;
	private int batchSize = 10;

	/**
	 * 新たにオブジェクトを構築します。
	 *
	 * @param properties
	 *            データベース名付き設定プロパティ
	 */
	public GuiceManagedConfig(DbNamedProperties properties) {
		this.properties = properties;
		maxRows = this.properties.getInt(DOMA_MAX_ROWS, maxRows);
		fetchSize = this.properties.getInt(DOMA_FETCH_SIZE, fetchSize);
		queryTimeout = this.properties.getInt(DOMA_QUERY_TIMEOUT, queryTimeout);
		batchSize = this.properties.getInt(DOMA_BATCH_SIZE, batchSize);
	}

	/**
	 * Guice インジェクタを設定します。
	 *
	 * @param injector Guice インジェクタ
	 */
	@Inject
	public void setInjector(Injector injector) {
		this.injector = injector;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public DataSource getDataSource() {
		if (dataSource == null) {
			dataSource = getInstance(DataSource.class);
		}

		return dataSource;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getDataSourceName() {
		return getDataSource().getClass().getSimpleName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Dialect getDialect() {
		if (dialect == null) {
			dialect = getInstance(Dialect.class);
		}

		return dialect;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public SqlFileRepository getSqlFileRepository() {
		if (sqlFileRepository == null) {
			sqlFileRepository = getInstance(SqlFileRepository.class);
		}

		return sqlFileRepository;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public JdbcLogger getJdbcLogger() {
		if (jdbcLogger == null) {
			jdbcLogger = getInstance(JdbcLogger.class);
		}

		return jdbcLogger;
	}

    /**
	 * {@inheritDoc}
	 */
	@Override
	public int getMaxRows() {
		return maxRows;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int getFetchSize() {
		return fetchSize;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int getQueryTimeout() {
		return queryTimeout;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int getBatchSize() {
		return batchSize;
	}

	/**
	 * 例外に含めるSQLログのタイプを返します。
	 *
	 * @return 常に {@link ExceptionSqlLogType#FORMATTED_SQL}
	 */
	@Override
	public ExceptionSqlLogType getExceptionSqlLogType() {
		return ExceptionSqlLogType.FORMATTED_SQL;
	}

	private <T> T getInstance(Class<T> type) {
		if (injector == null) {
			return null;
		}
		String dbName = properties.getDbName();
		if (dbName == null) {
			return injector.getInstance(Key.get(type, Doma.class));
		}
		return injector.getInstance(Key.get(type, Names.named(dbName)));
	}
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for C:\xampp\htdocs\monitor\application/controllers/admin/regm.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

C:\xampp\htdocs\monitor\application /

controllers /

admin /

regm.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

100.00%

1 / 1

100.00%

2 / 2

      <acronym title="Change Risk Anti-Patterns (CRAP) Index">CRAP</acronym>

100.00%

19 / 19

      Regm

100.00%

1 / 1

100.00%

2 / 2

      3

100.00%

19 / 19

       __construct()

100.00%

1 / 1

      1

100.00%

5 / 5

       index()

100.00%

1 / 1

      2

100.00%

14 / 14

1
	<?php

2
	defined('BASEPATH') OR exit('No direct script access allowed');

3

4
	/**

5
	*

6
	*/

7
	class Regm extends CI_Controller

8
	{

9

10
	    function __construct()

11
	    {

12
	        parent::__construct();

13
	        $this->load->library(array('form_validation'));

14
	        $this->load->helper(array('url','form'));

15
	        $this->load->model('m_account');

16
	    }

17

18
	    public function index(){

19
	        $this->form_validation->set_rules('nama', 'NAMA','required');

20
	        $this->form_validation->set_rules('username', 'USERNAME','required');

21
	        $this->form_validation->set_rules('password', 'PASSWORD','required');

22
	        $this->form_validation->set_rules('role','ROLE','required');

23
	        if($this->form_validation->run() == FALSE) {

24
	            $this->load->view('account/m_register');

25
	        }else{

26

27
	            $data['nama'] = $this->input->post('nama');

28
	            $data['username'] = $this->input->post('username');

29
	            $data['password'] = sha1($this->input->post('password'));

30
	            $data['role'] = $this->input->post('role');

31

32
	            $this->m_account->daftar($data);

33

34
	            $pesan['message'] = "Pendaftaran berhasil";

35

36
	            $this->load->view('account/v_success',$pesan);

37
	        }

38
	    }

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.11 using PHP 7.1.9 and PHPUnit 3.7.21 at Tue Oct 17 16:34:32 CEST 2017.


text:
namespace ConoHaNet.Services.Compute
{
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using OpenStack.Net;

    /// <summary>
    /// Represents a map of network labels to collections of IP addresses.
    /// </summary>
    /// <remarks>
    /// The keys of this collection are network labels (see <see cref="CloudNetwork.Label"/>),
    /// and the values are collections of IP addresses.
    /// </remarks>
    /// <threadsafety static="true" instance="false"/>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable"), JsonDictionary]
    public class ServerAddresses : Dictionary<string, IPAddressList>
    {
        /// <summary>
        /// Gets the server IP addresses associated with the <c>private</c> network.
        /// </summary>
        [JsonIgnore]
        public IList<IPAddress> Private
        {
            get
            {
                IPAddressList result;
                if (!TryGetValue("private", out result))
                    return null;

                return result;
            }
        }

        /// <summary>
        /// Gets the server IP addresses associated with the <c>public</c> network.
        /// </summary>
        [JsonIgnore]
        public IList<IPAddress> Public
        {
            get
            {
                IPAddressList result;
                if (!TryGetValue("public", out result))
                    return null;

                return result;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE ONIXmessage SYSTEM "http://www.editeur.org/onix/2.1/short/onix-international.dtd">
<ONIXmessage release="2.1">

<m173>2027089</m173>
<m174>InterVarsity Press</m174>
<m175>Marsha Barnish</m175>
<m182>20101129</m182>
<m184>eng</m184>
<m185>01</m185>
<m186>USD</m186>
<m187>in</m187>
<m188>oz</m188>

<product>
<a001>9780830810871</a001>
<a002>03</a002>
<productidentifier>
<b221>03</b221>
<b244>9780830810871</b244>
</productidentifier>
<productidentifier>
<b221>02</b221>
<b244>0830810870</b244>
</productidentifier>
<b246>10</b246>
<b012>BC</b012>
<n338></n338>
<title>
<b202>01</b202>
<b203>Discipleship Essentials</b203>
<b029>A Guide to Building Your Life in Christ</b029>
</title>
<contributor>
<b034>1</b034>
<b035>A01</b035>
<b036>Greg Ogden </b036>
<b037>Ogden, Greg </b037>
<b039>Greg</b039>
<b040>Ogden</b040>
<b044>Greg Ogden (D.Min., Fuller Theological Seminary) is executive pastor of discipleship at Christ Church of Oak Brook in Oak Brook, Illinois. Previously he was academic director of the doctor of ministry program and associate professor of lay equipping and discipleship at Fuller Theological Seminary in Pasadena, California.

A pastor for 23 years with the Presbyterian Church, USA, he also served for nine years as senior pastor of Saratoga Federated Church in Saratoga, California. While there, he developed a discipleship program used by over 15,000 people and resulting in his book, Discipleship Essentials. Ogden has also written The New Reformation: Returning the Ministry to the People of God (Zondervan, rereleased in 2003 as Unfinished Business).</b044>
<website>
<b295>www.cc-ob.org</b295>
</website>
</contributor>
<b058>Expanded Edition</b058>
<language>
<b253>01</b253>
<b252>eng</b252>
</language>
<b061>237</b061>
<b064>REL012120</b064>
<b073>01</b073>
<othertext>
<d102>01</d102>
<d104 textformat="05">A year 2000 Finalist in the ECPA book competition!

Discover the fullness of life in Christ.

We grow in Christ as we seek him together. Jesus' own pattern of disciple-making was to be intimately involved with others and allow life to rub against life. By gathering in twos or threes to study the Bible and encourage one another, we most closely follow Jesus' example with the twelve disciples.

This workbook by Greg Ogden is a tool designed to help you follow this pattern Jesus drew for us. Working through it will deepen your knowledge of essential Christian teaching and strengthen your faith.

Each week contains the following elements:

a core truth presented in a question-answer format

a memory verse and accompanying study

an field-tested inductive Bible study

a reading on the theme for the week

questions to draw out key principles in the reading

This material is designed for groups of three. It has also been used successfully as an individual study program, a one-on-one discipling tool and small group curriculum.

Jesus had a big enough vision to think small. Focusing on a few did not limit his influence. Rather, it expanded it. Discipleship Essentials is designed to help us influence others as Jesus did--by investing in a few.

Second edition includes a new foreword by the author. These studies are for both individuals and groups.</d104>
</othertext>
<othertext>
<d102>02</d102>
<d104 textformat="05">Greg Ogden presents 25 sessions on growing in spiritual maturity. Second edition includes a new foreword by the author. These studies are for both individuals and groups.</d104>
</othertext>
<othertext>
<d102>04</d102>
<d104 textformat="05">A Word from the Author

Getting the Most from Discipleship Essentials

Part One: Growing Up in Christ

1 Making Disciples

2 Being a Disciple

3 Quiet Time

4 Bible Study

5 Prayer

6 Worship

Part Two: Understanding the Message of Christ

7 The Three-Person God

8 Made in God?s Image

9 Sin

10 Grace

11 Redemption

12 Justification

13 Adoption

Part Three: Becoming Like Christ

14 Filled with the Holy Spirit

15 Fruit of the Holy Spirit

16 Trust

17 Love

18 Justice

19 Witness

Part Four: Serving Christ

20 The Church

21 Ministry Gifts

22 Spiritual Warfare

23 Walking in Obedience

24 Sharing the Wealth

Bonus Section

25 Money

Appendix: Building a Discipleship Ministry</d104>
</othertext>
<othertext>
<d102>07</d102>
<d104 textformat="05">"I have long admired Greg Ogden's rare ability to distill the complex down to the essential. Discipleship Essentials has become a modern classic in the field of discipleship because it does just this. If you've ever looked for a tool to help people you care about understand the core principles and practices of the Christian life, look no further than this book. I have seen it help absolute beginners and advanced disciples alike mature in their walk with Christ in a life-changing way. The book is interactive, thought-provoking, enjoyable and deep. I use it weekly myself.
</d104>
<d107>Daniel Meyer, senior pastor, Christ Church of Oak Brook, Illinois</d107>
</othertext>
<othertext>
<d102>30</d102>
<d104 textformat="05">"If you're looking for a shortcut to the likeness of Christ, stop looking because there isn't one. No program or structure can replace the hard, time-consuming, rewarding and utterly fulfilling process of discipleship. Discipleship Essentials is revolutionizing the lives of the people in our church. Everyone can and should use this effective tool!"</d104>
<d107>Jan den Ouden, minister-at-large, OM International, Rotterdam</d107>
</othertext>
<othertext>
<d102>30</d102>
<d104 textformat="05">"Our entire congregation used Discipleship Essentials as the template for a yearlong sermon and small group series. It served as a life-changing tool that united our church family and deepened our faith as a community. Ogden's work is thorough, organized and challenging--a great resource for churches and small groups who desire to grow in their love for the Lord and their commitment to following him."</d104>
<d107>Rev. Jane Filkin, associate pastor of community life, First Presbyterian Church, Boulder, Colorado</d107>
</othertext>
<othertext>
<d102>30</d102>
<d104 textformat="05">"I am currently leading my fourth group. The study is a Spirit-inspired study of the skeletal structure of our Christian faith upon which individuals can flesh out the shape of their individual walk with our Lord. If taken seriously and followed as a spiritual discipline, the truths it contains will change the follower's life, and lives that come in contact with the disciple will be touched by God's love. It's a powerful tool in a group for learning to practice confession and being accountable. It is never old for me. The Spirit speaks to me through the Word in the study. I am refreshed every time we meet as a group."</d104>
<d107>Hudson Staffield, president, Chi Rho Ministry</d107>
</othertext>
<othertext>
<d102>30</d102>
<d104 textformat="05">"Greg Ogden's engaging book sets the expectation that every follower of Jesus has the joyful responsibility to invest into two or three regularly and purposefully for the kingdom. For the past ten years, Discipleship Essentials has provided an engaging and balanced approach to the task of raising up mature believers who will then themselves invest in others. I can only imagine that in the next ten years thousands more will be shaped toward maturity because of his important work that gives each believer the inspiration and the framework to do what they were made to do: advance the kingdom by making mature disciples."</d104>
<d107>Rev. Timothy J. Yee, minister of young adults, St. Andrews Presbyterian Church, Newport Beach, California</d107>
</othertext>
<othertext>
<d102>30</d102>
<d104 textformat="05">"One of the most serious challenges facing the church in North America is that of undiscipled church members. Greg Ogden's work seeks to move Sunday-only consumer Christians into the adventurous life of following Jesus on a daily basis in authentic community. It provides an indispensable resource to help local churches address this challenge."</d104>
<d107>Eddie Gibbs, professor, Fuller Theological Seminary and author of ChurchNext</d107>
</othertext>
<othertext>
<d102>30</d102>
<d104 textformat="05">"Discipleship Essentials is the most effective tool I know of for use in encouraging actual growth in personal discipleship. I give it to all of the pastors I am working with in congregational transformation and missional engagement because growing disciples is essential to their congregations' vitality."</d104>
<d107>E. Stanley Ott, president, The Vital Churches Institute</d107>
</othertext>
<mediafile>
<f114>04</f114>
<f115>03</f115>
<f116>01</f116>
<f117>http://www.IVPress.com/img/book/100w/1169.jpg</f117>
</mediafile>
<imprint>
<b241>01</b241>
<b243>CNCT</b243>
<b079>IVP Connect</b079>
</imprint>
<publisher>
<b291>01</b291>
<b081>InterVarsity Press</b081>
<website>
<b295>http://www.ivpress.com/</b295>
</website>
</publisher>
<b394>04</b394>
<b003>20071129</b003>
<salesrights>
<b089>01</b089>
<b090>US</b090>
</salesrights>
<measure>
<c093>01</c093>
<c094>10</c094>
<c095>in</c095>
</measure>
<measure>
<c093>02</c093>
<c094>7</c094>
<c095>in</c095>
</measure>
<measure>
<c093>03</c093>
<c094>0.7</c094>
<c095>in</c095>
</measure>
<measure>
<c093>08</c093>
<c094>16</c094>
<c095>oz</c095>
</measure>
<supplydetail>
<j136>2027089</j136>
<j137>InterVarsity Press</j137>
<j270>630-734-4000</j270>
<j271>630-734-4200</j271>
<j272>email@ivpress.com</j272>
<website>
<b295>http://www.ivpress.com/</b295>
</website>
<j268>02</j268>
<j269>Y</j269>
<j141>IP</j141>
<j396>21</j396>
<j145>22</j145>
<price>
<j148>01</j148>
<discountcoded>
<j363>02</j363>
<j364>FLT</j364>
</discountcoded>
<j151>18.00</j151>
<j152>USD</j152>
</price>
</supplydetail>
</product>
</ONIXmessage>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace beRemote.GUI.Control.ConnectionTreeViewNS.ViewModel
{
    public class ConnectionItem : INotifyPropertyChanged
    {
        ///<summary>
        ///Occurs when a property value changes.
        ///</summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Fires the <see cref="PropertyChanged"/> event for a
        /// given property.
        /// </summary>
        /// <param name="propertyName">The changed property.</param>
        private void RaisePropertyChangedEvent(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}


text:
    Input a URL which failed to load, and then click the button to run some
    tests for why it failed.

  <form id="test-view-connection-tests-form">
    URL: <input id="test-view-url-input" type="text">
    <input id="test-view-connection-tests-submit" type="submit"
        value="Start tests">
  </form>


text:
#region License
// ICommandLineOptionBuilderFluent.cs
// Copyright (c) 2013, Simon Williams
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provide
// d that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Fclp
{
	/// <summary>
	/// Defines the fluent interface for setting up a <see cref="ICommandLineOptionFluent{TProperty}"/>.
	/// </summary>
	public interface ICommandLineOptionBuilderFluent<TProperty>
	{
		/// <summary>
		/// Setup a new <see cref="ICommandLineOptionFluent{T}"/> using the specified short and long Option name.
		/// </summary>
		/// <param name="shortOption">The short name for the Option. This must not be <c>whitespace</c> or a control character.</param>
		/// <param name="longOption">The long name for the Option. This must not be <c>null</c>, <c>empty</c> or only <c>whitespace</c>.</param>
		/// <returns></returns>
		/// <exception cref="OptionAlreadyExistsException">
		/// A Option with the same <paramref name="shortOption"/> name or <paramref name="longOption"/> name already exists in the <see cref="IFluentCommandLineParser"/>.
		/// </exception>
		/// <exception cref="InvalidOptionNameException">
		/// Either <paramref name="shortOption"/> or <paramref name="longOption"/> are not valid. <paramref name="shortOption"/> must not be <c>whitespace</c>
		/// or a control character. <paramref name="longOption"/> must not be <c>null</c>, <c>empty</c> or only <c>whitespace</c>.
		/// </exception>
		ICommandLineOptionFluent<TProperty> As(char shortOption, string longOption);

		/// <summary>
		/// Setup a new <see cref="ICommandLineOptionFluent{T}"/> using the specified short Option name.
		/// </summary>
		/// <param name="shortOption">The short name for the Option. This must not be <c>whitespace</c> or a control character.</param>
		/// <returns></returns>
		/// <exception cref="InvalidOptionNameException">if <paramref name="shortOption"/> is invalid for a short option.</exception>
		/// <exception cref="OptionAlreadyExistsException">
		/// A Option with the same <paramref name="shortOption"/> name
		/// already exists in the <see cref="IFluentCommandLineParser"/>.
		/// </exception>
		ICommandLineOptionFluent<TProperty> As(char shortOption);

		/// <summary>
		/// Setup a new <see cref="ICommandLineOptionFluent{T}"/> using the specified long Option name.
		/// </summary>
		/// <param name="longOption">The long name for the Option. This must not be <c>null</c>, <c>empty</c> or only <c>whitespace</c>.</param>
		/// <exception cref="InvalidOptionNameException">if <paramref name="longOption"/> is invalid for a long option.</exception>
		/// <exception cref="OptionAlreadyExistsException">
		/// A Option with the same <paramref name="longOption"/> name already exists in the <see cref="IFluentCommandLineParser"/>.
		/// </exception>
		ICommandLineOptionFluent<TProperty> As(string longOption);
	}
}


text:
"""Test Efergy config flow."""
from unittest.mock import patch

from pyefergy import exceptions

from homeassistant.components.efergy.const import DEFAULT_NAME, DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_REAUTH, SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_SOURCE
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import (
    RESULT_TYPE_ABORT,
    RESULT_TYPE_CREATE_ENTRY,
    RESULT_TYPE_FORM,
)

from . import (
    CONF_DATA,
    HID,
    IMPORT_DATA,
    _patch_efergy,
    _patch_efergy_status,
    create_entry,
)

def _patch_setup():
    return patch("homeassistant.components.efergy.async_setup_entry")

async def test_flow_user(hass: HomeAssistant):
    """Test user initialized flow."""
    with _patch_efergy(), _patch_setup():
        result = await hass.config_entries.flow.async_init(
            DOMAIN,
            context={CONF_SOURCE: SOURCE_USER},
        )
        assert result["type"] == RESULT_TYPE_FORM
        assert result["step_id"] == "user"

        result = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            user_input=CONF_DATA,
        )
        assert result["type"] == RESULT_TYPE_CREATE_ENTRY
        assert result["title"] == DEFAULT_NAME
        assert result["data"] == CONF_DATA
        assert result["result"].unique_id == HID

async def test_flow_user_cannot_connect(hass: HomeAssistant):
    """Test user initialized flow with unreachable service."""
    with _patch_efergy_status() as efergymock:
        efergymock.side_effect = exceptions.ConnectError
        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=CONF_DATA
        )
        assert result["type"] == RESULT_TYPE_FORM
        assert result["step_id"] == "user"
        assert result["errors"]["base"] == "cannot_connect"

async def test_flow_user_invalid_auth(hass: HomeAssistant):
    """Test user initialized flow with invalid authentication."""
    with _patch_efergy_status() as efergymock:
        efergymock.side_effect = exceptions.InvalidAuth
        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=CONF_DATA
        )
        assert result["type"] == RESULT_TYPE_FORM
        assert result["step_id"] == "user"
        assert result["errors"]["base"] == "invalid_auth"

async def test_flow_user_unknown(hass: HomeAssistant):
    """Test user initialized flow with unknown error."""
    with _patch_efergy_status() as efergymock:
        efergymock.side_effect = Exception
        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=CONF_DATA
        )
        assert result["type"] == RESULT_TYPE_FORM
        assert result["step_id"] == "user"
        assert result["errors"]["base"] == "unknown"

async def test_flow_import(hass: HomeAssistant):
    """Test import step."""
    with _patch_efergy(), _patch_setup():
        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={CONF_SOURCE: SOURCE_IMPORT}, data=IMPORT_DATA
        )

        assert result["type"] == RESULT_TYPE_CREATE_ENTRY
        assert result["title"] == DEFAULT_NAME
        assert result["data"] == CONF_DATA
        assert result["result"].unique_id == HID

async def test_flow_import_already_configured(hass: HomeAssistant):
    """Test import step already configured."""
    create_entry(hass)
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={CONF_SOURCE: SOURCE_IMPORT}, data=IMPORT_DATA
    )

    assert result["type"] == RESULT_TYPE_ABORT
    assert result["reason"] == "already_configured"

async def test_flow_reauth(hass: HomeAssistant):
    """Test reauth step."""
    entry = create_entry(hass)
    with _patch_efergy(), _patch_setup():
        result = await hass.config_entries.flow.async_init(
            DOMAIN,
            context={
                CONF_SOURCE: SOURCE_REAUTH,
                "entry_id": entry.entry_id,
                "unique_id": entry.unique_id,
            },
            data=CONF_DATA,
        )

        assert result["type"] == RESULT_TYPE_FORM
        assert result["step_id"] == "user"

        new_conf = {CONF_API_KEY: "1234567890"}
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            user_input=new_conf,
        )
        assert result["type"] == RESULT_TYPE_ABORT
        assert result["reason"] == "reauth_successful"
        assert entry.data == new_conf


text:
/**
 * Entity objects describing trades and products in financial markets.
 *

 * The trade model has three basic concepts, trades, securities and products.
 *

 * A {@link com.opengamma.strata.product.Trade Trade} is the basic element of finance,
 * a transaction between two organizations, known as counterparties.
 * Most trades represented in the system will be contracts that have been agreed on a date in the past.
 * The trade model also allows trades with a date in the future, or without any date.
 *

 * A {@link com.opengamma.strata.product.Security Security} is a standard contract that is traded,
 * such as an equity share or futures contract. Securities are typically created once and shared
 * using an identifier, represented by a {@link com.opengamma.strata.product.SecurityId SecurityId}.
 * They are often referred to as reference data.
 * Securities may also be stored in a {@link com.opengamma.strata.product.Position Position} instead
 * of in a {@code Trade}.
 *

 * A {@link com.opengamma.strata.product.Product Product} is the financial details of the trade or security.
 * A product typically contains enough information to be priced, such as the dates, holidays, indices,
 * currencies and amounts. There is an implementation of {@code Product} for each distinct type
 * of financial instrument.
 *

 * Trades are typically classified as Over-The-Counter (OTC) and listed.
 *

 * An OTC trade directly embeds the product it refers to.
 * As such, OTC trades implement {@link com.opengamma.strata.product.ProductTrade ProductTrade}.
 *

 * For example, consider an OTC instrument such as an interest rate swap.
 * The object model consists of a {@link com.opengamma.strata.product.swap.SwapTrade SwapTrade}
 * that directly contains a {@link com.opengamma.strata.product.swap.Swap Swap},
 * where {@code SwapTrade} implements {@code ProductTrade}.
 *

 * The key to understanding the model is appreciating the separation of products from trades.
 * In many cases, it is possible to price the product without knowing any trade details.
 * This allows a product to be an underlying of another product, such as a swap within a swaption.
 *

 * A listed trade can be defined in two ways.
 *

 * The first approach is to use {@link com.opengamma.strata.product.SecurityTrade SecurityTrade}.
 * A {@code SecurityTrade} stores just the security identifier, quantity and trade price.
 * When the trade needs to be priced, the identifier can be resolved to a {@code Security} using
 * {@link com.opengamma.strata.basics.ReferenceData ReferenceData}.
 * The reference data could be backed by an in-memory store or a database.
 *

 * The second approach is to use a more specific trade type, such as
 * {@link com.opengamma.strata.product.bond.BondFutureTrade BondFutureTrade}.
 * These types include the product details directly so that no reference data is needed.
 * As such, this approach avoids the need to use the Strata {@code Security} classes.
 *

 * For example, consider a bond future.
 * In the first approach, the application would create a {@code SecurityTrade} using the identifier of the future.
 * The reference data would be populated, mapping the identifier to an instance of {@code BondFutureSecurity}
 * and additional identifiers for each of the underlying {@code FixedCouponBondSecurity} instances.
 *

 * In the second approach, the trade would be defined using {@code BondFutureTrade}. In this case,
 * the trade directly holds the product model of the {@code BondFuture} and each underlying {@code FixedCouponBond}.
 * There is thus no need to populate the reference data with securities.
 *

 * The key to understanding the model is appreciating the separation of products from trades and securities.
 * It is often possible to price either against the market or against a model.
 * Details for pricing against the market are held in the security.
 * Details for pricing against the model are held in the product.
 */
package com.opengamma.strata.product;


text:
package plist

import (
	"encoding/base64"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"math"
	"runtime"
	"strings"
	"time"
)

const xmlDOCTYPE = `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
`

type xmlPlistGenerator struct {
	writer     io.Writer
	xmlEncoder *xml.Encoder
}

func (p *xmlPlistGenerator) generateDocument(pval *plistValue) {
	io.WriteString(p.writer, xml.Header)
	io.WriteString(p.writer, xmlDOCTYPE)

	plistStartElement := xml.StartElement{
		Name: xml.Name{
			Space: "",
			Local: "plist",
		},
		Attr: []xml.Attr{{
			Name: xml.Name{
				Space: "",
				Local: "version"},
			Value: "1.0"},
		},
	}

	p.xmlEncoder.EncodeToken(plistStartElement)

	p.writePlistValue(pval)

	p.xmlEncoder.EncodeToken(plistStartElement.End())
	p.xmlEncoder.Flush()
}

func (p *xmlPlistGenerator) writePlistValue(pval *plistValue) {
	if pval == nil {
		return
	}

	defer p.xmlEncoder.Flush()

	key := ""
	encodedValue := pval.value
	switch pval.kind {
	case Dictionary:
		startElement := xml.StartElement{Name: xml.Name{Local: "dict"}}
		p.xmlEncoder.EncodeToken(startElement)
		dict := encodedValue.(*dictionary)
		dict.populateArrays()
		for i, k := range dict.keys {
			p.xmlEncoder.EncodeElement(k, xml.StartElement{Name: xml.Name{Local: "key"}})
			p.writePlistValue(dict.values[i])
		}
		p.xmlEncoder.EncodeToken(startElement.End())
	case Array:
		startElement := xml.StartElement{Name: xml.Name{Local: "array"}}
		p.xmlEncoder.EncodeToken(startElement)
		values := encodedValue.([]*plistValue)
		for _, v := range values {
			p.writePlistValue(v)
		}
		p.xmlEncoder.EncodeToken(startElement.End())
	case String:
		key = "string"
	case Integer:
		key = "integer"
		if pval.value.(signedInt).signed {
			encodedValue = int64(pval.value.(signedInt).value)
		} else {
			encodedValue = pval.value.(signedInt).value
		}
	case Real:
		key = "real"
		encodedValue = pval.value.(sizedFloat).value
		switch {
		case math.IsInf(pval.value.(sizedFloat).value, 1):
			encodedValue = "inf"
		case math.IsInf(pval.value.(sizedFloat).value, -1):
			encodedValue = "-inf"
		case math.IsNaN(pval.value.(sizedFloat).value):
			encodedValue = "nan"
		}
	case Boolean:
		key = "false"
		b := pval.value.(bool)
		if b {
			key = "true"
		}
		encodedValue = ""
	case Data:
		key = "data"
		encodedValue = xml.CharData(base64.StdEncoding.EncodeToString(pval.value.([]byte)))
	case Date:
		key = "date"
		encodedValue = pval.value.(time.Time).In(time.UTC).Format(time.RFC3339)
	}
	if key != "" {
		err := p.xmlEncoder.EncodeElement(encodedValue, xml.StartElement{Name: xml.Name{Local: key}})
		if err != nil {
			panic(err)
		}
	}
}

func (p *xmlPlistGenerator) Indent(i string) {
	p.xmlEncoder.Indent("", i)
}

func newXMLPlistGenerator(w io.Writer) *xmlPlistGenerator {
	mw := mustWriter{w}
	return &xmlPlistGenerator{mw, xml.NewEncoder(mw)}
}

type xmlPlistParser struct {
	reader             io.Reader
	xmlDecoder         *xml.Decoder
	whitespaceReplacer *strings.Replacer
	ntags              int
}

func (p *xmlPlistParser) parseDocument() (pval *plistValue, parseError error) {
	defer func() {
		if r := recover(); r != nil {
			if _, ok := r.(runtime.Error); ok {
				panic(r)
			}
			if _, ok := r.(invalidPlistError); ok {
				parseError = r.(error)
			} else {
				// Wrap all non-invalid-plist errors.
				parseError = plistParseError{"XML", r.(error)}
			}
		}
	}()
	for {
		if token, err := p.xmlDecoder.Token(); err == nil {
			if element, ok := token.(xml.StartElement); ok {
				pval = p.parseXMLElement(element)
				if p.ntags == 0 {
					panic(invalidPlistError{"XML", errors.New("no elements encountered")})
				}
				return
			}
		} else {
			// The first XML parse turned out to be invalid:
			// we do not have an XML property list.
			panic(invalidPlistError{"XML", err})
		}
	}
}

func (p *xmlPlistParser) parseXMLElement(element xml.StartElement) *plistValue {
	var charData xml.CharData
	switch element.Name.Local {
	case "plist":
		p.ntags++
		for {
			token, err := p.xmlDecoder.Token()
			if err != nil {
				panic(err)
			}

			if el, ok := token.(xml.EndElement); ok && el.Name.Local == "plist" {
				break
			}

			if el, ok := token.(xml.StartElement); ok {
				return p.parseXMLElement(el)
			}
		}
		return nil
	case "string":
		p.ntags++
		err := p.xmlDecoder.DecodeElement(&charData, &element)
		if err != nil {
			panic(err)
		}

		return &plistValue{String, string(charData)}
	case "integer":
		p.ntags++
		err := p.xmlDecoder.DecodeElement(&charData, &element)
		if err != nil {
			panic(err)
		}

		s := string(charData)
		if s[0] == '-' {
			n := mustParseInt(string(charData), 10, 64)
			return &plistValue{Integer, signedInt{uint64(n), true}}
		} else {
			n := mustParseUint(string(charData), 10, 64)
			return &plistValue{Integer, signedInt{n, false}}
		}
	case "real":
		p.ntags++
		err := p.xmlDecoder.DecodeElement(&charData, &element)
		if err != nil {
			panic(err)
		}

		n := mustParseFloat(string(charData), 64)
		return &plistValue{Real, sizedFloat{n, 64}}
	case "true", "false":
		p.ntags++
		p.xmlDecoder.Skip()

		b := element.Name.Local == "true"
		return &plistValue{Boolean, b}
	case "date":
		p.ntags++
		err := p.xmlDecoder.DecodeElement(&charData, &element)
		if err != nil {
			panic(err)
		}

		t, err := time.ParseInLocation(time.RFC3339, string(charData), time.UTC)
		if err != nil {
			panic(err)
		}

		return &plistValue{Date, t}
	case "data":
		p.ntags++
		err := p.xmlDecoder.DecodeElement(&charData, &element)
		if err != nil {
			panic(err)
		}

		str := p.whitespaceReplacer.Replace(string(charData))

		l := base64.StdEncoding.DecodedLen(len(str))
		bytes := make([]uint8, l)
		l, err = base64.StdEncoding.Decode(bytes, []byte(str))
		if err != nil {
			panic(err)
		}

		return &plistValue{Data, bytes[:l]}
	case "dict":
		p.ntags++
		var key *string
		var subvalues map[string]*plistValue = make(map[string]*plistValue)
		for {
			token, err := p.xmlDecoder.Token()
			if err != nil {
				panic(err)
			}

			if el, ok := token.(xml.EndElement); ok && el.Name.Local == "dict" {
				if key != nil {
					panic(errors.New("missing value in dictionary"))
				}
				break
			}

			if el, ok := token.(xml.StartElement); ok {
				if el.Name.Local == "key" {
					var k string
					p.xmlDecoder.DecodeElement(&k, &el)
					key = &k
				} else {
					if key == nil {
						panic(errors.New("missing key in dictionary"))
					}
					subvalues[*key] = p.parseXMLElement(el)
					key = nil
				}
			}
		}
		return &plistValue{Dictionary, &dictionary{m: subvalues}}
	case "array":
		p.ntags++
		var subvalues []*plistValue = make([]*plistValue, 0, 10)
		for {
			token, err := p.xmlDecoder.Token()
			if err != nil {
				panic(err)
			}

			if el, ok := token.(xml.EndElement); ok && el.Name.Local == "array" {
				break
			}

			if el, ok := token.(xml.StartElement); ok {
				subvalues = append(subvalues, p.parseXMLElement(el))
			}
		}
		return &plistValue{Array, subvalues}
	}
	err := fmt.Errorf("encountered unknown element %s", element.Name.Local)
	if p.ntags == 0 {
		// If out first XML tag is invalid, it might be an openstep data element, ala <abab> or <0101>
		panic(invalidPlistError{"XML", err})
	}
	panic(err)
}

func newXMLPlistParser(r io.Reader) *xmlPlistParser {
	return &xmlPlistParser{r, xml.NewDecoder(r), strings.NewReplacer("\t", "", "\n", "", " ", "", "\r", ""), 0}
}


text:
<!-- Copyright (c) Microsoft Corporation. All rights reserved.
     Licensed under the MIT License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.azure</groupId>
  <artifactId>azure-formrecognizer-service</artifactId>
  <packaging>pom</packaging>
  <version>1.0.0</version>  <!-- Need not change for every release-->
  <modules>
    <module>azure-ai-formrecognizer</module>
  </modules>
</project>