text:
namespace re2 {
class RE2;
}  // namespace re2

namespace autofill {
namespace structured_address {

struct AddressToken;
struct SortedTokenComparisonResult;

// Represents the validation status of value stored in the AutofillProfile.
// The associated integer values used to store the verification code in SQL and
// should not be modified.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome.browser.autofill
enum class VerificationStatus {
  // No verification status assigned.
  kNoStatus = 0,
  // The value token was parsed from a parent token.
  kParsed = 1,
  // Value was built from its subcomponents.
  kFormatted = 2,
  // The value was observed in a form transmission.
  kObserved = 3,
  // The user used the autofill settings to verify and store this token.
  kUserVerified = 4,
  // The token was parsed by the server.
  kServerParsed = 5,
  kMaxValue = kServerParsed
};

// Prints the string representation of |status| to |os|.
std::ostream& operator<<(std::ostream& os, VerificationStatus status);

// Returns true if |left| has a less significant verification status compared to
// |right|.
bool IsLessSignificantVerificationStatus(VerificationStatus left,
                                         VerificationStatus right);

// Returns the more significant verification status according to
// |IsLessSignificantVerificationStatus|.
VerificationStatus GetMoreSignificantVerificationStatus(
    VerificationStatus left,
    VerificationStatus right);

// The merge mode defines if and how two components are merged.
// The merge operations are applied in the order defined here.
// If one merge operation succeeds, the subsequent ones are not tested.
// Therefore, if |KUseBetterOrMoreRecentIfDifferent| is active,
// |kMergeChildrenAndReformatIfNeeded| will not be applied because
// |kUseBetterOrMostRecentIfDifferent| is always applicable.
enum MergeMode {
  // If one component has an empty value, use the non-empty one.
  kReplaceEmpty = 1,
  // Recursively merge two components that have the same tokens in arbitrary
  // order. This is used as the default merge mode.
  kRecursivelyMergeTokenEquivalentValues = 1 << 1,
  // If both tokens have the same normalized value, use the one with the better
  // verification status. If both statuses are the same, use the newer one.
  kUseBetterOrNewerForSameValue = 1 << 2,
  // If one component is a superset of the other, use the subset.
  kReplaceSuperset = 1 << 3,
  // If one component is a subset of the other, use the superset.
  kReplaceSubset = 1 << 4,
  // If both components have a different value, is the newer one.
  kUseNewerIfDifferent = 1 << 5,
  // If the newer component contains one token more, apply a recursive strategy
  // to merge the tokens.
  kRecursivelyMergeSingleTokenSubset = 1 << 6,
  // If one is a substring of the other use the most recent one.
  kUseMostRecentSubstring = 1 << 7,
  // Merge the child nodes and reformat the node from its children after merge
  // if the value has changed.
  kPickShorterIfOneContainsTheOther = 1 << 8,
  // If the normalized values are different, use the better one in terms
  // of verification score or the most recent one if both scores are the same.
  kUseBetterOrMostRecentIfDifferent = 1 << 9,
  // Defines the default merging behavior.
  kMergeChildrenAndReformatIfNeeded = 1 << 10,
  // If the tokens match or one is a subset of the other, pick the shorter one.
  kDefault = kRecursivelyMergeTokenEquivalentValues
};

// An AddressComponent is a tree structure that represents a semi-structured
// address token. Such an address token can either be an atomic leaf node or
// have a set of children, each representing a more granular subtoken of the
// component.
//
// An AddressComponent has a string representation stored in |value_| and a
// VerificationStatus stored in |verification_status_|.
// The latter indicates if the value was user-verified, observed in a form
// submission event, parsed from its parent component or was formatted from its
// child components.
//
// In a proper component tree, each AddressComponent has a unique
// ServerFieldType. Additionally, an AddressComponent may be associated with a
// list of additional field types that allow for retrieving and setting the
// Component's value in specific formats. For example, NAME_MIDDLE may be the
// storage type and NAME_MIDDLE_INITIAL is an additional field type.
//
// The usage pattern of such an address tree is as follows:
//
//  * Create a tree from an observed form submission or a profile editing or
//  creation event in the Chrome settings. It is assumed that the created
//  tree does not have values for competing field types. Two types are competing
//  iff they are on a common root-to-leaf path. For example, an imported profile
//  with a value for NAME_FULL and NAME_LAST has conflicting types that
//  carry redundant information.
//
//  * After the creation of the tree, the values of unassigned nodes in the tree
//  are deducted from the values of assigned nodes. This happens by parsing
//  (taking a string and splitting it into components) or by formatting (taking
//  one or multiple strings and combining them into one string).
//
//  * After the completion, there should be no need to modify the tree.
//
//  * A tree may be mergeable with another tree of the same type. This
//  operation incorporates complementing observations. For example, in the first
//  tree NAME_FIRST, NAME_MIDDLE and NAME_LAST may be parsed from an observed
//  unstructured name (NAME_FULL). The second tree may be built from observing
//  the structured name, and contain observed NAME_FIRST, NAME_MIDDLE and
//  NAME_LAST values but only a formatted NAME_FULL value.
class AddressComponent {
 public:
  // Constructor for a compound child node.
  AddressComponent(ServerFieldType storage_type,
                   AddressComponent* parent,
                   unsigned int merge_mode);

  // Disallows copies and direct assignments since they are not needed in the
  // current Autofill design.
  AddressComponent(const AddressComponent& other) = delete;
  AddressComponent& operator=(const AddressComponent& right) = delete;

  virtual ~AddressComponent();

  // Migrates from a legacy structure in which tokens are imported without
  // a status.
  virtual void MigrateLegacyStructure(bool is_verified_profile) {}

  // Comparison operators are deleted in favor of and |SameAs()|.
  bool operator==(const AddressComponent& right) const = delete;
  bool operator!=(const AddressComponent& right) const = delete;

  // Compares the values and verification statuses with |other| recursively down
  // the tree. Returns true iff all values and verification statuses of this
  // node and its subtree and |other| with its subtree are the same.
  bool SameAs(const AddressComponent& other) const;

  // Copies the values and verification statuses from |other| recursively down
  // the tree.
  void CopyFrom(const AddressComponent& other);

  // Returns the autofill storage type stored in |storage_type_|.
  ServerFieldType GetStorageType() const;

  // Returns the string representation of |storage_type_|.
  std::string GetStorageTypeName() const;

  // Returns the value verification status of the component's value;
  VerificationStatus GetVerificationStatus() const;

  // Returns true if the component has no subcomponents.
  bool IsAtomic() const;

  // Returns a constant reference to |value_.value()|. If the value is not
  // assigned, an empty string is returned.
  const std::u16string& GetValue() const;

  // Returns true if the value of this AddressComponent is assigned.
  bool IsValueAssigned() const;

  // Sets the value corresponding to the storage type of this AddressComponent.
  virtual void SetValue(std::u16string value, VerificationStatus status);

  // Sets the value to an empty string, marks it unassigned and sets the
  // verification status to |kNoStatus|.
  virtual void UnsetValue();

  // The method sets the value of the current node if its |storage_type_| is
  // |type| or if |ConvertAndGetTheValueForAdditionalFieldTypeName()| supports
  // retrieving |type|. Otherwise, the call is delegated recursively to the
  // node's children.
  // Returns true if the |value_| and |verification_status_| were successfully
  // set for this or an ancestor node with the storage type |type|. If
  // |invalidate_child_nodes|, all child nodes of the assigned node are
  // unassigned. If |invalidate_parent_nodes|, all ancestor nodes of the
  // assigned node as unassigned.
  bool SetValueForTypeIfPossible(const ServerFieldType& type,
                                 const std::u16string& value,
                                 const VerificationStatus& verification_status,
                                 bool invalidate_child_nodes = false,
                                 bool invalidate_parent_nodes = false);

  // Same as |SetValueForTypeIfPossible()| but the type is supplied in the
  // corresponding string representation.
  bool SetValueForTypeIfPossible(const std::string& type_name,
                                 const std::u16string& value,
                                 const VerificationStatus& verification_status,
                                 bool invalidate_child_nodes = false,
                                 bool invalidate_parent_nodes = false);

  // Convenience wrapper to allow setting the value using a std::string.
  bool SetValueForTypeIfPossible(const ServerFieldType& type,
                                 const std::string& value,
                                 const VerificationStatus& verification_status,
                                 bool invalidate_child_nodes = false,
                                 bool invalidate_parent_nodes = false);

  // Convenience wrapper to allow setting the value using a std::string.
  bool SetValueForTypeIfPossible(const std::string& type_name,
                                 const std::string& value,
                                 const VerificationStatus& verification_status,
                                 bool invalidate_child_nodes = false,
                                 bool invalidate_parent_nodes = false);

  // Convenience method to get the value of |type|.
  // Returns an empty string if |type| is not supported.
  std::u16string GetValueForType(const ServerFieldType& type) const;

  // Convenience method to get the value of |type| identified by its string
  // representation name. Returns an empty string if |type| is not supported.
  std::u16string GetValueForType(const std::string& type) const;

  // Convenience method to get the verification status of |type|.
  // Returns |VerificationStatus::kNoStatus| if |type| is not supported.
  VerificationStatus GetVerificationStatusForType(
      const ServerFieldType& type) const;

  // Convenience method to get the verification status of |type| identified by
  // its name. Returns |VerificationStatus::kNoStatus| if |type| is not
  // supported.
  VerificationStatus GetVerificationStatusForType(
      const std::string& type) const;

  // Get the value and status of a |type|,
  // Returns false if the |type| is not supported by the structure.
  // The method returns |value_| and |validation_status_| of the current node if
  // its |storage_type_| is |type| or if
  // |ConvertAndSetTheValueForAdditionalFieldTypeName()| supports setting
  // |type|. Otherwise, the call is delegated recursively to the node's
  // children. Returns false if the neither the node or one of its ancestors
  // supports |type|.
  bool GetValueAndStatusForTypeIfPossible(const ServerFieldType& type,
                                          std::u16string* value,
                                          VerificationStatus* status) const;

  // Get the value and status of a |type| identified by its name.
  // Returns false if the |type| is not supported by the structure.
  bool GetValueAndStatusForTypeIfPossible(const std::string& type_name,
                                          std::u16string* value,
                                          VerificationStatus* status) const;

  // Returns true if the |value| and |verification_status| were successfully
  // unset for |type|.
  bool UnsetValueForTypeIfSupported(const ServerFieldType& type);

  // Parses |value_| to assign values to the subcomponents.
  // The method uses 3 stages:
  //
  // * Use |ParseValueAndAssignSubcomponentsByMethod()|. This stage exists
  // to catch special cases and may fail. The method is virtual and can be
  // implemented on the type level.
  //
  // * Use |ParseValueAndAssignSubcomponentsByRegularExpressions()|. This stage
  // uses a list of regular expressions acquired by the virtual method
  // |GetParseRegularExpressionsByRelevance()|. This stage my fail.
  //
  // * Use |ParseValueAndAssignSubcomponentsByFallbackMethod()| as the last
  // resort to parse |value_|. This method must produce a valid result.
  void ParseValueAndAssignSubcomponents();

