text:
package org.winterblade.minecraft.harmony.misc.operations;

import net.minecraft.item.Item;
import org.winterblade.minecraft.harmony.api.BasicOperation;
import org.winterblade.minecraft.harmony.api.Operation;
import org.winterblade.minecraft.harmony.api.OperationException;

/**
 * Created by Matt on 5/2/2016.
 */
@Operation(name = "setToolHarvestLevel")
public class SetToolLevelOperation extends BasicOperation {
    /*
     * Serialized properties
     */
    private Item what;
    private int to;
    private String as;

    /*
     * Computed properties
     */
    private transient int from;

    @Override
    public void init() throws OperationException {
        if(what == null) throw new OperationException("Cannot set tool harvest level on unknown item.");

        from = what.getHarvestLevel(null, as);
    }

    @Override
    public void apply() {
        what.setHarvestLevel(as, to);
    }

    @Override
    public void undo() {
        what.setHarvestLevel(as, from);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <sys/time.h>

#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>

#include "private/bionic_time_conversions.h"

static int futimesat(int fd, const char* path, const timeval tv[2], int flags) {
  timespec ts[2];
  if (tv && (!timespec_from_timeval(ts[0], tv[0]) || !timespec_from_timeval(ts[1], tv[1]))) {
    errno = EINVAL;
    return -1;
  }
  return utimensat(fd, path, tv ? ts : nullptr, flags);
}

int utimes(const char* path, const timeval tv[2]) {
  return futimesat(AT_FDCWD, path, tv, 0);
}

int lutimes(const char* path, const timeval tv[2]) {
  return futimesat(AT_FDCWD, path, tv, AT_SYMLINK_NOFOLLOW);
}

int futimesat(int fd, const char* path, const timeval tv[2]) {
  return futimesat(fd, path, tv, 0);
}

int futimes(int fd, const timeval tv[2]) {
  timespec ts[2];
  if (tv && (!timespec_from_timeval(ts[0], tv[0]) || !timespec_from_timeval(ts[1], tv[1]))) {
    errno = EINVAL;
    return -1;
  }
  return futimens(fd, tv ? ts : nullptr);
}


text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: nikolayyotsov
 * Date: 5/22/17
 * Time: 11:24 PM
 */

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;

class LogoutController extends Controller
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function logout()
    {
        if ($this->isAuthenticated()) {
            Auth::logout();
        }

        return view('welcome');
    }
}


text:
using System;
using System.Threading;

class WaitOneEx
{
    private Mutex myMutex;
    private ManualResetEvent myMRE;
    private int iRet = -1;

    public WaitOneEx()
    {
        myMutex = new Mutex(false);
        myMRE = new ManualResetEvent(false);
    }

    public static int Main()
    {
        WaitOneEx wao = new WaitOneEx();
        wao.Run();
        Console.WriteLine(100 == wao.iRet ? "Test Passed" : "Test Failed");
        return wao.iRet;
    }

    private void Run()
    {
        Console.WriteLine("Test abandoned mutex is thrown using WaitOne");
        Thread t = new Thread(new ThreadStart(this.AbandonTheMutex));
        t.Start();
        myMRE.WaitOne();
        try
        {
            Console.WriteLine("Wait on an abandoned mutex");
            bool bRet = myMutex.WaitOne(10000);
            Console.WriteLine("WaitOne did not throw an exception!");
        }
        catch(AbandonedMutexException am)
        {
            Console.WriteLine("AbandonedMutexException thrown! Checking values...");
            if(-1 == am.MutexIndex && null == am.Mutex)
                iRet = 100;
        }
        catch(Exception e)
        {
            Console.WriteLine("Unexpected exception thrown: " + e.ToString());
        }
    }

    private void AbandonTheMutex()
    {
        Console.WriteLine("Acquire the Mutex");
        myMutex.WaitOne();
        myMRE.Set();
        Thread.Sleep(1000);
    }
}


text:
import {
	SELECTED_LOCATION
} from '../actions';

const initialState = null;

export default (state = initialState, action) => {
	switch (action.type) {
		case SELECTED_LOCATION:
			return action.id;
		default:
			return state;
	}
};


text:
using System;
using Agiil.Domain.Tickets;
using CSF.Entities;

namespace Agiil.Web.Rendering.Tickets
{
  /// <summary>
  /// Service which gets the URI to a ticket's main "view this ticket detail" web page.
  /// </summary>
  public interface IGetsTicketUri
  {
    Uri GetAbsoluteUri(TicketReference ticketRef);
  }
}


text:
package com.quollwriter.ui;

import java.awt.Point;
import java.awt.Dimension;
import java.awt.Component;
import java.awt.Rectangle;

import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;

import com.gentlyweb.utils.*;

import com.jgoodies.forms.builder.*;
import com.jgoodies.forms.factories.*;
import com.jgoodies.forms.layout.*;

import com.quollwriter.*;
import com.quollwriter.data.*;
import com.quollwriter.text.*;
import com.quollwriter.ui.components.ActionAdapter;

public class NamedObjectPreviewPopup extends HideablePopup<AbstractProjectViewer>
{

    private NamedObject obj = null;

    public NamedObjectPreviewPopup (AbstractProjectViewer viewer)
    {

        super (viewer);

    }

    /**
     * Not supported, call show with NamedObject instead.
     */
    @Override
    public void show (final int         showDelay,
                      final int         hideDelay,
                      final Point       po,
                      final ActionListener onHide)
    {

        throw new UnsupportedOperationException ("Not supported, use show(NamedObject,int,int,Point,ActionListener) instead.");

    }

    public void show (final NamedObject obj,
                      final int         showDelay,
                      final int         hideDelay,
                      final Point       po,
                      final ActionListener onHide)
    {

        if (obj == null)
        {

            return;

        }

        this.obj = obj;

        super.show (showDelay,
                    hideDelay,
                    po,
                    onHide);

    }

    @Override
    public JComponent getContent ()
    {

        if (this.obj == null)
        {

            throw new IllegalStateException ("No object set.");

        }

        // TODO: Make this nicer later.
        if (this.obj instanceof Chapter)
        {

            Chapter c = (Chapter) this.obj;

            JComponent t = UIUtils.getChapterInfoPreview (c,
                                                          null,
                                                          this.viewer);

            if (t == null)
            {

                // May be a fake chapter, return null.
                return null;

            }

            t.setSize (new Dimension (300,
                                      Short.MAX_VALUE));

            return t;

        } else {

            String firstLine = Environment.getUIString (LanguageStrings.project,
                                                        LanguageStrings.sidebar,
                                                        LanguageStrings.objectpreview,
                                                        LanguageStrings.assets,
                                                        LanguageStrings.novalue);
                                                        //"No description.";

            String t = (obj.getDescription () != null ? obj.getDescription ().getText () : null);

            if ((t != null)
                &&
                (t.length () > 0)
               )
            {

                firstLine = new Paragraph (t, 0).getFirstSentence ().getText ();

            }

            JEditorPane desc = UIUtils.createHelpTextPane (firstLine,
                                                           null);

            FormLayout fl = new FormLayout ("380px",
                                            "p");

            PanelBuilder pb = new PanelBuilder (fl);

            CellConstraints cc = new CellConstraints ();

            pb.add (desc, cc.xy (1, 1));

            desc.setAlignmentX (Component.LEFT_ALIGNMENT);

            JPanel p = pb.getPanel ();
            p.setOpaque (true);
            p.setBackground (UIUtils.getComponentColor ());

            return p;

        }

    }

}


text:
<?php

# Copyright (c) 2012 John Reese
# Licensed under the MIT license

access_ensure_global_level( plugin_config_get( 'update_threshold' ) );
require_once( config_get( 'plugin_path' ) . 'Source/Source.ViewAPI.php' );

$f_changeset_id = gpc_get_int( 'id' );
$f_offset = gpc_get_int( 'offset', 0 );

$t_changeset = SourceChangeset::load( $f_changeset_id );

$t_repos = SourceRepo::load_by_changesets( $t_changeset );
if ( count( $t_repos ) < 1 ) {
	trigger_error( ERROR_GENERIC, ERROR );
}

$t_repo = array_shift( $t_repos );
$t_repo->load_branches();
$t_vcs = SourceVCS::repo( $t_repo );

$t_use_porting = plugin_config_get( 'enable_porting' );

html_page_top1( plugin_lang_get( 'title' ) );
html_page_top2();
?>

<form action="<?php echo plugin_page( 'edit' ), '&id=', $t_changeset->id ?>" method="post">
<?php echo form_security_field( 'plugin_Source_edit' ) ?>
<input type="hidden" name="offset" value="<?php echo $f_offset ?>"/>

<table class="<?php echo $t_columns > 4 ? 'width90' : 'width75' ?>" cellspacing="1" align="center">

<?php echo string_display_line( $t_repo->name ), ': ', $t_vcs->show_changeset( $t_repo, $t_changeset ) ?>

<?php print_bracket_link( plugin_page( 'view' ) . '&id=' . $t_changeset->id . '&offset=' . $f_offset, plugin_lang_get( 'back_changeset' ) ); ?>

<tr <?php echo helper_alternate_class() ?>>
<?php echo plugin_lang_get( 'author' ) ?>
<select name="user_id">
<option value="0" <?php echo check_selected( 0, $t_changeset->user_id ) ?>>--</option>
<?php print_user_option_list( $t_changeset->user_id ) ?>
</select>

<tr <?php echo helper_alternate_class() ?>>
<?php echo plugin_lang_get( 'committer' ) ?>
<select name="committer_id">
<option value="0" <?php echo check_selected( 0, $t_changeset->committer_id ) ?>>--</option>
<?php print_user_option_list( $t_changeset->committer_id ) ?>
</select>

<tr <?php echo helper_alternate_class() ?>>
<?php echo plugin_lang_get( 'branch' ) ?>
<select name="branch">
<?php if ( $t_changeset->branch == "" ) { ?>
<option value="" <?php echo check_selected( "", $t_changeset->branch ) ?>>--</option>
<?php } foreach( $t_repo->branches as $t_branch ) { ?>
<option value="<?php echo string_attribute( $t_branch ) ?>" <?php echo check_selected( $t_branch, $t_changeset->branch ) ?>><?php echo string_display_line( $t_branch ) ?></option>
<?php } ?>
</select>

<?php if ( $t_use_porting ) { ?>
<tr <?php echo helper_alternate_class() ?>>
<?php echo plugin_lang_get( 'ported' ) ?>
<select name="ported">
<option value="" <?php echo check_selected( "", $t_changeset->ported ) ?>><?php echo plugin_lang_get( 'pending' ) ?></option>
<option value="0" <?php echo check_selected( "0", $t_changeset->ported ) ?>><?php echo plugin_lang_get( 'na' ) ?></option>
<option value="">--</option>
<?php foreach( $t_repo->branches as $t_branch ) { if ( $t_branch == $t_changeset->branch ) { continue; } ?>
<option value="<?php echo string_attribute( $t_branch ) ?>" <?php echo check_selected( $t_branch, $t_changeset->ported ) ?>><?php echo string_display_line( $t_branch ) ?></option>
<?php } ?>
</select>

<?php } ?>

<tr <?php echo helper_alternate_class() ?>>
<?php echo plugin_lang_get( 'message' ) ?>
<textarea name="message" cols="80" rows="8"><?php echo string_textarea( $t_changeset->message ) ?></textarea>

<input type="submit" value="<?php echo plugin_lang_get( 'edit' ) ?>"/>

</form>

<?php
html_page_bottom1( __FILE__ );


text:
all: app object

app:
	popcc -o main pingpong.ph pingpong.cc main.cc

object:
	popcc -object -o pingpong.obj pingpong.cc pingpong.ph main.cc
	./pingpong.obj -listlong > obj.map

clean:
	rm -f *.o *.obj main obj.map

run:
	popcrun obj.map ./main


text:
const os = require('os')

module.exports = function Startup () {
  const platform = os.platform()
  const supported = ['darwin', 'linux', 'win32']

  if (supported.indexOf(platform) > -1) {
    return require(`./startup/${platform}.js`)
  }

  throw new Error(`Unsupported platform ${platform}`)
}


text:
#import "FIRAdditionalUserInfo.h"

NS_ASSUME_NONNULL_BEGIN

@interface FIRAdditionalUserInfo () <NSSecureCoding>

/** @fn userInfoWithVerifyAssertionResponse:
    @brief A convenience factory method for constructing a @c FIRAdditionalUserInfo instance from
        data returned by the verifyAssertion endpoint.
    @param verifyAssertionResponse Data returned by the verifyAssertion endpoint.
    @return A new instance of @c FIRAdditionalUserInfo using data from the verifyAssertion endpoint.
 */
+ (nullable instancetype)userInfoWithVerifyAssertionResponse:
    (FIRVerifyAssertionResponse *)verifyAssertionResponse;

/** @fn initWithProviderID:profile:username:
    @brief Designated initializer.
    @param providerID The provider identifier.
    @param profile Dictionary containing the additional IdP specific information.
    @param username The name of the user.
    @param isNewUser Indicates whether or not the current user was signed in for the first time.
 */
- (nullable instancetype)initWithProviderID:(nullable NSString *)providerID
                                    profile:(nullable NSDictionary<NSString *, NSObject *> *)profile
                                   username:(nullable NSString *)username
                                  isNewUser:(BOOL)isNewUser NS_DESIGNATED_INITIALIZER;

@end

NS_ASSUME_NONNULL_END


text:
namespace MOE.Common.Models.Repositories
{
    public class ApproachPcdAggregationRepositoryFactory
    {
        private static IApproachPcdAggregationRepository _approachPcdAggregationRepository;

