text:
/*
 * filename   :    cornix_utils.h
 * author     :    Kathryn Dahlgren
 * date       :    27 Feb 2016
 */

#ifndef CORNIX_UTILS_H
#define CORNIX_UTILS_H

#include "cornix_includes.h"
#include "cornix_parser.h"
#include "cornix_time.h"
#include "cornix_agg.h"
#include "cornix_ops.h"
#include "cornix_booleans.h"

// getData_noAgg
void getData_noAgg(rocksdb::DB* db, rocksdb::Status status, std::vector<std::string> keyList, std::vector<std::string> idList)
{
  std::map<std::string, std::string> resultsMap ;

  // Iterate over keys
  for(unsigned int i = 0 ; i < keyList.size() ; i++)
  {
    // Get field from keyList
    std::string key = keyList[i] ;
    // Get value at key
    std::string value = read_data(db, status, key) ;
    // Get tuple List from value
    std::vector<std::string> tupleList = parseList(value) ;

    // Get valid values
    for(unsigned int j = 0 ; j < tupleList.size() ; j++)
    {
      // Get current tuple
      std::string currtup = tupleList[j] ;

      // Get tuple id
      std::string tupleID = getID( tupleList[j] ) ;
      // Get tuple value
      std::string tupleVal = getValue( tupleList[j] ) ;
      // Check if tuple id in idlist
      bool check = std::find(idList.begin(), idList.end(), tupleID) != idList.end() ;
      if( check == true )
      {
        // Check if the map already contains an entry for tupleID
        if( resultsMap.find(tupleID) != resultsMap.end())
        {
          // Get curr value of tupleID from map
          std::string mapValue = resultsMap[tupleID] ;
          // Concatenate new value to old value
          // Result will be comma-separated values
          std::string newValue = mapValue + ", " + key + ": " + tupleVal ;
          // Add modified back into map
          resultsMap[tupleID] = newValue ;
        }
        else
        {
          std::string entry = "id: " + tupleID + ", " + key + ": " + tupleVal ;
          resultsMap.insert( std::make_pair(tupleID, entry) );
        }
      }
    }
  }

  // Generate timestamp
  std::string myTime = currentDateTime() ;
  // Generate file name
  std::string filename = "readData_" + myTime + ".txt" ;

  // Create new data/ dir in ../ if it does not exist
  // http://www.dreamincode.net/forums/topic/59943-accessing-directories-in-cc-part-i/
  DIR* pdir = NULL ;
  pdir = opendir( "../data/" ) ;
  if( pdir == NULL )
  {
    std::cout << "Creating data dir at ../data/" << std::endl ;
    const int err = system( "mkdir ../data/" );
    if( err == (-1) )
    {
      std::cout << "Error: Could not create data/ directory" << std::endl ;
      exit(1) ;
    }
  }
  closedir( pdir ) ;

  // Write contents of map to file in ../data/
  std::string pathName = "../data/" + filename ;
  std::ofstream dataFile ;
  dataFile.open( pathName, std::ios::app ) ;
  if( dataFile.is_open() )
  {
    // Iterate through all elements in std::map
    std::map<std::string, std::string>::iterator it = resultsMap.begin();
    while(it != resultsMap.end())
    {
      //dataFile << it->first << ": " << it->second <<std::endl ;
      dataFile << it->second <<std::endl ;
      it++ ;
    }
  }
  dataFile.close();

  return ;
}

// getData_Agg
void getData_Agg(rocksdb::DB* db, rocksdb::Status status, std::string agg, std::vector<std::string> keyList, std::vector<std::string> idList)
{
  double aggResult = 0.0 ;

  // Eval on Agg op
  if( agg == "avg")
    aggResult = avg(db, status, keyList, idList) ;
  else if( agg == "min")
    aggResult = min(db, status, keyList, idList) ;
  else if( agg == "max")
    aggResult = max(db, status, keyList, idList) ;
  else if( agg == "sum")
    aggResult = sum(db, status, keyList, idList) ;
  else if( agg == "count")
    aggResult = count(db, status, keyList, idList) ;

  // Generate timestamp
  std::string myTime = currentDateTime() ;
  // Generate file name
  std::string filename = "readData_" + myTime + ".txt" ;

  // Create new data/ dir in ../ if it does not exist
  // http://www.dreamincode.net/forums/topic/59943-accessing-directories-in-cc-part-i/
  DIR* pdir = NULL ;
  pdir = opendir( "../data/" ) ;
  if( pdir == NULL )
  {
    std::cout << "Creating data dir at ../data/" << std::endl ;
    const int err = system( "mkdir ../data/" );
    if( err == (-1) )
    {
      std::cout << "Error: Could not create data/ directory" << std::endl ;
      exit(1) ;
    }
  }
  closedir( pdir ) ;

  std::cout << "aggResult = " << aggResult << std::endl ;

  // Write contents of map to file in ../data/
  std::string pathName = "../data/" + filename ;
  std::ofstream dataFile ;
  dataFile.open( pathName, std::ios::app ) ;
  if( dataFile.is_open() )
  {
    dataFile << aggResult <<std::endl ;
  }
  dataFile.close();

  return ;
}

// getData
void getData(rocksdb::DB* db, rocksdb::Status status, std::string agg, std::vector<std::string> keyList, std::vector<std::string> idList)
{
  if( agg != "" )
    getData_Agg( db, status, agg, keyList, idList ) ;
  else
    getData_noAgg( db, status, keyList, idList ) ;

  return ;
}

// getKeyList
std::vector<std::string> getKeyList(std::string query)
{
  std::vector<std::string> parsedQuery = parseRead(query) ;
  std::vector<std::string> keyList = getFieldList(parsedQuery[0]) ;
  return keyList ;
}

// getIDList
std::vector<std::string> getIDList(rocksdb::DB* db, rocksdb::Status status, std::string query)
{
  std::vector<std::string> idList ;
  std::vector<std::string> parsedQuery = parseRead(query) ;
  std::vector<std::string> predList ;

  // Get list of predicates
  for(unsigned int i = 1 ; i < parsedQuery.size() ; i++)
    predList.push_back( parsedQuery[i] ) ;

  if( predList.size() != 0)
  {
    // DEBUG
    for(unsigned int i = 0 ; i < predList.size() ; i++)
    {
      std::cout << "*** predList[i] = " << predList[i] << std::endl ;
    }

    // Iterate over predicates
    for(unsigned int i = 0 ; i < predList.size() ; i++)
    {
      std::string currPred = predList[i] ;
      std::string lhs = getLHS( currPred ) ;
      std::string op = getOp( currPred ) ;
      std::string rhs = getRHS( currPred ) ;

      std::vector<std::string> list ;

      // Eval on op
      if( op == "eq")
        list = eq(db, status, lhs, rhs) ;
      else if( op == "ne")
        list = ne(db, status, lhs, rhs) ;
      else if( op == "gt")
        list = gt(db, status, lhs, rhs) ;
      else if( op == "gte")
        list = gte(db, status, lhs, rhs) ;
      else if( op == "lt")
        list = lt(db, status, lhs, rhs) ;
      else if( op == "lte")
        list = lte(db, status, lhs, rhs) ;

      for(unsigned int k = 0 ; k < list.size() ; k++)
        std::cout << "list[k] = " << list[k] << std::endl ;

      // Append new list of valid ids to idList
      idList.insert( idList.end(), list.begin(), list.end() ) ;

      for(unsigned int k = 0 ; k < idList.size() ; k++)
        std::cout << "idList[k] = " << idList[k] << std::endl ;
    }

    // AND
    //int numPreds = predList.size() ;
    //idList = AND( idList, numPreds ) ;

    // OR
    idList = OR( idList ) ;

  }
  else // no predicates
  {
    // Get all ids in all key fields
    // for each key:
    //   Get value
    //   Convert value into vector of tuplesi
    //   for each tuple:
    //     Get id
    //     Place id in idSet

    std::set<std::string> idSet ;
    std::vector<std::string> keyList = getKeyList( query ) ;

    for(unsigned int i = 0 ; i < keyList.size() ; i++)
    {
      std::string currKey = keyList[i] ;
      // Get value at key
      std::string value = read_data(db, status, currKey) ;
      // Get tuple List from value
      std::vector<std::string> tupleList = parseList(value) ;
      for(unsigned int i = 0 ; i < tupleList.size() ; i++)
      {
        std::string tupleID = getID( tupleList[i] ) ;
        idSet.insert( tupleID ) ;
      }
    }

    std::vector<std::string> listVector( idSet.begin(), idSet.end() );
    idList = listVector ;
  }

  // DEBUG PRINT
  std::cout << "Valid ids for: " << query << std::endl ;
  for(unsigned int i = 0 ; i < idList.size() ; i++)
  {
    std::cout << "i =" << i << ": " << idList[i] << std::endl ;
  }
  std::cout << "     ... exitting getIDList" << std::endl ;

  return idList ;
}

