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

<TITLE>
AuditListener (Simian - Similarity Analyser v2.3.33)
</TITLE>

<META NAME="date" CONTENT="2011-08-15">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

Simian - Similarity Analyser v2.3.33

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.harukizaemon.simian

Interface AuditListener

All Known Implementing Classes:
CompositeAuditListener, DecoratorAuditListener

public interface AuditListener

Classes wishing to be notified of checking events should implement this interface.

Version:

$Id: AuditListener.java 3019 2007-11-08 09:59:10Z haruki_zaemon $

Author:

Simon Harris

Method Summary

 void
block(Block block)

          Called once for each block of duplicate lines within a set.

 void
endCheck(CheckSummary summary)

          Called when checking has finished.

 void
endSet(java.lang.String text)

          Called to indicate the end of a set of blocks of duplicate lines.

 void
fileProcessed(SourceFile sourceFile)

          Called when a file has been loaded.

 void
startCheck(Options options)

          Called when checking begins.

 void
startSet(int lineCount)

          Called to indicate the start of a set of blocks of duplicate lines.

Method Detail

startCheck

void startCheck(Options options)

Called when checking begins.

Parameters:
options - The options used when performing the check

fileProcessed

void fileProcessed(SourceFile sourceFile)

Called when a file has been loaded.

Parameters:
sourceFile - The file that was just loaded

startSet

void startSet(int lineCount)

Called to indicate the start of a set of blocks of duplicate lines.

Parameters:
lineCount - The number of lines the blocks have in common

block

void block(Block block)

Called once for each block of duplicate lines within a set.

Parameters:
block - the duplicated block.

endSet

void endSet(java.lang.String text)

Called to indicate the end of a set of blocks of duplicate lines.

Parameters:
text - The text

endCheck

void endCheck(CheckSummary summary)

Called when checking has finished.

Parameters:
summary -

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

Simian - Similarity Analyser v2.3.33

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (c) 2003-2011 Simon Harris.  All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Mycotaxon 10(1): 117 (1979)

#### Original name
Mucilopilus Wolfe

### Remarks
null


text:
package com.jmandrillapi.utils;

public class ApiServiceMethods {

	public class Users {
		public static final String BASE_USER_PATH = "/users";
		public static final String INFO = BASE_USER_PATH + "/info";
		public static final String PING = BASE_USER_PATH + "/ping";
		public static final String PING2 = BASE_USER_PATH + "/ping2";
		public static final String SENDERS = BASE_USER_PATH + "/senders";
	}

	public class Messages {
		public static final String BASE_MSG_PATH = "/messages";
		public static final String SEND = BASE_MSG_PATH + "/send";
		public static final String SEND_TEMPLATE = BASE_MSG_PATH + "/send-template";
	}

	public class SubAccounts {
		public static final String BASE_SUBACCT_PATH = "/subaccounts";
		public static final String LIST = BASE_SUBACCT_PATH + "/list";
		public static final String ADD = BASE_SUBACCT_PATH + "/add";
		public static final String INFO = BASE_SUBACCT_PATH + "/info";
		public static final String UPDATE = BASE_SUBACCT_PATH + "/update";
		public static final String DELETE = BASE_SUBACCT_PATH + "/delete";
		public static final String PAUSE = BASE_SUBACCT_PATH + "/pause";
		public static final String RESUME = BASE_SUBACCT_PATH + "/resume";
	}

}


text:
class CreateEventPublisherAnonymousUsers < ActiveRecord::Migration
  def change
    create_table :event_publisher_anonymous_users do |t|

      t.timestamps
    end
  end
end


text:
using System;
using System.Web.UI.WebControls;
using Ninject;
using Subtext.Framework.Configuration;
using Subtext.Framework.Security;
using Subtext.Web.Properties;

namespace Subtext.Web.Admin.Pages
{
    /// <summary>
    /// Summary description for Password.
    /// </summary>
    public partial class Security : AdminOptionsPage
    {
        protected Label Message;
        protected ValidationSummary ValidationSummary1;

        [Inject]
        public IAccountService AccountService { get; set; }

        protected override void BindLocalUI()
        {
            if (!String.IsNullOrEmpty(Blog.OpenIdUrl))
            {
                tbOpenIDURL.Text = Blog.OpenIdUrl;
            }

            tbOpenIDServer.Text = Blog.OpenIdServer;
            tbOpenIDDelegate.Text = Blog.OpenIdDelegate;

            base.BindLocalUI();
        }

        protected void btnSaveOptions_Click(object sender, EventArgs e)
        {
            string openIdUrl = tbOpenIDURL.Text == "http://" ? string.Empty : tbOpenIDURL.Text;
            Blog.OpenIdUrl = openIdUrl;

            Repository.UpdateConfigData(Blog);
        }

        protected void btnChangePassword_Click(object sender, EventArgs e)
        {
            string failureMessage = Resources.Security_PasswordNotUpdated;
            if (Page.IsValid)
            {
                if (SecurityHelper.IsValidPassword(SubtextContext.Blog, tbCurrent.Text))
                {
                    if (tbPassword.Text == tbPasswordConfirm.Text)
                    {
                        AccountService.UpdatePassword(tbPassword.Text);

                        Messages.ShowMessage(Resources.Security_PasswordUpdated);
                    }
                    else
                    {
                        Messages.ShowError(failureMessage);
                    }
                }
                else
                {
                    Messages.ShowError(failureMessage);
                }
            }
            else
            {
                Messages.ShowError(failureMessage);
            }
        }

