text:
function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)
%GRADIENTDESCENTMULTI Performs gradient descent to learn theta
%   theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by
%   taking num_iters gradient steps with learning rate alpha

% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);

for iter = 1:num_iters

    % ====================== YOUR CODE HERE ======================
    % Instructions: Perform a single gradient step on the parameter vector
    %               theta.
    %
    % Hint: While debugging, it can be useful to print out the values
    %       of the cost function (computeCostMulti) and gradient here.
    %

    % create a hypothesis matrix containing all values of X multiplied
    % by the current theta
    hypothesis = X * theta;

    % create a matrix containing the difference between the hypothesis and
    % y values
    differencesFromY = hypothesis - y;

    % create a new (1)x(n+1) matrix from the product of the transposed differencesFromY
    % matrix ((1)x(m)) and X ((m)x(n+1)) => (1)x(m) * (m)x(n+1) => (1)x(n+1)
    % matrix
    delta = (differencesFromY' * X);

    % calculate the next version of theta using the transposed delta
    % matrix (to make it an (n)x(1) matrix, matching the theta matrix size
    theta = theta - alpha / m * delta';
    % ============================================================

    % Save the cost J in every iteration
    J_history(iter) = computeCostMulti(X, y, theta);

end

end

redpajama_set_name: RedPajamaGithub


text:
module Lavigne
  module Models
    class TestCase
      include Avromatic::Model.build(schema_name: 'com.lavigne.test_case', mutable: true)
    end
  end
end


text:
class AddFileToList < ActiveRecord::Migration
  def change
    add_column :lists, :file, :string
  end
end


text:
// DlgRevDCMotorData.cpp : implementation file
//

#include "stdafx.h"
#include "DMViewer.h"
#include "DlgRevDCMotorData.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CDlgRevDCMotorData dialog

CDlgRevDCMotorData::CDlgRevDCMotorData(CWnd* pParent /*=NULL*/)
	: CDialog(CDlgRevDCMotorData::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDlgRevDCMotorData)
	//}}AFX_DATA_INIT
	m_pCdmvRevDCMotorData = NULL;
	m_strtRevDCMotorParameters.fArmatureResistance = 0.0f;
	m_strtRevDCMotorParameters.fBackEMFConstant = 0.0f;
	m_strtRevDCMotorParameters.fCoulombFrictionConstant = 0.0f;
	m_strtRevDCMotorParameters.fHalfDropValue = 0.0f;
	m_strtRevDCMotorParameters.fMaxBrushDrop = 0.0f;
	m_strtRevDCMotorParameters.fRotorInertia = 0.0f;
	m_strtRevDCMotorParameters.fTorqueConstant = 0.0f;
	m_strtRevDCMotorParameters.fViscousFrictionConstant = 0.0f;
	m_strtRevDCMotorParameters.fGearRatio = 0.0f;
}

void CDlgRevDCMotorData::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDlgRevDCMotorData)
	//}}AFX_DATA_MAP
	DDX_Text(pDX, IDC_EDIT_ARMATURE_RESISTANCE, m_strtRevDCMotorParameters.fArmatureResistance);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fArmatureResistance, REV_DC_MOTOR_ARMATURE_RESISTANCE_MIN, REV_DC_MOTOR_ARMATURE_RESISTANCE_MAX);
	DDX_Text(pDX, IDC_EDIT_BACK_EMF_CONSTANT, m_strtRevDCMotorParameters.fBackEMFConstant);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fBackEMFConstant, REV_DC_MOTOR_BACK_EMF_CONSTANT_MIN, REV_DC_MOTOR_BACK_EMF_CONSTANT_MAX);
	DDX_Text(pDX, IDC_EDIT_COULOMB_FRICTION_CONSTANT, m_strtRevDCMotorParameters.fCoulombFrictionConstant);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fCoulombFrictionConstant, REV_DC_MOTOR_COULOMB_FRICTION_MIN, REV_DC_MOTOR_COULOMB_FRICTION_MAX);
	DDX_Text(pDX, IDC_EDIT_HALF_DROP_VALUE, m_strtRevDCMotorParameters.fHalfDropValue);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fHalfDropValue, REV_DC_MOTOR_HALF_DROP_MIN, REV_DC_MOTOR_HALF_DROP_MAX);
	DDX_Text(pDX, IDC_EDIT_ROTOR_INERTIA, m_strtRevDCMotorParameters.fRotorInertia);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fRotorInertia, REV_DC_MOTOR_INERTIA_MIN, REV_DC_MOTOR_INERTIA_MAX);
	DDX_Text(pDX, IDC_EDIT_TORQUE_CONSTANT, m_strtRevDCMotorParameters.fTorqueConstant);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fTorqueConstant, REV_DC_MOTOR_TORQUE_CONSTANT_MIN, REV_DC_MOTOR_TORQUE_CONSTANT_MAX);
	DDX_Text(pDX, IDC_EDIT_VISCOUS_FRICTION_CONSTANT, m_strtRevDCMotorParameters.fViscousFrictionConstant);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fViscousFrictionConstant, REV_DC_MOTOR_VISCOUS_FRICTION_MIN, REV_DC_MOTOR_VISCOUS_FRICTION_MAX);
	DDX_Text(pDX, IDC_EDIT_MAXIMUM_DROP_VALUE, m_strtRevDCMotorParameters.fMaxBrushDrop);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fMaxBrushDrop, REV_DC_MOTOR_MAX_BRUSH_DROP_MIN, REV_DC_MOTOR_MAX_BRUSH_DROP_MAX);
	DDX_Text(pDX, IDC_EDIT_GEAR_RATIO, m_strtRevDCMotorParameters.fGearRatio);
	DDV_MinMaxDouble(pDX, m_strtRevDCMotorParameters.fGearRatio, REV_DC_MOTOR_GEAR_RATIO_MIN, REV_DC_MOTOR_GEAR_RATIO_MAX);
}

BEGIN_MESSAGE_MAP(CDlgRevDCMotorData, CDialog)
	//{{AFX_MSG_MAP(CDlgRevDCMotorData)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDlgRevDCMotorData message handlers

