text:
namespace ash {

namespace {
const char kTransparentButtonName[] = "TransparentButton";

// Transparent button that handles events to activate or close windows in
// overview mode.
class TransparentButton
    : public views::CustomButton,
      public views::ButtonListener {
 public:
  explicit TransparentButton(TransparentActivateWindowButtonDelegate* delegate);

  ~TransparentButton() override;

  TransparentActivateWindowButtonDelegate* delegate() { return delegate_; }

  // views::View:
  void OnGestureEvent(ui::GestureEvent* event) override;

  const char* GetClassName() const override { return kTransparentButtonName; }

  // views::ButtonListener:
  void ButtonPressed(views::Button* sender, const ui::Event& event) override;

 private:
  TransparentActivateWindowButtonDelegate* delegate_;

  DISALLOW_COPY_AND_ASSIGN(TransparentButton);
};

TransparentButton::TransparentButton(
        TransparentActivateWindowButtonDelegate* delegate)
    : CustomButton(this),
      delegate_(delegate) {
}

TransparentButton::~TransparentButton() {
}

void TransparentButton::OnGestureEvent(ui::GestureEvent* event) {
  // TODO(tdanderson): Re-evaluate whether we want to set capture once
  //                   the a fix has landed to avoid crashing when a window
  //                   having an active gesture sequence is destroyed as a
  //                   result of a gesture in a separate window. Consider using
  //                   a StaticWindowTargeter instead of a transparent overlay
  //                   widget to re-direct input events.
  if (event->type() == ui::ET_GESTURE_TAP_DOWN)
    GetWidget()->SetCapture(this);

  if (event->type() == ui::ET_GESTURE_TAP ||
      event->type() == ui::ET_GESTURE_END) {
    GetWidget()->ReleaseCapture();
  }

  CustomButton::OnGestureEvent(event);
  event->StopPropagation();
}

void TransparentButton::ButtonPressed(views::Button* sender,
                                      const ui::Event& event) {
  delegate_->Select();
}

// Initializes the event handler transparent window.
views::Widget* InitEventHandler(aura::Window* root_window) {
  views::Widget* widget = new views::Widget;
  views::Widget::InitParams params;
  params.type = views::Widget::InitParams::TYPE_POPUP;
  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
  params.accept_events = true;
  params.parent = Shell::GetContainer(root_window,
                                      kShellWindowId_OverlayContainer);
  widget->set_focus_on_creation(false);
  widget->Init(params);
  widget->Show();

  aura::Window* handler = widget->GetNativeWindow();
  handler->parent()->StackChildAtBottom(handler);

  return widget;
}

}  // namespace

TransparentActivateWindowButton::TransparentActivateWindowButton(
        aura::Window* root_window,
        TransparentActivateWindowButtonDelegate* delegate)
    : event_handler_widget_(InitEventHandler(root_window)),
      transparent_button_(new TransparentButton(delegate)) {
  event_handler_widget_->SetContentsView(transparent_button_);
}

TransparentActivateWindowButton::~TransparentActivateWindowButton() {
}

void TransparentActivateWindowButton::SetAccessibleName(
    const base::string16& name) {
  transparent_button_->SetAccessibleName(name);
}

void TransparentActivateWindowButton::SetBounds(const gfx::Rect& bounds) {
  aura::Window* window = event_handler_widget_->GetNativeWindow();
  const gfx::Display& display = gfx::Screen::GetScreenFor(
      window)->GetDisplayNearestWindow(window);
  // Explicitly specify the display so that the window doesn't change root
  // windows and cause the z-order of the transparent overlays to be updated.
  window->SetBoundsInScreen(bounds, display);
}

void TransparentActivateWindowButton::SendFocusAlert() const {
  event_handler_widget_->GetContentsView()->
      NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
}

void TransparentActivateWindowButton::StackAbove(
    TransparentActivateWindowButton* activate_button) {
  aura::Window* this_window = event_handler_widget_->GetNativeWindow();
  aura::Window* other_window = activate_button->event_handler_widget_->
      GetNativeWindow();
  this_window->parent()->StackChildAbove(this_window, other_window);
}

}  // namespace ash


text:
require_relative '../init'
require_relative 'gem_updater'

module AppPreloader
  def self.preload!
    copy_static_files
    start_update_gems_timer
    GC.compact
  end

  def self.copy_static_files
    # Copy template files
    puts ">> Copying static system files..."
    YARD::Templates::Engine.template(:default, :fulldoc, :html).full_paths.each do |path|
      %w(css js images).each do |ext|
        srcdir, dstdir = File.join(path, ext), File.join('public', ext)
        next unless File.directory?(srcdir)
        system "mkdir -p #{dstdir} && cp #{srcdir}/* #{dstdir}/"
      end
    end
  end

  def self.start_update_gems_timer
    Thread.new do
      loop do
        fork { GemUpdater.update_remote_gems display: true }
        sleep 600
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.lucene.analysis.standard;

import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.std31.StandardTokenizerImpl31;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.Version;

import java.io.IOException;
import java.io.Reader;

/** A grammar-based tokenizer constructed with JFlex.
 *

 * As of Lucene version 3.1, this class implements the Word Break rules from the
 * Unicode Text Segmentation algorithm, as specified in
 * Unicode Standard Annex #29.
 *

 *
Many applications have specific tokenizer needs.  If this tokenizer does
 * not suit your application, please consider copying this source code
 * directory to your project and maintaining your own grammar-based tokenizer.
 *
 *
 *
You must specify the required {@link Version}
 * compatibility when creating StandardTokenizer:
 *

 *
 As of 3.4, Hiragana and Han characters are no longer wrongly split
 *   from their combining characters. If you use a previous version number,
 *   you get the exact broken behavior for backwards compatibility.
 *
 As of 3.1, StandardTokenizer implements Unicode text segmentation.
 *   If you use a previous version number, you get the exact behavior of
 *   {@link ClassicTokenizer} for backwards compatibility.
 *

 */

public final class StandardTokenizer extends Tokenizer {
  /** A private instance of the JFlex-constructed scanner */
  private StandardTokenizerInterface scanner;

  public static final int ALPHANUM          = 0;
  /** @deprecated */
  @Deprecated
  public static final int APOSTROPHE        = 1;
  /** @deprecated */
  @Deprecated
  public static final int ACRONYM           = 2;
  /** @deprecated */
  @Deprecated
  public static final int COMPANY           = 3;
  public static final int EMAIL             = 4;
  /** @deprecated */
  @Deprecated
  public static final int HOST              = 5;
  public static final int NUM               = 6;
  /** @deprecated */
  @Deprecated
  public static final int CJ                = 7;

  /**
   * @deprecated this solves a bug where HOSTs that end with '.' are identified
   *             as ACRONYMs.
   */
  @Deprecated
  public static final int ACRONYM_DEP       = 8;

  public static final int SOUTHEAST_ASIAN = 9;
  public static final int IDEOGRAPHIC = 10;
  public static final int HIRAGANA = 11;
  public static final int KATAKANA = 12;
  public static final int HANGUL = 13;

  /** String token types that correspond to token type int constants */
  public static final String [] TOKEN_TYPES = new String [] {
    "<ALPHANUM>",
    "<APOSTROPHE>",
    "<ACRONYM>",
    "<COMPANY>",
    "<EMAIL>",
    "<HOST>",
    "<NUM>",
    "<CJ>",
    "<ACRONYM_DEP>",
    "<SOUTHEAST_ASIAN>",
    "<IDEOGRAPHIC>",
    "<HIRAGANA>",
    "<KATAKANA>",
    "<HANGUL>"
  };

  private boolean replaceInvalidAcronym;

  private int maxTokenLength = StandardAnalyzer.DEFAULT_MAX_TOKEN_LENGTH;

  /** Set the max allowed token length.  Any token longer
   *  than this is skipped. */
  public void setMaxTokenLength(int length) {
    this.maxTokenLength = length;
  }

  /** @see #setMaxTokenLength */
  public int getMaxTokenLength() {
    return maxTokenLength;
  }

  /**
   * Creates a new instance of the {@link org.apache.lucene.analysis.standard.StandardTokenizer}.  Attaches
   * the input to the newly created JFlex scanner.
   *
   * @param input The input reader
   *
   * See http://issues.apache.org/jira/browse/LUCENE-1068
   */
  public StandardTokenizer(Version matchVersion, Reader input) {
    super();
    init(input, matchVersion);
  }

  /**
   * Creates a new StandardTokenizer with a given {@link AttributeSource}.
   */
  public StandardTokenizer(Version matchVersion, AttributeSource source, Reader input) {
    super(source);
    init(input, matchVersion);
  }

