text:
namespace Microsoft.Azure.Management.WorkloadMonitor
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Microsoft.Rest.Serialization;
    using Models;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;

    /// <summary>
    /// Workload Monitor API
    /// </summary>
    public partial class WorkloadMonitorAPIClient : ServiceClient<WorkloadMonitorAPIClient>, IWorkloadMonitorAPIClient, IAzureClient
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        public System.Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        public JsonSerializerSettings SerializationSettings { get; private set; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        public JsonSerializerSettings DeserializationSettings { get; private set; }

        /// <summary>
        /// Credentials needed for the client to connect to Azure.
        /// </summary>
        public ServiceClientCredentials Credentials { get; private set; }

        /// <summary>
        /// The API version to use for this operation.
        /// </summary>
        public string ApiVersion { get; private set; }

        /// <summary>
        /// The preferred language for the response.
        /// </summary>
        public string AcceptLanguage { get; set; }

        /// <summary>
        /// The retry timeout in seconds for Long Running Operations. Default value is
        /// 30.
        /// </summary>
        public int? LongRunningOperationRetryTimeout { get; set; }

        /// <summary>
        /// Whether a unique x-ms-client-request-id should be generated. When set to
        /// true a unique x-ms-client-request-id value is generated and included in
        /// each request. Default is true.
        /// </summary>
        public bool? GenerateClientRequestId { get; set; }

        /// <summary>
        /// Gets the IOperations.
        /// </summary>
        public virtual IOperations Operations { get; private set; }

        /// <summary>
        /// Gets the IMonitorsOperations.
        /// </summary>
        public virtual IMonitorsOperations Monitors { get; private set; }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='httpClient'>
        /// HttpClient to be used
        /// </param>
        /// <param name='disposeHttpClient'>
        /// True: will dispose the provided httpClient on calling WorkloadMonitorAPIClient.Dispose(). False: will not dispose provided httpClient</param>
        protected WorkloadMonitorAPIClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        protected WorkloadMonitorAPIClient(params DelegatingHandler[] handlers) : base(handlers)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        protected WorkloadMonitorAPIClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        protected WorkloadMonitorAPIClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (baseUri == null)
            {
                throw new System.ArgumentNullException("baseUri");
            }
            BaseUri = baseUri;
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        protected WorkloadMonitorAPIClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (baseUri == null)
            {
                throw new System.ArgumentNullException("baseUri");
            }
            BaseUri = baseUri;
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Credentials needed for the client to connect to Azure.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WorkloadMonitorAPIClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Credentials needed for the client to connect to Azure.
        /// </param>
        /// <param name='httpClient'>
        /// HttpClient to be used
        /// </param>
        /// <param name='disposeHttpClient'>
        /// True: will dispose the provided httpClient on calling WorkloadMonitorAPIClient.Dispose(). False: will not dispose provided httpClient</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WorkloadMonitorAPIClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
        {
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Credentials needed for the client to connect to Azure.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WorkloadMonitorAPIClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='credentials'>
        /// Required. Credentials needed for the client to connect to Azure.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WorkloadMonitorAPIClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (baseUri == null)
            {
                throw new System.ArgumentNullException("baseUri");
            }
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            BaseUri = baseUri;
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the WorkloadMonitorAPIClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='credentials'>
        /// Required. Credentials needed for the client to connect to Azure.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WorkloadMonitorAPIClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (baseUri == null)
            {
                throw new System.ArgumentNullException("baseUri");
            }
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            BaseUri = baseUri;
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// An optional partial-method to perform custom initialization.
        /// </summary>
        partial void CustomInitialize();
        /// <summary>
        /// Initializes client properties.
        /// </summary>
        private void Initialize()
        {
            Operations = new Operations(this);
            Monitors = new MonitorsOperations(this);
            BaseUri = new System.Uri("https://management.azure.com");
            ApiVersion = "2020-01-13-preview";
            AcceptLanguage = "en-US";
            LongRunningOperationRetryTimeout = 30;
            GenerateClientRequestId = true;
            SerializationSettings = new JsonSerializerSettings
            {
                Formatting = Newtonsoft.Json.Formatting.Indented,
                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
                ContractResolver = new ReadOnlyJsonContractResolver(),
                Converters = new List<JsonConverter>
                    {
                        new Iso8601TimeSpanConverter()
                    }
            };
            SerializationSettings.Converters.Add(new TransformationJsonConverter());
            DeserializationSettings = new JsonSerializerSettings
            {
                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
                ContractResolver = new ReadOnlyJsonContractResolver(),
                Converters = new List<JsonConverter>
                    {
                        new Iso8601TimeSpanConverter()
                    }
            };
            CustomInitialize();
            DeserializationSettings.Converters.Add(new TransformationJsonConverter());
            DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
        }
    }
}


text:
import * as path from 'path';
import * as admin from 'firebase-admin';
import { Storage } from '@google-cloud/storage';
import * as client from 'firebase-tools';
import { getProjectId, initializeAndEnsureAuth, resolveApp } from '../util';
import { materializeAll } from 'firebase-tools/lib/functionsConfig';
import { ensureDirSync, writeFileSync } from 'fs-extra';

export const exportFirestore = async (foldername: string) => {
  const firestore = admin.firestore();
  firestore.settings({ timestampsInSnapshots: true });
  const collections = await firestore.listCollections();
  const data = {};
  for (let collection of collections) {
    const test = await firestore.collection(collection.id).get();
    data[collection.id] = {};
    test.forEach(doc => {
      data[collection.id][doc.id] = doc.data();
    });
  }
  writeFileSync(foldername, JSON.stringify(data, null, 2));
};

export const exportStorage = async (projectId: string, foldername: string) => {
  const storage = new Storage({ projectId });

  const bucket = storage.bucket(`gs://${projectId}.appspot.com`);
  const [files] = await bucket.getFiles();
  ensureDirSync(foldername);
  files.forEach(async file => {
    try {
      await bucket.file(file.name).download({
        destination: path.join(foldername, `${file.name}`),
      });
      writeFileSync(
        path.join(foldername, `${file.name}.metadata`),
        JSON.stringify(file.metadata.metadata || {}, null, 2)
      );
    } catch (error) {
      console.log(error);
    }
  });
};

export const exportAuthenticationUsers = (foldername: string) =>
  client.auth.export(foldername, { format: 'json' });

export const exportConfiguration = async (
  projectId: string,
  foldername: string
) =>
  writeFileSync(
    foldername,
    JSON.stringify(await materializeAll(projectId), null, 2)
  );

// export configuration
// export firestore collections
// export authentication users
// export storage files
export default async (
  foldername: string,
  {
    configuration,
    firestore,
    storage,
    accounts,
  }: {
    configuration?: boolean;
    firestore?: boolean;
    storage?: boolean;
    accounts?: boolean;
  }
): Promise<void> => {
  console.log('  - now exporting');
  // If no arguments are provided everything is false and should get backed up
  const backupAll = !configuration && !firestore && !storage && !accounts;

  ensureDirSync(foldername);

  const projectId = await getProjectId();

  try {
    await initializeAndEnsureAuth(projectId);

    if (configuration || backupAll) {
      console.log('exporting configuration');
      await exportConfiguration(
        projectId,
        path.join(resolveApp(foldername), 'config.json')
      );
    }

    if (firestore || backupAll) {
      console.log('exporting firestore');
      await exportFirestore(
        path.join(resolveApp(foldername), 'firestore.json')
      );
    }

    if (accounts || backupAll) {
      console.log('exporting authentication users');
      exportAuthenticationUsers(
        path.join(resolveApp(foldername), 'accounts.json')
      );
    }

    if (storage || backupAll) {
      console.log('exporting storage');
      await exportStorage(
        projectId,
        path.join(resolveApp(foldername), 'storage')
      );
    }
  } catch (err) {
    console.log(err);
  }
};

redpajama_set_name: RedPajamaGithub


text:
using extensions::AppWindow;

namespace {

const int kMinPanelWidth = 100;
const int kMinPanelHeight = 100;
const int kDefaultPanelWidth = 200;
const int kDefaultPanelHeight = 300;

struct AcceleratorMapping {
  ui::KeyboardCode keycode;
  int modifiers;
  int command_id;
};

const AcceleratorMapping kAppWindowAcceleratorMap[] = {
  { ui::VKEY_W, ui::EF_CONTROL_DOWN, IDC_CLOSE_WINDOW },
  { ui::VKEY_W, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, IDC_CLOSE_WINDOW },
  { ui::VKEY_F4, ui::EF_ALT_DOWN, IDC_CLOSE_WINDOW },
};

// These accelerators will only be available in kiosk mode. These allow the
// user to manually zoom app windows. This is only necessary in kiosk mode
// (in normal mode, the user can zoom via the screen magnifier).
// TODO(xiyuan): Write a test for kiosk accelerators.
const AcceleratorMapping kAppWindowKioskAppModeAcceleratorMap[] = {
  { ui::VKEY_OEM_MINUS, ui::EF_CONTROL_DOWN, IDC_ZOOM_MINUS },
  { ui::VKEY_OEM_MINUS, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN,
    IDC_ZOOM_MINUS },
  { ui::VKEY_SUBTRACT, ui::EF_CONTROL_DOWN, IDC_ZOOM_MINUS },
  { ui::VKEY_OEM_PLUS, ui::EF_CONTROL_DOWN, IDC_ZOOM_PLUS },
  { ui::VKEY_OEM_PLUS, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, IDC_ZOOM_PLUS },
  { ui::VKEY_ADD, ui::EF_CONTROL_DOWN, IDC_ZOOM_PLUS },
  { ui::VKEY_0, ui::EF_CONTROL_DOWN, IDC_ZOOM_NORMAL },
  { ui::VKEY_NUMPAD0, ui::EF_CONTROL_DOWN, IDC_ZOOM_NORMAL },
};

void AddAcceleratorsFromMapping(const AcceleratorMapping mapping[],
                                size_t mapping_length,
                                std::map<ui::Accelerator, int>* accelerators) {
  for (size_t i = 0; i < mapping_length; ++i) {
    ui::Accelerator accelerator(mapping[i].keycode, mapping[i].modifiers);
    (*accelerators)[accelerator] = mapping[i].command_id;
  }
}

const std::map<ui::Accelerator, int>& GetAcceleratorTable() {
  typedef std::map<ui::Accelerator, int> AcceleratorMap;
  CR_DEFINE_STATIC_LOCAL(AcceleratorMap, accelerators, ());
  if (!chrome::IsRunningInForcedAppMode()) {
    if (accelerators.empty()) {
      AddAcceleratorsFromMapping(
          kAppWindowAcceleratorMap,
          arraysize(kAppWindowAcceleratorMap),
          &accelerators);
    }
    return accelerators;
  }

  CR_DEFINE_STATIC_LOCAL(AcceleratorMap, app_mode_accelerators, ());
  if (app_mode_accelerators.empty()) {
    AddAcceleratorsFromMapping(
        kAppWindowAcceleratorMap,
        arraysize(kAppWindowAcceleratorMap),
        &app_mode_accelerators);
    AddAcceleratorsFromMapping(
        kAppWindowKioskAppModeAcceleratorMap,
        arraysize(kAppWindowKioskAppModeAcceleratorMap),
        &app_mode_accelerators);
  }
  return app_mode_accelerators;
}

}  // namespace

