text
stringlengths 8
6.88M
|
|---|
#ifndef DECK56_HPP
#define DECK56_HPP
#include "Deck52.hpp"
class Deck56: public Deck52{
public :
Deck56();
};
#endif
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void sort(int*a, int b)
{
int j, c;
int i_min;
for (int i = 0; i<b-1;i++) // swap (a[i], a[i_min])
{
i_min = i;
for (j = i + 1; j < b; j++)
if (a[i_min] > a[j])
i_min = j;
c = a[i];
a[i] = a[i_min];
a[i_min] = c;
}
}
int main()
{
srand(time(NULL));
int n;
int a[100];
cin >> n;
for (int i = 0; i < n; i++)
{
a[i] = rand() % 51;
cout << a[i] << " ";
}
sort(a, n);
cout << endl;
for (int i = 0; i < n; i++)
cout << a[i] << " " ;
}
|
/*
Copyright (c) 2015, Vlad Mesco
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.
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.
*/
#include "blocks_interpreter.h"
#include "notes_interpreter.h"
#include "parser_types.h"
#include "log.h"
#include <cstdio>
#include <ios>
#include <iostream>
#include <fstream>
static struct {
std::string outfile;
std::string infile;
} options = {
"-",
"-"
};
extern bool GetNextToken(std::istream&, int&, char*&);
extern void* ParseAlloc(void* (*)(size_t));
extern void Parse(void*, int, char*, struct PpFile*);
extern void ParseFree(void*, void (*)(void*));
extern void ParseTrace(FILE*, char*);
static void PpValue_free(PpValue v)
{
switch(v.type) {
case PpValue::PpSTRING:
free(v.str);
break;
case PpValue::PpLIST:
{
PpValueList* p = v.list;
while(p) {
PpValue_free(p->value);
PpValueList* prev = p;
p = p->next;
free(prev);
}
}
break;
default:
break;
}
}
static void PpParamList_free(PpParamList* head)
{
for(PpParamList* pp = head; pp;) {
PpParam param = pp->value;
free(param.key);
PpValue_free(param.value);
auto prev = pp;
pp = pp->next;
free(prev);
}
}
static void PpFile_free(PpFile f)
{
for(PpInstanceList* p = f.instances; p;) {
PpInstance instance = p->value;
free(instance.name);
free(instance.type);
PpParamList_free(instance.params);
auto prev = p;
p = p->next;
free(prev);
}
for(PpStaffList* p = f.staves; p;) {
PpStaff staff = p->value;
free(staff.name);
PpParamList_free(staff.params);
auto prev = p;
p = p->next;
free(prev);
}
}
std::tuple<std::function<float(void)>, size_t> sketch(std::istream& fin)
{
void* pParser;
char* sToken;
int hTokenId;
PpFile fileHead;
pParser = ParseAlloc(malloc);
if(LOGE(LOG_PARSER)) {
ParseTrace(stderr, "parser.y: ");
}
while(GetNextToken(fin, hTokenId, sToken)) {
Parse(pParser, hTokenId, sToken, &fileHead);
}
Parse(pParser, 0, sToken, &fileHead);
ParseFree(pParser, free);
LookupMap_t map;
std::vector<DelayedLookup_fn> delayedLookups;
for(PpInstanceList* p = fileHead.instances; p; p = p->next) {
PpInstance instance = p->value;
std::remove_reference<decltype(GetInterpreter(instance.type, instance.name))>::type interp;
try {
interp = GetInterpreter(instance.type, (instance.name) ? instance.name : "OUTPUT");
} catch(std::exception e) {
fprintf(stderr, "Exception when instantiating %s: %s\n", instance.name, e.what());
continue;
}
for(PpParamList* pparam = instance.params; pparam; pparam = pparam->next) {
PpParam param = pparam->value;
DelayedLookup_fn f;
try {
f = interp->AcceptParameter(param.key, param.value);
} catch(std::exception e) {
fprintf(stderr, "Exception when processing parameter %s for instance %s: %s\n", param.key, instance.name, e.what());
continue;
}
if(f) delayedLookups.push_back(f);
}
map.data_.push_back(interp);
}
for(auto&& f : delayedLookups) f(map);
size_t maxDuration = 0;
for(PpStaffList* p = fileHead.staves; p; p = p->next) {
PpStaff staff = p->value;
std::string type = (staff.type == 'N') ? "NOTES" : "PCM";
std::remove_reference<decltype(GetNotesInterpreter(type, staff.name))>::type interp;
try {
interp = GetNotesInterpreter(type, staff.name);
} catch(std::exception e) {
fprintf(stderr, "Exception caught while instantiating interpreter for %s: %s\n", staff.name, e.what());
continue;
}
for(PpParamList* pparam = staff.params; pparam; pparam = pparam->next) {
PpParam param = pparam->value;
try {
interp->AcceptParameter(param.key, param.value);
} catch(std::exception e) {
fprintf(stderr, "Exception caught while processing parameter %s for staff %s: %s\n", param.key, staff.name, e.what());
continue;
}
}
try {
interp->Fill(map);
} catch(std::exception e) {
fprintf(stderr, "Exception caught while filling %s: %s\n", staff.name, e.what());
continue;
}
maxDuration = std::max(maxDuration, interp->Duration());
}
PpFile_free(fileHead);
std::vector<std::shared_ptr<ABlock>> blocks;
for(auto&& block : map) {
blocks.push_back(block->Block());
}
auto&& found = std::find_if(blocks.begin(), blocks.end(),
[](decltype(blocks)::value_type v) -> bool {
auto p = std::dynamic_pointer_cast<Output>(v);
return (bool)p;
});
if(found == blocks.end()) {
throw std::runtime_error("Output block not defined.");
}
auto&& out = *found;
#if 0
auto cycle = [out, blocks]() mutable -> float {
for(auto&& b : blocks) b->Tick1();
for(auto&& b : blocks) b->Tick2();
for(auto&& b : blocks) b->Tick3();
double dvalue = out->Value(); // -1..1
return dvalue;
};
#else
auto cycle = [out, map]() mutable -> float {
LOGF(LOG_MAINLOOP, "BEGIN CYCLE");
for(auto&& kv : map.data_)
{
LOGF(LOG_MAINLOOP, "block %s.Tick1()", kv->Name().c_str());
kv->Block()->Tick1();
}
for(auto&& kv : map.data_)
{
LOGF(LOG_MAINLOOP, "block %s.Tick2()", kv->Name().c_str());
kv->Block()->Tick2();
}
for(auto&& kv : map.data_)
{
LOGF(LOG_MAINLOOP, "block %s.Tick3()", kv->Name().c_str());
kv->Block()->Tick3();
}
double dvalue = out->Value(); // -1..1
LOGF(LOG_MAINLOOP, "END CYCLE");
return dvalue;
};
#endif
return std::make_tuple(cycle, maxDuration);
//for(size_t i = 0; i < maxDuration; ++i) {
// doStuffWithSample(cycle());
//}
}
#ifdef _MSC_VER
__declspec(noreturn)
#endif
static void usage()
#ifdef __GNUC__
__attribute__((noreturn))
#endif
{
printf("jakmuse [-i infile] [-w out.wav]\n");
exit(1);
}
static void processArgs(int& argc, char* argv[])
{
for(int i = 1; i < argc; ++i) {
std::string thing = argv[i];
if(thing.compare(0, 2, "-w") == 0) {
std::string tenta = thing.substr(2);
if(tenta.size()) {
options.outfile = tenta;
} else {
if(i == argc) usage();
++i;
thing.assign(argv[i]);
options.outfile = thing;
}
} else if(thing.compare("--crash") == 0) {
throw 1;
} else if(thing.compare("-h") == 0) {
usage();
} else if(thing.compare(0, 2, "-i") == 0) {
std::string tenta = thing.substr(2);
if(tenta.empty()) {
if(i == argc) usage();
++i;
thing.assign(argv[i]);
options.infile = thing;
} else {
options.infile = tenta;
}
}
}
}
int main(int argc, char* argv[])
{
#ifndef VERSION
# define VERSION unbekannt
#endif
#define QUOTE_HELPER(X) #X
#define QUOTE(X) QUOTE_HELPER(X)
printf("jakmuse v3.%s\n", QUOTE(VERSION));
printf("Copyright (C) 2015 Vlad Mesco\n");
processArgs(argc, argv);
try {
std::istream* fin = nullptr;
if(!options.infile.empty() && options.infile.compare("-") != 0) {
fin = new std::fstream(options.infile, std::ios::in);
fin->exceptions(std::ios::failbit|std::ios::badbit);
}
auto&& op = sketch(fin ? *fin : std::cin);
if(fin) delete fin;
if(options.outfile.empty() || options.outfile.compare("-") == 0) {
throw std::invalid_argument("Not implemented: stdout output");
} else {
std::vector<float> wav;
for(size_t i = 0; i < std::get<1>(op); ++i) {
wav.push_back(std::get<0>(op)());
}
extern void wav_write_file(std::string const&, std::vector<float> const&, unsigned);
wav_write_file(options.outfile, wav, 44100);
}
} catch(std::exception e) {
printf("Caught exception: %s\n", e.what());
}
// END TEST CODE
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2005 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef CUSTOMIZE_HEADER_DIALOG_H
#define CUSTOMIZE_HEADER_DIALOG_H
#ifdef M2_SUPPORT
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/desktop_util/treemodel/simpletreemodel.h"
#include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeView.h"
#include "modules/widgets/OpEdit.h"
class HeaderDisplay;
/***********************************************************************************
**
** CustomizeHeaderDialog
**
***********************************************************************************/
class CustomizeHeaderDialog : public Dialog, public DialogListener
{
public:
CustomizeHeaderDialog();
virtual ~CustomizeHeaderDialog();
void Init(DesktopWindow* parent_window);
virtual const char* GetWindowName() {return "Customize Header Dialog";}
virtual void OnInit();
virtual UINT32 OnOk();
virtual void OnCancel();
virtual void OnClick(OpWidget *widget, UINT32 id);
virtual void OnOk(Dialog* dialog, UINT32 result);
virtual void OnChange(OpWidget *widget, BOOL changed_by_mouse = FALSE);
private:
SimpleTreeModel m_header_model;
OpTreeView* m_tree_view;
OpButton* m_up_button;
OpButton* m_down_button;
OpButton* m_add_button;
OpButton* m_delete_button;
HeaderDisplay* m_display;
OpINT32Vector m_moves;
};
/***********************************************************************************
**
** AddCustomHeaderDialog
**
***********************************************************************************/
class AddCustomHeaderDialog : public Dialog
{
public:
AddCustomHeaderDialog();
virtual ~AddCustomHeaderDialog();
void Init(DesktopWindow* parent_window);
virtual const char* GetWindowName() {return "Add Custom Header Dialog";}
virtual void OnInit();
virtual UINT32 OnOk();
virtual void OnCancel();
OP_STATUS GetHeaderName(OpString &header_name) { return m_edit->GetText(header_name) ;}
private:
OpEdit* m_edit;
};
#endif //M2_SUPPORT
#endif //CUSTOMIZE_HEADER_DIALOG_H
|
#ifndef __FOOBAR_VOTING_MACHINE_H__
#define __FOOBAR_VOTING_MACHINE_H__
#include <string>
#include <vector>
#include <unordered_map>
#include <utility>
#include "types.h"
namespace foobar
{
class voting_machine
{
public:
void add_vote(const std::string &voter, const std::string &choice);
void add_delegation(const std::string &voter, const std::string &delegate);
std::vector<vote_count> get_votes() const;
private:
typedef std::vector<const std::string *> key_vector;
enum instruction_type
{
VOTE,
DELEGATION,
};
struct instruction
{
instruction_type type;
size_type voter;
size_type votee;
};
internal::ptr_vector voters;
internal::ptr_vector choices;
internal::lookup_map voters_map;
internal::lookup_map choices_map;
std::vector<instruction> instructions;
};
} // namespace foobar
#endif
|
/*
https://www.acmicpc.net/problem/5622
*/
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
char str[16] = { 0, };
scanf("%s", str);
int strLength = strlen(str);
int total = 0;
for (int i = 0; i < strLength; i++)
{
char ch = str[i];
switch (ch)
{
case 65: case 66: case 67:
total += 3;
break;
case 68: case 69: case 70:
total += 4;
break;
case 71: case 72: case 73:
total += 5;
break;
case 74: case 75: case 76:
total += 6;
break;
case 77: case 78: case 79:
total += 7;
break;
case 80: case 81: case 82: case 83:
total += 8;
break;
case 84: case 85: case 86:
total += 9;
break;
case 87: case 88: case 89: case 90:
total += 10;
break;
default:
break;
}
}
printf("%d", total);
return 0;
}
|
#ifndef INCLUDE
#define INCLUDE
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <regex>
#include <unordered_map>
#include <cassert>
#include <cstdarg>
#include <cstring>
using std::cout;
using std::cin;
using std::flush;
using std::vector;
using std::string;
using std::istream;
using std::ostream;
using std::ifstream;
using std::ofstream;
using std::regex;
using std::smatch;
using std::unordered_map;
using std::to_string;
using std::find;
using std::not1;
using std::ptr_fun;
using std::bind;
#endif // INCLUDE
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int n, as[100000];
while(cin>>n)
{
int i, chest=0, biceps=0, backs=0;
for(i=1; i<=n; i++)cin>>as[i];
int c=1, bi=0, ba=0;
i=1;
while(i<=n)
{
if(c==1)
{
chest+=as[i];
c=0, bi=1, i++;
}
else if(bi==1)
{
biceps+=as[i];
bi=0, ba=1, i++;
}
else if(ba==1)
{
backs+=as[i];
ba=0, c=1, i++;
}
}
if(chest>biceps && chest>backs)printf("chest\n");
else if(biceps>chest && biceps>backs)printf("biceps\n");
else if(backs>chest && backs>biceps)printf("back\n");
}
return 0;
}
|
#include <iostream>
using namespace std;
/*
Problema 4.1
Complejidad de tiempo: O(N)
*/
int main() {
int capacitores;
cin >> capacitores;
float valorMaximo = 0;
int indiceMaximo = 0;
for (int i = 0; i < capacitores; i++) {
int capacitancia, voltaje, corriente;
cin >> capacitancia >> voltaje >> corriente;
float valor = capacitancia * voltaje * voltaje / 2 + voltaje * corriente;
if (valor > valorMaximo) {
valorMaximo = valor;
indiceMaximo = i;
}
}
cout << valorMaximo << " " << (indiceMaximo + 1);
}
|
#ifndef NET_INCLUDE_H
#define NET_INCLUDE_H
#include <string>
#include <vector>
using namespace std;
typedef vector<string> VSTRING;
typedef struct
{
int nRow;
int nCol;
bool bValid;
}POS;
class net
{
public:
net(string s[], int n);
~net();
bool in_net(string &s);
private:
POS get_first(POS &start, string &s, int level = 0);
POS get_next(POS &start, string &s, int level);
bool bEqual(int nRow, int nCol, string &s, int level);
void clear(int level);
void printused();
int rowSize;
int colSize;
int **bUsed;
VSTRING alpha_v;
};
#endif
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
//
// You are writing a simple text editor that supports only
// the following two commands:
//
// "type c" where c is a character: Append character c to the
// end of the current text.
// "undo t" where t is an integer: Undo all operations that
// were performed in the previous t seconds in reverse order.
//
//
//
// All quotes are for clarity only. The text in the editor
// is initially empty.
//
//
// For example, consider the following sequence of commands:
//
//
// Second 1: type a
// Second 2: type b
// Second 3: type c
// Second 5: undo 3
//
//
// At the end of second 3, the text is "abc". At second 5,
// all commands performed in the previous 3 seconds are
// undone in reverse order. This means 'c' is removed, and
// then 'b' is removed. The text becomes just "a".
//
//
// Note that "undo" commands can also be undone. For example:
//
//
// Second 1: type a
// Second 2: type b
// Second 3: undo 2
// Second 4: undo 2
//
//
// After second 2, the text is "ab". After second 3,
// everything is undone, and the text becomes empty. At
// second 4, the previous "undo" is undone, so the text
// becomes "ab" again. Then, the "type b" is also undone and
// the text becomes just "a".
//
//
// You are given a vector <string> commands and a vector
// <int> time. Each element of commands is a single command,
// and commands[i] is performed at time[i]. The commands are
// given in chronological order. Return the text after all
// the commands are executed.
//
//
// DEFINITION
// Class:Undo
// Method:getText
// Parameters:vector <string>, vector <int>
// Returns:string
// Method signature:string getText(vector <string> commands,
// vector <int> time)
//
//
// CONSTRAINTS
// -commands will contain between 1 and 50 elements, inclusive.
// -Each element of commands will be either "type c" where c
// is a lowercase letter ('a'-'z') or "undo t" where t is an
// integer between 1 and 10^9, inclusive, with no leading
// zeroes (quotes for clarity only).
// -time will contain the same number of elements as commands.
// -Each element of time will be between 1 and 10^9, inclusive.
// -The elements of time will be in strictly ascending order.
//
//
// EXAMPLES
//
// 0)
// {"type a", "type b", "type c", "undo 3"}
// {1, 2, 3, 5}
//
// Returns: "a"
//
// The first example from the problem statement.
//
// 1)
// {"type a", "type b", "undo 2", "undo 2"}
// {1,2,3,4}
//
// Returns: "a"
//
// The second example from the problem statement.
//
// 2)
// {"type a", "undo 1", "undo 1"}
// {1,2,3}
//
// Returns: "a"
//
//
//
// 3)
// {"type a", "type b", "type c", "undo 10"}
// {1, 2, 3, 1000}
//
// Returns: "abc"
//
// Note that "undo" can undo nothing if it is too late.
//
// 4)
// {"undo 1"}
// {1}
//
// Returns: ""
//
//
//
// END CUT HERE
#line 120 "Undo.cc"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
vector<VS> c;
VI t;
template<class T>
T fromString(string inp)
{
stringstream s(inp);
T a;
s>>a;
return a;
}
VS toks(string inp,string delim)
{
char *ch = strdup(inp.c_str());
char *ptr = strtok(ch,delim.c_str());
VS ret;
while (ptr != NULL){
ret.push_back(ptr);
ptr = strtok(NULL,delim.c_str());
}
free(ch);
return ret;
}
class Undo
{
public:
void Und(int pos, string &ret) {
if (c[pos][0] == "type") {
b[pos] = 0;
} else {
int back = fromString<int>(c[pos][1]);
Do(pos, t[pos] - back, t[pos] - 1, ret);
}
}
void Do(int pos, int st, int en, string &ret) {
int cu = pos - 1;
while (cu >= 0 && t[cu] >= st) {
Do(cu, ret);
--cu;
}
}
void Und(int pos, int st, int en, string &ret) {
int cu = pos - 1;
while (cu >= 0 && t[cu] >= st) {
Und(cu, ret);
--cu;
}
}
void Do(int pos, string &ret) {
if (c[pos][0] == "type") {
b[pos] = 1;
} else {
int back = fromString<int>(c[pos][1]);
Und(pos, t[pos] - back, t[pos] - 1, ret);
}
}
VI b;
string getText(vector <string> co, vector <int> ti)
{
string ret;
t = ti;
c.clear();
c.resize(co.size());
fi(co.size()) {
c[i] = toks(co[i], " ");
}
b.clear();
b.resize(c.size(), 0);
fi(c.size()) {
Do(i, ret);
}
fi(c.size()) {
if (c[i][0] == "type" && b[i]) {
ret += c[i][1];
}
}
return ret;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"type a", "type b", "type c", "undo 3"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 2, 3, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "a"; verify_case(0, Arg2, getText(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"type a", "type b", "undo 2", "undo 2"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,3,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "a"; verify_case(1, Arg2, getText(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"type a", "undo 1", "undo 1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "a"; verify_case(2, Arg2, getText(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {"type a", "type b", "type c", "undo 10"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 2, 3, 1000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "abc"; verify_case(3, Arg2, getText(Arg0, Arg1)); }
void test_case_4() { string Arr0[] = {"undo 1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = ""; verify_case(4, Arg2, getText(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Undo ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include <string>
#include <iostream>
#include <numeric>
#include <vector>
double Range(double start, int end, double interest);
int main() {
double amount = 0;
std::cout << "How much to invest : ";
std::cin >> amount;
double interest = 0;
std::cout << "Interest rate : ";
std::cin >> interest;
std::cout << "After 10 years you'll have : " << Range(amount, 10, interest) << "\n";
return 0;
}
double Range(double start, int end, double interest) {
double result = start;
for (int i = 1; i <= end; i++) {
double factor = 1 + interest / 100;
result = result * factor;
}
return result;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#if defined(_PLUGIN_SUPPORT_) && !defined(NS4P_COMPONENT_PLUGINS)
#include "platforms/windows/WindowsPluginDetector.h"
#include "modules/pi/system/OpFolderLister.h"
#include "modules/prefs/prefsmanager/collections/pc_app.h"
#include "modules/util/opfile/opfile.h"
#include "modules/util/gen_str.h"
#include "platforms/windows/windows_ui/registry.h"
#include "platforms/windows/windows_ui/winshell.h"
#include "platforms/windows/win_handy.h"
#include "adjunct/desktop_util/filelogger/desktopfilelogger.h"
#include "platforms/windows_common/utils/fileinfo.h"
#define MAX_LEN 1024
OP_STATUS WindowsPluginDetector::ReadPlugins(const OpStringC& suggested_plugin_paths)
{
OP_PROFILE_METHOD("Read plugins");
OpString paths;
RETURN_IF_ERROR(paths.Set(suggested_plugin_paths.IsEmpty() ?
g_pcapp->GetStringPref(PrefsCollectionApp::PluginPath) : suggested_plugin_paths));
int pos = 0;
BOOL done = FALSE;
OP_STATUS stat = OpStatus::OK;
while (TRUE)
{
uni_char *dir = MyUniStrTok(const_cast<uni_char*>(paths.CStr()), UNI_L("\n\t;"), pos, done);
if (done)
break;
if (!dir || !*dir)
continue;
OpFolderLister *folder_lister = OpFile::GetFolderLister(OPFILE_ABSOLUTE_FOLDER, UNI_L("*.dll"), dir);
if (!folder_lister)
continue;
while (folder_lister->Next())
{
const uni_char* file_path = folder_lister->GetFullPath();
if (file_path && !folder_lister->IsFolder() && !g_pcapp->IsPluginToBeIgnored(file_path))
stat = InsertPluginPath(file_path);
}
OP_DELETE(folder_lister);
}
// check registry for installed plugins
if (!m_read_from_registry)
{
OP_STATUS stat2 = ReadFromRegistry();
if (OpStatus::IsError(stat2))
stat = stat2;
RETURN_IF_ERROR(SubmitPlugins());
}
return stat;
}
OP_STATUS WindowsPluginDetector::CheckReplacePlugin(PluginType type, BOOL& ignore, const OpStringC& checkedFileDescription)
{
OP_STATUS stat = OpStatus::OK;
ignore = FALSE;
OpString newfname;
uni_char szRegPath[_MAX_PATH]; /* ARRAY OK 2007-01-26 peter */
DWORD dwSize = ARRAY_SIZE(szRegPath);
switch (type)
{
case ACROBAT:
{
m_acrobat_installed = TRUE;
// Use the registry path and get the installed Adobe plugin path
static const uni_char szKeyName[] = UNI_L("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcroRd32.exe");
static const uni_char alt_szKeyName[] = UNI_L("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Acrobat.exe");
if (OpRegReadStrValue(HKEY_LOCAL_MACHINE, szKeyName, UNI_L("Path"), szRegPath, &dwSize) == ERROR_SUCCESS ||
OpRegReadStrValue(HKEY_LOCAL_MACHINE, alt_szKeyName, UNI_L("Path"), szRegPath, &dwSize) == ERROR_SUCCESS)
{
RETURN_IF_ERROR(StrAppendSubDir(szRegPath, UNI_L("Browser\\nppdf32.dll"), newfname));
RETURN_IF_ERROR(InsertPluginPath(newfname, &ignore, checkedFileDescription, TRUE));
}
else
{ // ignore all Adobe plugins if AcroRd32.exe or Acrobat.exe is not in registry!
ignore = TRUE;
}
break;
}
case SVG:
{
m_svg_installed = TRUE;
HKEY hkey;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,UNI_L("SOFTWARE\\Adobe\\Adobe SVG Viewer"), 0, KEY_READ, &hkey) == ERROR_SUCCESS)
{
const DWORD key_name_size = 32;
uni_char key_name[key_name_size]; /* ARRAY OK 2007-01-26 peter */
DWORD key_name_len;
LONG ret = ERROR_SUCCESS;
DWORD index = 0;
while (OpStatus::IsSuccess(stat) && ret != ERROR_NO_MORE_ITEMS)
{
key_name_len = key_name_size;
ret = RegEnumKeyEx(hkey, index++, key_name, &key_name_len, NULL, NULL, NULL, NULL);
if (ret == ERROR_SUCCESS)
{
if ((OpRegReadStrValue(hkey, key_name, UNI_L("Path"), szRegPath, &dwSize) == ERROR_SUCCESS))
stat = newfname.Set(szRegPath);
}
}
RegCloseKey(hkey);
if (OpStatus::IsSuccess(stat) && newfname.HasContent())
RETURN_IF_ERROR(InsertPluginPath(newfname, &ignore, checkedFileDescription, TRUE));
}
else
{ // ignore any Adobe SVG plugins if Adobe SVG is not in registry!
ignore = TRUE;
}
break;
}
case QT:
{
// QuickTime plugin files in Opera's plugin path are ignored
// Use the registry path and get the installed QuickTime plugin path, if any, and expand Opera's plugin path
m_qt_installed = TRUE;
static const uni_char szKeyName[] = UNI_L("SOFTWARE\\Apple Computer, Inc.\\QuickTime");
if (OpRegReadStrValue(HKEY_LOCAL_MACHINE, szKeyName, UNI_L("InstallDir"), szRegPath, &dwSize) == ERROR_SUCCESS)
{
RETURN_IF_ERROR(StrAppendSubDir(szRegPath, UNI_L("Plugins"), newfname));
RETURN_IF_ERROR(ReadPlugins(newfname.CStr())); // plugin path is expanded with QuickTime plugin path
}
else
{
ignore = TRUE;
}
break;
}
case WMP:
{
m_wmp_detection_done = TRUE;
OpFile path;
OpString path_string;
BOOL exists = FALSE;
if(IsSystemWin2000orXP())
{
DWORD drives, drive;
if ((drives = GetLogicalDrives()) == 0)
{
ignore = TRUE;
break;
}
uni_char drive_path[4] = UNI_L("*:\\");
for (drive = 0; drive < 26; drive++)
{
if (drives & (1 << drive))
{
drive_path[0] = 'A' + drive;
if(GetDriveType(drive_path) == DRIVE_FIXED)
{
path_string.Set(drive_path);
path_string.Append(UNI_L("PFiles\\plugins\\"));
RETURN_IF_ERROR(path.Construct(path_string.CStr()));
if (OpStatus::IsSuccess(path.Exists(exists)) && exists)
break;
}
}
}
if(exists)
{
RETURN_IF_ERROR(ReadPlugins(path_string.CStr()));
}
else
{
ignore = TRUE;
}
}
else
{
ignore = TRUE;
}
break;
}
default:
ignore = TRUE;
break;
}
return stat;
}
OP_STATUS WindowsPluginDetector::InsertPluginPath(const OpStringC& plugin_path, BOOL* was_different, const OpStringC& checkedFileDescription, BOOL is_replacement)
{
// check if this is a plugin for my particular CPU architecture (Win32 or x64)
if(!IsPluginForArchitecture(plugin_path))
return OpStatus::OK;
WindowsCommonUtils::FileInformation fileinfo;
// We want to ignore errors. That will ignore just this plugin and not all of them.
if (OpStatus::IsError(fileinfo.Construct(plugin_path)))
return OpStatus::OK;
// Do this the American english translation be default.
// Keep track of the string length for easy updating.
// 040904E4 represents the language ID and the four
// least significant digits represent the codepage for
// which the data is formatted. The language ID is
// composed of two parts: the low ten bits represent
// the major language and the high six bits represent
// the sub language.
fileinfo.SetLanguageId(UNI_L("040904E4"));
UniString uni_productName;
UniString uni_fileExtents;
UniString uni_mimeType;
UniString uni_fileOpenName;
UniString uni_fileDescription;
UniString uni_version;
// First check. If no mime type, not a plugin.
if (OpStatus::IsError(fileinfo.GetInfoItem(UNI_L("MIMEType"), uni_mimeType)))
return OpStatus::OK;
fileinfo.GetInfoItem(UNI_L("ProductName"), uni_productName);
fileinfo.GetInfoItem(UNI_L("FileExtents"), uni_fileExtents);
fileinfo.GetInfoItem(UNI_L("FileOpenName"), uni_fileOpenName);
fileinfo.GetInfoItem(UNI_L("FileDescription"), uni_fileDescription);
fileinfo.GetInfoItem(UNI_L("FileVersion"), uni_version);
// Stupid hacks to get OpStrings from UniStrings. Should be gone once DSK-342766 is integrated
const uni_char* ptr;
OpString productName;
RETURN_IF_ERROR(uni_productName.CreatePtr(&ptr, TRUE));
RETURN_IF_ERROR(productName.Set(ptr));
OpString fileExtents;
RETURN_IF_ERROR(uni_fileExtents.CreatePtr(&ptr, TRUE));
RETURN_IF_ERROR(fileExtents.Set(ptr));
OpString mimeType;
RETURN_IF_ERROR(uni_mimeType.CreatePtr(&ptr, TRUE));
RETURN_IF_ERROR(mimeType.Set(ptr));
OpString fileOpenName;
RETURN_IF_ERROR(uni_fileOpenName.CreatePtr(&ptr, TRUE));
RETURN_IF_ERROR(fileOpenName.Set(ptr));
OpString fileDescription;
RETURN_IF_ERROR(uni_fileDescription.CreatePtr(&ptr, TRUE));
RETURN_IF_ERROR(fileDescription.Set(ptr));
OpString version;
RETURN_IF_ERROR(uni_version.CreatePtr(&ptr, TRUE));
RETURN_IF_ERROR(version.Set(ptr));
// Filter out commas from productName
const uni_char *delChars = UNI_L(",");
StrFilterOutChars(productName.CStr(), delChars);
if (is_replacement)
{
if (checkedFileDescription.IsEmpty() || fileDescription.Compare(checkedFileDescription))
{ // file versions differ
RETURN_IF_ERROR(InsertPlugin(productName, mimeType, fileExtents, fileOpenName, fileDescription, plugin_path, version));
if (was_different)
*was_different = TRUE;
}
}
else
{
// Check if plugin should be used, replaced and ignored, or just ignored
BOOL ignore = FALSE;
if (productName.HasContent() && fileDescription.HasContent())
{
if (!productName.Compare("Adobe Acrobat", MAXSTRLEN("Adobe Acrobat")))
{
if (m_acrobat_installed)
ignore = TRUE;
else
RETURN_IF_ERROR(CheckReplacePlugin(ACROBAT, ignore, fileDescription));
}
else if (productName.Find("Java(TM)") == 0)
{
if (IsVersionNewer(m_latest_seen_java_version, version))
{
if (m_latest_seen_java_name.HasContent())
// Remove old version.
OpStatus::Ignore(RemovePlugin(m_latest_seen_java_name));
OpStatus::Ignore(m_latest_seen_java_name.Set(productName));
OpStatus::Ignore(m_latest_seen_java_version.Set(version));
}
else
// Ignore this version.
ignore = TRUE;
}
else if (!productName.Compare("Adobe SVG Viewer Plugin", MAXSTRLEN("Adobe SVG Viewer Plugin")))
{
if (m_svg_installed)
ignore = TRUE;
else
RETURN_IF_ERROR(CheckReplacePlugin(SVG, ignore, fileDescription));
}
else if (!productName.Compare("QuickTime Plug-in", MAXSTRLEN("QuickTime Plug-in")))
{
if (!m_qt_installed)
ignore = TRUE; // local installed QuickTime plug-in is ignored
}
// this is the old plugin, not suitable for Windows Vista/Windows 7
else if(!productName.Compare("Windows Media Player Plug-in Dynamic Link Library", MAXSTRLEN("Windows Media Player Plug-in Dynamic Link Library")))
{
if(m_wmp_installed)
{
// we have a newer installed already
ignore = TRUE;
// remove this plugin from the list if the new one is already installed
RETURN_IF_ERROR(RemovePlugin(productName));
RETURN_IF_ERROR(RemovePlugin(UNI_L("Microsoftยฎ DRM")));
}
}
else if(!productName.Compare("Microsoftยฎ Windows Media Player Firefox Plugin", MAXSTRLEN("Microsoftยฎ Windows Media Player Firefox Plugin")))
{
if(GetWinType() < WIN2K)
{
ignore = TRUE;
}
else
{
m_wmp_installed = TRUE;
// remove the old plugin from the list if the new is already installed
RETURN_IF_ERROR(RemovePlugin(UNI_L("Windows Media Player Plug-in Dynamic Link Library")));
RETURN_IF_ERROR(RemovePlugin(UNI_L("Microsoftยฎ DRM")));
}
}
}
if (!ignore)
return InsertPlugin(productName, mimeType, fileExtents, fileOpenName, fileDescription, plugin_path, version);
}
return OpStatus::OK;
}
OP_STATUS WindowsPluginDetector::ReadFromRegistry()
{
BOOL dummy = FALSE;
if (!m_acrobat_installed)
RETURN_IF_ERROR(CheckReplacePlugin(ACROBAT, dummy));
if (!m_svg_installed)
RETURN_IF_ERROR(CheckReplacePlugin(SVG, dummy));
if (!m_qt_installed)
RETURN_IF_ERROR(CheckReplacePlugin(QT, dummy));
if (!m_wmp_detection_done)
RETURN_IF_ERROR(CheckReplacePlugin(WMP, dummy));
if (!m_read_from_registry)
{
m_read_from_registry = TRUE;
RETURN_IF_ERROR(ReadEntries(HKEY_LOCAL_MACHINE)); // FF installed
RETURN_IF_ERROR(ReadEntries(HKEY_CURRENT_USER)); // FF not installed
}
return OpStatus::OK;
}
OP_STATUS WindowsPluginDetector::ReadEntries(const HKEY hk)
{
OP_STATUS stat = OpStatus::OK;
HKEY hkey_accounts = NULL;
DWORD res = RegOpenKeyEx(hk, UNI_L("SOFTWARE\\MozillaPlugins"), 0, KEY_READ, &hkey_accounts);
if (res == ERROR_SUCCESS)
{
DWORD index = 0;
DWORD size = MAX_LEN - 1;
uni_char key[MAX_LEN] = {0};
while (RegEnumKeyEx(hkey_accounts, index++, key, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
{
HKEY hkey = NULL;
size = MAX_LEN - 1;
res = RegOpenKeyEx(hkey_accounts, key, 0, KEY_READ, &hkey);
if (res == ERROR_SUCCESS)
{
size = MAX_LEN - 1;
uni_char value[MAX_LEN] = {'\0'};
if (RegQueryValueEx(hkey, UNI_L("Path"), NULL, NULL, (LPBYTE)value, &size) == ERROR_SUCCESS)
{
OpString newfname;
stat = newfname.Set(value);
if (OpStatus::IsSuccess(stat) && !g_pcapp->IsPluginToBeIgnored(newfname.CStr()))
// Ignoring return value as failure while adding plugin should not stop enumeration
OpStatus::Ignore(InsertPluginPath(newfname));
}
}
RegCloseKey(hkey);
// Update max size of key - RegEnumKeyEx will use it for getting next key
size = MAX_LEN - 1;
}
}
RegCloseKey(hkey_accounts);
return stat;
}
BOOL WindowsPluginDetector::IsVersionNewer(const OpStringC& existing, const OpStringC& added)
{
if (existing.IsEmpty())
return added.HasContent();
const uni_char *old_version_pos = existing.CStr();
const uni_char *new_version_pos = added.CStr();
const uni_char *next_dot_old, *next_dot_new;
OpString number;
while ((next_dot_old = uni_strpbrk(old_version_pos, UNI_L(".,"))) != 0)
{
if ((next_dot_new = uni_strpbrk(new_version_pos, UNI_L(".,"))) == 0) //New version number is shorter -> older
return FALSE;
number.Set(old_version_pos, next_dot_old-old_version_pos);
int old_ver = uni_atoi(number);
number.Set(new_version_pos, next_dot_new-new_version_pos);
int new_ver = uni_atoi(number);
if (old_ver > new_ver)
return FALSE;
else if (old_ver < new_ver)
return TRUE;
old_version_pos = next_dot_old + 1;
new_version_pos = next_dot_new + 1;
}
if ((next_dot_new = uni_strpbrk(new_version_pos, UNI_L(".,"))) != 0) //New version number is longer -> newer
return TRUE;
return uni_atoi(old_version_pos) < uni_atoi(new_version_pos);
}
OP_STATUS WindowsPluginDetector::RemovePlugin(const OpStringC& productName)
{
PluginInfo *existing_plugin;
const uni_char *hashkey;
hashkey = productName.CStr();
if (OpStatus::IsSuccess(m_plugin_list.GetData(hashkey, &existing_plugin)))
{
m_plugin_list.Remove(hashkey, &existing_plugin);
OP_DELETE(existing_plugin);
}
return OpStatus::OK;
}
OP_STATUS WindowsPluginDetector::InsertPlugin(const OpStringC& productName, const OpStringC& mimeType, const OpStringC& fileExtensions, const OpStringC& fileOpenName, const OpStringC& fileDescription, const OpStringC& plugin, const OpStringC& version)
{
PluginInfo *existing_plugin;
const uni_char *hashkey;
BOOL hash_mimetype = FALSE;
hashkey = productName.CStr() ? productName.CStr() : fileDescription.CStr() ? fileDescription.CStr() : mimeType.CStr();
if (OpStatus::IsSuccess(m_plugin_list.GetData(hashkey, &existing_plugin)))
{
if (IsVersionNewer(existing_plugin->version, version))
{
m_plugin_list.Remove(hashkey, &existing_plugin);
OP_DELETE(existing_plugin);
}
else
{
// allow same version, but different mime types (stupid QuickTime, see bug #335179)
if (!existing_plugin->version.Compare(version) && existing_plugin->mime_type.Compare(mimeType))
hash_mimetype = TRUE;
else
return OpStatus::OK;
}
}
PluginInfo *new_plugin = OP_NEW(PluginInfo, ());
if (!new_plugin)
return OpStatus::ERR_NO_MEMORY;
OP_STATUS status;
if (OpStatus::IsError(status = new_plugin->product_name.Set(hashkey))
|| OpStatus::IsError(status = new_plugin->mime_type.Set(mimeType))
|| OpStatus::IsError(status = new_plugin->extensions.Set(fileExtensions))
|| OpStatus::IsError(status = new_plugin->file_open_name.Set(fileOpenName))
|| OpStatus::IsError(status = new_plugin->description.Set(fileDescription))
|| OpStatus::IsError(status = new_plugin->plugin.Set(plugin))
|| OpStatus::IsError(status = new_plugin->version.Set(version))
|| OpStatus::IsError(status = m_plugin_list.Add(hash_mimetype ? new_plugin->mime_type.CStr() : new_plugin->product_name.CStr(), new_plugin)))
{
OP_DELETE(new_plugin);
}
return status;
}
OP_STATUS WindowsPluginDetector::SubmitPlugins()
{
OP_PROFILE_METHOD("Submitted plugins to core");
OpHashIterator* it = m_plugin_list.GetIterator();
if (!it)
{
OP_ASSERT(!"SubmitPlugins(): Could not get iterator");
return OpStatus::ERR_NO_MEMORY;
}
OP_STATUS status = OpStatus::OK;
for (OP_STATUS for_status = it->First(); OpStatus::IsSuccess(for_status); for_status = it->Next())
{
PluginInfo* plugin = (PluginInfo*)it->GetData();
void *token = NULL;
if (plugin->mime_type.IsEmpty())
{
OP_ASSERT(!"SubmitPlugins(): mimetype is empty");
status = OpStatus::ERR;
break;
}
// OnPrepareNewPlugin() return ERR if the plug-in path already exists for another plug-in already registered. We should just ignore it probably and
// skip to the next plugin. This is perferctly normal since SubmitPlugins() is called multiple times when refreshing plugins.
if (OpStatus::IsError(m_listener->OnPrepareNewPlugin(plugin->plugin, plugin->product_name, plugin->description, plugin->version, COMPONENT_PLUGIN, TRUE, token)))
continue;
const uni_char* next_mime_type_ptr = plugin->mime_type.CStr();
const uni_char* next_mime_type_end_ptr = NULL;
const uni_char* next_ext_ptr = plugin->extensions.CStr();
const uni_char* next_ext_end_ptr = NULL;
const uni_char* next_desc_ptr = plugin->file_open_name.CStr();
const uni_char* next_desc_end_ptr = NULL;
OpString next_mime_type;
OpString next_ext;
OpString next_desc;
if (!next_ext.Reserve(5))
return OpStatus::ERR_NO_MEMORY;
if (!next_desc.Reserve(30))
return OpStatus::ERR_NO_MEMORY;
while (1)
{
next_mime_type_end_ptr = uni_strchr(next_mime_type_ptr, '|');
next_mime_type.Set(next_mime_type_ptr, next_mime_type_end_ptr?next_mime_type_end_ptr-next_mime_type_ptr:KAll);
if (next_ext_ptr)
{
next_ext_end_ptr = uni_strchr(next_ext_ptr, '|');
int length = next_ext_end_ptr ? next_ext_end_ptr-next_ext_ptr : KAll;
RETURN_IF_ERROR(next_ext.Set(next_ext_ptr, length));
}
else
next_ext[0] = 0;
if (next_desc_ptr)
{
next_desc_end_ptr = uni_strchr(next_desc_ptr, '|');
int length = next_desc_end_ptr ? next_desc_end_ptr - next_desc_ptr : KAll;
RETURN_IF_ERROR(next_desc.Set(next_desc_ptr, length));
}
else
next_desc[0] = 0;
if (next_mime_type.HasContent() && OpStatus::IsError(status = m_listener->OnAddContentType(token, next_mime_type)))
break;
if(next_ext.HasContent() && OpStatus::IsError(status = m_listener->OnAddExtensions(token, next_mime_type, next_ext, next_desc)))
break;
if (!next_mime_type_end_ptr)
break;
next_mime_type_ptr = next_mime_type_end_ptr + 1;
next_ext_ptr = next_ext_end_ptr ? next_ext_end_ptr+1 : 0;
next_desc_ptr = next_desc_end_ptr ? next_desc_end_ptr+1 : 0;
}
if (OpStatus::IsError(status) || OpStatus::IsError(status = m_listener->OnCommitPreparedPlugin(token)))
{
OP_ASSERT(!"SumbitPlugins(): Cancelling prepared plugin due to prevous errors or could not commit");
OpStatus::Ignore(m_listener->OnCancelPreparedPlugin(token));
break;
}
}
OP_DELETE(it);
return status;
}
#define PLUGIN_DLL_READ_BUFFER_SIZE 1024
BOOL WindowsPluginDetector::IsPluginForArchitecture(const OpStringC& plugin_path)
{
if(plugin_path.IsEmpty())
return FALSE;
BOOL is_supported;
{
OpAutoHANDLE fhandle(CreateFile(plugin_path.CStr(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0));
if (fhandle.get() == INVALID_HANDLE_VALUE)
return FALSE;
DWORD fsize = GetFileSize(fhandle, NULL);
if (fsize == 0xFFFFFFFF || fsize < sizeof(IMAGE_DOS_HEADER))
return FALSE;
{
OpAutoHANDLE mhandle(CreateFileMapping(fhandle, 0, PAGE_READONLY, 0, 0, 0));
if (!mhandle.get())
return FALSE;
char *view = (char *)MapViewOfFile(mhandle, FILE_MAP_READ, 0, 0, 0);
if (!view)
return FALSE;
PIMAGE_DOS_HEADER dos_header = reinterpret_cast<PIMAGE_DOS_HEADER>(view);
LONG nth_offset = dos_header->e_lfanew;
PIMAGE_NT_HEADERS nt_header = reinterpret_cast<PIMAGE_NT_HEADERS>(view + nth_offset);
if (nth_offset + sizeof(nt_header->FileHeader.Machine) > fsize)
{
UnmapViewOfFile(view);
return FALSE;
}
// check if we support this one
#ifdef _WIN64
is_supported = (nt_header->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64);
#else
// this is the only type allowed, see MiVerifyImageHeader in ntoskrnl.exe
is_supported = (nt_header->FileHeader.Machine == IMAGE_FILE_MACHINE_I386);
#endif // _WIN64
UnmapViewOfFile(view);
}
}
return is_supported;
}
#endif // _PLUGIN_SUPPORT_ && !NS4P_COMPONENT_PLUGINS
|
#pragma once
template <typename TCollection, typename TFilter>
class query_where
{
public:
template <typename TNestedIterator>
class iterator
{
public:
using iterator_category = std::forward_iterator_tag;
using value_type = typename std::iterator_traits<TNestedIterator>::value_type;
using difference_type = typename std::iterator_traits<TNestedIterator>::difference_type;
using pointer = typename std::iterator_traits<TNestedIterator>::pointer;
using reference = typename std::iterator_traits<TNestedIterator>::reference;
private:
TNestedIterator m_Iter;
query_where<TCollection, TFilter>& m_Query;
public:
iterator(TNestedIterator iter, query_where<TCollection, TFilter>& query)
: m_Iter(iter)
, m_Query(query)
{
}
decltype(auto) operator*() const
{
return (*m_Iter);
}
iterator& operator++()
{
if (m_Iter != m_Query.m_Collection.end())
{
while (true)
{
++m_Iter;
if (m_Iter == m_Query.m_Collection.end())
{
break;
}
if (m_Query.m_Filter(*m_Iter))
{
break;
}
}
}
return *this;
}
iterator operator++(int)
{
iterator tmp = *this;
++*this;
return tmp;
}
bool operator == (const iterator& iter) const
{
return m_Iter == iter.m_Iter;
}
bool operator != (const iterator& iter) const
{
return m_Iter != iter.m_Iter;
}
};
private:
TCollection m_Collection;
TFilter m_Filter;
public:
query_where(TCollection && collection, TFilter && filter)
: m_Collection(std::forward<TCollection>(collection))
, m_Filter(std::forward<TFilter>(filter))
{
}
auto begin()
{
auto iter = m_Collection.begin();
while (iter != m_Collection.end() && !m_Filter(*iter))
{
++iter;
}
return iterator<decltype(iter)>(iter, *this);
}
auto end()
{
auto iter = m_Collection.end();
return iterator<decltype(iter)>(iter, *this);
}
};
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Float4.h>
#include <Uno.UX.Property-1.h>
namespace g{namespace Fuse{namespace Controls{struct TextControl;}}}
namespace g{namespace Uno{namespace UX{struct PropertyObject;}}}
namespace g{namespace Uno{namespace UX{struct Selector;}}}
namespace g{struct app18_FuseControlsTextControl_Color_Property;}
namespace g{
// internal sealed class app18_FuseControlsTextControl_Color_Property :378
// {
::g::Uno::UX::Property1_type* app18_FuseControlsTextControl_Color_Property_typeof();
void app18_FuseControlsTextControl_Color_Property__ctor_3_fn(app18_FuseControlsTextControl_Color_Property* __this, ::g::Fuse::Controls::TextControl* obj, ::g::Uno::UX::Selector* name);
void app18_FuseControlsTextControl_Color_Property__Get1_fn(app18_FuseControlsTextControl_Color_Property* __this, ::g::Uno::UX::PropertyObject* obj, ::g::Uno::Float4* __retval);
void app18_FuseControlsTextControl_Color_Property__New1_fn(::g::Fuse::Controls::TextControl* obj, ::g::Uno::UX::Selector* name, app18_FuseControlsTextControl_Color_Property** __retval);
void app18_FuseControlsTextControl_Color_Property__get_Object_fn(app18_FuseControlsTextControl_Color_Property* __this, ::g::Uno::UX::PropertyObject** __retval);
void app18_FuseControlsTextControl_Color_Property__Set1_fn(app18_FuseControlsTextControl_Color_Property* __this, ::g::Uno::UX::PropertyObject* obj, ::g::Uno::Float4* v, uObject* origin);
void app18_FuseControlsTextControl_Color_Property__get_SupportsOriginSetter_fn(app18_FuseControlsTextControl_Color_Property* __this, bool* __retval);
struct app18_FuseControlsTextControl_Color_Property : ::g::Uno::UX::Property1
{
uWeak< ::g::Fuse::Controls::TextControl*> _obj;
void ctor_3(::g::Fuse::Controls::TextControl* obj, ::g::Uno::UX::Selector name);
static app18_FuseControlsTextControl_Color_Property* New1(::g::Fuse::Controls::TextControl* obj, ::g::Uno::UX::Selector name);
};
// }
} // ::g
|
#include "LeaveProcess.h"
#include "Logger.h"
#include "HallManager.h"
#include "Room.h"
#include "ErrorMsg.h"
#include "GameCmd.h"
#include "ProcessManager.h"
LeaveProcess::LeaveProcess()
{
this->name = "LeaveProcess";
}
LeaveProcess::~LeaveProcess()
{
}
int LeaveProcess::doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket, Context* pt )
{
//_NOTUSED(pt);
int cmd = pPacket->GetCmdType();
short seq = pPacket->GetSeqNum();
short source = pPacket->GetSource();
int uid = pPacket->ReadInt();
int tid = pPacket->ReadInt();
short svid = tid >> 16;
short realTid = tid & 0x0000FFFF;
Room* room = Room::getInstance();
Table* table = room->getTable();
if(table == NULL)
{
_LOG_ERROR_("[LeaveProcess] uid=[%d] tid=[%d] realTid=[%d] Table is NULL\n",uid, tid, realTid);
return sendErrorMsg(clientHandler, cmd, uid, -2,ErrorMsg::getInstance()->getErrMsg(-2),seq);
}
Player* player = table->getPlayer(uid);
if(player == NULL)
{
_LOG_ERROR_("[LeaveProcess] uid=[%d] tid=[%d] realTid=[%d] Your not in This Table\n",uid, tid, realTid);
return sendErrorMsg(clientHandler, cmd, uid, -1,ErrorMsg::getInstance()->getErrMsg(-1),seq);
}
if(player->notBetCoin() && table->bankeruid != player->id)
{
ULOGGER(E_LOG_INFO, player->id) << "player leave now";
OutputPacket response;
response.Begin(cmd,player->id);
response.SetSeqNum(seq);
response.WriteShort(0);
response.WriteString("ok");
response.WriteInt(player->id);
response.WriteShort(player->m_nStatus);
response.WriteInt(table->id);
response.WriteShort(table->m_nStatus);
response.WriteInt(player->id);
response.End();
HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false);
table->playerLeave(player);
}
else
{
player->isonline = false;
ULOGGER(E_LOG_INFO, player->id) << "player cant leave";
//_LOG_DEBUG_("[Data Response] player=[%d] leave error logout\n", player->id);
}
return 0;
}
int LeaveProcess::sendLeaveInfo(Table* table, Player* leavePlayer, short seq)
{
int sendnum = 0;
int svid = Configure::getInstance()->m_nServerId;
int tid = (svid << 16)|table->id;
int i = 0;
for(i = 0; i < GAME_PLAYER; ++i)
{
if(table->player_array[i])
{
OutputPacket response;
response.Begin(CLIENT_MSG_LEAVE,table->player_array[i]->id);
if(leavePlayer->id == table->player_array[i]->id)
response.SetSeqNum(seq);
response.WriteShort(0);
response.WriteString("ok");
response.WriteInt(table->player_array[i]->id);
response.WriteShort(table->player_array[i]->m_nStatus);
response.WriteInt(tid);
response.WriteShort(table->m_nStatus);
response.WriteInt(leavePlayer->id);
response.End();
HallManager::getInstance()->sendToHall(table->player_array[i]->m_nHallid, &response, false);
sendnum++;
}
}
return 0;
}
REGISTER_PROCESS(CLIENT_MSG_LEAVE, LeaveProcess);
|
#ifndef SETTINGS_H_
#define SETTINGS_H_
constexpr int flag = 0;
//if using ccs811/bme280 keep flag=0
//if using ms8607 keep flag=1
#endif // SETTINGS_H_
|
/*
* reverse_adj_list.cpp
*
* Created on: 05-Nov-2017
* Author: divya
*/
#include <sstream>
#include <fstream>
#include <string>
#include <iostream>
#define debug 0
using namespace std;
// n = num of vertices, m = num of edges
//int main(int argc, char **argv)
void reverse_adj_list(const char *filename, int *Vertices, int *AdjacencyList)
{
// const char *filename=argv[1];
std::string line;
std::ifstream infile(filename);
// int *Vertices;
// int *AdjacencyList;
int *edges_count_per_vertex;
std::getline(infile,line);
std::getline(infile,line);
std::istringstream iss(line);
char c;
iss>>c;
int m,n,x,u,v;
int i;
iss>>m;
iss>>n;
iss>>x;
if(debug)
{
std::cout << "number of edges=" <<m<< '\n';
std::cout << "number of vertices = " <<n<< '\n';
}
// Vertices = new int[n];
// AdjacencyList = new int[m];
edges_count_per_vertex = new int[n];
int oldu = -1;
//-------------------------------------------------------------------------
//-------------------------Filling O(V) list-------------------------------
//-------------------------------------------------------------------------
while (std::getline(infile, line)) // this does the checking!
{
std::istringstream iss(line);
iss>>v;
iss>>u;
Vertices[u-1] += 1;
while (iss >> x)
{
}
}
int temp1, temp2=0;
for(i=1;i<n;i++)
{
temp1 = Vertices[i];
Vertices[i] = Vertices[i-1]+temp2;
temp2 = temp1;
// cout<<i<<" : "<<Vertices[i]<<"\n";
}
if(debug)
cout<<"----O(V) list----\n";
for(i=0;i<n;i++)
{
if(i == 0)
Vertices[i] = 0;
// else if(Vertices[i] == Vertices[i-1])
// Vertices[i-1] = -1;
if(debug)
cout<<"Vertices["<<i<<"] : "<<Vertices[i]<<"\n";
edges_count_per_vertex[i]=Vertices[i];
}
if(debug)
cout<<"----O(V) list----\n";
infile.close();
//-------------------------------------------------------------------------
//-------------------------Filling O(E) list-------------------------------
//-------------------------------------------------------------------------
infile.open(filename);
std::getline(infile,line);
std::getline(infile,line);
int idx = 0;
oldu = -1;
while (std::getline(infile, line)) // this does the checking!
{
std::istringstream iss(line);
iss>>v;
iss>>u;
oldu = u-1;
idx = edges_count_per_vertex[oldu];
// cout << " count["<<oldu<<"] : "<< edges_count_per_vertex[oldu] << "idx : " << idx << endl;
AdjacencyList[idx] = v;
edges_count_per_vertex[oldu] += 1;
// std::cout << "else AdjacencyList["<<idx<<"] : "<<v << '\n';
while (iss >> x)
{
}
}
if(debug)
{
cout<<"----O(E) list----\n";
for(i=0;i<m;i++)
{
cout<<"AdjacencyList["<<i<<"] : " << AdjacencyList[i]<<endl;
}
cout<<"----O(E) list----\n";
}
infile.close();
delete(edges_count_per_vertex);
}
|
#include "TimeCode.h"
#ifdef USING_QT
#include <QRegExp>
#include <QStringList>
#else
#include <regex>
#endif
#include <cmath>
#include <cfenv>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cassert>
template<typename T>
std::vector<T> split(const T& str, const T& delimiters)
{
std::vector<T> v;
typename T::size_type start = 0;
auto pos = str.find_first_of(delimiters, start);
while(pos != T::npos)
{
if(pos != start) // ignore empty tokens
v.emplace_back(str, start, pos - start);
start = pos + 1;
pos = str.find_first_of(delimiters, start);
}
if(start < str.length()) // ignore trailing delimiter
v.emplace_back(str, start, str.length() - start); // add what's left of the string
return v;
}
template<typename T>
inline T convertToNumber(std::wstring const& s)
{
std::wistringstream i(s);
T x;
if (!(i >> x))
{
std::string message("Conversion failed ");
message += __FUNCTION__;
throw std::runtime_error(message);
}
return x;
}
Timecode Timecode::fromTimecodeString(const std::wstring& timecode, int32_t rateNum, int32_t rateDen)
{
std::wstring expression = L"([0-1][0-9]|2[0-3])([:][0-5][0-9]){2}([:;][0-5][0-9])";
#ifdef USING_QT
//Using QT allows more systems and compilers to be supported
QRegExp regExp(QString::fromStdWString(expression));
if (!regExp.exactMatch(QString::fromStdWString(timecode)))
return Timecode();
std::wstring matchValue = regExp.cap(0).toStdWString();
#else
//First validate
std::wregex regExp(expression);
std::wsmatch wsMatch;
std::regex_match(timecode, wsMatch, regExp);
if (wsMatch.empty())
return Timecode();
std::wstring matchValue = *wsMatch.cbegin();
#endif
std::vector<std::wstring> components = split<std::wstring>(matchValue, L":;");
assert(components.size() == 4);
return Timecode(rateNum,
rateDen,
matchValue.find(';') != std::wstring::npos,
convertToNumber<int16_t>(components[0]),
convertToNumber<int16_t>(components[1]),
convertToNumber<int16_t>(components[2]),
convertToNumber<int16_t>(components[3]));
}
Timecode Timecode::fromMilliseconds(double milliseconds, int32_t rateNum, int32_t rateDen, bool dropFrame)
{
std::fesetround(FE_DOWNWARD);
int16_t hours = (int16_t) std::lrint(milliseconds / 3600000.0);
milliseconds -= hours * 3600000.0;
int16_t minutes = (int16_t) std::lrint(milliseconds / 60000.0);
milliseconds -= minutes * 60000.0;
int16_t seconds = (int16_t) std::lrint(milliseconds / 1000);
milliseconds -= seconds * 1000;
int16_t frames = (int16_t) std::lrint(((milliseconds * (double) rateNum) / (double) rateDen) / 1000.0);
return Timecode(rateNum, rateDen, dropFrame, hours, minutes, seconds, frames);
}
Timecode::Timecode()
{
setInvalid();
}
Timecode::Timecode(uint16_t roundedRate, bool dropFrame)
{
init(roundedRate, dropFrame);
}
Timecode::Timecode(uint16_t roundedRate, bool dropFrame, int64_t offset)
{
init(roundedRate, dropFrame, offset);
}
Timecode::Timecode(int32_t rateNum, int32_t rateDen, bool dropFrame)
{
init(rateNum, rateDen, dropFrame);
}
Timecode::Timecode(int32_t rateNum, int32_t rateDen, bool dropFrame, int16_t hour, int16_t min, int16_t sec, int16_t frame)
{
init(rateNum, rateDen, dropFrame);
init(hour, min, sec, frame);
}
uint64_t Timecode::getTotalFrames()
{
uint64_t totalFrames = 0;
totalFrames = hour_ * framesPerHour_;
if (dropFrame_)
{
totalFrames += (min_ / 10) * framesPer10Min_;
totalFrames += (min_ % 10) * framesPerMin_;
}
else
{
totalFrames += min_ * framesPerMin_;
}
totalFrames += sec_ * roundedTCBase_;
totalFrames += frame_;
return totalFrames;
}
Timecode::Timecode(int32_t rateNum, int32_t rateDen, bool dropFrame, int64_t offset)
{
init(rateNum, rateDen, dropFrame);
init(offset);
}
void Timecode::setInvalid()
{
roundedTCBase_ = 0;
dropFrame_ = false;
hour_ = 0;
min_ = 0;
sec_ = 0;
frame_ = 0;
offset_ = 0;
framesPerMin_ = 0;
nDFramesPerMin_ = 0;
framesPer10Min_ = 0;
framesPerHour_ = 0;
}
void Timecode::init(uint16_t roundedRate, bool dropFrame)
{
roundedTCBase_ = roundedRate;
if (roundedRate == 30 || roundedRate == 60)
dropFrame_ = dropFrame;
else
dropFrame_ = false;
if (dropFrame_)
{
// first 2 frame numbers shall be omitted at the start of each minute,
// except minutes 0, 10, 20, 30, 40 and 50
dropCount_ = 2;
if (roundedTCBase_ == 60)
dropCount_ *= 2;
framesPerMin_ = roundedTCBase_ * 60 - dropCount_;
framesPer10Min_ = framesPerMin_ * 10 + dropCount_;
}
else
{
framesPerMin_ = roundedTCBase_ * 60;
framesPer10Min_ = framesPerMin_ * 10;
}
framesPerHour_ = framesPer10Min_ * 6;
nDFramesPerMin_ = roundedTCBase_ * 60;
hour_ = 0;
min_ = 0;
sec_ = 0;
frame_ = 0;
offset_ = 0;
}
void Timecode::init(uint16_t roundedRate, bool dropFrame, int64_t offset)
{
init(roundedRate, dropFrame);
offset_ = offset;
cleanOffset();
updateTimecode();
}
void Timecode::init(int32_t rateNum, int32_t rateDen, bool dropFrame)
{
uint16_t roundedBase = (uint16_t)((rateNum + rateDen/2) / rateDen);
init(roundedBase, dropFrame);
}
void Timecode::init(int64_t offset)
{
offset_ = offset;
cleanOffset();
updateTimecode();
}
void Timecode::init(int32_t rateNum, int32_t rateDen, bool dropFrame, int64_t offset)
{
init(rateNum, rateDen, dropFrame);
init(offset);
}
void Timecode::init(int16_t hour, int16_t min, int16_t sec, int16_t frame)
{
hour_ = hour;
min_ = min;
sec_ = sec;
frame_ = frame;
cleanTimecode();
updateOffset();
}
void Timecode::init(int32_t rateNum, int32_t rateDen, bool dropFrame, int16_t hour, int16_t min, int16_t sec, int16_t frame)
{
init(rateNum, rateDen, dropFrame);
init(hour, min, sec, frame);
}
void Timecode::addOffset(int64_t offset)
{
offset_ += offset;
cleanOffset();
updateTimecode();
}
void Timecode::addOffset(int64_t offset, int32_t rateNum, int32_t rateDen)
{
uint16_t roundedBase = (uint16_t)((rateNum + rateDen/2) / rateDen);
addOffset(convertPosition(offset, roundedTCBase_, roundedBase, Rounding::ROUND_AUTO));
}
int64_t Timecode::getMaxOffset() const
{
return 24 * framesPerHour_;
}
bool Timecode::operator==(const Timecode& right) const
{
return (roundedTCBase_ == 0 && right.roundedTCBase_ == 0) ||
(roundedTCBase_ != 0 && right.roundedTCBase_ != 0 &&
offset_ == convertPosition(right.offset_, roundedTCBase_, right.roundedTCBase_, Rounding::ROUND_AUTO));
}
bool Timecode::operator!=(const Timecode& right) const
{
return !(*this == right);
}
bool Timecode::operator<(const Timecode& right) const
{
return (roundedTCBase_ != 0 && right.roundedTCBase_ == 0) ||
(roundedTCBase_ != 0 && right.roundedTCBase_ != 0 &&
offset_ < convertPosition(right.offset_, roundedTCBase_, right.roundedTCBase_, Rounding::ROUND_AUTO));
}
std::wstring Timecode::toTimecodeString(bool useDropDelimiter) const
{
std::wstringstream wss;
wss << std::setfill(L'0') << std::setw(2) << getHour();
wss << L":" << std::setfill(L'0') << std::setw(2) << getMin();
wss << L":" << std::setfill(L'0') << std::setw(2) << getSec();
wss << (useDropDelimiter && isDropFrame() ? L";" : L":") << std::setfill(L'0') << std::setw(2) << getFrame();
return wss.str();
}
void Timecode::cleanOffset()
{
if (roundedTCBase_ == 0)
offset_ = 0;
else
offset_ %= getMaxOffset();
if (offset_ < 0)
offset_ += getMaxOffset();
}
void Timecode::cleanTimecode()
{
if (roundedTCBase_ == 0)
{
hour_ = 0;
min_ = 0;
sec_ = 0;
frame_ = 0;
}
else
{
hour_ %= 24;
min_ %= 60;
sec_ %= 60;
frame_ %= roundedTCBase_;
// replace invalid drop frame hhmmssff with a valid one after it
if (dropFrame_ && sec_ == 0 && (min_ % 10) && frame_ < dropCount_)
frame_ = dropCount_;
}
}
void Timecode::updateOffset()
{
if (roundedTCBase_ == 0)
{
offset_ = 0;
return;
}
offset_ = getTotalFrames();
}
void Timecode::updateTimecode()
{
if (roundedTCBase_ == 0)
{
hour_ = 0;
min_ = 0;
sec_ = 0;
frame_ = 0;
return;
}
int64_t offset = offset_;
bool frames_dropped = false;
hour_ = (int16_t)(offset / framesPerHour_);
offset = offset % framesPerHour_;
min_ = (int16_t)(offset / framesPer10Min_ * 10);
offset = offset % framesPer10Min_;
if (offset >= nDFramesPerMin_)
{
offset -= nDFramesPerMin_;
min_ += (int16_t)((offset / framesPerMin_) + 1);
offset = offset % framesPerMin_;
frames_dropped = dropFrame_;
}
sec_ = (int16_t)(offset / roundedTCBase_);
frame_ = (int16_t)(offset % roundedTCBase_);
if (frames_dropped)
{
frame_ += dropCount_;
if (frame_ >= roundedTCBase_)
{
frame_ -= roundedTCBase_;
sec_++;
if (sec_ >= 60)
{
sec_ = 0;
min_++;
if (min_ >= 60)
{
min_ = 0;
hour_++;
if (hour_ >= 24)
hour_ = 0;
}
}
}
}
}
int64_t Timecode::convertPosition(int64_t inPosition, int64_t factorTop, int64_t factorBottom, Rounding rounding) const
{
if (inPosition == 0 || factorTop == factorBottom)
return inPosition;
if (inPosition < 0) {
if (rounding == Rounding::ROUND_UP || (rounding == Rounding::ROUND_AUTO && factorTop < factorBottom))
return -convertPosition(-inPosition, factorTop, factorBottom, Rounding::ROUND_DOWN);
else
return -convertPosition(-inPosition, factorTop, factorBottom, Rounding::ROUND_UP);
}
int64_t round_num = 0;
if (rounding == Rounding::ROUND_UP || (rounding == Rounding::ROUND_AUTO && factorTop < factorBottom))
round_num = factorBottom - 1;
else if (rounding == Rounding::ROUND_NEAREST)
round_num = factorBottom / 2;
if (inPosition <= INT32_MAX)
{
// no chance of overflow (assuming there exists a result that fits into int64_t)
return (inPosition * factorTop + round_num) / factorBottom;
}
else
{
// separate the calculation into 2 parts so there is no chance of an overflow (assuming there exists
// a result that fits into int64_t)
// a*b/c = ((a/c)*c + a%c) * b) / c = (a/c)*b + (a%c)*b/c
return (inPosition / factorBottom) * factorTop +
((inPosition % factorBottom) * factorTop + round_num) / factorBottom;
}
}
|
#define _CRT_SECURE_NO_WARNINGS
#include "Table.h"
#include "Tree.h"
#include "Node.h"
#include <stdlib.h>
#include <stdio.h>
#define SIZE 256
#define MSG 1000
int main()
{
Table *table = inizialise();
char file[] = "text.txt";
setTable(table, file);
Table * tableCount = clearTable(table);
int sizeTableCount = sizeTable(table);
Node *node = 0;
for (int i = 0; i < sizeTableCount; i++)
{
Tree *tree = (Tree *)malloc(sizeof(Tree));
tree->table = tableCount[i];
tree->code[0] = '\0';
tree->left = NULL;
tree->countRoot = tableCount[i].count;
tree->right = NULL;
add2List(&node, (tree));
}
for (int i = 0; i < sizeTableCount-1; i++)
{
Tree *t = (Tree *)malloc(sizeof(Tree));
int n1 = node->tree.countRoot;
int n2 = node->pnext->tree.countRoot;
t->countRoot = n1 + n2;
t->table.count = NULL;
t->table.letter = NULL;
t->code[0] = '\0';
Tree *tLeft = (Tree *)malloc(sizeof(Tree));
*tLeft = node->tree;
Tree *tRigth = (Tree *)malloc(sizeof(Tree));
*tRigth = (node->pnext)->tree;
t->left = tLeft;
t->right = tRigth;
add2List(&node, t);
deleteFirst(node);
deleteFirst(node);
}
makeCodes(&node->tree);
Tree *rootHoff = &node->tree;
FILE *stream = fopen(file, "r");
char msg[SIZE] = {'\0'};
printf("Code File \n");
for (int i = 0; i < SIZE; i++)
{
msg[i] = fgetc(stream);
char lett = msg[i];
inL(rootHoff, lett);
}
puts("\n");
fclose(stream);
}
|
#pragma once
#include "cocos2d.h"
#include "cocos-ext.h"
#include "ui/CocosGUI.h"
#include "SceneManager.h"
USING_NS_CC;
class ShopLayer : public Layer
{
public:
ShopLayer();
~ShopLayer();
CREATE_FUNC(ShopLayer);
virtual bool init();
};
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@tiliae.eu *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#include <cmath>
#include "ProjectionMatrix.h"
namespace Geometry {
using namespace boost::numeric::ublas;
const ProjectionMatrix ProjectionMatrix::UNITARY;
void ProjectionMatrix::setViewport (float left, float right, float bottom, float top)
{
operator() (0,0) = 2.0 / (right - left); operator() (0,1) = 0; operator() (0,2) = 0; operator() (0,3) = -(right + left) / (right - left);
operator() (1,0) = 0; operator() (1,1) = 2.0 / (top - bottom); operator() (1,2) = 0; operator() (1,3) = -(top + bottom) / (top - bottom);
operator() (2,0) = 0; operator() (2,1) = 0; operator() (2,2) = -1; operator() (2,3) = 0;
operator() (3,0) = 0; operator() (3,1) = 0; operator() (3,2) = 0; operator() (3,3) = 1;
}
} // nam
|
#include <iostream>
#include <random>
#include <iomanip>
#include <unordered_map>
using namespace std;
#define ADDR_SLICE true
int main() {
random_device rd;
mt19937 gen(rd());
unordered_map<uint32_t, uint32_t> mem;
uniform_int_distribution<uint32_t> dist(0, 0xfffffffful);
size_t count = 0;
while(!cin.eof()) {
char mode;
uint32_t addr, data;
cin>>hex>>mode>>addr>>data;
if(cin.eof()) break;
++count;
#ifdef ADDR_SLICE
addr &= 0xffff;
#endif
addr &= ~0x3; // align to 4 bytes
cout<<hex<<mode<<" "<<addr<<" ";
if(mode == 'r') {
if(mem.count(addr) > 0) cout<<mem[addr]<<endl;
else cout<<0<<endl;
} else {
mem[addr] = dist(gen);
cout<<mem[addr]<<endl;
}
}
cerr<<"Total count: "<<count<<endl;
}
|
#include <iostream>
#include <ctime>
#include "Maze.h"
using namespace std;
int main() {
//Maze maze;
//maze.GenerateRandomArray();
Maze* maze = new Maze();
maze->GenerateRandomArray();
cout <<endl<<"่ตทๅง้ๅก :"<< endl;
maze->PrintMaze();
cout << endl;
if (maze->visit(1,1)!= 2) {//้้ๅฐฑๆๆน่ฎclassๅ
ง็่ทฏๅพ็ตๆๆธๆ
cout << "ๆฒๆๅบๅฃ่ทฏๅพ" << endl<<endl;
}
maze->PrintMaze();
cout << endl;
delete maze;
//free(&maze);
system("pause");
}
|
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
/*Programa que pide el nombre al usuario y devuelve la cantidad de vocales que
contiene.
Elaborado por:Viviana Rojas Ruiz*/
int main() {
char vec[20];
char *nombre=vec;
printf("Ingrese su Nombre: ");
gets(nombre);
int cont=0;
for(int x=0;x<20;x++){
switch(nombre[x]){
case 'a': cont++; break;
case 'e': cont++; break;
case 'i': cont++; break;
case 'o': cont++; break;
case 'u': cont++; break;
}
}
printf("\nCantidad de Vocales que contiene en Nombre==> %d",cont);
return 0;
}
|
#include <Windows.h>
#include "Mutex.h"
struct Mutex::MutexInternal
{
::CRITICAL_SECTION mtx;
};
Mutex::Mutex(void):m_pInternal(NULL)
{
m_pInternal = new MutexInternal;
::InitializeCriticalSection(&m_pInternal->mtx);
}
Mutex::~Mutex(void)
{
::DeleteCriticalSection(&m_pInternal->mtx);
}
bool Mutex::enter()
{
::EnterCriticalSection(&m_pInternal->mtx);
return true;
}
bool Mutex::leave()
{
::LeaveCriticalSection(&m_pInternal->mtx);
return true;
}
|
// Created by: Peter KURNEV
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BOPAlgo_Section_HeaderFile
#define _BOPAlgo_Section_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BOPAlgo_Builder.hxx>
#include <NCollection_BaseAllocator.hxx>
class BOPAlgo_PaveFiller;
//! The algorithm to build a Section between the arguments.
//! The Section consists of vertices and edges.
//! The Section contains:
//! 1. new vertices that are subjects of V/V, E/E, E/F, F/F interferences
//! 2. vertices that are subjects of V/E, V/F interferences
//! 3. new edges that are subjects of F/F interferences
//! 4. edges that are Common Blocks
class BOPAlgo_Section : public BOPAlgo_Builder
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
Standard_EXPORT BOPAlgo_Section();
Standard_EXPORT virtual ~BOPAlgo_Section();
//! Constructor with allocator
Standard_EXPORT BOPAlgo_Section(const Handle(NCollection_BaseAllocator)& theAllocator);
protected:
//! Checks the data before performing the operation
Standard_EXPORT virtual void CheckData() Standard_OVERRIDE;
//! Combine the result of section operation
Standard_EXPORT virtual void BuildSection(const Message_ProgressRange& theRange);
//! Performs calculations using prepared Filler object <thePF>
Standard_EXPORT virtual void PerformInternal1(const BOPAlgo_PaveFiller& thePF, const Message_ProgressRange& theRange) Standard_OVERRIDE;
protected:
//! List of operations to be supported by the Progress Indicator.
//! Override the whole enumeration here since the constant operations are also
//! going to be overridden.
enum BOPAlgo_PIOperation
{
PIOperation_TreatVertices = 0,
PIOperation_TreatEdges,
PIOperation_BuildSection,
PIOperation_FillHistory,
PIOperation_PostTreat,
PIOperation_Last
};
//! Filling steps for constant operations
Standard_EXPORT void fillPIConstants(const Standard_Real theWhole, BOPAlgo_PISteps& theSteps) const Standard_OVERRIDE;
//! Filling steps for all other operations
Standard_EXPORT void fillPISteps(BOPAlgo_PISteps& theSteps) const Standard_OVERRIDE;
};
#endif // _BOPAlgo_Section_HeaderFile
|
#include "pch.h"
CTestOneIocp* CTestOneIocp::_Instance = nullptr;
DWORD WINAPI GameThreadCallback(LPVOID parameter)
{
CTestOneIocp* iocp = (CTestOneIocp*)parameter;
while (TRUE)
{
iocp->GameThreadCallback();
Sleep(1);
}
}
DWORD WINAPI KeepThreadCallback(LPVOID parameter)
{
CTestOneIocp *Owner = (CTestOneIocp*)parameter;
Owner->KeepThreadCallback();
return 0;
}
CTestOneIocp::CTestOneIocp()
{
}
CTestOneIocp::~CTestOneIocp()
{
}
BOOL CTestOneIocp::Begin()
{
if (!CIocp::Begin())
{
CLog::WriteDebugLog(_T(""));
End();
return FALSE;
}
m_UserManager = new CUserManager();
m_ListenSession = new CNetworkSession();
m_ServerOne = new CServerOne();
if (!m_ListenSession->Begin())
{
CLog::WriteDebugLog(_T("m_ListenSession->Begin() Error"));
End();
return FALSE;
}
if (!m_ListenSession->TcpBind())
{
CLog::WriteDebugLog(_T("m_ListenSession->TcpBind() Error"));
End();
return FALSE;
}
if (!m_ListenSession->Listen(8002, 200))
{
CLog::WriteDebugLog(_T("m_ListenSession->Listen(8001, 200) Error"));
End();
return FALSE;
}
if (!CIocp::RegisterSocketToIocp(m_ListenSession->GetSocket(), reinterpret_cast<ULONG_PTR>(m_ListenSession)))
{
CLog::WriteDebugLog(_T("CIocp::RegisterSocketToIocp Error"));
End();
return FALSE;
}
if (!m_UserManager->Begin(100, m_ListenSession->GetSocket()))
{
CLog::WriteDebugLog(_T("m_UserManager->Begin Error"));
End();
return FALSE;
}
if (!m_UserManager->AcceptAll())
{
CLog::WriteDebugLog(_T("m_UserManager->AcceptAll() Error"));
End();
return FALSE;
}
if (!m_ServerOne->Begin())
{
CLog::WriteDebugLog(_T("m_ServerOne->Begin() Error"));
End();
return FALSE;
}
mGameThreadDestroyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!mGameThreadDestroyEvent)
{
CLog::WriteDebugLog(_T("mGameThreadDestroyEvent Error"));
End();
return FALSE;
}
mGameThreadHandle = CreateThread(NULL, 0, ::GameThreadCallback, this, 0, NULL);
if (!mGameThreadHandle)
{
CLog::WriteDebugLog(_T("mGameThreadHandle Error"));
End();
return FALSE;
}
mKeepThreadDestroyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!mKeepThreadDestroyEvent)
{
CLog::WriteDebugLog(_T("mKeepThreadDestroyEvent Error"));
End();
return FALSE;
}
mKeepThreadHandle = CreateThread(NULL, 0, ::KeepThreadCallback, this, 0, NULL);
if (!mKeepThreadHandle)
{
CLog::WriteDebugLog(_T("mKeepThreadHandle Error"));
End();
return FALSE;
}
CLog::WriteDebugLog(_T("IOCP Load"));
return TRUE;
}
BOOL CTestOneIocp::End()
{
delete m_ListenSession;
delete m_UserManager;
return 0;
}
VOID CTestOneIocp::GameThreadCallback(VOID)
{
// while (TRUE)
{
PACKET_DATA data;
ZeroMemory(&data, sizeof(PACKET_DATA));
if (g_QueuePacket.Pop(data))
{
CPacketSession* pPacketSession = data.user;
DWORD dataLength = data.dataLength;
DWORD Protocol = 0;
BYTE Packet[MAX_BUFFER_LENGTH] = { 0, };
DWORD PacketLength = 0;
if (pPacketSession->ReadPacketForIocp(dataLength))
{
while (pPacketSession->GetPacket(Protocol, Packet, PacketLength))
{
switch (Protocol)
{
case PT_GAME_PROTOCOL:
{
CLog::WriteDebugLog(_T(" == Connect Server == "));
CPacketSession* tempSession = (CPacketSession*)m_UserManager->GetSession(pPacketSession);
m_ServerOne->GetSession()->SetServerSession(tempSession);
m_ServerOne->GetSession()->SendPacket(PT_LOGIN_PROTOCOL, Packet, PacketLength);
break;
}
case PT_REQ_LOGIN:
{
CLog::WriteDebugLog(_T("== PT_REQ_LOGIN"));
READ_PACKET(PT_REQ_LOGIN);
BYTE LoginBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_ServerOne->GetSession()->SendPacket(
PT_SEND_LOGIN,
LoginBuffer,
WRITE_PT_SEND_LOGIN(LoginBuffer, Data.strUserId, 0));
break;
}
default:
break;
}
}
}
}
}
}
VOID CTestOneIocp::KeepThreadCallback(VOID)
{
DWORD KeepAlive = 0xFFFF;
while (TRUE)
{
}
}
VOID CTestOneIocp::OnIoRead(VOID * object, DWORD dataLength)
{
CNetworkSession* pNetworkSession = (CNetworkSession*)object;
CPacketSession *pPacketSession = (CPacketSession*)pNetworkSession;
PACKET_DATA data;
data.user = pPacketSession;
data.dataLength = dataLength;
g_QueuePacket.Push(data);
if (!pPacketSession->InitializeReadForIocp())
{
CLog::WriteDebugLog(_T("OnIoRead Error"));
}
}
VOID CTestOneIocp::OnIoWrote(VOID * object, DWORD dataLength)
{
CNetworkSession* pNetworkSession = (CNetworkSession*)object;
CPacketSession *pPacketSession = (CPacketSession*)pNetworkSession;
pPacketSession->WriteComplete();
}
VOID CTestOneIocp::OnIoConnected(VOID * object)
{
CNetworkSession* pNetworkSession = (CNetworkSession*)object;
CPacketSession *pPacketSession = (CPacketSession*)pNetworkSession;
CUserSession *user = (CUserSession*)pPacketSession;
if (!CIocp::RegisterSocketToIocp(user->GetSocket(), (ULONG_PTR)user))
{
CLog::WriteDebugLog(_T("! OnIoConnected : CIocp::RegisterSocketToIocp"));
End();
return;
}
if (!user->InitializeReadForIocp())
{
CLog::WriteDebugLog(_T("! OnIoConnected : CIocp::InitializeReadForIocp"));
End();
return;
}
user->SetIsConnected(TRUE);
CLog::WriteDebugLog(_T("# New client connected : 0x%x(= %d)"), user, user->GetSocket());
}
VOID CTestOneIocp::OnIoDisconnected(VOID * object)
{
CNetworkSession* pNetworkSession = (CNetworkSession*)object;
CPacketSession *pPacketSession = (CPacketSession*)pNetworkSession;
CUserSession *user = (CUserSession*)pPacketSession;
if (!user->Reload(m_ListenSession->GetSocket()))
{
CLog::WriteDebugLog(_T("! OnIoDisconnected : user->Reload"));
End();
return;
}
CLog::WriteLog(_T("# Client disconnected : 0x%x(0x%x)\n"), user, user->GetSocket());
}
|
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
bool r[30],c1[30],c2[30];
int ans[30];
int n,sum;
void print()
{
for (int i = 1;i < n; i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n]);
sum++;
}
void dfs(int k)
{
//cout << k << " " << n << endl;
if (k > n)
{//cout << "!" << endl;
//print();
sum++;
return;
}
for (int i = 1;i <= n; i++)
if (!r[i] && !c1[k-i+n] && !c2[k+i])
{//cout << k << " " << i << endl;
ans[k] = i;
r[i] = c1[k-i+n] = c2[k+i] = true;
dfs(k+1);
r[i] = c1[k-i+n] = c2[k+i] = false;
}
}
int main()
{
while (scanf("%d",&n) != EOF && n)
{
sum = 0;
dfs(1);
printf("%d\n",sum);
}
return 0;
}
|
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() < 2) return 0;
vector<int> buy(prices.size(),0);
vector<int> sell(prices.size(),0);
buy[0] = -prices[0];
buy[1] = prices[1]>prices[0]?-prices[0]:-prices[1];
sell[0] = 0;
sell[1] = prices[1]-prices[0];
sell[1] = sell[1]>0?sell[1]:0;
for(int i = 2; i < prices.size(); i++) {
buy[i] = max(buy[i-1], sell[i-2]-prices[i]);
sell[i] = max(buy[i-1]+prices[i], sell[i-1]);
}
return sell.back();
}
};
|
#include<bits/stdc++.h>
using namespace std;
int main(){
string str;
cin>>str;
int cnt=0;
int p=0;
for(int i=0;i<str.length();i++){
if(str[i]!='0'){
p=i;
break;
}
}
str.erase(0,p);
p=-1;
for(int i=str.length()-1;i>=0;i--){
if(str[i]!='0'){
p=i+1;
break;
}
}
str.erase(p);
string::iterator it=str.begin();
if(str[0]=='.')
str.insert(it,'0');
p=str.find('.');
if(p!=string::npos){
if(str[p-1]=='0'){
for(int i=p;i<str.length();i++){
if(str[i]=='0'){
cnt++;
}
else{
p=i;
break;
}
}
if()
}
}
}
|
//66
class Solution { //quick but ugly
public:
vector<int> plusOne(vector<int>& digits) {
int next = 1;
for(int i=digits.size()-1;i>=0;--i){
if(next!=0){
if(digits[i]!=9){
++digits[i];
next = 0;
return digits;
}else{
digits[i]=0;
}
}else{
return digits;
}
}
digits[0] = 1;
digits.push_back(0);
return digits;
}
};
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int next = 1;
for(int i=digits.size()-1;i>=0;--i){
if(digits[i]!=9&&next!=0){
++digits[i];
next = 0;
break;
}else if(digits[i]==9&&next!=0){
digits[i]=0;
}else{
break;
}
}
if(next == 1){ //special case
digits[0] = 1;
digits.push_back(0);
}
return digits;
}
};
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int next = 1;
for(int i=digits.size()-1;i>=0;--i){
if(digits[i]!=9&&next==0){
break;
}else if(digits[i]!=9&&next!=0){
++digits[i];
next = 0;
break;
}else if(digits[i]==9&&next==0){
break;
}else if(digits[i]==9&&next!=0){
digits[i]=0;
}
}
if(next == 1){ //special case
digits[0] = 1;
digits.push_back(0);
}
return digits;
}
};
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int sign = 0;
for(int i=0;i<digits.size();++i){
if(digits[i]!=9){
sign = 1;
}
}
if(sign == 0){ //special case
for(int i=0;i<digits.size();++i){
digits[i] = 0;
}
digits[0] = 1;
digits.push_back(0);
return digits;
}else if(sign == 1){
int next = 1;
for(int i=digits.size()-1;i>=0;--i){
if(digits[i]!=9&&next==0){
return digits;
}else if(digits[i]!=9&&next!=0){
++digits[i];
return digits;
}else if(digits[i]==9&&next==0){
return digits;
}else if(digits[i]==9&&next!=0){
digits[i]=0;
}
}
}
}
};
|
#pragma once
#include "../Toolbox/Toolbox.h"
#include "../Idioms/NotCopiable/NotCopiable.h"
#include "../Graphics/Color/Color.h"
#include <string>
namespace ae
{
class WindowSettings;
class Renderer;
/// <summary>
/// Utility class that can be used to create application runned by the engine.<para/>
/// It can be sent to the engine that will handle all the initialization, updates and rendering
/// and call the events of the application.<para/>
/// Usage of this class require C++17 or above compiler.
/// </summary>
class AERO_CORE_EXPORT Application : public NotCopiable
{
public:
/// <summary>First event called, just before the window creation.</summary>
/// <param name="_PathToEngineData">Path to the engine data to setup if the folders architecture is not the default one.</param>
virtual void OnApplicationStart( AE_InOut std::string& _PathToEngineData );
/// <summary>Event called just before the creation of the window.</summary>
/// <param name="_Settings">Setting prefilled, can be changed by the user.</param>
virtual void OnWindowCreation( AE_InOut WindowSettings& _Settings );
/// <summary>Event called just before the creation of the editor.</summary>
/// <param name="_InitFileName">Name of the file of the UI configuration that can be changed.</param>
virtual void OnEditorCreation( AE_InOut std::string& _InitFileName );
/// <summary>Event called before the first update.</summary>
virtual void OnInitialize();
/// <summary>Event called just before the update of the engine (inputs, physics, ...).</summary>
virtual void OnPreUpdate();
/// <summary>Event called just after the update of the engine (inputs, physics, ...)</summary>
virtual void OnUpdate();
/// <summary>Event called before starting rendering.</summary>
/// <param name="_MustClear">The rendering target must be clear ?</param>
/// <param name="_ClearColor">The color the clear the target with.</param>
virtual void OnPreRender( AE_InOut Bool& _MustClear, AE_InOut Color& _ClearColor );
/// <summary>Envet called during the rendering.</summary>
/// <param name="_Renderer">The current bound renderer (can be the viewport or the final render target).</param>
virtual void OnRender( Renderer& _Renderer );
/// <summary>Event called after the rendering.</summary>
virtual void OnPostRender();
/// <summary>
/// Event called just before the editor is updated.<para/>
/// Not called if the editor is not asked when sending the application to the engine.
/// </summary>
virtual void OnPreEditorUpdate();
/// <summary>
/// Event called just after the editor is updated.<para/>
/// Not called if the editor is not asked when sending the application to the engine.
/// </summary>
virtual void OnEditorUpdate();
/// <summary>Event called just before the editor is drawn.</summary>
/// <param name="_ShowEditor">Must the editor be drawn ?</param>
virtual void OnEditorPreRender( AE_InOut Bool& _ShowEditor );
/// <summary>
/// Event called juste after the editor is drawn.<para/>
/// Not called if the editor is not drawn.
/// </summary>
virtual void OnEditorRender();
/// <summary>Called if the window is closing, just before its destruction.</summary>
virtual void OnDeinitialize();
};
}
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
vector<int> helper(vector<vector<int>> &matrix, int col, int row){
vector<int> res;
if(col == 0 || row == 0) return res;
if(row == 1){
for(int i=0;i<col;i++)
res.push_back(matrix[0][i]);
return res;
}
if(col == 1){
for(int i=0;i<row;i++)
res.push_back(matrix[i][0]);
return res;
}
for(int i=0;i<col;i++)
res.push_back(matrix[0][i]);
for(int i=1;i<row-1;i++)
res.push_back(matrix[i][col-1]);
for(int i=col-1;i>=0;i--)
res.push_back(matrix[row-1][i]);
for(int i=row-2;i>0;i--)
res.push_back(matrix[i][0]);
vector<vector<int>> tempMatrix;
for(int i=1;i<row-1;i++){
vector<int> oneline;
for(int j=1;j<col-1;j++){
oneline.push_back(matrix[i][j]);
}
tempMatrix.push_back(oneline);
}
vector<int> post = helper(tempMatrix,col-2,row-2);
res.insert(res.end(),post.begin(),post.end());
return res;
}
vector<int> spiralOrder(vector<vector<int>> &matrix){
vector<int> res;
int row = matrix.size();
if(row == 0) return res;
int col = matrix[0].size();
res = helper(matrix,col,row);
return res;
}
int main(){
int row,col,k;
cin >> row >> col;
vector<vector<int>> matrix(row,vector<int>(col,0));
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cin >> k;
matrix[i][j] = k;
}
}
for(auto x : matrix){
for(auto y : x)
cout << y << " ";
cout << endl;
}
vector<int> res = spiralOrder(matrix);
for(auto &x : res) cout << x << endl;
}
|
../forwarding/forwarding.cpp
|
/*Complete the function below
Which contains 2 arguments
1) root of the tree formed while encoding
2) Encoded String*/
string decode_file(struct MinHeapNode* root, string s)
{
//add code here.
string ans ="";
struct MinHeapNode*curr = root;
for(int i = 0;i<s.size();i++){
if(s[i] == '0'){
curr = curr->left;
}
else
curr = curr->right;
if(curr->right == NULL && curr->left == NULL){
ans+=curr->data;
curr = root;
}
}
return ans+'\0';
}
|
#include "compman.h"
compman::compman(sf::Texture* texture, sf::Vector2u imageCount, float switchTime, float speed, float jumpHeight)
:animation(texture, imageCount, switchTime), canJump(0)
{
this->speed = speed;
this->jumpHeight = jumpHeight;
row = 0;
faceRight = true;
body.setSize(sf::Vector2f(75.0f, 75.0f));
body.setOrigin(body.getSize() / 2.2f);
body.setPosition(3072.f, 706.5f);
body.setTexture(texture);
}
compman::~compman()
{
}
void compman::Update(float deltaTime)
{
velocity.x = 0.0f;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
velocity.x -= speed;
faceRight = false;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
velocity.x += speed;
faceRight = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && canJump)
{
canJump = false;
velocity.y = -sqrtf(2.0f * 980.0f * jumpHeight);
//std::cout << "JUMP !!!" << std::endl;
}
velocity.y += 980.0f * deltaTime;
//std::cout << velocity.y << std::endl;
if (!canJump)
{
if (velocity.y < 0)
{
row = 2;
}
if (velocity.y > 0)
{
row = 3;
}
}
else
{
if (velocity.x == 0.0f)
{
row = 0;
}
else
{
row = 1;
if (velocity.x > 0.0f) {
faceRight = true;
}
else {
faceRight = false;
}
}
}
animation.Update(row, deltaTime, faceRight);
body.setTextureRect(animation.uvRect);
body.move(velocity * deltaTime);
}
void compman::Draw(sf::RenderWindow& window)
{
window.draw(body);
}
void compman::OnCollision(sf::Vector2f direction)
{
if (direction.x < 0.0f)
{
//Collision of the left.
velocity.x = 0.0f;
}
else if (direction.x > 0.0f)
{
//Collision of the right.
velocity.x = 0.0f;
}
if (direction.y < 0.0f)
{
//Collision of the bottom.
velocity.y = 0.0f;
canJump = true;
}
else if (direction.y > 0.0f)
{
velocity.y = 0.0f;
}
}
const Vector2f& compman::getPosition() const
{
return this->body.getPosition();
}
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STUDENTSMAX 3
#define SUBJECTSMAX 3
typedef struct {
int roll;
char *name;
float subjects[SUBJECTSMAX];
float avg;
} student;
int getInt(const char *msg) {
int x;
printf("%s", msg);
scanf("%d", &x);
return x;
}
float getReal(const char *msg, int n) {
float x;
printf(msg, n);
scanf("%f", &x);
return x;
}
char *strInputs[100];
int strs = 0;
char *getStr(const char *msg) {
strInputs[strs] = (char *)malloc(sizeof(char) * 20);
printf("%s", msg);
scanf("%s", strInputs[strs]);
++strs;
return strInputs[strs - 1];
}
void freeStrInputs() {
for (int i = 0; i < strs; ++i)
free(strInputs[i]);
}
int main() {
int noOfStudents = getInt("Enter number of students: ");
student students[noOfStudents];
for (int i = 0; i < noOfStudents; ++i) {
printf("\tStudent %d\n", i + 1);
students[i].roll = getInt("Enter roll number: ");
students[i].name = getStr("Enter name: ");
students[i].avg = 0;
for (int j = 0; j < SUBJECTSMAX; ++j) {
students[i].subjects[j] = getReal("Enter subject %d: ", j + 1);
students[i].avg += students[i].subjects[j];
}
students[i].avg /= SUBJECTSMAX;
}
printf("\nName\tAverage Marks");
for (int i = 0; i < noOfStudents; ++i) {
printf("\n%s\t%f", students[i].name, students[i].avg);
}
printf("\n");
freeStrInputs();
return 0;
}
|
#include "gf2_polynomial_tests.h"
#include "gf2_polynomial.h"
#include "test_assert.h"
#include <sstream>
namespace {
void test_construction() {
std::vector<uint8_t> c = {{1,0,0,1,1,0}};
auto p = make_gf2_polynomial(c);
TEST_EQ(p.coefficients.size(), 5);
}
void test_stream() {
std::vector<uint8_t> c = {{1,0,0,1,1,0}};
auto p = make_gf2_polynomial(c);
std::stringstream ss;
ss << p;
TEST_EQ(ss.str(), std::string("X^4 + X^3 + 1"));
}
void test_stream_2() {
gf2_polynomial g;
g.coefficients.push_back(1);
g.coefficients.push_back(2);
g.coefficients.push_back(3);
g.coefficients.push_back(4);
g.coefficients.push_back(5);
g.coefficients.push_back(6);
std::stringstream ss;
ss << g;
TEST_EQ(ss.str(), std::string("X^4 + X^2 + 1"));
}
void test_degree() {
gf2_polynomial g;
g.coefficients.push_back(1);
g.coefficients.push_back(2);
g.coefficients.push_back(3);
g.coefficients.push_back(4);
g.coefficients.push_back(5);
g.coefficients.push_back(6);
TEST_EQ(degree(g), 4);
}
void test_equal() {
gf2_polynomial g1;
g1.coefficients.push_back(1);
g1.coefficients.push_back(2);
g1.coefficients.push_back(3);
g1.coefficients.push_back(4);
g1.coefficients.push_back(5);
g1.coefficients.push_back(6);
gf2_polynomial g2;
g2.coefficients.push_back(1);
g2.coefficients.push_back(0);
g2.coefficients.push_back(1);
g2.coefficients.push_back(0);
g2.coefficients.push_back(1);
TEST_ASSERT(g1==g2);
gf2_polynomial g3;
gf2_polynomial g4;
g4.coefficients.push_back(2);
g4.coefficients.push_back(4);
g4.coefficients.push_back(6);
g4.coefficients.push_back(8);
TEST_ASSERT(g3==g4);
TEST_ASSERT(g1!=g3);
TEST_ASSERT(g1!=g4);
TEST_ASSERT(g2!=g3);
TEST_ASSERT(g2!=g4);
}
void test_add() {
gf2_polynomial g1 = make_gf2_polynomial({{0,1,1,1}});
gf2_polynomial g2 = make_gf2_polynomial({{1,0,1,0,1}});
auto g3 = g1+g2;
TEST_ASSERT(g3==make_gf2_polynomial({{1,1,0,1,1}}));
}
void test_sub() {
gf2_polynomial g1 = make_gf2_polynomial({{0,1,1,1}});
gf2_polynomial g2 = make_gf2_polynomial({{1,0,1,0,1}});
auto g3 = g1-g2;
TEST_ASSERT(g3==make_gf2_polynomial({{1,1,0,1,1}}));
}
void test_mul() {
gf2_polynomial g1 = make_gf2_polynomial({{0,1,1,1}});
gf2_polynomial g2 = make_gf2_polynomial({{1,0,1,0,1}});
auto g3 = g1*g2;
TEST_ASSERT(g3==make_gf2_polynomial({{0,1,1,0,1,0,1,1}}));
}
void test_derivative() {
gf2_polynomial g1 = make_gf2_polynomial({{0,0,0,3,101,6,8}});
gf2_polynomial g2 = derivative(g1);
TEST_ASSERT(g2==make_gf2_polynomial({{0,0,1}}));
}
void test_xn() {
gf2_polynomial g = make_xn(3);
TEST_ASSERT(g==make_gf2_polynomial({{0,0,0,1}}));
g = make_xn(2);
TEST_ASSERT(g==make_gf2_polynomial({{0,0,1}}));
g = make_xn(1);
TEST_ASSERT(g==make_gf2_polynomial({{0,1}}));
g = make_xn(0);
TEST_ASSERT(g==make_gf2_polynomial({1}));
}
void test_euclidean_division() {
gf2_polynomial a = make_gf2_polynomial({{0,0,0,1,1}});
gf2_polynomial b = make_gf2_polynomial({{0,0,1}});
auto div = euclidean_division(a, b);
TEST_ASSERT(div.first==make_gf2_polynomial({{0,1,1}}));
TEST_ASSERT(div.second==make_gf2_polynomial({0}));
a = make_gf2_polynomial({{0,0,0,1,1,0,1,0}});
b = make_gf2_polynomial({{0,1,1,1}});
div = euclidean_division(a, b);
//std::cout << a << " / " << b << " = (" << div.first << "," << div.second << ")\n";
TEST_ASSERT(a == div.first*b + div.second);
TEST_ASSERT(a/b == div.first);
TEST_ASSERT(a%b == div.second);
b = make_gf2_polynomial({{0,0,0,1,1,0,1,0}});
a = make_gf2_polynomial({{0,1,1,1}});
div = euclidean_division(a, b);
//std::cout << a << " / " << b << " = (" << div.first << "," << div.second << ")\n";
TEST_ASSERT(a == div.first*b + div.second);
TEST_ASSERT(a/b == div.first);
TEST_ASSERT(a%b == div.second);
}
void test_gcd() {
gf2_polynomial a = make_gf2_polynomial({{0,0,0,1,1}});
gf2_polynomial b = make_gf2_polynomial({{0,0,3,4}});
gf2_polynomial g = gcd(a, b);
TEST_ASSERT(g==make_gf2_polynomial({0,0,1}));
TEST_ASSERT(a%g==make_gf2_polynomial({0}));
TEST_ASSERT(b%g==make_gf2_polynomial({0}));
a = make_gf2_polynomial({{0,0,0,1,1}});
b = make_gf2_polynomial({{0,1,3,4}});
g = gcd(a, b);
TEST_ASSERT(g==make_gf2_polynomial({0,1,1}));
TEST_ASSERT(a%g==make_gf2_polynomial({0}));
TEST_ASSERT(b%g==make_gf2_polynomial({0}));
}
void test_hex_to_gf2_polynomial() {
gf2_polynomial g = hex_to_gf2_polynomial("c");
TEST_ASSERT(g==make_gf2_polynomial({0,0,1,1}));
TEST_ASSERT(gf2_polynomial_to_hex(g)==std::string("c"));
TEST_ASSERT(gf2_polynomial_to_hex(hex_to_gf2_polynomial("a466cfdc"))==std::string("a466cfdc"));
}
void test_sqrt() {
gf2_polynomial g = make_gf2_polynomial({{1,0,1}});
auto s = sqrt(g);
TEST_ASSERT(s==make_gf2_polynomial({1,1}));
g = hex_to_gf2_polynomial("a466cfdc");
TEST_ASSERT(g == sqrt(power(g,2)));
}
void test_square_free_factorization() {
gf2_polynomial g = hex_to_gf2_polynomial("c");
auto R = square_free_factorization(g);
auto p = R.front();
for (int i = 1; i < R.size(); ++i)
p = p * R[i];
TEST_EQ(2, R.size());
TEST_ASSERT(gf2_polynomial_to_hex(p) == gf2_polynomial_to_hex(g));
}
void test_distinct_degree_factorization() {
gf2_polynomial g = make_gf2_polynomial({{0,0,1,1,0,1,0,0,1}});
auto S = distinct_degree_factorization(g);
auto p = make_xn(0);
for (auto s : S) {
//std::cout << s.first << std::endl;
p = p*s.first;
}
TEST_ASSERT(p == g);
TEST_EQ(3, S.size());
}
void test_equal_degree_factorization() {
gf2_polynomial g = hex_to_gf2_polynomial("73af");
uint64_t d = degree(g);
auto factors = equal_degree_factorization(g, d/2);
TEST_EQ(2, factors.size());
TEST_ASSERT(gf2_polynomial_to_hex(factors[0]) == std::string("e5") || gf2_polynomial_to_hex(factors[1]) == std::string("e5"));
TEST_ASSERT(gf2_polynomial_to_hex(factors[0]) == std::string("83") || gf2_polynomial_to_hex(factors[1]) == std::string("83"));
}
void test_equal_degree_factorization_2() {
gf2_polynomial g = hex_to_gf2_polynomial("738377c1");
uint64_t d = degree(g);
auto factors = equal_degree_factorization(g, d/2);
TEST_EQ(2, factors.size());
TEST_ASSERT(gf2_polynomial_to_hex(factors[0]) == std::string("b0c5") || gf2_polynomial_to_hex(factors[1]) == std::string("b0c5"));
TEST_ASSERT(gf2_polynomial_to_hex(factors[0]) == std::string("cd55") || gf2_polynomial_to_hex(factors[1]) == std::string("cd55"));
}
} // namespace
void run_all_gf2_polynomial_tests() {
test_construction();
test_stream();
test_stream_2();
test_degree();
test_equal();
test_add();
test_sub();
test_mul();
test_derivative();
test_xn();
test_euclidean_division();
test_gcd();
test_hex_to_gf2_polynomial();
test_sqrt();
test_square_free_factorization();
test_distinct_degree_factorization();
test_equal_degree_factorization();
test_equal_degree_factorization_2();
}
|
/*****************************************************************************************************************
* File Name : arrayqueue.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\tutorials\nptel\DSAndAlgo\lecture03\arrayqueue.h
* Created on : Dec 29, 2013 :: 7:07:17 PM
* Author : AVINASH
* Testing Status : TODO
* URL : TODO
*****************************************************************************************************************/
/************************************************ Namespaces ****************************************************/
using namespace std;
using namespace __gnu_cxx;
/************************************************ User Includes *************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <programming/ds/tree.h>
#include <programming/ds/linkedlist.h>
#include <programming/utils/treeutils.h>
#include <programming/utils/llutils.h>
/************************************************ User defined constants *******************************************/
#define null NULL
#define SIZE_OF_QUEUE 30
/************************************************* Main code ******************************************************/
#ifndef ARRAYQUEUE_H_
#define ARRAYQUEUE_H_
int queue[SIZE_OF_QUEUE];
unsigned int front = -1;
unsigned int rear = 0;
bool isQueueEmpty(){
}
bool isQueueFull(){
}
void enqueue(int userInput){
if(isQueueFull()){
printf("Queue is full\n");
return;
}
queue[rear] = userInput;
rear = (rear+1)%SIZE_OF_QUEUE;
}
void deque(){
if(isQueueEmpty()){
printf("Queue is empty\n");
return;
}
queue[front++] = 0;
}
unsigned int sizeOfQueue(){
return SIZE_OF_QUEUE - front + rear;
}
int front(){
if(isQueueEmpty()){
printf("Queue is empty\n");
return INT_MIN;
}
return queue[front];
}
#endif /* ARRAYQUEUE_H_ */
/************************************************* End code *******************************************************/
|
#include<iostream>
#include<string>
using namespace std;
class Vehicle {
protected:
string vehicleName;
string vehicleModel;
string vehicleType;
public:
Vehicle() {
}
void setVehicleName(string vehicleName) {
this->vehicleName = vehicleName;
}
void setVehicleModel(string vehicleModel) {
this->vehicleModel = vehicleModel;
}
void setVehicleType(string vehicleType) {
this->vehicleType = vehicleType;
}
string getVechileName() {
return this->vehicleName;
}
string getVechileModel() {
return this->vehicleModel;
}
string getVechileType() {
return this->vehicleType;
}
virtual void drive()=0;
virtual void fuelAmount()=0;
virtual void applyBreaks()=0;
~Vehicle() {
}
};
class Car : public Vehicle {
private:
int carEngine;
int carDoors ;
int carWheels ;
int fuel;
void setCarEngine(){
this->carEngine = 1;
}
void setCarWheels(){
this->carWheels = 4;
}
void setCarDoors(){
this->carDoors = 4;
}
public:
Car() {
}
void setFuel(int fuel){
this->fuel = fuel;
}
int getFuel(){
return this->fuel;
}
void drive() {
cout << "Car is started driving."<<endl;
}
void fuelAmount() {
cout << "Car fuel ammount is "<<this->fuel <<"liters. " << endl;
}
void applyBreaks() {
cout << "Car breaks applied." << endl;
}
~Car() {
}
};
class Motorcycle : public Vehicle {
private:
int motorcycleEngine ;
int motorcycleWheels ;
int fuel;
void setMotorcycleEngine(){
this->motorcycleEngine = 1;
}
void setMotorcycleWheels(){
this->motorcycleWheels = 2;
}
public:
Motorcycle() {
}
void setFuel(int fuel){
this->fuel = fuel;
}
int getFuel(){
return this->fuel;
}
void drive() {
cout << "Motorcycle is started driving." << endl;
}
void fuelAmount() {
cout << "Motorcycle fuel ammount is "<<this->fuel <<"liters. "<< endl;
}
void applyBreaks() {
cout << "Motorcycle breaks applied." << endl;
}
~Motorcycle() {
}
};
int main() {
Car car;
Motorcycle bike;
Vehicle* v;
v = &car;
v->drive();
v = &bike;
v->drive();
v->applyBreaks();
v->setVehicleName("Honda");
cout<<v->getVechileName();
return 0;
}
|
#ifndef MORPHOLOGY_H
#define MORPHOLOGY_H
#include <QImage>
#include <QPoint>
namespace Morphology
{
// Any colour that is not Qt::color1 is assumed to be Qt::color0.
// Origin specifies the point on the kernel to use as the origin.
// The passed images should be in ARGB32 format.
void dilate(QImage& image, const QImage &kernel, const QPoint &origin);
void erode(QImage& image, const QImage &kernel, const QPoint &origin);
void thresholdBrightness(QImage &image, unsigned char brightness);
void thresholdAlpha(QImage &image, unsigned char alpha);
void invert(QImage &image);
QImage exor(const QImage &i1, const QImage &i2); // Must have same dimension
}
#endif // MORPHOLOGY_H
|
template <class T>
class Heap{
struct Item{
Item( T data );
~Item();
Item* nxt;
Item* lst;
T dta;
}
Boolean bubble( Item* itm );
Item* root;
public:
Heap();
~Heap();
void append(T data);
T pop();
}
|
//
// Transaction.hpp
// EX05_05
//
// Created by Eben Schumann on 11/1/16.
// Copyright ยฉ 2016 Eben Schumann. All rights reserved.
//
#ifndef Transaction_hpp
#define Transaction_hpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Transaction
{
private:
int Date; // This represents the date that the transaction occurs
int year; // This represents the year that the transaction occurs
int month; // This represents the month that the transaction occurs
int day; // This represents the day that the transaction occurs
char type; // This represents the type of transaction that occurs
double amount; // This represents the amount of money that is added or removed
double balance; // This represents the balance of the account
string description; // This represents the reason that the user performs the transaction
public:
Transaction(); // default constructor
Transaction(char, double, double, string); // This takes data from the user to create a transaction
void setDate(int, int, int); // This sets the variable for the date
int getYear(); // return the year
int getMonth(); // returns the month
int getDay(); // returns the day
void setType(char); // this sets the type of transaction
void setAmount(double); // this sets the amount of money that was moved to or from the account
void setBalance(double); // this sets the ablance that remains after the transactions
void setDescription(string); // this sets the description that the user gives for why they made a transaction
//void getDate(); // returns the date of the transaction
char getType(); // returns the type of transaction that occured
double getAmount(); // returns the amount of money that was moved
double getBalance(); // returns the balance of the account after the transaction occurs
string getDescription(); // returns the description for the user performing the transaction
void displayTransactions(); // this will display the transactiosn that were performed
};
#endif /* Transaction_hpp */
|
#include "prims.hpp"
#include "vm.hpp"
#include "defs.hpp"
#include "process.hpp"
#include "utils.hpp"
#include "mmobj.hpp"
#include "mec_image.hpp"
#include "net_prims.hpp"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <gc_cpp.h>
#include "gc/gc_allocator.h"
namespace fs = ::boost::filesystem;
#define DBG(...) if(_log._enabled) { _log << _log.yellow + _log.bold + "[prim|" << __FUNCTION__ << "] " << _log.normal << __VA_ARGS__; }
#define WARNING() MMLog::warning() << "[prim|" << __FUNCTION__ << "] " << _log.normal
#define ERROR() MMLog::error() << "[prim|" << __FUNCTION__ << "] " << _log.normal
static MMLog _log(LOG_PRIMS);
static inline bool is_numeric(Process* proc, oop o) {
return is_small_int(o) || proc->mmobj()->mm_object_vt(o) == proc->vm()->core()->get_prime("LongNum");
}
static inline number extract_number(Process* proc, oop o) {
if (is_small_int(o)) {
return untag_small_int(o);
} else if (proc->mmobj()->mm_object_vt(o) == proc->vm()->core()->get_prime("LongNum")) {
return proc->mmobj()->mm_longnum_get(proc, o);
} else {
proc->raise("TypeError", "Expecting numeric value");
}
return 0; // unreachable
}
static int prim_remote_repl_compile_module(Process* proc) {
oop module_name = proc->get_arg(0);
char* mmpath = getenv("MEME_PATH");
std::stringstream s;
s << "python -m pycompiler.compiler "<< mmpath << proc->mmobj()->mm_string_stl_str(proc, module_name) << ".me";
DBG("Executing ... " << s.str() << std::endl);
if (system(s.str().c_str()) == 0) {
proc->stack_push(MM_TRUE);
} else {
proc->stack_push(MM_FALSE);
}
return 0;
}
static int prim_remote_repl_instantiate_module(Process* proc) {
oop oop_module_name = proc->get_arg(0);
char* module_name = proc->mmobj()->mm_string_cstr(proc, oop_module_name);
try {
DBG("instantiating module" << module_name << endl);
oop imod = proc->vm()->instantiate_meme_module(proc, module_name,
proc->mmobj()->mm_list_new());
proc->stack_push(imod);
return 0;
} catch(std::invalid_argument e) {
DBG("instantiating module failed: " << e.what() << endl);
oop ex = proc->mm_exception(
"ImportError",
(std::string("could not import module ") + e.what()).c_str());
DBG("returning mm_exception : " << ex << endl);
proc->stack_push(ex);
return PRIM_RAISED;
}
}
static int prim_io_print(Process* proc) {
oop obj = proc->get_arg(0);
DBG("---- prim_print" << endl);
int exc;
oop res = proc->send_0(obj, proc->vm()->new_symbol("toString"), &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
std::cout << proc->mmobj()->mm_string_stl_str(proc, res) << endl;
proc->stack_push(MM_NULL);
return 0;
}
static int prim_io_read_file(Process* proc) {
oop oop_path = proc->get_arg(0);
char* path = proc->mmobj()->mm_string_cstr(proc, oop_path);
std::fstream file;
file.open(path, std::fstream::in | std::fstream::binary);
int fsize;
char* text = read_file(file, &fsize);
proc->stack_push(proc->mmobj()->mm_string_new(text));
return 0;
}
static int prim_io_write_file(Process* proc) {
oop oop_path = proc->get_arg(0);
oop oop_text = proc->get_arg(1);
char* path = proc->mmobj()->mm_string_cstr(proc, oop_path);
std::string text = proc->mmobj()->mm_string_stl_str(proc, oop_text);
std::fstream file;
file.open(path, std::fstream::out | std::fstream::binary);
file << text;
file.close();
proc->stack_push(proc->mp());
return 0;
}
static int prim_io_open_file(Process* proc) {
oop oop_filepath = proc->get_arg(0);
oop oop_direction = proc->get_arg(1);
char* filepath = proc->mmobj()->mm_string_cstr(proc, oop_filepath);
std::fstream* file = new std::fstream;
if (oop_direction == proc->vm()->new_symbol("write")) {
file->open(filepath, std::fstream::out | std::fstream::binary);
proc->stack_push((oop)file);
return 0;
} else {
proc->raise("Exception", "TODO rest of io_open_file");
}
return 0; // unreachable
}
static int prim_io_write(Process* proc) {
std::fstream* file = (std::fstream*) proc->get_arg(0);
oop oop_text = proc->get_arg(1);
std::string text = proc->mmobj()->mm_string_stl_str(proc, oop_text);
*file << text;
proc->stack_push(proc->mp());
return 0;
}
static int prim_io_close(Process* proc) {
std::fstream* file = (std::fstream*) proc->get_arg(0);
file->close();
delete file;
proc->stack_push(proc->mp());
return 0;
}
static int prim_string_concat(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
std::string str_1 = proc->mmobj()->mm_string_stl_str(proc, self);
std::string str_2 = proc->mmobj()->mm_string_stl_str(proc, other);
std::string ret(str_1 + str_2);
oop oop_str = proc->mmobj()->mm_string_new(ret);
proc->stack_push(oop_str);
return 0;
}
static int prim_string_times(Process* proc) {
oop self = proc->dp();
number num = untag_small_int(proc->get_arg(0));
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string ret;
for (int i = 0; i < num; i++) {
ret += str;
}
oop oop_str = proc->mmobj()->mm_string_new(ret);
proc->stack_push(oop_str);
return 0;
}
static int prim_string_to_integer(Process* proc) {
oop self = proc->dp();
std::string str_1 = proc->mmobj()->mm_string_stl_str(proc, self);
number s = std::atol(str_1.c_str()); //TODO: check bounds
proc->stack_push(tag_small_int(s));
return 0;
}
static int prim_string_to_byte(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
if (str.length() != 1) {
proc->raise("TypeError", "Expecting string of length 1");
}
proc->stack_push(tag_small_int((unsigned char)str[0]));
return 0;
}
static int prim_string_as_hex(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
number x;
std::stringstream ss;
ss << std::hex << str;
ss >> x;
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, x));
return 0;
}
static int prim_string_equal(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
if (proc->mmobj()->mm_is_string(other)) {
std::string str_1 = proc->mmobj()->mm_string_stl_str(proc, self);
std::string str_2 = proc->mmobj()->mm_string_stl_str(proc, other);
if (str_1 == str_2) {
proc->stack_push(MM_TRUE);
} else {
proc->stack_push(MM_FALSE);
}
} else {
proc->stack_push(MM_FALSE);
}
return 0;
}
static int prim_string_lt(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
if (proc->mmobj()->mm_is_string(other)) {
std::string str_1 = proc->mmobj()->mm_string_stl_str(proc, self);
std::string str_2 = proc->mmobj()->mm_string_stl_str(proc, other);
if (str_1 < str_2) {
proc->stack_push(MM_TRUE);
} else {
proc->stack_push(MM_FALSE);
}
} else {
proc->stack_push(MM_FALSE);
}
return 0;
}
static int prim_string_size(Process* proc) {
oop self = proc->dp();
number len = proc->mmobj()->mm_string_size(proc, self);
proc->stack_push(tag_small_int(len));
return 0;
}
static int prim_string_count(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
std::string str_1 = proc->mmobj()->mm_string_stl_str(proc, self);
std::string str_2 = proc->mmobj()->mm_string_stl_str(proc, other);
int count = 0;
const char* pos = str_1.c_str();
while ((pos = strstr(pos, str_2.c_str())) != NULL) { //TODO: make it work with \0 in the string
count++;
pos++;
}
proc->stack_push(tag_small_int(count));
return 0;
}
static int prim_string_find(Process* proc) {
oop self = proc->dp();
oop arg = proc->get_arg(0);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string str_arg = proc->mmobj()->mm_string_stl_str(proc, arg);
std::size_t pos = str.find(str_arg);
if (pos == std::string::npos) {
proc->stack_push(tag_small_int(-1));
} else {
proc->stack_push(tag_small_int(pos));
}
return 0;
}
static int prim_string_rindex(Process* proc) {
oop self = proc->dp();
oop arg = proc->get_arg(0);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string str_arg = proc->mmobj()->mm_string_stl_str(proc, arg);
std::size_t pos = str.rfind(str_arg);
if (pos == std::string::npos) {
proc->stack_push(tag_small_int(-1));
} else {
proc->stack_push(tag_small_int(pos));
}
return 0;
}
static int prim_string_rindex_from(Process* proc) {
oop self = proc->dp();
oop arg = proc->get_arg(0);
oop begin = proc->get_arg(1);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string str_arg = proc->mmobj()->mm_string_stl_str(proc, arg);
std::size_t pos = str.rfind(str_arg, untag_small_int(begin));
if (pos == std::string::npos) {
proc->stack_push(tag_small_int(-1));
} else {
proc->stack_push(tag_small_int(pos));
}
return 0;
}
static int prim_string_index(Process* proc) {
oop self = proc->dp();
oop arg = proc->get_arg(0);
if (!is_numeric(proc, arg)) {
proc->raise("IndexError", "string index should be a number");
}
number idx = untag_small_int(arg);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
if (idx < proc->mmobj()->mm_string_size(proc, self)) {
char res[2];
res[0] = str[idx];
res[1] = '\0';
proc->stack_push(proc->mmobj()->mm_string_new(res));
return 0;
} else {
proc->raise("IndexError", "out of bounds");
}
}
static int prim_string_from(Process* proc) {
oop self = proc->dp();
oop idx = proc->get_arg(0);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string sub = str.substr(untag_small_int(idx));
proc->stack_push(proc->mmobj()->mm_string_new(sub));
return 0;
}
static int prim_string_substr(Process* proc) {
oop self = proc->dp();
oop from = proc->get_arg(0);
oop max = proc->get_arg(1);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string sub = str.substr(untag_small_int(from), untag_small_int(max));
proc->stack_push(proc->mmobj()->mm_string_new(sub));
return 0;
}
#include <boost/algorithm/string/replace.hpp>
static int prim_string_replace_all(Process* proc) {
oop self = proc->dp();
oop what = proc->get_arg(0);
oop val = proc->get_arg(1);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string _what = proc->mmobj()->mm_string_stl_str(proc, what);
std::string _val = proc->mmobj()->mm_string_stl_str(proc, val);
std::string output = boost::replace_all_copy(str, _what, _val);
proc->stack_push(proc->mmobj()->mm_string_new(output));
return 0;
}
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
static std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
#include <boost/xpressive/xpressive.hpp>
using namespace boost;
using namespace xpressive;
static std::string escape_format_fun(smatch const &what)
{
std::string::size_type num;
num = atoi( what[1].str().c_str());
std::string ret;
ret += (char) num;
return ret;
}
static std::string str_escape(std::string str) {
std::string ret;
std::string null;
null += (char) 0;
std::string::iterator it = str.begin();
bool escaped = false;
for ( ; it < str.end(); it++) {
switch(*it) {
case '\\':
if (escaped) {
ret += '\\';
escaped = false;
break;
} else {
escaped = true;
break;
}
case '0':
if (escaped) {
ret += null;
escaped = false;
break;
} else {
goto def;
}
case 'n':
if (escaped) {
ret += '\n';
escaped = false;
break;
}
case 't':
if (escaped) {
ret += '\t';
escaped = false;
break;
}
case 'b':
if (escaped) {
ret += '\b';
escaped = false;
break;
}
case 'f':
if (escaped) {
ret += '\f';
escaped = false;
break;
}
case 'r':
if (escaped) {
ret += '\r';
escaped = false;
break;
}
case 'v':
if (escaped) {
ret += '\v';
escaped = false;
break;
}
case '"':
if (escaped) {
ret += '\"';
escaped = false;
break;
}
default:
goto def;
}
continue;
def:
if (escaped) {
ret += '\\';
}
escaped = false;
ret += *it;
}
return ret;
}
static int prim_string_unescape(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string ret = str_escape(str);
//\x[0-9]+
sregex exp = sregex::compile( "\\\\x(\\d+)");
ret = regex_replace(ret, exp, escape_format_fun);
oop oop_ret = proc->mmobj()->mm_string_new(ret);
proc->stack_push(oop_ret);
return 0;
}
static int prim_string_split(Process* proc) {
oop self = proc->dp();
oop sep = proc->get_arg(0);
std::string sep_str = proc->mmobj()->mm_string_stl_str(proc, sep);
std::string self_str = proc->mmobj()->mm_string_stl_str(proc, self);
oop ret = proc->mmobj()->mm_list_new();
if (sep_str.size() == 0) {
for (size_t i = 0; i < self_str.size(); i++) {
std::stringstream s;
s << self_str[i];
oop chr = proc->mmobj()->mm_string_new(s.str());
proc->mmobj()->mm_list_append(proc, ret, chr);
}
} else {
std::size_t pos = self_str.find(sep_str);
DBG("string: " << self_str << " split: " << sep_str << " pos: " << pos << endl);
if (pos == std::string::npos) {
proc->mmobj()->mm_list_append(proc, ret, self);
} else {
std::size_t pos, prev_pos = 0;
while ((pos = self_str.find(sep_str, prev_pos)) != std::string::npos) {
std::string str1 = self_str.substr(prev_pos, pos);
DBG("string: " << self_str << " str1: '" << str1 << "'" << endl);
oop oop_str1 = proc->mmobj()->mm_string_new(str1);
proc->mmobj()->mm_list_append(proc, ret, oop_str1);
prev_pos = pos + 1;
}
std::string str1 = self_str.substr(prev_pos);
DBG("string: " << self_str << " str1: '" << str1 << "'" << endl);
oop oop_str1 = proc->mmobj()->mm_string_new(str1);
proc->mmobj()->mm_list_append(proc, ret, oop_str1);
}
}
proc->stack_push(ret);
return 0;
}
static int prim_string_to_symbol(Process* proc) {
oop self = proc->dp();
proc->stack_push(proc->vm()->new_symbol(proc, self));
return 0;
}
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
static int prim_string_trim(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
std::string res = trim(str);
oop oop_res = proc->mmobj()->mm_string_new(res);
proc->stack_push(oop_res);
return 0;
}
static int prim_string_each(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
// DBG("prim_list_each: closure is: " << fun << endl);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
for (size_t i = 0; i < str.size(); i++) {
std::stringstream s;
s << str[i];
oop next = proc->mmobj()->mm_string_new(s.str());
DBG("string each[" << i << "] = " << next << endl);
int exc;
oop val = proc->call_2(fun, tag_small_int(i), next, &exc);
if (exc != 0) {
DBG("prim_string_each raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
DBG("string each[" << i << "] fun returned " << val << endl);
}
proc->stack_push(self);
return 0;
}
static int prim_string_map(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
// DBG("prim_list_each: closure is: " << fun << endl);
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
oop ret = proc->mmobj()->mm_list_new();
for (size_t i = 0; i < str.size(); i++) {
std::stringstream s;
s << str[i];
oop next = proc->mmobj()->mm_string_new(s.str());
DBG("string map[" << i << "] = " << next << endl);
int exc;
oop val = proc->call_1(fun, next, &exc);
if (exc != 0) {
DBG("prim_string_map raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
DBG("string map[" << i << "] fun returned " << val << endl);
proc->mmobj()->mm_list_append(proc, ret, val);
}
proc->stack_push(ret);
return 0;
}
static int prim_string_b64decode(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
DBG("decode: [" << str << "] " << str.size() << endl);
std::string dec = base64_decode(str);
DBG("decoded: [" << dec << "]" << endl);
oop oop_res = proc->mmobj()->mm_string_new(dec);
proc->stack_push(oop_res);
return 0;
}
static int prim_string_b64encode(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
DBG("encode: [" << str << "] " << str.size() << endl);
std::string enc = base64_encode(reinterpret_cast<const unsigned char*>(str.c_str()), str.length());
DBG("encoded: [" << enc << "]" << endl);
oop oop_res = proc->mmobj()->mm_string_new(enc);
proc->stack_push(oop_res);
return 0;
}
static int prim_string_only_spaces(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
for (size_t i = 0; i < str.size(); i++) {
if (str[i] != ' ' &&
str[i] != '\t' &&
str[i] != '\r' &&
str[i] != '\n') {
proc->stack_push(MM_FALSE);
return 0;
}
}
proc->stack_push(MM_TRUE);
return 0;
}
static int prim_string_only_digits(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
for (size_t i = 0; i < str.size(); i++) {
if (str[i] < '0' || str[i] > '9') {
proc->stack_push(MM_FALSE);
return 0;
}
}
proc->stack_push(MM_TRUE);
return 0;
}
static int prim_string_is_lower(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
for (size_t i = 0; i < str.size(); i++) {
if (str[i] < 'a' || str[i] > 'z') {
proc->stack_push(MM_FALSE);
return 0;
}
}
proc->stack_push(MM_TRUE);
return 0;
}
static int prim_string_is_upper(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_string_stl_str(proc, self);
for (size_t i = 0; i < str.size(); i++) {
DBG((str[i] < 'A') << (str[i] > 'Z') << endl);
if (str[i] < 'A' || str[i] > 'Z') {
proc->stack_push(MM_FALSE);
return 0;
}
}
proc->stack_push(MM_TRUE);
return 0;
}
/// numeric
static int prim_numeric_sum(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
number n_res;
if (__builtin_add_overflow(n_self, n_other, &n_res)) {
proc->raise("Overflow", "result of + overflows");
} else {
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, n_res));
return 0;
}
return 0; // unreachable
}
static int prim_numeric_sub(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
number n_res;
if (__builtin_sub_overflow(n_self, n_other, &n_res)) {
proc->raise("Overflow", "result of - overflows");
} else {
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, n_res));
return 0;
}
return 0; // unreachable
}
static int prim_numeric_mul(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
number n_res;
if (__builtin_mul_overflow(n_self, n_other, &n_res)) {
proc->raise("Overflow", "result of * overflows");
} else {
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, n_res));
return 0;
}
return 0; // unreachable
}
static int prim_numeric_div(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
float n_res = n_self / (float) n_other; //FIXME: this is temporary
proc->stack_push(proc->mmobj()->mm_float_new(proc, n_res));
return 0;
}
static int prim_numeric_bit_and(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
unsigned long n_self = extract_number(proc, self);
unsigned long n_other = extract_number(proc, other);
unsigned long n_res = n_self & n_other;
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, n_res));
return 0;
}
static int prim_numeric_bit_or(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
unsigned long n_self = extract_number(proc, self);
unsigned long n_other = extract_number(proc, other);
unsigned long n_res = n_self | n_other;
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, n_res));
return 0;
}
static int prim_numeric_lt(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
oop res = n_self < n_other ? MM_TRUE : MM_FALSE;
proc->stack_push(res);
return 0;
}
static int prim_numeric_gt(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
oop res = n_self > n_other ? MM_TRUE : MM_FALSE;
proc->stack_push(res);
return 0;
}
static int prim_numeric_gteq(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
oop res = n_self >= n_other ? MM_TRUE : MM_FALSE;
proc->stack_push(res);
return 0;
}
static int prim_numeric_lteq(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
oop res = n_self <= n_other ? MM_TRUE : MM_FALSE;
proc->stack_push(res);
return 0;
}
static int prim_numeric_eq(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
if (is_numeric(proc, other)) {
number n_self = extract_number(proc, self);
number n_other = extract_number(proc, other);
proc->stack_push(n_self == n_other ? MM_TRUE : MM_FALSE);
return 0;
} else {
proc->stack_push(MM_FALSE);
return 0;
}
}
static int prim_numeric_rshift(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
unsigned long n_self = extract_number(proc, self);
unsigned long n_other = extract_number(proc, other);
unsigned long n_res = n_self >> n_other;
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, n_res));
return 0;
}
static int prim_numeric_lshift(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
unsigned long n_self = extract_number(proc, self);
unsigned long n_other = extract_number(proc, other);
unsigned long n_res = n_self << n_other;
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, n_res));
return 0;
}
static int prim_numeric_neg(Process* proc) {
oop self = proc->dp();
number n_self = extract_number(proc, self);
number n_res = - n_self;
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, n_res));
return 0;
}
static int prim_numeric_to_string(Process* proc) {
oop self = proc->dp();
number n_self = extract_number(proc, self);
std::stringstream s;
s << n_self;
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_numeric_as_char(Process* proc) {
oop self = proc->rp();
unsigned long n_self = extract_number(proc, self);
if (n_self >= 0 and n_self < 256) {
std::string s = "";
s += (char) n_self;
oop oop_str = proc->mmobj()->mm_string_new(s);
proc->stack_push(oop_str);
return 0;
} else {
proc->raise("Exception", "unsupported value for asChar ");
}
return 0; // unreachable
}
static int prim_numeric_to_source(Process* proc) {
return prim_numeric_to_string(proc);
}
static int prim_float_ceil(Process* proc) {
oop self = proc->rp();
float n_self = proc->mmobj()->mm_float_get(proc, self);
number res = ceil(n_self);
proc->stack_push(tag_small_int(res));
return 0;
}
///end numeric
static int prim_exception_throw(Process* proc) {
oop self = proc->rp();
proc->stack_push(self);
return PRIM_RAISED;
}
static int prim_list_new(Process* proc) {
//oop self = proc->mmobj()->mm_list_new();
oop self = proc->dp();
proc->mmobj()->mm_list_init(self);
DBG(self << endl);
proc->stack_push(proc->rp());
return 0;
}
static int prim_list_new_from_stack(Process* proc) {
oop self = proc->dp();
// oop self = proc->mmobj()->mm_list_new();
// number length = proc->mmobj(length_oo);
DBG("appending " << proc->current_args_number() << " values" << endl);
for (number i = 0; i < proc->current_args_number(); i++) {
oop element = proc->get_arg(i);
DBG("appending " << element << endl);
proc->mmobj()->mm_list_append(proc, self, element);
}
// DBG("done new_from_stack" << endl);
proc->stack_push(proc->rp());
return 0;
}
static int prim_list_append(Process* proc) {
oop self = proc->dp();
oop element = proc->get_arg(0);
proc->mmobj()->mm_list_append(proc, self, element);
proc->stack_push(proc->rp());
return 0;
}
static int prim_list_insert(Process* proc) {
oop self = proc->dp();
oop oop_idx = proc->get_arg(0);
oop element = proc->get_arg(1);
number index = untag_small_int(oop_idx);
proc->mmobj()->mm_list_insert(proc, self, index, element);
proc->stack_push(proc->rp());
return 0;
}
static int prim_list_prepend(Process* proc) {
oop self = proc->dp();
oop element = proc->get_arg(0);
// DBG("LIST: prepend " << element << endl);
proc->mmobj()->mm_list_prepend(proc, self, element);
proc->stack_push(proc->rp());
return 0;
}
static int prim_list_index(Process* proc) {
oop self = proc->dp();
oop index_oop = proc->get_arg(0);
number index = untag_small_int(index_oop);
oop val = proc->mmobj()->mm_list_entry(proc, self, index);
DBG("list " << self << "[" << index << "] = " << val << endl);
proc->stack_push(val);
return 0;
}
static int prim_list_set(Process* proc) {
oop self = proc->dp();
oop index_oop = proc->get_arg(0);
oop val_oop = proc->get_arg(1);
number index = untag_small_int(index_oop);
proc->mmobj()->mm_list_set(proc, self, index, val_oop);
proc->stack_push(proc->rp());
return 0;
}
static int prim_list_replace(Process* proc) {
oop self = proc->dp();
oop begin_oop = proc->get_arg(0);
oop end_oop = proc->get_arg(1);
oop lst = proc->get_arg(2);
number size = proc->mmobj()->mm_list_size(proc, self);
number lst_size = proc->mmobj()->mm_list_size(proc, lst);
number begin = untag_small_int(begin_oop);
number end = untag_small_int(end_oop);
if (!(begin < size and end < size and begin < end)) {
proc->raise("TypeError", "begin and end must be smaller than list size");
}
oop_vector* sframe = proc->mmobj()->mm_list_frame(proc, self);
int i;
for (i = 0; i < lst_size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, lst, i);
sframe->insert(sframe->begin() + begin + i, next);
}
sframe->erase(sframe->begin() + begin + i, sframe->begin() + end + i);
proc->stack_push(proc->rp());
return 0;
}
static int prim_list_extend(Process* proc) {
oop self = proc->dp();
oop lst = proc->get_arg(0);
number size = proc->mmobj()->mm_list_size(proc, lst);
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, lst, i);
proc->mmobj()->mm_list_append(proc, self, next);
}
proc->stack_push(proc->rp());
return 0;
}
static int prim_list_pos(Process* proc) {
oop self = proc->dp();
oop value = proc->get_arg(0);
number idx = proc->mmobj()->mm_list_index_of(proc, self, value);
if (idx != -1) {
proc->stack_push(tag_small_int(idx));
return 0;
}
for (number i = 0; i < proc->mmobj()->mm_list_size(proc, self); i++) {
oop entry = proc->mmobj()->mm_list_entry(proc, self, i);
int exc;
oop res = proc->send_1(entry, proc->vm()->new_symbol("=="), value, &exc);
if (exc != 0) {
proc->stack_push(res);
return exc;
}
if (res == MM_TRUE) {
proc->stack_push(tag_small_int(i));
return 0;
}
}
proc->stack_push(tag_small_int(-1));
return 0;
}
static int prim_list_each(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
// DBG("prim_list_each: closure is: " << fun << endl);
number size = proc->mmobj()->mm_list_size(proc, self);
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
DBG("list each[" << i << "] = " << next << endl);
int exc;
oop val = proc->call_2(fun, tag_small_int(i), next, &exc);
if (exc != 0) {
DBG("prim_list_each raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
DBG("list each[" << i << "] fun returned " << val << endl);
}
proc->stack_push(proc->rp());
return 0;
}
static oop mm_quicksort(Process* proc, oop lst, oop fun, int* exc) {
number size = proc->mmobj()->mm_list_size(proc, lst);
if (size <= 1) {
return lst;
}
oop pivot = proc->mmobj()->mm_list_entry(proc, lst, 0);
oop g1 = proc->mmobj()->mm_list_new();
oop g2 = proc->mmobj()->mm_list_new();
for (int i = 1; i < size; i++) {
oop item = proc->mmobj()->mm_list_entry(proc, lst, i);
oop val = proc->call_2(fun, pivot, item, exc);
if (*exc != 0) {
return val;
}
if (val == MM_FALSE or val == MM_NULL) {
proc->mmobj()->mm_list_append(proc, g1, item);
} else {
proc->mmobj()->mm_list_append(proc, g2, item);
}
}
oop sorted_1 = mm_quicksort(proc, g1, fun, exc);
if (*exc != 0) {
return sorted_1;
}
oop sorted_2 = mm_quicksort(proc, g2, fun, exc);
if (*exc != 0) {
return sorted_2;
}
proc->mmobj()->mm_list_append(proc, sorted_1, pivot);
number s2_size = proc->mmobj()->mm_list_size(proc, sorted_2);
for (int i = 0; i < s2_size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, sorted_2, i);
proc->mmobj()->mm_list_append(proc, sorted_1, next);
}
return sorted_1;
}
static int prim_list_ordered_by(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
int exc = 0;
oop sorted = mm_quicksort(proc, self, fun, &exc);
proc->stack_push(sorted);
if (exc != 0) {
return PRIM_RAISED;
} else {
return 0;
}
}
static int prim_list_map(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
number size = proc->mmobj()->mm_list_size(proc, self);
oop ret = proc->mmobj()->mm_list_new();
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
DBG("map[" << i << "] = " << next << endl);
int exc;
oop val = proc->call_1(fun, next, &exc);
if (exc != 0) {
DBG("raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
DBG("list map[" << i << "] fun returned " << val << endl);
proc->mmobj()->mm_list_append(proc, ret, val);
}
proc->stack_push(ret);
return 0;
}
static int prim_list_sum(Process* proc) {
oop self = proc->dp();
number size = proc->mmobj()->mm_list_size(proc, self);
if (size == 0) {
proc->stack_push(MM_NULL);
return 0;
}
oop first = proc->mmobj()->mm_list_entry(proc, self, 0);
if (is_numeric(proc, first)) {
number ret = extract_number(proc, first);
for (int i = 1; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
ret += extract_number(proc, next);
}
proc->stack_push(proc->mmobj()->mm_integer_or_longnum_new(proc, ret));
} else {
oop ret = first;
for (int i = 1; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
int exc;
oop val = proc->send_1(ret, proc->vm()->new_symbol("+"), next, &exc);
if (exc != 0) {
proc->stack_push(val);
return PRIM_RAISED;
}
ret = val;
}
proc->stack_push(ret);
}
return 0;
}
class less_then_oop {
public:
Process* proc;
less_then_oop(Process* p) : proc(p) {}
inline bool operator() (const oop a, oop b) {
int exc;
oop ret = proc->send_1(a, proc->vm()->new_symbol("<"), b, &exc);
if (exc != 0) {
throw mm_exception_rewind(ret);
}
if (ret == MM_FALSE) {
return false;
} else {
return true;
}
}
};
static int prim_list_sorted(Process* proc) {
oop self = proc->dp();
//dirty sorting of lists
oop ret = proc->mmobj()->mm_list_new();
oop_vector* this_vector = proc->mmobj()->mm_list_frame(proc, self);
oop_vector* ret_vector = proc->mmobj()->mm_list_frame(proc, ret);
*ret_vector = *this_vector;
std::sort(ret_vector->begin(), ret_vector->end(), less_then_oop(proc));
proc->stack_push(ret);
return 0;
}
static int prim_list_any(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
number size = proc->mmobj()->mm_list_size(proc, self);
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
int exc;
oop val = proc->call_1(fun, next, &exc);
if (exc != 0) {
DBG("raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
if (!(val == MM_FALSE || val == MM_NULL)) {
proc->stack_push(MM_TRUE);
return 0;
}
}
proc->stack_push(MM_FALSE);
return 0;
}
static int prim_list_times(Process* proc) {
oop self = proc->dp();
number val = extract_number(proc, proc->get_arg(0));
number size = proc->mmobj()->mm_list_size(proc, self);
oop ret = proc->mmobj()->mm_list_new();
for (number i = 0; i < val; i++) {
for (number j = 0; j < size; j++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, j);
proc->mmobj()->mm_list_append(proc, ret, next);
}
}
proc->stack_push(ret);
return 0;
}
static int prim_list_filter(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
number size = proc->mmobj()->mm_list_size(proc, self);
oop ret = proc->mmobj()->mm_list_new();
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
DBG("filter[" << i << "] = " << next << endl);
int exc;
oop val = proc->call_1(fun, next, &exc);
if (exc != 0) {
DBG("raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
DBG("filter[" << i << "] fun returned " << val << endl);
if (val != MM_NULL && val != MM_FALSE) {
proc->mmobj()->mm_list_append(proc, ret, next);
}
}
proc->stack_push(ret);
return 0;
}
static int prim_list_detect(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
number size = proc->mmobj()->mm_list_size(proc, self);
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
DBG("detect[" << i << "] = " << next << endl);
int exc;
oop val = proc->call_1(fun, next, &exc);
if (exc != 0) {
DBG("raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
DBG("detect[" << i << "] fun returned " << val << endl);
if (val != MM_NULL && val != MM_FALSE) {
proc->stack_push(next);
return 0;
}
}
proc->raise("Exception", "No value found");
}
static int prim_list_first_success(Process* proc) {
// this.detect(fun(x) {
// try {
// fn(x);
// return true;
// } catch(e) {
// return false;
// }
// });
oop self = proc->dp();
oop exc_type = proc->get_arg(0);
oop fun = proc->get_arg(1);
number size = proc->mmobj()->mm_list_size(proc, self);
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
DBG("detect[" << i << "] = " << next << endl);
int exc;
oop val = proc->call_1(fun, next, &exc);
if (exc != 0 && !proc->mmobj()->delegates_or_is_subclass(proc, proc->mmobj()->mm_object_vt(val), exc_type)) {
DBG("raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
} else if (exc == 0) {
proc->stack_push(next);
return 0;
}
proc->clear_exception_state();
}
proc->raise("Exception", "No value found");
}
static int prim_list_reduce(Process* proc) {
oop self = proc->dp();
oop acc = proc->get_arg(0);
oop fun = proc->get_arg(1);
number size = proc->mmobj()->mm_list_size(proc, self);
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
DBG("reduce[" << i << "] = " << next << endl);
int exc;
acc = proc->call_2(fun, acc, next, &exc);
if (exc != 0) {
DBG("raised" << endl);
proc->stack_push(acc);
return PRIM_RAISED;
}
DBG("reduce[" << i << "] fun returned " << acc << endl);
}
proc->stack_push(acc);
return 0;
}
static int prim_list_unique(Process* proc) {
oop self = proc->dp();
number size = proc->mmobj()->mm_list_size(proc, self);
oop ret = proc->mmobj()->mm_list_new();
for (number i = 0; i < size; i++) {
oop entry = proc->mmobj()->mm_list_entry(proc, self, i);
if (proc->mmobj()->mm_list_index_of(proc, ret, entry) != -1) {
continue;
} else {
int exc;
oop res = proc->send_1(ret, proc->vm()->new_symbol("has"), entry, &exc);
if (exc != 0) {
proc->stack_push(res);
return exc;
}
if (res == MM_TRUE) {
continue;
}
}
proc->mmobj()->mm_list_append(proc, ret, entry);
}
proc->stack_push(ret);
return 0;
}
static int prim_list_size(Process* proc) {
oop self = proc->dp();
proc->stack_push(tag_small_int(proc->mmobj()->mm_list_size(proc, self)));
return 0;
}
static int prim_list_reverse(Process* proc) {
oop self = proc->dp();
number size = proc->mmobj()->mm_list_size(proc, self);
oop ret = proc->mmobj()->mm_list_new();
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
proc->mmobj()->mm_list_prepend(proc, ret, next);
}
proc->stack_push(ret);
return 0;
}
static int prim_list_join(Process* proc) {
oop self = proc->dp();
oop sep = proc->get_arg(0);
std::string str_sep = "";
number size = proc->mmobj()->mm_list_size(proc, self);
std::stringstream s;
for (int i = 0; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
s << str_sep << proc->mmobj()->mm_string_stl_str(proc, next);
if (!proc->mmobj()->mm_is_string(next)) {
proc->raise("TypeError", "list should contain only strings");
}
str_sep = proc->mmobj()->mm_string_stl_str(proc, sep);
}
oop res = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(res);
return 0;
}
static int prim_list_plus(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
number this_size = proc->mmobj()->mm_list_size(proc, self);
oop res = proc->mmobj()->mm_list_new();
if (proc->mmobj()->mm_is_list(other)) { //fast concatenation
number other_size = proc->mmobj()->mm_list_size(proc, other);
for (int i = 0; i < this_size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
proc->mmobj()->mm_list_append(proc, res, next);
}
for (int i = 0; i < other_size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, other, i);
proc->mmobj()->mm_list_append(proc, res, next);
}
proc->stack_push(res);
return 0;
} else { //slower concatenation
int exc;
oop maybe_other_size = proc->send_0(other, proc->vm()->new_symbol("size"), &exc);
if (exc != 0) {
proc->stack_push(maybe_other_size);
return PRIM_RAISED;
}
number other_size = extract_number(proc, maybe_other_size);
std::stringstream s;
for (int i = 0; i < this_size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
proc->mmobj()->mm_list_append(proc, res, next);
}
for (int i = 0; i < other_size; i++) {
oop next = proc->send_1(other, proc->vm()->new_symbol("index"), tag_small_int(i), &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
proc->mmobj()->mm_list_append(proc, res, next);
}
proc->stack_push(res);
return 0;
}
}
static int prim_list_equals(Process* proc) {
//shallow equals (for now, we are just comparing the oop of each element)
oop self = proc->dp();
oop other = proc->get_arg(0);
//FIXME: this likely breaks with two equal objs, subclasses of List.
if (proc->mmobj()->mm_object_vt(other) != proc->vm()->get_prime("List")) {
proc->stack_push(MM_FALSE);
return 0;
}
number this_size = proc->mmobj()->mm_list_size(proc, self);
number other_size = proc->mmobj()->mm_list_size(proc, other);
if (this_size != other_size) {
proc->stack_push(MM_FALSE);
return 0;
}
for (int i = 0; i < this_size; i++) {
oop next_self = proc->mmobj()->mm_list_entry(proc, self, i);
oop next_other = proc->mmobj()->mm_list_entry(proc, other, i);
int exc;
oop res = proc->send_1(next_self, proc->vm()->new_symbol("=="), next_other, &exc);
if (exc != 0) {
DBG("prim_list_equals raised" << endl);
proc->stack_push(res);
return PRIM_RAISED;
}
if (res == MM_FALSE) {
proc->stack_push(MM_FALSE);
return 0;
}
}
proc->stack_push(MM_TRUE);
return 0;
}
static int prim_list_has(Process* proc) {
oop self = proc->dp();
oop value = proc->get_arg(0);
if (proc->mmobj()->mm_list_index_of(proc, self, value) != -1) {
proc->stack_push(MM_TRUE);
return 0;
}
for (number i = 0; i < proc->mmobj()->mm_list_size(proc, self); i++) {
oop entry = proc->mmobj()->mm_list_entry(proc, self, i);
int exc;
oop res = proc->send_1(entry, proc->vm()->new_symbol("=="), value, &exc);
if (exc != 0) {
proc->stack_push(res);
return exc;
}
if (res == MM_TRUE) {
proc->stack_push(MM_TRUE);
return 0;
}
}
proc->stack_push(MM_FALSE);
return 0;
}
static int prim_list_last(Process* proc) {
oop self = proc->dp();
number size = proc->mmobj()->mm_list_size(proc, self);
DBG("size of list: " << size << endl);
if (size > 0) {
oop entry = proc->mmobj()->mm_list_entry(proc, self, size-1);
proc->stack_push(entry);
} else {
proc->raise("IndexError", "List overflow");
assert(0); //unreachable
}
return 0;
}
static int prim_list_from(Process* proc) {
oop self = proc->dp();
number index = extract_number(proc, proc->get_arg(0));
number size = proc->mmobj()->mm_list_size(proc, self);
oop ret = proc->mmobj()->mm_list_new();
if (index >= 0) {
for (number i = index; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
proc->mmobj()->mm_list_append(proc, ret, next);
}
} else if (size > 0) {
for (number i = size + index; i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
proc->mmobj()->mm_list_append(proc, ret, next);
}
}
proc->stack_push(ret);
return 0;
}
static int prim_list_range(Process* proc) {
oop self = proc->dp();
number from = extract_number(proc, proc->get_arg(0));
number to = extract_number(proc, proc->get_arg(1));
number size = proc->mmobj()->mm_list_size(proc, self);
oop ret = proc->mmobj()->mm_list_new();
if (from < 0) {
proc->raise("TypeError", "first parameter has to be positive");
} else { //`from` is positive
if (to >= 0) {
for (number i = from; i < to and i < size; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
proc->mmobj()->mm_list_append(proc, ret, next);
}
} else { //`to` is negative
for (number i = from; i < size + to and i >= 0; i++) {
oop next = proc->mmobj()->mm_list_entry(proc, self, i);
proc->mmobj()->mm_list_append(proc, ret, next);
}
}
}
proc->stack_push(ret);
return 0;
}
static int prim_list_to_string(Process* proc) {
oop self = proc->dp();
std::stringstream s;
s << "[";
std::string comma = "";
for (int i = 0; i < proc->mmobj()->mm_list_size(proc, self); i++) {
int exc;
oop res = proc->send_0(proc->mmobj()->mm_list_entry(proc, self, i),
proc->vm()->new_symbol("toString"), &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
s << comma << proc->mmobj()->mm_string_stl_str(proc, res);
comma = ", ";
}
s << "]";
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_list_to_source(Process* proc) {
oop self = proc->dp();
std::stringstream s;
s << "[";
std::string comma = "";
for (int i = 0; i < proc->mmobj()->mm_list_size(proc, self); i++) {
int exc;
oop res = proc->send_0(proc->mmobj()->mm_list_entry(proc, self, i),
proc->vm()->new_symbol("toSource"), &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
s << comma << proc->mmobj()->mm_string_stl_str(proc, res);
comma = ", ";
}
s << "]";
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_dictionary_new(Process* proc) {
//oop self = proc->mmobj()->mm_dictionary_new();
oop self = proc->dp();
proc->mmobj()->mm_dictionary_init(self);
DBG(self << endl);
proc->stack_push(proc->rp());
return 0;
}
static int prim_dictionary_copy(Process* proc) {
//oop self = proc->mmobj()->mm_dictionary_new();
oop self = proc->dp();
oop d = proc->mmobj()->mm_dictionary_new();
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, self);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, self);
for ( ; it != end; it++) {
proc->mmobj()->mm_dictionary_set(proc, d, it->first, it->second);
}
proc->stack_push(d);
return 0;
}
static int prim_dictionary_set(Process* proc) {
oop self = proc->dp();
oop key = proc->get_arg(0);
oop val = proc->get_arg(1);
proc->mmobj()->mm_dictionary_set(proc, self, key, val);
proc->stack_push(proc->rp());
return 0;
}
static int prim_dictionary_index(Process* proc) {
oop self = proc->dp();
oop key = proc->get_arg(0);
proc->stack_push(proc->mmobj()->mm_dictionary_get(proc, self, key));
return 0;
}
static int prim_dictionary_to_string(Process* proc) {
oop self = proc->dp();
std::stringstream s;
s << "{";
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, self);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, self);
std::string comma = "";
for ( ; it != end; it++) {
int exc;
oop res = proc->send_0(it->first,
proc->vm()->new_symbol("toString"), &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
s << comma << proc->mmobj()->mm_string_stl_str(proc, res) << ": ";
res = proc->send_0(it->second,
proc->vm()->new_symbol("toString"), &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
s << proc->mmobj()->mm_string_stl_str(proc, res);
comma = ", ";
}
s << "}";
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_dictionary_to_source(Process* proc) {
oop self = proc->dp();
std::stringstream s;
s << "{";
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, self);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, self);
std::string comma = "";
for ( ; it != end; it++) {
int exc;
oop res = proc->send_0(it->first,
proc->vm()->new_symbol("toSource"), &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
s << comma << proc->mmobj()->mm_string_stl_str(proc, res) << ": ";
res = proc->send_0(it->second,
proc->vm()->new_symbol("toSource"), &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
s << proc->mmobj()->mm_string_stl_str(proc, res);
comma = ", ";
}
s << "}";
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_dictionary_plus(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
oop d = proc->mmobj()->mm_dictionary_new();
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, self);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, self);
for ( ; it != end; it++) {
proc->mmobj()->mm_dictionary_set(proc, d, it->first, it->second);
}
it = proc->mmobj()->mm_dictionary_begin(proc, other);
end = proc->mmobj()->mm_dictionary_end(proc, other);
for ( ; it != end; it++) {
proc->mmobj()->mm_dictionary_set(proc, d, it->first, it->second);
}
proc->stack_push(d);
return 0;
}
static int prim_dictionary_delete(Process* proc) {
oop self = proc->dp();
oop key = proc->get_arg(0);
oop_map* dframe = proc->mmobj()->mm_dictionary_frame(proc, self);
dframe->erase(key);
proc->stack_push(self);
return 0;
}
static int prim_dictionary_has(Process* proc) {
oop self = proc->dp();
oop key = proc->get_arg(0);
if (proc->mmobj()->mm_dictionary_has_key(proc, self, key)) {
proc->stack_push(MM_TRUE);
} else {
proc->stack_push(MM_FALSE);
}
return 0;
}
static int prim_dictionary_keys(Process* proc) {
oop self = proc->dp();
proc->stack_push(proc->mmobj()->mm_dictionary_keys(proc, self));
return 0;
}
static int prim_dictionary_values(Process* proc) {
oop self = proc->dp();
proc->stack_push(proc->mmobj()->mm_dictionary_values(proc, self));
return 0;
}
static int prim_dictionary_each(Process* proc) {
oop self = proc->dp();
oop fun = proc->get_arg(0);
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, self);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, self);
for ( ; it != end; it++) {
int exc;
oop val = proc->call_2(fun, it->first, it->second, &exc);
if (exc != 0) {
DBG("prim_dictionary_each raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
}
proc->stack_push(proc->rp());
return 0;
}
static int prim_dictionary_size(Process* proc) {
oop self = proc->dp();
proc->stack_push(tag_small_int(proc->mmobj()->mm_dictionary_size(proc, self)));
return 0;
}
static int prim_dictionary_equals(Process* proc) {
oop self = proc->dp();
oop other = proc->get_arg(0);
oop Dictionary = proc->vm()->get_prime("Dictionary");
// oop klass = proc->mmobj()->mm_object_vt(other);
// if (!proc->mmobj()->delegates_to(klass, Dictionary)) {
// proc->stack_push(MM_FALSE);
// return 0;
// }
if (proc->mmobj()->mm_object_vt(proc->rp()) != proc->mmobj()->mm_object_vt(other)) {
proc->stack_push(MM_FALSE);
return 0;
}
oop dp_other = proc->mmobj()->delegate_for_vt(proc, other, Dictionary);
oop_map* d_self = proc->mmobj()->mm_dictionary_frame(proc, self);
oop_map* d_other = proc->mmobj()->mm_dictionary_frame(proc, dp_other);
if (d_self->size() != d_other->size()) {
proc->stack_push(MM_FALSE);
return 0;
}
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, self);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, self);
for ( ; it != end; it++) {
int exc;
oop val = proc->send_1(other, proc->vm()->new_symbol("index"), it->first, &exc);
if (exc != 0) {
DBG("prim_dictionary_equals raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
oop val_eq = proc->send_1(it->second, proc->vm()->new_symbol("=="), val, &exc);
if (exc != 0) {
DBG("prim_dictionary_equals raised" << endl);
proc->stack_push(val);
return PRIM_RAISED;
}
if (val_eq == MM_FALSE) {
proc->stack_push(MM_FALSE);
return 0;
}
}
proc->stack_push(MM_TRUE);
return 0;
}
static int prim_mirror_entries(Process* proc) {
oop self = proc->dp();
oop mirrored = ((oop*)self)[2];
if (is_small_int(mirrored)) {
DBG("mirrored is number" << endl);
oop lst = proc->mmobj()->mm_list_new();
proc->stack_push(lst);
return 0;
} else if (proc->mmobj()->mm_is_list(mirrored)) {
oop lst = proc->mmobj()->mm_list_new();
for (number i = 0; i < proc->mmobj()->mm_list_size(proc, mirrored); i++) {
proc->mmobj()->mm_list_append(proc, lst, tag_small_int(i));
}
proc->stack_push(lst);
return 0;
} else if (proc->mmobj()->mm_is_dictionary(mirrored)) {
oop lst = proc->mmobj()->mm_list_new();
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, mirrored);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, mirrored);
for ( ; it != end; it++) {
proc->mmobj()->mm_list_append(proc, lst, it->first);
}
proc->stack_push(lst);
return 0;
} else {
DBG("mirrored is not [number|list|dict]" << endl);
oop mirrored_class = proc->mmobj()->mm_object_vt(mirrored);
if (proc->mmobj()->delegates_to(mirrored_class, proc->vm()->get_prime("Object"))) {
// mirrored is a class instance
DBG("mirrored is class instance" << endl);
oop cclass = proc->mmobj()->mm_class_get_compiled_class(proc, mirrored_class);
proc->stack_push(proc->mmobj()->mm_compiled_class_fields(proc, cclass));
return 0;
} else { //unknown structure
DBG("mirrored has unknown structure" << endl);
oop lst = proc->mmobj()->mm_list_new();
proc->stack_push(lst);
return 0;
}
}
}
static int prim_mirror_value_for(Process* proc) {
oop self = proc->dp();
oop entry = proc->get_arg(0);
oop mirrored = ((oop*)self)[2];
if (proc->mmobj()->mm_is_list(mirrored)) {
proc->stack_push(proc->mmobj()->mm_list_entry(proc, mirrored, untag_small_int(entry)));
return 0;
} else if (proc->mmobj()->mm_is_dictionary(mirrored)) {
proc->stack_push(proc->mmobj()->mm_dictionary_get(proc, mirrored, entry));
return 0;
} else { //generic instance ?
//assume mirrored is a class instance
oop mirrored_class = proc->mmobj()->mm_object_vt(mirrored);
if (!(proc->mmobj()->delegates_to(mirrored_class, proc->vm()->get_prime("Object")))) {
proc->raise("TypeError", "Mirrored should be class instance");
}
oop cclass = proc->mmobj()->mm_class_get_compiled_class(proc, mirrored_class);
oop fields = proc->mmobj()->mm_compiled_class_fields(proc, cclass);
number idx = proc->mmobj()->mm_list_index_of(proc, fields, entry);
if (!(idx >= 0)) {
proc->raise("TypeError", "invalid index");
}
DBG("index of " << idx << endl);
proc->stack_push(((oop*)mirrored)[2+idx]);
return 0;
}
}
static int prim_mirror_set_value_for(Process* proc) {
oop self = proc->dp();
oop entry = proc->get_arg(0);
oop value = proc->get_arg(1);
oop mirrored = ((oop*)self)[2];
if (proc->mmobj()->mm_is_list(mirrored)) {
proc->mmobj()->mm_list_set(proc, mirrored, untag_small_int(entry), value);
proc->stack_push(proc->rp());
return 0;
} else if (proc->mmobj()->mm_is_dictionary(mirrored)) {
proc->mmobj()->mm_dictionary_set(proc, mirrored, entry, value);
return 0;
} else { //generic instance ?
//assume mirrored is a class instance
oop mirrored_class = proc->mmobj()->mm_object_vt(mirrored);
if (!(proc->mmobj()->delegates_to(mirrored_class, proc->vm()->get_prime("Object")))) {
proc->raise("TypeError", "Mirrored should be class instance");
}
oop cclass = proc->mmobj()->mm_class_get_compiled_class(proc, mirrored_class);
oop fields = proc->mmobj()->mm_compiled_class_fields(proc, cclass);
number idx = proc->mmobj()->mm_list_index_of(proc, fields, entry);
if (!(idx >= 0)) {
proc->raise("TypeError", "invalid index");
}
DBG("index of " << idx << endl);
((oop*)mirrored)[2+idx] = value;
proc->stack_push(proc->rp());
return 0;
}
}
static int prim_mirror_vt_for(Process* proc) {
oop obj = proc->get_arg(0);
DBG("vt for " << obj << " = " << proc->mmobj()->mm_object_vt(obj) << endl);
proc->stack_push(proc->mmobj()->mm_object_vt(obj));
return 0;
}
static int prim_mirror_is_subclass(Process* proc) {
oop sub = proc->get_arg(0);
oop sup = proc->get_arg(1);
if (proc->mmobj()->delegates_to(sub, sup)) {
proc->stack_push(MM_TRUE);
} else {
proc->stack_push(MM_FALSE);
}
return 0;
}
static int prim_equal(Process* proc) {
oop self = proc->rp();
oop other = proc->get_arg(0);
DBG(self << " == " << other << "?" << (self == other ? MM_TRUE : MM_FALSE) << endl);
proc->stack_push(self == other ? MM_TRUE : MM_FALSE);
return 0;
}
// static int prim_id(Process* proc) {
// oop self = proc->rp();
// std::stringstream s;
// s << self;
// proc->stack_push(proc->mmobj()->mm_string_new(s.str()));
// return 0;
// }
static int prim_object_not(Process* proc) {
oop self = proc->dp();
if ((self == MM_FALSE) || (self == MM_NULL)) {
proc->stack_push(MM_TRUE);
} else {
proc->stack_push(MM_FALSE);
}
return 0;
}
static int prim_behavior_to_string(Process* proc) {
oop klass = proc->rp();
oop cclass = proc->mmobj()->mm_class_get_compiled_class(proc, klass);
oop class_name = proc->mmobj()->mm_compiled_class_name(proc, cclass);
std::string str_class_name = proc->mmobj()->mm_string_stl_str(proc, class_name);
std::stringstream s;
s << "#<" << str_class_name << " class>";
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_behavior_to_source(Process* proc) {
return prim_behavior_to_string(proc);
}
static int prim_object_to_string(Process* proc) {
oop self = proc->rp();
oop klass = proc->mmobj()->mm_object_vt(self);
oop cclass = proc->mmobj()->mm_class_get_compiled_class(proc, klass);
oop class_name = proc->mmobj()->mm_compiled_class_name(proc, cclass);
std::string str_class_name = proc->mmobj()->mm_string_stl_str(proc, class_name);
std::stringstream s;
s << "#<" << str_class_name << " instance: " << self << ">";
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_object_to_source(Process* proc) {
return prim_object_to_string(proc);
}
static int prim_object_send(Process* proc) {
oop self = proc->rp();
oop name = proc->get_arg(0);
oop args_list = proc->get_arg(1);
int exc;
oop res = proc->send(self, name, args_list, &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
proc->stack_push(res);
return 0;
}
static int prim_object_super_send(Process* proc) {
oop self = proc->rp();
oop name = proc->get_arg(0);
oop args_list = proc->get_arg(1);
int exc;
oop res = proc->super_send(self, name, args_list, &exc);
if (exc != 0) {
proc->stack_push(res);
return PRIM_RAISED;
}
proc->stack_push(res);
return 0;
}
static int prim_object_id(Process* proc) {
oop self = proc->rp();
std::stringstream s;
s << self;
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_symbol_to_string(Process* proc) {
oop self = proc->dp();
std::string str = proc->mmobj()->mm_symbol_cstr(proc, self);
DBG(self << " str: " << str << endl);
oop oop_str = proc->mmobj()->mm_string_new(str);
proc->stack_push(oop_str);
return 0;
}
static int prim_module_to_string(Process* proc) {
oop self = proc->rp();
oop cmod = proc->mmobj()->mm_module_get_cmod(self);
// DBG("prim_module_to_string imod: " << self << " cmod: " << cmod << endl);
oop mod_name = proc->mmobj()->mm_compiled_module_name(proc, cmod);
std::string str_mod_name = proc->mmobj()->mm_string_stl_str(proc, mod_name);
std::stringstream s;
s << "#<" << str_mod_name << " module instance: " << self << ">";
oop oop_str = proc->mmobj()->mm_string_new(s.str());
proc->stack_push(oop_str);
return 0;
}
static int prim_compiled_function_new_context(Process* proc) {
//return Context.new(this, fp, module);
oop args = proc->mmobj()->mm_list_new();
proc->mmobj()->mm_list_append(proc, args, proc->rp());
proc->mmobj()->mm_list_append(proc, args, proc->get_arg(0));
proc->mmobj()->mm_list_append(proc, args, proc->get_arg(1));
int exc;
oop ctx = proc->send(proc->vm()->get_prime("Context"), proc->vm()->new_symbol("new"), args, &exc);
if (exc != 0) {
proc->stack_push(ctx);
return PRIM_RAISED;
}
proc->stack_push(ctx);
return 0;
}
static int prim_compiled_function_with_env(Process* proc) {
// oop self = proc->dp();
oop text = proc->get_arg(0);
oop scope_names = proc->get_arg(1);
oop cmod = proc->get_arg(2);
// DBG("prim_compiled_function_with_env " << proc->mmobj()->mm_string_stl_str(text) << " -- " << cmod << " " << vars << endl);
std::list<std::string> lst = proc->mmobj()->mm_sym_list_to_cstring_list(proc, scope_names);
int exc;
oop cfun = proc->vm()->compile_fun(proc, proc->mmobj()->mm_string_cstr(proc, text), lst, cmod, &exc);
if (exc != 0) {
proc->stack_push(cfun);
return PRIM_RAISED;
}
// DBG("prim_compiled_function_with_env: GOT cfun: " << cfun << " " << *(oop*) cfun << endl);
proc->stack_push(cfun);
return 0;
}
static int prim_compiled_function_with_frame(Process* proc) {
oop text = proc->get_arg(0);
oop frame = proc->get_arg(1);
oop cmod = proc->get_arg(2);
oop fn = proc->mmobj()->mm_frame_get_cp(proc, frame);
// DBG("prim_compiled_function_with_frame: associated to fun: " << fn << endl);
oop env_table = proc->mmobj()->mm_function_env_table(proc, fn);
// DBG("prim_compiled_function_with_frame: env_table: " << env_table << endl);
std::list<std::string> lst = proc->mmobj()->mm_sym_list_to_cstring_list(proc, env_table);
int exc;
oop cfun = proc->vm()->compile_fun(proc, proc->mmobj()->mm_string_cstr(proc, text), lst, cmod, &exc);
// DBG("prim_compiled_function_with_frame: cfun: " << cfun << " " << exc << endl);
if (exc != 0) {
proc->stack_push(cfun);
return PRIM_RAISED;
}
// DBG("prim_compiled_function_with_env: GOT cfun: " << cfun << " " << *(oop*) cfun << endl);
proc->stack_push(cfun);
return 0;
}
static int prim_compiled_function_as_context_with_vars(Process* proc) {
/* (1) allocate and assemble the ep/env from the vars with its values;
(2) instantiate a Context with (self, env, imod)
*/
oop self = proc->dp();
oop imod = proc->get_arg(0);
oop vars = proc->get_arg(1);
number env_size = CFUN_STORAGE_SIZE(proc->mmobj()->mm_compiled_function_get_header(proc, self));
oop env = (oop) GC_MALLOC(sizeof(oop) * (env_size + 2)); //+2: rp, dp
if (vars != MM_NULL) {
oop env_table = proc->mmobj()->mm_compiled_function_env_table(proc, self);
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, vars);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, vars);
for ( ; it != end; it++) {
std::string name = proc->mmobj()->mm_symbol_cstr(proc, it->first);
if (name == "this") {
((oop*)env)[env_size] = it->second; //rp
((oop*)env)[env_size+1] = it->second; //ep
} else {
number idx = proc->mmobj()->mm_list_index_of(proc, env_table, it->first);
((oop*)env)[idx] = it->second;
}
}
}
oop args = proc->mmobj()->mm_list_new();
proc->mmobj()->mm_list_append(proc, args, self);
proc->mmobj()->mm_list_append(proc, args, env);
proc->mmobj()->mm_list_append(proc, args, imod);
DBG("Creating context..." << self << " " << vars << " " << imod << endl);
int exc;
oop ctx = proc->send(proc->vm()->get_prime("Context"), proc->vm()->new_symbol("new"), args, &exc);
if (exc != 0) {
proc->stack_push(ctx);
return PRIM_RAISED;
}
// DBG("compiled_function_as_context_with_vars: " << ctx << endl);
// DBG("ctx[cfun] " << proc->mmobj()->mm_function_get_cfun(ctx) << endl);
// DBG("ctx[env] " << proc->mmobj()->mm_context_get_env(ctx) << endl);
// DBG("ctx[imod] " << proc->mmobj()->mm_function_get_module(ctx) << endl);
proc->stack_push(ctx);
return 0;
}
static int prim_compiled_function_get_text(Process* proc) {
oop self = proc->dp();
proc->stack_push(proc->mmobj()->mm_compiled_function_get_text(proc, self));
return 0;
}
// static int prim_compiled_function_get_line_mapping(Process* proc) {
// oop self = proc->dp();
// proc->stack_push(proc->mmobj()->mm_compiled_function_get_line_mapping(self));
// return 0;
// }
// static int prim_compiled_function_get_loc_mapping(Process* proc) {
// oop self = proc->dp();
// proc->stack_push(proc->mmobj()->mm_compiled_function_get_loc_mapping(self));
// return 0;
// }
static int prim_compiled_function_loc_for(Process* proc) {
oop self = proc->dp();
if (CFUN_IS_PRIM(proc->mmobj()->mm_compiled_function_get_header(proc, self))) {
DBG("LOCINFO IS NULL" << endl);
proc->stack_push(MM_NULL);
return 0;
}
oop frame = proc->get_arg(0);
bytecode* ip = proc->mmobj()->mm_frame_get_ip(proc, frame);
DBG("loc_for_ip: " << ip << endl);
bytecode* base_ip = proc->mmobj()->mm_compiled_function_get_code(proc, self);
word idx = ip - base_ip;
DBG("loc_for_ip base: " << base_ip << " ip: " << ip << " idx: " << idx << endl);
oop mapping = proc->mmobj()->mm_compiled_function_get_loc_mapping(proc, self);
oop_map::iterator it = proc->mmobj()->mm_dictionary_begin(proc, mapping);
oop_map::iterator end = proc->mmobj()->mm_dictionary_end(proc, mapping);
oop the_lst = MM_NULL;
word next_offset = INT_MAX;
for ( ; it != end; it++) {
word b_offset = untag_small_int(it->first); //11, 8, 7, 4, 0
if (idx == b_offset) {
DBG(" -- eq " << b_offset << " " << idx << std::endl);
next_offset = b_offset; //7
the_lst = it->second;
} else if ((idx < b_offset) && (next_offset > b_offset)) {
DBG(" -- " << b_offset << " " << idx << std::endl);
next_offset = b_offset; //7
the_lst = it->second;
} else {
DBG(" -- ignored: " << b_offset << " " << idx << std::endl);
}
}
proc->stack_push(the_lst);
return 0;
}
static int prim_compiled_function_recompile(Process* proc) {
oop line = proc->get_arg(0);
oop text = proc->get_arg(1);
oop self = proc->dp();
int exc;
oop cfun = proc->vm()->recompile_fun(proc, self, untag_small_int(line), proc->mmobj()->mm_string_cstr(proc, text), &exc);
DBG("cfun: " << cfun << " " << exc << endl);
if (exc != 0) {
proc->stack_push(cfun);
return PRIM_RAISED;
}
// DBG() << "prim_compiled_function_with_env: GOT cfun: " << cfun << " " << *(oop*) cfun << endl;
proc->stack_push(cfun);
return 0;
}
static int prim_context_get_env(Process* proc) {
oop self = proc->dp();
oop ctx_env = proc->mmobj()->mm_context_get_env(proc, self);
oop env_table = proc->mmobj()->mm_function_env_table(proc, self);
oop env_dict = proc->mmobj()->mm_dictionary_new();
for (number i = 0; i < proc->mmobj()->mm_list_size(proc, env_table); i++) {
oop key = proc->mmobj()->mm_list_entry(proc, env_table, i);
oop val = ((oop*)ctx_env)[i];
proc->mmobj()->mm_dictionary_set(proc, env_dict, key, val);
}
// std::map<oop, oop>::iterator it = proc->mmobj()->mm_dictionary_begin(env_table);
// std::map<oop, oop>::iterator end = proc->mmobj()->mm_dictionary_end(env_table);
// for ( ; it != end; it++) {
// number idx = untag_small_int(it->second);
// DBG("env idx " << idx << endl);
// proc->mmobj()->mm_dictionary_set(env_dict, it->first, ((oop*)ctx_env)[2+idx]); //2: rp, dp
// }
proc->stack_push(env_dict);
return 0;
}
static int prim_context_with_frame(Process* proc) {
oop code = proc->get_arg(0);
oop frame = proc->get_arg(1);
oop imod = proc->get_arg(2);
oop cmod = proc->mmobj()->mm_module_get_cmod(imod);
oop args = proc->mmobj()->mm_list_new();
proc->mmobj()->mm_list_append(proc, args, code);
proc->mmobj()->mm_list_append(proc, args, frame);
proc->mmobj()->mm_list_append(proc, args, cmod);
int exc;
oop cfn = proc->send(proc->vm()->get_prime("CompiledFunction"), proc->vm()->new_symbol("withFrame"), args, &exc);
if (exc != 0) {
proc->stack_push(cfn);
return PRIM_RAISED;
}
oop fp = proc->mmobj()->mm_frame_get_fp(proc, frame);
args = proc->mmobj()->mm_list_new();
proc->mmobj()->mm_list_append(proc, args, fp);
proc->mmobj()->mm_list_append(proc, args, imod);
oop ctx = proc->send(cfn, proc->vm()->new_symbol("new_context"), args, &exc);
if (exc != 0) {
proc->stack_push(ctx);
return PRIM_RAISED;
}
proc->stack_push(ctx);
return 0;
}
static int prim_function_get_env(Process* proc) {
return prim_context_get_env(proc);
}
static int prim_context_new(Process* proc) {
oop self = proc->dp();
oop cfun = proc->get_arg(0);
oop env = proc->get_arg(1);
oop imod = proc->get_arg(2);
proc->mmobj()->mm_context_set_cfun(proc, self, cfun);
proc->mmobj()->mm_context_set_env(proc, self, env);
proc->mmobj()->mm_context_set_module(proc, self, imod);
proc->stack_push(proc->rp());
return 0;
}
static int prim_get_compiled_module(Process* proc) {
oop imod = proc->get_arg(0);
proc->stack_push(proc->mmobj()->mm_module_get_cmod(imod));
return 0;
}
static int prim_get_compiled_module_by_name(Process* proc) {
oop name = proc->get_arg(0);
char* str_name = proc->mmobj()->mm_string_cstr(proc, name);
proc->stack_push(proc->vm()->get_compiled_module(proc, str_name));
return 0;
}
static int prim_get_current_process(Process* proc) {
proc->stack_push(proc->mmobj()->mm_process_new(proc, proc));
return 0;
}
static int prim_get_current_frame(Process* proc) {
proc->stack_push(proc->mmobj()->mm_frame_new(proc, proc->bp()));
return 0;
}
static int prim_test_import(Process* proc) {
oop filepath = proc->get_arg(0);
oop args = proc->get_arg(1);
std::string str_filepath = proc->mmobj()->mm_string_stl_str(proc, filepath);
DBG(str_filepath << endl);
int data_size;
char* data = read_mec_file(str_filepath, &data_size);
MECImage* mec = new (GC) MECImage(proc, proc->vm()->core(), str_filepath, data_size, data);
mec->load();
proc->stack_push(mec->instantiate_module(args));
return 0;
}
// static int prim_test_get_module_function(Process* proc) {
// oop name = proc->get_arg(0);
// oop imod = proc->get_arg(1);
// // char* str = proc->mmobj()->mm_symbol_stl_str(name);
// // DBG("XX: " << name << " str: " << str << endl);
// oop dict = proc->mmobj()->mm_module_dictionary(imod);
// oop fun = proc->mmobj()->mm_dictionary_get(dict, name);
// DBG("prim_test_get_module_function: " << imod << " "
// << name << " " << dict << " " << fun << endl);
// proc->stack_push(fun);
// return 0;
// }
static
void get_mm_test_files(const fs::path& root, std::vector<std::string>& ret) {
if (!fs::exists(root)) return;
std::string prefix = "test_";
if (fs::is_directory(root)) {
fs::directory_iterator it(root);
fs::directory_iterator endit;
while(it != endit) {
if (fs::is_regular_file(*it)
and it->path().extension() == ".mec"
and it->path().filename().string().compare(0, prefix.length(), prefix) == 0)
{
//std::cerr << it->path() << endl;
ret.push_back(it->path().string());
}
++it;
}
}
}
static int prim_test_files(Process* proc) {
std::vector<std::string> ret;
std::string path = proc->mmobj()->mm_string_stl_str(proc, proc->get_arg(0));
get_mm_test_files(path, ret);
oop list = proc->mmobj()-> mm_list_new();
for(std::vector<std::string>::iterator it = ret.begin(); it != ret.end(); it++) {
oop str = proc->mmobj()->mm_string_new((*it));
proc->mmobj()->mm_list_append(proc, list, str);
}
proc->stack_push(list);
return 0;
}
static int prim_test_catch_exception(Process* proc) {
int exc;
oop ret = proc->send_0(proc->mp(), proc->vm()->new_symbol("bar"), &exc);
proc->stack_push(ret);
return 0;
}
static int prim_test_debug(Process* proc) {
return PRIM_HALTED;
}
// // DBG("prim_test_debug" << endl);
// proc->pause();
// // DBG("prim_test_debug: paused" << endl);
// Process* dbg_proc = new Process(proc->vm());
// // DBG("prim_test_debug: created new process" << endl);
// oop oop_target_proc = proc->mmobj()->mm_process_new(proc);
// int exc;
// oop res = dbg_proc->send_1(proc->mp(), proc->vm()->new_symbol("dbg_main"), oop_target_proc, &exc);
// if (exc != 0) {
// proc->stack_push(res);
// return PRIM_RAISED;
// }
// // DBG("prim_test_debug: called dbg_main" << endl);
// proc->stack_push(proc->rp());
// return 0;
// }
static int prim_process_step_into(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->step_into();
proc->stack_push(proc->rp());
return 0;
}
static int prim_process_step_over(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->step_over();
proc->stack_push(proc->rp());
return 0;
}
static int prim_process_step_over_line(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->step_over_line();
proc->stack_push(proc->rp());
return 0;
}
static int prim_process_step_out(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->step_out();
proc->stack_push(proc->rp());
return 0;
}
static int prim_process_resume(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->resume();
proc->stack_push(proc->rp());
return 0;
}
static int prim_process_reload_frame(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->reload_frame();
proc->stack_push(proc->rp());
return 0;
}
static int prim_process_return_from_frame(Process* proc) {
oop oop_target_proc = proc->rp();
oop retval = proc->get_arg(0);
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->unload_fun_and_return(retval);
target_proc->clear_exception_state(true);
return 0;
}
static int prim_process_break_at_addr(Process* proc) {
oop oop_target_proc = proc->rp();
bytecode* addr = (bytecode*) proc->get_arg(0);
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->break_at_addr(addr);
proc->stack_push(proc->rp());
return 0;
}
static int prim_process_rewind_and_continue(Process* proc) {
oop oop_target_proc = proc->rp();
oop bp = proc->get_arg(0);
DBG("rewiding to bp: " << bp << endl);
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
target_proc->rewind_to_frame_and_continue(bp);
proc->stack_push(proc->rp());
return 0;
}
static int prim_process_cp(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
proc->stack_push(target_proc->cp());
return 0;
}
static int prim_process_fp(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
proc->stack_push(target_proc->fp());
return 0;
}
static int prim_process_mp(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
proc->stack_push(target_proc->mp());
return 0;
}
// static int prim_process_ip(Process* proc) {
// oop oop_target_proc = proc->rp();
// Process* target_proc = (Process*) (((oop*)oop_target_proc)[2]);
// proc->stack_push((oop) target_proc->ip());
// return 0;
// }
static int prim_process_frames(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = proc->mmobj()->mm_process_get_proc(proc, oop_target_proc);
oop frames = proc->mmobj()->mm_list_new();
// DBG("prim_process_frames: stack deph: " << target_proc->stack_depth() << endl);
oop bp = target_proc->top_frame();
DBG("cp from bp " << bp << ": " << target_proc->cp_from_base(bp) << endl);
while(bp > (oop) 2) { //??
DBG("loop on bp: " << bp << endl);
oop cp = target_proc->cp_from_base(bp);
DBG("cp: " << cp << endl);
if (cp) {
proc->mmobj()->mm_list_append(proc, frames, proc->mmobj()->mm_frame_new(proc, bp));
} else {
break;
}
bp = *(oop*) bp;
DBG("new bp " << bp << endl);
}
proc->stack_push(frames);
return 0;
}
static int prim_exception_constructor(Process* proc) {
oop dself = proc->dp();
// std::cerr << "prim exception" << " bp " << proc->bp() << endl;
oop msg = proc->get_arg(0);
proc->mmobj()->mm_exception_set_message(proc, dself, msg);
// oop bp = proc->bp();
std::stringstream s;
s << "Uncaugh exception: " << proc->mmobj()->mm_string_stl_str(proc, msg) << endl;
s << proc->dump_stack_trace(true);
// while (bp) {
// oop cp = proc->cp_from_base(bp);
// if (!cp) break;
// s << proc->mmobj()->mm_string_stl_str(proc,
// proc->mmobj()->mm_function_get_name(
// proc, cp), true);
// s << "():" << (proc->mmobj()->mm_function_get_line_for_instruction(
// proc, cp, proc->ip_from_base(bp), true) + 1) << endl;
// bp = *(oop*)bp;
// }
oop st = proc->mmobj()->mm_string_new(s.str());
proc->mmobj()->mm_exception_set_st(proc, dself, st);
// std::cerr << "get bp " << proc->mmobj()->mm_exception_get_bp(proc, self);
proc->stack_push(proc->rp());
return 0;
}
// static int prim_exception_stack_trace(Process* proc) {
// oop dself = proc->dp();
// oop msg = proc->mmobj()->mm_exception_get_message(proc, dself, msg);
// std::stringstream s;
// s << "Uncaugh exception: " << proc->mmobj()->mm_string_stl_str(proc, msg) << endl;
// while (bp) {
// oop cp = proc->cp_from_base(bp);
// if (!cp) break;
// s << proc->mmobj()->mm_string_stl_str(proc,
// proc->mmobj()->mm_function_get_name(
// proc, cp), true);
// s << "():" << (proc->mmobj()->mm_function_get_line_for_instruction(
// proc, cp, proc->ip_from_base(bp), true) + 1) << endl;
// bp = *(oop*)bp;
// }
// oop ret = proc->mmobj()->mm_string_new(s.str().c_str());
// proc->stack_push(ret);
// return 0;
// }
static int prim_process_current_exception(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = proc->mmobj()->mm_process_get_proc(proc, oop_target_proc);
proc->stack_push(target_proc->current_exception());
return 0;
}
static int prim_process_last_returned_value(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = proc->mmobj()->mm_process_get_proc(proc, oop_target_proc);
proc->stack_push(target_proc->last_retval());
return 0;
}
static int prim_process_run_until(Process* proc) {
oop oop_target_proc = proc->rp();
oop cfun = proc->get_arg(0);
oop lineno = proc->get_arg(1);
Process* target_proc = proc->mmobj()->mm_process_get_proc(proc, oop_target_proc);
target_proc->run_until(cfun, untag_small_int(lineno));
proc->stack_push(oop_target_proc);
return 0;
}
static int prim_process_add_breakpoint(Process* proc) {
oop oop_target_proc = proc->rp();
oop cfun = proc->get_arg(0);
oop lineno = proc->get_arg(1);
Process* target_proc = proc->mmobj()->mm_process_get_proc(proc, oop_target_proc);
target_proc->add_breakpoint(cfun, untag_small_int(lineno));
proc->stack_push(oop_target_proc);
return 0;
}
static int prim_process_toggle_module_break_mode(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = proc->mmobj()->mm_process_get_proc(proc, oop_target_proc);
if (target_proc->toggle_module_break_mode()) {
proc->stack_push(MM_TRUE);
} else {
proc->stack_push(MM_FALSE);
}
return 0;
}
static int prim_process_detach_debugger(Process* proc) {
oop oop_target_proc = proc->rp();
Process* target_proc = proc->mmobj()->mm_process_get_proc(proc, oop_target_proc);
target_proc->detach_debugger();
proc->stack_push(proc->rp());
return 0;
}
// static int prim_process_apply(Process* proc) {
// oop oop_target_proc = proc->rp();
// oop fn = proc->get_arg(0);
// Process* target_proc = proc->mmobj()->mm_process_get_proc(oop_target_proc);
// int exc;
//TODO: we are not checking arity!
// oop res = target_proc->do_call_protected(fn, &exc);
// if (exc != 0) {
// proc->stack_push(res);
// return PRIM_RAISED;
// }
// proc->stack_push(res);
// return 0;
// }
static int prim_frame_ip(Process* proc) {
oop frame = proc->dp();
oop ip = (oop) proc->mmobj()->mm_frame_get_ip(proc, frame);
// oop bp = proc->mmobj()->mm_frame_get_bp(frame);
// DBG("prim_frame_ip bp: " << bp << endl);
// oop ip = *((oop*)(bp - 2));
// DBG("prim_frame_ip bp: " << bp << " has ip: " << ip << endl);
proc->stack_push(ip);
return 0;
}
static int prim_frame_cp(Process* proc) {
oop frame = proc->dp();
// oop bp = proc->mmobj()->mm_frame_get_bp(frame);
// DBG("prim_frame_cp bp: " << bp << endl);
// oop cp = *((oop*)(bp - 5));
// DBG("prim_frame_cp bp: " << bp << " has cp: " << cp << endl);
proc->stack_push(proc->mmobj()->mm_frame_get_cp(proc, frame));
return 0;
}
static int prim_frame_fp(Process* proc) {
oop frame = proc->dp();
proc->stack_push(proc->mmobj()->mm_frame_get_fp(proc, frame));
return 0;
}
static int prim_frame_rp(Process* proc) {
oop frame = proc->dp();
proc->stack_push(proc->mmobj()->mm_frame_get_rp(proc, frame));
return 0;
}
static int prim_frame_dp(Process* proc) {
oop frame = proc->dp();
proc->stack_push(proc->mmobj()->mm_frame_get_dp(proc, frame));
return 0;
}
static int prim_frame_get_local_value(Process* proc) {
oop frame = proc->dp();
number idx = untag_small_int(proc->get_arg(0));
oop fp = proc->mmobj()->mm_frame_get_fp(proc, frame);
proc->stack_push(*((oop*)fp + idx));
return 0;
}
static int prim_modules_path(Process* proc) {
const char* mmpath = getenv("MEME_PATH");
if (mmpath) {
proc->stack_push(proc->mmobj()->mm_string_new(mmpath));
} else {
proc->stack_push(proc->mmobj()->mm_string_new("./mm"));
}
return 0;
}
static int prim_set_debugger_module(Process* proc) {
oop oop_imod = proc->get_arg(0);
proc->vm()->set_debugger_module(oop_imod);
proc->stack_push(proc->rp());
return 0;
}
static int prim_get_argv(Process* proc) {
int i = 0;
oop ret = proc->mmobj()->mm_list_new();
while (true) {
char* carg = proc->vm()->get_argv(i++);
if (carg) {
oop arg = proc->mmobj()->mm_string_new(carg);
proc->mmobj()->mm_list_append(proc, ret, arg);
} else {
break;
}
}
proc->stack_push(ret);
return 0;
}
static int prim_exit(Process* proc) {
exit(extract_number(proc, proc->get_arg(0)));
}
static int prim_basename(Process* proc) {
oop filepath = proc->get_arg(0);
fs::path p(proc->mmobj()->mm_string_stl_str(proc, filepath));
oop basename = proc->mmobj()->mm_string_new(p.stem().string());
proc->stack_push(basename);
return 0;
}
#include <time.h>
static int prim_bench(Process* proc) {
oop oop_name = proc->get_arg(0);
oop fun = proc->get_arg(1);
std::string name = proc->mmobj()->mm_string_stl_str(proc, oop_name);
struct timespec now, tmstart;
std::cerr << "*bench begin: " << name << std::endl;
clock_gettime(CLOCK_REALTIME, &tmstart);
int exc;
oop val = proc->do_call(fun, &exc);
clock_gettime(CLOCK_REALTIME, &now);
double time_used = (double)((now.tv_sec+now.tv_nsec*1e-9) - (double)(tmstart.tv_sec+tmstart.tv_nsec*1e-9));
std::cerr << "*bench end : " << name << ": " << time_used << std::endl;
proc->stack_push(val);
if (exc != 0) {
return PRIM_RAISED;
} else {
return 0;
}
}
static int prim_compiled_module_path(Process* proc) {
oop self = proc->dp();
void* img = proc->mmobj()->mm_compiled_module_get_image_ptr(proc, self);
if (img == proc->vm()->core()) {
CoreImage* core_img = (CoreImage*) img;
proc->stack_push(proc->mmobj()->mm_string_new(core_img->filepath()));
} else {
MECImage* mec_img = (MECImage*) img;
proc->stack_push(proc->mmobj()->mm_string_new(mec_img->filepath()));
}
return 0;
}
void init_primitives(VM* vm) {
vm->register_primitive("io_print", prim_io_print);
vm->register_primitive("io_read_file", prim_io_read_file);
vm->register_primitive("io_write_file", prim_io_write_file);
vm->register_primitive("io_open_file", prim_io_open_file);
vm->register_primitive("io_write", prim_io_write);
vm->register_primitive("io_close", prim_io_close);
vm->register_primitive("remote_repl_compile_module", prim_remote_repl_compile_module);
vm->register_primitive("remote_repl_instantiate_module", prim_remote_repl_instantiate_module);
vm->register_primitive("behavior_to_string", prim_behavior_to_string);
vm->register_primitive("behavior_to_source", prim_behavior_to_source);
vm->register_primitive("numeric_sum", prim_numeric_sum);
vm->register_primitive("numeric_sub", prim_numeric_sub);
vm->register_primitive("numeric_mul", prim_numeric_mul);
vm->register_primitive("numeric_div", prim_numeric_div);
vm->register_primitive("numeric_bit_and", prim_numeric_bit_and);
vm->register_primitive("numeric_bit_or", prim_numeric_bit_or);
vm->register_primitive("numeric_lshift", prim_numeric_lshift);
vm->register_primitive("numeric_rshift", prim_numeric_rshift);
vm->register_primitive("numeric_lt", prim_numeric_lt);
vm->register_primitive("numeric_gt", prim_numeric_gt);
vm->register_primitive("numeric_lshift", prim_numeric_lshift);
vm->register_primitive("numeric_rshift", prim_numeric_rshift);
vm->register_primitive("numeric_gteq", prim_numeric_gteq);
vm->register_primitive("numeric_lteq", prim_numeric_lteq);
vm->register_primitive("numeric_eq", prim_numeric_eq);
vm->register_primitive("numeric_neg", prim_numeric_neg);
vm->register_primitive("numeric_to_string", prim_numeric_to_string);
vm->register_primitive("numeric_as_char", prim_numeric_as_char);
vm->register_primitive("numeric_to_source", prim_numeric_to_source);
vm->register_primitive("float_ceil", prim_float_ceil);
vm->register_primitive("exception_throw", prim_exception_throw);
vm->register_primitive("equal", prim_equal);
// vm->register_primitive("id", prim_id);
vm->register_primitive("object_not", prim_object_not);
vm->register_primitive("object_to_string", prim_object_to_string);
vm->register_primitive("object_to_source", prim_object_to_source);
vm->register_primitive("object_send", prim_object_send);
vm->register_primitive("object_super_send", prim_object_super_send);
vm->register_primitive("object_id", prim_object_id);
vm->register_primitive("symbol_to_string", prim_symbol_to_string);
vm->register_primitive("module_to_string", prim_module_to_string);
vm->register_primitive("list_new", prim_list_new);
vm->register_primitive("list_new_from_stack", prim_list_new_from_stack);
vm->register_primitive("list_insert", prim_list_insert);
vm->register_primitive("list_append", prim_list_append);
vm->register_primitive("list_prepend", prim_list_prepend);
vm->register_primitive("list_index", prim_list_index);
vm->register_primitive("list_pos", prim_list_pos);
vm->register_primitive("list_each", prim_list_each);
vm->register_primitive("list_ordered_by", prim_list_ordered_by);
vm->register_primitive("list_map", prim_list_map);
vm->register_primitive("list_sum", prim_list_sum);
vm->register_primitive("list_sorted", prim_list_sorted);
vm->register_primitive("list_times", prim_list_times);
vm->register_primitive("list_filter", prim_list_filter);
vm->register_primitive("list_detect", prim_list_detect);
vm->register_primitive("list_reduce", prim_list_reduce);
vm->register_primitive("list_unique", prim_list_unique);
vm->register_primitive("list_has", prim_list_has);
vm->register_primitive("list_last", prim_list_last);
vm->register_primitive("list_from", prim_list_from);
vm->register_primitive("list_range", prim_list_range);
vm->register_primitive("list_to_string", prim_list_to_string);
vm->register_primitive("list_to_source", prim_list_to_source);
vm->register_primitive("list_size", prim_list_size);
vm->register_primitive("list_reverse", prim_list_reverse);
vm->register_primitive("list_join", prim_list_join);
vm->register_primitive("list_plus", prim_list_plus);
vm->register_primitive("list_equals", prim_list_equals);
vm->register_primitive("list_set", prim_list_set);
vm->register_primitive("list_any", prim_list_any);
vm->register_primitive("list_replace", prim_list_replace);
vm->register_primitive("list_extend", prim_list_extend);
vm->register_primitive("list_first_success", prim_list_first_success);
vm->register_primitive("dictionary_new", prim_dictionary_new);
vm->register_primitive("dictionary_copy", prim_dictionary_copy);
vm->register_primitive("dictionary_set", prim_dictionary_set);
vm->register_primitive("dictionary_index", prim_dictionary_index);
vm->register_primitive("dictionary_plus", prim_dictionary_plus);
vm->register_primitive("dictionary_has", prim_dictionary_has);
vm->register_primitive("dictionary_keys", prim_dictionary_keys);
vm->register_primitive("dictionary_values", prim_dictionary_values);
vm->register_primitive("dictionary_each", prim_dictionary_each);
vm->register_primitive("dictionary_size", prim_dictionary_size);
vm->register_primitive("dictionary_equals", prim_dictionary_equals);
vm->register_primitive("dictionary_to_string", prim_dictionary_to_string);
vm->register_primitive("dictionary_to_source", prim_dictionary_to_source);
vm->register_primitive("dictionary_delete", prim_dictionary_delete);
vm->register_primitive("string_to_integer", prim_string_to_integer);
vm->register_primitive("string_to_byte", prim_string_to_byte);
vm->register_primitive("string_as_hex", prim_string_as_hex);
vm->register_primitive("string_concat", prim_string_concat);
vm->register_primitive("string_times", prim_string_times);
vm->register_primitive("string_equal", prim_string_equal);
vm->register_primitive("string_count", prim_string_count);
vm->register_primitive("string_size", prim_string_size);
vm->register_primitive("string_find", prim_string_find);
vm->register_primitive("string_rindex", prim_string_rindex);
vm->register_primitive("string_rindex_from", prim_string_rindex_from);
vm->register_primitive("string_index", prim_string_index);
vm->register_primitive("string_from", prim_string_from);
vm->register_primitive("string_substr", prim_string_substr);
vm->register_primitive("string_replace_all", prim_string_replace_all);
vm->register_primitive("string_b64decode", prim_string_b64decode);
vm->register_primitive("string_b64encode", prim_string_b64encode);
vm->register_primitive("string_only_spaces", prim_string_only_spaces);
vm->register_primitive("string_only_digits", prim_string_only_digits);
vm->register_primitive("string_is_lower", prim_string_is_lower);
vm->register_primitive("string_is_upper", prim_string_is_upper);
vm->register_primitive("string_split", prim_string_split);
vm->register_primitive("string_to_symbol", prim_string_to_symbol);
vm->register_primitive("string_trim", prim_string_trim);
vm->register_primitive("string_each", prim_string_each);
vm->register_primitive("string_map", prim_string_map);
vm->register_primitive("string_unescape", prim_string_unescape);
vm->register_primitive("string_lt", prim_string_lt);
vm->register_primitive("mirror_entries", prim_mirror_entries);
vm->register_primitive("mirror_value_for", prim_mirror_value_for);
vm->register_primitive("mirror_set_value_for", prim_mirror_set_value_for);
vm->register_primitive("mirror_vt_for", prim_mirror_vt_for);
vm->register_primitive("mirror_is_subclass", prim_mirror_is_subclass);
vm->register_primitive("compiled_function_new_context", prim_compiled_function_new_context);
vm->register_primitive("compiled_function_with_env", prim_compiled_function_with_env);
vm->register_primitive("compiled_function_with_frame", prim_compiled_function_with_frame);
vm->register_primitive("compiled_function_as_context_with_vars", prim_compiled_function_as_context_with_vars);
vm->register_primitive("compiled_function_get_text", prim_compiled_function_get_text);
// vm->register_primitive("compiled_function_get_line_mapping", prim_compiled_function_get_line_mapping);
// vm->register_primitive("compiled_function_get_loc_mapping", prim_compiled_function_get_loc_mapping);
vm->register_primitive("compiled_function_loc_for", prim_compiled_function_loc_for);
vm->register_primitive("compiled_function_recompile", prim_compiled_function_recompile);
vm->register_primitive("context_new", prim_context_new);
vm->register_primitive("context_get_env", prim_context_get_env);
vm->register_primitive("context_with_frame", prim_context_with_frame);
vm->register_primitive("function_get_env", prim_function_get_env);
vm->register_primitive("test_import", prim_test_import);
// vm->register_primitive("test_get_module_function", prim_test_get_module_function);
vm->register_primitive("test_files", prim_test_files);
vm->register_primitive("test_catch_exception", prim_test_catch_exception);
vm->register_primitive("test_debug", prim_test_debug);
vm->register_primitive("process_step_into", prim_process_step_into);
vm->register_primitive("process_step_over", prim_process_step_over);
vm->register_primitive("process_step_over_line", prim_process_step_over_line);
vm->register_primitive("process_step_out", prim_process_step_out);
vm->register_primitive("process_resume", prim_process_resume);
vm->register_primitive("process_reload_frame", prim_process_reload_frame);
vm->register_primitive("process_return_from_frame", prim_process_return_from_frame);
vm->register_primitive("process_break_at_addr", prim_process_break_at_addr);
vm->register_primitive("process_rewind_and_continue", prim_process_rewind_and_continue);
vm->register_primitive("process_current_exception", prim_process_current_exception);
vm->register_primitive("process_last_returned_value", prim_process_last_returned_value);
vm->register_primitive("process_run_until", prim_process_run_until);
vm->register_primitive("process_add_breakpoint", prim_process_add_breakpoint);
vm->register_primitive("process_toggle_module_break_mode", prim_process_toggle_module_break_mode);
vm->register_primitive("process_detach_debugger", prim_process_detach_debugger);
vm->register_primitive("process_cp", prim_process_cp);
vm->register_primitive("process_fp", prim_process_fp);
vm->register_primitive("process_mp", prim_process_mp);
// vm->register_primitive("process_ip", prim_process_ip);
vm->register_primitive("process_frames", prim_process_frames);
// vm->register_primitive("process_apply", prim_process_apply);
// vm->register_primitive("process_eval_in_frame", prim_process_eval_in_frame);
vm->register_primitive("exception_constructor", prim_exception_constructor);
// vm->register_primitive("exception_stack_trace", prim_exception_stack_trace);
vm->register_primitive("frame_ip", prim_frame_ip);
vm->register_primitive("frame_cp", prim_frame_cp);
vm->register_primitive("frame_fp", prim_frame_fp);
vm->register_primitive("frame_rp", prim_frame_rp);
vm->register_primitive("frame_dp", prim_frame_dp);
vm->register_primitive("frame_get_local_value", prim_frame_get_local_value);
vm->register_primitive("get_current_process", prim_get_current_process);
vm->register_primitive("get_current_frame", prim_get_current_frame);
vm->register_primitive("get_compiled_module", prim_get_compiled_module);
vm->register_primitive("get_compiled_module_by_name", prim_get_compiled_module_by_name);
vm->register_primitive("modules_path", prim_modules_path);
vm->register_primitive("set_debugger_module", prim_set_debugger_module);
vm->register_primitive("get_argv", prim_get_argv);
vm->register_primitive("exit", prim_exit);
vm->register_primitive("basename", prim_basename);
vm->register_primitive("bench", prim_bench);
vm->register_primitive("compiled_module_path", prim_compiled_module_path);
net_init_primitives(vm);
}
|
/*
Copyright 2021 University of Manchester
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.
*/
#pragma once
#include <vector>
#include "dma_interface.hpp"
#include "memory_manager_interface.hpp"
#include "stream_data_parameters.hpp"
namespace orkhestrafs::dbmstodspi {
/**
* @brief Interface for classes which can setup DMA modules.
*/
class DMASetupInterface {
public:
virtual ~DMASetupInterface() = default;
virtual void SetupDMAModule(
DMAInterface& dma_module,
const std::vector<StreamDataParameters>& input_streams,
const std::vector<StreamDataParameters>& output_streams) = 0;
virtual auto CreateDMAModule(MemoryManagerInterface* memory_manager)
-> std::unique_ptr<DMAInterface> = 0;
};
} // namespace orkhestrafs::dbmstodspi
|
#include "Player.h"
Player::Player()
: m_isAI(false)
{
}
Player::~Player()
{
}
void Player::Drawn(LinkedList* pBag, int count)
{
for (int i = 0; i < count; i++)
{
Node* node = pBag->Pop();
hand.AddTail(node);
}
}
void Player::ClearHand()
{
hand.Clear();
}
bool Player::Discard(Colour colour,Shape shape)
{
Node *node = hand.Extract(colour, shape);
if (node == nullptr) return false;
else
{
delete node->tile;
delete node;
return true;
}
}
|
//
// Created by Yujing Shen on 28/05/2017.
//
#ifndef TENSORGRAPH_SESSIONTENSOR_H
#define TENSORGRAPH_SESSIONTENSOR_H
#include "TensorGraph.h"
namespace sjtu{
class SessionTensor
{
public:
SessionTensor() = delete;
SessionTensor(const SessionTensor &rhs);
SessionTensor(const Shape &shape);
SessionTensor(const Dtype *data, int len);
SessionTensor(const vector<Dtype> &data);
virtual ~SessionTensor(){_shape.clear(); SAFEDELETES(_data);}
inline bool test_valid(const vector<int> &shape) const;
Tensor init_variable(int Itype);
Tensor assign(const vector<Dtype> &vs);
Tensor assign(const Dtype *vs, int len);
Tensor reshape(const vector<int> &shape);
Dtype* get_data();
// get_shape: shape C H W D or sub
Shape get_shape() const;
int get_channel() const;
int get_dim() const;
bool check_shape(Tensor r) const;
int get_count() const;
// Reference Caffe
Dtype& operator()(const vector<int> &pos);
Dtype& operator()(int c, int i, int j, int k);
Dtype& operator()(int i, int j, int k);
Dtype& operator()(int i, int j);
Dtype& operator()(int i);
protected:
Shape _shape;
int _count;
Dtype* _data;
static bool is_rand_set;
static void set_rand(){if(!is_rand_set)SET_RAND, is_rand_set = true;}
};
}
#endif //TENSORGRAPH_SESSIONTENSOR_H
|
#pragma once
// Listing 3.4 An outline class definitoin for a thread-safe stack
#include <exception>
#include <memory>
#include <mutex>
#include <stack>
struct empty_stack :public std::runtime_error
{
// ยณฮฮฮค
// const char* what() const noexcept;
explicit empty_stack(const char* s) :std::runtime_error(s) {}
};
template<typename T>
class threadsafe_stack
{
public:
threadsafe_stack() {}
threadsafe_stack(const threadsafe_stack& other);
threadsafe_stack& operator=(const threadsafe_stack&) = delete;
bool empty() const;
void push(T& new_value);
void pop(T& value);
std::shared_ptr<T> pop();
private:
std::stack<T> data;
mutable std::mutex m;
};
// Listing 3.5 A fleshed-out class defintion for a thread-safe stack
template<typename T>
threadsafe_stack<T>::threadsafe_stack(const threadsafe_stack& other)
{
std::lock_guard<std::mutex> lock(other.m);
data = other.data;
}
template<typename T>
bool threadsafe_stack<T>::empty() const
{
std::lock_guard<std::mutex> lock(m);
return data.empty();
}
template <typename T>
void threadsafe_stack<T>::push(T& new_val)
{
std::lock_guard<std::mutex> lock(m);
data.push(std::move(new_val));
}
template <typename T>
std::shared_ptr<T> threadsafe_stack<T>::pop()
{
std::lock_guard<std::mutex> lock(m);
if (data.empty())
throw empty_stack("Stack is empty.");
std::shared_ptr<T> const temp(std::make_shared<T>(data.top()));
data.pop();
return temp;
}
template <typename T>
void threadsafe_stack<T>::pop(T& value)
{
std::lock_guard<std::mutex> lock(m);
if (data.empty())
throw empty_stack("Stack is empty.");
value = data.top();
data.pop();
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "NullRenderer/Shader/ShaderLanguage.h"
#include "NullRenderer/Shader/Program.h"
#include "NullRenderer/Shader/VertexShader.h"
#include "NullRenderer/Shader/GeometryShader.h"
#include "NullRenderer/Shader/FragmentShader.h"
#include "NullRenderer/Shader/TessellationControlShader.h"
#include "NullRenderer/Shader/TessellationEvaluationShader.h"
#include <Renderer/IRenderer.h>
#include <Renderer/IAllocator.h>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace NullRenderer
{
//[-------------------------------------------------------]
//[ Public definitions ]
//[-------------------------------------------------------]
const char* ShaderLanguage::NAME = "Null";
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
ShaderLanguage::ShaderLanguage(NullRenderer& nullRenderer) :
IShaderLanguage(reinterpret_cast<Renderer::IRenderer&>(nullRenderer))
{
// Nothing here
}
ShaderLanguage::~ShaderLanguage()
{
// Nothing here
}
//[-------------------------------------------------------]
//[ Public virtual Renderer::IShaderLanguage methods ]
//[-------------------------------------------------------]
const char* ShaderLanguage::getShaderLanguageName() const
{
return NAME;
}
Renderer::IVertexShader* ShaderLanguage::createVertexShaderFromBytecode(const Renderer::VertexAttributes&, const Renderer::ShaderBytecode&)
{
// There's no need to check for "Renderer::Capabilities::vertexShader", we know there's vertex shader support
return RENDERER_NEW(getRenderer().getContext(), VertexShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::IVertexShader* ShaderLanguage::createVertexShaderFromSourceCode(const Renderer::VertexAttributes&, const Renderer::ShaderSourceCode&, Renderer::ShaderBytecode*)
{
// There's no need to check for "Renderer::Capabilities::vertexShader", we know there's vertex shader support
return RENDERER_NEW(getRenderer().getContext(), VertexShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::ITessellationControlShader* ShaderLanguage::createTessellationControlShaderFromBytecode(const Renderer::ShaderBytecode&)
{
// There's no need to check for "Renderer::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation control shader support
return RENDERER_NEW(getRenderer().getContext(), TessellationControlShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::ITessellationControlShader* ShaderLanguage::createTessellationControlShaderFromSourceCode(const Renderer::ShaderSourceCode&, Renderer::ShaderBytecode*)
{
// There's no need to check for "Renderer::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation control shader support
return RENDERER_NEW(getRenderer().getContext(), TessellationControlShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::ITessellationEvaluationShader* ShaderLanguage::createTessellationEvaluationShaderFromBytecode(const Renderer::ShaderBytecode&)
{
// There's no need to check for "Renderer::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation evaluation shader support
return RENDERER_NEW(getRenderer().getContext(), TessellationEvaluationShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::ITessellationEvaluationShader* ShaderLanguage::createTessellationEvaluationShaderFromSourceCode(const Renderer::ShaderSourceCode&, Renderer::ShaderBytecode*)
{
// There's no need to check for "Renderer::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation evaluation shader support
return RENDERER_NEW(getRenderer().getContext(), TessellationEvaluationShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::IGeometryShader* ShaderLanguage::createGeometryShaderFromBytecode(const Renderer::ShaderBytecode&, Renderer::GsInputPrimitiveTopology, Renderer::GsOutputPrimitiveTopology, uint32_t)
{
// There's no need to check for "Renderer::Capabilities::maximumNumberOfGsOutputVertices", we know there's geometry shader support
return RENDERER_NEW(getRenderer().getContext(), GeometryShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::IGeometryShader* ShaderLanguage::createGeometryShaderFromSourceCode(const Renderer::ShaderSourceCode&, Renderer::GsInputPrimitiveTopology, Renderer::GsOutputPrimitiveTopology, uint32_t, Renderer::ShaderBytecode*)
{
// There's no need to check for "Renderer::Capabilities::maximumNumberOfGsOutputVertices", we know there's geometry shader support
return RENDERER_NEW(getRenderer().getContext(), GeometryShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::IFragmentShader* ShaderLanguage::createFragmentShaderFromBytecode(const Renderer::ShaderBytecode&)
{
// There's no need to check for "Renderer::Capabilities::fragmentShader", we know there's fragment shader support
return RENDERER_NEW(getRenderer().getContext(), FragmentShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::IFragmentShader* ShaderLanguage::createFragmentShaderFromSourceCode(const Renderer::ShaderSourceCode&, Renderer::ShaderBytecode*)
{
// There's no need to check for "Renderer::Capabilities::fragmentShader", we know there's fragment shader support
return RENDERER_NEW(getRenderer().getContext(), FragmentShader)(reinterpret_cast<NullRenderer&>(getRenderer()));
}
Renderer::IProgram* ShaderLanguage::createProgram(const Renderer::IRootSignature&, const Renderer::VertexAttributes&, Renderer::IVertexShader* vertexShader, Renderer::ITessellationControlShader* tessellationControlShader, Renderer::ITessellationEvaluationShader* tessellationEvaluationShader, Renderer::IGeometryShader* geometryShader, Renderer::IFragmentShader* fragmentShader)
{
// A shader can be a null pointer, but if it's not the shader and program language must match!
// -> Optimization: Comparing the shader language name by directly comparing the pointer address of
// the name is safe because we know that we always reference to one and the same name address
// TODO(co) Add security check: Is the given resource one of the currently used renderer?
if (nullptr != vertexShader && vertexShader->getShaderLanguageName() != NAME)
{
// Error! Vertex shader language mismatch!
}
else if (nullptr != tessellationControlShader && tessellationControlShader->getShaderLanguageName() != NAME)
{
// Error! Tessellation control shader language mismatch!
}
else if (nullptr != tessellationEvaluationShader && tessellationEvaluationShader->getShaderLanguageName() != NAME)
{
// Error! Tessellation evaluation shader language mismatch!
}
else if (nullptr != geometryShader && geometryShader->getShaderLanguageName() != NAME)
{
// Error! Geometry shader language mismatch!
}
else if (nullptr != fragmentShader && fragmentShader->getShaderLanguageName() != NAME)
{
// Error! Fragment shader language mismatch!
}
else
{
return RENDERER_NEW(getRenderer().getContext(), Program)(reinterpret_cast<NullRenderer&>(getRenderer()), static_cast<VertexShader*>(vertexShader), static_cast<TessellationControlShader*>(tessellationControlShader), static_cast<TessellationEvaluationShader*>(tessellationEvaluationShader), static_cast<GeometryShader*>(geometryShader), static_cast<FragmentShader*>(fragmentShader));
}
// Error! Shader language mismatch!
// -> Ensure a correct reference counter behaviour, even in the situation of an error
if (nullptr != vertexShader)
{
vertexShader->addReference();
vertexShader->releaseReference();
}
if (nullptr != tessellationControlShader)
{
tessellationControlShader->addReference();
tessellationControlShader->releaseReference();
}
if (nullptr != tessellationEvaluationShader)
{
tessellationEvaluationShader->addReference();
tessellationEvaluationShader->releaseReference();
}
if (nullptr != geometryShader)
{
geometryShader->addReference();
geometryShader->releaseReference();
}
if (nullptr != fragmentShader)
{
fragmentShader->addReference();
fragmentShader->releaseReference();
}
// Error!
return nullptr;
}
//[-------------------------------------------------------]
//[ Protected virtual Renderer::RefCount methods ]
//[-------------------------------------------------------]
void ShaderLanguage::selfDestruct()
{
RENDERER_DELETE(getRenderer().getContext(), ShaderLanguage, this);
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // NullRenderer
|
#include "NuiMatrix.h"
namespace NuiMatrix {
/// <summary>
/// Set Identity in a Matrix4
/// </summary>
/// <param name="mat">The matrix to set to identity</param>
void SetIdentityMatrix(Matrix4 &mat)
{
mat.M11 = 1; mat.M12 = 0; mat.M13 = 0; mat.M14 = 0;
mat.M21 = 0; mat.M22 = 1; mat.M23 = 0; mat.M24 = 0;
mat.M31 = 0; mat.M32 = 0; mat.M33 = 1; mat.M34 = 0;
mat.M41 = 0; mat.M42 = 0; mat.M43 = 0; mat.M44 = 1;
}
}
|
#include "cli.h"
#include <cerrno>
#include <cstring>
#include <regex>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "replxx.hxx"
using namespace replxx;
int
utf8str_codepoint_len(char const* s, int utf8len)
{
int codepointLen = 0;
unsigned char m4 = 128 + 64 + 32 + 16;
unsigned char m3 = 128 + 64 + 32;
unsigned char m2 = 128 + 64;
for (int i = 0; i < utf8len; ++i, ++codepointLen) {
char c = s[i];
if ((c & m4) == m4) {
i += 3;
} else if ((c & m3) == m3) {
i += 2;
} else if ((c & m2) == m2) {
i += 1;
}
}
return (codepointLen);
}
int
context_len(char const* prefix)
{
char const wb[] = " \t\n\r\v\f-=+*&^%$#@!,./?<>;:`~'\"[]{}()\\|";
int i = (int)strlen(prefix) - 1;
int cl = 0;
while (i >= 0) {
if (strchr(wb, prefix[i]) != NULL) {
break;
}
++cl;
--i;
}
return (cl);
}
Replxx::completions_t
hook_completion(std::string const& context, int& contextLen,
std::vector<std::string> const& examples)
{
Replxx::completions_t completions;
int utf8ContextLen(context_len(context.c_str()));
int prefixLen(static_cast<int>(context.length()) - utf8ContextLen);
if ((prefixLen > 0) && (context[prefixLen - 1] == '\\')) {
--prefixLen;
++utf8ContextLen;
}
contextLen =
utf8str_codepoint_len(context.c_str() + prefixLen, utf8ContextLen);
std::string prefix{context.substr(prefixLen)};
if (prefix == "\\pi") {
completions.push_back("ฯ");
} else {
for (auto const& e : examples) {
if (e.compare(0, prefix.size(), prefix) == 0) {
Replxx::Color c(Replxx::Color::DEFAULT);
if (e.find("brightred") != std::string::npos) {
c = Replxx::Color::BRIGHTRED;
} else if (e.find("red") != std::string::npos) {
c = Replxx::Color::RED;
}
completions.emplace_back(e.c_str(), c);
}
}
}
return completions;
}
Replxx::hints_t
hook_hint(std::string const& context, int& contextLen, Replxx::Color& color,
std::vector<std::string> const& examples)
{
Replxx::hints_t hints;
// only show hint if prefix is at least 'n' chars long
// or if prefix begins with a specific character
int utf8ContextLen(context_len(context.c_str()));
int prefixLen(static_cast<int>(context.length()) - utf8ContextLen);
contextLen =
utf8str_codepoint_len(context.c_str() + prefixLen, utf8ContextLen);
std::string prefix{context.substr(prefixLen)};
if (prefix.size() >= 2 || (!prefix.empty() && prefix.at(0) == '.')) {
for (auto const& e : examples) {
if (e.compare(0, prefix.size(), prefix) == 0) {
hints.emplace_back(e.c_str());
}
}
}
// set hint color to green if single match found
if (hints.size() == 1) {
color = Replxx::Color::GREEN;
}
return hints;
}
void
hook_color(
std::string const& context, Replxx::colors_t& colors,
std::vector<std::pair<std::string, Replxx::Color>> const& regex_color)
{
// highlight matching regex sequences
for (auto const& e : regex_color) {
size_t pos{0};
std::string str = context;
std::smatch match;
while (std::regex_search(str, match, std::regex(e.first))) {
std::string c{match[0]};
std::string prefix(match.prefix().str());
pos += utf8str_codepoint_len(prefix.c_str(),
static_cast<int>(prefix.length()));
int len(
utf8str_codepoint_len(c.c_str(), static_cast<int>(c.length())));
for (int i = 0; i < len; ++i) {
colors.at(pos + i) = e.second;
}
pos += len;
str = match.suffix();
}
}
}
Replxx::ACTION_RESULT
message(Replxx& replxx, std::string s, char32_t)
{
replxx.invoke(Replxx::ACTION::CLEAR_SELF, 0);
replxx.print("%s\n", s.c_str());
replxx.invoke(Replxx::ACTION::REPAINT, 0);
return (Replxx::ACTION_RESULT::CONTINUE);
}
bool
sim::client::CLI::Setup()
{
try {
rx_.install_window_change_handler();
// load the history file if it exists
rx_.history_load(history_file);
// set the max history size
rx_.set_max_history_size(128);
// set the max number of hint rows to show
rx_.set_max_hint_rows(3);
// set the callbacks
using namespace std::placeholders;
rx_.set_completion_callback(
std::bind(&hook_completion, _1, _2, cref(examples)));
rx_.set_highlighter_callback(
std::bind(&hook_color, _1, _2, cref(regex_color)));
rx_.set_hint_callback(
std::bind(&hook_hint, _1, _2, _3, cref(examples)));
// other api calls
rx_.set_word_break_characters(" \t.,-%!;:=*~^'\"/?<>|[](){}");
rx_.set_completion_count_cutoff(128);
rx_.set_double_tab_completion(false);
rx_.set_complete_on_empty(true);
rx_.set_beep_on_ambiguous_completion(false);
rx_.set_no_color(false);
BindKeys();
return true;
} catch (...) {
return false;
}
}
void
sim::client::CLI::RunLoop()
{
// main repl loop
for (;;) {
// display the prompt and retrieve input from the user
char const* cinput{nullptr};
do {
cinput = rx_.input(prompt);
} while ((cinput == nullptr) && (errno == EAGAIN));
if (cinput == nullptr) {
break;
}
// change cinput into a std::string
// easier to manipulate
std::string input{cinput};
if (input.empty()) {
continue;
} else {
rx_.history_add(input);
// pass to RPC-Client
process_callback(input);
}
}
// save the history
rx_.history_sync(history_file);
}
void
sim::client::CLI::BindKeys()
{
using namespace std::placeholders;
rx_.bind_key_internal(Replxx::KEY::BACKSPACE,
"delete_character_left_of_cursor");
rx_.bind_key_internal(Replxx::KEY::DELETE, "delete_character_under_cursor");
rx_.bind_key_internal(Replxx::KEY::LEFT, "move_cursor_left");
rx_.bind_key_internal(Replxx::KEY::RIGHT, "move_cursor_right");
rx_.bind_key_internal(Replxx::KEY::UP, "history_previous");
rx_.bind_key_internal(Replxx::KEY::DOWN, "history_next");
rx_.bind_key_internal(Replxx::KEY::PAGE_UP, "history_first");
rx_.bind_key_internal(Replxx::KEY::PAGE_DOWN, "history_last");
rx_.bind_key_internal(Replxx::KEY::HOME, "move_cursor_to_begining_of_line");
rx_.bind_key_internal(Replxx::KEY::END, "move_cursor_to_end_of_line");
rx_.bind_key_internal(Replxx::KEY::TAB, "complete_line");
rx_.bind_key_internal(Replxx::KEY::control(Replxx::KEY::LEFT),
"move_cursor_one_word_left");
rx_.bind_key_internal(Replxx::KEY::control(Replxx::KEY::RIGHT),
"move_cursor_one_word_right");
rx_.bind_key_internal(Replxx::KEY::control(Replxx::KEY::UP),
"hint_previous");
rx_.bind_key_internal(Replxx::KEY::control(Replxx::KEY::DOWN), "hint_next");
rx_.bind_key_internal(Replxx::KEY::control(Replxx::KEY::ENTER),
"commit_line");
rx_.bind_key_internal(Replxx::KEY::control('R'),
"history_incremental_search");
rx_.bind_key_internal(Replxx::KEY::control('W'),
"kill_to_begining_of_word");
rx_.bind_key_internal(Replxx::KEY::control('U'),
"kill_to_begining_of_line");
rx_.bind_key_internal(Replxx::KEY::control('K'), "kill_to_end_of_line");
rx_.bind_key_internal(Replxx::KEY::control('Y'), "yank");
rx_.bind_key_internal(Replxx::KEY::control('L'), "clear_screen");
rx_.bind_key_internal(Replxx::KEY::control('D'), "send_eof");
rx_.bind_key_internal(Replxx::KEY::control('C'), "abort_line");
rx_.bind_key_internal(Replxx::KEY::control('T'), "transpose_characters");
#ifndef _WIN32
rx_.bind_key_internal(Replxx::KEY::control('V'), "verbatim_insert");
rx_.bind_key_internal(Replxx::KEY::control('Z'), "suspend");
#endif
rx_.bind_key_internal(Replxx::KEY::meta(Replxx::KEY::BACKSPACE),
"kill_to_whitespace_on_left");
rx_.bind_key_internal(Replxx::KEY::meta('p'),
"history_common_prefix_search");
rx_.bind_key_internal(Replxx::KEY::meta('n'),
"history_common_prefix_search");
rx_.bind_key_internal(Replxx::KEY::meta('d'), "kill_to_end_of_word");
rx_.bind_key_internal(Replxx::KEY::meta('y'), "yank_cycle");
rx_.bind_key_internal(Replxx::KEY::meta('u'), "uppercase_word");
rx_.bind_key_internal(Replxx::KEY::meta('l'), "lowercase_word");
rx_.bind_key_internal(Replxx::KEY::meta('c'), "capitalize_word");
rx_.bind_key_internal('a', "insert_character");
rx_.bind_key_internal(Replxx::KEY::INSERT, "toggle_overwrite_mode");
rx_.bind_key(Replxx::KEY::F1,
std::bind(&message, std::ref(rx_), "<F1>", _1));
rx_.bind_key(Replxx::KEY::F2,
std::bind(&message, std::ref(rx_), "<F2>", _1));
rx_.bind_key(Replxx::KEY::F3,
std::bind(&message, std::ref(rx_), "<F3>", _1));
rx_.bind_key(Replxx::KEY::F4,
std::bind(&message, std::ref(rx_), "<F4>", _1));
rx_.bind_key(Replxx::KEY::F5,
std::bind(&message, std::ref(rx_), "<F5>", _1));
rx_.bind_key(Replxx::KEY::F6,
std::bind(&message, std::ref(rx_), "<F6>", _1));
rx_.bind_key(Replxx::KEY::F7,
std::bind(&message, std::ref(rx_), "<F7>", _1));
rx_.bind_key(Replxx::KEY::F8,
std::bind(&message, std::ref(rx_), "<F8>", _1));
rx_.bind_key(Replxx::KEY::F9,
std::bind(&message, std::ref(rx_), "<F9>", _1));
rx_.bind_key(Replxx::KEY::F10,
std::bind(&message, std::ref(rx_), "<F10>", _1));
rx_.bind_key(Replxx::KEY::F11,
std::bind(&message, std::ref(rx_), "<F11>", _1));
rx_.bind_key(Replxx::KEY::F12,
std::bind(&message, std::ref(rx_), "<F12>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F1),
std::bind(&message, std::ref(rx_), "<S-F1>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F2),
std::bind(&message, std::ref(rx_), "<S-F2>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F3),
std::bind(&message, std::ref(rx_), "<S-F3>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F4),
std::bind(&message, std::ref(rx_), "<S-F4>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F5),
std::bind(&message, std::ref(rx_), "<S-F5>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F6),
std::bind(&message, std::ref(rx_), "<S-F6>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F7),
std::bind(&message, std::ref(rx_), "<S-F7>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F8),
std::bind(&message, std::ref(rx_), "<S-F8>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F9),
std::bind(&message, std::ref(rx_), "<S-F9>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F10),
std::bind(&message, std::ref(rx_), "<S-F10>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F11),
std::bind(&message, std::ref(rx_), "<S-F11>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::F12),
std::bind(&message, std::ref(rx_), "<S-F12>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F1),
std::bind(&message, std::ref(rx_), "<C-F1>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F2),
std::bind(&message, std::ref(rx_), "<C-F2>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F3),
std::bind(&message, std::ref(rx_), "<C-F3>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F4),
std::bind(&message, std::ref(rx_), "<C-F4>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F5),
std::bind(&message, std::ref(rx_), "<C-F5>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F6),
std::bind(&message, std::ref(rx_), "<C-F6>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F7),
std::bind(&message, std::ref(rx_), "<C-F7>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F8),
std::bind(&message, std::ref(rx_), "<C-F8>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F9),
std::bind(&message, std::ref(rx_), "<C-F9>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F10),
std::bind(&message, std::ref(rx_), "<C-F10>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F11),
std::bind(&message, std::ref(rx_), "<C-F11>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::F12),
std::bind(&message, std::ref(rx_), "<C-F12>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::TAB),
std::bind(&message, std::ref(rx_), "<S-Tab>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::HOME),
std::bind(&message, std::ref(rx_), "<C-Home>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::HOME),
std::bind(&message, std::ref(rx_), "<S-Home>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::END),
std::bind(&message, std::ref(rx_), "<C-End>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::END),
std::bind(&message, std::ref(rx_), "<S-End>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::PAGE_UP),
std::bind(&message, std::ref(rx_), "<C-PgUp>", _1));
rx_.bind_key(Replxx::KEY::control(Replxx::KEY::PAGE_DOWN),
std::bind(&message, std::ref(rx_), "<C-PgDn>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::LEFT),
std::bind(&message, std::ref(rx_), "<S-Left>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::RIGHT),
std::bind(&message, std::ref(rx_), "<S-Right>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::UP),
std::bind(&message, std::ref(rx_), "<S-Up>", _1));
rx_.bind_key(Replxx::KEY::shift(Replxx::KEY::DOWN),
std::bind(&message, std::ref(rx_), "<S-Down>", _1));
}
|
#include "I2Y0A21.h"
I2Y0A21 i(6,0.1);
void setup() {
Serial.begin(9800);
}
void loop() {
Serial.println(i.measure());
delay(100);
}
|
#ifndef _GBUFFEREDINPUT_H
#define _GBUFFEREDINPUT_H
#include "../G_Core/GBroadcasting.h"
#include "../G_System/GKeyDefines.h"
namespace GW
{
namespace CORE
{
#pragma pack(push, 1)
//! G_INPUT_DATA will hold any information you may need about an Input Event.
/*!
*/
struct G_INPUT_DATA
{
int _data; /*<_data Data store the key/button information. */
int _x; /*<_x Window Mouse position x when event is send. */
int _y; /*<_y Window Mouse position y when event is send. */
int _screenX; /*<_x Screen Mouse position x when event is send. */
int _screenY; /*<_y Screen Mouse position y when event is send. */
};
#pragma pack(pop)
//! GBInput_Events hold the possible events that can be sent from GBufferedInput.
/*!
*/
enum GBInput_Events {
KEYPRESSED, /*<KEYPRESSED Key pressed event. */
KEYRELEASED, /*<KEYRELEASED Key released event. */
BUTTONPRESSED, /*<BUTTONPRESSED Button pressed event. */
BUTTONRELEASED, /*<BUTTONRELEASED Button released event. */
MOUSESCROLL, /*<MOUSESCROLL Mouse scroll event. */
};
static const GUUIID GBufferedInputUUIID =
{
0x4cba9d69, 0x1b32, 0x43da,{ 0xb7, 0xb2, 0xa4, 0x21, 0xc5, 0x78, 0x18, 0xf0 }
};
//! A Multi threaded buffered input library.
/*!
* Register with a GBufferedInput to recieve mouse and keyboard events.
*/
class GBufferedInput : public GBroadcasting { };
//! Creates a GBufferedInput Object.
/*!
*
* \param [out] _outBufferedInput
* \param [in] _data (Windows) The handle to the window (HWND).
* \param [in] _data (Linux) Not Yet Implemented.
* \param [in] _data (Max) Not Yet Implemented.
*
* \retval SUCCESS no problems found.
* \retval FAILURE could not make an BufferedInput Object.
* \retval INVALID_ARGUMENT _outInput and or _data is nullptr.
*/
GRETURN CreateGBufferedInput(GBufferedInput** _outBufferedInput, void * _data);
};
};
#endif
|
#include <QtTest/QtTest>
#include <QObject>
#include "generator.h"
#include "plugins.h"
#include "menu.h"
class TestGenerator : public QObject
{
Q_OBJECT
private slots:
void generateSite();
void translateContent_data();
void translateContent();
void nextTokens_data();
void nextTokens();
void initTestCase();
void cleanupTestCase();
};
class TextEditor : public ElementEditorInterface
{
Q_OBJECT
public:
TextEditor() {}
void setContent(QString) {}
QString className() override {return "TextEditor";}
QString displayName() override {return "Text";}
QString tagName() override {return "Text";}
QImage icon() override {return QImage(":/images/text.png");}
QString version() override {return "1.5.4";}
QString getHtml(QXmlStreamReader *) {return "<h1>testPageTitle</h1>";}
QString load(QXmlStreamReader *) override {return "";}
public slots:
void closeEditor() override {}
};
void TestGenerator::initTestCase()
{
QDir dir("/home/olaf/SourceCode/FlatSiteBuilder/test");
dir.mkdir("sites");
}
void TestGenerator::cleanupTestCase()
{
QDir dir("/home/olaf/SourceCode/FlatSiteBuilder/test/sites");
dir.removeRecursively();
}
void TestGenerator::nextTokens_data()
{
QTest::addColumn<QString>("content");
QTest::addColumn<QStringList>("tokens");
QTest::addColumn<bool>("result");
QTest::newRow("endif a") << "{% endif %}" << (QStringList() << "{%" << "endif" << "%}") << true;
QTest::newRow("endif b") << "{% endif %}" << (QStringList() << "{%" << "endif" << "%}") << true;
QTest::newRow("endif c") << "{% endif %}" << (QStringList() << "{%" << "endif" << "%}") << true;
QTest::newRow("endif d") << "{% endifa %}" << (QStringList() << "{%" << "endif" << "%}") << false;
QTest::newRow("endif e") << "{% aendif %}" << (QStringList() << "{%" << "endif" << "%}") << false;
QTest::newRow("endif f") << "{%a endif %}" << (QStringList() << "{%" << "endif" << "%}") << false;
QTest::newRow("endif g") << "{% endif a%}" << (QStringList() << "{%" << "endif" << "%}") << false;
QTest::newRow("endif h") << "a{% endif %}" << (QStringList() << "{%" << "endif" << "%}") << false;
QTest::newRow("endif i") << "{% endif %}a" << (QStringList() << "{%" << "endif" << "%}") << true;
}
void TestGenerator::nextTokens()
{
QFETCH(QString, content);
QFETCH(QStringList, tokens);
QFETCH(bool, result);
Generator g;
QCOMPARE(g.nextTokens(content, tokens), result);
}
void TestGenerator::translateContent_data()
{
QTest::addColumn<QString>("var");
QTest::addColumn<QString>("result");
QTest::newRow("page") << "{{ page.title }}" << "PageTitle";
QTest::newRow("site") << "{{ site.title }}" << "SiteTitle";
QTest::newRow("loop") << "{{ item.title }}" << "ItemTitle";
QTest::newRow("wrong loop") << "{{ ite.title }}" << "";
QTest::newRow("loop without spaces") << "{{item.title}}" << "ItemTitle";
QTest::newRow("loop left space") << "{{ item.title}}" << "ItemTitle";
QTest::newRow("loop left spaces") << "{{ item.title}}" << "ItemTitle";
QTest::newRow("loop right space") << "{{item.title }}" << "ItemTitle";
QTest::newRow("loop right spaces") << "{{item.title }}" << "ItemTitle";
QTest::newRow("for a") << "{% for item in site.menus[page.menu] %}{{ item.title }}{% endfor %}" << "MenuItemTitle";
QTest::newRow("for b") << "{% for item in site.menus[page.menu] %}{{ item.title }}{%endfor %}" << "MenuItemTitle";
QTest::newRow("for c") << "{% for item in site.menus[page.menu] %}{{ item.title }}{% endfor%}" << "MenuItemTitle";
QTest::newRow("for d") << "{% for item in site.menus[page.menu] %}{{ item.title }}{%endfor%}" << "MenuItemTitle";
QTest::newRow("for e") << "{% for item in site.menus[page.menu] %}\n{{ item.title }}\n{%endfor%}\n" << "MenuItemTitle\n";
QTest::newRow("for wrong index") << "{% for item in site.menus[page.menus] %}{{ item.title }}{% endfor %}" << "";
QTest::newRow("for nested a") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{% endfor %}{% endfor %}" << "SubItemTitle";
QTest::newRow("for nested b") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{% endfor %}{% endfor %}" << "SubItemTitle";
QTest::newRow("for nested c") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{% endfor %}{% endfor %}" << "SubItemTitle";
QTest::newRow("for nested d") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{% endfor %}{% endfor %}" << "SubItemTitle";
QTest::newRow("for nested e") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{% endfor %}{% endfor %}" << "SubItemTitle";
QTest::newRow("for nested f") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{% endfor %}{% endfor %}" << "SubItemTitle";
QTest::newRow("for nested g") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{%endfor %}{% endfor %}" << "SubItemTitle";
QTest::newRow("for nested h") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{% endfor%}{% endfor %}" << "SubItemTitle";
QTest::newRow("for nested i") << "{% for item in site.menus[page.menu] %}{% for subitem in item.items %}{{ subitem.title }}{%endfor%}{% endfor %}" << "SubItemTitle";
QTest::newRow("if equal theme a") << "{% if theme.switch %}left{% endif %}" << "left";
QTest::newRow("if equal theme b") << "{% if theme.switch == true %}left{% endif %}" << "left";
QTest::newRow("if equal theme c") << "{% if theme.switch == false %}left{% endif %}" << "";
QTest::newRow("if equal theme d") << "{% if theme.noswitch %}left{% endif %}" << "";
QTest::newRow("if equal theme e") << "{% if theme.noswitch == true %}left{% endif %}" << "";
QTest::newRow("if equal theme f") << "{% if theme.noswitch == false %}left{% endif %}" << "left";
QTest::newRow("if equal theme undef a") << "{% if theme.switc %}left{% endif %}" << "";
QTest::newRow("if equal theme undef b") << "{% if theme.switc == true %}left{% endif %}" << "";
QTest::newRow("if not equal theme a") << "{% if theme.switch != true %}left{% endif %}" << "";
QTest::newRow("if not equal theme c") << "{% if theme.switch != false %}left{% endif %}" << "left";
QTest::newRow("if not equal theme d") << "{% if theme.noswitch != true %}left{% endif %}" << "left";
QTest::newRow("if not equal theme e") << "{% if theme.noswitch != false %}left{% endif %}" << "";
QTest::newRow("if not equal theme undef a") << "{% if theme.switc != true %}left{% endif %}" << "left";
QTest::newRow("if not equal theme undef b") << "{% if theme.switc == false %}left{% endif %}" << "left";
QTest::newRow("if equal a") << "{% if site.title == \"SiteTitle\" %}true{% endif %}" << "true";
QTest::newRow("if equal b") << "{% if site.title == \"SiteTitl\" %}true{% endif %}" << "";
QTest::newRow("if not equal") << "{% if site.title != \"Siteitle\" %}false{% endif %}" << "false";
QTest::newRow("if else a") << "{% if site.title == \"Siteitle\" %}true{% else %}false{% endif %}" << "false";
QTest::newRow("if else b") << "{% if site.title == \"SiteTitle\" %}true{% else %}false{% endif %}" << "true";
QTest::newRow("if equal space a") << "{% if site.title == \"SiteTitle\" %}true{% endif %}" << "true";
QTest::newRow("if equal space b") << "{% if site.title == \"SiteTitle\" %}true{% endif %}" << "true";
QTest::newRow("if equal space c") << "{% if site.title == \"SiteTitle\" %}true{% endif %}" << "true";
QTest::newRow("if equal space d") << "{% if site.title == \"SiteTitle\" %}true{% endif %}" << "true";
QTest::newRow("if equal space e") << "{% if site.title == \"SiteTitle\" %}true{% endif %}" << "true";
QTest::newRow("if equal space f") << "{% if site.title == \"SiteTitle\" %}true{% endif %}" << "true";
QTest::newRow("if else space a") << "{% if site.title == \"SiteTitle\" %}true{% else %}false{% endif %}" << "true";
QTest::newRow("if else space b") << "{% if site.title == \"SiteTitle\" %}true{% else %}false{% endif %}" << "true";
QTest::newRow("if else no space a") << "{% if site.title == \"SiteTitle\" %}true{%else%}false{% endif %}" << "true";
QTest::newRow("if else no space b") << "{% if site.title == \"SiteTitle\" %}true{%else %}false{% endif %}" << "true";
QTest::newRow("if else no space c") << "{% if site.title == \"SiteTitle\" %}true{% else%}false{% endif %}" << "true";
QTest::newRow("if endif no space a") << "{% if site.title == \"SiteTitle\" %}true{% else %}false{%endif%}" << "true";
QTest::newRow("if endif no space b") << "{% if site.title == \"SiteTitle\" %}true{% else %}false{%endif %}" << "true";
QTest::newRow("if endif no space c") << "{% if site.title == \"SiteTitle\" %}true{% else%}false{% endif%}" << "true";
QTest::newRow("if nested a") << "{% if site.title == \"SiteTitle\" %}{% if page.title == site.title %}A{% else %}B{% endif %}{% else %}C{% endif %}" << "B";
QTest::newRow("if nested b") << "{% if site.title == \"SiteTitle\" %}A{% else %}{% if page.title == site.title %}B{% else %}C{% endif %}{% endif %}" << "A";
QTest::newRow("if nested c") << "{% if site.title == \"Sitetitle\" %}{% if page.title == site.title %}A{% else %}B{% endif %}{% else %}C{% endif %}" << "C";
QTest::newRow("if nested d") << "{% if site.title == \"Sitetitle\" %}{% if page.title == site.title %}A{% else %}B{% endif %}{% else %}C{% endif %}" << "C";
QTest::newRow("if nested e") << "{% if site.title == \"SiteTitle\" %}A{% else %}{% if page.title == site.title %}B{% else %}C{% endif %}{% endif %}D" << "AD";
QTest::newRow("if nested f") << "{% if true == false %}A{% else %}B{% if true == true %}C{% else %}D{% endif %}E{% endif %}F" << "BCEF";
QTest::newRow("if nested g") << "{% if true == true %}A{% if true == true %}B{% endif %}C{% endif %}D" << "ABCD";
QTest::newRow("if nested h") << "{% if true == true %}A{% if true == true %}B{% else %}C{% endif %}D{% endif %}E" << "ABDE";
}
void TestGenerator::translateContent()
{
QFETCH(QString, var);
QFETCH(QString, result);
QVariantMap loopvars;
Generator g;
QVariantMap cm;
cm["title"] = "ItemTitle";
loopvars["item"] = cm;
QVariantMap menus;
QVariantList items;
QVariantMap menuitem;
menuitem["title"] = "MenuItemTitle";
QVariantList subitems;
QVariantMap submenuitem;
submenuitem["title"] = "SubItemTitle";
subitems.append(submenuitem);
menuitem["items"] = subitems;
menuitem["hasItems"] = "true";
items.append(menuitem);
menus["MenuName"] = items;
g.addSiteVar("menus", menus);
g.addSiteVar("title", "SiteTitle");
g.addThemeVar("switch", "true");
g.addThemeVar("noswitch", "false");
g.addPageVar("title", "PageTitle");
g.addPageVar("menu", "MenuName");
QString rc = g.translateContent(var, loopvars);
QCOMPARE(rc, result);
}
void TestGenerator::generateSite()
{
Plugins::insert("TextEditor", new TextEditor());
QString dir = "/home/olaf/SourceCode/FlatSiteBuilder/test";
Generator g;
g.setSitesPath(dir + "/sites");
g.setThemePath(dir + "/themes");
Site *site = new Site(NULL, dir + "/Site.xml");
site->setCopyright("siteCopyright");
site->setTheme("testSiteTheme");
site->setTitle("testSiteTitle");
site->setAuthor("testSiteAuthor");
site->setDescription("testSiteDescription");
site->setKeywords("testSiteKeywords");
Content *page = new Content(ContentType::Page);
page->setSource("test.xml");
page->setTitle("testPageTitle");
page->setLayout("testPageLayout");
page->addAttribute("language", "de");
page->setMenu("testMenu");
Menu *menu = new Menu();
menu->setName("testMenu");
MenuItem *item = new MenuItem();
item->setTitle("testMenuItemTitle");
item->setUrl("test.html");
menu->addMenuitem(item);
MenuItem *item2 = new MenuItem();
item2->setTitle("testMenuItemTitle2");
item2->setUrl("testMenuItemUrl2");
MenuItem *item3 = new MenuItem();
item3->setTitle("testMenuItemTitle3");
item3->setUrl("testMenuItemUrl3");
item2->addMenuitem(item3);
menu->addMenuitem(item2);
site->addMenu(menu);
site->addPage(page);
g.generateSite(NULL, site);
QStringList list;
list << "<html>\n";
list << "<head>\n";
list << "<meta name=\"description\" content=\"testSiteDescription\">\n";
list << "<meta name=\"keywords\" content=\"testSiteKeywords\"/>\n";
list << "<meta name=\"author\" content=\"testSiteAuthor\">\n";
list << "<title>testSiteTitle</title>\n";
list << "</head>\n";
list << "<body>\n";
list << "<ul>\n";
list << "<li class=\"active\"><a href=\"test.html\">testMenuItemTitle</a></li>\n";
list << "<li class=\"dropdown\">\n";
list << "<a class=\"dropdown-toggle\" href=\"#\">\n";
list << "<img src=\"\" width=\"16\" height=\"11\" alt=\"testMenuItemTitle2\" /> testMenuItemTitle2 <i class=\"fa fa-angle-down\"></i>\n";
list << "</a>\n";
list << "<ul class=\"dropdown-menu\">\n";
list << "<li>\n";
list << "<a href=\"testMenuItemUrl3\"><img src=\"\" width=\"16\" height=\"11\" alt=\"testMenuItemTitle3\" /> testMenuItemTitle3</a>\n";
list << "</li>\n";
list << "</ul>\n";
list << "</li>\n";
list << "</ul>\n";
list << "<!-- language = \"de\" -->\n";
list << "<!-- german -->\n";
list << "<!-- german -->\n";
list << "<!-- end of language -->\n";
list << "<section class=\"container\">\n";
list << "<div class=\"row\">\n";
list << "<div class=\"col-md-12\">\n";
list << "<h1>testPageTitle</h1>\n";
list << "</div>\n";
list << "</div>\n";
list << "</section>\n";
list << "</body>\n";
list << "</html>\n";
QFile file(dir + "/sites/testSiteTitle/test.html");
QVERIFY2(file.exists(), "Output file has not been generated");
if(file.open(QFile::ReadOnly))
{
for(int i=0; i < list.count(); i++)
{
QString content = QString::fromLatin1(file.readLine());
QCOMPARE(content, list.at(i));
}
file.close();
}
}
QTEST_MAIN(TestGenerator)
#include "testgenerator.moc"
|
/*
Name: ไปฃไปท
Copyright:
Author: Hill Bamboo
Date: 2019/8/21 16:45:09
Description:
ไธ็ฅ้pddๅบ่ฟ้ขๆๅฅๆไน
ๆฉๅฑ๏ผ ็ปๅฎn ไธชไปปๅก๏ผ ๆฏไธชไปปๅก็ไปฃไปทๆฏ c_i, ๅๅฎ็ฌฌiไธชไปปๅกๅๅฏไปฅ็จ |c_i - c_j| ็ไปฃไปทๅฎๆ็ฌฌ j ไธชไปปๅก
่งฃๆณ๏ผ ๆๅคงๅผๅๆๅฐๅผ
*/
#include <bits/stdc++.h>
using namespace std;
// https://www.nowcoder.com/questionTerminal/b7985769dc434d85a16717908669bcab?f=discussion
const int INF = 1e9;
void solve() {
int minv = INF;
int maxv = -INF;
int num = 0;
while (~scanf("%d", &num)) {
if (num < minv) minv = num;
if (maxv < num) maxv = num;
}
cout << (maxv - minv) << endl;
}
int main() {
int arr[3];
int n = 0;
while (~scanf("%d", &arr[n])) ++n;
int ans[3] = {0, 0, 0};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (j != i) ans[i] += abs(arr[i] - arr[j]);
}
}
sort(ans, ans + 3);
printf("%d\n", ans[0]);
return 0;
}
|
#pragma once
#ifndef IMAGIO_JOINT_TRACKER
#define IMAGIO_JOINT_TRACKER
#pragma once
#define GLM_FORCE_RADIANS
#pragma warning(push, 0)
#include <glm/gtc/matrix_transform.hpp>
#include <glm/mat4x4.hpp>
#include <glm/gtc/type_ptr.hpp>
#pragma warning(pop)
#include <vector>
#include <cmath>
#include <tuple>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include "../viewers/3d/painter3d.h"
namespace imagio
{
class joint_tracker
{
private:
const float pi = 3.1415926535897f;
const float pnoise = 0.01f;
const float pinvisible = 0.1f;
//const float sigma = 0.0001f;
const float sigma = 0.0001f;
const int force_lambda = 100;
const int em_itterations = 20;
const float depth_occlude_tol = 0.03f;
std::vector<std::tuple<glm::vec3, const ImColor&, std::string>> joints;
// wimgui::vertex* points = nullptr;
unsigned int points_count = 0;
std::vector<std::vector<float>> alpha_kn;
std::vector<glm::vec3> force_k;
std::vector<std::vector<float>> distance;
std::vector<float> visibility_k;
public:
joint_tracker(std::vector<std::tuple<glm::vec3, const ImColor&, std::string>> initial_joints) : joints(initial_joints) {};
// void new_frame(wimgui::vertex* vertices, unsigned int vertices_count);
void calculate_visibility_k();
void calculate_alpha_kn();
void calculate_force_k();
std::vector<std::vector<float>>& get_alpha_kn() { return alpha_kn; }
std::vector<std::vector<float>>& get_distance() { return distance; }
std::vector<glm::vec3>& get_force_k() { return force_k; }
};
}
#endif
|
/* This file is part of FineFramework project */
#ifndef FFW_UTILS_MATH_TOKENIZER
#define FFW_UTILS_MATH_TOKENIZER
#include "config.h"
#include <string>
namespace ffw {
/**
* @ingroup utils
*/
template<class T, typename CharTrait = std::char_traits<T>, typename Allocator = std::allocator<T>>
class Tokenizer {
public:
Tokenizer(const std::basic_string<T, CharTrait, Allocator>& str, const std::basic_string<T, CharTrait, Allocator>& delim):ptr(str),del(delim) {
pos = 0;
last = 0;
}
bool getNext(std::basic_string<T, CharTrait, Allocator>* str) {
// Loop until all tokens found
while (del.size() > 0 && (pos = ptr.find(del, pos)) != std::basic_string<T, CharTrait, Allocator>::npos) {
// Do we have non-empty token?
if (last < pos && pos - last > 0) {
if(str != NULL)*str = ptr.substr(last, pos - last);
pos += del.size();
last = pos;
return true;
}
pos += del.size();
last = pos;
}
// add the last token (will also include a whole string when no delim was found)
if (last < ptr.size()) {
if (str != NULL)*str = ptr.substr(last, ptr.size() - last);
last = ptr.size();
return true;
}
return false;
}
std::basic_string<T, CharTrait, Allocator> getNext() {
std::basic_string<T, CharTrait, Allocator> str;
getNext(&str);
return str;
}
bool skipNext() {
return getNext(NULL);
}
bool hasNext() {
size_t tempLast = last;
size_t tempPos = pos;
bool result = getNext(NULL);
last = tempLast;
pos = tempPos;
return result;
}
size_t getPos() {
return pos;
}
private:
const std::basic_string<T, CharTrait, Allocator>& ptr;
const std::basic_string<T, CharTrait, Allocator> del;
size_t pos = 0;
size_t last = 0;
};
}
#endif
|
/* ะกะพััะธัะพะฒะบะฐ ัะตัะฝัั
ัะธัะตะป ะธะท ัะฐะนะปะฐ
1. ะะฒะตััะธ ะธะผั ัะฐะนะปะฐ ั ะบะพะฝัะพะปะธ.
2. ะัะพัะธัะฐัั ะธะท ะฝะตะณะพ ะฝะฐะฑะพั ัะธัะตะป.
3. ะัะฒะตััะธ ะฝะฐ ะบะพะฝัะพะปั ัะพะปัะบะพ ัะตัะฝัะต, ะพััะพััะธัะพะฒะฐะฝะฝัะต ะฟะพ ะฒะพะทัะฐััะฐะฝะธั.
ะัะธะผะตั ะฒะฒะพะดะฐ:
5
8
11
3
2
10
ะัะธะผะตั ะฒัะฒะพะดะฐ:
2
8
10
*/
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Solution
{
public static void main(String[] args) throws Exception
{
ArrayList<Integer> list = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String file_N = reader.readLine();//D:\ะ ะฐะฑะพัะฐ\cvc.txt
FileReader fin = new FileReader(file_N);
Scanner src = new Scanner(fin);
while (src.hasNextInt()){
int i = src.nextInt();
if(i%2==0){
list.add(i);
}
}
src.close();
for(int p = list.size();p>0;p--){
int tmp;
for(int i=1;i<p;i++){
if(list.get(i-1)>list.get(i)){
tmp = list.get(i-1);
list.set(i-1,list.get(i));
list.set(i,tmp);
}
}
}
for(Integer c : list){
System.out.println(c);
}
}
}
|
//
// StateIndicatorLED.hpp
//
//
// Created by Markus Buhl on 15.11.18.
//
#ifndef StateIndicatorLED_hpp
#define StateIndicatorLED_hpp
#include <stdio.h>
#include "StateIndicatorLED.hpp"
#include "Arduino.h"
#include "FastLED.h"
enum IndicatorLEDType {
SOLID,
BLINKING,
BREATHING
};
class StateIndicatorLED {
protected:
unsigned int m_LEDIndex;
CRGB m_color;
IndicatorLEDType m_LEDType;
byte m_stateCounter = 0;
const int m_interval = 50;
const int m_incrementSpeed = 2;
public:
StateIndicatorLED() {
m_LEDIndex = 0;
m_color = CRGB::Blue;
m_LEDType = SOLID;
}
StateIndicatorLED(unsigned int LEDIndex, CRGB baseColor, IndicatorLEDType LEDType) {
m_LEDIndex = LEDIndex;
m_color = baseColor;
m_LEDType = LEDType;
}
void setLEDIndex(unsigned int LEDIndex) {
m_LEDIndex = LEDIndex;
}
unsigned int getLEDIndex() {
return m_LEDIndex;
}
void setColor(CRGB color) {
m_color = color;
}
CRGB getColor() {
switch(m_LEDType) {
case IndicatorLEDType::SOLID:
return m_color;
break;
case IndicatorLEDType::BLINKING:
m_stateCounter+=m_incrementSpeed;
if(m_stateCounter > m_interval) {
m_stateCounter = 0;
}
return (m_stateCounter < m_interval / 2) ? m_color : CRGB::Black;
break;
case IndicatorLEDType::BREATHING:
byte v = sin8(m_stateCounter);
byte r = m_color.r / 255 * v;
byte g = m_color.g / 255 * v;
byte b = m_color.b / 255 * v;
m_stateCounter+=m_incrementSpeed;
return CRGB(r,g,b);
break;
}
return m_color;
}
void setLEDType(IndicatorLEDType LEDType) {
m_stateCounter = 0;
m_LEDType = LEDType;
}
IndicatorLEDType getLEDType() {
return m_LEDType;
}
};
#endif /* StateIndicatorLED_hpp */
|
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<vector>
int main()
{
int k,N,M,*x,*y,i,j=0;
std::vector <std::string> output;
do{
std::cin>>k;
if(k==0)
break;
x=(int*)calloc(k,sizeof(int));
y=(int*)calloc(k,sizeof(int));
std::cin>>N>>M;
for(i=0;i<k;i++)
std::cin>>x[i]>>y[i];
for(i=0;i<k;i++,j++)
{
if((x[i]-N)==0||(y[i]-M)==0)
output.push_back("divisa");
else if((x[i]-N)>0&&(y[i]-M)>0)
output.push_back("NE");
else if((x[i]-N)<0&&(y[i]-M)>0)
output.push_back("NO");
else if((x[i]-N)<0&&(y[i]-M)<0)
output.push_back("SO");
else if((x[i]-N)>0&&(y[i]-M)<0)
output.push_back("SE");
}
}while(k!=0);
for(i=0;i<output.size();i++)
{
std::cout<<output[i]<<"\n";
}
return 0;
}
|
// This program is free software: you can use, modify and/or redistribute it
// under the terms of the simplified BSD License. You should have received a
// copy of this license along this program. If not, see
// <http://www.opensource.org/licenses/bsd-license.html>.
//
// Copyright (C) 2014, Roberto P.Palomares <r.perezpalomares@gmail.com>
// All rights reserved.
#ifndef ENERGY_MODEL
#define ENERGY_MODEL
#include <cmath>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <algorithm>
extern "C" {
#include "bicubic_interpolation.h"
//#include "mask.h"
}
#include "utils.h"
#include "energy_structures.h"
#include "aux_energy_model.h"
#include "energy_model.h"
//Models
#include "tvl2_model.h"
#include "nltv_model.h"
#include "tvcsad_model.h"
#include "nltvcsad_model.h"
//Models with weights
#include "tvl2w_model.h"
#include "nltvw_model.h"
#include "nltvcsadw_model.h"
#include "tvcsadw_model.h"
//Models with occlusions
#include "tvl2_model_occ.h"
void rgb_to_gray(const float *in, const int w, const int h, float *out){
const int size = w*h;
for (int i = 0; i < size; i++){
out[i] = .299*in[i] + .587*in[size + i] + .114*in[2*size + i];
}
}
float pow2( const float f ) {return f*f;}
//Asume que las imagenes no estan normalizadas
void rgb_to_lab(const float *in, int size, float *out){
const float T = 0.008856;
const float color_attenuation = 1.5f;
for(int i = 0 ; i < size ; i++){
const float r = in[i]/255.f;
const float g = in[i + size]/255.f;
const float b = in[i + 2*size]/255.f;
float X = 0.412453 * r + 0.357580 * g + 0.180423 * b;
float Y = 0.212671 * r + 0.715160 * g + 0.072169 * b;
float Z = 0.019334 * r + 0.119193 * g + 0.950227 * b;
X /= 0.950456;
Z /= 1.088754;
float Y3 = pow(Y,1./3);
float fX = X>T ? pow(X,1./3) : 7.787 * X + 16/116.;
float fY = Y>T ? Y3 : 7.787 * Y + 16/116.;
float fZ = Z>T ? pow(Z,1./3) : 7.787 * Z + 16/116.;
float L = Y>T ? 116 * Y3 - 16.0 : 903.3 * Y;
float A = 500 * (fX - fY);
float B = 200 * (fY - fZ);
// correct L*a*b*: dark area or light area have less reliable colors
float correct_lab = exp(-color_attenuation*pow2(pow2(L/100) - 0.6));
out[i] = L;
out[i + size] = A*correct_lab;
out[i + 2*size] = B*correct_lab;
}
}
//////////////////////////////////////
/////Initialize bilteral filter///////
/////////////////////////////////////
static float weight_dist(int x1, int x2, //center of patch
int chi1, int chi2 //pixel in patch
){
float sigma = SIGMA_BILATERAL_DIST;
float result = exp(-0.5*(pow(x1 - chi1, 2.0) + pow(x2 - chi2, 2.0))/pow(sigma, 2.0));
return result;
}
static float weight_color(float color_x,
float color_chi){
float sigma = SIGMA_BILATERAL_COLOR;
float result = exp(-0.5*pow(std::abs(color_x - color_chi)/sigma, 2.0));
return result;
}
BilateralFilterData* init_weights_bilateral(
float* i0,
int w,
int h){
BilateralFilterData* Filter_data = new BilateralFilterData[1];
Filter_data->weights_filtering = new Weights_Bilateral[w*h];
Filter_data->indexes_filtering.resize(w*h);
int wr_filter = PATCH_BILATERAL_FILTER;
for (int j = 0; j < h; j++){
for (int i = 0; i < w; i++){
//For each pixel in the image, compute neighbor of weights
const int ij = j*w + i;
auto neighbor = get_index_patch(wr_filter, w, h, i, j, 1 );
Filter_data->indexes_filtering[ij] = neighbor;
const int w_patch = neighbor.ei - neighbor.ii;
const int h_patch = neighbor.ej - neighbor.ij;
Filter_data->weights_filtering[ij].weight = new float[w_patch*h_patch];
for (int idx_j = 0; idx_j < h_patch; idx_j++){
for (int idx_i = 0; idx_i < w_patch; idx_i++){
int x = idx_i + neighbor.ii;
int y = idx_j + neighbor.ij;
int xy = y*w + x;
int idx_ij = idx_j*w_patch + idx_i;
float dist = weight_dist(i, j, x, y);
float color = weight_color(i0[ij], i0[xy]);
//Save the weight for each point in the neighborhood
Filter_data->weights_filtering[ij].weight[idx_ij] = color*dist;
}
}
}
}
return Filter_data;
}
//Initialization of Optical Flow data for global method
OpticalFlowData init_Optical_Flow_Data(
const Parameters& params
) {
int w = params.w;
int h = params.h;
OpticalFlowData of;
of.u1 = new float[w*h*2];
of.u2 = of.u1 + w*h;
of.u1_ba = new float[w*h*2];
of.u2_ba = of.u1_ba + w*h;
of.chi = new float[w*h];
of.params = params;
return of;
}
//Initialization of Optical Flow data for local method
OpticalFlowData init_Optical_Flow_Data(
float *saliency,
const Parameters& params
) {
int w = params.w;
int h = params.h;
OpticalFlowData of;
of.u1 = new float[w*h*2];
of.u2 = of.u1 + w*h;
of.u1_ba = new float[w*h*2];
of.u2_ba = of.u1_ba + w*h;
of.u1_filter = new float[w*h*2];
of.u2_filter = of.u1_filter + w*h;
of.chi = new float[w*h];
of.fixed_points = new int[w*h];
of.trust_points = new int[w*h];
of.saliency = saliency;
of.params = params;
return of;
}
void initialize_auxiliar_stuff(
SpecificOFStuff& ofStuff,
OpticalFlowData& ofCore){
switch(ofCore.params.val_method){
case M_NLTVL1: //NLTV-L1
intialize_stuff_nltvl1(&ofStuff, &ofCore);
break;
case M_TVCSAD: //TV-CSAD
intialize_stuff_tvcsad(&ofStuff, &ofCore);
break;
case M_NLTVCSAD: //NLTV-CSAD
intialize_stuff_nltvcsad(&ofStuff, &ofCore);
break;
case M_TVL1_W: //TV-l2 coupled con pesos
intialize_stuff_tvl2coupled_w(&ofStuff, &ofCore);
break;
case M_NLTVCSAD_W: //NLTV-CSAD con pesos
intialize_stuff_nltvcsad_w(&ofStuff, &ofCore);
break;
case M_NLTVL1_W: //NLTV-L1 con pessos
intialize_stuff_nltvl1_w(&ofStuff, &ofCore);
break;
case M_TVCSAD_W: //TV-CSAD con pesos
intialize_stuff_tvcsad_w(&ofStuff, &ofCore);
break;
case M_TVL1_OCC: //TV-l2 with occlusion
intialize_stuff_tvl2coupled_occ(ofStuff, ofCore);
break;
default: //TV-l2 coupled
intialize_stuff_tvl2coupled(&ofStuff, &ofCore);
}
}
void free_auxiliar_stuff(SpecificOFStuff *ofStuff, OpticalFlowData *ofCore){
const int method = ofCore->params.val_method;
switch(method){
case M_NLTVL1: //NLTVL1
free_stuff_nltvl1(ofStuff);
break;
case M_TVCSAD: //TV-CSAD
free_stuff_tvcsad(ofStuff);
break;
case M_NLTVCSAD: //NLTV-CSAD
free_stuff_nltvcsad(ofStuff);
break;
case M_TVL1_W: //TV-l2 con pesos
free_stuff_tvl2coupled_w(ofStuff);
break;
case M_NLTVCSAD_W: //NLTV-CSAD con pesos
free_stuff_nltvcsad_w(ofStuff);
break;
case M_NLTVL1_W: //NLTV-L1 con pesos
free_stuff_nltvl1_w(ofStuff);
break;
case M_TVCSAD_W: //TV-CSAD con pesos
free_stuff_tvcsad_w(ofStuff);
break;
case M_TVL1_OCC: //TV-l2 with occlusion
free_stuff_tvl2coupled_occ(ofStuff);
break;
default: //TV-l2 coupled
free_stuff_tvl2coupled(ofStuff);
}
}
void prepare_stuff(
SpecificOFStuff *ofStuff1,
OpticalFlowData *ofCore1,
SpecificOFStuff *ofStuff2,
OpticalFlowData *ofCore2,
const float *i0,
const float *i1,
const float *i_1,
const float *i2,
const int pd,
float **out_i0,
float **out_i1,
float **out_i_1,
float **out_i2
) {
const int method = ofCore1->params.val_method;
const int w = ofCore1->params.w;
const int h = ofCore1->params.h;
switch(method){
case M_NLTVL1: //NLTV-L1
{
float *a_tmp = new float[w*h];
float *b_tmp = new float[w*h];
float *alb = new float[w*h*pd];
float *blb = new float[w*h*pd];
const int n_d = NL_DUAL_VAR;
const int radius = NL_BETA;
rgb_to_lab(i0, w*h, alb);
rgb_to_lab(i1, w*h, blb);
// std::printf("W:%d x H:%d\n Neir:%d, radius:%d\n",w,h,n_d,radius);
nltv_ini_dual_variables(alb, pd, w, h, n_d, radius,
ofStuff1->nltvl1.p, ofStuff1->nltvl1.q);
nltv_ini_dual_variables(blb, pd, w, h, n_d, radius,
ofStuff2->nltvl1.p, ofStuff2->nltvl1.q);
if (pd != 1){
rgb_to_gray(i0, w, h, a_tmp);
rgb_to_gray(i1, w, h, b_tmp);
}else{
memcpy(a_tmp, i0, w*h*sizeof(float));
memcpy(b_tmp, i1, w*h*sizeof(float));
}
// normalize the images between 0 and 255
image_normalization(a_tmp, b_tmp, a_tmp, b_tmp, w*h);
gaussian(a_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(b_tmp, w, h, PRESMOOTHING_SIGMA);
centered_gradient(b_tmp, ofStuff1->nltvl1.I1x, ofStuff1->nltvl1.I1y,
w, h);
centered_gradient(a_tmp, ofStuff2->nltvl1.I1x, ofStuff2->nltvl1.I1y,
w, h);
*out_i0 = a_tmp;
*out_i1 = b_tmp;
delete [] alb;
delete [] blb;
}
break;
case M_TVCSAD: //TVCSAD
{
float *a_tmp = new float[w*h];
float *b_tmp = new float[w*h];
const int rdt = DT_R;
const int ndt = DT_NEI;
std::printf("1 - Inicializado CSAD\n");
csad_ini_pos_nei(w, h, ndt, rdt, ofStuff1->tvcsad.pnei);
std::printf("2 - Inicializado CSAD\n");
csad_ini_pos_nei(w, h, ndt, rdt, ofStuff2->tvcsad.pnei);
if (pd != 1)
{
// std::printf("Numero canales:%d\n",pd);
rgb_to_gray(i0, w, h, a_tmp);
rgb_to_gray(i1, w, h, b_tmp);
}
else
{
memcpy(a_tmp, i0, w*h*sizeof(float));
memcpy(b_tmp, i1, w*h*sizeof(float));
}
// normalize the images between 0 and 255
image_normalization(a_tmp, b_tmp, a_tmp, b_tmp, w*h);
gaussian(a_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(b_tmp, w, h, PRESMOOTHING_SIGMA);
centered_gradient(b_tmp, ofStuff1->tvcsad.I1x, ofStuff1->tvcsad.I1y,
w, h);
centered_gradient(a_tmp, ofStuff2->tvcsad.I1x, ofStuff2->tvcsad.I1y,
w, h);
*out_i0 = a_tmp;
*out_i1 = b_tmp;
std::printf("Salimos de CSAD\n");
}
break;
case M_NLTVCSAD: //NLTV-CSAD
{
float *a_tmp = new float[w*h];
float *b_tmp = new float[w*h];
float *alb = new float[w*h*pd];
float *blb = new float[w*h*pd];
int n_d = NL_DUAL_VAR;
int radius = NL_BETA;
int rdt = DT_R;
int ndt = DT_NEI;
std::printf("Preparando CSAD\n");
csad_ini_pos_nei(w, h, ndt, rdt, ofStuff1->nltvcsad.pnei);
csad_ini_pos_nei(w, h, ndt, rdt, ofStuff2->nltvcsad.pnei);
rgb_to_lab(i0, w*h, alb);
rgb_to_lab(i1, w*h, blb);
// std::printf("W:%d x H:%d\n Neir:%d, radius:%d\n",w,h,n_d,radius);
nltv_ini_dual_variables(alb, pd, w, h, n_d, radius,
ofStuff1->nltvcsad.p, ofStuff1->nltvcsad.q);
nltv_ini_dual_variables(blb, pd, w, h, n_d, radius,
ofStuff2->nltvcsad.p, ofStuff2->nltvcsad.q);
std::printf("Preparado NLTV\n");
if (pd!=1)
{
rgb_to_gray(i0, w, h, a_tmp);
rgb_to_gray(i0, w, h, b_tmp);
}
else
{
memcpy(a_tmp, i0, w*h*sizeof(float));
memcpy(b_tmp, i1, w*h*sizeof(float));
}
// normalize the images between 0 and 255
image_normalization(a_tmp, b_tmp, a_tmp, b_tmp, w*h);
gaussian(a_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(b_tmp, w, h, PRESMOOTHING_SIGMA);
centered_gradient(b_tmp, ofStuff1->nltvcsad.I1x, ofStuff1->nltvcsad.I1y,
w, h);
centered_gradient(a_tmp, ofStuff2->nltvcsad.I1x, ofStuff2->nltvcsad.I1y,
w, h);
*out_i0 = a_tmp;
*out_i1 = b_tmp;
delete [] alb;
delete [] blb;
std::printf("Salimos NLTV_CSAD\n");
}
break;
case M_TVL1_W://TV-l2 coupled con pesos
{
float *weight1 = ofStuff1->tvl2w.weight;
float *weight2 = ofStuff2->tvl2w.weight;
gaussian1Dweight(weight1, ofCore1->params.w_radio);
gaussian1Dweight(weight2, ofCore2->params.w_radio);
std::printf("Pesos\n");
float *a_tmp = new float[w*h];
float *b_tmp = new float[w*h];
if (pd!=1)
{
// std::printf("Numero canales:%d\n",pd);
rgb_to_gray(i0, w, h, a_tmp);
rgb_to_gray(i1, w, h, b_tmp);
}
else
{
memcpy(a_tmp, i0, w*h*sizeof(float));
memcpy(b_tmp, i1, w*h*sizeof(float));
}
// normalize the images between 0 and 255
image_normalization(a_tmp, b_tmp, a_tmp, b_tmp, w*h);
gaussian(a_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(b_tmp, w, h, PRESMOOTHING_SIGMA);
centered_gradient(b_tmp, ofStuff1->tvl2w.I1x, ofStuff1->tvl2w.I1y,
w, h);
centered_gradient(a_tmp, ofStuff2->tvl2w.I1x, ofStuff2->tvl2w.I1y,
w, h);
*out_i0 = a_tmp;
*out_i1 = b_tmp;
}
break;
case M_NLTVCSAD_W: //NLTV-CSAD con pesos
{
float *weight1 = ofStuff1->nltvcsadw.weight;
float *weight2 = ofStuff2->nltvcsadw.weight;
gaussian1Dweight(weight1, ofCore1->params.w_radio);
gaussian1Dweight(weight2, ofCore2->params.w_radio);
float *a_tmp = new float[w*h];
float *b_tmp = new float[w*h];
float *alb = new float[w*h*pd];
float *blb = new float[w*h*pd];
int n_d = NL_DUAL_VAR;
int radius = NL_BETA;
int rdt = DT_R;
int ndt = DT_NEI;
std::printf("Preparado CSAD\n");
csad_ini_pos_nei(w, h, ndt, rdt, ofStuff1->nltvcsadw.pnei);
csad_ini_pos_nei(w, h, ndt, rdt, ofStuff2->nltvcsadw.pnei);
rgb_to_lab(i0, w*h, alb);
rgb_to_lab(i1, w*h, blb);
// std::printf("W:%d x H:%d\n Neir:%d, radius:%d\n",w,h,n_d,radius);
nltv_ini_dual_variables(alb, pd, w, h, n_d, radius,
ofStuff1->nltvcsadw.p, ofStuff1->nltvcsadw.q);
nltv_ini_dual_variables(blb, pd, w, h, n_d, radius,
ofStuff2->nltvcsadw.p, ofStuff2->nltvcsadw.q);
std::printf("Preparado NLTV\n");
if (pd!=1)
{
rgb_to_gray(i0, w, h, a_tmp);
rgb_to_gray(i1, w, h, b_tmp);
}
else
{
memcpy(a_tmp, i0, w*h*sizeof(float));
memcpy(b_tmp, i1, w*h*sizeof(float));
}
// normalize the images between 0 and 255
image_normalization(a_tmp, b_tmp, a_tmp, b_tmp, w*h);
gaussian(a_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(b_tmp, w, h, PRESMOOTHING_SIGMA);
centered_gradient(b_tmp, ofStuff1->nltvcsadw.I1x, ofStuff1->nltvcsadw.I1y,
w, h);
centered_gradient(a_tmp, ofStuff2->nltvcsadw.I1x, ofStuff2->nltvcsadw.I1y,
w, h);
*out_i0 = a_tmp;
*out_i1 = b_tmp;
delete [] alb;
delete [] blb;
std::printf("Salimos NLTV_CSAD con pesos\n");
}
break;
case M_NLTVL1_W: //NLTV-L1 con pesos
{
float *weight1 = ofStuff1->nltvl1w.weight;
float *weight2 = ofStuff2->nltvl1w.weight;
gaussian1Dweight(weight1, ofCore1->params.w_radio);
gaussian1Dweight(weight2, ofCore2->params.w_radio);
float *a_tmp = new float[w*h];
float *b_tmp = new float[w*h];
float *alb = new float[w*h*pd];
float *blb = new float[w*h*pd];
int n_d = NL_DUAL_VAR;
int radius = NL_BETA;
rgb_to_lab(i0, w*h, alb);
rgb_to_lab(i1, w*h, blb);
// std::printf("W:%d x H:%d\n Neir:%d, radius:%d\n",w,h,n_d,radius);
nltv_ini_dual_variables(alb, pd, w, h, n_d, radius,
ofStuff1->nltvl1w.p, ofStuff1->nltvl1w.q);
nltv_ini_dual_variables(blb, pd, w, h, n_d, radius,
ofStuff2->nltvl1w.p, ofStuff2->nltvl1w.q);
if (pd!=1)
{
rgb_to_gray(i0, w, h, a_tmp);
rgb_to_gray(i1, w, h, b_tmp);
}
else
{
memcpy(a_tmp, i0, w*h*sizeof(float));
memcpy(b_tmp, i1, w*h*sizeof(float));
}
// normalize the images between 0 and 255
image_normalization(a_tmp, b_tmp, a_tmp, b_tmp, w*h);
gaussian(a_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(b_tmp, w, h, PRESMOOTHING_SIGMA);
centered_gradient(b_tmp, ofStuff1->nltvl1w.I1x, ofStuff1->nltvl1w.I1y,
w, h);
centered_gradient(a_tmp, ofStuff2->nltvl1w.I1x, ofStuff2->nltvl1w.I1y,
w, h);
*out_i0 = a_tmp;
*out_i1 = b_tmp;
delete [] alb;
delete [] blb;
}
break;
case M_TVCSAD_W: //TVCSAD con pesos
{
float *weight1 = ofStuff1->tvcsadw.weight;
float *weight2 = ofStuff2->tvcsadw.weight;
gaussian1Dweight(weight1, ofCore1->params.w_radio);
gaussian1Dweight(weight2, ofCore2->params.w_radio);
float *a_tmp = new float[w*h];
float *b_tmp = new float[w*h];
int rdt = DT_R;
int ndt = DT_NEI;
std::printf("1 - Inicializado CSAD\n");
csad_ini_pos_nei(w, h, ndt, rdt, ofStuff1->tvcsadw.pnei);
std::printf("2 - Inicializado CSAD\n");
csad_ini_pos_nei(w, h, ndt, rdt, ofStuff2->tvcsadw.pnei);
if (pd != 1) {
// std::printf("Numero canales:%d\n",pd);
rgb_to_gray(i0, w, h, a_tmp);
rgb_to_gray(i1, w, h, b_tmp);
}
else
{
memcpy(a_tmp, i0, w*h*sizeof(float));
memcpy(b_tmp, i1, w*h*sizeof(float));
}
// normalize the images between 0 and 255
image_normalization(a_tmp, b_tmp, a_tmp, b_tmp, w*h);
gaussian(a_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(b_tmp, w, h, PRESMOOTHING_SIGMA);
centered_gradient(b_tmp, ofStuff1->tvcsadw.I1x, ofStuff1->tvcsadw.I1y,
w, h);
centered_gradient(a_tmp, ofStuff2->tvcsadw.I1x, ofStuff2->tvcsadw.I1y,
w, h);
*out_i0 = a_tmp;
*out_i1 = b_tmp;
std::printf("Salimos de CSAD\n");
}
break;
case M_TVL1_OCC:
{
float *i1_tmp = new float[w*h];
float *i2_tmp = new float[w*h];
float *i0_tmp = new float[w*h];
float *i_1_tmp = new float[w*h];
//Check if image is gray, otherwise transform
if (pd != 1){
rgb_to_gray(i0, w, h, i0_tmp);
rgb_to_gray(i1, w, h, i1_tmp);
rgb_to_gray(i_1, w, h, i_1_tmp);
rgb_to_gray(i2, w, h, i2_tmp);
}else{
memcpy(i0_tmp, i0, w*h*sizeof(float));
memcpy(i1_tmp, i1, w*h*sizeof(float));
memcpy(i_1_tmp, i_1, w*h*sizeof(float));
memcpy(i2_tmp, i2, w*h*sizeof(float));
}
// Normalize the images between 0 and 255
image_normalization_4(i0_tmp, i1_tmp, i_1_tmp, i2_tmp, i0_tmp, i1_tmp, i_1_tmp, i2_tmp, w*h);
//Make a little smoth of images
gaussian(i1_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(i2_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(i0_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(i_1_tmp, w, h, PRESMOOTHING_SIGMA);
//TODO: change the computation of derivatives
centered_gradient(i1_tmp, ofStuff1->tvl2_occ.I1x, ofStuff1->tvl2_occ.I1y, w, h);
centered_gradient(i_1_tmp, ofStuff1->tvl2_occ.I_1x, ofStuff1->tvl2_occ.I_1y, w, h);
centered_gradient(i0_tmp, ofStuff2->tvl2_occ.I1x, ofStuff2->tvl2_occ.I1y, w, h);
centered_gradient(i2_tmp, ofStuff2->tvl2_occ.I_1x, ofStuff2->tvl2_occ.I_1y, w, h);
// Initialize g (weight)
// The derivatives are taken from previous computation. Forward: I0, backward: I1
init_weight(ofStuff1->tvl2_occ.g, ofStuff2->tvl2_occ.I1x, ofStuff2->tvl2_occ.I1y, w*h);
init_weight(ofStuff2->tvl2_occ.g, ofStuff1->tvl2_occ.I1x, ofStuff1->tvl2_occ.I1y, w*h);
//The following variables contain a gray and smooth version
//of the corresponding image
*out_i1 = i1_tmp;
*out_i2 = i2_tmp;
*out_i0 = i0_tmp;
*out_i_1 = i_1_tmp;
}
break;
default: //TV-l2 coupled
{
float *a_tmp = new float[w*h];
float *b_tmp = new float[w*h];
//Check if image is gray, otherwise transform
if (pd != 1){
// std::printf("Numero canales:%d\n",pd);
rgb_to_gray(i0, w, h, a_tmp);
rgb_to_gray(i1, w, h, b_tmp);
}else{
memcpy(a_tmp, i0, w*h*sizeof(float));
memcpy(b_tmp, i1, w*h*sizeof(float));
}
// Normalize the images between 0 and 255
image_normalization(a_tmp, b_tmp, a_tmp, b_tmp, w*h);
gaussian(a_tmp, w, h, PRESMOOTHING_SIGMA);
gaussian(b_tmp, w, h, PRESMOOTHING_SIGMA);
centered_gradient(b_tmp, ofStuff1->tvl2.I1x, ofStuff1->tvl2.I1y,
w, h);
centered_gradient(a_tmp, ofStuff2->tvl2.I1x, ofStuff2->tvl2.I1y,
w, h);
*out_i0 = a_tmp;
*out_i1 = b_tmp;
}
}
}
void of_estimation(
SpecificOFStuff *ofStuff,
OpticalFlowData *ofCore,
float *ener_N,
const float *i0, //first frame
const float *i1, //second frame
const float *i_1,
const PatchIndexes index // end row
) {
//TODO: Each method should have its own set of parameters
float lambda = PAR_DEFAULT_LAMBDA;
float theta = PAR_DEFAULT_THETA;
float tau = PAR_DEFAULT_TAU;
float tol_OF = PAR_DEFAULT_TOL_D;
int verbose = PAR_DEFAULT_VERBOSE;
int warps = PAR_DEFAULT_NWARPS_LOCAL;
switch(ofCore->params.val_method) {
case M_NLTVL1: //NLTV-L1
{
lambda = 2;
theta = 0.3;
tau = 0.1;
//estimate_tvl1
guided_nltvl1(i0, i1, ofCore, &(ofStuff->nltvl1), ener_N, index,
lambda, theta, tau, tol_OF, warps, verbose);
}
break;
case M_TVCSAD: //TVCSAD
{
lambda = 0.85; //80/(49-2)
theta = 0.3;
tau = 0.1;
//estimate_tvl1
guided_tvcsad(i0, i1, ofCore, &(ofStuff->tvcsad), ener_N, index.ii, index.ij, index.ei, index.ej,
lambda, theta, tau, tol_OF, warps, verbose);
}
break;
case M_NLTVCSAD: //NLTV-CSAD
{
lambda = 0.85; //80/(49-2)
theta = 0.3;
tau = 0.1;
//estimate_tvl1
guided_nltvcsad(i0, i1, ofCore, &(ofStuff->nltvcsad), ener_N, index.ii, index.ij, index.ei, index.ej,
lambda, theta, tau, tol_OF, warps, verbose);
}
break;
case M_TVL1_W: //TV-l2 coupled con pesos
{
const float central = ofStuff->tvl2w.weight[ofCore->params.w_radio + 1];
lambda = lambda /(central*central);
guided_tvl2coupled_w(i0, i1, ofCore, &(ofStuff->tvl2w), ener_N, index.ii, index.ij, index.ei, index.ej,
lambda, theta, tau, tol_OF, warps, verbose);
}
break;
case M_NLTVCSAD_W: //NLTV-CSAD con pesos
{
lambda = 0.85; //80/(49-2)
const float central = ofStuff->nltvcsadw.weight[ofCore->params.w_radio + 1];
lambda = lambda /(central*central);
theta = 0.3;
tau = 0.1;
//estimate_tvl1
guided_nltvcsad_w(i0, i1, ofCore, &(ofStuff->nltvcsadw), ener_N, index.ii, index.ij, index.ei, index.ej,
lambda, theta, tau, tol_OF, warps, verbose);
}
break;
case M_NLTVL1_W: //NLTV-L1 cons pesos
{
lambda = 2;
lambda = 0.85; //80/(49-2)
const float central = ofStuff->nltvl1w.weight[ofCore->params.w_radio + 1];
lambda = lambda /(central*central);
theta = 0.3;
tau = 0.1;
//estimate_tvl1
guided_nltvl1_w(i0, i1, ofCore, &(ofStuff->nltvl1w), ener_N, index.ii, index.ij, index.ei, index.ej,
lambda, theta, tau, tol_OF, warps, verbose);
}
break;
case M_TVCSAD_W: //TVCSAD con pesos
{
lambda = 0.85; //80/(49-2)
const float central = ofStuff->tvcsadw.weight[ofCore->params.w_radio + 1];
lambda = lambda /(central*central);
theta = 0.3;
tau = 0.1;
//estimate_tvl1
guided_tvcsad_w(i0, i1, ofCore, &(ofStuff->tvcsadw), ener_N, index.ii, index.ij, index.ei, index.ej,
lambda, theta, tau, tol_OF, warps, verbose);
}
break;
case M_TVL1_OCC:
{
//estimate_tvl2 with occlusions
guided_tvl2coupled_occ(i0, i1, i_1, ofCore, &(ofStuff->tvl2_occ), ener_N, index);
}
break;
default: //TV-l2 coupled
//estimate_tvl2
guided_tvl2coupled(i0, i1, ofCore, &(ofStuff->tvl2), ener_N, index.ii, index.ij, index.ei, index.ej,
lambda, theta, tau, tol_OF, warps, verbose);
}
}
#endif //ENERGY_MODEL
|
//
// This file contains the C++ code from Program 7.21 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm07_21.cpp
//
#ifndef SORTLISTASARRAY_H_
#define SORTLISTASARRAY_H_
#include <Object.h>
#include <ListAsArray.h>
#include <SortedList.h>
class SortedListAsArray :
public virtual SortedList, public virtual ListAsArray
{
unsigned int FindOffset (Object const&) const;
public:
SortedListAsArray (unsigned int n) :ListAsArray( (unsigned int )n)
{ }
void Insert (Object& object);
Object& Find (Object const& object) const;
Position& FindPosition (Object const& object) const;
void Withdraw (Object& object);
};
#endif /*SORTLISTASARRAY_H_*/
|
// Created on: 2001-07-25
// Created by: Julia DOROVSKIKH
// Copyright (c) 2001-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _XmlDrivers_DocumentRetrievalDriver_HeaderFile
#define _XmlDrivers_DocumentRetrievalDriver_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <XmlLDrivers_DocumentRetrievalDriver.hxx>
#include <XmlObjMgt_Element.hxx>
#include <Standard_Integer.hxx>
class XmlMDF_ADriverTable;
class Message_Messenger;
class XmlMDF_ADriver;
class XmlDrivers_DocumentRetrievalDriver;
DEFINE_STANDARD_HANDLE(XmlDrivers_DocumentRetrievalDriver, XmlLDrivers_DocumentRetrievalDriver)
class XmlDrivers_DocumentRetrievalDriver : public XmlLDrivers_DocumentRetrievalDriver
{
public:
Standard_EXPORT XmlDrivers_DocumentRetrievalDriver();
Standard_EXPORT virtual Handle(XmlMDF_ADriverTable) AttributeDrivers
(const Handle(Message_Messenger)& theMsgDriver) Standard_OVERRIDE;
Standard_EXPORT virtual Handle(XmlMDF_ADriver) ReadShapeSection
(const XmlObjMgt_Element& thePDoc,
const Handle(Message_Messenger)& theMsgDriver,
const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE;
Standard_EXPORT virtual void ShapeSetCleaning
(const Handle(XmlMDF_ADriver)& theDriver) Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(XmlDrivers_DocumentRetrievalDriver,XmlLDrivers_DocumentRetrievalDriver)
};
#endif // _XmlDrivers_DocumentRetrievalDriver_HeaderFile
|
// Created on: 1996-01-05
// Created by: Jean Yves LEBEY
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepBuild_CompositeClassifier_HeaderFile
#define _TopOpeBRepBuild_CompositeClassifier_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Address.hxx>
#include <TopOpeBRepBuild_LoopClassifier.hxx>
#include <TopAbs_State.hxx>
class TopOpeBRepBuild_BlockBuilder;
class TopOpeBRepBuild_Loop;
class TopoDS_Shape;
//! classify composite Loops, i.e, loops that can be either a Shape, or
//! a block of Elements.
class TopOpeBRepBuild_CompositeClassifier : public TopOpeBRepBuild_LoopClassifier
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT virtual TopAbs_State Compare (const Handle(TopOpeBRepBuild_Loop)& L1, const Handle(TopOpeBRepBuild_Loop)& L2) Standard_OVERRIDE;
//! classify shape <B1> with shape <B2>
Standard_EXPORT virtual TopAbs_State CompareShapes (const TopoDS_Shape& B1, const TopoDS_Shape& B2) = 0;
//! classify element <E> with shape <B>
Standard_EXPORT virtual TopAbs_State CompareElementToShape (const TopoDS_Shape& E, const TopoDS_Shape& B) = 0;
//! prepare classification involving shape <B>
//! calls ResetElement on first element of <B>
Standard_EXPORT virtual void ResetShape (const TopoDS_Shape& B) = 0;
//! prepare classification involving element <E>.
Standard_EXPORT virtual void ResetElement (const TopoDS_Shape& E) = 0;
//! Add element <E> in the set of elements used in classification.
//! Returns FALSE if the element <E> has been already added to the set of elements,
//! otherwise returns TRUE.
Standard_EXPORT virtual Standard_Boolean CompareElement (const TopoDS_Shape& E) = 0;
//! Returns state of classification of 2D point, defined by
//! ResetElement, with the current set of elements, defined by Compare.
Standard_EXPORT virtual TopAbs_State State() = 0;
protected:
Standard_EXPORT TopOpeBRepBuild_CompositeClassifier(const TopOpeBRepBuild_BlockBuilder& BB);
Standard_Address myBlockBuilder;
private:
};
#endif // _TopOpeBRepBuild_CompositeClassifier_HeaderFile
|
int rob(vector<int>& nums) {
if(nums.empty())
return 0;
int k0 = 0;
int k1 = nums[0];
int k = k1;
for(int i=1; i<nums.size(); i++) {
k = max(k0+nums[i], k1);
k0 = k1;
k1 = k;
}
return k;
}
|
//check out my youtube channel :https://www.youtube.com/channel/UC92gG4BBWAYu4vw_OgsgSLA?view_as=subscriber
#include<LiquidCrystal.h>
#include<Servo.h>
#define button1 22
#define button2 23
#define button3 24
#define button4 25
#define button5 26
#define button6 27
#define button7 28
Servo servo1;
Servo servo2;
Servo servo3;
LiquidCrystal lcd(14,15,16,17,18,19);
int pos1 = 93; // for motor 1
int posl1=pos1;
int pos2 = 93; // for motor 2
int posl2=pos2;
int pos3 = 93; // for motor 3
int posl3=pos3;
void intro() //// this is a silly intro you can delete if you want
{
lcd.setCursor(0,0);
lcd.print("Rookie_developer");
lcd.setCursor(0,1);
lcd.print("presents");
delay(1000);
lcd.clear();delay(500);
lcd.setCursor(3,0);lcd.print("**robotic ARM**");delay(1000);
lcd.clear();delay(500);
}
void action1() /// this is to control servo 1
{
servo1.write(pos1);
lcd.setCursor(13,0);
lcd.print(posl1);
if(digitalRead(button2)==0)
{
pos1++;posl1=pos1;delayMicroseconds(2);
}else if(digitalRead(button3)==0)
{
pos1--;posl1=pos1;delayMicroseconds(2);
}
if(posl1<43){posl1=43;}
else if(posl1<10){lcd.setCursor(14,0);lcd.print(" ");}
else if(posl1<100){lcd.setCursor(15,0);lcd.print(" ");}
else if(posl1>143){posl1=143;}
}
void action2() /// this is to control servo 2
{
servo2.write(pos2);
lcd.setCursor(13,1);
lcd.print(posl2);
if(digitalRead(button4)==0)
{
pos2++;posl2=pos2;delay(2);
}else if(digitalRead(button5)==0)
{
pos2--;posl2=pos2;delay(2);
}
if(posl2<43){posl2=43;}
else if(posl2<10){lcd.setCursor(14,1);lcd.print(" ");}
else if(posl2<100){lcd.setCursor(15,1);lcd.print(" ");}
else if(posl2>143){posl2=143;}
}
void action3() /// this is to control servo 3
{
servo3.write(pos3);
lcd.setCursor(13,2);
lcd.print(posl3);
if(digitalRead(button6)==0)
{
pos3++;posl3=pos3;delay(2);
}else if(digitalRead(button7)==0)
{
pos3--;posl3=pos3;delay(2);
}
if(posl3<43){posl3=43;}
else if(posl3<10){lcd.setCursor(14,2);lcd.print(" ");}
else if(posl3<100){lcd.setCursor(15,2);lcd.print(" ");}
else if(posl3>143){posl3=143;}
}
///////////////////////////////////////here is the setup and loop ////////////////////////////////////////////////////////
void setup()
{
servo1.attach(3);
servo2.attach(4);
servo3.attach(5);
lcd.begin(20,4);
for(int i=22;i<30;i++)
{
pinMode(i,INPUT);
}
intro();cli();
}
void loop()
{
lcd.setCursor(0,0);
lcd.print("press START");
lcd.setCursor(0,1);lcd.print("to start controle");
if(digitalRead(button1)==0)
{
sei();
lcd.clear();delay(200);lcd.setCursor(0,0);
lcd.print("initialising");delay(500);
lcd.clear();delay(200);
while(1)
{
lcd.setCursor(0,0);
lcd.print("servo num1 :");
lcd.setCursor(0,1);
lcd.print("servo num2 :");
lcd.setCursor(0,2);
lcd.print("servo num3 :");
lcd.setCursor(0,3);
lcd.print("START to go back");
action1();
action2();
action3();
if(digitalRead(button1)==0)
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("controle interrupted");delay(1000);
break;
}
}
cli();lcd.clear();delay(500);
}
}
|
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <random>
#include <ctime>
#include <numeric>
using namespace std;
using Point = pair<float, float>;
using Paramater = Point; // (k, b)
using Module = vector<Point>;
double gaussrand()
{
static double V1, V2, S;
static int phase = 0;
double X;
if ( phase == 0 ) {
do {
double U1 = (double)rand() / RAND_MAX;
double U2 = (double)rand() / RAND_MAX;
V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S >= 1 || S == 0);
X = V1 * sqrt(-2 * log(S) / S);
} else
X = V2 * sqrt(-2 * log(S) / S);
phase = 1 - phase;
return X;
}
Module create_module(size_t size, float k, float b, float x_min, float x_max, float var)
{
Module m(size);
float x, y;
for(auto iter = m.begin(); iter != m.end(); iter++)
{
x = rand()/(float)RAND_MAX*(x_max - x_min) + x_min;
y = k*x + b + gaussrand()*var;
*iter = Point(x, y);
}
return m;
}
ostream &operator <<(ostream &out, const Point &p)
{
out << "(" << p.first << ", " << p.second << ")";
return out;
}
double distance(float k, float b, const Point &p)
{
double num = fabs(k*p.first - p.second + b);
double den = sqrt(k*k + 1);
return num/den;
}
double get_fittness(const Module &m, size_t index_1, size_t index_2)
{
double fit = 0;
Point p1 = m[index_1];
Point p2 = m[index_2];
float k = (p2.second - p1.second)/(p2.first - p1.first);
float b = p1.second - k*p1.first;
for(size_t i = 0; i < m.size(); i++)
{
fit += distance(k, b, m[i]);
}
return fit;
}
Paramater get_parameter_of_line(const Point &p1, const Point &p2)
{
float k = (p2.second - p1.second)/(p2.first - p1.first);
float b = p1.second - k*p1.first;
return Paramater(k, b);
}
Paramater ransac(const Module &m)
{
constexpr int RepeatTimes = 1000;
size_t size = m.size();
Paramater p;
double fittness = numeric_limits<double>::max(); // the lower the better
for (int i = 0; i < RepeatTimes; i++)
{
// random choose two different points
int index_1, index_2;
index_1 = rand()%size;
index_2 = rand()%size;
if(index_1 == index_2)
{
i--; // this time does not account
continue;
}
float new_fittness = get_fittness(m, index_1, index_2);
if(fittness > new_fittness)
{
fittness = new_fittness;
p = get_parameter_of_line(m[index_1], m[index_2]);
}
}
return p;
}
Paramater hough_transform(const Module &m)
{
// set up table
int table[200][200] = {0};
float x, y;
float k_f, b_f;
int b;
for(auto iter = m.begin(); iter != m.end(); iter++)
{
x = iter->first;
y = iter->second;
for(int k = 0; k < 200; k++)
{
k_f = k/10.0 - 10;
b_f = -x*k_f + y;
b = int((b_f + 10)*10 + 0.5); // round
if(b >= 0 && b <200)
{
table[b][k]++;
}
}
}
Paramater p(-10, -10);
int max_ele = table[0][0];
for(int i = 0; i < 200; i++)
{
for(int j = 0; j < 200; j++)
{
if(table[i][j] > max_ele)
{
max_ele = table[i][j];
p.second = i/10.0 - 10;
p.first = j/10.0 - 10;
}
}
}
return p;
}
int main()
{
for(int i = 0; i < 10; i++)
{
Module m = create_module(50000, 2, 1, 0, 10, 1);
// for(auto iter = m.begin(); iter != m.end(); iter++)
// {
// cout << *iter << endl;
// }
Paramater res = ransac(m);
cout << "ransac\t" << res << endl;
res = hough_transform(m);
cout << "hough\t" << res << endl;
}
return 0;
}
|
#include "parser_main.h"
#ifndef __PARSER_LINKS__
#define __PARSER_LINKS__
/**
* A class of functions for manipulating links within
* wikimarkup. Extends the base parser class.
*/
class link_parser : public parser{
private:
/**
* A string representing the identifying characters
* for a wikimarkup internal link. Used in combination with
* parser::regex_def to construct boost
* regular expressions around said characters.
*/
static const std::string link_delimiters;
public:
/**
* A function for extracting links from a piece of
* wikitext. Called by the (exported) extract_links
* function in mwutils.cpp
*
* @param text a piece of wikitext
*
* @return a vector of strings, each one consisting
* of one link from within the input text.
*/
std::vector < std::string > extract_links(std::string text);
/**
* A function for /removing/ links from a
* piece of wikitext. Can be used for sanitisation
* purposes, or just for fun.
*
* @param text a piece of wikitext
*
* @return a string consisting of the same
* piece of wikitext as the input, but without
* any included links.
*/
std::string remove_links(std::string text);
/**
* A function for extracting the actual human-visible
* text from links retrieved with extract_links.
* Called by the exported extract_link_text
* function in wmutils.cpp
*
* @param link_def a link.
*
* @return the human-readable text contained in
* link_def.
*/
std::string link_text(std::string link_def);
/**
* A function for extracting the target page
* from a link extracted with extract_links.
* Called by extract_link_target, which
* is exported and found in wmutils.cpp.
*
* @param link_def a link.
*
* @return a string consisting of the target
* of link_def
*/
std::string link_target(std::string link_def);
};
#endif
|
#pragma once
#include <iberbar/RHI/D3D11/Headers.h>
#include <iberbar/RHI/D3D11/ShaderReflection.h>
#include <iberbar/RHI/Shader.h>
namespace iberbar
{
namespace RHI
{
namespace D3D11
{
class CDevice;
//class CConstantBuffer;
class CUniformBuffer;
class CShader abstract
: public IShader
{
public:
CShader( CDevice* pDevice, EShaderType eShaderType );
virtual ~CShader();
public:
virtual CResult LoadFromFile( const char* pstrFile ) override;
virtual CResult LoadFromSource( const char* pstrSource ) override;
virtual IShaderReflection* GetReflection() override;
CResult CreateReflection( const void* pCodes, uint32 nCodeLen );
FORCEINLINE CShaderReflection* GetReflectionInternal() { return m_pReflection; }
//FORCEINLINE const std::vector<CConstantBuffer*>& GetConstantBuffers() { return m_ConstantBuffers; }
//FORCEINLINE const uint8* GetConstantBuffersMemory() const
//{
// if (m_ConstBuffersData.empty())
// return nullptr;
// return &(m_ConstBuffersData.front());
//}
protected:
CDevice* m_pDevice;
CShaderReflection* m_pReflection;
//std::vector<CConstantBuffer*> m_ConstantBuffers;
//std::vector<uint8> m_ConstBuffersData;
};
class CVertexShader
: public CShader
{
public:
CVertexShader( CDevice* pDevice );
virtual CResult Load( const void* pCodes, uint32 nCodeLen ) override;
FORCEINLINE ID3D11VertexShader* GetD3DShader() { return m_pD3DShader.Get(); }
FORCEINLINE const uint8* GetCodePointer() { return &m_Code.front(); }
FORCEINLINE uint32 GetCodeSize() { return m_Code.size(); }
protected:
ComPtr<ID3D11VertexShader> m_pD3DShader;
std::vector<uint8> m_Code;
};
class CPixelShader
: public CShader
{
public:
CPixelShader( CDevice* pDevice );
virtual CResult Load( const void* pCodes, uint32 nCodeLen ) override;
FORCEINLINE ID3D11PixelShader* GetD3DShader() { return m_pD3DShader.Get(); }
protected:
ComPtr<ID3D11PixelShader> m_pD3DShader;
};
class CGeometryShader
: public CShader
{
public:
CGeometryShader( CDevice* pDevice );
virtual CResult Load( const void* pCodes, uint32 nCodeLen ) override;
FORCEINLINE ID3D11GeometryShader* GetD3DShader() { return m_pD3DShader.Get(); }
protected:
ComPtr<ID3D11GeometryShader> m_pD3DShader;
};
class CHullShader
: public CShader
{
public:
CHullShader( CDevice* pDevice );
virtual CResult Load( const void* pCodes, uint32 nCodeLen ) override;
FORCEINLINE ID3D11HullShader* GetD3DShader() { return m_pD3DShader.Get(); }
protected:
ComPtr<ID3D11HullShader> m_pD3DShader;
};
class CDomainShader
: public CShader
{
public:
CDomainShader( CDevice* pDevice );
virtual CResult Load( const void* pCodes, uint32 nCodeLen ) override;
FORCEINLINE ID3D11DomainShader* GetD3DShader() { return m_pD3DShader.Get(); }
protected:
ComPtr<ID3D11DomainShader> m_pD3DShader;
};
class CComputeShader
: public CShader
{
public:
CComputeShader( CDevice* pDevice );
virtual CResult Load( const void* pCodes, uint32 nCodeLen ) override;
FORCEINLINE ID3D11ComputeShader* GetD3DShader() { return m_pD3DShader.Get(); }
protected:
ComPtr<ID3D11ComputeShader> m_pD3DShader;
};
class CShaderProgram
: public IShaderProgram
{
public:
CShaderProgram(
CDevice* pDevice,
IShader* pVS,
IShader* pPS,
IShader* pHS,
IShader* pGS,
IShader* pDS );
virtual ~CShaderProgram();
inline CVertexShader* GetVertexShader() { return (CVertexShader*)m_pShaders[ (int)EShaderType::VertexShader ]; }
inline CPixelShader* GetPixelShader() { return (CPixelShader*)m_pShaders[ (int)EShaderType::PixelShader ]; }
inline CGeometryShader* GetGeometryShader() { return (CGeometryShader*)m_pShaders[ (int)EShaderType::GeometryShader ]; }
inline CHullShader* GetHullShader() { return (CHullShader*)m_pShaders[ (int)EShaderType::HullShader ]; }
inline CDomainShader* GetDomainShader() { return (CDomainShader*)m_pShaders[ (int)EShaderType::DomainShader ]; }
void Initial();
protected:
CDevice* m_pDevice;
};
}
}
}
|
/**
* Unidad 5: MIDI
* Notas MIDI:
* http://www.midimountain.com/midi/midi_note_numbers.html
*/
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();
byte nota;
void setup() {
MIDI.begin(); // Podemos seleccionar el canal o usar 1 por defecto
Serial.begin(115200);
}
void loop() {
nota = random(60, 96);
MIDI.sendNoteOn(nota, 127, 1); // Envรญa una nota (pitch 42, velocity 127, canal 1)
delay(333);
MIDI.sendNoteOff(nota, 0, 1); // Para la nota
delay(333);
MIDI.sendNoteOn(nota - 12, 100, 1);
delay(333);
MIDI.sendNoteOff(nota - 12, 0, 1);
}
|
//
// Model.h
// Odin.MacOSX
//
// Created by Daniel on 15/10/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#ifndef __Odin_MacOSX__Model__
#define __Odin_MacOSX__Model__
#include "Drawable.h"
#include "Transform.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <vector>
#include "Material.h"
#include "Texture2D.h"
#include "AABB.h"
namespace odin
{
namespace resource
{
class Model :
public render::Drawable
{
public:
struct Mesh
{
std::string name;
UI32 indexCount;
UI32 indexOffset;
render::Material* material;
};
struct Node
{
std::string name;
render::Transform transformation;
std::vector<Node> childNodes;
std::vector<Mesh*> meshes;
};
Model();
~Model();
bool loadFromFile(const std::string& filename, bool resizeToUnitCube = false);
bool loadFromMemory(const void* data);
virtual void draw(const render::RenderStates& states);
private:
render::Material* processMaterials(aiMaterial* material);
Mesh processMesh(aiMesh* mesh);
void processNode(aiNode* node, Node& newNode);
void loadModel();
void drawNode(const resource::Shader* shaderProgram, const Node* node, math::mat4& objectMatrix);
void resizeToUnitCoords();
void findObjectDimensions(Node& node, math::mat4& transform, math::shape::AABB& bbox);
std::string m_directory;
std::vector<render::Material*> m_materials;
std::vector<Mesh> m_meshes;
Node m_rootNode;
UI32 m_vao;
UI32 m_vbo[5];
UI32 m_ebo;
std::vector<F32> m_vertices;
std::vector<F32> m_normals;
std::vector<F32> m_texcoords;
std::vector<F32> m_tangents;
std::vector<F32> m_bitangents;
std::vector<UI32> m_indices;
static bool s_loaded;
};
}
}
#endif /* defined(__Odin_MacOSX__Model__) */
|
/*
Name: ๅญ็ฌฆ่ฟท้ต
Copyright:
Author: Hill bamboo
Date: 2019/8/17 9:41:48
Description: ็ฝๆ
็นไพ
aaaaa ๆฅๆพ a ่ฟ็ฎๅ ไธช ๏ผ 16ไธช๏ผ่ฟๆฏ5ไธช๏ผ
ๆ้ขๆๅบ่ฏฅๆฏ16ไธช๏ผไธ้ข็ไปฃ็ ไนๆฏ่พๅบ16ไธช็
ๆป็ป๏ผ
ๆฃๅฎ่พน็ๅๅๅ้ๅๅฎ๏ผๅจ่่ฏไธญ่ฟๆฏๅคชๆ
ขไบ
*/
#include <bits/stdc++.h>
using namespace std;
vector<string> maze;
string str, t;
int m, n;
bool inside(int x, int y) {
return 0 <= x && x < m && 0 <= y && y < n;
}
bool dfs(int i, int j, int d) {
int s = 0;
while (s < t.size() && inside(i, j) && t[s] == maze[i][j]) {
++s;
if (d == 0) ++j;
else if (d == 1) ++i;
else {
++i; ++j;
}
}
return s == t.size();
}
int main() {
int tt;
scanf("%d", &tt);
while (tt--) {
maze.clear();
scanf("%d %d", &m, &n);
for (int i = 0; i < m; ++i) {
cin >> str;
maze.push_back(str);
}
cin >> t;
int k = t.size();
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j <= n - k; ++j) {
if (dfs(i, j, 0)) ++ans;
}
}
for (int i = 0; i <= m - k; ++i) {
for (int j = 0; j < n; ++j) {
if (dfs(i, j, 1)) ++ans;
}
}
for (int i = 0; i <= m - k; ++i) {
for (int j = 0; j <= n - k; ++j) {
if (dfs(i, j, 2)) ++ans;
}
}
printf("%d\n", ans);
}
return 0;
}
|
#include "Q04.h"
/* ----------------------- CNode ----------------------- */
CNode::CNode(){
setType(LEAF);
setKeyNum(0);
}
CNode::~CNode(){
setKeyNum(0);
}
int CNode::getKeyIndex(KeyType key)const
{
int left = 0;
int right = getKeyNum()-1;
int current;
while(left!=right)
{
current = (left+right)/2;
KeyType currentKey = getKeyValue(current);
if (key>currentKey)
{
left = current+1;
}
else
{
right = current;
}
}
return left;
}
// CInternalNode
CInternalNode::CInternalNode():CNode(){
setType(INTERNAL);
}
CInternalNode::~CInternalNode(){
}
void CInternalNode::clear()
{
for (int i=0; i<=m_KeyNum; ++i)
{
m_Childs[i]->clear();
delete m_Childs[i];
m_Childs[i] = null;
}
}
void CInternalNode::split(CNode* parentNode, int childIndex)
{
CInternalNode* newNode = new CInternalNode();//ๅ่ฃๅ็ๅณ่็น
newNode->setKeyNum(MINNUM_KEY);
int i;
for (i=0; i<MINNUM_KEY; ++i)// ๆท่ดๅ
ณ้ฎๅญ็ๅผ
{
newNode->setKeyValue(i, m_KeyValues[i+MINNUM_CHILD]);
}
for (i=0; i<MINNUM_CHILD; ++i) // ๆท่ดๅญฉๅญ่็นๆ้
{
newNode->setChild(i, m_Childs[i+MINNUM_CHILD]);
}
setKeyNum(MINNUM_KEY); //ๆดๆฐๅทฆๅญๆ ็ๅ
ณ้ฎๅญไธชๆฐ
((CInternalNode*)parentNode)->insert(childIndex, childIndex+1, m_KeyValues[MINNUM_KEY], newNode);
}
void CInternalNode::insert(int keyIndex, int childIndex, KeyType key, CNode* childNode){
int i;
for (i=getKeyNum(); i>keyIndex; --i)//ๅฐ็ถ่็นไธญ็childIndexๅ็ๆๆๅ
ณ้ฎๅญ็ๅผๅๅญๆ ๆ้ๅๅ็งปไธไฝ
{
setChild(i+1,m_Childs[i]);
setKeyValue(i,m_KeyValues[i-1]);
}
if (i==childIndex)
{
setChild(i+1, m_Childs[i]);
}
setChild(childIndex, childNode);
setKeyValue(keyIndex, key);
setKeyNum(m_KeyNum+1);
}
void CInternalNode::mergeChild(CNode* parentNode, CNode* childNode, int keyIndex)
{
// ๅๅนถๆฐๆฎ
insert(MINNUM_KEY, MINNUM_KEY+1, parentNode->getKeyValue(keyIndex), ((CInternalNode*)childNode)->getChild(0));
int i;
for (i=1; i<=childNode->getKeyNum(); ++i)
{
insert(MINNUM_KEY+i, MINNUM_KEY+i+1, childNode->getKeyValue(i-1), ((CInternalNode*)childNode)->getChild(i));
}
//็ถ่็นๅ ้คindex็key
parentNode->removeKey(keyIndex, keyIndex+1);
delete ((CInternalNode*)parentNode)->getChild(keyIndex+1);
}
void CInternalNode::removeKey(int keyIndex, int childIndex)
{
for (int i=0; i<getKeyNum()-keyIndex-1; ++i)
{
setKeyValue(keyIndex+i, getKeyValue(keyIndex+i+1));
setChild(childIndex+i, getChild(childIndex+i+1));
}
setKeyNum(getKeyNum()-1);
}
void CInternalNode::borrowFrom(CNode* siblingNode, CNode* parentNode, int keyIndex, SIBLING_DIRECTION d)
{
switch(d)
{
case LEFT: // ไปๅทฆๅ
ๅผ็ป็นๅ
{
insert(0, 0, parentNode->getKeyValue(keyIndex), ((CInternalNode*)siblingNode)->getChild(siblingNode->getKeyNum()));
parentNode->setKeyValue(keyIndex, siblingNode->getKeyValue(siblingNode->getKeyNum()-1));
siblingNode->removeKey(siblingNode->getKeyNum()-1, siblingNode->getKeyNum());
}
break;
case RIGHT: // ไปๅณๅ
ๅผ็ป็นๅ
{
insert(getKeyNum(), getKeyNum()+1, parentNode->getKeyValue(keyIndex), ((CInternalNode*)siblingNode)->getChild(0));
parentNode->setKeyValue(keyIndex, siblingNode->getKeyValue(0));
siblingNode->removeKey(0, 0);
}
break;
default:
break;
}
}
int CInternalNode::getChildIndex(KeyType key, int keyIndex)const
{
if (key==getKeyValue(keyIndex))
{
return keyIndex+1;
}
else
{
return keyIndex;
}
}
// CLeafNode
CLeafNode::CLeafNode():CNode(){
setType(LEAF);
setLeftSibling(null);
setRightSibling(null);
}
CLeafNode::~CLeafNode(){
}
void CLeafNode::clear()
{
for (int i=0; i<m_KeyNum; ++i)
{
// if type of m_Datas is pointer
//delete m_Datas[i];
//m_Datas[i] = null;
}
}
void CLeafNode::insert(KeyType key, const DataType& data)
{
int i;
for (i=m_KeyNum; i>=1 && m_KeyValues[i-1]>key; --i)
{
setKeyValue(i, m_KeyValues[i-1]);
setData(i, m_Datas[i-1]);
}
setKeyValue(i, key);
setData(i, data);
setKeyNum(m_KeyNum+1);
}
void CLeafNode::split(CNode* parentNode, int childIndex)
{
CLeafNode* newNode = new CLeafNode();//ๅ่ฃๅ็ๅณ่็น
setKeyNum(MINNUM_LEAF);
newNode->setKeyNum(MINNUM_LEAF+1);
newNode->setRightSibling(getRightSibling());
setRightSibling(newNode);
newNode->setLeftSibling(this);
int i;
for (i=0; i<MINNUM_LEAF+1; ++i)// ๆท่ดๅ
ณ้ฎๅญ็ๅผ
{
newNode->setKeyValue(i, m_KeyValues[i+MINNUM_LEAF]);
}
for (i=0; i<MINNUM_LEAF+1; ++i)// ๆท่ดๆฐๆฎ
{
newNode->setData(i, m_Datas[i+MINNUM_LEAF]);
}
((CInternalNode*)parentNode)->insert(childIndex, childIndex+1, m_KeyValues[MINNUM_LEAF], newNode);
}
void CLeafNode::mergeChild(CNode* parentNode, CNode* childNode, int keyIndex)
{
// ๅๅนถๆฐๆฎ
for (int i=0; i<childNode->getKeyNum(); ++i)
{
insert(childNode->getKeyValue(i), ((CLeafNode*)childNode)->getData(i));
}
setRightSibling(((CLeafNode*)childNode)->getRightSibling());
//็ถ่็นๅ ้คindex็key๏ผ
parentNode->removeKey(keyIndex, keyIndex+1);
}
void CLeafNode::removeKey(int keyIndex, int childIndex)
{
for (int i=keyIndex; i<getKeyNum()-1; ++i)
{
setKeyValue(i, getKeyValue(i+1));
setData(i, getData(i+1));
}
setKeyNum(getKeyNum()-1);
}
void CLeafNode::borrowFrom(CNode* siblingNode, CNode* parentNode, int keyIndex, SIBLING_DIRECTION d)
{
switch(d)
{
case LEFT: // ไปๅทฆๅ
ๅผ็ป็นๅ
{
insert(siblingNode->getKeyValue(siblingNode->getKeyNum()-1), ((CLeafNode*)siblingNode)->getData(siblingNode->getKeyNum()-1));
siblingNode->removeKey(siblingNode->getKeyNum()-1, siblingNode->getKeyNum()-1);
parentNode->setKeyValue(keyIndex, getKeyValue(0));
}
break;
case RIGHT: // ไปๅณๅ
ๅผ็ป็นๅ
{
insert(siblingNode->getKeyValue(0), ((CLeafNode*)siblingNode)->getData(0));
siblingNode->removeKey(0, 0);
parentNode->setKeyValue(keyIndex, siblingNode->getKeyValue(0));
}
break;
default:
break;
}
}
int CLeafNode::getChildIndex(KeyType key, int keyIndex)const
{
return keyIndex;
}
/* ----------------------- CNode ----------------------- */
/* ----------------------- B+ Tree ----------------------- */
CBPlusTree::CBPlusTree(){
m_Root = null;
m_DataHead = null;
}
CBPlusTree::~CBPlusTree(){
clear();
}
bool CBPlusTree::insert(KeyType key, const DataType& data){
// ๆฏๅฆๅทฒ็ปๅญๅจ
if (search(key))
{
return false;
}
// ๆพๅฐๅฏไปฅๆๅ
ฅ็ๅถๅญ็ป็น๏ผๅฆๅๅๅปบๆฐ็ๅถๅญ็ป็น
if(m_Root==null)
{
m_Root = new CLeafNode();
m_DataHead = (CLeafNode*)m_Root;
m_MaxKey = key;
}
if (m_Root->getKeyNum()>=MAXNUM_KEY) // ๆ น็ป็นๅทฒๆปก๏ผๅ่ฃ
{
CInternalNode* newNode = new CInternalNode(); //ๅๅปบๆฐ็ๆ น่็น
newNode->setChild(0, m_Root);
m_Root->split(newNode, 0); // ๅถๅญ็ป็นๅ่ฃ
m_Root = newNode; //ๆดๆฐๆ น่็นๆ้
}
if (key>m_MaxKey) // ๆดๆฐๆๅคง้ฎๅผ
{
m_MaxKey = key;
}
recursive_insert(m_Root, key, data);
return true;
}
void CBPlusTree::recursive_insert(CNode* parentNode, KeyType key, const DataType& data)
{
if (parentNode->getType()==LEAF) // ๅถๅญ็ป็น๏ผ็ดๆฅๆๅ
ฅ
{
((CLeafNode*)parentNode)->insert(key, data);
}
else
{
// ๆพๅฐๅญ็ป็น
int keyIndex = parentNode->getKeyIndex(key);
int childIndex= parentNode->getChildIndex(key, keyIndex); // ๅญฉๅญ็ป็นๆ้็ดขๅผ
CNode* childNode = ((CInternalNode*)parentNode)->getChild(childIndex);
if (childNode->getKeyNum()>=MAXNUM_LEAF) // ๅญ็ป็นๅทฒๆปก๏ผ้่ฟ่กๅ่ฃ
{
childNode->split(parentNode, childIndex);
if (parentNode->getKeyValue(childIndex)<=key) // ็กฎๅฎ็ฎๆ ๅญ็ป็น
{
childNode = ((CInternalNode*)parentNode)->getChild(childIndex+1);
}
}
recursive_insert(childNode, key, data);
}
}
void CBPlusTree::clear()
{
if (m_Root!=null)
{
m_Root->clear();
delete m_Root;
m_Root = null;
m_DataHead = null;
}
}
bool CBPlusTree::search(KeyType key)
{
return recursive_search(m_Root, key);
}
bool CBPlusTree::recursive_search(CNode *pNode, KeyType key)const
{
if (pNode==null) //ๆฃๆต่็นๆ้ๆฏๅฆไธบ็ฉบ๏ผๆ่ฏฅ่็นๆฏๅฆไธบๅถๅญ่็น
{
return false;
}
else
{
int keyIndex = pNode->getKeyIndex(key);
int childIndex = pNode->getChildIndex(key, keyIndex); // ๅญฉๅญ็ป็นๆ้็ดขๅผ
if (keyIndex<pNode->getKeyNum() && key==pNode->getKeyValue(keyIndex))
{
return true;
}
else
{
if (pNode->getType()==LEAF) //ๆฃๆฅ่ฏฅ่็นๆฏๅฆไธบๅถๅญ่็น
{
return false;
}
else
{
return recursive_search(((CInternalNode*)pNode)->getChild(childIndex), key);
}
}
}
}
void CBPlusTree::print()const
{
printInConcavo(m_Root, 10);
}
void CBPlusTree::printInConcavo(CNode *pNode, int count) const{
if (pNode!=null)
{
int i, j;
for (i=0; i<pNode->getKeyNum(); ++i)
{
if (pNode->getType()!=LEAF)
{
printInConcavo(((CInternalNode*)pNode)->getChild(i), count-2);
}
for (j=count; j>=0; --j)
{
cout<<"-";
}
cout<<pNode->getKeyValue(i)<<endl;
}
if (pNode->getType()!=LEAF)
{
printInConcavo(((CInternalNode*)pNode)->getChild(i), count-2);
}
}
}
void CBPlusTree::printData()const
{
CLeafNode* itr = m_DataHead;
while(itr!=null)
{
for (int i=0; i<itr->getKeyNum(); ++i)
{
cout<<itr->getData(i)<<" ";
}
cout<<endl;
itr = itr->getRightSibling();
}
}
bool CBPlusTree::remove(KeyType key)
{
if (!search(key)) //ไธๅญๅจ
{
return false;
}
if (m_Root->getKeyNum()==1)//็นๆฎๆ
ๅตๅค็
{
if (m_Root->getType()==LEAF)
{
clear();
return true;
}
else
{
CNode *pChild1 = ((CInternalNode*)m_Root)->getChild(0);
CNode *pChild2 = ((CInternalNode*)m_Root)->getChild(1);
if (pChild1->getKeyNum()==MINNUM_KEY && pChild2->getKeyNum()==MINNUM_KEY)
{
pChild1->mergeChild(m_Root, pChild2, 0);
delete m_Root;
m_Root = pChild1;
}
}
}
recursive_remove(m_Root, key);
return true;
}
// parentNodeไธญๅ
ๅซ็้ฎๅผๆฐ>MINNUM_KEY
void CBPlusTree::recursive_remove(CNode* parentNode, KeyType key)
{
int keyIndex = parentNode->getKeyIndex(key);
int childIndex= parentNode->getChildIndex(key, keyIndex); // ๅญฉๅญ็ป็นๆ้็ดขๅผ
if (parentNode->getType()==LEAF)// ๆพๅฐ็ฎๆ ๅถๅญ่็น
{
if (key==m_MaxKey&&keyIndex>0)
{
m_MaxKey = parentNode->getKeyValue(keyIndex-1);
}
parentNode->removeKey(keyIndex, childIndex); // ็ดๆฅๅ ้ค
// ๅฆๆ้ฎๅผๅจๅ
้จ็ป็นไธญๅญๅจ๏ผไน่ฆ็ธๅบ็ๆฟๆขๅ
้จ็ป็น
if (childIndex==0 && m_Root->getType()!=LEAF && parentNode!=m_DataHead)
{
changeKey(m_Root, key, parentNode->getKeyValue(0));
}
}
else // ๅ
็ป็น
{
CNode *pChildNode = ((CInternalNode*)parentNode)->getChild(childIndex); //ๅ
ๅซkey็ๅญๆ ๆ น่็น
if (pChildNode->getKeyNum()==MINNUM_KEY) // ๅ
ๅซๅ
ณ้ฎๅญ่พพๅฐไธ้ๅผ๏ผ่ฟ่ก็ธๅ
ณๆไฝ
{
CNode *pLeft = childIndex>0 ? ((CInternalNode*)parentNode)->getChild(childIndex-1) : null; //ๅทฆๅ
ๅผ่็น
CNode *pRight = childIndex<parentNode->getKeyNum() ? ((CInternalNode*)parentNode)->getChild(childIndex+1) : null;//ๅณๅ
ๅผ่็น
// ๅ
่่ไปๅ
ๅผ็ป็นไธญๅ
if (pLeft && pLeft->getKeyNum()>MINNUM_KEY)// ๅทฆๅ
ๅผ็ป็นๅฏๅ
{
pChildNode->borrowFrom(pLeft, parentNode, childIndex-1, LEFT);
}
else if (pRight && pRight->getKeyNum()>MINNUM_KEY)//ๅณๅ
ๅผ็ป็นๅฏๅ
{
pChildNode->borrowFrom(pRight, parentNode, childIndex, RIGHT);
}
//ๅทฆๅณๅ
ๅผ่็น้ฝไธๅฏๅ๏ผ่่ๅๅนถ
else if (pLeft) //ไธๅทฆๅ
ๅผๅๅนถ
{
pLeft->mergeChild(parentNode, pChildNode, childIndex-1);
pChildNode = pLeft;
}
else if (pRight) //ไธๅณๅ
ๅผๅๅนถ
{
pChildNode->mergeChild(parentNode, pRight, childIndex);
}
}
recursive_remove(pChildNode, key);
}
}
void CBPlusTree::changeKey(CNode *pNode, KeyType oldKey, KeyType newKey)
{
if (pNode!=null && pNode->getType()!=LEAF)
{
int keyIndex = pNode->getKeyIndex(oldKey);
if (keyIndex<pNode->getKeyNum() && oldKey==pNode->getKeyValue(keyIndex)) // ๆพๅฐ
{
pNode->setKeyValue(keyIndex, newKey);
}
else // ็ปง็ปญๆพ
{
changeKey(((CInternalNode*)pNode)->getChild(keyIndex), oldKey, newKey);
}
}
}
bool CBPlusTree::update(KeyType oldKey, KeyType newKey)
{
if (search(newKey)) // ๆฃๆฅๆดๆฐๅ็้ฎๆฏๅฆๅทฒ็ปๅญๅจ
{
return false;
}
else
{
int dataValue;
remove(oldKey, dataValue);
if (dataValue==INVALID_INDEX)
{
return false;
}
else
{
return insert(newKey, dataValue);
}
}
}
void CBPlusTree::remove(KeyType key, DataType& dataValue)
{
if (!search(key)) //ไธๅญๅจ
{
dataValue = INVALID_INDEX;
return;
}
if (m_Root->getKeyNum()==1)//็นๆฎๆ
ๅตๅค็
{
if (m_Root->getType()==LEAF)
{
dataValue = ((CLeafNode*)m_Root)->getData(0);
clear();
return;
}
else
{
CNode *pChild1 = ((CInternalNode*)m_Root)->getChild(0);
CNode *pChild2 = ((CInternalNode*)m_Root)->getChild(1);
if (pChild1->getKeyNum()==MINNUM_KEY && pChild2->getKeyNum()==MINNUM_KEY)
{
pChild1->mergeChild(m_Root, pChild2, 0);
delete m_Root;
m_Root = pChild1;
}
}
}
recursive_remove(m_Root, key, dataValue);
}
void CBPlusTree::recursive_remove(CNode* parentNode, KeyType key, DataType& dataValue)
{
int keyIndex = parentNode->getKeyIndex(key);
int childIndex= parentNode->getChildIndex(key, keyIndex); // ๅญฉๅญ็ป็นๆ้็ดขๅผ
if (parentNode->getType()==LEAF)// ๆพๅฐ็ฎๆ ๅถๅญ่็น
{
if (key==m_MaxKey&&keyIndex>0)
{
m_MaxKey = parentNode->getKeyValue(keyIndex-1);
}
dataValue = ((CLeafNode*)parentNode)->getData(keyIndex);
parentNode->removeKey(keyIndex, childIndex); // ็ดๆฅๅ ้ค
// ๅฆๆ้ฎๅผๅจๅ
้จ็ป็นไธญๅญๅจ๏ผไน่ฆ็ธๅบ็ๆฟๆขๅ
้จ็ป็น
if (childIndex==0 && m_Root->getType()!=LEAF && parentNode!=m_DataHead)
{
changeKey(m_Root, key, parentNode->getKeyValue(0));
}
}
else // ๅ
็ป็น
{
CNode *pChildNode = ((CInternalNode*)parentNode)->getChild(childIndex); //ๅ
ๅซkey็ๅญๆ ๆ น่็น
if (pChildNode->getKeyNum()==MINNUM_KEY) // ๅ
ๅซๅ
ณ้ฎๅญ่พพๅฐไธ้ๅผ๏ผ่ฟ่ก็ธๅ
ณๆไฝ
{
CNode *pLeft = childIndex>0 ? ((CInternalNode*)parentNode)->getChild(childIndex-1) : null; //ๅทฆๅ
ๅผ่็น
CNode *pRight = childIndex<parentNode->getKeyNum() ? ((CInternalNode*)parentNode)->getChild(childIndex+1) : null;//ๅณๅ
ๅผ่็น
// ๅ
่่ไปๅ
ๅผ็ป็นไธญๅ
if (pLeft && pLeft->getKeyNum()>MINNUM_KEY)// ๅทฆๅ
ๅผ็ป็นๅฏๅ
{
pChildNode->borrowFrom(pLeft, parentNode, childIndex-1, LEFT);
}
else if (pRight && pRight->getKeyNum()>MINNUM_KEY)//ๅณๅ
ๅผ็ป็นๅฏๅ
{
pChildNode->borrowFrom(pRight, parentNode, childIndex, RIGHT);
}
//ๅทฆๅณๅ
ๅผ่็น้ฝไธๅฏๅ๏ผ่่ๅๅนถ
else if (pLeft) //ไธๅทฆๅ
ๅผๅๅนถ
{
pLeft->mergeChild(parentNode, pChildNode, childIndex-1);
pChildNode = pLeft;
}
else if (pRight) //ไธๅณๅ
ๅผๅๅนถ
{
pChildNode->mergeChild(parentNode, pRight, childIndex);
}
}
recursive_remove(pChildNode, key, dataValue);
}
}
vector<DataType> CBPlusTree::select(KeyType compareKey, int compareOpeartor)
{
vector<DataType> results;
if (m_Root!=null)
{
if (compareKey>m_MaxKey) // ๆฏ่พ้ฎๅผๅคงไบB+ๆ ไธญๆๅคง็้ฎๅผ
{
if (compareOpeartor==LE || compareOpeartor==LT)
{
for(CLeafNode* itr = m_DataHead; itr!=null; itr= itr->getRightSibling())
{
for (int i=0; i<itr->getKeyNum(); ++i)
{
results.push_back(itr->getData(i));
}
}
}
}
else if (compareKey<m_DataHead->getKeyValue(0)) // ๆฏ่พ้ฎๅผๅฐไบB+ๆ ไธญๆๅฐ็้ฎๅผ
{
if (compareOpeartor==BE || compareOpeartor==BT)
{
for(CLeafNode* itr = m_DataHead; itr!=null; itr= itr->getRightSibling())
{
for (int i=0; i<itr->getKeyNum(); ++i)
{
results.push_back(itr->getData(i));
}
}
}
}
else // ๆฏ่พ้ฎๅผๅจB+ๆ ไธญ
{
SelectResult result;
search(compareKey, result);
switch(compareOpeartor)
{
case LT:
case LE:
{
CLeafNode* itr = m_DataHead;
int i;
while (itr!=result.targetNode)
{
for (i=0; i<itr->getKeyNum(); ++i)
{
results.push_back(itr->getData(i));
}
itr = itr->getRightSibling();
}
for (i=0; i<result.keyIndex; ++i)
{
results.push_back(itr->getData(i));
}
if (itr->getKeyValue(i)<compareKey ||
(compareOpeartor==LE && compareKey==itr->getKeyValue(i)))
{
results.push_back(itr->getData(i));
}
}
break;
case EQ:
{
if (result.targetNode->getKeyValue(result.keyIndex)==compareKey)
{
results.push_back(result.targetNode->getData(result.keyIndex));
}
}
break;
case BE:
case BT:
{
CLeafNode* itr = result.targetNode;
if (compareKey<itr->getKeyValue(result.keyIndex) ||
(compareOpeartor==BE && compareKey==itr->getKeyValue(result.keyIndex))
)
{
results.push_back(itr->getData(result.keyIndex));
}
int i;
for (i=result.keyIndex+1; i<itr->getKeyNum(); ++i)
{
results.push_back(itr->getData(i));
}
itr = itr->getRightSibling();
while (itr!=null)
{
for (i=0; i<itr->getKeyNum(); ++i)
{
results.push_back(itr->getData(i));
}
itr = itr->getRightSibling();
}
}
break;
default: // ่ๅดๆฅ่ฏข
break;
}
}
}
sort<vector<DataType>::iterator>(results.begin(), results.end());
return results;
}
vector<DataType> CBPlusTree::select(KeyType smallKey, KeyType largeKey)
{
vector<DataType> results;
if (smallKey<=largeKey)
{
SelectResult start, end;
search(smallKey, start);
search(largeKey, end);
CLeafNode* itr = start.targetNode;
int i = start.keyIndex;
if (itr->getKeyValue(i)<smallKey)
{
++i;
}
if (end.targetNode->getKeyValue(end.keyIndex)>largeKey)
{
--end.keyIndex;
}
while (itr!=end.targetNode)
{
for (; i<itr->getKeyNum(); ++i)
{
results.push_back(itr->getData(i));
}
itr = itr->getRightSibling();
i = 0;
}
for (; i<=end.keyIndex; ++i)
{
results.push_back(itr->getData(i));
}
}
sort<vector<DataType>::iterator>(results.begin(), results.end());
return results;
}
void CBPlusTree::search(KeyType key, SelectResult& result)
{
recursive_search(m_Root, key, result);
}
void CBPlusTree::recursive_search(CNode* pNode, KeyType key, SelectResult& result)
{
int keyIndex = pNode->getKeyIndex(key);
int childIndex = pNode->getChildIndex(key, keyIndex); // ๅญฉๅญ็ป็นๆ้็ดขๅผ
if (pNode->getType()==LEAF)
{
result.keyIndex = keyIndex;
result.targetNode = (CLeafNode*)pNode;
return;
}
else
{
return recursive_search(((CInternalNode*)pNode)->getChild(childIndex), key, result);
}
}
/* ----------------------- B+ Tree ----------------------- */
|
#include "Includes.h"
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int solver(const vector<int> &v);
void uva11264Main() {
int ntc, n, x;
vector<int> v;
scanf("%d", &ntc);
while(ntc-->0) {
scanf("%d", &n);
for(int i=0; i<n; i++) {
cin>>x;
v.push_back(x);
}
printf("RESULT %d RESULT\n",solver(v));
v.clear();
}
}
int solver(const vector<int> &v) {
int result = v.size() > 1 ? 2 : 1, sum = 1;
for(int i=0; i<v.size()-1; i++) {
if(sum + v[i] < v[i+1]) {
sum+=v[i];
++result;
}
}
return result;
}
|
#pragma once
class IKComponent;
class IKObject : public hg::IComponent
{
public:
IKObject();
static hg::Entity* Create(XMVECTOR pos, XMVECTOR dir, float length, StrID ikInstanceName, IKObject* parent = nullptr, IKComponent* ikComponent = nullptr);
static hg::Entity* Create( XMVECTOR pos, XMVECTOR dir, float length, hg::Entity* entity, IKObject* parent = nullptr, IKComponent* ikComponent = nullptr );
static hg::Entity* CreateFront( XMVECTOR pos, XMVECTOR dir, float length, StrID ikInstanceName, IKObject* parent = nullptr, IKComponent* ikComponent = nullptr );
void PointTo(hg::Transform* target);
void DragTo(hg::Transform* target, float dragSpeed = 5.0f);
void DragToReversed( hg::Transform* target, float dragSpeed = 5.0f );
void Drag(hg::Transform* target);
virtual int GetTypeID() const { return s_TypeID; }
float Length()const;
hg::IComponent* MakeCopyDerived() const;
void OnMessage(hg::Message* msg)override;
public:
static uint32_t s_TypeID;
friend IKComponent;
private:
IKComponent* m_ik;
IKObject* m_parent;
IKObject* m_child;
float m_length;
};
|
//
// Created by jglrxavpok on 04/09/2020.
//
#pragma once
#include <curand_kernel.h>
#include "Material.h"
class Dielectric: public Material {
private:
double refractiveIndex;
public:
__device__ explicit Dielectric(double refractiveIndex);
__device__ bool
scatter(const Ray &ray, const HitResult &hit, curandState *rand, Color &attenuation, Ray &scattered) const override;
};
|
#ifndef _UTIL_QP_H_
#define _UTIL_QP_H_
#include "adjunct/m2/src/include/defs.h"
#include "modules/encodings/charconverter.h"
#include "modules/util/opstring.h"
#if !defined IN
# define IN
#endif
#if !defined OUT
# define OUT
#endif
#if !defined IO
# define IO
#endif
class InputConverterManager;
class OpQP
{
public:
OpQP() {}
~OpQP() {}
private:
static BOOL LooksLikeQPEncodedWord(const OpStringC16& buffer, int& start_offset, int& end_offset);
static void SkipWhitespaceBeforeEncodedWord(IO const char** src);
static OP_STATUS AppendText(const OpStringC8& charset, OpString16& destination, const char* source, int length=KAll, BOOL accept_illegal_characters=FALSE);
static OP_STATUS StartNewLine(OpString8& buffer, const OpStringC8& charset, const OpStringC8& type, UINT8& chars_used, BOOL first_line=FALSE);
static const char* StartOfEncodedWord(const char* buffer, BOOL allow_quotedstring_qp, const char** start_of_iso2022 = NULL);
static OP_STATUS UnknownDecode(IO const char** src, IN const OpStringC8& charset, OpString16& decoded);
static void Base64Encode(const char* source_3bytes, UINT8 bytes_to_convert, char* destination_4bytes);
static OP_STATUS Base64LineEncode(IN const uni_char* source, OUT OpString8& encoded, const OpStringC8& charset); //Will not clear 'encoded' before encoding!
static BOOL QPEncode(IN char source, OUT char* destination_2bytes); //Returns TRUE if source has been encoded into destination
static OP_STATUS QPLineEncode(IN const uni_char* source, OUT OpString8& encoded, OpString8& charset); //Will not clear 'encoded' before encoding!
static InputConverterManager* s_input_converter_manager;
static InputConverterManager& GetInputConverterManager();
public:
static OP_STATUS QPDecode(const BYTE*& src, const OpStringC8& charset, OpString16& decoded,
BOOL& warning_found, BOOL& error_found, BOOL encoded_word = TRUE);
static OP_STATUS Base64Decode(const BYTE*& src, const OpStringC8& charset, OpString16& decoded,
BOOL& warning_found, BOOL& error_found, BOOL encoded_word = TRUE);
static OP_STATUS Base64Encode(IN const OpStringC16& source, OUT OpString8& encoded, OpString8& charset, BOOL add_controlchars=TRUE, BOOL is_subject=FALSE);
static OP_STATUS Base64Encode(const char* source, int length, OpString8& encoded);
static OP_STATUS QPEncode(IN const OpStringC16& source, OUT OpString8& encoded, OpString8& charset, BOOL add_controlchars=TRUE, BOOL is_subject=FALSE);
static UINT8 BitsNeeded(const OpStringC16& buffer, int length=KAll); //returns 7, 8 or 16
static UINT8 BitsNeeded(const OpStringC8& buffer, int length=KAll); //returns 7 or 8
static OP_STATUS Encode(IN const OpStringC16& source, OUT OpString8& encoded, OpString8& charset, BOOL allow_8bit=FALSE, BOOL is_subject=FALSE, BOOL check_for_lookalikes=TRUE);
static OP_STATUS Decode(IN const OpStringC8& source, OUT OpString16& decoded, const OpStringC8& preferred_charset,
BOOL& warning_found, BOOL& error_found, BOOL allow_quotedstring_qp=FALSE, BOOL is_rfc822=FALSE);
static void SetInputConverterManager(InputConverterManager* input_converter_manager);
};
#endif
|
#include <iostream>
#include <utility>
using std::cout;
//------------------------------
template<typename T1, typename T2>
struct pair{
typedef T1 first_type; // Sposob na przechowanie typow
typedef T2 second_type; // wewnatrz struktury.
pair() : first(T1()), second(T2()) {}
pair(const T1 &a, const T2 &b) : first(a), second(b) {}
template<typename U1, typename U2>
pair(const pair<U1, U2> &p) : first(p.first), second(p.second) {}
T1 first;
T2 second;
};
template<typename T1, typename T2>
bool operator==(const pair<T1, T2> &a, const pair<T1, T2> &b){
return a.first == b.first && a.second == b.second;
}
template<typename T1, typename T2>
pair<T1, T2> make_pair(const T1 &a, const T2 &b){
return pair<T1, T2>(a, b);
}
//------------------------------
// Jesli nie byloby const w zwracanym typie,
// nie moznaby okreslic argumentow jako const.
template<typename T> const T& min(const T &a, const T &b){
return a<b ? a : b;
}
// STL jest tak przygotowany, ze preferuje '<' ponad '>'.
template<typename T> const T& max(const T &a, const T &b){
return a<b ? b : a;
}
template<typename T> void swap(T &a, T &b){
T tmp = a;
a = b;
b = tmp;
}
//------------------------------
int main(){
// pair<int, char> ic(321, 'x');
auto ic = make_pair(321, 'x');
pair<float, int> fi(ic);
struct{int dx, dy;} v{3, -1}, u{0, 7};
auto vv = make_pair(v, u);
std::cout << vv.first.dx << "/" << vv.second.dy << '\n';
float q1(3.14159), q2(2.7182818);
std::cout << "min: " << min(q1, q2) << '\n';
std::cout << "max: " << max(q1, q2) << '\n';
std::cout << "Watchout " << max<double>(1, 2.5) << '\n';
swap(q1, q2);
std::cout << "pi = " << q1 << ", e = " << q2 << '\n';
}
|
#ifndef BUTTON_H_
#define BUTTON_H_
#include "GameInterface.h"
class Button : public GameInterface
{
public:
Button(SDL_Rect *r, /*SDL_Texture *t*/SDL_Surface *s);
bool isActive(Uint32 mouseState, SDL_Event event);
};
#endif
|
#include <iberbar/Font/FreeType.h>
#include <iberbar/Utility/Math.h>
#include <iberbar/Utility/Buffer.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include FT_STROKER_H
#include <freetype/fterrors.h>
namespace iberbar
{
class CBitsBuffer
{
public:
CBitsBuffer( void );
~CBitsBuffer();
void PaintChar( const CSize2i& BitmapSize, const CSize2i& CopySize, const CPoint2i& CopyOffset, const uint8* pBytes );
void PaintChar( const CSize2i& BitmapSize, const uint8* pBytes );
void* GetBitsFill() { return m_pBits.GetPointer(); }
private:
TBuffer<uint8> m_pBits;
CSize2i m_BitmapSize;
};
class CFontDeviceFtCore
{
public:
CFontDeviceFtCore();
~CFontDeviceFtCore();
public:
CResult Initialize();
FORCEINLINE FT_Library GetFTLibrary() { return m_Library; }
private:
FT_Library m_Library;
FT_Stroker m_Stroker;
};
class CFontFaceFtCore
{
public:
CFontFaceFtCore();
~CFontFaceFtCore();
CResult Initialize( FT_Library pLibrary, const char* strFile );
FORCEINLINE FT_Face GetFtFace() { return m_pFtFace; }
private:
FT_Face m_pFtFace;
};
}
iberbar::CFontDeviceFtCore::CFontDeviceFtCore()
: m_Library( nullptr )
, m_Stroker( nullptr )
{
}
iberbar::CFontDeviceFtCore::~CFontDeviceFtCore()
{
if ( m_Stroker )
{
FT_Stroker_Done( m_Stroker );
m_Stroker = NULL;
}
if ( m_Library )
{
FT_Done_FreeType( m_Library );
m_Library = NULL;
}
}
iberbar::CResult iberbar::CFontDeviceFtCore::Initialize()
{
FT_Error err = FT_Init_FreeType( &m_Library );
if ( err )
return MakeResult( ResultCode::Bad, FT_Error_String( err ) );
err = FT_Stroker_New( m_Library, &m_Stroker );
if ( err )
return MakeResult( ResultCode::Bad, FT_Error_String( err ) );
return CResult();
}
iberbar::CFontFaceFtCore::CFontFaceFtCore()
: m_pFtFace( nullptr )
{
}
iberbar::CFontFaceFtCore::~CFontFaceFtCore()
{
if ( m_pFtFace )
{
FT_Done_Face( m_pFtFace );
m_pFtFace = nullptr;
}
}
iberbar::CResult iberbar::CFontFaceFtCore::Initialize( FT_Library pLibrary, const char* strFile )
{
FT_Error err = FT_New_Face( pLibrary, strFile, 0, &m_pFtFace );
if ( err == FT_Err_Unknown_File_Format )
return MakeResult( ResultCode::Bad, FT_Error_String( err ) );
else if ( err )
return MakeResult( ResultCode::Bad, FT_Error_String( err ) );
return CResult();
}
iberbar::CFontDeviceFt::CFontDeviceFt()
: m_pCore( new CFontDeviceFtCore() )
{
}
iberbar::CFontDeviceFt::~CFontDeviceFt()
{
SAFE_DELETE( m_pCore );
}
iberbar::CResult iberbar::CFontDeviceFt::Initialize()
{
return m_pCore->Initialize();
}
iberbar::CResult iberbar::CFontDeviceFt::CreateFace( CFontFaceFt** ppOutFace, const char* strFile )
{
assert( ppOutFace );
CFontFaceFtCore* pFaceCore = new CFontFaceFtCore();
CResult ret = pFaceCore->Initialize( m_pCore->GetFTLibrary(), strFile );
if ( ret.IsOK() == false )
{
delete pFaceCore;
return ret;
}
if ( *ppOutFace )
(*ppOutFace)->Release();
(*ppOutFace) = new CFontFaceFt( pFaceCore );
return CResult();
}
iberbar::CFontFaceFt::CFontFaceFt( CFontFaceFtCore* pFaceCore )
: m_pCore( pFaceCore )
, m_nFontSizeNow( 0 )
, m_nFontWeightNow( 0 )
, m_pByteBuffer( new CBitsBuffer() )
{
}
iberbar::CFontFaceFt::~CFontFaceFt()
{
SAFE_DELETE( m_pCore );
SAFE_DELETE( m_pByteBuffer );
}
iberbar::CResult iberbar::CFontFaceFt::SetFontSize( int nSize )
{
FT_Error err;
FT_Face pFtFace = m_pCore->GetFtFace();
if ( m_nFontSizeNow == nSize )
return CResult();
m_nFontSizeNow = nSize;
if ( m_nFontSizeNow <= 0 )
return MakeResult( ResultCode::Bad, "Invalid font size" );
//err = FT_Set_Char_Size( pFtFace, 0, nSize * 64, 72, 72 );
//if ( err )
// return MakeResult( ResultCode::Bad, FT_Error_String( err ) );
// ๅ
่ทๅ่ฏฅๅญไฝ็้ป่พๅฐบๅฏธๅๅฎ้
ๅฐบๅฏธ็ๆฏไพ
err = FT_Set_Pixel_Sizes( pFtFace, nSize, nSize );
if ( err )
return MakeResult( ResultCode::Bad, FT_Error_String( err ) );
int lc_RealSize = pFtFace->size->metrics.height >> 6;
// ้ๆฐ่ฎก็ฎ็ๅฎ้่ฆ็้ป่พๅฐบๅฏธ
int FontWidth = nSize * nSize / lc_RealSize;
int FontHeight = nSize * nSize / lc_RealSize;
err = FT_Set_Pixel_Sizes( pFtFace, FontWidth, FontHeight );
if ( err )
return MakeResult( ResultCode::Bad, FT_Error_String( err ) );
return CResult();
}
iberbar::CResult iberbar::CFontFaceFt::SetFontWeight( int nWeight )
{
return CResult();
}
iberbar::CResult iberbar::CFontFaceFt::CreateCharBitmap( wchar_t nChar, UFontCharBitmapDesc* pDesc, UFontBitsFormat nBitsFormat )
{
FT_Error error = FT_Err_Ok;
FT_Face pFtFace = m_pCore->GetFtFace();
assert( pFtFace );
FT_UInt nGlyphIndex = FT_Get_Char_Index( pFtFace, nChar );
//FT_Int32 nLoadGlyphFlags = FT_LOAD_FORCE_AUTOHINT | FT_LOAD_RENDER;
FT_Int32 nLoadGlyphFlags = FT_LOAD_FORCE_AUTOHINT;
error = FT_Load_Glyph( pFtFace, nGlyphIndex, nLoadGlyphFlags );
if ( error )
return MakeResult( ResultCode::Bad, FT_Error_String( error ) );
////ๅพๅฐๅญๆจก
FT_GlyphSlot pGlyphSlot = pFtFace->glyph;
FT_Glyph pGlyph;
error = FT_Get_Glyph( pGlyphSlot, &pGlyph );
if ( error )
return MakeResult( ResultCode::Bad, FT_Error_String( error ) );
//่ฝฌๅๆไฝๅพ
error = FT_Render_Glyph( pGlyphSlot, FT_RENDER_MODE_NORMAL );
if ( error )
return MakeResult( ResultCode::Bad, FT_Error_String( error ) );
error = FT_Glyph_To_Bitmap( &pGlyph, FT_RENDER_MODE_NORMAL, 0, true );
if ( error )
return MakeResult( ResultCode::Bad, FT_Error_String( error ) );
FT_BitmapGlyph pBitmapGlyph = (FT_BitmapGlyph)pGlyph;
//ๅ้ไฝๅพๆฐๆฎ
FT_Bitmap& lc_bitmap = pBitmapGlyph->bitmap;
//ๆไฝๅพๆฐๆฎๆท่ด่ชๅทฑๅฎไน็ๆฐๆฎๅบ้.่ฟๆ ทๆงๅฏไปฅ็ปๅฐ้่ฆ็ไธ่ฅฟไธ้ขไบใ
int nBitmapWidth = lc_bitmap.width;
int nBitmapHeight = lc_bitmap.rows;
int nAscender = (int)(pFtFace->size->metrics.ascender / 64.0f);
int nAdvX = (int)(pFtFace->glyph->metrics.horiAdvance / 64.0f); //ๆญฅ่ฟๅฎฝๅบฆ
int nAdvY = (int)/*( pFtFace->pGlyph->metrics.vertAdvance / 64.0f )*/pFtFace->size->metrics.y_ppem;
int nDeltaX = (int)pBitmapGlyph->left; //left:ๅญๅฝขๅ็น(0,0)ๅฐๅญๅฝขไฝๅพๆๅทฆ่พน่ฑก็ด ็ๆฐดๅนณ่ท็ฆป.ๅฎไปฅๆดๆฐ่ฑก็ด ็ๅฝขๅผ่กจ็คบใ
int nDeltaY = (int)(nAscender - pFtFace->glyph->bitmap_top);
nAdvY = tMax( nDeltaY + nBitmapHeight, nAdvY );
if ( nBitmapWidth > 0 && nBitmapHeight > 0 )
{
m_pByteBuffer->PaintChar( CSize2i( nBitmapWidth, nBitmapHeight ), lc_bitmap.buffer );
pDesc->pBitsFill = m_pByteBuffer->GetBitsFill();
}
else
{
pDesc->pBitsFill = nullptr;
}
pDesc->bOutline = false;
pDesc->nBmpWidth = nBitmapWidth;
pDesc->nBmpHeight = nBitmapHeight;
pDesc->nCharWidth = nAdvX;
pDesc->nCharHeight = m_nFontSizeNow;
pDesc->nDeltaX = nDeltaX;
pDesc->nDeltaY = nDeltaY;
FT_Done_Glyph( pGlyph );
return CResult();
}
iberbar::CBitsBuffer::CBitsBuffer( void )
: m_pBits()
{
}
iberbar::CBitsBuffer::~CBitsBuffer()
{
m_pBits.Clear();
}
//void iberbar::CBitsBuffer::StartPaint( CSize2i BitmapSize, UFontBitsFormat format )
//{
// assert( BitmapSize.w > 0 && BitmapSize.h );
// m_bStartDraw = true;
// m_nPaintOffset = 0;
// m_nPaintSize = 0;
//
// uint32 lc_bitsSize = BitmapSize.w * BitmapSize.h * 4;
// if ( m_nBitsSize == 0 || lc_bitsSize > m_nBitsSize )
// {
// m_pBits[ 0 ].Resize( lc_bitsSize, false );
// m_pBits[ 1 ].Resize( lc_bitsSize, false );
// m_nBitsSize = lc_bitsSize;
// }
// memset( m_pBits[ 0 ].GetPointer(), 0, lc_bitsSize );
// memset( m_pBits[ 1 ].GetPointer(), 0, lc_bitsSize );
// m_BitmapSize = BitmapSize;
// m_format = format;
//}
//
//
//void iberbar::CBitsBuffer::EndPaint()
//{
// m_bStartDraw = false;
//}
void iberbar::CBitsBuffer::PaintChar( const CSize2i& BitmapSize, const CSize2i& CopySize, const CPoint2i& ptDelta, const uint8* pBytes )
{
int nByteCount = BitmapSize.w * BitmapSize.h * 4;
if ( nByteCount > (int)m_pBits.GetDataSize() )
{
m_pBits.Resize( nByteCount );
}
memset( m_pBits.GetPointer(), 0xff, nByteCount );
int nAlphaIndex = 3;
uint8* pDst = m_pBits.GetPointer();
const uint8* pSrc = pBytes;
int nSrcStartX = (ptDelta.x < 0) ? 0 : ptDelta.x;
int nSrcStartY = (ptDelta.y < 0) ? 0 : ptDelta.y;
int nSrcEndX = nSrcStartX + CopySize.w;
int nSrcEndY = nSrcStartY + CopySize.h;
int nDstStride = BitmapSize.w * 4;
int nSrcStride = CopySize.w;
for ( int y = 0; y < BitmapSize.h; y++ )
{
if ( y >= nSrcStartY && y < nSrcEndY )
{
for ( int x = 0; x < BitmapSize.w; x++ )
{
if ( x >= nSrcStartX && x < nSrcEndX )
{
pDst[ nAlphaIndex ] = pSrc[ x - nSrcStartX ];
}
else
{
pDst[ nAlphaIndex ] = 0;
}
pDst += 4;
}
pSrc += nSrcStride;
}
else
{
for ( int x = 0; x < BitmapSize.w; x++ )
{
pDst[ nAlphaIndex ] = 0;
pDst += 4;
}
}
}
//for ( int y = nSrcStartY; y < nSrcEndY; y++ )
//{
// for ( int x = nSrcStartX; x < nSrcEndX; x++ )
// {
// pDstTemp[ nAlphaIndex ] = pSrc[ 0 ];
// pDstTemp += 4;
// pSrc += 1;
// }
// pDst += nStride;
// pDstTemp = pDst;
//}
//byte* lc_pBitsFill = m_pBits.GetPointer();
//int nCopyHeight = tMin( ChBitmapSize.h, m_BitmapSize.h - ChBitmapDelta.y );
//int lc_nCopyWidth = tMin( ChBitmapSize.w, m_BitmapSize.w - m_nPaintOffset - ChBitmapDelta.x );
//int lc_src_start_x = (ChBitmapDelta.x < 0) ? (-ChBitmapDelta.x) : 0;
//int lc_src_start_y = (ChBitmapDelta.y < 0) ? (-ChBitmapDelta.y) : 0;
//int lc_dest_start_x = ((ChBitmapDelta.x < 0) ? 0 : ChBitmapDelta.x) + m_nPaintOffset;
//int lc_dest_start_y = ((ChBitmapDelta.y < 0) ? 0 : ChBitmapDelta.y);
//int rowByteSize = m_BitmapSize.w * 4;
//int rowByteSizeCopy = lc_nCopyWidth * 4;
//int dest_offset = (lc_dest_start_x + lc_dest_start_y * m_BitmapSize.w) * 4;
//int dest_offset_x = 0;
//int src_offset = lc_src_start_y * ChBitmapSize.w + lc_src_start_x;
//int src_offset_last = src_offset;
//byte* ptr = nullptr;
//int alphaIndex = 3;
//if ( m_format == UFontBitsFormat::BGRA || m_format == UFontBitsFormat::RGBA )
//{
// alphaIndex = 0;
//}
//for ( int lc_j = lc_src_start_y; lc_j < nCopyHeight; lc_j++ )
//{
// ptr = lc_pBitsFill + dest_offset;
// memset( ptr, 0xff, rowByteSizeCopy );
// for ( int lc_i = lc_src_start_x; lc_i < lc_nCopyWidth; lc_i++ )
// {
// ptr[ alphaIndex ] = pBitsFill[ src_offset ];
// ptr += 4;
// src_offset++;
// }
// dest_offset += rowByteSize;
// src_offset = src_offset_last + ChBitmapSize.w;
// src_offset_last = src_offset;
//}
//m_nPaintOffset += nCharWidth;
//m_nPaintSize += ChBitmapSize.w;
}
void iberbar::CBitsBuffer::PaintChar( const CSize2i& BitmapSize, const uint8* pBytes )
{
int nByteCount = BitmapSize.w * BitmapSize.h * 4;
if ( nByteCount > (int)m_pBits.GetDataSize() )
{
m_pBits.Resize( nByteCount );
}
memset( m_pBits.GetPointer(), 0xff, nByteCount );
int nAlphaIndex = 3;
uint8* pDst = m_pBits.GetPointer();
const uint8* pSrc = pBytes;
//int nSrcStartX = ( ptDelta.x < 0 ) ? 0 : ptDelta.x;
//int nSrcStartY = ( ptDelta.y < 0 ) ? 0 : ptDelta.y;
//int nSrcEndX = nSrcStartX + CopySize.w;
//int nSrcEndY = nSrcStartY + CopySize.h;
int nDstStride = BitmapSize.w * 4;
int nSrcStride = BitmapSize.w;
for ( int y = 0; y < BitmapSize.h; y++ )
{
for ( int x = 0; x < BitmapSize.w; x++ )
{
pDst[nAlphaIndex] = pSrc[0];
pDst += 4;
pSrc += 1;
}
}
}
|
#include "PEImage.h"
#include "exceptions.h"
#include <Windows.h>
#include "DumpPE.h"
using namespace std;
shared_ptr<std::string> PEImage::getImage()
{
return m_image;
}
DWORD PEImage::getImageSize()
{
return m_imageSize;
}
PEImage::PEImage()
{
// Intentionally left empty.
}
std::shared_ptr<PEImage> PEImage::fromMemory(ULONG64 imageBase)
{
ULONG bytesRead = 0;
IMAGE_DOS_HEADER dosHeader;
// Verify DOS magic
ULONG rc = ReadMemory(imageBase, &dosHeader, sizeof(IMAGE_DOS_HEADER), &bytesRead);
if (bytesRead != sizeof(IMAGE_DOS_HEADER) || memcmp(&dosHeader.e_magic, &DOS_SIGNATURE, sizeof(DOS_SIGNATURE))) {
dprintf("Address %p does not contain the beginning of a valid PE image (DOS header signature check failed)\n", imageBase);
throw BadPEException();
}
dprintf("DOS magic found\n");
// Verify PE magic
IMAGE_NT_HEADERS ntHeaders;
rc = ReadMemory(imageBase+dosHeader.e_lfanew, &ntHeaders, sizeof(IMAGE_NT_HEADERS), &bytesRead);
if (bytesRead != sizeof(IMAGE_NT_HEADERS) || memcmp(&ntHeaders.Signature, &PE_SIGNATURE, sizeof(PE_SIGNATURE))) {
dprintf("Address %p does not contain the beginning of a valid PE image (NT header signature check failed)\n", imageBase+dosHeader.e_lfanew);
throw BadPEException();
}
dprintf("PE magic found\n");
std::shared_ptr<PEImage> peImage(new PEImage());
// Get the image size
peImage->m_imageSize = ntHeaders.OptionalHeader.SizeOfImage;
dprintf("SizeOfImage is %u\n", peImage->m_imageSize);
// Read the whole image into memory.
std::shared_ptr<BYTE> rawBuffer(new BYTE[peImage->m_imageSize]);
ReadMemory(imageBase, rawBuffer.get(), peImage->m_imageSize, &bytesRead);
peImage->m_image.reset(new string((char*)rawBuffer.get(), peImage->m_imageSize));
if (bytesRead != peImage->m_imageSize) {
dprintf("ERROR: PE size is %d but only %d bytes were found", peImage->m_imageSize, bytesRead);
throw ReadMemoryException();
}
return peImage;
}
LONG PEImage::getNTHeaderOffset()
{
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)m_image->c_str();
return dosHeader->e_lfanew;
}
DWORD PEImage::getSectionAlignment()
{
std::string ntHeaders = getNTHeaders();
return ((PIMAGE_NT_HEADERS)ntHeaders.c_str())->OptionalHeader.SectionAlignment;
}
DWORD PEImage::getFileAlignment()
{
std::string ntHeaders = getNTHeaders();
return ((PIMAGE_NT_HEADERS)ntHeaders.c_str())->OptionalHeader.FileAlignment;
}
std::string PEImage::getDOSStub()
{
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)m_image->c_str();
return std::string((char*)dosHeader, dosHeader->e_lfanew);
}
std::string PEImage::getNTHeaders()
{
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)m_image->c_str();
PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)dosHeader + dosHeader->e_lfanew);
return std::string((char*)ntHeaders, sizeof(IMAGE_NT_HEADERS));
}
std::string PEImage::getSectionHeaders()
{
PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS)(m_image->c_str() + getNTHeaderOffset());
PIMAGE_SECTION_HEADER sectionHeaders = IMAGE_FIRST_SECTION(ntHeaders);
uint32_t size = ntHeaders->FileHeader.NumberOfSections;
return std::string((char*)sectionHeaders, ntHeaders->FileHeader.NumberOfSections*sizeof(IMAGE_SECTION_HEADER));
}
std::string PEImage::getSections()
{
PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS)(m_image->c_str() + getNTHeaderOffset());
std::string s;
PIMAGE_SECTION_HEADER currentSectionHeader = IMAGE_FIRST_SECTION(ntHeaders);
for (int i = 0; i < ntHeaders->FileHeader.NumberOfSections; i++)
{
LPVOID sectionStartInMemory = (LPVOID)(m_image->c_str() + currentSectionHeader->VirtualAddress);
s += std::string((char*)sectionStartInMemory, currentSectionHeader->SizeOfRawData);
currentSectionHeader++;
}
return s;
}
|
#include <iostream>
using namespace std;
/*
Problema 1.2
Complejidad de tiempo: O(1)
*/
int main() {
int puntos;
cin >> puntos;
//Solo los primeros tres puntos son relevantes
int alturas[3];
for (int i = 0; i < 3; i++) {
cin >> alturas[i];
}
//Calcula la concavidad utilizando la pendiente de las pendientes
float discriminante = alturas[2] - 2 * alturas[1] + alturas[0];
if (discriminante > 0) {
cout << "ARRIBA";
} else if (discriminante < 0) {
cout << "ABAJO";
} else {
cout << "LINEA";
}
//Descarta los demas puntos
for (int i = 3; i < puntos; i++) {
int basura;
cin >> basura;
}
}
|
// ๅจๅคงๅคๆฐ็ๆ
ๅตไธ๏ผๆไปฌๆๆฐ็ปๅๅๆ้็ญๅ่ตทๆฅ๏ผ้คไบsizeof๏ผไปฅๅ้ๅธธ่่จๆ้่ฝ่ฟ่กไฟฎๆน๏ผ่ๆฐ็ปๅๆฏๅธธ้
// &array ไธ&array[0] ๆฏไธๅ็๏ผๅฐฝ็ฎกไปไปฌ็ๅผ็ธ็ญ๏ผไฝๆฏๅจ่ฟ่ก+2่ฟ็ฎ็ๆถๅ๏ผๅ่
ๅ ็ๆฏ2*(sizeof array)๏ผๅ่
ๅ ็ๆฏ2*int(ๅ่ฎพarrayๆฏintๆฐ็ป)
#include <iostream>
int main()
{
using namespace std;
int * p = new int[10]; // psomeๆๅ10ไธชintๅผๅ
ๅญๅไธญ็็ฌฌไธไธชๅ
็ด
for (int i = 0; i < 10; i++) {
p[i] = i;
}
for (int i = 0; i < 10; i++) {
cout << p[i] << " ";
}
delete[] p;
cout << endl;
double wages[3] = { 10000.0, 20000.0, 30000.0 };
short stacks[3] = { 3, 2, 1 };
double *pd = wages;
short *ps = &stacks[0];
for (; pd <= &wages[2]; pd++) {
cout << *pd << " ";
}
cout << endl;
for (; ps <= &stacks[2]; ps++) {
cout << *ps << " ";
}
cout << endl;
cout << "size of wages: " << sizeof wages << endl; // ๆฐ็ป็็ฉบ้ด
cout << "size of pd: " << sizeof pd << endl; // pdๅ ็ๅญ่้ฟๅบฆ
while (cin.get() != 'q')
;
return 0;
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#define INF 1000000000
#define REP(i,n) for(int i=0; i<n; i++)
#define REP_R(i,n,m) for(int i=m; i<n; i++)
#define MAX 100
using namespace std;
int main() {
long long N;
scanf("%lld", &N);
if (N%2==0) {
printf("%lld\n", N);
} else {
printf("%lld\n", N*2);
}
}
|
#ifndef ATTACK_H
#define ATTACK_H
#include "../unit/Unit.h"
class Unit;
class Attack {
protected:
Unit* instance;
public:
Attack(Unit* instance);
virtual ~Attack();
virtual void attack(Unit* enemy);
virtual void counterAttack(Unit* enemy);
};
#endif // ATTACK_H
|
// Created on: 1996-12-26
// Created by: Alexander BRIVIN and Dmitry TARASOV
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Vrml_IndexedLineSet_HeaderFile
#define _Vrml_IndexedLineSet_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <Standard_Transient.hxx>
#include <Standard_OStream.hxx>
class Vrml_IndexedLineSet;
DEFINE_STANDARD_HANDLE(Vrml_IndexedLineSet, Standard_Transient)
//! defines a IndexedLineSet node of VRML specifying geometry shapes.
//! This node represents a 3D shape formed by constructing polylines from vertices
//! located at the current coordinates. IndexedLineSet uses the indices in its coordIndex
//! field to specify the polylines. An index of -1 separates one polyline from the next
//! (thus, a final -1 is optional). the current polyline has ended and the next one begins.
//! Treatment of the current material and normal binding is as follows: The PER_PART binding
//! specifies a material or normal for each segment of the line. The PER_FACE binding
//! specifies a material or normal for each polyline. PER_VERTEX specifies a material or
//! normal for each vertex. The corresponding _INDEXED bindings are the same, but use
//! the materialIndex or normalIndex indices. The DEFAULT material binding is equal
//! to OVERALL. The DEFAULT normal binding is equal to PER_VERTEX_INDEXED;
//! if insufficient normals exist in the state, the lines will be drawn unlit. The same
//! rules for texture coordinate generation as IndexedFaceSet are used.
class Vrml_IndexedLineSet : public Standard_Transient
{
public:
Standard_EXPORT Vrml_IndexedLineSet(const Handle(TColStd_HArray1OfInteger)& aCoordIndex, const Handle(TColStd_HArray1OfInteger)& aMaterialIndex, const Handle(TColStd_HArray1OfInteger)& aNormalIndex, const Handle(TColStd_HArray1OfInteger)& aTextureCoordIndex);
Standard_EXPORT Vrml_IndexedLineSet();
Standard_EXPORT void SetCoordIndex (const Handle(TColStd_HArray1OfInteger)& aCoordIndex);
Standard_EXPORT Handle(TColStd_HArray1OfInteger) CoordIndex() const;
Standard_EXPORT void SetMaterialIndex (const Handle(TColStd_HArray1OfInteger)& aMaterialIndex);
Standard_EXPORT Handle(TColStd_HArray1OfInteger) MaterialIndex() const;
Standard_EXPORT void SetNormalIndex (const Handle(TColStd_HArray1OfInteger)& aNormalIndex);
Standard_EXPORT Handle(TColStd_HArray1OfInteger) NormalIndex() const;
Standard_EXPORT void SetTextureCoordIndex (const Handle(TColStd_HArray1OfInteger)& aTextureCoordIndex);
Standard_EXPORT Handle(TColStd_HArray1OfInteger) TextureCoordIndex() const;
Standard_EXPORT Standard_OStream& Print (Standard_OStream& anOStream) const;
DEFINE_STANDARD_RTTIEXT(Vrml_IndexedLineSet,Standard_Transient)
protected:
private:
Handle(TColStd_HArray1OfInteger) myCoordIndex;
Handle(TColStd_HArray1OfInteger) myMaterialIndex;
Handle(TColStd_HArray1OfInteger) myNormalIndex;
Handle(TColStd_HArray1OfInteger) myTextureCoordIndex;
};
#endif // _Vrml_IndexedLineSet_HeaderFile
|
// Created on: 2004-06-15
// Created by: Sergey ZARITCHNY <szy@opencascade.com>
// Copyright (c) 2004-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BinTools_LocationSet_HeaderFile
#define _BinTools_LocationSet_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <TopLoc_IndexedMapOfLocation.hxx>
#include <Standard_Integer.hxx>
#include <Standard_OStream.hxx>
#include <Standard_IStream.hxx>
class TopLoc_Location;
//! Operator for writing transformation into the stream
Standard_OStream& operator << (Standard_OStream& OS, const gp_Trsf& T);
//! The class LocationSet stores a set of location in
//! a relocatable state.
//!
//! It can be created from Locations.
//!
//! It can create Locations.
class BinTools_LocationSet
{
public:
DEFINE_STANDARD_ALLOC
//! Returns an empty set of locations.
Standard_EXPORT BinTools_LocationSet();
//! Clears the content of the set.
Standard_EXPORT void Clear();
//! Incorporate a new Location in the set and returns
//! its index.
Standard_EXPORT Standard_Integer Add (const TopLoc_Location& L);
//! Returns the location of index <I>.
Standard_EXPORT const TopLoc_Location& Location (const Standard_Integer I) const;
//! Returns the index of <L>.
Standard_EXPORT Standard_Integer Index (const TopLoc_Location& L) const;
//! Returns number of locations.
Standard_EXPORT Standard_Integer NbLocations() const;
//! Writes the content of me on the stream <OS> in a
//! format that can be read back by Read.
Standard_EXPORT void Write (Standard_OStream& OS) const;
//! Reads the content of me from the stream <IS>. me
//! is first cleared.
Standard_EXPORT void Read (Standard_IStream& IS);
protected:
private:
TopLoc_IndexedMapOfLocation myMap;
};
#endif // _BinTools_LocationSet_HeaderFile
|
//
// NTPEventArgs.cpp
//
// $Id: //poco/1.4/Net/src/NTPEventArgs.cpp#1 $
//
// Library: Net
// Package: NTP
// Module: NTPEventArgs
//
// Implementation of NTPEventArgs
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "_Net/NTPEventArgs.h"
#include "_Net/SocketAddress.h"
#include "_Net/DNS.h"
#include "_/Exception.h"
#include "_Net/NetException.h"
using _::IOException;
using _::InvalidArgumentException;
namespace _Net {
NTPEventArgs::NTPEventArgs(const SocketAddress& address):
_address(address), _packet()
{
}
NTPEventArgs::~NTPEventArgs()
{
}
std::string NTPEventArgs::hostName() const
{
try
{
return DNS::resolve(_address.host().toString()).name();
}
catch (HostNotFoundException&)
{
}
catch (NoAddressFoundException&)
{
}
catch (DNSException&)
{
}
catch (IOException&)
{
}
return _address.host().toString();
}
std::string NTPEventArgs::hostAddress() const
{
return _address.host().toString();
}
} //< namespace _Net
|
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
ui->pushButton->setText("speach");
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_pressed()
{
ui->pushButton->setText("release");
m_audio =new Audio;
m_audio->startAudio("D:\\1.pcm");
}
void Widget::on_pushButton_released()
{
m_audio->stopAudio();
ui->pushButton->setText("start shibie");
speech m_speech;
ui->textEdit->setText(m_speech.speechIdentify("D:\\1.pcm"));
ui->pushButton->setText("speach");
}
|
// Copyright 2012 Yandex
#ifndef LTR_LEARNERS_GP_LEARNER_GP_LEARNER_H_
#define LTR_LEARNERS_GP_LEARNER_GP_LEARNER_H_
#include <boost/lexical_cast.hpp>
#include <string>
#include <vector>
#include <functional>
#include "contrib/puppy/Puppy.hpp"
#include "ltr/learners/learner.h"
#include "ltr/learners/gp_learner/gp_primitives.h"
#include "ltr/learners/gp_learner/strategies/population_handler.h"
#include "ltr/learners/gp_learner/strategies/default_selection_strategy.h"
#include "ltr/learners/gp_learner/strategies/default_crossover_strategy.h"
#include "ltr/learners/gp_learner/strategies/default_mutation_standart_strategy.h"
#include "ltr/learners/gp_learner/strategies/default_mutation_swap_strategy.h"
#include "ltr/scorers/gp_scorer.h"
#include "ltr/measures/measure.h"
#include "ltr/measures/reciprocal_rank.h"
#include "ltr/parameters_container/parameters_container.h"
namespace ltr {
namespace gp {
/**
* \brief GPLearner
* Implements genetic programming approach applied to learning to rank.
* \tparam TElement object container of those the dataset consists (it can be
* Object, ObjectPair, ObjectList).
*/
template <typename TElement>
class GPLearner : public BaseLearner<TElement, GPScorer> {
public:
/**
* Constructor creates a GPLearner.
* \param measure shared pointer to the measure that would be maximized on
* a dataset within learning.
* \param parameters the ParametersContainer parameters from which would
* overwrite the default parameters.
*/
explicit GPLearner(typename Measure<TElement>::Ptr measure,
const ParametersContainer& parameters)
: feature_count_(0),
measure_(measure) {
this->setParameters(parameters);
}
/**
* Constructor creates a GPLearner. But leaves p_measure uninitialized.
* \param parameters the ParametersContainer parameters from which would
* overwrite the default parameters.
*/
explicit GPLearner(const ParametersContainer& parameters)
: feature_count_(0) {
this->setParameters(parameters);
}
explicit GPLearner(typename Measure<TElement>::Ptr measure,
int population_size = 10,
int number_of_generations = 3,
int min_init_depth = 2,
int max_init_depth = 5,
double init_grow_probability = 0.5,
int seed = 1)
: feature_count_(0),
measure_(measure),
population_size_(population_size),
number_of_generations_(number_of_generations),
min_init_depth_(min_init_depth),
max_init_depth_(max_init_depth),
init_grow_probability_(init_grow_probability),
seed_(seed) {}
explicit GPLearner(int population_size = 10,
int number_of_generations = 3,
int min_init_depth = 2,
int max_init_depth = 5,
double init_grow_probability = 0.5,
int seed = 1)
: feature_count_(0),
population_size_(population_size),
number_of_generations_(number_of_generations),
min_init_depth_(min_init_depth),
max_init_depth_(max_init_depth),
init_grow_probability_(init_grow_probability),
seed_(seed) {}
/**
* The function sets up default parameters for genetic learning process.
*/
virtual void setDefaultParameters();
/**
* The method checks the correctness of the parameters in the parameters
* container. If one of them is not correct it throws
* std::logical_error(PARAMETER_NAME).
*/
virtual void checkParameters() const;
/**
* The function recreates the context and reinitializes the population.
*/
void reset();
string toString() const;
/**
* The function sets up context and population from the given GPScorer.
* \param scorer GPScorer whose population and context would be set up.
*/
void setInitialScorer(const GPScorer& scorer);
void addPopulationHandler(BasePopulationHandler::Ptr
new_population_handler);
void addGPOperation(BaseGPOperation::Ptr
new_gp_operation);
GET_SET(int, population_size);
GET_SET(int, number_of_generations);
GET_SET(int, min_init_depth);
GET_SET(int, max_init_depth);
GET_SET(double, init_grow_probability);
GET_SET(int, seed);
GET_SET(std::vector<BasePopulationHandler::Ptr>, population_handlers);
GET_SET(std::vector<BaseGPOperation::Ptr>, gp_operations);
private:
virtual void setParametersImpl(const ParametersContainer& parameters);
virtual string getDefaultAlias() const {return "GPLeaner";}
/**
* Method clears and adds primitives to the context.
*/
void initContext();
/**
* Method creates initial population.
*/
void initPopulation();
/**
* \brief This function implements the changes made in the population at each
* algorithm's iteration.
*/
virtual void evaluationStepImpl();
/**
* The implementation of genetic programming optimization approach.
* \param data DataSet on which the measure would be maximized within the
* learning procedure.
*/
void learnImpl(const DataSet<TElement>& data, GPScorer* scorer);
/**
* Method evaluates the population, it sets individ tree fitness to the
* average on the data set metric value.
* @param data data set for calculation of the average metric value
*/
void evaluatePopulation(const DataSet<TElement>& data);
/**
* The number of features, to process dataset with the number of features
* the context_ is constructed for.
*/
int feature_count_;
typename Measure<TElement>::Ptr measure_;
int population_size_;
int number_of_generations_;
int min_init_depth_;
int max_init_depth_;
double init_grow_probability_;
int seed_;
protected:
/**
* The set of Puppy::trees (formulas that represent the optimization space),
* that represent a population within the learning procedure.
*/
Population population_;
/**
* Context that contains all the routine needed to build Puppy::trees within
* the population.
*/
Puppy::Context context_;
/**
* The best Puppy::tree(formula,
* individ) in the population.
*/
Puppy::Tree best_tree_;
std::vector<BasePopulationHandler::Ptr> population_handlers_;
std::vector<BaseGPOperation::Ptr> gp_operations_;
};
// template realizations
template <typename TElement>
void GPLearner<TElement>::setDefaultParameters() {
population_size_ = 10;
number_of_generations_ = 3;
min_init_depth_ = 2;
max_init_depth_ = 5;
init_grow_probability_ = 0.5;
seed_ = 1;
}
template <typename TElement>
void GPLearner<TElement>::checkParameters() const {
CHECK(population_size_ > 0); // NOLINT
CHECK(number_of_generations_ > 0); // NOLINT
CHECK(min_init_depth_ > 0); // NOLINT
CHECK(max_init_depth_ > min_init_depth_ - 1); // NOLINT
CHECK(0.0 <= init_grow_probability_ && init_grow_probability_ <= 1.0); // NOLINT
}
template <typename TElement>
void GPLearner<TElement>::reset() {
this->initContext();
this->initPopulation();
}
template <typename TElement>
string GPLearner<TElement>::toString() const {
std::stringstream str;
std::fixed(str);
str.precision(2);
str << "Genetic programming learner with parameters: ";
str << "population_size = " << population_size_ << ", ";
str << "number_of_generations = " << number_of_generations_ << ", ";
str << "min_init_depth = " << min_init_depth_ << ", ";
str << "max_init_depth = " << max_init_depth_ << ", ";
str << "init_grow_probability = " << init_grow_probability_ << ", ";
str << "seed = " << seed_;
return str.str();
}
template <typename TElement>
void GPLearner<TElement>::setInitialScorer(const GPScorer& scorer) {
best_tree_ = scorer.best_tree_;
context_ = scorer.context_;
feature_count_ = scorer.feature_count_;
}
template <typename TElement>
void GPLearner<TElement>::addPopulationHandler(
BasePopulationHandler::Ptr new_population_handler) {
population_handlers_.push_back(new_population_handler);
}
template <typename TElement>
void GPLearner<TElement>::addGPOperation(
BaseGPOperation::Ptr new_gp_operation) {
gp_operations_.push_back(new_gp_operation);
}
template <typename TElement>
void GPLearner<TElement>::
setParametersImpl(const ParametersContainer& parameters) {
population_size_ = parameters.Get<int>("POPULATION_SIZE");
number_of_generations_ = parameters.Get<int>("NUMBER_OF_GENERATIONS");
min_init_depth_ = parameters.Get<int>("MIN_INIT_DEPTH");
max_init_depth_ = parameters.Get<int>("MAX_INIT_DEPTH");
init_grow_probability_ = parameters.Get<double>("INIT_GROW_PROBABILITY");
seed_ = parameters.Get<int>("SEED");
}
template <typename TElement>
void GPLearner<TElement>::initContext() {
Puppy::Context newContext;
context_= newContext;
context_.mRandom.seed(seed_);
for (int gp_operations_index = 0;
gp_operations_index < (int)gp_operations_.size();
++gp_operations_index) {
context_.insert(gp_operations_[gp_operations_index].get());
}
if (gp_operations_.empty()) {
context_.insert(new Add);
context_.insert(new Subtract);
context_.insert(new Multiply);
context_.insert(new Divide);
}
for (int feature_index = 0;
feature_index < feature_count_;
++feature_index) {
std::string feature_name = "feature[";
feature_name += boost::lexical_cast<string>(feature_index);
feature_name += "]";
context_.insert(new Puppy::TokenT<double>(feature_name));
}
}
template <typename TElement>
void GPLearner<TElement>::initPopulation() {
population_.clear();
population_.resize(population_size_);
Puppy::initializePopulation(population_, context_, init_grow_probability_,
min_init_depth_, max_init_depth_);
}
template <typename TElement>
void GPLearner<TElement>::evaluationStepImpl() {
if (population_handlers_.empty()) {
population_handlers_.push_back(new DefaultSelectionStrategy);
population_handlers_.push_back(new DefaultCrossoverStrategy);
population_handlers_.push_back(new DefaultMutationStandartStrategy);
population_handlers_.push_back(new DefaultMutationSwapStrategy);
}
for (int population_handler_index = 0;
population_handler_index < (int) population_handlers_.size();
++population_handler_index) {
population_handlers_[population_handler_index]->
handlePopulation(population_, context_);
}
}
template <typename TElement>
void GPLearner<TElement>::
learnImpl(const DataSet<TElement>& data, GPScorer* scorer) {
if (data.feature_count() != feature_count_) {
feature_count_ = data.feature_count();
reset();
}
std::cout << "Evaluating data for the first time.\n";
this->evaluatePopulation(data);
std::cout << "The population looks like: \n";
for (int tree_index = 0;
tree_index < (int)population_.size(); ++tree_index) {
using ::operator <<;
std::cout << population_[tree_index] << std::endl;
}
std::cout << "Evolution begins.\n";
for (int generationIdx = 0;
generationIdx < number_of_generations_;
++generationIdx) {
std::cout << "Generation "<< generationIdx << ".\n";
std::cout << "Calling strategy\n";
this->evaluationStepImpl();
std::cout << "Evaluation.\n";
this->evaluatePopulation(data);
int best_tree_index = 0;
for (int tree_index = 1;
tree_index < (int)population_.size(); ++tree_index) {
if (population_[best_tree_index].mFitness <
population_[tree_index].mFitness) {
best_tree_index = tree_index;
}
}
std::cout
<< "The best one is number " << best_tree_index << ".\n";
using ::operator <<;
best_tree_ = population_[best_tree_index];
std::cout << best_tree_ << std::endl;
std::cout << "with fitness " << best_tree_.mFitness << "\n";
}
// \TODO ? rewrite with setters and getters
*scorer = GPScorer(best_tree_, context_, feature_count_);
}
template <typename TElement>
void GPLearner<TElement>::evaluatePopulation(const DataSet<TElement>& data) {
for (int tree_index = 0;
tree_index < (int)population_.size(); ++tree_index) {
if (population_[tree_index].mValid) {
continue;
}
GPScorer gp_scorer(population_[tree_index], context_, feature_count_);
gp_scorer.markDataSet(data);
// This line yields a topic for research. Why so?
//
double measureVal = this->measure_->average(data);
population_[tree_index].mFitness = static_cast<float>(measureVal);
population_[tree_index].mValid = true;
}
}
};
};
#endif // LTR_LEARNERS_GP_LEARNER_GP_LEARNER_H_
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Espen Sand
*/
#ifndef MENUBAR_H
#define MENUBAR_H
#include "popupmenu.h"
#include "modules/pi/OpView.h"
#include "modules/util/simset.h"
#include "modules/widgets/WidgetContainer.h"
#include "platforms/unix/base/x11/x11_callback.h"
#include "platforms/unix/base/x11/x11_windowdecoration.h" // WMButtonSet and MDIButtonSet
#include "platforms/unix/product/x11quick/x11_global_desktop_application.h"
#include "platforms/quix/toolkits/ToolkitLibrary.h"
#include "adjunct/desktop_scope/src/generated/g_scope_desktop_window_manager_interface.h"
#include "adjunct/desktop_scope/src/scope_desktop_window_manager.h"
#include "adjunct/desktop_util/settings/SettingsListener.h"
class OpWindow;
class PopupMenu;
class VisualDevice;
class MenuBar
:public OpInputContext
,public MenuElement
,public OpPaintListener
,public OpMouseListener
,public X11CbObject
,public GlobalKeyEventListener
{
private:
class MenuBarItem : public Link
{
public:
MenuBarItem() : button(NULL), value(0), menu(NULL) { }
~MenuBarItem() { OP_DELETE(menu); }
public:
class MenuBarButton* button;
OpString8 name;
OpString visible_name;
int value;
PopupMenu *menu;
};
struct Controls
{
class MenuBackgroundWidget* background;
OpToolbarMenuButton* menu; // The 'opera' menu button
WMButtonSet* wm_buttonset;
MDIButtonSet* mdi_buttonset;
};
public:
enum DisplayMode
{
ROW_MENU, // Content is displayed as a regular horizontal menu bar
OPERA_MENU // Content is displayed as an 'opera' menu (only one button visible)
};
void SetDisplayMode(DisplayMode mode);
public:
MenuBar();
~MenuBar();
OP_STATUS Init(void *parent_handle, OpWindow* parent_window);
/*
* Cancels any open sub menu and removes all contents
*/
void Reset();
/**
* Load menu bar content from spec file
*/
OP_STATUS Populate();
OP_STATUS AddPopupMenu(const char *name, const uni_char *visible_name, INTPTR value);
// For scope ( watir, automated testing)
OP_STATUS SetQuickMenuInfo(OpScopeDesktopWindowManager_SI::QuickMenuInfo& info);
BOOL GetMenubarButtons(OpScopeDesktopWindowManager_SI::QuickMenuInfo &out);
UINT32 CalculateHeight();
void SetSize(int width, int height);
void SetGeometry(int x, int y, int width, int height);
void Show();
void Hide();
bool IsInside(int x, int y, bool is_global_coordinates);
void Invalidate();
void Show(MenuBarItem* item);
void Activate();
void Deactivate();
UINT32 Height() const { return m_visible ? m_height : 0; }
X11Widget::MoveResizeAction GetAction(const OpPoint& point, UINT32 width, UINT32 height);
X11Widget::MoveResizeAction UpdateCursorShape(const OpPoint& point);
bool IsCaptured() const;
bool IsVisible() const { return m_visible; }
void SetCanMoveResize(bool can_move_resize) { m_can_move_resize = can_move_resize; }
void SetDrawBorder(bool draw_border) { m_draw_border = draw_border; }
void SetBorderColor(UINT32 border_color) { m_border_color = border_color; }
void ShowControls(bool show_wm_buttons, bool show_mdi_buttons);
OpView* GetOpView();
/*
* Implementation of MenuElement
*/
bool IsMenuBar() const { return true; }
void Stop(bool cancel=false);
void CancelSubMenu();
void ShowNext(MenuElement* current, bool next);
bool HandleMouseEvent(int gx, int gy, MouseEvent event, bool confine_to_area);
bool ShowSubmenu(int gx, int gy);
MenuElement* Hide(int gx, int gy) { return 0; }
class PopupMenuComponent* ItemAt(int gx, int gy) { return 0; }
/*
* Implementation of OpPaintListener
*/
void OnPaint(const OpRect &rect, OpView *view);
/*
* Implementation of OpMouseListener
*/
void OnMouseMove(const OpPoint &point, ShiftKeyState shift_state, OpView *view);
void OnMouseDown(MouseButton button, UINT8 nclicks, ShiftKeyState shift_state, OpView *view);
void OnMouseUp(MouseButton button, ShiftKeyState shift_state, OpView *view);
void OnMouseLeave();
BOOL OnMouseWheel(INT32 delta, BOOL vertical, ShiftKeyState shift_state) { return FALSE; }
void OnSetCursor() {}
void OnMouseCaptureRelease() {}
/*
* Implementation of X11CbObject
*/
void HandleCallBack(INTPTR ev);
/**
* Implementation of GlobalKeyEventListener
*/
bool OnGlobalKeyEvent(XEvent *event);
private:
OP_STATUS PopulateMenu(MenuBarItem *m);
MenuBarItem *GetMenuBarItemAt(const OpPoint &p, OpRect *item_dimensions);
void HandleMouseEventInternal(const OpPoint &point, bool was_just_pressed);
void SetLocalFocus(bool on);
private:
Head m_menus;
ToolkitLibrary::MenuBarLayout m_toolkit_layout;
OpRect m_pending_exec_rect;
OpAutoPtr<OpWindow> m_op_window;
OpAutoPtr<OpView> m_op_view;
OpAutoPtr<VisualDevice> m_vis_dev;
OpAutoPtr<WidgetContainer> m_widget_container;
OpAutoPtr<Controls> m_controls;
const int m_corner_size;
const int m_resize_margin;
MenuBarItem* m_active_menu;
UINT32 m_border_color; // Format 0xAABBGGRR
UINT32 m_height;
bool m_visible;
bool m_has_open_menu;
bool m_has_pending_exec;
bool m_holds_focus;
bool m_keep_focus;
bool m_active;
bool m_opened_with_mouse;
bool m_captured;
bool m_can_move_resize;
bool m_draw_border;
};
#endif // MENUBAR_H
|
#include <string>
#include <iostream>
#include <specex_message.h>
#include <specex_pyprior.h>
using namespace std;
int specex::PyPrior::set_priors(specex::PyOptions opts){
map<string,Prior*> priors;
{
int np=int(opts.argurment_priors.size());
if( ! (np%3==0) ) {
cerr << "error in parsing, priors must be of the form 'name value error' (np=" << np << ")" << endl;
return EXIT_FAILURE;
}
try {
for(int i=0;i<np/3;i++) {
string pname=opts.argurment_priors[3*i];
double val=atof(opts.argurment_priors[3*i+1].c_str());
double err=atof(opts.argurment_priors[3*i+2].c_str());
cout << "priors[" << i << "]= " << pname << " " << val << " " << err << endl;
priors[pname]= new GaussianPrior(val,err);
}
}catch(std::exception) {
cerr << "error in parsing arguments of priors" << endl;
cerr << "priors must be of the form 'name value error'" << endl;
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/** @file stdlib_string_common.inl Common string declarations.
This file is included several times by stdlib_string.cpp, to produce
various 'char' and 'uni_char' versions. This file is parameterized
in several ways:
- the HAVE_WHATEVER macros determine whether anything is defined,
for a key 'whatever'
- WHATEVER_NAME is the name of whatever is defined
- CHAR_TYPE is the base type of the first string argument, and
often of the second string argument
- UCHAR_TYPE is the unsigned variant of CHAR_TYPE
- CHAR_UNICODE is defined if the first string argument type is
UTF-16, and undefined if it is ASCII
- CHAR2_TYPE is the base type of the second string argument, for
some functions
- UCHAR2_TYPE is the unsigned variant of CHAR_TYPE
- CHAR2_UNICODE is defined if the second string argument type is
UTF-16, and undefined if it is ASCII
- CHARPARAM_TYPE is the name of the type used to receive character
parameters; for the op_ functions this is 'int' in keeping with
the C standard
IMPLEMENTATION NOTE: I'm using op_tolower() for case conversion here rather
than Unicode::ToLower, since the platform may provide its own op_tolower
functionality.
*/
#ifndef HAVE_STRLEN
size_t STRLEN_NAME(const CHAR_TYPE* s)
{
OP_ASSERT( s != NULL );
const CHAR_TYPE *t = s;
while (*t++ != 0)
;
return t - s - 1;
}
#endif // HAVE_STRLEN
#ifndef HAVE_STRCPY
CHAR_TYPE * STRCPY_NAME(CHAR_TYPE *dest, const CHAR_TYPE *src)
{
// Note, the C Standard requires dest to be non-NULL. It is not known why we
// allow dest to be NULL here, or whether Opera needs it.
OP_ASSERT(dest != NULL && src != NULL);
if (dest == NULL)
return NULL;
CHAR_TYPE *dest0 = dest;
while ((*dest++ = *src++) != 0)
;
return dest0;
}
#endif // HAVE_STRCPY
#ifndef HAVE_STRNCPY
/* PERFORMANCE NOTE: Spec violation: strncpy() should zero-fill the rest of
the string */
CHAR_TYPE * STRNCPY_NAME(CHAR_TYPE *dest, const CHAR_TYPE *src, size_t n)
{
OP_ASSERT( dest != NULL && src != NULL );
CHAR_TYPE *dest0 = dest;
while (n != 0 && *src != 0)
{
*dest++ = *src++;
--n;
}
if (n != 0)
*dest = 0;
return dest0;
}
#endif // HAVE_STRNCPY
#ifndef HAVE_STRLCPY
size_t STRLCPY_NAME(CHAR_TYPE *dest, const CHAR2_TYPE *src, size_t dest_size)
{
size_t srclen = 0;
if (dest_size > 0)
{
dest_size --; // Leave space for nul
while (*src && dest_size)
{
OP_ASSERT(CHAR_TYPE(*src) == *src || !"Unicode-to-ASCII conversion is lossy");
*(dest ++) = CHAR_TYPE(*(src ++));
dest_size --;
srclen ++;
}
// Always nul-terminate
*dest = 0;
}
while (*(src ++))
{
srclen ++;
}
return srclen;
}
#endif // HAVE_STRLCPY
#ifndef HAVE_STRCAT
CHAR_TYPE * STRCAT_NAME(CHAR_TYPE *dest, const CHAR_TYPE *src)
{
OP_ASSERT( dest != NULL && src != NULL );
CHAR_TYPE *dest0 = dest;
while (*dest != 0)
dest++;
while ((*dest++ = *src++) != 0)
;
return dest0;
}
#endif // HAVE_STRCAT
#ifndef HAVE_STRNCAT
CHAR_TYPE * STRNCAT_NAME(CHAR_TYPE *dest, const CHAR_TYPE *src, size_t n)
{
OP_ASSERT( dest != NULL && src != NULL );
CHAR_TYPE *dest0 = dest;
while (*dest != 0)
dest++;
while (n > 0 && *src != 0)
{
*dest++ = *src++;
--n;
}
/* We are required to add a trailing nul, even when n is zero, which
means that the n passed as parameter has to be one less than the
remaining space in dest (C99 7.21.3.2.2) */
*dest = 0;
return dest0;
}
#endif // HAVE_STRNCAT
#ifndef HAVE_STRLCAT
size_t STRLCAT_NAME(CHAR_TYPE * dest, const CHAR_TYPE * src, size_t dest_size)
{
//OP_ASSERT(dest != NULL && src != NULL);
CHAR_TYPE *d = dest;
if (dest_size > 0)
{
while (*dest)
dest++;
if (dest_size > size_t(dest - d + 1))
{
dest_size -= dest - d + 1;
while (*src && dest_size-- > 0)
(*dest++) = (*src++);
*dest = 0;
}
}
const CHAR_TYPE *s = src;
while (*src)
src++;
return dest - d + src - s;
}
#endif // HAVE_STRLCAT
#ifndef HAVE_STRCMP
int STRCMP_NAME(const CHAR_TYPE *s1_0, const CHAR2_TYPE *s2_0)
{
OP_ASSERT( s1_0 != NULL && s2_0 != NULL );
const UCHAR_TYPE *s1 = (const UCHAR_TYPE *)s1_0;
const UCHAR2_TYPE *s2 = (const UCHAR2_TYPE *)s2_0;
while (*s1 && *s1 == *s2)
++s1, ++s2;
return (int)*s1 - (int)*s2;
}
#endif // HAVE_STRCMP
#ifndef HAVE_STRNCMP
int STRNCMP_NAME(const CHAR_TYPE *s1_0, const CHAR2_TYPE *s2_0, size_t n)
{
OP_ASSERT( s1_0 != NULL && s2_0 != NULL );
const UCHAR_TYPE *s1 = (const UCHAR_TYPE *)s1_0;
const UCHAR2_TYPE *s2 = (const UCHAR2_TYPE *)s2_0;
while (n > 0 && *s1 && *s1 == *s2)
++s1, ++s2, --n;
return n > 0 ? (int)*s1 - (int)*s2 : 0;
}
#endif // HAVE_STRNCMP
#ifndef HAVE_STRICMP
int STRICMP_NAME(const CHAR_TYPE *s1_0, const CHAR2_TYPE *s2_0)
{
OP_ASSERT( s1_0 != NULL && s2_0 != NULL );
const UCHAR_TYPE *s1 = (const UCHAR_TYPE *)s1_0;
const UCHAR2_TYPE *s2 = (const UCHAR2_TYPE *)s2_0;
while (*s1 && *s2 && (*s1 == *s2 || op_tolower(*s1) == op_tolower(*s2)))
++s1, ++s2;
return op_tolower(*s1) - op_tolower(*s2);
}
#endif // HAVE_STRICMP
#ifndef HAVE_STRNICMP
int STRNICMP_NAME(const CHAR_TYPE *s1_0, const CHAR2_TYPE *s2_0, size_t n)
{
OP_ASSERT( s1_0 != NULL && s2_0 != NULL );
const UCHAR_TYPE *s1 = (const UCHAR_TYPE *)s1_0;
const UCHAR2_TYPE *s2 = (const UCHAR2_TYPE *)s2_0;
while (n > 0 && *s1 && *s2 && (*s1 == *s2 || op_tolower(*s1) == op_tolower(*s2)))
++s1, ++s2, --n;
return n > 0 ? op_tolower(*s1) - op_tolower(*s2) : 0;
}
#endif // HAVE_STRNICMP
#ifndef HAVE_STRDUP
CHAR_TYPE * STRDUP_NAME(const CHAR_TYPE* s)
{
OP_ASSERT( s != NULL );
#ifdef HAVE_LTH_MALLOC
LTH_MALLOC_SITE(site, MALLOC_TAG_MALLOC|MALLOC_TAG_STRDUP);
CHAR_TYPE *p = reinterpret_cast<CHAR_TYPE *>(internal_malloc((strlib_strlen(s) + 1) * sizeof(CHAR_TYPE), site));
#else
CHAR_TYPE *p = reinterpret_cast<CHAR_TYPE *>(op_malloc((strlib_strlen(s) + 1) * sizeof(CHAR_TYPE)));
#endif
if (p != NULL)
strlib_strcpy(p, s);
return p;
}
#endif // HAVE_STRDUP
#ifndef HAVE_STRCHR
CHAR_TYPE * STRCHR_NAME(const CHAR_TYPE *s, CHARPARAM_TYPE c0)
{
OP_ASSERT( s != NULL );
CHAR_TYPE c = (CHAR_TYPE)c0;
while (*s && *s != c)
++s;
return *s == c ? const_cast<CHAR_TYPE *>(s) : NULL;
}
#endif // HAVE_STRCHR
#ifndef HAVE_STRRCHR
CHAR_TYPE * STRRCHR_NAME(const CHAR_TYPE * s, CHARPARAM_TYPE c0)
{
OP_ASSERT( s != NULL );
CHAR_TYPE c = (CHAR_TYPE)c0;
const CHAR_TYPE * p = NULL;
do
{
if (*s == c)
p = s;
} while (*s++ != 0);
return const_cast<CHAR_TYPE *>(p);
}
#endif // HAVE_STRRCHR
#ifndef HAVE_STRSTR
CHAR_TYPE * STRSTR_NAME(const CHAR_TYPE * haystack, const CHAR2_TYPE * needle0)
{
OP_ASSERT( haystack != NULL && needle0 != NULL );
if (!*needle0)
return (CHAR_TYPE *) haystack;
if (*haystack)
{
const UCHAR2_TYPE *needle = (const UCHAR2_TYPE *)needle0;
do
{
if (*needle == *((UCHAR_TYPE*)haystack))
{
// Continue scanning if we find a match
++ needle;
// Return pointer to beginning of string when we have scanned to
// the end of needle.
if (!*needle)
return (CHAR_TYPE *) haystack - ((const CHAR2_TYPE *) needle - needle0) + 1;
}
else if (needle != (const UCHAR2_TYPE *) needle0)
{
// Else backtrack to the start of the current substring.
haystack -= ((const CHAR2_TYPE *) needle - needle0);
needle = (const UCHAR2_TYPE *) needle0;
}
++ haystack;
} while (*haystack);
}
return NULL;
}
#endif // HAVE_STRSTR
#ifndef HAVE_STRISTR
const CHAR_TYPE *STRISTR_NAME(const CHAR_TYPE * haystack0, const CHAR2_TYPE * needle0)
{
const UCHAR_TYPE *haystack = (UCHAR_TYPE*)haystack0;
const UCHAR2_TYPE *needle = (UCHAR2_TYPE*)needle0;
int h = 0, n, first, i;
int first_caseless;
OP_ASSERT(haystack && needle);
n = *needle;
if (!n)
return haystack0;
// Cache lower-case version of the first character in needle
first = op_tolower(n);
first_caseless = (first == op_toupper(n));
do
{
// Scan until we find the first letter of the needle
if (first_caseless)
{
haystack = (UCHAR_TYPE*) STRCHR_NAME((CHAR_TYPE*)haystack, (CHARPARAM_TYPE)first);
if (!haystack)
return NULL; // Reached end of input
}
else
{
while ((h = *haystack) != 0 && first != op_tolower(h))
++haystack;
if (!h)
return NULL; // Reached end of input
}
// After the first letter, match haystack and needle letter for letter
i = 1;
while ((n = needle[i]) != 0 && (h = haystack[i]) != 0 && op_tolower(h) == op_tolower(n))
++i;
if (!n)
return (CHAR_TYPE*)haystack; // Found a match
if (!h)
return NULL; // Reached end of input
haystack++;
}
while (1);
}
#endif // HAVE_STRISTR
#ifndef HAVE_STRSPN
/** Calculate length of prefix containing only characters from accept. */
size_t STRSPN_NAME(const CHAR_TYPE *string, const CHAR_TYPE *accept)
{
OP_ASSERT( string != NULL && accept != NULL );
int count = 0;
bool found;
while (*string)
{
found = false;
for (const CHAR_TYPE *c = accept; *c && !found; c ++)
{
// Continue if we find a character from accept
if (*c == *string)
found = true;
}
// Return if we didn't find it
if (!found)
return count;
count ++; string ++;
}
return count;
}
#endif // HAVE_STRSPN
#ifndef HAVE_STRCSPN
/** Calculate length of prefix not containing characters from reject. */
size_t STRCSPN_NAME(const CHAR_TYPE *string, const CHAR_TYPE *reject)
{
OP_ASSERT( string != NULL && reject != NULL );
int count = 0;
while (*string)
{
for (const CHAR_TYPE *c = reject; *c; c ++)
{
// Exit if we find a character from reject
if (*c == *string)
return count;
}
count ++; string ++;
}
return count;
}
#endif // HAVE_STRCSPN
#ifndef HAVE_STRPBRK
CHAR_TYPE * STRPBRK_NAME(const CHAR_TYPE *str, const CHAR_TYPE *charset)
{
OP_ASSERT( str != NULL && charset != NULL );
for (; *str; ++str)
for (const CHAR_TYPE* tmp = charset; *tmp; ++tmp)
if (*str == *tmp)
return (CHAR_TYPE *)str;
return NULL;
}
#endif // HAVE_STRPBRK
#ifndef HAVE_CONVERTING_STRDUP
CHAR2_TYPE * CONVERTING_STRDUP_NAME(const CHAR_TYPE *s)
{
if (s == NULL)
return NULL;
CHAR2_TYPE *copy = (CHAR2_TYPE*) op_malloc((strlib_strlen(s) + 1) * sizeof(CHAR2_TYPE));
if (copy == NULL)
return NULL;
CHAR2_TYPE *copyptr = copy;
while (*s)
{
OP_ASSERT(((UCHAR_TYPE) *s) == ((CHAR2_TYPE) *(UCHAR_TYPE *) s) || !"Unicode-to-ASCII conversion is lossy");
*copyptr++ = (CHAR2_TYPE)*(UCHAR_TYPE*)s++;
}
*copyptr = 0;
return copy;
}
#endif // HAVE_CONVERTING_STRDUP
#ifndef HAVE_STR_EQ
BOOL STR_EQ_NAME(const CHAR_TYPE * str1, const CHAR2_TYPE *str2)
{
while (*str1 && *str1 == *(const UCHAR2_TYPE*)str2)
str1++, str2++;
return *str1 == *(const UCHAR2_TYPE*)str2;
}
#endif
#ifndef HAVE_STRREV
/** Reverse a Unicode string */
void STRREV_NAME(CHAR_TYPE *buffer)
{
CHAR_TYPE *end = buffer;
#ifdef CHAR_UNICODE
CHAR_TYPE *str = buffer;
bool have_surrogate = false;
#endif
while (*end)
{
#ifdef CHAR_UNICODE
if (Unicode::IsSurrogate(*end))
have_surrogate = true;
#endif
++end;
}
while (--end > buffer)
{
CHAR_TYPE temp = *end;
*end = *buffer;
*buffer++ = temp;
}
#ifdef CHAR_UNICODE
if (have_surrogate)
{
// Fix up surrogate pairs
while (*str)
{
if (Unicode::IsLowSurrogate(*str) && Unicode::IsHighSurrogate(*(str + 1)))
{
CHAR_TYPE high_surrogate = *(str + 1);
*(str + 1) = *str;
*(str ++) = high_surrogate;
}
++ str;
}
}
#endif
}
#endif // HAVE_STRREV
#ifndef HAVE_STRCASE
void STRUPR_NAME(CHAR_TYPE* buffer)
{
while (*buffer)
{
*buffer = op_toupper(*(UCHAR_TYPE*)buffer);
++buffer;
}
}
void STRLWR_NAME(CHAR_TYPE* buffer)
{
while (*buffer)
{
*buffer = op_tolower(*(UCHAR_TYPE*)buffer);
++buffer;
}
}
#endif // HAVE_STRCASE
|
/* BEGIN LICENSE */
/*****************************************************************************
* SKFind : the SK search engine
* Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr>
* $Id: wordlist.cpp,v 1.55.2.4 2005/02/21 14:22:47 krys Exp $
*
* Authors: Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Alternatively you can contact IDM <skcontact @at@ idm> for other license
* contracts concerning parts of the code owned by IDM.
*
*****************************************************************************/
/* END LICENSE */
#include <skfind/skfind.h>
#include "wordlist.h"
//#define DEBUG_WORDLIST
SK_REFCOUNT_IMPL_DEFAULT(SKWordList)
SK_REFCOUNT_IMPL_IID(SKWordList, SK_SKWORDLIST_IID, SKTextFile)
SKWordList::SKWordList()
{
m_bInitialized = PR_FALSE;
m_bInterrupt = PR_FALSE;
SKEnvir *pEnv = NULL;
SKEnvir::GetEnvir(&pEnv);
char* pcSubRSSorted;
pEnv->GetValue(SKF_FE_WORDLIST_PRESORTED, &pcSubRSSorted);
m_bSubRSSorted =
pcSubRSSorted && atol(pcSubRSSorted);
PR_Free(pcSubRSSorted);
}
SKWordList::~SKWordList()
{
}
SKERR SKWordList::SetFileName(const char *pszFileName,
const char *pszDefaultFileName)
{
SKERR err;
// inherited
err = SKTextFile::SetFileName(pszFileName, pszDefaultFileName);
if (err != noErr)
return err;
// open configuration file
err = SetSimplifierURL("simplifier:unicode:uni_case,uni_comp");
if(err != noErr)
return err;
m_bInitialized = PR_FALSE;
err = ParseConfiguration();
return err;
}
SKERR SKWordList::SetWordRecordSet(SKIRecordSet *pRecordSet)
{
if(!pRecordSet)
return err_failure;
m_pWordRecordSet = pRecordSet;
return m_pWordRecordSet->GetFldCollection(
m_pWordFldCollection.already_AddRefed());
}
SKERR SKWordList::GetWordRecordSet(SKIRecordSet **ppRecordSet)
{
return m_pWordRecordSet.CopyTo(ppRecordSet);
}
SKERR SKWordList::SetLookupRecordSet(SKIRecordSet *pRecordSet,
SKIField *pLookupField,
SKIField *pLookupSubField,
SKIField *pTextTokenField)
{
if(!pRecordSet || !pTextTokenField)
return err_failure;
m_pLookupRecordSet = pRecordSet;
m_pLookupField = pLookupField;
m_pLookupSubField = pLookupSubField;
m_pTextTokenField = pTextTokenField;
return noErr;
}
SKERR SKWordList::GetLookupRecordSet(SKIRecordSet **ppRecordSet,
SKIField **ppLookupField,
SKIField **ppLookupSubField,
SKIField **ppTextTokenField)
{
SKERR err = noErr;
if(ppRecordSet)
err |= m_pLookupRecordSet.CopyTo(ppRecordSet);
if(ppLookupField)
err |= m_pLookupField.CopyTo(ppLookupField);
if(ppLookupSubField)
err |= m_pLookupSubField.CopyTo(ppLookupSubField);
if(ppTextTokenField)
err |= m_pTextTokenField.CopyTo(ppTextTokenField);
return err;
}
SKERR SKWordList::SetRevLookupRecordSet(SKIRecordSet *pRecordSet,
SKIField *pRevLookupField)
{
if(!pRecordSet || !pRevLookupField)
return err_failure;
m_pRevLookupRecordSet = pRecordSet;
m_pRevLookupField = pRevLookupField;
return noErr;
}
SKERR SKWordList::GetRevLookupRecordSet(SKIRecordSet **ppRecordSet,
SKIField **ppRevLookupField)
{
SKERR err = noErr;
if(ppRecordSet)
err |= m_pRevLookupRecordSet.CopyTo(ppRecordSet);
if(ppRevLookupField)
err |= m_pRevLookupField.CopyTo(ppRevLookupField);
return err;
}
SKERR SKWordList::SetCapLookupRecordSet(SKIRecordSet *pRecordSet,
SKIField *pCapLookupField,
SKIField *pCapLookupSubField)
{
if(!pRecordSet || !pCapLookupField || !pCapLookupSubField)
return err_failure;
m_pCapLookupRecordSet = pRecordSet;
m_pCapLookupField = pCapLookupField;
m_pCapLookupSubField = pCapLookupSubField;
return noErr;
}
SKERR SKWordList::GetCapLookupRecordSet(SKIRecordSet **ppRecordSet,
SKIField **ppCapLookupField,
SKIField **ppCapLookupSubField)
{
SKERR err = noErr;
if(ppRecordSet)
err |= m_pCapLookupRecordSet.CopyTo(ppRecordSet);
if(ppCapLookupField)
err |= m_pCapLookupField.CopyTo(ppCapLookupField);
if(ppCapLookupSubField)
err |= m_pCapLookupSubField.CopyTo(ppCapLookupSubField);
return err;
}
SKERR SKWordList::SetRevCapLookupRecordSet(SKIRecordSet *pRecordSet,
SKIField *pRevCapLookupField)
{
if(!pRecordSet || !pRevCapLookupField)
return err_failure;
m_pRevCapLookupRecordSet = pRecordSet;
m_pRevCapLookupField = pRevCapLookupField;
return noErr;
}
SKERR SKWordList::GetRevCapLookupRecordSet(SKIRecordSet **ppRecordSet,
SKIField **ppRevCapLookupField)
{
SKERR err = noErr;
if(ppRecordSet)
err |= m_pRevCapLookupRecordSet.CopyTo(ppRecordSet);
if(ppRevCapLookupField)
err |= m_pRevCapLookupField.CopyTo(ppRevCapLookupField);
return err;
}
SKERR SKWordList::ConfigureItem( char* pszSection, char* pszToken,
char* pszValue)
{
SKERR err;
if((!pszToken) || (!pszSection))
return noErr;
if (!PL_strcmp(pszSection, "WORDTABLE"))
{
if (!PL_strcmp(pszToken, "RSURL"))
{
skPtr<SKIRecordSet> pRS;
SKFactoryGetSubRecordSet(pszValue, pRS, err);
if(err != noErr)
return err;
return SetWordRecordSet(pRS);
}
}
else if (!PL_strcmp(pszSection, "LOOKUPTABLE"))
{
if (!PL_strcmp(pszToken, "RSURL"))
{
SKFactoryGetSubRecordSet(pszValue, m_pLookupRecordSet, err);
if((err != noErr) || m_pWordRecordSet)
return err;
return SetWordRecordSet(m_pLookupRecordSet);
}
else if (!PL_strcmp(pszToken, "FIELD"))
{
if(!m_pLookupRecordSet)
return err_invalid;
skPtr<SKIFldCollection> pCol;
err = m_pLookupRecordSet->GetFldCollection(pCol.already_AddRefed());
if(err != noErr)
return err;
err = pCol->GetField(pszValue,
m_pLookupField.already_AddRefed());
return err;
}
else if (!PL_strcmp(pszToken, "SUBFIELD"))
{
if(!m_pLookupField)
return err_invalid;
skPtr<SKIRecordSet> pRS;
err = m_pLookupField->GetLinkSubRecordSet(pRS.already_AddRefed());
if(err != noErr)
return noErr;
skPtr<SKIFldCollection> pCol;
err = pRS->GetFldCollection(pCol.already_AddRefed());
if(err != noErr)
return err;
err = pCol->GetField(pszValue,
m_pLookupSubField.already_AddRefed());
return err;
}
else if (!PL_strcmp(pszToken, "TEXTTOKENFIELD"))
{
if(!m_pLookupRecordSet)
return err_invalid;
skPtr<SKIFldCollection> pCol;
err = m_pLookupRecordSet->GetFldCollection(pCol.already_AddRefed());
if(err != noErr)
return err;
err = pCol->GetField(pszValue,
m_pTextTokenField.already_AddRefed());
return err;
}
}
else if (!PL_strcmp(pszSection, "REVLOOKUPTABLE"))
{
if (!PL_strcmp(pszToken, "RSURL"))
{
SKERR err;
SKFactoryGetSubRecordSet(pszValue, m_pRevLookupRecordSet, err);
return err;
}
else if (!PL_strcmp(pszToken, "FIELD"))
{
if(!m_pRevLookupRecordSet)
return err_invalid;
skPtr<SKIFldCollection> pCol;
err = m_pRevLookupRecordSet->GetFldCollection(pCol.already_AddRefed());
if(err != noErr)
return err;
err = pCol->GetField(pszValue,
m_pRevLookupField.already_AddRefed());
return err;
}
}
else if (!PL_strcmp(pszSection, "CAPLOOKUPTABLE"))
{
if (!PL_strcmp(pszToken, "RSURL"))
{
SKERR err;
SKFactoryGetSubRecordSet(pszValue, m_pCapLookupRecordSet, err);
return err;
}
else if (!PL_strcmp(pszToken, "SIMPURL"))
return SetSimplifierURL(pszValue);
else if (!PL_strcmp(pszToken, "FIELD"))
{
if(!m_pCapLookupRecordSet)
return err_invalid;
skPtr<SKIFldCollection> pCol;
err = m_pCapLookupRecordSet->GetFldCollection(pCol.already_AddRefed());
if(err != noErr)
return err;
err = pCol->GetField(pszValue,
m_pCapLookupField.already_AddRefed());
return err;
}
else if (!PL_strcmp(pszToken, "SUBFIELD"))
{
if(!m_pCapLookupField)
return err_invalid;
skPtr<SKIRecordSet> pRS;
err = m_pCapLookupField->
GetLinkSubRecordSet(pRS.already_AddRefed());
if(err != noErr)
return err;
skPtr<SKIFldCollection> pCol;
err = pRS->GetFldCollection(pCol.already_AddRefed());
if(err != noErr)
return err;
err = pCol->GetField(pszValue,
m_pCapLookupSubField.already_AddRefed());
return err;
}
}
else if (!PL_strcmp(pszSection, "REVCAPLOOKUPTABLE"))
{
if (!PL_strcmp(pszToken, "RSURL"))
{
SKERR err;
SKFactoryGetSubRecordSet(pszValue, m_pRevCapLookupRecordSet, err);
return err;
}
else if (!PL_strcmp(pszToken, "FIELD"))
{
if(!m_pRevCapLookupRecordSet)
return err_invalid;
skPtr<SKIFldCollection> pCol;
err = m_pRevCapLookupRecordSet
->GetFldCollection(pCol.already_AddRefed());
if(err != noErr)
return err;
err = pCol->GetField(pszValue,
m_pRevCapLookupField.already_AddRefed());
return err;
}
}
return err_not_handled;
}
SKERR SKWordList::GetWords(eSearchMode mode, PRBool bSensitive,
SKIRecordFilter* pFilter, const char* pszLinks,
const char* pszToken, SKCursor** ppCursor)
{
if((mode != MODE_EXACT) && (mode != MODE_BEGIN) && (mode != MODE_END))
return SKError(err_invalid, "[SKWordList::GetWords] Invalid arguments");
if(!m_pWordRecordSet)
return SKError(err_failure, "[SKWordList::GetWords] "
"Word table is missing");
#ifdef DEBUG_WORDLIST
printf("WordList::GetWords(mode=%u, %s, %p, %s, %s)\n",
mode, bSensitive ? "sensitive " : "not sensitive", pFilter,
pszLinks, pszToken);
#endif
// Reset the interrupt process
m_bInterrupt = PR_FALSE;
// if the token is empty and the mode isn't MODE_EXACT then doing a
// sensitive query in MODE_BEGIN produces the same result without
// the huge artillery of skResolveRSLink.
if((!*pszToken) && (mode != MODE_EXACT))
{
bSensitive = PR_TRUE;
mode = MODE_BEGIN;
}
skPtr<SKIRecordSet> pLookupRecordSet;
skPtr<SKIField> pDirectField;
PRUint32 iId1, iId2;
*ppCursor = NULL;
// Check we have the lookup table we're going to use
if((mode == MODE_EXACT) || (mode == MODE_BEGIN))
{
if(bSensitive)
{
if(!m_pLookupRecordSet)
return SKError(err_failure, "[SKWordList::GetWords] "
"Lookup table is missing");
#ifdef DEBUG_WORDLIST
printf("Selecting exact direct table\n");
#endif
pLookupRecordSet = m_pLookupRecordSet;
}
else
{
if(!m_pCapLookupRecordSet)
return SKError(err_failure, "[SKWordList::GetWords] "
"CapLookup table is missing");
pLookupRecordSet = m_pCapLookupRecordSet;
#ifdef DEBUG_WORDLIST
printf("Selecting simplified direct table\n");
#endif
}
}
else
{
if(bSensitive)
{
if(!m_pRevLookupRecordSet)
return SKError(err_failure, "[SKWordList::GetWords] "
"RevLookup table is missing");
pLookupRecordSet = m_pRevLookupRecordSet;
pDirectField = m_pRevLookupField;
#ifdef DEBUG_WORDLIST
printf("Selecting exact reverse table\n");
#endif
}
else
{
if(!m_pRevCapLookupRecordSet)
return SKError(err_failure, "[SKWordList::GetWords] "
"RevCapLookup table is missing");
pLookupRecordSet = m_pRevCapLookupRecordSet;
pDirectField = m_pRevCapLookupField;
#ifdef DEBUG_WORDLIST
printf("Selecting simplified reverse table\n");
#endif
}
}
SKERR err = noErr;
skPtr<SKCursor> pResult;
// First step: token lookup
if(mode == MODE_EXACT)
{
err = pLookupRecordSet->LookupText(pszToken, skflmEXACT, &iId1);
if((err != noErr) && (err != err_notfound))
return err;
if(err == noErr)
iId2 = iId1 + 1;
else
iId2 = iId1 = 0;
}
else if(!*pszToken)
{
iId1 = 0;
err = pLookupRecordSet->GetCount(&iId2);
if(err != noErr)
return err;
}
else
{
char* pszToken2 = PL_strdup(pszToken);
if(mode == MODE_END)
sk_invertString(pszToken2);
#ifdef DEBUG_WORDLIST
printf("Looking up last item before %s\n", pszToken2);
#endif
err = pLookupRecordSet->LookupText(pszToken2, skflmLASTBEFORE, &iId1);
if(err == err_notfound)
{
iId1 = 0;
err = noErr;
}
else if(err != noErr)
{
PL_strfree(pszToken2);
return err;
}
else
{
++iId1;
}
sk_nextString(pszToken2);
#ifdef DEBUG_WORDLIST
printf("Looking up last item before %s\n", pszToken2);
#endif
err = pLookupRecordSet->LookupText(pszToken2, skflmLASTBEFORE, &iId2);
if(err == err_notfound)
{
iId2 = 0;
err = noErr;
}
else if(err != noErr)
{
PL_strfree(pszToken2);
return err;
}
else
{
++iId2;
}
#ifdef DEBUG_WORDLIST
printf("Interval : %u - %u\n", iId1, iId2);
#endif
PL_strfree(pszToken2);
SK_ASSERT(iId1 <= iId2);
}
*pResult.already_AddRefed() = sk_CreateInstance(SKCursor)();
if(!pResult)
return err_memory;
err = pResult->InitStartCount(iId1, iId2 - iId1);
if(err != noErr)
return err;
// reversed -> not reversed
if(pDirectField)
{
#ifdef DEBUG_WORDLIST
printf("Get direct ids\n");
#endif
skPtr<SKCursor> pNewResult;
err = skResolveRSUNum(pResult, pLookupRecordSet, pDirectField,
PR_FALSE, &m_bInterrupt,
pNewResult.already_AddRefed());
if(err != noErr)
return err;
pResult = pNewResult;
}
// Check the interrupt flag
if(m_bInterrupt)
{
m_bInterrupt = PR_FALSE;
return err_interrupted;
}
// simplified -> not simplified
if(!bSensitive)
{
skPtr<SKCursor> pNewResult;
err = skResolveRSLink(pResult, m_pCapLookupRecordSet,
m_pCapLookupField, m_pCapLookupSubField,
PR_FALSE, &m_bInterrupt,
pNewResult.already_AddRefed());
if(err != noErr)
return err;
pResult = pNewResult;
}
// Check the interrupt flag
if(m_bInterrupt)
{
m_bInterrupt = PR_FALSE;
return err_interrupted;
}
// Filtering
if(pFilter)
{
SKCursorFilterRecordWrapper cursorFilter;
err = cursorFilter.SetCursor(pResult);
if(err != noErr)
return err;
err = pFilter->SetRecordSet(m_pLookupRecordSet);
if(err != noErr)
return err;
err = cursorFilter.SetRecordFilter(pFilter, PR_TRUE);
if(err != noErr)
return err;
if(pResult != NULL)
{
err = pResult->Filter(&cursorFilter);
if(err != noErr)
return err;
}
}
// Check the interrupt flag
if(m_bInterrupt)
{
m_bInterrupt = PR_FALSE;
return err_interrupted;
}
// token -> word
if(m_pLookupField)
{
skPtr<SKCursor> pNewResult;
if(m_pLookupSubField)
err = skResolveRSLink(pResult, m_pLookupRecordSet,
m_pLookupField, m_pLookupSubField,
PR_FALSE, &m_bInterrupt,
pNewResult.already_AddRefed());
else
err = skResolveRSUNum(pResult, m_pLookupRecordSet,
m_pLookupField, PR_FALSE,
&m_bInterrupt, pNewResult.already_AddRefed());
if(err != noErr)
return err;
pResult = pNewResult;
}
// Check the interrupt flag
if(m_bInterrupt)
{
m_bInterrupt = PR_FALSE;
return err_interrupted;
}
// Second step: links resolution
skPtr<SKCursor> pNewResult;
err = ResolveLinks(pResult, pszLinks, pNewResult.already_AddRefed());
if(err != noErr)
return err;
m_bInterrupt = PR_FALSE;
return pNewResult.CopyTo(ppCursor);
}
SKERR SKWordList::ResolveLinks(SKCursor* pFrom, const char* pszLinks,
SKCursor** ppTo)
{
pFrom->AddRef();
*ppTo = pFrom;
char* pszLinksCopy = PL_strdup(pszLinks);
if(pszLinks && !pszLinksCopy)
{
(*ppTo)->Release();
*ppTo = NULL;
return SKError(err_failure, "[SKWordList::ResolveLinks] "
"Out of memory");
}
char* pszPointer = pszLinksCopy;
while(pszPointer && (*pszPointer != '\0'))
{
char* pszNext = PL_strchr(pszPointer, '|');
if(pszNext)
*pszNext = '\0';
char* pszCut1 = PL_strchr(pszPointer, ',');
if(!pszCut1)
{
(*ppTo)->Release();
*ppTo = NULL;
PL_strfree(pszLinksCopy);
return SKError(err_invalid, "[SKWordList::ResolveLinks] "
"Invalid link field '%s'", pszLinks);
}
*pszCut1 = '\0';
char* pszCut2 = PL_strchr(pszCut1 + 1, ',');
if(!pszCut2)
{
(*ppTo)->Release();
*ppTo = NULL;
PL_strfree(pszLinksCopy);
return SKError(err_invalid, "[SKWordList::ResolveLinks] "
"Invalid link field '%s'", pszLinks);
}
*pszCut2 = '\0';
skPtr<SKCursor> pTmpCursor;
SKERR err;
if(*(pszCut1 + 1))
{
err = ResolveLink(*ppTo, pszPointer, pszCut1 + 1,
pTmpCursor.already_AddRefed());
}
else
{
err = ResolveUNum(*ppTo, pszPointer,
pTmpCursor.already_AddRefed());
}
if(err != noErr)
{
(*ppTo)->Release();
*ppTo = NULL;
PL_strfree(pszLinksCopy);
return err;
}
// Check the interrupt flag
if(m_bInterrupt)
{
(*ppTo)->Release();
*ppTo = NULL;
PL_strfree(pszLinksCopy);
m_bInterrupt = PR_FALSE;
return err_interrupted;
}
if(pszCut2[1] != '\0')
{
err = pTmpCursor->Merge(*ppTo, skfopOR);
if(err != noErr)
{
(*ppTo)->Release();
*ppTo = NULL;
PL_strfree(pszLinksCopy);
return err;
}
}
(*ppTo)->Release();
pTmpCursor.CopyTo(ppTo);
pszPointer = pszNext;
if(pszPointer)
pszPointer++;
}
PL_strfree(pszLinksCopy);
return noErr;
}
SKERR SKWordList::ResolveLink(SKCursor *pFrom, const char *pszField,
const char *pszSubField, SKCursor **ppTo)
{
SKERR err;
skPtr<SKIField> pField;
err = m_pWordFldCollection->GetField(pszField,
pField.already_AddRefed());
if(err != noErr)
return err;
skPtr<SKIRecordSet> pSubRS;
err = pField->GetLinkSubRecordSet(pSubRS.already_AddRefed());
if(err != noErr)
return err;
skPtr<SKIFldCollection> pSubCol;
err = pSubRS->GetFldCollection(pSubCol.already_AddRefed());
if(err != noErr)
return err;
skPtr<SKIField> pSubField;
err = pSubCol->GetField(pszSubField, pSubField.already_AddRefed());
if(err != noErr)
return err;
return skResolveRSLink(pFrom, m_pWordRecordSet, pField, pSubField,
m_bSubRSSorted, &m_bInterrupt, ppTo);
}
SKERR SKWordList::ResolveUNum(SKCursor *pFrom, const char *pszField,
SKCursor **ppTo)
{
skPtr<SKIField> pField;
SKERR err = m_pWordFldCollection->GetField(pszField,
pField.already_AddRefed());
if(err != noErr)
return err;
return skResolveRSUNum(pFrom, m_pWordRecordSet, pField, PR_FALSE,
&m_bInterrupt, ppTo);
}
SKERR SKWordList::SetSimplifierURL(const char* pcUrl)
{
SKERR err;
SKFactory* pFactory;
err = SKFactory::GetFactory(&pFactory);
SK_ASSERT(err == noErr);
err = pFactory->CreateInstance(pcUrl,
(SKRefCount**) m_pTableSimplifier.already_AddRefed());
return err;
}
void SKWordList::Interrupt()
{
m_bInterrupt = PR_TRUE;
}
|
// ChatClient.cpp : ์ฝ์ ์์ฉ ํ๋ก๊ทธ๋จ์ ๋ํ ์ง์
์ ์ ์ ์ํฉ๋๋ค.
//
#include "stdafx.h"
// ํด๋ผ์ด์ธํธ ํต์ ์ ๋ด๋นํ CTestClientSession ๊ฐ์ฒด
// CClientSession์ ์์๋ฐ์์ ์ฌ์ฉํฉ๋๋ค.
class CTestClientSession : public CClientSession
{
protected:
// ํด๋ผ์ด์ธํธ๊ฐ ์ ์ ์ฑ๊ณต๋์์๋ ํธ์ถ๋๋ ๊ฐ์ํจ์
VOID OnIoConnected(VOID)
{
//std::cout << "IOConnected" << std::endl;
}
// ํด๋ผ์ด์ธํธ๊ฐ ์ ์ ์ข
๋ฃ๋์์๋ ํธ์ถ๋๋ ๊ฐ์ํจ์
VOID OnIoDisconnected(VOID)
{
//std::cout << "IODisconnected" << std::endl;
}
};
unsigned int WINAPI WorkThreadFunc(void* arg)
{
int readLen = 0;
char tempMessage[MAX_BUFFER_LENGTH] = { 0, };
CTestClientSession *pClientSession = (CTestClientSession*)arg;
while (TRUE)
{
DWORD dwProtocol = 0, dwPacketLength = 0;
BYTE Packet[MAX_BUFFER_LENGTH] = { 0, };
if (pClientSession->ReadPacket(dwProtocol, Packet, dwPacketLength))
{
switch (dwProtocol)
{
case PT_SEND_LOGIN:
{
std::cout << "SEND LOGIN" << std::endl;
break;
}
case PT_SEND_GAME_CHAT:
{
READ_PACKET(PT_SEND_GAME_CHAT);
printf("%S : %S\n", Data.strID, Data.strChat);
break;
}
case PT_SEND_MAFIA_CHAT:
{
READ_PACKET(PT_SEND_MAFIA_CHAT);
printf("MAFIA %S : %S\n", Data.strID, Data.strChat);
break;
}
default:
break;
}
}
Sleep(1);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
// Winsock์ ์ฌ์ฉํ๊ธฐ ์ํ DLL ๋ก๋
WSADATA WsaData;
WSAStartup(MAKEWORD(2, 2), &WsaData); // 2.2 ๋ฒ์ ์ ๋ก๋ํฉ๋๋ค.
// ํต์ ๊ฐ์ฒด๋ฅผ ์์ฑํฉ๋๋ค.
CTestClientSession *pClientSession = new CTestClientSession();
if (pClientSession->BeginTcp("127.0.0.1", 8001))
{
WCHAR szUserID[32] = { 0, };
WCHAR szAdress[32] = { 0, };
HANDLE hThread;
DWORD dwThreadID;
hThread = (HANDLE)_beginthreadex(NULL, 0, WorkThreadFunc, (VOID*)pClientSession, 0, (unsigned*)&dwThreadID);
if (hThread == 0) printf("thread error \n");
bool isFirst = false;
while (TRUE)
{
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
char command;
std::cin >> command;
if (command == 'a')
{
WCHAR ID[32];
cout << "Input ID :";
std::wcin >> ID;
if (!pClientSession->WritePacket(PT_REQ_LOGIN, WriteBuffer,
WRITE_PT_REQ_LOGIN(
WriteBuffer,
ID,
_T("anlu2658"))))
std::cout << "Error" << std::endl;
//DWORD dwProtocol = 0, dwPacketLength = 0;
//BYTE Packet[MAX_BUFFER_LENGTH] = { 0, };
//while (TRUE)
// if (pClientSession->ReadPacket(dwProtocol, Packet, dwPacketLength))
// {
// cout << dwProtocol << endl;
// if (dwProtocol == PT_SEND_LOGIN)
// {
// std::cout << "SEND LOGIN" << std::endl;
// break;
// }
// }
}
else if (command == 'b')
{
WCHAR ID[32];
std::wcin >> ID;
if (!pClientSession->WritePacket(PT_REQ_GAME_CHAT, WriteBuffer,
WRITE_PT_REQ_GAME_CHAT
(
WriteBuffer,
ID,
_T("testtest chat")
)
))
std::cout << "Error" << std::endl;
}
else if (command == 'c')
{
if (!pClientSession->WritePacket(PT_REQ_MAFIA_CHAT, WriteBuffer,
0)
)
std::cout << "Error" << std::endl;
}
Sleep(1);
}
}
pClientSession->End();
delete pClientSession;
WSACleanup();
return 0;
}
|
#include <Shaders/Shader.h>
CShader::CShader(GLenum type, const std::string &source) :
_id(glCreateShader(type))
{
compile(source);
}
CShader::~CShader()
{
glDeleteShader(_id);
}
void CShader::compile(const std::string &source)
{
utils::Log(L"Compiling shader...", utils::ELogLevel::Debug);
utils::Log(utils::CFormat(L"Shader source:\n%%") << source, utils::ELogLevel::Debug);
const GLchar *sources[] = { source.c_str() };
const GLint lengths[] = { static_cast<GLint>(source.size()) };
glShaderSource(_id, 1, sources, lengths);
glCompileShader(_id);
check(GL_COMPILE_STATUS);
}
void CShader::check(GLenum status)
{
GLint result = GL_FALSE;
int infoLogLength = 0;
glGetShaderiv(_id, status, &result);
if (result != GL_TRUE) {
glGetShaderiv(_id, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength <= 1) {
return;
}
std::string infoLog(static_cast<size_t>(infoLogLength), 0);
glGetShaderInfoLog(_id, infoLogLength, nullptr, &infoLog[0]);
if ( !infoLog.empty() ) {
throw std::runtime_error( utils::ws2s(utils::CFormat(L"Shader error: %%") << infoLog) );
}
}
utils::checkErrorStatus();
}
|
#include <iostream>
#include "Fraction.h"
using namespace std;
// invariant: denominator is always positive.
// fraction always in lowest terms (simplified).
// Default constructor
Fraction::Fraction(void)
{
numerator = 0;
denominator = 1;
}
// Constructor
Fraction::Fraction(int n, int d)
{
if (d == 0) {
throw new DivideByZeroException();
} else {
numerator = n;
denominator = d;
simplify();
}
}
Fraction::~Fraction(void)
{
}
// Returns the (positive) greatest common divisor of two integers
int Fraction::gcd(int a, int b) const {
if (a < 0) a = -a;
if (b < 0) b = -b;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Simplifies the receiver
void Fraction::simplify(){
int factor = gcd(numerator, denominator);
numerator = numerator / factor;
denominator = denominator / factor;
}
// Overloaded Operators
/* (try to figure out the expressions
* for the result numerator and denominator yourself.
* Only use this to check your work.)
*
* In each case: (num1/den1) op (num2/den2)
*
* PLUS OPERATOR
* result = (num1 * den2 + num2 * den1) / (den1 * den2)
*
* MINUS OPERATOR
* result = (num1 * den2 - num2 * den1) / (den1 * den2)
*
* MULIPLICATION OPERATOR
* result = (num1 * num2) / (den1 * den2)
*
* DIVISION OPERATOR
* result = (num1 * den2) / (den1 * num2)
*/
Fraction Fraction::operator+(const Fraction & f) const{
Fraction result;
result.denominator = f.denominator*denominator;
result.numerator = f.numerator*denominator + numerator*f.denominator;
result.simplify();
return result;
}
Fraction Fraction::operator-(const Fraction & f) const{
Fraction result;
result.denominator = f.denominator*denominator;
result.numerator = - (f.numerator*denominator) + numerator*f.denominator;
result.simplify();
return result;
}
Fraction Fraction::operator*(const Fraction & f) const{
Fraction result;
result.denominator = f.denominator*denominator;
result.numerator = f.numerator*numerator;
result.simplify();
return result;
}
Fraction Fraction::operator / (const Fraction & f) const{
Fraction result;
result.denominator = denominator*f.numerator;
result.numerator = f.denominator*numerator;
result.simplify();
return result;
}
void operator<<(ostream & os, const Fraction & f){
os << f.numerator << "/" << f.denominator;
}
|
//
// MapElement.h
// GetFish
//
// Created by zhusu on 15/2/4.
//
//
#ifndef __GetFish__MapElement__
#define __GetFish__MapElement__
#include "cocos2d.h"
USING_NS_CC;
class MapElement : public CCSprite
{
public:
static MapElement* create(int star,int lev);
virtual bool init(int star,int lev);
MapElement();
virtual ~MapElement();
CCRect getBody() ;
int getLev();
int getStar();
protected:
int _lev;
int _star;
CCSprite* _back;
CCLabelAtlas* _levLabel;
};
#endif /* defined(__GetFish__MapElement__) */
|
// You are given an infix expression S of length N. You need to convert the given expression S to its postfix equivalent using stack.
// Input
// The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
// The first line of each test case contains a single integer N denoting the length of S.
// The second line contains a string S, the infix expression.
// Output
// For each test case print a single line containing the postfix equivalent for the given infix expression.
// Constraints
// 1โคTโค10
// 1โคNโค102
// S contains only uppercase English letters (A...Z), and these characters - (,),+,โ,โ,/,^. S is a valid infix expression.
#include <bits/stdc++.h>
#include <stack>
#include <string>
using namespace std;
int prec(char c ){
if(c=='^')
return 3;
else if(c=='/' || c=='*')
return 2;
else if(c=='+' || c=='-')
return 1;
else
return -1;
}
void infixToPostfix(string s){
stack<char> st;
string result;
for(int i=0;i<s.length();i++){
char c=s[i];
if((c>='A' && c<='Z') || (c>='0' && c<='9'))
result+=c;
else if(c=='(')
st.push('(');
else if(c==')'){
while(st.top() != '('){
result+=st.top();
st.pop();
}
st.pop();
}
else{
while(!st.empty() && prec(s[i]) <= prec(st.top())){
result+=st.top();
st.pop();
}
st.push(c);
}
}
while(!st.empty()){
result += st.top();
st.pop();
}
cout << result << endl;
}
int main() {
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int n;
cin >> n;
string s;
cin >> s;
infixToPostfix(s);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.