text:
/* { dg-do run { xfail { { cris-*-* crisv32-*-* h8300-*-* hppa*64*-*-* m32r-*-* mcore-*-* mn10300-*-* msp430*-*-* nds32*-*-* xstormy16-*-* v850*-*-* vax-*-* xtensa*-*-* } || { arm*-*-* && { ! arm32 } } } } } */
/* -mlongcall disables sibcall patterns.  */
/* { dg-skip-if "" { powerpc*-*-* } { "-mlongcall" } { "" } } */
/* { dg-options "-O2 -foptimize-sibling-calls" } */

/* The option -foptimize-sibling-calls is the default, but serves as
   marker.  This test is xfailed on targets without sibcall patterns
   (except targets where the test does not work due to the return address
   not saved on the regular stack).  */

extern void abort (void);
extern void exit (int);

/* Sibcalls are not supported in MIPS16 mode, which has direct calls but
   not direct jumps.  */
#ifdef __mips
#define ATTR __attribute__((nomips16))
#else
#define ATTR
#endif

static ATTR void recurser_void1 (int);
static ATTR void recurser_void2 (int);
extern void track (int);

int main ()
{
  recurser_void1 (0);
  exit (0);
}

/* The functions should get the same stack-frame, and best way to make it
   reasonably sure is to make them have the same contents (regarding the
   n tests).  */

static void __attribute__((noinline)) ATTR
recurser_void1 (int n)
{
  if (n == 0 || n == 7 || n == 8)
    track (n);

  if (n == 10)
    return;

  recurser_void2 (n + 1);
}

static void __attribute__((noinline)) ATTR
recurser_void2 (int n)
{
  if (n == 0 || n == 7 || n == 8)
    track (n);

  if (n == 10)
    return;

  recurser_void1 (n + 1);
}

void *trackpoint;

void __attribute__ ((noinline))
track (int n)
{
  char stackpos[1];

  if (n == 0)
    trackpoint = stackpos;
  else if ((n != 7 && n != 8) || trackpoint != stackpos)
    abort ();
}


text:
class ChromeHttpUserAgentSettings;
class ChromeNetworkDelegate;
class ChromeURLRequestContextGetter;
class ChromeExpectCTReporter;
class HostContentSettingsMap;
class MediaDeviceIDSalt;
class ProtocolHandlerRegistry;
class SupervisedUserURLFilter;

namespace chromeos {
class CertificateProvider;
}

namespace chrome_browser_net {
class ResourcePrefetchPredictorObserver;
}

namespace certificate_transparency {
class CTPolicyManager;
class TreeStateTracker;
}

namespace content_settings {
class CookieSettings;
}

namespace data_reduction_proxy {
class DataReductionProxyIOData;
}

namespace extensions {
class ExtensionThrottleManager;
class InfoMap;
}

namespace net {
class CertVerifier;
class ChannelIDService;
class ClientCertStore;
class CookieStore;
class CTVerifier;
class HttpServerProperties;
class HttpTransactionFactory;
class ProxyConfigService;
class ProxyService;
class ReportSender;
class SSLConfigService;
class TransportSecurityPersister;
class TransportSecurityState;
class URLRequestContextStorage;
class URLRequestJobFactoryImpl;
}  // namespace net

namespace policy {
class PolicyCertVerifier;
class PolicyHeaderIOHelper;
class URLBlacklistManager;
}  // namespace policy

// Conceptually speaking, the ProfileIOData represents data that lives on the IO
// thread that is owned by a Profile, such as, but not limited to, network
// objects like CookieMonster, HttpTransactionFactory, etc.  Profile owns
// ProfileIOData, but will make sure to delete it on the IO thread (except
// possibly in unit tests where there is no IO thread).
class ProfileIOData {
 public:
  typedef std::vector<scoped_refptr<ChromeURLRequestContextGetter>>
      ChromeURLRequestContextGetterVector;

  virtual ~ProfileIOData();

  static ProfileIOData* FromResourceContext(content::ResourceContext* rc);

  // Returns true if |scheme| is handled in Chrome, or by default handlers in
  // net::URLRequest.
  static bool IsHandledProtocol(const std::string& scheme);

  // Returns true if |url| is handled in Chrome, or by default handlers in
  // net::URLRequest.
  static bool IsHandledURL(const GURL& url);

  // Utility to install additional WebUI handlers into the |job_factory|.
  // Ownership of the handlers is transfered from |protocol_handlers|
  // to the |job_factory|.
  static void InstallProtocolHandlers(
      net::URLRequestJobFactoryImpl* job_factory,
      content::ProtocolHandlerMap* protocol_handlers);

  // Sets a global CertVerifier to use when initializing all profiles.
  static void SetCertVerifierForTesting(net::CertVerifier* cert_verifier);

  // Called by Profile.
  content::ResourceContext* GetResourceContext() const;

  // Initializes the ProfileIOData object and primes the RequestContext
  // generation. Must be called prior to any of the Get*() methods other than
  // GetResouceContext or GetMetricsEnabledStateOnIOThread.
  void Init(
      content::ProtocolHandlerMap* protocol_handlers,
      content::URLRequestInterceptorScopedVector request_interceptors) const;

  net::URLRequestContext* GetMainRequestContext() const;
  net::URLRequestContext* GetMediaRequestContext() const;
  net::URLRequestContext* GetExtensionsRequestContext() const;
  net::URLRequestContext* GetIsolatedAppRequestContext(
      net::URLRequestContext* main_context,
      const StoragePartitionDescriptor& partition_descriptor,
      std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
          protocol_handler_interceptor,
      content::ProtocolHandlerMap* protocol_handlers,
      content::URLRequestInterceptorScopedVector request_interceptors) const;
  net::URLRequestContext* GetIsolatedMediaRequestContext(
      net::URLRequestContext* app_context,
      const StoragePartitionDescriptor& partition_descriptor) const;

  // These are useful when the Chrome layer is called from the content layer
  // with a content::ResourceContext, and they want access to Chrome data for
  // that profile.
  extensions::InfoMap* GetExtensionInfoMap() const;
  extensions::ExtensionThrottleManager* GetExtensionThrottleManager() const;
  content_settings::CookieSettings* GetCookieSettings() const;
  HostContentSettingsMap* GetHostContentSettingsMap() const;

  IntegerPrefMember* session_startup_pref() const {
    return &session_startup_pref_;
  }

  StringPrefMember* google_services_account_id() const {
    return &google_services_user_account_id_;
  }

  net::URLRequestContext* extensions_request_context() const {
    return extensions_request_context_.get();
  }

  BooleanPrefMember* safe_browsing_enabled() const {
    return &safe_browsing_enabled_;
  }

  BooleanPrefMember* sync_disabled() const {
    return &sync_disabled_;
  }

  BooleanPrefMember* signin_allowed() const {
    return &signin_allowed_;
  }

  IntegerPrefMember* network_prediction_options() const {
    return &network_prediction_options_;
  }

  bool HasMediaDeviceIDSalt() const {
    return media_device_id_salt_.get() != nullptr;
  }

  std::string GetMediaDeviceIDSalt() const;

  DevToolsNetworkControllerHandle* network_controller_handle() const {
    return &network_controller_handle_;
  }

  net::TransportSecurityState* transport_security_state() const {
    return transport_security_state_.get();
  }

#if defined(OS_CHROMEOS)
  std::string username_hash() const {
    return username_hash_;
  }
#endif

  Profile::ProfileType profile_type() const {
    return profile_type_;
  }

  bool IsOffTheRecord() const;

  IntegerPrefMember* incognito_availibility() const {
    return &incognito_availibility_pref_;
  }

  chrome_browser_net::ResourcePrefetchPredictorObserver*
      resource_prefetch_predictor_observer() const {
    return resource_prefetch_predictor_observer_.get();
  }

  policy::PolicyHeaderIOHelper* policy_header_helper() const {
    return policy_header_helper_.get();
  }

#if defined(ENABLE_SUPERVISED_USERS)
  const SupervisedUserURLFilter* supervised_user_url_filter() const {
    return supervised_user_url_filter_.get();
  }
#endif

  // Initialize the member needed to track the metrics enabled state. This is
  // only to be called on the UI thread.
  void InitializeMetricsEnabledStateOnUIThread();