  // This methods populated the unassigned entries in the subtree of this node
  // by either parsing unknown values for subcomponents from their parents, or
  // vice versa, formatting unknown values from known subcomponents. The method
  // is virtual and can be reimplemented on the type level.
  virtual void RecursivelyCompleteTree();

  // Completes the full tree by calling |RecursivelyCompleteTree()| starting
  // form the root node. Returns true if the completion was successful.
  virtual bool CompleteFullTree();

  // Checks if a tree is completable in the sense that there are no conflicting
  // observed or verified types. This means that there is not more than one
  // observed or verified node on any root-to-leaf path in the tree.
  bool IsTreeCompletable();

  // Recursively adds the supported types to the set. Calls
  // |GetAdditionalSupportedFieldTypes()| to add field types.
  void GetSupportedTypes(ServerFieldTypeSet* supported_types) const;

  // Adds the additional supported field types to |supported_types|.
  // The method should DCHECK that the added types are not part of the set yet.
  virtual void GetAdditionalSupportedFieldTypes(
      ServerFieldTypeSet* supported_types) const {}

  // Unassigns all nodes with parsed or formatted values.
  void UnsetParsedAndFormattedValuesInEntireTree();

  // Unassigns all nodes with parsed or formatted values.
  void RecursivelyUnsetParsedAndFormattedValues();

  // Returns true if both components are mergeable.
  virtual bool IsMergeableWithComponent(
      const AddressComponent& newer_component) const;

  // Recursively updates the verification statuses to the higher one, for nodes
  // in |newer_component| that have the same values as the nodes in |this|.
  virtual void MergeVerificationStatuses(
      const AddressComponent& newer_component);

  // Merge |newer_component| into this AddressComponent.
  // Returns false if the merging is not possible.
  // The state of the component is not altered by a failed merging attempt.
  // |newer_was_more_recently_used| indicates that the newer component was also
  // more recently used for filling a form.
  virtual bool MergeWithComponent(const AddressComponent& newer_component,
                                  bool newer_was_more_recently_used = true);

  // Merge |newer_component| into this AddressComponent.
  // The merging is possible iff the value of both root nodes is token
  // equivalent, meaning they contain the same tokens in an arbitrary order.
  // Returns false if the merging is not possible.
  // The state of the component is not altered by a failed merging attempt.
  bool MergeTokenEquivalentComponent(const AddressComponent& newer_component);

  // Returns a constant vector of pointers to the child nodes of the component.
  const std::vector<AddressComponent*>& Subcomponents() const {
    return subcomponents_;
  }

  // Returns a vector containing sorted normalized tokens of the
  // value of the component. The tokens are lazily calculated when first needed.
  const std::vector<AddressToken> GetSortedTokens() const;

  // Recursively unsets all subcomponents.
  void RecursivelyUnsetSubcomponents();

  // Return if the value associated with |field_type_name| is valid.
  // If |wipe_if_not|, the value is unset if invalid.
  bool IsValueForTypeValid(const std::string& field_type_name,
                           bool wipe_if_not = false);

  // Convenience wrapper to work the ServerFieldTypes.
  bool IsValueForTypeValid(ServerFieldType field_type,
                           bool wipe_if_not = false);

  // Recursively determines the validity status of a component value associated
  // with |field_type_name|.  If |wipe_if_not|, the value is unset if invalid.
  // Returns true if it is possible to determine the validity status of the
  // value in this subcomponent.
  bool GetIsValueForTypeValidIfPossible(const std::string& field_type_name,
                                        bool* validity_status,
                                        bool wipe_if_not = false);

  // Deletes the stored structure and returns true if |IsStructureValid()|
  // returns false.
  virtual bool WipeInvalidStructure();

  // Returns if the structure in the tree below this node is valid. A structure
  // becomes invalid when it contains information that is not contained in the
  // value of this node.
  bool IsStructureValid() const;

  // Returns true if all values of all descendent nodes are empty.
  bool AllDescendantsAreEmpty() const;

#ifdef UNIT_TEST
  // Initiates the formatting of the values from the subcomponents.
  void FormatValueFromSubcomponentsForTesting() {
    FormatValueFromSubcomponents();
  }

  // Returns the best format string for testing.
  std::u16string GetBestFormatStringForTesting() {
    return GetBestFormatString();
  }

  // Returns the parse expressions by relevance for testing.
  std::vector<const re2::RE2*>
  GetParseRegularExpressionsByRelevanceForTesting() {
    return GetParseRegularExpressionsByRelevance();
  }

  // Returns a reference to the root node of the tree for testing.
  AddressComponent& GetRootNodeForTesting() { return GetRootNode(); }

  // Replaces placeholder values in the best format string with the
  // corresponding values.
  std::u16string GetReplacedPlaceholderTypesWithValuesForTesting() const {
    return ReplacePlaceholderTypesWithValues(GetBestFormatString());
  }

  // Returns a vector containing the |storage_types_| of all direct
  // subcomponents.
  std::vector<ServerFieldType> GetSubcomponentTypesForTesting() const {
    return GetSubcomponentTypes();
  }

  // Sets the merge mode for testing purposes.
  void SetMergeModeForTesting(int merge_mode) { merge_mode_ = merge_mode; }

  // Returns the value used for comparison for testing purposes.
  std::u16string ValueForComparisonForTesting() const {
    return ValueForComparison();
  }
#endif

 protected:
  // Returns the verification score of this component and its substructure.
  // Each observed node contributes to the validation score by 1.
  virtual int GetStructureVerificationScore() const;

  // Returns a vector containing the |storage_types_| of all direct
  // subcomponents.
  std::vector<ServerFieldType> GetSubcomponentTypes() const;

  // Heuristic method to get the best suited format string.
  // This method is virtual and can be reimplemented for each type.
  virtual std::u16string GetBestFormatString() const;

  // Returns pointers to regular expressions sorted by their relevance.
  // This method is virtual and can be reimplemented for each type.
  virtual std::vector<const re2::RE2*> GetParseRegularExpressionsByRelevance()
      const;

  // Method to parse |value_| into the values of |subcomponents_|. The
  // purpose of this method is to cover special cases. This method returns true
  // on success and is allowed to fail. On failure, the |subcomponents_| are not
  // altered.
  virtual bool ParseValueAndAssignSubcomponentsByMethod();

  // This method parses |value_| to assign values to the subcomponents.
  // The method is virtual and can be reimplemented per type.
  // It must succeed.
  virtual void ParseValueAndAssignSubcomponentsByFallbackMethod();

  // This method is used to set the value given by a type different than the
  // storage type. It must implement the conversion logic specific to each type.
  // It returns true if conversion logic exists and the type can be set.
  virtual bool ConvertAndSetValueForAdditionalFieldTypeName(
      const std::string& field_type_name,
      const std::u16string& value,
      const VerificationStatus& status);

  // This method is used to retrieve the value for a supported field type
  // different from the storage type. It must implement the conversion logic
  // specific to each type. It returns true if the type is supported and the
  // value can be written back to value.
  // The method must handle |nullptr|s for both the value and status.
  virtual bool ConvertAndGetTheValueForAdditionalFieldTypeName(
      const std::string& field_type_name,
      std::u16string* value) const;

  // Clears all parsed and formatted values.
  void ClearAllParsedAndFormattedValues();

  // Merge a component that has exactly one token less.
  bool MergeSubsetComponent(
      const AddressComponent& subset_component,
      const SortedTokenComparisonResult& token_comparison_result);

  // Consumes an additional token into the most appropriate subcomponent.
  // Can be implemented by the specific node types.
  // The fall-back solution uses the first empty node.
  // If no empty node is available, it appends the value to the first node.
  virtual void ConsumeAdditionalToken(const std::u16string& token_value);

  // Returns a reference to the root node of the tree.
  AddressComponent& GetRootNode();

  // Returns a reference to the root node of the tree.
  const AddressComponent& GetRootNode() const;

  // Function to determine if the value stored in this component is valid.
  // Return true be default but can be overloaded by a subclass.
  virtual bool IsValueValid() const;

  // Function to be called post assign to do sanitization.
  virtual void PostAssignSanitization() {}

  // Returns a normalized value for comparison.
  // In the default implementation, this converts the value to lower case and
  // removes white spaces. This function may be reimplemented to perform
  // different normalization operations.
  virtual std::u16string NormalizedValue() const;

  // Returns a value used for comparison.
  // In the default implementation this is just the normalized value but this
  // function can be overridden in subclasses to apply further operations on
  // the normalized value.
  virtual std::u16string ValueForComparison() const;

  // Returns true if the merging of two token identical values should give
  // precedence to the newer value. By default, the newer component gets
  // precedence if it has the same or better verification status.
  virtual bool HasNewerValuePrecendenceInMerging(
      const AddressComponent& newer_component) const;

  // Parses |value| by using |parse_expressions| and assigns the values.
  // Returns true on success.
  bool ParseValueAndAssignSubcomponentsByRegularExpression(
      const std::u16string& value,
      const re2::RE2* parse_expression);

  // Determines and sets a formatted value using
  // |GetFormattedValueFromSubcomponents|.
  void FormatValueFromSubcomponents();

  // Returns the maximum number of components with assigned values on the path
  // from the component to a leaf node.
  int MaximumNumberOfAssignedAddressComponentsOnNodeToLeafPaths() const;

 private:
  // Function to be called by child nodes on construction to register
  // themselves as child nodes.
  void RegisterChildNode(AddressComponent* child);

  // Unsets the node and all of its children.
  void UnsetAddressComponentAndItsSubcomponents();

  // Unsets the children of a node.
  void UnsetSubcomponents();

  // Determines a value from the subcomponents by using the
  // most suitable format string determined by |GetBestFormatString()|.
  std::u16string GetFormattedValueFromSubcomponents();

  // Replaces placeholder values with the corresponding values.
  std::u16string ReplacePlaceholderTypesWithValues(
      const std::u16string& format) const;

  // Replaces placeholder values with the corresponding values.
  std::u16string ReplacePlaceholderTypesWithValuesRegexVersion(
      const std::u16string& format) const;

  // This method uses regular expressions acquired by
  // |GetParseRegularExpressionsByRelevance| to parse |value_| into the values
  // of the subcomponents. Returns true on success and is allowed to fail.
  bool ParseValueAndAssignSubcomponentsByRegularExpressions();

  // The unstructured value of this component.
  absl::optional<std::u16string> value_;

  // The verification status of |value_| indicates the certainty of the value
  // to be correct.
  VerificationStatus value_verification_status_;

  // The storable Autofill type of the component.
  const ServerFieldType storage_type_;

  // A vector of pointers to the subcomponents.
  std::vector<AddressComponent*> subcomponents_;

  // A vector that contains the tokens of |value_| after normalization,
  // meaning that it was converted to lower case and diacritics have been
  // removed. |value_| is tokenized by splitting the string by white spaces and
  // commas. It is calculated when |value_| is set.
  absl::optional<std::vector<AddressToken>> sorted_normalized_tokens_;