        public static IApproachPcdAggregationRepository Create()
        {
            if (_approachPcdAggregationRepository != null)
                return _approachPcdAggregationRepository;
            return new ApproachPcdAggregationRepository();
        }

        public static void SetApplicationEventRepository(IApproachPcdAggregationRepository newRepository)
        {
            _approachPcdAggregationRepository = newRepository;
        }
    }
}


text:
var tokenizer = require('ecmaless-tokenizer')
var tdop = require('./tdop')

module.exports = function (src) {
  var r = tokenizer(src)
  if (r.type !== 'Ok') {
    return r
  }
  return tdop.parse(r.value)
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="../wwwroot/css/bootstrap.css">
  <link rel="stylesheet" href="../wwwroot/css/font-awesome.css">
  <link rel="stylesheet" href="app.css">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      Bibliobabel

1(current)

1

1

  Seyed Jalal Hosseini

  Settings

  Help

  Log Out

{{}}

{{kir}}

{{post.user.screenName}}

                        <time title="{{ post.createdAt | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}" am-time-ago="post.createdAt"></time>

                                <textarea type="text" class="form-control" placeholder="Search for..." rows="1"></textarea>

                    <button class="btn btn-default" type="button">Send</button>

                    No comment yet!

{{comment.owner.displayName}} <time title="{{ comment.createdAt | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}" am-time-ago="comment.createdAt"></time>

                                Like

kos


text:
<?php

//
// uranus directory override. if $_COOKIE['psudevhost'] is
// set, nothing else in this repository's /app/ will be executed.
//
// this override functionality is limited by the conditional
// logic capabilities of an .htaccess file, so we'll perform
// this check on the Host: header.
//
// See also: /app/.htaccess
//
if( 'www.dev.plymouth.edu' === $_SERVER['HTTP_HOST'] ) {
	require dirname( __DIR__ ) . '/legacy/git-uranus.php';
}

require dirname( __DIR__ ) . '/legacy/git-bootstrap.php';

require 'autoload.php';
require PSU_BASE_DIR . '/routes/routes.php';

$uri = substr( $_SERVER['REQUEST_URI'], strlen( parse_url( PSU\Config\Factory::get_config()->get( 'app_url' ), PHP_URL_PATH ) ) );

dispatch( $uri );


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;

namespace EspaceClient.FrontOffice.Domaine
{
    public partial class Region
    {

        [DataMember]
        public long ID { get; set; }

        [DataMember]
				[StringLength(50)]
        public string Code { get; set; }

        [DataMember]
				[StringLength(50)]
        public string CodeEchange { get; set; }

        [DataMember]
				[StringLength(255)]
        public string Description { get; set; }

        [DataMember]
        public virtual Pays Pays { get; set; }

        [DataMember]
        public long PaysID { get; set; }
    }
}


text:
{-# LANGUAGE DeriveDataTypeable         #-}
{-# LANGUAGE DeriveFoldable             #-}
{-# LANGUAGE DeriveFunctor              #-}
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE DeriveTraversable          #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoMonomorphismRestriction  #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE UndecidableInstances       #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE PatternGuards              #-}

module Language.Fixpoint.Types.Environments (

  -- * Environments
    SEnv, SESearch(..)
  , emptySEnv, toListSEnv, fromListSEnv
  , mapSEnvWithKey
  , insertSEnv, deleteSEnv, memberSEnv, lookupSEnv
  , intersectWithSEnv
  , filterSEnv
  , lookupSEnvWithDistance
  , envCs

  , IBindEnv, BindId, BindMap
  , emptyIBindEnv, insertsIBindEnv, deleteIBindEnv, elemsIBindEnv

  , BindEnv, beBinds
  , insertBindEnv, emptyBindEnv, lookupBindEnv, mapBindEnv, adjustBindEnv
  , bindEnvFromList, bindEnvToList
  , unionIBindEnv

  ) where

-- import qualified Data.Binary as B
import qualified Data.Binary as B
import           Data.Generics             (Data)
import           Data.Typeable             (Typeable)
import           GHC.Generics              (Generic)
import           Data.Hashable
import qualified Data.HashMap.Strict       as M
import qualified Data.HashSet              as S
import           Data.Maybe
import           Text.PrettyPrint.HughesPJ
import           Control.DeepSeq

import           Language.Fixpoint.Types.PrettyPrint
import           Language.Fixpoint.Types.Names
import           Language.Fixpoint.Types.Refinements
import           Language.Fixpoint.Types.Substitutions
import           Language.Fixpoint.Misc

type BindId        = Int
type BindMap a     = M.HashMap BindId a

newtype IBindEnv   = FB (S.HashSet BindId) deriving (Eq, Data, Typeable, Generic)

newtype SEnv a     = SE { seBinds :: M.HashMap Symbol a }
                     deriving (Eq, Data, Typeable, Generic, Foldable, Traversable)

data SizedEnv a    = BE { beSize  :: Int
                        , beBinds :: BindMap a
                        } deriving (Eq, Show, Functor, Foldable, Generic, Traversable)

type BindEnv       = SizedEnv (Symbol, SortedReft)
-- Invariant: All BindIds in the map are less than beSize

toListSEnv              ::  SEnv a -> [(Symbol, a)]
toListSEnv (SE env)     = M.toList env

fromListSEnv            ::  [(Symbol, a)] -> SEnv a
fromListSEnv            = SE . M.fromList

mapSEnv f (SE env)      = SE (fmap f env)
mapSEnvWithKey f        = fromListSEnv . fmap f . toListSEnv
deleteSEnv x (SE env)   = SE (M.delete x env)
insertSEnv x y (SE env) = SE (M.insert x y env)
lookupSEnv x (SE env)   = M.lookup x env
emptySEnv               = SE M.empty
memberSEnv x (SE env)   = M.member x env
intersectWithSEnv f (SE m1) (SE m2) = SE (M.intersectionWith f m1 m2)
filterSEnv f (SE m)     = SE (M.filter f m)

lookupSEnvWithDistance x (SE env)
  = case M.lookup x env of
     Just z  -> Found z
     Nothing -> Alts $ symbol <$> alts
  where
    alts       = takeMin $ zip (editDistance x' <$> ss) ss
    ss         = symbolString <$> fst <$> M.toList env
    x'         = symbolString x
    takeMin xs = [z | (d, z) <- xs, d == getMin xs]
    getMin     = minimum . (fst <$>)

data SESearch a = Found a | Alts [Symbol]

-- | Functions for Indexed Bind Environment

emptyIBindEnv :: IBindEnv
emptyIBindEnv = FB S.empty

deleteIBindEnv :: BindId -> IBindEnv -> IBindEnv
deleteIBindEnv i (FB s) = FB (S.delete i s)

insertsIBindEnv :: [BindId] -> IBindEnv -> IBindEnv
insertsIBindEnv is (FB s) = FB (foldr S.insert s is)

elemsIBindEnv :: IBindEnv -> [BindId]
elemsIBindEnv (FB s) = S.toList s

-- | Functions for Global Binder Environment
insertBindEnv :: Symbol -> SortedReft -> BindEnv -> (BindId, BindEnv)
insertBindEnv x r (BE n m) = (n, BE (n + 1) (M.insert n (x, r) m))

emptyBindEnv :: BindEnv
emptyBindEnv = BE 0 M.empty

bindEnvFromList :: [(BindId, Symbol, SortedReft)] -> BindEnv
bindEnvFromList [] = emptyBindEnv
bindEnvFromList bs = BE (1 + maxId) be
  where
    maxId          = maximum $ fst3 <$> bs
    be             = M.fromList [(n, (x, r)) | (n, x, r) <- bs]

bindEnvToList :: BindEnv -> [(BindId, Symbol, SortedReft)]
bindEnvToList (BE _ be) = [(n, x, r) | (n, (x, r)) <- M.toList be]

mapBindEnv :: ((Symbol, SortedReft) -> (Symbol, SortedReft)) -> BindEnv -> BindEnv
mapBindEnv f (BE n m) = BE n $ M.map f m

lookupBindEnv :: BindId -> BindEnv -> (Symbol, SortedReft)
lookupBindEnv k (BE _ m) = fromMaybe err (M.lookup k m)
  where
    err                  = errorstar $ "lookupBindEnv: cannot find binder" ++ show k

unionIBindEnv :: IBindEnv -> IBindEnv -> IBindEnv
unionIBindEnv (FB m1) (FB m2) = FB $ m1 `S.union` m2

adjustBindEnv :: ((Symbol, SortedReft) -> (Symbol, SortedReft)) -> BindId -> BindEnv -> BindEnv
adjustBindEnv f i (BE n m) = BE n $ M.adjust f i m

instance Functor SEnv where
  fmap = mapSEnv

instance Fixpoint BindEnv where
  toFix (BE _ m) = vcat $ map toFixBind $ hashMapToAscList m

toFixBind (i, (x, r)) = text "bind" <+> toFix i <+> toFix x <+> text ":" <+> toFix r

instance (Fixpoint a) => Fixpoint (SEnv a) where
   toFix (SE m)   = toFix (hashMapToAscList m)

instance Fixpoint (SEnv a) => Show (SEnv a) where
  show = render . toFix

instance Monoid (SEnv a) where
  mempty        = SE M.empty
  mappend s1 s2 = SE $ M.union (seBinds s1) (seBinds s2)

instance Monoid BindEnv where
  mempty = BE 0 M.empty
  mappend (BE 0 _) b = b
  mappend b (BE 0 _) = b
  mappend _ _        = errorstar "mappend on non-trivial BindEnvs"

envCs :: BindEnv -> IBindEnv -> [(Symbol, SortedReft)]
envCs be env = [lookupBindEnv i be | i <- elemsIBindEnv env]

instance Fixpoint (IBindEnv) where
  toFix (FB ids) = text "env" <+> toFix ids

--------------------------------------------------------------------------------

instance NFData IBindEnv
instance NFData BindEnv
instance (NFData a) => NFData (SEnv a)

instance B.Binary IBindEnv
instance B.Binary BindEnv
instance (B.Binary a) => B.Binary (SEnv a)
instance (Hashable a, Eq a, B.Binary a) => B.Binary (S.HashSet a) where
  put = B.put . S.toList
  get = S.fromList <$> B.get


text:
package ru.al.gorev.myapplication;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;

public class SoGame extends AppCompatActivity
        implements FragPrev.OnSelectedButtonListener,FragGame.OnFinishGame {
    View vwe;
    FragmentManager fran;
    public static int score = 0;
    public static int money = 0;
    public static int pTime,Ilifes,diffficulty,moneyX;
    static float dishevel = 0.0f;
    static boolean isGr,onPause,hasItems,firstDiffF = false,secondDiffF = false,secondSetted = false;
    static int[][] items_;
    char[] jk;
    TextView why,who;
    static GameItem gameItem;

    @SuppressLint("InlinedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            isGr=true;
            jk = new char[36];
            gameItem = new GameItem(getSharedPreferences(MnActivity.SHARED_IS_PS,MODE_PRIVATE)
                    .getInt("ho_selected",0)+1);
            moneyX = gameItem.moneyXX;
            restoreAll();
            setContentView(R.layout.game_layout);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            vwe = findViewById(R.id.tyt);
            vwe.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
            why = (TextView)findViewById(R.id.textView3);
            who = (TextView)findViewById(R.id.textViewLfs);
            who.setText(("-"+Ilifes));
            why.setText("SCORE  "+String.valueOf(score)+"   COINS  +"+String.valueOf(money));
        }else {
            isGr = false;
            setContentView(R.layout.stop_set);
            Toast tst = Toast.makeText(getApplicationContext(), "В ИГРУ МОЖНО ЗАЙТИ, " +
                    "ТОЛЬКО ПРЕДОСТАВИВ РАЗРЕШНИЯ!", Toast.LENGTH_LONG);
            TextView tc = (TextView)findViewById(R.id.tex_y);
            tc.setText(R.string.dont_grant);
            tst.show();
        }
    }

    private void restoreAll() {
        SharedPreferences spSO = getPreferences(MODE_PRIVATE);
        if (spSO.contains("Items")) {
            hasItems = true;
            gameItem = new GameItem(getSharedPreferences(MnActivity.SHARED_IS_PS,MODE_PRIVATE)
                    .getInt("last_scd_item",0)+1);
            FragGame.selected_img = gameItem.itDrawIt;
            FragGame.selected_img_l = gameItem.itDrawItL;
            pTime = gameItem.itSpeedT;
            moneyX = gameItem.moneyXX;
            diffficulty = 1;
            Ilifes = getPreferences(MODE_PRIVATE).getInt("gF_hd",0);
            SharedPreferences apl = getSharedPreferences(MnActivity.SHARED_IS_PS,MODE_PRIVATE);
            score = apl.getInt("lastGame",0);
            money = apl.getInt("yamagata",0);
            if (apl.getInt("l_mode_selected",0)==1){
            if (score>555&&diffficulty<2){
                diffficulty++;
                firstDiffF = true;
            }if (score>3333&&diffficulty<3){
                diffficulty++;
                secondDiffF = true;
            }}else{if (apl.getInt("l_mode_selected",0)==2){
                firstDiffF = true;
                secondSetted = true;
                diffficulty = 2;
                if (score>555){
                    diffficulty++;
                    secondDiffF = true;
                }}else{
                diffficulty = 3;
                firstDiffF = true;
                secondDiffF = true;
            }}
            FragGame.selected_item = apl.getInt("last_scd_item",0)+1;
            String th = spSO.getString("Items", null);
            FragGame.isLefted = spSO.getBoolean("isLefted",false);
            dishevel = spSO.getFloat("differed",0.0f);
            char[] it = new char[36];
            if (th!=null){
             it = th.toCharArray();}
            jk = it;
            items_= new int[6][6];
            for (int em=0;em<6;em++){
                items_[em] = new int[6];
            }
            int nb = 0;
            for (int i=0;i<6;i++){
                for (int i2=0;i2<6;i2++){
                    items_[i][i2] = Integer.parseInt(String.valueOf(it[nb]));
                    nb++;
                }}
        }else{
            diffficulty = 1;
            dishevel = 0.0f;
            pTime = gameItem.itSpeedT;
            FragGame.selected_item = gameItem.rate;
            FragGame.selected_img = gameItem.itDrawIt;
            FragGame.selected_img_l = gameItem.itDrawItL;
            hasItems = false;
            onPause = false;
            Ilifes = gameItem.itLife;
        }
    }
    void clearAllPrefs(SharedPreferences spSo){
        SharedPreferences.Editor spEdit = spSo.edit();
        spEdit.remove("Items");
        spEdit.putInt("gF_hd",gameItem.itLife);
        spEdit.apply();
        Ilifes = gameItem.itLife;
        SharedPreferences.Editor sp = getSharedPreferences(MnActivity.SHARED_IS_PS,MODE_PRIVATE).edit();
        sp.remove("lastGame");
        sp.remove("last_scd_item");
        sp.remove("yamagata");
        sp.putBoolean("onPause",false);
        sp.apply();
    }
    void saveAllPrefs(){
        if (isGr&&FragPrev.isPl){
            FragPrev.isPl = false;
            onPause = true;
            SharedPreferences sp = getPreferences(MODE_PRIVATE);
            SharedPreferences.Editor spEdit = sp.edit();
            String items = "";
            for (int i=0;i<6;i++){
                for (int o=0;o<6;o++){
                    items = items + String.valueOf(FragGame.allItems[i][o]);
                }
            }
            spEdit.putString("Items",items)
                    .putInt("gF_hd",Ilifes)
                    .putInt("yuj",diffficulty)
                    .putFloat("differed", dishevel)
                    .putBoolean("isLefted",FragGame.isLefted)
                    .apply();
            hasItems=true;
            sp = getSharedPreferences(MnActivity.SHARED_IS_PS,MODE_PRIVATE);
            spEdit = sp.edit();
            spEdit.putInt("last_scd_item",FragGame.selected_item-1);
            spEdit.putBoolean("onPause",true);
            if (money>0){
            spEdit.putInt(getString(R.string.money_i),sp.getInt(getString(R.string.money_i),0)+money);
            spEdit.putInt("yamagata",money);
            }
            if (sp.getInt("ethy",0)<score){
                spEdit.putInt("ethy",score);
            }
            spEdit.putInt(getString(R.string.Time_to_pause),pTime)
                    .putInt("lastGame",score)
                    .apply();
        }else{
            SharedPreferences sp = getSharedPreferences(MnActivity.SHARED_IS_PS,MODE_PRIVATE);
            SharedPreferences.Editor spEdit = sp.edit();
            if (sp.getInt("ethy",0)<score){
                spEdit.putInt("ethy",score)
                        .apply();
            }
        }
    }
    @Override
    public void onBackPressed() {
        if (!FragPrev.isPl){
            startActivity(new Intent(SoGame.this,MnActivity.class));
        }
    }
    @SuppressLint({"InlinedApi", "SetTextI18n"})
    @Override
    protected void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            isGr=true;
            restoreAll();
        vwe.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
                fran = getSupportFragmentManager();
                FragGame fragGame = (FragGame) fran.findFragmentById(R.id.fragment2);
                FragPrev fragPrev = (FragPrev) fran.findFragmentById(R.id.fragment);
                if (fragPrev != null) {
                    fragPrev.makeVISIBLE(false, false);
                }
                if (FragPrev.finished&&fragGame != null) {
                    fragGame.restoreThenFinished();
                    score = 0;
                    money = 0;
                    why.setText("SCORE  "+String.valueOf(score)+"   COINS  +"+String.valueOf(money));
                    who.setText(("-"+Ilifes));
                }
        }else {isGr = false;}
    }
    @Override
    protected void onPause() {
        super.onPause();
        saveAllPrefs();
        }
    public void onButtonSelected(int ix) {
        fran = getSupportFragmentManager();
        FragGame fragGame = (FragGame) fran.findFragmentById(R.id.fragment2);
        if (fragGame!=null){
            switch (ix){
                case 1:
                    fragGame.setLeft();
                    break;
                case 3:
                    fragGame.setRight();
                    break;
                case 10:
                    fragGame.setTop();
                    break;
                case 30:
                    fragGame.setDown();
                    break;
                case 2:
                    fragGame.playG(true);
                    break;
                case 0:
                    saveAllPrefs();
                    break;
            }}}

    @Override
    public void onFinishG() {
        String path;
        fran = getSupportFragmentManager();
        FragPrev fragPrev = (FragPrev) fran.findFragmentById(R.id.fragment);
        FragGame.allItems = FragGame.nullItems;
        if (fragPrev!=null){
            fragPrev.makeVISIBLE(false,true);
        }
        SharedPreferences sp = getSharedPreferences(MnActivity.SHARED_IS_PS,MODE_PRIVATE);
        SharedPreferences.Editor spEdit = sp.edit();
        if (sp.getInt("ethy",0)<score){
            spEdit.putInt("ethy",score)
                    .apply();
        }
        if (money>0){
        spEdit.putInt(getString(R.string.money_i),sp.getInt(getString(R.string.money_i),0)+money);
        }
        clearAllPrefs(getPreferences(MODE_PRIVATE));
        Intent inst = new Intent(SoGame.this,AfterGame.class);
        Bitmap lo = getScreenShot();
        try {
            if(lo!=null){
            File file = new File(Environment.getExternalStorageDirectory(),"LastGameScreenShot.jpg");
            FileOutputStream fos = new FileOutputStream(file);
            lo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
            path = file.getAbsolutePath();}else{
                path = "high";
            }
        }catch(Exception e){
            path = "cp";
            Log.e("file","out error");}
        inst.putExtra("path",path).putExtra("score",score);
        score = 0;
        money = 0;
        startActivity(inst);
    }

    @Override
    public void moneyPlus() {
        why.setText("SCORE  "+String.valueOf(score)+"   COINS  +"+String.valueOf(money));
        who.setText(("-"+Ilifes));
        dishevel+=0.7f;
        if (score>555&&!firstDiffF&&diffficulty<2){
            diffficulty++;
            firstDiffF = true;
            dishevel = 0.0f;
        }
        if (score>555&&diffficulty<3&&secondSetted){
            diffficulty++;
            secondDiffF = true;
            dishevel = 0.0f;
        }
        if (score>3333&&!secondDiffF&&diffficulty<3){
            diffficulty++;
            secondDiffF = true;
            dishevel = 0.0f;
        }
        Log.d("mon",String.valueOf(money));
    }
    Bitmap getScreenShot(){
        vwe.setDrawingCacheEnabled(true);
        vwe.buildDrawingCache();
        return vwe.getDrawingCache();
    }
    public void onGrant(View view) {
        Intent intu = new Intent(SoGame.this,MnActivity.class);
        intu.putExtra("neeToGrant",true);
        startActivity(intu);
    }
    static class GameItem {
        int[] itLifer = new int[]{1,2,2,1,3,4,6,5,8,228,1488};
        int[] itXenon = new int[]{1,2,3,4,3,4,5,6,8,10,20};
        int[] itSpeedTime = new int[]{800,650,375,250,300,250,300,150,187,50,1};
        int[] itCoasts = new int[]{1000,4500,7000,9999,15000,22222,55000,120000,250000,1000000,9999999};
        //TODO: all
        String[] itCataractSpeed = new String[]{"x1","x1,25","x2","x3","x2,5","x3"
                ,"x2,5","x5","x4","x15","x1000"};
        String[] itNames = new String[]{"Петух классический","Петух  классический живучий","Пiвень"
        ,"Петух классический раскалённый","Петух-курильщик","Петух-вейпер","Индюк","Петух двухглавый","Негор-петух","Петушара-Кочок"
                ,"ЛЕГЕНДАРНЫЙ древний ПЕТУХ"};
        int[] itDraw = new int[]{R.drawable.ic_launcher,R.drawable.petoh,R.drawable.o_petuhukr
                ,R.drawable.ptyjh};
        int[] itDrawL= new int[]{R.drawable.ic_launcher_l,R.drawable.petoh_l,R.drawable.o_petuhukr_l
                ,R.drawable.ptyjh_l};
        int itLife;
        int rate;
        int itSpeedT;
        int itDrawIt;
        int itDrawItL;
        int itCoast;
        int moneyXX;
        String itCharactS,nameCoc;
        GameItem(int rating){
            itLife = itLifer[rating-1];
            itCoast = itCoasts[rating-1];
            itSpeedT = itSpeedTime[rating-1];
            itCharactS = itCataractSpeed[rating-1];
            rate = rating;
            nameCoc = itNames[rating-1];
            itDrawIt = itDraw[rating-1];
            itDrawItL = itDrawL[rating-1];
            moneyXX = itXenon[rating-1];
        }
    }
}


text:
using Microsoft.AspNet.Identity.EntityFramework;
using z4a_dsa.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace z4a_dsa
{
	public class DefaultContext : IdentityDbContext<IdentityUser>
	{
		public DefaultContext()	: base("DefaultContext") {	}
	}
}


text:
"""Tests for dm_c19_modelling.evaluation.forecast_indexing."""

import os

from absl.testing import absltest
from dm_c19_modelling.evaluation import forecast_indexing
import numpy as np
import pandas as pd

_TEST_DATASET = "test_dataset"
_TEST_FORECASTS_FILE = "test_forecasts.csv"

def _get_test_predictions_and_arrays():
  dates = np.array(["2020-05-07", "2020-05-08", "2020-05-09"])
  sites = np.array(["site_1", "site_2"])
  targets = np.array(["new_confirmed", "new_deceased"])
  predictions = np.random.rand(len(dates), len(sites), len(targets)) * 10
  return predictions, dates, sites, targets

def _get_test_entry(directory):
  return {
      "forecast_id": "12345",
      "file_location": os.path.join(directory, _TEST_FORECASTS_FILE),
      "source_data_info": ["test_dataset_1"],
      "creation_timestamp": "2020-06-07_12:43:02",
      "dataset_name": _TEST_DATASET,
      "last_observation_date": "2020-05-04",
      "cadence": 1,
      "features_used": ["new_deceased"],
      "extra_info": {"model_description": "test_model"}
  }

def _create_test_forecasts(file_location):
  target_dfs = []
  for target_name in ["new_deceased", "new_confirmed"]:
    target_dfs.append(pd.DataFrame({
        "site_id": ["site_1", "site_2", "site_1", "site_2"],
        "date": ["2020-05-05", "2020-05-05", "2020-05-06", "2020-05-06"],
        "target_name": [target_name] * 4,
        "prediction": np.random.rand(4) * 10
    }))
  df = pd.concat(target_dfs)
  df.to_csv(file_location, index=False)

class ForecastIndexingTest(absltest.TestCase):

  def setUp(self):
    super().setUp()
    self._preds_arr, self._dates_arr, self._sites_arr, self._targets_arr = (
        _get_test_predictions_and_arrays())
    self._test_dir = absltest.get_default_test_tmpdir()
    os.makedirs(self._test_dir, exist_ok=True)
    self._key = "12345"
    self._entry = _get_test_entry(self._test_dir)
    _create_test_forecasts(self._entry["file_location"])
    self._remove_index_if_exists()

  def _remove_index_if_exists(self):
    index_path = os.path.join(
        self._test_dir, f"forecast_index-{_TEST_DATASET}.json")
    if os.path.exists(index_path):
      os.remove(index_path)

  def test_prediction_df_columns(self):
    """Checks the columns in the predictions dataframe are as expected."""
    predictions_df = forecast_indexing.build_predictions_df(
        self._preds_arr, self._dates_arr, self._sites_arr, self._targets_arr)
    np.testing.assert_array_equal(
        sorted(predictions_df.columns),
        ["date", "prediction", "site_id", "target_name"])

  def test_prediction_df_entries(self):
    """Checks that values in the predictions dataframe are as expected."""
    predictions_df = forecast_indexing.build_predictions_df(
        self._preds_arr, self._dates_arr, self._sites_arr, self._targets_arr)
    np.testing.assert_array_equal(sorted(predictions_df.site_id.unique()),
                                  self._sites_arr)
    np.testing.assert_array_equal(sorted(predictions_df.date.unique()),
                                  self._dates_arr)
    np.testing.assert_array_equal(sorted(predictions_df.target_name.unique()),
                                  self._targets_arr)
    sample_entry = predictions_df.query(
        "site_id=='site_1' & date=='2020-05-09' & target_name=='new_confirmed'"
    ).prediction
    np.testing.assert_array_almost_equal(
        sample_entry, [self._preds_arr[2][0][0]])

    sample_entry = predictions_df.query(
        "site_id=='site_2' & date=='2020-05-07' & target_name=='new_deceased'"
    ).prediction
    np.testing.assert_array_almost_equal(
        sample_entry, [self._preds_arr[0][1][1]])

  def test_predictions_df_bad_shape(self):
    """Checks that building the dataframe fails with inconsistent shapes."""
    sites_arr = np.append(self._sites_arr, ["site_3"])
    with self.assertRaisesRegex(
        ValueError, "Predictions have unexpected shape *"):
      forecast_indexing.build_predictions_df(
          self._preds_arr, self._dates_arr, sites_arr, self._targets_arr)

  def test_add_to_index_and_query(self):
    """Tests that a well-formatted forecasts entry is added to the index."""
    with forecast_indexing.ForecastIndex(self._test_dir, _TEST_DATASET,
                                         read_only=False) as index:
      index.add_entry(self._key, self._entry)

    read_index = forecast_indexing.ForecastIndex(self._test_dir, _TEST_DATASET)
    self.assertIsNotNone(read_index.query_by_forecast_id("12345"))

  def test_fails_validation_nan_predictions(self):
    """Checks that validation fails if there are NaNs in predictions."""
    df = pd.read_csv(self._entry["file_location"])
    df.loc[0, "prediction"] = np.nan
    df.to_csv(self._entry["file_location"], index=False)
    with forecast_indexing.ForecastIndex(self._test_dir, _TEST_DATASET,
                                         read_only=False) as index:
      with self.assertRaisesWithLiteralMatch(
          ValueError, "NaNs founds in forecasts"):
        index.add_entry(self._key, self._entry)

  def test_fails_validation_missing_predictions(self):
    """Checks that validation fails if a date is undefined for a site."""
    df = pd.read_csv(self._entry["file_location"])
    df.drop(0, inplace=True)
    df.to_csv(self._entry["file_location"], index=False)
    with forecast_indexing.ForecastIndex(self._test_dir, _TEST_DATASET,
                                         read_only=False) as index:
      with self.assertRaisesRegex(
          ValueError, "Missing data found in the forecasts*"):
        index.add_entry(self._key, self._entry)

  def test_fails_validation_missing_column(self):
    """Checks that validation fails when a column is missing."""
    df = pd.read_csv(self._entry["file_location"])
    df.drop(columns=["target_name"], inplace=True)
    df.to_csv(self._entry["file_location"], index=False)
    with forecast_indexing.ForecastIndex(self._test_dir, _TEST_DATASET,
                                         read_only=False) as index:
      with self.assertRaisesRegex(
          ValueError, "Forecasts must have columns*"):
        index.add_entry(self._key, self._entry)

  def test_fails_validation_inconsistent_cadence(self):
    """Checks that validation fails when forecasts have inconsistent cadence."""
    df = pd.read_csv(self._entry["file_location"])
    df_extra = df[df.date == "2020-05-06"]
    df_extra.date = "2020-05-08"
    df = pd.concat([df, df_extra])
    df.to_csv(self._entry["file_location"], index=False)
    with forecast_indexing.ForecastIndex(self._test_dir, _TEST_DATASET,
                                         read_only=False) as index:
      with self.assertRaisesWithLiteralMatch(
          ValueError, "Inconsistent cadence found in forecasts"):
        index.add_entry(self._key, self._entry)

  def test_fails_invalid_target_name(self):
    """Checks that validation fails when forecasts contain an invalid target."""
    df = pd.read_csv(self._entry["file_location"])
    df.loc[0:3, "target_name"] = "bad_target"
    df.to_csv(self._entry["file_location"], index=False)

    with forecast_indexing.ForecastIndex(self._test_dir, _TEST_DATASET,
                                         read_only=False) as index:
      with self.assertRaisesWithLiteralMatch(
          ValueError, "Invalid target in forecasts: bad_target"):
        index.add_entry(self._key, self._entry)

if __name__ == "__main__":
  absltest.main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.Text.Formatting;
using System.ComponentModel.Composition;
using EnvDTE;

namespace Microsoft.VisualStudio.Editor.EmacsEmulation.Commands
{
    /// <summary>
    /// If the region is active, this command deletes the region without putting it on the Clipboard Ring or the Clipboard;
    /// otherwise, it signals an error and messages in the status bar that the region is not active.
    ///
    /// Keys: Ctrl+Del
    /// </summary>
    [EmacsCommand(EmacsCommandID.DeleteSelection, UndoName="Delete")]
    internal class DeleteSelectionCommand : EmacsCommand
    {
        internal override void Execute(EmacsCommandContext context)
        {
            if (!context.TextView.Selection.IsEmpty)
                context.EditorOperations.Delete();
            else
                context.Manager.UpdateStatus(Resources.OperationCannotBePerformedWithoutTextSelection);
        }
    }
}


text:
package org.g_node.micro.commons;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit tests for the {@link RDFService} class. Output and Error streams are redirected
 * from the console to a different PrintStream and reset after tests are finished
 * to avoid mixing tool error messages with actual test error messages.
 *
 * @author Michael Sonntag (sonntag@bio.lmu.de)
 */
public class RDFServiceTest {

    private ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    private PrintStream stdout;

    private final String tmpRoot = System.getProperty("java.io.tmpdir");
    private final String testFolderName = "rdfServiceTest";
    private final Path testFileFolder = Paths.get(tmpRoot, testFolderName);

    /**
     * Redirect Out stream and create a test folder and the main
     * test file in the java temp directory.
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {

        this.stdout = System.out;
        this.outStream = new ByteArrayOutputStream();
        System.setOut(new PrintStream(this.outStream));

        Logger rootLogger = Logger.getRootLogger();
        rootLogger.setLevel(Level.INFO);
        rootLogger.addAppender(
                new ConsoleAppender(
                        new PatternLayout("[%-5p] %m%n")
                )
        );

        final String testFileName = "test.txt";
        final File currTestFile = this.testFileFolder.resolve(testFileName).toFile();
        FileUtils.write(currTestFile, "This is a normal test file");
    }

    /**
     * Reset Out stream to the console and remove all created
     * folders and files after the tests are done.
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {

        System.setOut(this.stdout);

        if (Files.exists(this.testFileFolder)) {
            FileUtils.deleteDirectory(this.testFileFolder.toFile());
        }
    }

    /**
     * Check, that a Jena RDF model is written to file.
     * @throws Exception
     */
    @Test
    public void testSaveModelToFile() throws Exception {

        final String outFileName = "testRdf.ttl";
        final String outFilePath = this.testFileFolder.resolve(outFileName).toString();
        final String outFileFormat = "TTL";
        final String testString = String.join(
                "", "[INFO ] Writing data to RDF file '",
                outFilePath, "' using format '", outFileFormat, "'"
        );

        final Model model = ModelFactory.createDefaultModel();

        RDFService.saveModelToFile("", model, outFileFormat);
        assertThat(this.outStream.toString()).startsWith("[ERROR] Could not open output file");

        RDFService.saveModelToFile(outFilePath, model, outFileFormat);
        assertThat(this.outStream.toString()).contains(testString);
    }

    /**
     * Test that an empty and a non empty RDF file can be opened.
     * @throws Exception
     */
    @Test
    public void testOpenModelFromFile() throws Exception {
        final File currEmptyTestFile = this.testFileFolder.resolve("testEmpty.ttl").toFile();
        FileUtils.write(currEmptyTestFile, "");

        Model emptyModel = RDFService.openModelFromFile(currEmptyTestFile.toString());
        assertThat(emptyModel.isEmpty()).isTrue();

        final String miniTTL = "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\n_:a foaf:name\t\"TestName\"";
        final File currTestFile = this.testFileFolder.resolve("test.ttl").toFile();
        FileUtils.write(currTestFile, miniTTL);

        Model m = RDFService.openModelFromFile(currTestFile.toString());
        assertThat(m.isEmpty()).isFalse();
    }

}


text:
void checkError(cl_int error, int line);

// =================================================================================================

// Set the locations of the OpenCL kernel files
#define CL_INCLUDE_FILE "src/settings.h"
#define CL_KERNEL_FILE "src/kernels.cl"

// Determine the location where to output the PTX code
#define CL_PTX_FILE "bin/myGEMM.cl.ptx"

// Define OpenCL compiler options, such as "-cl-nv-maxrregcount=127"
#define COMPILER_OPTIONS ""

// =================================================================================================

// Matrix-multiplication using a custom OpenCL SGEMM kernel. This function also copies the input
// matrices to the GPU, runs SGEMM, and copies the output matrix back to the CPU.
void myclblas(float* A, float* B, float* C,
              int K, int M, int N,
              int timerID) {

    // In case of myGEMM10, compute matrix sizes K, M, N as rounded-up to form complete tiles
    #if KERNEL == 10
        int K_XL = CEIL_DIV(K, TSK) * TSK;
        int M_XL = CEIL_DIV(M, TSM) * TSM;
        int N_XL = CEIL_DIV(N, TSN) * TSN;
    #else
        int K_XL = K;
        int M_XL = M;
        int N_XL = N;
    #endif

    // Define OpenCL variables
    cl_int err;
    cl_platform_id platform = 0;
    cl_device_id device = 0;
    cl_device_id devices[MAX_NUM_DEVICES];
    cl_uint numDevices = 0;
    cl_context_properties props[3] = {CL_CONTEXT_PLATFORM, 0, 0};
    cl_context context = 0;
    cl_command_queue queue = 0;
    cl_event event = NULL;
    cl_program program = NULL;
    char deviceName[MAX_DEVICE_NAME];

    // Configure the OpenCL environment
    err = clGetPlatformIDs(1, &platform, NULL);
    err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
    err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
    device = devices[CURRENT_DEVICE];
    props[1] = (cl_context_properties)platform;
    context = clCreateContext(props, 1, &device, NULL, NULL, &err);
    queue = clCreateCommandQueue(context, device, 0, &err);
    err = clGetDeviceInfo(device, CL_DEVICE_NAME, MAX_DEVICE_NAME, deviceName, NULL);
    checkError(err,__LINE__);
    //printf("## %d devices, running on %d: '%s'\n", numDevices, CURRENT_DEVICE, deviceName);

    // Read the kernel file from disk
    long sizeHeader, sizeSource;
    char* header = readKernelFile(CL_INCLUDE_FILE, &sizeHeader);
    char* source = readKernelFile(CL_KERNEL_FILE, &sizeSource);
    long size = 2 + sizeHeader + sizeSource;
    char* code = (char*)malloc(size*sizeof(char));
    for (int c=0; c<size; c++) { code[c] = '\0'; }
    strcat(code, header);
    strcat(code, source);
    const char* constCode = code;
    free(header);
    free(source);

    // Compile the kernel file
    program = clCreateProgramWithSource(context, 1, &constCode, NULL, &err);
    checkError(err,__LINE__);
    err = clBuildProgram(program, 0, NULL, COMPILER_OPTIONS, NULL, NULL);

    // Check for compilation errors
    size_t logSize;
    err = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
    checkError(err,__LINE__);
    char* messages = (char*)malloc((1+logSize)*sizeof(char));
    err = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, logSize, messages, NULL);
    checkError(err,__LINE__);
    messages[logSize] = '\0';
    //if (logSize > 10) { printf("## Compiler message: %s\n", messages); }
    free(messages);

    // Retrieve the PTX code from the OpenCL compiler and output it to disk
    size_t binSize;
    err = clGetProgramInfo(program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t), &binSize, NULL);
    checkError(err,__LINE__);
    unsigned char *bin = (unsigned char *)malloc(binSize);
    err = clGetProgramInfo(program, CL_PROGRAM_BINARIES, sizeof(unsigned char *), &bin, NULL);
    checkError(err,__LINE__);
    FILE* file = fopen(CL_PTX_FILE, "wb");
    fwrite(bin, sizeof(char), binSize, file);
    fclose(file);
    free(bin);

    // Prepare OpenCL memory objects
    cl_mem bufA    = clCreateBuffer(context, CL_MEM_READ_ONLY,  M*K*sizeof(*A), NULL, &err);
    cl_mem bufB    = clCreateBuffer(context, CL_MEM_READ_ONLY,  K*N*sizeof(*B), NULL, &err);
    cl_mem bufB_TR = clCreateBuffer(context, CL_MEM_READ_ONLY,  N*K*sizeof(*B), NULL, &err);
    cl_mem bufC    = clCreateBuffer(context, CL_MEM_READ_WRITE, M*N*sizeof(*C), NULL, &err);
    checkError(err,__LINE__);

    // Copy matrices to the GPU (also C to erase the results of the previous run)
    err = clEnqueueWriteBuffer(queue, bufA, CL_TRUE, 0, M*K*sizeof(*A), A, 0, NULL, NULL);
    err = clEnqueueWriteBuffer(queue, bufB, CL_TRUE, 0, K*N*sizeof(*B), B, 0, NULL, NULL);
    err = clEnqueueWriteBuffer(queue, bufC, CL_TRUE, 0, M*N*sizeof(*C), C, 0, NULL, NULL);
    checkError(err,__LINE__);

    // Create extra objects for rounded-up sizes (only needed in case of myGEMM10)
    cl_mem bufA_XL    = clCreateBuffer(context, CL_MEM_READ_ONLY,  M_XL*K_XL*sizeof(*A), NULL, &err);
    cl_mem bufB_TR_XL = clCreateBuffer(context, CL_MEM_READ_ONLY,  N_XL*K_XL*sizeof(*B), NULL, &err);
    cl_mem bufC_XL    = clCreateBuffer(context, CL_MEM_READ_WRITE, M_XL*N_XL*sizeof(*C), NULL, &err);
    checkError(err,__LINE__);

    // Configure the myGEMM kernel
    char kernelname[100];
    sprintf(kernelname, "myGEMM%d", KERNEL);
    cl_kernel kernel1 = clCreateKernel(program, kernelname, &err);
    checkError(err,__LINE__);

    // Set the arguments of the myGEMM kernel
    #if KERNEL == 10
        err = clSetKernelArg(kernel1, 0, sizeof(int), (void*)&M_XL);
        err = clSetKernelArg(kernel1, 1, sizeof(int), (void*)&N_XL);
        err = clSetKernelArg(kernel1, 2, sizeof(int), (void*)&K_XL);
        err = clSetKernelArg(kernel1, 3, sizeof(cl_mem), (void*)&bufA_XL);
        err = clSetKernelArg(kernel1, 4, sizeof(cl_mem), (void*)&bufB_TR_XL);
        err = clSetKernelArg(kernel1, 5, sizeof(cl_mem), (void*)&bufC_XL);
    #else
        err = clSetKernelArg(kernel1, 0, sizeof(int), (void*)&M);
        err = clSetKernelArg(kernel1, 1, sizeof(int), (void*)&N);
        err = clSetKernelArg(kernel1, 2, sizeof(int), (void*)&K);
        err = clSetKernelArg(kernel1, 3, sizeof(cl_mem), (void*)&bufA);
        #if KERNEL == 5 || KERNEL == 6 || KERNEL == 7 || KERNEL == 8 || KERNEL == 9
            err = clSetKernelArg(kernel1, 4, sizeof(cl_mem), (void*)&bufB_TR);
        #else
            err = clSetKernelArg(kernel1, 4, sizeof(cl_mem), (void*)&bufB);
        #endif
        err = clSetKernelArg(kernel1, 5, sizeof(cl_mem), (void*)&bufC);
    #endif
    checkError(err,__LINE__);

    // Configure the supporting transpose kernel and set its arguments (only for certain myGEMMs)
    #if KERNEL == 5 || KERNEL == 6 || KERNEL == 7 || KERNEL == 8 || KERNEL == 9 || KERNEL == 10
        cl_kernel kernel2 = clCreateKernel(program, "transpose", &err);
        checkError(err,__LINE__);
        err = clSetKernelArg(kernel2, 0, sizeof(int), (void*)&K);
        err = clSetKernelArg(kernel2, 1, sizeof(int), (void*)&N);
        err = clSetKernelArg(kernel2, 2, sizeof(cl_mem), (void*)&bufB);
        err = clSetKernelArg(kernel2, 3, sizeof(cl_mem), (void*)&bufB_TR);
        checkError(err,__LINE__);
        const size_t tLocal[2] = { TRANSPOSEX, TRANSPOSEY };
        const size_t tGlobal[2] = { (size_t)K, (size_t)N };
    #endif

    // Configure the supporting padding kernels and set their arguments (only for myGEMM10)
    #if KERNEL == 10
        cl_kernel kernel3a = clCreateKernel(program, "paddingAddZeroes", &err);
        checkError(err,__LINE__);
        err = clSetKernelArg(kernel3a, 0, sizeof(int), (void*)&M);
        err = clSetKernelArg(kernel3a, 1, sizeof(int), (void*)&K);
        err = clSetKernelArg(kernel3a, 2, sizeof(cl_mem), (void*)&bufA);
        err = clSetKernelArg(kernel3a, 3, sizeof(int), (void*)&M_XL);
        err = clSetKernelArg(kernel3a, 4, sizeof(int), (void*)&K_XL);
        err = clSetKernelArg(kernel3a, 5, sizeof(cl_mem), (void*)&bufA_XL);
        checkError(err,__LINE__);
        cl_kernel kernel3b = clCreateKernel(program, "paddingAddZeroes", &err);
        checkError(err,__LINE__);
        err = clSetKernelArg(kernel3b, 0, sizeof(int), (void*)&N);
        err = clSetKernelArg(kernel3b, 1, sizeof(int), (void*)&K);
        err = clSetKernelArg(kernel3b, 2, sizeof(cl_mem), (void*)&bufB_TR);
        err = clSetKernelArg(kernel3b, 3, sizeof(int), (void*)&N_XL);
        err = clSetKernelArg(kernel3b, 4, sizeof(int), (void*)&K_XL);
        err = clSetKernelArg(kernel3b, 5, sizeof(cl_mem), (void*)&bufB_TR_XL);
        checkError(err,__LINE__);
        cl_kernel kernel3c = clCreateKernel(program, "paddingRemoveZeroes", &err);
        checkError(err,__LINE__);
        err = clSetKernelArg(kernel3c, 0, sizeof(int), (void*)&M_XL);
        err = clSetKernelArg(kernel3c, 1, sizeof(int), (void*)&N_XL);
        err = clSetKernelArg(kernel3c, 2, sizeof(cl_mem), (void*)&bufC_XL);
        err = clSetKernelArg(kernel3c, 3, sizeof(int), (void*)&M);
        err = clSetKernelArg(kernel3c, 4, sizeof(int), (void*)&N);
        err = clSetKernelArg(kernel3c, 5, sizeof(cl_mem), (void*)&bufC);
        checkError(err,__LINE__);
        const size_t pLocal[2] = { PADDINGX, PADDINGY };
        const size_t pAGlobal[2] = { (size_t)M_XL, (size_t)K_XL };
        const size_t pBGlobal[2] = { (size_t)N_XL, (size_t)K_XL };
        const size_t pCGlobal[2] = { (size_t)M, (size_t)N };
    #endif

    // Configure the thread/work-group dimensions of the myGEMM kernel
    #if KERNEL == 1 || KERNEL == 2
        const size_t local[2] = { TS, TS };
        const size_t global[2] = { (size_t)M, (size_t)N };
    #elif KERNEL == 3 || KERNEL == 5
        const size_t local[2] = { TS, TS/WPT };
        const size_t global[2] = { (size_t)M, (size_t)(N/WPT) };
    #elif KERNEL == 4
        const size_t local[2] = { TS/WIDTH, TS };
        const size_t global[2] = { (size_t)(M/WIDTH), (size_t)N };
    #elif KERNEL == 6 || KERNEL == 7 || KERNEL == 8 || KERNEL == 9
        const size_t local[2] = { TSM/WPTM, TSN/WPTN };
        const size_t global[2] = { (size_t)(M/WPTM), (size_t)(N/WPTN) };
    #elif KERNEL == 10
        const size_t local[2] = { TSM/WPTM, TSN/WPTN };
        const size_t global[2] = { (size_t)(M_XL/WPTM), (size_t)(N_XL/WPTN) };
    #elif KERNEL == 11
        const size_t local[2] = { THREADSX, THREADSY };
        const size_t global[2] = { (size_t)(M/RX), (size_t)(N/RY) };
    #endif

    // Start the timed loop
    double startTime = timer();
    for (int r=0; r<NUM_RUNS; r++) {

        // Run the transpose kernel first
        #if KERNEL == 5 || KERNEL == 6 || KERNEL == 7 || KERNEL == 8 || KERNEL == 9 || KERNEL == 10
            err = clEnqueueNDRangeKernel(queue, kernel2, 2, NULL, tGlobal, tLocal, 0, NULL, &event);
        #endif

        // Make the inputs extra large with padded zeros
        #if KERNEL == 10
            err = clEnqueueNDRangeKernel(queue, kernel3a, 2, NULL, pAGlobal, pLocal, 0, NULL, &event);
            err = clEnqueueNDRangeKernel(queue, kernel3b, 2, NULL, pBGlobal, pLocal, 0, NULL, &event);
        #endif

        // Run the myGEMM kernel
        err = clEnqueueNDRangeKernel(queue, kernel1, 2, NULL, global, local, 0, NULL, &event);

        // Remove padded zeroes from the larger output
        #if KERNEL == 10
            err = clEnqueueNDRangeKernel(queue, kernel3c, 2, NULL, pCGlobal, pLocal, 0, NULL, &event);
        #endif

        // Wait for calculations to be finished
        checkError(err,__LINE__);
        err = clWaitForEvents(1, &event);
    }

    // End the timed loop
    timers[timerID].t += (timer() - startTime) / (double)NUM_RUNS;
    timers[timerID].kf += ((long)K * (long)M * (long)N * 2) / 1000;

    // Copy the output matrix C back to the CPU memory
    err = clEnqueueReadBuffer(queue, bufC, CL_TRUE, 0, M*N*sizeof(*C), C, 0, NULL, NULL);
    checkError(err,__LINE__);

    // Free the memory objects
    free(code);
    clReleaseMemObject(bufA);
    clReleaseMemObject(bufB);
    clReleaseMemObject(bufB_TR);
    clReleaseMemObject(bufC);
    clReleaseMemObject(bufA_XL);
    clReleaseMemObject(bufB_TR_XL);
    clReleaseMemObject(bufC_XL);

    // Clean-up OpenCL
    clReleaseCommandQueue(queue);
    clReleaseContext(context);
    clReleaseProgram(program);
    clReleaseKernel(kernel1);
    #if KERNEL == 5 || KERNEL == 6 || KERNEL == 7 || KERNEL == 8 || KERNEL == 9 || KERNEL == 10
        clReleaseKernel(kernel2);
    #endif
    #if KERNEL == 10
        clReleaseKernel(kernel3a);
        clReleaseKernel(kernel3b);
        clReleaseKernel(kernel3c);
    #endif
}

// =================================================================================================

// Print an error message to screen (only if it occurs)
void checkError(cl_int error, int line) {
    if (error != CL_SUCCESS) {
        switch (error) {
            case CL_DEVICE_NOT_FOUND:                 printf("-- Error at %d:  Device not found.\n", line); break;
            case CL_DEVICE_NOT_AVAILABLE:             printf("-- Error at %d:  Device not available\n", line); break;
            case CL_COMPILER_NOT_AVAILABLE:           printf("-- Error at %d:  Compiler not available\n", line); break;
            case CL_MEM_OBJECT_ALLOCATION_FAILURE:    printf("-- Error at %d:  Memory object allocation failure\n", line); break;
            case CL_OUT_OF_RESOURCES:                 printf("-- Error at %d:  Out of resources\n", line); break;
            case CL_OUT_OF_HOST_MEMORY:               printf("-- Error at %d:  Out of host memory\n", line); break;
            case CL_PROFILING_INFO_NOT_AVAILABLE:     printf("-- Error at %d:  Profiling information not available\n", line); break;
            case CL_MEM_COPY_OVERLAP:                 printf("-- Error at %d:  Memory copy overlap\n", line); break;
            case CL_IMAGE_FORMAT_MISMATCH:            printf("-- Error at %d:  Image format mismatch\n", line); break;
            case CL_IMAGE_FORMAT_NOT_SUPPORTED:       printf("-- Error at %d:  Image format not supported\n", line); break;
            case CL_BUILD_PROGRAM_FAILURE:            printf("-- Error at %d:  Program build failure\n", line); break;
            case CL_MAP_FAILURE:                      printf("-- Error at %d:  Map failure\n", line); break;
            case CL_INVALID_VALUE:                    printf("-- Error at %d:  Invalid value\n", line); break;
            case CL_INVALID_DEVICE_TYPE:              printf("-- Error at %d:  Invalid device type\n", line); break;
            case CL_INVALID_PLATFORM:                 printf("-- Error at %d:  Invalid platform\n", line); break;
            case CL_INVALID_DEVICE:                   printf("-- Error at %d:  Invalid device\n", line); break;
            case CL_INVALID_CONTEXT:                  printf("-- Error at %d:  Invalid context\n", line); break;
            case CL_INVALID_QUEUE_PROPERTIES:         printf("-- Error at %d:  Invalid queue properties\n", line); break;
            case CL_INVALID_COMMAND_QUEUE:            printf("-- Error at %d:  Invalid command queue\n", line); break;
            case CL_INVALID_HOST_PTR:                 printf("-- Error at %d:  Invalid host pointer\n", line); break;
            case CL_INVALID_MEM_OBJECT:               printf("-- Error at %d:  Invalid memory object\n", line); break;
            case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:  printf("-- Error at %d:  Invalid image format descriptor\n", line); break;
            case CL_INVALID_IMAGE_SIZE:               printf("-- Error at %d:  Invalid image size\n", line); break;
            case CL_INVALID_SAMPLER:                  printf("-- Error at %d:  Invalid sampler\n", line); break;
            case CL_INVALID_BINARY:                   printf("-- Error at %d:  Invalid binary\n", line); break;
            case CL_INVALID_BUILD_OPTIONS:            printf("-- Error at %d:  Invalid build options\n", line); break;
            case CL_INVALID_PROGRAM:                  printf("-- Error at %d:  Invalid program\n", line); break;
            case CL_INVALID_PROGRAM_EXECUTABLE:       printf("-- Error at %d:  Invalid program executable\n", line); break;
            case CL_INVALID_KERNEL_NAME:              printf("-- Error at %d:  Invalid kernel name\n", line); break;
            case CL_INVALID_KERNEL_DEFINITION:        printf("-- Error at %d:  Invalid kernel definition\n", line); break;
            case CL_INVALID_KERNEL:                   printf("-- Error at %d:  Invalid kernel\n", line); break;
            case CL_INVALID_ARG_INDEX:                printf("-- Error at %d:  Invalid argument index\n", line); break;
            case CL_INVALID_ARG_VALUE:                printf("-- Error at %d:  Invalid argument value\n", line); break;
            case CL_INVALID_ARG_SIZE:                 printf("-- Error at %d:  Invalid argument size\n", line); break;
            case CL_INVALID_KERNEL_ARGS:              printf("-- Error at %d:  Invalid kernel arguments\n", line); break;
            case CL_INVALID_WORK_DIMENSION:           printf("-- Error at %d:  Invalid work dimensionsension\n", line); break;
            case CL_INVALID_WORK_GROUP_SIZE:          printf("-- Error at %d:  Invalid work group size\n", line); break;
            case CL_INVALID_WORK_ITEM_SIZE:           printf("-- Error at %d:  Invalid work item size\n", line); break;
            case CL_INVALID_GLOBAL_OFFSET:            printf("-- Error at %d:  Invalid global offset\n", line); break;
            case CL_INVALID_EVENT_WAIT_LIST:          printf("-- Error at %d:  Invalid event wait list\n", line); break;
            case CL_INVALID_EVENT:                    printf("-- Error at %d:  Invalid event\n", line); break;
            case CL_INVALID_OPERATION:                printf("-- Error at %d:  Invalid operation\n", line); break;
            case CL_INVALID_GL_OBJECT:                printf("-- Error at %d:  Invalid OpenGL object\n", line); break;
            case CL_INVALID_BUFFER_SIZE:              printf("-- Error at %d:  Invalid buffer size\n", line); break;
            case CL_INVALID_MIP_LEVEL:                printf("-- Error at %d:  Invalid mip-map level\n", line); break;
            case -1024:                               printf("-- Error at %d:  *clBLAS* Functionality is not implemented\n", line); break;
            case -1023:                               printf("-- Error at %d:  *clBLAS* Library is not initialized yet\n", line); break;
            case -1022:                               printf("-- Error at %d:  *clBLAS* Matrix A is not a valid memory object\n", line); break;
            case -1021:                               printf("-- Error at %d:  *clBLAS* Matrix B is not a valid memory object\n", line); break;
            case -1020:                               printf("-- Error at %d:  *clBLAS* Matrix C is not a valid memory object\n", line); break;
            case -1019:                               printf("-- Error at %d:  *clBLAS* Vector X is not a valid memory object\n", line); break;
            case -1018:                               printf("-- Error at %d:  *clBLAS* Vector Y is not a valid memory object\n", line); break;
            case -1017:                               printf("-- Error at %d:  *clBLAS* An input dimension (M,N,K) is invalid\n", line); break;
            case -1016:                               printf("-- Error at %d:  *clBLAS* Leading dimension A must not be less than the size of the first dimension\n", line); break;
            case -1015:                               printf("-- Error at %d:  *clBLAS* Leading dimension B must not be less than the size of the second dimension\n", line); break;
            case -1014:                               printf("-- Error at %d:  *clBLAS* Leading dimension C must not be less than the size of the third dimension\n", line); break;
            case -1013:                               printf("-- Error at %d:  *clBLAS* The increment for a vector X must not be 0\n", line); break;
            case -1012:                               printf("-- Error at %d:  *clBLAS* The increment for a vector Y must not be 0\n", line); break;
            case -1011:                               printf("-- Error at %d:  *clBLAS* The memory object for Matrix A is too small\n", line); break;
            case -1010:                               printf("-- Error at %d:  *clBLAS* The memory object for Matrix B is too small\n", line); break;
            case -1009:                               printf("-- Error at %d:  *clBLAS* The memory object for Matrix C is too small\n", line); break;
            case -1008:                               printf("-- Error at %d:  *clBLAS* The memory object for Vector X is too small\n", line); break;
            case -1007:                               printf("-- Error at %d:  *clBLAS* The memory object for Vector Y is too small\n", line); break;
            case -1001:                               printf("-- Error at %d:  Code -1001: no GPU available?\n", line); break;
            default:                                  printf("-- Error at %d:  Unknown with code %d\n", line, error);
        }
        exit(1);
    }
}

// =================================================================================================


text:
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Conreign.Client.Contracts;
using Conreign.Client.SignalR.Logging;
using Microsoft.AspNet.SignalR.Client;
using Polly;
using Polly.Retry;

namespace Conreign.Client.SignalR
{
    public class SignalRClient : IClient
    {
        private readonly RetryPolicy _connectionPolicy;
        private readonly ConcurrentDictionary<Guid, Task<IClientConnection>> _connections;
        private readonly SignalRClientOptions _options;

