text:
from docker import Client as DockerClient
import os
import uuid
from io import BytesIO
import tarfile

class container(object):
    def __init__(self, image,
                 name=None,
                 cwd=None,
                 remove=True,
                 docker_cli=None,
                 docker_sock='unix://var/run/docker.sock', **kwargs):

        self.image = image

        if not name:
            name = 'seasalt_created_' + str(uuid.uuid4())
        self.name = name

        if not cwd:
            cwd = os.getcwd()
        self.cwd = cwd

        self.remove = remove

        if not docker_cli:
            docker_cli = DockerClient(base_url=docker_sock)
        self.docker = docker_cli

        self.in_cn_seasalt_path = '/srv/seasalt'

        volumes = [
            '/srv/salt',
            '/srv/pillar',
            self.in_cn_seasalt_path
        ]

        salt_path = os.path.abspath(os.path.join(cwd, 'salt'))
        pillar_path = os.path.abspath(os.path.join(cwd, 'pillar'))
        tests_path = os.path.abspath(os.path.join(cwd, 'tests'))

        host_config = self.docker.create_host_config(binds=[
            '{}:/srv/salt:ro'.format(salt_path),
            '{}:/srv/pillar:ro'.format(pillar_path),
            '{}:{}:rw'.format(tests_path, self.in_cn_seasalt_path)
        ], network_mode='bridge')
        self.id = self.docker.create_container(image=self.image,
                                               volumes=volumes,
                                               host_config=host_config,
                                               name=name)['Id']

        self.docker.start(self.id)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.remove:
            self.docker.remove_container(container=self.id, v=True, force=True)
        else:
            self.docker.stop(container=self.id)

    def close(self):
        self.__exit__(None, None, None)

    def cp(self, src, dest=None):
        if not dest:
            dest = self.in_cn_seasalt_path

        src = os.path.abspath(src)
        arcname = os.path.basename(src.rstrip('/'))

        with BytesIO() as c:
            with tarfile.open(mode='w', fileobj=c) as t:
                t.add(src, arcname=arcname)
            data = c.getvalue()

        self.docker.put_archive(self.id, path=dest, data=data)

    def exec(self, cmd):
        ret = {
            'cmd': cmd,
            'exit_code': None,
            'result': None
        }

        exec_id = self.docker.exec_create(container=self.id, cmd=cmd)['Id']
        ret['result'] = self.docker.exec_start(exec_id=exec_id).decode()
        exec_inspect = self.docker.exec_inspect(exec_id)
        ret['exit_code'] = exec_inspect['ExitCode']

        return ret


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using System.Threading.Tasks;
using System.Windows;
using ArcGIS.Core.CIM;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Mapping.Events;

namespace ConstructMarkerFromFont
{
  /// <summary>
  /// This sample demonstrate how to create a CIMMarker from a font file and use it to render a point feature layer.
  /// The marker is then added to a personal style item in the current project.
  /// </summary>
  /// <remarks>
  /// 1. In Visual Studio click the Build menu. Then select Build Solution.
  /// 1. This solution is using the **Extended.Wpf.Toolkit Nuget**.  If needed, you can install the Nuget from the "Nuget Package Manager Console" by using this script: "Install-Package Extended.Wpf.Toolkit".
  /// 1. Click Start button to open ArcGIS Pro.
  /// 1. ArcGIS Pro will open.
  /// 1. Open any project file that contains a point feature layer.
  /// 1. Right click on the point feature layer to bring up the context menu.
  /// 1. Select the "Construct Marker from Fonts" menu item.
  /// 1. This will open the "Construct Marker from Fonts" dockpane.
  /// 1. Select a font, style and size and click Apply to render the point feature layer with the selected character.
  /// 1. If you check the "Add selected marker to a personal FontMarker style" option, the selected marker will be added to a FontMarker style in the project.
  /// ![UI](ScreenShots/ConstructMarkerFromFonts.png)
  /// </remarks>
  internal class Module1 : Module
  {
    private static Module1 _this = null;
    private const string StateId = "construct_marker_singlePointFeatureLayerSelectedState";

    /// <summary>
    /// Retrieve the singleton instance to this module here
    /// </summary>
    public static Module1 Current
    {
      get
      {
        return _this ?? (_this = (Module1)FrameworkApplication.FindModule("ConstructMarkerFromFont_Module"));
      }
    }

    /// <summary>
    /// Called by Framework whenever this Module is loaded.
    /// </summary>
    /// <returns></returns>
    protected override bool Initialize()
    {
      //Subscribe to the TOC selection changed event to find out if a Point feature layer is selected.
      //This will activate the context menu item to open the "Construct Marker from Fonts" dockpane.
      TOCSelectionChangedEvent.Subscribe((args) =>
      {
        if (args.MapView == null) return;
        Construct_MarkerViewModel vm = FrameworkApplication.DockPaneManager.Find("ConstructMarkerFromFont_Construct_Marker") as Construct_MarkerViewModel;
        if (GetSelectedPointLayers(args.MapView).Count() == 1)
        {
                //activate state
                FrameworkApplication.State.Activate(StateId); //Activates the custom state when the context is set.

                if (vm != null)
          {
            vm.DockpaneVisible = Visibility.Visible;
            vm.GetSelectedPointFeatureLayer();
          }

        }
        else
        {
          FrameworkApplication.State.Deactivate(StateId);
          if (vm != null)
            vm.DockpaneVisible = Visibility.Collapsed;
        }
      });
      return base.Initialize();
    }

    private IEnumerable<FeatureLayer> GetSelectedPointLayers(MapView mapview)
    {
      var layers =
          mapview.GetSelectedLayers()
              .OfType<FeatureLayer>()
              .Where(fl => fl.ShapeType == esriGeometryType.esriGeometryPoint);
      return layers;
    }

    #region Overrides
    /// <summary>
    /// Called by Framework when ArcGIS Pro is closing
    /// </summary>
    /// <returns>False to prevent Pro from closing, otherwise True</returns>
    protected override bool CanUnload()
    {
      //TODO - add your business logic
      //return false to ~cancel~ Application close
      return true;
    }

    #endregion Overrides

  }
}

redpajama_set_name: RedPajamaGithub


text:
Rails.application.routes.draw do

  mount Docomo::Engine => "/docomo"

end


text:
using System.Runtime.InteropServices;
using Xunit;

namespace System.IO.Tests
{
    public class File_GetSetAttributes : FileSystemTest
    {
        #region Utilities

        protected virtual FileAttributes Get(string path)
        {
            return File.GetAttributes(path);
        }

        protected virtual void Set(string path, FileAttributes attributes)
        {
            File.SetAttributes(path, attributes);
        }

        #endregion

        [Fact]
        public void NullParameters()
        {
            Assert.Throws<ArgumentNullException>(() => Get(null));
            Assert.Throws<ArgumentNullException>(() => Set(null, FileAttributes.Normal));
        }

        [Fact]
        public void InvalidParameters()
        {
            Assert.Throws<ArgumentException>(() => Get(string.Empty));
            Assert.Throws<ArgumentException>(() => Set(string.Empty, FileAttributes.Normal));
        }

        [Fact]
        public void NonExistentFile()
        {
            Assert.Throws<FileNotFoundException>(() => Set(GetTestFilePath(), FileAttributes.Normal));
        }

        [Theory]
        [InlineData(FileAttributes.ReadOnly)]
        [InlineData(FileAttributes.Normal)]
        [PlatformSpecific(PlatformID.AnyUnix)]
        public void UnixAttributeSetting(FileAttributes attr)
        {
            var path = GetTestFilePath();
            File.Create(path).Dispose();
            Set(path, attr);
            Assert.Equal(attr, Get(path));
            Set(path, 0);
        }

        [Theory]
        [InlineData(FileAttributes.ReadOnly)]
        [InlineData(FileAttributes.Hidden)]
        [InlineData(FileAttributes.System)]
        [InlineData(FileAttributes.Archive)]
        [InlineData(FileAttributes.Normal)]
        [InlineData(FileAttributes.Temporary)]
        [InlineData(FileAttributes.ReadOnly | FileAttributes.Hidden)]
        [PlatformSpecific(PlatformID.Windows)]
        public void WindowsAttributeSetting(FileAttributes attr)
        {
            var path = GetTestFilePath();
            File.Create(path).Dispose();
            Set(path, attr);
            Assert.Equal(attr, Get(path));
            Set(path, 0);
        }

        [Theory]
        [InlineData(FileAttributes.SparseFile)]
        [InlineData(FileAttributes.Temporary)]
        [InlineData(FileAttributes.ReparsePoint)]
        [InlineData(FileAttributes.Compressed)]
        [InlineData(FileAttributes.Encrypted)]
        [PlatformSpecific(PlatformID.AnyUnix)]
        public void UnixInvalidAttributes(FileAttributes attr)
        {
            var path = GetTestFilePath();
            File.Create(path).Dispose();
            Set(path, attr);
            Assert.Equal(FileAttributes.Normal, Get(path));
        }

        [Theory]
        [InlineData(FileAttributes.Normal)]
        [InlineData(FileAttributes.Encrypted)]
        [InlineData(FileAttributes.SparseFile)]
        [InlineData(FileAttributes.ReparsePoint)]
        [InlineData(FileAttributes.Compressed)]
        [PlatformSpecific(PlatformID.Windows)]
        public void WindowsInvalidAttributes(FileAttributes attr)
        {
            var path = GetTestFilePath();
            File.Create(path).Dispose();
            Set(path, attr);
            Assert.Equal(FileAttributes.Normal, Get(path));
        }

        // In some cases (such as when running without elevated privileges,
        // the symbolic link may fail to create. Only run this test if it creates
        // links successfully.
        [ConditionalFact(nameof(CanCreateSymbolicLinks))]
        public void SymLinksAreReparsePoints()
        {
            var path = GetTestFilePath();
            var linkPath = GetTestFilePath();
            File.Create(path).Dispose();
            Assert.True(MountHelper.CreateSymbolicLink(linkPath, path));
            Assert.Equal(FileAttributes.ReparsePoint, FileAttributes.ReparsePoint & Get(linkPath));
        }