// http://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c
std::string random_string( size_t length )
{
    auto randchar = []() -> char
    {
        const char charset[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
        const size_t max_index = (sizeof(charset) - 1);
        return charset[ rand() % max_index ];
    };
    std::string str(length,0);
    std::generate_n( str.begin(), length, randchar );
    return str;
}

// getAllKeys
// input db and status
// output vector of keys - all keys in entire db
std::vector<std::string> getAllKeys ( rocksdb::DB* db, rocksdb::Status status )
{
  std::vector<std::string> allKeys ;

  // https://github.com/facebook/rocksdb/wiki/Basic-Operations
  rocksdb::Iterator* it = db->NewIterator(rocksdb::ReadOptions()) ;
  for( it->SeekToFirst() ; it->Valid() ; it->Next() )
    allKeys.push_back( it->key().ToString() ) ;
  delete it;

  return allKeys ;
}

// inIDList
// input id, idList
// output bool
bool inIDList ( std::string id, std::vector<std::string> idList )
{
  bool flag = false ;

  if( std::find( idList.begin(), idList.end(), id ) != idList.end() )
    flag = true ;

  return flag ;
}

// getMap
// input map + concept in ontology map
// output vector of concepts subsumed by input concept
std::vector<std::string> getMap ( std::string concept, std::map< std::string, std::vector<std::string> > ontoMap )
{
  std::vector<std::string> mapForConcept = ontoMap[ concept ] ;
  return mapForConcept ;
}

// inMap
// input ontology concept, map value for a concept
// output bool
bool inMap ( std::string concept, std::vector<std::string> mapValue )
{
  bool flag = false ;

  if( std::find( mapValue.begin(), mapValue.end(), concept ) != mapValue.end() )
    flag = true ;

  return flag ;
}

#endif


text:
// SASL AUTH methods

// var mime = require("./mime")
import mime from './mime'
var crypto = require("crypto");

/**
 * sasl.AUTHMethods -> Array
 *
 * Array of objects containing information about the authentication functions
 * Struncture: {name: NAME_OF_THE_METHOD, fn: authentication_function(authObject)}
 *
 * authObject has the following structure:
 *   - wait (Boolean): initially false. If set to TRUE, then the next response from
 *                     the client will be forwarded directly back to the function
 *   - user (String): initially false. Set this value with the user name of the logging user
 *   - params (String): Authentication parameters from the client
 *   - history (Array): an array of previous params if .wait was set to TRUE
 *   - n3 (Object): current session object
 *   - check (Function): function to validate the user, has two params:
 *     - user (String): username of the logging user
 *     - pass (Function | String): password or function(pass){return pass==pass}
 *     returns TRUE if successful or FALSE if not
 **/
exports.AUTHMethods = [
    {
        name:"PLAIN",
        fn:  PLAIN
    },
    {
        name:"CRAM-MD5",
        fn:  CRAM_MD5
    }
]

// AUTH PLAIN

// SCENARIO 1:
// STEP 1
//   CLIENT: AUTH PLAIN
//   SERVER: +
// STEP 2
//   CLIENT: BASE64(<NULL>username<NULL>password)
//   SERVER: +OK logged in

// SCENARIO 2:
// STEP 1
//   CLIENT: AUTH PLAIN BASE64(<NULL>username<NULL>password)
//   SERVER: +OK logged in

function PLAIN(authObj){

    // Step 1
    if(!authObj.params){
        authObj.wait = true;
        return "+ ";
    }

    // Step 2
    var login = mime.decodeBase64(authObj.params),
        parts = login.split("\u0000");

    if(parts.length!=3 || !parts[1])
        return "-ERR Invalid authentication data";

    if(parts[0].length) // try to log in in behalf of some other user
        return "-ERR [AUTH] Not authorized to requested authorization identity";

    return authObj.check(parts[1], parts[2]);
}

// AUTH CRAM-MD5

// STEP 1
//   CLIENT: AUTH CRAM-MD5
//   SERVER: + BASE64(secret)
// STEP 2
//   CLIENT: BASE64(user HMAC-MD5(secret, password))
//   SERVER: +OK Logged in

function CRAM_MD5(authObj){

    // Step 1
    if(!authObj.params){
        authObj.wait = true;
        return "+ "+mime.encodeBase64("<"+authObj.n3.UID+"@"+authObj.n3.server_name+">");
    }

    // Step 2
    var params = mime.decodeBase64(authObj.params).split(" "), user, challenge,
        salt = "<"+authObj.n3.UID+"@"+authObj.n3.server_name+">";
    console.log("CRAM-MD5 Unencoded: "+params);
    user = params && params[0];
    challenge = params && params[1];
    if(!user || !challenge)
        return "-ERR Invalid authentication";

    return authObj.check(user, function(pass){
            var hmac = crypto.createHmac("md5", pass), digest;
            hmac.update(salt);
            digest = hmac.digest("hex");
            return digest==challenge;
        });
}

redpajama_set_name: RedPajamaGithub


text:
require_relative '../../../spec_helper'

describe CitrusPayments::Marketplace::Refunds::TransRefund do
  valid_auth_token='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY2Nlc3Nfa2V5IjoiMURZUUk4UzVFRTVVTTk3QUpZS0EiLCJleHBpcmVzIjoiMjAxNy0wOC0xMlQwNToyNTowNS42NTFaIiwiY2FuX3RyYW5zYWN0IjoxLCJhZG1pbiI6MH0.jhghjtqWczvGhZAU1Z8zpNPiZZc5aIY7MyafkenZ-u8'

  context 'Release Payment' do
    refund_attributes={
        trans_id: 114413,
        refund_amount: 6,
        refund_ref: 'RD-6191651979_Refund',
        pg_refund_charge: 0,
        refund_datetime: '2017-08-09 12:00:28'
    }
    it 'returns error if invalid token' do
      VCR.use_cassette('marketplace/refunds/trans_refund/failure_token') do
        response=CitrusPayments::Marketplace::Refunds::TransRefund.create('wrong_auth_token', refund_attributes)
        expect(response[:error_description]).to eq('Invalid user Token')
      end
    end

    it 'returns success if refunded' do
      VCR.use_cassette('marketplace/refunds/trans_refund/success') do
        response=CitrusPayments::Marketplace::Refunds::TransRefund.create(valid_auth_token, refund_attributes)
        expect(response[:refund_id]).not_to be_nil
      end
    end

    it "returns error if invalid fields" do
      VCR.use_cassette("marketplace/refunds/trans_refund/invalid_trans_id") do
        altered_trans_id=refund_attributes.clone
        altered_trans_id['trans_id']="..."
        response=CitrusPayments::Marketplace::Refunds::TransRefund.create(valid_auth_token, altered_trans_id)
        expect(response[:error_description]).to eq("trans_id is not of a type(s) number")
      end
    end

    it "throws input error when params missing" do
      refund_attributes_sample={
          refund_ref: 'RD-6191651979_Refund',
          pg_refund_charge: 0,
          refund_datetime: '2017-08-09 12:00:28'
      }
      expect{CitrusPayments::Marketplace::Refunds::TransRefund.create(valid_auth_token, refund_attributes_sample)}.to  raise_error(CitrusPayments::Errors::Input)
    end

  end

end


text:
<?php
namespace HtImgModule\Imagine\Loader;

use Gaufrette\Filesystem;
use Gaufrette\Exception\FileNotFound as FileNotFoundException;
use HtImgModule\Exception;
use HtImgModule\Binary\Binary;

/**
 * Image Loader for Library, Gaufrette
 * @see https://github.com/KnpLabs/Gaufrette
 */
class GaufretteLoader implements LoaderInterface
{
    /**
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * Constructor
     *
     * @param Filesystem $filesystem
     */
    public function __construct(Filesystem $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * {@inheritDoc}
     */
    public function load($path)
    {
        try {
            $contents = $this->filesystem->read($path);
        } catch (FileNotFoundException $e) {
            throw new Exception\ImageNotFoundException(sprintf('Source image not found in "%s"', $path));
        }

        try {
            $mimeType = $this->filesystem->mimeType($path);
        } catch (\LogicException $e) {
            // Mime Type could not be detected
            return $contents;
        }

        if (!$mimeType) {
            // Mime Type could not be detected
            return $contents;
        }

        return new Binary($contents, $mimeType);
    }
}


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

<title>ClassTemplate (esoco-lib 1.3.0 API)</title>
<meta name="date" content="2018-10-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

de.esoco.lib.template

Class ClassTemplate<T>

java.lang.Object

org.obrel.core.RelatedObject

de.esoco.lib.template.Template<T>

de.esoco.lib.template.ClassTemplate<T>

All Implemented Interfaces:

org.obrel.core.Relatable

public class ClassTemplate<T>
extends Template<T>

A concrete template implementation that can create instances of the described
 type from the type's class.

Constructor Summary

Constructors

Constructor and Description

ClassTemplate(java.lang.Class<? extends T> rClass,
             java.lang.String sDescription)

Creates a new instance for a certain type class.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

protected T
create()

Creates a new instance of the type class described by this template by
 invoking an empty constructor through reflection.

Methods inherited from class org.obrel.core.RelatedObject

deleteRelation, get, getRelation, getRelations, notifyRelationListeners, readRelations, relationsEqual, relationsHashCode, relationsString, set, set, toString, transform, writeRelations

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Methods inherited from interface org.obrel.core.Relatable

deleteRelation, deleteRelations, get, get, getAll, getRelationCount, getRelations, hasFlag, hasRelation, hasRelations, init, set, set, set, streamRelations

Constructor Detail

ClassTemplate

public ClassTemplate(java.lang.Class<? extends T> rClass,
                     java.lang.String sDescription)

Creates a new instance for a certain type class.

Parameters:

rClass - The class of the template's class

sDescription - The template description

Method Detail

create

protected T create()

Creates a new instance of the type class described by this template by
 invoking an empty constructor through reflection. Throws a
 RuntimeException if the constructor invocation fails.

Specified by:

create in class Template<T>

Returns:

A new instance of the template's type

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.koverse.restaurants;

import com.koverse.sdk.application.AbstractApplication;
import com.koverse.sdk.data.Parameter;
import java.util.List;

public class MyCustomApplication extends AbstractApplication {

  /**
   * A universally unique string that indentifies this application. This
   * string must be the same across all versions of the application.
   */
  @Override
  public String getApplicationId() {
    return "restaurants";
  }

  /** The application name which is shown to the users. */
  @Override
  public String getDisplayName() {
    return "Restaurant Inspection Violations";
  }

  /**
   * The name of the category in which this application is grouped in the UI.
   * The name much match the desired group name exactly.
   */
  @Override
  public String getDefaultCategoryName() {
    return "My Custom Category";
  }

  /**
   * A string that simply identifies the version of the application installed,
   * but which has no bearing on version control. The last installed version
   * of the app is the one that is used.
   */
  @Override
  public String getVersion() {
    return "0.0.1";
  }

  /** The parameters that a system administrator can use to configure the app. */
  @Override
  protected void fillInParameters(List<Parameter> parameters) {

//    parameters.add(new Parameter.Builder()
//      .parameterName("testParameter")
//      .displayName("Test Parameter").type(Parameter.TYPE_STRING)
//      .defaultValue("default value").build());

  }

  /**
   * Set this false to force the system administrator to manually deploy
   * instances of this application. Usually enabling auto-deploy is the most
   * appropriate.
   */
  @Override
  public boolean getAutoDeploy() {
    return true;
  }
}


text:
namespace BullsAndCows.Models
{
    using System.Collections.Generic;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;

    public class User : IdentityUser
    {
        private ICollection<Notification> notifications;
        private int rank;

        public User()
        {
            this.notifications = new HashSet<Notification>();
        }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager, string authenticationType)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
            // Add custom user claims here
            return userIdentity;
        }

        public int Losses { get; set; }

        public int Wins { get; set; }

        public int Rank
        {
            get
            {
                return ((this.Wins * 100) + (15 * this.Losses));
            }
        }

        public virtual ICollection<Notification> Notifications
        {
            get { return this.notifications; }
            set { this.notifications = value; }
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CursoDesignPatterns
{
  public class Finalizado : EstadoDeUmOrcamento
  {
    public void AplicaDescontoExtra(Orcamento orcamento)
    {
      throw new Exception("Orcamentos finalizados não recebem desconto extra");
    }

    public void Aprova(Orcamento orcamento) {
      throw new Exception("Orcamento já está finalizado");
    }

    public void Reprova(Orcamento orcamento) {
      throw new Exception("Orcamento já está finalizado");
    }

    public void Finaliza(Orcamento orcamento) {
      throw new Exception("Orcamento já está finalizado");
    }
  }
}


text:
class Criterion < ActiveRecord::Base
  belongs_to :rubric
end


text:
/**
 * @name responsive-config
 * @description Core responsive-config provider in ngx-responsive
 *
 * @license MIT
 */
import { Injectable, Inject, Optional } from '@angular/core';
import { IResponsiveConfig } from '../../interfaces/responsive-config.interfaces';

@Injectable()
export class ResponsiveConfig {
    public config: IResponsiveConfig;
    constructor(@Inject('config') private _config?: IResponsiveConfig) {
       this.config = this._config;
    }
}


text:
#include "BlobDictionary.h"

#include <assert.h>

namespace filamat {

size_t BlobDictionary::addBlob(const std::vector<uint32_t>& vblob) noexcept {
    std::string_view blob((char*) vblob.data(), vblob.size() * 4);
    auto iter = mBlobIndices.find(blob);
    if (iter != mBlobIndices.end()) {
        return iter->second;
    }
    mBlobs.emplace_back(std::make_unique<std::string>(blob));
    mBlobIndices.emplace(*mBlobs.back(), mBlobs.size() - 1);
    return mBlobs.size() - 1;
}

} // namespace filamat


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Stories.Migrations
{
    public partial class Flag_Stories_And_Comments : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Flags",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
                    CommentId = table.Column<int>(nullable: true),
                    CreatedDate = table.Column<DateTime>(nullable: false),
                    ModifiedDate = table.Column<DateTime>(nullable: false),
                    StoryId = table.Column<int>(nullable: true),
                    UserId = table.Column<Guid>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Flags", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Flags_Comments_CommentId",
                        column: x => x.CommentId,
                        principalTable: "Comments",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_Flags_Stories_StoryId",
                        column: x => x.StoryId,
                        principalTable: "Stories",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_Flags_Users_UserId",
                        column: x => x.UserId,
                        principalTable: "Users",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Flags_CommentId",
                table: "Flags",
                column: "CommentId");

            migrationBuilder.CreateIndex(
                name: "IX_Flags_StoryId",
                table: "Flags",
                column: "StoryId");

            migrationBuilder.CreateIndex(
                name: "IX_Flags_UserId",
                table: "Flags",
                column: "UserId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Flags");
        }
    }
}