BOOL CDlgRevDCMotorData::OnInitDialog()
{
	CDialog::OnInitDialog();

	ASSERT (m_pCdmvRevDCMotorData);

	m_pCdmvRevDCMotorData->GetParameters (&m_strtRevDCMotorParameters);

	// Set DDX the dialog data.
	BOOL bReturnStatus = UpdateData (FALSE);
	ASSERT (bReturnStatus);

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CDlgRevDCMotorData::SaveDialogData()
{
	// The UpdateData function should have already been called by the client

	ASSERT (m_pCdmvRevDCMotorData);
	m_pCdmvRevDCMotorData->SetParameters (&m_strtRevDCMotorParameters);
}

void CDlgRevDCMotorData::OnCancel()
{
	delete m_pCdmvRevDCMotorData;
}


text:
layout: base
title:  'POS tags'
generated: 'true'
permalink: ca/pos/index.html
---

# POS tags

{% include ca-pos-table.html %}

----------

Alphabetical listing

{% assign sorted = site.ca-pos | sort: 'title' %}{% for p in sorted %}
* [{{ p.title }}](): {{ p.shortdef }}{% endfor %}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syn. Fung. (Oslo) 23: 88 (2007)

#### Original name
Radulodon revolubilis Hjortstam & Ryvarden

### Remarks
null


text:
/**
 * @file PWM servo output interface.
 *
 * Servo values can be set with the PWM_SERVO_SET ioctl, by writing a
 * pwm_output_values structure to the device
 * Writing a value of 0 to a channel suppresses any output for that
 * channel.
 */

#pragma once

#include <px4_platform_common/defines.h>

#include <stdint.h>
#include <sys/ioctl.h>
#include <board_config.h>

#include "drv_orb_dev.h"

__BEGIN_DECLS

/**
 * Path for the default PWM output device.
 *
 * Note that on systems with more than one PWM output path (e.g.
 * PX4FMU with PX4IO connected) there may be other devices that
 * respond to this protocol.
 */
#define PWM_OUTPUT_BASE_DEVICE_PATH "/dev/pwm_output"
#define PWM_OUTPUT0_DEVICE_PATH	"/dev/pwm_output0"
#define PWM_OUTPUT1_DEVICE_PATH	"/dev/pwm_output1"

#define PWM_OUTPUT_MAX_CHANNELS 16

struct pwm_output_values {
	uint32_t channel_count;
	uint16_t values[PWM_OUTPUT_MAX_CHANNELS];
};

/* Use defaults unless the board override the defaults by providing
 * PX4_PWM_ALTERNATE_RANGES and a replacement set of
 * constants
 */
#if !defined(PX4_PWM_ALTERNATE_RANGES)

/**
 * Lowest minimum PWM in us
 */
#define PWM_LOWEST_MIN 90

/**
 * Default value for a shutdown motor
 */
#define PWM_MOTOR_OFF	900

/**
 * Default minimum PWM in us
 */
#define PWM_DEFAULT_MIN 1000

/**
 * Highest PWM allowed as the minimum PWM
 */
#define PWM_HIGHEST_MIN 1600

/**
 * Highest maximum PWM in us
 */
#define PWM_HIGHEST_MAX 2500

/**
 * Default maximum PWM in us
 */
#define PWM_DEFAULT_MAX 2000

/**
 * Default trim PWM in us
 */
#define PWM_DEFAULT_TRIM 0

/**
 * Lowest PWM allowed as the maximum PWM
 */
#define PWM_LOWEST_MAX 200

#endif // not PX4_PWM_ALTERNATE_RANGES

/**
 * Do not output a channel with this value
 */
#define PWM_IGNORE_THIS_CHANNEL UINT16_MAX

/**
 * Servo output signal type, value is actual servo output pulse
 * width in microseconds.
 */
typedef uint16_t	servo_position_t;

/*
 * ioctl() definitions
 *
 * Note that ioctls and ORB updates should not be mixed, as the
 * behaviour of the system in this case is not defined.
 */
#define _PWM_SERVO_BASE		0x2a00

/** arm all servo outputs handle by this driver */
#define PWM_SERVO_ARM		_PX4_IOC(_PWM_SERVO_BASE, 0)

/** disarm all servo outputs (stop generating pulses) */
#define PWM_SERVO_DISARM	_PX4_IOC(_PWM_SERVO_BASE, 1)

/** get default servo update rate */
#define PWM_SERVO_GET_DEFAULT_UPDATE_RATE _PX4_IOC(_PWM_SERVO_BASE, 2)

/** set alternate servo update rate */
#define PWM_SERVO_SET_UPDATE_RATE _PX4_IOC(_PWM_SERVO_BASE, 3)

/** get alternate servo update rate */
#define PWM_SERVO_GET_UPDATE_RATE _PX4_IOC(_PWM_SERVO_BASE, 4)

/** get the number of servos in *(unsigned *)arg */
#define PWM_SERVO_GET_COUNT	_PX4_IOC(_PWM_SERVO_BASE, 5)

/** selects servo update rates, one bit per servo. 0 = default (50Hz), 1 = alternate */
#define PWM_SERVO_SET_SELECT_UPDATE_RATE _PX4_IOC(_PWM_SERVO_BASE, 6)

/** check the selected update rates */
#define PWM_SERVO_GET_SELECT_UPDATE_RATE _PX4_IOC(_PWM_SERVO_BASE, 7)

/** set the 'ARM ok' bit, which activates the safety switch */
#define PWM_SERVO_SET_ARM_OK	_PX4_IOC(_PWM_SERVO_BASE, 8)

/** clear the 'ARM ok' bit, which deactivates the safety switch */
#define PWM_SERVO_CLEAR_ARM_OK	_PX4_IOC(_PWM_SERVO_BASE, 9)

/** start DSM bind */
#define DSM_BIND_START	_PX4_IOC(_PWM_SERVO_BASE, 10)

/** set the PWM value for failsafe */
#define PWM_SERVO_SET_FAILSAFE_PWM	_PX4_IOC(_PWM_SERVO_BASE, 12)

/** get the PWM value for failsafe */
#define PWM_SERVO_GET_FAILSAFE_PWM	_PX4_IOC(_PWM_SERVO_BASE, 13)

/** set the PWM value when disarmed - should be no PWM (zero) by default */
#define PWM_SERVO_SET_DISARMED_PWM	_PX4_IOC(_PWM_SERVO_BASE, 14)

/** get the PWM value when disarmed */
#define PWM_SERVO_GET_DISARMED_PWM	_PX4_IOC(_PWM_SERVO_BASE, 15)

/** set the minimum PWM value the output will send */
#define PWM_SERVO_SET_MIN_PWM	_PX4_IOC(_PWM_SERVO_BASE, 16)

/** get the minimum PWM value the output will send */
#define PWM_SERVO_GET_MIN_PWM	_PX4_IOC(_PWM_SERVO_BASE, 17)

/** set the maximum PWM value the output will send */
#define PWM_SERVO_SET_MAX_PWM	_PX4_IOC(_PWM_SERVO_BASE, 18)

/** get the maximum PWM value the output will send */
#define PWM_SERVO_GET_MAX_PWM	_PX4_IOC(_PWM_SERVO_BASE, 19)

/** get the TRIM value the output will send */
#define PWM_SERVO_GET_TRIM_PWM	_PX4_IOC(_PWM_SERVO_BASE, 21)

/** set the lockdown override flag to enable outputs in HIL */
#define PWM_SERVO_SET_DISABLE_LOCKDOWN		_PX4_IOC(_PWM_SERVO_BASE, 23)

/** get the lockdown override flag to enable outputs in HIL */
#define PWM_SERVO_GET_DISABLE_LOCKDOWN		_PX4_IOC(_PWM_SERVO_BASE, 24)

/** force safety switch off (to disable use of safety switch) */
#define PWM_SERVO_SET_FORCE_SAFETY_OFF		_PX4_IOC(_PWM_SERVO_BASE, 25)

/** force failsafe mode (failsafe values are set immediately even if failsafe condition not met) */
#define PWM_SERVO_SET_FORCE_FAILSAFE		_PX4_IOC(_PWM_SERVO_BASE, 26)

/** make failsafe non-recoverable (termination) if it occurs */
#define PWM_SERVO_SET_TERMINATION_FAILSAFE	_PX4_IOC(_PWM_SERVO_BASE, 27)

/** force safety switch on (to enable use of safety switch) */
#define PWM_SERVO_SET_FORCE_SAFETY_ON		_PX4_IOC(_PWM_SERVO_BASE, 28)

/** setup OVERRIDE_IMMEDIATE behaviour on FMU fail */
#define PWM_SERVO_SET_OVERRIDE_IMMEDIATE	_PX4_IOC(_PWM_SERVO_BASE, 32)

/** set auxillary output mode. These correspond to enum Mode in px4fmu/fmu.cpp */
#define PWM_SERVO_MODE_NONE         0
#define PWM_SERVO_MODE_1PWM         1
#define PWM_SERVO_MODE_2PWM         2
#define PWM_SERVO_MODE_2PWM2CAP     3
#define PWM_SERVO_MODE_3PWM         4
#define PWM_SERVO_MODE_3PWM1CAP     5
#define PWM_SERVO_MODE_4PWM         6
#define PWM_SERVO_MODE_4PWM1CAP     7
#define PWM_SERVO_MODE_4PWM2CAP     8
#define PWM_SERVO_MODE_5PWM         9
#define PWM_SERVO_MODE_5PWM1CAP    10
#define PWM_SERVO_MODE_6PWM        11
#define PWM_SERVO_MODE_8PWM        12
#define PWM_SERVO_MODE_12PWM       13
#define PWM_SERVO_MODE_14PWM       14
#define PWM_SERVO_MODE_4CAP        15
#define PWM_SERVO_MODE_5CAP        16
#define PWM_SERVO_MODE_6CAP        17
#define PWM_SERVO_ENTER_TEST_MODE  18
#define PWM_SERVO_EXIT_TEST_MODE   19
#define PWM_SERVO_SET_MODE         _PX4_IOC(_PWM_SERVO_BASE, 34)

/*
 *
 *
 * WARNING WARNING WARNING! DO NOT EXCEED 47 IN IOC INDICES HERE!
 *
 *
 */

/** set a single servo to a specific value */
#define PWM_SERVO_SET(_servo)	_PX4_IOC(_PWM_SERVO_BASE, 0x30 + _servo)

/** get a single specific servo value */
#define PWM_SERVO_GET(_servo)	_PX4_IOC(_PWM_SERVO_BASE, 0x50 + _servo)

/** get the _n'th rate group's channels; *(uint32_t *)arg returns a bitmap of channels
 *  whose update rates must be the same.
 */
#define PWM_SERVO_GET_RATEGROUP(_n) _PX4_IOC(_PWM_SERVO_BASE, 0x70 + _n)

/** specific rates for configuring the timer for OneShot or PWM */
#define	PWM_RATE_ONESHOT			0u
#define	PWM_RATE_LOWER_LIMIT		1u
#define	PWM_RATE_UPPER_LIMIT		10000u

typedef enum {
	DShot_cmd_motor_stop = 0,
	DShot_cmd_beacon1,
	DShot_cmd_beacon2,
	DShot_cmd_beacon3,
	DShot_cmd_beacon4,
	DShot_cmd_beacon5,
	DShot_cmd_esc_info, // V2 includes settings
	DShot_cmd_spin_direction_1,
	DShot_cmd_spin_direction_2,
	DShot_cmd_3d_mode_off,
	DShot_cmd_3d_mode_on,
	DShot_cmd_settings_request, // Currently not implemented
	DShot_cmd_save_settings,
	DShot_cmd_spin_direction_normal   = 20,
	DShot_cmd_spin_direction_reversed = 21,
	DShot_cmd_led0_on,      // BLHeli32 only
	DShot_cmd_led1_on,      // BLHeli32 only
	DShot_cmd_led2_on,      // BLHeli32 only
	DShot_cmd_led3_on,      // BLHeli32 only
	DShot_cmd_led0_off,     // BLHeli32 only
	DShot_cmd_led1_off,     // BLHeli32 only
	DShot_cmd_led2_off,     // BLHeli32 only
	DShot_cmd_led4_off,     // BLHeli32 only
	DShot_cmd_audio_stream_mode_on_off              = 30, // KISS audio Stream mode on/off
	DShot_cmd_silent_mode_on_off                    = 31, // KISS silent Mode on/off
	DShot_cmd_signal_line_telemeetry_disable        = 32,
	DShot_cmd_signal_line_continuous_erpm_telemetry = 33,
	DShot_cmd_MAX          = 47,     // >47 are throttle values
	DShot_cmd_MIN_throttle = 48,
	DShot_cmd_MAX_throttle = 2047
} dshot_command_t;

/*
 * Low-level PWM output interface.
 *
 * This is the low-level API to the platform-specific PWM driver.
 */

/**
 * Intialise the PWM servo outputs using the specified configuration.
 *
 * @param channel_mask	Bitmask of channels (LSB = channel 0) to enable.
 *			This allows some of the channels to remain configured
 *			as GPIOs or as another function.
 * @return		OK on success.
 */
__EXPORT extern int	up_pwm_servo_init(uint32_t channel_mask);

/**
 * De-initialise the PWM servo outputs.
 *
 * @param channel_mask  Bitmask of channels (LSB = channel 0) to enable.
 *      This allows some of the channels to remain configured
 *      as GPIOs or as another function.
 *      A value of 0 is ALL channels
 *
 */
__EXPORT extern void	up_pwm_servo_deinit(uint32_t channel_mask);

/**
 * Arm or disarm servo outputs.
 *
 * When disarmed, servos output no pulse.
 *
 * @bug This function should, but does not, guarantee that any pulse
 *      currently in progress is cleanly completed.
 *
 * @param armed		If true, outputs are armed; if false they
 *			are disarmed.
 *
 * @param channel_mask  Bitmask of channels (LSB = channel 0) to enable.
 *      This allows some of the channels to remain configured
 *      as GPIOs or as another function.
 *      A value of 0 is ALL channels
 *
 */
__EXPORT extern void	up_pwm_servo_arm(bool armed, uint32_t channel_mask);

/**
 * Set the servo update rate for all rate groups.
 *
 * @param rate		The update rate in Hz to set.
 * @return		OK on success, -ERANGE if an unsupported update rate is set.
 */
__EXPORT extern int	up_pwm_servo_set_rate(unsigned rate);

/**
 * Get a bitmap of output channels assigned to a given rate group.
 *
 * @param group		The rate group to query. Rate groups are assigned contiguously
 *			starting from zero.
 * @return		A bitmap of channels assigned to the rate group, or zero if
 *			the group number has no channels.
 */
__EXPORT extern uint32_t up_pwm_servo_get_rate_group(unsigned group);

/**
 * Set the update rate for a given rate group.
 *
 * @param group		The rate group whose update rate will be changed.
 * @param rate		The update rate in Hz.
 * @return		OK if the group was adjusted, -ERANGE if an unsupported update rate is set.
 */
__EXPORT extern int	up_pwm_servo_set_rate_group_update(unsigned group, unsigned rate);

/**
 * Trigger all timer's channels in Oneshot mode to fire
 * the oneshot with updated values.
 * Nothing is done if not in oneshot mode.
 *
 */
__EXPORT extern void up_pwm_update(void);

/**
 * Set the current output value for a channel.
 *
 * @param channel	The channel to set.
 * @param value		The output pulse width in microseconds.
 */
__EXPORT extern int	up_pwm_servo_set(unsigned channel, servo_position_t value);

/**
 * Get the current output value for a channel.
 *
 * @param channel	The channel to read.
 * @return		The output pulse width in microseconds, or zero if
 *			outputs are not armed or not configured.
 */
__EXPORT extern servo_position_t up_pwm_servo_get(unsigned channel);

/**
 * Intialise the Dshot outputs using the specified configuration.
 *
 * @param channel_mask		Bitmask of channels (LSB = channel 0) to enable.
 *				This allows some of the channels to remain configured
 *				as GPIOs or as another function.
 * @param dshot_pwm_freq	Frequency of DSHOT signal. Usually DSHOT150, DSHOT300, DSHOT600 or DSHOT1200
 * @return OK on success.
 */
__EXPORT extern int up_dshot_init(uint32_t channel_mask, unsigned dshot_pwm_freq);

/**
 * Set the current dshot throttle value for a channel (motor).
 *
 * @param channel	The channel to set.
 * @param throttle	The output dshot throttle value in [0 = DSHOT_DISARM_VALUE, 1 = DSHOT_MIN_THROTTLE, 1999 = DSHOT_MAX_THROTTLE].
 * @param telemetry	If true, request telemetry from that motor
 */
__EXPORT extern void up_dshot_motor_data_set(unsigned channel, uint16_t throttle, bool telemetry);

/**
 * Send DShot command to a channel (motor).
 *
 * @param channel	The channel to set.
 * @param command	dshot_command_t
 * @param telemetry	If true, request telemetry from that motor
 */
__EXPORT extern void up_dshot_motor_command(unsigned channel, uint16_t command, bool telemetry);

/**
 * Trigger dshot data transfer.
 */
__EXPORT extern void up_dshot_trigger(void);

/**
 * Arm or disarm dshot outputs (This will enable/disable complete timer for safety purpose.).
 *
 * When disarmed, dshot output no pulse.
 *
 * @param armed		If true, outputs are armed; if false they
 *			are disarmed.
 */
__EXPORT extern int up_dshot_arm(bool armed);

__END_DECLS


text:
namespace Google.Cloud.AIPlatform.V1.Snippets
{
    // [START aiplatform_v1_generated_FeaturestoreService_UpdateEntityType_sync]
    using Google.Cloud.AIPlatform.V1;
    using Google.Protobuf.WellKnownTypes;

    public sealed partial class GeneratedFeaturestoreServiceClientSnippets
    {
        /// <summary>Snippet for UpdateEntityType</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void UpdateEntityTypeRequestObject()
        {
            // Create client
            FeaturestoreServiceClient featurestoreServiceClient = FeaturestoreServiceClient.Create();
            // Initialize request argument(s)
            UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
            {
                EntityType = new EntityType(),
                UpdateMask = new FieldMask(),
            };
            // Make the request
            EntityType response = featurestoreServiceClient.UpdateEntityType(request);
        }
    }
    // [END aiplatform_v1_generated_FeaturestoreService_UpdateEntityType_sync]
}


text:
var utils = require('../utils.js');

exports.check = function(hash, res) {
    hs = '7ec92c7c98de3fac'
    if (hash.length == hs.length && !utils.isANumber(hash) && !utils.isAlpha(hash) && utils.isAlphaNumeric(hash)) {
      res.push("MD5Middle");
    }
    return res;
}


text:
class AddUserSignatureCache < ActiveRecord::Migration
  def self.up
     add_column :users, :signature, :string
  end

  def self.down
    remove_column :users, :signature
  end
end


text:
comment_confirm_url
===================


text:
package com.srotya.sidewinder.core.storage.mem;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.regex.Pattern;

import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.srotya.sidewinder.core.filters.ComplexTagFilter;
import com.srotya.sidewinder.core.filters.ComplexTagFilter.ComplexFilterType;
import com.srotya.sidewinder.core.filters.SimpleTagFilter;
import com.srotya.sidewinder.core.filters.TagFilter;
import com.srotya.sidewinder.core.monitoring.MetricsRegistryService;
import com.srotya.sidewinder.core.storage.ByteString;
import com.srotya.sidewinder.core.storage.Measurement;
import com.srotya.sidewinder.core.storage.Series;
import com.srotya.sidewinder.core.storage.TagIndex;

/**
 * Tag hash lookup table + Tag inverted index
 *
 * @author ambud
 */
public class MemTagIndex implements TagIndex {

	private Map<String, SortedMap<String, Set<Integer>>> rowKeyIndex;
	private Counter metricIndexRow;
	private Measurement m;
	@SuppressWarnings("unused")
	private boolean enableMetrics;

	@Override
	public void configure(Map<String, String> conf, String indexDir, Measurement measurement) throws IOException {
		m = measurement;
		rowKeyIndex = new ConcurrentHashMap<>();
		MetricsRegistryService instance = MetricsRegistryService.getInstance();
		if (instance != null) {
			MetricRegistry registry = instance.getInstance("requests");
			metricIndexRow = registry.counter("index-row");
			enableMetrics = true;
		}
	}

	public Set<String> getTagKeys() {
		return new HashSet<>(rowKeyIndex.keySet());
	}

	@Override
	public void close() throws IOException {
	}

	@Override
	public int getSize() {
		return 0;
	}

	@Override
	public void index(String tag, String value, int rowIndex) throws IOException {
		SortedMap<String, Set<Integer>> map = rowKeyIndex.get(tag);

		if (map == null) {
			map = new ConcurrentSkipListMap<>();
			rowKeyIndex.put(tag, map);
		}

		Set<Integer> rowKeySet = map.get(value);
		if (rowKeySet == null) {
			synchronized (rowKeyIndex) {
				if ((rowKeySet = map.get(value)) == null) {
					rowKeySet = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
					map.put(value, rowKeySet);
				}
			}
		}
		if (!rowKeySet.contains(rowIndex)) {
			rowKeySet.add(rowIndex);
			if (metricIndexRow != null) {
				metricIndexRow.inc();
			}
		}
	}

	@Override
	public Set<ByteString> searchRowKeysForTagFilter(TagFilter tagFilterTree) {
		Set<Integer> e = evalFilterForTags(tagFilterTree);
		Set<ByteString> rowKeys = new HashSet<>();
		List<Series> list = m.getSeriesList();
		if (e != null) {
			for (Integer val : e) {
				rowKeys.add(new ByteString(list.get(val).getSeriesId().toString()));
			}
		}
		return rowKeys;
	}

	public Set<Integer> evalFilterForTags(TagFilter filterTree) {
		// either it's a simple tag filter or a complex tag filter
		if (filterTree instanceof SimpleTagFilter) {
			SimpleTagFilter simpleFilter = (SimpleTagFilter) filterTree;
			SortedMap<String, Set<Integer>> sortedMap = rowKeyIndex.get(simpleFilter.getTagKey());
			if (sortedMap == null) {
				return null;
			}
			return evalSimpleTagFilter(simpleFilter, sortedMap);
		} else {
			// if it's a complex tag filter then get individual units of return
			ComplexTagFilter complexFilter = (ComplexTagFilter) filterTree;
			List<TagFilter> filters = complexFilter.getFilters();
			Set<Integer> set = new HashSet<>();
			ComplexFilterType type = complexFilter.getType();
			for (TagFilter tagFilter : filters) {
				Set<Integer> r = evalFilterForTags(tagFilter);
				if (r == null) {
					// no match found from evaluation of this filter
					if (type == ComplexFilterType.AND) {
						// if filter condition is AND then short circuit terminate the evaluation
						return set = new HashSet<>();
					} else {
						// if filter condition is OR then continue evaluation
						continue;
					}
				} else if (set.isEmpty()) {
					set.addAll(r);
				}
				switch (type) {
				case AND:
					set.retainAll(r);
					break;
				case OR:
					set.addAll(r);
					break;
				}
			}
			return set;
		}
	}

	private Set<Integer> evalSimpleTagFilter(SimpleTagFilter simpleFilter, SortedMap<String, Set<Integer>> map) {
		switch (simpleFilter.getFilterType()) {
		case EQUALS:
			return map.get(simpleFilter.getComparedValue());
		case GREATER_THAN:
			SortedMap<String, Set<Integer>> tailMap = map.tailMap(simpleFilter.getComparedValue());
			if (tailMap == null || tailMap.isEmpty()) {
				return null;
			}
			Iterator<Set<Integer>> iterator = tailMap.values().iterator();
			// skip the first one since the condition is greater than
			iterator.next();
			return combineMaps(iterator);
		case LESS_THAN:
			SortedMap<String, Set<Integer>> headMap = map.headMap(simpleFilter.getComparedValue());
			if (headMap == null || headMap.isEmpty()) {
				return null;
			}
			return combineMaps(headMap.values().iterator());
		case GREATER_THAN_EQUALS:
			SortedMap<String, Set<Integer>> tailMap1 = map.tailMap(simpleFilter.getComparedValue());
			if (tailMap1 == null || tailMap1.isEmpty()) {
				return null;
			}
			Iterator<Set<Integer>> iterator1 = tailMap1.values().iterator();
			return combineMaps(iterator1);
		case LESS_THAN_EQUALS:
			SortedMap<String, Set<Integer>> headMap1 = map
					.headMap(simpleFilter.getComparedValue() + Character.MAX_VALUE);
			if (headMap1 == null || headMap1.isEmpty()) {
				return null;
			}
			return combineMaps(headMap1.values().iterator());
		case LIKE:
			List<Set<Integer>> filteredOutput = new ArrayList<>();
			Pattern p = Pattern.compile(simpleFilter.getComparedValue());
			for (Entry<String, Set<Integer>> v : map.entrySet()) {
				if (p.matcher(v.getKey()).matches()) {
					filteredOutput.add(v.getValue());
				}
			}
			return combineMaps(filteredOutput.iterator());
		}
		return null;
	}

	private Set<Integer> combineMaps(Iterator<Set<Integer>> itr) {
		Set<Integer> uberSet = new HashSet<>();
		while (itr.hasNext()) {
			uberSet.addAll(itr.next());
		}
		return uberSet;
	}

	@Override
	public Collection<String> getTagValues(String tagKey) {
		SortedMap<String, Set<Integer>> map = rowKeyIndex.get(tagKey);
		if (map != null) {
			return map.keySet();
		} else {
			return null;
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CSharpCommonDll;
using Newtonsoft.Json;
using SelectPaste.Service;
using Timer = System.Windows.Forms.Timer;

namespace SelectPaste
{
    public partial class SelectPaste_From : Form
    {
        private string filePath = "FilePath";
        static Jyh jyh = Jyh.GetInstance();
        private const int hotKeyId = 100;
        private static string passwdPath;
        public static DateTime anchorDateTime;
        public static DateTime ctDateTime;
        public SelectPaste_From()
        {
            InitializeComponent();
            anchorDateTime = new DateTime(1991, 6, 18);
            ctDateTime = new DateTime(1991, 6, 18);
        }

        private void SelectFile_Click(object sender, EventArgs e)
        {
            passwdPath = jyh.OpenFile("*.txt");
            FileInfo fi = new FileInfo(passwdPath);
            if (fi.Extension != ".txt")
            {
                MessageBox.Show("请选择txt文件");
                return;
            }
            var signal=jyh.WriteRegister(filePath, filePath, filePath, passwdPath);
            if (!signal)
            {
                MessageBox.Show("写入注册表失败");
                return;
            }
            txtboxFilePath.Text = passwdPath;
            ReloadList(ReadValue(passwdPath));

        }
        BackgroundWorker backgroundWorker1 = new BackgroundWorker();
        //运行线程
        public void DoWork(object sender, DoWorkEventArgs eventArgs)
        {
            while (true)
            {
                backgroundWorker1.ReportProgress(0, sender);
                Thread.Sleep(240*1000);
            }
        }
        //统一处理业务
        private void ProgressChanged(object o, ProgressChangedEventArgs eventArgs)
        {
            try
            {
                //调试,查看时间
                watchDate.Text = anchorDateTime.ToString("an: yyyy-MM-dd HH:mm:sss") + " - "+
                            ctDateTime.ToString("yyyy-MM-dd HH:mm:sss");
                //检测到网络畅通
                if (new Ping().Send("119.29.29.29", 1000).Status != IPStatus.Success)
                {
                    return;
                }

                var setTime = new SetTime();
                var unixBeijingTime = setTime.GetUnixBeijingTime();
                //增加对比时间点更新
                setTime.SetTimeFunc(unixBeijingTime);

                if (setTime.ifTimeDiff())
                {
                    var BlazingsBingWallpaperFullPath = Path.Combine(Environment.CurrentDirectory, "BlazingsBingWallpaper.exe");
                    if (File.Exists(BlazingsBingWallpaperFullPath))
                    {
                        System.Diagnostics.Process.Start(BlazingsBingWallpaperFullPath);
                    }
                }

            }
            catch (Exception e)
            {
            }

        }

        //窗口加载
        private void SelectPaste_From_Load(object sender, EventArgs e)
        {

            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.DoWork += DoWork;
            backgroundWorker1.ProgressChanged += ProgressChanged;

            backgroundWorker1.RunWorkerAsync();

            //热键
            if (!Jyh.RegisterHotKey(Handle, hotKeyId,  Jyh.KeyModifiers.Shift, Keys.V))
            {
                MessageBox.Show("热键注册失败");
            }

            var regInfo=jyh.GetRegister(filePath, filePath);
            if (regInfo.Count>0 && File.Exists(regInfo.First(r => r.Key==filePath).Value))
            {
                txtboxFilePath.Text = regInfo.First(r => r.Key == filePath).Value;
                passwdPath = txtboxFilePath.Text;
                ReloadList(ReadValue(txtboxFilePath.Text));
            }
            else
            {
                SelectFile_Click(sender, e);
            }
            HideForm();
        }
        //添加一个
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtboxValue.Text))
            {
                return;
            }
            try
            {
                WriteValue(txtboxValue.Text);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
                throw;
            }
            ReloadList(ReadValue(txtboxFilePath.Text));
            txtboxValue.Text = "";
        }
        public List<string> ReadValue(string filePath)
        {
            var StrList=File.ReadAllText(filePath);
            var deStrList = JsonConvert.DeserializeObject<List<string>>(StrList);
            if (deStrList == null)
            {
                deStrList = new List<string>();
            }
            return deStrList;
        }
        //重载列表
        public void ReloadList(List<string> values)
        {
            listBox1.Items.Clear();
            if (values!=null)
            {
                foreach (var value in values)
                {
                    listBox1.Items.Add(value);
                }
            }
        }
        //写入文件
        public void WriteValue(string valueText)
        {
            var passwdList = ReadValue(passwdPath);
            if (passwdList.Contains(valueText))
            {
                return;
            }
            passwdList.Add(valueText);
            var toJson = JsonConvert.SerializeObject(passwdList);
            jyh.WriteTxt(passwdPath,toJson);
        }
        //删除
        public void DeleteValue(string filePath,string valueText, string passwordIV = "blazings")
        {
            var passwdList = ReadValue(passwdPath);
            for (int i = passwdList.Count - 1; i >= 0; i--)
            {
                if (valueText.Equals(passwdList[i]))
                {
                    passwdList.RemoveAt(i);
                }
            }
            var toJson = JsonConvert.SerializeObject(passwdList);
            jyh.WriteTxt(passwdPath, toJson);
        }
        //单击复制
        private void listBox1_Click(object sender, EventArgs e)
        {
            try
            {
                Clipboard.SetDataObject(listBox1.SelectedItem.ToString());
                labState.Text = listBox1.SelectedItem.ToString();
            }
            catch (Exception exception)
            {
            }
        }
        //删除
        private void listBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                try
                {
                    if (jyh.ConfirmForm("确认删除?"))
                    {
                        var deleteStr = listBox1.SelectedItem.ToString();
                        DeleteValue(txtboxFilePath.Text, deleteStr);
                        labState.Text = "删除: " + deleteStr;
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    throw;
                }
                ReloadList(ReadValue(txtboxFilePath.Text));
            }
        }
        //窗口关闭
        private void SelectPaste_From_FormClosed(object sender, FormClosedEventArgs e)
        {
            Jyh.UnregisterHotKey(Handle, hotKeyId);
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            //按快捷键
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case hotKeyId:
                            if (Visible)
                            {
                                HideForm();
                            }
                            else
                            {
                                ShowForm();
                            }
                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        private void SelectPaste_From_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                notifyIcon1.Visible = true;
                Hide();
            }
        }

        public void ShowForm()
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
        public void HideForm()
        {
            this.WindowState = FormWindowState.Minimized;
            this.notifyIcon1.Visible = true;
            this.Hide();
        }
        //双击显示
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                HideForm();
            }
            else
            {
                ShowForm();
            }
        }

        private void txtboxValue_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData==Keys.Enter)
            {
                btnAdd_Click(sender, e);
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            MouseEventArgs mouseE = e;
            //右键
            if (mouseE.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show();
            }
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}