        public SignalRClient(SignalRClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            _options = options;
            _connections = new ConcurrentDictionary<Guid, Task<IClientConnection>>();
            _connectionPolicy =
                _connectionPolicy = Policy
                    .Handle<Exception>()
                    .WaitAndRetryAsync(5, attempt => TimeSpan.FromSeconds(attempt * 2));
        }

        public Task<IClientConnection> Connect(Guid connectionId)
        {
            return _connections.GetOrAdd(connectionId, async id =>
            {
                var hubConnection = new HubConnection(_options.ConnectionUri + "/$/api")
                {
                    TraceLevel = TraceLevels.All,
                    TraceWriter = new SerilogTextWriter(),
                    ConnectionId = connectionId.ToString()
                };
                var gameHub = hubConnection.CreateHubProxy("GameHub");
                try
                {
                    if (_options.IsDebug)
                    {
                        await hubConnection.Start();
                    }
                    else
                    {
                        var result = await _connectionPolicy.ExecuteAndCaptureAsync(hubConnection.Start);
                        if (result.Outcome == OutcomeType.Failure)
                        {
                            throw result.FinalException;
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new ConnectionException($"Failed to connect to the API: {ex.Message}", ex);
                }
                var connection = new SignalRClientConnection(hubConnection, gameHub);
                return connection;
            });
        }
    }
}


text:
{% extends "../outcome.html" %}

{% block content %}