text:
<?xml version="1.0"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<mbeans-descriptors>

  <mbean name="RewriteValve"
         description="A URL rewrite valve"
         domain="Catalina"
         group="Valve"
         type="org.apache.catalina.valves.rewrite.RewriteValve">

    <attribute   name="className"
               description="Fully qualified class name of the managed object"
               type="java.lang.String"
               writeable="false"/>

    <attribute   name="configuration"
               description="Rewrite configuration"
               type="java.lang.String" />

  </mbean>

</mbeans-descriptors>


text:
from findex_gui.web import db
from findex_gui.orm.models import NmapRule, ResourceGroup
from findex_gui.controllers.user.roles import role_req

class NmapController:
    @staticmethod
    @role_req("ADMIN")
    def get(uid: str = None, limit: int = None, offset: int = None):
        q = db.session.query(NmapRule)
        if uid:
            return q.filter(NmapRule.id == uid).first()
        if isinstance(limit, int):
            q = q.limit(limit)
        if isinstance(offset, int):
            q = q.offset(offset)
        return q.all()

    @staticmethod
    @role_req("ADMIN")
    def add(cmd: str, name: str, interval: int, group: str = "Default"):
        if isinstance(name, str) and not name:
            raise Exception("name cannot be empty")
        elif isinstance(cmd, str) and not cmd:
            raise Exception("rule or cmd cannot be empty")

        try:
            _group = db.session.query(ResourceGroup).filter(ResourceGroup.name == group).first()
            if not _group:
                raise Exception("group could not be found")

            db.session.add(NmapRule(rule=cmd, name=name, interval=interval, group=_group))
            db.session.commit()
            db.session.flush()
            return True
        except:
            raise

    @staticmethod
    @role_req("ADMIN")
    def remove(uid):
        try:
            result = db.session.query(NmapRule).filter(NmapRule.id == uid).first()
            if not result:
                return True
            result.remove()
            db.session.commit()
            db.session.flush()
            return True
        except:
            raise

    @staticmethod
    @role_req("ADMIN")
    def update(uid: str, name: str = None, rule: str = None, output: str = None):
        try:
            result = db.session.query(NmapRule).filter(NmapRule.id == uid).first()
            if not result:
                raise Exception("rule not found")
            if isinstance(rule, str):
                result.rule = rule
            if isinstance(output, str):
                result.output = output
            if isinstance(name, str):
                result.name = name
            db.session.commit()
            db.session.flush()
            return True
        except:
            raise


text:
package core

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
	"net/http"
)

// GetIPSecConnectionRequest wrapper for the GetIPSecConnection operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/GetIPSecConnection.go.html to see an example of how to use GetIPSecConnectionRequest.
type GetIPSecConnectionRequest struct {

	// The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the IPSec connection.
	IpscId *string `mandatory:"true" contributesTo:"path" name:"ipscId"`

	// Unique Oracle-assigned identifier for the request.
	// If you need to contact Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`

	// Metadata about the request. This information will not be transmitted to the service, but
	// represents information that the SDK will consume to drive retry behavior.
	RequestMetadata common.RequestMetadata
}

func (request GetIPSecConnectionRequest) String() string {
	return common.PointerString(request)
}