  /**
   * Creates a new StandardTokenizer with a given {@link org.apache.lucene.util.AttributeSource.AttributeFactory}
   */
  public StandardTokenizer(Version matchVersion, AttributeFactory factory, Reader input) {
    super(factory);
    init(input, matchVersion);
  }

  private final void init(Reader input, Version matchVersion) {
    if (matchVersion.onOrAfter(Version.LUCENE_34)) {
      this.scanner = new StandardTokenizerImpl(input);
    } else if (matchVersion.onOrAfter(Version.LUCENE_31)) {
      this.scanner = new StandardTokenizerImpl31(input);
    } else {
      this.scanner = new ClassicTokenizerImpl(input);
    }
    if (matchVersion.onOrAfter(Version.LUCENE_24)) {
      replaceInvalidAcronym = true;
    } else {
      replaceInvalidAcronym = false;
    }
    this.input = input;
  }

  // this tokenizer generates three attributes:
  // term offset, positionIncrement and type
  private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
  private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
  private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
  private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);

  /*
   * (non-Javadoc)
   *
   * @see org.apache.lucene.analysis.TokenStream#next()
   */
  @Override
  public final boolean incrementToken() throws IOException {
    clearAttributes();
    int posIncr = 1;

    while(true) {
      int tokenType = scanner.getNextToken();

      if (tokenType == StandardTokenizerInterface.YYEOF) {
        return false;
      }

      if (scanner.yylength() <= maxTokenLength) {
        posIncrAtt.setPositionIncrement(posIncr);
        scanner.getText(termAtt);
        final int start = scanner.yychar();
        offsetAtt.setOffset(correctOffset(start), correctOffset(start+termAtt.length()));
        // This 'if' should be removed in the next release. For now, it converts
        // invalid acronyms to HOST. When removed, only the 'else' part should
        // remain.
        if (tokenType == StandardTokenizer.ACRONYM_DEP) {
          if (replaceInvalidAcronym) {
            typeAtt.setType(StandardTokenizer.TOKEN_TYPES[StandardTokenizer.HOST]);
            termAtt.setLength(termAtt.length() - 1); // remove extra '.'
          } else {
            typeAtt.setType(StandardTokenizer.TOKEN_TYPES[StandardTokenizer.ACRONYM]);
          }
        } else {
          typeAtt.setType(StandardTokenizer.TOKEN_TYPES[tokenType]);
        }
        return true;
      } else
        // When we skip a too-long term, we still increment the
        // position increment
        posIncr++;
    }
  }

  @Override
  public final void end() {
    // set final offset
    int finalOffset = correctOffset(scanner.yychar() + scanner.yylength());
    offsetAtt.setOffset(finalOffset, finalOffset);
  }

  @Override
  public void reset(Reader reader) throws IOException {
    super.reset(reader);
    scanner.yyreset(reader);
  }

  /**
   * Prior to https://issues.apache.org/jira/browse/LUCENE-1068, StandardTokenizer mischaracterized as acronyms tokens like www.abc.com
   * when they should have been labeled as hosts instead.
   * @return true if StandardTokenizer now returns these tokens as Hosts, otherwise false
   *
   * @deprecated Remove in 3.X and make true the only valid value
   */
  @Deprecated
  public boolean isReplaceInvalidAcronym() {
    return replaceInvalidAcronym;
  }

  /**
   *
   * @param replaceInvalidAcronym Set to true to replace mischaracterized acronyms as HOST.
   * @deprecated Remove in 3.X and make true the only valid value
   *
   * See https://issues.apache.org/jira/browse/LUCENE-1068
   */
  @Deprecated
  public void setReplaceInvalidAcronym(boolean replaceInvalidAcronym) {
    this.replaceInvalidAcronym = replaceInvalidAcronym;
  }
}


text:
layout: page
title: Snow Entertainment Executive Retreat
date: 2016-05-24
author: Harry Stuart
tags: weekly links, java
status: published
summary: Nullam risus dolor, fringilla ullamcorper convallis non, porttitor eget mauris.
banner: images/banner/office-01.jpg
booking:
  startDate: 05/31/2018
  endDate: 06/05/2018
  ctyhocn: BILMTHX
  groupCode: SEER
published: true
---
Nunc eget finibus ligula, nec mollis nulla. Sed rutrum, nisi quis gravida finibus, diam risus pellentesque mi, at tempor lorem felis vitae lorem. Integer dignissim varius velit et sollicitudin. Vestibulum lobortis gravida dolor ut volutpat. Sed id dignissim tellus. In hac habitasse platea dictumst. Nunc ut tincidunt tellus, eu consectetur ante.
Pellentesque vitae quam lorem. Sed at augue ullamcorper, sagittis ligula a, molestie nunc. Quisque consectetur semper condimentum. Donec volutpat convallis dolor, et pulvinar ex pretium nec. Phasellus viverra lacus ut lectus varius sodales. Pellentesque egestas iaculis nibh rutrum maximus. Vivamus eu erat nec metus ornare maximus. Vivamus tristique venenatis pulvinar. Ut ac molestie leo. Nunc ac semper nulla. Duis dapibus tempus magna, quis vestibulum purus mattis vel. Sed ut dui orci.

* Aenean faucibus augue eget nisl fringilla tristique
* Nullam ultricies ex ac quam condimentum, vitae pulvinar est tristique
* Morbi pellentesque nisl non ultrices viverra.

In vitae pretium diam. Vivamus consequat sapien ut ex volutpat, ac sollicitudin diam semper. In volutpat magna sit amet iaculis tincidunt. Duis maximus dolor ac sapien venenatis interdum. Donec nibh leo, eleifend in dolor eu, sodales hendrerit est. Nullam gravida at tellus nec volutpat. Vivamus eu magna neque. Fusce sed elementum turpis.
Vestibulum quis pharetra ante, id luctus quam. In tincidunt cursus elementum. Morbi in venenatis urna, non pulvinar dui. Suspendisse imperdiet sodales hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pellentesque sit amet quam nec mollis. Mauris dapibus eros sit amet tortor sagittis, vitae dapibus augue condimentum. Morbi non erat erat. In dignissim, nunc sit amet fermentum lobortis, justo ex pharetra quam, eget fringilla risus sem in velit. Phasellus pharetra tempus est et mollis.


text:
from builtins import object
class Module(object):

    def __init__(self, mainMenu, params=[]):

        # metadata info about the module, not modified during runtime
        self.info = {
            # name for the module that will appear in module menus
            'Name': 'Sandbox-Keychain-Dump',

            # list of one or more authors for the module
            'Author': ['@import-au'],

            # more verbose multi-line description of the module
            'Description': ("Uses Apple Security utility to dump the contents of the keychain. "
                            "WARNING: Will prompt user for access to each key."
                            "On Newer versions of Sierra and High Sierra, this will also ask the user for their password for each key."),

            'Software': '',

            'Techniques': ['T1142'],

            # True if the module needs to run in the background
            'Background' : False,

            # File extension to save the file as
            'OutputExtension' : "",

            # if the module needs administrative privileges
            'NeedsAdmin' : False,

            # True if the method doesn't touch disk/is reasonably opsec safe
            'OpsecSafe' : False,

            # the module language
            'Language' : 'python',

            # the minimum language version needed
            'MinLanguageVersion' : '2.6',

            # list of any references/other comments
            'Comments': [
                ""
            ]
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent' : {
                # The 'Agent' option is the only one that MUST be in a module
                'Description'   :   'Agent to execute module on.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'OutFile' : {
                'Description': 'File to output AppleScript to, otherwise displayed on the screen.',
                'Required': False,
                'Value': ''
            }
        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        # During instantiation, any settable option parameters
        #   are passed as an object set to the module and the
        #   options dictionary is automatically set. This is mostly
        #   in case options are passed on the command line
        if params:
            for param in params:
                # parameter format is [Name, Value]
                option, value = param
                if option in self.options:
                    self.options[option]['Value'] = value

    def generate(self, obfuscate=False, obfuscationCommand=""):

        script = r"""
import subprocess
import re

process = subprocess.Popen('/usr/bin/security dump-keychain -d', stdout=subprocess.PIPE, shell=True)
keychain = process.communicate()
find_account = re.compile('0x00000007\s\<blob\>\=\"([^\"]+)\"\n.*\n.*\"acct\"\<blob\>\=\"([^\"]+)\"\n.*\n.*\n.*\n\s+\"desc\"\<blob\>\=([^\n]+)\n.*\n.*\n.*\n.*\n.*\n.*\n.*\n.*\n.*\ndata\:\n([^\n]+)')
accounts = find_account.findall(keychain[0])
for account in accounts:
    print("System: " + account[0])
    print("Description: " + account[2])
    print("Username: " + account[1])
    print("Secret: " + account[3])

"""

        return script