    {{ govukPanel({
      titleText: "Fast-track this person",
      text: "Refer to decision maker",
      classes: "outcome"
    }) }}

Claimant status

Spouse of EEA Citizen

Evidence to record in the ALP

One of the following:

residence card – card number (right hand corner), nationality, place of issue, issue date, expiry date, permit type, remarks on the front and back of the card

passport – number, nationality, issue date, expiry date and visa status

national ID card – number, nationality, issue date and expiry date

If they have a residence card, you must record it in the ALP.

All of the following:

marriage or civil partnership certificate – both names, date of marriage and country of marriage

    {{ govukWarningText({
      text: "If the claimant cannot provide the necessary evidence, book an HRT interview.",
      iconFallbackText: "Important"
    }) }}

Go to the 'check if HRT interview is needed' to-do

For the question "Does the 'prove you can apply' service say 'this person has proved they can apply for Universal Credit'?", select 'No'.

Select the category 'Fast-track this person'.

Select 'Done'.

Complete the 'refer to decision maker (HRT)' to-do

Download the ALP.

Complete the appropriate section in the ALP using the necessary evidence.

Upload the ALP.

Enter the claimant's nationality.

Select 'Done'.

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;

namespace MessageIo.Tests
{
    [TestFixture]
    public class StreamTests
    {
        [TestCase(LengthPrefixStyle.Int8)]
        [TestCase(LengthPrefixStyle.UInt8)]
        [TestCase(LengthPrefixStyle.Int16)]
        [TestCase(LengthPrefixStyle.UInt16)]
        [TestCase(LengthPrefixStyle.Int32)]
        [TestCase(LengthPrefixStyle.UInt32)]
        [TestCase(LengthPrefixStyle.Int64)]
        [TestCase(LengthPrefixStyle.UInt64)]
        [TestCase(LengthPrefixStyle.Varint)]
        [TestCase(LengthPrefixStyle.UVarint)]
        public void TestReadWrite(LengthPrefixStyle lps)
        {
            using (var mem = new MemoryStream())
            using (var stream = new MessageStream(mem, true, lps))
            {
                SubtestReadWrite(stream, lps, () => stream?.Seek(0, SeekOrigin.Begin));
            }
        }

