text:
const webpack = require("webpack");

module.exports = {
    context : __dirname + "/../static/scripts/",

    output : {
        path : __dirname + "/../.tmp/static/scripts/",
        filename : "[name].js",
    },

    devtool : "inline-source-map",

    resolve : {
        root : [
            (__dirname + "/../static/scripts/"),
        ],

        extensions : [
            "",
            ".js",
        ],

        modulesDirectories  : [
            "node_modules",
        ],

        alias : {
            "views" : __dirname + "/../views/",
            "socket.io" : "socket.io-client"
        },

        module : {
            loaders : [

            ],
        },
    },

    plugins : [
        new webpack.ResolverPlugin([
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("package.json", ["main"]),
        ]),
    ]
};


text:
**Digital Waveform Graph** transforms channel so that it will plot on a Digital Waveform Chart.  A channel is made into an array of booleans based upon a threshold value and then displayed.  This graph is similar to the Digital Waveform Chart in LabVIEW, but with some limited functionality.

### LabVIEW Version ###

LabVIEW 2010

### Built Availability ###

No builds are available.

### Quality, Limitations ###

This IP was made in 2010 and has not been tested since. There are no known users of the IP. Proceed with caution.

### License ###

*This repository and any materials provided by NI therein are provided AS IS. NI DISCLAIMS ANY AND ALL LIABILITIES FOR AND MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR  PARTICULAR PURPOSE, OR NON-INFRINGEMENT OF INTELLECTUAL PROPERTY. NI shall have no liability for any direct, indirect, incidental, punitive, special, or consequential damages for your use of the repository or any materials contained therein.*

redpajama_set_name: RedPajamaGithub


text:
package org.kie.workbench.common.services.backend.social;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.ext.uberfire.social.activities.model.DefaultTypes;
import org.ext.uberfire.social.activities.model.PagedSocialQuery;
import org.ext.uberfire.social.activities.model.SocialActivitiesEvent;
import org.ext.uberfire.social.activities.model.SocialEventType;
import org.ext.uberfire.social.activities.model.SocialPaged;
import org.ext.uberfire.social.activities.model.SocialUser;
import org.ext.uberfire.social.activities.service.SocialAdapter;
import org.ext.uberfire.social.activities.service.SocialAdapterRepositoryAPI;
import org.ext.uberfire.social.activities.service.SocialCommandTypeFilter;
import org.ext.uberfire.social.activities.service.SocialTimeLineRepositoryAPI;
import org.ext.uberfire.social.activities.service.SocialTypeTimelinePagedRepositoryAPI;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.*;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class SocialTimelineRulesQueryTest {

    @Mock
    private SocialTimeLineRepositoryAPI socialTimeLineRepositoryAPI;

    @Mock
    private SocialTypeTimelinePagedRepositoryAPI socialTypeTimelinePagedRepositoryAPI;

    @Mock
    private SocialAdapterRepositoryAPI socialAdapterRepositoryAPI;

    @Mock
    private PagedSocialQuery pagedSocialQuery;

    private SocialTimelineRulesQuery query;

    @Before
    public void setup() {
        this.query = new SocialTimelineRulesQuery(socialTimeLineRepositoryAPI,
                                                  socialTypeTimelinePagedRepositoryAPI,
                                                  socialAdapterRepositoryAPI);
        when(socialTimeLineRepositoryAPI.getLastEventTimeline(anyString(),
                                                              anyMap())).thenReturn(Collections.singletonList(makeMockEvent()));
        when(socialAdapterRepositoryAPI.getSocialAdapters()).thenReturn(new HashMap<Class, SocialAdapter>() {{
            put(TestSocialEvent.class,
                new TestSocialAdaptor());
        }});
        when(socialTypeTimelinePagedRepositoryAPI.getEventTimeline(anyString(),
                                                                   any(SocialPaged.class),
                                                                   anyMap())).thenReturn(pagedSocialQuery);
        when(pagedSocialQuery.socialEvents()).thenReturn(Collections.singletonList(makeMockEvent()));
    }

    @Test
    public void checkKSessionInstantiation() {
        final List<SocialActivitiesEvent> events = query.executeAllRules();
        assertNotNull(events);
    }

    private SocialActivitiesEvent makeMockEvent() {
        return new SocialActivitiesEvent().withAdicionalInfo("info");
    }

    private static class TestSocialEvent {

    }

    private static class TestSocialAdaptor implements SocialAdapter<TestSocialEvent> {

        @Override
        public Class<TestSocialEvent> eventToIntercept() {
            return TestSocialEvent.class;
        }

        @Override
        public SocialEventType socialEventType() {
            return DefaultTypes.DUMMY_EVENT;
        }

        @Override
        public boolean shouldInterceptThisEvent(final Object event) {
            return event.getClass().getSimpleName().equals(eventToIntercept().getSimpleName());
        }

        @Override
        public SocialActivitiesEvent toSocial(final Object object) {
            return new SocialActivitiesEvent(new SocialUser("user"),
                                             socialEventType().name(),
                                             new Date()
            ).withDescription("test adaptor").withAdicionalInfo("info");
        }

        @Override
        public List<SocialCommandTypeFilter> getTimelineFilters() {
            return new ArrayList<>();
        }

        @Override
        public List<String> getTimelineFiltersNames() {
            return new ArrayList<>();
        }
    }
}


text:
layout: media
title: "Padrão de criação - Singleton"
categories: design_patterns
author: cristiano
date: 2021-09-07 02:00:00
tags: [java, design patterns, singleton]
published: true
excerpt: Exemplo do padrão de projeto Singleton em Java.
comments: true
image:
  teaser: 2022-09-07-teaser-design-pattern-singleton.png
ads: false
---

Exemplo do padrão de projeto Singleton em Java

<iframe width="420" height="315" src="https://www.youtube.com/embed/XmHMRmjxVmo" frameborder="0" allowfullscreen></iframe>


text:
<?php

namespace Munisense\Zigbee\APS;
use Munisense\Zigbee\AbstractFrame;
use Munisense\Zigbee\Buffer;
use Munisense\Zigbee\Exception\ZigbeeException;
use Munisense\Zigbee\IFrame;
use Munisense\Zigbee\ZCL\ZCLFrame;
use Munisense\Zigbee\ZDP\ZDPFrame;

/**
 * Zigbee Specification: 2.2.5.1
 */