text:
#ifndef _SYSTEM_SAMD21_H_INCLUDED_
#define _SYSTEM_SAMD21_H_INCLUDED_

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

extern uint32_t SystemCoreClock;   /*!< System Clock Frequency (Core Clock)  */

void SystemInit(void);
void SystemCoreClockUpdate(void);

#ifdef __cplusplus
}
#endif

#endif /* SYSTEM_SAMD21_H_INCLUDED */


text:
package me.deftware.client.framework.event.events;

import me.deftware.client.framework.event.Event;
import me.deftware.client.framework.math.position.ChunkBlockPosition;
import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket;
import net.minecraft.util.math.ChunkPos;

public class EventChunkDataReceive extends Event {

    private final ChunkPos rawPos;
    private final ChunkBlockPosition pos;

    public boolean isInitialFullChunk, updatedIsFullChunk;

    private final ChunkDataS2CPacket rootPacket;

    public ChunkDataS2CPacket getRootPacket() {
        return rootPacket;
    }

    public ChunkPos getRawPos() {
        return rawPos;
    }

    public ChunkBlockPosition getPos() {
        return pos;
    }

    public EventChunkDataReceive(ChunkDataS2CPacket rootPacket) {
        this.rootPacket = rootPacket;
        this.rawPos = new ChunkPos(rootPacket.getX(), rootPacket.getZ());
        this.pos = new ChunkBlockPosition(rawPos);
        isInitialFullChunk = rootPacket.isWritingErrorSkippable(); // TODO: Verify isWritingErrorSkippable
        updateFullChunk(rootPacket);
    }

    private void updateFullChunk(ChunkDataS2CPacket rootPacket) {
        updatedIsFullChunk = rootPacket.isWritingErrorSkippable();
    }

}


text:
import java.util.*;
import java.util.stream.Collectors;

public class Main {
  public List<CharSequence> getListCharSequence(List<String> input) {
    List<CharSequence> result = input.stream().filter(s -> !s.isEmpty()).map(String::trim).collect(Collectors.toList());
      return result;
  }
}


text:
<md-list>
    <md-subheader>

{{::to.label}}

        <md-input-container flex ng-show="to.showSearch" md-no-float class="no-margins no-padding">
            <input ng-model="itemSearchText" placeholder="Search...">
        </md-input-container>
    </md-subheader>

        <md-list-item ng-if="to.multiple" ng-repeat="option in to.options | filter:itemSearchText:false:(to.labelProp || 'title')">

 {{ ::option[to.labelProp || 'title'] }}

            <md-checkbox class="md-secondary" aria-label="{{::option[to.labelProp || 'title']}}" ng-checked="isChecked(option[to.valueProp || 'value'])" ng-click="onCheck(option[to.valueProp || 'value'])"></md-checkbox>
        </md-list-item>

        <md-radio-group ng-if="!to.multiple" ng-model="model[options.key]">
            <md-list-item ng-repeat="option in to.options">

 {{ ::option[to.labelProp || 'title'] }}

                <md-radio-button aria-label="{{::option[to.labelProp || 'title']}}" class="md-secondary" ng-value="option[to.valueProp || 'value']"></md-radio-button>
            </md-list-item>
        </md-radio-group>

    <md-divider></md-divider>
</md-list>


text:
static void helpMessage(){
    //Select the executable name
    #ifdef _WIN32
    const std::string EXECUTABLE = "latexImprover.exe";
    #else
    const std::string EXECUTABLE = "latexImprover";
    #endif // _WIN32

    std::cerr << "usage: " << EXECUTABLE << " [options] filenames..\n"
              << "Options:\n"
              << "\t-h\t\tShow this help message\n"
              << "\t-d\t\tDebug mode"
              << std::endl;
}

int main(int argc, char* argv[]){
    bool debug = false;
    int fileCount = 0;
    if(argc < 2){
        helpMessage();
        return 1;
    }
    for (int i = 1; i < argc; ++i){// argv[0] is not interesting, since it's just the program's path.
        if(std::strcmp(argv[i], "-d") == 0){
            debug = true;
        }
        else if(std::strcmp(argv[i], "-h") == 0){
            helpMessage();
            return 0;
        }
        else{
            fileCount++;
            std::string filePath = argv[i];
            std::ifstream file(filePath);
            if(file){
                auto started = std::chrono::high_resolution_clock::now();
                std::stringstream buffer;
                std::stringstream out;
                buffer << file.rdbuf();
                file.close();
                latexImprover(buffer, out);
                std::ostringstream convert;
                convert << fileCount;
                std::ofstream file("newFile" + convert.str() + ".tex");
                if (file){
                    file << out.rdbuf();
                    file.close();
                }
                if(debug){
                    auto done = std::chrono::high_resolution_clock::now();
                    std::cout << "Executed: " << filePath << " In: " << std::chrono::duration_cast<std::chrono::milliseconds>(done-started).count() << "ms" << std::endl;
                }
            }
        }
    }
    if(fileCount < 1){
        //No files has been provided
        helpMessage();
        return 1;
    }
    return 0;
}


text:
/**
 * @file rnn_impl.hpp
 * @author Marcus Edel
 *
 * Definition of the RNN class, which implements recurrent neural networks.
 */
#ifndef MLPACK_METHODS_ANN_RNN_IMPL_HPP
#define MLPACK_METHODS_ANN_RNN_IMPL_HPP

// In case it hasn't been included yet.
#include "rnn.hpp"