        protected void OnSavePassthroughClick(object sender, EventArgs e)
        {
            Blog.OpenIdServer = tbOpenIDServer.Text;
            Blog.OpenIdDelegate = tbOpenIDDelegate.Text;

            Repository.UpdateConfigData(Blog);
        }
    }
}


text:
package org.lodder.subtools.sublibrary.model;

public enum SubtitleMatchType {
    EXACT, KEYWORD, TEAM, EVERYTHING
}


text:
=========================================
Exercise 8.8 - bfree maintained by malloc
=========================================

Question
========

Write a routine bfree(p,n) that will free any arbitrary block p of n characters
into the free list maintained by malloc and free. By using bfree, a user can add
a static or external array to the free list at any time.

.. literalinclude:: ../../languages/cprogs/Ex_8.8_bfree.c
   :language: c
   :tab-width: 4

.. runcode:: ../../languages/cprogs/Ex_8.8_bfree.c
   :language: c
   :codesite: ideone

Explanation
===========

.. git_changelog::

.. seealso::

   * :c-suggest-improve:`Ex_8.8_bfree.c`
   * :c-better-explain:`Ex_8.8_bfree.rst`


text:
//The MIT License (MIT)
//Copyright (c) 2014 abdallah HACID, https://www.facebook.com/ab.hacid

//Permission is hereby granted, free of charge, to any person obtaining a copy of this software
//and associated documentation files (the "Software"), to deal in the Software without restriction,
//including without limitation the rights to use, copy, modify, merge, publish, distribute,
//sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
//is furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all copies or
//substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// Project Hosting for Open Source Software on Github : https://github.com/abhacid/cAlgoBot

using System;
using cAlgo.API;

namespace cAlgo.Indicators
{
    [Levels(-20, -50, -80)]
    [Indicator(ScalePrecision = 2, AccessRights = AccessRights.None)]
    public class WPRIndicator : Indicator
    {
        [Parameter(DefaultValue = 14)]
        public int Period { get; set; }

        [Output("Main", Color = Colors.CornflowerBlue)]
        public IndicatorDataSeries Result { get; set; }

        public override void Calculate(int index)
        {
            double max = MarketSeries.High.Maximum(Period);
            double min = MarketSeries.Low.Minimum(Period);
            double close = MarketSeries.Close[index];

            if ((max - min) > 0)
                Result[index] = -100 * (max - close) / (max - min);
            else
                Result[index] = 0.0;

        }
    }
}


text:
struct PARA_APP1: public PARA_VN
{
    int  bkg_thresh; //for initial reconstruction generation
    int  visible_thresh; //for dark pruning
    int  channel;
    int  downsample_factor; //when set to be 0, then set b_256cube to be 1 which means downsample based on fit to a 256px cube automatically
    int  b_256cube;

    QString inimg_file, inmarker_file, outswc_file;

    PARA_APP1()
    {
        bkg_thresh = -1; //-1 for auto-thresholding, i.e. using the ave of image channel; //10; //30; change to 10 by PHC 2012-10-11
        visible_thresh = 30;
        channel = 0;
        downsample_factor = 2;
        b_256cube = 1; //whether or not preprocessing to downsample to a 256xYxZ cube UINT8 for tracing

        inimg_file = "";
        inmarker_file = "";
        outswc_file = "";
    }

    bool app1_dialog()
    {
        if (!p4dImage || !p4dImage->valid())
            return false;

        int chn_num = p4dImage->getCDim();
        // fetch parameters from dialog
        {
            //set update the dialog
            QDialog * dialog = new QDialog();
            dialog->setWindowTitle("Vaa3D-Neuron2 Auto_tracing Based on APP1 (All-Path-Pruning-v1)");
            QGridLayout * layout = new QGridLayout();

            QSpinBox * channel_spinbox = new QSpinBox();
            channel_spinbox->setRange(1,chn_num);
            channel_spinbox->setValue(1);

            QSpinBox * bkgthresh_spinbox = new QSpinBox();
            bkgthresh_spinbox->setRange(-1, 255);
            bkgthresh_spinbox->setValue(bkg_thresh);

            QSpinBox * visthresh_spinbox = new QSpinBox();
            visthresh_spinbox->setRange(1, 255);
            visthresh_spinbox->setValue(visible_thresh);

            QSpinBox * downsample_spinbox = new QSpinBox();
            downsample_spinbox->setRange(0, 10);
            downsample_spinbox->setValue(downsample_factor);

            layout->addWidget(new QLabel("color channel"),0,0);
            layout->addWidget(channel_spinbox, 0,1,1,5);
            layout->addWidget(new QLabel("background_threshold \n  (if set as -1, \nthen auto-thresholding)"),1,0);
            layout->addWidget(bkgthresh_spinbox, 1,1,1,5);
            layout->addWidget(new QLabel("visibility threshold \n  (normally do not need to change)"),2,0);
            layout->addWidget(visthresh_spinbox, 2,1,1,5);

            QHBoxLayout * hbox1 = new QHBoxLayout();
            hbox1->addWidget(new QLabel("downsample factor \n  (set 0 for auto-downsample)"));
            hbox1->addWidget(downsample_spinbox);

            layout->addLayout(hbox1,3,0,1,6);

            QHBoxLayout * hbox2 = new QHBoxLayout();
            QPushButton * ok = new QPushButton(" ok ");
            ok->setDefault(true);
            QPushButton * cancel = new QPushButton("cancel");
            hbox2->addWidget(cancel);
            hbox2->addWidget(ok);

            layout->addLayout(hbox2,4,0,1,6);
            dialog->setLayout(layout);
            QObject::connect(ok, SIGNAL(clicked()), dialog, SLOT(accept()));
            QObject::connect(cancel, SIGNAL(clicked()), dialog, SLOT(reject()));

            //run the dialog

            if(dialog->exec() != QDialog::Accepted)
                return false;

            //get the dialog return values
            channel = channel_spinbox->value() - 1;
            bkg_thresh = bkgthresh_spinbox->value();
            visible_thresh = visthresh_spinbox->value();
            downsample_factor = downsample_spinbox->value();

            b_256cube = (downsample_factor==0) ? 1 : 0;

            if (dialog) {delete dialog; dialog=0;}
        }

        return true;
    }