text:
package com.ivstuart.tmud.state;

public class MobStateDuration {

	private static final String[] durationDescription = {
			"is about to wear off", "will last for a short while",
			"will last a while", "will last for a long time",
			"will last for hours", "will last for days" };

	private long expiryTimeMillis;

	MobStateDuration(int expirySeconds) {
		expiryTimeMillis = System.currentTimeMillis() + (expirySeconds * 1000);
	}

	public String getDuration() {
		long durationTimeMillis = expiryTimeMillis - System.currentTimeMillis();

		int index = (int) durationTimeMillis / (1000 * 60);

		if (index < 0) {
			index = 0;
		} else if (index > durationDescription.length - 1) {
			index = durationDescription.length - 1;
		}

		return "(" + durationDescription[index] + ")";
	}

	public boolean isExpired() {
		return (expiryTimeMillis - System.currentTimeMillis() < 0);
	}

}


text:
<?php

/**
 * Runtime workflow configuration. In Arcanist, commands you type like
 * "arc diff" or "arc lint" are called "workflows". This class allows you to add
 * new workflows (and extend existing workflows) by subclassing it and then
 * pointing to your subclass in your project configuration.
 *
 * When specified as the **arcanist_configuration** class in your project's
 * ##.arcconfig##, your subclass will be instantiated (instead of this class)
 * and be able to handle all the method calls. In particular, you can:
 *
 *    - create, replace, or disable workflows by overriding buildWorkflow()
 *      and buildAllWorkflows();
 *    - add additional steps before or after workflows run by overriding
 *      willRunWorkflow() or didRunWorkflow() or didAbortWorkflow(); and
 *    - add new flags to existing workflows by overriding
 *      getCustomArgumentsForCommand().
 *
 * @concrete-extensible
 */
