text:
using System;
using System.Collections.Generic;
using System.Threading;
using IBApi.Connection;
using IBApi.Contracts;
using IBApi.Errors;
using IBApi.Messages.Client;
using IBApi.Messages.Server;
using CodeContract = System.Diagnostics.Contracts.Contract;
using ContractInvariantMethod = System.Diagnostics.Contracts.ContractInvariantMethodAttribute;

namespace IBApi.Quotes
{
    internal class QuoteSubscription : IDisposable
    {
        private readonly IConnection connection;
        private readonly IQuoteObserver observer;
        private int requestId;
        private ICollection<IDisposable> subscriptions;
        private bool disposed;
        private Quote quote;

        public QuoteSubscription(IConnection connection, IIdsDispenser dispenser, IQuoteObserver observer, Contract contract)
        {
            CodeContract.Requires(connection != null);
            CodeContract.Requires(observer != null);
            CodeContract.Requires(dispenser != null);

            this.connection = connection;
            this.observer = observer;

            this.Subscribe(contract, dispenser);
        }

        public void Dispose()
        {
            if (this.disposed)
            {
                return;
            }

            this.disposed = true;

            this.subscriptions.Unsubscribe();
            this.SendCancelRequest();
        }

        private void Subscribe(Contract contract, IIdsDispenser dispenser)
        {
            this.requestId = dispenser.NextRequestId();

            this.subscriptions = new List<IDisposable>
            {
                this.connection.Subscribe((TickPriceMessage message) => message.RequestId == this.requestId,
                    this.OnTickPrice),
                this.connection.SubscribeForRequestErrors(this.requestId, this.OnError)
            };

            this.SendRequest(contract);
        }

        private void SendRequest(Contract contract)
        {
            var request = RequestMarketDataMessage.FromContract(contract);
            request.RequestId = this.requestId;
            this.connection.SendMessage(request);
        }

        private void SendCancelRequest()
        {
            var cancelRequest = RequestCancelMarketData.Default;
            cancelRequest.RequestId = this.requestId;
            this.connection.SendMessage(cancelRequest);
        }

        private void OnTickPrice(TickPriceMessage message)
        {
            this.UpdateQuote(message);
            this.observer.OnQuote(this.quote);
        }

        private void OnError(Error error)
        {
            this.observer.OnError(error);
        }

        private void UpdateQuote(TickPriceMessage tickPriceMessage)
        {
            switch (tickPriceMessage.TickType)
            {
                case TickType.Bid:
                    this.quote.BidPrice = tickPriceMessage.Price;
                    this.quote.BidSize = tickPriceMessage.Size;
                    return;

                case TickType.Ask:
                    this.quote.AskPrice = tickPriceMessage.Price;
                    this.quote.AskSize = tickPriceMessage.Size;
                    return;

                case TickType.Last:
                    this.quote.TradePrice = tickPriceMessage.Price;
                    this.quote.TradeSize = tickPriceMessage.Size;
                    return;
            }
        }