ChromeNativeAppWindowViews::ChromeNativeAppWindowViews()
    : is_fullscreen_(false),
      has_frame_color_(false),
      active_frame_color_(SK_ColorBLACK),
      inactive_frame_color_(SK_ColorBLACK) {
}

ChromeNativeAppWindowViews::~ChromeNativeAppWindowViews() {}

void ChromeNativeAppWindowViews::OnBeforeWidgetInit(
    const AppWindow::CreateParams& create_params,
    views::Widget::InitParams* init_params,
    views::Widget* widget) {
}

void ChromeNativeAppWindowViews::OnBeforePanelWidgetInit(
    views::Widget::InitParams* init_params,
    views::Widget* widget) {
}

void ChromeNativeAppWindowViews::InitializeDefaultWindow(
    const AppWindow::CreateParams& create_params) {
  views::Widget::InitParams init_params(views::Widget::InitParams::TYPE_WINDOW);
  init_params.delegate = this;
  init_params.remove_standard_frame = IsFrameless() || has_frame_color_;
  init_params.use_system_default_icon = true;
  if (create_params.alpha_enabled) {
    init_params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;

    // The given window is most likely not rectangular since it uses
    // transparency and has no standard frame, don't show a shadow for it.
    // TODO(skuhne): If we run into an application which should have a shadow
    // but does not have, a new attribute has to be added.
    if (IsFrameless())
      init_params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
  }
  init_params.keep_on_top = create_params.always_on_top;
  init_params.visible_on_all_workspaces =
      create_params.visible_on_all_workspaces;

  OnBeforeWidgetInit(create_params, &init_params, widget());
  widget()->Init(init_params);

  // The frame insets are required to resolve the bounds specifications
  // correctly. So we set the window bounds and constraints now.
  gfx::Insets frame_insets = GetFrameInsets();
  gfx::Rect window_bounds = create_params.GetInitialWindowBounds(frame_insets);
  SetContentSizeConstraints(create_params.GetContentMinimumSize(frame_insets),
                            create_params.GetContentMaximumSize(frame_insets));
  if (!window_bounds.IsEmpty()) {
    typedef AppWindow::BoundsSpecification BoundsSpecification;
    bool position_specified =
        window_bounds.x() != BoundsSpecification::kUnspecifiedPosition &&
        window_bounds.y() != BoundsSpecification::kUnspecifiedPosition;
    if (!position_specified)
      widget()->CenterWindow(window_bounds.size());
    else
      widget()->SetBounds(window_bounds);
  }

#if defined(OS_CHROMEOS)
  if (create_params.is_ime_window)
    return;
#endif

  // Register accelarators supported by app windows.
  // TODO(jeremya/stevenjb): should these be registered for panels too?
  views::FocusManager* focus_manager = GetFocusManager();
  const std::map<ui::Accelerator, int>& accelerator_table =
      GetAcceleratorTable();
  const bool is_kiosk_app_mode = chrome::IsRunningInForcedAppMode();

  // Ensures that kiosk mode accelerators are enabled when in kiosk mode (to be
  // future proof). This is needed because GetAcceleratorTable() uses a static
  // to store data and only checks kiosk mode once. If a platform app is
  // launched before kiosk mode starts, the kiosk accelerators will not be
  // registered. This CHECK catches the case.
  CHECK(!is_kiosk_app_mode ||
        accelerator_table.size() ==
            arraysize(kAppWindowAcceleratorMap) +
                arraysize(kAppWindowKioskAppModeAcceleratorMap));

  // Ensure there is a ZoomController in kiosk mode, otherwise the processing
  // of the accelerators will cause a crash. Note CHECK here because DCHECK
  // will not be noticed, as this could only be relevant on real hardware.
  CHECK(!is_kiosk_app_mode ||
        ui_zoom::ZoomController::FromWebContents(web_view()->GetWebContents()));

  for (std::map<ui::Accelerator, int>::const_iterator iter =
           accelerator_table.begin();
       iter != accelerator_table.end(); ++iter) {
    if (is_kiosk_app_mode && !chrome::IsCommandAllowedInAppMode(iter->second))
      continue;

    focus_manager->RegisterAccelerator(
        iter->first, ui::AcceleratorManager::kNormalPriority, this);
  }
}

void ChromeNativeAppWindowViews::InitializePanelWindow(
    const AppWindow::CreateParams& create_params) {
  views::Widget::InitParams params(views::Widget::InitParams::TYPE_PANEL);
  params.delegate = this;

  gfx::Rect initial_window_bounds =
      create_params.GetInitialWindowBounds(gfx::Insets());
  preferred_size_ = gfx::Size(initial_window_bounds.width(),
                              initial_window_bounds.height());
  if (preferred_size_.width() == 0)
    preferred_size_.set_width(kDefaultPanelWidth);
  else if (preferred_size_.width() < kMinPanelWidth)
    preferred_size_.set_width(kMinPanelWidth);

  if (preferred_size_.height() == 0)
    preferred_size_.set_height(kDefaultPanelHeight);
  else if (preferred_size_.height() < kMinPanelHeight)
    preferred_size_.set_height(kMinPanelHeight);

  params.bounds = gfx::Rect(preferred_size_);
  OnBeforePanelWidgetInit(&params, widget());
  widget()->Init(params);
  widget()->set_focus_on_creation(create_params.focused);
}

views::NonClientFrameView*
ChromeNativeAppWindowViews::CreateStandardDesktopAppFrame() {
  return views::WidgetDelegateView::CreateNonClientFrameView(widget());
}

apps::AppWindowFrameView*
ChromeNativeAppWindowViews::CreateNonStandardAppFrame() {
  apps::AppWindowFrameView* frame =
      new apps::AppWindowFrameView(widget(), this, has_frame_color_,
                                   active_frame_color_, inactive_frame_color_);
  frame->Init();
  return frame;
}

// ui::BaseWindow implementation.

gfx::Rect ChromeNativeAppWindowViews::GetRestoredBounds() const {
  return widget()->GetRestoredBounds();
}

ui::WindowShowState ChromeNativeAppWindowViews::GetRestoredState() const {
  if (IsMaximized())
    return ui::SHOW_STATE_MAXIMIZED;
  if (IsFullscreen())
    return ui::SHOW_STATE_FULLSCREEN;

  return ui::SHOW_STATE_NORMAL;
}

bool ChromeNativeAppWindowViews::IsAlwaysOnTop() const {
  // TODO(jackhou): On Mac, only docked panels are always-on-top.
  return app_window()->window_type_is_panel() || widget()->IsAlwaysOnTop();
}

// views::WidgetDelegate implementation.

gfx::ImageSkia ChromeNativeAppWindowViews::GetWindowAppIcon() {
  gfx::Image app_icon = app_window()->app_icon();
  if (app_icon.IsEmpty())
    return GetWindowIcon();
  else
    return *app_icon.ToImageSkia();
}

gfx::ImageSkia ChromeNativeAppWindowViews::GetWindowIcon() {
  content::WebContents* web_contents = app_window()->web_contents();
  if (web_contents) {
    FaviconTabHelper* favicon_tab_helper =
        FaviconTabHelper::FromWebContents(web_contents);
    gfx::Image app_icon = favicon_tab_helper->GetFavicon();
    if (!app_icon.IsEmpty())
      return *app_icon.ToImageSkia();
  }
  return gfx::ImageSkia();
}

views::NonClientFrameView* ChromeNativeAppWindowViews::CreateNonClientFrameView(
    views::Widget* widget) {
  return (IsFrameless() || has_frame_color_) ?
      CreateNonStandardAppFrame() : CreateStandardDesktopAppFrame();
}

bool ChromeNativeAppWindowViews::WidgetHasHitTestMask() const {
  return shape_ != NULL;
}

void ChromeNativeAppWindowViews::GetWidgetHitTestMask(gfx::Path* mask) const {
  shape_->getBoundaryPath(mask);
}

// views::View implementation.

gfx::Size ChromeNativeAppWindowViews::GetPreferredSize() const {
  if (!preferred_size_.IsEmpty())
    return preferred_size_;
  return NativeAppWindowViews::GetPreferredSize();
}

bool ChromeNativeAppWindowViews::AcceleratorPressed(
    const ui::Accelerator& accelerator) {
  const std::map<ui::Accelerator, int>& accelerator_table =
      GetAcceleratorTable();
  std::map<ui::Accelerator, int>::const_iterator iter =
      accelerator_table.find(accelerator);
  DCHECK(iter != accelerator_table.end());
  int command_id = iter->second;
  switch (command_id) {
    case IDC_CLOSE_WINDOW:
      Close();
      return true;
    case IDC_ZOOM_MINUS:
      ui_zoom::PageZoom::Zoom(web_view()->GetWebContents(),
                              content::PAGE_ZOOM_OUT);
      return true;
    case IDC_ZOOM_NORMAL:
      ui_zoom::PageZoom::Zoom(web_view()->GetWebContents(),
                              content::PAGE_ZOOM_RESET);
      return true;
    case IDC_ZOOM_PLUS:
      ui_zoom::PageZoom::Zoom(web_view()->GetWebContents(),
                              content::PAGE_ZOOM_IN);
      return true;
    default:
      NOTREACHED() << "Unknown accelerator sent to app window.";
  }
  return NativeAppWindowViews::AcceleratorPressed(accelerator);
}

// NativeAppWindow implementation.