  // Returns whether or not metrics reporting is enabled in the browser instance
  // on which this profile resides. This is safe for use from the IO thread, and
  // should only be called from there.
  bool GetMetricsEnabledStateOnIOThread() const;

  void set_client_cert_store_factory_for_testing(
      const base::Callback<std::unique_ptr<net::ClientCertStore>()>& factory) {
    client_cert_store_factory_ = factory;
  }

  bool IsDataReductionProxyEnabled() const;

  data_reduction_proxy::DataReductionProxyIOData*
  data_reduction_proxy_io_data() const {
    return data_reduction_proxy_io_data_.get();
  }

  // This function is to be used to check if the |url| is defined in
  // blacklist or whitelist policy.
  virtual policy::URLBlacklist::URLBlacklistState GetURLBlacklistState(
      const GURL& url) const;

  // Returns the predictor service for this Profile. Returns nullptr if there is
  // no Predictor, as is the case with OffTheRecord profiles.
  virtual chrome_browser_net::Predictor* GetPredictor();

  // Get platform ClientCertStore. May return nullptr.
  std::unique_ptr<net::ClientCertStore> CreateClientCertStore();

 protected:
  // A URLRequestContext for media that owns its HTTP factory, to ensure
  // it is deleted.
  class MediaRequestContext : public net::URLRequestContext {
   public:
    MediaRequestContext();

    void SetHttpTransactionFactory(
        std::unique_ptr<net::HttpTransactionFactory> http_factory);

   private:
    ~MediaRequestContext() override;

    std::unique_ptr<net::HttpTransactionFactory> http_factory_;
  };

  // A URLRequestContext for apps that owns its cookie store and HTTP factory,
  // to ensure they are deleted.
  class AppRequestContext : public net::URLRequestContext {
   public:
    AppRequestContext();

    void SetCookieStore(std::unique_ptr<net::CookieStore> cookie_store);
    void SetChannelIDService(
        std::unique_ptr<net::ChannelIDService> channel_id_service);
    void SetHttpNetworkSession(
        std::unique_ptr<net::HttpNetworkSession> http_network_session);
    void SetHttpTransactionFactory(
        std::unique_ptr<net::HttpTransactionFactory> http_factory);
    void SetJobFactory(std::unique_ptr<net::URLRequestJobFactory> job_factory);

   private:
    ~AppRequestContext() override;

    std::unique_ptr<net::CookieStore> cookie_store_;
    std::unique_ptr<net::ChannelIDService> channel_id_service_;
    std::unique_ptr<net::HttpNetworkSession> http_network_session_;
    std::unique_ptr<net::HttpTransactionFactory> http_factory_;
    std::unique_ptr<net::URLRequestJobFactory> job_factory_;
  };

  // Created on the UI thread, read on the IO thread during ProfileIOData lazy
  // initialization.
  struct ProfileParams {
    ProfileParams();
    ~ProfileParams();

    base::FilePath path;
    IOThread* io_thread;
    scoped_refptr<content_settings::CookieSettings> cookie_settings;
    scoped_refptr<HostContentSettingsMap> host_content_settings_map;
    scoped_refptr<net::SSLConfigService> ssl_config_service;
    scoped_refptr<net::CookieMonsterDelegate> cookie_monster_delegate;
#if defined(ENABLE_EXTENSIONS)
    scoped_refptr<extensions::InfoMap> extension_info_map;
#endif
    std::unique_ptr<chrome_browser_net::ResourcePrefetchPredictorObserver>
        resource_prefetch_predictor_observer_;

    // This pointer exists only as a means of conveying a url job factory
    // pointer from the protocol handler registry on the UI thread to the
    // the URLRequestContext on the IO thread. The consumer MUST take
    // ownership of the object by calling release() on this pointer.
    std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
        protocol_handler_interceptor;

    // Holds the URLRequestInterceptor pointer that is created on the UI thread
    // and then passed to the list of request_interceptors on the IO thread.
    std::unique_ptr<net::URLRequestInterceptor> new_tab_page_interceptor;

    // We need to initialize the ProxyConfigService from the UI thread
    // because on linux it relies on initializing things through gconf,
    // and needs to be on the main thread.
    std::unique_ptr<net::ProxyConfigService> proxy_config_service;

#if defined(ENABLE_SUPERVISED_USERS)
    scoped_refptr<const SupervisedUserURLFilter> supervised_user_url_filter;
#endif

#if defined(OS_CHROMEOS)
    std::string username_hash;
    bool use_system_key_slot;
    std::unique_ptr<chromeos::CertificateProvider> certificate_provider;
#endif

    // The profile this struct was populated from. It's passed as a void* to
    // ensure it's not accidently used on the IO thread. Before using it on the
    // UI thread, call ProfileManager::IsValidProfile to ensure it's alive.
    void* profile;
  };

  explicit ProfileIOData(Profile::ProfileType profile_type);

  void InitializeOnUIThread(Profile* profile);
  void ApplyProfileParamsToContext(net::URLRequestContext* context) const;

  // Does common setup of the URLRequestJobFactories. Adds default
  // ProtocolHandlers to |job_factory|, adds URLRequestInterceptors in front of
  // it as needed, and returns the result.
  //
  // |protocol_handler_interceptor| is configured to intercept URLRequests
  //     before all other URLRequestInterceptors, if non-null.
  // |host_resolver| is needed to set up the FtpProtocolHandler.
  std::unique_ptr<net::URLRequestJobFactory> SetUpJobFactoryDefaults(
      std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory,
      content::URLRequestInterceptorScopedVector request_interceptors,
      std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
          protocol_handler_interceptor,
      net::NetworkDelegate* network_delegate,
      net::HostResolver* host_resolver) const;

  // Called when the Profile is destroyed. |context_getters| must include all
  // URLRequestContextGetters that refer to the ProfileIOData's
  // URLRequestContexts. Triggers destruction of the ProfileIOData and shuts
  // down |context_getters| safely on the IO thread.
  // TODO(mmenke):  Passing all those URLRequestContextGetters around like this
  //     is really silly.  Can we do something cleaner?
  void ShutdownOnUIThread(
      std::unique_ptr<ChromeURLRequestContextGetterVector> context_getters);

  void set_data_reduction_proxy_io_data(
      std::unique_ptr<data_reduction_proxy::DataReductionProxyIOData>
          data_reduction_proxy_io_data) const;

  net::ProxyService* proxy_service() const {
    return proxy_service_.get();
  }

  net::URLRequestContext* main_request_context() const {
    return main_request_context_.get();
  }

  // Storage for |main_request_context_|, to allow objects created by subclasses
  // to live until the ProfileIOData destructor is invoked, so it can safely
  // cancel URLRequests.
  net::URLRequestContextStorage* main_request_context_storage() const {
    return main_request_context_storage_.get();
  }

  bool initialized() const {
    return initialized_;
  }

  // Destroys the ResourceContext first, to cancel any URLRequests that are
  // using it still, before we destroy the member variables that those
  // URLRequests may be accessing.
  void DestroyResourceContext();

  std::unique_ptr<net::HttpNetworkSession> CreateHttpNetworkSession(
      const ProfileParams& profile_params) const;

  // Creates main network transaction factory.
  std::unique_ptr<net::HttpCache> CreateMainHttpFactory(
      net::HttpNetworkSession* session,
      std::unique_ptr<net::HttpCache::BackendFactory> main_backend) const;

  // Creates network transaction factory.
  std::unique_ptr<net::HttpCache> CreateHttpFactory(
      net::HttpNetworkSession* shared_session,
      std::unique_ptr<net::HttpCache::BackendFactory> backend) const;

  void SetCookieSettingsForTesting(
      content_settings::CookieSettings* cookie_settings);

 private:
  class ResourceContext : public content::ResourceContext {
   public:
    explicit ResourceContext(ProfileIOData* io_data);
    ~ResourceContext() override;

    // ResourceContext implementation:
    net::HostResolver* GetHostResolver() override;
    net::URLRequestContext* GetRequestContext() override;
    void CreateKeygenHandler(
        uint32_t key_size_in_bits,
        const std::string& challenge_string,
        const GURL& url,
        const base::Callback<void(std::unique_ptr<net::KeygenHandler>)>&
            callback) override;
    std::string GetMediaDeviceIDSalt() override;