  // A pointer to the parent node. It is set to nullptr if the node is the root
  // node of the AddressComponent tree.
  const raw_ptr<AddressComponent> parent_;

  // Defines if and how two components can be merged.
  int merge_mode_;
};

}  // namespace structured_address

}  // namespace autofill
#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_COMPONENT_H_


text:
import { IFileService } from 'vs/platform/files/common/files';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { ILogService } from 'vs/platform/log/common/log';
import { WorkingCopyBackupService } from 'vs/workbench/services/workingCopy/common/workingCopyBackupService';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IWorkingCopyBackupService } from 'vs/workbench/services/workingCopy/common/workingCopyBackup';
import { joinPath } from 'vs/base/common/resources';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Registry } from 'vs/platform/registry/common/platform';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { BrowserWorkingCopyBackupTracker } from 'vs/workbench/services/workingCopy/browser/workingCopyBackupTracker';

export class BrowserWorkingCopyBackupService extends WorkingCopyBackupService {

	constructor(
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
		@IFileService fileService: IFileService,
		@ILogService logService: ILogService
	) {
		super(joinPath(environmentService.userRoamingDataHome, 'Backups', contextService.getWorkspace().id), fileService, logService);
	}
}

// Register Service
registerSingleton(IWorkingCopyBackupService, BrowserWorkingCopyBackupService);

// Register Backup Tracker
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(BrowserWorkingCopyBackupTracker, LifecyclePhase.Starting);

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: About
permalink: /about/
published: true
---

My primary occupation is to develop and improve the performance of scientific applications running on some of the worlds largest Cray Supercomputers.

I also dabble in web programming, riding bikes, skiing, and climbing things.

### Contact me

[rmolson@gmail.com](mailto:rmolson@gmail.com)


text:
package Google::Ads::AdWords::v201809::DraftAsyncError;
use strict;
use warnings;

__PACKAGE__->_set_element_form_qualified(1);

sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' };

our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;

sub __get_attr_class {
    return $XML_ATTRIBUTE_CLASS;
}

use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);

{ # BLOCK to scope variables

my %baseCampaignId_of :ATTR(:get<baseCampaignId>);
my %draftId_of :ATTR(:get<draftId>);
my %draftCampaignId_of :ATTR(:get<draftCampaignId>);
my %asyncError_of :ATTR(:get<asyncError>);
my %baseAdGroupId_of :ATTR(:get<baseAdGroupId>);
my %draftAdGroupId_of :ATTR(:get<draftAdGroupId>);

__PACKAGE__->_factory(
    [ qw(        baseCampaignId
        draftId
        draftCampaignId
        asyncError
        baseAdGroupId
        draftAdGroupId

    ) ],
    {
        'baseCampaignId' => \%baseCampaignId_of,
        'draftId' => \%draftId_of,
        'draftCampaignId' => \%draftCampaignId_of,
        'asyncError' => \%asyncError_of,
        'baseAdGroupId' => \%baseAdGroupId_of,
        'draftAdGroupId' => \%draftAdGroupId_of,
    },
    {
        'baseCampaignId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
        'draftId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
        'draftCampaignId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
        'asyncError' => 'Google::Ads::AdWords::v201809::ApiError',
        'baseAdGroupId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
        'draftAdGroupId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
    },
    {

        'baseCampaignId' => 'baseCampaignId',
        'draftId' => 'draftId',
        'draftCampaignId' => 'draftCampaignId',
        'asyncError' => 'asyncError',
        'baseAdGroupId' => 'baseAdGroupId',
        'draftAdGroupId' => 'draftAdGroupId',
    }
);

} # end BLOCK

1;

=pod

=head1 NAME

Google::Ads::AdWords::v201809::DraftAsyncError

=head1 DESCRIPTION

Perl data type class for the XML Schema defined complexType
DraftAsyncError from the namespace https://adwords.google.com/api/adwords/cm/v201809.

An error that has occurred while asynchronously processing the promotion of a draft.

=head2 PROPERTIES

The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:

=over

=item * baseCampaignId

=item * draftId

=item * draftCampaignId

=item * asyncError

=item * baseAdGroupId

=item * draftAdGroupId

=back

=head1 METHODS

=head2 new

Constructor. The following data structure may be passed to new():

=head1 AUTHOR

Generated by SOAP::WSDL

=cut


text:
:information_source:
If this is your first pull request to Bioconda please ping `@bioconda/core` so it can be reviewed and to request being added as a member of the Bioconda team. Members of the Bioconda team are able to merge their own pull requests once tests and linting have passed.

----------------