// HTTPRequest implements the OCIRequest interface
func (request GetIPSecConnectionRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {

	return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}

// BinaryRequestBody implements the OCIRequest interface
func (request GetIPSecConnectionRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {

	return nil, false

}

// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request GetIPSecConnectionRequest) RetryPolicy() *common.RetryPolicy {
	return request.RequestMetadata.RetryPolicy
}

// GetIPSecConnectionResponse wrapper for the GetIPSecConnection operation
type GetIPSecConnectionResponse struct {

	// The underlying http response
	RawResponse *http.Response

	// The IpSecConnection instance
	IpSecConnection `presentIn:"body"`

	// For optimistic concurrency control. See `if-match`.
	Etag *string `presentIn:"header" name:"etag"`

	// Unique Oracle-assigned identifier for the request. If you need to contact
	// Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}

func (response GetIPSecConnectionResponse) String() string {
	return common.PointerString(response)
}

// HTTPResponse implements the OCIResponse interface
func (response GetIPSecConnectionResponse) HTTPResponse() *http.Response {
	return response.RawResponse
}


text:
<!DOCTYPE html>

  <title>Ratchet template page</title>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <link href="css/ratchet.min.css" rel="stylesheet">
  <link href="css/zocial.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

  <button class="btn btn-link btn-nav pull-left">

      Back

  </button>

Selected Stories

Lorem ipsum dolor sit amet.


text:
import getopt,sys,traceback
class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __repr__(self):
        return self.msg

def main_function(getOptString='', numArgs=0):
    def main_decorator(maincode):
        def decorated_main(argv=[__name__]):
            try:
                opts={}
                args=[]
                if len(getOptString) > 0:
                    try:
                        opt_list, args = getopt.getopt(argv[1:], getOptString)
                        opts=dict([(x[0][1:], x[1]) for x in opt_list])
                    except getopt.error, msg:
                        raise Usage(msg)
                else:
                    args=argv[1:]
                if len(args) < numArgs:
                    raise Usage("Not enough arguments")
                return maincode(args, opts) or 0
            except KeyboardInterrupt:
                sys.exit(-1)
            except SystemExit:
                pass
            except Usage, usage:
                sys.stderr.write('%s\n%s\n' % (maincode.__doc__, usage.msg))
            except Exception, err:
                cla, exc, trbk = sys.exc_info()
                import traceback
                sys.stderr.write("Caught Exception:\n%s:%s\n%s" % (cla.__name__, str(exc), ''.join(traceback.format_tb(trbk,5))))
                sys.exit(-1)
        return decorated_main
    return main_decorator

########### Example Usage ################

@main_function('o:', 2)
def main(args, opts):
    """Usage: test.py [-o opt1] arg1 arg2"""

if __name__=="__main__":
    sys.exit(main(sys.argv) or 0)


text:
package com.sinotrans.transport.service;

import com.sinotrans.transport.common.enums.CompanyType;
import com.sinotrans.transport.dto.*;
import com.sinotrans.transport.dto.common.CommonNoPageListResponse;
import com.sinotrans.transport.dto.common.RestResponse;

/**
 * Created by emi on 2016/5/31.
 */
public interface AdminOrderService {

    CommonListCountResponse searchImport(CompanyType companyType, OrderImportSearchRequest searchRequest);

    CommonListCountResponse searchExport(CompanyType companyType, OrderExportSearchRequest searchRequest);

    OrderImportAllResponse searchImportAll(CompanyType companyType, Long orderId);

    OrderExportAllResponse searchExportAll(CompanyType companyType, Long orderId);

    CommonNoPageListResponse importAddress(Long containerId);

    CommonNoPageListResponse exportAddress(Long containerId);

    OrderImportAlterResponse importModify(String adminCode, CompanyType companyType, OrderImportAlterRequest alterRequest, boolean checkExist);

    CommonNoPageListResponse modifyImportContainers(String adminCode, CompanyType companyType, ContainerImportAlterRequest alterRequest);

    ContainerDropResponse dropImportContainers(String adminCode, CompanyType companyType, DomainsDropRequest dropRequest);

    CommonNoPageListResponse modifyImportAddress(String adminCode, CompanyType companyType, AddressImportAlterRequest alterRequest);

    CommonNoPageListResponse dropImportAddresses(String adminCode, CompanyType companyType, DomainsDropRequest dropRequest);

    OrderExportAlterResponse exportModify(String adminCode, CompanyType companyType, OrderExportAlterRequest alterRequest, boolean checkExist);

    CommonNoPageListResponse modifyExportContainer(String adminCode, CompanyType companyType, ContainerExportAlterRequest alterRequest);

    ContainerDropResponse dropExportContainers(String adminCode, CompanyType companyType, DomainsDropRequest dropRequest);

    CommonNoPageListResponse modifyExportAddress(String adminCode, CompanyType companyType, AddressExportAlterRequest alterRequest);

    CommonNoPageListResponse dropExportAddresses(String adminCode, CompanyType companyType, DomainsDropRequest dropRequest);

    OrderVerifierResponse verifierOrder(String adminCode, String adminName, CompanyType companyType, Long orderId, OrderVerifierRequest verifierRequest);

    RestResponse modifierOrder(String adminCode, String adminName, CompanyType companyType, Long orderId);

    RestResponse finishContainer(Long containerId);

    OrderCreateResponse OrderExportModifyReques(String adminCode, CompanyType companyType, OrderExportCreateRequest orderExportCreateRequest, boolean checkExist);

    OrderCreateResponse OrderImportModifyReques(String adminCode, CompanyType companyType, OrderImportCreateRequest orderImportCreateRequest, boolean checkExist);

//    OrderWaitingResponse waiting(CompanyType companyType, NoticeWaitingRequest noticeRequest);
//
//    CommonListResponse noticeList(CompanyType companyType, NoticeWaitingRequest noticeRequest);
}


text:
[![Maven Central](https://img.shields.io/maven-central/v/com.google.accompanist/accompanist-testharness)](https://search.maven.org/search?q=g:com.google.accompanist)

For more information, visit the documentation: https://google.github.io/accompanist/testharness

## Download

```groovy
repositories {
    mavenCentral()
}

dependencies {
    implementation "com.google.accompanist:accompanist-testharness:<version>"
}
```

Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap]. These are updated on every commit.

  [snap]: https://oss.sonatype.org/content/repositories/snapshots/com/google/accompanist/accompanist-testharness/


text:
require 'concurrent'

module WaybackArchiver
  # Thread pool
  class ThreadPool
    # Build a thread pool
    # @return [Concurrent::FixedThreadPool/Concurrent::ImmediateExecutor] an instance of a concurrent thread pool
    # @param [Integer] concurrency the desired concurrency
    # @example Build a thread pool with 10 as the desired concurrency
    #    pool = ThreadPool.build(10)
    #    pool.post { some_work } # Returns a Concurrent::FixedThreadPool
    # @example Build a thread pool with 1 as the desired concurrency
    #    pool = ThreadPool.build(1)
    #    pool.post { some_work } # Returns a Concurrent::ImmediateExecutor
    # @see https://github.com/ruby-concurrency/concurrent-ruby/blob/master/doc/thread_pools.md
    def self.build(concurrency)
      if concurrency == 1
        Concurrent::ImmediateExecutor.new
      elsif concurrency > 1
        Concurrent::FixedThreadPool.new(concurrency)
      else
        raise ArgumentError, 'concurrency must be one or greater'
      end
    end
  end
end


text:
import { NodeMaterialBlock } from "../nodeMaterialBlock";
import { NodeMaterialBlockConnectionPointTypes } from "../Enums/nodeMaterialBlockConnectionPointTypes";
import type { NodeMaterialBuildState } from "../nodeMaterialBuildState";
import type { NodeMaterialConnectionPoint } from "../nodeMaterialBlockConnectionPoint";
import { NodeMaterialBlockTargets } from "../Enums/nodeMaterialBlockTargets";
import { RegisterClass } from "../../../Misc/typeStore";
/**
 * Block used to get negative version of a value (i.e. x * -1)
 */
export class NegateBlock extends NodeMaterialBlock {
    /**
     * Creates a new NegateBlock
     * @param name defines the block name
     */
    public constructor(name: string) {
        super(name, NodeMaterialBlockTargets.Neutral);

        this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
        this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);

        this._outputs[0]._typeConnectionSource = this._inputs[0];
    }

    /**
     * Gets the current class name
     * @returns the class name
     */
    public getClassName() {
        return "NegateBlock";
    }

    /**
     * Gets the value input component
     */
    public get value(): NodeMaterialConnectionPoint {
        return this._inputs[0];
    }

    /**
     * Gets the output component
     */
    public get output(): NodeMaterialConnectionPoint {
        return this._outputs[0];
    }

    protected _buildBlock(state: NodeMaterialBuildState) {
        super._buildBlock(state);

        const output = this._outputs[0];

        state.compilationString += this._declareOutput(output, state) + ` = -1.0 * ${this.value.associatedVariableName};\r\n`;

        return this;
    }
}

RegisterClass("BABYLON.NegateBlock", NegateBlock);


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Node Home Page</title>

Header Text

This is some content routed via Express from / with Nodemon watching.


text:
package com.kirbybanman.travelclaimer.view;

import java.text.DateFormat;
import java.util.Currency;
import java.util.Locale;
import java.util.Map;

import com.kirbybanman.travelclaimer.model.Claim;
import com.kirbybanman.travelclaimer.model.Expense;

/**
 * Class for rendering Claims as strings.  Represents separation of (textual) view information
 * from model information.  This ended up being *very* nice.  My model was squeeky clean, and
 * I could still have powerful string representations of it whenever I wanted.
 *
 * @author kdbanman
 */
public class ClaimStringRenderer {

	private Claim claim;
	private DateFormat dateFormatter;

	public ClaimStringRenderer(Claim claim) {
		this.claim = claim;

		dateFormatter = DateFormat.getDateInstance(DateFormat.LONG, Locale.CANADA);
	}

	public String getFullDescription() {
		return "Details\n" +
	           "=======\n" +
			   getAllDetails() + "\n" +
			   "\n" +
			   "Expenses\n" +
			   "========\n" +
			   getAllExpenses();
	}

	public String getAllDetails() {
		return  getDescription() + "\n" +
				"\n" +
				"Status:  " + getStatus()    + "\n" +
				"Start:   " + getStartDate() + "\n" +
		        "Finish:  " + getEndDate()   + "\n";
	}

	public String getAllExpenses() {

		String expenses = "Totals: \n" +
				          getTotals() + "\n" +
				          "\n" +
				          "Individual Expenses:\n" +
				          "\n";

		for (Expense expense : claim.getExpenses()) {
			expenses += new ExpenseStringRenderer(expense).getFullDescription() + "\n\n";
		}

		return expenses;
	}

	public String getStartDate() {
		return dateFormatter.format(claim.getStartDate());
	}

	public String getEndDate() {
		return dateFormatter.format(claim.getEndDate());
	}

	public String getStatus() {
		return claim.getStatus().toString();
	}

	public String getTotals() {

		if (claim.getExpenses().size() < 1) return "(no expenses)";

		String totals = "";

		for (Map.Entry<Currency, Float> total : claim.getExpenses().getTotals().entrySet()) {
			String code = total.getKey().getCurrencyCode();
			String amount = String.format(Locale.getDefault(), "%.2f", total.getValue());
			totals +=  "" + code + " "+ amount + "\n";
		}

		return totals.substring(0, totals.length() - 1);
	}

	public String getDescription() {
		return claim.getDescription();
	}

}


text:
"""
:copyright:
    Lion Krischer (krischer@geophysik.uni-muenchen.de), 2015
:license:
    BSD 3-Clause ("BSD New" or "BSD Simplified")
"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from future.builtins import *  # NOQA

class PyadjointError(Exception):
    """
    Base class for all Pyadjoint exceptions. Will probably be used for all
    exceptions to not overcomplicate things as the whole package is pretty
    small.
    """
    pass

class PyadjointWarning(UserWarning):
    """
    Base class for all Pyadjoint warnings.
    """
    pass

__version__ = "0.0.1a"

# Main objects and functions available at the top level.
from .adjoint_source import AdjointSource, calculate_adjoint_source  # NOQA


text:
package org.hl7.fhir.dstu3.model.codesystems;

// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0

import org.hl7.fhir.exceptions.FHIRException;

public enum ImmunizationRecommendationStatus {

        /**
         * The patient is due for their next vaccination.
         */
        DUE,
        /**
         * The patient is considered overdue for their next vaccination.
         */
        OVERDUE,
        /**
         * added to help the parsers
         */
        NULL;
        public static ImmunizationRecommendationStatus fromCode(String codeString) throws FHIRException {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("due".equals(codeString))
          return DUE;
        if ("overdue".equals(codeString))
          return OVERDUE;
        throw new FHIRException("Unknown ImmunizationRecommendationStatus code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case DUE: return "due";
            case OVERDUE: return "overdue";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/immunization-recommendation-status";
        }
        public String getDefinition() {
          switch (this) {
            case DUE: return "The patient is due for their next vaccination.";
            case OVERDUE: return "The patient is considered overdue for their next vaccination.";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case DUE: return "Due";
            case OVERDUE: return "Overdue";
            default: return "?";
          }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  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. See accompanying LICENSE file.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-project</artifactId>
    <version>2.6.0-cdh5.5.1</version>
    <relativePath>../hadoop-project</relativePath>
  </parent>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-maven-plugins</artifactId>
  <packaging>maven-plugin</packaging>
  <name>Apache Hadoop Maven Plugins</name>
  <properties>
    <maven.dependency.version>3.0</maven.dependency.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>${maven.dependency.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
      <version>${maven.dependency.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <version>${maven.dependency.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-plugin-plugin</artifactId>
        <version>${maven.dependency.version}</version>
        <configuration>
          <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
        </configuration>
        <executions>
          <execution>
            <id>mojo-descriptor</id>
            <goals>
              <goal>descriptor</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <!--
      Skip Clover instrumentation for this module to prevent error finding Clover
      classes during plugin execution when running a build with Clover enabled.
      -->
      <plugin>
        <groupId>com.atlassian.maven.plugins</groupId>
        <artifactId>maven-clover2-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
@interface SetPayPasswordViewController : UIViewController
@property (nonatomic,copy)NSString * phoneCode;
@property (nonatomic,copy)NSString * phone;

@end


text:
package com.socrata.datacoordinator.common.soql.jsonreps

import com.socrata.datacoordinator.truth.json.CodecBasedJsonColumnRep
import com.socrata.soql.types.{SoQLNull, SoQLValue, SoQLBlob, SoQLType}

object BlobRep extends CodecBasedJsonColumnRep[SoQLType, SoQLValue, String](SoQLBlob, _.asInstanceOf[SoQLBlob].value, SoQLBlob(_), SoQLNull)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using FluentAutomation.Interfaces;

namespace FluentAutomation
{
    public class WbTstrAssertTextSyntaxProvider : IAssertTextSyntaxProvider
    {
        private readonly WbTstrAssertSyntaxProvider _assertSyntaxProvider;
        private readonly IAssertTextSyntaxProvider _assertTextSyntaxProvider;
        private readonly ILogger _logger;

        internal WbTstrAssertTextSyntaxProvider(WbTstrAssertSyntaxProvider assertSyntaxProvider, IAssertTextSyntaxProvider assertTextSyntaxProvider, ILogger logger)
        {
            _assertSyntaxProvider = assertSyntaxProvider;
            _assertTextSyntaxProvider = assertTextSyntaxProvider;
            _logger = logger;
        }

        /*-------------------------------------------------------------------*/

        public IAssertTextSyntaxProvider Not
        {
            get
            {
                return new WbTstrAssertTextSyntaxProvider(_assertSyntaxProvider, _assertTextSyntaxProvider.Not, _logger);
            }
        }

        public bool IsInDryRunMode
        {
            get
            {
                return FluentSettings.Current.IsDryRun;
            }
        }

        /*-------------------------------------------------------------------*/

        public IAssertSyntaxProvider In(string selector)
        {
            // Before
            _logger.LogPartialMessage("in element with selector: " + selector, true);

            // Execute
            if (!IsInDryRunMode)
            {
                _assertTextSyntaxProvider.In(selector);
            }

            // After
            return _assertSyntaxProvider;
        }

        public IAssertSyntaxProvider In(ElementProxy element)
        {
            // Before
            _logger.LogPartialMessage("in element with selector: " + element.Element.Selector, true);

            // Execute
            if (!IsInDryRunMode)
            {
                _assertTextSyntaxProvider.In(element);
            }

            // After
            return _assertSyntaxProvider;
        }

        public IAssertSyntaxProvider In(Alert accessor)
        {
            // Before
            _logger.LogPartialMessage("in: " + accessor, true);

            // Execute
            if (!IsInDryRunMode)
            {
                _assertTextSyntaxProvider.In(accessor);
            }

            // After
            return _assertSyntaxProvider;
        }
    }
}


text:
layout: compress
---
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
    <meta name=viewport content="width=device-width, initial-scale=1">

    <meta name=description content="{{ site.bio }}">
    <meta name=author content="{{ site.name }}">

    <title>{{ site.name }} · {{ page.title }}</title>

    {% seo %}

    {% include favicon.html %}

    <link rel="canonical" href="{{ site.url }}{{ page.url | replace:'index.html','' }}">
    <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ site.url }}{{ "/feed.xml" }}" />

        {% if page.tag %}

        {% else %}
            {% if page.title == "About" %}

            {% else %}

            {% endif %}
        {% endif %}

            {{ content }}

    {% include icons.html %}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require(dirname(__FILE__) . '/../../../config.php');
require_once($CFG->libdir.'/filelib.php');

require_login();
require_capability('moodle/site:config', context_system::instance());

if (!empty($CFG->disableonclickaddoninstall)) {
    notice(get_string('featuredisabled', 'tool_installaddon'));
}

require_sesskey();

$jobid = required_param('jobid', PARAM_ALPHANUM);
$plugintype = required_param('type', PARAM_ALPHANUMEXT);
$pluginname = required_param('name', PARAM_PLUGIN);

$zipcontentpath = $CFG->tempdir.'/tool_installaddon/'.$jobid.'/contents';

if (!is_dir($zipcontentpath)) {
    debugging('Invalid location of the extracted ZIP package: '.s($zipcontentpath), DEBUG_DEVELOPER);
    redirect(new moodle_url('/admin/tool/installaddon/index.php'),
        get_string('invaliddata', 'core_error'));
}

if (!is_dir($zipcontentpath.'/'.$pluginname)) {
    debugging('Invalid location of the plugin root directory: '.$zipcontentpath.'/'.$pluginname, DEBUG_DEVELOPER);
    redirect(new moodle_url('/admin/tool/installaddon/index.php'),
        get_string('invaliddata', 'core_error'));
}

$installer = tool_installaddon_installer::instance();

if (!$installer->is_plugintype_writable($plugintype)) {
    debugging('Plugin type location not writable', DEBUG_DEVELOPER);
    redirect(new moodle_url('/admin/tool/installaddon/index.php'),
        get_string('invaliddata', 'core_error'));
}

$plugintypepath = $installer->get_plugintype_root($plugintype);

if (file_exists($plugintypepath.'/'.$pluginname)) {
    debugging('Target location already exists', DEBUG_DEVELOPER);
    redirect(new moodle_url('/admin/tool/installaddon/index.php'),
        get_string('invaliddata', 'core_error'));
}

// Copy permissions form the plugin type directory.
$dirpermissions = fileperms($plugintypepath);
$filepermissions = ($dirpermissions & 0666); // Strip execute flags.

$installer->move_directory($zipcontentpath.'/'.$pluginname, $plugintypepath.'/'.$pluginname, $dirpermissions, $filepermissions);
fulldelete($CFG->tempdir.'/tool_installaddon/'.$jobid);
redirect(new moodle_url('/admin'));


text:
Simple program to solve polynomials and my first Windows Forms app. I don't remember why I created it, but if I had to guess it was for Discrete Math class. Anyways, thought I'd share it.

###Notes
- Runs only on Windows OS


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Gyrostemon ramulosus var. strictus Diels

### Remarks
null


text:
namespace TraktApiSharp.Tests.Objects.Get.Episodes.Json.Writer
{
    using FluentAssertions;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Traits;
    using TraktApiSharp.Extensions;
    using TraktApiSharp.Objects.Get.Episodes;
    using TraktApiSharp.Objects.Json;
    using Xunit;

    [Category("Objects.Get.Episodes.JsonWriter")]
    public partial class EpisodeArrayJsonWriter_Tests
    {
        [Fact]
        public void Test_EpisodeArrayJsonWriter_WriteArray_Array_Exceptions()
        {
            var traktJsonWriter = new ArrayJsonWriter<ITraktEpisode>();
            Func<Task<string>> action = () => traktJsonWriter.WriteArrayAsync(default(IEnumerable<ITraktEpisode>));
            action.Should().Throw<ArgumentNullException>();
        }

        [Fact]
        public async Task Test_EpisodeArrayJsonWriter_WriteArray_Array_Empty()
        {
            IEnumerable<ITraktEpisode> traktEpisodes = new List<TraktEpisode>();

            var traktJsonWriter = new ArrayJsonWriter<ITraktEpisode>();
            string json = await traktJsonWriter.WriteArrayAsync(traktEpisodes);
            json.Should().Be("[]");
        }

        [Fact]
        public async Task Test_EpisodeArrayJsonWriter_WriteArray_Array_SingleObject()
        {
            IEnumerable<ITraktEpisode> traktEpisodes = new List<ITraktEpisode>
            {
                new TraktEpisode
                {
                    SeasonNumber = 1,
                    Number = 1,
                    Title = "title 1",
                    Ids = new TraktEpisodeIds
                    {
                        Trakt = 123456,
                        Tvdb = 234567,
                        Imdb = "345678",
                        Tmdb = 456789,
                        TvRage = 567890
                    },
                    NumberAbsolute = 1,
                    Overview = "overview 1",
                    Runtime = 60,
                    Rating = 8.45672f,
                    Votes = 8925,
                    FirstAired = FIRST_AIRED,
                    UpdatedAt = UPDATED_AT,
                    AvailableTranslationLanguageCodes = new List<string>
                    {
                        "en",
                        "de"
                    },
                    Translations = new List<TraktEpisodeTranslation>
                    {
                        new TraktEpisodeTranslation
                        {
                            Title = "german title 1",
                            Overview = "german overview 1",
                            LanguageCode = "de"
                        },
                        new TraktEpisodeTranslation
                        {
                            Title = "english title 1",
                            Overview = "english overview 1",
                            LanguageCode = "en"
                        }
                    }
                }
            };

            var traktJsonWriter = new ArrayJsonWriter<ITraktEpisode>();
            string json = await traktJsonWriter.WriteArrayAsync(traktEpisodes);
            json.Should().Be(@"[{""season"":1,""number"":1,""title"":""title 1""," +
                             @"""ids"":{""trakt"":123456,""tvdb"":234567,""imdb"":""345678"",""tmdb"":456789,""tvrage"":567890}," +
                             @"""number_abs"":1,""overview"":""overview 1""," +
                             @"""runtime"":60,""rating"":8.45672,""votes"":8925," +
                             $"\"first_aired\":\"{FIRST_AIRED.ToTraktLongDateTimeString()}\"," +
                             $"\"updated_at\":\"{UPDATED_AT.ToTraktLongDateTimeString()}\"," +
                             @"""available_translations"":[""en"",""de""]," +
                             @"""translations"":[{""title"":""german title 1"",""overview"":""german overview 1"",""language"":""de""}," +
                             @"{""title"":""english title 1"",""overview"":""english overview 1"",""language"":""en""}]}]");
        }

        [Fact]
        public async Task Test_EpisodeArrayJsonWriter_WriteArray_Array_Complete()
        {
            IEnumerable<ITraktEpisode> traktEpisodes = new List<ITraktEpisode>
            {
                new TraktEpisode
                {
                    SeasonNumber = 1,
                    Number = 1,
                    Title = "title 1",
                    Ids = new TraktEpisodeIds
                    {
                        Trakt = 123456,
                        Tvdb = 234567,
                        Imdb = "345678",
                        Tmdb = 456789,
                        TvRage = 567890
                    },
                    NumberAbsolute = 1,
                    Overview = "overview 1",
                    Runtime = 60,
                    Rating = 8.45672f,
                    Votes = 8925,
                    FirstAired = FIRST_AIRED,
                    UpdatedAt = UPDATED_AT,
                    AvailableTranslationLanguageCodes = new List<string>
                    {
                        "en",
                        "de"
                    },
                    Translations = new List<TraktEpisodeTranslation>
                    {
                        new TraktEpisodeTranslation
                        {
                            Title = "german title 1",
                            Overview = "german overview 1",
                            LanguageCode = "de"
                        },
                        new TraktEpisodeTranslation
                        {
                            Title = "english title 1",
                            Overview = "english overview 1",
                            LanguageCode = "en"
                        }
                    }
                },
                new TraktEpisode
                {
                    SeasonNumber = 1,
                    Number = 2,
                    Title = "title 2",
                    Ids = new TraktEpisodeIds
                    {
                        Trakt = 123456,
                        Tvdb = 234567,
                        Imdb = "345678",
                        Tmdb = 456789,
                        TvRage = 567890
                    },
                    NumberAbsolute = 2,
                    Overview = "overview 2",
                    Runtime = 60,
                    Rating = 8.45672f,
                    Votes = 8925,
                    FirstAired = FIRST_AIRED,
                    UpdatedAt = UPDATED_AT,
                    AvailableTranslationLanguageCodes = new List<string>
                    {
                        "en",
                        "de"
                    },
                    Translations = new List<TraktEpisodeTranslation>
                    {
                        new TraktEpisodeTranslation
                        {
                            Title = "german title 2",
                            Overview = "german overview 2",
                            LanguageCode = "de"
                        },
                        new TraktEpisodeTranslation
                        {
                            Title = "english title 2",
                            Overview = "english overview 2",
                            LanguageCode = "en"
                        }
                    }
                }
            };

            var traktJsonWriter = new ArrayJsonWriter<ITraktEpisode>();
            string json = await traktJsonWriter.WriteArrayAsync(traktEpisodes);
            json.Should().Be(@"[{""season"":1,""number"":1,""title"":""title 1""," +
                             @"""ids"":{""trakt"":123456,""tvdb"":234567,""imdb"":""345678"",""tmdb"":456789,""tvrage"":567890}," +
                             @"""number_abs"":1,""overview"":""overview 1""," +
                             @"""runtime"":60,""rating"":8.45672,""votes"":8925," +
                             $"\"first_aired\":\"{FIRST_AIRED.ToTraktLongDateTimeString()}\"," +
                             $"\"updated_at\":\"{UPDATED_AT.ToTraktLongDateTimeString()}\"," +
                             @"""available_translations"":[""en"",""de""]," +
                             @"""translations"":[{""title"":""german title 1"",""overview"":""german overview 1"",""language"":""de""}," +
                             @"{""title"":""english title 1"",""overview"":""english overview 1"",""language"":""en""}]}," +
                             @"{""season"":1,""number"":2,""title"":""title 2""," +
                             @"""ids"":{""trakt"":123456,""tvdb"":234567,""imdb"":""345678"",""tmdb"":456789,""tvrage"":567890}," +
                             @"""number_abs"":2,""overview"":""overview 2""," +
                             @"""runtime"":60,""rating"":8.45672,""votes"":8925," +
                             $"\"first_aired\":\"{FIRST_AIRED.ToTraktLongDateTimeString()}\"," +
                             $"\"updated_at\":\"{UPDATED_AT.ToTraktLongDateTimeString()}\"," +
                             @"""available_translations"":[""en"",""de""]," +
                             @"""translations"":[{""title"":""german title 2"",""overview"":""german overview 2"",""language"":""de""}," +
                             @"{""title"":""english title 2"",""overview"":""english overview 2"",""language"":""en""}]}]");
        }
    }
}


