text:
#include "pch.h"
#include <utility>
#include <algorithm>
#include "ClientControl.xaml.h"
#include "Factory.h"
#include "TalkHelper.h"

using namespace ot;

using namespace Concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

std::atomic<int> ClientControl::_clientPort{ TalkConsts::DEF_CLIENT_PORT_INIT };

ClientControl::ClientControl()
{
    InitializeComponent();

    ServerPort->Text = DEF_SERVER_PORT.ToString();
    auto clientPort = _clientPort.load();
    ClientPort->Text = clientPort.ToString();
}

void
ClientControl::Init(
    IAsyncThreadNotify^  notify,
    IMainPageUIElements^ mainPageUIElements)
{
    _notify = std::move(notify);
    _mainPageUIElements = std::move(mainPageUIElements);
}

void
ClientControl::ProtocolChanged(
    Protocol protocol)
{
    _protocol = protocol;
}

void
ClientControl::Connect_Click(
    Object^          sender,
    RoutedEventArgs^ e)
{
    try
    {
        auto clientArgs = ref new ClientArgs();

        auto serverIP = ServerIP->Text;
        if (serverIP->IsEmpty())
        {
            throw Exception::CreateException(E_INVALIDARG, "No Server IP");
        }

        // check valid chars of Ipv6 Address
        if (!TalkHelper::AllValidIpv6Chars(serverIP->Data(), serverIP->Data() + serverIP->Length()))
        {
            throw Exception::CreateException(E_INVALIDARG, "Not a valid Server IPv6 address");
        }

        clientArgs->ServerHostName = ref new HostName(serverIP);

        if (ServerPort->Text->IsEmpty())
        {
            throw Exception::CreateException(E_INVALIDARG, "No Server Port");
        }
        clientArgs->ServerPort = ServerPort->Text;

        auto clientIP = ClientIP->Text;
        if (clientIP->IsEmpty())
        {
            throw Exception::CreateException(E_INVALIDARG, "No Client IP");
        }

        // check valid chars of Ipv6 Address
        if (!TalkHelper::AllValidIpv6Chars(clientIP->Data(), clientIP->Data() + clientIP->Length()))
        {
            throw Exception::CreateException(E_INVALIDARG, "Not a valid client IPv6 address");
        }

        clientArgs->ClientHostName = ref new HostName(clientIP);

        if (ClientPort->Text->IsEmpty())
        {
            throw Exception::CreateException(E_INVALIDARG, "No Client Port");
        }
        clientArgs->ClientPort = ClientPort->Text;

        auto cleintContext = Factory::CreateClientContext(_notify, clientArgs, _protocol);
        cleintContext->Connect_Click(sender, e);

        // fix Only usage of each socket address (protocol/network address/port)
        // is normally permitted.
        auto clientPort = ++_clientPort;
        ClientPort->Text = clientPort.ToString();
    }
    catch (Exception^ ex)
    {
        _notify->NotifyFromAsyncThread(
            "Connecting failed with input error: " + ex->Message,
            NotifyType::Error);
    }
}

void
ClientControl::Send_Click(
    Object^          sender,
    RoutedEventArgs^ e)
{
    try
    {
        auto input = Input->Text;
        if (input->IsEmpty())
        {
            throw Exception::CreateException(E_INVALIDARG, "No Input");
        }

        if (!CoreApplication::Properties->HasKey("clientContext"))
        {
            throw Exception::CreateException(E_UNEXPECTED, "Not Connected");
        }

        auto clientContext = dynamic_cast<IClientContext^>(
            CoreApplication::Properties->Lookup("clientContext"));
        if (clientContext == nullptr)
        {
            throw Exception::CreateException(E_UNEXPECTED, "No clientContext");
        }

        clientContext->Send_Click(sender, e, input);
    }
    catch (Exception^ ex)
    {
        _notify->NotifyFromAsyncThread(
            "Sending message failed with error: " + ex->Message,
            NotifyType::Error);
    }
}

void
ClientControl::Exit_Click(
    Object^          sender,
    RoutedEventArgs^ e)
{
    _mainPageUIElements->TalkGrid->Visibility = Xaml::Visibility::Collapsed;
    _mainPageUIElements->ThreadGrid->Visibility = Xaml::Visibility::Visible;
}


text:
package cn.gavinliu.notificationbox.widget;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

/**
 * Created by Gavin on 16-10-17.
 */