namespace mlpack {
namespace ann /** Artificial Neural Network. */ {

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
template<typename LayerType,
         typename OutputType,
         template<typename> class OptimizerType
>
RNN<LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::RNN(LayerType &&network,
       OutputType &&outputLayer,
       const arma::mat& predictors,
       const arma::mat& responses,
       OptimizerType<NetworkType>& optimizer,
       InitializationRuleType initializeRule,
       PerformanceFunction performanceFunction) :
    network(std::forward<LayerType>(network)),
    outputLayer(std::forward<OutputType>(outputLayer)),
    performanceFunc(std::move(performanceFunction)),
    predictors(predictors),
    responses(responses),
    numFunctions(predictors.n_cols),
    inputSize(0),
    outputSize(0)
{
  static_assert(std::is_same<typename std::decay<LayerType>::type,
                  LayerTypes>::value,
                  "The type of network must be LayerTypes.");

  static_assert(std::is_same<typename std::decay<OutputType>::type,
                OutputLayerType>::value,
                "The type of outputLayer must be OutputLayerType.");

  initializeRule.Initialize(parameter, NetworkSize(this->network), 1);
  NetworkWeights(parameter, this->network);

  // Train the model.
  Timer::Start("rnn_optimization");
  const double out = optimizer.Optimize(parameter);
  Timer::Stop("rnn_optimization");

  Log::Info << "RNN::RNN(): final objective of trained model is " << out
      << "." << std::endl;
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
template<typename LayerType, typename OutputType>
RNN<LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::RNN(LayerType &&network,
       OutputType &&outputLayer,
       const arma::mat& predictors,
       const arma::mat& responses,
       InitializationRuleType initializeRule,
       PerformanceFunction performanceFunction) :
    network(std::forward<LayerType>(network)),
    outputLayer(std::forward<OutputType>(outputLayer)),
    performanceFunc(std::move(performanceFunction)),
    inputSize(0),
    outputSize(0)
{
  static_assert(std::is_same<typename std::decay<LayerType>::type,
                  LayerTypes>::value,
                  "The type of network must be LayerTypes.");

  static_assert(std::is_same<typename std::decay<OutputType>::type,
                OutputLayerType>::value,
                "The type of outputLayer must be OutputLayerType.");

  initializeRule.Initialize(parameter, NetworkSize(this->network), 1);
  NetworkWeights(parameter, this->network);

  Train(predictors, responses);
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
template<typename LayerType, typename OutputType>
RNN<LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::RNN(LayerType &&network,
       OutputType &&outputLayer,
       InitializationRuleType initializeRule,
       PerformanceFunction performanceFunction) :
    network(std::forward<LayerType>(network)),
    outputLayer(std::forward<OutputType>(outputLayer)),
    performanceFunc(std::move(performanceFunction)),
    inputSize(0),
    outputSize(0)
{
  static_assert(std::is_same<typename std::decay<LayerType>::type,
                  LayerTypes>::value,
                  "The type of network must be LayerTypes.");

  static_assert(std::is_same<typename std::decay<OutputType>::type,
                OutputLayerType>::value,
                "The type of outputLayer must be OutputLayerType.");

  initializeRule.Initialize(parameter, NetworkSize(this->network), 1);
  NetworkWeights(parameter, this->network);
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
template<template<typename> class OptimizerType>
void RNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Train(const arma::mat& predictors, const arma::mat& responses)
{
  numFunctions = predictors.n_cols;
  this->predictors = predictors;
  this->responses = responses;

  OptimizerType<decltype(*this)> optimizer(*this);

  // Train the model.
  Timer::Start("rnn_optimization");
  const double out = optimizer.Optimize(parameter);
  Timer::Stop("rnn_optimization");

  Log::Info << "RNN::RNN(): final objective of trained model is " << out
      << "." << std::endl;
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
template<template<typename> class OptimizerType>
void RNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Train(const arma::mat& predictors,
         const arma::mat& responses,
         OptimizerType<NetworkType>& optimizer)
{
  numFunctions = predictors.n_cols;
  this->predictors = predictors;
  this->responses = responses;

  // Train the model.
  Timer::Start("rnn_optimization");
  const double out = optimizer.Optimize(parameter);
  Timer::Stop("rnn_optimization");

  Log::Info << "RNN::RNN(): final objective of trained model is " << out
      << "." << std::endl;
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
template<
    template<typename> class OptimizerType
>
void RNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Train(OptimizerType<NetworkType>& optimizer)
{
  // Train the model.
  Timer::Start("rnn_optimization");
  const double out = optimizer.Optimize(parameter);
  Timer::Stop("rnn_optimization");

  Log::Info << "RNN::RNN(): final objective of trained model is " << out
      << "." << std::endl;
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
void RNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Predict(arma::mat& predictors, arma::mat& responses)
{
  arma::mat responsesTemp;
  SinglePredict(arma::mat(predictors.colptr(0), predictors.n_rows,
      1, false, true), responsesTemp);

  responses = arma::mat(responsesTemp.n_elem, predictors.n_cols);
  responses.col(0) = responsesTemp.col(0);

  for (size_t i = 1; i < predictors.n_cols; i++)
  {
    SinglePredict(arma::mat(predictors.colptr(i), predictors.n_rows,
      1, false, true), responsesTemp);
    responses.col(i) = responsesTemp.col(0);
  }
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
double RNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Evaluate(const arma::mat& /* unused */,
            const size_t i,
            const bool deterministic)
{
  this->deterministic = deterministic;

  arma::mat input = arma::mat(predictors.colptr(i), predictors.n_rows,
      1, false, true);
  arma::mat target = arma::mat(responses.colptr(i), responses.n_rows,
      1, false, true);

  // Initialize the activation storage only once.
  if (activations.empty())
    InitLayer(input, target, network);

  double networkError = 0;
  seqLen = input.n_rows / inputSize;
  ResetParameter(network);

  error = arma::mat(outputSize, outputSize < target.n_elem ? seqLen : 1);

  // Iterate through the input sequence and perform the feed forward pass.
  for (seqNum = 0; seqNum < seqLen; seqNum++)
  {
    // Perform the forward pass and save the activations.
    Forward(input.rows(seqNum * inputSize, (seqNum + 1) * inputSize - 1),
        network);
    SaveActivations(network);

    // Retrieve output error of the subsequence.
    if (seqOutput)
    {
      arma::mat seqError = error.unsafe_col(seqNum);
      arma::mat seqTarget = target.submat(seqNum * outputSize, 0,
          (seqNum + 1) * outputSize - 1, 0);
      networkError += OutputError(seqTarget, seqError, network);
    }
  }

  // Retrieve output error of the complete sequence.
  if (!seqOutput)
    return OutputError(target, error, network);

  return networkError;
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
void RNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Gradient(const arma::mat& /* unused */,
            const size_t i,
            arma::mat& gradient)
{
  if (gradient.is_empty())
  {
    gradient = arma::zeros<arma::mat>(parameter.n_rows, parameter.n_cols);
  }
  else
  {
    gradient.zeros();
  }

  Evaluate(parameter, i, false);

  arma::mat currentGradient = arma::mat(gradient.n_rows, gradient.n_cols);
  NetworkGradients(currentGradient, network);

  const arma::mat input = arma::mat(predictors.colptr(i), predictors.n_rows,
      1, false, true);

  // Iterate through the input sequence and perform the feed backward pass.
  for (seqNum = seqLen - 1; seqNum >= 0; seqNum--)
  {
    // Load the network activation for the upcoming backward pass.
    LoadActivations(input.rows(seqNum * inputSize, (seqNum + 1) *
        inputSize - 1), network);

    // Perform the backward pass.
    if (seqOutput)
    {
      arma::mat seqError = error.unsafe_col(seqNum);
      Backward(seqError, network);
    }
    else
    {
      Backward(error, network);
    }

    // Link the parameters and update the gradients.
    LinkParameter(network);
    UpdateGradients<>(network);

    // Update the overall gradient.
    gradient += currentGradient;

    if (seqNum == 0) break;
  }
}

template<typename LayerTypes,
         typename OutputLayerType,
         typename InitializationRuleType,
         typename PerformanceFunction
>
template<typename Archive>
void RNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Serialize(Archive& ar, const unsigned int /* version */)
{
  ar & data::CreateNVP(parameter, "parameter");

  // If we are loading, we need to initialize the weights.
  if (Archive::is_loading::value)
  {
    NetworkWeights(parameter, network);
  }
}

} // namespace ann
} // namespace mlpack

#endif


text:
import logging
import angr

######################################
# futex
######################################

l = logging.getLogger(name=__name__)
#pylint:disable=redefined-builtin,arguments-differ
class futex(angr.SimProcedure):

    def run(self, uaddr, futex_op, val, timeout, uaddr2, val3):
        op = self.state.solver.eval(futex_op)
        if op & 1:  # FUTEX_WAKE
            l.debug('futex(FUTEX_WAKE)')
            return 0
        else:
            l.debug('futex(futex_op=%d)', op)
            return self.state.solver.Unconstrained("futex", self.state.arch.bits, key=('api', 'futex'))


text:
Blog & Comments

            Evan Bartlett

Cameron's silence on defence is shameful

            Jonathan Owen

Architects plan to stop skyscrapers from blocking out sunlight

            Susie Lau

Fashion's first selfies: It was a 16th-century German accountant who started the trend for style blogging

            John Rentoul

How to run a country: A 10 point manifesto for leaders who stand – and want to deliver

            Richard Garner

Controversial plan to test new primary school pupils infuriates teachers

Social

                Like
                31,702

                Follow Us
                164,290

                Add to circle
                5,425,764

Recent News

Misused words and how to use them correctly

Mar 6, 2015

 0

8 health benefits and drawbacks of coffee

Mar 6, 2015

 0

What are the top five books you must read?

Mar 6, 2015

 0

Stylish things to do, see and buy this week

Mar 6, 2015

 0

                Hi-Tech

                Other News

Audio Recorder AR-T7 explained

Mar 6, 2015

 0

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec imperdiet sed eros sed tincidunt.

Apple iPad review

The new MacBook Air Impressions!

                    Mar 6, 2015

Cameron's silence on defence is shameful

                    Mar 7, 2015

Architects plan to stop skyscrapers from blocking out sunlight

                    Mar 9, 2015

Fashion's first selfies: It was a 16th-century German accountant who started the trend for style blogging

                    Mar 12, 2015

How to run a country: A 10 point manifesto for leaders who stand – and want to deliver

                    Mar 23, 2015

Controversial plan to test new primary school pupils infuriates teachers

Tags

Web Design

Economy

Sport

Marketing

Books

Elections

Flickr

Politics

Marketing

Web Hosting

Art & Design

Popular Video

                Holiday
                Mar 6, 2015

Most Beautiful Places

                Science
                Mar 6, 2015

Existance a timeplase project

                Travel
                Mar 6, 2015

Who are the 10 greatest living athletes in the UK?

Twitter Posts

                    Dr.Cafee
                    @DrCafee
                    4h

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                    http://bit.ly/1c0UN3Y

                    Jessi
                    @Jessi
                    5m

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                    http://bit.ly/1c0UN3Y

                    PhotoStudio
                    @PS
                    7h

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                    http://bit.ly/1c0UN3Y

                    Wrapbootstrap
                    @Wrapbootstrap
                    25m

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

                    http://bit.ly/1c0UN3Y


text:
class CreateBlogPosts < ActiveRecord::Migration
  def change
    create_table :blog_posts do |t|
      t.string  :site_url
      t.string  :title
      t.datetime :date
      t.integer :votes
      t.text    :blog_content
    # go to http://stackoverflow.com/questions/22247582/rails-4-saving-images-in-database
    # set images

      t.integer :user_id

      t.timestamps null: false
    end
  end
end


text:
namespace SAMRAI
{
namespace solv
{
template <int DIM>
class RobinBcCoefStrategy;
} // namespace solv
} // namespace SAMRAI

/////////////////////////////// NAMESPACE ////////////////////////////////////

namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////

const std::string INSStaggeredConvectiveOperatorManager::DEFAULT = "DEFAULT";
const std::string INSStaggeredConvectiveOperatorManager::CENTERED = "CENTERED";
const std::string INSStaggeredConvectiveOperatorManager::PPM = "PPM";
const std::string INSStaggeredConvectiveOperatorManager::UPWIND = "UPWIND";
const std::string INSStaggeredConvectiveOperatorManager::STABILIZED_PPM = "STABILIZED_PPM";

INSStaggeredConvectiveOperatorManager* INSStaggeredConvectiveOperatorManager::s_operator_manager_instance = NULL;
bool INSStaggeredConvectiveOperatorManager::s_registered_callback = false;
unsigned char INSStaggeredConvectiveOperatorManager::s_shutdown_priority = 200;

INSStaggeredConvectiveOperatorManager* INSStaggeredConvectiveOperatorManager::getManager()
{
    if (!s_operator_manager_instance)
    {
        s_operator_manager_instance = new INSStaggeredConvectiveOperatorManager();
    }
    if (!s_registered_callback)
    {
        ShutdownRegistry::registerShutdownRoutine(freeManager, s_shutdown_priority);
        s_registered_callback = true;
    }
    return s_operator_manager_instance;
} // getManager

void INSStaggeredConvectiveOperatorManager::freeManager()
{
    delete s_operator_manager_instance;
    s_operator_manager_instance = NULL;
    return;
} // freeManager

/////////////////////////////// PUBLIC ///////////////////////////////////////

Pointer<ConvectiveOperator>
INSStaggeredConvectiveOperatorManager::allocateOperator(const std::string& operator_type,
                                                        const std::string& operator_object_name,
                                                        Pointer<Database> input_db,
                                                        const ConvectiveDifferencingType difference_form,
                                                        const std::vector<RobinBcCoefStrategy<NDIM>*>& bc_coefs) const
{
    std::map<std::string, OperatorMaker>::const_iterator it = d_operator_maker_map.find(operator_type);
    if (it == d_operator_maker_map.end())
    {
        TBOX_ERROR("INSStaggeredConvectiveOperatorManager::allocateOperator():\n"
                   << "  unrecognized operator type: " << operator_type << "\n");
    }
    return (it->second)(operator_object_name, input_db, difference_form, bc_coefs);
} // allocateOperator

void INSStaggeredConvectiveOperatorManager::registerOperatorFactoryFunction(const std::string& operator_type,
                                                                            OperatorMaker operator_maker)
{
    if (d_operator_maker_map.find(operator_type) != d_operator_maker_map.end())
    {
        pout << "INSStaggeredConvectiveOperatorManager::registerOperatorFactoryFunction():\n"
             << "  NOTICE: overriding initialization function for operator_type = " << operator_type << "\n";
    }
    d_operator_maker_map[operator_type] = operator_maker;
    return;
} // registerOperatorFactoryFunction

/////////////////////////////// PROTECTED ////////////////////////////////////

INSStaggeredConvectiveOperatorManager::INSStaggeredConvectiveOperatorManager() : d_operator_maker_map()
{
    registerOperatorFactoryFunction(DEFAULT, INSStaggeredPPMConvectiveOperator::allocate_operator);
    registerOperatorFactoryFunction(CENTERED, INSStaggeredCenteredConvectiveOperator::allocate_operator);
    registerOperatorFactoryFunction(PPM, INSStaggeredPPMConvectiveOperator::allocate_operator);
    registerOperatorFactoryFunction(UPWIND, INSStaggeredUpwindConvectiveOperator::allocate_operator);
    registerOperatorFactoryFunction(STABILIZED_PPM, INSStaggeredStabilizedPPMConvectiveOperator::allocate_operator);
    return;
} // INSStaggeredConvectiveOperatorManager

INSStaggeredConvectiveOperatorManager::~INSStaggeredConvectiveOperatorManager()
{
    // intentionally blank
    return;
} // ~INSStaggeredConvectiveOperatorManager

/////////////////////////////// PRIVATE //////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////

} // namespace IBAMR

//////////////////////////////////////////////////////////////////////////////


text:
var getNumCheckinsOfType = function(_programType) {
	if(!Ti.App.Properties.hasProperty(_programType+'Count')) { //do some caching
		Ti.App.Properties.setInt(_programType+'Count',1);
		return 1;
	} else {
		var numCheckInsSoFar = Ti.App.Properties.getInt(_programType+'Count');
		var newNumCheckins = numCheckInsSoFar + 1
		Ti.App.Properties.setString(_programType+'Count',newNumCheckins);
		return newNumCheckins;
	}
}
exports.getNumCheckinsOfType = getNumCheckinsOfType;

var getNumCheckinsOfProgramId = function(_programId) {
	if(!Ti.App.Properties.hasProperty(_programId+'Count')) { //do some caching
		Ti.App.Properties.setInt(_programId+'Count',1);
		return 1;
	} else {
		var numCheckInsSoFar = Ti.App.Properties.getInt(_programId+'Count');
		var newNumCheckins = numCheckInsSoFar + 1
		Ti.App.Properties.setString(_programId+'Count',newNumCheckins);
		Ti.API.info('getNumCheckinsOfProgramId: '+_programId+'//'+newNumCheckins);
		return newNumCheckins;
	}
}
exports.getNumCheckinsOfProgramId = getNumCheckinsOfProgramId;

////////////////////////////////////////////////////////////////////////
var checkCountCondition = function(e) {
	var checkinCount = e.result;
	//badge desc: i'm loving it
	//condition: 20th check in
	//badge id: 2
	if(checkinCount >= 20) Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(), {badgeID: 2});
	//badge desc: fall for you
	//condition: 10th check in
	//badge id: 1
	else if(checkinCount >= 10) Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(),{badgeID: 1});
	//badge desc: nice to meet you
	//condition: 1st check in
	//badge id: 0
	else if(checkinCount >= 1)
		Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(),{badgeID: 0});
}

exports.checkFriendCondition = function(_friendCheckIn) {
	//badge desc: love sharing
	//condition: checkin with more than 5 friends
	//badge id: 3
	if(_friendCheckIn >= 3) {
		Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(), {badgeID: 3});
		return true;
	} else {
		return false;
	}
}

var checkTypeCondition = function(_type) {
	var checkinCount = getNumCheckinsOfType(_type);
	Ti.API.info('checkinCount// '+_type+' = '+checkinCount);
	var badgeEarn = false;
	if(checkinCount==5) {
		switch (_type){
			//badge desc: sports fan
			//condition: 4 checkins in sport
			//badge id: 4
			case 'sport': {
				Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(), {badgeID: 4});
				badgeEarn = true;
				break;
			};
			//badge desc: drama queen
			//condition: 4 checkins in drama
			//badge id: 5
			case 'drama': {
				Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(), {badgeID: 5});
				badgeEarn = true;
				break;
			};
			//badge desc: game show addict
			//condition: 4 checkins in gameshow
			//badge id: 6
			case 'gameshow': {
				Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(), {badgeID: 6});
				badgeEarn = true;
				break;
			};
		}
	}
	return badgeEarn;
}