* [ ] I have read the [guidelines for bioconda recipes](https://bioconda.github.io/guidelines.html).
* [ ] This PR adds a new recipe.
* [ ] AFAIK, this recipe **is directly relevant to the biological sciences** (otherwise, please submit to the more general purpose [conda-forge channel](https://conda-forge.org/docs/)).
* [ ] This PR updates an existing recipe.
* [ ] This PR does something else (explain below).


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tab_layout"/>
</RelativeLayout>


text:
<!doctype html>{% load i18n %}{% load static %}

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  {% block meta %}{% endblock meta %}
  <title>{% block title %}{% trans "Home" %}{% endblock title %} | {% trans "Higher Ed Outcomes" %} | {% trans "The Texas Tribune" %}</title>
  <link rel="canonical" href="https://schools.texastribune.org{{ request.path }}" />

  <link rel="stylesheet" href="{% static 'styles/main.css' %}">

  {% block extra_head %}{% endblock extra_head %}

{% block header %}{% endblock header %}

{% block search %}{% endblock search %}

{% block extra_content %}{% endblock %}

{% block breadcrumbs %}{% endblock breadcrumbs %}
{% block content %}{% endblock content %}

{% block footer_ad %}
{% include "includes/ad_slot_footer.html" %}
{% endblock footer_ad %}

{% block footer %}

© {% now "Y" %} The Texas Tribune

About Us

Contact Us

Who Funds Us?

Terms of Service

Code of Ethics

Privacy Policy

Donate

{% endblock footer %}

{% block data_script %}{% endblock data_script %}

{% block extra_script %}{% endblock extra_script %}


text:
package com.hyphenate.easeui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.easeui.R;

/**
 * title bar
 *
 */
public class EaseTitleBar extends RelativeLayout{

    protected RelativeLayout leftLayout;
    protected ImageView leftImage;
    protected RelativeLayout rightLayout;
    protected ImageView rightImage;
    protected TextView titleView;
    protected RelativeLayout titleLayout;

    public EaseTitleBar(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs);
    }

    public EaseTitleBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public EaseTitleBar(Context context) {
        super(context);
        init(context, null);
    }

    private void init(Context context, AttributeSet attrs){
        LayoutInflater.from(context).inflate(R.layout.ease_widget_title_bar, this);
        leftLayout = (RelativeLayout) findViewById(R.id.left_layout);
        leftImage = (ImageView) findViewById(R.id.left_image);
        rightLayout = (RelativeLayout) findViewById(R.id.right_layout);
        rightImage = (ImageView) findViewById(R.id.right_image);
        titleView = (TextView) findViewById(R.id.title);
        titleLayout = (RelativeLayout) findViewById(R.id.root);

        parseStyle(context, attrs);
    }

    private void parseStyle(Context context, AttributeSet attrs){
        if(attrs != null){
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.EaseTitleBar);
            String title = ta.getString(R.styleable.EaseTitleBar_titleBarTitle);
            titleView.setText(title);

            Drawable leftDrawable = ta.getDrawable(R.styleable.EaseTitleBar_titleBarLeftImage);
            if (null != leftDrawable) {
                leftImage.setImageDrawable(leftDrawable);
            }
            Drawable rightDrawable = ta.getDrawable(R.styleable.EaseTitleBar_titleBarRightImage);
            if (null != rightDrawable) {
                rightImage.setImageDrawable(rightDrawable);
            }

            Drawable background = ta.getDrawable(R.styleable.EaseTitleBar_titleBarBackground);
            if(null != background) {
                titleLayout.setBackgroundDrawable(background);
            }

            ta.recycle();
        }
    }

    public void setLeftImageResource(int resId) {
        leftImage.setImageResource(resId);
    }

    public void setRightImageResource(int resId) {
        rightImage.setImageResource(resId);
    }

    public void setLeftLayoutClickListener(OnClickListener listener){
        leftLayout.setOnClickListener(listener);
    }

    public void setRightLayoutClickListener(OnClickListener listener){
        rightLayout.setOnClickListener(listener);
    }

    public void setLeftLayoutVisibility(int visibility){
        leftLayout.setVisibility(visibility);
    }

    public void setRightLayoutVisibility(int visibility){
        rightLayout.setVisibility(visibility);
    }

    public void setTitle(String title){
        titleView.setText(title);
    }

    public void setBackgroundColor(int color){
        titleLayout.setBackgroundColor(color);
    }

    public RelativeLayout getLeftLayout(){
        return leftLayout;
    }

    public RelativeLayout getRightLayout(){
        return rightLayout;
    }
}


text:
cron
====

[![Build Status](https://travis-ci.org/resios/cron.svg?branch=master)](https://travis-ci.org/resios/cron)
[![Coverage Status](https://coveralls.io/repos/github/resios/cron/badge.svg?branch=master)](https://coveralls.io/github/resios/cron?branch=master)
[![Coverity Scan Build](https://scan.coverity.com/projects/8129/badge.svg)](https://scan.coverity.com/projects/8129)

 Cron expression parser and evaluator.

 Allows for specifying cron - expressions (in Unix or [Quartz](http://quartz-scheduler.org/api/2.2.0/org/quartz/CronExpression.html) like format) and evaluating when it will next match.

 Since it's specified on Joda-time it allows for easy integration into unit testing and simulations, by adjusting the Joda-time offset to speed up executions.

usage
=====
 See javadoc


text:
/* zstd_decompress_internal:
 * objects and definitions shared within lib/decompress modules */

 #ifndef ZSTD_DECOMPRESS_INTERNAL_H
 #define ZSTD_DECOMPRESS_INTERNAL_H

/*-*******************************************************
 *  Dependencies
 *********************************************************/
#include "mem.h"             /* BYTE, U16, U32 */
#include "zstd_internal.h"   /* ZSTD_seqSymbol */

/*-*******************************************************
 *  Constants
 *********************************************************/
static const U32 LL_base[MaxLL+1] = {
                 0,    1,    2,     3,     4,     5,     6,      7,
                 8,    9,   10,    11,    12,    13,    14,     15,
                16,   18,   20,    22,    24,    28,    32,     40,
                48,   64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
                0x2000, 0x4000, 0x8000, 0x10000 };

static const U32 OF_base[MaxOff+1] = {
                 0,        1,       1,       5,     0xD,     0x1D,     0x3D,     0x7D,
                 0xFD,   0x1FD,   0x3FD,   0x7FD,   0xFFD,   0x1FFD,   0x3FFD,   0x7FFD,
                 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD,
                 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD, 0x1FFFFFFD, 0x3FFFFFFD, 0x7FFFFFFD };

static const U32 OF_bits[MaxOff+1] = {
                     0,  1,  2,  3,  4,  5,  6,  7,
                     8,  9, 10, 11, 12, 13, 14, 15,
                    16, 17, 18, 19, 20, 21, 22, 23,
                    24, 25, 26, 27, 28, 29, 30, 31 };

static const U32 ML_base[MaxML+1] = {
                     3,  4,  5,    6,     7,     8,     9,    10,
                    11, 12, 13,   14,    15,    16,    17,    18,
                    19, 20, 21,   22,    23,    24,    25,    26,
                    27, 28, 29,   30,    31,    32,    33,    34,
                    35, 37, 39,   41,    43,    47,    51,    59,
                    67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803,
                    0x1003, 0x2003, 0x4003, 0x8003, 0x10003 };

/*-*******************************************************
 *  Decompression types
 *********************************************************/
 typedef struct {
     U32 fastMode;
     U32 tableLog;
 } ZSTD_seqSymbol_header;

 typedef struct {
     U16  nextState;
     BYTE nbAdditionalBits;
     BYTE nbBits;
     U32  baseValue;
 } ZSTD_seqSymbol;

 #define SEQSYMBOL_TABLE_SIZE(log)   (1 + (1 << (log)))

typedef struct {
    ZSTD_seqSymbol LLTable[SEQSYMBOL_TABLE_SIZE(LLFSELog)];    /* Note : Space reserved for FSE Tables */
    ZSTD_seqSymbol OFTable[SEQSYMBOL_TABLE_SIZE(OffFSELog)];   /* is also used as temporary workspace while building hufTable during DDict creation */
    ZSTD_seqSymbol MLTable[SEQSYMBOL_TABLE_SIZE(MLFSELog)];    /* and therefore must be at least HUF_DECOMPRESS_WORKSPACE_SIZE large */
    HUF_DTable hufTable[HUF_DTABLE_SIZE(HufLog)];  /* can accommodate HUF_decompress4X */
    U32 rep[ZSTD_REP_NUM];
} ZSTD_entropyDTables_t;

typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader,
               ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock,
               ZSTDds_decompressLastBlock, ZSTDds_checkChecksum,
               ZSTDds_decodeSkippableHeader, ZSTDds_skipFrame } ZSTD_dStage;

typedef enum { zdss_init=0, zdss_loadHeader,
               zdss_read, zdss_load, zdss_flush } ZSTD_dStreamStage;

typedef enum {
    ZSTD_use_indefinitely = -1,  /* Use the dictionary indefinitely */
    ZSTD_dont_use = 0,           /* Do not use the dictionary (if one exists free it) */
    ZSTD_use_once = 1            /* Use the dictionary once and set to ZSTD_dont_use */
} ZSTD_dictUses_e;

struct ZSTD_DCtx_s
{
    const ZSTD_seqSymbol* LLTptr;
    const ZSTD_seqSymbol* MLTptr;
    const ZSTD_seqSymbol* OFTptr;
    const HUF_DTable* HUFptr;
    ZSTD_entropyDTables_t entropy;
    U32 workspace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];   /* space needed when building huffman tables */
    const void* previousDstEnd;   /* detect continuity */
    const void* prefixStart;      /* start of current segment */
    const void* virtualStart;     /* virtual start of previous segment if it was just before current one */
    const void* dictEnd;          /* end of previous segment */
    size_t expected;
    ZSTD_frameHeader fParams;
    U64 decodedSize;
    blockType_e bType;            /* used in ZSTD_decompressContinue(), store blockType between block header decoding and block decompression stages */
    ZSTD_dStage stage;
    U32 litEntropy;
    U32 fseEntropy;
    XXH64_state_t xxhState;
    size_t headerSize;
    ZSTD_format_e format;
    const BYTE* litPtr;
    ZSTD_customMem customMem;
    size_t litSize;
    size_t rleSize;
    size_t staticSize;
    int bmi2;                     /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */

    /* dictionary */
    ZSTD_DDict* ddictLocal;
    const ZSTD_DDict* ddict;     /* set by ZSTD_initDStream_usingDDict(), or ZSTD_DCtx_refDDict() */
    U32 dictID;
    int ddictIsCold;             /* if == 1 : dictionary is "new" for working context, and presumed "cold" (not in cpu cache) */
    ZSTD_dictUses_e dictUses;

    /* streaming */
    ZSTD_dStreamStage streamStage;
    char*  inBuff;
    size_t inBuffSize;
    size_t inPos;
    size_t maxWindowSize;
    char*  outBuff;
    size_t outBuffSize;
    size_t outStart;
    size_t outEnd;
    size_t lhSize;
    void* legacyContext;
    U32 previousLegacyVersion;
    U32 legacyVersion;
    U32 hostageByte;
    int noForwardProgress;

    /* workspace */
    BYTE litBuffer[ZSTD_BLOCKSIZE_MAX + WILDCOPY_OVERLENGTH];
    BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX];
};  /* typedef'd to ZSTD_DCtx within "zstd.h" */

/*-*******************************************************
 *  Shared internal functions
 *********************************************************/

/*! ZSTD_loadDEntropy() :
 *  dict : must point at beginning of a valid zstd dictionary.
 * @return : size of entropy tables read */
size_t ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,
                   const void* const dict, size_t const dictSize);

/*! ZSTD_checkContinuity() :
 *  check if next `dst` follows previous position, where decompression ended.
 *  If yes, do nothing (continue on current segment).
 *  If not, classify previous segment as "external dictionary", and start a new segment.
 *  This function cannot fail. */
void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst);

#endif /* ZSTD_DECOMPRESS_INTERNAL_H */


text:
from awx.main import signals

class TestCleanupDetachedLabels:
    def test_cleanup_detached_labels_on_deleted_parent(self, mocker):
        mock_labels = [mocker.MagicMock(), mocker.MagicMock()]
        mock_instance = mocker.MagicMock()
        mock_instance.labels.all = mocker.MagicMock()
        mock_instance.labels.all.return_value = mock_labels
        mock_labels[0].is_candidate_for_detach.return_value = True
        mock_labels[1].is_candidate_for_detach.return_value = False

        signals.cleanup_detached_labels_on_deleted_parent(None, mock_instance)

        mock_labels[0].is_candidate_for_detach.assert_called_with()
        mock_labels[1].is_candidate_for_detach.assert_called_with()
        mock_labels[0].delete.assert_called_with()
        mock_labels[1].delete.assert_not_called()


text:
<?php

namespace ZF\Apigility\Admin\Model;

use ReflectionClass;
use Zend\Filter\FilterChain;
use Zend\Stdlib\Glob;
use ZF\Apigility\Admin\Exception;
use ZF\Configuration\ConfigResource;

class VersioningModel
{
    protected $configResource;

    protected $docsConfigResource;

    protected $moduleNameFilter;

    /**
     * @param  ConfigResource $config
     * @param  null|ConfigResource $docsConfig
     */
    public function __construct(ConfigResource $config, ConfigResource $docsConfig = null)
    {
        $this->configResource = $config;
        $this->docsConfigResource = $docsConfig;
    }

    /**
     * Create a new version for a module
     *
     * @param  string $module
     * @param  integer $version
     * @param  string $path
     * @return boolean
     */
    public function createVersion($module, $version, $path = false)
    {
        $module  = $this->normalizeModule($module);
        if (!$path) {
            $path = $this->getModuleSourcePath($module);
        }

        $versions = $this->getModuleVersions($module, $path);
        if (in_array($version, $versions)) {
            throw new Exception\InvalidArgumentException(sprintf(
                'The API version %d of the module %s already exists',
                $version,
                $module
            ));
        }

        $previous = (int) $version - 1;
        if (!in_array($previous, $versions)) {
            throw new Exception\RuntimeException(sprintf(
                'The previous API version %d doesn\'t exist, I cannot create version %d',
                $previous,
                $version
            ));
        }

        $this->recursiveCopy($path . '/V'. $previous, $path . '/V' . $version, $previous, $version);

        $configPath = $this->locateConfigPath($path);
        if ($configPath !== false) {
            foreach (Glob::glob($configPath . '/*.config.php') as $file) {
                $this->updateConfigVersion($module, $file, $previous, $version);
            }
        }

        return true;
    }

    /**
     * Get the versions of a module
     *
     * @param  string $module
     * @param  string $path
     * @return array|boolean
     */
    public function getModuleVersions($module, $path = false)
    {
        $module       = $this->normalizeModule($module);

        if (!$path) {
            $path = $this->getModuleSourcePath($module);
        }

        $versions  = [];
        foreach (Glob::glob($path . DIRECTORY_SEPARATOR . 'V*') as $dir) {
            if (preg_match('/\\V(?P<version>\d+)$/', $dir, $matches)) {
                $versions[] = (int) $matches['version'];
            }
        }
        return $versions;
    }

    /**
     * Updates the default version of a module that will be used if no version is
     * specified by the API consumer.
     *
     * @param  integer $defaultVersion
     * @return boolean
     */
    public function setDefaultVersion($defaultVersion)
    {
        $defaultVersion = (int) $defaultVersion;

        $this->configResource->patch([
            'zf-versioning' => [
                'default_version' => $defaultVersion
            ]
        ], true);

        $config = $this->configResource->fetch(true);

        return isset($config['zf-versioning']['default_version'])
            && ($config['zf-versioning']['default_version'] === $defaultVersion);
    }

    /**
     * Copy file and folder recursively
     *
     * @param string $source
     * @param string $target
     * @param int $previous
     * @param int $version
     */
    protected function recursiveCopy($source, $target, $previous, $version)
    {
        $dir = opendir($source);
        @mkdir($target);
        $nsSep   = preg_quote('\\');
        $pattern = sprintf(
            '#%sV%s%s#',
            $nsSep,
            $previous,
            $nsSep
        );
        while (false !== ($file = readdir($dir))) {
            if (($file == '.') || ($file == '..')) {
                continue;
            }

            $origin      = sprintf('%s/%s', $source, $file);
            $destination = sprintf('%s/%s', $target, $file);

            if (is_dir($origin)) {
                $this->recursiveCopy($origin, $destination, $previous, $version);
                continue;
            }

            $contents    = file_get_contents($origin);
            $newContents = preg_replace($pattern, '\V' . $version . '\\', $contents);
            file_put_contents($destination, $newContents);
        }
        closedir($dir);
    }

    /**
     * Update a PHP configuration file from $previous to $version version
     *
     * @param  string  $module
     * @param  string  $file
     * @param  integer $previous Previous version
     * @param  integer $version New version
     * @return boolean
     */
    protected function updateConfigVersion($module, $file, $previous, $version)
    {
        if (preg_match('#[/\\\\]documentation.config.php$#', $file)) {
            return $this->updateDocumentationVersion($module, $previous, $version);
        }

        $config = $this->configResource->fetch(true);
        if (empty($config)) {
            return false;
        }

        // update zf-hal.metadata_map
        if (isset($config['zf-hal']['metadata_map'])) {
            $newValues = $this->changeVersionArray($config['zf-hal']['metadata_map'], $previous, $version);
            $this->configResource->patch([
                'zf-hal' => ['metadata_map' => $newValues]
            ], true);
        }

        // update zf-rpc
        if (isset($config['zf-rpc'])) {
            $newValues = $this->changeVersionArray($config['zf-rpc'], $previous, $version);
            $this->configResource->patch([
                'zf-rpc' => $newValues
            ], true);
        }

        // update zf-rest
        if (isset($config['zf-rest'])) {
            $newValues = $this->changeVersionArray($config['zf-rest'], $previous, $version);
            $this->configResource->patch([
                'zf-rest' => $newValues
            ], true);
        }

        // update zf-content-negotiation
        if (isset($config['zf-content-negotiation'])) {
            foreach (['controllers', 'accept_whitelist', 'content_type_whitelist'] as $key) {
                if (isset($config['zf-content-negotiation'][$key])) {
                    $newValues = $this->changeVersionArray(
                        $config['zf-content-negotiation'][$key],
                        $previous,
                        $version
                    );

                    // change version in mediatype
                    if (in_array($key, ['accept_whitelist', 'content_type_whitelist'])) {
                        foreach ($newValues as $k => $v) {
                            foreach ($v as $index => $mediatype) {
                                if (strstr($mediatype, '.v' . $previous . '+')) {
                                    $newValues[$k][$index] = 'application/vnd.'
                                        . $this->getModuleNameFilter()->filter($module)
                                        . '.v'
                                        . $version
                                        . '+json';
                                }
                            }
                        }
                    }

                    $this->configResource->patch([
                        'zf-content-negotiation' => [$key => $newValues]
                    ], true);
                }
            }
        }

        // update zf-mvc-auth
        if (isset($config['zf-mvc-auth']['authorization'])) {
            $newValues = $this->changeVersionArray($config['zf-mvc-auth']['authorization'], $previous, $version);
            $this->configResource->patch([
                'zf-mvc-auth' => ['authorization' => $newValues]
            ], true);
        }

        // update zf-content-validation and input_filter_specs
        if (isset($config['zf-content-validation'])) {
            $newValues = $this->changeVersionArray($config['zf-content-validation'], $previous, $version);
            $this->configResource->patch([
                'zf-content-validation' => $newValues
            ], true);
        }

        if (isset($config['input_filter_specs'])) {
            $newValues = $this->changeVersionArray($config['input_filter_specs'], $previous, $version);
            $this->configResource->patch([
                'input_filter_specs' => $newValues
            ], true);
        }

        // update zf-apigility
        if (isset($config['zf-apigility']['db-connected'])) {
            $newValues = $this->changeVersionArray($config['zf-apigility']['db-connected'], $previous, $version);
            $this->configResource->patch([
                'zf-apigility' => ['db-connected' => $newValues]
            ], true);
        }

        // update service_manager
        if (isset($config['service_manager'])) {
            $newValues = $this->changeVersionArray($config['service_manager'], $previous, $version);
            $this->configResource->patch([
                'service_manager' => $newValues
            ], true);
        }

        // update controllers
        if (isset($config['controllers'])) {
            $newValues = $this->changeVersionArray($config['controllers'], $previous, $version);
            $this->configResource->patch([
                'controllers' => $newValues
            ], true);
        }

        return true;
    }

    /**
     * Change version in a namespace
     *
     * @param  string $string
     * @param  integer $previous
     * @param  integer $version
     * @return string
     */
    protected function changeVersionNamespace($string, $previous, $version)
    {
        return str_replace('\\V' . $previous . '\\', '\\V' . $version . '\\', $string);
    }

    /**
     * Change version in an array
     *
     * @param  array $data
     * @param  integer $previous
     * @param  integer $version
     * @return array
     */
    protected function changeVersionArray($data, $previous, $version)
    {
        $result = [];
        foreach ($data as $key => $value) {
            $newKey = $this->changeVersionNamespace($key, $previous, $version);
            if (is_array($value)) {
                $result[$newKey] = $this->changeVersionArray($value, $previous, $version);
            } else {
                $result[$newKey] = $this->changeVersionNamespace($value, $previous, $version);
            }
        }
        return $result;
    }

    /**
     * Normalize a module name
     *
     * Module names come over the wire dot-separated; make them namespaced.
     *
     * @param  string $module
     * @return string
     */
    protected function normalizeModule($module)
    {
        return str_replace('.', '\\', $module);
    }

    /**
     * Determine the source path for the module
     *
     * Usually, this is the "src/{modulename}" subdirectory of the
     * module.
     *
     * @param  string $module
     * @return string
     */
    protected function getModuleSourcePath($module)
    {
        $moduleClass = sprintf('%s\\Module', $module);

        if (!class_exists($moduleClass)) {
            throw new Exception\InvalidArgumentException(sprintf(
                'The module %s doesn\'t exist',
                $module
            ));
        }

        $r       = new ReflectionClass($moduleClass);
        $srcPath = dirname($r->getFileName());
        if (file_exists($srcPath . '/src') && is_dir($srcPath . '/src')) {
            $srcPath = sprintf('%s/src/%s', $srcPath, str_replace('\\', '/', $moduleClass));
        }

        if (!file_exists($srcPath) && !is_dir($srcPath)) {
            throw new Exception\InvalidArgumentException(sprintf(
                'The module "%s" has a malformed directory structure; cannot determine source path',
                $module
            ));
        }

        return $srcPath;
    }

    /**
     * Locate the config path for this module
     *
     * @param  string $srcPath
     * @return string|false
     */
    protected function locateConfigPath($srcPath)
    {
        $config = sprintf('%s/config', $srcPath);
        if (file_exists($config) && is_dir($config)) {
            return $config;
        }

        if ($srcPath == '.' || $srcPath == '/') {
            return false;
        }

        return $this->locateConfigPath(dirname($srcPath));
    }

    /**
     * Filter for module names
     *
     * @return FilterChain
     */
    protected function getModuleNameFilter()
    {
        if ($this->moduleNameFilter instanceof FilterChain) {
            return $this->moduleNameFilter;
        }

        $this->moduleNameFilter = new FilterChain();
        $this->moduleNameFilter->attachByName('Word\CamelCaseToDash')
            ->attachByName('StringToLower');
        return $this->moduleNameFilter;
    }

    /**
     * Update the documentation to add a new $version based on the $previous
     *
     * @param  string $module
     * @param  integer $previous Previous version
     * @param  integer $version New version
     * @return true
     */
    protected function updateDocumentationVersion($module, $previous, $version)
    {
        if (!$this->docsConfigResource) {
            // Nothing to do
            return true;
        }

        $originalDocs = $this->docsConfigResource->fetch(true);
        $newDocs = $this->changeVersionArray($originalDocs, $previous, $version);
        $this->docsConfigResource->patch($newDocs, true);
        return true;
    }
}


text:
@interface MOBProjectionEPSG2180 : MOBProjection

@end


text:
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace WinKernelObjectsDotNet
{
	/// <summary>
	/// The exception that is thrown when a call to an NT-API did not return 'STATUS_SUCCESS'
	/// </summary>
	[Serializable]
	public class NtStatusException : Exception, ISerializable
	{
		#region private fields...
		private NT_STATUS status;
		#endregion

		// constructors...
		#region NtStatusException()
		/// <summary>
		/// Constructs a new NtStatusException.
		/// </summary>
		public NtStatusException() { }
		#endregion
		#region NtStatusException(string message, NT_STATUS status)
		/// <summary>
		/// Constructs a new NtStatusException.
		/// </summary>
		/// <param name="message">The exception message</param>
		/// <param name="status">The value for the Status property.</param>
		public NtStatusException(string message, NT_STATUS status) : base(message)
		{
			this.status = status;
		}
		#endregion
		#region NtStatusException(string message, NT_STATUS status, Exception innerException)
		/// <summary>
		/// Constructs a new NtStatusException.
		/// </summary>
		/// <param name="message">The exception message.</param>
		/// <param name="status">The value for the Status property.</param>
		/// <param name="innerException">The inner exception.</param>
		public NtStatusException(string message, NT_STATUS status, Exception innerException) : base(message, innerException)
		{
			this.status = status;
		}
		#endregion
		#region NtStatusException(SerializationInfo info, StreamingContext context)
		/// <summary>
		/// Serialization constructor.
		/// </summary>
		protected NtStatusException(SerializationInfo info, StreamingContext context) : base(info, context)
		{
			this.status = (NT_STATUS)info.GetValue("Status", typeof(NT_STATUS));
		}
		#endregion

		// public methods...
		#region GetObjectData
		/// <summary>
		/// Overridden method from the ISerializable interface, to include the additional fields in serialization.
		/// </summary>
		[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			base.GetObjectData(info, context);
			info.AddValue("Status", Status);
		}
		#endregion

		// public properties...
		#region Message
		/// <summary>
		/// Overridden property from System.Exception, to include the additional fields in the message.
		/// </summary>
		public override string Message
		{
			get { return String.Format(CultureInfo.CurrentCulture, "{0}, Status: {1}", base.Message, Status); }
		}
		#endregion
		#region Status
		/// <summary>
		/// The returned error code.
		/// </summary>
		public NT_STATUS Status
		{
			get { return status; }
		}
		#endregion
	}
}


text:
'''
File: structures.py
Description: Message dispatcher related structures
Date: 29/09/2017
Author: Saurabh Badhwar <sbadhwar@redhat.com>
'''
import hashlib
import json

class Message(object):
    """Structure for handling new message types.

    Provides general functionality for all the messages to go through
    and pass there structural representation for validation.

    The message structure looks like:
    message = {
        message_name: [message_strcuture]
    }
    """

    def __init__(self):
        """Initialize the Message Structure"""

        self.messages = {}
        self.message_count = 0
        self.error_count = 0

    def add_message(self, message_name, message_structure):
        """Add a new message to the message structure

        Keyword arguments:
        message_name -- The name of the message
        message_strcuture -- The strcuture the message follows

        Raises:
            RuntimeError if message_name already exists
        """

        if message_name in self.messages.keys():
            raise RuntimeError("The specified message already exists")

        self.messages[message_name] = message_structure

    def get_message(self, message_name):
        """Get the message structure associated with the name

        Keyword arguments:
        message_name -- The name of the message whose structure is requested

        Raises:
            KeyError when the message is not found

        Returns:
            Mixed The message structure
        """

        if message_name not in self.messages.keys():
            raise KeyError("The requested message structure was not found")

        return self.messages[message_name]

    def get_message_list(self):
        """Get all the registered messages

        Return:
            List of registered messages
        """

        return self.messages.keys()

    def remove_message(self, message_name):
        """Remove the message from the registered list

        Keyword arguments:
        message_name -- The name of the message to be removed
        """

        if message_name in self.messages.keys():
            del self.messages[message_name]

class MessagePacket(object):
    """The message pakcet Structure for the Bolt Server

    Encapsulates the message along with a unique recognizable id so as to manage
    the message lifecycle

    Message Packet: {
        identifier: <unique_identifier>,
        message: Message
    }
    """

    def __init__(self, message):
        """Initialize the Message Packet"""

        self.message_packet = {}
        self.message_digest = hashlib.sha256(str(message)).hexdigest()
        self.message_packet['id'] = self.message_digest
        self.message_packet['payload'] = message

    def get_packet(self):
        """Get the JSON formatted packet which can be transmitted

        Returns: JSON
        """

        return (self.message_digest, json.dumps(self.message_packet))

class MessageQueue(object):
    """We use a message queue to track the responses received for the message

    Message Queue keeps a track of unique message identifiers along with the
    response they they generate so as to decide what to do next
    """

    def __init__(self):
        """Initialize the message queue"""

        self.message_queue = {}

    def queue(self, message_identifier):
        """Queue a newly sent message

        Keyword arguments:
        message_identifier -- The unique identifier pertaining to message
        """

        self.message_queue[message_identifier] = 'Awaited'

    def update_status(self, message_identifier, status):
        """Update the status of a sent message

        Keyword arguments:
        message_identifier -- The identifier to update
        status -- The new status of the message

        Raises:
            KeyError if the message is not present in the queue
        """

        if message_identifier not in self.message_queue.keys():
            raise KeyError("Cannot update status for an inexistant message")

        self.message_queue[message_identifier] = status


text:
{#
 #    Copyright (c) 2019-2020 Google LLC. All Rights Reserved.
 #    Copyright (c) 2016-2018 Nest Labs Inc. All Rights Reserved.
 #
 #    Licensed under the Apache License, Version 2.0 (the "License");
 #    you may not use this file except in compliance with the License.
 #    You may obtain a copy of the License at
 #
 #        http://www.apache.org/licenses/LICENSE-2.0
 #
 #    Unless required by applicable law or agreed to in writing, software
 #    distributed under the License is distributed on an "AS IS" BASIS,
 #    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 #    See the License for the specific language governing permissions and
 #    limitations under the License.
 #

 #
 #    Description:
 #      This file effects a Jinja-based openweave-core device C header
 #      trait code generation template for Weave Data Language (WDL) schema.
 #}
{% from 'common.macros' import include_guard, namespace_blocks, enum_def %}

{% do set_dest_file(c_header_file(typespace,suffix='-c')) -%}

{%- with schema_object=typespace -%}
{% include 'copyright.inc' %}
{% endwith %}

{% call include_guard(typespace, suffix='C_H') %}

{% if typespace.enum_list %}
    //
    // Enums
    //

    {% for enum in typespace.enum_list %}
    // {{enum.base_name}}
    typedef enum
    {
    {% for pair in enum.pair_list if pair.number != 0 %}
    {{ pair.base_name | underscore | upper }} = {{ pair.number }},
    {% endfor %}
    } {{full_c_name(enum)}}_t;
    {% endfor %}

{% endif %}

{% if typespace.constant_group_list %}
    //
    // Constants
    //

    {% for constant_group in typespace.constant_group_list %}
      {% for constant in constant_group.constant_list %}
    #define {{ (full_c_name(constant_group) ~ '_' ~ constant.base_name|replace(constant_group.base_name|underscore|upper~'_',''))|upper }} {
        {%- for byte in resource_id_bytes(constant.value) -%}
          0x{{ '%02x'|format(byte) }}{{ ', ' if not loop.last else '' }}
        {%- endfor -%}
    }
      {% endfor %}
    {% endfor %}

    {% for constant_group in typespace.constant_group_list %}
      {% for constant in constant_group.constant_list %}
    #define {{ (full_c_name(constant_group) ~ '_' ~ constant.base_name|replace(constant_group.base_name|underscore|upper~'_',''))|upper }}_IMP = (
        {%- for byte in resource_id_bytes(constant.value) -%}
          {{- '0x' ~ '%016x'|format(resource_id_number(constant.value)) }}ULL)
          {{- ' // ' ~ constant.value }}
        {%- endfor %}

      {% endfor %}
    {% endfor %}

{% endif %}

{% endcall %}{# include_guard #}


text:
set -x
set -e

# Install dependencies.
URI="deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main"
echo $URI | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
apt-get install -y apt-transport-https ca-certificates gnupg curl
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | \
  apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -
apt-get update && apt-get install -y google-cloud-sdk
apt-get install -y google-cloud-sdk-app-engine-java

# Setup auth.
gcloud init
gcloud auth application-default login --no-launch-browser


text:
<?php

namespace RectorPrefix20210615;

if (\class_exists('SC_login_frameset')) {
    return;
}
class SC_login_frameset
{
}
\class_alias('SC_login_frameset', 'SC_login_frameset', \false);


text:
import noteDAO from 'dao/NoteDAO'
import MongoClient from 'dao/MongoClient'

jest.mock('dao/MongoClient')

it('is MongoClient of note', () => {
  expect(noteDAO).toBeInstanceOf(MongoClient)
  expect(noteDAO).toEqual(new MongoClient('note'))
})


text:
var elastomer = require('../../../..')

require('../elasto-foo')
require('../elasto-qux')
require('../elasto-button')

module.exports = elastomer('elasto-layout', {
  html: require('./layout.html'),
  css: require('./style.css'),
  link: link
})

function link (scope, elasto) {
  // scope.model = {
  //   ctx: {
  //     path: '/foo'
  //   }
  // }
  // window.scope = scope
  // window.watchy = elastomer.watchy
  //
  // elasto.watch('model.ctx.path', function (val, old) {
  //   console.log('watch A', val, old)
  // })
  //
  // elasto.watch('model.ctx.path', function (val, old) {
  //   console.log('watch B', val, old)
  // })

  // elasto.watch('model.ctx.path', function (val, old) {
  //   console.log('watch B', val, old)
  // })
  //
  // elasto.watch('model.ctx.path', function (val, old) {
  //   console.log('watch C', val, old)
  // })
  //
  // elasto.watch('model.ctx.path', function (val, old) {
  //   console.log('watch D', val, old)
  // })

  scope.handleRemove = function () {
    elasto.host.parentElement.removeChild(elasto.host)
  }
}


text:
title: BaseMasterEditorLookUp
sidebar: flexberry-aspnet_sidebar
keywords: Flexberry ASP-NET, Web UI (Controls)
toc: true
permalink: en/fa_base-master-editor-lookup.html
lang: en
autotranslated: true
hash: 28447e29e2116a99b99dd4bdf8fca5fa8ead2eb2a290b3bef807c3adb4edf705
---

## Uniform changes in the properties of lyapov

Implemented two static delegate:
1. `InitLookUpSettings` - Delegate to initialize the settings. Settings you can override in the. aspx forms.
2. `ChangeLookUpSettings` - Delegate to change settings, which allows you to bring all lucapa to the uniform mind.

Example, you need to subscribe to in the Global.asax:

```csharp
BaseMasterEditorLookUp.ChangeLookUpSettings = AllForms.ChangeLookUpSettings;
```

```csharp
/// <summary>
/// Change settings lyapov
/// </summary>
/// <param name="lookup">Lookup who are changing the settings</param>
public static void ChangeLookUpSettings(BaseMasterEditorLookUp lookup)
{
    lookup.LookUpFormHeight = 640;
    lookup.LookUpFormWidth = 854;
    lookup.ShowInThickBox = true;
    lookup.LookUpFormCaption = "Choose a value";
}
```


text:
@interface FileReaderWindow : SkNSWindow {
    IBOutlet SkNSView* fView;
    ReaderView* fReaderView;
}
@end


text:
<!DOCTYPE html>
<html>
<head>
  <title>Vue.js Skeleton Project</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.0-beta5/vue.js"></script>
  <style>
    body {
      background-color: #ccc;
    }

    #app {}
  </style>
  <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
      'use strict';

      var vm = new Vue({ // jshint ignore:line
        el: '#app',
        data: {},
        methods: {}
      });
    });
  </script>
</head>
<body>
  <div id="app">

  </div>
</body>
</html>


text: export * from './dist/node/server'


text:
<?php

namespace Studna\Common\Exceptions;

/**
 * Class InvalidPasswordException
 * @package Studna\Common\Exceptions
 */
class InvalidPasswordException extends \Exception {}


text:
namespace PinballClientTests.ClientDisplays.DeviceInformation
{
    class SwitchConfigurationViewModelTests
    {
    }
}


text:
Update Mobile Bank Type

                            <form method="post" action="<?php echo base_url('admin/updateMobileBank/' . $mobile_bank->id) ?>" class="form-inline">
                                <?php if (validation_errors()) { ?>

                                        ×
                                        <?php echo validation_errors(); ?>

                                <?php } ?>

                                    Mobile Bank Type
                                    <input value="<?php echo $mobile_bank->mobile_bank_name; ?>" name="mobile_bank_name" class="form-control" type="text" placeholder="Enter Mobile Bank Type">

                                    <input class="btn btn-primary" type="submit" value="Update">

                            </form>


text:
package com.linecorp.centraldogma.server.command;

import static java.util.Objects.requireNonNull;

import java.util.List;
import java.util.Objects;

import javax.annotation.Nullable;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.collect.ImmutableList;

import com.linecorp.centraldogma.common.Author;
import com.linecorp.centraldogma.common.Change;
import com.linecorp.centraldogma.common.Markup;
import com.linecorp.centraldogma.common.Revision;

/**
 * A {@link Command} which is used for pushing changes to the repository.
 */
abstract class AbstractPushCommand<T> extends RepositoryCommand<T> {

    private final Revision baseRevision;
    private final String summary;
    private final String detail;
    private final Markup markup;
    private final List<Change<?>> changes;

    AbstractPushCommand(CommandType type, @Nullable Long timestamp, @Nullable Author author,
                        String projectName, String repositoryName, Revision baseRevision,
                        String summary, String detail, Markup markup, Iterable<Change<?>> changes) {
        super(type, timestamp, author, projectName, repositoryName);

        this.baseRevision = requireNonNull(baseRevision, "baseRevision");
        this.summary = requireNonNull(summary, "summary");
        this.detail = requireNonNull(detail, "detail");
        this.markup = requireNonNull(markup, "markup");

        requireNonNull(changes, "changes");
        this.changes = ImmutableList.copyOf(changes);
    }

    /**
     * Returns the base {@link Revision}.
     */
    @JsonProperty
    public Revision baseRevision() {
        return baseRevision;
    }

    /**
     * Returns the human-readable summary of the commit.
     */
    @JsonProperty
    public String summary() {
        return summary;
    }

    /**
     * Returns the human-readable detail of the commit.
     */
    @JsonProperty
    public String detail() {
        return detail;
    }

    /**
     * Returns the {@link Markup} of the {@link #detail()}.
     */
    @JsonProperty
    public Markup markup() {
        return markup;
    }

    /**
     * Returns the {@link Change}s of the commit.
     */
    @JsonProperty
    public List<Change<?>> changes() {
        return changes;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof AbstractPushCommand)) {
            return false;
        }

        final AbstractPushCommand that = (AbstractPushCommand) obj;
        return super.equals(that) &&
               baseRevision.equals(that.baseRevision) &&
               summary.equals(that.summary) &&
               detail.equals(that.detail) &&
               markup == that.markup &&
               changes.equals(that.changes);
    }

    @Override
    public int hashCode() {
        return Objects.hash(baseRevision, summary, detail, markup, changes) * 31 + super.hashCode();
    }

    @Override
    ToStringHelper toStringHelper() {
        return super.toStringHelper()
                    .add("baseRevision", baseRevision)
                    .add("summary", summary)
                    .add("detail", detail)
                    .add("markup", markup)
                    .add("changes", changes);
    }
}