        private static void SubtestReadWrite(Stream stream, LengthPrefixStyle lps, Action reset)
        {
            var rand = new Random(Environment.TickCount);
            var msgs = Enumerable.Range(0, 64).Select(_ =>
            {
                var msg = new byte[ReaderWriterTests.GetMaxLength(lps, rand.Next(16, 1024))];
                rand.NextBytes(msg);
                return msg;
            }).ToList();

            msgs.ForEach(msg => stream.Write(msg, 0, msg.Length));

            reset();

            foreach (var msg in msgs)
            {
                var msg2 = new byte[msg.Length];
                stream.Read(msg2, 0, msg2.Length);

                Assert.That(msg2, Is.EqualTo(msg));
            }
        }

        [TestCase(LengthPrefixStyle.Int8)]
        [TestCase(LengthPrefixStyle.UInt8)]
        [TestCase(LengthPrefixStyle.Int16)]
        [TestCase(LengthPrefixStyle.UInt16)]
        [TestCase(LengthPrefixStyle.Int32)]
        [TestCase(LengthPrefixStyle.UInt32)]
        [TestCase(LengthPrefixStyle.Int64)]
        [TestCase(LengthPrefixStyle.UInt64)]
        [TestCase(LengthPrefixStyle.Varint)]
        [TestCase(LengthPrefixStyle.UVarint)]
        public async Task TestReadWriteAsync(LengthPrefixStyle lps)
        {
            using (var mem = new MemoryStream())
            using (var stream = new MessageStream(mem, true, lps))
            {
                await SubtestReadWriteAsync(stream, lps, () => stream?.Seek(0, SeekOrigin.Begin));
            }
        }