class ArcanistConfiguration extends Phobject {

  public function buildWorkflow($command) {
    if ($command == '--help') {
      // Special-case "arc --help" to behave like "arc help" instead of telling
      // you to type "arc help" without being helpful.
      $command = 'help';
    } else if ($command == '--version') {
      // Special-case "arc --version" to behave like "arc version".
      $command = 'version';
    }

    $workflow = idx($this->buildAllWorkflows(), $command);

    if (!$workflow) {
      return null;
    }

    return clone $workflow;
  }

  public function buildAllWorkflows() {
    return id(new PhutilClassMapQuery())
      ->setAncestorClass('ArcanistWorkflow')
      ->setUniqueMethod('getWorkflowName')
      ->execute();
  }

  final public function isValidWorkflow($workflow) {
    return (bool)$this->buildWorkflow($workflow);
  }

  public function willRunWorkflow($command, ArcanistWorkflow $workflow) {
    // This is a hook.
  }

  public function didRunWorkflow($command, ArcanistWorkflow $workflow, $err) {

    // This is a hook.
  }

  public function didAbortWorkflow($command, $workflow, Exception $ex) {
    // This is a hook.
  }

  public function getCustomArgumentsForCommand($command) {
    return array();
  }

  final public function selectWorkflow(
    &$command,
    array &$args,
    ArcanistConfigurationManager $configuration_manager,
    PhutilConsole $console) {

    // First, try to build a workflow with the exact name provided. We always
    // pick an exact match, and do not allow aliases to override it.
    $workflow = $this->buildWorkflow($command);
    if ($workflow) {
      return $workflow;
    }

    // If the user has an alias, like 'arc alias dhelp diff help', look it up
    // and substitute it. We do this only after trying to resolve the workflow
    // normally to prevent you from doing silly things like aliasing 'alias'
    // to something else.
    $aliases = ArcanistAliasWorkflow::getAliases($configuration_manager);
    list($new_command, $args) = ArcanistAliasWorkflow::resolveAliases(
      $command,
      $this,
      $args,
      $configuration_manager);

    $full_alias = idx($aliases, $command, array());
    $full_alias = implode(' ', $full_alias);

    // Run shell command aliases.
    if (ArcanistAliasWorkflow::isShellCommandAlias($new_command)) {
      $shell_cmd = substr($full_alias, 1);

      $console->writeLog(
        "[%s: 'arc %s' -> $ %s]",
        pht('alias'),
        $command,
        $shell_cmd);

      if ($args) {
        $err = phutil_passthru('%C %Ls', $shell_cmd, $args);
      } else {
        $err = phutil_passthru('%C', $shell_cmd);
      }

      exit($err);
    }

    // Run arc command aliases.
    if ($new_command) {
      $workflow = $this->buildWorkflow($new_command);
      if ($workflow) {
        $console->writeLog(
          "[%s: 'arc %s' -> 'arc %s']\n",
          pht('alias'),
          $command,
          $full_alias);
        $command = $new_command;
        return $workflow;
      }
    }

    $all = array_keys($this->buildAllWorkflows());

    // We haven't found a real command or an alias, so try to locate a command
    // by unique prefix.
    $prefixes = $this->expandCommandPrefix($command, $all);

    if (count($prefixes) == 1) {
      $command = head($prefixes);
      return $this->buildWorkflow($command);
    } else if (count($prefixes) > 1) {
      $this->raiseUnknownCommand($command, $prefixes);
    }

    // We haven't found a real command, alias, or unique prefix. Try similar
    // spellings.
    $corrected = PhutilArgumentSpellingCorrector::newCommandCorrector()
      ->correctSpelling($command, $all);
    if (count($corrected) == 1) {
      $console->writeErr(
        pht(
          "(Assuming '%s' is the British spelling of '%s'.)",
          $command,
          head($corrected))."\n");
      $command = head($corrected);
      return $this->buildWorkflow($command);
    } else if (count($corrected) > 1) {
      $this->raiseUnknownCommand($command, $corrected);
    }

    $this->raiseUnknownCommand($command);
  }