text:
/********************************************************************
*
*	22. Write a program to check if an integer is within 20 of 100 or 200
*
*
* 	By: Jesus Hilario Hernandez
* 	Last Updated: October 11th 2017
*
*
********************************************************************/
using System;

public class Exercise_22
{
	public static void Main()
	{
		/************************
		 *	Jesus' Solution
		 ************************/
		Console.WriteLine("Enter your 1st integer: ");
		var number_1 = Convert.ToInt32(Console.ReadLine());

		var condition = number_1 >= 20 && number_1 <= 100 || number_1 == 200;

		if (condition)
			Console.WriteLine(condition + "\n"); // True
		else
			Console.WriteLine(condition + "\n"); // False
		/*******************************************
		 *	Jesus' Solution After checking response
		 *******************************************/
		Console.WriteLine("Enter your 1st integer: ");
		number_1 = Convert.ToInt32(Console.ReadLine());
		var condition2 = Math.Abs(number_1 - 100) <= 20 || Math.Abs(number_1 - 200) <= 20;
		if (condition2)
			Console.WriteLine(condition2);
		else
			Console.WriteLine(condition2);

		/**************************
		 *	W3resource's Solution
		 **************************/
		Console.WriteLine("\nInput an integer:");
		int x = Convert.ToInt32(Console.ReadLine());
		Console.WriteLine(result(x));
	}

