text stringlengths 1 1.05M |
|---|
<reponame>thomastay/collectable<gh_stars>100-1000
import test from 'ava';
import { isImmutable } from '@collectable/core';
import { appendArray, empty, set, updateList } from '../../src';
import { arrayFrom } from '../../src/internals';
// test('returns the same list if no changes are made', t => {
// const list = empty<string>();
// const list1 = updateList(list => {}, list);
// t.is(list1, list);
// });
test('treats the inner list as mutable', t => {
const list = empty<string>();
const list1 = updateList(list => {
t.false(isImmutable(list));
appendArray(['X', 'Y', 'Z'], list);
set(1, 'K', list);
}, list);
t.true(isImmutable(list1));
t.deepEqual(arrayFrom(list1), ['X', 'K', 'Z']);
});
|
<reponame>Ashindustry007/competitive-programming
// https://open.kattis.com/problems/dejavu
#include<bits/stdc++.h>
using namespace std;
using ii=tuple<int,int>;
using vii=vector<ii>;
using ll=long long;
const int N=100000;
ll X[N+1],Y[N+1];
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
ll n,x,y;
cin>>n;
vii a(n);
for(int i=0;i<n;i++){
cin>>x>>y;
a[i]={x,y};
X[x]++;
Y[y]++;
}
ll c=0;
for(ii p:a){
tie(x,y)=p;
c+=(Y[y]-1)*(X[x]-1);
}
cout<<c<<"\n";
}
|
<filename>src/pages/contact.js
import React from 'react'
import Layout from '../components/layout'
const contact = () => {
return (
<Layout>
<div class="container mx-auto">
<div class="text-white text-3xl uppercase">
Contact
</div>
</div>
</Layout>
)
}
export default contact
|
<filename>quiz/code0.js
gdjs.IntroCode = {};
gdjs.IntroCode.GDQObjects1= [];
gdjs.IntroCode.GDQObjects2= [];
gdjs.IntroCode.GDWrongAnswerObjects1= [];
gdjs.IntroCode.GDWrongAnswerObjects2= [];
gdjs.IntroCode.GDWelcomeObjects1= [];
gdjs.IntroCode.GDWelcomeObjects2= [];
gdjs.IntroCode.GDFineprintObjects1= [];
gdjs.IntroCode.GDFineprintObjects2= [];
gdjs.IntroCode.GDBEGINObjects1= [];
gdjs.IntroCode.GDBEGINObjects2= [];
gdjs.IntroCode.conditionTrue_0 = {val:false};
gdjs.IntroCode.condition0IsTrue_0 = {val:false};
gdjs.IntroCode.condition1IsTrue_0 = {val:false};
gdjs.IntroCode.condition2IsTrue_0 = {val:false};
gdjs.IntroCode.mapOfGDgdjs_46IntroCode_46GDBEGINObjects1Objects = Hashtable.newFrom({"BEGIN": gdjs.IntroCode.GDBEGINObjects1});gdjs.IntroCode.eventsList0xb2158 = function(runtimeScene) {
{
gdjs.IntroCode.condition0IsTrue_0.val = false;
{
gdjs.IntroCode.condition0IsTrue_0.val = gdjs.evtTools.runtimeScene.sceneJustBegins(runtimeScene);
}if (gdjs.IntroCode.condition0IsTrue_0.val) {
{runtimeScene.getGame().getVariables().getFromIndex(1).setNumber(0);
}{runtimeScene.getGame().getVariables().getFromIndex(2).setNumber(0);
}{runtimeScene.getGame().getVariables().getFromIndex(3).setNumber(0);
}{runtimeScene.getGame().getVariables().getFromIndex(4).setNumber(0);
}{runtimeScene.getGame().getVariables().getFromIndex(5).setNumber(0);
}{runtimeScene.getGame().getVariables().getFromIndex(6).setNumber(0);
}{runtimeScene.getGame().getVariables().getFromIndex(7).setNumber(0);
}{runtimeScene.getGame().getVariables().getFromIndex(8).setNumber(0);
}}
}
{
gdjs.IntroCode.GDBEGINObjects1.createFrom(runtimeScene.getObjects("BEGIN"));
gdjs.IntroCode.condition0IsTrue_0.val = false;
gdjs.IntroCode.condition1IsTrue_0.val = false;
{
gdjs.IntroCode.condition0IsTrue_0.val = gdjs.evtTools.input.isMouseButtonPressed(runtimeScene, "Left");
}if ( gdjs.IntroCode.condition0IsTrue_0.val ) {
{
gdjs.IntroCode.condition1IsTrue_0.val = gdjs.evtTools.input.cursorOnObject(gdjs.IntroCode.mapOfGDgdjs_46IntroCode_46GDBEGINObjects1Objects, runtimeScene, true, false);
}}
if (gdjs.IntroCode.condition1IsTrue_0.val) {
{gdjs.evtTools.runtimeScene.replaceScene(runtimeScene, "QuestionEngine", true);
}}
}
}; //End of gdjs.IntroCode.eventsList0xb2158
gdjs.IntroCode.func = function(runtimeScene) {
runtimeScene.getOnceTriggers().startNewFrame();
gdjs.IntroCode.GDQObjects1.length = 0;
gdjs.IntroCode.GDQObjects2.length = 0;
gdjs.IntroCode.GDWrongAnswerObjects1.length = 0;
gdjs.IntroCode.GDWrongAnswerObjects2.length = 0;
gdjs.IntroCode.GDWelcomeObjects1.length = 0;
gdjs.IntroCode.GDWelcomeObjects2.length = 0;
gdjs.IntroCode.GDFineprintObjects1.length = 0;
gdjs.IntroCode.GDFineprintObjects2.length = 0;
gdjs.IntroCode.GDBEGINObjects1.length = 0;
gdjs.IntroCode.GDBEGINObjects2.length = 0;
gdjs.IntroCode.eventsList0xb2158(runtimeScene);
return;
}
gdjs['IntroCode'] = gdjs.IntroCode;
|
<reponame>dbvis-ukon/JSONCrush<gh_stars>0
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var JSONCrush_1 = require("./JSONCrush");
exports.JSONCrush = JSONCrush_1.JSONCrush;
var JSONUncrush_1 = require("./JSONUncrush");
exports.JSONUncrush = JSONUncrush_1.JSONUncrush;
|
export { default } from './TodoHeadTitle';
|
<reponame>EmilRyberg/P5BinPicking<filename>orientation_detector.py
import tensorflow as tf
import numpy as np
import PIL.Image as pimg
config = tf.ConfigProto(intra_op_parallelism_threads=4,
inter_op_parallelism_threads=4,
allow_soft_placement=True,
device_count = {'CPU' : 1,
'GPU' : 0})
session = tf.Session(config=config)
tf.compat.v1.keras.backend.set_session(session)
class OrientationDetector:
def __init__(self, model_path):
self.model = tf.keras.models.load_model(model_path)
def is_facing_right(self, image_np_array, threshold=0.5):
pil_image = pimg.fromarray(image_np_array, 'RGB')
resized_image = pil_image.resize((224, 224))
resized_image_np = np.array(resized_image)
resized_image_np = np.expand_dims(resized_image_np, axis=0) / 255
prediction = self.model.predict(resized_image_np)
if prediction > threshold:
return True
return False
|
<reponame>SoftwareDevEngResearch/FRIDGe<gh_stars>1-10
import fridge.Constituent.Constituent as Constituent
import numpy as np
class FuelUniverse(Constituent.Constituent):
"""Creates the lattice for the fuel pin, bond, clad, and coolant.
This lattice gets repeated for the number of pins present, and all excess pins are BlankCoolant."""
def __init__(self, fuelUniverseInfo):
self.fuelUniverse = fuelUniverseInfo[0]
self.blankUniverse = fuelUniverseInfo[1]
self.numPins = fuelUniverseInfo[2]
self.cellNum = fuelUniverseInfo[3]
self.blankCellNum = fuelUniverseInfo[4]
self.latticeUniverse = fuelUniverseInfo[5]
self.cellCard = self.getCellCard()
def getCellCard(self):
cellCard = "{} 0 -{} lat=2 u={} imp:n=1\n".format(self.cellNum, self.blankCellNum, self.latticeUniverse)
rings = int(max(np.roots([1, -1, -2*(self.numPins-1)/6])))
lattice_array = np.zeros((rings * 2 + 1, rings * 2 + 1))
for x in range(rings * 2 + 1):
for y in range(rings * 2 + 1):
if x == 0 or x == 2 * rings:
lattice_array[x][y] = self.blankUniverse
elif x < (rings + 1):
if y < (rings + 1 - x) or y == (2 * rings):
lattice_array[x][y] = self.blankUniverse
else:
lattice_array[x][y] = self.fuelUniverse
else:
if y > (2 * rings - (x - rings + 1)) or y == 0:
lattice_array[x][y] = self.blankUniverse
else:
lattice_array[x][y] = self.fuelUniverse
cellCard += " fill=-{}:{} -{}:{} 0:0\n ".format(rings, rings, rings, rings)
row_jump = 0
for row in lattice_array:
for lat_iter, element in enumerate(row):
if (row_jump+1) % 10 == 0:
cellCard += " {}\n ".format(int(element))
else:
cellCard += " {}".format(int(element))
row_jump += 1
return cellCard
|
# functional.py
import itertools
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(itertools.islice(iterable, n))
|
git checkout master && \
git pull origin master && \
npm version patch && \
git tag -l && \
echo Publishing in 10s: Ctrl-C to cancel && \
sleep 10 && \
npm publish && \
git push --tags origin master
|
#!/bin/sh
scp * root@192.168.1.3:
ssh -t -t 192.168.1.3 -l root << 'ENDSSH'
rm -rf "/var/lib/bluetooth/*"
hciconfig hci0 reset
python test1.py
sleep 1
ENDSSH
|
<reponame>nyanmisaka/media-driver
/*
* Copyright (c) 2019-2021, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file policy.h
//! \brief Defines the common interface for vp features manager
//! \details The policy is further sub-divided by vp type
//! this file is for the base interface which is shared by all components.
//!
#ifndef __POLICY_H__
#define __POLICY_H__
#include "media_feature_manager.h"
#include "vp_utils.h"
#include "vp_pipeline_common.h"
#include "vp_allocator.h"
#include "vp_feature_caps.h"
#include "hw_filter.h"
#include "sw_filter_pipe.h"
#include "vp_resource_manager.h"
#include <map>
namespace vp
{
#define ENGINE_MUST_MASK(supported) (supported & 0x02)
#define ENGINE_SUPPORT_MASK(supported) (supported & 0x3)
#define ENGINE_MUST(supported) (supported << 1)
#define FEATURE_TYPE_EXECUTE(feature, engine) FeatureType##feature##On##engine
class VpInterface;
class Policy
{
public:
Policy(VpInterface &vpInterface);
virtual ~Policy();
MOS_STATUS CreateHwFilter(SwFilterPipe &subSwFilterPipe, HwFilter *&pFilter);
MOS_STATUS Initialize();
//!
//! \brief Check whether VEBOX-SFC Format Supported
//! \details Check whether VEBOX-SFC Format Supported.
//! \param inputFormat
//! [in] Format of Input Frame
//! \param outputFormat
//! [in] Format of Output Frame
//! \return bool
//! Return true if supported, otherwise failed
//!
bool IsVeboxSfcFormatSupported(MOS_FORMAT formatInput, MOS_FORMAT formatOutput);
protected:
virtual MOS_STATUS RegisterFeatures();
virtual MOS_STATUS GetExecutionCapsForSingleFeature(FeatureType featureType, SwFilterSubPipe& swFilterPipe);
virtual MOS_STATUS UpdateExeCaps(SwFilter* feature, VP_EXECUTE_CAPS& caps, EngineType Type);
virtual MOS_STATUS BuildVeboxSecureFilters(SwFilterPipe& featurePipe, VP_EXECUTE_CAPS& caps, HW_FILTER_PARAMS& params);
MOS_STATUS BuildExecutionEngines(SwFilterSubPipe &swFilterPipe);
MOS_STATUS GetHwFilterParam(SwFilterPipe& subSwFilterPipe, HW_FILTER_PARAMS& params);
MOS_STATUS ReleaseHwFilterParam(HW_FILTER_PARAMS ¶ms);
MOS_STATUS InitExecuteCaps(VP_EXECUTE_CAPS &caps, VP_EngineEntry &engineCapsInputPipe, VP_EngineEntry &engineCapsOutputPipe);
MOS_STATUS GetExecuteCaps(SwFilterPipe& subSwFilterPipe, HW_FILTER_PARAMS& params);
MOS_STATUS GetCSCExecutionCapsHdr(SwFilter *hdr, SwFilter *csc);
MOS_STATUS GetCSCExecutionCapsDi(SwFilter* feature);
MOS_STATUS GetCSCExecutionCaps(SwFilter* feature);
MOS_STATUS GetScalingExecutionCaps(SwFilter* feature);
bool IsSfcRotationSupported(FeatureParamRotMir *rotationParams);
MOS_STATUS GetRotationExecutionCaps(SwFilter* feature);
MOS_STATUS GetDenoiseExecutionCaps(SwFilter* feature);
MOS_STATUS GetSteExecutionCaps(SwFilter* feature);
MOS_STATUS GetTccExecutionCaps(SwFilter* feature);
MOS_STATUS GetProcampExecutionCaps(SwFilter* feature);
MOS_STATUS GetHdrExecutionCaps(SwFilter *feature);
MOS_STATUS GetExecutionCaps(SwFilter* feature);
MOS_STATUS GetDeinterlaceExecutionCaps(SwFilter* feature);
MOS_STATUS GetColorFillExecutionCaps(SwFilter* feature);
MOS_STATUS GetAlphaExecutionCaps(SwFilter* feature);
MOS_STATUS BuildExecuteCaps(SwFilterPipe& featurePipe, VP_EXECUTE_CAPS &caps, VP_EngineEntry &engineCapsInputPipe, VP_EngineEntry &engineCapsOutputPipe,
bool &isSingleSubPipe, uint32_t &selectedPipeIndex);
MOS_STATUS BypassVeboxFeatures(SwFilterSubPipe *featureSubPipe, VP_EngineEntry &engineCaps);
MOS_STATUS GetInputPipeEngineCaps(SwFilterPipe& featurePipe, VP_EngineEntry &engineCapsInputPipe,
SwFilterSubPipe *&singlePipeSelected, bool &isSingleSubPipe, uint32_t &selectedPipeIndex);
// inputPipeSelected != nullptr for single input pipe case, otherwise, it's multi-input pipe case.
MOS_STATUS GetOutputPipeEngineCaps(SwFilterPipe& featurePipe, VP_EngineEntry &engineCaps, SwFilterSubPipe *inputPipeSelected);
MOS_STATUS UpdateFeatureTypeWithEngine(std::vector<int> &layerIndexes, SwFilterPipe& featurePipe, VP_EXECUTE_CAPS& caps,
bool isolatedFeatureSelected, bool outputPipeNeeded);
MOS_STATUS UpdateFeatureTypeWithEngineSingleLayer(SwFilterSubPipe *featureSubPipe, VP_EXECUTE_CAPS& caps, bool isolatedFeatureSelected);
MOS_STATUS LayerSelectForProcess(std::vector<int> &layerIndexes, SwFilterPipe& featurePipe, bool isSingleSubPipe, uint32_t pipeIndex, VP_EXECUTE_CAPS& caps);
MOS_STATUS UpdateFeaturePipe(SwFilterPipe &featurePipe, uint32_t pipeIndex, SwFilterPipe &executedFilters, uint32_t executePipeIndex,
bool isInputPipe, VP_EXECUTE_CAPS& caps);
MOS_STATUS UpdateFeaturePipeSingleLayer(SwFilterPipe &featurePipe, uint32_t pipeIndex, SwFilterPipe &executedFilters, uint32_t executePipeIndex, VP_EXECUTE_CAPS& caps);
MOS_STATUS UpdateFeatureOutputPipe(std::vector<int> &layerIndexes, SwFilterPipe &featurePipe, SwFilterPipe &executedFilters, VP_EXECUTE_CAPS& caps);
MOS_STATUS BuildFilters(SwFilterPipe& subSwFilterPipe, HW_FILTER_PARAMS& params);
MOS_STATUS BuildExecuteFilter(SwFilterPipe& swFilterPipe, std::vector<int> &layerIndexes, VP_EXECUTE_CAPS& caps, HW_FILTER_PARAMS& params);
MOS_STATUS BuildExecuteHwFilter(VP_EXECUTE_CAPS& caps, HW_FILTER_PARAMS& params);
MOS_STATUS SetupExecuteFilter(SwFilterPipe& featurePipe, std::vector<int> &layerIndexes, VP_EXECUTE_CAPS& caps, HW_FILTER_PARAMS& params);
MOS_STATUS SetupFilterResource(SwFilterPipe& featurePipe, std::vector<int> &layerIndexes, VP_EXECUTE_CAPS& caps, HW_FILTER_PARAMS& params);
virtual MOS_STATUS AddFiltersBasedOnCaps(
SwFilterPipe& featurePipe,
uint32_t pipeIndex,
VP_EXECUTE_CAPS& caps,
SwFilterPipe& executedFilters,
uint32_t executedPipeIndex);
MOS_STATUS AddNewFilterOnVebox(
SwFilterPipe& featurePipe,
uint32_t pipeIndex,
VP_EXECUTE_CAPS& caps,
SwFilterPipe& executedFilters,
uint32_t executedPipeIndex,
FeatureType featureType);
virtual MOS_STATUS GetCscParamsOnCaps(PVP_SURFACE surfInput, PVP_SURFACE surfOutput, VP_EXECUTE_CAPS &caps, FeatureParamCsc &cscParams);
MOS_STATUS AssignExecuteResource(VP_EXECUTE_CAPS& caps, HW_FILTER_PARAMS& params);
virtual bool IsExcludedFeatureForHdr(FeatureType feature);
virtual MOS_STATUS FilterFeatureCombination(SwFilterSubPipe *pipe);
virtual bool IsVeboxSecurePathEnabled(SwFilterPipe& subSwFilterPipe, VP_EXECUTE_CAPS& caps)
{
return false;
}
virtual MOS_STATUS UpdateSecureExecuteResource(SwFilterPipe& featurePipe, VP_EXECUTE_CAPS& caps, HW_FILTER_PARAMS& params)
{
return MOS_STATUS_SUCCESS;
}
virtual bool IsSecureResourceNeeded(VP_EXECUTE_CAPS& caps)
{
VP_FUNC_CALL();
return false;
}
std::map<FeatureType, PolicyFeatureHandler*> m_VeboxSfcFeatureHandlers;
std::map<FeatureType, PolicyFeatureHandler*> m_RenderFeatureHandlers;
std::vector<FeatureType> m_featurePool;
VpInterface &m_vpInterface;
VP_HW_CAPS m_hwCaps = {};
uint32_t m_bypassCompMode = 0;
bool m_initialized = false;
//!
//! \brief Check whether Alpha Supported
//! \details Check whether Alpha Supported.
//! \param scalingParams
//! [in] Params of Scaling
//! \return bool
//! Return true if enabled, otherwise failed
//!
virtual bool IsColorfillEnabled(FeatureParamScaling *scalingParams);
//!
//! \brief Check whether Colorfill Supported
//! \details Check whether Colorfill Supported.
//! \param scalingParams
//! [in] Params of Scaling
//! \return bool
//! Return true if enabled, otherwise failed
//!
virtual bool IsAlphaEnabled(FeatureParamScaling *scalingParams);
virtual bool IsHDRfilterExist(SwFilterSubPipe *inputPipe)
{
if (inputPipe)
{
SwFilter *feature = (SwFilter *)inputPipe->GetSwFilter(FeatureType(FeatureTypeHdr));
return feature != nullptr;
}
return false;
}
void PrintFeatureExecutionCaps(const char *name, VP_EngineEntry &engineCaps);
};
}
#endif // !__POLICY_H__ |
#!/bin/bash
set -ev
if [ "$TRAVIS_JDK_VERSION" == "oraclejdk8" ] && [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_BRANCH" == "master" ]; then
if [[ -z "$GH_TOKEN" ]]; then
echo -e "GH_TOKEN is not set"
exit 1
fi
echo -e "Publishing javadoc to gh-pages . . .\n"
cp -R -v ./target/apidocs $HOME/javadoc-latest
git config --global user.email "travis@travis-ci.org"
git config --global user.name "travis-ci"
# clone the gh-pages branch.
cd $HOME
rm -rf gh-pages
git clone --quiet --branch=gh-pages https://$GH_TOKEN@github.com/gwtbootstrap3/gwtbootstrap3-demo gh-pages > /dev/null
cd gh-pages
# remove the javadoc directories from git.
if [[ -d ./snapshot/extras-apidocs ]]; then
git rm -rf ./snapshot/extras-apidocs
fi
# copy the new javadoc to snapshot dir.
cp -Rf $HOME/javadoc-latest ./snapshot/extras-apidocs
git add -f .
git commit -m "Auto-push javadoc to gh-pages successful. (Travis build: $TRAVIS_BUILD_NUMBER)"
git push -fq origin gh-pages
echo -e "Published javadoc to gh-pages.\n"
fi
|
//Customer interface
public interface Customer {
public void placeOrder(String productName);
public void receiveOrder(String productName);
public void sendPayment(String productName);
public void receivePaymentConfirmation(String productName);
}
//Order class
class Order {
private String productName;
private int quantity;
private double price;
public Order(String productName, int quantity, double price) {
this.productName = productName;
this.quantity = quantity;
this.price = price;
}
public String getProductName() {
return productName;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
}
//CustomerOrderProcessor class
class CustomerOrderProcessor {
private Order order;
public CustomerOrderProcessor(Order order) {
this.order = order;
}
public void processOrder() {
System.out.println("Processing order…");
System.out.println("Product: " + order.getProductName());
System.out.println("Quantity: " + order.getQuantity());
System.out.println("Price: " + order.getPrice());
}
}
//Implement Customer interface
public class DefaultCustomer implements Customer {
public void placeOrder(String productName) {
System.out.println("Placing order for " + productName);
//place the order
}
public void receiveOrder(String productName) {
System.out.println("Receiving order for " + productName);
//receive the order
}
public void sendPayment(String productName) {
System.out.println("Sending payment for " + productName);
//send the payment
}
public void receivePaymentConfirmation(String productName) {
System.out.println("Receiving payment confirmation for " + productName);
//receive the payment confirmation
}
} |
import { FOREM_LINK, GITHUB_LINK, INSTAGRAM_LINK, REDDIT_LINK, TWITTER_LINK } from '../../Util/constant';
import { GitHubIcon, InstagramIcon, ForemIcon, RedditIcon, TwitterIcon } from '../../Util/icon';
const SocialLinks = () => {
return (
<div className="social-link">
<a href={GITHUB_LINK} className="social-link-item" title="GitHub" target="_blank" rel="noopener noreferrer">
<GitHubIcon></GitHubIcon>
</a>
<a href={INSTAGRAM_LINK} className="social-link-item" title="Instagram" target="_blank" rel="noopener noreferrer">
<InstagramIcon></InstagramIcon>
</a>
<a href={FOREM_LINK} className="social-link-item" title="DEV Community" target="_blank" rel="noopener noreferrer">
<ForemIcon></ForemIcon>
</a>
<a href={REDDIT_LINK} className="social-link-item" title="Reddit" target="_blank" rel="noopener noreferrer">
<RedditIcon></RedditIcon>
</a>
<a href={TWITTER_LINK} className="social-link-item" title="Twitter" target="_blank" rel="noopener noreferrer">
<TwitterIcon></TwitterIcon>
</a>
</div>
);
};
export default SocialLinks;
|
#! /bin/sh
set -euxo pipefail
gcloud auth activate-service-account --key-file="${GOOGLE_CREDENTIALS}" \
&& gcloud config set project "${GOOGLE_PROJECT}"
exec "$@" |
def print_fibonacci(n):
# first and second number of Fibonacci series
a = 0
b = 1
# check axis
if n < 0:
print("Incorrect input")
elif n == 0:
print(a)
elif n == 1:
print(a,b)
else:
print(a,b,end=" ")
# use the loop to generate and print remaining Fibonacci numbers
for i in range(2,n):
c = a + b
a = b
b = c
print(b,end=" ") |
Console.WriteLine("What is your age?");
int age = Int32.Parse(Console.ReadLine());
if (age < 0)
{
Console.WriteLine("Invalid age!");
} else if (age < 10)
{
Console.WriteLine("You are still a child!");
} else if (age >= 10 && age < 18)
{
Console.WriteLine("You are a teenager!");
} else if (age >= 18 && age < 65)
{
Console.WriteLine("You are an adult!");
} else if (age >= 65)
{
Console.WriteLine("You are a senior citizen!");
} |
package ru.job4j.musicplayer;
public interface Music {
void getMusic();
}
|
bool isPerfectCube(int num)
{
int root = round(cbrt(num));
return num == root * root * root;
} |
#!/bin/bash
DISPLAYNAME=$1
DATE=$2
FILENAME="$DATE.wellness.txt"
URL="https://connect.garmin.com/modern/proxy/userstats-service/wellness/daily/$DISPLAYNAME?fromDate=$DATE&untilDate=$DATE"
test -e $FILENAME ||wget -O $FILENAME $URL
|
/***********************************************************************
* Copyright (c) 2008-2080 pepstack.com, <EMAIL>
*
* ALL RIGHTS RESERVED.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************/
/**
* @filename ringbuf.h
* Multi-threads Safety Ring Buffer.
*
* This code has been tested OK on 20 threads!
*
* @author <NAME> <<EMAIL>>
* @version 1.0.0
* @create 2019-12-14 12:46:50
* @update 2020-06-30 11:32:10
*/
/**************************************************************
* Length(L) = 10, Read(R), Write(W), wrap factor=0,1
* Space(S)
*
* + R W + +
* |--+--+--+--+--+--+--+--+--+--|--+--+--+--+--+--+--+--+--+--|--+--+--+--
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
*
* S = L - (fL + W - R), W - R < L
* D = fL + W - R
*
* S > 0: writable
* D > 0: readable
*************************************************************/
/**************************************************************
*
* RW
* wrap=0 |----------|----------|---
* L L
* R W
* wrap=1 |----------|----------|---
*
* RW
* wrap=0 |----------|----------|---
*
* W R
* wrap=1 |----------|----------|---
*
* RW
* wrap=0 |----------|----------|---
*
* wrap(R, W, L) => ((R/L == W/L)? 0 : 1)
*
* A = W + 1 (or A = R + 1)
*
* W1 = (( A/L ) %2 ) * L + A % L
*************************************************************/
#ifndef _RINGBUF_H_
#define _RINGBUF_H_
#if defined(__cplusplus)
extern "C"
{
#endif
#include "uatomic.h"
#include "memapi.h"
#define RINGBUF_LENGTH_MAX 0x01FFFF
/* must > 1 */
#define RINGBUF_LENGTH_MIN 2
#define RINGBUF_RESTORE_STATE(Ro, Wo, L) \
int wrap = ((int)((Ro)/(L) == (Wo)/(L) ? 0 : 1)); \
int R = (Ro) % (L); \
int W = (Wo) % (L)
#define RINGBUF_NORMALIZE_OFFSET(Ao, L) \
((((Ao)/(L))%2)*L + (Ao)%(L))
#define ringbuf_elt_free(elt) free(elt)
typedef void (*ringbuf_elt_free_cb)(void *);
typedef struct
{
ringbuf_elt_free_cb free_cb;
size_t size;
char data[1];
} ringbuf_elt_t, *ringbuf_eltp;
static char * ringbuf_elt_new (size_t datasize, ringbuf_elt_free_cb free_cb, ringbuf_elt_t **eltp)
{
ringbuf_elt_t *elt = (ringbuf_elt_t *) mem_alloc_zero(1, sizeof(*elt) + datasize);
if (! elt) {
/* out memory */
exit(EXIT_FAILURE);
}
elt->free_cb = free_cb;
elt->size = datasize;
*eltp = elt;
return (char *) elt->data;
}
typedef struct
{
/* MT-safety Read Lock */
uatomic_int RLock;
/* MT-safety Write Lock */
uatomic_int WLock;
/* Write (push) index: 0, L-1 */
uatomic_int W;
/* Read (pop) index: 0, L-1 */
uatomic_int R;
/* Length of ring buffer */
int L;
/* Buffer */
ringbuf_elt_t *B[0];
} ringbuf_t;
/**
* public interface
*/
static ringbuf_t * ringbuf_init(int length)
{
ringbuf_t *rb;
if (length < RINGBUF_LENGTH_MIN) {
length = RINGBUF_LENGTH_MIN;
}
if (length > RINGBUF_LENGTH_MAX) {
length = RINGBUF_LENGTH_MAX;
}
/* new and initialize read and write index by 0 */
rb = (ringbuf_t *) mem_alloc_zero(1, sizeof(*rb) + sizeof(ringbuf_elt_t*) * length);
rb->L = length;
return rb;
}
static void ringbuf_uninit(ringbuf_t *rb)
{
uatomic_int_set(&rb->RLock, 1);
uatomic_int_set(&rb->WLock, 1);
ringbuf_elt_free_cb elt_free;
int i = rb->L;
while (i-- > 0) {
ringbuf_elt_t *elt = rb->B[i];
if (elt) {
rb->B[i] = NULL;
elt_free = elt->free_cb;
if (elt_free) {
elt_free(elt);
}
}
}
mem_free(rb);
}
static int ringbuf_push (ringbuf_t *rb, ringbuf_elt_t *elt)
{
if (! uatomic_int_comp_exch(&rb->WLock, 0, 1)) {
/* copy constant of length */
int L = rb->L;
/* original values of R, W */
int Ro = uatomic_int_get(&rb->R);
/* MUST get W after R */
int Wo = rb->W;
RINGBUF_RESTORE_STATE(Ro, Wo, L);
/* Sw = L - (f*L+W - R) */
if (L + R - wrap*L - W > 0) {
/* writable: Sw > 0 */
rb->B[W] = elt;
/* to next Write offset */
++Wo;
/* W = [0, 2L) */
W = RINGBUF_NORMALIZE_OFFSET(Wo, L);
uatomic_int_set(&rb->W, W);
/* push success */
uatomic_int_zero(&rb->WLock);
return 1;
}
uatomic_int_zero(&rb->WLock);
}
/* push failed */
return 0;
}
static int ringbuf_pop (ringbuf_t *rb, ringbuf_elt_t **eltp)
{
if (! uatomic_int_comp_exch(&rb->RLock, 0, 1)) {
int L = rb->L;
/* original values of W, R */
int Wo = uatomic_int_get(&rb->W);
/* MUST get R after W */
int Ro = rb->R;
RINGBUF_RESTORE_STATE(Ro, Wo, L);
/* Sr = f*L + W - R */
if (wrap*L + W - R > 0) {
/* readable: Sr > 0 */
*eltp = rb->B[R];
/* must clear elt */
rb->B[R] = NULL;
++Ro;
/* R = [0, 2L) */
R = RINGBUF_NORMALIZE_OFFSET(Ro, L);
uatomic_int_set(&rb->R, R);
/* pop success */
uatomic_int_zero(&rb->RLock);
return 1;
}
uatomic_int_zero(&rb->RLock);
}
/* pop failed */
return 0;
}
#define ringbuf_pop_always(rb, elt) \
while (ringbuf_pop((rb), &(elt)) != 1)
#define ringbuf_push_always(rb, elt) \
while (ringbuf_push((rb), (elt)) != 1)
#ifdef __cplusplus
}
#endif
#endif /* _RINGBUF_H_ */
|
#!/bin/bash
# Run script within the directory
BINDIR=$(dirname "$(readlink -fn "$0")")
cd "$BINDIR"
# Execute package scripts
for D in *; do
if [ -d "${D}" ]; then
echo "Packaging ${D}"
${D}/package.sh
fi
done
printf "\n"
|
/*
* Gray: A Ray Tracing-based Monte Carlo Simulator for PET
*
* Copyright (c) 2018, <NAME>, <NAME>, <NAME>, <NAME>
*
* This software is distributed under the terms of the MIT License unless
* otherwise noted. See LICENSE for further details.
*
*/
#include "Gray/Sources/VoxelSource.h"
#include <algorithm>
#include <array>
#include <iostream>
#include <fstream>
#include <numeric>
#include <vector>
#include "Gray/Random/Random.h"
VoxelSource::VoxelSource(
const VectorR3& position, const VectorR3& size, const VectorR3& axis,
double activity) :
Source(position, activity),
size(size),
local_to_global(RefAxisPlusTransToMap(axis, position)),
global_to_local(local_to_global.Inverse())
{
}
VectorR3 VoxelSource::Decay() const {
// Since we have created a CDF for the indices, we can do an inversion
// selection to randomly choose the voxel with the appropriate value. We
// have already created a sorted array, with 1.0 being the last value, so
// lower_bound will never select past end() - 1. So idx ends up being
// [0, x*y*z - 1].
auto val = std::lower_bound(prob.begin(), prob.end(), Random::Uniform());
size_t idx = std::distance(prob.begin(), val);
// Now, since this was in [x,y,z], c order, calculate the voxel value in
// each of the dimensions.
int z = idx % dims[2];
int y = (idx / dims[2]) % dims[1];
int x = idx / dims[2] / dims[1];
// Each dimension is distributed [0, dim - 1], add a random variable to
// distribute within voxels so that we have [0, dim] as a float. divide
// by dim so we have a [0,1]. Subtract 0.5 so we're [-0.5, 0.5]. Scale
// that by size so we're [-size/2, size/2].
VectorR3 pos(
((x + Random::Uniform()) / dims[0] - 0.5) * size.x,
((y + Random::Uniform()) / dims[1] - 0.5) * size.y,
((z + Random::Uniform()) / dims[2] - 0.5) * size.z);
return (local_to_global * pos);
}
bool VoxelSource::Load(const std::string& filename) {
std::ifstream input(filename);
if (!Load(input, prob, dims)) {
return (false);
}
std::partial_sum(prob.begin(), prob.end(), prob.begin());
for (double& val : prob) {
val /= prob.back();
}
return (true);
}
/*!
* Reads a binary image. Assumes the image has a 20 bytes, 4 int32 header that
* contains:
* - a "magic" number 65531, chosen arbitrarily
* - a version number. This only handles on version 1
* - the dimensions of the image in x, y, and z
* The remainder of the file is assumed to be x*y*z float32 values written in
* [x][z][y] C order.
*/
bool VoxelSource::Load(
std::istream& input,
std::vector<double>& vox_vals,
std::array<int,3>& dims)
{
if (!input) {
return (false);
}
int magic_number;
int version_number;
input.read(reinterpret_cast<char*>(&magic_number),
sizeof(magic_number));
input.read(reinterpret_cast<char*>(&version_number),
sizeof(version_number));
input.read(reinterpret_cast<char*>(dims.data()),
sizeof(int) * dims.size());
if (!input || (magic_number != 65531) || (version_number != 1)) {
return (false);
}
int no_vox = dims[0] * dims[1] * dims[2];
std::vector<float> data(no_vox);
input.read(reinterpret_cast<char*>(data.data()), no_vox * sizeof(float));
if (input.fail()) {
return (false);
}
vox_vals.clear();
vox_vals.resize(no_vox);
int idx = 0;
for (int x = 0; x < dims[0]; ++x) {
for (int y = 0; y < dims[1]; ++y) {
for (int z = 0; z < dims[2]; ++z) {
// Calculate the index into the XZY array
int data_idx = (x * dims[2] + z) * dims[1] + y;
vox_vals[idx++] = data[data_idx];
}
}
}
return (true);
}
bool VoxelSource::Inside(const VectorR3&) const {
// TODO: allow for positioning inside of voxelized sources
return false;
}
|
#!/usr/bin/env bash
# Copyright 2019 The Knative Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
readonly ROOT_DIR=$(dirname $0)/..
source ${ROOT_DIR}/vendor/knative.dev/test-infra/scripts/library.sh
set -o errexit
set -o nounset
set -o pipefail
cd ${ROOT_DIR}
# This controls the knative release version we track.
KN_VERSION="release-0.17" # This is for controlling the knative related release version.
CONTOUR_VERSION="release-1.4" # This is for controlling which version of contour we want to use.
# The list of dependencies that we track at HEAD and periodically
# float forward in this repository.
FLOATING_DEPS=(
"knative.dev/networking@${KN_VERSION}"
"knative.dev/pkg@${KN_VERSION}"
"knative.dev/test-infra@${KN_VERSION}"
"github.com/projectcontour/contour@${CONTOUR_VERSION}"
"knative.dev/serving@master"
)
# Parse flags to determine if we need to update our floating deps.
GO_GET=0
while [[ $# -ne 0 ]]; do
parameter=$1
case ${parameter} in
--upgrade) GO_GET=1 ;;
*) abort "unknown option ${parameter}" ;;
esac
shift
done
readonly GO_GET
if (( GO_GET )); then
go get -d ${FLOATING_DEPS[@]}
fi
# Prune modules.
go mod tidy
go mod vendor
rm -rf $(find vendor/ -name 'OWNERS')
# Remove unit tests & e2e tests.
rm -rf $(find vendor/ -path '*/pkg/*_test.go')
rm -rf $(find vendor/ -path '*/e2e/*_test.go')
# Add permission for shell scripts
chmod +x $(find vendor -type f -name '*.sh')
function add_ingress_provider_labels() {
sed '${/---/d;}' | go run ${ROOT_DIR}/vendor/github.com/mikefarah/yq/v3 m - ./hack/labels.yaml -d "*"
}
function delete_contour_cluster_role_bindings() {
sed -e '/apiVersion: rbac.authorization.k8s.io/{' -e ':a' -e '${' -e 'p' -e 'd' -e '}' -e 'N' -e '/---/!ba' -e '/kind: ClusterRoleBinding/d' -e '}'
}
function rewrite_contour_namespace() {
sed "s@namespace: projectcontour@namespace: $1@g" \
| sed "s@name: projectcontour@name: $1@g"
}
function configure_leader_election() {
sed -e $'s@ contour.yaml: |@ contour.yaml: |\\\n leaderelection:\\\n configmap-name: contour\\\n configmap-namespace: '$1'@g'
}
function rewrite_serve_args() {
sed -e $'s@ - serve@ - serve\\\n - --ingress-class-name='$1'@g'
}
function rewrite_image() {
sed -E $'s@docker.io/projectcontour/contour:.+@ko://github.com/projectcontour/contour/cmd/contour@g'
}
function rewrite_command() {
sed -e $'s@/bin/contour@contour@g'
}
function disable_hostport() {
sed -e $'s@hostPort:@# hostPort:@g'
}
function privatize_loadbalancer() {
sed "s@type: LoadBalancer@type: ClusterIP@g" \
| sed "s@externalTrafficPolicy: Local@# externalTrafficPolicy: Local@g"
}
rm -rf config/contour/*
# Apply patch to contour
git apply ${ROOT_DIR}/hack/contour.patch
# We do this manually because it's challenging to rewrite
# the ClusterRoleBinding without collateral damage.
cat > config/contour/internal.yaml <<EOF
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
name: contour-internal
labels:
networking.knative.dev/ingress-provider: contour
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: contour
subjects:
- kind: ServiceAccount
name: contour
namespace: contour-internal
---
EOF
KO_DOCKER_REPO=ko.local ko resolve -f ./vendor/github.com/projectcontour/contour/examples/contour/ \
| delete_contour_cluster_role_bindings \
| rewrite_contour_namespace contour-internal \
| configure_leader_election contour-internal \
| rewrite_serve_args contour-internal \
| rewrite_image | rewrite_command | disable_hostport | privatize_loadbalancer \
| add_ingress_provider_labels >> config/contour/internal.yaml
# We do this manually because it's challenging to rewrite
# the ClusterRoleBinding without collateral damage.
cat > config/contour/external.yaml <<EOF
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
name: contour-external
labels:
networking.knative.dev/ingress-provider: contour
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: contour
subjects:
- kind: ServiceAccount
name: contour
namespace: contour-external
---
EOF
KO_DOCKER_REPO=ko.local ko resolve -f ./vendor/github.com/projectcontour/contour/examples/contour/ \
| delete_contour_cluster_role_bindings \
| rewrite_contour_namespace contour-external \
| configure_leader_election contour-external \
| rewrite_serve_args contour-external \
| rewrite_image | rewrite_command | disable_hostport \
| add_ingress_provider_labels >> config/contour/external.yaml
|
/*
* Copyright (c) 2020 Chanus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chanus.yuntao.weixin.mp.api;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chanus.yuntao.utils.core.HttpUtils;
import com.chanus.yuntao.utils.core.StringUtils;
import java.util.List;
/**
* 用户标签管理 API<br>
* 详情请见:https://developers.weixin.qq.com/doc/offiaccount/User_Management/User_Tag_Management.html
*
* @author Chanus
* @date 2020-05-18 16:11:42
* @since 1.0.0
*/
public class UserTagApi {
/**
* 创建标签 url,请求方式为 POST
*/
private static final String CREATE_TAG_URL = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=ACCESS_TOKEN";
/**
* 获取公众号已创建的标签 url,请求方式为 GET
*/
private static final String GET_TAG_URL = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=ACCESS_TOKEN";
/**
* 编辑标签 url,请求方式为 POST
*/
private static final String UPDATE_TAG_URL = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token=ACCESS_TOKEN";
/**
* 删除标签 url,请求方式为 POST
*/
private static final String DELETE_TAG_URL = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=ACCESS_TOKEN";
/**
* 获取标签下粉丝列表 url,请求方式为 POST
*/
private static final String GET_TAG_USER_URL = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=ACCESS_TOKEN";
/**
* 批量为用户打标签 url,请求方式为 POST
*/
private static final String BATCH_TAGGING_URL = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=ACCESS_TOKEN";
/**
* 批量为用户取消标签 url,请求方式为 POST
*/
private static final String BATCH_UNTAGGING_URL = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=ACCESS_TOKEN";
/**
* 获取用户身上的标签列表 url,请求方式为 POST
*/
private static final String GET_USER_TAGS_URL = "https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=ACCESS_TOKEN";
/**
* 创建标签
*
* @param name 标签名(30个字符以内)
* @return 请求结果的 json 对象
*/
public static JSONObject create(String name) {
String accessToken = AccessTokenApi.getAccessTokenStr();
String url = CREATE_TAG_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject tagJson = new JSONObject();
JSONObject tagNameJson = new JSONObject();
tagNameJson.put("name", name);
tagJson.put("tag", tagNameJson);
String result = HttpUtils.post(url, tagJson.toJSONString());
return JSON.parseObject(result);
}
/**
* 获取公众号已创建的标签
*
* @return 请求结果的 json 对象
*/
public static JSONObject get() {
String accessToken = AccessTokenApi.getAccessTokenStr();
String url = GET_TAG_URL.replace("ACCESS_TOKEN", accessToken);
String result = HttpUtils.get(url);
return JSON.parseObject(result);
}
/**
* 编辑标签
*
* @param id 标签id
* @param name 标签名(30个字符以内)
* @return 请求结果的 json 对象
*/
public static JSONObject update(int id, String name) {
String accessToken = AccessTokenApi.getAccessTokenStr();
String url = UPDATE_TAG_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject tagJson = new JSONObject();
JSONObject tagNameJson = new JSONObject();
tagNameJson.put("id", id);
tagNameJson.put("name", name);
tagJson.put("tag", tagNameJson);
String result = HttpUtils.post(url, tagJson.toJSONString());
return JSON.parseObject(result);
}
/**
* 删除标签
*
* @param id 标签id
* @return 请求结果的 json 对象
*/
public static JSONObject delete(int id) {
String accessToken = AccessTokenApi.getAccessTokenStr();
String url = DELETE_TAG_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject tagJson = new JSONObject();
JSONObject tagIdJson = new JSONObject();
tagIdJson.put("id", id);
tagJson.put("tag", tagIdJson);
String result = HttpUtils.post(url, tagJson.toJSONString());
return JSON.parseObject(result);
}
/**
* 获取标签下粉丝列表
*
* @param tagId 标签id
* @param nextOpenId 第一个拉取的 OPENID,不填默认从头开始拉取
* @return 请求结果的 json 对象
*/
public static JSONObject getTagUsers(int tagId, String nextOpenId) {
String accessToken = AccessTokenApi.getAccessTokenStr();
String url = GET_TAG_USER_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject jsonObject = new JSONObject();
jsonObject.put("tagid", tagId);
if (StringUtils.isNotBlank(nextOpenId))
jsonObject.put("next_openid", nextOpenId);
String result = HttpUtils.post(url, jsonObject.toJSONString());
return JSON.parseObject(result);
}
/**
* 批量为用户打标签
*
* @param tagId 标签 id
* @param openIdList 粉丝列表
* @return 请求结果的 json 对象
*/
public static JSONObject batchTagging(int tagId, List<String> openIdList) {
String accessToken = AccessTokenApi.getAccessTokenStr();
String url = BATCH_TAGGING_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject jsonObject = new JSONObject();
jsonObject.put("tagid", tagId);
jsonObject.put("openid_list", openIdList);
String result = HttpUtils.post(url, jsonObject.toJSONString());
return JSON.parseObject(result);
}
/**
* 批量为用户取消标签
*
* @param tagId 标签 id
* @param openIdList 粉丝列表
* @return 请求结果的 json 对象
*/
public static JSONObject batchUntagging(int tagId, List<String> openIdList) {
String accessToken = AccessTokenApi.getAccessTokenStr();
String url = BATCH_UNTAGGING_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject jsonObject = new JSONObject();
jsonObject.put("tagid", tagId);
jsonObject.put("openid_list", openIdList);
String result = HttpUtils.post(url, jsonObject.toJSONString());
return JSON.parseObject(result);
}
/**
* 获取用户身上的标签列表
*
* @param openId 用户 openid
* @return 请求结果的 json 对象
*/
public static JSONObject getUserTags(String openId) {
String accessToken = AccessTokenApi.getAccessTokenStr();
String url = GET_USER_TAGS_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject jsonObject = new JSONObject();
jsonObject.put("openid", openId);
String result = HttpUtils.post(url, jsonObject.toJSONString());
return JSON.parseObject(result);
}
}
|
var async = require("async");
var mongoq = require('mongoq');
var stock_piling = function(location,items){
var stock_pile = {};
var stock_pile_arr =[];
for(var i=0;i<items.length; i++){
if(items[i].uom == "Package"){
var pitems = items[i].packages;
for(var j=0;j<pitems.length; j++){
if(stock_pile[pitems[j]._id]){
stock_pile[pitems[j]._id].quantity+= (items[i].quantity * pitems[j].quantity);
}
else{
stock_pile[pitems[j]._id] = {
location : location,
quantity : items[i].quantity * pitems[j].quantity,
_id : pitems[j]._id
}
}
}
}
else {
if(stock_pile[items[i]._id]){
stock_pile[items[i]._id].quantity+=items[i].quantity;
}
else{
stock_pile[items[i]._id] = {
location : location,
quantity : items[i].quantity,
_id : items[i]._id
}
}
}
}
for(var i in stock_pile){
stock_pile_arr.push(stock_pile[i]);;
}
return stock_pile_arr;
};
module.exports = {
check : function(db,items,location,cb){
var stock_pile_arr = stock_piling(location,items);
var stock_availability = [];
async.eachSeries(stock_pile_arr,
function(item,ccb){
var id = mongoq.mongodb.BSONPure.ObjectID.createFromHexString(item._id);
},
function(err){
if(err){
cb(err);
}
else{
cb(null,stock_availability);
}
}
);
}
}
module.exports = {
check : function(req,res,next){
if(req.body.triggerInventory){
if(req.body.ordered_items){
var stock_pile = {};
var stock_pile_arr =[];
var items = req.body.ordered_items;
var stock_pile_arr = stock_piling(req,items);
var stock_availability = [];
req.stock = {};
async.eachSeries(stock_pile_arr,function(item,callback){
var id = mongoq.mongodb.BSONPure.ObjectID.createFromHexString(item._id);
var error_message;
req.db.collection("products")
.find({
_id : id,
inventories : {"$elemMatch" : { _id: item.location, quantity : {"$gte": item.quantity}}}}).toArray()
.done(function(data){
if(!data[0]){
item.error_message = "INSUFFICIENT_STOCK";
callback(item);
}
else{
item.quantity = (item.quantity * -1)
stock_availability.push(item);
callback();
}
});
},function(err){
if(err){
console.log(err);
res.status(400).json(err);
}
else{
req.stock.available = stock_availability
console.log(req.stock);
next();
}
})
}
else{
next();
}
}
else{
next();
}
},
deduct : function(req,res,next){
if(req.stock && req.stock.available){
var stock = req.stock.available;
async.eachSeries(stock,function(item,callback){
var id = mongoq.mongodb.BSONPure.ObjectID.createFromHexString(item._id);
req.db.collection("products")
.update({_id : id, "inventories._id":item.location}, {"$inc":{"inventories.$.quantity":item.quantity}}, {safe: true})
.done(function(data){
console.log("SUCCESS",data);
callback();
})
.fail( function( err ) {
item.error_message = "DATABASE_INSERTION_ERROR";
callback(item);
});
},function(err){
if(err){
res.status(400).json(item);
}
else{
next();
}
});
}
else{
next();
}
}
};
|
#!/bin/bash
REALPATH="$(readlink -f $0)"
RUNNING_DIR="$(dirname "$REALPATH")"
function updatediscordstable() {
APP_VERSION="$(grep -m1 '"version":' $RUNNING_DIR/discord-stable.json | cut -f4 -d'"')"
NEW_APP_VERSION="$(curl -sSL -I -X GET "https://discordapp.com/api/download?platform=linux&format=tar.gz" | grep -im1 '^location:' | rev | cut -f1 -d'-' | cut -f3- -d'.' | rev)"
if [ ! -z "$NEW_APP_VERSION" ] && [ ! "$APP_VERSION" = "$NEW_APP_VERSION" ]; then
GITHUB_DL_URL="https://github.com/simoniz0r/Discord-AppImage/releases/download/v$NEW_APP_VERSION/discord-stable-$NEW_APP_VERSION-x86_64.AppImage"
if curl -sSL -I -X GET "$GITHUB_DL_URL"; then
fltk-dialog --question --center --text="New Discord version has been released!\nDownload version $NEW_APP_VERSION now?"
case $? in
1)
exit 0
;;
esac
fltk-dialog --message --center --text="Please choose the save location for 'discord'"
DEST_DIR="$(fltk-dialog --directory --center --native)"
if [ -z "$DEST_DIR" ] || [[ "$DEST_DIR" =~ "/tmp/." ]]; then
fltk-dialog --message --center --text="Invalid directory selected; using $HOME/Downloads"
DEST_DIR="$HOME/Downloads"
fi
if [ -w "$DEST_DIR" ]; then
mkdir -p "$DEST_DIR"
fltk-dialog --progress --center --pulsate --no-cancel --no-escape --text="Downloading Discord" &
PROGRESS_PID=$!
curl -sSL -o "$DEST_DIR"/discord-stable "$GITHUB_DL_URL" || { fltk-dialog --warning --center --text="Failed to download Discord!\nPlease try again."; exit 1; }
chmod +x "$DEST_DIR"/discord-stable
kill -SIGTERM -f $PROGRESS_PID
else
PASSWORD="$(fltk-dialog --password --center --text="Enter your password to download Discord to $DEST_DIR")"
echo "$PASSWORD" | sudo -S mkdir -p "$DEST_DIR" || { fltk-dialog --warning --center --text="Failed to create $DEST_DIR!\nPlease try again."; exit 1; }
fltk-dialog --progress --center --pulsate --no-cancel --no-escape --text="Downloading Discord" &
PROGRESS_PID=$!
curl -sSL -o /tmp/discord-stable-"$NEW_APP_VERSION"-x86_64.AppImage "$GITHUB_DL_URL" || { fltk-dialog --warning --center --text="Failed to download Discord!\nPlease try again."; exit 1; }
chmod +x /tmp/discord-stable-"$NEW_APP_VERSION"-x86_64.AppImage
echo "$PASSWORD" | sudo -S mv /tmp/discord-stable-"$NEW_APP_VERSION"-x86_64.AppImage "$DEST_DIR"/discord-stable || \
{ fltk-dialog --warning --center --text="Failed to move Discord to $DEST_DIR!\nPlease try again."; rm -f /tmp/discord-stable-"$APP_VERSION"-x86_64.AppImage; exit 1; }
kill -SIGTERM -f $PROGRESS_PID
fi
fltk-dialog --message --center --text="Discord $NEW_APP_VERSION has been downloaded to $DEST_DIR\nLaunching Discord now..."
"$DEST_DIR"/discord-stable &
exit 0
else
fltk-dialog --question --center --text="New Discord version has been released!\nUse deb2appimage to build an AppImage for $NEW_APP_VERSION now?"
case $? in
1)
exit 0
;;
esac
mkdir -p "$HOME"/.cache/deb2appimage
fltk-dialog --message --center --text="Please choose the save location for 'discord-stable'"
DEST_DIR="$(fltk-dialog --directory --center --native)"
if [ -z "$DEST_DIR" ] || [[ "$DEST_DIR" =~ "/tmp/." ]]; then
fltk-dialog --message --center --text="Invalid directory selected; using $HOME/Downloads"
DEST_DIR="$HOME/Downloads"
fi
if [ -w "$DEST_DIR" ]; then
mkdir -p "$DEST_DIR"
else
PASSWORD="$(fltk-dialog --password --center --text="Enter your password to build Discord AppImage to $DEST_DIR")"
echo "$PASSWORD" | sudo -S mkdir -p "$DEST_DIR" || { fltk-dialog --warning --center --text="Failed to create $DEST_DIR!\nPlease try again."; exit 1; }
fi
cp "$RUNNING_DIR"/deb2appimage "$HOME"/.cache/deb2appimage/deb2appimage.AppImage
cp "$RUNNING_DIR"/fltk-dialog "$HOME"/.cache/deb2appimage/fltk-dialog
cp "$RUNNING_DIR"/discord-stable.sh "$HOME"/.cache/deb2appimage/discord-stable.sh
cp "$RUNNING_DIR"/discord-stable.json "$HOME"/.cache/deb2appimage/discord-stable.json
fltk-dialog --progress --center --pulsate --no-cancel --no-escape --text="Downloading Discord" &
PROGRESS_PID=$!
echo "$(sed "s%\"version\": \"0..*%\"version\": \"$NEW_APP_VERSION\",%g" "$HOME"/.cache/deb2appimage/discord-stable.json)" > "$HOME"/.cache/deb2appimage/discord-stable.json
deb2appimage -j "$RUNNING_DIR"/discord-stable.json -o "$HOME"/Downloads || { fltk-dialog --warning --center --text="Failed to build Discord AppImage\nPlease create an issue here:\nhttps://github.com/simoniz0r/Discord-Stable-AppImage/issues/new"; exit 1; }
kill -SIGTERM -f $PROGRESS_PID
if [ -w "$DEST_DIR" ]; then
mv "$HOME"/Downloads/discord-stable-"$APP_VERSION"-x86_64.AppImage "$DEST_DIR"/discord-stable
else
echo "$PASSWORD" | sudo -S mv "$HOME"/Downloads/discord-stable-"$NEW_APP_VERSION"-x86_64.AppImage "$DEST_DIR"/discord-stable || \
{ fltk-dialog --warning --center --text="Failed to move Discord to $DEST_DIR!\nPlease try again."; rm -f "$HOME"/Downloads/discord-stable-"$APP_VERSION"-x86_64.AppImage; exit 1; }
fi
fltk-dialog --message --center --text="Discord AppImage $NEW_APP_VERSION has been built to $DEST_DIR\nLaunching Discord now..."
"$DEST_DIR"/discord-stable &
exit 0
fi
else
echo "$APP_VERSION"
echo "Discord is up to date"
echo
fi
}
case $1 in
--remove)
./usr/bin/discord.wrapper --remove-appimage-desktop-integration && echo "Removed .desktop file and icon for menu integration for Discord." || echo "Failed to remove .desktop file and icon!"
exit 0
;;
--help)
echo "Arguments provided by Discord AppImage:"
echo "--remove - Remove .desktop file and icon for menu integration if created by the AppImage."
echo "--help - Show this help output."
echo
echo "All other arguments will be passed to Discord; any valid arguments will function the same as a regular Discord install."
exit 0
;;
*)
if ! type curl > /dev/null 2>&1; then
fltk-dialog --message --center --text="Please install 'curl' to enable update checks"
else
updatediscordstable
fi
./usr/bin/discord.wrapper &
sleep 30
while ps aux | grep -v 'grep' | grep -q 'Discord'; do
sleep 30
done
exit 0
;;
esac
|
require "eventmachine"
require "securerandom"
module Kcl
class Worker
PROCESS_INTERVAL = 2 # by sec
def self.run(id, record_processor_factory)
worker = self.new(id, record_processor_factory)
worker.start
end
def initialize(id, record_processor_factory)
@id = id
@record_processor_factory = record_processor_factory
@live_shards = {} # Map<String, Boolean>
@shards = {} # Map<String, Kcl::Workers::ShardInfo>
@consumers = [] # [Array<Thread>] args the arguments passed from input. This array will be modified.
@kinesis = nil # Kcl::Proxies::KinesisProxy
@checkpointer = nil # Kcl::Checkpointer
@timer = nil
end
# process 1 process 2
# kinesis.shards sync periodically
# shards.start
# go through shards, assign itself
# on finish shard, release shard
#
# kinesis.shards sync periodically in parallel thread
#
# consumer should not block main thread
# available_lease_shard? should divide all possible shards by worker ids
# Start consuming data from the stream,
# and pass it to the application record processors.
def start
Kcl.logger.info(message: "Start worker", object_id: object_id)
EM.run do
trap_signals
@timer = EM::PeriodicTimer.new(PROCESS_INTERVAL) do
Thread.current[:uuid] = SecureRandom.uuid
sync_shards!
consume_shards!
end
end
cleanup
Kcl.logger.info(message: "Finish worker", object_id: object_id)
rescue => e
Kcl.logger.error(e)
raise e
end
# Shutdown gracefully
def shutdown(signal = :NONE)
terminate_timer!
terminate_consumers!
EM.stop
Kcl.logger.info(message: "Shutdown worker with signal #{signal} at #{object_id}")
rescue => e
Kcl.logger.error(e)
raise e
end
# Cleanup resources
def cleanup
@live_shards = {}
@shards = {}
@kinesis = nil
@checkpointer = nil
@consumers = []
end
def terminate_consumers!
Kcl.logger.info(message: "Stop #{@consumers.count} consumers in draining mode...")
# except main thread
@consumers.each do |consumer|
consumer[:stop] = true
consumer.join
end
end
def terminate_timer!
unless @timer.nil?
@timer.cancel
@timer = nil
end
end
# Add new shards and delete unused shards
def sync_shards!
@live_shards.transform_values! { |_| false }
kinesis.shards.each do |shard|
@live_shards[shard.shard_id] = true
next if @shards[shard.shard_id]
@shards[shard.shard_id] = Kcl::Workers::ShardInfo.new(
shard.shard_id,
shard.parent_shard_id,
shard.sequence_number_range
)
Kcl.logger.info(message: "Found new shard", shard: shard.to_h)
end
@live_shards.each do |shard_id, alive|
next if alive
checkpointer.remove_lease(@shards[shard_id])
@shards.delete(shard_id)
Kcl.logger.info(message: "Remove shard", shard_id: shard_id)
end
@shards
end
# Count the number of leases hold by worker excluding the processed shard
def avaliable_leases_count
stats = @shards.values.inject(Hash.new(0)) do |memo, shard|
memo[shard.lease_owner] += 1 unless shard.completed?
memo
end
Kcl.logger.debug(message: "Stats", stats: stats)
Kcl.logger.debug(message: "Workers", workers: stats.keys.compact.push(@id).uniq)
number_of_workers = stats.keys.compact.push(@id).uniq.count
shards_per_worker = @shards.count.to_f / number_of_workers
return stats[nil] if number_of_workers == 1 # all free shards are available if there is single worker
return 0 if stats[@id] >= shards_per_worker # no shards are available if current worker already took his portion of shards
return stats[nil] if stats[nil] < 2 # if there are not to much free shards - take all of them
[shards_per_worker.round - stats[@id], stats[nil]].min # how many free shards the worker can take
end
# Process records by shard
def consume_shards!
counter = 0
@available_leases_count = avaliable_leases_count
@consumers.delete_if { |consumer| !consumer.alive? }
@shards.sort_by { |_k, v| v }.reverse.to_h.each do |shard_id, shard|
Kcl.logger.debug(message: "Available leases", count: avaliable_leases_count)
begin
shard = checkpointer.fetch_checkpoint(shard)
rescue Kcl::Errors::CheckpointNotFoundError
Kcl.logger.warn(message: "Not found checkpoint of shard", shard: shard.to_h)
next
end
# the shard has owner already
next if shard.lease_owner.present?
# shard is closed and processed all records
next if shard.completed?
# break if available_leases_count is not positive
break if counter >= @available_leases_count
# count the shard as consumed
begin
shard = checkpointer.lease(shard, @id)
rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException
Kcl.logger.warn(message: "Lease failed of shard", shard: shard.to_h)
next
end
counter += 1
@consumers << Thread.new do
begin
Thread.current[:uuid] = SecureRandom.uuid
consumer = Kcl::Workers::Consumer.new(
shard,
@record_processor_factory.create_processor,
kinesis,
checkpointer
)
consumer.consume!
ensure
shard = checkpointer.remove_lease_owner(shard)
Kcl.logger.info(message: "Finish to consume shard", shard_id: shard_id)
end
end
end
end
private
def kinesis
if @kinesis.nil?
@kinesis = Kcl::Proxies::KinesisProxy.new(Kcl.config)
Kcl.logger.info(message: "Created Kinesis session in worker")
end
@kinesis
end
def checkpointer
if @checkpointer.nil?
@checkpointer = Kcl::Checkpointer.new(Kcl.config)
Kcl.logger.info(message: "Created Checkpoint in worker")
end
@checkpointer
end
def trap_signals
[:HUP, :INT, :TERM].each do |signal|
trap signal do
EM.add_timer(0) { shutdown(signal) }
end
end
end
end
end
|
<reponame>CommanderStorm/rallyetool-v2<filename>rallyetool/settings/staging_settings.py
# flake8: noqa
# pylint: skip-file
# type: ignore
import logging.config
import os
USE_KEYCLOAK = os.getenv("USE_KEYCLOAK", "False") == "True"
if USE_KEYCLOAK:
from rallyetool.settings.keycloak_settings import *
OIDC_RP_CLIENT_ID = os.environ["OIDC_RP_CLIENT_ID"]
OIDC_RP_CLIENT_SECRET = os.environ["OIDC_RP_CLIENT_SECRET"]
else:
from rallyetool.settings.dev_settings import *
DEBUG = os.getenv("DJANGO_DEBUG", "False") == "True"
ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "").split(",")
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
# generate your own secret key using
# import random, string
# print("".join(random.choice(string.printable) for _ in range(50)))
# staticfiles
MIDDLEWARE.insert(1, "whitenoise.middleware.WhiteNoiseMiddleware")
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# logging
LOGGING_CONFIG = None
LOGLEVEL = os.getenv("DJANGO_LOGLEVEL", "info").upper()
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {
"format": "%(asctime)s %(levelname)s "
"[%(name)s:%(lineno)s] "
"%(module)s %(process)d %(thread)d %(message)s",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "console",
},
},
"loggers": {
"": {
"level": LOGLEVEL,
"handlers": ["console"],
},
},
},
)
|
package com.dacelonid.weeklychallenge.bonus;
class Kata {
static String bonusTime(final int salary, final boolean bonus) {
return "£" + (bonus ? salary * 10:salary);
}
}
|
#!/bin/bash
# ========== Experiment Seq. Idx. 2075 / 39.1.5.0 / N. 0 - _S=39.1.5.0 D1_N=33 a=-1 b=1 c=-1 d=-1 e=-1 f=-1 D3_N=3 g=-1 h=1 i=1 D4_N=4 j=4 D5_N=0 ==========
set -u
# Prints header
echo -e '\n\n========== Experiment Seq. Idx. 2075 / 39.1.5.0 / N. 0 - _S=39.1.5.0 D1_N=33 a=-1 b=1 c=-1 d=-1 e=-1 f=-1 D3_N=3 g=-1 h=1 i=1 D4_N=4 j=4 D5_N=0 ==========\n\n'
# Prepares all environment variables
JBHI_DIR="$HOME/jbhi-special-issue"
RESULTS_DIR="$JBHI_DIR/results"
if [[ "Yes" == "Yes" ]]; then
SVM_SUFFIX="svm"
PREDICTIONS_FORMAT="isbi"
else
SVM_SUFFIX="nosvm"
PREDICTIONS_FORMAT="titans"
fi
RESULTS_PREFIX="$RESULTS_DIR/deep.33.layer.3.test.4.index.2075.$SVM_SUFFIX"
RESULTS_PATH="$RESULTS_PREFIX.results.txt"
# ...variables expected by jbhi-checks.include.sh and jbhi-footer.include.sh
SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue"
LIST_OF_INPUTS="$RESULTS_PREFIX.finish.txt"
# ...this experiment is a little different --- only one master procedure should run, so there's only a master lock file
METRICS_TEMP_PATH="$RESULTS_DIR/this_results.anova.txt"
METRICS_PATH="$RESULTS_DIR/all_results.anova.txt"
START_PATH="$METRICS_PATH.start.txt"
FINISH_PATH="-"
LOCK_PATH="$METRICS_PATH.running.lock"
LAST_OUTPUT="$METRICS_PATH"
mkdir -p "$RESULTS_DIR"
#
# Assumes that the following environment variables where initialized
# SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue"
# LIST_OF_INPUTS="$DATASET_DIR/finish.txt:$MODELS_DIR/finish.txt:"
# START_PATH="$OUTPUT_DIR/start.txt"
# FINISH_PATH="$OUTPUT_DIR/finish.txt"
# LOCK_PATH="$OUTPUT_DIR/running.lock"
# LAST_OUTPUT="$MODEL_DIR/[[[:D1_MAX_NUMBER_OF_STEPS:]]].meta"
EXPERIMENT_STATUS=1
STARTED_BEFORE=No
# Checks if code is stable, otherwise alerts scheduler
pushd "$SOURCES_GIT_DIR" >/dev/null
GIT_STATUS=$(git status --porcelain)
GIT_COMMIT=$(git log | head -n 1)
popd >/dev/null
if [ "$GIT_STATUS" != "" ]; then
echo 'FATAL: there are uncommitted changes in your git sources file' >&2
echo ' for reproducibility, experiments only run on committed changes' >&2
echo >&2
echo ' Git status returned:'>&2
echo "$GIT_STATUS" >&2
exit 162
fi
# The experiment is already finished - exits with special code so scheduler won't retry
if [[ "$FINISH_PATH" != "-" ]]; then
if [[ -e "$FINISH_PATH" ]]; then
echo 'INFO: this experiment has already finished' >&2
exit 163
fi
fi
# The experiment is not ready to run due to dependencies - alerts scheduler
if [[ "$LIST_OF_INPUTS" != "" ]]; then
IFS=':' tokens_of_input=( $LIST_OF_INPUTS )
input_missing=No
for input_to_check in ${tokens_of_input[*]}; do
if [[ ! -e "$input_to_check" ]]; then
echo "ERROR: input $input_to_check missing for this experiment" >&2
input_missing=Yes
fi
done
if [[ "$input_missing" != No ]]; then
exit 164
fi
fi
# Sets trap to return error code if script is interrupted before successful finish
LOCK_SUCCESS=No
FINISH_STATUS=161
function finish_trap {
if [[ "$LOCK_SUCCESS" == "Yes" ]]; then
rmdir "$LOCK_PATH" &> /dev/null
fi
if [[ "$FINISH_STATUS" == "165" ]]; then
echo 'WARNING: experiment discontinued because other process holds its lock' >&2
else
if [[ "$FINISH_STATUS" == "160" ]]; then
echo 'INFO: experiment finished successfully' >&2
else
[[ "$FINISH_PATH" != "-" ]] && rm -f "$FINISH_PATH"
echo 'ERROR: an error occurred while executing the experiment' >&2
fi
fi
exit "$FINISH_STATUS"
}
trap finish_trap EXIT
# While running, locks experiment so other parallel threads won't attempt to run it too
if mkdir "$LOCK_PATH" --mode=u=rwx,g=rx,o=rx &>/dev/null; then
LOCK_SUCCESS=Yes
else
echo 'WARNING: this experiment is already being executed elsewhere' >&2
FINISH_STATUS="165"
exit
fi
# If the experiment was started before, do any cleanup necessary
if [[ "$START_PATH" != "-" ]]; then
if [[ -e "$START_PATH" ]]; then
echo 'WARNING: this experiment is being restarted' >&2
STARTED_BEFORE=Yes
fi
#...marks start
date -u >> "$START_PATH"
echo GIT "$GIT_COMMIT" >> "$START_PATH"
fi
if [[ "$STARTED_BEFORE" == "Yes" ]]; then
# If the experiment was started before, do any cleanup necessary
echo -n
else
echo "D1_N;D3_N;D4_N;a;b;c;d;e;f;g;h;i;j;m_ap;m_auc;m_tn;m_fp;m_fn;m_tp;m_tpr;m_fpr;k_ap;k_auc;k_tn;k_fp;k_fn;k_tp;k_tpr;k_fpr;isbi_auc" > "$METRICS_PATH"
fi
python \
"$SOURCES_GIT_DIR/etc/compute_metrics.py" \
--metadata_file "$SOURCES_GIT_DIR/data/all-metadata.csv" \
--predictions_format "$PREDICTIONS_FORMAT" \
--metrics_file "$METRICS_TEMP_PATH" \
--predictions_file "$RESULTS_PATH"
EXPERIMENT_STATUS="$?"
echo -n "33;3;4;" >> "$METRICS_PATH"
echo -n "-1;1;-1;-1;-1;-1;-1;1;1;4;" >> "$METRICS_PATH"
tail "$METRICS_TEMP_PATH" -n 1 >> "$METRICS_PATH"
#
#...starts training
if [[ "$EXPERIMENT_STATUS" == "0" ]]; then
if [[ "$LAST_OUTPUT" == "" || -e "$LAST_OUTPUT" ]]; then
if [[ "$FINISH_PATH" != "-" ]]; then
date -u >> "$FINISH_PATH"
echo GIT "$GIT_COMMIT" >> "$FINISH_PATH"
fi
FINISH_STATUS="160"
fi
fi
|
<!DOCTYPE html>
<html>
<head>
<title>Top Performing Stocks</title>
</head>
<body>
<h1>Top Performing Stocks</h1>
<table>
<tr>
<th>Stock Symbol</th>
<th>Company Name</th>
<th>Current Price</th>
<th>Daily Change</th>
<th>Absolute Change</th>
</tr>
<tr>
<td>AAPL</td>
<td>Apple Inc.</td>
<td>119.13</td>
<td>-1.45</td>
<td>-0.12</td>
</tr>
<tr>
<td>BABA</td>
<td>Alibaba Group Holding Ltd.</td>
<td>190.02</td>
<td>1.50</td>
<td>0.08</td>
</tr>
<tr>
<td>MSFT</td>
<td>Microsoft Corporation</td>
<td>206.91</td>
<td>0.98</td>
<td>0.48</td>
</tr>
<tr>
<td>NFLX</td>
<td>Netflix, Inc.</td>
<td>360.86</td>
<td>-0.51</td>
<td>-0.14</td>
</tr>
<tr>
<td>GOOG</td>
<td>Alphabet Inc.</td>
<td>1546.94</td>
<td>0.10</td>
<td>15.00</td>
</tr>
</table>
</body>
</html> |
#!/bin/sh
set -e
LG=$1
WIKI_DUMP_NAME=${LG}wiki-latest-pages-articles.xml.bz2
WIKI_DUMP_DOWNLOAD_URL=https://dumps.wikimedia.org/${LG}wiki/latest/$WIKI_DUMP_NAME
# download latest Wikipedia dump in chosen language
echo "Downloading the latest $LG-language Wikipedia dump from $WIKI_DUMP_DOWNLOAD_URL..."
wget -c $WIKI_DUMP_DOWNLOAD_URL
echo "Succesfully downloaded the latest $LG-language Wikipedia dump to $WIKI_DUMP_NAME"
|
import { EmbeddedViewRef } from '@angular/core';
class CustomDataStructure {
isLastViewPort: boolean;
items: any[];
renderedItems: EmbeddedViewRef<Object>[];
constructor() {
this.isLastViewPort = false;
this.items = [];
this.renderedItems = [];
}
get numberOfItems() {
return this.items.length;
}
addItem(item: any): void {
this.items.push(item);
}
removeItem(index: number): void {
this.items.splice(index, 1);
}
getItem(index: number): any {
return this.items[index];
}
renderItem(index: number): void {
// Render the view for the item at the specified index
// Add the view reference to the renderedItems array
// Update isLastViewPort if necessary
// Example:
// const viewRef = renderView(this.items[index]);
// this.renderedItems.push(viewRef);
// this.isLastViewPort = this.renderedItems.length === this.items.length;
}
unrenderItem(index: number): void {
// Unrender the view for the item at the specified index
// Remove the view reference from the renderedItems array
// Update isLastViewPort if necessary
// Example:
// unrenderView(this.renderedItems[index]);
// this.renderedItems.splice(index, 1);
// this.isLastViewPort = this.renderedItems.length === this.items.length - 1;
}
} |
#!/bin/sh
# usage: dataset field_separator percentage_training output_folder training_prefix training_suffix test_prefix test_suffix per_user per_items overwrite
dataset=${1}
field_separator=${2}
percentage_training=${3}
output_folder=${4}
training_prefix=${5}
training_suffix=${6}
test_prefix=${7}
test_suffix=${8}
per_user=${9}
per_items=${10} # unused
overwrite=${11}
# a tab is passed as $'\t'
if [[ $field_separator == " " ]]
then
users=`cut -f1 $dataset | sort | uniq`
else
users=`cut -f1 -d $'$field_separator' $dataset | sort | uniq`
fi
if $per_user
then
# per_user random split
training_file=$output_folder$training_prefix$percentage_training$training_suffix
test_file=$output_folder$test_prefix$percentage_training$test_suffix
if [ -f $training_file ] && [ -f $test_file ] && ! $overwrite
then
echo "ignoring $training_file and $test_file "
else
if [ -f $training_file ]
then
rm $training_file
fi
if [ -f $test_file ]
then
rm $test_file
fi
for user in $users
do
dataset_user=$dataset\_$user
grep -P "^$user$field_separator" $dataset | shuf > $dataset_user
RATINGS_COUNT=`wc -l $dataset_user | cut -d ' ' -f 1`
SPLIT_SIZE=`echo $RATINGS_COUNT $percentage_training | awk '{print int($1 * $2)}'`
DIFFERENCE=`echo $RATINGS_COUNT $SPLIT_SIZE | awk '{print $1 - $2}'`
# training
head -$SPLIT_SIZE $dataset_user >> $training_file
# test
tail -$DIFFERENCE $dataset_user >> $test_file
rm $dataset_user
done
echo "$training_file created. `wc -l $training_file | cut -d " " -f 1` lines."
echo "$test_file created. `wc -l $test_file | cut -d " " -f 1` lines."
fi
else
# global random split
RATINGS_COUNT=`wc -l $dataset | cut -d ' ' -f 1`
SPLIT_SIZE=`echo $RATINGS_COUNT $percentage_training | awk '{print int($1 * $2)}'`
DIFFERENCE=`echo $RATINGS_COUNT $SPLIT_SIZE | awk '{print $1 - $2}'`
dataset_shuf=$dataset\_shuf
shuf $dataset > $dataset_shuf
training_file=$output_folder$training_prefix$percentage_training$training_suffix
test_file=$output_folder$test_prefix$percentage_training$test_suffix
if [ -f $training_file ] && ! $overwrite
then
echo "ignoring $training_file"
else
head -$SPLIT_SIZE $dataset_shuf > $training_file
echo "$training_file created. `wc -l $training_file | cut -d " " -f 1` lines."
fi
if [ -f $test_file ] && ! $overwrite
then
echo "ignoring $test_file"
else
tail -$DIFFERENCE $dataset_shuf > $test_file
echo "$test_file created. `wc -l $test_file | cut -d " " -f 1` lines."
fi
# delete files
rm $dataset_shuf
fi
|
<gh_stars>1-10
import bs4
from bs4 import BeautifulSoup
from requests import get
from time import sleep
from pickle import load
from urllib.parse import quote
SKIP_PAGES = 0 # 0 unless debugging
KEYS_PORTUGUESE = {'link': 'Link', 'title': 'Título', 'price': 'Preço', 'no-interest': 'Parcelamento sem Juros',
'in-sale': 'Em Promoção', 'reputable': 'Boa reputação', 'picture': 'Link da imagem', 'free-shipping': 'Frete Grátis'}
def get_link(product):
link = product.find(class_="item__info-title").get("href").strip()
jm_loc = link.find('-_JM')
if jm_loc == -1:
return link
return link[:jm_loc + 4]
def get_title(product):
return product.find(class_="main-title").contents[0].strip()
def get_price(product):
price = product.find(
class_="price__fraction").contents[0].strip()
return float(price) * (1 if len(price) < 4 else 1000)
def get_picture(product):
picture = product.find(class_="item__image item__image--stack").find("img").get("src")
if not picture:
picture = product.find(class_="item__image item__image--stack").find("img")["data-src"]
return picture
def is_no_interest(product):
return True if product.find(class_="stack_column_item installments highlighted").contents[0].get(
"class") == "item-installments free-interest" else False
def has_free_shipping(product):
return "stack_column_item shipping highlighted" in str(product)
def is_in_sale(product):
return "item__discount" in str(product)
def get_all_products(pages, min_rep):
products = [
BeautifulSoup(
page,
"html.parser").find_all(
class_="results-item highlighted article stack product") for page in pages]
return [{
"link": get_link(product),
"title": get_title(product),
"price": get_price(product),
"no-interest": is_no_interest(product),
"free-shipping": has_free_shipping(product),
"in-sale": is_in_sale(product),
"reputable": is_reputable(
get_link(product), min_rep),
"picture": get_picture(product)} for page in products for product in page]
def is_reputable(link, min_rep=3, aggressiveness=2):
product_page = BeautifulSoup(get(link).text, "html.parser")
thermometer = str(
product_page.find(
class_="card-section seller-thermometer"))
sleep(0.5**aggressiveness)
THERM_LEVELS = ("newbie", "red", "orange",
"yellow", "light_green", "green")
if any(badrep in thermometer for badrep in (THERM_LEVELS[i] for i in range(min_rep))):
return False
return True
with open("categories.pickle", "rb") as cat:
CATS = load(cat)
def print_cats():
for father_cat in CATS:
print(f"{father_cat[0][0]} ---> {father_cat[0][1]}:")
print()
for cat in father_cat[1]:
print(f"{father_cat[0][0]}.{cat['number']} -> {cat['name']}")
print()
def get_cat(catid):
father_num, child_num = map(int, catid.split('.'))
for father_cat in CATS:
if father_cat[0][0] == father_num:
for child in father_cat[1]:
if child['number'] == child_num:
subdomain = child['subdomain']
suffix = child['suffix']
break
return subdomain, suffix
def get_search_pages(term, cat='0.0', price_min=0, price_max=2147483647, condition=0, aggressiveness=2):
CONDITIONS = ["", "_ITEM*CONDITION_2230284", "_ITEM*CONDITION_2230581"]
CATS.insert(0, [[0, 'Todas as categorias'], [
{'subdomain': 'lista', 'suffix': '', 'number': 0, 'name': 'Todas'}]])
subdomain, suffix = get_cat(cat)
index = 1
pages = []
while True:
page = get(
f"https://{subdomain}.mercadolivre.com.br/{suffix}{quote(term, safe='')}_Desde_{index}_PriceRange_{price_min}-{price_max}{CONDITIONS[condition]}")
index += 50 * (SKIP_PAGES + 1) # DEBUG
if page.status_code == 404:
break
else:
pages.append(page.text)
sleep(0.5**aggressiveness)
return pages
def get_parameters():
# TODO: ADD EXCEPTION HANDLING
price_min = int(input(
"Digite como um número inteiro, sem outros símbolos, o preço mínimo para os resultados da pesquisa (Ex: '150' sem aspas para R$ 150,00): "))
price_max = int(input(
"Digite como um número inteiro, sem outros símbolos, o preço máximo para os resultados da pesquisa (Ex: '1500' sem aspas para R$ 1500,00): "))
if price_min > price_max:
price_min, price_max = price_max, price_min
condition = int(input(
"Insira a condição do produto para os resultados da busca.\n(0 - misto | 1 - novo | 2 - usado): "))
print_cats()
category = input(
"Insira a categoria de acordo com os código identificadores exibidos\n(Ex: Caso queira a categoria \"Adultos\", digite '31.1' sem aspas): ")
aggressiveness = (int(input(
"Insira, entre 1 a 3 o nível desejado de agressividade:\n(Cuidado! Em um nível de agressividade alto, você pode ser bloqueado! )")) % 4) - 1
return category, price_min, price_max, condition, aggressiveness
def ML_query(search_term, order=1, min_rep=3, category='0.0', price_min=0, price_max=2147483647, condition=0, aggressiveness=2):
products = get_all_products(get_search_pages(search_term, category,
price_min, price_max, condition, aggressiveness), min_rep)
return sorted(products, key=lambda p: p["price"], reverse=order == 2)
if __name__ == "__main__":
search_term = input("Digite os termos da pesquisa: ")
advanced_mode = input(
"Deseja utilizar as opções avançadas de pesquisa? Digite \"sim\" se positivo: ")
if 'sim' in advanced_mode.lower():
args = get_parameters()
order = int(input(
"Insira a ordenação desejada dos resultados.\n(0 - relevância | 1 - preço mínimo | 2 - preço máximo): "))
min_rep = int(input(
"Insira, entre 0 a 6, qual é o nível mínimo de reputação desejada para os vendedores: "))
else:
args = ()
order = 1
min_rep = 3
products = ML_query(search_term, order, min_rep, *args)
for product in products:
if product["reputable"]:
for k, v in product.items():
print(f"{KEYS_PORTUGUESE[k]}: {v}")
print()
# TODO: ASK IF USER INTENDS TO DO ANOTHER SEARCH
|
// https://www.hackerrank.com/challenges/balanced-brackets
#include <iostream>
#include <stack>
using namespace std;
int main() {
int t;
cin >> t;
for (int i = 0; i < t; i++) {
string s;
stack<char> st;
cin >> s;
bool ok = true;
for (auto c : s) {
if (c == '{' || c == '(' || c == '[') {
switch (c) {
case '{': st.push('}'); break;
case '(': st.push(')'); break;
default: st.push(']');
}
} else if (!st.empty() && c == st.top()) {
st.pop();
} else {
ok = false;
break;
}
}
if (ok && st.empty()) cout << "YES\n";
else cout << "NO\n";
}
}
|
"""Leetcode 1007. Minimum Domino Rotations For Equal Row
Medium
URL: https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the
i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half
of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same,
or all the values in B are the same.
If it cannot be done, return -1.
Example 1:
Input: A = [2,1,2,4,2,2],
B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any
rotations.
If we rotate the second and fourth dominoes, we can make every value in the top
row equal to 2, as indicated by the second figure.
Example 2:
Input: A = [3,5,1,2,3],
B = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
Note:
- 1 <= A[i], B[i] <= 6
- 2 <= A.length == B.length <= 20000
"""
class SolutionNumCountsCover(object):
def minDominoRotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
Time complexity: O(n).
Space complexity: O(n).
"""
n = len(A)
# Create 1~6 number counts for A and B.
A_num_counts = [0] * 7
B_num_counts = [0] * 7
for i in range(n):
A_num_counts[A[i]] += 1
B_num_counts[B[i]] += 1
for num in range(1, 7):
# Check if number covers the whole list;
# if yes, return min diff between length and number counts in A & B.
if all([num == a or num == b for a, b in zip(A, B)]):
return min(n - A_num_counts[num], n - B_num_counts[num])
return -1
class SolutionNumCountsUnion(object):
def minDominoRotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
Time complexity: O(n).
Space complexity: O(n).
"""
n = len(A)
# Create 1~6 number counts for A and B and at the same pos if A[i] == B[i].
A_num_counts = [0] * 7
B_num_counts = [0] * 7
same_num_counts = [0] * 7
for i in range(n):
A_num_counts[A[i]] += 1
B_num_counts[B[i]] += 1
if A[i] == B[i]:
same_num_counts[A[i]] += 1
# Check iteratively all in numbers, their union set cover the whole list.
for j in range(1, 7):
if A_num_counts[j] + B_num_counts[j] - same_num_counts[j] == n:
return min(n - A_num_counts[j], n - B_num_counts[j])
return -1
def main():
# Output: 2
A = [2,1,2,4,2,2]
B = [5,2,6,2,3,2]
print SolutionNumCountsCover().minDominoRotations(A, B)
print SolutionNumCountsUnion().minDominoRotations(A, B)
# Output: -1
A = [3,5,1,2,3]
B = [3,6,3,3,4]
print SolutionNumCountsCover().minDominoRotations(A, B)
print SolutionNumCountsUnion().minDominoRotations(A, B)
# Output: 1
A = [1,5,1,2,3]
B = [3,3,3,3,4]
print SolutionNumCountsCover().minDominoRotations(A, B)
print SolutionNumCountsUnion().minDominoRotations(A, B)
if __name__ == '__main__':
main()
|
package com.mh.controltool2.handler.message;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface ExceptionHandler {
Object resolveException(HttpServletRequest request, HttpServletResponse response, Exception exception);
}
|
<filename>datastream-kafka-connector/src/main/java/com/linkedin/datastream/connectors/kafka/KafkaPositionTracker.java
/**
* Copyright 2019 LinkedIn Corporation. All rights reserved.
* Licensed under the BSD 2-Clause License. See the LICENSE file in the project root for license information.
* See the NOTICE file in the project root for additional information regarding copyright ownership.
*/
package com.linkedin.datastream.connectors.kafka;
import java.io.Closeable;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.common.Metric;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
import com.linkedin.datastream.common.DurableScheduledService;
import com.linkedin.datastream.common.diag.KafkaPositionKey;
import com.linkedin.datastream.common.diag.KafkaPositionValue;
import com.linkedin.datastream.server.DatastreamTask;
/**
* KafkaPositionTracker is intended to be used with a Kafka-based Connector task to keep track of the current
* offset/position of the Connector task's consumer.
*
* The information stored can then be queried via the /diag endpoint for diagnostic and analytic purposes.
*/
public class KafkaPositionTracker implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(KafkaPositionTracker.class);
/**
* The suffix for Kafka consumer metrics that record records lag.
*/
private static final String RECORDS_LAG_METRIC_NAME_SUFFIX = "records-lag";
/**
* The number of offsets to fetch from the broker per endOffsets() RPC call. This should be chosen to avoid timeouts
* (larger requests are more likely to cause timeouts).
*/
private final int _brokerOffsetsFetchSize;
/**
* The task prefix for the DatastreamTask.
* @see com.linkedin.datastream.server.DatastreamTask#getTaskPrefix()
*/
@NotNull
private final String _datastreamTaskPrefix;
/**
* The unique DatastreamTask name.
* @see com.linkedin.datastream.server.DatastreamTask#getDatastreamTaskName()
*/
@NotNull
private final String _datastreamTaskName;
/**
* The time at which the Connector task was instantiated.
*/
@NotNull
private final Instant _connectorTaskStartTime;
/**
* The position data for this DatastreamTask.
*/
@NotNull
private final ConcurrentMap<KafkaPositionKey, KafkaPositionValue> _positions = new ConcurrentHashMap<>();
/**
* A map of TopicPartitions to KafkaPositionKeys currently owned/operated on by this KafkaPositionTracker instance.
*/
@NotNull
private final ConcurrentMap<TopicPartition, KafkaPositionKey> _ownedKeys = new ConcurrentHashMap<>();
/**
* A set of TopicPartitions which are assigned to us, but for which we have not yet received any records or
* consumer position data for.
*/
@NotNull
private final Set<TopicPartition> _uninitializedPartitions = ConcurrentHashMap.newKeySet();
/**
* A look-up table of TopicPartition -> MetricName as they are encountered to speed consumer metric look up.
*/
@NotNull
private final Map<TopicPartition, MetricName> _metricNameCache = new HashMap<>();
/**
* The client id of the Kafka consumer used by the Connector task. Used to fetch metrics.
*/
@Nullable
private String _clientId;
/**
* The metrics format supported by the Kafka consumer used by the Connector task.
*/
@Nullable
private ConsumerMetricsFormatSupport _consumerMetricsSupport;
/**
* A Supplier that determines if the Connector task which this tracker is for is alive. If it is not, then we should
* stop running.
*/
private final Supplier<Consumer<?, ?>> _consumerSupplier;
/**
* The service responsible for periodically fetching offsets from the broker.
*/
@Nullable
private final BrokerOffsetFetcher _brokerOffsetFetcher; // Defined to help investigation issues (when you have a
// heap dump or are in a debugger)
/**
* Describes the metrics format supported by a Kafka consumer.
*/
private enum ConsumerMetricsFormatSupport {
/**
* The Kafka consumer exposes record lag by KIP-92, which applies to Kafka versions >= 0.10.2.0 and < 1.1.0.
* @see <a href="https://cwiki.apache.org/confluence/x/bhX8Awr">KIP-92</a>
*/
KIP_92,
/**
* The Kafka consumer exposes record lag by KIP-225 (superseding KIP-92), which applies to Kafka versions >= 1.1.0.
* @see <a href="https://cwiki.apache.org/confluence/x/uaBzB">KIP-225</a>
*/
KIP_225
}
/**
* Constructor for a KafkaPositionTracker.
*
* @param datastreamTaskPrefix The task prefix for the DatastreamTask
* {@see com.linkedin.datastream.server.DatastreamTask#getTaskPrefix()}
* @param datastreamTaskName The DatastreamTask name
* {@see com.linkedin.datastream.server.DatastreamTask#getDatastreamTaskName()}
* @param connectorTaskStartTime The time at which the associated DatastreamTask started
* @param isConnectorTaskAlive A Supplier that determines if the Connector task which this tracker is for is alive. If
* it is not, then we should stop.
* @param consumerSupplier A Consumer supplier that is suitable for querying the brokers that the Connector task is
* talking to
* @param positionTrackerConfig User-supplied configuration settings
*/
private KafkaPositionTracker(@NotNull String datastreamTaskPrefix, @NotNull String datastreamTaskName,
@NotNull Instant connectorTaskStartTime, @NotNull Supplier<Boolean> isConnectorTaskAlive,
@NotNull Supplier<Consumer<?, ?>> consumerSupplier, KafkaPositionTrackerConfig positionTrackerConfig) {
_datastreamTaskPrefix = datastreamTaskPrefix;
_datastreamTaskName = datastreamTaskName;
_connectorTaskStartTime = connectorTaskStartTime;
_consumerSupplier = consumerSupplier;
_brokerOffsetsFetchSize = positionTrackerConfig.getBrokerOffsetsFetchSize();
if (positionTrackerConfig.isEnableBrokerOffsetFetcher()) {
_brokerOffsetFetcher = new BrokerOffsetFetcher(datastreamTaskName, this, isConnectorTaskAlive,
positionTrackerConfig);
_brokerOffsetFetcher.startAsync();
} else {
_brokerOffsetFetcher = null;
}
}
/**
* Initializes position data for the assigned partitions. This method should be called whenever the Connector's
* consumer finishes assigning partitions.
*
* @see AbstractKafkaBasedConnectorTask#onPartitionsAssigned(Collection) for how this method is used in a connector
* task
* @param topicPartitions the topic partitions which have been assigned
*/
public synchronized void onPartitionsAssigned(@NotNull Collection<TopicPartition> topicPartitions) {
final Instant assignmentTime = Instant.now();
for (final TopicPartition topicPartition : topicPartitions) {
final KafkaPositionKey key = new KafkaPositionKey(topicPartition.topic(), topicPartition.partition(),
_datastreamTaskPrefix, _datastreamTaskName, _connectorTaskStartTime);
_ownedKeys.put(topicPartition, key);
_uninitializedPartitions.add(topicPartition);
final KafkaPositionValue value = _positions.computeIfAbsent(key, s -> new KafkaPositionValue());
value.setAssignmentTime(assignmentTime);
}
}
/**
* Frees position data for partitions which have been unassigned. This method should be called whenever the
* Connector's consumer is about to rebalance (and thus unassign partitions).
*
* @see AbstractKafkaBasedConnectorTask#onPartitionsRevoked(Collection) for how this method is used in a connector
* task
* @param topicPartitions the topic partitions which were previously assigned
*/
public synchronized void onPartitionsRevoked(@NotNull Collection<TopicPartition> topicPartitions) {
for (final TopicPartition topicPartition : topicPartitions) {
_metricNameCache.remove(topicPartition);
_uninitializedPartitions.remove(topicPartition);
@Nullable final KafkaPositionKey key = _ownedKeys.remove(topicPartition);
if (key != null) {
_positions.remove(key);
}
}
}
/**
* Updates the position data after the Connector's consumer has finished polling, using both the returned records and
* the available internal Kafka consumer metrics.
*
* This method will only update position data for partitions which have received records.
*
* @param records the records fetched from {@link Consumer#poll(Duration)}
* @param metrics the metrics for the Kafka consumer as fetched from {@link Consumer#metrics()}
*/
public synchronized void onRecordsReceived(@NotNull ConsumerRecords<?, ?> records,
@NotNull Map<MetricName, ? extends Metric> metrics) {
final Instant receivedTime = Instant.now();
for (final TopicPartition topicPartition : records.partitions()) {
// It shouldn't be possible to have the key/value missing here, because we to have onPartitionsAssigned() called
// with this topicPartition before then, but it should be safe to construct them here as this data should be
// coming from the consumer thread without race conditions.
final KafkaPositionKey key = _ownedKeys.computeIfAbsent(topicPartition,
s -> new KafkaPositionKey(topicPartition.topic(), topicPartition.partition(), _datastreamTaskPrefix,
_datastreamTaskName, _connectorTaskStartTime));
final KafkaPositionValue value = _positions.computeIfAbsent(key, s -> new KafkaPositionValue());
// Derive the consumer offset and the last record polled timestamp from the records
records.records(topicPartition).stream()
.max(Comparator.comparingLong(ConsumerRecord::offset))
.ifPresent(record -> {
value.setLastNonEmptyPollTime(receivedTime);
// Why add +1? The consumer's position is the offset of the next record it expects.
value.setConsumerOffset(record.offset() + 1);
value.setLastRecordReceivedTimestamp(Instant.ofEpochMilli(record.timestamp()));
});
// Attempt derive the broker's offset from the consumer's metrics
getLagMetric(metrics, topicPartition).ifPresent(consumerLag ->
Optional.ofNullable(value.getConsumerOffset()).ifPresent(consumerOffset -> {
// If we know both the consumer's lag from the metrics, and the consumer's offset from our position data,
// then we can calculate what the broker's offset should be.
final long brokerOffset = consumerOffset + consumerLag;
value.setLastBrokerQueriedTime(receivedTime);
value.setBrokerOffset(brokerOffset);
}));
_uninitializedPartitions.remove(topicPartition);
}
}
/**
* Checks the Kafka consumer metrics as acquired by {@link Consumer#metrics()} to see if it contains information on
* record lag (the lag between the consumer and the broker) for a given TopicPartition.
*
* If it does, the lag value is returned.
*
* @param metrics The metrics returned by the Kafka consumer to check
* @param topicPartition The TopicPartition to match against
* @return the lag value if it can be found
*/
@NotNull
private Optional<Long> getLagMetric(@NotNull Map<MetricName, ? extends Metric> metrics,
@NotNull TopicPartition topicPartition) {
@Nullable final MetricName metricName = Optional.ofNullable(_metricNameCache.get(topicPartition))
.orElseGet(() -> tryCreateMetricName(topicPartition, metrics.keySet()).orElse(null));
return Optional.ofNullable(metricName)
.map(name -> (Metric) metrics.get(name))
.map(Metric::metricValue)
.filter(value -> value instanceof Double)
.map(value -> ((Double) value).longValue());
}
/**
* Attempts to return the metric name containing record lag information if it exists. This method will attempt to
* return the cached value before calculating it (calculating the value is expensive).
*
* @param topicPartition the provided topic partition
* @param metricNames the collection of metric names
* @return the metric name containing record lag information, if it can be derived
*/
@NotNull
private Optional<MetricName> tryCreateMetricName(@NotNull TopicPartition topicPartition,
@NotNull Collection<MetricName> metricNames) {
// Try to fetch the result from cache first
MetricName metricName = _metricNameCache.get(topicPartition);
if (metricName != null) {
return Optional.of(metricName);
}
// Try to initialize the variables if they are not set
if (_clientId == null || _consumerMetricsSupport == null) {
// Find a testable metric name in the collection
metricNames.stream()
.filter(candidateMetricName -> candidateMetricName.name() != null)
.filter(candidateMetricName -> candidateMetricName.tags() != null)
.filter(candidateMetricName -> candidateMetricName.name().endsWith(RECORDS_LAG_METRIC_NAME_SUFFIX))
.findAny()
.ifPresent(testableMetricName -> {
// Attempt to extract the consumer's client id and the consumer's metric support level through the testable
// metric name
_clientId = Optional.ofNullable(testableMetricName.tags()).map(tags -> tags.get("client-id")).orElse(null);
_consumerMetricsSupport = testableMetricName.name().length() == RECORDS_LAG_METRIC_NAME_SUFFIX.length()
? ConsumerMetricsFormatSupport.KIP_225 : ConsumerMetricsFormatSupport.KIP_92;
});
}
// Ensure our variables are initialized (they should be, but we are being extra defensive)
@Nullable final String clientId = _clientId;
@Nullable final ConsumerMetricsFormatSupport consumerMetricsSupport = _consumerMetricsSupport;
if (clientId == null || consumerMetricsSupport == null) {
// Client metric support is unimplemented in the current consumer
LOG.trace("The current consumer does not seem to have metric support for record lag.");
return Optional.empty();
}
// Build our metric name
switch (consumerMetricsSupport) {
case KIP_92: {
final Map<String, String> tags = new HashMap<>();
tags.put("client-id", clientId);
metricName = new MetricName(topicPartition + "." + RECORDS_LAG_METRIC_NAME_SUFFIX,
"consumer-fetch-manager-metrics", "", tags);
break;
}
case KIP_225: {
final Map<String, String> tags = new HashMap<>();
tags.put("client-id", clientId);
tags.put("topic", topicPartition.topic());
tags.put("partition", String.valueOf(topicPartition.partition()));
metricName = new MetricName(RECORDS_LAG_METRIC_NAME_SUFFIX, "consumer-fetch-manager-metrics", "", tags);
break;
}
default: {
// Client metric support is unimplemented in the current consumer
LOG.trace("The current consumer does not seem to have metric support for record lag.");
return Optional.empty();
}
}
// Store it in the cache and return it
_metricNameCache.put(topicPartition, metricName);
return Optional.of(metricName);
}
/**
* Returns a Set of TopicPartitions which are assigned to us, but for which we have not yet received any records or
* consumer position data for.
*
* @return the Set of TopicPartitions which are not yet initialized
*/
@NotNull
public synchronized Set<TopicPartition> getUninitializedPartitions() {
return Collections.unmodifiableSet(_uninitializedPartitions);
}
/**
* Fills the current consumer offset into the position data for the given TopicPartition, causing the TopicPartition
* to no longer need initialization.
*
* This offset is typically found by the Connector's consumer by calling {@link Consumer#position(TopicPartition)}
* after a successful {@link Consumer#poll(Duration)}.
*
* @param topicPartition The given TopicPartition to provide position data for
* @param consumerOffset The Connector consumer's offset for this topic partition as if specified by
* {@link Consumer#position(TopicPartition)}
*/
public synchronized void initializePartition(@Nullable TopicPartition topicPartition, @Nullable Long consumerOffset) {
if (topicPartition != null && consumerOffset != null) {
// It shouldn't be possible to have the key/value missing here, because we to have onPartitionsAssigned() called
// with this topicPartition before then, but it should be safe to construct them here as this data should be
// coming from the consumer thread without race conditions.
final KafkaPositionKey key = _ownedKeys.computeIfAbsent(topicPartition,
s -> new KafkaPositionKey(topicPartition.topic(), topicPartition.partition(), _datastreamTaskPrefix,
_datastreamTaskName, _connectorTaskStartTime));
final KafkaPositionValue value = _positions.computeIfAbsent(key, s -> new KafkaPositionValue());
value.setConsumerOffset(consumerOffset);
_uninitializedPartitions.remove(topicPartition);
}
}
/**
* Returns the position data stored in this instance.
*
* @return the position data stored in this instance
*/
public Map<KafkaPositionKey, KafkaPositionValue> getPositions() {
return Collections.unmodifiableMap(_positions);
}
/**
* {@inheritDoc}
*/
@Override
public void close() {
final BrokerOffsetFetcher brokerOffsetFetcher = _brokerOffsetFetcher;
if (brokerOffsetFetcher != null) {
brokerOffsetFetcher.stopAsync();
}
onPartitionsRevoked(_ownedKeys.keySet());
}
/**
* Returns a Builder which can be used to construct a {@link KafkaPositionTracker}.
*
* @return a Builder for this class
*/
public static Builder builder() {
return new Builder();
}
/**
* Uses the specified consumer to make RPC calls of {@link Consumer#endOffsets(Collection)} to get the broker's latest
* offsets for the specified TopicPartitions, and then updates the position data. The partitions will be fetched in
* batches to reduce the likelihood of a given call timing out.
*
* Note that the provided consumer must not be operated on by any other thread, or a concurrent modification condition
* may arise.
*
* Ideally the partitions provided to this method are owned all by the same broker for performance purposes.
*
* Use externally for testing purposes only.
*/
@VisibleForTesting
void queryBrokerForLatestOffsets(@NotNull Consumer<?, ?> consumer, @NotNull Set<TopicPartition> partitions,
@NotNull Duration requestTimeout) {
for (final List<TopicPartition> batch : Iterables.partition(partitions, _brokerOffsetsFetchSize)) {
LOG.trace("Fetching the latest offsets for partitions: {}", batch);
final Instant queryTime = Instant.now();
final Map<TopicPartition, Long> offsets;
try {
offsets = consumer.endOffsets(batch, requestTimeout);
} catch (Exception e) {
LOG.trace("Unable to fetch latest offsets for partitions: {}", batch, e);
continue;
} finally {
LOG.trace("Finished fetching the latest offsets for partitions {} in {} ms", batch,
Duration.between(queryTime, Instant.now()).toMillis());
}
offsets.forEach((topicPartition, offset) -> {
if (offset != null) {
// Race condition could exist where we might be unassigned the topic in a different thread while we are in
// this thread, so do not create/initialize the key/value in the map.
final KafkaPositionKey key = _ownedKeys.get(topicPartition);
if (key != null) {
final KafkaPositionValue value = _positions.get(key);
if (value != null) {
value.setLastBrokerQueriedTime(queryTime);
value.setBrokerOffset(offset);
}
}
}
});
}
}
/**
* Supplies a consumer usable for fetching broker offsets.
*
* @return a consumer usable for RPC calls
*/
@VisibleForTesting
Supplier<Consumer<?, ?>> getConsumerSupplier() {
return _consumerSupplier;
}
/**
* Implements a periodic service which queries the broker for its latest partition offsets.
*/
private static class BrokerOffsetFetcher extends DurableScheduledService {
/**
* The frequency at which to fetch offsets from the broker using the endOffsets() RPC call.
*/
private final Duration _brokerOffsetsFetchInterval;
/**
* The maximum duration that a consumer request is allowed to take before it times out.
*/
private final Duration _consumerRequestTimeout;
/**
* The KafkaPositionTracker object which created us.
*/
private final KafkaPositionTracker _kafkaPositionTracker;
/**
* A Consumer supplier that is suitable for querying the brokers that the Connector task is talking to.
*/
private final Supplier<Boolean> _isConnectorTaskAlive;
/**
* True if we should calculate performance leadership to improve the broker query performance, false otherwise.
*/
private final boolean _enablePartitionLeadershipCalculation;
/**
* The frequency at which we should fetch partition leadership.
*/
private final Duration _partitionLeadershipCalculationFrequency;
/**
* A cache of partition leadership used to optimize the endOffset() RPC calls made. This is necessary as an
* endOffset() RPC call can in a very large fanout of requests (as it may need to talk to a lot of brokers). By
* keeping a very weakly consistent list of who owns what partitions, we can offer a performance boost. If this map
* is very out-of-date, it is unlikely to be much worse than not using it at all.
*/
private final Map<TopicPartition, Node> _partitionLeadershipMap = new ConcurrentHashMap<>();
/**
* The underlying Consumer used to make the endOffsets() RPC call.
*/
private Consumer<?, ?> _consumer;
/**
* The time of the last partition leadership calculation.
*/
private Instant _lastPartitionLeadershipCalculation;
/**
* Constructor for this class.
*
* @param brooklinTaskId The DatastreamTask name
* {@see com.linkedin.datastream.server.DatastreamTask#getDatastreamTaskName()}
* @param kafkaPositionTracker The KafkaPositionTracker instantiating this object
* @param isConnectorTaskAlive A Supplier that determines if the Connector task which this tracker is for is alive.
* If it is not, then we should stop
* @param positionTrackerConfig User-supplied configuration settings
*/
public BrokerOffsetFetcher(@NotNull String brooklinTaskId, @NotNull KafkaPositionTracker kafkaPositionTracker,
@NotNull Supplier<Boolean> isConnectorTaskAlive, @NotNull KafkaPositionTrackerConfig positionTrackerConfig) {
super("KafkaPositionTracker-" + brooklinTaskId, positionTrackerConfig.getBrokerOffsetFetcherInterval(),
positionTrackerConfig.getConsumerFailedDetectionThreshold());
_kafkaPositionTracker = kafkaPositionTracker;
_isConnectorTaskAlive = isConnectorTaskAlive;
_enablePartitionLeadershipCalculation = positionTrackerConfig.isEnablePartitionLeadershipCalculation();
_brokerOffsetsFetchInterval = positionTrackerConfig.getBrokerOffsetFetcherInterval();
_consumerRequestTimeout = positionTrackerConfig.getBrokerRequestTimeout();
_partitionLeadershipCalculationFrequency = positionTrackerConfig.getPartitionLeadershipCalculationFrequency();
}
/**
* {@inheritDoc}
*/
@Override
protected void startUp() {
_consumer = _kafkaPositionTracker._consumerSupplier.get();
}
/**
* {@inheritDoc}
*/
@Override
protected void runOneIteration() {
// Find which partitions have stale broker offset information
final Instant staleBy = Instant.now().minus(_brokerOffsetsFetchInterval);
final Set<TopicPartition> partitionsNeedingUpdate = new HashSet<>();
_kafkaPositionTracker._ownedKeys.forEach(((topicPartition, key) -> {
// Race condition could exist where we might be unassigned the topic in a different thread while we are in
// this thread, so do not create/initialize the value in the map.
@Nullable final KafkaPositionValue value = _kafkaPositionTracker._positions.get(key);
if (value != null
&& (value.getLastBrokerQueriedTime() == null || value.getLastBrokerQueriedTime().isBefore(staleBy))) {
partitionsNeedingUpdate.add(topicPartition);
}
}));
try {
if (_enablePartitionLeadershipCalculation) {
Instant calculationStaleBy = Optional.ofNullable(_lastPartitionLeadershipCalculation)
.map(lastCalculation -> lastCalculation.plus(_partitionLeadershipCalculationFrequency))
.orElse(Instant.MIN);
if (Instant.now().isAfter(calculationStaleBy)) {
updatePartitionLeadershipMap();
_lastPartitionLeadershipCalculation = Instant.now();
}
}
} catch (Exception e) {
LOG.warn("Failed to update the partition leadership map. Using stale leadership data. Reason: {}", e.getMessage());
LOG.debug("Failed to update the partition leadership map. Using stale leadership data.", e);
}
// Query the broker for its offsets for those partitions
batchPartitionsByLeader(partitionsNeedingUpdate).forEach(partitionLeaderBatch -> {
try {
_kafkaPositionTracker.queryBrokerForLatestOffsets(_consumer, partitionLeaderBatch, _consumerRequestTimeout);
} catch (Exception e) {
LOG.warn("Failed to query latest broker offsets for this leader batch via endOffsets() RPC. Reason: {}", e.getMessage());
LOG.debug("Failed to query latest broker offsets for this leader batch via endOffsets() RPC", e);
}
});
}
/**
* Queries a Kafka broker for the leader of each partition and caches that information.
*/
private void updatePartitionLeadershipMap() {
LOG.debug("Updating partition leadership map");
Optional.ofNullable(_consumer.listTopics(_consumerRequestTimeout)).ifPresent(response -> {
Map<TopicPartition, Node> updateMap = response.values().stream()
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(partitionInfo -> partitionInfo != null && partitionInfo.topic() != null && partitionInfo.leader() != null)
.collect(Collectors.toMap(
partitionInfo -> new TopicPartition(partitionInfo.topic(), partitionInfo.partition()),
PartitionInfo::leader));
_partitionLeadershipMap.keySet().retainAll(updateMap.keySet());
_partitionLeadershipMap.putAll(updateMap);
});
}
/**
* Groups topic partitions into batches based on their leader.
* @param topicPartitions the topic partitions to group by leader
* @return a list of topic partitions batches
*/
@NotNull
private List<Set<TopicPartition>> batchPartitionsByLeader(@NotNull Set<TopicPartition> topicPartitions) {
if (!_enablePartitionLeadershipCalculation || _partitionLeadershipMap.isEmpty()) {
if (_partitionLeadershipMap.isEmpty()) {
LOG.debug("Leadership unknown for all topic partitions");
}
return Collections.singletonList(topicPartitions);
}
final Map<Node, Set<TopicPartition>> assignedPartitions = new HashMap<>();
final Set<TopicPartition> unassignedPartitions = new HashSet<>();
topicPartitions.forEach(topicPartition -> {
@Nullable final Node leader = _partitionLeadershipMap.get(topicPartition);
if (leader == null) {
LOG.debug("Leader unknown for topic partition {}", topicPartition);
unassignedPartitions.add(topicPartition);
} else {
LOG.trace("Leader for topic partition {} is {}", topicPartition, leader);
assignedPartitions.computeIfAbsent(leader, s -> new HashSet<>()).add(topicPartition);
}
});
final List<Set<TopicPartition>> batches = new ArrayList<>();
batches.addAll(assignedPartitions.values());
batches.add(unassignedPartitions);
return batches;
}
/**
* {@inheritDoc}
*/
@Override
protected void signalShutdown(@Nullable Thread taskThread) throws Exception {
if (taskThread != null && taskThread.isAlive()) {
// Attempt to gracefully interrupt the consumer
_consumer.wakeup();
// Wait up to ten seconds for success
taskThread.join(Duration.ofSeconds(10).toMillis());
if (taskThread.isAlive()) {
// Attempt to more aggressively interrupt the consumer
taskThread.interrupt();
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected void shutDown() {
if (_consumer != null) {
_consumer.close();
}
}
/**
* {@inheritDoc}
*/
@Override
protected boolean hasLeaked() {
final boolean hasLeaked = !_isConnectorTaskAlive.get();
if (hasLeaked) {
_kafkaPositionTracker.onPartitionsRevoked(_kafkaPositionTracker._ownedKeys.keySet());
}
return hasLeaked;
}
}
/**
* Builder which can be used to create an instance of {@link KafkaPositionTracker}.
*/
public static class Builder {
private Instant _connectorTaskStartTime;
private Supplier<Consumer<?, ?>> _consumerSupplier;
private String _datastreamTaskName;
private String _datastreamTaskPrefix;
private Supplier<Boolean> _isConnectorTaskAlive;
private KafkaPositionTrackerConfig _kafkaPositionTrackerConfig;
/**
* Configures this builder with the time at which the associated DatastreamTask was started. This value is required
* to construct a {@link KafkaPositionTracker} object and must be provided before {@link #build()} is called.
*
* @param connectorTaskStartTime the time at which the associated DatastreamTask was started
* @return a builder configured with the connectorTaskStartTime param
*/
@NotNull
public Builder withConnectorTaskStartTime(@NotNull Instant connectorTaskStartTime) {
_connectorTaskStartTime = connectorTaskStartTime;
return this;
}
/**
* Configures the builder with a Consumer supplier that is suitable for querying the brokers that the Connector task
* is talking to. This value is required to construct a {@link KafkaPositionTracker} object and must be provided
* before {@link #build()} is called.
*
* @param consumerSupplier A Consumer supplier that is suitable for querying the brokers that the Connector task is
* talking to
* @return a builder configured with the consumerSupplier param
*/
@NotNull
public Builder withConsumerSupplier(@NotNull Supplier<Consumer<?, ?>> consumerSupplier) {
_consumerSupplier = consumerSupplier;
return this;
}
/**
* Configures the builder with the associated {@link DatastreamTask}. This class requires two pieces of data from
* the DatastreamTask it is associated with, the DatastreamTask's task prefix and task name, which it collects using
* {@link DatastreamTask#getTaskPrefix()} and {@link DatastreamTask#getDatastreamTaskName()} respectively. These
* values are required to construct a {@link KafkaPositionTracker} object and must be provided before
* {@link #build()} is called.
*
* @param datastreamTask The DatastreamTask associated with this position tracker
* @return a builder configured with the datastreamTaskPrefix and datastreamTaskName params acquired from the
* provided DatastreamTask
*/
@NotNull
public Builder withDatastreamTask(@NotNull DatastreamTask datastreamTask) {
_datastreamTaskName = datastreamTask.getDatastreamTaskName();
_datastreamTaskPrefix = datastreamTask.getTaskPrefix();
return this;
}
/**
* Configures the builder with a function that allows us to check if the connector task is alive. If it is not
* alive, then we should ensure this position tracker is closed down properly. This value is required to construct a
* {@link KafkaPositionTracker} object and must be provided before {@link #build()} is called.
*
* @param isConnectorTaskAlive A Supplier that determines if the Connector task which this tracker is for is alive
* @return a builder configured with the isConnectorTaskAlive param
*/
@NotNull
public Builder withIsConnectorTaskAlive(@NotNull Supplier<Boolean> isConnectorTaskAlive) {
_isConnectorTaskAlive = isConnectorTaskAlive;
return this;
}
/**
* Configures the builder with various user-supplied configuration settings.
*
* @param kafkaPositionTrackerConfig user-supplied configuration settings
* @return a builder configured with the kafkaPositionTrackerConfig param
*/
@NotNull
public Builder withKafkaPositionTrackerConfig(@NotNull KafkaPositionTrackerConfig kafkaPositionTrackerConfig) {
_kafkaPositionTrackerConfig = kafkaPositionTrackerConfig;
return this;
}
/**
* Uses the information already provided to the current instantiation of the builder to create an instance of the
* {@link KafkaPositionTracker} class.
*
* @return a {@link KafkaPositionTracker} object configured using the instance data from this builder
*/
@NotNull
public KafkaPositionTracker build() {
return new KafkaPositionTracker(_datastreamTaskPrefix, _datastreamTaskName, _connectorTaskStartTime,
_isConnectorTaskAlive, _consumerSupplier, _kafkaPositionTrackerConfig);
}
}
} |
package com.justinblank.strings.Search;
import java.util.TreeMap;
class Trie {
protected int length;
protected boolean accepting;
protected Trie root;
protected Trie supplier;
protected TreeMap<Character, Trie> followers = new TreeMap<>();
protected Trie(int length) {
this.length = length;
}
protected Trie next(char c) {
return this.followers.get(c);
}
void addFollower(char c, Trie trie) {
this.followers.put(c, trie);
}
void markAccepting() {
this.accepting = true;
}
int length() {
return length;
}
}
|
<filename>test/tikzRenderer.spec.ts
import { expect } from 'chai';
import { View } from '@daign/2d-pipeline';
import { GraphicStyle, Line } from '@daign/2d-graphics';
import { StyleSheet } from '@daign/style-sheets';
import { TikzRendererFactory } from '../lib';
describe( 'TikzRenderer', (): void => {
describe( 'render', (): void => {
it( 'should return the TikZ document', (): void => {
// Arrange
const styleSheet = new StyleSheet<GraphicStyle>();
const rendererFactory = new TikzRendererFactory();
const tikzRenderer = rendererFactory.createRenderer( styleSheet );
const node = new Line();
const view = new View();
view.mountNode( node );
// Act
const result = tikzRenderer.render( view );
// Assert
expect( result ).to.equal( '\\begin{tikzpicture}\n\\end{tikzpicture}' );
} );
} );
} );
|
#!/bin/bash
line_echo "Finished installations and configurations"
echo ""
line_echo "Start proccess..." $date_start
line_echo "Finish..........." $(date +'%Y-%m-%d %T')
echo ""
line_echo "Log file generated in ./log/installation_log.txt"
echo ""
line_echo "Open vim and execute the command :PluginInstall"
line_echo "Execute the configuration of IDE"
line_echo "Thanks!"
echo ""
line_echo "System restart required"
echo ""
title_echo "Do you want to restart the system now? (1) Yes (0) No"
read restart
if [ $restart = 1 ]
then
title_echo "Restarting the system"
reboot
fi
title_echo "OK, thanks for using our script :)"
exit |
<reponame>meisterwerkAndroid/crypto-church-android
package io.meisterwerk.coinsocean.db;
import java.util.List;
import io.meisterwerk.coinsocean.model.CryptoCoin;
public class DataHandler implements Repository {
private static final String TAG = "DataHandler";
private DataSource dataSource;
// private List<CryptoCoin> coins;
private static Repository sInstance;
private DataHandler() {
dataSource = new RealmSource();
// coins = new ArrayList<>();
}
public static Repository getInstance() {
if (sInstance == null) sInstance = new DataHandler();
return sInstance;
}
@Override
public void closeRepo() {
sInstance = null;
dataSource = null;
}
@Override
public List<CryptoCoin> getCoinsByName(String name) {
dataSource.getCoinsByName(name);
return null;
}
@Override
public void addAllCoins(CryptoCoin coinListResponse) {
if (coinListResponse == null) return;
dataSource.addAllCoins(coinListResponse);
}
@Override
public void addChainConverter() {
}
}
|
<reponame>code-check/github-api
package codecheck.github.app.commands
import scala.concurrent.ExecutionContext.Implicits.global
import codecheck.github.api.GitHubAPI
import scala.concurrent.Future
import codecheck.github.app.Repo
import codecheck.github.app.Command
import codecheck.github.app.CommandSetting
class ChangeRepositoryCommand(val api: GitHubAPI) extends Command {
def check(repo: Repo): Future[Some[Repo]] = {
api.getRepository(repo.owner, repo.name).map{ret =>
ret.map { v =>
val p = v.permissions
print("Your permissions: ")
if (p.admin) print("admin ")
if (p.push) print("push ")
if (p.pull) print("pull ")
println
v
}.orElse {
println(s"Repository ${repo.owner}/${repo.name} is not found.")
None
}
}.transform(
(_ => Some(repo)),
(_ => new Exception(s"Repository ${repo.owner}/${repo.name} is not found."))
)
}
def run(setting: CommandSetting, args: List[String]): Future[CommandSetting] = {
val repo = args match {
case str :: Nil =>
var split = str.split("/")
val repo = if (split.length == 2) {
Repo(split(0), split(1))
} else {
Repo(setting.repositoryOwner.getOrElse(api.user.login), str)
}
Some(repo)
case owner :: repo :: Nil =>
Some(Repo(owner, repo))
case _ =>
println("cr [OWNER] [REPO]")
None
}
repo.map(check(_).map(v => setting.copy(repo=v))).getOrElse(Future(setting))
}
}
|
def sum_of_primes(n):
if n < 2:
return 0
primes = [2]
num = 3
while len(primes) < n:
is_prime = True
for p in primes:
if num % p == 0:
is_prime = False
break
if is_prime:
primes.append(num)
num += 2
return sum(primes)
print(sum_of_primes(10)) |
package com.vmware.spring.workshop.services.facade.impl;
import java.util.List;
import javax.inject.Inject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.vmware.spring.workshop.dao.api.BranchDao;
import com.vmware.spring.workshop.dto.banking.BankDTO;
import com.vmware.spring.workshop.dto.banking.BranchDTO;
import com.vmware.spring.workshop.model.banking.Branch;
import com.vmware.spring.workshop.services.convert.BranchDTOConverter;
import com.vmware.spring.workshop.services.facade.BranchesFacade;
import com.vmware.spring.workshop.services.facade.Facade;
/**
* @author lgoldstein
*/
@Facade("branchesFacade")
@Transactional
public class BranchesFacadeImpl
extends AbstractCommonFacadeActions<Branch,BranchDTO,BranchDao,BranchDTOConverter>
implements BranchesFacade {
@Inject
public BranchesFacadeImpl(final BranchDao daoBranch,
final BranchDTOConverter brhConverter) {
super(BranchDTO.class, Branch.class, daoBranch, brhConverter);
}
@Override
@Transactional(readOnly=true)
public BranchDTO findByBranchCode(int branchCode) {
return _converter.toDTO(_dao.findByBranchCode(branchCode));
}
@Override
@Transactional(readOnly=true)
public List<BranchDTO> findAllBranches(BankDTO bank) {
Assert.notNull(bank, "No bank specified");
return findAllBranchesById(bank.getId());
}
@Override
@Transactional(readOnly=true)
public List<BranchDTO> findAllBranchesById(Long bankId) {
return _converter.toDTO(_dao.findByBankId(bankId));
}
@Override
@Transactional(readOnly=true)
public List<BranchDTO> findByBranchBankCode(int bankCode) {
return _converter.toDTO(_dao.findByBranchBankCode(bankCode));
}
}
|
#!/bin/bash
echo "Place SSL certificates if defined"
<% if_p("ssl.certificates") do |certificates| -%>
echo "Placing certs"
<% for cert in certificates -%>
cat > /var/vcap/jobs/nginx/ssl/<%= cert["name"] %>.crt << EOF
<%= cert["certificate"] %>
EOF
cat > /var/vcap/jobs/nginx/ssl/<%= cert["name"] %>.key << EOF
<%= cert["key"] %>
EOF
<% end -%>
echo "Done"
<% end -%>
|
#!/usr/bin/env bats
load test_helper
create_executable() {
local bin="${RSENV_ROOT}/versions/${1}/bin"
mkdir -p "$bin"
touch "${bin}/$2"
chmod +x "${bin}/$2"
}
@test "finds versions where present" {
create_executable "0.8" "rust"
create_executable "0.8" "rake"
create_executable "0.10-pre" "rust"
create_executable "0.10-pre" "rspec"
run rsenv-whence rust
assert_success
assert_output <<OUT
0.10-pre
0.8
OUT
run rsenv-whence rake
assert_success "0.8"
run rsenv-whence rspec
assert_success "0.10-pre"
}
|
function maxDepth(root) {
// base case if root is null
if(root == null) {
return 0;
}
// recursive case, find maxDepth of left and right side of tree
let leftDepth = maxDepth(root.left);
let rightDepth = maxDepth(root.right);
//return the maximum of the two plus one for the current node
return Math.max(leftDepth, rightDepth) + 1;
} |
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for USN-2746-2
#
# Security announcement date: 2015-09-25 00:00:00 UTC
# Script generation date: 2017-01-01 21:04:48 UTC
#
# Operating System: Ubuntu 15.04
# Architecture: i686
#
# Vulnerable packages fix on version:
# - python-simplestreams:0.1.0~bzr354-0ubuntu1.15.04.2
# - simplestreams:0.1.0~bzr354-0ubuntu1.15.04.2
# - python-simplestreams-openstack:0.1.0~bzr354-0ubuntu1.15.04.2
# - python3-simplestreams:0.1.0~bzr354-0ubuntu1.15.04.2
#
# Last versions recommanded by security team:
# - python-simplestreams:0.1.0~bzr354-0ubuntu1.15.04.2
# - simplestreams:0.1.0~bzr354-0ubuntu1.15.04.2
# - python-simplestreams-openstack:0.1.0~bzr354-0ubuntu1.15.04.2
# - python3-simplestreams:0.1.0~bzr354-0ubuntu1.15.04.2
#
# CVE List:
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo apt-get install --only-upgrade python-simplestreams=0.1.0~bzr354-0ubuntu1.15.04.2 -y
sudo apt-get install --only-upgrade simplestreams=0.1.0~bzr354-0ubuntu1.15.04.2 -y
sudo apt-get install --only-upgrade python-simplestreams-openstack=0.1.0~bzr354-0ubuntu1.15.04.2 -y
sudo apt-get install --only-upgrade python3-simplestreams=0.1.0~bzr354-0ubuntu1.15.04.2 -y
|
( cd hotspot ; git pull origin master )
git pull origin master
java -jar ../saxon/saxon.jar gatw.xml hotspot/hotspot/hotspot.xsl messages=informative
|
#!/bin/bash
echo "Author Commits"
git log | grep 'Author: ' |rev| cut -d " " -f 1 | rev | sort | uniq -c
echo ""
echo ""
echo "Date Commits"
git log | grep 'Date: ' | cut -d " " -f 5-6 | sort | uniq -c
echo ""
echo ""
echo "Use of Array List"
count=$(grep -Rn "ArrayList<.*>.*=" --include=*.java . | wc -l)
echo $count
if [ $count -gt 0 ]
then grep -Rn "ArrayList<.*>.*=" --include=*.java .
fi
echo ""
echo ""
echo "Use of Hash Map"
count=$(grep -Rn "HashMap<.*,.*>.*=" --include=*.java . | wc -l)
echo $count
if [ $count -gt 0 ]
then grep -Rn "HashMap<.*,.*>.*=" --include=*.java .
fi
echo ""
echo ""
echo "Use of Hash Set"
count=$(grep -Rn "HashSet<.*>.*=" --include=*.java . | wc -l)
echo $count
if [ $count -gt 0 ]
then grep -Rn "HashSet<.*>.*=" --include=*.java .
fi
echo ""
echo ""
echo "Number of extensions"
count=$(grep -Rn "extends" --include=*.java . | wc -l)
echo $count
# if [ $count -gt 0 ]
# then grep -Rn "extends" --include=*.java .
# fi
echo ""
echo ""
echo "Number of interfaces used"
count=$(grep -Rn "implements" --include=*.java . | wc -l)
echo $count
#if [ $count -gt 0 ]
# then grep -Rn "implements" --include=*.java .
# fi
echo ""
echo ""
echo "Number of interfaces"
count=$(grep -Rn "interface" --include=*.java . | wc -l)
echo $count
# if [ $count -gt 0 ]
# then grep -Rn "interface" --include=*.java .
# fi
echo ""
echo ""
echo "public variables"
count=$(grep -Rn "public [^(]*$" --include=*.java . | grep -v "final" | grep -v "class" | grep -v "enum" | wc -l)
echo $count
if [ $count -gt 0 ]
then grep -Rn "public [^(]*$" --include=*.java . | grep -v "final" | grep -v "class" | grep -v "enum"
fi
echo ""
echo ""
echo "Global variables"
count=$(grep -Rn "public [^(]*$" --include=*.java . | grep "static" | grep -v "final" | wc -l)
echo $count
if [ $count -gt 0 ]
then grep -Rn "public [^(]*$" --include=*.java . | grep "static" | grep -v "final"
fi
echo "Chained Ifs"
count=$(pcregrep -Mrn --include="\w\.java" "if\(.*\)(\n|.)*}(\n|\s|else)*if\(.*\)" . | grep ":[[:digit:]]" | wc -l)
echo $count
if [ $count -gt 0 ]
then pcregrep -Mrn --include="\w\.java" "if\(.*\)(\n|.)*}(\n|\s|else)*if\(.*\)" .
fi
echo ""
echo ""
echo "Switches"
count=$(grep -Rn "switch" --include=*.java . | wc -l)
echo $count
if [ $count -gt 0 ]
then grep -Rn "switch" --include=*.java .
|
#!/usr/bin/env bash
#
# Starts up webpack-dev-server for local development of webpack clients in the monorepo
#
# Options:
# - CLIENT=alternate|default as an environment variable, you may specify a directory in clients/
#
set -e
set -o pipefail
export CLIENT=${CLIENT-default}
# rebuild the html in case the user has changed CLIENT
npm run build:html
# rebuild the node-pty native code, in case the user is switching from
# electron to webpack (each of which may use a different node ABI)
npm run pty:nodejs
# npm install the webpack support, if we haven't already done so (we
# forgo installing the webpack components initially, due to their
# size)
if [ ! -d node_modules/webpack ]; then
npm install --no-save --ignore-scripts --no-package-lock ./packages/webpack
fi
# for development purposes, we will need to do a bit of hackery to
# link in the CLIENT theming into the dist/webpack staging area
rm -rf clients/$CLIENT/dist/webpack
mkdir -p clients/$CLIENT/dist/webpack/css
(cd clients/$CLIENT/dist/webpack && \
ln -sf ../../theme/icons && \
ln -sf ../../theme/images && \
cd css && \
for i in ../../../../../packages/core/web/css/*; do ln -sf $i; done && \
for i in ../../../theme/css/*; do ln -sf $i; done \
)
# link in any config.json settings that the CLIENT definition may specify
(cd node_modules/@kui-shell/settings && \
rm -f config-dev.json; if [ -f ../../../clients/$CLIENT/theme/config.json ]; then echo "linking config-dev.json"; cp ../../../clients/$CLIENT/theme/config.json config-dev.json; fi)
# display extra build progress?
if [ -z "$TRAVIS_JOB_ID" ]; then
PROGRESS="--progress"
fi
export KUI_MONO_HOME=$(cd ./ && pwd)
# finally, launch webpack-dev-server
webpack-dev-server $PROGRESS --config packages/webpack/webpack.config.js
|
$(document).ready(function(){
var typeId;
$('select#realestate-realestate_type_id').change(function(){
typeId = $(this).val();
switch(typeId){
case '1':
$('.field-realestate-rooms_number, .field-realestate-hols_number, .field-realestate-pathrooms_number, .field-realestate-store_number, .field-realestate-realestate_age, .field-realestate-flats_number').css({'display': ''});
$('.field-realestate-flats_number').css({'display': 'none'});
break;
case '2':
$('.field-realestate-rooms_number, .field-realestate-hols_number, .field-realestate-pathrooms_number, .field-realestate-store_number, .field-realestate-realestate_age, .field-realestate-flats_number').css({'display': ''});
$('.field-realestate-flats_number, .field-realestate-store_number').css({'display': 'none'});
break;
case '3':
$('.field-realestate-rooms_number, .field-realestate-hols_number, .field-realestate-pathrooms_number, .field-realestate-store_number, .field-realestate-realestate_age, .field-realestate-flats_number').css({'display': ''});
$('.field-realestate-rooms_number, .field-realestate-hols_number, .field-realestate-pathrooms_number').css({'display': 'none'});
break;
case '4':
$('.field-realestate-rooms_number, .field-realestate-hols_number, .field-realestate-pathrooms_number, .field-realestate-store_number, .field-realestate-realestate_age, .field-realestate-flats_number').css({'display': ''});
$('.field-realestate-hols_number, .field-realestate-store_number, .field-realestate-flats_number').css({'display': 'none'});
break;
case '5':
$('.field-realestate-rooms_number, .field-realestate-hols_number, .field-realestate-pathrooms_number, .field-realestate-store_number, .field-realestate-realestate_age, .field-realestate-flats_number').css({'display': ''});
$('.field-realestate-rooms_number, .field-realestate-hols_number, .field-realestate-pathrooms_number, .field-realestate-store_number, .field-realestate-realestate_age, .field-realestate-flats_number').css({'display': 'none'});
break;
default:
alert('unknown!');
}
});
$('select#realestate-ads_type_id').change(function(){
var adsType = $(this).val();
if(adsType == '1'){
$('.field-realestate-realestate_recuretment_period').css({'display': 'none'});
}else{
$('.field-realestate-realestate_recuretment_period').css({'display': ''});
}
});
}); |
<reponame>LukasVolgger/delivery-service
let menuItems = [
{
'name': 'HIT! <NAME>',
'description': 'frittierte Hühnerbrust mit Sesamkörnern, Salat, Reis und Teriyaki-Sauce',
'price': 12.90,
'allergenic': ['Enthält glutenhaltige/s Getreide/-Erzeugnisse', 'Enthält Ei/-Erzeugnisse', 'Enthält Sojabohnen/-Erzeugnisse', 'Enthält Sesamsamen/-Erzeugnisse', 'Enthält Schwefeldioxid/Sulfite']
},
{
'name': 'HIT! Lachs Teriyaki',
'description': 'leicht frittiertes Lachsfilets mit Teriyaki-Sauce, Gemüse, Sojasprossen und Reis',
'price': 13.50,
'allergenic': ['Enthält glutenhaltige/s Getreide/-Erzeugnisse', 'Enthält Fisch/-Erzeugnisse', 'Enthält Sojabohnen/-Erzeugnisse', 'Enthält Milch/-Erzeugnisse (laktosehaltig)', 'Enthält Schwefeldioxid/Sulfite']
},
{
'name': 'HIT! Harumaki (6 Stück, vegan)',
'description': 'japanische Frühlingsrollen gefüllt mit Gemüse und Kyosasauce',
'price': 4.70,
'allergenic': ['Enthält glutenhaltige/s Getreide/-Erzeugnisse', 'Enthält Sojabohnen/-Erzeugnisse', 'Enthält Sesamsamen/-Erzeugnisse', 'Enthält Schwefeldioxid/Sulfite']
},
{
'name': 'HIT! Kimchi (scharf)',
'description': 'scharfer fermentierter Chinakohl mit Ingwer und reichtlich Knoblauchin scharfem Paprikapulver. Mit probiotischen Kulturen.',
'price': 4.20,
'allergenic': ['Enthält glutenhaltige/s Getreide/-Erzeugnisse', 'Enthält Fisch/-Erzeugnisse', 'Enthält Sesamsamen/-Erzeugnisse', 'Enthält Schwefeldioxid/Sulfite']
},
{
'name': 'Sweet Sour Soup, 340ml (pikant)',
'description': 'mit Hühnerbrust, Morcheln, roter Paprika und Eistreifen',
'price': 4.10,
'allergenic': ['Enthält Sojabohnen/-Erzeugnisse']
},
{
'name': '<NAME> (4 Stück)',
'description': 'Teigtaschen gefüllt mit Garnelen, Wasserkastanien, Bärlauch, Bambussprossen und Karotten dazu Süß-Saurer-Chilisauce',
'price': 5.50,
'allergenic': ['Enthält glutenhaltige/s Getreide/-Erzeugnisse', 'Enthält Krebstiere/-Erzeugnisse', 'Enthält Ei/-Erzeugnisse', 'Enthält Sojabohnen/-Erzeugnisse', 'Enthält Milch/-Erzeugnisse (laktosehaltig)', 'Enthält Senf/-Erzeugnisse', 'Enthält Sesamsamen/-Erzeugnisse', 'Enthält Schwefeldioxid/Sulfite']
}
];
let menuCategories = [
'Beliebte Gerichte',
'Suppen',
'Salate',
'Vorspeisen',
'Sushi und Maki Set\'s',
'Sushi-Sashimi Set\'s',
'Sushi einzeln',
'Kleine Maki Rollen',
'Große Maki Rollen',
'Bento Boxen',
'Desserts',
'Alkoholfreie Getränke',
'Alkoholische Getränke'
]
let menuItemsInBasket = [];
let menuItemIsOpen = [];
let itemCounter = [];
let itemSubtotal = [];
let itemsInBasket = [];
let deliveryCosts = 0;
let minimumOrderValue = 15;
let languageAndCountrySelectionIsOpen = false;
let loginSectionIsOpen = false;
let liked = false;
let basketSubTotal;
let basketTotal = 0;
// ####################################### RENDERING #######################################
function render() {
renderMenuCategories();
renderMenuItems();
generateEmptyBasketHTML();
updateMobileBasketBtn();
}
function renderMenuCategories() {
let container = document.getElementById('menu-categories');
container.innerHTML = '';
for (i = 0; i < menuCategories.length; i++) {
container.innerHTML += `
<span id="menu-category-${i}" class="menu-category" onclick="selectMenuCategory(${i})">${menuCategories[i]}</span>
`;
}
}
function renderMenuItems() {
let menuItemsContainer = document.getElementById('menu-items-container');
menuItemsContainer.innerHTML = '';
for (let i = 0; i < menuItems.length; i++) {
menuItemsContainer.innerHTML += generateMenuItemsHTML(i);
}
// Select the first category as default = favorite meals
document.getElementById('menu-category-0').classList.add('selected-menu-category');
}
function renderBasketItems() {
calcBasketSubTotal();
calcBasketTotal();
updateMobileBasketBtn();
// Get the container where the basket items are rendered
let container = document.getElementById('basket-container');
container.innerHTML = '';
// Iterate through array and add all basket items
for (let i = 0; i < menuItemsInBasket.length; i++) {
container.innerHTML += generateBasketItemsHTML(i);
renderAnnotationBtn(i);
// Check if a Annotation is stored in existing items of basket and don't hide them
if (menuItemsInBasket[i].annotation != '') {
showAnnotationOutput(i);
document.getElementById(`basket-item-body-${i}`).style = 'padding-bottom: 0;';
}
}
// Show basket summary only if there are items in basket
if (menuItemsInBasket.length > 0) {
container.innerHTML += generateBasketSummaryHTML();
// Minimum order value not reached
if (basketSubTotal < minimumOrderValue) {
container.innerHTML += generateMinOrderValueNotReacheHTML();
}
// Generate disabled checkout btn
container.innerHTML += `
<div class="checkout-btn-container">
<button id="checkout-btn" class="checkout-btn-disabled btns">Bezahlen (${convertPrice(basketTotal) + ' €'})</button>
</div>
`;
// Minimum order value reached = enable btn
if (basketSubTotal >= minimumOrderValue) {
enableCheckoutBtn();
}
} else {
generateEmptyBasketHTML();
}
}
function renderAnnotationBtn(item) {
if (menuItemsInBasket[item].annotation === '') {
generateAddAnnotation(item);
} else {
generateEditAddAnnotation(item);
}
}
// ####################################### MAIN FUNCTIONS #######################################
function selectMenuCategory(item) {
document.getElementById(`menu-category-${item}`).classList.add('selected-menu-category');
// De-select all other categories
for (let i = 0; i < menuCategories.length; i++) {
if (i !== item) {
document.getElementById(`menu-category-${i}`).classList.remove('selected-menu-category');
}
}
}
function openMenuItem(item) {
menuItemIsOpen[item] = !menuItemIsOpen[item];
if (menuItemIsOpen[item] === true) {
document.getElementById(`menu-item-basket-section-${item}`).classList.remove('d-none');
document.getElementById(`menu-item-icon-${item}`).src = './img/icons/close.svg';
// Close all other menu items when selected menu item is open
for (let i = 0; i < menuItems.length; i++) {
if (i !== item) {
closeMenuItem(i);
}
}
} else {
closeMenuItem(item);
}
disableMinusBtn(item);
calcItemSubtotal(item);
}
function closeMenuItem(item) {
document.getElementById(`menu-item-basket-section-${item}`).classList.add('d-none');
document.getElementById(`menu-item-icon-${item}`).src = './img/icons/plus.svg';
itemCounter[item] = 1;
document.getElementById(`menu-item-amount-${item}`).innerHTML = itemCounter[item];
}
function itemCounterPlus(item) {
itemCounter[item]++;
document.getElementById(`menu-item-amount-${item}`).innerHTML = itemCounter[item];
if (itemCounter[item] !== 1) {
enableMinusBtn(item);
}
calcItemSubtotal(item);
}
function itemCounterMinus(item) {
if (itemCounter[item] > 1) {
itemCounter[item]--;
document.getElementById(`menu-item-amount-${item}`).innerHTML = itemCounter[item];
}
if (itemCounter[item] === 1) {
disableMinusBtn(item);
}
calcItemSubtotal(item);
}
function calcItemSubtotal(item) {
let amount = itemCounter[item];
let price = menuItems[item].price;
let subTotal = amount * price;
itemSubtotal[item] = subTotal;
document.getElementById(`add-to-basket-btn-${item}`).innerHTML = convertPrice(subTotal) + ' €';
}
function addToBasket(item) {
let itemName = menuItems[item].name;
let itemPrice = menuItems[item].price;
let itemAmount = itemCounter[item];
let itemTotal = itemPrice * itemAmount;
let itemAlreadyExistsInBasket = false;
let indexOfExistingItemInBasket;
// Check if menu item is already in basket
for (let i = 0; i < menuItemsInBasket.length; i++) {
let name = menuItemsInBasket[i].name;
if (name === itemName) {
itemAlreadyExistsInBasket = true;
indexOfExistingItemInBasket = i;
break;
}
}
if (itemAlreadyExistsInBasket) {
// console.log('Item already exists in basket');
menuItemsInBasket[indexOfExistingItemInBasket].amount += itemAmount;
menuItemsInBasket[indexOfExistingItemInBasket].total += itemTotal;
} else {
// console.log('Item doesn\'t exist in basket');
menuItemsInBasket.push({
'name': itemName,
'price': itemPrice,
'amount': itemAmount,
'total': itemTotal,
'annotation': ''
});
}
renderBasketItems();
closeMenuItem(item);
updateMobileBasketBtn();
}
function updateMobileBasketBtn() {
let container = document.getElementById('mobile-basket-btn');
container.innerHTML = `Warenkorb (${convertPrice(basketTotal)} €)`
}
function calcBasketItemSubtotal(item) {
return menuItemsInBasket[item].amount * menuItemsInBasket[item].price;
}
function calcBasketSubTotal() {
let sum = 0;
for (let i = 0; i < menuItemsInBasket.length; i++) {
sum += menuItemsInBasket[i].total;
}
basketSubTotal = sum;
}
function calcBasketTotal() {
basketTotal = basketSubTotal + deliveryCosts;
}
function decreaseItemInBasket(item) {
if (menuItemsInBasket[item].amount >= 1) {
menuItemsInBasket[item].amount--;
menuItemsInBasket[item].total = calcBasketItemSubtotal(item);
// Update menu item in basket
document.getElementById(`item-amount-in-basket-${item}`).innerHTML = menuItemsInBasket[item].amount;
document.getElementById(`item-total-in-basket-${item}`).innerHTML = convertPrice(menuItemsInBasket[item].total) + ' €';
calcBasketSubTotal()
}
if (menuItemsInBasket[item].amount === 0) {
deleteMenuitemInBasket(item);
}
renderBasketItems();
updateMobileBasketBtn();
}
function increaseItemInBasket(item) {
menuItemsInBasket[item].amount++;
menuItemsInBasket[item].total = calcBasketItemSubtotal(item);
// Update menu item in basket
document.getElementById(`item-amount-in-basket-${item}`).innerHTML = menuItemsInBasket[item].amount;
document.getElementById(`item-total-in-basket-${item}`).innerHTML = convertPrice(menuItemsInBasket[item].total) + ' €';
calcBasketSubTotal();
renderBasketItems();
updateMobileBasketBtn();
}
function deleteMenuitemInBasket(item) {
menuItemsInBasket.splice(item, 1);
renderBasketItems();
}
function convertPrice(number) {
return number.toFixed(2).replace('.', ',');
}
function checkout() {
menuItemsInBasket = [];
showOrderSuccesful();
renderBasketItems();
closeMobileBasket();
}
function showMobileBasket() {
document.getElementById('basket-section').classList.remove('hide-mobile');
document.getElementById('basket-section').classList.add('mobile-basket');
document.getElementById('mobile-basket-header').classList.remove('d-none');
document.getElementById('basket-header').classList.add('d-none');
document.body.style = 'overflow: hidden;'
}
function closeMobileBasket() {
document.getElementById('basket-section').classList.add('hide-mobile');
document.getElementById('basket-section').classList.remove('mobile-basket');
document.getElementById('mobile-basket-header').classList.add('d-none');
document.getElementById('basket-header').classList.remove('d-none');
document.body.style = 'overflow: auto;'
}
// Track user scrolling
document.addEventListener('scroll', function() {
let scrolledFromTop = window.pageYOffset;
let headerHeight = document.getElementById('header').offsetHeight;
let restaurantBannerHeight = document.getElementById('restaurant-banner').offsetHeight;
// console.log('pageyOffset: ' + scrolledFromTop);
// Check to enable sticky-up-btn
if (scrolledFromTop >= (headerHeight + restaurantBannerHeight)) {
enableUpBtn();
// console.log('btn enabled = true');
} else {
disableUpBtn();
// console.log('btn enabled = false');
}
}); |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
module('Integration | Component | pix-background-header', function (hooks) {
setupRenderingTest(hooks);
const BACKGROUND_HEADER_SELECTOR = '.pix-background-header';
const BACKGROUND_SELECTOR = `${BACKGROUND_HEADER_SELECTOR} .pix-background-header__background`;
test('it renders the default PixBackgroundHeader', async function (assert) {
// when
await render(hbs`
<PixBackgroundHeader>
Je suis un beau background bleu
</PixBackgroundHeader>
`);
const backgroundHeaderElement = this.element.querySelector(BACKGROUND_HEADER_SELECTOR);
const backgroundElement = this.element.querySelector(BACKGROUND_SELECTOR);
// then
assert.contains('Je suis un beau background bleu');
assert.equal(backgroundHeaderElement.className, 'pix-background-header');
assert.equal(backgroundElement.className, 'pix-background-header__background');
});
module('when there is PixBloc inside PixBackgroundHeader component', function () {
test('first PixBlock render', async function (assert) {
// given
this.set('shadowWeight', 'heavy');
// when
await render(hbs`
<PixBackgroundHeader>
<PixBlock @shadow={{this.shadowWeight}}>Je suis un beau bloc foncé</PixBlock>
<PixBlock>Je suis un deuxième bloc</PixBlock>
</PixBackgroundHeader>
`);
const firstBlockElement = this.element.querySelector(BACKGROUND_HEADER_SELECTOR).children[1];
const lastBlockElement = this.element.querySelector(BACKGROUND_HEADER_SELECTOR).children[2];
// then
assert.equal(firstBlockElement.className, 'pix-block pix-block--shadow-heavy');
assert.contains('Je suis un beau bloc foncé');
assert.equal(lastBlockElement.className, 'pix-block pix-block--shadow-light');
assert.contains('Je suis un deuxième bloc');
});
});
});
|
<filename>test/tests.ts
import assert = require("assert");
import path = require('path');
import http = require("http");
import fs = require("fs");
declare function it(stage: string, impl: Function): void;
//process.env['WORKER_COUNT'] = "1";
process.env['HTTP_PORT'] = "8080";
import nexusfork = require("../index");
import { NexusFork } from "../src/nexusfork";
var nf: NexusFork;
it("static website", function(done){
nexusfork(path.resolve(__dirname, "static-website"), function(err, n) {
if(err)
done(err);
else {
nf = n;
done();
}
});
});
it("test static website", function(done){
http.get("http://127.0.0.1:8080/", function(res) {
var document = "";
res.on("data", function(chunk) {
document += chunk;
});
res.on("end", function() {
try {
assert.equal(document,
fs.readFileSync(path.resolve(__dirname,
"static-website/www", "index.html")));
done();
} catch(e) {
done(e);
}
});
}).on('error', done);
});
it("shutdown static website", function(done){
nf.stop(done);
});
/*it("service website", function(done){
nexusfork(path.resolve(__dirname, "service-website"), done);
});
it("test service website", function(done){
http.get("http://127.0.0.1:8080/", function(res) {
var document = "";
res.on("data", function(chunk) {
document += chunk;
});
res.on("end", function() {
try {
assert.equal(document, JSON.stringify({mode:23}));
done();
} catch(e) {
done(e);
}
});
}).on('error', done);
});*/
|
import sqlite3
from flask import Flask, render_template
app = Flask(name)
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
@app.route('/')
def index():
cursor.execute("SELECT * FROM mytable")
results = cursor.fetchall()
return render_template('index.html', results=results)
if name == 'main':
app.run(debug=True)
// templates/index.html
<html>
<head>
<title>Welcome to my page</title>
</head>
<body>
<h1>My Database Results:</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
{% for result in results %}
<tr>
<td>{{ result[0] }}</td>
<td>{{ result[1] }}</td>
<td>{{ result[2] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html> |
<reponame>datyayu/raji-net-backend<filename>app/serializers/user_serializer.rb<gh_stars>0
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :password, :email
end
|
#!/bin/sh
set -e
. ../../common.sh
# Read the 'nspr' download URL from '.config'.
DOWNLOAD_URL=`read_property NSPR_SOURCE_URL`
# Grab everything after the last '/' character.
ARCHIVE_FILE=${DOWNLOAD_URL##*/}
# Download 'nspr' source archive in the 'source/overlay' directory.
download_source $DOWNLOAD_URL $OVERLAY_SOURCE_DIR/$ARCHIVE_FILE
# Extract all 'nspr' sources in the 'work/overlay/nspr' directory.
extract_source $OVERLAY_SOURCE_DIR/$ARCHIVE_FILE nspr
cd $SRC_DIR
|
<reponame>smagill/opensphere-desktop
package io.opensphere.core.util.collections.observable;
import java.util.function.Predicate;
import javafx.beans.WeakListener;
/**
* Base class for expression helpers, which contains utility methods useful in
* concrete implementations.
*/
public abstract class ExpressionHelperBase
{
/**
* Trims the size of the listeners, removing any garbage collected weak
* references.
*
* @param size the initial size of the array (note that the actual array may
* be larger) to examine.
* @param listeners the listeners to examine for obsolete references.
* @return the new size, after removing obsolete references.
*/
protected static int trim(int size, final Object[] listeners)
{
final Predicate<Object> p = t -> t instanceof WeakListener && ((WeakListener)t).wasGarbageCollected();
int index = 0;
for (; index < size; index++)
{
if (p.test(listeners[index]))
{
break;
}
}
if (index < size)
{
for (int src = index + 1; src < size; src++)
{
if (!p.test(listeners[src]))
{
listeners[index++] = listeners[src];
}
}
final int oldSize = size;
size = index;
for (; index < oldSize; index++)
{
listeners[index] = null;
}
}
return size;
}
}
|
`VERBS for BEYOND ZORK:
Copyright (C)1987 Infocom, Inc. All Rights Reserved.`
function GOTO(_WHERE) {
let _CR=0, _WHO, _X, _L, _OLIT;
_OLIT = isLIT;
_WHO = WINNER;
_L = LOC(WINNER);
if((isEQUAL(_L, SADDLE)
&& isIN(_L, DACT))) {
_WHO = DACT;
} else if((!(isEQUAL(_L, HERE))
&& isIS(_L, VEHICLE))) {
if(isEQUAL(PERFORM("EXIT", _L), M_FATAL)) {
P_WALK_DIR = null;
return true;
}
P_WALK_DIR = null;
OLD_HERE = null;
++_CR
}
_X = APPLY(GETP(HERE, "ACTION"), M_EXIT);
if(isEQUAL(_X, M_FATAL)) {
P_WALK_DIR = null;
return true;
} else if(isT(_X)) {
if(isT(_CR)) {
TELL(TAB);
}
++_CR
}
/*if(isEQUAL(_WHERE, APLANE, DEATH)) {
} else if(isT(EXIT_LINE)) {
if(isT(_CR)) {
TELL(TAB);
}
TELL(EXIT_LINE, CR);
++_CR
}*/
/*EXIT_LINE = null;*/
if((isEQUAL(_WHO, WINNER)
&& isIN(DACT, HERE)
&& isIS(DACT, LIVING)
&& !(isIS(DACT, MUNGED))
&& !(isIS(DACT, SLEEPING)))) {
REMOVE(DACT);
if(!(isEQUAL(_WHERE, APLANE, DEATH))) {
if(isT(_CR)) {
TELL(TAB);
}
++_CR
TELL("A shadow passes over ", HEAD, " as you leave.", CR);
}
}
if((isT(_CR)
&& isT(VERBOSITY))) {
CRLF();
}
HERE = _WHERE;
MOVE(_WHO, _WHERE);
isLIT = isIS_LIT();
if((!(_OLIT)
&& !(isLIT))) {
if(isT(_CR)) {
TELL(TAB);
}
TELL(CYOU, PICK_NEXT(DARK_WALKS));
if(isGRUE_ROOM()) {
} else if(PROB(50)) {
TELL(", straight into the jaws of a deadly presence lurking in the darkness");
JIGS_UP();
return true;
}
PRINT(PERIOD);
if(isT(VERBOSITY)) {
CRLF();
}
}
APPLY(GETP(HERE, "ACTION"), M_ENTERING);
if(!(isEQUAL(HERE, _WHERE))) {
return true;
}
if(!(isLIT)) {
MARK_DIR();
}
LAST_PSEUDO_LOC = null;
MAKE(PSEUDO_OBJECT, NOARTICLE);
UNMAKE(PSEUDO_OBJECT, VOWEL);
UNMAKE(PSEUDO_OBJECT, TRYTAKE);
LAST_MONSTER = null;
LAST_MONSTER_DIR = null;
P_IT_OBJECT = NOT_HERE_OBJECT;
P_THEM_OBJECT = NOT_HERE_OBJECT;
P_HIM_OBJECT = NOT_HERE_OBJECT;
P_HER_OBJECT = NOT_HERE_OBJECT;
V_LOOK(null);
APPLY(GETP(HERE, "ACTION"), M_ENTERED);
return true;
}
function MARK_DIR(_DIR=P_WALK_DIR) {
let _TBL, _WRD, _TYPE, _LEN;
if(asDIRECTION(_DIR) < asDIRECTION("DOWN")) {
return false;
}
_TBL = GETP(HERE, XPDIR_LIST[(0 - (asDIRECTION(_DIR) - asDIRECTION("NORTH")))]);
if(!(_TBL)) {
return false;
}
_WRD = _TBL[XTYPE];
if(_WRD & MARKBIT) {
return true;
}
_TYPE = MSB(_WRD);
_LEN = (_WRD & 127);
if((isEQUAL(_TYPE, CONNECT, SCONNECT, X_EXIT)
|| (isEQUAL(_TYPE, FCONNECT)
&& isT(_LEN))
|| (isEQUAL(_TYPE, DCONNECT)
&& isIS(_TBL[XDATA], OPENED)))) {
_TBL[XTYPE] = (_WRD + MARKBIT);
return true;
}
return false;
}
function DO_WALK(_DIR1, _DIR2=null, _DIR3=null) {
let _X;
P_WALK_DIR = _DIR1;
_X = PERFORM("WALK", _DIR1);
if(isEQUAL(_X, M_FATAL)) {
return RFATAL();
} else if(isT(_DIR2)) {
CRLF();
P_WALK_DIR = _DIR2;
_X = PERFORM("WALK", _DIR2);
if(isEQUAL(_X, M_FATAL)) {
return RFATAL();
} else if(isT(_DIR3)) {
CRLF();
P_WALK_DIR = _DIR3;
_X = PERFORM("WALK", _DIR3);
}
}
return _X;
}
function V_WALK() {
let _TBL, _TYPE, _DATA;
if(!(P_WALK_DIR)) {
if(isT(PRSO)) {
PRINT("[Presumably, you mean ");
TELL("WALK TO ", THEO);
PRINTC('\.'.charCodeAt(0));
PRINT(BRACKET);
PERFORM("WALK-TO", PRSO);
return true;
}
V_WALK_AROUND();
return true;
} else if((isIN(PLAYER, SADDLE)
&& isIN(SADDLE, DACT))) {
return NEXT_SKY();
} else if(isHERE(APLANE)) {
return NEXT_APLANE();
}
_TBL = GETP(HERE, PRSO);
if(!(_TBL)) {
NO_EXIT_THAT_WAY();
return RFATAL();
}
_TYPE = MSB(_TBL[XTYPE]);
if(isEQUAL(_TYPE, NO_EXIT, SHADOW_EXIT)) {
NO_EXIT_THAT_WAY();
return RFATAL();
}
if((!(isEQUAL(LAST_MONSTER, null, DORN, MAMA))
&& isIN(LAST_MONSTER, HERE)
&& isIN(WINNER, HERE)
&& isIS(LAST_MONSTER, LIVING)
&& !(isIS(LAST_MONSTER, SLEEPING))
&& isEQUAL(LAST_MONSTER_DIR, P_WALK_DIR)
&& isT(isLIT))) {
TELL(CTHE(LAST_MONSTER), " block");
if((!(isLIT)
|| !(isIS(LAST_MONSTER, PLURAL)))) {
TELL("s");
}
TELL(" your path!", CR);
return true;
}
_DATA = _TBL[XROOM];
if(isEQUAL(_TYPE, CONNECT, X_EXIT)) {
GOTO(_DATA);
return true;
} else if(isEQUAL(_TYPE, SORRY_EXIT)) {
TELL(_DATA, CR);
return RFATAL();
} else /*if(isEQUAL(_TYPE, FSORRY_EXIT)) {
_TYPE = _TBL[XDATA];
if(!(_TYPE)) {
_DATA = APPLY(_DATA);
return RFATAL();
}
_DATA = APPLY(_DATA, _TYPE);
return RFATAL();
}*/if(isEQUAL(_TYPE, SCONNECT)) {
TELL(_TBL[XDATA], CR);
if(isT(VERBOSITY)) {
CRLF();
}
GOTO(_DATA);
return true;
} else if(isEQUAL(_TYPE, FCONNECT)) {
_DATA = APPLY(_DATA);
if(isT(_DATA)) {
GOTO(_DATA);
return true;
}
return RFATAL();
} else if(isEQUAL(_TYPE, DCONNECT)) {
_TYPE = _TBL[XDATA];
if(isIS(_TYPE, OPENED)) {
GOTO(_DATA);
return true;
}
ITS_CLOSED(_TYPE);
return RFATAL();
}
/*SAY_ERROR("V-WALK");*/
return RFATAL();
}
function NO_EXIT_THAT_WAY() {
let _STR;
_STR = GETP(HERE, "EXIT-STR");
if(isEQUAL(P_WALK_DIR, null, "UP", "DOWN")) {
} else if(isEQUAL(P_WALK_DIR, "IN", "OUT")) {
} else if(isT(_STR)) {
TELL(_STR, CR);
return true;
}
TELL("There's no exit that way.", CR);
return true;
}
function NEXT_OVER() {
let _CNT=0, _DIR, _BITS, _TBL, _XTBL, _TYPE, _DATA;
_XTBL = FLY_TABLES[ABOVE];
_BITS = _XTBL[0];
_DIR = I_NORTH;
while(true) {
_TBL = GETP(HERE, PDIR_LIST[_DIR]);
_DATA = 0;
if(_BITS & DBIT_LIST[_DIR]) {
_TYPE = (CONNECT + 9 + MARKBIT);
++_CNT
_DATA = _XTBL[_CNT];
if((isHERE(IN_SKY)
&& isEQUAL(_DATA, OPLAIN))) {
_TYPE = (FCONNECT + 9 + MARKBIT);
} else if((isHERE(APLANE)
&& isEQUAL(_DATA, OCAVES))) {
_TYPE = NO_EXIT;
_DATA = 0;
}
} else if(isHERE(IN_SKY)) {
_TYPE = (FCONNECT + 9 + MARKBIT);
} else {
_TYPE = NO_EXIT;
}
_TBL[XTYPE] = _TYPE;
_TBL[XDATA] = _DATA;
if(++_DIR > I_NW) {
return false;
}
}
}
function NEXT_SKY() {
let _DIR, _IDIR, _D1, _D2, _D3, _TBL, _DATA, _X;
if((isT(DACT_SLEEP)
|| isIS(DACT, SLEEPING)
|| isIS(DACT, MUNGED)
|| !(isIS(DACT, LIVING)))) {
TELL(CTHE(DACT), " is in no condition to move around.", CR);
return RFATAL();
}
_DIR = P_WALK_DIR;
P_WALK_DIR = null;
if(isEQUAL(_DIR, "UP")) {
if(isHERE(IN_SKY)) {
TELL(CTHE(DACT
), " puffs and strains, but cannot lift you any higher.", CR);
return RFATAL();
}
_X = GETP(HERE, "FNUM");
if(!(_X)) {
TELL(CANT, "fly here.", CR);
return RFATAL();
}
TELL(CTHE(DACT));
if((isHERE(IN_GARDEN)
&& isT(PTIMER))) {
TELL(" cocks his head, hesitating.", CR);
return true;
}
TELL(" spreads his leathery wings and ");
if((isIN(PARASOL, PLAYER)
&& isIS(PARASOL, OPENED))) {
TELL("tries to take off. But your open ", PARASOL
, " seems to be dragging him down.", CR);
return true;
}
ABOVE = _X;
PUTP(IN_SKY, "FNUM", ABOVE);
TELL("rises into the sky.", CR);
if(isT(VERBOSITY)) {
CRLF();
}
GOTO(IN_SKY);
CHECK_BREEZE();
return true;
} else if(isEQUAL(_DIR, "DOWN")) {
if(!(isHERE(IN_SKY))) {
TELL(CTHE(DACT), " is already on ", THE(GROUND
), PERIOD);
return RFATAL();
}
_X = isDOWN_TO();
if(!(_X)) {
if(isEQUAL(ABOVE, OTHRIFF)) {
TELL(CTHE(DACT
), " tries his best to land, but ", THE(GROUND
), " below is completely choked with ", XTREES, PERIOD);
}
return RFATAL();
}
TELL(CTHE(DACT), " glides earthward.", CR);
if(isT(VERBOSITY)) {
CRLF();
}
GOTO(_X);
return true;
} else if(isEQUAL(_DIR, null, "IN", "OUT")) {
PUZZLED_DACT();
return RFATAL();
} else if(!(isHERE(IN_SKY))) {
P_WALK_DIR = null;
TELL("It's hard enough for a ", DACT
, " to walk, even when there's not an adventurer riding his back.", CR);
return RFATAL();
}
_TBL = GETP(HERE, _DIR);
_DATA = _TBL[XDATA];
if(isEQUAL(_TBL[XTYPE], (FCONNECT + 9 + MARKBIT))) {
TELL("The sky is filled with impenetrable ");
if(isEQUAL(_DATA, OPLAIN)) {
TELL("funnel ");
}
TELL("clouds in that ", INTDIR, PERIOD);
return RFATAL();
}
/*"D1-D3 are IDIRs favored by the wind."*/
_D1 = (WINDIR + 4);
if(_D1 > I_NW) {
_D1 = (_D1 - 8);
}
_D2 = (_D1 + 1);
if(_D2 > I_NW) {
_D2 = I_NORTH;
}
_D3 = (_D1 - 1);
if(_D3 < I_NORTH) {
_D3 = I_NW;
}
_IDIR = (0 - (asDIRECTION(_DIR) - asDIRECTION("NORTH")));
if(isEQUAL(_IDIR, _D1, _D2, _D3)) {
UNMAKE(BREEZE, SEEN);
TELL(CTHE(DACT));
TELL(" banks smoothly to the ", B(DIR_NAMES[_IDIR]), PERIOD);
FLYOVER(_DATA);
return true;
}
/*"Check for crosswinds."*/
MAKE(BREEZE, SEEN);
_D1 = (WINDIR - 2);
if(_D1 < I_NORTH) {
_D1 = (_D1 + 8);
}
if(isEQUAL(_IDIR, _D1)) {
_D2 = (WINDIR - 3);
if(_D2 < I_NORTH) {
_D2 = (_D2 + 8);
}
return DO_CROSSWIND(_IDIR, _D2);
}
_D1 = (WINDIR + 2);
if(_D1 > I_NW) {
_D1 = (_D1 - 8);
}
if(isEQUAL(_IDIR, _D1)) {
_D2 = (WINDIR + 3);
if(_D2 > I_NW) {
_D2 = (_D2 - 8);
}
return DO_CROSSWIND(_IDIR, _D2);
}
TELL(CTHE(DACT
), " does his best to fly into the wind, but fails.", CR);
return RFATAL();
}
function DO_CROSSWIND(_IDIR, _D2) {
let _TBL, _DATA;
_TBL = GETP(IN_SKY, PDIR_LIST[_D2]);
_DATA = _TBL[XDATA];
if((isEQUAL(_DATA, 0, OPLAIN, OCAVES)
|| isEQUAL(_TBL[XTYPE], (FCONNECT + 9 + MARKBIT))
|| PROB(50))) {
TELL("A strong crosswind prevents ", THE(DACT), " from flying that way.", CR);
return RFATAL();
}
TELL(CTHE(DACT));
TELL(" banks to the ", B(DIR_NAMES[_IDIR]
), ", but a strong crosswind blows him off course.", CR);
FLYOVER(_DATA);
return true;
}
function FLYOVER(_DATA) {
ABOVE = _DATA;
PUTP(IN_SKY, "FNUM", ABOVE);
NEXT_OVER();
RELOOK(true);
CHECK_BREEZE();
return true;
}
function CHECK_BREEZE() {
if(((isEQUAL(ABOVE, OTHRIFF)
&& isEQUAL(WINDIR, I_EAST, I_SE, I_SOUTH))
|| (isEQUAL(ABOVE, OXROADS)
&& isEQUAL(WINDIR, I_NORTH, I_NE, I_EAST)))) {
WINDIR = isNEXT_WINDIR();
MAKE(BREEZE, SEEN);
TELL(TAB, PICK_NEXT(WIND_ALERTS), PERIOD);
}
return false;
}
function NEXT_APLANE() {
let _DIR, _TBL, _DATA, _NEW, _X;
_DIR = P_WALK_DIR;
P_WALK_DIR = null;
_X = LOC(PLAYER);
if((isEQUAL(_DIR, "UP", "DOWN")
|| isEQUAL(_DIR, "IN", "OUT"))) {
TELL("Such ", INTDIR, "s have no meaning here.", CR);
return RFATAL();
} else if(isEQUAL(_X, APLANE)) {
} else if(isIS(_X, VEHICLE)) {
if(isEQUAL(PERFORM("EXIT", _X), M_FATAL)) {
return RFATAL();
}
TELL(TAB);
}
_TBL = GETP(HERE, _DIR);
_DATA = _TBL[XTYPE];
if(isEQUAL(_DATA, NO_EXIT)) {
TELL("The local geometry does not extend in that "
, INTDIR, PERIOD);
return RFATAL();
} else if(isEQUAL(ABOVE, OPLAIN)) {
if(isT(IMPSAY)) {
PERMISSION();
return RFATAL();
}
EXIT_IMPS();
}
_NEW = _TBL[XDATA];
if(isEQUAL(_NEW, OPLAIN)) {
if(isIS(SHAPE, LIVING)) {
if(!(isIN(SHAPE, APLANE))) {
WINDOW(SHOWING_ROOM);
MOVE(SHAPE, APLANE);
LAST_MONSTER = SHAPE;
LAST_MONSTER_DIR = null;
P_IT_OBJECT = SHAPE;
TELL("The space before you flexes in on itself, twists sideways and reopens into "
, A(SHAPE), ", stretched across your path like the skin of a drum.", CR);
return RFATAL();
}
TELL(CTHE(SHAPE
), " stretches itself tighter across your path.", CR);
return RFATAL();
} else if(!(IMPSAY)) {
KERBLAM();
TELL("A bolt of ", B("LIGHTNING"
), " blocks your path.", CR);
return RFATAL();
}
}
if(isEQUAL(ABOVE, OACCARDI, OCITY, OMIZNIA)) {
REMOVE(CURTAIN);
}
if(isIN(SHAPE, APLANE)) {
REMOVE(SHAPE);
LAST_MONSTER = null;
P_IT_OBJECT = NOT_HERE_OBJECT;
TELL(CTHE(SHAPE), " disincorporates as you retreat.", CR);
if(isT(VERBOSITY)) {
CRLF();
}
}
ABOVE = _NEW;
GET_APLANE_THINGS();
NEXT_OVER();
V_LOOK();
return true;
}
function PERMISSION() {
TELL("\"We didn't say you could leave yet,\" notes an Implementor dryly.", CR);
return true;
}
function EXIT_IMPS() {
REMOVE(IMPTAB);
REMOVE(IMPS);
DEQUEUE(I_IMPS);
return false;
}
function GET_APLANE_THINGS() {
if(isEQUAL(ABOVE, OCITY, OMIZNIA, OACCARDI)) {
if(!(isIN(CURTAIN, APLANE))) {
MOVE(CURTAIN, APLANE);
UNMAKE(CURTAIN, NODESC);
}
return true;
} else if((isEQUAL(ABOVE, OPLAIN)
&& !(isIN(IMPS, APLANE)))) {
MOVE(IMPTAB, APLANE);
MOVE(IMPS, APLANE);
QUEUE(I_IMPS);
return true;
} else {
return false;
}
}
function isANY_TOUCHED(_TBL, _EXCLUDED) {
let _LEN, _RM, _CNT;
_LEN = _TBL[0];
_CNT = 1;
while(true) {
_RM = toROOM(_TBL[_LEN]);
if((isIS(_RM, TOUCHED)
&& (!(isASSIGNED(_EXCLUDED))
|| !(isIS(_RM, _EXCLUDED))))) {
++_CNT
AUX_TABLE[_CNT] = _RM;
}
if(--_LEN < 1) {
break;
}
}
if(isEQUAL(_CNT, 1)) {
return false;
} else if(isEQUAL(_CNT, 2)) {
return AUX_TABLE[2];
}
AUX_TABLE[0] = _CNT;
AUX_TABLE[1] = 0;
return PICK_ONE(AUX_TABLE);
}
function isDOWN_TO() {
let _RM=0, _X;
if(isEQUAL(ABOVE, ORUINS)) {
_RM = isANY_TOUCHED(RUIN_ROOMS);
if((!(_RM)
&& isSETUP_RUINS())) {
_RM = isRANDOM_ROOM(RUIN_ROOMS);
}
return _RM;
} else if(isEQUAL(ABOVE, OBRIDGE)) {
BRIDGE_DIR = 0;
ZTOP = 1;
ZBOT = 2;
return ON_BRIDGE;
} else if(isEQUAL(ABOVE, OFOREST)) {
_RM = isANY_TOUCHED(FOREST_ROOMS);
if((!(_RM)
&& isSETUP_FOREST())) {
_RM = isRANDOM_ROOM(FOREST_ROOMS);
}
return _RM;
} else if(isEQUAL(ABOVE, OACCARDI)) {
_RM = IN_ACCARDI;
if((isIS(AT_GATE, TOUCHED)
&& PROB(50))) {
_RM = AT_GATE;
}
return _RM;
} else if(isEQUAL(ABOVE, OCITY)) {
_RM = IN_GURTH;
if(isIS(AT_MAGICK, TOUCHED)) {
_RM = AT_MAGICK;
}
return _RM;
} else if(isEQUAL(ABOVE, OSHORE)) {
_RM = isANY_TOUCHED(SHORE_ROOMS);
if(!(_RM)) {
_RM = AT_LEDGE;
}
return _RM;
} else if(isEQUAL(ABOVE, OXROADS)) {
return XROADS;
} else if(isEQUAL(ABOVE, OPLAIN)) {
return false;
} else if(isEQUAL(ABOVE, OGRUBBO)) {
return HILLTOP;
} else if(isEQUAL(ABOVE, OCAVES)) {
return IN_GARDEN;
} else if(isEQUAL(ABOVE, OMOOR)) {
_RM = isANY_TOUCHED(MOOR_ROOMS);
if((!(_RM)
&& isSETUP_MOOR())) {
_RM = isRANDOM_ROOM(MOOR_ROOMS);
}
return _RM;
} else if(isEQUAL(ABOVE, OJUNGLE)) {
_RM = isANY_TOUCHED(JUNGLE_ROOMS);
if((!(_RM)
&& isSETUP_JUNGLE())) {
_RM = isRANDOM_ROOM(JUNGLE_ROOMS);
}
return _RM;
} else if(isEQUAL(ABOVE, OMIZNIA)) {
_RM = isANY_TOUCHED(MIZNIA_ROOMS);
if(!(_RM)) {
_RM = IN_PORT;
}
return _RM;
} else if(isEQUAL(ABOVE, OTHRIFF)) {
_RM = IN_THRIFF;
if(isIS(IN_THRIFF, MUNGED)) {
_RM = IN_PASTURE;
}
return _RM;
} else {
/*SAY_ERROR("DOWN-TO?");*/
return false;
}
}
function isRANDOM_ROOM(_TBL) {
let _OHERE, _RM, _X;
_RM = toROOM(_TBL[RANDOM(_TBL[0])]);
if(!(isIS(_RM, TOUCHED))) {
_OHERE = HERE;
HERE = _RM;
_X = APPLY(GETP(_RM, "ACTION"), M_ENTERING);
HERE = _OHERE;
MAKE(_RM, TOUCHED);
}
return _RM;
}
function PRE_TAKE() {
let _L, _LL, _WHO, _X, _X2;
_L = LOC(PRSO);
if(isT(_L)) {
_LL = LOC(_L);
}
if((!(isLIT)
&& !(isEQUAL(WINNER, _L, _LL)))) {
TOO_DARK();
return true;
} else if(isEQUAL(_L, GLOBAL_OBJECTS)) {
IMPOSSIBLE();
return true;
} else if(isEQUAL(_L, WINNER)) {
THIS_IS_IT(PRSO);
TELL(ALREADY);
if(isIS(PRSO, WORN)) {
TELL(B("WEAR"));
} else {
TELL(B("HOLD"));
}
TELL("ing ", THEO, PERIOD);
return true;
} else if((!(isEQUAL(_L, null, BROG))
&& isIS(_L, CONTAINER)
&& isIS(_L, TRANSPARENT)
&& !(isIS(_L, OPENED)))) {
CANT_REACH_INTO(_L);
return true;
} else if((!(isEQUAL(_LL, null, BROG))
&& isIS(_LL, CONTAINER)
&& isIS(_LL, TRANSPARENT)
&& !(isIS(_LL, OPENED)))) {
CANT_REACH_INTO(_LL);
return true;
} else if(isT(PRSI)) {
if(isPRSO(PRSI)) {
_X = P_NAMW[0];
_X2 = P_ADJW[0];
if((isEQUAL(_X, P_NAMW[1])
|| isEQUAL(_X2, P_ADJW[1]))) {
IMPOSSIBLE();
return true;
}
} else if(isPRSI(ME)) {
if(isEQUAL(WINNER, PLAYER)) {
NOBODY_TO_ASK();
return true;
} else if(!(isEQUAL(_L, WINNER))) {
TELL(CTHE(WINNER), " doesn't have "
, THEO, PERIOD);
return true;
} else {
return false;
}
} else if(!(isEQUAL(_L, PRSI))) {
if((isEQUAL(_L, ON_MCASE, ON_WCASE, ON_BCASE)
&& isPRSI(MCASE, WCASE, BCASE))) {
return false;
}
TELL(CTHEO);
ISNT_ARENT();
ON_IN(PRSI);
TELL(PERIOD);
return true;
}
return false;
} else if(isEQUAL(PRSO, LOC(WINNER))) {
if(isPRSO(BUSH, POOL)) {
return false;
}
TELL("Difficult. You're");
ON_IN();
TELL(PERIOD);
return true;
} else {
return false;
}
}
function CANT_REACH_INTO(_L) {
TELL(CANT, "reach into ", THE(_L), ". It's closed.", CR);
return true;
}
function V_TAKE() {
let _L;
_L = ITAKE();
if(!(_L)) {
return true;
} else if(isSPARK(null)) {
TELL(TAB);
}
if((isT(isP_MULT)
|| isEQUAL(_L, UNDERUG, UNDERPEW, LAMPHOUSE)
|| (isT(STATIC)
&& isIS(PRSO, FERRIC)))) {
TAKEN();
return true;
} else if((isIS(_L, CONTAINER)
|| isIS(_L, SURFACE)
|| isIS(_L, PERSON)
|| isIS(_L, LIVING))) {
TELL("You take ", THEO);
OUT_OF_LOC(_L);
TELL(PERIOD);
return true;
} else if(PROB(50)) {
TAKEN();
return true;
}
TELL(CYOU);
if(isEQUAL(P_PRSA_WORD, "GRAB", "SEIZE", "SNATCH")) {
TELL(B(P_PRSA_WORD));
} else if(PROB(50)) {
TELL("pick up");
} else {
TELL(B("TAKE"));
}
TELL(C(SP), THEO, PERIOD);
return true;
}
function TAKEN() {
TELL("Taken.", CR);
return true;
}
function isFIRST_TAKE() {
if((isVERB(V_TAKE)
&& !(isIS(PRSO, TOUCHED)))) {
if(ITAKE()) {
PUTP(PRSO, "DESCFCN", 0);
TAKEN();
}
return true;
} else {
return false;
}
}
function ITAKE(_VB=true) {
let _CNT=0, _OBJ, _L, _X, _MAX;
if((!(PRSO)
|| !((_L = LOC(PRSO))))) {
CANT_SEE_ANY();
return false;
}
THIS_IS_IT(PRSO);
if(!(isIS(PRSO, TAKEABLE))) {
if(isT(_VB)) {
IMPOSSIBLE();
}
return false;
} else if((isIS(_L, CONTAINER)
&& isIS(_L, OPENABLE)
&& !(isIS(_L, OPENED))
&& !(isEQUAL(_L, LOC(WINNER))))) {
if(isT(_VB)) {
YOUD_HAVE_TO("open", _L);
}
return false;
}
if((isEQUAL(WINNER, UNICORN)
&& (_X = isFIRST(WINNER)))) {
MOVE(_X, LOC(WINNER));
TELL("[putting down ", THE(_X), " first", BRACKET);
} else if(isEQUAL(WINNER, PLAYER)) {
if(isIN(ONION, PLAYER)) {
if(isT(_VB)) {
YOUD_HAVE_TO("put down", ONION);
}
return false;
}
_X = WEIGHT(PRSO);
_MAX = (LOAD_ALLOWED + (STATS[STRENGTH] / 10));
if((!(isIN(_L, WINNER))
&& (_X + WEIGHT(WINNER)) > _MAX)) {
if(isT(_VB)) {
if((_X = isFIRST(WINNER))) {
TELL("Your load is ");
} else {
TELL(CTHEO);
IS_ARE();
}
TELL("too heavy.", CR);
}
return false;
}
if((_OBJ = isFIRST(WINNER))) {
while(true) {
if(isIS(_OBJ, NODESC)) {
} else if(isIS(_OBJ, WORN)) {
} else if(isIS(_OBJ, TAKEABLE)) {
++_CNT
}
if(!((_OBJ = isNEXT(_OBJ)))) {
break;
}
}
}
_MAX = (FUMBLE_NUMBER + (STATS[DEXTERITY] / 10));
if(_CNT > _MAX) {
if(isT(_VB)) {
TELL("Your hands are full.", CR);
}
return false;
}
}
WINDOW(SHOWING_ALL);
MAKE(PRSO, TOUCHED);
UNMAKE(PRSO, NODESC);
UNMAKE(PRSO, NOALL);
MOVE(PRSO, WINNER);
return _L;
}"So that .L an be analyzed."
"Return total weight of objects in THING."
function WEIGHT(_THING) {
let _WT=0, _OBJ;
if((_OBJ = isFIRST(_THING))) {
while(true) {
if((isEQUAL(_THING, WINNER)
&& isIS(_OBJ, WORN))) {
++_WT
} else {
_WT = (_WT + WEIGHT(_OBJ));
}
if(!((_OBJ = isNEXT(_OBJ)))) {
break;
}
}
}
return (_WT + GETP(_THING, "SIZE"));
}
function V_WIELD() {
let _OBJ;
if(!(isIS(PRSO, TAKEABLE))) {
IMPOSSIBLE();
return true;
} else if(!(isIN(PRSO, WINNER))) {
MUST_HOLD(PRSO);
TELL(" before you can wield it.", CR);
return true;
} else if(isIS(PRSO, WORN)) {
YOUD_HAVE_TO("take off", PRSO);
return true;
} else if(isIS(PRSO, WIELDED)) {
TELL(ALREADY, "wielding ", THEO, PERIOD);
return true;
}
if((_OBJ = isFIRST(WINNER))) {
while(true) {
if(isIS(_OBJ, WIELDED)) {
UNMAKE(_OBJ, WIELDED);
TELL("[setting aside ", THE(_OBJ), " first", BRACKET);
break;
}
if(!((_OBJ = isNEXT(_OBJ)))) {
break;
}
}
}
WINDOW(SHOWING_INV);
MAKE(PRSO, WIELDED);
TELL("You wield ", THEO, PERIOD);
return true;
}
function V_UNWIELD() {
if(!(isIS(PRSO, TAKEABLE))) {
IMPOSSIBLE();
return true;
} else if(!(isIS(PRSO, WIELDED))) {
TELL("You're not wielding ", THEO, PERIOD);
return true;
}
WINDOW(SHOWING_INV);
UNMAKE(PRSO, WIELDED);
TELL("You set aside ", THEO, PERIOD);
return true;
}
function isSPARK(_INDENT=true, _OBJ=PRSO) {
if(isNO_SPARK(_OBJ)) {
return false;
} else if(isT(_INDENT)) {
TELL(TAB);
}
ITALICIZE("Snap");
TELL("! You feel a ");
if(STATIC > 2) {
TELL("painful ");
}
TELL("spark as you touch ", THE(_OBJ), PERIOD);
UPDATE_STAT((0 - STATIC));
SPARK_OBJ(_OBJ);
return true;
}
function isSPARK_TO(_OBJ1=PRSO, _OBJ2=PRSI) {
if(isNO_SPARK(_OBJ2)) {
return false;
} else if(isEQUAL(_OBJ1, HANDS, FEET, ME)) {
} else if(!(isIS(_OBJ1, FERRIC))) {
return false;
}
SAY_SNAP();
SAY_YOUR(_OBJ1);
TELL(AND, THE(_OBJ2), "!", CR);
if(!(isIS(_OBJ1, FERRIC))) {
UPDATE_STAT((0 - STATIC));
}
SPARK_OBJ(_OBJ2);
return true;
}
function SAY_SNAP() {
ITALICIZE("Snap");
TELL("! A ");
if(STATIC > 3) {
TELL("painful ");
}
TELL("spark leaps between ");
return false;
}
function isNO_SPARK(_OBJ) {
let _L;
if(!(STATIC)) {
return true;
}
_L = LOC(_OBJ);
if(isEQUAL(_L, null, LOCAL_GLOBALS, GLOBAL_OBJECTS)) {
return true;
} else if(isEQUAL(PLAYER, _L, LOC(_L))) {
return true;
} else {
return false;
}
}
function SPARK_OBJ(_OBJ) {
if(!(isIS(_OBJ, LIVING))) {
} else if(isEQUAL(_OBJ, DUST)) {
VANISH(DUST);
DEQUEUE(I_DUST);
MOVE(RING, HERE);
P_IT_OBJECT = RING;
P_THEM_OBJECT = NOT_HERE_OBJECT;
TELL(" A bright blue ");
ITALICIZE("snap");
TELL(" of electricity lights the room! ");
BLINK(DUST);
TELL(" draw");
if(isEQUAL(BUNNIES, 1)) {
TELL("s itself");
} else {
TELL(" themselves");
}
TELL(" together into a hard ring of particles, which falls with a clatter to your feet.", CR);
UPDATE_STAT(GETP(DUST, "VALUE"), EXPERIENCE);
} else if(isIS(_OBJ, MONSTER)) {
MAKE(_OBJ, STRICKEN);
PUTP(_OBJ, "ENDURANCE"
, (GETP(_OBJ, "ENDURANCE") - STATIC));
} else {
TELL(TAB, CTHE(_OBJ), " looks at you reproachfully.", CR);
if(isEQUAL(_OBJ, UNICORN)) {
UPDATE_STAT(-5, LUCK, true);
}
}
STATIC = 0;
return false;
}
function BLINK(_OBJ) {
TELL("In the blink of an eye, ", THE(_OBJ));
return false;
}
"Takes monster OBJ and NEGATIVE damage, returns net damage."
function isMSPARK(_OBJ, _DAMAGE) {
let _X;
if(!(STATIC)) {
return _DAMAGE;
}
_X = (GETP(_OBJ, "ENDURANCE") + _DAMAGE);
TELL(TAB);
SAY_SNAP();
TELL("you and ", THE(_OBJ));
if(_X < 1) {
_X = 1;
TELL(", leaving it nearly stunned");
}
TELL(PERIOD);
PUTP(_OBJ, "ENDURANCE", _X);
_DAMAGE = (_DAMAGE - STATIC);
STATIC = 0;
return _DAMAGE;
}
function V_DROP() {
if(IDROP()) {
SAY_DROPPED();
}
return true;
}
function SAY_DROPPED() {
if((isT(isP_MULT)
|| PROB(50))) {
TELL("Dropped.", CR);
return true;
}
TELL(CYOU);
if(PROB(50)) {
TELL("drop ");
} else {
TELL("put down ");
}
TELL(THEO, PERIOD);
return true;
}
function IDROP() {
let _L;
_L = LOC(PRSO);
if((isEQUAL(_L, null, LOCAL_GLOBALS, GLOBAL_OBJECTS)
|| isPRSO(WINNER, ME))) {
IMPOSSIBLE();
return false;
} else if(!(isEQUAL(_L, WINNER))) {
if(isEQUAL(WINNER, PLAYER)) {
TELL("You'd ");
} else {
TELL(CTHE(WINNER), " would ");
}
TELL("have to take ", THEO);
OUT_OF_LOC(_L);
TELL(SFIRST);
return false;
} else if((isIS(PRSO, WORN)
&& isIN(PRSO, WINNER))) {
if(isTAKE_OFF_PRSO_FIRST()) {
return true;
}
} else if(isPRSO(MINX)) {
UNMAKE(PRSO, SEEN);
UNMAKE(PRSO, TOUCHED);
UNMAKE(PRSO, TRYTAKE);
} else if(isPRSO(TRUFFLE)) {
UNMAKE(MINX, SEEN);
}
UNMAKE(PRSO, WIELDED);
WINDOW(SHOWING_ALL);
_L = LOC(WINNER);
if((isHERE(IN_SKY, ON_BRIDGE, APLANE)
|| isEQUAL(_L, SADDLE))) {
TELL(CTHEO, C(SP));
FALLS();
return false;
}
MOVE(PRSO, _L);
return true;
}
function PRSO_SLIDES_OFF_PRSI() {
TELL(CTHEO, " slide");
if(!(isIS(PRSO, PLURAL))) {
TELL("s");
}
TELL(" off ", THEI, AND);
FALLS();
return true;
}
function FALLS(_OBJ=PRSO, _V=true) {
let _S, _L, _X;
_S = "s ";
if(isIS(_OBJ, PLURAL)) {
_S = " ";
}
_L = LOC(WINNER);
WINDOW(SHOWING_ALL);
UNMAKE(_OBJ, WIELDED);
UNMAKE(_OBJ, WORN);
if(isHERE(ON_BRIDGE)) {
VANISH(_OBJ);
if(isT(_V)) {
TELL("slip", _S, B("BETWEEN"), " the ropes and ");
}
TELL("fall", _S, "out of sight.", CR);
return true;
} else if(isHERE(IN_SKY, APLANE)) {
_X = isDOWN_TO();
if(!(_X)) {
REMOVE(_OBJ);
} else {
MOVE(_OBJ, _X);
}
if(isHERE(IN_SKY)) {
TELL("fall", _S, "out of sight.", CR);
return true;
}
if(isEQUAL(_OBJ, PHASE)) {
MUNG_PHASE();
}
TELL("disappear", _S, "in a spectral flash.", CR);
return true;
} else if(isEQUAL(_L, SADDLE)) {
_X = LOC(_L);
if(isIS(_X, VEHICLE)) {
MOVE(_OBJ, LOC(_X));
} else {
MOVE(_OBJ, _X);
}
if(isT(_V)) {
TELL("slide", _S, "off ", THE(_L), AND);
}
} else {
MOVE(_OBJ, _L);
}
TELL("land", _S, "on the ");
GROUND_WORD();
TELL(PERIOD);
return true;
}
function V_CASH() {
if(!(LOOT)) {
PRINT("You're broke.|");
return true;
}
SAY_CASH();
return true;
}
function V_INVENTORY() {
if((!(DMODE)
|| isEQUAL(PRIOR, SHOWING_ROOM, SHOWING_STATS))) {
PRINT_INVENTORY();
} else {
TELL("You take stock of your possessions.", CR);
DBOX_TOP = 0;
UPDATE_INVENTORY();
if(LOWCORE(FLAGS) & 1) {
DIROUT(D_SCREEN_OFF);
CRLF();
PRINT_INVENTORY();
DIROUT(D_SCREEN_ON);
}
}
if(!(isIS(MONEY, TOUCHED))) {
MAKE(MONEY, TOUCHED);
TELL(TAB);
NYMPH_APPEARS("financial");
TELL("By the way, you can check the amount of cash you're holding at any time with the CASH command. Or, just type a $ followed by [RETURN]");
PRINT(". Bye!\"| She disappears with a wink.|");
}
return true;
}
function UPDATE_INVENTORY() {
IN_DBOX = SHOWING_INV;
SETUP_DBOX();
PRINT_INVENTORY();
JUSTIFY_DBOX();
DISPLAY_DBOX();
return false;
}
var WEARING = () => OBJECT({
});
var HOLDING = () => OBJECT({
});
var isINV_PRINTING/*FLAG*/ = null;
function PRINT_INVENTORY() {
let _HOLDS=0, _WORNS=0, _ANY=0, _B=0, _OBJ, _NXT;
if(!((_OBJ = isFIRST(WINNER)))) {
NUTHIN();
return true;
}
isINV_PRINTING = true;
while(true) {
_NXT = isNEXT(_OBJ);
if((isIS(_OBJ, NODESC)
|| !(isIS(_OBJ, TAKEABLE)))) {
MOVE(_OBJ, DUMMY_OBJECT);
} else if((isIS(_OBJ, CLOTHING)
&& isIS(_OBJ, WORN))) {
++_WORNS
MOVE(_OBJ, WEARING);
} else if((isEQUAL(_OBJ, GOBLET)
&& isIN(BFLY, _OBJ)
&& isIS(BFLY, LIVING))) {
++_B
MAKE(BFLY, NODESC);
}
if((isSEE_INSIDE(_OBJ)
&& isSEE_ANYTHING_IN(_OBJ))) {
++_HOLDS
MOVE(_OBJ, HOLDING);
}
_OBJ = _NXT;
if(!(_OBJ)) {
break;
}
}
if((_OBJ = isFIRST(WINNER))) {
while(true) {
_NXT = isNEXT(_OBJ);
if(isIS(_OBJ, WIELDED)) {
REMOVE(_OBJ);
MOVE(_OBJ, WINNER);
}
_OBJ = _NXT;
if(!(_OBJ)) {
break;
}
}
++_ANY
TELL("You're carrying ");
CONTENTS(WINNER);
PRINT(PERIOD);
}
if(isT(_HOLDS)) {
if(isT(_ANY)) {
TELL(TAB, "You're also ");
} else {
TELL("You're ");
}
++_ANY
TELL("carrying ");
CONTENTS(HOLDING);
if((_OBJ = isFIRST(HOLDING))) {
while(true) {
TELL(". ");
if(isEQUAL(_OBJ, GURDY)) {
TELL("Within");
} else if(isIS(_OBJ, CONTAINER)) {
TELL("Inside");
} else {
TELL("Upon");
}
TELL(C(SP), THE(_OBJ), " you see ");
CONTENTS(_OBJ);
if(!((_OBJ = isNEXT(_OBJ)))) {
break;
}
}
}
TELL(PERIOD);
MOVE_ALL(HOLDING, WINNER);
}
if(isT(_WORNS)) {
if(isT(_ANY)) {
TELL(TAB);
}
++_ANY
TELL("You're wearing ");
CONTENTS(WEARING);
if((_OBJ = isFIRST(WEARING))) {
while(true) {
if((isSEE_INSIDE(_OBJ)
&& isSEE_ANYTHING_IN(_OBJ))) {
TELL(". ");
if(isIS(_OBJ, CONTAINER)) {
TELL("Inside");
} else {
TELL("Upon");
}
TELL(C(SP), THE(_OBJ), " you see ");
CONTENTS(_OBJ);
}
if(!((_OBJ = isNEXT(_OBJ)))) {
break;
}
}
}
TELL(PERIOD);
MOVE_ALL(WEARING, WINNER);
}
MOVE_ALL(DUMMY_OBJECT, WINNER);
if(!(_ANY)) {
NUTHIN();
} else if(isT(LOOT)) {
TELL(TAB);
SAY_CASH();
}
if(isT(_B)) {
UNMAKE(BFLY, NODESC);
}
isINV_PRINTING = null;
return true;
}
function NUTHIN() {
TELL(DONT, "have anything");
if(isT(LOOT)) {
TELL(" except ");
SAY_LOOT();
}
PRINT(PERIOD);
return true;
}
function PRE_EXAMINE() {
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
} else {
return false;
}
}
function V_EXAMINE() {
if(isIS(PRSO, OPENABLE)) {
TELL("It looks as if ", THEO);
IS_ARE();
if(isIS(PRSO, OPENED)) {
PRINTB("OPEN");
} else {
PRINTB("CLOSED");
}
PRINT(PERIOD);
return true;
} else if(isIS(PRSO, PLACE)) {
CANT_SEE_MUCH();
return true;
} else if(isIS(PRSO, READABLE)) {
TELL("There appears to be something written on it.", CR);
return true;
} else if(isIS(PRSO, SURFACE)) {
TELL(YOU_SEE);
CONTENTS();
TELL(SON, THEO);
PRINT(PERIOD);
return true;
} else if(isIS(PRSO, CONTAINER)) {
if((isIS(PRSO, OPENED)
|| isIS(PRSO, TRANSPARENT))) {
V_LOOK_INSIDE();
return true;
}
ITS_CLOSED();
return true;
} else if(isLOOK_INTDIR()) {
return true;
} else if((isIS(PRSO, PERSON)
&& isSEE_ANYTHING_IN())) {
TELL(CTHEO, " has ");
CONTENTS();
PRINT(PERIOD);
return true;
}
NOTHING_INTERESTING();
TELL(" about ", THEO, PERIOD);
return true;
}
function NOTHING_INTERESTING() {
TELL(YOU_SEE, "nothing ", PICK_NEXT(YAWNS));
return false;
}
var CAN_UNDO/*NUMBER*/ = 0;
function V_UNDO() {
if(isCANT_SAVE()) {
return true;
}
OLD_HERE = null;
IRESTORE(_X => {
if(isEQUAL(_X, -1)) {
NOT_AVAILABLE();
} else if (_X === 1) {
INITVARS();
V_REFRESH();
COMPLETED("RESTORE");
CRLF();
V_LOOK();
} else
FAILED("UNDO");
//setTimeout(DO_MAIN_LOOP, 20);
return true;
});
}
function isCANT_SAVE() {
let _OBJ, _NXT, _X;
if(isT(CHOKE)) {
MUMBLAGE(SKELETON);
return true;
} else if((_OBJ = isFIRST(HERE))) {
while(true) {
if((isIS(_OBJ, MONSTER)
&& isIS(_OBJ, LIVING)
&& !(isIS(_OBJ, SLEEPING)))) {
MUMBLAGE(_OBJ);
return true;
} else if(!((_OBJ = isNEXT(_OBJ)))) {
return false;
}
}
}
return false;
}
function MUMBLAGE(_OBJ) {
PCLEAR();
TELL("You begin to mumble the Spell of ");
if(isVERB(V_SAVE)) {
TELL("Sav");
} else {
TELL("Undo");
}
TELL("ing, but the ");
if(isT(isLIT)) {
TELL("sight of ", THE(_OBJ), " makes");
} else {
TELL("noises in the darkness make");
}
TELL(" your mind wander.", CR);
return true;
}
function V_USE() {
if(isIS(PRSO, PERSON)) {
TELL(CTHEO, " might resent that.", CR);
return true;
}
isHOW();
return true;
}
function V_BITE() {
if(!(isSPARK(null))) {
HACK_HACK("Biting");
}
return true;
}
function V_BLOW_INTO() {
if(isIS(PRSO, PERSON)) {
P_PRSA_WORD = "USE";
PERFORM("USE", PRSO);
return true;
}
HACK_HACK("Blowing");
return true;
}
function V_LIGHT_ON() {
TELL(CANT, "light ", THEO, " on anything.", CR);
return true;
}
function V_LIGHT_WITH() {
V_BURN_WITH();
return true;
}
function V_BURN_WITH() {
if(isT(PRSI)) {
TELL("With ", A(PRSI), "? ");
}
TELL(PICK_NEXT(YUKS), PERIOD);
return true;
}
function ALREADY_HAVE(_OBJ=PRSO) {
if(isEQUAL(WINNER, PLAYER)) {
TELL("You already have ");
} else {
TELL(CTHE(WINNER), " already has ");
}
TELL(A(_OBJ), PERIOD);
return true;
}
/*function NO_MONEY() {
TELL(DONT, "have any money.", CR);
return true;
}*/
function V_CLEAN() {
if(!(isSPARK(null))) {
HACK_HACK("Cleaning");
}
return true;
}
function V_CLEAN_OFF() {
if(isPRSO(PRSI)) {
IMPOSSIBLE();
return true;
}
TELL(CANT, B(P_PRSA_WORD), C(SP), THEO, SON, THEI, PERIOD);
return true;
}
function V_CLIMB_DOWN() {
if((isEQUAL(P_PRSA_WORD, "JUMP", "LEAP", "HURDLE")
|| isEQUAL(P_PRSA_WORD, "VAULT", "BOUND"))) {
PERFORM("DIVE", PRSO);
return true;
} else if(isPRSO(ROOMS)) {
DO_WALK("DOWN");
return true;
}
IMPOSSIBLE();
return true;
}
function V_CLIMB_ON() {
if(isEQUAL(P_PRSA_WORD, "TAKE")) {
PERFORM("HIT", PRSO);
return true;
} else if(isIS(PRSO, VEHICLE)) {
PERFORM("ENTER", PRSO);
return true;
}
TELL(CANT, B(P_PRSA_WORD), " onto that.", CR);
return true;
}
function V_CLIMB_OVER() {
if(isPRSO(ROOMS)) {
V_WALK_AROUND();
return true;
}
TELL(CANT);
TELL("climb over that.", CR);
return true;
}
function V_CLIMB_UP() {
if(isPRSO(ROOMS)) {
DO_WALK("UP");
return true;
}
IMPOSSIBLE();
return true;
}
function V_OPEN_WITH() {
if(!(isIS(PRSO, OPENABLE))) {
CANT_OPEN_PRSO();
return true;
} else if(isIS(PRSO, OPENED)) {
ITS_ALREADY("open");
return true;
}
TELL(CANT, B(P_PRSA_WORD), C(SP), THEO, WITH, THEI, PERIOD);
return true;
}
function CANT_OPEN_PRSO() {
TELL(IMPOSSIBLY, "open ", AO, PERIOD);
return true;
}
function V_OPEN() {
let _X;
if(!(isIS(PRSO, OPENABLE))) {
CANT_OPEN_PRSO();
return true;
} else if(isIS(PRSO, OPENED)) {
ITS_ALREADY("open");
return true;
} else if(isIS(PRSO, LOCKED)) {
TELL(CTHEO, " seems to be locked.", CR);
return true;
}
if(isSPARK()) {
TELL(TAB);
}
TELL("You open ", THEO, PERIOD);
IOPEN();
if((isPRSO(CELLAR_DOOR)
&& !(isIS(ONION, TOUCHED)))) {
TELL(TAB);
COOK_MENTIONS_ONION();
}
return true;
}
function IOPEN(_OBJ=PRSO) {
WINDOW(SHOWING_ALL);
MAKE(_OBJ, OPENED);
if((isIS(_OBJ, DOORLIKE)
&& isIN(_OBJ, LOCAL_GLOBALS))) {
MARK_EXITS();
if(!(DMODE)) {
LOWER_SLINE();
return false;
}
DRAW_MAP();
SHOW_MAP();
return false;
} else if(isIS(_OBJ, CONTAINER)) {
if(isIS(_OBJ, TRANSPARENT)) {
return false;
} else if(!(isSEE_ANYTHING_IN(_OBJ))) {
return false;
}
TELL(TAB);
PRINT("Peering inside, you see ");
CONTENTS(_OBJ);
PRINT(PERIOD);
}
return false;
}
function ICLOSE(_OBJ=PRSO) {
WINDOW(SHOWING_ALL);
UNMAKE(_OBJ, OPENED);
if((isIS(_OBJ, DOORLIKE)
&& isIN(_OBJ, LOCAL_GLOBALS))) {
if(!(DMODE)) {
LOWER_SLINE();
return false;
}
DRAW_MAP();
SHOW_MAP();
}
return false;
}
function V_CLOSE() {
if(isIS(PRSO, OPENABLE)) {
if(isIS(PRSO, OPENED)) {
if(isSPARK()) {
TELL(TAB);
}
TELL("You close ", THEO, PERIOD);
ICLOSE();
return true;
}
ITS_ALREADY("closed");
return true;
}
TELL(CANT);
TELL("close ", AO, PERIOD);
return true;
}
function V_COUNT() {
if(isIS(PRSO, PLURAL)) {
TELL("Your mind wanders, and you lose count.", CR);
return true;
}
ONLY_ONE();
return true;
}
function ONLY_ONE() {
TELL("You only see one.", CR);
return true;
}
function V_COVER() {
PERFORM("PUT-ON", PRSI, PRSO);
return true;
}
function V_HOLD_OVER() {
WASTE_OF_TIME();
return true;
}
function V_CROSS() {
TELL(CANT);
TELL("cross that.", CR);
return true;
}
function V_CUT() {
if(isPRSI(DAGGER, SWORD, AXE)) {
NYMPH_APPEARS("safety");
TELL("Careful with that ", PRSI
, "!\" she scolds, wagging a tiny finger. \"You might hurt ", ME);
PRINT(". Bye!\"| She disappears with a wink.|");
return true;
}
V_RIP();
return true;
}
function V_RIP() {
TELL(IMPOSSIBLY, B(P_PRSA_WORD), C(SP), THEO);
if(!(isPRSI(HANDS))) {
TELL(WITH, THEI);
}
PRINT(PERIOD);
return true;
}
function V_DEFLATE() {
IMPOSSIBLE();
return true;
}
function V_DETONATE() {
IMPOSSIBLE();
return true;
}
function PRE_DIG_UNDER() {
return PRE_DIG();
}
function PRE_DIG() {
if(isPRSO(PRSI)) {
IMPOSSIBLE();
return true;
} else if(!(isLIT)) {
TOO_DARK();
return true;
} else if(isT(PRSI)) {
return false;
}
PRSI = HANDS;
if(isIN(SPADE, PLAYER)) {
PRSI = SPADE;
}
TELL("[with ", THEI, BRACKET);
return false;
}
function V_DIG_UNDER() {
WASTE_OF_TIME();
return true;
}
function V_DIG() {
WASTE_OF_TIME();
return true;
}
function V_SDIG() {
PERFORM("DIG", PRSI, PRSO);
return RFATAL();
}
function V_DRINK(_isFROM=null) {
TELL(CANT);
TELL("drink ");
if(isT(_isFROM)) {
TELL("from ");
}
TELL(D(NOT_HERE_OBJECT), PERIOD);
return true;
}
function V_DRINK_FROM() {
V_DRINK(true);
return true;
}
function V_EAT() {
if(isEQUAL(WINNER, PLAYER)) {
NOT_LIKELY();
TELL(" would agree with you.", CR);
return true;
}
TELL("\"It", PICK_NEXT(LIKELIES)
, " that ", THEO, " would agree with me.\"", CR);
return true;
}
function V_ENTER() {
let _X;
if(isIS(PRSO, VEHICLE)) {
if(isIN(PLAYER, PRSO)) {
TELL("You're already");
ON_IN();
TELL(PERIOD);
return true;
} else if(!(isEQUAL(LOC(PRSO), HERE, LOCAL_GLOBALS))) {
CANT_FROM_HERE();
return true;
} else if(isDROP_ONION_FIRST()) {
return true;
}
OLD_HERE = null;
WINDOW(SHOWING_ROOM);
MOVE(PLAYER, PRSO);
TELL("You get");
ON_IN();
RELOOK();
return true;
} else if(isPRSO(ROOMS)) {
_X = isFIND_IN(HERE, VEHICLE);
if(isT(_X)) {
P_PRSA_WORD = "ENTER";
PERFORM("ENTER", _X);
return true;
}
DO_WALK("IN");
return true;
} else if(isIS(PRSO, CLOTHING)) {
PRINT("[Presumably, you mean ");
TELL("WEAR ", THEO);
PRINTC('\.'.charCodeAt(0));
PRINT(BRACKET);
P_PRSA_WORD = "WEAR";
PERFORM("WEAR", PRSO);
return true;
}
IMPOSSIBLE();
return true;
}
function V_ESCAPE() {
if(isIS(PRSO, PLACE)) {
NOT_IN();
return true;
}
V_WALK_AROUND();
return true;
}
function PRE_DUMB_EXAMINE() {
if(!(isLIT)) {
TOO_DARK();
return true;
} else if(isLOOK_INTDIR()) {
return true;
}
if(!(isIS(EYES, SEEN))) {
MAKE(EYES, SEEN);
PRINT("[Presumably, you mean ");
TELL("LOOK AT ", THEO
, ", not LOOK INSIDE or LOOK UNDER or LOOK BEHIND ", THEO);
PRINTC('\.'.charCodeAt(0));
PRINT(BRACKET);
}
PERFORM("EXAMINE", PRSO);
return true;
}
function V_DUMB_EXAMINE() {
V_EXAMINE();
return true;
}
function isLOOK_INTDIR() {
let _X;
if(isPRSO(RIGHT, LEFT)) {
} else if(!(isPRSO(INTDIR))) {
return false;
}
_X = GETP(HERE, "SEE-ALL");
if(isT(_X)) {
THIS_IS_IT(_X);
TELL(YOU_SEE);
if((!(isIS(_X, NOARTICLE))
&& !(isIS(_X, PLURAL)))) {
TELL(LTHE);
}
TELL(D(_X), " that way.", CR);
return true;
}
NOTHING_INTERESTING();
TELL(SIN, D(RIGHT), PERIOD);
return true;
}
function PRE_EXAMINE_IN() {
let _L;
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
} else if(isPRSO(PRSI)) {
IMPOSSIBLE();
return true;
} else if(isIN(PRSI, GLOBAL_OBJECTS)) {
return false;
} else if((isIN(PRSI, LOCAL_GLOBALS)
&& isIS(PRSI, PLACE))) {
return false;
}
_L = LOC(PRSO);
if(isEQUAL(_L, PRSI)) {
return false;
} else if(isIN(_L, PRSI)) {
return false;
}
TELL(CTHEO);
ISNT_ARENT();
ON_IN(PRSI);
TELL(PERIOD);
return true;
}
function V_EXAMINE_IN() {
V_EXAMINE();
return true;
}
function V_EXIT() {
let _L;
if(isPRSO(ROOMS)) {
_L = LOC(WINNER);
if(isIS(_L, VEHICLE)) {
PERFORM("EXIT", _L);
return true;
}
DO_WALK("OUT");
return true;
} else if((isT(PRSO)
&& isIS(PRSO, VEHICLE))) {
if(!(isIN(WINNER, PRSO))) {
TELL("You're not");
ON_IN();
TELL(PERIOD);
return true;
}
OLD_HERE = null;
WINDOW(SHOWING_ROOM);
MOVE(WINNER, LOC(PRSO));
TELL("You get");
OUT_OF_LOC(PRSO);
RELOOK();
return true;
}
_L = LOC(PRSO);
if(isIS(PRSO, PLACE)) {
NOT_IN();
return true;
} else if((isIS(_L, CONTAINER)
&& isVISIBLE(PRSO))) {
TELL("[from ", D(_L), BRACKET);
PERFORM("TAKE", PRSO);
return true;
}
DO_WALK("OUT");
return true;
}
function V_FILL_FROM() {
V_FILL();
return true;
}
function V_FILL() {
if((isPRSO(VIAL, GOBLET)
&& isVISIBLE(POOL))) {
TELL("[from ", THE(POOL), BRACKET);
P_PRSA_WORD = "GET";
PERFORM("FILL-FROM", PRSO, POOL);
return true;
}
TELL(CANT, B(P_PRSA_WORD), C(SP), THEO, PERIOD);
return true;
}
function V_SUBMERGE() {
if((isPRSO(CIRCLET)
&& isVISIBLE(JAR))) {
TELL("[into ", THE(JAR), BRACKET);
DIP_CIRCLET();
return true;
} else if(isIN(POOL, HERE)) {
TELL("[in ", THE(POOL), BRACKET);
if(isPRSO(VIAL, GOBLET)) {
PERFORM("FILL-FROM", PRSO, POOL);
return true;
}
PERFORM("PUT-UNDER", PRSO, POOL);
return true;
}
TELL(NOTHING, "here in which to ", B(P_PRSA_WORD
), C(SP), THEO, PERIOD);
return true;
}
function V_FIND() {
let _L;
_L = LOC(PRSO);
if(!(_L)) {
} else if(isPRSO(ME, HANDS, WINNER)) {
PRINT("You're right here.|");
return true;
} else if(isIN(PRSO, WINNER)) {
TELL("You're holding it.", CR);
return true;
} else if((isIN(PRSO, HERE)
|| (isIN(PRSO, LOCAL_GLOBALS)
&& isGLOBAL_IN(HERE, PRSO))
|| isIN(PRSO, LOC(WINNER)))) {
ITS_RIGHT_HERE();
return true;
} else if(((isIS(_L, PERSON)
|| isIS(_L, LIVING))
&& isVISIBLE(_L))) {
TELL(CTHE(_L), " has it.", CR);
return true;
} else if((isSEE_INSIDE(_L)
&& isVISIBLE(_L))) {
SAY_ITS();
ON_IN(_L);
TELL(PERIOD);
return true;
}
DO_IT_YOURSELF();
return true;
}
function DO_IT_YOURSELF() {
TELL("You'll have to do that ", D(ME), PERIOD);
return true;
}
function ITS_RIGHT_HERE() {
SAY_ITS();
TELL(" right here in front of you.", CR);
return true;
}
function SAY_ITS() {
if(isIS(PRSO, PLURAL)) {
TELL("They're");
return true;
} else if(isIS(PRSO, FEMALE)) {
TELL("She's");
return true;
} else if(isIS(PRSO, PERSON)) {
TELL("He's");
return true;
}
TELL("It's");
return true;
}
function V_LAND() {
if(isHERE(IN_SKY)) {
DO_WALK("DOWN");
return true;
}
NOT_FLYING();
return true;
}
function NOT_FLYING() {
TELL("You're not flying", AT_MOMENT);
return true;
}
function V_LAND_ON() {
if(!(isHERE(IN_SKY))) {
NOT_FLYING();
return true;
} else if(isPRSO(GROUND, FLOOR)) {
DO_WALK("DOWN");
return true;
}
V_WALK_AROUND();
return true;
}
function V_BANK() {
if((isPRSO(INTDIR)
&& isT(P_DIRECTION)
&& isHERE(IN_SKY))) {
V_WALK();
return true;
}
NOT_FLYING();
return true;
}
function V_FLY() {
if((isPRSO(ROOMS)
&& isIN(PLAYER, SADDLE)
&& isIN(SADDLE, DACT))) {
if(isHERE(IN_SKY)) {
TELL("Try looking down.", CR);
return true;
}
DO_WALK("UP");
return true;
}
TELL("Psst! Guess what? ", CANT, "fly unassisted.", CR);
return true;
}
function V_FLY_UP() {
if((isPRSO(ROOMS)
&& isIN(PLAYER, SADDLE)
&& isIN(SADDLE, DACT))) {
DO_WALK("UP");
return true;
}
V_FLY();
return true;
}
function V_FLY_DOWN() {
if((isPRSO(ROOMS)
&& isIN(PLAYER, SADDLE)
&& isIN(SADDLE, DACT))) {
DO_WALK("DOWN");
return true;
}
V_FLY();
return true;
}
function V_FOLD() {
IMPOSSIBLE();
return true;
}
function V_FOLLOW() {
if(!(PRSO)) {
CANT_SEE_ANY();
return RFATAL();
}
TELL("But ");
if(isPRSO(ME, WINNER)) {
if(isEQUAL(WINNER, PLAYER)) {
TELL("you're");
} else {
TELL(THE(WINNER), " is");
}
PRINT(" right here.|");
return true;
} else {
TELL(THEO);
if(isIS(PRSO, PLURAL)) {
TELL(" are");
} else {
TELL(" is");
}
if((isVISIBLE(PRSO)
|| isIN(PRSO, GLOBAL_OBJECTS))) {
PRINT(" right here.|");
return true;
}
}
TELL("n't visible", AT_MOMENT);
return true;
}
function PRE_FEED() {
if(PRE_GIVE(true)) {
return true;
} else {
return false;
}
}
function V_FEED() {
if(isPRSI(ME, WINNER)) {
if(isEQUAL(WINNER, PLAYER)) {
TELL("You");
} else {
TELL(CTHE(WINNER));
}
} else {
TELL(CTHEI);
}
TELL(" can't eat that.", CR);
return true;
}
function V_SFEED() {
PERFORM("FEED", PRSI, PRSO);
return true;
}
function PRE_GIVE(_isFEED=null) {
if((!(PRSO)
|| !(PRSI))) {
REFERRING();
return true;
} else if(!(isLIT)) {
TOO_DARK();
return true;
} else if(isEQUAL(PRSO, PRSI)) {
IMPOSSIBLE();
return true;
} else if(isIN(PRSI, GLOBAL_OBJECTS)) {
IMPOSSIBLE();
return true;
} else if(!(isIS(PRSI, LIVING))) {
TELL(CANT);
if(isT(_isFEED)) {
TELL("feed ");
} else {
TELL("give ");
}
TELL("anything to ", A(PRSI), PERIOD);
return true;
} else if(isPRSO(MONEY, INTNUM)) {
return false;
} else if(isPRSI(ME, WINNER)) {
if(isIN(PRSO, WINNER)) {
ALREADY_HAVE();
return true;
}
} else if(isDONT_HAVE()) {
return true;
}
if((isIS(PRSO, WORN)
&& isIN(PRSO, WINNER))) {
return isTAKE_OFF_PRSO_FIRST();
} else {
return false;
}
}
function V_SGIVE() {
PERFORM("GIVE", PRSI, PRSO);
return true;
}
function V_GIVE() {
if(isPRSI(ME)) {
NOBODY_TO_ASK();
return true;
} else if(isIS(PRSO, PERSON)) {
TELL(CTHEI, " shows little interest in your offer.", CR);
return true;
}
NOT_LIKELY(PRSI);
TELL(" would accept your offer.", CR);
return true;
}
function PRE_SHOW() {
if((!(PRSO)
|| !(PRSI))) {
REFERRING();
return true;
} else if(!(isLIT)) {
TOO_DARK();
return true;
} else if(isEQUAL(PRSO, PRSI)) {
IMPOSSIBLE();
return true;
} else if(isIN(PRSI, GLOBAL_OBJECTS)) {
IMPOSSIBLE();
return true;
} else if(!(isIS(PRSI, LIVING))) {
TELL(CANT);
TELL("show things to ", A(PRSI), PERIOD);
return true;
} else if(isPRSO(MONEY, INTNUM)) {
return false;
} else if(isPRSI(ME, WINNER)) {
if(isIN(PRSO, WINNER)) {
ALREADY_HAVE();
return true;
}
return false;
} else if(isDONT_HAVE()) {
return true;
} else {
return false;
}
}
function V_SSHOW() {
PERFORM("SHOW", PRSI, PRSO);
return true;
}
function V_SHOW() {
TELL(CTHEI, " glance");
if(!(isIS(PRSI, PLURAL))) {
TELL("s");
}
TELL(" at ", THEO, ", but make");
if(!(isIS(PRSI, PLURAL))) {
TELL("s");
}
TELL(" no comment.", CR);
return true;
}
function V_REFUSE() {
if(!(isIS(PRSO, TAKEABLE))) {
WASTE_OF_TIME();
return true;
}
TELL("How could you turn down such a tempting ", D(PRSO), "?", CR);
return true;
}
function V_HIDE() {
if(isHERE(LOC(ARCH))) {
TELL("[under ", THE(ARCH), BRACKET);
ENTER_ARCH();
return true;
} else if(isHERE(IN_GARDEN)) {
TELL("[behind ", THE(BUSH), BRACKET);
ENTER_BUSH();
return true;
}
TELL("There aren't any good hiding places here.", CR);
return true;
}
function V_KICK() {
if(isSPARK(null)) {
return true;
} else if(isIS(PRSO, MONSTER)) {
PERFORM("HIT", PRSO, FEET);
return true;
}
HACK_HACK("Kicking");
return true;
}
function V_BOUNCE() {
if(isPRSO(ROOMS)) {
WASTE_OF_TIME();
return true;
}
IMPOSSIBLE();
return true;
}
function V_KNOCK() {
if(isSPARK(null)) {
return true;
} else if(isIS(PRSO, DOORLIKE)) {
if(isIS(PRSO, OPENED)) {
ITS_ALREADY("open");
return true;
}
TELL("There's no answer.", CR);
return true;
} else if(isIS(PRSO, PERSON)) {
PERFORM("USE", PRSO);
return true;
}
WASTE_OF_TIME();
return true;
}
function V_KISS() {
if(!(isSPARK(null))) {
WASTE_OF_TIME();
}
return true;
}
function V_LAMP_OFF() {
if(isPRSO(ROOMS)) {
if(isEQUAL(WINNER, PLAYER)) {
TELL("You pause");
} else {
TELL(CTHE(WINNER), " pauses");
}
TELL(" for a moment.", CR);
return true;
}
V_LAMP_ON(true);
return true;
}
function V_LAMP_ON(_isOFF=null) {
TELL(IMPOSSIBLY, "turn that ");
if(isT(_isOFF)) {
TELL("off");
} else {
TELL("on");
}
if(!(isEQUAL(PRSI, null, HANDS))) {
TELL(", ", D(PRSI), " or no ", D(PRSI));
}
PRINT(PERIOD);
return true;
}
function V_LEAP() {
if(!(isPRSO(ROOMS))) {
TELL("That'd be a cute trick.", CR);
return true;
} else if(isHERE(OVER_JUNGLE)) {
JUNGLE_JUMP();
return true;
} else if(isHERE(ON_BRIDGE)) {
JUMP_OFF_BRIDGE();
return true;
}
WASTE_OF_TIME();
return true;
}
function V_LEAVE() {
if(isIS(PRSO, PLACE)) {
NOT_IN();
return true;
} else if((isPRSO(ROOMS)
|| !(isIS(PRSO, TAKEABLE)))) {
DO_WALK("OUT");
return true;
} else if(isDONT_HAVE()) {
return true;
}
PERFORM("DROP", PRSO);
return true;
}
function V_SLEEP() {
V_LIE_DOWN();
return true;
}
function V_LIE_DOWN() {
TELL("This is no time for that.", CR);
return true;
}
function V_LISTEN() {
let _OBJ=null;
if(isPRSO(ROOMS, SOUND_OBJ)) {
_OBJ = GETP(HERE, "HEAR");
if(!(_OBJ)) {
TELL(DONT, "hear anything "
, PICK_NEXT(YAWNS), PERIOD);
return true;
}
PERFORM("LISTEN", _OBJ);
return true;
} else if(isIS(PRSO, LIVING)) {
TELL("No doubt ", THEO, " appreciate");
if(!(isIS(PRSO, PLURAL))) {
TELL("s");
}
TELL(" your attention.", CR);
return true;
}
TELL("At the moment, ", THEO);
IS_ARE();
TELL("silent.", CR);
return true;
}
function V_LOCK() {
if((isIS(PRSO, OPENABLE)
|| isIS(PRSO, CONTAINER))) {
if(isIS(PRSO, OPENED)) {
YOUD_HAVE_TO("close");
return true;
} else if(isIS(PRSO, LOCKED)) {
TELL(CTHEO);
IS_ARE();
TELL("already locked.", CR);
return true;
}
THING_WONT_LOCK(PRSI, PRSO);
return true;
}
CANT_LOCK();
return true;
}
function V_UNLOCK() {
if((isIS(PRSO, OPENABLE)
|| isIS(PRSO, CONTAINER))) {
if((isIS(PRSO, OPENED)
|| !(isIS(PRSO, LOCKED)))) {
TELL(CTHEO);
ISNT_ARENT();
TELL(" locked.", CR);
return true;
}
THING_WONT_LOCK(PRSI, PRSO, true);
return true;
}
CANT_LOCK(true);
return true;
}
function CANT_LOCK(_isUN=null) {
TELL(CANT);
if(isT(_isUN)) {
TELL("un");
}
TELL("lock ", AO, PERIOD);
return true;
}
function THING_WONT_LOCK(_THING, _CLOSED_THING, _isUN=null) {
NOT_LIKELY(_THING);
TELL(" could ");
if(isT(_isUN)) {
TELL("un");
}
TELL("lock ", THE(_CLOSED_THING), PERIOD);
return true;
}
/*function V_SCREW_WITH() {
NOT_LIKELY(PRSI);
TELL(" could help you do that.", CR);
return true;
}*/
/*function V_UNSCREW() {
TELL(CANT, "unscrew ", THEO);
if(!(isPRSI(HANDS))) {
TELL(", with or without ", THEI);
}
PRINT(PERIOD);
return true;
}*/
/*function V_UNSCREW_FROM() {
if(isPRSO(PRSI)) {
IMPOSSIBLE();
return true;
} else if(!(isIN(PRSO, PRSI))) {
if(isIS(PRSI, LIVING)) {
TELL(CTHEI, " doesn't have ", THEO, PERIOD);
return true;
}
TELL(CTHEO);
ISNT_ARENT();
ON_IN(PRSI);
TELL(PERIOD);
return true;
}
TELL(CANT, "unscrew ", THEO, PERIOD);
return true;
}*/
function V_UNTIE() {
TELL(CANT, B(P_PRSA_WORD), C(SP), AO, PERIOD);
return true;
}
function V_LOOK_ON() {
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
} else if(isIS(PRSO, SURFACE)) {
TELL(YOU_SEE);
CONTENTS();
TELL(SON, THEO, PERIOD);
return true;
} else if(isIS(PRSO, READABLE)) {
TELL(CTHEO);
IS_ARE();
TELL("undecipherable.", CR);
return true;
}
NOTHING_INTERESTING();
TELL(SON, THEO, PERIOD);
return true;
}
function V_LOOK_BEHIND() {
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
} else if(isIS(PRSO, DOORLIKE)) {
if(isIS(PRSO, OPENED)) {
CANT_SEE_MUCH();
return true;
}
ITS_CLOSED();
return true;
}
TELL(NOTHING, "behind ", THEO, PERIOD);
return true;
}
function V_LOOK_DOWN() {
let _X;
if(!(isLIT)) {
TOO_DARK();
return true;
} else if(isIS(PRSO, PLACE)) {
CANT_SEE_MUCH();
return true;
} else if(isPRSO(ROOMS)) {
_X = GETP(HERE, "BELOW");
if(isT(_X)) {
PERFORM("EXAMINE", _X);
return true;
} else if(isIS(HERE, INDOORS)) {
PERFORM("EXAMINE", FLOOR);
return true;
}
PERFORM("EXAMINE", GROUND);
return true;
}
PERFORM("LOOK-INSIDE", PRSO);
return true;
}
function V_LOOK_UP() {
let _X=null;
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
} else if(isPRSO(ROOMS)) {
_X = GETP(HERE, "OVERHEAD");
if(isT(_X)) {
PERFORM("EXAMINE", _X);
return true;
}
NOTHING_INTERESTING();
PRINT(PERIOD);
return true;
}
TELL(CANT, "look up ", AO, PERIOD);
return true;
}
function V_LOOK_INSIDE() {
if(!(isLIT)) {
TOO_DARK();
return true;
} else if(isIS(PRSO, PLACE)) {
CANT_SEE_MUCH();
return true;
} else if(isIS(PRSO, PERSON)) {
NOT_A("surgeon");
return true;
} else if(isIS(PRSO, LIVING)) {
NOT_A("veterinarian");
return true;
} else if(isIS(PRSO, CONTAINER)) {
if((!(isIS(PRSO, OPENED))
&& !(isIS(PRSO, TRANSPARENT)))) {
ITS_CLOSED();
return true;
} else if(isSEE_ANYTHING_IN()) {
TELL(YOU_SEE);
CONTENTS();
TELL(SIN, THEO, PERIOD);
return true;
}
TELL(CTHEO, " is empty.", CR);
return true;
} else if(isIS(PRSO, DOORLIKE)) {
if(isIS(PRSO, OPENED)) {
CANT_SEE_MUCH();
return true;
}
ITS_CLOSED();
return true;
}
TELL(CANT, "look inside ", AO, PERIOD);
return true;
}
function V_LOOK_OUTSIDE() {
if(!(isLIT)) {
TOO_DARK();
return true;
} else if(isPRSO(ROOMS)) {
if(isIS(HERE, INDOORS)) {
NOTHING_INTERESTING();
TELL(C(SP));
} else {
TELL(ALREADY);
}
TELL(B("OUTSIDE"), PERIOD);
return true;
} else if(isIS(PRSO, DOORLIKE)) {
if(isIS(PRSO, OPENED)) {
CANT_SEE_MUCH();
return true;
}
ITS_CLOSED();
return true;
}
TELL(CANT, "look out of ", AO, PERIOD);
return true;
}
function V_SLOOK_THRU() {
PERFORM("LOOK-THRU", PRSI, PRSO);
return true;
}
function V_LOOK_THRU() {
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
} else if((isT(PRSI)
&& !(isIS(PRSI, TRANSPARENT)))) {
TELL(CANT, "look through that.", CR);
return true;
}
NOTHING_INTERESTING();
PRINT(PERIOD);
return true;
}
function V_LOOK_UNDER() {
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
}
NOTHING_INTERESTING();
TELL(" under ", THEO, PERIOD);
return true;
}
function V_WEDGE() {
PERFORM("LOOSEN", PRSI, PRSO);
return true;
}
function V_LOOSEN() {
WASTE_OF_TIME();
return true;
}
function V_LOWER() {
if(isPRSO(ROOMS)) {
DO_WALK("DOWN");
return true;
}
V_RAISE();
return true;
}
function V_MAKE() {
isHOW();
return true;
}
function V_MELT() {
isHOW();
return true;
}
function V_MOVE() {
if(isPRSO(ROOMS)) {
V_WALK_AROUND();
return true;
} else if(isIS(PRSO, TAKEABLE)) {
TELL("Moving ", THEO, " would", PICK_NEXT(HO_HUM)
, PERIOD);
return true;
}
TELL(IMPOSSIBLY, B(P_PRSA_WORD), C(SP), THEO, PERIOD);
return true;
}
function V_MUNG() {
if(isIS(PRSO, MONSTER)) {
PERFORM("HIT", PRSO, PRSI);
return true;
} else if(!(isSPARK(null))) {
HACK_HACK("Trying to destroy");
}
return true;
}
function V_PICK() {
if(isIS(PRSO, OPENABLE)) {
NOT_A("locksmith");
return true;
}
IMPOSSIBLE();
return true;
}
function V_POINT() {
if(isT(PRSI)) {
if(isIS(PRSI, PERSON)) {
TELL(CTHEI);
if(isPRSO(PRSI)) {
TELL(" looks confused.", CR);
return true;
}
TELL(GLANCES_AT, THEO, ", but doesn't respond.", CR);
return true;
}
NOT_LIKELY(PRSI);
PRINT(" would respond.|");
return true;
}
TELL("You point at ", THEO);
NOTHING_HAPPENS();
return true;
}
function NOTHING_HAPPENS(_BUT=true) {
if(!(_BUT)) {
PRINTC('\N'.charCodeAt(0));
} else {
TELL(", but n");
}
TELL("othing ", PICK_NEXT(YAWNS), " happens.", CR);
return true;
}
function V_SPOINT_AT() {
PERFORM("POINT-AT", PRSI, PRSO);
return true;
}
function PRE_POINT_AT() {
if((!(isLIT)
&& !(isEQUAL(PRSI, null, ME)))) {
TOO_DARK();
return true;
} else {
return false;
}
}
function V_POINT_AT() {
if(isPRSO(ME, HANDS)) {
V_POINT();
return true;
}
TELL(CYOU, B(P_PRSA_WORD), C(SP), THEO, " at ", THEI);
NOTHING_HAPPENS();
return true;
}
function V_POP() {
TELL(CANT, B(P_PRSA_WORD), C(SP), AO, PERIOD);
return true;
}
function V_POUR() {
if(isPRSO(HANDS)) {
TELL("[To do that, just DROP EVERYTHING.]", CR);
return RFATAL();
} else if(isIS(PRSO, SURFACE)) {
EMPTY_PRSO(GROUND);
return true;
} else if(isIS(PRSO, CONTAINER)) {
if(isIS(PRSO, OPENED)) {
EMPTY_PRSO(GROUND);
return true;
}
ITS_CLOSED();
return true;
}
TELL(CANT, "empty that.", CR);
return true;
}
function V_POUR_FROM() {
if(isPRSO(PRSI)) {
IMPOSSIBLE();
return true;
} else if(isPRSI(HANDS)) {
PERFORM("DROP", PRSO);
return true;
} else if((!(isIS(PRSI, CONTAINER))
&& !(isIS(PRSI, SURFACE)))) {
TELL(CANT, B(P_PRSA_WORD), " things from ", A(PRSI), PERIOD);
return true;
} else if((isIS(PRSI, CONTAINER)
&& !(isIS(PRSI, OPENED)))) {
ITS_CLOSED(PRSI);
return true;
} else if(isIN(PRSO, PRSI)) {
if(isIS(PRSO, TAKEABLE)) {
TELL(CTHEO, C(SP));
FALLS();
return true;
}
IMPOSSIBLE();
return true;
}
TELL(CTHEO, " isn't in ", THEI, PERIOD);
return true;
}
function V_EMPTY_INTO() {
if(isPRSI(HANDS, ME)) {
V_EMPTY();
return true;
} else if(isPRSI(GROUND, FLOOR, GLOBAL_ROOM)) {
if(isHERE(IN_SKY)) {
CANT_FROM_HERE();
return true;
}
V_EMPTY(LOC(WINNER));
return true;
} else if(isIS(PRSI, SURFACE)) {
V_EMPTY(PRSI);
return true;
} else if(isIS(PRSI, CONTAINER)) {
if(isIS(PRSI, OPENED)) {
V_EMPTY(PRSI);
return true;
}
ITS_CLOSED(PRSI);
return true;
}
TELL(CANT, "empty ", THEO);
ON_IN(PRSI);
TELL(PERIOD);
return true;
}
function V_EMPTY(_DEST=0) {
if(isIS(PRSO, PERSON)) {
} else if(isIS(PRSO, LIVING)) {
} else if(isIS(PRSO, MONSTER)) {
} else if(isIS(PRSO, SURFACE)) {
EMPTY_PRSO(_DEST);
return true;
} else if(isIS(PRSO, CONTAINER)) {
if(isIS(PRSO, OPENED)) {
EMPTY_PRSO(_DEST);
return true;
}
ITS_CLOSED();
return true;
}
TELL(IMPOSSIBLY, "empty ", THEO, PERIOD);
return true;
}
function EMPTY_PRSO(_DEST) {
let _ANY=0, _OBJ, _NXT, _X, _ICAP, _ILOAD, _OSIZE;
if(isT(_DEST)) {
_X = LOC(_DEST);
if((!(_X)
|| isEQUAL(PRSO, _DEST))) {
IMPOSSIBLE();
return true;
} else if((isEQUAL(_X, PRSO)
|| isIN(_X, PRSO))) {
YOUD_HAVE_TO("remove", _DEST);
return true;
}
} else {
_DEST = WINNER;
}
if(!(isSEE_ANYTHING_IN())) {
TELL("There's nothing");
ON_IN();
TELL(PERIOD);
return true;
}
isP_MULT = true;
if(!(isEQUAL(_DEST, WINNER, LOC(WINNER)))) {
_ILOAD = WEIGHT(_DEST);
_ILOAD = (_ILOAD - GETP(_DEST, "SIZE"));
_ICAP = GETP(_DEST, "CAPACITY");
}
if((_OBJ = isFIRST(PRSO))) {
while(true) {
_NXT = isNEXT(_OBJ);
if(!(isIS(_OBJ, TAKEABLE))) {
} else if(!(isIS(_OBJ, NODESC))) {
++_ANY
_OSIZE = GETP(_OBJ, "SIZE");
if(!(isIS(_OBJ, NOARTICLE))) {
TELL(XTHE);
}
TELL(D(_OBJ), ": ");
if(isEQUAL(_DEST, WINNER)) {
_X = PERFORM("TAKE", _OBJ, PRSO);
if(isEQUAL(_X, M_FATAL)) {
break;
}
} else if(isEQUAL(_DEST, LOC(WINNER))) {
if(isIS(_OBJ, PLURAL)) {
TELL("They ");
} else {
TELL("It ");
}
FALLS(_OBJ);
} else if(_OSIZE > _ICAP) {
TELL(CTHE(_OBJ));
IS_ARE(_OBJ);
TELL("too big to fit in "
, THE(_DEST), PERIOD);
} else if((_ILOAD + _OSIZE) > _ICAP) {
NO_ROOM_IN(_DEST);
} else {
UNMAKE(_OBJ, WIELDED);
MOVE(_OBJ, _DEST);
TELL("Done.", CR);
}
}
_OBJ = _NXT;
if(!(_OBJ)) {
break;
}
}
}
WINDOW(SHOWING_ALL);
isP_MULT = null;
if(!(_ANY)) {
TELL(NOTHING, "you can take.", CR);
}
return true;
}
function V_PULL() {
if(!(isSPARK(null))) {
HACK_HACK("Pulling on");
}
return true;
}
function V_PUSH() {
if(!(isSPARK(null))) {
HACK_HACK("Pushing around");
}
return true;
}
function V_PUSH_TO() {
if((isPRSO(HANDS)
&& isT(PRSI))) {
PERFORM("REACH-IN", PRSI);
return true;
}
PUSHOVER();
return true;
}
function PUSHOVER() {
TELL(CANT, "push ", THEO, " around like that.", CR);
return true;
}
function V_PUSH_UP() {
if((isPRSO(HANDS)
&& isT(PRSI))) {
PERFORM("RAISE", PRSI);
return true;
}
PUSHOVER();
return true;
}
function V_PUSH_DOWN() {
if((isPRSO(HANDS)
&& isT(PRSI))) {
PERFORM("LOWER", PRSI);
return true;
}
PUSHOVER();
return true;
}
function PRE_PUT() {
let _L;
_L = LOC(PRSO);
if(isPRSO(PRSI)) {
isHOW();
return true;
} else if(isPRSI(INTDIR, RIGHT, LEFT)) {
NYMPH_APPEARS();
TELL("You really must specify an object");
PRINT(". Bye!\"| She disappears with a wink.|");
return true;
} else if(isPRSI(HANDS, HEAD)) {
if((isPRSI(HEAD)
&& isPRSO(HELM))) {
PERFORM("WEAR", PRSO);
return true;
}
NOT_LIKELY();
TELL(" would fit very well.", CR);
return true;
} else if((isEQUAL(FEET, PRSO, PRSI)
|| isEQUAL(HEAD, PRSO, PRSI))) {
WASTE_OF_TIME();
return true;
} else if(!(isLIT)) {
if((isPRSI(GRUE, URGRUE)
&& isWEARING_MAGIC(HELM))) {
} else if(isIN(PRSI, WINNER)) {
} else {
TOO_DARK();
return true;
}
}
if(isPRSO(MONEY, INTNUM)) {
BENJAMIN();
return true;
} else if(isPRSI(GROUND, FLOOR)) {
PERFORM("DROP", PRSO);
return true;
} else if(isIN(PRSI, GLOBAL_OBJECTS)) {
IMPOSSIBLE();
return true;
} else if(isPRSO(HANDS)) {
PERFORM("REACH-IN", PRSI);
return true;
} else if(isEQUAL(_L, PRSI)) {
TELL(CTHEO);
IS_ARE();
TELL("already");
ON_IN(PRSI);
TELL(PERIOD);
return true;
} else if((isEQUAL(PRSO, PRSI)
|| isEQUAL(_L, GLOBAL_OBJECTS)
|| !(isIS(PRSO, TAKEABLE)))) {
IMPOSSIBLE();
return true;
} else if(!(isACCESSIBLE(PRSI))) {
CANT_SEE_ANY(PRSI);
return true;
} else if((isIS(PRSO, WORN)
&& isEQUAL(_L, WINNER)
&& !(isPRSI(ME, WINNER)))) {
return isTAKE_OFF_PRSO_FIRST();
} else if((isIN(_L, WINNER)
&& isVISIBLE(PRSO))) {
TAKING_OBJ_FIRST(PRSO);
if(ITAKE()) {
return false;
}
return true;
} else {
return false;
}
}
function isTAKE_OFF_PRSO_FIRST() {
let _X;
_X = GETP(PRSO, "EFFECT");
if(!(_X)) {
} else if(isPRSO(CLOAK)) {
} else if((isIN(CLOAK, PLAYER)
&& isIS(CLOAK, WORN))) {
YOUD_HAVE_TO("take off", CLOAK);
return true;
}
UNMAKE(PRSO, WORN);
WINDOW(SHOWING_INV);
TELL("[taking off ", THEO, " first]", CR);
if((isPRSO(AMULET)
&& isT(AMULET_TIMER))) {
NORMAL_STRENGTH();
return true;
} else if(isHOTFOOT(true)) {
return true;
} else if((isPRSO(HELM)
&& !(isIS(PRSO, NEUTRALIZED)))) {
NORMAL_IQ();
}
if(isT(_X)) {
UPDATE_STAT((0 - _X), ARMOR_CLASS);
}
TELL(TAB);
return false;
}
function PRE_PUT_ON() {
if(PRE_PUT()) {
return true;
} else if(isPRSI(CHEST)) {
return false;
} else if(!(isIS(PRSI, SURFACE))) {
NO_GOOD_SURFACE();
return true;
} else {
return false;
}
}
function NO_GOOD_SURFACE(_OBJ=PRSI) {
TELL("There's no good surface on ", THE(_OBJ), PERIOD);
return true;
}
function V_PUT_ON() {
if(isPRSI(ME)) {
PERFORM("WEAR", PRSO);
return true;
}
V_PUT();
return true;
}
function V_PUT() {
let _OL, _ICAP, _ILOAD, _OSIZE;
_OL = LOC(PRSO);
if((!(_OL)
|| (isT(PRSI)
&& !(isIS(PRSI, SURFACE))
&& !(isIS(PRSI, CONTAINER))))) {
IMPOSSIBLE();
return true;
} else if((!(isIS(PRSI, OPENED))
&& !(isIS(PRSI, SURFACE)))) {
THIS_IS_IT(PRSI);
TELL(CTHEI);
ISNT_ARENT(PRSI);
TELL(" open.", CR);
return true;
} else if(!(isEQUAL(_OL, WINNER))) {
TELL("Maybe you should take ", THEO);
OUT_OF_LOC(_OL);
TELL(SFIRST);
return true;
}
_ILOAD = WEIGHT(PRSI);
_ILOAD = (_ILOAD - GETP(PRSI, "SIZE"));
_ICAP = GETP(PRSI, "CAPACITY");
_OSIZE = GETP(PRSO, "SIZE");
if(_OSIZE > _ICAP) {
TELL(CTHEO);
IS_ARE();
TELL("too big to fit");
ON_IN(PRSI);
TELL(PERIOD);
return true;
} else if((_ILOAD + _OSIZE) > _ICAP) {
NO_ROOM_IN(PRSI);
return true;
}
WINDOW(SHOWING_ALL);
UNMAKE(PRSO, WIELDED);
MOVE(PRSO, PRSI);
MAKE(PRSO, TOUCHED);
if(isT(isP_MULT)) {
TELL("Done.", CR);
return true;
}
TELL("You put ", THEO);
ON_IN(PRSI);
TELL(PERIOD);
return true;
}
function NO_ROOM_IN(_OBJ) {
TELL("There isn't enough room");
ON_IN(_OBJ);
TELL(PERIOD);
return true;
}
/*function V_SCREW() {
TELL(CANT, "screw ");
O_INTO_I();
return true;
}*/
function V_PLUG_IN() {
TELL(CANT, B(P_PRSA_WORD), C(SP));
O_INTO_I();
return true;
}
function NEVER_FIT() {
TELL("You'd never fit ");
O_INTO_I();
return true;
}
function O_INTO_I(_NOCR) {
TELL(THEO, SINTO, THEI);
if(!(isASSIGNED(_NOCR))) {
TELL(PERIOD);
}
return false;
}
function V_UNPLUG() {
TELL(CTHEO);
ISNT_ARENT();
TELL(" connected to ");
if(isT(PRSI)) {
TELL(THEI);
} else {
TELL("anything");
}
PRINT(PERIOD);
return true;
}
function V_PUT_BEHIND() {
TELL("That hiding place is too obvious.", CR);
return true;
}
function V_PUT_UNDER() {
TELL(CANT, "put anything under that.", CR);
return true;
}
function V_RAPE() {
TELL("What a wholesome idea.", CR);
return true;
}
function V_RAISE() {
if(isPRSO(ROOMS)) {
V_STAND();
return true;
} else if(!(isSPARK(null))) {
HACK_HACK("Toying in this way with");
}
return true;
}
function V_REACH_IN() {
let _OBJ;
_OBJ = isFIRST(PRSO);
if((isIS(PRSO, PERSON)
|| isIS(PRSO, LIVING))) {
NOT_A("surgeon");
return true;
} else if(isIS(PRSO, DOORLIKE)) {
if(isIS(PRSO, OPENED)) {
REACH_INTO_PRSO();
TELL(", but experience nothing "
, PICK_NEXT(YAWNS), PERIOD);
return true;
}
ITS_CLOSED();
return true;
} else if(!(isIS(PRSO, CONTAINER))) {
IMPOSSIBLE();
return true;
} else if(!(isIS(PRSO, OPENED))) {
TELL("It's not open.", CR);
return true;
} else if((isIN(PRSO, PLAYER)
&& isIS(PRSO, WORN))) {
YOUD_HAVE_TO("take off");
return true;
} else if((!(_OBJ)
|| !(isIS(_OBJ, TAKEABLE)))) {
PRINT("It's empty.|");
return true;
}
THIS_IS_IT(_OBJ);
REACH_INTO_PRSO();
TELL(" and feel ", B("SOMETHING"), PERIOD);
return true;
}
function REACH_INTO_PRSO() {
TELL("You reach into ", THEO);
return true;
}
function V_READ() {
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
} else if(!(isIS(PRSO, READABLE))) {
HOW_READ();
TELL("?", CR);
return true;
}
TELL(NOTHING, "written on it.", CR);
return true;
}
function V_READ_TO() {
if(!(isLIT)) {
TOO_DARK();
return RFATAL();
} else if(!(isIS(PRSO, READABLE))) {
HOW_READ();
TELL(STO, A(PRSI), "?", CR);
return true;
} else if(isEQUAL(WINNER, PLAYER)) {
NOT_LIKELY(PRSI);
TELL(" would appreciate your reading.", CR);
return true;
}
TELL("Maybe you ought to do it.", CR);
return true;
}
function HOW_READ() {
TELL("How can you read ", AO);
return true;
}
function V_RELEASE() {
if(isIN(PRSO, WINNER)) {
PERFORM("DROP", PRSO);
return true;
}
if(isPRSO(ME)) {
TELL("You aren't");
} else {
TELL(CTHEO);
ISNT_ARENT();
}
TELL(" being held by anything.", CR);
return true;
}
function V_REPLACE() {
if(isPRSO(ME)) {
TELL("Easily done.", CR);
return true;
}
TELL(CTHEO, " doesn't need replacement.", CR);
return true;
}
function V_REPAIR() {
if(isPRSO(ME)) {
TELL("You aren't");
} else {
TELL(CTHEO);
ISNT_ARENT();
}
TELL(" in need of repair.", CR);
return true;
}
function V_HELP() {
TELL("[If you're really stuck, maps and InvisiClues(TM) Hint Booklets are available at most Infocom dealers, or use the order form included in your game package.]", CR);
return true;
}
function V_RESCUE() {
if(isPRSO(ME)) {
if(isEQUAL(WINNER, PLAYER)) {
V_HELP();
return true;
}
isHOW();
return true;
}
TELL(CTHEO);
if(isIS(PRSO, PLURAL)) {
TELL(" do");
} else {
TELL(" does");
}
TELL("n't need any help.", CR);
return true;
}
function V_RIDE() {
if(isIS(PRSO, LIVING)) {
NOT_LIKELY();
TELL(" wants to play piggyback.", CR);
return true;
} else if(isIS(PRSO, VEHICLE)) {
PERFORM("ENTER", PRSO);
return true;
}
TELL(CANT, "ride that.", CR);
return true;
}
function V_TOUCH() {
if(!(isSPARK(null))) {
HACK_HACK("Fiddling with");
}
return true;
}
function V_STOUCH_TO() {
PERFORM("TOUCH-TO", PRSI, PRSO);
return true;
}
function V_TOUCH_TO() {
if(isSPARK_TO()) {
return true;
}
TELL(CYOU, B(P_PRSA_WORD), C(SP), THEO, " against ", THEI);
NOTHING_HAPPENS();
return true;
}
function V_SCRATCH() {
if(!(isSPARK(null))) {
TELL(CYOU, B(P_PRSA_WORD), " your fingers across ", THEO);
BUT_NOTHING_HAPPENS();
}
return true;
}
function BUT_NOTHING_HAPPENS() {
TELL(", but nothing ", PICK_NEXT(YAWNS), " happens.", CR);
return true;
}
function BUT_FIND_NOTHING() {
TELL(", but nothing ", PICK_NEXT(YAWNS), " turns up.", CR);
return true;
}
function V_PEEL() {
TELL(CANT, B(P_PRSA_WORD), C(SP), THEO, PERIOD);
return true;
}
function V_SCRAPE_ON() {
if(isSPARK_TO()) {
return true;
} else if(isPRSO(HANDS)) {
PERFORM("TOUCH", PRSI);
return true;
} else if(isPRSO(FEET)) {
PERFORM("KICK", PRSI);
return true;
}
TELL(CYOU, B(P_PRSA_WORD), C(SP), THEO);
if(!(isEQUAL(PRSI, null, HANDS))) {
TELL(SON, THEI);
}
NOTHING_HAPPENS();
return true;
}
function V_BOW() {
HACK_HACK("Paying respect to");
return true;
}
function V_SEARCH() {
if(isIS(PRSO, PLACE)) {
CANT_SEE_MUCH();
return true;
} else if(isIS(PRSO, CONTAINER)) {
if((!(isIS(PRSO, OPENED))
&& !(isIS(PRSO, TRANSPARENT)))) {
YOUD_HAVE_TO("open");
return true;
}
TELL(YOU_SEE);
CONTENTS();
TELL(" inside ", THEO, PERIOD);
return true;
} else if(isIS(PRSO, SURFACE)) {
TELL(YOU_SEE);
CONTENTS();
TELL(SON, THEO, PERIOD);
return true;
} else if(isIS(PRSO, PERSON)) {
PERFORM("USE", PRSO);
return true;
}
NOTHING_INTERESTING();
PRINT(PERIOD);
return true;
}
function V_SHAKE() {
if(isSPARK(null)) {
return true;
} else if(isIS(PRSO, PERSON)) {
PERFORM("ALARM", PRSO);
return true;
} else if((!(isIS(PRSO, TAKEABLE))
&& !(isIS(PRSO, TRYTAKE)))) {
HACK_HACK("Shaking");
return true;
}
WASTE_OF_TIME();
return true;
}
function V_SFIRE_AT() {
PERFORM("FIRE-AT", PRSI, PRSO);
return true;
}
function V_FIRE_AT() {
TELL(CANT, B(P_PRSA_WORD), C(SP), THEO, " at anything.", CR);
return true;
}
function V_ZAP_WITH() {
TELL(CANT, "zap things with ", A(PRSI), PERIOD);
return true;
}
function V_SIT() {
if(isPRSO(ROOMS)) {
if(isHERE(IN_CHAPEL)) {
ENTER_PEW();
return true;
}
}
NO_PLACE_TO_PRSA();
return true;
}
function NO_PLACE_TO_PRSA() {
TELL("There's no place to ", B(P_PRSA_WORD), " here.", CR);
return true;
}
function V_SMELL() {
let _X;
if(isPRSO(ROOMS)) {
_X = GETP(HERE, "ODOR");
if(!(_X)) {
TELL(DONT, "smell anything "
, PICK_NEXT(YAWNS), PERIOD);
return true;
}
PERFORM("SMELL", _X);
return true;
} else if(!(isIS(PRSO, LIVING))) {
TELL("It");
} else if(isIS(PRSO, FEMALE)) {
TELL("She");
} else {
TELL("He");
}
TELL(" smells just like ", AO, PERIOD);
return true;
}
function V_PLANT() {
IMPOSSIBLE();
return true;
}
function V_UPROOT() {
TELL(CTHEO, " isn't rooted anywhere.", CR);
return true;
}
function V_SPIN() {
if(isPRSO(ROOMS, ME)) {
TELL("You begin to feel a little dizzy.", CR);
return true;
}
TELL(CANT, "spin that.", CR);
return true;
}
function V_SQUEEZE() {
if(!(isSPARK(null))) {
WASTE_OF_TIME();
}
return true;
}
function V_DUCK() {
WASTE_OF_TIME();
return true;
}
function V_STAND() {
if(isPRSO(ROOMS)) {
if(isIN(PLAYER, PEW)) {
EXIT_PEW();
return true;
}
}
ALREADY_STANDING();
return true;
}
function ALREADY_STANDING() {
TELL(ALREADY, "standing.", CR);
return true;
}
function V_STAND_ON() {
WASTE_OF_TIME();
return true;
}
function V_STAND_UNDER() {
IMPOSSIBLE();
return true;
}
function V_SWING() {
if(!(PRSI)) {
WASTE_OF_TIME();
return true;
}
PERFORM("HIT", PRSI, PRSO);
return true;
}
function V_DIVE() {
if(isPRSO(ROOMS)) {
if(isHERE(IN_SKY)) {
DISMOUNT_DACT();
return true;
}
}
V_SWIM();
return true;
}
function V_SWIM() {
if(isPRSO(ROOMS)) {
if(isHERE(ON_BRIDGE)) {
JUMP_OFF_BRIDGE();
return true;
} else if(isHERE(JUN0)) {
ENTER_QUICKSAND();
return true;
} else if(isHERE(ON_WHARF, AT_LEDGE, AT_BRINE)) {
DO_WALK("DOWN");
return true;
}
NO_PLACE_TO_PRSA();
return true;
} else if((isPRSO(INTDIR)
&& isT(P_DIRECTION)
&& isEQUAL(WINNER, PLAYER))) {
TELL(CANT, B(P_PRSA_WORD), " that way from here.", CR);
return true;
}
IMPOSSIBLE();
return true;
}
function V_SGET_FOR() {
PERFORM("TAKE", PRSI);
return true;
}
function V_GET_FOR() {
PERFORM("TAKE", PRSO);
return true;
}
function V_TAKE_WITH() {
isHOW();
return true;
}
function V_TAKE_OFF() {
let _X;
if(isPRSO(ROOMS)) {
_X = LOC(WINNER);
if((isEQUAL(P_PRSA_WORD, "GET")
&& !(isEQUAL(_X, HERE))
&& isIS(_X, VEHICLE))) {
PERFORM("EXIT", _X);
return true;
}
V_WALK_AROUND();
return true;
} else if(isPRSO(HANDS, FEET)) {
IMPOSSIBLE();
return true;
} else if(isIS(PRSO, PLACE)) {
NOT_IN();
return true;
} else if(isIS(PRSO, TAKEABLE)) {
_X = LOC(PRSO);
if(!(_X)) {
REFERRING();
return true;
} else if((isEQUAL(_X, WINNER)
&& isIS(PRSO, CLOTHING))) {
if(isIS(PRSO, WORN)) {
if(isHOTFOOT()) {
return true;
}
TAKEOFF();
_X = GETP(PRSO, "EFFECT");
if(isT(_X)) {
UPDATE_STAT((0 - _X), ARMOR_CLASS);
}
return true;
}
PRINT("You're not wearing ");
TELL(THEO, PERIOD);
return true;
} else if(!(isIS(_X, SURFACE))) {
TELL(CTHEO, " isn't \"on\" anything.", CR);
return true;
}
PERFORM("TAKE", PRSO);
return true;
} else if(isIS(PRSO, VEHICLE)) {
PERFORM("EXIT", PRSO);
return true;
}
IMPOSSIBLE();
return true;
}
function TAKEOFF() {
WINDOW(SHOWING_INV);
UNMAKE(PRSO, WORN);
TELL("You take off ", THEO, PERIOD);
return true;
}
function isHOTFOOT(_INDENT) {
if((isPRSO(RING)
&& isT(MAGMA_TIMER)
&& isHERE(FOREST_EDGE, ON_TRAIL, ON_PEAK))) {
if(isASSIGNED(_INDENT)) {
TELL(TAB);
}
TELL("You slip ", THEO, " off ", HANDS, PTAB);
ITALICIZE("Whoosh");
TELL("! Your flesh bakes in the volcanic heat of the lava underfoot");
JIGS_UP();
return true;
} else {
return false;
}
}
function V_TASTE() {
PERFORM("EAT", PRSO);
return true;
}
function V_ADJUST() {
if(!(isSPARK(null))) {
TELL(CTHEO, " doesn't need adjustment.", CR);
}
return true;
}
"*** CHARACTER INTERACTION DEFAULTS ***"
function isSILLY_SPEAK() {
if(isEQUAL(PRSO, null, ROOMS)) {
return false;
} else if(!(isIS(PRSO, PERSON))) {
NOT_LIKELY();
PRINT(" would respond.|");
PCLEAR();
return true;
} else if(isPRSO(ME, PRSI, WINNER)) {
WASTE_OF_TIME();
PCLEAR();
return true;
} else {
THIS_IS_IT(PRSO);
return false;
}
}
function V_ASK_ABOUT() {
if(isSILLY_SPEAK()) {
return RFATAL();
} else if(isEQUAL(WINNER, PRSI)) {
WASTE_OF_TIME();
return RFATAL();
} else if((isPRSO(ME)
|| isEQUAL(WINNER, PLAYER))) {
TALK_TO_SELF();
return true;
}
NO_RESPONSE();
return true;
}
function V_REPLY() {
let _WHO;
if(isSILLY_SPEAK()) {
return RFATAL();
}
NO_RESPONSE(PRSO);
return true;
}
function V_QUESTION() {
if(isEQUAL(WINNER, PLAYER)) {
TO_DO_THING_USE("ask about", "ASK CHARACTER ABOUT");
return RFATAL();
}
NO_RESPONSE();
return true;
}
function V_ALARM() {
if(isSILLY_SPEAK()) {
return RFATAL();
}
if(isPRSO(ROOMS, ME)) {
TELL(ALREADY, "wide awake.", CR);
return true;
} else if(isIS(PRSO, LIVING)) {
TELL(CTHEO);
IS_ARE();
TELL("already wide awake.", CR);
return true;
}
IMPOSSIBLE();
return true;
}
function V_YELL() {
if(isPRSO(ROOMS)) {
TELL("You begin to get a sore throat.", CR);
if(isHERE(ON_WHARF)) {
TELL(TAB);
NOT_DEAF();
}
return true;
}
V_SAY();
return true;
}
function V_LAUGH() {
if(isPRSO(ROOMS)) {
TELL("There's a place for people who ", B(P_PRSA_WORD), " without reason.", CR);
return true;
} else if(isEQUAL(P_PRSA_WORD, "INSULT", "OFFEND")) {
if(isIS(PRSO, MONSTER)) {
TELL(CTHEO, " look");
if(!(isIS(PRSO, PLURAL))) {
TELL("s");
}
TELL(" mad enough already.", CR);
return true;
} else if(isIS(PRSO, LIVING)) {
TELL(CTHEO, " remain");
if(!(isIS(PRSO, PLURAL))) {
TELL("s");
}
TELL(" silent. Maybe you should too.", CR);
return true;
}
NOT_LIKELY();
TELL(" would be offended.");
return true;
}
V_SAY();
return true;
}
function PRE_NAME() {
if(!(PRSI)) {
SEE_MANUAL("name things");
return true;
} else if(!(isPRSI(QWORD))) {
HOLLOW_VOICE("reserved by the Implementors");
return true;
} else {
return false;
}
}
function V_NAME(_OBJ=PRSO) {
let _TBL, _WORD, _BASE, _LEN, _PTR, _CHAR, _COMPLEX, _BAD, _ANY, _X;
PCLEAR();
_TBL = GETP(_OBJ, "NAME-TABLE");
if((!(isIS(_OBJ, NAMEABLE))
|| !(_TBL))) {
TELL("Alas; ", THE(_OBJ));
if(isIS(PRSO, PERSON)) {
TELL(" already ha");
if(isIS(PRSO, PLURAL)) {
TELL("ve");
} else {
TELL("s");
}
TELL(" a Name.", CR);
return true;
}
TELL(" cannot be Named.", CR);
return true;
} else if(isIS(_OBJ, NAMED)) {
TELL("You've already assigned a Name to ", THE(_OBJ
), ". To alter that Name, you must first Unmake ");
PRONOUN(_OBJ, true);
TELL(", a dangerous procedure requiring years of magical training. Someday, perhaps...", CR);
return true;
}
COPYT(_TBL, 0, (NAMES_LENGTH + 1));
/*"Convert word typed into a byte LTABLE in AUX-TABLE."*/
_BASE = P_LEXV.strings[P_QWORD];//REST(P_LEXV, (P_QWORD));
_LEN = _BASE.length;//_BASE[2]; /*"Length of word typed."*/
AUX_TABLE[0] = _LEN; /*"Save it here."*/
//_BASE = REST(P_INBUF, _BASE[3]); /*"And start"*/
COPYT(_BASE.split(""), REST(AUX_TABLE, 1), _LEN);
AUX_TABLE[(_LEN + 1)] = 0; /*"Zero-terminate."*/
/*"Scan for obviously silly names."*/
_PTR = _LEN;
_BAD = 0;
_ANY = 0;
while(true) {
_CHAR = AUX_TABLE[_PTR];
/*if((_CHAR > ('\a'.charCodeAt(0) - 1)
&& _CHAR < ('\z'.charCodeAt(0) + 1))) {*/
if (/[A-Z]/.test(_CHAR)){
++_ANY
} else {
++_BAD
break;
}
if(--_PTR < 1) {
break;
}
}
if((!(_ANY)
|| isT(_BAD))) {
HOLLOW_VOICE("too complex");
return true;
} else if(_LEN > (NAMES_LENGTH - 1)) {
HOLLOW_VOICE("too long");
return true;
}
/*"Copy AUX-TABLE into TBL w/appropriate caps."*/
/*_PTR = 1;
while(true) {
_CHAR = AUX_TABLE[_PTR];
if(isEQUAL(_PTR, 1)) {
_CHAR = (_CHAR - 32);
}
_TBL[_PTR] = _CHAR;
if(++_PTR > _LEN) {
break;
}
}
_TBL[0] = _LEN;
_TBL[(_LEN + 1)] = 0; /*"Zero-terminate."*/
_TBL[0] = _LEN;
_TBL[1] = _BASE[0] + _BASE.slice(1).toLowerCase();
ADD_VOCAB(_BASE, _OBJ);
isADD_CAP(_BASE);
MAKE(_OBJ, NAMED);
MAKE(_OBJ, NOARTICLE);
MAKE(_OBJ, PROPER);
WINDOW(SHOWING_ALL);
TELL("You invoke the Spell of Naming, and the ");
if((isEQUAL(_OBJ, BFLY)
&& isIS(BFLY, MUNGED))) {
PRINT("caterpillar");
} else if((isEQUAL(_OBJ, PHASE)
&& !(isHERE(APLANE)))) {
TELL(B("OUTLINE"));
} else {
PRINTD(_OBJ);
}
TELL(" basks in the glow of a new-forged synonym. Henceforth, you may refer to ");
PRONOUN(_OBJ, true);
TELL(" as \"");
PRINT_TABLE([_TBL[0], ..._TBL[1].split("")]);
TELL(PERQ);
return true;
}
`Adds the ASCII byte-LTABLE string at TBL to the alternate charset, using
the PS? field of synonym .WRD. Returns base address of new word.`
function ADD_VOCAB(_TBL, _OBJ) {
let _WRD, _SYNS, _SIBS, _ELEN, _CNT, _BASE, _LEN;
_SYNS = GETPT(_OBJ, "SYNONYM");
_WRD = _SYNS[0];
_SYNS.push(_TBL);
VOCAB2[_TBL] = [...VOCAB2[_WRD]];
//_SIBS = VOCAB2[0]; /*"Size of SIB table."*/
//_ELEN = REST(VOCAB2, (_SIBS + 1))[0]; /*"Entry length."*/
//_CNT = REST(VOCAB2, (_SIBS + 2))[0]; /*"# entries."*/
/*_BASE = REST(VOCAB2, (_SIBS + 4));
if(isT(_CNT)) {
_BASE = REST(_BASE, (_ELEN * (0 - _CNT)));
}*/
//ZWSTR(_TBL, _TBL[0], 1, _BASE);
//_TBL = REST(_WRD, 6); /*"Point to PS? field of synonym."*/
//_LEN = (_ELEN - 6); /*"Length of PS? field."*/
//COPYT(_TBL, REST(_BASE, 6), _LEN); /*"Copy PS? field of synonym."*/
//--_CNT /*"List is unsorted, so CNT is negative."*/
//REST(VOCAB2, (_SIBS + 2))[0] = _CNT; /*"Update count."*/
//_SYNS[1] = _BASE;
//return _BASE;
}
function V_GOODBYE() {
V_HELLO();
return true;
}
function V_HELLO() {
if(isSILLY_SPEAK()) {
return RFATAL();
} else if(isPRSO(ROOMS)) {
TALK_TO_SELF();
return true;
}
NO_RESPONSE(PRSO);
return true;
}
function V_WAVE_AT() {
V_WHAT();
return true;
}
function V_REQUEST() {
let _L;
_L = LOC(PRSO);
if(!(isVISIBLE(_L))) {
CANT_SEE_ANY();
return true;
} else if(isIS(_L, PERSON)) {
SPOKEN_TO(_L);
PERFORM("ASK-FOR", _L, PRSO);
return true;
} else if(isIS(PRSO, TAKEABLE)) {
} else if(isIS(PRSO, TRYTAKE)) {
} else {
NOT_LIKELY();
TELL(" could be moved.", CR);
return true;
}
TELL(DONT, "have to ask for ", THEO, ". Just take ");
if(isIS(PRSO, PLURAL)) {
TELL(B("THEM"));
} else {
TELL(B("IT"));
}
if((isIS(_L, SURFACE)
|| isIS(_L, CONTAINER))) {
OUT_OF_LOC(_L);
}
TELL(PERIOD);
return true;
}
function V_SASK_FOR() {
PERFORM("ASK-FOR", PRSI, PRSO);
return true;
}
function V_ASK_FOR() {
if(isSILLY_SPEAK()) {
return RFATAL();
} else if((isEQUAL(WINNER, PRSI)
|| !(isIS(PRSI, TAKEABLE)))) {
IMPOSSIBLE();
return true;
}
NO_RESPONSE(PRSO);
return true;
}
function V_TELL() {
if(isSILLY_SPEAK()) {
return RFATAL();
} else if(isPRSO(ME)) {
if(isEQUAL(WINNER, PLAYER)) {
TALK_TO_SELF();
return true;
}
} else {
SEE_CHARACTER(PRSO);
if(isT(P_CONT)) {
WINNER = PRSO;
return true;
}
}
NO_RESPONSE(PRSO);
return true;
}
function V_TELL_ABOUT() {
if(!(isEQUAL(WINNER, PLAYER))) {
TELL(CTHE(WINNER));
if(isPRSO(ME)) {
TELL(" shrugs. \"I don't know anything about ", THEI, " you don't know.", CR);
return true;
}
TELL(" snorts. \"Don't be ridiculous.\"", CR);
return true;
}
V_WHAT();
return true;
}
function V_THANK() {
if(isSILLY_SPEAK()) {
return RFATAL();
} else if(isEQUAL(WINNER, PLAYER)) {
if(isPRSO(ME)) {
TELL("Self-congratulations");
WONT_HELP();
return true;
}
TELL("There's no need to thank ", THEO, PERIOD);
return true;
}
return true;
}
function V_WHO() {
if(isEQUAL(WINNER, PLAYER)) {
TELL("Who, indeed?", CR);
return true;
}
NO_RESPONSE();
return true;
}
function V_WHERE() {
if(isEQUAL(WINNER, PLAYER)) {
if(isVISIBLE(PRSO)) {
if(isIS(PRSO, PLURAL)) {
TELL("They're ");
} else if(isIS(PRSO, FEMALE)) {
TELL("She's ");
} else if(isIS(PRSO, PERSON)) {
TELL("He's ");
} else {
TELL("It's ");
}
TELL("right here.", CR);
return true;
}
TELL("Where, indeed?", CR);
return true;
}
NO_RESPONSE();
return true;
}
function V_WHAT() {
if(isEQUAL(WINNER, PLAYER)) {
TELL("What, indeed?", CR);
return true;
}
NO_RESPONSE();
return true;
}
function NO_RESPONSE(_OBJ=WINNER) {
PCLEAR();
SEE_CHARACTER(_OBJ);
TELL(CTHE(_OBJ));
PRINT(" looks at you expectantly. ");
CRLF();
return true;
}
function V_THROUGH() {
let _X;
if(isPRSO(ROOMS)) {
_X = LOC(PLAYER);
if(isIS(_X, VEHICLE)) {
PERFORM("ENTER", _X);
return true;
}
DO_WALK("IN");
return true;
} else /*if(isIS(PRSO, OPENABLE)) {
DO_WALK(OTHER_SIDE(PRSO));
return true;
}*/if(isIS(PRSO, VEHICLE)) {
PERFORM("ENTER", PRSO);
return true;
} else /*if(isIN(PRSO, WINNER)) {
TELL("That would involve quite a contortion.", CR);
return true;
}*/if(isIS(PRSO, LIVING)) {
V_RAPE();
return true;
} else /*if(!(isIS(PRSO, TAKEABLE))) {
TELL("You hit ", HEAD, " against ", THEO
, " as you attempt this feat.", CR);
return true;
}*/
IMPOSSIBLE();
return true;
}
function V_STHROW() {
PERFORM("THROW", PRSI, PRSO);
return true;
}
function PRE_THROW_OVER() {
return PRE_PUT();
}
function V_THROW_OVER() {
WASTE_OF_TIME();
return true;
}
function PRE_THROW() {
return PRE_PUT();
}
function V_THROW() {
if(isIS(PRSI, DOORLIKE)) {
WASTE_OF_TIME();
return true;
} else if(IDROP()) {
TELL("Thrown", PTAB, CTHEO, " lands on the ");
if(isIS(HERE, INDOORS)) {
TELL(FLOOR);
} else {
TELL(GROUND);
}
TELL(" nearby.", CR);
}
return true;
}
function V_TIE() {
TELL(IMPOSSIBLY, "tie ", THEO);
if(isT(PRSI)) {
TELL(STO, THEI);
}
PRINT(PERIOD);
return true;
}
function V_TIE_UP() {
TELL(CANT, "tie anything with that.", CR);
return true;
}
function V_TURN() {
if((!(isIS(PRSO, TAKEABLE))
&& !(isIS(PRSO, TRYTAKE)))) {
IMPOSSIBLE();
return true;
} else if(isSPARK(null)) {
return true;
}
HACK_HACK("Turning");
return true;
}
function V_TURN_TO() {
if(isVISIBLE(PRSO)) {
PERFORM("EXAMINE", PRSO);
return true;
}
TELL(DONT, "see ", THEO, PERIOD);
return true;
}
function V_WALK_AROUND() {
PCLEAR();
TELL("Which way do you want to go?", CR);
return true;
}
function V_WALK_TO() {
if(isPRSO(ROOMS)) {
V_WALK_AROUND();
return true;
} else if(isPRSO(INTDIR)) {
DO_WALK(P_DIRECTION);
return true;
} else if(isPRSO(RIGHT, LEFT)) {
MORE_SPECIFIC();
return true;
}
V_FOLLOW();
return true;
}
function V_WAIT(_N=3) {
let _X=null;
TELL("Time passes.", CR);
while(true) {
if((isT(_X)
|| _N < 1)) {
return true;
} else if(CLOCKER()) {
_X = true;
isCLOCK_WAIT = true;
}
--_N
}
return true;
}
function V_WAIT_FOR() {
if(isPRSO(INTNUM)) {
if(!(P_NUMBER)) {
isCLOCK_WAIT = true;
IMPOSSIBLE();
return true;
} else if(P_NUMBER > 120) {
isCLOCK_WAIT = true;
TELL("[That's too long to WAIT.]", CR);
return true;
}
V_WAIT((P_NUMBER - 1));
return true;
} else if(isVISIBLE(PRSO)) {
TELL(CTHEO);
IS_ARE();
TELL("already here.", CR);
return true;
}
TELL("You may be waiting quite a while.", CR);
return true;
}
function V_WEAR() {
let _X;
if((isIN(PRSO, WINNER)
&& isIS(PRSO, WORN))) {
TELL(ALREADY, "wearing ", THEO, PERIOD);
return true;
} else if(!(isIS(PRSO, CLOTHING))) {
TELL(CANT, "wear ", THEO, PERIOD);
return true;
} else if(isDONT_HAVE()) {
return true;
}
PUTON();
_X = GETP(PRSO, "EFFECT");
if(isT(_X)) {
UPDATE_STAT(_X, ARMOR_CLASS);
}
return true;
}
function PUTON() {
WINDOW(SHOWING_INV);
MAKE(PRSO, WORN);
TELL("You put on ", THEO, PERIOD);
return true;
}
function isWEARING_MAGIC(_OBJ) {
if((isIN(_OBJ, PLAYER)
&& isIS(_OBJ, WORN)
&& !(isIS(_OBJ, NEUTRALIZED)))) {
return true;
} else {
return false;
}
}
function V_WIND() {
TELL(CANT, "wind ", AO, PERIOD);
return true;
}
function YOU_CLIMB_UP(_NOCR=0) {
TELL(CYOU);
if(PROB(33)) {
TELL(B("ASCEND"));
} else {
if(PROB(50)) {
TELL(B("CLAMBER"));
} else {
TELL(B("CLIMB"));
}
TELL(" up");
}
TELL(" the steps.", CR);
if(isT(_NOCR)) {
return true;
} else if(isT(VERBOSITY)) {
CRLF();
}
return true;
}
function HACK_HACK(_STR) {
TELL(_STR, C(SP), THEO, " would", PICK_NEXT(HO_HUM), PERIOD);
return true;
}
function IMPOSSIBLE() {
TELL(PICK_NEXT(YUKS), PERIOD);
return true;
}
function TOO_DARK() {
PCLEAR();
TELL("It's too dark to see.", CR);
return true;
}
/*function CANT_GO() {
if(isIS(HERE, INDOORS)) {
TELL("There's no exit ");
} else {
TELL(CANT, "go ");
}
TELL("that way.", CR);
return true;
}*/
/*function ALREADY_OPEN() {
ITS_ALREADY("open");
return true;
}*/
/*function ALREADY_CLOSED() {
ITS_ALREADY("closed");
return true;
}*/
function ITS_ALREADY(_STR) {
TELL("It's already ", _STR, PERIOD);
return true;
}
function REFERRING() {
TELL("[To what are you referring?]", CR);
return true;
}
function MORE_SPECIFIC() {
NYMPH_APPEARS();
TELL("You really must be more specific");
PRINT(". Bye!\"| She disappears with a wink.|");
return true;
}
function WASTE_OF_TIME() {
TELL(PICK_NEXT(POINTLESS), PERIOD);
return true;
}
function isWHAT_TALK(_WHO, _OBJ) {
MAKE(_WHO, SEEN);
if(isVISIBLE(_OBJ)) {
return false;
}
PERPLEXED(_WHO);
TELL("I'm afraid I'm not sure");
WHO_WHAT(_OBJ);
TELL("you're talking about.\"", CR);
return true;
}
function PERPLEXED(_WHO) {
let _STR, _X;
PCLEAR();
_STR = PICK_NEXT(PUZZLES);
TELL(CTHE(_WHO));
_X = RANDOM(100);
if(_X < 33) {
TELL(" gives you a ", _STR, "ed look");
} else if(_X < 67) {
if(PROB(50)) {
TELL(" look");
} else {
TELL(" appear");
}
TELL("s ");
if(PROB(50)) {
if(PROB(50)) {
TELL("somewhat ");
} else {
TELL("a bit ");
}
}
TELL(_STR, "ed");
} else {
TELL(" looks at you with a ", _STR
, "ed expression");
}
TELL(". \"");
return true;
}
function WHO_WHAT(_OBJ) {
TELL(" wh");
if(isIS(_OBJ, PERSON)) {
TELL("o ");
return true;
} else if(isIS(_OBJ, PLACE)) {
TELL("ere ");
return true;
}
TELL("at ");
return true;
}
function V_SWRAP() {
PERFORM("WRAP-AROUND", PRSI, PRSO);
return true;
}
function V_WRAP_AROUND() {
TELL(IMPOSSIBLY, B(P_PRSA_WORD), C(SP), THEO
, " around ", THEI, PERIOD);
return true;
}
function V_DRESS() {
if(isPRSO(ROOMS, ME)) {
TELL("Try putting ", B("SOMETHING"), " on.", CR);
return true;
} else if(isIS(PRSO, PERSON)) {
TELL(CTHEO, " has all the clothing ");
if(isIS(PRSO, FEMALE)) {
TELL("s");
}
TELL("he needs.", CR);
return true;
}
TELL(CANT, "dress ", AO, PERIOD);
return true;
}
function V_UNDRESS() {
let _ANY=null, _X, _OBJ, _NXT;
if(isPRSO(ROOMS, ME, WINNER)) {
_OBJ = isFIRST(WINNER);
while(true) {
if(!(_OBJ)) {
break;
}
_NXT = isNEXT(_OBJ);
if(isIS(_OBJ, WORN)) {
_ANY = true;
isP_MULT = true;
_X = PERFORM("TAKE-OFF", _OBJ);
if(isEQUAL(_X, M_FATAL)) {
break;
}
}
_OBJ = _NXT;
}
if(isT(_ANY)) {
isP_MULT = null;
if(!(_X)) {
return true;
}
return _X;
}
PRINT("You're not wearing ");
TELL("anything unusual.", CR);
return true;
} else if(isIS(PRSO, PERSON)) {
INAPPROPRIATE();
return true;
}
TELL(CANT, B(P_PRSA_WORD), C(SP), AO, PERIOD);
return true;
}
function V_HANG() {
let _X;
if(isHERE(OUTSIDE_PUB, ON_BRIDGE)) {
_X = PUB_SIGN;
if(isHERE(ON_BRIDGE)) {
_X = ZBRIDGE;
}
TELL("[on ", THE(_X), BRACKET);
PERFORM("HANG-ON", PRSO, _X);
return true;
}
TELL(NOTHING, "here on which to "
, B(P_PRSA_WORD), C(SP), THEO, PERIOD);
return true;
}
function V_HANG_ON() {
TELL(CTHEI);
IS_ARE(PRSI);
TELL("hardly suitable for ", B(P_PRSA_WORD), "ing things.", CR);
return true;
}
function V_LURK() {
TELL("Leave the ", B(P_PRSA_WORD), "ing to the grues.", CR);
return true;
}
function V_SAY() {
if(!(isMAGICWORD(P_LEXV[P_CONT]))) {
TALK_TO_SELF();
}
PCLEAR();
return true;
}
function V_MAGIC() {
if(isMAGICWORD()) {
return true;
} else if(isEQUAL(P_PRSA_WORD, "DISPEL")) {
isHOW();
return true;
}
NOTHING_HAPPENS(null);
return true;
}
/*function YOU_CANT() {
SAY_YOU();
TELL(" can't ");
return true;
}*/
/*function SAY_YOU() {
if(isEQUAL(WINNER, PLAYER)) {
TELL("You");
return true;
}
TELL(CTHE(WINNER));
return true;
}*/
/*function YOURE() {
if(isEQUAL(WINNER, PLAYER)) {
TELL("You're ");
return true;
}
TELL(CTHE(WINNER), SIS);
return true;
}*/
function V_ERASE_WITH() {
TELL(CANT, B(P_PRSA_WORD), C(SP), THEO);
if(!(isPRSI(HANDS))) {
TELL(WITH, THEI);
}
PRINT(PERIOD);
return true;
}
function V_WRITE_ON() {
TELL("It would be difficult to ", B(P_PRSA_WORD), C(SP), AO
, SON, THEI, PERIOD);
return true;
}
function V_WRITE_WITH() {
NOT_LIKELY(PRSI);
TELL(" could ", B(P_PRSA_WORD), " anything on ", THEO, PERIOD);
return true;
}
function V_CRANK() {
if(isPRSO(ROOMS)) {
if(isVISIBLE(GURDY)) {
PRINTC('\['.charCodeAt(0));
TELL(THE(GURDY), BRACKET);
LAST_CRANK_DIR = null;
TURN_GURDY();
return true;
}
TELL(NOTHING, "here to crank.", CR);
return true;
}
TELL(CANT, "crank ", THEO, PERIOD);
return true;
}
function V_UNMAKE() {
TELL("Such magic lies far beyond your meager abilities.", CR);
return true;
}
function V_SPELLS() {
TELL(DONT, "know any. Few ");
ANNOUNCE_RANK();
TELL("s do.", CR);
return true;
}
"*** BARTERING ***"
var MONEY = () => OBJECT({
LOC: GLOBAL_OBJECTS,
DESC: "foo",
SDESC: DESCRIBE_MONEY,
FLAGS: [NODESC, NOARTICLE, NOALL],
SYNONYM: ["MONEY", "ZORKMIDS", "ZORKMID", "ZM", "CASH", "LOOT", "ASSETS", "COINS", "COIN", "CREDIT", "LINE"],
ADJECTIVE: ["INTNUM", "MY", "PERSONAL", "CREDIT"],
ACTION: MONEY_F
});
var LOOT/*NUMBER*/ = 1;
function DESCRIBE_MONEY(_OBJ) {
return "your zorkmid" + (!(isEQUAL(LOOT, 1)) ? "s" : "");
}
function MONEY_F() {
let _X;
if(isTHIS_PRSI()) {
if((isVERB(V_TRADE_FOR)
&& isHERE(IN_MAGICK, IN_BOUTIQUE, IN_WEAPON))) {
TRADE_FOR_LOOT(PRSO);
return true;
}
return false;
} else if(isVERB(V_SPEND)) {
return true;
} else if(isVERB(V_FIND, V_BUY)) {
TELL("Good luck.", CR);
return true;
} else if(!(LOOT)) {
PRINT("You're broke.|");
return RFATAL();
} else if(isVERB(V_EXAMINE, V_COUNT)) {
SAY_CASH();
return true;
} else if(isVERB(V_WHAT)) {
TELL("Zorkmids are the local unit of currency.", CR);
return true;
} else if((isVERB(V_DROP, V_EMPTY)
|| (_X = isPUTTING()))) {
BENJAMIN();
return true;
}
IMPOSSIBLE();
return true;
}
function SAY_CASH() {
TELL("You have ");
SAY_LOOT();
PRINT(PERIOD);
return true;
}
function isNOT_ENOUGH_LOOT(_AMT) {
if(_AMT > LOOT) {
TELL("You only have ");
SAY_LOOT();
TELL(PERIOD);
return true;
} else {
return false;
}
}
function SAY_LOOT(_VAL=LOOT) {
TELL(N(_VAL), " zorkmid");
if(!(isEQUAL(_VAL, 1))) {
TELL("s");
}
return true;
}
function BENJAMIN() {
TELL("A zorkmid saved is a zorkmid earned.", CR);
return true;
}
function isGIVING_LOOT(_OBJ, _WHO) {
if(!(isEQUAL(_OBJ, MONEY, INTNUM))) {
return false;
} else if(!(LOOT)) {
PRINT("You're broke.|");
return true;
}
_OBJ = LOOT;
if(!(isEQUAL(P_NUMBER, -1))) {
if(isNOT_ENOUGH_LOOT(P_NUMBER)) {
return true;
}
_OBJ = P_NUMBER;
}
TELL(CTHE(_WHO
), " gives you a bewildered look, shrugs, and accepts ", D(MONEY));
LOOT = (LOOT - _OBJ);
TELL(" without question.", CR);
return true;
}
function PRE_BUY() {
if(!(isLIT)) {
TOO_DARK();
return true;
} else if(!(PRSI)) {
PRSI = MONEY;
TELL("[with ", D(PRSI), BRACKET);
return false;
} else {
return false;
}
}
function V_SBUY() {
PERFORM("BUY", PRSI, PRSO);
return true;
}
function V_BUY() {
if(!(isVISIBLE(PRSO))) {
NONE_FOR_SALE();
return RFATAL();
} else if(isHELD()) {
ALREADY_HAVE();
return true;
} else if(isHERE(IN_MAGICK, IN_WEAPON, IN_BOUTIQUE)) {
BUY_X_WITH_Y();
return true;
}
NOT_LIKELY();
TELL(" is for sale.", CR);
return true;
}
function NONE_FOR_SALE() {
TELL("There are none here to buy.", CR);
return true;
}
function V_SPEND() {
if(isPRSO(ROOMS, MONEY, INTNUM)) {
TELL("Easily done");
if(isHERE(IN_MAGICK, IN_BOUTIQUE, IN_WEAPON)) {
TELL(", especially here");
}
PRINT(PERIOD);
return true;
}
IMPOSSIBLE();
return true;
}
function V_PAY() {
PERFORM("GIVE", PRSI, PRSO);
return true;
}
function V_BUY_FROM() {
if(!(isVISIBLE(PRSO))) {
NONE_FOR_SALE();
return RFATAL();
} else if(isHELD()) {
ALREADY_HAVE();
return true;
} else if(isPRSI(OWOMAN, MCASE, BCASE, WCASE)) {
BUY_X_WITH_Y();
return true;
}
NOT_LIKELY(PRSI);
TELL(" could sell you ", THEO, PERIOD);
return true;
}
function PRE_TRADE_FOR() {
if(PRE_SELL_TO()) {
return true;
} else if(isIN(PRSI, WINNER)) {
ALREADY_HAVE(PRSI);
return true;
} else {
return false;
}
}
function V_TRADE_FOR() {
let _L;
_L = LOC(PRSI);
if(!(_L)) {
IMPOSSIBLE();
return true;
} else if(isHERE(IN_MAGICK, IN_BOUTIQUE, IN_WEAPON)) {
BUY_X_WITH_Y(PRSI, PRSO);
return true;
} else if(isIS(_L, PERSON)) {
TELL(CTHE(_L), " seems reluctant to give up ", THEI, PERIOD);
return true;
}
TELL("Why not just pick up ", THEI, " instead?", CR);
return true;
}
function PRE_SELL_TO() {
if(!(PRSI)) {
if(isIN(OWOMAN, HERE)) {
PERFORM(PRSA, PRSO, OWOMAN);
return true;
}
}
if(isEQUAL(null, PRSO, PRSI)) {
REFERRING();
return true;
} else if(!(isLIT)) {
TOO_DARK();
return true;
} else if(isPRSO(PRSI)) {
IMPOSSIBLE();
return true;
} else if(isPRSI(MONEY, INTNUM)) {
return false;
} else if((isIN(PRSI, GLOBAL_OBJECTS)
|| (!(isIS(PRSO, TAKEABLE))
&& !(isIS(PRSO, TRYTAKE))))) {
IMPOSSIBLE();
return true;
} else if((isIS(PRSO, WORN)
&& isIN(PRSO, WINNER))) {
return isTAKE_OFF_PRSO_FIRST();
} else {
return false;
}
}
function V_SELL_TO() {
if(!(isEQUAL(WINNER, PLAYER))) {
NOT_LIKELY(WINNER);
IS_ARE();
TELL("interested in selling anything");
return true;
} else if(isPRSI(PRSO, ME, WINNER)) {
IMPOSSIBLE();
return true;
} else if(!(isIS(PRSI, PERSON))) {
NOT_LIKELY(PRSI);
TELL(" would buy anything.", CR);
return true;
}
NOT_A("salesperson");
return true;
}
function V_SSELL_TO() {
PERFORM("SELL-TO", PRSI, PRSO);
return true;
}
function BUY_X_WITH_Y(_X=PRSO, _Y=PRSI) {
let _CASE, _VAL, _OFFER, _CHANGE;
_CASE = GETP(HERE, "THIS-CASE");
if(!(isVISIBLE(_X))) {
TELL("\"I don't have any for sale,\" admits "
, THE(OWOMAN), PERIOD);
return true;
} else if(!(isIN(_X, _CASE))) {
TELL("\"Only the items in ", THE(_CASE
), " are for sale.\"", CR);
return true;
}
_VAL = GETP(_X, "VALUE");
if(_VAL < 1) {
NO_WORTH(_X);
return true;
} else if(isEQUAL(_Y, null, MONEY, INTNUM)) {
_OFFER = P_NUMBER;
if(!(LOOT)) {
PRINT("You're broke.|");
return true;
} else if((!(_Y)
|| isEQUAL(P_NUMBER, -1))) {
_OFFER = LOOT;
} else if(isNOT_ENOUGH_LOOT(_OFFER)) {
return true;
}
if(_OFFER < _VAL) {
TELL(CTHELADY
, " shakes her head firmly. \"My price is ");
SAY_LOOT(_VAL);
TELL(", dear.\"", CR);
return true;
}
PUTP(_X, "VALUE", (_VAL / 2));
if((!(isEQUAL(P_NUMBER, -1))
&& _OFFER > _VAL)) {
LOOT = (LOOT - P_NUMBER);
PRINT("\"You are too kind");
} else {
LOOT = (_OFFER - _VAL);
TELL("\"Done");
}
TELL(",\" says ", THE(OWOMAN), ", taking your zorkmid");
if(!(isEQUAL(_VAL, 1))) {
TELL("s");
}
SOLD(_X);
return true;
} else if(isNO_DEAL(_Y)) {
return true;
} else if(isIN(_Y, GLOBAL_OBJECTS)) {
TELL("\"Don't be silly.\"", CR);
return true;
}
_OFFER = GETP(_Y, "VALUE");
if(!(_OFFER)) {
NO_WORTH(_Y);
return true;
} else if(_OFFER < _VAL) {
WORTHLESS(_Y);
TELL(" only worth ");
SAY_LOOT(_OFFER);
TELL(". This ", D(_X), " is valued at ");
SAY_LOOT(_VAL);
TELL("!\"", CR);
return true;
}
WINDOW(SHOWING_ALL);
MOVE(_Y, _CASE);
MAKE(_Y, USED);
PUTP(_Y, "VALUE", (_OFFER + _OFFER));
PUTP(_X, "VALUE", (_VAL / 2));
if(_OFFER > _VAL) {
PRINT("\"You are too kind");
} else {
TELL("\"Done");
}
TELL(",\" says ", THE(OWOMAN), ", taking ");
SAY_YOUR(_Y);
if(_OFFER > _VAL) {
_CHANGE = (_OFFER - _VAL);
LOOT = (LOOT + _CHANGE);
SOLD(_X, _CHANGE);
PRINT(" and handing you ");
SAY_LOOT(_CHANGE);
TELL(" in change.", CR);
return true;
}
SOLD(_X);
return true;
}
function SOLD(_OBJ, _CHANGE=0) {
WINDOW(SHOWING_ALL);
THIS_IS_IT(_OBJ);
MAKE(_OBJ, USED);
if(isT(_CHANGE)) {
TELL(", ");
} else {
TELL(AND);
}
if(ITAKE(null)) {
MOVE(_OBJ, PLAYER);
TELL("handing you ", THE(_OBJ));
} else {
MOVE(_OBJ, GETP(GETP(HERE, "THIS-CASE"), "DNUM"));
TELL("setting ", THE(_OBJ), SON, THE(MCASE));
}
if(!(_CHANGE)) {
PRINT(PERIOD);
}
return true;
}
function NO_WORTH(_OBJ) {
WORTHLESS(_OBJ);
TELL(" not worth anything here.\"", CR);
return true;
}
function WORTHLESS(_OBJ) {
TELL(CTHELADY, GLANCES_AT, THE(_OBJ
), " and shakes her head. \"");
if(isIS(_OBJ, FEMALE)) {
TELL("She's");
} else if(isIS(_OBJ, LIVING)) {
TELL("He's");
} else if(isIS(_OBJ, PLURAL)) {
TELL("They're");
} else {
TELL("That's");
}
return true;
}
function isNO_DEAL(_OBJ) {
if(isEQUAL(_OBJ, HELM, RUG, CAKE)) {
TELL("\"No,\" replies ", THE(OWOMAN
), ", shaking her head firmly. \"I don't think I want to carry this.\"", CR);
return true;
} else {
return false;
}
}
function TRADE_FOR_LOOT(_OBJ) {
let _VAL, _CASE;
if(!(isIN(_OBJ, PLAYER))) {
TAKE_FIRST(_OBJ, LOC(_OBJ));
return true;
}
if(isNO_DEAL(_OBJ)) {
return true;
}
_VAL = GETP(_OBJ, "VALUE");
_CASE = toOBJECT(GETP(HERE, "THIS-CASE"));
TELL(CTHELADY, " examines ", THE(_OBJ));
if(!(_VAL)) {
TELL(" and hands it back to you with a shrug. \"Worthless.\"", CR);
return true;
}
WINDOW(SHOWING_ALL);
LOOT = (_VAL + LOOT);
TELL(" critically. \"Okay,\" she agrees, ");
if(isEQUAL(_OBJ, TRUFFLE)) {
VANISH(_OBJ);
TELL("popping ", THE(_OBJ), " in her mouth");
} else {
PUTP(_OBJ, "VALUE", (_VAL + _VAL));
MOVE(_OBJ, _CASE);
TELL("stashing it away in ", THE(_CASE));
}
PRINT(" and handing you ");
SAY_LOOT(_VAL);
TELL(" in return.", CR);
return true;
}
function V_ZOOM() {
let _WRD;
if(!(isPRSO(ROOMS))) {
BAD_COMMAND("ZOOM", "that way");
return true;
} else if(!(DMODE)) {
BAD_COMMAND("ZOOM", "in this display mode");
return true;
} else if(isEQUAL(MAP_ROUTINE, CLOSE_MAP)) {
MAP_ROUTINE = FAR_MAP;
_WRD = "OUT";
} else {
MAP_ROUTINE = CLOSE_MAP;
_WRD = "IN";
}
SAME_COORDS = null;
TELL("[Zooming ", B(_WRD), ".]", CR);
NEW_MAP();
SHOW_MAP();
return true;
}
var PRIOR/*NUMBER*/ = 0;
function V_PRIORITY_ON() {
if(isBAD_PRIOR()) {
return true;
} else if(isEQUAL(PRIOR, IN_DBOX)) {
TELL("already ");
} else {
PRIOR = IN_DBOX;
TELL("now ");
}
TELL("set to ");
SAY_PRIORITY();
TELL(".]", CR);
return true;
}
function SAY_PRIORITY() {
if(isEQUAL(PRIOR, SHOWING_ROOM)) {
TELL("Room Descriptions");
return true;
} else if(isEQUAL(PRIOR, SHOWING_INV)) {
TELL("Inventory");
return true;
} else {
TELL("Player Status");
return true;
}
}
function V_PRIORITY_OFF() {
if(isBAD_PRIOR()) {
return true;
} else if(!(PRIOR)) {
TELL("already ");
} else {
PRIOR = 0;
TELL("now ");
}
TELL("disabled.]", CR);
return true;
}
function isBAD_PRIOR() {
if(!(isPRSO(ROOMS))) {
BAD_COMMAND("PRIORITY", "that way");
return true;
} else if(!(DMODE)) {
BAD_COMMAND("PRIORITY", "in this display mode");
return true;
}
TELL("[Display priority is ");
return false;
}
function BAD_COMMAND(_STR1, _STR2) {
TELL("[", CANT, "use the ", _STR1, " command ", _STR2, ".]", CR);
return true;
}
var DMODE/*FLAG*/ = true;"T = enhanced, <> = normal."
function V_MODE() {
let _STR;
_STR = "Normal";
if(!(DMODE)) {
_STR = "Enhanced";
DMODE = true;
} else {
DMODE = null;
}
V_REFRESH();
CRLF();
PRINTC('\['.charCodeAt(0));
TELL(_STR, " display mode.]", CR, CR);
return true;
}
var VERBOSITY/*NUMBER*/ = 1;"0 = super, 1 = brief, 2 = verbose."
function V_VERBOSE() {
VERBOSITY = 2;
TELL("[Maximum verbosity");
FOR_SCRIPTING();
if(!(DMODE)) {
CRLF();
V_LOOK();
}
return true;
}
function V_BRIEF() {
VERBOSITY = 1;
TELL("[Brief descriptions");
FOR_SCRIPTING();
return true;
}
function V_SUPER_BRIEF() {
VERBOSITY = 0;
TELL("[Superbrief descriptions");
FOR_SCRIPTING();
return true;
}
function FOR_SCRIPTING() {
if(isT(DMODE)) {
TELL(" for transcripting");
}
TELL(".]", CR);
return true;
}
function V_QUIT(after) {
stop_main_loop = true;
PRINT("Are you sure you want to ");
TELL("leave the story now?");
const lazy_yes = lazy();
isYES(lazy_yes);
lazy_yes.setFn(yes => {
if (yes) {
CRLF();
QUIT();
}
CONTINUING();
stop_main_loop = false;
if (after)
after.post();
else
DO_MAIN_LOOP();
});
}
function CONTINUING() {
TELL(CR, "[Continuing.]", CR);
return true;
}
function V_RESTART() {
stop_main_loop = true;
V_SCORE();
CRLF();
PRINT("Are you sure you want to ");
TELL("restart the story?");
const lazy_yes = lazy();
isYES(lazy_yes);
lazy_yes.setFn(yes => {
if(yes) {
RESTART();
FAILED("RESTART");
}
stop_main_loop = false;
DO_MAIN_LOOP();
});
}
function V_RESTORE(after=DO_MAIN_LOOP) {
OLD_HERE = null;
RESTORE(() => {
V_RESTORE2();
after();
});
}
var CHECKSUM/*NUMBER*/ = 0;
function V_SAVE() {
let _X, _STAT;
if(isCANT_SAVE()) {
return true;
}
TELL("You mumble the Spell of Saving.", CR);
PCLEAR();
OLD_HERE = null;
OOPS_INBUF[1] = 0; /*"Retrofix #50"*/
_STAT = ENDURANCE;
CHECKSUM = 0;
while(true) {
CHECKSUM = (CHECKSUM + STATS[_STAT]);
if(++_STAT > EXPERIENCE) {
break;
}
}
_STAT = ENDURANCE;
while(true) {
CHECKSUM = (CHECKSUM + MAXSTATS[_STAT]);
if(++_STAT > EXPERIENCE) {
break;
}
}
CHECKSUM = (0 - CHECKSUM);
_X = SAVE();
if(!(_X)) {
FAILED("SAVE");
return RFATAL();
} else if(isEQUAL(_X, 1)) {
COMPLETED("SAVE");
return RFATAL();
}
}
function V_RESTORE2() {
INITVARS();
V_REFRESH();
COMPLETED("RESTORE");
CRLF();
V_LOOK();
_STAT = ENDURANCE;
_X = 0;
while(true) {
_X = (_X + STATS[_STAT]);
if(++_STAT > EXPERIENCE) {
break;
}
}
_STAT = ENDURANCE;
while(true) {
_X = (_X + MAXSTATS[_STAT]);
if(++_STAT > EXPERIENCE) {
break;
}
}
if(!(isEQUAL((0 - CHECKSUM), _X))) {
CHEATER();
}
return RFATAL();
}
function COMPLETED(_STR) {
TELL(CR, "[", _STR, " completed.]", CR);
return true;
}
function FAILED(_STR) {
TELL(CR, "[", _STR, " failed.]", CR);
return true;
}
function V_SCORE() {
TELL("[Your rank is ");
ANNOUNCE_RANK();
TELL(", achieved in ", N(MOVES), " move");
if(!(isEQUAL(MOVES, 1))) {
TELL("s");
}
TELL(".]", CR);
return true;
}
function V_DIAGNOSE() {
if(isPRSO(ME, ROOMS)) {
NYMPH_APPEARS("medical");
TELL("Please use the STATUS command to monitor your health");
PRINT(". Bye!\"| She disappears with a wink.|");
return true;
} else if(isIS(PRSO, MONSTER)) {
DIAGNOSE_MONSTER();
return true;
} else if(isIS(PRSO, LIVING)) {
TELL(CTHEO, " seem");
if(!(isIS(PRSO, PLURAL))) {
TELL("s");
}
TELL(" well enough.", CR);
return true;
} else if(isIS(PRSO, PERSON)) {
TELL(CTHEO);
ISNT_ARENT();
TELL(" looking well.", CR);
return true;
}
TELL(CANT, B(P_PRSA_WORD), C(SP), AO, PERIOD);
return true;
}
var SAY_STAT/*FLAG*/ = null;
function V_NOTIFY() {
TELL("[Status notification is now o");
if(isT(SAY_STAT)) {
SAY_STAT = null;
TELL("ff");
} else {
SAY_STAT = true;
TELL("n");
}
TELL(".]", CR);
return true;
}
function V_TIME() {
TELL("This is a timeless tale.", CR);
return true;
}
function V_SCRIPT() {
PRINT("[Transcripting o");
TELL("n.]", CR);
DIROUT(D_PRINTER_ON);
TRANSCRIPT("begin");
return true;
}
function V_UNSCRIPT() {
TRANSCRIPT("end");
DIROUT(D_PRINTER_OFF);
PRINT("[Transcripting o");
TELL("ff.]", CR);
return true;
}
function TRANSCRIPT(_STR) {
DIROUT(D_SCREEN_OFF);
TELL(CR, "Here ", _STR, "s a transcript of interaction with", CR);
V_VERSION();
DIROUT(D_SCREEN_ON);
return true;
}
function V_VERSION() {
let _X;
CRLF();
if(isT(isCOLORS)) {
COLOR(INCOLOR, BGND);
} else if(!(isEQUAL(HOST, MACINTOSH))) {
HLIGHT(H_BOLD);
}
TELL("BEYOND ZORK: ");
PRINT("The Coconut of Quendor");
CRLF();
COLOR(FORE, BGND);
HLIGHT(H_NORMAL);
PRINT("Copyright (C)1987 Infocom, Inc. All rights reserved.");
CRLF();
TRADEMARK();
CRLF();
TELL("Release ");
PRINTN((LOWCORE(ZORKID) & 2047));
TELL(" / Serial Number ");
//LOWCORE_TABLE(SERIAL, 6, PRINTC);
CRLF();
INTERPRETER_ID();
return true;
}
function V_$VERIFY() {
/*if(isT(PRSO)) {
if((isPRSO(INTNUM)
&& isEQUAL(P_NUMBER, 105))) {
TELL(N(SERIAL), CR);
return true;
}
DONT_UNDERSTAND();
return true;
}*/
INTERPRETER_ID();
TELL(CR, "[Verifying.]", CR);
if(VERIFY()) {
NYMPH_APPEARS();
TELL("Your disk is correct");
PRINT(". Bye!\"| She disappears with a wink.|");
return true;
}
FAILED("$VERIFY");
return true;
}
function INTERPRETER_ID() {
if(HOST < 1) {
TELL("XZIP");
} else if(HOST > MACHINES[0]) {
TELL("Interpreter ", N(HOST));
} else {
TELL(MACHINES[HOST]);
}
if(isT(isCOLORS)) {
TELL(" Color");
}
TELL(" Version ", C(LOWCORE(INTVR)), CR);
return true;
}
var POTENTIAL/*NUMBER*/ = 0;
var STATS/*TABLE*/ = [0, 0, 0, 0, 0, 0, 0, 0];
var MAXSTATS/*TABLE*/ = [0, 0, 0, 0, 0, 0, 0, 0];
function V_STATUS() {
let _CNT=0, _X;
if((isT(DMODE)
&& isT(VT220)
&& !(isEQUAL(IN_DBOX, SHOWING_STATS))
&& !(PRIOR))) {
TELL("[Displaying status.]", CR);
SHOW_RANK();
DISPLAY_STATS();
} else {
STANDARD_STATS();
}
if(LOWCORE(FLAGS) & 1) {
DIROUT(D_SCREEN_OFF);
STANDARD_STATS();
DIROUT(D_SCREEN_ON);
}
return true;
}
function STANDARD_STATS() {
PRINT_TABLE(CHARNAME);
PRINTC('\/'.charCodeAt(0));
ANNOUNCE_RANK();
CRLF();
TEXT_STATS();
CRLF();
return true;
}
var BMODE/*FLAG*/ = null;"Battle display mode flag."
var AUTO/*FLAG*/ = true;"Automatic display mode flag."
function V_MONITOR() {
let _X;
if(!(VT220)) {
NOT_AVAILABLE();
return true;
} else if(!(DMODE)) {
TELL("[That command works only in Enhanced display mode.]", CR);
return true;
} else if(!(AUTO)) {
AUTO = true;
_X = STATS[ENDURANCE];
if(_X < MAXSTATS[ENDURANCE]) {
BMODE_ON();
}
PRINT("[Combat monitor o");
TELL("n.]", CR);
return true;
}
AUTO = 0;
if(isT(BMODE)) {
BATTLE_MODE_OFF();
}
PRINT("[Combat monitor o");
TELL("ff.]", CR);
return true;
}
function BMODE_OFF() {
let _X;
if((!(BMODE)
|| !(VT220))) {
return false;
}
_X = STATS[ENDURANCE];
if(!(_X < MAXSTATS[ENDURANCE])) {
BATTLE_MODE_OFF();
}
return false;
}
function BATTLE_MODE_OFF() {
BMODE = 0;
WINDOW(SHOWING_ALL);
DHEIGHT = MAX_DHEIGHT;
TO_TOP_WINDOW();
DO_CURSET((DHEIGHT + (11 - MAX_DHEIGHT)), 2);
PRINT_SPACES(DWIDTH);
TO_BOTTOM_WINDOW();
return false;
}
function BMODE_ON() {
if((!(DMODE)
|| isT(BMODE)
|| !(VT220)
|| isEQUAL(SHOWING_STATS, IN_DBOX, NEW_DBOX))) {
return false;
}
BATTLE_MODE_ON();
return false;
}
function BATTLE_MODE_ON() {
let _Y;
BMODE = true;
WINDOW(SHOWING_ALL);
_Y = (DHEIGHT + (11 - MAX_DHEIGHT));
TO_TOP_WINDOW();
DO_CURSET(_Y, 2);
PRINT_SPACES(DWIDTH);
TO_BOTTOM_WINDOW();
STATBARS(_Y, 0, 0);
DHEIGHT = (MAX_DHEIGHT - 1);
return false;
}
function V_DEFINE() {
keydown_handler.inDefine(true);
let _KEYS, _TOP, _LTBL, _LMARGIN, _DKEY, _TBL, _TBL2, _LEN, _HIT, _X, _Y;
/*"Set up routine constants."*/
stop_main_loop = true;
_KEYS = 9;
if(isEQUAL(HOST, C128, C64)) {
_KEYS = 7;
}
_TOP = Math.floor((HEIGHT - (_KEYS + 7)) / 2);
_LTBL = KEY_LABELS;
if((isEQUAL(HOST, APPLE_2E, APPLE_2C, APPLE_2GS)
|| isEQUAL(HOST, MACINTOSH))) {
_LTBL = APPLE_LABELS;
}
_LMARGIN = Math.floor((WIDTH - (SOFT_LEN + 4)) / 2);
/*"Init screen."*/
COLOR(GCOLOR, BGND);
CLEAR(-1);
SPLIT(20);
TO_TOP_WINDOW();
/*"Set up image of SOFT-KEYS in DBOX."*/
DO_CURSET(_TOP, (8 + _LMARGIN));
TELL("Function Key Definitions");
SOFTS_TO_DBOX(_KEYS);
_X = (_LMARGIN + 4);
DO_CURSET((_TOP + 2), _X);
HLIGHT(H_INVERSE);
PRINTT(DBOX, SOFT_LEN, (_KEYS + 1));
/*"Print key labels."*/
if((!(isCOLORS)
|| isEQUAL(FORE, GCOLOR))) {
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
}
_X = 0;
while(true) {
DO_CURSET(((_TOP + _X) + 2), _LMARGIN);
TELL(_LTBL[_X]);
if(++_X > _KEYS) {
break;
}
}
_X = (_LMARGIN + 4);
DO_CURSET(((_KEYS + 4) + _TOP), _X);
TELL(" Restore Defaults ");
DO_CURSET(((_KEYS + 6) + _TOP), _X);
PRINT(" Exit ");
_DKEY = 0;
const outer_loop = loop_stream(),
inner_loop = loop_stream();
outer_loop.loadPreaction(() => {
_Y = ((_DKEY + _TOP) + 2);
COLOR(FORE, BGND);
HLIGHT(H_INVERSE);
if(isEQUAL(_DKEY, (_KEYS + 1))) {
_X = (_LMARGIN + 4);
DO_CURSET(((_KEYS + 4) + _TOP), _X);
TELL(" Restore Defaults ");
HLIGHT(H_NORMAL);
SCREEN(S_TEXT);
inner_loop.loadPreaction(() => {
DO_INPUT(inner_loop);
});
inner_loop.loadPostaction(_HIT => {
const post_sure = () => {
if(isEQUAL(_HIT, UP_ARROW, DOWN_ARROW)) {
_DKEY = (_KEYS + 2);
if(isEQUAL(_HIT, UP_ARROW)) {
_DKEY = _KEYS;
}
SCREEN(S_WINDOW);
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
COLOR(GCOLOR, BGND);
if((isT(isCOLORS)
&& !(isEQUAL(FORE, GCOLOR)))) {
HLIGHT(H_INVERSE);
}
_X = (_LMARGIN + 4);
DO_CURSET(((_KEYS + 4) + _TOP), _X);
TELL(" Restore Defaults ");
inner_loop.finish();return;
}
SOUND(S_BOOP);
inner_loop.again();
};
if(isEQUAL(_HIT, EOL, LF)) {
const lazy_sure = lazy(
sure => {
if (sure) {
DEFAULT_SOFTS();
SOFTS_TO_DBOX(_KEYS);
SCREEN(S_WINDOW);
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
HLIGHT(H_INVERSE);
COLOR(GCOLOR, BGND);
_X = (_LMARGIN + 4);
DO_CURSET((_TOP + 2), _X);
PRINTT(DBOX, SOFT_LEN, (_KEYS + 1));
inner_loop.finish();return;
} else {
_HIT = DOWN_ARROW;
post_sure();
}
}
);
isMAKE_SURE(lazy_sure);
} else
post_sure();
});
inner_loop.onFinish(() => {
setTimeout(outer_loop.again, 20);
});
} else if(isEQUAL(_DKEY, (_KEYS + 2))) {
_X = (_LMARGIN + 4);
DO_CURSET(((_KEYS + 6) + _TOP), _X);
PRINT(" Exit ");
HLIGHT(H_NORMAL);
SCREEN(S_TEXT);
inner_loop.loadPreaction(() => {
DO_INPUT(inner_loop);
});
inner_loop.loadPostaction(_HIT => {
const post_sure = () => {
if(isEQUAL(_HIT, UP_ARROW, DOWN_ARROW)) {
_DKEY = 0;
if(isEQUAL(_HIT, UP_ARROW)) {
_DKEY = (_KEYS + 1);
}
SCREEN(S_WINDOW);
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
COLOR(GCOLOR, BGND);
if((isT(isCOLORS)
&& !(isEQUAL(FORE, GCOLOR)))) {
HLIGHT(H_INVERSE);
}
_X = (_LMARGIN + 4);
DO_CURSET(((_KEYS + 6) + _TOP), _X);
PRINT(" Exit ");
inner_loop.finish();return;
}
SOUND(S_BOOP);
};
if(isEQUAL(_HIT, EOL, LF)) {
if(!(isEQUAL(HOST, MACINTOSH))) {
V_REFRESH();
CONTINUING();
stop_main_loop = false;
keydown_handler.inDefine(false);
setTimeout(DO_MAIN_LOOP, 20);
return true;
} else {
const lazy_sure = lazy();
isMAKE_SURE(lazy_sure);
lazy_sure.setFn(sure => {
if (sure) {
V_REFRESH();
CONTINUING();
return true;
} else {
_HIT = DOWN_ARROW;
post_sure();
}
});
return;
}
} else
post_sure();
});
inner_loop.onFinish(() => {
setTimeout(outer_loop.again, 20);
});
} else {
setTimeout(outer_loop.post, 20);
}
});
outer_loop.loadPostaction(() => {
DO_CURSET(_Y, _LMARGIN);
TELL(_LTBL[_DKEY]);
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
DBOX[0] = SP;
COPYT(DBOX, REST(DBOX, 1), NSOFT_LEN);
_TBL = SOFT_KEYS[_DKEY][3].split("");
_TBL = [_TBL.length, ..._TBL];
_LEN = _TBL[0];
if(isT(_LEN)) {
COPYT(_TBL.slice(1), DBOX, _LEN);
}
DO_CURSET(_Y, (_LMARGIN + 4));
COLOR(INCOLOR, BGND);
PRINTT(DBOX, SOFT_LEN);
DO_CURSET(_Y, ((_LMARGIN + _LEN) + 4));
inner_loop.loadPreaction(() => {
keydown_handler.setLine(SOFT_KEYS[_DKEY][3]);
READ(_TBL, 0, inner_loop);
});
inner_loop.loadPostaction(_HIT => {
if((isEQUAL(_HIT, EOL, LF)
|| isEQUAL(_HIT, UP_ARROW, DOWN_ARROW, MAC_UP_ARROW
, MAC_DOWN_ARROW))) {
inner_loop.finish(_HIT);return;
}
SOUND(S_BOOP);
inner_loop.again();
});
inner_loop.onFinish(_HIT => {
DBOX[0] = SP;
COPYT(DBOX, REST(DBOX, 1), NSOFT_LEN);
_LEN = _TBL[1];
if(!(_LEN)) {
_TBL[0] = SP;
//COPYT(_TBL, REST(_TBL, 1), NSOFT_LEN);
_TBL = "".padEnd(SOFT_LEN,0).split("").map(()=>32);
_TBL2 = KEY_DEFAULTS[_DKEY][2].split("");
_LEN = _TBL2.length;
//_TBL[0] = SOFT_LEN;
//_TBL[1] = _LEN;
_X = [_LEN,_LEN,..._TBL2.map(x => x.charCodeAt(0))];//REST(_TBL2, 1);
COPYT(_X, _TBL, _LEN+2);
if(!(isEQUAL(HOST, C128, C64))) {
} else if((_X = isINTBL('\|'.charCodeAt(0), _TBL, _LEN+2, 1))) {
_X[0] = '\!'.charCodeAt(0);
}
}
COPYT(_TBL
.slice(2)
.map(x => String.fromCharCode(x))
.join("")
.toLowerCase()
.padEnd(SOFT_LEN," ")
.split("")
.map(x => x.charCodeAt(0)), DBOX, _LEN);
SOFT_KEYS[_DKEY][3] = _TBL.slice(2,_TBL[1]+2).map(x => String.fromCharCode(x)).join("").toLowerCase();
Screen.blinking.disable();
DO_CURSET(_Y, (_LMARGIN + 4));
COLOR(GCOLOR, BGND);
HLIGHT(H_INVERSE);
PRINTT(DBOX, SOFT_LEN);
_Y = ((_DKEY + 2) + _TOP);
DO_CURSET(_Y, _LMARGIN);
if((!(isCOLORS)
|| isEQUAL(FORE, GCOLOR))) {
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
}
COLOR(GCOLOR, BGND);
TELL(_LTBL[_DKEY]);
printBuffer();
if(isEQUAL(_HIT, EOL, DOWN_ARROW, LF, MAC_DOWN_ARROW)) {
++_DKEY
} else if(--_DKEY < 0) {
_DKEY = (_KEYS + 2);
}
Screen.blinking.enable();
setTimeout(outer_loop.again, 20);
});
});
}
function isMAKE_SURE(after) {
let _X;
TELL(CR, "Are you sure? (Y/N) >");
const lazy_input = lazy();
INPUT(lazy_input.post);
lazy_input.setFn(_X => {
CRLF();
CLEAR(S_TEXT);
if(isEQUAL(_X, '\Y'.charCodeAt(0), '\y'.charCodeAt(0))) {
after.post(true);return true;
} else {
after.post(false);return false;
}
});
}
function DEFAULT_SOFTS() {
let _CNT=0, _TBL, _X, _LEN;
while(true) {
_TBL = SOFT_KEYS[_CNT];
_TBL[0] = SOFT_LEN;
_TBL = REST(_TBL, 1);
_X = KEY_DEFAULTS[_CNT];
_LEN = (_X[0] + 1);
COPYT(_X, _TBL, _LEN);
if((isEQUAL(HOST, C128, C64)
&& (_X = isINTBL('\|'.charCodeAt(0), _TBL, _LEN, 1)))) {
_X[0] = '\!'.charCodeAt(0);
}
if(++_CNT > 9) {
return false;
}
}
}
function SOFTS_TO_DBOX(_KEYS) {
let _X, _TBL, _TBL2, _LEN;
DBOX[0] = SP;
COPYT(DBOX, REST(DBOX, 1), (0 - (DBOX_LENGTH - 1)));
_X = 0;
while(true) {
_TBL2 = REST(DBOX, (_X * SOFT_LEN));
//_TBL = SOFT_KEYS[_X];
//_LEN = _TBL[1];
_TBL = SOFT_KEYS[_X][3].split("");
_LEN = _TBL.length;
if(isT(_LEN)) {
COPYT(_TBL, _TBL2, _LEN);
}
if(++_X > _KEYS) {
return false;
}
}
}
function V_SETTINGS() {
let _TOP, _LMARGIN, _LINE, _X, _KEY;
_TOP = Math.floor((HEIGHT - 19) / 2);
_LMARGIN = Math.floor((WIDTH - 52) / 2);
COLOR(GCOLOR, BGND);
CLEAR(-1);
SPLIT(22);
TO_TOP_WINDOW();
DO_CURSET(_TOP, (_LMARGIN + 18));
COLOR(FORE, BGND);
TELL("Display Settings");
_LINE = 0;
while(true) {
SHOW_SETLINE(_LINE, _TOP, _LMARGIN);
if(++_LINE > 8) {
break;
}
}
stop_main_loop = true;
_LINE = 0;
const outer = lazy(),
inner_loop = loop_stream();
outer.setFn(() => {
SHOW_SETLINE(_LINE, _TOP, _LMARGIN, 1);
HLIGHT(H_NORMAL);
SCREEN(S_TEXT);
if(isEQUAL(_LINE, 7)) {
/*"Restore."*/
inner_loop.loadPreaction(() => {
DO_INPUT(inner_loop);
});
inner_loop.loadPostaction(_KEY => {
const after_sure = () => {
if(isEQUAL(_KEY, UP_ARROW, DOWN_ARROW
, MAC_UP_ARROW, MAC_DOWN_ARROW)) {
_LINE = 8;
if(isEQUAL(_KEY, UP_ARROW, MAC_UP_ARROW)) {
_LINE = 6;
if(!(DMODE)) {
_LINE = 3;
}
}
SHOW_SETLINE(7, _TOP, _LMARGIN);
inner_loop.finish();return;
}
SOUND(S_BOOP);
inner_loop.again();
};
if(isEQUAL(_KEY, EOL, LF)) {
const lazy_sure = lazy();
isMAKE_SURE(lazy_sure);
lazy_sure.setFn(sure => {
if(sure) {
if(!(DMODE)) {
DMODE = true;
SHOW_SETLINE(0, _TOP, _LMARGIN);
MAP_ROUTINE = CLOSE_MAP;
if(!(VT220)) {
MAP_ROUTINE = FAR_MAP;
}
IN_DBOX = SHOWING_ROOM;
SHOW_SETLINE(4, _TOP, _LMARGIN);
PRIOR = 0;
SHOW_SETLINE(5, _TOP, _LMARGIN);
AUTO = true;
SHOW_SETLINE(6, _TOP, _LMARGIN);
}
if(!(isEQUAL(VERBOSITY, 1))) {
VERBOSITY = 1;
SHOW_SETLINE(1, _TOP, _LMARGIN);
}
if(LOWCORE(FLAGS) & 1) {
DIROUT(D_PRINTER_OFF);
SHOW_SETLINE(2, _TOP, _LMARGIN);
}
if(!(SAY_STAT)) {
SAY_STAT = true;
SHOW_SETLINE(3, _TOP, _LMARGIN);
}
if((isT(VT220)
&& isEQUAL(MAP_ROUTINE
, FAR_MAP))) {
MAP_ROUTINE = CLOSE_MAP;
SHOW_SETLINE(4, _TOP, _LMARGIN);
} else if((!(VT220)
&& isEQUAL(MAP_ROUTINE
, CLOSE_MAP))) {
MAP_ROUTINE = FAR_MAP;
SHOW_SETLINE(4, _TOP, _LMARGIN);
}
if(isT(PRIOR)) {
PRIOR = 0;
SHOW_SETLINE(5, _TOP, _LMARGIN);
}
if(!(AUTO)) {
AUTO = true;
SHOW_SETLINE(6, _TOP, _LMARGIN);
}
/*break;*/
}
_KEY = DOWN_ARROW;
after_sure();
});
} else
after_sure();
});
inner_loop.onFinish(() => {
setTimeout(outer.post, 20);
});
return;
} else if(isEQUAL(_LINE, 8)) {
/*"Exit"*/
inner_loop.loadPreaction(() => {
DO_INPUT(inner_loop);
});
inner_loop.loadPostaction(_KEY => {
const after_sure = () => {
if(isEQUAL(_KEY, UP_ARROW, DOWN_ARROW)) {
_LINE = 0;
if(isEQUAL(_KEY, UP_ARROW)) {
_LINE = 7;
}
SHOW_SETLINE(8, _TOP, _LMARGIN);
inner_loop.finish();return;
}
SOUND(S_BOOP);
inner_loop.again();
};
if(isEQUAL(_KEY, EOL, LF)) {
if((!(isEQUAL(HOST, MACINTOSH)))) {
V_REFRESH();
CONTINUING();
stop_main_loop = false;
setTimeout(DO_MAIN_LOOP, 20);
return true;
} else {
const lazy_sure = lazy();
isMAKE_SURE(lazy_sure)
lazy_sure.setFn(sure => {
if (sure) {
V_REFRESH();
CONTINUING();
stop_main_loop = false;
setTimeout(DO_MAIN_LOOP, 20);
return true;
} else {
_KEY = DOWN_ARROW;
after_sure();
}
});
}
} else
after_sure();
});
inner_loop.onFinish(() => {
setTimeout(outer.post, 20);
});
return;
}
inner_loop.loadPreaction(() => {
DO_INPUT(inner_loop);
});
inner_loop.loadPostaction(_KEY => {
if(isEQUAL(_KEY, UP_ARROW)) {
SHOW_SETLINE(_LINE, _TOP, _LMARGIN);
if(--_LINE < 0) {
_LINE = 8;
}
inner_loop.finish();return;
} else if(isEQUAL(_KEY, DOWN_ARROW, EOL, LF)) {
SHOW_SETLINE(_LINE, _TOP, _LMARGIN);
if((!(DMODE)
&& isEQUAL(_LINE, 3))) {
_LINE = 7;
inner_loop.finish();return;
}
++_LINE
inner_loop.finish();return;
} else if(isEQUAL(_KEY, RIGHT_ARROW, LEFT_ARROW, SP)) {
if(!(_LINE)) {
if(!(DMODE)) {
++DMODE
} else {
DMODE = 0;
}
SHOW_SETLINE(4, _TOP, _LMARGIN);
SHOW_SETLINE(5, _TOP, _LMARGIN);
SHOW_SETLINE(6, _TOP, _LMARGIN);
} else if(isEQUAL(_LINE, 2)) {
if(LOWCORE(FLAGS) & 1) {
DIROUT(D_PRINTER_OFF);
} else {
DIROUT(D_PRINTER_ON);
}
} else if(isEQUAL(_LINE, 3)) {
if(!(SAY_STAT)) {
++SAY_STAT
} else {
SAY_STAT = 0;
}
} else if(isEQUAL(_LINE, 4)) {
if(isEQUAL(MAP_ROUTINE, CLOSE_MAP)) {
MAP_ROUTINE = FAR_MAP;
} else {
MAP_ROUTINE = CLOSE_MAP;
}
} else if(isEQUAL(_LINE, 6)) {
if(!(AUTO)) {
++AUTO
} else {
AUTO = 0;
}
} else if(isEQUAL(_KEY, RIGHT_ARROW, SP)) {
if(isEQUAL(_LINE, 1)) {
if(++VERBOSITY > 2) {
VERBOSITY = 0;
}
} else if(isEQUAL(_LINE, 5)) {
if(!(PRIOR)) {
PRIOR = SHOWING_ROOM;
IN_DBOX = SHOWING_ROOM;
} else if(isEQUAL(PRIOR, SHOWING_ROOM)) {
PRIOR = SHOWING_INV;
IN_DBOX = SHOWING_INV;
} else if((isEQUAL(PRIOR
, SHOWING_INV)
&& !(isEQUAL(STAT_ROUTINE
, BAR_NUMBER)))) {
PRIOR = SHOWING_STATS;
IN_DBOX = SHOWING_STATS;
} else {
PRIOR = 0;
}
}
} else {
if(isEQUAL(_LINE, 1)) {
if(--VERBOSITY < 0) {
VERBOSITY = 2;
}
} else if(isEQUAL(_LINE, 5)) {
if(!(PRIOR)) {
PRIOR = SHOWING_STATS;
IN_DBOX = SHOWING_STATS;
if(isEQUAL(STAT_ROUTINE
, BAR_NUMBER)) {
PRIOR = SHOWING_INV;
IN_DBOX = SHOWING_INV;
}
} else if(isEQUAL(PRIOR, SHOWING_ROOM)) {
PRIOR = 0;
} else if(isEQUAL(PRIOR, SHOWING_INV)) {
PRIOR = SHOWING_ROOM;
IN_DBOX = SHOWING_ROOM;
} else if(!(isEQUAL(STAT_ROUTINE
, BAR_NUMBER))) {
PRIOR = SHOWING_INV;
IN_DBOX = SHOWING_INV;
}
}
}
inner_loop.finish();return;
}
SOUND(S_BOOP);
setTimeout(inner_loop.again, 20);
});
inner_loop.onFinish(() => {
setTimeout(outer.post, 20);
});
});
outer.post();
}
function SHOW_SETLINE(_LINE, _TOP, _LMARGIN, _HL=0) {
let _X;
SCREEN(S_WINDOW);
_TOP = (_TOP + 2);
_X = (SETOFFS[_LINE] + _LMARGIN);
DO_CURSET(((_LINE * 2) + _TOP), _X);
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
COLOR(FORE, BGND);
if(isT(_HL)) {
HLIGHT(H_INVERSE);
}
PRINT(SNAMES[_LINE]);
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(isEQUAL(_LINE, 7, 8)) {
return true;
} else if(!(_LINE)) {
if(isT(DMODE)) {
HLIGHT(H_INVERSE);
}
TELL(" Enhanced ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(!(DMODE)) {
HLIGHT(H_INVERSE);
}
TELL(" Standard ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
return true;
} else if(isEQUAL(_LINE, 1)) {
if(!(VERBOSITY)) {
HLIGHT(H_INVERSE);
}
TELL(" Superbrief ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(isEQUAL(VERBOSITY, 1)) {
HLIGHT(H_INVERSE);
}
TELL(" Brief ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(isEQUAL(VERBOSITY, 2)) {
HLIGHT(H_INVERSE);
}
TELL(" Verbose ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
return true;
} else if(isEQUAL(_LINE, 2)) {
_X = (LOWCORE(FLAGS) & 1);
if(!(_X)) {
HLIGHT(H_INVERSE);
}
TELL(" Off ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(isT(_X)) {
HLIGHT(H_INVERSE);
}
TELL(" On ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
return true;
} else if(isEQUAL(_LINE, 3)) {
if(!(SAY_STAT)) {
HLIGHT(H_INVERSE);
}
TELL(" Off ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(isT(SAY_STAT)) {
HLIGHT(H_INVERSE);
}
TELL(" On ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
return true;
} else if(isEQUAL(_LINE, 4)) {
if(!(DMODE)) {
} else if(isEQUAL(MAP_ROUTINE, CLOSE_MAP)) {
HLIGHT(H_INVERSE);
}
TELL(" Normal ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(!(DMODE)) {
} else if(isEQUAL(MAP_ROUTINE, FAR_MAP)) {
HLIGHT(H_INVERSE);
}
TELL(" Wide ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
return true;
} else if(isEQUAL(_LINE, 5)) {
if(!(DMODE)) {
} else if(!(PRIOR)) {
HLIGHT(H_INVERSE);
}
TELL(" Off ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(!(DMODE)) {
} else if(isEQUAL(PRIOR, SHOWING_ROOM)) {
HLIGHT(H_INVERSE);
}
TELL(" Room ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(!(DMODE)) {
} else if(isEQUAL(PRIOR, SHOWING_INV)) {
HLIGHT(H_INVERSE);
}
TELL(" Inventory ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
if(!(isEQUAL(STAT_ROUTINE, BAR_NUMBER))) {
PRINTC(SP);
if(!(DMODE)) {
} else if(isEQUAL(PRIOR, SHOWING_STATS)) {
HLIGHT(H_INVERSE);
}
TELL(" Status ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
}
return true;
} else if(isEQUAL(_LINE, 6)) {
if(!(DMODE)) {
} else if(isT(AUTO)) {
HLIGHT(H_INVERSE);
}
TELL(" Automatic ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
PRINTC(SP);
if(!(DMODE)) {
} else if(!(AUTO)) {
HLIGHT(H_INVERSE);
}
TELL(" Off ");
HLIGHT(H_NORMAL);
HLIGHT(H_MONO);
return true;
} else {
return false;
}
}
function INIT_VERBS() {
WEARING = WEARING();
HOLDING = HOLDING();
MONEY = MONEY();
} |
package io.quarkiverse.config.sample.it;
import io.quarkus.test.junit.NativeImageTest;
@NativeImageTest
public class NativeConfigExtensionsResourceIT extends ConfigExtensionsResourceTest {
}
|
<reponame>lananh265/social-network<filename>node_modules/react-icons-kit/ionicons/arrowDownA.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.arrowDownA = void 0;
var arrowDownA = {
"viewBox": "0 0 512 512",
"children": [{
"name": "polygon",
"attribs": {
"points": "256.5,448.5 448.5,256.5 336.5,256.5 336.5,64.5 176.5,64.5 176.5,256.5 64.5,256.5 "
},
"children": []
}]
};
exports.arrowDownA = arrowDownA; |
<reponame>yao-zhixiang/vite-vue-ts-starter<gh_stars>1-10
import { ref, watch, Ref } from 'vue'
import { useRoute } from 'vue-router'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
export function useCurrentRouteName(): Ref<any> {
const currentRouteName: Ref<any> = ref()
const route: RouteLocationNormalizedLoaded = useRoute()
watch(
() => route.name,
async (name) => {
currentRouteName.value = name
},
{ immediate: true },
)
return currentRouteName
}
|
package Main;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertGrades {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost";//at first we might dont have a database
static final String DB_URL1 = "jdbc:mysql://localhost/university";//here is the url fro the database
// Database credentials
static final String USER = "root";
static final String PASS = "<PASSWORD>#@!";
public boolean InsertValuestoGrades(String id_Student,String id_lesson,int grade) {
boolean x=false;
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection with the database
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL1, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
System.out.println("Insert records into students");
stmt = conn.createStatement();
String sql = "INSERT INTO GRADES " +
"VALUES ('"+id_Student+"','"+id_lesson+"','"+grade+"')";
stmt.executeUpdate(sql);
System.out.println("Records inserted");
x=true;
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
return x;
}
}
|
import time
import asyncio
import functools
def measure_execution_time(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = (end_time - start_time) * 1000 # Convert to milliseconds
print(f"Execution time for {func.__name__}: {execution_time} ms")
return result
return wrapper
# Test the decorator with synchronous and asynchronous functions
@measure_execution_time
def sync_function():
time.sleep(1)
@measure_execution_time
async def async_function():
await asyncio.sleep(1)
@measure_execution_time
def function_with_args(arg1, arg2):
time.sleep(1)
@measure_execution_time
async def async_function_with_args(arg1, arg2):
await asyncio.sleep(1) |
{"name": "John Doe", "age": 41, "location": "New York"} |
// C++ program to calculate
// determinant of a matrix
#include <iostream>
using namespace std;
// Dimension of input matrix
#define N 4
int determinant (int a[N][N], int k)
{
int s = 1, det = 0, b[N][N];
int i, j, m, n, c;
if (k == 1)
return (a[0][0]);
else
{
det = 0;
for (c = 0; c < k; c++)
{
m = 0;
n = 0;
for (i = 0;i < k; i++)
{
for (j = 0 ;j < k; j++)
{
b[i][j] = 0;
if (i != 0 && j != c)
{
b[m][n] = a[i][j];
if (n < (k - 2))
n++;
else
{
n = 0;
m++;
}
}
}
}
det = det + s * (a[0][c] * determinant(b, k - 1));
s = -1 * s;
}
}
return (det);
} |
function validateForm(form) {
var errors = [];
// Validate that all form fields have been populated
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value == '') {
errors.push('Please fill in all form fields.');
}
}
// Validate email address format
if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value)) {
errors.push('Please enter a valid email address.');
}
// If there are errors, let the user know
if (errors.length > 0) {
alert(errors.join("\n"));
} else {
form.submit();
}
} |
<gh_stars>0
/*
* Copyright (C) 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mhv.firebaseauth;
import android.accounts.AccountManager;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.mhv.firebaseauth.util.AuthUtils;
public class AuthService extends IntentService {
private static final String TAG = "AuthService";
public static final String ACTION_LOGIN = "auth_action_login";
public static final String ACTION_REGISTER = "auth_action_register";
public static final String EXTRA_USER_NAME = "extra_user_name";
public static final String EXTRA_USER_EMAIL = "extra_user_email";
public static final String EXTRA_USER_PASSWORD = "<PASSWORD>";
public static final String EXTRA_AUTH_TOKEN = "extra_auth_token";
private FirebaseAuth mAuth;
public AuthService() {
super("AuthService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
if (intent == null) {
return;
}
String action = intent.getAction();
if (action == null) {
return;
}
mAuth = FirebaseAuth.getInstance();
switch (action) {
case ACTION_REGISTER:
register(intent);
break;
case ACTION_LOGIN:
login(intent);
break;
}
}
private void register(Intent registrationIntent) {
final String userName = registrationIntent.getStringExtra(EXTRA_USER_NAME);
final String userEmail = registrationIntent.getStringExtra(EXTRA_USER_EMAIL);
final String userPassword = registrationIntent.getStringExtra(EXTRA_USER_PASSWORD);
Log.d(TAG, "Registering - user: " + userName + " email: " + userEmail);
final Bundle registerData = new Bundle();
mAuth.createUserWithEmailAndPassword(userEmail, userPassword)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String authToken = AuthUtils.generateFirebaseAuthToken(userName);
registerData.putString(AccountManager.KEY_ACCOUNT_NAME, userEmail);
registerData.putString(AccountManager.KEY_ACCOUNT_TYPE,
Constants.ACCOUNT_TYPE);
registerData.putString(AccountManager.KEY_AUTHTOKEN, authToken);
registerData.putString(AccountManager.KEY_PASSWORD, <PASSWORD>);
Log.d(TAG, "Registration successful - user: " + userName
+ " email: " + userEmail + " token: " + authToken);
// TODO: Also broadcast errors!
final Intent result = new Intent(ACTION_REGISTER);
result.putExtras(registerData);
LocalBroadcastManager
.getInstance(AuthService.this).sendBroadcast(result);
} else {
Log.e(TAG, "Registration failed", task.getException());
registerData.putString(AccountManager.KEY_ERROR_MESSAGE,
task.getException().getMessage());
}
}
});
}
private void login(Intent loginIntent) {
final String userEmail = loginIntent.getStringExtra(EXTRA_USER_EMAIL);
final String userPassword = loginIntent.getStringExtra(EXTRA_USER_PASSWORD);
final String authToken = loginIntent.getStringExtra(EXTRA_AUTH_TOKEN);
Log.d(TAG, "Login - user: " + userEmail + " authToken: " + authToken);
final Bundle loginData = new Bundle();
if (!TextUtils.isEmpty(authToken)) {
mAuth.signInWithCustomToken(authToken)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
loginData.putString(AccountManager.KEY_ACCOUNT_NAME, userEmail);
loginData.putString(AccountManager.KEY_ACCOUNT_TYPE,
Constants.ACCOUNT_TYPE);
loginData.putString(AccountManager.KEY_AUTHTOKEN, authToken);
loginData.putString(AccountManager.KEY_PASSWORD, <PASSWORD>);
Log.d(TAG, "Registration successful - user: " + userEmail
+ " token: " + authToken);
} else {
Log.e(TAG, "Login failed", task.getException());
loginData.putString(AccountManager.KEY_ERROR_MESSAGE,
task.getException().getMessage());
}
}
});
final Intent result = new Intent(ACTION_LOGIN);
result.putExtras(loginData);
LocalBroadcastManager.getInstance(this).sendBroadcast(result);
}
}
}
|
package mobile
import (
"testing"
"github.com/elko-dev/spawn/applications"
"github.com/golang/mock/gomock"
)
func TestMobileTypeCallsClientOnlyWhenIncludeBackendIsFalse(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient := applications.NewMockProject(ctrl)
mockServer := applications.NewMockProject(ctrl)
mockClient.EXPECT().Create().Return(nil)
mockServer.EXPECT().Create().MaxTimes(0)
mobileType := NewMobileType(mockClient, mockServer, false)
err := mobileType.Create()
if err != nil {
t.Log("Error found when none existed ", err)
t.Fail()
}
}
func TestMobileTypeCallsClientAndServerWhenIncludeBackendIsFalse(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient := applications.NewMockProject(ctrl)
mockServer := applications.NewMockProject(ctrl)
mockClient.EXPECT().Create().Return(nil)
mockServer.EXPECT().Create().Return(nil)
mobileType := NewMobileType(mockClient, mockServer, true)
err := mobileType.Create()
if err != nil {
t.Log("Error found when none existed ", err)
t.Fail()
}
}
|
<reponame>10088/spring-data-mongodb<filename>spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/SkipOperation.java<gh_stars>0
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.aggregation;
import org.bson.Document;
import org.springframework.util.Assert;
/**
* Encapsulates the aggregation framework {@code $skip}-operation.
* <p>
* We recommend to use the static factory method {@link Aggregation#skip(int)} instead of creating instances of this
* class directly.
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @since 1.3
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/skip/">MongoDB Aggregation Framework:
* $skip</a>
*/
public class SkipOperation implements AggregationOperation {
private final long skipCount;
/**
* Creates a new {@link SkipOperation} skipping the given number of elements.
*
* @param skipCount number of documents to skip, must not be less than zero.
*/
public SkipOperation(long skipCount) {
Assert.isTrue(skipCount >= 0, "Skip count must not be negative");
this.skipCount = skipCount;
}
@Override
public Document toDocument(AggregationOperationContext context) {
return new Document(getOperator(), skipCount);
}
@Override
public String getOperator() {
return "$skip";
}
}
|
<filename>src/app/bet/bet.component.spec.ts
import { async, TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { By } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';
import { AppModule } from '../app.module';
import { RaceService } from '../race.service';
import { BetComponent } from './bet.component';
import { PonyComponent } from '../pony/pony.component';
import { RaceModel } from '../models/race.model';
import { PonyModel } from '../models/pony.model';
describe('BetComponent', () => {
const fakeRaceService = jasmine.createSpyObj('RaceService', ['get', 'bet', 'cancelBet']);
const race = { id: 1, name: 'Paris' };
fakeRaceService.get.and.returnValue(Observable.of(race));
const fakeActivatedRoute = { snapshot: { params: { raceId: 1 } } };
beforeEach(() => TestBed.configureTestingModule({
imports: [AppModule, RouterTestingModule],
providers: [
{ provide: RaceService, useValue: fakeRaceService },
{ provide: ActivatedRoute, useValue: fakeActivatedRoute }
]
}));
it('should display a race name, its date and its ponies', () => {
const fixture = TestBed.createComponent(BetComponent);
fixture.detectChanges();
// given a race in Paris with 5 ponies
const betComponent = fixture.componentInstance;
betComponent.raceModel = {
id: 12,
name: 'Paris',
ponies: [
{ id: 1, name: 'Gentle Pie', color: 'YELLOW' },
{ id: 2, name: 'Big Soda', color: 'ORANGE' },
{ id: 3, name: 'Gentle Bottle', color: 'PURPLE' },
{ id: 4, name: 'Superb Whiskey', color: 'GREEN' },
{ id: 5, name: 'Fast Rainbow', color: 'BLUE' }
],
startInstant: '2016-02-18T08:02:00Z'
};
// when triggering the change detection
fixture.detectChanges();
// then we should have the name and ponies displayed in the template
const directives = fixture.debugElement.queryAll(By.directive(PonyComponent));
expect(directives).not.toBeNull('You should use the PonyComponent in your template to display the ponies');
expect(directives.length).toBe(5, 'You should have five pony components in your template');
const element = fixture.nativeElement;
const raceName = element.querySelector('h2');
expect(raceName).not.toBeNull('You need an h2 element for the race name');
expect(raceName.textContent).toContain('Paris', 'The h2 element should contain the race name');
const startInstant = element.querySelector('p');
expect(startInstant).not.toBeNull('You should use a `p` element to display the start instant');
expect(startInstant.textContent).toContain('ago', 'You should use the `fromNow` pipe you created to format the start instant');
});
it('should trigger a bet when a pony is clicked', async(() => {
const fixture = TestBed.createComponent(BetComponent);
fixture.detectChanges();
fakeRaceService.bet.and.returnValue(Observable.of({
id: 12,
name: 'Paris',
ponies: [
{ id: 1, name: '<NAME>', color: 'YELLOW' },
{ id: 2, name: 'Big Soda', color: 'ORANGE' }
],
startInstant: '2016-02-18T08:02:00Z',
betPonyId: 1
}));
// given a race in Paris with 5 ponies
const betComponent = fixture.componentInstance;
betComponent.raceModel = {
id: 12,
name: 'Paris',
ponies: [
{ id: 1, name: '<NAME>', color: 'YELLOW' },
{ id: 2, name: '<NAME>', color: 'ORANGE' }
],
startInstant: '2016-02-18T08:02:00Z'
};
fixture.detectChanges();
// when we emit a `ponyClicked` event
const directives = fixture.debugElement.queryAll(By.directive(PonyComponent));
const gentlePie = directives[0].componentInstance;
// then we should have placed a bet on the pony
gentlePie.ponyClicked.subscribe(() => {
expect(fakeRaceService.bet).toHaveBeenCalledWith(12, 1);
});
gentlePie.ponyClicked.emit(betComponent.raceModel.ponies[0]);
}));
it('should test if the pony is the one we bet on', () => {
const fixture = TestBed.createComponent(BetComponent);
const component = fixture.componentInstance;
component.raceModel = {
id: 12,
name: 'Paris',
ponies: [
{ id: 1, name: '<NAME>', color: 'YELLOW' },
{ id: 2, name: '<NAME>', color: 'ORANGE' }
],
startInstant: '2016-02-18T08:02:00Z',
betPonyId: 1
};
const pony = { id: 1 };
const isSelected = component.isPonySelected(pony);
expect(isSelected).toBe(true, 'The `isPonySelected` medthod should return true if the pony is selected');
});
it('should initialize the race with ngOnInit', () => {
const fixture = TestBed.createComponent(BetComponent);
const component = fixture.componentInstance;
expect(component.raceModel).toBeUndefined();
fakeActivatedRoute.snapshot.params = { raceId: 1 };
component.ngOnInit();
expect(component.raceModel).toBe(race, '`ngOnInit` should initialize the `raceModel`');
expect(fakeRaceService.get).toHaveBeenCalledWith(1);
});
it('should display an error message if bet failed', () => {
const fixture = TestBed.createComponent(BetComponent);
fakeRaceService.bet.and.callFake(() => Observable.throw(new Error('Oops')));
const component = fixture.componentInstance;
component.raceModel = { id: 2 } as RaceModel;
expect(component.betFailed).toBe(false);
const pony = { id: 1 };
component.betOnPony(pony);
expect(component.betFailed).toBe(true);
fixture.detectChanges();
const element = fixture.nativeElement;
const message = element.querySelector('.alert.alert-danger');
expect(message.textContent).toContain('The race is already started or finished');
});
it('should cancel a bet', () => {
const fixture = TestBed.createComponent(BetComponent);
fakeRaceService.cancelBet.and.returnValue(Observable.of(null));
const component = fixture.componentInstance;
component.raceModel = { id: 2, betPonyId: 1, name: 'Lyon', ponies: [], startInstant: '2016-02-18T08:02:00Z' };
const pony = { id: 1 } as PonyModel;
component.betOnPony(pony);
expect(fakeRaceService.cancelBet).toHaveBeenCalledWith(2);
expect(component.raceModel.betPonyId).toBeNull();
});
it('should display a message if canceling a bet fails', () => {
const fixture = TestBed.createComponent(BetComponent);
fixture.detectChanges();
fakeRaceService.cancelBet.and.callFake(() => Observable.throw(new Error('Oops')));
const component = fixture.componentInstance;
component.raceModel = { id: 2, betPonyId: 1, name: 'Lyon', ponies: [], startInstant: '2016-02-18T08:02:00Z' };
expect(component.betFailed).toBe(false);
const pony = { id: 1 } as PonyModel;
component.betOnPony(pony);
expect(fakeRaceService.cancelBet).toHaveBeenCalledWith(2);
expect(component.raceModel.betPonyId).toBe(1);
expect(component.betFailed).toBe(true);
});
it('should display a link to go to live', () => {
const fixture = TestBed.createComponent(BetComponent);
fixture.detectChanges();
const component = fixture.componentInstance;
component.raceModel = { id: 2, betPonyId: 1, name: 'Lyon', ponies: [], startInstant: '2016-02-18T08:02:00Z' };
fixture.detectChanges();
const element = fixture.nativeElement;
const button = element.querySelector('a[href="/races/2/live"]');
expect(button).not.toBeNull('You should have a link to go to the live with an href `/races/id/live`');
expect(button.textContent).toContain('Watch live!');
});
});
|
#!/bin/sh
APP="Example.app"
mkdir -p $APP/Contents/{MacOS,Resources}
go build -o $APP/Contents/MacOS/OTPNWACFEGO
cat > $APP/Contents/Info.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>OTPNWACFEGO</string>
<key>CFBundleIconFile</key>
<string>icon.icns</string>
<key>CFBundleIdentifier</key>
<string>com.zserge.lorca.example</string>
</dict>
</plist>
EOF
cp icons/icon.icns $APP/Contents/Resources/icon.icns
find $APP
|
import * as pulumi from '@pulumi/pulumi'
import { Config as BaseConfig, Cluster, Dockerhub } from '../../../pulumi'
const SUPPORTED_NETWORKS = ['mainnet']
export interface Config {
kubeconfig: string
config: BaseConfig
namespace: string
}
export const getConfig = async (): Promise<Config> => {
let config: BaseConfig
try {
config = new pulumi.Config('unchained').requireObject<BaseConfig>('cosmos')
} catch (e) {
throw new pulumi.RunError(
`Could not find required configuration file. \n\tDid you copy the Pulumi.sample.yaml file to Pulumi.${pulumi.getStack()}.yaml and update the necessary configuration?`
)
}
const stackReference = new pulumi.StackReference(config.stack)
const kubeconfig = (await stackReference.getOutputValue('kubeconfig')) as string
const namespaces = (await stackReference.getOutputValue('namespaces')) as Array<string>
const defaultNamespace = (await stackReference.getOutputValue('defaultNamespace')) as string
const namespace = config.environment ? `${defaultNamespace}-${config.environment}` : defaultNamespace
if (!namespaces.includes(namespace)) {
throw new Error(
`Error: environment: ${config.environment} not found in cluster. Either remove to use default environment or verify environment exists`
)
}
config.isLocal = (await stackReference.getOutputValue('isLocal')) as boolean
config.cluster = (await stackReference.getOutputValue('cluster')) as Cluster
config.dockerhub = (await stackReference.getOutputValue('dockerhub')) as Dockerhub
config.rootDomainName = (await stackReference.getOutputValue('rootDomainName')) as string
const missingRequiredConfig: Array<string> = []
if (!config.stack) missingRequiredConfig.push('stack')
if (!config.network || !SUPPORTED_NETWORKS.includes(config.network)) {
missingRequiredConfig.push(`network (${SUPPORTED_NETWORKS})`)
}
if (config.api) {
if (config.api.autoscaling) {
if (config.api.autoscaling.enabled === undefined) missingRequiredConfig.push('api.autoscaling.enabled')
if (config.api.autoscaling.maxReplicas === undefined) missingRequiredConfig.push('api.autoscaling.maxReplicas')
if (config.api.autoscaling.cpuThreshold === undefined) missingRequiredConfig.push('api.autoscaling.cpuThreshold')
}
if (config.api.cpuLimit === undefined) missingRequiredConfig.push('api.cpuLimit')
if (config.api.memoryLimit === undefined) missingRequiredConfig.push('api.memoryLimit')
if (config.api.replicas === undefined) missingRequiredConfig.push('api.replicas')
}
if (missingRequiredConfig.length) {
throw new Error(
`Missing the following configuration values from Pulumi.${pulumi.getStack()}.yaml: ${missingRequiredConfig.join(
', '
)}`
)
}
return { kubeconfig, config, namespace }
}
|
<gh_stars>0
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.atlas.data;
import java.util.Comparator ;
import java.util.HashSet ;
import java.util.Iterator ;
import org.apache.jena.atlas.iterator.Iter ;
import org.apache.jena.atlas.iterator.PeekIterator ;
import org.apache.jena.atlas.lib.Closeable ;
/**
* <p>
* This data bag will gather distinct items in memory until a size threshold is passed, at which point it will write
* out all of the items to disk using the supplied serializer.
* </p>
* <p>
* After adding is finished, call {@link #iterator()} to set up the data bag for reading back items and iterating over them.
* The iterator will retrieve only distinct items.
* </p>
* <p>
* IMPORTANT: You may not add any more items after this call. You may subsequently call {@link #iterator()} multiple
* times which will give you a new iterator for each invocation. If you do not consume the entire iterator, you should
* call {@link Iter#close(Iterator)} to close any FileInputStreams associated with the iterator.
* </p>
* <p>
* Additionally, make sure to call {@link #close()} when you are finished to free any system resources (preferably in a finally block).
* </p>
* <p>
* Implementation Notes: Data is stored without duplicates as it comes in in a HashSet. When it is time to spill,
* that data is sorted and written to disk. An iterator that eliminates adjacent duplicates is used in conjunction
* with the SortedDataBag's iterator.
* </p>
*/
public class DistinctDataBag<E> extends SortedDataBag<E>
{
public DistinctDataBag(ThresholdPolicy<E> policy, SerializationFactory<E> serializerFactory, Comparator<E> comparator)
{
super(policy, serializerFactory, comparator);
this.memory = new HashSet<>();
}
@Override
public boolean isSorted()
{
// The bag may not be sorted if we havn't spilled
return false;
}
@Override
public boolean isDistinct()
{
return true;
}
@Override
public Iterator<E> iterator()
{
// We could just return super.iterator() in all cases,
// but no need to waste time sorting if we havn't spilled
if (!spilled)
{
checkClosed();
finishedAdding = true;
if (memory.size() > 0)
{
return memory.iterator();
}
else
{
return Iter.nullIterator();
}
}
else
{
return new DistinctReducedIterator<>(super.iterator());
}
}
protected static class DistinctReducedIterator<T> extends PeekIterator<T> implements Closeable
{
private Iterator<T> iter;
public DistinctReducedIterator(Iterator<T> iter)
{
super(iter);
this.iter = iter;
}
@Override
public T next()
{
T item = super.next();
// Keep going until as long as the next item is the same as the current one
while (hasNext() && ((null == item && null == peek()) || (null != item && item.equals(peek()))))
{
item = super.next();
}
return item;
}
@Override
public void close()
{
Iter.close(iter);
}
}
}
|
#!/usr/bin/env bash
set -euo pipefail
PAYLOAD="{}"
if [[ -e buildpack.toml ]]; then
PAYLOAD=$(jq -n -r \
--argjson PAYLOAD "${PAYLOAD}" \
--argjson BUILDPACK "$(yj -tj < buildpack.toml)" \
'$PAYLOAD | .primary = $BUILDPACK')
fi
if [[ -e builder.toml ]]; then
PAYLOAD=$(jq -n -r \
--argjson PAYLOAD "${PAYLOAD}" \
--argjson BUILDER "$(yj -tj < builder.toml)" \
'$PAYLOAD | .primary = $BUILDER')
for BUILDPACK in $(
jq -n -r \
--argjson PAYLOAD "${PAYLOAD}" \
'$PAYLOAD.primary.buildpacks[].uri | capture("(?:.+://)?(?<image>.+)") | .image'
); do
crane export "${BUILDPACK}" - | tar xf - --absolute-names --strip-components 1 --wildcards "/cnb/buildpacks/*/*/buildpack.toml"
done
fi
if [[ -e package.toml ]]; then
for PACKAGE in $(yj -t < package.toml | jq -r '.dependencies[].uri | capture("(?:.+://)?(?<image>.+)") | .image'); do
crane export "${PACKAGE}" - | tar xf - --absolute-names --strip-components 1 --wildcards "/cnb/buildpacks/*/*/buildpack.toml"
done
fi
if [[ -d buildpacks ]]; then
while IFS= read -r -d '' FILE; do
PAYLOAD=$(jq -n -r \
--argjson PAYLOAD "${PAYLOAD}" \
--argjson BUILDPACK "$(yj -tj < "${FILE}")" \
'$PAYLOAD | .buildpacks += [ $BUILDPACK ]')
done < <(find buildpacks -name buildpack.toml -print0)
fi
jq -n -r \
--argjson PAYLOAD "${PAYLOAD}" \
--arg RELEASE_NAME "${RELEASE_NAME}" \
'( select($PAYLOAD.primary.buildpack.name) | "\($PAYLOAD.primary.buildpack.name) \($RELEASE_NAME)" ) // "\($RELEASE_NAME)"' \
> "${HOME}"/name
jq -n -r \
--argjson PAYLOAD "${PAYLOAD}" \
--arg RELEASE_BODY "${RELEASE_BODY}" \
'
def id(b):
select(b.buildpack.id) | "**ID**: `\(b.buildpack.id)`"
;
def included_buildpackages(b): [
"#### Included Buildpackages:",
"Name | ID | Version",
":--- | :- | :------",
( b | sort_by(.buildpack.name | ascii_downcase) | map("\(.buildpack.name) | `\(.buildpack.id)` | `\(.buildpack.version)`") ),
""
];
def stacks(s): [
"#### Supported Stacks:",
( s | sort_by(.id | ascii_downcase) | map("- `\(.id)`") ),
""
];
def default_dependency_versions(d): [
"#### Default Dependency Versions:",
"ID | Version",
":- | :------",
( d | to_entries | sort_by(.key | ascii_downcase) | map("`\(.key)` | `\(.value)`") ),
""
];
def dependencies(d): [
"#### Dependencies:",
"Name | Version | SHA256",
":--- | :------ | :-----",
( d | sort_by(.name // .id | ascii_downcase) | map("\(.name // .id) | `\(.version)` | `\(.sha256)`")),
""
];
def order_groupings(o): [
"<details>",
"<summary>Order Groupings</summary>",
"",
( o | map([
"ID | Version | Optional",
":- | :------ | :-------",
( .group | map([ "`\(.id)` | ", (select(.version) | "`\(.version)`"), ( select(.optional) | "| `\(.optional)`" ) ] | join(" ")) ),
""
])),
"</details>",
""
];
def primary_buildpack(p): [
id(p.primary),
"**Digest**: <!-- DIGEST PLACEHOLDER -->",
"",
( select(p.buildpacks) | included_buildpackages(p.buildpacks) ),
( select(p.primary.stacks) | stacks(p.primary.stacks) ),
( select(p.primary.metadata."default-versions") | default_dependency_versions(p.primary.metadata."default-versions") ),
( select(p.primary.metadata.dependencies) | dependencies(p.primary.metadata.dependencies) ),
( select(p.primary.order) | order_groupings(p.primary.order) ),
( select(p.buildpacks) | "---" ),
""
];
def nested_buildpack(b): [
"<details>",
"<summary>\(b.buildpack.name) \(b.buildpack.version)</summary>",
"",
id(b),
"",
( select(b.stacks) | stacks(b.stacks) ),
( select(b.metadata."default-versions") | default_dependency_versions(b.metadata."default-versions") ),
( select(b.metadata.dependencies) | dependencies(b.metadata.dependencies) ),
( select(b.order) | order_groupings(b.order) ),
"---",
"",
"</details>",
""
];
$PAYLOAD | [
primary_buildpack(.),
( select(.buildpacks) | [ .buildpacks | sort_by(.buildpack.name | ascii_downcase) | map(nested_buildpack(.)) ] ),
"",
"---",
"",
$RELEASE_BODY
] | flatten | join("\n")
' > "${HOME}"/body
gh api \
--method PATCH \
"/repos/:owner/:repo/releases/${RELEASE_ID}" \
--field "tag_name=${RELEASE_TAG_NAME}" \
--field "name=@${HOME}/name" \
--field "body=@${HOME}/body"
|
import urllib.request
def download_webpage_source(url):
'''This function will download the source code of a given web page'''
response = urllib.request.urlopen(url)
data = response.read()
text = data.decode('utf-8')
return text |
<filename>lib/cbr/obj/src/cli_display_header.c
/* **** Notes
Display the two-row header.
Remarks:
EOL with CR (0x0D) and LF (0x0A)
*/
# define CBR
# include <stdio.h>
# include <time.h>
# include "../../../incl/config.h"
signed(__cdecl cli_display_header(CLI_TYPEWRITER(*argp))) {
/* **** DATA, BSS and STACK */
auto signed char *(day_of_the_week[]) = {
(signed char(*)) ("SUNDAY"),
(signed char(*)) ("MONDAY"),
(signed char(*)) ("TUESDAY"),
(signed char(*)) ("WEDNESDAY"),
(signed char(*)) ("THURSDAY"),
(signed char(*)) ("FRIDAY"),
(signed char(*)) ("SATURDAY"),
(signed char(*)) (0x00)
};
auto signed char *(mon[]) = {
(signed char(*)) ("JANUARY"),
(signed char(*)) ("FEBRUARY"),
(signed char(*)) ("MARCH"),
(signed char(*)) ("APRIL"),
(signed char(*)) ("MAY"),
(signed char(*)) ("JUNE"),
(signed char(*)) ("JULY"),
(signed char(*)) ("AUGUST"),
(signed char(*)) ("SEPTEMBER"),
(signed char(*)) ("OCTOBER"),
(signed char(*)) ("NOVEMBER"),
(signed char(*)) ("DECEMBER"),
(signed char(*)) (0x00)
};
auto struct tm *tp;
auto time_t t;
auto signed i,r;
auto signed short flag;
/* **** CODE/TEXT */
if(!argp) return(0x00);
t = time(&t);
if(!(t^(~0x00))) {
printf("%s \n","<< Error at fn. time()");
return(0x00);
}
tp = localtime(&t);
if(!tp) {
printf("%s \n","<< Error at fn. localtime()");
return(0x00);
}
/* The two-row header */
printf("%s %d %s %d ",*(day_of_the_week+(R(tm_wday,*tp))),R(tm_mday,*tp),*(mon+(R(tm_mon,*tp))),1900+(R(tm_year,*tp)));
if(!(CLI_DEFAULT^(R(display_header,R(config,*argp))))) {
printf("%s %s ","|","Ctrl-Q to quit");
printf("%s %s ","|","UTF-8");
printf("%s %s %d ","|","Tab:",R(align_tab,R(config,*argp)));
AND(flag,0x00);
if(!(LINEBREAK_CRLF^(R(linebreak_form,R(config,*argp))))) {
printf("%s %s ","|","EOL: CRLF (0x0D and 0x0A)");
OR(flag,0x01);
}
if(!(LINEBREAK_LF^(R(linebreak_form,R(config,*argp))))) {
printf("%s %s ","|","EOL: LF (0x0A)");
OR(flag,0x01);
}
if(!flag) {
printf("%s \n","<< Set the linebreak form at (R(linebreak_form,R(config,*argp..");
return(0x00);
}}
return(0x01);
}
|
#!/bin/bash
sudo apt-get install default-jdk ant zip
VERSION=${VERSION:-`git describe --tags`}
ZIPDIR="Koto-${VERSION}-Windows"
cd `dirname $0`
set -e
mkdir -p tmp
cd tmp
if [ -d koto-swing-wallet-ui ]; then
rm -rf koto-swing-wallet-ui
fi
git clone https://github.com/KotoDevelopers/koto-swing-wallet-ui.git
cd koto-swing-wallet-ui
ant -buildfile src/build/build.xml
cd ..
mkdir -p $ZIPDIR
cp ../win/* $ZIPDIR
cp koto-swing-wallet-ui/build/jars/KotoSwingWalletUI.jar $ZIPDIR
cp ../../src/kotod.exe ../../src/koto-cli.exe ../../src/koto-tx.exe $ZIPDIR
strip $ZIPDIR/kotod.exe $ZIPDIR/koto-cli.exe $ZIPDIR/koto-tx.exe
zip -r ../${ZIPDIR}.zip $ZIPDIR
|
module.exports = (function() {
var mongoose = require("mongoose");
var connectionString = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/cryptocaster';
mongoose.connect(connectionString);
})(); |
<gh_stars>10-100
#ifndef _WKT_SCRIPT_SYSTEM_H
#define _WKT_SCRIPT_SYSTEM_H
#include "ecs/System.h"
#include "components/Script.h"
namespace wkt {
namespace systems
{
class ScriptSystem : public wkt::ecs::SequentialSystem<wkt::components::Script>
{
public:
ScriptSystem();
public:
void operator()(std::shared_ptr<wkt::components::Script>);
};
}}
#endif |
// Import React
import React from "react";
// Import Spectacle Core tags
import { Deck } from "spectacle";
// Slides
import { Slide0 } from './0';
import { Agenda } from './1';
import { Setup } from './2';
import { Setup2 } from './3';
import { HMR } from './4';
import { Debug } from './5';
import { ServerSideRendering } from './6';
import { NodeServices } from './7';
import { NodeServices2 } from './8';
import { Links } from './9';
// Import theme
//import createTheme from "spectacle/lib/themes/default";
import theme from "../themes/formidable/index.js";
// Require CSS
require("normalize.css");
require("spectacle/lib/themes/default/index.css");
// Best way to include fonts rite
require("../fonts/worksans.css");
require("../fonts/biorhyme.css");
require("../fonts/silkscreen.css");
export default class Presentation extends React.Component {
render() {
return <Deck progress="none" theme={theme} transition={["fade"]} transitionDuration={500} controls={false}>
{Slide0}
{Agenda}
{Setup}
{Setup2}
{HMR}
{Debug}
{ServerSideRendering}
{NodeServices}
{NodeServices2}
{Links}
</Deck>;
}
}
|
#pragma once
#include "Component.h"
namespace fl {
class MayaCameraComponent : public Component
{
public:
private:
};
}
|
#!/bin/bash
set -e
# Download grid files to nad/
wget http://download.osgeo.org/proj/proj-datumgrid-1.6.zip
cd nad
unzip -o ../proj-datumgrid-1.6.zip
wget http://download.osgeo.org/proj/vdatum/egm96_15/egm96_15.gtx
wget https://raw.githubusercontent.com/OSGeo/proj-datumgrid/master/BETA2007.gsb
GRIDDIR=`pwd`
echo $GRIDDIR
cd ..
# prepare build files
./autogen.sh
# cmake build
mkdir build_cmake
cd build_cmake
cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/proj_cmake_install
make -j3
make install
find /tmp/proj_cmake_install
cd ..
# autoconf build
mkdir build_autoconf
cd build_autoconf
../configure --prefix=/tmp/proj_autoconf_install
make -j3
make install
make dist-all
find /tmp/proj_autoconf_install
PROJ_LIB=$GRIDDIR make check
# Check consistency of generated tarball
TAR_FILENAME=`ls *.tar.gz`
TAR_DIRECTORY=`basename $TAR_FILENAME .tar.gz`
tar xvzf $TAR_FILENAME
cd $TAR_DIRECTORY
./configure --prefix=/tmp/proj_autoconf_install_from_dist_all
make -j3
make install
PROJ_LIB=$GRIDDIR make check
CURRENT_PWD=`pwd`
cd /tmp/proj_autoconf_install
find | sort > /tmp/list_proj_autoconf_install.txt
cd /tmp/proj_autoconf_install_from_dist_all
find | sort > /tmp/list_proj_autoconf_install_from_dist_all.txt
cd $CURRENT_PWD
# The list of file is not identical. See http://lists.maptools.org/pipermail/proj/2015-September/007231.html
#diff -u /tmp/list_proj_autoconf_install.txt /tmp/list_proj_autoconf_install_from_dist_all.txt
cd ..
#
cd ..
# cmake build with grids
mkdir build_cmake_nad
cd build_cmake_nad
cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/proj_cmake_install_nad
make -j3
make install
find /tmp/proj_cmake_install_nad
cd ..
# autoconf build with grids
mkdir build_autoconf_nad
cd build_autoconf_nad
../configure --prefix=/tmp/proj_autoconf_install_nad
make -j3
make install
find /tmp/proj_autoconf_install_nad
PROJ_LIB=$GRIDDIR make check
cd src
make multistresstest
make test228
cd ..
PROJ_LIB=../nad src/multistresstest
cd ..
# autoconf build with grids and coverage
if [ $TRAVIS_OS_NAME == "osx" ]; then
CFLAGS="--coverage" ./configure;
else
CFLAGS="--coverage" LDFLAGS="-lgcov" ./configure;
fi
make -j3
PROJ_LIB=$GRIDDIR make check
# Rerun tests without grids not included in proj-datumgrid
rm -v ${GRIDDIR}/egm96_15.gtx
PROJ_LIB=$GRIDDIR make check
mv src/.libs/*.gc* src
|
(function() {
window.cookieconsent.initialise({CONFIG});
})(); |
export function microInMacro() {
return new Promise((resolve, reject) => {
setTimeout(resolve, 0)
})
}
|
#!/bin/sh
# Test "ln -sf".
# Copyright (C) 1997-2015 Free Software Foundation, Inc.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
. "${srcdir=.}/tests/init.sh"; path_prepend_ ./src
print_ver_ ln
echo foo > a || framework_failure_
# Check that a target directory of '.' is supported
# and that indirectly specifying the same target and link name
# through that is detected.
ln -s . b || framework_failure_
ln -sf a b > err 2>&1 && fail=1
case $(cat err) in
*'are the same file') ;;
*) fail=1 ;;
esac
# Ensure we replace symlinks that don't or can't link to an existing target.
# coreutils-8.22 would fail to replace {ENOTDIR,ELOOP,ENAMETOOLONG}_link below.
name_max_plus1=$(expr $(stat -f -c %l .) + 1)
test $name_max_plus1 -gt 1 || skip_ 'Error determining NAME_MAX'
long_name=$(printf '%0*d' $name_max_plus1 0)
for f in '' f; do
ln -s$f missing ENOENT_link || fail=1
ln -s$f a/b ENOTDIR_link || fail=1
ln -s$f ELOOP_link ELOOP_link || fail=1
ln -s$f "$long_name" ENAMETOOLONG_link || fail=1
done
Exit $fail
|
<reponame>jjallaire/prosemirror-gdrive<filename>src/core/log.js<gh_stars>0
import Vue from 'vue'
import * as Sentry from '@sentry/browser';
import config from '../config'
const production = process.env.NODE_ENV === 'production';
export function initialize() {
// configure sentry in production mode
if (useSentry()) {
Sentry.init({
dsn: config.sentry.dsn,
integrations: [new Sentry.Integrations.Vue({ Vue })]
});
if (process.env.VUE_APP_BRANCH) {
Sentry.configureScope((scope) => {
scope.setTag("branch", process.env.VUE_APP_BRANCH);
});
}
}
}
export function addBreadcrumb(category, message, level = 'info') {
Sentry.addBreadcrumb({
category: category,
message: message,
level: level
});
}
export function logException(error, tag) {
console.log(tag + ": " + error.message);
if (useSentry()) {
Sentry.withScope(scope => {
if (tag)
scope.setTag("tag", tag);
Sentry.captureException(error);
});
}
}
export function logMessage(message) {
console.log(message);
if (useSentry())
Sentry.captureMessage(message);
}
function useSentry() {
return config.sentry.dsn && production;
}
|
subscribe() {
this.navigate$.subscribe((direction: 'next' | 'previous') => {
if (direction === 'next') {
this.hasNextStep$.pipe(take(1)).subscribe((hasNext: boolean) => {
if (hasNext) {
// Navigate to the next step using the Angular Router
// Example: this.router.navigate(['/questionnaire', 'next-step']);
}
});
} else if (direction === 'previous') {
this.hasPreviousStep$.pipe(take(1)).subscribe((hasPrevious: boolean) => {
if (hasPrevious) {
// Navigate to the previous step using the Angular Router
// Example: this.router.navigate(['/questionnaire', 'previous-step']);
}
});
}
});
} |
#!/bin/bash
set -ev
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
sudo apt-get -y -o Dpkg::Options::="--force-confnew" install docker-ce
# hack to address problem with using DOCKER_BUILDKIT=1, inspired by:
# * https://github.com/rootless-containers/usernetes/blob/master/.travis.yml
#
# links discussing the issue:
# * https://github.com/moby/buildkit/issues/606#issuecomment-453959632
# * https://travis-ci.community/t/docker-builds-are-broken-if-buildkit-is-used-docker-buildkit-1/2994
# * https://github.com/moby/moby/issues/39120
sudo docker --version
sudo cat /etc/docker/daemon.json
sudo rm -f /etc/docker/daemon.json
sudo systemctl restart docker
|
#!/bin/bash
###############
### For Mac ###
###############
if [ "$(uname)" = "Darwin" ]
then
DIR=$(pwd)
cp config/database.yml.example config/database.yml
cp config/secrets.yml.example config/secrets.yml
NODE_VERSION=8.4.0
NPM_VERSION=5.4.2
echo 'Install Third-party Javascript Libraries for Mac OS X platform'
# Checking Homebrew
which -s brew
if [[ $? != 0 ]] ; then
# Install Homebrew
/usr/bin/ruby -e "$(curl -fsSL https://raw.github.com/gist/323731)"
echo "Brew was not installed"
else
echo "Brew already there"
brew update
fi
# Checking Git
echo "Checking for Git"
which -s git || brew install git
# Checking Node
echo "Checking for Node"
node --version
if [[ $? != 0 ]] ; then
# Install Node
cd `brew --prefix`
$(brew versions node | grep ${NODE_VERSION} | cut -c 16- -)
brew install node
# Reset Homebrew formulae versions
git reset HEAD `brew --repository` && git checkout -- `brew --repository`
else
echo "NodeJS $(node -v) is already installed"
fi
cd $DIR
# Checking NPM
echo "Checking for NPM"
npm --version
if [[ $? != 0 ]] ; then
echo "Downloading npm"
git clone git://github.com/isaacs/npm.git && cd npm
git checkout v${NPM_VERSION}
make install
else
echo "NPM $(npm --version) is already installed"
echo "Looking for an update"
sudo npm i -g npm
fi
sudo npm install -g bower && bower install
#################
### For Linux ###
#################
elif [ "$(expr substr $(uname -s) 1 5)" = "Linux" ]
then
cp config/database.yml.example config/database.yml
cp config/secrets.yml.example config/secrets.yml
echo 'Install Third-party Javascript Libraries for Linux Platform'
sudo apt-get update
sudo apt-get install build-essential libssl-dev
sudo apt-get update ca-certificates
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs && sudo apt-get install -y npm && sudo ln -s /usr/bin/nodejs /usr/bin/node
# Checking NPM
echo "Checking for NPM"
npm --version
if [ $? != 0 ]
then
echo "Installing NPM"
sudo apt-get install -y npm
else
echo "NPM was already installed"
echo "Looking for an update"
sudo npm i -g npm
fi
# Installing Bower
sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config
sudo npm install -g bower
bower install
sudo apt-get autoremove
######################
### For Windows :( ###
######################
elif [ -n "$COMSPEC" -a -x "$COMSPEC" ]
then
echo $0: this script does not support Windows \:\(
fi
|
import numpy as np
from sklearn.svm import SVC
# define data
data = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
# define labels
labels = np.array([0, 1, 1, 0])
# ML model
model = SVC(kernel = 'linear', C = 1)
# fit the model
model.fit(data, labels)
# make prediction
prediction = model.predict([[2, 5, 7]])
print(prediction) |
#!/bin/bash
cd ..
premake4 clean >/dev/null 2>&1
premake4 gmake linux >/dev/null 2>&1
#param 1: test_name
#only outputs a message when compilation passes
function run_test()
{
if make $1 >/dev/null 2>&1; then
echo "[failed] $1"
#else
# echo "[pass] $1"
fi
}
run_test cpp_acquire_int
run_test cpp_acquire_ptr_int
run_test cpp_acquire_stub
run_test cpp_acquire_ref_stub
run_test lua_acquire_int
run_test lua_acquire_ref_int
run_test lua_acquire_ptr_int
run_test lua_acquire_ref_ptr_int
run_test lua_acquire_ptr_const_int
run_test lua_acquire_const_int
run_test lua_acquire_ref_const_int
run_test lua_acquire_const_ptr_const_int
run_test lua_acquire_ref_const_ptr_const_int
run_test lua_acquire_stub
run_test lua_acquire_ref_stub
run_test cpp_in_int
run_test cpp_in_ptr_int
run_test cpp_in_ref_int
run_test cpp_in_stub
run_test cpp_in_ref_stub
run_test cpp_in_ref_const_stub
run_test in_out_int
run_test in_out_stub
run_test lua_out_int
run_test lua_out_ref_int
run_test lua_out_ptr_int
run_test lua_out_ref_stub
run_test lua_out_ptr_stub
run_test lua_out_ref_const_stub
run_test lua_out_ref_ptr_const_stub
run_test lua_return_int
run_test lua_return_ptr_int
run_test lua_return_stub
run_test lua_return_const_stub
run_test lua_return_ref_stub
run_test lua_return_ref_const_stub
run_test out_int
run_test out_stub
run_test maybe_null_int
run_test maybe_null_stub
run_test maybe_null_ref_stub
run_test maybe_null_ref_const_stub
run_test maybe_null_ref_ptr_stub
run_test maybe_null_ref_const_ptr_stub
run_test maybe_null_ref_const_ptr_const_stub
run_test maybe_null_ref_ptr_const_stub
run_test maybe_null_shared
run_test maybe_null_shared_const
run_test lua_maybe_null_int
run_test lua_maybe_null_stub
run_test lua_maybe_null_ref_stub
run_test lua_maybe_null_ref_const_stub
run_test lua_maybe_null_ref_ptr_stub
run_test lua_maybe_null_ref_const_ptr_stub
run_test lua_maybe_null_ref_const_ptr_const_stub
run_test lua_maybe_null_ref_ptr_const_stub
run_test shared_return_int
run_test shared_return_ptr_int
run_test shared_return_stub
run_test shared_return_ref_stub
run_test shared_return_ref_const_stub
run_test shared_return_ptr_shared_ptr
premake4 clean >/dev/null 2>&1
cd build_scripts
|
import random, time
geral = dict()
count = 1
geral1 = dict()
list = list()
for c in range(4):
n1 = random.randint(1, 6)
geral[f'Jogador{c + 1}'] = n1
time.sleep(0.5)
print('Dados jogados...')
for f, v in geral.items():
time.sleep(0.5)
print(f' O {f} jogou {v}...')
for p in geral.values():
list.append(p)
list.sort()
for c in range(6):
for k, v in geral.items():
if v == (max(list) - c):
geral1[f'{k}'] = f'{v}'
time.sleep(0.5)
print('Ranking dos jogadores:')
for k, v in geral1.items():
time.sleep(0.5)
print(f' {count}°Lugar: {k} com o número {v}.')
count += 1
|
<gh_stars>0
var iohook = require("iohook");
var request = require("request");
var path = require("path");
var stockfish = require("stockfish");
var engine = stockfish(path.join(__dirname, "./node_modules/stockfish/src/stockfish.wasm"));
var selenium = require("selenium-webdriver");
var Builder = selenium.Builder;
var By = selenium.By;
var Key = selenium.Key;
var until = selenium.until;
var Condition = selenium.Condition;
var driver = new Builder().forBrowser("chrome").build();
driver.get("http://www.lichess.org/");
function startBot() {
function yourTurnHandler(message) {
if(message === "success") {
playMove();
driver.wait(
new Condition("Timedout while waiting for their turn.", function(driver) {
return driver.findElements(By.css(".clock_top")).then(function(elements) {
return elements[0].getAttribute("class").then(function(classes) {
return classes.indexOf("running") >= 0;
});
});
}),
60000
).catch(function(error) {
console.log(error);
}).then(function(success) {
if(success) {
yourTurn(yourTurnHandler);
}
});
} else if (message === "Not in game") {
return;
}
}
yourTurn(yourTurnHandler);
}
function yourTurn(callback) {
// waits for 1 min
driver.wait(
new Condition("Timed out while waiting for our turn.", function(driver) {
return driver.findElements(By.css(".clock_bottom")).then(function(elements) {
if(elements.length === 0) {
console.log("Not in a game.");
return "Not in game";
}
return elements[0].getAttribute("class").then(function(classes) {
if(classes.indexOf("running") >= 0) {
return "success"
}
});
});
}),
60000
).catch(function(error) {
console.log(error);
}).then(callback);
}
function playMove() {
console.log("Finding best move.");
getBestMove(function(bestMove) {
driver.executeScript(function(bestMove) {
window.lichess.socket.send("move", {
u: bestMove,
b: 1
});
}, bestMove);
});
}
function getBestMove(callback) {
var bestMove;
getFen(function(fen) {
engine.postMessage("position fen " + fen);
engine.postMessage("go movetime 100");
});
engine.onmessage = function(message) {
if(message.indexOf("bestmove") === 0) {
bestMove = message.split(" ")[1];
callback(bestMove);
}
};
}
function getFen(callback) {
driver.getCurrentUrl().then(function(url) {
request.get(url, {}, function(err, res, body) {
var split1 = body.split('"fen":"');
var fen = split1[split1.length-1].split('"}')[0];
callback(fen);
});
});
}
// Listens for alt + s
var id = iohook.registerShortcut([56, 31], function(keys) {
startBot();
});
iohook.start(); |
#!/bin/sh
HOST="172.16.238.15"
USER="$1"
PASS="$2"
FILE="$3"
#Choose random file
#FILE=$(ls /dataToShare/ | sort -R | tail -1)
echo "CONNECTING ..."
ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASS
pwd
ls
bin
verbose
put /dataToShare/$FILE newfile
get newfile
quit
END_SCRIPT
exit 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.