public abstract class BaseFragment extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getArguments(getArguments());
        setupActionBar(((AppCompatActivity) getActivity()).getSupportActionBar());
    }

    public void getArguments(Bundle bundle) {

    }

    public void setupActionBar(ActionBar actionBar) {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import { render } from 'react-dom';
import './index.css';
import App from './components/App';

render(
    <App />,
    document.getElementById('App')
);


text:
module Main where

import Lib

main :: IO ()
main = do
  num <- getLine
  print $ listAnswers . read $ num


text:
import {
  Mesh,
  PlaneBufferGeometry,
  PlaneGeometry
} from 'three';

import {PlaneMesh, ClothMesh} from '../../physics/index.js';

import {Component} from '../../core/Component';
import {MeshComponent} from '../../core/MeshComponent';
import {PhysicsComponent} from '../../core/PhysicsComponent';
import {SoftbodyComponent} from '../../core/SoftbodyComponent';
import {loadMaterial} from '../../utils/index';

@SoftbodyComponent
@PhysicsComponent
@MeshComponent
class Plane extends Component {
  static defaults = {
    ...Component.defaults,
    geometry: {
      width: 10,
      height: 10,
      wSegments: 32,
      hSegments: 32
    }
  };

  static instructions = {
    ...Component.instructions,
    geometry: ['width', 'height', 'wSegments', 'hSegments']
  };

  constructor(params = {}) {
    super(params, Plane.defaults, Plane.instructions);

    if (params.build) {
      this.build(params);
      super.wrap();
    }
  }

  build(params = {}) {
    const material = loadMaterial(params.material);

    let MeshNative;

    if (this.physics && this.params.softbody) MeshNative = ClothMesh;
    else if (this.physics) MeshNative = PlaneMesh;
    else MeshNative = Mesh;

    return new Promise((resolve) => {
      this.native = new MeshNative(
        this.buildGeometry(params),
        material,
        this.params
      );

      resolve();
    });
  }

  buildGeometry(params = {}) {
    const GConstruct = params.buffer || params.softbody ? PlaneBufferGeometry : PlaneGeometry;

    const geometry = new GConstruct(
      params.geometry.width,
      params.geometry.height,
      params.geometry.wSegments,
      params.geometry.hSegments
    );

    if (params.softbody) this.proccessSoftbodyGeometry(geometry);

    return geometry;
  }

  set g_width(val) {
    this._native.geometry = this.buildGeometry(this.updateParams({geometry: {width: val}}));
  }

  get g_width() {
    return this._native.geometry.parameters.width;
  }

  set g_height(val) {
    this._native.geometry = this.buildGeometry(this.updateParams({geometry: {height: val}}));
  }

  get g_height() {
    return this._native.geometry.parameters.height;
  }

  set g_segments(val) {
    this._native.geometry = this.buildGeometry(this.updateParams({geometry: {segments: val}}));
  }

  get g_segments() {
    return this._native.geometry.parameters.segments;
  }

  clone() {
    return new Plane({build: false}).copy(this);
  }
}

export {
  Plane
};


text:
require_relative 'pesel_inspector'
require_relative 'string'
require_relative 'fixnum'
require_relative 'p_parser'
# Core file
module PeselParser
  def self.root
    File.dirname __dir__
  end
end


text:
<?php
/**
 * @file
 * Crontab cron job scheduler for Ultimate Cron.
 */

/**
 * Crontab scheduler.
 */
class UltimateCronCrontabScheduler extends UltimateCronScheduler {
  /**
   * Default settings.
   */
  public function defaultSettings() {
    return array(
      'rules' => array('*/10+@ * * * *'),
      'catch_up' => '86400',
    );
  }

  /**
   * Label for schedule.
   */
  public function formatLabel($job) {
    $settings = $job->getSettings($this->type);
    return implode("\n", $settings['rules']);
  }

  /**
   * Label for schedule.
   */
  public function formatLabelVerbose($job) {
    $settings = $job->getSettings($this->type);

    $parsed = '';
    $next_schedule = NULL;
    $time = REQUEST_TIME;
    $skew = $this->getSkew($job);
    foreach ($settings['rules'] as $rule) {
      $cron = CronRule::factory($rule, $time, $skew);
      $parsed .= $cron->parseRule() . "\n";
      $result = $cron->getNextSchedule();
      $next_schedule = is_null($next_schedule) || $next_schedule > $result ? $result : $next_schedule;
      $result = $cron->getLastSchedule();
      if ($time < $result + $settings['catch_up']) {
        $result = floor($time / 60) * 60 + 60;
        $next_schedule = $next_schedule > $result ? $result : $next_schedule;
      }
    }
    $parsed .= t('Next scheduled run at @datetime', array(
      '@datetime' => format_date($next_schedule, 'custom', 'Y-m-d H:i:s'),
    ));
    return $parsed;
  }

  /**
   * Settings form for the crontab scheduler.
   */
  public function settingsForm(&$form, &$form_state, $job = NULL) {
    $elements = &$form['settings'][$this->type][$this->name];
    $values = &$form_state['values']['settings'][$this->type][$this->name];

    $rules = is_array($values['rules']) ? implode(',', $values['rules']) : '';

    $elements['rules'] = array(
      '#title' => t("Rules"),
      '#type' => 'textfield',
      '#default_value' => $rules,
      '#description' => t('Comma separated list of crontab rules.'),
      '#fallback' => TRUE,
      '#required' => TRUE,
      '#element_validate' => array('ultimate_cron_plugin_crontab_element_validate_rule'),
    );
    $elements['rules_help'] = array(
      '#type' => 'fieldset',
      '#title' => t('Rules help'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    $elements['rules_help']['info'] = array(
      '#markup' => file_get_contents(drupal_get_path('module', 'ultimate_cron') . '/help/rules.html'),
    );
    $elements['catch_up'] = array(
      '#title' => t("Catch up"),
      '#type' => 'textfield',
      '#default_value' => $values['catch_up'],
      '#description' => t("Don't run job after X seconds of rule."),
      '#fallback' => TRUE,
      '#required' => TRUE,
    );
  }

  /**
   * Submit handler.
   */
  public function settingsFormSubmit(&$form, &$form_state, $job = NULL) {
    $values = &$form_state['values']['settings'][$this->type][$this->name];

    if (!empty($values['rules'])) {
      $rules = explode(',', $values['rules']);
      $values['rules'] = array_map('trim', $rules);
    }
  }

  /**
   * Schedule handler.
   */
  public function isScheduled($job) {
    $settings = $job->getSettings($this->type);
    $log_entry = isset($job->log_entry) ? $job->log_entry : $job->loadLatestLogEntry();
    $skew = $this->getSkew($job);
    $class = get_class($this);
    return $class::shouldRun($settings['rules'], $log_entry->start_time, NULL, $settings['catch_up'], $skew) ? TRUE : FALSE;
  }

  /**
   * Check crontab rules against times.
   */
  static public function shouldRun($rules, $job_last_ran, $time = NULL, $catch_up = 0, $skew = 0) {
    $time = is_null($time) ? time() : $time;
    foreach ($rules as $rule) {
      $cron = CronRule::factory($rule, $time, $skew);
      $cron_last_ran = $cron->getLastSchedule();

      if ($job_last_ran < $cron_last_ran && $cron_last_ran <= $time) {
        if ($time <= $cron_last_ran + $catch_up) {
          return $time - $job_last_ran;
        }
      }
    }
    return FALSE;
  }

  /**
   * Determine if job is behind schedule.
   */
  public function isBehind($job) {
    // Disabled jobs are not behind!
    if (!empty($job->disabled)) {
      return FALSE;
    }

    $log_entry = isset($job->log_entry) ? $job->log_entry : $job->loadLatestLogEntry();
    // If job hasn't run yet, then who are we to say it's behind its schedule?
    // Check the registered time, and use that if it's available.
    $job_last_ran = $log_entry->start_time;
    if (!$job_last_ran) {
      $registered = variable_get('ultimate_cron_hooks_registered', array());
      if (empty($registered[$job->name])) {
        return FALSE;
      }
      $job_last_ran = $registered[$job->name];
    }

    $settings = $job->getSettings($this->type);

    $skew = $this->getSkew($job);
    $next_schedule = NULL;
    foreach ($settings['rules'] as $rule) {
      $cron = CronRule::factory($rule, $job_last_ran, $skew);
      $time = $cron->getNextSchedule();
      $next_schedule = is_null($next_schedule) || $time < $next_schedule ? $time : $next_schedule;
    }
    $behind = REQUEST_TIME - $next_schedule;

    return $behind > $settings['catch_up'] ? $behind : FALSE;
  }

  /**
   * Get a "unique" skew for a job.
   */
  protected function getSkew($job) {
    return $job->getUniqueID() & 0xff;
  }
}


text:
#include <linux/time.h>
#include <linux/errno.h>
#include <linux/stat.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mm.h>
#include <asm/uaccess.h>
#include <asm/byteorder.h>
#include <linux/smp_lock.h>

#include <linux/ncp_fs.h>

#include "ncplib_kernel.h"

static void ncp_read_volume_list(struct file *, void *, filldir_t,
				struct ncp_cache_control *);
static void ncp_do_readdir(struct file *, void *, filldir_t,
				struct ncp_cache_control *);

static int ncp_readdir(struct file *, void *, filldir_t);

static int ncp_create(struct inode *, struct dentry *, int, struct nameidata *);
static struct dentry *ncp_lookup(struct inode *, struct dentry *, struct nameidata *);
static int ncp_unlink(struct inode *, struct dentry *);
static int ncp_mkdir(struct inode *, struct dentry *, int, void *);
static int ncp_rmdir(struct inode *, struct dentry *);
static int ncp_rename(struct inode *, struct dentry *,
	  	      struct inode *, struct dentry *);
static int ncp_mknod(struct inode * dir, struct dentry *dentry,
		     int mode, dev_t rdev, void *label);
#if defined(CONFIG_NCPFS_EXTRAS) || defined(CONFIG_NCPFS_NFS_NS)
extern int ncp_symlink(struct inode *, struct dentry *, const char *);
#else
#define ncp_symlink NULL
#endif

const struct file_operations ncp_dir_operations =
{
	.read		= generic_read_dir,
	.readdir	= ncp_readdir,
	.ioctl		= ncp_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl	= ncp_compat_ioctl,
#endif
};

const struct inode_operations ncp_dir_inode_operations =
{
	.create		= ncp_create,
	.lookup		= ncp_lookup,
	.unlink		= ncp_unlink,
	.symlink	= ncp_symlink,
	.mkdir		= ncp_mkdir,
	.rmdir		= ncp_rmdir,
	.mknod		= ncp_mknod,
	.rename		= ncp_rename,
	.setattr	= ncp_notify_change,
};

/*
 * Dentry operations routines
 */
static int ncp_lookup_validate(struct dentry *, struct nameidata *);
static int ncp_hash_dentry(struct dentry *, struct qstr *);
static int ncp_compare_dentry (struct dentry *, struct qstr *, struct qstr *);
static int ncp_delete_dentry(struct dentry *);

static struct dentry_operations ncp_dentry_operations =
{
	.d_revalidate	= ncp_lookup_validate,
	.d_hash		= ncp_hash_dentry,
	.d_compare	= ncp_compare_dentry,
	.d_delete	= ncp_delete_dentry,
};

struct dentry_operations ncp_root_dentry_operations =
{
	.d_hash		= ncp_hash_dentry,
	.d_compare	= ncp_compare_dentry,
	.d_delete	= ncp_delete_dentry,
};

/*
 * Note: leave the hash unchanged if the directory
 * is case-sensitive.
 */
static int
ncp_hash_dentry(struct dentry *dentry, struct qstr *this)
{
	struct nls_table *t;
	unsigned long hash;
	int i;

	t = NCP_IO_TABLE(dentry);

	if (!ncp_case_sensitive(dentry->d_inode)) {
		hash = init_name_hash();
		for (i=0; i<this->len ; i++)
			hash = partial_name_hash(ncp_tolower(t, this->name[i]),
									hash);
		this->hash = end_name_hash(hash);
	}
	return 0;
}

static int
ncp_compare_dentry(struct dentry *dentry, struct qstr *a, struct qstr *b)
{
	if (a->len != b->len)
		return 1;

	if (ncp_case_sensitive(dentry->d_inode))
		return strncmp(a->name, b->name, a->len);

	return ncp_strnicmp(NCP_IO_TABLE(dentry), a->name, b->name, a->len);
}

/*
 * This is the callback from dput() when d_count is going to 0.
 * We use this to unhash dentries with bad inodes.
 * Closing files can be safely postponed until iput() - it's done there anyway.
 */
static int
ncp_delete_dentry(struct dentry * dentry)
{
	struct inode *inode = dentry->d_inode;

	if (inode) {
		if (is_bad_inode(inode))
			return 1;
	} else
	{
	/* N.B. Unhash negative dentries? */
	}
	return 0;
}

static inline int
ncp_single_volume(struct ncp_server *server)
{
	return (server->m.mounted_vol[0] != '\0');
}

static inline int ncp_is_server_root(struct inode *inode)
{
	return (!ncp_single_volume(NCP_SERVER(inode)) &&
		inode == inode->i_sb->s_root->d_inode);
}

/*
 * This is the callback when the dcache has a lookup hit.
 */

#ifdef CONFIG_NCPFS_STRONG
/* try to delete a readonly file (NW R bit set) */

static int
ncp_force_unlink(struct inode *dir, struct dentry* dentry)
{
        int res=0x9c,res2;
	struct nw_modify_dos_info info;
	__le32 old_nwattr;
	struct inode *inode;

	memset(&info, 0, sizeof(info));

        /* remove the Read-Only flag on the NW server */
	inode = dentry->d_inode;

	old_nwattr = NCP_FINFO(inode)->nwattr;
	info.attributes = old_nwattr & ~(aRONLY|aDELETEINHIBIT|aRENAMEINHIBIT);
	res2 = ncp_modify_file_or_subdir_dos_info_path(NCP_SERVER(inode), inode, NULL, DM_ATTRIBUTES, &info);
	if (res2)
		goto leave_me;

        /* now try again the delete operation */
        res = ncp_del_file_or_subdir2(NCP_SERVER(dir), dentry);

        if (res)  /* delete failed, set R bit again */
        {
		info.attributes = old_nwattr;
		res2 = ncp_modify_file_or_subdir_dos_info_path(NCP_SERVER(inode), inode, NULL, DM_ATTRIBUTES, &info);
		if (res2)
                        goto leave_me;
        }
leave_me:
        return(res);
}
#endif	/* CONFIG_NCPFS_STRONG */

#ifdef CONFIG_NCPFS_STRONG
static int
ncp_force_rename(struct inode *old_dir, struct dentry* old_dentry, char *_old_name,
                 struct inode *new_dir, struct dentry* new_dentry, char *_new_name)
{
	struct nw_modify_dos_info info;
        int res=0x90,res2;
	struct inode *old_inode = old_dentry->d_inode;
	__le32 old_nwattr = NCP_FINFO(old_inode)->nwattr;
	__le32 new_nwattr = 0; /* shut compiler warning */
	int old_nwattr_changed = 0;
	int new_nwattr_changed = 0;

	memset(&info, 0, sizeof(info));

        /* remove the Read-Only flag on the NW server */

	info.attributes = old_nwattr & ~(aRONLY|aRENAMEINHIBIT|aDELETEINHIBIT);
	res2 = ncp_modify_file_or_subdir_dos_info_path(NCP_SERVER(old_inode), old_inode, NULL, DM_ATTRIBUTES, &info);
	if (!res2)
		old_nwattr_changed = 1;
	if (new_dentry && new_dentry->d_inode) {
		new_nwattr = NCP_FINFO(new_dentry->d_inode)->nwattr;
		info.attributes = new_nwattr & ~(aRONLY|aRENAMEINHIBIT|aDELETEINHIBIT);
		res2 = ncp_modify_file_or_subdir_dos_info_path(NCP_SERVER(new_dir), new_dir, _new_name, DM_ATTRIBUTES, &info);
		if (!res2)
			new_nwattr_changed = 1;
	}
        /* now try again the rename operation */
	/* but only if something really happened */
	if (new_nwattr_changed || old_nwattr_changed) {
	        res = ncp_ren_or_mov_file_or_subdir(NCP_SERVER(old_dir),
        	                                    old_dir, _old_name,
                	                            new_dir, _new_name);
	}
	if (res)
		goto leave_me;
	/* file was successfully renamed, so:
	   do not set attributes on old file - it no longer exists
	   copy attributes from old file to new */
	new_nwattr_changed = old_nwattr_changed;
	new_nwattr = old_nwattr;
	old_nwattr_changed = 0;

leave_me:;
	if (old_nwattr_changed) {
		info.attributes = old_nwattr;
		res2 = ncp_modify_file_or_subdir_dos_info_path(NCP_SERVER(old_inode), old_inode, NULL, DM_ATTRIBUTES, &info);
		/* ignore errors */
	}
	if (new_nwattr_changed)	{
		info.attributes = new_nwattr;
		res2 = ncp_modify_file_or_subdir_dos_info_path(NCP_SERVER(new_dir), new_dir, _new_name, DM_ATTRIBUTES, &info);
		/* ignore errors */
	}
        return(res);
}
#endif	/* CONFIG_NCPFS_STRONG */

static int
__ncp_lookup_validate(struct dentry * dentry, struct nameidata *nd)
{
	struct ncp_server *server;
	struct dentry *parent;
	struct inode *dir;
	struct ncp_entry_info finfo;
	int res, val = 0, len;
	__u8 __name[NCP_MAXPATHLEN + 1];

	parent = dget_parent(dentry);
	dir = parent->d_inode;

	if (!dentry->d_inode)
		goto finished;

	server = NCP_SERVER(dir);

	if (!ncp_conn_valid(server))
		goto finished;

	/*
	 * Inspired by smbfs:
	 * The default validation is based on dentry age:
	 * We set the max age at mount time.  (But each
	 * successful server lookup renews the timestamp.)
	 */
	val = NCP_TEST_AGE(server, dentry);
	if (val)
		goto finished;

	DDPRINTK("ncp_lookup_validate: %s/%s not valid, age=%ld, server lookup\n",
		dentry->d_parent->d_name.name, dentry->d_name.name,
		NCP_GET_AGE(dentry));

	len = sizeof(__name);
	if (ncp_is_server_root(dir)) {
		res = ncp_io2vol(server, __name, &len, dentry->d_name.name,
				 dentry->d_name.len, 1);
		if (!res)
			res = ncp_lookup_volume(server, __name, &(finfo.i));
	} else {
		res = ncp_io2vol(server, __name, &len, dentry->d_name.name,
				 dentry->d_name.len, !ncp_preserve_case(dir));
		if (!res)
			res = ncp_obtain_info(server, dir, __name, &(finfo.i));
	}
	finfo.volume = finfo.i.volNumber;
	DDPRINTK("ncp_lookup_validate: looked for %s/%s, res=%d\n",
		dentry->d_parent->d_name.name, __name, res);
	/*
	 * If we didn't find it, or if it has a different dirEntNum to
	 * what we remember, it's not valid any more.
	 */
	if (!res) {
		if (finfo.i.dirEntNum == NCP_FINFO(dentry->d_inode)->dirEntNum) {
			ncp_new_dentry(dentry);
			val=1;
		} else
			DDPRINTK("ncp_lookup_validate: found, but dirEntNum changed\n");

		ncp_update_inode2(dentry->d_inode, &finfo);
	}

finished:
	DDPRINTK("ncp_lookup_validate: result=%d\n", val);
	dput(parent);
	return val;
}

static int
ncp_lookup_validate(struct dentry * dentry, struct nameidata *nd)
{
	int res;
	lock_kernel();
	res = __ncp_lookup_validate(dentry, nd);
	unlock_kernel();
	return res;
}

static struct dentry *
ncp_dget_fpos(struct dentry *dentry, struct dentry *parent, unsigned long fpos)
{
	struct dentry *dent = dentry;
	struct list_head *next;

	if (d_validate(dent, parent)) {
		if (dent->d_name.len <= NCP_MAXPATHLEN &&
		    (unsigned long)dent->d_fsdata == fpos) {
			if (!dent->d_inode) {
				dput(dent);
				dent = NULL;
			}
			return dent;
		}
		dput(dent);
	}

	/* If a pointer is invalid, we search the dentry. */
	spin_lock(&dcache_lock);
	next = parent->d_subdirs.next;
	while (next != &parent->d_subdirs) {
		dent = list_entry(next, struct dentry, d_u.d_child);
		if ((unsigned long)dent->d_fsdata == fpos) {
			if (dent->d_inode)
				dget_locked(dent);
			else
				dent = NULL;
			spin_unlock(&dcache_lock);
			goto out;
		}
		next = next->next;
	}
	spin_unlock(&dcache_lock);
	return NULL;

out:
	return dent;
}

static time_t ncp_obtain_mtime(struct dentry *dentry)
{
	struct inode *inode = dentry->d_inode;
	struct ncp_server *server = NCP_SERVER(inode);
	struct nw_info_struct i;

	if (!ncp_conn_valid(server) || ncp_is_server_root(inode))
		return 0;

	if (ncp_obtain_info(server, inode, NULL, &i))
		return 0;

	return ncp_date_dos2unix(i.modifyTime, i.modifyDate);
}

static int ncp_readdir(struct file *filp, void *dirent, filldir_t filldir)
{
	struct dentry *dentry = filp->f_path.dentry;
	struct inode *inode = dentry->d_inode;
	struct page *page = NULL;
	struct ncp_server *server = NCP_SERVER(inode);
	union  ncp_dir_cache *cache = NULL;
	struct ncp_cache_control ctl;
	int result, mtime_valid = 0;
	time_t mtime = 0;

	lock_kernel();

	ctl.page  = NULL;
	ctl.cache = NULL;

	DDPRINTK("ncp_readdir: reading %s/%s, pos=%d\n",
		dentry->d_parent->d_name.name, dentry->d_name.name,
		(int) filp->f_pos);

	result = -EIO;
	if (!ncp_conn_valid(server))
		goto out;

	result = 0;
	if (filp->f_pos == 0) {
		if (filldir(dirent, ".", 1, 0, inode->i_ino, DT_DIR))
			goto out;
		filp->f_pos = 1;
	}
	if (filp->f_pos == 1) {
		if (filldir(dirent, "..", 2, 1, parent_ino(dentry), DT_DIR))
			goto out;
		filp->f_pos = 2;
	}

	page = grab_cache_page(&inode->i_data, 0);
	if (!page)
		goto read_really;

	ctl.cache = cache = kmap(page);
	ctl.head  = cache->head;

	if (!PageUptodate(page) || !ctl.head.eof)
		goto init_cache;

	if (filp->f_pos == 2) {
		if (jiffies - ctl.head.time >= NCP_MAX_AGE(server))
			goto init_cache;

		mtime = ncp_obtain_mtime(dentry);
		mtime_valid = 1;
		if ((!mtime) || (mtime != ctl.head.mtime))
			goto init_cache;
	}

	if (filp->f_pos > ctl.head.end)
		goto finished;

	ctl.fpos = filp->f_pos + (NCP_DIRCACHE_START - 2);
	ctl.ofs  = ctl.fpos / NCP_DIRCACHE_SIZE;
	ctl.idx  = ctl.fpos % NCP_DIRCACHE_SIZE;

	for (;;) {
		if (ctl.ofs != 0) {
			ctl.page = find_lock_page(&inode->i_data, ctl.ofs);
			if (!ctl.page)
				goto invalid_cache;
			ctl.cache = kmap(ctl.page);
			if (!PageUptodate(ctl.page))
				goto invalid_cache;
		}
		while (ctl.idx < NCP_DIRCACHE_SIZE) {
			struct dentry *dent;
			int res;

			dent = ncp_dget_fpos(ctl.cache->dentry[ctl.idx],
						dentry, filp->f_pos);
			if (!dent)
				goto invalid_cache;
			res = filldir(dirent, dent->d_name.name,
					dent->d_name.len, filp->f_pos,
					dent->d_inode->i_ino, DT_UNKNOWN);
			dput(dent);
			if (res)
				goto finished;
			filp->f_pos += 1;
			ctl.idx += 1;
			if (filp->f_pos > ctl.head.end)
				goto finished;
		}
		if (ctl.page) {
			kunmap(ctl.page);
			SetPageUptodate(ctl.page);
			unlock_page(ctl.page);
			page_cache_release(ctl.page);
			ctl.page = NULL;
		}
		ctl.idx  = 0;
		ctl.ofs += 1;
	}
invalid_cache:
	if (ctl.page) {
		kunmap(ctl.page);
		unlock_page(ctl.page);
		page_cache_release(ctl.page);
		ctl.page = NULL;
	}
	ctl.cache = cache;
init_cache:
	ncp_invalidate_dircache_entries(dentry);
	if (!mtime_valid) {
		mtime = ncp_obtain_mtime(dentry);
		mtime_valid = 1;
	}
	ctl.head.mtime = mtime;
	ctl.head.time = jiffies;
	ctl.head.eof = 0;
	ctl.fpos = 2;
	ctl.ofs = 0;
	ctl.idx = NCP_DIRCACHE_START;
	ctl.filled = 0;
	ctl.valid  = 1;
read_really:
	if (ncp_is_server_root(inode)) {
		ncp_read_volume_list(filp, dirent, filldir, &ctl);
	} else {
		ncp_do_readdir(filp, dirent, filldir, &ctl);
	}
	ctl.head.end = ctl.fpos - 1;
	ctl.head.eof = ctl.valid;
finished:
	if (page) {
		cache->head = ctl.head;
		kunmap(page);
		SetPageUptodate(page);
		unlock_page(page);
		page_cache_release(page);
	}
	if (ctl.page) {
		kunmap(ctl.page);
		SetPageUptodate(ctl.page);
		unlock_page(ctl.page);
		page_cache_release(ctl.page);
	}
out:
	unlock_kernel();
	return result;
}

static int
ncp_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
		struct ncp_cache_control *ctrl, struct ncp_entry_info *entry)
{
	struct dentry *newdent, *dentry = filp->f_path.dentry;
	struct inode *newino, *inode = dentry->d_inode;
	struct ncp_cache_control ctl = *ctrl;
	struct qstr qname;
	int valid = 0;
	int hashed = 0;
	ino_t ino = 0;
	__u8 __name[NCP_MAXPATHLEN + 1];

	qname.len = sizeof(__name);
	if (ncp_vol2io(NCP_SERVER(inode), __name, &qname.len,
			entry->i.entryName, entry->i.nameLen,
			!ncp_preserve_entry_case(inode, entry->i.NSCreator)))
		return 1; /* I'm not sure */

	qname.name = __name;
	qname.hash = full_name_hash(qname.name, qname.len);

	if (dentry->d_op && dentry->d_op->d_hash)
		if (dentry->d_op->d_hash(dentry, &qname) != 0)
			goto end_advance;

	newdent = d_lookup(dentry, &qname);

	if (!newdent) {
		newdent = d_alloc(dentry, &qname);
		if (!newdent)
			goto end_advance;
	} else {
		hashed = 1;
		memcpy((char *) newdent->d_name.name, qname.name,
							newdent->d_name.len);
	}

	if (!newdent->d_inode) {
		entry->opened = 0;
		entry->ino = iunique(inode->i_sb, 2);
		newino = ncp_iget(inode->i_sb, entry);
		if (newino) {
			newdent->d_op = &ncp_dentry_operations;
			d_instantiate(newdent, newino);
			if (!hashed)
				d_rehash(newdent);
		}
	} else
		ncp_update_inode2(newdent->d_inode, entry);

	if (newdent->d_inode) {
		ino = newdent->d_inode->i_ino;
		newdent->d_fsdata = (void *) ctl.fpos;
		ncp_new_dentry(newdent);
	}

	if (ctl.idx >= NCP_DIRCACHE_SIZE) {
		if (ctl.page) {
			kunmap(ctl.page);
			SetPageUptodate(ctl.page);
			unlock_page(ctl.page);
			page_cache_release(ctl.page);
		}
		ctl.cache = NULL;
		ctl.idx  -= NCP_DIRCACHE_SIZE;
		ctl.ofs  += 1;
		ctl.page  = grab_cache_page(&inode->i_data, ctl.ofs);
		if (ctl.page)
			ctl.cache = kmap(ctl.page);
	}
	if (ctl.cache) {
		ctl.cache->dentry[ctl.idx] = newdent;
		valid = 1;
	}
	dput(newdent);
end_advance:
	if (!valid)
		ctl.valid = 0;
	if (!ctl.filled && (ctl.fpos == filp->f_pos)) {
		if (!ino)
			ino = find_inode_number(dentry, &qname);
		if (!ino)
			ino = iunique(inode->i_sb, 2);
		ctl.filled = filldir(dirent, qname.name, qname.len,
				     filp->f_pos, ino, DT_UNKNOWN);
		if (!ctl.filled)
			filp->f_pos += 1;
	}
	ctl.fpos += 1;
	ctl.idx  += 1;
	*ctrl = ctl;
	return (ctl.valid || !ctl.filled);
}

static void
ncp_read_volume_list(struct file *filp, void *dirent, filldir_t filldir,
			struct ncp_cache_control *ctl)
{
	struct dentry *dentry = filp->f_path.dentry;
	struct inode *inode = dentry->d_inode;
	struct ncp_server *server = NCP_SERVER(inode);
	struct ncp_volume_info info;
	struct ncp_entry_info entry;
	int i;

	DPRINTK("ncp_read_volume_list: pos=%ld\n",
			(unsigned long) filp->f_pos);

	for (i = 0; i < NCP_NUMBER_OF_VOLUMES; i++) {

		if (ncp_get_volume_info_with_number(server, i, &info) != 0)
			return;
		if (!strlen(info.volume_name))
			continue;

		DPRINTK("ncp_read_volume_list: found vol: %s\n",
			info.volume_name);

		if (ncp_lookup_volume(server, info.volume_name,
					&entry.i)) {
			DPRINTK("ncpfs: could not lookup vol %s\n",
				info.volume_name);
			continue;
		}
		entry.volume = entry.i.volNumber;
		if (!ncp_fill_cache(filp, dirent, filldir, ctl, &entry))
			return;
	}
}

static void
ncp_do_readdir(struct file *filp, void *dirent, filldir_t filldir,
						struct ncp_cache_control *ctl)
{
	struct dentry *dentry = filp->f_path.dentry;
	struct inode *dir = dentry->d_inode;
	struct ncp_server *server = NCP_SERVER(dir);
	struct nw_search_sequence seq;
	struct ncp_entry_info entry;
	int err;
	void* buf;
	int more;
	size_t bufsize;

	DPRINTK("ncp_do_readdir: %s/%s, fpos=%ld\n",
		dentry->d_parent->d_name.name, dentry->d_name.name,
		(unsigned long) filp->f_pos);
	PPRINTK("ncp_do_readdir: init %s, volnum=%d, dirent=%u\n",
		dentry->d_name.name, NCP_FINFO(dir)->volNumber,
		NCP_FINFO(dir)->dirEntNum);

	err = ncp_initialize_search(server, dir, &seq);
	if (err) {
		DPRINTK("ncp_do_readdir: init failed, err=%d\n", err);
		return;
	}
	/* We MUST NOT use server->buffer_size handshaked with server if we are
	   using UDP, as for UDP server uses max. buffer size determined by
	   MTU, and for TCP server uses hardwired value 65KB (== 66560 bytes).
	   So we use 128KB, just to be sure, as there is no way how to know
	   this value in advance. */
	bufsize = 131072;
	buf = vmalloc(bufsize);
	if (!buf)
		return;
	do {
		int cnt;
		char* rpl;
		size_t rpls;

		err = ncp_search_for_fileset(server, &seq, &more, &cnt, buf, bufsize, &rpl, &rpls);
		if (err)		/* Error */
			break;
		if (!cnt)		/* prevent endless loop */
			break;
		while (cnt--) {
			size_t onerpl;

			if (rpls < offsetof(struct nw_info_struct, entryName))
				break;	/* short packet */
			ncp_extract_file_info(rpl, &entry.i);
			onerpl = offsetof(struct nw_info_struct, entryName) + entry.i.nameLen;
			if (rpls < onerpl)
				break;	/* short packet */
			(void)ncp_obtain_nfs_info(server, &entry.i);
			rpl += onerpl;
			rpls -= onerpl;
			entry.volume = entry.i.volNumber;
			if (!ncp_fill_cache(filp, dirent, filldir, ctl, &entry))
				break;
		}
	} while (more);
	vfree(buf);
	return;
}

int ncp_conn_logged_in(struct super_block *sb)
{
	struct ncp_server* server = NCP_SBP(sb);
	int result;

	if (ncp_single_volume(server)) {
		int len;
		struct dentry* dent;
		__u32 volNumber;
		__le32 dirEntNum;
		__le32 DosDirNum;
		__u8 __name[NCP_MAXPATHLEN + 1];

		len = sizeof(__name);
		result = ncp_io2vol(server, __name, &len, server->m.mounted_vol,
				    strlen(server->m.mounted_vol), 1);
		if (result)
			goto out;
		result = -ENOENT;
		if (ncp_get_volume_root(server, __name, &volNumber, &dirEntNum, &DosDirNum)) {
			PPRINTK("ncp_conn_logged_in: %s not found\n",
				server->m.mounted_vol);
			goto out;
		}
		dent = sb->s_root;
		if (dent) {
			struct inode* ino = dent->d_inode;
			if (ino) {
				NCP_FINFO(ino)->volNumber = volNumber;
				NCP_FINFO(ino)->dirEntNum = dirEntNum;
				NCP_FINFO(ino)->DosDirNum = DosDirNum;
			} else {
				DPRINTK("ncpfs: sb->s_root->d_inode == NULL!\n");
			}
		} else {
			DPRINTK("ncpfs: sb->s_root == NULL!\n");
		}
	}
	result = 0;

out:
	return result;
}

static struct dentry *ncp_lookup(struct inode *dir, struct dentry *dentry, struct nameidata *nd)
{
	struct ncp_server *server = NCP_SERVER(dir);
	struct inode *inode = NULL;
	struct ncp_entry_info finfo;
	int error, res, len;
	__u8 __name[NCP_MAXPATHLEN + 1];

	lock_kernel();
	error = -EIO;
	if (!ncp_conn_valid(server))
		goto finished;

	PPRINTK("ncp_lookup: server lookup for %s/%s\n",
		dentry->d_parent->d_name.name, dentry->d_name.name);

	len = sizeof(__name);
	if (ncp_is_server_root(dir)) {
		res = ncp_io2vol(server, __name, &len, dentry->d_name.name,
				 dentry->d_name.len, 1);
		if (!res)
			res = ncp_lookup_volume(server, __name, &(finfo.i));
	} else {
		res = ncp_io2vol(server, __name, &len, dentry->d_name.name,
				 dentry->d_name.len, !ncp_preserve_case(dir));
		if (!res)
			res = ncp_obtain_info(server, dir, __name, &(finfo.i));
	}
	PPRINTK("ncp_lookup: looked for %s/%s, res=%d\n",
		dentry->d_parent->d_name.name, __name, res);
	/*
	 * If we didn't find an entry, make a negative dentry.
	 */
	if (res)
		goto add_entry;

	/*
	 * Create an inode for the entry.
	 */
	finfo.opened = 0;
	finfo.ino = iunique(dir->i_sb, 2);
	finfo.volume = finfo.i.volNumber;
	error = -EACCES;
	inode = ncp_iget(dir->i_sb, &finfo);

	if (inode) {
		ncp_new_dentry(dentry);
add_entry:
		dentry->d_op = &ncp_dentry_operations;
		d_add(dentry, inode);
		error = 0;
	}

finished:
	PPRINTK("ncp_lookup: result=%d\n", error);
	unlock_kernel();
	return ERR_PTR(error);
}

/*
 * This code is common to create, mkdir, and mknod.
 */
static int ncp_instantiate(struct inode *dir, struct dentry *dentry,
			struct ncp_entry_info *finfo)
{
	struct inode *inode;
	int error = -EINVAL;

	finfo->ino = iunique(dir->i_sb, 2);
	inode = ncp_iget(dir->i_sb, finfo);
	if (!inode)
		goto out_close;
	d_instantiate(dentry,inode);
	error = 0;
out:
	return error;

out_close:
	PPRINTK("ncp_instantiate: %s/%s failed, closing file\n",
		dentry->d_parent->d_name.name, dentry->d_name.name);
	ncp_close_file(NCP_SERVER(dir), finfo->file_handle);
	goto out;
}

int ncp_create_new(struct inode *dir, struct dentry *dentry, int mode,
		   dev_t rdev, __le32 attributes)
{
	struct ncp_server *server = NCP_SERVER(dir);
	struct ncp_entry_info finfo;
	int error, result, len;
	int opmode;
	__u8 __name[NCP_MAXPATHLEN + 1];

	PPRINTK("ncp_create_new: creating %s/%s, mode=%x\n",
		dentry->d_parent->d_name.name, dentry->d_name.name, mode);

	error = -EIO;
	lock_kernel();
	if (!ncp_conn_valid(server))
		goto out;

	ncp_age_dentry(server, dentry);
	len = sizeof(__name);
	error = ncp_io2vol(server, __name, &len, dentry->d_name.name,
			   dentry->d_name.len, !ncp_preserve_case(dir));
	if (error)
		goto out;

	error = -EACCES;

	if (S_ISREG(mode) &&
	    (server->m.flags & NCP_MOUNT_EXTRAS) &&
	    (mode & S_IXUGO))
		attributes |= aSYSTEM | aSHARED;

	result = ncp_open_create_file_or_subdir(server, dir, __name,
				OC_MODE_CREATE | OC_MODE_OPEN | OC_MODE_REPLACE,
				attributes, AR_READ | AR_WRITE, &finfo);
	opmode = O_RDWR;
	if (result) {
		result = ncp_open_create_file_or_subdir(server, dir, __name,
				OC_MODE_CREATE | OC_MODE_OPEN | OC_MODE_REPLACE,
				attributes, AR_WRITE, &finfo);
		if (result) {
			if (result == 0x87)
				error = -ENAMETOOLONG;
			DPRINTK("ncp_create: %s/%s failed\n",
				dentry->d_parent->d_name.name, dentry->d_name.name);
			goto out;
		}
		opmode = O_WRONLY;
	}
	finfo.access = opmode;
	if (ncp_is_nfs_extras(server, finfo.volume)) {
		finfo.i.nfs.mode = mode;
		finfo.i.nfs.rdev = new_encode_dev(rdev);
		if (ncp_modify_nfs_info(server, finfo.volume,
					finfo.i.dirEntNum,
					mode, new_encode_dev(rdev)) != 0)
			goto out;
	}

	error = ncp_instantiate(dir, dentry, &finfo);
out:
	unlock_kernel();
	return error;
}

static int ncp_create(struct inode *dir, struct dentry *dentry, int mode,
		struct nameidata *nd)
{
	return ncp_create_new(dir, dentry, mode, 0, 0);
}

static int ncp_mkdir(struct inode *dir, struct dentry *dentry, int mode, void *label)
{
	struct ncp_entry_info finfo;
	struct ncp_server *server = NCP_SERVER(dir);
	int error, len;
	__u8 __name[NCP_MAXPATHLEN + 1];

	DPRINTK("ncp_mkdir: making %s/%s\n",
		dentry->d_parent->d_name.name, dentry->d_name.name);

	error = -EIO;
	lock_kernel();
	if (!ncp_conn_valid(server))
		goto out;

	ncp_age_dentry(server, dentry);
	len = sizeof(__name);
	error = ncp_io2vol(server, __name, &len, dentry->d_name.name,
			   dentry->d_name.len, !ncp_preserve_case(dir));
	if (error)
		goto out;

	error = -EACCES;
	if (ncp_open_create_file_or_subdir(server, dir, __name,
					   OC_MODE_CREATE, aDIR,
					   cpu_to_le16(0xffff),
					   &finfo) == 0)
	{
		if (ncp_is_nfs_extras(server, finfo.volume)) {
			mode |= S_IFDIR;
			finfo.i.nfs.mode = mode;
			if (ncp_modify_nfs_info(server,
						finfo.volume,
						finfo.i.dirEntNum,
						mode, 0) != 0)
				goto out;
		}
		error = ncp_instantiate(dir, dentry, &finfo);
	}
out:
	unlock_kernel();
	return error;
}

static int ncp_rmdir(struct inode *dir, struct dentry *dentry)
{
	struct ncp_server *server = NCP_SERVER(dir);
	int error, result, len;
	__u8 __name[NCP_MAXPATHLEN + 1];

	DPRINTK("ncp_rmdir: removing %s/%s\n",
		dentry->d_parent->d_name.name, dentry->d_name.name);

	error = -EIO;
	lock_kernel();
	if (!ncp_conn_valid(server))
		goto out;

	error = -EBUSY;
	if (!d_unhashed(dentry))
		goto out;

	len = sizeof(__name);
	error = ncp_io2vol(server, __name, &len, dentry->d_name.name,
			   dentry->d_name.len, !ncp_preserve_case(dir));
	if (error)
		goto out;

	result = ncp_del_file_or_subdir(server, dir, __name);
	switch (result) {
		case 0x00:
			error = 0;
			break;
		case 0x85:	/* unauthorized to delete file */
		case 0x8A:	/* unauthorized to delete file */
			error = -EACCES;
			break;
		case 0x8F:
		case 0x90:	/* read only */
			error = -EPERM;
			break;
		case 0x9F:	/* in use by another client */
			error = -EBUSY;
			break;
		case 0xA0:	/* directory not empty */
			error = -ENOTEMPTY;
			break;
		case 0xFF:	/* someone deleted file */
			error = -ENOENT;
			break;
		default:
			error = -EACCES;
			break;
       	}
out:
	unlock_kernel();
	return error;
}

static int ncp_unlink(struct inode *dir, struct dentry *dentry)
{
	struct inode *inode = dentry->d_inode;
	struct ncp_server *server;
	int error;

	lock_kernel();
	server = NCP_SERVER(dir);
	DPRINTK("ncp_unlink: unlinking %s/%s\n",
		dentry->d_parent->d_name.name, dentry->d_name.name);

	error = -EIO;
	if (!ncp_conn_valid(server))
		goto out;

	/*
	 * Check whether to close the file ...
	 */
	if (inode) {
		PPRINTK("ncp_unlink: closing file\n");
		ncp_make_closed(inode);
	}

	error = ncp_del_file_or_subdir2(server, dentry);
#ifdef CONFIG_NCPFS_STRONG
	/* 9C is Invalid path.. It should be 8F, 90 - read only, but
	   it is not :-( */
	if ((error == 0x9C || error == 0x90) && server->m.flags & NCP_MOUNT_STRONG) { /* R/O */
		error = ncp_force_unlink(dir, dentry);
	}
#endif
	switch (error) {
		case 0x00:
			DPRINTK("ncp: removed %s/%s\n",
				dentry->d_parent->d_name.name, dentry->d_name.name);
			break;
		case 0x85:
		case 0x8A:
			error = -EACCES;
			break;
		case 0x8D:	/* some files in use */
		case 0x8E:	/* all files in use */
			error = -EBUSY;
			break;
		case 0x8F:	/* some read only */
		case 0x90:	/* all read only */
		case 0x9C:	/* !!! returned when in-use or read-only by NW4 */
			error = -EPERM;
			break;
		case 0xFF:
			error = -ENOENT;
			break;
		default:
			error = -EACCES;
			break;
	}

out:
	unlock_kernel();
	return error;
}

static int ncp_rename(struct inode *old_dir, struct dentry *old_dentry,
		      struct inode *new_dir, struct dentry *new_dentry)
{
	struct ncp_server *server = NCP_SERVER(old_dir);
	int error;
	int old_len, new_len;
	__u8 __old_name[NCP_MAXPATHLEN + 1], __new_name[NCP_MAXPATHLEN + 1];

	DPRINTK("ncp_rename: %s/%s to %s/%s\n",
		old_dentry->d_parent->d_name.name, old_dentry->d_name.name,
		new_dentry->d_parent->d_name.name, new_dentry->d_name.name);

	error = -EIO;
	lock_kernel();
	if (!ncp_conn_valid(server))
		goto out;

	ncp_age_dentry(server, old_dentry);
	ncp_age_dentry(server, new_dentry);

	old_len = sizeof(__old_name);
	error = ncp_io2vol(server, __old_name, &old_len,
			   old_dentry->d_name.name, old_dentry->d_name.len,
			   !ncp_preserve_case(old_dir));
	if (error)
		goto out;

	new_len = sizeof(__new_name);
	error = ncp_io2vol(server, __new_name, &new_len,
			   new_dentry->d_name.name, new_dentry->d_name.len,
			   !ncp_preserve_case(new_dir));
	if (error)
		goto out;

	error = ncp_ren_or_mov_file_or_subdir(server, old_dir, __old_name,
						      new_dir, __new_name);
#ifdef CONFIG_NCPFS_STRONG
	if ((error == 0x90 || error == 0x8B || error == -EACCES) &&
			server->m.flags & NCP_MOUNT_STRONG) {	/* RO */
		error = ncp_force_rename(old_dir, old_dentry, __old_name,
					 new_dir, new_dentry, __new_name);
	}
#endif
	switch (error) {
		case 0x00:
               	        DPRINTK("ncp renamed %s -> %s.\n",
                                old_dentry->d_name.name,new_dentry->d_name.name);
			break;
		case 0x9E:
			error = -ENAMETOOLONG;
			break;
		case 0xFF:
			error = -ENOENT;
			break;
		default:
			error = -EACCES;
			break;
	}
out:
	unlock_kernel();
	return error;
}

static int ncp_mknod(struct inode * dir, struct dentry *dentry,
		     int mode, dev_t rdev, void *label)
{
	if (!new_valid_dev(rdev))
		return -EINVAL;
	if (ncp_is_nfs_extras(NCP_SERVER(dir), NCP_FINFO(dir)->volNumber)) {
		DPRINTK(KERN_DEBUG "ncp_mknod: mode = 0%o\n", mode);
		return ncp_create_new(dir, dentry, mode, rdev, 0);
	}
	return -EPERM; /* Strange, but true */
}

/* The following routines are taken directly from msdos-fs */

/* Linear day numbers of the respective 1sts in non-leap years. */

static int day_n[] =
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 0, 0, 0, 0};
/* Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec */

extern struct timezone sys_tz;

static int utc2local(int time)
{
	return time - sys_tz.tz_minuteswest * 60;
}

static int local2utc(int time)
{
	return time + sys_tz.tz_minuteswest * 60;
}

/* Convert a MS-DOS time/date pair to a UNIX date (seconds since 1 1 70). */
int
ncp_date_dos2unix(__le16 t, __le16 d)
{
	unsigned short time = le16_to_cpu(t), date = le16_to_cpu(d);
	int month, year, secs;

	/* first subtract and mask after that... Otherwise, if
	   date == 0, bad things happen */
	month = ((date >> 5) - 1) & 15;
	year = date >> 9;
	secs = (time & 31) * 2 + 60 * ((time >> 5) & 63) + (time >> 11) * 3600 +
		86400 * ((date & 31) - 1 + day_n[month] + (year / 4) +
		year * 365 - ((year & 3) == 0 && month < 2 ? 1 : 0) + 3653);
	/* days since 1.1.70 plus 80's leap day */
	return local2utc(secs);
}

/* Convert linear UNIX date to a MS-DOS time/date pair. */
void
ncp_date_unix2dos(int unix_date, __le16 *time, __le16 *date)
{
	int day, year, nl_day, month;

	unix_date = utc2local(unix_date);
	*time = cpu_to_le16(
		(unix_date % 60) / 2 + (((unix_date / 60) % 60) << 5) +
		(((unix_date / 3600) % 24) << 11));
	day = unix_date / 86400 - 3652;
	year = day / 365;
	if ((year + 3) / 4 + 365 * year > day)
		year--;
	day -= (year + 3) / 4 + 365 * year;
	if (day == 59 && !(year & 3)) {
		nl_day = day;
		month = 2;
	} else {
		nl_day = (year & 3) || day <= 59 ? day : day - 1;
		for (month = 0; month < 12; month++)
			if (day_n[month] > nl_day)
				break;
	}
	*date = cpu_to_le16(nl_day - day_n[month - 1] + 1 + (month << 5) + (year << 9));
}


text:
package com.s4game.server.bus.share.rule;

import javax.annotation.Resource;

import com.s4game.server.bus.share.service.IRoleStateService;
import com.s4game.server.executor.IRuleChecker;

/**
 *
 * @Author zeusgooogle@gmail.com
 * @sine   2015年6月19日 下午6:10:28
 *
 */
public class BusRuleChecker implements IRuleChecker {

    @Resource
    private IRoleStateService roleStateService;

    @Override
    public boolean valid(Object roleId) {
        return roleStateService.isOnline((String)roleId);
    }

}


text:
rm -rf $HOME/A/*/;

echo "We deleted all subcatalogs in folder A.";

exit 0;


text:
<?php

namespace Alcys\Core\Db\Facade;

/**
 * Interface SelectFacadeInterface
 * @Todo    Outsource join stuff, because other statements also could use joins.
 * @package Alcys\Core\Db\Facade
 */
interface SelectFacadeInterface
{
	/**
	 * Add a table to the query.
	 *
	 * @param string      $tableName The name of the table.
	 * @param string|null $alias     (Optional) An alias name, if exists.
	 *
	 * @return $this The same instance to concatenate methods.
	 */
	public function table($tableName, $alias = null);

	/**
	 * Add a column to the query. When this method would not called, a * wildcard will set.
	 *
	 * @param string      $name     Name of the column.
	 * @param string|null $tableRef (Optional) Name of the referred table, if exists.
	 * @param string|null $alias    (Optional) An alias name, if exists.
	 *
	 * @return $this The same instance to concatenate methods.
	 */
	public function column($name, $tableRef = null, $alias = null);

	/**
	 * Add a group by expression to the query.
	 *
	 * @param string      $column
	 * @param string|null $orderMode
	 *
	 * @return $this The same instance to concatenate methods
	 */
	public function groupBy($column, $orderMode = null);

	/**
	 * Add a distinct expression to the query.
	 *
	 * @return $this The same instance to concatenate methods.
	 */
	public function distinct();

	/**
	 * Add a join expression to the query.
	 *
	 * @param JoinFacadeInterface $join The configured join facade object, get by joinBuilder method.
	 *
	 * @return $this The same instance to concatenate methods.
	 */
	public function join(JoinFacadeInterface $join);

	/**
	 * Return a join object which could passed through the join method.
	 *
	 * @return JoinFacadeInterface
	 */
	public function joinBuilder();
}


text:
//Problem 12. Extract students by phone

//    Extract all students with phones in Sofia.
//    Use LINQ.

using System;
using System.Collections.Generic;
using System.Linq;
using MyStudent;

class ExtractStudentsByPhone
{
    static void Main()
    {
        List<Student> students = ListOfStudents.GetListOfSudents();

        Console.WriteLine("Students with phone in Sofia!");

        var phoneInSofia =
            from student in students
            where student.PhoneNumber.StartsWith("02") ||
                  student.PhoneNumber.StartsWith("+359 2") ||
                  student.PhoneNumber.StartsWith("00359 2")
            select student;
        foreach (var st in phoneInSofia)
        {
            Console.WriteLine("Name: {0} {1}, Phone number: {2}",
                st.FirstName,
                st.LastName,
                st.PhoneNumber);
        }
    }
}


text:
using System.Collections;
using lizzard.Proxies;
using UnityPureMVC.Interfaces;
using UnityPureMVC.Patterns;

namespace lizzard.Commands
{
    public class StartCoroutineCommand : SimpleCommand
    {
        public override void Execute(INotification notification)
        {
            base.Execute(notification);

            var engineProxy = Facade.RetrieveProxy(ProxyNames.ENGINE_PROXY) as EngineProxy;

            if (engineProxy != null) engineProxy.StartCoroutine((IEnumerator) notification.Body);
        }
    }
}


text:
/** @file */

/**
 * Public shared types for Ion implementation.
 * This includes typedef's for various platforms and int sizes
 * and other associated configuration
 */

#ifndef ION_TYPES_H_
#define ION_TYPES_H_

#include "ion_errors.h"

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>
#include <decNumber/decQuad.h>
#include <decNumber/decNumber.h>

#ifdef ION_INIT
  #define GLOBAL    ION_API_EXPORT
  #define INITTO(x) = x
  #define INIT_STATICS
#else
  #define GLOBAL    extern
  #define INITTO(x) /* nothing */
  #ifdef  INIT_STATICS
  #undef  INIT_STATICS
  #endif
#endif

#ifndef NULL
#define NULL ((void *)0)
#endif

#ifndef TRUE
#define TRUE  1
#define FALSE 0
#endif

#ifndef MAX_INT32
#define MAX_INT32         0x7FFFFFFF    // 2,147,483,647
#define MIN_INT32         -0x7FFFFFFF-1    // -2,147,483,648
#endif

#ifndef MAX_INT64
#define MAX_INT64  0x7FFFFFFFFFFFFFFFLL
#define MIN_INT64  -0x7FFFFFFFFFFFFFFFLL-1
#define HIGH_BIT_INT64 (((uint64_t)(1)) << 63)
#endif

/** Strong typed enum over pointer type. */
typedef struct ion_type    *ION_TYPE;
#define ION_TYPE_INT(x) ((intptr_t) (x))

/**
 * Current value type not known (has not been checked)
 */
#define tid_none      ((ION_TYPE)(tid_none_INT))

/**
 * Stands for both End of File and End of Container, unfortunately.
 */
#define tid_EOF       ((ION_TYPE)(tid_EOF_INT))

/**
 * Ion Value Type NULL.
 */
#define tid_NULL         ((ION_TYPE) tid_NULL_INT)
#define tid_BOOL         ((ION_TYPE) tid_BOOL_INT)
#define tid_INT          ((ION_TYPE) tid_INT_INT)
#define tid_FLOAT        ((ION_TYPE) tid_FLOAT_INT)
#define tid_DECIMAL      ((ION_TYPE) tid_DECIMAL_INT)
#define tid_TIMESTAMP    ((ION_TYPE) tid_TIMESTAMP_INT)
#define tid_SYMBOL       ((ION_TYPE) tid_SYMBOL_INT)
#define tid_STRING       ((ION_TYPE) tid_STRING_INT)
#define tid_CLOB         ((ION_TYPE) tid_CLOB_INT)
#define tid_BLOB         ((ION_TYPE) tid_BLOB_INT)
#define tid_LIST         ((ION_TYPE) tid_LIST_INT)
#define tid_SEXP         ((ION_TYPE) tid_SEXP_INT)
#define tid_STRUCT       ((ION_TYPE) tid_STRUCT_INT)
#define tid_DATAGRAM     ((ION_TYPE) tid_DATAGRAM_INT)

#define tid_none_INT       -0x200
#define tid_EOF_INT        -0x100
#define tid_NULL_INT       0x000
#define tid_BOOL_INT       0x100
#define tid_INT_INT        0x200
#define tid_FLOAT_INT      0x400
#define tid_DECIMAL_INT    0x500
#define tid_TIMESTAMP_INT  0x600
#define tid_SYMBOL_INT     0x700
#define tid_STRING_INT     0x800
#define tid_CLOB_INT       0x900
#define tid_BLOB_INT       0xA00
#define tid_LIST_INT       0xB00
#define tid_SEXP_INT       0xC00
#define tid_STRUCT_INT     0xD00
#define tid_DATAGRAM_INT   0xF00

typedef int32_t             SID;
typedef int32_t             SIZE;
typedef uint8_t             BYTE;
typedef int                 BOOL;
#define MAX_SIZE            INT32_MAX

//
// forward references of pointers for linked lists
//
typedef struct _ion_symbol_table        ION_SYMBOL_TABLE;
typedef struct _ion_catalog             ION_CATALOG;

/**
 * An Ion String.
 *
 * @see _ion_string
 */
typedef struct _ion_string              ION_STRING;
typedef struct _ion_symbol              ION_SYMBOL;

typedef struct _ion_symbol_table_import_descriptor ION_SYMBOL_TABLE_IMPORT_DESCRIPTOR;
typedef struct _ion_symbol_table_import            ION_SYMBOL_TABLE_IMPORT;

typedef struct _ion_reader              ION_READER;
typedef struct _ion_writer              ION_WRITER;
typedef struct _ion_int                 ION_INT;
typedef struct _ion_decimal             ION_DECIMAL;
typedef struct _ion_timestamp           ION_TIMESTAMP;
typedef struct _ion_collection          ION_COLLECTION;

#ifndef ION_STREAM_DECL
#define ION_STREAM_DECL

// needed when the stream is used outside the context of the
// general Ion library. Otherwise this must be defined in the
// Ion type header (ion_types.h).
typedef struct _ion_stream        ION_STREAM;

// decl's for user managed stream
struct _ion_user_stream;
typedef iERR (*ION_STREAM_HANDLER)(struct _ion_user_stream *pstream);
struct _ion_user_stream
{
    BYTE *curr;
    BYTE *limit;
    void *handler_state;
    ION_STREAM_HANDLER handler;
};

#endif

// some public pointers to these, which we don't really need
// and should be changed TODO
typedef ION_STRING              *iSTRING;
typedef ION_SYMBOL              *iSYMBOL;
typedef ION_SYMBOL_TABLE_IMPORT *iIMPORT;
typedef ION_SYMBOL_TABLE        *iSYMTAB;
typedef ION_CATALOG             *iCATALOG;
typedef ION_STREAM              *iSTREAM;
typedef ION_TIMESTAMP           *iTIMESTAMP;

// TODO: switch to: typedef struct _ion_catalog_proxy *hCATALOG;
typedef void                    *hOWNER;
typedef ION_READER              *hREADER;
typedef ION_WRITER              *hWRITER;
typedef ION_SYMBOL_TABLE        *hSYMTAB;
typedef ION_CATALOG             *hCATALOG;

#ifdef __cplusplus
}
#endif