text:
require "spec_helper"

describe Mongoid::Sessions::Options do

  describe "#with" do

    context "when passing some options" do

      let(:options) { { database: 'test' } }

      let!(:klass) do
        Band.with(options)
      end

      it "sets the options into the class" do
        expect(klass.persistence_options).to eq(options)
      end

      it "sets the options into the instance" do
        expect(klass.new.persistence_options).to eq(options)
      end

      it "doesnt set the options on class level" do
        expect(Band.new.persistence_options).to be_nil
      end

      context "when calling .collection method" do

        before do
          klass.collection
        end

        it "keeps the options" do
          expect(klass.persistence_options).to eq(options)
        end
      end

      context "when returning a criteria" do

        let(:criteria) do
          klass.all
        end

        it "sets the options into the criteria object" do
          expect(criteria.persistence_options).to eq(options)
        end

        it "doesnt set the options on class level" do
          expect(Band.new.persistence_options).to be_nil
        end
      end
    end
  end

  describe ".with" do

    let(:options) { { database: 'test' } }

    let(:instance) do
      Band.new.with(options)
    end

    it "sets the options into" do
      expect(instance.persistence_options).to eq(options)
    end

    it "passes down the options to collection" do
      expect_any_instance_of(Moped::Session).to receive(:with).with(options).and_return({})
      instance.collection
    end
  end

  describe "#persistence_options" do

    it "touches the thread local" do
      expect(Thread.current).to receive(:[]).with("[mongoid][Band]:persistence-options").and_return({foo: :bar})
      expect(Band.persistence_options).to eq({foo: :bar})
    end

    it "cannot force a value on thread local" do
      expect {
        Band.set_persistence_options(Band, {})
      }.to raise_error(NoMethodError)
    end
  end

  describe ".persistence_options" do

    context "when options exist on the current thread" do

      let(:klass) do
        Band.with(write: { w: 2 })
      end

      it "returns the options" do
        expect(klass.persistence_options).to eq(write: { w: 2 })
      end
    end

    context "when there are no options on the current thread" do

      it "returns nil" do
        expect(Band.persistence_options).to be_nil
      end
    end
  end