        // In some cases (such as when running without elevated privileges,
        // the symbolic link may fail to create. Only run this test if it creates
        // links successfully.
        [ConditionalFact(nameof(CanCreateSymbolicLinks))]
        public void SymLinksReflectTargetAttributes()
        {
            var path = GetTestFilePath();
            var linkPath = GetTestFilePath();
            File.Create(path).Dispose();
            Assert.True(MountHelper.CreateSymbolicLink(linkPath, path));

            Set(path, FileAttributes.ReadOnly);

            Assert.Equal(FileAttributes.ReadOnly, Get(path));

            // Can't assume that ReparsePoint is the only attribute because Windows will add Archive automatically
            // Instead, make sure that ReparsePoint is present.
            Assert.Equal(FileAttributes.ReparsePoint, FileAttributes.ReparsePoint & Get(linkPath));

            // Then for ReadOnly, there is a difference between Windows and Unix.  Given the prevalence of symlinks
            // on Unix, matching the existing Windows behavior doesn't make as much sense, so we still follow
            // to the target object.  As such, on Windows ReadOnly should not be set, but it should be set elsewhere.
            Assert.Equal(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? (FileAttributes)0 : FileAttributes.ReadOnly,
                FileAttributes.ReadOnly & Get(linkPath));
        }
    }
}


text:
<?php