#endif


text:
using System.Security;
using System;
using System.Text;
using System.Threading;
using System.Runtime;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

namespace System.Globalization
{
    public partial class TextInfo
    {
        ////--------------------------------------------------------------------//
        ////                        Internal Information                        //
        ////--------------------------------------------------------------------//

        ////
        ////  Variables.
        ////

        private String m_listSeparator;
        private bool m_isReadOnly = false;

        ////
        //// In Whidbey we had several names:
        ////      m_win32LangID is the name of the culture, but only used for (de)serialization.
        ////      customCultureName is the name of the creating custom culture (if custom)  In combination with m_win32LangID
        ////              this is authoratative, ie when deserializing.
        ////      m_cultureTableRecord was the data record of the creating culture.  (could have different name if custom)
        ////      m_textInfoID is the LCID of the textinfo itself (no longer used)
        ////      m_name is the culture name (from cultureinfo.name)
        ////
        //// In Silverlight/Arrowhead this is slightly different:
        ////      m_cultureName is the name of the creating culture.  Note that we consider this authoratative,
        ////              if the culture's textinfo changes when deserializing, then behavior may change.
        ////              (ala Whidbey behavior).  This is the only string Arrowhead needs to serialize.
        ////      m_cultureData is the data that backs this class.
        ////      m_textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
        ////              this can be the same as m_cultureName on Silverlight since the OS knows
        ////              how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't
        ////              know how to resolve custom locle names to sort ids so we have to have alredy resolved this.
        ////