  private function raiseUnknownCommand($command, array $maybe = array()) {
    $message = pht("Unknown command '%s'. Try '%s'.", $command, 'arc help');
    if ($maybe) {
      $message .= "\n\n".pht('Did you mean:')."\n";
      sort($maybe);
      foreach ($maybe as $other) {
        $message .= "    ".$other."\n";
      }
    }
    throw new ArcanistUsageException($message);
  }

  private function expandCommandPrefix($command, array $options) {
    $is_prefix = array();
    foreach ($options as $option) {
      if (strncmp($option, $command, strlen($command)) == 0) {
        $is_prefix[$option] = true;
      }
    }

    return array_keys($is_prefix);
  }

}


text:
<?php namespace SublimeArts\SublimeChimp\Models;

use SublimeArts\SublimeChimp\Classes\SublimeChimp\BaseModel;
use SublimeArts\SublimeChimp\Models\Settings;

/**
 * MailingList Model
 */
class MailingList extends BaseModel
{
    /**
     * @var string The database table used by the model.
     */
    public $table = 'sa_sublimechimp_mailing_lists';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [
        'mailchimp_id'
    ];

    /**
     * @var array Relations
     */
    public $hasMany = [
        'campaigns' => [ 'SublimeArts\SublimeChimp\Models\Campaign' ],
        'campaigns_count' => [ 'SublimeArts\SublimeChimp\Models\Campaign', 'count' => 'true' ],
    ];

    public $belongsToMany = [
        'recipients' => [
            'SublimeArts\SublimeChimp\Models\Recipient',
            'table'    => 'sa_mailing_list_recipient',
            'key'      => 'mailing_list_id',
            'otherKey' => 'recipient_id'
        ],
        'recipients_count' => [
            'SublimeArts\SublimeChimp\Models\Recipient',
            'table'    => 'sa_mailing_list_recipient',
            'key'      => 'mailing_list_id',
            'otherKey' => 'recipient_id',
            'count'    => 'true'
        ]
    ];

    public function getContactInfo()
    {
        return json_encode([
            "company" => Settings::get("contact_organization"),
            "address1" => Settings::get("contact_address"),
            "city" => Settings::get("contact_city"),
            "state" => Settings::get("contact_state"),
            "zip" => Settings::get("contact_zip"),
            "country" => Settings::get("contact_country"),
            "phone" => Settings::get("contact_phone")
        ]);
    }

    public function getContactAttribute()
    {
        return ( Settings::get("contact_organization") )
                ? Settings::get("contact_organization")
                : "-";
    }

    public function beforeSave()
    {

    }
}


text:
'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var Post = new Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    content: {
        type: String,
        trim: true
    },
    category: {
        type: Schema.ObjectId,
        ref: 'PostCategory'
    },
    isDeleted: {
        type: Boolean,
        default: false
    },
    created: {
        type: Date,
        default: Date.now
    },
    updated: [{
        type: Date
    }]
});

mongoose.model('Post', Post);


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<WindowOpeningMode>LockOwnerWindow</WindowOpeningMode>
	<AutoSaveDataInSettings>Use</AutoSaveDataInSettings>
	<VerticalScroll>useIfNecessary</VerticalScroll>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1"/>
	<Events>
		<Event name="NotificationProcessing">ОбработкаОповещения</Event>
		<Event name="OnOpen">ПриОткрытии</Event>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
		<Event name="OnClose">ПриЗакрытии</Event>
	</Events>
	<ChildItems>
		<Table name="Список" id="1">
			<Representation>List</Representation>
			<CommandBarLocation>None</CommandBarLocation>
			<SkipOnInput>false</SkipOnInput>
			<DefaultItem>true</DefaultItem>
			<ChoiceMode>true</ChoiceMode>
			<SelectionMode>SingleRow</SelectionMode>
			<UseAlternationRowColor>true</UseAlternationRowColor>
			<DataPath>Список</DataPath>
			<RowPictureDataPath>Список.DefaultPicture</RowPictureDataPath>
			<SearchStringLocation>None</SearchStringLocation>
			<ViewStatusLocation>None</ViewStatusLocation>
			<SearchControlLocation>None</SearchControlLocation>
			<AutoRefresh>false</AutoRefresh>
			<AutoRefreshPeriod>60</AutoRefreshPeriod>
			<Period xsi:type="v8:StandardPeriod">
				<v8:variant xsi:type="v8:StandardPeriodVariant">Custom</v8:variant>
				<v8:startDate>0001-01-01T00:00:00</v8:startDate>
				<v8:endDate>0001-01-01T00:00:00</v8:endDate>
			</Period>
			<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
			<RestoreCurrentRow>false</RestoreCurrentRow>
			<TopLevelParent xsi:nil="true"/>
			<ShowRoot>false</ShowRoot>
			<AllowRootChoice>false</AllowRootChoice>
			<UpdateOnDataChange>Auto</UpdateOnDataChange>
			<ContextMenu name="СписокКонтекстноеМеню" id="2"/>
			<AutoCommandBar name="СписокКоманднаяПанель" id="3"/>
			<ExtendedTooltip name="СписокExtendedTooltip" id="22"/>
			<SearchStringAddition name="СписокSearchString" id="23">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>0</lf:additionId>
				</Source>
				<ContextMenu name="СписокSearchStringContextMenu" id="24"/>
				<ExtendedTooltip name="СписокSearchStringExtendedTooltip" id="25"/>
			</SearchStringAddition>
			<ViewStatusAddition name="СписокViewStatus" id="26">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>1</lf:additionId>
				</Source>
				<ContextMenu name="СписокViewStatusContextMenu" id="27"/>
				<ExtendedTooltip name="СписокViewStatusExtendedTooltip" id="28"/>
			</ViewStatusAddition>
			<SearchControlAddition name="СписокSearchControl" id="29">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>2</lf:additionId>
				</Source>
				<ContextMenu name="СписокSearchControlContextMenu" id="30"/>
				<ExtendedTooltip name="СписокSearchControlExtendedTooltip" id="31"/>
			</SearchControlAddition>
			<ChildItems>
				<InputField name="СписокНомер" id="6">
					<DataPath>Список.Number</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Номер</v8:content>
						</v8:item>
					</Title>
					<Width>10</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<Wrap>false</Wrap>
					<ContextMenu name="СписокНомерКонтекстноеМеню" id="7"/>
					<ExtendedTooltip name="СписокНомерExtendedTooltip" id="32"/>
				</InputField>
				<InputField name="СписокДата" id="4">
					<DataPath>Список.Date</DataPath>
					<DefaultItem>true</DefaultItem>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Дата</v8:content>
						</v8:item>
					</Title>
					<Width>14</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<Wrap>false</Wrap>
					<ContextMenu name="СписокДатаКонтекстноеМеню" id="5"/>
					<ExtendedTooltip name="СписокДатаExtendedTooltip" id="33"/>
				</InputField>
				<InputField name="СписокСуммаДокумента" id="18">
					<DataPath>Список.СуммаДокумента</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Сумма</v8:content>
						</v8:item>
					</Title>
					<Width>9</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<Wrap>false</Wrap>
					<ContextMenu name="СписокСуммаДокументаКонтекстноеМеню" id="19"/>
					<ExtendedTooltip name="СписокСуммаДокументаExtendedTooltip" id="34"/>
				</InputField>
				<InputField name="СписокВалюта" id="16">
					<DataPath>Список.Валюта</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Валюта</v8:content>
						</v8:item>
					</Title>
					<Width>6</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<Wrap>false</Wrap>
					<ContextMenu name="СписокВалютаКонтекстноеМеню" id="17"/>
					<ExtendedTooltip name="СписокВалютаExtendedTooltip" id="35"/>
				</InputField>
				<InputField name="СписокПартнер" id="8">
					<DataPath>Список.Партнер</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Партнер</v8:content>
						</v8:item>
					</Title>
					<Width>16</Width>
					<Wrap>false</Wrap>
					<ContextMenu name="СписокПартнерКонтекстноеМеню" id="9"/>
					<ExtendedTooltip name="СписокПартнерExtendedTooltip" id="36"/>
				</InputField>
				<InputField name="СписокСделка" id="14">
					<DataPath>Список.Сделка</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Сделка</v8:content>
						</v8:item>
					</Title>
					<Width>16</Width>
					<Wrap>false</Wrap>
					<ContextMenu name="СписокСделкаКонтекстноеМеню" id="15"/>
					<ExtendedTooltip name="СписокСделкаExtendedTooltip" id="37"/>
				</InputField>
				<InputField name="СписокКонтрагент" id="10">
					<DataPath>Список.Контрагент</DataPath>
					<UserVisible>
						<xr:Common>false</xr:Common>
					</UserVisible>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Контрагент</v8:content>
						</v8:item>
					</Title>
					<Width>16</Width>
					<Wrap>false</Wrap>
					<ContextMenu name="СписокКонтрагентКонтекстноеМеню" id="11"/>
					<ExtendedTooltip name="СписокКонтрагентExtendedTooltip" id="38"/>
				</InputField>
				<InputField name="СписокОрганизация" id="12">
					<DataPath>Список.Организация</DataPath>
					<UserVisible>
						<xr:Common>false</xr:Common>
					</UserVisible>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Организация</v8:content>
						</v8:item>
					</Title>
					<Width>16</Width>
					<Wrap>false</Wrap>
					<ContextMenu name="СписокОрганизацияКонтекстноеМеню" id="13"/>
					<ExtendedTooltip name="СписокОрганизацияExtendedTooltip" id="39"/>
				</InputField>
				<LabelField name="Ссылка" id="20">
					<DataPath>Список.Ref</DataPath>
					<UserVisible>
						<xr:Common>false</xr:Common>
					</UserVisible>
					<ContextMenu name="СсылкаКонтекстноеМеню" id="21"/>
					<ExtendedTooltip name="СсылкаExtendedTooltip" id="40"/>
				</LabelField>
			</ChildItems>
		</Table>
	</ChildItems>
	<Attributes>
		<Attribute name="Список" id="1">
			<Type>
				<v8:Type>cfg:DynamicList</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
			<Settings xsi:type="DynamicList">
				<ManualQuery>false</ManualQuery>
				<DynamicDataRead>true</DynamicDataRead>
				<MainTable>Document.ЗаказКлиента</MainTable>
				<ListSettings>
					<dcsset:filter>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>dfcece9d-5077-440b-b6b3-45a5cb4538eb</dcsset:userSettingID>
					</dcsset:filter>
					<dcsset:order>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>88619765-ccb3-46c6-ac52-38e9c992ebd4</dcsset:userSettingID>
					</dcsset:order>
					<dcsset:conditionalAppearance>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>b75fecce-942b-4aed-abc9-e6a02e460fb3</dcsset:userSettingID>
					</dcsset:conditionalAppearance>
				</ListSettings>
			</Settings>
		</Attribute>
		<Attribute name="ИспользоватьПодключаемоеОборудование" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Использовать подключаемое оборудование</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
		<Attribute name="ПоддерживаемыеТипыПодключаемогоОбрудования" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Поддерживаемые типы подключаемого обрудования</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:string</v8:Type>
				<v8:StringQualifiers>
					<v8:Length>0</v8:Length>
					<v8:AllowedLength>Variable</v8:AllowedLength>
				</v8:StringQualifiers>
			</Type>
		</Attribute>
	</Attributes>
	<CommandInterface>
		<CommandBar>
			<Item>
				<Command>0</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ИсторияИзменений</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>0</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ОперацияПоПлатежнойКарте.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ПоступлениеБезналичныхДенежныхСредств.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ПриходныйКассовыйОрдер.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.РасходныйОрдерНаТовары.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.РеализацияТоваровУслуг.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.СчетНаОплатуКлиенту.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>DataProcessor.ПечатьЗаданияНаОтборРазмещениеТоваров.Command.ПечатьЗаданияНаРазмещениеТоваров</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>0</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>0</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>BusinessProcess.Задание.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ВозвратТоваровОтКлиента.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>BusinessProcess.СогласованиеПродажи.Command.СоздатьНовоеСогласованиеЗаказаКлиента</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ДополнительныеСведенияКоманднаяПанель</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ЗаказКлиента.Command.ПечатьЗаказКлиента</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.Печать</CommandGroup>
				<Index>3</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ЗаказКлиента.Command.ПечатьСчетНаОплату</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.АктВыполненныхРабот.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Catalog.ПретензииКлиентов.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.СчетНаОплатуКлиенту.Command.СоздатьСчетНаОплату</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>DataProcessor.ПечатьСчетовНаОплату.Command.ПечатьСчетНаОплатуПоЗаказуЗаявке</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.Печать</CommandGroup>
				<Index>1</Index>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>0:ab3824ad-d1cd-4b9a-9323-a740c99b809c</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.Печать</CommandGroup>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ДополнительныеОтчетыИОбработкиПечатныеФормы</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.Печать</CommandGroup>
				<Index>2</Index>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>0:c4f0f453-4564-4293-94b0-6ed1c59db430</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.Печать</CommandGroup>
				<Index>4</Index>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>DataProcessor.ЭлектронныеДокументы.Command.ОткрытьАктуальныйЭД</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.ЭД</CommandGroup>
				<Index>4</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>DataProcessor.ЭлектронныеДокументы.Command.ПереотправитьЭД</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.ЭД</CommandGroup>
				<Index>1</Index>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>DataProcessor.ЭлектронныеДокументы.Command.ПерезаполнитьДокумент</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.ЭД</CommandGroup>
				<Index>2</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>DataProcessor.ЭлектронныеДокументы.Command.СформироватьЭД</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.ЭД</CommandGroup>
				<Index>3</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>DataProcessor.ЭлектронныеДокументы.Command.СформироватьПодписатьОтправитьЭД</Command>
				<Type>Auto</Type>
				<CommandGroup>CommandGroup.ЭД</CommandGroup>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
		</CommandBar>
	</CommandInterface>