void ChromeNativeAppWindowViews::SetFullscreen(int fullscreen_types) {
  // Fullscreen not supported by panels.
  if (app_window()->window_type_is_panel())
    return;
  is_fullscreen_ = (fullscreen_types != AppWindow::FULLSCREEN_TYPE_NONE);
  widget()->SetFullscreen(is_fullscreen_);

  // TODO(jeremya) we need to call RenderViewHost::ExitFullscreen() if we
  // ever drop the window out of fullscreen in response to something that
  // wasn't the app calling webkitCancelFullScreen().
}

bool ChromeNativeAppWindowViews::IsFullscreenOrPending() const {
  return is_fullscreen_;
}

void ChromeNativeAppWindowViews::UpdateBadgeIcon() {
  const gfx::Image* icon = NULL;
  if (!app_window()->badge_icon().IsEmpty()) {
    icon = &app_window()->badge_icon();
    // chrome::DrawTaskbarDecoration can do interesting things with non-square
    // bitmaps.
    // TODO(benwells): Refactor chrome::DrawTaskbarDecoration to not be avatar
    // specific, and lift this restriction.
    if (icon->Width() != icon->Height()) {
      LOG(ERROR) << "Attempt to set a non-square badge; request ignored.";
      return;
    }
  }
  chrome::DrawTaskbarDecoration(GetNativeWindow(), icon);
}

void ChromeNativeAppWindowViews::UpdateShape(scoped_ptr<SkRegion> region) {
  shape_ = region.Pass();
  widget()->SetShape(shape() ? new SkRegion(*shape()) : nullptr);
  widget()->OnSizeConstraintsChanged();
}

bool ChromeNativeAppWindowViews::HasFrameColor() const {
  return has_frame_color_;
}

SkColor ChromeNativeAppWindowViews::ActiveFrameColor() const {
  return active_frame_color_;
}

SkColor ChromeNativeAppWindowViews::InactiveFrameColor() const {
  return inactive_frame_color_;
}

void ChromeNativeAppWindowViews::SetInterceptAllKeys(bool want_all_keys) {
  if (want_all_keys && (desktop_keyboard_capture_.get() == NULL)) {
    desktop_keyboard_capture_.reset(new DesktopKeyboardCapture(widget()));
  } else if (!want_all_keys) {
    desktop_keyboard_capture_.reset(NULL);
  }
}

// NativeAppWindowViews implementation.

void ChromeNativeAppWindowViews::InitializeWindow(
    AppWindow* app_window,
    const AppWindow::CreateParams& create_params) {
  DCHECK(widget());
  has_frame_color_ = create_params.has_frame_color;
  active_frame_color_ = create_params.active_frame_color;
  inactive_frame_color_ = create_params.inactive_frame_color;
  if (create_params.window_type == AppWindow::WINDOW_TYPE_PANEL ||
      create_params.window_type == AppWindow::WINDOW_TYPE_V1_PANEL) {
    InitializePanelWindow(create_params);
  } else {
    InitializeDefaultWindow(create_params);
  }
  extension_keybinding_registry_.reset(new ExtensionKeybindingRegistryViews(
      Profile::FromBrowserContext(app_window->browser_context()),
      widget()->GetFocusManager(),
      extensions::ExtensionKeybindingRegistry::PLATFORM_APPS_ONLY,
      NULL));
}


text:
package com.ibm.mqlight.api;

import com.ibm.mqlight.api.logging.Logger;
import com.ibm.mqlight.api.logging.LoggerFactory;

/**
 * A set of options that can be used to configure the behaviour of the NonBlockingClient
 * {@link NonBlockingClient#send(String, java.nio.ByteBuffer, Map, SendOptions, CompletionListener, Object)} and
 * {@link NonBlockingClient#send(String, String, Map, SendOptions, CompletionListener, Object)} methods. For example:
 *

 * SendOptions opts = SendOptions.builder().setQos(QOS.AT_LEAST_ONCE).setTtl(5000).build();
 * client.send("/tadpoles", "Hello baby frogs!", opts, listener, null);
 *

 */
public class SendOptions {

    private static final Logger logger = LoggerFactory.getLogger(SendOptions.class);

    private final QOS qos;
    private final long ttl;
    private final boolean retainLink;

    private SendOptions(QOS qos, long ttl, boolean retainLink) {
        final String methodName = "<init>";
        logger.entry(this, methodName, qos, ttl);

        this.qos = qos;
        this.ttl = ttl;
        this.retainLink = retainLink;

        logger.exit(this, methodName);
    }

    public final QOS getQos() {
        return qos;
    }

    public final long getTtl() {
        return ttl;
    }

    public final boolean getRetainLink() {
        return retainLink;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(super.toString());
        sb.append(" [qos=")
          .append(qos)
          .append(", ttl=")
          .append(ttl)
          .append(", retainLink=")
          .append(retainLink)
          .append("]");
        return sb.toString();
    }

    /**
     * @return a new instance of SendOptionsBuilder that can be used to build
     *         (immutable) instances of SendOptions.
     */
    public static SendOptionsBuilder builder() {
        return new SendOptionsBuilder();
    }

    /**
     * A builder for SendOptions objects.
     */
    public static class SendOptionsBuilder {
        private QOS qos = QOS.AT_MOST_ONCE;
        private long ttl = 0;
        private boolean retainLink = true;

        private SendOptionsBuilder() {}

        /**
         * Sets the quality of service that will be used to send messages to the MQ Light
         * server.
         * @param qos The required quality of service. Cannot be null.
         * @return the instance of SendOptionsBuilder that this method was
         *         called on.
         * @throws IllegalArgumentException if an invalid qos value is specified.
         */
        public SendOptionsBuilder setQos(QOS qos) throws IllegalArgumentException {
            final String methodName = "setQos";
            logger.entry(this, methodName, qos);

            if (qos == null) {
              final IllegalArgumentException exception = new IllegalArgumentException("qos argument cannot be null");
              logger.throwing(this,  methodName, exception);
              throw exception;
            }
            this.qos = qos;

            logger.exit(this, methodName, this);

            return this;
        }

        /**
         * Sets the time to live that will be used for messages sent to the MQ Light server.
         * @param ttl time to live in milliseconds. This must be a positive value, and a maximum of 4294967295 (0xFFFFFFFF)
         * @return the instance of SendOptionsBuilder that this method was
         *         called on.
         * @throws IllegalArgumentException if an invalid ttl value is specified.
         */
        public SendOptionsBuilder setTtl(long ttl) throws IllegalArgumentException {
            final String methodName = "setTtl";
            logger.entry(this, methodName, ttl);

            if (ttl < 1 || ttl > 4294967295L) {
              final IllegalArgumentException exception = new IllegalArgumentException("ttl value '" + ttl + "' is invalid, must be an unsigned non-zero integer number");
              logger.throwing(this,  methodName, exception);
              throw exception;
            }
            this.ttl = ttl;

            logger.exit(this, methodName, this);

            return this;
        }

        /**
         * Set the retainLink option.  True by default this value will determine if the AMQP Link should
         * be retained by the connection so that it can be re-used for subsequent messages.  When a client
         * will not send further messages to a given topic this value can be set to false to automatically
         * close the Link after sending this message.
         * @param retainLink true if the Link should be retained, false to close after message send.
         * @return the instance of SendOptionsBuilder that this method was
         *         called on.
         */
        public SendOptionsBuilder setRetainLink(boolean retainLink) {
            final String methodName = "setRetainLink";
            logger.entry(this, methodName, retainLink);

            this.retainLink = retainLink;

            logger.exit(this, methodName, this);

            return this;
        }
        /**
         * @return an instance of SendOptions based on the current settings of
         *         this builder.
         */
        public SendOptions build() {
            return new SendOptions(qos, ttl, retainLink);
        }
    }

}


text:
namespace BigEgg.Tools.ConsoleExtension.Parameters.Errors
{
    internal class VersionRequestError : Error
    {
        public VersionRequestError()
            : base(ErrorType.VersionRequest, true)
        { }
    }
}


text:
package com.hazelcast.client.longrunning;

import com.hazelcast.client.ClientConfig;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.config.Config;
import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import org.junit.After;
import org.junit.Test;

import java.util.Map;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotSame;
import static org.junit.Assert.assertFalse;

public class ClientMapGuavaCacheTest {

    @After
    public void shutdown(){
        Hazelcast.shutdownAll();
    }

    @Test
    public void testReadFromCache() {
        System.setProperty("hazelcast.client.near.cache.enabled", "true");
        Config config = new Config();
        NearCacheConfig nearCacheConfig = new NearCacheConfig();
        nearCacheConfig.setMaxSize(1000);
        nearCacheConfig.setMaxIdleSeconds(10);
        nearCacheConfig.setTimeToLiveSeconds(20);
        config.getMapConfig("default").setNearCacheConfig(nearCacheConfig);
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        String mapName = "testReadFromCache";
        IMap<String, String> mapH = h.getMap(mapName);
        mapH.put("a", "a");
        HazelcastClient client = HazelcastClient.newHazelcastClient(new ClientConfig());
        Map<Object, Object> mapC = client.getMap(mapName);

        assertEquals("a", mapC.get("a"));
        int hit = mapH.getMapEntry("a").getHits();
        mapC.get("a");
        assertEquals(mapH.getMapEntry("a").getHits(), hit);
        for (int i = 0; i < 100; i++) {
            mapC.get("a");
        }
        assertEquals(mapH.getMapEntry("a").getHits(), hit);
    }

    @Test
    public void testNoNearCacheConfig() {
        System.setProperty("hazelcast.client.near.cache.enabled", "false");
        Config config = new Config();
        NearCacheConfig nearCacheConfig = new NearCacheConfig();
        nearCacheConfig.setMaxSize(1000);
        nearCacheConfig.setMaxIdleSeconds(10);
        nearCacheConfig.setTimeToLiveSeconds(20);
        config.getMapConfig("default").setNearCacheConfig(nearCacheConfig);
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        String mapName = "testReadFromCache";
        IMap<String, String> mapH = h.getMap(mapName);
        mapH.put("a", "a");
        HazelcastClient client = HazelcastClient.newHazelcastClient(new ClientConfig());
        Map<Object, Object> mapC = client.getMap(mapName);

        assertEquals("a", mapC.get("a"));
        int hit = mapH.getMapEntry("a").getHits();
        mapC.get("a");
        assertEquals(mapH.getMapEntry("a").getHits(), ++hit);
        for (int i = 0; i < 100; i++) {
            mapC.get("a");
        }
        assertEquals(mapH.getMapEntry("a").getHits(), hit + 100);
    }