var checkTimeCondition = function() {
	var badgeEarn = false;
	var now = moment().format('HH');
	//badge desc: early bird
	//condition: checkin 5.00-7.59 am
	//badge id: 7
	if(now === '05' || now === '06' || now === '07') {
		Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(),{badgeID: 7});
		badgeEarn = true;
	}
	//badge desc: insomnia
	//condition: checkin 1.00 - 3.59 am
	//badge id: 8
	if(now === '01' || now === '02' || now === '03') {
		Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(),{badgeID: 8});
		badgeEarn = true;
	}
	return badgeEarn;
}

var determineShowBadgeId = function(_programId,_numCheckins) {
	Ti.API.info('_programId: '+_programId+'/_numCheckin: '+_numCheckins);
	if(_programId === "CH3_ATTEN") {
		//badge desc: At-Ten Fan LV3; condition: 10 checkins in At-Ten; badge id: 11
		if(_numCheckins >= 10) return 11;

		//badge desc: At-Ten Fan LV2; condition: 4 checkins in At-Ten; badge id: 10
		if(_numCheckins >= 4) return 10;

		//badge desc: At-Ten Fan LV1; condition: 1 checkins in At-Ten; badge id: 9
		if(_numCheckins >= 1) return 9;
	} else if(_programId === "CH3_TNSHO") {
		//badge desc: At-Ten Fan LV3; condition: 10 checkins in At-Ten; badge id: 14
		if(_numCheckins >= 10) return 14;

		//badge desc: At-Ten Fan LV2; condition: 4 checkins in At-Ten; badge id: 13
		if(_numCheckins >= 4) return 13;

		//badge desc: At-Ten Fan LV1; condition: 1 checkins in At-Ten; badge id: 12
		if(_numCheckins >= 1) return 12;
	} else if(_programId === "CH3_WMTWM") {
		//badge desc: Woman to Woman Fan LV3; condition: 10 checkins in Woman to Woman; badge id: 17
		if(_numCheckins >= 10) return 17;

		//badge desc: Woman to Woman Fan LV2; condition: 4 checkins in Woman to Woman; badge id: 16
		if(_numCheckins >= 4) return 16;

		//badge desc: Woman to Woman Fan LV1; condition: 1 checkins in Woman to Woman; badge id: 15
		if(_numCheckins >= 1) return 15;
	} else if(_programId === "CH3_MNEWS") {
		//badge desc: Morning News Fan LV3; condition: 10 checkins in Morning News; badge id: 20
		if(_numCheckins >= 10) return 20;

		//badge desc: Morning News Fan LV2; condition: 4 checkins in Morning News; badge id: 19
		if(_numCheckins >= 4) return 19;

		//badge desc: Morning News Fan LV1; condition: 1 checkins in Morning News; badge id: 18
		if(_numCheckins >= 1) return 18;
	} else if(_programId === "CH3_STSNE") {
		//badge desc: Sat-Sun News Fan LV3; condition: 10 checkins in Sat-Sun News; badge id: 23
		if(_numCheckins >= 10) return 23;

		//badge desc: Sat-Sun News Fan LV2; condition: 4 checkins in Sat-Sun News; badge id: 22
		if(_numCheckins >= 4) return 22;

		//badge desc: Sat-Sun News Fan LV1; condition: 1 checkins in Sat-Sun News; badge id: 21
		if(_numCheckins >= 1) return 21;
	} else if(_programId === "CH5_JOJAI") {
		//badge desc: Jor Jai Fan LV3; condition: 10 checkins in Jor Jai; badge id: 26
		if(_numCheckins >= 10) return 26;

		//badge desc: Jor Jai Fan LV2; condition: 4 checkins in Jor Jai; badge id: 25
		if(_numCheckins >= 4) return 25;

		//badge desc: Jor Jai Fan LV1; condition: 1 checkins in Jor Jai; badge id: 24
		if(_numCheckins >= 1) return 24;
	} else if(_programId === "CH5_SABUD") {
		//badge desc: Sabud Show Fan LV3; condition: 10 checkins in Sabud Show; badge id: 29
		if(_numCheckins >= 10) return 29;
		//badge desc: Sabud Show Fan LV2; condition: 4 checkins in Sabud Show; badge id: 28
		if(_numCheckins >= 4) return 28;
		//badge desc: Sabud Show Fan LV1; condition: 1 checkins in Sabud Show; badge id: 27
		if(_numCheckins >= 1) return 27;

	} else if(_programId === "CH9_WDYKU") {
		//badge desc: Woody Talk Show Fan LV3; condition: 10 checkins in Woody Talk Show; badge id: 32
		if(_numCheckins >= 10) return 32;

		//badge desc: Woody Talk Show Fan LV2; condition: 4 checkins in Woody Talk Show; badge id: 31
		if(_numCheckins >= 4) return 31;

		//badge desc: Woody Talk Show Fan LV1; condition: 1 checkins in Woody Talk Show; badge id: 30
		if(_numCheckins >= 1) return 30;
	} else if(_programId === "CH9_WDYMN") {
		//badge desc: Morning Woody Fan LV3; condition: 10 checkins in  Morning Woody; badge id: 35
		if(_numCheckins >= 10) return 35;

		//badge desc: Morning Woody Fan LV2; condition: 4 checkins in  Morning Woody; badge id: 34
		if(_numCheckins >= 4) return 34;

		//badge desc: Morning Woody Fan LV1; condition: 1 checkins in  Morning Woody; badge id: 33
		if(_numCheckins >= 1) return 33;
	} else if(_programId === "CH7_IRCHF") {
		//badge desc: Iron Chef Thailand Fan LV3; condition: 10 checkins in  Iron Chef Thailand; badge id: 38
		if(_numCheckins >= 10) return 38;

		//badge desc: Iron Chef Thailand Fan LV2; condition: 4 checkins in  Iron Chef Thailand; badge id: 37
		if(_numCheckins >= 4) return 37;

		//badge desc: Iron Chef Thailand Fan LV1; condition: 1 checkins in  Iron Chef Thailand; badge id: 36
		if(_numCheckins >= 1) return 36;
	}
	return undefined;
}