</Form>


text:
interface Token {
  unencoded: UnencodedToken;
  encoded: string;
}

export interface AuthState {
  token: Token;
}

interface UnencodedToken {
  /** ISSUER - Where token came from (API URL). */
  iss: string;
  /** JSON Token Identifier- auto sync needs this to hear its echo on MQTT */
  jti: string;
  /** Audience claim - usually "bot", "human", or "unknown" */
  aud: string;
  /** This is the username for the MQTT server. Follows format of `device_x`,
   * where `x` represents the device's `id` property. */
  bot: string;
  /** URL for MQTT over websockets. */
  mqtt_ws: string;
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

<title>Estimote Beacons Example</title>

Estimote Beacons

Range Estimote Beacons. This app demonstrates how to scan for Estimote Beacons using ranging.

Run this example in Evothings Viewer, or build a Cordova app with the plugin phonegap-estimotebeacons. iOS 7 or later, or an Android device with support for Bluetooth 4.0 and Android 4.3 or higher, is required.

Source code

You can browse the source code for this example at the
	Evothings GitHub repository

The file index.html is the main HTML file of the app.

In file app.js you will find the JavaScript code for the app.

What you need

This example works with Estimote Beacons. Visit estimote.com for further details.

Run the app in Evothings Viewer on Android or iOS.

Optionally you can build a stand-alone native app using Cordova. You then need to include the Cordova plugin pl.makingwaves.estimotebeacons. For further details see the Cordova build guide.

An iOS device (iOS 7 or 8) or an Android device with support for Bluetooth 4.0 (which includes BLE) is required. For Android version 4.3 or later is needed.

How to get up and running

Follow these steps to get started with this example:

Have at least one Estimote Beacon nearby.

Run Evothings Workbench on your desktop/laptop computer.

Run Evothings Viewer on a mobile device and connect to the Workbench.

Launch the example "Estimote Beacons" from the Workbench window by pressing "Run".

If everything works, the app should automatically detect your Estimote Beacons.

To learn more, have a look at the GitHub page for the Estimote JavaScript plugin.


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.github.jochenw.afw.core.log.log4j (AFW (Core) 1.0 API)</title>
<meta name="date" content="2019-02-06">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

com.github.jochenw.afw.core.log.log4j

Classes

Log4j2Log

Log4j2LogFactory

Log4jLog

Log4jLogFactory


text:
#ifndef __PACKET_ICMP_H__
#define __PACKET_ICMP_H__

extern int proto_icmp;

/* ICMP echo request/reply transaction statistics ... used by ICMP tap(s) */
typedef struct _icmp_transaction_t {
    guint32 rqst_frame;
    guint32 resp_frame;
    nstime_t rqst_time;
    nstime_t resp_time;
} icmp_transaction_t;

#endif


text:
import defaults from 'appConfig/defaults';
import sf from 'appConfig/sf';
import tahoe from 'appConfig/tahoe';
import contracosta from 'appConfig/contracosta';

const configs = {
  defaults,
  sf,
  tahoe,
  contracosta,
};

const DEFAULT_REGION = 'sf';
const region = process.env.NEXT_PUBLIC_REGION || DEFAULT_REGION;
const config = { ...configs.defaults, ...configs[region] };

export default config;


text:
package apple.coremotion;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;

/**
 * @since Available in iOS 7.0 and later.
 */
@Library("CoreMotion/CoreMotion.h") @Mapping("CMMotionActivityManager")
public class CMMotionActivityManager
    extends NSObject
     {

    @Mapping("init")
    public CMMotionActivityManager() { }

    @Mapping("stopActivityUpdates")
    public native void stopActivityUpdates();
    @Mapping("isActivityAvailable")
    public static native boolean isActivityAvailable();

}


text: docker build --no-cache -t glot/clojure:latest .


text:
require 'spec_helper'

describe ExampleGroupsController, type: :controller do
  before :all do
    ExampleGroup.create(description: 'foobar')
  end

  describe "GET /example_groups.json" do
    specify "it should return all ExampleGroups" do
      json_request :index

      response.should be_successful
      response.should be_valid_json
      response.should have_json_body_of(ExampleGroup.all)
    end
  end

  describe "GET /example_groups/1.json" do
    specify "With valid params, it should return the example_group" do
      json_request :show, id: 1

      response.should be_successful
      response.should be_valid_json
      response.should have_json_body_of(ExampleGroup.first)
    end

    specify "With invalid params, it should not be successful" do
      json_request :show, description: 'foobar'

      response.should_not be_successful
    end
  end

  describe "POST /example_groups.json" do
    specify "With valid params, it should return the newly created example_group" do
      json_request :create, { example_group: { description: 'new' } }

      response.should be_successful
      response.should be_valid_json
      response.should have_json_body_of(ExampleGroup.where(description: 'new').first)
    end

    specify "With invalid params, it should not be successful" do
      json_request :create, { example_group: { age: 13 } }

      response.should_not be_successful
    end
  end

  describe "PUT /example_groups/1.json" do
    specify "With valid params, it should return the newly updated example_group" do
      json_request :update, { id: '1', example_group: { description: 'foobaz' } }

      response.should be_successful
      response.should be_valid_json
      response.should have_json_body_of(ExampleGroup.where(description: 'foobaz').first)
    end

    specify "With invalid params, it should not be successful" do
      json_request :update, { example_group: { age: 13 } }

      response.should_not be_successful
    end
  end

  describe "DELETE /example_groups/1.json" do
    specify "With valid params, it should return be successful" do
      json_request :destroy, { id: '1' }

      response.should be_successful
      ExampleGroup.exists?(1).should be_false
    end

    specify "With invalid params, it should not be successful" do
      json_request :destroy, { description: 'foobar' }