    @Test
    public void testInvalidateOnChange() throws InterruptedException {
        System.setProperty("hazelcast.client.near.cache.enabled", "true");
        Config config = new Config();
        NearCacheConfig nearCacheConfig = new NearCacheConfig();
        nearCacheConfig.setMaxSize(1000);
        nearCacheConfig.setInvalidateOnChange(true);
        config.getMapConfig("default").setNearCacheConfig(nearCacheConfig);
        HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
        String mapName = "testInvalidateOnChange";
        IMap<String, String> mapH = h.getMap(mapName);
        mapH.put("a", "a");
        HazelcastClient client = HazelcastClient.newHazelcastClient(new ClientConfig());
        Map<Object, Object> mapC = client.getMap(mapName);
        int hit = mapH.getMapEntry("a").getHits();
        assertEquals("a", mapC.get("a"));
        assertEquals(mapH.getMapEntry("a").getHits(), ++hit);
        mapC.get("a");
        assertEquals(mapH.getMapEntry("a").getHits(), hit);
        mapH.put("a", "b");
        Thread.sleep(100);
        assertEquals("b", mapC.get("a"));
        assertEquals(mapH.getMapEntry("a").getHits(), ++hit);
    }
}


text:
author: chipoglesby
comments: true
date: 2009-08-27 07:26:56+00:00
excerpt: Welcome to my new site. Now that you're here, what are you going to do?
layout: post
slug: welcome-to-my-new-site
title: Welcome to my new site!
wordpress_id: 351
categories:
- Journalism
---

I would say welcome to my new blog, but if you look through the archives, I've actually been blogging for about two years on the [blogger platform.](http://chipoglesby.blogspot.com)

Don't get me wrong, blogger is a great platform, but you've just got to know when to move on to bigger and better things.

I've been kicking around the idea of having my own site for about two years, but I've just never had the interest until now.

Why now? Well, since still and watching my friends and followers on twitter for over a year, I'm tired of not having the room, rhyme or reason to post something more than just a comment or reply on their website, it's time for me to have my own creative domain.

**So what can you expect from this site**
Right now, you can expect about one blog post per week about a topic of my choice, but something usually relating to the future of journalism and what we can do to save it.

I know, plenty of people do that already and you're probably asking yourself "Do we really need another freaking blog about saving journalism?" No, we don't but then again, the blogosphere doesn't have my "voice" so I may as well go ahead and add it to the ring.

Don't worry, this blog won't just be my boring ramblings, I'll also be posting my photography here, just like I did on my old site but now it will all be in one convenient location.


text:
#ifndef I_CLASS_DEFINITION_HPP
#define I_CLASS_DEFINITION_HPP

#include "core_reflection/property_iterator.hpp"
#include "core_reflection/ref_object_id.hpp"
#include "core_reflection/interfaces/i_property_path.hpp"

#include <functional>

namespace wgt
{
class IClassDefinitionDetails;
class IBaseProperty;
class IDefinitionManager;
class TypeId;
class PropertyAccessor;
class MetaData;
class ObjectHandle;
typedef std::shared_ptr<class IObjectHandleStorage> ObjectHandleStoragePtr;
typedef std::unique_ptr<class IManagedObject> ManagedObjectPtr;
class IPropertyPath;

/**
 *	Interface for storing info that "defines" a class.
 *
 *	Info such as the names and types of members on a class and metadata about
 *	their usage.
 *	E.g. so you could iterate over each variable in a class and
 *	print out the name and value, serialize it to disk, add it to the UI etc.
 *
 *	Stores info about inheritance and if a class can be cast to a base or
 *	derived class.
 */
class REFLECTION_DLL IClassDefinition
{
public:
	static const char DOT_OPERATOR = '.';

	virtual ~IClassDefinition()
	{
	}

	/**
	 *	Get the info extracted from a class.
	 */
	virtual const IClassDefinitionDetails& getDetails() const = 0;

	/**
	*	Create a PropertyAccessor bound to a property on the given object.
	*	@param name name of the property to bind.
	*	@param object the object which contains the value.
	*	@pre the object's IClassDefinition must match this IClassDefinition.
	*	@return an accessor bound to the property on the object on success.
	*		The accessor will not be valid on failure.
	*/
	virtual PropertyAccessor bindProperty(
		const std::shared_ptr< const IPropertyPath > & name, const ObjectHandle& object) const = 0;

	/**
	 *	Create a PropertyAccessor bound to a property on the given object.
	 *	@param name name of the property to bind.
	 *	@param object the object which contains the value.
	 *	@pre the object's IClassDefinition must match this IClassDefinition.
	 *	@return an accessor bound to the property on the object on success.
	 *		The accessor will not be valid on failure.
	 */
	virtual PropertyAccessor bindProperty(const char* name, const ObjectHandle& object) const = 0;

	/**
	 *	Get the manager in which this definition belongs.
	 */
	virtual IDefinitionManager* getDefinitionManager() const = 0;

	/**
	 *	Set the manager in which this definition belongs.
	 */
	virtual void setDefinitionManager(IDefinitionManager* defManager) = 0;

	/**
	 *	Check if this class definition can have properties added and removed
	 *	after construction.
	 *	@return true if it is possible to add/remove properties.
	 */
	virtual bool isGeneric() const = 0;

	/**
	*	Get the definition for the base class from which this class inherits.
	*	@return base class definitions or empty collection if there
	*			are no base classes
	*/
	virtual const std::vector< std::string > & getParentNames() const = 0;

	/**
	 *	Check if this class definition can be cast up/down the inheritance
	 *	chain to another definition.
	 */
	virtual bool canBeCastTo(const IClassDefinition& definition) const = 0;

	/**
	 *	Cast the given object from this definition to another type of definition.
	 *
	 *	@param definition the definition to which to cast.
	 *	@param object the object to be cast to the new definition.
	 *
	 *	@pre the object's definition should match this definition.
	 *
	 *	@return the object cast to the other definition or null on failure.
	 */
	virtual void* castTo(const IClassDefinition& definition, void* object) const = 0;

	/**
	 *	Range for all properties contained in this and its parents' definitions.
	 */
	virtual PropertyIteratorRange allProperties() const = 0;

	/**
	 *	Range for only properties contained in this definition.
	 */
	virtual PropertyIteratorRange directProperties() const = 0;

	/**
	 *	Find the first property with the given ID.
	 *	Searches all properties, direct and parent.
	 */
	virtual IBasePropertyPtr findProperty(const char* name, size_t length) const = 0;

	IBasePropertyPtr findProperty(const char* name) const
	{
		return findProperty(name, strlen(name));
	}

	virtual IBasePropertyPtr findProperty(IPropertyPath::ConstPtr & path) const = 0;

	/**
	 *	Get an identifier for this definition's type.
	 */
	virtual const char* getName() const = 0;

	/**
	 *	Get metadata about this definition.
	 */
	virtual const MetaData & getMetaData() const = 0;

	// TODO Remove this
	virtual ObjectHandleStoragePtr createObjectStorage() const = 0;

	// TODO Revisit these
	virtual ManagedObjectPtr createManaged(RefObjectId id = RefObjectId::zero()) const = 0;
	virtual ObjectHandle createShared(RefObjectId id = RefObjectId::zero()) const = 0;
};
} // end namespace wgt
#endif // I_CLASS_DEFINITION_HPP


text:
<?php
/**
 * Created by PhpStorm.
 * User: stefan
 * Date: 24.05.15
 * Time: 13:27
 */

namespace Mandator\Classes\Mysql;

class Connection extends \Db\Classes\Mysql\Connection {
	protected $mandator_application_instance = NULL;
	public function __construct(\Mandator\Model\Application\Instance $mandator_application_instance, $host, $port, $database, $username, $password)
	{
		parent::__construct($host, $port, $database, $username, $password);

		$this->mandator_application_instance = $mandator_application_instance;
	}
}


text:
require 'rubygems'
require 'sinatra'
require 'dm-core'
require 'dm-migrations'
require 'digest/sha1'
require 'haml'

require './tc_functions'
require 'sinatra/reloader'

# DataMapper.setup(:default, 'mysql://rubytest:rubytestpass@local.derbserv.org/rubytest')
DataMapper.setup(:default, 'sqlite3:timeclock.db')

class Punch
  include DataMapper::Resource
  property :id, Serial
  property :username, String
  property :punchtime, DateTime
  property :punchstate, String
end

class User
  include DataMapper::Resource
  property :id, Serial
  property :username, String
  property :password, String
  property :cookie, String
  property :admin, Boolean
end

class Taker
  include DataMapper::Resource
  property :id, Serial
  property :username, String
  property :hours, Float
  property :note, String
end

DataMapper.auto_upgrade!

class Dummy
  def admin
    @admin
  end
  def admin=(admin)
    @admin = admin
  end
end

get '/' do
  @title="Timeclock"
  @username = cookiecheck(request.cookies["MainSiteKey"])
  if !@username
    @title="Timeclock - Log In"
    @alert=alert()
    @admininfo=Dummy.new
    @admininfo.admin = false
    @hoursused = Punch.all(:username => @username)
    haml :loginpage
  else
    @punchstate=getstate(@username)
    @username = cookiecheck(request.cookies["MainSiteKey"])
    @alert=alert()
    @admininfo=User.first(:username => @username)

    @output=""
    @total = 0
    @list = Punch.all(:username => @username)  #
    (0..@list.length-2).step(2) do |i|
      @output << "#{@list[i].username} punched #{@list[i].punchstate} on #{@list[i].punchtime.strftime(fmt='%F')} at #{@list[i].punchtime.strftime(fmt='%T')}
"
      @output << "#{@list[i+1].username} punched #{@list[i+1].punchstate} on #{@list[i+1].punchtime.strftime(fmt='%F')} at #{@list[i+1].punchtime.strftime(fmt='%T')}
"
      @output << "Hours worked: #{((@list[i+1].punchtime - @list[i].punchtime).to_f*24).to_s}

"
      @total += ((@list[i+1].punchtime - @list[i].punchtime).to_f*24)
    end
    @output << "

Total Hours Worked: " << @total.to_s

    haml :mainpage
  end
end

get '/logout' do
  response.set_cookie("MainSiteKey", {:value => "", :expires => Time.now})
  setalert("Succesfully logged out.")
  redirect '/'
end

post '/submitpunch' do
  return params[:textings]
end