var checkProgramCondition = function(_programId) {
	var BadgeShowPermissionACS = require('acs/badgeShowPermissionACS');
	var checkinCount = getNumCheckinsOfProgramId(_programId);
	Ti.API.info('checkinCount/'+_programId+' = '+checkinCount);
	if(BadgeShowPermissionACS.getBadgeOfShowPermission(_programId)) {
		var badgeId = determineShowBadgeId(_programId,checkinCount);
	}
	if(badgeId !== undefined) {
		Ti.App.fireEvent('badgeConditionUpdate'+acs.getUserId(), {badgeID: badgeId});
		return true;
	} else return false;
}

Ti.App.addEventListener('UserTotalCheckInsFromACS'+acs.getUserId(), checkCountCondition);

/////////////////////////////////////////////////////////////////////

exports.checkinEvent = function(_checkinData){

	var r1 = checkTimeCondition();
	var r2 = checkTypeCondition(_checkinData.program_type);
	var r3 = checkProgramCondition(_checkinData.program_id);
	return (r1 || r2 || r3);
}

exports.badgeCondition_createBadgeUnlocked = function(_badgeID,_userID){
	var myBadgeACS = require('acs/myBadgeACS');
	var my_id = acs.getUserId();
	if(my_id===_userID) myBadgeACS.myBadgeACS_createNewBadge(my_id,_badgeID);
};


text:
package com.buffalokiwi.aerodrome.jet.reports;

import com.buffalokiwi.aerodrome.jet.IJetDate;
import com.buffalokiwi.aerodrome.jet.JetDate;
import com.buffalokiwi.aerodrome.jet.Utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.json.JsonArray;
import javax.json.JsonObject;

/**
 * A record that represents sales data for a single sku.
 *
 * Analyze how your individual product price (item and shipping price) compares
 * to the lowest individual product prices from the marketplace. These prices
 * are only provided for SKUs that have the status "Available for Sale". If a
 * best price does not change, then the last_update time also will not change.
 * If your inventory is zero, then these prices will not continue to be updated
 * and will be stale. Note: It may take up to 24 hours to reflect any price
 * updates from you and the marketplace.
 *
 * Product pricing is one factor that Jet uses to determine which retailer wins
 * a basket order. Jet determines what orders retailers will win based on the
 * the product prices of all products in the order, base commission on those
 * items as well as commission adjustments set via the Rules Engine. Commission
 * adjustments set via the Rules Engine can be very effective in optimizing
 * your win rate and profitability at the order level without having to have
 * the absolute lowest item and shipping prices.
 *
 *
 * @author John Quinn
 */
public class SkuSalesDataRec
{
  public static class Builder
  {
    /**
     * The product sku for this data
     */
    private String sku = "";

    /**
     * Jet sales rank of a SKU based off its exponential moving average sales by
     * all retailers on the marketplace, updated daily.
     */
    private int level0 = 0;

    /**
     * The last time Jet sales rank was updated
     */
    private IJetDate salesRankUpdate = null;

    /**
     * Units of this SKU sold on Jet by all retailers over the last 30 days,
     * updated daily. If there are no units sold, this field will not be presented.
     */
    private int last30 = 0;

    /**
     * The last time units sold was updated
     */
    private IJetDate unitsSoldUpdate = null;

    /**
     * Best offer overall
     */
    private final List<OfferRec> bestOffers = new ArrayList<>();

    /**
     * Best marketplace offer
     */
    private final List<OfferRec> marketplaceOffers = new ArrayList<>();

    /**
     * Create a new builder
     * @param sku The merchant sku
     */
    public Builder( final String sku )
    {
      Utils.checkNull( sku, "sku" );
      this.sku = sku;
    }

    /**
     * Jet sales rank of a SKU based off its exponential moving average sales
     * by all retailers on the marketplace, updated daily.
     * @param rank
     * @return this
     */
    public Builder setSalesRank( final int rank )
    {
      if ( rank < 0 )
        throw new IllegalArgumentException( "rank cannot be less than zero" );

      this.level0 = rank;
      return this;
    }

    /**
     * Set the last update for sales rank
     * @param date
     * @return this
     */
    public Builder setLastSalesRankUpdate( final IJetDate date )
    {
      this.salesRankUpdate = date;
      return this;
    }

    /**
     * Set the number of units sold in the last 30 days
     * @param units
     * @return this
     */
    public Builder setUnitsSoldLast30( final int units )
    {
      if ( units < 0 )
        throw new IllegalArgumentException( "units cannot be less than zero" );

      this.last30 = units;
      return this;
    }