        private static async Task SubtestReadWriteAsync(Stream stream, LengthPrefixStyle lps, Action reset)
        {
            var rand = new Random(Environment.TickCount);
            var msgs = Enumerable.Range(0, 64).Select(_ =>
            {
                var msg = new byte[ReaderWriterTests.GetMaxLength(lps, rand.Next(16, 1024))];
                rand.NextBytes(msg);
                return msg;
            }).ToList();

            var tasks = msgs.Select(msg => stream.WriteAsync(msg, 0, msg.Length, CancellationToken.None));
            await Task.WhenAll(tasks);

            reset();

            foreach (var msg in msgs)
            {
                var msg2 = new byte[msg.Length];
                await stream.ReadAsync(msg2, 0, msg2.Length, CancellationToken.None);

                Assert.That(msg2, Is.EqualTo(msg));
            }
        }

        [TestCase(LengthPrefixStyle.Int8)]
        [TestCase(LengthPrefixStyle.UInt8)]
        [TestCase(LengthPrefixStyle.Int16)]
        [TestCase(LengthPrefixStyle.UInt16)]
        [TestCase(LengthPrefixStyle.Int32)]
        [TestCase(LengthPrefixStyle.UInt32)]
        [TestCase(LengthPrefixStyle.Int64)]
        [TestCase(LengthPrefixStyle.UInt64)]
        [TestCase(LengthPrefixStyle.Varint)]
        [TestCase(LengthPrefixStyle.UVarint)]
        public void TestReadWriteMessage(LengthPrefixStyle lps)
        {
            using (var mem = new MemoryStream())
            using (var stream = new MessageStream(mem, true, lps))
            {
                SubtestReadWriteMessage(stream, lps, () => stream?.Seek(0, SeekOrigin.Begin));
            }
        }