      response.should_not be_successful
      ExampleGroup.exists?(2).should_not be_false
    end
  end
end


text:
/**
 * @file:ast_support.cpp
 * A definition of a variety of convinient functions for easy AST manipulating
 */
 /*
  * Copyright 2012 MIPT-COMPILER team
  */

#include "est_support.hpp"
#include "interpreter_exception.hpp"

namespace interpreter
{
namespace est
{

SExprp copyList( SExprp list)
{
    if ( list->type != SExpr::cons)
        return Nil::make();
    return Cons::make( as<Cons>(list)->car, //TODO: rewrite it in an
                       copyList( as<Cons>(list)->cdr)); // iterative fashion
}

SExprp append( SExprp list, SExprp tail)
{
    SExprp prev = list;
    if ( prev->type == SExpr::nil)
        return tail;
    if ( prev->type != SExpr::cons)
        throw Exception( "trying to append to a non list", prev);
    SExprp current = as<Cons>(prev)->cdr;
    while( current->type != SExpr::nil)
    {
        if ( prev->type != SExpr::cons)
            throw Exception( "trying to append to a non list", prev);
        prev = current;
        current = as<Cons>(current)->cdr;
    }
    as<Cons>(prev)->cdr = tail;
    return list;
}

SExprp reverse( SExprp list, SExprp tail)
{
    if (list->type == SExpr::nil) return tail;

    assert( list->type== SExpr::cons);
    return reverse( as<Cons>(list)->cdr, Cons::make( as<Cons>(list)->car, tail));
}

int listLength( SExprp list)
{
    int len = 0;
    SExprp current = list;
    while( current->type == SExpr::cons)
    {
        current = as<Cons>(current)->cdr;
//        assert( current != list);//TODO: provide acyclic list
        ++len;
    }
    assert( current->type == SExpr::nil);
    return len;
}

/* Many parts, which are implementation specified, implemented
 * as they should be implemented in eqv for simplicity*/
bool areEq( SExprp one, SExprp another)
{
    if ( one.get() == another.get())
        return true;

    if (one->type != another->type)
        return false;

    switch( one->type)
    {
    case SExpr::nil:
        return true;
    case SExpr::cons:
        return false;
    case SExpr::symbol:
        return as<Symbol>(one)->getName() == as<Symbol>(another)->getName();
    case SExpr::vector:
        return as<Vector>(one)->val().size() == 0
            && as<Vector>(another)->val().size() == 0;
    case SExpr::string_const:
        return as<StrConst>(one)->val().size() == 0
            && as<StrConst>(another)->val().size() == 0;
    case SExpr::number_const:
        return as<Number>(one)->val() == as<Number>(another)->val();
    case SExpr::character_const:
        return as<Character>(one)->val() == as<Character>(another)->val();
    case SExpr::boolean_const:
        return as<Boolean>(one)->val() == as<Boolean>(another)->val();
    case SystemObj::funid:
        return as<FunId>(one)->id() == as<FunId>(another)->id();
    case SystemObj::macid:
        return as<MacId>(one)->id() == as<MacId>(another)->id();
    case SystemObj::specid:
        return as<SpecId>(one)->id() == as<SpecId>(another)->id();
    case SystemObj::port:
        return as<Port>(one)->in() == as<Port>(another)->in()
            && as<Port>(one)->out() == as<Port>(another)->out();
    case SystemObj::eof_val:
        return true;
    default:
        return false;
    };
}

bool areEqv( SExprp one, SExprp another)
{
    if ( areEq( one, another))
        return true;
    return false;//here can be some additional comparings
}

}//namespace est
}//namespace interpreter


text:
using Kaftar.Core.Data.DataContext;

namespace Avicenna.Domain.Data
{
    public class AvicennaContext:DbContextBase
    {

    }
}


text:
//
// A ZlibInStream reads from a zlib.io.InputStream
//

package com.iiordanov.tigervnc.rdr;
import com.iiordanov.jcraft.jzlib.*;

public class ZlibInStream extends InStream {

  static final int defaultBufSize = 16384;

  public ZlibInStream(int bufSize_)
  {
    bufSize = bufSize_;
    b = new byte[bufSize];
    bytesIn = offset = 0;
    zs = new ZStream();
    zs.next_in = null;
    zs.next_in_index = 0;
    zs.avail_in = 0;
    if (zs.inflateInit() != JZlib.Z_OK) {
      zs = null;
      throw new Exception("ZlinInStream: inflateInit failed");
    }
    ptr = end = start = 0;
  }

  public ZlibInStream() { this(defaultBufSize); }

  protected void finalize() throws Throwable {
    try {
      b = null;
      zs.inflateEnd();
    } finally {
      super.finalize();
    }
  }

  public void setUnderlying(InStream is, int bytesIn_)
  {
    underlying = is;
    bytesIn = bytesIn_;
    ptr = end = start;
  }

  public int pos()
  {
    return offset + ptr - start;
  }

  public void reset()
  {
    ptr = end = start;
    if (underlying == null) return;

    while (bytesIn > 0) {
      decompress(true);
      end = start; // throw away any data
    }
    underlying = null;
  }

  protected int overrun(int itemSize, int nItems, boolean wait)
  {
    if (itemSize > bufSize)
      throw new Exception("ZlibInStream overrun: max itemSize exceeded");
    if (underlying == null)
      throw new Exception("ZlibInStream overrun: no underlying stream");

    if (end - ptr != 0)
      System.arraycopy(b, ptr, b, start, end - ptr);

    offset += ptr - start;
    end -= ptr - start;
    ptr = start;

    while (end - ptr < itemSize) {
      if (!decompress(wait))
        return 0;
    }

    if (itemSize * nItems > end - ptr)
      nItems = (end - ptr) / itemSize;

    return nItems;
  }

  // decompress() calls the decompressor once.  Note that this won't
  // necessarily generate any output data - it may just consume some input
  // data.  Returns false if wait is false and we would block on the underlying
  // stream.

  private boolean decompress(boolean wait)
  {
    zs.next_out = b;
    zs.next_out_index = end;
    zs.avail_out = start + bufSize - end;

    int n = underlying.check(1, 1, wait);
    if (n == 0) return false;
    zs.next_in = underlying.getbuf();
    zs.next_in_index = underlying.getptr();
    zs.avail_in = underlying.getend() - underlying.getptr();
    if (zs.avail_in > bytesIn)
      zs.avail_in = bytesIn;

    int rc = zs.inflate(JZlib.Z_SYNC_FLUSH);
    if (rc != JZlib.Z_OK) {
      throw new Exception("ZlibInStream: inflate failed");
    }

    bytesIn -= zs.next_in_index - underlying.getptr();
    end = zs.next_out_index;
    underlying.setptr(zs.next_in_index);
    return true;
  }