end


text:
<?php
class Bredabeds_Solditems_Block_Recount extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element){
        $this->setElement($element);
        $url = Mage::getModel('adminhtml/url')->getUrl('adminhtml/adminhtml_recount/index');

        $html = $this->getLayout()->createBlock('adminhtml/widget_button')
                    ->setType('button')
                    ->setClass('scalable')
                    ->setLabel('Run')
                    ->setOnClick("setLocation('$url')")
                    ->toHtml();

        return $html;
    }
}


text:
'use strict';

////* global $ */
//angular.bootstrap(document, ['controleDeTarefa']);

var app = angular.module('controleDeTarefa',
    [
        'ngRoute'
    ]);


text:
import phue
import time
import threading
import pprint
import RPi.GPIO as io
import logging
import collections
import datetime
#import traceback
import urllib2
import json
import os
import ConfigParser
import TSL2561

PIR_PIN = 18

pp = pprint.PrettyPrinter()
logging.basicConfig(format='%(asctime)s: %(levelname)s %(message)s', level=logging.INFO)

LightSetting = collections.namedtuple('LightSetting', ['command','timeout'])

bridge_ip = None
light_group = None
wu_api_key = None
zip_code = None

LOOP_DELAY = 1
DAY_TIMEOUT = 1800
NIGHT_TIMEOUT = 180

DAYTIME_DARKNESS_THRESHOLD = 10.0

MORNING_COMMAND  = {'ct' : 447, 'bri' : 240, 'on' : True}
DAY_COMMAND = {'ct' : 328, 'bri' : 254, 'on' : True}
EVENING_COMMAND = {'ct' : 328, 'bri' : 254, 'on' : True}
NIGHT_COMMAND  = {'ct' : 328, 'bri' : 127, 'on' : True}

weather = None
tsl = None

def refresh_weather():
	global weather
	f = urllib2.urlopen('http://api.wunderground.com/api/' + wu_api_key +
	                    '/astronomy/conditions/q/' + wu_station + '.json')
	json_string = f.read()
	weather = json.loads(json_string)
	f.close()
#	logging.info('Sunrise hour ' + weather['sun_phase']['sunrise']['hour'] + ' min ' + weather['sun_phase']['sunrise']['minute'])

def get_light_setting():
	now = datetime.datetime.now()

	check_time = now.replace(hour=6, minute=0, second=0)
	if (now < check_time):
		return LightSetting(command = NIGHT_COMMAND, timeout = NIGHT_TIMEOUT)

#	check_time = now.replace(hour=7, minute=0, second=0)
	check_time = now.replace(hour=int(weather['sun_phase']['sunrise']['hour']),
							 minute=int(weather['sun_phase']['sunrise']['minute']),
							 second=0)
	check_time += datetime.timedelta(hours=1)
	if now < check_time:
		return LightSetting(command = MORNING_COMMAND, timeout = DAY_TIMEOUT)

	check_time = now.replace(hour=int(weather['sun_phase']['sunset']['hour']),
						     minute=int(weather['sun_phase']['sunset']['minute']),
						     second=0)
	if now < check_time:
	    lux = tsl.readlux()
	    logging.info('Lux = ' + lux)
		if (lux < DAYTIME_DARKNESS_THRESHOLD):
			return LightSetting(command = DAY_COMMAND, timeout = DAY_TIMEOUT)
		else:
			return None

	check_time = now.replace(hour=22, minute=30, second=0)
	if now < check_time:
		return LightSetting(command = EVENING_COMMAND, timeout = DAY_TIMEOUT)
	else:
		return LightSetting(command = NIGHT_COMMAND, timeout = NIGHT_TIMEOUT)

def all_on(command):
	logging.info('Lights on')
#	bridge.set_group(light_group, command)
	bridge.set_group(light_group, command)