    bool fetch_para_commandline(const V3DPluginArgList &input, V3DPluginArgList &output, V3DPluginCallback2 &callback, QWidget *parent);
};

bool proc_app1(V3DPluginCallback2 &callback, PARA_APP1 &p, const QString & versionStr);

#endif


text:
module.exports = {
  parser: `@typescript-eslint/parser`,
  extends: [
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier/@typescript-eslint",
  ],
  plugins: ["@typescript-eslint", "prettier"],
  parserOptions: {
    ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
    sourceType: "module", // Allows for the use of imports
  },
  env: {
    browser: true,
    node: true,
  },
  rules: {
    quotes: "off",
    "@typescript-eslint/quotes": [
      2,
      "backtick",
      {
        avoidEscape: true,
      },
    ],
    indent: ["error", 2, { SwitchCase: 1 }],
    "prettier/prettier": [
      "error",
      {
        trailingComma: "es5",
        semi: false,
        singleQuote: false,
        printWidth: 120,
      },
    ],
  },
}


text:
btv-geographic
==============

Burlington Geographic maps section

![screen](screen.png)


text:
import json
import logging
import os
import sys
from functools import wraps

from docker.utils.ports import split_port
from jsonschema import Draft4Validator
from jsonschema import FormatChecker
from jsonschema import RefResolver
from jsonschema import ValidationError

from .errors import ConfigurationError

log = logging.getLogger(__name__)

DOCKER_CONFIG_HINTS = {
    'cpu_share': 'cpu_shares',
    'add_host': 'extra_hosts',
    'hosts': 'extra_hosts',
    'extra_host': 'extra_hosts',
    'device': 'devices',
    'link': 'links',
    'memory_swap': 'memswap_limit',
    'port': 'ports',
    'privilege': 'privileged',
    'priviliged': 'privileged',
    'privilige': 'privileged',
    'volume': 'volumes',
    'workdir': 'working_dir',
}

VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'

@FormatChecker.cls_checks(
    format="ports",
    raises=ValidationError(
        "Invalid port formatting, it should be "
        "'[[remote_ip:]remote_port:]port[/protocol]'"))
def format_ports(instance):
    try:
        split_port(instance)
    except ValueError:
        return False
    return True

@FormatChecker.cls_checks(format="environment")
def format_boolean_in_environment(instance):
    """
    Check if there is a boolean in the environment and display a warning.
    Always return True here so the validation won't raise an error.
    """
    if isinstance(instance, bool):
        log.warn(
            "Warning: There is a boolean value in the 'environment' key.\n"
            "Environment variables can only be strings.\nPlease add quotes to any boolean values to make them string "
            "(eg, 'True', 'yes', 'N').\nThis warning will become an error in a future release. \r\n"
        )
    return True

def validate_service_names(func):
    @wraps(func)
    def func_wrapper(config):
        for service_name in config.keys():
            if type(service_name) is int:
                raise ConfigurationError(
                    "Service name: {} needs to be a string, eg '{}'".format(service_name, service_name)
                )
        return func(config)
    return func_wrapper

def validate_top_level_object(func):
    @wraps(func)
    def func_wrapper(config):
        if not isinstance(config, dict):
            raise ConfigurationError(
                "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
            )
        return func(config)
    return func_wrapper

def validate_extends_file_path(service_name, extends_options, filename):
    """
    The service to be extended must either be defined in the config key 'file',
    or within 'filename'.
    """
    error_prefix = "Invalid 'extends' configuration for %s:" % service_name

    if 'file' not in extends_options and filename is None:
        raise ConfigurationError(
            "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
        )

def validate_extended_service_exists(extended_service_name, full_extended_config, extended_config_path):
    if extended_service_name not in full_extended_config:
        msg = (
            "Cannot extend service '%s' in %s: Service not found"
        ) % (extended_service_name, extended_config_path)
        raise ConfigurationError(msg)