  private InStream underlying;
  private int bufSize;
  private int offset;
  private ZStream zs;
  private int bytesIn;
  private int start;
}


text:
import expect from 'expect';
import RestApi, {RestfulAPI} from '../index.js';

const baseUrl = 'https://jsonplaceholder.typicode.com';
const NOT_FOUND_ERROR = 404;

describe('main plug-in test', function () {

	this.timeout(10000);

	it('should be initialized by default', () => {
		expect(RestfulAPI).toExist();
	});

	it('should create a new instance of class RestfulAPI', () => {
		expect(new RestfulAPI()).toExist();
	});

	it('should include error handler', () => {
		let errorResponseHandler = () => {
		};
		let restfulAPI = new RestfulAPI({errorResponseHandler});
		expect(restfulAPI.errorResponseHandler).toBe(errorResponseHandler);
	});

	it('RestApi instance should exist', () => {
		expect(RestApi).toExist();
	});

	it.only('should get response from server', done => {
		RestApi.fetch(`${baseUrl}/users`).then(response => {
			expect(response.length).toExist().toBeMoreThan(0);
			done();
		});
	});

	it('should get response from server', done => {
		RestApi.get(`${baseUrl}/users`).then(response => {
			expect(response.length).toExist().toBeMoreThan(0);
			done();
		});
	});

	it('should post data to server', done => {
		RestApi.post(`${baseUrl}/posts`, {
			data: {
				title: 'restful-js'
			}
		}).then(response => {
			expect(response).toExist().toIncludeKey('id').toIncludeKey('data');
			done();
		});
	});

	it('should post data to server with FormData object', done => {
		let formData = new FormData();
		if (formData.set) { // to support FF < 39.0
			formData.set('upload', JSON.stringify({
				data: {
					title: 'restful-js'
				}
			}));
			RestApi.post(`${baseUrl}/posts`, formData).then(response => {
				expect(response).toExist().toIncludeKey('id');
				done();
			});
		}
		else {done();}
	});

	it('should update data on server', done => {
		RestApi.put(`${baseUrl}/posts/1`, {
			data: {
				id: 1,
				title: 'restful-js is awesome'
			}
		}).then(response => {
			expect(response).toExist().toIncludeKey('id');
			done();
		});
	});

	it('should delete data on server', done => {
		RestApi.destroy(`${baseUrl}/posts/1`).then(response => {
			expect(response).toExist();
			done();
		});
	});

	it('should throw error without error handling', done => {
		RestApi.fetch(`${baseUrl}/non/exist/resource`).then(() => {
		}, error => {
			expect(error.status).toExist().toEqual(NOT_FOUND_ERROR);
			done();
		});
	});

	it('should throw error with error handling', done => {
		let errorResponseHandler = (xhr/*, textStatus, errorThrown*/) => {
			expect(xhr.status).toExist().toEqual(NOT_FOUND_ERROR);
			done();
		};
		let restfulAPI = new RestfulAPI({errorResponseHandler});
		restfulAPI.fetch(`${baseUrl}/non/exist/resource`);
	});

	it('should call ajax start event', done => {
		const ajaxStartHandler = function () {
			done();
		};
		new RestfulAPI({ajaxStartHandler}).get(`${baseUrl}/users`);
	});

	it('should call ajax stop event', done => {
		const ajaxStopHandler = function () {
			done();
		};
		new RestfulAPI({ajaxStopHandler}).get(`${baseUrl}/users`);
	});

	it('should expose jQuery to the out side', () => {
		expect(RestApi.$).toExist();
	});

});


text:
$(document).ready(function () {

    $("#create-btn").click(function () {

        var name = $("#name");
        var password = $("#password");
        var role = $("#role");
        var address = $("#address");
        var musicType = $("#musicType");

        if (name != '') {
            $.ajax({
                url: "create",
                method: "post",
                data: {
                    'name': name.val(),
                    'password': password.val(),
                    'role': role.val(),
                    'address': address.val(),
                    'musicType': musicType.val()},
                complete: function (data) {
                    var result = JSON.parse(data.responseText);
                    if (Boolean(result.success)) {
                        alert("User successfully created.");
                        clearFields();
                    }
                    else {
                        alert("Something went wrong, during user creation process, check input data!");
                    }
                }
            });
        } else {
            alert("Please check input data!");
        }
    });

    function clearFields() {
        $('input').val('');
    };

    $("#addr-btn").click(function () {

        var address = $("#Address_field");
        if (address != '') {
            $.ajax({
                url: "json",
                method: "get",
                datatype: 'json',
                data: {
                    'address': address.val(),
                    'music': '',
                    'role': '',
                    'roleAll': ''
                },
                complete: function (data) {
                    var result = JSON.parse(data.responseText);
                    if(result.user != ''){
                        var user =  JSON.parse(result.user);
                        var insertTable = "";
                        for (var i = 0; i != user.length; ++i) {
                            insertTable += "
";
                            insertTable += ""+user[i].name+"	";
                            insertTable += ""+user[i].address+"	";
                            insertTable += ""+user[i].musictypes+"	";
                            insertTable += ""+user[i].role+"	";
                            insertTable += "
";
                        }
                        var filledTable = document.getElementById("insert");
                        filledTable.innerHTML = insertTable;

                    }
                }
            });
        }
    });

    $("#role-btn").click(function () {

        var role = $("#Role_field");
        if (role != '') {
            $.ajax({
                url: "json",
                method: "get",
                datatype: 'json',
                data: {
                    'address': '',
                    'music': '',
                    'role': role.val(),
                    'roleAll': ''
                },
                complete: function (data) {
                    var result = JSON.parse(data.responseText);
                    if(result.user != ''){
                        var user =  JSON.parse(result.user);
                        var insertTable = "";
                        for (var i = 0; i != user.length; ++i) {
                            insertTable += "
";
                            insertTable += ""+user[i].name+"	";
                            insertTable += ""+user[i].address+"	";
                            insertTable += ""+user[i].musictypes+"	";
                            insertTable += ""+user[i].role+"	";
                            insertTable += "
";
                        }
                        var filledTable = document.getElementById("insert");
                        filledTable.innerHTML = insertTable;
                        table.show();
                    }
                }
            });
        }
    });

    $("#musictype-btn").click(function () {

        var music = $("#Musictype_field");
        if (music != '') {
            $.ajax({
                url: "json",
                method: "get",
                datatype: 'json',
                data: {
                    'address': '',
                    'music': music.val(),
                    'role': '',
                    'roleAll': ''
                },
                complete: function (data) {
                    var result = JSON.parse(data.responseText);
                    if(result.user != ''){
                        var user =  JSON.parse(result.user);
                        var insertTable = "";
                        for (var i = 0; i != user.length; ++i) {
                            insertTable += "
";
                            insertTable += ""+user[i].name+"	";
                            insertTable += ""+user[i].address+"	";
                            insertTable += ""+user[i].musictypes+"	";
                            insertTable += ""+user[i].role+"	";
                            insertTable += "
";
                        }
                        var filledTable = document.getElementById("insert");
                        filledTable.innerHTML = insertTable;
                        table.show();
                    }
                }
            });
        }
    });

    $("#role-all-btn").click(function () {

        var role = $("#Role_field");
        if (role != '') {
            $.ajax({
                url: "json",
                method: "get",
                datatype: 'json',
                data: {
                    'address': '',
                    'music': '',
                    'role': '',
                    'roleAll': 'role'
                },
                complete: function (data) {
                    var result = JSON.parse(data.responseText);
                    if(result.user != ''){
                        var user =  JSON.parse(result.user);
                        var insertTable = "";
                        for (var i = 0; i != user.length; ++i) {
                            insertTable += "
";
                            insertTable += ""+user[i].name+"	";
                            insertTable += ""+user[i].address+"	";
                            insertTable += ""+user[i].musictypes+"	";
                            insertTable += ""+user[i].role+"	";
                            insertTable += "
";
                        }
                        var filledTable = document.getElementById("insert");
                        filledTable.innerHTML = insertTable;
                        table.show();
                    }
                }
            });
        }
    });

});


text:
package geom

type PathElementType int

const (
	MoveTo PathElementType = iota
	LineTo
	QuadCurveTo
	CubicCurveTo
	ClosePath
)

type PathElement struct {
	Type   PathElementType
	Points [3]Point
}

type Path struct {
	Elements []PathElement
}

type Shape interface {
	Path() Path
}

func MakePath(cap int) Path {
	return Path{
		Elements: make([]PathElement, 0, cap),
	}
}

func AppendPath(path Path, other Path) Path {
	return Path{Elements: append(path.Elements, other.Elements...)}
}

func AppendRect(path Path, rect Rect) Path {
	x0 := rect.X
	y0 := rect.Y
	x1 := rect.X + rect.W
	y1 := rect.Y + rect.H
	return AppendPolygon(path, Point{x0, y0}, Point{x1, y0}, Point{x1, y1}, Point{x0, y1})
}

func AppendPolygon(path Path, points ...Point) Path {
	if len(points) != 0 {
		path.MoveTo(points[0])

		for _, p := range points[1:] {
			path.LineTo(p)
		}

		path.Close()
	}

	return path
}

func (self *Path) MoveTo(p Point) {
	self.append(PathElement{
		Type:   MoveTo,
		Points: [...]Point{p, {}, {}},
	})
}

func (self *Path) LineTo(p Point) {
	self.ensureStartWithMoveTo()
	self.append(PathElement{
		Type:   LineTo,
		Points: [...]Point{p, {}, {}},
	})
}

func (self *Path) QuadCurveTo(c Point, p Point) {
	self.ensureStartWithMoveTo()
	self.append(PathElement{
		Type:   QuadCurveTo,
		Points: [...]Point{c, p, {}},
	})
}

func (self *Path) CubicCurveTo(c1 Point, c2 Point, p Point) {
	self.ensureStartWithMoveTo()
	self.append(PathElement{
		Type:   CubicCurveTo,
		Points: [...]Point{c1, c2, p},
	})
}

func (self *Path) Close() {
	self.append(PathElement{
		Type: ClosePath,
	})
}

func (self *Path) Clear() {
	self.Elements = self.Elements[:0]
}

func (self *Path) Copy() Path {
	if self.Empty() {
		return Path{}
	}

	p := Path{
		Elements: make([]PathElement, len(self.Elements)),
	}

	copy(p.Elements, self.Elements)
	return p
}

func (self *Path) LastPoint() Point {
	return self.lastPointAt(len(self.Elements) - 1)
}

func (self *Path) lastPointAt(n int) Point {
	if n < 0 {
		return Point{}
	}

	switch e := self.Elements[n-1]; e.Type {
	case MoveTo, LineTo:
		return e.Points[0]

	case QuadCurveTo:
		return e.Points[1]

	case CubicCurveTo:
		return e.Points[2]

	default:
		return self.lastPointAt(n - 1)
	}
}

func (self *Path) Empty() bool {
	return len(self.Elements) == 0
}

func (self Path) Path() Path {
	return self.Copy()
}

func (self *Path) append(e PathElement) {
	self.Elements = append(self.Elements, e)
}

func (self *Path) ensureStartWithMoveTo() {
	if n := len(self.Elements); n == 0 {
		// Empty paths must start with a MoveTo element.
		self.MoveTo(Point{})

	} else if self.Elements[n-1].Type == ClosePath {
		// When a subpath is closed the path that contains more elements must
		// be restarted with a MoveTo as well.
		self.MoveTo(self.LastPoint())
	}
}


text:
namespace IdentityServer3.Postgres
{
    using System.IO;

    using IdentityServer3.Postgres.Converters;

    using Newtonsoft.Json;

    public static class JsonSerializerFactory
    {
        public static JsonSerializer Create()
        {
            var serializer = new JsonSerializer()
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Objects,
            };

            serializer.Converters.Add(new ClaimConverter());

            return serializer;
        }
    }

    internal static class JsonSerializerExtensions
    {
        public static string Serialize(this JsonSerializer serializer, object value)
        {
            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, value);

                writer.Flush();

                return writer.ToString();
            }
        }

        public static T Deserialize<T>(this JsonSerializer serializer, string value)
        {
            using (var reader = new JsonTextReader(new StringReader(value)))
            {
                return serializer.Deserialize<T>(reader);
            }
        }
    }
}


text:
MKL (Math Kernel Library) is an optimised implementation of BLAS.
It is available on the CECI clusters and can be freely downloaded for your own machine.

## Your machine (Windows/Linux)

  * go to [Intel Performance Libraries](https://software.intel.com/en-us/performance-libraries)
  * register for free and download "Intel Math Kernel Libraries" (you don't need the other sets of libraries)

![Install Intel MKL](intel_mkl_install.png)

  * install (e.g. Linux)
```
tar xvzf l_mkl_2017.3.196.tgz
cd l_mkl_2017.3.196
./install_GUI.sh
```
  * once installed, the libraries can "added" to the environment (see `PATH`, `LIB`, `INCLUDE`, `MKLROOT`, etc.) with this line (Linux):
```
. /opt/intel/mkl/bin/mklvars.sh intel64
```
or (Windows):
```
call "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries\windows\mkl\bin\mklvars.bat" intel64 vs2015
```

## CECI clusters

In the CECI clusters, use the following module:
```
module load intel/mkl/64/11.1/2013_sp1.3.174
```


text:
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Net;
using System.Net;

namespace NetduinoFeeder
{
    class StaticEthernetNetwork
    {
        Microsoft.SPOT.Net.NetworkInformation.NetworkInterface _ethernet = null;

        public StaticEthernetNetwork(string ipaddress, string netmask, string gateway)
        {
            _ethernet = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];
            if (_ethernet == null)
                throw new NullReferenceException();

            _ethernet.EnableStaticIP(ipaddress, netmask, gateway);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Mollisia urticae E.K. Cash

### Remarks
null


text:
import sys
from typing import Any, Callable, Dict, List, Optional, TypeVar

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat

from .. import models as _models
from .._serialization import Serializer
from .._vendor import _convert_request, _format_url_section

if sys.version_info >= (3, 8):
    from typing import Literal  # pylint: disable=no-name-in-module, ungrouped-imports
else:
    from typing_extensions import Literal  # type: ignore  # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False

def build_list_request(
    resource_group_name: str, workspace_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: Literal["2022-04-01-preview"] = kwargs.pop(
        "api_version", _params.pop("api-version", "2022-04-01-preview")
    )
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/outboundNetworkDependenciesEndpoints",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1, pattern=r"^[-\w\._\(\)]+$"
        ),
        "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str", max_length=64, min_length=3),
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
    }

    _url: str = _format_url_section(_url, **path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)

class OutboundNetworkDependenciesEndpointsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.databricks.AzureDatabricksManagementClient`'s
        :attr:`outbound_network_dependencies_endpoints` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs):
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self, resource_group_name: str, workspace_name: str, **kwargs: Any
    ) -> List[_models.OutboundEnvironmentEndpoint]:
        """Gets a list of egress endpoints (network endpoints of all outbound dependencies) in the
        specified Workspace.

        Gets the list of endpoints that VNET Injected Workspace calls Azure Databricks Control Plane.
        You must configure outbound access with these endpoints. For more information, see
        https://docs.microsoft.com/en-us/azure/databricks/administration-guide/cloud-configurations/azure/udr.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Required.
        :type workspace_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: list of OutboundEnvironmentEndpoint or the result of cls(response)
        :rtype: list[~azure.mgmt.databricks.models.OutboundEnvironmentEndpoint]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: Literal["2022-04-01-preview"] = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )
        cls: ClsType[List[_models.OutboundEnvironmentEndpoint]] = kwargs.pop("cls", None)

        request = build_list_request(
            resource_group_name=resource_group_name,
            workspace_name=workspace_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self.list.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize("[OutboundEnvironmentEndpoint]", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    list.metadata = {
        "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/outboundNetworkDependenciesEndpoints"
    }