/* @Framework/Form/range_widget.html.php */
class __TwigTemplate_892f65683e9c6d385027964fbad853171542b17309296a9287e35e803131f8ea extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_8b052a80a4c43a21dcf10263c0735b5157e70d051f4031bcd760aef353a85260 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_8b052a80a4c43a21dcf10263c0735b5157e70d051f4031bcd760aef353a85260->enter($__internal_8b052a80a4c43a21dcf10263c0735b5157e70d051f4031bcd760aef353a85260_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Framework/Form/range_widget.html.php"));

        // line 1
        echo "<?php echo \$view['form']->block(\$form, 'form_widget_simple', array('type' => isset(\$type) ? \$type : 'range'));
";

        $__internal_8b052a80a4c43a21dcf10263c0735b5157e70d051f4031bcd760aef353a85260->leave($__internal_8b052a80a4c43a21dcf10263c0735b5157e70d051f4031bcd760aef353a85260_prof);

    }

    public function getTemplateName()
    {
        return "@Framework/Form/range_widget.html.php";
    }

    public function getDebugInfo()
    {
        return array (  22 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("<?php echo \$view['form']->block(\$form, 'form_widget_simple', array('type' => isset(\$type) ? \$type : 'range'));
", "@Framework/Form/range_widget.html.php", "/home/michelk9/public_html/myBackEnd/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/range_widget.html.php");
    }
}


text:
FROM ubuntu:10.04
MAINTAINER Guillaume Claret

RUN apt-get update && apt-get upgrade -y
RUN apt-get install -y camlp4-extra
RUN apt-get install -y mpi libopenmpi-dev
RUN apt-get install -y curl make

WORKDIR /root
RUN curl -L http://traclifo.univ-orleans.fr/BSML/raw-attachment/wiki/WikiStart/bsml-0.5.tar.gz |tar -xz
WORKDIR bsml-0.5
RUN ./configure && make && make install


text:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = patterns('',
    # Admin panel
    url(r'^admin/', include(admin.site.urls)),

    # Login URLs
    url(r'^accounts/login/$', 'django.contrib.auth.views.login',
        {'template_name': 'login.html'}),
    url(r'^accounts/logout/$', 'django.contrib.auth.views.logout',
        {'template_name': 'logout.html'}),

    # API
    url('^api/', include('oauth.api.urls')),

    # OAuth
    url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


text:
<?php
/**
 * @property String Id
 * @property String ContactId
 * @property String AffiliateId
 * @property String DateSet
 * @property String DateExpires
 * @property String IPAddress
 * @property String Source
 * @property String Info
 * @property String Type
 */
class Infusionsoft_Generated_Referral extends Infusionsoft_Generated_Base{
    protected static $tableFields = array('Id', 'ContactId', 'AffiliateId', 'DateSet', 'DateExpires', 'IPAddress', 'Source', 'Info', 'Type');

    public function __construct($id = null, $app = null){
    	parent::__construct('Referral', $id, $app);
    }

    public function getFields(){
		return self::$tableFields;
	}

	public function addCustomField($name){
		self::$tableFields[] = $name;
	}

    public function removeField($fieldName){
        $fieldIndex = array_search($fieldName, self::$tableFields);
        if($fieldIndex !== false){
            unset(self::$tableFields[$fieldIndex]);
            self::$tableFields = array_values(self::$tableFields);
        }
    }
}


text:
class TimezoneSerializer < ActiveModel::Serializer
  attributes :id, :name, :offset
end


text:
package org.joshy.gfx.css;

import org.joshy.gfx.draw.Font;
import org.joshy.gfx.node.Insets;

public class StyleInfo {
    public Insets margin;
    public Insets borderWidth;
    public Insets padding;
    public double contentBaseline;
    public Font font;
    public CSSMatcher matcher;

    public Insets calcContentInsets() {
        return new Insets(margin,borderWidth,padding);
    }
}


text:
#pragma once

#include <qrutils/graphicsUtils/lineImpl.h>

#include "solidItem.h"

namespace twoDModel {
namespace items {

class WallItem : public SolidItem
{
	Q_OBJECT

public:
	WallItem(const QPointF &begin, const QPointF &end);

	/// Creates a copy of this wall item. Transfers ownership to the caller.
	WallItem *clone() const;

	/// Creates and returns wall item for 2D model palette.
	/// Transfers ownership.
	static QAction *wallTool();

	QPainterPath shape() const override;
	QRectF boundingRect() const override;

	QPointF begin() const;
	QPointF end() const;
	bool isDragged() const;
	qreal width() const;

	/// Draws selection rect around sensorBoundingBox
	void drawExtractionForItem(QPainter *painter) override;
	void drawItem(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;

	void resizeItem(QGraphicsSceneMouseEvent *event) override;
	void reshapeRectWithShift() override;

	void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
	void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
	void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;

	void serialize(QDomElement &element) const override;
	void deserialize(const QDomElement &element) override;

	void onOverlappedWithRobot(bool overlapped = true);

	QPainterPath path() const;

	void resizeWithGrid(QGraphicsSceneMouseEvent *event, int indexGrid);

	void resizeBeginWithGrid(int indexGrid);
	void reshapeEndWithGrid(int indexGrid);
	void reshapeBeginWithGrid(int indexGrid);
	void setDraggedEnd(qreal x, qreal y);
	void alignTheWall(int indexGrid);

signals:
	void wallDragged(WallItem *item, const QPainterPath &shape, const QRectF &oldPos);

protected:
	void setPrivateData();

private:
	void recalculateBorders();

	qreal alignedCoordinate(qreal coord, int coef, const int indexGrid) const;
	void setBeginCoordinatesWithGrid(int indexGrid);
	void setEndCoordinatesWithGrid(int indexGrid);
	void countCellNumbCoordinates(int indexGrid);

	graphicsUtils::LineImpl mLineImpl;

	bool mDragged = false;
	bool mOverlappedWithRobot = false;
	const QImage mImage;

	int mOldX1 = 0;
	int mOldY1 = 0;
	int mCellNumbX1 = 0;
	int mCellNumbY1 = 0;
	int mCellNumbX2 = 0;
	int mCellNumbY2 = 0;

	QPainterPath mPath;
};

}
}


text:
"""
ROS node which converts joel world model, osl_world_model, AcousticModemData
msgs into the ones used for the Evologics modem driver
Author: Gordon Frost; email: gwf2@hw.ac.uk
date: 05/02/2015
"""
# TODO: Add Radio Modem switch in here when vehicles known to be on surface

import roslib;roslib.load_manifest("evologics_driver")
import rospy

from vehicle_interface.msg import AcousticModemData
from vehicle_interface.msg import AcousticModemPayload

global wm_incoming_pub, evologics_pub

def wmOutgoingMsg(msg):
    """ method must convert from AcousticModemData uint8[]]
    to AcousticModemPayload string
    """
    global evologics_pub
    rospy.loginfo("WM outgoing msg being converted and sent to Evologics driver")

    uint8_payload = msg.payload
    converted_payload = str(uint8_payload)

    # populate new msg and send to evologics modem driver
    converted_msg = AcousticModemPayload()
    converted_msg.address = 5
    converted_msg.payload = converted_payload
    evologics_pub.publish(converted_msg)

def wmIncomingMsg(msg):
    """ method must convert from AcousticModemPayload string to
    AcousticModemData uint8
    """
    global wm_incoming_pub
    rospy.loginfo("Msg received from Evologics driver, sending to WM")
    string_payload = msg.payload
    converted_payload = list(bytearray(string_payload))

    # populate new msg and send to world model
    converted_msg = AcousticModemData()
    converted_msg.payload = converted_payload
    wm_incoming_pub.publish(converted_msg)

if __name__ == '__main__':
    rospy.init_node("world_model_msg_translator")
    global wm_incoming_pub, evologics_pub
    # Topics for World model sending message to Evologics modem for transmission
    wm_outgoing_sub = rospy.Subscriber("/modem/outgoing", AcousticModemData, wmOutgoingMsg)
    evologics_pub    = rospy.Publisher("/modem/burst/out", AcousticModemPayload)

    # Topics for incoming acoustic msgs being sent on to the World Model
    wm_incoming_pub    = rospy.Publisher("/modem/incoming", AcousticModemData)
    evologics_sub    = rospy.Subscriber("/modem/burst/in", AcousticModemPayload, wmIncomingMsg)

    rospy.spin()


text:
NewSpring Staff Roku App
------------------------

This is a single screen live streaming app for Roku. I created it because
clicking through 5 different menu screens is unnecessary and inefficient.

Setup
-----

Make sure you put your roku in [dev mode](http://sdkdocs.roku.com/display/sdkdoc/Developer+Guide#DeveloperGuide-71EnablingDevelopmentModeonyourbox). Compiling the app is as simple as running `make` from the `apps/source/staff` directory. Install or Replace your app on your Roku box to test. You can telnet into the box and see any debugging output that might have been printed if your app didn't run as expected.

You can also read Roku's extensive documentation at http://sdkdocs.roku.com/

Notes
-----

Parts of this app use code from the `simplevideoplayer` app listed in the
documentation above. I noted in the `appMain.brs` file where this happened.

License
-------

See [LICENSE](https://github.com/NewSpring/Staff-Roku/blob/master/LICENSE)


text:
import React from 'react'
import _ from 'lodash'

import { ModelNodeWidget } from '../BaseNodeWidget'

export const TYPE='distributionNetwork';

export class DistributionNetworkWidget extends ModelNodeWidget {

  getClassName(node) { return 'a-node model_p distributionNetwork'; }
}


text:
//
//  FindPasd+Event.m
//  LoginDemo
//
//  Created by lichq on 6/25/15.
//  Copyright (c) 2015 ciyouzen. All rights reserved.
//

#import "FindPasd+Event.h"
#import "NSString+Validate.h"
#import "NSString+Attributed.h"

@implementation FindPasd (Event)

#pragma mark - 返回
- (IBAction)goBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 找回密码
- (IBAction)tryFindPasd:(id)sender{
    [self.tfEmail resignFirstResponder];

    if ([self.tfEmail.text validateEmail]) {
        [self doFindPasd];
    }else{
        [[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"提示", nil)
                                   message:NSLocalizedString(@"邮箱输入错误", nil)
                                  delegate:self
                         cancelButtonTitle:NSLocalizedString(@"好的,我知道了", nil)
                         otherButtonTitles:nil] show];
    }
}

- (void)doFindPasd{
    [self.view endEditing:YES];

    HUD = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    HUD.delegate = self;
    HUD.labelText = NSLocalizedString(@"正在发送", nil);

    NSString *Url = API_BASE_Url_Health(@"user/request_new_password");
    NSDictionary *params = @{@"name": self.tfEmail.text};

    AFHTTPSessionManager *manager = [HealthyHTTPSessionManager sharedInstance];
    [[CJNetworkClient sharedInstance] useManager:manager postRequestUrl:Url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        HUD.mode = MBProgressHUDModeText;
        HUD.labelText = NSLocalizedString(@"邮件发送成功", nil);
        [HUD hide:YES afterDelay:1];

        NSString *string1 = NSLocalizedString(@"我们已将重置密码的邮件发送至您的账户邮箱:\n", nil);
        NSString *string3 = NSLocalizedString(@"\n请访问邮件内的地址进行重置", nil);
        NSString *mesg = [NSString stringWithFormat:@"%@%@%@", string1, self.tfEmail.text, string3];
        NSAttributedString *attributedString = [mesg attributedSubString:self.tfEmail.text font:[UIFont systemFontOfSize:21.0] color:[UIColor blackColor] udline:YES];

        NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:@"PopupFindPasd" owner:self options:nil];
        CommonPPMessageShow *customView = [bundle lastObject];
        customView.delegate = self;
        customView.lab.attributedText = attributedString;
        customView.layer.cornerRadius = 30;
        [customView cj_popupInWindowAtPosition:CJWindowPositionCenter
                                 animationType:CJAnimationTypeNormal
                                  showComplete:nil
                              tapBlankComplete:nil];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSString * _Nullable errorMessage) {
        HUD.mode = MBProgressHUDModeText;
        HUD.labelText = NSLocalizedString(@"邮件发送失败", nil);
        [HUD hide:YES afterDelay:1];
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.tfEmail becomeFirstResponder];
}

#pragma mark -
/////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder];
    return YES;

    //按Return进行换行功能
    /*
    [textField resignFirstResponder];
    [self tryFindPasd:NULL];
    return YES;
    */
}

- (void)goOK_CommonPPMessageShow:(CommonPPMessageShow *)commonPPMessageShow {
    [commonPPMessageShow cj_hidePopupViewWithAnimationType:CJAnimationTypeNone];
    [self.navigationController popViewControllerAnimated:YES];
}

@end


text:
#window1 { top:6em;left:15%; }
#window2 { top:6em; right:25%; }
#window3 { top:30em; left:15%; }
#window4 { top:30em; right:25%}
.window {
    border:1px dotted gray;
    width:9.7em;
    height:8em;
    position:absolute;
    color:gray;
    font-family:serif;
    font-style:italic;
    padding-top:0.9em;
    font-size:0.9em;

}
.demo { position:relative; }
.drag-locked { border:1px solid red; }

.dragActive { border:2px dotted orange; }
.dropHover { border:1px dotted red; }

/*
._jsPlumb_endpoint._jsPlumb_dragging { border:2px solid green; }
._jsPlumb_endpoint_full { border:3px solid #606; }
._jsPlumb_endpoint_connected { border:4px solid black; }
._jsPlumb_endpoint_drop_allowed { border:5px solid #935; }
._jsPlumb_endpoint_drop_forbidden { border:5px solid #539; }
*/

.cmdLink { font-size:0.80em;}
#clear { padding:0.3em; }
#clear:hover { background-color:yellow; }
#list {
    text-align:center;
    display:none;
    font-size:90%;
    position:absolute;
    width:250px;
    left:30%;
    top:100px;
    background-color:white;
    padding:5px;
    border:1px solid #456;
    opacity:0.8;
}
#list table { width:100%; text-align:left;}
#explanation { text-align:center; }


text:
package org.apereo.cas.configuration.model.support.couchdb;

import org.apereo.cas.configuration.support.RequiresModule;

import lombok.Getter;
import lombok.Setter;

/**
 * This is {@link CouchDbServiceRegistryProperties}.
 *
 * @author Timur Duehr
 * @since 5.3.0
 */
@RequiresModule(name = "cas-server-support-couchdb-service-registry")
@Getter
@Setter
public class CouchDbServiceRegistryProperties extends AbstractCouchDbProperties {
    private static final long serialVersionUID = -5101551655756163621L;

    public CouchDbServiceRegistryProperties() {
        this.setDbName("serviceRegistry");
    }
}


text:
This document describes the steps taken to investigate a real memory leak
discovered by heap profiling in the wild. For investigators less familiar with
the code base, `Navigating the Stack Trace` should be enough information to
determine the relevant component, and to forward the bug to a component OWNER.

## Understanding the heap dump summary

The opening comment of [Issue
834033](https://bugs.chromium.org/p/chromium/issues/detail?id=834033) contains a
heap dump summary. The highlights are:

* 315723 calls to malloc without corresponding call to free.
* 806MB of memory.
* The common stacktrace for all 315723 allocations.

Usually, anything that uses over 10MB of memory is a red flag. With the
exception of large image resources, most code in Chrome should use much less
than 10MB. Anything that has over 100k allocations is also a red flag.

### Navigating the Stack Trace - Detailed Breakdown

Let's take a look at the stack trace:

```
profiling::(anonymous namespace)::HookAlloc(base::allocator::AllocatorDispatch const*, unsigned long, void*)
base::allocator::MallocZoneFunctionsToReplaceDefault()::$_1::__invoke(_malloc_zone_t*, unsigned long)
<???>
<???>
base::allocator::UncheckedMallocMac(unsigned long, void**)
sk_malloc_flags(unsigned long, unsigned int)
SkMallocPixelRef::MakeAllocate(SkImageInfo const&, unsigned long)
SkBitmap::tryAllocPixels(SkImageInfo const&, unsigned long)
IPC::ParamTraits<SkBitmap>::Read(base::Pickle const*, base::PickleIterator*, SkBitmap*)
ExtensionAction::ParseIconFromCanvasDictionary(base::DictionaryValue const&, gfx::ImageSkia*)
extensions::ExtensionActionSetIconFunction::RunExtensionAction()
extensions::ExtensionActionFunction::Run()
ExtensionFunction::RunWithValidation()
extensions::ExtensionFunctionDispatcher::DispatchWithCallbackInternal(ExtensionHostMsg_Request_Params const&, content::RenderFrameHost*, int, base::RepeatingCallback<void (ExtensionFunction::ResponseType, base::ListValue const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, extensions::functions::HistogramValue)> const&)
extensions::ExtensionFunctionDispatcher::Dispatch(ExtensionHostMsg_Request_Params const&, content::RenderFrameHost*, int)
bool IPC::MessageT<ExtensionHostMsg_Request_Meta, std::__1::tuple<ExtensionHostMsg_Request_Params>, void>::Dispatch<extensions::ExtensionWebContentsObserver, extensions::ExtensionWebContentsObserver, content::RenderFrameHost, void (extensions::ExtensionWebContentsObserver::*)(content::RenderFrameHost*, ExtensionHostMsg_Request_Params const&)>(IPC::Message const*, extensions::ExtensionWebContentsObserver*, extensions::ExtensionWebContentsObserver*, content::RenderFrameHost*, void (extensions::ExtensionWebContentsObserver::*)(content::RenderFrameHost*, ExtensionHostMsg_Request_Params const&))
extensions::ExtensionWebContentsObserver::OnMessageReceived(IPC::Message const&, content::RenderFrameHost*)
extensions::ChromeExtensionWebContentsObserver::OnMessageReceived(IPC::Message const&, content::RenderFrameHost*)
content::WebContentsImpl::OnMessageReceived(content::RenderFrameHostImpl*, IPC::Message const&)
content::RenderFrameHostImpl::OnMessageReceived(IPC::Message const&)
IPC::ChannelProxy::Context::OnDispatchMessage(IPC::Message const&)
base::debug::TaskAnnotator::RunTask(char const*, base::PendingTask*)
base::MessageLoop::RunTask(base::PendingTask*)
base::MessageLoop::DoWork()
base::MessagePumpCFRunLoopBase::RunWork()
base::mac::CallWithEHFrame(void () block_pointer)
base::MessagePumpCFRunLoopBase::RunWorkSource(void*)
<???>
<???>
<???>
<???>
<???>
<???>
<???>
<???>
<???>
__71-[BrowserCrApplication nextEventMatchingMask:untilDate:inMode:dequeue:]_block_invoke
base::mac::CallWithEHFrame(void () block_pointer)
-[BrowserCrApplication nextEventMatchingMask:untilDate:inMode:dequeue:]
<???>
base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*)
base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*)
<name omitted>
ChromeBrowserMainParts::MainMessageLoopRun(int*)
content::BrowserMainLoop::RunMainMessageLoopParts()
content::BrowserMainRunnerImpl::Run()
content::BrowserMain(content::MainFunctionParams)
content::ContentMainRunnerImpl::Run()
service_manager::Main(service_manager::MainParams const&)
content::ContentMain(content::ContentMainParams const&)
ChromeMain
main
<???>
```

The first step is to divide the stack trace into smaller segments to get a
better understanding of what's happening at the time of allocations. The best
way to do this is to segment by name space and/or function prefixes.

```
profiling::(anonymous namespace)::HookAlloc(base::allocator::AllocatorDispatch const*, unsigned long, void*)
base::allocator::MallocZoneFunctionsToReplaceDefault()::$_1::__invoke(_malloc_zone_t*, unsigned long)
<???>
<???>
base::allocator::UncheckedMallocMac(unsigned long, void**)
```

The top of each stack will always contain some `base` and/or `profiling`
code. This is the code responsible for allocating and recording the memory.

```
sk_malloc_flags(unsigned long, unsigned int)
SkMallocPixelRef::MakeAllocate(SkImageInfo const&, unsigned long)
SkBitmap::tryAllocPixels(SkImageInfo const&, unsigned long)
```

Next, we three 3 frames with the prefix `sk`. Searching for
`sk_malloc_flags` on
[codesearch](https://cs.chromium.org/search/?q=sk_malloc_flags&sq=package:chromium&type=cs)
reveals that the component is `third_party/skia`. Looking at the
[README](https://cs.chromium.org/chromium/src/third_party/skia/README) reveals
that Skia is a 2D graphics library.

```
IPC::ParamTraits<SkBitmap>::Read(base::Pickle const*, base::PickleIterator*, SkBitmap*)
```

Next we see a templated function called `Read` in the namespace `IPC`.
`IPC` stands for inter-process communication. This suggests that the
function is responsible for reading an IPC Message, perhaps concerning an
`SkBitmap`.

```
ExtensionAction::ParseIconFromCanvasDictionary(base::DictionaryValue const&, gfx::ImageSkia*)
extensions::ExtensionActionSetIconFunction::RunExtensionAction()
extensions::ExtensionActionFunction::Run()
ExtensionFunction::RunWithValidation()
extensions::ExtensionFunctionDispatcher::DispatchWithCallbackInternal(ExtensionHostMsg_Request_Params const&, content::RenderFrameHost*, int, base::RepeatingCallback<void (ExtensionFunction::ResponseType, base::ListValue const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, extensions::functions::HistogramValue)> const&)
extensions::ExtensionFunctionDispatcher::Dispatch(ExtensionHostMsg_Request_Params const&, content::RenderFrameHost*, int)
bool IPC::MessageT<ExtensionHostMsg_Request_Meta, std::__1::tuple<ExtensionHostMsg_Request_Params>, void>::Dispatch<extensions::ExtensionWebContentsObserver, extensions::ExtensionWebContentsObserver, content::RenderFrameHost, void (extensions::ExtensionWebContentsObserver::*)(content::RenderFrameHost*, ExtensionHostMsg_Request_Params const&)>(IPC::Message const*, extensions::ExtensionWebContentsObserver*, extensions::ExtensionWebContentsObserver*, content::RenderFrameHost*, void (extensions::ExtensionWebContentsObserver::*)(content::RenderFrameHost*, ExtensionHostMsg_Request_Params const&))
extensions::ExtensionWebContentsObserver::OnMessageReceived(IPC::Message const&, content::RenderFrameHost*)
extensions::ChromeExtensionWebContentsObserver::OnMessageReceived(IPC::Message const&, content::RenderFrameHost*)
```

Next, we see many frames with the `extension` prefix. Extensions are exactly
what they sound like - Chrome extensions like AdBlock are used to modify the
behavior of the browser.

```
content::WebContentsImpl::OnMessageReceived(content::RenderFrameHostImpl*, IPC::Message const&)
content::RenderFrameHostImpl::OnMessageReceived(IPC::Message const&)
```

`content` is the name of code that glues together web code [like extensions] and
the rest of Chrome.

```
IPC::ChannelProxy::Context::OnDispatchMessage(IPC::Message const&)
```

More `IPC` code.

```
base::debug::TaskAnnotator::RunTask(char const*, base::PendingTask*)
base::MessageLoop::RunTask(base::PendingTask*)
base::MessageLoop::DoWork()
base::MessagePumpCFRunLoopBase::RunWork()
base::mac::CallWithEHFrame(void () block_pointer)
base::MessagePumpCFRunLoopBase::RunWorkSource(void*)
```

More `base` code. The bottom of most stack traces should go back to
`MessageLoop`, a primitive Chrome construct used to run tasks.

### Navigating the Stack Trace - Summary

* The top and bottom of the stack should generally be the same and are not very
  interesting.
* The prefixes of frames can be used to get a rough idea of the components
  involved.
* Function names can be used to get a rough idea of what's going on.

In this case, extension code is calling `ParseIconFromCanvasDictionary` - so
it's probably trying to parse an icon. This calls into Skia code. Given that
Skia is a 2D drawing library, and the function is `tryAllocPixels`, Skia is
allocating some pixels for the icon. This process is being repeated 315 thousand
times, and the icon is being leaked every time.

## Diving into the code

Now that we have a rough idea of what's happening, let's look at the code for
ParseIconFromCanvasDictionary.

```cpp
bool ExtensionAction::ParseIconFromCanvasDictionary(
    const base::DictionaryValue& dict,
    gfx::ImageSkia* icon) {
  for (base::DictionaryValue::Iterator iter(dict); !iter.IsAtEnd();
       iter.Advance()) {
    std::string binary_string64;
    IPC::Message pickle;
    if (iter.value().is_blob()) {
      pickle = IPC::Message(iter.value().GetBlob().data(),
                            iter.value().GetBlob().size());
    } else if (iter.value().GetAsString(&binary_string64)) {
      std::string binary_string;
      if (!base::Base64Decode(binary_string64, &binary_string))
        return false;
      pickle = IPC::Message(binary_string.c_str(), binary_string.length());
    } else {
      continue;
    }
    base::PickleIterator pickle_iter(pickle);
    SkBitmap bitmap;
    if (!IPC::ReadParam(&pickle, &pickle_iter, &bitmap))
      return false;
    CHECK(!bitmap.isNull());

    // Chrome helpfully scales the provided icon(s), but let's not go overboard.
    const int kActionIconMaxSize = 10 * ActionIconSize();
    if (bitmap.drawsNothing() || bitmap.width() > kActionIconMaxSize)
      continue;

    float scale = static_cast<float>(bitmap.width()) / ActionIconSize();
    icon->AddRepresentation(gfx::ImageSkiaRep(bitmap, scale));
  }
  return true;
}
```

There's a lot going on here, but we can use the information we have to focus.
The leak happens in IPC::ReadParam, so the relevant lines are:

```
SkBitmap bitmap;
if (!IPC::ReadParam(&pickle, &pickle_iter, &bitmap))
  return false;
```

The `IPC` message is being decoded into `bitmap`.

```
 icon->AddRepresentation(gfx::ImageSkiaRep(bitmap, scale));
```
Looking at subsequent consumers of `bitmap`, we see that it is being added as a
representation to `icon`. `icon` is an output parameter of this function, so we
have to look at the calling frame,
`ExtensionActionSetIconFunction::RunExtensionAction`.

```
ExtensionFunction::ResponseAction
ExtensionActionSetIconFunction::RunExtensionAction() {
...
    EXTENSION_FUNCTION_VALIDATE(
        ExtensionAction::ParseIconFromCanvasDictionary(*canvas_set, &icon));

    if (icon.isNull())
      return RespondNow(Error("Icon invalid."));

    extension_action_->SetIcon(tab_id_, gfx::Image(icon));
...
}
```

In this case, I've already focused on the code that calls
`ParseIconFromCanvasDictionary`. Let's look at `SetIcon`.

```
void ExtensionAction::SetIcon(int tab_id, const gfx::Image& image) {
  SetValue(&icon_, tab_id, image);
}
```

```
template<class T>
void SetValue(std::map<int, T>* map, int tab_id, const T& val) {
  (*map)[tab_id] = val;
}
```

The icon is being added to a map `icon_`, with `tab_id` as the key. Ah ha!
Adding elements to a container [and never removing them] is one of the most
common sources of memory issues.

There are two ways for this memory to be released - the container `icon_` can be
destroyed, or the element can be removed from the container.

`icon_` is a member of `ExtensionAction`, whose documentation reads:
```
// ExtensionAction encapsulates the state of a browser action or page action.
// Instances can have both global and per-tab state. If a property does not have
// a per-tab value, the global value is used instead.
```

This suggests that the lifetime of `icon_` is tied to the lifetime of the
ExtensionAction, which we can guess is tied to the lifetime of the Extension. As
long as the extension stays installed and enabled, `icon_` will not be
destroyed.

Next, we use codesearch to look at all code that removes elements from `icon_`.
The only place that performs removal is

```
void ExtensionAction::ClearAllValuesForTab(int tab_id) {
...
  icon_.erase(tab_id);
...
}
```

This is called by `ExtensionActionAPI::ClearAllValuesForTab`, which is called by
`TabHelper::DidFinishNavigation`. The name of this method suggests that each
time a tab is navigated, the previous tab-specific icon is cleared. However,
that means that if a tab is closed, then the icon is leaked forever.


text:
from pandas import Categorical

class TestCategorical:
    def setup_method(self, method):
        self.factor = Categorical(
            ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True
        )


text:
<?xml version="1.0"?>
<PluginConfig>
	<Field id="topLabel" type="label" fontSize="small" fontColor="darkgray">
		Please provide the network location for your Heatmiser netmonitor (do not include the port). Please note this plugin does not need your username/password combination.  Ergo, I would advise against opening port 80 of your netmonitor to the outside world.
	</Field>
	<Field id="netmonitorLocation" type="textfield" defaultValue="192.168.0.1">
		Netmonitor Location:
	</Field>
</PluginConfig>


text:
package org.apache.http.impl.auth;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthOption;
import org.apache.http.auth.AuthProtocolState;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.ContextAwareAuthScheme;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.client.AuthCache;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Lookup;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.TargetAuthenticationStrategy;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

@SuppressWarnings({"boxing","static-access"})
public class TestHttpAuthenticator {

    private AuthenticationStrategy defltAuthStrategy;
    private AuthState authState;
    private ContextAwareAuthScheme authScheme;
    private HttpContext context;
    private HttpHost defaultHost;
    private Credentials credentials;
    private BasicCredentialsProvider credentialsProvider;
    private Lookup<AuthSchemeProvider> authSchemeRegistry;
    private AuthCache authCache;
    private HttpAuthenticator httpAuthenticator;

    @Before
    public void setUp() throws Exception {
        this.defltAuthStrategy = Mockito.mock(AuthenticationStrategy.class);
        this.authState = new AuthState();
        this.authScheme = Mockito.mock(ContextAwareAuthScheme.class);
        Mockito.when(this.authScheme.getSchemeName()).thenReturn("Basic");
        Mockito.when(this.authScheme.isComplete()).thenReturn(Boolean.TRUE);
        this.context = new BasicHttpContext();
        this.defaultHost = new HttpHost("localhost", 80);
        this.context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.defaultHost);
        this.credentials = Mockito.mock(Credentials.class);
        this.credentialsProvider = new BasicCredentialsProvider();
        this.credentialsProvider.setCredentials(AuthScope.ANY, this.credentials);
        this.context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider);
        this.authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register("basic", new BasicSchemeFactory())
            .register("digest", new DigestSchemeFactory())
            .register("ntlm", new NTLMSchemeFactory()).build();
        this.context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry);
        this.authCache = Mockito.mock(AuthCache.class);
        this.context.setAttribute(HttpClientContext.AUTH_CACHE, this.authCache);
        this.httpAuthenticator = new HttpAuthenticator();
    }

    @Test
    public void testAuthenticationRequested() throws Exception {
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        Mockito.when(this.defltAuthStrategy.isAuthenticationRequested(
                Mockito.any(HttpHost.class),
                Mockito.any(HttpResponse.class),
                Mockito.any(HttpContext.class))).thenReturn(Boolean.TRUE);

        Assert.assertTrue(this.httpAuthenticator.isAuthenticationRequested(
                this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context));

        Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context);
    }

    @Test
    public void testAuthenticationRequestedAfterSuccess() throws Exception {
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        Mockito.when(this.defltAuthStrategy.isAuthenticationRequested(
                Mockito.any(HttpHost.class),
                Mockito.any(HttpResponse.class),
                Mockito.any(HttpContext.class))).thenReturn(Boolean.TRUE);

        this.authState.update(this.authScheme, this.credentials);
        this.authState.setState(AuthProtocolState.SUCCESS);

        Assert.assertTrue(this.httpAuthenticator.isAuthenticationRequested(
                this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context));

        Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context);
        Mockito.verify(this.defltAuthStrategy).authFailed(this.defaultHost, this.authScheme, this.context);
    }

    @Test
    public void testAuthenticationNotRequestedUnchallenged() throws Exception {
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
        Mockito.when(this.defltAuthStrategy.isAuthenticationRequested(
                Mockito.any(HttpHost.class),
                Mockito.any(HttpResponse.class),
                Mockito.any(HttpContext.class))).thenReturn(Boolean.FALSE);

        Assert.assertFalse(this.httpAuthenticator.isAuthenticationRequested(
                this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context));
        Assert.assertEquals(AuthProtocolState.UNCHALLENGED, this.authState.getState());

        Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context);
    }

    @Test
    public void testAuthenticationNotRequestedSuccess1() throws Exception {
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
        Mockito.when(this.defltAuthStrategy.isAuthenticationRequested(
                Mockito.any(HttpHost.class),
                Mockito.any(HttpResponse.class),
                Mockito.any(HttpContext.class))).thenReturn(Boolean.FALSE);
        this.authState.update(this.authScheme, this.credentials);
        this.authState.setState(AuthProtocolState.CHALLENGED);

        Assert.assertFalse(this.httpAuthenticator.isAuthenticationRequested(
                this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context));
        Assert.assertEquals(AuthProtocolState.SUCCESS, this.authState.getState());

        Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context);
        Mockito.verify(this.defltAuthStrategy).authSucceeded(this.defaultHost, this.authScheme, this.context);
    }

    @Test
    public void testAuthenticationNotRequestedSuccess2() throws Exception {
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
        Mockito.when(this.defltAuthStrategy.isAuthenticationRequested(
                Mockito.any(HttpHost.class),
                Mockito.any(HttpResponse.class),
                Mockito.any(HttpContext.class))).thenReturn(Boolean.FALSE);
        this.authState.update(this.authScheme, this.credentials);
        this.authState.setState(AuthProtocolState.HANDSHAKE);

        Assert.assertFalse(this.httpAuthenticator.isAuthenticationRequested(
                this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context));
        Assert.assertEquals(AuthProtocolState.SUCCESS, this.authState.getState());

        Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context);
        Mockito.verify(this.defltAuthStrategy).authSucceeded(this.defaultHost, this.authScheme, this.context);
    }

    @Test
    public void testAuthentication() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

        final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

        Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
                response, authStrategy, this.authState, this.context));
        Assert.assertEquals(AuthProtocolState.CHALLENGED, this.authState.getState());

        final Queue<AuthOption> options = this.authState.getAuthOptions();
        Assert.assertNotNull(options);
        final AuthOption option1 = options.poll();
        Assert.assertNotNull(option1);
        Assert.assertEquals("digest", option1.getAuthScheme().getSchemeName());
        final AuthOption option2 = options.poll();
        Assert.assertNotNull(option2);
        Assert.assertEquals("basic", option2.getAuthScheme().getSchemeName());
        Assert.assertNull(options.poll());
    }

    @Test
    public void testAuthenticationNoChallenges() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");

        Mockito.when(this.defltAuthStrategy.getChallenges(
                Mockito.any(HttpHost.class),
                Mockito.any(HttpResponse.class),
                Mockito.any(HttpContext.class))).thenReturn(new HashMap<String, Header>());

        Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
                response, this.defltAuthStrategy, this.authState, this.context));
    }

    @Test
    public void testAuthenticationNoSupportedChallenges() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "This realm=\"test\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "That realm=\"realm1\", nonce=\"1234\""));

        final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

        Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
                response, authStrategy, this.authState, this.context));
    }

    @Test
    public void testAuthenticationNoCredentials() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

        this.credentialsProvider.clear();

        final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

        Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
                response, authStrategy, this.authState, this.context));
    }

    @Test
    public void testAuthenticationFailed() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

        this.authState.setState(AuthProtocolState.CHALLENGED);
        this.authState.update(this.authScheme, this.credentials);

        final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

        Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
                response, authStrategy, this.authState, this.context));

        Assert.assertEquals(AuthProtocolState.FAILURE, this.authState.getState());

        Mockito.verify(this.authCache).remove(host);
    }

    @Test
    public void testAuthenticationFailedPreviously() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

        this.authState.setState(AuthProtocolState.FAILURE);

        final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

        Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
                response, authStrategy, this.authState, this.context));

        Assert.assertEquals(AuthProtocolState.FAILURE, this.authState.getState());
    }

    @Test
    public void testAuthenticationFailure() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

        final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

        this.authState.setState(AuthProtocolState.CHALLENGED);
        this.authState.update(new BasicScheme(), this.credentials);

        Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
                response, authStrategy, this.authState, this.context));
        Assert.assertEquals(AuthProtocolState.FAILURE, this.authState.getState());
        Assert.assertNull(this.authState.getCredentials());
    }

    @Test
    public void testAuthenticationHandshaking() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", stale=true, nonce=\"1234\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

        final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

        this.authState.setState(AuthProtocolState.CHALLENGED);
        this.authState.update(new DigestScheme(), this.credentials);

        Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
                response, authStrategy, this.authState, this.context));

        Assert.assertEquals(AuthProtocolState.HANDSHAKE, this.authState.getState());
    }

    @Test
    public void testAuthenticationNoMatchingChallenge() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
        response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

        final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

        this.authState.setState(AuthProtocolState.CHALLENGED);
        this.authState.update(new BasicScheme(), this.credentials);

        Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
                response, authStrategy, this.authState, this.context));
        Assert.assertEquals(AuthProtocolState.CHALLENGED, this.authState.getState());

        final Queue<AuthOption> options = this.authState.getAuthOptions();
        Assert.assertNotNull(options);
        final AuthOption option1 = options.poll();
        Assert.assertNotNull(option1);
        Assert.assertEquals("digest", option1.getAuthScheme().getSchemeName());
        Assert.assertNull(options.poll());
    }

    @Test
    public void testAuthenticationException() throws Exception {
        final HttpHost host = new HttpHost("somehost", 80);
        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");

        this.authState.setState(AuthProtocolState.CHALLENGED);

        Mockito.doThrow(new MalformedChallengeException()).when(this.defltAuthStrategy).getChallenges(
                Mockito.any(HttpHost.class),
                Mockito.any(HttpResponse.class),
                Mockito.any(HttpContext.class));

        Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
                response, this.defltAuthStrategy, this.authState, this.context));

        Assert.assertEquals(AuthProtocolState.UNCHALLENGED, this.authState.getState());
        Assert.assertNull(this.authState.getAuthScheme());
        Assert.assertNull(this.authState.getCredentials());
    }

    @Test
    public void testAuthFailureState() throws Exception {
        final HttpRequest request = new BasicHttpRequest("GET", "/");
        this.authState.setState(AuthProtocolState.FAILURE);
        this.authState.update(this.authScheme, this.credentials);

        this.httpAuthenticator.generateAuthResponse(request, authState, context);

        Assert.assertFalse(request.containsHeader(AUTH.WWW_AUTH_RESP));

        Mockito.verify(this.authScheme, Mockito.never()).authenticate(
                Mockito.any(Credentials.class),
                Mockito.any(HttpRequest.class),
                Mockito.any(HttpContext.class));
    }

    @Test
    public void testAuthChallengeStateNoOption() throws Exception {
        final HttpRequest request = new BasicHttpRequest("GET", "/");
        this.authState.setState(AuthProtocolState.CHALLENGED);
        this.authState.update(this.authScheme, this.credentials);

        Mockito.when(this.authScheme.authenticate(
                Mockito.any(Credentials.class),
                Mockito.any(HttpRequest.class),
                Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

        this.httpAuthenticator.generateAuthResponse(request, authState, context);

        Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

        Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context);
    }

    @Test
    public void testAuthChallengeStateOneOptions() throws Exception {
        final HttpRequest request = new BasicHttpRequest("GET", "/");
        this.authState.setState(AuthProtocolState.CHALLENGED);
        final LinkedList<AuthOption> authOptions = new LinkedList<AuthOption>();
        authOptions.add(new AuthOption(this.authScheme, this.credentials));
        this.authState.update(authOptions);

        Mockito.when(this.authScheme.authenticate(
                Mockito.any(Credentials.class),
                Mockito.any(HttpRequest.class),
                Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

        this.httpAuthenticator.generateAuthResponse(request, authState, context);

        Assert.assertSame(this.authScheme, this.authState.getAuthScheme());
        Assert.assertSame(this.credentials, this.authState.getCredentials());
        Assert.assertNull(this.authState.getAuthOptions());

        Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

        Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context);
    }

    @Test
    public void testAuthChallengeStateMultipleOption() throws Exception {
        final HttpRequest request = new BasicHttpRequest("GET", "/");
        this.authState.setState(AuthProtocolState.CHALLENGED);

        final LinkedList<AuthOption> authOptions = new LinkedList<AuthOption>();
        final ContextAwareAuthScheme authScheme1 = Mockito.mock(ContextAwareAuthScheme.class);
        Mockito.doThrow(new AuthenticationException()).when(authScheme1).authenticate(
                Mockito.any(Credentials.class),
                Mockito.any(HttpRequest.class),
                Mockito.any(HttpContext.class));
        final ContextAwareAuthScheme authScheme2 = Mockito.mock(ContextAwareAuthScheme.class);
        Mockito.when(authScheme2.authenticate(
                Mockito.any(Credentials.class),
                Mockito.any(HttpRequest.class),
                Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));
        authOptions.add(new AuthOption(authScheme1, this.credentials));
        authOptions.add(new AuthOption(authScheme2, this.credentials));
        this.authState.update(authOptions);

        this.httpAuthenticator.generateAuthResponse(request, authState, context);

        Assert.assertSame(authScheme2, this.authState.getAuthScheme());
        Assert.assertSame(this.credentials, this.authState.getCredentials());
        Assert.assertNull(this.authState.getAuthOptions());

        Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

        Mockito.verify(authScheme1, Mockito.times(1)).authenticate(this.credentials, request, this.context);
        Mockito.verify(authScheme2, Mockito.times(1)).authenticate(this.credentials, request, this.context);
    }

    @Test
    public void testAuthSuccess() throws Exception {
        final HttpRequest request = new BasicHttpRequest("GET", "/");
        this.authState.setState(AuthProtocolState.SUCCESS);
        this.authState.update(this.authScheme, this.credentials);

        Mockito.when(this.authScheme.isConnectionBased()).thenReturn(Boolean.FALSE);
        Mockito.when(this.authScheme.authenticate(
                Mockito.any(Credentials.class),
                Mockito.any(HttpRequest.class),
                Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

        this.httpAuthenticator.generateAuthResponse(request, authState, context);

        Assert.assertSame(this.authScheme, this.authState.getAuthScheme());
        Assert.assertSame(this.credentials, this.authState.getCredentials());
        Assert.assertNull(this.authState.getAuthOptions());

        Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

        Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context);
    }

    @Test
    public void testAuthSuccessConnectionBased() throws Exception {
        final HttpRequest request = new BasicHttpRequest("GET", "/");
        this.authState.setState(AuthProtocolState.SUCCESS);
        this.authState.update(this.authScheme, this.credentials);

        Mockito.when(this.authScheme.isConnectionBased()).thenReturn(Boolean.TRUE);
        Mockito.when(this.authScheme.authenticate(
                Mockito.any(Credentials.class),
                Mockito.any(HttpRequest.class),
                Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

        this.httpAuthenticator.generateAuthResponse(request, authState, context);

        Assert.assertFalse(request.containsHeader(AUTH.WWW_AUTH_RESP));

        Mockito.verify(this.authScheme, Mockito.never()).authenticate(
                Mockito.any(Credentials.class),
                Mockito.any(HttpRequest.class),
                Mockito.any(HttpContext.class));
    }

}


text:
package org.ScripterRon.MyMoney;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

/**
 * Bank transaction edit dialog
 */
public final class BankTransactionEditDialog extends JDialog implements ActionListener {

    /** The transaction panel */
    private TransactionPanel transactionPanel;

    /** The transaction account */
    private AccountRecord account;

    /** Transaction */
    private TransactionRecord transaction;

    /** Transaction splits */
    private List<TransactionSplit> splits;

    /** Transaction has splits */
    private boolean showSplits;

    /** This is a security transaction */
    private boolean securityTransaction;

    /** Transaction date field */
    private JFormattedTextField dateField;

    /** Check number field */
    private JFormattedTextField checkField;

    /** Transaction name field */
    private JTextField nameField;

    /** Category/Account field */
    private JComboBox categoryAccountField;

    /** Category/Account model */
    private TransferComboBoxModel categoryAccountModel;

    /** Splits model */
    private DefaultComboBoxModel splitsModel;

    /** Memo field */
    private JTextField memoField;

    /** Payment field */
    private JFormattedTextField paymentField;

    /** Deposit field */
    private JFormattedTextField depositField;

    /** "Not reconciled" radio button */
    private JRadioButton notReconciledField;

    /** "Reconcile pending" radio button */
    private JRadioButton reconcilePendingField;

    /** "Reconciled" radio button */
    private JRadioButton reconciledField;

    /**
     * Create the dialog
     *
     * @param       parent              Parent window
     * @param       title               Dialog title
     * @param       transactionPanel    The transaction panel
     * @param       transaction         Transaction to edit or null for new transaction
     */
    public BankTransactionEditDialog(JFrame parent, String title, TransactionPanel transactionPanel,
                                     TransactionRecord transaction) {
        super(parent, title, Dialog.ModalityType.DOCUMENT_MODAL);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.transactionPanel = transactionPanel;
        this.transaction = transaction;
        account = transactionPanel.getTransactionAccount();

        //
        // Get the transaction specifics for an existing transaction
        //
        AccountRecord transferAccount = null;
        CategoryRecord category = null;
        String name = null;
        double payment = 0.00;
        double deposit = 0.00;
        int reconciledState = 0;
        double amount;
        securityTransaction = false;
        splits = null;
        showSplits = false;
        if (transaction != null) {
            splits = transaction.getSplits();
            if (transaction.getAccount() == account) {
                transferAccount = transaction.getTransferAccount();
                category = transaction.getCategory();
                name = transaction.getName();
                amount = transaction.getAmount();
                if (amount < 0.0)
                    payment = -amount;
                else if (amount > 0.0)
                    deposit = amount;
                int reconciled = transaction.getReconciled();
                if ((reconciled&TransactionRecord.SOURCE_PENDING) != 0)
                    reconciledState = 1;
                else if ((reconciled&TransactionRecord.SOURCE_RECONCILED) != 0)
                    reconciledState = 2;
            } else if (transaction.getTransferAccount() == account) {
                transferAccount = transaction.getAccount();
                category = transaction.getCategory();
                SecurityRecord s = transaction.getSecurity();
                if (s != null) {
                    name = s.getName();
                    securityTransaction = true;
                } else {
                    name = transaction.getName();
                }

                amount = transaction.getAmount();
                if (amount > 0.0)
                    payment = amount;
                else if (amount < 0.0)
                    deposit = -amount;
                int reconciled = transaction.getReconciled();
                if ((reconciled&TransactionRecord.TARGET_PENDING) != 0)
                    reconciledState = 1;
                else if ((reconciled&TransactionRecord.TARGET_RECONCILED) != 0)
                    reconciledState = 2;
            } else if (splits != null) {
                for (TransactionSplit split : splits) {
                    if (split.getAccount() == account) {
                        transferAccount = transaction.getAccount();
                        category = split.getCategory();
                        name = split.getDescription();
                        amount = split.getAmount();
                        if (amount > 0.0)
                            payment = amount;
                        else if (amount < 0.0)
                            deposit = -amount;
                        int reconciled = split.getReconciled();
                        if ((reconciled&TransactionRecord.TARGET_PENDING) != 0)
                            reconciledState = 1;
                        else if ((reconciled&TransactionRecord.TARGET_RECONCILED) != 0)
                            reconciledState = 2;
                        break;
                    }
                }
            }
        }

        //
        // Get the transaction date
        //
        // The date cannot be changed for an investment transaction
        //
        dateField = new JFormattedTextField(new EditDate());
        dateField.setColumns(8);
        dateField.setInputVerifier(new EditInputVerifier(false));
        dateField.addActionListener(new FormattedTextFieldListener(this));
        if (transaction != null) {
            dateField.setValue(transaction.getDate());
            if (securityTransaction)
                dateField.setEditable(false);
        } else {
            dateField.setValue(Main.getCurrentDate());
        }

        //
        // Get the check number
        //
        // The check number field is not displayed for a transfer account
        //
        if (transaction == null || transaction.getAccount() == account) {
            checkField = new JFormattedTextField(new EditNumber(0, false));
            checkField.setColumns(5);
            checkField.setInputVerifier(new EditInputVerifier(true));
            checkField.addActionListener(new FormattedTextFieldListener(this));
            if (transaction != null) {
                int number = transaction.getCheckNumber();
                if (number != 0)
                    checkField.setValue(new Integer(number));
            }
        }

        //
        // Get the transaction name
        //
        // The name cannot be changed for an investment transaction
        //
        if (name != null)
            nameField = new JTextField(name, 20);
        else
            nameField = new JTextField(20);

        if (securityTransaction) {
            nameField.setEditable(false);
        } else {
            JTable table = transactionPanel.getTransactionTable();
            AccountTableModel model = (AccountTableModel)table.getModel();
            NameDocumentListener.addInstance(nameField, model.getTransactionNames());
        }

        //
        // Get the category or transfer account
        //
        // The source account cannot be changed from a transfer account.
        //
        categoryAccountModel = new TransferComboBoxModel(account, transferAccount, category);
        splitsModel = new DefaultComboBoxModel();
        if (transaction != null && transaction.getAccount() != account) {
            categoryAccountField = new JComboBox(splitsModel);
            categoryAccountField.addItem("["+transaction.getAccount().getName()+"]");
            categoryAccountField.setSelectedIndex(0);
        } else if (splits != null) {
            categoryAccountField = new JComboBox(splitsModel);
            categoryAccountField.addItem("--Split--");
            categoryAccountField.setSelectedIndex(0);
            showSplits = true;
        } else {
            categoryAccountField = new JComboBox(categoryAccountModel);
            if (transferAccount != null)
                categoryAccountModel.setSelectedItem("["+transferAccount.getName()+"]");
            else if (category != null)
                categoryAccountModel.setSelectedItem(category.getName());
            else
                categoryAccountField.setSelectedIndex(0);
        }

        //
        // Get the memo
        //
        if (transaction != null)
            memoField = new JTextField(transaction.getMemo(), 25);
        else
            memoField = new JTextField(25);

        //
        // Get the payment amount
        //
        // Investment amounts cannot be changed from the linked account.
        // The payment amount cannot be changed if there are splits.
        //
        paymentField = new JFormattedTextField(new EditNumber(2, true));
        paymentField.setColumns(10);
        paymentField.setInputVerifier(new EditInputVerifier(true));
        paymentField.addActionListener(new FormattedTextFieldListener(this));
        if (payment != 0.00)
            paymentField.setValue(new Double(payment));
        if (securityTransaction || splits != null)
            paymentField.setEditable(false);

        //
        // Get the deposit amount
        //
        // Investment amounts cannot be changed from the linked account
        // The deposit amount cannot be changed if there are splits.
        //
        depositField = new JFormattedTextField(new EditNumber(2, true));
        depositField.setColumns(10);
        depositField.setInputVerifier(new EditInputVerifier(true));
        depositField.addActionListener(new FormattedTextFieldListener(this));
        if (deposit != 0.00)
            depositField.setValue(new Double(deposit));
        if (securityTransaction || splits != null)
            depositField.setEditable(false);

        //
        // Create the edit pane
        //
        //    Date:              <text-field>
        //    Check number:      <text-field>  (Optional)
        //    Name:              <text-field>
        //    Category/Account:  <combo-box>
        //    Memo:              <text-field>
        //    Payment:           <text-field>
        //    Deposit:           <text-field>
        //
        JPanel editPane = new JPanel(new GridLayout(0, 2, 5, 5));

        editPane.add(new JLabel("Date:", JLabel.RIGHT));
        editPane.add(dateField);

        if (checkField != null) {
            editPane.add(new JLabel("Check number:", JLabel.RIGHT));
            editPane.add(checkField);
        }

        editPane.add(new JLabel("Name:", JLabel.RIGHT));
        editPane.add(nameField);

        editPane.add(new JLabel("Category/Account:", JLabel.RIGHT));
        editPane.add(categoryAccountField);

        editPane.add(new JLabel("Memo:", JLabel.RIGHT));
        editPane.add(memoField);

        editPane.add(new JLabel("Payment:", JLabel.RIGHT));
        editPane.add(paymentField);

        editPane.add(new JLabel("Deposit:", JLabel.RIGHT));
        editPane.add(depositField);

        //
        // Create the reconcile radio buttons
        //
        notReconciledField = new JRadioButton("Not Reconciled");
        reconcilePendingField = new JRadioButton("Reconcile Pending");
        reconciledField = new JRadioButton("Reconciled");

        switch (reconciledState) {
            case 0:                             // Not reconciled
                notReconciledField.setSelected(true);
                break;

            case 1:                             // Reconcile pending
                reconcilePendingField.setSelected(true);
                break;

            case 2:                             // Reconciled
                reconciledField.setSelected(true);
                break;
        }

        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(notReconciledField);
        buttonGroup.add(reconcilePendingField);
        buttonGroup.add(reconciledField);

        JPanel groupPane = new JPanel();
        groupPane.setLayout(new BoxLayout(groupPane, BoxLayout.X_AXIS));
        groupPane.add(notReconciledField);
        groupPane.add(Box.createHorizontalStrut(15));
        groupPane.add(reconcilePendingField);
        groupPane.add(Box.createHorizontalStrut(15));
        groupPane.add(reconciledField);

        //
        // Create the buttons (OK, Edit Splits, Cancel, Help)
        //
        // The "Edit Splits" button is not displayed for a transfer account since
        // the splits can be edited only from the source account
        //
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));

        JButton button = new JButton("OK");
        button.setActionCommand("ok");
        button.addActionListener(this);
        buttonPane.add(button);
        getRootPane().setDefaultButton(button);

        buttonPane.add(Box.createHorizontalStrut(10));

        if (transaction == null || transaction.getAccount() == account) {
            button = new JButton("Edit Splits");
            button.setActionCommand("edit splits");
            button.addActionListener(this);
            buttonPane.add(button);

            buttonPane.add(Box.createHorizontalStrut(10));
        }

        button = new JButton("Cancel");
        button.setActionCommand("cancel");
        button.addActionListener(this);
        buttonPane.add(button);

        buttonPane.add(Box.createHorizontalStrut(10));

        button = new JButton("Help");
        button.setActionCommand("help");
        button.addActionListener(this);
        buttonPane.add(button);

        //
        // Set up the content pane
        //
        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
        contentPane.setOpaque(true);
        contentPane.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
        contentPane.add(editPane);
        contentPane.add(Box.createVerticalStrut(15));
        contentPane.add(groupPane);
        contentPane.add(Box.createVerticalStrut(15));
        contentPane.add(buttonPane);
        setContentPane(contentPane);
    }

    /**
     * Show the bank transaction edit dialog
     *
     * @param       parent              Parent window for the dialog
     * @param       transactionPanel    Transaction panel
     * @param       transaction         Transaction or null for a new transaction
     */
    public static void showDialog(JFrame parent, TransactionPanel transactionPanel,
                                  TransactionRecord transaction) {
        try {
            String title = (transaction==null ? "New Transaction" : "Edit Transaction");
            JDialog dialog = new BankTransactionEditDialog(parent, title, transactionPanel, transaction);
            dialog.pack();
            dialog.setLocationRelativeTo(parent);
            dialog.setVisible(true);
        } catch (Exception exc) {
            Main.logException("Exception while displaying dialog", exc);
        }
    }

    /**
     * Action performed (ActionListener interface)
     *
     * @param   ae              Action event
     */
    public void actionPerformed(ActionEvent ae) {

        //
        // Process the action command
        //
        // "ok" - Data entry is complete
        // "edit splits" - Edit the transaction splits
        // "cancel" - Cancel the request
        // "help" - Display help for bank accounts
        //
        try {
            switch (ae.getActionCommand()) {
                case "ok":
                    if (processFields()) {
                        setVisible(false);
                        dispose();
                    }
                    break;

                case "edit splits":
                    processSplits(this);
                    break;

                case "cancel":
                    setVisible(false);
                    dispose();
                    break;

                case "help":
                    Main.mainWindow.displayHelp(HelpWindow.BANK_ACCOUNT);
                    break;
            }
        } catch (Exception exc) {
            Main.logException("Exception while processing action event", exc);
        }
    }

    /**
     * Process transaction splits
     *
     * @param       parent          Parent window
     */
    private void processSplits(JDialog parent) {

        //
        // Display the splits dialog
        //
        if (splits == null)
            splits = new ArrayList<>(5);

        SplitsDialog.showDialog(parent, splits, account);

        //
        // Update the category/account combo box if necessary
        //
        // The payment and deposit fields are set from the transaction splits
        // and are not editable when there are transaction splits.
        //
        if (splits.isEmpty()) {
            splits = null;
            paymentField.setEditable(true);
            depositField.setEditable(true);
            if (showSplits) {
                categoryAccountField.setModel(categoryAccountModel);
                categoryAccountField.setSelectedIndex(0);
                showSplits = false;
            }
        } else {
            paymentField.setEditable(false);
            depositField.setEditable(false);
            double amount = 0.00;

            for (TransactionSplit split : splits)
                amount += split.getAmount();

            if (amount < 0.0) {
                paymentField.setValue(new Double(-amount));
                depositField.setValue(null);
            } else {
                paymentField.setValue(null);
                depositField.setValue(new Double(amount));
            }

            if (!showSplits) {
                categoryAccountField.setModel(splitsModel);
                categoryAccountField.removeAllItems();
                categoryAccountField.addItem("--Split--");
                categoryAccountField.setSelectedIndex(0);
                showSplits = true;
            }
        }
    }

    /**
     * Process the transaction fields
     *
     * @return                  TRUE if the entered data is valid
     */
    private boolean processFields() {
        AccountRecord a, t;
        int index, reconciled;
        int transactionPosition = -1, modelPosition = -1;
        double amount;
        String name;

        //
        // Validate the transaction information
        //
        if (!dateField.isEditValid()) {
           JOptionPane.showMessageDialog(this, "You must specify a transaction date",
                                         "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (!paymentField.isEditValid() && !depositField.isEditValid()) {
            JOptionPane.showMessageDialog(this, "You must specify a payment or deposit amount",
                                          "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        Date date = (Date)dateField.getValue();
        JTable table = transactionPanel.getTransactionTable();
        AccountTableModel tableModel = (AccountTableModel)table.getModel();

        //
        // Remove an existing transaction (an investment transaction is not
        // removed since the investment fields cannot be changed from the
        // linked account)
        //
        if (transaction != null) {
            a = transaction.getAccount();
            t = transaction.getTransferAccount();
            name = transaction.getName();
            amount = transaction.getAmount();
            reconciled = transaction.getReconciled();
            if (!securityTransaction) {
                ListIterator<TransactionRecord> i = TransactionRecord.transactions.listIterator();
                transactionPosition = 0;
                while (i.hasNext()) {
                    if (i.next() == transaction) {
                        i.remove();
                        break;
                    }

                    transactionPosition++;
                }

                transaction.clearReferences();
                modelPosition = tableModel.transactionRemoved(transaction);
                if (date.compareTo(transaction.getDate()) != 0) {
                    transactionPosition = -1;
                    modelPosition = -1;
                }

                transaction = new TransactionRecord(date, a);
                if (t != null && t == account)
                    transaction.setTransferAccount(t);

                if (a != account && splits != null) {
                    transaction.setName(name);
                    transaction.setAmount(amount);
                }
            }

            if (a == account) {
                reconciled &= (255-TransactionRecord.SOURCE_PENDING-TransactionRecord.SOURCE_RECONCILED);
                transaction.setReconciled(reconciled);
            } else if (t == account) {
                reconciled &= (255-TransactionRecord.TARGET_PENDING-TransactionRecord.TARGET_RECONCILED);
                transaction.setReconciled(reconciled);
            } else if (splits != null) {
                for (TransactionSplit split : splits) {
                    if (split.getAccount() == account) {
                        reconciled = split.getReconciled();
                        reconciled &= (255-TransactionRecord.TARGET_PENDING-TransactionRecord.TARGET_RECONCILED);
                        split.setReconciled(reconciled);
                        break;
                    }
                }
            }
        } else {
            transaction = new TransactionRecord(date, account);
        }

        //
        // Get the transaction name and update the name list
        //
        name = nameField.getText();
        if (name.length() > 0 && !securityTransaction)
            tableModel.getTransactionNames().add(name);

        //
        // Build the new transaction
        //
        transaction.setMemo(memoField.getText());
        if (checkField != null && checkField.isEditValid())
            transaction.setCheckNumber(((Number)checkField.getValue()).intValue());

        index = categoryAccountField.getSelectedIndex();
        if (index > 0) {
            DBElement element = categoryAccountModel.getDBElementAt(index);
            if (element instanceof AccountRecord)
                transaction.setTransferAccount((AccountRecord)element);
            else
                transaction.setCategory((CategoryRecord)element);
        }

        a = transaction.getAccount();
        t = transaction.getTransferAccount();
        amount = 0.00;
        if (paymentField.isEditValid())
            amount -= ((Number)paymentField.getValue()).doubleValue();
        if (depositField.isEditValid())
            amount += ((Number)depositField.getValue()).doubleValue();

        if (a == account) {
            transaction.setName(name);
            transaction.setAmount(amount);
            reconciled = transaction.getReconciled();
            if (reconciledField.isSelected())
                reconciled |= TransactionRecord.SOURCE_RECONCILED;
            else if (reconcilePendingField.isSelected())
                reconciled |= TransactionRecord.SOURCE_PENDING;
            transaction.setReconciled(reconciled);
        } else  if (t == account) {
            transaction.setName(name);
            transaction.setAmount(-amount);
            reconciled = transaction.getReconciled();
            if (reconciledField.isSelected())
                reconciled |= TransactionRecord.TARGET_RECONCILED;
            else if (reconcilePendingField.isSelected())
                reconciled |= TransactionRecord.TARGET_PENDING;
            transaction.setReconciled(reconciled);
        } else if (splits != null) {
            for (TransactionSplit split : splits) {
                if (split.getAccount() == account) {
                    split.setDescription(name);
                    reconciled = split.getReconciled();
                    if (reconciledField.isSelected())
                        reconciled |= TransactionRecord.TARGET_RECONCILED;
                    else if (reconcilePendingField.isSelected())
                        reconciled |= TransactionRecord.TARGET_PENDING;
                    split.setReconciled(reconciled);
                    break;
                }
            }
        }

        transaction.setSplits(splits);
        splits = null;

        //
        // Add the new transaction and scroll the table to display the
        // transaction.  A security transaction is not added since it was
        // not removed earlier.
        //
        if (!securityTransaction) {
            if (transactionPosition >= 0)
                TransactionRecord.transactions.add(transactionPosition, transaction);
            else
                TransactionRecord.insertTransaction(transaction);

            int modelRow = tableModel.transactionAdded(modelPosition, transaction);
            transactionPanel.showSelectedRow(table.convertRowIndexToView(modelRow));
        } else {
            tableModel.transactionModified(transaction);
        }

        Main.dataModified = true;
        return true;
    }
}


text:
<!doctype html>

	<meta charset="utf-8">

	<title>Name of Tutorial</title>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta http-equiv="Content-language" content="en" />

	<meta name="description" content="Description of tutorial." />

	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<link rel="icon" href="http://chemcollective.org/assets/common/images/styling/favicon.ico">

	<link rel="stylesheet" type="text/css" media="screen" href="http://chemcollective.org/assets/common/css/styles.css" />
	<link rel="stylesheet" type="text/css" media="print" href="http://chemcollective.org/assets/common/css/print-styles.css" />
	<link rel="StyleSheet" href="style.css" type="text/css" />

Online Resources for Teaching and Learning Chemistry

Home

						About

						Teachers

						Help

Feedback

					<form method="get" id="searchform" action="http://chemcollective.org/search/">
						<input type="submit" class="submit" id="searchsubmit" value="Search" style="margin-right:1px">
						<input type="text" id="q" name="q" class="field">
					</form>

We've recently updated our site. If you are having problems, you can click here to get to the old site.

Equilibrium Tutorials

-LeChatlier's Principle-

LeChatlier's Principle: Hemoglobin scenario

Reversible Reactions

Using LeChatlier's Principle

Concentration

Temperature

Volume/Pressure

-Comparing Q to K-

Comparing Q to K: Hemoglobin scenario

Progress of reaction (Q)

Law of mass action (Q=K)

Equilibrium is dynamic

Comparing Q to K to determine shift

Q for heterogeneous reactions

Equilibrium and thermodynamics (K and ΔG)

Manipulating K and chemical reactions

-Quantitative Equilibrium Calculations-

Quantitative Equilibrium: Hemoglobin scenario

Overview (Equilibrium vs. limiting reagents)

Limiting reagents using ICE tables

Calculations for intermediate values of K

Shifting starting position to simplify calculations

Calculations for large or small values of K

You are here:

Home >

 Equilibrium /
								 Tutorials >

 LeChatlier's Principle: Hemoglobin scenario

Name of Tutorial

Introductory paragraph(s)

						<audio id="audio" src=""></audio>

						<object data="Converted_Images/Mod1_Intro.svg" type="image/svg+xml" width="720" height="600"></object>

The ChemCollective site and its contents are licensed under a Creative Commons Attribution 3.0 NonCommercial-NoDerivs License.

				Contact Us

		<srcipt src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>


text:
"""\
Create a panel showing all of the colors defined in the pawt.colors module
Display the names of bright colors in black and of dark colors in white
"""

from java import awt
from pawt import colors, test
from math import sqrt

p = awt.Panel()
for name in dir(colors):
	color = getattr(colors, name)
	if isinstance(color, awt.Color):
		l = awt.Label(name, awt.Label.CENTER, background=color)
		intensity = sqrt(color.red**2 + color.green**2 + color.blue**2)/3
		if intensity < 90: l.foreground = colors.white
		p.add(l)

test(p, size=(700,500))


text:
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from optparse import make_option
from satchmo.product.models import Product, ProductPriceLookup

class Command(BaseCommand):
    help = "Builds Satcho Product pricing lookup tables."
    args = ['sitename...']

    requires_model_validation = True

    def handle(self, *sitenames, **options):
        from django.conf import settings

        verbosity = int(options.get('verbosity', 1))
        if len(sitenames) == 0:
            if verbosity>0:
                print "Rebuilding pricing for all products for all sites"
                sites = Site.objects.all()
        else:
            sites = []
            for sitename in sitenames:
                try:
                    sites.append(Site.objects.get(domain__iexact=sitename))
                except Site.DoesNotExist:
                    print "Warning: Could not find site '%s'" % sitename

        total = 0
        for site in sites:
            ct = 0
            if verbosity > 0:
                print "Starting product pricing for %s" % site.domain

            if verbosity > 1:
                print "Deleting old pricing"

            for lookup in ProductPriceLookup.objects.filter(siteid=site.id):
                lookup.delete()

            products = Product.objects.active_by_site(site=site, variations=False)
            if verbosity > 0:
                print "Adding %i products" % products.count()

            for product in products:
                if verbosity > 1:
                    print "Processing product: %s" % product.slug

                prices = ProductPriceLookup.objects.smart_create_for_product(product)
                if verbosity > 1:
                    print "Created %i prices" % len(prices)

                ct += len(prices)

            if verbosity > 0:
                print "Added %i total prices for site" % ct

            total += ct

        if verbosity > 0:
            print "Added %i total prices" % total


text:
didthattoday
============

A webapp for saying whether you did something on a day.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Inocybe coerulescens Kobayasi

### Remarks
null