	public static bool result(int n)
	{
		if (Math.Abs(n - 100) <= 10 || Math.Abs(n - 200) <= 10)
			return true;
		return false;
	}
}


text:
recordingFilename=$(date | md5sum | awk '{print $1}')
arecord -D plughw:1 -d 10 -f cd "/tmp/${recordingFilename}.wav" --max-file-time 30 &>/dev/null
echo "/tmp/${recordingFilename}.wav"


text:
// Name Type Value

#ifndef _Z_PML_NTV_UNSIGNED_VALUE_H_
#define _Z_PML_NTV_UNSIGNED_VALUE_H_

#include "ctk/ctk_config.h"

#include "ctk/pml/ntv_valuebase.h"

namespace ctk {
namespace pml {
namespace ntv {

    class CTK_API UnsignedValue : public ValueBase
    {
    public:
        typedef UnsignedValue _Self;
        typedef ValueBase _Super;
        typedef Uint64 store_type;
        typedef uint64 value_type;

    public:
        UnsignedValue(Unit* _owner=0);
        UnsignedValue(value_type _v, Unit* _owner=0);

        _Self& operator=(value_type _v);
        _Self& assign(value_type _v);

        const store_type& data() const;

        static _Self* create(value_type _v);

        virtual bool single() const;
        virtual _Self* clone() const;
        virtual std::ostream& dump(std::ostream& _os) const;
        virtual ctk::dumper& dump(ctk::dumper& _os) const;