class APSFrame extends AbstractFrame implements IFrame
  {
  // Zigbee Specification: 2.2.5.1.1
  const FRAME_TYPE_DATA = 0x00;
  const FRAME_TYPE_COMMAND = 0x01;
  const FRAME_TYPE_ACKNOWLEDGE = 0x02;
  private $frame_type = self::FRAME_TYPE_DATA;

  // Zigbee Specification: 2.2.5.1.2
  const DELIVERY_MODE_UNICAST = 0x00;
  const DELIVERY_MODE_INDIRECT = 0x01;
  const DELIVERY_MODE_BROADCAST = 0x02;
  const DELIVERY_MODE_GROUP_ADDRESS = 0x03;
  private $delivery_mode = self::DELIVERY_MODE_UNICAST;

  // Zigbee Specification: 2.2.5.1.3
  const ACK_FORMAT_DATA = 0x00;
  const ACK_FORMAT_COMMAND = 0x01;
  private $ack_format = self::ACK_FORMAT_DATA;

  // Zigbee Specification: 2.2.5.1.4
  const SECURITY_DISABLED = 0x00;
  const SECURITY_ENABLED = 0x01;
  private $security = self::SECURITY_DISABLED;

  // Zigbee Specification: 2.2.5.1.5
  const ACK_REQUEST_DISABLED = 0x00;
  const ACK_REQUEST_ENABLED = 0x01;
  private $ack_request = self::ACK_REQUEST_DISABLED;

  // Zigbee Specification: 2.2.5.1.6
  const EXT_HEADER_NOT_PRESENT = 0x00;
  const EXT_HEADER_IS_PRESENT = 0x01;
  private $ext_header_present = self::EXT_HEADER_NOT_PRESENT;

  // Zigbee Specification: 2.2.5.8.1
  const FRAGMENTATION_DISABLED = 0x00;
  const FRAGMENTATION_FIRST = 0x01;
  const FRAGMENTATION_FOLLOWING = 0x02;
  private $fragmentation = self::FRAGMENTATION_DISABLED;

  // Zigbee Specification: 2.2.5.1.8.2
  private $frag_block_number = 0;

  // Zigbee Specification: 2.2.5.1.8.3
  private $frag_ack_bitfield = 0b00000000;

  // Zigbee Specification: 2.2.5.1.2
  private $destination_endpoint = 0x00;

  // Zigbee Specification: 2.2.5.1.3
  private $group_address = 0x0000;

  // Zigbee Specification: 2.2.5.1.4
  private $cluster_id = 0x0000;

  // Zigbee Specification: 2.2.5.1.5
  private $profile_id = 0x0000;

  // Zigbee Specification: 2.2.5.1.6
  private $source_endpoint = 0x00;

  // Zigbee Specification: 2.2.5.1.7
  private $aps_counter = 0x00;

  // Zigbee Specification: 2.2.5.1.9
  private $payload = "";

  /**
   * Set all parameters of this object by parsing a frame
   *
   * @param string $frame Byte string of the APS frame
   * @return void
   * @throws ZigbeeException
   */
  public function setFrame($frame)
    {
    $this->setFrameControl(Buffer::unpackInt8u($frame));

    if($this->isGroupAddressPresent())
      $this->setGroupAddress(Buffer::unpackInt16u($frame));

    if($this->isDestinationEndpointPresent())
      $this->setDestinationEndpoint(Buffer::unpackInt8u($frame));

    if($this->isClusterIdPresent())
      $this->setClusterId(Buffer::unpackInt16u($frame));

    if($this->isProfileIdPresent())
      $this->setProfileId(Buffer::unpackInt16u($frame));

    if($this->isSourceEndpointPresent())
      $this->setSourceEndpoint(Buffer::unpackInt8u($frame));

    $this->setApsCounter(Buffer::unpackInt8u($frame));

    if($this->isExtHeaderPresent())
      $this->setExtHeader(Buffer::unpackInt8u($frame));

    if($this->isFragBlockNumberPresent())
      $this->setFragBlockNumber(Buffer::unpackInt8u($frame));

    if($this->isFragAckBitfieldPresent())
      $this->setFragAckBitfield(Buffer::unpackInt8u($frame));

    if($this->isPayloadPresent())
      $this->setPayload($frame);
    elseif(strlen($frame) > 0)
      throw new ZigbeeException("Unparsed data (".strlen($frame)." bytes) at end of frame");
    }

  /**
   * Get the current frame.
   *
   * @return string Frame
   */
  public function getFrame()
    {
    $frame = "";

    Buffer::packInt8u($frame, $this->getFrameControl());

    if($this->isGroupAddressPresent())
      Buffer::packInt16u($frame, $this->getGroupAddress());

    if($this->isDestinationEndpointPresent())
      Buffer::packInt8u($frame, $this->getDestinationEndpoint());

    if($this->isClusterIdPresent())
      Buffer::packInt16u($frame, $this->getClusterId());

    if($this->isProfileIdPresent())
      Buffer::packInt16u($frame, $this->getProfileId());

    if($this->isSourceEndpointPresent())
      Buffer::packInt8u($frame, $this->getSourceEndpoint());

    Buffer::packInt8u($frame, $this->getApsCounter());

    if($this->isExtHeaderPresent())
      Buffer::packInt8u($frame, $this->getExtHeader());

    if($this->isFragBlockNumberPresent())
      Buffer::packInt8u($frame, $this->getFragBlockNumber());

    if($this->isFragAckBitfieldPresent())
      Buffer::packInt8u($frame, $this->getFragAckBitfield());

    if($this->isPayloadPresent())
      $frame .= $this->getPayload();

    return $frame;
    }

  public function setFrameControl($frame_control)
    {
    $frame_control = intval($frame_control);

    if($frame_control < 0x00 || $frame_control > 0xff)
      throw new ZigbeeException("Invalid frame control");

    $this->setFrameType(($frame_control >> 0) & 0x03);
    $this->setDeliveryMode(($frame_control >> 2) & 0x03);
    $this->setAckFormat(($frame_control >> 4) & 0x01);
    $this->setSecurity(($frame_control >> 5) & 0x01);
    $this->setAckRequest(($frame_control >> 6) & 0x01);
    $this->setExtHeaderPresent(($frame_control >> 7) & 0x01);
    }

  public function getFrameControl()
    {
    return ($this->getFrameType()        & 0x03) << 0 |
           ($this->getDeliveryMode()     & 0x03) << 2 |
           ($this->getAckFormat()        & 0x01) << 4 |
           ($this->getSecurity()         & 0x01) << 5 |
           ($this->getAckRequest()       & 0x01) << 6 |
           ($this->getExtHeaderPresent() & 0x01) << 7;
    }

  public function displayFrameControl()
    {
    return Buffer::displayBitmap8($this->getFrameControl());
    }

  public function setFrameType($frame_type)
    {
    $frame_type = intval($frame_type);

    if($frame_type < 0x00 || $frame_type > 0x02)
      throw new ZigbeeException("Invalid frame type");

    $this->frame_type = $frame_type;
    }

  public function getFrameType()
    {
    return $this->frame_type;
    }

  public function displayFrameType()
    {
    $frame_type = $this->getFrameType();
    switch($frame_type)
      {
      case self::FRAME_TYPE_DATA: $output = "Data"; break;
      case self::FRAME_TYPE_COMMAND: $output = "Command"; break;
      case self::FRAME_TYPE_ACKNOWLEDGE: $output = "Acknowledge"; break;
      default: $output = "unknown"; break;
      }

    return sprintf("%s (0x%02x)", $output, $frame_type);
    }

  public function setDeliveryMode($delivery_mode)
    {
    $delivery_mode = intval($delivery_mode);

    if($delivery_mode < 0x00 || $delivery_mode > 0x03)
      throw new ZigbeeException("Invalid delivery mode");

    $this->delivery_mode = $delivery_mode;
    }

  public function getDeliveryMode()
    {
    return $this->delivery_mode;
    }

  public function displayDeliveryMode()
    {
    $delivery_mode = $this->getDeliveryMode();
    switch($delivery_mode)
      {
      case self::DELIVERY_MODE_UNICAST: $output = "Unicast"; break;
      case self::DELIVERY_MODE_INDIRECT: $output = "Indirect"; break;
      case self::DELIVERY_MODE_BROADCAST: $output = "Broadcast"; break;
      case self::DELIVERY_MODE_GROUP_ADDRESS: $output = "Group Address"; break;
      default: $output = "unknown"; break;
      }

    return sprintf("%s (0x%02x)", $output, $delivery_mode);
    }

  public function setAckFormat($ack_format)
    {
    $this->ack_format = $ack_format ? self::ACK_FORMAT_COMMAND : self::ACK_FORMAT_DATA;
    }

  public function getAckFormat()
    {
    return $this->ack_format;
    }

  public function displayAckFormat()
    {
    $ack_format = $this->getAckFormat();
    switch($ack_format)
      {
      case self::ACK_FORMAT_DATA: $output = "Data"; break;
      case self::ACK_FORMAT_COMMAND: $output = "Command"; break;
      default: $output = "unknown"; break;
      }

    return sprintf("%s (0x%02x)", $output, $ack_format);
    }

  public function setSecurity($security)
    {
    $this->security = $security ? self::SECURITY_ENABLED : self::SECURITY_DISABLED;
    }

  public function getSecurity()
    {
    return $this->security;
    }

  public function displaySecurity()
    {
    $security = $this->getSecurity();
    switch($security)
      {
      case self::SECURITY_DISABLED: $output = "Disabled"; break;
      case self::SECURITY_ENABLED: $output = "Enabled"; break;
      default: $output = "unknown"; break;
      }

    return sprintf("%s (0x%02x)", $output, $security);
    }

  public function setAckRequest($ack_request)
    {
    $this->ack_request = $ack_request ? self::ACK_REQUEST_ENABLED : self::ACK_REQUEST_DISABLED;
    }

  public function getAckRequest()
    {
    return $this->ack_request;
    }

  public function displayAckRequest()
    {
    $ack_request = $this->getAckRequest();
    switch($ack_request)
      {
      case self::ACK_REQUEST_DISABLED: $output = "Disabled"; break;
      case self::ACK_REQUEST_ENABLED: $output = "Enabled"; break;
      default: $output = "unknown"; break;
      }

    return sprintf("%s (0x%02x)", $output, $ack_request);
    }

  public function setExtHeaderPresent($ext_header_present)
    {
    $this->ext_header_present = $ext_header_present ? self::EXT_HEADER_IS_PRESENT : self::EXT_HEADER_NOT_PRESENT;
    }

  public function getExtHeaderPresent()
    {
    return $this->ext_header_present;
    }

  public function displayExtHeaderPresent()
    {
    $ext_header_present = $this->getExtHeaderPresent();
    switch($ext_header_present)
      {
      case self::EXT_HEADER_NOT_PRESENT: $output = "Not Present"; break;
      case self::EXT_HEADER_IS_PRESENT: $output = "Present"; break;
      default: $output = "unknown"; break;
      }

    return sprintf("%s (0x%02x)", $output, $ext_header_present);
    }

  public function setDestinationEndpoint($destination_endpoint)
    {
    $destination_endpoint = intval($destination_endpoint);
    if($destination_endpoint < 0x00 || $destination_endpoint > 0xff)
      throw new ZigbeeException("Invalid destination endpoint");

    $this->destination_endpoint = $destination_endpoint;
    }

  public function getDestinationEndpoint()
    {
    return $this->destination_endpoint;
    }

  public function displayDestinationEndpoint()
    {
    return sprintf("0x%02x", $this->getDestinationEndpoint());
    }

  public function setGroupAddress($group_address)
    {
    $group_address = intval($group_address);
    if($group_address < 0x00 || $group_address > 0xffff)
      throw new ZigbeeException("Invalid group address");

    $this->group_address = $group_address;
    }

  public function getGroupAddress()
    {
    return $this->group_address;
    }

  public function displayGroupAddress()
    {
    return sprintf("0x%04x", $this->getGroupAddress());
    }

  public function setClusterId($cluster_id)
    {
    $cluster_id = intval($cluster_id);
    if($cluster_id < 0x00 || $cluster_id > 0xffff)
      throw new ZigbeeException("Invalid cluster id");

    $this->cluster_id = $cluster_id;
    }

  public function getClusterId()
    {
    return $this->cluster_id;
    }

  public function displayClusterId()
    {
    return sprintf("0x%04x", $this->getClusterId());
    }

  public function setProfileId($profile_id)
    {
    $profile_id = intval($profile_id);
    if($profile_id < 0x00 || $profile_id > 0xffff)
      throw new ZigbeeException("Invalid profile id");

    $this->profile_id = $profile_id;
    }

  public function getProfileId()
    {
    return $this->profile_id;
    }

  public function displayProfileId()
    {
    return sprintf("0x%04x", $this->getProfileId());
    }

  public function setSourceEndpoint($source_endpoint)
    {
    $source_endpoint = intval($source_endpoint);
    if($source_endpoint < 0x00 || $source_endpoint > 0xff)
      throw new ZigbeeException("Invalid source endpoint");

    $this->source_endpoint = $source_endpoint;
    }

  public function getSourceEndpoint()
    {
    return $this->source_endpoint;
    }

  public function displaySourceEndpoint()
    {
    return sprintf("0x%02x", $this->getSourceEndpoint());
    }

  public function setApsCounter($aps_counter)
    {
    $aps_counter = intval($aps_counter);
    if($aps_counter < 0x00 || $aps_counter > 0xff)
      throw new ZigbeeException("Invalid destination endpoint");

    $this->aps_counter = $aps_counter;
    }

  public function getApsCounter()
    {
    return $this->aps_counter;
    }

  public function displayApsCounter()
    {
    return sprintf("0x%02x", $this->getApsCounter());
    }

  public function setExtHeader($ext_header)
    {
    $ext_header = intval($ext_header);
    if($ext_header < 0x00 || $ext_header > 0xff)
      throw new ZigbeeException("Invalid frame control");

    $this->setFragmentation(($ext_header >> 0) & 0x03);
    }

  public function getExtHeader()
    {
    return ($this->getFragmentation() & 0x03) << 0;
    }

  public function displayExtHeader()
    {
    return Buffer::displayBitmap8($this->getExtHeader());
    }

  public function setFragmentation($fragmentation)
    {
    $fragmentation = intval($fragmentation);
    if($fragmentation < 0x00 || $fragmentation > 0x02)
      throw new ZigbeeException("Invalid fragmentation field");

    $this->fragmentation = $fragmentation;
    }

  public function getFragmentation()
    {
    return $this->fragmentation;
    }

  public function displayFragmentation()
    {
    $fragmentation = $this->getFragmentation();
    switch($fragmentation)
      {
      case self::FRAGMENTATION_DISABLED: $output = "Disabled"; break;
      case self::FRAGMENTATION_FIRST: $output = "First Frame"; break;
      case self::FRAGMENTATION_FOLLOWING: $output = "Following Frame"; break;
      default: $output = "unknown"; break;
      }

    return sprintf("%s (0x%02x)", $output, $fragmentation);
    }

  public function setFragBlockNumber($frag_block_number)
    {
    $frag_block_number = intval($frag_block_number);
    if($frag_block_number < 0x00 || $frag_block_number > 0xff)
      throw new ZigbeeException("Invalid fragmentation block number field");

    $this->frag_block_number = $frag_block_number;
    }

  public function getFragBlockNumber()
    {
    return $this->frag_block_number;
    }

  public function displayFragBlockNumber()
    {
    return sprintf("0x%02x", $this->getFragBlockNumber());
    }

  public function setFragAckBitfield($frag_ack_bitfield)
    {
    $frag_ack_bitfield = intval($frag_ack_bitfield);
    if($frag_ack_bitfield < 0x00 || $frag_ack_bitfield > 0xff)
      throw new ZigbeeException("Invalid fragmentation ack bitfield");

    $this->frag_ack_bitfield = $frag_ack_bitfield;
    }

  public function getFragAckBitfield()
    {
    return $this->frag_ack_bitfield;
    }

  public function displayFragAckBitfield()
    {
    return Buffer::displayBitmap8($this->getFragAckBitfield());
    }

  public function setPayload($payload)
    {
    $this->payload = $payload;
    }

  public function getPayload()
    {
    return $this->payload;
    }

  public function setPayloadObject($object)
    {
    if($object instanceof ZDPFrame)
      {
      $this->setFrameType(self::FRAME_TYPE_DATA);
      $this->setDestinationEndpoint(0x00);
      $this->setProfileId(0x0000);
      $this->setClusterId($object->getCommandId());
      $this->setPayload($object->getFrame());
      return;
      }
    elseif($object instanceof ZCLFrame)
      {
      $this->setFrameType(self::FRAME_TYPE_DATA);
      $this->setPayload($object->getFrame());
      return;
      }

    throw new ZigbeeException("Invalid payload object");
    }

  public function getPayloadObject()
    {
    if($this->isZDPPayload())
      return new ZDPFrame($this->getPayload(), $this->getClusterId());
    elseif($this->isZCLPayload())
      return new ZCLFrame($this->getPayload());

    throw new ZigbeeException("Could not find payload object");
    }

  public function displayPayload()
    {
    return Buffer::displayOctetString($this->getPayload());
    }

  protected function isZDPPayload()
    {
    if($this->getFrameType() === self::FRAME_TYPE_DATA &&
        ($this->getProfileId() === 0x0000 &&
         $this->getDestinationEndpoint() === 0x00))
      return true;

    return false;
    }

  protected function isZCLPayload()
    {
    if($this->getFrameType() === self::FRAME_TYPE_DATA &&
        !($this->getProfileId() === 0x0000 &&
          $this->getDestinationEndpoint() === 0x00))
      return true;

    return false;
    }

  protected function isGroupAddressPresent()
    {
    if($this->isDataFrameOrDataAck() &&
       $this->getFrameType() === self::FRAME_TYPE_DATA &&
       $this->getDeliveryMode() === self::DELIVERY_MODE_GROUP_ADDRESS)
      return true;

    return false;
    }

  protected function isDestinationEndpointPresent()
    {
    if($this->isDataFrameOrDataAck() &&
       $this->getDeliveryMode() !== self::DELIVERY_MODE_GROUP_ADDRESS)
      return true;

    return false;
    }

  protected function isClusterIdPresent()
    {
    if($this->isDataFrameOrDataAck())
      return true;

    return false;
    }

  protected function isProfileIdPresent()
    {
    if($this->isDataFrameOrDataAck())
      return true;

    return false;
    }

  protected function isSourceEndpointPresent()
    {
    if($this->isDataFrameOrDataAck())
      return true;

    return false;
    }

  protected function isExtHeaderPresent()
    {
    if($this->getFrameType() !== self::FRAME_TYPE_COMMAND &&
       $this->getExtHeaderPresent() === self::EXT_HEADER_IS_PRESENT)
      return true;

    return false;
    }

  protected function isDataFrameOrDataAck()
    {
    if($this->getFrameType() === self::FRAME_TYPE_DATA ||
        ($this->getFrameType() === self::FRAME_TYPE_ACKNOWLEDGE &&
         $this->getAckFormat() === self::ACK_FORMAT_DATA))
      return true;

    return false;
    }

  protected function isFragBlockNumberPresent()
    {
    if($this->isExtHeaderPresent() &&
       in_array($this->getFragmentation(), array(self::FRAGMENTATION_FIRST, self::FRAGMENTATION_FOLLOWING)))
      return true;

    return false;
    }

  protected function isFragAckBitfieldPresent()
    {
    if($this->isFragBlockNumberPresent() &&
       $this->getFrameType() === self::FRAME_TYPE_ACKNOWLEDGE)
      return true;

    return false;
    }

  protected function isPayloadPresent()
    {
    if($this->getFrameType() !== self::FRAME_TYPE_ACKNOWLEDGE)
      return true;

    return false;
    }

  public function __toString()
    {
    $output =  __CLASS__." (length: ".strlen($this->getFrame()).")".PHP_EOL;
    $output .= "|- frameControl     : ".$this->displayFrameControl().PHP_EOL;
    $output .= "|  |- frameType     : ".$this->displayFrameType().PHP_EOL;
    $output .= "|  |- deliveryMode  : ".$this->displayDeliveryMode().PHP_EOL;
    $output .= "|  |- ackFormat     : ".$this->displayAckFormat().PHP_EOL;
    $output .= "|  |- security      : ".$this->displaySecurity().PHP_EOL;
    $output .= "|  |- ackRequest    : ".$this->displayAckRequest().PHP_EOL;
    $output .= "|  `- extHeaderPres : ".$this->displayExtHeaderPresent().PHP_EOL;

    if($this->isDestinationEndpointPresent())
      $output .= "|- destEndpoint     : ".$this->displayDestinationEndpoint().PHP_EOL;

    if($this->isGroupAddressPresent())
      $output .= "|- groupAddress     : ".$this->displayGroupAddress().PHP_EOL;

    if($this->isClusterIdPresent())
      $output .= "|- clusterId        : ".$this->displayClusterId().PHP_EOL;

    if($this->isProfileIdPresent())
      $output .= "|- profileId        : ".$this->displayProfileId().PHP_EOL;

    if($this->isSourceEndpointPresent())
      $output .= "|- sourceEndpoint   : ".$this->displaySourceEndpoint().PHP_EOL;

    $output .= "|- apsCounter       : ".$this->displayApsCounter().PHP_EOL;

    if($this->isExtHeaderPresent())
      {
      $output .= "|- extHeader        : ".$this->displayExtHeader().PHP_EOL;
      $output .= "|  |- fragmentation : ".$this->displayFragmentation().PHP_EOL;
      if($this->isFragBlockNumberPresent())
        $output .= "|  |- blockNumber   : ".$this->displayFragBlockNumber().PHP_EOL;

      if($this->isFragAckBitfieldPresent())
        $output .= "|  `- ackBitfield   : ".$this->displayFragAckBitfield().PHP_EOL;
      }

    if($this->isPayloadPresent())
      {
      $output .= "|- payload (length: ".strlen($this->getPayload()).")".PHP_EOL;

      try
        {
        $output .= preg_replace("/^   /", "`- ", preg_replace("/^/m", "   ", $this->getPayloadObject()));
        }
      catch(\Exception $e)
        {
        $output .= "`-> ".$this->displayPayload().PHP_EOL;
        }
      }

    return $output;
    }

  }