   private:
    friend class ProfileIOData;

    ProfileIOData* const io_data_;

    net::HostResolver* host_resolver_;
    net::URLRequestContext* request_context_;
  };

  typedef std::map<StoragePartitionDescriptor,
                   net::URLRequestContext*,
                   StoragePartitionDescriptorLess>
      URLRequestContextMap;

  // --------------------------------------------
  // Virtual interface for subtypes to implement:
  // --------------------------------------------

  // Does the actual initialization of the ProfileIOData subtype. Subtypes
  // should use the static helper functions above to implement this.
  virtual void InitializeInternal(
      std::unique_ptr<ChromeNetworkDelegate> chrome_network_delegate,
      ProfileParams* profile_params,
      content::ProtocolHandlerMap* protocol_handlers,
      content::URLRequestInterceptorScopedVector request_interceptors)
      const = 0;

  // Initializes the RequestContext for extensions.
  virtual void InitializeExtensionsRequestContext(
      ProfileParams* profile_params) const = 0;
  // Does an on-demand initialization of a RequestContext for the given
  // isolated app.
  virtual net::URLRequestContext* InitializeAppRequestContext(
      net::URLRequestContext* main_context,
      const StoragePartitionDescriptor& details,
      std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
          protocol_handler_interceptor,
      content::ProtocolHandlerMap* protocol_handlers,
      content::URLRequestInterceptorScopedVector request_interceptors)
      const = 0;

  // Does an on-demand initialization of a media RequestContext for the given
  // isolated app.
  virtual net::URLRequestContext* InitializeMediaRequestContext(
      net::URLRequestContext* original_context,
      const StoragePartitionDescriptor& details) const = 0;

  // These functions are used to transfer ownership of the lazily initialized
  // context from ProfileIOData to the URLRequestContextGetter.
  virtual net::URLRequestContext*
      AcquireMediaRequestContext() const = 0;
  virtual net::URLRequestContext* AcquireIsolatedAppRequestContext(
      net::URLRequestContext* main_context,
      const StoragePartitionDescriptor& partition_descriptor,
      std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
          protocol_handler_interceptor,
      content::ProtocolHandlerMap* protocol_handlers,
      content::URLRequestInterceptorScopedVector request_interceptors)
      const = 0;
  virtual net::URLRequestContext*
      AcquireIsolatedMediaRequestContext(
          net::URLRequestContext* app_context,
          const StoragePartitionDescriptor& partition_descriptor) const = 0;

  // The order *DOES* matter for the majority of these member variables, so
  // don't move them around unless you know what you're doing!
  // General rules:
  //   * ResourceContext references the URLRequestContexts, so
  //   URLRequestContexts must outlive ResourceContext, hence ResourceContext
  //   should be destroyed first.
  //   * URLRequestContexts reference a whole bunch of members, so
  //   URLRequestContext needs to be destroyed before them.
  //   * Therefore, ResourceContext should be listed last, and then the
  //   URLRequestContexts, and then the URLRequestContext members.
  //   * Note that URLRequestContext members have a directed dependency graph
  //   too, so they must themselves be ordered correctly.

  // Tracks whether or not we've been lazily initialized.
  mutable bool initialized_;

  // Data from the UI thread from the Profile, used to initialize ProfileIOData.
  // Deleted after lazy initialization.
  mutable std::unique_ptr<ProfileParams> profile_params_;

  // Used for testing.
  mutable base::Callback<std::unique_ptr<net::ClientCertStore>()>
      client_cert_store_factory_;

  mutable StringPrefMember google_services_user_account_id_;

  mutable scoped_refptr<MediaDeviceIDSalt> media_device_id_salt_;

  // Member variables which are pointed to by the various context objects.
  mutable BooleanPrefMember enable_referrers_;
  mutable BooleanPrefMember enable_do_not_track_;
  mutable BooleanPrefMember force_google_safesearch_;
  mutable IntegerPrefMember force_youtube_restrict_;
  mutable BooleanPrefMember safe_browsing_enabled_;
  mutable StringPrefMember allowed_domains_for_apps_;
  mutable BooleanPrefMember sync_disabled_;
  mutable BooleanPrefMember signin_allowed_;
  mutable IntegerPrefMember network_prediction_options_;
  // TODO(marja): Remove session_startup_pref_ if no longer needed.
  mutable IntegerPrefMember session_startup_pref_;
  mutable BooleanPrefMember quick_check_enabled_;
  mutable IntegerPrefMember incognito_availibility_pref_;

  BooleanPrefMember enable_metrics_;

  // Pointed to by NetworkDelegate.
  mutable std::unique_ptr<policy::URLBlacklistManager> url_blacklist_manager_;
  mutable std::unique_ptr<policy::PolicyHeaderIOHelper> policy_header_helper_;

  // Pointed to by URLRequestContext.
#if defined(ENABLE_EXTENSIONS)
  mutable scoped_refptr<extensions::InfoMap> extension_info_map_;
#endif

  mutable std::unique_ptr<data_reduction_proxy::DataReductionProxyIOData>
      data_reduction_proxy_io_data_;

  mutable std::unique_ptr<net::ProxyService> proxy_service_;
  mutable std::unique_ptr<net::TransportSecurityState>
      transport_security_state_;
  mutable std::unique_ptr<net::CTVerifier> cert_transparency_verifier_;
  mutable std::unique_ptr<ChromeExpectCTReporter> expect_ct_reporter_;
#if defined(OS_CHROMEOS)
  // Set to |cert_verifier_| if it references a PolicyCertVerifier. In that
  // case, the verifier is owned by  |cert_verifier_|. Otherwise, set to NULL.
  mutable std::unique_ptr<net::CertVerifier> cert_verifier_;
  mutable policy::PolicyCertVerifier* policy_cert_verifier_;
  mutable std::string username_hash_;
  mutable bool use_system_key_slot_;
  mutable std::unique_ptr<chromeos::CertificateProvider> certificate_provider_;
#endif

  // Pointed to by the TransportSecurityState.
  mutable std::unique_ptr<net::TransportSecurityPersister>
      transport_security_persister_;
  mutable std::unique_ptr<net::ReportSender> certificate_report_sender_;
  mutable std::unique_ptr<certificate_transparency::CTPolicyManager>
      ct_policy_manager_;

  // Owns the subset of URLRequestContext's elements that are created by
  // subclasses of ProfileImplIOData, to ensure proper destruction ordering.
  // TODO(mmenke):  Move ownship of net objects owned by the ProfileIOData
  // itself to this class, to improve destruction ordering.
  mutable std::unique_ptr<net::URLRequestContextStorage>
      main_request_context_storage_;
  mutable std::unique_ptr<net::URLRequestContext> main_request_context_;

  mutable std::unique_ptr<net::URLRequestContext> extensions_request_context_;
  // One URLRequestContext per isolated app for main and media requests.
  mutable URLRequestContextMap app_request_context_map_;
  mutable URLRequestContextMap isolated_media_request_context_map_;

  mutable std::unique_ptr<ResourceContext> resource_context_;

  mutable scoped_refptr<content_settings::CookieSettings> cookie_settings_;

  mutable scoped_refptr<HostContentSettingsMap> host_content_settings_map_;

  mutable std::unique_ptr<chrome_browser_net::ResourcePrefetchPredictorObserver>
      resource_prefetch_predictor_observer_;

  mutable std::unique_ptr<ChromeHttpUserAgentSettings>
      chrome_http_user_agent_settings_;

#if defined(ENABLE_SUPERVISED_USERS)
  mutable scoped_refptr<const SupervisedUserURLFilter>
      supervised_user_url_filter_;
#endif

#if defined(ENABLE_EXTENSIONS)
  // Is NULL if switches::kDisableExtensionsHttpThrottling is on.
  mutable std::unique_ptr<extensions::ExtensionThrottleManager>
      extension_throttle_manager_;
#endif

  mutable DevToolsNetworkControllerHandle network_controller_handle_;