    private:
        store_type data_;
    };

} // end of namespace ntv
} // end of namespace pml
} // end of namespace ctk

#endif // !_Z_PML_NTV_UNSIGNED_VALUE_H_


text:
from setuptools import setup, find_packages

setup(
    name='django-1.8-registration',
    version='0.2.0',
    description='Django Registration patched for Django 1.8',
    long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(),
    author='Unomena',
    author_email='dev@unomena.com',
    license='BSD',
    url='https://github.com/unomena/django-1.8-registration',
    packages = find_packages(),
    install_requires = [
    ],
    tests_require=[
        'django-setuptest>=0.1.2',
        'pysqlite>=2.5'
    ],
    test_suite="setuptest.setuptest.SetupTestSuite",
    include_package_data=True,
    classifiers = [
        "Programming Language :: Python",
        "License :: OSI Approved :: BSD License",
        "Development Status :: 4 - Beta",
        "Operating System :: OS Independent",
        "Framework :: Django",
        "Intended Audience :: Developers",
        "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
    ],
    zip_safe=False,
)


text:
namespace bluez {
namespace {
const char kErrorInvalidArgs[] = "org.freedesktop.DBus.Error.InvalidArgs";
const char kErrorPropertyReadOnly[] =
    "org.freedesktop.DBus.Error.PropertyReadOnly";
const char kErrorFailed[] = "org.freedesktop.DBus.Error.Failed";
}  // namespace

// The BluetoothGattDescriptorServiceProvider implementation used in production.
class BluetoothGattDescriptorServiceProviderImpl
    : public BluetoothGattDescriptorServiceProvider {
 public:
  BluetoothGattDescriptorServiceProviderImpl(
      dbus::Bus* bus,
      const dbus::ObjectPath& object_path,
      Delegate* delegate,
      const std::string& uuid,
      const std::vector<std::string>& permissions,
      const dbus::ObjectPath& characteristic_path)
      : origin_thread_id_(base::PlatformThread::CurrentId()),
        uuid_(uuid),
        bus_(bus),
        delegate_(delegate),
        object_path_(object_path),
        characteristic_path_(characteristic_path),
        weak_ptr_factory_(this) {
    VLOG(1) << "Created Bluetooth GATT characteristic descriptor: "
            << object_path.value() << " UUID: " << uuid;
    DCHECK(bus_);
    DCHECK(delegate_);
    DCHECK(!uuid_.empty());
    DCHECK(object_path_.IsValid());
    DCHECK(characteristic_path_.IsValid());
    DCHECK(base::StartsWith(object_path_.value(),
                            characteristic_path_.value() + "/",
                            base::CompareCase::SENSITIVE));

    exported_object_ = bus_->GetExportedObject(object_path_);

    exported_object_->ExportMethod(
        dbus::kDBusPropertiesInterface, dbus::kDBusPropertiesGet,
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::Get,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnExported,
                   weak_ptr_factory_.GetWeakPtr()));

    exported_object_->ExportMethod(
        dbus::kDBusPropertiesInterface, dbus::kDBusPropertiesSet,
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::Set,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnExported,
                   weak_ptr_factory_.GetWeakPtr()));

    exported_object_->ExportMethod(
        dbus::kDBusPropertiesInterface, dbus::kDBusPropertiesGetAll,
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::GetAll,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnExported,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  ~BluetoothGattDescriptorServiceProviderImpl() override {
    VLOG(1) << "Cleaning up Bluetooth GATT characteristic descriptor: "
            << object_path_.value();
    bus_->UnregisterExportedObject(object_path_);
  }

  // BluetoothGattDescriptorServiceProvider override.
  void SendValueChanged(const std::vector<uint8>& value) override {
    VLOG(2) << "Emitting a PropertiesChanged signal for descriptor value.";
    dbus::Signal signal(dbus::kDBusPropertiesInterface,
                        dbus::kDBusPropertiesChangedSignal);
    dbus::MessageWriter writer(&signal);
    dbus::MessageWriter array_writer(NULL);
    dbus::MessageWriter dict_entry_writer(NULL);
    dbus::MessageWriter variant_writer(NULL);

    // interface_name
    writer.AppendString(
        bluetooth_gatt_descriptor::kBluetoothGattDescriptorInterface);

    // changed_properties
    writer.OpenArray("{sv}", &array_writer);
    array_writer.OpenDictEntry(&dict_entry_writer);
    dict_entry_writer.AppendString(bluetooth_gatt_descriptor::kValueProperty);
    dict_entry_writer.OpenVariant("ay", &variant_writer);
    variant_writer.AppendArrayOfBytes(value.data(), value.size());
    dict_entry_writer.CloseContainer(&variant_writer);
    array_writer.CloseContainer(&dict_entry_writer);
    writer.CloseContainer(&array_writer);

    // invalidated_properties.
    writer.OpenArray("s", &array_writer);
    writer.CloseContainer(&array_writer);

    exported_object_->SendSignal(&signal);
  }

 private:
  // Returns true if the current thread is on the origin thread.
  bool OnOriginThread() {
    return base::PlatformThread::CurrentId() == origin_thread_id_;
  }

  // Called by dbus:: when the Bluetooth daemon fetches a single property of
  // the descriptor.
  void Get(dbus::MethodCall* method_call,
           dbus::ExportedObject::ResponseSender response_sender) {
    VLOG(2) << "BluetoothGattDescriptorServiceProvider::Get: "
            << object_path_.value();
    DCHECK(OnOriginThread());

    dbus::MessageReader reader(method_call);

    std::string interface_name;
    std::string property_name;
    if (!reader.PopString(&interface_name) ||
        !reader.PopString(&property_name) || reader.HasMoreData()) {
      scoped_ptr<dbus::ErrorResponse> error_response =
          dbus::ErrorResponse::FromMethodCall(method_call, kErrorInvalidArgs,
                                              "Expected 'ss'.");
      response_sender.Run(error_response.Pass());
      return;
    }

    // Only the GATT descriptor interface is supported.
    if (interface_name !=
        bluetooth_gatt_descriptor::kBluetoothGattDescriptorInterface) {
      scoped_ptr<dbus::ErrorResponse> error_response =
          dbus::ErrorResponse::FromMethodCall(
              method_call, kErrorInvalidArgs,
              "No such interface: '" + interface_name + "'.");
      response_sender.Run(error_response.Pass());
      return;
    }

    // If getting the "Value" property, obtain the value from the delegate.
    if (property_name == bluetooth_gatt_descriptor::kValueProperty) {
      DCHECK(delegate_);
      delegate_->GetDescriptorValue(
          base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnGet,
                     weak_ptr_factory_.GetWeakPtr(), method_call,
                     response_sender),
          base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnFailure,
                     weak_ptr_factory_.GetWeakPtr(), method_call,
                     response_sender));
      return;
    }

    scoped_ptr<dbus::Response> response =
        dbus::Response::FromMethodCall(method_call);
    dbus::MessageWriter writer(response.get());
    dbus::MessageWriter variant_writer(NULL);

    // TODO(armansito): Process the "Permissions" property below.
    if (property_name == bluetooth_gatt_descriptor::kUUIDProperty) {
      writer.OpenVariant("s", &variant_writer);
      variant_writer.AppendString(uuid_);
      writer.CloseContainer(&variant_writer);
    } else if (property_name ==
               bluetooth_gatt_descriptor::kCharacteristicProperty) {
      writer.OpenVariant("o", &variant_writer);
      variant_writer.AppendObjectPath(characteristic_path_);
      writer.CloseContainer(&variant_writer);
    } else {
      response = dbus::ErrorResponse::FromMethodCall(
          method_call, kErrorInvalidArgs,
          "No such property: '" + property_name + "'.");
    }