def get_unsupported_config_msg(service_name, error_key):
    msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
    if error_key in DOCKER_CONFIG_HINTS:
        msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
    return msg

def anglicize_validator(validator):
    if validator in ["array", "object"]:
        return 'an ' + validator
    return 'a ' + validator

def process_errors(errors, service_name=None):
    """
    jsonschema gives us an error tree full of information to explain what has
    gone wrong. Process each error and pull out relevant information and re-write
    helpful error messages that are relevant.
    """
    def _parse_key_from_error_msg(error):
        return error.message.split("'")[1]

    def _clean_error_message(message):
        return message.replace("u'", "'")

    def _parse_valid_types_from_validator(validator):
        """
        A validator value can be either an array of valid types or a string of
        a valid type. Parse the valid types and prefix with the correct article.
        """
        if isinstance(validator, list):
            if len(validator) >= 2:
                first_type = anglicize_validator(validator[0])
                last_type = anglicize_validator(validator[-1])
                types_from_validator = "{}{}".format(first_type, ", ".join(validator[1:-1]))

                msg = "{} or {}".format(
                    types_from_validator,
                    last_type
                )
            else:
                msg = "{}".format(anglicize_validator(validator[0]))
        else:
            msg = "{}".format(anglicize_validator(validator))

        return msg

    def _parse_oneof_validator(error):
        """
        oneOf has multiple schemas, so we need to reason about which schema, sub
        schema or constraint the validation is failing on.
        Inspecting the context value of a ValidationError gives us information about
        which sub schema failed and which kind of error it is.
        """
        constraint = [context for context in error.context if len(context.path) > 0]
        if constraint:
            valid_types = _parse_valid_types_from_validator(constraint[0].validator_value)
            msg = "contains {}, which is an invalid type, it should be {}".format(
                constraint[0].instance,
                valid_types
            )
            return msg

        uniqueness = [context for context in error.context if context.validator == 'uniqueItems']
        if uniqueness:
            msg = "contains non unique items, please remove duplicates from {}".format(
                uniqueness[0].instance
            )
            return msg

        types = [context.validator_value for context in error.context if context.validator == 'type']
        valid_types = _parse_valid_types_from_validator(types)

        msg = "contains an invalid type, it should be {}".format(valid_types)

        return msg

    root_msgs = []
    invalid_keys = []
    required = []
    type_errors = []
    other_errors = []

    for error in errors:
        # handle root level errors
        if len(error.path) == 0 and not error.instance.get('name'):
            if error.validator == 'type':
                msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
                root_msgs.append(msg)
            elif error.validator == 'additionalProperties':
                invalid_service_name = _parse_key_from_error_msg(error)
                msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
                root_msgs.append(msg)
            else:
                root_msgs.append(_clean_error_message(error.message))

        else:
            if not service_name:
                # field_schema errors will have service name on the path
                service_name = error.path[0]
                error.path.popleft()
            else:
                # service_schema errors have the service name passed in, as that
                # is not available on error.path or necessarily error.instance
                service_name = service_name

            if error.validator == 'additionalProperties':
                invalid_config_key = _parse_key_from_error_msg(error)
                invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
            elif error.validator == 'anyOf':
                if 'image' in error.instance and 'build' in error.instance:
                    required.append(
                        "Service '{}' has both an image and build path specified. "
                        "A service can either be built to image or use an existing "
                        "image, not both.".format(service_name))
                elif 'image' not in error.instance and 'build' not in error.instance:
                    required.append(
                        "Service '{}' has neither an image nor a build path "
                        "specified. Exactly one must be provided.".format(service_name))
                elif 'image' in error.instance and 'dockerfile' in error.instance:
                    required.append(
                        "Service '{}' has both an image and alternate Dockerfile. "
                        "A service can either be built to image or use an existing "
                        "image, not both.".format(service_name))
                else:
                    required.append(_clean_error_message(error.message))
            elif error.validator == 'oneOf':
                config_key = error.path[0]
                msg = _parse_oneof_validator(error)

                type_errors.append("Service '{}' configuration key '{}' {}".format(
                    service_name, config_key, msg)
                )
            elif error.validator == 'type':
                msg = _parse_valid_types_from_validator(error.validator_value)

                if len(error.path) > 0:
                    config_key = " ".join(["'%s'" % k for k in error.path])
                    type_errors.append(
                        "Service '{}' configuration key {} contains an invalid "
                        "type, it should be {}".format(
                            service_name,
                            config_key,
                            msg))
                else:
                    root_msgs.append(
                        "Service '{}' doesn\'t have any configuration options. "
                        "All top level keys in your docker-compose.yml must map "
                        "to a dictionary of configuration options.'".format(service_name))
            elif error.validator == 'required':
                config_key = error.path[0]
                required.append(
                    "Service '{}' option '{}' is invalid, {}".format(
                        service_name,
                        config_key,
                        _clean_error_message(error.message)))
            elif error.validator == 'dependencies':
                dependency_key = list(error.validator_value.keys())[0]
                required_keys = ",".join(error.validator_value[dependency_key])
                required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
                    dependency_key, service_name, dependency_key, required_keys))
            else:
                config_key = " ".join(["'%s'" % k for k in error.path])
                err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
                other_errors.append(err_msg)

    return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)