post '/submit' do
  @username = cookiecheck(request.cookies["MainSiteKey"])
  if !@username
    redirect '/'
  end
  @punchstate = getstate(@username)

  Punch.create(
    :username =>  @username,
    :punchtime  =>  Time.now,
    :punchstate =>  @punchstate
  )
  setalert("Punch #{@punchstate} for #{@username} successful!")
  redirect '/'
end

post '/loginsubmit' do
  username=params[:username]
  password=params[:password]
  passcheck(username,password)
  redirect '/'
end

get '/admin' do
  @username = cookiecheck(request.cookies["MainSiteKey"])
  if !@username
    redirect '/'
  end
  @admininfo=User.first(:username => @username)
  if @admininfo.admin
    haml :adminpage
  else
    # return "You are not logged in as an administrative user."
    setalert("You are not logged in as an administrative user.")
    redirect '/'
   end

end

post '/createuser' do
	logincheck = cookiecheck(request.cookies["MainSiteKey"])
  if !logincheck
  	setalert("Login expired")
    redirect '/'
  end
  username = params[:username]
  password = params[:password]
  if params[:admin] == 'true'
    admin = true
  else
    admin = false
  end

  if !(username == '') && !(password=='')
  User.create(
  :username => username,
  :password => Digest::SHA1.hexdigest(password),
  :cookie => "none",
  :admin => admin
  )
  setalert("User successfully created!")
  else
    setalert("Username and password fields are required.")
  end
  redirect '/admin'
end

get '/report' do
  @username = cookiecheck(request.cookies["MainSiteKey"])
  if !@username
    redirect '/'
  end
  # @output=""
  # @total = 0
  # @list = Punch.all(:username => @username)  #
  # (0..@list.length-2).step(2) do |i|
  #   @output << "#{@list[i].username} punched #{@list[i].punchstate} on #{@list[i].punchtime.strftime(fmt='%F')} at #{@list[i].punchtime.strftime(fmt='%T')}
"
  #   @output << "#{@list[i+1].username} punched #{@list[i+1].punchstate} on #{@list[i+1].punchtime.strftime(fmt='%F')} at #{@list[i+1].punchtime.strftime(fmt='%T')}
"
  #   @output << "#{((@list[i+1].punchtime - @list[i].punchtime).to_f*24).to_s}
"
  #   @total += ((@list[i+1].punchtime - @list[i].punchtime).to_f*24)
  # end
  # @output << "

Hours Worked: " << @total.to_s
  # return @output

end

post '/moduser' do
  query = User.all(:fields => [:id, :username])
  listem = Array.new
  newlist = Array.new

  query.each do |c|
    listem << c.username
  end

listem.each do |username|
  tempthing = User.first(:username => username)
  if params[username]
    tempthing.admin = true
  else
    tempthing.admin = false
  end
  tempthing.save
end

listem.each do |username|
  temp_User = User.first(:username => username)
  temp_param = username + "delete"
  if params[temp_param]
    temp_User.destroy!
    temp_punches = Punch.all(:username => username)
    temp_punches.destroy!
  end
end

  setalert("User modification successful")
  redirect '/admin'
end


text:
This page was generated with Wiki Builder. Do not change the format!

## Zydron, Gate Lord
### Info
* **enemyId:** R1S1StoryVenus7Ultra0
* **enemyName:** Zydron, Gate Lord
* **cardId:** 503130
* **enemyTier:** Ultra
* **raceName:** Vex
* **raceClass:** VexUltraMinotaurA
* **enemyWeapon:** TorchHammer
* **enemyShield:**
* **enemyOtherWeapons:** SlapRifle
* **activityType:** Story
* **activity:** StoryVenus7
* **destination:** Venus
* **location:** EndlessSteps

### Stats
statType | statId
-------- | ------
assistsAgainst | assistsAgainstR1S1StoryVenus7Ultra0
precisionKillsOf | precisionKillOfR1S1StoryVenus7Ultra0
deathsFrom | deathsFromR1S1StoryVenus7Ultra0
killsOf | killsOfR1S1StoryVenus7Ultra0


text:
import axios from 'axios';
import { queryByCategory } from '../config/api';

export const actionTypes = {
    GET_ARTICLES: 'ARTICLES/GET_ARTICLES',
    GET_ARTICLES_PENDING: 'ARTICLES/GET_ARTICLES_PENDING',
    GET_ARTICLES_FULFILLED: 'ARTICLES/GET_ARTICLES_FULFILLED',
    GET_ARTICLES_REJECTED: 'ARTICLES/GET_ARTICLES_REJECTED',
    SEARCH_ARTICLES_PENDING: 'ARTICLES/SEARCH_ARTICLES_PENDING',
    SEARCH_ARTICLES: 'ARTICLES/SEARCH_ARTICLES',
    SEARCH_ARTICLES_FULFILLED: 'ARTICLES/SEARCH_ARTICLES_FULFILLED',
    SEARCH_ARTICLES_REJECTED: 'ARTICLES/SEARCH_ARTICLES_REJECTED',
};

const initialState = {
    isPending: false,
    articles: [],
    searchedArticles: [],
    error: null
};

export default function reducer(state = initialState, action) {
    switch (action.type) {
        case actionTypes.GET_ARTICLES_PENDING:
            return {
                ...state,
                articles: [],
                isPending: true
            }
        case actionTypes.GET_ARTICLES_FULFILLED:
            return {
                ...state,
                isPending: false,
                articles: action.payload
            }
        case actionTypes.GET_ARTICLES_REJECTED:
            return {
                ...state,
                isPending: false,
                error: action.payload
            }
        case actionTypes.SEARCH_ARTICLES_PENDING:
            return {
                ...state,
                searchedArticles: [],
                isPending: true
            }
        case actionTypes.SEARCH_ARTICLES_FULFILLED:
            return {
                ...state,
                isPending: false,
                searchedArticles: action.payload
            }
        case actionTypes.GET_ARTICLES_REJECTED:
            return {
                ...state,
                isPending: false,
                error: action.payload
            }
        default:
            return state;
    }
}

export const actionCreators = {
    getArticles: (category) => ({
        type: actionTypes.GET_ARTICLES,
        payload: axios
            .get(queryByCategory(category))
            .then((result) => result.data.articles)
    }),
    searchArticles: (searchedText) => ({
        type: actionTypes.SEARCH_ARTICLES,
        payload: searchedText
    })
};


text:
{% load admin_static %}{% load url from future %}<!DOCTYPE html>

<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}" />
<link rel="stylesheet" type="text/css" href="{% static "css/base.css" %}" />
{% block extrastyle %}{% endblock %}

{% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}" />{% endif %}