        private static void SubtestReadWriteMessage(MessageStream stream, LengthPrefixStyle lps, Action reset)
        {
            var rand = new Random(Environment.TickCount);
            var msgs = Enumerable.Range(0, 64).Select(_ =>
            {
                var msg = new byte[ReaderWriterTests.GetMaxLength(lps, rand.Next(16, 1024))];
                rand.NextBytes(msg);
                return msg;
            }).ToList();

            msgs.ForEach(stream.WriteMessage);

            reset();

            foreach (var msg in msgs)
            {
                var msg2 = stream.ReadMessage();

                Assert.That(msg2, Is.EqualTo(msg));
            }
        }

        [TestCase(LengthPrefixStyle.Int8)]
        [TestCase(LengthPrefixStyle.UInt8)]
        [TestCase(LengthPrefixStyle.Int16)]
        [TestCase(LengthPrefixStyle.UInt16)]
        [TestCase(LengthPrefixStyle.Int32)]
        [TestCase(LengthPrefixStyle.UInt32)]
        [TestCase(LengthPrefixStyle.Int64)]
        [TestCase(LengthPrefixStyle.UInt64)]
        [TestCase(LengthPrefixStyle.Varint)]
        [TestCase(LengthPrefixStyle.UVarint)]
        public async Task TestReadWriteMessageAsync(LengthPrefixStyle lps)
        {
            using (var mem = new MemoryStream())
            using (var stream = new MessageStream(mem, true, lps))
            {
                await SubtestReadWriteMessageAsync(stream, lps, () => stream?.Seek(0, SeekOrigin.Begin));
            }
        }

        private static async Task SubtestReadWriteMessageAsync(MessageStream stream, LengthPrefixStyle lps, Action reset)
        {
            var rand = new Random(Environment.TickCount);
            var msgs = Enumerable.Range(0, 64).Select(_ =>
            {
                var msg = new byte[ReaderWriterTests.GetMaxLength(lps, rand.Next(16, 1024))];
                rand.NextBytes(msg);
                return msg;
            }).ToList();

            var tasks = msgs.Select(msg => stream.WriteMessageAsync(msg, CancellationToken.None));
            await Task.WhenAll(tasks);

            reset();

            foreach (var msg in msgs)
            {
                var msg2 = await stream.ReadMessageAsync(CancellationToken.None);

                Assert.That(msg2, Is.EqualTo(msg));
            }
        }