def validate_against_fields_schema(config):
    schema_filename = "fields_schema.json"
    format_checkers = ["ports", "environment"]
    return _validate_against_schema(config, schema_filename, format_checkers)

def validate_against_service_schema(config, service_name):
    schema_filename = "service_schema.json"
    format_checkers = ["ports"]
    return _validate_against_schema(config, schema_filename, format_checkers, service_name)

def _validate_against_schema(config, schema_filename, format_checker=[], service_name=None):
    config_source_dir = os.path.dirname(os.path.abspath(__file__))

    if sys.platform == "win32":
        file_pre_fix = "///"
        config_source_dir = config_source_dir.replace('\\', '/')
    else:
        file_pre_fix = "//"

    resolver_full_path = "file:{}{}/".format(file_pre_fix, config_source_dir)
    schema_file = os.path.join(config_source_dir, schema_filename)

    with open(schema_file, "r") as schema_fh:
        schema = json.load(schema_fh)

    resolver = RefResolver(resolver_full_path, schema)
    validation_output = Draft4Validator(schema, resolver=resolver, format_checker=FormatChecker(format_checker))

    errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
    if errors:
        error_msg = process_errors(errors, service_name)
        raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))


text:
// Header for CCreateAccountDialog class

#ifndef __CCREATEACCOUNTDIALOG__MULBERRY__
#define __CCREATEACCOUNTDIALOG__MULBERRY__

#include "CDialogDirector.h"

#include "cdstring.h"

#include "HPopupMenu.h"

// Classes

class CTextInputField;
class JXTextButton;

class CCreateAccountDialog : public CDialogDirector
{
public:
	CCreateAccountDialog(JXDirector* supervisor);

	static bool PoseDialog(cdstring& name, short& type);

protected:
// begin JXLayout

    JXTextButton*    mOkBtn;
    JXTextButton*    mCancelBtn;
    CTextInputField* mText;
    HPopupMenu*      mType;

// end JXLayout

	virtual void	OnCreate();								// Do odds & ends

			void InitAccountTypePopup();
			void GetDetails(cdstring& name, short& type);

};

#endif


text:
#ifndef _MITKUNSTRUCTUREDGRIDCLUSTERINGFILTER_h__
#define _MITKUNSTRUCTUREDGRIDCLUSTERINGFILTER_h__

#include <MitkAlgorithmsExtExports.h>

#include <mitkCommon.h>

#include <mitkUnstructuredGrid.h>
#include <mitkUnstructuredGridToUnstructuredGridFilter.h>
#include <vtkIdList.h>
#include <vtkPoints.h>
#include <vtkSmartPointer.h>

namespace mitk
{
  /**
  * @brief This filter uses the DBSCAN algorithm for clustering an
  * mitk::UnstructuredGrid. "MinPts" defines the number of neighbours which are
  * required to be a kernel point if a point is in range of a kernel point
  * but hasnt enough neighbours this point is added to the cluster but is a
  * density reachable point and the cluster ends at this point. "eps" is the
  * range in which the neighbours are searched. If "Meshing" is set the
  * clusteres UnstructuredGrid is meshed and visible in 2D renderwindows.
  *
  * DBSCAN algorithm:
  *
  *     DBSCAN(D, eps, MinPts)
  *     C = 0
  *     for each unvisited point P in dataset D
  *       mark P as visited
  *       N = D.regionQuery(P, eps)
  *       if sizeof(N) < MinPts
  *         mark P as NOISE
  *       else
  *         C = next cluster
  *         expandCluster(P, N, C, eps, MinPts)
  *
  *     expandCluster(P, N, C, eps, MinPts)
  *       add P to cluster C
  *       for each point P' in N
  *         if P' is not visited
  *           mark P' as visited
  *           N' = D.regionQuery(P', eps)
  *           if sizeof(N') >= MinPts
  *             N = N joined with N'
  *         if P' is not yet member of any cluster
  *           add P' to cluster C
  */

  class MITKALGORITHMSEXT_EXPORT UnstructuredGridClusteringFilter : public UnstructuredGridToUnstructuredGridFilter
  {
  public:
    mitkClassMacro(UnstructuredGridClusteringFilter, UnstructuredGridToUnstructuredGridFilter)
      itkFactorylessNewMacro(Self) itkCloneMacro(Self)

      /** Sets the distance for the neighbour search */
      itkSetMacro(eps, double) itkGetMacro(eps, double)

      /** Sets the number of required neighbours */
      itkSetMacro(MinPts, int) itkGetMacro(MinPts, int)

      /** If activated the clusteres UnstructuredGrid is meshed */
      itkSetMacro(Meshing, bool)

      /** Returns all clusters as UnstructuredGrids which were found */
      virtual std::vector<mitk::UnstructuredGrid::Pointer> GetAllClusters();

    /** Returns the number of the clusters which were found */
    virtual int GetNumberOfFoundClusters();

  protected:
    /** Constructor */
    UnstructuredGridClusteringFilter();