{% block extrahead %}{% endblock %}
{% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE" />{% endblock %}

{% load i18n %}

    {% if not is_popup %}

        {% if user.is_active and user.is_staff %}

            {% trans 'Welcome,' %}
            {% filter force_escape %}{% firstof user.first_name user.username %}{% endfilter %}.
            {% block userlinks %}
                Sair
            {% endblock %}

        {% endif %}

            {% block branding %}{% endblock %}

        {% block nav-global %}{% endblock %}

    {% endif %}

    {% block messages %}
        {% if messages %}

{% for message in messages %}

{{ message }}

        {% endfor %}

        {% endif %}
    {% endblock messages %}

        {% block pretitle %}{% endblock %}
        {% block content_title %}{% if title %}
{{ title }}
{% endif %}{% endblock %}
        {% block content %}
        {% block object-tools %}{% endblock %}
        {{ content }}
        {% endblock %}
        {% block sidebar %}{% endblock %}

    {% block footer %}
Sistema Desenvolvido pela TI Campus Pau dos Ferros
{% endblock %}


text:
The official examples are maintained by the Turborepo team:

- [Turborepo + Next.js Examples](https://github.com/vercel/turborepo/tree/main/examples/with-nextjs)


text:
@interface ZAlertView ()
@property (nonatomic, copy) ZAlertViewDismissBlock dismissBlock;
@end

@implementation ZAlertView

+ (ZAlertView*) showAlertWithTitle:(NSString*)title message:(NSString*)message
	{
	ZAlertView* alert =
		[[ZAlertView alloc]
			initWithTitle:title
			message:message
			delegate:nil
			cancelButtonTitle:@"OK"
			otherButtonTitles:nil];
	[alert show];
	return alert;
	}

//	ToDo: Format as a **super**classy** error message.

+ (ZAlertView*) showAlertWithTitle:(NSString *)title error:(NSError*)error
	{
	#ifdef showfullerror

		return [ZAlertView showAlertWithTitle:title message:[NSString stringWithFormat:@"%@", error]];

	#else

		NSString *message = [error localizedDescription];
		if (!message.length)
			message = error.userInfo.description;
		if (!message.length)
			message = error.description;
		return [ZAlertView showAlertWithTitle:title message:message];

	#endif
	}

+ (ZAlertView*) showAlertWithError:(NSError*)error
	{
	return [ZAlertView showAlertWithTitle:@"Error" error:error];
	}

+ (ZAlertView*) showAlertWithTitle:(NSString *)title
					message:(NSString *)message
					dismissBlock:(ZAlertViewDismissBlock)dismissBlock
					cancelButtonTitle:(NSString*)cancelTitle
					otherButtonTitles:(NSString*)otherButtonTitle, ...
	{
	ZAlertView* alertView =
		[[ZAlertView alloc]
			initWithTitle:title
			message:message
			delegate:nil
			cancelButtonTitle:cancelTitle
			otherButtonTitles:nil];
	alertView.dismissBlock = dismissBlock;
	alertView.delegate = alertView;

	va_list otherButtonList;
    va_start(otherButtonList, otherButtonTitle);
	while (otherButtonTitle)
		{
		[alertView addButtonWithTitle:otherButtonTitle];
		otherButtonTitle = va_arg(otherButtonList, NSString*);
		}
    va_end(otherButtonList);

	[alertView show];
	return alertView;
	}

- (void) alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
	{
	if ([alertView isKindOfClass:[ZAlertView class]])
		{
		ZAlertViewDismissBlock dismissBlock = ((ZAlertView*)alertView).dismissBlock;
		if (dismissBlock)
			dismissBlock((ZAlertView*)alertView, buttonIndex);
		alertView.delegate = nil;
		}
	}

@end


text:
<?php

namespace Magento\CatalogInventory\Model\ResourceModel\Stock\Status;

use Magento\Framework\DB\GenericMapper;

/**
 * Class StockStatusCriteriaMapper
 * @package Magento\CatalogInventory\Model\ResourceModel\Stock\Status
 */
class StockStatusCriteriaMapper extends GenericMapper
{
    /**
     * @inheritdoc
     */
    protected function init()
    {
        $this->initResource('Magento\CatalogInventory\Model\ResourceModel\Stock\Status');
    }

    /**
     * Apply initial query parameters
     *
     * @return void
     */
    public function mapInitialCondition()
    {
        $this->getSelect()->join(
            ['cp_table' => $this->getTable('catalog_product_entity')],
            'main_table.product_id = cp_table.entity_id',
            ['sku', 'type_id']
        );
    }

    /**
     * Apply website filter
     *
     * @param int|\Magento\Store\Model\Website $website
     * @return void
     */
    public function mapWebsiteFilter($website)
    {
        if ($website instanceof \Magento\Store\Model\Website) {
            $website = $website->getId();
        }
        $this->addFieldToFilter('main_table.website_id', $website);
    }

    /**
     * Apply product(s) filter
     *
     * @param int|array|\Magento\Catalog\Model\Product|\Magento\Catalog\Model\Product[] $products
     * @return void
     */
    public function mapProductsFilter($products)
    {
        $productIds = [];
        if (!is_array($products)) {
            $products = [$products];
        }
        foreach ($products as $product) {
            if ($product instanceof \Magento\Catalog\Model\Product) {
                $productIds[] = $product->getId();
            } else {
                $productIds[] = $product;
            }
        }
        if (empty($productIds)) {
            $productIds[] = false;
        }
        $this->addFieldToFilter('main_table.product_id', ['in' => $productIds]);
    }

    /**
     * Apply filter by quantity
     *
     * @param float|int $qty
     * @return void
     */
    public function mapQtyFilter($qty)
    {
        $this->addFieldToFilter('main_table.qty', ['lteq' => $qty]);
    }
}


text:
<TITLE>Review for F.P.1 (1933)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

F.P.1 (1933)

reviewed by
Mark R. Leeper

                         New York City Double Feature
                        Film comment by Mark R. Leeper
                        Copyright 1989 Mark R. Leeper

     I came out of a double feature at the Film Forum in New York City
listening to the conversation of the couple behind me.  "Boy, I guess you
really don't know how bad films were back then," the man said.  I guess the
comment really took me by surprise.  This was an evening I had been looking
forward to for months and which had surpassed all expectations.  The evening
started with a chapter from the serial BATMAN, continued with DELUGE, and
concluded with F.P.1.  Each was a film I'd wanted to see for years.  The
fact that they did not stand up well compared to THE ABYSS is hardly
relevant.  Each of these films is a missing piece of the puzzle of how
science fiction films evolved.  When they find a new fossil at Olduvai they
don't get excited because it came from a really terrific ape.  Of the great
classic science fiction films that I have never seen, I expect them all to
be at best mediocre by today's standards.  Better than that is too much to
hope for.  I frankly never expect to see a great 1930s science fiction film
that I have not already seen.

     The BATMAN serial was not actually from the 1930s, but from 1943, and
directed by Lambert Hillyer, who had previously directed atmospheric
chillers such as THE INVISIBLE RAY and DRACULA'S DAUGHTER.  Lewis Wilson was
the screen's first Batman (succeeded by Robert Lowry and, of course, Adam
West and Michael Keaton).  I have seen Michael Keaton sticking his chin out
of his stiff--probably plastic--costume, and he really looks like the comic
character.  In 1943 Columbia did not have the same materials.  Wilson's
Batman suit really does look like the long underwear it was probably made
from.  There are wrinkles on the legs and the arms.  There is a pressed
crease up the side of the legs.  The cowl has the bat-ears but they are bent
at the ends.  The effect is like a jester's cap and brought howls of
laughter from the audience.  Robin had a full head of curly hair and a
Halloween mask.

     The only recognizable actor in the episode was J. Carrol Naish as the
evil Japanese mad scientist Dr. Daka with a machine that turns men into
zombies.  When Daka turns on his weird electrical equipment the entire
theatre vibrates, probably due to equipment left over from showing THE
TINGLER earlier the same week.  It wasn't as visually impressive as the 1989
BATMAN, but it was a lot more fun.  This was Chapter Five of BATMAN, for the
record.

     Film number two was DELUGE, directed in 1933 by Felix Feist, then 23
years old.  He directed the 1953 DONOVAN'S BRAIN and several episodes of
television's VOYAGE TO THE BOTTOM OF THE SEA.  Here he was directing a
screen version of the novel by S. Fowler Wright.  It should be noted that
DELUGE has long been thought to be a lost film and remains semi-lost.  It
has been just a couple of years since a copy turned up and it is dubbed in
Italian.  For this showing a man at the back of the theatre translated.

     The film opens by reminding us that God promised not to destroy the
world by flood again and then, after a buildup of nature going very sour,
proceeds to show most of the world being destroyed just the same way again.
We are told that the west coast has fallen into the ocean but never see it.
We do see New York City struck down by tidal waves and we see buildings
crumble.  If the effects were believable they would be spectacular.
However, even a contemporary reviewer complained that the effects were none
too convincing.  My audience apparently agreed and jeered.  Now I like
really credible effects.  They are a virtue.  But a reasonable attempt at
effects is sufficient for me.  They are, after all, just a device to carry
the plot.  When I go to a puppet show I do not complain that the puppets do
not fool me into thinking they are real people.  Weak effects are quite
forgivable as far as I am concerned if the rest of the film captures my
interest.

     And DELUGE is a very interesting film, if not for anything intrinsic at
least for where it fits historically.  What is particularly interesting is
how the film reminds one of films that came after, but not of films that
came before.  After the holocaust is over and there are just a handful of
people left the story has definite parallels to NO BLADE OF GRASS and the
excellent British television series THE SURVIVORS.

     Before the holocaust we have been introduced to iron-jawed Martin
(Sidney Blackmer), a family man who saves his family by moving them to a
stone quarry but is somehow separated from them.  And we meet Claire, an
athletic swimmer.  The storm washes Claire to the doorstep of two criminals.
Claire becomes one vertex in a triangle that leads to the murder of one of
the criminals.  Roger Corman would use almost the same plot for the 1960
LAST WOMAN ON EARTH.

     Claire escapes the killer Jephson only to be found by Martin, alone
since the storm.  The two of them try to survive together.  However, in the
mean time, a group of survivors has set up a small town.  They have thrown
out some undesirables and the criminals pick Jephson as their leader.  He
leads them on a raid against Martin and Claire.  At this point the film has
sort of degenerated into a bad Western plot.  Surprisingly, things do *not*
work out well for all concerned, and the film does at times touch on
questions of whether bigamy is justifiable in a post-holocaust world.  The
story if crudely done, but that didn't stop much of it from being redone,
often no better, by other filmmakers.  A good film?  No.  But not a bad film
either and definitely an important artifact.

     Waiting for the film to start, I started talking to someone sitting
next to me who had just finished seeing F.P.1.  He assured me it really
cornball with bad dialog.  I think I'd like to thank him for lowering my
expectations and making F.P.1 such a pleasant surprise when my turn came to
see it.  F.P.1 (1932) is an engineering film, sort of a forerunner to THE
TUNNEL and its remake THE TRANSATLANTIC TUNNEL, and later THINGS TO COME.
Like the Tunnel films, F.P.1 concerns itself with engineering feats to aid
transatlantic travel.  Instead of being about a tunnel, it is about the
building of a great floating airstrip and hotel to be built mid-Atlantic,
the Floating Platform 1.

     F.P.1 is really a German film refilmed in English to give it the
trappings of a British film.  It is the story of engineer Captain Drost, who
designed the platform but could not sell it to anyone, and his friend pilot
Major Ellissen, an enigmatic figure who arranges stunts to bring the
platform to the attention of a shipyard, then competes with Drost for the
attentions of heiress Clare Lennartz.  Ellissen is played by a very dashing
Conrad Veidt.

     F.P.1 is a spectacular melodrama of a great engineering feat and what
goes into building it.  There is a subplot of a consortium dedicated to
destroying the great platform for no readily apparent reason.

     I am glad I went.

                                        Mark R. Leeper
                                        att!mtgzx!leeper
                                        leeper@mtgzx.att.com
.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package com.kotcrab.vis.editor.module.scene.system;

import com.artemis.Aspect;
import com.artemis.Component;
import com.artemis.Entity;
import com.artemis.systems.EntityProcessingSystem;
import com.artemis.utils.Bag;
import com.badlogic.gdx.utils.IntArray;
import com.kotcrab.vis.runtime.assets.VisAssetDescriptor;
import com.kotcrab.vis.runtime.properties.StoresAssetDescriptor;

/**
 * This system should be passive.
 * @author Kotcrab
 */
public class AssetsUsageAnalyzer extends EntityProcessingSystem {
	private IntArray ids;
	private VisAssetDescriptor searchFor;

	private Bag<Component> fillBag = new Bag<>();

	public AssetsUsageAnalyzer () {
		super(Aspect.all());
	}

	@Override
	protected void process (Entity e) {
		fillBag.clear();
		e.getComponents(fillBag);

		for (Component component : fillBag) {
			if (component instanceof StoresAssetDescriptor) {
				StoresAssetDescriptor storage = (StoresAssetDescriptor) component;
				VisAssetDescriptor asset = storage.getAsset();

				if (asset != null && asset.compare(searchFor)) {
					ids.add(e.getId());
					return;
				}
			}
		}
	}

	public void collectUsages (IntArray ids, VisAssetDescriptor searchFor) {
		this.ids = ids;
		this.searchFor = searchFor;

		setEnabled(true);
		process();
		setEnabled(false);
	}
}


text:
package org.oldo.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Default stream helper
 */
public class StreamsImpl implements Streams {

    private static final int END_OF_STREAM = -1;

    private final int bufferSize;

    public StreamsImpl(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    @Override
    public byte[] allBytes(InputStream in) {
        final ByteArrayOutputStream out = new ByteArrayOutputStream(bufferSize);
        copy(in, out);
        return out.toByteArray();
    }

    @Override
    public int copy(InputStream inputStream, OutputStream outputStream) {
        final byte[] buf = new byte[bufferSize];
        int total = 0;
        // try-with-resources auto-closes the streams in a hidden finally block
        try (InputStream in = inputStream; OutputStream out = outputStream) {
            for (int read = in.read(buf);
                 read != END_OF_STREAM;
                 read = in.read(buf)) {

                out.write(buf, 0, read);
                total += read;
            }
            out.flush();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        return total;
    }
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, OnChanges, DoCheck, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { HImage  } from './image';
import { Callback } from './callback';
import { Graphics } from './graphics';
import { Utility } from './utility';

let width = 100;
let height = 100;

@Component({
  selector: 'bla',
  template: '
<canvas [attr.id]="uuid" #renderCanvas class="canvas" [(attr.width)]="width" [(style.width.px)]="stwidth"   [(attr.height)]="height" [(style.height.px)]="stheight" ></canvas>
',
  styleUrls: []
})
export class SurfaceComponent {
  width: number;
  height: number;
  stwidth: number;
  stheight: number;

  @ViewChild("renderCanvas") canvas: ElementRef;
  /**
   *
   */
  constructor() {
    this.width = width;
    this.height = height;

  }
}

describe('graphics', () => {
  let comp: SurfaceComponent;
  let fixture: ComponentFixture<SurfaceComponent>;
  let canvas: HTMLCanvasElement;
  let img: HImage;
  let context: CanvasRenderingContext2D;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [SurfaceComponent], // declare the test component
    });

    fixture = TestBed.createComponent(SurfaceComponent);

    comp = fixture.componentInstance; // BannerComponent test instance
    canvas = comp.canvas.nativeElement as HTMLCanvasElement;
    img = new HImage(width, height);
    context = canvas.getContext("2d");
  });

  it('should  create a valid graphics ', () => {
    let grp: Graphics = new Graphics(comp.canvas, width, height,1);
    expect(grp.width).toEqual(width);
    expect(grp.height).toEqual(height);
    expect(grp.scale).toEqual(1);

  });

  it('should  drawImage ', () => {
    let grp = new Graphics(comp.canvas, width, height,1);
    grp.drawImage(img);

     let result = true;
      var data = context.getImageData(0, 0, width, height).data;
      data.forEach(
        (val, index) => {
          if (img.Pixels[index] != val)
            result = false;
        });

    expect(result).toBe(true);

  });

});


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Source alignment and coordinate frames — MNE 0.18.2 documentation</title>
    <link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/bootstrap_divs.css" />
    <link rel="stylesheet" href="../../_static/reset-syntax.css" type="text/css" />

    <link rel="shortcut icon" href="../../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />

    <link rel="stylesheet" href="../../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/flag-icon.css" type="text/css" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.18.2