text:
<!DOCTYPE html>

  <meta charset="utf-8">

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

  <title>Can I use the /reload command? — PetBlocks 7.3.0 documentation</title>

    <link rel="shortcut icon" href="../_static/favicon.png"/>

    <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />

        <link rel="index" title="Index"
              href="../genindex.html"/>
        <link rel="search" title="Search" href="../search.html"/>
    <link rel="top" title="PetBlocks 7.3.0 documentation" href="../index.html"/>
        <link rel="up" title="FAQ" href="index.html"/>
        <link rel="next" title="Contributing to PetBlock" href="../contributing/index.html"/>
        <link rel="prev" title="How can I disable rightclicking the pet?" href="candisablegrabbing.html"/>

             PetBlocks

                7.3.0

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Getting Started

Customizing

Commands

General

Developer API

FAQ

The pet falls through the ground when riding?

The pet does not spawn?

The pet flashes or does not spawn correctly on fresh a installment?

Are there any differences between Sponge and Bukkit PetBlocks?

How can you sell costumes/skins?

Can you support Minecraft 1.7.x or below?

How to use a custom skin URL?

How to use the MySQL database?

How to use the same pets on multiple servers?

Can the pet walk instead of hopping like a rabbit?

The player head is not visible in the GUI or when the Pet spawns?