        private static void MakeTcpStreamPair(out Stream aStream, out Stream bStream)
        {
            var listener = new TcpListener(IPAddress.Loopback, new Random(Environment.TickCount).Next(1024, 8192));
            listener.Start();
            var accept = listener.AcceptTcpClientAsync();
            var a = new TcpClient();
            a.ExclusiveAddressUse = false;
            a.NoDelay = true;
            a.Connect((IPEndPoint) listener.LocalEndpoint);
            var b = accept.Result;
            b.NoDelay = true;
            listener.Stop();

            aStream = a.GetStream();
            bStream = b.GetStream();
        }

        [TestCase(LengthPrefixStyle.Int8)]
        [TestCase(LengthPrefixStyle.UInt8)]
        [TestCase(LengthPrefixStyle.Int16)]
        [TestCase(LengthPrefixStyle.UInt16)]
        [TestCase(LengthPrefixStyle.Int32)]
        [TestCase(LengthPrefixStyle.UInt32)]
        [TestCase(LengthPrefixStyle.Int64)]
        [TestCase(LengthPrefixStyle.UInt64)]
        [TestCase(LengthPrefixStyle.Varint)]
        [TestCase(LengthPrefixStyle.UVarint)]
        public void CombineStreamPair_TestReadWriteMessage(LengthPrefixStyle lps)
        {
            Stream a = null, b = null;
            try
            {
                MakeTcpStreamPair(out a, out b);
                using (var stream = MessageStream.Combine(new MessageReader(a, true, lps), new MessageWriter(b, true, lps)))
                {
                    SubtestReadWriteMessage(stream, lps, () => {});
                }
            }
            finally
            {
                a?.Dispose();
                b?.Dispose();
            }
        }
    }
}


text:
// Copyright 2007, 2010 The Apache Software Foundation
//
// 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.

package org.apache.tapestry5.ioc.services;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Used to disambiguate which version of {@link SymbolProvider} is being referenced. Contributions to the
 * ApplicationDefaults symbol source are overridden by JVM System properties.
 *
 * @see FactoryDefaults
 */
@Target(
{ PARAMETER, FIELD, METHOD })
@Retention(RUNTIME)
@Documented
public @interface ApplicationDefaults
{

}


text:
'use strict';
/**
 * @ngdoc overview
 * @name freeCodeLondonersCampApp
 * @description
 * # freeCodeLondonersCampApp
 *
 * Main module of the application.
 */
module.exports = function router($routeProvider) {
  $routeProvider
    .when('/', {
      template: require('./main/main.html'),
      controller: 'mainC'
    })
    .when('/campers', {
      template: require('./campers/campers.html'),
      controller: 'campersC'
    })
    .otherwise({
      redirectTo: '/'
    });
};


text:
<?php

namespace AntiMattr\ETL\Load\MySQL;

use AntiMattr\ETL\Exception\LoadException;
use AntiMattr\ETL\Exception\LoadNoDataException;
use AntiMattr\ETL\Load\LoaderInterface;
use AntiMattr\ETL\Load\LoaderTrait;
use AntiMattr\ETL\Load\PDO\PDOStatement;

/**
 * @author Matthew Fitzgerald <matthewfitz@gmail.com>
 */
class MySQLInsertIntoLoader implements LoaderInterface
{
    use LoaderTrait;

    /** @var \PDO */
    protected $connection;

    /** @var string */
    protected $table;

    public function __construct(\PDO $connection, $table)
    {
        $this->connection = $connection;
        $this->table = $table;
    }

    /**
     * @param array $transformed
     *
     * @throws \AntiMattr\ETL\Exception\LoadException
     */
    public function load(array $transformed = [])
    {
        if (empty($transformed)) {
            throw new LoadNoDataException("Error - No data to load");
        }

        $properties = [];
        $values = [];

        $transformations = $this->task->getTransformations();

        foreach ($transformations as $transformation) {
            $properties[$transformation->name] = null;
        }

        $columns = implode(', ', array_keys($properties));
        $questionMarks = array_fill(0, count($properties), '?');
        $valuePlaceholders = array_fill(0, count($transformed), '(' . implode(',', $questionMarks) . ')');

        foreach ($transformed as $row) {
            $value = array_merge($properties, $row);
            $values = array_merge($values, array_values($value));
        }

        $sql = sprintf(
            "INSERT INTO %s (%s) VALUES %s",
            $this->table,
            $columns,
            implode(',', $valuePlaceholders)
        );

        $this->connection->beginTransaction();
        try {
            $statement = $this->connection->prepare($sql);
            $statement->execute($values);
            $this->connection->commit();
        } catch (\PDOException $e){
            try {
                $this->connection->rollBack();
            } catch (\Exception $rollback) {

            }

            $query = $statement->queryString;
            if ($statement instanceof PDOStatement) {
                $query = $statement->getDebugQuery();
            }

            $message = sprintf(
                "Error: %s Query: %s",
                $e->getMessage(),
                $query
            );

            throw new LoadException($message);
        }

        $dataContext = $this->task->getDataContext();
        $dataContext->setLoadedCount($statement->rowCount());
    }
}


text:
layout: event
title: "#31: MLDublin meets Criteo @ Huckletree D2"
date: 2018-11-26 12:00
categories: meeting report
tags: [["2018"]]
talks:
- speaker: Flavian Vasile
  job: Research Lead, Criteo
  linkedin: flavianv
  title: Causal embeddings for recommendation
  description: Falvian presented his work which was submitted to RecSys 2018 and won a best paper award for best long paper.
  links:
  - sides: /assets/slides/meetup_31/CausalMF.RecSys.pdf
- speaker: Hossein Javidnia
  job: Postdoctoral Researcher, ADAPT Centre, TCD
  linkedin: hossein-javidnia-09794ab8
  title: "Learning to See in 3D: From Lidar to Synthetic Data Generation"
  description: "Our world is dynamic and three-dimensional. Understanding the 3D layout of scenes and the motion of objects is crucial for successfully operating in such an environment. This talk will cover two lines of recent research in this direction: End-to-End learning of motion and 3D structure and exploring the synthetic depth/3D data generation platforms."
  links:
  - sides: https://drive.google.com/open?id=1CDCzMQzWB06BZM-b10BTZ9Wa3xB-FCk7
  - sides (smaller without videos): /assets/slides/meetup_31/Pres_WithoutVideo.pdf
- speaker: Dimitar Shterionov
  job: Postdoctoral Researcher, ADAPT Centre, DCU
  linkedin: dimitar-shterionov-4a5b0b1a
  title: Encoder-decoder, Machine Translation and More
  description: "The encoder-decoder architecture has facilitated Neural Machine Translation. For NMT an input sentence is encoded into a context vector via an RNN -- the last hidden state represents the context. Consecutively this context is used in a decoder RNN to compute the target sentence. While recent advances have lead to the development of the multi-headed attention architecture (known as the transformer), RNN-based encoder-decoder models are still widely used not only in MT but in other related tasks.
This talk covered basic and advanced encoder-decoder architectures for MT along with available implementations and will investigate which other tasks can be solved with the same or similar architectures together with the extra requirements that are imposed by these tasks. Among them are the tasks of automatic post-editing, translation quality estimation and others."
  links:
  - sides: /assets/slides/meetup_31/ML_meetup_dshterionov_26112018.pdf
---

We're joined by Diarmuid and the some of the team from Criteo AI Lab.


text:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1;
    }
}


text:
from flask import Flask
from flask_apidoc import ApiDoc

app = Flask(__name__)
doc = ApiDoc(app=app)

@app.route('/users', methods=['POST'])
def add_user():
    """
    @api {post} /user Adds a new User
    @apiVersion 1.0.0
    @apiName add_user
    @apiGroup User

    @apiParam {String}      username        The user's username.
    @apiParam {String}      first_name      The first name of the User.
    @apiParam {String}      last_name       the last name of the User.
    @apiParam {Object}      profile         The profile data
    @apiParam {Number}      profile.age     The user's age.
    @apiParam {String}      profile.image   The user's avatar-image.

    @apiSuccess {Number}    id              The new user id.
    """
    return

@app.route('/users/<id>')
def get_user(id):
    """
    @api {get} /users/:id Gets an user
    @apiVersion 1.0.0
    @apiName get_user
    @apiGroup User

    @apiDescription Gets an user for the given id.

    @apiExample Example usage:
    curl -i http://localhost/users/4711

    @apiParam {Number}      id              The user's i

    @apiSuccess {Number}    id              The user's id.
    @apiSuccess {String}    username        The user's username.
    @apiSuccess {String}    first_name      The first name of the User.
    @apiSuccess {String}    last_name       The last name of the User.
    @apiSuccess {Object}    profile         The profile data
    @apiSuccess {Number}    profile.age     The user's age.
    @apiSuccess {String}    profile.image   The user's avatar-image.

    @apiError UserNotFound      The id of the User was not found.
    """
    return

@app.route('/users')
def get_users():
    """
    @api {get} /users/:id Gets all the users
    @apiVersion 1.0.0
    @apiName get_users
    @apiGroup User

    @apiExample Example usage:
    curl -i http://localhost/users

    @apiSuccess {Object}    users                 The user data
    @apiSuccess {Number}    users.id              The user's id.
    @apiSuccess {String}    users.username        The user's username.
    @apiSuccess {String}    users.first_name      The first name of the User.
    @apiSuccess {String}    users.last_name       The last name of the User.
    @apiSuccess {Object}    users.profile         The profile data
    @apiSuccess {Number}    users.profile.age     The user's age.
    @apiSuccess {String}    users.profile.image   The user's avatar-image.
    """
    return

@app.route('/users/<id>', methods=['POST'])
def update_user():
    """
    @api {post} /users/:id Updates a user
    @apiVersion 1.0.0
    @apiName update_user
    @apiGroup User

    @apiParam {Number}    id              The user's id
    @apiParam {String}    first_name      The first name of the User.
    @apiParam {String}    last_name       The last name of the User.
    """
    return


text:
console.log("Loading client-side JS...");
var socket = io('http://catarse-live.herokuapp.com');
socket.on('connected', function (data) {
  console.log('Connected to websocket');
});

var statApp = document.getElementById('statistics');
m.mount(statApp, m.component(c.pages.LiveStatistics, {socket: socket}));


text:
<?php

session_start();
$seleccionada = $_SESSION['seleccionada'];
$user_id = $_SESSION['user_id'];
$respuesta = $_POST['respuesta'];
$conjunto = $_SESSION['conjunto'];
$respuesta = trim($respuesta);
$conjunto = trim($conjunto);

$conn = new PDO('mysql:host=localhost; dbname=estudiaresfacil;charset=utf8', 'estudiaresfacil' , 'UPChack2016');
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$stmt = $conn ->prepare("SELECT correct FROM preguntas WHERE id = :seleccionada");
$stmt->bindValue(':seleccionada', $seleccionada);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$correct = $result["correct"];
}
catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}

$correct = trim($correct);

if($correct == $respuesta){

  $stmt = $conn->prepare("INSERT INTO respondidas(id, pregunta , conjunto , alumno , respuesta) VALUES (NULL , :pregunta , :conjunto , :alumno , '1')");
      $stmt->bindValue(':pregunta', $seleccionada);
      $stmt->bindValue(':conjunto', $conjunto);
      $stmt->bindValue(':alumno', $user_id);

  $stmt->execute();
//$respuesta2 = array(1,"$correct");
echo $correct;
}
else{
  $stmt = $conn->prepare("INSERT INTO respondidas(id, pregunta , conjunto , alumno , respuesta) VALUES (NULL , :pregunta , :conjunto , :alumno , '2')");
      $stmt->bindValue(':pregunta', $seleccionada);
      $stmt->bindValue(':conjunto', $conjunto);
      $stmt->bindValue(':alumno', $user_id);

  $stmt->execute();
//$respuesta2 = array(0,"$correct");
echo $correct;
}

?>