Install

Documentation

API

Glossary

Examples

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.18.2

  </button>

Development

v0.18 (stable)

v0.17

v0.16

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Source alignment and coordinate frames

Understanding coordinate frames

Coordinate frame definitions

A bad example

A good example

Defining the head↔MRI trans using the GUI

Alignment without MRI

<form action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Note

Click here to download the full example code

Source alignment and coordinate frames¶

The aim of this tutorial is to show how to visually assess that the data are
well aligned in space for computing the forward solution, and understand
the different coordinate frames involved in this process.

Topics

Understanding coordinate frames

Coordinate frame definitions

A bad example

A good example

Defining the head↔MRI trans using the GUI

Alignment without MRI

Let's start out by loading some data.

import os.path as op

import numpy as np
from mayavi import mlab

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname = op.join(data_path, 'MEG', 'sample',
                      'sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(raw_fname)
trans = mne.read_trans(trans_fname)
src = mne.read_source_spaces(op.join(subjects_dir, 'sample', 'bem',
                                     'sample-oct-6-src.fif'))

Out:

Opening raw data file /home/circleci/mne_data/MNE-sample-data/MEG/sample/sample_audvis_raw.fif...
    Read a total of 3 projection items:
        PCA-v1 (1 x 102)  idle
        PCA-v2 (1 x 102)  idle
        PCA-v3 (1 x 102)  idle
    Range : 25800 ... 192599 =     42.956 ...   320.670 secs
Ready.
Current compensation grade : 0
    Reading a source space...
    Computing patch statistics...
    Patch information added...
    Distance information added...
    [done]
    Reading a source space...
    Computing patch statistics...
    Patch information added...
    Distance information added...
    [done]
    2 source spaces read

Understanding coordinate frames¶

For M/EEG source imaging, there are three coordinate frames that we must
bring into alignment using two 3D
transformation matrices
that define how to rotate and translate points in one coordinate frame
to their equivalent locations in another.

mne.viz.plot_alignment() is a very useful function for inspecting
these transformations, and the resulting alignment of EEG sensors, MEG
sensors, brain sources, and conductor models. If the subjects_dir and
subject parameters are provided, the function automatically looks for the
Freesurfer MRI surfaces to show from the subject's folder.

We can use the show_axes argument to see the various coordinate frames
given our transformation matrices. These are shown by axis arrows for each
coordinate frame:

shortest arrow is (R)ight/X

medium is forward/(A)nterior/Y

longest is up/(S)uperior/Z

i.e., a RAS coordinate system in each case. We can also set
the coord_frame argument to choose which coordinate
frame the camera should initially be aligned with.

Let's take a look:

mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
                       subjects_dir=subjects_dir, surfaces='head-dense',
                       show_axes=True, dig=True, eeg=[], meg='sensors',
                       coord_frame='meg')
mlab.view(45, 90, distance=0.6, focalpoint=(0., 0., 0.))
print('Distance from head origin to MEG origin: %0.1f mm'
      % (1000 * np.linalg.norm(raw.info['dev_head_t']['trans'][:3, 3])))
print('Distance from head origin to MRI origin: %0.1f mm'
      % (1000 * np.linalg.norm(trans['trans'][:3, 3])))

Out:

Using lh.seghead for head surface.
Distance from head origin to MEG origin: 65.0 mm
Distance from head origin to MRI origin: 29.9 mm

Coordinate frame definitions¶

Neuromag head coordinate frame ("head", pink axes)

Defined by the intersection of 1) the line between the LPA
(red sphere) and RPA (purple sphere), and
2) the line perpendicular to this LPA-RPA line one that goes through
the Nasion (green sphere).
The axes are oriented as X origin→RPA, Y origin→Nasion,
Z origin→upward (orthogonal to X and Y).

Note

This gets defined during the head digitization stage during
acquisition, often by use of a Polhemus or other digitizer.

MEG device coordinate frame ("meg", blue axes)

This is defined by the MEG manufacturers. From the Elekta user manual:

The origin of the device coordinate system is located at the center
of the posterior spherical section of the helmet with axis going
from left to right and axis pointing front. The axis is, again
normal to the plane with positive direction up.

Note

The device is coregistered with the head coordinate frame
during acquisition via emission of sinusoidal currents in
head position indicator (HPI) coils
(magenta spheres) at the beginning of the
recording. This is stored in raw.info['dev_head_t'].

MRI coordinate frame ("mri", gray axes)

Defined by Freesurfer, the MRI (surface RAS) origin is at the
center of a 256×256×256 1mm anisotropic volume (may not be in the center
of the head).

Note

This is aligned to the head coordinate frame that we
typically refer to in MNE as trans.

A bad example¶

Let's try using trans=None, which (incorrectly!) equates the MRI
and head coordinate frames.

mne.viz.plot_alignment(raw.info, trans=None, subject='sample', src=src,
                       subjects_dir=subjects_dir, dig=True,
                       surfaces=['head-dense', 'white'], coord_frame='meg')

Out:

Using lh.seghead for head surface.
Getting helmet for system 306m

It is quite clear that the MRI surfaces (head, brain) are not well aligned
to the head digitization points (dots).

A good example¶

Here is the same plot, this time with the trans properly defined
(using a precomputed matrix).

mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
                       src=src, subjects_dir=subjects_dir, dig=True,
                       surfaces=['head-dense', 'white'], coord_frame='meg')

Out:

Using lh.seghead for head surface.
Getting helmet for system 306m

Defining the head↔MRI trans using the GUI¶

You can try creating the head↔MRI transform yourself using
mne.gui.coregistration().

First you must load the digitization data from the raw file
(Head Shape Source). The MRI data is already loaded if you provide the
subject and subjects_dir. Toggle Always Show Head Points to see
the digitization points.

To set the landmarks, toggle Edit radio button in MRI Fiducials.

Set the landmarks by clicking the radio button (LPA, Nasion, RPA) and then
clicking the corresponding point in the image.

After doing this for all the landmarks, toggle Lock radio button. You
can omit outlier points, so that they don't interfere with the finetuning.

Note

You can save the fiducials to a file and pass
mri_fiducials=True to plot them in
mne.viz.plot_alignment(). The fiducials are saved to the
subject's bem folder by default.

Click Fit Head Shape. This will align the digitization points to the
head surface. Sometimes the fitting algorithm doesn't find the correct
alignment immediately. You can try first fitting using LPA/RPA or fiducials
and then align according to the digitization. You can also finetune
manually with the controls on the right side of the panel.

Click Save As... (lower right corner of the panel), set the filename
and read it with mne.read_trans().

For more information, see step by step instructions
in these slides.
Uncomment the following line to align the data yourself.

# mne.gui.coregistration(subject='sample', subjects_dir=subjects_dir)

Alignment without MRI¶

The surface alignments above are possible if you have the surfaces available
from Freesurfer. mne.viz.plot_alignment() automatically searches for
the correct surfaces from the provided subjects_dir. Another option is
to use a spherical conductor model. It is
passed through bem parameter.

sphere = mne.make_sphere_model(info=raw.info, r0='auto', head_radius='auto')
src = mne.setup_volume_source_space(sphere=sphere, pos=10.)
mne.viz.plot_alignment(
    raw.info, eeg='projected', bem=sphere, src=src, dig=True,
    surfaces=['brain', 'outer_skin'], coord_frame='meg', show_axes=True)

Out:

Fitted sphere radius:         91.0 mm
Origin head coordinates:      -4.1 16.0 51.7 mm
Origin device coordinates:    1.4 17.8 -10.3 mm

Equiv. model fitting -> RV = 0.0034856 %
mu1 = 0.944754    lambda1 = 0.137089
mu2 = 0.667504    lambda2 = 0.683819
mu3 = -0.26966    lambda3 = -0.0105378
Set up EEG sphere model with scalp radius    91.0 mm

Sphere                : origin at (-4.1 16.0 51.7) mm
              radius  : 81.9 mm
grid                  : 10.0 mm
mindist               : 5.0 mm

Setting up the sphere...
Surface CM = (  -4.1   16.0   51.7) mm
Surface fits inside a sphere with radius   81.9 mm
Surface extent:
    x =  -86.0 ...   77.8 mm
    y =  -65.9 ...   97.9 mm
    z =  -30.2 ...  133.7 mm
