blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8c7019e2dbab5a5590bc2f362607b0d3c11c7aa0 | 0d22b8f910e18ab7109fd85366ced187f90ae5f2 | /binaryTree.cpp | ae03f21d17b59212f6b03632c480108386365c30 | [] | no_license | zhaoly12/dataStruct | fe56cd4f0ff376518ecf22d31e5330dacd2aaba2 | 9309bcd2a79c50696347588fe67eaa6c312c817a | refs/heads/master | 2022-12-16T12:47:18.330328 | 2020-09-15T03:55:48 | 2020-09-15T03:55:48 | 279,025,704 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,786 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define elemType char
/*
define a binary tree using linked list
*/
typedef struct node
{
elemType data;
node* LChild, *RChild, *parent;
int LTag, RTag;
} node, *tree;
/*
initialize a binary tree
*/
void init(tree* t)
{
(*t) = NULL;
}
/*
check if a binary tree is an empty tree
*/
void empty(tree t)
{
if(t)
puts("the tree is not empty!");
else
puts("the tree is empty!");
}
/*
return the root of a binary tree
*/
elemType root(tree t)
{
if(!t)
{
puts("empty tree!");
exit(0);
}
return t->data;
}
/*
return the parent of a certain node of a binary tree
*/
// look up a tree upwards
node* parent(node* n)
{
return n->parent;
}
/*
return the left child of a certain node of a binary tree
*/
// look up a tree downwards
node* leftChild(node* n)
{
return n->LChild;
}
/*
return the right child of a certain node of a binary tree
*/
// look up a tree downwards
node* rightChild(node* n)
{
return n->RChild;
}
/*
traverse a binary tree
*/
void traverse(tree t, char mode)
{
if(!t)
{
return;
}
node* left = t->LChild, *right = t->RChild, *p = t;
// traverse in DLR sequence
if(mode == 'h')
{
if(!p)
return;
else
{
printf("%c", p->data);
traverse(left, mode);
traverse(right, mode);
}
}
// traverse in LDR sequence
else if(mode == 'c')
{
if(!p)
return;
else
{
traverse(left, mode);
printf("%c", p->data);
traverse(right, mode);
}
}
// traverse in LRD sequence
else
{
if(!p)
return;
else
{
traverse(left, mode);
traverse(right, mode);
printf("%c", p->data);
}
}
}
// traverse a tree using stack instead of recursion
void traverse2(tree t, char mode)
{
if(!t)
{
puts("empty tree!");
return;
}
node* np = t; // node pointer
node* stack[100]; // the number of the elements in the stack should no less than the number of nodes in the tree
int i;
for(i=0;i<100;i++)
{
stack[i] = NULL;
}
int p = -1; // top of the stack
// traverse in DLR sequence
if(mode == 'h')
{
while(np)
{
printf("%c", np->data);
if(np->RChild)// push
{
p++;
stack[p] = np->RChild;
}
if(np->LChild)
{
np = np->LChild;
}
else
{
if(p>=0)// pop
{
np = stack[p];
p--;
}
else
np = NULL;
}
}
}
// traverse in LDR sequence
else if(mode == 'c')
{
int flag = 0;
while(np)
{
// push
// you can see a node as a child tree
// a child tree can be seen as already distroyed when it has already been traversed once
if(np->RChild && flag == 0)
{
p++;
stack[p] = np->RChild;
}
if(np->LChild && flag == 0)
{
p++;
stack[p] = np;
np = np->LChild;
}
else
{
printf("%c", np->data);
if(p >= 0)
{
// this is an important part
// when you get a node from the stack, it means you go back to some node that you once passed
// if you go back to the right child of a node, it means you will reverse the right child tree now
/* if you go back to a node that is not the right child of the node that you are checking,
it means you have traversed the child tree whose root node is the node that you are checking now */
if(np->RChild != stack[p])
flag = 1;
else
flag = 0;
// pop
np = stack[p];
p--;
}
else
np = NULL;
}
}
}
// traverse in LRD sequence
else
{
int flag = 0;
while(np)
{
// push
// you can see a node as a child tree
// a child tree can be seen as already distroyed when it has already been traversed once
if((np->RChild || np->LChild) && flag == 0)
{
p++;
stack[p] = np;
if(np->RChild && np->LChild)
{
p++;
stack[p] = np->RChild;
np = np->LChild;
}
else if(np->RChild)
np = np->RChild;
else
np = np->LChild;
}
else
{
printf("%c", np->data);
if(p >= 0)
{
// this is an important part
// when you get a node from the stack, it means you go back to some node that you once passed
/*
if the node you get in the stack is the parent node of the node you are checking now,
it means you have already traversed the child tree whose root node is the node you are checking now */
if(np->parent == stack[p])
flag = 1;
else
flag = 0;
// pop
np = stack[p];
p--;
}
else
np = NULL;
}
}
}
}
int leafNum = 0;
/*
count the number of the leaf nodes of a tree
*/
void leafNodes(tree t)
{
if(t)
{
leafNodes(t->LChild);
leafNodes(t->RChild);
if((t->LChild == NULL)&&(t->RChild == NULL))
leafNum++;
}
}
// count leaf nodes version 2
int leafNodes2(tree t)
{
if(!t)
return 0;
if((t->LChild == NULL)&&(t->RChild == NULL))
return 1;
return leafNodes2(t->LChild)+leafNodes2(t->RChild);
}
/*
return the depth of a binary tree
*/
int depth(tree t)
{
if(!t)
return 0;
else
{
int max = depth(t->LChild) > depth(t->RChild) ? depth(t->LChild):depth(t->RChild);
return max+1;
}
}
/*
show a binary tree
*/
// using RDL sequence
void show(tree t, int layer)
{
if(!t)
return;
show(t->RChild, layer+1);
int i;
for(i=1;i<layer;printf(" "),i++);
printf("%c\n", t->data);
show(t->LChild, layer+1);
}
/*
create a binary tree using a list
*/
// this list is a string and '.'means nothing
void create(tree* t, tree parent)
{
char data = getchar();
if(data == '.')
*t = NULL;
else
{
(*t) = (node*)malloc(sizeof(node));
(*t)->data = data;
(*t)->parent = parent;
(*t)->LTag = 0;
(*t)->RTag = 0;
create(&((*t)->LChild), *t);
create(&((*t)->RChild), *t);
}
}
/*
empty a binary tree
*/
void clear(tree* t)
{
(*t) = NULL;
puts("\ntree cleared!");
}
/*
thread a binary tree
*/
// if a node does not have a left child LTag will be set to 1 and its left child pointer will point at its prior node
// if a node does not have a right child RTag will be set to 1 and its right child pointer will point at its next node
void thread(tree t, node** pre, char mode)
{
// thread a tree in DLR sequence
if(mode == 'h')
{
if(t)
{
if(t->LChild == NULL && (*pre) != NULL)
{
t->LTag = 1;
t->LChild = (*pre);
}
if(*pre)
{
if(!(*pre)->RChild)
{
(*pre)->RTag = 1;
(*pre)->RChild = t;
}
}
*pre = t;
printf("->%c", (*pre)->data);
// thread the left child tree
if(t->LTag != 1)
thread(t->LChild, pre, 'h');
// thread the right child tree
if(t->RTag != 1)
thread(t->RChild, pre, 'h');
}
}
// thread a tree in LDR sequence
else if (mode == 'c')
{
if(t)
{
// thread the left child tree
thread(t->LChild, pre, 'c');
if(!t->LChild && (*pre) != NULL)
{
t->LTag = 1;
t->LChild = *pre;
}
if(*pre)
{
if(!(*pre)->RChild)
{
(*pre)->RTag = 1;
(*pre)->RChild = t;
}
}
*pre = t;
printf("->%c", (*pre)->data);
// thread the right child tree
thread(t->RChild, pre, 'c');
}
}
// thread a tree in LRD sequence
else
{
if(t)
{
// thread the left child tree
thread(t->LChild, pre, 't');
// thread the right child tree
thread(t->RChild, pre, 't');
if(t->LChild == NULL && (*pre) != NULL && t->LTag != 1)
{
t->LTag = 1;
t->LChild = *pre;
}
if(*pre)
{
if((*pre)->RChild == NULL && (*pre)->RTag != 1)
{
(*pre)->RTag = 1;
(*pre)->RChild = t;
}
}
*pre = t;
printf("->%c", (*pre)->data);
}
}
}
/*
find the prior node of a node in a threaded binary tree
*/
node* prior(node* n, char mode)
{
node* pre = NULL;
if(n->LTag == 1)
pre = n->LChild;
else
{
// DLR
// the right chid of the rightmost leaf node is NULL in DLR mode
// the left child of the root node is NULL in DLR mode when there is no left child tree
if(mode == 'h')
{
node* p = n->parent;
if(p)
{
if(n == p->LChild || (p->LChild == NULL))
pre = p;
else
{
// this node is the right child and its parent node has a left child
// in this case the prior node is the last node of the left child tree in DLR mode(the rightmost leaf node of the left child tree)
pre = p->LChild;
while((pre->LTag == 0 && pre->LChild) || (pre->RTag == 0 && pre->RChild))
{
if(pre->RChild)
pre = pre->RChild;
else
pre = pre->LChild;
}
}
}
else
pre = NULL;
}
// LDR
// the right chid of the rightmost leaf node is NULL in LDR mode
// the left child of the leftmost leaf node is NULL in LDR mode
else if(mode == 'c')
{
node* p = NULL;
// the most right node of the left child tree is the prior node(here is different from LRD and DLR. the node does not have to be a leaf node!)
if(n->LChild)
for(p=n->LChild;(p->RTag==0 && p->RChild);p=p->RChild);
pre = p;
}
// LRD
// the left child of the leftmost leaf node is NULL in LRD mode
// the right child of the root node is NULL in LRD mode when there is no right child tree
else
{
if(n->RTag == 0 && n->RChild)
pre = n->RChild;
else
pre = n->LChild;
}
}
return pre;
}
/*
find the next node of a node in a threaded binary tree
*/
node* next(node* n, char mode)
{
node* next = NULL;
if(n->RTag == 1)
next = n->RChild;
else
{
// DLR
if(mode == 'h')
{
if(n->LTag == 0 && n->LChild)
next = n->LChild;
else
next = n->RChild;
}
// LDR
else if(mode == 'c')
{
node* p = NULL;
// the most left node of the right child tree is the next node(here is different from LRD and DLR. the node does not have to be a leaf node!)
if(n->RChild)
for(p=n->RChild;(p->LTag==0 && p->LChild);p=p->LChild);
next = p;
}
// LRD
else
{
node* p = n->parent;
if(p)
{
if(n == p->RChild || (p->RChild == NULL))
{
next = p;
}
else
{
// the node is the left child and its parent node has a right child
// the next node is the first node of the right child tree(the leftmost leaf node of the right child tree)
next = p->RChild;
while((next->LChild && next->LTag == 0) || (next->RTag == 0 && next->RChild))
{
if(next->LChild)
next = next->LChild;
else
next = next->RChild;
}
}
}
else
next = NULL;
}
}
return next;
}
// test
int main()
{
tree * t = (tree*)malloc(sizeof(tree));
// initialize a binary tree
init(t);
empty((*t));
//printf("the root node of this tree is %c\n", root((*t)));
// create a binary tree
puts("\nplease input all the nodes of a binary tree");
puts("if you input '.' it means this position is empty");
puts("don't forget that the leaf nodes also have 'childs', which are '.'");
puts("\nnow please input the nodes in sequence:");
create(t, NULL);
fflush(stdin);
empty((*t));
printf("the root node of this tree is %c\n", root((*t)));
int bias = 3;
puts("the tree you have typed in is:");
show((*t), bias);
leafNodes(*t);
printf("\n this tree has %d leaf nodes\n", leafNum);
printf("\n this tree has %d leaf nodes and its depth is %d\n", leafNodes2(*t), depth(*t));
// traverse a binary tree
puts("traverse this tree in DLR sequence:");
traverse((*t), 'h');
printf("\n");
traverse2((*t), 'h');
printf("\n");
puts("traverse this tree in LDR sequence:");
traverse((*t), 'c');
printf("\n");
traverse2((*t), 'c');
printf("\n");
puts("traverse this tree in LRD sequence:");
traverse((*t), 't');
printf("\n");
traverse2((*t), 't');
printf("\n");
// thread a binary tree
node** pt = (node**)malloc(sizeof(node*));
*pt = NULL;
node* p = *t;
/*
puts("\nthread the tree in LDR sequence");
printf("LDR");
thread((*t), pt, 'c');
puts("\nfind the next node");
while(next(p,'c'))
{
printf("->%c", p->data);
p = next(p,'c');
}
printf("->%c\n", p->data);
puts("\nfind the prior node");
while(prior(p,'c'))
{
printf("->%c", p->data);
p = prior(p,'c');
}
printf("->%c\n", p->data);
*/
/*
puts("\nthread the tree in DLR sequence");
printf("DLR");
thread((*t), pt, 'h');
puts("\nfind the next node");
while(next(p,'h'))
{
printf("->%c", p->data);
p = next(p,'h');
}
printf("->%c\n", p->data);
puts("\nfind the prior node");
while(prior(p,'h'))
{
printf("->%c", p->data);
p = prior(p,'h');
}
printf("->%c\n", p->data);
*/
puts("\nthread the tree in LRD sequence");
printf("LRD");
thread((*t), pt, 't');
puts("\nfind the prior node");
while(prior(p,'t'))
{
printf("<-%c", p->data);
p = prior(p,'t');
}
printf("<-%c\n", p->data);
puts("\nfind the next node");
while(next(p,'t'))
{
printf("->%c", p->data);
p = next(p,'t');
}
printf("->%c\n", p->data);
// clear this binary tree
clear(t);
system("pause");
return 0;
}
| [
"[email protected]"
] | |
9657d88df2d154c91c8172a1030fe65b6f1c4f95 | 60470ca9f67acf563a80e7d11c4a86bae0f7902c | /src/qt/transactionrecord.h | 70aac176b879c3e7a9ae6891dd376eea9af03fe8 | [
"MIT"
] | permissive | peterfillmore/duckcoin | ad266463fdb649c6c98ae7185f721795cc5456f3 | b2127d7a6654bcb60633230fe3922794ba55bf2f | refs/heads/master | 2021-01-13T09:27:20.526141 | 2016-11-24T05:48:33 | 2016-11-24T05:48:33 | 72,105,032 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,427 | h | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITBREADCRUMB_QT_TRANSACTIONRECORD_H
#define BITBREADCRUMB_QT_TRANSACTIONRECORD_H
#include "amount.h"
#include "uint256.h"
#include <QList>
#include <QString>
class CWallet;
class CWalletTx;
/** UI model for transaction status. The transaction status is the part of a transaction that will change over time.
*/
class TransactionStatus
{
public:
TransactionStatus():
countsForBalance(false), sortKey(""),
matures_in(0), status(Offline), depth(0), open_for(0), cur_num_blocks(-1)
{ }
enum Status {
Confirmed, /**< Have 6 or more confirmations (normal tx) or fully mature (mined tx) **/
/// Normal (sent/received) transactions
OpenUntilDate, /**< Transaction not yet final, waiting for date */
OpenUntilBlock, /**< Transaction not yet final, waiting for block */
Offline, /**< Not sent to any other nodes **/
Unconfirmed, /**< Not yet mined into a block **/
Confirming, /**< Confirmed, but waiting for the recommended number of confirmations **/
Conflicted, /**< Conflicts with other transaction or mempool **/
/// Generated (mined) transactions
Immature, /**< Mined but waiting for maturity */
MaturesWarning, /**< Transaction will likely not mature because no nodes have confirmed */
NotAccepted /**< Mined but not accepted */
};
/// Transaction counts towards available balance
bool countsForBalance;
/// Sorting key based on status
std::string sortKey;
/** @name Generated (mined) transactions
@{*/
int matures_in;
/**@}*/
/** @name Reported status
@{*/
Status status;
qint64 depth;
qint64 open_for; /**< Timestamp if status==OpenUntilDate, otherwise number
of additional blocks that need to be mined before
finalization */
/**@}*/
/** Current number of blocks (to know whether cached status is still valid) */
int cur_num_blocks;
};
/** UI model for a transaction. A core transaction can be represented by multiple UI transactions if it has
multiple outputs.
*/
class TransactionRecord
{
public:
enum Type
{
Other,
Generated,
SendToAddress,
SendToOther,
RecvWithAddress,
RecvFromOther,
SendToSelf
};
/** Number of confirmation recommended for accepting a transaction */
static const int RecommendedNumConfirmations = 6;
TransactionRecord():
hash(), time(0), type(Other), address(""), debit(0), credit(0), idx(0)
{
}
TransactionRecord(uint256 hash, qint64 time):
hash(hash), time(time), type(Other), address(""), debit(0),
credit(0), idx(0)
{
}
TransactionRecord(uint256 hash, qint64 time,
Type type, const std::string &address,
const CAmount& debit, const CAmount& credit):
hash(hash), time(time), type(type), address(address), debit(debit), credit(credit),
idx(0)
{
}
/** Decompose CWallet transaction to model transaction records.
*/
static bool showTransaction(const CWalletTx &wtx);
static QList<TransactionRecord> decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx);
/** @name Immutable transaction attributes
@{*/
uint256 hash;
qint64 time;
Type type;
std::string address;
CAmount debit;
CAmount credit;
/**@}*/
/** Subtransaction index, for sort key */
int idx;
/** Status: can change with block chain update */
TransactionStatus status;
/** Whether the transaction was sent/received with a watch-only address */
bool involvesWatchAddress;
/** Return the unique identifier for this transaction (part) */
QString getTxID() const;
/** Format subtransaction id */
static QString formatSubTxId(const uint256 &hash, int vout);
/** Update status from core wallet tx.
*/
void updateStatus(const CWalletTx &wtx);
/** Return whether a status update is needed.
*/
bool statusUpdateNeeded();
};
#endif // BITBREADCRUMB_QT_TRANSACTIONRECORD_H
| [
"[email protected]"
] | |
ae1ddb3f12872e51aa34b79945de51dd80155f7a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/rsync/gumtree/rsync_repos_function_187_rsync-2.6.0.cpp | cf226ace37aa8e6b26785a8dd47b5bf07fbc677e | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | void log_recv(struct file_struct *file, struct stats *initial_stats)
{
extern int module_id;
extern int am_server;
extern char *log_format;
if (lp_transfer_logging(module_id)) {
log_formatted(FLOG, lp_log_format(module_id), "recv", file, initial_stats);
} else if (log_format && !am_server) {
log_formatted(FINFO, log_format, "recv", file, initial_stats);
}
} | [
"[email protected]"
] | |
d8588154d923b46bd9277bdf31d2aea588c60ffa | 2ba9998af29e55d35b48c5823c0e03ddbd0e9aa5 | /toolkits/graphical_models/factors/sparse_table.hpp | adb74a37b3e633a4320503f65ea3bb23efdf3f88 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | Lab41/graphlab | 7c6ab239ac6ae49ec95260e3ab97be6375da2322 | 09d82e70ae8c4265a487f0d722af7b69825e275b | refs/heads/master | 2021-01-21T01:43:11.174988 | 2013-09-17T00:49:34 | 2013-09-17T00:49:34 | 12,882,141 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,415 | hpp | /**
* Software submitted by
* Systems & Technology Research / Vision Systems Inc., 2013
*
* Approved for public release; distribution is unlimited. [DISTAR Case #21428]
*
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#ifndef SPARSE_TABLE_HPP
#define SPARSE_TABLE_HPP
#include <stdint.h>
#include <assert.h>
#include <iostream>
#include <algorithm>
#include <limits>
#include <vector>
#include <map>
#include <graphlab/serialization/serialization_includes.hpp>
#include <graphlab/logger/assertions.hpp>
#include "table_base.hpp"
#include "dense_table.hpp"
#include "sparse_index.hpp"
namespace graphlab {
/**
* An n-D sparse table up to max_dim dimensions.
* SEE dense_table.hpp for more detail
*
* \author Scott Richardson 10/2012
*/
template<size_t MAX_DIM>
class sparse_table : public table_base<MAX_DIM> {
private:
typedef sparse_table const *const const_ptr;
typedef table_base<MAX_DIM> table_base_t;
typedef discrete_variable variable_t;
typedef discrete_domain<MAX_DIM> domain_t;
typedef discrete_assignment<MAX_DIM> assignment_t;
typedef dense_table<MAX_DIM> dense_table_t;
public:
typedef sparse_index<MAX_DIM> sparse_index_t;
typedef std::vector<std::pair<sparse_index_t, double> > compact_data_t;
private:
typedef std::map<sparse_index_t, double> sparse_data_t;
typedef std::vector<std::pair<const sparse_index_t*, double*> > compact_view_t;
typedef std::vector<std::pair<const sparse_index_t*, const double*> > compact_const_view_t;
public:
/** Construct an empty table */
sparse_table() { }
/** Construct a table over the given domain */
sparse_table(const domain_t& dom) {
set_domain(dom);
}
/** Construct a table over the given domain
* dom : the domain over which the table is defined
* data : a vector of assignment-value pairs. the assignment must
* be sorted according to dom; that is, such that the
* variable with the smallest id iterates fastest
*/
sparse_table(const domain_t& dom, const sparse_data_t& data) {
set_domain(dom);
_dataAtAsg = data;
}
/** Construct a table over the given domain
* vars : a vector of variables that compose the domain
* data : a vector of values serialized such that the first
* variable in vars iterates the fastest
* NOTE this is a convenience constructor. the entries in the
* vector are re-sorted such that the variable with the smallest
* id iterates fastest
*/
sparse_table(const std::vector<variable_t>& vars,
const std::vector<std::pair<size_t, double> >& data)
{
// Construct the arguments (which will remap the domain)
set_domain(domain_t(vars));
// create a faux domain with the size of the dimensions ordered correctly. this
// is essentially a permute operation.
domain_t dom;
for(size_t i=0; i<vars.size(); ++i) {
domain_t d1(variable_t(i, vars[i].size()));
dom += d1;
}
for(size_t i=0; i < data.size(); ++i) {
size_t sparse_idx = data[i].first;
assignment_t asg(dom, sparse_idx);
// permute the assignment
std::vector<size_t> asgs(asg.begin(), asg.end());
assignment_t fast_asg(vars, asgs);
set_logP(fast_asg, data[i].second);
}
}
/** Construct an empty table over the given variable */
sparse_table(const variable_t& args) {
// Construct the arguments (which will remap the domain)
set_domain(domain_t(args));
}
/** Construct an empty table over the given domain */
sparse_table(const std::vector<variable_t>& args) {
// Construct the arguments (which will remap the domain)
set_domain(domain_t(args));
}
// NOTE currently, implementing the (big) three isnt strictly necessary
/** Construct a copy */
sparse_table(const sparse_table& other) :
_args(other._args), _dataAtAsg(other._dataAtAsg) { }
/** Destructor */
virtual ~sparse_table() { }
// REVIEW currently, this isnt necessary
/** Standard assignment operator */
sparse_table& operator=(const sparse_table& other) {
if(this == &other)
return *this;
_args = other._args;
//_dataAtAsg.insert(other._dataAtAsg.begin(), other._dataAtAsg.end());
_dataAtAsg = other._dataAtAsg;
return *this;
}
public:
using table_base_t::APPROX_LOG_ZERO;
// if the data structures between the two tables is equivilent, this is faster
sparse_table& copy_onto(const sparse_table& other) {
if(this == &other)
return *this;
// ensure the domains are the same
DCHECK_EQ(args(), other.args());
// ensure the number of non-zero entries are the same (sanity check)
DCHECK_EQ(_dataAtAsg.size(), other._dataAtAsg.size());
typename sparse_data_t::iterator entry = _dataAtAsg.begin();
typename sparse_data_t::const_iterator end = _dataAtAsg.end();
typename sparse_data_t::const_iterator oentry = other._dataAtAsg.begin();
for( ; entry != end; ++entry, ++oentry) {
// ensure the two assignments are equivilent (std::map should sort them similarly)
DCHECK_EQ(entry->first, oentry->first);
__set_logP(entry->second, oentry->second);
}
// slower
//_dataAtAsg.insert(other._dataAtAsg.begin(), other._dataAtAsg.end());
return *this;
}
/**
* Reset the domain for the table. A domain is defined by a vector of
* variables, and an assignment is defined over that domain.
*/
void set_domain(const domain_t& args) {
_args = args;
_dataAtAsg.clear();
}
const domain_t& domain() const {
return args();
}
bool operator==(const sparse_table& other) {
// are the two domains equal
if(args() != other.args()) return false;
// are there the same number of non-zero elements in the two tables
if(_dataAtAsg.size() != other._dataAtAsg.size()) return false;
typename sparse_data_t::iterator entry = _dataAtAsg.begin();
typename sparse_data_t::const_iterator end = _dataAtAsg.end();
typename sparse_data_t::const_iterator oentry = other._dataAtAsg.begin();
for( ; entry != end; ++entry, ++oentry) {
// is the assignment the same (std::map should sort them similarly)
if(entry->first != oentry->first) return false;
// is the value the same
if(entry->second != oentry->second) return false;
}
return true;
}
bool operator!=(const sparse_table& other) {
return !this->operator==(other);
}
/**
* Return the variable at the given index within the domain. (var(i)
* specifies the dimension associated with the i'th element of an
* assignment, i.e., sparse_index::_asg[i])
*/
virtual const variable_t& var(const size_t index) const {
return args().var(index);
}
/**
* Return the index for a given variable within the domain (as well as
* into sparse_index::_asg[]).
*/
size_t var_location(const variable_t& var) {
return args().var_location(var);
}
/** Return the number of dimensions in the domain */
virtual size_t ndims() const { return args().num_vars(); }
/** Return the number of elements in the domain: prod(size(table)) */
virtual size_t numel() const { return args().size(); }
/** Return the number of non-zero elements in the table */
size_t nnz() const { return _dataAtAsg.size(); }
/** Zero existing entries in the table */
virtual void zero() {
typename sparse_data_t::iterator entry = _dataAtAsg.begin();
typename sparse_data_t::const_iterator end = _dataAtAsg.end();
for( ; entry != end; ++entry) {
entry->second = 0.0;
}
}
private:
inline void remove_logP(const sparse_index_t& asg) {
// the assignment must be within the domain
DASSERT_TRUE(validate_asg(asg));
if(_dataAtAsg.count(asg) == 0) return;
_dataAtAsg.erase(asg);
}
// REVIEW i dont love this method, but it does afford me some bounds checking.
// set_logP(sparse_index_t&, double), seems cleaner, but it has to
// re-lookup the pointer. very slow.
inline void __set_logP(double& tbl_ref, const double& val) {
tbl_ref = std::max(val, APPROX_LOG_ZERO());
}
inline void set_logP(const size_t linear_index, const double& val) {
set_logP(compute_asg(linear_index), val);
}
inline void set_logP(const std::vector<size_t>& asg, const double& val) {
set_logP(sparse_index_t(asg), val);
}
inline void set_logP(const sparse_index_t& asg, const double& val) {
// the assignment must be within the domain
DASSERT_TRUE(validate_asg(asg));
_dataAtAsg[asg] = std::max(val, APPROX_LOG_ZERO());
}
inline double logP(const sparse_index_t& asg) const {
DASSERT_TRUE(validate_asg(asg));
// O(log(n))
typename sparse_data_t::const_iterator val = _dataAtAsg.find(asg);
return val == _dataAtAsg.end() ? APPROX_LOG_ZERO() : val->second;
}
public:
/**
* Add an entry to the sparse table (indexed by its sparse_index).
* Clip values to be greater than or equal to APPROX_LOG_ZERO.
*/
// NOTE the assignment is not removed from the domain if val is APPROX_LOG_ZERO.
// in the future, if these values are removed, it could invalidate any iterator
// over the list of sparse assignments.
inline void set_logP(const assignment_t& asg, const double& val) {
DCHECK_EQ(asg.args(), args());
set_logP(as_sparse_index(asg), val);
}
/** Remove an entry from the sparse table and its corresponding sparse_index) */
inline void remove_logP(const assignment_t& asg) {
DCHECK_EQ(asg.args(), args());
remove_logP(as_sparse_index(asg));
}
// NOTE index is serialized according to the linear indexing of the domain
// TODO can i make this private?
inline double logP(const size_t linear_index) const {
return logP(compute_asg(linear_index));
}
/** Return an entry from the sparse table (indexed by its sparse_index) */
inline double logP(const assignment_t& asg) const {
DCHECK_EQ(asg.args(), args());
return logP(as_sparse_index(asg));
}
//! this(x) /= other(x);
// supports broadcasting of a sub-domain across the full domain
sparse_table& operator/=(const dense_table_t& other) {
return for_each_assignment(other, divides());
return *this;
}
//! this(x) *= other(x);
// supports broadcasting of a sub-domain across the full domain
sparse_table& operator*=(const dense_table_t& other) {
return for_each_assignment(other, multiplies());
}
//! this(x) /= other(x);
// supports broadcasting of a sub-domain across the full domain
sparse_table& operator/=(const sparse_table& other) {
return for_each_assignment(other, divides());
}
//! this(x) *= other(x);
// supports broadcasting of a sub-domain across the full domain
sparse_table& operator*=(const sparse_table& other) {
return for_each_assignment(other, multiplies());
}
private:
struct divides {
inline double operator()(const double& a, const double& b) const {
return a - b;
}
};
struct multiplies {
inline double operator()(const double& a, const double& b) const {
return a + b;
}
};
template<class Func>
inline sparse_table& for_each_assignment(const dense_table_t& other, const Func& f) {
// other domain must be a subset of this domain
DCHECK_EQ((args() + other.args()).num_vars(), args().num_vars());
assignment_t dense_asg(args());
// only need to operate on the the assignments in the sparse table
// (equivalently, the intersection of the sparse and dense assignments)
typename sparse_data_t::iterator it = _dataAtAsg.begin();
typename sparse_data_t::const_iterator end = _dataAtAsg.end();
for( ; it != end; ++it) {
dense_asg.set_index(linear_index(it->first));
//double val = it->second + other.logP(dense_asg));
//it->second = val;
double val = f(it->second, other.logP(dense_asg));
__set_logP(it->second, val);
}
return *this;
}
template<class Func>
sparse_table& for_each_assignment(const sparse_table& other, const Func& f) {
// if the tables span the same domain
if(args() == other.args()) {
DCHECK_EQ(numel(), other.numel());
// NOTE the assignments NOT in the intersection of the two sparse tables
// will be APPROX_LOG_ZERO() and are removed in *this
intersect(other);
typename sparse_data_t::iterator it = _dataAtAsg.begin();
typename sparse_data_t::const_iterator end = _dataAtAsg.end();
typename sparse_data_t::const_iterator other_it = other._dataAtAsg.begin();
for( ; it != end; ++it, ++other_it) {
//double val = it->second + other_it->second);
//it->second = val;
double val = f(it->second, other_it->second);
__set_logP(it->second, val);
}
}
// else, broadcast the sub-domain across the full domain
else {
// other domain must be a subset of this domain
DCHECK_EQ((args() + other.args()).num_vars(), args().num_vars());
compact_view_t compact_view = as_vector_view();
compact_const_view_t other_compact_view = other.as_vector_view();
// define the one-to-one mapping from other's domain to our's
std::vector<size_t> sorting_inds = args().vars_location(other.args());
// reorder the assignments so they can be quickly iterated over
permute(sorting_inds, compact_view);
other.permute(other_compact_view);
// Loop over x
// NOTE the assignments are sorted the same. ie. our assignments share the same
// ordering over the sub-domain spaned by msg as the assignments in msg.
typename compact_const_view_t::const_iterator x_fastasg = other_compact_view.begin();
typename compact_const_view_t::const_iterator x_end = other_compact_view.end();
typename compact_view_t::iterator y_fastasg = compact_view.begin();
typename compact_view_t::const_iterator y_end = compact_view.end();
sparse_index_t yasg;
for( ; x_fastasg < x_end; ++x_fastasg) {
while(y_fastasg != y_end) {
yasg = restrict(*(y_fastasg->first), other.args());
if(*(x_fastasg->first) > yasg) {
++y_fastasg;
continue;
}
else if(*(x_fastasg->first) < yasg) {
++x_fastasg;
break;
}
// else the sub-assignments are equal
else {
//double val = *(y_fastasg->second) + *(x_fastasg->second);
//*(y_fastasg->second) = val;
double val = f(*(y_fastasg->second), *(x_fastasg->second));
__set_logP(*(y_fastasg->second), val);
++y_fastasg;
}
}
}
}
return *this;
}
public:
using table_base_t::MAP;
// since the message is always a unary distribution, this is basically
// >>> max(reshape(permute(
// cavity, circshift(1:ndims(cavity), [1 -msg.dim])), [], msg.numel),
// [], 1)
// or more generally,
// >>> max(reshape(permute(
// cavity, [setdiff(1:ndims(cavity), msg.dims), msg.dims]), [], msg.numel),
// [], 1)
void MAP(dense_table_t& msg) const {
// No need to marginalize
if(args() == msg.args()) {
// Just copy and return
as_dense_table(msg);
return;
}
// the domains cannot be disjoint
DCHECK_GT((args() - msg.args()).num_vars(), 0);
compact_const_view_t fast_view = as_vector_view();
// define the one-to-one mapping from the msg's domain to our's
std::vector<size_t> sorting_inds = args().vars_location(msg.args());
// reorder the assignments so they can be quickly iterated over
permute(sorting_inds, fast_view);
assignment_t yasg(args());
// Loop over x
// NOTE our assignments have been reordered so we can index assignments in
// the two domains consecutively. e.g., if the domain of msg, {v1,v2}, is
// sorted in ascending order, then our assignments must also be sorted in
// assending order over {v1,v2} (although these sub-domains need not be
// be sorted the same.)
typename compact_const_view_t::const_iterator fastyasg = fast_view.begin();
typename compact_const_view_t::const_iterator yend = fast_view.end();
typename domain_t::const_iterator xasg = msg.args().begin();
typename domain_t::const_iterator xend = msg.args().end();
for( ; xasg != xend; ++xasg) {
double maxval = APPROX_LOG_ZERO();
// loop over y
while(fastyasg != yend) {
yasg.set_index(linear_index(*(fastyasg->first)));
if(*xasg != yasg.restrict(xasg->args())) break;
//maxval = std::max(maxval, _dataAtAsg[*fastyasg]);
maxval = std::max(maxval, *(fastyasg->second));
++fastyasg;
}
msg.set_logP( *xasg, maxval );
}
}
void intersect(const sparse_table& other) {
map_left_intersection(_dataAtAsg, other._dataAtAsg);
}
private:
//! Compute the index from the sparse_index
// NOTE index is serialized according to the linear indexing of the domain
size_t linear_index(const sparse_index_t& asg) const {
size_t multiple = 1;
// Clear the index
size_t index = 0;
for(size_t i = 0; i < args().num_vars(); ++i) {
index += multiple * asg.asg_at(i);
// assert(args().var(i).nasgs > 0);
multiple *= args().var(i).size();
}
return index;
}
/** Ensure that an asg falls within the domain */
bool validate_asg(const sparse_index_t& asg) const {
// no index can be larger than the number of labels in that dimension
//return asg <= end_asg();
for(size_t i=0; i<args().num_vars(); ++i)
if(asg.asg_at(i) >= args().var(i).size()) return false;
return true;
}
//! Compute the sparse_index from the index
// NOTE index is serialized according to the linear indexing of the domain
sparse_index_t compute_asg(const size_t index) const {
DCHECK_LT(index, args().size());
sparse_index_t asg(args().num_vars());
size_t quotient = index;
for(size_t i = 0; i < args().num_vars(); ++i) {
asg.set_asg_at(i, quotient % args().var(i).size());
quotient /= args().var(i).size();
// assert(asg.asg_at(i) < args().var(i).size());
}
return asg;
}
public:
//! Compute the largest assignment possible
assignment_t end_asg() {
sparse_index_t asg;
for(size_t i=0; i<args().num_vars(); ++i)
asg.set_asg_at(i, args().var(i).size() - 1);
return as_assignment(asg);
}
//! WARNING this could lead to a very large table
void as_dense_table(dense_table_t& other) const {
other.set_domain(args());
typename domain_t::const_iterator asg = other.args().begin();
typename domain_t::const_iterator end = other.args().end();
for( ; asg != end; ++asg) {
other.set_logP( *asg, logP(*asg) );
}
}
compact_data_t as_vector() const {
compact_data_t compact_data;
compact_data.resize(_dataAtAsg.size());
typename sparse_data_t::const_iterator it = _dataAtAsg.begin();
for(size_t i = 0; i < _dataAtAsg.size(); ++i, ++it) {
compact_data.at(i) = *it;
}
//std::copy(_dataAtAsg.begin(), _dataAtAsg.end(), compact_data.begin());
return compact_data;
}
std::vector<sparse_index_t> keyset() const {
std::vector<sparse_index_t> keys;
typename sparse_data_t::const_iterator it = _dataAtAsg.begin();
typename sparse_data_t::const_iterator end = _dataAtAsg.end();
for( ; it != end; ++it) {
keys.push_back(it->first);
}
return keys;
}
//: virtual methods
public:
virtual sparse_table& deep_copy(const table_base_t& base) {
if(this == &base) return *this;
// ensure we are dealing with a sparse_table
const_ptr other = dynamic_cast<const_ptr>(&base);
if(other == NULL) {
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
*this = *other;
return *this;
}
virtual sparse_table& copy_onto(const table_base_t& base) {
if(this == &base) return *this;
// ensure we are dealing with a sparse_table
const_ptr other = dynamic_cast<const_ptr>(&base);
if(other == NULL) {
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
this->copy_onto(*other);
return *this;
}
/*
// NOTE this operation would turn a sparse table into a dense table
//! this(x) += other(x);
virtual sparse_table& plus_equals(const table_base_t& base) {
// ensure we are dealing with a sparse_table
const_ptr other = dynamic_cast<const_ptr>(&base);
if(other == NULL) {
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
// TODO implement operator
*this += *other;
return *this;
}
*/
//! this(x) *= other(x);
virtual sparse_table& times_equals(const table_base_t& base) {
// ensure we are dealing with a sparse_table
{
sparse_table const* const other =
dynamic_cast<sparse_table const* const>(&base);
if( NULL != other) {
*this *= *other;
return *this;
}
} {
dense_table_t const* const other =
dynamic_cast<dense_table_t const* const>(&base);
if( NULL != other ) {
*this *= *other;
return *this;
}
}
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
//! this(x) /= other(x);
virtual sparse_table& divide_equals(const table_base_t& base) {
// ensure we are dealing with a sparse_table
{
sparse_table const* const other =
dynamic_cast<sparse_table const* const>(&base);
if( NULL != other) {
*this /= *other;
return *this;
}
} {
dense_table_t const* const other =
dynamic_cast<dense_table_t const* const>(&base);
if( NULL != other ) {
*this /= *other;
return *this;
}
}
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
//! (out(x) = this(x)) * other(x);
virtual void times(const table_base_t& base,
table_base_t& out_base) const {
// ensure we are dealing with a sparse_table
sparse_table *const out =
dynamic_cast<sparse_table *const>(&out_base);
if(out == NULL) {
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
*out = *this; // deep copy
out->times_equals(base);
}
//! (out(x) = this(x)) / other(x);
virtual void divide(const table_base_t& base,
table_base_t& out_base) const {
// ensure we are dealing with a sparse_table
sparse_table *const out =
dynamic_cast<sparse_table *const>(&out_base);
if(out == NULL) {
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
*out = *this; // deep copy
out->divide_equals(base);
}
virtual void MAP(table_base_t& base) const {
// ensure we are dealing with a dense_table
dense_table_t* msg = dynamic_cast<dense_table_t*>(&base);
if(msg == NULL) {
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
MAP(*msg);
}
virtual std::ostream& print(std::ostream& out = std::cout) const {
// ensure we are dealing with a sparse_table
const_ptr tbl = dynamic_cast<const_ptr>(this);
if(tbl == NULL) {
std::cout << "ERROR: std::bad_cast" << std::endl;
// REVIEW should probably raise an exception
ASSERT_TRUE(false);
}
out << *tbl;
return out;
}
friend std::ostream& operator<<(std::ostream& out,
const sparse_table<MAX_DIM>& tbl)
{
out << "Sparse Table: " << tbl.args() << "{" << std::endl;
typename sparse_data_t::const_iterator val = tbl._dataAtAsg.begin();
typename sparse_data_t::const_iterator end = tbl._dataAtAsg.end();
for( ; val != end; ++val) {
out << "\tLogP({" << val->first << "}=" << tbl.linear_index(val->first) << ")=" << val->second << std::endl;
}
out << "}";
return out;
}
virtual void load(graphlab::iarchive& arc) {
arc >> _args;
arc >> _dataAtAsg; // uses graphlab serialization operator
}
virtual void save(graphlab::oarchive& arc) const {
arc << _args;
arc << _dataAtAsg; // uses graphlab serialization operator
}
private:
//! Tests whether one sparse_index's i'th index is < another's
struct less_than_by_index {
less_than_by_index(size_t ind) : _sorting_ind(ind) { }
inline bool operator()(
const std::pair<sparse_index_t, double>& a,
const std::pair<sparse_index_t, double>& b) const
{
return less_than(a.first, b.first);
}
inline bool operator()(
const std::pair<const sparse_index_t*, double*>& a,
const std::pair<const sparse_index_t*, double*>& b) const
{
return less_than(*(a.first), *(b.first));
}
inline bool operator()(
const std::pair<const sparse_index_t*, const double*>& a,
const std::pair<const sparse_index_t*, const double*>& b) const
{
return less_than(*(a.first), *(b.first));
}
private:
inline bool less_than(const sparse_index_t& a,
const sparse_index_t& b) const
{
return a.asg_at(_sorting_ind) < b.asg_at(_sorting_ind);
}
size_t _sorting_ind;
};
template<class T>
void permute(T& data) const {
std::vector<size_t> sorting_inds;
for(size_t i=0; i<args().num_vars(); ++i)
sorting_inds.push_back(i);
permute(sorting_inds, data);
}
template<class T>
void permute( const size_t sorting_ind, T& data ) const {
std::vector<size_t> sorting_inds;
sorting_inds.push_back(sorting_ind);
permute(sorting_inds, data);
}
// REVIEW i might be able to copy _dataAtAsg and sort it with a new predicate
template<class T>
void permute( const std::vector<size_t>& sorting_inds, T& data ) const {
std::vector<size_t>::const_reverse_iterator s = sorting_inds.rbegin();
std::vector<size_t>::const_reverse_iterator rend = sorting_inds.rend();
for( ; s != rend; ++s) {
DCHECK_LT(*s, args().num_vars());
std::stable_sort(data.begin(), data.end(), less_than_by_index(*s));
}
}
//! Restrict the sparse_index to a sparse_index over the subdomain
sparse_index_t restrict(const sparse_index_t& asg,
const domain_t& sub_domain) const
{
sparse_index_t other_asg(sub_domain.num_vars());
size_t index = 0;
// Map the variables
for(size_t i = 0; i < args().num_vars() &&
index < sub_domain.num_vars(); ++i) {
if(sub_domain.var(index) == args().var(i)) {
other_asg.set_asg_at(index, asg.asg_at(i));
index++;
}
}
DCHECK_EQ(index, sub_domain.num_vars());
return other_asg;
} // end of restrict
// O(n)
// from http://stackoverflow.com/questions/3772664/intersection-of-two-stl-maps
// and http://stackoverflow.com/questions/1773526/in-place-c-set-intersection
// REVIEW is there any problem with invalidated iterators?
template<typename KeyType, typename LeftValue, typename RightValue>
void map_left_intersection(
std::map<KeyType, LeftValue>& left,
const std::map<KeyType, RightValue>& right) const
{
typename std::map<KeyType, LeftValue>::iterator il = left.begin();
typename std::map<KeyType, LeftValue>::iterator l_end = left.end();
typename std::map<KeyType, RightValue>::const_iterator ir = right.begin();
typename std::map<KeyType, RightValue>::const_iterator r_end = right.end();
while (il != l_end && ir != r_end) {
if (il->first < ir->first) {
left.erase(il);
++il;
}
else if (ir->first < il->first) {
++ir;
}
else {
++il;
++ir;
}
}
left.erase(il, l_end);
}
compact_view_t as_vector_view() {
compact_view_t compact_view;
compact_view.resize(_dataAtAsg.size());
typename sparse_data_t::iterator it = _dataAtAsg.begin();
for(size_t i = 0; i < _dataAtAsg.size(); ++i, ++it) {
compact_view.at(i) = std::make_pair(&(it->first), &(it->second));
}
//std::copy(_dataAtAsg.begin(), _dataAtAsg.end(), compact_view.begin());
return compact_view;
}
compact_const_view_t as_vector_view() const {
compact_const_view_t compact_view;
compact_view.resize(_dataAtAsg.size());
typename sparse_data_t::const_iterator it = _dataAtAsg.begin();
for(size_t i = 0; i < _dataAtAsg.size(); ++i, ++it) {
compact_view.at(i) = std::make_pair(&(it->first), &(it->second));
}
//std::copy(_dataAtAsg.begin(), _dataAtAsg.end(), compact_view.begin());
return compact_view;
}
private:
inline const domain_t& args() const { return _args; }
inline assignment_t as_assignment(const sparse_index_t &asg) const {
std::vector<size_t> asgs(asg.begin(), asg.end());
return assignment_t(args(), asgs);
}
inline sparse_index_t as_sparse_index(const assignment_t &asg) const {
std::vector<size_t> asgs(asg.begin(), asg.end());
return sparse_index_t(asgs);
}
private:
//! The indicies in an assignment are mapped (one-to-one and in-order) to the
// variables in a domain.
domain_t _args;
//! Map between the sparse assignment in the domain and its value. Sorted by
// assignment.
sparse_data_t _dataAtAsg;
};
} // end of namespace graphlab
#endif // SPARSE_TABLE_HPP
| [
"[email protected]"
] | |
d959153edfa9b8e2bf892a4d725186c00c5b2636 | 03ad1b957132959e7fac4a8da46135d9c1a4be15 | /PAT/PATB/1050.cpp | b29c63c7cce6cb72575329083709ca96ef43d473 | [] | no_license | nopnewbie/OJExercise | 7276125d6ba69b8249845a7fa88489c57bb33f51 | 7f99619e1bbe056ea63a0d0e993c9afe5ac94bec | refs/heads/master | 2021-01-22T05:20:37.551780 | 2017-05-12T15:54:09 | 2017-05-12T15:54:09 | 81,650,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | /*
PAT(B):1050. 螺旋矩阵(25)
Date: 2016年1月30日 10:52:46
*/
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1e4 ;
int a[maxn + 10][110];
int num[maxn + 10];
int m, n, N;
int main()
{
//#define LOCAL
#ifdef LOCAL
#define cin fin
ifstream fin("F:\\input.txt");
freopen("F:\\input.txt", "r", stdin);
#endif
memset(a, 0, sizeof(a));
cin >> N;
for( int i = 1; i * i <= N; ++i ) if( !(N % i) ) n = i;
m = N / n; //N可能是素数,所以m可能等于N.此时数组a要有至少N+1行
for( int i = 0; i < N; ++i ) scanf("%d", num + i);
sort(num, num + N, greater<int>());
a[1][1] = num[0];
for( int cnt = 0, x = 1, y = 1; cnt < N - 1; )
{
while( cnt < N && y + 1 <= n && !a[x][y + 1]) a[x][++y] = num[++cnt];
while( cnt < N && x + 1 <= m && !a[x + 1][y]) a[++x][y] = num[++cnt];
while( cnt < N && 1 < y && !a[x][y - 1]) a[x][--y] = num[++cnt];
while( cnt < N && 1 < x && !a[x - 1][y]) a[--x][y] = num[++cnt];
}
for( int i = 1; i <= m; ++i )
{
printf("%d", a[i][1]);
for( int j = 2; j <= n; ++j ) printf(" %d", a[i][j]);
putchar('\n');
}
return 0;
} | [
"[email protected]"
] | |
ad1fa4cd43eb1bcc8312744311d3122986e3aca0 | 5ba28aadaea3160a4c2a16bf423cc90ec063ce05 | /PhysicsTools/Heppy/interface/PATTauDiscriminationByMVAIsolationRun2FWlite.h | 1d03bf465be36a51a9d4a566fab3fdfeba920bc9 | [
"Apache-2.0"
] | permissive | CERN-PH-CMG/cmg-cmssw | 0645db4cb5878f8c527417b8ee809468d7a72923 | ec18c38ac0bb252fec58c92df03578bba36c3e1f | refs/heads/heppy_94X_dev | 2020-04-03T20:23:11.038409 | 2019-06-22T11:06:03 | 2019-06-22T11:06:03 | 13,088,143 | 13 | 201 | null | 2019-07-03T13:58:44 | 2013-09-25T08:23:20 | C++ | UTF-8 | C++ | false | false | 1,454 | h | #ifndef _heppy_PATTauDiscriminationByMVAIsolationRun2FWlite_h
#define _heppy_PATTauDiscriminationByMVAIsolationRun2FWlite_h
#include "CondFormats/EgammaObjects/interface/GBRForest.h"
#include "DataFormats/PatCandidates/interface/Tau.h"
namespace heppy {
class PATTauDiscriminationByMVAIsolationRun2FWlite {
public:
PATTauDiscriminationByMVAIsolationRun2FWlite() : mvaReader_(nullptr) {}
PATTauDiscriminationByMVAIsolationRun2FWlite(const std::string & fileName, const std::string & mvaName, const std::string &mvaKind) ;
~PATTauDiscriminationByMVAIsolationRun2FWlite();
PATTauDiscriminationByMVAIsolationRun2FWlite(const PATTauDiscriminationByMVAIsolationRun2FWlite & other) = delete;
PATTauDiscriminationByMVAIsolationRun2FWlite & operator=(const PATTauDiscriminationByMVAIsolationRun2FWlite & other) = delete;
float operator()(const pat::Tau& tau) const ;
private:
const GBRForest* mvaReader_;
enum { kOldDMwoLT, kOldDMwLT, kNewDMwoLT, kNewDMwLT, kDBoldDMwLT, kDBnewDMwLT, kPWoldDMwLT, kPWnewDMwLT, kDBoldDMwLTwGJ, kDBnewDMwLTwGJ };
int mvaOpt_;
float* mvaInput_;
std::string chargedIsoPtSums_;
std::string neutralIsoPtSums_;
std::string puCorrPtSums_;
std::string photonPtSumOutsideSignalCone_;
std::string footprintCorrection_;
};
}
#endif
| [
"[email protected]"
] | |
b8dbb8d63c8a7b8d1d47d83894b5f0750bcaa682 | fe3de171c8e7731c18ca68bb6d73486566449f7b | /RenderComponent.cpp | 6ba99dae239067ed5d57dfcc208eaf35e7039400 | [] | no_license | TD6370/DemoGL | b92f3cba03bdfe3b3bfafcdad31d2e4e052e6ccf | c93e2f00eda83dd7eb0b6c89b5e879b93fc81e11 | refs/heads/master | 2023-08-13T20:00:19.675614 | 2021-10-09T00:18:41 | 2021-10-09T00:18:41 | 298,083,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29 | cpp | #include "RenderComponent.h"
| [
"[email protected]"
] | |
a164b9238a33fa0c37aa34c85165ad7b1060311b | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/drivers/wdm/capture/mini/bt848/pscolspc.cpp | 3b6c3c3a307ad232848404f0fa195f24a48aec1d | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 1,525 | cpp | // $Header: G:/SwDev/WDM/Video/bt848/rcs/Pscolspc.cpp 1.4 1998/04/29 22:43:35 tomz Exp $
extern "C" {
#ifndef _STREAM_H
#include "strmini.h"
#endif
}
#include "pscolspc.h"
/* Method: PsColorSpace::SetColorFormat
* Purpose: Sets BtPisces color space converter to the given color
* Input: eaColor: enum of type ColFmt
* Output: None
* Note: No error checking is done ( enum is checked by the compiler during compile
* The function writes to the XXXX register
*/
BOOL VerifyColorFormat( ColFmt val )
{
// [WRK] - use constants here for valid formats
switch( val ) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0xe:
return( TRUE );
default:
DebugOut((0, "Caught bad write to ColorFormat (0x%x)\n", val));
return( FALSE );
}
}
void PsColorSpace::SetColorFormat( ColFmt eColor )
{
// save for later use...
ColorSpace::SetColorFormat( eColor );
ByteSwap_ = 0;
switch ( eColor ) {
case CF_YUV9:
eColor = CF_PL_411;
break;
case CF_YUV12:
case CF_I420:
eColor = CF_PL_422;
break;
case CF_UYVY:
eColor = CF_YUY2;
ByteSwap_ = 1;
break;
}
// set the hardware
if ( VerifyColorFormat(eColor) ) {
Format_ = eColor;
} else {
Format_ = 7;
DebugOut((0, "Forcing invalid color format to 0x%x\n", Format_));
}
}
| [
"[email protected]"
] | |
12b7f66462dd62803b205457f1dc60436ccf3640 | bb8f0401cd49d87bfdde0bb397720e8733715a7b | /src/BinaryTreePostorderTraversal/BinaryTreePostorderTraversal.cpp | c0973c745c72d02008fc51838fe0a9ec265b68a4 | [] | no_license | yezhangxiang/LeetCode | 62351731b4985b621908db44c8afbf71f20df738 | 6ce92b1daeeb12977de2f5b9e107c153d627cc24 | refs/heads/master | 2016-09-05T22:48:55.483822 | 2015-05-25T15:10:35 | 2015-05-25T15:10:35 | 26,020,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 715 | cpp | #include <iostream>
#include <vector>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
recursion(ans, root);
return ans;
}
private:
void recursion(vector<int> &order, TreeNode*root)
{
if (root)
{
recursion(order, root->left);
recursion(order, root->right);
order.push_back(root->val);
}
}
};
int main()
{
} | [
"[email protected]"
] | |
40344c4c3df5e6919281799994b4b18ecfa0d73e | 698861e2598da34da2229bc5b81d878680017b9c | /kirikiri/src/kirikiri/cxdec/nidaimeTrial_cxdec.cpp | 193aba5d0c5dbb8fc3d249f0265a03bbc08d3f96 | [] | no_license | Kerisa/ExtractGames | 399a45da181a7f85788aef5525aad81d4ddf2c4a | b98e884c2cefb319159fc75a22e2b7690a54bbc1 | refs/heads/master | 2023-08-18T19:11:19.055478 | 2023-08-04T16:14:44 | 2023-08-04T16:14:44 | 38,112,558 | 70 | 18 | null | null | null | null | UTF-8 | C++ | false | false | 35,255 | cpp | #include "cxdec.h"
static int xcode_building_stage0(struct cxdec_xcode_status *xcode, int stage);
static int xcode_building_stage1(struct cxdec_xcode_status *xcode, int stage);
static BYTE EncryptionControlBlock[4096] = {
0x20, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74,
0x69, 0x6f, 0x6e, 0x20, 0x63, 0x6f, 0x6e, 0x74,
0x72, 0x6f, 0x6c, 0x20, 0x62, 0x6c, 0x6f, 0x63,
0x6b, 0x20, 0x2d, 0x2d, 0x20, 0x53, 0x74, 0x61,
0x74, 0x69, 0x63, 0x61, 0x6c, 0x6c, 0x79, 0x20,
0x6f, 0x72, 0x20, 0x64, 0x79, 0x6e, 0x61, 0x6d,
0x69, 0x63, 0x61, 0x6c, 0x6c, 0x79, 0x2c, 0x20,
0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6c, 0x79,
0x20, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x64, 0x69,
0x72, 0x65, 0x63, 0x74, 0x6c, 0x79, 0x2c, 0x20,
0x75, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
0x61, 0x6d, 0x20, 0x61, 0x6e, 0x64, 0x2f, 0x6f,
0x72, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x20,
0x66, 0x72, 0x6f, 0x6d, 0x20, 0x6f, 0x74, 0x68,
0x65, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
0x61, 0x6d, 0x73, 0x20, 0x77, 0x69, 0x6c, 0x6c,
0x20, 0x62, 0x65, 0x20, 0x69, 0x6c, 0x6c, 0x65,
0x67, 0x61, 0x6c, 0x20, 0x62, 0x79, 0x20, 0x74,
0x68, 0x65, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e,
0x73, 0x65, 0x20, 0x61, 0x67, 0x72, 0x65, 0x65,
0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x20, 0x82, 0xb1,
0x82, 0xcc, 0x83, 0x76, 0x83, 0x8d, 0x83, 0x4f,
0x83, 0x89, 0x83, 0x80, 0x82, 0xe2, 0x83, 0x75,
0x83, 0x8d, 0x83, 0x62, 0x83, 0x4e, 0x82, 0xf0,
0x81, 0x41, 0x90, 0xc3, 0x93, 0x49, 0x82, 0xc5,
0x82, 0xa0, 0x82, 0xea, 0x93, 0xae, 0x93, 0x49,
0x82, 0xc5, 0x82, 0xa0, 0x82, 0xea, 0x81, 0x41,
0x92, 0xbc, 0x90, 0xda, 0x93, 0x49, 0x82, 0xc5,
0x82, 0xa0, 0x82, 0xea, 0x8a, 0xd4, 0x90, 0xda,
0x93, 0x49, 0x82, 0xc5, 0x82, 0xa0, 0x82, 0xea,
0x81, 0x41, 0x91, 0xbc, 0x82, 0xcc, 0x83, 0x76,
0x83, 0x8d, 0x83, 0x4f, 0x83, 0x89, 0x83, 0x80,
0x82, 0xa9, 0x82, 0xe7, 0x97, 0x70, 0x82, 0xa2,
0x82, 0xe9, 0x82, 0xb1, 0x82, 0xc6, 0x82, 0xcd,
0x83, 0x89, 0x83, 0x43, 0x83, 0x5a, 0x83, 0x93,
0x83, 0x58, 0x82, 0xc9, 0x82, 0xe6, 0x82, 0xe8,
0x8b, 0xd6, 0x82, 0xb6, 0x82, 0xe7, 0x82, 0xea,
0x82, 0xc4, 0x82, 0xa2, 0x82, 0xdc, 0x82, 0xb7,
0x81, 0x42, 0x0a, 0x96, 0x82, 0x96, 0x40, 0x82,
0xcc, 0x8d, 0x91, 0x81, 0x41, 0x81, 0x75, 0x83,
0x6a, 0x83, 0x93, 0x83, 0x4c, 0x83, 0x87, 0x83,
0x69, 0x81, 0x5b, 0x83, 0x54, 0x81, 0x76, 0x81,
0x42, 0x0a, 0x82, 0xbb, 0x82, 0xcc, 0x95, 0xbd,
0x98, 0x61, 0x82, 0xc8, 0x8d, 0x91, 0x82, 0xcd,
0x81, 0x41, 0x8c, 0xbb, 0x8e, 0xc0, 0x90, 0xa2,
0x8a, 0x45, 0x82, 0xc9, 0x8f, 0x5a, 0x82, 0xde,
0x90, 0x6c, 0x81, 0x58, 0x82, 0xcc, 0x91, 0xbc,
0x90, 0x6c, 0x82, 0xf0, 0x8e, 0x76, 0x82, 0xa2,
0x82, 0xe2, 0x82, 0xe9, 0x90, 0x53, 0x82, 0xf0,
0x97, 0xc6, 0x82, 0xc6, 0x82, 0xb5, 0x82, 0xc4,
0x90, 0xac, 0x82, 0xe8, 0x97, 0xa7, 0x82, 0xc1,
0x82, 0xc4, 0x82, 0xa2, 0x82, 0xbd, 0x81, 0x42,
0x0a, 0x82, 0xbe, 0x82, 0xaa, 0x81, 0x41, 0x92,
0x4e, 0x82, 0xe0, 0x82, 0xaa, 0x8e, 0xa9, 0x95,
0xaa, 0x82, 0xcc, 0x82, 0xb1, 0x82, 0xc6, 0x82,
0xce, 0x82, 0xa9, 0x82, 0xe8, 0x82, 0xf0, 0x8d,
0x6c, 0x82, 0xa6, 0x81, 0x41, 0x8e, 0x76, 0x82,
0xa2, 0x82, 0xe2, 0x82, 0xe8, 0x82, 0xcc, 0x90,
0x53, 0x81, 0x81, 0x8b, 0xa0, 0x8b, 0x43, 0x28,
0x82, 0xa8, 0x82, 0xc6, 0x82, 0xb1, 0x82, 0xac,
0x29, 0x82, 0xf0, 0x8e, 0xb8, 0x82, 0xa2, 0x82,
0xc2, 0x82, 0xc2, 0x82, 0xa0, 0x82, 0xe9, 0x90,
0xa2, 0x82, 0xcc, 0x92, 0x86, 0x81, 0x41, 0x0a,
0x96, 0x82, 0x96, 0x40, 0x82, 0xcc, 0x8d, 0x91,
0x82, 0xcd, 0x96, 0xc5, 0x82, 0xd1, 0x82, 0xcc,
0x8a, 0xeb, 0x8b, 0x40, 0x82, 0xc9, 0x95, 0x6d,
0x82, 0xb5, 0x82, 0xc4, 0x82, 0xa2, 0x82, 0xbd,
0x81, 0x63, 0x81, 0x42, 0x0a, 0x82, 0xbb, 0x82,
0xcc, 0x96, 0x82, 0x96, 0x40, 0x82, 0xcc, 0x8d,
0x91, 0x82, 0xcc, 0x83, 0x73, 0x83, 0x93, 0x83,
0x60, 0x82, 0xf0, 0x8b, 0x7e, 0x82, 0xa4, 0x82,
0xbd, 0x82, 0xdf, 0x8c, 0xbb, 0x8e, 0xc0, 0x90,
0xa2, 0x8a, 0x45, 0x82, 0xc9, 0x8c, 0xad, 0x82,
0xed, 0x82, 0xb3, 0x82, 0xea, 0x82, 0xbd, 0x82,
0xcc, 0x82, 0xaa, 0x81, 0x41, 0x90, 0xe6, 0x91,
0xe3, 0x82, 0xcc, 0x96, 0x82, 0x96, 0x40, 0x8f,
0xad, 0x8f, 0x97, 0x81, 0x42, 0x0a, 0x94, 0xde,
0x8f, 0x97, 0x82, 0xcd, 0x90, 0xa2, 0x82, 0xcc,
0x92, 0x86, 0x82, 0xc9, 0x82, 0xd9, 0x82, 0xf1,
0x82, 0xcc, 0x8f, 0xad, 0x82, 0xb5, 0x8e, 0x63,
0x82, 0xb3, 0x82, 0xea, 0x82, 0xbd, 0x81, 0x75,
0x8b, 0xa0, 0x8b, 0x43, 0x81, 0x76, 0x82, 0xf0,
0x8f, 0x57, 0x82, 0xdf, 0x81, 0x41, 0x81, 0x75,
0x83, 0x6a, 0x83, 0x93, 0x83, 0x4c, 0x83, 0x87,
0x83, 0x69, 0x81, 0x5b, 0x83, 0x54, 0x81, 0x76,
0x82, 0xf0, 0x96, 0xc5, 0x82, 0xd1, 0x82, 0xa9,
0x82, 0xe7, 0x8b, 0x7e, 0x82, 0xc1, 0x82, 0xbd,
0x82, 0xcc, 0x82, 0xbe, 0x82, 0xc1, 0x82, 0xbd,
0x81, 0x42, 0x0a, 0x0a, 0x82, 0xbb, 0x82, 0xb5,
0x82, 0xc4, 0x81, 0x41, 0x82, 0xbb, 0x82, 0xea,
0x82, 0xa9, 0x82, 0xe7, 0x8f, 0x5c, 0x90, 0x94,
0x94, 0x4e, 0x81, 0x42, 0x0a, 0x81, 0x75, 0x83,
0x6a, 0x83, 0x93, 0x83, 0x4c, 0x83, 0x87, 0x83,
0x69, 0x81, 0x5b, 0x83, 0x54, 0x81, 0x76, 0x82,
0xcd, 0x8d, 0xc4, 0x82, 0xd1, 0x96, 0xc5, 0x82,
0xd1, 0x82, 0xcc, 0x89, 0x8f, 0x82, 0xc9, 0x82,
0xa0, 0x82, 0xc1, 0x82, 0xbd, 0x81, 0x42, 0x0a,
0x82, 0xa9, 0x82, 0xc2, 0x82, 0xc4, 0x82, 0xc6,
0x93, 0xaf, 0x82, 0xb6, 0x82, 0xad, 0x81, 0x41,
0x90, 0x6c, 0x81, 0x58, 0x82, 0xaa, 0x8b, 0xa0,
0x8b, 0x43, 0x82, 0xf0, 0x8e, 0xb8, 0x82, 0xc1,
0x82, 0xc4, 0x82, 0xb5, 0x82, 0xdc, 0x82, 0xc1,
0x82, 0xbd, 0x82, 0xb1, 0x82, 0xc6, 0x82, 0xbe,
0x82, 0xaf, 0x82, 0xc5, 0x82, 0xc8, 0x82, 0xad,
0x81, 0x41, 0x96, 0x82, 0x8a, 0x45, 0x83, 0x7d,
0x83, 0x74, 0x83, 0x42, 0x83, 0x41, 0x82, 0xc9,
0x82, 0xe0, 0x91, 0x5f, 0x82, 0xed, 0x82, 0xea,
0x82, 0xc4, 0x82, 0xa2, 0x82, 0xbd, 0x82, 0xcc,
0x82, 0xbe, 0x81, 0x42, 0x0a, 0x88, 0xd9, 0x90,
0xa2, 0x8a, 0x45, 0x82, 0xf0, 0x8e, 0x9f, 0x81,
0x58, 0x82, 0xc6, 0x92, 0x6e, 0x8f, 0xe3, 0x82,
0xb0, 0x82, 0xb5, 0x81, 0x41, 0x0a, 0x89, 0xe4,
0x82, 0xaa, 0x95, 0xa8, 0x82, 0xc6, 0x82, 0xb5,
0x82, 0xc4, 0x82, 0xa2, 0x82, 0xbd, 0x96, 0x82,
0x8a, 0x45, 0x83, 0x7d, 0x83, 0x74, 0x83, 0x42,
0x83, 0x41, 0x82, 0xbd, 0x82, 0xbf, 0x82, 0xcd,
0x81, 0x41, 0x81, 0x75, 0x83, 0x6a, 0x83, 0x93,
0x83, 0x4c, 0x83, 0x87, 0x83, 0x69, 0x81, 0x5b,
0x83, 0x54, 0x81, 0x76, 0x82, 0xcc, 0x8a, 0xeb,
0x8b, 0x40, 0x82, 0xf0, 0x95, 0x71, 0x8a, 0xb4,
0x82, 0xc9, 0x8e, 0x40, 0x82, 0xb5, 0x81, 0x41,
0x0a, 0x83, 0x6e, 0x83, 0x43, 0x83, 0x47, 0x83,
0x69, 0x82, 0xcc, 0x82, 0xb2, 0x82, 0xc6, 0x82,
0xad, 0x94, 0x97, 0x82, 0xc1, 0x82, 0xc4, 0x82,
0xad, 0x82, 0xe9, 0x81, 0x42, 0x0a, 0x82, 0xbe,
0x82, 0xaa, 0x81, 0x41, 0x90, 0xe6, 0x91, 0xe3,
0x96, 0x82, 0x96, 0x40, 0x8f, 0xad, 0x8f, 0x97,
0x82, 0xcd, 0x8a, 0xf9, 0x82, 0xc9, 0x96, 0x53,
0x82, 0xad, 0x81, 0x41, 0x8c, 0xbb, 0x8e, 0xc0,
0x90, 0xa2, 0x8a, 0x45, 0x82, 0xc5, 0x90, 0xb6,
0x8a, 0x88, 0x82, 0xb7, 0x82, 0xe9, 0x96, 0x82,
0x96, 0x40, 0x8f, 0xad, 0x8f, 0x97, 0x82, 0xcc,
0x97, 0x42, 0x88, 0xea, 0x82, 0xcc, 0x8e, 0x71,
0x8b, 0x9f, 0x82, 0xcd, 0x92, 0x6a, 0x82, 0xcc,
0x8e, 0x71, 0x81, 0x42, 0x0a, 0x8d, 0xa1, 0x82,
0xdc, 0x82, 0xb3, 0x82, 0xc9, 0x81, 0x75, 0x83,
0x6a, 0x83, 0x93, 0x83, 0x4c, 0x83, 0x87, 0x83,
0x69, 0x81, 0x5b, 0x83, 0x54, 0x81, 0x76, 0x8e,
0x6e, 0x82, 0xdc, 0x82, 0xc1, 0x82, 0xc4, 0x88,
0xcb, 0x97, 0x8a, 0x82, 0xcc, 0x8a, 0xeb, 0x8b,
0x40, 0x82, 0xc9, 0x81, 0x41, 0x0a, 0x81, 0x75,
0x8b, 0xa0, 0x8b, 0x43, 0x81, 0x76, 0x88, 0xec,
0x82, 0xea, 0x82, 0xe9, 0x8f, 0xad, 0x8f, 0x97,
0x82, 0xcc, 0x93, 0x6f, 0x8f, 0xea, 0x82, 0xaa,
0x81, 0x41, 0x8b, 0xad, 0x82, 0xad, 0x8b, 0xad,
0x82, 0xad, 0x91, 0xd2, 0x82, 0xbf, 0x96, 0x5d,
0x82, 0xdc, 0x82, 0xea, 0x82, 0xc4, 0x82, 0xa2,
0x82, 0xbd, 0x81, 0x42, 0x0a, 0x0a, 0x0a, 0x81,
0x63, 0x82, 0xbb, 0x82, 0xea, 0x82, 0xcd, 0x82,
0xbb, 0x82, 0xea, 0x82, 0xc6, 0x82, 0xb5, 0x82,
0xc4, 0x81, 0x41, 0x8c, 0xbb, 0x8e, 0xc0, 0x90,
0xa2, 0x8a, 0x45, 0x81, 0x42, 0x0a, 0x82, 0xbb,
0x82, 0xf1, 0x82, 0xc8, 0x96, 0x82, 0x96, 0x40,
0x82, 0xcc, 0x8d, 0x91, 0x82, 0xcc, 0x8a, 0xeb,
0x8b, 0x40, 0x82, 0xc8, 0x82, 0xc7, 0x82, 0xcd,
0x82, 0xc2, 0x82, 0xe4, 0x92, 0x6d, 0x82, 0xe7,
0x82, 0xb8, 0x81, 0x41, 0x8d, 0xa1, 0x93, 0xfa,
0x82, 0xe0, 0x8a, 0x79, 0x82, 0xb5, 0x82, 0xad,
0x82, 0xcc, 0x82, 0xd9, 0x82, 0xd9, 0x82, 0xf1,
0x82, 0xc6, 0x90, 0xb6, 0x82, 0xab, 0x82, 0xc4,
0x82, 0xa2, 0x82, 0xe9, 0x8e, 0xe5, 0x90, 0x6c,
0x8c, 0xf6, 0x81, 0x41, 0x90, 0x9b, 0x8c, 0xb4,
0x95, 0xb6, 0x91, 0xbe, 0x98, 0x59, 0x81, 0x42,
0x0a, 0x93, 0x56, 0x8a, 0x55, 0x8c, 0xc7, 0x93,
0xc6, 0x82, 0xcc, 0x90, 0x67, 0x82, 0xc5, 0x82,
0xcd, 0x82, 0xa0, 0x82, 0xe9, 0x82, 0xe0, 0x82,
0xcc, 0x82, 0xcc, 0x81, 0x41, 0x0a, 0x90, 0xb6,
0x97, 0x88, 0x82, 0xcc, 0x8f, 0x97, 0x8d, 0x44,
0x82, 0xab, 0x82, 0xf0, 0x91, 0xb6, 0x95, 0xaa,
0x82, 0xc9, 0x94, 0xad, 0x8a, 0xf6, 0x82, 0xb5,
0x82, 0xc4, 0x92, 0xb4, 0x91, 0x4f, 0x8c, 0xfc,
0x82, 0xab, 0x82, 0xc9, 0x90, 0xb6, 0x82, 0xab,
0x82, 0xc4, 0x82, 0xa2, 0x82, 0xbd, 0x94, 0xde,
0x82, 0xcd, 0x81, 0x41, 0x82, 0xa0, 0x82, 0xe9,
0x93, 0xfa, 0x93, 0xcb, 0x91, 0x52, 0x82, 0xcc,
0x89, 0xce, 0x8d, 0xd0, 0x82, 0xc5, 0x81, 0x41,
0x0a, 0x8f, 0x5a, 0x82, 0xf1, 0x82, 0xc5, 0x82,
0xa2, 0x82, 0xbd, 0x83, 0x41, 0x83, 0x70, 0x81,
0x5b, 0x83, 0x67, 0x82, 0xf0, 0x8f, 0xc4, 0x82,
0xaf, 0x8f, 0x6f, 0x82, 0xb3, 0x82, 0xea, 0x82,
0xc4, 0x82, 0xb5, 0x82, 0xdc, 0x82, 0xc1, 0x82,
0xbd, 0x81, 0x42, 0x0a, 0x82, 0xbb, 0x82, 0xf1,
0x82, 0xc8, 0x94, 0xde, 0x82, 0xc9, 0x81, 0x75,
0x82, 0xc6, 0x82, 0xe8, 0x82, 0xa0, 0x82, 0xa6,
0x82, 0xb8, 0x82, 0xa4, 0x82, 0xbf, 0x82, 0xc9,
0x97, 0x88, 0x82, 0xe9, 0x82, 0xa9, 0x81, 0x48,
0x81, 0x76, 0x82, 0xc6, 0x90, 0x65, 0x90, 0xd8,
0x82, 0xc8, 0x90, 0xba, 0x82, 0xf0, 0x82, 0xa9,
0x82, 0xaf, 0x82, 0xc4, 0x82, 0xad, 0x82, 0xea,
0x82, 0xe9, 0x91, 0xe5, 0x89, 0xc6, 0x82, 0xcc,
0x96, 0xba, 0x81, 0x41, 0x8b, 0x53, 0x97, 0xb4,
0x89, 0x40, 0x83, 0x6e, 0x83, 0x69, 0x81, 0x42,
0x0a, 0x89, 0xc2, 0x88, 0xa4, 0x82, 0xa2, 0x8f,
0x97, 0x82, 0xcc, 0x8e, 0x71, 0x82, 0xc9, 0x81,
0x75, 0x89, 0xc6, 0x82, 0xc9, 0x97, 0x88, 0x82,
0xa2, 0x81, 0x76, 0x82, 0xc6, 0x8c, 0xbe, 0x82,
0xed, 0x82, 0xea, 0x82, 0xbd, 0x8e, 0x96, 0x82,
0xc9, 0x95, 0x40, 0x82, 0xcc, 0x89, 0xba, 0x82,
0xf0, 0x90, 0x4c, 0x82, 0xce, 0x82, 0xb5, 0x82,
0xc2, 0x82, 0xc2, 0x81, 0x41, 0x82, 0xc2, 0x82,
0xa2, 0x82, 0xc4, 0x82, 0xa2, 0x82, 0xad, 0x95,
0xb6, 0x91, 0xbe, 0x98, 0x59, 0x81, 0x42, 0x0a,
0x82, 0xb5, 0x82, 0xa9, 0x82, 0xb5, 0x81, 0x49,
0x8f, 0xad, 0x8f, 0x97, 0x82, 0xc9, 0x88, 0xc4,
0x93, 0xe0, 0x82, 0xb3, 0x82, 0xea, 0x82, 0xbd,
0x90, 0xe6, 0x82, 0xcd, 0x81, 0x41, 0x83, 0x84,
0x83, 0x4e, 0x83, 0x55, 0x82, 0xcc, 0x90, 0x65,
0x95, 0xaa, 0x82, 0xcc, 0x82, 0xa8, 0x89, 0xae,
0x95, 0x7e, 0x82, 0xbe, 0x82, 0xc1, 0x82, 0xbd,
0x81, 0x63, 0x82, 0xc1, 0x81, 0x49, 0x0a, 0x0a,
0x82, 0xb3, 0x82, 0xb7, 0x82, 0xaa, 0x82, 0xcc,
0x95, 0xb6, 0x91, 0xbe, 0x98, 0x59, 0x82, 0xe0,
0x8d, 0xc5, 0x8f, 0x89, 0x82, 0xcd, 0x95, 0x7c,
0x82, 0xb6, 0x8b, 0x43, 0x82, 0xc3, 0x82, 0xad,
0x82, 0xe0, 0x82, 0xcc, 0x82, 0xcc, 0x81, 0x41,
0x82, 0xbb, 0x82, 0xcc, 0x82, 0xa8, 0x89, 0xae,
0x95, 0x7e, 0x81, 0x75, 0x8b, 0x53, 0x97, 0xb4,
0x91, 0x67, 0x81, 0x76, 0x82, 0xaa, 0x8f, 0x97,
0x8f, 0x8a, 0x91, 0xd1, 0x82, 0xc6, 0x92, 0x6d,
0x82, 0xe9, 0x82, 0xe2, 0x81, 0x41, 0x0a, 0x82,
0xa0, 0x82, 0xc1, 0x82, 0xb3, 0x82, 0xe8, 0x82,
0xc6, 0x8b, 0x8f, 0x8c, 0xf3, 0x82, 0xf0, 0x8c,
0x88, 0x82, 0xdf, 0x8d, 0x9e, 0x82, 0xde, 0x81,
0x42, 0x0a, 0x90, 0xdc, 0x82, 0xb5, 0x82, 0xe0,
0x81, 0x41, 0x8b, 0x53, 0x97, 0xb4, 0x91, 0x67,
0x82, 0xcd, 0x90, 0xe6, 0x91, 0xe3, 0x91, 0x67,
0x92, 0xb7, 0x82, 0xf0, 0x96, 0x53, 0x82, 0xad,
0x82, 0xb5, 0x82, 0xbd, 0x82, 0xce, 0x82, 0xa9,
0x82, 0xe8, 0x82, 0xc5, 0x81, 0x41, 0x93, 0x47,
0x91, 0xce, 0x82, 0xb7, 0x82, 0xe9, 0x91, 0x67,
0x82, 0xc6, 0x8d, 0x52, 0x91, 0x88, 0x82, 0xcc,
0x82, 0xdc, 0x82, 0xc1, 0x82, 0xbd, 0x82, 0xbe,
0x92, 0x86, 0x81, 0x42, 0x0a, 0x95, 0xb6, 0x91,
0xbe, 0x98, 0x59, 0x82, 0xcd, 0x81, 0x41, 0x89,
0xc2, 0x88, 0xa4, 0x82, 0xa2, 0x8f, 0x97, 0x82,
0xcc, 0x8e, 0x71, 0x82, 0xc6, 0x82, 0xcc, 0x96,
0xb2, 0x82, 0xcc, 0x82, 0xe6, 0x82, 0xa4, 0x82,
0xc8, 0x90, 0xb6, 0x8a, 0x88, 0x82, 0xf0, 0x8e,
0xe7, 0x82, 0xe9, 0x82, 0xd7, 0x82, 0xad, 0x81,
0x41, 0x0a, 0x83, 0x50, 0x83, 0x93, 0x83, 0x4a,
0x82, 0xe0, 0x8e, 0xe3, 0x82, 0xa2, 0x82, 0xad,
0x82, 0xb9, 0x82, 0xc9, 0x97, 0xa7, 0x82, 0xbf,
0x8f, 0xe3, 0x82, 0xaa, 0x82, 0xe9, 0x82, 0xcc,
0x82, 0xbe, 0x82, 0xc1, 0x82, 0xbd, 0x81, 0x42,
0x0a, 0x0a, 0x0a, 0x81, 0x63, 0x82, 0xc6, 0x82,
0xcd, 0x82, 0xa2, 0x82, 0xa6, 0x81, 0x41, 0x83,
0x50, 0x83, 0x93, 0x83, 0x4a, 0x82, 0xcd, 0x82,
0xa9, 0x82, 0xe7, 0x82, 0xab, 0x82, 0xb5, 0x82,
0xcc, 0x95, 0xb6, 0x91, 0xbe, 0x98, 0x59, 0x81,
0x42, 0x88, 0xc4, 0x82, 0xcc, 0x92, 0xe8, 0x81,
0x41, 0x82, 0xbf, 0x82, 0xf1, 0x82, 0xd2, 0x82,
0xe7, 0x8b, 0xa4, 0x82, 0xc9, 0x82, 0xda, 0x82,
0xb1, 0x82, 0xda, 0x82, 0xb1, 0x82, 0xc9, 0x82,
0xb3, 0x82, 0xea, 0x82, 0xc4, 0x82, 0xb5, 0x82,
0xdc, 0x82, 0xa4, 0x81, 0x42, 0x0a, 0x82, 0xbb,
0x82, 0xb5, 0x82, 0xc4, 0x81, 0x41, 0x8a, 0xeb,
0x8b, 0x40, 0x82, 0xc9, 0x8a, 0xd7, 0x82, 0xc1,
0x82, 0xbd, 0x95, 0xb6, 0x91, 0xbe, 0x98, 0x59,
0x82, 0xf0, 0x8f, 0x95, 0x82, 0xaf, 0x82, 0xe6,
0x82, 0xa4, 0x82, 0xc6, 0x81, 0x41, 0x83, 0x6e,
0x83, 0x69, 0x82, 0xaa, 0x8b, 0xec, 0x82, 0xaf,
0x8a, 0xf1, 0x82, 0xc1, 0x82, 0xc4, 0x82, 0xab,
0x82, 0xbd, 0x8e, 0x9e, 0x81, 0x63, 0x81, 0x63,
0x81, 0x42, 0x0a, 0x95, 0xb6, 0x91, 0xbe, 0x98,
0x59, 0x82, 0xcc, 0x95, 0xea, 0x82, 0xcc, 0x8c,
0x60, 0x8c, 0xa9, 0x82, 0xcc, 0x83, 0x58, 0x83,
0x67, 0x83, 0x89, 0x83, 0x62, 0x83, 0x76, 0x82,
0xaa, 0x8b, 0x50, 0x82, 0xab, 0x82, 0xf0, 0x95,
0xfa, 0x82, 0xbf, 0x81, 0x41, 0x83, 0x6e, 0x83,
0x69, 0x82, 0xcd, 0x81, 0x41, 0x81, 0x75, 0x96,
0x82, 0x96, 0x40, 0x8f, 0xad, 0x8f, 0x97, 0x81,
0x76, 0x82, 0xc9, 0x95, 0xcf, 0x90, 0x67, 0x82,
0xb5, 0x82, 0xbd, 0x81, 0x49, 0x81, 0x49, 0x0a,
0x5b, 0xd3, 0x54, 0xa9, 0x93, 0x5a, 0x55, 0x21,
0x87, 0x11, 0x2d, 0xfe, 0x88, 0x35, 0xe1, 0x44,
0x78, 0xad, 0x8a, 0xa9, 0x16, 0x0d, 0xe2, 0x39,
0xfe, 0x19, 0x5b, 0x1d, 0xcd, 0x05, 0x1f, 0x67,
0xb6, 0x6e, 0x9c, 0xe9, 0x5f, 0x5c, 0xd5, 0x7d,
0x84, 0x9b, 0x20, 0x96, 0x35, 0x78, 0xd4, 0xcd,
0xb1, 0xf9, 0x93, 0x94, 0xf6, 0x5a, 0x0d, 0x8b,
0x7f, 0xe8, 0x76, 0x0b, 0xd8, 0x71, 0x1d, 0x69,
0x2d, 0x82, 0xd3, 0xac, 0x5b, 0x02, 0x74, 0xb1,
0xa7, 0x0b, 0x81, 0x5a, 0x3b, 0x70, 0x6a, 0x97,
0x69, 0xb1, 0xdd, 0x65, 0x03, 0xae, 0x27, 0xee,
0xa6, 0x2b, 0x84, 0xa8, 0x03, 0xd6, 0x19, 0xbb,
0xf0, 0x1d, 0x51, 0xd9, 0x7f, 0xd1, 0x84, 0xee,
0xc7, 0xc5, 0x2a, 0x2d, 0xff, 0x99, 0x7a, 0x10,
0x64, 0x0f, 0x05, 0x6f, 0xcb, 0x75, 0xda, 0x3f,
0xcc, 0x31, 0x60, 0x84, 0xf3, 0xf6, 0x39, 0x28,
0xd3, 0xe0, 0xf1, 0x2a, 0xc6, 0xb2, 0xf2, 0x3a,
0xd4, 0x3f, 0x78, 0xfa, 0x37, 0x2e, 0x2b, 0xfc,
0xb8, 0x9c, 0xe7, 0xe8, 0x5c, 0xee, 0x8d, 0x2c,
0x33, 0x18, 0x28, 0x30, 0x4f, 0xe8, 0x3b, 0x8d,
0x82, 0x80, 0x96, 0x71, 0xd4, 0x51, 0x68, 0xbe,
0xcf, 0x82, 0x1b, 0xab, 0x5f, 0x70, 0x3d, 0xe2,
0xc1, 0xba, 0xa6, 0x0a, 0x49, 0xc3, 0x41, 0xfc,
0xe0, 0x57, 0x40, 0x52, 0xd4, 0x17, 0x1d, 0x1a,
0xe8, 0x47, 0xa1, 0x50, 0x1e, 0x5b, 0xa6, 0xeb,
0xbf, 0xad, 0x59, 0x90, 0xc1, 0x24, 0xb1, 0x0c,
0xac, 0x1a, 0x77, 0x91, 0x4b, 0x5d, 0xc7, 0xf5,
0x98, 0xe4, 0x1f, 0xe5, 0xa2, 0x41, 0x73, 0x95,
0xf6, 0x92, 0x1a, 0xff, 0x5f, 0x56, 0x43, 0xf0,
0x3b, 0x72, 0xbc, 0xe1, 0x05, 0x53, 0x9c, 0x6a,
0xcd, 0x44, 0x36, 0x4f, 0x6b, 0xa8, 0xc7, 0x33,
0x09, 0xcb, 0xe0, 0xf9, 0xef, 0xfa, 0x26, 0x17,
0x30, 0x03, 0xb1, 0xbb, 0x51, 0x1a, 0xa5, 0x54,
0x44, 0x4a, 0x10, 0x54, 0x0d, 0xe8, 0xb7, 0x0e,
0x4b, 0x44, 0x4f, 0x6a, 0x7c, 0xe6, 0xfc, 0x77,
0xf2, 0x3f, 0xb2, 0x9f, 0x72, 0xa8, 0x20, 0xfd,
0x81, 0xbe, 0x43, 0xc0, 0xc7, 0x51, 0xcb, 0xe2,
0x9b, 0x2b, 0x35, 0xa6, 0x16, 0xf6, 0xd3, 0xd1,
0x42, 0x68, 0xf6, 0x1c, 0x9d, 0xae, 0xe2, 0x46,
0x18, 0x72, 0x89, 0x6d, 0xf7, 0xb7, 0xa0, 0xe7,
0x16, 0x0c, 0xf5, 0x65, 0x76, 0xfc, 0x74, 0xa7,
0xc5, 0xb5, 0xb2, 0x27, 0x2c, 0x91, 0xfe, 0x7d,
0x0f, 0x15, 0xa1, 0xf1, 0xc9, 0xea, 0x8f, 0x65,
0x82, 0xdd, 0x9c, 0x5e, 0xe0, 0xd4, 0x4c, 0x1b,
0xdc, 0xcc, 0x8e, 0xd0, 0x29, 0x6f, 0x76, 0x54,
0x2d, 0x9b, 0x21, 0x2e, 0xf4, 0x91, 0x90, 0x70,
0xf6, 0x40, 0x59, 0xbd, 0x3a, 0xd6, 0xe8, 0x73,
0x8b, 0x0c, 0x35, 0xd2, 0x90, 0x44, 0x1a, 0x82,
0x2c, 0x5d, 0xec, 0xbc, 0x2c, 0x51, 0xf9, 0xc1,
0x81, 0x93, 0xdd, 0x10, 0x23, 0xe5, 0xa2, 0x6e,
0xcd, 0xf6, 0x7d, 0x12, 0xff, 0x36, 0xd8, 0x9e,
0x34, 0x1f, 0x44, 0x2a, 0x00, 0x5a, 0x86, 0xc9,
0x9f, 0x78, 0x7e, 0x39, 0x91, 0x9e, 0x78, 0x88,
0xb1, 0xa7, 0x08, 0x0b, 0x74, 0x0a, 0x30, 0x3e,
0x71, 0x55, 0x6f, 0x2c, 0xfc, 0x0d, 0x9c, 0xeb,
0x52, 0xcb, 0x7d, 0x4d, 0xbd, 0x05, 0x90, 0xe1,
0x0e, 0xd3, 0x89, 0x6c, 0x3c, 0x57, 0x08, 0x85,
0x15, 0x66, 0xd7, 0x40, 0xb4, 0x99, 0x9e, 0xfb,
0x4d, 0x12, 0x65, 0x98, 0xa8, 0x47, 0x8b, 0x22,
0x7b, 0xd8, 0x15, 0xb6, 0x56, 0xc1, 0xbc, 0x8f,
0x3d, 0xba, 0x54, 0x7b, 0x38, 0xbe, 0x79, 0xed,
0xc7, 0x70, 0xd5, 0xd4, 0xc8, 0x37, 0x42, 0x15,
0xb8, 0xf3, 0x29, 0xe7, 0x10, 0x22, 0xb6, 0xcf,
0x4d, 0xd3, 0xa9, 0x63, 0xf1, 0xa2, 0xe0, 0x5c,
0x32, 0x23, 0xfc, 0x11, 0x12, 0xad, 0x36, 0x83,
0x23, 0x0e, 0x8c, 0x6e, 0x94, 0x24, 0xf3, 0x7c,
0xc7, 0x84, 0x19, 0x40, 0x41, 0x1d, 0xcc, 0xa1,
0xf4, 0xcb, 0xd8, 0xd6, 0xc5, 0xff, 0xba, 0x95,
0xb2, 0x80, 0xb2, 0x3e, 0xdb, 0x8c, 0xfc, 0x63,
0x6c, 0x09, 0x5e, 0x4c, 0x93, 0xe0, 0x70, 0x3b,
0xd4, 0x53, 0xb8, 0x9b, 0xdf, 0xd2, 0x4a, 0x9e,
0x08, 0x74, 0x84, 0xf6, 0x90, 0xb2, 0x57, 0xab,
0x6d, 0x0b, 0x68, 0x76, 0xc9, 0xdf, 0x5a, 0xba,
0x78, 0x70, 0x91, 0xfd, 0xa3, 0xee, 0xcb, 0xa9,
0x20, 0xc6, 0x4c, 0x07, 0x23, 0x18, 0x02, 0xcc,
0x60, 0x19, 0xb5, 0x0e, 0x20, 0xea, 0xcd, 0xb3,
0x22, 0x92, 0x58, 0xb1, 0x16, 0x36, 0xf6, 0x0a,
0xa2, 0xe4, 0xbf, 0xa8, 0x39, 0x29, 0x1a, 0x39,
0xae, 0x91, 0x4f, 0x14, 0xc7, 0x1c, 0x5c, 0xc9,
0x96, 0x02, 0x06, 0xec, 0x2a, 0xaa, 0xb3, 0x06,
0x99, 0xf5, 0x4d, 0x9b, 0xfd, 0x3c, 0x38, 0x9b,
0x06, 0x9d, 0x83, 0xc2, 0x48, 0x3c, 0x45, 0x5c,
0xc2, 0x41, 0x5e, 0x58, 0x9b, 0xf2, 0x02, 0x83,
0xac, 0xd4, 0xd7, 0x63, 0xf9, 0x49, 0x73, 0xc1,
0x26, 0xa9, 0xb8, 0x30, 0xe2, 0xdc, 0x1d, 0x75,
0x97, 0x63, 0xd0, 0x5a, 0x8d, 0xa8, 0x9a, 0x58,
0x09, 0x34, 0xbd, 0xfe, 0x02, 0xef, 0x32, 0x80,
0x65, 0x30, 0x99, 0x59, 0xd7, 0xf0, 0x5f, 0xd6,
0xbb, 0x39, 0x9c, 0x17, 0xf8, 0x04, 0x76, 0x76,
0x69, 0x16, 0x2a, 0x01, 0x45, 0xc3, 0x3d, 0x19,
0xf3, 0xa0, 0xe2, 0x01, 0x33, 0x6c, 0x01, 0x47,
0xc8, 0x4f, 0x96, 0x88, 0x56, 0xa0, 0x19, 0x48,
0xc6, 0xc1, 0xc3, 0x37, 0xbc, 0xfa, 0x97, 0x11,
0x69, 0x59, 0x5c, 0xc9, 0x43, 0xb4, 0x51, 0x50,
0xb0, 0x3a, 0x05, 0xf4, 0xbb, 0x18, 0xd2, 0x33,
0xc3, 0x0e, 0x16, 0x40, 0x89, 0x2b, 0xca, 0xf3,
0x4c, 0x24, 0xb8, 0x0a, 0x28, 0x54, 0xda, 0x0c,
0xc3, 0x50, 0x71, 0xde, 0x3c, 0x7a, 0x82, 0x6d,
0x5a, 0x4d, 0x87, 0x3c, 0x67, 0x73, 0xa3, 0xc6,
0x54, 0x4c, 0x3b, 0xd4, 0x18, 0xb7, 0x1e, 0x71,
0xe7, 0xc5, 0x1a, 0xf1, 0x4e, 0xff, 0xe8, 0xc0,
0x79, 0xc7, 0x8a, 0xb9, 0xfc, 0x15, 0xfc, 0x39,
0x99, 0xca, 0xd8, 0x53, 0x5d, 0x55, 0x31, 0x43,
0x01, 0xaf, 0x37, 0x98, 0x90, 0xf1, 0x92, 0xa5,
0x03, 0x2e, 0x60, 0xd0, 0xa4, 0x3a, 0xd6, 0xdc,
0xe1, 0x9c, 0xed, 0xec, 0xd1, 0x48, 0xc0, 0x8d,
0x1e, 0xa3, 0xfe, 0x86, 0x12, 0x67, 0x4f, 0x32,
0x10, 0x6e, 0x50, 0xc7, 0x93, 0xc5, 0xbc, 0x92,
0x61, 0xfe, 0x7f, 0x8c, 0xb4, 0x99, 0x06, 0xd2,
0x96, 0xb0, 0x25, 0xdc, 0x1e, 0x6f, 0x34, 0x1b,
0x5b, 0x10, 0xd6, 0xb7, 0x13, 0x25, 0xa4, 0xf0,
0x9e, 0x56, 0x24, 0x81, 0x43, 0x39, 0x73, 0x94,
0x07, 0xd3, 0x46, 0x24, 0x8a, 0x04, 0x62, 0x57,
0x84, 0x3b, 0x3b, 0x81, 0xd8, 0x74, 0x94, 0x54,
0x97, 0x5c, 0x3b, 0xcc, 0xff, 0xe3, 0x5b, 0xec,
0xe9, 0x47, 0xcf, 0x69, 0x5a, 0xe0, 0x22, 0x05,
0x4c, 0x25, 0x62, 0x15, 0xf9, 0xe8, 0xd7, 0xc6,
0xee, 0xc6, 0xa4, 0xd9, 0xfb, 0xd9, 0x1b, 0xef,
0xbd, 0x18, 0xe1, 0x2e, 0x7a, 0xf8, 0x70, 0xea,
0x07, 0xb4, 0x46, 0x54, 0x24, 0xe7, 0x59, 0x59,
0x5e, 0x6d, 0x5b, 0x63, 0xa5, 0xf2, 0xa3, 0x1d,
0xdb, 0x31, 0x54, 0xe2, 0x13, 0xb2, 0x8c, 0x47,
0x0c, 0x53, 0x8e, 0xda, 0xeb, 0x7a, 0x7a, 0x73,
0x50, 0x27, 0x10, 0xec, 0x71, 0x8c, 0xbd, 0x52,
0xaf, 0xb6, 0x36, 0xf5, 0x58, 0x37, 0x6d, 0x9e,
0xa2, 0xdd, 0x83, 0x01, 0x46, 0xa9, 0x7c, 0x5c,
0x86, 0xc8, 0xcb, 0xa2, 0x0c, 0x19, 0xcc, 0xd2,
0x9f, 0x6d, 0xf8, 0x82, 0x25, 0xa4, 0xb4, 0x4c,
0x81, 0x35, 0x50, 0x98, 0x61, 0xa0, 0x2e, 0xce,
0xf4, 0x70, 0x8f, 0xb1, 0xb7, 0x2a, 0x16, 0xf0,
0x35, 0x90, 0x37, 0x6c, 0xbe, 0x96, 0x52, 0xf6,
0xe3, 0xd4, 0x5c, 0x26, 0x09, 0xc3, 0x3a, 0xa1,
0xbf, 0x9c, 0x9b, 0x1c, 0x8d, 0x57, 0x61, 0x89,
0xc1, 0x73, 0xe9, 0xab, 0xa2, 0xf4, 0x46, 0x0b,
0x2f, 0x8d, 0x45, 0x70, 0x65, 0x48, 0x4a, 0xf6,
0xf1, 0x51, 0xf2, 0x80, 0xfb, 0x05, 0x1f, 0x84,
0xa7, 0x66, 0x49, 0xd2, 0xd6, 0x1e, 0x88, 0x6c,
0xcf, 0x18, 0xc7, 0x04, 0xd6, 0xb0, 0x8e, 0x08,
0xf6, 0x9f, 0x69, 0xfe, 0x66, 0x97, 0xc8, 0xa8,
0x63, 0x6e, 0xee, 0x99, 0x0a, 0x58, 0xb7, 0x7b,
0xb7, 0xa0, 0xd3, 0xa3, 0xb4, 0xf7, 0xf6, 0x59,
0x88, 0x8f, 0xf1, 0x8c, 0xf3, 0xc4, 0x12, 0x06,
0xce, 0x01, 0x6f, 0x66, 0x4e, 0x03, 0x72, 0x28,
0x10, 0x34, 0x5d, 0x03, 0xc8, 0x4e, 0x5a, 0x8b,
0xf7, 0xeb, 0x44, 0xca, 0x23, 0xb9, 0x97, 0xd5,
0x2b, 0x4e, 0xd4, 0x2d, 0xf3, 0x9d, 0x90, 0xb6,
0x3b, 0xba, 0xb4, 0xfd, 0xfd, 0x4c, 0xb2, 0xe8,
0xbc, 0x87, 0xad, 0xcc, 0x72, 0x92, 0x31, 0xa5,
0xad, 0x7c, 0x4d, 0x18, 0x46, 0xa2, 0x13, 0x8b,
0x39, 0x11, 0x23, 0x35, 0x0d, 0xfc, 0x02, 0xb2,
0xa9, 0x2d, 0xaa, 0x2e, 0x95, 0x38, 0x88, 0x9a,
0x6b, 0x18, 0x23, 0x1e, 0x11, 0xfb, 0xce, 0xc9,
0xf8, 0x9d, 0xb3, 0x2e, 0x11, 0x30, 0x2e, 0xea,
0x39, 0x15, 0xc2, 0x74, 0x51, 0x76, 0xfb, 0x13,
0x49, 0x0b, 0x1a, 0x35, 0x3f, 0x31, 0xc6, 0xb6,
0x61, 0xf2, 0x84, 0xf1, 0x46, 0xf8, 0xc6, 0xec,
0x17, 0x2a, 0xfe, 0x46, 0xc0, 0xe8, 0xfc, 0x23,
0xc2, 0xbb, 0xb8, 0xbd, 0xa1, 0xa4, 0x61, 0xf9,
0x0a, 0xdd, 0xcb, 0xe4, 0x34, 0x85, 0x11, 0xd8,
0xce, 0x20, 0x9e, 0xd6, 0x47, 0x9c, 0xed, 0xc7,
0x21, 0x47, 0xf9, 0x1b, 0x0d, 0xa1, 0x65, 0xbc,
0x86, 0xcb, 0x36, 0xc8, 0x74, 0xe2, 0x9e, 0x17,
0x46, 0xad, 0x5b, 0xe1, 0x47, 0xc6, 0xa7, 0xc2,
0xef, 0x72, 0x3c, 0x5f, 0x4b, 0xcf, 0x41, 0xb5,
0xee, 0x96, 0x84, 0xeb, 0x4c, 0x08, 0x67, 0x00,
0x33, 0x50, 0xeb, 0xe6, 0x54, 0x70, 0x9e, 0x74,
0xe6, 0x4b, 0xff, 0x66, 0x97, 0x0a, 0x03, 0xf6,
0x8b, 0x4c, 0xd4, 0xa0, 0xcf, 0x7c, 0x02, 0xba,
0xaa, 0x62, 0xd5, 0x8c, 0x30, 0x9b, 0x40, 0xfb,
0x92, 0xd6, 0x8d, 0x22, 0xd0, 0x66, 0xa3, 0x2a,
0xdb, 0x19, 0x2b, 0xff, 0xee, 0xea, 0xbb, 0x3d,
0x27, 0x28, 0xfd, 0x96, 0xa2, 0x4f, 0xf1, 0x1a,
0x57, 0x89, 0xa3, 0xa2, 0x06, 0x2e, 0x47, 0xe0,
0x7b, 0x42, 0xd4, 0xe6, 0x08, 0x99, 0xd3, 0xa9,
0x57, 0x90, 0x69, 0x4f, 0x18, 0x44, 0xb4, 0x33,
0x20, 0x10, 0xd2, 0x50, 0x3b, 0x5d, 0x38, 0x5d,
0x3a, 0x9b, 0x7a, 0xec, 0x98, 0xea, 0x25, 0x86,
0x9c, 0x47, 0x4f, 0xd6, 0xb6, 0xc7, 0x28, 0x74,
0x5f, 0xba, 0x99, 0x7b, 0x94, 0x59, 0xd9, 0x87,
0x75, 0xa6, 0x72, 0x1d, 0x91, 0x8e, 0xd3, 0x62,
0xeb, 0x3d, 0xc9, 0x78, 0x79, 0xfb, 0x54, 0x06,
0x78, 0xf2, 0x6c, 0xb0, 0x93, 0x83, 0xa0, 0xe2,
0x20, 0xb7, 0x1b, 0x2c, 0x74, 0x90, 0xe7, 0x3e,
0xfd, 0x1d, 0x00, 0x28, 0x9f, 0x3a, 0x40, 0x98,
0x58, 0x3a, 0xd7, 0xea, 0x8d, 0x4f, 0xe7, 0xbe,
0xd4, 0xa0, 0x74, 0x15, 0x6c, 0xd0, 0x3c, 0x0e,
0x19, 0x39, 0xa6, 0xa1, 0x30, 0x53, 0x34, 0xa1,
0xcc, 0x3f, 0x73, 0x28, 0x87, 0x91, 0x54, 0xc6,
0xb1, 0x2c, 0xea, 0xb8, 0x60, 0x3b, 0xb2, 0x61,
0xca, 0x84, 0x2e, 0x29, 0x25, 0x86, 0x51, 0x57,
0x0b, 0x89, 0x54, 0x69, 0xd4, 0x4e, 0xd4, 0x3a,
0x01, 0xe6, 0xa6, 0xaf, 0xef, 0x26, 0x45, 0xc3,
0x7b, 0x88, 0x1f, 0x70, 0x7e, 0x67, 0x9e, 0xb4,
0x98, 0xd4, 0xb7, 0x15, 0x24, 0xe3, 0x9a, 0xf0,
0x8f, 0xb3, 0x14, 0x2c, 0x6f, 0xc5, 0xf3, 0xb9,
0x49, 0x35, 0x4a, 0x8c, 0xfb, 0xcf, 0x51, 0x3d,
0x90, 0xc2, 0x26, 0x21, 0x77, 0xef, 0x67, 0xd2,
0x51, 0x8b, 0xc0, 0x16, 0x62, 0x67, 0x24, 0x20,
0x0f, 0x43, 0xd7, 0x62, 0x24, 0x8c, 0x8f, 0xf3,
0x6c, 0x4e, 0x8f, 0xa7, 0x7c, 0xe8, 0xa6, 0x26,
0x0c, 0x93, 0x73, 0x5c, 0x02, 0xc0, 0x9d, 0x67,
0x49, 0x35, 0x40, 0xbb, 0x71, 0x98, 0x00, 0x02,
0x3b, 0x20, 0xe4, 0x99, 0x2c, 0x0e, 0xf9, 0x01,
0xad, 0xab, 0x7f, 0x4b, 0x8f, 0xed, 0xd7, 0xb1,
0xdf, 0x48, 0xbf, 0x4c, 0x5a, 0x31, 0xe7, 0x77,
0xdc, 0xf7, 0x3e, 0xaa, 0x5f, 0xcd, 0x46, 0x45,
0x93, 0xfe, 0x15, 0xe4, 0xc1, 0xf9, 0x1c, 0xbe,
0x6c, 0x16, 0xb4, 0x47, 0x9b, 0x45, 0xde, 0x38,
0x1f, 0x43, 0xd5, 0xea, 0x38, 0x59, 0x2b, 0xc9,
0x26, 0x05, 0x1a, 0x0b, 0x56, 0xb4, 0x8d, 0xec,
0x72, 0xeb, 0x08, 0xd6, 0x33, 0xcc, 0x9e, 0x59,
0x65, 0x32, 0x0d, 0xec, 0x07, 0x94, 0xf5, 0xea,
0xb6, 0x78, 0xa5, 0xc7, 0x01, 0x22, 0x68, 0x64,
0x99, 0xaa, 0x32, 0x8a, 0xdd, 0x4e, 0xc4, 0x3f,
0x70, 0x43, 0xa0, 0x69, 0x34, 0xf0, 0x41, 0xc9,
0x70, 0x71, 0xae, 0x21, 0xcf, 0x36, 0x1d, 0xf4,
0x4e, 0x72, 0xb5, 0xf6, 0x69, 0xdf, 0xed, 0x28,
0x4c, 0x46, 0x3c, 0xb7, 0x16, 0x6f, 0x3c, 0x48,
0xfc, 0xbd, 0x51, 0x2d, 0x0d, 0x0e, 0x96, 0x43,
0xe2, 0x1d, 0xcc, 0xd2, 0x54, 0xc9, 0x17, 0x1f,
0x1c, 0xfe, 0xcb, 0x0e, 0xeb, 0x21, 0x90, 0x07,
0xa8, 0x48, 0x02, 0x09, 0xa1, 0x3f, 0x9b, 0x35,
0x5a, 0x0e, 0x67, 0x70, 0x09, 0x53, 0x03, 0x23,
0x28, 0x82, 0x44, 0xba, 0x0b, 0xcf, 0x3e, 0x31,
0x60, 0xec, 0x75, 0x0b, 0x02, 0x01, 0xa9, 0xc6,
0xdc, 0x6b, 0xe0, 0x77, 0xe6, 0xbd, 0x0b, 0x0c,
0x11, 0xb3, 0xb0, 0xdb, 0xb8, 0x41, 0x06, 0x6b,
0xf3, 0xaf, 0x05, 0xc0, 0xeb, 0x70, 0x0a, 0xc8,
0x46, 0x31, 0x51, 0xcc, 0xc1, 0x6b, 0x63, 0x40,
0xe9, 0x64, 0x89, 0x7d, 0x1d, 0x69, 0x09, 0x51,
0xfa, 0x88, 0x9c, 0xd6, 0x2d, 0x2e, 0xd9, 0x5f,
0xb4, 0x98, 0xc3, 0x87, 0x02, 0xa6, 0x8e, 0x26,
0x3c, 0x59, 0xa4, 0xb6, 0x1c, 0x9e, 0x51, 0xa2,
0x26, 0x14, 0x31, 0xac, 0x27, 0x87, 0xa8, 0xa1,
0x47, 0x13, 0xc5, 0x5d, 0x8e, 0xc4, 0x52, 0x85,
0x46, 0xd8, 0x74, 0x7c, 0xef, 0x72, 0x9c, 0xd0,
0xef, 0xee, 0xf9, 0xb0, 0x9e, 0xae, 0x57, 0xaf,
0xab, 0x6e, 0x61, 0xe8, 0x66, 0xc0, 0xbb, 0x1b,
};
static int xcode_building_first_stage(struct cxdec_xcode_status *xcode)
{
switch (xcode_rand(xcode) % 3) {
case 2:
// MOV ESI, EncryptionControlBlock
// MOV EAX, DWORD PTR DS:[ESI+((xcode_rand(xcode) & 0x3ff) << 2)]
if (!push_bytexcode(xcode, 0xbe)
|| !push_dwordxcode(xcode, (DWORD)EncryptionControlBlock)
|| !push_2bytesxcode(xcode, 0x8b, 0x86)
|| !push_dwordxcode(xcode, (xcode_rand(xcode) & 0x3ff) << 2))
return 0;
break;
case 0:
// MOV EAX, EDI
if (!push_2bytesxcode(xcode, 0x8b, 0xc7))
return 0;
break;
case 1:
// MOV EAX, xcode_rand(xcode)
if (!push_bytexcode(xcode, 0xb8)
|| !push_dwordxcode(xcode, xcode_rand(xcode)))
return 0;
break;
}
return 1;
}
static int xcode_building_stage0(struct cxdec_xcode_status *xcode, int stage)
{
if (stage == 1)
return xcode_building_first_stage(xcode);
if (xcode_rand(xcode) & 1) {
if (!xcode_building_stage1(xcode, stage - 1))
return 0;
} else {
if (!xcode_building_stage0(xcode, stage - 1))
return 0;
}
switch (xcode_rand(xcode) & 7) {
case 6:
// NOT EAX
if (!push_2bytesxcode(xcode, 0xf7, 0xd0))
return 0;
break;
case 0:
// MOV ESI, EncryptionControlBlock
// AND EAX, 3FFh
// MOV EAX, DWORD PTR DS:[ESI+EAX*4]
if (!push_bytexcode(xcode, 0xbe)
|| !push_dwordxcode(xcode, (DWORD)EncryptionControlBlock)
|| !push_bytexcode(xcode, 0x25)
|| !push_dwordxcode(xcode, 0x3ff)
|| !push_3bytesxcode(xcode, 0x8b, 0x04, 0x86))
return 0;
break;
case 5:
// DEC EAX
if (!push_bytexcode(xcode, 0x48))
return 0;
break;
case 4:
// NEG EAX
if (!push_2bytesxcode(xcode, 0xf7, 0xd8))
return 0;
break;
case 1:
if (xcode_rand(xcode) & 1) {
// ADD EAX, xcode_rand(xcode)
if (!push_bytexcode(xcode, 0x05))
return 0;
} else {
// SUB EAX, xcode_rand(xcode)
if (!push_bytexcode(xcode, 0x2d))
return 0;
}
if (!push_dwordxcode(xcode, xcode_rand(xcode)))
return 0;
break;
case 2:
// PUSH EBX
// MOV EBX, EAX
// AND EBX, AAAAAAAA
// AND EAX, 55555555
// SHR EBX, 1
// SHL EAX, 1
// OR EAX, EBX
// POP EBX
if (!push_bytexcode(xcode, 0x53)
|| !push_2bytesxcode(xcode, 0x89, 0xc3)
|| !push_6bytesxcode(xcode, 0x81, 0xe3, 0xaa, 0xaa, 0xaa, 0xaa)
|| !push_5bytesxcode(xcode, 0x25, 0x55, 0x55, 0x55, 0x55)
|| !push_2bytesxcode(xcode, 0xd1, 0xeb)
|| !push_2bytesxcode(xcode, 0xd1, 0xe0)
|| !push_2bytesxcode(xcode, 0x09, 0xd8)
|| !push_bytexcode(xcode, 0x5b))
return 0;
break;
case 7:
// INC EAX
if (!push_bytexcode(xcode, 0x40))
return 0;
break;
case 3:
// XOR EAX, xcode_rand(xcode)
if (!push_bytexcode(xcode, 0x35)
|| !push_dwordxcode(xcode, xcode_rand(xcode)))
return 0;
break;
}
return 1;
}
static int xcode_building_stage1(struct cxdec_xcode_status *xcode, int stage)
{
if (stage == 1)
return xcode_building_first_stage(xcode);
// PUSH EBX
if (!push_bytexcode(xcode, 0x53))
return 0;
if (xcode_rand(xcode) & 1) {
if (!xcode_building_stage1(xcode, stage - 1))
return 0;
} else {
if (!xcode_building_stage0(xcode, stage - 1))
return 0;
}
// MOV EBX, EAX
if (!push_2bytesxcode(xcode, 0x89, 0xc3))
return 0;
if (xcode_rand(xcode) & 1) {
if (!xcode_building_stage1(xcode, stage - 1))
return 0;
} else {
if (!xcode_building_stage0(xcode, stage - 1))
return 0;
}
switch (xcode_rand(xcode) % 6) {
case 1:
// ADD EAX, EBX
if (!push_2bytesxcode(xcode, 0x01, 0xd8))
return 0;
break;
case 3:
// PUSH ECX
// MOV ECX, EBX
// AND ECX, 0F
// SHR EAX, CL
// POP ECX
if (!push_bytexcode(xcode, 0x51)
|| !push_2bytesxcode(xcode, 0x89, 0xd9)
|| !push_3bytesxcode(xcode, 0x83, 0xe1, 0x0f)
|| !push_2bytesxcode(xcode, 0xd3, 0xe8)
|| !push_bytexcode(xcode, 0x59))
return 0;
break;
case 4:
// PUSH ECX
// MOV ECX, EBX
// AND ECX, 0F
// SHL EAX, CL
// POP ECX
if (!push_bytexcode(xcode, 0x51)
|| !push_2bytesxcode(xcode, 0x89, 0xd9)
|| !push_3bytesxcode(xcode, 0x83, 0xe1, 0x0f)
|| !push_2bytesxcode(xcode, 0xd3, 0xe0)
|| !push_bytexcode(xcode, 0x59))
return 0;
break;
case 2:
// NEG EAX, ADD EAX, EBX
if (!push_2bytesxcode(xcode, 0xf7, 0xd8)
|| !push_2bytesxcode(xcode, 0x01, 0xd8))
return 0;
break;
case 5:
// IMUL EAX, EBX
if (!push_3bytesxcode(xcode, 0x0f, 0xaf, 0xc3))
return 0;
break;
case 0:
// SUB EAX, EBX
if (!push_2bytesxcode(xcode, 0x29, 0xd8))
return 0;
break;
}
// POP EBX
return push_bytexcode(xcode, 0x5b);
}
struct cxdec_callback nidaimeTrial_cxdec_callback = {
"nidaimeTrial",
{ 0x187, 0x7ac },
xcode_building_stage1
};
| [
"[email protected]"
] | |
0bf2a3cc50a2934a3891b89171fbcf5d1ab5407d | 766b16d0117dc951cdc40f739631b9cdd1b3086f | /TouchGFX/generated/gui_generated/include/gui_generated/common/SimConstants.hpp | 5e7ceee6c40c9ad73a31902b379fc838444c077f | [] | no_license | IotGod/OTGMessenger | 7f5ca301eeecbe7d92fda11cb07e1c40b422cd9a | 7f0f051afb70882ee32781d0db3f0e0c920932d5 | refs/heads/master | 2023-06-14T18:22:25.369533 | 2021-07-12T09:33:03 | 2021-07-12T09:33:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | hpp | /*********************************************************************************/
/********** THIS FILE IS GENERATED BY TOUCHGFX DESIGNER, DO NOT MODIFY ***********/
/*********************************************************************************/
#ifndef SIMCONSTANTS_HPP
#define SIMCONSTANTS_HPP
static unsigned short SIM_WIDTH = 320;
static unsigned short SIM_HEIGHT = 240;
#define SIM_TITLE "H742VGT6"
#endif // SIMCONSTANTS_HPP
| [
"[email protected]"
] | |
b90b1469da4b8e336d5a75e9c21ad207896d2053 | 9b4f4ad42b82800c65f12ae507d2eece02935ff6 | /src/IO/SensorManagerW.cpp | 0a37795e713f78f1c2922a81a0a7e751ad6048d2 | [] | no_license | github188/SClass | f5ef01247a8bcf98d64c54ee383cad901adf9630 | ca1b7efa6181f78d6f01a6129c81f0a9dd80770b | refs/heads/main | 2023-07-03T01:25:53.067293 | 2021-08-06T18:19:22 | 2021-08-06T18:19:22 | 393,572,232 | 0 | 1 | null | 2021-08-07T03:57:17 | 2021-08-07T03:57:16 | null | UTF-8 | C++ | false | false | 5,655 | cpp | #include "Stdafx.h"
#include "MyMemory.h"
#include "IO/SensorAccelerometerW.h"
#include "IO/SensorOrientationWin.h"
#include "IO/SensorUnknownWin.h"
#include "IO/SensorManager.h"
#include <windows.h>
#include <initguid.h>
#include <sensorsapi.h>
#include <sensors.h>
#include <stdio.h>
#if !defined(__MINGW32__)
// {77a1c827-fcd2-4689-8915-9d613cc5fa3e}
DEFINE_GUID(CLSID_SensorManager, 0X77a1c827, 0Xfcd2, 0X4689, 0X89, 0X15, 0X9d, 0X61, 0X3c, 0Xc5, 0Xfa, 0X3e);
#endif
typedef struct
{
ISensorManager *mgr;
Bool accessDenined;
} ClassData;
IO::SensorManager::SensorManager()
{
ClassData *me = MemAlloc(ClassData, 1);
this->clsData = me;
me->mgr = 0;
me->accessDenined = false;
CoInitialize(0);
ISensorManager *pSensorManager = 0;
HRESULT hr = CoCreateInstance(CLSID_SensorManager,
NULL, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&pSensorManager));
if(hr == HRESULT_FROM_WIN32(ERROR_ACCESS_DISABLED_BY_POLICY))
{
me->accessDenined = true;
}
else if (pSensorManager)
{
me->mgr = pSensorManager;
}
}
IO::SensorManager::~SensorManager()
{
ClassData *me = (ClassData*)this->clsData;
if (me->mgr)
{
me->mgr->Release();
}
MemFree(me);
CoUninitialize();
}
UOSInt IO::SensorManager::GetSensorCnt()
{
ClassData *me = (ClassData*)this->clsData;
if (me->mgr == 0)
return 0;
UOSInt ret = 0;
ISensorCollection *pSensorColl;
HRESULT hr;
hr = me->mgr->GetSensorsByCategory(SENSOR_CATEGORY_ALL, &pSensorColl);
if(SUCCEEDED(hr))
{
ULONG ulCount = 0;
hr = pSensorColl->GetCount(&ulCount);
if(SUCCEEDED(hr))
{
ret = ulCount;
}
pSensorColl->Release();
}
return ret;
}
IO::Sensor::SensorType IO::SensorManager::GetSensorType(UOSInt index)
{
ClassData *me = (ClassData*)this->clsData;
if (me->mgr == 0)
return IO::Sensor::ST_UNKNOWN;
IO::Sensor::SensorType sensorType = IO::Sensor::ST_UNKNOWN;
ISensorCollection *pSensorColl;
HRESULT hr;
hr = me->mgr->GetSensorsByCategory(SENSOR_CATEGORY_ALL, &pSensorColl);
if(SUCCEEDED(hr))
{
ULONG ulCount = 0;
hr = pSensorColl->GetCount(&ulCount);
if(SUCCEEDED(hr))
{
if (ulCount > index)
{
ISensor *pSensor;
if (SUCCEEDED(pSensorColl->GetAt((ULONG)index, &pSensor)))
{
SENSOR_TYPE_ID sType;
if (SUCCEEDED(pSensor->GetType(&sType)))
{
if (sType == SENSOR_TYPE_ACCELEROMETER_3D)
{
sensorType = IO::Sensor::ST_ACCELEROMETER;
}
else if (sType == SENSOR_TYPE_ENVIRONMENTAL_ATMOSPHERIC_PRESSURE)
{
sensorType = IO::Sensor::ST_PRESSURE;
}
else if (sType == SENSOR_TYPE_COMPASS_3D)
{
sensorType = IO::Sensor::ST_MAGNETOMETER;
}
else if (sType == SENSOR_TYPE_INCLINOMETER_3D)
{
sensorType = IO::Sensor::ST_ORIENTATION;
}
}
pSensor->Release();
}
}
}
pSensorColl->Release();
}
return sensorType;
}
IO::Sensor *IO::SensorManager::CreateSensor(UOSInt index)
{
ClassData *me = (ClassData*)this->clsData;
if (me->mgr == 0 || index < 0)
return 0;
IO::Sensor *ret = 0;
ISensorCollection *pSensorColl;
HRESULT hr;
hr = me->mgr->GetSensorsByCategory(SENSOR_CATEGORY_ALL, &pSensorColl);
if(SUCCEEDED(hr))
{
ULONG ulCount = 0;
hr = pSensorColl->GetCount(&ulCount);
if(SUCCEEDED(hr))
{
if (ulCount > index)
{
ISensor *pSensor;
if (SUCCEEDED(pSensorColl->GetAt((ULONG)index, &pSensor)))
{
SENSOR_TYPE_ID sType;
if (SUCCEEDED(pSensor->GetType(&sType)))
{
// printf("type = %x, %x\r\n", sType.Data1, sType.Data2);
if (sType == SENSOR_TYPE_ACCELEROMETER_3D)
{
NEW_CLASS(ret, IO::SensorAccelerometerW(pSensor));
}
else if (sType == SENSOR_TYPE_ENVIRONMENTAL_ATMOSPHERIC_PRESSURE)
{
NEW_CLASS(ret, IO::SensorUnknownWin(pSensor));
}
else if (sType == SENSOR_TYPE_COMPASS_3D)
{
NEW_CLASS(ret, IO::SensorUnknownWin(pSensor));
}
else if (sType == SENSOR_TYPE_INCLINOMETER_3D)
{
NEW_CLASS(ret, IO::SensorOrientationWin(pSensor));
}
else
{
NEW_CLASS(ret, IO::SensorUnknownWin(pSensor));
}
}
else
{
NEW_CLASS(ret, IO::SensorUnknownWin(pSensor));
}
}
}
}
pSensorColl->Release();
}
return ret;
}
UOSInt IO::SensorManager::GetAccelerometerCnt()
{
ClassData *me = (ClassData*)this->clsData;
if (me->mgr == 0)
return 0;
UOSInt ret = 0;
ISensorCollection *pSensorColl;
HRESULT hr;
hr = me->mgr->GetSensorsByType(SENSOR_TYPE_ACCELEROMETER_3D, &pSensorColl);
if(SUCCEEDED(hr))
{
ULONG ulCount = 0;
hr = pSensorColl->GetCount(&ulCount);
if(SUCCEEDED(hr))
{
ret = ulCount;
}
pSensorColl->Release();
}
return ret;
}
IO::SensorAccelerometer *IO::SensorManager::CreateAccelerometer(UOSInt index)
{
IO::SensorAccelerometer *ret = 0;
ClassData *me = (ClassData*)this->clsData;
if (me->mgr == 0 || index < 0)
return 0;
ISensorCollection *pSensorColl;
HRESULT hr;
hr = me->mgr->GetSensorsByType(SENSOR_TYPE_ACCELEROMETER_3D, &pSensorColl);
if(SUCCEEDED(hr))
{
ULONG ulCount = 0;
hr = pSensorColl->GetCount(&ulCount);
if(SUCCEEDED(hr))
{
if ((OSInt)ulCount > index)
{
ISensor *pSensor;
if (SUCCEEDED(pSensorColl->GetAt((ULONG)index, &pSensor)))
{
NEW_CLASS(ret, IO::SensorAccelerometerW(pSensor));
}
}
}
pSensorColl->Release();
}
return ret;
}
| [
"[email protected]"
] | |
2dfd78497524ec64c5fa5bb01db88b8f900fe944 | 92745756b1d9280222894d6b7ba918c00f76bf3b | /SDK/PUBG_DeathDropItemPackage_classes.hpp | 6a1cb4f3fca8d91109aef0bd49313a1f491be310 | [] | no_license | ziyouhaofan/PUBG-SDK | 018b2b28420b762de8c2b7e7142cb4f28647dc7f | 03d5f52e8d4fd7e2bef250217a9a5622366610e2 | refs/heads/master | 2021-07-19T11:34:17.527464 | 2017-10-26T03:42:44 | 2017-10-26T03:42:44 | 108,414,666 | 1 | 0 | null | 2017-10-26T13:24:32 | 2017-10-26T13:24:32 | null | UTF-8 | C++ | false | false | 1,009 | hpp | #pragma once
// PlayerUnknown's Battlegrounds SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace Classes {
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass DeathDropItemPackage.DeathDropItemPackage_C
// 0x0008 (0x0520 - 0x0518)
class ADeathDropItemPackage_C : public AFloorSnapItemPackage {
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0518(0x0008) (CPF_ZeroConstructor, CPF_Transient, CPF_DuplicateTransient)
static UClass* StaticClass() {
static UClass* ptr = nullptr;
if (!ptr) ptr = UObject::FindClass(0x70d2c535);
return ptr;
}
void GetCategory(struct FText* Category);
void UserConstructionScript();
void ReceiveBeginPlay();
void ExecuteUbergraph_DeathDropItemPackage(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
bc9c6849b49ffd77d977fefd3b5c0ce7fa9dfef0 | 37cca16f12e7b1d4d01d6f234da6d568c318abee | /src/rice/p2p/util/RedBlackMap_KeyIterator.hpp | 231a1065ccaef11e40512f3eb400e4ddf94483af | [] | no_license | subhash1-0/thirstyCrow | e48155ce68fc886f2ee8e7802567c1149bc54206 | 78b7e4e3d2b9a9530ad7d66b44eacfe73ceea582 | refs/heads/master | 2016-09-06T21:25:54.075724 | 2015-09-21T17:21:15 | 2015-09-21T17:21:15 | 42,881,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | hpp | // Generated from /pastry-2.1/src/rice/p2p/util/RedBlackMap.java
#pragma once
#include <java/lang/fwd-pastry-2.1.hpp>
#include <rice/p2p/util/fwd-pastry-2.1.hpp>
#include <rice/p2p/util/RedBlackMap_EntryIterator.hpp>
struct default_init_tag;
class rice::p2p::util::RedBlackMap_KeyIterator
: public RedBlackMap_EntryIterator
{
public:
typedef RedBlackMap_EntryIterator super;
::java::lang::Object* next() override;
// Generated
RedBlackMap_KeyIterator(RedBlackMap *RedBlackMap_this);
protected:
RedBlackMap_KeyIterator(RedBlackMap *RedBlackMap_this, const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
friend class RedBlackMap;
friend class RedBlackMap_keySet_1;
friend class RedBlackMap_values_2;
friend class RedBlackMap_entrySet_3;
friend class RedBlackMap_SubMap;
friend class RedBlackMap_SubMap_EntrySetView;
friend class RedBlackMap_SubWrappedMap;
friend class RedBlackMap_SubWrappedMap_EntrySetView;
friend class RedBlackMap_EntryIterator;
friend class RedBlackMap_ValueIterator;
friend class RedBlackMap_SubMapEntryIterator;
friend class RedBlackMap_SubWrappedMapEntryIterator;
friend class RedBlackMap_Entry;
};
| [
"[email protected]"
] | |
f836d1919eb9abc6e33cd6512890cf97b84d504f | 9c65c6fa7cd4d9d8017f34021907c04c791eb8cb | /src/comunicacion/EnviadorMensajesServidor.cpp | 6f2eb6cc282c5ee672039746652152fd0414d5ce | [] | no_license | MartinCohen98/ProyectoTaller-Luminegro | 7da58aed4a66945622da8e83e8788b889f0e0b1c | c45429167b922bd8f4995c4007113b5b871527ad | refs/heads/master | 2020-07-14T22:51:04.476699 | 2019-12-05T00:30:47 | 2019-12-05T00:30:47 | 205,419,022 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 524 | cpp | #include "EnviadorMensajesServidor.h"
EnviadorMensajesServidor::EnviadorMensajesServidor(Socket* unSocket,
ColaMensajesServidor* unaCola) {
socket = unSocket;
cola = unaCola;
}
void EnviadorMensajesServidor::operator()() {
while(socket->getEstado() == Socket::ESTADO_CONECTADO) {
mensaje = cola->desencolar();
if (mensaje.obtenerTipoDeSprite() != MensajeInvalido) {
socket->enviar(&mensaje);
} else {
std::this_thread::yield();
}
}
}
EnviadorMensajesServidor::~EnviadorMensajesServidor() {}
| [
"[email protected]"
] | |
16a211c8fa827d1db43dea61db456e4b80fb4c01 | 2098c74a59133c985e10f57a901bc5839a6d1333 | /Source/XrGameCS/ai/monsters/rats/rat_state_initialize.cpp | cd2f0c8d0848b2b0474742cedf466ad4819e59dc | [] | no_license | ChuniMuni/XRayEngine | 28672b4c5939e95c6dfb24c9514041dd25cfa306 | cdb13c23552fd86409b6e4e2925ac78064ee8739 | refs/heads/master | 2023-04-02T01:04:01.134317 | 2021-04-10T07:44:41 | 2021-04-10T07:44:41 | 266,738,168 | 1 | 0 | null | 2021-04-10T07:44:41 | 2020-05-25T09:27:11 | C++ | UTF-8 | C++ | false | false | 1,549 | cpp | #include "pch_script.h"
#include "ai_rat.h"
#include "../../ai_monsters_misc.h"
#include "../../../game_level_cross_table.h"
#include "../../../game_graph.h"
#include "ai_rat_space.h"
#include "../../../../xrRender/Public/KinematicsAnimated.h"
#include "../../../detail_path_manager.h"
#include "../../../memory_manager.h"
#include "../../../enemy_manager.h"
#include "../../../item_manager.h"
#include "../../../memory_space.h"
#include "../../../ai_object_location.h"
#include "../../../movement_manager.h"
#include "../../../sound_player.h"
#include "ai_rat_impl.h"
#include "../../../ai_space.h"
void CAI_Rat::init_state_under_fire()
{
if (!switch_if_enemy()&&get_if_dw_time()&&m_tLastSound.dwTime >= m_dwLastUpdateTime)
{
Fvector tTemp;
tTemp.setHP(-movement().m_body.current.yaw,-movement().m_body.current.pitch);
tTemp.normalize_safe();
tTemp.mul(m_fUnderFireDistance);
m_tSpawnPosition.add(Position(),tTemp);
}
m_tGoalDir = m_tSpawnPosition;
}
void CAI_Rat::init_free_recoil()
{
m_dwLostRecoilTime = Device.dwTimeGlobal;
m_tRecoilPosition = m_tLastSound.tSavedPosition;
if (!switch_if_enemy()&&!switch_if_time())
{
Fvector tTemp;
tTemp.setHP(-movement().m_body.current.yaw,-movement().m_body.current.pitch);
tTemp.normalize_safe();
tTemp.mul(m_fUnderFireDistance);
m_tSpawnPosition.add(Position(),tTemp);
}
}
void CAI_Rat::init_free_active()
{
if (bfCheckIfGoalChanged()) {
if (Position().distance_to(m_home_position) > m_fMaxHomeRadius)
m_fSpeed = m_fSafeSpeed = m_fMaxSpeed;
vfChooseNewSpeed();
}
} | [
"[email protected]"
] | |
929732c141e0583b618b7156becade9d471d5500 | d872449199115ba136dbd1e14e993bffc8182a24 | /ParticlePhysics/ParticlePhysics/Source/ComputeHelp.cpp | afb86b212b371adb6b88f280acd15d51ca9950fe | [] | no_license | Torkelz/Particle-Physics | 073ebfde15a1cb6e3a9b46d1bb1451e1e3688616 | 4533b7c17c8be87963d12b8cc667156287a5ea81 | refs/heads/master | 2021-01-02T22:38:11.997180 | 2014-09-30T15:32:17 | 2014-09-30T15:32:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,585 | cpp | //--------------------------------------------------------------------------------------
// Copyright (c) Stefan Petersson 2012. All rights reserved.
//--------------------------------------------------------------------------------------
#include "ComputeHelp.h"
#include <cstdio>
#pragma comment(lib, "d3dcompiler.lib")
#pragma comment(lib, "dxguid.lib")
//#if defined( DEBUG ) || defined( _DEBUG )
//#pragma comment(lib, "d3d11d.lib")
//#else
//#pragma comment(lib, "d3d11.lib")
//#endif
ComputeShader::ComputeShader()
: mD3DDevice(NULL), mD3DDeviceContext(NULL)
{
}
ComputeShader::~ComputeShader()
{
//SAFE_RELEASE(mD3DDevice);
}
bool ComputeShader::Init(TCHAR* shaderFile, char* blobFileAppendix, char* pFunctionName, D3D10_SHADER_MACRO* pDefines,
ID3D11Device* d3dDevice, ID3D11DeviceContext*d3dContext)
{
HRESULT hr = S_OK;
mD3DDevice = d3dDevice;
mD3DDeviceContext = d3dContext;
ID3DBlob* pCompiledShader = NULL;
ID3DBlob* pErrorBlob = NULL;
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined(DEBUG) || defined(_DEBUG)
dwShaderFlags |= D3DCOMPILE_DEBUG;
dwShaderFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL0;
#else
dwShaderFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL0;
#endif
hr = D3DCompileFromFile(shaderFile, pDefines, D3D_COMPILE_STANDARD_FILE_INCLUDE, pFunctionName, "cs_5_0",
dwShaderFlags, NULL, &pCompiledShader, &pErrorBlob);
if (pErrorBlob)
{
char* err = (char*)pErrorBlob->GetBufferPointer();
OutputDebugStringA(err);
}
if(hr == S_OK)
{
/*
ID3D11ShaderReflection* pReflector = NULL;
hr = D3DReflect( pCompiledShader->GetBufferPointer(),
pCompiledShader->GetBufferSize(), IID_ID3D11ShaderReflection,
(void**) &pReflector);
*/
if(hr == S_OK)
{
hr = mD3DDevice->CreateComputeShader(pCompiledShader->GetBufferPointer(),
pCompiledShader->GetBufferSize(), NULL, &mShader);
}
}
SAFE_RELEASE(pErrorBlob);
SAFE_RELEASE(pCompiledShader);
return (hr == S_OK);
}
void ComputeShader::Set()
{
mD3DDeviceContext->CSSetShader( mShader, NULL, 0 );
}
void ComputeShader::Unset()
{
mD3DDeviceContext->CSSetShader( NULL, NULL, 0 );
}
ComputeBuffer* ComputeWrap::CreateBuffer(COMPUTE_BUFFER_TYPE uType,
UINT uElementSize, UINT uCount, bool bSRV, bool bUAV, VOID* pInitData, bool bCreateStaging, char* debugName)
{
ComputeBuffer* buffer = new ComputeBuffer();
buffer->_D3DContext = mD3DDeviceContext;
if(uType == STRUCTURED_BUFFER)
buffer->_Resource = CreateStructuredBuffer(uElementSize, uCount, bSRV, bUAV, pInitData);
else if(uType == RAW_BUFFER)
buffer->_Resource = CreateRawBuffer(uElementSize * uCount, pInitData);
if(buffer->_Resource != NULL)
{
if(bSRV)
buffer->_ResourceView = CreateBufferSRV(buffer->_Resource);
if(bUAV)
buffer->_UnorderedAccessView = CreateBufferUAV(buffer->_Resource);
if(bCreateStaging)
buffer->_Staging = CreateStagingBuffer(uElementSize * uCount);
}
if(debugName)
{
if(buffer->_Resource) SetDebugName(buffer->_Resource, debugName);
if(buffer->_Staging) SetDebugName(buffer->_Staging, debugName);
if(buffer->_ResourceView) SetDebugName(buffer->_ResourceView, debugName);
if(buffer->_UnorderedAccessView) SetDebugName(buffer->_UnorderedAccessView, debugName);
}
return buffer; //return shallow copy
}
ID3D11Buffer* ComputeWrap::CreateStructuredBuffer(UINT uElementSize, UINT uCount,
bool bSRV, bool bUAV, VOID* pInitData)
{
ID3D11Buffer* pBufOut = NULL;
D3D11_BUFFER_DESC desc;
ZeroMemory( &desc, sizeof(desc) );
desc.BindFlags = 0;
if(bUAV) desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
if(bSRV) desc.BindFlags |= D3D11_BIND_SHADER_RESOURCE;
UINT bufferSize = uElementSize * uCount;
desc.ByteWidth = bufferSize < 16 ? 16 : bufferSize;
desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
desc.StructureByteStride = uElementSize;
if ( pInitData )
{
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = pInitData;
mD3DDevice->CreateBuffer( &desc, &InitData, &pBufOut);
}
else
{
mD3DDevice->CreateBuffer(&desc, NULL, &pBufOut);
}
return pBufOut;
}
ID3D11Buffer* ComputeWrap::CreateRawBuffer(UINT uSize, VOID* pInitData)
{
ID3D11Buffer* pBufOut = NULL;
D3D11_BUFFER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_INDEX_BUFFER | D3D11_BIND_VERTEX_BUFFER;
desc.ByteWidth = uSize;
desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS;
if ( pInitData )
{
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = pInitData;
mD3DDevice->CreateBuffer(&desc, &InitData, &pBufOut);
}
else
{
mD3DDevice->CreateBuffer(&desc, NULL, &pBufOut);
}
return pBufOut;
}
ID3D11ShaderResourceView* ComputeWrap::CreateBufferSRV(ID3D11Buffer* pBuffer)
{
ID3D11ShaderResourceView* pSRVOut = NULL;
D3D11_BUFFER_DESC descBuf;
ZeroMemory(&descBuf, sizeof(descBuf));
pBuffer->GetDesc(&descBuf);
D3D11_SHADER_RESOURCE_VIEW_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
desc.BufferEx.FirstElement = 0;
if(descBuf.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS)
{
// This is a Raw Buffer
desc.Format = DXGI_FORMAT_R32_TYPELESS;
desc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW;
desc.BufferEx.NumElements = descBuf.ByteWidth / 4;
}
else if(descBuf.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED)
{
// This is a Structured Buffer
desc.Format = DXGI_FORMAT_UNKNOWN;
desc.BufferEx.NumElements = descBuf.ByteWidth / descBuf.StructureByteStride;
}
else
{
return NULL;
}
mD3DDevice->CreateShaderResourceView(pBuffer, &desc, &pSRVOut);
return pSRVOut;
}
ID3D11UnorderedAccessView* ComputeWrap::CreateBufferUAV(ID3D11Buffer* pBuffer)
{
ID3D11UnorderedAccessView* pUAVOut = NULL;
D3D11_BUFFER_DESC descBuf;
ZeroMemory(&descBuf, sizeof(descBuf));
pBuffer->GetDesc(&descBuf);
D3D11_UNORDERED_ACCESS_VIEW_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
desc.Buffer.FirstElement = 0;
if (descBuf.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS)
{
// This is a Raw Buffer
desc.Format = DXGI_FORMAT_R32_TYPELESS; // Format must be DXGI_FORMAT_R32_TYPELESS, when creating Raw Unordered Access View
desc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW;
desc.Buffer.NumElements = descBuf.ByteWidth / 4;
}
else if(descBuf.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED)
{
// This is a Structured Buffer
desc.Format = DXGI_FORMAT_UNKNOWN; // Format must be DXGI_FORMAT_UNKNOWN, when creating a View of a Structured Buffer
desc.Buffer.NumElements = descBuf.ByteWidth / descBuf.StructureByteStride;
}
else
{
return NULL;
}
mD3DDevice->CreateUnorderedAccessView(pBuffer, &desc, &pUAVOut);
return pUAVOut;
}
ID3D11Buffer* ComputeWrap::CreateStagingBuffer(UINT uSize)
{
ID3D11Buffer* debugbuf = NULL;
D3D11_BUFFER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.ByteWidth = uSize;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.MiscFlags = 0;
mD3DDevice->CreateBuffer(&desc, NULL, &debugbuf);
return debugbuf;
}
// TEXTURE FUNCTIONS
ComputeTexture* ComputeWrap::CreateTexture(DXGI_FORMAT dxFormat, UINT uWidth,
UINT uHeight, UINT uRowPitch, VOID* pInitData, bool bCreateStaging, char* debugName)
{
ComputeTexture* texture = new ComputeTexture();
texture->_D3DContext = mD3DDeviceContext;
texture->_Resource = CreateTextureResource(dxFormat, uWidth, uHeight, uRowPitch, pInitData);
if(texture->_Resource != NULL)
{
texture->_ResourceView = CreateTextureSRV(texture->_Resource);
texture->_UnorderedAccessView = CreateTextureUAV(texture->_Resource);
if(bCreateStaging)
texture->_Staging = CreateStagingTexture(texture->_Resource);
}
if(debugName)
{
if(texture->_Resource) SetDebugName(texture->_Resource, debugName);
if(texture->_Staging) SetDebugName(texture->_Staging, debugName);
if(texture->_ResourceView) SetDebugName(texture->_ResourceView, debugName);
if(texture->_UnorderedAccessView) SetDebugName(texture->_UnorderedAccessView, debugName);
}
return texture;
}
ComputeTexture* ComputeWrap::CreateTexture(TCHAR* textureFilename, char* debugName)
{
ComputeTexture* texture = new ComputeTexture();
texture->_D3DContext = mD3DDeviceContext;
//if(SUCCEEDED(D3DX11CreateTextureFromFile(mD3DDevice, textureFilename, NULL, NULL, (ID3D11Resource**)&texture->_Resource, NULL)))
//{
// texture->_ResourceView = CreateTextureSRV(texture->_Resource);
//
// if(debugName)
// {
// if(texture->_Resource) SetDebugName(texture->_Resource, debugName);
// if(texture->_Staging) SetDebugName(texture->_Staging, debugName);
// if(texture->_ResourceView) SetDebugName(texture->_ResourceView, debugName);
// if(texture->_UnorderedAccessView) SetDebugName(texture->_UnorderedAccessView, debugName);
// }
//}
return texture;
}
ID3D11Texture2D* ComputeWrap::CreateTextureResource(DXGI_FORMAT dxFormat,
UINT uWidth, UINT uHeight, UINT uRowPitch, VOID* pInitData)
{
ID3D11Texture2D* pTexture = NULL;
D3D11_TEXTURE2D_DESC desc;
desc.Width = uWidth;
desc.Height = uHeight;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = dxFormat;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = pInitData;
data.SysMemPitch = uRowPitch;
if(FAILED(mD3DDevice->CreateTexture2D( &desc, pInitData ? &data : NULL, &pTexture )))
{
}
return pTexture;
}
ID3D11ShaderResourceView* ComputeWrap::CreateTextureSRV(ID3D11Texture2D* pTexture)
{
ID3D11ShaderResourceView* pSRV = NULL;
D3D11_TEXTURE2D_DESC td;
pTexture->GetDesc(&td);
//init view description
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
ZeroMemory( &viewDesc, sizeof(viewDesc) );
viewDesc.Format = td.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
viewDesc.Texture2D.MipLevels = td.MipLevels;
if(FAILED(mD3DDevice->CreateShaderResourceView(pTexture, &viewDesc, &pSRV)))
{
//MessageBox(0, "Unable to create shader resource view", "Error!", 0);
}
return pSRV;
}
ID3D11UnorderedAccessView* ComputeWrap::CreateTextureUAV(ID3D11Texture2D* pTexture)
{
ID3D11UnorderedAccessView* pUAV = NULL;
mD3DDevice->CreateUnorderedAccessView( pTexture, NULL, &pUAV );
pTexture->Release();
return pUAV;
}
ID3D11Texture2D* ComputeWrap::CreateStagingTexture(ID3D11Texture2D* pTexture)
{
ID3D11Texture2D* pStagingTex = NULL;
D3D11_TEXTURE2D_DESC desc;
pTexture->GetDesc(&desc);
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.MiscFlags = 0;
mD3DDevice->CreateTexture2D(&desc, NULL, &pStagingTex);
return pStagingTex;
}
ID3D11Buffer* ComputeWrap::CreateConstantBuffer(UINT uSize, VOID* pInitData, char* debugName)
{
ID3D11Buffer* pBuffer = NULL;
// setup creation information
D3D11_BUFFER_DESC cbDesc;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.ByteWidth = uSize + (16 - uSize % 16);
cbDesc.CPUAccessFlags = 0;
cbDesc.MiscFlags = 0;
cbDesc.StructureByteStride = 0;
cbDesc.Usage = D3D11_USAGE_DEFAULT;
if(pInitData)
{
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = pInitData;
mD3DDevice->CreateBuffer(&cbDesc, &InitData, &pBuffer);
}
else
{
mD3DDevice->CreateBuffer(&cbDesc, NULL, &pBuffer);
}
if(debugName && pBuffer)
{
SetDebugName(pBuffer, debugName);
}
return pBuffer;
}
void ComputeWrap::SetDebugName(ID3D11DeviceChild* object, char* debugName)
{
#if defined( DEBUG ) || defined( _DEBUG )
// Only works if device is created with the D3D debug layer, or when attached to PIX for Windows
object->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(debugName), debugName );
#endif
}
ComputeShader* ComputeWrap::CreateComputeShader(TCHAR* shaderFile, char* blobFileAppendix, char* pFunctionName, D3D10_SHADER_MACRO* pDefines)
{
ComputeShader* cs = new ComputeShader();
if(cs && !cs->Init(
shaderFile,
blobFileAppendix,
pFunctionName,
pDefines,
mD3DDevice,
mD3DDeviceContext))
{
SAFE_DELETE(cs);
}
return cs;
} | [
"[email protected]"
] | |
d76a69c3cd16e676320020d583378058db218ae0 | e2a27aa5cb3b97a1ea99fe2467efdfb72da04304 | /OpinionDynamics/src/Sznajd.cpp | 2364daf197528ecfc9c720d8757fc9ae65736b55 | [] | no_license | ysjeong0601/OpinionDynamicsReproduce | ec4396cbedd807e5e6345f6dde8353d56363c8f1 | b443a65e348d72d167ed34a91a9565d3e0b275a1 | refs/heads/main | 2023-07-26T22:11:26.603625 | 2021-08-13T02:40:41 | 2021-08-13T02:40:41 | 392,857,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,670 | cpp | //
// Sznajd.cpp
// OpinionDynamics
//
// Created by 정연수 on 2021/08/06.
//
#include <iostream>
#include <random>
#include <string>
#include <queue>
#include <cmath>
#include "NetworkGenerator.hpp"
#include "Sznajd.hpp"
#define OPINION_A 1
#define OPINION_B -1
Sznajd::Sznajd(string __fileName){
// set file location
// project folder/result/data.txt
string dummyFileName = __fileName.append(".txt");
string folder = "result";
filePath = fs::current_path();
filePath/=folder;
if (!fs::exists(filePath)) {
fs::create_directory(filePath);
}
filePath /= dummyFileName;
}
Sznajd::Sznajd(Network& __network,string __fileStream) : Sznajd(__fileStream){
setNetwork(__network);
setFraction_A(0.5);
if (__network.isFullConnected() == true) {
cout << "complete network is not allowed";
exit(1);
}
}
void Sznajd::setNetwork(Network& __network){
this->network = &__network;
this->nodeVec = &__network.getNodeVector();
this->adjMxt = &__network.getAdjMtx();
setFraction_A(0.5);
}
void Sznajd::setFraction_A(double __fraction){
int init_A = __fraction * network->getTotalNumberofNode();
int assign_count = 0;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int> dis(0,(network->getTotalNumberofNode())-1);
n_A = 0;
n_B = 0;
for (Agent &node : *nodeVec) {
node.setOpinionState(OPINION_B);
n_B += 1;
}
while (assign_count != init_A) {
int node = dis(gen);
if (nodeVec->at(node).getOpinionState() == OPINION_B) {
nodeVec->at(node).setOpinionState(OPINION_A);
assign_count += 1;
n_A += 1;
n_B -= 1;
}
}
}
double Sznajd::getOpinionAverage(){
return abs((double)(n_A - n_B)/network->getTotalNumberofNode());
}
void Sznajd::run(int __time){
// check stream
if (!fileStream.is_open()) {
fileStream.open(filePath);
}
int step = 0;
int time = __time;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(0,network->getTotalNumberofNode()-1);
// write initial state
fileStream << step << " " << (double)n_A/network->getTotalNumberofNode() << " " << (double)n_B/network->getTotalNumberofNode() << " " << getOpinionAverage() <<"\n";
// initial state
// a row represents state of all node
int sNode1=0,sNode2=0;
while (step < time || (n_A == 0 || n_B == 0)) {
do {
sNode1 = dis(gen);
} while (nodeVec->at(sNode1).getDeg() == 0);
uniform_int_distribution<> dis2(0,(nodeVec->at(sNode1).getDeg())-1);
sNode2 = dis2(gen);
sNode2 = adjMxt->at(sNode1).at(sNode2);
// if two agents have different opinion
if (nodeVec->at(sNode1).getOpinionState() != nodeVec->at(sNode2).getOpinionState()) {
step++;
continue;
}
queue<int> queue;
// push all neighbors of agent 1 in queue
for (int &index : adjMxt->at(sNode1)) {
queue.push(index);
}
for (int &index : adjMxt->at(sNode2)) {
queue.push(index);
}
switch (nodeVec->at(sNode1).getOpinionState()) {
case OPINION_A:
while (!queue.empty()) {
int index = queue.front();
if (nodeVec->at(index).getOpinionState() == OPINION_B) {
nodeVec->at(index).setOpinionState(OPINION_A);
n_A += 1;
n_B -= 1;
}
queue.pop();
}
break;
case OPINION_B:
while (!queue.empty()) {
int index = queue.front();
if (nodeVec->at(index).getOpinionState() == OPINION_A) {
nodeVec->at(index).setOpinionState(OPINION_B);
n_A -= 1;
n_B += 1;
}
queue.pop();
}
break;
default:
cout << "exception occured\n";
break;
}
fileStream << step << " " << (double)n_A/network->getTotalNumberofNode() << " " << (double)n_B/network->getTotalNumberofNode() << " " << getOpinionAverage() <<"\n";
if (n_A == 0 || n_B == 0) {
break;
}
step++;
} // while(step<time) end
fileStream.close();
}
Sznajd::~Sznajd(){
}
| [
"[email protected]"
] | |
3d7c8c86f894ec99a1590c5b2d68a78def0fc2a6 | 5ec675243f0e34ab7e44c61f67a4a1b8bb810882 | /MyProject/Middlewares/ST/touchgfx/framework/source/touchgfx/containers/scrollers/ScrollWheelWithSelectionStyle.cpp | 34a9fe249f00f7b29bf1ce1d370ac1f08a3473f9 | [
"MIT"
] | permissive | wowawhite/TouchGFX_Template | a38c8280c498ce73a816eb1164556518a6c8c1b4 | b0b80c936aff7216e312db06672e7fcdf577c03d | refs/heads/master | 2021-05-17T15:31:47.315808 | 2020-03-28T19:49:51 | 2020-03-28T19:49:51 | 250,846,502 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,300 | cpp | /**
******************************************************************************
* This file is part of the TouchGFX 4.13.0 distribution.
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include <touchgfx/containers/scrollers/ScrollWheelWithSelectionStyle.hpp>
namespace touchgfx
{
ScrollWheelWithSelectionStyle::ScrollWheelWithSelectionStyle()
: ScrollWheelBase(),
drawablesInFirstList(0),
extraSizeBeforeSelectedItem(0),
extraSizeAfterSelectedItem(0),
marginBeforeSelectedItem(0),
marginAfterSelectedItem(0),
drawables(0),
centerDrawables(0),
originalUpdateDrawableCallback(0),
originalUpdateCenterDrawableCallback(0)
{
ScrollWheelBase::add(list2);
ScrollWheelBase::add(list1); // Put center list at top of the first/last list.
}
void ScrollWheelWithSelectionStyle::setWidth(int16_t width)
{
ScrollWheelBase::setWidth(width);
if (getHorizontal())
{
refreshDrawableListsLayout();
}
}
void ScrollWheelWithSelectionStyle::setHeight(int16_t height)
{
ScrollWheelBase::setHeight(height);
if (!getHorizontal())
{
refreshDrawableListsLayout();
}
}
void ScrollWheelWithSelectionStyle::setHorizontal(bool horizontal)
{
ScrollWheelBase::setHorizontal(horizontal);
list1.setHorizontal(horizontal);
list2.setHorizontal(horizontal);
refreshDrawableListsLayout();
}
void ScrollWheelWithSelectionStyle::setCircular(bool circular)
{
ScrollWheelBase::setCircular(circular);
list1.setCircular(circular);
list2.setCircular(circular);
}
void ScrollWheelWithSelectionStyle::setNumberOfItems(int16_t numberOfItems)
{
if (numberOfItems != getNumberOfItems())
{
ScrollWheelBase::setNumberOfItems(numberOfItems);
list1.setNumberOfItems(numberOfItems);
list2.setNumberOfItems(numberOfItems);
}
}
void ScrollWheelWithSelectionStyle::setSelectedItemOffset(int16_t offset)
{
ScrollWheelBase::setSelectedItemOffset(offset);
refreshDrawableListsLayout();
}
void ScrollWheelWithSelectionStyle::setSelectedItemExtraSize(int16_t extraSizeBefore, int16_t extraSizeAfter)
{
extraSizeBeforeSelectedItem = extraSizeBefore;
extraSizeAfterSelectedItem = extraSizeAfter;
refreshDrawableListsLayout();
}
int16_t ScrollWheelWithSelectionStyle::getSelectedItemExtraSizeBefore() const
{
return extraSizeBeforeSelectedItem;
}
int16_t ScrollWheelWithSelectionStyle::getSelectedItemExtraSizeAfter() const
{
return extraSizeAfterSelectedItem;
}
void ScrollWheelWithSelectionStyle::setSelectedItemMargin(int16_t marginBefore, int16_t marginAfter)
{
marginBeforeSelectedItem = marginBefore;
marginAfterSelectedItem = marginAfter;
refreshDrawableListsLayout();
}
int16_t ScrollWheelWithSelectionStyle::getSelectedItemMarginBefore() const
{
return marginBeforeSelectedItem;
}
int16_t ScrollWheelWithSelectionStyle::getSelectedItemMarginAfter() const
{
return marginAfterSelectedItem;
}
void ScrollWheelWithSelectionStyle::setSelectedItemPosition(int16_t offset, int16_t extraSizeBefore, int16_t extraSizeAfter, int16_t marginBefore, int16_t marginAfter)
{
setSelectedItemOffset(offset);
setSelectedItemExtraSize(extraSizeBefore, extraSizeAfter);
setSelectedItemMargin(marginBefore, marginAfter);
}
void ScrollWheelWithSelectionStyle::setDrawableSize(int16_t drawableSize, int16_t drawableMargin)
{
ScrollWheelBase::setDrawableSize(drawableSize, drawableMargin);
list1.setDrawableSize(drawableSize, drawableMargin);
list2.setDrawableSize(drawableSize, drawableMargin);
// Resize the three lists
setSelectedItemOffset(distanceBeforeAlignedItem);
// Changing the drawable size alters number of required drawables, so refresh this
refreshDrawableListsLayout();
}
void ScrollWheelWithSelectionStyle::setDrawables(DrawableListItemsInterface& drawableListItems, GenericCallback<DrawableListItemsInterface*, int16_t, int16_t>& updateDrawableCallback,
DrawableListItemsInterface& centerDrawableListItems, GenericCallback<DrawableListItemsInterface*, int16_t, int16_t>& updateCenterDrawableCallback)
{
drawables = &drawableListItems;
centerDrawables = ¢erDrawableListItems;
currentAnimationState = NO_ANIMATION;
originalUpdateDrawableCallback = &updateDrawableCallback;
originalUpdateCenterDrawableCallback = &updateCenterDrawableCallback;
refreshDrawableListsLayout();
setOffset(0);
}
void ScrollWheelWithSelectionStyle::setOffset(int32_t offset)
{
ScrollWheelBase::setOffset(offset);
list1.setOffset((distanceBeforeAlignedItem - (distanceBeforeAlignedItem - extraSizeBeforeSelectedItem)) + offset);
list2.setOffset((distanceBeforeAlignedItem - (distanceBeforeAlignedItem + itemSize + extraSizeAfterSelectedItem + marginAfterSelectedItem)) + offset);
}
void ScrollWheelWithSelectionStyle::itemChanged(int itemIndex)
{
ScrollWheelBase::itemChanged(itemIndex);
list1.itemChanged(itemIndex);
list2.itemChanged(itemIndex);
}
void ScrollWheelWithSelectionStyle::refreshDrawableListsLayout()
{
if (drawables != 0 && centerDrawables != 0)
{
int32_t currentOffset = getOffset();
int16_t list1Pos = distanceBeforeAlignedItem - extraSizeBeforeSelectedItem;
int16_t list2Pos = distanceBeforeAlignedItem + itemSize + (extraSizeAfterSelectedItem + marginAfterSelectedItem);
int16_t list0Size = list1Pos - marginBeforeSelectedItem;
int16_t list1Size = itemSize + extraSizeBeforeSelectedItem + extraSizeAfterSelectedItem;
if (getHorizontal())
{
int16_t list2Size = getWidth() - list2Pos;
list.setPosition(0, 0, list0Size, getHeight());
list1.setPosition(list1Pos, 0, list1Size, getHeight());
list2.setPosition(list2Pos, 0, list2Size, getHeight());
}
else
{
int16_t list2Size = getHeight() - list2Pos;
list.setPosition(0, 0, getWidth(), list0Size);
list1.setPosition(0, list1Pos, getWidth(), list1Size);
list2.setPosition(0, list2Pos, getWidth(), list2Size);
}
list.removeAll();
list1.removeAll();
list2.removeAll();
list.setDrawables(*drawables, 0, *originalUpdateDrawableCallback);
drawablesInFirstList = list.getNumberOfDrawables();
list1.setDrawables(*centerDrawables, 0, *originalUpdateCenterDrawableCallback);
list2.setDrawables(*drawables, drawablesInFirstList, *originalUpdateDrawableCallback);
setOffset(keepOffsetInsideLimits(currentOffset, 0));
}
}
} // namespace touchgfx
| [
"wowa@wowa-desktopL"
] | wowa@wowa-desktopL |
2b9f893ee7e125ca96cbd5981f4b091d53da605d | 40b41de2be14344aa4a04f20ff648714f3bd6b11 | /DeathEater/DeathEater.ino | b70636e1e1574be60ae1ff548838b96c3e66b04f | [] | no_license | MattWis/Bewitched_Galleons | bee8a3a9813bbb4c98a2d2d52df42575722a2192 | 7ebeda9078bf8de947a458a6c6a4280636c87724 | refs/heads/master | 2016-09-05T17:17:49.735878 | 2013-12-08T14:22:42 | 2013-12-08T14:22:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,597 | ino | #include <SPI.h>
#include <RF22.h>
// Singleton instance of the radio
RF22 rf22;
//set pins
int transistor = 3;
int thermistor = A0;
int motorRight = 5; //pwm
int motorLeft = 6; //pwm
//constants
int tooHot = 200; //temperature/resistance threshhold
int timeToTurn;
bool message = false;
bool firstMotor = false;
bool secondMotor = false;
bool heating = false;
uint8_t buf[RF22_MAX_MESSAGE_LEN];
//timing variables
unsigned long lastTimeIdle;
unsigned long lastTimeRx;
unsigned long turnTime;
void setup()
{
pinMode(transistor, OUTPUT);
pinMode(thermistor, INPUT);
digitalWrite(transistor, LOW);
Serial.begin(9600);
if (!rf22.init())
Serial.println("RF22 init failed");
// Defaults after init are 434.0MHz, 0.05MHz AFC pull-in, modulation FSK_Rb2_4Fd36
rf22.setModeIdle();
lastTimeIdle = millis();
}
//tries to read for 10 seconds
void loop() {
if (abs(lastTimeIdle - millis()) > 50000) {
rf22.setModeRx();
lastTimeIdle = 0;
lastTimeRx = millis();
}
if ((abs(lastTimeRx - millis()) < 10000) && message == false) {
if (rf22.available()) {
uint8_t len = sizeof(buf);
if (rf22.recv(buf, &len)) {
message = true;
firstMotor = true;
turnTime= millis();
Serial.println((char*)buf);
}
}
}
if (message == true) {
if(firstMotor) {
turnTime = turnMotorClockWise(buf[0]);
if (motorDone()) {
firstMotor = false;
secondMotor = true;
turnTime = millis();
}
}
if (secondMotor) {
turnTime = turnMotorCounter(buf[1], buf[2]);
if (motorDone()) {
secondMotor = false;
heating = true;
}
}
if (heating) {
heat();
if (heatingDone()) {
heating = false;
lastTimeIdle = millis();
rf22.setModeIdle();
}
}
}
}
int turnMotorClockWise(uint8_t daysFrom) {
analogWrite(motorRight, 10);
digitalWrite(motorLeft, LOW);
return 500 * (int) daysFrom;
}
int turnMotorCounter(uint8_t hourOf, uint8_t minuteOf) {
analogWrite(motorLeft, 10);
digitalWrite(motorRight, LOW);
return 125*(((int) hourOf * 4) + (int) minuteOf);
}
bool motorDone() {
if (abs(turnTime - millis()) > timeToTurn) {
digitalWrite(motorRight, LOW);
digitalWrite(motorLeft, LOW);
return true;
}
return false;
}
void heat() {
digitalWrite(transistor, HIGH);
}
bool heatingDone() {
if (analogRead(thermistor) < tooHot) {
//as temperature increases, analog read decreases
digitalWrite(transistor, LOW);
return true;
} else {
return false;
}
}
| [
"[email protected]"
] | |
fa1960ee813f39d03abdd8a14ce3556923dc0a71 | ac34cad5e20b8f46c0b0aa67df829f55ed90dcb6 | /src/ballistica/base/input/device/test_input.cc | 7e20a291f9d592c281055868c01e32a7c5d2bf3c | [
"MIT"
] | permissive | sudo-logic/ballistica | fd3bf54a043717f874b71f4b2ccd551d61c65008 | 9aa73cd20941655e96b0e626017a7395ccb40062 | refs/heads/master | 2023-07-26T19:52:06.113981 | 2023-07-12T21:32:56 | 2023-07-12T21:37:46 | 262,056,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,891 | cc | // Released under the MIT License. See LICENSE for details.
#include "ballistica/base/input/device/test_input.h"
#include "ballistica/base/input/device/joystick_input.h"
#include "ballistica/base/input/input.h"
#include "ballistica/core/platform/support/min_sdl.h"
#include "ballistica/shared/math/random.h"
namespace ballistica::base {
TestInput::TestInput() {
joystick_ = Object::NewDeferred<JoystickInput>(-1, // not an sdl joystick
"TestInput", // device name
false, // allow configuring?
false); // calibrate?;
g_base->input->PushAddInputDeviceCall(joystick_, true);
}
TestInput::~TestInput() {
g_base->input->PushRemoveInputDeviceCall(joystick_, true);
}
void TestInput::Reset() {
assert(g_core->InMainThread());
reset_ = true;
}
void TestInput::HandleAlreadyPressedTwice() {
if (print_already_did2_) {
print_already_did2_ = false;
}
}
void TestInput::Process(millisecs_t time) {
assert(g_core->InMainThread());
if (reset_) {
reset_ = false;
join_end_time_ = time + 7000; // do joining for the next few seconds
join_start_time_ = time + 1000;
join_press_count_ = 0;
print_non_join_ = true;
print_already_did2_ = true;
}
if (print_non_join_ && time >= join_end_time_) {
print_non_join_ = false;
}
if (time > next_event_time_) {
next_event_time_ = time + static_cast<int>(RandomFloat() * 300.0f);
// Do absolutely nothing before join start time.
if (time < join_start_time_) {
return;
}
float r = RandomFloat();
SDL_Event e;
if (r < 0.5f) {
// Movement change.
r = RandomFloat();
if (r < 0.3f) {
lr_ = ud_ = 0;
} else {
lr_ = std::max(
-32767,
std::min(32767,
static_cast<int>(-50000.0f + 100000.0f * RandomFloat())));
ud_ = std::max(
-32767,
std::min(32767,
static_cast<int>(-50000.0f + 100000.0f * RandomFloat())));
}
e.type = SDL_JOYAXISMOTION;
e.jaxis.axis = 0;
e.jaxis.value = static_cast_check_fit<int16_t>(ud_);
g_base->input->PushJoystickEvent(e, joystick_);
e.jaxis.axis = 1;
e.jaxis.value = static_cast_check_fit<int16_t>(lr_);
g_base->input->PushJoystickEvent(e, joystick_);
} else {
// Button change.
r = RandomFloat();
if (r > 0.75f) {
// Jump:
// Don't do more than 2 presses while joining.
if (!jump_pressed_ && time < join_end_time_ && join_press_count_ > 1) {
HandleAlreadyPressedTwice();
} else {
jump_pressed_ = !jump_pressed_;
if (jump_pressed_) {
join_press_count_++;
}
e.type = jump_pressed_ ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
e.jbutton.button = 0;
g_base->input->PushJoystickEvent(e, joystick_);
}
} else if (r > 0.5f) {
// Bomb:
// Don't do more than 2 presses while joining.
if (!bomb_pressed_ && time < join_end_time_ && join_press_count_ > 1) {
HandleAlreadyPressedTwice();
} else {
bomb_pressed_ = !bomb_pressed_;
// This counts as a join press *only* if its the first.
// (presses after that simply change our character)
if (join_press_count_ == 0 && bomb_pressed_) {
// cout << "GOT BOMB AS FIRST PRESS " << this << endl;
join_press_count_++;
}
e.type = bomb_pressed_ ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
e.jbutton.button = 2;
g_base->input->PushJoystickEvent(e, joystick_);
}
} else if (r > 0.25f) {
// Grab:
// Don't do more than 2 presses while joining.
if (!pickup_pressed_ && time < join_end_time_
&& join_press_count_ > 1) {
HandleAlreadyPressedTwice();
} else {
pickup_pressed_ = !pickup_pressed_;
if (pickup_pressed_) {
join_press_count_++;
}
e.type = pickup_pressed_ ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
e.jbutton.button = 3;
g_base->input->PushJoystickEvent(e, joystick_);
}
} else {
// Punch:
// Don't do more than 2 presses while joining.
if (!punch_pressed_ && time < join_end_time_ && join_press_count_ > 1) {
HandleAlreadyPressedTwice();
} else {
punch_pressed_ = !punch_pressed_;
if (punch_pressed_) {
join_press_count_++;
}
e.type = punch_pressed_ ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
e.jbutton.button = 1;
g_base->input->PushJoystickEvent(e, joystick_);
}
}
}
}
}
} // namespace ballistica::base
| [
"[email protected]"
] | |
556f6552f2c462a2679053ae6ea249536ebce7da | a301c745ff8409cc619bd5c251047d2b09180ed9 | /amlogic/sensors/mpu3050/invensense/hardware/MPLGesture.cpp | 5e65a93dfebae38cb5213e31f76a2a00e266cb39 | [
"Apache-2.0"
] | permissive | fards/ainol_elfii_hardware | b17e5046e1d4b9acd9ecdc93083566b616c27138 | 59cf37b6aa1c6c4320891929234b477a36785e3b | refs/heads/master | 2021-01-22T23:54:15.252915 | 2012-08-25T15:13:20 | 2012-08-25T15:13:20 | 5,587,197 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,492 | cpp | /*
* Copyright (C) 2011 Invensense, Inc.
*
* 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.
*/
#define LOG_NDEBUG 0
#include "MPLSensor.h"
#include "ml.h"
#include "mlFIFO.h"
#include "mlsl.h"
#include "mlos.h"
#include "ml_mputest.h"
#include "ml_stored_data.h"
#include "mpu.h"
extern "C" {
#include "mlsupervisor.h"
}
#include "mlsupervisor_9axis.h"
#include "gesture.h"
#include "mlcontrol.h"
#include "orientation.h"
#include "mlpedometer_fullpower.h"
#include "mlpedometer_lowpower.h"
//#include "pedometer.h"
#include "mlglyph.h"
#include "mldl_cfg.h"
#include "mldl.h"
#include "mlFIFO.h"
extern "C" {
void initMPL();
void setupCallbacks();
void setupFIFO();
void cb_onMotion(uint16_t);
void cb_onMotion_gest(uint16_t);
void cb_onGesture(gesture_t* gesture);
void cb_onOrientation(uint16_t orientation);
void cb_onGridMove(unsigned short ctlSig, long *gNum, long *gChg);
void cb_onStep(uint16_t);
void cb_onStep_fp(unsigned long, unsigned long);
void cb_procData();
void set_power_states(int, bool);
void log_sys_api_addr();
void setupPed_fp();
void setupGestures();
void setupGlyph();
tMLError MLDisableGlyph(void);
}
#define EXTRA_VERBOSE (1)
#define FUNC_LOG LOGV("%s", __PRETTY_FUNCTION__)
#define VFUNC_LOG LOGV_IF(EXTRA_VERBOSE, "%s", __PRETTY_FUNCTION__)
sensors_event_t* output_gesture_list;
extern uint32_t* s_enabledMask;
extern uint32_t* s_pendingMask;
extern struct stepParams s_step_params;
extern long s_ped_steps; //pedometer steps recorded
extern long s_ped_wt;
extern bool s_sys_ped_enabled; //flag indicating if the sys-api ped is enabled
#define PITCH_SHAKE 0x01
#define ROLL_SHAKE 0x02
#define YAW_SHAKE 0x04
#define TAP 0x08
#define YAW_IMAGE_ROTATE 0x10
#define ORIENTATION 0x20
#define MOTION 0x40
#define GRID_NUM 0x80
#define GRID_CHANGE 0x100
#define CONTROL_SIG 0x200
#define STEP 0x400
#define SNAP 0x800
/** setup the pedometer engine.
* this function should only be called when the mpld thread holds the mpld_mutex
*/
/*void setupPed()
{
tMLError result;
result = MLEnablePedometer();
if (result != ML_SUCCESS) {
LOGE("Fatal error: MLEnablePedometer returned %d\n",result);
}
result = MLPedometerSetDataRate(6);
if (result != ML_SUCCESS) {
LOGE("Fatal error: MLPedometerSetDataRate returned %d\n",result);
}
result = MLClearNumOfSteps();
if(result != ML_SUCCESS) LOGE("MLClearNumOfSteps fail (%d)", result);
result = MLSetStepCallback( cb_onStep );
if (result != ML_SUCCESS) {
LOGE("Fatal error: MLSetStepCallback returned %d\n",result);
}
}*/
/* struct used to store gesture parameters. copied from MPL apps */
struct gparams {
/* Tap Params */
int xTapThreshold;
int yTapThreshold;
int zTapThreshold;
int tapTime;
int nextTapTime;
int maxTaps;
float shakeRejectValue;
/* Shake Params */
int xShakeThresh;
int yShakeThresh;
int zShakeThresh;
int xSnapThresh;
int ySnapThresh;
int zSnapThresh;
int shakeTime;
int nextShakeTime;
int shakeFunction;
int maxShakes;
/* Yaw rotate params */
int yawRotateTime;
int yawRotateThreshold;
};
struct gparams params = {
xTapThreshold: 100,
yTapThreshold: 100,
zTapThreshold: 100,
tapTime: 100,
nextTapTime: 600,
maxTaps: 2,
shakeRejectValue: 0.8f,
xShakeThresh: 750,
yShakeThresh: 750,
zShakeThresh: 750,
xSnapThresh: 160,
ySnapThresh: 320,
zSnapThresh: 160,
shakeTime: 400,
nextShakeTime: 1000,
shakeFunction: 0,
maxShakes: 3,
yawRotateTime: 150,
yawRotateThreshold: 60,
};
/**
* apply the parameters stored in the params struct and enable other 'gesture' data
* (control, etc.)
*/
void setupGestures() {
VFUNC_LOG;
tMLError result;
result = MLEnableGesture();
if (result != ML_SUCCESS) {
LOGE("Fatal error: MLEnableGesture returned %d\n",result);
}
result = MLSetGestureCallback(cb_onGesture);
if (result != ML_SUCCESS) {
LOGE("Fatal error: MLSetGestureCallback returned %d\n",result);
}
result = MLSetGestures(ML_GESTURE_ALL);
if (result != ML_SUCCESS) {
LOGE("Fatal error: MLSetGestures returned %d\n",result);
}
result = MLSetTapThreshByAxis(ML_TAP_AXIS_X, params.xTapThreshold);
if (result != ML_SUCCESS) {
LOGE("MLSetTapThreshByAxis returned :%d\n",result);
}
result = MLSetTapThreshByAxis(ML_TAP_AXIS_Y, params.yTapThreshold);
if (result != ML_SUCCESS) {
LOGE("MLSetTapThreshByAxis returned :%d\n",result);
}
result = MLSetTapThreshByAxis(ML_TAP_AXIS_Z, params.zTapThreshold);
if (result != ML_SUCCESS) {
LOGE("MLSetTapThreshByAxis returned :%d\n",result);
}
result = MLSetTapTime(params.tapTime);
if (result != ML_SUCCESS) {
LOGE("MLSetTapTime returned :%d\n",result);
}
result = MLSetNextTapTime(params.nextTapTime);
if (result != ML_SUCCESS) {
LOGE("MLSetNextTapTime returned :%d\n",result);
}
result = MLSetMaxTaps(params.maxTaps);
if (result != ML_SUCCESS) {
LOGE("MLSetMaxTaps returned :%d\n",result);
}
result = MLSetTapShakeReject(params.shakeRejectValue);
if (result != ML_SUCCESS) {
LOGE("MLSetTapShakeReject returned :%d\n",result);
}
//Set up shake gesture
result = MLSetShakeFunc(params.shakeFunction);
if (result != ML_SUCCESS) {
LOGE("MLSetShakeFunc returned :%d\n",result);
}
result = MLSetShakeThresh(ML_ROLL_SHAKE, params.xShakeThresh);
if (result != ML_SUCCESS) {
LOGE("MLSetShakeThresh returned :%d\n",result);
}
result = MLSetShakeThresh(ML_PITCH_SHAKE, params.yShakeThresh);
if (result != ML_SUCCESS) {
LOGE("MLSetShakeThresh returned :%d\n",result);
}
result = MLSetShakeThresh(ML_YAW_SHAKE, params.zShakeThresh);
if (result != ML_SUCCESS) {
LOGE("MLSetShakeThresh returned :%d\n",result);
}
result = MLSetShakeTime(params.shakeTime);
if (result != ML_SUCCESS) {
LOGE("MLSetShakeTime returned :%d\n",result);
}
result = MLSetNextShakeTime(params.nextShakeTime);
if (result != ML_SUCCESS) {
LOGE("MLSetNextShakeTime returned :%d\n",result);
}
result = MLSetMaxShakes(ML_SHAKE_ALL,params.maxShakes);
if (result != ML_SUCCESS) {
LOGE("MLSetMaxShakes returned :%d\n",result);
}
// Yaw rotate settings
result = MLSetYawRotateTime(params.yawRotateTime);
if (result != ML_SUCCESS) {
LOGE("MLSetYawRotateTime returned :%d\n",result);
}
result = MLSetYawRotateThresh(params.yawRotateThreshold);
if (result != ML_SUCCESS) {
LOGE("MLSetYawRotateThresh returned :%d\n",result);
}
#define CHK_RES {if(result != ML_SUCCESS) LOGE("unexpected mpl failure %d at line %d",result, __LINE__);}
//Orientation is lumped in with gestures
result = MLEnableOrientation(); CHK_RES;
result = MLSetOrientations(ML_ORIENTATION_ALL);CHK_RES;
result = MLSetOrientationCallback(cb_onOrientation);CHK_RES;
//Control is also a 'gesture'
result = MLSetGridCallback(cb_onGridMove);CHK_RES;
result = MLSetControlData(ML_CONTROL_1, ML_ANGULAR_VELOCITY, ML_ROLL);CHK_RES;
result = MLSetControlData(ML_CONTROL_2, ML_ANGULAR_VELOCITY, ML_PITCH);CHK_RES;
result = MLSetControlData(ML_CONTROL_3, ML_ANGULAR_VELOCITY, ML_PITCH);CHK_RES;
result = MLSetControlData(ML_CONTROL_4, ML_ANGULAR_VELOCITY, ML_YAW);CHK_RES;
result = MLSetControlSensitivity(ML_CONTROL_1, 50);CHK_RES;
result = MLSetControlSensitivity(ML_CONTROL_2, 50);CHK_RES;
result = MLSetControlSensitivity(ML_CONTROL_3, 150);CHK_RES;
result = MLSetControlSensitivity(ML_CONTROL_4, 150);CHK_RES;
result = MLSetGridThresh(ML_CONTROL_1, 100000);CHK_RES;
result = MLSetGridThresh(ML_CONTROL_2, 100000);CHK_RES;
result = MLSetGridThresh(ML_CONTROL_3, 1000);CHK_RES;
result = MLSetGridThresh(ML_CONTROL_4, 1000);CHK_RES;
result = MLSetGridMax(ML_CONTROL_1, 120);CHK_RES;
result = MLSetGridMax(ML_CONTROL_2, 120);CHK_RES;
result = MLSetGridMax(ML_CONTROL_3, 3);CHK_RES;
result = MLSetGridMax(ML_CONTROL_4, 3);CHK_RES;
result = MLSetControlFunc( ML_GRID | ML_HYSTERESIS);CHK_RES;
// Enable Control.
result = MLEnableControl();CHK_RES;
FIFOSendControlData(ML_ALL,ML_32_BIT); //enable control should do this
}
void setupGlyph()
{
VFUNC_LOG;
tMLError result;
result = MLSetControlData(ML_CONTROL_3, ML_ANGULAR_VELOCITY, ML_PITCH); CHK_RES;
result = MLSetControlData(ML_CONTROL_4, ML_ANGULAR_VELOCITY, ML_YAW); CHK_RES;
result = MLSetControlSensitivity(ML_CONTROL_3, 150); CHK_RES;
result = MLSetControlSensitivity(ML_CONTROL_4, 150); CHK_RES;
result = MLSetGridThresh(ML_CONTROL_3, 1000); CHK_RES;
result = MLSetGridThresh(ML_CONTROL_4, 1000); CHK_RES;
result = MLSetGridMax(ML_CONTROL_3, 3); CHK_RES;
result = MLSetGridMax(ML_CONTROL_4, 3); CHK_RES;
result = MLSetControlFunc( ML_HYSTERESIS | ML_GRID ); CHK_RES;
//Set up glyph recognition
result = MLEnableGlyph(); CHK_RES;
result = MLSetGlyphSpeedThresh(10); CHK_RES;
result = MLSetGlyphProbThresh(64); CHK_RES;
}
/**
* utility function for putting mpl data into our local data struct
*/
void store_gest(sensors_event_t* dest, gesture_t* src) {
int *int_ary = (int*)dest->data;
int_ary[0] = src->type;
int_ary[1] = src->strength;
int_ary[2] = src->speed;
int_ary[3] = src->num;
int_ary[4] = src->meta;
int_ary[5] = src->reserved;
}
/**
* handle gesture data returned from the MPL.
*/
void cb_onGesture(gesture_t* gesture)
{
#ifdef ENABLE_GESTURE_MANAGER
LOGD("gesture callback (type: %d)", gesture->type);
switch (gesture->type)
{
case ML_TAP:
{
if(*s_enabledMask & (1<<MPLSensor::Tap)) {
store_gest(output_gesture_list+MPLSensor::Tap ,gesture);
*s_pendingMask |= (1<<MPLSensor::Tap);
LOGD("stored TAP");
}
}
break;
case ML_ROLL_SHAKE:
case ML_PITCH_SHAKE:
case ML_YAW_SHAKE:
{
if(gesture->strength == 1 && gesture->num == 1) {
if(*s_enabledMask & (1<<MPLSensor::Snap)) {
store_gest(&(output_gesture_list[MPLSensor::Snap]), gesture);
*s_pendingMask |= (1<<MPLSensor::Snap);
}
}
if(*s_enabledMask & (1<<MPLSensor::Shake)) {
store_gest(&(output_gesture_list[MPLSensor::Shake]), gesture);
*s_pendingMask |= (1<<MPLSensor::Shake);
LOGD("stored SHAKE");
} else {
LOGD("SHAKE ignored");
}
}
break;
case ML_YAW_IMAGE_ROTATE:
{
if(*s_enabledMask & (1<<MPLSensor::YawIR)) {
store_gest(&(output_gesture_list[MPLSensor::YawIR]),gesture);
*s_pendingMask |= (1<<MPLSensor::YawIR);
}
}
break;
default:
LOGE("Unknown Gesture received\n");
break;
}
#endif
}
/**
* handle Orientation output from MPL
*/
void cb_onOrientation(uint16_t orientation) {
#ifdef ENABLE_GESTURE_MANAGER
if(*s_enabledMask & (1<<MPLSensor::Orient6)) {
//((int*)(output_gesture_list[MPLSensor::Orient6].data))[0] = ORIENTATION;
((int*)(output_gesture_list[MPLSensor::Orient6].data))[0] = orientation;
output_gesture_list[MPLSensor::Orient6].sensor = MPLSensor::Orient6;
*s_pendingMask |= (1<<MPLSensor::Orient6);
LOGD("stored ORIENTATION");
}
#endif
}
/**
* handle control events and generate associated output gestures
*/
void cb_onGridMove(unsigned short ctlSig, long *gNum, long *gChg) {
#ifdef ENABLE_GESTURE_MANAGER
//LOGD("%s", __FUNCTION__);
int cs[4];
int c[4];
int d[4];
//MLGetControlData(cs, d, c);
if(*s_enabledMask & (1<<MPLSensor::CtrlSig)) {
//((int*)(output_gesture_list[MPLSensor::CtrlSig].data))[0] = CONTROL_SIG;
((int*)(output_gesture_list[MPLSensor::CtrlSig].data))[0] = ctlSig;//cs[0];
output_gesture_list[MPLSensor::CtrlSig].sensor = MPLSensor::CtrlSig;
*s_pendingMask |= (1<<MPLSensor::CtrlSig);
LOGD_IF(EXTRA_VERBOSE, "stored CONTROL_SIG");
LOGV_IF(EXTRA_VERBOSE, "mPendingEvents = %x", *s_pendingMask);
}
if(*s_enabledMask & (1<<MPLSensor::GridNum)) {
//((int*)(output_gesture_list[MPLSensor::GridNum].data))[0] = GRID_NUM;
((int*)(output_gesture_list[MPLSensor::GridNum].data))[0] = gNum[0]; //d[0];
((int*)(output_gesture_list[MPLSensor::GridNum].data))[1] = gNum[1]; //d[1];
((int*)(output_gesture_list[MPLSensor::GridNum].data))[2] = gNum[2]; //d[2];
((int*)(output_gesture_list[MPLSensor::GridNum].data))[3] = gNum[3]; //d[3];
output_gesture_list[MPLSensor::GridNum].sensor = MPLSensor::GridNum;
*s_pendingMask |= (1<<MPLSensor::GridNum);
LOGD_IF(EXTRA_VERBOSE, "stored GRID_NUM");
LOGV_IF(EXTRA_VERBOSE, "mPendingEvents = %x", *s_pendingMask);
}
if(*s_enabledMask & (1<<MPLSensor::GridDelta)) {
//((int*)(output_gesture_list[MPLSensor::GridDelta].data))[0] = GRID_CHANGE;
((int*)(output_gesture_list[MPLSensor::GridDelta].data))[0] = gChg[0]; //c[0];
((int*)(output_gesture_list[MPLSensor::GridDelta].data))[1] = gChg[1]; //c[1];
((int*)(output_gesture_list[MPLSensor::GridDelta].data))[2] = gChg[2]; //c[2];
((int*)(output_gesture_list[MPLSensor::GridDelta].data))[3] = gChg[3]; //c[3];
output_gesture_list[MPLSensor::GridDelta].sensor = MPLSensor::GridDelta;
*s_pendingMask |= (1<<MPLSensor::GridDelta);
LOGD_IF(EXTRA_VERBOSE, "stored GRID_CHANGE");
LOGV_IF(EXTRA_VERBOSE, "mPendingEvents = %x", *s_pendingMask);
}
#endif
}
void cb_onStep(uint16_t val)
{
#ifdef ENABLE_GESTURE_MANAGER
if(*s_enabledMask & (1<<MPLSensor::Step)) {
//((int*)(output_gesture_list[MPLSensor::Step].data))[0] = STEP;
((int*)(output_gesture_list[MPLSensor::Step].data))[0] = val;
output_gesture_list[MPLSensor::Step].sensor = MPLSensor::Step;
*s_pendingMask |= (1<<MPLSensor::Step);
LOGD("stored STEP");
}
#endif
}
void cb_onMotion_gest(uint16_t val)
{
#ifdef ENABLE_GESTURE_MANAGER
if(*s_enabledMask & (1<<MPLSensor::Motion)) {
//((int*)(output_gesture_list[MPLSensor::Motion].data))[0] = MOTION;
((int*)(output_gesture_list[MPLSensor::Motion].data))[0] = val;
output_gesture_list[MPLSensor::Motion].sensor = MPLSensor::Motion;
*s_pendingMask |= (1<<MPLSensor::Motion);
LOGD("stored MOTION");
}
#endif
}
| [
"marcelo@marchtpc.(none)"
] | marcelo@marchtpc.(none) |
1e787bf711feb688ce478746eeb53eac09398baf | a5c3e91f00ae8d0318077ec5db6e46dc44b2acd3 | /00000/00067. Add Binary.cpp | e53b7c390a646a4656fd5ac233d0b3cbdf394c86 | [] | no_license | badstyle319/Leetcode | 6cba801a1049d084ca47096535db0e239632c03a | de80b5a6fde18be409f12ed81c3c5803f7ef63d8 | refs/heads/master | 2023-01-21T06:45:29.604967 | 2023-01-19T02:11:34 | 2023-01-19T02:11:34 | 83,555,350 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | class Solution {
public:
string addBinary(string a, string b) {
int len = max((int)a.length(), (int)b.length());
if(a.length() < len)
a.insert(0, len-a.length(), '0');
if(b.length() < len)
b.insert(0, len-b.length(), '0');
string ans = "";
int carry = 0;
for(int i = len - 1; i >= 0; i--)
{
int sum = a[i] - '0' + b[i] - '0' + carry;
ans.insert(0, 1, sum % 2 + '0');
carry = sum / 2;
}
if(carry)
ans.insert(0, 1, '1');
return ans;
}
}; | [
"[email protected]"
] | |
413db9a20402738856a45616910dc58566e34039 | 38b0563d1e65dc9e85537ae05e388790bae8b37c | /coada cu char si ldi.cpp | 7450d486e0efc75244344437a96ba3e11c2e8dd7 | [] | no_license | StefanLazea/sddx | c110e2c843d15e92bc5fb134ceae6bc8768f06ee | 1c5a3461953c9f194112f02020c9a3a3e2408922 | refs/heads/master | 2022-01-12T21:11:42.220120 | 2019-07-01T09:01:29 | 2019-07-01T09:01:29 | 192,412,550 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,552 | cpp | #include <stdlib.h>
#include <stdio.h>
#pragma warning(disable:4996)
#include <string.h>
struct Comanda
{
int cod;
char* nume;
int numarProduse;
char** produse;
float suma;
};
struct nod {
Comanda info;
nod* next;
};
Comanda initComanda(int cod, const char* nume, int numarProduse, char** produse, float suma) {
Comanda c;
c.cod = cod;
c.nume = (char*)malloc(sizeof(char)*(strlen(nume) + 1));
strcpy(c.nume, nume);
c.numarProduse = numarProduse;
c.produse = (char**)malloc(sizeof(char*)*numarProduse);
for (int i = 0; i < numarProduse; i++){
c.produse[i] = (char*)malloc(sizeof(char)*(strlen(produse[i]) + 1));
}
for (int i = 0; i < numarProduse; i++) {
strcpy(c.produse[i], produse[i]);
}
c.suma = suma;
return c;
}
nod* adaugareInceput(nod* cap, Comanda c) {
nod* nou = (nod*)malloc(sizeof(nod));
nou->next = cap;
nou->info = initComanda(c.cod, c.nume, c.numarProduse, c.produse, c.suma);
return nou; //se realizeaza legatura prin apel
}
nod* adaugareFinal(nod*cap, Comanda c) {
if (cap) {
nod* t = cap;
while (t->next) {
t = t->next;
}
t->next = adaugareInceput(NULL, c); //ptr ca trebuie ca next sa duca la null
return cap; //returnez lista
}
else {
return adaugareInceput(NULL, c);
}
}
nod* pushStack(nod* stack, Comanda c) {
stack = adaugareInceput(stack, c);
return stack;
}
nod* pushQueue(nod* queue, Comanda c) {
queue = adaugareFinal(queue, c);
return queue;
}
Comanda popQueue(nod* &cap) {
if (cap) {
Comanda rez = initComanda(cap->info.cod, cap->info.nume, cap->info.numarProduse, cap->info.produse, cap->info.suma);
nod*temp = cap;
cap = cap->next;
free(temp->info.nume);
for (int i = 0; i < temp->info.numarProduse; i++) {
free(temp->info.produse[i]);
}
free(temp->info.produse);
free(temp);
return rez;
}
else {
return initComanda(-1, NULL, -1, NULL, -1);
}
}
Comanda popStack(nod* &cap) {
if (cap) {
Comanda rez = initComanda(cap->info.cod, cap->info.nume, cap->info.numarProduse, cap->info.produse, cap->info.suma);
nod* temp = cap;
cap = cap->next;
free(temp->info.nume);
for (int i = 0; i < temp->info.numarProduse; i++) {
free(temp->info.produse[i]);
}
free(temp->info.produse);
free(temp);
return rez;
}
else {
return initComanda(-1, NULL, -1, NULL, -1);
}
}
void afisareComanda(Comanda c) {
printf("comanda cu codul %d si denumirea %s, are %d produse:\n", c.cod, c.nume, c.numarProduse);
for (int i = 0; i < c.numarProduse; i++) {
printf("produsul %d: %s \n", i + 1, c.produse[i]);
}
}
void afisareLista(nod* cap) {
while (cap) {
afisareComanda(cap->info);
cap = cap->next;
}
}
struct nodDublu {
Comanda info;
nodDublu* prev;
nodDublu* next;
};
struct LDI {
nodDublu* first;
nodDublu* last;
};
nodDublu* creareNod(Comanda c, nodDublu* next, nodDublu* prev) {
nodDublu* nou = (nodDublu*)malloc(sizeof(nodDublu));
nou->info = initComanda(c.cod, c.nume, c.numarProduse, c.produse, c.suma);
nou->next = next;
nou->prev = prev;
return nou;
}
LDI adaugareInceputLDI(LDI lista, Comanda c) {
nodDublu * nou = creareNod(c, lista.first, NULL);
if (lista.first) {
lista.first->prev = nou;
lista.first = nou;
return lista;
}
else {
lista.first = nou;
lista.last = nou;
return lista;
}
}
void afisareListaInceputSfarsit(LDI lista) {
nodDublu * p = lista.first;
while (p) {
afisareComanda(p->info);
printf("\n");
p = p->next;
}
}
int isEmptyStack(nod *cap) {
return cap == NULL;
}
void main() {
const char *produse[3] = { "aragaz","frigider","cuptor" };
Comanda c = initComanda(100, "celmaimisto", 3, (char**)produse, 2000);
const char *produse2[3] = { "aragaz","frigider","cuptor" };
Comanda c2 = initComanda(100, "celmaimisto", 3, (char**)produse2, 190);
const char *produse3[3] = { "aragaz","frigider","cuptor" };
Comanda c3 = initComanda(100, "celmaimisto", 3, (char**)produse3, 311);
afisareComanda(c);
nod* coada = NULL;
coada = pushQueue(coada, c);
coada = pushQueue(coada, c2);
coada = pushQueue(coada, c3);
printf("\n***************\n");
LDI listaMaiMari;
listaMaiMari.first = NULL;
listaMaiMari.last = NULL;
LDI listaMici;
listaMici.first = NULL;
listaMici.last = NULL;
afisareLista(coada);
//nu merge
while (!isEmptyStack(coada)) {
if (coada->info.suma > 300) {
Comanda c = popQueue(coada);
listaMaiMari = adaugareInceputLDI(listaMaiMari, c);
}
else {
listaMici = adaugareInceputLDI(listaMici, c);
}
coada = coada->next;
}
printf("\n***************\n");
afisareListaInceputSfarsit(listaMaiMari);
} | [
"[email protected]"
] | |
8deb546ef9d16c3b7ff7973934fa41dfccf53169 | 71cb21b4c0b3e319efecf8dab8dde996f6a5ebc2 | /main.cpp | 47e69c9dd84399d96da93f3821b737ff058a6269 | [] | no_license | alaquitara/cs161 | f3d61ca48941ef33786c9b72f35121715167e6e9 | 69af326ecd871da044cb21b1e2f4906f19314a89 | refs/heads/master | 2021-01-20T21:15:45.501559 | 2016-07-20T21:53:45 | 2016-07-20T21:53:45 | 63,817,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 941 | cpp | //
// main.cpp
// enterNum
//
// Created by Alexander Laquitara on 6/11/15.
// Copyright (c) 2015 Alexander Laquitara. All rights reserved.
//
#include <iostream>
using namespace std;
void bigLittle (int i)
{
int inNum, counter;
double currentNum, min_val, max_val;
cout<< "how many nums?"<<endl;
cin>> inNum;
for (counter=1; counter <= inNum; counter++)
{
cout<< "input a number : " <<endl;
cin>>currentNum;
if(counter == 1)
(max_val= currentNum) && (min_val = currentNum);
if (currentNum >= max_val)
max_val = currentNum;
if(currentNum <= min_val)
min_val = currentNum;
if(counter ==inNum)
cout<<"The largest number is: "<< max_val<<" The smallest number is: "<<min_val<<endl;
}
}
int main()
{
int i;
bigLittle(i);
return 0;
}
| [
"[email protected]"
] | |
df2f0d8e9cf0dfc12871179f66f4acbee1e289f2 | f40f9ba28daec4a6102d836cb8ed579b912c7d06 | /demande_saisie_colonne.cpp | f3d005d4e2a381cc78929ffde7c3bfdc9daf3139 | [] | no_license | ThomasSNIR/Puissance4git | b5bcd67a8cf3c782845c416731d91486efd16650 | 530fdda8bed09e603eed0b0cfef74e44930132f0 | refs/heads/master | 2023-08-26T21:37:07.470328 | 2021-11-09T16:38:36 | 2021-11-09T16:38:36 | 425,874,359 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cpp | /*************************************************************
* Nom ............ : Thomas Caron
* Rôle ........... : Etudiant
* Auteur ......... : Thomas.CARON
* Date création .. :
* Version/Màj .... :
* Licence ........ : GPLv4
*************************************************************/
#include <iostream>
#include <declarations_structures.h>
#include <declarations_fonctions.h>
using namespace std;
int demande_saisie_colonne()
{
int colonne =0;
printf("Saisissez la colonne a laquelle vous voulez placer votre jeton :\n");
cin >> colonne;
return colonne;
}
| [
"[email protected]"
] | |
6509dc56f4cd57c7364fcf77c1d439c56cf32874 | 04132a0e5bb04c5df3c81b54aa90fae60fec6853 | /Data-Structures/Stacks/game-of-two-stacks.cpp | 0581a363f3ec05b7dde576ffafca9b544285eda7 | [
"MIT"
] | permissive | rajat19/Hackerrank | 9d7b8f7fb7ce6a78438f729823db34c83d3b199c | d261d8d3ec103a66674931121c3d6f05ef6571ed | refs/heads/master | 2022-11-11T03:15:04.032460 | 2022-10-30T16:12:24 | 2022-10-30T16:12:24 | 140,057,670 | 30 | 91 | MIT | 2022-10-30T16:12:24 | 2018-07-07T06:09:14 | C++ | UTF-8 | C++ | false | false | 855 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int g;
cin >> g;
for(int a0 = 0; a0 < g; a0++){
int n;
int m;
int x;
cin >> n >> m >> x;
vector<int> a(n);
for(int a_i = 0; a_i < n; a_i++){
cin >> a[a_i];
}
vector<int> b(m);
for(int b_i = 0; b_i < m; b_i++){
cin >> b[b_i];
}
int i=0, j=0, c=0;
while(x>0 && i<n && j<m) {
if(a[i] < b[j]) {
x-=a[i];
i++; c++;
}
else {
x-=b[j];
j++; c++;
}
}
while(x>0 && i<n) {
x-=a[i];
i++; c++;
}
while(x>0 && i<n) {
x-=a[i];
i++; c++;
}
cout<<c-1;
}
return 0;
}
| [
"[email protected]"
] | |
ef769e6feac3c749a343bd0374030e50c064bf38 | ef9f45769704fced7beefb0f20afc1f25f1024d4 | /printTheElementsOfALinkedlist.cpp | eeb1c4e2af8fbbe0f04107845b3b4da137a5a849 | [] | no_license | YogaVicky/Hackerrank-solutions | 4a517b0272d994807895123e1a5c3a95bd86d7ac | f5d8a3b5cb4ab3bbf7116391aa4c3de17d366bf8 | refs/heads/master | 2020-05-30T08:57:29.006496 | 2019-12-17T19:11:19 | 2019-12-17T19:11:19 | 189,629,279 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | cpp | #include<iostream>
#include<stdlib.h>
using namespace std;
struct node{
int data;
node *next;
};
node *head = NULL;
void insert(int data){
node *temp = (node *)malloc(sizeof(node));
temp->data = data;
temp->next = NULL;
if(head == NULL)
head = temp;
else{
node *thead = head;
while(thead->next != NULL)
thead = thead->next;
thead->next = temp;
}
}
void printList(){
node *thead = head;
while(thead != NULL){
cout<<thead->data<<endl;
thead = thead->next;
}
}
int main(){
int n , a , i;
cin>>n;
for(i=0;i<n;i++){
cin>>a;
insert(a);
}
printList();
return 0;
} | [
"[email protected]"
] | |
aed691fbbd49b311df81135dbfecd1a997a3e3e1 | da8ae98080ff729586bfeb4c11c52bd48327d06f | /Symbolic/src/terms/Sub.hpp | ddb8b84fbee522b348ab2d1cafe181274e3a4ade | [] | no_license | RhobanProject/SimLagrange | 24670ffbb99cfca0c0f365ab1476f68e0e9aa3cc | db62b31cbbe7ddb2da821e927531a3b1fc80d927 | refs/heads/master | 2021-01-10T15:27:39.338821 | 2018-07-01T19:36:56 | 2018-07-01T19:36:56 | 44,232,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,748 | hpp | #ifndef LEPH_SYMBOLIC_SUB_HPP
#define LEPH_SYMBOLIC_SUB_HPP
#include "Symbolic/src/BinaryFunction.hpp"
#include "Symbolic/src/terms/Minus.hpp"
namespace Leph {
namespace Symbolic {
/**
* Sub
*/
template <class T>
class Sub : public BinaryFunction<T,T,T>
{
public:
static inline typename Term<T>::TermPtr create(
typename Term<T>::TermPtr termLeft,
typename Term<T>::TermPtr termRight)
{
if (termLeft->toString() == BaseSymbol::zero()) {
return Minus<T>::create(termRight);
} else if (termRight->toString() == BaseSymbol::zero()) {
return termLeft;
} else {
return BinaryFunction<T,T,T>::checkCst(
new Sub<T>(termLeft, termRight));
}
}
virtual inline typename Term<T>::TermPtr computeSubstitution
(const BaseSymbol::BaseSymbolPtr& sym, const Any::Any& term)
{
typename Term<T>::TermPtr argLeft =
BinaryFunction<T,T,T>::_argLeft;
typename Term<T>::TermPtr argRight =
BinaryFunction<T,T,T>::_argRight;
typename Term<T>::TermPtr termLeft =
argLeft->computeSubstitution(sym, term);
typename Term<T>::TermPtr termRight =
argRight->computeSubstitution(sym, term);
return Sub<T>::create(termLeft, termRight);
}
protected:
Sub(const typename Term<T>::TermPtr& termLeft,
const typename Term<T>::TermPtr& termRight) :
BinaryFunction<T,T,T>(termLeft, termRight)
{
}
virtual inline std::string computeString()
{
return "(" + BinaryFunction<T,T,T>::_argLeft->toString()
+ ")-(" + BinaryFunction<T,T,T>::_argRight->toString() + ")";
}
virtual inline typename Term<T>::TermPtr computeDerivative
(const BaseSymbol::BaseSymbolPtr& sym)
{
typename Term<T>::TermPtr argLeft =
BinaryFunction<T,T,T>::_argLeft;
typename Term<T>::TermPtr argRight =
BinaryFunction<T,T,T>::_argRight;
typename Term<T>::TermPtr termLeft =
argLeft->derivate(sym);
typename Term<T>::TermPtr termRight =
argRight->derivate(sym);
return Sub<T>::create(termLeft, termRight);
}
virtual T computeEvaluation(const Bounder& bounder)
{
T left = BinaryFunction<T,T,T>::_argLeft->evaluate(bounder);
T right = BinaryFunction<T,T,T>::_argRight->evaluate(bounder);
return left - right;
}
};
}
}
#endif
| [
"[email protected]"
] | |
fea6f6e56097596c840b52b6fcf4eb429a39dbbc | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/third_party/blink/public/mojom/native_file_system/native_file_system_error.mojom-test-utils.h | 48c90443bfff6043a9581723428df7d3458adcee | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | h | // third_party/blink/public/mojom/native_file_system/native_file_system_error.mojom-test-utils.h is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_PUBLIC_MOJOM_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_ERROR_MOJOM_TEST_UTILS_H_
#define THIRD_PARTY_BLINK_PUBLIC_MOJOM_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_ERROR_MOJOM_TEST_UTILS_H_
#include "third_party/blink/public/mojom/native_file_system/native_file_system_error.mojom.h"
#include "third_party/blink/public/common/common_export.h"
namespace blink {
namespace mojom {
} // namespace mojom
} // namespace blink
#endif // THIRD_PARTY_BLINK_PUBLIC_MOJOM_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_ERROR_MOJOM_TEST_UTILS_H_ | [
"[email protected]"
] | |
5f3d3da207dffad2654be6653232884a28ad4fed | 66a265cf4a32e972fe2ddfc711ca9e128d817c36 | /URIbr/beginner/1004.cpp | ace0a9de6fe418e054c323c14c15494e2054e6fd | [] | no_license | danilogr/problems | 5f2ca5b9fd923e6c3a7e7cbf2b5b313e1de2a156 | c950fb5125047dd0bee5a3477134e13b0b54a1ce | refs/heads/master | 2021-01-17T11:39:01.036578 | 2013-11-26T01:47:57 | 2013-11-26T01:47:57 | 14,650,091 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 130 | cpp | #include <iostream>
using namespace std;
int main()
{
int a,b;
cin >>a >>b;
cout << "PROD = " <<a*b << endl;
return 0;
}
| [
"[email protected]"
] | |
90cf08839ba820c20af0119d19b46603603526e0 | a4c8c67ac6a91e76402ae6f7f053668b52629ed8 | /tests/CommandConfigTests.cpp | 0c2f1b7e5e8a217ec27a0b54c81ad3ad684ccabc | [] | no_license | joshfernandez/cmpt373_combatgame | 229cb9ba8bc06b90631faca4e6aa198f55a0733e | bc3094d20ab963b50c184ad2a036a0908cc82d97 | refs/heads/master | 2021-01-12T02:33:02.982661 | 2017-01-04T23:15:24 | 2017-01-04T23:15:24 | 78,059,742 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,045 | cpp | #include <gtest/gtest.h>
#include <../src/game-server/commands/CommandConfig.hpp>
class TestCommand : public Command {
public:
virtual std::unique_ptr<MessageBuilder>
execute(const gsl::span<std::string, -1> arguments, const PlayerInfo& player) override {
return nullptr;
}
};
class CommandConfigTest : public ::testing::Test {
protected:
virtual void SetUp() {
root["commands"] = commandNode;
}
YAML::Node root;
YAML::Node commandNode;
TestCommand testCommand;
void createCommandConfig(const std::string& name, const std::string& desc,
const std::string& usage, const std::vector<std::string>& bindings) {
YAML::Node configNode;
configNode["desc"] = desc;
configNode["usage"] = usage;
configNode["role"] = "user";
for (const auto& b : bindings) {
configNode["bindings"].push_back(b);
}
commandNode["command-" + name] = configNode;
};
};
TEST_F(CommandConfigTest, CreateFromNode) {
const std::string id = "test";
const std::string desc = "desc";
const std::string usage = "usage";
const std::string binding1 = "bind1";
createCommandConfig(id, desc, usage, {binding1});
CommandConfig config{root};
auto res = config.createInputBindingsForCommand(id, testCommand);
EXPECT_TRUE(res.getId() == id);
EXPECT_TRUE(res.getDescription() == desc);
EXPECT_TRUE(res.getUsage() == usage);
EXPECT_TRUE(res.getInputBindings().size() == 1);
EXPECT_TRUE(res.getInputBindings()[0] == binding1);
EXPECT_TRUE(res.getDescription() == config.getCommandDescription(id));
EXPECT_TRUE(res.getUsage() == config.getCommandUsage(id));
EXPECT_TRUE(res.getInputBindings() == config.getCommandInputBindings(id));
}
TEST_F(CommandConfigTest, InvalidCommandId) {
const std::string id = "notexist";
CommandConfig c{root};
EXPECT_DEATH(c.createInputBindingsForCommand(id, testCommand), ".*Command configuration doesn't exist for: " + id);
} | [
"[email protected]"
] | |
217edde7bf27565ab68aa297136867a82aa618d8 | 24146e5b09a792692d9acb9e82ba4fbd12af20ad | /src/ExtLib/MediaInfo/MediaInfo/Audio/File_Aac_GeneralAudio.cpp | 3c7654f3b67b9272ca6850cf2221fc9e3a71625d | [
"Zlib",
"curl",
"NCSA",
"BSD-2-Clause"
] | permissive | RocherKong/MPCBE | 846a0bdeaa92d37f93526b0be4d5325e0f360312 | 3a3a879aa4d71cfd23cab36d2e30b67f82e7b04e | refs/heads/master | 2020-06-10T07:39:51.502548 | 2017-11-29T05:35:40 | 2017-11-29T05:35:40 | 75,987,960 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,908 | cpp | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_AAC_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Aac.h"
#include "MediaInfo/Audio/File_Aac_GeneralAudio.h"
using namespace std;
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Infos
//***************************************************************************
//---------------------------------------------------------------------------
extern const int32u Aac_sampling_frequency[];
extern const char* Aac_audioObjectType(int8u audioObjectType);
extern const char* Aac_Format_Profile(int8u ID);
//---------------------------------------------------------------------------
static const char* Aac_id_syn_ele[8]=
{
"SCE - single_channel_element",
"CPE - channel_pair_element",
"CCE - coupling_channel_element",
"LFE - lfe_channel_element",
"DSE - data_stream_element",
"PCE - program_config_element",
"FIL - fill_element",
"END - End"
};
//---------------------------------------------------------------------------
static const char* Aac_window_sequence[4]=
{
"ONLY_LONG_SEQUENCE",
"LONG_START_SEQUENCE",
"EIGHT_SHORT_SEQUENCE",
"LONG_STOP_SEQUENCE"
};
//***************************************************************************
// Elements - Decoder configuration
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::GASpecificConfig ()
{
//Parsing
Element_Begin1("GASpecificConfig");
bool frameLengthFlag, dependsOnCoreCoder, extensionFlag;
Get_SB ( frameLengthFlag, "frameLengthFlag");
frame_length=frameLengthFlag==0?1024:960; Param_Info2(frame_length, " bytes");
Get_SB ( dependsOnCoreCoder, "dependsOnCoreCoder");
if (dependsOnCoreCoder)
Skip_S2(14, "coreCoderDelay");
Get_SB ( extensionFlag, "extensionFlag");
if (channelConfiguration==0)
program_config_element();
if (audioObjectType==06 || audioObjectType==20)
Skip_S1(3, "layerNr");
if (extensionFlag)
{
bool extensionFlag3;
if (audioObjectType==22)
{
Skip_S1( 5, "numOfSubFrame");
Skip_S2(11, "layer_length");
}
if (audioObjectType==17
|| audioObjectType==19
|| audioObjectType==20
|| audioObjectType==23)
{
Skip_SB( "aacSectionDataResilienceFlag");
Skip_SB( "aacScalefactorDataResilienceFlag");
Skip_SB( "aacSpectralDataResilienceFlag");
}
Get_SB ( extensionFlag3, "extensionFlag3");
if (extensionFlag3)
{
Skip_BS(Data_BS_Remain(), "Not implemented");
}
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::program_config_element()
{
Element_Begin1("program_config_element");
Ztring comment_field_data;
int8u Channels=0, Channels_Front=0, Channels_Side=0, Channels_Back=0, Channels_LFE=0;
int8u num_front_channel_elements, num_side_channel_elements, num_back_channel_elements, num_lfe_channel_elements, num_assoc_data_elements, num_valid_cc_elements, comment_field_bytes;
int8u audioObjectType_Temp, sampling_frequency_index_Temp;
Skip_S1(4, "element_instance_tag");
Get_S1 (2, audioObjectType_Temp, "object_type"); audioObjectType_Temp++; Param_Info1(Aac_audioObjectType(audioObjectType_Temp));
Get_S1 (4, sampling_frequency_index_Temp, "sampling_frequency_index"); Param_Info1(Aac_sampling_frequency[sampling_frequency_index_Temp]);
Get_S1 (4, num_front_channel_elements, "num_front_channel_elements");
Get_S1 (4, num_side_channel_elements, "num_side_channel_elements");
Get_S1 (4, num_back_channel_elements, "num_back_channel_elements");
Get_S1 (2, num_lfe_channel_elements, "num_lfe_channel_elements");
Get_S1 (3, num_assoc_data_elements, "num_assoc_data_elements");
Get_S1 (4, num_valid_cc_elements, "num_valid_cc_elements");
TEST_SB_SKIP( "mono_mixdown_present");
Skip_S1(4, "mono_mixdown_element_number");
TEST_SB_END();
TEST_SB_SKIP( "stereo_mixdown_present");
Skip_S1(4, "stereo_mixdown_element_number");
TEST_SB_END();
TEST_SB_SKIP( "matrix_mixdown_idx_present");
Skip_S1(2, "matrix_mixdown_idx");
Skip_SB( "pseudo_surround_enable");
TEST_SB_END();
bool front1_element_is_cpe=false;
if (!num_side_channel_elements && num_back_channel_elements && num_back_channel_elements<3) // Hack: e.g. in case of 5.1, 7.1
{
num_side_channel_elements=1;
num_back_channel_elements--;
}
for (int8u Pos=0; Pos<num_front_channel_elements; Pos++)
{
Element_Begin1("front_element");
bool front_element_is_cpe;
Get_SB ( front_element_is_cpe, "front_element_is_cpe");
Skip_S1(4, "front_element_tag_select");
if (front_element_is_cpe)
{
Channels_Front+=2;
Channels+=2;
if (Pos==0)
front1_element_is_cpe=true;
}
else
{
Channels_Front++;
Channels++;
}
Element_End0();
}
for (int8u Pos=0; Pos<num_side_channel_elements; Pos++)
{
Element_Begin1("side_element");
bool side_element_is_cpe;
Get_SB ( side_element_is_cpe, "side_element_is_cpe");
Skip_S1(4, "side_element_tag_select");
if (side_element_is_cpe)
{
Channels_Side+=2;
Channels+=2;
}
else
{
Channels_Side++;
Channels++;
}
Element_End0();
}
for (int8u Pos=0; Pos<num_back_channel_elements; Pos++)
{
Element_Begin1("back_element");
bool back_element_is_cpe;
Get_SB ( back_element_is_cpe, "back_element_is_cpe");
Skip_S1(4, "back_element_tag_select");
if (back_element_is_cpe)
{
Channels_Back+=2;
Channels+=2;
}
else
{
Channels_Back++;
Channels++;
}
Element_End0();
}
for (int8u Pos=0; Pos<num_lfe_channel_elements; Pos++)
{
Element_Begin1("lfe_element");
Skip_S1(4, "lfe_element_tag_select");
Channels_LFE++;
Channels++;
Element_End0();
}
for (int8u Pos=0; Pos<num_assoc_data_elements; Pos++)
{
Element_Begin1("assoc_data_element");
Skip_S1(4, "assoc_data_element_tag_select");
Element_End0();
}
for (int8u Pos=0; Pos<num_valid_cc_elements; Pos++)
{
Element_Begin1("valid_cc_element");
Skip_SB( "cc_element_is_ind_sw");
Skip_S1(4, "valid_cc_element_tag_select");
Element_End0();
}
BS_End(); //Byte align
Get_B1 (comment_field_bytes, "comment_field_bytes");
if (comment_field_bytes)
Get_Local(comment_field_bytes, comment_field_data, "comment_field_data");
BS_Begin(); //The stream needs continuity in the bitstream
Element_End0();
//Filling
Ztring Channels_Positions, Channels_Positions2, ChannelLayout;
switch (Channels_Front)
{
case 0 : break;
case 1 : Channels_Positions+=__T("Front: C"); ChannelLayout+=__T("C "); break;
case 2 : Channels_Positions+=__T("Front: L R"); ChannelLayout+=__T("L R "); break;
case 3 : Channels_Positions+=__T("Front: L C R"); ChannelLayout+=num_front_channel_elements==2?(front1_element_is_cpe?__T("L R C "):__T("C L R ")):__T("? ? ? "); break;
default : Channels_Positions+=__T("Front: "); Channels_Positions+=Ztring::ToZtring(Channels_Front); ChannelLayout+=__T("? "); //Which config?
}
switch (Channels_Side)
{
case 0 : break;
case 1 : Channels_Positions+=__T(", Side: C"); ChannelLayout+=__T("Cs "); break;
case 2 : Channels_Positions+=__T(", Side: L R"); ChannelLayout+=__T("Ls Rs "); break;
case 3 : Channels_Positions+=__T(", Side: L C R"); ChannelLayout+=__T("? ? ? "); break;
default : Channels_Positions+=__T(", Side: "); Channels_Positions+=Ztring::ToZtring(Channels_Side); ChannelLayout+=__T("? "); //Which config?
}
switch (Channels_Back)
{
case 0 : break;
case 1 : Channels_Positions+=__T(", Back: C"); ChannelLayout+=__T("Cs "); break;
case 2 : Channels_Positions+=__T(", Back: L R"); ChannelLayout+=__T("Rls Rrs "); break;
case 3 : Channels_Positions+=__T(", Back: L C R"); ChannelLayout+=__T("Rls Cs Rrs "); break;
default : Channels_Positions+=__T(", Back: "); Channels_Positions+=Ztring::ToZtring(Channels_Back); ChannelLayout+=__T("? "); //Which config?
}
switch (Channels_LFE)
{
case 0 : break;
case 1 : Channels_Positions+=__T(", LFE"); ChannelLayout+=__T("LFE "); break;
default : Channels_Positions+=__T(", LFE= "); Channels_Positions+=Ztring::ToZtring(Channels_LFE); ChannelLayout+=__T("? "); //Which config?
}
Channels_Positions2=Ztring::ToZtring(Channels_Front)+__T('/')
+Ztring::ToZtring(Channels_Side)+__T('/')
+Ztring::ToZtring(Channels_Back)
+(Channels_LFE?__T(".1"):__T(""));
if (!ChannelLayout.empty())
ChannelLayout.resize(ChannelLayout.size()-1);
FILLING_BEGIN();
//Integrity test
if (Aac_sampling_frequency[sampling_frequency_index_Temp]==0 || Channels>24) // TODO: full_2023548870.mp4 is buggy
{
Trusted_IsNot("sampling frequency / channels");
Skip_BS(Data_BS_Remain(), "(Unknown frequency)");
return;
}
if (audioObjectType==(int8u)-1)
audioObjectType=audioObjectType_Temp;
if (sampling_frequency_index==(int8u)-1)
sampling_frequency_index=sampling_frequency_index_Temp;
Infos_General["Comment"]=comment_field_data;
Infos["CodecID"].From_Number(audioObjectType);
Infos["Format"].From_Local("AAC");
Infos["Format_Profile"].From_Local(Aac_Format_Profile(audioObjectType));
Infos["Codec"].From_Local(Aac_audioObjectType(audioObjectType));
Infos["SamplingRate"].From_Number(Aac_sampling_frequency[sampling_frequency_index]);
Infos["Channel(s)"].From_Number(Channels);
Infos["ChannelPositions"]=Channels_Positions;
Infos["ChannelPositions/String2"]=Channels_Positions2;
Infos["ChannelLayout"]=ChannelLayout;
if (!Infos["Format_Settings_SBR"].empty())
{
Infos["Format_Profile"]=__T("HE-AAC");
Ztring SamplingRate=Infos["SamplingRate"];
Infos["SamplingRate"].From_Number((extension_sampling_frequency_index==(int8u)-1)?(Frequency_b*2):extension_sampling_frequency, 10);
if (MediaInfoLib::Config.LegacyStreamDisplay_Get())
{
Infos["Format_Profile"]+=__T(" / LC");
Infos["SamplingRate"]+=__T(" / ")+SamplingRate;
}
Infos["Format_Settings"]==__T("NBC"); // "Not Backward Compatible"
Infos["Format_Settings_SBR"]=__T("Yes (NBC)"); // "Not Backward Compatible"
Infos["Codec"]=Ztring().From_Local(Aac_audioObjectType(audioObjectType))+__T("-SBR");
}
if (!Infos["Format_Settings_PS"].empty())
{
Infos["Format_Profile"]=__T("HE-AACv2");
Ztring Channels=Infos["Channel(s)"];
Ztring ChannelPositions=Infos["ChannelPositions"];
Ztring SamplingRate=Infos["SamplingRate"];
Infos["Channel(s)"]=__T("2");
Infos["ChannelPositions"]=__T("Front: L R");
if (MediaInfoLib::Config.LegacyStreamDisplay_Get())
{
Infos["Format_Profile"]+=__T(" / HE-AAC / LC");
Infos["Channel(s)"]+=__T(" / ")+Channels+__T(" / ")+Channels;
Infos["ChannelPositions"]+=__T(" / ")+ChannelPositions+__T(" / ")+ChannelPositions;
Infos["SamplingRate"]=Ztring().From_Number((extension_sampling_frequency_index==(int8u)-1)?(Frequency_b*2):extension_sampling_frequency, 10)+__T(" / ")+SamplingRate;
}
if (Infos["Format_Settings"]!=__T("NBC"))
{
if (!Infos["Format_Settings"].empty())
Infos["Format_Settings"].insert(0, __T(" / "));
Infos["Format_Settings"].insert(0, __T("NBC")); // "Not Backward Compatible"
}
Infos["Format_Settings_PS"]=__T("Yes (NBC)"); // "Not Backward Compatible"
Ztring Codec=Retrieve(Stream_Audio, StreamPos_Last, Audio_Codec);
Infos["Codec"]=Ztring().From_Local(Aac_audioObjectType(audioObjectType))+__T("-SBR-PS");
}
FILLING_END();
}
//***************************************************************************
// Elements - GA bitstream
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::raw_data_block()
{
if (sampling_frequency_index>=13)
{
Trusted_IsNot("(Problem)");
Skip_BS(Data_BS_Remain(), "(Problem)");
return;
}
if (audioObjectType!=2)
{
Skip_BS(Data_BS_Remain(), "Data");
return; //We test only AAC LC
}
//Parsing
Element_Begin1("raw_data_block");
int8u id_syn_ele=0, id_syn_ele_Previous;
do
{
Element_Begin0();
id_syn_ele_Previous=id_syn_ele;
Get_S1 (3, id_syn_ele, "id_syn_ele"); Param_Info1(Aac_id_syn_ele[id_syn_ele]); Element_Name(Aac_id_syn_ele[id_syn_ele]);
#if MEDIAINFO_TRACE
bool Trace_Activated_Save=Trace_Activated;
if (id_syn_ele!=0x05)
Trace_Activated=false; //It is too big, disabling trace for now for full AAC parsing
#endif //MEDIAINFO_TRACE
switch (id_syn_ele)
{
case 0x00 : single_channel_element(); break; //ID_SCE
case 0x01 : channel_pair_element(); break; //ID_CPE
case 0x02 : coupling_channel_element(); break; //ID_CCE
case 0x03 : lfe_channel_element(); break; //ID_LFE
case 0x04 : data_stream_element(); break; //ID_DSE
case 0x05 : program_config_element(); break; //ID_PCE
case 0x06 : fill_element(id_syn_ele_Previous); break; //ID_FIL
case 0x07 : break; //ID_END
default : ; //Can not happen
}
#if MEDIAINFO_TRACE
Trace_Activated=Trace_Activated_Save;
#endif //MEDIAINFO_TRACE
Element_End0();
}
while(Element_IsOK() && Data_BS_Remain() && id_syn_ele!=0x07); //ID_END
if (Element_IsOK() && Data_BS_Remain()%8)
Skip_S1(Data_BS_Remain()%8, "byte_alignment");
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::single_channel_element()
{
//Parsing
Skip_S1 (4, "element_instance_tag");
individual_channel_stream(false, false);
}
//---------------------------------------------------------------------------
void File_Aac::channel_pair_element()
{
//Parsing
Skip_S1(4, "element_instance_tag");
Get_SB (common_window, "common_window");
if (common_window)
{
int8u ms_mask_present;
ics_info();
Get_S1(2, ms_mask_present, "ms_mask_present");
if (ms_mask_present==1)
{
Element_Begin1("ms_mask");
for (int8u g=0; g<num_window_groups; g++)
{
Element_Begin1("window");
for (int8u sfb=0; sfb<max_sfb; sfb++)
Skip_SB( "ms_used[g][sfb]");
Element_End0();
}
Element_End0();
}
}
individual_channel_stream(common_window, false);
if (!Element_IsOK())
return;
individual_channel_stream(common_window, false);
}
//---------------------------------------------------------------------------
void File_Aac::ics_info()
{
//Parsing
Element_Begin1("ics_info");
Skip_SB( "ics_reserved_bit");
Get_S1 (2, window_sequence, "window_sequence"); Param_Info1(Aac_window_sequence[window_sequence]);
Skip_SB( "window_shape");
if (window_sequence==2) //EIGHT_SHORT_SEQUENCE
{
Get_S1 (4, max_sfb, "max_sfb");
Get_S1 (7, scale_factor_grouping, "scale_factor_grouping");
}
else
{
bool predictor_data_present;
Get_S1 (6, max_sfb, "max_sfb");
Get_SB ( predictor_data_present, "predictor_data_present");
if (predictor_data_present)
{
if (audioObjectType==1) //AAC Main
{
bool predictor_reset;
Get_SB (predictor_reset, "predictor_reset");
if (predictor_reset)
Skip_S1(5, "predictor_reset_group_number");
int8u PRED_SFB_MAX=max_sfb;
if (PRED_SFB_MAX>Aac_PRED_SFB_MAX[sampling_frequency_index])
PRED_SFB_MAX=Aac_PRED_SFB_MAX[sampling_frequency_index];
for (int8u sfb=0; sfb<PRED_SFB_MAX; sfb++)
Skip_SB( "prediction_used[sfb]");
}
else
{
bool ltp_data_present;
Get_SB (ltp_data_present, "ltp_data_present");
if (ltp_data_present)
ltp_data();
if (common_window)
{
Get_SB (ltp_data_present, "ltp_data_present");
if (ltp_data_present)
ltp_data();
}
}
}
}
Element_End0();
//Calculation of windows
switch (window_sequence)
{
case 0 : //ONLY_LONG_SEQUENCE
case 1 : //LONG_START_SEQUENCE
case 3 : //LONG_STOP_SEQUENCE
num_windows=1;
num_window_groups=1;
window_group_length[0]=1;
num_swb=Aac_swb_offset_long_window[sampling_frequency_index]->num_swb;
for (int8u i=0; i<num_swb+1; i++)
{
if (Aac_swb_offset_long_window[sampling_frequency_index]->swb_offset[i]<frame_length)
swb_offset[i]=Aac_swb_offset_long_window[sampling_frequency_index]->swb_offset[i];
else
swb_offset[i]=frame_length;
sect_sfb_offset[0][i]=swb_offset[i];
}
break;
case 2 : //EIGHT_SHORT_SEQUENCE
num_windows=8;
num_window_groups=1;
window_group_length[0]=1;
num_swb=Aac_swb_offset_short_window[sampling_frequency_index]->num_swb;
for (int8u i=0; i<num_swb + 1; i++)
swb_offset[i] = Aac_swb_offset_short_window[sampling_frequency_index]->swb_offset[i];
swb_offset[num_swb] = frame_length/8;
for (int8u i=0; i<num_windows-1; i++)
{
if (!(scale_factor_grouping&(1<<(6-i))))
{
num_window_groups++;
window_group_length[num_window_groups-1]=1;
}
else
window_group_length[num_window_groups-1]++;
}
for (int g = 0; g < num_window_groups; g++)
{
int8u sect_sfb = 0;
int16u offset = 0;
for (int8u i=0; i<num_swb; i++)
{
int16u width = Aac_swb_offset_short_window[sampling_frequency_index]->swb_offset[i+1] - Aac_swb_offset_short_window[sampling_frequency_index]->swb_offset[i];
width *= window_group_length[g];
sect_sfb_offset[g][sect_sfb++] = offset;
offset += width;
}
sect_sfb_offset[g][sect_sfb] = offset;
}
break;
default: ;
}
}
//---------------------------------------------------------------------------
void File_Aac::pulse_data()
{
//Parsing
int8u number_pulse;
Get_S1(2,number_pulse, "number_pulse");
Skip_S1(6, "pulse_start_sfb");
for (int i = 0; i < number_pulse+1; i++)
{
Skip_S1(5, "pulse_offset[i]");
Skip_S1(4, "pulse_amp[i]");
}
}
//---------------------------------------------------------------------------
void File_Aac::coupling_channel_element()
{
//Parsing
int8u num_coupled_elements;
bool ind_sw_cce_flag;
Skip_S1(4, "element_instance_tag");
Get_SB ( ind_sw_cce_flag, "ind_sw_cce_flag");
Get_S1 (3, num_coupled_elements, "num_coupled_elements");
size_t num_gain_element_lists=0;
for (int8u c=0; c<num_coupled_elements+1; c++)
{
num_gain_element_lists++;
bool cc_target_is_cpe;
Get_SB ( cc_target_is_cpe, "cc_target_is_cpe[c]");
Skip_S1(4, "cc_target_tag_select[c]");
if (cc_target_is_cpe)
{
bool cc_l, cc_r;
Get_SB (cc_l, "cc_l[c]");
Get_SB (cc_r, "cc_r[c]");
if (cc_l && cc_r)
num_gain_element_lists++;
}
}
Skip_SB( "cc_domain");
Skip_SB( "gain_element_sign");
Skip_S1(2, "gain_element_scale");
individual_channel_stream(false, false);
if (!Element_IsOK())
return;
bool cge;
for (size_t c=1; c<num_gain_element_lists; c++)
{
if (ind_sw_cce_flag)
cge = true;
else
Get_SB (cge, "common_gain_element_present[c]");
if (cge)
hcod_sf( "hcod_sf[common_gain_element[c]]");
else
{
for (int g = 0; g < num_window_groups; g++)
{
for (int sfb=0; sfb<max_sfb; sfb++)
{
if (sfb_cb[g][sfb]) //Not ZERO_HCB
hcod_sf( "hcod_sf[dpcm_gain_element[c][g][sfb]]");
}
}
}
}
}
//---------------------------------------------------------------------------
void File_Aac::lfe_channel_element()
{
Skip_S1(4, "element_instance_tag");
individual_channel_stream(false, false);
}
//---------------------------------------------------------------------------
void File_Aac::data_stream_element()
{
bool data_byte_align_flag;
int16u cnt;
int8u count;
Skip_S1(4, "element_instance_tag");
Get_SB ( data_byte_align_flag, "data_byte_align_flag");
Get_S1 (8, count, "count");
cnt=count;
if (cnt==255)
{
Get_S1(8, count, "esc_count");
cnt+=count;
}
if (data_byte_align_flag)
{
if (Data_BS_Remain()%8)
Skip_S1(Data_BS_Remain()%8, "byte_alignment");
}
Element_Begin1("data_stream_byte[element_instance_tag]");
for (int16u i=0; i<cnt; i++)
Skip_S1(8, "[i]");
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::fill_element(int8u id_syn_ele)
{
//Parsing
int8u count;
Get_S1 (4, count, "count");
size_t cnt=count;
if (count==15)
{
int8u esc_count;
Get_S1 (8, esc_count, "esc_count");
cnt+=esc_count-1;
}
if (cnt)
{
if (Data_BS_Remain()>=8*cnt)
{
size_t End=Data_BS_Remain()-8*cnt;
extension_payload(End, id_syn_ele);
}
else
Skip_BS(Data_BS_Remain(), "(Error)");
}
}
//---------------------------------------------------------------------------
void File_Aac::gain_control_data()
{
int8u max_band, adjust_num, aloc_bits, aloc_bits0;
int8u wd_max=0;
switch(window_sequence)
{
case 0 : //ONLY_LONG_SEQUENCE
wd_max = 1;
aloc_bits0 = 5;
aloc_bits = 5;
break;
case 1 : //LONG_START_SEQUENCE
wd_max = 2;
aloc_bits0 = 4;
aloc_bits = 2;
break;
case 2 : //EIGHT_SHORT_SEQUENCE
wd_max = 8;
aloc_bits0 = 2;
aloc_bits = 2;
break;
case 3 : //LONG_STOP_SEQUENCE
wd_max = 2;
aloc_bits0 = 4;
aloc_bits = 5;
break;
default: return; //Never happens but makes compiler happy
}
Get_S1 (2, max_band, "max_band");
for (int8u bd=1; bd<=max_band; bd++)
{
for (int8u wd=0; wd<wd_max; wd++)
{
Get_S1(3, adjust_num, "adjust_num[bd][wd]");
for (int8u ad=0; ad<adjust_num; ad++)
{
Skip_S1(4, "alevcode[bd][wd][ad]");
Skip_S1(wd==0?aloc_bits0:aloc_bits, "aloccode[bd][wd][ad]");
}
}
}
}
//***************************************************************************
// Elements - Subsidiary
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::individual_channel_stream (bool common_window, bool scale_flag)
{
Element_Begin1("individual_channel_stream");
Skip_S1(8, "global_gain");
if (!common_window && !scale_flag)
ics_info();
if (!Element_IsOK())
{
Element_End0();
return;
}
section_data();
if (!Element_IsOK())
{
Element_End0();
return;
}
scale_factor_data();
if (!Element_IsOK())
{
Element_End0();
return;
}
if (!scale_flag)
{
bool pulse_data_present;
Get_SB (pulse_data_present, "pulse_data_present");
if (pulse_data_present)
pulse_data ();
bool tns_data_present;
Get_SB(tns_data_present, "tns_data_present");
if (tns_data_present)
tns_data ();
bool gain_control_data_present;
Get_SB(gain_control_data_present, "gain_control_data_present");
if (gain_control_data_present)
gain_control_data ();
}
if (!aacSpectralDataResilienceFlag)
spectral_data ();
else
{
Skip_BS(Data_BS_Remain(), "Not implemented");
//~ length_of_reordered_spectral_data;
//~ length_of_longest_codeword;
//~ reordered_spectral_data ();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::section_data()
{
Element_Begin1("section_data");
int8u sect_esc_val;
if (window_sequence==2) //EIGHT_SHORT_SEQUENCE
sect_esc_val=(1<<3)-1;
else
sect_esc_val=(1<<5)-1;
for (int8u g=0; g<num_window_groups; g++)
{
if (num_window_groups>1)
Element_Begin1("windows");
int8u k=0;
int8u i=0;
while (k<max_sfb)
{
if (aacSectionDataResilienceFlag)
Get_S1(5, sect_cb[g][i], "sect_cb[g][i]");
else
Get_S1(4, sect_cb[g][i], "sect_cb[g][i]");
int8u sect_len=0;
int8u sect_len_incr;
if (!aacSectionDataResilienceFlag || sect_cb[g][i]<11 || (sect_cb[g][i]>11 && sect_cb[g][i]<16))
{
for (;;)
{
if (Data_BS_Remain()==0)
{
Trusted_IsNot("Size is wrong");
if (num_window_groups>1)
Element_End0();
Element_End0();
return; //Error
}
Get_S1 ((window_sequence==2?3:5), sect_len_incr, "sect_len_incr"); // (window_sequence == EIGHT_SHORT_SEQUENCE) => 3
if (sect_len_incr!=sect_esc_val)
break;
sect_len+=sect_esc_val;
}
}
else
sect_len_incr=1;
sect_len+=sect_len_incr;
sect_start[g][i]=k;
sect_end[g][i]=k+sect_len;
for (int16u sfb=k; sfb<k+sect_len; sfb++)
sfb_cb[g][sfb]=sect_cb[g][i];
k+= sect_len;
i++;
if (i>64)
{
Trusted_IsNot("Increment is wrong");
if (num_window_groups>1)
Element_End0();
Element_End0();
return; //Error
}
}
num_sec[g]=i;
if (num_window_groups>1)
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::scale_factor_data()
{
Element_Begin1("scale_factor_data");
if (!aacScalefactorDataResilienceFlag)
{
bool noise_pcm_flag=true;
for (int g=0; g<num_window_groups; g++)
{
for (int8u sfb=0; sfb<max_sfb; sfb++)
{
if (sfb_cb[g][sfb]) //Not ZERO_HCB
{
if (is_intensity( g, sfb))
hcod_sf( "hcod_sf[dpcm_is_position[g][sfb]]");
else
{
if (is_noise(g, sfb))
{
if (noise_pcm_flag)
{
noise_pcm_flag = 0;
Skip_S2(9, "dpcm_noise_nrg[g][sfb]");
}
else
hcod_sf( "hcod_sf[dpcm_noise_nrg[g][sfb]]");
}
else
hcod_sf( "hcod_sf[dpcm_sf[g][sfb]]");
}
}
}
}
}
else
{
//scale_factor_data - part not implemented
Skip_BS(Data_BS_Remain(), "Not implemented");
//~ intensity_used = 0;
//~ noise_used = 0;
//~ sf_concealment;
//~ rev_global_gain;
//~ length_of_rvlc_sf;
//~ for ( g = 0; g < num_window_groups; g++ ) {
//~ for ( sfb=0; sfb < max_sfb; sfb++ ) {
//~ if ( sfb_cb[g][sfb] ) { //Not ZERO_HCB
//~ if ( is_intensity ( g, sfb) ) {
//~ intensity_used = 1;
//~ rvlc_cod_sf[dpcm_is_position[g][sfb]];
//~ } else {
//~ if ( is_noise(g,sfb) ) {
//~ if ( ! noise_used ) {
//~ noise_used = 1;
//~ dpcm_noise_nrg[g][sfb];
//~ } else {
//~ rvlc_cod_sf[dpcm_noise_nrg[g][sfb]];
//~ }
//~ } else {
//~ rvlc_cod_sf[dpcm_sf[g][sfb]];
//~ }
//~ }
//~ }
//~ }
//~ }
//~ if ( intensity_used ) {
//~ rvlc_cod_sf[dpcm_is_last_position];
//~ }
//~ noise_used = 0;
//~ sf_escapes_present;
//~ if ( sf_escapes_present ) {
//~ length_of_rvlc_escapes;
//~ for ( g = 0; g < num_window_groups; g++ ) {
//~ for ( sfb = 0; sfb < max_sfb; sfb++ ) {
//~ if ( sfb_cb[g][sfb]) { //Not ZERO_HCB
//~ if ( is_intensity ( g, sfb ) && dpcm_is_position[g][sfb] == ESC_FLAG ) {
//~ rvlc_esc_sf[dpcm_is_position[g][sfb]];
//~ } else {
//~ if ( is_noise ( g, sfb ) {
//~ if ( ! noise_used ) {
//~ noise_used = 1;
//~ } else {
//~ if (dpcm_noise_nrg[g][sfb] == ESC_FLAG ) {
//~ rvlc_esc_sf[dpcm_noise_nrg[g][sfb]];
//~ }
//~ }
//~ } else {
//~ if (dpcm_sf[g][sfb] == ESC_FLAG ) {
//~ rvlc_esc_sf[dpcm_sf[g][sfb]];
//~ }
//~ }
//~ }
//~ }
//~ }
//~ }
//~ if ( intensity_used && dpcm_is_last_position == ESC_FLAG ) {
//~ rvlc_esc_sf[dpcm_is_last_position];
//~ }
//~ }
//~ if ( noise_used ) {
//~ dpcm_noise_last_position;
//~ }
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::tns_data()
{
int8u n_filt_bits=2;
int8u length_bits=6;
int8u order_bits=5;
if (window_sequence==2) //EIGHT_SHORT_SEQUENCE
{
n_filt_bits=1;
length_bits=4;
order_bits=3;
}
for (int8u w=0; w<num_windows; w++)
{
int8u start_coef_bits, n_filt;
Get_S1(n_filt_bits, n_filt, "n_filt[w]");
if (n_filt)
{
bool coef_res;
Get_SB (coef_res, "coef_res[w]");
start_coef_bits=coef_res?4:3;
for (int8u filt=0; filt<n_filt; filt++)
{
int8u order;
Skip_S1(length_bits, "length[w][filt]");
Get_S1 (order_bits, order, "order[w][filt]");
if (order)
{
bool coef_compress;
Skip_SB( "direction[w][filt]");
Get_SB (coef_compress, "coef_compress[w][filt]");
int8u coef_bits=start_coef_bits-(coef_compress?1:0);
for (int8u i=0; i<order; i++)
Skip_S1(coef_bits, "coef[w][filt][i]");
}
}
}
}
}
//---------------------------------------------------------------------------
void File_Aac::ltp_data()
{
Element_Begin1("ltp_data");
//int sfb;
//bool ltp_lag_update;
//if (AudioObjectType == ER_AAC_LD ) {
//~ Get_SB(ltp_lag_update,"ltp_lag_update");
//~ if ( ltp_lag_update ) {
//~ Get_S2(10,ltp_lag,"ltp_lag");
//~ } else {
//~ //ltp_lag = ltp_prev_lag;
//~ }
//~ Skip_S1(3,"ltp_coef");
//~ for (sfb = 0; sfb <(max_sfb<MAX_LTP_LONG_SFB?max_sfb:MAX_LTP_LONG_SFB);& sfb++ ) {
//~ Skip_SB("ltp_long_used[sfb]");
//~ }
//} else {
Get_S2(11,ltp_lag, "ltp_lag");
Skip_S1(3, "ltp_coef");
if(window_sequence!=2) //EIGHT_SHORT_SEQUENCE
{
for (int8u sfb=0; sfb<(max_sfb<40?max_sfb:40); sfb++ ) //MAX_LTP_LONG_SFB=40
Skip_SB("ltp_long_used[sfb]");
}
//}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::spectral_data()
{
Element_Begin1("spectral_data");
for (int g = 0; g < num_window_groups; g++)
{
if (num_window_groups>1)
Element_Begin1("windows");
for (int8u i=0; i<num_sec[g]; i++)
{
switch (sect_cb[g][i])
{
case 0 : //ZERO_HCB
case 13 : //NOISE_HCB
case 14 : //INTENSITY_HCB2
case 15 : //INTENSITY_HCB
break;
default :
if (sect_end[g][i]>=num_swb+1)
{
Trusted_IsNot("(Problem)");
Skip_BS(Data_BS_Remain(), "(Problem)");
if (num_window_groups>1)
Element_End0();
Element_End0();
return;
}
for (int16u k=sect_sfb_offset[g][sect_start[g][i]]; k<sect_sfb_offset[g][sect_end[g][i]]; k+=(sect_cb[g][i]<5?4:2))
{
hcod(sect_cb[g][i], "sect_cb");
if (!Element_IsOK())
{
Skip_BS(Data_BS_Remain(), "(Problem)");
if (num_window_groups>1)
Element_End0();
Element_End0();
return;
}
}
}
}
if (num_window_groups>1)
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::extension_payload(size_t End, int8u id_aac)
{
Element_Begin1("extension_payload");
int8u extension_type;
Get_S1 (4, extension_type, "extension_type");
switch(extension_type)
{
case 11 : dynamic_range_info(); break; //EXT_DYNAMIC_RANGE
case 12 : sac_extension_data(End); break; //EXT_SAC_DATA
case 13 : sbr_extension_data(End, id_aac, 0); break; //EXT_SBR_DATA
case 14 : sbr_extension_data(End, id_aac, 1); break; //EXT_SBR_DATA_CRC
case 1 : //EXT_FILL_DATA
Skip_S1(4, "fill_nibble"); Param_Info1("must be 0000");
if (Data_BS_Remain()>End)
{
Element_Begin1("fill_byte");
while (Data_BS_Remain()>End)
Skip_S1(8, "fill_byte[i]"); Param_Info1("must be 10100101");
Element_End0();
}
break;
case 2 : //EXT_DATA_ELEMENT
int8u data_element_version;
Get_S1 (4,data_element_version, "data_element_version");
switch(data_element_version)
{
case 0 : //ANC_DATA
{
int16u dataElementLength=0;
int8u dataElementLengthPart;
do
{
Get_S1 (8, dataElementLengthPart, "dataElementLengthPart");
dataElementLength+=dataElementLengthPart;
}
while (dataElementLengthPart==255);
Skip_BS(8*dataElementLength, "data_element_byte[i]");
}
break;
default: ;
}
break;
case 0 : //EXT_FILL
default:
Skip_BS(Data_BS_Remain()-End, "other_bits");
}
Element_End0();
if (End<Data_BS_Remain())
Skip_BS(Data_BS_Remain()-End, "padding");
if (Data_BS_Remain()!=End)
{
Skip_BS(Data_BS_Remain(), "Wrong size");
Trusted_IsNot("Wrong size");
}
}
//---------------------------------------------------------------------------
void File_Aac::dynamic_range_info()
{
Element_Begin1("dynamic_range_info");
int8u drc_num_bands=1;
bool present;
Get_SB (present, "pce_tag_present");
if (present)
{
Skip_S1(4, "pce_ instance_tag");
Skip_S1(4, "drc_tag_reserved_bits");
}
Skip_SB( "excluded_chns_present");
Get_SB (present, "drc_bands_present");
if (present)
{
int8u drc_band_incr;
Get_S1 (4, drc_band_incr, "drc_band_incr");
Skip_S1(4, "drc_interpolation_scheme");
drc_num_bands+=drc_band_incr;
for (int8u i=0; i<drc_num_bands; i++)
{
Skip_S1(8, "drc_band_top[i]");
}
}
Get_SB (present, "prog_ref_level_present");
if (present)
{
Skip_S1(7, "prog_ref_level");
Skip_S1(1, "prog_ref_level_reserved_bits");
}
for (int8u i=0; i<drc_num_bands; i++)
{
Skip_S1(1, "dyn_rng_sgn[i]");
Skip_S1(7, "dyn_rng_ctl[i]");
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::sac_extension_data(size_t End)
{
Element_Begin1("sac_extension_data");
Skip_S1(2, "ancType");
Skip_SB( "ancStart");
Skip_SB( "ancStop");
Element_Begin1("ancDataSegmentByte");
while (Data_BS_Remain()>End)
Skip_S1(8, "ancDataSegmentByte[i]");
Element_End0();
Element_End0();
}
//***************************************************************************
// Elements - Perceptual noise substitution (PNS)
//***************************************************************************
//---------------------------------------------------------------------------
int File_Aac::is_intensity(size_t group, size_t sfb)
{
switch (sfb_cb[group][sfb])
{
case 14 : return 1;
case 15 : return -1;
default : return 0;
}
}
//---------------------------------------------------------------------------
bool File_Aac::is_noise(size_t group, size_t sfb)
{
return (sfb_cb[group][sfb]==13);
}
//---------------------------------------------------------------------------
void File_Aac::hcod_sf(const char* Name)
{
Element_Begin1(Name);
int16u Pos=0;
while (huffman_sf[Pos][1])
{
bool h;
Get_SB (h, "huffman");
Pos+=huffman_sf[Pos][h];
if (Pos>240)
{
Skip_BS(Data_BS_Remain(), "Error");
Element_End0();
return;
}
}
Element_Info1(huffman_sf[Pos][0]-60);
Element_End0();
return;
}
//---------------------------------------------------------------------------
void File_Aac::hcod_2step(int8u CodeBook, int8s* Values, int8u Values_Count)
{
int8u CodeWord;
int8u ToRead=hcb_2step_Bytes[CodeBook];
if ((size_t)ToRead>Data_BS_Remain())
ToRead=(int8u)Data_BS_Remain(); //Read a maximum of remaining bytes
Peek_S1(ToRead, CodeWord);
int16u Offset=hcb_2step[CodeBook][CodeWord].Offset;
int8u Extra=hcb_2step[CodeBook][CodeWord].Extra;
if (Extra)
{
Skip_BS(hcb_2step_Bytes[CodeBook], "extra");
int8u Offset_inc;
Peek_S1(Extra, Offset_inc);
Offset+=Offset_inc;
if(hcb_table[CodeBook][Offset][0]-hcb_2step_Bytes[CodeBook])
Skip_BS(hcb_table[CodeBook][Offset][0]-hcb_2step_Bytes[CodeBook],"extra");
}
else
{
Skip_BS(hcb_table[CodeBook][Offset][0], "bits");
}
if (Offset>=hcb_table_size[CodeBook])
{
Skip_BS(Data_BS_Remain(), "Error");
return;
}
for (int8u Pos=0; Pos<Values_Count; Pos++)
Values[Pos]=hcb_table[CodeBook][Offset][Pos+1];
}
//---------------------------------------------------------------------------
void File_Aac::hcod_binary(int8u CodeBook, int8s* Values, int8u Values_Count)
{
int16u Offset=0;
while (!hcb_table[CodeBook][Offset][0])
{
bool b;
Get_SB(b, "huffman binary");
Offset+=hcb_table[CodeBook][Offset][1+(b?1:0)];
}
if (Offset>=hcb_table_size[CodeBook])
{
Skip_BS(Data_BS_Remain(), "Error");
return;
}
for (int8u Pos=0; Pos<Values_Count; Pos++)
Values[Pos]=hcb_table[CodeBook][Offset][Pos+1];
}
//***************************************************************************
// Elements - Enhanced Low Delay Codec
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::ELDSpecificConfig ()
{
Element_Begin1("ELDSpecificConfig");
Skip_SB("frameLengthFlag");
Skip_SB("aacSectionDataResilienceFlag");
Skip_SB("aacScalefactorDataResilienceFlag");
Skip_SB("aacSpectralDataResilienceFlag");
bool ldSbrPresentFlag;
Get_SB(ldSbrPresentFlag,"ldSbrPresentFlag");
if (ldSbrPresentFlag)
{
Skip_SB("ldSbrSamplingRate");
Skip_SB("ldSbrCrcFlag");
ld_sbr_header();
}
int8u eldExtType;
for (;;)
{
Get_S1(4,eldExtType,"eldExtType");
if (eldExtType == 0/*ELDEXT_TERM*/)
break;
int8u eldExtLen,eldExtLenAdd=0;
int16u eldExtLenAddAdd;
Get_S1(4,eldExtLen,"eldExtLen");
int32u len = eldExtLen;
if (eldExtLen == 15)
{
Get_S1(8,eldExtLenAdd,"eldExtLenAdd");
len += eldExtLenAdd;
}
if (eldExtLenAdd==255)
{
Get_S2(16,eldExtLenAddAdd,"eldExtLenAddAdd");
len += eldExtLenAdd;
}
//~ switch (eldExtType) {
/* add future eld extension configs here */
//~ default:
for(int32u cnt=0; cnt<len; cnt++)
Skip_S1(8,"other_byte");
//~ break;
//~ }
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::ld_sbr_header()
{
int8u numSbrHeader;
switch (channelConfiguration)
{
case 1:
case 2:
numSbrHeader = 1;
break;
case 3:
numSbrHeader = 2;
break;
case 4:
case 5:
case 6:
numSbrHeader = 3;
break;
case 7:
numSbrHeader = 4;
break;
default:
numSbrHeader = 0;
break;
}
for (int el=0; el<numSbrHeader; el++) {
//~ sbr_header();
Element_Begin1("not implemented");
Element_End0();
}
}
//***************************************************************************
// Helpers
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::hcod(int8u sect_cb, const char* Name)
{
int8s Values[4];
Element_Begin1(Name);
switch (sect_cb)
{
case 1 :
case 2 :
case 4 : //4-values, 2-step method
hcod_2step(sect_cb, Values, 4);
break;
case 3 : //4-values, binary search method
hcod_binary(sect_cb, Values, 4);
break;
case 5 :
case 7 :
case 9 : //2-values, binary search method
hcod_binary(sect_cb, Values, 2);
break;
case 6 :
case 8 :
case 10 :
case 11 : //2-values, 2-step method
hcod_2step(sect_cb, Values, 2);
break;
default: Trusted_IsNot("(Problem)");
Element_End0();
return;
}
switch (sect_cb)
{
case 1 :
case 2 :
case 5 :
case 6 :
break;
default : //With sign
for(int i=0; i<((sect_cb<5)?4:2); i++)
if(Values[i])
Skip_SB( "sign");
}
switch (sect_cb)
{
case 11 : //With hcod_esc
for (int i=0; i<2; i++)
if (Values[i]==16 || Values[i] == -16)
{
Element_Begin1("hcod_esc");
bool Escape;
int BitCount=3;
do
{
BitCount++;
Get_SB(Escape, "bit count");
}
while (Escape);
Skip_BS(BitCount, "value");
Element_End0();
}
break;
default: ;
}
Element_End0();
}
//***************************************************************************
// C++
//***************************************************************************
} //NameSpace
#endif //MEDIAINFO_AAC_YES
| [
"[email protected]"
] | |
194099e803a5a7303d7ef37dab59e7a067198013 | 6a6984544a4782e131510a81ed32cc0c545ab89c | /src/cmake/tool-patches/boost-1.38.0/boost/iostreams/filter/symmetric.hpp | 40db6202134be1014d080abd5dcbeba37db52329 | [] | no_license | wardVD/IceSimV05 | f342c035c900c0555fb301a501059c37057b5269 | 6ade23a2fd990694df4e81bed91f8d1fa1287d1f | refs/heads/master | 2020-11-27T21:41:05.707538 | 2016-09-02T09:45:50 | 2016-09-02T09:45:50 | 67,210,139 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,568 | hpp | // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2003-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
// Contains the definitions of the class templates symmetric_filter,
// which models DualUseFilter based on a model of the Symmetric Filter.
//
// Roughly, a Symmetric Filter is a class type with the following interface:
//
// struct symmetric_filter {
// typedef xxx char_type;
//
// bool filter( const char*& begin_in, const char* end_in,
// char*& begin_out, char* end_out, bool flush )
// {
// // Consume as many characters as possible from the interval
// // [begin_in, end_in), without exhausting the output range
// // [begin_out, end_out). If flush is true, write as mush output
// // as possible.
// // A return value of true indicates that filter should be called
// // again. More precisely, if flush is false, a return value of
// // false indicates that the natural end of stream has been reached
// // and that all filtered data has been forwarded; if flush is
// // true, a return value of false indicates that all filtered data
// // has been forwarded.
// }
// void close() { /* Reset filter's state. */ }
// };
//
// Symmetric Filter filters need not be CopyConstructable.
//
#ifndef BOOST_IOSTREAMS_SYMMETRIC_FILTER_HPP_INCLUDED
#define BOOST_IOSTREAMS_SYMMETRIC_FILTER_HPP_INCLUDED
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <cassert>
#include <memory> // allocator, auto_ptr.
#include <boost/config.hpp> // BOOST_DEDUCED_TYPENAME.
#include <boost/iostreams/char_traits.hpp>
#include <boost/iostreams/constants.hpp> // buffer size.
#include <boost/iostreams/detail/buffer.hpp>
#include <boost/iostreams/detail/char_traits.hpp>
#include <boost/iostreams/detail/config/limits.hpp>
#include <boost/iostreams/detail/template_params.hpp>
#include <boost/iostreams/traits.hpp>
#include <boost/iostreams/operations.hpp> // read, write.
#include <boost/iostreams/pipeline.hpp>
#include <boost/preprocessor/iteration/local.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/shared_ptr.hpp>
// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp> // MSVC.
namespace boost { namespace iostreams {
template< typename SymmetricFilter,
typename Alloc =
std::allocator<
BOOST_DEDUCED_TYPENAME char_type_of<SymmetricFilter>::type
> >
class symmetric_filter {
public:
typedef typename char_type_of<SymmetricFilter>::type char_type;
typedef std::basic_string<char_type> string_type;
struct category
: dual_use,
filter_tag,
multichar_tag,
closable_tag
{ };
// Expands to a sequence of ctors which forward to impl.
#define BOOST_PP_LOCAL_MACRO(n) \
BOOST_IOSTREAMS_TEMPLATE_PARAMS(n, T) \
explicit symmetric_filter( \
int buffer_size BOOST_PP_COMMA_IF(n) \
BOOST_PP_ENUM_BINARY_PARAMS(n, const T, &t) ) \
: pimpl_(new impl(buffer_size BOOST_PP_COMMA_IF(n) \
BOOST_PP_ENUM_PARAMS(n, t))) \
{ } \
/**/
#define BOOST_PP_LOCAL_LIMITS (0, BOOST_IOSTREAMS_MAX_FORWARDING_ARITY)
#include BOOST_PP_LOCAL_ITERATE()
#undef BOOST_PP_LOCAL_MACRO
template<typename Source>
std::streamsize read(Source& src, char_type* s, std::streamsize n)
{
using namespace std;
if (!(state() & f_read))
begin_read();
buffer_type& buf = pimpl_->buf_;
int status = (state() & f_eof) != 0 ? f_eof : f_good;
char_type *next_s = s,
*end_s = s + n;
while (true)
{
// Invoke filter if there are unconsumed characters in buffer or if
// filter must be flushed.
bool flush = status == f_eof;
if (buf.ptr() != buf.eptr() || flush) {
const char_type* next = buf.ptr();
bool done =
!filter().filter(next, buf.eptr(), next_s, end_s, flush);
buf.ptr() = buf.data() + (next - buf.data());
if (done)
return detail::check_eof(
static_cast<std::streamsize>(next_s - s)
);
}
// If no more characters are available without blocking, or
// if read request has been satisfied, return.
if ( (status == f_would_block && buf.ptr() == buf.eptr()) ||
next_s == end_s )
{
return static_cast<std::streamsize>(next_s - s);
}
// Fill buffer.
if (status == f_good)
status = fill(src);
}
}
template<typename Sink>
std::streamsize write(Sink& snk, const char_type* s, std::streamsize n)
{
if (!(state() & f_write))
begin_write();
buffer_type& buf = pimpl_->buf_;
const char_type *next_s, *end_s;
for (next_s = s, end_s = s + n; next_s != end_s; ) {
if (buf.ptr() == buf.eptr() && !flush(snk))
break;
filter().filter(next_s, end_s, buf.ptr(), buf.eptr(), false);
}
return static_cast<std::streamsize>(next_s - s);
}
template<typename Sink>
void close(Sink& snk, BOOST_IOS::openmode which)
{
if ((state() & f_write) != 0) {
// Repeatedly invoke filter() with no input.
try {
buffer_type& buf = pimpl_->buf_;
char dummy;
const char* end = &dummy;
bool again = true;
while (again) {
if (buf.ptr() != buf.eptr())
again = filter().filter( end, end, buf.ptr(),
buf.eptr(), true );
flush(snk);
}
} catch (...) {
try { close_impl(); } catch (...) { }
throw;
}
close_impl();
} else {
close_impl();
}
}
SymmetricFilter& filter() { return *pimpl_; }
string_type unconsumed_input() const;
// Give impl access to buffer_type on Tru64
#if !BOOST_WORKAROUND(__DECCXX_VER, BOOST_TESTED_AT(60590042))
private:
#endif
typedef detail::buffer<char_type, Alloc> buffer_type;
private:
buffer_type& buf() { return pimpl_->buf_; }
const buffer_type& buf() const { return pimpl_->buf_; }
int& state() { return pimpl_->state_; }
void begin_read();
void begin_write();
template<typename Source>
int fill(Source& src)
{
std::streamsize amt = iostreams::read(src, buf().data(), buf().size());
if (amt == -1) {
state() |= f_eof;
return f_eof;
}
buf().set(0, amt);
return amt == buf().size() ? f_good : f_would_block;
}
// Attempts to write the contents of the buffer the given Sink.
// Returns true if at least on character was written.
template<typename Sink>
bool flush(Sink& snk)
{
typedef typename iostreams::category_of<Sink>::type category;
typedef is_convertible<category, output> can_write;
return flush(snk, can_write());
}
template<typename Sink>
bool flush(Sink& snk, mpl::true_)
{
typedef char_traits<char_type> traits_type;
std::streamsize amt =
static_cast<std::streamsize>(buf().ptr() - buf().data());
std::streamsize result =
boost::iostreams::write(snk, buf().data(), amt);
if (result < amt && result > 0)
traits_type::move(buf().data(), buf().data() + result, amt - result);
buf().set(amt - result, buf().size());
return result != 0;
}
template<typename Sink>
bool flush(Sink&, mpl::false_) { return true;}
void close_impl();
enum flag_type {
f_read = 1,
f_write = f_read << 1,
f_eof = f_write << 1,
f_good,
f_would_block
};
struct impl : SymmetricFilter {
// Expands to a sequence of ctors which forward to SymmetricFilter.
#define BOOST_PP_LOCAL_MACRO(n) \
BOOST_IOSTREAMS_TEMPLATE_PARAMS(n, T) \
impl( int buffer_size BOOST_PP_COMMA_IF(n) \
BOOST_PP_ENUM_BINARY_PARAMS(n, const T, &t) ) \
: SymmetricFilter(BOOST_PP_ENUM_PARAMS(n, t)), \
buf_(buffer_size), state_(0) \
{ } \
/**/
#define BOOST_PP_LOCAL_LIMITS (0, BOOST_IOSTREAMS_MAX_FORWARDING_ARITY)
#include BOOST_PP_LOCAL_ITERATE()
#undef BOOST_PP_LOCAL_MACRO
buffer_type buf_;
int state_;
};
shared_ptr<impl> pimpl_;
};
BOOST_IOSTREAMS_PIPABLE(symmetric_filter, 2)
//------------------Implementation of symmetric_filter----------------//
template<typename SymmetricFilter, typename Alloc>
void symmetric_filter<SymmetricFilter, Alloc>::begin_read()
{
assert(!(state() & f_write));
state() |= f_read;
buf().set(0, 0);
}
template<typename SymmetricFilter, typename Alloc>
void symmetric_filter<SymmetricFilter, Alloc>::begin_write()
{
assert(!(state() & f_read));
state() |= f_write;
buf().set(0, buf().size());
}
template<typename SymmetricFilter, typename Alloc>
void symmetric_filter<SymmetricFilter, Alloc>::close_impl()
{
state() = 0;
buf().set(0, 0);
filter().close();
}
template<typename SymmetricFilter, typename Alloc>
typename symmetric_filter<SymmetricFilter, Alloc>::string_type
symmetric_filter<SymmetricFilter, Alloc>::unconsumed_input() const
{ return string_type(buf().ptr(), buf().eptr()); }
//----------------------------------------------------------------------------//
} } // End namespaces iostreams, boost.
#include <boost/iostreams/detail/config/enable_warnings.hpp> // MSVC.
#endif // #ifndef BOOST_IOSTREAMS_SYMMETRIC_FILTER_HPP_INCLUDED
| [
"[email protected]"
] | |
ad442de94e84a4884bbfc296c6f3385c42588d83 | 4d1926e60792b4a6e0ee9abfa38ea9c465caa363 | /15.cpp | c7a9bc0a42027e204fce89b923d3b403562aa2d8 | [] | no_license | hd-hitesh/SDE-Questions | 05e30218e8d883513ff563140403104911b7b715 | 8efc257e2f81901165f029bc5578b695b9957464 | refs/heads/main | 2023-02-11T06:23:05.247314 | 2021-01-06T12:31:03 | 2021-01-06T12:31:03 | 313,694,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | cpp | #include <bits/stdc++.h>
#define pb push_back
#define fr first
#define sc second
#define MOD 1e9 + 7
#define len(x) x.size()
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min3(a, b, c) min(a, min(b, c))
#define max3(a, b, c) max(a, max(b, c))
#define FOR(i,j,n) for(int i=j;i<n;i++)
#define FORR(i,j,n) for(int i=j;i>n;i--)
// #define FOR(i,n) for(int i=0;i<n;i++)
// #define FORR(i,n) for(int i=j;i>=0;i--)
#define all(v) v.begin(), v.end()
#define endl "\n";
#define tez_chal_bsdk \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<string> vs;
typedef unordered_map<int, int> mp;
typedef unordered_map<ll, ll> mpl;
#define cint(a) int a; cin>>a;
#define cin(a) ll a; cin>>a;
#define cin2(a,b) ll a,b; cin>>a>>b;
#define cin3(a,b,c) ll a,b,c; cin>>a>>b>>c;
#define vin(v,n) for(ll i=0; i<n;i++) cin>>v[i];
#define vout(v,n) for(ll i=0; i<n;i++) cout<<v[i]<<" "; cout<<endl;
void solve()
{
cin(n);
ll a[n+2],a1[n+2];
memset(a,0,sizeof(a));
memset(a1,0,sizeof(a1));
cin(q);
while(q--){
cin2(l,r);
a[l]+=1;
a[r+1]-=1;
a1[r+1]-=(r-l+1);
}
cin(m);
FOR(i,1,n+1)
a[i]+=a[i-1];
FOR(i,1,n+1)
a1[i]+=a1[i-1]+a[i];
while(m--)
{
cin(index);
cout<<a1[index]<<endl;
}
}
int main()
{
tez_chal_bsdk;
#ifndef ONLINE_JUDGE
freopen("input1.txt", "r", stdin);
freopen("output1.txt", "w", stdout);
#endif
solve();
// cint(t);
// while (t--)
// {
// solve();
// cout << endl;
// }
return 0;
}
// ctrl + alt + F : format the code
// ctrl + shift + B : build with
// ctrl + B : build
// ctrl + X : cut the line
// ctrl + | [
"[email protected]"
] | |
2cd24cbd2e943271a89fc4c937c3560b1dfeeb49 | ba660ff5c37595c929130558158ebfee7b564137 | /Search_Sort/main.cpp | 2d66c98a7f54ac08a70b4b8ff73c8543cdcafadd | [] | no_license | sattuGit/Cpp | 3dc4658a022955ddb12ba6c74328e38e5fadb370 | e926927ed663f12037a06dc691c5af02b8889df8 | refs/heads/master | 2023-09-01T20:21:14.540942 | 2021-08-18T08:06:42 | 2021-08-18T08:06:42 | 120,272,043 | 0 | 0 | null | 2023-08-29T15:26:14 | 2018-02-05T07:49:41 | C++ | UTF-8 | C++ | false | false | 617 | cpp | #include<iostream>
#include "SelectionSort.h"
#include "binarySearch.h"
int main()
{
int data[]={01,22,-9,9999,578,25,8797,245,0632,7,8,0,8};
struct arr dataList;
dataList.data = data;
dataList.len = sizeof(data)/sizeof(int);
display(dataList); //before sorting
SelectionSort(dataList); // sorting
display(dataList); // after sorting
/*Binary Search */
int key = 8;
int result = binarySearch(dataList,key,0,dataList.len-1);
std::cout << "Search of value "<<key<< " result is availble @ index "<<result << std::endl;
return 0;
}
| [
"[email protected]"
] | |
e2cb4cc993191a58651068a483b07930b477eb9b | 5c1328a271a8607e59be87244068ab46fd24c893 | /cpp/49-Group-Anagrams.cpp | fe5768942648fe814072cbbb4a87f44b04f7bc5f | [
"MIT"
] | permissive | ErdemOzgen/leetcode | 32d0f2fae605caf33655db38d8dc701062dd773c | c50d6fa482a608a2556e92e6f629e9c29089efd6 | refs/heads/main | 2022-11-06T06:22:10.322894 | 2022-10-02T23:20:09 | 2022-10-02T23:20:09 | 514,034,071 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | cpp | /*
Given array of strings, group anagrams together (same letters diff order)
Ex. strs = ["eat","tea","tan","ate","nat","bat"] -> [["bat"],["nat","tan"],["ate","eat","tea"]]
Count chars, for each string use total char counts (naturally sorted) as key
Time: O(n x l) -> n = length of strs, l = max length of a string in strs
Space: O(n x l)
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
for (int i = 0; i < strs.size(); i++) {
string key = getKey(strs[i]);
m[key].push_back(strs[i]);
}
vector<vector<string>> result;
for (auto it = m.begin(); it != m.end(); it++) {
result.push_back(it->second);
}
return result;
}
private:
string getKey(string str) {
vector<int> count(26);
for (int j = 0; j < str.size(); j++) {
count[str[j] - 'a']++;
}
string key = "";
for (int i = 0; i < 26; i++) {
key.append(to_string(count[i] + 'a'));
}
return key;
}
};
| [
"[email protected]"
] | |
047422b786440037aac47338246f937df3942d86 | e3b5ff6c210fca025be32168340438fad0569e7b | /Zumo32U4Encoders_aktivitet2/src/main.cpp | 3c328ce333f332cb8096511c2a30fe4c3173e4df | [] | no_license | theBadMusician/SmartCityMCUs | 0b6d87800b8f2a0f42421126d4cd5c727774fc2c | f900f4c3a09f9412a52c355898c352859933595e | refs/heads/master | 2022-06-06T05:19:31.671115 | 2020-05-02T16:28:31 | 2020-05-02T16:28:31 | 256,524,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,319 | cpp | #include <Arduino.h>
#include <Zumo32U4.h>
#include <stdlib.h>
using namespace std;
// Ved søppeltømmingssystemet med ruter:
// Utvidelse til programvarebatteri -> sjekke hvor mye batteri det er igjen
// og hvis det er bare nok energi til å komme basen, kjøre tilbake til hjembasen ved bruk av samme ruten.
// Utvidelse til ladestasjon -> jo mer man betaler per sekund/minutt, jo fortere/saktere skjer oppladninga.
// -> Hvis man ikke har nok penger i konto, får man "låne" penger fra systemet med renter.
// Utvidelse til luftstasjon -> Kritisk nivåvarsling - hvis temp, trykk, el. annet overstiger en terskelverdi, biler returnerer hjem,
// og stanser all virkning inntil verdiene blir "normale".
// Utvidelse til parkeringshus -> Hvis en bil står lengere enn konto tilatter
// -> Premiumparkeringsplasser
// Utvidelse til søppeltømming -> QR-code gjennkjennelse til søppelbøtter
// Modul: kjøre på en bane mellom vegger: fortest som kjør uten treffe vegger vinner
// -------||-------
Zumo32U4Encoders encoders;
Zumo32U4Motors motors;
Zumo32U4ButtonA buttonA;
Zumo32U4LCD LCD;
int16_t motor_speed = 300,
batteryCap;
uint32_t check_time,
delta_time;
struct {
float revCounts[2];
float meterCounts[2];
float metersAbs;
float batteryMeters;
} counters;
bool flag = false,
battery_flag = false;
void revCounters ();
void writeToLCD (String text);
void setup() {
Serial.begin(115200);
LCD.clear();
}
void loop() {
if (buttonA.isPressed()) {
motors.setSpeeds(0, 0);
buttonA.waitForRelease();
flag = !flag;
delay(100);
}
if (!flag) motor_speed = 400;
else motor_speed = -400;
if (batteryCap - counters.batteryMeters > 0) battery_flag = true;
else battery_flag = false;
if (!battery_flag && motor_speed > 0) motors.setSpeeds(0, 0);
else motors.setSpeeds(motor_speed, motor_speed);
revCounters();
Serial.print(counters.revCounts[0]);
Serial.print(" ");
Serial.print(counters.revCounts[1]);
Serial.print(" ");
Serial.print(counters.meterCounts[0]);
Serial.print(" ");
Serial.print(counters.meterCounts[1]);
Serial.print(" ");
Serial.println(counters.metersAbs);
if (millis() - check_time > 100) {
writeToLCD(String(counters.metersAbs));
check_time = millis();
}
}
void revCounters () {
counters.revCounts[0] = encoders.getCountsLeft() / 909.70;
counters.revCounts[1] = encoders.getCountsRight() / 909.70;
counters.meterCounts[0] = counters.revCounts[0] / 8.300;
counters.meterCounts[1] = counters.revCounts[1] / 8.300;
if (counters.meterCounts[0] > 0.1 || counters.meterCounts[0] < -0.1 || counters.meterCounts[1] > 0.1 || counters.meterCounts[1] < -0.1) {
counters.batteryMeters += (counters.meterCounts[0] + counters.meterCounts[1]) * 0.5;
counters.batteryMeters = constrain(counters.batteryMeters, 0, batteryCap);
counters.metersAbs += abs(counters.meterCounts[0] + counters.meterCounts[1]) * 0.5;
counters.revCounts[0] = encoders.getCountsAndResetLeft() / 909.70;
counters.revCounts[1] = encoders.getCountsAndResetRight() / 909.70;
}
}
void writeToLCD (String text) {
LCD.clear();
LCD.gotoXY(0, 0);
LCD.println(text);
} | [
"[email protected]"
] | |
2d093580caf1dbf14b58ef9bd2f2e9520fc35f67 | 41510b72be90c5fd8ccaf814d381861000bd40d0 | /TeamRandShareMgr.h | d67f7192f5ff149bb575709e7f5028d574cdd279 | [] | no_license | chuyiwen/CCgame | 4e7183c821bc3e4a3a5ac922f3f3b07bcad15732 | 597e7f337ebb3845ecac056bc5ce6085c2f99666 | refs/heads/master | 2021-01-24T12:04:35.050807 | 2018-02-27T10:58:38 | 2018-02-27T10:58:38 | 123,116,689 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,104 | h | /*******************************************************************************
Copyright 2010 by tiankong Interactive Game Co., Ltd.
All rights reserved.
This software is the confidential and proprietary information of
tiankong Interactive Game Co., Ltd. ('Confidential Information'). You shall
not disclose such Confidential Information and shall use it only in
accordance with the terms of the license agreement you entered into with
tiankong Interactive Co., Ltd.
*******************************************************************************/
/**
* @file TeamRandShareMgr
* @author mwh
* @date 2012/05/23 initial
* @version 0.0.1.0
* @brief <所谓的战神同盟系统>
*/
#ifndef __TEAM_RAND_SHARE_QUEST_H_
#define __TEAM_RAND_SHARE_QUEST_H_
class Team;
struct RandShare_t;
#include "event_mgr.h"
class TeamRandSahreQuestMgr : public EventMgr<TeamRandSahreQuestMgr>
{
typedef EventMgr<TeamRandSahreQuestMgr> Super;
DWORD mLogicThreadID;
INT mNotifyActvieTick;
package_map<DWORD, RandShare_t*> mAllShare;
public:
static TeamRandSahreQuestMgr& GetInstance(){
static TeamRandSahreQuestMgr __innerobj;
return __innerobj;
}
public:
/** Init */
BOOL Init( );
VOID Destroy();
VOID ForceAllDelDB( );
BOOL AddNew(DWORD teamID);
VOID DelOne(DWORD teamID);
/** <主线程>update */
VOID Update();
VOID MemberNext(DWORD dwNPCID, DWORD roleID, BOOL sysauto = FALSE, BOOL Compelte = FALSE);
VOID MemberExit(DWORD teamID, DWORD roleID);
VOID MemberJoin(DWORD teamID, DWORD roleID);
public:
/** AddEvent */
VOID EvtMemberNext(DWORD dwRoleID, VOID* pMsg);
public:
BOOL CanActive(DWORD teamID);
BOOL CanRefresh(RandShare_t *pShare);
VOID Refresh(DWORD teamID, RandShare_t *pShare);
private:
VOID CheckThread( );
VOID RandQuestList(const Team *pTeam, RandShare_t *pShare);
VOID SendToOneDelQuest(DWORD dwRoleID, RandShare_t *pShare);
VOID register_event( );//注册所有事件
private:
TeamRandSahreQuestMgr(){}
~TeamRandSahreQuestMgr(){Destroy();}
};
#define sTeamShareMgr TeamRandSahreQuestMgr::GetInstance()
#endif /** __TEAM_RAND_SHARE_QUEST_H_ */ | [
"[email protected]"
] | |
1b7c9cf63028173921057153c092cee1872a274b | 24c6c4c156800d03ccc444306af5010ae600d465 | /UVA/01. Accepted/10450_World cup noise.cpp | 6513b38adee8b12aac0cbe5b9763b04083b47cc1 | [] | no_license | RajibTheKing/ACMProgramming | 5e1ba7e4271b372ddd2e2cf417bd1bffe5cd838a | d89e94fc671c7138c97d4fb9d197d5abbca99f6f | refs/heads/master | 2021-12-14T01:33:09.537195 | 2021-12-05T19:58:17 | 2021-12-05T19:58:17 | 67,598,402 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | cpp | #include<iostream>
using namespace std;
main()
{
long long fibonacci[60];
int i, t, n, kase=0;
fibonacci[1]=2;
fibonacci[2]=3;
for(i=3;i<=60;i++)
fibonacci[i]=fibonacci[i-1]+fibonacci[i-2];
cin>>t;
while(t--)
{
cin>>n;
cout<<"Scenario #"<<++kase<<":"<<endl;
cout<<fibonacci[n]<<endl;
cout<<endl;
}
}
| [
"[email protected]"
] | |
a68dec32a436528a447bf5772ef4c04325d0c89f | 5b41e312db8aeb5532ba59498c93e2ec1dccd4ff | /SMC_DBClasses/CHD_HEAT_DATA.h | 7cc170a58ba474c36b9141d36397cb70ed264bb5 | [] | no_license | frankilfrancis/KPO_HMI_vs17 | 10d96c6cb4aebffb83254e6ca38fe6d1033eba79 | de49aa55eccd8a7abc165f6057088a28426a1ceb | refs/heads/master | 2020-04-15T16:40:14.366351 | 2019-11-14T15:33:25 | 2019-11-14T15:33:25 | 164,845,188 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,163 | h | //## Copyright (C) 2009 SMS Siemag AG, Germany
//## Version generated by DBClassCodeUtility BETA 0.6.3
//## ALL METHODS MARKED AS - //##DBClassCodeUtility - WILL BE OVERWRITTEN, IF DB CLASS RE-GENERATED
//## MANUALLY IMPLEMENTED METHODS MUST BE LOCATED BELOW THE MARK - "YOUR-CODE" -
#if defined (_MSC_VER) && (_MSC_VER >= 1000)
#pragma once
#endif
#ifndef _INC_CHD_HEAT_DATA_INCLUDED
#define _INC_CHD_HEAT_DATA_INCLUDED
#include "CSMC_DBData.h"
class CHD_HEAT_DATA
: public CSMC_DBData
{
public:
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string HEATID;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATID;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string PLANT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string STEELGRADECODE_PLAN;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string STEELGRADECODE_ACT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string PRODORDERID_PLAN;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string PRODORDERID_ACT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string AIMSTEELWGT_PLAN;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string AIMSTEELWGT_MOD;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string AIMTEMP_PLAN;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string AIMTEMP_MOD;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string HEATANNOUNCE_OFFLINE;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string HEATANNOUNCE_ACT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATSTART_PLAN;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATSTART_MOD;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATSTART_ACT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATEND_PLAN;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATEND_MOD;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATEND_CALC;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATEND_ACT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string HEATDEPARTURE_ACT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATEND_PREV;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string LADLETYPE;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string LADLENO;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string STEELMASS;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string SLAGMASS;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string SAMPLE_REF;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string REVTIME;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string USERCODE;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TEMP_SAMPLES;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string STEEL_SAMPLES;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string SLAG_SAMPLES;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string STEELMASS_START;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string SLAGMASS_START;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string ROUTECODE_PLAN;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string ROUTECODE_ACT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATMENTDURATION;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string FINALTEMP;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string SHIFT_ID;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string CREW_ID;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string CREW_RESPONSIBILITY;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string HEAT_RESPONSIBILITY;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string COMMENTS;
//##DBClassCodeUtility ! DO NOT EDIT !
CHD_HEAT_DATA(cCBS_StdConnection* Connection);
//##DBClassCodeUtility ! DO NOT EDIT !
CHD_HEAT_DATA(cCBS_Connection* Connection);
//##DBClassCodeUtility ! DO NOT EDIT !
CHD_HEAT_DATA();
//##DBClassCodeUtility ! DO NOT EDIT !
~CHD_HEAT_DATA();
//##DBClassCodeUtility ! DO NOT EDIT !
//##Internal heat identifier
std::string getHEATID(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setHEATID(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Treatment identifier
std::string getTREATID(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATID(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Plant identifier
std::string getPLANT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setPLANT(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Planned steel grade code
std::string getSTEELGRADECODE_PLAN(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSTEELGRADECODE_PLAN(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Actual Steel grade code
std::string getSTEELGRADECODE_ACT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSTEELGRADECODE_ACT(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##From PP_ORDER as planned
std::string getPRODORDERID_PLAN(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setPRODORDERID_PLAN(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##From PP_ORDER but modified
std::string getPRODORDERID_ACT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setPRODORDERID_ACT(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Aim steel weight according production order.
double getAIMSTEELWGT_PLAN(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setAIMSTEELWGT_PLAN(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Aim steel weight according operator. (= Order if not changed)
double getAIMSTEELWGT_MOD(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setAIMSTEELWGT_MOD(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Aim temperature according plan.
double getAIMTEMP_PLAN(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setAIMTEMP_PLAN(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Aim temperature according operator modification
double getAIMTEMP_MOD(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setAIMTEMP_MOD(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##In case a model supports offline calculation for e.g. scrap order this time stamp is used to have a complete time line for the heat
CDateTime getHEATANNOUNCE_OFFLINE(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setHEATANNOUNCE_OFFLINE(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Heat announcement time
CDateTime getHEATANNOUNCE_ACT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setHEATANNOUNCE_ACT(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Treatment start from schedule
CDateTime getTREATSTART_PLAN(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATSTART_PLAN(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Treatment start, schedule modified
CDateTime getTREATSTART_MOD(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATSTART_MOD(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Actual treatment start
CDateTime getTREATSTART_ACT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATSTART_ACT(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Treatment end from schedule
CDateTime getTREATEND_PLAN(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATEND_PLAN(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Treatment end, schedule modified
CDateTime getTREATEND_MOD(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATEND_MOD(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Treatment end time calculated by model
CDateTime getTREATEND_CALC(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATEND_CALC(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Actual treatment end
CDateTime getTREATEND_ACT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATEND_ACT(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Heat departure time
CDateTime getHEATDEPARTURE_ACT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setHEATDEPARTURE_ACT(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Last treatment end, should be filled from PD_PLANTSTATUS_PLANT.LASTTREATENDTIME
CDateTime getTREATEND_PREV(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATEND_PREV(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##e.g. Hot Metal -> H, Teeming -> T
std::string getLADLETYPE(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setLADLETYPE(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Unique ladle number
long getLADLENO(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setLADLENO(long value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Cummulated steel mass from all additions, Eng. Unit : kg,
double getSTEELMASS(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSTEELMASS(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Cummulated slag mass from all additions, Eng. Unit : kg,
double getSLAGMASS(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSLAGMASS(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Unique sample reference
long getSAMPLE_REF(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSAMPLE_REF(long value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Date and time of last revision
CDateTime getREVTIME(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setREVTIME(const CDateTime& value);
//##DBClassCodeUtility ! DO NOT EDIT !
std::string getUSERCODE(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setUSERCODE(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Number of taken temperature measurements
long getTEMP_SAMPLES(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTEMP_SAMPLES(long value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Number of taken steel analysis measurements
long getSTEEL_SAMPLES(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSTEEL_SAMPLES(long value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Number of taken slag analysis measurements
long getSLAG_SAMPLES(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSLAG_SAMPLES(long value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Steel mass at begin of treatment
double getSTEELMASS_START(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSTEELMASS_START(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Slag mass at begin of treatment
double getSLAGMASS_START(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSLAGMASS_START(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Planned route code
std::string getROUTECODE_PLAN(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setROUTECODE_PLAN(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Actual route code
std::string getROUTECODE_ACT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setROUTECODE_ACT(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Treatment duration
double getTREATMENTDURATION(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATMENTDURATION(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Final temperature (measured or calculated, plant dependend)
double getFINALTEMP(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setFINALTEMP(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Shift of Production
std::string getSHIFT_ID(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSHIFT_ID(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Identification of working crew
std::string getCREW_ID(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setCREW_ID(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Responsible person of crew, typically the foreman
std::string getCREW_RESPONSIBILITY(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setCREW_RESPONSIBILITY(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Crew member (MEMBER_ID), reponsible for the heat, if required
std::string getHEAT_RESPONSIBILITY(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setHEAT_RESPONSIBILITY(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Free text for operator comments.
std::string getCOMMENTS(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setCOMMENTS(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
bool select(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT);
//## ----------------------------------END-GENERATED-CODE---------------------
//## ----------------------------------YOUR-CODE------------------------------
bool selectByREVTIME(const CDateTime& REVTIME, const std::string& Operator);
bool copy(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT, bool Commit, cCBS_ODBC_DBError &Error);
bool exists(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT);
bool checkNULLValues(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT);
};
#endif /* _INC_CHD_HEAT_DATA_INCLUDED */
| [
"[email protected]"
] | |
b5a0fc7eed0ce3a93bb9ead95a2b81679c62e8d5 | ddef3a21a3a7b5eed7a6126a5edc8456c54b2807 | /etherlib/rpcresult.cpp | 284037be0be3a8bb3625b9acf91289abdea26427 | [
"MIT"
] | permissive | mjmau/ethslurp | d490b33f0344f17dfd48a44cdbd05ecc51c6d53e | 8ad8afc4f2991871fbc00baabb90229b754033c3 | refs/heads/master | 2021-06-10T12:47:54.364257 | 2017-01-07T08:02:52 | 2017-01-07T08:02:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,329 | cpp | /*--------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2016 Great Hill Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--------------------------------------------------------------------------------*/
/*
* This file was generated with makeClass. Edit only those parts of the code inside
* of 'EXISTING_CODE' tags.
*/
#include "rpcresult.h"
//---------------------------------------------------------------------------
IMPLEMENT_NODE(CRPCResult, CBaseNode, curVersion);
//---------------------------------------------------------------------------
void CRPCResult::Format(CExportContext& ctx, const SFString& fmtIn, void *data) const
{
if (!isShowing())
return;
if (fmtIn.IsEmpty())
{
ctx << toJson();
return;
}
SFString fmt = fmtIn;
if (handleCustomFormat(ctx, fmt, data))
return;
CRPCResultNotify dn(this);
while (!fmt.IsEmpty())
ctx << getNextChunk(fmt, nextRpcresultChunk, &dn);
}
//---------------------------------------------------------------------------
SFString nextRpcresultChunk(const SFString& fieldIn, SFBool& force, const void *data)
{
CRPCResultNotify *rp = (CRPCResultNotify*)data;
const CRPCResult *rpc = rp->getDataPtr();
// Now give customized code a chance to override
SFString ret = nextRpcresultChunk_custom(fieldIn, force, data);
if (!ret.IsEmpty())
return ret;
switch (tolower(fieldIn[0]))
{
case 'i':
if ( fieldIn % "id" ) return rpc->id;
break;
case 'j':
if ( fieldIn % "jsonrpc" ) return rpc->jsonrpc;
break;
case 'r':
if ( fieldIn % "result" ) return rpc->result;
break;
}
// Finally, give the parent class a chance
ret = nextBasenodeChunk(fieldIn, force, rpc);
if (!ret.IsEmpty())
return ret;
return "<span class=warning>Field not found: [{" + fieldIn + "}]</span>\n";
}
//---------------------------------------------------------------------------------------------------
SFBool CRPCResult::setValueByName(const SFString& fieldName, const SFString& fieldValue)
{
// EXISTING_CODE
// EXISTING_CODE
switch (tolower(fieldName[0]))
{
case 'i':
if ( fieldName % "id" ) { id = fieldValue; return TRUE; }
break;
case 'j':
if ( fieldName % "jsonrpc" ) { jsonrpc = fieldValue; return TRUE; }
break;
case 'r':
if ( fieldName % "result" ) { result = fieldValue; return TRUE; }
break;
default:
break;
}
return FALSE;
}
//---------------------------------------------------------------------------------------------------
void CRPCResult::finishParse()
{
// EXISTING_CODE
// EXISTING_CODE
}
//---------------------------------------------------------------------------------------------------
void CRPCResult::Serialize(SFArchive& archive)
{
if (!SerializeHeader(archive))
return;
if (archive.isReading())
{
archive >> jsonrpc;
archive >> result;
archive >> id;
finishParse();
} else
{
archive << jsonrpc;
archive << result;
archive << id;
}
}
//---------------------------------------------------------------------------
void CRPCResult::registerClass(void)
{
static bool been_here=false;
if (been_here) return;
been_here=true;
SFInt32 fieldNum=1000;
ADD_FIELD(CRPCResult, "schema", T_NUMBER|TS_LABEL, ++fieldNum);
ADD_FIELD(CRPCResult, "deleted", T_BOOL|TS_LABEL, ++fieldNum);
ADD_FIELD(CRPCResult, "jsonrpc", T_TEXT, ++fieldNum);
ADD_FIELD(CRPCResult, "result", T_TEXT, ++fieldNum);
ADD_FIELD(CRPCResult, "id", T_TEXT, ++fieldNum);
// Hide our internal fields, user can turn them on if they like
HIDE_FIELD(CRPCResult, "schema");
HIDE_FIELD(CRPCResult, "deleted");
// EXISTING_CODE
// EXISTING_CODE
}
//---------------------------------------------------------------------------
int sortRpcresult(const SFString& f1, const SFString& f2, const void *rr1, const void *rr2)
{
CRPCResult *g1 = (CRPCResult*)rr1;
CRPCResult *g2 = (CRPCResult*)rr2;
SFString v1 = g1->getValueByName(f1);
SFString v2 = g2->getValueByName(f1);
SFInt32 s = v1.Compare(v2);
if (s || f2.IsEmpty())
return (int)s;
v1 = g1->getValueByName(f2);
v2 = g2->getValueByName(f2);
return (int)v1.Compare(v2);
}
int sortRpcresultByName(const void *rr1, const void *rr2) { return sortRpcresult("rp_Name", "", rr1, rr2); }
int sortRpcresultByID (const void *rr1, const void *rr2) { return sortRpcresult("rpcresultID", "", rr1, rr2); }
//---------------------------------------------------------------------------
SFString nextRpcresultChunk_custom(const SFString& fieldIn, SFBool& force, const void *data)
{
CRPCResultNotify *rp = (CRPCResultNotify*)data;
const CRPCResult *rpc = rp->getDataPtr();
switch (tolower(fieldIn[0]))
{
// EXISTING_CODE
// EXISTING_CODE
default:
break;
}
#pragma unused(rp)
#pragma unused(rpc)
return EMPTY;
}
//---------------------------------------------------------------------------
SFBool CRPCResult::handleCustomFormat(CExportContext& ctx, const SFString& fmtIn, void *data) const
{
// EXISTING_CODE
// EXISTING_CODE
return FALSE;
}
//---------------------------------------------------------------------------
SFBool CRPCResult::readBackLevel(SFArchive& archive)
{
SFBool done=FALSE;
// EXISTING_CODE
// EXISTING_CODE
return done;
}
//---------------------------------------------------------------------------
// EXISTING_CODE
// EXISTING_CODE
| [
"[email protected]"
] | |
4d838ab53cc812c1553532101741772f354973f8 | 5998b5ca67574f1d7e79d6532c4227dec7a9db3d | /Engine/Misc/Sources/Math/Vector.cpp | 2761e64f0fe20c5033a136921d51f75696420f91 | [
"MIT"
] | permissive | kaluginadaria/YetAnotherProject | 2adb3b7e57eaf1312707cbeed27f2c406f41c9a0 | abedd20b484f868ded83e72261970703a27e024d | refs/heads/dev | 2020-03-14T23:00:09.025815 | 2018-05-09T08:51:32 | 2018-05-09T08:51:32 | 131,834,054 | 0 | 0 | MIT | 2018-05-09T08:51:33 | 2018-05-02T10:16:23 | C++ | UTF-8 | C++ | false | false | 4,294 | cpp | #include "Vector.hpp"
#include "Vector2.hpp"
#include <assert.h>
#include <cmath>
#define OPERATION(_SIGN, _R) \
X _SIGN _R.X; \
Y _SIGN _R.Y; \
Z _SIGN _R.Z;
#define OPERATION_LIST(_SIGN, _R) \
X _SIGN _R.X, \
Y _SIGN _R.Y, \
Z _SIGN _R.Z
#define OPERATION_FLOAT(_SIGN, _R) \
X _SIGN _R; \
Y _SIGN _R; \
Z _SIGN _R;
#define OPERATION_LIST_FLOAT(_SIGN, _R) \
X _SIGN _R, \
Y _SIGN _R, \
Z _SIGN _R
#define NO_ZERO(_R) assert(_R.X); assert(_R.Y); assert(_R.Z);
// constants
const FVector FVector::ZeroVector = FVector( 0, 0, 0);
const FVector FVector::Forward = FVector( 1, 0, 0);
const FVector FVector::Backward = FVector(-1, 0, 0);
const FVector FVector::Upward = FVector( 0, 1, 0);
const FVector FVector::Downward = FVector( 0,-1, 0);
const FVector FVector::Rightward = FVector( 0, 0, 1);
const FVector FVector::Leftward = FVector( 0, 0,-1);
FVector::FVector()
: X(0), Y(0), Z(0)
{}
FVector::FVector(float X, float Y, float Z)
: X(X), Y(Y), Z(Z)
{}
FVector::FVector(const FVector& r)
: X(r.X), Y(r.Y), Z(r.Z)
{}
FVector::FVector(const FVector2& r)
: X(r.X), Y(r.Y), Z(0)
{}
FVector& FVector::operator=(const FVector& r)
{
OPERATION(=, r);
return *this;
}
FVector& FVector::operator=(const FVector2& r)
{
X = r.X;
Y = r.Y;
Z = 0;
return *this;
}
float& FVector::operator[](int i)
{
switch (i) {
case 0: return X;
case 1: return Y;
case 2: return Z;
}
throw std::out_of_range("");
}
const float& FVector::operator[](int i) const
{
return const_cast<FVector&>(*this)[i];
}
// FVector - FVector
FVector FVector::operator+(const FVector& r) const { return FVector(OPERATION_LIST(+, r)); }
FVector FVector::operator-(const FVector& r) const { return FVector(OPERATION_LIST(-, r)); }
FVector FVector::operator*(const FVector& r) const { return FVector(OPERATION_LIST(*, r)); }
FVector FVector::operator/(const FVector& r) const { NO_ZERO(r); return FVector(OPERATION_LIST(/, r)); }
FVector FVector::operator^(const FVector& r) const
{
return FVector(
Y * r.Z - r.Y * Z,
Z * r.X - r.Z * X,
X * r.Y - r.X * Y);
}
FVector& FVector::operator+=(const FVector& r) { OPERATION(+=, r); return *this; }
FVector& FVector::operator-=(const FVector& r) { OPERATION(-=, r); return *this; }
FVector& FVector::operator*=(const FVector& r) { OPERATION(*=, r); return *this; }
FVector& FVector::operator/=(const FVector& r) { NO_ZERO(r); OPERATION(/=, r); return *this; }
FVector& FVector::operator^=(const FVector& r)
{
X = Y * r.Z - r.Y * Z;
Y = Z * r.X - r.Z * X;
Z = X * r.Y - r.X * Y;
return *this;
}
// FVector - Scalar
FVector FVector::operator+(float r) const { return FVector(OPERATION_LIST_FLOAT(+, r)); }
FVector FVector::operator-(float r) const { return FVector(OPERATION_LIST_FLOAT(-, r)); }
FVector FVector::operator*(float r) const { return FVector(OPERATION_LIST_FLOAT(*, r)); }
FVector FVector::operator/(float r) const { assert(r); return FVector(OPERATION_LIST_FLOAT(/, r)); }
FVector& FVector::operator+=(float r) { OPERATION_FLOAT(+=, r) return *this; }
FVector& FVector::operator-=(float r) { OPERATION_FLOAT(+=, r) return *this; }
FVector& FVector::operator*=(float r) { OPERATION_FLOAT(+=, r) return *this; }
FVector& FVector::operator/=(float r) { assert(r); OPERATION_FLOAT(+=, r) return *this; }
// Misc
FVector FVector::operator-() const
{
return FVector(-X, -Y, -Z);
}
bool FVector::operator==(const FVector& r) const
{
return X == r.X
&& Y == r.Y
&& Z == r.Z;
}
bool FVector::operator!=(const FVector& r) const
{
return !(*this == r);
}
float FVector::Size() const
{
return std::sqrtf(X*X + Y*Y + Z*Z);
}
float FVector::SizeSq() const
{
return X*X + Y*Y + Z*Z;
}
FVector FVector::GetNormal() const
{
float size = Size();
return FVector(OPERATION_LIST_FLOAT(/, size));
}
FVector& FVector::Normalise()
{
float size = Size();
OPERATION_FLOAT(/=, size)
return *this;
}
FVector FVector::Lerp(const FVector& r, float factor)
{
return (*this) - (r - (*this)) * factor;
}
std::string FVector::ToString() const
{
return "X: " + std::to_string(X) + " "
+ "Y: " + std::to_string(Y) + " "
+ "Z: " + std::to_string(Z);
} | [
"[email protected]"
] | |
3a1b06b436eff3c90be9d0f4132a8414813e0302 | 1a29e3fc23318be40f27339a749bbc3bdc59c0c3 | /codeforces/gym/102392/j.cpp | 3680ee594d57630e1c4ae10df975c354d4d51990 | [] | no_license | wdzeng/cp-solutions | 6c2ac554f6d291774929bc6ad612c4c2e3966c9f | 8d39fcbda812a1db7e03988654cd20042cf4f854 | refs/heads/master | 2023-03-23T17:23:08.809526 | 2020-12-05T00:29:21 | 2020-12-05T00:29:21 | 177,706,525 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define x first
#define y second
#define all(v) v.begin(), v.end()
#define ms(v) memset(v, 0, sizeof(v))
#define mss(v) memset(v, -1, sizeof(v))
const int N = 1000;
vector<pii> adj[N];
int main() {
cin.tie(0), ios::sync_with_stdio(0);
int n;
cin >> n;
for (int i = n * (n - 1) / 2; i; i--) {
int a, b, w;
cin >> a >> b >> w;
a--, b--;
adj[a].emplace_back(w, b);
adj[b].emplace_back(w, a);
}
ll ans = 0;
for (int i = 0; i < n; i++) {
sort(all(adj[i]));
for (int j = 1; j < adj[i].size(); j += 2) ans += adj[i][j].first;
}
cout << ans << endl;
return 0;
} | [
"[email protected]"
] | |
a1643edb456727936e3854827b21be9c05e9d67d | 8fd2732c941c818e570bf842c4fe9e59a153b179 | /RemoteControl/RemoteControlDlg.cpp | b33773a7350f810b1ad55a5768cd301a27b859e4 | [] | no_license | yzqcode/RemoteControl | c3546184ccc2586d3e25106f9485fa90dfe10390 | ad6c224ec2d3c5975b82618be78c46c8774e04b9 | refs/heads/master | 2021-01-13T01:55:15.094059 | 2015-08-30T00:52:59 | 2015-08-30T00:52:59 | 41,611,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,901 | cpp |
// RemoteControlDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "RemoteControl.h"
#include "RemoteControlDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
typedef struct
{
char *title; //列表的名称
int nWidth; //列表的宽度
}COLUMNSTRUCT;
COLUMNSTRUCT g_Column_Online_Data[] =
{
{ "IP", 148 },
{ "区域", 150 },
{ "计算机名/备注", 160 },
{ "操作系统", 128 },
{ "CPU", 80 },
{ "摄像头", 81 },
{ "PING", 81 }
};
COLUMNSTRUCT g_Column_Message_Data[] =
{
{ "信息类型", 68 },
{ "时间", 100 },
{ "信息内容", 660 }
};
//变量声明
int g_Column_Count_Message = 3; //日志列表的个数
int g_Column_Count_Online = 7; //主机列表的个数
int g_Column_Online_Width = 0; //列总宽度
int g_Column_Message_Width = 0; //列总宽度
CIOCPServer *m_iocpServer = NULL;
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CRemoteControlDlg 对话框
CRemoteControlDlg::CRemoteControlDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CRemoteControlDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
iCount = 0;
}
void CRemoteControlDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_ONLINE, m_CList_Online);
DDX_Control(pDX, IDC_MESSAGE, m_CList_Message);
}
BEGIN_MESSAGE_MAP(CRemoteControlDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_SIZE()
ON_NOTIFY(NM_RCLICK, IDC_ONLINE, &CRemoteControlDlg::OnNMRClickOnline)
ON_COMMAND(ID_ONLINE_AUDIO, &CRemoteControlDlg::OnOnlineAudio)
ON_COMMAND(ID_ONLINE_CMD, &CRemoteControlDlg::OnOnlineCmd)
ON_COMMAND(ID_ONLINE_DESKTOP, &CRemoteControlDlg::OnOnlineDesktop)
ON_COMMAND(ID_ONLINE_FILE, &CRemoteControlDlg::OnOnlineFile)
ON_COMMAND(ID_ONLINE_PROCESS, &CRemoteControlDlg::OnOnlineProcess)
ON_COMMAND(ID_ONLINE_REGEDIT, &CRemoteControlDlg::OnOnlineRegedit)
ON_COMMAND(ID_ONLINE_Remote, &CRemoteControlDlg::OnOnlineRemote)
ON_COMMAND(ID_ONLINE_SERVER, &CRemoteControlDlg::OnOnlineServer)
ON_COMMAND(ID_ONLINE_VIDEO, &CRemoteControlDlg::OnOnlineVideo)
ON_COMMAND(ID_ONLINE_WINDOW, &CRemoteControlDlg::OnOnlineWindow)
ON_COMMAND(ID_ONLINE_DELETE, &CRemoteControlDlg::OnOnlineDelete)
ON_COMMAND(ID_MAIN_ABOUT, &CRemoteControlDlg::OnMainAbout)
ON_COMMAND(ID_MAIN_BUILD, &CRemoteControlDlg::OnMainBuild)
ON_COMMAND(ID_MAIN_SET, &CRemoteControlDlg::OnMainSet)
ON_COMMAND(ID_MAIN_CLOSE, &CRemoteControlDlg::OnMainClose)
ON_MESSAGE(UM_ICONNOTIFY, (LRESULT(__thiscall CWnd::*)(WPARAM, LPARAM))OnIconNotify)
ON_COMMAND(IDM_NOTIFY_CLOSE, &CRemoteControlDlg::OnNotifyClose)
ON_COMMAND(IDM_NOTIFY_SHOW, &CRemoteControlDlg::OnNotifyShow)
ON_WM_CLOSE()
END_MESSAGE_MAP()
//所有关于socket的处理都要经过这个函数
void CALLBACK CRemoteControlDlg::NotifyProc(LPVOID lpParam, ClientContext *pContext, UINT nCode)
{
switch (nCode)
{
case NC_CLIENT_CONNECT:
break;
case NC_CLIENT_DISCONNECT:
//g_pConnectView->PostMessage(WM_REMOVEFROMLIST, 0, (LPARAM)pContext);
break;
case NC_TRANSMIT:
break;
case NC_RECEIVE:
//ProcessReceive(pContext); //这里是有数据到来,但没有完全接受
break;
case NC_RECEIVE_COMPLETE:
//ProcessReceiveComplete(pContext); //这里是完全接收发送来的数据 跟进 ProcessReceiveComplete
break;
}
}
void CRemoteControlDlg::Activate(UINT nPort, UINT nMaxConnections)
{
CString str;
if (m_iocpServer != NULL)
{
m_iocpServer->Shutdown();
delete m_iocpServer;
}
m_iocpServer = new CIOCPServer;
////lang2.1_8
// 开启IPCP服务器 最大连接 端口 查看NotifyProc回调函数 函数定义
if (m_iocpServer->Initialize(NotifyProc, NULL, 100000, nPort))
{
char hostname[256];
gethostname(hostname, sizeof(hostname));
HOSTENT *host = gethostbyname(hostname);
if (host != NULL)
{
for (int i = 0;; i++)
{
str += inet_ntoa(*(IN_ADDR*)host->h_addr_list[i]);
if (host->h_addr_list[i] + host->h_length >= host->h_name)
break;
str += "/";
}
}
str.Format("监听端口: %d成功", nPort);
ShowMessage(true, str);
}
else
{
str.Format("监听端口: %d失败", nPort);
ShowMessage(false, str);
}
//m_wndStatusBar.SetPaneText(3, "连接: 0");
}
// CRemoteControlDlg 消息处理程序
BOOL CRemoteControlDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDD_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
CreatStatusBar();//创建状态栏
InitList();//初始化列表信息
Activate(2000, 9999);
test();//测试上线
HMENU hmenu;
hmenu = LoadMenu(NULL, MAKEINTRESOURCE(IDR_MENU_MAIN)); //载入菜单资源
::SetMenu(this->GetSafeHwnd(), hmenu); //为窗口设置菜单
::DrawMenuBar(this->GetSafeHwnd()); //显示菜单
AddNotify();
CRect rect;
GetWindowRect(&rect);
rect.bottom += 20;
MoveWindow(rect);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CRemoteControlDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CRemoteControlDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CRemoteControlDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CRemoteControlDlg::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize(nType, cx, cy);
if (m_CList_Online.m_hWnd != NULL)
{
CRect rc;
rc.left = 10; //列表的左坐标
rc.top = 0; //列表的上坐标
rc.right = cx - 10; //列表的右坐标
rc.bottom = cy - 160; //列表的下坐标
m_CList_Online.MoveWindow(rc);
double dcx = cx; //对话框的总宽度
for (int i = 0; i < g_Column_Count_Online; i++){ //遍历每一个列
double dd = g_Column_Online_Data[i].nWidth; //得到当前列的宽度
dd /= g_Column_Online_Width+20; //看一看当前宽度占总长度的几分之几
dd *= dcx; //用原来的长度乘以所占的几分之几得到当前的宽度
int lenth = dd; //转换为int 类型
m_CList_Online.SetColumnWidth(i, (lenth)); //设置当前的宽度
}
}
if (m_CList_Message.m_hWnd != NULL)
{
CRect rc;
rc.left = 10; //列表的左坐标
rc.top = cy - 156; //列表的上坐标
rc.right = cx - 10; //列表的右坐标
rc.bottom = cy - 16; //列表的下坐标
m_CList_Message.MoveWindow(rc);
double dcx = cx;
for (int i = 0; i < g_Column_Count_Message; i++){ //遍历每一个列
double dd = g_Column_Message_Data[i].nWidth; //得到当前列的宽度
dd /= g_Column_Message_Width+20; //看一看当前宽度占总长度的几分之几
dd *= dcx; //用原来的长度乘以所占的几分之几得到当前的宽度
int lenth = dd; //转换为int 类型
m_CList_Message.SetColumnWidth(i, (lenth)); //设置当前的宽度
}
}
if (m_wndStatusBar.m_hWnd != NULL){ //当对话框大小改变时 状态条大小也随之改变
CRect rc;
rc.top = cy - 20;
rc.left = 0;
rc.right = cx;
rc.bottom = cy;
m_wndStatusBar.MoveWindow(rc);
m_wndStatusBar.SetPaneInfo(0, m_wndStatusBar.GetItemID(0), SBPS_POPOUT, cx - 10);
}
// TODO: 在此处添加消息处理程序代码
}
// 初始化列表
int CRemoteControlDlg::InitList()
{
m_CList_Online.SetExtendedStyle(LVS_EX_FULLROWSELECT);
m_CList_Message.SetExtendedStyle(LVS_EX_FULLROWSELECT);
for (int i = 0; i < g_Column_Count_Online; i++)
{
m_CList_Online.InsertColumn(i, g_Column_Online_Data[i].title, LVCFMT_CENTER, g_Column_Online_Data[i].nWidth);
g_Column_Online_Width += g_Column_Online_Data[i].nWidth; //得到总宽度
}
for (int i = 0; i < g_Column_Count_Message; i++)
{
m_CList_Message.InsertColumn(i, g_Column_Message_Data[i].title, LVCFMT_CENTER, g_Column_Message_Data[i].nWidth);
g_Column_Message_Width += g_Column_Message_Data[i].nWidth; //得到总宽度
}
return 0;
}
// 添加上线主机信息
void CRemoteControlDlg::AddList(CString strIP, CString strAddr, CString strPCName, CString strOS, CString strCPU, CString strVideo, CString strPing)
{
m_CList_Online.InsertItem(0, strIP); //默认为0行 这样所有插入的新列都在最上面
m_CList_Online.SetItemText(0, ONLINELIST_ADDR, strAddr); //设置列的显示字符 这里 ONLINELIST_ADDR等 为第二节课中的枚举类型 用这样的方法
m_CList_Online.SetItemText(0, ONLINELIST_COMPUTER_NAME, strPCName); //解决问题会避免以后扩展时的冲突
m_CList_Online.SetItemText(0, ONLINELIST_OS, strOS);
m_CList_Online.SetItemText(0, ONLINELIST_CPU, strCPU);
m_CList_Online.SetItemText(0, ONLINELIST_VIDEO, strVideo);
m_CList_Online.SetItemText(0, ONLINELIST_PING, strPing);
ShowMessage(true, strIP + "主机上线");
}
//添加日志消息的处理:
void CRemoteControlDlg::ShowMessage(bool bIsOK, CString strMsg)
{
CString strIsOK, strTime;
CTime t = CTime::GetCurrentTime();
strTime = t.Format("%H:%M:%S");
if (bIsOK)
{
strIsOK = "执行成功";
}
else{
strIsOK = "执行失败";
}
m_CList_Message.InsertItem(0, strIsOK);
m_CList_Message.SetItemText(0, 1, strTime);
m_CList_Message.SetItemText(0, 2, strMsg);
CString strStatusMsg;
if (strMsg.Find("上线") > 0) //处理上线还是下线消息
{
iCount++;
}
else if (strMsg.Find("下线") > 0)
{
iCount--;
}
else if (strMsg.Find("断开") > 0)
{
iCount--;
}
iCount = (iCount <= 0 ? 0 : iCount); //防止iCount 有-1的情况
strStatusMsg.Format("有%d个主机在线", iCount);
m_wndStatusBar.SetPaneText(0, strStatusMsg, TRUE); //在状态条上显示文字
}
// 伪造的上线信息,仅测试使用
void CRemoteControlDlg::test()
{
ShowMessage(true, "软件初始化成功...");
AddList("192.168.0.7", "本机局域网", "root", "Windows7", "3.2GHZ", "有", "10");
AddList("192.168.0.8", "本机局域网", "root", "Windows7", "3.2GHZ", "有", "10");
AddList("192.168.0.9", "本机局域网", "root", "Windows7", "3.2GHZ", "有", "10");
}
void CRemoteControlDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
// TODO: 在此添加控件通知处理程序代码
CMenu popup; //声明一个菜单变量
popup.LoadMenu(IDR_LIST); //载入菜单资源
CMenu* pM = popup.GetSubMenu(0); //得到菜单项
CPoint p;
GetCursorPos(&p); //得到鼠标指针的位置
int count = pM->GetMenuItemCount(); //得到菜单的个数
if (m_CList_Online.GetSelectedCount() == 0) //如果没有选中列表中的条目
{
// for (int i = 0; i < count - 2 ; i++) //遍历每一个菜单
// {
// pM->EnableMenuItem(i, MF_BYPOSITION | MF_DISABLED | MF_GRAYED); //该项变灰
// }
// //pM->EnableMenuItem(count - 1, MF_BYPOSITION | MF_DISABLED | MF_GRAYED);
//}
//// 全选
//if (m_CList_Online.GetItemCount() > 0) //列表中的条目项大于0
// pM->EnableMenuItem(count - 2, MF_BYPOSITION | MF_ENABLED); //激活倒数第二个菜单
//else
// pM->EnableMenuItem(count - 2, MF_BYPOSITION | MF_DISABLED | MF_GRAYED); //否则变灰
for (int i = 0; i < count; i++) //遍历每一个菜单
{
pM->EnableMenuItem(i, MF_BYPOSITION | MF_DISABLED | MF_GRAYED); //该项变灰
}
}
pM->TrackPopupMenu(TPM_LEFTALIGN, p.x, p.y, this); //在指定位置显示菜单
*pResult = 0;
}
void CRemoteControlDlg::OnOnlineAudio()
{
// TODO: 在此添加命令处理程序代码
MessageBox("语音管理");
}
void CRemoteControlDlg::OnOnlineCmd()
{
// TODO: 在此添加命令处理程序代码
MessageBox("终端管理");
}
void CRemoteControlDlg::OnOnlineDesktop()
{
// TODO: 在此添加命令处理程序代码
MessageBox("桌面管理");
}
void CRemoteControlDlg::OnOnlineFile()
{
// TODO: 在此添加命令处理程序代码
MessageBox("文件管理");
}
void CRemoteControlDlg::OnOnlineProcess()
{
// TODO: 在此添加命令处理程序代码
MessageBox("进程管理");
}
void CRemoteControlDlg::OnOnlineRegedit()
{
// TODO: 在此添加命令处理程序代码
MessageBox("注册表管理");
}
void CRemoteControlDlg::OnOnlineRemote()
{
// TODO: 在此添加命令处理程序代码
MessageBox("远程管理");
}
void CRemoteControlDlg::OnOnlineServer()
{
// TODO: 在此添加命令处理程序代码
MessageBox("服务管理");
}
void CRemoteControlDlg::OnOnlineVideo()
{
// TODO: 在此添加命令处理程序代码
MessageBox("s视频管理");
}
void CRemoteControlDlg::OnOnlineWindow()
{
// TODO: 在此添加命令处理程序代码
MessageBox("窗口管理");
}
void CRemoteControlDlg::OnOnlineDelete()
{
// TODO: 在此添加命令处理程序代码
CString strIP;
int iSelect = m_CList_Online.GetSelectionMark();
strIP = m_CList_Online.GetItemText(iSelect, ONLINELIST_IP);
m_CList_Online.DeleteItem(iSelect);
strIP += " 主机断开连接";
ShowMessage(true, strIP);
}
void CRemoteControlDlg::OnMainAbout()
{
// TODO: 在此添加命令处理程序代码
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
void CRemoteControlDlg::OnMainBuild()
{
// TODO: 在此添加命令处理程序代码
MessageBox("生成服务端");
}
void CRemoteControlDlg::OnMainSet()
{
// TODO: 在此添加命令处理程序代码
MessageBox("参数设置");
}
void CRemoteControlDlg::OnMainClose()
{
// TODO: 在此添加命令处理程序代码
PostMessage(WM_CLOSE, 0, 0);
}
//创建字符ID的数组
static UINT indicators[] =
{
IDS_STATUSBAR_STRING
};
// 创建状态栏
void CRemoteControlDlg::CreatStatusBar()
{
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators) / sizeof(UINT))) //创建状态条并设置字符资源的ID
{
TRACE0("Failed to create status bar\n");
return; // fail to create
}
CRect rc;
::GetWindowRect(m_wndStatusBar.m_hWnd, rc);
m_wndStatusBar.MoveWindow(rc); //移动状态条到指定位置
}
// 添加托盘图标
void CRemoteControlDlg::AddNotify()
{
nid.cbSize = sizeof(nid); //大小赋值
nid.hWnd = m_hWnd; //父窗口
nid.uID = IDR_MAINFRAME; //icon ID
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; //托盘所拥有的状态
nid.uCallbackMessage = UM_ICONNOTIFY; //回调消息
nid.hIcon = m_hIcon; //icon 变量
CString str = "PCRemote远程协助软件........."; //气泡提示
lstrcpyn(nid.szTip, (LPCSTR)str, sizeof(nid.szTip) / sizeof(nid.szTip[0]));
Shell_NotifyIcon(NIM_ADD, &nid); //显示托盘
}
void CRemoteControlDlg::OnIconNotify(WPARAM wParam, LPARAM lParam)
{
switch ((UINT)lParam)
{
case WM_LBUTTONDOWN: // click or dbclick left button on icon
case WM_LBUTTONDBLCLK: // should show desktop
if (!IsWindowVisible())
ShowWindow(SW_SHOW);
else
ShowWindow(SW_HIDE);
break;
case WM_RBUTTONDOWN: // click right button, show menu
CMenu menu;
menu.LoadMenu(IDR_MENU_NOTIFY);
CPoint point;
GetCursorPos(&point);
SetForegroundWindow();
menu.GetSubMenu(0)->TrackPopupMenu(
TPM_LEFTBUTTON | TPM_RIGHTBUTTON,
point.x, point.y, this, NULL);
PostMessage(WM_USER, 0, 0);
break;
}
}
void CRemoteControlDlg::OnNotifyClose()
{
// TODO: 在此添加命令处理程序代码
PostQuitMessage(0);
}
void CRemoteControlDlg::OnNotifyShow()
{
// TODO: 在此添加命令处理程序代码
ShowWindow(SW_SHOW);
}
void CRemoteControlDlg::OnClose()
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
Shell_NotifyIcon(NIM_DELETE, &nid); //销毁图标
CDialogEx::OnClose();
}
| [
"[email protected]"
] | |
fe4fb59d5c399e3e0cd8ff22b45a3f02d7dfb53e | fa800a1cea9ae09e49f61a05343acc02e9b79a57 | /GAME2005_A1_LeTrung_ShuDeng/src/StartScene.cpp | d8a189d43f8af50361ae281301c32e657167342e | [] | no_license | KojimaMcMaple/GAME_2005_GAME-PHYSICS | b8c547b5faeb85b012876ef141cb1db64dc0bce9 | fda17a895b0082a77c833b9330b522b56725c53a | refs/heads/master | 2023-02-02T16:48:49.382055 | 2020-12-20T04:12:44 | 2020-12-20T04:12:44 | 297,480,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,040 | cpp | #include "StartScene.h"
#include <algorithm>
#include "Game.h"
#include "glm/gtx/string_cast.hpp"
#include "EventManager.h"
StartScene::StartScene()
{
StartScene::start();
}
StartScene::~StartScene()
= default;
void StartScene::draw()
{
drawDisplayList();
}
void StartScene::update()
{
updateDisplayList();
}
void StartScene::clean()
{
removeAllChildren();
}
void StartScene::handleEvents()
{
EventManager::Instance().update();
// Keyboard Events
if(EventManager::Instance().isKeyDown(SDL_SCANCODE_ESCAPE))
{
TheGame::Instance()->quit();
}
if(EventManager::Instance().isKeyDown(SDL_SCANCODE_1))
{
TheGame::Instance()->changeSceneState(PLAY_SCENE);
}
}
void StartScene::start()
{
const SDL_Color blue = { 0, 0, 255, 255 };
m_pStartLabel = new Label("GAME2005_A1", "Consolas", 80, blue, glm::vec2(400.0f, 40.0f));
m_pStartLabel->setParent(this);
addChild(m_pStartLabel);
m_pAuthorLabel1 = new Label("by Trung Le (Kyle) - 101264698", "Consolas", 20, blue, glm::vec2(400.0f, 90.0f));
m_pAuthorLabel1->setParent(this);
addChild(m_pAuthorLabel1);
m_pAuthorLabel2 = new Label("and Shu Deng - 101260645", "Consolas", 20, blue, glm::vec2(400.0f, 130.0f));
m_pAuthorLabel2->setParent(this);
addChild(m_pAuthorLabel2);
m_pInstructionsLabel = new Label("Press 1 to Play", "Consolas", 40, blue, glm::vec2(400.0f, 180.0f));
m_pInstructionsLabel->setParent(this);
addChild(m_pInstructionsLabel);
m_pShip = new Ship();
m_pShip->getTransform()->position = glm::vec2(400.0f, 300.0f);
addChild(m_pShip);
// Start Button
m_pStartButton = new Button();
m_pStartButton->getTransform()->position = glm::vec2(400.0f, 400.0f);
m_pStartButton->addEventListener(CLICK, [&]()-> void
{
m_pStartButton->setActive(false);
TheGame::Instance()->changeSceneState(PLAY_SCENE);
});
m_pStartButton->addEventListener(MOUSE_OVER, [&]()->void
{
m_pStartButton->setAlpha(128);
});
m_pStartButton->addEventListener(MOUSE_OUT, [&]()->void
{
m_pStartButton->setAlpha(255);
});
addChild(m_pStartButton);
}
| [
"[email protected]"
] | |
cf8699ec2ba3f264958164023eb98e0cd9c90868 | 433a2faf5a215307165a67a5b7e8a3632c7e87a2 | /基礎題庫/a005.cpp | 1fe476c394052a9613ee6518d4980b15c1c47d1d | [] | no_license | evo960225/GreenJudge | 79cccb7280b9fcb99f811738d54f5c5d3d67bd70 | 37aa7e96294121f1c1a558e4a91ccbc67cea1caf | refs/heads/master | 2021-10-24T03:59:29.169539 | 2021-10-13T06:45:29 | 2021-10-13T06:45:29 | 13,683,843 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 135 | cpp | #include<iostream>
#include<cstdio>
using namespace std;
int main(){
int a,b;
while(cin>>a>>b){
cout<<a*b<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
3eb017c428f942e9d7650944416ebd2926700d92 | 4c492e5c480c580614f7f85e65ec8a17ceacc12e | /Semester 4 - Fall 2015/Assignment 3/CECS 302 - 3.2a.cpp | 870838f54d28569bd8a67150280bb00bee93c906 | [] | no_license | zshumate/My-Code | 01844f3a22086ff6638c853ab255327cfe0af752 | 15d13b5d99ba8c434acb37a8b79c50c2ffed0e94 | refs/heads/master | 2021-01-17T10:12:11.686256 | 2017-03-06T03:22:09 | 2017-03-06T03:22:09 | 84,006,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,751 | cpp | //Assignment 3: 3.2a
//Zachary Shumate
//10-12-2015
//CECS 302-01
#include <iostream>
#include<vector>
using namespace std;
template<typename Container>
void printCollection(const Container & c, ostream & out = cout)
{
if (c.empty())
out << "(empty)";
else
{
typename Container::const_iterator itr = c.begin();
out << "[ " << *itr++; // Print first item
while (itr != c.end())
out << ", " << *itr++;
out << " ]" << endl;
}
}
template <typename Object>
class Vector{
public:
explicit Vector(int initSize = 0):theSize(initSize), theCapacity(initSize+SPARE_CAPACITY){
objects = new Object[theCapacity];
}
Vector(const Vector & rhs):objects(NULL){
operator=(rhs);
}
~Vector(){
delete[] objects;
}
const Vector & operator=(const Vector & rhs){
if(this != &rhs){
delete[] objects;
theSize = rhs.size();
theCapacity = rhs.theCapacity;
objects = new Object[capacity()];
for(int k=0; k<size(); k++)
objects[k] = rhs.objects[k];
}
return *this;
}
void resize(int newSize){
if(newSize>theCapacity)
reserve(newSize*2+1);
theSize = newSize;
}
void reserve(int newCapacity){
if(newCapacity<theSize)
return;
Object *oldArray = objects;
objects = new Object[newCapacity];
for(int k=0; k<theSize; k++)
objects[k] = oldArray[k];
theCapacity = newCapacity;
delete[] oldArray;
}
const Object & operator[](int index) const{
return objects[index];
}
bool empty() const{
return size()==0;
}
int size() const{
return theSize;
}
int capacity() const{
return theCapacity;
}
void push_back(const Object & x){
if(theSize == theCapacity)
reserve(2*theCapacity+1);
objects[theSize++] = x;
}
void pop_back(){
theSize--;
}
const Object & back() const{
return objects[theSize-1];
}
void swap(int n1, int n2){
Object temp;
temp = objects[n1];
objects[n1] = objects[n2];
objects[n2] = temp;
}
typedef Object *iterator;
typedef const Object *const_iterator;
iterator begin(){
return &objects[0];
}
const_iterator begin() const{
return &objects[0];
}
iterator end(){
return &objects[size()];
}
const_iterator end() const{
return &objects[size()];
}
enum{
SPARE_CAPACITY = 16
};
private:
int theSize;
int theCapacity;
Object *objects;
};
main(){
Vector<int> vector(0);
vector.push_back(-65);
vector.push_back(193);
vector.push_back(24);
vector.push_back(72);
vector.push_back(-54);
cout << "Vector size = " << vector.size() << endl;
cout << "Vector: ";
printCollection(vector, cout);
vector.swap(2,5);
//printCollection(vector, cout);
cout << "[ -65, -54, 24, 72, 193 ]" << endl;
}
| [
"[email protected]"
] | |
5c90d3ea6ef01e4a7b10ed44fc9e9944f2c8dcdb | 0739bfedcffaf0bcf98a2e69063011a27a89bcfb | /src/detection/TimeDetection.cpp | ec86aea4291416f9770f786c60e9e32f4a5ea177 | [] | no_license | kakekake314/Kougakusai2017-M2 | 85cdcadb04f44ba5816e21c2f8c9df0d8f7243bc | 51262aa1af40a769a2f992661e7ef71ea522e957 | refs/heads/master | 2021-06-16T00:19:19.338467 | 2017-05-02T06:48:43 | 2017-05-02T06:48:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,409 | cpp | /**
* @file TimeDetection.cpp
* @brief 時間検知クラス
* @author sisido
*/
#include "TimeDetection.h"
using namespace device;
namespace detection{
TimeDetection::TimeDetection(){
clock = Clock();
base_time_ = 0;
target_time_ = 0;
display_ = Display::getInstance();
}
bool TimeDetection::isDetected(){
uint32_t now_time_ = clock.now();
uint32_t def = now_time_ - base_time_;
char msg[128];
sprintf(msg,"base : %ld", base_time_);
display_->updateDisplay(msg, 8);
sprintf(msg,"tar : %ld", target_time_);
display_->updateDisplay(msg, 9);
sprintf(msg,"now : %ld", now_time_);
display_->updateDisplay(msg, 10);
sprintf(msg,"def : %ld", def);
display_->updateDisplay(msg, 11);
if(def >= target_time_){
ev3_speaker_play_tone ( 500, 100);
display_->updateDisplay("target time now! ", 13);
return true;
}return false;
}
void TimeDetection::setBaseTime (){
base_time_ = clock.now();
}
void TimeDetection::setTargetTime(uint32_t target_time){
target_time_ = target_time;
}
// void TimeDetection::setTimeConfig(uint32_t base_time, uint32_t target_time){
// this->setBaseTime(base_time);
// this->setTargetTime(target_time);
// }
};
| [
"[email protected]"
] | |
af3bf687139b57800a6795aba1a70ca3e702571c | b0e6f616ec3030d7dbb5fa4d9c35e3c2c084c6eb | /src/test/cpp/cfs/osal/MailboxTest.hpp | 18c7568a3c5dca1d475580391a70c017567cd676 | [
"Apache-2.0",
"LGPL-3.0-only",
"CC-BY-4.0",
"GPL-3.0-only",
"CC-BY-NC-SA-4.0",
"LGPL-2.0-or-later",
"BSD-2-Clause"
] | permissive | doevelopper/cfs-osal | 0557ea9138f3a034d5eac06040d23d3c8dde1c73 | cd5a8801251e750a9c50718bf15b5e394ced20d0 | refs/heads/master | 2023-01-28T02:11:25.707544 | 2019-06-22T22:52:40 | 2019-06-22T22:52:40 | 132,522,764 | 0 | 1 | Apache-2.0 | 2023-01-22T00:28:22 | 2018-05-07T22:24:52 | Python | UTF-8 | C++ | false | false | 737 | hpp |
#ifndef CFS_OSAL_MAILBOXTEST_HPP
#define CFS_OSAL_MAILBOXTEST_HPP
#include <gmock/gmock.h>
#include <cfs/osal/log/TestLogger.hpp>
//#include <cfs/osal/Mailbox.hpp>
namespace cfs::osal::test
{
class MailboxTest : public ::testing::Test
{
public:
MailboxTest();
MailboxTest(const MailboxTest&) = default;
MailboxTest(MailboxTest&&) = default;
MailboxTest& operator=(const MailboxTest&) = default;
MailboxTest& operator=(MailboxTest&&) = default;
virtual ~MailboxTest();
void SetUp() override;
void TearDown() override;
protected:
static log4cxx::LoggerPtr logger;
private:
};
}
#endif
| [
"[email protected]"
] | |
e4f620076c9e212143217a864ee40e7993089396 | f4c1902534825c7b97a9392e78b148345a011147 | /Region/shanghai/1010.cpp | b2720b37b6b3cd05c5b7f4a10aa5d3e43ae94cc4 | [] | no_license | obsolescenceL/obsolescenceL | 6443fbfc88f5286007800b809839ef3b663b6ce0 | 096f50469beb0c98b71b828d185b685d071177ed | refs/heads/master | 2020-04-04T00:15:43.241792 | 2017-06-10T05:24:38 | 2017-06-10T05:24:38 | 28,584,497 | 3 | 2 | null | 2017-06-10T05:24:39 | 2014-12-29T07:41:23 | C++ | UTF-8 | C++ | false | false | 1,352 | cpp | /*************************************************************************
File Name: 1010.cpp
ID: obsoles1
PROG:
LANG: C++
Mail: [email protected]
Created Time: 2015年09月26日 星期六 12时33分26秒
************************************************************************/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cctype>
#include<ctime>
#include<cstdlib>
#include<string>
#include<vector>
#include<set>
#include<bitset>
#define Max(x,y) ((x)>(y)?(x):(y))
#define Min(x,y) ((x)<(y)?(x):(y))
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();++it)
#define Abs(x,y) ((x)>(y)?((x)-(y)):((y)-(x)))
#define ll long long
#define Mem0(x) memset(x,0,sizeof(x))
#define Mem1(x) memset(x,-1,sizeof(x))
#define MemX(x) memset(x,0x3f,sizeof(x))
#define pb push_back
using namespace std;
int main(){
int t,n,a,b,L,l,r,maxn,s;
while(~scanf("%d",&t)){
for(int nc=1;nc<=t;++nc){
scanf("%d%d%d%d",&n,&a,&b,&L);
maxn=s=l=r=0;
while(n--){
//cout<<"s="<<s<<endl;
scanf("%d",&l);
s+=b*(l-r);
scanf("%d",&r);
s-=a*(r-l);
//cout<<"s="<<s<<endl;
maxn=Min(maxn,s);
}
printf("Case #%d: %d\n",nc,-maxn);
}
}
}
| [
"[email protected]"
] | |
9ddec2b7926b6f199dd65e4141ac127a81f4ac87 | bc3568a7f1ef526f484e29ebf01096e4279c9292 | /gelataio_boy_control/src/hand_interface.cpp | 52cb5b5a8fe28e8ad89057bf92488c5422e179ac | [] | no_license | rfn123/gelataio-boy | 926dc466698f9d143db656076ae6cdb61f57e7e2 | 1d02197c5cb4c83fae044d8141d199a275e8f5c6 | refs/heads/master | 2020-09-15T16:26:56.601674 | 2019-09-30T22:38:40 | 2019-09-30T22:38:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | cpp | //
// Created by arne on 16.08.19.
//
#include <sstream>
#include "gelataio_boy_control/hand_interface.h"
#include <ros/ros.h>
bool DummyHand::grasp() {
std::stringstream ss;
ss << "Closing hand " << hand_name << ".";
ROS_INFO_STREAM(ss.str());
return true;
}
bool DummyHand::release() {
std::stringstream ss;
ss << "Opening hand " << hand_name << ".";
ROS_INFO_STREAM(ss.str());
return true;
}
| [
"[email protected]"
] | |
7dce5b66ea6ce29cfe1cb2e30d27c4d0ba338732 | 39d585477bdd26971deb13ca2924becadc1bb30a | /BattleCity/Item.h | 702a0c0823ba8f5c1579cb7ac66b878ac4054534 | [] | no_license | duyuit/BattleCity_Directx | 9920d1846a1a0a6418c7e55def10eb913c0205db | a244d7c4db59473cfcbaf71189916ce2256bd3c8 | refs/heads/master | 2020-03-07T04:43:26.347887 | 2018-06-13T10:52:58 | 2018-06-13T10:52:58 | 127,274,593 | 1 | 1 | null | 2018-06-13T10:52:59 | 2018-03-29T10:16:20 | C | UTF-8 | C++ | false | false | 747 | h | #pragma once
#include "Entity.h"
#include "Sprite.h"
class Item : public Entity
{
public:
~Item();
virtual void Update(float dt);
void Draw(D3DXVECTOR3 position = D3DXVECTOR3(), RECT sourceRect = RECT(), D3DXVECTOR2 scale = D3DXVECTOR2(), D3DXVECTOR2 transform = D3DXVECTOR2(), float angle = 0, D3DXVECTOR2 rotationCenter = D3DXVECTOR2(), D3DXCOLOR colorKey = D3DCOLOR_XRGB(255, 255, 255));
void OnSetPosition(D3DXVECTOR3 position);
void BeCollideWith_Player();
void Read(InputMemoryBitStream& is) override;
bool getDelete();
protected:
Item();
bool Init(D3DXVECTOR3 position);
float exist_time = 0;
float cout_time = 0;
virtual const char* fileName() = 0;
virtual RECT rect() = 0;
Sprite* mSprite;
RECT reg;
bool isDelete;
};
| [
"[email protected]"
] | |
0d34e7e945b476d3ee18b42484b5c2e3d67c1c2f | b6a847e45326815db5f268cd3a2812744fa3cd38 | /input.hpp | 81cc5e5929c55bc93c3653ec95f606f991938df3 | [
"MIT"
] | permissive | 190n/chip8 | 384221cf55d3e755e79b2684b61a65e9381570f6 | 08994ce4627eed9cfb7e150eb52fdd36371cbf90 | refs/heads/master | 2021-08-10T11:55:16.207106 | 2018-10-03T15:07:55 | 2018-10-03T15:07:55 | 136,063,264 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32 | hpp | #pragma once
char* getInput();
| [
"[email protected]"
] | |
8f42e8ec4bfc757afdc0872ef469f9dddc430921 | 2a64c259fdde52c1405a9c867260df995a54c931 | /codechef/ICPCTR01/SEGDIR.cpp | 00901c7d2c351582ebb4382352f3e554fd14920e | [] | no_license | arjitkansal/CP-contests | dab952af7624552e101701764cac8a29a5504435 | 05573e6a7096505029ef1ae06fc0e6f430f50848 | refs/heads/master | 2023-06-21T17:38:22.368174 | 2021-08-08T17:40:42 | 2021-08-08T17:40:42 | 310,842,153 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,812 | cpp | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
#define mod ((int)1e9+7)
#define lim 1000000000000000007
#define lim1 18446744073709551615 //Unsigned
#define sq(a) ((a)*(a))
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define mms(v,i) memset(v,i,sizeof(v))
#define pb push_back
#define pf push_front
#define ppb pop_back
#define ppf pop_front
#define REP(i,a,b) for (int i = a; i <= b; i++)
#define REPN(i,a,b) for (int i = a; i >= b; i--)
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
typedef pair<int,int> pi;
typedef pair<ll,ll> PL;
typedef pair<ll,int> PLI;
typedef pair<int,ll> PIL;
typedef pair<int,pair<int,int> > pii;
typedef pair<double,double> pdd;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> indexed_set;
ll power(ll a,ll b) {
a %= mod;
ll res=1;
while(b){
if(b%2==1) res=(res*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return res;
}
ll gcdll(ll a,ll b) {
if (b==0) return a;
return gcdll(b,a%b);
}
int gcd(int a,int b) {
if (b==0) return a;
return gcd(b,a%b);
}
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
const int N = (int)2e5+5;
const int M = (int)1e3+5;
const int Q = 301;
const int logN = 19;
int col[M];
vector<int> adj[M];
bool intersecting(pi a, pi b) {
return max(a.first, b.first) <= min(a.second, b.second);
}
bool dfs(int i, int c) {
if(col[i] != -1) {
return (col[i] == c);
}
col[i] = c;
for(auto it : adj[i]) {
if(!dfs(it, 1-c)) {
return false;
}
}
return true;
}
void solve() {
int n;
cin >> n;
REP(i,0,n-1) {
adj[i].clear();
col[i] = -1;
}
vector<pii> v(n);
REP(i,0,n-1) {
cin >> v[i].second.first >> v[i].second.second >> v[i].first;
REP(j,0,i-1) {
if(v[i].first == v[j].first && intersecting(v[i].second, v[j].second)) {
adj[i].pb(j);
adj[j].pb(i);
}
}
}
REP(i,0,n-1) {
if(col[i] == -1 && !dfs(i,0)) {
cout << "NO";
return;
}
}
cout << "YES";
}
int main() {
//freopen("output.txt","r",stdin);
//freopen("output.txt","w",stdout);
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T=1;
cin>>T;
REP(TC,1,T) {
//cout<<"Case #"<<TC<<": ";
solve();
cout<<"\n";
}
}
| [
"[email protected]"
] | |
f865f815184ddb497c746571f8c2829222c5b23f | 91ba0c0c42b3fcdbc2a7778e4a4684ab1942714b | /Cpp/SDK/AD_ThirdPerson_PlayerPirate_Female_Athletic_classes.h | c4384414d82d4cb99257fe5c542df808721819c4 | [] | no_license | zH4x/SoT-SDK-2.1.1 | 0f8c1ec3ad8821de82df3f75a0356642b581b8c6 | 35144dfc629aeddf96c1741e9e27e5113a2b1bb3 | refs/heads/main | 2023-05-12T09:03:32.050860 | 2021-06-05T01:54:15 | 2021-06-05T01:54:15 | 373,997,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 886 | h | #pragma once
// Name: SoT, Version: 2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass AD_ThirdPerson_PlayerPirate_Female_Athletic.AD_ThirdPerson_PlayerPirate_Female_Athletic_C
// 0x0000 (FullSize[0x0750] - InheritedSize[0x0750])
class UAD_ThirdPerson_PlayerPirate_Female_Athletic_C : public UAD_ThirdPerson_PlayerPirate_Female_Default_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass AD_ThirdPerson_PlayerPirate_Female_Athletic.AD_ThirdPerson_PlayerPirate_Female_Athletic_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
1f58cdd922bc74246ef57387a05c21b253abb62a | a1809f8abdb7d0d5bbf847b076df207400e7b08a | /Simpsons Hit&Run/game/libs/pure3d/toollib/src/tlPhotonMap.cpp | 81db8d20c193d4b2871d1597d1fccd4ab0d250a4 | [] | no_license | RolphWoggom/shr.tar | 556cca3ff89fff3ff46a77b32a16bebca85acabf | 147796d55e69f490fb001f8cbdb9bf7de9e556ad | refs/heads/master | 2023-07-03T19:15:13.649803 | 2021-08-27T22:24:13 | 2021-08-27T22:24:13 | 400,380,551 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,139 | cpp | /*===========================================================================
File:: tlPhotonMap.cpp
Copyright (c) 2001 Radical Entertainment, Inc. All rights reserved.
===========================================================================*/
#include "tlPhotonMap.hpp"
#include "tlPhotonMapChunk.hpp"
#include <assert.h>
#include <math.h>
#include <string.h>
#include "tlFile.hpp"
#include "tlLight.hpp"
#include "tlPoint.hpp"
#include "tlColour.hpp"
#include "tlVertex.hpp"
#include "tlMatrix.hpp"
#ifndef M_PI
const float M_PI = 3.1415926535f;
#endif
struct tlNearestPhotons
{
int max;
int found;
bool got_heap;
tlPoint pos;
float* dist2;
const tlPhoton** index;
};
// tlPhoton::tlPhoton() : numScatterings( 0 )
tlPhoton::tlPhoton() : pos( -777.0f, -777.0f, -777.0f ), plane( -777 ),
theta( 0xff ), phi( 0xff ), power( -777.0f, -777.0f, -777.0f ),
numScatterings( 0xff ), lightIndex( 0xff )
{
}
tlPoint
tlPhoton::Direction() const
{
// The photon mapping book does this with a lookup table.
// We may want to do that for speed
float t = float(theta) * (1.0f/256.0f) * M_PI;
float p = float(phi) * (1.0f/256.0f) * M_PI * 2.0f;
float x = sinf(t) * cosf(p);
float y = sinf(t) * sinf(p);
float z = cosf(t);
return tlPoint(x,y,z);
}
float
tlPhoton::Theta() const
{
// The photon mapping book does this with a lookup table.
// We may want to do that for speed
float thetaRadians = float(theta) * (1.0f/256.0f) * M_PI;
return thetaRadians;
}
float
tlPhoton::Phi() const
{
// The photon mapping book does this with a lookup table.
// We may want to do that for speed
float phiRadians = float(phi) * (1.0f/256.0f) * M_PI * 2.0f;
return phiRadians;
}
bool tlPhoton::operator==(const tlPhoton& p) const
{
return ( phi == p.phi &&
plane == p.plane &&
pos == p.pos &&
power == p.power &&
theta == p.theta &&
lightIndex == p.lightIndex );
}
void
tlPhoton::Read(tlFile* f)
{
pos = f->GetPoint();
// Dont' read in plane. plane = f->GetWord();
theta = f->GetChar();
phi = f->GetChar();
power.red = f->GetFloat();
power.green = f->GetFloat();
power.blue = f->GetFloat();
numScatterings = f->GetChar();
lightIndex = f->GetChar();
}
void
tlPhoton::Write(tlFile* f)
{
f->PutPoint( pos );
// Don't save plane. f->PutWord( plane );
// does putchar work for unsigned char?;
f->PutChar( theta );
f->PutChar( phi );
f->PutFloat( power.red );
f->PutFloat( power.green );
f->PutFloat( power.blue );
f->PutChar( numScatterings );
f->PutChar( lightIndex );
}
void
tlPhoton::Print( int index, int indent )
{
printf( "%*s%3d\n", indent, "", index );
printf( "%*s Position = %3.3f %3.3f %3.3f\n", indent, "", pos.x, pos.y, pos.z );
printf( "%*s Direction = %3.3f %3.3f\n", indent, "", Theta(), Phi() );
printf( "%*s Power = %3.3f %3.3f %3.3f\n", indent, "",
power.red, power.green, power.blue );
printf( "%*s numScat = %d\n", indent, "", (int)numScatterings );
printf( "%*s lightIdx = %d\n", indent, "", (int)lightIndex );
}
void
tlPhoton::PrintFormatted(int index, int indent)
{
}
void
tlPhoton::Init()
{
}
bool
tlPhoton::GetFieldValue(char* val, int len) const
{
char buf[256];
sprintf( buf, "Position( %3.3f, %3.3f, %3.3f ), "
"Direction( %3.3f, %3.3f ), "
"Power( %3.3f, %3.3f, %3.3f), "
"numScat( %u ), lightIdx( %u )",
pos.x, pos.y, pos.z,
Theta(), Phi(),
power.red, power.green, power.blue,
(int)numScatterings, (int)lightIndex );
::strncpy(val, buf, len);
return true;
}
bool
tlPhoton::GetFieldUpdatable()
{
return false;
}
bool
tlPhoton::SetFieldValue(const char*)
{
return false;
}
tlPhotonMapLights::tlPhotonMapLights() : m_next(0)
{
int i;
for( i = 0; i < 255; i++ )
{
m_name[i] = NULL;
m_pLight[i] = NULL;
m_scale[i] = 1.0f;
}
}
tlPhotonMapLights::~tlPhotonMapLights()
{
int i;
for( i = 0; i < m_next; i++ )
{
delete m_name[i];
}
}
//tlLight* tlPhotonMapLights::GetLight( int index ) const
//{
// if( index < 0 || index >= m_next )
// {
// return NULL;
// }
//
// return m_pLight[index];
//}
char* tlPhotonMapLights::GetLightName( int index ) const
{
if( index < 0 || index >= m_next )
{
return NULL;
}
return m_name[index];
}
int tlPhotonMapLights::GetLightIndex( const char *name ) const
{
int result = -1;
int i;
for( i = 0; i < m_next; i++ )
{
if( ::strcmp( name, m_name[i] ) )
{
result = i;
break;
}
}
return result;
}
int tlPhotonMapLights::GetLightIndex( const tlLight &light ) const
{
int result = -1;
int i;
for( i = 0; i < m_next; i++ )
{
if( m_pLight[i] == &light )
{
result = i;
break;
}
}
return result;
}
float tlPhotonMapLights::GetScale( int index ) const
{
if( index < 0 || index >= m_next )
{
return -777.0;
}
return m_scale[index];
}
int tlPhotonMapLights::GetMaxIndex() const
{
return m_next - 1;
}
//=============================================================================
// Add a new light to the list. return ( is the light added? ).
bool tlPhotonMapLights::AddLight( const tlLight &light )
{
bool result = false;
int index = m_next;
bool lightAlreadyAdded = GetLightIndex( light ) != -1;
if( !lightAlreadyAdded && index < 255 )
{
m_pLight[index] = &light; // Add the pointer to the light.
m_name[index] = ::strnew( light.GetName() ); // Add the name to the list.
m_next++;
result = true;
}
return result;
}
bool tlPhotonMapLights::SetScale( int index, float scale )
{
bool result = false;
if( index < 0 || index >= m_next )
{
m_scale[index] = scale;
result = true;
}
return result;
}
bool tlPhotonMapLights::operator==(const tlPhotonMapLights& lights) const
{
if( this->m_next != lights.m_next )
{
return false;
}
int i;
for( i = 0; i < m_next; i++ )
{
if( ::strcmp( this->m_name[i], lights.m_name[i] ) != 0 ||
this->m_scale[i] != lights.m_scale[i] ||
this->m_pLight[i] != lights.m_pLight[i] )
{
return false;
}
}
return true;
}
// This is only half of the initializatio process. After this is called, a call
// must also be made to Initialize() to initialize m_plight.
void tlPhotonMapLights::PreInitialize( int count, char** lightNames, float* scale )
{
m_next = count;
int i;
for( i = 0; i < count; i++ )
{
m_name[i] = ::strnew( lightNames[i] );
m_scale[i] = scale[i];
}
}
const char* tlPhotonMap::PHOTON_GEOMETRY_SHADER = "photonGeometryShader";
const int tlPhotonMap::CurrentPhotonMapVersion = 0x0100; // Version 1.00
tlPhotonMap::tlPhotonMap( tlDataChunk *ch ) :
half_stored_photons( 0 ),
prev_scale( 0 ),
m_MaxNumberSampled( 50 ),
m_MaxRadiusSampled( 0.1f ),
m_ignorePrimary( true )
{
box.Invalidate();
if (ch != NULL) LoadFromChunk(ch);
}
tlPhotonMap::~tlPhotonMap()
{
}
tlColour
tlPhotonMap::Irradiance(const tlPoint& pos,
const tlPoint& normal) const
{
if(m_photons.Count() <= 0) // Quick exit if no photons in the map.
{
return tlColour( 0.0f, 0.0f, 0.0f );
}
tlColour result( 0.0f, 0.0f, 0.0f );
// const int MIN_PHOTONS_REQUIRED = 8;
const int MIN_PHOTONS_REQUIRED = 3;
tlNearestPhotons np;
np.dist2 = new float[m_MaxNumberSampled+1];
np.index = new const tlPhoton*[m_MaxNumberSampled+1];
np.pos = pos;
np.max = m_MaxNumberSampled;
np.found = 0;
np.got_heap = false;
np.dist2[0] = m_MaxRadiusSampled * m_MaxRadiusSampled;
// locate the nearest photons
LocatePhotons(&np, this->IsPrimaryIgnored() );
if(np.found < MIN_PHOTONS_REQUIRED)
{
return result;
}
for(int i = 1; i <= np.found; i++)
{
const tlPhoton* p = np.index[i];
tlPoint pdir = p->Direction();
if( DotProd(pdir, normal) < 0.0f )
{
result = result + p->power;
}
}
const float density = (1.0f / M_PI) / (np.dist2[0]);
result = result * density;
delete[] np.dist2;
delete[] np.index;
return result;
}
// Generate a mesh of objects positioned at the photon locations.
tlPrimGroupMesh*
tlPhotonMap::CreateMesh(const float length) const
{
if( m_photons.Count() == 0 )
{
return NULL;
}
tlPrimGroupMesh *result = new tlPrimGroupMesh;
int i;
for(i = 0; i < m_photons.Count(); i++)
{
tlPrimGroup *marker = GenPhotonMarker( length, m_photons[i].power );
tlMatrix matrix;
matrix.RotateY(M_PI - m_photons[i].Theta());
matrix.RotateZ(M_PI + m_photons[i].Phi());
matrix.Translate(m_photons[i].pos);
marker->Transform(matrix);
marker->SetShader( PHOTON_GEOMETRY_SHADER );
result->AddPrimGroup(marker);
}
return result;
}
void
tlPhotonMap::LocatePhotons(tlNearestPhotons* const np, bool ignorePrimary,
const int index) const
{
assert( index >= 0 && index < m_photons.Count() );
const tlPhoton* p = &m_photons[index];
float dist1;
if(index < half_stored_photons)
{
dist1 = np->pos[(int)(p->plane)] - p->pos[p->plane];
// if dist1 is positive, searche the right plane
if(dist1 > 0.0f)
{
LocatePhotons( np, ignorePrimary, 2*index + 2 );
if( (dist1*dist1) < np->dist2[0])
{
LocatePhotons( np, ignorePrimary, 2*index + 1);
}
}
else
{
LocatePhotons( np, ignorePrimary, 2*index + 1);
if( (dist1*dist1) < np->dist2[0])
{
LocatePhotons( np, ignorePrimary, 2*index + 2);
}
}
}
// compute the sqaured distance between current photon and np->pos
float dist2 = LengthSquared(p->pos - np->pos);
if(dist2 < np->dist2[0] && !( ignorePrimary && p->numScatterings == 0 ) )
{
// we found a photon
if(np->found < np->max)
{
np->found++;
np->dist2[np->found] = dist2;
np->index[np->found] = p;
}
else
{
// use a heap to keep only closest photons
int j, parent;
if(np->got_heap == false)
{
// build the heap
float dst2;
const tlPhoton* phot;
int half_found = np->found / 2;
for(int k = half_found; k >= 1; k--)
{
parent = k;
phot = np->index[k];
dst2 = np->dist2[k];
while ( parent <= half_found)
{
j = parent * 2;
if ( (j < np->found) && (np->dist2[j] < np->dist2[j+1]) )
{
j++;
}
if ( dst2 >= np->dist2[j] )
{
break;
}
np->dist2[parent] = np->dist2[j];
np->index[parent] = np->index[j];
parent = j;
}
np->dist2[parent] = dst2;
np->index[parent] = phot;
}
np->got_heap = true;
}
// insert new photon into heap
parent = 1;
j = 2;
while ( j <= np->found )
{
if( ( j < np->found ) && (np->dist2[j] < np->dist2[j+1]) )
{
j++;
}
if ( dist2 >= np->dist2[j] )
{
break;
}
np->dist2[parent] = np->dist2[j];
np->index[parent] = np->index[j];
parent = j;
j += j;
}
np->dist2[parent] = dist2;
np->index[parent] = p;
np->dist2[0] = np->dist2[1];
}
}
}
void
tlPhotonMap::Store(const tlColour& col,
const tlPoint& pos,
const tlPoint& dir,
const unsigned char numScatterings,
const tlLight& light )
{
int count = m_photons.Count();
if( count >= m_photons.Nalloc() )
{
Resize( count * 2 );
}
m_photons.SetCount(count + 1);
tlPhoton* node = & m_photons[count];
node->pos = pos;
node->power = col;
node->numScatterings = numScatterings;
node->lightIndex = m_lights.GetLightIndex( light );
box.AddPoint(pos);
int theta = int( acos(dir.z) * (256.0f / M_PI) );
if(theta > 255)
{
node->theta = 255;
}
else
{
node->theta = (unsigned char) theta;
}
int phi = int( atan2(dir.y, dir.x) * (256.0f / (2.0f*M_PI)) );
if(phi > 255)
{
node->phi = 255;
}
else if (phi < 0)
{
node->phi = (unsigned char) (phi + 256);
}
else
{
node->phi = (unsigned char) phi;
}
}
void
tlPhotonMap::Store( const tlPhoton &photon )
{
int count = m_photons.Count();
if( count >= m_photons.Nalloc() )
{
Resize( count * 2 );
}
m_photons.SetCount(count + 1);
tlPhoton* node = & m_photons[count];
*node = photon;
box.AddPoint( photon.pos );
}
int
tlPhotonMap::GetPhotonCount() const
{
return m_photons.Count();
}
bool tlPhotonMap::SetMaxNumberSampled( int max )
{
bool result = false;
if( max > 0 )
{
m_MaxNumberSampled = max;
result = true;
}
return result;
}
bool tlPhotonMap::SetMaxRadiusSampled( float radius )
{
bool result = false;
if( radius > 0.0f )
{
m_MaxRadiusSampled = radius;
result = true;
}
return result;
}
void tlPhotonMap::IgnorePrimary( bool ignorePrimary )
{
m_ignorePrimary = ignorePrimary;
}
bool tlPhotonMap::IsPrimaryIgnored( ) const
{
return m_ignorePrimary;
}
bool tlPhotonMap::AddLight( const tlLight &light )
{
return m_lights.AddLight( light );
}
// Change the size of allocation for photon storage, not the number of
// stored photons. Return success of allocation.
bool tlPhotonMap::Resize( int size )
{
bool isSuccessful = false;
int count = m_photons.Count();
if( size > count )
{
isSuccessful = m_photons.Resize( size ) ? 1 : 0;
}
return isSuccessful;
}
void
tlPhotonMap::ScalePhotonPower( const float scale )
{
//for(int i = prev_scale; i < m_photons.Count(); i++)
for(int i = 0; i < m_photons.Count(); i++)
{
m_photons[i].power = m_photons[i].power * scale;
}
// prev_scale = m_photons.Count();
}
void
tlPhotonMap::Balance()
{
if(m_photons.Count() > 0)
{
// allocate two arrays for the balancing procedure
tlPhoton ** pa1 = new tlPhoton*[m_photons.Count()];
tlPhoton ** pa2 = new tlPhoton*[m_photons.Count()];
int i;
for(i = 0; i < m_photons.Count(); i++)
{
pa2[i] = &m_photons[i];
}
BalanceSegment( pa1, pa2, 0, 0, m_photons.Count() - 1);
delete[] pa2;
// make a heap from the balanced kd tree
int d, j=0, k=0;
tlPhoton phot = m_photons[j];
for(i = 0; i <m_photons.Count(); i++)
{
d = pa1[j] - m_photons.Addr(0);
pa1[j] = NULL;
if(d != k)
{
m_photons[j] = m_photons[d];
}
else
{
m_photons[j] = phot;
if(i < m_photons.Count()-1)
{
for( ; k <m_photons.Count(); k++)
{
if(pa1[k] != NULL)
{
break;
}
}
phot = m_photons[k];
j = k;
}
continue;
}
j = d;
}
delete[] pa1;
}
half_stored_photons = m_photons.Count()/2 -1;
}
#define swap(ph, a, b) { tlPhoton* ph2 = ph[a]; ph[a] = ph[b]; ph[b] = ph2; }
void
tlPhotonMap::MedianSplit(tlPhoton** p,
const int start,
const int end,
const int median,
const int axis)
{
int left = start;
int right = end;
while(right > left)
{
const float v = p[right]->pos[axis];
int i = left-1;
int j = right;
while(1)
{
while( p[++i]->pos[axis] < v )
{
// empty
}
while( (p[--j]->pos[axis] > v) && (j > left))
{
// empty
}
if ( i >= j)
{
break;
}
swap(p,i,j);
}
swap(p,i, right);
if(i >= median )
{
right = i - 1;
}
if(i <= median )
{
left = i + 1;
}
}
}
void
tlPhotonMap:: BalanceSegment(tlPhoton **pbal,
tlPhoton **porg,
const int index,
const int start,
const int end)
{
// compute new median
int median = 1;
while( (median * 4) <= (end - start + 1) )
{
median += median;
}
if( (median * 3) > (end - start + 1) )
{
median = end - median + 1;
}
else
{
median += median;
median += start - 1;
}
// find axis to split along
int axis = 2;
if( ((box.high.x - box.low.x) > (box.high.y - box.low.y)) &&
((box.high.x - box.low.x) > (box.high.z - box.low.z)) )
{
axis = 0;
}
else if( (box.high.y - box.low.y) > (box.high.z - box.low.z) )
{
axis = 1;
}
// partition photon block around the median
MedianSplit( porg, start, end, median, axis );
pbal[ index ] = porg[ median ];
pbal[ index ]->plane = axis;
// recursivly balance the left and right blocks
if ( median > start )
{
if( start < median - 1)
{
const float tmp = box.high[axis];
box.high[axis] = pbal[index]->pos[axis];
BalanceSegment( pbal, porg, 2*index + 1, start, median-1);
box.high[axis] = tmp;
} else {
pbal[ 2 * index + 1 ] = porg[start];
}
}
if( median < end)
{
if( median + 1 < end )
{
const float tmp = box.low[axis];
box.low[axis] = pbal[index]->pos[axis];
BalanceSegment( pbal, porg, 2 * index + 2, median+1, end);
box.low[axis] = tmp;
} else {
pbal[ 2* index + 2] = porg[end];
}
}
}
// Build a coloured diamond with a specified edge length.
tlPrimGroup*
tlPhotonMap::GenPhotonMarker( const float length, const tlColour &power ) const
{
tlColour scaledPower( power );
float maxValue = power[power.MaxChannel()];
if( maxValue != 0.0f )
{
scaledPower = power * ( 1.0f / maxValue );
}
tlColour fullColour( scaledPower );
tlColour halfColour( scaledPower * 0.5f );
tlColour black( 0.0f, 0.0f, 0.0f );
float dist = length * (float)sqrt(2.0) / 2.0f;
tlPoint coord[6] = { tlPoint( 0.0f, 0.0f, dist ),
tlPoint( dist, 0.0f, 0.0f ),
tlPoint( 0.0f, -dist, 0.0f ),
tlPoint( -dist, 0.0f, 0.0f ),
tlPoint( 0.0f, dist, 0.0f ),
tlPoint( 0.0f, 0.0f, -dist ) };
tlColour colour[6] = { fullColour,
halfColour,
halfColour,
halfColour,
halfColour,
black };
int vertIndex[24] = { 0, 2, 1,
0, 3, 2,
0, 4, 3,
0, 1, 4,
5, 3, 4,
5, 2, 3,
5, 1, 2,
5, 4, 1 };
int i;
tlVertex *vert = NULL;
tlPoint pt;
tlUV uv;
tlTable<tlVertex *> vertList;
vertList.Resize( 24 );
for ( i = 0; i < 24; i++ )
{
vert = new tlVertex( coord[vertIndex[i]], pt, colour[vertIndex[i]], uv );
// Bug #236: Added by Bryan Ewert on 22 Apr 2002
vert->SetVertexFormat( PDDI_V_CT );
vertList.Append(vert);
}
tlPrimGroup *prim = new tlPrimGroup( vertList );
tlMatrix matrix;
matrix.RotateZ(M_PI/4.0f);
prim->Transform(matrix);
prim->SetVertexType( PDDI_V_CT );
return prim;
}
void tlPhotonMap::LoadFromChunk(tlDataChunk *ch)
{
tlPhotonMapChunk *photonMapChunk = dynamic_cast<tlPhotonMapChunk *>(ch);
if (photonMapChunk == NULL)
{
return;
}
assert(photonMapChunk->GetVersion() == (unsigned long)CurrentPhotonMapVersion);
SetName(photonMapChunk->GetName());
//----- Copy the light index (names and scales). -----------------
int numLights = m_lights.GetMaxIndex();
char **names = photonMapChunk->GetLights();
float *lightScales = photonMapChunk->GetLightScales();
m_lights.PreInitialize( numLights, names, lightScales );
// Allocate memory for photons
Resize( photonMapChunk->GetNumPhotons() );
//------ Copy all the photons. -----------------------------------
const tlPhoton *photons = photonMapChunk->GetPhotons();
int subChunkCount = photonMapChunk->SubChunkCount();
int i(0);
for( i = 0; i < (int)(photonMapChunk->GetNumPhotons()); i++ )
{
// Add each photon to the map.
Store( photons[i] );
}
Balance();
}
void tlPhotonMap::LoadFromChunk16(tlDataChunk* ch)
{
assert(false); // Not implemented.
}
tlDataChunk* tlPhotonMap::Chunk()
{
tlPhotonMapChunk *photonMapChunk = new tlPhotonMapChunk;
photonMapChunk->SetName(GetName());
photonMapChunk->SetVersion(CurrentPhotonMapVersion);
int i;
//----- Copy the light index (names and scales). -----------------
int numLights = m_lights.GetMaxIndex() + 1;
char **names = new char*[numLights];
float *lightScales = new float[numLights];
for( i = 0; i < numLights; i++ )
{
names[i] = ::strnew( m_lights.GetLightName( i ) );
lightScales[i] = m_lights.GetScale( i );
}
photonMapChunk->SetNumLights( numLights );
photonMapChunk->SetLights( names, numLights );
photonMapChunk->SetLightScales( lightScales, numLights );
//------ Copy all the photons. -----------------------------------
tlPhoton *photons = new tlPhoton[m_photons.Count()];
for( i = 0; i < m_photons.Count(); i++ )
{
photons[i] = m_photons[i];
}
photonMapChunk->SetPhotons( photons, m_photons.Count() );
photonMapChunk->SetNumPhotons( m_photons.Count() );
return photonMapChunk;
}
tlDataChunk* tlPhotonMap::Chunk16()
{
assert(false); // Not implemented.
tlDataChunk *dummy = NULL;
return dummy;
}
| [
"[email protected]"
] | |
39a91a47ee495b1a3dc13abd666b9b09d21afb64 | 1d915e33566f5c0044f9e2d666ddbe9d70263aba | /graphic/assighment5/Sphere.h | b084eee4920130102e40c13b0cce47cad8474cc5 | [] | no_license | alexunder/X-toys | b4a52600396a4a3d36fb301e27ef4846fd04d9d6 | b652db4b308cbf0614a75f044b8da261f316917b | refs/heads/master | 2021-08-07T07:42:10.514018 | 2021-02-03T08:13:50 | 2021-02-03T08:13:50 | 1,125,091 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 584 | h | /*
* The Sphere class derived from Object3D.
* Implemented by Mohism Research
*/
#ifndef __H_SPHERE
#define __H_SPHERE
#include "Object3D.h"
#include "vectors.h"
#include "material.h"
class Sphere : public Object3D
{
public:
Sphere(const Vec3f &point, float radius, Material *m);
bool intersect(const Ray &r, Hit &h, float tmin);
void paint(void);
void insertIntoGrid(Grid *g, Matrix *m);
static void setTesselationSize(int theta, int phi);
private:
float mRadius;
Vec3f mCenterPoint;
static int mThetaSteps;
static int mPhiSteps;
};
#endif
| [
"[email protected]"
] | |
cdbd17e20af2589f7be3fc5259019ea044f55f10 | 0464ef72e5f9cd84a0563bc250e9f1a42b78ee45 | /cocos2d/external/bullet/BulletCollision/CollisionDispatch/btHashedSimplePairCache.h | e041a4a208cc7fe43fd7080ad705e84f76c3ecb6 | [
"MIT"
] | permissive | lcyzgdy/KeepDistance | 5389bfa35b8bd8b48e3374c17afc1ead56fe2a7f | 1f93a7f553846c0176a7fae10acadf962b0b4c1b | refs/heads/master | 2021-01-01T06:44:17.494408 | 2017-07-17T17:20:54 | 2017-07-17T17:20:54 | 97,500,785 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,871 | h | /*
BulletSprite Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/BulletSprite/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_HASHED_SIMPLE_PAIR_CACHE_H
#define BT_HASHED_SIMPLE_PAIR_CACHE_H
#include "bullet/LinearMath/btAlignedObjectArray.h"
const int BT_SIMPLE_NULL_PAIR=0xffffffff;
struct btSimplePair
{
btSimplePair(int indexA,int indexB)
:m_indexA(indexA),
m_indexB(indexB),
m_userPointer(0)
{
}
int m_indexA;
int m_indexB;
union
{
void* m_userPointer;
int m_userValue;
};
};
typedef btAlignedObjectArray<btSimplePair> btSimplePairArray;
extern int gOverlappingSimplePairs;
extern int gRemoveSimplePairs;
extern int gAddedSimplePairs;
extern int gFindSimplePairs;
class btHashedSimplePairCache
{
btSimplePairArray m_overlappingPairArray;
bool m_blockedForChanges;
protected:
btAlignedObjectArray<int> m_hashTable;
btAlignedObjectArray<int> m_next;
public:
btHashedSimplePairCache();
virtual ~btHashedSimplePairCache();
void removeAllPairs();
virtual void* removeOverlappingPair(int indexA,int indexB);
// Add a pair and return the new pair. If the pair already exists,
// no new pair is created and the old one is returned.
virtual btSimplePair* addOverlappingPair(int indexA,int indexB)
{
gAddedSimplePairs++;
return internalAddPair(indexA,indexB);
}
virtual btSimplePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btSimplePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btSimplePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btSimplePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
btSimplePair* findPair(int indexA,int indexB);
int GetCount() const { return m_overlappingPairArray.size(); }
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
private:
btSimplePair* internalAddPair(int indexA, int indexB);
void growTables();
SIMD_FORCE_INLINE bool equalsPair(const btSimplePair& pair, int indexA, int indexB)
{
return pair.m_indexA == indexA && pair.m_indexB == indexB;
}
SIMD_FORCE_INLINE unsigned int getHash(unsigned int indexA, unsigned int indexB)
{
int key = static_cast<int>(((unsigned int)indexA) | (((unsigned int)indexB) <<16));
// Thomas Wang's hash
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return static_cast<unsigned int>(key);
}
SIMD_FORCE_INLINE btSimplePair* internalFindPair(int proxyIdA , int proxyIdB, int hash)
{
int index = m_hashTable[hash];
while( index != BT_SIMPLE_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyIdA, proxyIdB) == false)
{
index = m_next[index];
}
if ( index == BT_SIMPLE_NULL_PAIR )
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
};
#endif //BT_HASHED_SIMPLE_PAIR_CACHE_H
| [
"[email protected]"
] | |
13f97d2b79da5a45bb7df704a683fada27c5dfbe | ad822f849322c5dcad78d609f28259031a96c98e | /SDK/ModernPOI_SolarFarm_01_Small_Collection_functions.cpp | 06ebb1039bccb99c2feab520c28af15b5e6df85b | [] | no_license | zH4x-SDK/zAstroneer-SDK | 1cdc9c51b60be619202c0258a0dd66bf96898ac4 | 35047f506eaef251a161792fcd2ddd24fe446050 | refs/heads/main | 2023-07-24T08:20:55.346698 | 2021-08-27T13:33:33 | 2021-08-27T13:33:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | cpp |
#include "../SDK.h"
// Name: Astroneer-SDK, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function ModernPOI_SolarFarm_01_Small_Collection.ModernPOI_SolarFarm_01_Small_Collection_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void AModernPOI_SolarFarm_01_Small_Collection_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function ModernPOI_SolarFarm_01_Small_Collection.ModernPOI_SolarFarm_01_Small_Collection_C.UserConstructionScript");
AModernPOI_SolarFarm_01_Small_Collection_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
cf9866da236379306f0bfda06620cf5bde19da72 | a63bc208c747ed457989c8be1c2cc368920e595a | /src/pMove/sonar.cpp | 09a6d98d934d8d09984410a403c46b76ac714208 | [] | no_license | msis/moos-ivp-ENSTABretagne | a14b91289549eb967c69c66f5e05c3968e932e01 | 1efd1ecc2ed2368a7a273d8368329e62564d4fe8 | refs/heads/master | 2021-01-25T05:35:41.880199 | 2014-09-16T08:21:37 | 2014-09-16T08:21:37 | 10,523,552 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 405 | cpp | #include "sonar.h"
#include "localisation.h"
void Sonar :: getIndMax(unsigned int *raw, int size, int *ind){
unsigned int max = 0;
for(int i = 0; i < size; i++){
if(max < raw[i]){
max = raw[i];
*ind = i;
}
}
}
void Sonar :: localisation(float *rho, float *tt, int size, PARAM *param, POS *pos, float cap, int mode){
localisation( rho, tt, size, param, pos, cap, mode);
} | [
"[email protected]"
] | |
bfab8bd47f6dd5052b6a96c616260ddd7522d0f0 | 63d888492eb5760997d28f7e464620ab560589cc | /OMAC/Src/Native/Level_0J/OMACTest.h | 636cedba6c0d770d6447422782e29f8ce2102b8e | [] | no_license | Samraksh/TestSuite | ef4ea58b7bf844d6263d52ad2a4fe2d91852bf48 | 5a2ad0157ff878e9460fc85d222191ce7dcd595f | refs/heads/master | 2022-10-28T22:51:33.354774 | 2020-03-10T18:29:06 | 2020-03-10T18:29:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | h | /*
* OMACTest.h
*/
#ifndef OMACTEST_H_
#define OMACTEST_H_
#include <tinyhal.h>
#include <Samraksh/Mac_decl.h>
#include <Samraksh/MAC/OMAC/OMAC.h>
#include <Samraksh/VirtualTimer.h>
#include <Samraksh/Message.h>
typedef struct {
UINT16 MSGID;
UINT8 data[5];
}Payload_t;
class OMACTest{
public:
UINT8 MyAppID;
Payload_t msg;
MacEventHandler myEventHandler;
MacConfig Config;
UINT8 MacId;
BOOL LocalClkPINState;
BOOL NeighborClkPINState;
UINT64 LocalClockMonitorFrameNum;
UINT64 NeighborClockMonitorFrameNum;
UINT16 SendCount;
UINT16 RcvCount;
BOOL Initialize();
BOOL StartTest();
void Receive(void* msg, UINT16 size);
BOOL Send();
void SendAck(void *msg, UINT16 size, NetOpStatus status);
BOOL ScheduleNextNeighborCLK();
BOOL ScheduleNextLocalCLK();
};
//extern OMACTest g_OMACTest;
void OMACTest_Initialize();
#endif /* OMACTEST_H_ */
| [
"[email protected]"
] | |
9ad464b74ddb6a2f2e7c16089a87c9ae4dfd8747 | 0c135ed68e97041099f46b3e7263acf7285c872b | /src/ImpGears/SceneGraph/Node.cpp | 3e28f810dc318f2da6519b36f25840630f996dc6 | [
"MIT"
] | permissive | Lut1n/ImpGears | b45f3389c3100bde19e207ca64d4af14d89775bd | d6fd13715780be41c91f24c9865bb0c2500c4efb | refs/heads/master | 2021-07-09T00:45:13.666944 | 2020-08-02T19:38:38 | 2020-08-02T19:38:38 | 29,250,437 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,101 | cpp | #include <ImpGears/SceneGraph/Node.h>
#include <ImpGears/SceneGraph/Visitor.h>
IMPGEARS_BEGIN
//--------------------------------------------------------------
Node::Node()
: _state(nullptr)
, _position(0.0)
, _rotation(0.0)
, _scale(1.0)
{
_transformChanged = true;
}
//--------------------------------------------------------------
Node::~Node()
{
}
//--------------------------------------------------------------
void Node::addNode(const Node::Ptr& node)
{
_children.push_back( node );
}
//--------------------------------------------------------------
void Node::remNode(const Node::Ptr& node)
{
_children.remove( node );
}
//--------------------------------------------------------------
void Node::clearNode()
{
_children.clear();
}
//--------------------------------------------------------------
void Node::accept( Visitor& visitor )
{
for(auto node : _children)
{
node->update();
node->computeMatrices();
visitor.push(node);
visitor.apply(node);
node->accept(visitor);
visitor.pop();
}
}
//--------------------------------------------------------------
void Node::computeMatrices()
{
if(_transformChanged)
{
_modelMatrix = _scaleMat * _rotationMat * _positionMat;
_transformChanged = false;
}
}
void Node::setPosition(const Vec3& position)
{
_position=position;
_positionMat = Matrix4::translation(_position.x(), _position.y(), _position.z());
_transformChanged = true;
}
void Node::setRotation(const Vec3& rotation)
{
_rotation=rotation;
_rotationMat = Matrix4::rotationX(_rotation.x())
* Matrix4::rotationY(_rotation.y())
* Matrix4::rotationZ(_rotation.z());
_transformChanged = true;
}
void Node::setScale(const Vec3& scale)
{
_scale=scale;
_scaleMat = Matrix4::scale(_scale.x(), _scale.y(), _scale.z());
_transformChanged = true;
}
State::Ptr Node::getState(bool createIfNotExist)
{
if(createIfNotExist && _state==nullptr)
_state = State::create();
return _state;
}
IMPGEARS_END
| [
"[email protected]"
] | |
22475d895b0b419767ade83e349e1dc6917efee5 | 641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2 | /components/sync/engine_impl/apply_control_data_updates_unittest.cc | b72507ff6ae936cbae94d4d203e2694fea47592f | [
"BSD-3-Clause"
] | permissive | massnetwork/mass-browser | 7de0dfc541cbac00ffa7308541394bac1e945b76 | 67526da9358734698c067b7775be491423884339 | refs/heads/master | 2022-12-07T09:01:31.027715 | 2017-01-19T14:29:18 | 2017-01-19T14:29:18 | 73,799,690 | 4 | 4 | BSD-3-Clause | 2022-11-26T11:53:23 | 2016-11-15T09:49:29 | null | UTF-8 | C++ | false | false | 41,363 | cc | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/engine_impl/apply_control_data_updates.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <string>
#include "base/format_macros.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/stringprintf.h"
#include "components/sync/base/cryptographer.h"
#include "components/sync/engine_impl/syncer.h"
#include "components/sync/engine_impl/syncer_util.h"
#include "components/sync/engine_impl/test_entry_factory.h"
#include "components/sync/protocol/nigori_specifics.pb.h"
#include "components/sync/syncable/directory.h"
#include "components/sync/syncable/mutable_entry.h"
#include "components/sync/syncable/nigori_util.h"
#include "components/sync/syncable/syncable_read_transaction.h"
#include "components/sync/syncable/syncable_util.h"
#include "components/sync/syncable/syncable_write_transaction.h"
#include "components/sync/test/engine/fake_model_worker.h"
#include "components/sync/test/engine/test_directory_setter_upper.h"
#include "components/sync/test/engine/test_id_factory.h"
#include "components/sync/test/fake_sync_encryption_handler.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer {
using syncable::MutableEntry;
using syncable::UNITTEST;
using syncable::Id;
class ApplyControlDataUpdatesTest : public ::testing::Test {
public:
protected:
ApplyControlDataUpdatesTest() {}
~ApplyControlDataUpdatesTest() override {}
void SetUp() override {
dir_maker_.SetUp();
entry_factory_ = base::MakeUnique<TestEntryFactory>(directory());
}
void TearDown() override { dir_maker_.TearDown(); }
syncable::Directory* directory() { return dir_maker_.directory(); }
TestIdFactory id_factory_;
std::unique_ptr<TestEntryFactory> entry_factory_;
private:
base::MessageLoop loop_; // Needed for directory init.
TestDirectorySetterUpper dir_maker_;
DISALLOW_COPY_AND_ASSIGN(ApplyControlDataUpdatesTest);
};
// Verify that applying a nigori node sets initial sync ended properly,
// updates the set of encrypted types, and updates the cryptographer.
TEST_F(ApplyControlDataUpdatesTest, NigoriUpdate) {
// Storing the cryptographer separately is bad, but for this test we
// know it's safe.
Cryptographer* cryptographer;
ModelTypeSet encrypted_types;
encrypted_types.PutAll(SyncEncryptionHandler::SensitiveTypes());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
// Nigori node updates should update the Cryptographer.
Cryptographer other_cryptographer(cryptographer->encryptor());
KeyParams params = {"localhost", "dummy", "foobar"};
other_cryptographer.AddKey(params);
sync_pb::EntitySpecifics specifics;
sync_pb::NigoriSpecifics* nigori = specifics.mutable_nigori();
other_cryptographer.GetKeys(nigori->mutable_encryption_keybag());
nigori->set_encrypt_everything(true);
entry_factory_->CreateUnappliedNewItem(ModelTypeToRootTag(NIGORI), specifics,
true);
EXPECT_FALSE(cryptographer->has_pending_keys());
ApplyControlDataUpdates(directory());
EXPECT_FALSE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->has_pending_keys());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
}
// Create some local unsynced and unencrypted data. Apply a nigori update that
// turns on encryption for the unsynced data. Ensure we properly encrypt the
// data as part of the nigori update. Apply another nigori update with no
// changes. Ensure we ignore already-encrypted unsynced data and that nothing
// breaks.
TEST_F(ApplyControlDataUpdatesTest, EncryptUnsyncedChanges) {
// Storing the cryptographer separately is bad, but for this test we
// know it's safe.
Cryptographer* cryptographer;
ModelTypeSet encrypted_types;
encrypted_types.PutAll(SyncEncryptionHandler::SensitiveTypes());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
// With default encrypted_types, this should be true.
EXPECT_TRUE(VerifyUnsyncedChangesAreEncrypted(&trans, encrypted_types));
Syncer::UnsyncedMetaHandles handles;
GetUnsyncedEntries(&trans, &handles);
EXPECT_TRUE(handles.empty());
}
// Create unsynced bookmarks without encryption.
// First item is a folder
Id folder_id = id_factory_.NewLocalId();
entry_factory_->CreateUnsyncedItem(folder_id, id_factory_.root(), "folder",
true, BOOKMARKS, nullptr);
// Next five items are children of the folder
size_t i;
size_t batch_s = 5;
for (i = 0; i < batch_s; ++i) {
entry_factory_->CreateUnsyncedItem(id_factory_.NewLocalId(), folder_id,
base::StringPrintf("Item %" PRIuS "", i),
false, BOOKMARKS, nullptr);
}
// Next five items are children of the root.
for (; i < 2 * batch_s; ++i) {
entry_factory_->CreateUnsyncedItem(
id_factory_.NewLocalId(), id_factory_.root(),
base::StringPrintf("Item %" PRIuS "", i), false, BOOKMARKS, nullptr);
}
KeyParams params = {"localhost", "dummy", "foobar"};
cryptographer->AddKey(params);
sync_pb::EntitySpecifics specifics;
sync_pb::NigoriSpecifics* nigori = specifics.mutable_nigori();
cryptographer->GetKeys(nigori->mutable_encryption_keybag());
nigori->set_encrypt_everything(true);
encrypted_types.Put(BOOKMARKS);
entry_factory_->CreateUnappliedNewItem(ModelTypeToRootTag(NIGORI), specifics,
true);
EXPECT_FALSE(cryptographer->has_pending_keys());
EXPECT_TRUE(cryptographer->is_ready());
{
// Ensure we have unsynced nodes that aren't properly encrypted.
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_FALSE(VerifyUnsyncedChangesAreEncrypted(&trans, encrypted_types));
Syncer::UnsyncedMetaHandles handles;
GetUnsyncedEntries(&trans, &handles);
EXPECT_EQ(2 * batch_s + 1, handles.size());
}
ApplyControlDataUpdates(directory());
EXPECT_FALSE(cryptographer->has_pending_keys());
EXPECT_TRUE(cryptographer->is_ready());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
// If ProcessUnsyncedChangesForEncryption worked, all our unsynced changes
// should be encrypted now.
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
EXPECT_TRUE(VerifyUnsyncedChangesAreEncrypted(&trans, encrypted_types));
Syncer::UnsyncedMetaHandles handles;
GetUnsyncedEntries(&trans, &handles);
EXPECT_EQ(2 * batch_s + 1, handles.size());
}
// Simulate another nigori update that doesn't change anything.
{
syncable::WriteTransaction trans(FROM_HERE, UNITTEST, directory());
MutableEntry entry(&trans, syncable::GET_TYPE_ROOT, NIGORI);
ASSERT_TRUE(entry.good());
entry.PutServerVersion(entry_factory_->GetNextRevision());
entry.PutIsUnappliedUpdate(true);
}
ApplyControlDataUpdates(directory());
EXPECT_FALSE(cryptographer->has_pending_keys());
EXPECT_TRUE(cryptographer->is_ready());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
// All our changes should still be encrypted.
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
EXPECT_TRUE(VerifyUnsyncedChangesAreEncrypted(&trans, encrypted_types));
Syncer::UnsyncedMetaHandles handles;
GetUnsyncedEntries(&trans, &handles);
EXPECT_EQ(2 * batch_s + 1, handles.size());
}
}
// Create some local unsynced and unencrypted changes. Receive a new nigori
// node enabling their encryption but also introducing pending keys. Ensure
// we apply the update properly without encrypting the unsynced changes or
// breaking.
TEST_F(ApplyControlDataUpdatesTest, CannotEncryptUnsyncedChanges) {
// Storing the cryptographer separately is bad, but for this test we
// know it's safe.
Cryptographer* cryptographer;
ModelTypeSet encrypted_types;
encrypted_types.PutAll(SyncEncryptionHandler::SensitiveTypes());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
// With default encrypted_types, this should be true.
EXPECT_TRUE(VerifyUnsyncedChangesAreEncrypted(&trans, encrypted_types));
Syncer::UnsyncedMetaHandles handles;
GetUnsyncedEntries(&trans, &handles);
EXPECT_TRUE(handles.empty());
}
// Create unsynced bookmarks without encryption.
// First item is a folder
Id folder_id = id_factory_.NewLocalId();
entry_factory_->CreateUnsyncedItem(folder_id, id_factory_.root(), "folder",
true, BOOKMARKS, nullptr);
// Next five items are children of the folder
size_t i;
size_t batch_s = 5;
for (i = 0; i < batch_s; ++i) {
entry_factory_->CreateUnsyncedItem(id_factory_.NewLocalId(), folder_id,
base::StringPrintf("Item %" PRIuS "", i),
false, BOOKMARKS, nullptr);
}
// Next five items are children of the root.
for (; i < 2 * batch_s; ++i) {
entry_factory_->CreateUnsyncedItem(
id_factory_.NewLocalId(), id_factory_.root(),
base::StringPrintf("Item %" PRIuS "", i), false, BOOKMARKS, nullptr);
}
// We encrypt with new keys, triggering the local cryptographer to be unready
// and unable to decrypt data (once updated).
Cryptographer other_cryptographer(cryptographer->encryptor());
KeyParams params = {"localhost", "dummy", "foobar"};
other_cryptographer.AddKey(params);
sync_pb::EntitySpecifics specifics;
sync_pb::NigoriSpecifics* nigori = specifics.mutable_nigori();
other_cryptographer.GetKeys(nigori->mutable_encryption_keybag());
nigori->set_encrypt_everything(true);
encrypted_types.Put(BOOKMARKS);
entry_factory_->CreateUnappliedNewItem(ModelTypeToRootTag(NIGORI), specifics,
true);
EXPECT_FALSE(cryptographer->has_pending_keys());
{
// Ensure we have unsynced nodes that aren't properly encrypted.
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_FALSE(VerifyUnsyncedChangesAreEncrypted(&trans, encrypted_types));
Syncer::UnsyncedMetaHandles handles;
GetUnsyncedEntries(&trans, &handles);
EXPECT_EQ(2 * batch_s + 1, handles.size());
}
ApplyControlDataUpdates(directory());
EXPECT_FALSE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->has_pending_keys());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
// Since we have pending keys, we would have failed to encrypt, but the
// cryptographer should be updated.
EXPECT_FALSE(VerifyUnsyncedChangesAreEncrypted(&trans, encrypted_types));
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
EXPECT_FALSE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->has_pending_keys());
Syncer::UnsyncedMetaHandles handles;
GetUnsyncedEntries(&trans, &handles);
EXPECT_EQ(2 * batch_s + 1, handles.size());
}
}
// Verify we handle a nigori node conflict by merging encryption keys and
// types, but preserve the custom passphrase state of the server.
// Initial sync ended should be set.
TEST_F(ApplyControlDataUpdatesTest,
NigoriConflictPendingKeysServerEncryptEverythingCustom) {
Cryptographer* cryptographer;
ModelTypeSet encrypted_types(SyncEncryptionHandler::SensitiveTypes());
KeyParams other_params = {"localhost", "dummy", "foobar"};
KeyParams local_params = {"localhost", "dummy", "local"};
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(directory()->GetNigoriHandler()->GetEncryptedTypes(&trans),
encrypted_types);
}
// Set up a temporary cryptographer to generate new keys with.
Cryptographer other_cryptographer(cryptographer->encryptor());
other_cryptographer.AddKey(other_params);
// Create server specifics with pending keys, new encrypted types,
// and a custom passphrase (unmigrated).
sync_pb::EntitySpecifics server_specifics;
sync_pb::NigoriSpecifics* server_nigori = server_specifics.mutable_nigori();
other_cryptographer.GetKeys(server_nigori->mutable_encryption_keybag());
server_nigori->set_encrypt_everything(true);
server_nigori->set_keybag_is_frozen(true);
int64_t nigori_handle = entry_factory_->CreateUnappliedNewItem(
kNigoriTag, server_specifics, true);
// Initialize the local cryptographer with the local keys.
cryptographer->AddKey(local_params);
EXPECT_TRUE(cryptographer->is_ready());
// Set up a local nigori with the local encryption keys and default encrypted
// types.
sync_pb::EntitySpecifics local_specifics;
sync_pb::NigoriSpecifics* local_nigori = local_specifics.mutable_nigori();
cryptographer->GetKeys(local_nigori->mutable_encryption_keybag());
local_nigori->set_encrypt_everything(false);
local_nigori->set_keybag_is_frozen(true);
ASSERT_TRUE(
entry_factory_->SetLocalSpecificsForItem(nigori_handle, local_specifics));
// Apply the update locally so that UpdateFromEncryptedTypes knows what state
// to use.
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
directory()->GetNigoriHandler()->ApplyNigoriUpdate(*local_nigori, &trans);
}
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_TRUE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
ApplyControlDataUpdates(directory());
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
EXPECT_FALSE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->is_initialized());
EXPECT_TRUE(cryptographer->has_pending_keys());
EXPECT_TRUE(other_cryptographer.CanDecryptUsingDefaultKey(
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encryption_keybag()));
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.keybag_is_frozen());
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encrypt_everything());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
}
// Verify we handle a nigori node conflict by merging encryption keys and
// types, but preserve the custom passphrase state of the server.
// Initial sync ended should be set.
TEST_F(ApplyControlDataUpdatesTest,
NigoriConflictPendingKeysLocalEncryptEverythingCustom) {
Cryptographer* cryptographer;
ModelTypeSet encrypted_types(SyncEncryptionHandler::SensitiveTypes());
KeyParams other_params = {"localhost", "dummy", "foobar"};
KeyParams local_params = {"localhost", "dummy", "local"};
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
// Set up a temporary cryptographer to generate new keys with.
Cryptographer other_cryptographer(cryptographer->encryptor());
other_cryptographer.AddKey(other_params);
// Create server specifics with pending keys, new encrypted types,
// and a custom passphrase (unmigrated).
sync_pb::EntitySpecifics server_specifics;
sync_pb::NigoriSpecifics* server_nigori = server_specifics.mutable_nigori();
other_cryptographer.GetKeys(server_nigori->mutable_encryption_keybag());
server_nigori->set_encrypt_everything(false);
server_nigori->set_keybag_is_frozen(false);
int64_t nigori_handle = entry_factory_->CreateUnappliedNewItem(
kNigoriTag, server_specifics, true);
// Initialize the local cryptographer with the local keys.
cryptographer->AddKey(local_params);
EXPECT_TRUE(cryptographer->is_ready());
// Set up a local nigori with the local encryption keys and default encrypted
// types.
sync_pb::EntitySpecifics local_specifics;
sync_pb::NigoriSpecifics* local_nigori = local_specifics.mutable_nigori();
cryptographer->GetKeys(local_nigori->mutable_encryption_keybag());
local_nigori->set_encrypt_everything(true);
local_nigori->set_keybag_is_frozen(true);
ASSERT_TRUE(
entry_factory_->SetLocalSpecificsForItem(nigori_handle, local_specifics));
// Apply the update locally so that UpdateFromEncryptedTypes knows what state
// to use.
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
directory()->GetNigoriHandler()->ApplyNigoriUpdate(*local_nigori, &trans);
}
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_TRUE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
ApplyControlDataUpdates(directory());
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
EXPECT_FALSE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->is_initialized());
EXPECT_TRUE(cryptographer->has_pending_keys());
EXPECT_TRUE(other_cryptographer.CanDecryptUsingDefaultKey(
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encryption_keybag()));
EXPECT_FALSE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.keybag_is_frozen());
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encrypt_everything());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
}
// If the conflicting nigori has a subset of the local keys, the conflict
// resolution should preserve the full local keys. Initial sync ended should be
// set.
TEST_F(ApplyControlDataUpdatesTest, NigoriConflictOldKeys) {
Cryptographer* cryptographer;
ModelTypeSet encrypted_types(SyncEncryptionHandler::SensitiveTypes());
KeyParams old_params = {"localhost", "dummy", "old"};
KeyParams new_params = {"localhost", "dummy", "new"};
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
// Set up the cryptographer with old keys
cryptographer->AddKey(old_params);
// Create server specifics with old keys and new encrypted types.
sync_pb::EntitySpecifics server_specifics;
sync_pb::NigoriSpecifics* server_nigori = server_specifics.mutable_nigori();
cryptographer->GetKeys(server_nigori->mutable_encryption_keybag());
server_nigori->set_encrypt_everything(true);
int64_t nigori_handle = entry_factory_->CreateUnappliedNewItem(
kNigoriTag, server_specifics, true);
// Add the new keys to the cryptogrpaher
cryptographer->AddKey(new_params);
EXPECT_TRUE(cryptographer->is_ready());
// Set up a local nigori with the superset of keys.
sync_pb::EntitySpecifics local_specifics;
sync_pb::NigoriSpecifics* local_nigori = local_specifics.mutable_nigori();
cryptographer->GetKeys(local_nigori->mutable_encryption_keybag());
local_nigori->set_encrypt_everything(false);
ASSERT_TRUE(
entry_factory_->SetLocalSpecificsForItem(nigori_handle, local_specifics));
// Apply the update locally so that UpdateFromEncryptedTypes knows what state
// to use.
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
directory()->GetNigoriHandler()->ApplyNigoriUpdate(*local_nigori, &trans);
}
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_TRUE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
ApplyControlDataUpdates(directory());
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encryption_keybag()));
EXPECT_FALSE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.keybag_is_frozen());
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encrypt_everything());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
}
// If both nigoris are migrated, but we also set a custom passphrase locally,
// the local nigori should be preserved.
TEST_F(ApplyControlDataUpdatesTest, NigoriConflictBothMigratedLocalCustom) {
Cryptographer* cryptographer;
ModelTypeSet encrypted_types(SyncEncryptionHandler::SensitiveTypes());
KeyParams old_params = {"localhost", "dummy", "old"};
KeyParams new_params = {"localhost", "dummy", "new"};
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
// Set up the cryptographer with new keys
Cryptographer other_cryptographer(cryptographer->encryptor());
other_cryptographer.AddKey(old_params);
// Create server specifics with a migrated keystore passphrase type.
sync_pb::EntitySpecifics server_specifics;
sync_pb::NigoriSpecifics* server_nigori = server_specifics.mutable_nigori();
other_cryptographer.GetKeys(server_nigori->mutable_encryption_keybag());
server_nigori->set_encrypt_everything(false);
server_nigori->set_keybag_is_frozen(true);
server_nigori->set_passphrase_type(
sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE);
server_nigori->mutable_keystore_decryptor_token();
int64_t nigori_handle = entry_factory_->CreateUnappliedNewItem(
kNigoriTag, server_specifics, true);
// Add the new keys to the cryptographer.
cryptographer->AddKey(old_params);
cryptographer->AddKey(new_params);
EXPECT_TRUE(cryptographer->is_ready());
// Set up a local nigori with a migrated custom passphrase type
sync_pb::EntitySpecifics local_specifics;
sync_pb::NigoriSpecifics* local_nigori = local_specifics.mutable_nigori();
cryptographer->GetKeys(local_nigori->mutable_encryption_keybag());
local_nigori->set_encrypt_everything(true);
local_nigori->set_keybag_is_frozen(true);
local_nigori->set_passphrase_type(
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE);
ASSERT_TRUE(
entry_factory_->SetLocalSpecificsForItem(nigori_handle, local_specifics));
// Apply the update locally so that UpdateFromEncryptedTypes knows what state
// to use.
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
directory()->GetNigoriHandler()->ApplyNigoriUpdate(*local_nigori, &trans);
}
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_TRUE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
ApplyControlDataUpdates(directory());
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encryption_keybag()));
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.keybag_is_frozen());
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encrypt_everything());
EXPECT_EQ(sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE,
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.passphrase_type());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
}
// If both nigoris are migrated, but a custom passphrase with a new key was
// set remotely, the remote nigori should be preserved.
TEST_F(ApplyControlDataUpdatesTest, NigoriConflictBothMigratedServerCustom) {
Cryptographer* cryptographer;
ModelTypeSet encrypted_types(SyncEncryptionHandler::SensitiveTypes());
KeyParams old_params = {"localhost", "dummy", "old"};
KeyParams new_params = {"localhost", "dummy", "new"};
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
// Set up the cryptographer with both new keys and old keys.
Cryptographer other_cryptographer(cryptographer->encryptor());
other_cryptographer.AddKey(old_params);
other_cryptographer.AddKey(new_params);
// Create server specifics with a migrated custom passphrase type.
sync_pb::EntitySpecifics server_specifics;
sync_pb::NigoriSpecifics* server_nigori = server_specifics.mutable_nigori();
other_cryptographer.GetKeys(server_nigori->mutable_encryption_keybag());
server_nigori->set_encrypt_everything(true);
server_nigori->set_keybag_is_frozen(true);
server_nigori->set_passphrase_type(
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE);
int64_t nigori_handle = entry_factory_->CreateUnappliedNewItem(
kNigoriTag, server_specifics, true);
// Add the old keys to the cryptographer.
cryptographer->AddKey(old_params);
EXPECT_TRUE(cryptographer->is_ready());
// Set up a local nigori with a migrated keystore passphrase type
sync_pb::EntitySpecifics local_specifics;
sync_pb::NigoriSpecifics* local_nigori = local_specifics.mutable_nigori();
cryptographer->GetKeys(local_nigori->mutable_encryption_keybag());
local_nigori->set_encrypt_everything(false);
local_nigori->set_keybag_is_frozen(true);
local_nigori->set_passphrase_type(
sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE);
server_nigori->mutable_keystore_decryptor_token();
ASSERT_TRUE(
entry_factory_->SetLocalSpecificsForItem(nigori_handle, local_specifics));
// Apply the update locally so that UpdateFromEncryptedTypes knows what state
// to use.
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
directory()->GetNigoriHandler()->ApplyNigoriUpdate(*local_nigori, &trans);
}
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_TRUE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
ApplyControlDataUpdates(directory());
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
EXPECT_TRUE(cryptographer->is_initialized());
EXPECT_TRUE(cryptographer->has_pending_keys());
EXPECT_TRUE(other_cryptographer.CanDecryptUsingDefaultKey(
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encryption_keybag()));
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.keybag_is_frozen());
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encrypt_everything());
EXPECT_EQ(sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE,
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.passphrase_type());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
}
// If the local nigori is migrated but the server is not, preserve the local
// nigori.
TEST_F(ApplyControlDataUpdatesTest, NigoriConflictLocalMigrated) {
Cryptographer* cryptographer;
ModelTypeSet encrypted_types(SyncEncryptionHandler::SensitiveTypes());
KeyParams old_params = {"localhost", "dummy", "old"};
KeyParams new_params = {"localhost", "dummy", "new"};
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
// Set up the cryptographer with both new keys and old keys.
Cryptographer other_cryptographer(cryptographer->encryptor());
other_cryptographer.AddKey(old_params);
// Create server specifics with an unmigrated implicit passphrase type.
sync_pb::EntitySpecifics server_specifics;
sync_pb::NigoriSpecifics* server_nigori = server_specifics.mutable_nigori();
other_cryptographer.GetKeys(server_nigori->mutable_encryption_keybag());
server_nigori->set_encrypt_everything(true);
server_nigori->set_keybag_is_frozen(false);
int64_t nigori_handle = entry_factory_->CreateUnappliedNewItem(
kNigoriTag, server_specifics, true);
// Add the old keys to the cryptographer.
cryptographer->AddKey(old_params);
cryptographer->AddKey(new_params);
EXPECT_TRUE(cryptographer->is_ready());
// Set up a local nigori with a migrated custom passphrase type
sync_pb::EntitySpecifics local_specifics;
sync_pb::NigoriSpecifics* local_nigori = local_specifics.mutable_nigori();
cryptographer->GetKeys(local_nigori->mutable_encryption_keybag());
local_nigori->set_encrypt_everything(true);
local_nigori->set_keybag_is_frozen(true);
local_nigori->set_passphrase_type(
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE);
ASSERT_TRUE(
entry_factory_->SetLocalSpecificsForItem(nigori_handle, local_specifics));
// Apply the update locally so that UpdateFromEncryptedTypes knows what state
// to use.
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
directory()->GetNigoriHandler()->ApplyNigoriUpdate(*local_nigori, &trans);
}
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_TRUE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
ApplyControlDataUpdates(directory());
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encryption_keybag()));
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.keybag_is_frozen());
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encrypt_everything());
EXPECT_EQ(sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE,
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.passphrase_type());
{
syncable::ReadTransaction trans(FROM_HERE, directory());
EXPECT_EQ(ModelTypeSet::All(),
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
}
// If the server nigori is migrated but the local is not, preserve the server
// nigori.
TEST_F(ApplyControlDataUpdatesTest, NigoriConflictServerMigrated) {
Cryptographer* cryptographer;
ModelTypeSet encrypted_types(SyncEncryptionHandler::SensitiveTypes());
KeyParams old_params = {"localhost", "dummy", "old"};
KeyParams new_params = {"localhost", "dummy", "new"};
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
EXPECT_EQ(encrypted_types,
directory()->GetNigoriHandler()->GetEncryptedTypes(&trans));
}
// Set up the cryptographer with both new keys and old keys.
Cryptographer other_cryptographer(cryptographer->encryptor());
other_cryptographer.AddKey(old_params);
// Create server specifics with an migrated keystore passphrase type.
sync_pb::EntitySpecifics server_specifics;
sync_pb::NigoriSpecifics* server_nigori = server_specifics.mutable_nigori();
other_cryptographer.GetKeys(server_nigori->mutable_encryption_keybag());
server_nigori->set_encrypt_everything(false);
server_nigori->set_keybag_is_frozen(true);
server_nigori->set_passphrase_type(
sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE);
server_nigori->mutable_keystore_decryptor_token();
int64_t nigori_handle = entry_factory_->CreateUnappliedNewItem(
kNigoriTag, server_specifics, true);
// Add the old keys to the cryptographer.
cryptographer->AddKey(old_params);
cryptographer->AddKey(new_params);
EXPECT_TRUE(cryptographer->is_ready());
// Set up a local nigori with a migrated custom passphrase type
sync_pb::EntitySpecifics local_specifics;
sync_pb::NigoriSpecifics* local_nigori = local_specifics.mutable_nigori();
cryptographer->GetKeys(local_nigori->mutable_encryption_keybag());
local_nigori->set_encrypt_everything(false);
local_nigori->set_keybag_is_frozen(false);
ASSERT_TRUE(
entry_factory_->SetLocalSpecificsForItem(nigori_handle, local_specifics));
// Apply the update locally so that UpdateFromEncryptedTypes knows what state
// to use.
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
directory()->GetNigoriHandler()->ApplyNigoriUpdate(*local_nigori, &trans);
}
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_TRUE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
ApplyControlDataUpdates(directory());
EXPECT_TRUE(entry_factory_->GetIsUnsyncedForItem(nigori_handle));
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(nigori_handle));
EXPECT_TRUE(cryptographer->is_ready());
// Note: we didn't overwrite the encryption keybag with the local keys. The
// sync encryption handler will do that when it detects that the new
// keybag is out of date (and update the keystore bootstrap if necessary).
EXPECT_FALSE(cryptographer->CanDecryptUsingDefaultKey(
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encryption_keybag()));
EXPECT_TRUE(cryptographer->CanDecrypt(
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.encryption_keybag()));
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.keybag_is_frozen());
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.has_keystore_decryptor_token());
EXPECT_EQ(sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE,
entry_factory_->GetLocalSpecificsForItem(nigori_handle)
.nigori()
.passphrase_type());
{ syncable::ReadTransaction trans(FROM_HERE, directory()); }
}
// Check that we can apply a simple control datatype node successfully.
TEST_F(ApplyControlDataUpdatesTest, ControlApply) {
std::string experiment_id = "experiment";
sync_pb::EntitySpecifics specifics;
specifics.mutable_experiments()->mutable_keystore_encryption()->set_enabled(
true);
int64_t experiment_handle =
entry_factory_->CreateUnappliedNewItem(experiment_id, specifics, false);
ApplyControlDataUpdates(directory());
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(experiment_handle));
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(experiment_handle)
.experiments()
.keystore_encryption()
.enabled());
}
// Verify that we apply top level folders before their children.
TEST_F(ApplyControlDataUpdatesTest, ControlApplyParentBeforeChild) {
std::string parent_id = "parent";
std::string experiment_id = "experiment";
sync_pb::EntitySpecifics specifics;
specifics.mutable_experiments()->mutable_keystore_encryption()->set_enabled(
true);
int64_t experiment_handle = entry_factory_->CreateUnappliedNewItemWithParent(
experiment_id, specifics, parent_id);
int64_t parent_handle =
entry_factory_->CreateUnappliedNewItem(parent_id, specifics, true);
ApplyControlDataUpdates(directory());
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(parent_handle));
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(experiment_handle));
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(experiment_handle)
.experiments()
.keystore_encryption()
.enabled());
}
// Verify that we handle control datatype conflicts by preserving the server
// data.
TEST_F(ApplyControlDataUpdatesTest, ControlConflict) {
std::string experiment_id = "experiment";
sync_pb::EntitySpecifics local_specifics, server_specifics;
server_specifics.mutable_experiments()
->mutable_keystore_encryption()
->set_enabled(true);
local_specifics.mutable_experiments()
->mutable_keystore_encryption()
->set_enabled(false);
int64_t experiment_handle =
entry_factory_->CreateSyncedItem(experiment_id, EXPERIMENTS, false);
entry_factory_->SetServerSpecificsForItem(experiment_handle,
server_specifics);
entry_factory_->SetLocalSpecificsForItem(experiment_handle, local_specifics);
ApplyControlDataUpdates(directory());
EXPECT_FALSE(entry_factory_->GetIsUnappliedForItem(experiment_handle));
EXPECT_TRUE(entry_factory_->GetLocalSpecificsForItem(experiment_handle)
.experiments()
.keystore_encryption()
.enabled());
}
// Check that applying a EXPERIMENTS update marks the datatype as downloaded.
TEST_F(ApplyControlDataUpdatesTest, ExperimentsApplyMarksDownloadCompleted) {
EXPECT_FALSE(directory()->InitialSyncEndedForType(EXPERIMENTS));
// Create root node for EXPERIMENTS datatype
{
syncable::WriteTransaction trans(FROM_HERE, UNITTEST, directory());
syncable::ModelNeutralMutableEntry entry(
&trans, syncable::CREATE_NEW_TYPE_ROOT, EXPERIMENTS);
ASSERT_TRUE(entry.good());
entry.PutServerIsDir(true);
entry.PutUniqueServerTag(ModelTypeToRootTag(EXPERIMENTS));
}
// Initial sync isn't marked as ended for EXPERIMENTS even though the
// root folder exists.
EXPECT_FALSE(directory()->InitialSyncEndedForType(EXPERIMENTS));
std::string experiment_id = "experiment";
sync_pb::EntitySpecifics specifics;
specifics.mutable_experiments()->mutable_keystore_encryption()->set_enabled(
true);
entry_factory_->CreateUnappliedNewItem(experiment_id, specifics, false);
ApplyControlDataUpdates(directory());
// After applying the updates EXPERIMENTS should be marked as having its
// initial sync completed.
EXPECT_TRUE(directory()->InitialSyncEndedForType(EXPERIMENTS));
// Verify that there is no side effect on another control type.
EXPECT_FALSE(directory()->InitialSyncEndedForType(NIGORI));
}
// Check that applying a NIGORI update marks the datatype as downloaded.
TEST_F(ApplyControlDataUpdatesTest, NigoriApplyMarksDownloadCompleted) {
EXPECT_FALSE(directory()->InitialSyncEndedForType(NIGORI));
Cryptographer* cryptographer;
{
syncable::ReadTransaction trans(FROM_HERE, directory());
cryptographer = directory()->GetCryptographer(&trans);
}
KeyParams params = {"localhost", "dummy", "foobar"};
cryptographer->AddKey(params);
sync_pb::EntitySpecifics specifics;
sync_pb::NigoriSpecifics* nigori = specifics.mutable_nigori();
cryptographer->GetKeys(nigori->mutable_encryption_keybag());
nigori->set_encrypt_everything(true);
entry_factory_->CreateUnappliedNewItem(ModelTypeToRootTag(NIGORI), specifics,
true);
ApplyControlDataUpdates(directory());
// After applying the updates NIGORI should be marked as having its
// initial sync completed.
EXPECT_TRUE(directory()->InitialSyncEndedForType(NIGORI));
// Verify that there is no side effect on another control type.
EXPECT_FALSE(directory()->InitialSyncEndedForType(EXPERIMENTS));
}
} // namespace syncer
| [
"[email protected]"
] | |
f747f26da20aae8c2c15781f1a02a154256611c8 | ca9d98e43420dea54cc06cc2baec23f7620ac777 | /Project1/Game.h | dc4ac08a9333e98f09f3e72401dd6c4bc6c70dd2 | [] | no_license | Piotr-Skorupa/Bloody-Trial | c655d3fbf92726f373df28b4845734881c3620fa | c36f91746c66b5f9ccafbaebe390f2ca3f0fab1e | refs/heads/master | 2020-05-22T22:56:50.977914 | 2018-01-23T20:19:33 | 2018-01-23T20:19:33 | 84,732,487 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,081 | h | #pragma once
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "Hero.h"
class Game
{
public:
sf::Texture t1;
sf::Texture t2;
sf::Sprite tutorial1;
sf::Sprite tutorial2;
sf::Texture zycie;
sf::Texture zycie075;
sf::Texture zycie05;
sf::Texture zycie025;
sf::Texture zycie0;
sf::Sprite life;
sf::Texture czar;
sf::Texture czar075;
sf::Texture czar05;
sf::Texture czar025;
sf::Texture czar0;
sf::Texture potman;
sf::Texture potlif;
sf::Sprite pot1;
sf::Sprite pot2;
sf::Texture bron1;
sf::Texture bron2;
sf::Texture bron3;
sf::Texture bron4;
sf::Texture bron5;
sf::Sprite weapon;
sf::Sprite mana;
sf::Font font;
sf::Text level;
sf::Texture pasek;
sf::Sprite label;
sf::Text cash;
sf::Text p1;
sf::Text p2;
sf::Text damage;
Game();
~Game();
void draw(sf::RenderWindow &window);
void tutorial(sf::RenderWindow &window, bool f);
void lvlText(int x);
void cashText(int x);
void pot1Txt(int x);
void pot2Txt(int x);
void dmgTxt(int x, int y);
void check_wep(Hero &h);
};
| [
"[email protected]"
] | |
a6dd68edd5099be7184796d4858b377f995f000e | 2f557f60fc609c03fbb42badf2c4f41ef2e60227 | /DataFormats/CaloTowers/src/CaloTowerDetId.cc | 4c97b528958f83eb8e4d256ec373e2010ca26904 | [
"Apache-2.0"
] | permissive | CMS-TMTT/cmssw | 91d70fc40a7110832a2ceb2dc08c15b5a299bd3b | 80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7 | refs/heads/TMTT_1060 | 2020-03-24T07:49:39.440996 | 2020-03-04T17:21:36 | 2020-03-04T17:21:36 | 142,576,342 | 3 | 5 | Apache-2.0 | 2019-12-05T21:16:34 | 2018-07-27T12:48:13 | C++ | UTF-8 | C++ | false | false | 1,223 | cc | #include "DataFormats/CaloTowers/interface/CaloTowerDetId.h"
#include "FWCore/Utilities/interface/Exception.h"
#include <iostream>
CaloTowerDetId::CaloTowerDetId() : DetId() {
}
CaloTowerDetId::CaloTowerDetId(uint32_t rawid) : DetId(rawid&0xFFF0FFFFu) {
}
CaloTowerDetId::CaloTowerDetId(int ieta, int iphi) : DetId(Calo,SubdetId) {
id_|=
((ieta>0)?(0x2000|((ieta&0x3F)<<7)):(((-ieta)&0x3f)<<7)) |
(iphi&0x7F);
}
CaloTowerDetId::CaloTowerDetId(const DetId& gen) {
if (!gen.null() && (gen.det()!=Calo || gen.subdetId()!=SubdetId)) {
throw cms::Exception("Invalid DetId") << "Cannot initialize CaloTowerDetId from " << std::hex << gen.rawId() << std::dec;
}
id_=gen.rawId();
}
CaloTowerDetId& CaloTowerDetId::operator=(const DetId& gen) {
if (!gen.null() && (gen.det()!=Calo || gen.subdetId()!=SubdetId)) {
throw cms::Exception("Invalid DetId") << "Cannot assign CaloTowerDetId from " << std::hex << gen.rawId() << std::dec;
}
id_=gen.rawId();
return *this;
}
int CaloTowerDetId::iphi() const {
int retval=id_&0x7F;
return retval;
}
std::ostream& operator<<(std::ostream& s, const CaloTowerDetId& id) {
return s << "Tower (" << id.ieta() << "," << id.iphi() << ")";
}
| [
"[email protected]"
] | |
b006ecccf20cad414dd40c51af2f70323b719ca0 | 0886e02d259b8f09e2ce4271784fb9a31eb08d3d | /src/strand.h | b4ab1b13fd9629b38a763cd93a1bd6bb3b3561b4 | [
"MIT"
] | permissive | haowenz/chromap | fc7d830ed8902bff111a4e253b7d7413a5c0aa5b | 9620d1392ff312a41df73e9bd039fbf1432415f5 | refs/heads/master | 2023-08-31T11:30:15.478358 | 2023-05-20T04:04:49 | 2023-05-23T16:48:36 | 217,435,356 | 149 | 18 | MIT | 2023-09-06T06:42:27 | 2019-10-25T02:32:53 | C++ | UTF-8 | C++ | false | false | 148 | h | #ifndef STRAND_H_
#define STRAND_H_
namespace chromap {
enum Strand {
kPositive,
kNegative,
};
} // namespace chromap
#endif // STRAND_H_
| [
"[email protected]"
] | |
4b68a7add48b99e448e9e76069589ec2873d5b1e | a9c268b492d91d3267683449f205b785785fcf28 | /GameEngine/Engine/Physics/RigidBody.h | 99f7b584e0ead8243a19cdc0c4826d5bfaf9fa83 | [] | no_license | oneillsimon/GameEngine_Old | 707698588c2108d82c8aaf50b775deacf8434cfa | 7dc3004fe34524067340f768afea65be99f588bf | refs/heads/master | 2021-05-28T14:17:01.750369 | 2015-03-02T15:27:50 | 2015-03-02T15:27:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,843 | h | #ifndef RIGIDBODY_H
#define RIGIDBODY_H
#include <assert.h>
#include <math.h>
#include "../Core/Math3D.h"
#include "PhysicsComponent.h"
class PhysicsComponent;
class RigidBody
{
private:
const float m_sleepEpsilon = 0.1f;
PhysicsComponent* m_parent;
float m_inverseMass;
Matrix3 m_inverseInertiaTensor;
float m_linearDamping;
float m_angularDamping;
Vector3 m_velocity;
Vector3 m_acceleration;
Vector3 m_rotation;
Matrix3 m_inverseInertiaTensorWorld;
float m_motion;
bool m_isAwake;
bool m_canSleep;
bool m_hasInfiniteMass;
Vector3 m_forceAccum;
Vector3 m_torqueAccum;
Vector3 m_lastFrameAcceleration;
public:
RigidBody(float mass, float linear = 0.1f, float angular = 0.1f);
void calculateDerivedData();
void integrate(float delta);
void clearAccumulators();
bool hasFiniteMass() const;
void setParent(PhysicsComponent* physicsObject);
void setMass(const float mass);
void setInverseMass(const float inverseMass);
void setIntertiaTensor(const Matrix3& interiaTensor);
void setInverseInertiaTensor(const Matrix3& inverseInertiaTensor);
void setDamping(const float linearDamping, const float angularDamping);
void setLinearDamping(const float linearDamping);
void setAngularDamping(const float angularDamping);
void setPosition(const Vector3& position);
void setOrientation(Quaternion& orientation);
PhysicsComponent* getParent();
float getMass() const;
float getInverseMass() const;
void getInertiaTensor(Matrix3* intertiaTensor) const;
Matrix3 getInertiaTensor() const;
void getInertiaTensorWorld(Matrix3* intertiaTensor) const;
Matrix3 getInertiaTensorWorld() const;
Matrix3 getInverseInertiaTensor() const;
Matrix3 getInverseInertiaTensorWorld() const;
float getLinearDamping() const;
float getAngularDamping() const;
Vector3 getPosition() const;
Quaternion getOrientation() const;
Vector3 getPointInLocalSpace(const Vector3& point) const;
Vector3 getPointInWorldSpace(const Vector3& point) const;
Vector3 getDirectionInLocalSpace(const Vector3& direction) const;
Vector3 getDirectionInWorldSpace(const Vector3& direction) const;
void setVelocity(const Vector3& velocity);
Vector3 getVelocity() const;
void addVelocity(const Vector3& deltaVelocity);
void setRotation(const Vector3& rotation);
Vector3 getRotation() const;
void addRotation(const Vector3& deltaRotation);
bool getAwake() const;
void setAwake(const bool awake = true);
bool getCanSleep() const;
void setCanSleep(const bool canSleep = true);
Vector3 getLastFrameAcceleration() const;
void addForce(const Vector3& force);
void addForceAtPoint(const Vector3& force, const Vector3& point);
void addForceAtBodyPoint(const Vector3& force, const Vector3& point);
void addTorque(const Vector3& torque);
void setAcceleration(const Vector3& acceleration);
Vector3 getAcceleration() const;
};
#endif | [
"[email protected]"
] | |
076e83e6d54c94d294ef389e0c7aa1c5de6faffa | 037faae47a5b22d3e283555e6b5ac2a0197faf18 | /plugins/gs/gsdx9/GSRendererNull.h | 574a5364a33c4ca403299612ffabbf6e25aef475 | [] | no_license | isabella232/pcsx2-sourceforge | 6e5aac8d0b476601bfc8fa83ded66c1564b8c588 | dbb2c3a010081b105a8cba0c588f1e8f4e4505c6 | refs/heads/master | 2023-03-18T22:23:15.102593 | 2008-11-17T20:10:17 | 2008-11-17T20:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,215 | h | /*
* Copyright (C) 2003-2005 Gabest
* http://www.gabest.org
*
* 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, 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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#pragma once
#include "GSRenderer.h"
#pragma pack(push, 1)
struct NULLVERTEX {/*DWORD dummy;*/};
#pragma pack(pop)
class GSRendererNull : public GSRenderer<NULLVERTEX>
{
protected:
void VertexKick(bool fSkip);
int DrawingKick(bool fSkip);
void Flip();
void EndFrame();
public:
GSRendererNull(HWND hWnd, HRESULT& hr);
~GSRendererNull();
}; | [
"zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84"
] | zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84 |
a774b9004060e0205fbe9d8988ad8b40ea216f02 | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /third_party/blink/common/features.cc | 00034bce4cd07b76740d7ad53d113a85d40acd1e | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 21,940 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/public/common/features.h"
#include "base/feature_list.h"
#include "build/build_config.h"
#include "services/network/public/cpp/features.h"
#include "third_party/blink/public/common/forcedark/forcedark_switches.h"
namespace blink {
namespace features {
// Enable intervention for download that was initiated from or occurred in an ad
// frame without user activation.
const base::Feature kBlockingDownloadsInAdFrameWithoutUserActivation{
"BlockingDownloadsInAdFrameWithoutUserActivation",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable defer commits to avoid flash of unstyled content.
const base::Feature kPaintHolding{"PaintHolding",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable eagerly setting up a CacheStorage interface pointer and
// passing it to service workers on startup as an optimization.
const base::Feature kEagerCacheStorageSetupForServiceWorkers{
"EagerCacheStorageSetupForServiceWorkers",
base::FEATURE_ENABLED_BY_DEFAULT};
// Controls script streaming.
const base::Feature kScriptStreaming{"ScriptStreaming",
base::FEATURE_ENABLED_BY_DEFAULT};
// Allow streaming small (<30kB) scripts.
const base::Feature kSmallScriptStreaming{"SmallScriptStreaming",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables user level memory pressure signal generation on Android.
const base::Feature kUserLevelMemoryPressureSignal{
"UserLevelMemoryPressureSignal", base::FEATURE_DISABLED_BY_DEFAULT};
// Perform memory purges after freezing only if all pages are frozen.
const base::Feature kFreezePurgeMemoryAllPagesFrozen{
"FreezePurgeMemoryAllPagesFrozen", base::FEATURE_DISABLED_BY_DEFAULT};
// Freezes the user-agent as part of https://github.com/WICG/ua-client-hints.
const base::Feature kFreezeUserAgent{"FreezeUserAgent",
base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, enter assumed-overlap mode in compositing overlap testing
// anytime a fixed or sticky position element is encountered.
const base::Feature kAssumeOverlapAfterFixedOrStickyPosition{
"AssumeOverlapAfterFixedOrStickyPosition",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enable Display Locking JavaScript APIs.
const base::Feature kDisplayLocking{"DisplayLocking",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kJSONModules{"JSONModules",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enable LayoutNG.
const base::Feature kLayoutNG{"LayoutNG", base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kMixedContentAutoupgrade{"AutoupgradeMixedContent",
base::FEATURE_ENABLED_BY_DEFAULT};
// Used to control the collection of anchor element metrics (crbug.com/856683).
// If kNavigationPredictor is enabled, then metrics of anchor elements
// in the first viewport after the page load and the metrics of the clicked
// anchor element will be extracted and recorded. Additionally, navigation
// predictor may preconnect/prefetch to resources/origins to make the
// future navigations faster.
const base::Feature kNavigationPredictor {
"NavigationPredictor",
#if defined(OS_ANDROID)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Start service workers on a background thread.
// https://crbug.com/692909
const base::Feature kOffMainThreadServiceWorkerStartup{
"OffMainThreadServiceWorkerStartup", base::FEATURE_ENABLED_BY_DEFAULT};
// Enable browser-initiated dedicated worker script loading
// (PlzDedicatedWorker). https://crbug.com/906991
const base::Feature kPlzDedicatedWorker{"PlzDedicatedWorker",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enable Portals. https://crbug.com/865123.
const base::Feature kPortals{"Portals", base::FEATURE_DISABLED_BY_DEFAULT};
// When kPortals is enabled, allow portals to load content that is third-party
// (cross-origin) to the hosting page. Otherwise has no effect.
//
// This will be disabled by default by the time Portals is generally available,
// either in origin trial or shipped.
//
// https://crbug.com/1013389
const base::Feature kPortalsCrossOrigin{"PortalsCrossOrigin",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable limiting previews loading hints to specific resource types.
const base::Feature kPreviewsResourceLoadingHintsSpecificResourceTypes{
"PreviewsResourceLoadingHintsSpecificResourceTypes",
base::FEATURE_DISABLED_BY_DEFAULT};
// Perform a memory purge after a renderer is backgrounded. Formerly labelled as
// the "PurgeAndSuspend" experiment.
//
// TODO(adityakeerthi): Disabled by default on Mac and Android for historical
// reasons. Consider enabling by default if experiment results are positive.
// https://crbug.com/926186
const base::Feature kPurgeRendererMemoryWhenBackgrounded {
"PurgeRendererMemoryWhenBackgrounded",
#if defined(OS_MACOSX) || defined(OS_ANDROID)
base::FEATURE_DISABLED_BY_DEFAULT
#else
base::FEATURE_ENABLED_BY_DEFAULT
#endif
};
// Enable Implicit Root Scroller. https://crbug.com/903260.
// TODO(bokan): Temporarily disabled on desktop platforms to address issues
// with non-overlay scrollbars. https://crbug.com/948059.
const base::Feature kImplicitRootScroller {
"ImplicitRootScroller",
#if defined(OS_ANDROID)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Enable CSSOM View Scroll Coordinates. https://crbug.com/721759.
const base::Feature kCSSOMViewScrollCoordinates{
"CSSOMViewScrollCoordinates", base::FEATURE_DISABLED_BY_DEFAULT};
// Enables Raw Clipboard. https://crbug.com/897289.
const base::Feature kRawClipboard{"RawClipboard",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables usage of getDisplayMedia() that allows capture of web content, see
// https://crbug.com/865060.
const base::Feature kRTCGetDisplayMedia{"RTCGetDisplayMedia",
base::FEATURE_ENABLED_BY_DEFAULT};
// Changes the default RTCPeerConnection constructor behavior to use Unified
// Plan as the SDP semantics. When the feature is enabled, Unified Plan is used
// unless the default is overridden (by passing {sdpSemantics:'plan-b'} as the
// argument).
const base::Feature kRTCUnifiedPlanByDefault{"RTCUnifiedPlanByDefault",
base::FEATURE_ENABLED_BY_DEFAULT};
// Determines if the SDP attrbute extmap-allow-mixed should be offered by
// default or not. The default value can be overridden by passing
// {offerExtmapAllowMixed:true} as an argument to the RTCPeerConnection
// constructor.
const base::Feature kRTCOfferExtmapAllowMixed{
"RTCOfferExtmapAllowMixed", base::FEATURE_DISABLED_BY_DEFAULT};
// Enables negotiation of experimental multiplex codec in SDP.
const base::Feature kWebRtcMultiplexCodec{"WebRTC-MultiplexCodec",
base::FEATURE_DISABLED_BY_DEFAULT};
// Causes WebRTC to replace host ICE candidate IP addresses with generated
// names ending in ".local" and resolve them using mDNS.
// http://crbug.com/878465
const base::Feature kWebRtcHideLocalIpsWithMdns{
"WebRtcHideLocalIpsWithMdns", base::FEATURE_ENABLED_BY_DEFAULT};
#if BUILDFLAG(RTC_USE_H264) && BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS)
// Run-time feature for the |rtc_use_h264| encoder/decoder.
const base::Feature kWebRtcH264WithOpenH264FFmpeg{
"WebRTC-H264WithOpenH264FFmpeg", base::FEATURE_ENABLED_BY_DEFAULT};
#endif // BUILDFLAG(RTC_USE_H264) && BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS)
// Experiment of the delay from navigation to starting an update of a service
// worker's script.
const base::Feature kServiceWorkerUpdateDelay{
"ServiceWorkerUpdateDelay", base::FEATURE_DISABLED_BY_DEFAULT};
// Freeze scheduler task queues in background after allowed grace time.
// "stop" is a legacy name.
const base::Feature kStopInBackground {
"stop-in-background",
#if defined(OS_ANDROID)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Freeze scheduler task queues in background on network idle.
// This feature only works if stop-in-background is enabled.
const base::Feature kFreezeBackgroundTabOnNetworkIdle{
"freeze-background-tab-on-network-idle", base::FEATURE_DISABLED_BY_DEFAULT};
// Freeze non-timer task queues in background, after allowed grace time.
// "stop" is a legacy name.
const base::Feature kStopNonTimersInBackground{
"stop-non-timers-in-background", base::FEATURE_ENABLED_BY_DEFAULT};
// Enable the Storage Access API. https://crbug.com/989663.
const base::Feature kStorageAccessAPI{"StorageAccessAPI",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enable text snippets in URL fragments. https://crbug.com/919204.
const base::Feature kTextFragmentAnchor{"TextFragmentAnchor",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables the site isolated Wasm code cache that is keyed on the resource URL
// and the origin lock of the renderer that is requesting the resource. When
// this flag is enabled, content/GeneratedCodeCache handles code cache requests.
const base::Feature kWasmCodeCache = {"WasmCodeCache",
base::FEATURE_ENABLED_BY_DEFAULT};
// Writable files and native file system access. https://crbug.com/853326
const base::Feature kNativeFileSystemAPI{"NativeFileSystemAPI",
base::FEATURE_ENABLED_BY_DEFAULT};
// File handling integration. https://crbug.com/829689
const base::Feature kFileHandlingAPI{"FileHandlingAPI",
base::FEATURE_DISABLED_BY_DEFAULT};
// Allows for synchronous XHR requests during page dismissal
const base::Feature kAllowSyncXHRInPageDismissal{
"AllowSyncXHRInPageDismissal", base::FEATURE_DISABLED_BY_DEFAULT};
// Font enumeration and table access. https://crbug.com/535764 and
// https://crbug.com/982054.
const base::Feature kFontAccess{"FontAccess",
base::FEATURE_DISABLED_BY_DEFAULT};
// Allows Web Components v0 to be re-enabled.
const base::Feature kWebComponentsV0Enabled{"WebComponentsV0Enabled",
base::FEATURE_DISABLED_BY_DEFAULT};
// Prefetch request properties are updated to be privacy-preserving. See
// crbug.com/988956.
const base::Feature kPrefetchPrivacyChanges{"PrefetchPrivacyChanges",
base::FEATURE_DISABLED_BY_DEFAULT};
const char kMixedContentAutoupgradeModeParamName[] = "mode";
const char kMixedContentAutoupgradeModeAllPassive[] = "all-passive";
// Decodes jpeg 4:2:0 formatted images to YUV instead of RGBX and stores in this
// format in the image decode cache. See crbug.com/919627 for details on the
// feature.
const base::Feature kDecodeJpeg420ImagesToYUV{
"DecodeJpeg420ImagesToYUV", base::FEATURE_DISABLED_BY_DEFAULT};
// Decodes lossy WebP images to YUV instead of RGBX and stores in this format
// in the image decode cache. See crbug.com/900264 for details on the feature.
const base::Feature kDecodeLossyWebPImagesToYUV{
"DecodeLossyWebPImagesToYUV", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables cache-aware WebFonts loading. See https://crbug.com/570205.
// The feature is disabled on Android for WebView API issue discussed at
// https://crbug.com/942440.
const base::Feature kWebFontsCacheAwareTimeoutAdaption {
"WebFontsCacheAwareTimeoutAdaption",
#if defined(OS_ANDROID)
base::FEATURE_DISABLED_BY_DEFAULT
#else
base::FEATURE_ENABLED_BY_DEFAULT
#endif
};
// Enabled to block programmatic focus in subframes when not triggered by user
// activation (see htpps://crbug.com/954349).
const base::Feature kBlockingFocusWithoutUserActivation{
"BlockingFocusWithoutUserActivation", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kAudioWorkletRealtimeThread{
"AudioWorkletRealtimeThread", base::FEATURE_DISABLED_BY_DEFAULT};
// A feature to reduce the set of resources fetched by No-State Prefetch.
const base::Feature kLightweightNoStatePrefetch{
"LightweightNoStatePrefetch",
#if defined(OS_ANDROID)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// A feature to enable web fonts to be fetched by No-State Prefetch.
const base::Feature kLightweightNoStatePrefetch_FetchFonts{
"LightweightNoStatePrefetch_FetchFonts", base::FEATURE_DISABLED_BY_DEFAULT};
// Automatically convert light-themed pages to use a Blink-generated dark theme
const base::Feature kForceWebContentsDarkMode{
"WebContentsForceDark", base::FEATURE_DISABLED_BY_DEFAULT};
// A feature to enable using the smallest image specified within image srcset
// for users with Save Data enabled.
const base::Feature kSaveDataImgSrcset{"SaveDataImgSrcset",
base::FEATURE_DISABLED_BY_DEFAULT};
// Which algorithm should be used for color inversion?
const base::FeatureParam<ForceDarkInversionMethod>::Option
forcedark_inversion_method_options[] = {
{ForceDarkInversionMethod::kUseBlinkSettings,
"use_blink_settings_for_method"},
{ForceDarkInversionMethod::kHslBased, "hsl_based"},
{ForceDarkInversionMethod::kCielabBased, "cielab_based"},
{ForceDarkInversionMethod::kRgbBased, "rgb_based"}};
const base::FeatureParam<ForceDarkInversionMethod>
kForceDarkInversionMethodParam{&kForceWebContentsDarkMode,
"inversion_method",
ForceDarkInversionMethod::kUseBlinkSettings,
&forcedark_inversion_method_options};
// Should images be inverted?
const base::FeatureParam<ForceDarkImageBehavior>::Option
forcedark_image_behavior_options[] = {
{ForceDarkImageBehavior::kUseBlinkSettings,
"use_blink_settings_for_images"},
{ForceDarkImageBehavior::kInvertNone, "none"},
{ForceDarkImageBehavior::kInvertSelectively, "selective"}};
const base::FeatureParam<ForceDarkImageBehavior> kForceDarkImageBehaviorParam{
&kForceWebContentsDarkMode, "image_behavior",
ForceDarkImageBehavior::kUseBlinkSettings,
&forcedark_image_behavior_options};
// Do not invert text lighter than this.
// Range: 0 (do not invert any text) to 256 (invert all text)
// Can also set to -1 to let Blink's internal settings control the value
const base::FeatureParam<int> kForceDarkTextLightnessThresholdParam{
&kForceWebContentsDarkMode, "text_lightness_threshold", -1};
// Do not invert backgrounds darker than this.
// Range: 0 (invert all backgrounds) to 256 (invert no backgrounds)
// Can also set to -1 to let Blink's internal settings control the value
const base::FeatureParam<int> kForceDarkBackgroundLightnessThresholdParam{
&kForceWebContentsDarkMode, "background_lightness_threshold", -1};
// Instructs WebRTC to honor the Min/Max Video Encode Accelerator dimensions.
const base::Feature kWebRtcUseMinMaxVEADimensions {
"WebRtcUseMinMaxVEADimensions",
// TODO(crbug.com/1008491): enable other platforms.
#if defined(OS_CHROMEOS)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Blink garbage collection.
// Enables compaction of backing stores on Blink's heap.
const base::Feature kBlinkHeapCompaction{"BlinkHeapCompaction",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables concurrently marking Blink's heap.
const base::Feature kBlinkHeapConcurrentMarking{
"BlinkHeapConcurrentMarking", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables concurrently sweeping Blink's heap.
const base::Feature kBlinkHeapConcurrentSweeping{
"BlinkHeapConcurrentSweeping", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables incrementally marking Blink's heap.
const base::Feature kBlinkHeapIncrementalMarking{
"BlinkHeapIncrementalMarking", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables a marking stress mode that schedules more garbage collections and
// also adds additional verification passes.
const base::Feature kBlinkHeapIncrementalMarkingStress{
"BlinkHeapIncrementalMarkingStress", base::FEATURE_DISABLED_BY_DEFAULT};
// Enables removing AppCache delays when triggering requests when the HTML was
// not fetched from AppCache.
const base::Feature kVerifyHTMLFetchedFromAppCacheBeforeDelay{
"VerifyHTMLFetchedFromAppCacheBeforeDelay",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether we use ThreadPriority::DISPLAY for renderer
// compositor & IO threads.
const base::Feature kBlinkCompositorUseDisplayThreadPriority {
"BlinkCompositorUseDisplayThreadPriority",
#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(OS_WIN)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Ignores cross origin windows in the named property interceptor of Window.
// https://crbug.com/538562
const base::Feature kIgnoreCrossOriginWindowWhenNamedAccessOnWindow{
"IgnoreCrossOriginWindowWhenNamedAccessOnWindow",
base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, loading priority of JavaScript requests is lowered when they
// are force deferred by the intervention.
const base::Feature kLowerJavaScriptPriorityWhenForceDeferred{
"LowerJavaScriptPriorityWhenForceDeferred",
base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, scripts in iframes are not force deferred by the DeferAllScript
// intervention.
const base::Feature kDisableForceDeferInChildFrames{
"DisableForceDeferInChildFrames", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kHtmlImportsRequestInitiatorLock{
"HtmlImportsRequestInitiatorLock", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables redirecting subresources in the page to better compressed and
// optimized versions to provide data savings.
const base::Feature kSubresourceRedirect{"SubresourceRedirect",
base::FEATURE_DISABLED_BY_DEFAULT};
// When 'enabled', all cross-origin iframes will get a compositing layer.
const base::Feature kCompositeCrossOriginIframes{
"CompositeCrossOriginIframes", base::FEATURE_DISABLED_BY_DEFAULT};
// When 'enabled', an accurate occlusion test will be performed to improve the
// quality of viz hit test data.
const base::Feature kVizHitTestOcclusionCheck{
"VizHitTestOcclusionCheck", base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, beacons (and friends) have ResourceLoadPriority::kLow,
// not ResourceLoadPriority::kVeryLow.
const base::Feature kSetLowPriorityForBeacon{"SetLowPriorityForBeacon",
base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled allows the header name used in the blink
// CacheStorageCodeCacheHint runtime feature to be modified. This runtime
// feature disables generating full code cache for responses stored in
// cache_storage during a service worker install event. The runtime feature
// must be enabled via the blink runtime feature mechanism, however.
const base::Feature kCacheStorageCodeCacheHintHeader{
"CacheStorageCodeCacheHintHeader", base::FEATURE_DISABLED_BY_DEFAULT};
const base::FeatureParam<std::string> kCacheStorageCodeCacheHintHeaderName{
&kCacheStorageCodeCacheHintHeader, "name", "x-CacheStorageCodeCacheHint"};
// When enabled, the beforeunload handler is dispatched when a frame is frozen.
// This allows the browser to know whether discarding the frame could result in
// lost user data, at the cost of extra CPU usage. The feature will be removed
// once we have determine whether the CPU cost is acceptable.
const base::Feature kDispatchBeforeUnloadOnFreeze{
"DispatchBeforeUnloadOnFreeze", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables the use of GpuMemoryBuffer images for low latency 2d canvas.
// TODO(khushalsagar): Enable this if we're using SurfaceControl and GMBs allow
// us to overlay these resources.
const base::Feature kLowLatencyCanvas2dImageChromium {
"LowLatencyCanvas2dImageChromium",
#if defined(OS_CHROMEOS)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif // OS_CHROMEOS
};
// Enables the use of shared image swap chains for low latency 2d canvas.
const base::Feature kLowLatencyCanvas2dSwapChain{
"LowLatencyCanvas2dSwapChain", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables the use of shared image swap chains for low latency webgl canvas.
const base::Feature kLowLatencyWebGLSwapChain{"LowLatencyWebGLSwapChain",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables forcing additional rendering of subframes for the purpose of sticky
// frame tracking.
const base::Feature kForceExtraRenderingToTrackStickyFrame{
"ForceExtraRenderingToTrackStickyFrame", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kCSSReducedFontLoadingInvalidations{
"CSSReducedFontLoadingInvalidations", base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, frees up CachedMetadata after consumption by script resources
// and modules. Needed for the experiment in http://crbug.com/1045052.
const base::Feature kDiscardCodeCacheAfterFirstUse{
"DiscardCodeCacheAfterFirstUse", base::FEATURE_DISABLED_BY_DEFAULT};
// The kill-switch for the fix for https://crbug.com/1051439.
// TODO(crbug.com/1053369): Remove this around M84.
const base::Feature kSuppressContentTypeForBeaconMadeWithArrayBufferView{
"SuppressContentTypeForBeaconMadeWithArrayBufferView",
base::FEATURE_ENABLED_BY_DEFAULT};
} // namespace features
} // namespace blink
| [
"[email protected]"
] | |
7b628e27d6c5ae1c6b1fa159aadf8592aea550f1 | 8a7183308a2189d01244fe3f37367eaf72b88c34 | /design_pattern/factory/Product.cc | 7552e5a5f5d498e6a72177bbfdb0b828dd12ddfb | [] | no_license | xkfz007/cpp_progs | 0b4e6eb75c78c13c2696fcfd164929f532cfefc5 | b474b4678d6e6286b0db7a0b06ed27ed0207c801 | refs/heads/master | 2020-12-24T06:49:20.224825 | 2017-01-20T11:11:01 | 2017-01-20T11:11:01 | 59,337,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cc | #include "Product.h"
#include <iostream>
Product::Product(){
std::cout<<"constructor of Product\n";
}
Product::~Product(){
std::cout<<"destructor of Product\n";
}
ConcreteProduct1::ConcreteProduct1(){
std::cout<<"constructor of ConcreteProduct1\n";
}
ConcreteProduct1::~ConcreteProduct1(){
std::cout<<"destructor of ConcreteProduct1\n";
}
void ConcreteProduct1::Operation(){
std::cout<<"Operation of ConcreteProduct1\n";
}
ConcreteProduct0::ConcreteProduct0(){
std::cout<<"constructor of ConcreteProduct0\n";
}
ConcreteProduct0::~ConcreteProduct0(){
std::cout<<"destructor of ConcreteProduct0\n";
}
void ConcreteProduct0::Operation(){
std::cout<<"Operation of ConcreteProduct0\n";
}
| [
"[email protected]"
] | |
300b4bbdb6e436b2638c85c663e04d06b21dfdca | 28dba754ddf8211d754dd4a6b0704bbedb2bd373 | /Contest/SEU-2014-5-11/G/main.cpp | 71ffd647b9e2f84dd4ff174ebd0761c78be2affb | [] | no_license | zjsxzy/algo | 599354679bd72ef20c724bb50b42fce65ceab76f | a84494969952f981bfdc38003f7269e5c80a142e | refs/heads/master | 2023-08-31T17:00:53.393421 | 2023-08-19T14:20:31 | 2023-08-19T14:20:31 | 10,140,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | cpp | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <string>
#include <cassert>
#include <climits>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define abs(x) ((x) > 0 ? (x) : -(x))
#define FOREACH(e,x) for(__typeof(x.begin()) e=x.begin();e!=x.end();++e)
typedef long long LL;
const double eps = 1e-8;
double X1, X2, Y1, Y2, vx, vy, V;
int main() {
int ts;
scanf("%d", &ts);
while (ts--) {
scanf("%lf%lf%lf%lf%lf%lf%lf", &X1, &Y1, &X2, &Y2, &vx, &vy, &V);
double dx = X1 - X2, dy = Y1 - Y2;
double a = vx * vx + vy * vy - V * V;
double b = 2.0 * (vx * dx + vy * dy);
double c = dx * dx + dy * dy;
double delta = b * b - 4 * a * c;
if (abs(a) < eps) {
double t = -(c / b);
if (t < 0) {
printf("(0,0)\n");
} else {
double x3 = X1 + vx * t, y3 = Y1 + vy * t;
dx = x3 - X2; dy = y3 - Y2;
double len = sqrt(dx * dx + dy * dy);
dx /= len;
dy /= len;
printf("(%.6f,%.6f)\n", dx, dy);
}
continue;
}
if (delta < 0) {
printf("(0,0)\n");
} else {
double t1 = (-b - sqrt(delta)) / a / 2.0, t2 = (-b + sqrt(delta)) / a / 2.0;
double t;
if (t1 < 0 && t2 < 0) {
printf("(0,0)\n");
continue;
} else if (t1 < 0 && t2 >= 0) {
t = t2;
} else if (t2 < 0 && t1 >= 0) {
t = t1;
} else {
t = min(t1, t2);
}
//printf("%.6f %.6f %.6f %.6f\n", a, b, c, t);
double x3 = X1 + vx * t, y3 = Y1 + vy * t;
dx = x3 - X2; dy = y3 - Y2;
double len = sqrt(dx * dx + dy * dy);
dx /= len;
dy /= len;
printf("(%.6f,%.6f)\n", dx, dy);
}
}
return 0;
}
| [
"[email protected]"
] | |
e8c9117fbb2f7733cdeb508a594bd88de3501bb4 | 06861f9da5c7ef4764ba2b739c7b8028160d59e4 | /MyLittleGame/source/Button.cpp | f7e7e3d5d937f43585a39bd416ac149ee5f1be5d | [] | no_license | archfedorov/tryGithub | 17161edfe22112c152f58a5e307139f5b917b378 | 4d05e7b57d0b52163d896c204aa11e39c3f95d72 | refs/heads/master | 2023-01-06T05:13:29.354220 | 2020-11-07T05:16:53 | 2020-11-07T05:16:53 | 240,283,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,591 | cpp | #include "Button.h"
#include "ManagersInstance.h"
#include "ResourceManager.h"
#include "SFML/Graphics/RenderTarget.hpp"
#include "SFML/Graphics/RectangleShape.hpp"
#include "SFML/Window/Event.hpp"
using namespace mlg;
Button::Button() {
setFillColor(sf::Color::White);
text.getTransform();
text.setFont(GET_RESOURCE_MANAGER()->getFont());
text.setFillColor(sf::Color::Black);
text.setOutlineColor(sf::Color::Red);
releaseCallback = nullptr;
pressCallback = nullptr;
}
Button::~Button() {
}
void Button::setLabel(const std::string& label) {
text.setString(label);
}
void Button::draw(sf::RenderTarget& target) {
target.draw(static_cast<sf::RectangleShape>(*this));
text.setPosition(getGlobalBounds().left + getGlobalBounds().width / 2.f, getGlobalBounds().top + getGlobalBounds().height / 2.f);
text.setOrigin(text.getLocalBounds().width / 2.f, text.getLocalBounds().height / 2.f);
target.draw(text);
}
bool Button::handleEvent(const sf::Event& ev) {
if (ev.type == sf::Event::EventType::MouseButtonPressed) {
if (getGlobalBounds().contains(ev.mouseButton.x, ev.mouseButton.y)) {
if (pressCallback) {
pressCallback();
}
return true;
}
}
else if (ev.type == sf::Event::EventType::MouseButtonReleased) {
if (getGlobalBounds().contains(ev.mouseButton.x, ev.mouseButton.y)) {
if (releaseCallback) {
releaseCallback();
}
return true;
}
}
return false;
}
void Button::setPressCallback(const std::function<void(void)>& cb) {
pressCallback = cb;
}
void Button::setReleaseCallback(const std::function<void(void)>& cb) {
releaseCallback = cb;
} | [
"[email protected]"
] | |
390153a39f3a733ebcec6217677546cef0038729 | fcf4e81c20cf12d69c974805a63ccea878069d34 | /3DRenderer/Camera.h | 3051c48076ebf1044f2dbe6ce480a4b0f6ec9302 | [] | no_license | alexlup36/Basic_SoftwareRasterizer | 16ecddcb1e92d9f6db837315c510dd70cc02da4e | 397226fcbedf22137b79c749ce819942265074bf | refs/heads/master | 2020-04-15T17:19:22.932588 | 2019-01-09T13:55:22 | 2019-01-09T13:55:22 | 164,870,246 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | h | #pragma once
#include "Matrix4.h"
class Matrix4;
class Vector3;
class Camera
{
public:
Camera(void);
~Camera(void);
static Matrix4 CreateViewMatrix(const Vector3& position, const Vector3& at, const Vector3& up);
static Matrix4 CreateProjectionMatrix(const float width, const float height, const float dn, const float df);
static Matrix4 CreatePerspectiveFieldOfView(float fov, float aspect, float dn, float df);
};
| [
"[email protected]"
] | |
aa2eb0aed4982845123122015217913ba851aa53 | a7b4e51254988822170e9fe23bea91c5548da52a | /source/QtSensors/QSensorGestureManagerSlots.h | 7b8c6301ab6661f382ce66dd1f305921dcca9e24 | [
"MIT"
] | permissive | orangesocks/Qt5xHb | 0989da07c7e3ddd7c6503a1fe5b691fa1804ce31 | 03aa383d9ae86cdadf7289d846018f8a3382a0e4 | refs/heads/master | 2021-10-25T17:07:37.831633 | 2021-05-07T11:17:30 | 2021-05-07T11:17:30 | 125,614,579 | 0 | 0 | MIT | 2019-04-05T15:56:42 | 2018-03-17T09:30:06 | xBase | UTF-8 | C++ | false | false | 961 | h | /*
Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#ifndef QSENSORGESTUREMANAGERSLOTS_H
#define QSENSORGESTUREMANAGERSLOTS_H
#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>
#if (QT_VERSION >= QT_VERSION_CHECK(5,1,0))
#include <QtSensors/QSensorGestureManager>
#endif
#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#include "qt5xhb_signals.h"
class QSensorGestureManagerSlots: public QObject
{
Q_OBJECT
public:
QSensorGestureManagerSlots( QObject *parent = 0 );
~QSensorGestureManagerSlots();
public slots:
#if (QT_VERSION >= QT_VERSION_CHECK(5,1,0))
void newSensorGestureAvailable();
#endif
};
#endif /* QSENSORGESTUREMANAGERSLOTS_H */
| [
"[email protected]"
] | |
9d7f60e99f57f12891f717128f58deecf6ccfe7e | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtbase/src/plugins/platforms/winrt/qwinrteventdispatcher.h | ecbdde34bd55b2a1eb85fcdd673da5d01e3492c5 | [
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-commercial-license",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"LicenseRef-scancode-qt-commercial-1.1",
"LGPL-3.0-only",
"LicenseRef-scancode-qt-company-exception-lgpl-2.1",
"GPL-1.0-or-later",
"GPL-3.0-only",
"BSD-3-Clause",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-generic-exception"
] | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 2,158 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QWINRTEVENTDISPATCHER_H
#define QWINRTEVENTDISPATCHER_H
#include <QtCore/private/qeventdispatcher_winrt_p.h>
QT_BEGIN_NAMESPACE
class QWinRTEventDispatcher : public QEventDispatcherWinRT
{
Q_OBJECT
public:
explicit QWinRTEventDispatcher(QObject *parent = 0);
protected:
bool hasPendingEvents();
bool sendPostedEvents(QEventLoop::ProcessEventsFlags flags);
};
QT_END_NAMESPACE
#endif // QWINRTEVENTDISPATCHER_H
| [
"[email protected]"
] | |
b14f95191926c34cfaa380df2c0d057a2bd28a65 | 08ebdefa08567276fc19465d540183fe1ac8141e | /WORKSHOP CODE/WishLab/a_LongHairWish/a_LongHairWish.ino | 79956f7102b66dbf83b9fc9caee781592f6e0570 | [] | no_license | Raketa9/CODE | 04cbaa63e34c0b9dfee6181ed7f48556035f1cb2 | 08f6026ac52e280fb0e8ba577d76d88791c621e3 | refs/heads/master | 2021-07-19T05:48:48.240766 | 2017-10-26T05:20:12 | 2017-10-26T05:20:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,641 | ino | /*WISH LAB: Lights that make long heir even more seducive
Software PWM on Attiny45 with 4 output pins and 1 input pin to detect motion
*/
int led[]={
0,1,3,4};
int randomPin[]={
1,2,3,4,5,6,7,8,9,10,11,12,6,5,7,4,8,3,9,2,10,2,3,4,5,6,7,8,9,10,11,12,6,5,7,4,8,3,9,2,10,1,11,12,9,7,5,3,1,2,4,6,8,10,11,12,3,2,5,8,6,5,9,12,3,4,5};
int movementValue;
int delayTime = 3;
int r = 0;
int y = 0;
int x;
int charliePin;
void setup(){
for (int z=0;z<4;z++){
pinMode(led[z],OUTPUT);
} //for z
pinMode(2, INPUT);
digitalWrite(2, HIGH); // no pull-up, use slider pin to GND instead
}
void loop(){
testLoop();
}
// blink through all 12 LEDs:
void testLoop(){
for (int i=1;i<13;i++) {
for (int x=1;x<254;x++) spwm(x,i,1);
for (int x=254;x>1;x--) spwm(x,i,1);
}
}
// software PWM
void spwm(int freq,int pin,int sp){
// call charlieplexing to set correct pin outs:
charliePlexPin(pin);
//on:
digitalWrite(charliePin,HIGH);
delayMicroseconds(sp*freq);
// off:
digitalWrite(charliePin,LOW);
delayMicroseconds(sp*(255-freq));
}
// charlieplexing sets correct pin outs and returns pin to spwm to:
void charliePlexPin(int myLed){
switch(myLed){
// 1
case 1:
pinMode(led[0], OUTPUT);
pinMode(led[1], OUTPUT);
pinMode(led[2], INPUT);
pinMode(led[3], INPUT);
digitalWrite(led[0], LOW);
charliePin = led[1];
break;
// 2
case 2:
pinMode(led[0], OUTPUT);
pinMode(led[1], INPUT);
pinMode(led[2], OUTPUT);
pinMode(led[3], INPUT);
digitalWrite(led[0], LOW);
charliePin = led[2];
break;
// 3
case 3:
pinMode(led[0], OUTPUT);
pinMode(led[1], INPUT);
pinMode(led[2], INPUT);
pinMode(led[3], OUTPUT);
digitalWrite(led[0], LOW);
charliePin = led[3];
break;
// 4
case 4:
pinMode(led[0], OUTPUT);
pinMode(led[1], OUTPUT);
pinMode(led[2], INPUT);
pinMode(led[3], INPUT);
digitalWrite(led[1], LOW);
charliePin = led[0];
break;
// 5
case 5:
pinMode(led[0], OUTPUT);
pinMode(led[1], INPUT);
pinMode(led[2], OUTPUT);
pinMode(led[3], INPUT);
digitalWrite(led[1], LOW);
charliePin = led[2];
break;
// 6
case 6:
pinMode(led[0], INPUT);
pinMode(led[1], OUTPUT);
pinMode(led[2], INPUT);
pinMode(led[3], OUTPUT);
digitalWrite(led[1], LOW);
charliePin = led[3];
break;
// 7
case 7:
pinMode(led[0], OUTPUT);
pinMode(led[1], INPUT);
pinMode(led[2], OUTPUT);
pinMode(led[3], INPUT);
digitalWrite(led[2], LOW);
charliePin = led[0];
break;
// 8
case 8:
pinMode(led[0], INPUT);
pinMode(led[1], OUTPUT);
pinMode(led[2], OUTPUT);
pinMode(led[3], INPUT);
digitalWrite(led[2], LOW);
charliePin = led[1];
break;
// 9
case 9:
pinMode(led[0], INPUT);
pinMode(led[1], INPUT);
pinMode(led[2], OUTPUT);
pinMode(led[3], OUTPUT);
digitalWrite(led[2], LOW);
charliePin = led[3];
break;
// 10
case 10:
pinMode(led[0], OUTPUT);
pinMode(led[1], INPUT);
pinMode(led[2], INPUT);
pinMode(led[3], OUTPUT);
digitalWrite(led[3], LOW);
charliePin = led[0];
break;
// 11
case 11:
pinMode(led[0], INPUT);
pinMode(led[1], OUTPUT);
pinMode(led[2], INPUT);
pinMode(led[3], OUTPUT);
digitalWrite(led[3], LOW);
charliePin = led[1];
break;
// 12
case 12:
pinMode(led[0], INPUT);
pinMode(led[1], INPUT);
pinMode(led[2], OUTPUT);
pinMode(led[3], OUTPUT);
digitalWrite(led[3], LOW);
charliePin = led[2];
break;
}
}
| [
"[email protected]"
] | |
3769cd5a82757d8631ef0b58baea20001fdfd9ba | 786de89be635eb21295070a6a3452f3a7fe6712c | /psddl_hdf2psana/tags/V00-01-30/include/imp.ddl.h | 111537f1f6e1720cfc3dcdf043c276dec58a3196 | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,074 | h | #ifndef PSDDL_HDF2PSANA_IMP_DDL_H
#define PSDDL_HDF2PSANA_IMP_DDL_H 1
// *** Do not edit this file, it is auto-generated ***
#include "psddl_psana/imp.ddl.h"
#include "hdf5pp/Group.h"
#include "hdf5pp/Type.h"
#include "PSEvt/Proxy.h"
namespace psddl_hdf2psana {
namespace Imp {
namespace ns_ConfigV1_v0 {
struct dataset_config {
static hdf5pp::Type native_type();
static hdf5pp::Type stored_type();
dataset_config();
~dataset_config();
uint32_t range;
uint32_t calRange;
uint32_t reset;
uint32_t biasData;
uint32_t calData;
uint32_t biasDacData;
uint32_t calStrobe;
uint32_t numberOfSamples;
uint32_t trigDelay;
uint32_t adcDelay;
};
}
class ConfigV1_v0 : public Psana::Imp::ConfigV1 {
public:
typedef Psana::Imp::ConfigV1 PsanaType;
ConfigV1_v0() {}
ConfigV1_v0(hdf5pp::Group group, hsize_t idx)
: m_group(group), m_idx(idx) {}
ConfigV1_v0(const boost::shared_ptr<Imp::ns_ConfigV1_v0::dataset_config>& ds) : m_ds_config(ds) {}
virtual ~ConfigV1_v0() {}
virtual uint32_t range() const;
virtual uint32_t calRange() const;
virtual uint32_t reset() const;
virtual uint32_t biasData() const;
virtual uint32_t calData() const;
virtual uint32_t biasDacData() const;
virtual uint32_t calStrobe() const;
virtual uint32_t numberOfSamples() const;
virtual uint32_t trigDelay() const;
virtual uint32_t adcDelay() const;
private:
mutable hdf5pp::Group m_group;
hsize_t m_idx;
mutable boost::shared_ptr<Imp::ns_ConfigV1_v0::dataset_config> m_ds_config;
void read_ds_config() const;
};
boost::shared_ptr<PSEvt::Proxy<Psana::Imp::ConfigV1> > make_ConfigV1(int version, hdf5pp::Group group, hsize_t idx);
namespace ns_Sample_v0 {
struct dataset_data {
static hdf5pp::Type native_type();
static hdf5pp::Type stored_type();
dataset_data();
~dataset_data();
uint32_t channels[4];
operator Psana::Imp::Sample() const { return Psana::Imp::Sample(channels); }
};
}
namespace ns_LaneStatus_v0 {
struct dataset_data {
static hdf5pp::Type native_type();
static hdf5pp::Type stored_type();
dataset_data();
~dataset_data();
uint8_t linkErrCount;
uint8_t linkDownCount;
uint8_t cellErrCount;
uint8_t rxCount;
uint8_t locLinked;
uint8_t remLinked;
uint16_t zeros;
uint8_t powersOkay;
operator Psana::Imp::LaneStatus() const { return Psana::Imp::LaneStatus(linkErrCount, linkDownCount, cellErrCount, rxCount, locLinked, remLinked, zeros, powersOkay); }
};
}
namespace ns_ElementV1_v0 {
struct dataset_data {
static hdf5pp::Type native_type();
static hdf5pp::Type stored_type();
dataset_data();
~dataset_data();
uint8_t vc;
uint8_t lane;
uint32_t frameNumber;
uint32_t ticks;
uint32_t fiducials;
uint32_t range;
Imp::ns_LaneStatus_v0::dataset_data laneStatus;
};
}
template <typename Config>
class ElementV1_v0 : public Psana::Imp::ElementV1 {
public:
typedef Psana::Imp::ElementV1 PsanaType;
ElementV1_v0() {}
ElementV1_v0(hdf5pp::Group group, hsize_t idx, const boost::shared_ptr<Config>& cfg)
: m_group(group), m_idx(idx), m_cfg(cfg) {}
virtual ~ElementV1_v0() {}
virtual uint8_t vc() const;
virtual uint8_t lane() const;
virtual uint32_t frameNumber() const;
virtual uint32_t ticks() const;
virtual uint32_t fiducials() const;
virtual uint32_t range() const;
virtual const Psana::Imp::LaneStatus& laneStatus() const;
virtual ndarray<const Psana::Imp::Sample, 1> samples() const;
private:
mutable hdf5pp::Group m_group;
hsize_t m_idx;
boost::shared_ptr<Config> m_cfg;
mutable boost::shared_ptr<Imp::ns_ElementV1_v0::dataset_data> m_ds_data;
void read_ds_data() const;
mutable Psana::Imp::LaneStatus m_ds_storage_data_laneStatus;
mutable ndarray<const Psana::Imp::Sample, 1> m_ds_samples;
void read_ds_samples() const;
};
boost::shared_ptr<PSEvt::Proxy<Psana::Imp::ElementV1> > make_ElementV1(int version, hdf5pp::Group group, hsize_t idx, const boost::shared_ptr<Psana::Imp::ConfigV1>& cfg);
} // namespace Imp
} // namespace psddl_hdf2psana
#endif // PSDDL_HDF2PSANA_IMP_DDL_H
| [
"[email protected]@b967ad99-d558-0410-b138-e0f6c56caec7"
] | [email protected]@b967ad99-d558-0410-b138-e0f6c56caec7 |
c0e4a78eeccf8b57af1151809ef7b6672c31a00b | 3583de683e923eb34db4afa6eecd3bdcbb6a8987 | /Engine/source/T3D/fx/ImprovedParticle/Emitters/graphEmitter.h | ee67d35f2ab50313fa7862f9238331afaf81f5e9 | [] | no_license | lukaspj/IPS-Pro-Development | a50a7f9c8450438a91d78c135a077588bd41749b | 82b668c2b8f3c919adcf2af2f6d3ab592b3185ed | refs/heads/master | 2021-05-27T21:08:30.703208 | 2014-01-06T14:42:21 | 2014-01-06T14:42:21 | 6,166,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,002 | h | // Copyright (C) 2013 Winterleaf Entertainment L,L,C.
//
// THE SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND,
// INCLUDING WITHOUT LIMITATION THE WARRANTIES OF MERCHANT ABILITY, FITNESS
// FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. THE ENTIRE RISK AS TO THE
// QUALITY AND PERFORMANCE OF THE SOFTWARE IS THE RESPONSIBILITY OF LICENSEE.
// SHOULD THE SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, LICENSEE AND NOT LICEN-
// SOR OR ITS SUPPLIERS OR RESELLERS ASSUMES THE ENTIRE COST OF ANY SERVICE AND
// REPAIR. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
// AGREEMENT. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// The use of the WinterLeaf Entertainment LLC Improved Particle System Bundle (IPS Bundle)
// is governed by this license agreement.
//
// RESTRICTIONS
//
// (a) Licensee may not: (i) create any derivative works of IPS Bundle, including but not
// limited to translations, localizations, technology add-ons, or game making software
// other than Games without express permission from Winterleaf Entertainment; (ii) redistribute,
// encumber , sell, rent, lease, sublicense, or otherwise
// transfer rights to IPS Bundle; or (iii) remove or alter any trademark, logo, copyright
// or other proprietary notices, legends, symbols or labels in IPS Bundle; or (iv) use
// the Software to develop or distribute any software that competes with the Software
// without WinterLeaf Entertainment's prior written consent; or (v) use the Software for
// any illegal purpose.
// (b) Licensee may not distribute the IPS Bundle in any manner.
//
// LICENSEGRANT.
// This license allows companies of any size, government entities or individuals to cre-
// ate, sell, rent, lease, or otherwise profit commercially from, games using executables
// created from the source code of IPS Bundle
//
// Please visit http://www.winterleafentertainment.com for more information about the project and latest updates.
#ifndef GRAPH_EMITTER_H_
#define GRAPH_EMITTER_H_
#include "T3D\fx\particleEmitter.h"
#include "math/muParser/muParser.h"
#ifndef _NETCONNECTION_H_
#include "sim/netConnection.h"
#endif
using namespace mu;
class GraphEmitterData : public ParticleEmitterData
{
typedef ParticleEmitterData Parent;
//------- Functions -------
public:
enum EnumProgressMode {
byParticleCount = 0,
byTime,
};
GraphEmitterData();
DECLARE_CONOBJECT(GraphEmitterData);
static void initPersistFields();
void packData(BitStream* stream);
void unpackData(BitStream* stream);
bool onAdd();
virtual ParticleEmitter* createEmitter();
//------- Variables -------
public:
char* xFunc; ///< The expression that calculates the x-coordinate of new particles
char* yFunc; ///< The expression that calculates the y-coordinate of new particles
char* zFunc; ///< The expression that calculates the z-coordinate of new particles
S32 funcMax; ///< The upper boundary for the t-value
S32 funcMin; ///< The lower boundary for the t-value
S32 particleProg; ///< The t-value
EnumProgressMode ProgressMode; ///< Enum that defines how the t-value rises
bool Reverse; ///< If true, the t-value is falling
bool Loop; ///< If true, the t-value will iterate between the upper and the lower boundary
bool mGrounded; ///< If true, particles will be emitted along the terrain
F32 mTimeScale; ///< A coefficient for the t-value
//------- Callbacks -------
// onBoundaryLimit is called when the t-value reaches funcMax or funcMin
DECLARE_CALLBACK( void, onBoundaryLimit, ( GameBase* obj, bool Max) );
};
class GraphEmitter : public ParticleEmitter
{
typedef ParticleEmitter Parent;
//------- Enums -------
enum MaskBits
{
exprEdited = Parent::NextFreeMask << 0,
dynamicMod = Parent::NextFreeMask << 1,
NextFreeMask = Parent::NextFreeMask << 2,
};
public:
//------- Functions -------
public:
GraphEmitter();
DECLARE_CONOBJECT(GraphEmitter);
bool onNewDataBlock( GameBaseData *dptr, bool reload );
void onStaticModified(const char* slotName, const char*newValue);
virtual void onDynamicModified(const char* slotName, const char*newValue);
static void initPersistFields();
U32 packUpdate (NetConnection *conn, U32 mask, BitStream* stream);
void unpackUpdate(NetConnection *conn, BitStream* stream);
protected:
virtual bool addParticle(const Point3F &pos, const Point3F &axis, const Point3F &vel, const Point3F &axisx, const MatrixF& trans);
virtual bool addParticle(const Point3F &pos, const Point3F &axis, const Point3F &vel, const Point3F &axisx, ParticleEmitterNode* node);
//------- Variables -------
public:
char* xFunc; ///< The expression that calculates the x-coordinate of new particles
char* yFunc; ///< The expression that calculates the y-coordinate of new particles
char* zFunc; ///< The expression that calculates the z-coordinate of new particles
S32 funcMax; ///< The upper boundary for the t-value
S32 funcMin; ///< The lower boundary for the t-value
F32 particleProg; ///< The t-value
S32 ProgressMode; ///< Enum that defines how the t-value rises
bool Reverse; ///< If true, the t-value is falling
bool Loop; ///< If true, the t-value will iterate between the upper and the lower boundary
bool mGrounded; ///> If true, the particles will be emitted along the terrain
F32 timeScale; ///< A coefficient for the t-value
Parser xfuncParser; ///< The parser for xFunc
Parser yfuncParser; ///< The parser for yFunc
Parser zfuncParser; ///< The parser for zFunc
struct muVar{ ///< A muParser variable struct
F32 value;
char token;
};
muVar xVariables[100]; ///< All the variables for the xfuncParser
muVar yVariables[100]; ///< All the variables for the yfuncParser
muVar zVariables[100]; ///< All the variables for the zfuncParser
F32 xMxDist; ///< The maximal x-distance the xFunc can hit
F32 xMnDist; ///< The maximal y-distance the xFunc can hit
F32 yMxDist; ///< The maximal z-distance the xFunc can hit
F32 yMnDist; ///< The minimum x-distance the xFunc can hit
F32 zMxDist; ///< The minimum y-distance the xFunc can hit
F32 zMnDist; ///< The minimum z-distance the xFunc can hit
private:
bool cb_Max; ///< Internal boolean to tell wether the boundary was hit max or low
U32 lastErrorTime;
public:
//------- MuParser custom functions -------
static F32 mu_RandomInteger() { return gRandGen.randI(); };
static F32 mu_SeededRandomInteger(F32 seed) { gRandGen.setSeed(seed); return gRandGen.randI(); };
static F32 mu_RandomFloat() { return gRandGen.randF(); };
static F32 mu_SeededRandomFloat(F32 seed) { gRandGen.setSeed(seed); return gRandGen.randF(); };
static F32 mu_ModulusOprt(F32 val, F32 mod) { return F32( U32(val) % U32(mod) ); };
//------- Callbacks -------
public:
void onBoundaryLimit(bool Max, ParticleEmitterNode* node); ///< onBoundaryLimit callback handler
private:
virtual GraphEmitterData* getDataBlock() { return static_cast<GraphEmitterData*>(Parent::getDataBlock()); }
};
//*****************************************************************************
// GraphEmitterNetEvemt
//*****************************************************************************
// A simple NetEvent to transmit a string over the network.
// This is based on the code in netTest.cc
class CallbackEvent : public NetEvent
{
typedef NetEvent Parent;
bool Max;
S32 mNode;
public:
CallbackEvent(S32 node = -1, bool max = false);
virtual ~CallbackEvent();
virtual void pack (NetConnection *conn, BitStream *bstream);
virtual void write (NetConnection *conn, BitStream *bstream) { pack(conn, bstream); };
virtual void unpack (NetConnection *conn, BitStream *bstream);
virtual void process(NetConnection *conn);
DECLARE_CONOBJECT(CallbackEvent);
};
#endif // GRAPH_EMITTER_H_
| [
"[email protected]"
] | |
944e884b626b0c7898087ee34509026b8cd39b44 | 47fc025917d53c0a05dcf2dd6f03685f31c28d7e | /CPP-Pool/Rush2/src/Factory/PapaXmasConveyorBelt.hpp | d3ecffef9d21e39ea84d4b8a9874660edd9bafff | [] | no_license | PilowEpi/Tek2Project | 05a266874c1767c6b26fd1ccfead8f525df64f99 | 781a01632d0d18ebdd9e7b56bac25c45aa4f6b29 | refs/heads/main | 2023-08-11T19:32:40.942625 | 2021-09-11T13:28:09 | 2021-09-11T13:28:09 | 405,377,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | hpp | /*
** EPITECH PROJECT, 2021
** Rush2
** File description:
** PapaXmasConveyorBelt
*/
#ifndef __PAPAXMASCONVEYORBELT__
#define __PAPAXMASCONVEYORBELT__
#include "Object.hpp"
#include "IConveyorBelt.hpp"
class PapaXmasConveyorBelt : public IConveyorBelt
{
public:
PapaXmasConveyorBelt();
~PapaXmasConveyorBelt();
bool IN();
bool OUT();
bool insert(Object *obj);
Object *remove();
bool isEmpty();
protected:
Object *obj;
};
#endif | [
"[email protected]"
] | |
4213c65860e79c73ffca52a45b8215523c68c6a1 | e763b855be527d69fb2e824dfb693d09e59cdacb | /aws-cpp-sdk-appstream/source/AppStreamEndpoint.cpp | c0fdfbeb2ce42c5361554086e5d447b50ed44e0c | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | 34234344543255455465/aws-sdk-cpp | 47de2d7bde504273a43c99188b544e497f743850 | 1d04ff6389a0ca24361523c58671ad0b2cde56f5 | refs/heads/master | 2023-06-10T16:15:54.618966 | 2018-05-07T23:32:08 | 2018-05-07T23:32:08 | 132,632,360 | 1 | 0 | Apache-2.0 | 2023-06-01T23:20:47 | 2018-05-08T15:56:35 | C++ | UTF-8 | C++ | false | false | 1,426 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/appstream/AppStreamEndpoint.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/HashingUtils.h>
using namespace Aws;
using namespace Aws::AppStream;
namespace Aws
{
namespace AppStream
{
namespace AppStreamEndpoint
{
static const int CN_REGION_HASH = Aws::Utils::HashingUtils::HashString("cn-north-1");
Aws::String ForRegion(const Aws::String& regionName, bool useDualStack)
{
auto hash = Aws::Utils::HashingUtils::HashString(regionName.c_str());
Aws::StringStream ss;
ss << "appstream2" << ".";
if(useDualStack)
{
ss << "dualstack.";
}
ss << regionName << ".amazonaws.com";
if(hash == CN_REGION_HASH)
{
ss << ".cn";
}
return ss.str();
}
} // namespace AppStreamEndpoint
} // namespace AppStream
} // namespace Aws
| [
"[email protected]"
] | |
a10be9247007fb30c069afdd140bf7908c99d060 | e359db0e752a11c5d677e3a82574065831bab447 | /app/demo/touchgfx_demo2014_480x272/gui/include/gui/list_navigation_screen/TrackSelector.hpp | aeaa8dc7e9a0cd35e0a483056c56a51e59a02dc3 | [] | no_license | chichtlm/TouchGFX | 694936495ba49b4baba4fb56fd1165f424518c94 | 09cfdf466ae98fa61f54d55548248134a007871f | refs/heads/master | 2020-05-10T00:07:11.813953 | 2016-12-14T06:55:22 | 2016-12-14T06:55:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,377 | hpp | /******************************************************************************
*
* @brief This file is part of the TouchGFX 4.5.0 evaluation distribution.
*
* @author Draupner Graphics A/S <http://www.touchgfx.com>
*
******************************************************************************
*
* @section Copyright
*
* This file is free software and is provided for example purposes. You may
* use, copy, and modify within the terms and conditions of the license
* agreement.
*
* This is licensed software for evaluation use, any use must strictly comply
* with the evaluation license agreement provided with delivery of the
* TouchGFX software.
*
* The evaluation license agreement can be seen on www.touchgfx.com
*
* @section Disclaimer
*
* DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Draupner Graphics A/S has
* no obligation to support this software. Draupner Graphics A/S is providing
* the software "AS IS", with no express or implied warranties of any kind,
* including, but not limited to, any implied warranties of merchantability
* or fitness for any particular purpose or warranties against infringement
* of any proprietary rights of a third party.
*
* Draupner Graphics A/S can not be held liable for any consequential,
* incidental, or special damages, or any other relief, or for any claim by
* any third party, arising from your use of this software.
*
*****************************************************************************/
#ifndef TRACK_SELECTOR_HPP_
#define TRACK_SELECTOR_HPP_
#include <touchgfx/containers/Container.hpp>
#include <touchgfx/widgets/Image.hpp>
#include <touchgfx/widgets/Button.hpp>
#include <touchgfx/widgets/ToggleButton.hpp>
#include <touchgfx/containers/ListLayout.hpp>
#include <touchgfx/containers/ScrollableContainer.hpp>
#include <touchgfx/widgets/TextArea.hpp>
#include <BitmapDatabase.hpp>
#include <gui/list_navigation_screen/Album.hpp>
#include <gui/list_navigation_screen/AlbumManager.hpp>
#include <gui/list_navigation_screen/TrackRow.hpp>
using namespace touchgfx;
class TrackSelector : public Container
{
public:
TrackSelector(AlbumManager& albumManager_);
virtual ~TrackSelector();
void setAlbumAndTrackSelectedCallback(GenericCallback< const Album*, const uint8_t >& callback)
{
albumAndTrackSelectedCallback = &callback;
}
void setTrackSelectionCancelledCallback(GenericCallback< >& callback)
{
trackSelectionCancelledCallback = &callback;
}
void setAlbum(Album* album_);
private:
AlbumManager& albumManager;
Album* album;
Image background;
Image albumCover;
Image headlineBackground;
Button headlineButton;
TextArea albumName;
TextArea albumArtist;
Button playButton;
static const uint8_t MAX_NUMBER_OF_TRACKS = 14;
TrackRow trackRows[MAX_NUMBER_OF_TRACKS];
ScrollableContainer trackScrollableArea;
ListLayout trackList;
GenericCallback< const Album*, const uint8_t >* albumAndTrackSelectedCallback;
GenericCallback< >* trackSelectionCancelledCallback;
Callback<TrackSelector, const AbstractButton&> onButtonPressed;
Callback<TrackSelector, const TrackRow&> onTrackRowSelected;
void buttonPressedhandler(const AbstractButton& button);
void trackRowSelectedHandler(const TrackRow& track);
};
#endif /* TRACK_SELECTOR_HPP_ */
| [
"[email protected]"
] | |
894be1081eec47d2af0a3508be90e9d2c94dd52f | 159177fa9900172caf5fd1c00e9274c1870611d7 | /POJ/1050.To the Max.cpp | d6d8245d0510ea34fe9250d719d4394232ca3441 | [] | no_license | Wbrta/ACM | 436cd37681b599e4631af732ca1ea56bd4c390eb | bf0be17b5691cadf0413359897d86d191b6694ee | refs/heads/master | 2020-05-29T15:12:18.066081 | 2017-08-09T07:11:27 | 2017-08-09T07:11:27 | 67,347,267 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | cpp | #include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 100 + 5;
int n, d[maxn];
int num[maxn][maxn];
inline int Max(int a, int b){
return (a >= b ? a : b);
}
int fun(){
int sum = 0, tmp = 0;
for(int i = 0; i < n; ++i){
tmp += d[i];
if(tmp > sum) sum = tmp;
if(tmp < 0) tmp = 0;
}
return sum;
}
int main()
{
while(~scanf("%d", &n)){
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
scanf("%d", &num[i][j]);
}
}
int ans = 0;
for(int i = 0; i < n; ++i){
memset(d, 0, sizeof(d));
for(int j = i; j < n; ++j){
for(int k = 0; k < n; ++k){
d[k] += num[j][k];
}
ans = Max(ans, fun());
}
}
printf("%d\n", ans);
}
return 0;
}
| [
"[email protected]"
] | |
fabd0794ef09095076cb8d135cf45c59a4500066 | 7e68c3e0e86d1a1327026d189a613297b769c411 | /Math/Mandelbrot/BigRealTransformation.h | 3e0cff34f62d8be410bd32a1c8a0e9df51fbe22b | [] | no_license | staticlibs/Big-Numbers | bc08092e36c7c640dcf43d863448cd066abaebed | adbfa38cc2e3b8ef706a3ac8bbd3e398f741baf3 | refs/heads/master | 2023-03-16T20:25:08.699789 | 2020-12-20T20:50:25 | 2020-12-20T20:50:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,451 | h | #pragma once
#include <Math/Rectangle2DTransformation.h>
#include "BigRealInterval.h"
#define AUTOPRECISION 0
class BigRealSize2D : public SizeTemplate<BigReal, 2> {
private:
public:
template<typename X, typename Y> BigRealSize2D(const X &cx, const Y &cy, DigitPool *digitPool=nullptr)
: SizeTemplate(digitPool?BigReal(cx,digitPool):cx)
,digitPool?BigReal(cy,digitPool),digitPool:cx.getDigitPool()))
{
}
inline BigRealSize2D(const BigRealSize2D &src, DigitPool *digitPool=nullptr)
: SizeTemplate(BigReal(src[0],digitPool?digitPool:src.getDigitPool())
,BigReal(src[1],digitPool?digitPool:src.getDigitPool()))
{
}
inline DigitPool *getDigitPool() const {
return cx().getDigitPool();
}
template<typename T> BigRealSize2D &operator=(const FixedDimensionVector<T, 2> &src) {
DigitPool *dp = getDigitPool();
cx() = BigReal(src.cx(),dp);
cy() = BigReal(src.cy(),dp);
return *this;
}
#if defined(__ATLTYPES_H__)
inline BigRealSize2D(const CSize &s, DigitPool *digitPool=nullptr)
: Size2DTemplate(BigReal(s.cx,digitPool),BigReal(s.cy,digitPool))
{
}
inline BigRealSize2D &operator=(const CSize &s) {
cx() = s.cx; cy() = s.cy;
return *this;
}
inline explicit operator CSize() const {
return CSize((int)round(cx()), (int)round(cy()));
}
#endif // __ATLTYPES_H__
};
class BigRealPoint2D : public Point2DTemplate<BigReal> {
public:
inline BigRealPoint2D(DigitPool *digitPool=nullptr)
: Point2DTemplate(BigReal(0,digitPool), BigReal(0,digitPool))
{
}
inline BigRealPoint2D(const BigReal &x, const BigReal &y, DigitPool *digitPool=nullptr)
: Point2DTemplate(BigReal(x,digitPool?digitPool:x.getDigitPool())
,BigReal(y,digitPool?digitPool:x.getDigitPool()))
{
}
inline BigRealPoint2D(const BigRealPoint2D &src, DigitPool *digitPool=nullptr)
: Point2DTemplate(BigReal(src.x(),digitPool?digitPool:src.getDigitPool())
,BigReal(src.y(),digitPool?digitPool:src.getDigitPool()))
{
}
inline DigitPool *getDigitPool() const {
return x().getDigitPool();
}
template<typename T> BigRealSize2D &operator=(const FixedDimensionVector<T, 2> &src) {
DigitPool *dp = getDigitPool();
cx() = BigReal(src.cx(),dp);
cy() = BigReal(src.cy(),dp);
return *this;
}
template<typename T> inline explicit operator Point2DTemplate<T>() const {
return Point2DTemplate<T>((T)cx(), (T)cy());
}
#if defined(__ATLTYPES_H__)
inline BigRealPoint2D(const CPoint &p, DigitPool *digitPool=nullptr)
: Point2DTemplate(BigReal(p.x,digitPool),BigReal(p.y,digitPool))
{
}
inline BigRealPoint2D &operator=(const CPoint &p) {
x() = p.x; y() = p.y;
return *this;
}
inline explicit operator CPoint() const {
return CPoint((int)round(x()), (int)round(y()));
}
#endif // __ATLTYPES_H__
};
class BigRealIntervalTransformation {
private:
const IntervalScale m_scaleType;
BigRealInterval m_fromInterval, m_toInterval;
BigReal m_a, m_b;
UINT m_precision, m_digits;
protected:
virtual BigReal translate( const BigReal &x) const = 0;
virtual BigReal inverseTranslate(const BigReal &x) const = 0;
void computeTransformation();
void checkFromInterval(const TCHAR *method, const BigRealInterval &interval);
public:
BigRealIntervalTransformation(const BigRealInterval &fromInterval, const BigRealInterval &toInterval, IntervalScale scaleType, UINT precision=AUTOPRECISION, DigitPool *digitPool = nullptr);
// Set number of decimal digits in calculations
// Specify AUTOPRECISION to get 8 extra decimal digits whatever from- and toInterval are
inline IntervalScale getScaleType() const {
return m_scaleType;
}
inline bool isLinear() const {
return getScaleType() == LINEAR;
}
UINT setPrecision(UINT precsion);
inline UINT getPrecision() const {
return m_precision;
}
inline UINT getDigits() const {
return m_digits;
}
inline DigitPool *getDigitPool() const {
return m_fromInterval.getDigitPool();
}
static BigRealInterval getDefaultInterval(IntervalScale scale, DigitPool *digitPool=nullptr);
inline const BigRealInterval &getFromInterval() const {
return m_fromInterval;
}
inline const BigRealInterval &getToInterval() const {
return m_toInterval;
}
virtual const BigRealInterval &setFromInterval(const BigRealInterval &interval);
virtual const BigRealInterval &setToInterval(const BigRealInterval &interval);
inline BigReal forwardTransform(const BigReal &x) const {
DigitPool *dp = getDigitPool();
return rProd(m_a,translate(x),m_digits, getDigitPool()) + m_b;
}
inline BigReal backwardTransform(const BigReal &x) const {
DigitPool *dp = getDigitPool();
return m_a.isZero() ? BigReal(getFromInterval().getFrom(),dp) : inverseTranslate(rQuot(dif(x,m_b,dp->_0(),dp),m_a,m_digits,dp));
}
inline BigRealInterval forwardTransform(const BigRealInterval &interval) const {
return BigRealInterval(forwardTransform(interval.getFrom()),forwardTransform(interval.getTo()));
}
inline BigRealInterval backwardTransform(const BigRealInterval &interval) const {
return BigRealInterval(backwardTransform(interval.getFrom()),backwardTransform(interval.getTo()));
}
// Returns new fromInterval.
const BigRealInterval &zoom(const BigReal &x, const BigReal &factor, bool xInToInterval=true);
virtual BigRealIntervalTransformation *clone(DigitPool *digitPool=nullptr) const = 0;
};
class BigRealLinearTransformation : public BigRealIntervalTransformation {
protected:
BigReal translate(const BigReal &x) const override {
return BigReal(x, getDigitPool());
}
BigReal inverseTranslate(const BigReal &x) const override {
return BigReal(x, getDigitPool());
}
public:
BigRealLinearTransformation(const BigRealInterval &fromInterval, const BigRealInterval &toInterval, UINT precision=AUTOPRECISION, DigitPool *digitPool=nullptr)
: BigRealIntervalTransformation(fromInterval, toInterval, LINEAR, precision, digitPool) {
computeTransformation();
}
BigRealIntervalTransformation *clone(DigitPool *digitPool=nullptr) const override {
return new BigRealLinearTransformation(getFromInterval(),getToInterval(),getPrecision(),digitPool);
}
};
class BigRealRectangle2D : public Rectangle2DTemplate<BigRealPoint2D, BigRealSize2D, BigReal> {
public:
inline BigRealRectangle2D(DigitPool *digitPool = nullptr)
: Rectangle2DTemplate(BigReal(0,digitPool), BigReal(0,digitPool), BigReal(0, digitPool), BigReal(0, digitPool))
{
}
inline BigRealRectangle2D(const BigReal &x, const BigReal &y, const BigReal &w, const BigReal &h, DigitPool *digitPool = nullptr)
: Rectangle2DTemplate(BigReal(x,digitPool?digitPool:x.getDigitPool())
,BigReal(y,digitPool?digitPool:x.getDigitPool())
,BigReal(w,digitPool?digitPool:x.getDigitPool())
,BigReal(h,digitPool?digitPool:x.getDigitPool()))
{
}
inline BigRealRectangle2D(const BigRealPoint2D &topLeft, const BigRealPoint2D &bottomRight, DigitPool *digitPool = nullptr)
: Rectangle2DTemplate(BigReal(topLeft.x() ,digitPool?digitPool:topLeft.getDigitPool())
,BigReal(topLeft.y() ,digitPool?digitPool:topLeft.getDigitPool())
,dif(bottomRight.x(),topLeft.x(),digitPool?digitPool:topLeft.getDigitPool())
,dif(bottomRight.y(),topLeft.y(),digitPool?digitPool:topLeft.getDigitPool()))
{
}
inline BigRealRectangle2D(const BigRealPoint2D &p, const BigRealSize2D &size, DigitPool *digitPool = nullptr)
: Rectangle2DTemplate(BigRealPoint2D(p ,digitPool)
,BigRealSize2D( size,digitPool)
)
{
}
inline DigitPool *getDigitPool() const {
return ((BigRealPoint2D&)p0()).getDigitPool();
}
template<typename T> BigRealRectangle2D &operator=(const T &r) {
DigitPool *dp = getDigitPool();
*this = BigRealRectangle2D(BigReal(r.getX() ,dp)
,BigReal(r.getY() ,dp)
,BigReal(r.getWidth() ,dp)
,BigReal(r.getHeight(),dp));
return *this;
}
inline operator RealRectangle2D() const {
return RealRectangle2D((Real)getX(), (Real)getY(), (Real)getWidth(), (Real)getHeight());
}
inline size_t getNeededDecimalDigits(size_t digits) const {
const size_t digitsX = ((BigRealInterval&)getXInterval()).getNeededDecimalDigits(digits);
const size_t digitsY = ((BigRealInterval&)getYInterval()).getNeededDecimalDigits(digits);
return max(digitsX, digitsY);
}
};
class BigRealRectangleTransformation {
private:
DigitPool *m_digitPool;
BigRealIntervalTransformation *m_xtransform, *m_ytransform;
BigRealIntervalTransformation *allocateTransformation(const BigRealInterval &from, const BigRealInterval &to, IntervalScale scale) const;
void cleanup();
void computeTransformation(const BigRealRectangle2D &from, const BigRealRectangle2D &to, IntervalScale xScale, IntervalScale yScale);
BigRealRectangleTransformation(const BigRealIntervalTransformation &tx, const BigRealIntervalTransformation &ty, DigitPool *digitPool = nullptr);
static BigRealRectangle2D getDefaultFromRectangle(IntervalScale xScale, IntervalScale yScale, DigitPool *digitPool=nullptr);
static inline BigRealRectangle2D getDefaultToRectangle(DigitPool *digitPool=nullptr) {
BigRealRectangle2D result(digitPool);
result = RealRectangle2D(0, 100, 100, -100);
return result;
}
public:
inline BigRealRectangleTransformation(IntervalScale xScale = LINEAR, IntervalScale yScale = LINEAR, DigitPool *digitPool=nullptr)
: m_digitPool(digitPool?digitPool:DEFAULT_DIGITPOOL)
{
m_xtransform = m_ytransform = nullptr;
computeTransformation(getDefaultFromRectangle(xScale,yScale,getDigitPool()), getDefaultToRectangle(getDigitPool()), xScale, yScale);
}
inline BigRealRectangleTransformation(const BigRealRectangle2D &from, const BigRealRectangle2D &to, IntervalScale xScale = LINEAR, IntervalScale yScale = LINEAR, DigitPool *digitPool=nullptr)
: m_digitPool(digitPool?digitPool:from.getDigitPool())
{
m_xtransform = m_ytransform = nullptr;
computeTransformation(from, to, xScale, yScale);
}
inline BigRealRectangleTransformation(const BigRealRectangleTransformation &src, DigitPool *digitPool=nullptr)
: m_digitPool(digitPool?digitPool:src.getDigitPool())
{
m_xtransform = src.getXTransformation().clone(getDigitPool());
m_ytransform = src.getYTransformation().clone(getDigitPool());
}
inline BigRealRectangleTransformation &operator=(const BigRealRectangleTransformation &src) {
cleanup();
m_xtransform = src.getXTransformation().clone(getDigitPool());
m_ytransform = src.getYTransformation().clone(getDigitPool());
return *this;
}
virtual ~BigRealRectangleTransformation() {
cleanup();
}
inline DigitPool *getDigitPool() const {
return m_digitPool;
}
inline const BigRealIntervalTransformation &getXTransformation() const {
return *m_xtransform;
}
inline const BigRealIntervalTransformation &getYTransformation() const {
return *m_ytransform;
}
inline void setFromRectangle(const BigRealRectangle2D &rect) {
computeTransformation(rect,getToRectangle(),getXTransformation().getScaleType(),getYTransformation().getScaleType());
}
inline void setToRectangle(const BigRealRectangle2D &rect) {
computeTransformation(getFromRectangle(),rect,getXTransformation().getScaleType(),getYTransformation().getScaleType());
}
BigRealRectangle2D getFromRectangle() const;
BigRealRectangle2D getToRectangle() const;
inline BigRealPoint2D forwardTransform(const Point2DTemplate<BigReal> &p) const {
return forwardTransform(p[0], p[1]);
}
inline BigRealPoint2D backwardTransform(const Point2DTemplate<BigReal> &p) const {
return backwardTransform(p[0], p[1]);
}
inline BigRealPoint2D forwardTransform(const BigReal &x, const BigReal &y) const {
return BigRealPoint2D(getXTransformation().forwardTransform(x),getYTransformation().forwardTransform(y));
}
inline BigRealPoint2D backwardTransform(const BigReal &x, const BigReal &y) const {
return BigRealPoint2D(getXTransformation().backwardTransform(x),getYTransformation().backwardTransform(y));
}
inline BigRealRectangle2D forwardTransform(const BigRealRectangle2D &rect) const {
return BigRealRectangle2D(forwardTransform(rect.LT()), forwardTransform(rect.RB()));
}
inline BigRealRectangle2D backwardTransform( const BigRealRectangle2D &rect) const {
return BigRealRectangle2D(backwardTransform(rect.LT()), backwardTransform(rect.RB()));
}
void setScale(IntervalScale newScale, int flags);
// Returns new fromRectangle.
BigRealRectangle2D zoom(const BigRealPoint2D &p, const BigReal &factor, int flags = X_AXIS | Y_AXIS, bool pInToRectangle=true);
// returns true if transformation is changed
bool adjustAspectRatio();
static inline BigRealRectangleTransformation getId(DigitPool *digitPool=nullptr) {
if(digitPool == nullptr) digitPool = DEFAULT_DIGITPOOL;
return BigRealRectangleTransformation(BigRealRectangle2D(0,0,1,1,digitPool)
,BigRealRectangle2D(0,0,1,1,digitPool));
}
};
| [
"[email protected]"
] | |
00255bb407edeb7f390858a3a6a557767281482b | 8d15b5f0573899d8223bd78cbf0c6007efe7f739 | /vibrato/vibrato/Source/PluginProcessor.cpp | ec27870843b8b1af924ccc5c73631773df93b029 | [] | no_license | jiemojiemo/Audio-Effects-Theory-Implementation-and-Application-Code | c46461e4849969fe127b9e331ca8926ebf1ebfbc | ed7acb536e4ba1e4f590c853573c8cbe3e950675 | refs/heads/master | 2020-12-18T21:43:38.732738 | 2020-01-29T03:55:55 | 2020-01-29T03:55:55 | 235,528,049 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,661 | cpp | /*
==============================================================================
This file was auto-generated!
It contains the basic framework code for a JUCE plugin processor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
#include <iostream>
using namespace std;
#ifndef M_PI
#define M_PI 3.14159
#endif
//==============================================================================
VibratoAudioProcessor::VibratoAudioProcessor()
#ifndef JucePlugin_PreferredChannelConfigurations
: AudioProcessor (BusesProperties()
#if ! JucePlugin_IsMidiEffect
#if ! JucePlugin_IsSynth
.withInput ("Input", AudioChannelSet::stereo(), true)
#endif
.withOutput ("Output", AudioChannelSet::stereo(), true)
#endif
)
#endif
{
}
VibratoAudioProcessor::~VibratoAudioProcessor()
{
}
//==============================================================================
const String VibratoAudioProcessor::getName() const
{
return JucePlugin_Name;
}
bool VibratoAudioProcessor::acceptsMidi() const
{
#if JucePlugin_WantsMidiInput
return true;
#else
return false;
#endif
}
bool VibratoAudioProcessor::producesMidi() const
{
#if JucePlugin_ProducesMidiOutput
return true;
#else
return false;
#endif
}
bool VibratoAudioProcessor::isMidiEffect() const
{
#if JucePlugin_IsMidiEffect
return true;
#else
return false;
#endif
}
double VibratoAudioProcessor::getTailLengthSeconds() const
{
return 0.0;
}
int VibratoAudioProcessor::getNumPrograms()
{
return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs,
// so this should be at least 1, even if you're not really implementing programs.
}
int VibratoAudioProcessor::getCurrentProgram()
{
return 0;
}
void VibratoAudioProcessor::setCurrentProgram (int index)
{
}
const String VibratoAudioProcessor::getProgramName (int index)
{
return {};
}
void VibratoAudioProcessor::changeProgramName (int index, const String& newName)
{
}
//==============================================================================
void VibratoAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)
{
// Use this method as the place to do any pre-playback
// initialisation that you need..
const float kMaxSweepWidth = 0.05f;
delayBufferLength_ = (int)(kMaxSweepWidth*sampleRate) + 3;
delayBuffer_.setSize(2, delayBufferLength_);
delayBuffer_.clear();
lfopahse_ = 0.0f;
inverseSampleRate_ = 1.0/sampleRate;
}
void VibratoAudioProcessor::releaseResources()
{
// When playback stops, you can use this as an opportunity to free up any
// spare memory, etc.
}
#ifndef JucePlugin_PreferredChannelConfigurations
bool VibratoAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
{
#if JucePlugin_IsMidiEffect
ignoreUnused (layouts);
return true;
#else
// This is the place where you check if the layout is supported.
// In this template code we only support mono or stereo.
if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono()
&& layouts.getMainOutputChannelSet() != AudioChannelSet::stereo())
return false;
// This checks if the input layout matches the output layout
#if ! JucePlugin_IsSynth
if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
return false;
#endif
return true;
#endif
}
#endif
void VibratoAudioProcessor::processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiMessages)
{
ScopedNoDenormals noDenormals;
auto totalNumInputChannels = getTotalNumInputChannels();
auto totalNumOutputChannels = getTotalNumOutputChannels();
auto numSamples = buffer.getNumSamples();
// In case we have more outputs than inputs, this code clears any output
// channels that didn't contain input data, (because these aren't
// guaranteed to be empty - they may contain garbage).
// This is here to avoid people getting screaming feedback
// when they first compile a plugin, but obviously you don't need to keep
// this code if your algorithm always overwrites all the output channels.
for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
buffer.clear (i, 0, buffer.getNumSamples());
// This is the place where you'd normally do the guts of your plugin's
// audio processing...
// Make sure to reset the state if your inner loop is processing
// the samples and the outer loop is handling the channels.
// Alternatively, you can process the samples with the channels
// interleaved by keeping the same state.
int dpw = 0;
float dpr = 0.0f;
float currentDelay = 0.0f;
float ph = 0.0;
auto lfo = [](float phase){ return 0.5f + 0.5f*sinf(2.0 * M_PI * phase); };
for (int channel = 0; channel < totalNumInputChannels; ++channel)
{
auto* channelData = buffer.getWritePointer (channel);
auto* delayData = delayBuffer_.getWritePointer(channel);
dpw = delayWritePosition_;
ph = lfopahse_;
for(int i = 0; i < numSamples; ++i)
{
const float in = channelData[i];
float interpolatedSample = 0.0f;
currentDelay = sweepWidth_ * lfo(ph);
dpr = fmodf((float)dpw - (float)(currentDelay * getSampleRate()) + (float)delayBufferLength_ - 3.0,
(float)delayBufferLength_);
float fraction = dpr - floorf(dpr);
int previousSample = (int)floorf(dpr);
int nextSample = (previousSample+1)%delayBufferLength_;
interpolatedSample = fraction * delayData[nextSample] + (1.0f-fraction)*delayData[previousSample];
delayData[dpw] = in;
if(++dpw >= delayBufferLength_)
dpw = 0;
channelData[i] = interpolatedSample;
ph += frequency_ * inverseSampleRate_;
if(ph >= 1.0f)
ph -= 1.0f;
}
}
delayWritePosition_ = dpw;
lfopahse_ = ph;
}
//==============================================================================
bool VibratoAudioProcessor::hasEditor() const
{
return true; // (change this to false if you choose to not supply an editor)
}
AudioProcessorEditor* VibratoAudioProcessor::createEditor()
{
return new VibratoAudioProcessorEditor (*this);
}
//==============================================================================
void VibratoAudioProcessor::getStateInformation (MemoryBlock& destData)
{
// You should use this method to store your parameters in the memory block.
// You could do that either as raw data, or use the XML or ValueTree classes
// as intermediaries to make it easy to save and load complex data.
}
void VibratoAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
{
// You should use this method to restore your parameters from this memory block,
// whose contents will have been created by the getStateInformation() call.
}
void VibratoAudioProcessor::setSweepWidth(float SweepWidth) {
sweepWidth_ = SweepWidth;
}
void VibratoAudioProcessor::setFrequency(float Frequency) {
frequency_ = Frequency;
}
//==============================================================================
// This creates new instances of the plugin..
AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new VibratoAudioProcessor();
}
| [
"[email protected]"
] | |
8b1e771d6b4b94ea20c09865884f35e383ed421b | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /base/rand_util_fuchsia.cc | 743c709898a2fecfd31e7f9790157564338c9304 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 360 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/rand_util.h"
#include <zircon/syscalls.h>
namespace base {
void RandBytes(void* output, size_t output_length) {
zx_cprng_draw(output, output_length);
}
} // namespace base
| [
"[email protected]"
] | |
dce078edd32c481728cee48ed082fb1a5e9cf4d3 | de64bd4c9ddf4f852cfa073253d6754e737db7ae | /c++-srcs/techmap/lutmap/include/AreaCover_MCT2.h | 349512661d11583266460689d5413b3406895a58 | [] | no_license | yusuke-matsunaga/magus | 8424537aea8b12f7ff50e358f05dae150abfac73 | 0855cfc95ea76f330830034f8c222eb562c09730 | refs/heads/master | 2023-05-26T14:56:11.347118 | 2023-05-26T00:23:03 | 2023-05-26T00:23:03 | 38,558,020 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,254 | h | #ifndef AREACOVER_MCT2_H
#define AREACOVER_MCT2_H
/// @file AreaCover_MCT1.h
/// @brief AreaCover_MCT1 のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2016 Yusuke Matsunaga
/// All rights reserved.
#include "mct2_nsdef.h"
#include "DagCover.h"
BEGIN_NAMESPACE_LUTMAP
class Cut;
END_NAMESPACE_LUTMAP
BEGIN_NAMESPACE_LUTMAP_MCT2
//////////////////////////////////////////////////////////////////////
/// @brief 面積モードの DAG covering のヒューリスティック
//////////////////////////////////////////////////////////////////////
class AreaCover_MCT2 :
public DagCover
{
public:
//////////////////////////////////////////////////////////////////////
// コンストラクタ/デストラクタ
//////////////////////////////////////////////////////////////////////
/// @brief コンストラクタ
/// @param[in] fanout_mode ファンアウトモード
/// @param[in] count 試行回数
/// @param[in] verbose verbose フラグ
AreaCover_MCT2(bool fanout_mode,
int count,
bool verbose);
/// @brief デストラクタ
~AreaCover_MCT2();
public:
//////////////////////////////////////////////////////////////////////
// 外部インターフェイス
//////////////////////////////////////////////////////////////////////
/// @brief best cut の記録を行う.
/// @param[in] sbjgraph サブジェクトグラフ
/// @param[in] cut_holder 各ノードのカットを保持するオブジェクト
/// @param[in] count 試行回数
/// @param[out] maprec マッピング結果を記録するオブジェクト
void
record_cuts(const SbjGraph& sbjgraph,
const CutHolder& cut_holder,
MapRecord& maprec) override;
private:
//////////////////////////////////////////////////////////////////////
// 内部で用いられる関数
//////////////////////////////////////////////////////////////////////
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// 試行回数
int mCount;
// verbose フラグ
bool mVerbose;
};
END_NAMESPACE_LUTMAP_MCT2
#endif // AREACOVER_MCT2_H
| [
"[email protected]"
] | |
8c7d23adbfed0cb089f21528e4452a3d29fe24f4 | 2c17be46683e4abaeb7337cbb5f9b9592990d48a | /LeetCode/Cpp/[461] Hamming Distance.cpp | b883518558bb6272ef5c95a5abce0d54847544b2 | [] | no_license | syahn/Problem-solving | a99a8d4ee5c82abf51c8e647012d0183d9eb6930 | e3581f63305d9833fbcbaccad261d36f3a54d799 | refs/heads/master | 2021-06-22T20:23:36.151921 | 2017-07-16T14:27:36 | 2017-07-16T14:27:36 | 66,939,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | cpp | // Reflection
// - First problem regarding bit manipulation.
// - For counting 1 in the sequence,
// while (n) {
// ++count;
// n &= n - 1;
// }
// Problem
// The Hamming distance between two integers is the number of positions at which
// the corresponding bits are different.
//
// Given two integers x and y, calculate the Hamming distance.
//
// Note:
// 0 ≤ x, y < 231.
// Initial solution( Complexity: O(n) )
class Solution {
public:
int getBit(int num, int i){
return ((num & (1<<i)) != 0);
}
int hammingDistance(int x, int y) {
int countDecimal = x ^ y,
count = 0;
for(int i=0; i<32; i++){
count += getBit(countDecimal, i);
}
return count;
}
};
// Improved solution( Complexity: O(n) )
class Solution {
public:
int hammingDistance(int x, int y) {
int dist = 0, n = x ^ y;
while (n) {
++dist;
n &= n - 1;
}
return dist;
}
};
| [
"[email protected]"
] | |
e365de90d9a71c11429f26c46e36bd70e505dc2f | 585f48f03da5f141833c32d66dfb0379914eeb08 | /lab5/dllmain.h | 69ccd38ef385a4d4b54e4ff71e2b537cdfb8879d | [] | no_license | ShiloDenis1997/COM.Lab5 | a7e747fb89791903386d92086c62e00db47b45dd | c4bbd6b7ecae244b16c42a4387ab78bfc6dc80e2 | refs/heads/master | 2021-01-22T08:18:36.856200 | 2017-05-28T00:47:06 | 2017-05-28T00:47:06 | 92,611,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | h | // dllmain.h : Declaration of module class.
class Clab5Module : public ATL::CAtlDllModuleT< Clab5Module >
{
public :
DECLARE_LIBID(LIBID_lab5Lib)
DECLARE_REGISTRY_APPID_RESOURCEID(IDR_LAB5, "{57E5CD6C-A0D6-45F7-AA90-08470428590E}")
};
extern class Clab5Module _AtlModule;
| [
"[email protected]"
] | |
892d286aafc8ab85ea2d2100d988c904755154bb | 731d0d3e1d1cc11f31ca8f8c0aa7951814052c15 | /InetSpeed/Generated Files/winrt/impl/Windows.Devices.Geolocation.1.h | 97545d2983d8992789ae5183216ce8f3703fc6e7 | [] | no_license | serzh82saratov/InetSpeedCppWinRT | 07623c08b5c8135c7d55c17fed1164c8d9e56c8f | e5051f8c44469bbed0488c1d38731afe874f8c1f | refs/heads/master | 2022-04-20T05:48:22.203411 | 2020-04-02T19:36:13 | 2020-04-02T19:36:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,421 | h | // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.200316.3
#ifndef WINRT_Windows_Devices_Geolocation_1_H
#define WINRT_Windows_Devices_Geolocation_1_H
#include "winrt/impl/Windows.Devices.Geolocation.0.h"
WINRT_EXPORT namespace winrt::Windows::Devices::Geolocation
{
struct __declspec(empty_bases) ICivicAddress :
Windows::Foundation::IInspectable,
impl::consume_t<ICivicAddress>
{
ICivicAddress(std::nullptr_t = nullptr) noexcept {}
ICivicAddress(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeoboundingBox :
Windows::Foundation::IInspectable,
impl::consume_t<IGeoboundingBox>,
impl::require<Windows::Devices::Geolocation::IGeoboundingBox, Windows::Devices::Geolocation::IGeoshape>
{
IGeoboundingBox(std::nullptr_t = nullptr) noexcept {}
IGeoboundingBox(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeoboundingBoxFactory :
Windows::Foundation::IInspectable,
impl::consume_t<IGeoboundingBoxFactory>
{
IGeoboundingBoxFactory(std::nullptr_t = nullptr) noexcept {}
IGeoboundingBoxFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeoboundingBoxStatics :
Windows::Foundation::IInspectable,
impl::consume_t<IGeoboundingBoxStatics>
{
IGeoboundingBoxStatics(std::nullptr_t = nullptr) noexcept {}
IGeoboundingBoxStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeocircle :
Windows::Foundation::IInspectable,
impl::consume_t<IGeocircle>,
impl::require<Windows::Devices::Geolocation::IGeocircle, Windows::Devices::Geolocation::IGeoshape>
{
IGeocircle(std::nullptr_t = nullptr) noexcept {}
IGeocircle(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeocircleFactory :
Windows::Foundation::IInspectable,
impl::consume_t<IGeocircleFactory>
{
IGeocircleFactory(std::nullptr_t = nullptr) noexcept {}
IGeocircleFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeocoordinate :
Windows::Foundation::IInspectable,
impl::consume_t<IGeocoordinate>
{
IGeocoordinate(std::nullptr_t = nullptr) noexcept {}
IGeocoordinate(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeocoordinateSatelliteData :
Windows::Foundation::IInspectable,
impl::consume_t<IGeocoordinateSatelliteData>
{
IGeocoordinateSatelliteData(std::nullptr_t = nullptr) noexcept {}
IGeocoordinateSatelliteData(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeocoordinateWithPoint :
Windows::Foundation::IInspectable,
impl::consume_t<IGeocoordinateWithPoint>
{
IGeocoordinateWithPoint(std::nullptr_t = nullptr) noexcept {}
IGeocoordinateWithPoint(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeocoordinateWithPositionData :
Windows::Foundation::IInspectable,
impl::consume_t<IGeocoordinateWithPositionData>,
impl::require<Windows::Devices::Geolocation::IGeocoordinateWithPositionData, Windows::Devices::Geolocation::IGeocoordinate>
{
IGeocoordinateWithPositionData(std::nullptr_t = nullptr) noexcept {}
IGeocoordinateWithPositionData(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeocoordinateWithPositionSourceTimestamp :
Windows::Foundation::IInspectable,
impl::consume_t<IGeocoordinateWithPositionSourceTimestamp>
{
IGeocoordinateWithPositionSourceTimestamp(std::nullptr_t = nullptr) noexcept {}
IGeocoordinateWithPositionSourceTimestamp(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeolocator :
Windows::Foundation::IInspectable,
impl::consume_t<IGeolocator>
{
IGeolocator(std::nullptr_t = nullptr) noexcept {}
IGeolocator(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeolocator2 :
Windows::Foundation::IInspectable,
impl::consume_t<IGeolocator2>
{
IGeolocator2(std::nullptr_t = nullptr) noexcept {}
IGeolocator2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeolocatorStatics :
Windows::Foundation::IInspectable,
impl::consume_t<IGeolocatorStatics>
{
IGeolocatorStatics(std::nullptr_t = nullptr) noexcept {}
IGeolocatorStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeolocatorStatics2 :
Windows::Foundation::IInspectable,
impl::consume_t<IGeolocatorStatics2>
{
IGeolocatorStatics2(std::nullptr_t = nullptr) noexcept {}
IGeolocatorStatics2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeolocatorWithScalarAccuracy :
Windows::Foundation::IInspectable,
impl::consume_t<IGeolocatorWithScalarAccuracy>,
impl::require<Windows::Devices::Geolocation::IGeolocatorWithScalarAccuracy, Windows::Devices::Geolocation::IGeolocator>
{
IGeolocatorWithScalarAccuracy(std::nullptr_t = nullptr) noexcept {}
IGeolocatorWithScalarAccuracy(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeopath :
Windows::Foundation::IInspectable,
impl::consume_t<IGeopath>,
impl::require<Windows::Devices::Geolocation::IGeopath, Windows::Devices::Geolocation::IGeoshape>
{
IGeopath(std::nullptr_t = nullptr) noexcept {}
IGeopath(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeopathFactory :
Windows::Foundation::IInspectable,
impl::consume_t<IGeopathFactory>
{
IGeopathFactory(std::nullptr_t = nullptr) noexcept {}
IGeopathFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeopoint :
Windows::Foundation::IInspectable,
impl::consume_t<IGeopoint>,
impl::require<Windows::Devices::Geolocation::IGeopoint, Windows::Devices::Geolocation::IGeoshape>
{
IGeopoint(std::nullptr_t = nullptr) noexcept {}
IGeopoint(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeopointFactory :
Windows::Foundation::IInspectable,
impl::consume_t<IGeopointFactory>
{
IGeopointFactory(std::nullptr_t = nullptr) noexcept {}
IGeopointFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeoposition :
Windows::Foundation::IInspectable,
impl::consume_t<IGeoposition>
{
IGeoposition(std::nullptr_t = nullptr) noexcept {}
IGeoposition(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeoposition2 :
Windows::Foundation::IInspectable,
impl::consume_t<IGeoposition2>,
impl::require<Windows::Devices::Geolocation::IGeoposition2, Windows::Devices::Geolocation::IGeoposition>
{
IGeoposition2(std::nullptr_t = nullptr) noexcept {}
IGeoposition2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeoshape :
Windows::Foundation::IInspectable,
impl::consume_t<IGeoshape>
{
IGeoshape(std::nullptr_t = nullptr) noexcept {}
IGeoshape(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeovisit :
Windows::Foundation::IInspectable,
impl::consume_t<IGeovisit>
{
IGeovisit(std::nullptr_t = nullptr) noexcept {}
IGeovisit(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeovisitMonitor :
Windows::Foundation::IInspectable,
impl::consume_t<IGeovisitMonitor>
{
IGeovisitMonitor(std::nullptr_t = nullptr) noexcept {}
IGeovisitMonitor(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeovisitMonitorStatics :
Windows::Foundation::IInspectable,
impl::consume_t<IGeovisitMonitorStatics>
{
IGeovisitMonitorStatics(std::nullptr_t = nullptr) noexcept {}
IGeovisitMonitorStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeovisitStateChangedEventArgs :
Windows::Foundation::IInspectable,
impl::consume_t<IGeovisitStateChangedEventArgs>
{
IGeovisitStateChangedEventArgs(std::nullptr_t = nullptr) noexcept {}
IGeovisitStateChangedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IGeovisitTriggerDetails :
Windows::Foundation::IInspectable,
impl::consume_t<IGeovisitTriggerDetails>
{
IGeovisitTriggerDetails(std::nullptr_t = nullptr) noexcept {}
IGeovisitTriggerDetails(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IPositionChangedEventArgs :
Windows::Foundation::IInspectable,
impl::consume_t<IPositionChangedEventArgs>
{
IPositionChangedEventArgs(std::nullptr_t = nullptr) noexcept {}
IPositionChangedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IStatusChangedEventArgs :
Windows::Foundation::IInspectable,
impl::consume_t<IStatusChangedEventArgs>
{
IStatusChangedEventArgs(std::nullptr_t = nullptr) noexcept {}
IStatusChangedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IVenueData :
Windows::Foundation::IInspectable,
impl::consume_t<IVenueData>
{
IVenueData(std::nullptr_t = nullptr) noexcept {}
IVenueData(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
}
#endif
| [
"[email protected]"
] | |
2e7cb88a976685fc4a172e60d8c912ddfc28b4e1 | 49b310d0aee382e81194559eb3e0a0536036672b | /程序/2017-7-1集训/main.cpp | 7360edc427e2c1027af21869f4976f0a3a2cbb86 | [] | no_license | JameMoriarty/Hello-World | 7bfb33ac5b6c6959872179471ad234b2ead7b593 | 6c6052a5e14613579817e4cee177e159c24ffc58 | refs/heads/master | 2020-04-28T21:39:37.569187 | 2019-10-09T05:29:47 | 2019-10-09T05:29:47 | 175,589,879 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,896 | cpp | #include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int main ()
{
int n;
while (scanf("%d",&n)==1)
{
if (n==0)
break;
int a,i,dp[100005]={0},judge[100005]={-1};
for (i=1;i<=n;i++)
{
scanf("%d",&a);
judge[a]=i;
if (judge[a]!=-1)
{
if (a==999)
{
dp[i]=max(dp[i-1],dp[judge[a]]+3);
}
else
{
dp[i]=max(dp[i-1],dp[judge[a]]+1);
}
}
else
dp[i]=dp[i-1];
}
for (i=1;i<=n;i++)
{
printf("%d ",judge[i]);
}
printf("\n");
printf("%d\n",dp[n]);
}
return 0;
}
//
//int dp[100010];
//bool vis[100010];
//int a[100010];
//
//int main(){
// int n;
//
// while(scanf("%d",&n)!=EOF){
// if(n==0)
// break;
//
//
// memset(dp,0,sizeof(dp));
// memset(a,0,sizeof(a));
// memset(vis,false,sizeof(vis));
//
// for(int i=0;i<n;i++){
// scanf("%d",&a[i]);
// }
//
// int sum=-1;
//
// int point=a[0];
// vis[point]=true;
//
//
//
// for(int i=1;i<n;i++){
// int next=a[i];
// if(!vis[next]){
//
// dp[next]=dp[point];
// vis[next]=true;
// }
// else{
// if(next==999){
// dp[next]=max(dp[point],dp[next]+3);
// }
// else{
// dp[next]=max(dp[point],dp[next]+1);
// }
// }
//
// point=next;
//
// if(dp[next]>sum)
// sum=dp[next];
//
// }
// printf("%d\n",sum);
// }
// return 0;
//}
| [
"[email protected]"
] | |
0ba24626f20bcbf7104016f6f39b2f81eaebe242 | 5222b85a557a82521f9d65b7f9fedddf4971f24f | /01_basics/13_while.cpp | d8996b267e8c7ba2ef1107fced8ec05b3479a70d | [] | no_license | andres-udemy-git/cpp_in_4_stunden | 889c4e60a9de0c0205ecdfbd0e12a3dbf52e0f81 | ffb7428f1b5b6b1358555843c569d3f8cc025833 | refs/heads/master | 2021-01-07T13:55:32.343155 | 2020-02-19T21:00:13 | 2020-02-19T21:00:13 | 241,715,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 157 | cpp | #include <iostream>
using namespace std;
int main() {
int i = 5;
while (i < 15) {
cout << i << " ";
i++;
}
cout << endl;
} | [
"[email protected]"
] | |
881561c9c41fe6f443d38950b9f897147e5025b7 | 01108f3877316d10c0a4060a2623701ab91b1e1a | /q191.h | 9036d32bbb6a5801d74ab6c83e6bf76fce6db8fb | [] | no_license | GreysTone/Leetcode | 94085d15f53208f034681d74e07db75055ad5c72 | 37486b0c9066a82c8a19b082dd1532c0a38ccaf9 | refs/heads/master | 2020-03-07T15:56:49.210444 | 2018-03-31T20:55:05 | 2018-03-31T20:55:05 | 127,568,624 | 0 | 0 | null | 2018-03-31T20:27:03 | 2018-03-31T20:27:03 | null | UTF-8 | C++ | false | false | 828 | h | //
// Created by Jerry Li on 2017/10/26.
//
/********************* Problem Specification *********************
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
***************************** Solution **************************
See the code and descriptions below.
******************************** End ****************************
*/
#ifndef LEETCODE_Q191_H
#define LEETCODE_Q191_H
#include "commons.h"
class Solution {
public:
int hammingWeight(uint32_t n) {
int result = 0;
while(n != 0) {
n = n &(n-1);
result += 1;
}
return result;
}
};
#endif; | [
"[email protected]"
] | |
3c64db319b43011fb591b9a0dd92b7b7a1a2d058 | c002e0807aaa361c87c4a8b43bf2f53f755a1eca | /DataStruct/Chapter4-Experiment/Graph.h | ba1dd7d81cc6732916e16115a1db0d3580b14a1a | [
"MIT"
] | permissive | AlongWY/HIT-WorkShop | d6f815fb9a360657f6c4a8690186e9bf4097bcca | d1b7a75493608b58c7b56f303e5996b20dd6d4c0 | refs/heads/master | 2022-01-18T21:38:58.214527 | 2021-12-29T11:40:48 | 2021-12-29T11:40:48 | 213,611,806 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 7,210 | h | //
// Created by along on 17-11-26.
//
#ifndef PROJECT_GRAPH_H
#define PROJECT_GRAPH_H
#ifdef USE_BOOST_LIB
#include <boost/dynamic_bitset.hpp>
#endif
#include <vector>
#include <forward_list>
#include <functional>
class Graph {
public:
/**
* 产生一个顶点为0 -- n-1的图
* @param n
*/
explicit Graph(unsigned long n) : vexNum(n), edgeNum(0) {};
/**
* 使用已有的图构造一个新图
* @param rhs
*/
Graph(const Graph &rhs);
/**
* 析构函数,避免内存泄漏
*/
virtual ~Graph() { clear(); };
/**
* 拷贝赋值函数
* @param rhs
* @return
*/
Graph &operator=(const Graph &rhs);
/**
* 添加一条边
* @param source
* @param sink
*/
virtual void addEdge(unsigned long source, unsigned long sink);
/**
* 删除一条边
* @param source
* @param sink
*/
virtual void delEdge(unsigned long source, unsigned long sink);
/**
* 返回顶点个数
* @return
*/
virtual unsigned long vexCount() const;
/**
* 边的个数
* @return
*/
virtual unsigned long edgeCount() const;
/**
* 顶点的出度
* @param source
* @return
*/
virtual unsigned long outDegree(unsigned long source) const;
/**
* 顶点的入度
* @param source
* @return
*/
virtual unsigned long inDegree(unsigned long source) const;
/**
* 两个顶点之间是否有边
* @param source
* @param sink
* @return
*/
virtual bool hasEdge(unsigned long source, unsigned long sink) const;
/**
* 遍历与某个顶点相临接的所有顶点
* 当func返回值为false的时候可以停止访问
* @param source
* @param func
*/
virtual void foreach(unsigned long source, std::function<bool(unsigned long, unsigned long)> &func) const = 0;
/**
* 先深遍历
* @param DFSTree
* @param out
*/
virtual void DFS(std::function<void(unsigned long)> &visit) const;
/**
* 先深遍历(递归)
* @param DFSTree
* @param out
*/
virtual void DFSR(std::function<void(unsigned long)> &visit) const;
/**
* 先广遍历
* @param BFSTree
* @param out
*/
virtual void BFS(std::function<void(unsigned long)> &visit) const;
/**
* 带起始点的先深遍历
* @param DFSTree
* @param start
* @param visit
*/
virtual void DFS(Graph &DFSTree, unsigned long start, std::function<void(unsigned long)> &visit) const;
/**
* 带起始点的先深遍历(递归)
* @param DFSTree
* @param start
* @param out
*/
virtual void DFSR(Graph &DFSTree, unsigned long start, std::function<void(unsigned long)> &visit) const;
/**
* 带起始点的先广遍历
* @param BFSTree
* @param start
* @param out
*/
virtual void BFS(Graph &BFSTree, unsigned long start, std::function<void(unsigned long)> &visit) const;
/**
* 重置
*/
virtual void reset();
/**
* 重置
* @param vexNum
*/
virtual void reset(unsigned long vexNum);
/**
* 将dot图打印到流
* @param out
*/
void printDot(std::ostream &out);
/**
* 从文件构造一个图
* @param filename
*/
void resetFromStream(std::istream &theStream);
protected:
/**
* 对数据进行清空
*/
virtual void clear();
private:
/**
* 克隆一个图
* @param graph
*/
void clone(const Graph &graph);
unsigned long vexNum;
unsigned long edgeNum;
};
/**
* 图的邻接表实现
* T:Table
*/
class GraphT : public Graph {
public:
explicit GraphT(unsigned long n);
explicit GraphT(const Graph &rhs);
void addEdge(unsigned long source, unsigned long sink) override;
void delEdge(unsigned long source, unsigned long sink) override;
inline unsigned long vexCount() const override;
unsigned long edgeCount() const override;
unsigned long outDegree(unsigned long source) const override;
unsigned long inDegree(unsigned long source) const override;
bool hasEdge(unsigned long source, unsigned long sink) const override;
void foreach(unsigned long source, std::function<bool(unsigned long, unsigned long)> &func) const override;
void reset() override;
void reset(unsigned long vexNum) override;
private:
void clear() override;
/** 顶点表的数据结构 */
typedef struct VexNode {
unsigned long in;
unsigned long out;
std::forward_list<unsigned long> adjVex;
} VexNode;
/** 邻接表顶点 */
std::vector<VexNode> vexes;
};
/**
* 图的邻接矩阵实现
* M:Matrix
*/
class GraphM : public Graph {
public:
explicit GraphM(unsigned long n);
explicit GraphM(const Graph &rhs);
void addEdge(unsigned long source, unsigned long sink) override;
void delEdge(unsigned long source, unsigned long sink) override;
inline unsigned long vexCount() const override;
unsigned long edgeCount() const override;
unsigned long outDegree(unsigned long source) const override;
unsigned long inDegree(unsigned long source) const override;
bool hasEdge(unsigned long source, unsigned long sink) const override;
void foreach(unsigned long source, std::function<bool(unsigned long, unsigned long)> &func) const override;
void reset() override;
void reset(unsigned long vexNum) override;
private:
void clear() override;
#ifdef USE_BOOST_LIB
std::vector<boost::dynamic_bitset<>> vexes;
#else
std::vector<std::vector<bool>> vexes;
#endif
};
/**
* 图的十字链表实现
* L:List
*/
class GraphL : public Graph {
public:
explicit GraphL(unsigned long n);
explicit GraphL(const Graph &rhs);
~GraphL() override { clear(); };
void addEdge(unsigned long source, unsigned long sink) override;
void delEdge(unsigned long source, unsigned long sink) override;
unsigned long vexCount() const override;
unsigned long edgeCount() const override;
unsigned long outDegree(unsigned long source) const override;
unsigned long inDegree(unsigned long source) const override;
bool hasEdge(unsigned long source, unsigned long sink) const override;
void foreach(unsigned long source, std::function<bool(unsigned long, unsigned long)> &func) const override;
void foreachIn(unsigned long dst, std::function<bool(unsigned long, unsigned long)> &func) const;
void reset() override;
void reset(unsigned long vexNum) override;
private:
typedef struct ArcBox {
unsigned long headVex, tailVex;
struct ArcBox *hLink, *tLink;
ArcBox(unsigned long head, unsigned long tail, ArcBox *headLink, ArcBox *tailLink) :
headVex(head), tailVex(tail), hLink(headLink), tLink(tailLink) {}
} ArcBox;
typedef struct VexNode {
unsigned long in, out;
ArcBox *firstIn, *firstOut;
VexNode() : in(0), out(0), firstIn(nullptr), firstOut(nullptr) {};
} VexNode;
void clear() override;
std::vector<VexNode> vexes;
};
#endif //PROJECT_GRAPH_H
| [
"[email protected]"
] | |
4bcc8075e62d82ca14ed6d0f7a495e3a734c36bf | 0c7e20a002108d636517b2f0cde6de9019fdf8c4 | /Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/telephony/CSmsCbLocation.cpp | 993d6d65f2a88acf3b92ffdfc3b8bf78585c6b14 | [
"Apache-2.0"
] | permissive | kernal88/Elastos5 | 022774d8c42aea597e6f8ee14e80e8e31758f950 | 871044110de52fcccfbd6fd0d9c24feefeb6dea0 | refs/heads/master | 2021-01-12T15:23:52.242654 | 2016-10-24T08:20:15 | 2016-10-24T08:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include "elastos/droid/telephony/CSmsCbLocation.h"
namespace Elastos {
namespace Droid {
namespace Telephony {
CAR_OBJECT_IMPL(CSmsCbLocation)
} // namespace Telephony
} // namespace Droid
} // namespace Elastos
| [
"[email protected]"
] | |
eefdeee154bb55cddbef09ccc3be95a0eaffd41e | 2aeb5e7a79eeafa405dd44466f4fd6a728b8d684 | /HotelReservationManagementSystem/Room.h | 14c1f75079f925c48447638d27261e096bfdc82b | [] | no_license | firatkarakusoglu/Hotel-Reservation-Management-System | 583f579d3ea90d07709bdd6f2360c2c730a5f50b | 8a0c79d3e94ce23b14b88335f18caffaf2fdfe1c | refs/heads/master | 2021-01-10T21:06:34.815753 | 2013-03-10T08:00:57 | 2013-03-10T08:00:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,834 | h | #include "Reservation.h"
class Room
{
private:
int stairNumber;//this shows the stair number, that this room is inside.
int sortOfRoom; //this shows which sort of room is. king, suit, luxury, standard
int sequenceNumber; //It shows the sequence, in that stair
int thisRoomNumber; // A _00B_ C ; A stair number, B, sequence number, C is sort of room
int numberOfMadeReservations;
public:
int *forStatisticInfos;
Room();
~Room();
Reservation *reservations; //each room has its reservation schedule, for each
void setStairNumber(int _stairNumber);
void setSortOfRoom(int _sortOfRoom);
void setSequenceNumber(int _sequenceNumber);
void setNumberOfMadeReservations(int _numberOfMadeReservations) {numberOfMadeReservations = _numberOfMadeReservations;};
int getStairNumber();
int getSortOfRoom();
int getSequenceNumber();
int getThisRoomNumber();
static int getStairNumber(int _roomNumber){return (_roomNumber/10000);};
static int getSortOfRoom(int _roomNumber){return (_roomNumber-(_roomNumber/10)*10);};
static int getSequenceNumber(int _roomNumber){return ((_roomNumber-((_roomNumber/10000)*10000))/10); };
int generateRoomNumber(int _stairNumber, int _sequenceNumber, int _sortOfRoom);
void registerNewReservation(char *_customerName_Surname,char *_customerAddress,char *_customerCreditCardNumber,char *_customerPhoneNumber,Date _reservationBeginDate,Date _reservationEndDate, double _roomDailyPrice);
double cancelPreviousReservation(Date _reservationBeginDate);
int searchForReservation(Date _reservationBeginDate);
int checkIn(char * _customerName_Surname);
int checkOut(char *_customerName_Surname, int & reservationSequence);
int searchAccordingToTheName(char *_customerName_Surname);
bool isItFree(Date _reservationBeginDate, Date _reservationEndDate);
int makeService(int _serviceId);
};
Room::Room()
{
numberOfMadeReservations = 0;
forStatisticInfos = new int[1];
};
Room::~Room()
{
delete [] reservations;
};
void Room::setStairNumber(int _stairNumber){stairNumber = _stairNumber;};
void Room::setSortOfRoom(int _sortOfRoom){sortOfRoom = _sortOfRoom;};
void Room::setSequenceNumber(int _sequenceNumber){sequenceNumber = _sequenceNumber;};
int Room::getStairNumber(){return stairNumber;};
int Room::getSortOfRoom(){return sortOfRoom;};
int Room::getSequenceNumber(){return sequenceNumber;};
int Room::getThisRoomNumber(){return thisRoomNumber;};
int Room::generateRoomNumber(int _stairNumber, int _sequenceNumber, int _sortOfRoom)
{
if(_sequenceNumber<1000 && _sequenceNumber>0)
{
thisRoomNumber = ((_stairNumber*10000)+(_sequenceNumber*10)+_sortOfRoom);
return thisRoomNumber;
}
else
{
cout<<endl<<_sequenceNumber;
cout<<endl<<"Error: Each stair can have max. 999 room.";
return 0;
};
};
void Room::registerNewReservation(char *_customerName_Surname,char *_customerAddress,char *_customerCreditCardNumber,char *_customerPhoneNumber,Date _reservationBeginDate,Date _reservationEndDate, double _roomDailyPrice)
{
numberOfMadeReservations++; //at the beginning, it will be 1
if(numberOfMadeReservations == 1) reservations = new Reservation[2];
else
{
Reservation *tempReservations= new Reservation[numberOfMadeReservations];
tempReservations = reservations;
reservations = new Reservation[numberOfMadeReservations];
reservations = tempReservations;
};
reservations[numberOfMadeReservations-1].setCustomerName_Surname(_customerName_Surname);
reservations[numberOfMadeReservations-1].setCustomerAddress(_customerAddress);
//cout<<endl<<"deneme: adres"<<reservations[numberOfMadeReservations-1].getCustomerAddress();
reservations[numberOfMadeReservations-1].setCustomerCreditCardNumber(_customerCreditCardNumber);
reservations[numberOfMadeReservations-1].setCustomerPhoneNumber(_customerPhoneNumber);
reservations[numberOfMadeReservations-1].setReservationBeginDate(_reservationBeginDate);
reservations[numberOfMadeReservations-1].setReservationEndDate(_reservationEndDate);
reservations[numberOfMadeReservations-1].setReservationSequence(numberOfMadeReservations);
//cout<<endl<<"deneme: ad soyad"<<reservations[numberOfMadeReservations-1].getCustomerName_Surname();
//cout<<endl<<"res sirasi"<<reservations[numberOfMadeReservations-1].getReservationSequence();
//cout<<endl<<"deneme: ad soyad"<<reservations[0].getCustomerName_Surname();
double roomPayment = ((_reservationEndDate - _reservationBeginDate)*_roomDailyPrice);
reservations[numberOfMadeReservations-1].setPayment(roomPayment);
//cout<<endl<<" room class ROOM PAYMENT IS : "<<roomPayment;
//cout<<endl<<" room class ROOM DAILY PRICE IS : "<<_roomDailyPrice;
getch();
};
int Room::searchForReservation(Date _reservationBeginDate)
{
bool foundLogic = false;
for(int ctr=0;ctr<numberOfMadeReservations;ctr++)
{
Date beginDate = reservations[ctr].getReservationBeginDate();
//Date endDate = reservations[ctr].getReservationEndDate();
if(beginDate == _reservationBeginDate)
{
Date begin = reservations[ctr].getReservationBeginDate();
//Date end = reservations[ctr].getReservationEndDate();
int a;
a = reservations[ctr].getReservationSequence();
return ctr+1;
foundLogic = true;
};
};
if(foundLogic == false) return 0;
};
double Room::cancelPreviousReservation(Date _reservationBeginDate)
{
int reservationOrder = searchForReservation(_reservationBeginDate);
if(reservationOrder!=0 && ((reservations[reservationOrder-1].getCancelationInfo())!= true))
{
if((reservations[reservationOrder-1].getCheckInInfo())!= true )
{
if((reservations[reservationOrder-1].getCheckOutInfo())!= true )
{
Date today2;
int remainDay = _reservationBeginDate - today2;
// cout<<endl<<"in room class today: "<<today;
// cout<<endl<<"in room class _reservationBeginDate: "<<_reservationBeginDate;
if(remainDay<4)
{
double payment = reservations[reservationOrder-1].getPayment();
// cout<<endl<<"in room class remainDay:"<<remainDay;
payment = payment - ((payment/4)*remainDay);
reservations[reservationOrder-1].setCancelationInfo(true);
//"Customer should pay some money.";
// cout<<endl<<"in room class: payment"<<payment;
return payment;
}
else
{
//cout<<endl<<endl<<"remainDay : "<<remainDay;
reservations[reservationOrder-1].setCancelationInfo(true);
//reservation canceled
return 0;
}
/////////////FOR STATISTIC INFOS - 1's IS MAKING 0
Date today;
int year = today.getYear();
Date newYear(1,1,year);
Date _reservationEndDate;
_reservationEndDate = reservations[reservationOrder-1].getReservationEndDate();
int dayFromTheBeginning = 0;
dayFromTheBeginning = _reservationBeginDate - newYear;
while(_reservationBeginDate != _reservationEndDate)
{
dayFromTheBeginning++;
forStatisticInfos[dayFromTheBeginning] = 0;
_reservationBeginDate++;
};
/////////////////////////////////////////////////////
}return (-3); //reservation checked out before
} return (-2);//reservation checked in
}
else { return (-1); }; //that reservation could not find.
};
int Room::checkIn(char * _customerName_Surname)
{
Date today;
int customerSequence = searchAccordingToTheName(_customerName_Surname);
//cout<<endl<<"customer sequence: "<<customerSequence;
if(customerSequence)
{
Date reservationBeginDate = reservations[customerSequence-1].getReservationBeginDate();
Date reservationEndDate = reservations[customerSequence-1].getReservationEndDate();
if(reservationBeginDate<=today && reservationEndDate>today)
{
if(reservations[customerSequence-1].getCheckOutInfo() == false)
{
reservations[customerSequence-1].setCheckInInfo(true);
return 1; //cout<<endl<<"You checked in";
}
return -2; //you checked out before
};
//cout<<endl<<"Error: Your reservation does not include this day...";
return -1;
};
//cout<<endl<<"There is no reservation that includes today.";
return 0;
};
int Room::checkOut(char * _customerName_Surname,int & reservationSequence)
{
Date today;
int customerSequence = searchAccordingToTheName(_customerName_Surname);
if(customerSequence)
{
Date reservationBeginDate = reservations[customerSequence-1].getReservationBeginDate();
Date reservationEndDate = reservations[customerSequence-1].getReservationEndDate();
if(reservationBeginDate<=today && reservationEndDate >today)
{
if( reservations[customerSequence-1].getCheckInInfo() == true)
{
reservations[customerSequence-1].setCheckOutInfo(true);
reservations[customerSequence-1].setCheckInInfo(false);
//gf. blink("check out icindeyim");
reservationSequence = customerSequence;
// cout<<endl<<"You checked out...";
return 1;
}
else
{
//cout<<endl<<"Error: you have not checked in, yet";
return -1;
};
};
//cout<<endl<<"Error: Your reservation does not include this day...";
return -2;
};
//cout<<endl<<"There is no reservation that includes today.";
return 0;
};
int Room::searchAccordingToTheName(char *_customerName_Surname)
{
for(int ctr = 0; ctr<numberOfMadeReservations; ctr++)
{
if(strcmp(reservations[ctr].getCustomerName_Surname(),_customerName_Surname)==0)
{
if( reservations[ctr].getCheckOutInfo() == false || reservations[ctr].getCancelationInfo() == false)
return ctr+1;
//returns the sequence of the reservation
};
}
cout<<endl<<"Error: There is no reservation";
return 0;
};
bool Room::isItFree(Date _reservationBeginDate, Date _reservationEndDate)
{
for(int ctr = 0; ctr<numberOfMadeReservations; ctr++)
{
Date reservationBeginDate = reservations[ctr].getReservationBeginDate();
Date reservationEndDate = reservations[ctr].getReservationEndDate();
//cout<<endl<<"reservationBeginDate : "<<reservationBeginDate;
//cout<<endl<<"reservationEndDate: "<<reservationEndDate;
if((_reservationBeginDate<reservationBeginDate && _reservationEndDate<=reservationBeginDate) || (_reservationBeginDate >= reservationEndDate && _reservationEndDate>reservationEndDate))
{
//cout<<endl<<"IN TRUE FREE ROOM";
return true;
}
else if(reservations[ctr].getCheckOutInfo() == true || reservations[ctr].getCancelationInfo() == true)
{
//cout<<endl<<"IN TRUE FREE ROOM";
return true;
}
else
{
//cout<<endl<<"IN FALSE FREE ROOM";
return false;
}
}
return true;
};
int Room::makeService(int _serviceId)
{
Date today;
int foundKey=0;
int resOrder = 0;
int ctr;
//getCheckInInfo
if(numberOfMadeReservations>0)
{
//cout<<endl<<endl<<"numberOfMadeReservations:" <<numberOfMadeReservations;
for( ctr= 0; ctr<numberOfMadeReservations; ctr++)
{
Date reservationBeginDate = reservations[ctr].getReservationBeginDate();
Date reservationEndDate = reservations[ctr].getReservationEndDate();
if(today<reservationEndDate && today>=reservationBeginDate && (reservations[ctr].getCancelationInfo()==false))
{
foundKey = 1;
resOrder = ctr;
};
};
int checkInKey ;
checkInKey = reservations[ctr-1].getCheckInInfo();
if(checkInKey == true && foundKey==1 )
{
reservations[ctr-1].addServices(_serviceId);
return 1; // bulundu - servis yapilabilir
}
checkInKey = reservations[ctr-1].getCheckInInfo();
//cout<<endl<<endl<<"customer checked in: "<<checkInKey;
//cout<<endl<<"ctr: "<<ctr;
if( checkInKey == false && foundKey==1)
{
return -1; //bulundu fakat check in yapilmamis
};
return 0; //bulunamadi
}
else return 0;
};
| [
"[email protected]"
] | |
3fecb228c0dda92ba17a48b597b3d150b769a47e | a707b32ea38de5f83cbc4415c6cced45f9dd8053 | /dsms/include/execution/internals/aeval.h | 195543038562e5f212bc47c25a449f8466e1c861 | [] | no_license | BarbaNikos/selena | 39881a252e2ab4129a38e7ffd3c60885b679f430 | 300fc9afe19c954b31b20247a5ba6d311b1c275a | refs/heads/master | 2021-04-28T16:15:40.376183 | 2018-02-19T02:45:22 | 2018-02-19T02:45:22 | 122,011,170 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,893 | h | //
// Created by Nikos R. Katsipoulakis on 2/7/18.
//
#ifndef _AEVAL_
#define _AEVAL_
#include <cstring>
#include "execution/internals/eval_context.h"
namespace Execution {
enum AOp {
INT_ADD,
INT_SUB,
INT_MUL,
INT_DIV,
FLT_ADD,
FLT_SUB,
FLT_MUL,
FLT_DIV,
INT_CPY,
FLT_CPY,
CHR_CPY,
BYT_CPY,
INT_UMX,
INT_UMN,
FLT_UMX,
FLT_UMN,
INT_AVG,
FLT_AVG
};
struct AInstr {
AOp op;
unsigned int r1;
unsigned int c1;
unsigned int r2;
unsigned int c2;
unsigned int dr;
unsigned int dc;
};
struct AEval {
private:
static const unsigned int MAX_INSTRS = 20;
AInstr instrs [MAX_INSTRS];
unsigned int numInstrs;
char **roles;
public:
AEval ();
~AEval ();
int addInstr (AInstr instr);
int setEvalContext (EvalContext *evalContext);
inline void eval () {
for (unsigned int i = 0 ; i < numInstrs ; i++) {
switch (instrs [i].op) {
case INT_ADD:
ILOC(instrs[i].dr, instrs[i].dc) =
ILOC (instrs[i].r1, instrs[i].c1) +
ILOC (instrs[i].r2, instrs[i].c2);
break;
case INT_SUB:
ILOC(instrs[i].dr, instrs[i].dc) =
ILOC (instrs[i].r1, instrs[i].c1) -
ILOC (instrs[i].r2, instrs[i].c2);
break;
case INT_MUL:
ILOC(instrs[i].dr, instrs[i].dc) =
ILOC (instrs[i].r1, instrs[i].c1) *
ILOC (instrs[i].r2, instrs[i].c2);
break;
case INT_DIV:
ILOC(instrs[i].dr, instrs[i].dc) =
ILOC (instrs[i].r1, instrs[i].c1) /
ILOC (instrs[i].r2, instrs[i].c2);
break;
case FLT_ADD:
FLOC(instrs[i].dr, instrs[i].dc) =
FLOC (instrs[i].r1, instrs[i].c1) +
FLOC (instrs[i].r2, instrs[i].c2);
break;
case FLT_SUB:
FLOC(instrs[i].dr, instrs[i].dc) =
FLOC (instrs[i].r1, instrs[i].c1) -
FLOC (instrs[i].r2, instrs[i].c2);
break;
case FLT_MUL:
FLOC(instrs[i].dr, instrs[i].dc) =
FLOC (instrs[i].r1, instrs[i].c1) *
FLOC (instrs[i].r2, instrs[i].c2);
break;
case FLT_DIV:
FLOC(instrs[i].dr, instrs[i].dc) =
FLOC (instrs[i].r1, instrs[i].c1) /
FLOC (instrs[i].r2, instrs[i].c2);
break;
case INT_CPY:
ILOC (instrs[i].dr, instrs[i].dc) =
ILOC (instrs[i].r1, instrs[i].c1);
break;
case FLT_CPY:
FLOC (instrs[i].dr, instrs[i].dc) =
FLOC (instrs[i].r1, instrs[i].c1);
break;
case CHR_CPY:
strcpy (CLOC(instrs[i].dr, instrs[i].dc),
CLOC(instrs[i].r1, instrs[i].c1));
break;
case BYT_CPY:
BLOC (instrs[i].dr, instrs[i].dc) =
BLOC (instrs[i].r1, instrs[i].c1);
break;
case INT_UMX:
if (ILOC (instrs [i].r1, instrs [i].c1) <
ILOC (instrs [i].r2, instrs [i].c2)) {
ILOC (instrs [i].dr, instrs [i].dc) =
ILOC (instrs [i].r2, instrs [i].c2);
}
else {
ILOC (instrs [i].dr, instrs [i].dc) =
ILOC (instrs [i].r1, instrs [i].c1);
}
break;
case INT_UMN:
if (ILOC (instrs [i].r1, instrs [i].c1) >
ILOC (instrs [i].r2, instrs [i].c2)) {
ILOC (instrs [i].dr, instrs [i].dc) =
ILOC (instrs [i].r2, instrs [i].c2);
}
else {
ILOC (instrs [i].dr, instrs [i].dc) =
ILOC (instrs [i].r1, instrs [i].c1);
}
break;
case FLT_UMX:
if (FLOC (instrs [i].r1, instrs [i].c1) <
FLOC (instrs [i].r2, instrs [i].c2)) {
FLOC (instrs [i].dr, instrs [i].dc) =
FLOC (instrs [i].r2, instrs [i].c2);
}
else {
FLOC (instrs [i].dr, instrs [i].dc) =
FLOC (instrs [i].r1, instrs [i].c1);
}
break;
case FLT_UMN:
if (FLOC (instrs [i].r1, instrs [i].c1) <
FLOC (instrs [i].r2, instrs [i].c2)) {
FLOC (instrs [i].dr, instrs [i].dc) =
FLOC (instrs [i].r2, instrs [i].c2);
}
else {
FLOC (instrs [i].dr, instrs [i].dc) =
FLOC (instrs [i].r1, instrs [i].c1);
}
break;
case INT_AVG:
FLOC (instrs [i].dr, instrs[i].dc) =
(1.0 * ILOC (instrs [i].r1, instrs [i].c1)) /
(1.0 * ILOC (instrs [i].r2, instrs [i].c2));
break;
case FLT_AVG:
FLOC (instrs [i].dr, instrs[i].dc) =
FLOC (instrs [i].r1, instrs [i].c1) /
(1.0 * ILOC (instrs [i].r2, instrs [i].c2));
break;
}
}
}
};
}
#endif //_AEVAL_
| [
"[email protected]"
] | |
c2cad06c7c1c210898fc0b4b182156ac76ce0909 | c8987d13443c91f150e3c1c99ab99044608568c0 | /openFrameworks/libs/poco/include/Poco/Zip/Compress.h | bed4324c8ef33f66487b78755703afa09c41d8f0 | [
"MIT"
] | permissive | joshuajnoble/Totem | 178abf5c1e53c3517590ff932cb03480cdfd54a1 | 6fe30947c14acd16ed0dddf33fc581c9b05bcc5e | refs/heads/master | 2021-05-29T05:55:39.413006 | 2015-09-08T22:17:28 | 2015-09-08T22:17:28 | 33,137,549 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,924 | h | //
// Compress.h
//
// $Id: //poco/1.4/Zip/include/Poco/Zip/Compress.h#1 $
//
// Library: Zip
// Package: Zip
// Module: Compress
//
// Definition of the Compress class.
//
// Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Zip_Compress_INCLUDED
#define Zip_Compress_INCLUDED
#include "Poco/Zip/Zip.h"
#include "Poco/Zip/ZipArchive.h"
#include "Poco/FIFOEvent.h"
#include <istream>
#include <ostream>
namespace Poco {
namespace Zip {
class Zip_API Compress
/// Compresses a directory or files as zip.
{
public:
Poco::FIFOEvent<const ZipLocalFileHeader> EDone;
Compress(std::ostream& out, bool seekableOut);
/// seekableOut determines how we write the zip, setting it to true is recommended for local files (smaller zip file),
/// if you are compressing directly to a network, you MUST set it to false
~Compress();
void addFile(std::istream& input, const Poco::DateTime& lastModifiedAt, const Poco::Path& fileName, ZipCommon::CompressionMethod cm = ZipCommon::CM_DEFLATE, ZipCommon::CompressionLevel cl = ZipCommon::CL_MAXIMUM);
/// Adds a single file to the Zip File. fileName must not be a directory name.
void addFile(const Poco::Path& file, const Poco::Path& fileName, ZipCommon::CompressionMethod cm = ZipCommon::CM_DEFLATE, ZipCommon::CompressionLevel cl = ZipCommon::CL_MAXIMUM);
/// Adds a single file to the Zip File. fileName must not be a directory name. The file must exist physically!
void addDirectory(const Poco::Path& entryName, const Poco::DateTime& lastModifiedAt);
/// Adds a directory entry excluding all children to the Zip file, entryName must not be empty.
void addRecursive(const Poco::Path& entry, ZipCommon::CompressionLevel cl = ZipCommon::CL_MAXIMUM, bool excludeRoot = true, const Poco::Path& name = Poco::Path());
/// Adds a directory entry recursively to the zip file, set excludeRoot to false to exclude the parent directory.
/// If excludeRoot is true you can specify an empty name to add the files as relative files
void addRecursive(const Poco::Path& entry, ZipCommon::CompressionMethod cm, ZipCommon::CompressionLevel cl = ZipCommon::CL_MAXIMUM, bool excludeRoot = true, const Poco::Path& name = Poco::Path());
/// Adds a directory entry recursively to the zip file, set excludeRoot to false to exclude the parent directory.
/// If excludeRoot is true you can specify an empty name to add the files as relative files
void setZipComment(const std::string& comment);
/// Sets the Zip file comment.
const std::string& getZipComment() const;
/// Returns the Zip file comment.
ZipArchive close();
/// Finalizes the ZipArchive, closes it.
private:
enum
{
COMPRESS_CHUNK_SIZE = 8192
};
Compress(const Compress&);
Compress& operator=(const Compress&);
void addEntry(std::istream& input, const Poco::DateTime& lastModifiedAt, const Poco::Path& fileName, ZipCommon::CompressionMethod cm = ZipCommon::CM_DEFLATE, ZipCommon::CompressionLevel cl = ZipCommon::CL_MAXIMUM);
/// Either adds a file or a single directory entry (excluding subchildren) to the Zip file. the compression level will be ignored
/// for directories.
void addFileRaw(std::istream& in, const ZipLocalFileHeader& hdr, const Poco::Path& fileName);
/// copys an already compressed ZipEntry from in
private:
std::ostream& _out;
bool _seekableOut;
ZipArchive::FileHeaders _files;
ZipArchive::FileInfos _infos;
ZipArchive::DirectoryInfos _dirs;
Poco::UInt32 _offset;
std::string _comment;
friend class Keep;
friend class Rename;
};
//
// inlines
//
inline void Compress::setZipComment(const std::string& comment)
{
_comment = comment;
}
inline const std::string& Compress::getZipComment() const
{
return _comment;
}
} } // namespace Poco::Zip
#endif // Zip_Compress_INCLUDED
| [
"[email protected]"
] | |
84ff21e96a91c7da5aed81ca5723eb1750c3f8bd | 62e6e04d4ab08ca4b5090179af1f670099f94780 | /客户端组件/游戏控件/PasswordControl.cpp | dba9c69cfd453c4822cb50ac8580043cfbc305d1 | [] | no_license | hanshouqing85/wh6603_hpkj | 9895e3bc2e9948aacb15f6bc60f083146796ddf9 | eed96681c75dcc2948f89c63088da21e3d8e0bc0 | refs/heads/master | 2020-04-13T13:48:10.811183 | 2019-06-15T10:49:21 | 2019-06-15T10:49:21 | 163,242,393 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 21,696 | cpp | #include "StdAfx.h"
#include <WinUser.h>//#include "Winable.h"
#include "Resource.h"
#include "PasswordControl.h"
//////////////////////////////////////////////////////////////////////////////////
//位置定义
#define ITEM_POS_S 3 //按钮间距
#define ITEM_POS_X 8 //按钮位置
#define ITEM_POS_Y 8 //按钮位置
//关闭按钮
#define POS_BUTTON_X 5 //按钮位置
#define POS_BUTTON_Y 8 //按钮位置
//常量定义
#define ROW_BACK 0 //退格按钮
#define ROW_SHIFT 1 //切换按钮
#define ROW_CAPITAL 2 //大写按钮
#define ROW_CLOSE_KEY 3 //关闭按钮
#define LINE_FUNCTION 4 //功能按钮
//控件标识
#define IDC_BT_KEYBOARD 100 //键盘按钮
#define IDC_ED_PASSWORD 200 //密码控件
//////////////////////////////////////////////////////////////////////////////////
BEGIN_MESSAGE_MAP(CPasswordControl, CWnd)
ON_WM_PAINT()
ON_WM_NCPAINT()
ON_WM_SETFOCUS()
ON_WM_ERASEBKGND()
ON_EN_CHANGE(IDC_ED_PASSWORD, OnEnChangePassword)
ON_BN_CLICKED(IDC_BT_KEYBOARD, OnBnClickedKeyboard)
END_MESSAGE_MAP()
BEGIN_MESSAGE_MAP(CPasswordKeyboard, CDialog)
ON_WM_NCPAINT()
ON_WM_KILLFOCUS()
ON_WM_SETCURSOR()
ON_WM_LBUTTONUP()
ON_WM_ERASEBKGND()
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
//////////////////////////////////////////////////////////////////////////////////
//构造函数
CPasswordControl::CPasswordControl()
{
//设置变量
m_bModify=false;
m_bFalsity=false;
m_bDrawBorad=true;
m_bRenderImage=true;
ZeroMemory(m_szPassword,sizeof(m_szPassword));
return;
}
//析构函数
CPasswordControl::~CPasswordControl()
{
}
//绑定函数
VOID CPasswordControl::PreSubclassWindow()
{
__super::PreSubclassWindow();
//获取位置
CRect rcClient;
CRect rcWindow;
GetClientRect(&rcClient);
GetWindowRect(&rcWindow);
//创建按钮
CRect rcButton(0,0,0,0);
m_btKeyboard.Create(NULL,WS_CHILD|WS_VISIBLE,rcButton,this,IDC_BT_KEYBOARD);
m_btKeyboard.SetButtonImage(IDB_BT_KEYBOARD,GetModuleHandle(SHARE_CONTROL_DLL_NAME),false,false);
//创建控件
CRect rcEditCreate;
rcEditCreate.top=5;
rcEditCreate.left=25;
rcEditCreate.bottom=36;
rcEditCreate.right=rcClient.Width()-23;
m_edPassword.Create(WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL|ES_PASSWORD,rcEditCreate,this,IDC_ED_PASSWORD);
//设置控件
m_edPassword.LimitText(LEN_PASSWORD-1);
m_edPassword.SetEnableColor(RGB(0,0,0),RGB(234,179,106),RGB(234,179,106));
m_edPassword.SetFont(&CSkinResourceManager::GetInstance()->GetDefaultFont());
//移动窗口
SetWindowPos(NULL,0,0,rcWindow.Width(),32,SWP_NOMOVE|SWP_NOZORDER|SWP_NOCOPYBITS);
m_btKeyboard.SetWindowPos(NULL,3,5,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOCOPYBITS|SWP_NOACTIVATE);
return;
}
//边框设置
VOID CPasswordControl::SetDrawBorad(bool bDrawBorad)
{
//设置变量
m_bDrawBorad=bDrawBorad;
//更新界面
if (m_hWnd!=NULL)
{
RedrawWindow(NULL,NULL,RDW_INVALIDATE|RDW_ERASE|RDW_UPDATENOW|RDW_ERASENOW);
}
return;
}
//设置密码
VOID CPasswordControl::SetUserPassword(LPCTSTR pszPassword)
{
//设置控件
INT nPasswordLen=lstrlen(pszPassword);
m_edPassword.SetWindowText((nPasswordLen>0)?TEXT("\n********"):TEXT(""));
//设置变量
m_bModify=false;
m_bFalsity=true;
lstrcpyn(m_szPassword,pszPassword,CountArray(m_szPassword));
return;
}
//获取密码
LPCTSTR CPasswordControl::GetUserPassword(TCHAR szPassword[LEN_PASSWORD])
{
//控件密码
if (m_bModify==true)
{
m_bModify=false;
m_edPassword.GetWindowText(m_szPassword,CountArray(m_szPassword));
}
//拷贝密码
lstrcpyn(szPassword,m_szPassword,LEN_PASSWORD);
return szPassword;
}
//设置颜色
VOID CPasswordControl::SetEnableColor(COLORREF crEnableText, COLORREF crEnableBK, COLORREF crEnableBorad)
{
m_edPassword.SetEnableColor(crEnableText,crEnableBK,crEnableBorad);
}
//重画消息
VOID CPasswordControl::OnPaint()
{
CPaintDC dc(this);
//获取位置
CRect rcClient;
GetClientRect(&rcClient);
//绘画背景
if (IsWindowEnabled()==TRUE)
{
dc.FillSolidRect(rcClient,RGB(40,29,27));
}
else
{
dc.FillSolidRect(rcClient,RGB(40,29,27));
}
return;
}
//重画消息
VOID CPasswordControl::OnNcPaint()
{
//获取位置
CRect rcWindow;
GetWindowRect(&rcWindow);
ScreenToClient(&rcWindow);
//颜色定义
COLORREF crBackGround=CSkinEdit::m_SkinAttribute.m_crEnableBK;
COLORREF crFrameBorad=CSkinEdit::m_SkinAttribute.m_crEnableBorad;
//禁用状态
if (IsWindowEnabled()==FALSE)
{
if (m_bRenderImage==false)
{
crBackGround=RGB(234,179,106);
crFrameBorad=RGB(234,179,106);
}
else
{
crBackGround=RGB(234,179,106);
crFrameBorad=RGB(234,179,106);
}
}
else
{
crBackGround=RGB(234,179,106);
crFrameBorad=RGB(234,179,106);
}
//边框判断
if (m_bDrawBorad==false)
{
crFrameBorad=RGB(45,26,22);
}
//绘画边框
CClientDC ClientDC(this);
ClientDC.Draw3dRect(rcWindow.left,rcWindow.top,rcWindow.Width(),rcWindow.Height(),crFrameBorad,crFrameBorad);
ClientDC.Draw3dRect(rcWindow.left+1,rcWindow.top+1,rcWindow.Width()-2,rcWindow.Height()-2,crBackGround,crBackGround);
return;
}
//绘画背景
BOOL CPasswordControl::OnEraseBkgnd(CDC * pDC)
{
return TRUE;
}
//获取焦点
VOID CPasswordControl::OnSetFocus(CWnd * pOldWnd)
{
__super::OnSetFocus(pOldWnd);
//设置焦点
m_edPassword.SetFocus();
//设置选择
m_edPassword.SetSel(0,-1,FALSE);
return;
}
//密码改变
VOID CPasswordControl::OnEnChangePassword()
{
//设置变量
m_bModify=true;
m_bFalsity=false;
//发送消息
CWnd * pParent=GetParent();
if (pParent!=NULL) pParent->SendMessage(WM_COMMAND,MAKELONG(GetWindowLong(m_hWnd,GWL_ID),EN_CHANGE),(LPARAM)m_hWnd);
return;
}
//键盘按钮
VOID CPasswordControl::OnBnClickedKeyboard()
{
//获取位置
CRect rcWindow;
GetWindowRect(&rcWindow);
//密码清理
if (m_bFalsity==true)
{
m_bFalsity=false;
m_edPassword.SetWindowText(TEXT(""));
}
//创建键盘
if (m_PasswordKeyboard.m_hWnd==NULL)
{
m_PasswordKeyboard.Create(IDD_PASSWORD_KEYBOARD,this);
}
//显示窗口
UINT uFlags=SWP_NOZORDER|SWP_NOSIZE|SWP_SHOWWINDOW;
m_PasswordKeyboard.SetWindowPos(NULL,rcWindow.left,rcWindow.bottom,0,0,uFlags);
return;
}
//////////////////////////////////////////////////////////////////////////////////
//构造函数
CPasswordKeyboard::CPasswordKeyboard() : CDialog(IDD_PASSWORD_KEYBOARD)
{
//设置变量
m_nRandLine[0]=rand()%11;
m_nRandLine[1]=rand()%10;
m_nRandLine[2]=rand()%13;
m_nRandLine[3]=rand()%13;
//键盘状态
m_bShiftStatus=false;
m_bCapsLockStatus=false;
//状态变量
m_bMouseDown=false;
m_wHoverRow=INVALID_WORD;
m_wHoverLine=INVALID_WORD;
//键盘字符
m_nItemCount[0]=11;
lstrcpyn(m_szKeyboradChar[0][0],TEXT("`1234567890"),CountArray(m_szKeyboradChar[0][0]));
lstrcpyn(m_szKeyboradChar[0][1],TEXT("~!@#$%^&*()"),CountArray(m_szKeyboradChar[0][1]));
//键盘字符
m_nItemCount[1]=10;
lstrcpyn(m_szKeyboradChar[1][0],TEXT("-=[]\\;',./"),CountArray(m_szKeyboradChar[1][0]));
lstrcpyn(m_szKeyboradChar[1][1],TEXT("_+{}|:\"<>?"),CountArray(m_szKeyboradChar[1][1]));
//键盘字符
m_nItemCount[2]=13;
lstrcpyn(m_szKeyboradChar[2][0],TEXT("abcdefghijklm"),CountArray(m_szKeyboradChar[2][0]));
lstrcpyn(m_szKeyboradChar[2][1],TEXT("ABCDEFGHIJKLM"),CountArray(m_szKeyboradChar[2][1]));
//键盘字符
m_nItemCount[3]=13;
lstrcpyn(m_szKeyboradChar[3][0],TEXT("nopqrstuvwxyz"),CountArray(m_szKeyboradChar[3][0]));
lstrcpyn(m_szKeyboradChar[3][1],TEXT("NOPQRSTUVWXYZ"),CountArray(m_szKeyboradChar[3][1]));
//变量定义
HINSTANCE hResInstance=GetModuleHandle(SHARE_CONTROL_DLL_NAME);
//加载资源
CImage ImageItem1;
CImage ImageItem2;
CImage ImageItem3;
ImageItem1.LoadFromResource(hResInstance,IDB_KEYBOARD_ITEM1);
ImageItem2.LoadFromResource(hResInstance,IDB_KEYBOARD_ITEM2);
ImageItem3.LoadFromResource(hResInstance,IDB_KEYBOARD_ITEM3);
//设置大小
m_SizeImageItem1.SetSize(ImageItem1.GetWidth()/3,ImageItem1.GetHeight());
m_SizeImageItem2.SetSize(ImageItem2.GetWidth()/3,ImageItem2.GetHeight());
m_SizeImageItem3.SetSize(ImageItem3.GetWidth()/3,ImageItem3.GetHeight());
//关闭按钮
CImage ImageButton;
ImageButton.LoadFromResource(hResInstance,IDB_BT_KEYBOARD_CLOSE);
m_SizeImageButton.SetSize(ImageButton.GetWidth()/3,ImageButton.GetHeight());
//背景大小
CImage ImageBackGround;
ImageBackGround.LoadFromResource(hResInstance,IDB_PASSWORD_KEYBORAD_BK);
m_SizeBackGround.SetSize(ImageBackGround.GetWidth(),ImageBackGround.GetHeight());
return;
}
//析构函数
CPasswordKeyboard::~CPasswordKeyboard()
{
}
//消息解释
BOOL CPasswordKeyboard::PreTranslateMessage(MSG * pMsg)
{
//大写锁键
if ((pMsg->message==WM_KEYDOWN)&&(pMsg->wParam==VK_CAPITAL))
{
//设置变量
bool bCapsLockStatus=m_bCapsLockStatus;
m_bCapsLockStatus=(GetKeyState(VK_CAPITAL)&0x0F)>0;
//更新界面
if (bCapsLockStatus!=m_bCapsLockStatus)
{
RedrawWindow(NULL,NULL,RDW_FRAME|RDW_ERASE|RDW_INVALIDATE|RDW_UPDATENOW|RDW_ERASENOW);
}
return TRUE;
}
//切换按钮
if ((pMsg->wParam==VK_SHIFT)&&(pMsg->message==WM_KEYUP)||(pMsg->message==WM_KEYDOWN))
{
//设置变量
bool bShiftStatus=m_bShiftStatus;
m_bShiftStatus=(GetKeyState(VK_SHIFT)&0xF0)>0;
//更新界面
if (bShiftStatus!=m_bShiftStatus)
{
RedrawWindow(NULL,NULL,RDW_FRAME|RDW_ERASE|RDW_INVALIDATE|RDW_UPDATENOW|RDW_ERASENOW);
}
return TRUE;
}
return __super::PreTranslateMessage(pMsg);
}
//创建函数
BOOL CPasswordKeyboard::OnInitDialog()
{
__super::OnInitDialog();
//设置变量
m_bMouseDown=false;
m_wHoverRow=INVALID_WORD;
m_wHoverLine=INVALID_WORD;
//获取状态
m_bShiftStatus=(GetKeyState(VK_SHIFT)&0xF0)>0;
m_bCapsLockStatus=(GetKeyState(VK_CAPITAL)&0x0F)>0;
//构造位置
CRect rcWindow;
rcWindow.SetRect(0,0,m_SizeBackGround.cx,m_SizeBackGround.cy);
//移动窗口
CalcWindowRect(&rcWindow,CWnd::adjustBorder);
SetWindowPos(NULL,0,0,rcWindow.Width(),rcWindow.Height(),SWP_NOMOVE|SWP_NOZORDER);
return FALSE;
}
//更新位置
VOID CPasswordKeyboard::SetCurrentStation(CPoint MousePoint)
{
//变量定义
WORD wHoverRow=INVALID_WORD;
WORD wHoverLine=INVALID_WORD;
//字符按钮
if ((MousePoint.x>=ITEM_POS_X)&&(MousePoint.y>=ITEM_POS_Y))
{
//列数计算
if (((MousePoint.x-ITEM_POS_X)%(m_SizeImageItem1.cx+ITEM_POS_S))<=m_SizeImageItem1.cx)
{
wHoverRow=(WORD)((MousePoint.x-ITEM_POS_X)/(m_SizeImageItem1.cx+ITEM_POS_S));
}
//行数计算
if (((MousePoint.y-ITEM_POS_Y)%(m_SizeImageItem1.cy+ITEM_POS_S))<=m_SizeImageItem1.cy)
{
wHoverLine=(WORD)((MousePoint.y-ITEM_POS_Y)/(m_SizeImageItem1.cy+ITEM_POS_S));
}
//参数调整
if (wHoverLine>=CountArray(m_nItemCount)) wHoverLine=INVALID_WORD;
if ((wHoverLine==INVALID_WORD)||(wHoverRow>=m_nItemCount[wHoverLine])) wHoverRow=INVALID_WORD;
}
//功能按钮
if ((wHoverLine<2)&&(wHoverRow==INVALID_WORD))
{
//变量定义
INT nEndLine1=ITEM_POS_X+(m_SizeImageItem1.cx+ITEM_POS_S)*m_nItemCount[0];
INT nEndLine2=ITEM_POS_X+(m_SizeImageItem1.cx+ITEM_POS_S)*m_nItemCount[1];
//原点位置
CPoint ButtonPoint[4];
ButtonPoint[0].SetPoint(nEndLine1,ITEM_POS_Y);
ButtonPoint[1].SetPoint(nEndLine2,ITEM_POS_Y+ITEM_POS_S+m_SizeImageItem3.cy);
ButtonPoint[2].SetPoint(nEndLine2+ITEM_POS_S+m_SizeImageItem2.cx,ITEM_POS_Y+ITEM_POS_S+m_SizeImageItem3.cy);
ButtonPoint[3].SetPoint(m_SizeBackGround.cx-m_SizeImageButton.cx-POS_BUTTON_X,POS_BUTTON_Y);
//按钮区域
CRect rcBack(ButtonPoint[0],m_SizeImageItem3);
CRect rcShift(ButtonPoint[1],m_SizeImageItem2);
CRect rcCapital(ButtonPoint[2],m_SizeImageItem2);
CRect rcCloseKey(ButtonPoint[3],m_SizeImageButton);
//退格按钮
if (rcBack.PtInRect(MousePoint))
{
wHoverRow=ROW_BACK;
wHoverLine=LINE_FUNCTION;
}
//切换按钮
if (rcShift.PtInRect(MousePoint))
{
wHoverRow=ROW_SHIFT;
wHoverLine=LINE_FUNCTION;
}
//大写按钮
if (rcCapital.PtInRect(MousePoint))
{
wHoverRow=ROW_CAPITAL;
wHoverLine=LINE_FUNCTION;
}
//关闭按钮
if (rcCloseKey.PtInRect(MousePoint))
{
wHoverRow=ROW_CLOSE_KEY;
wHoverLine=LINE_FUNCTION;
}
}
//设置变量
m_wHoverRow=wHoverRow;
m_wHoverLine=wHoverLine;
return;
}
//虚拟编码
WORD CPasswordKeyboard::GetVirualKeyCode(WORD wHoverLine, WORD wHoverRow)
{
//功能建区
if (wHoverLine==LINE_FUNCTION)
{
switch (wHoverRow)
{
case ROW_BACK: { return VK_BACK; }
case ROW_SHIFT: { return VK_SHIFT; }
case ROW_CAPITAL: { return VK_CAPITAL; }
}
}
//字符建区
if ((wHoverLine<CountArray(m_nItemCount))&&(wHoverRow<m_nItemCount[wHoverLine]))
{
//计算索引
bool bLowerChar=true;
if (m_bShiftStatus==true) bLowerChar=!bLowerChar;
if ((wHoverLine>=2)&&(m_bCapsLockStatus==true)) bLowerChar=!bLowerChar;
//获取字符
INT nItemCount=m_nItemCount[wHoverLine];
INT nCharRowIndex=(wHoverRow+m_nRandLine[wHoverLine])%nItemCount;
TCHAR chChar=m_szKeyboradChar[wHoverLine][(bLowerChar==true)?0:1][nCharRowIndex];
return chChar;
}
return 0;
}
//界面绘画
VOID CPasswordKeyboard::OnNcPaint()
{
__super::OnNcPaint();
//获取位置
CRect rcWindow;
GetWindowRect(&rcWindow);
//绘画边框
CWindowDC WindowDC(this);
COLORREF crBoradFrame=RGB(234,179,106);
WindowDC.Draw3dRect(0,0,rcWindow.Width(),rcWindow.Height(),crBoradFrame,crBoradFrame);
return;
}
//绘画背景
BOOL CPasswordKeyboard::OnEraseBkgnd(CDC * pDC)
{
//获取位置
CRect rcClient;
GetClientRect(&rcClient);
//创建缓冲
CDC BufferDC;
CBitmap ImageBuffer;
BufferDC.CreateCompatibleDC(pDC);
ImageBuffer.CreateCompatibleBitmap(pDC,rcClient.Width(),rcClient.Height());
//设置环境
BufferDC.SetBkMode(TRANSPARENT);
BufferDC.SelectObject(&ImageBuffer);
BufferDC.SelectObject(CSkinResourceManager::GetInstance()->GetDefaultFont());
//变量定义
HINSTANCE hResInstance=GetModuleHandle(SHARE_CONTROL_DLL_NAME);
CSkinRenderManager * pSkinRenderManager=CSkinRenderManager::GetInstance();
//加载资源
CImage ImageItem1;
CImage ImageItem2;
CImage ImageItem3;
CImage ImageButton;
CImage ImageBackGround;
ImageItem1.LoadFromResource(hResInstance,IDB_KEYBOARD_ITEM1);
ImageItem2.LoadFromResource(hResInstance,IDB_KEYBOARD_ITEM2);
ImageItem3.LoadFromResource(hResInstance,IDB_KEYBOARD_ITEM3);
ImageButton.LoadFromResource(hResInstance,IDB_BT_KEYBOARD_CLOSE);
ImageBackGround.LoadFromResource(hResInstance,IDB_PASSWORD_KEYBORAD_BK);
//渲染资源
pSkinRenderManager->RenderImage(ImageItem1);
pSkinRenderManager->RenderImage(ImageItem2);
pSkinRenderManager->RenderImage(ImageItem3);
pSkinRenderManager->RenderImage(ImageButton);
pSkinRenderManager->RenderImage(ImageBackGround);
//绘画背景
ImageBackGround.BitBlt(BufferDC,0,0);
//字符按钮
for (INT nLine=0;nLine<CountArray(m_nItemCount);nLine++)
{
//绘画子项
for (INT nRow=0;nRow<m_nItemCount[nLine];nRow++)
{
//计算位置
INT nXImageIndex=0;
INT nCharItemIndex=(nRow+m_nRandLine[nLine])%m_nItemCount[nLine];
if ((m_wHoverLine==nLine)&&(m_wHoverRow==nRow)) nXImageIndex=(m_bMouseDown==false)?1:2;
//绘画子项
INT nXDrawPos=ITEM_POS_X+(m_SizeImageItem1.cx+ITEM_POS_S)*nRow;
INT nYDrawPos=ITEM_POS_Y+(m_SizeImageItem1.cy+ITEM_POS_S)*nLine;
ImageItem1.BitBlt(BufferDC,nXDrawPos,nYDrawPos,m_SizeImageItem1.cx,m_SizeImageItem1.cy,nXImageIndex*m_SizeImageItem1.cx,0);
//构造颜色
INT nColorIndex=0;
COLORREF crTextColor[2]={RGB(0,0,0),RGB(125,125,125)};
//颜色计算
if (m_bShiftStatus==true) nColorIndex=(nColorIndex+1)%CountArray(crTextColor);
if ((m_bCapsLockStatus==true)&&(nLine>=2)) nColorIndex=(nColorIndex+1)%CountArray(crTextColor);
//绘画字符
BufferDC.SetTextColor(crTextColor[nColorIndex]);
BufferDC.TextOut(nXDrawPos+5,nYDrawPos+9,&m_szKeyboradChar[nLine][0][nCharItemIndex],1);
//绘画字符
BufferDC.SetTextColor(crTextColor[(nColorIndex+1)%CountArray(crTextColor)]);
BufferDC.TextOut(nXDrawPos+15,nYDrawPos+3,&m_szKeyboradChar[nLine][1][nCharItemIndex],1);
}
}
//退格按钮
{
//资源位置
INT nXImageIndex=0;
if ((m_wHoverLine==LINE_FUNCTION)&&(m_wHoverRow==ROW_BACK)) nXImageIndex=(m_bMouseDown==false)?1:2;
//绘画背景
INT nYDrawPos=ITEM_POS_Y;
INT nXDrawPos=ITEM_POS_X+(m_SizeImageItem1.cx+ITEM_POS_S)*m_nItemCount[0];
ImageItem3.BitBlt(BufferDC,nXDrawPos,nYDrawPos,m_SizeImageItem3.cx,m_SizeImageItem3.cy,nXImageIndex*m_SizeImageItem3.cx,0);
//绘画字符
BufferDC.SetTextColor(RGB(0,0,0));
BufferDC.TextOut(nXDrawPos+20,ITEM_POS_Y+7,TEXT("←"),2);
}
//切换按钮
{
//资源位置
INT nXImageIndex=(m_bShiftStatus==true)?1:0;
if ((m_wHoverLine==LINE_FUNCTION)&&(m_wHoverRow==ROW_SHIFT)) nXImageIndex=(m_bMouseDown==false)?1:2;
//绘画背景
INT nYDrawPos=ITEM_POS_Y+ITEM_POS_S+m_SizeImageItem1.cx;
INT nXDrawPos=ITEM_POS_X+(m_SizeImageItem1.cx+ITEM_POS_S)*m_nItemCount[1];
ImageItem2.BitBlt(BufferDC,nXDrawPos,nYDrawPos,m_SizeImageItem2.cx,m_SizeImageItem2.cy,nXImageIndex*m_SizeImageItem2.cx,0);
//切换按钮
BufferDC.SetTextColor(RGB(0,0,0));
BufferDC.TextOut(nXDrawPos+5,ITEM_POS_Y+ITEM_POS_S+m_SizeImageItem1.cx+6,TEXT("Shift"),5);
}
//大写按钮
{
//资源位置
INT nXImageIndex=(m_bCapsLockStatus==true)?1:0;
if ((m_wHoverLine==LINE_FUNCTION)&&(m_wHoverRow==ROW_CAPITAL)) nXImageIndex=(m_bMouseDown==false)?1:2;
//绘画背景
INT nYDrawPos=ITEM_POS_Y+ITEM_POS_S+m_SizeImageItem1.cx;
INT nXDrawPos=ITEM_POS_X+(m_SizeImageItem1.cx+ITEM_POS_S)*m_nItemCount[1]+m_SizeImageItem2.cx+ITEM_POS_S;
ImageItem2.BitBlt(BufferDC,nXDrawPos,nYDrawPos,m_SizeImageItem2.cx,m_SizeImageItem2.cy,nXImageIndex*m_SizeImageItem2.cx,0);
//大写按钮
BufferDC.SetTextColor(RGB(0,0,0));
BufferDC.TextOut(nXDrawPos+8,ITEM_POS_Y+ITEM_POS_S+m_SizeImageItem1.cx+6,TEXT("Caps"),4);
}
//关闭按钮
{
//资源位置
INT nXImageIndex=0;
if ((m_wHoverLine==LINE_FUNCTION)&&(m_wHoverRow==ROW_CLOSE_KEY)) nXImageIndex=(m_bMouseDown==false)?1:2;
//绘画背景
INT nXDrawPos=rcClient.Width()-m_SizeImageButton.cx-POS_BUTTON_X;
ImageButton.BitBlt(BufferDC,nXDrawPos,POS_BUTTON_Y,m_SizeImageButton.cx,m_SizeImageButton.cy,nXImageIndex*m_SizeImageButton.cx,0);
}
//绘画界面
pDC->BitBlt(0,0,rcClient.Width(),rcClient.Height(),&BufferDC,0,0,SRCCOPY);
//清理资源
BufferDC.DeleteDC();
ImageBuffer.DeleteObject();
return TRUE;
}
//失去焦点
VOID CPasswordKeyboard::OnKillFocus(CWnd * pNewWnd)
{
__super::OnKillFocus(pNewWnd);
//销毁窗口
DestroyWindow();
return;
}
//鼠标消息
VOID CPasswordKeyboard::OnLButtonUp(UINT nFlags, CPoint Point)
{
__super::OnLButtonUp(nFlags,Point);
//取消捕获
if (m_bMouseDown==true)
{
//取消捕获
ReleaseCapture();
//设置变量
m_bMouseDown=false;
//获取光标
CPoint MousePoint;
GetCursorPos(&MousePoint);
ScreenToClient(&MousePoint);
//更新位置
WORD wHoverRow=m_wHoverRow;
WORD wHoverLine=m_wHoverLine;
SetCurrentStation(MousePoint);
//点击处理
if ((m_wHoverRow==wHoverRow)&&(m_wHoverLine==wHoverLine))
{
//关闭按钮
if ((m_wHoverLine==LINE_FUNCTION)&&(m_wHoverRow==ROW_CLOSE_KEY))
{
//设置焦点
CONTAINING_RECORD(this,CPasswordControl,m_PasswordKeyboard)->m_edPassword.SetFocus();
//销毁窗口
DestroyWindow();
return;
}
//虚拟编码
WORD wViraulCode=GetVirualKeyCode(m_wHoverLine,m_wHoverRow);
//按钮处理
switch (wViraulCode)
{
case VK_SHIFT: //切换按钮
{
//设置变量
m_bShiftStatus=!m_bShiftStatus;
break;
}
case VK_CAPITAL: //大写按钮
{
//变量定义
INPUT Input[2];
ZeroMemory(Input,sizeof(Input));
//设置变量
Input[1].ki.dwFlags=KEYEVENTF_KEYUP;
Input[0].type=Input[1].type=INPUT_KEYBOARD;
Input[0].ki.wVk=Input[1].ki.wVk=wViraulCode;
//模拟输入
SendInput(CountArray(Input),Input,sizeof(INPUT));
break;
}
default: //默认按钮
{
//设置变量
m_bShiftStatus=(GetKeyState(VK_SHIFT)&0xF0)>0;
//发送消息
CPasswordControl * pPasswordControl=CONTAINING_RECORD(this,CPasswordControl,m_PasswordKeyboard);
if (pPasswordControl!=NULL) pPasswordControl->m_edPassword.SendMessage(WM_CHAR,wViraulCode,0L);
break;
}
}
}
//更新界面
RedrawWindow(NULL,NULL,RDW_FRAME|RDW_ERASE|RDW_INVALIDATE|RDW_UPDATENOW|RDW_ERASENOW);
}
return;
}
//鼠标消息
VOID CPasswordKeyboard::OnLButtonDown(UINT nFlags, CPoint Point)
{
__super::OnLButtonDown(nFlags,Point);
//点击按钮
if ((m_wHoverLine!=INVALID_WORD)&&(m_wHoverRow!=INVALID_WORD))
{
//捕获鼠标
SetCapture();
//设置变量
m_bMouseDown=true;
//更新界面
RedrawWindow(NULL,NULL,RDW_FRAME|RDW_ERASE|RDW_INVALIDATE|RDW_UPDATENOW|RDW_ERASENOW);
}
return;
}
//光标消息
BOOL CPasswordKeyboard::OnSetCursor(CWnd * pWnd, UINT nHitTest, UINT uMessage)
{
//获取光标
CPoint MousePoint;
GetCursorPos(&MousePoint);
ScreenToClient(&MousePoint);
//更新位置
WORD wHoverRow=m_wHoverRow;
WORD wHoverLine=m_wHoverLine;
SetCurrentStation(MousePoint);
//更新界面
if ((m_wHoverRow!=wHoverRow)||(m_wHoverLine!=wHoverLine))
{
RedrawWindow(NULL,NULL,RDW_FRAME|RDW_ERASE|RDW_INVALIDATE|RDW_UPDATENOW|RDW_ERASENOW);
}
//设置光标
if ((m_wHoverRow!=INVALID_WORD)&&(m_wHoverLine!=INVALID_WORD))
{
SetCursor(LoadCursor(GetModuleHandle(SHARE_CONTROL_DLL_NAME),MAKEINTRESOURCE(IDC_HAND_CUR)));
return true;
}
return __super::OnSetCursor(pWnd,nHitTest,uMessage);
}
//////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
5ed94f53394c8d4fdb38dfa6b968c758285ffe6f | 4e3c4f30415062da425ad3058a0c1fed167e961e | /interview/16.26.cpp | 7f0309620dc6ac36640bc18267b32fd057ac6932 | [] | no_license | jing-ge/Jing-leetcode | 7f423d94d3983076630f33e7205c0ef6d54c20d8 | ae428bd3da52bb5658f3a25fbbd395b24552a735 | refs/heads/main | 2023-08-22T12:19:12.861091 | 2021-09-29T03:15:24 | 2021-09-29T03:15:24 | 321,316,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,299 | cpp | // 面试题 16.26. Calculator LCCI
// Given an arithmetic equation consisting of positive integers, +, -, * and / (no parentheses), compute the result.
// The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
// Example 1:
// Input: "3+2*2"
// Output: 7
// Example 2:
// Input: " 3/2 "
// Output: 1
// Example 3:
// Input: " 3+5 / 2 "
// Output: 5
// Note:
// You may assume that the given expression is always valid.
// Do not use the eval built-in library function.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int cal(string &s, int l, int r){
for(int i=r;i>=l;i--){
if(s[i]=='+')return cal(s,l,i-1)+cal(s,i+1,r);
if(s[i]=='-')return cal(s,l,i-1)-cal(s,i+1,r);
}
for(int i=r;i>=l;i--){
if(s[i]=='*')return cal(s,l,i-1)*cal(s,i+1,r);
if(s[i]=='/')return cal(s,l,i-1)/cal(s,i+1,r);
}
return stoi(s.substr(l,r-l+1));
}
int calculate(string s) {
if(s.empty()) return 0;
return cal(s,0,s.size()-1);
}
};
int main(){
Solution s = Solution();
int res = s.calculate("2*3*4");
cout<<res<<endl;
return 0;
} | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.