blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d2b71704e4cb0ab19327ab37761ed606dd0a3d34 | e2c48e041d2983164cf04bc49d37f3bc7324f2d3 | /Cplusplus/_0000_study/_leetcode/_swordoffer/_028_isSymmetric/_swordoffer_28_main.cpp | 3baf16ee14043bd4ab02377e39f0a89556b1e72b | [] | no_license | ToLoveToFeel/LeetCode | 17aff7f9b36615ccebe386545440f921d8fdf740 | de7a893fc625ff30122899969f761ed5f8df8b12 | refs/heads/master | 2023-07-12T07:35:09.410016 | 2021-08-23T02:33:00 | 2021-08-23T02:33:00 | 230,863,299 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cpp | _swordoffer_28_main.cpp | // Created by WXX on 2021/7/19 11:13
#include "MyTree.h"
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if (!root) return true;
return dfs(root->left, root->right);
}
bool dfs(TreeNode *p, TreeNode *q) {
if (!p && !q) return true;
if (!p || !q || p->val != q->val) return false;
return dfs(p->left, q->right) && dfs(p->right, q->left);
}
};
int main() {
int nu = INT_MAX;
vector<int> nums = {
1,
2, 2,
3, 4, 4, 3
};
TreeNode *root = MyTree(nums).getRoot();
cout << Solution().isSymmetric(root) << endl; // true
return 0;
}
|
c7681f9516025543a44db7acbac5cea3fe48ed5d | 0ec74eeede904f900140cd6b53714d110789b6f9 | /mymap.cpp | 70cb2312f5d0c9dbf814cf608e9fe3d3d123d1cc | [] | no_license | 1393987347/Mymap | a2bf629fa1bb8099340f23fc1214ac5547161e51 | a3f7dcd1317af49a9c9a6e14802e8e9c4914d6d3 | refs/heads/master | 2021-08-16T16:47:28.983126 | 2017-11-20T05:29:01 | 2017-11-20T05:29:01 | 111,365,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 223 | cpp | mymap.cpp | #include <iostream>
#include <cstring>
using namespace std;
template <typename T>
class Mymap
{
Mymap <string, string> map = new Mymap<string, string>();
};
void insert(string, string)
{
}
int main(void)
{
} |
d4cac4954d78fc532b47fae45ff1dda78b6106e9 | 6e57eb71595cf82353150eb149e186a31e76e506 | /main.cpp | 4ca33cfbe654049dce27341f3b4ab560c1e5de18 | [] | no_license | umerzia-7001/Hashtable_with_AVL | dc56fd0497013d19ddb6072145e872b0c983095d | 3a7e75705e5832bd72de1b8345967119c6a3e549 | refs/heads/main | 2023-02-28T11:42:02.960288 | 2021-02-05T18:17:51 | 2021-02-05T18:17:51 | 336,352,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,760 | cpp | main.cpp | //
// Created by Umer on 04/02/2021.
// Importing requirements
#include <iostream>
#include "HashTable.cpp"
#include "AVL.cpp"
using namespace std;
// Add a name into hashTable
void insert(hashTable avlHashTable){
string inputData;
cout << "Enter Data you want to enter:";
getline(cin, inputData);
cin.ignore();
avlHashTable.insert(inputData);
}
// delete name from hashTable
void deleteName(hashTable avlHashTable) {
string inputData;
cout << "Enter Data you want to remove:";
getline(cin, inputData);
cin.ignore();
avlHashTable.deleteName(inputData);
}
int main() {
int option;
bool again = true;
cout << "Populating..." << endl;
// put path to text file here
hashTable table("/Users/apple/Downloads/NamesToHash.txt");
while (again) {
cout << "\nSelect Option from below:\n"
"1. Insert\n"
"2. Remove\n"
"3. Print Pre-Order\n"
"4. Print In-Order\n"
"5. Print Post-Order\n"
"6. Exit\n"
"Enter Option >> ";
cin >> option;
cin.ignore();
switch (option) {
case 1:
insert(table);
break;
case 2:
deleteName(table);
break;
case 3:
table.preOrder();
break;
case 4:
table.InOrder();
break;
case 5:
table.postOrder();
break;
case 6:
again = false;
break;
default:
cout << "Select correct option(1-6)" << endl;
continue;
}
}
};
// end |
41318548fe7649c25b3dfcfe5a91abf88b5f94f2 | 9d364cba2641ea99ac9b0dfb28f065de5e6a3457 | /src/Things/Structures/University.h | b81377ea6771b3c21edb27364b52a50a64f3d45a | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | Goof-fr/OPHD | f4019db3e2681d5d371a3c87a6e47dd8a817fdb0 | ab3414181b04ab2757b124d81fd5592f930c5370 | refs/heads/master | 2020-03-14T03:24:06.699220 | 2020-01-27T19:44:02 | 2020-01-27T19:44:02 | 236,367,556 | 2 | 0 | BSD-3-Clause | 2020-01-26T19:54:36 | 2020-01-26T19:54:35 | null | UTF-8 | C++ | false | false | 530 | h | University.h | #pragma once
#include "Structure.h"
#include "../../Constants.h"
class University : public Structure
{
public:
University() : Structure(constants::UNIVERSITY, "structures/university.sprite", CLASS_UNIVERSITY)
{
sprite().play(constants::STRUCTURE_STATE_CONSTRUCTION);
maxAge(500);
turnsToBuild(4);
requiresCHAP(true);
}
virtual ~University()
{}
protected:
virtual void think()
{
}
virtual void defineResourceInput()
{
resourcesIn().energy(1);
}
virtual void defineResourceOutput()
{}
private:
};
|
1af1d1ca9a4c0af95c9b624573ae10ac841185d2 | 604930c37b162a7c16aabda9a2342416f8e64a02 | /Code Chef C++ Answers/DWNLD.cpp | fb00ed40369ee2d8ac624320dd123f96e6c7cc64 | [] | no_license | DecimatorMind/Code-Chef-CPP-Answers | b6357188769e4c0227cdcf3cc65f91e09e9ca01a | 86ca3f4f6d477d4f05fc2368c1a54aa8bfdc817f | refs/heads/master | 2023-03-02T17:13:53.410553 | 2021-02-15T03:25:58 | 2021-02-15T03:25:58 | 275,600,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 686 | cpp | DWNLD.cpp | //
// DWNLD.cpp
// Code Chef C++ Answers
//
// Created by Pranjal Bhardwaj on 31/07/20.
// Copyright © 2020 Pranjal Bhardwaj. All rights reserved.
//
#include <iostream>
using namespace std;
int dwnld(){
int iter {};
cin >> iter;
for (int i = 0; i < iter; i++){
int n,k,result {};
cin >> n >> k;
for (int j = 0; j < n; j++) {
int t,d;
cin >> t >> d;
if(t-k >= 0){
result += (t-k)*d;
k = 0;
} else if(k == 0){
result += t*d;
} else {
k -= t;
}
}
cout << result << endl;
}
return 0;
}
|
92d0b3d7318002519808e4dc9fe0185a96d45bf0 | 094507fb25fd5774bbf89b5d84c15a132b596e78 | /StepFeatures.cpp | d0d79a6a869ec4849e9ddd0355d96cdccdfca8c4 | [] | no_license | csverma610/PocketDetector | e45c806bd71c7979c6ba9e14fe4eeb135741da15 | c4b372c79720b346ae48462af59d80355f95e536 | refs/heads/master | 2020-04-03T01:29:51.566696 | 2018-10-27T06:18:36 | 2018-10-27T06:18:36 | 154,932,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,762 | cpp | StepFeatures.cpp | #include "GModel.hpp"
//////////////////////////////////////////////////////////////////////////////////////
void ReorientModel( JFace *seedface, GModel *model)
{
}
//////////////////////////////////////////////////////////////////////////////////////
void BFSearch( JDualNode *node, JGraph *graph, JFaceSequence &sidefaces)
{
}
//////////////////////////////////////////////////////////////////////////////////////
JPocket* SearchPocket( JFace *seedface, GModel *model )
{
if( seedface == nullptr) return nullptr;
if( !seedface->isPlanar() ) return nullptr;
if( !seedface->isCircular() ) return nullptr;
ReorientModel(seedface, model);
JGraph *graph = model->getGraph();
JDualNode *dualnode = seedface->getDualNode();
JFaceSequence sidefaces;
BFSearch(dualnode, graph, sidefaces);
if( sidefaces.empty() ) return nullptr;
JPocket *newpocket = new JPocket;
newpocket->baseface = seedface;
newpocket->sidefaces = sidefaces;
return newpocket;
}
//////////////////////////////////////////////////////////////////////////////////////
vector<JPocket*> SearchPockets(GModel *gmodel)
{
vector<JPocket*> pockets;
size_t numfaces = gmodel->getSize(2);
for( size_t i = 0; i < numfaces; i++) {
JFace *face = gmodel->getFaceAt(i);
JPocket *pocket = SearchPocket(face, gmodel);
if( pocket ) pockets.push_back(pocket);
}
}
//////////////////////////////////////////////////////////////////////////////////////
/*
int main(int argc, char **argv)
{
if( argc != 2) {
cout << "Usage: " << argv[0] << " Stepfile" << endl;
return 1;
}
GModel *gmodel = new GModel();
assert( gmodel ) ;
gmodel->readSTEP( argv[1] );
gmodel->getOCCInfo();
}
*/
|
00d1d1161cb469569a61f3b4d2af4ff703fd6367 | be2e23022d2eadb59a3ac3932180a1d9c9dee9c2 | /GameServer/MapGroupKernel/NpcStorage.h | 98d53170176d6f4f8292931cc5f4550b75abe825 | [] | no_license | cronoszeu/revresyksgpr | 78fa60d375718ef789042c452cca1c77c8fa098e | 5a8f637e78f7d9e3e52acdd7abee63404de27e78 | refs/heads/master | 2020-04-16T17:33:10.793895 | 2010-06-16T12:52:45 | 2010-06-16T12:52:45 | 35,539,807 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 880 | h | NpcStorage.h |
#pragma once
#include "Item.h"
#include "Myheap.h"
#include "Package.h"
class CPackage;
class CNpcTrunk
{
protected:
CNpcTrunk();
virtual ~CNpcTrunk();
public:
static CNpcTrunk* CreateNew() { return new CNpcTrunk; }
ULONG Release() { delete this; return 0; }
public:
bool Create(PROCESS_ID, OBJID idRecordNpc, int nSize, int nPosition = ITEMPOSITION_TRUNK);
CPackage* QueryPackage(OBJID idPlayer=ID_NONE); // { ASSERT(m_pPackage); return m_pPackage; }
bool IsPackageFull(OBJID idPlayer=ID_NONE) { return QueryPackage(idPlayer)->GetAmount() >= m_nSize; }
bool IsEmpty(OBJID idPlayer=ID_NONE) { return QueryPackage(idPlayer)->GetAmount() == 0; }
protected:
CPackage* m_pPackage;
int m_nSize;
int m_nPosition;
OBJID m_idRecordNpc;
private: // ctrl
PROCESS_ID m_idProcess;
MYHEAP_DECLARATION(s_heap)
};
|
60c9c23874ed752ebdf41631d9e90849fd7dcb5f | 0f15a1536f6fe86ffb49092abb30b38217c376c6 | /MFC_SDI_Client/MFC_SDI_Client/WarningDlg.h | fd3c8bb1cb1ab378e1441354033c391938705878 | [] | no_license | jiangkid/smart-lighting | a5898a59a7ece0e1ff9ef1dd1778af9d047a0f84 | 0f6a32cbc0f30e730271c2c2ec2bddd4c6edf326 | refs/heads/master | 2020-06-04T07:20:40.718285 | 2012-06-20T06:05:23 | 2012-06-20T06:05:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 908 | h | WarningDlg.h | #pragma once
#include "afxwin.h"
//#include "ControlWaringDlg.h"
// CWarningDlg dialog
class CWarningDlg : public CDialog
{
DECLARE_DYNAMIC(CWarningDlg)
public:
CWarningDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CWarningDlg();
// Dialog Data
enum { IDD = IDD_WARNING_DLG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
protected:
virtual void OnOK();
public:
CReportCtrl m_ListWarning;
CDateTimeCtrl m_DataBegin;
CDateTimeCtrl m_DataEnd;
afx_msg void OnBnClickedBtnGet();
void OneWarningToShow(WarningInfo* pWarning, int nRow);
void AllWarningToShow(int nWarningCount);
afx_msg void OnNMDblclkWarningDlg(NMHDR *pNMHDR, LRESULT *pResult);
CComboBox m_TheGID;
int warningpackCount;
//CControlWaringDlg* m_pCtrlWarn;
CComboBox m_Box;
}; |
5d96390d723adc88dbe1dd46ff843fc588a0b426 | 726431091eb4b9ada6effd22ec04f1a8f1e84cc6 | /RadixSort.cpp | b906455319376df40d550c686ea38ba476429780 | [] | no_license | AjaySankar/Algorithms | c54004dc7ce2f65a01fa326fd347084d2a056b5b | e3edad23510eda5d176609c0ad8df70ad267c2cd | refs/heads/master | 2021-01-19T08:58:33.994594 | 2019-05-11T06:18:44 | 2019-05-11T06:18:44 | 87,701,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | cpp | RadixSort.cpp | #include <iostream>
using namespace std;
#define MAX 10
//MAX defines the range of elements in the array 0 to MAX-1
void PrintArray(int *arr,int n){
for(int i=0;i<n;i++)
cout << arr[i] << " ";
}
void CountSort(int *arr,int n,int exp){
int count[MAX];
for(int i=0;i<MAX;i++)
count[i]=0;
for(int i=0;i<n;i++)
count[(arr[i]/exp)%10]++;
for(int i=1;i<MAX;i++)
count[i]=count[i]+count[i-1];
int sorted_arry[n];
for(int i=0;i<n;i++){
int pos=count[(arr[i]/exp)%10];
sorted_arry[pos-1]=arr[i];
count[(arr[i]/exp)%10]--;
}
for(int i=0;i<n;i++)
arr[i]=sorted_arry[i];
}
int getMax(int *arr,int n){
int max=arr[0];
for(int i=0;i<n;i++){
if(arr[i]>max)
max=arr[i];
}
return max;
}
void RadixSort(int *arr,int n){
int max=getMax(arr,n);
for(int exp=1;max/exp>0;exp=exp*10)
CountSort(arr,n,exp);
}
int main() {
int arr[]={1, 4, 1, 2, 7, 5, 2};
int n=sizeof(arr)/sizeof(*arr);
RadixSort(arr,n);
PrintArray(arr,n);
return 0;
}
|
3ea9126d2e6f0aee344bd16638f0dfb6b7d74666 | d352cb980107b8665e63c8b8b21e2921af53b8d3 | /toph/implementation/version-checker.cpp | 8d5d66c10d8b6a6ee3c3d79100c509df76f2a003 | [] | no_license | sir-rasel/Online_Judge_Problem_Solve | 490949f0fc639956b20f6dec32676c7d8dc66a81 | 9fb93ff4d143d56228443e55e8d8dac530ce728b | refs/heads/master | 2021-06-03T19:48:04.700992 | 2021-03-30T16:41:03 | 2021-03-30T16:41:03 | 133,169,776 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | cpp | version-checker.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
string a,b;
cin >> a >> b;
stringstream as(a),bs(b);
int x,y;
bool flag=true;
while(as >> x && bs >> y){
if(x>y) break;
else if(x<y) {flag=false;break;}
char c;
as>>c;
bs>>c;
}
if(flag) cout << a << "\n";
else cout << b << "\n";
return 0;
}
|
fbe2352ecfd5bb4655e548b66732f240f3298d50 | 3873163d3ccfd45121d364010b52108cc5118378 | /lab04/rectangle.cpp | 7602227ca94e2768b78a5bc514cda50c60c8a052 | [
"MIT"
] | permissive | juditacs/bop2 | d518f0e5dea59b0ac0a0b86813f3149c0aa5a7cf | 239c59bf07fa95d2e0f3f780e219b9aa94456576 | refs/heads/master | 2021-01-07T08:31:01.475319 | 2020-05-06T16:12:59 | 2020-05-06T16:12:59 | 241,634,932 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 677 | cpp | rectangle.cpp | #include "rectangle.h"
Rectangle::Rectangle(double a, double b) {
if (a < 0) {
std::cerr << "Rectangle side [a] cannot be negative, setting it to 0\n";
a = 0;
}
if (b < 0) {
std::cerr << "Rectangle side [b] cannot be negative, setting it to 0\n";
b = 0;
}
this->a = a;
if (b == 0) this->b = a;
else this->b = b;
}
double Rectangle::Perimeter() const {
return 2*(a+b);
}
double Rectangle::Area() const {
return a*b;
}
void Rectangle::print() const {
std::cout << "Sides a=" << a << ", b=" << b <<"\n";
std::cout << "Perimeter=" << Perimeter() << "\n";
std::cout << "Area=" << Area() << "\n";
}
|
e87776ac62b66a479ffeb6e3c39f25baec829bca | d743b2d40957a3c07e8bfc03ea69e459c96ace56 | /201 Bitwise AND of Numbers Range/201.cpp | 107029d918b632fdbeb0e455c1cddc8441ab469b | [] | no_license | TakuyaKimura/Leetcode | f126e72458f7a1b6eb8af9dd874fc2ee77eefe01 | 6f68ed674a3de7d2277c256583c67dda73092dc0 | refs/heads/master | 2021-01-10T21:39:48.227089 | 2016-02-06T11:08:29 | 2016-02-06T11:08:29 | 40,781,363 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | cpp | 201.cpp | /*
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
*/
#include <cmath>
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
while (n > m)
n &= n - 1; // clear the least significant set bit
return n;
}
};
class Solution2 {
public:
int rangeBitwiseAnd(int m, int n) {
int count = 0;
while (m != n)
{
m >>= 1;
n >>= 1;
++count;
}
return m << count;
}
};
class Solution3 {
public:
int rangeBitwiseAnd(int m, int n) {
if (m == n)
return m;
// The highest bit of 1 in m^n is the highest changed bit
// to get the bit length, have to add 1 to the logarithm
int bitlen = log2(m ^ n) + 1; // If argument is zero, it may cause a pole error (depending on the library implementation)
return m >> bitlen << bitlen;
}
};
class Solution4 {
public:
int rangeBitwiseAnd(int m, int n) {
if (m == n)
return m;
int bitlen = log2(n - m) + 1;
return m & n & (~0 << bitlen);
}
}; |
76707f55e03805be430e9101d02ce07a54fccd4a | d4645102c926c4406713bccbb00b889d5e46f593 | /LibraryDemo/LibraryDemo/ObjectManager/ObjectManager.cpp | 6217459fdbc218ce3dc074098d68e5c22a808082 | [] | no_license | shibata0430/DemoLibrary | 5646632185a36a7e6103d8d7bab6817882094c04 | 9d473344d55f1b7a4a5a1546fc13738180c0c58c | refs/heads/master | 2021-01-18T16:45:59.794666 | 2017-06-01T16:12:17 | 2017-06-01T16:12:17 | 86,765,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 790 | cpp | ObjectManager.cpp | /**
* @file ObjectManager.cpp
* @breif 出てくるオブジェクトを管理しているクラス実装
* @author shibata
*/
#include "ObjectManager.h"
#include "../Character/CharacterManager.h"
#include "../Field/FieldManager.h"
#include <Library\DebugSystem.h>
#include <Library\Define.h>
ObjectManager::ObjectManager() :
m_pCharacterManager(New CharacterManager),
m_pFieldManager(New FieldManager)
{
MyAssert(m_pCharacterManager, "NULLが入っています");
MyAssert(m_pFieldManager, "NULLが入っています");
}
ObjectManager::~ObjectManager()
{
SafeDelete(m_pCharacterManager);
SafeDelete(m_pFieldManager);
}
void ObjectManager::Control()
{
m_pCharacterManager->Control();
}
void ObjectManager::Draw()
{
m_pFieldManager->Drwa();
m_pCharacterManager->Draw();
}
|
0f1efbe2d20de94562587f204ba57890daa85f00 | 6b01b545dc9fe1222f963344c5ba306863996933 | /include/Graph.hpp | 5c94ea69fc4a3dd06165c66340e1ab87ff45e6e5 | [
"MIT"
] | permissive | SynapticNulship/Anibots | bdd2a94323355026c7595f2c3f0c7418031e33e5 | c1737c7e2aec710b96a4b48433b6ff45fbb0bb46 | refs/heads/master | 2018-09-06T15:33:50.901558 | 2013-09-19T04:28:48 | 2013-09-19T04:28:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,457 | hpp | Graph.hpp | /** @file
@author Samuel H. Kenyon <sam@synapticnulship.com>
http://synapticnulship.com
@copyright Copyright (c) 2004-2013 Samuel H. Kenyon. This is open source,
made available under the MIT License (see the accompanying file LICENSE).
*/
#ifndef _GRAPH_H_
#define _GRAPH_H_
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include "utils.hpp"
namespace anibots
{
#define PROX_ID_OFFSET 26
#define PROX_ID_START 91
typedef char NodeID_t; //small nets...char allows you to use letters in the data file
typedef int HopMetric_t;
typedef unsigned int edge_t;
template<typename NodePtrType_t>
struct NodeAdjacency
{
NodePtrType_t node;
//NodeID_t ID;
edge_t edge;
//HopMetric_t distance;
};
struct PathHistory
{
HopMetric_t hopCount;
std::vector<NodeID_t> sequence;
};
/**
Graph class loads a network description text file.
Graph definition file format: see accompanying file "graph_file_format.txt".
@todo Should anigraf-specific functions be in another class?
@todo Should social pref graphs be in their own class?
@todo the Node struct itself shouldn't contain the adjaceny list--Graph should
use a wrapper class to do that, so the network is a graph of wrapper class instances
@todo Add support to load/save GraphML and/or GEXF files
@todo Use Boost graph?
*/
template <class Node>
class Graph
{
public:
///@todo deprecate the vector in favor of a map?
//typedef std::vector<std::unique_ptr<Node> > NodeList_t;
typedef std::vector<Node*> NodeList_t;
typedef typename NodeList_t::const_iterator NodeListConstIter_t;
typedef std::vector<NodeID_t> NodeSequence_t;
//typedef map< NodeID_t, Node* > NodeMap_t;
typedef typename Node::adjacency_t NodeAdjacency_t;
typedef typename std::vector<NodeAdjacency_t>::iterator NodeAdjIter_t;
typedef typename std::vector<NodeAdjacency_t>::const_iterator NodeAdjConstIter_t;
Graph();
~Graph();
//mutators
bool LoadGraph(std::string inFilename);
bool LoadProxyWeights(std::string inFilename);
bool Proxify(std::string proxyEdgeFilename, const bool proxyWeightsProportional, const float proxyWeightsProportion);
bool ProxifyWithWeights(std::string proxyEdgeFilename, std::vector<int>* proxy_weights);
bool ProxifyWithWeights(std::string proxyEdgeFilename, std::string proxyWeightsFilename);
void RandomizeWeights(int quantization, int quantDiff, bool irregular );
void RandomizeWeightsRange(int min, int max, int quantization=3, int quantDiff=3 );
void RandomizeEdges();
void SetSingleTopFlag(const bool flag) { m_SingleTopFlag = flag; }
int UpdateProxyWeights(const NodeID_t node_id, std::stringstream& logstream);
void CopyWeights(const NodeList_t* n);
int SetWeight(const NodeID_t node_id, const int weight);
//void SetLogStream(stringstream* ss) { m_LogRef = *ss; }
//both accessor & mutator
Node* FindNode(const NodeID_t fid);
//non const accessor:
Node* FindExistingNode(const NodeID_t fid);
//accessors
const Node* FindExistingNode(const NodeID_t fid) const;
const NodeList_t* NodeList() const { return &m_Network; }
const HopMetric_t FindCycle(const Node& src, const NodeID_t dest) const;
const HopMetric_t HopDistance(const Node& src, const NodeID_t dest, int kDepth) const;
const HopMetric_t HopDistance(const NodeID_t src, const NodeID_t dest) const;
const HopMetric_t RecursiveTraverse(const Node& src, const NodeID_t dest, const NodeID_t routeID) const;
PathHistory RecursiveTraverseHistoric(
const Node& src, const NodeID_t dest, const NodeID_t routeID) const;
bool FindNodeInSequence(const NodeID_t dest, const NodeSequence_t& seq) const;
bool FindTopCycles(unsigned int cycleLength) const;
void ShowTopCyclePatterns(Graph<Node>* original, unsigned int cycleLength) const;
const NodeSequence_t & TopCycle(int index) const { return m_TopCycles.at(index); }
bool IsAdjacentTo(const NodeID_t a, const NodeID_t b) const;
void DisplayNetPretty(bool showWeights = true) const;
void DisplayNetPrettyString(bool showWeights, std::stringstream& ss) const;
void DisplayNet() const;
void DisplayNetWeights() const;
void DisplayRoutes() const;
std::string GetNodeLabel(const char id) const;
void ClearFlags() const;
const bool SingleTopFlag() const { return m_SingleTopFlag; }
///@hack
mutable int m_Pattern3B;
mutable int m_Pattern3x;
protected:
bool CloneGraph(const int numClones, std::vector<int>* proxy_weights=NULL);
bool LoadProxyEdges(std::string proxyEdgeFilename);
void PrintNodeLabel(const char id, std::stringstream& ss) const;
private:
Graph(const Graph& rh);
NodeList_t m_Network;
mutable NodeID_t m_StartID;
mutable int m_RecurseCount;
mutable int m_RecurseMax;
mutable bool m_Verbose; //for debugging
mutable NodeSequence_t m_CurrPath;
mutable std::vector< NodeSequence_t > m_Routes;
mutable std::vector< NodeSequence_t > m_TopCycles;
bool m_SingleTopFlag;
NodeID_t prevProxyWinner;
std::vector<int> m_ProxyWeights;
bool m_ProxyWeightsGiven;
bool m_ProxyWeightsProportional;
float m_ProxyWeightsProportion;
// stringstream m_LogDefault;
};
#include "Graph.cpp"
}
#endif
|
7ab93f7e5033f1dd39216e69d0d8b7fab02d466c | 88b46d6d433a5b4fda84665d78ef05dd972814cd | /src/gui/widgets/detailedit.hpp | f2ac1ecb263d7d6d33f17005dd810a00dcfb86f5 | [] | no_license | yamamushi/Moneychanger | 5f9261c263c7b8421a1028d9902caccd279b1539 | 5c918bfc124baae454eecc95321f952a6c5ce4c0 | refs/heads/master | 2021-01-18T04:04:11.414157 | 2016-02-23T17:30:53 | 2016-02-23T17:30:53 | 26,220,373 | 1 | 1 | null | 2015-01-20T11:25:37 | 2014-11-05T13:18:30 | null | UTF-8 | C++ | false | false | 5,920 | hpp | detailedit.hpp | #ifndef DETAILEDIT_HPP
#define DETAILEDIT_HPP
#include "core/WinsockWrapper.h"
#include "core/ExportWrapper.h"
#include <QPointer>
#include <QWidget>
#include <QTabWidget>
#include <QVBoxLayout>
#include "core/mapidname.hpp"
namespace Ui {
class MTDetailEdit;
}
class MTEditDetails;
class Moneychanger;
class DlgMarkets;
class MTDetailEdit : public QWidget
{
Q_OBJECT
bool m_bFirstRun;
public:
enum DetailEditType {
DetailEditTypeError,
DetailEditTypeContact,
DetailEditTypeNym,
DetailEditTypeServer,
DetailEditTypeAsset,
DetailEditTypeAccount,
DetailEditTypeMarket,
DetailEditTypeOffer,
DetailEditTypeAgreement,
DetailEditTypeCorporation,
DetailEditTypeTransport
};
explicit MTDetailEdit(QWidget *parent);
~MTDetailEdit();
void SetPreSelected(QString strSelected);
void EnableAdd (bool bEnabled) { m_bEnableAdd = bEnabled; }
void EnableDelete(bool bEnabled) { m_bEnableDelete = bEnabled; }
// --------------------------------
void SetMarketMap(QMultiMap<QString, QVariant> & theMap);
void SetOfferMap(QMap<QString, QVariant> & theMap);
// --------------------------------
void SetMarketNymID(QString qstrNymID) { m_qstrMarketNymID = qstrNymID; }
QString GetMarketNymID() const { return m_qstrMarketNymID; }
// --------------------------------
// NOTE: Used by marketdetails and offerdetails.
// WARNING: THIS MAY CONTAIN "all" instead of a server ID!
//
void SetMarketNotaryID(QString qstrNotaryID) { m_qstrMarketNotaryID = qstrNotaryID; }
QString GetMarketNotaryID() const { return m_qstrMarketNotaryID; }
// --------------------------------
void SetMarketID(QString qstrMarketID) { m_qstrMarketID = qstrMarketID; }
QString GetMarketID() const { return m_qstrMarketID; }
// --------------------------------
void SetLawyerID(QString qstrLawyerID) { m_qstrLawyerID = qstrLawyerID; }
QString GetLawyerID() const { return m_qstrLawyerID; }
// --------------------------------
// Use for modeless or modal dialogs.
void dialog(DetailEditType theType, bool bIsModal=false);
// Use for widget that appears on a parent dialog.
void show_widget(DetailEditType theType);
// --------------------------------
void FirstRun(MTDetailEdit::DetailEditType theType); // This only does something the first time you run it.
// --------------------------------
void RefreshRecords();
void ClearRecords();
void ClearContents();
// --------------------------------
void RefreshMarketCombo();
void SetCurrentMarketIDBasedOnIndex(int index);
// --------------------------------
void RefreshLawyerCombo();
void SetCurrentLawyerIDBasedOnIndex(int index);
// --------------------------------
bool getAccountIDs(QString & qstrAssetAcctID, QString & qstrCurrencyAcctID); // For a market offer.
// --------------------------------
QWidget * GetTab(int nTab);
// --------------------------------
QMultiMap<QString, QVariant> * m_pmapMarkets=nullptr; // do not delete. For reference only.
QMap <QString, QVariant> * m_pmapOffers=nullptr; // do not delete. For reference only.
// --------------------------------
int m_nCurrentRow = -1;
QString m_qstrCurrentID;
QString m_qstrCurrentName;
mapIDName m_map; // qstr/qstr for id/name
// ----------------------------------
// Only used in DetailEdit for Offer Details. m_mapMarkets is a Map that uniquely identifies each marketID/scale with a Name.
// (It's a copy of m_map from the MarketDetails DetailEdit.)
// Whereas m_pOwner->m_pmapMarkets is a MultiMap that contains multiple entries with the same id/scale (each for a different server.)
// (It's a pointer to the DlgMarkets m_mapMarkets multimap.)
// The first is used to populate the combo box, whereas the second is used to loop through actual MarketData pointers.
//
mapIDName m_mapMarkets;
QString m_qstrMarketID;
// ----------------------------------
// Only used in DetailEdit for Smart Contracts.
//
mapIDName m_mapLawyers;
QString m_qstrLawyerID;
// ----------------------------------
void SetType(DetailEditType theType) { m_Type = theType; }
signals:
void balancesChanged();
void CurrentMarketChanged(QString qstrMarketID);
void NeedToLoadOrRetrieveOffers(QString qstrMarketID);
public slots:
void onBalancesChangedFromAbove();
void onBalancesChangedFromBelow(QString qstrAcctID);
void onRefreshRecords();
void onExpertModeUpdated(bool bExpertMode);
void onMarketIDChangedFromAbove(QString qstrMarketID);
void onSetNeedToRetrieveOfferTradeFlags();
protected:
// --------------------------------
QString m_qstrMarketNymID; // used by marketdetails and offerdetails.
QString m_qstrMarketNotaryID; // used by marketdetails and offerdetails.
// ----------------------------------
bool m_bEnableAdd=false;
bool m_bEnableDelete=false;
// ----------------------------------
QString m_PreSelected;
// ----------------------------------
QPointer<MTEditDetails> m_pDetailPane;
QPointer<QVBoxLayout> m_pDetailLayout;
// ----------------------------------
QPointer<QTabWidget> m_pTabWidget;
// ----------------------------------
bool eventFilter(QObject *obj, QEvent *event);
virtual void showEvent(QShowEvent * event);
private slots:
void on_tableWidget_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn);
void on_comboBox_currentIndexChanged(int index);
void on_addButton_clicked();
void on_deleteButton_clicked();
private:
DetailEditType m_Type;
Ui::MTDetailEdit *ui;
};
#endif // DETAILEDIT_HPP
|
ea93a77db0134701f60fd7a4435ba95c7e4cdefd | 9b6b495328298488d853821493bec042270f3e1b | /code/reverseLinkedList.cpp | 16058db20603d26260712f2a77dc4042a3e1882a | [] | no_license | RaymondWaterlooLi/InterviewQuestion | 664a3213cc93504fc0df07f22a411b4e194f116c | b492044c4c7f575dd053afafac4058baa9ed5420 | refs/heads/master | 2020-04-18T00:45:08.249281 | 2020-02-24T21:16:10 | 2020-02-24T21:16:10 | 167,089,641 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 621 | cpp | reverseLinkedList.cpp | //
// Created by Raymond Li on 2019-01-26.
//
#include <iostream>
using namespace std;
struct node {
int num;
node* next;
};
void reverseList(node* t, node* prev) {
while (t != NULL) {
node* temp = t->next;
t->next = prev;
prev = t;
t = temp;
}
}
//int main() {
//// cout << "hey" << endl;
// node* f1 = new node{1,NULL};
// node* f2 = new node{2,NULL};
// node* f3 = new node{3,NULL};
// f1->next = f2;
// f2->next = f3;
// reverseList(f1, NULL);
// while (f3 != NULL) {
// cout << f3->num << endl;
// f3 = f3->next;
// }
//} |
3062593d9d2010a9c8dd8b5513116668eb472921 | a99a27dadf5a47667795f0ecc73fb1510263fc26 | /src/lib/synthetic/TorusField.cpp | b3b5367e363843441823ba176a4999dd672a441e | [
"MIT"
] | permissive | SCIInstitute/Cleaver | 5b9c49aca788dcb7d102e6f1a7253814b37f94df | 04338ff9e68e4cfb9a1bbec36a674e107e44e1f2 | refs/heads/master | 2023-05-27T11:28:54.972421 | 2023-05-14T21:26:48 | 2023-05-14T21:26:48 | 21,179,667 | 1 | 0 | NOASSERTION | 2023-05-14T21:26:50 | 2014-06-24T20:25:44 | C | UTF-8 | C++ | false | false | 1,667 | cpp | TorusField.cpp | #include "TorusField.h"
#include <cmath>
#include <cassert>
#include <vector>
using namespace cleaver;
TorusField::TorusField(const vec3 &cx, float ur, float vr, const BoundingBox &bounds) :
m_bounds(bounds), m_cx(cx), m_ur(ur), m_vr(vr)
{
}
double TorusField::valueAt(double x, double y, double z) const
{
return valueAt(vec3(x,y,z));
}
double TorusField::valueAt(const vec3 &x) const
{
vec3 xx = x - m_cx;
double ring1 = (m_ur - sqrt(xx.y*xx.y + xx.z*xx.z));
double total = ring1*ring1 + xx.x*xx.x - m_vr*m_vr;
return -1*total;
}
void TorusField::setBounds(const BoundingBox &bounds)
{
m_bounds = bounds;
}
BoundingBox TorusField::bounds() const
{
return m_bounds;
}
void getorthobasis(vec3 &v1, vec3 &v2, vec3 &v3)
{
double invLen;
if (fabs(v1[0]) > fabs(v1[1]))
{
invLen = 1.0 / sqrt(v1[0] * v1[0] + v1[2] * v1[2]);
v2[0] = -v1[2] * invLen;
v2[1] = 0.0;
v2[2] = v1[0] * invLen;
}
else
{
invLen = 1.0 / sqrt(v1[1] * v1[1] + v1[2] * v1[2]);
v2[0] = 0.0;
v2[1] = v1[2] * invLen;
v2[2] = -v1[1] * invLen;
}
v3 = cross(v1, v2);
assert(length(v1) > 0.0);
assert(length(v2) > 0.0);
assert(length(v3) > 0.0);
}
std::vector<vec3> TorusField::tensorAt(const vec3 &x) const
{
// first build basis
vec3 out = vec3(x - m_cx);
vec3 up; // = vec3(1,0,0);
vec3 rot; // = normalize(up.cross(out));
float a = 4; // anisotropy factor
getorthobasis(out, up, rot);
std::vector<vec3> tensor;
tensor.push_back(out);
tensor.push_back(up);
tensor.push_back(rot);
return tensor;
}
|
f32580942ad7caf5e65b50a1ef63cfbec0c9873d | 327c8d0a42e42ffc15284c42078fe5b2e91b7358 | /cpp/24.SwapNodesInPairs.cpp | a7196d44f77192f1d37b1c2906f5197a380bdd2e | [] | no_license | HONGJICAI/LeetCode | 90f969f1fd5c33ed5d9202e1898019484dd78f00 | 7170ddea769f9fbcceb1be4d3bad1c4d1fc11db0 | refs/heads/master | 2021-01-19T09:00:57.302687 | 2019-06-30T15:25:05 | 2019-06-30T15:25:05 | 87,710,391 | 0 | 0 | null | 2020-10-03T09:24:58 | 2017-04-09T13:26:54 | C++ | UTF-8 | C++ | false | false | 1,226 | cpp | 24.SwapNodesInPairs.cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution { // recursion 0ms
public:
ListNode* swapPairs(ListNode* head) {
function<ListNode*(ListNode*,ListNode*,ListNode*,ListNode*)> swap= [&swap](ListNode* pre,ListNode *a,ListNode* b,ListNode *cur){
if(a&&b){
b->next=a;
a->next=cur;
if(pre)
pre->next=b;
}
if(cur&&cur->next)
swap(a,cur,cur->next,cur->next->next);
return b;
};
if(head&&head->next)
return swap(nullptr,head,head->next,head->next->next);
return head;
}
};
class Solution { // iteration 4ms
public:
ListNode* swapPairs(ListNode* head) {
if(!head||!head->next)
return head;
auto h=ListNode(0);
h.next=head;
auto p=&h;
while(p->next&&p->next->next){
auto l=p->next,r=p->next->next;
auto next=r->next;
p->next=r;
r->next=l;
l->next=next;
p=l;
}
return h.next;
}
}; |
dc75ebc83abecaac8abbb61448cf32aa7ed2fd87 | c98b2280a8083374d88d26a05edbebe044963ca2 | /Meet_In_The_Middle/1093.cpp | 050881d9a37d5c5476998bec9f3eeb443d47c5f0 | [] | no_license | hihiroo/BOJ | 3b41c3dfb7e317ae76a0ead9261dc177da4f47b8 | c851f3e8e93a353239ce4e25184b2dd97481575b | refs/heads/master | 2022-06-24T08:24:39.639149 | 2022-06-02T04:50:04 | 2022-06-02T04:50:04 | 216,061,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | cpp | 1093.cpp | //스티커 수집
#include<bits/stdc++.h>
#define pb push_back
#define lli long long
#define mp make_pair
#define fst first
#define snd second
using namespace std;
#define it map<int,int>::iterator
int n, price[35], value[35],k;
map<int,int> r,l;
void f(int idx, int p, int val, bool isLeft){
if(isLeft && idx == (n+1)/2){
if(l.count(-val) && l[-val]<p);
else l[-val] = p;
return;
}
if(!isLeft && idx == n){
if(r.count(-val) && r[-val]<p);
else r[-val] = p;
return;
}
f(idx+1,p,val,isLeft);
f(idx+1,p+price[idx],val+value[idx],isLeft);
}
int main(){
cin >> n;
for(int i=0; i<n; i++) cin >> price[i];
for(int i=0; i<n; i++) cin >> value[i];
cin >> k;
int sum = 0, cnt, a;
cin >> cnt;
while(cnt--){
cin >> a;
sum += price[a];
}
f(0,0,0,1);
f((n+1)/2,0,0,0);
vector<int> lkey, rkey;
int min_v = 1e9;
for(it i=l.begin(); i!=l.end(); i++){
min_v = min(min_v, i->snd);
i->snd = min_v;
lkey.pb(-(i->fst));
}
min_v = 1e9;
for(it i=r.begin(); i!=r.end(); i++){
min_v = min(min_v, i->snd);
i->snd = min_v;
rkey.pb(-(i->fst));
}
sort(lkey.begin(), lkey.end());
sort(rkey.begin(),rkey.end());
int ans = 1e9;
for(int i=0; i<lkey.size(); i++){
int lval = lkey[i];
int idx = lower_bound(rkey.begin(), rkey.end(),
max(0,k-lval))-rkey.begin();
if(idx == rkey.size()) continue;
ans = min(ans,r[-rkey[idx]] + l[-lval]);
}
for(int i=0; i<rkey.size(); i++){
int rval = rkey[i];
int idx = lower_bound(lkey.begin(), lkey.end(),
max(0,k-rval))-lkey.begin();
if(idx == lkey.size()) continue;
ans = min(ans,r[-rval]+l[-lkey[idx]]);
}
if(ans == 1e9) return cout << -1,0;
cout << max(0,ans-sum);
}
|
b082550e950ee924b57a4fdd896f7c19a93626c0 | 4732757f4f519ca274d77230d11c1607f4fef0b9 | /src/neural/global_neural_network_param.h | d79b8eeb75590cee89255c398a03542a9b589ca7 | [] | no_license | allanj/StatNLP-Framework | b97b6d7e0ff284787d9636131c633908fb508948 | b862c9f54e0bbed4af1b3c90a51959793d58e585 | refs/heads/master | 2020-03-28T21:08:08.505389 | 2018-09-17T12:24:09 | 2018-09-17T12:24:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,250 | h | global_neural_network_param.h | //
// Created by ngs on 03/09/2018.
//
#ifndef STATNLP_GLOBAL_NN_PARAM_H
#define STATNLP_GLOBAL_NN_PARAM_H
#include "neural_network.h"
#include "src/common/common.h"
#include "dynet_interface.h"
#include "neural_factory.h"
class Network;
class LocalNetworkParam;
class GlobalNeuralNetworkParam{
public:
GlobalNeuralNetworkParam();
~GlobalNeuralNetworkParam();
void SetLearningState();
void InitNetwork();
std::vector<NeuralNetwork *> *GetNNVect();
void Forward();
void Backward();
double GetNNScore(Network *ptr_network, int parent_k, int children_k_index);
void SetNNGradientOutput(double count, Network *ptr_network, int parent_k, int children_k_index);
void ResetAllNNGradient();
void SetNNVect(std::vector<NeuralNetwork *> *ptr_nn_vec);
void InitNNParameter(int &argc, char **&argv, unsigned random_seed = 0, bool shared_parameters = false);
DynetFunctionHelper *GetDynetFunctionHelper();
private:
std::vector<NeuralNetwork *> *ptr_nn_vec_;
LocalNetworkParam **pptr_param_l_;
//the nerual net's internal weight and gradient;
StatNLP::NeuralParameter *ptr_nn_param_;
DynetFunctionHelper *ptr_call_dynet_;
NeuralFactory *ptr_nf_;
};
#endif //STATNLP_GLOBAL_NN_PARAM_H
|
9da3972e7ac82f486d240d3b72cbfbe8e625b1cb | 3c89528fa43ccd6bd22e593eac571aefa00766e0 | /src/main/cpp/Balau/ThirdParty/Date/tz_private.hpp | 07800862ccfd6d282dc31d0dc1c5dbbd6296d808 | [
"BSL-1.0"
] | permissive | pylot/balau | f371e54ec94e7ebc08d973105bd17e052e8a7157 | 079a7ad4dfa35f179454b543af9d3f10c870f271 | refs/heads/master | 2020-09-21T15:58:18.897256 | 2019-11-24T09:00:21 | 2019-11-24T09:00:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,698 | hpp | tz_private.hpp | // The MIT License (MIT)
//
// Copyright (c) 2015, 2016 Howard Hinnant
//
// 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.
//
// Our apologies. When the previous paragraph was written, lowercase had not yet
// been invented (that would involve another several millennia of evolution).
// We did not mean to shout.
#ifndef BALAU_TP__DATE__TZ_PRIVATE
#define BALAU_TP__DATE__TZ_PRIVATE
#if !defined(_MSC_VER) || (_MSC_VER >= 1900)
#include<Balau/ThirdParty/Date/tz.hpp>
#else
#include<Balau/ThirdParty/Date/date.hpp>
#include <vector>
#endif
namespace Balau {
namespace Date {
namespace detail {
#if !USE_OS_TZDB
enum class tz {
utc, local, standard
};
//forward declare to avoid warnings in gcc 6.2
class MonthDayTime;
std::istream & operator >>(std::istream & is, MonthDayTime & x);
std::ostream & operator <<(std::ostream & os, const MonthDayTime & x);
class MonthDayTime {
private:
struct pair {
#if defined(_MSC_VER) && (_MSC_VER < 1900)
pair() : month_day_(Balau::Date::jan / 1), weekday_(0U) {}
pair(const Balau::Date::month_day& month_day, const Balau::Date::weekday& weekday)
: month_day_(month_day), weekday_(weekday) {}
#endif
Balau::Date::month_day month_day_;
Balau::Date::weekday weekday_;
};
enum Type {
month_day, month_last_dow, lteq, gteq
};
Type type_ { month_day };
#if !defined(_MSC_VER) || (_MSC_VER >= 1900)
union U
#else
struct U
#endif
{
Balau::Date::month_day month_day_;
Balau::Date::month_weekday_last month_weekday_last_;
pair month_day_weekday_;
#if !defined(_MSC_VER) || (_MSC_VER >= 1900)
U() : month_day_ { Balau::Date::jan / 1 } {}
#else
U() :
month_day_(Balau::Date::jan/1),
month_weekday_last_(Balau::Date::month(0U), Balau::Date::weekday_last(Balau::Date::weekday(0U)))
{}
#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900)
U & operator =(const Balau::Date::month_day & x);
U & operator =(const Balau::Date::month_weekday_last & x);
U & operator =(const pair & x);
} u;
std::chrono::hours h_ { 0 };
std::chrono::minutes m_ { 0 };
std::chrono::seconds s_ { 0 };
tz zone_ { tz::local };
public:
MonthDayTime() = default;
MonthDayTime(local_seconds tp, tz timezone);
MonthDayTime(const Balau::Date::month_day & md, tz timezone);
Balau::Date::day day() const;
Balau::Date::month month() const;
tz zone() const { return zone_; }
void canonicalize(Balau::Date::year y);
sys_seconds to_sys(Balau::Date::year y, std::chrono::seconds offset, std::chrono::seconds save) const;
sys_days to_sys_days(Balau::Date::year y) const;
sys_seconds to_time_point(Balau::Date::year y) const;
int compare(Balau::Date::year y, const MonthDayTime & x, Balau::Date::year yx, std::chrono::seconds offset,
std::chrono::minutes prev_save) const;
friend std::istream & operator >>(std::istream & is, MonthDayTime & x);
friend std::ostream & operator <<(std::ostream & os, const MonthDayTime & x);
};
// A Rule specifies one or more set of datetimes without using an offset.
// Multiple dates are specified with multiple years. The years in effect
// go from starting_year_ to ending_year_, inclusive. starting_year_ <=
// ending_year_. save_ is in effect for times from the specified time
// onward, including the specified time. When the specified time is
// local, it uses the save_ from the chronologically previous Rule, or if
// there is none, 0.
//forward declare to avoid warnings in gcc 6.2
class Rule;
bool operator ==(const Rule & x, const Rule & y);
bool operator <(const Rule & x, const Rule & y);
bool operator ==(const Rule & x, const Balau::Date::year & y);
bool operator <(const Rule & x, const Balau::Date::year & y);
bool operator ==(const Balau::Date::year & x, const Rule & y);
bool operator <(const Balau::Date::year & x, const Rule & y);
bool operator ==(const Rule & x, const std::string & y);
bool operator <(const Rule & x, const std::string & y);
bool operator ==(const std::string & x, const Rule & y);
bool operator <(const std::string & x, const Rule & y);
std::ostream & operator <<(std::ostream & os, const Rule & r);
class Rule {
private:
std::string name_;
Balau::Date::year starting_year_ { 0 };
Balau::Date::year ending_year_ { 0 };
MonthDayTime starting_at_;
std::chrono::minutes save_ { 0 };
std::string abbrev_;
public:
Rule() = default;
explicit Rule(const std::string & s);
Rule(const Rule & r, Balau::Date::year starting_year, Balau::Date::year ending_year);
const std::string & name() const { return name_; }
const std::string & abbrev() const { return abbrev_; }
const MonthDayTime & mdt() const { return starting_at_; }
const Balau::Date::year & starting_year() const { return starting_year_; }
const Balau::Date::year & ending_year() const { return ending_year_; }
const std::chrono::minutes & save() const { return save_; }
static void split_overlaps(std::vector <Rule> & rules);
friend bool operator ==(const Rule & x, const Rule & y);
friend bool operator <(const Rule & x, const Rule & y);
friend bool operator ==(const Rule & x, const Balau::Date::year & y);
friend bool operator <(const Rule & x, const Balau::Date::year & y);
friend bool operator ==(const Balau::Date::year & x, const Rule & y);
friend bool operator <(const Balau::Date::year & x, const Rule & y);
friend bool operator ==(const Rule & x, const std::string & y);
friend bool operator <(const Rule & x, const std::string & y);
friend bool operator ==(const std::string & x, const Rule & y);
friend bool operator <(const std::string & x, const Rule & y);
friend std::ostream & operator <<(std::ostream & os, const Rule & r);
private:
Balau::Date::day day() const;
Balau::Date::month month() const;
static void split_overlaps(std::vector <Rule> & rules, std::size_t i, std::size_t & e);
static bool overlaps(const Rule & x, const Rule & y);
static void split(std::vector <Rule> & rules, std::size_t i, std::size_t k, std::size_t & e);
};
inline bool operator !=(const Rule & x, const Rule & y) { return !(x == y); }
inline bool operator >(const Rule & x, const Rule & y) { return y < x; }
inline bool operator <=(const Rule & x, const Rule & y) { return !(y < x); }
inline bool operator >=(const Rule & x, const Rule & y) { return !(x < y); }
inline bool operator !=(const Rule & x, const Balau::Date::year & y) { return !(x == y); }
inline bool operator >(const Rule & x, const Balau::Date::year & y) { return y < x; }
inline bool operator <=(const Rule & x, const Balau::Date::year & y) { return !(y < x); }
inline bool operator >=(const Rule & x, const Balau::Date::year & y) { return !(x < y); }
inline bool operator !=(const Balau::Date::year & x, const Rule & y) { return !(x == y); }
inline bool operator >(const Balau::Date::year & x, const Rule & y) { return y < x; }
inline bool operator <=(const Balau::Date::year & x, const Rule & y) { return !(y < x); }
inline bool operator >=(const Balau::Date::year & x, const Rule & y) { return !(x < y); }
inline bool operator !=(const Rule & x, const std::string & y) { return !(x == y); }
inline bool operator >(const Rule & x, const std::string & y) { return y < x; }
inline bool operator <=(const Rule & x, const std::string & y) { return !(y < x); }
inline bool operator >=(const Rule & x, const std::string & y) { return !(x < y); }
inline bool operator !=(const std::string & x, const Rule & y) { return !(x == y); }
inline bool operator >(const std::string & x, const Rule & y) { return y < x; }
inline bool operator <=(const std::string & x, const Rule & y) { return !(y < x); }
inline bool operator >=(const std::string & x, const Rule & y) { return !(x < y); }
struct zonelet {
enum tag {
has_rule, has_save, is_empty
};
std::chrono::seconds gmtoff_;
tag tag_ = has_rule;
#if !defined(_MSC_VER) || (_MSC_VER >= 1900)
union U
#else
struct U
#endif
{
std::string rule_;
std::chrono::minutes save_;
~U() {}
U() {}
U(const U &) {}
U & operator =(const U &) = delete;
} u;
std::string format_;
Balau::Date::year until_year_ { 0 };
MonthDayTime until_date_;
sys_seconds until_utc_;
local_seconds until_std_;
local_seconds until_loc_;
std::chrono::minutes initial_save_ {};
std::string initial_abbrev_;
std::pair<const Rule *, Balau::Date::year> first_rule_ { nullptr, Balau::Date::year::min() };
std::pair<const Rule *, Balau::Date::year> last_rule_ { nullptr, Balau::Date::year::max() };
~zonelet();
zonelet();
zonelet(const zonelet & i);
zonelet & operator =(const zonelet &) = delete;
};
#else // USE_OS_TZDB
struct ttinfo
{
std::int32_t tt_gmtoff;
unsigned char tt_isdst;
unsigned char tt_abbrind;
unsigned char pad[2];
};
static_assert(sizeof(ttinfo) == 8, "");
struct expanded_ttinfo
{
std::chrono::seconds offset;
std::string abbrev;
bool is_dst;
};
struct transition
{
sys_seconds timepoint;
const expanded_ttinfo* info;
transition(sys_seconds tp, const expanded_ttinfo* i = nullptr)
: timepoint(tp)
, info(i)
{}
friend
std::ostream&
operator<<(std::ostream& os, const transition& t)
{
using namespace Balau::Date;
using namespace std::chrono;
using Balau::Date::operator<<;
os << t.timepoint << "Z ";
if (t.info->offset >= seconds{0})
os << '+';
os << make_time(t.info->offset);
if (t.info->is_dst > 0)
os << " daylight ";
else
os << " standard ";
os << t.info->abbrev;
return os;
}
};
#endif // USE_OS_TZDB
} // namespace detail
} // namespace Date
} // namespace Balau
#if defined(_MSC_VER) && (_MSC_VER < 1900)
#include<Balau/ThirdParty/Date/tz.hpp>
#endif
#endif // BALAU_TP__DATE__TZ_PRIVATE
|
3a9e75dee4b42beafc8fb10be810f940122d9a8e | 058229aeedbfbabe06021e1bb494fda66167da27 | /sources/historybrowserwindow.cpp | fb7a77f4a5922519e221d6fc29ce4aec09fbe89e | [
"MIT"
] | permissive | kr0st/fpgui | 371fe3445e5f308879b35251c9dc628bc17868d8 | 26c584648b3954fd86f1499f8898c96156e33e9e | refs/heads/master | 2021-06-05T11:16:28.393474 | 2021-01-09T19:22:54 | 2021-01-09T19:22:54 | 101,194,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,221 | cpp | historybrowserwindow.cpp | #include <QClipboard>
#include "historybrowserwindow.h"
#include "ui_historybrowserwindow.h"
#include <utils.h>
#include <settings.h>
#include <set>
namespace fpgui { namespace ui {
HistoryBrowserWindow::HistoryBrowserWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::HistoryBrowserWindow)
{
ui->setupUi(this);
ui->from_datetime->setDateTime(QDateTime::currentDateTimeUtc());
ui->to_datetime->setDateTime(QDateTime::currentDateTimeUtc());
QSettings settings;
auto conf = fpgui::settings::read_app_config(settings);
ui->per_page_edit->setText(std::to_string(conf.view_max_messages).c_str());
ui->per_page_edit->setValidator(new QIntValidator(1, 10000, this));
ui->goto_edit->setValidator(new QIntValidator(1, 65534, this));
this->installEventFilter(&key_emitter_);
connect(&key_emitter_, SIGNAL(key_pressed(QKeyEvent)), this, SLOT(on_key_press(QKeyEvent)));
ui->tableWidget->addAction(ui->actionCopy);
}
HistoryBrowserWindow::~HistoryBrowserWindow()
{
delete ui;
}
void HistoryBrowserWindow::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
if (history_browser_view_)
history_browser_view_->do_resize();
}
void HistoryBrowserWindow::on_autoscroll_box_stateChanged(int state)
{
if (history_browser_view_)
history_browser_view_->on_autoscroll_change(state);
}
void HistoryBrowserWindow::on_sorting_box_stateChanged(int state)
{
if (history_browser_view_)
history_browser_view_->on_sorting_change(state);
}
void HistoryBrowserWindow::on_clear_button_clicked()
{
if (history_browser_view_)
history_browser_view_->on_clear_screen();
}
void HistoryBrowserWindow::on_connection_button_clicked()
{
if (history_browser_view_)
history_browser_view_->on_connection_stop_resume();
}
void HistoryBrowserWindow::on_quickfilter_edit_textEdited(const QString &text)
{
if (history_browser_view_)
history_browser_view_->on_quick_filter(text);
}
void HistoryBrowserWindow::message_box(const QString &text)
{
generic_utils::ui::message_box(text);
}
void HistoryBrowserWindow::on_from_datetime_editingFinished()
{
qint64 from = ui->from_datetime->dateTime().toSecsSinceEpoch(),
to = ui->to_datetime->dateTime().toSecsSinceEpoch();
if (history_browser_view_)
history_browser_view_->on_datetime_changed(from, to);
}
void HistoryBrowserWindow::on_to_datetime_editingFinished()
{
qint64 from = ui->from_datetime->dateTime().toSecsSinceEpoch(),
to = ui->to_datetime->dateTime().toSecsSinceEpoch();
if (history_browser_view_)
history_browser_view_->on_datetime_changed(from, to);
}
void HistoryBrowserWindow::on_left_button_clicked()
{
if (history_browser_view_)
history_browser_view_->on_browse_back();
}
void HistoryBrowserWindow::on_right_button_clicked()
{
if (history_browser_view_)
history_browser_view_->on_browse_forward();
}
void HistoryBrowserWindow::on_per_page_edit_editingFinished()
{
if (history_browser_view_)
history_browser_view_->on_per_page_changed(ui->per_page_edit->text().toInt());
}
void HistoryBrowserWindow::on_goto_edit_editingFinished()
{
if (history_browser_view_)
history_browser_view_->on_goto_page(ui->goto_edit->text().toInt());
}
void HistoryBrowserWindow::on_page_counter_update(int current_page, int total_pages)
{
std::string page_counter;
page_counter = std::to_string(current_page) + "/" + std::to_string(total_pages);
ui->page_counter_label->setText(page_counter.c_str());
}
int HistoryBrowserWindow::get_per_page_count()
{
return ui->per_page_edit->text().toInt();
}
void HistoryBrowserWindow::on_tableWidget_itemActivated(QTableWidgetItem *item)
{
if (history_browser_view_)
history_browser_view_->on_item_activated(item->row());
}
void HistoryBrowserWindow::on_key_press(QKeyEvent e)
{
if (e.key() == Qt::Key_Return)
{
if (ui->tableWidget->selectedItems().size() > 0)
{
QTableWidgetItem* item = ui->tableWidget->selectedItems()[0];
if (history_browser_view_)
history_browser_view_->on_item_activated(item->row());
}
}
}
void HistoryBrowserWindow::on_actionCopy_triggered()
{
int sz = ui->tableWidget->selectedItems().size();
std::set<int> rows;
int min_row = 100000000;
for (int i = 0; i < sz; ++i)
{
QTableWidgetItem* item = ui->tableWidget->selectedItems()[i];
int row(item->row());
if (row < min_row)
min_row = row;
rows.insert(row);
}
if (rows.size() > 0)
{
sz = static_cast<int>(rows.size());
QString result("");
for (int i = 0; i < sz; ++i)
{
for (int j = 0; j < ui->tableWidget->columnCount(); ++j)
{
QTableWidgetItem* item = ui->tableWidget->item(i + min_row, j);
if (item)
result += (item->text() + "|");
else
result += ("|");
}
result += "\n";
}
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(result);
}
}
}};
|
da872f0922d54745451a9b82c26a79d5377af75a | 1ad0d32ddfdcbaf2b710f950cc01a31a36661314 | /builder.cpp | 3a4e36231accae609ea9b77e00e93922eb204724 | [] | no_license | ascend4nce/columbia | 4c2e5df0632b209e8987b22d7ff04a9970349efb | b627c84219cfdd549374aea1b23d4c9ce3ae0e53 | refs/heads/master | 2020-07-26T09:57:44.829631 | 2019-09-15T14:57:11 | 2019-09-15T14:57:11 | 208,609,893 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | cpp | builder.cpp | #include <mkl.h>
#include <mkl_rci.h>
#include <mkl_blas.h>
#include <mkl_spblas.h>
#include <mkl_service.h>
#include <cmath>
#include <cstdio>
#include "matrixCSR.h"
#include "maxvol.h"
#include "nonlinearities.h"
#include "fullscheme.h"
#include "newton.h"
#include "reduction.h"
#include "constants.h"
#include "columbia.h"
int main(int argc, char ** argv)
{
char basis[60];
char nlbasis[60];
char interpbasis[60];
if (argc < 2)
{
printf("Input the basis storage file name tag.");
return -2;
};
sprintf(basis, "bases/%sbasis.dat", argv[1]);
sprintf(nlbasis, "bases/%sassist.dat", argv[1]);
sprintf(interpbasis, "bases/%sinterp.dat", argv[1]);
builddata(GRIDsize, alphagrid, betagrid, shiftgrid, RANKmaxreduction, RANKnonlinearity, Snapshots, NLSnapshots, basis, nlbasis, interpbasis);
};
|
30655488901d91f209b42c1baa14ef020d3d92e1 | f7e8786b1e62222bd1cedcb58383a0576c36a2a2 | /src/mojo/edk/embedder/process_type.h | 4ea439e5fa500df7854fa19daa0edb7a58d858ae | [
"BSD-3-Clause"
] | permissive | amplab/ray-core | 656915553742302915a363e42b7497037985a91e | 89a278ec589d98bcbc7e57e0b80d055667cca62f | refs/heads/master | 2023-07-07T20:45:40.883095 | 2016-08-06T23:52:23 | 2016-08-06T23:52:23 | 61,343,320 | 4 | 5 | null | 2016-08-06T23:52:24 | 2016-06-17T03:35:34 | C++ | UTF-8 | C++ | false | false | 835 | h | process_type.h | // Copyright 2015 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 MOJO_EDK_EMBEDDER_PROCESS_TYPE_H_
#define MOJO_EDK_EMBEDDER_PROCESS_TYPE_H_
#include <ostream>
namespace mojo {
namespace embedder {
enum class ProcessType {
// |InitIPCSupport()| has not been called (or |ShutdownIPCSupport()| has been
// called).
UNINITIALIZED,
// Process without connection management.
NONE,
// Master process.
MASTER,
// Slave process.
SLAVE,
};
// So logging macros and |DCHECK_EQ()|, etc. work.
inline std::ostream& operator<<(std::ostream& out, ProcessType process_type) {
return out << static_cast<int>(process_type);
}
} // namespace embedder
} // namespace mojo
#endif // MOJO_EDK_EMBEDDER_PROCESS_TYPE_H_
|
e11da7e6f2cccf921ba0f51af1b56a24c3c4151c | 6ef6ff3ebace348edf205af760d528625a69c3dc | /pepestreamer/src/common/color.cpp | a9c3ea8c828c83a874b0f7f733e4dd1537a5fe99 | [] | no_license | pepe-gamedev-studio/pepestreamer | 3df70633bffc333d778a2a86738564055d64478d | aaf85b44701003c2ef2ec72e02bee456f627732d | refs/heads/master | 2023-04-04T09:54:00.456371 | 2021-04-17T15:22:53 | 2021-04-17T17:59:46 | 358,948,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | cpp | color.cpp | #include "color.h"
namespace pepestreamer {
uint8_t Clip(uint8_t x) { return x > 255 ? 255 : x < 0 ? 0 : x; }
Yuv Rgb2Yuv(const Rgb &color) {
return {Clip(((66 * color[0] + 129 * color[1] + 25 * color[2] + 128) >> 8) + 16),
Clip(((-38 * color[0] - 74 * color[1] + 112 * color[2] + 128) >> 8) + 128),
Clip(((112 * color[0] - 94 * color[1] - 18 * color[2] + 128) >> 8) + 128)};
}
} // namespace pepestreamer |
5fa49efb5724a8b4255675b87d2ff39fa3ee0c7c | 74fbb21630be2da23e0dd5a16071e4a663b11261 | /main.cpp | a55b0be8bf62a3378f9661125dd38e05478ee2d8 | [] | no_license | rrivas-utec/poo2_unit5_week8_2021_0_exercise | 3298162b29ca3e50e9ca7a82cb42d13e2e1e04bc | f4a9f78d1dc96b4ca29b4d0e22b028ff99ba559a | refs/heads/master | 2023-03-08T12:48:06.116678 | 2021-02-26T22:55:19 | 2021-02-26T22:55:19 | 342,721,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84 | cpp | main.cpp | // --------- DON'T TOUCH --------
#include "global.h"
int main() {
return 0;
}
|
451606a78e4c221b49e4ecd53f77897e77944c16 | bb0e13d6a34696c66e84a42c44586793a22a8be9 | /byte/byte/byte.cpp | b6de31136f2b00c183635ddba5ebd65dae5e92c8 | [] | no_license | NikitaVrnk/byte | cce9aba68aaea34dcf88aee17326ed7882696fc4 | e7f5fe42cac67f2cb03bf433cbfb1c2202dd38b9 | refs/heads/main | 2023-02-17T22:18:07.914139 | 2021-01-10T18:36:49 | 2021-01-10T18:36:49 | 324,612,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,689 | cpp | byte.cpp | #include <iostream>//Для работы с клавиатурой
#include <fstream>//Для работы с файлами
#include <bitset>
#define FLOAT_ARRAY_SIZE 5
#define OUTPUT_INT_ARRAY_SIZE 10
// опции флагов
#define FLAG_option_1 0
#define FLAG_option_2 1
#define FLAG_option_3 2
#define FLAG_option_4 3
#define FLAG_option_5 4
#define FLAG_option_6 5
#define FLAG_option_7 6
#define FLAG_option_8 7
struct Msg {
std::bitset<64> mask = 0xAAAAAAAAAAAAAAAA;
//uint64_t mask = 0xAAAAAAAAAAAAAAAA;
//uint8_t _flag = FLAG_option_1; //битовый флаг шестнадцатиричный литерал 0000 0001
std::bitset<8> bitsFLAG = FLAG_option_8; //8 бит
int32_t id = 2111111111;
int32_t n = 1999999999;
float arrayMSG[FLOAT_ARRAY_SIZE] = { 0.0, 1.1, 2.2,3.3,4.4 };
};
//запись структуры в массив
int struct2Array(Msg *msg, int32_t *arrMsg, uint32_t size) {
int8_t* ptr_arrMsg = (int8_t*)arrMsg;
int8_t* ptr_msg = (int8_t*)msg;
size_t sz_arrMsg = sizeof(*arrMsg) * size;
size_t sz_msg = sizeof(*msg);
//проверка на несоответствие размера sz_arrMsg != sz_msg0
if (sz_arrMsg != sz_msg) {
std::cerr << "Ошибка размеры sz_arrMsg и sz_msg0 не совпадают" << std::endl;
return 1;
}
for (size_t i = 0; i < sz_msg; i++) {
*(ptr_arrMsg + i) = *(ptr_msg + i);
}
return 0;
};
//запись массива в структуру
int array2Struct(int32_t *arrMsg, uint32_t size, Msg *msg) {
int8_t* ptr_arrMsg = (int8_t*)arrMsg;
int8_t* ptr_msg = (int8_t*)msg;
size_t sz_arrMsg = sizeof(*arrMsg) * size;
size_t sz_msg = sizeof(*msg);
//проверка на несоответствие размера sz_arrMsg != sz_msg1
if (sz_arrMsg != sz_msg) {
std::cerr << "Ошибка размеры sz_arrMsg и sz_msg1 не совпадают" << std::endl;
return 2;
}
for (size_t i = 0; i < sz_msg; i++) {
*(ptr_msg + i) = *(ptr_arrMsg + i);
}
return 0;
};
//сохранение массива в файл
int arr2File(int32_t *arrMsg, uint32_t size, std::string fileName) {
std::ofstream file;
file.open(fileName, std::ios::binary);
int8_t* ptr_arrMsg = (int8_t*)arrMsg;
size_t sz_arrMsg = sizeof(*arrMsg) * size;
for (size_t i = 0; i < sz_arrMsg; i++) {
file << *(ptr_arrMsg + i);
}
file.close();
return 0;
};
//вывод массива из файла
int file2Arr(std::string fileName, int32_t *arrMsg, uint32_t size) {
std::ifstream file;
file.open(fileName, std::ios::in || std::ios::binary);
int8_t* ptr_arrMsg = (int8_t*)arrMsg;
size_t sz_arrMsg = sizeof(*arrMsg) * size;
for (size_t i = 0; i < sz_arrMsg; i++) {
file.read((char*)ptr_arrMsg, sz_arrMsg);
}
file.close();
return 0;
};
int main()
{
setlocale(LC_ALL, "Rus");
int32_t arrMsg[OUTPUT_INT_ARRAY_SIZE] = {1999999999};
int32_t arrMsgInput[OUTPUT_INT_ARRAY_SIZE] = {};
Msg msg0;
Msg msg1 = {
0,
0,
0,
0,
{0,0,0,0,0}
};
std::cout << "Размер Msg = "<< sizeof(Msg) << std::endl;
std::cout << "Размер arrMsg = " << sizeof(arrMsg) << std::endl;
std::cout << "Размер msg0 = " << sizeof(msg0) << std::endl;
std::cout << "Размер msg1 = " << sizeof(msg1) << std::endl;
struct2Array(&msg0, arrMsg, OUTPUT_INT_ARRAY_SIZE);
arr2File(arrMsg, OUTPUT_INT_ARRAY_SIZE, "File.bin");
file2Arr("File.bin", arrMsgInput, OUTPUT_INT_ARRAY_SIZE);
array2Struct(arrMsgInput, OUTPUT_INT_ARRAY_SIZE, &msg1);
std::cout << " " << std::endl;
return 0;
} |
a545c1712fc69e852aa75cf23c9e1c4f6ebb4f67 | 916109bf168239202442498e568b2bfc9a8bc8a9 | /src/asiEngine/asiEngine_RE.cpp | c2938e686d55cc77c25d616390e00d8046a62403 | [
"BSD-3-Clause",
"MIT"
] | permissive | yeeeeeeti/3D_feature_extract | 35da69cd64cd6ed6c92fd4541da5de7bb96dc2b6 | 6297daa8afaac09aef9b44858e74fb2a95e1e7c5 | refs/heads/master | 2020-09-05T02:27:30.997017 | 2019-11-07T01:24:26 | 2019-11-07T01:24:26 | 219,956,109 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,805 | cpp | asiEngine_RE.cpp | //-----------------------------------------------------------------------------
// Created on: 06 October 2018
//-----------------------------------------------------------------------------
// Copyright (c) 2018-present, Sergey Slyadnev
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder(s) nor the
// names of all contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
// Own include
#include <asiEngine_RE.h>
// Active Data includes
#include <ActData_UniqueNodeName.h>
//-----------------------------------------------------------------------------
Handle(asiData_ReTopoNode) asiEngine_RE::Create_Topo()
{
/* ==================
* Create root Node
* ================== */
// Add Node to Partition.
Handle(asiData_ReTopoNode)
topo_n = Handle(asiData_ReTopoNode)::DownCast( asiData_ReTopoNode::Instance() );
//
m_model->GetReTopoPartition()->AddNode(topo_n);
// Initialize Node.
topo_n->Init();
topo_n->SetName("Topology");
// Add as a child to Triangulation Node.
m_model->GetTriangulationNode()->AddChildNode(topo_n);
/* ====================
* Create child Nodes
* ==================== */
this->Create_Patches (topo_n);
this->Create_Edges (topo_n);
this->Create_Vertices (topo_n);
// Return the just created Node.
return topo_n;
}
//-----------------------------------------------------------------------------
Handle(asiData_RePatchesNode)
asiEngine_RE::Create_Patches(const Handle(asiData_ReTopoNode)& topo_n)
{
// Add Node to Partition.
Handle(asiData_RePatchesNode)
patches_n = Handle(asiData_RePatchesNode)::DownCast( asiData_RePatchesNode::Instance() );
//
m_model->GetRePatchesPartition()->AddNode(patches_n);
// Initialize Node.
patches_n->Init();
patches_n->SetName("Patches");
// Add as a child to Topology Node.
topo_n->AddChildNode(patches_n);
// Return the just created Node.
return patches_n;
}
//-----------------------------------------------------------------------------
Handle(asiData_ReEdgesNode)
asiEngine_RE::Create_Edges(const Handle(asiData_ReTopoNode)& topo_n)
{
// Add Node to Partition.
Handle(asiData_ReEdgesNode)
edges_n = Handle(asiData_ReEdgesNode)::DownCast( asiData_ReEdgesNode::Instance() );
//
m_model->GetReEdgesPartition()->AddNode(edges_n);
// Initialize Node.
edges_n->Init();
edges_n->SetName("Edges");
// Add as a child to Topology Node.
topo_n->AddChildNode(edges_n);
// Return the just created Node.
return edges_n;
}
//-----------------------------------------------------------------------------
Handle(asiData_ReVerticesNode)
asiEngine_RE::Create_Vertices(const Handle(asiData_ReTopoNode)& topo_n)
{
// Add Node to Partition.
Handle(asiData_ReVerticesNode)
vertices_n = Handle(asiData_ReVerticesNode)::DownCast( asiData_ReVerticesNode::Instance() );
//
m_model->GetReVerticesPartition()->AddNode(vertices_n);
// Initialize Node.
vertices_n->Init();
vertices_n->SetName("Vertices");
// Add as a child to Topology Node.
topo_n->AddChildNode(vertices_n);
// Return the just created Node.
return vertices_n;
}
//-----------------------------------------------------------------------------
Handle(asiData_RePatchesNode) asiEngine_RE::Get_Patches()
{
Handle(asiData_Partition<asiData_RePatchesNode>)
patches_p = m_model->GetRePatchesPartition();
return Handle(asiData_RePatchesNode)::DownCast( patches_p->GetNode(1) );
}
//-----------------------------------------------------------------------------
Handle(asiData_ReEdgesNode) asiEngine_RE::Get_Edges()
{
Handle(asiData_Partition<asiData_ReEdgesNode>)
edges_p = m_model->GetReEdgesPartition();
return Handle(asiData_ReEdgesNode)::DownCast( edges_p->GetNode(1) );
}
//-----------------------------------------------------------------------------
Handle(asiData_ReVerticesNode) asiEngine_RE::Get_Vertices()
{
Handle(asiData_Partition<asiData_ReVerticesNode>)
vertices_p = m_model->GetReVerticesPartition();
return Handle(asiData_ReVerticesNode)::DownCast( vertices_p->GetNode(1) );
}
//-----------------------------------------------------------------------------
Handle(asiData_RePatchNode) asiEngine_RE::Create_Patch()
{
// Get or create parent Topo Node.
Handle(asiData_ReTopoNode) topo_n = m_model->GetReTopoNode();;
//
if ( topo_n.IsNull() )
topo_n = this->Create_Topo();
// Get Patches Node.
Handle(asiData_RePatchesNode) patches_n = this->Get_Patches();
// Add Node to Partition.
Handle(asiData_RePatchNode)
patch_n = Handle(asiData_RePatchNode)::DownCast( asiData_RePatchNode::Instance() );
//
m_model->GetRePatchPartition()->AddNode(patch_n);
// Initialize Node.
patch_n->Init();
// Add as a child to Patches Node.
patches_n->AddChildNode(patch_n);
// Generate unique name.
TCollection_ExtendedString
patchName = ActData_UniqueNodeName::Generate(ActData_SiblingNodes::CreateForChild(patch_n, patches_n), "Patch");
//
patch_n->SetName(patchName);
// Return the just created Node.
return patch_n;
}
//-----------------------------------------------------------------------------
Handle(asiData_ReEdgeNode)
asiEngine_RE::Create_Edge(const Handle(asiData_ReVertexNode)& vfirst,
const Handle(asiData_ReVertexNode)& vlast)
{
// Get or create parent Topo Node.
Handle(asiData_ReTopoNode) topo_n = m_model->GetReTopoNode();;
//
if ( topo_n.IsNull() )
topo_n = this->Create_Topo();
// Get parent Edges Node.
Handle(asiData_ReEdgesNode) edges_n = this->Get_Edges();
// Add Node to Partition.
Handle(asiData_ReEdgeNode)
edge_n = Handle(asiData_ReEdgeNode)::DownCast( asiData_ReEdgeNode::Instance() );
//
m_model->GetReEdgePartition()->AddNode(edge_n);
// Initialize Node.
edge_n->Init(vfirst, vlast);
edge_n->SetUserFlags(NodeFlag_IsPresentedInPartView);
// Add as a child to Edges Node.
edges_n->AddChildNode(edge_n);
// Generate unique name.
TCollection_ExtendedString
edgeName = ActData_UniqueNodeName::Generate(ActData_SiblingNodes::CreateForChild(edge_n, edges_n), "Edge");
//
edge_n->SetName(edgeName);
// Return the just created Node.
return edge_n;
}
//-----------------------------------------------------------------------------
Handle(asiData_ReCoEdgeNode)
asiEngine_RE::Create_CoEdge(const Handle(asiData_RePatchNode)& patch,
const Handle(asiData_ReEdgeNode)& edge,
const bool samesense)
{
// Add Node to Partition.
Handle(asiData_ReCoEdgeNode)
coedge_n = Handle(asiData_ReCoEdgeNode)::DownCast( asiData_ReCoEdgeNode::Instance() );
//
m_model->GetReCoEdgePartition()->AddNode(coedge_n);
// Initialize Node.
coedge_n->Init(edge, samesense);
coedge_n->SetUserFlags(NodeFlag_IsPresentedInPartView);
// Add as a child to Patch Node.
patch->AddChildNode(coedge_n);
// Generate unique name.
TCollection_ExtendedString
edgeName = ActData_UniqueNodeName::Generate(ActData_SiblingNodes::CreateForChild(coedge_n, patch), "CoEdge");
//
coedge_n->SetName(edgeName);
// Return the just created Node.
return coedge_n;
}
//-----------------------------------------------------------------------------
Handle(asiData_ReVertexNode)
asiEngine_RE::Create_Vertex(const gp_XYZ& coords)
{
// Get or create parent Topo Node.
Handle(asiData_ReTopoNode) topo_n = m_model->GetReTopoNode();;
//
if ( topo_n.IsNull() )
topo_n = this->Create_Topo();
// Get parent Vertices Node.
Handle(asiData_ReVerticesNode) vertices_n = this->Get_Vertices();
// Add Node to Partition.
Handle(asiData_ReVertexNode)
vertex_n = Handle(asiData_ReVertexNode)::DownCast( asiData_ReVertexNode::Instance() );
//
m_model->GetReVertexPartition()->AddNode(vertex_n);
// Initialize Node.
vertex_n->Init( coords.X(), coords.Y(), coords.Z() );
vertex_n->SetUserFlags(NodeFlag_IsPresentedInPartView);
// Add as a child to Vertices Node.
vertices_n->AddChildNode(vertex_n);
// Generate unique name.
TCollection_ExtendedString
vertexName = ActData_UniqueNodeName::Generate(ActData_SiblingNodes::CreateForChild(vertex_n, vertices_n), "Vertex");
//
vertex_n->SetName(vertexName);
// Return the just created Node.
return vertex_n;
}
|
8c4ad314cc203d8b7ce5162af2eacf39a1d5988f | 7b7498dcc9f0ab771c32743517c863e41f2411b7 | /_not_used/m_marsh.h | 5e206976582946536df95fb74cc4ca5ab95df429 | [] | no_license | yx500/mvp_classes | b544ebae63807db66f2542628ff793d3e60dac1f | 93c02bcd8fa8b500e8fb274d44039ca3fbbb7da2 | refs/heads/master | 2023-04-05T02:38:04.956275 | 2021-04-07T10:41:04 | 2021-04-07T10:41:04 | 254,649,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 754 | h | m_marsh.h | #ifndef M_MARSH_H
#define M_MARSH_H
#include "m_marsh_str.h"
class m_Marsh : public m_Base
{
Q_OBJECT
MYPROP(int, GROUP)
MYPROP(ObjectLink, SV1)
MYPROP(ObjectLink, SV2)
Q_PROPERTY(bool USTANOVLEN READ USTANOVLEN DESIGNABLE true STORED false)
public:
Q_INVOKABLE m_Marsh(QObject *parent = 0);
virtual ~m_Marsh(){}
virtual QString defaultGroupName() const {return "Список маршрутов";}
bool USTANOVLEN();
void setUSTANOVLEN(bool p);
QList<m_Marsh_Str*> marsh_Str(){return lMarsh_Str;}
virtual void updateAfterLoad();
void addMSTR(m_RC *rc,MVP_Enums::TStrelPol pol);
protected:
QList<m_Marsh_Str*> lMarsh_Str;
public slots:
virtual void updateStates();
};
#endif // M_MARSH_H
|
d3334d49f8e13ee7faf902872cf7bac49080b646 | fd8f3e0e6c297c82760fbb90edc5b6188e42b28a | /src/RwCalculators/GReWeightUtils.cxx | 9188ce4a09aa01285d9514ff4e522f12c8acd063 | [] | no_license | sjgardiner/Reweight | 998b81d0450799c1e4c63d6f8f5263b9f4e878c4 | 1a685cec649f406e65a3b999dea2caed77759f9a | refs/heads/master | 2022-10-30T08:13:27.912159 | 2021-11-15T15:45:30 | 2021-11-15T15:45:30 | 160,225,545 | 0 | 3 | null | 2018-12-17T16:19:12 | 2018-12-03T17:03:55 | C++ | UTF-8 | C++ | false | false | 9,836 | cxx | GReWeightUtils.cxx | //____________________________________________________________________________
/*
Copyright (c) 2003-2018, The GENIE Collaboration
For the full text of the license visit http://copyright.genie-mc.org
Author: Jim Dobson <J.Dobson07 \at imperial.ac.uk>
Imperial College London
Costas Andreopoulos <costas.andreopoulos \at stfc.ac.uk>
University of Liverpool & STFC Rutherford Appleton Lab
*/
//____________________________________________________________________________
#include <cassert>
#include <TMath.h>
// GENIE/Generator includes
#include "Framework/Conventions/Units.h"
#include "Framework/Conventions/Controls.h"
#include "Framework/GHEP/GHepParticle.h"
#include "Framework/Messenger/Messenger.h"
#include "Framework/Numerical/Spline.h"
#include "Framework/ParticleData/PDGUtils.h"
#include "Framework/ParticleData/PDGCodes.h"
#include "Physics/HadronTransport/INukeHadroData2018.h"
#include "Physics/HadronTransport/INukeHadroFates.h"
#include "Physics/HadronTransport/INukeUtils.h"
// GENIE/Reweight includes
#include "RwCalculators/GReWeightUtils.h"
using namespace genie;
using namespace genie::rew;
using namespace genie::controls;
//____________________________________________________________________________
double genie::utils::rew::MeanFreePathWeight(
int pdgc, const TLorentzVector & x4, const TLorentzVector & p4,
double A, double Z,
double mfp_scale_factor, bool interacted,
double nRpi, double nRnuc, double NR, double R0)
{
LOG("ReW", pINFO)
<< "Calculating mean free path weight: "
<< "A = " << A << ", Z = " << Z << ", mfp_scale = " << mfp_scale_factor
<< ", interacted = " << interacted;
LOG("ReW", pDEBUG)
<< "nR_pion = " << nRpi << ", nR_nucleon = " << nRnuc
<< ", NR = " << NR << ", R0 = " << R0;
// Get the nominal survival probability
double pdef = utils::intranuke::ProbSurvival(
pdgc,x4,p4,A,Z,1.,nRpi,nRnuc,NR,R0);
LOG("ReW", pINFO) << "Probability(default mfp) = " << pdef;
if(pdef<=0) return 1.;
// Get the survival probability for the tweaked mean free path
double ptwk = utils::intranuke::ProbSurvival(
pdgc,x4,p4,A,Z,mfp_scale_factor,nRpi,nRnuc,NR,R0);
LOG("ReW", pINFO) << "Probability(tweaked mfp) = " << ptwk;
if(ptwk<=0) return 1.;
// Calculate weight
double w_mfp = utils::rew::MeanFreePathWeight(pdef, ptwk, interacted);
LOG("ReW", pINFO) << "Mean free path weight = " << w_mfp;
return w_mfp;
}
//____________________________________________________________________________
double genie::utils::rew::FZoneWeight(
int pdgc, const TLorentzVector & vtx, const TLorentzVector & x4,
const TLorentzVector & p4, double A, double Z,
double fz_scale_factor, bool interacted,
double nRpi, double nRnuc, double NR, double R0)
{
// Calculate hadron start assuming tweaked formation zone
TLorentzVector fz = x4 - vtx;
TLorentzVector fztwk = fz_scale_factor*fz;
TLorentzVector x4twk = x4 + fztwk - fz;
LOG("ReW", pDEBUG) << "Formation zone = "<< fz.Vect().Mag() << " fm";
// Get nominal survival probability.
double pdef = utils::intranuke::ProbSurvival(
pdgc,x4,p4,A,Z,1.,nRpi,nRnuc,NR,R0);
LOG("ReW", pDEBUG) << "Survival probability (nominal) = "<< pdef;
if(pdef<=0) return 1.;
if(pdef>=1.){
LOG("ReW", pERROR)
<< "Default formation zone takes hadron outside "
<< "nucleus so cannot reweight!" ;
return 1.;
}
// Get tweaked survival probability.
double ptwk = utils::intranuke::ProbSurvival(
pdgc,x4twk,p4,A,Z,1.,nRpi,nRnuc,NR,R0);
if(ptwk<=0) return 1.;
LOG("ReW", pDEBUG) << "Survival probability (tweaked) = "<< ptwk;
// Calculate weight
double w_fz = utils::rew::MeanFreePathWeight(pdef, ptwk, interacted);
LOG("ReW", pDEBUG)
<< "Particle weight for formation zone tweak = "<< ptwk;
return w_fz;
}
//____________________________________________________________________________
double genie::utils::rew::MeanFreePathWeight(
double pdef, double ptwk, bool interacted)
{
// Returns a weight to account for a change in hadron mean free path inside
// insidea nuclear medium.
//
// Inputs:
// pdef : nominal survival probability
// ptwk : survival probability for the tweaked mean free path
// interacted : flag indicating whether the hadron interacted or escaped
//
// See utils::intranuke::ProbSurvival() for the calculation of probabilities.
//
double w_mfp = 1.;
if(interacted) {
w_mfp = (1-pdef>0) ? (1-ptwk) / (1-pdef) : 1;
} else {
w_mfp = (pdef>0) ? ptwk / pdef : 1;
}
w_mfp = TMath::Max(0.,w_mfp);
return w_mfp;
}
//____________________________________________________________________________
double genie::utils::rew::FateFraction(genie::rew::GSyst_t syst, double kinE,
int target_A, double frac_scale_factor)
{
if ( target_A < 1 ) LOG("ReW", pERROR) << "Invalid mass number A = "
<< target_A << " passed to genie::utils::rew::FateFraction";
double fate_frac = 0.0;
INukeHadroData2018 * hd = INukeHadroData2018::Instance();
// convert to MeV and
double ke = kinE / units::MeV;
ke = TMath::Max(INukeHadroData2018::fMinKinEnergy, ke);
ke = TMath::Min(INukeHadroData2018::fMaxKinEnergyHA, ke);
switch (syst) {
//
// pions
//
case (genie::rew::kINukeTwkDial_FrCEx_pi) :
{
fate_frac = hd->FracADep(kPdgPiP, kIHAFtCEx, ke, target_A);
}
break;
// case (genie::rew::kINukeTwkDial_FrElas_pi) :
// {
// fate_frac = hd->FracADep(kPdgPiP, kIHAFtElas, ke, target_A);
// }
// break;
case (genie::rew::kINukeTwkDial_FrInel_pi) :
{
fate_frac = hd->FracADep(kPdgPiP, kIHAFtInelas, ke, target_A);
}
break;
case (genie::rew::kINukeTwkDial_FrAbs_pi) :
{
fate_frac = hd->FracADep(kPdgPiP, kIHAFtAbs, ke, target_A);
}
break;
case (genie::rew::kINukeTwkDial_FrPiProd_pi) :
{
fate_frac = hd->FracADep(kPdgPiP, kIHAFtPiProd, ke, target_A);
}
break;
//
// nucleons
//
case (genie::rew::kINukeTwkDial_FrCEx_N) :
{
fate_frac = hd->FracAIndep(kPdgProton, kIHAFtCEx, ke);
}
break;
// case (genie::rew::kINukeTwkDial_FrElas_N) :
// {
// fate_frac = hd->Frac(kPdgProton, kIHAFtElas, ke);
// }
// break;
case (genie::rew::kINukeTwkDial_FrInel_N) :
{
fate_frac = hd->FracAIndep(kPdgProton, kIHAFtInelas, ke);
}
break;
case (genie::rew::kINukeTwkDial_FrAbs_N) :
{
fate_frac = hd->FracAIndep(kPdgProton, kIHAFtAbs, ke);
}
break;
case (genie::rew::kINukeTwkDial_FrPiProd_N) :
{
fate_frac = hd->FracAIndep(kPdgProton, kIHAFtPiProd, ke);
}
break;
default:
{
LOG("ReW", pDEBUG)
<< "Have reached default case and assigning fraction{fate} = 0";
fate_frac = 0;
}
break;
} // hadron_fate?
fate_frac *= frac_scale_factor;
return fate_frac;
}
//____________________________________________________________________________
double genie::utils::rew::WhichFateFractionScaleFactor(
genie::rew::GSyst_t syst, double kinE, int target_A, double fate_frac)
{
double fate_frac_nominal = FateFraction(syst, kinE, target_A, 1.0);
// Avoid NaNs if both the nominal value and the tweaked value are zero
if ( fate_frac_nominal == 0. && fate_frac == 0. ) return 1.;
if ( fate_frac_nominal <= 0. ) {
// We're having some sort of problem with the fate fraction calculation
LOG("ReW", pERROR) << "Nonpositive nominal fate fraction"
<< " encountered in genie::utils::rew::WhichFateFractionScaleFactor()";
return -99999.;
}
double scale = std::max(0., fate_frac) / fate_frac_nominal;
return scale;
}
//____________________________________________________________________________
bool genie::utils::rew::HadronizedByAGKY(const EventRecord & event)
{
Interaction * interaction = event.Summary();
assert(interaction);
bool is_dis = interaction->ProcInfo().IsDeepInelastic();
bool charm = interaction->ExclTag().IsCharmEvent();
bool by_agky = is_dis && !charm;
return by_agky;
}
//____________________________________________________________________________
bool genie::utils::rew::HadronizedByAGKYPythia(const EventRecord & event)
{
// Check whether the event was hadronized by AGKY/KNO or AGKY/PYTHIA
GHepStatus_t prefragm = kIStDISPreFragmHadronicState;
bool found_string = (event.FindParticle(kPdgString, prefragm, 0) != 0);
bool found_cluster = (event.FindParticle(kPdgCluster, prefragm, 0) != 0);
bool handled_by_pythia = found_string || found_cluster;
return handled_by_pythia;
}
//____________________________________________________________________________
TLorentzVector genie::utils::rew::Hadronic4pLAB(const EventRecord & event)
{
GHepParticle * nu = event.Probe(); // incoming v
GHepParticle * N = event.HitNucleon(); // struck nucleon
GHepParticle * l = event.FinalStatePrimaryLepton(); // f/s primary lepton
assert(nu);
assert(N);
assert(l);
// Compute the Final State Hadronic System 4p (PX = Pv + PN - Pl)
const TLorentzVector & p4nu = *(nu->P4());
const TLorentzVector & p4N = *(N ->P4());
const TLorentzVector & p4l = *(l ->P4());
TLorentzVector pX4 = p4nu + p4N - p4l;
return pX4;
}
//____________________________________________________________________________
double genie::utils::rew::AGKYWeight(int /*pdgc*/, double /*xF*/, double /*pT2*/)
{
return 1.0;
}
//____________________________________________________________________________
int genie::utils::rew::Sign(double twkdial)
{
if(twkdial < 0.) return -1;
if(twkdial > 0.) return +1;
return 0;
}
//____________________________________________________________________________
|
8408111c26ba619299d882b28f2dea2479f85330 | 35fc9126009a7f2638330879304ab5730969d4f5 | /Base/src/EventSync.cpp | 6687468931eb3d8e48c6ed6ef287c4cb819fb868 | [] | no_license | ruguiru/suholib | 24d556b683ee765d143e093e044c8e044640d807 | 0e309be7126b09a2ad90bdc42a6b46659adab919 | refs/heads/master | 2023-03-29T11:43:42.293821 | 2023-03-26T17:56:27 | 2023-03-26T17:56:27 | 119,015,405 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | cpp | EventSync.cpp | #include "EventSync.h"
using namespace suho::thread;
void EventSync::Wait()
{
std::unique_lock<std::mutex> lock( _mutex );
_condition.wait( lock, [&] () { return _signal; } );
lock.unlock();
}
void EventSync::Set()
{
std::lock_guard<std::mutex> lock( _mutex );
_signal = true;
_condition.notify_one();
}
void EventSync::Reset()
{
std::lock_guard<std::mutex> lock( _mutex );
_signal = false;
} |
7e814f1b382d5ffefbf27119a685c81d3e9a6e73 | 052803ba6222d92580f3bbe18a4872e0a0490276 | /FowlPlay/src/Character/Character.h | e2c5bef347a77a15e808c3d23242f39e03fa748f | [] | no_license | GPHS-Code-Club/GPHS-Hall-of-Fame-February | 0b005f8d575bf130132c7745f52645919f6db1bf | 34c3b42a803ada8ebb7240a80ef1a56bc8475745 | refs/heads/main | 2023-03-09T07:34:59.394990 | 2021-02-26T17:53:02 | 2021-02-26T17:53:02 | 342,413,078 | 0 | 1 | null | 2021-02-26T17:50:45 | 2021-02-26T00:04:36 | null | UTF-8 | C++ | false | false | 1,133 | h | Character.h | #pragma once
#ifndef CHARACTER_CHARACTER_H_
#define CHARACTER_CHARACTER_H_
#include "../input.h"
#include "../Animation/Animator.h"
class Character {
const char *texture_path;
const char *bullet_path;
const char *feather_path;
const char *eggshell_path;
command_map commands;
int bullet_damage;
int move_speed_divisor;
public:
Character(void);
Character(const char *texture_path, const char *bullet_path, const char *feather_path, const char *eggshell_path, int bullet_damage, int move_speed_divisor);
virtual ~Character(void);
const char *get_texture_path(void) const;
const char *get_bullet_path(void) const;
const char *get_feather_path(void) const;
BulletAttack get_attack(std::string command_input) const;
virtual void do_regular_bullet(Object *object, Sint16 left_x, Sint16 left_y) = 0;
int get_bullet_damage(void) const;
animation *get_moving_animation(void) const;
int get_low_speed_divisor(void) const;
int get_high_speed_divisor(void) const;
protected:
void map_command(std::string command_input, BulletAttack bullet_attack);
animation *moving;
};
#endif /* CHARACTER_H_ */
|
5a960c3a4ce837a7122a3497b77765fc589da89a | 4b77ab97f97309fe75067059d230dd4250801938 | /src/DRISE/pch.h | ccff67caa1a7d262b8359cc9daeecce87b8bd178 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | aravindkrishnaswamy/RISE | de862c1ab15fe2ed1bc620f3c3939430b801d54d | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | refs/heads/master | 2020-04-12T16:22:44.305654 | 2018-12-20T17:27:30 | 2018-12-20T17:27:30 | 162,610,783 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,535 | h | pch.h | //////////////////////////////////////////////////////////////////////
//
// pch.h - Precompiled header for DRISE
//
// Author: Aravind Krishnaswamy
// Date of Birth: November 24, 2003
// Tabs: 4
// Comments:
//
// License Information: Please see the attached LICENSE.TXT file
//
//////////////////////////////////////////////////////////////////////
#ifndef DRISE_PCH_
#define DRISE_PCH_
#ifdef USE_PRECOMPILED_HEADER_
//
// The precompiled header is orgainzed
//
//
// Platform and compiler dependent options
// In case of the Win32 and MSVC, we turn off
// some idiotic warnings that VC6 gives us
//
#ifdef WIN32
#pragma warning( disable : 4503 ) // disables warning about decorated names being truncated
#pragma warning( disable : 4786 ) // disables warning about 255 truncation in PDB
#pragma warning( disable : 4250 ) // disables silly virtual inheritance warning
#endif
//
// First all the platform independent system files
//
#include <iostream>
#include <fstream>
#include <math.h>
#include <memory.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
// STL stuff
#include <algorithm>
#include <deque>
#include <functional>
#include <vector>
#include <list>
#include <map>
#include "../Library/RISE_API.h"
#include "../Library/Interfaces/IReference.h"
//
// All essential RISE utilitary stuff
//
#include "../Library/Utilities/Threads/Threads.h"
#include "../Library/Utilities/Communications/ClientSocketCommunicator.h"
#endif // USE_PRECOMPILED_HEADER_
#endif // DRISE_PCH_
|
2c94af62b7888df2426661e087562394dbc7aaab | 387549ab27d89668e656771a19c09637612d57ed | /DRGLib UE project/Source/FSD/Private/TreasureBoxAnimInstance.cpp | 320cba88b8aea7478b751b0cf53364167dbc29c6 | [
"MIT"
] | permissive | SamsDRGMods/DRGLib | 3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a | 76f17bc76dd376f0d0aa09400ac8cb4daad34ade | refs/heads/main | 2023-07-03T10:37:47.196444 | 2023-04-07T23:18:54 | 2023-04-07T23:18:54 | 383,509,787 | 16 | 5 | MIT | 2023-04-07T23:18:55 | 2021-07-06T15:08:14 | C++ | UTF-8 | C++ | false | false | 268 | cpp | TreasureBoxAnimInstance.cpp | #include "TreasureBoxAnimInstance.h"
UTreasureBoxAnimInstance::UTreasureBoxAnimInstance() {
this->BuildProgress = 0.00f;
this->PhysicsAlpha = 0.00f;
this->IsTreasureAvailable = true;
this->IsLeftInserted = false;
this->IsRightInserted = false;
}
|
cd0aee8415fb8085a41e3d237ed5dc74d99b5259 | f6d5124e131c83f7b64dbeeb6b0d8a4bcaa09fdd | /branches/1.1b/TraumCheck/TraumCheck.cpp | 782eeb97f2fa336c70e29f340b42fa0abb8197b3 | [] | no_license | 5k0rp/traumlibcheck | 40bb4f16c533022f12c408c02e949f179e16cdfc | d20b56ad4f739bc867954dac2afd02e2caf2cb7a | refs/heads/master | 2021-01-01T06:54:05.354831 | 2010-12-13T23:08:39 | 2010-12-13T23:08:39 | 32,864,050 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,656 | cpp | TraumCheck.cpp | #include "common.h"
#include "DirStructure.h"
#include "TraumDb.h"
#include "null_wcodecvt.h"
#include <windows.h>
#include <stdio.h>
#include <fstream>
void splitPath(Combowstrings& tree, const wchar_t* ptr)
{
tree.clear();
const wchar_t* start = ptr;
for(; *ptr; ++ptr)
if(*ptr == L'\\')
tree.push_back(std::wstring(start, ptr));
tree.push_back(std::wstring(start, ptr));
}
bool checkAndPrint(std::wostream& fout, const LibNodeCalalog& cat, LibNode::MarkType type, const wchar_t* header)
{
bool isFind = false;
for(LibNodeCalalog::const_iterator it = cat.begin(); it != cat.end(); ++it)
if(it->mark() == type){
if(!isFind){
isFind = true;
fout << wendl << header << wendl;
}
fout << it->path() << wendl;
}
return isFind;
}
int wmain(int argc, wchar_t* argv[])
{
wprintf(L"Traum library check tool. V1.1b. 2009-10-29. Sk0rp\n");
DirStructure dirStruct;
wprintf(L"Reading EN...");
if(dirStruct.add(L"en"))
wprintf(L" done\n");
else {
wprintf(L" error\n");
return -1;
}
wprintf(L"Reading RU...");
if(dirStruct.add(L"ru"))
wprintf(L" done\n");
else {
wprintf(L" error\n");
return -1;
}
TraumDb traumDb;
wprintf(L"Reading Traum db...");
if(traumDb.add(L"db\\book"))
wprintf(L" done\n");
else {
wprintf(L" error\n");
return -1;
}
wprintf(L"Sorting...");
dirStruct.sort();
traumDb.sort();
wprintf(L" done\n");
wprintf(L"Checking...");
std::wfstream fout;
null_wcodecvt wcodec(1);
std::locale wloc(std::locale::classic(), &wcodec);
fout.imbue(wloc);
fout.open("cmplog.txt", std::ios::out | std::ios::binary);
if(!fout){
std::cerr << "Failed to open cmplog.txt for writting" << std::endl;
return 1;
}
fout << UTF_BOM << L"Протокол сравнения db\\book и библиотеки на диске." << wendl;
bool lostFiles = false;
std::wstring lastpath;
LibNodeCalalog::iterator dit;
LibNodeCalalog::iterator tit = traumDb.begin();
for(; tit != traumDb.end(); ++tit){
std::wstring curpath;
tit->getFolder(curpath);
if(curpath != lastpath){
lastpath = curpath;
Combowstrings tree;
splitPath(tree, curpath.c_str());
Combowstrings::const_iterator it = tree.begin();
for(; it != tree.end(); ++it){
dit = dirStruct.bsearch(it->c_str());
if(dit != dirStruct.end())
if(wcscmp(LibNode(it->c_str(), 0).file(), dit->file()))
dit->setMark(LibNode::WRONG_CASE);
else
dit->setMark(LibNode::ALL_GOOD);
}
}
LibNodeCalalog::iterator dit = dirStruct.bsearch(tit->path());
if(dit != dirStruct.end()){
if(tit->size() == dit->size())
if(wcscmp(tit->file(), dit->file()))
dit->setMark(LibNode::WRONG_CASE);
else
dit->setMark(LibNode::ALL_GOOD);
else
dit->setMark(LibNode::WRONG_SIZE);
}
else {
if(!lostFiles){
lostFiles = true;
fout << wendl << L"Не найдено в библиотеке:" << wendl;
}
fout << tit->path() << wendl;
}
}
bool overFiles = checkAndPrint(fout, dirStruct, LibNode::NO_FILE, L"\nЛишнее в библиотеке:");
overFiles = checkAndPrint(fout, dirStruct, LibNode::WRONG_SIZE, L"\nДругой размер:") || overFiles;
overFiles = checkAndPrint(fout, dirStruct, LibNode::WRONG_CASE, L"\nОтличается регистр букв:") || overFiles;
if(!lostFiles && !overFiles)
fout << wendl << L"Расхождений не обнаружено!" << wendl;
fout.close();
wprintf(L" done. Look cmplog.txt\n");
return 0;
}
|
7d75e5a196949db40e18f3ab63635c3c568a518d | 70f1c9f7814ce0ba808176f3eda43930e28ffa73 | /z__Utils - Copy/include/mr_defines.h | 5aaf8adc4174929b36ffc4cb5a908d8b16c87af3 | [] | no_license | MichaelRoop/CPP_TestHarness | 9acff5fcc0c1d4ca87eedaa6d6f715657d68f3ee | 3d4008a20ab03e4f51606e5c098a5a4c901ee1e2 | refs/heads/master | 2021-01-10T20:28:57.798744 | 2013-10-20T23:15:25 | 2013-10-20T23:15:25 | 5,349,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | h | mr_defines.h | ///--------------------------------------------------------------------------------------
/// @file mr_defines.h
/// @brief Common defines for system.
///
/// @author Michael Roop
/// @date 2010
/// @version 1.0
///
/// @todo Make char versions for trim functions.
///
/// Copyright 2010 Michael Roop
///--------------------------------------------------------------------------------------
#if !defined(MR_DEFINES_H)
#define MR_DEFINES_H
namespace mr_utils
{
/// @brief Macro to shorten the file and line macro arg insertion.
#define FL __FILE__,__LINE__
#define _FL_ __FILE__,__LINE__
} // end namespace
#endif |
db09c84f20644d6afec07fcbbf7e9be01962c32e | 66949aa40ce96974161f3d1c631de71ffe078178 | /Waiter.cpp | ca0d276110c47ab5e81886b2bd2be3f6c20b6549 | [
"Unlicense"
] | permissive | baatochan/DiningPhilosophersProblem | 7e4b526ef5f367f1fff679d5509ab237d6a43dd9 | 76af266a765184dd9466b3f69dca381b4b4994ad | refs/heads/master | 2021-04-06T03:45:57.896021 | 2018-07-30T10:23:45 | 2018-07-30T10:23:45 | 125,028,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,162 | cpp | Waiter.cpp | //
// Created by barto on 16.04.18.
//
#include <iostream>
#include "Waiter.h"
using namespace std;
void Waiter::setState(unsigned char state) {
stateMutex.lock();
Waiter::state = state;
stateMutex.unlock();
}
Waiter::Waiter(int numberOfPhilosophers) {
terminate = false;
checkQueue = false;
this->numberOfPhilosophers = numberOfPhilosophers;
for (int i = 0; i < numberOfPhilosophers; i++) {
forks.push_back(true);
}
}
void Waiter::start() {
unique_lock<mutex> uniqueLock(waiterMutex);
setState(1);
while (!(terminate && queue.size() == 0)) {
waiterSleep.wait(uniqueLock, [this] {return checkQueue;});
forksQueueMutex.lock();
setState(2);
checkQueue = false;
int i = 0;
for (auto &philosopher : queue) {
int id = philosopher->getId();
int left = id;
int right = id + 1;
if (right == numberOfPhilosophers)
right = 0;
if (forks[left] && forks[right]) {
forks[left] = false;
forks[right] = false;
philosopher->wakeUp();
queue.erase(queue.begin() + i);
i--;
}
i++;
}
setState(1);
forksQueueMutex.unlock();
}
setState(3);
}
void Waiter::askForForks(Philosopher* p) {
forksQueueMutex.lock();
queue.push_back(p);
checkQueue = true;
waiterSleep.notify_all();
forksQueueMutex.unlock();
}
void Waiter::returnForks(Philosopher* p) {
int id = p->getId();
int left = id;
int right = id + 1;
if (right == numberOfPhilosophers)
right = 0;
forksQueueMutex.lock();
forks[left] = true;
forks[right] = true;
checkQueue = true;
waiterSleep.notify_all();
forksQueueMutex.unlock();
}
void Waiter::setTerminate(bool terminate) {
Waiter::terminate = terminate;
}
std::thread Waiter::spawnThread() {
return std::thread([this] { this->start(); });
}
void Waiter::wakeUp() {
forksQueueMutex.lock();
checkQueue = true;
waiterSleep.notify_all();
forksQueueMutex.unlock();
}
unsigned char Waiter::getState() {
stateMutex.lock();
unsigned char temp = state;
stateMutex.unlock();
return temp;
}
const vector<bool> Waiter::getForks() {
forksQueueMutex.lock();
vector<bool> temp;
temp = forks;
forksQueueMutex.unlock();
return temp;
}
|
5c5e42707ae47b53832020ff0965c0a6d1b03d5c | 9e4cb0c415adfaee2d4ac2866f9992aeae84200b | /C++ Basics Videos/Not Organized/Array Example 7/ArrayEx7.cpp | b79eb6214dbbc0dbd5d1f426580e427a4852e74d | [] | no_license | CyberChimeraUSA/Cpp-Tutorials | 1648e8efe8fdeb0ec7f6957f0a0cb71cbcac36e5 | 04245959be4e684b9faa81b0303fbb4754b748a8 | refs/heads/master | 2021-05-04T14:53:42.498165 | 2019-08-18T21:48:50 | 2019-08-18T21:48:50 | 120,214,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | cpp | ArrayEx7.cpp | #include <iostream>
using namespace std;
void voltageCalculator (double [3][3]);
int main(void) {
int x, y;
double resistanceArray[3][3] = {{1,2,3},{4,5,6},{7,8,9} };
for(x=0; x < 3; x++)
for(y=0; y < 3; y++)
{
cout << "Matrix Location: " << x <<"," << y << " value: "<< resistanceArray[x][y] << endl;
}
voltageCalculator(resistanceArray);
return 0;
}
void voltageCalculator(double inputArray[3][3])
{
int a, b;
for (a =0; a < 3 ; a++)
for (b = 0; b < 3; b++)
{
double voltage, current = 0.1;
voltage = current *inputArray[a][b];
cout << voltage << endl;
}
}
|
c1b8662ceafb68a616c635b0a5510b0f1437306e | ae31542273a142210a1ff30fb76ed9d45d38eba9 | /src/backend/gporca/libgpopt/include/gpopt/xforms/CJoinOrderDPv2.h | 6ff3d342d8d51fd1d8e6b8c91047911b4a7873ed | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"PostgreSQL",
"OpenSSL",
"LicenseRef-scancode-stream-benchmark",
"ISC",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-ssleay-windows",
"BSD-2-Clause",
"Python-2.0"
] | permissive | greenplum-db/gpdb | 8334837bceb2d5d51a684500793d11b190117c6a | 2c0f8f0fb24a2d7a7da114dc80f5f5a2712fca50 | refs/heads/main | 2023-08-22T02:03:03.806269 | 2023-08-21T22:59:53 | 2023-08-22T01:17:10 | 44,781,140 | 6,417 | 2,082 | Apache-2.0 | 2023-09-14T20:33:42 | 2015-10-23T00:25:17 | C | UTF-8 | C++ | false | false | 20,034 | h | CJoinOrderDPv2.h | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2019 VMware, Inc. or its affiliates.
//
// @filename:
// CJoinOrderDPv2.h
//
// @doc:
// Dynamic programming-based join order generation
//---------------------------------------------------------------------------
#ifndef GPOPT_CJoinOrderDPv2_H
#define GPOPT_CJoinOrderDPv2_H
#include "gpos/base.h"
#include "gpos/common/CBitSet.h"
#include "gpos/common/CHashMap.h"
#include "gpos/common/DbgPrintMixin.h"
#include "gpos/io/IOstream.h"
#include "gpopt/base/CKHeap.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/operators/CExpression.h"
#include "gpopt/xforms/CJoinOrder.h"
namespace gpopt
{
using namespace gpos;
//---------------------------------------------------------------------------
// @class:
// CJoinOrderDPv2
//
// @doc:
// Helper class for creating join orders using dynamic programming
//
// Some terminology:
//
// NIJ: Non-inner join. This is sometimes used instead of left join,
// since we anticipate to extend this code to semi-joins and other
// types of joins.
// Atom: A child of the NAry join. This could be a table or some
// other operator like a groupby or a full outer join.
// Group: A set of atoms (called a "component" in DPv1). Once we generate
// a result expression, each of these sets will be associated
// with a CGroup in MEMO.
//---------------------------------------------------------------------------
class CJoinOrderDPv2 : public CJoinOrder,
public gpos::DbgPrintMixin<CJoinOrderDPv2>
{
private:
// Data structures for DPv2 join enumeration:
//
// Each level l is the set of l-way joins we are considering.
// Level 1 describes the "atoms" the leaves of the original NAry join we are transforming.
//
// Each level consists of a set (an array) of "groups". A group represents what may eventually
// become a group in the MEMO structure, if it is a part of one of the generated top k
// expressions at the top level. It is a set of atoms to be joined (in any order).
// The SGroupInfo struct contains the bitset representing the atoms, the cardinality from the
// derived statistics and an array of SExpressionInfo structs.
//
// Each SExpressionInfo struct describes an expression in a group. Besides a CExpression,
// it also has the SGroupInfo and SExpressionInfo of the children. Each SExpressionInfo
// also has a property. The SExpressionInfo entries in a group all have different properties.
// We only keep expressions that are not dominated by another expression, meaning that there
// is no other expression that can produce a superset of the properties for a less or equal
// cost.
//
//
// SLevelInfo
// +---------------------+
// Level n: | SGroupInfo array ---+----> SGroupInfo
// | optional top k | +------------------+
// +---------------------+ | Atoms (bitset) |
// | cardinality |
// | SExpressionInfo |
// | array |
// +--------+---------+
// v
// SExpressionInfo
// +------------------------+
// | CExpression |
// | child SExpressionInfos |
// | properties |
// +------------------------+
// +------------------------+
// | CExpression |
// | child SExpressionInfos |
// | properties |
// +------------------------+
// ...
// +------------------------+
// | CExpression |
// | child SExpressionInfos |
// | properties |
// +------------------------+
// ...
//
// SLevelInfo
// +---------------------+
// Level 1: | SGroupInfo array ---+----> SGroupInfo SGroupInfo
// | optional top k | +------------------+ +------------------+
// +---------------------+ | Atoms (bitset) | | Atoms (bitset) |
// | cardinality +--------------+ cardinality |
// | ExpressionInfo | | ExpressionInfo |
// | array | | array |
// +--------+---------+ +--------+---------+
// v v
// SExpressionInfo SExpressionInfo
// +------------------------+ +------------------------+
// | CExpression | | CExpression |
// | child SExpressionInfos | | child SExpressionInfos |
// | properties | | properties |
// +------------------------+ +------------------------+
//
// forward declarations, circular reference
struct SGroupInfo;
struct SExpressionInfo;
// Join enumeration algorithm properties, these can be added if an expression satisfies more than one
// consider these as constants, not as a true enum
// note that the numbers (other than the first) must be powers of 2,
// since we add them to make composite properties!!!
// Note also that query, mincard and GreedyAvoidXProd are all greedy algorithms.
// Sorry for the confusion with the term "greedy" used in the optimizer_join_order guc
// and the CXformExpandNAryJoinGreedy classes, where they refer to one type of greedy
// algorithm that avoids cross products.
enum JoinOrderPropType
{
EJoinOrderAny = 0, // the overall best solution (used for exhaustive2)
EJoinOrderQuery = 1, // this expression uses the "query" join order
EJoinOrderMincard = 2, // this expression has the "mincard" property
EJoinOrderGreedyAvoidXProd =
4, // best "greedy" expression with minimal cross products
EJoinOrderHasPS =
8, // best expression with special consideration for DPE
EJoinOrderDP = 16, // best solution using DP
EJoinOrderStats =
32 // this expression is used to calculate the statistics
// (row count) for the group
};
// properties of an expression in the DP structure (also used as required properties)
struct SExpressionProperties
{
// the join order enumeration algorithm for which this is a solution
// (exhaustive enumeration, can use any of these: EJoinOrderAny)
ULONG m_join_order;
SExpressionProperties(ULONG join_order_properties)
: m_join_order(join_order_properties)
{
}
BOOL
Satisfies(ULONG pt) const
{
return pt == (m_join_order & pt);
}
void
Add(const SExpressionProperties &p)
{
m_join_order |= p.m_join_order;
}
BOOL
IsGreedy() const
{
return 0 != (m_join_order & (EJoinOrderQuery + EJoinOrderMincard +
EJoinOrderGreedyAvoidXProd));
}
};
// a simple wrapper of an SGroupInfo * plus an index into its array of SExpressionInfos
// this identifies a group and one expression belonging to that group
struct SGroupAndExpression
{
SGroupInfo *m_group_info{nullptr};
ULONG m_expr_index{gpos::ulong_max};
SGroupAndExpression() = default;
SGroupAndExpression(SGroupInfo *g, ULONG ix)
: m_group_info(g), m_expr_index(ix)
{
}
SExpressionInfo *
GetExprInfo() const
{
return m_expr_index == gpos::ulong_max
? nullptr
: (*m_group_info->m_best_expr_info_array)[m_expr_index];
}
BOOL
IsValid() const
{
return nullptr != m_group_info && gpos::ulong_max != m_expr_index;
}
BOOL
operator==(const SGroupAndExpression &other) const
{
return m_group_info == other.m_group_info &&
m_expr_index == other.m_expr_index;
}
};
// description of an expression in the DP environment
// left and right child of join expressions point to
// child groups + expressions
struct SExpressionInfo : public CRefCount
{
// the expression
CExpression *m_expr;
// left/right child group/expr info (group for left/right child of m_expr),
// we do not keep a refcount for these
SGroupAndExpression m_left_child_expr;
SGroupAndExpression m_right_child_expr;
// derived properties of this expression
SExpressionProperties m_properties;
// in the future, we may add more properties relevant to the cost here,
// like distribution spec, partition selectors
// Stores part keys for atoms that are partitioned tables. NULL otherwise.
CPartKeysArray *m_atom_part_keys_array;
// cost of the expression
CDouble m_cost;
//cost adjustment for the effect of partition selectors, this is always <= 0.0
CDouble m_cost_adj_PS;
// base table rows, -1 if not atom or get/select
CDouble m_atom_base_table_rows;
// stores atom ids that are fufilled by a PS in this expression
CBitSet *m_contain_PS;
SExpressionInfo(CMemoryPool *mp, CExpression *expr,
const SGroupAndExpression &left_child_expr_info,
const SGroupAndExpression &right_child_expr_info,
SExpressionProperties &properties)
: m_expr(expr),
m_left_child_expr(left_child_expr_info),
m_right_child_expr(right_child_expr_info),
m_properties(properties),
m_atom_part_keys_array(nullptr),
m_cost(0.0),
m_cost_adj_PS(0.0),
m_atom_base_table_rows(-1.0),
m_contain_PS(nullptr)
{
m_contain_PS = GPOS_NEW(mp) CBitSet(mp);
this->UnionPSProperties(left_child_expr_info.GetExprInfo());
this->UnionPSProperties(right_child_expr_info.GetExprInfo());
}
SExpressionInfo(CMemoryPool *mp, CExpression *expr,
SExpressionProperties &properties)
: m_expr(expr),
m_properties(properties),
m_atom_part_keys_array(nullptr),
m_cost(0.0),
m_cost_adj_PS(0.0),
m_atom_base_table_rows(-1.0),
m_contain_PS(nullptr)
{
m_contain_PS = GPOS_NEW(mp) CBitSet(mp);
}
~SExpressionInfo() override
{
m_expr->Release();
CRefCount::SafeRelease(m_contain_PS);
}
// cost (use -1 for greedy solutions to ensure we keep all of them)
CDouble
GetCostForHeap() const
{
return m_properties.IsGreedy() ? -1.0 : GetCost();
}
CDouble
GetCost() const
{
return m_cost + m_cost_adj_PS;
}
void
UnionPSProperties(SExpressionInfo *other) const
{
m_contain_PS->Union(other->m_contain_PS);
}
BOOL
ChildrenAreEqual(const SExpressionInfo &other) const
{
return m_left_child_expr == other.m_left_child_expr &&
m_right_child_expr == other.m_right_child_expr;
}
};
using SExpressionInfoArray =
CDynamicPtrArray<SExpressionInfo, CleanupRelease<SExpressionInfo>>;
//---------------------------------------------------------------------------
// @struct:
// SGroupInfo
//
// @doc:
// Struct containing a bitset, representing a group, its best expression, and cost
//
//---------------------------------------------------------------------------
struct SGroupInfo : public CRefCount
{
// the set of atoms, this uniquely identifies the group
CBitSet *m_atoms;
// infos of the best (lowest cost) expressions (so far, if at the current level)
// for each interesting property
SExpressionInfoArray *m_best_expr_info_array;
CDouble m_cardinality;
CDouble m_lowest_expr_cost;
SGroupInfo(CMemoryPool *mp, CBitSet *atoms)
: m_atoms(atoms), m_cardinality(-1.0), m_lowest_expr_cost(-1.0)
{
m_best_expr_info_array = GPOS_NEW(mp) SExpressionInfoArray(mp);
}
~SGroupInfo() override
{
m_atoms->Release();
m_best_expr_info_array->Release();
}
BOOL
IsAnAtom() const
{
return 1 == m_atoms->Size();
}
CDouble
GetCostForHeap() const
{
return m_lowest_expr_cost;
}
};
// dynamic array of SGroupInfo, where each index represents an alternative group of a given level k
using SGroupInfoArray =
CDynamicPtrArray<SGroupInfo, CleanupRelease<SGroupInfo>>;
// info for a join level, the set of all groups representing <m_level>-way joins
struct SLevelInfo : public CRefCount
{
ULONG m_level;
SGroupInfoArray *m_groups;
CKHeap<SGroupInfoArray, SGroupInfo> *m_top_k_groups;
SLevelInfo(ULONG level, SGroupInfoArray *groups)
: m_level(level), m_groups(groups), m_top_k_groups(nullptr)
{
}
~SLevelInfo() override
{
m_groups->Release();
CRefCount::SafeRelease(m_top_k_groups);
}
};
// hashing function
static ULONG
UlHashBitSet(const CBitSet *pbs)
{
GPOS_ASSERT(nullptr != pbs);
return pbs->HashValue();
}
// equality function
static BOOL
FEqualBitSet(const CBitSet *pbsFst, const CBitSet *pbsSnd)
{
GPOS_ASSERT(nullptr != pbsFst);
GPOS_ASSERT(nullptr != pbsSnd);
return pbsFst->Equals(pbsSnd);
}
using ExpressionToEdgeMap =
CHashMap<CExpression, SEdge, CExpression::HashValue, CUtils::Equals,
CleanupRelease<CExpression>, CleanupRelease<SEdge>>;
// dynamic array of SGroupInfos
using BitSetToGroupInfoMap =
CHashMap<CBitSet, SGroupInfo, UlHashBitSet, FEqualBitSet,
CleanupRelease<CBitSet>, CleanupRelease<SGroupInfo>>;
// iterator over group infos in a level
using BitSetToGroupInfoMapIter =
CHashMapIter<CBitSet, SGroupInfo, UlHashBitSet, FEqualBitSet,
CleanupRelease<CBitSet>, CleanupRelease<SGroupInfo>>;
// dynamic array of SLevelInfos, where each index represents the level
using DPv2Levels = CDynamicPtrArray<SLevelInfo, CleanupRelease<SLevelInfo>>;
// an array of an array of groups, organized by level at the first array dimension,
// main data structure for dynamic programming
DPv2Levels *m_join_levels;
// map to find the associated edge in the join graph from a join predicate
ExpressionToEdgeMap *m_expression_to_edge_map;
// map to check whether a DPv2 group already exists
BitSetToGroupInfoMap *m_bitset_to_group_info_map;
// ON predicates for NIJs (non-inner joins, e.g. LOJs)
// currently NIJs are LOJs only, this may change in the future
// if/when we add semijoins, anti-semijoins and relatives
CExpressionArray *m_on_pred_conjuncts;
// association between logical children and inner join/ON preds
// (which of the logical children are right children of NIJs and what ON predicates are they using)
ULongPtrArray *m_child_pred_indexes;
// for each non-inner join (entry in m_on_pred_conjuncts), the required atoms on the left
CBitSetArray *m_non_inner_join_dependencies;
// top K expressions at the top level
CKHeap<SExpressionInfoArray, SExpressionInfo> *m_top_k_expressions;
// top K expressions at top level that contain promising dynamic partiion selectors
// if there are no promising dynamic partition selectors, this will be empty
CKHeap<SExpressionInfoArray, SExpressionInfo> *m_top_k_part_expressions;
// current penalty for cross products (depends on enumeration algorithm)
CDouble m_cross_prod_penalty;
// outer references, if any
CColRefSet *m_outer_refs;
CMemoryPool *m_mp;
SLevelInfo *
Level(ULONG l)
{
return (*m_join_levels)[l];
}
// build expression linking given groups
CExpression *PexprBuildInnerJoinPred(CBitSet *pbsFst, CBitSet *pbsSnd);
// compute cost of a join expression in a group
void ComputeCost(SExpressionInfo *expr_info, CDouble join_cardinality);
// if we need to keep track of used edges, make a map that
// speeds up this usage check
void PopulateExpressionToEdgeMapIfNeeded();
// add a select node with any remaining edges (predicates) that have
// not been incorporated in the join tree
CExpression *AddSelectNodeForRemainingEdges(CExpression *join_expr);
// mark all the edges used in a join tree
void RecursivelyMarkEdgesAsUsed(CExpression *expr);
// enumerate all possible joins between left_level-way joins on the left side
// and right_level-way joins on the right side, resulting in left_level + right_level-way joins
void SearchJoinOrders(ULONG left_level, ULONG right_level);
void GreedySearchJoinOrders(ULONG left_level, JoinOrderPropType algo);
void DeriveStats(CExpression *pexpr) override;
// create a CLogicalJoin and a CExpression to join two groups, for a required property
SExpressionInfo *GetJoinExprForProperties(
SGroupInfo *left_child, SGroupInfo *right_child,
SExpressionProperties &required_properties);
// get a join expression from two child groups with specified child expressions
SExpressionInfo *GetJoinExpr(const SGroupAndExpression &left_child_expr,
const SGroupAndExpression &right_child_expr,
SExpressionProperties &result_properties);
// does "prop" provide all the properties of "other_prop" plus maybe more?
static BOOL IsASupersetOfProperties(SExpressionProperties &prop,
SExpressionProperties &other_prop);
// is one of the properties a subset of the other or are they disjoint?
static BOOL ArePropertiesDisjoint(SExpressionProperties &prop,
SExpressionProperties &other_prop);
// get best expression in a group for a given set of properties
static SGroupAndExpression GetBestExprForProperties(
SGroupInfo *group_info, SExpressionProperties &props);
// add a new property to an existing predicate
static void AddNewPropertyToExpr(SExpressionInfo *expr_info,
SExpressionProperties props);
// enumerate bushy joins (joins where both children are also joins) of level "current_level"
void SearchBushyJoinOrders(ULONG current_level);
// look up an existing group or create a new one, with an expression to be used for stats
SGroupInfo *LookupOrCreateGroupInfo(SLevelInfo *levelInfo, CBitSet *atoms,
SExpressionInfo *stats_expr_info);
// add a new expression to a group, unless there already is an existing expression that dominates it
void AddExprToGroupIfNecessary(SGroupInfo *group_info,
SExpressionInfo *new_expr_info);
void PopulateDPEInfo(SExpressionInfo *join_expr_info,
SGroupInfo *left_group_info,
SGroupInfo *right_group_info);
void FinalizeDPLevel(ULONG level);
SGroupInfoArray *
GetGroupsForLevel(ULONG level) const
{
return (*m_join_levels)[level]->m_groups;
}
ULONG FindLogicalChildByNijId(ULONG nij_num);
static ULONG NChooseK(ULONG n, ULONG k);
BOOL LevelIsFull(ULONG level);
void EnumerateDP();
void EnumerateQuery();
void FindLowestCardTwoWayJoin(JoinOrderPropType prop_type);
void EnumerateMinCard();
void EnumerateGreedyAvoidXProd();
public:
// ctor
CJoinOrderDPv2(CMemoryPool *mp, CExpressionArray *pdrgpexprAtoms,
CExpressionArray *innerJoinConjuncts,
CExpressionArray *onPredConjuncts,
ULongPtrArray *childPredIndexes, CColRefSet *outerRefs);
// dtor
~CJoinOrderDPv2() override;
// main handler
virtual void PexprExpand();
CExpression *GetNextOfTopK();
// check for NIJs
BOOL IsRightChildOfNIJ(SGroupInfo *groupInfo,
CExpression **onPredToUse = nullptr,
CBitSet **requiredBitsOnLeft = nullptr);
// print function
IOstream &OsPrint(IOstream &) const;
static IOstream &OsPrintProperty(IOstream &, SExpressionProperties &);
CXform::EXformId
EOriginXForm() const override
{
return CXform::ExfExpandNAryJoinDPv2;
}
}; // class CJoinOrderDPv2
} // namespace gpopt
#endif // !GPOPT_CJoinOrderDPv2_H
// EOF
|
9b50865b58a8146df2b8611abcdfac4bf60f852c | dd0491d3546fc9b98d25bf661aa0d7d6bb16a150 | /aMazing/code/engine/system/ShaderCompilerClass.h | 908927a7d65f2fab561379ed623658a9360b5c51 | [] | no_license | ruleless/aMazing | b144eeb295416754bf3d9b91bb8d0c998524009b | 849dae6fc6a163cda5baa5a4548619197da3d598 | refs/heads/master | 2021-01-21T19:40:45.990110 | 2015-02-05T01:57:07 | 2015-02-05T01:57:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | h | ShaderCompilerClass.h | #pragma once
#include <D3D11.h>
#include <D3DX11.h>
#include <d3dcompiler.h>
#include <iostream>
#include "../system/FileTracker.h"
#include "MutableString.h"
#define D3D_COMPILE_STANDARD_FILE_INCLUDE ((ID3DInclude*)(UINT_PTR)1)
class ShaderCompilerClass
{
public:
ShaderCompilerClass();
~ShaderCompilerClass();
static HRESULT compileFromFile(MutableString& filename,
const char* entryPoint,
const char* shaderTarget,
ID3DBlob** output);
static HRESULT compileFromFile(MutableString&& filename,
const char* entryPoint,
const char* shaderTarget,
ID3DBlob** output);
static HRESULT compileString(MutableString& str,
const char* entryPoint,
const char* shaderTarget,
ID3DBlob** output);
static HRESULT compileString(MutableString&& str,
const char* entryPoint,
const char* shaderTarget,
ID3DBlob** output);
};
|
f4778fff2bd0345f3951c9d6a96504db4dc344a8 | ad8ba88632b37f500a2a3fa258da3342d88a20ef | /Code/OOADProject/OOADProject/customerviewallitems.cpp | cecea94b4c8984c7d2f816cd4a94d2f5006f7de4 | [] | no_license | hamzahsaleem/inventory-management-system | f4c56bfdcd3f0a80fbeaf0140a5d44f00beeaa34 | cf26c74339065ad195b7d5da82217d422a813511 | refs/heads/master | 2021-07-21T12:24:08.851954 | 2017-10-31T15:06:07 | 2017-10-31T15:06:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,362 | cpp | customerviewallitems.cpp | #include "customerviewallitems.h"
CustomerViewAllItems::CustomerViewAllItems(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
mydb = QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("database.db");
mydb.open();
dialogueBox = new DialogueBox();
if (!mydb.isOpen())
{
dialogueBox->show();
dialogueBox->DisplayError("DB not connected properly!");
return;
}
}
CustomerViewAllItems::~CustomerViewAllItems()
{
}
void CustomerViewAllItems::backpage()
{
this->close();
customerviewitems = new CustomerViewItems;
customerviewitems->show();
}
void CustomerViewAllItems::viewByName(string name)
{
this->show();
itemName = name;
QSqlQuery query1;
QString qstr = QString::fromStdString(itemName);
if (query1.exec("select * from Item where Name= '" + qstr + "'"))
{
int count = 0;
while (query1.next())
{
if (query1.value("Quantity").toInt() > 0)
{
QTableWidgetItem *itemname = new QTableWidgetItem(query1.value("Name").toString());
QTableWidgetItem *itempackagequantity = new QTableWidgetItem(query1.value("PackageQuantity").toString());
QTableWidgetItem *itemprice = new QTableWidgetItem(query1.value("SalePrice").toString());
ui.tableWidget->insertRow(count);
ui.tableWidget->setItem(count, 0, itemname);
ui.tableWidget->setItem(count, 1, itempackagequantity);
ui.tableWidget->setItem(count, 2, itemprice);
count++;
}
}
}
}
void CustomerViewAllItems::viewByCategory(string name)
{
categoryName = name;
this->show();
QSqlQuery query1;
QString qstr = QString::fromStdString(categoryName);
if (query1.exec("select * from Item where Category='" + qstr + "' and Quantity >0 "))
{
int count = 0;
while (query1.next())
{
QTableWidgetItem *itemname = new QTableWidgetItem(query1.value("Name").toString());
QTableWidgetItem *itempackagequantity = new QTableWidgetItem(query1.value("PackageQuantity").toString());
QTableWidgetItem *itemprice = new QTableWidgetItem(query1.value("SalePrice").toString());
ui.tableWidget->insertRow(count);
ui.tableWidget->setItem(count, 0, itemname);
ui.tableWidget->setItem(count, 1, itempackagequantity);
ui.tableWidget->setItem(count, 2, itemprice);
count++;
}
}
} |
01adf3eda89518341ec9045a7e525fddface867f | d6249a6c85101170b3e0dd548ca6982bc8a94fbd | /Chef/LOCAPR17/DRS.cpp | c5256bb8f6b0c3635ecbaaba7aadc0110c216bae | [] | no_license | anshumanv/Competitive | bb5c387168095f3716cabc6c591c3b7697da64da | 828d07ad5217de06736ae538f54524092ec99af4 | refs/heads/master | 2021-08-19T08:35:30.019660 | 2017-11-25T14:38:38 | 2017-11-25T14:38:38 | 81,228,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 649 | cpp | DRS.cpp | #include<bits/stdc++.h>
#define newl "\n"
#define MODULO 1000000007
using namespace std;
int main(){
std::ios::sync_with_stdio(false);
int t;
cin >> t;
while(t--){
int n,day=0,review = 2,count= 0;
double temp=79.6;
cin >> n;
vector<double> ball(n);
for(int i = 0; i<n; i++)
cin >> ball[i];
sort(ball. begin(), ball.end());
//finding start day
while(ball[0]>(79.6+day*80))
day++;
// the main thing lol
for(int i =0; i<ball.size(); i++){
if(ball[i]>(79.6+day*80)){
day++;
review = 2;
}
if(review){
count++;
review--;
}
}
cout << count << newl;
}
return 0;
}
|
a4c8cc12680814561deb857405491cf3b1d3defe | edc86dc528a7f9508f20c93849e17a65ab74b540 | /文件操作/LineStruct.cpp | 0f991c37d052e71b60ad208fceb4f10faad2bfc6 | [] | no_license | RefactorLife/DataStructAndArithmetic | 8bd1d320277cd92cc30e48de832157e0b4eb8152 | 9d8d3f12dfac8a46d85b4d53cfd9d3aa9a541680 | refs/heads/master | 2016-08-12T14:03:58.330763 | 2015-11-24T10:44:59 | 2015-11-24T10:44:59 | 45,082,439 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 916 | cpp | LineStruct.cpp | //线性表
#include "myLineStruct.h"
#include "Common.h"
bool insertCharList_1(CharList &L,int i,char ch)
{
tag("bool insertCharList_1(CharList &L,int i,char ch)");
//将元素ch插入到表中第i个位置
if(i<1||i>L.length+1)
{
printf("插入位置不合法\n");
return false;
}
if(L.length>=LimitSize)
{
printf("存储空间已满");
return false;
}
for(int j = L.length-1;j>=i-1;j--)
{
L.data[j+1]=L.data[j];
}
L.data[i-1]=ch;
L.length++;
printf("插入成功");
return true;
}
bool insertCharList(CharList &L,char ch)
{
//初始化Length
if(L.length<0||L.length>LimitSize+1)
{
L.length = 0;
}
if(L.length>=LimitSize)
{
printf("存储空间已满");
return false;
}
L.data[L.length]=ch;
L.length++;
return true;
}
void showCharList(CharList &L)
{
tag("void showCharList(CharList &L)");
for(int i = 0;i<L.length;i++)
{
printf(" %d.%c",i,L.data[i]);
}
return ;
} |
23e86c265aecfbb871b739dc31737e87fb73d501 | 4b10301804f0c9bbc32c12b20e70c4e91cfdaf24 | /nelson/ParallelExecHelper.cpp | 605ae813890651f2e556b9b950c403c9a1961955 | [] | no_license | simoneceriani/nelson | a99f446448e51bf59af9a655769ed10247ae72ef | 5cd24d11ab7a7c8219f0dbac621461e7527c3e3e | refs/heads/master | 2023-07-14T05:10:41.728514 | 2021-06-18T10:38:27 | 2021-06-18T10:38:27 | 399,262,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54 | cpp | ParallelExecHelper.cpp | #include "ParallelExecHelper.h"
namespace nelson {
} |
020b1acf14598ea8f0ab0e597a5899bfd6a5dcda | 138f7c8b9ac606d4d4d669f4c7eb846f7a28b419 | /src/main.cpp | 0a31490513c9aa87b61efc304edae6dc5f9b4409 | [] | no_license | Sophie-Williams/SFML-CPP-TicTacToe | 08afd6c0ea291af820f7b1685b8508e18f678154 | 1186c622af7847da53d500efeed6df34b852065b | refs/heads/master | 2020-05-19T15:38:29.055422 | 2016-08-21T19:56:23 | 2016-08-21T19:56:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,994 | cpp | main.cpp | #include<SFML\Graphics.hpp>
#include<iostream>
#include<vector>
#include<memory>
#include<string>
#include"CBot.hpp"
#include"GameData.hpp"
#define FIELD_HEIGHT 3
#define FIELD_WIDTH 3
#define SAFE_DELETE(X) {if(X!=NULL){delete(X);}}
std::string playerToString(PLAYER player);
void setupBackground(std::vector<std::vector<sf::RectangleShape*>*> *fieldMatrix);
void setupField (std::vector<std::vector<Box*>*> *fieldMatrix);
void clearField (std::vector<std::vector<Box*>*> *fieldMatrix);
void setBox (std::vector<std::vector<Box*>*> *fieldMatrix, PLAYER player, sf::Vector2i *boxPos);
void checkWinner (std::vector<std::vector<Box*>*> *fieldMatrix, bool *done);
int main()
{
//VARS/////////////////////
sf::RenderWindow *window = new sf::RenderWindow(sf::VideoMode(340, 340), "Tic Tac Toe");
sf::Event *sfEvent = new sf::Event();
sf::FloatRect *boxBounds = new sf::FloatRect();
PLAYER currentPlayer;
bool *done = new bool;
bool *againstBot = new bool;
char *playerMode = new char;
boxBounds->height = 100;
boxBounds->width = 100;
currentPlayer = PLAYER::PLAYER_1;
*done = false;
//BACKGROUND_INIT//////////
std::vector<std::vector<sf::RectangleShape*>*> *backgroundMatrix = new std::vector<std::vector<sf::RectangleShape*>*>();
setupBackground(backgroundMatrix);
//FIELD_INIT///////////////
std::vector<std::vector<Box*>*> *fieldMatrix = new std::vector<std::vector<Box*>*>();
setupField(fieldMatrix);
//BOT_INIT/////////////////
CBot *bot = new CBot(fieldMatrix);
std::cout << ">Gegen <B>ot oder realen <S>pieler spielen: ";
while (!*done) {
std::cin >> *playerMode;
if ((*playerMode == 'B') || (*playerMode == 'b')) {
*done = true;
*againstBot = true;
} else if ((*playerMode == 'S') || (*playerMode == 's')) {
*done = true;
*againstBot = false;
} else {
std::cout << ">Ungueltige Eingabe. Bitte erneut versuchen." << std::endl;
}
}
*done = false;
while (window != NULL && window->isOpen()) {
if (sfEvent != NULL && done != NULL && againstBot != NULL && bot != NULL && window != NULL && fieldMatrix != NULL && backgroundMatrix != NULL && boxBounds != NULL) {
while (window->pollEvent(*sfEvent)) {
if (sfEvent->type == sf::Event::Closed) {
window->close();
}
if (sfEvent->type == sf::Event::MouseButtonReleased && *done == false) {
if (currentPlayer == PLAYER::PLAYER_1 || (currentPlayer == PLAYER::PLAYER_2 && *againstBot == false)) {
for (int y = 0; y < fieldMatrix->size(); y++) {
for (int x = 0; x < fieldMatrix->at(y)->size(); x++) {
boxBounds->left = x * 110 + 10;
boxBounds->top = y * 110 + 10;
if (boxBounds->contains(sf::Mouse::getPosition(*window).x,
sf::Mouse::getPosition(*window).y) &&
*fieldMatrix->at(y)->at(x)->isSet != true) {
setBox(fieldMatrix, currentPlayer, &sf::Vector2i(x, y));
currentPlayer == PLAYER::PLAYER_1 ? currentPlayer = PLAYER::PLAYER_2 : currentPlayer = PLAYER::PLAYER_1;
checkWinner(fieldMatrix, done);
std::cout << ">main: P1 set box at x = " << x << " y = " << y << std::endl;
}
}
}
}
}
if (sfEvent->type == sf::Event::KeyReleased) {
switch (sfEvent->key.code) {
case sf::Keyboard::Escape:
window->close();
break;
case sf::Keyboard::C:
clearField(fieldMatrix);
currentPlayer = PLAYER::PLAYER_1;
*done = false;
break;
}
}
}
window->clear();
for (int y = 0; y < backgroundMatrix->size(); y++) {
for (int x = 0; x < backgroundMatrix->at(y)->size(); x++) {
window->draw(*backgroundMatrix->at(y)->at(x));
if (*fieldMatrix->at(y)->at(x)->isSet) {
window->draw(*fieldMatrix->at(y)->at(x)->Sprite);
}
}
}
if (*againstBot == true && *done == false && currentPlayer == PLAYER::PLAYER_2) {
bot->UpdateField(fieldMatrix);
currentPlayer = PLAYER::PLAYER_1;
checkWinner(fieldMatrix, done);
}
window->display();
}
}
SAFE_DELETE(bot);
SAFE_DELETE(done);
SAFE_DELETE(window);
SAFE_DELETE(sfEvent);
SAFE_DELETE(boxBounds);
SAFE_DELETE(againstBot);
SAFE_DELETE(fieldMatrix);
SAFE_DELETE(backgroundMatrix);
return 0;
}
void setupBackground(std::vector<std::vector<sf::RectangleShape*>*> *fieldMatrix) { //SETUP THE BACKGROUND
std::vector<sf::RectangleShape*> *tmpFieldVec;
sf::RectangleShape *tmpRect;
for (int y = 0; y < FIELD_HEIGHT; y++) {
tmpFieldVec = new std::vector<sf::RectangleShape*>();
for (int x = 0; x < FIELD_WIDTH; x++) {
tmpRect = new sf::RectangleShape(sf::Vector2f(100.F, 100.F));
tmpRect->setPosition(x * 110.F + 10.F, y * 110.F + 10.F);
tmpRect->setFillColor(sf::Color(161, 161, 161));
tmpFieldVec->push_back(tmpRect);
}
fieldMatrix->push_back(tmpFieldVec);
}
}
void setupField(std::vector<std::vector<Box*>*> *fieldMatrix) { //SETUP THE FIELD INIT VARS ETC
std::vector<Box*> *tmpBoxVec;
Box *tmpBox;
for (int y = 0; y < FIELD_HEIGHT; y++) {
tmpBoxVec = new std::vector<Box*>();
for (int x = 0; x < FIELD_WIDTH; x++) {
tmpBox = new Box();
tmpBox->isSet = new bool;
*tmpBox->isSet = false;
tmpBox->Sprite = new sf::Sprite();
tmpBox->Owner = PLAYER::NONE;
tmpBoxVec->push_back(tmpBox);
}
fieldMatrix->push_back(tmpBoxVec);
}
}
void setBox(std::vector<std::vector<Box*>*> *fieldMatrix, PLAYER player, sf::Vector2i *boxPos){ //SET THE SELECTED BOX TO A X OR O
sf::Texture *tmpTex = new sf::Texture();
if (!tmpTex->loadFromFile("assets\\gfx\\Tiles.png"))
std::cout << ">Unable to load assets\\gfx\\Tiles.png" << std::endl;
fieldMatrix->at(boxPos->y)->at(boxPos->x)->Sprite->setTexture(*tmpTex);
if (player == PLAYER::PLAYER_1)
fieldMatrix->at(boxPos->y)->at(boxPos->x)->Sprite->setTextureRect(sf::IntRect(0, 0, 25, 25));
if (player == PLAYER::PLAYER_2)
fieldMatrix->at(boxPos->y)->at(boxPos->x)->Sprite->setTextureRect(sf::IntRect(25, 0, 25, 25));
fieldMatrix->at(boxPos->y)->at(boxPos->x)->Sprite->setScale(4.f, 4.f);
fieldMatrix->at(boxPos->y)->at(boxPos->x)->Sprite->setPosition(boxPos->x * 110.F + 10.F, boxPos->y * 110.F + 10.F);
fieldMatrix->at(boxPos->y)->at(boxPos->x)->Owner = player;
*fieldMatrix->at(boxPos->y)->at(boxPos->x)->isSet = true;
}
void clearField(std::vector<std::vector<Box*>*> *fieldMatrix) { //CLEAR THE FIELD MATRIX
for (int y = 0; y < fieldMatrix->size(); y++) {
for (int x = 0; x < fieldMatrix->at(y)->size(); x++) {
*fieldMatrix->at(y)->at(x)->isSet = false;
fieldMatrix->at(y)->at(x)->Owner = PLAYER::NONE;
}
}
}
void checkWinner(std::vector<std::vector<Box*>*> *fieldMatrix, bool *done) { //CHECK IF SOMEBODY WINS IN THIS MOVE
int *tmpCount = new int;
for (int y = 0; y < fieldMatrix->size(); y++) //HORIZONTAL CHECK
if (*fieldMatrix->at(y)->at(0)->isSet && *fieldMatrix->at(y)->at(1)->isSet && *fieldMatrix->at(y)->at(2)->isSet &&
fieldMatrix->at(y)->at(0)->Owner == fieldMatrix->at(y)->at(1)->Owner &&
fieldMatrix->at(y)->at(1)->Owner == fieldMatrix->at(y)->at(2)->Owner) {
std::cout << ">" << playerToString(fieldMatrix->at(y)->at(0)->Owner) << " hat gewonnen." << std::endl;
*done = true;
}
for (int x = 0; x < fieldMatrix->size(); x++) //VERTICAL CHECK
if (*fieldMatrix->at(0)->at(x)->isSet && *fieldMatrix->at(1)->at(x)->isSet && *fieldMatrix->at(2)->at(x)->isSet &&
fieldMatrix->at(0)->at(x)->Owner == fieldMatrix->at(1)->at(x)->Owner &&
fieldMatrix->at(1)->at(x)->Owner == fieldMatrix->at(2)->at(x)->Owner) {
std::cout << ">" << playerToString(fieldMatrix->at(0)->at(x)->Owner) << " hat gewonnen." << std::endl;
*done = true;
}
if (*fieldMatrix->at(0)->at(0)->isSet && *fieldMatrix->at(1)->at(1)->isSet && *fieldMatrix->at(2)->at(2)->isSet && //LEFT UP TO RIGHT DOWN
fieldMatrix->at(0)->at(0)->Owner == fieldMatrix->at(1)->at(1)->Owner &&
fieldMatrix->at(1)->at(1)->Owner == fieldMatrix->at(2)->at(2)->Owner) {
std::cout << ">" << playerToString(fieldMatrix->at(1)->at(1)->Owner) << " hat gewonnen." << std::endl;
*done = true;
}
if (*fieldMatrix->at(0)->at(2)->isSet && *fieldMatrix->at(1)->at(1)->isSet && *fieldMatrix->at(2)->at(0)->isSet && //RIGHT UP TO LEFT DOWN
fieldMatrix->at(0)->at(2)->Owner == fieldMatrix->at(1)->at(1)->Owner &&
fieldMatrix->at(1)->at(1)->Owner == fieldMatrix->at(2)->at(0)->Owner) {
std::cout << ">" << playerToString(fieldMatrix->at(1)->at(1)->Owner) << " hat gewonnen." << std::endl;
*done = true;
}
}
std::string playerToString(PLAYER player) {
if (player == PLAYER::PLAYER_1)
return "Spieler 1";
if (player == PLAYER::PLAYER_2)
return "Spieler 2";
if (player == PLAYER::NONE)
return "NONE";
}
|
b5c01eb332ae4fd67e2cb4e6e5ba4ec29eeccad7 | 49e44cd8ba6a0ed53c3fa3a40859d83ca9371e6d | /src/yasync/lockScope.h | f3338b86dfa67e1df82018f72091b410cd8248bd | [
"MIT"
] | permissive | ondra-novak/yasync | a8af182217d42fed3dd8f57fdffa61130b5eaf4e | 39734bc1da3cdd5e9fc51abfbbfe57518587c39f | refs/heads/master | 2021-01-10T18:31:54.783604 | 2017-08-10T15:24:23 | 2017-08-10T15:24:23 | 74,596,811 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | h | lockScope.h | #pragma once
namespace yasync {
///Locks the current scope (unlocks in destructor)
template<typename _Mutex>
class LockScope {
public:
typedef _Mutex mutex_type;
explicit LockScope(mutex_type& __m) : mutex(__m)
{ mutex.lock(); }
LockScope(mutex_type& __m, bool locked) : mutex(__m)
{ if (!locked) mutex.lock(); }
~LockScope()
{ mutex.unlock(); }
LockScope(const LockScope&) = delete;
LockScope& operator=(const LockScope&) = delete;
private:
mutex_type& mutex;
};
///Unlocks the current scope (locks in destructor)
template<typename _Mutex>
class UnlockScope {
public:
typedef _Mutex mutex_type;
explicit UnlockScope(mutex_type& __m) : mutex(__m)
{ mutex.unlock(); }
~UnlockScope()
{ mutex.lock(); }
UnlockScope(const UnlockScope&) = delete;
UnlockScope& operator=(const UnlockScope&) = delete;
private:
mutex_type& mutex;
};
}
|
110123c680fb77687e13cc63f7c1e5fb76ac2a5a | 93cef903f4d1eabdcdc34de35fa12f15b452116f | /tests/resources/test_atc_env/test_backup/agc029/C/main.cpp | a4b63fb6b666d56d0e4bfe1516597616af1937b0 | [
"MIT"
] | permissive | sei40kr/atcoder-tools | 0029e8d8bd65f97e50961247f03dcef831905c3d | 693427a14b296584eab6e20d8f5326d61486a535 | refs/heads/master | 2020-04-26T19:28:23.272296 | 2019-11-01T15:53:09 | 2019-11-01T15:53:09 | 173,776,065 | 3 | 0 | MIT | 2019-03-04T15:59:25 | 2019-03-04T15:59:25 | null | UTF-8 | C++ | false | false | 300 | cpp | main.cpp | #include <bits/stdc++.h>
using namespace std;
void solve(long long N, std::vector<long long> A){
}
int main(){
long long N;
scanf("%lld",&N);
std::vector<long long> A(N);
for(int i = 0 ; i < N ; i++){
scanf("%lld",&A[i]);
}
solve(N, std::move(A));
return 0;
}
|
12bf005d1c887e1ed714995261d581febac171ed | 00e1c3843ed4389bd8f6262236f9d91237b12046 | /lab6/array_stats.cpp | 02cf5fdc4771288246195f4d1deeabdb6655389c | [] | no_license | kartikeyhpandey/CS1 | bddc7c90714fea9bc3453269dd28a1e60f33295f | 8bedc6f6c8275254c1f9d8b4984004d61b890890 | refs/heads/master | 2020-07-31T13:27:10.765363 | 2019-04-28T16:56:51 | 2019-04-28T16:56:51 | 210,617,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,302 | cpp | array_stats.cpp | #include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iomanip>
using namespace std;
int randNum(int randMax){
return (rand()%(randMax+1));
}
vector<int> freqVector(int numSample, int randMax){
vector<int> freqCount(randMax+1);
for(int i=0; i<numSample; i++){
int randSample = randNum(randMax);
freqCount[randSample]+=1;
}
return freqCount;
}
int maxVec(vector<int>& freqCount){
int max=freqCount[0];
for(unsigned int i=0; i<freqCount.size();i++){
if(freqCount[i]>=max){
max=freqCount[i];
}
}
return max;
}
int minVec(vector<int>& freqCount){
int min=freqCount[0];
for(unsigned int i=0; i<freqCount.size();i++){
if(freqCount[i]<=min){
min=freqCount[i];
}
}
return min;
}
int sumVec(vector<int>& freqCount){
int sum=0;
for(unsigned int i=0; i<freqCount.size();i++){
sum+=freqCount[i];
}
return sum;
}
double mean(vector<int>& freqCount){
return sumVec(freqCount)/double(freqCount.size());
}
void barPrint(int value, int scale){
int N=value/scale;
for (int i=0; i<N; i++){
cout<<"*";
}
}
int main()
{
int randMax, numSample;
cout<<"Enter End Range: ";
cin>>randMax;
cout<<endl;
cout<<"Enter number of Samples: ";
cin>>numSample;
cout<<endl;
vector<int> freqCount=freqVector(numSample,randMax);
int scale= maxVec(freqCount)/50;
if(scale==0)
scale=1;
cout<<setw(5)<<"Index"<<"\t";
cout<<setw(5)<<"Value"<<"\t";
cout<<"Bar";
cout<<endl;
for(unsigned int i=0; i<freqCount.size(); i++){
cout<<setw(5)<<i<<"\t";
cout<<setw(5)<<freqCount[i]<<"\t";
barPrint(freqCount[i],scale);
cout<<endl;
}
cout<<"Scale: "<<scale<<" per *"<<endl;
cout<<endl;
cout<<"Range: 0 to "<<randMax<<endl;
cout<<"Sample Count: "<<numSample<<endl;
cout<<"Min Value: "<<minVec(freqCount)<<endl;
cout<<"Max Value: "<<maxVec(freqCount)<<endl;
cout<<"Sum Value: "<<sumVec(freqCount)<<endl;
cout<<"Mean Value: "<<mean(freqCount)<<endl;
return 0;
}
|
38a1812204f22a3e28018a652f3ba36954434bad | 3e9c9f08f19644c8baa37c3cb63167b7ae374386 | /mainwindow.cpp | db52f087804bf9b219232118071dec5eca27173c | [] | no_license | eveningwyn/EthernetTool | df552463aaa0d3c3fee3ceaf2dc44b9752835afe | 2232c78b9d152cc9768da8580ffa5ec182cf43a3 | refs/heads/master | 2021-01-20T03:09:51.912754 | 2017-08-27T14:19:35 | 2017-08-27T14:19:35 | 101,353,176 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,429 | cpp | mainwindow.cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMutex>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QSettings>
#include <QRegExp>
#include <QMetaType>
#include <QMessageBox>
#define PRO_VERSION "V1.03"
#define BUILT_DATE "2017-08-27"
void MainWindow::on_actionAbout_triggered()
{
QMessageBox::about(this,NULL,QString(tr("\nVersion: %1\n"
"\nBuilt on %2\n"
"\n\t---evening.wen\n"))
.arg(PRO_VERSION).arg(BUILT_DATE));
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qRegisterMetaType<QString>("QString&");
qRegisterMetaType<SocketObj>("SocketObj");
qRegisterMetaType<ShowMsg>("ShowMsg");
// ui->lineEdit_serverIP->setText("127.0.0.14");
// ui->lineEdit_serverPort->setText("8080");
m_pTcpip = new TcpipObj;
m_pThread = new QThread;
connect(m_pThread,&QThread::started,m_pTcpip,&TcpipObj::init);
connect(m_pTcpip,&TcpipObj::log,this,&MainWindow::log);
connect(m_pTcpip,&TcpipObj::createSuccess,this,&MainWindow::createSuccess);
connect(m_pTcpip,&TcpipObj::showServerSendIpPort,this,
[this](const QString &ip, const QString &port)
{
ui->lineEdit_serverIP_send->setText(ip);
ui->lineEdit_serverPort_send->setText(port);
emit setServerSendIpPort(ip,port);
});
connect(this,&MainWindow::setCommFileName,m_pTcpip,&TcpipObj::setCommFileName);
connect(this,&MainWindow::setTimingFileName,m_pTcpip,&TcpipObj::setTimingFileName);
connect(this,&MainWindow::createObj,m_pTcpip,&TcpipObj::createObj);
connect(this,&MainWindow::setServerSendIpPort,m_pTcpip,&TcpipObj::setServerSendIpPort);
connect(this,&MainWindow::manualSendMsg,m_pTcpip,&TcpipObj::manualSendMsg);
connect(this,&MainWindow::deleteObj,m_pTcpip,&TcpipObj::deleteObj);
connect(ui->comboBox_split,&QComboBox::currentTextChanged,m_pTcpip,&TcpipObj::setRegExpPattern);
this->init();
m_pTcpip->moveToThread(m_pThread);
m_pThread->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::init()
{
QRegExp regExpIP("((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])[\\.]){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])");
QRegExp regExpNetPort("((6553[0-5])|[655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{3}|[1-9][0-9]{2}|[1-9][0-9]|[0-9])");
ui->lineEdit_serverIP->setValidator(new QRegExpValidator(regExpIP,this));
ui->lineEdit_serverPort->setValidator(new QRegExpValidator(regExpNetPort,this));
ui->lineEdit_clientPort->setValidator(new QRegExpValidator(regExpNetPort,this));
ui->lineEdit_serverIP_send->setValidator(new QRegExpValidator(regExpIP,this));
ui->lineEdit_serverPort_send->setValidator(new QRegExpValidator(regExpNetPort,this));
m_strLogFileName = "";
ui->mainToolBar->hide();
ui->comboBox_split->setCurrentIndex(1);
ui->label_clientPort->hide();
ui->checkBox_clientPort->hide();
ui->lineEdit_clientPort->hide();
ui->pushButton_send->setEnabled(false);
ui->pushButton_delete->setEnabled(false);
}
void MainWindow::log(const QString &msg, const ShowMsg &index)
{
static QMutex mutexLog;
mutexLog.lock();
QString time = QDateTime::currentDateTime().toString("yyyyMMdd_hh:mm:ss_zzz");
QString senderStr;
switch (index) {
case SHOW_SENDER:
senderStr = "Send to";
break;
case SHOW_RECEIVE:
senderStr = "Receive from";
break;
case SHOW_NULL:
senderStr = "";
break;
default:
senderStr = "";
break;
}
QString strMsg = QString("%1 %2:%3\n").arg(time).arg(senderStr).arg(msg);
if(!ui->checkBox_pauseShow->isChecked())
{
// ui->textBrowser_show_msg->moveCursor(QTextCursor::End);
// ui->textBrowser_show_msg->insertPlainText(strMsg);
// ui->textBrowser_show_msg->moveCursor(QTextCursor::End);
ui->textBrowser_show_msg->append(strMsg);
}
if(ui->checkBox_saveLog->isChecked())
{
saveLog(strMsg);
}
mutexLog.unlock();
}
void MainWindow::saveLog(const QString &msg)
{
if(!m_strLogFileName.isEmpty())
{
QFile file(m_strLogFileName);
if(file.open(QFile::Append | QIODevice::Text))
{
QTextStream out(&file);
out << msg;
if(!file.flush())
{
qWarning("log文件刷新失败!");
}
file.close();
}
}
}
void MainWindow::on_checkBox_saveLog_clicked()
{
if(ui->checkBox_saveLog->isChecked())
{
m_strLogFileName = QFileDialog::getSaveFileName(this,tr("选择存储路径"),
"..\\Message_log.txt",
tr("Text files (*.txt)"));
if(m_strLogFileName.isEmpty())
{
m_strLogFileName = "";
ui->checkBox_saveLog->setChecked(false);
return;
}
log(tr("通讯信息将保存到文件%1当中!").arg(m_strLogFileName),SHOW_NULL);
}
else
{
m_strLogFileName = "";
}
}
void MainWindow::on_pushButton_clear_clicked()
{
ui->textBrowser_show_msg->clear();
}
void MainWindow::on_pushButton_loadFile_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,tr("load"),
"..\\Message_list.txt",
tr("Text files (*.txt)"));
if(!fileName.isEmpty())
{
log(tr("加载通讯文件 %1成功!").arg(fileName),SHOW_NULL);
}
else
{
log(tr("已取消加载通讯文件!"),SHOW_NULL);
}
emit setCommFileName(fileName);
}
void MainWindow::on_pushButton_timer_clicked()
{
QString timerFileName = QFileDialog::getOpenFileName(this,tr("load"),
"..\\timer_list.txt",
tr("Text Files (*.txt)"));
if(!timerFileName.isEmpty())
{
log(tr("加载定时文件 %1成功!").arg(timerFileName),SHOW_NULL);
}
else
{
log(tr("已取消加载定时文件!"),SHOW_NULL);
}
emit setTimingFileName(timerFileName);
}
void MainWindow::on_pushButton_creat_clicked()
{
QString server_IP = ui->lineEdit_serverIP->text();
QString port = ui->lineEdit_serverPort->text();
int server_Port;
bool ok;
server_Port = port.toInt(&ok,10);
QString prefix = ui->comboBox_prefix->currentText();
QString suffix = ui->comboBox_suffix->currentText();
suffix.replace("\\r","\r");
suffix.replace("\\n","\n");
if(server_IP.isEmpty() || port.isEmpty() || !ok)
{
log(tr("请正确设置IP地址和端口号!"),SHOW_NULL);
return;
}
if(0==ui->comboBox_server_client->currentIndex())//服务器
{
emit createObj(server_IP,server_Port,prefix,suffix,TCPIP_SERVER);
}
else
{
if(1==ui->comboBox_server_client->currentIndex())//客户端
{
int clientPort = ui->lineEdit_clientPort->text().toInt();
if(ui->checkBox_clientPort->isChecked()
&& 0 < clientPort
&& "" != ui->lineEdit_clientPort->text())
{
emit createObj(server_IP,server_Port,prefix,suffix,TCPIP_CLIENT,clientPort);
}
else
{
emit createObj(server_IP,server_Port,prefix,suffix,TCPIP_CLIENT);
}
}
}
}
void MainWindow::on_pushButton_delete_clicked()
{
emit deleteObj((SocketObj) ui->comboBox_server_client->currentIndex());
ui->lineEdit_serverIP_send->clear();
ui->lineEdit_serverPort_send->clear();
}
void MainWindow::on_pushButton_send_clicked()
{
QString strMsg = ui->lineEdit_input->text();
if(!strMsg.isEmpty())
{
emit manualSendMsg((SocketObj)ui->comboBox_server_client->currentIndex(),strMsg);
}
}
void MainWindow::createSuccess(const SocketObj &index, const bool &success)
{
ui->pushButton_creat->setDisabled(success);
ui->comboBox_server_client->setDisabled(success);
ui->pushButton_delete->setDisabled(!success);
ui->lineEdit_serverIP->setDisabled(success);
ui->lineEdit_serverPort->setDisabled(success);
ui->comboBox_prefix->setDisabled(success);
ui->comboBox_suffix->setDisabled(success);
ui->checkBox_clientPort->setDisabled(success);
ui->lineEdit_clientPort->setDisabled(success);
if(!ui->checkBox_clientPort->isChecked())
{
ui->lineEdit_clientPort->setDisabled(true);
}
ui->pushButton_send->setEnabled(success);
ui->pushButton_delete->setEnabled(success);
}
void MainWindow::on_lineEdit_serverIP_send_returnPressed()
{
QString strIp = ui->lineEdit_serverIP_send->text();
QString strPort = ui->lineEdit_serverPort_send->text();
if(!strIp.isEmpty() && !strPort.isEmpty())
{
emit setServerSendIpPort(strIp,strPort);
}
}
void MainWindow::on_lineEdit_serverPort_send_returnPressed()
{
QString strIp = ui->lineEdit_serverIP_send->text();
QString strPort = ui->lineEdit_serverPort_send->text();
if(!strIp.isEmpty() && !strPort.isEmpty())
{
emit setServerSendIpPort(strIp,strPort);
}
}
void MainWindow::on_comboBox_server_client_currentIndexChanged(int index)
{
switch (index) {
case TCPIP_SERVER:
ui->label_serverIP_send->show();
ui->label_serverPort_send->show();
ui->lineEdit_serverIP_send->show();
ui->lineEdit_serverPort_send->show();
ui->label_clientPort->hide();
ui->checkBox_clientPort->hide();
ui->lineEdit_clientPort->hide();
break;
case TCPIP_CLIENT:
ui->label_serverIP_send->hide();
ui->label_serverPort_send->hide();
ui->lineEdit_serverIP_send->hide();
ui->lineEdit_serverPort_send->hide();
ui->label_clientPort->show();
ui->checkBox_clientPort->show();
ui->lineEdit_clientPort->show();
break;
default:
break;
}
}
void MainWindow::on_checkBox_clientPort_clicked()
{
ui->lineEdit_clientPort->setEnabled(ui->checkBox_clientPort->isChecked());
}
|
a2ca6327c127618e6ba1f0c8c2d9a72168d1ff7f | a4b09665ae7e698652aff7f67a751c031271ee14 | /DEM/Low/src/Render/D3D9/D3D9ConstantBuffer.cpp | 0fce35b67b83b856a1cd4a87ee5f7a2c6480a9e7 | [
"MIT"
] | permissive | ugozapad/deusexmachina | 80ce769c83ed997fa6440402ac4f0123ce907310 | f5ca9f2eb850bc827bcf2c18a7303f3e569fea5c | refs/heads/master | 2020-05-20T04:38:43.234542 | 2019-01-17T11:27:24 | 2019-01-17T11:27:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,587 | cpp | D3D9ConstantBuffer.cpp | #include "D3D9ConstantBuffer.h"
#include <Render/D3D9/SM30ShaderMetadata.h>
#include <Core/Factory.h>
#define WIN32_LEAN_AND_MEAN
#define D3D_DISABLE_9EX
#include <d3d9.h>
namespace Render
{
__ImplementClass(Render::CD3D9ConstantBuffer, 'CB09', Render::CConstantBuffer);
CD3D9ConstantBuffer::CD3D9ConstantBuffer() {}
CD3D9ConstantBuffer::~CD3D9ConstantBuffer()
{
InternalDestroy();
}
//---------------------------------------------------------------------
//!!!???assert destroyed?!
bool CD3D9ConstantBuffer::Create(const CSM30BufferMeta& Meta, const CD3D9ConstantBuffer* pInitData)
{
Float4Count = 0;
const CFixedArray<CRange>& Float4 = Meta.Float4;
for (UPTR i = 0; i < Float4.GetCount(); ++i)
Float4Count += Float4[i].Count;
Int4Count = 0;
const CFixedArray<CRange>& Int4 = Meta.Int4;
for (UPTR i = 0; i < Int4.GetCount(); ++i)
Int4Count += Int4[i].Count;
BoolCount = 0;
const CFixedArray<CRange>& Bool = Meta.Bool;
for (UPTR i = 0; i < Bool.GetCount(); ++i)
BoolCount += Bool[i].Count;
UPTR Float4Size = Float4Count * sizeof(float) * 4;
UPTR Int4Size = Int4Count * sizeof(int) * 4;
UPTR BoolSize = BoolCount * sizeof(BOOL);
UPTR TotalSize = Float4Size + Int4Size + BoolSize;
if (!TotalSize) FAIL;
if (pInitData && (Float4Count != pInitData->Float4Count || Int4Count != pInitData->Int4Count || BoolCount != pInitData->BoolCount)) FAIL;
char* pData = (char*)n_malloc_aligned(TotalSize, 16);
if (!pData)
{
Float4Count = 0;
Int4Count = 0;
BoolCount = 0;
FAIL;
}
if (pInitData)
{
const void* pInitDataPtr = pInitData->pFloat4Data ?
(const void*)pInitData->pFloat4Data :
(pInitData->pInt4Data ? (const void*)pInitData->pInt4Data : (const void*)pInitData->pBoolData);
memcpy(pData, pInitDataPtr, TotalSize);
}
else
{
// Documented SM 3.0 defaults are 0, 0.f and FALSE
memset(pData, 0, TotalSize);
}
if (Float4Size)
{
pFloat4Data = (float*)pData;
pData += Float4Size;
}
if (Int4Size)
{
pInt4Data = (int*)pData;
pData += Int4Size;
}
if (BoolSize)
{
pBoolData = (BOOL*)pData;
pData += BoolSize;
}
Handle = Meta.Handle;
OK;
}
//---------------------------------------------------------------------
void CD3D9ConstantBuffer::InternalDestroy()
{
if (pFloat4Data) n_free_aligned(pFloat4Data);
else if (pInt4Data) n_free_aligned(pInt4Data);
else if (pBoolData) n_free_aligned(pBoolData);
pFloat4Data = NULL;
pInt4Data = NULL;
pBoolData = NULL;
Float4Count = 0;
Int4Count = 0;
BoolCount = 0;
Handle = INVALID_HANDLE;
}
//---------------------------------------------------------------------
}
|
c7ff4e5090cbe1d9acb92ae6a15f80ad9c778ff3 | e097ca136d17ff092e89b3b54214ec09f347604f | /include/amtrs/io/.inc-io/io-streamif-string_view.hpp | ef02b79d1071a59047202c097140edd166217d0d | [
"BSD-2-Clause"
] | permissive | isaponsoft/libamtrs | 1c02063c06613cc43091d5341c132b45d3051ee0 | 0c5d4ebe7e0f23d260bf091a4ab73ab9809daa50 | refs/heads/master | 2023-01-14T16:48:23.908727 | 2022-12-28T02:27:46 | 2022-12-28T02:27:46 | 189,788,925 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,205 | hpp | io-streamif-string_view.hpp | /* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *
* Use of this source code is governed by a BSD-style license that *
* can be found in the LICENSE file. */
#ifndef __libamtrs__io__streamif__string_view__hpp
#define __libamtrs__io__streamif__string_view__hpp
#include <ios>
#include <sstream>
#include <iostream>
AMTRS_IO_NAMESPACE_BEGIN
template<>
struct streamif_traits<std::string_view>
{
using stream_type = std::string_view;
using size_type = std::streamsize;
using fpos_type = std::fpos<typename std::char_traits<char>::state_type>;
protected:
streamif_traits()
: cur(0)
{}
streamif_base::iostate read(stream_type& _value, size_type& _readsize, void* _data, size_type _size)
{
streamif_base::iostate bits = streamif_base::goodbit;
size_type sz = std::min<size_type>(_size, _value.size() - cur);
std::copy_n(_value.data() + cur, sz, (char*)_data);
cur += sz;
_readsize = sz;
if (cur == _value.size())
{
bits = (streamif_base::iostate)((int)bits | (int)streamif_base::eofbit);
}
return bits;
}
streamif_base::iostate seek(stream_type& _value, fpos_type& _position, streamif_base::seekdir _org)
{
switch (_org)
{
case streamif_base::beg :
{
cur = _position;
break;
}
case streamif_base::cur :
{
cur += _position;
break;
}
case streamif_base::end :
{
cur = _value.size() + _position;
break;
}
default :
{
return streamif_base::failbit;
}
}
cur = std::max<fpos_type>(cur, 0);
cur = std::min<fpos_type>(cur, _value.size());
_position = cur;
return streamif_base::goodbit;
}
streamif_base::iostate tell(stream_type& _value, fpos_type& _position)
{
_position = cur;
return streamif_base::goodbit;
}
streamif_base::iostate size(stream_type& _value, size_type& _size)
{
_size = _value.size();
return streamif_base::goodbit;
}
fpos_type cur;
};
using stringview_streamif = basic_streamif<std::string_view>;
template<class Source, base_if<std::string_view, Source> = 0>
auto make_streamif(Source _value)
{
return make_basic_streamif<Source>(std::move(_value));
}
AMTRS_IO_NAMESPACE_END
#endif
|
1371b9415b9c93a325116b13c511adeb1b6641b2 | 00c285309e7747e255a58484397c80264a6f85e7 | /Magic3D/build/ui_greentech.h | f8af0d2dbc0cdfcd8ae7d1ebdba1479aef7d9016 | [] | no_license | PuddingPengChen/Magic3D | e48b2b51d4f03369d73f856be3dc3e73107e7602 | 70e4757673020a42923f7cfbac8c09258107cd24 | refs/heads/master | 2021-09-27T02:12:05.645448 | 2021-09-23T06:08:27 | 2021-09-23T06:08:27 | 36,716,527 | 21 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 16,542 | h | ui_greentech.h | /********************************************************************************
** Form generated from reading UI file 'greentech.ui'
**
** Created: Tue Jun 2 12:22:59 2015
** by: Qt User Interface Compiler version 4.8.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_GREENTECH_H
#define UI_GREENTECH_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QMainWindow>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QStatusBar>
#include <QtGui/QToolBar>
#include <QtGui/QWidget>
#include <./Interface/graph.h>
QT_BEGIN_NAMESPACE
class Ui_GreenTech
{
public:
QAction *actionBack_View;
QAction *actionAuto_Support;
QAction *actionDeleteSupport;
QAction *actionManuAddSupport;
QAction *actionAddBasePlate;
QAction *actionLight_support;
QAction *actionMedium_support;
QAction *actionHeavy_support;
QAction *actionOpen;
QAction *actionSave;
QAction *actionQuit_Pudding;
QAction *actionSave_2;
QAction *actionMove;
QAction *actionScale;
QAction *actionRotate;
QAction *actionReset_Rotate;
QAction *actionSelect;
QAction *actionCopy;
QAction *actionDelete;
QAction *actionSnap;
QAction *actionOrtho;
QAction *actionPerspective;
QAction *actionTopView;
QAction *actionBottomView;
QAction *actionRightView;
QAction *actionLeftView;
QAction *actionFrontView;
QAction *actionBackView;
QAction *actionAuto;
QAction *actionManuDelete;
QAction *actionLight;
QAction *actionMid;
QAction *actionHeavy;
QAction *actionDeleteAll;
QAction *actionRemoveAll;
QWidget *centralwidget;
QGridLayout *gridLayout;
Graph *graphicsView;
QMenuBar *menubar;
QMenu *menuFile;
QMenu *menuEdit;
QMenu *menuHelp;
QMenu *menuView;
QStatusBar *statusbar;
QToolBar *viewToolBar;
QToolBar *supportEdit;
void setupUi(QMainWindow *GreenTech)
{
if (GreenTech->objectName().isEmpty())
GreenTech->setObjectName(QString::fromUtf8("GreenTech"));
GreenTech->resize(800, 600);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(GreenTech->sizePolicy().hasHeightForWidth());
GreenTech->setSizePolicy(sizePolicy);
GreenTech->setStyleSheet(QString::fromUtf8("QMainWindow{\n"
" background-color: rgb(244, 244, 244);\n"
"}"));
actionBack_View = new QAction(GreenTech);
actionBack_View->setObjectName(QString::fromUtf8("actionBack_View"));
QFont font;
font.setFamily(QString::fromUtf8("Andalus"));
font.setPointSize(12);
font.setBold(false);
font.setWeight(50);
actionBack_View->setFont(font);
actionAuto_Support = new QAction(GreenTech);
actionAuto_Support->setObjectName(QString::fromUtf8("actionAuto_Support"));
actionAuto_Support->setFont(font);
actionDeleteSupport = new QAction(GreenTech);
actionDeleteSupport->setObjectName(QString::fromUtf8("actionDeleteSupport"));
actionDeleteSupport->setFont(font);
actionManuAddSupport = new QAction(GreenTech);
actionManuAddSupport->setObjectName(QString::fromUtf8("actionManuAddSupport"));
actionManuAddSupport->setFont(font);
actionAddBasePlate = new QAction(GreenTech);
actionAddBasePlate->setObjectName(QString::fromUtf8("actionAddBasePlate"));
actionAddBasePlate->setFont(font);
actionLight_support = new QAction(GreenTech);
actionLight_support->setObjectName(QString::fromUtf8("actionLight_support"));
actionLight_support->setCheckable(true);
actionLight_support->setFont(font);
actionMedium_support = new QAction(GreenTech);
actionMedium_support->setObjectName(QString::fromUtf8("actionMedium_support"));
actionMedium_support->setCheckable(true);
actionMedium_support->setFont(font);
actionHeavy_support = new QAction(GreenTech);
actionHeavy_support->setObjectName(QString::fromUtf8("actionHeavy_support"));
actionHeavy_support->setCheckable(true);
actionHeavy_support->setFont(font);
actionOpen = new QAction(GreenTech);
actionOpen->setObjectName(QString::fromUtf8("actionOpen"));
actionSave = new QAction(GreenTech);
actionSave->setObjectName(QString::fromUtf8("actionSave"));
actionQuit_Pudding = new QAction(GreenTech);
actionQuit_Pudding->setObjectName(QString::fromUtf8("actionQuit_Pudding"));
actionSave_2 = new QAction(GreenTech);
actionSave_2->setObjectName(QString::fromUtf8("actionSave_2"));
actionMove = new QAction(GreenTech);
actionMove->setObjectName(QString::fromUtf8("actionMove"));
actionScale = new QAction(GreenTech);
actionScale->setObjectName(QString::fromUtf8("actionScale"));
actionRotate = new QAction(GreenTech);
actionRotate->setObjectName(QString::fromUtf8("actionRotate"));
actionReset_Rotate = new QAction(GreenTech);
actionReset_Rotate->setObjectName(QString::fromUtf8("actionReset_Rotate"));
actionSelect = new QAction(GreenTech);
actionSelect->setObjectName(QString::fromUtf8("actionSelect"));
actionCopy = new QAction(GreenTech);
actionCopy->setObjectName(QString::fromUtf8("actionCopy"));
actionDelete = new QAction(GreenTech);
actionDelete->setObjectName(QString::fromUtf8("actionDelete"));
actionSnap = new QAction(GreenTech);
actionSnap->setObjectName(QString::fromUtf8("actionSnap"));
actionOrtho = new QAction(GreenTech);
actionOrtho->setObjectName(QString::fromUtf8("actionOrtho"));
actionPerspective = new QAction(GreenTech);
actionPerspective->setObjectName(QString::fromUtf8("actionPerspective"));
actionTopView = new QAction(GreenTech);
actionTopView->setObjectName(QString::fromUtf8("actionTopView"));
actionBottomView = new QAction(GreenTech);
actionBottomView->setObjectName(QString::fromUtf8("actionBottomView"));
actionRightView = new QAction(GreenTech);
actionRightView->setObjectName(QString::fromUtf8("actionRightView"));
actionLeftView = new QAction(GreenTech);
actionLeftView->setObjectName(QString::fromUtf8("actionLeftView"));
actionFrontView = new QAction(GreenTech);
actionFrontView->setObjectName(QString::fromUtf8("actionFrontView"));
actionBackView = new QAction(GreenTech);
actionBackView->setObjectName(QString::fromUtf8("actionBackView"));
actionAuto = new QAction(GreenTech);
actionAuto->setObjectName(QString::fromUtf8("actionAuto"));
actionManuDelete = new QAction(GreenTech);
actionManuDelete->setObjectName(QString::fromUtf8("actionManuDelete"));
actionLight = new QAction(GreenTech);
actionLight->setObjectName(QString::fromUtf8("actionLight"));
actionMid = new QAction(GreenTech);
actionMid->setObjectName(QString::fromUtf8("actionMid"));
actionHeavy = new QAction(GreenTech);
actionHeavy->setObjectName(QString::fromUtf8("actionHeavy"));
actionDeleteAll = new QAction(GreenTech);
actionDeleteAll->setObjectName(QString::fromUtf8("actionDeleteAll"));
actionRemoveAll = new QAction(GreenTech);
actionRemoveAll->setObjectName(QString::fromUtf8("actionRemoveAll"));
QFont font1;
font1.setFamily(QString::fromUtf8("Andalus"));
font1.setPointSize(12);
actionRemoveAll->setFont(font1);
centralwidget = new QWidget(GreenTech);
centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
gridLayout = new QGridLayout(centralwidget);
gridLayout->setSpacing(0);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
gridLayout->setContentsMargins(0, 0, 0, 0);
graphicsView = new Graph(centralwidget);
graphicsView->setObjectName(QString::fromUtf8("graphicsView"));
graphicsView->setFocusPolicy(Qt::NoFocus);
graphicsView->setStyleSheet(QString::fromUtf8("Graph{\n"
" background-color: rgb(244, 244, 244);\n"
"}"));
graphicsView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
graphicsView->setRubberBandSelectionMode(Qt::IntersectsItemShape);
gridLayout->addWidget(graphicsView, 0, 0, 1, 1);
GreenTech->setCentralWidget(centralwidget);
menubar = new QMenuBar(GreenTech);
menubar->setObjectName(QString::fromUtf8("menubar"));
menubar->setGeometry(QRect(0, 0, 800, 23));
menuFile = new QMenu(menubar);
menuFile->setObjectName(QString::fromUtf8("menuFile"));
menuEdit = new QMenu(menubar);
menuEdit->setObjectName(QString::fromUtf8("menuEdit"));
menuHelp = new QMenu(menubar);
menuHelp->setObjectName(QString::fromUtf8("menuHelp"));
menuView = new QMenu(menubar);
menuView->setObjectName(QString::fromUtf8("menuView"));
GreenTech->setMenuBar(menubar);
statusbar = new QStatusBar(GreenTech);
statusbar->setObjectName(QString::fromUtf8("statusbar"));
GreenTech->setStatusBar(statusbar);
viewToolBar = new QToolBar(GreenTech);
viewToolBar->setObjectName(QString::fromUtf8("viewToolBar"));
GreenTech->addToolBar(Qt::TopToolBarArea, viewToolBar);
supportEdit = new QToolBar(GreenTech);
supportEdit->setObjectName(QString::fromUtf8("supportEdit"));
GreenTech->addToolBar(Qt::TopToolBarArea, supportEdit);
menubar->addAction(menuFile->menuAction());
menubar->addAction(menuEdit->menuAction());
menubar->addAction(menuView->menuAction());
menubar->addAction(menuHelp->menuAction());
menuFile->addAction(actionOpen);
menuFile->addAction(actionSave_2);
menuFile->addSeparator();
menuFile->addAction(actionQuit_Pudding);
menuEdit->addAction(actionSelect);
menuEdit->addAction(actionCopy);
menuEdit->addAction(actionDelete);
menuEdit->addSeparator();
menuEdit->addAction(actionMove);
menuEdit->addAction(actionScale);
menuEdit->addAction(actionRotate);
menuEdit->addAction(actionReset_Rotate);
menuEdit->addSeparator();
menuEdit->addAction(actionSnap);
menuView->addAction(actionOrtho);
menuView->addAction(actionPerspective);
menuView->addSeparator();
menuView->addAction(actionTopView);
menuView->addAction(actionBottomView);
menuView->addAction(actionRightView);
menuView->addAction(actionLeftView);
menuView->addAction(actionFrontView);
menuView->addAction(actionBackView);
retranslateUi(GreenTech);
QMetaObject::connectSlotsByName(GreenTech);
} // setupUi
void retranslateUi(QMainWindow *GreenTech)
{
GreenTech->setWindowTitle(QApplication::translate("GreenTech", "MainWindow", 0, QApplication::UnicodeUTF8));
actionBack_View->setText(QApplication::translate("GreenTech", "Back_View", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
actionBack_View->setToolTip(QApplication::translate("GreenTech", "OutSupportMode", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
actionAuto_Support->setText(QApplication::translate("GreenTech", "Auto_Support", 0, QApplication::UnicodeUTF8));
actionDeleteSupport->setText(QApplication::translate("GreenTech", "DeleteSupport", 0, QApplication::UnicodeUTF8));
actionManuAddSupport->setText(QApplication::translate("GreenTech", "ManuAddSupport", 0, QApplication::UnicodeUTF8));
actionAddBasePlate->setText(QApplication::translate("GreenTech", "AddBasePlate", 0, QApplication::UnicodeUTF8));
actionLight_support->setText(QApplication::translate("GreenTech", "Light_support", 0, QApplication::UnicodeUTF8));
actionMedium_support->setText(QApplication::translate("GreenTech", "Medium_support", 0, QApplication::UnicodeUTF8));
actionHeavy_support->setText(QApplication::translate("GreenTech", "Heavy_support", 0, QApplication::UnicodeUTF8));
actionOpen->setText(QApplication::translate("GreenTech", "Open", 0, QApplication::UnicodeUTF8));
actionSave->setText(QApplication::translate("GreenTech", "Save", 0, QApplication::UnicodeUTF8));
actionQuit_Pudding->setText(QApplication::translate("GreenTech", "Quit Pudding", 0, QApplication::UnicodeUTF8));
actionSave_2->setText(QApplication::translate("GreenTech", "Save", 0, QApplication::UnicodeUTF8));
actionMove->setText(QApplication::translate("GreenTech", "Move", 0, QApplication::UnicodeUTF8));
actionScale->setText(QApplication::translate("GreenTech", "Scale", 0, QApplication::UnicodeUTF8));
actionRotate->setText(QApplication::translate("GreenTech", "Rotate", 0, QApplication::UnicodeUTF8));
actionReset_Rotate->setText(QApplication::translate("GreenTech", "Reset Rotate", 0, QApplication::UnicodeUTF8));
actionSelect->setText(QApplication::translate("GreenTech", "Select", 0, QApplication::UnicodeUTF8));
actionCopy->setText(QApplication::translate("GreenTech", "Copy", 0, QApplication::UnicodeUTF8));
actionDelete->setText(QApplication::translate("GreenTech", "Delete", 0, QApplication::UnicodeUTF8));
actionSnap->setText(QApplication::translate("GreenTech", "Snap floor", 0, QApplication::UnicodeUTF8));
actionOrtho->setText(QApplication::translate("GreenTech", "Ortho", 0, QApplication::UnicodeUTF8));
actionPerspective->setText(QApplication::translate("GreenTech", "Perspective", 0, QApplication::UnicodeUTF8));
actionTopView->setText(QApplication::translate("GreenTech", "TopView", 0, QApplication::UnicodeUTF8));
actionBottomView->setText(QApplication::translate("GreenTech", "BottomView", 0, QApplication::UnicodeUTF8));
actionRightView->setText(QApplication::translate("GreenTech", "RightView", 0, QApplication::UnicodeUTF8));
actionLeftView->setText(QApplication::translate("GreenTech", "LeftView", 0, QApplication::UnicodeUTF8));
actionFrontView->setText(QApplication::translate("GreenTech", "FrontView", 0, QApplication::UnicodeUTF8));
actionBackView->setText(QApplication::translate("GreenTech", "BackView", 0, QApplication::UnicodeUTF8));
actionAuto->setText(QApplication::translate("GreenTech", "Auto", 0, QApplication::UnicodeUTF8));
actionManuDelete->setText(QApplication::translate("GreenTech", "ManuDelete", 0, QApplication::UnicodeUTF8));
actionLight->setText(QApplication::translate("GreenTech", "Light", 0, QApplication::UnicodeUTF8));
actionMid->setText(QApplication::translate("GreenTech", "Medium", 0, QApplication::UnicodeUTF8));
actionHeavy->setText(QApplication::translate("GreenTech", "Heavy", 0, QApplication::UnicodeUTF8));
actionDeleteAll->setText(QApplication::translate("GreenTech", "DeleteAll", 0, QApplication::UnicodeUTF8));
actionRemoveAll->setText(QApplication::translate("GreenTech", "RemoveAll", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
actionRemoveAll->setToolTip(QApplication::translate("GreenTech", "Remove all support struct", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
menuFile->setTitle(QApplication::translate("GreenTech", "File", 0, QApplication::UnicodeUTF8));
menuEdit->setTitle(QApplication::translate("GreenTech", "Edit", 0, QApplication::UnicodeUTF8));
menuHelp->setTitle(QApplication::translate("GreenTech", "Help", 0, QApplication::UnicodeUTF8));
menuView->setTitle(QApplication::translate("GreenTech", "View", 0, QApplication::UnicodeUTF8));
viewToolBar->setWindowTitle(QApplication::translate("GreenTech", "toolBar", 0, QApplication::UnicodeUTF8));
supportEdit->setWindowTitle(QApplication::translate("GreenTech", "toolBar", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class GreenTech: public Ui_GreenTech {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_GREENTECH_H
|
98ca0f78ed2fe8024c8bc05f0d924695dc19e5bc | 98714a3f69553ae63568fa7fb012f248a1d6361e | /EchoWebsock.cc | 20b5b31da932d50b4b92eab3a52288bf00473d2a | [] | no_license | kapilpipaliya/jdrogon | 3523da2f490f4ddbf9441542100370c436b99afd | 9d324c573c8d1fc6dd59452f8fdc5f812b0a02e3 | refs/heads/master | 2022-01-20T21:41:56.954889 | 2019-07-20T13:57:09 | 2019-07-20T13:57:09 | 197,937,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,067 | cc | EchoWebsock.cc | #include "EchoWebsock.h"
#include <map>
#include <regex>
#include "core/tables/functions.h"
#include "core/tables/savefunctions.h"
std::map<std::string, std::function<void(const std::string &event_name, const WebSocketConnectionPtr& wsConnPtr, Json::Value in)> > fns;
std::map<std::string, std::function<void(const std::string &event_name, const WebSocketConnectionPtr& wsConnPtr, std::string &message )> > fns_bin;
#define m(s) "material_" s
#define e(s) "entity_" s
#define p(s) "product_" s
#define px(t) "save_" t "_data"
void EchoWebsock::defineFns()
{
//fns.insert(std::pair<std::string, std::function<Json::Value()>>("accessory", accessory));
//Inserts a new element in the map if its key is unique.
// Public
// Branch
// Menu
// Mfg
// Payroll
// Material (synced)
CRUD(m("metal"), metal);
CRUD(m("purity"), purity);
CRUD(m("tone"), tone);
CRUD(m("accessory"), accessory);
CRUD(m("clarity"), clarity);
CRUD(m("shape"), shape);
CRUD(m("d_color"), d_color);
CRUD(m("cs_color"), cs_color);
getAllTheColumns(m("size"), query_size);
CRUD(m("diamond_size"), diamond_size);
CRUD(m("color_stone_size"), color_stone_size);
// Account
getAllTheColumns("account_heading", query_account_heading);
getAllTheColumns("account", query_account);
getAllTheColumns("order", query_order);
getAllTheColumns("sale", query_sale);
getAllTheColumns("transaction", query_transaction);
// Entity
CRUD(e("address_type"), address_type);
CRUD(e("contact_type"), contact_type);
CRUD(e("entity_type"), entity_type);
CRUD(e("entity"), entity);
// Setting
getAllTheColumns("global_setting", query_global_setting);
CRUD("setting_currency", currency);
getAllTheColumns("log", query_log);
// Part
getAllTheColumns("part_categories", query_part_group);
getAllTheColumns("part_type", query_part_type);
// product:
getAllTheColumns(p("option"), query_product_options);
CRUD(p("product"), product);
CRUD(p("post"), post);
CRUD(p("category"), category);
CRUD(p("tag"), tag);
CRUD(p("shipping_class"), shipping_class);
CRUD(p("setting_type"), setting_type);
CRUD(p("certified_by"), certified_by);
fns.emplace("get_product_attachment_data", get_product_attachment);
fns.emplace("get_product_diamond_price_data", get_diamond_price);
fns.emplace("get_product_cs_price_data", get_cs_price);
fns.emplace("get_product_category_tree_data", get_product_category_tree_data);
fns.emplace("admin_login", admin_login);
fns.emplace("admin_logout", admin_logout);
fns.emplace("is_admin_auth", is_admin_auth);
fns.emplace(px("image_meta"), saveImageMeta); // Save Image meta on server temparary
//Binary Handle Functions:
fns_bin.emplace(px("product_attachment"), save_product_attachment);
}
void EchoWebsock::handleNewMessage(const WebSocketConnectionPtr& wsConnPtr, std::string &&message, const WebSocketMessageType &type)
{
// It is very useful to keep a record of the connected clients, as it provides details with different data or send different messages to each one.
//fprintf(stdout, "%s\n", message.c_str());
//fflush(stdout);
switch (type) {
case WebSocketMessageType::Text: {
Json::Reader reader;
Json::Value valin;
reader.parse(message, valin);
if (valin.type() != Json::ValueType::arrayValue) {
return wsConnPtr->send("");
}
std::regex r("_data\\d*$");
auto f = fns.find(std::regex_replace(valin[0].asString(), r, "_data"));
if (f != fns.end()) {
f->second(valin[0].asString(), wsConnPtr, valin[1]);
} else {
Json::Value jresult;
jresult[0]=valin[0].asString();
jresult[1]=Json::arrayValue;
wsConnPtr->send(jresult.toStyledString());
}
break;
}
case WebSocketMessageType::Binary: {
std::regex r("_data\\d*$");
auto event_name_meta = getEventName(wsConnPtr);
auto f = fns_bin.find(std::regex_replace(event_name_meta, r, "_data"));
if (f != fns_bin.end()) {
f->second(event_name_meta, wsConnPtr, message);
}
break;
}
}
}
void EchoWebsock::handleNewConnection(const HttpRequestPtr &req,const WebSocketConnectionPtr& wsConnPtr)
{
// save the cookie in contex, because its not available on other handler
LOG_DEBUG << "new websocket connection!\n";
//auto &key=req->getHeader("Sec-WebSocket-Key");
//LOG_DEBUG << key;
processCookie(req, wsConnPtr);
// LOG_DEBUG << req->getCookie("admin");
for (auto i : req->cookies()) {
printf("%s,%s", i.first.c_str(), i.second.c_str());
fflush(stdout);
}
// create connection to the database and keep it open. Will Increase Performance.
}
void EchoWebsock::handleConnectionClosed(const WebSocketConnectionPtr& wsConnPtr) {
// deleteSession(wsConnPtr);
}
// How to use any: https://github.com/an-tao/drogon/issues/126
|
8518fede02067af37fbcb2bee68d0ef04a7f9c79 | 40ac4059db3763d47198837f76c916483cdc6f62 | /tagTile.h | 4fc145f63a170cf391ad0a2566b239beb391045e | [] | no_license | tpgns139/TeamProject-SecretOfGrandia | b340f6173ed6c7a80671e9b106b412f7cd289870 | 6a8afeebaa6a3e41cb4ac50cb69c81fd3afe20f3 | refs/heads/master | 2020-12-22T06:48:47.852447 | 2020-02-26T08:53:04 | 2020-02-26T08:53:04 | 236,700,522 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,382 | h | tagTile.h | #pragma once
#define TILESIZE 64 // 타일사이즈
//타일 갯수는 가로 20 / 세로 20
#define TILEX 100 // 타일 갯수
#define TILEY 100
//타일 총 사이즈는 640 X 640
#define TILESIZEX TILESIZE * TILEX
#define TILESIZEY TILESIZE * TILEY
enum frameImage
{
Frame,
NotFrame
};
enum attribute
{
nonBlocking,
blocking,
notJump
};
enum TYPE
{
TYPE_TERRAIN,
TYPE_TERRAIN2,
TYPE_TERRAIN3,
TYPE_TERRAIN4,
TYPE_TERRAIN5,
TYPE_TERRAIN6,
TYPE_NONE
};
class tagTile
{
private:
TYPE type;
RECT rc; //렉트
int terrainFrameX; //터레인 번호
int terrainFrameY; //터레인 번호
POINT center;
int indexX;
int indexY;
attribute _attribute;
tagTile* _parentNode;
bool _isOpen;
//F = G + H
float _totalCost; //총 비용
float _costFromStart; //시작위치로부터 현재 노드
float _costToGoal; //현재 노드로부터 도착점까지 경로비용
public:
tagTile() {}
~tagTile() {}
//================= 접근자 & 설정자 ==================
void setType(TYPE tp) { type = tp; }
TYPE getType() { return type; }
void setAttribute(attribute str) { _attribute = str; }
attribute getAttribute() { return _attribute; }
void setTotalCost(float totalCost) { _totalCost = totalCost; }
float getTotalCost() { return _totalCost; }
void setCostFromStart(float costFromStart) { _costFromStart = costFromStart; }
float getCostFromStart() { return _costFromStart; }
void setCostToGoal(float costToGoal) { _costToGoal = costToGoal; }
float getCostToGoal() { return _costToGoal; }
void setParentNode(tagTile* t) { _parentNode = t; }
tagTile* getParentNode() { return _parentNode; }
void setIsOpen(bool isOpen) { _isOpen = isOpen; }
bool getIsOpen() { return _isOpen; }
RECT getRect() { return rc; }
void setRect(RECT rect) { rc = rect; }
int getTerrainFrameIdx() { return terrainFrameX; }
void setTerrainFrameIdx(int num) { terrainFrameX = num; }
int getTerrainFrameIdY() { return terrainFrameY; }
void setTerrainFrameIdY(int num) { terrainFrameY = num; }
float getCenterX() { return center.x; }
float getCenterY() { return center.y; }
void setCenterX(float x) { center.x = x; }
void setCenterY(float y) { center.y = y; }
int getIdX() { return indexX; }
void setIdX(int index) {
indexX = index;
}
int getIdY() { return indexY; }
void setIdY(int index) {
indexY = index;
}
void render();
};
|
e0c626fb1fa9a0a582b4313977252ed87fdec8ae | db666b5c6b5381c55c716f95818a7ecc241d59c7 | /C++/1163-lastSubstringInLexicographicalOrder.cpp | 4f61669da446e03feae55586255497172c00e881 | [] | no_license | SaberDa/LeetCode | ed5ea145ff5baaf28ed104bb08046ff9d5275129 | 7dc681a2124fb9e2190d0ab37bf0965736bb52db | refs/heads/master | 2023-06-25T09:16:14.521110 | 2021-07-26T21:58:33 | 2021-07-26T21:58:33 | 234,479,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | cpp | 1163-lastSubstringInLexicographicalOrder.cpp | #include <iostream>
#include <string>
using namespace std;
string lastSubstring(string s) {
int i = 0, pos;
for (int j = 1; j < s.size(); j++) {
for (pos = 0; pos + j < s.size(); pos++) {
if (s[j + pos] == s[i + pos]) continue;
i = s[j + pos] > s[i + pos] ? j : i;
break;
}
if (j + pos == s.size()) break;
}
return s.substr(i);
} |
5c0ea34a916e19cf8f81e5c194fb25e82d65bf03 | cf8898b00e45b3e9e469e4d4b10d15c556e6f339 | /writer.cpp | 88b4c20c6b35020ef3fd6640b641179cb7f02c27 | [] | no_license | mrkline/ece556-router | ba6ded7b582455ef387f7941f36fdc27cfced5ef | 5bdd316954cd06f2296cb968ee50b021298e1788 | refs/heads/master | 2020-04-23T07:11:42.817777 | 2014-05-05T04:40:06 | 2014-05-05T04:40:06 | 17,260,224 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | writer.cpp |
#include "writer.hpp"
void Writer::write(const Point &p)
{
out << "(" << p.x << "," << p.y << ")";
}
void Writer::write(const Edge &e)
{
write(e.p1);
out << "-";
write(e.p2);
out << "\n";
}
void Writer::write(const Net &n)
{
out << "n" << n.id << "\n";
for(const auto &segment : n.nroute) {
for(int edge : segment.edges) {
write(routing.edge(edge));
}
}
out << "!\n";
}
void Writer::writeRouting()
{
for(const auto &net : routing.nets) {
write(net);
}
} |
170388e5014df5d1988152370a05ae52082eaeaa | fe2836176ca940977734312801f647c12e32a297 | /LeetCode/random/221.cpp | b29b7f6457c69d53c025ca8ad265020f7689c848 | [] | no_license | henrybear327/Sandbox | ef26d96bc5cbcdc1ce04bf507e19212ca3ceb064 | d77627dd713035ab89c755a515da95ecb1b1121b | refs/heads/master | 2022-12-25T16:11:03.363028 | 2022-12-10T21:08:41 | 2022-12-10T21:08:41 | 53,817,848 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | cpp | 221.cpp | class Solution
{
/*
matrix
1 1 1
1 1 1
1 1 1
dp
1 1 1
1 2 2
1 2 x
To get x, we look at its up, left, upper-left values
If you draw their squares out, you can see they will overlap into a 3*3
*/
public:
int maximalSquare(vector<vector<char>> &matrix)
{
int n = matrix.size();
if (n == 0)
return 0;
int m = matrix[0].size();
if (m == 0)
return 0;
int dp[n][m];
memset(dp, 0, sizeof(dp));
// init dp
int mx = 0;
for (int i = 0; i < m; i++) {
if (matrix[0][i] == '1')
dp[0][i] = 1, mx = 1;
}
for (int i = 0; i < n; i++) {
if (matrix[i][0] == '1')
dp[i][0] = 1, mx = 1;
}
for (int i = 1; i < n; i++)
for (int j = 1; j < m; j++) {
if (matrix[i][j] == '1') {
int mn = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1]));
mn += 1;
dp[i][j] = mn;
mx = max(mx, dp[i][j]);
}
}
return mx * mx;
}
};
|
45f45e2d02b7eab2887c7c70833484dc807388c2 | 38b5b45ac2de75ac89074981f865fbfbf0e33e06 | /CameraFeed/src/CommandLine.cpp | f38f764e81af168e4b54d3ece26cdf678e453d76 | [] | no_license | rarenivar/project5799 | c9950689b2268b614a7a2759af70ee4a38eb844e | 6b08a617446a5fd190a67ba8e233fb22c33454cd | refs/heads/master | 2020-04-15T20:23:53.733799 | 2016-05-06T02:09:46 | 2016-05-06T02:09:46 | 51,423,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,178 | cpp | CommandLine.cpp | #include <getopt.h>
#include <iostream>
#include <stdexcept>
#include "CommandLine.h"
CommandLine::CommandLine(int argc, char **argv)
{
extern int optind, opterr;
extern char* optarg;
opterr = 1;
while (true)
{
enum Option
{
Camera,
Debug,
Help,
Mongo,
Password,
User,
UserName,
};
static struct option options[] = {
{"user", required_argument, 0, User},
{"camera", required_argument, 0, Camera},
{"debug", optional_argument, 0, Debug},
{"mongo", required_argument, 0, Mongo},
{"username", required_argument, 0, UserName},
{"password", required_argument, 0, Password},
{"help", no_argument, 0, Help},
{0, 0, 0, 0 }
};
int optionIndex = 0;
auto c = ::getopt_long(argc, argv, "",
options, &optionIndex);
if (c == -1)
break;
switch (c) {
case Camera:
myCamera = optarg;
break;
case Debug:
if (optarg)
{
myDebug = std::atoi(optarg);
}
else
{
myDebug = 1;
}
break;
case Help:
usage(argv[0]);
std::exit(0);
break;
case Mongo:
myMongoLocation = optarg;
break;
case Password:
myPassword = optarg;
break;
case User:
myUser = optarg;
break;
case UserName:
myUserName = optarg;
break;
default:
usage(argv[0]);
std::exit(1);
}
}
if (argc - optind != 1)
{
throw std::runtime_error("No URI given.");
}
myURI = argv[optind];
}
std::string CommandLine::getCamera() const noexcept
{
return myCamera;
}
int CommandLine::getDebug() const noexcept
{
return myDebug;
}
std::string CommandLine::getMongoLocation() const noexcept
{
return myMongoLocation;
}
std::string CommandLine::getPassword() const noexcept
{
return myPassword;
}
std::string CommandLine::getUser() const noexcept
{
return myUser;
}
std::string CommandLine::getUserName() const noexcept
{
return myUserName;
}
std::string CommandLine::getURI() const noexcept
{
return myURI;
}
void CommandLine::usage(const char *argv0)
{
std::cerr << argv0 << " [OPTIONS] camera_host_name" << std::endl
<< std::endl
<< "Records data from the Amcrest IPM-721S camera at the "
<< "given host name" << std::endl
<< std::endl
<< "OPTIONS" << std::endl
<< " --camera=cameraId ID of the Amcrest camera"
<< std::endl
<< " --debug[=level] debug level (1 if no level specified)"
<< std::endl
<< " --help print this help and exit"
<< std::endl
<< " --mongo=mongo host/port for mongo (ex. 127.0.0.1:4)"
<< std::endl
<< " --password=password password for camera access"
<< std::endl
<< " --user=user User of the system"
<< std::endl
<< " --username=username User name for camera access"
<< std::endl;
}
|
77fce786af494689bacd4564d1440ba5342547b5 | 737019fead13f620229d4654459df4c027d1a03b | /c_impl/c_component_impl/source_code/imfeat_binary_get_perimeter_c.cpp | 583ea59fbab05a8cd53a514bbe3de376095ba658 | [] | no_license | ctku/project_text_detect | efdb947d66ff7d5662955bd5679681a5ad303421 | 1faa40eae8a63f6594c19cc32e89c545b46dc854 | refs/heads/master | 2016-09-10T19:15:36.029437 | 2013-10-07T14:25:27 | 2013-10-07T14:25:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,352 | cpp | imfeat_binary_get_perimeter_c.cpp | //#define MATLAB
/*=================================================================
*
* version: 01/27/2013 00:38
*
* Matlab: [out] = imfeat_binary_get_perimeter_c(new, cum)
*
* Input - new (u8 array): newly-added binary map (see ps.1)
* - cum (u8 array): accumulated binary map (see ps.1)
*
* Output - out (int): change of perimeter
*
* ps.1: Rember to have an transpose on this parameter when calling in Matlab,
* to compensate the different memory layout between Matlab & C.
*=================================================================*/
#ifdef MATLAB
#include "mex.h"
#include "matrix.h"
#define IMFEAT_BINARY_GET_PERIMETER_C
#else
#include "c_implement.h"
#endif
#ifdef IMFEAT_BINARY_GET_PERIMETER_C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define cor2idx(x,y,w) (x+(y)*(w))
typedef unsigned char u8;
typedef unsigned short int u16;
typedef unsigned long int u32;
int imfeat_perimeter_change_algo(u8 *img_new, u8 *img_cum, int img_rows, int img_cols)
{
// new_img: newly-added binary map
// cum_img: accumulated binary map
// calc Euler no difference for each new pixel
int p = -1;
int H = img_rows;
int W = img_cols;
// enlarge 1 pxl to avoid bondary checking
u8 *cums = (u8 *)malloc((W+2)*(H+2)*sizeof(u8));
u8 *news = (u8 *)malloc((W+2)*(H+2)*sizeof(u8));
int *psi = (int *)malloc((W+2)*(H+2)*sizeof(int));
memset(cums, 0, (W+2)*(H+2)*sizeof(u8));
memset(news, 0, (W+2)*(H+2)*sizeof(u8));
for (int y=0; y<H; y++) {
memcpy(&cums[cor2idx(1,y+1,W+2)], &img_cum[y*W], W*sizeof(u8));
memcpy(&news[cor2idx(1,y+1,W+2)], &img_new[y*W], W*sizeof(u8));
}
for (int h=1; h<H+1; h++) {
for (int w=1; w<W+1; w++) {
if (news[cor2idx(w,h,W+2)]==0)
continue;
// for each new pixel p
p = p + 1;
// (1) calc num of adjacent edge q with accumulated map
int q = 0;
if (cums[cor2idx(w,h-1,W+2)]==1) q = q + 1;
if (cums[cor2idx(w-1,h,W+2)]==1) q = q + 1;
if (cums[cor2idx(w+1,h,W+2)]==1) q = q + 1;
if (cums[cor2idx(w,h+1,W+2)]==1) q = q + 1;
// (2) calc edge no change: psi(p) = 4 - 2{q:qAp^C(q)<=C(p)}
psi[p] = 4 - 2*q;
// (3) add each new pixel into cum for next loop
cums[cor2idx(w,h,W+2)] = 1;
}
}
// update Euler no change
int phi = 0;
for (int i=0; i<=p; i++) {
phi = phi + psi[i];
}
//release memory
free(cums);
free(news);
free(psi);
return phi;
}
#ifndef MATLAB
int main(void)
{
u8 img_cum[28] = {0,0,0,0,0,0,0,
0,0,0,0,0,0,0,
0,0,0,0,0,0,0,
0,0,0,0,0,0,0};
u8 img_new[28] = {0,0,0,0,0,1,1,
0,1,1,0,1,1,1,
0,1,1,0,1,0,1,
0,0,0,0,0,0,1};
int out[4];
imfeat_perimeter_change_algo(img_new, img_cum, 4, 7);
return 0;
}
#else
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
u8 *img_new = (u8*)mxGetPr(prhs[0]); // transposed input matrix is expected
u8 *img_cum = (u8*)mxGetPr(prhs[1]); // transposed input matrix is expected
int img_rows = (int)mxGetN(prhs[0]); // switch rows & cols
int img_cols = (int)mxGetM(prhs[0]); // switch rows & cols
plhs[0] = mxCreateNumericMatrix(1, 1, mxINT32_CLASS, mxREAL);
int *out = (int*)mxGetPr(plhs[0]);
*out = imfeat_perimeter_change_algo(img_new, img_cum, img_rows, img_cols);
}
#endif
#endif |
f7435216004cc041243be7768bea393ca818786b | 7d9ff59d292bfc83ee0293cb4efa27a86b604aa9 | /LibDXGI/LibDXGI.h | 31409e721df926f4f1bbb1009716d77e73a73e8c | [] | no_license | barcharcraz/d3dGame | da9adbf8e48c267bbe5e72d098431185cea3a784 | a33a8626aaabf1a4576c44cf34c691629211da41 | refs/heads/master | 2021-01-22T13:57:09.788566 | 2014-03-21T22:00:38 | 2014-03-21T22:00:38 | 4,140,402 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 988 | h | LibDXGI.h | // The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the LIBDXGI_EXPORTS
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// LIBDXGI_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#include <atlbase.h>
#ifdef _DEBUG
#include <initguid.h>
#include <dxgidebug.h>
#endif
#ifdef LIBDXGI_EXPORTS
#define LIBDXGI_API __declspec(dllexport)
#else
#define LIBDXGI_API __declspec(dllimport)
#endif
namespace LibDXGI {
DXGI_SWAP_CHAIN_DESC1 GetDefaultSwapChain();
CComPtr<IDXGISwapChain1> CreateSwapChain(IDXGIDevice* pDevice, HWND target);
CComPtr<IDXGIFactory2> GetFactory(IDXGIDevice* pDevice);
#ifdef _DEBUG
CComPtr<IDXGIDebug> getDebugInterface();
#endif
}
|
61798cccd2b2de57dc62f848d39be4bb6b1eda15 | 7b6d73579a5c718d8944101cb263c90744de45b6 | /GoodBye2017/908A.cpp | daa2468cd0c9d29df0ca3a9338e855517e1e9aed | [] | no_license | zhenghaishu/Codeforces | be1d20e259d406ac9e8dd56ec1ab816d6f7a7a11 | a1fb6c03595cf5968ed813030d825bd250bdc8a2 | refs/heads/master | 2021-09-07T02:46:18.912343 | 2018-02-16T02:44:57 | 2018-02-16T02:44:57 | 115,092,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 494 | cpp | 908A.cpp | #include <iostream>
#include <string>
using namespace std;
#define MAX 50
int main()
{
int cnt = 0;
string s;
cin >> s;
for(int i = 0; i < s.length(); i++)
{
if('a' <= s.at(i) <= 'z')
{
if('a' == s.at(i)|| 'e' == s.at(i) || 'i' == s.at(i) || 'o' == s.at(i) || 'u' == s.at(i))
{
cnt++;
}
}
if('0' <= s.at(i) <= '9')
{
if('1' == s.at(i) || '3' == s.at(i) || '5' == s.at(i) || '7' == s.at(i) || '9' == s.at(i))
{
cnt++;
}
}
}
cout << cnt;
}
|
ffd11ce1283cba119e2e80b188b31686ae9bfa75 | 6bbdb1384a08e1f3bc42df70ee0dd13445993f2d | /AST/src/LiteralNode.cc | 682664b971c2e037b941d835cffec65d65c7f5aa | [
"MIT"
] | permissive | avartak/DIMPLE | fdee0767c85eb2937c83a0d54c7047801ca7c795 | b117baa2880cdae4afdeecea733c301e54980ef6 | refs/heads/main | 2023-04-16T13:19:49.535118 | 2021-04-25T22:40:48 | 2021-04-25T22:40:48 | 347,140,293 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,441 | cc | LiteralNode.cc | #include <cstdlib>
#include <cerrno>
#include <LiteralNode.h>
#include <TokenID.h>
namespace avl {
BoolNode::BoolNode(const std::shared_ptr<Token>& t, bool b):
ExprNode(EXPR_BOOL),
literal(b)
{
loc = t->loc;
}
std::shared_ptr<BoolNode> BoolNode::construct(const std::shared_ptr<Token>& token) {
std::shared_ptr<BoolNode> ret;
if (token->is != TOKEN_TRUE && token->is != TOKEN_FALSE) {
return ret;
}
return std::make_shared<BoolNode>(token, token->is == TOKEN_TRUE);
}
IntNode::IntNode(const std::shared_ptr<Token>& t, uint64_t i):
ExprNode(EXPR_INT),
str(t->str),
literal(i)
{
loc = t->loc;
}
std::shared_ptr<IntNode> IntNode::construct(const std::shared_ptr<Token>& token) {
std::shared_ptr<IntNode> ret;
if (token->is != TOKEN_INT) {
return ret;
}
auto num = token->str;
int base = 10;
if (num.length() > 2) {
switch (num[1]) {
case 'b' : base = 2; break;
case 'o' : base = 8; break;
case 'x' : base = 16; break;
default : base = 10;
}
if (base != 10) {
num = num.erase(0, 2);
}
}
uint64_t i = strtoull(token->str.c_str(), nullptr, 0);
if (errno == ERANGE) {
return ret;
}
return std::make_shared<IntNode>(token, i);
}
RealNode::RealNode(const std::shared_ptr<Token>& t, double d):
ExprNode(EXPR_REAL),
str(t->str),
literal(d)
{
loc = t->loc;
}
std::shared_ptr<RealNode> RealNode::construct(const std::shared_ptr<Token>& token) {
std::shared_ptr<RealNode> ret;
if (token->is != TOKEN_REAL) {
return ret;
}
double d = strtod(token->str.c_str(), nullptr);
if (errno == ERANGE) {
return ret;
}
return std::make_shared<RealNode>(token, d);
}
CharNode::CharNode(const std::shared_ptr<Token>& t, char c):
ExprNode(EXPR_CHAR),
str(t->str),
literal(c)
{
loc = t->loc;
}
std::shared_ptr<CharNode> CharNode::construct(const std::shared_ptr<Token>& token) {
std::shared_ptr<CharNode> ret;
if (token->is != TOKEN_CHAR) {
return ret;
}
char c = token->str[1];
std::size_t len = 4;
if (c == '\\') {
if (token->str[2] == '\\') {
c = '\\';
}
else if (token->str[2] == '\'') {
c = '\'';
}
else if (token->str[2] == '\"') {
c = '\"';
}
else if (token->str[2] == 'a') {
c = '\a';
}
else if (token->str[2] == 'b') {
c = '\b';
}
else if (token->str[2] == 'f') {
c = '\f';
}
else if (token->str[2] == 'n') {
c = '\n';
}
else if (token->str[2] == 'r') {
c = '\r';
}
else if (token->str[2] == 't') {
c = '\t';
}
else if (token->str[2] == 'v') {
c = '\v';
}
else if (token->str[2] == '0' || token->str[2] == '1' || token->str[2] == '2' || token->str[2] == '3') {
c = char(strtol(token->str.substr(2, 3).c_str(), nullptr, 8));
len = 6;
}
else if (token->str[2] == 'x') {
c = char(strtol(token->str.substr(3, 2).c_str(), nullptr, 16));
len = 6;
}
}
else {
len = 3;
}
if (token->str.length() != len) {
return ret;
}
return std::make_shared<CharNode>(token, c);
}
StringNode::StringNode(const std::shared_ptr<Token>& t, const std::string& l):
ExprNode(EXPR_STRING),
str(t->str),
literal(l)
{
loc = t->loc;
}
std::shared_ptr<StringNode> StringNode::construct(const std::shared_ptr<Token>& token) {
std::shared_ptr<StringNode> ret;
if (token->is != TOKEN_STRING) {
return ret;
}
std::size_t pos = 1;
std::string s = "";
while (pos < token->str.length()-1) {
if (token->str[pos] == '\\') {
pos++;
if (token->str[pos] == '\'') {
s += '\'';
pos++;
}
else if (token->str[pos] == '\"') {
s += '\"';
pos++;
}
else if (token->str[pos] == '\?') {
s += '\?';
pos++;
}
else if (token->str[pos] == 'a') {
s += '\a';
pos++;
}
else if (token->str[pos] == 'b') {
s += '\b';
pos++;
}
else if (token->str[pos] == 'f') {
s += '\f';
pos++;
}
else if (token->str[pos] == 'n') {
s += '\n';
pos++;
}
else if (token->str[pos] == 'r') {
s += '\r';
pos++;
}
else if (token->str[pos] == 't') {
s += '\t';
pos++;
}
else if (token->str[pos] == 'v') {
s += '\v';
pos++;
}
else if (token->str[pos] == '0' || token->str[pos] == '1' || token->str[pos] == '2' || token->str[pos] == '3') {
s += char(strtol(token->str.substr(pos, 3).c_str(), nullptr, 8));
pos += 3;
}
else if (token->str[pos] == 'x') {
s += char(strtol(token->str.substr(pos+1, 2).c_str(), nullptr, 8));
pos += 3;
}
}
else {
s += token->str[pos];
pos++;
}
}
return std::make_shared<StringNode>(token, s);
}
}
|
9902fc4328cbd177784a670dcebd7cf05e017f1c | fcf1e9d46c8fbdcefd83b886e9312d30bda3aed1 | /class work 2 pf/class work 2 pf/Source.cpp | 7810a1b6d879484b67b19c02f079965af3e6d1f1 | [] | no_license | MuhammadSaim7776/1st-semester-programes | 0d7c623a837a91b95bdc12bef63662ae5bb59872 | 3ea39e5bd6b84260a09917c00f70deb6c9031414 | refs/heads/main | 2023-03-09T00:25:31.543785 | 2021-02-20T10:57:25 | 2021-02-20T10:57:25 | 340,631,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | cpp | Source.cpp | #include<iostream>
#include<conio.h>
using namespace std;
char calculategrade(int x)
{
if (x >= 90)
{
return 'A';
}
else if (x >= 80&&x<90)
{
return'B';
}
else if (x >= 60 && x < 80)
{
return 'C';
}
else
{
return 'D';
}
}
void main()
{
int a;
char z;
cout << "Enter your marks out of 100" << endl;
cin >> a;
z = calculategrade(a);
cout <<"Your grade is"<< z;
_getch();
}
|
0316fd33ffc8e5330d7c8d0269440df06e9b3a44 | e09cb8c09886a74c3154dc9364db93831cdf95ff | /DataStructure/testAllClass.h | 75f5ce953aeb848551059ed718e69dbde59df725 | [] | no_license | MOYUMax/DataStructure | 851e55b48e03e8fefc33fd7bd1643e781fc746fd | 45026db5018e4caae44659374d152ac776ec668d | refs/heads/master | 2021-01-20T01:39:00.208215 | 2017-05-17T14:25:12 | 2017-05-17T14:25:12 | 89,313,289 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,305 | h | testAllClass.h | #ifndef _TESTALLCLASS_H
#define _TESTALLCLASS_H
#include "NaturalNumber.h"
#include "SeqList.h"
#include "LinkList.h"
#include "CLinkList.h"
#include "SeqStack.h"
#include "CLinkQueue.h"
#include "UpTriMatrix.h"
#include "BiTree.h"
#include "HuffmanTree.h"
#include "MGraph.h"
#include "ALGraph.h"
#include "LinkHashTable.h"
#include "BST.h"
#include "Sort.h"
void testNaturalNumber();//练习 1.4 自然数
void testSeqList();//practice 2.5.1 Sequence List
void testLinkList();//practice 2.5.1 Link List
void testCLinkList();//practice 2.5.5 Circular Link List
//practice 2.5.6
void Classify(LinkList<char> & A, CLinkList<char> & B, CLinkList<char> & C, CLinkList<char> & D);
//parctice 2.5.7
class node{ //
public:
int data;
node * next;
node(int i) : data(i), next(0){}
};
node * creatList(int n);
void Josephus(unsigned n, unsigned k);
//practice 3.3.1 SeqStack for check expression's parentheses match
bool ParenthesesMatch(const char * s);
void testParenthMatch();
void testSeqStack();
//parctice 3.3.2
void testCLinkQueue();
//practiec 3.3.3 将十进制数 n 转换为 base 进制数,使用除余入栈法
void convert(unsigned n, unsigned base);
void testConvertSystem();
//practice 3.3.4 可以放 s 的背包,有 n 个物品质量为 w[0~n-1];求使得放入的物品质量之和正好等于 s的物品序列解
int NPBagPack(int s, int * w,int n );
void testNPBagPack();
//practice 4.3.1
void testUpTriMatrix();
//practiec BiTree Self Definetion
void testBiTree();
//practice 5.10
void testHuffmanTree();
//practice 6.3
void testMGraph();
void testALGraph();
//parctice 6.4
void testPrim();
//practice 7.5.1
void testLinkHashTable();
//practice 7.5.2
void testBST();
//practice 8 All Sort aglriothm
void testSort();
//practice 8.5.2
void testSeperateOddEven();
void SeperateOddEven(int a[], int n);
//practice 8.5.3
int QuickKTH(int a[], int n, int k);
void testQuickKTH();
//
void Qsort(int a[], int start, int end);
//practice 8.5.5
void LinkBubbleSort(Node<int> * front);
void LinkInsertSort(Node<int> * front);
void LinkSelectSort(Node<int> * front);
void testLinkSort();
//practice 8.5.6
void HeapAdjustNP(int a[], int n);
void testHeapAdjustNP();
//practice 8.5.7
void shuffle(char a[], int n);
void testshuffle();
//practice myself
void testMergeSortWithInsertSort();
#endif |
143f0eb17e83c7d0aa78429043014e18f3602fb6 | b800fb6fb86cd4baccc9a72d7456cd2a45fb22de | /Akiev_Vyacheslav/Лабораторная работа №3/квест 3/квест 3.cpp | 849752f7a6c4d241756a0541e5de7434743d0f41 | [] | no_license | tagelharpa/Laboratory | 15da2de414f8323dc17190ceac844dbb260d5955 | 687e7d037116f9d98cca9277d77603eaaa0127b3 | refs/heads/master | 2023-02-22T23:19:17.586109 | 2021-01-25T14:58:20 | 2021-01-25T14:58:20 | 325,304,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cpp | квест 3.cpp | #include <iostream>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double a = 0.1, b = 1, eps = 0.0001;
int n = 10, k = 10;
int i;
double step = (b - a) / k;
double x = a;
double s = 1;
double ai = 1;
while (x <= b)
{
cout << "X=" << x;
s = 1;
ai = 1;
for (i = 1; i < n; i++)
{
ai *= log(3) / i * x;
s += ai;
}
cout << " SN=" << s;
s = 1;
ai = 1;
i = 1;
while (ai > eps)
{
ai *= log(3) / i * x;
s += ai;
i++;
}
cout << " SE=" << s << " Y=" << pow(3, x) << endl;
x += step;
}
return 0;
}
|
6a4481130ac1d04f480c2b2217be100e80e90fb8 | e118069368fb6d1f67768a816e0374ea4f3fc932 | /DataframeHelper/Core/Error.cpp | 0a6e9bd0f7b70695592392a601c8d3e682dfc4ba | [] | no_license | mwu-tow/Dataframes-xlsx | 7cb80136f2c72e4fca31d7056d810a583181612e | 2a654285ca30b02fd5fb5274fa81ca73db715f3a | refs/heads/master | 2020-03-22T06:12:31.973577 | 2018-07-09T15:57:24 | 2018-07-09T15:57:24 | 139,618,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 58 | cpp | Error.cpp | #include "Error.h"
thread_local std::string errorMessage; |
f7f0ac2688a91cec59eb9dd5b4e0debd097ffb6d | 06a25ec850b89e034e627d482de5ab38712385b3 | /goa/Classes/mini_games/Drop.cpp | e0d599c731b8458568c974b4aedd7ca7f607bccd | [
"Apache-2.0",
"MIT"
] | permissive | maqsoftware/Simple-Class | 05e85186e13ec17a0ba92f5d82b5f035ecce2a02 | 758a4cc7963625c1dd415d1068bb1b454714718d | refs/heads/master | 2023-03-07T22:14:50.830371 | 2019-09-16T13:39:03 | 2019-09-16T13:39:03 | 187,072,035 | 0 | 0 | Apache-2.0 | 2019-09-16T13:39:04 | 2019-05-16T17:23:42 | C++ | UTF-8 | C++ | false | false | 34,887 | cpp | Drop.cpp | #include "Drop.h"
#include "../util/CommonLabelTTF.h"
USING_NS_CC;
using namespace std;
using namespace cocos2d;
#define COCOS2D_DEBUG 1
Scene* Drop::createScene()
{
auto scene = Scene::create();
auto layer = Drop::create();
scene->addChild(layer);
layer->_menuContext = MenuContext::create(layer, "drop");
scene->addChild(layer->_menuContext);
return scene;
}
bool Drop::init()
{
if (!Layer::init()) { return false; }
return true;
}
void Drop::onEnterTransitionDidFinish()
{
// Taking a bag of a lesson according to complexity
//int minimumAnswer;
//if (_lesson.getComplexity() >= 0 && _lesson.getComplexity() <= 4)
//{
// minimumAnswer = RandomHelper::random_int(2,4);
// //vmc = _lesson.getBag(1, minimumAnswer, minimumAnswer+1, 3, 5, false);
//}
//else if(_lesson.getComplexity() >= 5 && _lesson.getComplexity() <= 7)
//{
// minimumAnswer = RandomHelper::random_int(5, 6);
// //vmc = _lesson.getBag(1, minimumAnswer, minimumAnswer + 1,3,5, false);
//}
//else
//{
// minimumAnswer = RandomHelper::random_int(7, 8);
// //vmc = _lesson.getBag(1, minimumAnswer, minimumAnswer + 1, 3, 5, false);
//}
auto ceilValueForLevelSelection = std::floor((((float)_menuContext->getCurrentLevel() / 50.0f) * 6.0f));
int complexity = 3 + ceilValueForLevelSelection;
_eventDispatcher->addCustomEventListener("bagOfChoiceQuiz", CC_CALLBACK_1(Drop::gameStart, this));
_lesson.getBag(1, 2, complexity, 3, 7, true);
}
void Drop::gameStart(cocos2d::EventCustom *eventCustom)
{
// Distributing choices , answer, question and help in their respective variables
std::map<std::string, std::map<std::string, std::string>> dropSceneMap = {
{ "dropjungle",
{
{ "bg", "dropjungle/dropjungle.csb" },
{ "holderAnimation", "dropjungle/leafball.csb" },
{ "removalPole", "dropjungle/leafbal.png" },
{ "basketAnimation","dropjungle/basket.csb" },
{ "pseudoHolderImage","dropjungle/leafbal.png" },
{ "basketImageName", "basketouter_1" },
{ "rightAnimName", "full" },
{ "ball", "dropjungle/ball.png" },
{ "wrongAnimName", "correct" },
{ "blastAnimName", "click" },
{ "demoBasket","" },
{ "helpBoard", "boardhelp_16" }
}
},
{ "drophero",
{
{ "bg", "drophero/drophero.csb" },
{ "holderAnimation", "drophero/trailer.csb" },
{ "removalPole", "drophero/boxback.png" },
{ "basketAnimation","drophero/dropbox.csb" },
{ "pseudoHolderImage","drophero/trailer1.png" },
{ "basketImageName", "boxback" },
{ "rightAnimName", "right" },
{ "wrongAnimName", "wrong" },
{ "ball", "drophero/ball.png" },
{ "blastAnimName", "" },
{ "demoBasket","drophero/box1.png" },
{ "helpBoard", "board" }
}
},
{ "dropcity",
{
{ "bg", "dropcity/dropcity.csb" },
{ "holderAnimation", "dropcity/blast.csb" },
{ "removalPole", "dropcity/balloon.png" },
{ "basketAnimation","dropcity/basket.csb" },
{ "pseudoHolderImage","dropcity/balloon.png" },
{ "basketImageName", "Sprite_3" },
{ "rightAnimName", "correct" },
{ "wrongAnimName", "wrong" },
{ "ball", "dropcity/ball.png" },
{ "blastAnimName", "blast" },
{ "demoBasket","dropcity/closebox.png" },
{ "helpBoard", "board" }
}
}
};
std::map<std::string, std::map<std::string, float>> dropSceneNumValue = {
{ "dropjungle",
{
{ "boxLabelYFactor",0.1138 },
{ "basketRectYFactor", 0 },
{ "flaotingLetterYFactor", 1 },
{ "floatBoxHeightFactor",0.75 },
{ "helpBoardHeight",0.93 },
{ "basketAnchorY",0.0 }
}
},
{ "drophero",
{
{ "boxLabelYFactor",0.07 },
{ "basketRectYFactor", 1 },
{ "flaotingLetterYFactor", 0.85 },
{ "floatBoxHeightFactor",0.62 },
{ "helpBoardHeight",0.884 },
{ "basketAnchorY",0.5 }
}
},
{ "dropcity",
{
{ "boxLabelYFactor",0.14 },
{ "basketRectYFactor", 0 },
{ "flaotingLetterYFactor", 1.36 },
{ "floatBoxHeightFactor",0.65 },
{ "helpBoardHeight",0.938 },
{ "basketAnchorY",0.0 }
}
}
};
std::map<int, std::string> dropSceneMapping = {
{ 0, "drophero" },
{ 1, "dropjungle" },
{ 2, "dropcity" }
};
std::vector<std::string> wordOnLayout;
/*
int gameCurrentLevel = _menuContext->getCurrentLevel();
std::pair<int, int> levelKeyNumber = levelAllInfo(gameCurrentLevel, 5,3,5,3);
int level;
if (gameCurrentLevel >= 1 && gameCurrentLevel <= 15)
level = RandomHelper::random_int(1, 2);
else if(gameCurrentLevel >= 16 && gameCurrentLevel <= 30)
level = RandomHelper::random_int(3, 4);
else if (gameCurrentLevel >= 31 && gameCurrentLevel <= 45)
level = 5;
else
level = 6;
if (levelKeyNumber.second == 0)
{
auto tg = TextGenerator::getInstance();
auto _data = TextGenerator::getInstance()->getAntonyms(1, level);
wordOnLabel = getConvertInUpperCase(_data.begin()->first);
wordOnLayout = getConvertInUpperCase(_data.begin()->second);
_labelPrefix = LangUtil::getInstance()->translateString("Make opposite of : ");
}
else if (levelKeyNumber.second == 1)
{
auto word = TextGenerator::getInstance()->getWords(TextGenerator::P_O_S::ANY,1,level);
wordOnLabel = getConvertInUpperCase(word[0]);
wordOnLayout = wordOnLabel;
_labelPrefix = LangUtil::getInstance()->translateString("Make same word : ");
}
else
{
auto tg = TextGenerator::getInstance();
auto _data = TextGenerator::getInstance()->getSynonyms(1, level);
wordOnLabel = getConvertInUpperCase(_data.begin()->first);
wordOnLayout = getConvertInUpperCase(_data.begin()->second);
_labelPrefix = LangUtil::getInstance()->translateString("Make word of same meaning as : ");
}
*/
// _gameConvertIntoLessonConcept
// Select a game theme
auto randomSceneIndex = RandomHelper::random_int(0, 2);
_dropCurrentTheme = dropSceneMapping.at(randomSceneIndex);
if (_menuContext->getCurrentLevel() == 1)
{
_dropCurrentTheme = "dropcity";
}
// Change the game concept according to game
//_lesson.setConcept(Lesson::CONCEPT::WORD_SPELLING);
//std::vector<Lesson::Bag> vBag;
CCLOG("onLessonReady begin");
std::string* buf = static_cast<std::string*>(eventCustom->getUserData());
CCLOG("onLessonReady to unmarshallBagOfChoices");
vector<Lesson::Bag> vBag = Lesson::unmarshallBag(buf);
wordOnLayout = vBag[0].answers;
_wordToDisplay = vBag[0].answerString;
_labelPrefix = vBag[0].help + " : ";
int columnSize = vBag[0].answers.size() + vBag[0].otherChoices.size();
std::vector<std::vector<std::string>> choices = MatrixUtil::generateMatrix(vBag[0].answers, vBag[0].otherChoices, 1, columnSize);
_choices = choices[0];
_scenePath = dropSceneMap.at(_dropCurrentTheme);
_sceneBasedNumericalVal = dropSceneNumValue.at(_dropCurrentTheme);
_maxLengthOfChoice = getMaxWordLength(_choices);
_maxLengthOfLayoutWord = getMaxWordLength(wordOnLayout);
if (!_dropCurrentTheme.compare("dropjungle"))
{
CCSpriteFrameCache* framecache1 = CCSpriteFrameCache::sharedSpriteFrameCache();
framecache1->addSpriteFramesWithFile("dropjungle/dropjungle.plist");
}
else if (!_dropCurrentTheme.compare("drophero"))
{
CCSpriteFrameCache* framecache1 = CCSpriteFrameCache::sharedSpriteFrameCache();
framecache1->addSpriteFramesWithFile("drophero/drophero.plist");
}
else
{
CCSpriteFrameCache* framecache1 = CCSpriteFrameCache::sharedSpriteFrameCache();
framecache1->addSpriteFramesWithFile("drophero/dropcity.plist");
}
//BackGround
auto dropBackground = CSLoader::createNode(_scenePath.at("bg"));
this->addChild(dropBackground, 0);
//auto boardHelp = (Sprite *)dropBackground->getChildren().at(2)->getChildByName("boardhelp_16");
if (visibleSize.width > 2560) {
auto myGameWidth = (visibleSize.width - 2560) / 2;
dropBackground->setPositionX(myGameWidth);
}
/*Vector <Node*> children = dropBackground->getChildren().at(2)->getChildren();
int size = children.size();
for (auto item = children.rbegin(); item != children.rend(); ++item) {
Node * monsterItem = *item;
std::string str = monsterItem->getName().c_str();
CCLOG("name : %s", str.c_str());
}
*/
_removalPole = Sprite::createWithSpriteFrameName(_scenePath.at("removalPole"));
setAllSpriteProperties(_removalPole, 0, -(visibleSize.width*0.13), visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"), true, 0.5, 0.5, 0, 1, 1);
this->addChild(_removalPole);
//auto aab = DrawNode::create();
//this->addChild(aab, 20);
////aa->drawRect(Vec2(i*gap + gap / 2 - basketImg->getContentSize().width / 2, visibleSize.height*0.08) , Vec2(i*gap + gap / 2 + basketImg->getContentSize().width / 2, visibleSize.height*0.08 + basketImg->getContentSize().height), Color4F(0, 0, 255, 22)); //jungle drop
//aab->drawRect(Vec2((visibleSize.width*0.13) - _removalPole->getContentSize().width / 2, (visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"))- _removalPole->getContentSize().height*0.1), Vec2((visibleSize.width*0.13) + _removalPole->getContentSize().width / 2, visibleSize.height *_sceneBasedNumericalVal.at("floatBoxHeightFactor") + _removalPole->getContentSize().height/2), Color4F(0, 0, 255, 22));
//bool levelForSpeaker = isSpeakerAddLevel();
if (false)//levelForSpeaker
{
std::ostringstream boardName;
boardName << _labelPrefix << _wordToDisplay;
_label = setAllLabelProperties(boardName.str(), 2, (visibleSize.width / 2), (visibleSize.height*_sceneBasedNumericalVal.at("helpBoardHeight")), true, 0.5, 0.5, 0, 1, 1, 100);
this->addChild(_label, 2);
this->runAction(Sequence::create(DelayTime::create(2), CCCallFunc::create([=] {
std::ostringstream nameOnBoard1;
nameOnBoard1 << _labelPrefix;
_label->setString(nameOnBoard1.str());
addSpeaker(_wordToDisplay);//wordOnLable
}), NULL));
}
else
{
std::ostringstream boardName;
boardName << _labelPrefix << _wordToDisplay;
_label = setAllLabelProperties(boardName.str(), 2, (visibleSize.width / 2), (visibleSize.height*_sceneBasedNumericalVal.at("helpBoardHeight")), true, 0.5, 0.5, 0, 1, 1, 100);
this->addChild(_label, 2);
}
//Random index getter for blanks
std::vector<int> randomIndex;
int sizeOfWord = wordOnLayout.size();
int sizeOfRandomIndexVector;
if (sizeOfWord % 2 == 0)
{
sizeOfRandomIndexVector = sizeOfWord / 2;
_middleBasketIndex = sizeOfWord / 2 - 1;
}
else
{
int justANumber = RandomHelper::random_int(0, 1);
if (justANumber)
sizeOfRandomIndexVector = sizeOfWord / 2;
else
sizeOfRandomIndexVector = sizeOfWord / 2 + 1;
_middleBasketIndex = sizeOfWord / 2;
}
while (randomIndex.size() != sizeOfRandomIndexVector) {
bool duplicateCheck = true;
int numberPicker = RandomHelper::random_int(0, sizeOfWord - 1);
for (int i = 0; i < randomIndex.size(); i++) {
if (numberPicker == randomIndex[i])
duplicateCheck = false;
}
if (duplicateCheck)
randomIndex.push_back(numberPicker);
}
auto B = randomIndex;
auto gap = Director::getInstance()->getVisibleSize().width / wordOnLayout.size();
for (int i = 0; i < wordOnLayout.size(); i++)
{
bool flag = false;
for (int j = 0; j < randomIndex.size(); j++)
{
if (i == randomIndex[j])
{
flag = true;
break;
}
}
layingOutBasket(flag, gap, wordOnLayout[i], i);
}
/*if (_dropHelpSelector == 0)
{
auto a = _basketBin[0]->getPositionY();
HelpLayer *_dropHelp = HelpLayer::create(Rect(boardHelp->getPosition().x*1.044, boardHelp->getPosition().y, boardHelp->getContentSize().width*1.04, boardHelp->getContentSize().height),
Rect(boardHelp->getPosition().x*1.044, visibleSize.height*0.45, boardHelp->getContentSize().width*1.04, visibleSize.height*0.9));
this->addChild(_dropHelp, 5);
_dropHelp->setName("Help");
_dropHelp->click(Vec2(visibleSize.width*0.5, 0.75));
_dropHelpSelector = 1;
}*/
/*auto callShowScore = CCCallFunc::create([=] {
for (int i = 0; i < this->getChildren().size(); i++)
{
auto str = this->getChildren().at(i)->getName();
if (!str.compare("Help"))
{
this->removeChild(this->getChildren().at(i));
break;
}
}
});*/
if (_menuContext->getCurrentLevel() == 1)
{
Sprite* floatBox = Sprite::createWithSpriteFrameName(_scenePath.at("pseudoHolderImage"));
setAllSpriteProperties(floatBox, 0, visibleSize.width*1.1, visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"), true, 0.5, 0.5, 0, 1, 1);//0.75, true
leftFloat(floatBox, 12, -(visibleSize.width*0.2), visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"));//0.75
this->addChild(floatBox, 1);
//addEvents(floatBox);
floatBox->setTag(letterHolderId);
_letterHolderSpriteBin.push_back(floatBox);
//Label
auto label = setAllLabelProperties(_levelOneString, 0, (floatBox->getBoundingBox().size.width / 2), ((floatBox->getBoundingBox().size.height / 2)*_sceneBasedNumericalVal.at("flaotingLetterYFactor")), true, 0.5, 0.5, 0, 1, 1, 100);
float fontSize = std::max(float(50.0), float(100 - (_levelOneString.length() - 1) * 10));
if (fontSize < 50 || fontSize > 100) {
fontSize = 50.0f;
}
label->setFontSize(fontSize);
floatBox->addChild(label, 0);
letterHolderId++;
_helpFlag = true;
_gapBetweenTwoBasket = gap;
creatHelp(gap);
CCLOG("LINE NO : 288");
}
//this->runAction(Sequence::create(DelayTime::create(2), callShowScore, NULL));
if (_menuContext->getCurrentLevel() != 1)
{
this->schedule(schedule_selector(Drop::letterAndHolderMaker), 3);
}
this->scheduleUpdate();
}
std::pair<int, int> Drop::levelAllInfo(int currentLevel, int sceneRepetitionNo, int totalScene, int catagoryRepetitionNo, int totalcatagory)
{
float currentLevelInFloat = static_cast<float>(currentLevel);
int sceneBaseValue = static_cast<int>(std::ceil(currentLevelInFloat/ sceneRepetitionNo));
int sceneNo = sceneBaseValue % totalScene;
int catagoryBaseValue = static_cast<int>(std::ceil(currentLevelInFloat / catagoryRepetitionNo));
int catagoryNo = catagoryBaseValue % totalcatagory;
return std::make_pair(sceneNo, catagoryNo);
}
void Drop::layingOutBasket(bool flag, float gap, std::string letter, int i)
{
if (flag)
{
std::pair<Sprite*, cocostudio::timeline::ActionTimeline*>animationData = setAnimationAndProperties(_scenePath.at("basketAnimation"), (i*gap + gap / 2), (visibleSize.height*0.08), 1);
cocostudio::timeline::ActionTimeline* basketTimeline = animationData.second;
Sprite* basket = animationData.first;
basket->setZOrder(1);
if (!_dropCurrentTheme.compare("dropjungle")) {
auto texture = SpriteFrameCache::getInstance()->getSpriteFrameByName("dropjungle/basketouter.png");
//((Sprite*)basket->getChildren().at(0))->setSpriteFrame(texture);
//basket->runAction(basketTimeline);
basketTimeline->play("idle",false);
}
_basketImg = (Sprite *)basket->getChildByName(_scenePath.at("basketImageName"));
auto label = setAllLabelProperties(letter, 0, (i*gap + gap / 2), (visibleSize.height*_sceneBasedNumericalVal.at("boxLabelYFactor")), true, 0.5, 0.5, 0, 1, 1, 100);
int fontSize = std::max(float(50.0), float(100 - (_maxLengthOfLayoutWord - 1) * 10));
if (fontSize < 50 || fontSize > 100) {
fontSize = 50.0f;
}
label->setFontSize(fontSize);
this->addChild(label, 2);
label->setVisible(false);
auto rectBin = CCRectMake(i*gap + gap / 2 - _basketImg->getContentSize().width / 2, (visibleSize.height*0.08 - (_basketImg->getContentSize().height / 2 * _sceneBasedNumericalVal.at("basketRectYFactor"))), _basketImg->getContentSize().width, _basketImg->getContentSize().height);
_basketRect.push_back(rectBin);
_basketAnimBin.push_back(basketTimeline);
_basketBin.push_back(label);
_wordOptionBin.push_back(letter);
_middleBasketIndex = i;
_levelOneString = letter;
//auto aa = DrawNode::create();
//this->addChild(aa, 20);
////aa->drawRect(Vec2(i*gap + gap / 2 - basketImg->getContentSize().width / 2, visibleSize.height*0.08) , Vec2(i*gap + gap / 2 + basketImg->getContentSize().width / 2, visibleSize.height*0.08 + basketImg->getContentSize().height), Color4F(0, 0, 255, 22)); //jungle drop
//aa->drawRect(Vec2(i*gap + gap / 2 - basketImg->getContentSize().width / 2, visibleSize.height*0.08), Vec2(i*gap + gap / 2 + basketImg->getContentSize().width / 2, visibleSize.height*0.08 + basketImg->getContentSize().height), Color4F(0, 0, 255, 22));
}
else
{
if (!_dropCurrentTheme.compare("dropjungle"))
{
std::pair<Sprite*, cocostudio::timeline::ActionTimeline*>animationData = setAnimationAndProperties(_scenePath.at("basketAnimation"), (i*gap + gap / 2), (visibleSize.height*0.08), 1);
cocostudio::timeline::ActionTimeline* basketTimeline = animationData.second;
auto basket = animationData.first;
basket->setZOrder(1);
basketTimeline->play("full", false);
}
else
{
auto basket = Sprite::createWithSpriteFrameName(_scenePath.at("demoBasket"));
setAllSpriteProperties(basket, 0, (i*gap + gap / 2), (visibleSize.height*0.08), true, 0.5, _sceneBasedNumericalVal.at("basketAnchorY"), 0, 1, 1);
this->addChild(basket, 1);
}
auto label = setAllLabelProperties(letter, 0, (i*gap + gap / 2), (visibleSize.height*_sceneBasedNumericalVal.at("boxLabelYFactor")), true, 0.5, 0.5, 0, 1, 1, 100);
float fontSize = std::max(float(50.0), float(100 - (_maxLengthOfLayoutWord - 1) * 10));
if (fontSize < 50 || fontSize > 100) {
fontSize = 50.0f;
}
label->setFontSize(fontSize);
this->addChild(label, 2);
}
}
void Drop::update(float delta) {
removeLetterHolder();
basketLetterCollisionChecker();
removeHeroTrailer();
removeFallingLetter();
if (_helpFlag )
{
/*for (int i = 0; i < _basketBin.size(); i++)
{
if (!_basketBin[i]->getString().compare(_levelOneString) && _flagForIndex)
{
_index = i;
_flagForIndex = false;
break;
}
}*/
if (_letterHolderSpriteBin[0]->getPositionX() < (_middleBasketIndex*_gapBetweenTwoBasket + _gapBetweenTwoBasket / 2))
{
CCLOG("LINE NO : 386");
_helpFlag = false;
_letterHolderSpriteBin[0]->pause();
_stopMovingHelpObject = true;
auto letterBoardSprite = Sprite::create();
letterBoardSprite->setTextureRect(Rect(0, 0, _letterHolderSpriteBin[0]->getContentSize().width, _letterHolderSpriteBin[0]->getContentSize().height));
letterBoardSprite->setColor(Color3B(219, 224, 252));
letterBoardSprite->setPosition(Vec2(_letterHolderSpriteBin[0]->getPositionX(), _letterHolderSpriteBin[0]->getPositionY()));
letterBoardSprite->setName("touchSprite");
letterBoardSprite->setOpacity(0);
addEvents(letterBoardSprite);
addChild(letterBoardSprite,3);
CCLOG("LINE NO : 397");
}
}
if(_stopMovingHelpObject && (_menuContext->getCurrentLevel() == 1) && this->getChildByName("helpLayer")){
_letterHolderSpriteBin[0]->pause();
}
}
void Drop::addSpeaker(const string word)
{
std::ostringstream boardName;
boardName << _labelPrefix;
auto speaker = Sprite::create("speaker/speaker.png");;
speaker->setName("speaker");
setAllSpriteProperties(speaker, 0, (_label->getContentSize().width/2 + visibleSize.width/2 + 40), (visibleSize.height*_sceneBasedNumericalVal.at("helpBoardHeight")), true, 0.5, 0.5, 0, 1, 1);
this->addChild(speaker, 1);
speaker->setScale(0.5);
addSpeakerTouchEvents(speaker,word );
}
bool Drop::isSpeakerAddLevel()
{
std::vector<int> levelNumber = { 1,2,3,4,5,16,17,18,19,20,31,32,33,34,35,46,47,48,49,50 };
for (int index = 0; index < levelNumber.size(); index++)
{
if (levelNumber[index] == _menuContext->getCurrentLevel())
{
return true;
}
}
return false;
}
Drop::~Drop(void)
{
this->removeAllChildrenWithCleanup(true);
this->getEventDispatcher()->removeCustomEventListeners("bagOfChoiceQuiz");
}
void Drop::creatHelp(float gap)
{
_help = HelpLayer::create(Rect((_middleBasketIndex*gap + gap / 2), visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"), _letterHolderSpriteBin[0]->getContentSize().width, _letterHolderSpriteBin[0]->getContentSize().height), Rect((visibleSize.width / 2), (visibleSize.height*_sceneBasedNumericalVal.at("helpBoardHeight")), visibleSize.width*0.35, visibleSize.height*0.1));
_help->click(Vec2((_middleBasketIndex*gap + gap / 2), visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor")));
this->addChild(_help, 6);
_help->setName("helpLayer");
}
void Drop::letterAndHolderMaker(float dt)
{
if (!_dropCurrentTheme.compare("dropjungle") || !_dropCurrentTheme.compare("dropcity"))
{
auto a = 1;
}
else
{
std::pair<Sprite*, cocostudio::timeline::ActionTimeline*>animationData = setAnimationAndProperties(_scenePath.at("holderAnimation"), visibleSize.width*1.1, visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"), 0);
Sprite* trailer = animationData.first;
trailer->setZOrder(2);
trailer->setTag(letterHolderId);
leftFloat(trailer, 12, -(visibleSize.width*0.2), visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"));//0.75
_dropHeroTrailerImageBin.push_back(trailer);
}
Sprite* floatBox = Sprite::createWithSpriteFrameName(_scenePath.at("pseudoHolderImage"));
setAllSpriteProperties(floatBox, 0, visibleSize.width*1.1, visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"), true, 0.5, 0.5, 0, 1, 1);//0.75, true
leftFloat(floatBox, 12, -(visibleSize.width*0.2), visibleSize.height*_sceneBasedNumericalVal.at("floatBoxHeightFactor"));//0.75
this->addChild(floatBox, 2);
floatBox->setTag(letterHolderId);
_letterHolderSpriteBin.push_back(floatBox);
//Label
int maxIndex = _choices.size() - 1; //_wordOptionBin
std::string str = _choices[RandomHelper::random_int(0, maxIndex)];
auto label = setAllLabelProperties(str, 0, (floatBox->getBoundingBox().size.width / 2), ((floatBox->getBoundingBox().size.height / 2)*_sceneBasedNumericalVal.at("flaotingLetterYFactor")), true, 0.5, 0.5, 0, 1, 1, 100);
float fontSize = std::max(float(50.0), float(100 - (_maxLengthOfChoice - 1) * 10));
if (fontSize < 50 || fontSize > 100) {
fontSize = 50.0f;
}
label->setFontSize(fontSize);
floatBox->addChild(label, 0);
addEvents(floatBox);
letterHolderId++;
CCLOG("LINE NO : 444");
}
void Drop::leftFloat(Sprite* floatingObj, int time, float positionX, float positionY)
{
// comment
floatingObj->runAction(MoveTo::create(time, Vec2(positionX, positionY)));
}
void Drop::addEvents(Sprite* clickedObject)
{
auto listener = cocos2d::EventListenerTouchOneByOne::create();
listener->setSwallowTouches(false);
listener->onTouchBegan = [=](cocos2d::Touch* touch, cocos2d::Event* event)
{
auto target = event->getCurrentTarget();
Point locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect;
if (!_dropCurrentTheme.compare("dropcity"))
{
rect = Rect(0, s.height * 0.5, s.width, s.height*0.5);
}
else
{
rect = Rect(0, 0, s.width, s.height);
}
if (rect.containsPoint(locationInNode) && !_isGameDone)
{
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
cocostudio::timeline::ActionTimeline* holderTimeline;
Sprite* holderImage;
auto helpSpriteName = target->getName();
if (helpSpriteName.compare("touchSprite") == 0)
{
this->getChildByName("touchSprite")->getEventDispatcher()->removeEventListener(listener);
CCLOG("LINE NO : 482");
}
if (!_dropCurrentTheme.compare("dropjungle") || !_dropCurrentTheme.compare("dropcity"))
{
if(!_dropCurrentTheme.compare("dropjungle"))
audio->playEffect("sounds/sfx/drop_jungle_touch.ogg", false);
else
audio->playEffect("sounds/sfx/shop_balloon_burst.ogg", false);
std::pair<Sprite*, cocostudio::timeline::ActionTimeline*> animationData = setAnimationAndProperties(_scenePath.at("holderAnimation"), (target->getPosition().x), (target->getPosition().y), 0);
holderTimeline = animationData.second;
holderImage = animationData.first;
holderTimeline->play(_scenePath.at("blastAnimName"), false);
holderTimeline->setAnimationEndCallFunc(_scenePath.at("blastAnimName"), CC_CALLBACK_0(Drop::removeHolderAnimation, this, holderImage));
}
else
{
for (int i = 0; i < _dropHeroTrailerImageBin.size(); i++)
{
if (_dropHeroTrailerImageBin[i]->getTag() == target->getTag())
{
CCLOG("LINE NO : 504");
audio->playEffect("sounds/sfx/drop_hero_touch.ogg", false);
cocostudio::timeline::ActionTimeline* holderTimeline = CSLoader::createTimeline(_scenePath.at("holderAnimation"));
_dropHeroTrailerImageBin[i]->runAction(holderTimeline);
//auto sp = std::make_tuple(_dropHeroTrailerImageBin[i], _dropHeroTrailerImageBin[i], i);
holderTimeline->gotoFrameAndPlay(0, false);
break;
}
}
}
auto sprite = Sprite::createWithSpriteFrameName(_scenePath.at("ball"));
sprite->setPosition(Vec2((target->getPosition().x), (target->getPosition().y)));
this->addChild(sprite, 0);
sprite->runAction(MoveTo::create(1, Vec2(sprite->getPosition().x, -visibleSize.height*0.015)));
_FallingLetter.push_back(sprite);
target->setVisible(false);
CCLOG("LINE NO : 522");
int iss = 0;
if (_initObj)
iss = 1;
CCLOG("LINE NO : 523 _initObj : %d --- , _letterHolderSpriteBin.size() : %d --- ",iss, _letterHolderSpriteBin.size());
if (_initObj && (_letterHolderSpriteBin.size() > 0) && (_menuContext->getCurrentLevel() == 1)) {
CCLOG("LINE NO : 524");
_letterHolderSpriteBin[0]->setVisible(false);
_letterHolderSpriteBin[0]->getEventDispatcher()->removeEventListener(listener);
_letterHolderSpriteBin[0]->resume();
_stopMovingHelpObject = false;
this->removeChild(this->getChildByName("touchSprite"));
CCLOG("LINE NO : 529");
auto calculate = ((std::string)_letterHolderSpriteBin[0]->getChildren().at(0)->getName()).length();
auto label = setAllLabelProperties(_letterHolderSpriteBin[0]->getChildren().at(0)->getName(), 0, (sprite->getBoundingBox().size.width / 2), (sprite->getBoundingBox().size.height / 2), true, 0.5, 0.5, 0, 1, 1, 100);
float fontSize = std::max(float(10), float(100 - (_maxLengthOfChoice - 1) * 10));
if (fontSize < 10 || fontSize > 100) {
fontSize = 10.0f;
}
label->setFontSize(fontSize);
sprite->addChild(label, 0);
this->removeChild(_help);
this->schedule(schedule_selector(Drop::letterAndHolderMaker), 3);
_initObj = false;
}
else {
CCLOG("LINE NO : 538");
auto calculate = ((std::string)target->getChildren().at(0)->getName()).length();
auto label = setAllLabelProperties(target->getChildren().at(0)->getName(), 0, (sprite->getBoundingBox().size.width / 2), (sprite->getBoundingBox().size.height / 2), true, 0.5, 0.5, 0, 1, 1, 100);
float fontSize = std::max(float(10), float(100 - (_maxLengthOfChoice - 1) * 10));
if (fontSize < 10 || fontSize > 100) {
fontSize = 10.0f;
}
label->setFontSize(fontSize);
sprite->addChild(label, 0);
for (int i = 0; i < _letterHolderSpriteBin.size(); i++)
{
if (_letterHolderSpriteBin[i]->getTag() == target->getTag())
{
_letterHolderSpriteBin[i]->getEventDispatcher()->removeEventListener(listener);
break;
}
}
}
CCLOG("LINE NO : 550");
CCLOG("size of holder container : %d", _letterHolderSpriteBin.size());
}
return false;
};
cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, clickedObject);
}
void Drop::addSpeakerTouchEvents(Sprite* clickedObject, string word)
{
auto listener = cocos2d::EventListenerTouchOneByOne::create();
listener->setSwallowTouches(false);
listener->onTouchBegan = [=](cocos2d::Touch* touch, cocos2d::Event* event)
{
auto target = event->getCurrentTarget();
Point locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = target->getBoundingBox();
if (rect.containsPoint(touch->getLocation()) && _speakerTouchFlag)
{
_speakerTouchCount++;
auto scaleTo = ScaleTo::create(0.1, 0.4);
auto scaleTo1 = ScaleTo::create(0.1, 0.5);
target->runAction(Sequence::create(scaleTo, scaleTo1, NULL));
_menuContext->pronounceWord(word);
if (_speakerTouchCount == 4)
{
_speakerTouchFlag = false;
this->runAction(Sequence::create(DelayTime::create(0.5), CCCallFunc::create([=] {
wordPopUp();
}), NULL));
}
}
return false;
};
cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, clickedObject);
}
void Drop::wordPopUp()
{
std::ostringstream boardName;
boardName << _labelPrefix << _wordToDisplay;
_label->setString(boardName.str());
this->getChildByName("speaker")->setVisible(false);
this->runAction(Sequence::create(DelayTime::create(2), CCCallFunc::create([=] {
std::ostringstream name;
name << _labelPrefix ;
_label->setString(name.str());
this->getChildByName("speaker")->setVisible(true);
_speakerTouchFlag = true;
_speakerTouchCount = 0;
}), NULL));
}
void Drop::removeLetterHolder()
{
for (int i = 0; i < _letterHolderSpriteBin.size(); i++)
{
auto letterHolder = CCRectMake(_letterHolderSpriteBin[i]->getPositionX(), _letterHolderSpriteBin[i]->getPositionY(), _letterHolderSpriteBin[i]->getContentSize().width, _letterHolderSpriteBin[i]->getContentSize().height);
//CCLOG("LINE NO : 561");
if (letterHolder.intersectsRect(_removalPole->getBoundingBox()))
{
this->removeChild(_letterHolderSpriteBin[i], true);
_letterHolderSpriteBin.erase(_letterHolderSpriteBin.begin() + i);
}
}
//CCLOG("LINE NO : 568");
}
void Drop::removeHeroTrailer()
{
for (int i = 0; i < _dropHeroTrailerImageBin.size(); i++)
{
auto letterHolder = CCRectMake(_dropHeroTrailerImageBin[i]->getPositionX(), _dropHeroTrailerImageBin[i]->getPositionY(), _dropHeroTrailerImageBin[i]->getContentSize().width, _dropHeroTrailerImageBin[i]->getContentSize().height);
if (letterHolder.intersectsRect(_removalPole->getBoundingBox()))
{
this->removeChild(_dropHeroTrailerImageBin[i], true);
_dropHeroTrailerImageBin.erase(_dropHeroTrailerImageBin.begin() + i);
}
}
}
void Drop::removeFallingLetter()
{
for (int i = 0; i < _FallingLetter.size(); i++)
{
if (_FallingLetter[i]->getPosition().y<-(visibleSize.height*0.001))
{
this->removeChild(_FallingLetter[i], true);
_FallingLetter.erase(_FallingLetter.begin() + i);
}
}
}
void Drop::basketLetterCollisionChecker()
{
for (int i = 0; i < _basketRect.size(); i++)
{
for (int j = 0; j < _FallingLetter.size(); j++)
{
// CCLOG("LINE NO : 602");
auto alphaBox = CCRectMake(_FallingLetter[j]->getPositionX() - _FallingLetter[j]->getContentSize().width / 2, _FallingLetter[j]->getPositionY() - _FallingLetter[j]->getContentSize().height / 2, _FallingLetter[j]->getContentSize().width, _FallingLetter[j]->getContentSize().height);
if (_basketRect[i].intersectsRect(alphaBox))
{
CCLOG("LINE NO : 605");
_pointCounter++;
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
auto str = _basketBin[i]->getString();
auto str1 = _FallingLetter[j]->getChildren().at(0)->getName();
if (!str.compare(str1))
{
audio->playEffect("sounds/sfx/success.ogg", false);
CCLOG("LINE NO : 613");
_basketAnimBin[i]->play(_scenePath.at("rightAnimName"), false);
_basketBin[i]->setVisible(true);
_basketRect.erase(_basketRect.begin() + i);
_basketAnimBin.erase(_basketAnimBin.begin() + i);
_basketBin.erase(_basketBin.begin() + i);
CCLOG("YES");
_menuContext->addPoints(1);
}
else
{
audio->playEffect("sounds/sfx/error.ogg", false);
CCLOG("LINE NO : 625");
_basketAnimBin[i]->play(_scenePath.at("wrongAnimName"), false);
//_basketAnimBin[i]->gotoFrameAndPlay(0, false);
CCLOG("NO");
}
this->removeChild(_FallingLetter[j], true);
_FallingLetter.erase(_FallingLetter.begin() + j);
}
}
}
if (_basketRect.size() == 0)
{
//Director::getInstance()->getEventDispatcher()->removeAllEventListeners();
_isGameDone = true;
auto unschedule = CCCallFunc::create([=] {
this->unschedule(schedule_selector(Drop::letterAndHolderMaker));
this->unscheduleUpdate();
});
this->runAction(Sequence::create(DelayTime::create(1.2), unschedule, NULL));
auto callShowScore = CCCallFunc::create([=] {
_menuContext->setMaxPoints(_pointCounter * 1);
_menuContext->showScore();
});
this->runAction(Sequence::create(DelayTime::create(1), callShowScore, NULL));
}
}
void Drop::removeHolderAnimation(Sprite* anim)
{
CCLOG("LINE NO : 652");
this->removeChild(anim, true);
}
//void Drop::removeHolderAnimationForHero(std::tuple<Sprite*, Sprite*, int> tupal_data)
//{
// std::get<1>(tupal_data)->removeAllChildren();
// //_dropHeroGarbageTrailer.push_back(_dropHeroTrailerImageBin[std::get<2>(tupal_data)]);
// _dropHeroTrailerImageBin.erase(_dropHeroTrailerImageBin.begin() + std::get<2>(tupal_data));
// _dropHeroTrailerAnimBin.erase(_dropHeroTrailerAnimBin.begin() + std::get<2>(tupal_data));
//}
void Drop::setAllSpriteProperties(Sprite* sprite, int zOrder, float posX, float posY, bool visibility, float anchorPointX, float anchorPointY, float rotation, float scaleX, float scaleY)
{
sprite->setPosition(Vec2(posX + origin.x, posY + origin.y));
sprite->setAnchorPoint(Vec2(anchorPointX, anchorPointY));
sprite->setScaleX(scaleX);
sprite->setScaleY(scaleY);
sprite->setVisible(visibility);
sprite->setRotation(rotation);
}
LabelTTF* Drop::setAllLabelProperties(std::string letterString, int zOrder, float posX, float posY, bool visibility, float anchorPointX, float anchorPointY, float rotation, float scaleX, float scaleY, int labelSizeInPixel)
{
auto label = CommonLabelTTF::create(letterString, "Helvetica", labelSizeInPixel);
label->setPosition(Vec2(posX, posY));
label->setVisible(visibility);
label->setAnchorPoint(Vec2(anchorPointX, anchorPointY));
label->setRotation(rotation);
label->setName(letterString);
label->setScaleX(scaleX);
label->setScaleY(scaleY);
return label;
}
std::pair<Sprite*, cocostudio::timeline::ActionTimeline*> Drop::setAnimationAndProperties(std::string csbString, float posX, float posY, int zOrder)
{
cocostudio::timeline::ActionTimeline* timeline = CSLoader::createTimeline(csbString);
Sprite* sprite = (Sprite *)CSLoader::createNode(csbString);
sprite->setPosition(Vec2(posX, posY));
sprite->runAction(timeline);
this->addChild(sprite, zOrder);
return std::make_pair(sprite, timeline);
}
std::string Drop::getConvertInUpperCase(std::string data)
{
std::ostringstream blockName;
int i = 0;
while (data[i])
{
blockName << (char)toupper(data[i]);
i++;
}
return blockName.str();
}
string Drop::getConvertVectorStringIntoString(vector<string> value) {
std::ostringstream convertedString;
for (size_t i = 0; i < value.size(); i++) {
convertedString << value[i];
}
return convertedString.str();
}
int Drop::getMaxWordLength(std::vector<string> wordVector)
{
int maxSize = 1;
int index = 0;
while(index != (wordVector.size() - 1))
{
if (wordVector[index].length() > maxSize)
{
maxSize = wordVector[index].length();
}
index++;
}
return maxSize;
}
|
4ab4c4de0fbcc6cdc6486fd7ce33830c910c0fe2 | 5fed2a5478ebcd156948b4435e3de94ad3d4f758 | /c++_mycode/company_task/l000.wangyi_02.cpp | 42c02a9b2d5372c31c3fc2bf4245dba45e0dc817 | [] | no_license | mistakk/c_code | 4a2d7468706359b778ffa83c518b009886b206bf | 8e5bcd0bd35c70c8d3609f72bfc31e7a5322cbd6 | refs/heads/master | 2020-04-01T09:29:09.872533 | 2018-10-16T12:26:00 | 2018-10-16T12:26:00 | 153,076,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | cpp | l000.wangyi_02.cpp | using namespace std;
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <set>
int main()
{
int n, k;
cin >> n >> k;
vector<long> num(n, 0);
vector<int>sleep(n, 0);
for (int i = 0; i < n; i++) {
cin >> num[i];
}
for (int i = 0; i < n; i++) {
cin >> sleep[i];
}
long retval = 0, maxval = 0;
for (int i = 0; i < n; i++) {
if (sleep[i] == 1)
maxval += num[i];
}
for (int i = 0; i < k; i++) {
if (sleep[i] == 0)
maxval += num[i];
}
if (k == n)
return maxval;
retval = maxval;
for (int i = k; i < n; i++) {
if (sleep[i] == 0)
maxval += num[i];
if (sleep[i - k] == 0)
maxval -= num[i - k];
retval = max(retval, maxval);
}
cout << retval << endl;
return 0;
} |
4bd4b153fd40ae6946b2ab7e67e36b6a7d9abac9 | d658fb52f2febc6f1bac65cc84417e2005cc80ab | /exam/no4/braille.h | 984a51fa76b47479a6937636bc31cd464227dd0f | [] | no_license | lumt/cpp_intro | cf2585f0900957bab7bb91ec3fdb46ddc7beffee | d77d0ae59d8634486e26803e0415b4260d4247fc | refs/heads/master | 2021-01-13T08:02:55.045891 | 2017-01-09T12:50:09 | 2017-01-09T12:50:09 | 71,492,567 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 435 | h | braille.h | #ifndef BRAILLE_H
#define BRAILLE_H value
#include <fstream>
using namespace std;
int encode_character(char ch, char* braille);
void encode_alpha(char ch, char* braille);
void encode(const char* text, char* braille);
void encodeR(const char* text, char* braille);
bool encodable(const char* text, char* buffer);
void print_braille(const char* text, ostream& out);
void print_row(const char* braille, int row, ostream& o);
#endif |
bf02c4f05591c466fd477c20227aa9b972724752 | 1e0293d706c5d7a06faf3c3ed806e9dd2983cdb5 | /engine/count/Int16Count.cpp | 2b087d9aa880ae884e0d15f216c0a37b3da3aa20 | [] | no_license | aiyou4love/source | a1b79c54ae782175754a9428ad0a88c8cd37db88 | 0e53be325dbe093a8a17173d2935c3fa911dd4b8 | refs/heads/master | 2021-01-18T20:35:04.570467 | 2017-02-27T00:14:09 | 2017-02-27T00:14:09 | 72,188,564 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,824 | cpp | Int16Count.cpp | #include "../Engine.hpp"
namespace cc {
void Int16Count::setInt(int16_t nId, int16_t nValue)
{
if ( (nId < 1) || (nId > (N * 2)) ) {
LOGE("[%s]%d,%d", __METHOD__, N, nId);
return;
}
int16_t id_ = (nId - 1) / 2;
int16_t bit_ = (nId - 1) % 2;
if (0 == bit_) {
mValue[id_] &= 0xFFFF0000;
mValue[id_] |= nValue;
} else {
int32_t value_ = (nValue << 16);
mValue[id_] &= 0xFFFF;
mValue[id_] |= value_;
}
mIntArray->runDirty();
}
int16_t Int16Count::getInt(int16_t nId)
{
if ( (nId < 1) || (nId > (N * 2)) ) {
LOGE("[%s]%d,%d", __METHOD__, N, nId);
return 0;
}
int16_t id_ = (nId - 1) / 2;
int16_t bit_ = (nId - 1) % 2;
if (0 == bit_) {
return ( int16_t(mValue[id_] & 0xFFFF) );
} else {
return ( int16_t(mValue[id_] >> 16) );
}
}
bool Int16Count::checkValue(int16_t nValue)
{
bool result_ = false;
for (int16_t i = 0; i < (N * 2); ++i) {
int16_t id_ = i / 2;
int16_t bit_ = i % 2;
if ( 0 == bit_ ) {
int16_t value_ = int16_t(mValue[id_] & 0xFFFF);
if ( nValue != value_ ) {
continue;
}
result_ = true;
break;
} else {
int16_t value_ = int16_t(mValue[id_] >> 16);
if ( nValue != value_ ) {
continue;
}
result_ = true;
break;
}
}
return result_;
}
void Int16Count::addInt(int16_t nId, int16_t nValue)
{
if ( (nId < 1) || (nId > (N * 2)) ) {
LOGE("[%s]%d,%d", __METHOD__, N, nId);
return;
}
int16_t id_ = (nId - 1) / 2;
int16_t bit_ = (nId - 1) % 2;
if (0 == bit_) {
int16_t value_ = int16_t(mValue[id_] & 0xFFFF);
value_ += nValue;
mValue[id_] &= 0xFFFF0000;
mValue[id_] |= value_;
} else {
int16_t value_ = int16_t(mValue[id_] >> 16);
value_ += nValue;
int32_t value0_ = (value_ << 16);
mValue[id_] &= 0xFFFF;
mValue[id_] |= value0_;
}
mIntArray->runDirty();
}
void Int16Count::addInt(int16_t nId)
{
if ( (nId < 1) || (nId > (N * 2)) ) {
LOGE("[%s]%d,%d", __METHOD__, N, nId);
return;
}
int16_t id_ = (nId - 1) / 2;
int16_t bit_ = (nId - 1) % 2;
if (0 == bit_) {
int16_t value_ = int16_t(mValue[id_] & 0xFFFF);
value_ += 1;
mValue[id_] &= 0xFFFF0000;
mValue[id_] |= value_;
} else {
int16_t value_ = int16_t(mValue[id_] >> 16);
value_ += 1;
int32_t value0_ = (value_ << 16);
mValue[id_] &= 0xFFFF;
mValue[id_] |= value0_;
}
mIntArray->runDirty();
}
void Int16Count::pushInt(int16_t nValue)
{
for (int16_t i = 0; i < (N * 2); ++i) {
int16_t id_ = i / 2;
int16_t bit_ = i % 2;
if ( 0 == bit_ ) {
int16_t value_ = int16_t(mValue[id_] & 0xFFFF);
if ( 0 != value_ ) {
continue;
}
mValue[id_] |= nValue;
break;
} else {
int16_t value_ = int16_t(mValue[id_] >> 16);
if ( 0 != value_ ) {
continue;
}
int32_t value0_ = (nValue << 16);
mValue[id_] |= value0_;
break;
}
}
mIntArray->runDirty();
}
void Int16Count::popInt(int16_t nValue)
{
for (int16_t i = 0; i < (N * 2); ++i) {
int16_t id_ = i / 2;
int16_t bit_ = i % 2;
if ( 0 == bit_ ) {
int16_t value_ = int16_t(mValue[id_] & 0xFFFF);
if ( nValue != value_ ) {
continue;
}
mValue[id_] &= 0xFFFF0000;
break;
} else {
int16_t value_ = int16_t(mValue[id_] >> 16);
if ( nValue != value_ ) {
continue;
}
mValue[id_] &= 0xFFFF;
break;
}
}
mIntArray->runDirty();
}
void Int16Count::runReset(int16_t nId)
{
if ( (nId < 1) || (nId > (N * 2)) ) {
LOGE("[%s]%d,%d", __METHOD__, N, nId);
return;
}
int16_t id_ = (nId - 1) / 2;
int16_t bit_ = (nId - 1) % 2;
if (0 == bit_) {
mValue[bit_] &= 0xFFFF0000;
} else {
mValue[bit_] &= 0xFFFF;
}
mIntArray->runDirty();
}
Int16Count::Int16Count()
{
}
Int16Count::~Int16Count()
{
}
}
|
fc24e4654a4aec26173087e583f76aef7bcec27a | 1c3dcb1ad48be6448c6732229d56d021fcd45594 | /3rd/main/main.ino | 05b096dd958286a4bf2bec504263a7686b4d03c5 | [] | no_license | youk720/test_rot | 9640ddada8b7c2e48b9f7a46561640d8cf365ed4 | 56439b8c4f83c6a5c9929236f0b41eec742a107d | refs/heads/master | 2020-03-31T16:24:29.900035 | 2019-06-12T10:12:32 | 2019-06-12T10:12:32 | 152,374,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,054 | ino | main.ino | #include <Encoder.h>
// ロータリーエンコーダ用ライブラリ導入
// ライブラリのリファレンスページ https://www.pjrc.com/teensy/td_libs_Encoder.html
// Change these pin numbers to the pins connected to your encoder.
// Best Performance: both pins have interrupt capability
// Good Performance: only the first pin has interrupt capability
// Low Performance: neither pin has interrupt capability
// エンコーダ接続ピン指定
Encoder left(2, 4);
Encoder center(2, 7);
Encoder right(2, 8);
// avoid using pins with LEDs attached
// 古い値の定義
long positionCenter = -999;
long positionLeft = -999;
long positionRight = -999;
//新しいエンコーダ値のもとの変数定義
long newCenter, newLeft, newRight;
// ロータリーエンコーダで操作した時にLEDの状態を変えるための変数定義
int red, green, blue;
//各種ピン番号を定義
#define rot_left_led 3
#define rot_center_led 5
#define rot_right_led 6
#define RedLED 9
#define GreenLED 10
#define BlueLED 11
#define left_sw A0
#define center_sw A1
#define right_sw A2
// 最初にさせるだけの動作等
void setup() {
// シリアル開業
Serial.begin(9600);
// Serial.println("TwoKnobs Encoder Test:");
pinMode(rot_center_led, OUTPUT);
pinMode(rot_left_led, OUTPUT);
pinMode(rot_right_led, OUTPUT);
pinMode(left_sw, INPUT); //エンコーダ値リセットスイッチ
pinMode(center_sw, INPUT);
pinMode(right_sw, INPUT);
// PWM対応ピンでLED光らせているものは記入不要のため記入していない
}
void loop() {
//新しいエンコーダの値を代入
newCenter = center.read();
newLeft = left.read();
newRight = right.read();
// ロータリーエンコーダが動き次第動作
if (newCenter != positionCenter) {
// ロータリーエンコーダ左右の動作の処理をいれた関数起動
center_rotation();
// 動作終了後に値を同一化
positionCenter = newCenter;
}
// 他のロータリーエンコーダでも上記と同様処理を実行
if(newLeft != positionLeft){
left_rotation();
positionLeft = newLeft;
}
if(newRight != positionRight){
right_rotation();
positionRight = newRight;
}
// ロータリーエンコーダ値 & LED値初期化処理
if (digitalRead(left_sw) == LOW) {
Serial.read();
Serial.println("Reset LEFT encoder by switch");
// 以下でロータリーエンコーダ値を上書き(ただしエンコーダライブラリを入れていないとこの機能は使用不可)
left.write(0);
red = 0;
}
if(digitalRead(center_sw) == LOW){
Serial.read();
Serial.println("Reset CENTER encoder by switch");
center.write(0);
green = 0;
}
if(digitalRead(right_sw) == LOW){
Serial.read();
Serial.println("Reset RIGHT encoder by switch");
right.write(0);
blue = 0;
}
// LED発行
analogWrite(RedLED, red);
analogWrite(GreenLED, green);
analogWrite(BlueLED, blue);
// ロータリーLED 点滅
if(red != 0){
digitalWrite(rot_left_led, LOW);
}else{
digitalWrite(rot_left_led, HIGH);
}
if(green!=0){
digitalWrite(rot_center_led, LOW);
}else{
digitalWrite(rot_center_led, HIGH);
}
if(blue!=0){
digitalWrite(rot_right_led, LOW);
}else{
digitalWrite(rot_right_led, HIGH);
}
}
// エンコーダ左右振り分け
void left_rotation(){
if(newLeft < positionLeft){
// 左回りの処理
if(red<=255){
red = red + 1;
}
}else if(newLeft > positionLeft){
// 右回りの処理
if(red!=0){
red = red - 1;
}
}
}
void center_rotation(){
if(newCenter < positionCenter){
if (green <= 255) {
green = green + 1;
}
}else if(newCenter > positionCenter){
if (green != 0) {
green = green - 1;
}
}
}
void right_rotation(){
if(newRight < positionRight){
if(blue<=255){
blue = blue + 1;
}
}else if(newRight > positionRight){
if (blue!=0) {
blue = blue - 1;
}
}
}
|
a55a61e65388f0ed6334818955901c1c61831588 | 65f60d63f327560f8b6c133f6dce5d83f115afa9 | /assignments/Assignment4/mpg.cpp | 3b50476cf30fa2c8a4f2d02541bbadaa98e45fdf | [
"MIT"
] | permissive | tspires/personal | 5a289baa1db440dce20f6239b9a5cc0cc3795ee0 | 7444621203e405739e02595a3c0b85b3fd63e894 | refs/heads/master | 2021-01-22T21:32:26.862926 | 2015-07-10T18:20:58 | 2015-07-10T18:20:58 | 21,474,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | cpp | mpg.cpp | #include <iostream>
#include <iomanip>
using namespace std;
double literToGallon(double liters);
int main() {
bool done = false;
char response;
int milesTraveled;
int litersConsumed;
double gallonsConsumed;
double mpg;
cout.precision(4);
while (done == false) {
cout << "How many liters of fuel did you use? " << endl;
cin >> litersConsumed;
cout << "How many miles did you travel? " << endl;
cin >> milesTraveled;
gallonsConsumed = literToGallon(litersConsumed);
mpg = milesTraveled / gallonsConsumed;
cout << "You used " << gallonsConsumed << " gallons of fuel and you got " << mpg << " miles per gallon. " << endl;
cout << "Would you like to go again? [y/n] ";
cin >> response;
if (response == 'y') {
done = false;
}
else {
done = true;
}
}
return 0;
}
double literToGallon(double liters) {
return liters * 0.264179;
}
|
886895d268e1d4e1d66a4a4437e2deeba0ac3cbc | 35e159e7360a2debb7432b9d94deaf8d843b4379 | /led_reg/main.cpp | ee229a8115d6fb9c6080999d1b3d864e9a294aba | [] | no_license | PolBadWolf/led_line | e0917ff65ea88ec5816db335e741deb9e0a4773d | b4448966b555bb5771caa3f0ba2019b23019a54e | refs/heads/master | 2021-01-23T02:06:19.612212 | 2017-03-27T11:39:18 | 2017-03-27T11:39:18 | 85,966,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,097 | cpp | main.cpp | /*
* led_reg.cpp
*
* Created: 23.03.2017 20:44:05
* Author : User
*/
#include "system/path.h"
#include "ws2812.h"
#define line1_len 18
sRGB line1_mass[line1_len];
WS2812* line1;
int main(void)
{
//__port(DDRB).bit7 = 1;
line1 = new WS2812(line1_len, line1_mass, &DDRB, &PORTB, 1<<1 );
while (1)
{
//__port(PORTB).bit7 = 0;
//__delay_ms(500);
//__port(PORTB).bit7 = 1;
//__delay_ms(500);
//
line1_mass[ 0] = { 255, 000, 000 };
line1_mass[ 1] = { 000, 255, 000 };
line1_mass[ 2] = { 000, 000, 255 };
line1_mass[ 3] = { 255, 255, 000 };
line1_mass[ 4] = { 255, 000, 255 };
line1_mass[ 5] = { 000, 255, 255 };
line1_mass[ 6] = { 128, 128, 128 };
line1_mass[ 7] = { 064, 255, 128 };
line1_mass[ 8] = { 255, 000, 000 };
line1_mass[ 9] = { 000, 255, 000 };
line1_mass[10] = { 255, 000, 000 };
line1_mass[11] = { 000, 255, 000 };
line1_mass[12] = { 255, 000, 000 };
line1_mass[13] = { 000, 255, 000 };
line1_mass[14] = { 255, 000, 000 };
line1_mass[15] = { 000, 255, 000 };
line1_mass[16] = { 128, 255, 128 };
line1->Interrupt();
}
}
|
9f2d68a6e17386fa940e5b9a473686f8df30bed4 | ef9cf52ffdd24cb8f7c9461acccd9e5770a131d6 | /cplus/leetcode/88merge.cpp | 485c676941c9d0b79ad2f6b7bcffcce0cb08043a | [] | no_license | Slwhy/Algorithm | 3e03bdaeed443dae29eea55aa897fcb2fe1e759d | 2b6b9bc783b67eba3e57371e5d9ce126add05f1f | refs/heads/master | 2022-04-27T19:03:27.014082 | 2022-04-05T09:40:01 | 2022-04-05T09:40:01 | 141,416,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | cpp | 88merge.cpp | //
// Created by slwhy on 2022/3/13.
//
#include "vector"
#include "queue"
using namespace std;
void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) {
int index = m + n - 1;
m--, n--;
while (n >= 0) {
if (m < 0) nums1[index--] = nums2[n--];
else if (nums1[m] > nums2[n]) nums1[index--] = nums1[m--];
else nums1[index--] = nums2[n--];
}
}
void merge2(vector<int> &nums1, int m, vector<int> &nums2, int n) {
queue<int> q;
int index1 = 0, index2 = 0;
while (index1 < m + n) {
if (index1 < m) q.push(nums1[index1]);
if (!q.empty() && (index2 >= n || q.front() <= nums2[index2])) {
nums1[index1++] = q.front();
q.pop();
} else {
nums1[index1++] = nums2[index2++];
}
}
} |
57ff53e006ce9070572e26473caee120557bd6c2 | 08fbcf15d01080b5ab222740d24a24dfb86f2e18 | /cpp/math/api/EseMathValStatIntf.h | db777ec191f6e482978f70fe92d622be2c43b007 | [] | no_license | vgromov/esfwxe | 399e07bec2370349821f19d84b9b0648a71b89ea | 5b64245b057884eb5dd708f60b90d7c97769dcca | refs/heads/master | 2021-07-10T15:16:17.591367 | 2020-07-10T13:48:06 | 2020-07-10T13:48:06 | 165,986,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,788 | h | EseMathValStatIntf.h | #ifndef _ese_math_val_stat_intf_h_
#define _ese_math_val_stat_intf_h_
#ifdef ESE_USE_STATS_SERIALIZATION
# if !defined(ESE_USE_STATS_SERIALIZATION_READ) && !defined(ESE_USE_STATS_SERIALIZATION_WRITE)
# undef ESE_USE_STATS_SERIALIZATION
# else
/// Foward declarations
class EseStreamIntf;
# endif
#else
# undef ESE_USE_STATS_SERIALIZATION_READ
# undef ESE_USE_STATS_SERIALIZATION_WRITE
#endif
/// Value statistics calculator interface
///
class ESE_ABSTRACT EseMathValStatIntf
{
public:
virtual void destroy() ESE_NOTHROW = 0;
virtual bool isComplete() const ESE_NOTHROW = 0;
virtual bool avgIsComplete() const ESE_NOTHROW = 0;
virtual bool uaIsComplete() const ESE_NOTHROW = 0;
virtual void reset() ESE_NOTHROW = 0;
virtual void valAppend(esF val) ESE_NOTHROW = 0;
virtual void avgFinalize() ESE_NOTHROW = 0;
virtual void uaValAppend(esF val) ESE_NOTHROW = 0;
virtual void finalize(esF deviceErr, bool errIsRel) ESE_NOTHROW = 0;
virtual esF minGet() const ESE_NOTHROW = 0;
virtual esF maxGet() const ESE_NOTHROW = 0;
virtual esF avgGet() const ESE_NOTHROW = 0;
virtual esF uaGet() const ESE_NOTHROW = 0;
virtual esF ubGet() const ESE_NOTHROW = 0;
virtual esF ucGet() const ESE_NOTHROW = 0;
virtual esF uGet() const ESE_NOTHROW = 0;
virtual esU32 cntGet() const ESE_NOTHROW = 0;
#ifdef ESE_USE_STATS_SERIALIZATION
# if defined(ESE_USE_STATS_SERIALIZATION_READ) && 0 != ESE_USE_STATS_SERIALIZATION_READ
virtual bool readFrom(EseStreamIntf& in) ESE_NOTHROW = 0;
# endif
# if defined(ESE_USE_STATS_SERIALIZATION_WRITE) && 0 != ESE_USE_STATS_SERIALIZATION_WRITE
virtual bool writeTo(EseStreamIntf& out) const ESE_NOTHROW = 0;
# endif
#endif
};
#endif //< _ese_math_val_stat_intf_h_
|
f7965703fbdeb3264c6f8b570a0282ac0a18c6d6 | 7122233f6730eaea0969e7c7d3d6075ee95a15b6 | /MathUtility/Matrix/LUDecomposition.hpp | 7fb81dccc2e4679a87639762a15a53df965d1576 | [] | no_license | zarath8128/NumericalCode | 9ad0d5ad587a911e60794a5daef41c221793529c | e59397f47be2def640bdb0ceec52b7826a445053 | refs/heads/master | 2021-01-19T21:28:30.367603 | 2013-08-15T08:16:21 | 2013-08-15T08:16:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,212 | hpp | LUDecomposition.hpp | #ifndef LU_DECOMPOSITION_HPP
#define LU_DECOMPOSITION_HPP
#ifdef __cplusplus
#include <cstdint>
#include <ostream>
#include <iomanip>
#else
#include <stdint.h>
#endif
#ifdef __cplusplus
namespace zarath
{
extern "C"
{
#endif
#ifdef __cplusplus
}
class LUBuffer
{
public:
LUBuffer(uint32_t size):Size(size)
{
buffer = new double[Size*Size];
U = new double*[Size];
L = new double*[Size - 1];
double *tp = buffer;
for(uint32_t i = 0; i < Size; ++i)
U[i] = (tp += i);
tp += Size;
for(uint32_t i = 0; i < Size -1 ; ++i)
L[i] = (tp += i);
}
~LUBuffer()
{
delete [] U;
delete [] L;
delete [] buffer;
}
double& operator()(uint32_t row, uint32_t column)
{
if(row > column)
return L[row - 1][column];
else
return U[column][row];
}
double getL(uint32_t row, uint32_t column)
{
if(row > column)
return L[row - 1][column];
else if(row == column)
return 1;
else
return 0;
}
double getU(uint32_t row, uint32_t column)
{
if(row > column)
return 0;
else
return U[column][row];
}
int LUDecomposition()
{
double buf;
for(uint32_t i = 0; i < Size; ++i)
{
//U
for(uint32_t c = i; c < Size; ++c)
{
for(uint32_t r = 0; r < i; ++r)
U[c][i] -= (L[i - 1][r] * U[c][r]);
}
//L
for(uint32_t r = i; r < (Size - 1); ++r)
{
for(uint32_t c = 0; c < i; ++c)
L[r][i] -= (L[r][c] * U[i][c]);
L[r][i] /= U[i][i];
}
}
return 0;
}
//b <- this-composite
int LUComposition(LUBuffer& b)
{
double buf;
for(int i = 0; i < Size; ++i)
for(int j = 0; j < Size; ++j)
{
buf = 0;
for(int k = 0; k < Size; ++k)
buf += this->getL(i, k)*this->getU(k, j);
b(i, j) = buf;
}
return 0;
}
uint32_t getSize(){return Size;}
private:
uint32_t Size;
double **L;
double **U;
double *buffer;
};
std::ostream& operator << (std::ostream& dist, LUBuffer& buf)
{
for(uint32_t i = 0; i < buf.getSize(); ++i)
{
for(uint32_t j = 0; j < buf.getSize(); ++j)
{
dist << std::setw(15) << std::left << buf(i, j);
}
dist << std::endl;
}
return dist;
}
}
#endif
#endif
|
643a3d3c9c0ed9cb2259307feb799e8d2843d7ab | 06d7c1ca396c4a58e650ad979b1453ea1ad99993 | /catkin_ws/src/ms_path_planner/include/ms_path_planner/ClusterPcl.h | 4363791aee274b219963bf768c7f5740aa5918fd | [] | no_license | Robotics-Mark/ros | 27dec75ed61d437c1281a9fe6393ce822a818e17 | a8fb9688e70757a46588744871595d7e3d08aaee | refs/heads/master | 2021-05-09T22:13:25.741223 | 2016-02-17T11:09:33 | 2016-02-17T11:09:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,215 | h | ClusterPcl.h | #ifndef CLUSTERPCL_H
#define CLUSTERPCL_H
#include <vector>
#include <ms_path_planner/ClusterPclConfig.h>
using namespace ms_path_planner;
#include <pcl/features/normal_3d.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/search/kdtree.h>
#include <pcl/segmentation/conditional_euclidean_clustering.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/filters/voxel_grid.h>
#include <Eigen/Dense>
using namespace std;
template<typename PointT>
class ClusterPcl{
public:
typedef pcl::PointXYZRGBNormal PointOut;
typedef pcl::PointCloud<PointOut> PointCloud;
typedef pcl::KdTreeFLANN<PointOut> KdTreeIn;
ClusterPcl();
~ClusterPcl();
void set_input_pcl(const PointCloud& input_pcl);
void set_kdtree(const KdTreeIn& input_kdtree);
int clustering(PointCloud& noWall, PointCloud& borders, PointCloud& segmented, PointCloud& wall);
void get_cluster_info(std::vector<int>& cluster_info_);
inline void setConfig(ClusterPclConfig& new_config) {config = new_config; normal_clustering_thres = new_config.normal_clustering_thres;}
inline ClusterPclConfig getConfig() {return config;}
private:
ClusterPclConfig config;
// this param needs to be static
static double normal_clustering_thres;
//Input point cloud
PointCloud pcl_in;
//Point cloud with normals
PointCloud pcl_normal;
//Kdtree of the input point cloud
KdTreeIn kdtree_input_pcl;
//Point cloud without wall
PointCloud pcl_noWall, pcl_Wall;
//Index of point filtered out in noWall
std::vector<int> pointIdxFilterOut;
//cluster is an array of indices-arrays, indexing points of the input point cloud and own cluster
pcl::IndicesClusters clusters;
std::vector<int> clusters_info;
bool in_filteredList(int p);
void compute_normals();
void filter_Wall();
void elaborate_cluster();
void cluster_pcl();
bool enforceSimilarity (const PointOut& point_a, const PointOut& point_b, float squared_distance);
};
#endif
|
e66fa983d9e21973120e3d458eba1c1dbbaf4dfc | 7f2e7edff293b0277137516a4f0b88021a63f1e3 | /Shape/pzshapequad.cpp | 83ac34d139be15f1b13b1a0db79fd37b9eb5a777 | [] | no_license | labmec/neopz | 3c8da1844164765606a9d4890597947c1fadbb41 | 4c6b6d277ce097b97bfc8dea1b6725860f4fe05a | refs/heads/main | 2023-08-30T22:35:13.662951 | 2022-03-18T19:57:30 | 2022-03-18T19:57:30 | 33,341,900 | 48 | 17 | null | 2023-09-13T19:46:34 | 2015-04-03T02:18:47 | C++ | UTF-8 | C++ | false | false | 18,191 | cpp | pzshapequad.cpp | /**
* @file
* @brief Contains the implementation of the TPZShapeQuad methods.
*/
#include "pzshapequad.h"
#include "pzshapelinear.h"
#include "pzshapepoint.h"
#include "pzmanvector.h"
#include "pzerror.h"
#include "pzreal.h"
#include "pzlog.h"
#ifdef PZ_LOG
static TPZLogger logger("pz.shape.TPZShapeQuad");
#endif
using namespace std;
namespace pzshape {
/**Transformation of the point within a quadrilateral face */
REAL TPZShapeQuad::gTrans2dQ[8][2][2] = {//s* , t*
{ { 1., 0.},{ 0., 1.} },
{ { 0., 1.},{ 1., 0.} },
{ { 0., 1.},{-1., 0.} },
{ {-1., 0.},{ 0., 1.} },
{ {-1., 0.},{ 0.,-1.} },//s* = -s t* = -t , etc
{ { 0.,-1.},{-1., 0.} },
{ { 0.,-1.},{ 1., 0.} },
{ { 1., 0.},{ 0.,-1.} }
};
REAL TPZShapeQuad::gRibTrans2dQ1d[4][2] = { {1.,0.},{0.,1.},{-1.,0.},{0.,-1.} };
void TPZShapeQuad::ShapeCorner(const TPZVec<REAL> &pt, TPZFMatrix<REAL> &phi, TPZFMatrix<REAL> &dphi) {
REAL x[2],dx[2],y[2],dy[2];
x[0] = (1.-pt[0])/2.;
x[1] = (1.+pt[0])/2.;
dx[0] = -0.5;
dx[1] = 0.5;
y[0] = (1.-pt[1])/2.;
y[1] = (1.+pt[1])/2.;
dy[0] = -0.5;
dy[1] = 0.5;
phi(0,0) = x[0]*y[0];
phi(1,0) = x[1]*y[0];
phi(2,0) = x[1]*y[1];
phi(3,0) = x[0]*y[1];
dphi(0,0) = dx[0]*y[0];
dphi(1,0) = x[0]*dy[0];
dphi(0,1) = dx[1]*y[0];
dphi(1,1) = x[1]*dy[0];
dphi(0,2) = dx[1]*y[1];
dphi(1,2) = x[1]*dy[1];
dphi(0,3) = dx[0]*y[1];
dphi(1,3) = x[0]*dy[1];
}
/*
* Computes the generating shape functions for a quadrilateral element
* @param pt (input) point where the shape function is computed
* @param phi (input) value of the (4) shape functions
* @param dphi (input) value of the derivatives of the (4) shape functions holding the derivatives in a column
*/
void TPZShapeQuad::ShapeGenerating(const TPZVec<REAL> &pt, TPZFMatrix<REAL> &phi, TPZFMatrix<REAL> &dphi)
{
int is;
for(is=4; is<8; is++)
{
phi(is,0) = phi(is%4,0)*phi((is+1)%4,0);
dphi(0,is) = dphi(0,is%4)*phi((is+1)%4,0)+phi(is%4,0)*dphi(0,(is+1)%4);
dphi(1,is) = dphi(1,is%4)*phi((is+1)%4,0)+phi(is%4,0)*dphi(1,(is+1)%4);
}
phi(8,0) = phi(0,0)*phi(2,0);
dphi(0,8) = dphi(0,0)*phi(2,0)+phi(0,0)*dphi(0,2);
dphi(1,8) = dphi(1,0)*phi(2,0)+phi(0,0)*dphi(1,2);
// Make the generating shape functions linear and unitary
for(is=4; is<8; is++)
{
phi(is,0) += phi(8,0);
dphi(0,is) += dphi(0,8);
dphi(1,is) += dphi(1,8);
phi(is,0) *= 4.;
dphi(0,is) *= 4.;
dphi(1,is) *= 4.;
}
phi(8,0) *= 16.;
dphi(0,8) *= 16.;
dphi(1,8) *= 16.;
}
/*
* Computes the generating shape functions for a quadrilateral element
* @param pt (input) point where the shape function is computed
* @param phi (input) value of the (4) shape functions
* @param dphi (input) value of the derivatives of the (4) shape functions holding the derivatives in a column
*/
void TPZShapeQuad::ShapeGenerating(const TPZVec<REAL> &pt, TPZVec<int> &nshape, TPZFMatrix<REAL> &phi, TPZFMatrix<REAL> &dphi)
{
int is;
for(is=4; is<8; is++)
{
if(nshape[is-NCornerNodes] < 1) continue;
phi(is,0) = phi(is%4,0)*phi((is+1)%4,0);
dphi(0,is) = dphi(0,is%4)*phi((is+1)%4,0)+phi(is%4,0)*dphi(0,(is+1)%4);
dphi(1,is) = dphi(1,is%4)*phi((is+1)%4,0)+phi(is%4,0)*dphi(1,(is+1)%4);
}
phi(8,0) = phi(0,0)*phi(2,0);
dphi(0,8) = dphi(0,0)*phi(2,0)+phi(0,0)*dphi(0,2);
dphi(1,8) = dphi(1,0)*phi(2,0)+phi(0,0)*dphi(1,2);
// Make the generating shape functions linear and unitary
for(is=4; is<8; is++)
{
if(nshape[is-NCornerNodes] < 1) continue;
phi(is,0) += phi(8,0);
dphi(0,is) += dphi(0,8);
dphi(1,is) += dphi(1,8);
phi(is,0) *= 4.;
dphi(0,is) *= 4.;
dphi(1,is) *= 4.;
}
phi(8,0) *= 16.;
dphi(0,8) *= 16.;
dphi(1,8) *= 16.;
}
void TPZShapeQuad::Shape(TPZVec<REAL> &pt, TPZVec<int64_t> &id, TPZVec<int> &order,
TPZFMatrix<REAL> &phi,TPZFMatrix<REAL> &dphi) {
ShapeCorner(pt,phi,dphi);
int is,d;
TPZFNMatrix<100> phiblend(NSides,1),dphiblend(Dimension,NSides);
for(is=0; is<NCornerNodes; is++)
{
phiblend(is,0) = phi(is,0);
for(d=0; d<Dimension; d++)
{
dphiblend(d,is) = dphi(d,is);
}
}
ShapeGenerating(pt,phiblend,dphiblend);
REAL out;
int shape = 4;
for (int rib = 0; rib < 4; rib++) {
ProjectPoint2dQuadToRib(rib,pt,out);
TPZVec<int64_t> ids(2);
TPZManVector<REAL,1> outvec(1,out);
ids[0] = id[rib%4];
ids[1] = id[(rib+1)%4];
REAL store1[20],store2[40];
int ord2 = order[rib]-1;//two orders : order in x and order in y
TPZFMatrix<REAL> phin(ord2,1,store1,20),dphin(2,ord2,store2,40);
TPZShapeLinear::ShapeInternal(outvec,order[rib],phin,dphin,TPZShapeLinear::GetTransformId1d(ids));
TransformDerivativeFromRibToQuad(rib,ord2,dphin);
for (int i = 0; i < ord2; i++) {
phi(shape,0) = phiblend(rib+4,0)*phin(i,0);
for(int xj=0;xj<2;xj++) {
dphi(xj,shape) = dphiblend(xj,rib+4)*phin(i,0)+
phiblend(rib+4,0)*dphin(xj,i);
}
shape++;
}
}
REAL store1[20],store2[40];
int ord = (order[4]-1)*(order[4]-1);
TPZFMatrix<REAL> phin(ord,1,store1,20),dphin(2,ord,store2,40);
ShapeInternal(pt,order[4]-2,phin,dphin,GetTransformId2dQ(id));
for(int i=0;i<ord;i++) {//funcoes de interior s�o em numero ordem-1
phi(shape,0) = phiblend(8,0)*phin(i,0);
for(int xj=0;xj<2;xj++) {//x e y
dphi(xj,shape) = dphiblend(xj,8)*phin(i,0) +
phiblend(8,0)*dphin(xj,i);
}
shape++;
}
}
void TPZShapeQuad::SideShape(int side,TPZVec<REAL> &pt, TPZVec<int64_t> &id, TPZVec<int> &order,
TPZFMatrix<REAL> &phi,TPZFMatrix<REAL> &dphi) {
switch(side) {
case 0:
case 1:
case 2:
case 3:
TPZShapePoint::Shape(pt, id, order, phi, dphi);
break;
case 4:
case 5:
case 6:
case 7:
TPZShapeLinear::Shape(pt, id, order, phi, dphi);
break;
case 8:
Shape(pt, id, order, phi, dphi);
}
}
void TPZShapeQuad::ShapeOrder(const TPZVec<int64_t> &id, const TPZVec<int> &order, TPZGenMatrix<int> &shapeorders)//, TPZVec<int64_t> &sides
{
int64_t nsides = TPZQuadrilateral::NSides;
// o que eh o vetor order?
// Eu suponho que em cada posicao tem a ordem de cada lado.
// Na shape ja esta associado a lados com dimensao maior que 1, order[0](lado 3) ...
int nshape = NCornerNodes;
for (int is = NCornerNodes; is < nsides; is++)
{
nshape += NConnectShapeF(is,order[is-NCornerNodes]);
}
// shapeorders ja vem com tamanho definido, entao a conta acima so serve para ver se as ordens estao corretas
if (nshape!=shapeorders.Rows())
{
// Algo errado
DebugStop();
}
int linha = 0;
for (int side = 0; side < nsides; side++)
{
nshape = 1;
if(side >= NCornerNodes) nshape = NConnectShapeF(side,order[side-NCornerNodes]);
int sideorder = 1;
if(side >= NCornerNodes) sideorder = order[side-NCornerNodes];
TPZGenMatrix<int> locshapeorders(nshape,3);
SideShapeOrder(side, id, sideorder, locshapeorders);
int nlin = locshapeorders.Rows();
int ncol = locshapeorders.Cols();
for (int il = 0; il<nlin; il++)
{
for (int jc = 0; jc<ncol; jc++)
{
shapeorders(linha, jc) = locshapeorders(il, jc);
}
linha++;
}
}
}
void TPZShapeQuad::SideShapeOrder(const int side, const TPZVec<int64_t> &id, const int order, TPZGenMatrix<int> &shapeorders)
{
if (side<=3)
{
if (shapeorders.Rows() != 1)
{
DebugStop();
}
shapeorders(0,0) = 1;
shapeorders(0,1) = 0;
shapeorders(0,2) = 0;
}
else if (side == 8)
{
if (shapeorders.Rows() != (order-1)*(order-1)) {
DebugStop();
}
int transid = GetTransformId(id);
int count = 0;
for (int i=2; i<order+1; i++) {
for (int j=2; j<order+1; j++) {
int a = i;
int b = j;
switch (transid)
{
case 0:
case 3:
case 4:
case 7:
break;
case 1:
case 2:
case 5:
case 6:
{
int c = a;
a = b;
b = c;
}
break;
default:
DebugStop();
break;
}
shapeorders(count,0) = a;
shapeorders(count,1) = b;
count++;
}
}
}
else
{
int nshape = order-1;
if (shapeorders.Rows() != nshape)
{
DebugStop();
}
for (int ioy = 0; ioy < order-1; ioy++)
{
shapeorders(ioy,0) = ioy+2;
}
}
}
void TPZShapeQuad::ShapeInternal(TPZVec<REAL> &x, int order,
TPZFMatrix<REAL> &phi, TPZFMatrix<REAL> &dphi) {
if((order-2) < 0) return;
int ord1 = order - 1;
int numshape = (order-1)*(order-1);
if(numshape > phi.Rows() || phi.Cols() < 1) phi.Resize(numshape,1);
if(dphi.Rows() < 2 || dphi.Cols() < numshape) dphi.Resize(2,numshape);
TPZFNMatrix<20, REAL> phi0(ord1,1),phi1(ord1,1),dphi0(1,ord1),dphi1(1,ord1);
TPZShapeLinear::fOrthogonal(x[0],ord1,phi0,dphi0);
TPZShapeLinear::fOrthogonal(x[1],ord1,phi1,dphi1);
for (int i=0;i<ord1;i++) {
for (int j=0;j<ord1;j++) {
int index = i*ord1+j;
phi(index,0) = phi0(i,0)* phi1(j,0);
dphi(0,index) = dphi0(0,i)* phi1(j,0);
dphi(1,index) = phi0(i,0)*dphi1(0,j);
}
}
}
void TPZShapeQuad::ShapeInternal(TPZVec<REAL> &x, int order,
TPZFMatrix<REAL> &phi, TPZFMatrix<REAL> &dphi,int quad_transformation_index) {
if(order < 0) return;
int ord1 = order+1;
int numshape = ord1*ord1;
TPZManVector<REAL> out(2);
TransformPoint2dQ(quad_transformation_index,x,out);
if(numshape > phi.Rows() || phi.Cols() < 1) phi.Resize(numshape,1);
if(dphi.Rows() < 2 || dphi.Cols() < numshape) dphi.Resize(2,numshape);
REAL store1[20],store2[20],store3[20],store4[20];
TPZFMatrix<REAL> phi0(ord1,1,store1,20),phi1(ord1,1,store2,20),dphi0(1,ord1,store3,20),dphi1(1,ord1,store4,20);
TPZShapeLinear::fOrthogonal(out[0],ord1,phi0,dphi0);
TPZShapeLinear::fOrthogonal(out[1],ord1,phi1,dphi1);
for (int i=0;i<ord1;i++) {
for (int j=0;j<ord1;j++) {
int index = i*ord1+j;
phi(index,0) = phi0(i,0)* phi1(j,0);
dphi(0,index) = dphi0(0,i)* phi1(j,0);
dphi(1,index) = phi0(i,0)*dphi1(0,j);
}
}
TransformDerivative2dQ(quad_transformation_index,numshape,dphi);
}
void TPZShapeQuad::ShapeInternal(int side, TPZVec<REAL> &x, int order,
TPZFMatrix<REAL> &phi, TPZFMatrix<REAL> &dphi) {
if (side < 4 || side > 8) {
DebugStop();
}
switch (side) {
case 4:
case 5:
case 6:
case 7:
{
pzshape::TPZShapeLinear::ShapeInternal(x, order, phi, dphi);
}
break;
case 8:
{
ShapeInternal(x, order, phi, dphi);
}
break;
default:
LOGPZ_ERROR(logger,"Wrong side parameter")
DebugStop();
break;
}
}
void TPZShapeQuad::TransformDerivative2dQ(int transid, int num, TPZFMatrix<REAL> &in) {
for(int i=0;i<num;i++) {
REAL aux[2];
aux[0] = in(0,i);
aux[1] = in(1,i);
in(0,i) = gTrans2dQ[transid][0][0]*aux[0]+gTrans2dQ[transid][1][0]*aux[1];
in(1,i) = gTrans2dQ[transid][0][1]*aux[0]+gTrans2dQ[transid][1][1]*aux[1];
}
}
//transf. o ponto dentro da face quadrilateral
void TPZShapeQuad::TransformPoint2dQ(int transid, TPZVec<REAL> &in, TPZVec<REAL> &out) {
out[0] = gTrans2dQ[transid][0][0]*in[0]+gTrans2dQ[transid][0][1]*in[1];//Cedric 23/02/99
out[1] = gTrans2dQ[transid][1][0]*in[0]+gTrans2dQ[transid][1][1]*in[1];//Cedric 23/02/99
}
TPZTransform<REAL> TPZShapeQuad::ParametricTransform(int trans_id){
TPZTransform<REAL> trans(2,2);
trans.Mult()(0,0) = gTrans2dQ[trans_id][0][0];
trans.Mult()(0,1) = gTrans2dQ[trans_id][0][1];
trans.Mult()(1,0) = gTrans2dQ[trans_id][1][0];
trans.Mult()(1,1) = gTrans2dQ[trans_id][1][1];
return trans;
}
void TPZShapeQuad::ProjectPoint2dQuadToRib(int rib, TPZVec<REAL> &in, REAL &out) {
out = gRibTrans2dQ1d[rib][0]*in[0]+gRibTrans2dQ1d[rib][1]*in[1];
}
int TPZShapeQuad::GetTransformId2dQ(TPZVec<int64_t> &id) {
int id0,id1,minid;
id0 = (id[0] < id[1]) ? 0 : 1;
id1 = (id[2] < id[3]) ? 2 : 3;
minid = (id[id0] < id[id1]) ? id0 : id1;//minid : menor id local
id0 = (minid+1)%4;//id anterior local (sentido antihorario)
id1 = (minid+3)%4;//id posterior local (sentido horario)
minid = id[minid];//minid : menor id global
if (id[id0] < id[id1]) {//antihorario
if (minid == id[0]) return 0;
if (minid == id[1]) return 2;
if (minid == id[2]) return 4;
if (minid == id[3]) return 6;
} else {//horario
if (minid == id[0]) return 1;
if (minid == id[1]) return 3;
if (minid == id[2]) return 5;
if (minid == id[3]) return 7;
}
return 0;
}
void TPZShapeQuad::TransformDerivativeFromRibToQuad(int rib,int num,TPZFMatrix<REAL> &dphi) {
for (int j = 0;j<num;j++) {
dphi(1,j) = gRibTrans2dQ1d[rib][1]*dphi(0,j);
dphi(0,j) = gRibTrans2dQ1d[rib][0]*dphi(0,j);
}
}
int TPZShapeQuad::NConnectShapeF(int side, int order) {
if(side<4) return 1;//0 a 4
// int s = side-4;//s = 0 a 14 ou side = 6 a 20
#ifdef PZDEBUG
{
// if(order <1) DebugStop();
}
#endif
if(side<8) return (order-1);//6 a 14
if(side==8) {
return ((order-1)*(order-1));
}
PZError << "TPZShapeQuad::NConnectShapeF, bad parameter side " << side << endl;
return 0;
}
int TPZShapeQuad::NShapeF(const TPZVec<int> &order) {
int in,res=NCornerNodes;
for(in=NCornerNodes;in<NSides;in++) {
res += NConnectShapeF(in,order[in-NCornerNodes]);
}
return res;
}
void TPZShapeQuad::Shape2dQuadInternal(TPZVec<FADREAL> &x, int order,
TPZVec<FADREAL> &phi,int quad_transformation_index) {
const int ndim = 3;
if(order < 0) return;
int ord1 = order+1;
int numshape = ord1*ord1;
TPZVec<FADREAL> out(2);
TransformPoint2dQ(quad_transformation_index,x,out);
if(numshape > phi.NElements()/*Rows()*/ || phi[0].size()/*Cols()*/ < ndim) phi.Resize(numshape, FADREAL(ndim, 0.0));
//if(dphi.Rows() < 2 || dphi.Cols() < numshape) dphi.Resize(2,numshape);
//REAL store1[20],store2[20],store3[20],store4[20];
//TPZFMatrix<REAL> phi0(ord1,1,store1,20),phi1(ord1,1,store2,20),dphi0(1,ord1,store3,20),dphi1(1,ord1,store4,20);
TPZVec<FADREAL> phi0(20, FADREAL(ndim, 0.0)),
phi1(20, FADREAL(ndim, 0.0));
TPZShapeLinear::FADfOrthogonal(out[0],ord1,phi0);
TPZShapeLinear::FADfOrthogonal(out[1],ord1,phi1);
for (int i=0;i<ord1;i++) {
for (int j=0;j<ord1;j++) {
int index = i*ord1+j;
//phi(index,0) = phi0(i,0)* phi1(j,0);
phi[index] = phi0[i] * phi1[j];
/*dphi(0,index) = dphi0(0,i)* phi1(j,0);
dphi(1,index) = phi0(i,0)*dphi1(0,j);*/
}
}
// TransformDerivative2dQ(quad_transformation_index,numshape,phi);
}
void TPZShapeQuad::TransformPoint2dQ(int transid, TPZVec<FADREAL> &in, TPZVec<FADREAL> &out) {
out[0] = gTrans2dQ[transid][0][0]*in[0]+gTrans2dQ[transid][0][1]*in[1];//Cedric 23/02/99
out[1] = gTrans2dQ[transid][1][0]*in[0]+gTrans2dQ[transid][1][1]*in[1];//Cedric 23/02/99
}
/*
void TPZShapeQuad::TransformDerivative2dQ(int transid, int num, TPZVec<FADREAL> &in) {
for(int i=0;i<num;i++) {
double aux[2];
aux[0] = in[i].d(0);
aux[1] = in[i].d(1);
in[i].fastAccessDx(0) = gTrans2dQ[transid][0][0]*aux[0]+gTrans2dQ[transid][1][0]*aux[1];
in[i].fastAccessDx(1) = gTrans2dQ[transid][0][1]*aux[0]+gTrans2dQ[transid][1][1]*aux[1];
}
}
void TPZShapeQuad::TransformDerivativeFromRibToQuad(int rib,int num,TPZVec<FADREAL> &phi) {
for (int j = 0;j<num;j++) {
//dphi(1,j) = gRibTrans2dQ1d[rib][1]*dphi(0,j);
//dphi(0,j) = gRibTrans2dQ1d[rib][0]*dphi(0,j);
phi[j].fastAccessDx(1) = gRibTrans2dQ1d[rib][1]*phi[j].d(0);
phi[j].fastAccessDx(0) = gRibTrans2dQ1d[rib][0]*phi[j].d(0);
}
}
*/
};
|
dd9dfd9100889bac139b03df6f2288386f0bde67 | 44a374b84b3048b23afd6e989df1291dcc9f5609 | /src/core/gamestatemanager.cpp | 73a10f0092c39bda488dd284439a14d828c625ba | [] | permissive | ricardoalcantara/learning-sdl | 34f21ecb36ab7a277243b0b67b5798c292c7fe83 | 27559dde0ce7cd7fce89014f6b9a45a4bfe2728c | refs/heads/main | 2023-05-31T04:27:15.254161 | 2021-06-30T21:01:39 | 2021-06-30T21:01:39 | 375,518,155 | 0 | 0 | MIT | 2021-06-09T23:54:26 | 2021-06-09T23:54:26 | null | UTF-8 | C++ | false | false | 1,340 | cpp | gamestatemanager.cpp | #include "core/gamestatemanager.h"
#include "core/gamestate.h"
GameStateManager *GameStateManager::instance = nullptr;
GameStateManager *GameStateManager::getInstance()
{
if (instance == nullptr)
{
instance = new GameStateManager();
}
return instance;
}
void GameStateManager::release()
{
delete instance;
instance = nullptr;
}
GameStateManager::GameStateManager()
{
}
GameStateManager::~GameStateManager()
{
}
void GameStateManager::addState(int id, GameState *gameState)
{
auto search = gameStates.find(id);
if (search != gameStates.end())
{
// Todo: Clean
}
gameStates.insert(std::make_pair(id, gameState));
}
void GameStateManager::loadState(int id)
{
auto search = gameStates.find(id);
if (search != gameStates.end())
{
currentGameState = search->second;
currentGameState->load();
}
}
bool GameStateManager::isStateLoaded(int id)
{
return currentGameState && currentGameState->isLoaded();
}
void GameStateManager::selectState(int id)
{
auto search = gameStates.find(id);
if (search != gameStates.end())
{
currentGameState = search->second;
}
}
void GameStateManager::ready()
{
currentGameState->ready();
}
void GameStateManager::handleEvents(SDL_Event *)
{
}
void GameStateManager::update()
{
currentGameState->update();
}
void GameStateManager::render()
{
currentGameState->render();
}
|
00d1b358c35f8c8fb47071fc67e336c3d32a91ea | 52ca17dca8c628bbabb0f04504332c8fdac8e7ea | /boost/archive/impl/basic_xml_oarchive.ipp | 998cd10c0910f1f95e7a5af02411770d21a4e084 | [] | no_license | qinzuoyan/thirdparty | f610d43fe57133c832579e65ca46e71f1454f5c4 | bba9e68347ad0dbffb6fa350948672babc0fcb50 | refs/heads/master | 2021-01-16T17:47:57.121882 | 2015-04-21T06:59:19 | 2015-04-21T06:59:19 | 33,612,579 | 0 | 0 | null | 2015-04-08T14:39:51 | 2015-04-08T14:39:51 | null | UTF-8 | C++ | false | false | 77 | ipp | basic_xml_oarchive.ipp | #include "thirdparty/boost_1_58_0/boost/archive/impl/basic_xml_oarchive.ipp"
|
9a32fb0c499daed67634e1e6a158b74fe0f7e3f9 | 42b45e18ac790a2cd08cd09c9fc7054e5f8eb3b8 | /stockaccount.cpp | d4371a1c2508f4fc113aa8d13499c8a98a0157dc | [] | no_license | mz363/Banking-and-Stock-Application-CPP | 66db6f248417816986c33856c3d9f9416426cffa | e309ce3b1169923bcfcfb2a66d76a718cc056293 | refs/heads/master | 2020-03-28T12:50:30.577520 | 2018-09-11T15:34:49 | 2018-09-11T15:34:49 | 148,339,603 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,385 | cpp | stockaccount.cpp | #include "stockaccount.h"
stockAccount::stockAccount()
{
}
int stockAccount::stringToINT(string a)
{
string Stocks[36] = { "","VNET","AGTK","AKAM","BIDU","BCOR","WIFI","CARB","JRJC","CCIH","CCOI","CXDO","EDXC","ENV","FB","GDDY","IAC","IIJI","INAP","IPAS","JCOM","LLNW","MOMO","NTES","EGOV","NQ","OPESY","BLNKF","NAME","SIFY","SINA","SOHU","SNST","TCTZF","TCEHY","TMMI" };
string numStocks[36] = { "","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35" };
for (int i = 0; i < 36; i++)
{
if (a == Stocks[i])
a = numStocks[i];
// if (a != Stocks[i]){
// cout << "The stock is not avaliable" << endl;
// break;
// }
}
int b = atoi(a.c_str());
return b;
}
string stockAccount::symCom(string stockSym, string symStock) {
string col1, col2, col3, col4, col5, col6;
string companys;
string space = " ";
istringstream ss(symStock);
ss >> col1 >> col2 >> col3 >> col4 >> col5 >> col6;
if (stockSym == "VNET" || stockSym == "JRJC" || stockSym == "FB" || stockSym == "GDDY" || stockSym == "IIJI" || stockSym == "NQ" || stockSym == "OPESY" || stockSym == "SIFY" || stockSym == "SNST" || stockSym == "TCEHY")
companys = col2 + space + col3 + space + col4 + space + col5;
else if (stockSym == "AGTK" || stockSym == "AKAM" || stockSym == "BIDU" || stockSym == "WIFI" || stockSym == "CCIH" || stockSym == "CCOI" || stockSym == "JCOM" || stockSym == "LLNW" || stockSym == "MOMO" || stockSym == "NTES" || stockSym == "NAME" || stockSym == "TCTZF")
companys = col2 + space + col3 + space + col4;
else if (stockSym == "BCOR" || stockSym == "CARB" || stockSym == "CXDO" || stockSym == "EDXC" || stockSym == "ENV" || stockSym == "INAP" || stockSym == "IPAS" || stockSym == "EGOV" || stockSym == "BLNKF" || stockSym == "SINA" || stockSym == "SOHU" || stockSym == "TMMI")
companys = col2 + space + col3;
else if (stockSym == "IAC")
companys = col2;
return companys;
}
double stockAccount::symPrice(string stockSym, string symStock) {
string col1, col2, col3, col4, col5, col6;
double price1 = 0.0;
istringstream ss(symStock);
ss >> col1 >> col2 >> col3 >> col4 >> col5 >> col6;
if (stockSym == "VNET" || stockSym == "JRJC" || stockSym == "FB" || stockSym == "GDDY" || stockSym == "IIJI" || stockSym == "NQ" || stockSym == "OPESY" || stockSym == "SIFY" || stockSym == "SNST" || stockSym == "TCEHY")
price1 = atof(col6.c_str());
else if (stockSym == "AGTK" || stockSym == "AKAM" || stockSym == "BIDU" || stockSym == "WIFI" || stockSym == "CCIH" || stockSym == "CCOI" || stockSym == "JCOM" || stockSym == "LLNW" || stockSym == "MOMO" || stockSym == "NTES" || stockSym == "NAME" || stockSym == "TCTZF")
price1 = atof(col5.c_str());
else if (stockSym == "BCOR" || stockSym == "CARB" || stockSym == "CXDO" || stockSym == "EDXC" || stockSym == "ENV" || stockSym == "INAP" || stockSym == "IPAS" || stockSym == "EGOV" || stockSym == "BLNKF" || stockSym == "SINA" || stockSym == "SOHU" || stockSym == "TMMI")
price1 = atof(col4.c_str());
else if (stockSym == "IAC")
price1 = atof(col3.c_str());
return price1;
}
string stockAccount::timeNow(int a)
{
#pragma warning(disable: 4996)
time_t now = time(0);
tm *ltm = localtime(&now);
string th = to_string(ltm->tm_hour);
string tm = to_string(ltm->tm_min);
string ts = to_string(ltm->tm_sec);
string ty = to_string(1900 + ltm->tm_year);
string tmn = to_string(1 + ltm->tm_mon);
string td = to_string(ltm->tm_mday);
string colon = ":";
string slash = "/";
string times;
if (a == 1)
times = th + colon + tm + colon + ts;
else if (a == 2)
times = tmn + slash + td + slash + ty;
return times;
#pragma warning(default: 4996)
}
void stockAccount::displayCurrent(string stockSym)
{
srand(unsigned(time(NULL)));
int choice = rand() % 4 + 1;
string symStock, col1, col2, col3, col4, col5, col6, choice1 = to_string(choice);;
ifstream f("stock1.txt");
for (int i = 0; i<stringToINT(stockSym); i++)
{
getline(f, symStock);
}
istringstream ss(symStock);
ss >> col1 >> col2 >> col3 >> col4 >> col5 >> col6;
cout << endl;
cout << setw(8) << left << col1 << setw(26) << left << symCom(stockSym, symStock) << setw(8) << left << symPrice(stockSym, symStock) << left << timeNow(1) << endl;
cout << endl;
}
void stockAccount::buyStock(vector <structAccount> &stk, string stockSym, int num, double priceRange)
{
structAccount info;
srand(unsigned(time(NULL)));
double price = 0.0;
int choice = rand() % 4 + 1;
string col1, col2, col3, col4, col5, col6, choice1 = to_string(choice);
string symStock;
ifstream f("stock" + choice1 + ".txt");
for (int i = 0; i<stringToINT(stockSym); i++) {
getline(f, symStock);
}
istringstream ss(symStock);
ss >> col1 >> col2 >> col3 >> col4 >> col5 >> col6;
price = symPrice(stockSym, symStock);
if (priceRange >= price) {
string line;
double a;
fstream f3;
f3.open("cashbalance.txt", fstream::in);
for (int i = 0; i<1; i++)
{
getline(f3, line);
}
a = atof(line.c_str());
a -= priceRange*num;
f3.close();
f3.open("cashbalance.txt", fstream::out | fstream::trunc);
f3 << a;
f3.close();
ofstream f1;
f1.open("stock_transaction_history.txt", ios::out | ios::app);
f1 << setw(12) << left << "Buy" << setw(12) << left << col1 << setw(12) << left << num << setw(11) << left << fixed << setprecision(2) << priceRange << left << timeNow(1) << endl;
f.close();
info.symbol = col1;
info.company = symCom(stockSym, symStock);
info.number = num;
info.price = price;
info.total = price*num;
info.sorting = stringToINT(stockSym);
for (int i = 0; i<stk.size(); ++i) {
if (stockSym != stk[i].symbol) {
stk.push_back(info);
break;
}
else if (stockSym == stk[i].symbol)
stk[i].symbol = col1;
stk[i].price = price;
stk[i].number += num;
stk[i].total += price*num;
stk[i].company = symCom(stockSym, symStock);
break;
}
if (stk.size() == 0)
stk.push_back(info);
}
else if (priceRange < price) {
cout << "Cannot process transaction. " << endl;
}
}
void stockAccount::displayPorfolio(const vector <structAccount> &stk) {
double value = 0.0;
cout << endl;
cout << "Cash balance = $" << cashBalance() << endl << endl;
cout << setw(8) << left << "Symbol" << setw(24) << left << "Company" << setw(8) << left << "Number" << setw(8) << left << "Price" << left << "Total" << endl;
ofstream f1;
f1.open("stockvector.txt", fstream::out | fstream::trunc);
for (int i = 0; i < stk.size(); ++i) {
f1 << setw(8) << left << stk[i].symbol << setw(24) << left << stk[i].company << setw(8) << left << stk[i].number << setw(8) << left << fixed << setprecision(2) << stk[i].price << left << setprecision(2) << stk[i].total << endl;
value += stk[i].total;
}
f1.close();
string STRING;
ifstream f;
f.open("stockvector.txt");
while (!f.eof())
{
getline(f, STRING);
cout << STRING << endl;
}
f.close();
cout << "Total portfolio value: $" << fixed << setprecision(2) << value + cashBalance() << endl << endl;
}
void stockAccount::displayTransaction() {
string STRING;
cout << setw(12) << left << "Action" << setw(12) << left << "Symbol" << setw(12) << left << "Shares" << setw(11) << left << "Price" << left << "Time" << endl;
ifstream f;
f.open("stock_transaction_history.txt");
while (!f.eof())
{
getline(f, STRING);
cout << STRING << endl;
}
f.close();
}
void stockAccount::menuStock()
{
vector <structAccount> stk;
bool flag = true;
int selection;
char test[256];
while (flag) {
cout << "Please select an option" << endl;
cout << "\t1. Display current price for a stock symbol\n\t2. Buy stock\n\t3. Sell stock\n\t4. Display current portfolio\n\t5. Display transactions history\n\t6. Return to main menu" << endl;
cout << "Your Selection:\t";
cin.getline(test, 256);
cout << test << endl;
selection = atoi(test);
switch (selection) {
case 1: {
char line[256];
cout << endl;
cout << "Enter stock symbol for checking price: ";
cin.getline(line, 256);
cout << line;
cout << endl;
string symbol(line);
displayCurrent(symbol);
break;
}
case 2: {
string a, b, c;
char line[256];
cout << endl;
cout << "Enter buy options: ";
cin.getline(line, 256);
cout << line << endl;
cout << endl;
istringstream ss(line);
ss >> a >> b >> c;
string symbol = a;
int numShare = atoi(b.c_str());
double price = atof(c.c_str());
buyStock(stk, symbol, numShare, price);
break;
}
case 3: {
string a, b, c;
char line[256];
cout << endl;
cout << "Enter selling options: ";
cin.getline(line, 256);
cout << line << endl;
cout << endl;
istringstream ss(line);
ss >> a >> b >> c;
string symbol = a;
int numShare = atoi(b.c_str());
double price = atof(c.c_str());
sellStock(stk, symbol, numShare, price);
break;
}
case 4:
displayPorfolio(stk);
break;
case 5:
cout << endl;
displayTransaction();
break;
case 6:
cout << endl;
flag = false;
break;
default:
break;
}
}
}
void stockAccount::sellStock(vector <structAccount> &stk, string stockSym, int num, double priceRange) {
structAccount info;
srand(unsigned(time(NULL)));
double price = 0.0;
int choice = rand() % 4 + 1;
string col1, col2, col3, col4, col5, col6, choice1 = to_string(choice);
string symStock;
ifstream f("stock" + choice1 + ".txt");
for (int i = 0; i<stringToINT(stockSym); i++) {
getline(f, symStock);
}
istringstream ss(symStock);
ss >> col1 >> col2 >> col3 >> col4 >> col5 >> col6;
price = symPrice(stockSym, symStock);
if (priceRange <= price) {
string line;
double a;
fstream f3;
f3.open("cashbalance.txt", fstream::in);
for (int i = 0; i<1; i++)
{
getline(f3, line);
}
a = atof(line.c_str());
a += priceRange*num;
f3.close();
f3.open("cashbalance.txt", fstream::out | fstream::trunc);
f3 << a;
f3.close();
ofstream f1;
f1.open("stock_transaction_history.txt", ios::out | ios::app);
f1 << setw(12) << left << "Sell" << setw(12) << left << col1 << setw(12) << left << num << setw(11) << left << priceRange << left << timeNow(1) << endl;
f.close();
info.symbol = col1;
info.company = symCom(stockSym, symStock);
info.number = num;
info.price = price;
info.total = price*num;
for (int i = 0; i<stk.size(); ++i) {
if (stockSym != stk[i].symbol) {
cout << "you do not have this stock" << endl;
break;
}
else if (stockSym == stk[i].symbol)
stk[i].symbol = col1;
stk[i].price = price;
stk[i].number -= num;
stk[i].total = price*stk[i].number;
stk[i].company = symCom(stockSym, symStock);
break;
}
if (stk.size() == 0)
cout << "You do not have this stock." << endl;
}
else if (priceRange > price)
cout << "Cannot process transaction. " << endl;
}
void stockAccount::sortBank(vector<structAccount> &stk) {
int finish = 0;
while (finish == 0) {
for (int i = 0; i < stk.size() - 1; i++) {
if (stk[i].sorting > stk[i + 1].sorting) {
swap(stk[i].symbol, stk[i + 1].symbol);
swap(stk[i].company, stk[i + 1].company);
swap(stk[i].number, stk[i + 1].number);
swap(stk[i].price, stk[i + 1].price);
swap(stk[i].total, stk[i + 1].total);
swap(stk[i].sorting, stk[i + 1].sorting);
continue;
}
}
finish = 1;
}
} |
4c3977f8bfbd8b4efa9fa60d81dbd7ccfba837c2 | 164d1dbfe4242b51e4bb17e1eceb534b66873c61 | /src/reduce.cpp | fd2c8e3f49dec7f2dc931af6497e81caef60386e | [] | no_license | haydenm2/rosbag_reduce_resolution | b1cf69de271e8d863b2f358f10529a7181a7fd93 | 0165f9f8bc215b7cc3753a292ea622e49c43c1e7 | refs/heads/master | 2021-06-23T14:54:51.204584 | 2021-06-10T16:22:38 | 2021-06-10T16:22:38 | 216,060,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,207 | cpp | reduce.cpp | #include "reduce.h"
namespace reduce_resolution {
ReduceResolution::ReduceResolution(double resize_ratio)
{
// create a private node handle for use with param server
ros::NodeHandle nh_private("~");
// ROS communication
image_transport::ImageTransport it(nh_);
sub_video_ = it.subscribe("video", 100, &ReduceResolution::CallbackVideo, this);
pub_video_ = it.advertise("video/image_raw", 1);
init_ = true;
resize_ratio_ = resize_ratio;
}
// ----------------------------------------------------------------------------
void ReduceResolution::CallbackVideo(const sensor_msgs::ImageConstPtr& data)
{
// Convert incoming image data to OpenCV format
msg_ = cv_bridge::toCvCopy(data, "bgr8");
frame_ = msg_->image;
if(init_)
{
// Define reduced image size parameters
sd_resolution_.width = frame_.size().width*resize_ratio_;
sd_resolution_.height = frame_.size().height*resize_ratio_;
init_ = false;
}
// Reduce size of image message
cv::resize(frame_, frame_reduced_, sd_resolution_, 0, 0, cv::INTER_AREA);
msg_->image = frame_reduced_;
// Publish reduced image
pub_video_.publish(msg_->toImageMsg());
}
} // namespace reduce_resolution |
1d79471bf13c6bf6c3a133357d81c2a9ad5b4f59 | fbbfc318ebcd9e19cb60647b6aef567046682bad | /src/videocapture/win/MediaFoundation_Capture.cpp | e45612abe986ddde4ae8bd22263ad7c66d57ef6c | [
"Apache-2.0"
] | permissive | killerbobjr/video_capture | 20674f84606c26caa7357ab9d5a16d9030a8b149 | 18e9b543e7fc8d8f8766adc7e512367b6ff4e03e | refs/heads/master | 2023-04-18T04:38:04.879743 | 2021-04-22T02:36:37 | 2021-04-22T02:36:37 | 281,543,164 | 0 | 0 | null | 2020-07-22T01:27:24 | 2020-07-22T01:27:23 | null | UTF-8 | C++ | false | false | 19,001 | cpp | MediaFoundation_Capture.cpp | #include <videocapture/win/MediaFoundation_Capture.h>
#include <iostream>
namespace ca
{
MediaFoundation_Capture::MediaFoundation_Capture(frame_callback fc, void* user): Base(fc, user), state(CA_STATE_NONE), mf_callback(NULL), imf_media_source(NULL), imf_source_reader(NULL), must_shutdown_com(true)
{
/* Initialize COM */
HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hr))
{
/*
CoInitializeEx must be called at least once and is usually called
only once freach each thread that uses the COM library. Multiple calls
to CoInitializeEx by the same thread are allowed as long as they pass
the same concurrency flag, but subsequent calls returns S_FALSE.
To close the COM library gracefully on a thread, each successful call to
CoInitializeEx, including any call that returns S_FALSE, must be balanced
by a corresponding call to CoUninitialize.
Source: https://searchcode.com/codesearch/view/76074495/
*/
must_shutdown_com = false;
printf("Warning: cannot initialize COM in MediaFoundation_Capture.\n");
}
/* Initialize MediaFoundation */
hr = MFStartup(MF_VERSION);
if (FAILED(hr))
{
printf("Error: cannot startup the MediaFoundation_Capture.\n");::exit(EXIT_FAILURE);
}
}
MediaFoundation_Capture::~MediaFoundation_Capture()
{
/* Close and stop */
if (state & CA_STATE_CAPTURING)
{
stop();
}
if (state & CA_STATE_OPENED)
{
close();
}
/* Shutdown MediaFoundation */
HRESULT hr = MFShutdown();
if (FAILED(hr))
{
printf("Error: failed to shutdown the MediaFoundation.\n");
}
/* Shutdown COM */
if (true == must_shutdown_com)
{
CoUninitialize();
}
pixel_buffer.user = NULL;
}
int MediaFoundation_Capture::open(Settings settings)
{
if (state & CA_STATE_OPENED)
{
printf("Error: already opened.\n");
return -1;
}
if (imf_media_source)
{
printf("Error: already opened the media source.\n");
return -2;
}
/* Create the MediaSource */
if (createVideoDeviceSource(settings.device, &imf_media_source) < 0)
{
printf("Error: cannot create the media device source.\n");
return -3;
}
/* Set the media format, width, height */
std::vector<Capability> capabilities;
if (getCapabilities(imf_media_source, capabilities) < 0)
{
printf("Error: cannot create the capabilities list to open the device.\n");
safeReleaseMediaFoundation(&imf_media_source);
return -4;
}
if (settings.capability >= capabilities.size())
{
printf("Error: invalid capability ID, cannot open the device.\n");
safeReleaseMediaFoundation(&imf_media_source);
return -5;
}
Capability cap = capabilities.at(settings.capability);
if (cap.pixel_format == CA_NONE)
{
printf("Error: cannot set a pixel format for CA_NONE.\n");
safeReleaseMediaFoundation(&imf_media_source);
return -6;
}
if (setDeviceFormat(imf_media_source, (DWORD) cap.pixel_format_index) < 0)
{
printf("Error: cannot set the device format.\n");
safeReleaseMediaFoundation(&imf_media_source);
return -7;
}
/* Create the source reader. */
MediaFoundation_Callback::createInstance(this, &mf_callback);
if (createSourceReader(imf_media_source, mf_callback, &imf_source_reader) < 0)
{
printf("Error: cannot create the source reader.\n");
safeReleaseMediaFoundation(&mf_callback);
safeReleaseMediaFoundation(&imf_media_source);
return -8;
}
/* Set the source reader format. */
if (setReaderFormat(imf_source_reader, cap) < 0)
{
printf("Error: cannot set the reader format.\n");
safeReleaseMediaFoundation(&mf_callback);
safeReleaseMediaFoundation(&imf_media_source);
return -9;
}
/* Set the pixel buffer strides, widths and heights based on the selected format. */
if (0 != pixel_buffer.setup(cap.width, cap.height, cap.pixel_format))
{
printf("Error: cannot setup the pixel buffer for the current pixel format.\n");
safeReleaseMediaFoundation(&mf_callback);
safeReleaseMediaFoundation(&imf_media_source);
return -10;
}
pixel_buffer.user = cb_user;
state |= CA_STATE_OPENED;
return 1;
}
int MediaFoundation_Capture::close()
{
if (!imf_source_reader)
{
printf("Error: cannot close the device because it seems that is hasn't been opend yet. Did you call openDevice?.\n");
return -1;
}
if (state & CA_STATE_CAPTURING)
{
stop();
}
safeReleaseMediaFoundation(&imf_source_reader);
safeReleaseMediaFoundation(&imf_media_source);
safeReleaseMediaFoundation(&mf_callback);
state &= ~CA_STATE_OPENED;
return 1;
}
int MediaFoundation_Capture::start()
{
if (!imf_source_reader)
{
printf("Error: cannot start capture becuase it looks like the device hasn't been opened yet.\n");
return -1;
}
if (!(state & CA_STATE_OPENED))
{
printf("Error: cannot start captureing because you haven't opened the device successfully.\n");
return -2;
}
if (state & CA_STATE_CAPTURING)
{
printf("Error: cannot start capture because we are already capturing.\n");
return -3;
}
/* Kick off the capture stream. */
HRESULT hr = imf_source_reader->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, NULL, NULL, NULL, NULL);
if (FAILED(hr))
{
if (hr == MF_E_INVALIDREQUEST)
{
printf("ReadSample returned MF_E_INVALIDREQUEST.\n");
}
else if (hr == MF_E_INVALIDSTREAMNUMBER)
{
printf("ReadSample returned MF_E_INVALIDSTREAMNUMBER.\n");
}
else if (hr == MF_E_NOTACCEPTING)
{
printf("ReadSample returned MF_E_NOTACCEPTING.\n");
}
else if (hr == E_INVALIDARG)
{
printf("ReadSample returned E_INVALIDARG.\n");
}
else if (hr == E_POINTER)
{
printf("ReadSample returned E_POINTER.\n");
}
else
{
printf("ReadSample - unhandled result.\n");
}
printf("Error: while trying to ReadSample() on the imf_source_reader. \n");
std::cout << "Error: " << std::hex << hr << std::endl;
return -4;
}
state |= CA_STATE_CAPTURING;
return 1;
}
int MediaFoundation_Capture::stop()
{
if (!imf_source_reader)
{
printf("Error: Cannot stop capture because it seems that the device hasn't been opened yet.\n");
return -1;
}
if (!(state&CA_STATE_CAPTURING))
{
printf("Error: Cannot stop capture because we're not capturing yet.\n");
return -2;
}
state &= ~CA_STATE_CAPTURING;
return 1;
}
void MediaFoundation_Capture::update()
{}
std::vector < Device > MediaFoundation_Capture::getDevices()
{
std::vector < Device > result;
UINT32 count = 0;
IMFAttributes * config = NULL;
IMFActivate ** devices = NULL;
HRESULT hr = MFCreateAttributes(&config, 1);
if (FAILED(hr))
{
goto done;
}
/* Filter capture devices. */
hr = config->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
if (FAILED(hr))
{
goto done;
}
/* Enumerate devices */
hr = MFEnumDeviceSources(config, &devices,&count);
if (FAILED(hr))
{
goto done;
}
if (count == 0)
{
goto done;
}
for (DWORD i = 0; i < count; ++i)
{
HRESULT hr = S_OK;
WCHAR* friendly_name = NULL;
UINT32 friendly_name_len = 0;
hr = devices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &friendly_name,&friendly_name_len);
if (SUCCEEDED(hr))
{
std::string name = string_cast<std::string>(friendly_name);
Device dev;
dev.index = i;
dev.name = name;
result.push_back(dev);
}
CoTaskMemFree(friendly_name);
}
done:
safeReleaseMediaFoundation(&config);
for (DWORD i = 0; i < count; ++i)
{
safeReleaseMediaFoundation(&devices[i]);
}
CoTaskMemFree(devices);
return result;
}
std::vector < Capability > MediaFoundation_Capture::getCapabilities(int device)
{
std::vector < Capability > result;
IMFMediaSource* source = NULL;
if (createVideoDeviceSource(device, &source) > 0)
{
getCapabilities(source, result);
safeReleaseMediaFoundation(&source);
}
return result;
}
std::vector<Format> MediaFoundation_Capture::getOutputFormats()
{
std::vector<Format> result;
return result;
}
/* PLATFORM SDK SPECIFIC */
/* -------------------------------------- */
int MediaFoundation_Capture::setDeviceFormat(IMFMediaSource* source, DWORD formatIndex)
{
IMFPresentationDescriptor* pres_desc = NULL;
IMFStreamDescriptor* stream_desc = NULL;
IMFMediaTypeHandler* handler = NULL;
IMFMediaType* type = NULL;
int result = 1;
HRESULT hr = source->CreatePresentationDescriptor(&pres_desc);
if (FAILED(hr))
{
printf("source->CreatePresentationDescriptor() failed.\n");
result = -1;
goto done;
}
BOOL selected;
hr = pres_desc->GetStreamDescriptorByIndex(0,&selected,&stream_desc);
if (FAILED(hr))
{
printf("pres_desc->GetStreamDescriptorByIndex failed.\n");
result = -2;
goto done;
}
hr = stream_desc->GetMediaTypeHandler(&handler);
if (FAILED(hr))
{
printf("stream_desc->GetMediaTypehandler() failed.\n");
result = -3;
goto done;
}
hr = handler->GetMediaTypeByIndex(formatIndex,&type);
if (FAILED(hr))
{
printf("hander->GetMediaTypeByIndex failed.\n");
result = -4;
goto done;
}
hr = handler->SetCurrentMediaType(type);
if (FAILED(hr))
{
printf("handler->SetCurrentMediaType failed.\n");
result = -5;
goto done;
}
done:
safeReleaseMediaFoundation(&pres_desc);
safeReleaseMediaFoundation(&stream_desc);
safeReleaseMediaFoundation(&handler);
safeReleaseMediaFoundation(&type);
return result;
}
int MediaFoundation_Capture::createSourceReader(IMFMediaSource* mediaSource, IMFSourceReaderCallback* callback, IMFSourceReader** sourceReader)
{
if (mediaSource == NULL)
{
printf("Error: Cannot create a source reader because the IMFMediaSource passed into this function is not valid.\n");
return -1;
}
if (callback == NULL)
{
printf("Error: Cannot create a source reader because the calls back passed into this function is not valid.\n");
return -2;
}
HRESULT hr = S_OK;
IMFAttributes* attrs = NULL;
int result = 1;
hr = MFCreateAttributes(&attrs, 1);
if (FAILED(hr))
{
printf("Error: cannot create attributes for the media source reader.\n");
result = -3;
goto done;
}
hr = attrs->SetUnknown(MF_SOURCE_READER_ASYNC_CALLBACK, callback);
if (FAILED(hr))
{
printf("Error: SetUnknown() failed on the source reader");
result = -4;
goto done;
}
/* Create a source reader which sets up the pipeline for us so we get access to the pixels */
hr = MFCreateSourceReaderFromMediaSource(mediaSource, attrs, sourceReader);
if (FAILED(hr))
{
printf("Error: while creating a source reader.\n");
result = -5;
goto done;
}
done:
safeReleaseMediaFoundation(&attrs);
return result;
}
int MediaFoundation_Capture::setReaderFormat(IMFSourceReader* reader, Capability&cap)
{
DWORD media_type_index = 0;
int result = -1;
HRESULT hr = S_OK;
while (SUCCEEDED(hr))
{
Capability match_cap;
IMFMediaType* type = NULL;
hr = imf_source_reader->GetNativeMediaType(0, media_type_index,&type);
if (SUCCEEDED(hr))
{
/* PIXELFORMAT */
PROPVARIANT var;
PropVariantInit(& var);
{
hr = type->GetItem(MF_MT_SUBTYPE, &var);
if (SUCCEEDED(hr))
{
match_cap.pixel_format = media_foundation_video_format_to_capture_format(*var.puuid);
}
}
PropVariantClear(&var);
/* SIZE */
PropVariantInit(&var);
{
hr = type->GetItem(MF_MT_FRAME_SIZE, &var);
if (SUCCEEDED(hr))
{
UINT32 high = 0;
UINT32 low = 0;
Unpack2UINT32AsUINT64(var.uhVal.QuadPart, &high, &low);
match_cap.width = high;
match_cap.height = low;
}
}
PropVariantClear(&var);
/* When the output media type of the source reader matches our specs, set it! */
if (match_cap.width == cap.width &&
match_cap.height == cap.height &&
match_cap.pixel_format == cap.pixel_format)
{
hr = imf_source_reader->SetCurrentMediaType(0, NULL, type);
if (FAILED(hr))
{
printf("Error: Failed to set the current media type for the given settings.\n");
}
else
{
hr = S_OK;
result = 1;
}
}
//type->Release(); // tmp moved down and wrapped around safeReleaseMediaFoundation()
}
else
{
break;
}
safeReleaseMediaFoundation(&type);
++media_type_index;
}
return result;
}
/**
* Get capabilities for the given IMFMediaSource which represents
* a video capture device.
*
* @param IMFMediaSource* source [in] Pointer to the video capture source.
* @param std::vector<AVCapability>& caps [out] This will be filled with capabilites
*/
int MediaFoundation_Capture::getCapabilities(IMFMediaSource* source, std::vector<Capability> &caps)
{
IMFPresentationDescriptor* presentation_desc = NULL;
IMFStreamDescriptor* stream_desc = NULL;
IMFMediaTypeHandler* media_handler = NULL;
IMFMediaType* type = NULL;
int result = 1;
DWORD types_count = 0;
HRESULT hr = source->CreatePresentationDescriptor(&presentation_desc);
if (FAILED(hr))
{
printf("Error: cannot get presentation descriptor.\n");
result = -1;
goto done;
}
BOOL selected;
hr = presentation_desc->GetStreamDescriptorByIndex(0, &selected, &stream_desc);
if (FAILED(hr))
{
printf("Error: cannot get stream descriptor.\n");
result = -2;
goto done;
}
hr = stream_desc->GetMediaTypeHandler(&media_handler);
if (FAILED(hr))
{
printf("Error: cannot get media type handler.\n");
result = -3;
goto done;
}
hr = media_handler->GetMediaTypeCount(&types_count);
if (FAILED(hr))
{
printf("Error: cannot get media type count.\n");
result = -4;
goto done;
}
#if 0
// The list of supported types is not garantueed to return everything :)
// this was a test to check if some types that are supported by my test-webcam
// were supported when I check them manually. (they didn't).
// See the Remark here for more info: http://msdn.microsoft.com/en-us/library/windows/desktop/bb970473(v=vs.85).aspx
IMFMediaType* test_type = NULL;
MFCreateMediaType(&test_type);
if (test_type)
{
GUID types[] = {
MFVideoFormat_UYVY,
MFVideoFormat_I420,
MFVideoFormat_IYUV,
MFVideoFormat_NV12,
MFVideoFormat_YUY2,
MFVideoFormat_Y42T,
MFVideoFormat_RGB24
};
test_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
for (int i = 0; i < 7; ++i)
{
test_type->SetGUID(MF_MT_SUBTYPE, types[i]);
hr = media_handler->IsMediaTypeSupported(test_type, NULL);
if (hr != S_OK)
{
printf("> Not supported: %d\n");
}
else
{
printf("> Yes, supported: %d\n", i);
}
}
}
safeReleaseMediaFoundation(&test_type);
#endif
// Loop over all the types
PROPVARIANT var;
for (DWORD i = 0; i < types_count; ++i)
{
Capability cap;
hr = media_handler->GetMediaTypeByIndex(i, &type);
if (FAILED(hr))
{
printf("Error: cannot get media type by index.\n");
result = -5;
goto done;
}
UINT32 attr_count = 0;
hr = type->GetCount(&attr_count);
if (FAILED(hr))
{
printf("Error: cannot type param count.\n");
result = -6;
goto done;
}
if (attr_count > 0)
{
for (UINT32 j = 0; j < attr_count; ++j)
{
GUID guid =
{
0
};
PropVariantInit(&var);
hr = type->GetItemByIndex(j,&guid, &var);
if (FAILED(hr))
{
printf("Error: cannot get item by index.\n");
result = -7;
goto done;
}
if (guid == MF_MT_SUBTYPE && var.vt == VT_CLSID)
{
cap.pixel_format = media_foundation_video_format_to_capture_format(*var.puuid);
cap.pixel_format_index = j;
}
else if (guid == MF_MT_FRAME_SIZE)
{
UINT32 high = 0;
UINT32 low = 0;
Unpack2UINT32AsUINT64(var.uhVal.QuadPart,&high,&low);
cap.width = (int) high;
cap.height = (int) low;
}
else if (guid == MF_MT_FRAME_RATE_RANGE_MIN ||
guid == MF_MT_FRAME_RATE_RANGE_MAX ||
guid == MF_MT_FRAME_RATE)
{
// @todo - not all FPS are added to the capability list.
UINT32 high = 0;
UINT32 low = 0;
Unpack2UINT32AsUINT64(var.uhVal.QuadPart,&high,&low);
cap.fps = fps_from_rational(low, high);
cap.fps_index = j;
}
PropVariantClear(&var);
}
cap.capability_index = i;
caps.push_back(cap);
}
safeReleaseMediaFoundation(&type);
}
done:
safeReleaseMediaFoundation(&presentation_desc);
safeReleaseMediaFoundation(&stream_desc);
safeReleaseMediaFoundation(&media_handler);
safeReleaseMediaFoundation(&type);
PropVariantClear(&var);
return result;
}
/**
* Create and active the given `device`.
*
* @param int device [in] The device index for which you want to get an
* activated IMFMediaSource object. This function
* allocates this object and increases the reference
* count. When you're ready with this object, make sure
* to call `safeReleaseMediaFoundation(&source)`
*
* @param IMFMediaSource** [out] We allocate and activate the device for the
* given `device` parameter. When ready, call
* `safeReleaseMediaFoundation(&source)` to free memory.
*/
int MediaFoundation_Capture::createVideoDeviceSource(int device, IMFMediaSource** source)
{
int result = 1;
IMFAttributes* config = NULL;
IMFActivate** devices = NULL;
UINT32 count = 0;
HRESULT hr = MFCreateAttributes(&config, 1);
if (FAILED(hr))
{
result = -1;
goto done;
}
/* Filter on capture devices */
hr = config->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
if (FAILED(hr))
{
printf("Error: cannot set the GUID on the IMFAttributes*.\n");
result = -2;
goto done;
}
/* Enumerate devices. */
hr = MFEnumDeviceSources(config,&devices,&count);
if (FAILED(hr))
{
printf("Error: cannot get EnumDeviceSources.\n");
result = -3;
goto done;
}
if (count == 0 || UINT32(device) > count)
{
result = -4;
goto done;
}
/* Make sure the given source is free/released. */
safeReleaseMediaFoundation(source);
/* Activate the capture device. */
hr = devices[device]->ActivateObject(IID_PPV_ARGS(source));
if (FAILED(hr))
{
printf("Error: cannot activate the object.");
result = -5;
goto done;
}
result = true;
done:
safeReleaseMediaFoundation(&config);
for (DWORD i = 0; i < count; ++i)
{
safeReleaseMediaFoundation(&devices[i]);
}
CoTaskMemFree(devices);
return result;
}
} /* namespace ca */
|
a1db27e125925892c8fd24a99a8aa945c9b1e56a | bb442983c32454261ca012d8946d33113ef961f6 | /problems/Find_The_Duplicate_Number.cpp | 87e5189ea0732efcc1103aed358fcb9592c16cc3 | [] | no_license | trooperli/my-leetcode | 98aef3aedcb7fd5be3eeb6f6c64c8c6fdfa7cbc9 | e71d9df5b89e187c93e66e3ec57bc6b245575e27 | refs/heads/master | 2021-04-04T06:12:40.035183 | 2020-04-29T19:41:53 | 2020-04-29T19:41:53 | 248,431,150 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 800 | cpp | Find_The_Duplicate_Number.cpp | /**
* This problem seems easy but not if it requires O(n) time complexity
* and O(1) space complexity. The key to this problem is when nums[i]
* != i, we do a swap(nums[i], nums[nums[i]]). Suppose nums[0] = 3,
* nums[3] = 4,after this swap, we have nums[3] = 3 and nums[0] = 4;
* then we swap(nums[0], nums[4]), suppose nums[4] = 0,we have nums[4]
* = 4 and nums[0]=0, and we move on to the next element in the array.
*/
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; ++i) {
while (nums[i] != i) {
if (nums[i] == nums[nums[i]]) {
return nums[i];
}
swap(nums[i], nums[nums[i]]);
}
}
return 0;
}
};
|
78945a92cb752f97b630642fe779a19b166f78e9 | 5ccdb058df19fc4e220b9bf7844ed9bbff956ffc | /p1157.cpp | b61f08f6bf9ee20634b74eebaaad7f3fb74e2d15 | [
"MIT"
] | permissive | sjnov11/Baekjoon-Online-Judge | 4db4253ba8df6923347ebdc33e920cfb1b2d8159 | a95df8a62e181d86a97d0e8969d139a3dae2be74 | refs/heads/master | 2020-04-02T09:00:30.235008 | 2018-12-03T10:05:52 | 2018-12-03T10:05:52 | 154,270,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 727 | cpp | p1157.cpp | #include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
int alpha_cnt[26];
for (int i = 0; i < 26; i++) {
alpha_cnt[i] = 0;
}
int diff_upper_lower = 'a' - 'A';
for (int i = 0; i < s.length(); i++) {
int idx = (int)s[i] > (int)'Z' ? s[i] - diff_upper_lower : s[i];
idx -= 'A';
alpha_cnt[idx]++;
}
int most_alpha_cnt = 0;
int most_alpha_idx = 0;
bool overlapped = false;
for (int i = 0; i < 26; i++) {
if (alpha_cnt[i] > most_alpha_cnt) {
most_alpha_cnt = alpha_cnt[i];
most_alpha_idx = i;
overlapped = false;
}
else if (alpha_cnt[i] == most_alpha_cnt) {
overlapped = true;
}
}
cout << (overlapped ? '?' : (char)('A'+most_alpha_idx)) << endl;
} |
0bfdb1631945d9a43e8e2724ba53fd7f2bfe7ba3 | 6aa2345c0801cdbfb498d312f0b6097b2e9616f3 | /src/kernel/utilities/ssl_path.cpp | e844768ab8d36b9c6c5c873a730db5d1b79d1717 | [
"Apache-2.0"
] | permissive | spin-scenario/spin-scenario | b98c73da3f07f523ef02a978787246e5a2c9b435 | 9cfff9117d221abd2e5a5e64bbe3780a615bf54d | refs/heads/master | 2022-12-15T03:01:53.990454 | 2022-12-09T03:29:02 | 2022-12-09T03:29:02 | 172,816,861 | 13 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 736 | cpp | ssl_path.cpp | #include "ssl_path.h"
#include <boost/algorithm/string.hpp>
namespace ssl {
namespace utility {
// terminal dir by the user.
std::string g_terminal_dir = "";
#ifdef WIN32
std::string g_install_dir = "../..";
#else
std::string g_install_dir = "..";
#endif
void set_terminal_dir(std::string s) {
g_terminal_dir = s;
boost::replace_all(g_terminal_dir, "\\", "\/");
}
void set_install_dir(std::string s) {
g_install_dir = s; // C:\Spin-Scenario\bin\spin-scenario.exe
boost::replace_all(g_install_dir, "\\", "\/");
#ifdef WIN32
boost::replace_last(g_install_dir, "spin-scenario.exe", "..");
#else
boost::replace_last(g_install_dir, "spin-scenario", "..");
#endif
}
} // namespace utility
} // namespace ssl
|
29d8b342ecf57f62a2f5a8a2152a3def63f3a7b7 | aa82c3e3be201e05225d31bda4e01ac577457d6f | /Src/EasyBuilder/view/ActorItem.cpp | dc780fd27f39ef8e481efca67c7788385b599462 | [] | no_license | xzrunner/doodle_editor | 8524493765676b821398acc090c0e7838e6e9647 | 78351087470cb38265f7a26317dcd116b8d02b0d | refs/heads/master | 2020-03-22T18:55:22.851215 | 2018-07-10T22:17:30 | 2018-07-10T22:17:30 | 140,491,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | cpp | ActorItem.cpp | #include "ActorItem.h"
#include "dataset/Actor.h"
using namespace ebuilder;
ActorItem::ActorItem(Actor* actor)
: m_actor(actor)
{
m_name = actor->m_name;
m_filepath = m_actor->getSymbol().getFilepath();
const wxgui::Bitmap* init = wxgui::BitmapMgr::Instance()->getItem(m_filepath);
if (m_bitmap != init) delete m_bitmap;
m_bitmap = const_cast<wxgui::Bitmap*>(init);
}
void ActorItem::loadFromTextFile(std::ifstream& fin)
{
}
void ActorItem::storeToTextFile(std::ofstream& fout) const
{
}
void ActorItem::reloadTexture() const
{
}
void ActorItem::draw() const
{
// m_actor->getSymbol().draw();
}
float ActorItem::getWidth() const
{
return 0;
}
float ActorItem::getHeight() const
{
return 0;
}
void ActorItem::loadResources()
{
} |
b599d405676e5737eefc1c039999bd1f821361d5 | 4a4b5d52807b0a34237c7996a8066ec74ecb6887 | /fraction/fraction.cpp | 8c09059ab53f869c40345450106c0b1ab647896f | [] | no_license | 19tpersons/CSIS352-Assign4 | e1a0d2a353fb47e955a62781330dce8de6dbce76 | cfd6f1aa013d7407ecbeb5d045f38cca69978073 | refs/heads/master | 2020-12-27T11:17:47.741835 | 2020-02-04T17:43:01 | 2020-02-04T17:43:01 | 237,882,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,717 | cpp | fraction.cpp | #include "fraction.h"
#include <string>
#include <math.h>
#include <iostream>
#include <iomanip>
using namespace std;
fraction::fractionType fraction::outputType = fraction::mixed;
fraction::fraction() {
}
fraction::fraction(double number) {
setFraction(number);
}
fraction::fraction(int numerator, int denominator) {
setFraction(numerator, denominator);
}
void fraction::setFraction(int n, int d) {
numerator = n;
denominator = d;
while (numerator >= denominator) {
wholeNumber += 1;
numerator -= d;
}
}
void fraction::setFraction(double number) {
bool negative = false;
if (number < 0) { //Needed because the calculations only work with positive numbers
negative = true;
number *= -1;
}
wholeNumber = floor(number);
//Turns the decimal part of the entered number into a integer
double decimal = fmod(number, 1);
double numOfDecimals = 0;
while (fmod(decimal, 1) > 0) {
numOfDecimals++;
decimal *= 10;
}
//sets numerator and denominator
numerator = decimal;
if (decimal == 0) {
denominator = 1;
} else {
denominator = pow(10, numOfDecimals);
}
if (negative) {
wholeNumber = wholeNumber * -1;
}
reduce();
}
void fraction::setDenominator(int number) {
if (number == 0) {
//TODO throw error
} else {
double divisor = (double) number / denominator;
if (numerator * divisor != (int)(numerator * divisor)) {
cout << "The numerator has to be a whole number" << endl;
return;
}
denominator *= divisor;
numerator *= divisor;
}
}
int fraction::getNumerator() {
bool negative = false;
int tmpWhole = wholeNumber;
int answer;
if (wholeNumber < 0) {
negative = true;
tmpWhole *= -1;
}
if (denominator == 1) {
answer = tmpWhole + numerator;
} else {
answer = tmpWhole * denominator + numerator;
}
if (negative) {
answer *= -1;
}
return answer;
}
int fraction::getNumerator(bool mixed) {
return numerator;
}
int fraction::getDenominator() {
return denominator;
}
int fraction::getWholeNumber() {
return wholeNumber;
}
double fraction::decimalValue() {
double converted;
if (wholeNumber < 0) {
converted = wholeNumber +((numerator / (double) denominator) * -1);
} else {
converted = wholeNumber + (numerator / (double) denominator);
}
return converted;
}
void fraction::outputFormat(fractionType newType) {
fraction::outputType = newType;
}
//implementation of euclids algorithm
int fraction::gcd(int a, int b)
{
if (a == 0)
return b;
return fraction::gcd(b % a, a);
}
void fraction::reduce() {
int prevRemainder = gcd(numerator, denominator);
numerator = numerator / prevRemainder;
denominator = denominator / prevRemainder;
}
const fraction& fraction::operator=(const fraction& rightObject) {
if (this != &rightObject) {
//copies over the state
numerator = rightObject.numerator;
denominator = rightObject.denominator;
wholeNumber = rightObject.wholeNumber;
}
return *this;
}
const fraction& fraction::operator=(double number) {
setFraction(number);
return *this;
}
ostream& operator<<(ostream& osObject, fraction& fract) {
//types
if (fraction::outputType == fraction::improper) {
if (fract.denominator == 1) {
osObject << fract.wholeNumber + fract.numerator;
} else {
osObject << fract.getNumerator() << "/" << fract.denominator;
}
} else if (fraction::outputType == fraction::decimal) {
osObject << fract.wholeNumber + ((double) fract.numerator / fract.denominator);
} else { //mixed number
if (fract.wholeNumber == 0) {
osObject << " " << fract.numerator << "/" << fract.denominator;
} else if (fract.denominator == 1) { //TODO FIX!!!
osObject << fract.wholeNumber + fract.numerator;
} else if(fract.numerator == 0) {
osObject << fract.wholeNumber;
} else {
osObject << fract.wholeNumber << " " << fract.numerator << "/" << fract.denominator;
}
}
return osObject;
}
istream& operator>>(istream& inStream, fraction& fract) {
string n;
string d;
bool slash = false; //used to see if the string we are iterating over has reached the denominator
string line;
getline(inStream, line);
for (int i = 0; i < line.length(); i++) {
char tmp;
tmp = line[i];
if (!slash) {
n = n + tmp;
} else {
d = d + tmp;
}
if (tmp == '/') {
slash = true;
}
}
fract.setFraction(stoi(n), stoi(d));
return inStream;
}
bool fraction::operator==(const fraction& fract) const {
return (wholeNumber == fract.wholeNumber && denominator == fract.denominator && numerator == fract.numerator);
}
bool fraction::operator==(int number) {
return (number == wholeNumber);
}
bool fraction::operator<(int number) {
return (number > decimalValue());
}
fraction fraction::operator+(const fraction& rightObject) const {
fraction sum;
sum.wholeNumber = rightObject.wholeNumber + wholeNumber;
//calculates fraction part
int tmpDenominator = denominator * rightObject.denominator;
int tmpNumerator = numerator * rightObject.denominator + rightObject.numerator * denominator;
sum.numerator = tmpNumerator;
sum.denominator = tmpDenominator;
fraction tmp(tmpNumerator, tmpDenominator);
tmp.reduce();
sum.numerator = tmp.getNumerator(true);
sum.denominator = tmp.getDenominator();
sum.wholeNumber += tmp.getWholeNumber();
return sum;
}
fraction fraction::operator-(const fraction& rightObject) const {
fraction difference;
difference.wholeNumber = wholeNumber - rightObject.wholeNumber;
int tmpDenominator = denominator * rightObject.denominator;
difference.denominator = tmpDenominator;
int tmpNumerator = numerator * rightObject.denominator - rightObject.numerator * denominator;
difference.numerator = tmpNumerator;
difference.reduce();
return difference;
}
fraction fraction::operator*(const fraction& rightObject) const {
fraction product;
product.wholeNumber = wholeNumber * rightObject.wholeNumber;
product.denominator = denominator * rightObject.denominator;
product.numerator = numerator * rightObject.numerator;
product.reduce();
return product;
}
fraction fraction::operator/(const fraction& rightObject) const {
fraction quotient;
//divide fraction part
quotient.numerator = numerator * rightObject.denominator;
quotient.denominator = denominator * rightObject.numerator;
//divide whole numbers and then add them back into the fraction
double divOfWholes = wholeNumber / (double) rightObject.wholeNumber;
fraction tmp;
tmp.setFraction(divOfWholes);
quotient = quotient + tmp;
return quotient;
}
|
a4a9fc35322f5d7a395d4dc8c068692250bc9b5a | 4dcde7b8b10bdee8e2a582d1e6fb1fb4958e9d58 | /c_cpp/c++_primer/ch6/array_params.cpp | 1c13135b7d9736ecfa0b468697243ec6f9d8449e | [] | no_license | wangfudex/practice | f103d1453cb917288b5b1101d8e9f6ae17754cbd | ce43a434a4f728d05e896869d3430d600b6c2dbb | refs/heads/master | 2021-06-16T14:19:03.490600 | 2017-04-16T14:59:59 | 2017-04-16T14:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | cpp | array_params.cpp | #include <iostream>
// 以下三個宣告為相同
void print(const int*);
void print(const int[]);
void print(const int[10]);
int main(void)
{
int i = 0, j[2] = {0, 1}; // list init.
print(&i); // ok,
print(j); // ok, j被轉成int*
print(&j); // error, &j為int (*)[2](pointer to array of 2 ints), 不是int*
}
|
2f8ba88db036a228deada0d66f372e2d5cc2f044 | e6a5e4d9538731efac8fbc199d0152a2e1560890 | /ch02/test/insertion_sort_test.cpp | c214180d75accc5ea684484fcca0fa7b0602c424 | [
"MIT"
] | permissive | tsyxyz/CLRS | 7517b07415567f7e8f5a8cdf59c664c8d2834710 | 562a294a16e0b9989862511183d12333c13f5b5f | refs/heads/master | 2021-07-11T10:00:57.614818 | 2021-06-13T15:02:43 | 2021-06-13T15:02:43 | 247,416,161 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | insertion_sort_test.cpp | #include "ch02/insertion_sort.h"
#include <gtest/gtest.h>
#include <iostream>
#include <vector>
TEST(insertion_sort, non_decrease) {
std::vector<int> seq = {8, 1, 3, 0, 2, 7};
std::vector<int> answer = {0, 1, 2, 3, 7, 8};
ch02::InsertionSortNonDecrease(seq);
EXPECT_TRUE(seq == answer);
}
TEST(insertion_sort, non_increase) {
std::vector<int> seq = {8, 1, 3, 0, 2, 7};
std::vector<int> answer = {8, 7, 3, 2, 1, 0};
ch02::InsertionSortNonIncrease(seq);
EXPECT_TRUE(seq == answer);
} |
6b707625d4c1225f6adaa56f354a02d93d09bc44 | 1154814c89c84b7e23ec1feed96be67491a5b7eb | /extern/libMeshRender/src/NormalCompresser.h | 6228cae3b9e7926a6d409b5c37bd7324c508bcbf | [] | no_license | linlut/View3dn | cc8e741a9a6967277a65a01793ddc61f7ac5ead9 | 4ba9a3b5414d95ac358d0e05f2834ebb451efedd | refs/heads/master | 2020-03-26T23:43:41.132808 | 2014-02-21T01:28:11 | 2014-02-21T01:28:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 715 | h | NormalCompresser.h | #pragma once
#ifndef NORMAL_COMPRESSER_H
#define NORMAL_COMPRESSER_H
#if defined(_MSC_VER) //Compiling on Windows
#if _MSC_VER <= 1700 //VS 2012 or older
#define uint32_t unsigned __int32
#else
#include <cstdint> //to provide def. for uint32_t
#endif
#else
#include <inttypes.h> //to provide def. for uint32_t
#endif
namespace MeshRender{
inline float reinterprete_uint32_as_float(uint32_t ival)
{
const float * p = reinterpret_cast<const float *>(&ival);
return *p;
}
//12-bit normal & 3-bit edge flags
uint32_t compress_normal(const float normf[3], const uint32_t edgeflags = 7);
void decompress_normal(uint32_t normi, float normf[3]);
}
#endif
|
7fdf117c212ff482d5920989a961fb2094913aab | fdf08b05ff4c660e183739dbc18009d0a9b8a49a | /OpenTESArena/src/Voxels/VoxelTextureDefinition.cpp | d249520d54575c510aaede1cb27cfb2636feeec7 | [
"MIT"
] | permissive | afritz1/OpenTESArena | f67c4f6ee8981ef3bffbfe5894e2b48d67554475 | 7e91599157e2b9268237b6689f691d29e89b1d74 | refs/heads/main | 2023-08-31T09:25:21.908575 | 2023-08-27T01:24:29 | 2023-08-27T01:24:29 | 50,629,945 | 942 | 100 | MIT | 2023-08-21T03:42:36 | 2016-01-29T02:07:08 | C++ | UTF-8 | C++ | false | false | 589 | cpp | VoxelTextureDefinition.cpp | #include "VoxelTextureDefinition.h"
#include "components/debug/Debug.h"
VoxelTextureDefinition::VoxelTextureDefinition()
{
this->textureCount = 0;
}
const TextureAsset &VoxelTextureDefinition::getTextureAsset(int index) const
{
DebugAssertIndex(this->textureAssets, index);
DebugAssert(index < this->textureCount);
return this->textureAssets[index];
}
void VoxelTextureDefinition::addTextureAsset(TextureAsset &&textureAsset)
{
DebugAssertIndex(this->textureAssets, this->textureCount);
this->textureAssets[this->textureCount] = std::move(textureAsset);
this->textureCount++;
}
|
0575cc6f573d3fbde25960ca3cce8da05c9a4cc3 | c07a5abb018c2be9d3d2500df3e33af59d7e7d69 | /Source/Twaliens/ProjectileA.h | 6b1b700fffe8d37ce0531062f92ce622555eaf42 | [] | no_license | Nekroarteriaa/TwaliensFinal | a9a4126215b04caf8ab2d3eddf1b1105b71e78ef | 2f41fa788da3d9125c499250a0e85a6d52cbeba1 | refs/heads/master | 2023-02-25T02:48:58.988462 | 2021-02-07T02:50:20 | 2021-02-07T02:50:20 | 336,685,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,856 | h | ProjectileA.h | // All rights reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Engine/Classes/Components/SphereComponent.h"
#include "Engine/Classes/GameFramework/ProjectileMovementComponent.h"
#include "Components/StaticMeshComponent.h"
#include "Interfaces/IPooledObject.h"
#include "ProjectileA.generated.h"
UCLASS()
class TWALIENS_API AProjectileA : public AActor, public IIPooledObject
{
GENERATED_BODY()
private:
FTimerHandle LifeTimeHanddle;
float LifeTime;
public:
// Sets default values for this actor's properties
AProjectileA();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
virtual void NotifyHit(class UPrimitiveComponent * MyComp, AActor * Other, class UPrimitiveComponent * OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalImpulse, const FHitResult & Hit) override;
//Sphere collision component
UPROPERTY(VisibleDefaultsOnly, Category = Projectile)
USphereComponent* CollisionComponent;
UPROPERTY(VisibleDefaultsOnly, Category = Projectile)
UStaticMeshComponent* MeshComp;
UPROPERTY(VisibleAnywhere, Category = Movement)
UProjectileMovementComponent* ProjectileMovementComponent;
UPROPERTY(EditAnywhere, Category = "Projectile Settings")
float damage;
UPROPERTY(EditAnywhere, Category = "Projectile Settings")
TArray<FName> AllowedTagsToDamage;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Function that initializes the projectile's velocity in the shoot direction.
UFUNCTION()
void FireInDirection(const FVector& ShootDirection);
UFUNCTION()
void AddAllowedTagsToDamage(FName TagName);
UFUNCTION()
void ResetAllowedTagsToDamage();
UFUNCTION()
virtual void OnObjectExitsPool() override;
UFUNCTION()
virtual void OnObjectEnterPool() override;
};
|
172679bb53febf175d1af8678903987221cfa834 | ccd9651e1d5ee1442d3b59cf86a6d889117a3454 | /Week2/BankAccount/Bank.cpp | 327e58a41b561c66fc2be37b8e227cd3786f1ff3 | [
"BSD-3-Clause"
] | permissive | AvansTi/TMTI-DATC-Voorbeelden | df35129a01129ad2345a998d872f55ed5d82a362 | 572d009ad9378228d125e4025bc0f9aa7763d053 | refs/heads/master | 2021-07-19T13:43:58.298192 | 2020-05-27T12:43:44 | 2020-05-27T12:43:44 | 173,193,158 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 767 | cpp | Bank.cpp | #include "Bankaccount.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
void addAccount(std::vector<Bankaccount>& accounts, const std::string& name, const std::string& number, int initVal) {
Bankaccount account{ name, number };
account.deposite(initVal);
accounts.push_back(account);
}
int main() {
std::vector<Bankaccount> accounts;
Bankaccount goossens = { "Goossens", "12345" };
goossens.deposite(1000.34);
accounts.emplace_back(goossens);
//accounts.push_back(goossens);
goossens.deposite(1000.34);
accounts.push_back(Bankaccount("Jansen", "23456"));
addAccount(accounts, "Jantje", "666", 2000);
//goossens.deposite(1000.34);
for (Bankaccount b : accounts) {
std::cout << b.toString() << std::endl;
}
}
|
a83525ce116d854cb3a4eb2d2d11a7c8a9fa540e | 9de0cec678bc4a3bec2b4adabef9f39ff5b4afac | /PWG/EMCAL/EMCALtasks/AliAodSkimTask.h | a89e59192f9c48291019d24ea48e56b17369c0c6 | [] | permissive | alisw/AliPhysics | 91bf1bd01ab2af656a25ff10b25e618a63667d3e | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | refs/heads/master | 2023-08-31T20:41:44.927176 | 2023-08-31T14:51:12 | 2023-08-31T14:51:12 | 61,661,378 | 129 | 1,150 | BSD-3-Clause | 2023-09-14T18:48:45 | 2016-06-21T19:31:29 | C++ | UTF-8 | C++ | false | false | 10,387 | h | AliAodSkimTask.h | #ifndef AliAodSkimTask_H
#define AliAodSkimTask_H
/// \class AliAodSkimTask
/// \brief Use to skim AOD files
///
/// Class to skim AOD files with the idea to keep the skimmed file as close as possible to the original AOD.
///
/// \author C.Loizides
#include <AliAnalysisTaskSE.h>
#include <TString.h>
class AliAODMCHeader;
class TH1F;
class AliAodSkimTask: public AliAnalysisTaskSE
{
public:
AliAodSkimTask(const char *name=0);
virtual ~AliAodSkimTask();
void SetCleanTracklets(Bool_t b) {fDoCleanTracklets=b;}
void SetCleanTracks(Bool_t b) {fDoCleanTracks=b;}
void SetClusMinE(Double_t v) {fClusMinE=v;}
void SetTrackMinPt(Double_t v) {fTrackMinPt=v;}
void SetTrackMaxPt(Double_t v) {fTrackMaxPt=v;}
void SetDoBothMinTrackAndClus(Bool_t b) {fDoBothMinTrackAndClus=b;}
void SetCopyCascades(Bool_t b) {fDoCopyCascades=b;}
void SetCopyCells(Bool_t b) {fDoCopyCells=b;}
void SetCopyClusters(Bool_t b) {fDoCopyClusters=b;}
void SetCopyConv(Bool_t b) {fDoCopyConv=b;}
void SetCopyDiMuons(Bool_t b) {fDoCopyDiMuons=b;}
void SetCopyHeader(Bool_t b) {fDoCopyHeader=b;}
void SetCopyMC(Bool_t b) {fDoCopyMC=b;}
void SetCopyMCHeader(Bool_t b) {fDoCopyMCHeader=b;}
void SetCopyKinks(Bool_t b) {fDoCopyKinks=b;}
void SetCopyPCells(Bool_t b) {fDoCopyPCells=b;}
void SetCopyPTrigger(Bool_t b) {fDoCopyPTrigger=b;}
void SetCopyTOF(Bool_t b) {fDoCopyTOF=b;}
void SetCopyTZERO(Bool_t b) {fDoCopyTZERO=b;}
void SetCopyTracklets(Bool_t b) {fDoCopyTracklets=b;}
void SetCopyTracks(Bool_t b) {fDoCopyTracks=b;}
void SetCopyTrdTracks(Bool_t b) {fDoCopyTrdTracks=b;}
void SetCopyTrigger(Bool_t b) {fDoCopyTrigger=b;}
void SetCopyV0s(Bool_t b) {fDoCopyV0s=b;}
void SetCopyUserTree(Bool_t b) {fDoCopyUserTree=b;}
void SetCopyVZERO(Bool_t b) {fDoCopyVZERO=b;}
void SetCopyVertices(Bool_t b) {fDoCopyVertices=b;}
void SetCopyZDC(Bool_t b) {fDoCopyZDC=b;}
void SetCutFilterBit(UInt_t b) {fCutFilterBit=b;}
void SetCutMcIsPrimary(Bool_t b) {fCutMcIsPrimary=b;}
void SetCutMcIsPhysicalPrimary(Bool_t b) {fCutMcIsPhysPrimary=b;}
void SetCutMcPt(Double_t pt) {fCutMcPt=pt;}
void SetCutMcY(Double_t y) {fCutMcY=y;}
void SetCutMcPhos(Bool_t b) {fCutMcPhos=b;}
void SetCutMcEmcal(Bool_t b) {fCutMcEmcal=b;}
void SetDoVertMain(Bool_t b) {fDoVertMain=b;}
void SetDoVertWoRefs(Bool_t b) {fDoVertWoRefs=b;}
void SetDoPhosFilter(Bool_t b) {fDoPhosFilt=b;}
void SetGammaBrName(TString s) {fGammaBr=s;}
void SetMinCutPt(Double_t pt) {fCutMinPt=pt;}
void SetRemCovMat(Bool_t b) {fDoRemCovMat=b;}
void SetRemPid(Bool_t b) {fDoRemPid=b;}
void SetRemoveMcParts(Bool_t b) {fDoRemoveMcParts=b;}
void SetRemoveTracks(Bool_t b) {fDoRemoveTracks=b;}
const char *Str() const;
protected:
virtual void CleanTrack(AliAODTrack *t);
const char *GetVersion() const { return "1.6"; }
virtual Bool_t KeepMcPart(AliAODMCParticle *p);
Bool_t IsDcalAcc(Double_t phi, Double_t eta);
Bool_t IsPhosAcc(Double_t phi, Double_t eta);
Bool_t IsEmcalAcc(Double_t phi, Double_t eta);
virtual Bool_t KeepTrack(AliAODTrack *t);
Bool_t PythiaInfoFromFile(const char *currFile, Float_t &xsec, Float_t &trials, Int_t &pthard);
virtual Bool_t SelectEvent();
void Terminate(Option_t* option);
void UserCreateOutputObjects();
void UserExec(Option_t* option);
Bool_t UserNotify();
virtual void CopyCascades();
virtual void CopyCells();
virtual void CopyCellsP();
virtual void CopyConv();
virtual void CopyClusters();
virtual void CopyDimuons();
virtual void CopyHeader();
virtual void CopyKinks();
virtual void CopyMc();
virtual void CopyMcHeader();
virtual void CopyTof();
virtual void CopyTracklets();
virtual void CopyTracks();
virtual void CopyTrdTracks();
virtual void CopyTrigger();
virtual void CopyTriggerP();
virtual void CopyTZero();
virtual void CopyUserTree();
virtual void CopyVertices();
virtual void CopyV0s();
virtual void CopyVZero();
virtual void CopyZdc();
virtual void CopyMore() {;}
Double_t fClusMinE; // minimum cluster energy to accept event
Double_t fTrackMinPt; // minimum track pt to accept event
Double_t fTrackMaxPt; // maximum track pt to accept event
Bool_t fDoBothMinTrackAndClus; // switch to enable simultaneous filtering for minimum track and cluster cuts
Double_t fCutMinPt; // minimum pT to keep track
UInt_t fCutFilterBit; // filter bit(s) to select
TString fGammaBr; // gamma branch name
Bool_t fDoCopyHeader; // if true copy header
Bool_t fDoCopyVZERO; // if true copy VZERO
Bool_t fDoCopyTZERO; // if true copy TZERO
Bool_t fDoCopyVertices; // if true copy vertices
Bool_t fDoCopyTOF; // if true copy TOF
Bool_t fDoCopyTracklets; // if true copy tracklets
Bool_t fDoCopyTracks; // if true copy tracks
Bool_t fDoRemoveTracks; // if true remove tracks
Bool_t fDoCleanTracks; // if true clean tracks
Bool_t fDoRemCovMat; // if true remove cov matrix from tracks
Bool_t fDoRemPid; // if true remove PID object from tracks
Bool_t fDoCopyTrigger; // if true copy trigger (EMC)
Bool_t fDoCopyPTrigger; // if true copy trigger (PHS)
Bool_t fDoCopyCells; // if true copy cells (EMC)
Bool_t fDoCopyPCells; // if true copy cells (PHS)
Bool_t fDoCopyClusters; // if true copy clusters
Bool_t fDoCopyDiMuons; // if true copy dimuons
Bool_t fDoCopyTrdTracks; // if true copy trd tracks
Bool_t fDoCopyV0s; // if true copy v0s
Bool_t fDoCopyCascades; // if true copy cascades
Bool_t fDoCopyZDC; // if true copy zdc
Bool_t fDoCopyConv; // if true copy conversions
Bool_t fDoCopyKinks; // if true copy kinks
Bool_t fDoCopyMC; // if true copy MC particles
Bool_t fDoCopyMCHeader; // if true copy MC header
Bool_t fDoVertWoRefs; // if true then do not copy TRefs in vertices
Bool_t fDoVertMain; // if true then only copy main vertices
Bool_t fDoCleanTracklets; // if true then clean tracklets
Bool_t fDoCopyUserTree; // if true copy input user tree
Bool_t fDoPhosFilt; // if true filter on phos (clusters and min energy cut)
Bool_t fDoRemoveMcParts; // if true remove mc particles
Bool_t fCutMcIsPrimary; // if true cut on primary mc particles
Bool_t fCutMcIsPhysPrimary; // if true cut on physical primary mc particles
Bool_t fCutMcPt; // if true cut on mc particles with pT<fCutMcPt
Bool_t fCutMcY; // if true cut on mc particles with |y|<fCutMcY
Bool_t fCutMcPhos; // if true cut particles not in PHOS
Bool_t fCutMcEmcal; // if true cut particles not in Emcal
UInt_t fTrials; //! events seen since last acceptance
Float_t fPyxsec; //! pythia xsection
Float_t fPytrials; //! pythia trials
Int_t fPypthardbin; //! pythia pthard bin
AliAODEvent *fAOD; //! input event
AliAODMCHeader *fAODMcHeader; //! MC header
TList *fOutputList; //! output list
TH1F *fHevs; //! events processed/accepted
TH1F *fHclus; //! cluster distribution
TH1F *fHtrack; //! track distribution
AliAodSkimTask(const AliAodSkimTask&); // not implemented
AliAodSkimTask& operator=(const AliAodSkimTask&); // not implemented
ClassDef(AliAodSkimTask, 10); // AliAodSkimTask
};
#endif
|
0b77d300c3226e90f9484dbf29c7a6ba63544038 | ad8271700e52ec93bc62a6fa3ee52ef080e320f2 | /CatalystRichPresence/CatalystSDK/Tool.h | 539f1c36f5611b1976bba0ce9de1ef3714458b29 | [] | no_license | RubberDuckShobe/CatalystRPC | 6b0cd4482d514a8be3b992b55ec143273b3ada7b | 92d0e2723e600d03c33f9f027c3980d0f087c6bf | refs/heads/master | 2022-07-29T20:50:50.640653 | 2021-03-25T06:21:35 | 2021-03-25T06:21:35 | 351,097,185 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | h | Tool.h | //
// Generated with FrostbiteGen by Chod
// File: SDK\Tool.h
// Created: Wed Mar 10 19:00:11 2021
//
#ifndef FBGEN_Tool_H
#define FBGEN_Tool_H
class Tool
{
public:
static void* GetTypeInfo()
{
return (void*)0x00000001427FC500;
}
unsigned char _0x0[0x18];
}; // size = 0x18
#endif // FBGEN_Tool_H
|
1c9f51213aba4a73896722fd54b95a281aab5263 | 3e60db9411ee906ca04e56c23a2d2bfb74089279 | /Karen and Morning.cpp | 0c309372cd0c696fd5d84a4395270885463af148 | [] | no_license | alexanderqchen/ICPC-Practice | e7632ff3dd0062019b430ac9a67cdb4238699d86 | 5e4a53e75e5d4ba3ad99a07fc2824b78c2e2a914 | refs/heads/master | 2020-04-05T13:08:14.007518 | 2017-09-28T22:57:07 | 2017-09-28T22:57:07 | 95,110,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | cpp | Karen and Morning.cpp | //http://codeforces.com/problemset/problem/816/A
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cin >> s;
int h = (s[0] - '0') * 10 + s[1] - '0';
int m = (s[3] - '0') * 10 + s[4] - '0';
int ans = 0;
while (h / 10 != m % 10 || h % 10 != m / 10)
{
ans++;
m++;
if (m >= 60)
{
m = 0;
h++;
}
if (h >= 24)
{
h = 0;
}
}
cout << ans << endl;
} |
96af7c6eb000c62878a7f3f843a57e85f01bb4fe | 18b5c416d59dd6a24a596fd65dcb06057bfd9095 | /sms/smsitem.h | c5fec430e50cd4bb4580aace8329db04868ec260 | [] | no_license | CMLDMR/SerikBLDCore | 3a62f1636763f71dd7fbbe51d185b0adfecfebf4 | b48d80231469454f7cb02553ff01306b34dc0a91 | refs/heads/master | 2023-04-30T19:24:41.086665 | 2023-04-17T08:31:40 | 2023-04-17T08:31:40 | 215,482,226 | 1 | 0 | null | 2023-04-17T08:31:42 | 2019-10-16T07:14:45 | C++ | UTF-8 | C++ | false | false | 3,012 | h | smsitem.h | #ifndef SMSITEM_H
#define SMSITEM_H
#include "Config.h"
#include "item.h"
#include <QByteArray>
#include <QXmlStreamWriter>
#include <iostream>
namespace SerikBLDCore {
namespace SMS {
static const std::string Collection{"SMSCollection"};
static const std::string sms{"sms"};
static const std::string numara{"telefon"};
static const std::string smsID{"smsid"};
static const std::string mSecStartDay{"mSecStartDay"};
static const std::string julianday{"julianDay"};
static const std::string raporKey{"rapor"};
static const std::string smsIDRapor{"smsidrapor"};
/**
* @brief The SMSItem class
* Gönderilecek SMS Item
*/
class SERIKBLDCORE_EXPORT SMSItem : public SerikBLDCore::Item
{
public:
explicit SMSItem( SMSItem* other = nullptr );
/**
* @brief SMSItem Copy Constructor
* @param other
*/
SMSItem( const SMSItem& other );
/**
* @brief SMSItem Move Constructor
* @param other
*/
SMSItem( SMSItem&& other );
/**
* @brief operator = Copy Assigment
* @param other
* @return
*/
SMSItem& operator=( const SMSItem& other );
/**
* @brief operator = Move Assignment
* @param other
* @return
*/
SMSItem& operator=( SMSItem&& other );
/**
* @brief setSMS SMS SetEder
* @param smsText
* @return
*/
SMSItem& setSMS( const QString &smsText );
/**
* @brief smsText SMS Geri Döndürür
* @return
*/
QString smsText() const;
/**
* @brief setNumara Numarayı Set Eder
* @param numaraText
* @return
*/
SMSItem& setNumara( const QString& numaraText );
/**
* @brief numaraText Numarayı Geri Döndürür
* @return
*/
QString numaraText() const;
/**
* @brief setID Gönderilen SMS ID'sini Set Eder
* @param smsIDText
* @return "ID:5445844"
*/
SMSItem& setID( const QString& smsIDText );
/**
* @brief idText Gönderilen SMS IDsini Geri Döndürür
* @return
*/
QString idText() const;
/**
* @brief setmSecStartOfDay Günün Başlangıcından itibaren olan Saniyeyi Set Eder
* @param mSecStartOfDay
* @return
*/
SMSItem& setmSecStartOfDay( const int& mSecStartOfDay );
/**
* @brief secStartOfDay Saniyeyi Geri Döndürür
* @return
*/
int secStartOfDay() const;
/**
* @brief setJulianDay Tarihi JulianDay Olarak Set Eder
* @param julianday
* @return
*/
SMSItem& setJulianDay( const int& julianday );
/**
* @brief julianDay Tarih JulianDay Olarak Geri Döndürür
* @return
*/
int julianDay() const;
SMSItem& setRapor( const QString &raporText);
QString rapor() const;
SMSItem& setRaporID( const int& id );
int raporID() const;
friend std::ostream& operator << (std::ostream& streamer, SMSItem& item);
friend std::ostream& operator << (std::ostream& streamer, const SMSItem& item);
};
}
}
#endif // SMSITEM_H
|
f66a3ac80213270bb5dfc256777bc3de206cf5b0 | 3a418573c80e7072c6b67a57df746326deb42a92 | /src/settingsoverrides.h | 13bdc20fe82c2d48ea0ede543dfb9acfccf58d21 | [] | no_license | 0branch/hugor | beaf25c164bc10fe24a36b2f5444f70c3b5da780 | 5271a71bca2f967c48f3af13c6814cc851fe22ff | refs/heads/master | 2021-01-16T20:05:32.596345 | 2013-06-18T04:08:06 | 2013-06-18T04:08:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | h | settingsoverrides.h | #ifndef SETTINGSOVERRIDES_H
#define SETTINGSOVERRIDES_H
#include <QString>
class SettingsOverrides {
public:
SettingsOverrides( const QString& filename );
QString appName;
QString authorName;
bool fullscreen;
int fullscreenWidth;
bool hideMenuBar;
int marginSize;
int propFontSize;
int fixedFontSize;
bool imageSmoothing;
bool pauseAudio;
};
#endif // SETTINGSOVERRIDES_H
|
7fe49b04117e4565e9acb4426838bcb7bc673e65 | 7b9f37b84695a85241a6a67ad156b1ef941f34ab | /Quest01/Quest01/Character.h | 7f3f1484f6638f5b561948c3088d3e1954f92b86 | [] | no_license | HyunOSung/PracticeProject | 4cda8e12523b065466af962609a91fd0c93a3446 | ed81fa6d450fe5262fb39e2fbef71f846d1d5496 | refs/heads/master | 2020-06-09T16:40:26.124593 | 2019-07-23T13:15:02 | 2019-07-23T13:15:02 | 193,469,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 80 | h | Character.h | #pragma once
class Character
{
public:
Character();
virtual ~Character();
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.