  mutable std::unique_ptr<certificate_transparency::TreeStateTracker>
      ct_tree_tracker_;
  mutable base::Closure ct_tree_tracker_unregistration_;

  const Profile::ProfileType profile_type_;

  DISALLOW_COPY_AND_ASSIGN(ProfileIOData);
};

#endif  // CHROME_BROWSER_PROFILES_PROFILE_IO_DATA_H_

redpajama_set_name: RedPajamaGithub


text:
namespace Piranha.Manager.Models.Content;

/// <summary>
/// Edit model for block groups.
/// </summary>
public class BlockGroupModel : BlockModel
{
    /// <summary>
    /// Gets/sets the unique id.
    /// </summary>
    public Guid Id { get; set; }

    /// <summary>
    /// Gets/sets the type of the block group.
    /// </summary>
    public string Type { get; set; }

    /// <summary>
    /// Gets/sets the available child items in the group.
    /// </summary>
    public IList<BlockModel> Items { get; set; } = new List<BlockModel>();

    /// <summary>
    /// Gets/sets the available global group fields.
    /// </summary>
    public IList<FieldModel> Fields { get; set; } = new List<FieldModel>();
}


text:
/*
 * Changes for GemFireXD distributed data platform (some marked by "GemStone changes")
 *
 * Portions Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
 * LICENSE file.
 */

package com.pivotal.gemfirexd.internal.impl.services.reflect;

import com.gemstone.gemfire.SystemFailure;
import com.pivotal.gemfirexd.internal.engine.Misc;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.loader.GeneratedMethod;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

class ReflectMethod implements GeneratedMethod {

	private final Method	realMethod;

	ReflectMethod(Method m) {
		super();
		realMethod = m;
	}

	public Object invoke(Object ref)
		throws StandardException {

		Throwable t;

		try {
			return realMethod.invoke(ref, (Object[])null);

		} catch (IllegalAccessException iae) {

			t = iae;

		} catch (IllegalArgumentException iae2) {

			t = iae2;

		} catch (InvocationTargetException ite) {

			t = ite.getTargetException();
			if (t instanceof StandardException)
				throw (StandardException) t;
// GemStone changes BEGIN
			if (t instanceof SQLException) {
			  throw Misc.wrapSQLException((SQLException)t, t);
			}
			Error err;
			if (t instanceof Error && SystemFailure
			    .isJVMFailureError(err = (Error)t)) {
			  SystemFailure.initiateFailure(err);
			  // If this ever returns, rethrow the error. We're
			  // poisoned now, so don't let this thread continue.
			  throw err;
			}
// GemStone changes END
		}

		throw StandardException.unexpectedUserException(t);
	}

}


text:
layout: post
disqus_identifier: #30
comments: true
categories:
  Shakespeare
---

## Characters

Principle players

* Lear
  * King
* Kent
  * Lear's faithful servant
  * Exiled
* Daughters
  * Goneril & Albany
  * Regan & Cornwall
  * Cordelia - The good one
* Glouchester, Duke of
* Edmund
  * Glouchester's bastard
* Edgar
  * Glouchester's legit son
* Fool
  * A fool

## Plot Summary

### Act 1

In which Lear fails to plan for his retirement.

#### Act 1 Scene 1

Lear decides to retire and splits up his kingdom amongst his daughters based on
how much they love him. Turns out Goneril and Regan are good at professing
their love.  Cordelia on the other hand is more plain spoken.  She gets the
shaft.  Kent gets exiled.  France marries Cordelia.

#### Act 1 Scene 2

Edmund starts to make his dad think that Edgar is out to kill him for his
inheritance.  Bastards gotta bastard.

#### Act 1 Scene 3

Goneril ain't enjoying having her dad live with her.

#### Act 1 Scene 4

Lear starts to chafe at living with his daughter.  Kent comes back all
disguised and ingratiates himself back in with Lear.  Fools gotta fool.

#### Act 1 Scene 5

Lear heads off to his other daughter's place with the Fool.  Kent goes ahead as
a messenger.

### Act 2

In which Lear realizes that he should have planned for his retirement

#### Act 2 Scene 1

Edmund scares Edgar into thinking that Glouchester has it out for him.  Fakes a
fight with Edgar and Edgar flees.  Glouchester sees this as proof that Edgar
was plotting against him and disowns his son.  Regan and Cornwall arrive and
support Glouchester in this decision.

#### Act 2 Scene 2

Kent arrives at Glouchester's at the same time as Goneril's messenger and gets
sassy with him.  Maybe a little too sassy since Cornwall has him put in the
stocks.

#### Act 2 Scene 3

Edgar is evading pursuit.  Decides to dress up as a crazy beggar (Tom o'
Bedlam) and go on the lam.

#### Act 2 Scene 4

Lear arrives to find his servant in the stocks and gets pissy about it.  Regan
don't care.  Goneril arrives and double teams Lear with her sister.  They say
as long as he is living under their roofs he has to give up his retinue of 100
knights.  Whittling it down to 50, then 25, then none.  Lear says F this and
runs out into the storm.

### Act 3

In which Lear argues with the wind, which I'm guessing is the medieval
equivalent of yelling at the T.V.

#### Act 3 Scene 1

Kent, looking for Lear, bumps into a "Gentleman" from Lear's retinue.  Tells
him that all is not lost and that France is coming with Cordelia.  Scene ends
with them going in separate directions in search of Lear.

#### Act 3 Scene 2

Lear wanders around in the storm yelling at it and wallowing in self pity.  The
Fool tries to cheer him up to no use.

#### Act 3 Scene 3

Glouchester frets over Lear being out in the storm.  Tells Edmund that he's
going to help his erstwhile king.  Edgar's all like "cool.  cool cool cool."
and then tells the audience that he's totally going to rat out his dad so that
Cornwall will like him.

#### Act 3 Scene 4

Kent finds Lear and convinces him to seek shelter.  They stumble across a shack
with Edmund in it who is pretending to be crazy.  Glouchester finds them and
invites them all back to his pad for safety.

#### Act 3 Scene 5

Edgar rats out his dad to Cornwall.  Cornwall calls for his head.

#### Act 3 Scene 6

Lear has a delirious fever dream of a trial for Goneril and Regan.  Imaginary
Regan is imagined to run away and is then chased by imaginary dogs. Glouchester
comes back and tells Kent to take Lear to Dover.

#### Act 3 Scene 7

Cornwall sends Goneril and Edgar back to Goneril's castle, plucks out
Glouchester's eyes, and is stabbed.  It's just a flesh wound.

### Act 4

In which reunions are made and more are hinted at.

#### Act 4 Scene 1

Blinded, Glouchester has been kicked out of his own castle and is brought to
Edgar.  Edgar agrees to take him to Dover.

#### Act 4 Scene 2

Goneril and Edmund arrive at Goneril's castle.  Albany (her hubby) isn't happy
about all the king-gas-lighting and eye-plucking.  Goneril totes has the hots
for Edmund.  Cornwall dies off stage.

#### Act 4 Scene 3

Lear has arrived at Dover.  Cordy reads a letter about how her sisters treated
their dad.  It made her sorrowful, but at least she's pretty when she's sad.
Lear is to ashamed to see his daughter.

#### Act 4 Scene 4

A doctor tells Cordelia that there is hope for treating her dad.  She sends
out people in search of him.

#### Act 4 Scene 5

Regan talks with Goneril's messenger.  She's concerned that Goneril might
be intersted in Edmund and tries to get this information from Oswald (the
messenger).  She reveals that she thinks she is a better match for the
new Duke of Glouchester.

#### Act 4 Scene 6

The cliff diving scene. Edgar (as Poor Tom) has led his father to "the edge"
of the Cliffs of Dover.  In fact they are nowhere near the cliffs.  Edgar
in the hopes of helping his father get over his suicidal depressoin encourages
his father to jump.  Glouchester jumps and doean't get hurt since they are
pretty much on solid ground. Edgar now pretends to be someone else and talks
about how far Glouchester had fallen.  Glouchester accepts this as a miracle
and resolves to live his life out.

Lear stumbles in around now and starts to pontificate on morality.  He's chased
off when Cordelia's messengers find him and try to bring him back t his daughter.