        private readonly String m_cultureName;      // Name of the culture that created this text info
        private readonly CultureData m_cultureData;      // Data record for the culture that made us, not for this textinfo
        private readonly String m_textInfoName;     // Name of the text info we're using (ie: m_cultureData.STEXTINFO)
        private bool? m_IsAsciiCasingSameAsInvariant;

        // Invariant text info
        internal static TextInfo Invariant
        {
            get
            {
                if (s_Invariant == null)
                    s_Invariant = new TextInfo(CultureData.Invariant);
                return s_Invariant;
            }
        }
        internal volatile static TextInfo s_Invariant;

        //
        // Internal ordinal comparison functions
        //

        internal static int GetHashCodeOrdinalIgnoreCase(String s)
        {
            // This is the same as an case insensitive hash for Invariant
            // (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules)
            return (Invariant.GetCaseInsensitiveHashCode(s));
        }

        // Currently we don't have native functions to do this, so we do it the hard way
        internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
        {
            if (count > source.Length || count < 0 || startIndex < 0 || startIndex >= source.Length || startIndex + count > source.Length)
            {
                return -1;
            }

            return CompareInfo.IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
        }

        // Currently we don't have native functions to do this, so we do it the hard way
        internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
        {
            if (count > source.Length || count < 0 || startIndex < 0 || startIndex > source.Length - 1 || (startIndex - count + 1 < 0))
            {
                return -1;
            }

            return CompareInfo.LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
        }