def all_off():
	logging.info('Lights off')
	bridge.set_group(light_group, 'on', False)

def motion_detected():
	return io.input(PIR_PIN)

# Read config file
if os.access(os.getenv('HOME'), os.W_OK):
	config_file_path = os.path.join(
		os.getenv('HOME'), '.hue9000config')
else:
	config_file_path = os.path.join(os.getcwd(), '.hue9000config')

logging.info(config_file_path)

try:
	config = ConfigParser.SafeConfigParser()
	config.read(config_file_path)
	bridge_ip = config.get('hue', 'bridge_ip')
	light_group = config.get('hue', 'light_group')
	wu_api_key = config.get('weather', 'wu_api_key')
	wu_station = config.get('weather', 'wu_station')
except Exception as e:
	logging.error('Error opening/reading config file: ' + config_file_path)
	print e
	exit(1)

logging.info(light_group)

# Set up the pin we'll be reading the PIR on
io.setmode(io.BCM)
io.setup(PIR_PIN, io.IN)

# Connect to the hue bridge
try:
	bridge = phue.Bridge(bridge_ip)
except Exception as e:
	print "Unable to connect to hue bridge."
	print e
	exit(1)

light_timer = None
light_setting = None

refresh_weather()

# Set up light sensor
tsl = TSL2561

while True:
	if motion_detected():
#		logging.info('Motion Detected')
		light_setting = get_light_setting()
		if light_setting:
			# Only run through this logic if the time of day or conditions require
			# the light to be on
			if light_timer is None:
				# No timer created yet, first time through, turn on lights.
				all_on(light_setting.command)
			else:
				if light_timer.isAlive():
					# We had a running timer, which means the lights were on. We'll just kill
					# this timer and create a new one.
					light_timer.cancel()
				else:
					# No timer running, lights must be off, turn on.
					all_on(light_setting.command)
			light_timer = threading.Timer(light_setting.timeout, all_off)
			light_timer.start()

#	pp.pprint(bridge.get_group(LIGHT_GROUP))
	time.sleep(LOOP_DELAY)


text:
package com.communote.server.persistence.user.security;

/**
 *

 * Base Spring DAO Class: is able to create, update, remove, load, and find objects of type
 * com.communote.server.persistence.user.security.AuthenticationFailedStatus.
 *

 *
 * @see com.communote.server.model.user.security.AuthenticationFailedStatus
 * @author Communote GmbH - http://www.communote.com/
 */