Oswald next stumbles into the scene and declares his intent to kill Glouchester.
Edgar, being the good son, takes issue with this and defends his father,
killing Oswald. After searching the body, he finds Goneril's note to
Edgar plotting the death of Albany (Goney's hubby).

#### Act 4 Scene 7

Lear has been caught and brought back to Cordy.

### Act 5

In which everyone lives happilly ever after, except for the vast majority who die in the last scene.

#### Act 5 Scene 1

Prelude to war.  Albany shows up and joins with Regan.  Edmund later contimplates
killing Albany.

Edgar gives Albany the letter from Goneril trying to plot his assination with Edmund.

Edmund think about which sister he wants to marry.

#### Act 5 Scene 2

The war has been lost.  Edgar tries to reassure Glouchester who is ready to die.
Which is good cuz he dies off stage between scenes.

> No further, sir.  A man may rot even here.
>
> -- Glouchester Line 9

#### Act 5 Scene 3

Edmund sends Lear and Cordelia to prison followed with orders to have them killed.  Lear goes gladly.  He looks forward to spending the rest of his days with Cordelia and cares not for prison.

Albany, Goneril, and Regan enter and start arguing over Edmund's station.  Goneril reveals that she's poisoned Regan.  Albany summons Edgar (no longr dressed as a commoner) who accuses Edmund of being a traitor and fights him in single combat.  Edmund is mortally wounded but takes his sweet ass time to die.

Albany promises to give everything to Cordelia and Lear.  Enter Lear with Cordy's dead body.  Lear dies of grief.  Kent arrives to say that he's not long for this world.

Who Dies:

1. Glouchester (off stage)
1. Regan (poisoned, dies off stage)
1. Edmund (wounded in single combat, dies slowly on stage)
1. Cordelia (hanged off stage)
1. Lear
1. Kent (implied to off stage soon after the completion of the play)

## Resources

* [RSC's Synopsis](https://www.youtube.com/watch?v=wtD10Nj1nRY)
* [New York Review of Books: History Revealed](http://www.nybooks.com/articles/2015/11/19/behind-king-lear-history-revealed/)
* [University of Oxford: Approaching Shakespeare](https://podcasts.ox.ac.uk/king-lear)
  * Showing how generations of critics - and Shakespeare himself - have rewritten the ending of King Lear, this sixteenth Approaching Shakespeare lecture engages with the question of tragedy and why it gives pleasure.


text:
Sample source code below will display you how to manage a complex task like export to 2d array with spreadsheet sdk in C#. Want to export to 2d array with spreadsheet sdk in your C# app? ByteScout Data Extraction Suite is designed for it. ByteScout Data Extraction Suite is the set that includes 3 SDK products for data extraction from PDF, scans, images and from spreadsheets: PDF Extractor SDK, Data Extraction SDK, Barcode Reader SDK.

Want to save time? You will save a lot of time on writing and testing code as you may just take the C# code from ByteScout Data Extraction Suite for export to 2d array with spreadsheet sdk below and use it in your application. IF you want to implement the functionality, just copy and paste this code for C# below into your code editor with your app, compile and run your application. Enjoy writing a code with ready-to-use sample codes in C#.

The trial version of ByteScout Data Extraction Suite can be downloaded for free from our website. It also includes source code samples for C# and other programming languages.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Data%20Extraction%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Data%20Extraction%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****ExportTo2DArray.VS2005.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{5E4683AA-4992-4259-8FF7-E081586F16A7}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bytescout.Spreadsheet.Demo.Csharp.ExportTo2DArray</RootNamespace>
    <AssemblyName>Bytescout.Spreadsheet.Demo.Csharp.ExportTo2DArray</AssemblyName>
    <TargetFrameworkProfile>
    </TargetFrameworkProfile>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.Spreadsheet, Version=2.3.0.750, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\lib\Bytescout.Spreadsheet.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="StockPricesSpreadsheet.xls">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****ExportTo2DArray.VS2008.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{5E4683AA-4992-4259-8FF7-E081586F16A7}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bytescout.Spreadsheet.Demo.Csharp.ExportTo2DArray</RootNamespace>
    <AssemblyName>Bytescout.Spreadsheet.Demo.Csharp.ExportTo2DArray</AssemblyName>
    <TargetFrameworkProfile>
    </TargetFrameworkProfile>
    <FileAlignment>512</FileAlignment>
    <OldToolsVersion>2.0</OldToolsVersion>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.Spreadsheet, Version=2.3.0.750, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\lib\Bytescout.Spreadsheet.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="StockPricesSpreadsheet.xls">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****ExportTo2DArray.VS2010.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{5E4683AA-4992-4259-8FF7-E081586F16A7}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bytescout.Spreadsheet.Demo.Csharp.ExportTo2DArray</RootNamespace>
    <AssemblyName>Bytescout.Spreadsheet.Demo.Csharp.ExportTo2DArray</AssemblyName>
    <TargetFrameworkProfile>
    </TargetFrameworkProfile>
    <FileAlignment>512</FileAlignment>
    <OldToolsVersion>3.5</OldToolsVersion>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.Spreadsheet, Version=2.3.0.750, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\lib\Bytescout.Spreadsheet.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="StockPricesSpreadsheet.xls">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Program.cs:**

```
using System;

namespace Bytescout.Spreadsheet.Demo.Csharp.ExportTo2DArray
{
    class Program
    {
        static void Main(string[] args)
        {
            const string inputFile = @"StockPricesSpreadsheet.xls";

            // Open and load spreadsheet
            Spreadsheet spreadsheet = new Spreadsheet();
            spreadsheet.LoadFromFile(inputFile);

            // Get the data from the spreadsheet
            string[,] stockPrices = spreadsheet.ExportTo2DArray();

            // Close spreadsheet
            spreadsheet.Close();

            // Display data in data table
            for(int i = 0; i < stockPrices.GetLength(0); i++)
            {
                for(int j = 0; j < stockPrices.GetLength(1); j++)
                {
                    Console.Write(stockPrices[i,j] + " ");
                }
                Console.WriteLine();
            }

            // Pause
            Console.ReadLine();
        }
    }
}

```

<!-- code block end -->


text:
CREATE TABLE t2(d, e INTEGER PRIMARY KEY AUTOINCREMENT, f);
INSERT INTO t2(d) VALUES(1);
SELECT * FROM sqlite_sequence;


text:
module Locomotive
  module Api
    class BaseController < ApplicationController

      include Locomotive::Routing::SiteDispatcher
      include Locomotive::ActionController::Timezone
      include Locomotive::ActionController::LocaleHelpers

      skip_before_filter :verify_authenticity_token

      around_filter :set_timezone

      before_filter :require_account

      before_filter :require_site

      before_filter :set_locale

      before_filter :set_current_thread_variables

      rescue_from Exception, with: :render_access_denied

      self.responder = Locomotive::ActionController::Responder # custom responder

      respond_to :json, :xml

      protected

      def set_current_thread_variables
        Thread.current[:account]  = current_locomotive_account
        Thread.current[:site]     = current_site
      end

      def current_ability
        @current_ability ||= Locomotive::Ability.new(current_locomotive_account, current_site)
      end

      def require_account
        authenticate_locomotive_account!
      end

      def require_site
        return true if current_site

        render_no_site_error

        false # halt chain
      end

      def set_locale
        locale = params[:locale] ||
          current_site.try(:default_locale) ||
          current_locomotive_account.try(:locale) ||
          Locomotive.config.default_locale

        ::Mongoid::Fields::I18n.locale = locale
        ::I18n.locale = ::Mongoid::Fields::I18n.locale

        self.setup_i18n_fallbacks if current_site
      end

      def render_access_denied(exception)
        status = (case exception
        when ::CanCan::AccessDenied               then 401
        when ::Mongoid::Errors::DocumentNotFound  then 404
        else 500
        end)
        render json: { error: exception.message }, status: status, layout: false
      end

      def self.cancan_resource_class
        Locomotive::Api::CanCan::ControllerResource
      end

      def self.description
        { overall: 'No documentation', actions: {} }
      end

    end
  end
end


text:
@implementation GRStreamInfo
{
    dispatch_queue_t _queue;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _writeStream = nil;
        _readStream = nil;
        _bytesThisIteration = 0;
        _bytesTotal = 0;
        _timeout = 30;
        _cancelRequestFlag = NO;
        _cancelDoesNotCallDelegate = NO;
        _queue = dispatch_queue_create("com.albertodebortoli.goldraccoon.streaminfo", DISPATCH_QUEUE_CONCURRENT);
    }

    return self;
}

- (void)openRead:(GRRequest *)request
{
    if ([request.dataSource hostnameForRequest:request] == nil) {
        request.error = [[GRError alloc] init];
        request.error.errorCode = kGRFTPClientHostnameIsNil;
        [request.delegate requestFailed:request];
        [request.streamInfo close:request];
        return;
    }

    // a little bit of C because I was not able to make NSInputStream play nice
    CFReadStreamRef readStreamRef = CFReadStreamCreateWithFTPURL(NULL, ( __bridge CFURLRef) request.fullURL);
    CFReadStreamSetProperty(readStreamRef,
                            kCFStreamPropertyFTPAttemptPersistentConnection,
                            kCFBooleanFalse);

    CFReadStreamSetProperty(readStreamRef, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
	CFReadStreamSetProperty(readStreamRef, kCFStreamPropertyFTPUsePassiveMode, request.passiveMode ? kCFBooleanTrue :kCFBooleanFalse);
    CFReadStreamSetProperty(readStreamRef, kCFStreamPropertyFTPFetchResourceInfo, kCFBooleanTrue);
    CFReadStreamSetProperty(readStreamRef, kCFStreamPropertyFTPUserName, (__bridge CFStringRef) [request.dataSource usernameForRequest:request]);
    CFReadStreamSetProperty(readStreamRef, kCFStreamPropertyFTPPassword, (__bridge CFStringRef) [request.dataSource passwordForRequest:request]);
    self.readStream = ( __bridge_transfer NSInputStream *) readStreamRef;

    if (self.readStream == nil) {
        request.error = [[GRError alloc] init];
        request.error.errorCode = kGRFTPClientCantOpenStream;
        [request.delegate requestFailed:request];
        [request.streamInfo close:request];
        return;
    }

    self.readStream.delegate = request;
	[self.readStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[self.readStream open];

    request.didOpenStream = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, self.timeout * NSEC_PER_SEC), _queue, ^{
        if (!request.didOpenStream && request.error == nil) {
            request.error = [[GRError alloc] init];
            request.error.errorCode = kGRFTPClientStreamTimedOut;
            [request.delegate requestFailed:request];
            [request.streamInfo close:request];
        }
    });
}

- (void)openWrite:(GRRequest *)request
{
    if ([request.dataSource hostnameForRequest:request] == nil) {
        request.error = [[GRError alloc] init];
        request.error.errorCode = kGRFTPClientHostnameIsNil;
        [request.delegate requestFailed:request];
        [request.streamInfo close:request];
        return;
    }

    CFWriteStreamRef writeStreamRef = CFWriteStreamCreateWithFTPURL(NULL, ( __bridge CFURLRef) request.fullURL);
    CFWriteStreamSetProperty(writeStreamRef,
                             kCFStreamPropertyFTPAttemptPersistentConnection,
                             kCFBooleanFalse);

    CFWriteStreamSetProperty(writeStreamRef, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
	CFWriteStreamSetProperty(writeStreamRef, kCFStreamPropertyFTPUsePassiveMode, request.passiveMode ? kCFBooleanTrue :kCFBooleanFalse);
    CFWriteStreamSetProperty(writeStreamRef, kCFStreamPropertyFTPFetchResourceInfo, kCFBooleanTrue);
    CFWriteStreamSetProperty(writeStreamRef, kCFStreamPropertyFTPUserName, (__bridge CFStringRef) [request.dataSource usernameForRequest:request]);
    CFWriteStreamSetProperty(writeStreamRef, kCFStreamPropertyFTPPassword, (__bridge CFStringRef) [request.dataSource passwordForRequest:request]);

    self.writeStream = ( __bridge_transfer NSOutputStream *) writeStreamRef;

    if (!self.writeStream) {
        request.error = [[GRError alloc] init];
        request.error.errorCode = kGRFTPClientCantOpenStream;
        [request.delegate requestFailed:request];
        [request.streamInfo close:request];
        return;
    }

    self.writeStream.delegate = request;
    [self.writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.writeStream open];

    request.didOpenStream = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, self.timeout * NSEC_PER_SEC), _queue, ^{
        if (!request.didOpenStream && (request.error == nil)) {
            request.error = [[GRError alloc] init];
            request.error.errorCode = kGRFTPClientStreamTimedOut;
            [request.delegate requestFailed:request];
            [request.streamInfo close:request];
        }
    });
}

- (BOOL)checkCancelRequest:(GRRequest *)request
{
    if (!self.cancelRequestFlag) {
        return NO;
    }

    // see if we don't want to call the delegate (set and forget)
    if (!self.cancelDoesNotCallDelegate) {
        [request.delegate requestCompleted:request];
    }

    [request.streamInfo close:request];

    return YES;
}

- (NSData *)read:(GRRequest *)request
{
    NSData *data;
    NSMutableData *bufferObject = [NSMutableData dataWithLength:kGRDefaultBufferSize];

    self.bytesThisIteration = [self.readStream read:(UInt8 *)[bufferObject bytes] maxLength:kGRDefaultBufferSize];
    self.bytesTotal += self.bytesThisIteration;

    // return the data
    if (self.bytesThisIteration > 0) {
        data = [NSData dataWithBytes:(UInt8 *)[bufferObject bytes] length:self.bytesThisIteration];
        request.percentCompleted = self.bytesTotal / request.maximumSize;

        if ([request.delegate respondsToSelector:@selector(percentCompleted:forRequest:)]) {
            [request.delegate percentCompleted:request.percentCompleted forRequest:request];
        }

        return data;
    }

    // return no data, but this isn't an error... just the end of the file
    else if (self.bytesThisIteration == 0) {
        return [NSData data]; // returns empty data object - means no error, but no data
    }

    // otherwise we had an error, return an error
    [self streamError:request errorCode:kGRFTPClientCantReadStream];

    return nil;
}

- (BOOL)write:(GRRequest *)request data:(NSData *)data
{
    self.bytesThisIteration = [self.writeStream write:[data bytes] maxLength:[data length]];
    self.bytesTotal += self.bytesThisIteration;

    if (self.bytesThisIteration > 0) {
        request.percentCompleted = self.bytesTotal / request.maximumSize;
        if ([request.delegate respondsToSelector:@selector(percentCompleted:forRequest:)]) {
            [request.delegate percentCompleted:request.percentCompleted forRequest:request];
        }

        return YES;
    }

    if (self.bytesThisIteration == 0) {
        return YES;
    }

    [self streamError:request errorCode:kGRFTPClientCantWriteStream]; // perform callbacks and close out streams

    return NO;
}

- (void)streamError:(GRRequest *)request errorCode:(enum GRErrorCodes)errorCode
{
    request.error = [[GRError alloc] init];
    request.error.errorCode = errorCode;
    [request.delegate requestFailed:request];
    [request.streamInfo close:request];
}

- (void)streamComplete:(GRRequest *)request
{
    [request.delegate requestCompleted:request];
    [request.streamInfo close:request];
}

- (void)close:(GRRequest *)request
{
    if (self.readStream) {
        [self.readStream close];
        [self.readStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        self.readStream = nil;
    }

    if (self.writeStream) {
        [self.writeStream close];
        [self.writeStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        self.writeStream = nil;
    }

    request.streamInfo = nil;
}

@end


text:
@font-face{font-family: Amatic; src: url("fonts/Amatic/Amatic-Bold.ttf");}
@font-face{font-family: Roboto; src: url("fonts/Roboto/Roboto-Regular.ttf");}
@font-face{font-family: AmaticRegular; src: url("fonts/Amatic/AmaticSC-Regular.ttf");}

html {
  background: url(comingsoon.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

body{text-align:center;}

/* General links parameters */
a { color: #0DC3A0; opacity:0.9; font-family: Roboto,'Source Sans Pro', sans-serif; border-bottom: 0px none; text-decoration:none; }
a:active { color: #0DC3A0; opacity:0.9; border-bottom: 2px solid #fff; }
a:hover { color: #4BCDB4; opacity:1; border-bottom: 0px none;  }
a:visited { color: #0DC3A0; opacity:0.9; font-family: Roboto,'Source Sans Pro', sans-serif; border-bottom: 0px none; text-decoration:none;}

h1 {font-family: Amatic,'Source Sans Pro', sans-serif;
	font-weight: normal;
	font-size:100px;
	color: white;
	margin:auto;
	margin-bottom:10px;}

h2 {font-family: AmaticRegular,'Source Sans Pro', sans-serif;
	font-weight: normal;
	font-size:40px;
	color: white;}

.content {font-family:Roboto,'Source Sans Pro', sans-serif; color:white; width:30%;height:auto;margin:auto;}

a img{height:50px; width:auto;float:right;margin-left:5px;}

/* MailChimp Form Embed Code - Slim - 08/17/2011 */
#mc_embed_signup {display:block;width:30%;margin:0 auto;padding-top:30px;}
#mc_embed_signup form {display:block; position:relative; padding:10px 0 10px 3%}
#mc_embed_signup h2 {font-weight:bold; padding:0; margin:15px 0; font-size:1.4em;}
#mc_embed_signup input {border:1px solid #999; -webkit-appearance:none;}
#mc_embed_signup input[type=checkbox]{-webkit-appearance:checkbox;}
#mc_embed_signup input[type=radio]{-webkit-appearance:radio;}
#mc_embed_signup input:focus {border-color:#333;}
#mc_embed_signup .button {clear:both; background-color: #aaa; border: 0 none; border-radius:4px; color: #FFFFFF; cursor: pointer; display: inline-block; font-size:15px; font-weight: bold; height: 32px; line-height: 32px; margin: 0 5px 10px 0; padding:0; text-align: center; text-decoration: none; vertical-align: top; white-space: nowrap; width: auto;}
#mc_embed_signup .button:hover {background-color:#777;}
#mc_embed_signup .small-meta {font-size: 11px;}
#mc_embed_signup .nowrap {white-space:nowrap;}
#mc_embed_signup .clear {clear:none; display:inline;}

#mc_embed_signup label {display:block; font-size:16px; padding-bottom:10px; font-weight:bold;}
#mc_embed_signup input.email {display:block; padding:8px 0; margin:0 4% 10px 0; text-indent:5px; width:58%; min-width:130px;}
#mc_embed_signup input.button {display:block; width:35%; margin:0 0 10px 0; min-width:90px;}

#mc_embed_signup div#mce-responses {float:left; top:-1.4em; padding:0em .5em 0em .5em; overflow:hidden; width:90%;margin: 0 5%; clear: both;}
#mc_embed_signup div.response {margin:1em 0; padding:1em .5em .5em 0; font-weight:bold; float:left; top:-1.5em; z-index:1; width:80%;}
#mc_embed_signup #mce-error-response {display:none;}
#mc_embed_signup #mce-success-response {color:#529214; display:none;}
#mc_embed_signup label.error {display:block; float:none; width:auto; margin-left:1.05em; text-align:left; padding:.5em 0;}

/* MailChimp Form
#mc_embed_signup {display:block;width:30%;margin:0 auto;padding-top:30px;}
#mc_embed_signup_scroll{text-align:center; margin:0 auto; }
#mc_embed_signup form {display:block;}
#mc_embed_signup label {display:block; padding-bottom:10px; font-family: AmaticRegular,'Source Sans Pro', sans-serif; font-weight: normal;	font-size:35px;	color: white;}
#mc_embed_signup input {border:1px solid #999; -webkit-appearance:none;font-family:Roboto,'Source Sans Pro', sans-serif;}

#mc_embed_signup .button {clear:both; background-color: #0A9076; border: 0 none; border-radius:4px; color: white; cursor: pointer; display: inline-block; font-size:15px; height: 32px; line-height: 32px; margin: 0 5px 10px 0; padding:0; text-align: center; text-decoration: none; vertical-align: top; white-space: nowrap; width: 30%;}
#mc_embed_signup .button:hover {background-color:#0DC3A0;font-size:16px;}

/*#mc_embed_signup .clear {clear:none; display:inline;}

#mc_embed_signup input.email {display:block; padding:8px 0; margin:0 4% 10px 0; text-indent:5px; width:58%; min-width:130px; background: rgba(255,255,255,0.8);}
#mc_embed_signup input.email:focus {background: rgba(255,255,255,0.9);}
#mc_embed_signup input.button {display:block; width:35%; margin:0 0 10px 0; min-width:90px;}

#mc_embed_signup div#mce-responses {float:left; top:-1.4em; padding:0em .5em 0em .5em; overflow:hidden; width:90%;margin: 0 5%; clear: both;}
#mc_embed_signup div.response {margin:1em 0; padding:1em .5em .5em 0; font-weight:bold; float:left; top:-1.5em; z-index:1; width:80%;}
#mc_embed_signup #mce-error-response {display:none;}
#mc_embed_signup #mce-success-response {color:#529214; display:none;}
#mc_embed_signup label.error {display:block; float:none; width:auto; margin-left:1.05em; text-align:left; padding:.5em 0;}*/


text:
import threading
import time

from perfkitbenchmarker import flags
from perfkitbenchmarker import network
from perfkitbenchmarker.openstack import utils

FLAGS = flags.FLAGS

flags.DEFINE_string('openstack_public_network', None,
                    'Name of OpenStack public network')

flags.DEFINE_string('openstack_private_network', 'private',
                    'Name of OpenStack private network')

MAX_PORT = 65535

class OpenStackFirewall(network.BaseFirewall):
    """
    An object representing OpenStack Firewall based on Secure Groups.
    """

    def __init__(self, project):
        super(OpenStackFirewall, self).__init__(project)
        self.project = project
        self.__nclient = utils.NovaClient()

        if not (self.__nclient.security_groups.findall(
                name='perfkit_sc_group')):
            self.sec_group = self.__nclient.security_groups.create(
                'perfkit_sc_group',
                'Firewall configuration for Perfkit Benchmarker'
            )
        else:
            self.sec_group = self.__nclient.security_groups.findall(
                name='perfkit_sc_group')[0]

        self.AllowPort(None, -1, protocol='icmp')
        self.AllowPort(None, 1, MAX_PORT)

    def AllowPort(self, vm, from_port, to_port=None, protocol='tcp'):
        if to_port is None:
            to_port = from_port

        try:
            self.__nclient.security_group_rules.create(self.sec_group.id,
                                                       ip_protocol=protocol,
                                                       from_port=from_port,
                                                       to_port=to_port)
        except Exception:
            pass

    def DisallowAllPorts(self):
        pass

class OpenStackPublicNetwork(object):

    def __init__(self, pool):
        self.__nclient = utils.NovaClient()
        self.__floating_ip_lock = threading.Lock()
        self.ip_pool_name = pool

    def allocate(self):
        with self.__floating_ip_lock:
            return self.__nclient.floating_ips.create(pool=self.ip_pool_name)

    def release(self, floating_ip):
        f_id = floating_ip.id
        if self.__nclient.floating_ips.get(f_id).fixed_ip:
            with self.__floating_ip_lock:
                if not self.__nclient.floating_ips.get(f_id).fixed_ip:
                    self.__nclient.floating_ips.delete(floating_ip)
                    while self.__nclient.floating_ips.findall(id=f_id):
                        time.sleep(1)

    def get_or_create(self):
        with self.__floating_ip_lock:
            floating_ips = self.__nclient.floating_ips.findall(
                fixed_ip=None,
                pool=self.ip_pool_name
            )
        if floating_ips:
            return floating_ips[0]
        else:
            return self.allocate()

    def is_attached(self, floating_ip):
        return self.__nclient.floating_ips.get(
            floating_ip.id
        ).fixed_ip is not None


text:
<?php

namespace Plinth\Response;

use Plinth\Routing\Route;

class ResponseHelper
{
    /**
     * @var string
     */
    const HTML      = "text/html";

    /**
     * @var string
     */
    const JSON		= "application/json";

    /**
     * @var string
     */
    const XML		= "application/xml";

	/**
	 * @var string
	 */
	const DEF		= "application/octet-stream";

    public static function getContentType(Route $route)
	{
		if ($route->hasContentType()) return $route->getContentType();

    	switch ($route->getType()) {
    		case Route::TYPE_JSON 	: return self::JSON;
    		case Route::TYPE_XML 	: return self::XML;
    		case Route::TYPE_PAGE 	:
    		case Route::TYPE_HTML 	: return self::HTML;
    		default					: return self::DEF;
    	}
    }
}


text:
This is a demo blog to demonstrate the awesome coorperation between Angular and Meteor.

### Installation

First you need to download Meteor. Only for Linux and OSX.

```sh
$ curl https://install.meteor.com | /bin/sh
```

Clone my repo.
```sh
$ git clone https://github.com/janekkkk/angular-meteor-demo.git
```
Install packages.
```sh
$ cd angular-meteor-demo
```

Combined
```sh
$ meteor add urigo:angular fourseven:scss matthew:foundation5-sass underscore jquery urigo:angular-ui-router accounts-password accounts-ui accounts-facebook accounts-twitter
$ meteor remove insecure
```

Separate
```sh
$ meteor add urigo:angular
$ meteor add fourseven:scss
$ meteor add matthew:foundation5-sass
$ meteor add underscore
$ meteor add jquery
$ meteor add urigo:angular-ui-router
$ meteor remove insecure
$ meteor add accounts-password
$ meteor add accounts-ui
$ meteor add accounts-facebook
$ meteor add accounts-twitter
```

Start Meteor
```sh
$ meteor run
```

### Packages
You can find more packages on  [Athmosphere](https://atmospherejs.com/  "Athmosphere").
- [Angular-Meteor](https://github.com/Urigo/angular-meteor  "Angular-Meteor")
- [SASS/SCSS](https://atmospherejs.com/matthew/foundation5-sass "SASS/SCSS")
- [Foundation with Sass](https://atmospherejs.com/matthew/foundation5-sass   "Foundation with Sass")
- [Underscore](https://atmospherejs.com/meteor/underscore "Underscore")
- [jQuery](https://atmospherejs.com/meteor/jquery  "jQuery")


text:
"""The app: very basic."""

# pylint: disable=cyclic-import, no-self-use, no-member, invalid-name, no-init
# pylint: disable=too-few-public-methods, no-name-in-module, import-error

import re

from functools import lru_cache, wraps

import arrow

from flask import request
from flask import current_app as app
from flask.ext.restful import Resource
from flask.ext.restful import reqparse

from sqlalchemy.orm.relationships import RelationshipProperty

from ersa_storage_hcp import db, Allocation, Tenant
from ersa_storage_hcp import Namespace, Snapshot, Usage

USAGE_QUERY_PARSER = reqparse.RequestParser()
USAGE_QUERY_PARSER.add_argument("filter", action="append", help="Filter")
USAGE_QUERY_PARSER.add_argument("page", type=int, default=1, help="Page #")

ALPHA_PREFIX = re.compile("^[A-Za-z]+")

ITEMS_PER_PAGE = 1000

def get_or_create(session, model, **kwargs):
    """Fetch object if returned by filter query, else create new."""
    item = session.query(model).filter_by(**kwargs).first()
    if not item:
        item = model(**kwargs)
        session.add(item)
        session.flush()
    return item

def extract_allocation(name):
    """Check for an allocation suffix."""
    if not name.islower():
        return None
    if "-" not in name:
        return None
    name = name.split("-")
    try:
        return int(ALPHA_PREFIX.sub("", name[-1]))
    except ValueError:
        return None

def dynamic_query(model, query, expression):
    """
    Construct query based on:
        attribute.operation.expression
    For example:
        foo.eq.42
    """
    key, op, value = expression.split(".", 3)
    column = getattr(model, key, None)
    if isinstance(column.property, RelationshipProperty):
        column = getattr(model, key + "_id", None)
    if op == "in":
        query_filter = column.in_(value.split(","))
    else:
        attr = None
        for candidate in ["%s", "%s_", "__%s__"]:
            if hasattr(column, candidate % op):
                attr = candidate % op
                break
        if value == "null":
            value = None
        query_filter = getattr(column, attr)(value)
    return query.filter(query_filter)

def require_auth(func):
    """Very simple authentication via HTTP header."""

    @wraps(func)
    def decorated(*args, **kwargs):
        """Check the header."""
        token = request.headers.get("x-ersa-storage-hcp-token", "")
        if token == app.config["ERSA_STORAGE_HCP_TOKEN"]:
            return func(*args, **kwargs)
        else:
            return "", 401

    return decorated

class PingResource(Resource):
    """Basic liveness test."""

    def get(self):
        """Hello?"""
        return "pong"

class StorageResource(Resource):
    """HCP Tenants and Namespaces"""

    @require_auth
    def get(self):
        """HCP Tenants and Namespaces"""
        return [tenant.json() for tenant in Tenant.query.all()]

class SnapshotResource(Resource):
    """Snapshot"""

    @require_auth
    def get(self):
        """Snapshot"""
        return [snapshot.json() for snapshot in Snapshot.query.all()]

class AllocationResource(Resource):
    """Allocation"""

    @require_auth
    def get(self):
        """Allocation"""
        return [allocation.json() for allocation in Allocation.query.all()]

class UsageResource(Resource):
    """Usage"""

    @require_auth
    def get(self):
        """Fetch usage."""
        args = USAGE_QUERY_PARSER.parse_args()
        query = Usage.query
        if args["filter"]:
            for query_filter in args["filter"]:
                query = dynamic_query(Usage, query, query_filter)
        return [usage.json()
                for usage in query.paginate(args["page"],
                                            per_page=ITEMS_PER_PAGE).items]

    @require_auth
    def post(self):
        """Fetch usage."""
        return self.get()

    @require_auth
    def put(self):
        """Ingest usage."""

        timestamps = set()

        @lru_cache(maxsize=10000)
        def cache(model, **kwargs):
            """Intra-request caching"""
            return get_or_create(db.session, model, **kwargs)

        inserts = []

        for message in request.json:
            data = message["data"]

            timestamp = data["timestamp"]
            if timestamp in timestamps:
                continue
            else:
                timestamps.add(timestamp)

            print(timestamp)

            snapshot = cache(Snapshot, ts=timestamp)

            for tenant_name, namespaces in data.items():
                if not isinstance(namespaces, list):
                    continue

                allocation = None
                allocation_id = extract_allocation(tenant_name)
                if allocation_id:
                    allocation = cache(Allocation, allocation=allocation_id)

                tenant = cache(Tenant, name=tenant_name, allocation=allocation)

                for details in namespaces:
                    if "namespaceName" in details:
                        namespace_name = details["namespaceName"]
                    else:
                        namespace_name = "__total__"

                    allocation = None
                    allocation_id = extract_allocation(namespace_name)
                    if allocation_id:
                        allocation = cache(Allocation,
                                           allocation=allocation_id)

                    namespace = cache(Namespace,
                                      name=namespace_name,
                                      tenant=tenant,
                                      allocation=allocation)

                    start_time = arrow.get(details["startTime"]).timestamp
                    end_time = arrow.get(details["endTime"]).timestamp

                    usage = {
                        "snapshot": snapshot,
                        "namespace": namespace,
                        "start_time": start_time,
                        "end_time": end_time,
                        "ingested_bytes": details["ingestedVolume"],
                        "raw_bytes": details["storageCapacityUsed"],
                        "reads": details["reads"],
                        "writes": details["writes"],
                        "deletes": details["deletes"],
                        "objects": details["objectCount"],
                        "bytes_in": details["bytesIn"],
                        "bytes_out": details["bytesOut"],
                        "metadata_only_objects":
                        details["metadataOnlyObjects"],
                        "metadata_only_bytes": details["metadataOnlyBytes"],
                        "tiered_objects": details["tieredObjects"],
                        "tiered_bytes": details["tieredBytes"]
                    }

                    inserts.append(Usage(**usage))

        # snapshot, tenant, namespace, allocation
        db.session.commit()

        # usage
        db.session.bulk_save_objects(inserts)
        db.session.commit()

        return "", 204