        //////////////////////////////////////////////////////////////////////////
        ////
        ////  CultureName
        ////
        ////  The name of the culture associated with the current TextInfo.
        ////
        //////////////////////////////////////////////////////////////////////////
        public string CultureName
        {
            get
            {
                return m_textInfoName;
            }
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  IsReadOnly
        //
        //  Detect if the object is readonly.
        //
        ////////////////////////////////////////////////////////////////////////
        [System.Runtime.InteropServices.ComVisible(false)]
        public bool IsReadOnly
        {
            get { return (m_isReadOnly); }
        }

        //////////////////////////////////////////////////////////////////////////
        ////
        ////  Clone
        ////
        ////  Is the implementation of IColnable.
        ////
        //////////////////////////////////////////////////////////////////////////
        internal virtual Object Clone()
        {
            object o = MemberwiseClone();
            ((TextInfo)o).SetReadOnlyState(false);
            return (o);
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  ReadOnly
        //
        //  Create a cloned readonly instance or return the input one if it is
        //  readonly.
        //
        ////////////////////////////////////////////////////////////////////////
        [System.Runtime.InteropServices.ComVisible(false)]
        internal static TextInfo ReadOnly(TextInfo textInfo)
        {
            if (textInfo == null) { throw new ArgumentNullException("textInfo"); }
            Contract.EndContractBlock();
            if (textInfo.IsReadOnly) { return (textInfo); }

            TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
            clonedTextInfo.SetReadOnlyState(true);

            return (clonedTextInfo);
        }

        private void VerifyWritable()
        {
            if (m_isReadOnly)
            {
                throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
            }
        }

        internal void SetReadOnlyState(bool readOnly)
        {
            m_isReadOnly = readOnly;
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  ListSeparator
        //
        //  Returns the string used to separate items in a list.
        //
        ////////////////////////////////////////////////////////////////////////
        public virtual String ListSeparator
        {
            get
            {
                if (m_listSeparator == null)
                {
                    m_listSeparator = this.m_cultureData.SLIST;
                }
                return (m_listSeparator);
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value", SR.ArgumentNull_String);
                }
                VerifyWritable();
                m_listSeparator = value;
            }
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  ToLower
        //
        //  Converts the character or string to lower case.  Certain locales
        //  have different casing semantics from the file systems in Win32.
        //
        ////////////////////////////////////////////////////////////////////////
        public unsafe virtual char ToLower(char c)
        {
            if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
            {
                return ToLowerAsciiInvariant(c);
            }
            return (ChangeCase(c, toUpper: false));
        }

        public unsafe virtual String ToLower(String str)
        {
            if (str == null) { throw new ArgumentNullException("str"); }

            return ChangeCase(str, toUpper: false);
        }

        static private Char ToLowerAsciiInvariant(Char c)
        {
            if ('A' <= c && c <= 'Z')
            {
                c = (Char)(c | 0x20);
            }
            return c;
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  ToUpper
        //
        //  Converts the character or string to upper case.  Certain locales
        //  have different casing semantics from the file systems in Win32.
        //
        ////////////////////////////////////////////////////////////////////////
        public unsafe virtual char ToUpper(char c)
        {
            if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
            {
                return ToUpperAsciiInvariant(c);
            }
            return (ChangeCase(c, toUpper: true));
        }

        public unsafe virtual String ToUpper(String str)
        {
            if (str == null) { throw new ArgumentNullException("str"); }

            return ChangeCase(str, toUpper: true);
        }

        static private Char ToUpperAsciiInvariant(Char c)
        {
            if ('a' <= c && c <= 'z')
            {
                c = (Char)(c & ~0x20);
            }
            return c;
        }

        static private bool IsAscii(Char c)
        {
            return c < 0x80;
        }

        private bool IsAsciiCasingSameAsInvariant
        {
            get
            {
#if PLATFORM_UNIX
                // UNIXTODO: This hack can be removed once collation works and the code after this correctly returns "false".
                if (m_needsTurkishCasing)
                {
                    return false;
                }
#endif

                if (m_IsAsciiCasingSameAsInvariant == null)
                {
                    m_IsAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(m_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
                                                                             "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                                                                             CompareOptions.IgnoreCase) == 0;
                }
                return (bool)m_IsAsciiCasingSameAsInvariant;
            }
        }

        // IsRightToLeft
        //
        // Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
        //
        public bool IsRightToLeft
        {
            get
            {
                return this.m_cultureData.IsRightToLeft;
            }
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  Equals
        //
        //  Implements Object.Equals().  Returns a boolean indicating whether
        //  or not object refers to the same CultureInfo as the current instance.
        //
        ////////////////////////////////////////////////////////////////////////
        public override bool Equals(Object obj)
        {
            TextInfo that = obj as TextInfo;

            if (that != null)
            {
                return this.CultureName.Equals(that.CultureName);
            }

            return (false);
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  GetHashCode
        //
        //  Implements Object.GetHashCode().  Returns the hash code for the
        //  CultureInfo.  The hash code is guaranteed to be the same for CultureInfo A
        //  and B where A.Equals(B) is true.
        //
        ////////////////////////////////////////////////////////////////////////
        public override int GetHashCode()
        {
            return (this.CultureName.GetHashCode());
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  ToString
        //
        //  Implements Object.ToString().  Returns a string describing the
        //  TextInfo.
        //
        ////////////////////////////////////////////////////////////////////////
        public override String ToString()
        {
            return ("TextInfo - " + this.m_cultureData.CultureName);
        }

        //
        // Get case-insensitive hash code for the specified string.
        //
        internal unsafe int GetCaseInsensitiveHashCode(String str)
        {
            // Validate inputs
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }

            // This code assumes that ASCII casing is safe for whatever context is passed in.
            // this is true today, because we only ever call these methods on Invariant.  It would be ideal to refactor
            // these methods so they were correct by construction and we could only ever use Invariant.

            uint hash = 5381;
            uint c;

            // Note: We assume that str contains only ASCII characters until
            // we hit a non-ASCII character to optimize the common case.
            for (int i = 0; i < str.Length; i++)
            {
                c = str[i];
                if (c >= 0x80)
                {
                    return GetCaseInsensitiveHashCodeSlow(str);
                }

                // If we have a lowercase character, ANDing off 0x20
                // will make it an uppercase character.
                if ((c - 'a') <= ('z' - 'a'))
                {
                    c = (uint)((int)c & ~0x20);
                }

                hash = ((hash << 5) + hash) ^ c;
            }

            return (int)hash;

        }

        private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
        {
            Contract.Assert(str != null);

            string upper = ToUpper(str);

            uint hash = 5381;
            uint c;

            for (int i = 0; i < upper.Length; i++)
            {
                c = upper[i];
                hash = ((hash << 5) + hash) ^ c;
            }

            return (int)hash;
        }
    }
}


text:
<?php

namespace StickyNotes\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity;
 */
class StickyNote {

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $note;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=false)
     */
    protected $createdAt;

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set CreatedAt
     *
     * @ORM\PrePersist
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }
}


text:
namespace signin {

// AccountReconcilorDelegate specialized for Mirror, using the "Mirror landing"
// variant. Mirror is always enabled, even when there is no primary account.
class MirrorLandingAccountReconcilorDelegate
    : public AccountReconcilorDelegate {
 public:
  MirrorLandingAccountReconcilorDelegate();
  ~MirrorLandingAccountReconcilorDelegate() override;

  MirrorLandingAccountReconcilorDelegate(
      const MirrorLandingAccountReconcilorDelegate&) = delete;
  MirrorLandingAccountReconcilorDelegate& operator=(
      const MirrorLandingAccountReconcilorDelegate&) = delete;

  // AccountReconcilorDelegate:
  bool IsReconcileEnabled() const override;
  gaia::GaiaSource GetGaiaApiSource() const override;
  bool ShouldAbortReconcileIfPrimaryHasError() const override;
  ConsentLevel GetConsentLevelForPrimaryAccount() const override;
  CoreAccountId GetFirstGaiaAccountForReconcile(
      const std::vector<CoreAccountId>& chrome_accounts,
      const std::vector<gaia::ListedAccount>& gaia_accounts,
      const CoreAccountId& primary_account,
      bool first_execution,
      bool will_logout) const override;
  std::vector<CoreAccountId> GetChromeAccountsForReconcile(
      const std::vector<CoreAccountId>& chrome_accounts,
      const CoreAccountId& primary_account,
      const std::vector<gaia::ListedAccount>& gaia_accounts,
      bool first_execution,
      bool primary_has_error,
      const gaia::MultiloginMode mode) const override;
};

}  // namespace signin

#endif  // COMPONENTS_SIGNIN_CORE_BROWSER_MIRROR_LANDING_ACCOUNT_RECONCILOR_DELEGATE_H_


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

<title>CommonTest</title>
<meta name="date" content="2016-08-17">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.fpe4j

Class CommonTest

java.lang.Object

org.fpe4j.CommonTest

public class CommonTest
extends java.lang.Object

JUnit test cases for the Common class.

Author:

Kai Johnson

Constructor Summary

Constructors

Constructor and Description

CommonTest()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
testBitstring()

Test method for
 Common.bitstring(boolean, int).

void
testByteArrayToHexString()

Test method for
 Common.byteArrayToHexString(byte[]).

void
testBytestringBigIntegerInt()

Test method for
 Common.bytestring(BigInteger, int).

void
testBytestringIntInt()

Test method for
 Common.bytestring(int, int).

void
testCeiling()

Test method for Common.ceiling(double).

void
testCommon()

Test method for Common.Common().

void
testConcatenateByteArrayByteArray()

Test method for
 Common.concatenate(byte[], byte[]).

void
testConcatenateIntArrayIntArray()

Test method for
 Common.concatenate(int[], int[]).

void
testFloor()

Test method for Common.floor(double).

void
testIntArrayToString()

Test method for
 Common.intArrayToString(int[]).

void
testLog2()

Test method for Common.log2(int).

void
testModBigIntegerBigInteger()

Test method for
 Common.mod(BigInteger, BigInteger).

void
testModIntInt()

Test method for Common.mod(int, int).

void
testNumByteArray()

Test method for Common.num(byte[]).

void
testNumIntArrayInt()

Test method for Common.num(int[], int).

void
testRev()

Test method for Common.rev(int[]).

void
testRevb()

Test method for Common.revb(byte[]).

void
testStr()

Test method for
 Common.str(java.math.BigInteger, int, int).

void
testUnsignedByteArrayToString()

Test method for
 Common.unsignedByteArrayToString(byte[]).

void
testXor()

Test method for Common.xor(byte[], byte[]).

Methods inherited from class java.lang.Object

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

Constructor Detail

CommonTest

public CommonTest()

Method Detail

testCommon

public void testCommon()

Test method for Common.Common().

testNumIntArrayInt

public void testNumIntArrayInt()

Test method for Common.num(int[], int).

testNumByteArray

public void testNumByteArray()

Test method for Common.num(byte[]).

testStr

public void testStr()

Test method for
 Common.str(java.math.BigInteger, int, int).

testRev

public void testRev()

Test method for Common.rev(int[]).

testRevb

public void testRevb()

Test method for Common.revb(byte[]).

testXor

public void testXor()

Test method for Common.xor(byte[], byte[]).

testLog2

public void testLog2()

Test method for Common.log2(int).

testFloor

public void testFloor()

Test method for Common.floor(double).

testCeiling

public void testCeiling()

Test method for Common.ceiling(double).

testModIntInt

public void testModIntInt()

Test method for Common.mod(int, int).

testModBigIntegerBigInteger

public void testModBigIntegerBigInteger()

Test method for
 Common.mod(BigInteger, BigInteger).

testBytestringIntInt

public void testBytestringIntInt()

Test method for
 Common.bytestring(int, int).

testBytestringBigIntegerInt

public void testBytestringBigIntegerInt()

Test method for
 Common.bytestring(BigInteger, int).

testBitstring

public void testBitstring()

Test method for
 Common.bitstring(boolean, int).

testConcatenateIntArrayIntArray

public void testConcatenateIntArrayIntArray()

Test method for
 Common.concatenate(int[], int[]).

testConcatenateByteArrayByteArray

public void testConcatenateByteArrayByteArray()

Test method for
 Common.concatenate(byte[], byte[]).

testIntArrayToString

public void testIntArrayToString()

Test method for
 Common.intArrayToString(int[]).

testUnsignedByteArrayToString

public void testUnsignedByteArrayToString()

Test method for
 Common.unsignedByteArrayToString(byte[]).

testByteArrayToHexString

public void testByteArrayToHexString()

Test method for
 Common.byteArrayToHexString(byte[]).

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        // return parent::render($request, $e);

        $error = $this->convertExceptionToResponse($e);

        $json = [
            'success' => false,
            'error' => [
                'code' => $error->getStatusCode(),
                'message' => $e->getMessage(),
            ],
        ];

        if ($error->getStatusCode() == 404) {
            $json['error']['message'] = "Not Found";
        }

        return response()->json($json, $error->getStatusCode());
    }
}


text:
#ifndef __dgMemory__
#define __dgMemory__

#include "dgStdafx.h"

class dgMemoryAllocator;

void* dgApi dgMalloc (size_t size, dgMemoryAllocator* const allocator);
void  dgApi dgFree (void* const ptr);

void* dgApi dgMallocStack (size_t size);
void* dgApi dgMallocAligned (size_t size, dgInt32 alignmentInBytes);
void  dgApi dgFreeStack (void* const ptr);

typedef void* (dgApi *dgMemAlloc) (dgUnsigned32 size);
typedef void (dgApi *dgMemFree) (void* const ptr, dgUnsigned32 size);

#define DG_CLASS_ALLOCATOR_NEW(allocator)			DG_INLINE void *operator new (size_t size, dgMemoryAllocator* const allocator) { return dgMalloc(size, allocator);}
#define DG_CLASS_ALLOCATOR_NEW_ARRAY(allocator)		DG_INLINE void *operator new[] (size_t size, dgMemoryAllocator* const allocator) { return dgMalloc(size, allocator);}
#define DG_CLASS_ALLOCATOR_DELETE(allocator)		DG_INLINE void operator delete (void* const ptr, dgMemoryAllocator* const allocator) { dgFree(ptr); }
#define DG_CLASS_ALLOCATOR_DELETE_ARRAY(allocator)	DG_INLINE void operator delete[] (void* const ptr, dgMemoryAllocator* const allocator) { dgFree(ptr); }
#define DG_CLASS_ALLOCATOR_NEW_DUMMY				DG_INLINE void *operator new (size_t size) { dgAssert (0); return dgMalloc(size, NULL);}
#define DG_CLASS_ALLOCATOR_NEW_ARRAY_DUMMY			DG_INLINE void *operator new[] (size_t size) { dgAssert (0); return dgMalloc(size, NULL);}
#define DG_CLASS_ALLOCATOR_DELETE_DUMMY				DG_INLINE void operator delete (void* const ptr) { dgFree(ptr); }
#define DG_CLASS_ALLOCATOR_DELETE_ARRAY_DUMMY		DG_INLINE void operator delete[] (void* const ptr) { dgFree(ptr); }

#define DG_CLASS_ALLOCATOR(allocator)				\
	DG_CLASS_ALLOCATOR_DELETE(allocator)			\
	DG_CLASS_ALLOCATOR_DELETE_ARRAY(allocator)		\
	DG_CLASS_ALLOCATOR_NEW(allocator)				\
	DG_CLASS_ALLOCATOR_NEW_ARRAY(allocator)			\
	DG_CLASS_ALLOCATOR_NEW_DUMMY					\
	DG_CLASS_ALLOCATOR_NEW_ARRAY_DUMMY				\
	DG_CLASS_ALLOCATOR_DELETE_DUMMY					\
	DG_CLASS_ALLOCATOR_DELETE_ARRAY_DUMMY

class dgMemoryAllocator
{
	#if (defined (__LP64__) || defined (_WIN_64_VER) || defined (_MINGW_64_VER) || defined (_POSIX_VER_64) || defined (_MACOSX_VER))
		#define DG_MEMORY_GRANULARITY_BITS		6
	#else
		#define DG_MEMORY_GRANULARITY_BITS		5
	#endif
	#define DG_MEMORY_GRANULARITY				(1 << DG_MEMORY_GRANULARITY_BITS)
	#define DG_MEMORY_SIZE						(1024 - 64)
	#define DG_MEMORY_BIN_SIZE					(1024 * 16)
	#define DG_MEMORY_BIN_ENTRIES				(DG_MEMORY_SIZE / DG_MEMORY_GRANULARITY)

	public:
	class dgMemoryBin;
	class dgMemoryInfo;
	class dgMemoryCacheEntry;

	class dgMemDirectory
	{
		public:
		dgMemoryBin* m_first;
		dgMemoryCacheEntry* m_cache;
	};

	dgMemoryAllocator ();
	virtual ~dgMemoryAllocator ();

	void *operator new (size_t size);
	void operator delete (void* const ptr);
	dgInt32 GetMemoryUsed() const;

	void SetAllocatorsCallback (dgMemAlloc memAlloc, dgMemFree memFree);
	virtual void *MallocLow (dgInt32 size, dgInt32 alignment = DG_MEMORY_GRANULARITY);
	virtual void FreeLow (void* const retPtr);
	virtual void *Malloc (dgInt32 memsize);
	virtual void Free (void* const retPtr);

	static dgInt32 GetGlobalMemoryUsed ();
	static void SetGlobalAllocators (dgMemAlloc alloc, dgMemFree free);

	protected:
	dgMemoryAllocator (bool init)
		:m_free(NULL)
		,m_malloc(NULL)
		,m_enumerator(0)
		,m_memoryUsed(0)
		,m_isInList(0)
	{
	}

	dgMemoryAllocator (dgMemAlloc memAlloc, dgMemFree memFree);

	dgMemFree m_free;
	dgMemAlloc m_malloc;
	dgMemDirectory m_memoryDirectory[DG_MEMORY_BIN_ENTRIES + 1];
	dgInt32 m_enumerator;
	dgInt32 m_memoryUsed;
	dgInt32 m_isInList;

	public:
	static dgInt32 m_lock;
};

class dgStackMemoryAllocator: public dgMemoryAllocator
{
	public:
	DG_INLINE dgStackMemoryAllocator(void* const pool, dgInt32 size)
		:dgMemoryAllocator (false)
		,m_pool((dgInt8*) pool)
		,m_index(0)
		,m_size(size)
	{
	}

	DG_INLINE ~dgStackMemoryAllocator()
	{
	}

	DG_INLINE void* Alloc(dgInt32 size)
	{
		dgInt8* const ptr = (dgInt8*) (reinterpret_cast<uintptr_t>(m_pool + m_index + 15) & -0x10);
		m_index = dgInt32 (ptr - m_pool) + size;
		dgAssert (m_index < m_size);
		return ptr;
	}

	DG_INLINE void* Malloc(dgInt32 size)
	{
		return Alloc(size);
	}

	DG_INLINE void* MallocLow(dgInt32 size, dgInt32 alignment)
	{
		return Alloc(size);
	}

	DG_INLINE void Free(void* const retPtr)
	{
	}

	DG_INLINE void FreeLow(void* const retPtr)
	{
	}

	dgInt8* m_pool;
	dgInt32 m_index;
	dgInt32 m_size;
};

#endif


text:
flexcamOSC::flexcamOSC()
{
}

//--------------------------------------------------------------
flexcamOSC::flexcamOSC(string ipAddress, int port, string blobName)
{
	oscSendIP = ipAddress;
	oscSendPort = port;
	oscBlobName = "/" + blobName;
	transmitSocket = new UdpTransmitSocket( IpEndpointName(oscSendIP.c_str(), oscSendPort) );
}

//--------------------------------------------------------------
flexcamOSC::~flexcamOSC()
{
	if (transmitSocket != NULL) delete transmitSocket;
}

//--------------------------------------------------------------
void flexcamOSC::messageBlobSend(flexcamBlob myBlob)
{
	char buffer[OUTPUT_BUFFER_SIZE];
	osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );

	p << osc::BeginBundleImmediate; p << osc::BeginMessage(oscBlobName.c_str());
		p << (float)myBlob.id << (float)myBlob.centroidX << (float)myBlob.centroidY;
		p << (float)myBlob.centroidXDiff << (float)myBlob.centroidYDiff << (float)myBlob.centroidDiffDist;
		p << (float)myBlob.aspectRatio << (float)myBlob.areaROI << (float)myBlob.areaDiffROI;
		p << (float)myBlob.angle << (float)myBlob.angleDiff << (float)myBlob.lifetime << (float)myBlob.blobActive;
	p << osc::EndMessage; p << osc::EndBundle;
	transmitSocket->Send( p.Data(), p.Size() );
}

//--------------------------------------------------------------
void flexcamOSC::messageActivitySend(string header, int number, float activityLevel)
{
	char buffer[OUTPUT_BUFFER_SIZE];
	osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );

	p << osc::BeginBundleImmediate; p << osc::BeginMessage(header.c_str());
		p << (float)number << activityLevel;
	p << osc::EndMessage; p << osc::EndBundle;
    transmitSocket->Send( p.Data(), p.Size() );
}

//--------------------------------------------------------------
void flexcamOSC::messageAllActivitySend(float activityLevel)
{
	char buffer[OUTPUT_BUFFER_SIZE];
	osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );

	p << osc::BeginBundleImmediate; p << osc::BeginMessage("all");
		p << activityLevel;
	p << osc::EndMessage; p << osc::EndBundle;
    transmitSocket->Send( p.Data(), p.Size() );
}


text:
<form action="http://catalog.library.miami.edu/search/" method="get" name="search" id="search" class="pure-form" target="_blank">

<input type="hidden" id="iiiFormHandle_1">

<fieldset>

<legend>Find items in the Catalog</legend>

<select name="searchtype" id="searchtype" style="vertical-align:middle;">
        <option value="X" selected="selected">Keyword</option>
        <option value="t">Title</option>
        <option value="a">Author</option>
        <option value="d">Subject</option>
        <option value="c">LC Call Number</option>
        <option value="l">Local Call Number</option>
        <option value="g">SuDocs Number</option>
        <option value="i">ISSN . ISBN Number</option>
        <option value="o">OCLC Number</option>
        <option value="m">Music Publisher Number</option>