public abstract class AuthenticationFailedStatusDaoBase extends
        org.springframework.orm.hibernate3.support.HibernateDaoSupport implements
        com.communote.server.persistence.user.security.AuthenticationFailedStatusDao {

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#create(com.communote.server.model.user.security.AuthenticationFailedStatus)
     */
    @Override
    public com.communote.server.model.user.security.AuthenticationFailedStatus create(
            com.communote.server.model.user.security.AuthenticationFailedStatus authenticationFailedStatus) {
        return (com.communote.server.model.user.security.AuthenticationFailedStatus) this.create(
                TRANSFORM_NONE, authenticationFailedStatus);
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#create(int
     *      transform, com.communote.server.persistence.user.security.AuthenticationFailedStatus)
     */
    @Override
    public Object create(
            final int transform,
            final com.communote.server.model.user.security.AuthenticationFailedStatus authenticationFailedStatus) {
        if (authenticationFailedStatus == null) {
            throw new IllegalArgumentException(
                    "AuthenticationFailedStatus.create - 'authenticationFailedStatus' can not be null");
        }
        this.getHibernateTemplate().save(authenticationFailedStatus);
        return this.transformEntity(transform, authenticationFailedStatus);
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#create(int,
     *      java.util.Collection<com.communote.server.persistence.user.security.
     *      AuthenticationFailedStatus>)
     */
    @Override
    public java.util.Collection<com.communote.server.model.user.security.AuthenticationFailedStatus> create(
            final int transform,
            final java.util.Collection<com.communote.server.model.user.security.AuthenticationFailedStatus> entities) {
        if (entities == null) {
            throw new IllegalArgumentException(
                    "AuthenticationFailedStatus.create - 'entities' can not be null");
        }
        this.getHibernateTemplate()
                .executeWithNativeSession(
                        new org.springframework.orm.hibernate3.HibernateCallback<com.communote.server.model.user.security.AuthenticationFailedStatus>() {
                            @Override
                            public com.communote.server.model.user.security.AuthenticationFailedStatus doInHibernate(
                                    org.hibernate.Session session)
                                    throws org.hibernate.HibernateException {
                                for (java.util.Iterator<com.communote.server.model.user.security.AuthenticationFailedStatus> entityIterator = entities
                                        .iterator(); entityIterator.hasNext();) {
                                    create(transform, entityIterator.next());
                                }
                                return null;
                            }
                        });
        return entities;
    }

    /**
     * @see
     *      com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#create(java.
     *      util
     *      .Collection<com.communote.server.persistence.user.security.AuthenticationFailedStatus>)
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public java.util.Collection<com.communote.server.model.user.security.AuthenticationFailedStatus> create(
            final java.util.Collection<com.communote.server.model.user.security.AuthenticationFailedStatus> entities) {
        return create(TRANSFORM_NONE, entities);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void evict(com.communote.server.model.user.security.AuthenticationFailedStatus entity) {
        this.getHibernateTemplate().evict(entity);
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#findByUserAndChannel(com.communote.server.model.user.User,
     *      com.communote.server.model.security.ChannelType)
     */
    @Override
    public com.communote.server.model.user.security.AuthenticationFailedStatus findByUserAndChannel(
            final com.communote.server.model.user.User user,
            final com.communote.server.model.security.ChannelType channel) {
        if (user == null) {
            throw new IllegalArgumentException(
                    "com.communote.server.persistence.user.security.AuthenticationFailedStatusDao.findByUserAndChannel(User user, ChannelType channel) - 'user' can not be null");
        }
        if (channel == null) {
            throw new IllegalArgumentException(
                    "com.communote.server.persistence.user.security.AuthenticationFailedStatusDao.findByUserAndChannel(User user, ChannelType channel) - 'channel' can not be null");
        }
        try {
            return this.handleFindByUserAndChannel(user, channel);
        } catch (RuntimeException rt) {
            throw new RuntimeException(
                    "Error performing 'com.communote.server.persistence.user.security.AuthenticationFailedStatusDao.findByUserAndChannel(User user, ChannelType channel)' --> "
                            + rt, rt);
        }
    }

    /**
     * Performs the core logic for
     * {@link #findByUserAndChannel(com.communote.server.model.user.User, com.communote.server.model.security.ChannelType)}
     */
    protected abstract com.communote.server.model.user.security.AuthenticationFailedStatus handleFindByUserAndChannel(
            com.communote.server.model.user.User user,
            com.communote.server.model.security.ChannelType channel);

    /**
     * Performs the core logic for {@link #incFailedAuthCount(long)}
     */
    protected abstract void handleIncFailedAuthCount(long failedAuthStatusId);

    /**
     * Performs the core logic for {@link #updateLockedTimeout(long, java.sql.Timestamp)}
     */
    protected abstract void handleUpdateLockedTimeout(long failedAuthStatusId,
            java.sql.Timestamp lockedTimeout);

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#incFailedAuthCount(long)
     */
    @Override
    public void incFailedAuthCount(final long failedAuthStatusId) {
        try {
            this.handleIncFailedAuthCount(failedAuthStatusId);
        } catch (RuntimeException rt) {
            throw new RuntimeException(
                    "Error performing 'com.communote.server.persistence.user.security.AuthenticationFailedStatusDao.incFailedAuthCount(long failedAuthStatusId)' --> "
                            + rt, rt);
        }
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#load(int,
     *      Long)
     */
    @Override
    public Object load(final int transform, final Long id) {
        if (id == null) {
            throw new IllegalArgumentException(
                    "AuthenticationFailedStatus.load - 'id' can not be null");
        }
        final Object entity = this.getHibernateTemplate().get(
                com.communote.server.model.user.security.AuthenticationFailedStatusImpl.class, id);
        return transformEntity(transform,
                (com.communote.server.model.user.security.AuthenticationFailedStatus) entity);
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#load(Long)
     */
    @Override
    public com.communote.server.model.user.security.AuthenticationFailedStatus load(Long id) {
        return (com.communote.server.model.user.security.AuthenticationFailedStatus) this.load(
                TRANSFORM_NONE, id);
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#loadAll()
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public java.util.Collection<com.communote.server.model.user.security.AuthenticationFailedStatus> loadAll() {
        return (java.util.Collection<com.communote.server.model.user.security.AuthenticationFailedStatus>) this
                .loadAll(TRANSFORM_NONE);
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#loadAll(int)
     */
    @Override
    public java.util.Collection<?> loadAll(final int transform) {
        final java.util.Collection<?> results = this.getHibernateTemplate().loadAll(
                com.communote.server.model.user.security.AuthenticationFailedStatusImpl.class);
        this.transformEntities(transform, results);
        return results;
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#remove(com.communote.server.model.user.security.AuthenticationFailedStatus)
     */
    @Override
    public void remove(
            com.communote.server.model.user.security.AuthenticationFailedStatus authenticationFailedStatus) {
        if (authenticationFailedStatus == null) {
            throw new IllegalArgumentException(
                    "AuthenticationFailedStatus.remove - 'authenticationFailedStatus' can not be null");
        }
        this.getHibernateTemplate().delete(authenticationFailedStatus);
    }

    /**
     * @see
     *      com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#remove(java.
     *      util
     *      .Collection<com.communote.server.persistence.user.security.AuthenticationFailedStatus>)
     */
    @Override
    public void remove(
            java.util.Collection<com.communote.server.model.user.security.AuthenticationFailedStatus> entities) {
        if (entities == null) {
            throw new IllegalArgumentException(
                    "AuthenticationFailedStatus.remove - 'entities' can not be null");
        }
        this.getHibernateTemplate().deleteAll(entities);
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#remove(Long)
     */
    @Override
    public void remove(Long id) {
        if (id == null) {
            throw new IllegalArgumentException(
                    "AuthenticationFailedStatus.remove - 'id' can not be null");
        }
        com.communote.server.model.user.security.AuthenticationFailedStatus entity = this.load(id);
        if (entity != null) {
            this.remove(entity);
        }
    }

    /**
     * Transforms a collection of entities using the
     * {@link #transformEntity(int,com.communote.server.model.user.security.AuthenticationFailedStatus)}
     * method. This method does not instantiate a new collection.
     *

     * This method is to be used internally only.
     *
     * @param transform
     *            one of the constants declared in
     *            com.communote.server.persistence.user.security.AuthenticationFailedStatusDao
     * @param entities
     *            the collection of entities to transform
     * @see #transformEntity(int,com.communote.server.model.user.security.AuthenticationFailedStatus)
     */
    protected void transformEntities(final int transform, final java.util.Collection<?> entities) {
        switch (transform) {
        case TRANSFORM_NONE: // fall-through
        default:
            // do nothing;
        }
    }

    /**
     * Allows transformation of entities into value objects (or something else for that matter),
     * when the transform flag is set to one of the constants defined in
     * com.communote.server.persistence.user.security.AuthenticationFailedStatusDao,
     * please note that the {@link #TRANSFORM_NONE} constant denotes no transformation, so the
     * entity itself will be returned.
     *
     * If the integer argument value is unknown {@link #TRANSFORM_NONE} is assumed.
     *
     * @param transform
     *            one of the constants declared in
     *            {@link com.communote.server.persistence.user.security.AuthenticationFailedStatusDao}
     * @param entity
     *            an entity that was found
     * @return the transformed entity (i.e. new value object, etc)
     * @see #transformEntities(int,java.util.Collection)
     */
    protected Object transformEntity(final int transform,
            final com.communote.server.model.user.security.AuthenticationFailedStatus entity) {
        Object target = null;
        if (entity != null) {
            switch (transform) {
            case TRANSFORM_NONE: // fall-through
            default:
                target = entity;
            }
        }
        return target;
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#update(com.communote.server.model.user.security.AuthenticationFailedStatus)
     */
    @Override
    public void update(
            com.communote.server.model.user.security.AuthenticationFailedStatus authenticationFailedStatus) {
        if (authenticationFailedStatus == null) {
            throw new IllegalArgumentException(
                    "AuthenticationFailedStatus.update - 'authenticationFailedStatus' can not be null");
        }
        this.getHibernateTemplate().update(authenticationFailedStatus);
    }

    /**
     * @see
     *      com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#update(java.
     *      util
     *      .Collection<com.communote.server.persistence.user.security.AuthenticationFailedStatus>)
     */
    @Override
    public void update(
            final java.util.Collection<com.communote.server.model.user.security.AuthenticationFailedStatus> entities) {
        if (entities == null) {
            throw new IllegalArgumentException(
                    "AuthenticationFailedStatus.update - 'entities' can not be null");
        }
        this.getHibernateTemplate()
                .executeWithNativeSession(
                        new org.springframework.orm.hibernate3.HibernateCallback<com.communote.server.model.user.security.AuthenticationFailedStatus>() {
                            @Override
                            public com.communote.server.model.user.security.AuthenticationFailedStatus doInHibernate(
                                    org.hibernate.Session session)
                                    throws org.hibernate.HibernateException {
                                for (java.util.Iterator<com.communote.server.model.user.security.AuthenticationFailedStatus> entityIterator = entities
                                        .iterator(); entityIterator.hasNext();) {
                                    update(entityIterator.next());
                                }
                                return null;
                            }
                        });
    }

    /**
     * @see com.communote.server.persistence.user.security.AuthenticationFailedStatusDao#updateLockedTimeout(long,
     *      java.sql.Timestamp)
     */
    @Override
    public void updateLockedTimeout(final long failedAuthStatusId,
            final java.sql.Timestamp lockedTimeout) {
        if (lockedTimeout == null) {
            throw new IllegalArgumentException(
                    "com.communote.server.persistence.user.security.AuthenticationFailedStatusDao.updateLockedTimeout(long failedAuthStatusId, java.sql.Timestamp lockedTimeout) - 'lockedTimeout' can not be null");
        }
        try {
            this.handleUpdateLockedTimeout(failedAuthStatusId, lockedTimeout);
        } catch (RuntimeException rt) {
            throw new RuntimeException(
                    "Error performing 'com.communote.server.persistence.user.security.AuthenticationFailedStatusDao.updateLockedTimeout(long failedAuthStatusId, java.sql.Timestamp lockedTimeout)' --> "
                            + rt, rt);
        }
    }

}


text:
module.exports = (function(){
  'use strict';

  function getPathSegments(crossPlatformShapesInstance, data) {
    var x = data.x,
      y = data.y,
      width = data.width,
      height = data.height;

    var yControlPoint = height * (2/3);

    var pathData = [{command: 'moveTo', points: [x, y]},
      {command: 'bezierCurveTo', points: [(x), (y + yControlPoint), (x + width), (y + yControlPoint), (x + width), (y)]}];

    return pathData;
  }

  function getDimensions(crossPlatformShapesInstance) {
    return {
      markerWidth:20,
      markerHeight:30
    };
  }

  return {
    getPathSegments:getPathSegments,
    getDimensions:getDimensions
  };
})();


text:
Both the Elasticsearch and Kibana archives can be extracted by using the below commands.
Alternatively, simply double-clicking them should do the trick.

```
cd /path/to/archive/directory
tar -zxf archive.tar.gz
```

## Starting up Elasticsearch

```
cd /path/to/elasticsearch
bin/elasticsearch
```

## Resetting the `elastic` user's password

If you lose the password for the `elastic` user, it can be reset with the following commands.

```
cd /path/to/elasticsearch
bin/elasticsearch-reset-password -u elastic
```

## Generating a new Kibana enrollment token

If you need to generate a new enrollment token for Kibana, this can be done with the following commands.

```
cd /path/to/elasticsearch
bin/elasticsearch-create-enrollment-token --scope kibana
```

## Disabling Gatekeeper for Kibana directory

macOS contains a security feature named Gatekeeper, which prevents Kibana from starting up.
We can disable it for just the Kibana directory, which allows Kibana to start up correctly.
Simply use the following command to do so.

```
xattr -d -r com.apple.quarantine /path/to/kibana
```

## Starting up Kibana

```
cd /path/to/kibana
bin/kibana
```


text:
title: Turtles All the Way Down
written_by: John Green
available: 'October 10th, 2017'
isbn: '9780525555384'
binding: Hardcover
link_to_buy_page:
image_path: 'https://images.booksense.com/images/384/555/9780525555384.jpg'
link:
---


text:
class Asset < ActiveRecord::Base
  include Freeberry::Models::Asset
end


text:
/* SPDX-License-Identifier: MIT */

import { Container, Typography } from "@mui/material";
import * as React from "react";

/**
 * An error screen that will be used as a fallback UI.
 * @see https://reactjs.org/docs/error-boundaries
 */
export class ErrorBoundary extends React.Component<Props> {
  static getDerivedStateFromError(error: Error) {
    // Update state so the next render will show the fallback UI.
    return { error };
  }

  override state: State = { error: undefined };

  override componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // You can also log the error to an error reporting service
    console.error(error, errorInfo);
  }

  override render() {
    const { error } = this.state;

    if (!error) {
      return this.props.children;
    }

    return (
      <Container sx={{ marginTop: "43vh" }}>
        <Container maxWidth="sm">
          <Typography
            variant="h1"
            align="center"
            sx={{
              fontSize: "2em",
              fontWeight: 300,
              "& strong": {
                fontWeight: 400,
              },
            }}
          >
            Error {error.status || 500}: {error.message}
          </Typography>
        </Container>
      </Container>
    );
  }
}

type Props = {
  children: React.ReactNode;
};

type State = {
  error: (Error & { status?: number }) | undefined;
};


text:
Transaction Object
==================

An SMTP transaction is valid from MAIL FROM time until RSET or "final-dot".

API
---

* transaction.mail\_from

The value of the MAIL FROM command

* transaction.rcpt\_to

An Array of values of recipients from the RCPT TO command

* transaction.data\_lines

An Array of the lines of the email after DATA

* transaction.notes

A safe place to store transaction specific values.


text:
<?php

namespace hipanel\modules\finance\tests\acceptance\seller;

use Exception;
use hipanel\helpers\Url;
use Codeception\Example;
use hipanel\tests\_support\Step\Acceptance\Seller;
use hipanel\modules\finance\tests\_support\Page\bill\Create;

class ToggleSignCest
{
    private ?string $billId = null;

    public function _before(Seller $I): void
    {
        $I->markTestSkipped("Moved to PW");
    }

    /**
     * @dataProvider provideDataBill
     * @throws Exception
     */
    public function ensureToggleSignWorksAndICanCreateBill(Seller $I, Example $example): void
    {
        $I->login();
        $create = new Create($I);

        $I->needPage(Url::to('@bill/create'));
        $I->see('Create payment', 'h1');
        $I->see('Save', 'button');

        $billData = iterator_to_array($example->getIterator());

        $create->fillMainBillFields($billData);
        $create->addCharge($billData['charge']);
        $create->clickToggleSign();

        $I->click('Save');
        $this->billId = $create->seeActionSuccess();
    }

    /**
     * @dataProvider provideDataBill
     * @depends      ensureToggleSignWorksAndICanCreateBill
     */
    public function ensureBillWasCreatedCorrectlyAndDeleteIt(Seller $I, Example $example): void
    {
        $I->login();

        $billData = iterator_to_array($example->getIterator());
        $chargeData = $billData['charge'];

        $create = new Create($I);

        $I->needPage(Url::to('@bill') . '?view=' . $this->billId);
        $I->see('$' . $chargeData['sum']);

        $create->deleteBillById($this->billId);
    }

    protected function provideDataBill(): array
    {
        return [
            'client' => [
                'login' => 'hipanel_test_user',
                'type' => 'PayPal',
                'sum' => '-777.00',
                'quantity' => '1',
                'charge' => [
                    'class' => 'Client',
                    'objectId' => 'hipanel_test_admin',
                    'type' => 'PayPal',
                    'sum' => '777.00',
                    'quantity' => '1',
                ],
            ],
        ];
    }
}