How can I disable rightclicking the pet?

Can I use the /reload command?

Contributing to PetBlock

          PetBlocks

Docs »

FAQ »

Can I use the /reload command?

               Edit on GitHub

Can I use the /reload command?¶

Yes you can. As petblock gets created by using the /reload command you can use it without harming the plugin PetBlocks.

However, please do a full server restart when you install a new PetBlocks version.

        Next

         Previous

        © Copyright 2015 - 2018, Shynixn.


text:
package com.thoughtworks.xstream.io.xml;

import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
import com.thoughtworks.xstream.io.naming.NameCoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class XmlFriendlyNameCoder
  implements NameCoder, Cloneable
{
  private static final IntPair[] XML_NAME_CHAR_EXTRA_BOUNDS = (IntPair[])local1IntPairList.toArray(new IntPair[local1IntPairList.size()]);
  private static final IntPair[] XML_NAME_START_CHAR_BOUNDS;
  private final String dollarReplacement;
  private transient Map escapeCache;
  private final String escapeCharReplacement;
  private final String hexPrefix;
  private transient Map unescapeCache;

  static
  {
    ArrayList local1IntPairList = new ArrayList()
    {
      void add(char paramAnonymousChar)
      {
        super.add(new XmlFriendlyNameCoder.IntPair(paramAnonymousChar, paramAnonymousChar));
      }

      void add(int paramAnonymousInt1, int paramAnonymousInt2)
      {
        super.add(new XmlFriendlyNameCoder.IntPair(paramAnonymousInt1, paramAnonymousInt2));
      }
    };
    local1IntPairList.add(':');
    local1IntPairList.add(65, 90);
    local1IntPairList.add(97, 122);
    local1IntPairList.add('_');
    local1IntPairList.add(192, 214);
    local1IntPairList.add(216, 246);
    local1IntPairList.add(248, 767);
    local1IntPairList.add(880, 893);
    local1IntPairList.add(895, 8191);
    local1IntPairList.add(8204, 8205);
    local1IntPairList.add(8304, 8591);
    local1IntPairList.add(11264, 12271);
    local1IntPairList.add(12289, 55295);
    local1IntPairList.add(63744, 64975);
    local1IntPairList.add(65008, 65533);
    local1IntPairList.add(65536, 983039);
    XML_NAME_START_CHAR_BOUNDS = (IntPair[])local1IntPairList.toArray(new IntPair[local1IntPairList.size()]);
    local1IntPairList.clear();
    local1IntPairList.add('-');
    local1IntPairList.add('.');
    local1IntPairList.add(48, 57);
    local1IntPairList.add('·');
    local1IntPairList.add(768, 879);
    local1IntPairList.add(8255, 8256);
  }

  public XmlFriendlyNameCoder()
  {
    this("_-", "__");
  }

  public XmlFriendlyNameCoder(String paramString1, String paramString2)
  {
    this(paramString1, paramString2, "_.");
  }

  public XmlFriendlyNameCoder(String paramString1, String paramString2, String paramString3)
  {
    this.dollarReplacement = paramString1;
    this.escapeCharReplacement = paramString2;
    this.hexPrefix = paramString3;
    readResolve();
  }

  private String decodeName(String paramString)
  {
    String str1 = (String)this.unescapeCache.get(paramString);
    String str2 = str1;
    if (str1 == null)
    {
      int i = this.dollarReplacement.charAt(0);
      int j = this.escapeCharReplacement.charAt(0);
      int k = this.hexPrefix.charAt(0);
      int m = paramString.length();
      for (int n = 0; n < m; n++)
      {
        int i2 = paramString.charAt(n);
        if ((i2 == i) || (i2 == j) || (i2 == k))
          break;
      }
      if (n == m)
        return paramString;
      StringBuffer localStringBuffer = new StringBuffer(m + 8);
      if (n > 0)
        localStringBuffer.append(paramString.substring(0, n));
      while (n < m)
      {
        char c1 = paramString.charAt(n);
        if ((c1 == i) && (paramString.startsWith(this.dollarReplacement, n)))
        {
          n += -1 + this.dollarReplacement.length();
          localStringBuffer.append('$');
        }
        else if ((c1 == k) && (paramString.startsWith(this.hexPrefix, n)))
        {
          int i1 = n + this.hexPrefix.length();
          char c2 = (char)Integer.parseInt(paramString.substring(i1, i1 + 4), 16);
          n = i1 + 3;
          localStringBuffer.append(c2);
        }
        else if ((c1 == j) && (paramString.startsWith(this.escapeCharReplacement, n)))
        {
          n += -1 + this.escapeCharReplacement.length();
          localStringBuffer.append('_');
        }
        else
        {
          localStringBuffer.append(c1);
        }
        n++;
      }
      str2 = localStringBuffer.toString();
      this.unescapeCache.put(paramString, str2);
    }
    return str2;
  }

  private String encodeName(String paramString)
  {
    String str1 = (String)this.escapeCache.get(paramString);
    String str2 = str1;
    if (str1 == null)
    {
      int i = paramString.length();
      for (int j = 0; j < i; j++)
      {
        int m = paramString.charAt(j);
        if ((m == 36) || (m == 95) || (m <= 27) || (m >= 127))
          break;
      }
      if (j == i)
        return paramString;
      StringBuffer localStringBuffer = new StringBuffer(i + 8);
      if (j > 0)
        localStringBuffer.append(paramString.substring(0, j));
      while (j < i)
      {
        int k = paramString.charAt(j);
        if (k == 36)
        {
          localStringBuffer.append(this.dollarReplacement);
        }
        else if (k == 95)
        {
          localStringBuffer.append(this.escapeCharReplacement);
        }
        else if (((j == 0) && (!isXmlNameStartChar(k))) || ((j > 0) && (!isXmlNameChar(k))))
        {
          localStringBuffer.append(this.hexPrefix);
          if (k < 16)
            localStringBuffer.append("000");
          else if (k < 256)
            localStringBuffer.append("00");
          else if (k < 4096)
            localStringBuffer.append("0");
          localStringBuffer.append(Integer.toHexString(k));
        }
        else
        {
          localStringBuffer.append(k);
        }
        j++;
      }
      str2 = localStringBuffer.toString();
      this.escapeCache.put(paramString, str2);
    }
    return str2;
  }

  private static boolean isInNameCharBounds(int paramInt, IntPair[] paramArrayOfIntPair)
  {
    for (int i = 0; i < paramArrayOfIntPair.length; i++)
    {
      IntPair localIntPair = paramArrayOfIntPair[i];
      if ((paramInt >= localIntPair.min) && (paramInt <= localIntPair.max))
        return true;
    }
    return false;
  }

  private static boolean isXmlNameChar(int paramInt)
  {
    if (isXmlNameStartChar(paramInt))
      return true;
    return isInNameCharBounds(paramInt, XML_NAME_CHAR_EXTRA_BOUNDS);
  }

  private static boolean isXmlNameStartChar(int paramInt)
  {
    return isInNameCharBounds(paramInt, XML_NAME_START_CHAR_BOUNDS);
  }

  private Object readResolve()
  {
    this.escapeCache = createCacheMap();
    this.unescapeCache = createCacheMap();
    return this;
  }

  public Object clone()
  {
    try
    {
      XmlFriendlyNameCoder localXmlFriendlyNameCoder = (XmlFriendlyNameCoder)super.clone();
      localXmlFriendlyNameCoder.readResolve();
      return localXmlFriendlyNameCoder;
    }
    catch (CloneNotSupportedException localCloneNotSupportedException)
    {
      throw new ObjectAccessException("Cannot clone XmlFriendlyNameCoder", localCloneNotSupportedException);
    }
  }

  protected Map createCacheMap()
  {
    return new HashMap();
  }

  public String decodeAttribute(String paramString)
  {
    return decodeName(paramString);
  }

  public String decodeNode(String paramString)
  {
    return decodeName(paramString);
  }

  public String encodeAttribute(String paramString)
  {
    return encodeName(paramString);
  }

  public String encodeNode(String paramString)
  {
    return encodeName(paramString);
  }

  static class IntPair
  {
    int max;
    int min;

    public IntPair(int paramInt1, int paramInt2)
    {
      this.min = paramInt1;
      this.max = paramInt2;
    }
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder
 * JD-Core Version:    0.6.2
 */


text:
var assert = require('assert'),
    uuid = require('node-uuid'),
    _ = require('underscore');

var Status = {
  NOT_STARTED: 0,
  WAIT_FOR_ROUND_START: 1,
  WAIT_FOR_ANSWERS: 2,
  WAIT_FOR_JUDGMENT: 3,
  GAME_OVER: 5
};

// boilerplate cardset-loading code for rn
var Cardset = require('./cardset.js'),
    cah = new Cardset(__dirname + '/sets/cah-cc-by-nc-sa.json');

module.exports = (function () {
  function Game() {
    this.id = uuid.v4();
    this.name = 'game ' + Math.floor(Math.random() * 1000000);

    this.players = [];
    this.winner = null;

    this._nextPlayerId = 1;

    this._winFn = function (player, otherPlayers) {
      return player.score >= 3;
    }

    this._state = Status.NOT_STARTED;

    this._whiteCards = cah.whiteCards;
    this._blackCards = cah.blackCards;

    this._whiteCardDeck = [];
    this._blackCardDeck = [];

    this._currentCardCzar = null;
    this._currentBlackCard = null;
    this._currentAnswers = null;

    this._n = 4;
  }

  Game.prototype.changeSize = function (newSize) {
    if (_(this._activePlayers()).size() > newSize) {
      // game would be too small after resizing
      return false;
    } else {
      // everything's cool
      this._n = newSize;
      return true;
    }
  }

  Game.prototype.join = function (user) {
    if (this._state == Status.GAME_OVER) {
      // game's already over
      return false;
    } else if (_(this._activePlayers()).size() >= this._n) {
      // game's already full
      return false;
    } else {
      // make sure the player's not already in here
      if (_(this.players).findWhere({ user: user })) {
        return false;
      }

      // everything's cool
      var player = this._makePlayer(user);
      this.players.push(player);

      // if we're currently waiting for answers, deal the player in
      if (this._state == Status.WAIT_FOR_ANSWERS) {
        this._dealToPlayer(player);
      }

      return true;
    }
  }

  Game.prototype._getPlayer = function (user) {
    return _(this.players).findWhere({ user: user });
  }

  Game.prototype._getCardCzar = function () {
    return this._currentCardCzar;
  }

  Game.prototype.leave = function (user) {
    var player = this._getPlayer(user);

    if (!player) {
      // user actually isn't in this game?
      return false;
    } else {
      // if the player is the current card czar, then abandon the current round
      if (player == this._currentCardCzar) {
        this._state = Status.WAIT_FOR_ROUND_START;
      }

      // everything's cool
      player.hasLeft = true;
      return true;
    }
  }

  Game.prototype.answer = function (user, answer) {
    var player = this._getPlayer(user);

    if (this._state != Status.WAIT_FOR_ANSWERS) {
      // not the time for answering
      return false;
    } else if (!player) {
      // user isn't in this game
      return false;
    } else if (player.hasLeft) {
      // player left the game
      return false;
    } else {
      // card czar can't answer
      if (player == this._currentCardCzar) {
        return false;
      }

      // find the card in the user's hand
      var card = _(player.hand).findWhere({ id: answer.id });

      if (this._currentAnswers[player.id]) {
        // player has already answered
        return false;
      } else if (card) {
        // player has card, so play it
        player.hand = _(player.hand).without(card);
        this._currentAnswers[player.id] = card;

        return true;
      } else {
        // player doesn't have card
        return false;
      }
    }
  }

  Game.prototype.lockAnswers = function (user) {
    var g = this;
    var allAnswersSubmitted = _(this._activePlayers()).every(function (player) {
      return (player == g._currentCardCzar) || (!!g._currentAnswers[player.id]);
    });

    if (this._state != Status.WAIT_FOR_ANSWERS) {
      // not waiting for answers right now
      return false;
    } else if (!allAnswersSubmitted) {
      // at least one active player hasn't answered
      return false;
    } else if (user != g._currentCardCzar.user) {
      // only the card czar can lock in answers
      return false;
    } else {
      // everything's cool
      this._state = Status.WAIT_FOR_JUDGMENT;
      return true;
    }
  }

  Game.prototype.vote = function (user, chosenAnswer) {
    if (this._state != Status.WAIT_FOR_JUDGMENT) {
      // not waiting for vote right now
      return false;
    } else if (user != this._currentCardCzar.user) {
      // only the card czar can vote
      return false;
    } else {
      var g = this, answerFound = false;

      // find the actual answer, and the person who submitted it
      _(this._currentAnswers).each(function (answer, answererId, answers) {
        if (chosenAnswer.id == answer.id) {
          var answerer = _(g.players).findWhere({ id: Number(answererId) });

          answerer.score += 1;
          answerFound = true;
        }
      });

      if (!answerFound) {
        return false;
      }

      // check for win state and move to new state
      var gameOver = false, winner = null;
      var g = this;

      _(this.players).each(function (player) {
        var otherPlayers = _(g.players).without(player);

        if (g._winFn(player, otherPlayers)) {
          gameOver = true;
          winner = player;
        }
      });

      if (gameOver) {
        this.winner = winner;
        this._state = Status.GAME_OVER;
      } else {
        this._state = Status.WAIT_FOR_ROUND_START;
      }

      // everything's cool
      return true;
    }
  }

  Game.prototype.newRound = function () {
    if (this._state != Status.NOT_STARTED && this._state != Status.WAIT_FOR_ROUND_START) {
      // can't start a new round right now
      return false;
    }

    if (_(this._activePlayers()).size() < 3) {
      // not enough players to start a round
      return false;
    }

    var g = this;

    // deal a new round
    _(this.players).forEach(this._dealToPlayer.bind(this));

    this._currentBlackCard = this._dealBlackCard();
    this._currentAnswers = {};

    // select new card czar
    if (this._currentCardCzar) {
      // already had a card czar, select next-by-id active player
      var cardCzar = this._currentCardCzar;
      var players = _(this._activePlayers()).sortBy(function (player) { return player.id; });
      var nextPlayer = _(players).find(function (player) { return player.id > cardCzar.id; });

      if (nextPlayer) {
        this._currentCardCzar = nextPlayer;
      } else {
        // no players with a higher id than the current card czar; start again at the beginning
        this._currentCardCzar = players[0];
      }
    } else {
      // no card czar yet, choose an active player randomly
      var players = _(this._activePlayers()).shuffle();
      this._currentCardCzar = players[0];
    }

    // change state to awaiting answers
    this._state = Status.WAIT_FOR_ANSWERS;

    return true;
  }

  Game.prototype._endGame = function () {
    if (this._state != Status.NOT_STARTED && this._state != Status.WAIT_FOR_ROUND_START) {
      return false;
    }

    this._state = Status.GAME_OVER;
    return true;
  }

  Game.prototype._getState = function() {
    return this._state;
  }

  Game.prototype._makePlayer = function (user) {
    return {
      id: this._nextPlayerId++,
      user: user,
      hasLeft: false,
      score: 0,
      hand: []
    };
  }

  Game.prototype._activePlayers = function () {
    return _(this.players).where({ hasLeft: false });
  }

  Game.prototype._dealBlackCard = function () {
    if (_(this._blackCardDeck).size() == 0) {
      // shuffle the black cards onto the deck
      this._blackCardDeck = this._blackCardDeck.concat(_(this._blackCards).shuffle());
    }

    return this._blackCardDeck.shift();
  }

  Game.prototype._dealWhiteCards = function (n) {
    if (_(this._whiteCardDeck).size() < n) {
      // shuffle the white cards onto the deck
      this._whiteCardDeck = this._whiteCardDeck.concat(_(this._whiteCards).shuffle());
    }

    // deal n off the top
    var dealt = _(this._whiteCardDeck).first(n), remainder = _(this._whiteCardDeck).rest(n);
    this._whiteCardDeck = remainder;

    return dealt;
  }

  Game.prototype._dealToPlayer = function (player) {
    var oldHandSize = _(player.hand).size();
    var newCards = this._dealWhiteCards(10 - oldHandSize);

    player.hand = player.hand.concat(newCards);
  }

  return Game;
})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<article id="1166">
	<title>New Tasks of Information Services and Specialists Training Problem	</title>
	<author>Gol'dgamer, G. I.	</author>
	<text>
		   State-of-the-art in reference information servicing and training of
		specialists for information establishments is described..
	</text>
</article>


text:
var TcUser = (function () {
    var tc = {};

    /* cached queries */
    var $loadingSpinner = $("#loadingSpinner"),
        $loadingCheck = $("#loadingCheck"),
        $loadingError = $("#loadingError");

    var $periodRange = $("#periodRange");

    var $tcTable = $("#tcTable"),
        $tcHead = $("#tcHead"),
        $tcHeaders;

    var $tcStatus = $("#tcStatus");

    var $buttonNewTemplate = $("#buttonNewTemplate"),
        $dropdownSelectTemplate = $("#dropdownSelectTemplate"),
        $menuSelectTemplate = $("#menuSelectTemplate"),
        $inputTemplateName = $("#inputTemplateName"),
        $buttonCancelTemplate = $("#buttonCancelTemplate"),
        $buttonSaveTemplate = $("#buttonSaveTemplate");

    /* local variables */
    var focusDate;
    var periodStart,
        periodEnd;

    var localSelectedTimestamps = new Set();
    var localUnselectedTimestamps = new Set();
    var selectedTimestamps;

    var templates;
    // TODO: Store selected template, nullify when changed

    var slotDown;
    var slotToggleTo;

    /* public variables */
    tc.initialDate;
    tc.validPeriodStart;
    tc.periodDuration;
    tc.lockDate;
    tc.slotIncrement;
    tc.slotFirstStart;
    tc.slotLastStart;

    tc.init = function () {
        var tcHeaders = [];
        for (var i = 0; i < tc.periodDuration; i++) {
            tcHeaders.push($("#tcHeader" + i));
        }
        $tcHeaders = $(tcHeaders);

        hideNewTemplate();

        currentPeriod();
    }

    function onTimestampsChanged() {
        updateTable();
        updateHeaderHours();

        for (var i = 0; i < tc.periodDuration; i++) {
            updateDayBlocks(i);
        }
    }

    function onPeriodChanged() {
        // TODO: ...
        $("#buttonSelectTemplate").text("None");

        dbUpdate();
        updateHeaderDates();
        updatePeriod();
    }

    function updateHeaderDates() {
        $tcHeaders.each(function (index, element) {
            var headerDate = moment(periodStart).add(index, "day");
            $(element).data("start", headerDate.unix());
            $(element).data("end", moment(headerDate).endOf("day").unix());
            $(element).children().eq(0).text(headerDate.format("ddd"));
            $(element).children().eq(1).text(headerDate.format("MMM D"));
        })
    }

    function updateHeaderHours() {
        $tcHeaders.each(function (index, element) {
            var hours = 0.0;
            var dayStart = $(element).data("start");
            var dayEnd = $(element).data("end");

            for (var ts of selectedTimestamps) {
                if (ts >= dayStart && ts <= dayEnd) {
                    if (!localUnselectedTimestamps.has(ts)) {
                        hours += (tc.slotIncrement / 60);
                    }
                }
            }

            for (var ts of localSelectedTimestamps) {
                // avoid double counting timestamps
                if (!selectedTimestamps.has(ts)) {
                    if (ts >= dayStart && ts <= dayEnd) {
                        hours += (tc.slotIncrement / 60);
                    }
                }
            }

            $(element).children().eq(2).text(hours.toFixed(1) + " hours");

            /*$.each(selectedTimestamps, function (ind, value) {
                if (value >= $(element).data("start") && value <= $(element).data("end")) {
                    if (!localUnselectedTimestamps.has(value)) {
                        hours += (tc.slotIncrement / 60);
                    }
                }
            });

            $.each(localSelectedTimestamps, function (ind, value) {
                if (value >= $(element).data("start") && value <= $(element).data("end")) {
                    hours += (tc.slotIncrement / 60);
                }
            });

            $(element).children().eq(2).text(hours.toFixed(1) + " hours");*/
        });
    }

    function updateDayBlocks(index) {
        var day = $("#tcDay" + index);

        var blockStartTime;

        day.children().each(function (index, element) {
            var slot = $(element);

            slot.text("");
            slot.removeClass("rounded-top");
            slot.removeClass("rounded-bottom");

            var lastSlot = (index == day.children().length - 1);
            var prevSlotSelected = index > 0 && timestampSelected(day.children().eq(index - 1).data("timestamp"));
            var slotSelected = timestampSelected(slot.data("timestamp"));
            var nextSlotSelected = !lastSlot && timestampSelected(day.children().eq(index + 1).data("timestamp"));

            var blockStart = slotSelected && !prevSlotSelected;
            var blockEnd = slotSelected && !nextSlotSelected;

            if (blockStart) {
                slot.addClass("rounded-top");

                blockStartTime = moment.unix(slot.data("timestamp"));

                blockLabel = $("<div>", {
                    class: "blocklabel",
                    html: ""
                });
                slot.append(blockLabel);
            }

            if (blockEnd) {
                slot.addClass("rounded-bottom");

                var blockEndTime = moment.unix(slot.data("timestamp")).add(tc.slotIncrement, "minute");
                var blockDuration = moment.duration(blockEndTime.diff(blockStartTime));

                // Show duration label for blocks of an hour or more
                if (blockDuration.asHours() >= 1) {
                    // If start and end are same meridiem
                    if (blockStartTime.format("a") === blockEndTime.format("a")) {
                        blockLabel.text(blockStartTime.format("h:mm") + "– " + blockEndTime.format("h:mma"));
                    } else {
                        blockLabel.text(blockStartTime.format("h:mma") + "– " + blockEndTime.format("h:mma"));
                    }
                }
            }
        });
    }

    function updateTable() {
        var $oldTcBody = $("#tcBody");
        var $newTcBody = $("<tbody>", {
            id: "tcBody"
        });

        var $tcRow = $("<tr>");
        $newTcBody.append($tcRow);

        var slotTimes = [];
        var slotTime = moment(tc.slotFirstStart).startOf("hour");
        var endTime = moment(tc.slotLastStart).endOf("hour");
        while (slotTime.isBefore(endTime)) {
            slotTimes.push(moment(slotTime));
            slotTime.add(tc.slotIncrement, "minute");
        }

        var $hoursCell = $("<td>");
        $tcRow.append($hoursCell);
        var $hoursStack = $("<div>", {
            class: "slot-stack"
        });
        $hoursCell.append($hoursStack);

        // Add hour marks in first column
        for (var i = 0; i < slotTimes.length; i++) {
            if (slotTimes[i].minute() == 0) {
                $hoursStack.append($("<div>", {
                    "class": "text-muted hour-mark",
                    "html": slotTimes[i].format("ha")
                }));
            }
        }

        for (var i = 0; i < tc.periodDuration; i++) {
            var dayTime = moment(periodStart).add(i, "day");

            var $dayCell = $("<td>", {
                class: "day-cell"
            });
            $tcRow.append($dayCell);

            // Highlight current day
            if (dayTime.isSame(tc.initialDate, "day")) {
                $dayCell.css("background-color", "#f4f4f4");
            }

            var $dayStack = $("<div>", {
                class: "slot-stack",
                id: "tcDay" + i,
                "data-day": i
            });
            $dayCell.append($dayStack);

            for (j = 0; j < slotTimes.length; j++) {
                var slotTime = slotTimes[j];
                var newTime = moment(dayTime).hour(slotTime.hour()).minute(slotTime.minute()).second(0);

                var $newSlot = $("<div>", {
                    id: i + "-" + newTime.format("HH:mm"),
                    "data-timestamp": newTime.unix()
                });

                // Slot is selected if: selected locally, or selected on server and not unselected locally
                if (timestampSelected($newSlot.data("timestamp").toString())) {
                    $newSlot.attr("class", "slot-selected");
                } else {
                    // if slot time is before first start times, lock it
                    if (slotTime.hour() < tc.slotFirstStart.hour() || (slotTime.hour() == tc.slotFirstStart.hour() && slotTime.minute() < tc.slotFirstStart.minute())) {
                        $newSlot.attr("class", "slot locked");
                    } else {
                        $newSlot.attr("class", "slot");
                    }
                }

                $dayStack.append($newSlot);
            }
        }

        $oldTcBody.replaceWith($newTcBody);
    }

    function updatePeriod() {
        $("#buttonPeriodToday").prop("disabled", focusDate.isSame(tc.initialDate, "day"));

        var startDate = moment(periodStart);
        var endDate = moment(periodEnd);
        if (startDate.isSame(endDate, "year")) {
            if (startDate.isSame(endDate, "month")) {
                $periodRange.text(startDate.format("MMM D") + "–" + endDate.format("D, YYYY"));
            } else {
                $periodRange.text(startDate.format("MMM D") + "–" + endDate.format("MMM D, YYYY"));
            }
        } else {
            $periodRange.text(startDate.format("MMM D, YYYY") + "–" + endDate.format("MMM D, YYYY"));
        }
    }

    function dbUpdate() {
        $loadingSpinner.show();
        $loadingCheck.hide();
        $loadingError.hide();

        var updateDict = {
            "range": [moment(periodStart).startOf("day").unix(), moment(periodEnd).endOf("day").unix()]
        };

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/update", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        // TODO: also set xhr.timeout and xhr.ontimeout?
        xhr.responseType = "json";
        xhr.onload = function () {
            $loadingSpinner.hide();

            if (xhr.status == 200) {
                $loadingCheck.show();
                $tcStatus.text("Last modified " + moment(xhr.response["lastmodified"]).fromNow()); // TODO: Use initialMoment, localInitialMoment and moment() to accurate use .from(getDbMoment())

                //localSelectedTimestamps = new Set();
                //localUnselectedTimestamps = new Set();

                selectedTimestamps = new Set();
                for (var i = 0; i < xhr.response["selected"].length; i++) {
                    selectedTimestamps.add(xhr.response["selected"][i]);
                }
                onTimestampsChanged();
            } else {
                $loadingError.show();
                // TODO: Tooltip with error
            }
        }
        xhr.send(JSON.stringify(updateDict));

        dbLoadTemplates();
    }

    function dbSave() {
        // TODO***: Blocks are broken after saving
        // Abort save if nothing is changed
        if (!(localSelectedTimestamps.size > 0 || localUnselectedTimestamps.size > 0)) {
            return;
        }

        $tcStatus.text("Saving...");

        var saveDict = {};
        if (localSelectedTimestamps.size > 0) {
            saveDict["selected"] = Array.from(localSelectedTimestamps);
        }
        if (localUnselectedTimestamps.size > 0) {
            saveDict["unselected"] = Array.from(localUnselectedTimestamps);
        }

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/save", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        // TODO: also set xhr.timeout and xhr.ontimeout?
        xhr.responseType = "json";
        xhr.onload = function () {
            dbUpdate();
            if (xhr.status == 200) {
                $tcStatus.text("All changes saved");
            } else {
                $tcStatus.text("Failed to save changes");
            }
        }
        xhr.send(JSON.stringify(saveDict));
        /*$.each(localSelectedTimestamps, function (index, value) {
            selectedTimestamps.add(value);
        });

        $.each(localUnselectedTimestamps, function (index, value) {
            selectedTimestamps.delete(value);
        });

        localSelectedTimestamps = new Set();
        localUnselectedTimestamps = new Set();*/
    }

    function dbLoadTemplates() {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/update/templates", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.responseType = "json";
        xhr.onload = function () {
            if (xhr.status == 200) {
                templates = xhr.response["templates"];
                updateTemplatesSelect();
            } else {

            }
        }
        xhr.send();
    }

    function dbSaveTemplates() {
        var saveDict = {
            templates: templates
        }

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/save/templates", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.responseType = "json";
        xhr.onload = function () {
            if (xhr.status == 200) {
                // TODO: Display 'successfully saved new template' banner
            } else {
                // TODO: Display 'failed to save new template' banner
            }
            dbLoadTemplates();
        }
        xhr.send(JSON.stringify(saveDict));
    }

    function updateTemplatesSelect() {
        $menuSelectTemplate.empty();

        // "None" option for no template
        $menuSelectTemplate.append($("<button>", {
            class: "dropdown-item",
            text: "None",
            "data-index": -1
        }));

        $menuSelectTemplate.append($("<div>", {
            class: "dropdown-divider"
        }));

        for (var i = 0; i < templates.length; i++) {
            var template = templates[i];

            $menuSelectTemplate.append($("<button>", {
                class: "dropdown-item",
                text: template["name"],
                "data-index": i
            }));
        }
    }

    $menuSelectTemplate.on("click", ".dropdown-item", function () {
        var index = $(this).data("index");

        if (index > -1) {
            applyTemplate(templates[index]);
            $("#buttonSelectTemplate").text(templates[index]["name"]);
        } else {
            $("#buttonSelectTemplate").text("None");
        }
    });

    $tcTable.on("mouseleave", ".day-cell", function () {
        slotDown = false;
    });

    $tcTable.on("mousedown", ".slot, .slot-selected", function () {
        slotDown = true;
        slotToggleTo = !timestampSelected($(this).data("timestamp").toString());

        slotMouseOver($(this));
    });

    $tcTable.on("mouseup", ".slot, .slot-selected", function () {
        slotDown = false;
    });

    $tcTable.on("mouseover", ".slot, .slot-selected", function () {
        slotMouseOver($(this));
    });

    function slotMouseOver(slot) {
        if (!slotDown) {
            return;
        }

        var slotTimestamp = slot.data("timestamp").toString();

        if (slotToggleTo) {
            // changing slots to selected, only if not already selected
            if (!timestampSelected(slotTimestamp)) {
                slot.attr("class", "slot-selected")
                selectTimestamp(slotTimestamp);
                updateHeaderHours();
                updateDayBlocks(slot.parent().data("day"));
            }
        } else {
            // changing slots to unselected, only if already selected
            if (timestampSelected(slotTimestamp)) {
                slot.attr("class", "slot")
                unselectTimestamp(slotTimestamp);
                updateHeaderHours();
                updateDayBlocks(slot.parent().data("day"));
            }
        }
    }

    $("#buttonSave").click(function () {
        dbSave();
    });

    function selectTimestamp(ts) {
        if (!selectedTimestamps.has(ts)) {
            localSelectedTimestamps.add(ts);
        }
        if (localUnselectedTimestamps.has(ts)) {
            localUnselectedTimestamps.delete(ts);
        }
    }

    function unselectTimestamp(ts) {
        if (selectedTimestamps.has(ts)) {
            localUnselectedTimestamps.add(ts);
        }
        if (localSelectedTimestamps.has(ts)) {
            localSelectedTimestamps.delete(ts);
        }
    }

    function timestampSelected(ts) {
        ts = ts.toString();
        return (selectedTimestamps.has(ts) && !localUnselectedTimestamps.has(ts)) || localSelectedTimestamps.has(ts);
    }

    $("#buttonPeriodPrev").on("click", function () {
        prevPeriod();
    });

    $("#buttonPeriodToday").on("click", function () {
        currentPeriod();
    });

    $("#buttonPeriodNext").on("click", function () {
        nextPeriod();
    });

    function prevPeriod() {
        focusDate.subtract(tc.periodDuration, "day");
        periodStart.subtract(tc.periodDuration, "day");
        periodEnd.subtract(tc.periodDuration, "day");

        onPeriodChanged();
    }

    function currentPeriod() {
        focusDate = moment(tc.initialDate);
        periodStart = moment(tc.validPeriodStart);
        // Calculate start of the period the initialDate is in
        periodStart.add(Math.floor((focusDate.unix() - periodStart.unix()) / 60 / 60 / 24 / tc.periodDuration) * tc.periodDuration, "day");
        periodEnd = moment(periodStart).add(tc.periodDuration - 1, "day").endOf("day");

        onPeriodChanged();
    }

    function nextPeriod() {
        focusDate.add(tc.periodDuration, "day");
        periodStart.add(tc.periodDuration, "day");
        periodEnd.add(tc.periodDuration, "day");

        onPeriodChanged();
    }

    $buttonNewTemplate.click(function () {
        showNewTemplate();
    });

    $buttonCancelTemplate.click(function () {
        hideNewTemplate();
    });

    $buttonSaveTemplate.click(function () {
        var newTemplate = createTemplate($inputTemplateName.val())
        templates.push(newTemplate);
        dbSaveTemplates();
        hideNewTemplate();
    });

    $inputTemplateName.on("change paste keyup", function () {
        $buttonSaveTemplate.prop("disabled", !($inputTemplateName.val().length > 2));
    });

    //$("#buttonEditTemplate").click(function () {});

    //$("#buttonDeleteTemplate").click(function () {});

    function showNewTemplate() {
        $buttonNewTemplate.hide();
        $dropdownSelectTemplate.hide();
        $inputTemplateName.show();
        $inputTemplateName.focus();
        $buttonCancelTemplate.show();
        $buttonSaveTemplate.prop("disabled", true);
        $buttonSaveTemplate.show();
    }

    function hideNewTemplate() {
        $buttonNewTemplate.show();
        $dropdownSelectTemplate.show();
        $inputTemplateName.hide();
        $inputTemplateName.val("");
        $buttonCancelTemplate.hide();
        $buttonSaveTemplate.hide();
    }

    function createTemplate(name) {
        // TODO: Should really operate on data, not elements
        var newTemplate = {
            name: name,
            timeblocks: []
        };

        for (var dayIndex = 0; dayIndex < tc.periodDuration; dayIndex++) {
            var day = $("#tcDay" + dayIndex);

            var blockStartTime;

            day.children().each(function (index, element) {
                var slot = $(element);

                var lastSlot = (index == day.children().length - 1);
                var prevSlotSelected = index > 0 && timestampSelected(day.children().eq(index - 1).data("timestamp"));
                var slotSelected = timestampSelected(slot.data("timestamp"));
                var nextSlotSelected = !lastSlot && timestampSelected(day.children().eq(index + 1).data("timestamp"));

                var blockStart = slotSelected && !prevSlotSelected;
                var blockEnd = slotSelected && !nextSlotSelected;

                if (blockStart) {
                    blockStartTime = moment.unix(slot.data("timestamp"));
                }

                if (blockEnd) {
                    var blockEndTime = moment.unix(slot.data("timestamp")).add(tc.slotIncrement, "minute");
                    var blockDuration = moment.duration(blockEndTime.diff(blockStartTime));

                    var blockString = dayIndex + "-" + blockStartTime.format("HH:mm") + "-" + blockDuration.asMinutes();
                    newTemplate["timeblocks"].push(blockString);
                }
            });
        }

        return newTemplate;
    }

    function applyTemplate(template) {
        // TODO: Make use of moment.duration to avoid DST issues
        // TODO: Rework this behavior to be more robust regarding local selections, template nullifying, etc.
        localUnselectedTimestamps = new Set();
        localSelectedTimestamps = new Set();

        // deselect all slots
        /*$(".slot, .slot-selected").each(function (index, element) {
            var slot = $(element);
            if (timestampSelected(slot.data("timestamp"))) {
                slot.attr("class", "slot")
                unselectTimestamp(slot.data("timestamp"));
            }
        });*/

        for (var ts of selectedTimestamps) {
            unselectTimestamp(ts);
        }

        $.each(template["timeblocks"], function (index, value) {
            var block = value.split("-");
            var dayIndex = block[0];
            var startTime = moment(block[1], "HH:mm");
            var duration = parseInt(block[2]);

            while (duration > 0) {
                // select the slot
                // selector has to be escaped due to "-" and ":"
                var id = $.escapeSelector(dayIndex + "-" + startTime.format("HH:mm"));
                var slot = $("#" + id);
                //slot.attr("class", "slot-selected")
                //selectTimestamp(slot.data("timestamp"));
                //localSelectedTimestamps.add();

                selectTimestamp(slot.data("timestamp").toString())

                startTime.add(tc.slotIncrement, "minute");
                duration -= tc.slotIncrement;
            }
        });

        onTimestampsChanged();
    }

    return tc;
})();
// Justin Carlson


text:
using System.Collections.Generic;
using System.Web.ModelBinding;
using System.Web.Mvc;

namespace MvcMusicStore.Controllers
{
    public class ModelBindingTestsController : Controller
    {
        public ActionResult Index()
        {
            return View("Index", new ComplexType());
        }

        [HttpPost]
        public ActionResult SimplePost(string firstname, string lastname)
        {
            return View("Index", new ComplexType());
        }

        [HttpPost]
        public ActionResult ComplexPost(ComplexType complexType, string additionalSimpleValue)
        {
            return View("Index", new ComplexType());
        }

        [HttpPost]
        public JsonResult PostItem(AjaxPostedData item)
        {
            return new JsonResult { Data = new { PostedItem = item } };
        }

        [HttpPost]
        public ActionResult HtmlContainedPost(HtmlInputAllowedType htmlInputAllowedType)
        {
            return View("Index", new ComplexType());
        }

        public class AjaxPostedData
        {
            public string MySimpleValue { get; set; }
            public Dictionary<string, string> MyStringDictionary { get; set; }
            public Dictionary<string, MyComplexObject> MyComplexObjectDictionary { get; set; }
            public MyComplexObject MyComplexObject { get; set; }
            public string[] MyStringArray { get; set; }
        }

        public class MyComplexObject
        {
            public string Name { get; set; }
            public string Value { get; set; }
        }

        public class ComplexType
        {
            public ComplexType()
            {
                this.Name = "Foo";
                this.Another = new SecondLevelComplexType();
            }

            public string Name { get; set; }
            public SecondLevelComplexType Another { get; set; }
        }

        public class SecondLevelComplexType
        {
            public SecondLevelComplexType()
            {
                this.Name = "Bar";
                this.Values = new ThirdLevelComplexType(this.Name);
            }

            public string Name { get; set; }
            public ThirdLevelComplexType Values { get; set; }
        }

        public class ThirdLevelComplexType
        {
            public ThirdLevelComplexType(string valueFor)
            {
                this.Value1 = "Value 1 for " + valueFor;
                this.Value2 = "Value 2 for " + valueFor;
            }

            public string Value1 { get; set; }
            public string Value2 { get; set; }
        }

        public class HtmlInputAllowedType
        {
            [AllowHtml]
            public string HtmlContent { get; set; }
        }
    }
}


text:
export { withStyles, createStyleSheet, MuiThemeProvider } from 'material-ui/styles'
export { default as muiPropTypes } from 'material-ui/utils/customPropTypes'
export { default as createPalette } from 'material-ui/styles/palette'
export { default as createMuiTheme } from 'material-ui/styles/theme'
import * as colors from 'material-ui/styles/colors'
export { colors }

export const capitalize = (string) => {
  return `${string.substring(0, 1).toUpperCase()}${string.substring(1)}`;
}

export const locationToString = (pathname) => {
  const path = pathname.split(/\//);
  const words = path[path.length - 1].split(/\-/).map((item) => {
    return capitalize(item);
  });
  let title = '';
  words.forEach((word) => {
    if (title.length) {
      title = `${title} ${word}`;
    } else {
      title = `${word}`;
    }
  });
  return title;
}

export const loadDatasources = (formName, forms) => {
  let form = forms.filter((form) => {
    return form.name === formName
  })[0]
  form.fields = form.fields.map((field) => {
    if (field.type === 'array') {
      let payload = forms.filter((f) => {
        return f.name === field.datasource
      })[0].fields
      let data = {}
      payload.forEach((chunk) => {
        data[chunk.id] = chunk
      })
      return Object.assign({}, field, {
        data
      })
    } else {
      return field
    }
  })
  return form
}


text:
import { FaceFeatureExtractor } from '../faceFeatureExtractor/FaceFeatureExtractor';
import { FaceFeatureExtractorParams } from '../faceFeatureExtractor/types';
import { FaceLandmark68NetBase } from './FaceLandmark68NetBase';
export declare class FaceLandmark68Net extends FaceLandmark68NetBase<FaceFeatureExtractorParams> {
    constructor(faceFeatureExtractor?: FaceFeatureExtractor);
    protected getDefaultModelName(): string;
    protected getClassifierChannelsIn(): number;
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('tournament', '0017_registration_status_changed_date'),
    ]

    operations = [
        migrations.AlterField(
            model_name='pairing',
            name='date_played',
            field=models.DateTimeField(blank=True, null=True),
        ),
        migrations.AlterField(
            model_name='round',
            name='end_date',
            field=models.DateTimeField(),
        ),
        migrations.AlterField(
            model_name='round',
            name='start_date',
            field=models.DateTimeField(),
        ),
    ]


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~  Copyright(c) 2017 lizhaotailang
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout_scan_code"
    android:fitsSystemWindows="true"
    tools:context=".zxing.CaptureActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/app_bar"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:elevation="0dp">

        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:id="@+id/toolbar"
            android:background="@color/colorPrimary"
            android:title="@string/scan_code"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize">

        <SurfaceView
            android:id="@+id/capture_preview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <RelativeLayout
            android:id="@+id/capture_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <ImageView
                android:id="@+id/capture_mask_top"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                android:layout_alignParentTop="true"
                android:background="@drawable/shadow" />

            <RelativeLayout
                android:id="@+id/capture_crop_view"
                android:layout_width="200dp"
                android:layout_height="200dp"
                android:layout_below="@id/capture_mask_top"
                android:layout_centerHorizontal="true"
                android:background="@drawable/qr_code_bg" >

                <ImageView
                    android:id="@+id/capture_scan_line"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_marginBottom="5dp"
                    android:layout_marginTop="5dp"
                    android:src="@drawable/scan_line" />
            </RelativeLayout>

            <ImageView
                android:id="@+id/capture_mask_bottom"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_below="@id/capture_crop_view"
                android:background="@drawable/shadow" />

            <ImageView
                android:id="@+id/capture_mask_left"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_above="@id/capture_mask_bottom"
                android:layout_alignParentStart="true"
                android:layout_below="@id/capture_mask_top"
                android:layout_toStartOf="@id/capture_crop_view"
                android:background="@drawable/shadow" />

            <ImageView
                android:id="@+id/capture_mask_right"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_above="@id/capture_mask_bottom"
                android:layout_alignParentEnd="true"
                android:layout_below="@id/capture_mask_top"
                android:layout_toEndOf="@id/capture_crop_view"
                android:background="@drawable/shadow" />
        </RelativeLayout>

    </FrameLayout>

</android.support.design.widget.CoordinatorLayout>


text:
<?php
/**
 * WordPress Coding Standard.
 *
 * @package WPCS\WordPressCodingStandards
 * @link    https://github.com/WordPress/WordPress-Coding-Standards
 * @license https://opensource.org/licenses/MIT MIT
 */

namespace WordPressCS\WordPress\Sniffs\PHP;

use WordPressCS\WordPress\AbstractFunctionParameterSniff;

/**
 * Flag calling preg_quote() without the second ($delimiter) parameter.
 *
 * @package WPCS\WordPressCodingStandards
 *
 * @since   1.0.0
 */
class PregQuoteDelimiterSniff extends AbstractFunctionParameterSniff {

	/**
	 * The group name for this group of functions.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	protected $group_name = 'preg_quote';

	/**
	 * List of functions this sniff should examine.
	 *
	 * @link http://php.net/preg_quote
	 *
	 * @since 1.0.0
	 *
	 * @var array <string function_name> => <bool>
	 */
	protected $target_functions = array(
		'preg_quote' => true,
	);

	/**
	 * Process the parameters of a matched function.
	 *
	 * @since 1.0.0
	 *
	 * @param int    $stackPtr        The position of the current token in the stack.
	 * @param string $group_name      The name of the group which was matched.
	 * @param string $matched_content The token content (function name) which was matched.
	 * @param array  $parameters      Array with information about the parameters.
	 *
	 * @return void
	 */
	public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
		if ( \count( $parameters ) > 1 ) {
			return;
		}

		$this->phpcsFile->addWarning(
			'Passing the $delimiter as the second parameter to preg_quote() is strongly recommended.',
			$stackPtr,
			'Missing'
		);
	}

}


text:
note this version might lag behind current development changes

`sudo pip install mppsolar`

## venv Install - recommended if testing new features / release ##
for when you want to keep the install and dependencies separate from the rest of the environment
* create venv folder `mkdir ~/venv`
* create venv `python3 -m venv ~/venv/mppsolar`
    * might need python3-venv installed
* activate venv `source venv/mppsolar/bin/activate` (needed each time before using)
* pip install from git `pip install -e "git+https://github.com/jblance/mpp-solar.git#egg=mppsolar"` (only needed if the code is updated)

see worked example [here](venv.md)

### Install development version from github ###
`sudo pip install -e "git+https://github.com/jblance/mpp-solar.git#egg=mppsolar"`

### Ubuntu Install example ###
[Documented Ubuntu Install](ubuntu_install.md)


text:
from inceptionModel import *
import sys
from ops import *
import shutil

bottleneck, target, keep_prob = getPlaceHolders()
vector, graph = interpret(bottleneck, keep_prob)
optim, lossVal = getOptimStep(vector, graph, target)
accuracy = accuracy(graph, target)

# this is for the summaries during the training
merged = tf.summary.merge_all()

data = dataset('inception_data/')
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # creating new summary writers and deleting old summary logs
    shutil.rmtree(log_dir, ignore_errors=True)
    train_writer, test_writer = getSummaryWriters(sess)
    # loadModel(sess, model_save_path[0])
    # loadModel(sess, model_save_path[1])

    cycles = 1200000
    testStep = 500
    saveStep = 4000
    log_step = 100
    startTime = time.time()
    test_batch_size = 700
    try:
        for i in range(cycles):
            batch = data.next_batch(batch_size)
            _, summary = sess.run([optim, merged], feed_dict={
                bottleneck: batch[0],
                target: batch[1],
                keep_prob:0.6
            })
            if i % log_step == 0: train_writer.add_summary(summary, i)

            timer = estimate_time(startTime, cycles, i)
            pL = 20 # this is the length of the progress bar to be displayed
            pNum = i % pL
            pBar = '#'*pNum + ' '*(pL - pNum)

            sys.stdout.write('...Training...|%s|-(%s/%s)- %s\r'%(pBar, i, cycles, timer))

            if i % testStep == 0:
                testBatch = data.test_batch(test_batch_size)
                summary, acc, lval, graph_out, vec = sess.run([
                    merged,
                    accuracy,
                    lossVal,
                    graph,
                    vector
                    ],feed_dict={
                        bottleneck: testBatch[0],
                        target: testBatch[1],
                        keep_prob:1.0
                    }
                )
                test_writer.add_summary(summary, i)

                g_sum = int(np.sum(graph_out))
                t_sum = int(np.sum(testBatch[1]))
                # tracker helps to compare the data being printed to previous run with same
                # training examples
                # tracker = (i/testStep)%(2500/test_batch_size)
                # print(testBatch[0][0])
                # print(vec[0], testBatch[1][0])
                print('Acc: %.2f; L: %.2f; Sums: %s/%s%s'%(acc, lval,g_sum,t_sum,' '*40))

        # now saving the trained model every 1500 cycles
            if i % saveStep == 0 and i != 0:
                saveModel(sess, model_save_path[1])

        # saving the model in the end
        saveModel(sess, model_save_path[1])
    # if the training is interrupted from keyboard (ctrl + c)
    except KeyboardInterrupt:
        print('')
        print('You interrupted the training process')
        decision = input('Do you want to save the current model before exiting? (y/n):')

        if decision == 'y':
            saveModel(sess, model_save_path[1])
        elif decision == 'n':
            print('\n...Model not saved...')
            pass
        else:
            print('\n...Invalid input. Model not saved...')
            pass


text:
<?php

/**
 * This is a widget with most read faq-questions
 *
 * @author Annelies Van Extergem <annelies.vanextergem@netlash.com>
 */
class FrontendFaqWidgetMostRead extends FrontendBaseWidget
{
	/**
	 * Execute the extra
	 */
	public function execute()
	{
		// call parent
		parent::execute();

		$this->loadTemplate();
		$this->parse();
	}

	/**
	 * Parse
	 */
	private function parse()
	{
		$this->tpl->assign('widgetFaqMostRead', FrontendFaqModel::getMostRead(FrontendModel::getModuleSetting('faq', 'most_read_num_items', 10)));
	}
}