Grid extent:
    x =  -90.0 ...   80.0 mm
    y =  -70.0 ...  100.0 mm
    z =  -40.0 ...  140.0 mm
6156 sources before omitting any.
2300 sources after omitting infeasible sources.
1904 sources remaining after excluding the sources outside the surface and less than    5.0 mm inside.
Adjusting the neighborhood info...
Getting helmet for system 306m
    Triangle neighbors and vertex normals...

It is also possible to use mne.gui.coregistration()
to warp a subject (usually fsaverage) to subject digitization data, see
these slides.

Total running time of the script: ( 0 minutes  16.667 seconds)

Estimated memory usage:  9 MB

Download Python source code: plot_source_alignment.py

Download Jupyter notebook: plot_source_alignment.ipynb

Gallery generated by Sphinx-Gallery

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2019, MNE Developers. Last updated on 2019-07-11.


text:
package com.winterwell.depot.merge;

import com.winterwell.utils.TodoException;

/**
 * TODO
 * @author daniel
 *
 */
public class StringMerger extends AMerger<String> {

	public StringMerger() {
		super(null);
	}

	@Override
	public Diff diff(String before, String after) {
		throw new TodoException();
	}

	@Override
	public String applyDiff(String a, Diff diff) {
		throw new TodoException();
	}

	@Override
	public String stripDiffs(String v) {
		return v;
	}

}


text:
global using Azure.Core;
global using Azure.Identity;
global using Autofac.Extensions.DependencyInjection;
global using Autofac;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Extensions;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure.ActionResults;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure.Exceptions;
global using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents;
global using Grpc.Core;
global using Microsoft.AspNetCore.Hosting;
global using Microsoft.AspNetCore.Http;
global using Microsoft.AspNetCore.Builder;
global using Microsoft.AspNetCore.Mvc.Filters;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.AspNetCore.Server.Kestrel.Core;
global using Microsoft.AspNetCore;
global using Microsoft.Extensions.Logging;
global using Microsoft.EntityFrameworkCore.Design;
global using Microsoft.EntityFrameworkCore.Metadata.Builders;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
global using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services;
global using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Utilities;
global using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure.EntityConfigurations;
global using Microsoft.eShopOnContainers.Services.Catalog.API;
global using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Model;
global using Microsoft.eShopOnContainers.Services.Catalog.API.ViewModel;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Grpc;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Options;
global using Polly.Retry;
global using Polly;
global using Serilog.Context;
global using Serilog;
global using System.Collections.Generic;
global using System.Data.Common;
global using System.Data.SqlClient;
global using System.Globalization;
global using System.IO.Compression;
global using System.IO;
global using System.Linq;
global using System.Net;
global using System.Text.RegularExpressions;
global using System.Threading.Tasks;
global using System;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure.Filters;
global using HealthChecks.UI.Client;
global using Microsoft.AspNetCore.Diagnostics.HealthChecks;
global using Azure.Messaging.ServiceBus;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
global using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus;
global using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHandling;
global using Microsoft.Extensions.Diagnostics.HealthChecks;
global using Microsoft.OpenApi.Models;
global using RabbitMQ.Client;
global using System.Reflection;


text:
package auth

import (
	"github.com/Unknwon/macaron"

	"github.com/macaron-contrib/binding"
)

type AdminEditUserForm struct {
	FullName     string `form:"fullname" binding:"MaxSize(100)"`
	Email        string `binding:"Required;Email;MaxSize(50)"`
	Password     string `binding:"OmitEmpty;MinSize(6);MaxSize(255)"`
	Website      string `binding:"MaxSize(50)"`
	Location     string `binding:"MaxSize(50)"`
	Avatar       string `binding:"Required;Email;MaxSize(50)"`
	Active       bool
	Admin        bool
	AllowGitHook bool
	LoginType    int
}

func (f *AdminEditUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
	return validate(errs, ctx.Data, f, ctx.Locale)
}


text:
drop table users if exists;
drop table friend if exists;

create table users (
  id int,
  name varchar(20)
);

create table friend (
  user_id int,
  friend_id int
);

insert into users (id, name) values
(1, 'User1'), (2, 'User2'), (3, 'User3');

insert into friend (user_id, friend_id) values
(1, 2), (2, 2), (2, 3);

drop table blog if exists;
drop table author if exists;

create table blog (
  id int,
  title varchar(16),
  author_id int,
  co_author_id int
);

create table author (
  id int,
  name varchar(16),
  reputation int
);

insert into blog (id, title, author_id, co_author_id) values
(1, 'Blog1', 1, 2), (2, 'Blog2', 2, 3);

insert into author (id, name, reputation) values
(1, 'Author1', 1), (2, 'Author2', 2), (3, 'Author3', 3);


text:
import { CounterActions } from '../actions/counter-actions';

export default (state: number = 0, action:any) => {
  switch (action.type) {
    case CounterActions.INCREMENT_COUNTER:
      return state + 1;
    case CounterActions.DECREMENT_COUNTER:
      return state - 1;
    case CounterActions.RANDOMIZE_COUNTER:
      return action.payload;
    default:
      return state;
  }
}


text:
using System;
using System.IO;

namespace XOFF.Core
{

    /// <summary>
    /// </summary>
    /// <typeparam name="TResult"></typeparam>

    public class XOFFOperationResult<TResult>
    {
        private XOFFOperationResult()
        {
        }

        public bool Success { get;  private set; }
        public TResult Result { get;  set; }
        public string Message { get;  set; }
        public Exception Exception { get; private set; }

        public static XOFFOperationResult<TResult> CreateSuccessResult(TResult result)
        {
            return new XOFFOperationResult<TResult> { Success = true, Result = result };
        }

        public static XOFFOperationResult<TResult> CreateFailure(string nonSuccessMessage)
        {
            return new XOFFOperationResult<TResult> { Success = false, Message = nonSuccessMessage };
        }

        public static XOFFOperationResult<TResult> CreateFailure(Exception ex)
        {
            return new XOFFOperationResult<TResult>
            {
                Success = false,
                Message = String.Format("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace),
                Exception = ex
            };
        }

        public XOFFOperationResult ToOperationResult()
        {
            return new XOFFOperationResult()
            {
                Success = this.Success,
                Exception = this.Exception,
                Message = this.Message
            };
        }

        public static XOFFOperationResult<TResult> CreateFailure(string message, Exception exception)
        {
            return new XOFFOperationResult<TResult> { Success = false, Message = message, Exception = exception };
        }
    }

    /*
      This class has been borrowed and adapted from https://www.codeproject.com/Articles/1022462/Error-Handling-in-SOLID-Csharp-NET-The-Operation-R
      This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
      */

}

public class XOFFOperationResult
{
    public bool Success { get; set; }
    public string Message { get; internal set; }
    public Exception Exception { get; internal set; }

    public static XOFFOperationResult CreateSuccessResult(string message = "Success")
    {
        return new XOFFOperationResult { Success = true, Message = message };
    }

    public static XOFFOperationResult CreateFailure(string message, Exception exception)
	{
        return new XOFFOperationResult { Success = false, Message = message, Exception = exception};
    }

    public static XOFFOperationResult CreateFailure(string message)
    {
        return new XOFFOperationResult { Success = false, Message = message };
    }
    public static XOFFOperationResult CreateFailure(Exception ex)
    {

        if (ex != null)
        {
            return new XOFFOperationResult
            {
                Success = false,
                Message = String.Format("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace),
                Exception = ex
            };
        }
        return CreateFailure("");

    }

    /*
      This class has been borrowed and adapted from https://www.codeproject.com/Articles/1022462/Error-Handling-in-SOLID-Csharp-NET-The-Operation-R
      This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
      */

}


text:
CaoLiao._setEmail = function(userId, email) {
	email = s.trim(email);
	if (!userId) {
		throw new Meteor.Error('error-invalid-user', 'Invalid user', { function: '_setEmail' });
	}

	if (!email) {
		throw new Meteor.Error('error-invalid-email', 'Invalid email', { function: '_setEmail', field: email });
	}

	CaoLiao.validateEmailDomain(email);

	const user = CaoLiao.models.Users.findOneById(userId);

	// User already has desired username, return
	if (user.emails && user.emails[0] && user.emails[0].address === email) {
		return user;
	}

	// Check email availability
	if (!CaoLiao.checkEmailAvailability(email)) {
		throw new Meteor.Error('error-field-unavailable', email + ' is already in use :(', { function: '_setEmail', field: email });
	}

	// Set new email
	CaoLiao.models.Users.setEmail(user._id, email);
	user.email = email;
	return user;
};

CaoLiao.setEmail = CaoLiao.RateLimiter.limitFunction(CaoLiao._setEmail, 1, 60000, {
	0: function() { return !Meteor.userId() || !CaoLiao.authz.hasPermission(Meteor.userId(), 'edit-other-user-info'); } // Administrators have permission to change others emails, so don't limit those
});


text:
<?php

namespace VGMdb\Component\HttpKernel\EventListener;

use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Silex\ExceptionListenerWrapper as BaseExceptionListenerWrapper;

/**
 * Wraps exception listeners.
 *
 * @author Gigablah <gigablah@vgmdb.net>
 */
class ExceptionListenerWrapper extends BaseExceptionListenerWrapper
{
    public function __invoke(GetResponseForExceptionEvent $event)
    {
        if (false === $argument = $this->getArgument($event)) {
            return;
        }

        $exception = $event->getException();
        $code = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;

        $response = call_user_func($this->callback, $argument, $code);

        $this->ensureResponse($response, $event);
    }

    protected function getArgument(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if (is_array($this->callback)) {
            $callbackReflection = new \ReflectionMethod($this->callback[0], $this->callback[1]);
        } elseif (is_object($this->callback) && !$this->callback instanceof \Closure) {
            $callbackReflection = new \ReflectionObject($this->callback);
            $callbackReflection = $callbackReflection->getMethod('__invoke');
        } else {
            $callbackReflection = new \ReflectionFunction($this->callback);
        }

        if ($callbackReflection->getNumberOfParameters() > 0) {
            $parameters = $callbackReflection->getParameters();
            $expectedParameter = $parameters[0];
            if (!$expectedParameter->getClass()) {
                return false;
            }
            if ($expectedParameter->getClass()->isInstance($event)) {
                return $event;
            }
            if ($expectedParameter->getClass()->isInstance($exception)) {
                return $exception;
            }
        }

        return false;
    }
}