</select>
<input type="hidden" name="SORT" id="SORT" value="D">

<input maxlength="75" name="searcharg">

<input type="hidden" id="iiiFormHandle_1">

Limit search to:

<select name="searchscope" id="searchscope">
    <option value="10"> Architecture Library</option>
        <option value="14"> Audiobooks</option>
        <option value="12"> Books (Print)</option>
        <option value="7"> Cuban Heritage Collection</option>
        <option value="17"> DVDs/Videos </option>
        <option value="13"> E-Books</option>
        <option value="4"> Government Documents & Maps</option>
        <option value="2"> Internet Resources</option>
        <option value="1"> Journals & Other Serials</option>
        <option value="9"> Marine Science Library</option>
        <option value="15"> Music CDs</option>
        <option value="8"> Music Library</option>
        <option value="16"> Music Recordings</option>
        <option value="3"> Richter Reference</option>
        <option value="18"> Music Scores</option>
        <option value="6"> Special Collections & UM Archives</option>
        <option value="19"> E-Music/E-Audio/E-Video</option>
        <option value="11" selected="selected"> View Entire Collection</option>
  </select>

<input name="Search" type="submit" id="Search" value="Search" class="pure-button pure-button-pluslet">

Advanced Search

</fieldset>

</form>


text:
class CefDownloadHandlerCToCpp
    : public CefCToCpp<CefDownloadHandlerCToCpp, CefDownloadHandler,
        cef_download_handler_t> {
 public:
  explicit CefDownloadHandlerCToCpp(cef_download_handler_t* str)
      : CefCToCpp<CefDownloadHandlerCToCpp, CefDownloadHandler,
          cef_download_handler_t>(str) {}
  virtual ~CefDownloadHandlerCToCpp() {}

  // CefDownloadHandler methods
  virtual bool ReceivedData(void* data, int data_size) OVERRIDE;
  virtual void Complete() OVERRIDE;
};

#endif  // BUILDING_CEF_SHARED
#endif  // CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_HANDLER_CTOCPP_H_


text:
package com.hearthsim.test.spell;

import com.hearthsim.card.Card;
import com.hearthsim.card.basic.minion.IronfurGrizzly;
import com.hearthsim.card.basic.spell.KillCommand;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.minion.MinionMock;
import com.hearthsim.exception.HSException;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.tree.HearthTreeNode;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