    /** Destructor */
    virtual ~UnstructuredGridClusteringFilter();

    /** Defines the output of the filter */
    virtual void GenerateOutputInformation();

    /** Is called by the Update() method */
    virtual void GenerateData();

  private:
    /** Used for the DBSCAN algorithm to expand a cluster and add more points to it */
    void ExpandCluster(int id, vtkIdList *pointIDs, vtkPoints *cluster, vtkPoints *inpPoints);

    /** The result main Cluster */
    mitk::UnstructuredGrid::Pointer m_UnstructGrid;

    /** All clusters which were found */
    std::vector<vtkSmartPointer<vtkPoints>> m_Clusters;

    /** The distances of the points from the input UnstructuredGrid*/
    std::vector<vtkSmartPointer<vtkDoubleArray>> m_DistanceArrays;

    /** The range for the neighbout search */
    double m_eps;

    /** The number of the required neighbours */
    int m_MinPts;

    /** Activates the meshing for the UnstructuredGrid clusters*/
    bool m_Meshing;

    /** If its activated the distance of the clusters is used instead of the
    * size */
    bool m_DistCalc;
  };

} // namespace mitk

#endif //_MITKUNSTRUCTUREDGRIDCLUSTERINGFILTER_h__


text:
layout: post
published: true
title: >-
  Create AI Platform Notebooks Instance in Shared VPC without Service
  Availability
date: '2020-07-16'
categories:
  - Google Cloud Platform
tags:
  - AI Platform
  - Shared VPC
  - gcloud
bigimg: /img/post/photo-computer.jpg
thumbnail: /img/post/photo-computer.jpg
---