        [ContractInvariantMethod]
        private void ContractInvariant()
        {
            CodeContract.Invariant(this.connection != null);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<TITLE>Review for Instinct (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Instinct (1999)

reviewed by
Harvey S. Karten

INSTINCT

 Reviewed by Harvey Karten, Ph.D.
 Touchstone Pictures/Spyglass Entertainment
 Director:  Jon Turteltaub
 Writer:  Gerald DiPego
 Cast: Anthony Hopkins, Cuba Gooding Jr., Donald
Sutherland, Maura Tierney, George Dzundza, John Ashton,
John Aylward

   The massacre at Columbine High School in Littleton,
Colorado, received massive publicity partly because of the
extent of the tragedy, but as much because the perpetrators
were privileged kids living in an upper- middle class suburban
area of the country.  Psychologists appear to agree that the
killers--who wore trench coats and referred to themselves as
mafia--were outsiders, disdained and ignored not only by the
"in" cliques of athletes but by women and scholarly types as
well.  They did not fit in and so they took brutal revenge.

   "Instinct" deals as well with a violent man--one who
becomes an outsider, but by his own volition. Repudiating the
safety, prestige and comfort of his academic profession, he
puts himself outside of so-called civilized society, living alone
among the gorillas of Rwanda for two years.  For motivations
which should not be revealed in a review lest such disclosure
spoil a key plot point, the man summons fearsome strength in
attacking park rangers with a wooden club, killing two and
injuring others.  Placed in a solitary cell in a bleak African
prison for a year, he grows his white hair and beard to great
lengths and refuses to speak to anyone.  But because he is a
celebrated anthropologist, the U.S. State Department
manages to secure his release, fly him back to Florida, and
incarcerate him in a maximum security prison that resembles
the institution of last year's documentary "The Farm" more
than it does the correctional facility displayed in the movie
"Life."

   "Instinct," which balances educated (if sophomoric)
discussion with occasional bouts of violence, juggles more
ideas about the human condition than Freud and Kierkegaard
could have formulated in a year.  While nothing novel is
trumpeted--certainly nothing that would gain the attention of
major peer-review magazines--director Jon Turteltaub
("Phenomenon," "3 Ninjas") keeps both the physical action
and the verbal exchanges flowing, gradually revealing the
demons that arouse the scholar to murderous fury.  The
picture shows off unusually good chemistry between Anthony
Hopkins as the besieged prisoner Ethan Powell and Cuba
Gooding, Jr. as Theo Caulder--the therapist who seeks to
uncover the mystery of the professor's mind but winds up
finding out more about himself than he learns about his
reluctant patient.

   The story opens in Rwanda (actually filmed among the lush
vegetation of Jamaica) as Professor Ethan Powell (Anthony
Hopkins) is transferred by the African authorities to the U.S.
State Department in preparation for his incarceration in a
prison for the criminally insane in Florida. The ironically-
named Harmony Bay facility, run by a pragmatic warden
(John Aylward) and staffed by psychiatrist John Murray
(George Dzundza) and brutal guards like Dacks (John
Ashton), is overcrowded.  To help control the inmates, the
prison resorts to the principle of divide and rule, manipulating
the convicts to take out their anger on one another rather
than on the staff.  Dr. Theo Caulder (Cuba Gooding, Jr.) is
assigned to assist in the psychotherapy, but his real interest
is in Dr. Powell.  What makes a man in a staid, secure
profession turn violently criminal?

   Those sections of "Instinct" that deal with the  turbulent talk
sessions between the anthropologist and the psychiatrist are
the most involving, notwithstanding the Psych. 101 level of
dialogue.  As the two professional men talk--or, rather, stalk
each other like creatures on a Rwandan jungle--they make us
privy to such issues as the nature of freedom, the lust for
control and domination, and the concept of illusion.  When
Powell accuses his helper of being a "taker," a person
consumed, even tied-up-in-knots by ambition, we think of the
character of Tracy Flick in Alexander Payne's great satire,
"Election."

   As Dr. Caulder encourages the patient to "show me the
violence"  he learns quite a bit about himself.  He finds out
that his primary motive is not the search for knowledge but
his own desire to advance his career--to publish an article
about his unhappy patient, perhaps even to get out a
best-seller that re-creates the buttoned-up psychiatrist as a
genuine hero.

   As "Instinct" is a studio-made film, an entertaining, well-
acted one indeed, we are not surprised by the dollops of
sentimentality that scripter Gerald DiPego uses to pepper the
action.  Powell's daughter Lyn (Maura Tierney) yearns to
have her estranged father "back," but Powell does not want
even to talk about her.  When Caulder lends the intelligent
and witty, but heartbroken, woman an ear, director Turteltaub
hints at a budding romance between the two.  The story
strains credibility at various points: where does a sixty-year
old academic get the strength to virtually pulverize a three-
hundred pound, much younger prisoner, and to smash his
way through a batallion of police officers determined to
restrain him?  By what vigor can he overpower several young
and muscular African park rangers who, presumably, work
out quite a bit more than the hirsute primatologist?   How
does Powell manage to get the lion's share of attention from
the guards and to have his session run from a room inside
the prison, while the other unfortunates, who need services
as well in this overcrowded facility, must settle for quick
meetings in an entirely public part of the recreation area?

   Donald Sutherland does a credible job as Ben HIllard, who
is Theo Caulder's mentor, who advises the ambitious
young man to think primarily of his career and not of his wish
to help the enraged and frequently silent patient he is
studying.  John Ashton has the appropriate demeanor as the
sadistic guard.  But the other supporting players who are
prisoners--Paul Bates as Bluto, Ian Ingram as Lester
Rodman, and Thomas Q. Morris as Pete--are directed as
cartoonish characters.

   Many in the audience will be reminded of "The Silence of
the Lambs," in which Anthony Hopkins dazzled as the
psychotic criminal Hannibal the Cannibal Lecter, with Jodie
Foster in the Cuba Gooding, Jr. role as the person who tries
to get through to him.  But "Instinct" is closer in
temperament to Peter Shaffer's play "Equus," the story of an
English psychiatrist, Martin Dysart, working with an obsessed
lover of horses, Alan Strang, who commits a barbarous act.
While Dysart is horrified by his patient's psychosis, he
secretly admires the young man's vitality and ends up
questioning his own staid, middle-class life.  "Instinct" is
inspired by the screenwriter's book, "Ishmael," more of a
meditation between a man and a gorilla than an action
adventure.  Turteltaub has turned the book into a not-always-
convincing balance of escapade and reflection, eminently
watchable with its National Geographic-like shots of Hopkins
living as a human being among the gorillas that fully accept
him.

Rated R.  Running Time: 100 minutes.  (C) 1999
Harvey Karten

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

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

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

Broken URLs inthe reviews are the responsibility of the author.

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

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


text:
(function() {  'use strict';

/************************************************************************************
* @ngdoc controller
* @name NotificationsController
* @module metricapp
* @requires $scope
* @requires $rootScope
* @requires $location
* @requires $filter
* @requires NotificationService
* @requires UserService
* @requires NOTIFICATION_EVENTS
*
* @description
* Realizes the control layer for `notifications.view`.
************************************************************************************/

angular.module('metricapp')

.controller('NotificationsController', NotificationsController);

NotificationsController.$inject = ['$scope', '$rootScope', '$location', '$filter', 'NotificationService', 'UserService', 'AuthService', 'NOTIFICATION_EVENTS', 'AUTH_EVENTS'];

function NotificationsController($scope, $rootScope, $location, $filter, NotificationService, UserService, AuthService, NOTIFICATION_EVENTS, AUTH_EVENTS) {

    var vm = this;

    vm.loadMore = loadMore;
    vm.search = search;

    vm.setRead = setRead;
    vm.setAllRead = setAllRead;
    vm.removeNews = removeNews;

    _init();

    function setRead(notificationid) {
        for (var i = 0; i < vm.buffer.length; i++) {
            var notification = vm.buffer[i];
            if (notification.id === notificationid) {
                if (!notification.read) {
                    notification.read = true;
                    vm.toread --;
                }
            }
        }
        NotificationService.setReadById(notificationid);
        $rootScope.$broadcast(NOTIFICATION_EVENTS.SET_READ, notificationid);
    }

    function setAllRead() {
        vm.buffer.forEach(function(notification) {
            notification.read = true;
        });
        vm.toread = 0;
        vm.news = 0;
        NotificationService.setAllRead();
        $rootScope.$broadcast(NOTIFICATION_EVENTS.ALL_READ);
    }

    function removeNews() {
        vm.news = 0;
    }

    function loadMore() {
        if (vm.idx < vm.buffer.length) {
            var e = Math.min(vm.idx + vm.step, vm.buffer.length);
            vm.notifications = vm.notifications.concat(vm.buffer.slice(vm.idx, e));
            vm.idx = e;
        }
    }

    function search(query) {
        vm.buffer = $filter('orderBy')($filter('filter')(vm.data, query), vm.orderBy);
    }

    function _loadAllNotifications() {
        vm.loading = true;
        vm.success = false;
        NotificationService.getAll().then(
            function(resolve) {
                var notifications = resolve.notifications;
                vm.toread = resolve.toread;
                vm.news = resolve.news;
                notifications.forEach(function(notification) {
                    vm.data.push(notification);
                });
                vm.buffer = $filter('orderBy')(vm.data, vm.orderBy);
                vm.success = true;
            },
            function(reject) {
                vm.errmsg = reject.errmsg;
                vm.success = false;
            }
        ).finally(function() {
            vm.loading = false;
        });
    }

    function _init() {
        vm.loading = true;
        vm.success = false;
        vm.errmsg = null;
        vm.data = [];
        vm.buffer = [];
        vm.notifications = [];
        vm.idx = 0;
        vm.step = 2;
        vm.query = '';
        vm.orderBy = '-ts_create';
        _loadAllNotifications();
        $scope.$watch('vm.buffer', function() {
            vm.idx = 0;
            var e = Math.min(vm.idx + vm.step, vm.buffer.length);
            vm.notifications = vm.buffer.slice(vm.idx, e);
            vm.idx = e;
        });
        $scope.$on(NOTIFICATION_EVENTS.ALL_READ, function() {
            vm.buffer.forEach(function(notification) {
                notification.read = true;
            });
            vm.toread = 0;
        });
        $scope.$on(NOTIFICATION_EVENTS.SET_READ, function(event, notificationid) {
            for (var i = 0; i < vm.buffer.length; i++) {
                var notification = vm.buffer[i];
                if (notification.id === notificationid) {
                    if (!notification.read) {
                        notification.read = true;
                        vm.toread --;
                    }
                }
            }
        });
    }

}

})();


text:
@interface TransactionsHeaderView()

@property (weak, nonatomic) IBOutlet OpenSansRegularLabel *sectionTitleLabel;

@end

@implementation TransactionsHeaderView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self = [[[NSBundle mainBundle] loadNibNamed:@"TransactionsHeaderView" owner:self options:nil] lastObject];
        self.backgroundColor = [Utilities colorFromHexString:@"#342F33"];
    }
    return self;
}

- (void)setTitle:(NSString *)title {
    self.sectionTitleLabel.text = [title uppercaseString];
    self.sectionTitleLabel.textColor = [Utilities colorFromHexString:@"#FFFFFF"];
}

@end


text:
'use strict';

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

var SessionSchema = new Schema({
  name: {
    type: String,
    trim: true,
    required: 'Please name the session'
  },
  items: {
    type: [{
      name: {
        type: String,
        trim: true,
        required: 'Please name the item'
      },
      description: {
        type: String,
        trim: true
      },
      estimates: [Number]
    }],
    activeItem: {
      type: {
        name: {
          type: String,
          trim: true,
          required: 'Please name the item'
        },
        description: {
          type: String,
          trim: true
        },
        estimates: [Number]
      }
    },

    default: []
  }
});

module.exports = mongoose.model('Session', SessionSchema);


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.04.07 at 04:43:56 PM EDT
//

package org.w3._1999.xlink;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *     Intended for use as the type of user-declared elements to make them
 *     extended links.
 *     Note that the elements referenced in the content model are all abstract.
 *     The intention is that by simply declaring elements with these as their
 *     substitutionGroup, all the right things will happen.
 *
 *
 *
Java class for extended complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="extended">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <group ref="{http://www.w3.org/1999/xlink}extendedModel" maxOccurs="unbounded" minOccurs="0"/>
 *       <attGroup ref="{http://www.w3.org/1999/xlink}extendedAttrs"/>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "extended", propOrder = {
    "extendedModel"
})
public class Extended
    implements Serializable
{

    private static final long serialVersionUID = -4831205231089058456L;
    @XmlElements({
        @XmlElement(name = "xtitle", type = TitleEltType.class),
        @XmlElement(name = "resource", type = ResourceType.class),
        @XmlElement(name = "locator", type = LocatorType.class),
        @XmlElement(name = "arc", type = ArcType.class)
    })
    protected List<Serializable> extendedModel;
    @XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink", required = true)
    protected TypeType type;
    @XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink")
    protected String role;
    @XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink")
    protected String title;

    /**
     * Gets the value of the extendedModel property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the extendedModel property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getExtendedModel().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link TitleEltType }
     * {@link ResourceType }
     * {@link LocatorType }
     * {@link ArcType }
     *
     *
     */
    public List<Serializable> getExtendedModel() {
        if (extendedModel == null) {
            extendedModel = new ArrayList<Serializable>();
        }
        return this.extendedModel;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link TypeType }
     *
     */
    public TypeType getType() {
        if (type == null) {
            return TypeType.EXTENDED;
        } else {
            return type;
        }
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link TypeType }
     *
     */
    public void setType(TypeType value) {
        this.type = value;
    }

    /**
     * Gets the value of the role property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRole() {
        return role;
    }

    /**
     * Sets the value of the role property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRole(String value) {
        this.role = value;
    }

    /**
     * Gets the value of the title property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTitle() {
        return title;
    }

    /**
     * Sets the value of the title property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTitle(String value) {
        this.title = value;
    }

}


text:
class TestStorage():
    def test_create(self, storage):
        key = storage.create("acsteststorage")
        assert key


text:
<?php

namespace GeoIPUpdater\GeoIP;

require_once(__DIR__.'/../GeoIP.php');

use \GeoIpUpdater\GeoIP;

/**
 * Class Lite
 * @package \GeoIpUpdater\GeoIP
 */
class Lite extends GeoIP {

    /**
     * Path to GeoIp DB files
     * @var string
     */
    protected $_sDbPath = GEOIP_LITE_DB_PATH;

    /**
     * Path to Archived GeoIp DB files
     * @var string
     */
    protected $_sArchiveDbPath = GEOIP_LITE_DB_ARCHIVE_PATH;

    /**
     * Path to a tmp dir where we temporarily store retrieved DB files
     * @var string
     */
    protected $_sTmpDbPath = GEOIP_LITE_DB_TMP_PATH;

    /**
     * Retrieves the DB files from MaxMind and stores them in the tmp folder.
     * @throws \Exception
     */
    protected function _retrieveDbFiles() {
        $this->_oLogger->log('DB files retrieval.');
        if (empty($this->_aDbFiles)) {
            throw new \Exception('There are no DB file to retrieve. Please check the DB URL CSV file in the resources dir.');
        }
        $this->_oLogger->log('There are '.count($this->_aDbFiles).' files to retrieve.');
        foreach ($this->_aDbFiles as $aDbFileSrc) {
            $sDbFileSrc = $aDbFileSrc[0];
            $this->_oLogger->log('Retrieving DB from '.$sDbFileSrc);
            $this->_oExtractor->extract($sDbFileSrc, $this->_sTmpDbPath);

            //Renaming and extracting .dat files to temp path root, remove extracted dirs
            $aDatFiles = $this->_oFileSystem->glob($this->_sTmpDbPath.DIRECTORY_SEPARATOR."*".$this->_sDbFileExtension);
            foreach ($aDatFiles as $sDatFile) {
                if (strpos($sDatFile, 'GeoLiteCity.dat')) {
                    $sDBName = 'GeoIPCity.dat';
                } else {
                    $sDBName = basename($sDatFile);
                }
                $this->_oFileSystem->rename($sDatFile, $this->_sTmpDbPath.DIRECTORY_SEPARATOR.$sDBName);
            }
        }
    }

    /**
     * @return mixed|void
     * @throws \Exception
     */
    protected function _checkConfig() {
        return true;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ruleset Braces Rules</title>
<link rel="stylesheet" href="ruleset.css" type="text/css">
<link rel="stylesheet" href="nbdocs:/org/netbeans/modules/usersguide/ide.css" type="text/css">

Ruleset Braces Rules

Index

                    Language -

Description

The Braces Ruleset contains a collection of braces rules.

IfStmtsMustUseBraces::

WhileLoopsMustUseBraces::

IfElseStmtsMustUseBraces::

ForLoopsMustUseBraces::

Rule IfStmtsMustUseBraces::

TOC

Description

Avoid using if statements without using curly braces.

Message

Avoid using if statements without curly braces

Class

net.sourceforge.pmd.rules.XPathRule

Reference

-

ExternalInfoUrl

http://pmd.sourceforge.net/rules/braces.html#IfStmtsMustUseBraces

TypeResolution

-

Priority

3

Example

Example code snippet of this rule.

 public class Foo {
   public void bar() {
     int x = 0;
     if (foo) x++;
   }
 }

Properties

Following properties are defined:

Name

xpath

Description

-

Value

//IfStatement[count(*) < 3][not(Statement/Block)]

TOC

Rule WhileLoopsMustUseBraces::

TOC

Description

Avoid using 'while' statements without using curly braces.

Message

Avoid using 'while' statements without curly braces

Class

net.sourceforge.pmd.rules.XPathRule

Reference

-

ExternalInfoUrl

http://pmd.sourceforge.net/rules/braces.html#WhileLoopsMustUseBraces

TypeResolution

-

Priority

3

Example

Example code snippet of this rule.

public void doSomething() {
  while (true)
      x++;
}

Properties

Following properties are defined:

Name

xpath

Description

-

Value

//WhileStatement[not(Statement/Block)]

TOC

Rule IfElseStmtsMustUseBraces::

TOC

Description

Avoid using if..else statements without using curly braces.

Message

Avoid using 'if...else' statements without curly braces

Class

net.sourceforge.pmd.rules.XPathRule

Reference

-

ExternalInfoUrl

http://pmd.sourceforge.net/rules/braces.html#IfElseStmtsMustUseBraces

TypeResolution

-

Priority

3

Example

Example code snippet of this rule.

 public void doSomething() {
   // this is OK
   if (foo) x++;
   // but this is not
   if (foo)
       x=x+1;
   else
       x=x-1;
 }

Properties

Following properties are defined:

Name

xpath

Description

-

Value

//Statement
 [parent::IfStatement[@Else='true']]
 [not(child::Block)]
 [not(child::IfStatement)]

TOC

Rule ForLoopsMustUseBraces::

TOC

Description

Avoid using 'for' statements without using curly braces.

Message

Avoid using 'for' statements without curly braces

Class

net.sourceforge.pmd.rules.XPathRule

Reference

-

ExternalInfoUrl

http://pmd.sourceforge.net/rules/braces.html#ForLoopsMustUseBraces

TypeResolution

-

Priority

3

Example

Example code snippet of this rule.

public void foo() {
 for (int i=0; i<42;i++)
   foo();
}

Properties

Following properties are defined:

Name

xpath

Description

-

Value

//ForStatement[not(Statement/Block)]

TOC


text:
class FloatBuilder

  def initialize ()
    @Float = TauObject.new($Class, "<class 'Int'>")
  end

  def make (params)
    TauObject.new(@Float, params[0].value.to_f)
  end

  def equ (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then
        z = x.value == y.value
        # return the singletons not a new value
        if z == true then $true else $false end
      when @Float then
        z = x.value == y.value
        if z == true then $true else $false end
      else
        $false
      end
    result
  end

  def neq (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then
        z = x.value != y.value
        # return the singletons not a new value
        if z == true then $true else $false end
      when @Float then
        z = x.value != y.value
        if z == true then $true else $false end
      else
        $true
      end
    result
  end

  def gt (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then TauObject.new($Bool, x.value > y.value)
      when @Float then TauObject.new($Bool, x.value > y.value)
      else
        TauObject.new($Exception, "Type error: unsupported operand types for >: Float and <other>")
      end
    result
  end

  def lt (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then TauObject.new($Bool, x.value < y.value)
      when @Float then TauObject.new($Bool, x.value < y.value)
      else
        TauObject.new($Exception, "Type error: unsupported operand types for <: Float and <other>")
      end
    result
  end

  def ge (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then TauObject.new($Bool, x.value >= y.value)
      when @Float then TauObject.new($Bool, x.value >= y.value)
      else
        TauObject.new($Exception, "Type error: unsupported operand types for >=: Float and <other>")
      end
    result
  end

  def le (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then TauObject.new($Bool, x.value <= y.value)
      when @Float then TauObject.new($Bool, x.value <= y.value)
      else
        TauObject.new($Exception, "Type error: unsupported operand types for <=: Float and <other>")
      end
    result
  end

  def add (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then TauObject.new(@Float, x.value + y.value)
      when @Float then TauObject.new(@Float, x.value + y.value)
      else
        TauObject.new($Exception, "Type error: unsupported operand types for +: Float and <other>")
      end
    result
  end

  def sub (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then TauObject.new(@Float, x.value - y.value)
      when @Float then TauObject.new(@Float, x.value - y.value)
      else
        TauObject.new($Exception, "Type error: unsupported operand types for -: Float and <other>")
      end
    result
  end

  def mul (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then TauObject.new(@Float, x.value * y.value)
      when @Float then TauObject.new(@Float, x.value * y.value)
      else
        TauObject.new($Exception, "Type error: unsupported operand types for *: Float and <other>")
      end
    result
  end

  def div (params)
    x = params[0]
    y = params[1]
    result =
      case y.type
      when $Int then TauObject.new(@Float, x.value / y.value)
      when @Float then TauObject.new(@Float, x.value / y.value)
      else
        TauObject.new($Exception, "Type error: unsupported operand types for /: Float and <other>")
      end
    result
  end

  def neg (params)
    x = params[0]
    result = TauObject.new(@Float, -x.value)
    result
  end

  def not (params)
    # Need to think about truthy vs. falsy values
    # Do we follow the python/javascript model or the ruby model?
    result = $false
    result
  end

  def toString (params)
    x = params[0]
    result = TauObject.new($String, x.value.to_s)
  end

  def classObj ()
    @Float
  end

  def build ()
    @Float.setMember('super', $Any)

    # Perhaps the value should be an array or some kind of 'NativeCode' ruby
    # object that the interpreter will distinguish at runtime. An array will
    # work for now.  Array is of the form [numParams, code].
    makeFun = TauObject.new($Function, [1, method(:make)])
    @Float.setMember('make', makeFun)

    @Float.setMember('equ', TauObject.new($Function, [2, method(:equ)]))
    @Float.setMember('neq', TauObject.new($Function, [2, method(:neq)]))
    @Float.setMember('gt', TauObject.new($Function, [2, method(:gt)]))
    @Float.setMember('lt', TauObject.new($Function, [2, method(:lt)]))
    @Float.setMember('ge', TauObject.new($Function, [2, method(:ge)]))
    @Float.setMember('le', TauObject.new($Function, [2, method(:le)]))
    @Float.setMember('add', TauObject.new($Function, [2, method(:add)]))
    @Float.setMember('sub', TauObject.new($Function, [2, method(:sub)]))
    @Float.setMember('mul', TauObject.new($Function, [2, method(:mul)]))
    @Float.setMember('div', TauObject.new($Function, [2, method(:div)]))
    @Float.setMember('neg', TauObject.new($Function, [1, method(:neg)]))
    @Float.setMember('not', TauObject.new($Function, [1, method(:not)]))
    @Float.setMember('toString', TauObject.new($Function, [1, method(:toString)]))
  end

end # class


text:
/**
 * Block argument types
 * @enum {string}
 */
const ArgumentType = {
    /**
     * Numeric value with angle picker
     */
    ANGLE: 'angle',

    /**
     * Boolean value with hexagonal placeholder
     */
    BOOLEAN: 'Boolean',

    /**
     * Numeric value with color picker
     */
    COLOR: 'color',

    /**
     * Numeric value with text field
     */
    NUMBER: 'number',

    /**
     * String value with text field
     */
    STRING: 'string',

    /**
     * String value with matrix field
     */
    MATRIX: 'matrix',

    /**
     * MIDI note number with note picker (piano) field
     */
    NOTE: 'note',

    /**
     * Inline image on block (as part of the label)
     */
    IMAGE: 'image'
};

module.exports = ArgumentType;


text:
/* $Id$ */

package org.apache.fop.render.afp.extensions;

import org.xml.sax.ContentHandler;

import org.apache.fop.util.ContentHandlerFactory;

/**
 * Factory for the ContentHandler that handles serialized AFPPageSetup instances.
 */
public class AFPExtensionHandlerFactory implements ContentHandlerFactory {

    private static final String[] NAMESPACES = new String[] {AFPPageSetup.CATEGORY};

    /** {@inheritDoc} */
    public String[] getSupportedNamespaces() {
        return NAMESPACES;
    }

    /** {@inheritDoc} */
    public ContentHandler createContentHandler() {
        return new AFPExtensionHandler();
    }
}


text:
module Shoppe
  class OrderItem < ActiveRecord::Base

    self.table_name = 'shoppe_order_items'

    # The associated order
    #
    # @return [Shoppe::Order]
    belongs_to :order, :class_name => 'Shoppe::Order', :touch => true, :inverse_of => :order_items

    # The item which has been ordered
    belongs_to :ordered_item, :polymorphic => true

    # Any stock level adjustments which have been made for this order item
    has_many :stock_level_adjustments, :as => :parent, :dependent => :nullify, :class_name => 'Shoppe::StockLevelAdjustment'

    # Validations
    validates :quantity, :numericality => true
    validates :ordered_item, :presence => true
    attr_accessible :order_id,:ordered_item_id,:ordered_item_type,:quantity,:unit_price,:unit_cost_price,:tax_amount,:tax_rate,:weight,:created_at,:updated_at
    validate do
      unless in_stock?
        errors.add :quantity, :too_high_quantity
      end
    end

    # Before saving an order item which belongs to a received order, cache the pricing again if appropriate.
    before_save do
      if order.received? && (unit_price_changed? || unit_cost_price_changed? || tax_rate_changed? || tax_amount_changed?)
        cache_pricing
      end
    end

    # After saving, if the order has been shipped, reallocate stock appropriate
    after_save do
      if order.shipped?
        allocate_unallocated_stock!
      end
    end

    # This allows you to add a product to the scoped order. For example Order.first.order_items.add_product(...).
    # This will either increase the quantity of the value in the order or create a new item if one does not
    # exist already.
    #
    # @param ordered_item [Object] an object which implements the Shoppe::OrderableItem protocol
    # @param quantity [Fixnum] the number of items to order
    # @return [Shoppe::OrderItem]
    def self.add_item(ordered_item, quantity = 1)
      raise Errors::UnorderableItem, :ordered_item => ordered_item unless ordered_item.orderable?
      transaction do
        if existing = self.where(:ordered_item_id => ordered_item.id, :ordered_item_type => ordered_item.class.to_s).first
          existing.increase!(quantity)
          existing
        else
          new_item = self.create(:ordered_item => ordered_item, :quantity => 0)
          new_item.increase!(quantity)
          new_item
        end
      end
    end

    # Remove a product from an order. It will also ensure that the order's custom delivery
    # service is updated if appropriate.
    #
    # @return [Shoppe::OrderItem]
    def remove
      transaction do
        self.destroy!
        self.order.remove_delivery_service_if_invalid
        self
      end
    end

    # Increases the quantity of items in the order by the number provided. Will raise an error if we don't have
    # the stock to do this.
    #
    # @param quantity [Fixnum]
    def increase!(amount = 1)
      transaction do
        self.quantity += amount
        unless self.in_stock?
          raise Shoppe::Errors::NotEnoughStock, :ordered_item => self.ordered_item, :requested_stock => self.quantity
        end
        self.save!
        self.order.remove_delivery_service_if_invalid
      end
    end

    # Decreases the quantity of items in the order by the number provided.
    #
    # @param amount [Fixnum]
    def decrease!(amount = 1)
      transaction do
        self.quantity -= amount
        self.quantity == 0 ? self.destroy : self.save!
        self.order.remove_delivery_service_if_invalid
      end
    end

    # The total weight of the item
    #
    # @return [BigDecimal]
    def weight
      read_attribute(:weight) || ordered_item.try(:weight) || BigDecimal(0)
    end

    # Return the total weight of the item
    #
    # @return [BigDecimal]
    def total_weight
      quantity * weight
    end

    # The unit price for the item
    #
    # @return [BigDecimal]
    def unit_price
      read_attribute(:unit_price) || ordered_item.try(:price) || BigDecimal(0)
    end

    # The cost price for the item
    #
    # @return [BigDecimal]
    def unit_cost_price
      read_attribute(:unit_cost_price) || ordered_item.try(:cost_price) || BigDecimal(0)
    end

    # The tax rate for the item
    #
    # @return [BigDecimal]
    def tax_rate
      read_attribute(:tax_rate) || ordered_item.try(:tax_rate).try(:rate_for, self.order) || BigDecimal(0)
    end

    # The total tax for the item
    #
    # @return [BigDecimal]
    def tax_amount
      read_attribute(:tax_amount) || (self.sub_total / BigDecimal(100)) * self.tax_rate
    end

    # The total cost for the product
    #
    # @return [BigDecimal]
    def total_cost
      quantity * unit_cost_price
    end

    # The sub total for the product
    #
    # @return [BigDecimal]
    def sub_total
      quantity * unit_price
    end

    # The total price including tax for the order line
    #
    # @return [BigDecimal]
    def total
      tax_amount + sub_total
    end

    # Cache the pricing for this order item
    def cache_pricing
      write_attribute :weight, self.weight
      write_attribute :unit_price, self.unit_price
      write_attribute :unit_cost_price, self.unit_cost_price
      write_attribute :tax_rate, self.tax_rate
    end

    # Cache the pricing for this order item and save
    def cache_pricing!
      cache_pricing
      save!
    end

    # Trigger when the associated order is confirmed. It handles caching the values
    # of the monetary items and allocating stock as appropriate.
    def confirm!
      cache_pricing!
      allocate_unallocated_stock!
    end

    # Trigger when the associated order is accepted
    def accept!
    end

    # Trigged when the associated order is rejected..
    def reject!
      self.stock_level_adjustments.destroy_all
    end

    # Do we have the stock needed to fulfil this order?
    #
    # @return [Boolean]
    def in_stock?
      if self.ordered_item && self.ordered_item.stock_control?
        self.ordered_item.stock >= unallocated_stock
      else
        true
      end
    end

    # How much stock remains to be allocated for this order?
    #
    # @return [Fixnum]
    def unallocated_stock
      self.quantity - allocated_stock
    end

    # How much stock has been allocated to this item?
    #
    # @return [Fixnum]
    def allocated_stock
      0 - self.stock_level_adjustments.sum(:adjustment)
    end

    # Validate the stock level against the product and update as appropriate. This method will be executed
    # before an order is completed. If we have run out of this product, we will update the quantity to an
    # appropriate level (or remove the order item) and return the object.
    def validate_stock_levels
      if in_stock?
        false
      else
        self.quantity = self.ordered_item.stock
        self.quantity == 0 ? self.destroy : self.save!
        self
      end
    end

    # Allocate any unallocated stock for this order item. There is no return value.
    def allocate_unallocated_stock!
      if self.ordered_item.stock_control? && self.unallocated_stock != 0
        self.ordered_item.stock_level_adjustments.create!(:parent => self, :adjustment => 0 - self.unallocated_stock, :description => "Order ##{self.order.number}")
      end
    end

  end
end


text:
package org.jboss.arquillian.warp.spi;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicReference;

import org.jboss.arquillian.warp.spi.exception.ObjectAlreadyAssociatedException;
import org.jboss.arquillian.warp.spi.exception.ObjectNotAssociatedException;
import org.jboss.arquillian.warp.spi.exception.StoreHasAssociatedObjectsException;

/**
 *

 * Holds associations of {@link LifecycleManager} with arbitrary objects.
 *

 *
 *

 * In order to store binding, one can need to use object and its class/interface as key.
 *

 *
 *

 * Once the binding is stored, one can use that object together with key to restore associated {@link LifecycleManager}.
 *

 *
 *

 * This way, {@link LifecycleManager} can be propagated to arbitrary contexts without need of shared store (particularly this
 * principle avoids use of {@link ThreadLocal} store.
 *

 *
 *

 * Storing current references:
 *

 *
 *

 *
 *
 * @author Lukas Fryc
 */
public abstract class LifecycleManagerStore {

    private static AtomicReference<LifecycleManagerStore> INSTANCE = new AtomicReference<LifecycleManagerStore>();

    /**
     * Retrieves instance of {@link LifecycleManager} for given instance of given class.
     *
     * @param clazz the class used as denominator during retrieval
     * @param boundObject the object used as key for retriving {@link LifecycleManager}
     * @return the bound instance of {@link LifecycleManager}
     * @throws ObjectNotAssociatedException when instance of no such class and class' instance was associated with any
     *         {@link LifecycleManager}
     */
    public static <T> LifecycleManager get(Class<T> type, T boundObject) throws ObjectNotAssociatedException {
        return getCurrentStore().obtain(type, boundObject);
    }

    /**
     * Provides implementation of binding a current {@link LifecycleManager} with given object of given class.
     *
     * @param clazz the class to be bound
     * @param object the object to be bound
     * @throws ObjectAlreadyAssociatedException when there is already object bound with {@link LifecycleManager} for given
     *         class.
     */
    protected abstract <T> void bind(LifecycleManager manager, Class<T> clazz, T object)
            throws ObjectAlreadyAssociatedException;

    /**
     * Provides implementation of binding a {@link LifecycleManager} for given class and given object.
     *
     * @param clazz the bound class
     * @param object the bound class
     * @throws ObjectNotAssociatedException when no object bound with {@link LifecycleManager}.
     */
    protected abstract <T> void unbind(LifecycleManager manager, Class<T> clazz, T object) throws ObjectNotAssociatedException;

    /**
     *

     * Checks that given manager does not have any associations in context of current store.
     *

     *
     *

     * It ensures that all managers associated with {@link #bind(LifecycleManager, Class, Object)} was properly unbound with
     * {@link #unbind(LifecycleManager, Class, Object)}.
     *

     *
     * @param manager
     * @throws ObjectNotAssociatedException
     */
    protected abstract <T> void checkUnbound(LifecycleManager manager) throws StoreHasAssociatedObjectsException;

    /**
     * Provides implementation of obtaining {@link LifecycleManager} for given instance of given class.
     *
     * @param clazz the class used as denominator during retrieval
     * @param boundObject the object used as key for retriving {@link LifecycleManager}
     * @return the bound instance of {@link LifecycleManager}
     * @throws ObjectNotAssociatedException when instance of no such class and class' instance was associated with any
     *         {@link LifecycleManager}
     */
    protected abstract <T> LifecycleManager obtain(Class<T> clazz, T object) throws ObjectNotAssociatedException;

    /**
     * Retrieves instance of {@link LifecycleManager} for given instance of given class.
     *
     * @param clazz the class used as denominator during retrieval
     * @param boundObject the object used as key for retriving {@link LifecycleManager}
     * @return the bound instance of {@link LifecycleManager}
     * @throws ObjectNotAssociatedException when instance of no such class and class' instance was associated with any
     *         {@link LifecycleManager}
     */
    static LifecycleManagerStore getCurrentStore() {
        LifecycleManagerStore store = INSTANCE.get();
        if (store != null) {
            return store;
        }

        try {
            InputStream resourceAsStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("META-INF/services/" + LifecycleManagerStore.class.getName());

            if (resourceAsStream != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream));
                String type = reader.readLine();
                store = (LifecycleManagerStore) Class.forName(type).newInstance();
                INSTANCE.compareAndSet(null, store);
                return INSTANCE.get();
            }
        } catch (Exception e) {
            throw new IllegalStateException("Cannot load " + LifecycleManagerStore.class.getSimpleName() + " service", e);
        }

        throw new IllegalStateException("No " + LifecycleManagerStore.class.getSimpleName() + " service is defined");
    }
}


text:
<?php

namespace WeLoveKpop\MostPlayed;

/**
 * Hooks!
 */
class Plugin
{
    /**
     * Initialise the plugin.
     *
     * @return void
     */
    public static function init()
    {
        add_shortcode(
            'sekshi-most-played',
            'WeLoveKpop\MostPlayed\MostPlayedPage::shortcode'
        );
        add_shortcode(
            'sekshi-history',
            'WeLoveKpop\MostPlayed\HistoryPage::shortcode'
        );
    }

    /**
     * "menu" hook, adds the options page.
     */
    public static function menu()
    {
        add_menu_page(
            'SekshiBot',
            'SekshiBot',
            'read',
            'sekshibot',
            'WeLoveKpop\MostPlayed\Admin\OptionsPage::show',
            plugins_url('../css/icons/sekshi.png', __FILE__)
        );

        // set submenu item name
        add_submenu_page(
            'sekshibot',
            'SekshiBot Options',
            'General',
            'read',
            'sekshibot',
            'WeLoveKpop\MostPlayed\Admin\OptionsPage::show'
        );

        add_submenu_page(
            'sekshibot',
            'SekshiBot - Media',
            'Media',
            'activate_plugins',
            'sekshibot-media',
            'WeLoveKpop\MostPlayed\Admin\MediaPage::show'
        );
    }

    /**
     * Registers settings for the settings page.
     */
    public static function registerSettings()
    {
        register_setting('wlkmp_options', 'wlkmp_mongo_uri');
        register_setting('wlkmp_options', 'wlkmp_mongo_name');
    }
}


text:
import {jsonLiteral} from '../../../../src/json';

const RAKAM_CONFIG = jsonLiteral({
  'vars': {
    'deviceId': 'CLIENT_ID(rakam_device_id)',
  },
  'requests': {
    'base':
      '?api.api_key=${writeKey}' +
      '&prop._platform=amp' +
      '&prop._device_id=${deviceId}' +
      '&prop.locale=${browserLanguage}' +
      '&prop.path=${canonicalPath}' +
      '&prop.url=${canonicalUrl}' +
      '&prop.color_depth=${screenColorDepth}' +
      '&prop._referrer=${documentReferrer}' +
      '&prop.title=${title}' +
      '&prop.timezone=${timezone}' +
      '&prop._time=${timestamp}' +
      '&prop.resolution=${screenWidth} × ${screenHeight}',
    'pageview':
      'https://${apiEndpoint}/event/pixel${base}&collection=${pageViewName}',
    'custom':
      'https://${apiEndpoint}/event/pixel${base}&collection=${collection}',
  },
});

export {RAKAM_CONFIG};


text:
@echo off
rem
rem Copyright (c) 2014 Luca Garulli @www.orientechnologies.com
rem
rem Guess ORIENTDB_HOME if not defined
set CURRENT_DIR=%cd%

if exist "%JAVA_HOME%\bin\java.exe" goto setJavaHome
set JAVA="java"
goto okJava

:setJavaHome
set JAVA="%JAVA_HOME%\bin\java"

:okJava
if not "%ORIENTDB_HOME%" == "" goto gotHome
set ORIENTDB_HOME=%CURRENT_DIR%
if exist "%ORIENTDB_HOME%\bin\oetl.bat" goto okHome
cd ..
set ORIENTDB_HOME=%cd%
cd %CURRENT_DIR%

:gotHome
if exist "%ORIENTDB_HOME%\bin\oetl.bat" goto okHome
echo The ORIENTDB_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program
goto end

:okHome
rem Get remaining unshifted command line arguments and save them in the
set CMD_LINE_ARGS=

:setArgs
if ""%1""=="""" goto doneSetArgs
set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
shift
goto setArgs

:doneSetArgs

set KEYSTORE=%ORIENTDB_HOME%\config\cert\orientdb-console.ks
set KEYSTORE_PASS=password
set TRUSTSTORE=%ORIENTDB_HOME%\config\cert\orientdb-console.ts
set TRUSTSTORE_PASS=password
set SSL_OPTS="-Dclient.ssl.enabled=false -Djavax.net.ssl.keyStore=%KEYSTORE% -Djavax.net.ssl.keyStorePassword=%KEYSTORE_PASS% -Djavax.net.ssl.trustStore=%TRUSTSTORE% -Djavax.net.ssl.trustStorePassword=%TRUSTSTORE_PASS%"

set ORIENTDB_SETTINGS=-Xmx512m -Djava.util.logging.config.file="%ORIENTDB_HOME%\config\orientdb-client-log.properties" -Djava.awt.headless=true
call %JAVA% -server %SSL_OPTS% %ORIENTDB_SETTINGS% -Dfile.encoding=utf-8 -Dorientdb.build.number="@BUILD@" -cp "%ORIENTDB_HOME%\lib\*;" com.orientechnologies.orient.etl.OETLProcessor %CMD_LINE_ARGS%

:end