    /**
     * Set the last update for units sold
     * @param date
     * @return this
     */
    public Builder setUnitsSoldLastUpdate( final IJetDate date )
    {
      this.unitsSoldUpdate = date;
      return this;
    }

    /**
     * Add a list of best offers
     * @param offers Offers to add.  Set to null to clear the internal list.
     * @return this
     */
    public Builder addBestOffers( final List<OfferRec> offers )
    {
      if ( offers == null )
        this.bestOffers.clear();
      else
        this.bestOffers.addAll( offers );

      return this;
    }

    /**
     * Clear the best offers list
     * @return this
     */
    public Builder clearBestOffers()
    {
      bestOffers.clear();
      return this;
    }

    /**
     * Add a single best offer
     * @param offer offer
     * @return this
     */
    public Builder addBestOffer( final OfferRec offer )
    {
      Utils.checkNull( offer, "offer" );
      this.bestOffers.add( offer );
      return this;
    }

    /**
     * Add a list of marketplace offers.
     * @param offers offer list.  Set to null to clear the internal list.
     * @return this
     */
    public Builder addMarketplaceOffers( final List<OfferRec> offers )
    {
      if ( offers == null )
        this.marketplaceOffers.clear();
      else
        this.marketplaceOffers.addAll( offers );

      return this;
    }

    /**
     * Clear the marketplace offers
     * @return this
     */
    public Builder clearMarketplaceOffers()
    {
      this.marketplaceOffers.clear();
      return this;
    }

    /**
     * Adds a single marketplace offer
     * @param offer Offer to add
     * @return this
     */
    public Builder addMarketplaceOffer( final OfferRec offer )
    {
      Utils.checkNull( offer, "offer" );
      marketplaceOffers.add( offer );
      return this;
    }

    /**
     * Build the sales data record
     * @return new record
     */
    public SkuSalesDataRec build()
    {
      return new SkuSalesDataRec( this );
    }
  }

  /**
   * The product sku for this data
   */
  private final String sku;

  /**
   * Jet sales rank of a SKU based off its exponential moving average sales by
   * all retailers on the marketplace, updated daily.
   */
  private final int level0;

  /**
   * The last time Jet sales rank was updated
   */
  private final IJetDate salesRankUpdate;

  /**
   * Units of this SKU sold on Jet by all retailers over the last 30 days,
   * updated daily. If there are no units sold, this field will not be presented.
   */
  private final int last30;

  /**
   * The last time units sold was updated
   */
  private final IJetDate unitsSoldUpdate;

  /**
   * Best offer overall
   */
  private final List<OfferRec> bestOffers;

  /**
   * Best marketplace offer
   */
  private final List<OfferRec> marketplaceOffers;

  protected SkuSalesDataRec( final Builder b )
  {
    if ( b.sku.trim().isEmpty())
      throw new IllegalArgumentException( "sku cannot be empty" );

    this.sku = b.sku;
    this.level0 = b.level0;
    this.salesRankUpdate = b.salesRankUpdate;
    this.last30 = b.last30;
    this.unitsSoldUpdate = b.unitsSoldUpdate;
    this.bestOffers = Collections.unmodifiableList( b.bestOffers );
    this.marketplaceOffers = Collections.unmodifiableList( b.marketplaceOffers );
  }

  /**
   * Turn jet json into an instance of this object
   * @param sku sku
   * @param json json
   * @return object
   */
  public static SkuSalesDataRec fromJSON( final String sku,
    final JsonObject json )
  {
    Utils.checkNull( json, "json" );

    final Builder b = new Builder( sku );

    final JsonObject sr = json.getJsonObject( "sales_rank" );
    if ( sr != null )
    {
      b.setSalesRank( sr.getInt( "level0", 0 ))
       .setLastSalesRankUpdate( JetDate.fromJetValueOrNull( sr.getString( "last_update", "" )));
    }

    final JsonObject us = json.getJsonObject( "units_sold" );

    if ( us != null )
    {
      b.setUnitsSoldLast30( json.getInt( "last_30_days", 0 ))
       .setUnitsSoldLastUpdate( JetDate.fromJetValueOrNull( json.getString( "last_update", "" )));
    }

    final List<OfferRec> boList = new ArrayList<>();

    final JsonArray bo = json.getJsonArray( "my_best_offer" );
    if ( bo != null )
    {
      for ( int i = 0; i < bo.size(); i++ )
      {
        boList.add( OfferRec.fromJSON( bo.getJsonObject( i )));
      }
    }

    Collections.reverse( boList );
    b.addBestOffers( boList );

    final List<OfferRec> moList = new ArrayList<>();

    final JsonArray mo = json.getJsonArray( "best_marketplace_offer" );
    if ( mo != null )
    {
      for ( int i = 0; i < mo.size(); i++ )
      {
        moList.add( OfferRec.fromJSON( mo.getJsonObject( i )));
      }
    }

    Collections.reverse( moList );
    b.addMarketplaceOffers( moList );

    return b.build();
  }

  /**
   * Get the product sku this object represents.
   * @return sku
   */
  public String getSku()
  {
    return sku;
  }

  /**
   * Get the sales rank data
   * @return data
   */
  public int getSalesRank()
  {
    return level0;
  }

  /**
   * Get the units sold data
   * @return data
   */
  public int getUnitsSold()
  {
    return last30;
  }

  public IJetDate getLastSalesRankUpdate()
  {
    return salesRankUpdate;
  }

  public IJetDate getLastUnitsSoldUpdate()
  {
    return unitsSoldUpdate;
  }

  public OfferRec getBestOffer()
  {
    for ( final OfferRec rec : bestOffers )
    {
      return rec;
    }

    return null;
  }

  public OfferRec getBestMarketplaceOffer()
  {
    for ( final OfferRec rec : marketplaceOffers )
    {
      return rec;
    }

    return null;
  }

  /**
   * Get the best offers data
   * @return data
   */
  public List<OfferRec> getBestOffers()
  {
    return bestOffers;
  }

  /**
   * Get the best marketplace offers data
   * @return data
   */
  public List<OfferRec> getBestMarketplaceOffers()
  {
    return marketplaceOffers;
  }
}


text:
date: 2013-04-01
slug: put-set-e-in-bash-scripts-to-exit-on-error
tags: shell
title: Put set -e in bash scripts to exit on error
---

Put `set -e` in bash scripts to exit on error.

```sh
#!/bin/bash
cd directory
echo "Deleting everything in the current directory"
```

```
$ ./script.sh
./script.sh: line 3: cd: stuff: No such file or directory
Deleting everything in the current directory
$
```

Oh no!

You can use `set -e` near the top of your script, or simply append `-e` to the shebang:

```sh
#!/bin/bash -e
cd directory
echo "Deleting everything in the current directory"
```

```
$ ./script.sh
./script.sh: line 5: cd: stuff: No such file or directory
```

Much better.