[AI Platform Notebooks](https://cloud.google.com/ai-platform-notebooks) is a managed service that provides an integration of JupyterLab, Git, and optimized data science libraries and frameworks. From it, you can get access to almost all ML frameworks, such as TensorFlow, Keras, PyTorch, etc. It is an excellent place for machine learning developers to experiment, develop, and deploy models into production. In addition, AI Platform Notebooks also supports enterprise security architectures through shared VPC and private IP controls.
<!--more-->
## What is Shared VPC?

[Shared Virtual Private Network (VPC)](https://cloud.google.com/vpc/docs/shared-vpc) allows organizations to connect resources from multiple projects to a common/shared VPC network. This allows cloud resources to communicate with each other securely and efficiently using internal IP addresses. Using Shared VPC is a good practice for Organization Admins to keep centralized control over network resources, while delegating administrative responsibilities to Service Project Admins.

## What is the Problem?

The problem is that not all regions support AI Platform Notebooks instance service and a Shared VPC usually does not contain all regions. For example, the following picture shows my shared VPC (**subnet-us-west-2**) from my host project (**my-host-project-268902**) only has region `us-west2`. For security reason, the shared VPC has turned the `Private Google Access` on, which means all VMs created in my service project can not have public IP.

![sharedvpc]({{site.baseurl}}/img/post/ai_notebooks_sharedvpc.png)

As shown by the following picture, however, if you create the AI Platform Notebooks instance through the web console, you would find that there is no `us-west2` in the **Region** dropdown list. Now, I need to create a notebook instance in region `us-west2` to use my shared VPC to connect to other network resources.  What should I do?

![notebook_instance_console]({{site.baseurl}}/img/post/ai_notebook_console.png)

If you are familiar with GCP, you might know that I can create an AI platform notebooks instance from the `gcloud beta notebooks instance create` command line as described in [Create an AI Platform Notebooks instance from the command line](https://cloud.google.com/ai-platform/notebooks/docs/create-new#create-command-line). However, when I specified the subnet to the shared VPC, I got the **PERMISSION_DENIED** error message shown as below:

![permissiondenied_error]({{site.baseurl}}/img/post/ai_notebook_error.png)

## How Did I Solve The Problem?

Instead of using the above `gcloud beta notebooks instance create` command, I created a Deep Learning VM instance from the command `gcloud compute instances create` as described in [Create a TensorFlow Deep Learning VM instance from the command line](https://cloud.google.com/ai-platform/deep-learning-vm/docs/tensorflow_start_instance#creating_ainstance_from_the_command_line).  However, the example command in the document can create a Deep Learning VM, but it did not show up in the AI Platform Notebooks Instance page.

The following are the two commands that I have adapted from the Deep Learning VM command mentioned above to create AI Platform Notebooks instances without GPUs and with GPUs.

### Command to create an instance without GPUs (cpu command)

```bash
export IMAGE_FAMILY="tf2-ent-latest-cpu"
export ZONE="us-west2-a"
export INSTANCE_NAME="cpu-instance-test"
export INSTANCE_TYPE="n1-standard-4"
export SUBNETWORK="https://www.googleapis.com/compute/v1/projects/my-host-project-268902/regions/us-west2/subnetworks/subnet-us-west-2"
export PROJECT_ID="my-service-project-271521"

gcloud compute instances create $INSTANCE_NAME \
  --zone=$ZONE \
  --project=$PROJECT_ID \
  --machine-type=$INSTANCE_TYPE \
  --image-family=$IMAGE_FAMILY \
  --image-project=deeplearning-platform-release \
  --subnet=$SUBNETWORK \
  --no-address \
  --tags=deeplearning-vm \
  --scopes=https://www.googleapis.com/auth/cloud-platform \
  --metadata='proxy-mode=project_editors'
```

Here is a breakdown of the command, so you understand what is happening:

- `gcloud compute instances create` creates a new instance with specified name
- `--zone` specifies which zone the instance to be created and needs to be consistent to the shared VPC region
- `--project` specifies the ID of project where the instance to be created
- `--machine-type` specifies the machine type as *n1-standard-4*, which provides 4 vCPU and 15GB of RAM. For more machine types, see [GCP VM Machine Types](https://cloud.google.com/compute/docs/machine-types)
- `--image-family` specifies the Deep Learning VM image. For more image families, see [AI Platform Deep Learning VM Images](https://cloud.google.com/ai-platform/deep-learning-vm/docs/images)
- `--image-project` must be **`deeplearning-platform-release`**
- `--subnet` specifies the shared subnet from the host project
- `--no-address` specifies that the VM has no public address. It can be ignored, if the shared VPC allows public IP
- `--tags` must be **`deeplearning-vm`**, otherwise, it will not show up in the notebook instance page
- `--scopes` and `--metadata` must be specified as above, otherwise, the instance cannot set up the proxy to the JupyterLab and the link of **OPEN JUPYTERLAB** won't work. For more information of the settings, see [Use SSH to Access to JupyterLab](https://cloud.google.com/ai-platform/notebooks/docs/ssh-access).

With success of above command, an instance named **cpu-instance-test** can be seen from the AI Platform Notebook Instances page:

![notebook_instance_cpu]({{site.baseurl}}/img/post/ai_notebooks_cpu.png)

### Command to create an instance with GPUs (gpu command)

```bash
export IMAGE_FAMILY="tf2-ent-latest-gpu"
export ZONE="us-west2-b"
export INSTANCE_NAME="gpu-instance-test"
export INSTANCE_TYPE="n1-standard-4"
export SUBNETWORK="https://www.googleapis.com/compute/v1/projects/my-host-project-268902/regions/us-west2/subnetworks/subnet-us-west-2"
export PROJECT_ID="my-service-project-271521"

gcloud compute instances create $INSTANCE_NAME \
  --zone=$ZONE \
  --project=$PROJECT_ID \
  --machine-type=$INSTANCE_TYPE \
  --image-family=$IMAGE_FAMILY \
  --image-project=deeplearning-platform-release \
  --subnet=$SUBNETWORK \
  --no-address \
  --tags=deeplearning-vm \
  --scopes=https://www.googleapis.com/auth/cloud-platform \
  --maintenance-policy=TERMINATE \
  --accelerator="type=nvidia-tesla-p4,count=1" \
  --metadata='install-nvidia-driver=True,proxy-mode=project_editors'
```

The gpu command is similar to the cpu command, the only differences are the last three options:

- `--maintenance-policy` must be **`TERMINATE`**, because of the [GPU restrictions](https://cloud.google.com/compute/docs/gpus#restrictions)
- `--accelerator` specifies the GPU type to use. For more details of GPU types, see [Create GPU instance gcloud](https://cloud.google.com/compute/docs/gpus/add-gpus#create-gpu-instance-gcloud)
- `--metadata` `install-nvidia-driver=True` specifies that the NVIDIA driver should be installed and `proxy-mode=project_editors` is used to setup proxy to JupyterLab.

With the success of above command, an instance with name of **gpu-instance-test** will show in the Notebook instances page:

![notebook_instance_gpu]({{site.baseurl}}/img/post/ai_notebooks_gpu.png)

I hope this post is helpful. If I missed anything, please let me know in the comments.

## References

[Create an AI Platform Notebooks instance from the command line](https://cloud.google.com/ai-platform/notebooks/docs/create-new#create-command-line)

[Create a TensorFlow Deep Learning VM instance from the command line](https://cloud.google.com/ai-platform/deep-learning-vm/docs/tensorflow_start_instance#creating_ainstance_from_the_command_line)

[Create GPU instance gcloud](https://cloud.google.com/compute/docs/gpus/add-gpus#create-gpu-instance-gcloud)


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class systemfile(base_resource) :
	""" Configuration for file resource. """
	def __init__(self) :
		self._filename = ""
		self._filecontent = ""
		self._filelocation = ""
		self._fileencoding = ""
		self._fileaccesstime = ""
		self._filemodifiedtime = ""
		self.___count = 0

	@property
	def filename(self) :
		"""Name of the file. It should not include filepath.
Maximum length =  63.
		"""
		try :
			return self._filename
		except Exception as e:
			raise e

	@filename.setter
	def filename(self, filename) :
		"""Name of the file. It should not include filepath.
Maximum length =  63
		"""
		try :
			self._filename = filename
		except Exception as e:
			raise e

	@property
	def filecontent(self) :
		"""file content in Base64 format.
		"""
		try :
			return self._filecontent
		except Exception as e:
			raise e

	@filecontent.setter
	def filecontent(self, filecontent) :
		"""file content in Base64 format.
		"""
		try :
			self._filecontent = filecontent
		except Exception as e:
			raise e

	@property
	def filelocation(self) :
		"""location of the file on NetScaler.
Maximum length =  127.
		"""
		try :
			return self._filelocation
		except Exception as e:
			raise e

	@filelocation.setter
	def filelocation(self, filelocation) :
		"""location of the file on NetScaler.
Maximum length =  127
		"""
		try :
			self._filelocation = filelocation
		except Exception as e:
			raise e

	@property
	def fileencoding(self) :
		"""encoding type of the file content.
Default value: "BASE64".
		"""
		try :
			return self._fileencoding
		except Exception as e:
			raise e

	@fileencoding.setter
	def fileencoding(self, fileencoding) :
		"""encoding type of the file content.
Default value: "BASE64"
		"""
		try :
			self._fileencoding = fileencoding
		except Exception as e:
			raise e

	@property
	def fileaccesstime(self) :
		"""Last access time of the file.
		"""
		try :
			return self._fileaccesstime
		except Exception as e:
			raise e

	@property
	def filemodifiedtime(self) :
		"""last modified time of the file.
		"""
		try :
			return self._filemodifiedtime
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(systemfile_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.systemfile
		except Exception as e :
			raise e

	def _get_object_name(self) :
		""" Returns the value of object identifier argument
		"""
		try :
			if (self.filename) :
				return str(self.filename)
			return None
		except Exception as e :
			raise e

	@classmethod
	def add(cls, client, resource) :
		""" Use this API to add systemfile.
		"""
		try :
			if type(resource) is not list :
				addresource = systemfile()
				addresource.filename = resource.filename
				addresource.filecontent = resource.filecontent
				addresource.filelocation = resource.filelocation
				addresource.fileencoding = resource.fileencoding
				return addresource.add_resource(client)
			else :
				if (resource and len(resource) > 0) :
					addresources = [ systemfile() for _ in range(len(resource))]
					for i in range(len(resource)) :
						addresources[i].filename = resource[i].filename
						addresources[i].filecontent = resource[i].filecontent
						addresources[i].filelocation = resource[i].filelocation
						addresources[i].fileencoding = resource[i].fileencoding
				result = cls.add_bulk_request(client, addresources)
			return result
		except Exception as e :
			raise e

	@classmethod
	def delete(cls, client, resource) :
		""" Use this API to delete systemfile.
		"""
		try :
			if type(resource) is not list :
				deleteresource = systemfile()
				if type(resource) !=  type(deleteresource):
					deleteresource.filename = resource
				else :
					deleteresource.filename = resource.filename
					deleteresource.filelocation = resource.filelocation
				return deleteresource.delete_resource(client)
			else :
				if type(resource[0]) != cls :
					if (resource and len(resource) > 0) :
						deleteresources = [ systemfile() for _ in range(len(resource))]
						for i in range(len(resource)) :
							deleteresources[i].filename = resource[i]
				else :
					if (resource and len(resource) > 0) :
						deleteresources = [ systemfile() for _ in range(len(resource))]
						for i in range(len(resource)) :
							deleteresources[i].filename = resource[i].filename
							deleteresources[i].filelocation = resource[i].filelocation
				result = cls.delete_bulk_request(client, deleteresources)
			return result
		except Exception as e :
			raise e

	@classmethod
	def get(cls, client, name="", option_="") :
		""" Use this API to fetch all the systemfile resources that are configured on netscaler.
		"""
		try :
			if not name :
				obj = systemfile()
				response = obj.get_resources(client, option_)
			else :
				if type(name) != cls :
					if type(name) is not list :
						obj = systemfile()
						obj.filename = name
						response = obj.get_resource(client, option_)
					else :
						if name and len(name) > 0 :
							response = [systemfile() for _ in range(len(name))]
							obj = [systemfile() for _ in range(len(name))]
							for i in range(len(name)) :
								obj[i] = systemfile()
								obj[i].filename = name[i]
								response[i] = obj[i].get_resource(client, option_)
			return response
		except Exception as e :
			raise e

	@classmethod
	def get_args(cls, client, args) :
		""" Use this API to fetch all the systemfile resources that are configured on netscaler.
	# This uses systemfile_args which is a way to provide additional arguments while fetching the resources.
		"""
		try :
			obj = systemfile()
			option_ = options()
			option_.args = nitro_util.object_to_string_withoutquotes(args)
			response = obj.get_resources(client, option_)
			return response
		except Exception as e :
			raise e

class systemfile_response(base_response) :
	def __init__(self, length=1) :
		self.systemfile = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.systemfile = [systemfile() for _ in range(length)]


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

<TITLE>
All Classes
</TITLE>

<META NAME="date" CONTENT="2012-03-09">

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

All Classes

Activity

Activity.ActivityCollection

Activity.ActivityObject

Activity.MediaLink

AggregateCounter

AggregateCounterSet

ApiResponse

ApiResponseCallback

Client

Client.Query

Client.QueuePosition

ClientAsyncTask

ClientCallback

ClientCredentialsInfo

Device

DeviceRegistrationCallback

DeviceUuidFactory

Entity

Group

GroupsRetrievedCallback

JsonUtils

MapUtils

Message

ObjectUtils

QueryResultsCallback

QueueInfo

UrlUtils

User