public class TestKillCommand {

    private HearthTreeNode board;
    private PlayerModel currentPlayer;
    private PlayerModel waitingPlayer;

    private static final byte mana = 2;
    private static final byte attack0 = 5;
    private static final byte health0 = 3;
    private static final byte health1 = 7;

    @Before
    public void setup() throws HSException {
        board = new HearthTreeNode(new BoardModel());
        currentPlayer = board.data_.getCurrentPlayer();
        waitingPlayer = board.data_.getWaitingPlayer();

        Minion minion0_0 = new MinionMock("" + 0, mana, attack0, health0, attack0, health0, health0);
        Minion minion0_1 = new MinionMock("" + 0, mana, attack0, (byte)(health1 - 1), attack0, health1, health1);
        Minion minion1_0 = new MinionMock("" + 0, mana, attack0, health0, attack0, health0, health0);
        Minion minion1_1 = new MinionMock("" + 0, mana, attack0, (byte)(health1 - 1), attack0, health1, health1);

        board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, minion0_0);
        board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, minion0_1);

        board.data_.placeMinion(PlayerSide.WAITING_PLAYER, minion1_0);
        board.data_.placeMinion(PlayerSide.WAITING_PLAYER, minion1_1);

        Card fb = new KillCommand();
        currentPlayer.placeCardHand(fb);

        currentPlayer.setMana((byte) 7);
        waitingPlayer.setMana((byte) 4);

        currentPlayer.setMaxMana((byte) 7);
        waitingPlayer.setMaxMana((byte) 4);
    }

    @Test
    public void test0() throws HSException {
        Card theCard = currentPlayer.getHand().get(0);
        HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, 0, board);

        assertFalse(ret == null);

        assertEquals(currentPlayer.getHand().size(), 0);
        assertEquals(currentPlayer.getNumMinions(), 2);
        assertEquals(waitingPlayer.getNumMinions(), 2);
        assertEquals(currentPlayer.getMana(), 4);
        assertEquals(waitingPlayer.getMana(), 4);
        assertEquals(currentPlayer.getHero().getHealth(), 30);
        assertEquals(waitingPlayer.getHero().getHealth(), 27);
        assertEquals(currentPlayer.getCharacter(1).getHealth(), health0);
        assertEquals(currentPlayer.getCharacter(2).getHealth(), health1 - 1);
        assertEquals(waitingPlayer.getCharacter(1).getHealth(), health0);
        assertEquals(waitingPlayer.getCharacter(2).getHealth(), health1 - 1);
    }

    @Test
    public void test1() throws HSException {
        Card theCard = currentPlayer.getHand().get(0);
        HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, 1, board);

        assertFalse(ret == null);

        assertEquals(currentPlayer.getHand().size(), 0);
        assertEquals(currentPlayer.getNumMinions(), 2);
        assertEquals(waitingPlayer.getNumMinions(), 1);
        assertEquals(currentPlayer.getMana(), 4);
        assertEquals(waitingPlayer.getMana(), 4);
        assertEquals(currentPlayer.getHero().getHealth(), 30);
        assertEquals(waitingPlayer.getHero().getHealth(), 30);
        assertEquals(currentPlayer.getCharacter(1).getHealth(), health0);
        assertEquals(currentPlayer.getCharacter(2).getHealth(), health1 - 1);
        assertEquals(waitingPlayer.getCharacter(1).getHealth(), health1 - 1);
    }

    @Test
    public void test2() throws HSException {
        board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new IronfurGrizzly());
        Card theCard = currentPlayer.getHand().get(0);
        HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, 0, board);

        assertFalse(ret == null);

        assertEquals(currentPlayer.getHand().size(), 0);
        assertEquals(currentPlayer.getNumMinions(), 3);
        assertEquals(waitingPlayer.getNumMinions(), 2);
        assertEquals(currentPlayer.getMana(), 4);
        assertEquals(waitingPlayer.getMana(), 4);
        assertEquals(currentPlayer.getHero().getHealth(), 30);
        assertEquals(waitingPlayer.getHero().getHealth(), 25);
        assertEquals(currentPlayer.getCharacter(1).getHealth(), health0);
        assertEquals(currentPlayer.getCharacter(2).getHealth(), health1 - 1);
        assertEquals(currentPlayer.getCharacter(3).getHealth(), 3);
        assertEquals(waitingPlayer.getCharacter(1).getHealth(), health0);
        assertEquals(waitingPlayer.getCharacter(2).getHealth(), health1 - 1);
    }
}


text:
package tarball

import (
	"archive/tar"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"sync"

	"github.com/google/go-containerregistry/name"
	"github.com/google/go-containerregistry/v1"
	"github.com/google/go-containerregistry/v1/partial"
	"github.com/google/go-containerregistry/v1/types"
	"github.com/google/go-containerregistry/v1/v1util"
)

type image struct {
	path          string
	td            *tarDescriptor
	config        []byte
	imgDescriptor *singleImageTarDescriptor

	tag *name.Tag
}

type uncompressedImage struct {
	*image
}

type compressedImage struct {
	*image
	manifestLock sync.Mutex // Protects manifest
	manifest     *v1.Manifest
}

// Image exposes an image from the tarball at the provided path.
func Image(path string, tag *name.Tag) (v1.Image, error) {
	img := &image{
		path: path,
		tag:  tag,
	}
	if err := img.loadTarDescriptorAndConfig(); err != nil {
		return nil, err
	}

	// Peek at the first layer and see if it's compressed.
	compressed, err := img.areLayersCompressed()
	if err != nil {
		return nil, err
	}
	if compressed {
		c := compressedImage{
			image: img,
		}
		return partial.CompressedToImage(&c)
	}

	uc := uncompressedImage{
		image: img,
	}
	return partial.UncompressedToImage(&uc)
}

func (i *image) MediaType() (types.MediaType, error) {
	return types.DockerManifestSchema2, nil
}

// singleImageTarDescriptor is the struct used to represent a single image inside a `docker save` tarball.
type singleImageTarDescriptor struct {
	Config   string
	RepoTags []string
	Layers   []string
}

// tarDescriptor is the struct used inside the `manifest.json` file of a `docker save` tarball.
type tarDescriptor []singleImageTarDescriptor

func (td tarDescriptor) findSpecifiedImageDescriptor(tag *name.Tag) (*singleImageTarDescriptor, error) {
	if tag == nil {
		if len(td) != 1 {
			return nil, errors.New("tarball must contain only a single image to be used with tarball.Image")
		}
		return &(td)[0], nil
	}
	for _, img := range td {
		for _, tagStr := range img.RepoTags {
			repoTag, err := name.NewTag(tagStr, name.WeakValidation)
			if err != nil {
				return nil, err
			}

			// Compare the resolved names, since there are several ways to specify the same tag.
			if repoTag.Name() == tag.Name() {
				return &img, nil
			}
		}
	}
	return nil, fmt.Errorf("tag %s not found in tarball", tag)
}

func (i *image) areLayersCompressed() (bool, error) {
	if len(i.imgDescriptor.Layers) == 0 {
		return false, errors.New("0 layers found in image")
	}
	layer := i.imgDescriptor.Layers[0]
	blob, err := extractFileFromTar(i.path, layer)
	if err != nil {
		return false, err
	}
	defer blob.Close()
	return v1util.IsGzipped(blob)
}

func (i *image) loadTarDescriptorAndConfig() error {
	td, err := extractFileFromTar(i.path, "manifest.json")
	if err != nil {
		return err
	}
	defer td.Close()

	if err := json.NewDecoder(td).Decode(&i.td); err != nil {
		return err
	}

	i.imgDescriptor, err = i.td.findSpecifiedImageDescriptor(i.tag)
	if err != nil {
		return err
	}

	cfg, err := extractFileFromTar(i.path, i.imgDescriptor.Config)
	if err != nil {
		return err
	}
	defer cfg.Close()

	i.config, err = ioutil.ReadAll(cfg)
	if err != nil {
		return err
	}
	return nil
}

func (i *image) RawConfigFile() ([]byte, error) {
	return i.config, nil
}

// tarFile represents a single file inside a tar. Closing it closes the tar itself.
type tarFile struct {
	io.Reader
	io.Closer
}

func extractFileFromTar(tarPath string, filePath string) (io.ReadCloser, error) {
	f, err := os.Open(tarPath)
	if err != nil {
		return nil, err
	}
	tf := tar.NewReader(f)
	for {
		hdr, err := tf.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
		if hdr.Name == filePath {
			return tarFile{
				Reader: tf,
				Closer: f,
			}, nil
		}
	}
	return nil, fmt.Errorf("file %s not found in tar", filePath)
}

// uncompressedLayerFromTarball implements partial.UncompressedLayer
type uncompressedLayerFromTarball struct {
	diffID   v1.Hash
	tarPath  string
	filePath string
}

// DiffID implements partial.UncompressedLayer
func (ulft *uncompressedLayerFromTarball) DiffID() (v1.Hash, error) {
	return ulft.diffID, nil
}

// Uncompressed implements partial.UncompressedLayer
func (ulft *uncompressedLayerFromTarball) Uncompressed() (io.ReadCloser, error) {
	return extractFileFromTar(ulft.tarPath, ulft.filePath)
}

func (i *uncompressedImage) LayerByDiffID(h v1.Hash) (partial.UncompressedLayer, error) {
	cfg, err := partial.ConfigFile(i)
	if err != nil {
		return nil, err
	}
	for idx, diffID := range cfg.RootFS.DiffIDs {
		if diffID == h {
			return &uncompressedLayerFromTarball{
				diffID:   diffID,
				tarPath:  i.path,
				filePath: i.imgDescriptor.Layers[idx],
			}, nil
		}
	}
	return nil, fmt.Errorf("diff id %q not found", h)
}

func (c *compressedImage) Manifest() (*v1.Manifest, error) {
	c.manifestLock.Lock()
	defer c.manifestLock.Unlock()
	if c.manifest != nil {
		return c.manifest, nil
	}

	b, err := c.RawConfigFile()
	if err != nil {
		return nil, err
	}

	cfgHash, cfgSize, err := v1.SHA256(v1util.NopReadCloser(bytes.NewBuffer(b)))
	if err != nil {
		return nil, err
	}

	c.manifest = &v1.Manifest{
		SchemaVersion: 2,
		MediaType:     types.DockerManifestSchema2,
		Config: v1.Descriptor{
			MediaType: types.DockerConfigJSON,
			Size:      cfgSize,
			Digest:    cfgHash,
		},
	}

	for _, p := range c.imgDescriptor.Layers {
		l, err := extractFileFromTar(c.path, p)
		if err != nil {
			return nil, err
		}
		sha, size, err := v1.SHA256(l)
		if err != nil {
			return nil, err
		}
		c.manifest.Layers = append(c.manifest.Layers, v1.Descriptor{
			MediaType: types.DockerLayer,
			Size:      size,
			Digest:    sha,
		})
	}
	return c.manifest, nil
}

func (c *compressedImage) RawManifest() ([]byte, error) {
	return partial.RawManifest(c)
}

// compressedLayerFromTarball implements partial.CompressedLayer
type compressedLayerFromTarball struct {
	digest   v1.Hash
	tarPath  string
	filePath string
}

// DiffID implements partial.CompressedLayer
func (clft *compressedLayerFromTarball) Digest() (v1.Hash, error) {
	return clft.digest, nil
}

// Compressed implements partial.CompressedLayer
func (clft *compressedLayerFromTarball) Compressed() (io.ReadCloser, error) {
	return extractFileFromTar(clft.tarPath, clft.filePath)
}

// Size implements partial.CompressedLayer
func (clft *compressedLayerFromTarball) Size() (int64, error) {
	r, err := clft.Compressed()
	if err != nil {
		return -1, err
	}
	_, i, err := v1.SHA256(r)
	return i, err
}

func (c *compressedImage) LayerByDigest(h v1.Hash) (partial.CompressedLayer, error) {
	m, err := c.Manifest()
	if err != nil {
		return nil, err
	}
	for i, l := range m.Layers {
		if l.Digest == h {
			fp := c.imgDescriptor.Layers[i]
			return &compressedLayerFromTarball{
				digest:   h,
				tarPath:  c.path,
				filePath: fp,
			}, nil
		}
	}
	return nil, fmt.Errorf("blob %v not found", h)
}


text:
New Building

            Home

            Building

            New Building

        <form data-ng-submit="create()" novalidate>
          <fieldset>

                Total Build Up Area

                  <input type="Number" data-ng-model="totalBuildUpArea" id="totalBuildUpArea" class="form-control" placeholder="" required />

                Purpose Of Floor

                  <input type="Text" data-ng-model="purposeOfFloor" id="purposeOfFloor" class="form-control" placeholder="" required />

                Block Name

                  <input type="Text" data-ng-model="blockName" id="blockName" class="form-control" placeholder="" required />

                <input type="submit" class="btn btn-primary" />

          </fieldset>
        </form>