Learned from the [first episode of Destroy All Software](https://www.destroyallsoftware.com/screencasts/catalog/statistics-over-git-repositories) by @garybernhardt.


text:
package com.heaven7.java.data.mediator.compiler.fillers;

import com.heaven7.java.data.mediator.compiler.DataMediatorConstants;
import com.heaven7.java.data.mediator.compiler.FieldData;
import com.heaven7.java.data.mediator.compiler.util.Util;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;

import javax.lang.model.element.ExecutableElement;
import java.util.List;

/**
 * Created by heaven7 on 2017/9/1 0001.
 */
public class TypeSnapableFiller extends TypeResetableFiller {

    @Override
    public String getInterfaceName() {
        return DataMediatorConstants.NAME_SNAP;
    }

    @Override
    public int getInterfaceFlag() {
        return FieldData.FLAG_SNAP;
    }

    @Override
    public void buildMethodStatement(String curPkg, String parentInterfaceName,
                                     String curClassName, ExecutableElement ee,
                                     MethodSpec.Builder builder, List<FieldData> list, boolean hasSuperClass, int superFlagsForParent) {
        note("start buildMethodStatement --------------", list);
        if(hasSuperClass && (superFlagsForParent & getInterfaceFlag()) != 0){
            builder.addStatement("super.clearSnap()");
        }
        if(list != null && !list.isEmpty()) {
            for (FieldData fd : list) {
                Util.addInitStatement(fd , builder);
            }
        }
        note("end buildMethodStatement --------------");
    }

    @Override
    public void buildProxyMethod(MethodSpec.Builder builder, ExecutableElement ee, ClassName cn_interface) {
        builder.addStatement("_getTarget().clearSnap()");
    }

}


text:
using MDDatasets
using SignalProcessing
using EasyPlot

#==Constants
===============================================================================#
vvst = paxes(ylabel="Amplitude (V)", xlabel="Time (s)")
Tpsvst = paxes(ylabel="Period (ps)", xlabel="Time (s)")
fvst = paxes(ylabel="Frequency (Hz)", xlabel="Time (s)")
solidline = line(style=:solid)

#==Input data
===============================================================================#
fnom = 1e9
osr = 50 #(fundamental) oversampling ratio
ncycles = 20
fshift=0.1 #ratio
fmod = fnom/ncycles #Frequency of modulation
xrise = CrossType(:rise)

#==Computations
===============================================================================#
T = 1/fnom
t = DataF1(0:(T/osr):(ncycles*T))
finst = fnom*(1+fshift*cos(2pi*fmod*t)) #instantaneous frequency
y = cos(2pi*finst*t)

#==Generate plot
===============================================================================#
plot=EasyPlot.new(title="Period & Frequency Measurements")
s = add(plot, vvst, title="Signal")
	add(s, y, id="y(t)")
s = add(plot, Tpsvst, title="Instantaneous Period")
	add(s, measperiod(y, xing=xrise, shiftx=true), solidline, glyph(shape=:+), id="shift")
	add(s, measperiod(y, xing=xrise, shiftx=false), solidline, glyph(shape=:x), id="no shift")
s = add(plot, fvst, title="Instantaneous Frequency")
	add(s, measfreq(y, xing=xrise, shiftx=true), solidline, glyph(shape=:+), id="shift")
	add(s, measfreq(y, xing=xrise, shiftx=false), solidline, glyph(shape=:x), id="no shift")

#==Return plot to user (call evalfile(...))
===============================================================================#
plot.ncolumns = 1
plot


text:
<tomcat-users>
<user name="user1" password="user1" roles="standard-user" />
<user name="user2" password="user2" roles="standard-user" />
<user name="user3" password="user3" roles="standard-user" />
<user name="user4" password="user4" roles="standard-user" />
<user name="user5" password="user5" roles="standard-user" />
<user name="user6" password="user6" roles="standard-user" />
<user name="user7" password="user7" roles="standard-user" />
<user name="user8" password="user8" roles="standard-user" />
<user name="user9" password="user9" roles="standard-user" />
<user name="user10" password="user10" roles="standard-user" />
<user name="user11" password="user11" roles="standard-user" />
<user name="user12" password="user12" roles="standard-user" />
<user name="user13" password="user13" roles="standard-user" />
<user name="user14" password="user14" roles="standard-user" />
<user name="user15" password="user15" roles="standard-user" />
<user name="user16" password="user16" roles="standard-user" />
<user name="user17" password="user17" roles="standard-user" />
<user name="user18" password="user18" roles="standard-user" />
<user name="user19" password="user19" roles="standard-user" />
<user name="user20" password="user20" roles="standard-user" />
</tomcat-users>


text:
package ru.stqa.pft.mantis.tests;

import biz.futureware.mantis.rpc.soap.client.IssueData;
import biz.futureware.mantis.rpc.soap.client.MantisConnectLocator;
import biz.futureware.mantis.rpc.soap.client.MantisConnectPortType;
import org.openqa.selenium.remote.BrowserType;
import org.testng.SkipException;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import ru.stqa.pft.mantis.appmanager.ApplicationManager;

import javax.xml.rpc.ServiceException;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Objects;

/**
 * Created by Sasha on 21.04.2016.
 */
public class TestBase {

  public static final ApplicationManager app = new ApplicationManager(System.getProperty("browser", BrowserType.CHROME));

  @BeforeSuite
  public void setUp() throws Exception {
    app.init();
    app.ftp().upload(new File("src/test/resources/config_inc.php"), "config_inc.php", "config_inc.php.bak");
  }

  @AfterSuite(alwaysRun = true)
  public void tearDown() throws IOException {
    app.ftp().restore("config_inc.php.bak", "config_inc.php");
    app.stop();
  }

  public boolean isIssueOpen(int issueId) throws MalformedURLException, ServiceException, RemoteException {
    MantisConnectPortType mc = new MantisConnectLocator().getMantisConnectPort(new URL(app.getProperty("web.soapUrl")));
    IssueData issueData = mc.mc_issue_get(app.getProperty("web.adminLogin"), app.getProperty("web.adminPassword"), BigInteger.valueOf(issueId));
    return !Objects.equals(issueData.getStatus().getName(), "closed");
  }

  public void skipIfNotFixed(int issueId) throws RemoteException, ServiceException, MalformedURLException {
    if (isIssueOpen(issueId)) {
      throw new SkipException("Ignored because of issue " + issueId);
    }
  }
}


text:
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const path = require('path');
const cors = require('cors');
require('dotenv').config()

// Set up the express app
const app = express();

// Parse incoming requests data (https://github.com/expressjs/body-parser)
app.use(bodyParser.urlencoded({ extended: false })); //the internet says this should be true
app.use(bodyParser.json());
app.use(cookieParser());
app.use(cookieSession({
  secret: "squirrel"
}))

// Log requests to the console.
app.use(logger('dev'));

app.use(cors());

//app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, OPTIONS')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
  next();
})

const bookshelf = app.get('./db/knex')
app.set('bookshelf', bookshelf);

const missions = require('./routes/missions');
const casefiles = require('./routes/casefiles');
const articles = require('./routes/articles');
const reviews = require('./routes/reviews');
const users = require('./routes/users');
const groups = require('./routes/groups');
const responses = require('./routes/responses');

// TODO
// app.use('/games', gamesRouter);
// something like that. so in your games router file the route get('/' ...) will actually be at /games/

app.use(missions);
app.use(casefiles);
app.use(articles);
app.use(reviews);
app.use(users);
app.use(groups);
app.use(responses);

const PORT = process.env.PORT || 5000;

// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));

// Answer API requests.
app.get('/api', function (req, res) {
  res.set('Content-Type', 'application/json');
  res.send('{"message":"Hello from the custom server, Haii!"}');
});

// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
  response.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
});

app.listen(PORT, function () {
  console.log(`Listening on port ${PORT}`);
});

module.exports = app;


text:
See [generating-clientset.md](../../../../docs/devel/generating-clientset.md)

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/cmd/libs/go2idl/client-gen/README.md?pixel)]()


text:
package org.locationtech.geogig.di;

import java.util.Map;
import java.util.concurrent.TimeoutException;

import org.locationtech.geogig.repository.RepositoryConnectionException;
import org.locationtech.geogig.storage.RefDatabase;
import org.locationtech.geogig.storage.memory.HeapRefDatabase;

import com.google.common.base.Preconditions;

class RefDatabaseSnapshot implements RefDatabase {

    private final RefDatabase actual;

    private HeapRefDatabase snapshot;

    public RefDatabaseSnapshot(RefDatabase actual) {
        Preconditions.checkArgument(!(actual instanceof RefDatabaseSnapshot));
        this.actual = actual;
        this.snapshot = new HeapRefDatabase();
    }

    @Override
    public void lock() throws TimeoutException {
        actual.lock();
    }

    @Override
    public void configure() throws RepositoryConnectionException {
        actual.configure();
    }

    @Override
    public boolean checkConfig() throws RepositoryConnectionException {
        return actual.checkConfig();
    }

    @Override
    public void unlock() {
        actual.unlock();
    }

    @Override
    public void create() {
        actual.create();
        snapshot.create();
        snapshot.putAll(actual.getAll());
    }

    @Override
    public void close() {
        actual.close();
        snapshot.close();
    }

    @Override
    public String getRef(String name) {
        String val = snapshot.getRef(name);
        return val;
    }

    @Override
    public String getSymRef(String name) {
        String val = snapshot.getSymRef(name);
        return val;
    }

    @Override
    public void putRef(String refName, String refValue) {
        actual.putRef(refName, refValue);
        snapshot.putRef(refName, refValue);
    }

    @Override
    public void putSymRef(String name, String val) {
        actual.putSymRef(name, val);
        snapshot.putSymRef(name, val);
    }

    @Override
    public String remove(String refName) {
        String ret = actual.remove(refName);
        snapshot.remove(refName);
        return ret;
    }

    @Override
    public Map<String, String> getAll() {
        return snapshot.getAll();
    }

    @Override
    public Map<String, String> getAll(String prefix) {
        return snapshot.getAll(prefix);
    }

    @Override
    public Map<String, String> removeAll(String namespace) {
        Map<String, String> ret = actual.removeAll(namespace);
        snapshot.removeAll(namespace);
        return ret;
    }

}


text:
module LintTrappings::Spec::IndentationHelpers
  # Strips off excess leading indentation from each line so we can use Heredocs
  # for writing code without having the leading indentation count.
  def normalize_indent(code)
    LintTrappings::Utils.normalize_indent(code)
  end
end