    response_sender.Run(response.Pass());
  }

  // Called by dbus:: when the Bluetooth daemon sets a single property of the
  // descriptor.
  void Set(dbus::MethodCall* method_call,
           dbus::ExportedObject::ResponseSender response_sender) {
    VLOG(2) << "BluetoothGattDescriptorServiceProvider::Set: "
            << object_path_.value();
    DCHECK(OnOriginThread());

    dbus::MessageReader reader(method_call);

    std::string interface_name;
    std::string property_name;
    dbus::MessageReader variant_reader(NULL);
    if (!reader.PopString(&interface_name) ||
        !reader.PopString(&property_name) ||
        !reader.PopVariant(&variant_reader) || reader.HasMoreData()) {
      scoped_ptr<dbus::ErrorResponse> error_response =
          dbus::ErrorResponse::FromMethodCall(method_call, kErrorInvalidArgs,
                                              "Expected 'ssv'.");
      response_sender.Run(error_response.Pass());
      return;
    }

    // Only the GATT descriptor interface is allowed.
    if (interface_name !=
        bluetooth_gatt_descriptor::kBluetoothGattDescriptorInterface) {
      scoped_ptr<dbus::ErrorResponse> error_response =
          dbus::ErrorResponse::FromMethodCall(
              method_call, kErrorInvalidArgs,
              "No such interface: '" + interface_name + "'.");
      response_sender.Run(error_response.Pass());
      return;
    }

    // Only the "Value" property is writeable.
    if (property_name != bluetooth_gatt_descriptor::kValueProperty) {
      std::string error_name;
      std::string error_message;
      if (property_name == bluetooth_gatt_descriptor::kUUIDProperty ||
          property_name == bluetooth_gatt_descriptor::kCharacteristicProperty) {
        error_name = kErrorPropertyReadOnly;
        error_message = "Read-only property: '" + property_name + "'.";
      } else {
        error_name = kErrorInvalidArgs;
        error_message = "No such property: '" + property_name + "'.";
      }
      scoped_ptr<dbus::ErrorResponse> error_response =
          dbus::ErrorResponse::FromMethodCall(method_call, error_name,
                                              error_message);
      response_sender.Run(error_response.Pass());
      return;
    }

    // Obtain the value.
    const uint8* bytes = NULL;
    size_t length = 0;
    if (!variant_reader.PopArrayOfBytes(&bytes, &length)) {
      scoped_ptr<dbus::ErrorResponse> error_response =
          dbus::ErrorResponse::FromMethodCall(
              method_call, kErrorInvalidArgs,
              "Property '" + property_name + "' has type 'ay'.");
      response_sender.Run(error_response.Pass());
      return;
    }

    // Pass the set request onto the delegate.
    std::vector<uint8> value(bytes, bytes + length);
    DCHECK(delegate_);
    delegate_->SetDescriptorValue(
        value, base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnSet,
                          weak_ptr_factory_.GetWeakPtr(), method_call,
                          response_sender),
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnFailure,
                   weak_ptr_factory_.GetWeakPtr(), method_call,
                   response_sender));
  }

  // Called by dbus:: when the Bluetooth daemon fetches all properties of the
  // descriptor.
  void GetAll(dbus::MethodCall* method_call,
              dbus::ExportedObject::ResponseSender response_sender) {
    VLOG(2) << "BluetoothGattDescriptorServiceProvider::GetAll: "
            << object_path_.value();
    DCHECK(OnOriginThread());

    dbus::MessageReader reader(method_call);

    std::string interface_name;
    if (!reader.PopString(&interface_name) || reader.HasMoreData()) {
      scoped_ptr<dbus::ErrorResponse> error_response =
          dbus::ErrorResponse::FromMethodCall(method_call, kErrorInvalidArgs,
                                              "Expected 's'.");
      response_sender.Run(error_response.Pass());
      return;
    }

    // Only the GATT descriptor interface is supported.
    if (interface_name !=
        bluetooth_gatt_descriptor::kBluetoothGattDescriptorInterface) {
      scoped_ptr<dbus::ErrorResponse> error_response =
          dbus::ErrorResponse::FromMethodCall(
              method_call, kErrorInvalidArgs,
              "No such interface: '" + interface_name + "'.");
      response_sender.Run(error_response.Pass());
      return;
    }

    // Try to obtain the value from the delegate. We will construct the
    // response in the success callback.
    DCHECK(delegate_);
    delegate_->GetDescriptorValue(
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnGetAll,
                   weak_ptr_factory_.GetWeakPtr(), method_call,
                   response_sender),
        base::Bind(&BluetoothGattDescriptorServiceProviderImpl::OnFailure,
                   weak_ptr_factory_.GetWeakPtr(), method_call,
                   response_sender));
  }

  // Called by dbus:: when a method is exported.
  void OnExported(const std::string& interface_name,
                  const std::string& method_name,
                  bool success) {
    LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "."
                              << method_name;
  }

  // Called by the Delegate in response to a method to call to get all
  // properties, in which the delegate has successfully returned the
  // descriptor value.
  void OnGetAll(dbus::MethodCall* method_call,
                dbus::ExportedObject::ResponseSender response_sender,
                const std::vector<uint8>& value) {
    VLOG(2) << "Descriptor value obtained from delegate. Responding to "
            << "GetAll.";

    scoped_ptr<dbus::Response> response =
        dbus::Response::FromMethodCall(method_call);
    dbus::MessageWriter writer(response.get());
    dbus::MessageWriter array_writer(NULL);
    dbus::MessageWriter dict_entry_writer(NULL);
    dbus::MessageWriter variant_writer(NULL);

    writer.OpenArray("{sv}", &array_writer);

    array_writer.OpenDictEntry(&dict_entry_writer);
    dict_entry_writer.AppendString(bluetooth_gatt_descriptor::kUUIDProperty);
    dict_entry_writer.AppendVariantOfString(uuid_);
    array_writer.CloseContainer(&dict_entry_writer);

    array_writer.OpenDictEntry(&dict_entry_writer);
    dict_entry_writer.AppendString(
        bluetooth_gatt_descriptor::kCharacteristicProperty);
    dict_entry_writer.AppendVariantOfObjectPath(characteristic_path_);
    array_writer.CloseContainer(&dict_entry_writer);

    array_writer.OpenDictEntry(&dict_entry_writer);
    dict_entry_writer.AppendString(bluetooth_gatt_descriptor::kValueProperty);
    dict_entry_writer.OpenVariant("ay", &variant_writer);
    variant_writer.AppendArrayOfBytes(value.data(), value.size());
    dict_entry_writer.CloseContainer(&variant_writer);
    array_writer.CloseContainer(&dict_entry_writer);

    // TODO(armansito): Process "Permissions" property.

    writer.CloseContainer(&array_writer);

    response_sender.Run(response.Pass());
  }

  // Called by the Delegate in response to a successful method call to get the
  // descriptor value.
  void OnGet(dbus::MethodCall* method_call,
             dbus::ExportedObject::ResponseSender response_sender,
             const std::vector<uint8>& value) {
    VLOG(2) << "Returning descriptor value obtained from delegate.";
    scoped_ptr<dbus::Response> response =
        dbus::Response::FromMethodCall(method_call);
    dbus::MessageWriter writer(response.get());
    dbus::MessageWriter variant_writer(NULL);

    writer.OpenVariant("ay", &variant_writer);
    variant_writer.AppendArrayOfBytes(value.data(), value.size());
    writer.CloseContainer(&variant_writer);

    response_sender.Run(response.Pass());
  }

  // Called by the Delegate in response to a successful method call to set the
  // descriptor value.
  void OnSet(dbus::MethodCall* method_call,
             dbus::ExportedObject::ResponseSender response_sender) {
    VLOG(2) << "Successfully set descriptor value. Return success.";
    response_sender.Run(dbus::Response::FromMethodCall(method_call));
  }

  // Called by the Delegate in response to a failed method call to get or set
  // the descriptor value.
  void OnFailure(dbus::MethodCall* method_call,
                 dbus::ExportedObject::ResponseSender response_sender) {
    VLOG(2) << "Failed to get/set descriptor value. Report error.";
    scoped_ptr<dbus::ErrorResponse> error_response =
        dbus::ErrorResponse::FromMethodCall(
            method_call, kErrorFailed, "Failed to get/set descriptor value.");
    response_sender.Run(error_response.Pass());
  }

  // Origin thread (i.e. the UI thread in production).
  base::PlatformThreadId origin_thread_id_;

  // 128-bit descriptor UUID of this object.
  std::string uuid_;

  // D-Bus bus object is exported on, not owned by this object and must
  // outlive it.
  dbus::Bus* bus_;

  // Incoming methods to get and set the "Value" property are passed on to the
  // delegate and callbacks passed to generate a reply. |delegate_| is generally
  // the object that owns this one and must outlive it.
  Delegate* delegate_;

  // D-Bus object path of object we are exporting, kept so we can unregister
  // again in our destructor.
  dbus::ObjectPath object_path_;

  // Object path of the GATT characteristic that the exported descriptor belongs
  // to.
  dbus::ObjectPath characteristic_path_;

  // D-Bus object we are exporting, owned by this object.
  scoped_refptr<dbus::ExportedObject> exported_object_;

  // Weak pointer factory for generating 'this' pointers that might live longer
  // than we do.
  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<BluetoothGattDescriptorServiceProviderImpl>
      weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(BluetoothGattDescriptorServiceProviderImpl);
};

BluetoothGattDescriptorServiceProvider::
    BluetoothGattDescriptorServiceProvider() {}

BluetoothGattDescriptorServiceProvider::
    ~BluetoothGattDescriptorServiceProvider() {}

// static
BluetoothGattDescriptorServiceProvider*
BluetoothGattDescriptorServiceProvider::Create(
    dbus::Bus* bus,
    const dbus::ObjectPath& object_path,
    Delegate* delegate,
    const std::string& uuid,
    const std::vector<std::string>& permissions,
    const dbus::ObjectPath& characteristic_path) {
  if (!bluez::BluezDBusManager::Get()->IsUsingStub()) {
    return new BluetoothGattDescriptorServiceProviderImpl(
        bus, object_path, delegate, uuid, permissions, characteristic_path);
  }
  return new FakeBluetoothGattDescriptorServiceProvider(
      object_path, delegate, uuid, permissions, characteristic_path);
}

}  // namespace bluez


text:
import os
import cPickle

def get_file_path():
    return os.path.dirname(os.path.realpath(__file__))

def load_text_data_set(dataset_name):
    data_set = cPickle.load(open(get_file_path() + '/textual/%s' % dataset_name, 'rb'))
    return data_set

def load_bimodal_data_set(dataset_name):
    data = cPickle.load(open(get_file_path() + '/bimodal/%s.p' % dataset_name, 'rb'))
    return data

def save_bimodal_data_set(bimodal_auto_encoder, data_set_name, embeddings_dict):
    output = {'embeddings_dict': embeddings_dict,
              'target_words': bimodal_auto_encoder.data_set['target_words'],
              'right_context_words': bimodal_auto_encoder.data_set['right_context_words']}
    path_ = get_file_path() + '/bimodal/' + data_set_name + '.p'
    cPickle.dump(output, open(path_, "wb"))