blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
fff68d2396e4a22c7005bf1f4c94a12972fdea9f
f274fd1e841945fa25751def67ade56889319534
/allegro5bitmap.cpp
101e682cf6bc3ea9a53ff5a87a3420615389be1a
[]
no_license
igorternyuk/TeAllegro5Pacman
fe42d5fcdf952658455b48dbf314b22d749764a2
8ce662f14edf7bd1fcfe075fe645f38e023e09c8
refs/heads/master
2021-09-14T04:09:35.776384
2018-05-08T07:32:46
2018-05-08T07:32:46
103,730,703
0
0
null
null
null
null
UTF-8
C++
false
false
618
cpp
#include "allegro5bitmap.hpp" Allegro5Bitmap::Allegro5Bitmap() {} bool Allegro5Bitmap::loadFromFile(const std::__cxx11::string &fileName) { mBitmap.reset(nullptr); auto bitmap = al_load_bitmap(fileName.c_str()); if(!bitmap) return false; my_unique_ptr<ALLEGRO_BITMAP> ptr {bitmap, al_destroy_bitmap}; mBitmap.swap(ptr); return true; } ALLEGRO_BITMAP *Allegro5Bitmap::get() const { return mBitmap.get(); } int Allegro5Bitmap::width() const { return al_get_bitmap_width(mBitmap.get()); } int Allegro5Bitmap::height() const { return al_get_bitmap_height(mBitmap.get()); }
cba5202fcbb3677d3994a73ff56c71822a8bc16e
012f0800c635f23d069f0c400768bc58cc1a0574
/hhvm/hhvm-3.17/hphp/zend/zend-html.h
56adb1de92be23205d034eafce689ba9e71a1b4f
[ "Zend-2.0", "BSD-3-Clause", "PHP-3.01" ]
permissive
chrispcx/es-hhvm
c127840387ee17789840ea788e308b711d3986a1
220fd9627b1b168271112d33747a233a91e8a268
refs/heads/master
2021-01-11T18:13:42.713724
2017-02-07T02:02:10
2017-02-07T02:02:10
79,519,670
5
0
null
null
null
null
UTF-8
C++
false
false
5,047
h
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1998-2010 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #ifndef incl_HPHP_ZEND_HTML_H_ #define incl_HPHP_ZEND_HTML_H_ #include <cstdint> // Avoid dragging in the icu namespace. #ifndef U_USING_ICU_NAMESPACE #define U_USING_ICU_NAMESPACE 0 #endif namespace HPHP { /////////////////////////////////////////////////////////////////////////////// /** * Major departures from Zend: * * 1. We are only supporting UTF-8 and ISO-8859-1 encoding. * Major reason for this is because the original get_next_char() bothers me, * sacrificing performance for some character sets that people rarely used * or that people shouldn't use. UTF-8 should really be the standard string * format everywhere, and we ought to write coding specifilized for it to * take full advantage of it: one example would be the new html encoding * function that simply do *p one a time iterating through the strings to * look for special characters for entity escaping. * * 2. HTML encoding function no longer encodes entities other than the basic * ones. There is no need to encode them, since all browsers support UTF-8 * natively, and we are ok to send out UTF-8 encoding characters without * turning them into printable ASCIIs. Basic entities are encoded for * a different reason! In fact, I personally don't see why HTML spec has * those extended list of entities, other than historical artifacts. * * 3. Double encoding parameter is not supported. That really sounds like * a workaround of buggy coding. I don't find a legit use for that yet. */ struct AsciiMap { uint64_t map[2]; }; enum StringHtmlEncoding { STRING_HTML_ENCODE_UTF8 = 1, STRING_HTML_ENCODE_NBSP = 2, STRING_HTML_ENCODE_HIGH = 4, STRING_HTML_ENCODE_UTF8IZE_REPLACE = 8 }; enum class EntBitmask { ENT_BM_NOQUOTES = 0, /* leave all quotes alone */ ENT_BM_SINGLE = 1, /* escape single quotes only */ ENT_BM_DOUBLE = 2, /* escape double quotes only */ ENT_BM_IGNORE = 4, /* silently discard invalid chars */ ENT_BM_SUBSTITUTE = 8, /* replace invalid chars with U+FFFD */ ENT_BM_XML1 = 16, /* XML1 mode*/ ENT_BM_XHTML = 32, /* XHTML mode */ }; namespace entity_charset_enum { enum entity_charset_impl { cs_terminator, cs_8859_1, cs_cp1252, cs_8859_15, cs_utf_8, cs_big5, cs_gb2312, cs_big5hkscs, cs_sjis, cs_eucjp, cs_koi8r, cs_cp1251, cs_8859_5, cs_cp866, cs_macroman, cs_unknown, cs_end }; } typedef entity_charset_enum::entity_charset_impl entity_charset; struct HtmlBasicEntity { unsigned short charcode; const char *entity; int entitylen; int flags; }; typedef const char *const entity_table_t; struct html_entity_map { entity_charset charset; /* charset identifier */ unsigned short basechar; /* char code at start of table */ unsigned short endchar; /* last char code in the table */ entity_table_t *table; /* the table of mappings */ }; const html_entity_map* html_get_entity_map(); /* * returns cs_unknown iff not found; * if input null, returns default charset of cs_utf_8 */ entity_charset determine_charset(const char*); char *string_html_encode(const char *input, int &len, const int64_t qsBitmask, bool utf8, bool dEncode, bool htmlEnt); char *string_html_encode_extra(const char *input, int &len, StringHtmlEncoding flags, const AsciiMap *asciiMap); /** * returns decoded string; * note, can return nullptr if the charset could not be detected * using the given charset_hint; can also pass in nullptr * for the charset_hint to use the default one (UTF-8). * (see determine_charset). */ char *string_html_decode(const char *input, int &len, bool decode_double_quote, bool decode_single_quote, const char *charset_hint, bool all, bool xhp = false ); /////////////////////////////////////////////////////////////////////////////// } #endif
0de50c2d37e11177e023b36599caf8a3ac4cc351
d20525bbd2603ab406bd607db90e54b7d8204bd4
/shore-mt/trunk/src/sm/sm_s.cpp
f3e2e1e7c77f2a6a2de975d68db57ed2a6624485
[ "LicenseRef-scancode-mit-old-style", "Spencer-94" ]
permissive
sunyangkobe/db_research
a2340bec6f26c701612b5e1a0c9e6020765ab837
67fce7500e6733a57f17fd2388cf29b9f9eafead
refs/heads/master
2020-03-27T05:41:17.409135
2013-12-01T18:16:27
2013-12-01T18:16:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,332
cpp
/* -*- mode:C++; c-basic-offset:4 -*- Shore-MT -- Multi-threaded port of the SHORE storage manager Copyright (c) 2007-2009 Data Intensive Applications and Systems Labaratory (DIAS) Ecole Polytechnique Federale de Lausanne All Rights Reserved. Permission to use, copy, modify and distribute this software and its documentation is hereby granted, provided that both the copyright notice and this permission notice appear in all copies of the software, derivative works or modified versions, and any portions thereof, and that both notices appear in supporting documentation. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. */ /*<std-header orig-src='shore'> $Id: sm_s.cpp,v 1.32 2010/07/01 00:08:22 nhall Exp $ SHORE -- Scalable Heterogeneous Object REpository Copyright (c) 1994-99 Computer Sciences Department, University of Wisconsin -- Madison All Rights Reserved. Permission to use, copy, modify and distribute this software and its documentation is hereby granted, provided that both the copyright notice and this permission notice appear in all copies of the software, derivative works or modified versions, and any portions thereof, and that both notices appear in supporting documentation. THE AUTHORS AND THE COMPUTER SCIENCES DEPARTMENT OF THE UNIVERSITY OF WISCONSIN - MADISON ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION, AND THEY DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. This software was developed with support by the Advanced Research Project Agency, ARPA order number 018 (formerly 8230), monitored by the U.S. Army Research Laboratory under contract DAAB07-91-C-Q518. Further funding for this work was provided by DARPA through Rome Research Laboratory Contract No. F30602-97-2-0247. */ #include "w_defines.h" /* -- do not edit anything above this line -- </std-header>*/ #define SM_SOURCE #ifdef __GNUG__ #pragma implementation "sm_s.h" #endif #include <sm_int_0.h> #include <w_strstream.h> #include <stdio.h> const rid_t rid_t::null; const lpid_t lpid_t::bof; const lpid_t lpid_t::eof; const lpid_t lpid_t::null; // debug pretty-print of an lsn -- used in debugger char const* db_pretty_print(lsn_t const* lsn, int /*i=0*/, char const* /* s=0 */) { char *tmp = (char *) ::valloc(100); snprintf(tmp, sizeof(tmp), "%d.%lld", lsn->hi(), (long long int)(lsn->lo())); return tmp; } #include <atomic_templates.h> /* This function makes an atomic copy of the lsn passed to it. To prove correctness, we need to show that all possible interleavings result in us returning a valid lsn. Note that we always access hi before lo. There are four possible results: correct (.), conflict (!), or incorrect (x) Read: H L H ================================================================== Write: . HL ! HL * HL . HL . H L * H L * H L . H L * H L x H L If we only write each value once there is one corner case that sneaks through. So, we need to add a step in the protocol: the writer will always set H to a sentinel value before changing L, then set H to its new proper value afterward. Read H L H ================================================================== Write: . HLH s HL H s HL H s HL H s H LH s H L H s H L H s H LH s H L H s H LH ! HLH ! HL H ! HL H ! H LH ! H L H ! H LH ! HLH ! HL H ! H LH . HLH */ bool lpid_t::valid() const { #if W_DEBUG_LEVEL > 2 // try to stomp out uses of this function if(_stid.vol.vol && ! page) w_assert3(0); #endif return _stid.vol.vol != 0; } /********************************************************************* * * key_type_s: used in btree manager interface and stored * in store descriptors * ********************************************************************/ w_rc_t key_type_s::parse_key_type( const char* s, uint4_t& count, key_type_s kc[]) { w_istrstream is(s); uint j; for (j = 0; j < count; j++) { kc[j].variable = 0; if (! (is >> kc[j].type)) { if (is.eof()) break; return RC(smlevel_0::eBADKEYTYPESTR); } if (is.peek() == '*') { // Variable-length keys look like: // ... b*<max> if (! (is >> kc[j].variable)) return RC(smlevel_0::eBADKEYTYPESTR); } if (! (is >> kc[j].length)) return RC(smlevel_0::eBADKEYTYPESTR); if (kc[j].length > key_type_s::max_len) return RC(smlevel_0::eBADKEYTYPESTR); switch (kc[j].type) { case key_type_s::I: // signed compressed case key_type_s::U: // unsigned compressed kc[j].compressed = true; // drop down case key_type_s::i: case key_type_s::u: if ( (kc[j].length != 1 && kc[j].length != 2 && kc[j].length != 4 && kc[j].length != 8 ) || kc[j].variable) return RC(smlevel_0::eBADKEYTYPESTR); break; case key_type_s::F: // float compressed kc[j].compressed = true; // drop down case key_type_s::f: if ((kc[j].length != 4 && kc[j].length != 8) || kc[j].variable) return RC(smlevel_0::eBADKEYTYPESTR); break; case key_type_s::B: // uninterpreted bytes, compressed kc[j].compressed = true; // drop down case key_type_s::b: // uninterpreted bytes w_assert3(kc[j].length > 0); break; default: return RC(smlevel_0::eBADKEYTYPESTR); } } count = j; for (j = 0; j < count; j++) { if (kc[j].variable && j != count - 1) return RC(smlevel_0::eBADKEYTYPESTR); } return RCOK; } w_rc_t key_type_s::get_key_type( char* s, // out int buflen, // in uint4_t count, // in const key_type_s* kc) // in { w_ostrstream o(s, buflen); uint j; char c; for (j = 0; j < count; j++) { if(o.fail()) break; switch (kc[j].type) { case key_type_s::I: // compressed int c = 'I'; break; case key_type_s::i: c = 'i'; break; case key_type_s::U: // compressed unsigned int c = 'U'; break; case key_type_s::u: c = 'u'; break; case key_type_s::F: // compressed float c = 'F'; break; case key_type_s::f: c = 'f'; break; case key_type_s::B: // uninterpreted bytes, compressed c = 'B'; break; case key_type_s::b: // uninterpreted bytes c = 'b'; break; default: return RC(smlevel_0::eBADKEYTYPESTR); } o << c; if(kc[j].variable) o << '*'; o << kc[j].length; } o << ends; if(o.fail()) return RC(smlevel_0::eRECWONTFIT); return RCOK; }
846344dc36769ce59593e8504fbc04069490edc0
23c7378bcb47d429f4519f9b2317d6ebe29b7297
/Arduino/Serial_Test/Serial_Test.ino
f16db50844934b0d5945892a4714357c18e78c53
[ "Apache-2.0" ]
permissive
stlcours/GhostPassword
0aaf0f4ab59dd76bfea7cee060c6be25bc2fcd72
a7fc49d1e6840b461b54a62386de3713215e4ace
refs/heads/master
2023-07-06T01:46:12.048280
2015-11-24T02:49:36
2015-11-24T02:49:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
746
ino
#include <SoftwareSerial.h> //#define HWSERIAL Serial1 SoftwareSerial test(0,1); void setup() { Serial.begin(115200); test.begin(115200); test.print("$"); test.print("$"); test.print("$"); } void loop() { int incomingByte; if (Serial.available() > 0) { incomingByte = (char)Serial.read(); Serial.print("USB received: "); Serial.println((char)incomingByte, DEC); test.print("USB received:"); test.println(incomingByte, DEC); } if (test.available() > 0) { incomingByte = test.read(); Serial.print("UART received: "); Serial.println(incomingByte); test.print("UART received:"); test.println(incomingByte, DEC); } }
8bad104c9c5801f09e4e9ac8a258b8b8ede890c4
3e96aaeb2130482e7d75f872144a745e1af472ef
/2015 Nov/Long Challenge/KFUNC/main.cpp
8b6f51cd5509f61bf9771c72e63e1e301a369a11
[]
no_license
Shadek07/codechef
08f499a1c73a4e9f93d878eb3a82e48b207cd8e5
673a829a52fee9995afe07fffbd565cca15288ff
refs/heads/master
2022-08-02T11:02:44.132500
2016-12-15T05:56:21
2016-12-15T05:56:21
265,459,241
1
0
null
null
null
null
UTF-8
C++
false
false
2,522
cpp
#pragma comment(linker,"/STACK:16777216") #pragma warning ( disable: 4786) #include<iostream> #include<cstring> #include<cstdio> #include<vector> #include<map> #include<set> #include<string> #include<cmath> #include<cstdlib> #include<cctype> #include<algorithm> #include<queue> #include<sstream> #include<stack> #include<list> #include <bitset> #include<iomanip> #include <fstream> #include<ctime> #include<climits> using namespace std; #define max(x,y) ((x)>(y)?(x):(y)) #define min(x,y) ((x)<(y)?(x):(y)) #define MX 1000000 #define forl(i,a,b) for ( i = a; i < b; i++) #define fore(i,a,b) for ( i = a; i <= b; i++) #define forrev(i,a,b) for ( i = a; i >= b; i--) #define pb push_back typedef long long LL; #define in(a,b,c) ((a) <= (b) && (b) <= (c)) #define ms(a,b) memset((a),(b),sizeof(a)) #define all(v) (v).begin(),(v).end() #define pb push_back #define ull unsigned long long int typedef vector<int> vi; typedef pair<int,int> pii; typedef vector<pii> vpii; string to_string(long long x) { stringstream ss; ss << x; return ss.str(); } long long to_int(const string &s) { stringstream ss; ss << s; long long x; ss >> x; return x; } #define MAX 100005 int f(int a){ if(a < 10) return a; else { int sum=0; while(a){ sum += a%10; a /= 10; } return f(sum); } } int main(void) { //freopen("1.txt", "r", stdin); //freopen("2.txt", "w", stdout); int t=20; unsigned long long int A,D,L,R; ull a,b,c,i,j,sum; ull ans; cin >> t; bool vis[11]; ull prefix[11]; //cout << ULLONG_MAX << endl; (resolution ( ((A)(B C) ) ((B)() ) ((C)() ) ) ) (loop for (x) in ( ((C D)(A)) ((A D E)()) (()(A C)) (()(D)) (()(E)) ) collect (list x) ) while(t--){ scanf("%llu %llu %llu %llu",&A, &D, &L, &R); a = A + (((L-1)%9)*(D%9))%9; b = a%9; ms(vis,0); if(b==0) b = 9; //cout << b << endl; vis[b]=true; prefix[0] = 0; prefix[1] = b; sum = b; c = 1; forl(i,0,R-L){ a = a + D; b = a%9; if(b == 0) b = 9; if(vis[b]){ break; } //cout << b << endl; sum += b; c++; vis[b] = true; prefix[c] = prefix[c-1] + b; } ull t = (R-L+1)/c; ull r = (R-L+1)%c; ans = t*sum + prefix[r]; cout << ans << endl; } return 0; }
839235c60af59df1a816137a82fdde1cfe604249
37c63be12437ffa82ee7a193be719235e041257e
/Client/include/Input/EventDetails.hpp
3ab7e9c87f700a8bd403c791bdc484cb1eae8708
[]
no_license
Sadzka/Arikazike-Project
b9441ba7f77095659378fb2ea4911fc92dd71db1
13583bc00700c73295c7e3618eca5b10e675a61a
refs/heads/master
2020-06-03T03:33:01.215192
2019-12-16T18:28:38
2019-12-16T18:28:38
191,419,448
0
0
null
null
null
null
UTF-8
C++
false
false
521
hpp
#pragma once #include <string> #include <SFML/Graphics.hpp> struct EventDetails { EventDetails(const std::string& bindName) : m_name(bindName) { clear(); } std::string m_name; sf::Vector2i m_size; sf::Uint32 m_textEntered; sf::Vector2i m_mouse; int m_mouseWheelDelta; int m_keyCode; // Single key code. void clear() { m_size = sf::Vector2i(0, 0); m_textEntered = 0; m_mouse = sf::Vector2i(0, 0); m_mouseWheelDelta = 0; m_keyCode = -1; } };
ec2596bb9ec0e42d94bdf2208cea46170af55daa
5d9f13a8ef3f8e078dcf39e00b473c4d92574475
/config.hpp
75fb987b088f5363a900c062b207edd0766b3cbc
[]
no_license
nlegoff/my-rest-sql
10012454ba49b111c96e5242da2abb80e88f5682
a45d2abad931f351b76ae65bf832102aad2413fd
refs/heads/master
2021-01-19T18:30:19.825367
2012-07-29T03:39:39
2012-07-29T03:39:39
5,219,395
1
0
null
null
null
null
UTF-8
C++
false
false
531
hpp
#ifndef CONFIG_HPP_INCLUDED #define CONFIG_HPP_INCLUDED ///Define backend stockage system //#define STOCKAGE "mysql" #define STOCKAGE "filesystem" ///Define http server properties #define HTTP_SERVER_ADRESS "127.0.0.1" #define HTTP_SERVER_PORT "8787" #define HTTP_SERVER_DOCUMENT_ROOT "/home/nicolas/workspace/my-rest-sql/tests/server1/document_root" ///Define mysql server properties #define MYSQL_SERVER_ADRESS "localhost" #define MYSQL_SERVER_USER "root" #define MYSQL_SERVER_PASS "Nicolas78" #endif // CONFIG_HPP_INCLUDED
014d2c2b9e8cf61a12d1b20e27ca30faddb169cc
86aa59218c6298e8f1c28b60c3274452be3bdea8
/alpaca/asset.h
99f6d94bd8208a96dc5dfcbe64881d945e4c80c5
[ "MIT" ]
permissive
kzhdev/alpaca-trade-api-cpp
92a8d92ae62f5fb1d0a685c03d8d0690d4e2b4fa
ab2190e318a740e6a6a00b548ac65849beb2e29b
refs/heads/master
2023-08-29T11:55:28.026042
2023-08-13T01:33:14
2023-08-13T01:33:14
298,900,266
1
0
MIT
2020-09-26T21:11:55
2020-09-26T21:11:55
null
UTF-8
C++
false
false
833
h
#pragma once #include <string> #include "alpaca/status.h" namespace alpaca { /** * @brief The class of an asset. */ enum AssetClass { USEquity, }; /** * @brief A helper to convert an AssetClass to a string */ std::string assetClassToString(const AssetClass asset_class); /** * @brief A type representing an Alpaca asset. */ class Asset { public: /** * @brief A method for deserializing JSON into the current object state. * * @param json The JSON string * * @return a Status indicating the success or faliure of the operation. */ Status fromJSON(const std::string& json); public: std::string asset_class; bool easy_to_borrow; std::string exchange; std::string id; bool marginable; bool shortable; std::string status; std::string symbol; bool tradable; }; } // namespace alpaca
4bc5d9533f8bfc7fbf811ebd5cdb54e4fee07a7b
846a7668ac964632bdb6db639ab381be11c13b77
/android/hardware/aw/gpu/mali-midgard/gralloc/src/gralloc_vsync_s3cfb.cpp
434e685b37c3bcabedfd879be85de539a0781398
[]
no_license
BPI-SINOVOIP/BPI-A64-Android8
f2900965e96fd6f2a28ced68af668a858b15ebe1
744c72c133b9bf5d2e9efe0ab33e01e6e51d5743
refs/heads/master
2023-05-21T08:02:23.364495
2020-07-15T11:27:51
2020-07-15T11:27:51
143,945,191
2
0
null
null
null
null
UTF-8
C++
false
false
1,902
cpp
/* * Copyright (C) 2014 ARM Limited. All rights reserved. * * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gralloc_priv.h" #include "gralloc_vsync.h" #include "gralloc_vsync_report.h" #include <sys/ioctl.h> #include <errno.h> #define FBIO_WAITFORVSYNC _IOW('F', 0x20, __u32) #define S3CFB_SET_VSYNC_INT _IOW('F', 206, unsigned int) int gralloc_vsync_enable(framebuffer_device_t *dev) { private_module_t *m = reinterpret_cast<private_module_t *>(dev->common.module); int interrupt = 1; if (ioctl(m->framebuffer->fd, S3CFB_SET_VSYNC_INT, &interrupt) < 0) { return -errno; } return 0; } int gralloc_vsync_disable(framebuffer_device_t *dev) { private_module_t *m = reinterpret_cast<private_module_t *>(dev->common.module); int interrupt = 0; if (ioctl(m->framebuffer->fd, S3CFB_SET_VSYNC_INT, &interrupt) < 0) { return -errno; } return 0; } int gralloc_wait_for_vsync(framebuffer_device_t *dev) { private_module_t *m = reinterpret_cast<private_module_t *>(dev->common.module); if (m->swapInterval) { int crtc = 0; gralloc_mali_vsync_report(MALI_VSYNC_EVENT_BEGIN_WAIT); if (ioctl(m->framebuffer->fd, FBIO_WAITFORVSYNC, &crtc) < 0) { gralloc_mali_vsync_report(MALI_VSYNC_EVENT_END_WAIT); return -errno; } gralloc_mali_vsync_report(MALI_VSYNC_EVENT_END_WAIT); } return 0; }
b66acf0bfcb1824243df3cc97f18bc6949fda951
075902fe1092367d8723bd3d0f93fd5e8303f69a
/src/SDK/core/include/common/FCMMacros.h
3c914674905e907842afa2f745adbd4d0131a2ca
[]
no_license
pbalmasov/pixi-animate-extension
39ec2a87adc4ed9e4a4075302577862666bd1556
80c05251456a225db276d3e98092c62f74459424
refs/heads/master
2021-01-19T09:56:46.278126
2020-03-16T12:39:30
2020-03-16T12:39:30
82,153,175
1
0
null
2017-02-16T07:37:35
2017-02-16T07:37:35
null
UTF-8
C++
false
false
10,090
h
/****************************************************************************** * ADOBE CONFIDENTIAL * ___________________ * * Copyright [2013] Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Adobe Systems Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Adobe Systems Incorporated and its * suppliers and are protected by all applicable intellectual * property laws, including trade secret and copyright laws. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Adobe Systems Incorporated. ******************************************************************************/ /** * @file FCMMacros.h * * @brief This file contains the macros used in FCM. */ #ifndef FCM_MACROS_H_ #define FCM_MACROS_H_ #include "FCMPreConfig.h" /* -------------------------------------------------- Forward Decl */ /* -------------------------------------------------- Enums */ /* -------------------------------------------------- Macros / Constants */ namespace FCM { /** * @def FCM_VERSION_MAJOR * * @brief Major version of the framework. */ #define FCM_VERSION_MAJOR 0x01 /** * @def FCM_VERSION_MINOR * * @brief Minor version of the framework. */ #define FCM_VERSION_MINOR 0x02 /** * @def FCM_VERSION_MAINTENANCE * * @brief Maintenance number of the framework. */ #define FCM_VERSION_MAINTENANCE 0x00 /** * @def FCM_VERSION_BUILD * * @brief Build number of the framework. */ #define FCM_VERSION_BUILD 0x00 /** * @def FCM_VERSION * * @brief Complete version of the framework. */ #define FCM_VERSION ((FCM_VERSION_MAJOR << 24) | (FCM_VERSION_MINOR << 16) | \ (FCM_VERSION_MAINTENANCE << 8) | (FCM_VERSION_BUILD)) /** * @def DEFINE_FCMIID * * @brief Defines interface with name @a name and ID whose textual representation is * @a l - @a w1 - @a w2 - @a b1 @a b2 - @a b3 @a b4 @a b5 @a b6 @a b7 @a b8. */ #define DEFINE_FCMIID (name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ const FCMID name = {l, w1, w2, {b1, b2, b3, b4, b5, b6, b7, b8}} /** * @def IID * * @brief Utility macro to define interface ID easily. */ #define IID(ifx) IID_##ifx /** * @def _FCM_SIMPLEMAPENTRY * * @brief This macro makes debugging asserts easier. */ #define _FCM_SIMPLEMAPENTRY ((_FCM_CREATORARGFUNC*)0) /** * @def FORWARD_DECLARE_INTERFACE * * @brief Used to forward declare an interface @a ifx. */ #define FORWARD_DECLARE_INTERFACE(ifx) \ class ifx; \ typedef ifx* P##ifx; /** * @def BEGIN_DECLARE_INTERFACE_COMMON * * @brief Used to begin any interface @a ifx with ID @a iid. */ #define BEGIN_DECLARE_INTERFACE_COMMON(ifx, iid) \ FORWARD_DECLARE_INTERFACE(ifx) \ const FCM::FCMIID IID_##ifx = (iid); \ using namespace FCM; /** * @def BEGIN_DECLARE_INTERFACE_INHERIT * * @brief Used to begin the interface @a ifx with ID @a iid , which inherits from @a baseifx. */ #define BEGIN_DECLARE_INTERFACE_INHERIT(ifx, iid, baseifx) \ BEGIN_DECLARE_INTERFACE_COMMON (ifx, iid) \ class ifx : public baseifx { public: inline static FCM::FCMIID GetIID() {return IID(ifx);} /** * @def BEGIN_DECLARE_INTERFACE * * @brief Used to begin the interface @a ifx with ID @a iid, which inherits from IFCMUnknown. */ #define BEGIN_DECLARE_INTERFACE(ifx, iid) BEGIN_DECLARE_INTERFACE_INHERIT(ifx, iid, FCM::IFCMUnknown); /** * @def BEGIN_DECLARE_BASE_INTERFACE * * @brief Used to begin the interface @a ifx with ID @a iid, which inherits from IFCMUnknown. */ #define BEGIN_DECLARE_BASE_INTERFACE(ifx, iid) \ BEGIN_DECLARE_INTERFACE_COMMON (ifx, iid) \ class ifx { public: inline static FCM::FCMIID GetIID() {return IID(ifx);} /** * @def END_DECLARE_INTERFACE * * @brief Ends an interface. */ #define END_DECLARE_INTERFACE }; /** * @def _FCMCALL * * @brief Defines calling convention for interface methods. */ #if defined(__GNUC__) #define _FCMCALL #else #define _FCMCALL __stdcall #endif /** * @def FCM_ADDREF * * @brief If @a intPtr exists, increment its reference count. */ #define FCM_ADDREF(intPtr) if(intPtr){(intPtr)->AddRef();} /** * @def FCM_RELEASE * * @brief If @a intPtr exists, decrement its reference count. */ #define FCM_RELEASE(intPtr) if(intPtr){(intPtr)->Release();(intPtr)=0;} /** * @def _FCM_PACKING * * @brief Used for internal purpose. */ #define _FCM_PACKING 1 /** * @def offsetofclass * * @brief Utility macro to get offset of a derived class. Used for internal purposes. */ #define offsetofclass(base, derived) \ ((FCM::S_Int64)(static_cast<base*>((derived*)_FCM_PACKING))-_FCM_PACKING) /** * @def offsetofclasscustom * * @brief Custom Class offset. Used for internal purposes. */ #define offsetofclasscustom(base,custom, derived) \ ((FCM::S_Int64)(static_cast<base*>((custom*)((derived*)_FCM_PACKING)))-_FCM_PACKING) /** * @def offsetofmem * * @brief Memory Offset */ #define offsetofmem(m,s) \ (FCM::S_Int64)&(((s *)0)->m) /** * @def BEGIN_INTERFACE_MAP * * @brief Format to begin Interface map. */ #define BEGIN_INTERFACE_MAP(impl,implVersion) \ public: \ virtual FCM::PIFCMCallback GetCallback()=0; \ typedef impl _ClassImpl; \ static FCM::U_Int32 GetVersion(){ return (FCM::U_Int32)implVersion;} \ static FCM::FCMInterfaceMap* GetInterfaceMap() \ { static FCM::FCMInterfaceMap _pInterfaceMap [] ={ \ INTERFACE_ENTRY(IFCMUnknown) /** * @def BEGIN_MULTI_INTERFACE_MAP * * @brief Format to Begin multi-interface map. This should be used if a implementation * class is inheriting from multiple interfaces. */ #define BEGIN_MULTI_INTERFACE_MAP(impl,implVersion) \ public: \ virtual FCM::PIFCMCallback GetCallback()=0; \ typedef impl _ClassImpl; \ static FCM::U_Int32 GetVersion(){ return (FCM::U_Int32)implVersion;} \ static FCM::FCMInterfaceMap* GetInterfaceMap() \ { static FCM::FCMInterfaceMap _pInterfaceMap [] ={ /** * @def INTERFACE_ENTRY * * @brief Add an interface. */ #define INTERFACE_ENTRY(ifx) \ {IID(ifx),offsetofclass(ifx,_ClassImpl),_FCM_SIMPLEMAPENTRY}, /** * @def INTERFACE_ENTRY_CUSTOM * * @brief Add custom interface. Used to avoid the "diamond problem" of * multiple inheritance. */ #define INTERFACE_ENTRY_CUSTOM(ifx,custom) \ {IID(ifx),offsetofclasscustom(ifx,custom,_ClassImpl),_FCM_SIMPLEMAPENTRY}, /** * @def INTERFACE_ENTRY_AGGREGATE * * @brief Add interface with aggregration. */ #define INTERFACE_ENTRY_AGGREGATE(ifx, punk)\ {IID(ifx),offsetofmem(punk,_ClassImpl),_Delegate}, /** * @def END_INTERFACE_MAP * * @brief Format to end the interface map. */ #define END_INTERFACE_MAP \ {FCM::FCMIID_NULL,0,_FCM_SIMPLEMAPENTRY}}; \ return _pInterfaceMap;} /** * @def BEGIN_MODULE * * @brief Format to mark the beginning of a module. A module contains a list of class map with name @a ursModule. */ #define BEGIN_MODULE(usrModule) \ class usrModule : public FCM::FCMPluginModule { /** * @def BEGIN_CLASS_ENTRY * * @brief Format to mark the begining of class map. */ #define BEGIN_CLASS_ENTRY \ public: \ FCM::Result init(FCM::PIFCMCallback pCallback) { FCM::Result res = FCMPluginModule::init(pCallback); /** * @def CLASS_ENTRY * * @brief Add class entry with class id @a clsid and classobject @a ursClass to classFactory. */ #define CLASS_ENTRY(clsid,ursClass) \ addClassEntry(clsid,&FCMClassFactory<ursClass>::GetFactory,&ursClass::GetInterfaceMap,ursClass::GetVersion()); /** * @def END_CLASS_ENTRY * * @brief Format to mark the end of a class map. */ #define END_CLASS_ENTRY return res; } /** * @def END_MODULE * * @brief Format to end the module. */ #define END_MODULE }; /** * @def DllExport * * @brief Used to export a function from a plugin */ #if defined(__GNUC__) #ifndef DllExport #define DllExport __attribute__((visibility("default"))) #endif #else #ifndef DllExport #define DllExport __declspec( dllexport ) #endif #endif /** * @def FCMPLUGIN_IMP_EXP * * @brief Used to export a function from the plugin. */ #if defined( __FCM_INTERNAL_PLUGIN__) #define FCMPLUGIN_IMP_EXP #else #define FCMPLUGIN_IMP_EXP DllExport #endif //__FCM_INTERNAL_PLUGIN__ }; /* -------------------------------------------------- Structs / Unions */ /* -------------------------------------------------- Class Decl */ /* -------------------------------------------------- Inline / Functions */ #include "FCMPostConfig.h" #endif //FCM_MACROS_H_
b88fe942ba993dc2d6bc0158f8f8169cefc2bb65
776be28110aeb3c9cb53c58383c964c11e11a8eb
/src/base58.h
49153f744b9efee0372ff1a38d3d18d19f31f1dc
[ "MIT" ]
permissive
mybittask/testylgc
8aac183016759de6d1c9c7cf0f7ef1786e96c18e
73cf70ae4e8fb2b36277c2d877aa0204e3f6450d
refs/heads/master
2021-09-10T20:31:41.089348
2018-04-01T20:22:58
2018-04-01T20:22:58
114,807,053
0
0
null
null
null
null
UTF-8
C++
false
false
13,014
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Why base-58 instead of standard base-64 encoding? // - Don't want 0OIl characters that look the same in some fonts and // could be used to create visually identical looking account numbers. // - A string with non-alphanumeric characters is not as easily accepted as an account number. // - E-mail usually won't line-break if there's no punctuation to break at. // - Double-clicking selects the whole number as one word if it's all alphanumeric. // #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H #include <string> #include <vector> #include "bignum.h" #include "key.h" #include "script.h" #include "allocators.h" static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // Encode a byte sequence as a base58-encoded string inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { CAutoBN_CTX pctx; CBigNum bn58 = 58; CBigNum bn0 = 0; // Convert big endian data to little endian // Extra zero at the end make sure bignum will interpret as a positive number std::vector<unsigned char> vchTmp(pend-pbegin+1, 0); reverse_copy(pbegin, pend, vchTmp.begin()); // Convert little endian data to bignum CBigNum bn; bn.setvch(vchTmp); // Convert bignum to std::string std::string str; // Expected size increase from base58 conversion is approximately 137% // use 138% to be safe str.reserve((pend - pbegin) * 138 / 100 + 1); CBigNum dv; CBigNum rem; while (bn > bn0) { if (!BN_div(&dv, &rem, &bn, &bn58, pctx)) throw bignum_error("EncodeBase58 : BN_div failed"); bn = dv; unsigned int c = rem.getulong(); str += pszBase58[c]; } // Leading zeroes encoded as base58 zeros for (const unsigned char* p = pbegin; p < pend && *p == 0; p++) str += pszBase58[0]; // Convert little endian std::string to big endian reverse(str.begin(), str.end()); return str; } // Encode a byte vector as a base58-encoded string inline std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } // Decode a base58-encoded string psz into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet) { CAutoBN_CTX pctx; vchRet.clear(); CBigNum bn58 = 58; CBigNum bn = 0; CBigNum bnChar; while (isspace(*psz)) psz++; // Convert big endian string to bignum for (const char* p = psz; *p; p++) { const char* p1 = strchr(pszBase58, *p); if (p1 == NULL) { while (isspace(*p)) p++; if (*p != '\0') return false; break; } bnChar.setulong(p1 - pszBase58); if (!BN_mul(&bn, &bn, &bn58, pctx)) throw bignum_error("DecodeBase58 : BN_mul failed"); bn += bnChar; } // Get bignum as little endian data std::vector<unsigned char> vchTmp = bn.getvch(); // Trim off sign byte if present if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) vchTmp.erase(vchTmp.end()-1); // Restore leading zeros int nLeadingZeros = 0; for (const char* p = psz; *p == pszBase58[0]; p++) nLeadingZeros++; vchRet.assign(nLeadingZeros + vchTmp.size(), 0); // Convert little endian data to big endian reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size()); return true; } // Decode a base58-encoded string str into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } // Encode a byte vector to a base58-encoded string, including checksum inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet)) return false; if (vchRet.size() < 4) { vchRet.clear(); return false; } uint256 hash = Hash(vchRet.begin(), vchRet.end()-4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size()-4); return true; } // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } /** Base class for all base58-encoded data */ class CBase58Data { protected: // the version byte unsigned char nVersion; // the actually encoded data typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar; vector_uchar vchData; CBase58Data() { nVersion = 0; vchData.clear(); } void SetData(int nVersionIn, const void* pdata, size_t nSize) { nVersion = nVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend) { SetData(nVersionIn, (void*)pbegin, pend - pbegin); } public: bool SetString(const char* psz) { std::vector<unsigned char> vchTemp; DecodeBase58Check(psz, vchTemp); if (vchTemp.empty()) { vchData.clear(); nVersion = 0; return false; } nVersion = vchTemp[0]; vchData.resize(vchTemp.size() - 1); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[1], vchData.size()); OPENSSL_cleanse(&vchTemp[0], vchData.size()); return true; } bool SetString(const std::string& str) { return SetString(str.c_str()); } std::string ToString() const { std::vector<unsigned char> vch(1, nVersion); vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CompareTo(const CBase58Data& b58) const { if (nVersion < b58.nVersion) return -1; if (nVersion > b58.nVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded Bitcoin addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress; class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress *addr; public: CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const; bool operator()(const CScriptID &id) const; bool operator()(const CNoDestination &no) const; }; class CBitcoinAddress : public CBase58Data { public: enum { PUBKEY_ADDRESS = 48, // logicrypt addresses start with L SCRIPT_ADDRESS = 5, PUBKEY_ADDRESS_TEST = 111, SCRIPT_ADDRESS_TEST = 196, }; bool Set(const CKeyID &id) { SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20); return true; } bool Set(const CScriptID &id) { SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20); return true; } bool Set(const CTxDestination &dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool IsValid() const { unsigned int nExpectedSize = 20; bool fExpectTestNet = false; switch(nVersion) { case PUBKEY_ADDRESS: nExpectedSize = 20; // Hash of public key fExpectTestNet = false; break; case SCRIPT_ADDRESS: nExpectedSize = 20; // Hash of CScript fExpectTestNet = false; break; case PUBKEY_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; case SCRIPT_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize; } CBitcoinAddress() { } CBitcoinAddress(const CTxDestination &dest) { Set(dest); } CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); } CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const { if (!IsValid()) return CNoDestination(); switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CKeyID(id); } case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CScriptID(id); } } return CNoDestination(); } bool GetKeyID(CKeyID &keyID) const { if (!IsValid()) return false; switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } default: return false; } } bool IsScript() const { if (!IsValid()) return false; switch (nVersion) { case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { return true; } default: return false; } } }; bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; } /** A base58-encoded secret key */ class CBitcoinSecret : public CBase58Data { public: enum { PRIVKEY_ADDRESS = CBitcoinAddress::PUBKEY_ADDRESS + 128, PRIVKEY_ADDRESS_TEST = CBitcoinAddress::PUBKEY_ADDRESS_TEST + 128, }; void SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(fTestNet ? PRIVKEY_ADDRESS_TEST : PRIVKEY_ADDRESS, vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey GetKey() { CKey ret; ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1); return ret; } bool IsValid() const { bool fExpectTestNet = false; switch(nVersion) { case PRIVKEY_ADDRESS: break; case PRIVKEY_ADDRESS_TEST: fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1)); } bool SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } CBitcoinSecret(const CKey& vchSecret) { SetKey(vchSecret); } CBitcoinSecret() { } }; #endif // BITCOIN_BASE58_H
b7fae3f0aeb5e97990840d3ee68b2d3606620937
bb2cca81ee55f761031acb64109a7cafad859c5c
/include/OGRE/OgreVector4.h
ac283da570a3681bbc88cec2cd91e9f5a5c2bbfb
[]
no_license
iaco79/baseogre
4ecc3f98dbda329c75bb4acd0bcaacdb9ccbeded
cba63af47a9a1c83b0af44332218e2dae088fa91
refs/heads/master
2021-08-30T17:39:21.064785
2015-12-02T19:44:43
2015-12-02T19:44:43
114,685,645
0
1
null
null
null
null
UTF-8
C++
false
false
11,224
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #ifndef __Vector4_H__ #define __Vector4_H__ #include "OgrePrerequisites.h" #include "OgreVector3.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Math * @{ */ /** 4-dimensional homogeneous vector. */ class _OgreExport Vector4 { public: Real x, y, z, w; public: /** Default constructor. @note It does <b>NOT</b> initialize the vector for efficiency. */ inline Vector4() { } inline Vector4( const Real fX, const Real fY, const Real fZ, const Real fW ) : x( fX ), y( fY ), z( fZ ), w( fW ) { } inline explicit Vector4( const Real afCoordinate[4] ) : x( afCoordinate[0] ), y( afCoordinate[1] ), z( afCoordinate[2] ), w( afCoordinate[3] ) { } inline explicit Vector4( const int afCoordinate[4] ) { x = (Real)afCoordinate[0]; y = (Real)afCoordinate[1]; z = (Real)afCoordinate[2]; w = (Real)afCoordinate[3]; } inline explicit Vector4( Real* const r ) : x( r[0] ), y( r[1] ), z( r[2] ), w( r[3] ) { } inline explicit Vector4( const Real scaler ) : x( scaler ) , y( scaler ) , z( scaler ) , w( scaler ) { } inline explicit Vector4(const Vector3& rhs) : x(rhs.x), y(rhs.y), z(rhs.z), w(1.0f) { } /** Exchange the contents of this vector with another. */ inline void swap(Vector4& other) { std::swap(x, other.x); std::swap(y, other.y); std::swap(z, other.z); std::swap(w, other.w); } inline Real operator [] ( const size_t i ) const { assert( i < 4 ); return *(&x+i); } inline Real& operator [] ( const size_t i ) { assert( i < 4 ); return *(&x+i); } /// Pointer accessor for direct copying inline Real* ptr() { return &x; } /// Pointer accessor for direct copying inline const Real* ptr() const { return &x; } /** Assigns the value of the other vector. @param rkVector The other vector */ inline Vector4& operator = ( const Vector4& rkVector ) { x = rkVector.x; y = rkVector.y; z = rkVector.z; w = rkVector.w; return *this; } inline Vector4& operator = ( const Real fScalar) { x = fScalar; y = fScalar; z = fScalar; w = fScalar; return *this; } inline bool operator == ( const Vector4& rkVector ) const { return ( x == rkVector.x && y == rkVector.y && z == rkVector.z && w == rkVector.w ); } inline bool operator != ( const Vector4& rkVector ) const { return ( x != rkVector.x || y != rkVector.y || z != rkVector.z || w != rkVector.w ); } inline Vector4& operator = (const Vector3& rhs) { x = rhs.x; y = rhs.y; z = rhs.z; w = 1.0f; return *this; } // arithmetic operations inline Vector4 operator + ( const Vector4& rkVector ) const { return Vector4( x + rkVector.x, y + rkVector.y, z + rkVector.z, w + rkVector.w); } inline Vector4 operator - ( const Vector4& rkVector ) const { return Vector4( x - rkVector.x, y - rkVector.y, z - rkVector.z, w - rkVector.w); } inline Vector4 operator * ( const Real fScalar ) const { return Vector4( x * fScalar, y * fScalar, z * fScalar, w * fScalar); } inline Vector4 operator * ( const Vector4& rhs) const { return Vector4( rhs.x * x, rhs.y * y, rhs.z * z, rhs.w * w); } inline Vector4 operator / ( const Real fScalar ) const { assert( fScalar != 0.0 ); Real fInv = 1.0f / fScalar; return Vector4( x * fInv, y * fInv, z * fInv, w * fInv); } inline Vector4 operator / ( const Vector4& rhs) const { return Vector4( x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w); } inline const Vector4& operator + () const { return *this; } inline Vector4 operator - () const { return Vector4(-x, -y, -z, -w); } inline friend Vector4 operator * ( const Real fScalar, const Vector4& rkVector ) { return Vector4( fScalar * rkVector.x, fScalar * rkVector.y, fScalar * rkVector.z, fScalar * rkVector.w); } inline friend Vector4 operator / ( const Real fScalar, const Vector4& rkVector ) { return Vector4( fScalar / rkVector.x, fScalar / rkVector.y, fScalar / rkVector.z, fScalar / rkVector.w); } inline friend Vector4 operator + (const Vector4& lhs, const Real rhs) { return Vector4( lhs.x + rhs, lhs.y + rhs, lhs.z + rhs, lhs.w + rhs); } inline friend Vector4 operator + (const Real lhs, const Vector4& rhs) { return Vector4( lhs + rhs.x, lhs + rhs.y, lhs + rhs.z, lhs + rhs.w); } inline friend Vector4 operator - (const Vector4& lhs, Real rhs) { return Vector4( lhs.x - rhs, lhs.y - rhs, lhs.z - rhs, lhs.w - rhs); } inline friend Vector4 operator - (const Real lhs, const Vector4& rhs) { return Vector4( lhs - rhs.x, lhs - rhs.y, lhs - rhs.z, lhs - rhs.w); } // arithmetic updates inline Vector4& operator += ( const Vector4& rkVector ) { x += rkVector.x; y += rkVector.y; z += rkVector.z; w += rkVector.w; return *this; } inline Vector4& operator -= ( const Vector4& rkVector ) { x -= rkVector.x; y -= rkVector.y; z -= rkVector.z; w -= rkVector.w; return *this; } inline Vector4& operator *= ( const Real fScalar ) { x *= fScalar; y *= fScalar; z *= fScalar; w *= fScalar; return *this; } inline Vector4& operator += ( const Real fScalar ) { x += fScalar; y += fScalar; z += fScalar; w += fScalar; return *this; } inline Vector4& operator -= ( const Real fScalar ) { x -= fScalar; y -= fScalar; z -= fScalar; w -= fScalar; return *this; } inline Vector4& operator *= ( const Vector4& rkVector ) { x *= rkVector.x; y *= rkVector.y; z *= rkVector.z; w *= rkVector.w; return *this; } inline Vector4& operator /= ( const Real fScalar ) { assert( fScalar != 0.0 ); Real fInv = 1.0f / fScalar; x *= fInv; y *= fInv; z *= fInv; w *= fInv; return *this; } inline Vector4& operator /= ( const Vector4& rkVector ) { x /= rkVector.x; y /= rkVector.y; z /= rkVector.z; w /= rkVector.w; return *this; } /** Calculates the dot (scalar) product of this vector with another. @param vec Vector with which to calculate the dot product (together with this one). @return A float representing the dot product value. */ inline Real dotProduct(const Vector4& vec) const { return x * vec.x + y * vec.y + z * vec.z + w * vec.w; } /// Check whether this vector contains valid values inline bool isNaN() const { return Math::isNaN(x) || Math::isNaN(y) || Math::isNaN(z) || Math::isNaN(w); } /** Function for writing to a stream. */ inline _OgreExport friend std::ostream& operator << ( std::ostream& o, const Vector4& v ) { o << "Vector4(" << v.x << ", " << v.y << ", " << v.z << ", " << v.w << ")"; return o; } // special static const Vector4 ZERO; }; /** @} */ /** @} */ } #endif
fa50fd8987f476af640f1fef29d71da851cee472
b216ecc99c64d1a8db94440d4fbfb8019b2ddd0b
/GMatrix.h
1be90b03cc1e803bdf83815fa4855c075e0b77fc
[]
no_license
kms0845/msKim_first
1bd58bfee73d6201cb3251d3b7b8a7e891874991
08fda6f85d446c7778e200a23f27975c1faac0bc
refs/heads/master
2021-01-01T06:33:37.738218
2015-08-04T06:06:42
2015-08-04T06:06:42
40,166,169
0
0
null
null
null
null
UTF-8
C++
false
false
781
h
/* * File: GMatrix.h * Author: MinSung * * Created on July 29, 2015, 3:48 PM */ #ifndef GMATRIX_H #define GMATRIX_H #include "IMatrix.h" #include <vector> #include <set> class GMatrix : public IMatrix { private: std::vector<std::vector<double> > itsValue; std::set<double> theSet; public: int getColumnSize() { return itsValue.size(); } int getRowSize() { if (this->itsValue.empty()) { return 0; } else { return this->itsValue.front().size(); } } int getValue(){ return this->itsValue; } int getValue(const int theRow,const int theColumn){ return this->itsValue.at(theRow).at(theColumn); } //getrow, getcolum //set }; #endif /* GMATRIX_H */
[ "MinSung@MinSung-PC" ]
MinSung@MinSung-PC
5a6f57310831696bb925138d439e527e2af611aa
c9764a063074b067a22821daefd85f6ab2ccd518
/source/gui/apropos.cpp
e01503925db56d8ca74b9b43449cdefb3c94d103
[]
no_license
hugodes/editeur-web
c8d3e6b1034f804a1c28f1ffe19836515af370d2
75dac924099d0e455b84749bcf6a7e902011572d
refs/heads/master
2020-05-17T18:41:08.679716
2013-05-28T20:55:55
2013-05-28T20:55:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include "headers/gui/apropos.h" #include "ui_apropos.h" aPropos::aPropos(QWidget *parent) : QDialog(parent), ui(new Ui::aPropos) { ui->setupUi(this); QPixmap *pixmap_img = new QPixmap("../editeur-web/image/leedit.png"); ui->logo->setPixmap(*pixmap_img); } aPropos::~aPropos() { delete ui; }
12f715c6ce74225efadc1e93ddcee5b894dac816
92328b9ffe1d1510e373561eb95469d306ba68e8
/xapian-core-file/api/omenquire.cc
4b0242140a554e81042d8ca5b34d4cc1fe101e4a
[]
no_license
EQ94/XapianInJD
82f592bbd3efd461e7bf14c9a9079c2e01d580fd
6c6e12d4f89f8e0226eecce340d306cefc6e285a
refs/heads/master
2020-03-28T20:32:24.924116
2018-09-17T06:56:38
2018-09-17T06:56:38
149,080,243
0
0
null
null
null
null
UTF-8
C++
false
false
26,666
cc
/* omenquire.cc: External interface for running queries * * Copyright 1999,2000,2001 BrightStation PLC * Copyright 2001,2002 Ananova Ltd * Copyright 2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2013,2014,2015,2016,2017 Olly Betts * Copyright 2007,2009 Lemur Consulting Ltd * Copyright 2011, Action Without Borders * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ #include <config.h> #include "xapian/enquire.h" #include "xapian/document.h" #include "xapian/error.h" #include "xapian/expanddecider.h" #include "xapian/matchspy.h" #include "xapian/termiterator.h" #include "xapian/weight.h" #include "vectortermlist.h" #include "backends/database.h" #include "debuglog.h" #include "expand/esetinternal.h" #include "expand/expandweight.h" #include "exp10.h" #include "matcher/multimatch.h" #include "omassert.h" #include "api/omenquireinternal.h" #include "str.h" #include "weight/weightinternal.h" #include <string> #include <algorithm> #include "autoptr.h" #include <cfloat> #include <cmath> #include <vector> #include <iostream> using namespace std; using Xapian::Internal::ExpandWeight; using Xapian::Internal::Bo1EWeight; using Xapian::Internal::TradEWeight; namespace Xapian { MatchDecider::~MatchDecider() { } // Methods for Xapian::RSet RSet::RSet() : internal(new RSet::Internal) { } RSet::RSet(const RSet &other) : internal(other.internal) { } void RSet::operator=(const RSet &other) { internal = other.internal; } RSet::RSet(RSet &&) = default; RSet& RSet::operator=(RSet &&) = default; RSet::~RSet() { } Xapian::doccount RSet::size() const { return internal->items.size(); } bool RSet::empty() const { return internal->items.empty(); } void RSet::add_document(Xapian::docid did) { if (did == 0) throw Xapian::InvalidArgumentError("Docid 0 not valid"); internal->items.insert(did); } void RSet::remove_document(Xapian::docid did) { internal->items.erase(did); } bool RSet::contains(Xapian::docid did) const { return internal->items.find(did) != internal->items.end(); } string RSet::get_description() const { return "RSet(" + internal->get_description() + ")"; } string RSet::Internal::get_description() const { string description("RSet::Internal("); set<Xapian::docid>::const_iterator i; for (i = items.begin(); i != items.end(); ++i) { if (i != items.begin()) description += ", "; description += str(*i); } description += ')'; return description; } namespace Internal { // Methods for Xapian::MSetItem string MSetItem::get_description() const { string description; description = str(did) + ", " + str(wt) + ", " + collapse_key; description = "Xapian::MSetItem(" + description + ")"; return description; } } // Methods for Xapian::MSet MSet::MSet() : internal(new MSet::Internal) { } MSet::~MSet() { } MSet::MSet(const MSet & other) : internal(other.internal) { } MSet & MSet::operator=(const MSet &other) { internal = other.internal; return *this; } MSet::MSet(MSet&&) = default; MSet& MSet::operator=(MSet&&) = default; void MSet::fetch_(Xapian::doccount first, Xapian::doccount last) const { LOGCALL_VOID(API, "Xapian::MSet::fetch_", first | last); Assert(internal.get() != 0); internal->fetch_items(first, last); } int MSet::convert_to_percent(double wt) const { LOGCALL(API, int, "Xapian::MSet::convert_to_percent", wt); Assert(internal.get() != 0); RETURN(internal->convert_to_percent_internal(wt)); } Xapian::doccount MSet::get_termfreq(const string &tname) const { LOGCALL(API, Xapian::doccount, "Xapian::MSet::get_termfreq", tname); Assert(internal.get() != 0); if (usual(internal->stats)) { Xapian::doccount termfreq; if (internal->stats->get_stats(tname, termfreq)) RETURN(termfreq); } if (internal->enquire.get() == 0) { throw InvalidOperationError("Can't get termfreq from an MSet which is not derived from a query."); } RETURN(internal->enquire->get_termfreq(tname)); } double MSet::get_termweight(const string &tname) const { LOGCALL(API, double, "Xapian::MSet::get_termweight", tname); Assert(internal.get() != 0); if (!internal->stats) { throw InvalidOperationError("Can't get termweight from an MSet which is not derived from a query."); } double termweight; if (!internal->stats->get_termweight(tname, termweight)) { string msg = tname; msg += ": termweight not available"; throw InvalidArgumentError(msg); } RETURN(termweight); } Xapian::doccount MSet::get_firstitem() const { Assert(internal.get() != 0); return internal->firstitem; } Xapian::doccount MSet::get_matches_lower_bound() const { Assert(internal.get() != 0); return internal->matches_lower_bound; } Xapian::doccount MSet::get_matches_estimated() const { Assert(internal.get() != 0); // Doing this here avoids calculating if the estimate is never looked at, // though does mean we recalculate if this method is called more than once. Xapian::doccount m = internal->matches_lower_bound; Xapian::doccount M = internal->matches_upper_bound; Xapian::doccount e = internal->matches_estimated; Xapian::doccount D = M - m; if (D == 0 || e == 0) { // Estimate is exact or zero. A zero but non-exact estimate can happen // with get_mset(0, 0). return e; } Xapian::doccount r = Xapian::doccount(exp10(int(log10(D))) + 0.5); while (r > e) r /= 10; Xapian::doccount R = e / r * r; if (R < m) { R += r; } else if (R > M) { R -= r; } else if (R < e && r % 2 == 0 && e - R == r / 2) { // Round towards the centre of the range. if (e - m < M - e) { R += r; } } // If it all goes pear-shaped, just stick to the original estimate. if (R < m || R > M) R = e; return R; } Xapian::doccount MSet::get_matches_upper_bound() const { Assert(internal.get() != 0); return internal->matches_upper_bound; } Xapian::doccount MSet::get_uncollapsed_matches_lower_bound() const { Assert(internal.get() != 0); return internal->uncollapsed_lower_bound; } Xapian::doccount MSet::get_uncollapsed_matches_estimated() const { Assert(internal.get() != 0); return internal->uncollapsed_estimated; } Xapian::doccount MSet::get_uncollapsed_matches_upper_bound() const { Assert(internal.get() != 0); return internal->uncollapsed_upper_bound; } double MSet::get_max_possible() const { Assert(internal.get() != 0); return internal->max_possible; } double MSet::get_max_attained() const { Assert(internal.get() != 0); return internal->max_attained; } string MSet::snippet(const string & text, size_t length, const Xapian::Stem & stemmer, unsigned flags, const string & hi_start, const string & hi_end, const string & omit) const { Assert(internal.get() != 0); return internal->snippet(text, length, stemmer, flags, hi_start, hi_end, omit); } Xapian::doccount MSet::size() const { Assert(internal.get() != 0); return internal->items.size(); } string MSet::get_description() const { Assert(internal.get() != 0); return "Xapian::MSet(" + internal->get_description() + ")"; } int MSet::Internal::convert_to_percent_internal(double wt) const { LOGCALL(MATCH, int, "Xapian::MSet::Internal::convert_to_percent_internal", wt); if (percent_factor == 0) RETURN(100); // Excess precision on x86 can result in a difference here. double v = wt * percent_factor + 100.0 * DBL_EPSILON; int pcent = static_cast<int>(v); LOGLINE(MATCH, "wt = " << wt << ", max_possible = " << max_possible << " => pcent = " << pcent); if (pcent > 100) pcent = 100; if (pcent < 0) pcent = 0; if (pcent == 0 && wt > 0) pcent = 1; RETURN(pcent); } Document MSet::Internal::get_doc_by_index(Xapian::doccount index) const { LOGCALL(MATCH, Document, "Xapian::MSet::Internal::get_doc_by_index", index); index += firstitem; map<Xapian::doccount, Document>::const_iterator doc; doc = indexeddocs.find(index); if (doc != indexeddocs.end()) { RETURN(doc->second); } if (index < firstitem || index >= firstitem + items.size()) { throw RangeError("The mset returned from the match does not contain the document at index " + str(index)); } Assert(enquire.get()); if (!requested_docs.empty()) { // There's already a pending request, so handle that. read_docs(); // Maybe we just fetched the doc we want. doc = indexeddocs.find(index); if (doc != indexeddocs.end()) { RETURN(doc->second); } } RETURN(enquire->get_document(items[index - firstitem])); } void MSet::Internal::fetch_items(Xapian::doccount first, Xapian::doccount last) const { LOGCALL_VOID(MATCH, "Xapian::MSet::Internal::fetch_items", first | last); if (enquire.get() == 0) { throw InvalidOperationError("Can't fetch documents from an MSet which is not derived from a query."); } if (items.empty()) return; if (last > items.size() - 1) last = items.size() - 1; for (Xapian::doccount i = first; i <= last; ++i) { map<Xapian::doccount, Document>::const_iterator doc; doc = indexeddocs.find(i); if (doc == indexeddocs.end()) { /* We don't have the document cached */ set<Xapian::doccount>::const_iterator s; s = requested_docs.find(i); if (s == requested_docs.end()) { /* We haven't even requested it yet - do so now. */ enquire->request_doc(items[i - firstitem]); requested_docs.insert(i); } } } } string MSet::Internal::get_description() const { string description = "Xapian::MSet::Internal("; description += "firstitem=" + str(firstitem) + ", " + "matches_lower_bound=" + str(matches_lower_bound) + ", " + "matches_estimated=" + str(matches_estimated) + ", " + "matches_upper_bound=" + str(matches_upper_bound) + ", " + "max_possible=" + str(max_possible) + ", " + "max_attained=" + str(max_attained); for (vector<Xapian::Internal::MSetItem>::const_iterator i = items.begin(); i != items.end(); ++i) { if (!description.empty()) description += ", "; description += i->get_description(); } description += ")"; return description; } void MSet::Internal::read_docs() const { set<Xapian::doccount>::const_iterator i; for (i = requested_docs.begin(); i != requested_docs.end(); ++i) { indexeddocs[*i] = enquire->read_doc(items[*i - firstitem]); LOGLINE(MATCH, "stored doc at index " << *i << " is " << indexeddocs[*i]); } /* Clear list of requested but not fetched documents. */ requested_docs.clear(); } // MSetIterator Xapian::docid MSetIterator::operator*() const { Assert(mset.internal.get()); Xapian::doccount size = mset.internal->items.size(); Xapian::doccount index = size - off_from_end; AssertRel(index,<,size); return mset.internal->items[index].did; } Document MSetIterator::get_document() const { Assert(mset.internal.get()); Xapian::doccount size = mset.internal->items.size(); Xapian::doccount index = size - off_from_end; AssertRel(index,<,size); return mset.internal->get_doc_by_index(index); } double MSetIterator::get_weight() const { Assert(mset.internal.get()); Xapian::doccount size = mset.internal->items.size(); Xapian::doccount index = size - off_from_end; AssertRel(index,<,size); return mset.internal->items[index].wt; } std::string MSetIterator::get_collapse_key() const { Assert(mset.internal.get()); Xapian::doccount size = mset.internal->items.size(); Xapian::doccount index = size - off_from_end; AssertRel(index,<,size); return mset.internal->items[index].collapse_key; } Xapian::doccount MSetIterator::get_collapse_count() const { Assert(mset.internal.get()); Xapian::doccount size = mset.internal->items.size(); Xapian::doccount index = size - off_from_end; AssertRel(index,<,size); return mset.internal->items[index].collapse_count; } string MSetIterator::get_sort_key() const { Assert(mset.internal.get()); Xapian::doccount size = mset.internal->items.size(); Xapian::doccount index = size - off_from_end; AssertRel(index,<,size); return mset.internal->items[index].sort_key; } string MSetIterator::get_description() const { return "Xapian::MSetIterator(" + str(mset.size() - off_from_end) + ")"; } // Methods for Xapian::Enquire::Internal Enquire::Internal::Internal(const Database &db_) : db(db_), query(), collapse_key(Xapian::BAD_VALUENO), collapse_max(0), order(Enquire::ASCENDING), percent_cutoff(0), weight_cutoff(0), sort_key(Xapian::BAD_VALUENO), sort_by(REL), sort_value_forward(true), sorter(), time_limit(0.0), weight(0), eweightname("trad"), expand_k(1.0) { if (db.internal.empty()) { throw InvalidArgumentError("Can't make an Enquire object from an uninitialised Database object."); } } Enquire::Internal::~Internal() { delete weight; weight = 0; } void Enquire::Internal::set_query(const Query &query_, termcount qlen_) { query = query_; qlen = qlen_ ? qlen_ : query.get_length(); } const Query & Enquire::Internal::get_query() const { return query; } MSet Enquire::Internal::get_mset(Xapian::doccount first, Xapian::doccount maxitems, MLmodel &ml, Xapian::doccount check_at_least, const RSet *rset, const MatchDecider *mdecider) const { LOGCALL(MATCH, MSet, "Enquire::Internal::get_mset", first | maxitems | check_at_least | rset | mdecider); if (percent_cutoff && (sort_by == VAL || sort_by == VAL_REL)) { throw Xapian::UnimplementedError("Use of a percentage cutoff while sorting primary by value isn't currently supported"); } if (weight == 0) { weight = new BM25Weight; } Xapian::doccount first_orig = first; { Xapian::doccount docs = db.get_doccount(); first = min(first, docs); maxitems = min(maxitems, docs - first); check_at_least = min(check_at_least, docs); check_at_least = max(check_at_least, first + maxitems); } AutoPtr<Xapian::Weight::Internal> stats(new Xapian::Weight::Internal); ::MultiMatch match(db, query, qlen, rset, collapse_max, collapse_key, percent_cutoff, weight_cutoff, order, sort_key, sort_by, sort_value_forward, time_limit, *(stats.get()), weight, spies, (sorter.get() != NULL), (mdecider != NULL)); // Run query and put results into supplied Xapian::MSet object. MSet retval; match.get_mset(first, maxitems, check_at_least, retval, *(stats.get()), mdecider, sorter.get()); if (first_orig != first && retval.internal.get()) { retval.internal->firstitem = first_orig; // no execute } Assert(weight->name() != "bool" || retval.get_max_possible() == 0); // The Xapian::MSet needs to have a pointer to ourselves, so that it can // retrieve the documents. This is set here explicitly to avoid having // to pass it into the matcher, which gets messy particularly in the // networked case. retval.internal->enquire = this; // execute if (!retval.internal->stats) { retval.internal->stats = stats.release(); // execute } // Second Index From Here ml.readFeature(retval); ml.getResult(); ml.readSpyData(spies); RETURN(retval); } ESet Enquire::Internal::get_eset(Xapian::termcount maxitems, const RSet & rset, int flags, const ExpandDecider * edecider_, double min_wt) const { LOGCALL(MATCH, ESet, "Enquire::Internal::get_eset", maxitems | rset | flags | edecider_ | min_wt); using Xapian::Internal::opt_intrusive_ptr; opt_intrusive_ptr<const ExpandDecider> edecider(edecider_); if (maxitems == 0 || rset.empty()) { // Either we were asked for no results, or wouldn't produce any // because no documents were marked as relevant. RETURN(ESet()); } LOGVALUE(MATCH, rset.size()); if (!query.empty() && !(flags & Enquire::INCLUDE_QUERY_TERMS)) { opt_intrusive_ptr<const ExpandDecider> decider_noquery( (new ExpandDeciderFilterTerms(query.get_terms_begin(), query.get_terms_end()))->release()); if (edecider.get()) { edecider = (new ExpandDeciderAnd(decider_noquery.get(), edecider.get()))->release(); } else { edecider = decider_noquery; } } bool use_exact_termfreq(flags & Enquire::USE_EXACT_TERMFREQ); Xapian::ESet eset; eset.internal = new Xapian::ESet::Internal; if (eweightname == "bo1") { Bo1EWeight bo1eweight(db, rset.size(), use_exact_termfreq); eset.internal->expand(maxitems, db, rset, edecider.get(), bo1eweight, min_wt); } else { TradEWeight tradeweight(db, rset.size(), use_exact_termfreq, expand_k); eset.internal->expand(maxitems, db, rset, edecider.get(), tradeweight, min_wt); } RETURN(eset); } class ByQueryIndexCmp { private: typedef map<string, unsigned int> tmap_t; const tmap_t &tmap; public: explicit ByQueryIndexCmp(const tmap_t &tmap_) : tmap(tmap_) {} bool operator()(const string &left, const string &right) const { tmap_t::const_iterator l, r; l = tmap.find(left); r = tmap.find(right); Assert((l != tmap.end()) && (r != tmap.end())); return l->second < r->second; } }; TermIterator Enquire::Internal::get_matching_terms(Xapian::docid did) const { if (query.empty()) return TermIterator(); // The ordered list of terms in the query. TermIterator qt = query.get_terms_begin(); // copy the list of query terms into a map for faster access. // FIXME: a hash would be faster than a map, if this becomes // a problem. map<string, unsigned int> tmap; unsigned int index = 1; for ( ; qt != query.get_terms_end(); ++qt) { if (tmap.find(*qt) == tmap.end()) tmap[*qt] = index++; } vector<string> matching_terms; TermIterator docterms = db.termlist_begin(did); TermIterator docterms_end = db.termlist_end(did); while (docterms != docterms_end) { string term = *docterms; map<string, unsigned int>::iterator t = tmap.find(term); if (t != tmap.end()) matching_terms.push_back(term); ++docterms; } // sort the resulting list by query position. sort(matching_terms.begin(), matching_terms.end(), ByQueryIndexCmp(tmap)); return TermIterator(new VectorTermList(matching_terms.begin(), matching_terms.end())); } TermIterator Enquire::Internal::get_matching_terms(const MSetIterator &it) const { // FIXME: take advantage of MSetIterator to ensure that database // doesn't get modified underneath us. return get_matching_terms(*it); } Xapian::doccount Enquire::Internal::get_termfreq(const string &tname) const { return db.get_termfreq(tname); } string Enquire::Internal::get_description() const { string description = db.get_description(); description += ", "; description += query.get_description(); return description; } // Private methods for Xapian::Enquire::Internal void Enquire::Internal::request_doc(const Xapian::Internal::MSetItem &item) const { unsigned int multiplier = db.internal.size(); Xapian::docid realdid = (item.did - 1) / multiplier + 1; Xapian::doccount dbnumber = (item.did - 1) % multiplier; db.internal[dbnumber]->request_document(realdid); } Document Enquire::Internal::read_doc(const Xapian::Internal::MSetItem &item) const { unsigned int multiplier = db.internal.size(); Xapian::docid realdid = (item.did - 1) / multiplier + 1; Xapian::doccount dbnumber = (item.did - 1) % multiplier; Xapian::Document::Internal *doc; doc = db.internal[dbnumber]->collect_document(realdid); return Document(doc); } Document Enquire::Internal::get_document(const Xapian::Internal::MSetItem &item) const { unsigned int multiplier = db.internal.size(); Xapian::docid realdid = (item.did - 1) / multiplier + 1; Xapian::doccount dbnumber = (item.did - 1) % multiplier; // We know the doc exists, so open lazily. return Document(db.internal[dbnumber]->open_document(realdid, true)); } // Methods of Xapian::Enquire Enquire::Enquire(const Enquire & other) : internal(other.internal) { LOGCALL_CTOR(API, "Enquire", other); } void Enquire::operator=(const Enquire & other) { LOGCALL_VOID(API, "Xapian::Enquire::operator=", other); internal = other.internal; } Enquire::Enquire(Enquire&&) = default; Enquire& Enquire::operator=(Enquire&&) = default; Enquire::Enquire(const Database &databases) : internal(new Internal(databases)) { LOGCALL_CTOR(API, "Enquire", databases); } Enquire::Enquire(const Database &databases, ErrorHandler *) : internal(new Internal(databases)) { LOGCALL_CTOR(API, "Enquire", databases | Literal("errorhandler")); } Enquire::~Enquire() { LOGCALL_DTOR(API, "Enquire"); } void Enquire::set_query(const Query & query, termcount len) { LOGCALL_VOID(API, "Xapian::Enquire::set_query", query | len); internal->set_query(query, len); } const Query & Enquire::get_query() const { LOGCALL(API, const Xapian::Query &, "Xapian::Enquire::get_query", NO_ARGS); RETURN(internal->get_query()); } void Enquire::add_matchspy(MatchSpy * spy) { LOGCALL_VOID(API, "Xapian::Enquire::add_matchspy", spy); internal->spies.push_back(spy); } void Enquire::clear_matchspies() { LOGCALL_VOID(API, "Xapian::Enquire::clear_matchspies", NO_ARGS); internal->spies.clear(); } void Enquire::set_weighting_scheme(const Weight &weight_) { LOGCALL_VOID(API, "Xapian::Enquire::set_weighting_scheme", weight_); // Clone first in case doing so throws an exception. Weight * wt = weight_.clone(); swap(wt, internal->weight); delete wt; } void Enquire::set_expansion_scheme(const std::string &eweightname_, double expand_k_) const { LOGCALL_VOID(API, "Xapian::Enquire::set_expansion_scheme", eweightname_ | expand_k_); if (eweightname_ != "bo1" && eweightname_ != "trad") { throw InvalidArgumentError("Invalid name for query expansion scheme."); } internal->eweightname = eweightname_; internal->expand_k = expand_k_; } void Enquire::set_collapse_key(Xapian::valueno collapse_key, Xapian::doccount collapse_max) { if (collapse_key == Xapian::BAD_VALUENO) collapse_max = 0; internal->collapse_key = collapse_key; internal->collapse_max = collapse_max; } void Enquire::set_docid_order(Enquire::docid_order order) { internal->order = order; } void Enquire::set_cutoff(int percent_cutoff, double weight_cutoff) { internal->percent_cutoff = percent_cutoff; internal->weight_cutoff = weight_cutoff; } void Enquire::set_sort_by_relevance() { internal->sort_by = Internal::REL; } void Enquire::set_sort_by_value(valueno sort_key, bool ascending) { internal->sorter = NULL; internal->sort_key = sort_key; internal->sort_by = Internal::VAL; internal->sort_value_forward = ascending; } void Enquire::set_sort_by_value_then_relevance(valueno sort_key, bool ascending) { internal->sorter = NULL; internal->sort_key = sort_key; internal->sort_by = Internal::VAL_REL; internal->sort_value_forward = ascending; } void Enquire::set_sort_by_relevance_then_value(valueno sort_key, bool ascending) { internal->sorter = NULL; internal->sort_key = sort_key; internal->sort_by = Internal::REL_VAL; internal->sort_value_forward = ascending; } void Enquire::set_sort_by_key(KeyMaker * sorter, bool ascending) { if (sorter == NULL) throw InvalidArgumentError("sorter can't be NULL"); internal->sorter = sorter; internal->sort_by = Internal::VAL; internal->sort_value_forward = ascending; } void Enquire::set_sort_by_key_then_relevance(KeyMaker * sorter, bool ascending) { if (sorter == NULL) throw InvalidArgumentError("sorter can't be NULL"); internal->sorter = sorter; internal->sort_by = Internal::VAL_REL; internal->sort_value_forward = ascending; } void Enquire::set_sort_by_relevance_then_key(KeyMaker * sorter, bool ascending) { if (sorter == NULL) throw Xapian::InvalidArgumentError("sorter can't be NULL"); internal->sorter = sorter; internal->sort_by = Internal::REL_VAL; internal->sort_value_forward = ascending; } void Enquire::set_time_limit(double time_limit) { internal->time_limit = time_limit; } MSet Enquire::get_mset(Xapian::doccount first, Xapian::doccount maxitems, MLmodel &ml, Xapian::doccount check_at_least, const RSet *rset, const MatchDecider *mdecider) const { LOGCALL(API, Xapian::MSet, "Xapian::Enquire::get_mset", first | maxitems | check_at_least | rset | mdecider); RETURN(internal->get_mset(first, maxitems, ml, check_at_least, rset, mdecider)); } MSet Enquire::get_mset(Xapian::doccount first, Xapian::doccount maxitems, Xapian::doccount check_at_least, const RSet *rset, const MatchDecider *mdecider) const { LOGCALL(API, Xapian::MSet, "Xapian::Enquire::get_mset", first | maxitems | check_at_least | rset | mdecider); MLmodel ml; RETURN(internal->get_mset(first, maxitems, ml, check_at_least, rset, mdecider)); } ESet Enquire::get_eset(Xapian::termcount maxitems, const RSet & rset, int flags, const ExpandDecider * edecider, double min_wt) const { LOGCALL(API, Xapian::ESet, "Xapian::Enquire::get_eset", maxitems | rset | flags | edecider | min_wt); RETURN(internal->get_eset(maxitems, rset, flags, edecider, min_wt)); } TermIterator Enquire::get_matching_terms_begin(const MSetIterator &it) const { LOGCALL(API, Xapian::TermIterator, "Xapian::Enquire::get_matching_terms_begin", it); RETURN(internal->get_matching_terms(it)); } TermIterator Enquire::get_matching_terms_begin(Xapian::docid did) const { LOGCALL(API, Xapian::TermIterator, "Xapian::Enquire::get_matching_terms_begin", did); RETURN(internal->get_matching_terms(did)); } string Enquire::get_description() const { return "Xapian::Enquire(" + internal->get_description() + ")"; } }
c5feb99c64ff3dbfbecde62bd255533008a56b1a
74f1fe67086a91650c8c34d71829c22c5bfa8e46
/Informatica-Grafica/Practica4/srcs-prac/MallaRevol.cpp
b8f3df9a2b97327edc6cb735bf288c5de67410fc
[]
no_license
SergioPadilla/Cuarto-Curso
e06818cec1479bec8338f0ed24ebd1cb7a25b9d8
0dc95afd4e7d39f8ec26feb61ad41412b7b1ef85
refs/heads/master
2021-01-15T15:22:48.728467
2016-07-17T16:35:13
2016-07-17T16:35:13
43,641,087
0
0
null
null
null
null
UTF-8
C++
false
false
2,289
cpp
#include "file_ply_stl.hpp" #include "MallaRevol.hpp" MallaRevol::MallaRevol(const char * archivo, unsigned nperfiles, bool textura){ vector <float> vertices_ply; ply::read_vertices(archivo, vertices_ply); int puntosPerfil = vertices_ply.size()/3; for (int j = 0;j < nperfiles; j++){ for (int i = 0;i < vertices_ply.size();i = i+3){ vertices.push_back(Tupla3f(vertices_ply[i]*cos(2*M_PI*j/nperfiles), vertices_ply[i+1], vertices_ply[i]*sin(2*M_PI*j/nperfiles))); } } vertices.push_back(Tupla3f(0, vertices_ply[1], 0)); vertices.push_back(Tupla3f(0, vertices_ply[vertices_ply.size()-2], 0)); for(int i = 0;i < nperfiles-1; i++){ caras.push_back(Tupla3i(i*puntosPerfil, puntosPerfil*nperfiles, (i+1)*puntosPerfil)); } for(int j = 0; j < nperfiles-1; j++){ for(int i = 0; i < puntosPerfil-1; i++){ caras.push_back(Tupla3i(i+puntosPerfil*j,i+1+puntosPerfil*j,i+puntosPerfil*(j+1))); caras.push_back(Tupla3i(i+puntosPerfil*(j+1),i+1+puntosPerfil*(j+1),i+1+puntosPerfil*j)); } } for(int i = 0;i < puntosPerfil-1; i++){ caras.push_back(Tupla3i(i+puntosPerfil*(nperfiles-1),i+1+puntosPerfil*(nperfiles-1),i)); caras.push_back(Tupla3i(i,i+1,i+1+puntosPerfil*(nperfiles-1))); } for (int i = 0;i < nperfiles-1; i++){ caras.push_back(Tupla3i(puntosPerfil-1+i*puntosPerfil,puntosPerfil*nperfiles+1,(puntosPerfil-1)+(i+1)*puntosPerfil)); } caras.push_back(Tupla3i(puntosPerfil-1+(nperfiles-1)*puntosPerfil,puntosPerfil*nperfiles+1,(puntosPerfil-1))); calcularNormales(); if(textura){ int mvertices = vertices_ply.size()/3; //Calculo posiciones de los vertices vector<Tupla3f> p; for(int i = 0; i < vertices_ply.size(); i+=3){ p.push_back(Tupla3f(vertices_ply[i],vertices_ply[i+1],vertices_ply[i+2])); } //Calculo distancias medias a lo largo del perfil vector<float> d; float di; d.push_back(0); for(int i = 1; i < mvertices; i++){ di = d[i-1] + sqrt((p[i]-p[i-1]).lengthSq()); d.push_back(di); } //Calculo coordenadas X e Y de la textura for(int i = 0; i < nperfiles; i++){ float s=(i/(nperfiles-1.0)); for(int j = 0; j < mvertices; j++){ texturas.push_back(Tupla2f(s,(d[j]/d[mvertices-1]))); } } } }
c3fd0e5be8130d294b29d17d9dae6ac2ab086a07
194840d144b77f3b662db6e3663c820db0807a46
/ProductLuaIdeCAPI/need_trans/core/ClipBase.h
5921e175c4fd115925a2ff48a6d7380bbccb14f4
[]
no_license
ToTPeople/my_own_tools
7cac7d84854b58d92f2ef4a538aea4ec06f5992c
d2509e7b399e076234162b8d757910627beec4b6
refs/heads/master
2020-03-24T03:46:05.723395
2018-07-26T12:15:49
2018-07-26T12:15:49
142,432,314
0
0
null
null
null
null
UTF-8
C++
false
false
3,657
h
#ifndef MTMVCORE_CLIPBASE_H #define MTMVCORE_CLIPBASE_H #include <memory> #include <sstream> #include "base/MTMacros.h" #include "Exceptions.h" #include "Point.h" #include "KeyFrame.h" #include "Json.h" NS_MEDIA_BEGIN class ClipBase { protected: string id; ///< ID Property for all derived Clip and Effect classes. float position; ///< The position on the timeline where this clip should start playing int layer; ///< The layer this clip is on. Lower clips are covered up by higher clips. float start; ///< The position in seconds to start playing (used to trim the beginning of a clip) float end; ///< The position in seconds to end playing (used to trim the ending of a clip) string previous_properties; ///< This string contains the previous JSON properties int max_width; ///< The maximum image width needed by this clip (used for optimizations) int max_height; ///< The maximium image height needed by this clip (used for optimizations) /// Generate JSON for a property Json::Value add_property_json(std::string name, float value, std::string type, std::string memo, Keyframe* keyframe, float min_value, float max_value, bool readonly, int64_t requested_frame); /// Generate JSON choice for a property (dropdown properties) Json::Value add_property_choice_json(std::string name, int value, int selected_value); public: /// Constructor for the base clip ClipBase() { max_width = 0; max_height = 0; }; // Compare a clip using the Position() property bool operator< ( ClipBase& a) { return (Position() < a.Position()); } bool operator<= ( ClipBase& a) { return (Position() <= a.Position()); } bool operator> ( ClipBase& a) { return (Position() > a.Position()); } bool operator>= ( ClipBase& a) { return (Position() >= a.Position()); } /// Get basic properties string Id() { return id; } ///< Get the Id of this clip object float Position() { return position; } ///< Get position on timeline (in seconds) int Layer() { return layer; } ///< Get layer of clip on timeline (lower number is covered by higher numbers) float Start() { return start; } ///< Get start position (in seconds) of clip (trim start of video) virtual float End() { return end; } ///< Get end position (in seconds) of clip (trim end of video) float Duration() { return end - start; } ///< Get the length of this clip (in seconds) /// Set basic properties void Id(string value) { id = value; } ///> Set the Id of this clip object void Position(float value) { position = value; } ///< Set position on timeline (in seconds) void Layer(int value) { layer = value; } ///< Set layer of clip on timeline (lower number is covered by higher numbers) void Start(float value) { start = value; } ///< Set start position (in seconds) of clip (trim start of video) virtual void End(float value) { end = value; } ///< Set end position (in seconds) of clip (trim end of video) /// Set Max Image Size (used for performance optimization) void SetMaxSize(int width, int height) { max_width = width; max_height = height; }; /// Get and Set JSON methods virtual string Json() = 0; ///< Generate JSON string of this object virtual void SetJson(string value) = 0; ///< Load JSON string into this object virtual Json::Value JsonValue() = 0; ///< Generate Json::JsonValue for this object virtual void SetJsonValue(Json::Value root) = 0; ///< Load Json::JsonValue into this object /// Get all properties for a specific frame (perfect for a UI to display the current state /// of all properties at any time) virtual string PropertiesJSON(int64_t requested_frame) = 0; }; NS_MEDIA_END #endif //MTMVCORE_CLIPBASE_H
32dad9d520e3c038e7442cd628aefd137b07ff2c
eaebd6929b0d0bcf86625a099ce3526d3aa54032
/src/qt/paymentserver.cpp
d45e8f4d8dbe0cf4d2b1d5ea400980dcb2c18c52
[ "MIT" ]
permissive
linuxmahara/volume
e036ac4f8208b27299201600c1737e8e60dc5cfc
85a90990ad77169b33a69b873e8d7dd68f0c76cc
refs/heads/master
2021-04-26T15:14:14.222383
2015-08-11T23:07:44
2015-08-11T23:07:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,501
cpp
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "paymentserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <QByteArray> #include <QDataStream> #include <QDebug> #include <QFileOpenEvent> #include <QHash> #include <QLocalServer> #include <QLocalSocket> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif using namespace boost; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("Volume:"); // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("BitcoinQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(GetDataDir(true).string().c_str()); name.append(QString::number(qHash(ddir))); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start Volume: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on bitcoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else emit receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) emit receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else emit receivedURI(message); }
60759e181a6cb1c9b42cf4d908f2d69f06104de0
fb3c1e036f18193d6ffe59f443dad8323cb6e371
/src/flash/AVMSWF/api/flash/filters/AS3GradientBevelFilter.h
ef17264bc9561db83be1c979570a377c8ba828c3
[]
no_license
playbar/nstest
a61aed443af816fdc6e7beab65e935824dcd07b2
d56141912bc2b0e22d1652aa7aff182e05142005
refs/heads/master
2021-06-03T21:56:17.779018
2016-08-01T03:17:39
2016-08-01T03:17:39
64,627,195
3
1
null
null
null
null
UTF-8
C++
false
false
2,249
h
#ifndef _AS3GradientBevelFilter_ #define _AS3GradientBevelFilter_ #include "AS3BitmapFilter.h" #define AS3GRADIENTBEVELDATA avmplus::NativeID::GradientBevelFilterObjectSlots namespace avmplus{namespace NativeID{ class GradientBevelFilterClassSlots{ friend class SlotOffsetsAndAsserts; public://Declare your STATIC AS3 slots here!!! private:}; class GradientBevelFilterObjectSlots{ friend class SlotOffsetsAndAsserts; public: //#if (__CORE_VERSION__>=0x02076000) XBOOL knockout;// : Boolean int quality;// : int ArrayObject* alphas;// : Array ArrayObject* colors;// : Array ArrayObject* ratios;// : Array Stringp type;// : String double angle;// : Number double blurX;// : Number double blurY;// : Number double distance;// : Number double strength;// : Number //#else // ArrayObject* alphas;// : Array // double angle;// : Number // double blurX;// : Number // double blurY;// : Number // ArrayObject* colors;// : Array // double distance;// : Number // XBOOL knockout;// : Boolean // int quality;// : int // ArrayObject* ratios;// : Array // double strength;// : Number // Stringp type;// : String //#endif //Declare your MEMBER AS3 slots here!!! private:}; }} namespace avmshell{ class GradientBevelFilterObject; class GradientBevelFilterClass : public ClassClosure { public: GradientBevelFilterClass(VTable *vtable); ScriptObject *createInstance(VTable *ivtable, ScriptObject *delegate); class GradientBevelFilterObject* CreateFilter(void*); private: #ifdef _SYMBIAN public: #endif friend class avmplus::NativeID::SlotOffsetsAndAsserts; avmplus::NativeID::GradientBevelFilterClassSlots m_slots_GradientBevelFilterClass; }; class GradientBevelFilterObject : public BitmapFilterObject { public: GradientBevelFilterObject(VTable* _vtable, ScriptObject* _delegate, int capacity); public: AS3GRADIENTBEVELDATA& GetData(){return m_slots_GradientBevelFilterObject;} virtual _XFilter* CreateFilter(); private: #ifdef _SYMBIAN public: #endif friend class avmplus::NativeID::SlotOffsetsAndAsserts; avmplus::NativeID::GradientBevelFilterObjectSlots m_slots_GradientBevelFilterObject; };} #endif
8ec24c6e55bc5f599861c66bbe03d71ce8d03708
65de6557a49a77664a3c2aef902429f7204640c0
/Type1.cpp
6681ba5bf7059a5884b6dc8c325aaa90224248ff
[]
no_license
BenBalidemaj/Mini-Game
33ed5f3fd7d2595826f85524e557ad82d1863921
08cd3b8a9f5c599c0e1a3fe2d105ecf9343352b3
refs/heads/master
2020-03-21T18:45:04.731503
2018-06-27T17:07:57
2018-06-27T17:07:57
138,909,999
0
0
null
null
null
null
UTF-8
C++
false
false
1,085
cpp
#include <iostream> #include "Enemy.h" #include "Type1.h" #include <string> using namespace std; Type1::Type1(string name) : Enemy(name) { setStatus(rand() % 2 + 1); setSpeed(6); setPositionY(500); } void Type1::move_position(int x, int y) { if (!isDead()) { setPositionX(x); setPositionY(y); cout << getName() + " moves to position " << x << ", " << y << " "; } else { cout << getName() + " is too dead to move "; } } void Type1::fire_weapon() { cout << getName() + " fired weapon: "; if (!isDead()) { int howManyAttacks = 3; int attackType = rand() % howManyAttacks; string attack; switch (attackType) { case 0: attack = "Bark "; break; case 1: attack = "Bite "; break; case 2: attack = "Slash "; break; } cout << attack; } else { cout << "NO WEAPON FIRED "; } } void Type1::update_status() { cout << getName() + " update status: "; if (!isDead()) { cout << "Ouch"; setStatus(getStatus() - 1); cout << ", status points: " << getStatus() << " \n"; } else { cout << "I'll be back..."; } }
e249b3c62f48566032dbcadf7ac80664153e33e4
1a26bee9356546ef7402a48fc2ee876d08cee029
/keepalivedaemoncore/src/main/cpp/keep_alive.cpp
80ce4d1a92b432909fcdd223f9ab22e8857b86d1
[]
no_license
lyjnew/KeepAlive2
ded10330c9df552f444e07a2050a669024472791
92cf978d2e06f7a57b319def841b5562dd03a3dd
refs/heads/master
2023-02-17T11:29:17.451314
2020-11-03T07:38:42
2020-11-03T07:38:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,589
cpp
#include <jni.h> #include <sys/wait.h> #include <android/log.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/file.h> #include <linux/android/binder.h> #include <sys/mman.h> #include "data_transact.h" #include "cParcel.h" #define DAEMON_CALLBACK_NAME "onDaemonDead" using namespace android; extern "C" { void set_process_name(JNIEnv *env) { jclass process = env->FindClass("android/os/Process"); jmethodID setArgV0 = env->GetStaticMethodID(process, "setArgV0", "(Ljava/lang/String;)V"); jstring name = env->NewStringUTF("daemon"); env->CallStaticVoidMethod(process, setArgV0, name); } void writeIntent(Parcel &out, const char *mPackage, const char *mClass) { // mAction out.writeString16(NULL, 0); // uri mData out.writeInt32(0); // mType out.writeString16(NULL, 0); // mIdentifier out.writeString16(NULL, 0); // mFlags out.writeInt32(0); // mPackage out.writeString16(NULL, 0); // mComponent out.writeString16(String16(mPackage)); out.writeString16(String16(mClass)); // mSourceBounds out.writeInt32(0); // mCategories out.writeInt32(0); // mSelector out.writeInt32(0); // mClipData out.writeInt32(0); // mContentUserHint out.writeInt32(-2); // mExtras out.writeInt32(-1); } void writeService(Parcel &out, const char *mPackage, const char *mClass, int sdk_version) { if (sdk_version >= 26) { out.writeInterfaceToken(String16("android.app.IActivityManager")); out.writeNullBinder(); out.writeInt32(1); writeIntent(out, mPackage, mClass); out.writeString16(NULL, 0); // resolvedType // mServiceData.writeInt(context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O ? 1 : 0); out.writeInt32(0); out.writeString16(String16(mPackage)); // callingPackage out.writeInt32(0); } else if (sdk_version >= 23) { out.writeInterfaceToken(String16("android.app.IActivityManager")); out.writeNullBinder(); writeIntent(out, mPackage, mClass); out.writeString16(NULL, 0); // resolvedType out.writeString16(String16(mPackage)); // callingPackage out.writeInt32(0); // userId } else { out.writeInterfaceToken(String16("android.app.IActivityManager")); out.writeNullBinder(); writeIntent(out, mPackage, mClass); out.writeString16(NULL, 0); // resolvedType out.writeInt32(0); // userId } } #define CHECK_SERVICE_TRANSACTION 1 uint32_t get_service(const char *serviceName, int mDriverFD) { Parcel *data1 = new Parcel;//, reply; Parcel *reply = new Parcel; data1->writeInterfaceToken(String16("android.os.IServiceManager")); data1->writeString16(String16(serviceName)); // remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply); // BpBinder.transact status_t status = write_transact(0, CHECK_SERVICE_TRANSACTION, *data1, reply, 0, mDriverFD); const flat_binder_object *flat = reply->readObject(false); if (flat) { LOGD("write_transact handle is:%llu", flat->handle); return flat->handle; } return 0; } void create_file_if_not_exist(char *path) { FILE *fp = fopen(path, "ab+"); if (fp) { fclose(fp); } } void notify_and_waitfor(const char *observer_self_path, const char *observer_daemon_path) { int observer_self_descriptor = open(observer_self_path, O_RDONLY | O_LARGEFILE); LOGD("open [%s] : %d", observer_self_path, observer_self_descriptor); if (observer_self_descriptor == -1) { observer_self_descriptor = open(observer_self_path, O_CREAT, S_IRUSR | S_IWUSR); LOGD("open [%s] : %d", observer_self_path, observer_self_descriptor); } while (open(observer_daemon_path, O_RDONLY | O_LARGEFILE) == -1) { usleep(1000); } remove(observer_daemon_path); LOGI("Watched >>>>OBSERVER<<<< has been ready..."); } int lock_file(const char *lock_file_path) { LOGD("start try to lock file >> %s <<", lock_file_path); int lockFileDescriptor = open(lock_file_path, O_RDONLY | O_LARGEFILE); LOGD("open [%s] : %d", lock_file_path, lockFileDescriptor); if (lockFileDescriptor == -1) { lockFileDescriptor = open(lock_file_path, O_CREAT, S_IRUSR | S_IWUSR); LOGD("open [%s] : %d", lock_file_path, lockFileDescriptor); } int lockRet = flock(lockFileDescriptor, LOCK_EX | LOCK_NB); LOGD("flock [%s:%d] : %d", lock_file_path, lockFileDescriptor, lockRet); if (lockRet == -1) { LOGE("lock file failed >> %s <<", lock_file_path); return 0; } else { LOGD("lock file success >> %s <<", lock_file_path); return 1; } } void java_callback(JNIEnv *env, jobject thiz, char *method_name) { jclass cls = env->GetObjectClass(thiz); jmethodID cb_method = env->GetMethodID(cls, method_name, "()V"); env->CallVoidMethod(thiz, cb_method); } void do_daemon(JNIEnv *env, jclass jclazz, const char *indicator_self_path, const char *indicator_daemon_path, const char *observer_self_path, const char *observer_daemon_path, const char *pkgName, const char *serviceName, int sdk_version, uint32_t transact_code) { int lock_status = 0; int try_time = 0; while (try_time < 5 && !(lock_status = lock_file(indicator_self_path))) { try_time++; LOGD("Persistent lock myself failed and try again as %d times", try_time); usleep(10000); } if (!lock_status) { LOGE("Persistent lock myself failed and exit"); return; } notify_and_waitfor(observer_self_path, observer_daemon_path); int pid = getpid(); // 1.获取service_manager, handle=0 // 根据BpBinder(C++)生成BinderProxy(Java)对象. 主要工作是创建BinderProxy对象,并把BpBinder对象地址保存到BinderProxy.mObject成员变量 // ServiceManagerNative.asInterface(BinderInternal.getContextObject()) = ServiceManagerNative.asInterface(new BinderProxy()) // ServiceManagerNative.asInterface(new BinderProxy()) = new ServiceManagerProxy(new BinderProxy()) // sp<IBinder> b = ProcessState::self()->getContextObject(NULL); // BpBinder // flatten_binder 将Binder对象扁平化,转换成flat_binder_object对象。 // BpBinder *proxy = binder->remoteBinder(); // const int32_t handle = proxy ? proxy->handle() : 0; // 2.获取activity服务 // IBinder在Java层已知 // mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0); // 得到binder_transaction_data结构体 // 参考native实现,获取不到则循环5次 int mDriverFD = open_driver(); void *mVMStart = MAP_FAILED; initProcessState(mDriverFD, mVMStart); uint32_t handle = get_service("activity", mDriverFD); Parcel *data = new Parcel; LOGD("writeService %s %s", pkgName, serviceName); // writeService(*data, pkgName, serviceName, sdk_version); // com.boolbird.keepalive com.boolbird.keepalive.demo.Service1 writeService(*data, pkgName, serviceName, sdk_version); LOGD("Watch >>>>to lock_file<<<<< !!"); lock_status = lock_file(indicator_daemon_path); if (lock_status) { LOGE("Watch >>>>DAEMON<<<<< Dead !!"); status_t status = write_transact(handle, transact_code, *data, NULL, 1, mDriverFD); LOGD("writeService result is %d", status); // int result = binder.get()->transact(code, parcel, NULL, 1); remove(observer_self_path);// it`s important ! to prevent from deadlock // java_callback(env, thiz, DAEMON_CALLBACK_NAME); if (pid > 0) { killpg(pid, SIGTERM); } } delete data; } bool wait_file_lock(const char *lock_file_path) { int lockFileDescriptor = open(lock_file_path, O_RDONLY | O_LARGEFILE); if (lockFileDescriptor == -1) lockFileDescriptor = open(lock_file_path, O_CREAT, S_IRUSR | S_IWUSR); // int try_time = 0; while (/*try_time < 5 && */flock(lockFileDescriptor, LOCK_EX | LOCK_NB) != -1) { // ++try_time; // LOGD("wait [%s:%d] lock retry: %d", lock_file_path, lockFileDescriptor, try_time); usleep(1000); } int err_no = flock(lockFileDescriptor, LOCK_EX); LOGD("flock [%s:%d] : %d", lock_file_path, lockFileDescriptor, err_no); bool ret = err_no != -1; if (ret) { LOGD("success to lock file >> %s <<", lock_file_path); } else { LOGD("failed to lock file >> %s <<", lock_file_path); } LOGD("retry lock file >> %s << %d", lock_file_path, err_no); return ret; } void keep_alive_set_sid(JNIEnv *env, jclass jclazz) { setsid(); } void keep_alive_wait_file_lock(JNIEnv *env, jclass jclazz, jstring path) { const char *file_path = (char *) env->GetStringUTFChars(path, 0); wait_file_lock(file_path); } void keep_alive_lock_file(JNIEnv *env, jclass jclazz, jstring lockFilePath) { const char *lock_file_path = (char *) env->GetStringUTFChars(lockFilePath, 0); lock_file(lock_file_path); } void keep_alive_do_daemon(JNIEnv *env, jclass jclazz, jstring indicatorSelfPath, jstring indicatorDaemonPath, jstring observerSelfPath, jstring observerDaemonPath, jstring packageName, jstring serviceName, jint sdk_version) { if (indicatorSelfPath == NULL || indicatorDaemonPath == NULL || observerSelfPath == NULL || observerDaemonPath == NULL) { LOGE("parameters cannot be NULL !"); return; } uint32_t transact_code = 0; switch (sdk_version) { case 26: case 27: transact_code = 26; break; case 28: transact_code = 30; break; case 29: transact_code = 24; break; default: transact_code = 34; break; } char *indicator_self_path = (char *) env->GetStringUTFChars(indicatorSelfPath, 0); char *indicator_daemon_path = (char *) env->GetStringUTFChars(indicatorDaemonPath, 0); char *observer_self_path = (char *) env->GetStringUTFChars(observerSelfPath, 0); char *observer_daemon_path = (char *) env->GetStringUTFChars(observerDaemonPath, 0); char *pkgName = (char *) env->GetStringUTFChars(packageName, 0); char *svcName = (char *) env->GetStringUTFChars(serviceName, 0); LOGD("indicator_self_path: %s, indicator_daemon_path: %s, observer_self_path: %s, " "observer_daemon_path: %s, pkgName: %s, svcName: %s", indicator_self_path, indicator_daemon_path, observer_self_path, observer_daemon_path, pkgName, svcName); pid_t pid; if ((pid = fork()) < 0) { LOGE("fork 1 error\n"); exit(-1); } else if (pid == 0) { //第一个子进程 if ((pid = fork()) < 0) { LOGE("fork 2 error\n"); exit(-1); } else if (pid > 0) { // 托孤 exit(0); } LOGD("mypid: %d", getpid()); const int MAX_PATH = 256; char indicator_self_path_child[MAX_PATH]; char indicator_daemon_path_child[MAX_PATH]; char observer_self_path_child[MAX_PATH]; char observer_daemon_path_child[MAX_PATH]; strcpy(indicator_self_path_child, indicator_self_path); strcat(indicator_self_path_child, "-c"); strcpy(indicator_daemon_path_child, indicator_daemon_path); strcat(indicator_daemon_path_child, "-c"); strcpy(observer_self_path_child, observer_self_path); strcat(observer_self_path_child, "-c"); strcpy(observer_daemon_path_child, observer_daemon_path); strcat(observer_daemon_path_child, "-c"); create_file_if_not_exist(indicator_self_path_child); create_file_if_not_exist(indicator_daemon_path_child); set_process_name(env); // 直接传递parcel,会导致监听不到进程被杀;改成传输u8*数据解决了 do_daemon(env, jclazz, indicator_self_path_child, indicator_daemon_path_child, observer_self_path_child, observer_daemon_path_child, pkgName, svcName, sdk_version, transact_code); } if (waitpid(pid, NULL, 0) != pid) LOGE("Oops!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! waitpid error"); LOGD("do_daemon pid=%d ppid=%d", getpid(), getppid()); do_daemon(env, jclazz, indicator_self_path, indicator_daemon_path, observer_self_path, observer_daemon_path, pkgName, svcName, sdk_version, transact_code); } void keep_alive_test(JNIEnv *env, jclass jclazz, jstring packageName, jstring serviceName, jint sdk_version) { int mDriverFD = open_driver(); void *mVMStart = MAP_FAILED; initProcessState(mDriverFD, mVMStart); uint32_t handle = get_service("activity", mDriverFD); // get_service("sensor"); // get_service("power"); // get_service("storage"); // get_service("phone"); char *pkgName = (char *) env->GetStringUTFChars(packageName, 0); char *svcName = (char *) env->GetStringUTFChars(serviceName, 0); Parcel *data = new Parcel; writeService(*data, pkgName, svcName, sdk_version); uint32_t transact_code = 0; switch (sdk_version) { case 26: case 27: transact_code = 26; break; case 28: transact_code = 30; break; case 29: transact_code = 24; break; default: transact_code = 34; break; } status_t status = write_transact(handle, transact_code, *data, NULL, 1, mDriverFD); LOGD("writeService result is %d", status); delete data; unInitProcessState(mDriverFD, mVMStart); } } static JNINativeMethod methods[] = { {"lockFile", "(Ljava/lang/String;)V", (void *) keep_alive_lock_file}, {"nativeSetSid", "()V", (void *) keep_alive_set_sid}, {"waitFileLock", "(Ljava/lang/String;)V", (void *) keep_alive_wait_file_lock}, {"doDaemon", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V", (void *) keep_alive_do_daemon}, {"test", "(Ljava/lang/String;Ljava/lang/String;I)V", (void *) keep_alive_test} }; static int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *gMethods, int numMethods) { jclass clazz = env->FindClass(className); if (clazz == NULL) { return JNI_FALSE; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { return JNI_FALSE; } return JNI_TRUE; } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env = NULL; LOGI("###### JNI_OnLoad ######"); if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { return -1; } if (!registerNativeMethods(env, JAVA_CLASS, methods, sizeof(methods) / sizeof(methods[0]))) { return -1; } return JNI_VERSION_1_6; }
60321b1b37167b8b6a42aaaf4f2d522eaf120470
a2111a80faf35749d74a533e123d9da9da108214
/raw/pmsb13/pmsb13-data-20130530/sources/b26wz51ypvk5m3bf/2013-04-09T15-40-11.953+0200/sandbox/my_sandbox/apps/first_app/first_app.cpp
d5ad30f75bcad81bcbf7be6b8807df28bd7e4e64
[ "MIT" ]
permissive
bkahlert/seqan-research
f2c550d539f511825842a60f6b994c1f0a3934c2
21945be863855077eec7cbdb51c3450afcf560a3
refs/heads/master
2022-12-24T13:05:48.828734
2015-07-01T01:56:22
2015-07-01T01:56:22
21,610,669
1
0
null
null
null
null
UTF-8
C++
false
false
1,320
cpp
#include <iostream> #include <seqan/sequence.h> #include <seqan/file.h> using namespace seqan; // Function to print simple alignment between two sequences with the same length // .. for two sequences of the same type template <typename TText> void printAlign(TText const & genomeFragment, TText const & read) { std::cout << "Alignment " << std::endl; std::cout << " genome : "; std::cout << genomeFragment << std::endl; std::cout << " read : "; std::cout << read << std::endl; } int main() { // We have given a genome sequence Dna5String genome = "ATGGTTTCAACGTAATGCTGAACATGTCGCGT"; // A read sequence Dna5String read = "TGGTNTCA"; // And the begin position of a given alignment between the read and the genome unsigned beginPosition = 1; Dna5String genomeFragment; // We have to create a copy of the corresponding fragment of the genome, where the read aligns to for (unsigned i = 0; i < length(read); ++i){ appendValue(genomeFragment, genome[beginPosition+i]); } // Call of our function to print the simple alignment printAlign(genomeFragment, read); String <int> test1; appendValue(test1, 1337); int test3 = 102; int * test2 = *test3; std::cout<<test2<<test1[0]<<'\n'; return 0; }
de65076061d28d291aea54d3104fff299d6718f8
0a851027d8b18c3440a824b76ab32d6fa9828445
/Lib-DeepLearning/DeepLearningNetwork.h
e74ed5c26fdc4c2cd6049d9af40ad6311ad512be
[]
no_license
Math-ss/Deep-Learning-Class
11de7e162f65d654902deef1f40dc71e2d93be24
d525b7f6a506546aaa454dc5e1ee63274b021dc6
refs/heads/master
2022-10-12T19:47:00.840281
2020-06-07T13:31:08
2020-06-07T13:31:08
212,854,647
0
0
null
null
null
null
UTF-8
C++
false
false
2,231
h
/* "DeepLearningNetwork.h" Created by Math's */ #pragma once #include <string> #include <ctype.h> #include "AI_Interface.h" /* Basic interface for a perceptron's network. -For back propagation see : class BackPropagationLearning -For genetical algorithm see: class GeneticalLearning */ class DeepLearningNetwork : public AI_Interface { public: /* If you need to extend this list, create the same enum (same type name) and add your constant at the end. (try to keep the same order) Override the necessary functions accordingly and add if necessary the correct activation functions (static). DON'T USE INHERITED CONSTRUCTOR(S) TO SET m_FActivation ! The copy construcor is safe (uses directly the type uint8_t) When you are outside the class, always use : YourClass::CONSTANT to avoid issues */ enum AIF_Activation { SIGMOIDE, TANGEANTE_HYPER }; protected: std::vector<std::vector<std::vector<float>>> m_weights; std::vector< std::vector<float>> m_biais; /* Activation value of each perceptron */ std::vector<std::vector<float>> m_perceptrons; int m_nbInput; int m_nbOutput; /* Network activation function */ uint8_t m_FActivation; public: DeepLearningNetwork(int inputLayer, int outputLayer, std::vector<int>& hiddenLayer, AIF_Activation FActivation = SIGMOIDE); DeepLearningNetwork(DeepLearningNetwork& source); /* Make a FeedForward */ virtual void computePrediction(TrainingParameters *param, std::vector<float> *input) override; /* Return the last percptron's layer : the Network's output layer. By const pointer */ virtual std::vector<float> const *getPredictionPtr() const override; /* Return the last percptron's layer : the Network's output layer. Return a copy or a const ref */ virtual std::vector<float> getPrediction() const override; /* Write all wheights in a info.wtw file *path -> the path with a / at the end */ virtual bool saveWeights(std::string path); /* Call the correct activation function (depends on m_FActivation) */ virtual float F_Activation(float value); /* Sigmoide activation function */ static float F_Sigmoide(float value); /* Hyperbolic tangeant activation function */ static float F_TangenteHyper(float value); };
b26ea2a9358111783a1fe10af6798409c29a374f
b93b75982b770dae63262bb5db05b78f835b8c67
/pc2vecvec.inl
984c071f7dcfe25430e9da80198d977656d2bbe8
[]
no_license
juliasanchez/registration_meanshift
812c97abe927fb095c75908f43473e955e297bdf
c5c0a505018f570ed2164d39a6d12b932035a543
refs/heads/master
2021-01-22T18:42:45.405532
2019-07-12T13:47:01
2019-07-12T13:47:01
85,105,681
0
0
null
null
null
null
UTF-8
C++
false
false
348
inl
void pc2vecvec(pcl::PointCloud<pcl::PointXYZ>::Ptr cloudin, std::vector< vector<double> >& vec) { vec.resize(cloudin->points.size()); for (int i=0; i<cloudin->points.size(); i++) { vec[i].resize(3); vec[i][0]=cloudin->points[i].x; vec[i][1]=cloudin->points[i].y; vec[i][2]=cloudin->points[i].z; } }
6b263efdcf0492f45af76b34fbdb4691d19e2189
4cbf15c4a5ab006c081ade42abdabcebc7df8708
/youtube/Tetris/Matrix.h
fc10775a68bef2372c66ff0ab6bc8a71ed7ea05d
[]
no_license
MiichaelD/c_cpp
85e2829ad1f0d56edcf43db34305503f2528d2d4
e26876b9c5a394cabc324b28dcad54016dc2e36f
refs/heads/master
2022-02-08T12:30:15.339033
2022-01-20T00:14:38
2022-01-20T00:14:38
53,229,953
1
0
null
null
null
null
UTF-8
C++
false
false
1,856
h
/* Description: Design the game of Tetris. Programmer: Michael Duarte Date: Sep 12, 2016. */ #include <iostream> #include <vector> template<class T> using Matrix = std::vector<std::vector<T>>; template<class T> Matrix<T> createMatrix(uint32_t size){ return Matrix<T>(size, std::vector<T>(size)); } template<class T> Matrix<T> createMatrix(uint32_t height, uint32_t width){ return Matrix<T>(height, std::vector<T>(width)); } template<class T> void rotateMatrix(std::vector<std::vector<T>> &matrix, bool clockwise = true){ int rowLimit = matrix.size() / 2; int colLimit = matrix.size(); int dim = matrix.size() - 1; if (clockwise == true){ for (int r = 0 ; r < rowLimit; ++r){ --colLimit; for (int c = r; c < colLimit; ++c){ T aux = matrix[r][c]; // copy top-left to aux matrix[r][c] = matrix[dim-c][r]; // copy bottom-left to top-left matrix[dim-c][r] = matrix[dim-r][dim-c]; // copy bottom-right to bottom-left matrix[dim-r][dim-c] = matrix[c][dim-r]; // copy top-right to bottom right matrix[c][dim-r] = aux; // copy aux to top-right } } } else { for (int r = 0 ; r < rowLimit; ++r){ --colLimit; for (int c = r; c < colLimit; ++c){ T aux = matrix[r][c]; // copy top-left to aux matrix[r][c] = matrix[c][dim-r];//copy top-right to top-left matrix[c][dim-r] = matrix[dim-r][dim-c];//copy bottom-right to top-right matrix[dim-r][dim-c] = matrix[dim-c][r]; //copy bottom-left to bottom-right matrix[dim-c][r] = aux; // copy aux to bottom-left } } } } template<class T> void printMatrix(const std::vector<std::vector<T>> &matrix){ if (matrix.size()){ for (int r = 0; r < matrix.size(); ++r){ int colLimit = matrix[r].size(); for (int c = 0; c < colLimit; ++c){ std::cout << (c == 0 ? "" : " " ) << matrix[r][c]; } std::cout << std::endl; } } }
143e7bdf7b48f69cacffd7084d62f460e59b5143
4960b53fd44b6f6e58c4ca150d90d10492de46aa
/student.h
a97210d1ad614c3f5422a30e169fff0dbd3d35c8
[]
no_license
paulthomasjerome/CPP-student-roster-system
0c5c0298f9ee51f3aade30c714bc7dfda6f5a4e7
8d2543c8e0f54c80274e3ff0f6ccd577b708cf13
refs/heads/master
2022-11-17T14:53:45.771105
2020-07-15T21:33:54
2020-07-15T21:33:54
279,983,919
0
0
null
null
null
null
UTF-8
C++
false
false
1,149
h
#pragma once #include "degree.h" #include <string> using std::string; class Student { protected: string studentId; string firstName; string lastName; string emailAddress; int age; int* daysToCompleteCourse; Degree degreeProgram; public: Student(); Student( string studentId, string firstName, string lastName, string emailAddress, int age, int daysToCompleteCourse[] ); string getStudentId() const; void setStudentId(string studentID); string getFirstName() const; void setFirstName(string firstName); string getLastName() const; void setLastName(string lastName); string getEmailAddress() const; void setEmailAddress(string emailAddress); int getAge() const; void setAge(int age); int* getDaysToCompleteCourse(); void setDaysToCompleteCourse(int daysToCompleteCourse[]); virtual void print() = 0; ~Student(); virtual Degree getDegreeProgram() = 0; };
b42197d4a974a625659a95daed999ab9f9aa25c2
cdab2ef737a481a92fee3e08bbdb7227adbb4259
/diagnostics/cros_healthd/fetchers/storage/device_info.cc
e579c5f9cd712d490db492c5d980a18e40f785ee
[ "BSD-3-Clause" ]
permissive
manduSry/platform2
a2c1c829e45356b920e6c7ba546324e6d6decfdf
58ede23d2f4cd5651b7afaae5c78893cc836f01d
refs/heads/main
2023-04-06T19:06:50.384147
2020-12-30T04:41:55
2021-01-20T04:53:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,568
cc
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "diagnostics/cros_healthd/fetchers/storage/device_info.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <base/files/file_path.h> #include <base/files/file_util.h> #include <base/optional.h> #include <base/strings/string_number_conversions.h> #include <base/strings/string_split.h> #include "diagnostics/common/status_macros.h" #include "diagnostics/common/statusor.h" #include "diagnostics/cros_healthd/fetchers/storage/caching_device_adapter.h" #include "diagnostics/cros_healthd/fetchers/storage/default_device_adapter.h" #include "diagnostics/cros_healthd/fetchers/storage/disk_iostat.h" #include "diagnostics/cros_healthd/fetchers/storage/emmc_device_adapter.h" #include "diagnostics/cros_healthd/fetchers/storage/nvme_device_adapter.h" #include "diagnostics/cros_healthd/fetchers/storage/storage_device_adapter.h" #include "diagnostics/cros_healthd/utils/error_utils.h" #include "diagnostics/cros_healthd/utils/file_utils.h" #include "mojo/cros_healthd_probe.mojom.h" namespace diagnostics { namespace { namespace mojo_ipc = ::chromeos::cros_healthd::mojom; // Creates a specific adapter for device's data retrieval. std::unique_ptr<StorageDeviceAdapter> CreateDeviceSpecificAdapter( const base::FilePath& dev_sys_path, const std::string& subsystem) { // A particular device has a chain of subsystems it belongs to. We pass them // here in a colon-separated format (e.g. "block:mmc:mmc_host:pci"). We expect // that the root subsystem is "block", and the type of the block device // immediately follows it. constexpr char kBlockSubsystem[] = "block"; constexpr char kNvmeSubsystem[] = "nvme"; constexpr char kMmcSubsystem[] = "mmc"; constexpr int kBlockSubsystemIndex = 0; constexpr int kBlockTypeSubsystemIndex = 1; constexpr int kMinComponentLength = 2; auto subs = base::SplitString(subsystem, ":", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); if (subs.size() < kMinComponentLength || subs[kBlockSubsystemIndex] != kBlockSubsystem) return nullptr; if (subs[kBlockTypeSubsystemIndex] == kNvmeSubsystem) return std::make_unique<NvmeDeviceAdapter>(dev_sys_path); if (subs[kBlockTypeSubsystemIndex] == kMmcSubsystem) return std::make_unique<EmmcDeviceAdapter>(dev_sys_path); return std::make_unique<DefaultDeviceAdapter>(dev_sys_path); } // Creates a device-specific adapter and wraps it into a caching decorator. std::unique_ptr<StorageDeviceAdapter> CreateAdapter( const base::FilePath& dev_sys_path, const std::string& subsystem) { auto adapter = CreateDeviceSpecificAdapter(dev_sys_path, subsystem); if (!adapter) return nullptr; return std::make_unique<CachingDeviceAdapter>(std::move(adapter)); } } // namespace StorageDeviceInfo::StorageDeviceInfo( const base::FilePath& dev_sys_path, const base::FilePath& dev_node_path, const std::string& subsystem, mojo_ipc::StorageDevicePurpose purpose, std::unique_ptr<StorageDeviceAdapter> adapter, const Platform* platform) : dev_sys_path_(dev_sys_path), dev_node_path_(dev_node_path), subsystem_(subsystem), purpose_(purpose), adapter_(std::move(adapter)), platform_(platform), iostat_(dev_sys_path) { DCHECK(adapter_); DCHECK(platform_); } std::unique_ptr<StorageDeviceInfo> StorageDeviceInfo::Create( const base::FilePath& dev_sys_path, const base::FilePath& dev_node_path, const std::string& subsystem, mojo_ipc::StorageDevicePurpose purpose, const Platform* platform) { auto adapter = CreateAdapter(dev_sys_path, subsystem); if (!adapter) return nullptr; return std::unique_ptr<StorageDeviceInfo>( new StorageDeviceInfo(dev_sys_path, dev_node_path, subsystem, purpose, std::move(adapter), platform)); } Status StorageDeviceInfo::PopulateDeviceInfo( mojo_ipc::NonRemovableBlockDeviceInfo* output_info) { DCHECK(output_info); output_info->path = dev_node_path_.value(); output_info->type = subsystem_; output_info->purpose = purpose_; ASSIGN_OR_RETURN(output_info->size, platform_->GetDeviceSizeBytes(dev_node_path_)); ASSIGN_OR_RETURN(output_info->name, adapter_->GetModel()); // Returns mojo objects. ASSIGN_OR_RETURN(auto vendor, adapter_->GetVendorId()); ASSIGN_OR_RETURN(auto product, adapter_->GetProductId()); ASSIGN_OR_RETURN(auto revision, adapter_->GetRevision()); ASSIGN_OR_RETURN(auto fwversion, adapter_->GetFirmwareVersion()); output_info->vendor_id = vendor.Clone(); output_info->product_id = product.Clone(); output_info->revision = revision.Clone(); output_info->firmware_version = fwversion.Clone(); RETURN_IF_ERROR(iostat_.Update()); ASSIGN_OR_RETURN(uint64_t sector_size, platform_->GetDeviceBlockSizeBytes(dev_node_path_)); output_info->read_time_seconds_since_last_boot = static_cast<uint64_t>(iostat_.GetReadTime().InSeconds()); output_info->write_time_seconds_since_last_boot = static_cast<uint64_t>(iostat_.GetWriteTime().InSeconds()); output_info->io_time_seconds_since_last_boot = static_cast<uint64_t>(iostat_.GetIoTime().InSeconds()); auto discard_time = iostat_.GetDiscardTime(); if (discard_time.has_value()) { output_info->discard_time_seconds_since_last_boot = mojo_ipc::NullableUint64::New( static_cast<uint64_t>(discard_time.value().InSeconds())); } // Convert from sectors to bytes. output_info->bytes_written_since_last_boot = sector_size * iostat_.GetWrittenSectors(); output_info->bytes_read_since_last_boot = sector_size * iostat_.GetReadSectors(); return Status::OkStatus(); } void StorageDeviceInfo::PopulateLegacyFields( mojo_ipc::NonRemovableBlockDeviceInfo* output_info) { DCHECK(output_info); constexpr char kLegacySerialFile[] = "device/serial"; constexpr char kLegacyManfidFile[] = "device/manfid"; // Not all devices in sysfs have a serial, so ignore the return code. ReadInteger(dev_sys_path_, kLegacySerialFile, &base::HexStringToUInt, &output_info->serial); uint64_t manfid = 0; if (ReadInteger(dev_sys_path_, kLegacyManfidFile, &base::HexStringToUInt64, &manfid)) { DCHECK_EQ(manfid & 0xFF, manfid); output_info->manufacturer_id = manfid; } } } // namespace diagnostics
2661da5fd3631cfaf83bdaf7dc39f90ce73c15c6
970f82502796e30c59ae96eb65ca1f9433ab6a1c
/HackerEarth/tree/1.cpp
089810cb694342cd8d9dee1630115cab44cf8903
[]
no_license
sivsnkr/CommonCoding
80201389974796f342ba4c1943785e331b2880b9
adbeaee290735158b5a705c37c68680517930c7c
refs/heads/master
2021-01-04T13:18:07.542084
2020-04-05T13:34:02
2020-04-05T13:34:02
240,567,824
1
0
null
null
null
null
UTF-8
C++
false
false
1,207
cpp
#include <bits/stdc++.h> using namespace std; int get_result(vector<int> v[], unordered_set<int> &dir_to_d, int size) { int counter = 0; int i; for (i = 0; i < size; i++) { if (v[i].size() > 0 && dir_to_d.find(v[i].front()) != dir_to_d.end()) { counter++; dir_to_d.erase(v[i].front()); int j; for (j = 1; j < v[i].size(); j++) { if (dir_to_d.find(v[i].at(j)) != dir_to_d.end()) dir_to_d.erase(v[i].at(j)); } } if (dir_to_d.size() == 0) break; } return counter; } int main() { int n; cin >> n; vector<int> graph[n]; int i; cin >> i; for (i = 0; i < n - 1; i++) { int value; cin >> value; if (graph[i + 1].size() == 0) { graph[i + 1].push_back(i + 1); } graph[value - 1].push_back(i + 1); } unordered_set<int> dir_to_d; int q; cin >> q; for (i = 0; i < q; i++) { int value; cin >> value; dir_to_d.insert(value - 1); } int res = get_result(graph, dir_to_d, n); cout << res << endl; }
55422a3b041224c658cf9fc470ce16f63a851afd
66263a415339473ad1f4f9e32cc102b9d23fdc37
/CodeChef/March Long 2021/Interesting_XOR_.cpp
4f84fe7f4a96811a1bdd39ab584972b0a656a920
[]
no_license
leetcode-notes/Competitive-Programming-2
b08b3e4dd437e2d146cb90522713821a4852a5fe
c0efb523340d09a901c53b33b40875d102108768
refs/heads/master
2023-04-03T22:31:13.628879
2021-04-19T13:34:11
2021-04-19T13:34:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,010
cpp
//------------------------------------------------------------------------------ #include <iostream> #include <vector> // #include <bits/stdc++.h> // #include <cmath> // #include <algorithm> // #include <unordered_map> // #include <map> // #include <set> // #include <unordered_set> //------------------------------------------------------------------------------ using namespace std; //------------------------------------------------------------------------------ #define FastIO ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); #define v(Type) vector<Type> #define w(T) \ int T; \ cin >> T; \ while (T--) #define int long long int #define mod 1000000007ll #define endl "\n" //------------------------------------------------------------------------------ // Any fucntion can be called using Math.function_name(); //------------------------------------------------------------------------------ class Math { public: //Returns gcd of two numbers int gcd(int a, int b) { return (a % b == 0) ? b : gcd(b, a % b); } //Returns lcm of two numbers int lcm(int a, int b) { return a * (b / gcd(a, b)); } // Returns flag array isPrime // isPrime[i] = true (if i is Prime) // isPrime[i] = false (if i is not Prime) vector<bool> *seiveOfEratosthenes(const int N) { vector<bool> *isPrime = new vector<bool>(N + 1, true); (*isPrime)[0] = (*isPrime)[1] = false; for (int i = 2; i * i <= N; ++i) if ((*isPrime)[i]) for (int j = i * i; j <= N; j += i) (*isPrime)[j] = false; return isPrime; } //Returns (x ^ n) int pow(const int &x, int n) { if (n == 0) return 1; int h = pow(x, n / 2); return (n & 1) ? h * h * x : h * h; } //Returns (x ^ n) % M int pow(const int &x, int n, const int &M) { if (n == 0) return 1; int h = pow(x, n / 2) % M; return (n & 1) ? (h * h * x) % M : (h * h) % M; } //Returns all Primes <= N vector<int> *primesUptoN(const int N) { vector<bool> *isPrime = seiveOfEratosthenes(N); vector<int> *Primes = new vector<int>; if (2 <= N) (*Primes).push_back(2); for (int i = 3; i <= N; i += 2) if ((*isPrime)[i]) (*Primes).push_back(i); return Primes; } } Math; //------------------------------------------------------------------------------ int countBits(int n) { int ans = 0; while (n) { n >>= 1; ans++; } return ans; } void solve() { int n; cin >> n; int a = (1 << (countBits(n) - 1)) - 1; cout << a * (a ^ n) << endl; } //------------------------------------------------------------------------------ int32_t main() { FastIO; w(T) solve(); return 0; } //------------------------------------------------------------------------------
29313d24b71ce07f3413ec029b91b63dc0321a41
7f45fa54386a7e2bb86b4bcfb04ff0a31d63703c
/algorithms/0375/getMoneyAmount.cpp
7d6824c9c2ad1ab2329ddd2022193620aca40f0e
[]
no_license
ejunjsh/leetcode
e3ca7e30eea89dd345b286264bd64695e5faaf73
5aa8d70939acd9180c1e8d351a72b2cfcd4ff04f
refs/heads/master
2021-08-31T22:19:20.522206
2021-08-25T07:47:47
2021-08-25T07:47:47
160,124,292
4
1
null
null
null
null
UTF-8
C++
false
false
563
cpp
class Solution { public: int getMoneyAmount(int n) { vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0)); for (int i = 2; i <= n; ++i) { for (int j = i - 1; j > 0; --j) { int global_min = INT_MAX; for (int k = j + 1; k < i; ++k) { int local_max = k + max(dp[j][k - 1], dp[k + 1][i]); global_min = min(global_min, local_max); } dp[j][i] = j + 1 == i ? j : global_min; } } return dp[1][n]; } };
369699f7a6772925e507423bcbc84f11b18cab49
62fce069bf1f730a95ee88ebe86e8538a7363283
/rjesenje/SpaDz2/zadatak2/Tocka.h
2868e9a9039fac010c3787b356f1e2619d018068
[]
no_license
LeaRezic/spa2017dz2
5c2463d75d117d4bcedaecdf687fb20e2eff8b74
5597c2a3ecca943eeea0ab67b2342351f446eb34
refs/heads/master
2021-01-25T11:54:57.915620
2017-06-11T14:15:38
2017-06-11T14:15:38
93,950,427
0
0
null
2017-06-10T16:06:29
2017-06-10T16:06:29
null
UTF-8
C++
false
false
145
h
#ifndef TOCKA_H_ #define TOCKA_H_ #include <iostream> using namespace std; struct Tocka { int x; int y; }; #endif // !TOCKA_H_
979bf57df6766d6529eb9a5e894172c187b3897d
406ce23771eda2a64efcf41cce28a31e6c7ecd87
/BOJ/1316.CPP
f57c5555c845fc705dbb2923a090872d369db7a0
[]
no_license
ypd01018/Algorithm
53d22c9f30e9025af25401718066c73200a6bcb2
8382f3adb6f84620d929fcac128cc49fba2f7b6e
refs/heads/master
2023-06-08T14:25:19.104589
2021-06-30T23:19:58
2021-06-30T23:19:58
324,764,846
0
0
null
null
null
null
UTF-8
C++
false
false
548
cpp
#include<bits/stdc++.h> #define endl "\n" using namespace std; string a; int N,idx[102],cnt; void sol() { cin >> a; for(int i=0;i<a.size();i++) { int alp = a[i]-'a'; if(idx[alp]==-1) { idx[alp]=i; continue; } if(idx[alp]== i-1) idx[alp]=i; else return; } cnt++; } int main() { ios::sync_with_stdio(0);cin.tie(0); cin >> N; for(int i=0;i<N;i++) { a.clear(); memset(idx,-1,sizeof(idx)); sol(); } cout << cnt; }
3e694f4822c89688f5577fc69fbaee786c51442e
13a597702f0ead2af27152c16cc9bb4892c99dc5
/src/imp/gstreamer/CGstElement.hpp
7b3618ab08bff092b6b8c007792b6c5e0bd3a497
[ "MIT" ]
permissive
Glebka/jenkins-vr
56d9b2a33e7bee70b8785bbe7a941b04254b1e26
06583872142a90a6bbf30e2322bb2cd3b15b5fca
refs/heads/master
2021-01-21T04:33:24.775187
2016-07-25T20:35:06
2016-07-25T20:35:06
54,278,259
1
0
null
null
null
null
UTF-8
C++
false
false
3,784
hpp
/************************************************************************* * jenkins-vr ************************************************************************* * @file CGstElement.hpp * @date 16.07.16 * @author Hlieb Romanov * @brief Base class for all gstreamer element wrappers ************************************************************************/ #pragma once #include <string> #include "CGstPad.hpp" /** * Base class for all GStreamer element wrapper classes. */ class CGstElement { public: CGstElement( void ); virtual ~CGstElement( void ); /** * Construct element from the factory name for example "audiotestsrc" */ explicit CGstElement( const std::string& factoryName ); /** * Wrap raw GstElement pointer. * @param element - raw pointer * @param takeOwnership - if set to true does not make ref() on raw pointer */ explicit CGstElement( GstElement* element, bool takeOwnership = false ); CGstElement( const CGstElement& other ); virtual CGstElement& operator=( CGstElement other ); friend void swap( CGstElement& first, CGstElement& second ); bool isValid( void ) const { return ( mElement != NULL ); } /** * Get name of this element */ std::string getName( void ) const; /** * Link this element to another one. */ virtual bool link( CGstElement& other ); /** * Unlink this element from another one */ virtual void unlink( CGstElement& other ); /** * Get source pad of this element ( if exists ). * Don't forget to check pad.isValid(), because some elements don't have src pads. * @return source pad of the element. */ virtual CGstPad& getSrcPad( void ); /** * Get sink pad of this element ( if exists ). * Don't forget to check pad.isValid(), because some elements don't have sink pads. * @return sink pad of the element */ virtual CGstPad& getSinkPad( void ); /** * Send event to this element * @param event - raw GStreamer event pointer * @return true if event was handled */ bool sendEvent( GstEvent* event ); /** * Set the state of this element. * @param state - the value from GstState enum * @param async - if set to true this method will return immediately * without waiting for the actual state change. */ bool setState( GstState state, bool async = false ); /** * Get the state of this element. * Warning! It may take some time if this method is * called when the element is doing the state change async. * @return state of this element */ GstState getState( void ) const; /** * Check whether the element is in specified state or not. */ bool isInState( GstState state ) const; /** * Get raw GStreamer element pointer */ GstElement* raw( void ) { return mElement; } /** * Get the element property value. * @param propertyName - the name of the property * @return property value */ template <typename T> T getProperty( const std::string& propertyName ) const { T propValue = NULL; g_object_get( G_OBJECT( mElement ), propertyName.c_str(), &propValue, NULL ); return propValue; } /** * Set the property value * @param propertyName - the property name * @param propertyValue - the property value */ template <typename T> void setProperty( const std::string& propertyName, T propertyValue ) { g_object_set( G_OBJECT( mElement ), propertyName.c_str(), propertyValue, NULL ); } private: /** * Helper method to get the element name. */ void extractName( void ); private: GstElement* mElement; CGstPad mSrcPad; CGstPad mSinkPad; std::string mName; };
fb7f50276e7a1238cc75915c17ca0f67ed69e5fa
b069829f0c181e40ecafb7dd333cdf50105e9de5
/tetris_ai/tetrisgame.h
9680d9e0519f7b5565edf5e8871b80d52f095114
[]
no_license
jezevec10/MisaMinoBot
bb045578d8d1a4412c04d07333ff2197acbcd440
254d55534d87c22d878acb8898f5c7c7b87ac378
refs/heads/master
2021-01-01T04:54:15.279553
2019-08-26T21:43:29
2019-08-26T21:43:29
97,270,642
10
6
null
null
null
null
UTF-8
C++
false
false
8,464
h
#pragma once #include <time.h> #include <vector> #include <string> #include <algorithm> #include "tetris.h" #include "tetris_ai.h" #include "tetris_setting.h" class TetrisGame : public AI::Tetris { public: TetrisGame() { m_base = AI::point(0, 30); m_size = AI::point(20, 20); hold = true; ai_movs_flag = -1; reset((unsigned)time(0)); ai_delay = 0; mov_llrr = 0; env_change = 0; n_win = 0; last_max_combo = 0; m_lr = 0; pAIName = NULL; pTetrisAI = NULL; AI::AI_Param param = { // 18, 37, 11, 12, 9, 2, -30, -36, -14, 0, 8, -2, 9, // 21, 30, -4, 9, 0, 5, -22, -6, -12, 9, 4, -3, 14 // 16, 29, 7, 7, 50, 6, -23, -24, -4, 9, 6, 60, 13 // 16, 29, 7, 7, 50, 6, -23, -24, -4, 9, 6, 60, 7 // 21, 21, 19, 12, 10, 7, -17, -2, -3, 6, 9, 15, 15 // 19, 32, 14, 13, 3, 22, -18, -15, -14, 11, 11, 5, 33 // 21, 30, 15, 13, 5, -2, -15, -20, -14, 9, 7, 4, 25 // 21, 30, 15, 13, 5, -2, -15, -20, -14, 9, 7, 30, 25 // 17, 34, 28, 20, 57, 3, -10, 29, -72, 17, 10, 50, 27 // 9, 14, 7, 9, 9, 11, 11, 5, 13, 2, 8, 10, 13 // 8, 13, 11, 7, 7, 12, 6, 2, 12, 3, 10, 12, 18 // 8, 13, 11, 7, 7, 12, 6, 2, 12, 3, 10, 12, 18, 18 // 7, 29, 16, 13, 11, 19, 7, 7, 20, 6, 14, 13, 13, 13 // 12, 14, 8, 15, 8, 14, 8, 4, 19, 2, 14, 10, 11, 11 // 21, 27, 15, 6, 40, 8, 20, 6, 7, -6, 3, 16, 8, 8 // 19, 27, 14, 5, 17, 12, 19, 5, 11, -2, 3, 13, 10, 14 // 13, 53, 45, 17, 15, 11, 12, 5, 7, 4, 8, 17, 18, 3 // 17, 26, 18, 1, 9, 12, 16, 4, 16, -4, 11, 7, 11, 14 // 19, 25, 20, 6, 23, 13, 12, 3, 14, 5, 13, 10, 13, 26 // 11, 27, 21, 3, 28, 10, 17, 5, 20, -2, 11, 15, 31, 11 // 8, 26, 16, 5, 23, 12, 7, 5, 8, -8, 14, 15, 9, 18 // APL �� // 8, 26, 21, 7, 21, 12, 5, 5, 1, -3, 13, 11, 11, 4 // 13, 28, 21, 14, 25, 11, 21, 6, 8, -3, 13, 24, 31, 1 // 8, 26, 21, 7, 21, 12, 5, 5, 1, -3, 13, 11, 11, 4 // 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 10, 10, 10, 10, // 8, 22, 12, 9, 11, 6, 7, 5, 15, 2, 8, 7, 10, 16 // 12, 29, 22, 13, 28, 11, 17, 7, 20, -1, 15, 13, 26, 17 // 9, 28, 24, 10, 13, 12, 3, 3, 14, -3, 11, 28, 26, 9 // 8, 26, 21, 7, 21, 12, 5, 5, 20, -3, 13, 21, 11, 4 // 8, 38, 18, 13, -14, 19, 7, 4, 14, -15, 9, 19, 16, -3 // 5, 38, 20, 5, 8, 39, 7, 8, -13, -5, 4, 24, 7, -20 // 36, 34, 50, 8, 12, 12, 7, 10, 2, 6, 11, 10, 9, 6 // ���ڻ� // 22, 36, 56, 17, 17, 29, 6, 6, 6, 7, 18, 13, 8, 21 // 3, 34, 38, 12, 20, 16, 10, 7, 10, 10, 14, 35, 12, 0 // 26, 35, 45, 14, -2, 10, 6, 7, 4, 8, 13, 14, 8, 1 // 27, 43, 52, 9, 53, 8, 13, 11, 3, 0, 18, 11, 17, 20 // 32, 43, 60, 9, 8, 24, 13, 8, 2, 7, 20, 10, 13, 21 // 28, 41, 63, 8, 30, 9, 12, 10, -5, 6, 15, 9, 20, 21 // 43, 43, 64, 21, 43, 12, 10, 16, 20, 22, 0, 17, 57, 12 // 28, 41, 69, 28, 0, 16, 34, 12, 4, 21, 3, 0, 20, 14, 50 // 28, 41, 69, 28, 0, 16, 34, 12, 4, 21, 3, 12, 20, 14, 50, 1000 // 40, 32, 76, 16, 41, 17, 13, 21, 10, 21, 3, 21, 70, 17, 54 // 28, 41, 69, 28, 51, 16, 34, 12, 4, 21, 3, 12, 20, 14, 50, 0 // 47, 26, 70, 4, 46, 16, 26, 21, 7, 31, 14, 17, 69, 1, 43, 300 // 34, 18, 61, 9, 39, 13, 22, 13, -9, 38, 9, 15, 64, 9, 36, 300 // 47, 26, 70, 4, 46, 16, 26, 21, 7, 31, 14, 17, 69, 11, 53, 300 // 33, 25, 57, 19, 37, 11, 33, 10, 9, 38, 12, 13, 63, 11, 51, 300 // 37, 24, 50, 29, 53, 15, 26, 12, 13, 36, 11, 7, 69, 12, 53, 300 // 36, 25, 50, 20, 55, 15, 28, 12, 15, 36, 12, 10, 70, 12, 53, 300 // 40, 15, 50, 20, 56, 16, 17, 12, 7, 55, 99, 23, 78, 16, 67, 300 // 1.4.1 // 21, 20, 66, 40, 27, 22, 48, 26, 8, 71, 13, 24, 92, 7, 69, 300 // 49, 18, 76, 33, 39, 27, 32, 25, 22, 99, 41, 29, 96, 14, 60, 300 //1.4.3 // 40, 27, 65, 22, 37, 18, 66, 28, 9, 32, 4, 16, 93, 10, 27, 300, // 45, 28, 84, 21, 35, 27, 56, 30, 9, 64, 13, 18, 97, 11, 29, 300 //1.4.4 // 40, 20, 98, 13, 35, 22, 63, 29, 5, 68, 11, 15, 98, 14, 32, 300 // 44, 32, 96, 28, 42, 24, 49, 25, -6, 58, 17, 20, 51, 10, 32, 300 // 36, 20, 99, 27, 41, 32, 28, 24, 11, 56, 26, 24, 43, 14, 27, 300 //1.4.4 // 44, 13, 98, 31, 51, 30, 53, 27, 16, 56, 29, 27, 34, 16, 24, 300 // 36, 30, 71, 67, 72, 48, 22, 16, 34, 60, 0, 34, 46, 35, 16, 33 // test // 61, 33, 87, 52, 85, 30, 30, 28, 2, 71, 55, 51, 98, 35, 57, 60 // test //70, 16, 99, 50, 95, 33, 21, 29, 38, 98, 10, 54, 91, 26, 42, 65 //45, 28, 84, 11, 35, 27, 26, 30, 39, 64, 13, 18, 97, 11, 29, 300 //1.4.4 //13, 9, 17, 10, 29, 25, 39, 2, 12, 19, 7, 24, 21, 16, 14, 19, 20 26, 0, 20, 17, 45, 41, -8, 9, 10, 27, 15, 20, 19, 11, 44, 4, 300//,1183 }; if ( GAMEMODE_4W ) { //param.h_variance = 0; param.tspin = 0; param.tspin3 = 0; } m_ai_param = param; } void reset ( unsigned seed, unsigned pass = 0 ) { last_max_combo = m_max_combo; AI::Tetris::reset(seed, 10, 20); mov_llrr = 0; env_change = 0; ai_movs.movs.clear(); n_pieces = 0; ai_last_deep = 0; ai_movs_flag = -1; accept_atts.clear(); m_last_hole_x = -1; total_clears = 0; total_atts = 0; total_sent = 0; total_accept_atts = 0; m_ko = 0; m_att_info = ""; } bool tryXMove(int dx) { bool ret = Tetris::tryXMove( dx ); return ret; } bool tryXXMove(int dx) { bool ret = Tetris::tryXMove( dx ); while ( Tetris::tryXMove(dx) ) ; return ret; } bool tryYMove(int dy) { bool ret = Tetris::tryYMove( dy ); return ret; } bool tryYYMove(int dy) { bool ret = Tetris::tryYMove( dy ); while ( Tetris::tryYMove(dy) ) ; return ret; } bool trySpin(int dSpin) { bool ret = Tetris::trySpin( dSpin ); return ret; } bool trySpin180() { bool ret = Tetris::trySpin180( ); return ret; } bool tryHold() { bool ret = Tetris::tryHold( ); return ret; } bool drop() { bool ret = Tetris::drop( ); return ret; } void acceptAttack(int n) { int att[2] = {0}; for ( int i = 0; i < 32; i += 2) { att[0] |= 1 << i; } att[0] &= m_pool.m_w_mask; att[1] = ~att[0] & m_pool.m_w_mask; int rowdata = 5; while ( m_last_hole_x == rowdata ) { rowdata = 5; } m_last_hole_x = rowdata; rowdata = ~( 1 << rowdata ) & m_pool.m_w_mask; for ( ; n > 0; --n ) { if ( ATTACK_MODE == 0 ) addRow( 0 ); // ������ if ( ATTACK_MODE == 1 ) addRow( rowdata ); // TOP�� if ( ATTACK_MODE == 2 ) addRow( att[n&1] ); // ��ƴ�� ++total_accept_atts; } if ( alive() ) { if ( m_pool.isCollide(m_cur_x, m_cur_y, m_cur) ) { m_state = STATE_OVER; m_ko = 1; } } } public: bool hold; AI::Moving ai_movs; int ai_movs_flag; int ai_last_deep; int ai_delay; AI::AIName_t pAIName; AI::TetrisAI_t pTetrisAI; int mov_llrr; int env_change; int n_pieces; std::vector<int> accept_atts; int m_last_hole_x; int n_win; int total_clears; int total_atts; int total_sent; int total_accept_atts; int last_max_combo; int m_ko; int m_lr; // 3d��Ч���� int m_piecedelay; AI::AI_Param m_ai_param; std::string m_name; mutable std::string m_att_info; };
0ab45e4fc307e99fd1a5a1c2c030913227a1469e
3fc1ee94ebece7022c99d69cad39c3710487a74a
/chrome/common/chrome_features.cc
fa4bff8510a89e1efac1ce5220eb33e5bae7b90f
[ "BSD-3-Clause" ]
permissive
vseal001/chromium
b78653699caa6d54f45401ad0d9e3e90c160b8fb
474eca05898d2524072c2e3d962a866ddcfe37fc
refs/heads/master
2023-01-15T05:05:41.728378
2018-08-07T12:38:42
2018-08-07T12:38:42
143,872,860
0
1
null
2018-08-07T12:52:25
2018-08-07T12:52:25
null
UTF-8
C++
false
false
29,409
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_features.h" #include "base/command_line.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "extensions/buildflags/buildflags.h" #include "ppapi/buildflags/buildflags.h" namespace features { // All features in alphabetical order. // Enables Ads Metrics. const base::Feature kAdsFeature{"AdsMetrics", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_ANDROID) const base::Feature kAllowAutoplayUnmutedInWebappManifestScope{ "AllowAutoplayUnmutedInWebappManifestScope", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // defined(OS_ANDROID) #if defined(OS_MACOSX) // Enables the menu item for Javascript execution via AppleScript. const base::Feature kAppleScriptExecuteJavaScriptMenuItem{ "AppleScriptExecuteJavaScriptMenuItem", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables the "this OS is obsolete" infobar on Mac 10.9. // TODO(ellyjones): Remove this after the last 10.9 release. const base::Feature kShow10_9ObsoleteInfobar{"Show109ObsoleteInfobar", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables the fullscreen toolbar to reveal itself if it's hidden. const base::Feature kFullscreenToolbarReveal{"FullscreenToolbarReveal", base::FEATURE_ENABLED_BY_DEFAULT}; // Use the Toolkit-Views Task Manager window. const base::Feature kViewsTaskManager{"ViewsTaskManager", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_MACOSX) #if !defined(OS_ANDROID) const base::Feature kAnimatedAppMenuIcon{"AnimatedAppMenuIcon", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kAppBanners { "AppBanners", #if defined(OS_CHROMEOS) base::FEATURE_ENABLED_BY_DEFAULT, #else base::FEATURE_DISABLED_BY_DEFAULT, #endif // defined(OS_CHROMEOS) }; #endif // !defined(OS_ANDROID) #if defined(OS_ANDROID) // Enables messaging in site permissions UI informing user when notifications // are disabled for the entire app. const base::Feature kAppNotificationStatusMessaging{ "AppNotificationStatusMessaging", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_ANDROID) // If enabled, the list of content suggestions on the New Tab page will contain // assets (e.g. books, pictures, audio) that the user downloaded for later use. // DO NOT check directly whether this feature is enabled (i.e. do not use // base::FeatureList::IsEnabled()). It is enabled conditionally. Use // |AreAssetDownloadsEnabled| instead. const base::Feature kAssetDownloadSuggestionsFeature{ "NTPAssetDownloadSuggestions", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables the built-in DNS resolver. const base::Feature kAsyncDns { "AsyncDns", #if defined(OS_CHROMEOS) || defined(OS_MACOSX) || defined(OS_ANDROID) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; #if defined(OS_WIN) || defined(OS_MACOSX) // Enables automatic tab discarding, when the system is in low memory state. const base::Feature kAutomaticTabDiscarding{"AutomaticTabDiscarding", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // defined(OS_WIN) || defined(OS_MACOSX) #if defined(OS_WIN) || defined(OS_LINUX) // Enables the Restart background mode optimization. When all Chrome UI is // closed and it goes in the background, allows to restart the browser to // discard memory. const base::Feature kBackgroundModeAllowRestart{ "BackgroundModeAllowRestart", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_WIN) || defined(OS_LINUX) // Enables or disables whether permission prompts are automatically blocked // after the user has explicitly dismissed them too many times. const base::Feature kBlockPromptsIfDismissedOften{ "BlockPromptsIfDismissedOften", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables whether permission prompts are automatically blocked // after the user has ignored them too many times. const base::Feature kBlockPromptsIfIgnoredOften{ "BlockPromptsIfIgnoredOften", base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_MACOSX) // Enables the new bookmark app system (e.g. Add To Applications on Mac). const base::Feature kBookmarkApps{"BookmarkAppsMac", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Fixes for browser hang bugs are deployed in a field trial in order to measure // their impact. See crbug.com/478209. const base::Feature kBrowserHangFixesExperiment{ "BrowserHangFixesExperiment", base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_MACOSX) // Enables or disables the browser's touch bar. const base::Feature kBrowserTouchBar{"BrowserTouchBar", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // Enables or disables redirecting users who get an interstitial when // accessing https://support.google.com/chrome/answer/6098869 to local // connection help content. const base::Feature kBundledConnectionHelpFeature{ "BundledConnectionHelp", base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_MACOSX) // Enables or disables touch bar support for dialogs. const base::Feature kDialogTouchBar{"DialogTouchBar", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables or disables keyboard focus for the tab strip. const base::Feature kTabStripKeyboardFocus{"TabStripKeyboardFocus", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_MACOSX) #if !defined(OS_ANDROID) // Enables logging UKMs for background tab activity by TabActivityWatcher. const base::Feature kTabMetricsLogging{"TabMetricsLogging", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if defined(OS_MACOSX) // Enables the suggested text touch bar for autocomplete in textfields. const base::Feature kTextSuggestionsTouchBar{"TextSuggestionsTouchBar", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) // Enables the blocking of third-party modules. // Note: Due to a limitation in the implementation of this feature, it is // required to start the browser two times to fully enable or disable it. const base::Feature kThirdPartyModulesBlocking{ "ThirdPartyModulesBlocking", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #if (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_MACOSX) // Enables the dual certificate verification trial feature. // https://crbug.com/649026 const base::Feature kCertDualVerificationTrialFeature{ "CertDualVerificationTrial", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Enables change picture video mode. const base::Feature kChangePictureVideoMode{"ChangePictureVideoMode", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_ANDROID) // Enables clearing of browsing data which is older than given time period. const base::Feature kClearOldBrowsingData{"ClearOldBrowsingData", base::FEATURE_DISABLED_BY_DEFAULT}; #endif const base::Feature kClickToOpenPDFPlaceholder{ "ClickToOpenPDFPlaceholder", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_MACOSX) const base::Feature kContentFullscreen{"ContentFullscreen", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Enables a site-wide permission in the UI which controls access to the // asynchronous Clipboard web API. const base::Feature kClipboardContentSetting{"ClipboardContentSetting", base::FEATURE_ENABLED_BY_DEFAULT}; // Whether inactive tabs show their close buttons by default for non-touch mode. const base::Feature kCloseButtonsInactiveTabs{"CloseButtonsInactiveTabs", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_CHROMEOS) // Enable project Crostini, Linux VMs on Chrome OS. const base::Feature kCrostini{"Crostini", base::FEATURE_DISABLED_BY_DEFAULT}; // Whether the UsageTimeLimit policy should be applied to the user. const base::Feature kUsageTimeLimitPolicy{"UsageTimeLimitPolicy", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if defined(OS_WIN) // Enables or disables desktop ios promotion, which shows a promotion to the // user promoting Chrome for iOS. const base::Feature kDesktopIOSPromotion{"DesktopIOSPromotion", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Enables or disables windowing related features for desktop PWAs. const base::Feature kDesktopPWAWindowing { "DesktopPWAWindowing", #if defined(OS_CHROMEOS) || defined(OS_WIN) || defined(OS_LINUX) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Enables or disables Desktop PWAs capturing links. const base::Feature kDesktopPWAsLinkCapturing{ "DesktopPWAsLinkCapturing", base::FEATURE_DISABLED_BY_DEFAULT}; // Disables downloads of unsafe file types over HTTP. const base::Feature kDisallowUnsafeHttpDownloads{ "DisallowUnsafeHttpDownloads", base::FEATURE_DISABLED_BY_DEFAULT}; const char kDisallowUnsafeHttpDownloadsParamName[] = "MimeTypeList"; #if !defined(OS_ANDROID) const base::Feature kDoodlesOnLocalNtp{"DoodlesOnLocalNtp", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #if defined(OS_ANDROID) // Enables downloads as a foreground service for all versions of Android. const base::Feature kDownloadsForeground{"DownloadsForeground", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if defined(OS_ANDROID) // Enable changing default downloads storage location on Android. const base::Feature kDownloadsLocationChange{"DownloadsLocationChange", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // An experimental way of showing app banners, which has modal banners and gives // developers more control over when to show them. const base::Feature kExperimentalAppBanners { "ExperimentalAppBanners", #if defined(OS_CHROMEOS) || defined(OS_ANDROID) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; #if defined(OS_CHROMEOS) extern const base::Feature kExperimentalCrostiniUI{ "ExperimentalCrostiniUI", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // If enabled, this feature's |kExternalInstallDefaultButtonKey| field trial // parameter value controls which |ExternalInstallBubbleAlert| button is the // default. const base::Feature kExternalExtensionDefaultButtonControl{ "ExternalExtensionDefaultButtonControl", base::FEATURE_DISABLED_BY_DEFAULT}; #if BUILDFLAG(ENABLE_VR) #if BUILDFLAG(ENABLE_OCULUS_VR) // Controls Oculus support. const base::Feature kOculusVR{"OculusVR", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // ENABLE_OCULUS_VR #if BUILDFLAG(ENABLE_OPENVR) // Controls OpenVR support. const base::Feature kOpenVR{"OpenVR", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // ENABLE_OPENVR #endif // BUILDFLAG(ENABLE_VR) // Enables a floating action button-like full screen exit UI to allow exiting // fullscreen using mouse or touch. const base::Feature kFullscreenExitUI{"FullscreenExitUI", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_WIN) // Enables using GDI to print text as simply text. const base::Feature kGdiTextPrinting {"GdiTextPrinting", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Controls whether the GeoLanguage system is enabled. GeoLanguage uses IP-based // coarse geolocation to provide an estimate (for use by other Chrome features // such as Translate) of the local/regional language(s) corresponding to the // device's location. If this feature is disabled, the GeoLanguage provider is // not initialized at startup, and clients calling it will receive an empty list // of languages. const base::Feature kGeoLanguage{"GeoLanguage", base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_ANDROID) const base::Feature kGrantNotificationsToDSE{"GrantNotificationsToDSE", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // defined(OS_ANDROID) #if defined (OS_CHROMEOS) // Enables or disables the Happiness Tracking System for the device. const base::Feature kHappinessTrackingSystem { "HappinessTrackingSystem", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #if !defined(OS_ANDROID) // Replaces the WebUI Cast dialog with a Views toolkit one. const base::Feature kViewsCastDialog{"ViewsCastDialog", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // !defined(OS_ANDROID) // Enables navigation suggestions for internationalized domain names that are // visually similar to popular domains. const base::Feature kIdnNavigationSuggestions{ "IdnNavigationSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Controls whether the "improved recovery component" is used. The improved // recovery component is a redesigned Chrome component intended to restore // a broken Chrome updater in more scenarios than before. const base::Feature kImprovedRecoveryComponent{ "ImprovedRecoveryComponent", base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) // A feature that controls whether Chrome warns about incompatible applications. const base::Feature kIncompatibleApplicationsWarning{ "IncompatibleApplicationsWarning", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if !defined(OS_ANDROID) // Enables Casting a Presentation API-enabled website to a secondary display. const base::Feature kLocalScreenCasting{"LocalScreenCasting", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // Enables or disables the Location Settings Dialog (LSD). The LSD is an Android // system-level geolocation permission prompt. const base::Feature kLsdPermissionPrompt{"LsdPermissionPrompt", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_MACOSX) // Enables RTL layout in macOS top chrome. const base::Feature kMacRTL{"MacRTL", base::FEATURE_ENABLED_BY_DEFAULT}; // Uses NSFullSizeContentViewWindowMask where available instead of adding our // own views to the window frame. This is a temporary kill switch, it can be // removed once we feel okay about leaving it on. const base::Feature kMacFullSizeContentView{"MacFullSizeContentView", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if defined(OS_MACOSX) // Enables the Material Design download shelf on Mac. const base::Feature kMacMaterialDesignDownloadShelf{ "MacMDDownloadShelf", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if BUILDFLAG(ENABLE_EXTENSIONS) // Sets whether dismissing the new-tab-page override bubble counts as // acknowledgement. const base::Feature kAcknowledgeNtpOverrideOnDeactivate{ "AcknowledgeNtpOverrideOnDeactivate", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) const base::Feature kWarnBeforeQuitting{"WarnBeforeQuitting", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // The material redesign of the Incognito NTP. const base::Feature kMaterialDesignIncognitoNTP{ "MaterialDesignIncognitoNTP", #if defined(OS_ANDROID) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif }; // Enables or disables modal permission prompts. const base::Feature kModalPermissionPrompts{"ModalPermissionPrompts", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables the use of native notification centers instead of using the Message // Center for displaying the toasts. The feature is hardcoded to enabled for // Chrome OS. #if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS) && !defined(OS_CHROMEOS) #if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(OS_LINUX) const base::Feature kNativeNotifications{"NativeNotifications", base::FEATURE_ENABLED_BY_DEFAULT}; #else const base::Feature kNativeNotifications{"NativeNotifications", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #endif // BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS) const base::Feature kNetworkPrediction{"NetworkPrediction", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_POSIX) // Enables NTLMv2, which implicitly disables NTLMv1. const base::Feature kNtlmV2Enabled{"NtlmV2Enabled", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // If enabled, the list of content suggestions on the New Tab page will contain // pages that the user downloaded for later use. // DO NOT check directly whether this feature is enabled (i.e. do not use // base::FeatureList::IsEnabled()). It is enabled conditionally. Use // |AreOfflinePageDownloadsEnabled| instead. const base::Feature kOfflinePageDownloadSuggestionsFeature{ "NTPOfflinePageDownloadSuggestions", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_ANDROID) // Enables or disabled the OOM intervention. const base::Feature kOomIntervention{"OomIntervention", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #if !defined(OS_ANDROID) // Enables or disabled the OneGoogleBar on the local NTP. const base::Feature kOneGoogleBarOnLocalNtp{"OneGoogleBarOnLocalNtp", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // Adds the base language code to the Language-Accept headers if at least one // corresponding language+region code is present in the user preferences. // For example: "en-US, fr-FR" --> "en-US, en, fr-FR, fr". const base::Feature kUseNewAcceptLanguageHeader{ "UseNewAcceptLanguageHeader", base::FEATURE_ENABLED_BY_DEFAULT}; // Delegate permissions to cross-origin iframes when the feature has been // allowed by feature policy. const base::Feature kPermissionDelegation{"PermissionDelegation", base::FEATURE_DISABLED_BY_DEFAULT}; // Disables PostScript generation when printing to PostScript capable printers // and instead sends Emf files. #if defined(OS_WIN) const base::Feature kDisablePostScriptPrinting{ "DisablePostScriptPrinting", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Enables a page for manaing policies at chrome://policy-tool. #if !defined(OS_ANDROID) const base::Feature kPolicyTool{"PolicyTool", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #if BUILDFLAG(ENABLE_PLUGINS) // Prefer HTML content by hiding Flash from the list of plugins. // https://crbug.com/626728 const base::Feature kPreferHtmlOverPlugins{"PreferHtmlOverPlugins", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if defined(OS_CHROMEOS) // The lock screen will be preloaded so it is instantly available when the user // locks the Chromebook device. const base::Feature kPreloadLockScreen{"PreloadLockScreen", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // If enabled, Print Preview will use the CloudPrinterHandler instead of the // cloud print interface to communicate with the cloud print server. This // prevents Print Preview from making direct network requests. See // https://crbug.com/829414. const base::Feature kCloudPrinterHandler{"CloudPrinterHandler", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables the new Print Preview UI. const base::Feature kNewPrintPreview{"NewPrintPreview", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kNupPrinting{"NupPrinting", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Enables or disables push subscriptions keeping Chrome running in the // background when closed. const base::Feature kPushMessagingBackgroundMode{ "PushMessagingBackgroundMode", base::FEATURE_DISABLED_BY_DEFAULT}; #if !defined(OS_ANDROID) const base::Feature kRemoveUsageOfDeprecatedGaiaSigninEndpoint{ "RemoveUsageOfDeprecatedGaiaSigninEndpoint", base::FEATURE_ENABLED_BY_DEFAULT}; #endif const base::Feature kSafeSearchUrlReporting{"SafeSearchUrlReporting", base::FEATURE_DISABLED_BY_DEFAULT}; // Controls whether the user is prompted when sites request attestation. const base::Feature kSecurityKeyAttestationPrompt{ "SecurityKeyAttestationPrompt", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_MACOSX) // Whether to show all dialogs with toolkit-views on Mac, rather than Cocoa. const base::Feature kShowAllDialogsWithViewsToolkit{ "ShowAllDialogsWithViewsToolkit", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // defined(OS_MACOSX) #if defined(OS_ANDROID) const base::Feature kShowTrustedPublisherURL{"ShowTrustedPublisherURL", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // Alternative to switches::kSitePerProcess, for turning on full site isolation. // Launch bug: https://crbug.com/739418. This is a //chrome-layer feature to // avoid turning on site-per-process by default for *all* //content embedders // (e.g. this approach lets ChromeCast avoid site-per-process mode). const base::Feature kSitePerProcess{"site-per-process", base::FEATURE_DISABLED_BY_DEFAULT}; // kSitePerProcessOnlyForHighMemoryClients is checked before kSitePerProcess, // and (if enabled) can restrict if kSitePerProcess feature is checked at all - // no check will be made on devices with low memory (these devices will have no // Site Isolation via kSitePerProcess trials and won't activate either the // control or the experiment group). The threshold for what is considered a // "low memory" device is set (in MB) via a field trial param with the name // defined below ("site-per-process-low-memory-cutoff-mb") and compared against // base::SysInfo::AmountOfPhysicalMemoryMB(). const base::Feature kSitePerProcessOnlyForHighMemoryClients{ "site-per-process-only-for-high-memory-clients", base::FEATURE_DISABLED_BY_DEFAULT}; const char kSitePerProcessOnlyForHighMemoryClientsParamName[] = "site-per-process-low-memory-cutoff-mb"; // The site settings all sites list page in the Chrome settings UI. const base::Feature kSiteSettings{"SiteSettings", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables committed error pages instead of transient navigation entries for // SSL interstitial error pages (i.e. certificate errors). const base::Feature kSSLCommittedInterstitials{ "SSLCommittedInterstitials", base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_CHROMEOS) // Enables or disables the ability to add a Samba Share to the Files app const base::Feature kNativeSmb{"NativeSmb", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_CHROMEOS) // Enables a special visual treatment for windows with a single tab. const base::Feature kSingleTabMode{"SingleTabMode", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables or disables the ability to use the sound content setting to mute a // website. const base::Feature kSoundContentSetting{"SoundContentSetting", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disabled committed interstitials for Supervised User // interstitials. const base::Feature kSupervisedUserCommittedInterstitials{ "SupervisedUserCommittedInterstitials", base::FEATURE_ENABLED_BY_DEFAULT}; #if defined(OS_CHROMEOS) // Enables or disables chrome://sys-internals. const base::Feature kSysInternals{"SysInternals", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Enable TopSites to source and sort its site data using site engagement. const base::Feature kTopSitesFromSiteEngagement{ "TopSitesFromSiteEngagement", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables using the local NTP if Google is the default search engine. const base::Feature kUseGoogleLocalNtp{"UseGoogleLocalNtp", base::FEATURE_DISABLED_BY_DEFAULT}; #if defined(OS_CHROMEOS) // Enables or disables logging for adaptive screen brightness on Chrome OS. const base::Feature kAdaptiveScreenBrightnessLogging{ "AdaptiveScreenBrightnessLogging", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables user activity event logging for power management on // Chrome OS. const base::Feature kUserActivityEventLogging{"UserActivityEventLogging", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables user activity prediction for power management on // Chrome OS. const base::Feature kUserActivityPrediction{"UserActivityPrediction", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Enables using the main HTTP cache for media files as well. const base::Feature kUseSameCacheForMedia{"UseSameCacheForMedia", base::FEATURE_DISABLED_BY_DEFAULT}; #if !defined(OS_ANDROID) // Enables or disables Voice Search on the local NTP. const base::Feature kVoiceSearchOnLocalNtp{"VoiceSearchOnLocalNtp", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if defined(OS_CHROMEOS) // Enables support of libcups APIs from ARC const base::Feature kArcCupsApi{"ArcCupsApi", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables or disables the opt-in IME menu in the language settings page. const base::Feature kOptInImeMenu{"OptInImeMenu", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables pin quick unlock. const base::Feature kQuickUnlockPin{"QuickUnlockPin", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables pin on the login screen. const base::Feature kQuickUnlockPinSignin{"QuickUnlockPinSignin", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables or disables fingerprint quick unlock. const base::Feature kQuickUnlockFingerprint{"QuickUnlockFingerprint", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables or disables emoji, handwriting and voice input on opt-in IME menu. const base::Feature kEHVInputOnImeMenu{"EmojiHandwritingVoiceInput", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables the bulk printer policies on Chrome OS. const base::Feature kBulkPrinters{"BulkPrinters", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables flash component updates on Chrome OS. const base::Feature kCrosCompUpdates{"CrosCompUpdates", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables Chrome OS Component updates on Chrome OS. const base::Feature kCrOSComponent{"CrOSComponent", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables TPM firmware update capability on Chrome OS. const base::Feature kTPMFirmwareUpdate{"TPMFirmwareUpdate", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables or disables "usm" service in the list of user services returned by // userInfo Gaia message. const base::Feature kCrOSEnableUSMUserService{"CrOSEnableUSMUserService", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables initialization & use of the Chrome OS ML Service. const base::Feature kMachineLearningService{"MachineLearningService", base::FEATURE_DISABLED_BY_DEFAULT}; // Enable USBGuard at the lockscreen on Chrome OS. const base::Feature kUsbguard{"USBGuard", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_CHROMEOS) #if !defined(OS_ANDROID) // Allow capturing of WebRTC event logs, and uploading of those logs to Crash. // Please note that a Chrome policy must also be set, for this to have effect. // Effectively, this is a kill-switch for the feature. // TODO(crbug.com/775415): Remove this kill-switch. extern const base::Feature kWebRtcRemoteEventLog{ "WebRtcRemoteEventLog", base::FEATURE_ENABLED_BY_DEFAULT}; // Compress remote-bound WebRTC event logs (if used; see kWebRtcRemoteEventLog). extern const base::Feature kWebRtcRemoteEventLogGzipped{ "WebRtcRemoteEventLogGzipped", base::FEATURE_ENABLED_BY_DEFAULT}; #endif #if defined(OS_WIN) // Enables the accelerated default browser flow for Windows 10. const base::Feature kWin10AcceleratedDefaultBrowserFlow{ "Win10AcceleratedDefaultBrowserFlow", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_WIN) #if defined(OS_ANDROID) // Enables showing alternative incognito strings. const base::Feature kIncognitoStrings{"IncognitoStrings", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_ANDROID) } // namespace features
163db4c6fd8ea22daa620bccd7456bc99d720f2e
aff66eb0b9bbd7765ffbd0343a1b5680f4549f3b
/cpp/factory_demo/product_impl.h
7fe5979d736cd7507fa34e2052176f562cef7894
[]
no_license
ygao12/experiments
d67dd0b48ce9e36a9d24ff39ae81d777e18baec3
89aea25388aa9d98a8208f22675e8145c80585e2
refs/heads/master
2021-06-27T08:55:42.657548
2021-03-23T12:34:57
2021-03-23T12:34:57
205,673,462
0
0
null
null
null
null
UTF-8
C++
false
false
610
h
#pragma once #include "product.h" #include "factory.h" class ProductA : public Product { public: void Say() { std::cout << "This is ProductA speaking" << std::endl; } }; class ProductB : public Product { public: void Say() { std::cout << "This is ProductB speaking" << std::endl; } }; class ProductC : public Product { public: void Say() { std::cout << "This is ProductC speaking" << std::endl; } }; inline Product *RegA() { Product *product = new ProductA(); return product; } REGISTER_PRODUCT_ADV(ProductA, RegA()); REGISTER_PRODUCT(ProductB); REGISTER_PRODUCT(ProductC);
968ee271c1eb706a2e8400b4e53428ec3c3416e8
898c761766be7b0db4ea51e50f11953a04da0f50
/2020-11-22/ABC184/E.cpp
69d947c0b6b1df432b00edff60387d9fd7316d4d
[]
no_license
zhoufangyuanTV/zzzz
342f87de6fdbdc7f8c6dce12649fe96c2c1bcf9c
1d686ff1bc6adb883fa18d0e110df7f82ebe568d
refs/heads/master
2023-08-25T03:22:41.184640
2021-09-30T12:42:01
2021-09-30T12:42:01
286,425,935
0
0
null
null
null
null
UTF-8
C++
false
false
1,384
cpp
#include<cstdio> #include<cstring> #include<vector> using namespace std; const int dx[4]={1,0,-1,0}; const int dy[4]={0,1,0,-1}; struct pt{int x,y;}; vector<pt> a[31]; bool b[2100][2100]; struct node { int x,y,d; }list[4010000]; char s[2100][2100]; int main() { int n,m;scanf("%d%d",&n,&m); int stx,sty,edx,edy; for(int i=1;i<=n;i++)scanf("%s",s[i]+1); memset(b,true,sizeof(b)); for(int i=1;i<=n;i++)b[i][0]=b[i][m+1]=false; for(int i=1;i<=m;i++)b[0][i]=b[n+1][i]=false; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(s[i][j]=='S')stx=i,sty=j; else if(s[i][j]=='G')edx=i,edy=j; else if(s[i][j]>='a'&&s[i][j]<='z') { a[s[i][j]-'a'].push_back((pt){i,j}); } else if(s[i][j]=='#')b[i][j]=false; } } int head=1,tail=2; list[1]=(node){stx,sty,0};b[stx][sty]=false; while(head<tail) { node x=list[head]; if(x.x==edx&&x.y==edy) { printf("%d\n",x.d); return 0; } for(int i=0;i<4;i++) { int xx=x.x+dx[i],yy=x.y+dy[i]; if(b[xx][yy]) { b[xx][yy]=false; list[tail++]=(node){xx,yy,x.d+1}; } } if(s[x.x][x.y]>='a'&&s[x.x][x.y]<='z') { for(int i=0;i<a[s[x.x][x.y]-'a'].size();i++) { int xr=a[s[x.x][x.y]-'a'][i].x,yr=a[s[x.x][x.y]-'a'][i].y; if(b[xr][yr]) { s[xr][yr]='.'; b[xr][yr]=false; list[tail++]=(node){xr,yr,x.d+1}; } } } head++; } puts("-1"); return 0; }
313e4140263230626a666d70377b27d47aee10f0
f9f575633fbf70e6989f3e3316c397dea69c0c3b
/Cpp/LeetCode/RemoveDuplicatesInVector.cpp
23ea911b25dc93b812b148ac335793cf7372a679
[]
no_license
mkberger/Library
031361d71d011b612d7eb446c212765a3cf59060
d6cba7695bc5711e51a368f6e61c079f099929db
refs/heads/master
2023-05-11T04:14:27.168878
2023-05-03T18:35:51
2023-05-03T18:35:51
29,210,732
0
0
null
null
null
null
UTF-8
C++
false
false
503
cpp
// https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ class Solution { public: int removeDuplicates(vector<int>& nums) { int val = nums[0]; int uniques = 1; for (int i = 1; i < nums.size(); i++) { if (nums[i] == val) { nums.erase(nums.begin() + i); i--; } else { uniques++; val = nums[i]; } } return uniques; } };
3b94debf71fdccbbda2a5114e543fcecf116bdfd
813058a2df5f8c8e8fe6f75302de08f01fd00ce6
/src/machine_state.cpp
afbdbedcf995ba64c722e657a1a9e9ba8ba92a56
[]
no_license
stoffer3/CatBot
b525082e03ff9f4b2665599f0eb7ef86024917ed
03f11eb56daa4931d1c88babdd3efcf618af1695
refs/heads/master
2020-03-28T09:05:43.242191
2019-02-18T09:30:38
2019-02-18T09:30:38
148,013,441
0
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
/* * MachineState.cpp * * Created on: Dec 17, 2017 * Author: stoffer */ #include "machine.hpp" #include "exceptions/notImplementedException.hpp" namespace FiniteStateMachine { Machine::MachineState::MachineState(Machine *innerMachine) { this->innerMachine = innerMachine; } Machine::MachineState::~MachineState() { } void Machine::MachineState::doInitialiation() { throw std::NotImplementedException("myFunction is not implemented yet."); } void Machine::MachineState::doObserve() { throw std::NotImplementedException("myFunction is not implemented yet."); } void Machine::MachineState::doDecition() { throw std::NotImplementedException("myFunction is not implemented yet."); } void Machine::MachineState::doAct() { throw std::NotImplementedException("myFunction is not implemented yet."); } void Machine::MachineState::doFinalizing() { throw std::NotImplementedException("myFunction is not implemented yet."); } }
200a61ff67931d7a4549218848180f51d7b47b03
e5cd80fd89480cbc27a177b9608ec93359cca5f8
/1115.cpp
35c063d5c98622a60de9ed3fe8849806b65220ef
[]
no_license
higsyuhing/leetcode_middle
c5db8dd2e64f1b0a879b54dbd140117a8616c973
405c4fabd82ed1188d89851b4df35b28c5cb0fa6
refs/heads/master
2023-01-28T20:40:52.865658
2023-01-12T06:15:28
2023-01-12T06:15:28
139,873,993
0
0
null
null
null
null
UTF-8
C++
false
false
804
cpp
#include <semaphore.h> class FooBar { private: int n; sem_t semfoo; sem_t sembar; public: FooBar(int n) { this->n = n; sem_init(&semfoo, 0, 1); sem_init(&sembar, 0, 0); } void foo(function<void()> printFoo) { for (int i = 0; i < n; i++) { sem_wait(&semfoo); // printFoo() outputs "foo". Do not change or remove this line. printFoo(); sem_post(&sembar); } } void bar(function<void()> printBar) { for (int i = 0; i < n; i++) { sem_wait(&sembar); // printBar() outputs "bar". Do not change or remove this line. printBar(); sem_post(&semfoo); } } };
de24c2c8b25f0b065f9d2ce9ddc83f6e9c985699
58e27e72cb912a4406ea82f52836771b4b28ef26
/H2O/RiemannStuff/localProblem.cpp
9ffd2dec9680250e22fffa970b2875f34be728e9
[]
no_license
RoteKekse/quantumchemistry
825ea17107b918a436fd5173285d42f318d5c5a8
289676f24461ac344d4f14cd4e486f41af904bb5
refs/heads/master
2023-04-18T07:00:52.931854
2021-05-03T12:35:29
2021-05-03T12:35:29
256,152,362
0
0
null
null
null
null
UTF-8
C++
false
false
28,913
cpp
#include <xerus.h> using namespace xerus; class localProblem{ const size_t d; std::vector<TTTensor> xbasis; std::vector<Tensor> leftAStack; std::vector<Tensor> rightAStack; std::vector<Tensor> middleAStack; std::vector<Tensor> leftYStack; std::vector<Tensor> rightYStack; std::vector<Tensor> Axleft; std::vector<Tensor> Axright; public: Tensor projectionT; Tensor projectionTS; //projection onto fixed rank tangentialspace void projection(Tensor& y){ time_t begin_time = time (NULL); size_t vectorpos=0; for (size_t pos=0;pos<d-1;pos++){ //TTTensor ypos=xbasis[pos]; Tensor xi=xbasis[1].get_component(pos); auto dims = xi.dimensions; size_t size=dims[0]*dims[1]*dims[2]; Tensor ycomp=Tensor({size}); for (size_t k=0;k<size;k++){ ycomp[k]=y[vectorpos+k]; } ycomp.reinterpret_dimensions(dims); Index i1,i2,i3, j1,j2,j3, q; Tensor tmp; tmp(i1,i2,i3)=xi(i1,i2,q)*xi(j1,j2,q)*ycomp(j1,j2,i3); ycomp-=tmp; ycomp.reinterpret_dimensions({size}); for (size_t k=0;k<size;k++){ y[vectorpos+k]=ycomp[k]; } vectorpos+=size; } // std::cout<<"time for projection: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; } //projection onto fixed rank and unitcircle tangentialspace void projectionS(Tensor& y){ time_t begin_time = time (NULL); size_t vectorpos=0; for (size_t pos=0;pos<d;pos++){ //TTTensor ypos=xbasis[pos]; Tensor xi=xbasis[1].get_component(pos); auto dims = xi.dimensions; size_t size=dims[0]*dims[1]*dims[2]; Tensor ycomp=Tensor({size}); for (size_t k=0;k<size;k++){ ycomp[k]=y[vectorpos+k]; } ycomp.reinterpret_dimensions(dims); Index i1,i2,i3, j1,j2,j3, q; Tensor tmp; tmp(i1,i2,i3)=xi(i1,i2,q)*xi(j1,j2,q)*ycomp(j1,j2,i3); ycomp-=tmp; for (size_t k=0;k<size;k++){ y[vectorpos+k]=ycomp[k]; } vectorpos+=size; } //std::cout<<"time for projection: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; } localProblem(TTTensor& x) : d(x.degree()) { // x/=frob_norm(x); x.move_core(0,true); xbasis.emplace_back(x); x.move_core(d-1,true); xbasis.emplace_back(x); } void update(TTTensor& x){ xbasis.clear(); // x/=frob_norm(x); x.move_core(0,true); xbasis.emplace_back(x); x.move_core(d-1,true); xbasis.emplace_back(x); } void built_projection(){ time_t begin_time = time (NULL); projectionT=Tensor(); for(size_t i=0;i<d-1;i++){ Tensor xi=xbasis[1].get_component(i); Tensor Pi; Index i1,i2,i3, j1,j2,j3, q; auto dims=xi.dimensions; auto I1 =Tensor::identity({dims[2],dims[2]}); auto I2 =Tensor::identity({dims[0],dims[1],dims[0],dims[1]}); Pi(i1,i2,i3,j1,j2,j3)=I1(i3,j3)*(I2(i1,i2,j1,j2)-(xi(i1,i2,q)*xi(j1,j2,q))); Pi.reinterpret_dimensions({dims[2]*dims[1]*dims[0],dims[0]*dims[1]*dims[2]}); if(i==0){ projectionT=Pi; }else{ projectionT.resize_mode(0,projectionT.dimensions[0]+Pi.dimensions[0],projectionT.dimensions[0]); Pi.resize_mode(0,projectionT.dimensions[0],0); projectionT.resize_mode(1,projectionT.dimensions[1] +Pi.dimensions[1],projectionT.dimensions[1]); Pi.resize_mode(1,projectionT.dimensions[1],0); projectionT+=Pi; } } projectionTS=projectionT; Tensor xi=xbasis[1].get_component(d-1); Tensor Pi; Index i1,i2,i3, j1,j2,j3, q; auto dims=xi.dimensions; auto I1 =Tensor::identity({dims[2],dims[2]}); auto I2 =Tensor::identity({dims[0],dims[1],dims[0],dims[1]}); auto I3 =Tensor::identity({dims[0]*dims[1]*dims[2],dims[0]*dims[1]*dims[2]}); Pi(i1,i2,i3,j1,j2,j3)=I1(i3,j3)*(I2(i1,i2,j1,j2)-(xi(i1,i2,q)*xi(j1,j2,q))); Pi.reinterpret_dimensions({dims[2]*dims[1]*dims[0],dims[0]*dims[1]*dims[2]}); projectionT.resize_mode(0,projectionT.dimensions[0]+Pi.dimensions[0],projectionT.dimensions[0]); Pi.resize_mode(0,projectionT.dimensions[0],0); projectionTS.resize_mode(0,projectionT.dimensions[0],projectionTS.dimensions[0]); I3.resize_mode(0,projectionT.dimensions[0],0); projectionT.resize_mode(1,projectionT.dimensions[1]+Pi.dimensions[1],projectionT.dimensions[1]); Pi.resize_mode(1,projectionT.dimensions[1],0); projectionTS.resize_mode(1,projectionT.dimensions[1],projectionTS.dimensions[1]); I3.resize_mode(1,projectionT.dimensions[1],0); projectionT+=I3; projectionTS+=Pi; //std::cout<<"time for projection matrix: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; } void push_left_stack(const size_t _position,const TTTensor& y) { Index i1, i2, i3, j1 , j2, j3, k1, k2; const Tensor &xi = xbasis[1].get_component(_position); const Tensor &yi = y.get_component(_position); Tensor tmpy; tmpy(i1, i2) = leftYStack.back()(j1, j2) *xi(j1, k1, i1)*yi(j2, k1, i2); leftYStack.emplace_back(std::move(tmpy)); } void push_right_stack(const size_t _position,const TTTensor& y){ Index i1, i2, i3, j1 , j2, j3, k1, k2; const Tensor &xi = xbasis[0].get_component(_position); const Tensor &yi = y.get_component(_position); Tensor tmpy; tmpy(i1, i2) = xi(i1, k1, j1)*yi(i2, k1, j2) *rightYStack.back()(j1, j2); rightYStack.emplace_back(std::move(tmpy)); } void push_left_stack(const size_t _position,const TTTensor& y,const TTOperator& A) { Index i1, i2, i3, j1 , j2, j3, k1, k2; const Tensor &xi = xbasis[1].get_component(_position); const Tensor &Ai = A.get_component(_position); const Tensor &yi = y.get_component(_position); Tensor tmpA; tmpA(i1, i2, i3) = leftYStack.back()(j1, j2, j3) *xi(j1, k1, i1)*Ai(j2, k1, k2, i2)*yi(j3, k2, i3); leftYStack.emplace_back(std::move(tmpA)); } void push_right_stack(const size_t _position,const TTTensor& y,const TTOperator& A) { Index i1, i2, i3, j1 , j2, j3, k1, k2; const Tensor &xi = xbasis[0].get_component(_position); const Tensor &Ai = A.get_component(_position); const Tensor &yi = y.get_component(_position); Tensor tmpA; tmpA(i1, i2, i3) = xi(i1, k1, j1)*Ai(i2, k1, k2, j2)*yi(i3, k2, j3) *rightYStack.back()(j1, j2, j3); rightYStack.emplace_back(std::move(tmpA)); } void push_left_stack(const size_t _position,const TTOperator& A) { Index i1, i2, i3, j1 , j2, j3, k1, k2; const Tensor &xi = xbasis[1].get_component(_position); const Tensor &Ai = A.get_component(_position); Tensor tmpA; tmpA(i1, i2, i3) = leftAStack.back()(j1, j2, j3) *xi(j1, k1, i1)*Ai(j2, k1, k2, i2)*xi(j3, k2, i3); leftAStack.emplace_back(std::move(tmpA)); } void push_right_stack(const size_t _position,const TTOperator& A) { Index i1, i2, i3, j1 , j2, j3, k1, k2; const Tensor &xi = xbasis[0].get_component(_position); const Tensor &Ai = A.get_component(_position); Tensor tmpA; tmpA(i1, i2, i3) = xi(i1, k1, j1)*Ai(i2, k1, k2, j2)*xi(i3, k2, j3) *rightAStack.back()(j1, j2, j3); rightAStack.emplace_back(std::move(tmpA)); } Tensor getBlockDiagOp(const TTOperator& A){ time_t begin_time = time (NULL); //first build every needed stack leftAStack.emplace_back(Tensor::ones({1,1,1})); rightAStack.emplace_back(Tensor::ones({1,1,1})); for (size_t pos=0; pos<d-1;pos++){ push_left_stack(pos,A); } for (size_t pos=d-1; pos>0;pos--){ push_right_stack(pos,A); } //now build matrix Tensor Aloc=Tensor(); for(size_t i=0;i<d;i++){ Tensor Acomp; Index i1,i2,i3,j1,j2,j3,k1,k2; Tensor left=leftAStack[i]; Tensor right=rightAStack[d-i-1]; Tensor Ai= A.get_component(i); Acomp(i1,i2,i3,j1,j2,j3)=left(i1,k1,j1)*Ai(k1,i2,j2,k2)*right(i3,k2,j3); auto d1=Acomp.dimensions[0]*Acomp.dimensions[1]*Acomp.dimensions[2]; auto d2=Acomp.dimensions[3]*Acomp.dimensions[4]*Acomp.dimensions[5]; Acomp.reinterpret_dimensions({d1,d2}); if(i==0){ Aloc=Acomp; }else{ auto dims =Acomp.dimensions; auto dims2=Aloc.dimensions; Aloc.resize_mode(1,dims[1]+dims2[1],dims2[1]); Acomp.resize_mode(1,dims[1]+dims2[1],0); Aloc.resize_mode(0,dims[0]+dims2[0],dims2[0]); Acomp.resize_mode(0,dims[0]+dims2[0],0); Aloc+=Acomp; } } leftAStack.clear(); rightAStack.clear(); return Aloc; } Tensor getlocalOperator(const TTOperator& A){ time_t begin_time = time (NULL); leftAStack.emplace_back(Tensor::ones({1,1,1})); rightAStack.emplace_back(Tensor::ones({1,1,1})); for (size_t pos=0; pos<d-1;pos++){ push_left_stack(pos,A); } for (size_t pos=d-1; pos>0;pos--){ push_right_stack(pos,A); } //if possible do in parallel for (size_t n=2;n<d;n++){ Tensor tmpA,Ai,xL,xR; Ai=A.get_component(n-1); xL=xbasis[1].get_component(n-1); xR=xbasis[0].get_component(n-1); Index i1,i2,i3, j1,j2,j3, k1,k2; tmpA(i1,i2,i3, j1,j2,j3)= xR(i1, k1, j1)*Ai(i2, k1, k2, j2)*xL(i3, k2, j3); middleAStack.emplace_back(tmpA); } Tensor Aloc; for(size_t i=0;i<d;i++){ Tensor Aloc1; Tensor Acomp; const TTTensor &xi =xbasis[0]; const TTTensor &xj =xbasis[1]; Tensor xicomp, xjcomp,Ai; Tensor Mi,Mj; //diagonal component Index i1,i2,i3,j1,j2,j3,l1,l2,l3,r1,r2,r3,k1,k2,k3,k4, n1,n2,n3; Tensor left=leftAStack[i]; Tensor right=rightAStack[d-i-1]; Ai= A.get_component(i); Aloc1(i1,i2,i3,j1,j2,j3)=0.5*left(i1,k1,j1)*Ai(k1,i2,j2,k2)*right(i3,k2,j3); size_t d1,d2; d1=Aloc1.dimensions[0]*Aloc1.dimensions[1]*Aloc1.dimensions[2]; d2=Aloc1.dimensions[3]*Aloc1.dimensions[4]*Aloc1.dimensions[5]; Aloc1.reinterpret_dimensions({d1,d2}); if(i<d-1){ size_t j =i+1; xicomp= xi.get_component(j); xjcomp= xj.get_component(i); Tensor Aj = A.get_component(j); Ai= A.get_component(i); using xerus::misc::operator<<; Mi(i2,k1,r1,k2,r2)=Ai(k1,i2,n2,k2)*xjcomp(r1,n2,r2); Mj(j2,l1,k1,l2,k2)=xicomp(l1,n1,l2)*Aj(k1,n1,j2,k2); Tensor left=leftAStack[i]; Tensor right=rightAStack[d-j-1]; //Tensor middle=middleAStack[i][j]; Tensor xi=xbasis[0].get_component(i); Tensor xj=xbasis[1].get_component(j); Acomp(i1,i2,i3,j1,j2,j3)=left(i1,k1,r1)*Mi(i2,k1,r1,k2,j1)*Mj(j2,i3,k2,l2,k4)*right(l2,k4,j3); size_t d1,d2; d1=Acomp.dimensions[0]*Acomp.dimensions[1]*Acomp.dimensions[2]; d2=Acomp.dimensions[3]*Acomp.dimensions[4]*Acomp.dimensions[5]; Acomp.reinterpret_dimensions({d1,d2}); auto dims =Acomp.dimensions; auto dims2=Aloc1.dimensions; Aloc1.resize_mode(1,dims[1]+dims2[1],dims2[1]); Acomp.resize_mode(1,dims[1]+dims2[1],0); //std::cout<<Aloc1.to_string()<<std::endl; //std::cout<<Acomp.to_string()<<std::endl; Aloc1+=Acomp; } Tensor tmp,tmp1,tmp2; for (size_t j= i+2; j<d;j++){ if(j==i+2){ tmp=middleAStack[i]; }else{ Index i1,i2,i3, j1,j2,j3, k1,k2,k3; tmp1=tmp; tmp2=middleAStack[j-2]; tmp(i1,i2,i3, j1,j2,j3)=tmp1(i1,i2,i3, k1,k2,k3)*tmp2(k1,k2,k3, j1,j2,j3); } Tensor left=leftAStack[i]; Tensor right=rightAStack[d-j-1]; xicomp= xi.get_component(j); xjcomp= xj.get_component(i); Tensor xi=xbasis[0].get_component(i); Tensor xj=xbasis[1].get_component(j); Tensor Aj = A.get_component(j); Ai= A.get_component(i); Mi(i2,k1,r1,k2,r2)=Ai(k1,i2,n2,k2)*xjcomp(r1,n2,r2); Mj(j2,l1,k1,l2,k2)=xicomp(l1,n1,l2)*Aj(k1,n1,j2,k2); Acomp(i1,i2,i3,j1,j2,j3)=left(i1,k1,r1)*Mi(i2,k1,r1,k2,r2)*tmp(i3,k2,r2,l1,k3,j1)*Mj(j2,l1,k3,l2,k4)*right(l2,k4,j3); size_t d1,d2; d1=Acomp.dimensions[0]*Acomp.dimensions[1]*Acomp.dimensions[2]; d2=Acomp.dimensions[3]*Acomp.dimensions[4]*Acomp.dimensions[5]; Acomp.reinterpret_dimensions({d1,d2}); auto dims =Acomp.dimensions; auto dims2=Aloc1.dimensions; Aloc1.resize_mode(1,dims[1]+dims2[1],dims2[1]); Acomp.resize_mode(1,dims[1]+dims2[1],0); //std::cout<<Aloc1.to_string()<<std::endl; //std::cout<<Acomp.to_string()<<std::endl; Aloc1+=Acomp; } if(i==0){ Aloc=Aloc1; }else{ auto dims =Aloc.dimensions; auto dims2=Aloc1.dimensions; Aloc.resize_mode(0,dims[0]+dims2[0],dims[0]); Aloc1.resize_mode(0,dims[0]+dims2[0],0); Aloc1.resize_mode(1,dims[1],0); Aloc+=Aloc1; } } Index i,j; Aloc(i,j)=Aloc(i,j)+Aloc(j,i); std::cout<<"time for A components: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; middleAStack.clear(); leftAStack.clear(); rightAStack.clear(); return Aloc; } Tensor getlocalVector(const TTTensor& y){ time_t begin_time = time (NULL); Tensor locY=Tensor(); leftYStack.clear(); rightYStack.clear(); leftYStack.emplace_back(Tensor::ones({1,1})); rightYStack.emplace_back(Tensor::ones({1,1})); for (size_t pos=d-1; pos>0;pos--){ push_right_stack(pos,y); } for (size_t corePosition=0;corePosition<d;corePosition++){ Tensor rhs; const Tensor &bi = y.get_component(corePosition); Index i1,i2,i3,k1,k2; rhs(i1, i2, i3) = leftYStack.back()(i1, k1) * bi(k1, i2, k2) * rightYStack.back()(i3, k2); rhs.reinterpret_dimensions({rhs.dimensions[2]*rhs.dimensions[1]*rhs.dimensions[0]}); if(corePosition==0){ locY=rhs; }else{ locY.resize_mode(0,locY.dimensions[0]+rhs.dimensions[0],locY.dimensions[0]); rhs.resize_mode(0,locY.dimensions[0],0); locY+=rhs; } if (corePosition+1 < d) { push_left_stack(corePosition,y); rightYStack.pop_back(); } } // std::cout<<"time for y components: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; return locY; } TTTensor builtTTTensor( Tensor& y){ time_t begin_time = time (NULL); TTTensor Y(xbasis[0].dimensions); size_t vectorpos=0; for (size_t pos=0;pos<d;pos++){ //TTTensor ypos=xbasis[pos]; auto dims = xbasis[0].get_component(pos).dimensions; size_t size=dims[0]*dims[1]*dims[2]; Tensor ycomp=Tensor({size}); for (size_t k=0;k<size;k++){ ycomp[k]=y[vectorpos+k]; } ycomp.reinterpret_dimensions(dims); auto tmpxl=xbasis[1].get_component(pos); auto tmpxr=xbasis[0].get_component(pos); if(pos==0){ ycomp.resize_mode(2,dims[2]*2,0); tmpxl.resize_mode(2,dims[2]*2,dims[2]); ycomp+=tmpxl; }else if(pos==d-1){ ycomp.resize_mode(0,dims[0]*2,dims[0]); tmpxr.resize_mode(0,dims[0]*2,0); ycomp+=tmpxr; }else{ ycomp.resize_mode(2,dims[2]*2,0); tmpxl.resize_mode(2,dims[2]*2,dims[2]); ycomp+=tmpxl; ycomp.resize_mode(0,dims[0]*2,dims[0]); tmpxr.resize_mode(2,dims[2]*2,0); tmpxr.resize_mode(0,dims[0]*2,0); ycomp+=tmpxr; } Index i,j; //ypos.set_component(pos,ycomp); Y.set_component(pos,ycomp); vectorpos+=size; } //std::cout<<"time for building y: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; return Y; } Tensor tangentAProduct( Tensor& y,const TTOperator& A){ time_t begin_time = time (NULL); TTTensor Y(xbasis[0].dimensions); size_t vectorpos=0; for (size_t pos=0;pos<d;pos++){ //TTTensor ypos=xbasis[pos]; auto dims = xbasis[0].get_component(pos).dimensions; size_t size=dims[0]*dims[1]*dims[2]; Tensor ycomp=Tensor({size}); for (size_t k=0;k<size;k++){ ycomp[k]=y[vectorpos+k]; } Tensor tmpxl,tmpxr; ycomp.reinterpret_dimensions(dims); if(pos<d-1){ tmpxl=Axleft[pos]; } if(pos>0){ tmpxr=Axright[pos-1]; } Tensor tmpA=A.get_component(pos); Index a1,a2,x1,x2,i,j; ycomp(a1,x1,i,a2,x2)=tmpA(a1,i,j,a2)*ycomp(x1,j,x2); dims=ycomp.dimensions; ycomp.reinterpret_dimensions({dims[0]*dims[1],dims[2],dims[3]*dims[4]}); dims=ycomp.dimensions; if(pos==0){ ycomp.resize_mode(2,dims[2]*2,0); tmpxl.resize_mode(2,dims[2]*2,dims[2]); ycomp+=tmpxl; }else if(pos==d-1){ ycomp.resize_mode(0,dims[0]*2,dims[0]); tmpxr.resize_mode(0,dims[0]*2,0); ycomp+=tmpxr; }else{ ycomp.resize_mode(2,dims[2]*2,0); tmpxl.resize_mode(2,dims[2]*2,dims[2]); ycomp+=tmpxl; ycomp.resize_mode(0,dims[0]*2,dims[0]); tmpxr.resize_mode(2,dims[2]*2,0); tmpxr.resize_mode(0,dims[0]*2,0); ycomp+=tmpxr; } //ypos.set_component(pos,ycomp); Y.set_component(pos,ycomp); vectorpos+=size; } Tensor result =getlocalVector(Y); Index i,j; projection(result); //std::cout<<"time for building y: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; return result; } Tensor localProduct(Tensor& y,const TTOperator& A){ time_t begin_time = time (NULL); TTTensor Y=builtTTTensor(y); Tensor locY=Tensor(); leftYStack.clear(); rightYStack.clear(); leftYStack.emplace_back(Tensor::ones({1,1,1})); rightYStack.emplace_back(Tensor::ones({1,1,1})); for (size_t pos=d-1; pos>0;pos--){ push_right_stack(pos,Y,A); } for (size_t corePosition=0;corePosition<d;corePosition++){ Tensor rhs; const Tensor &yi = Y.get_component(corePosition); const Tensor &Ai = A.get_component(corePosition); Index i1,i2,i3,A1,A2,k1,k2,j2; rhs(i1, i2, i3) = leftYStack.back()(i1,A1, k1) * Ai(A1,i2,j2,A2)* yi(k1, j2, k2) * rightYStack.back()(i3,A2, k2); rhs.reinterpret_dimensions({rhs.dimensions[2]*rhs.dimensions[1]*rhs.dimensions[0]}); if(corePosition==0){ locY=rhs; }else{ locY.resize_mode(0,locY.dimensions[0]+rhs.dimensions[0],locY.dimensions[0]); rhs.resize_mode(0,locY.dimensions[0],0); locY+=rhs; } if (corePosition+1 < d) { push_left_stack(corePosition,Y,A); rightYStack.pop_back(); } } Index i,j; projection(locY); leftYStack.clear(); rightYStack.clear(); // std::cout<<"time for A y product: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; return locY; } Tensor localProduct(const TTOperator& A){ time_t begin_time = time (NULL); Index i,j; Tensor result; TTTensor tmp; tmp(i&0)=A(i/2,j/2)*xbasis[0](j&0); result=getlocalVector(tmp); projection(result); // std::cout<<"time for product: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; return result; } void tangentProducts(const TTOperator& A){ time_t begin_time = time (NULL); Axleft.clear(); Axright.clear(); for(size_t pos=0;pos<d-1;pos++){ Tensor tmp,tmpA,tmpx; tmpA=A.get_component(pos); tmpx=xbasis[1].get_component(pos); Index a1,a2,x1,x2,i,j; tmp(a1,x1,i,a2,x2)=tmpA(a1,i,j,a2)*tmpx(x1,j,x2); auto dims=tmp.dimensions; tmp.reinterpret_dimensions({dims[0]*dims[1],dims[2],dims[3]*dims[4]}); Axleft.emplace_back(tmp); } for(size_t pos=1;pos<d;pos++){ Tensor tmp,tmpA,tmpx; tmpA=A.get_component(pos); tmpx=xbasis[0].get_component(pos); Index a1,a2,x1,x2,i,j; tmp(a1,x1,i,a2,x2)=tmpA(a1,i,j,a2)*tmpx(x1,j,x2); auto dims=tmp.dimensions; tmp.reinterpret_dimensions({dims[0]*dims[1],dims[2],dims[3]*dims[4]}); Axright.emplace_back(tmp); } std::cout<<"time for building Ax comps: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; } void cg_method3(const TTOperator& A, Tensor& rhs, Tensor& x, size_t maxit, size_t minit, value_t minerror){//TODO projection! time_t begin_time = time (NULL); //tangentProducts(A); value_t error=100; size_t it=0; Tensor r,d,z; Index i,j; double alpha,beta,rhsnorm; rhsnorm=frob_norm(rhs); Tensor Ax=localProduct(x,A); Tensor tmp; // tmp(i)=x0(i)*x0(j)*Ax(j); // Ax-=tmp; //Ax(i&0)=P(i/2,j/2)*Ax(j&0); r(i&0)=rhs(i&0)-Ax(i&0); d=r; size_t dims=1; for (size_t n=0;n<x.dimensions.size();n++){ dims*=x.dimensions[n]; } while((it<dims-1)&&(((error>minerror*minerror)&&(it<maxit))||(it<minit))){ z=localProduct(d,A); Tensor tmp; // tmp(i)=x0(i)*x0(j)*z(j); // z-=tmp; //z(i&0)=P(i/2,j/2)*z(j&0); Tensor tmp1,tmp2; tmp1()=r(i&0)*r(i&0); tmp2()=d(i&0)*z(i&0); alpha=tmp1[0]/tmp2[0]; x+=alpha*d; projection(x); r-=alpha*z; tmp2()=r(i&0)*r(i&0); beta=tmp2[0]/tmp1[0]; d=r+beta*d; projection(d); error=tmp2[0];//(rhsnorm*rhsnorm); it++; } std::cout<<"error^2="<<error<<" iterations: "<<it<<std::endl; std::cout<<"time for cg method: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; } void cg_method(const TTOperator& A,Tensor& x0, Tensor& rhs, Tensor& x, size_t maxit, size_t minit, value_t minerror){//TODO projection! time_t begin_time = time (NULL); //tangentProducts(A); value_t error=100; size_t it=0; Tensor r,d,z; Index i,j; double alpha,beta,rhsnorm; rhsnorm=frob_norm(rhs); Tensor Ax=localProduct(x,A); Tensor tmp; tmp(i)=x0(i)*x0(j)*Ax(j); Ax-=tmp; //Ax(i&0)=P(i/2,j/2)*Ax(j&0); r(i&0)=rhs(i&0)-Ax(i&0); d=r; size_t dims=1; for (size_t n=0;n<x.dimensions.size();n++){ dims*=x.dimensions[n]; } while((it<dims-1)&&(((error>minerror*minerror)&&(it<maxit))||(it<minit))){ z=localProduct(d,A); Tensor tmp; tmp(i)=x0(i)*x0(j)*z(j); z-=tmp; //z(i&0)=P(i/2,j/2)*z(j&0); Tensor tmp1,tmp2; tmp1()=r(i&0)*r(i&0); tmp2()=d(i&0)*z(i&0); alpha=tmp1[0]/tmp2[0]; x+=alpha*d; projection(x); r-=alpha*z; tmp2()=r(i&0)*r(i&0); beta=tmp2[0]/tmp1[0]; d=r+beta*d; projection(d); Tensor tmp3; tmp3() = d(i&0) * z(i&0); error=tmp2[0];//(rhsnorm*rhsnorm); std::cout<<"error^2="<<error<<" iterations: "<<it<< " orth? " << tmp3[0] <<std::endl; it++; } std::cout<<"error^2="<<error<<" iterations: "<<it<<std::endl; std::cout<<"time for cg method: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; } void cg_method2(const TTOperator& A,Tensor& P, Tensor& rhs, Tensor& x, size_t maxit, size_t minit, value_t minerror){ time_t begin_time = time (NULL); tangentProducts(A); value_t error=100; size_t it=0; Tensor r,d,z; Index i,j; double alpha,beta,rhsnorm; rhsnorm=frob_norm(rhs); Tensor Ax=tangentAProduct(x,A); Ax(i&0)=P(i/2,j/2)*Ax(j&0); r(i&0)=rhs(i&0)-Ax(i&0); d=r; size_t dims=1; for (size_t n=0;n<x.dimensions.size();n++){ dims*=x.dimensions[n]; } while((it<dims-1)&&(((error>minerror*minerror)&&(it<maxit))||(it<minit))){ z=tangentAProduct(d,A); z(i&0)=P(i/2,j/2)*z(j&0); Tensor tmp1,tmp2; tmp1()=r(i&0)*r(i&0); tmp2()=d(i&0)*z(i&0); alpha=tmp1[0]/tmp2[0]; x+=alpha*d; projection(x); r-=alpha*z; tmp2()=r(i&0)*r(i&0); beta=tmp2[0]/tmp1[0]; d=r+beta*d; projection(d); error=tmp2[0];//(rhsnorm*rhsnorm); it++; } std::cout<<"error^2="<<error<<" iterations: "<<it<<std::endl; std::cout<<"time for cg method: "<<time (NULL)-begin_time<<" sekunden"<<std::endl; } };
[ "anonymous@mail" ]
anonymous@mail
2b93df80d16064a1963528887a6e3b7ea1ae724a
603ad7bb3df5a02d222acefec08ce4f94d75409b
/EulerProject/ithprime.cpp
2131ef2a274dc03436359874b20f6f8a459d6a5b
[]
no_license
MijaelTola/icpc
6fc43aa49f97cf951a2b2fcbd0becd8c895abf36
ee2629ba087fbe7303743c84b509959f8d3fc9a0
refs/heads/master
2023-07-09T00:47:42.812242
2021-08-08T00:44:10
2021-08-08T00:44:10
291,160,127
0
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
#include <iostream> #include <algorithm> #include <queue> #include <stack> #include <vector> #include <climits> #include <map> #include <set> #include <cassert> #include <cstdio> #include <cstring> #include <cmath> #include <deque> #include <string> #include <sstream> #include <cstdlib> using namespace std; typedef long long ll; bool sieve[1010000]; vector<int> ans; int main(){ memset(sieve,false,sizeof sieve); for (int i = 2; i*i< 1010000; ++i){ int c = i+i; while(c < 1010000){ sieve[c] = true; c += i; } } for (int i = 2; i < 1010000; ++i){ if(!sieve[i]) ans.push_back(i); } cout << ans[10001-1] << endl; return 0; }
04f1fd9b1b300692efac7c4466453440d4e8abf8
8576f06c5c2efebd5fd751b8f6ecaba59ee1d0ea
/modules/imgproc/smooth.simd_declarations.hpp
b6dcfd35e4f90818bc97225a90f911724409256c
[]
no_license
EugChesn/QtOpenCV4-
8fe2fa5403baceb53a58f2e5a70e50e76d155541
2a400193514e344a4a0c8b7dd22976add6a1f624
refs/heads/master
2022-02-26T14:10:31.576062
2019-08-12T12:26:30
2019-08-12T12:33:54
201,924,521
0
0
null
null
null
null
UTF-8
C++
false
false
498
hpp
#define CV_CPU_SIMD_FILENAME "C:/OpenCv/opencv/sources/modules/imgproc/src/smooth.simd.hpp" #define CV_CPU_DISPATCH_MODE SSE2 #include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp" #define CV_CPU_DISPATCH_MODE SSE4_1 #include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp" #define CV_CPU_DISPATCH_MODE AVX2 #include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp" #define CV_CPU_DISPATCH_MODES_ALL AVX2, SSE4_1, SSE2, BASELINE #undef CV_CPU_SIMD_FILENAME
a03d7e58300255d6858043112330608e67cd2e9b
111224264d401a17b483601273a326872079d621
/v2/tablero.cpp
dee32de521b48c82d7ac49c4c103261c2890e7d3
[]
no_license
mayragarciaac/Inteligencia-Artificial
2b46337217c1e6aa360e4f80f9e31052a0c0e65d
06c8c33af6ca3a7bbca9ac6800623d3ea5553069
refs/heads/master
2020-04-13T20:02:03.958584
2018-12-28T14:30:34
2018-12-28T14:30:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,168
cpp
#include "tablero.hpp" #include <stdlib.h> tablero::tablero(int a,int b,int c_,int d_, int f_, int g_) { x=a; //FILAS!! y=b; //COLUMNAS!! c=c_;//punto partida d=d_; f=f_;//punto final g=g_; int d_p=x*y; T_= new char [d_p]; for(int i=1;i<=x;i++){ for(int j=1;j<=y;j++){ T_[(i-1)*y+j-1]=' '; if(i==c && j==d) set_pos(i,j,'I'); if(i==f && j==g) set_pos(i,j,'F'); if(i==1||j==1) T_[(i-1)*y+j-1]='*'; else{ if(i==x||j==y) T_[(i-1)*y+j-1]='*'; else T_[(i-1)*y+j-1]=' '; } } } } int tablero::datos_tabler(int a){ if(a==1) return x; else{ return y; } } void tablero::pintar_tablero(void){ for(int i=1;i<=x;i++){ for(int j=1;j<=y;j++){ cout << " "; if(i==f && j==g) T_[(i-1)*y+j-1]='F'; cout << T_[(i-1)*y+j-1]; } cout << endl; } } void tablero::set_pos(int i,int j,char c){ if(i>=x) i=x/5+ rand()%x; if(j>=y) j=y/5 + rand()%y; if(T_[(i-1)*y+j-1]==' ') T_[(i-1)*y+j-1]=c; } char tablero::get_dato(int i,int j){ return T_[(i-1)*y+j-1]; } int tablero:: get_y(){ //columnas return y; } int tablero:: get_x(){ return x; } int tablero:: tam(){ return x*y; } int tablero:: ocupado(int a,int b){ if ((get_dato(a,b)!=' ')&&(get_dato(a,b)!='F')) return 1; else return 0; } int tablero:: get_posfin1(){ return f; } int tablero:: get_posfin2(){ return g; }
569fea8b5ddc890fe9a2eed4ed51c6c3e494e1d7
538864396aefed639352fdedac4388a9f6747369
/src/qt/transactionrecord.cpp
da209f920116aa6cc04a0921efb10a457c5bce7c
[]
no_license
SaltineChips/CC
874dc50e5a59c8645c9442f83ab88e5e532a081c
c3185b3bb843ed4fa63b79170bd27f2e0177ce7c
refs/heads/master
2021-10-21T02:51:18.292658
2019-03-02T14:43:34
2019-03-02T14:43:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,100
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Htk developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2015-2017 The CC developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactionrecord.h" #include "base58.h" #include "Instantx.h" #include "timedata.h" #include "wallet.h" #include "masternode.h" #include <stdint.h> /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx& wtx) { if (wtx.IsCoinBase()) { // Ensures we show generated coins / mined transactions at depth 1 if (!wtx.IsInMainChain()) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet* wallet, const CWalletTx& wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.GetTxTime(); CAmount nCredit = wtx.GetCredit(ISMINE_ALL); CAmount nDebit = wtx.GetDebit(ISMINE_ALL); CAmount nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; if (wtx.IsCoinStake()) { TransactionRecord sub(hash, nTime); CTxDestination address; if (!ExtractDestination(wtx.vout[1].scriptPubKey, address)) return parts; if (!IsMine(*wallet, address)) { //if the address is not yours then it means you have a tx sent to you in someone elses coinstake tx for (unsigned int i = 1; i < wtx.vout.size(); i++) { CTxDestination outAddress; if (ExtractDestination(wtx.vout[i].scriptPubKey, outAddress)) { if (IsMine(*wallet, outAddress)) { isminetype mine = wallet->IsMine(wtx.vout[i]); sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; sub.type = TransactionRecord::MNReward; sub.address = CBitcoinAddress(outAddress).ToString(); sub.credit = wtx.vout[i].nValue; } } } } else { //stake reward isminetype mine = wallet->IsMine(wtx.vout[1]); sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; sub.type = TransactionRecord::StakeMint; sub.address = CBitcoinAddress(address).ToString(); sub.credit = nNet; } parts.append(sub); } else if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // BOOST_FOREACH (const CTxOut& txout, wtx.vout) { isminetype mine = wallet->IsMine(txout); if (mine) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = parts.size(); // sequence number sub.credit = txout.nValue; sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { // Received by CC Address sub.type = TransactionRecord::RecvWithAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } int nHeight = chainActive.Height(); int64_t nSubsidy; if (nHeight > 1 && nHeight <= 6000000) { if(175 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(400 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(850 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } } else if (nHeight > 6000000 && nHeight <= 769000) { if(175 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(400 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(850 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } } else if (nHeight > 769000 && nHeight <= 1018400) { if(175 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(400 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(850 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } } else if (nHeight > 1018400 && nHeight <= 1536800) { if(122.5 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(280 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(595 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } } else if (nHeight > 1536800 && nHeight <= 2015300) { if(104.15 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(238 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(505.75 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } } else if (nHeight > 2015300) { if(72.95 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(166.6 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } if(354.025 * COIN == txout.nValue) { sub.type = TransactionRecord::MNReward; } } parts.append(sub); } } } else { int nFromMe = 0; bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; BOOST_FOREACH (const CTxIn& txin, wtx.vin) { if (wallet->IsMine(txin)) { nFromMe++; } isminetype mine = wallet->IsMine(txin); if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if (fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; int nToMe = 0; BOOST_FOREACH (const CTxOut& txout, wtx.vout) { if (wallet->IsMine(txout)) { nToMe++; } isminetype mine = wallet->IsMine(txout); if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if (fAllToMe > mine) fAllToMe = mine; } if (fAllFromMe && fAllToMe) { // Payment to self // TODO: this section still not accurate but covers most cases, // might need some additional work however TransactionRecord sub(hash, nTime); // Payment to self by default sub.type = TransactionRecord::SendToSelf; sub.address = ""; if (mapValue["DS"] == "1") { sub.type = TransactionRecord::Obfuscated; CTxDestination address; if (ExtractDestination(wtx.vout[0].scriptPubKey, address)) { // Sent to CC Address sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.address = mapValue["to"]; } } else { for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; sub.idx = parts.size(); } } CAmount nChange = wtx.GetChange(); sub.debit = -(nDebit - nChange); sub.credit = nCredit - nChange; parts.append(sub); parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe) { // // Debit // CAmount nTxFee = nDebit - wtx.GetValueOut(); for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); sub.involvesWatchAddress = involvesWatchAddress; if (wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { // Sent to CC Address sub.type = TransactionRecord::SendToAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } if (mapValue["DS"] == "1") { sub.type = TransactionRecord::Obfuscated; } CAmount nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); parts.last().involvesWatchAddress = involvesWatchAddress; } } return parts; } void TransactionRecord::updateStatus(const CWalletTx& wtx) { AssertLockHeld(cs_main); // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = chainActive.Height(); status.cur_num_ix_locks = nCompleteTXLocks; if (!IsFinalTx(wtx, chainActive.Height() + 1)) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = wtx.nLockTime - chainActive.Height(); } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } // For generated transactions, determine maturity else if (type == TransactionRecord::Generated || type == TransactionRecord::StakeMint || type == TransactionRecord::MNReward) { if (wtx.GetBlocksToMaturity() > 0) { status.status = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.status = TransactionStatus::MaturesWarning; } else { status.status = TransactionStatus::NotAccepted; } } else { status.status = TransactionStatus::Confirmed; } } else { if (status.depth < 0) { status.status = TransactionStatus::Conflicted; } else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth == 0) { status.status = TransactionStatus::Unconfirmed; } else if (status.depth < RecommendedNumConfirmations) { status.status = TransactionStatus::Confirming; } else { status.status = TransactionStatus::Confirmed; } } } bool TransactionRecord::statusUpdateNeeded() { AssertLockHeld(cs_main); return status.cur_num_blocks != chainActive.Height() || status.cur_num_ix_locks != nCompleteTXLocks; } QString TransactionRecord::getTxID() const { return QString::fromStdString(hash.ToString()); } int TransactionRecord::getOutputIndex() const { return idx; }
5f73e85a0429b295f71361481b7183b8037255dc
4770198915790b7afb89a96e4e89e61c24768c56
/Hermes_project_ex_V76/Hermes_project_ex_V76/hermes.h
be379eb26808c1f3a31e07a6d8d74b754c913124
[]
no_license
Wang-shuange/gitdemo
f733c2cde2b8016832a281617a70b14ea608cfc2
68804d084c2c9f5393254cbd2184d52f56674baf
refs/heads/master
2020-03-29T16:32:37.231382
2018-10-18T01:42:22
2018-10-18T01:42:22
150,117,688
1
0
null
null
null
null
UTF-8
C++
false
false
7,239
h
#ifndef _HERMES_H #define _HERMES_H #include <Wire.h> #include "Arduino.h" #include "co2.h" #include "esp8266.h" #include "Si7020.h" #include "Enerlib.h" #include "Queue.h" #include "Digital_Light_TSL2561.h" ///Light Sensor IIC #define EEPROM_START_ADDRESS 100 // Start Address in EEPROM EEPROM_storage #define __TIME_COUNT__ #define __DEBUG__ #define __VP__ static char* functionType= "A"; static String IP; static String MAC; static char* deviceIP= ""; static char* BTaddr = ""; static unsigned char inputchar[32] = {0}; // Dust Serial buffer static long dust,cc; static long pm25; static char* deviceNum= "DVT6-151" ; //Device ID PL-1F-A-01 static char* fwversion= "V76"; static Queue *myQueue; static SQType *Q; /*---------------------------------------------- 2018-05-29 新增功能V76:新增功能1:設備location本地存儲 新增功能2:本地存儲已連接過的Wifi信息,實現環境變更時自動連接 問題點:功能1與功能2衝突(定位是在SmartConfig過程中獲取,實現自動連接無需再SmartConfig) 500位存儲是否存儲過Wifi的標誌位(flag=0未存儲過Wifi,flag=1有存儲Wifi) 占用字符長度(共50位): SSID長度:2位 SSID:16位 PSD長度:2位 PSD:16位 Location長度:2位 Location:12位 /*---------------------------------------------- 2018-03-21修改內容:取消1分鐘后開始上傳數據邏輯,改為僅粉塵1分鐘后開始上傳數據, 其他Sensor值連接上Server后即上傳 增加Flag判斷位置 2018-03-15新增功能V73:遠程修改Server IP及端口號功能 WEB中控發送Server IP及端口號,Hermes收到信息后保存至EEPROM 接收:ChangeServer#MAC,ServerIP,COM* 回傳:ChangeServer#MAC,OK* 收到信息后存入EEPROM,450位存儲ServerIP長度,455開始存IP 480位存儲端口號長度,490后存端口號 /*------------------------------------------------ 2018-02-27新增功能V72:遠程清空密碼功能 手機APP端發送清空密碼指令,Hermes設備接到指令清空密碼 接收:HermesCommand#ID,MAC* 回傳:CLEARPW#ID,MAC,OK* 測試服務器:10.199.28.206:8443 2018-02-02修改內容: 1.粉塵顆粒數X10; 2.新增恢復出廠設備按鍵,長按Reset 7S以上,即長按7S閃藍燈; 3.修復溫度40度以上出現負值的情況(變量定義問題,由int變為unsigned int) 4.除SmartConfig長亮紅燈外,其他異常均為每16S紅燈閃爍一次 /*-------------------------------------------- 2017-12-22修改內容V71:小功率無風扇帶煙感添加功能:恢復出廠設置功能 /*--------------------------------------------- 2017-12-02修改內容V66:小功率無風扇帶煙感增加異常LOG存儲功能 異常LOG存儲從EEPROM中150位開始,最長存255,至405結束 SmartConfig邏輯修改為長按Reset未接收到新Wifi信息前不清空原Wifi信息 /*------------------------------------------- 2017-11-24變更內容V63:小功率無風扇帶煙感增加讀取IP&Mac地址功能 /*------------------------------------------- 2017-11-11變更內容V58:Wifi重連機制變更 ---------------------------------------------*/ //2017-10-14 V56變更內容:溫濕度算法變更,濕度延時21S輸出 /*------------------------------------------- 小功率無風扇帶煙感: fix溫度 = 0.000163033*[Hermes溫度]^2 +1.01402*[Hermes溫度] - 3.06003-1.85      fix濕度 = 1.1438*[21秒後的Hermes濕度]+12.95+7.23813 ---------------------------------------------*/ //2017-10-13 变更内容:增加CO2阻抗检测算法,变更文件CO2.H,CO2.CPP; //2017-09-26 變更內容: //V52:修改粉塵數據為第一次有效數據為一分鐘,之後每次數據每3S傳一次,實現實時動態更新(28個有效值為一個隊列,當隊列滿時每更新一個有效值都需要刪除隊頭一個值) //2017-09-21 变更内容: //修改pm25浓度为1分钟显示一次; //a.为实现sensor 动态值,粉尘一分钟传一次有效值,在此期间,3秒传一次值,上传所有数据,与之前通信协议兼容,粉尘值使用上一次值; //b.粉尘取消X10; //2017-09-20 小风扇使用累加算法 //2017-09-14 添加一个程序开关用来切换VP的不同需求版本,将co 及烟感发送到服务器 //2017-09-12 增加CO &烟感,调试OK; //修改PM2.5 粉尘颗粒(0.5um)数系数 ,按照王清要求>10000 不变,小于10000值除2 //2017-08-23 change content: //1.依照PL副理指示,修改smart config 配置状态指示(变更前红灯闪烁3次后,变黑,变更后红灯闪烁3次后配置过程红灯常亮,配置成功led关掉。 //2.fix bug:smartconfig配置失败超时后无反应,变更后,配置失败两次超时后自动重启单片机; //3.修改LED1 蓝灯port,由digital3 变为digital46,消除LED1蓝灯与smarconfig 配置中断pin之冲突; //2017-08-25 change content: //1.修改smartconfig,将超时设置取消,一直等待用户输入,直到设置成功; static double s1,s2,t1,t2; static int i = 0; //32 Dust counter static int count = 0; //10 Dust counter static int num = 0; //28 Dust counter static float y = 1; ///0.58; //Dust 1.76 static float y1 = 1; //nosie static float y2 = 1; //sun � static float y3=1; //Temp � 25.8/19.34 static float y4=1; //Humi� 63/53.25 static int y5=1; //CO2� static int y6=1; //TVOC static int y7=1; //CO static double D0=0.00; static double D1=0.00; static double DS=0.00; static float z1=0.000163033; static float z2=1.01402; static float z3=2.55026; static float h1=1.1438; static float h2=1.5616; static char* PDCServer= "mlbserver.foxconn.com"; static int count_green=0; static long fenchen_sum=0; static long last_fenchen_sum=0; static long last_pm25=0; static int queueflag=0; class Hermes{ private: public: void init(); void init_with_smartconfig(); void exec(); void status_show(int color); void pms_reset(); void pms_init(); void light_init(); void temp_init(); bool postDataToPDC(char* deviceNum,char* functionType,char* deviceIP,char* BTaddr,char* dust,char* noise,char* sun1,char* sun2,char* temp,char* hum,char* CO2,char* TVOC,char* O2,char* motion1,char* motion2,char* resv1,char* resv2,char* resv3,char* resv4,char* resv5); double noise_test(); void co_init(); double co_test(); unsigned char FucCheckSum(unsigned char *i,unsigned char ln); void get_motion_value(int& motion1,int& motion2); void get_smoke_value(int& smoke); void wifi_control(); //2017-11-20 bool postLogToPDC(char* deviceNum,char* logValue); bool postToServer(); //2018-02-27清空密碼 bool postResultToPDC(char* deviceNum,char* Mac); // bool ClearPasswordFun(); //2018-03-16遠程修改Server IP bool postChangeServerResultToPDC(char* Mac); bool ChangeServerIPFun(); }; static Hermes *hermes; #endif
8ae68b1653c71f677646a30da645874166d7bfb9
ac24493aad6db8f720ea46eba8aa79f5981252f5
/SendMail_Ver00.01_00_forGit/sstd_socket/sendMail.cpp
4e3e29a84cc20a92b3ad5b1e9d97950c15b2af80
[ "MIT" ]
permissive
admiswalker/For-pasting-on-a-blog
d8eb8548e7b842827b84ce5acccf2bdbbc6cb1b7
21350d1bdfe4b29ab364074e1c886a3e0eba97ba
refs/heads/master
2020-03-28T22:25:29.892549
2019-05-29T13:54:04
2019-05-29T13:54:04
94,627,413
0
0
null
null
null
null
UTF-8
C++
false
false
9,824
cpp
#include <sstd/sstd.hpp> #include "socket.hpp" #include "sendMail.hpp" bool sendMail(struct sMail& mail){ sstd::sockSSL sock(sstd::ssprintf("smtp.%s", mail.domain.c_str()).c_str(), "465"); bool ret; if(!sock.open()){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send("EHLO localhost\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send("AUTH LOGIN\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send(sstd::base64_encode(mail.usr)+"\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} // mail User ID if( sock.send(sstd::base64_encode(mail.pass)+"\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} // mail pass if( sock.send("MAIL FROM: <"+mail.usr+'@'+mail.domain+">\r\n")<=0){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send("RCPT TO: <"+mail.to+">\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send("DATA\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} std::string buf; buf = "Subject: =?UTF-8?B?"+sstd::base64_encode(mail.subject)+"?=\r\n"; buf += "Mime-Version: 1.0;\r\n"; buf += "Content-Type: text/plain; charset=\"UTF-8\";\r\n"; buf += "Content-Transfer-Encoding: 7bit;\r\n"; buf += "\r\n"; buf += mail.data+"\r\n"; buf += ".\r\n"; if( sock.send(buf )<=0){return false;} sock.recv(ret); if(!ret){return false;} return true; } bool sendMail_withPrint(struct sMail& mail){ sstd::sockSSL sock(sstd::ssprintf("smtp.%s", mail.domain.c_str()).c_str(), "465"); bool ret; if(!sock.open()){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} if( sock.send_withPrint("EHLO localhost\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} if( sock.send_withPrint("AUTH LOGIN\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} printf("Sending Data >> %s\n", mail.usr.c_str()); if( sock.send_withPrint(sstd::base64_encode(mail.usr)+"\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} // mail User ID printf("Sending Data >> %s\n", mail.pass.c_str()); if( sock.send_withPrint(sstd::base64_encode(mail.pass)+"\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} // mail pass if( sock.send_withPrint("MAIL FROM: <"+mail.usr+'@'+mail.domain+">\r\n")<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} if( sock.send_withPrint("RCPT TO: <"+mail.to+">\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} if( sock.send_withPrint("DATA\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} std::string buf; buf = "Subject: =?UTF-8?B?"+sstd::base64_encode(mail.subject)+"?=\r\n"; buf += "Mime-Version: 1.0;\r\n"; buf += "Content-Type: text/plain; charset=\"UTF-8\";\r\n"; buf += "Content-Transfer-Encoding: 7bit;\r\n"; buf += "\r\n"; buf += mail.data+"\r\n"; buf += ".\r\n"; if( sock.send_withPrint(buf )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} return true; } bool sendMail_of_HTML(struct sMail& mail){ sstd::sockSSL sock(sstd::ssprintf("smtp.%s", mail.domain.c_str()).c_str(), "465"); bool ret; if(!sock.open()){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send("EHLO localhost\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send("AUTH LOGIN\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send(sstd::base64_encode(mail.usr)+"\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} // mail User ID if( sock.send(sstd::base64_encode(mail.pass)+"\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} // mail pass if( sock.send("MAIL FROM: <"+mail.usr+'@'+mail.domain+">\r\n")<=0){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send("RCPT TO: <"+mail.to+">\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} if( sock.send("DATA\r\n" )<=0){return false;} sock.recv(ret); if(!ret){return false;} std::string buf; buf = "Subject: =?UTF-8?B?"+sstd::base64_encode(mail.subject)+"?=\r\n"; buf += "Mime-Version: 1.0;\r\n"; buf += "Content-Type: text/html; charset=\"UTF-8\";\r\n"; buf += "Content-Transfer-Encoding: 7bit;\r\n"; buf += "\r\n"; buf += mail.data+"\r\n"; buf += ".\r\n"; if( sock.send(buf )<=0){return false;} sock.recv(ret); if(!ret){return false;} return true; } bool sendMail_of_HTML_withPrint(struct sMail& mail){ sstd::sockSSL sock(sstd::ssprintf("smtp.%s", mail.domain.c_str()).c_str(), "465"); // poart number >> 465: SMTP over SSL // 587: TLS bool ret; if(!sock.open()){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} if( sock.send_withPrint("EHLO localhost\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} if( sock.send_withPrint("AUTH LOGIN\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} printf("Sending Data >> %s\n", mail.usr.c_str()); if( sock.send_withPrint(sstd::base64_encode(mail.usr)+"\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} // mail User ID printf("Sending Data >> %s\n", mail.pass.c_str()); if( sock.send_withPrint(sstd::base64_encode(mail.pass)+"\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} // mail pass if( sock.send_withPrint("MAIL FROM: <"+mail.usr+'@'+mail.domain+">\r\n")<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} if( sock.send_withPrint("RCPT TO: <"+mail.to+">\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} if( sock.send_withPrint("DATA\r\n" )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} //std::string Subject_str = "TESTING_NOW_テスト投稿__(全角アンダーバーとか入れてみる。)_(全角アンダーバーとか入れてみる。)文字数制限を確認する為に、長いタイトルを送信してみる。たしか、約80文字以上に長いタイトルの場合は、文字ごとにまとめて改行を施すなど、多少面倒な操作が必要とされるらしい。まだ長さが足りないので、もう少し文字数を増やして見る。果たしてちゃんと(?)失敗するだろうか?いやいやぁ、まだまだこの程度の長さでは全くもう失敗しないので、もう少しもうだいぶ長くしてみようと思うんだけど、これ本当に失敗するのかな?Gmailが優秀だから失敗しないのか、それとも、そもそも最近の規格では考える必要が無くなったのか、その辺りをはっきりさせたいのだが、そろそろキーボードを叩くのが面倒になってきた。(半角『』)結局失敗しなかった……。もう成功って事で良いよね????"; //Gmailの送信箱や受信箱では、おおよそ167文字以上からの表示がバグる。ただし、Blogger側での表示は正常。 //sock.SendMsg = "Subject: \r\n"; //sock.SendMsg = "Subject: =?ISO-2022-JP?Q?XXXXXXX?=\r\n"; //sock.SendMsg = "Subject: =?ISO-2022-JP?B?XXXXXXX?=\r\n"; //sock.SendMsg = "Subject: =?UTF-8?Q?"; std::string buf; buf = "Subject: =?UTF-8?B?"+sstd::base64_encode(mail.subject)+"?=\r\n"; buf += "Mime-Version: 1.0;\r\n"; // buf += "Content-Type: text/html; charset=\"ISO-8859-1\";\r\n"; buf += "Content-Type: text/html; charset=\"UTF-8\";\r\n"; buf += "Content-Transfer-Encoding: 7bit;\r\n"; buf += "\r\n"; buf += mail.data+"\r\n"; buf += ".\r\n"; if( sock.send_withPrint(buf )<=0){return false;} sstd::print(sock.recv(ret)); if(!ret){return false;} return true; } /* 220 smtp.gmail.com ESMTP XXXXXXXXXXXXXXXXXXX - gsmtp Send Data >> EHLO localhost 250-smtp.gmail.com at your service, [XXX.XXX.XXX.XXX] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8 Send Data >> AUTH LOGIN 334 VXNlcm5hbWU6 Send Data >> [base64Encoded_usrName] 334 UGFzc3dvcmQ6 Send Data >> [base64Encoded_passWord] 235 2.7.0 Accepted Send Data >> MAIL FROM: <[usrName]@[domain]> 250 2.1.0 OK XXXXXXXXXXXXXXXXXXX - gsmtp Send Data >> RCPT TO: <[mail.to]> 250 2.1.5 OK XXXXXXXXXXXXXXXXXXX - gsmtp Send Data >> DATA 354 Go ahead XXXXXXXXXXXXXXXXXXX - gsmtp Send Data >> Subject: =?UTF-8?B?VEVTVElOR19OT1df44OG44K544OI5oqV56i/X+ODnuODq+ODgeODkOOCpOODiOOCs+ODvOODieOCguiHqueUseiHquWcqCEh?= Mime-Version: 1.0; Content-Type: text/html; charset="UTF-8"; Content-Transfer-Encoding: 7bit; <br/>これは,HTML メールの送信テストです.<br/>■■■ <b><u>タイトル</u></b> ■■■<br/><ul><li>項目 1. </li><li>項目 2. </li></ul><br/><hr/><br/>abc あいう<br/><br/> . 250 2.0.0 OK 1522244454 XXXXXXXXXXXXXXXXXXX - gsmtp */
d64292b6f5d6db8e8a0e4221b2f1812bc09e02f7
78c9fff3b11e19a3b11f0ecda4d5681f260e6305
/src/BabylonCpp/include/babylon/shaders/default_vertex_fx.h
42af109f0a0d4c1ec9b6b2da6a8891442b5e0e9f
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
sacceus/BabylonCpp
fe43406f9c6472f1b303fbdabde62f0f4c31d26a
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
refs/heads/master
2022-11-08T20:55:14.723048
2020-06-25T21:35:14
2020-06-25T21:35:14
274,984,203
0
0
Apache-2.0
2020-06-25T18:10:16
2020-06-25T18:10:15
null
UTF-8
C++
false
false
5,582
h
#ifndef BABYLON_SHADERS_DEFAULT_VERTEX_FX_H #define BABYLON_SHADERS_DEFAULT_VERTEX_FX_H namespace BABYLON { extern const char* defaultVertexShader; const char* defaultVertexShader = R"ShaderCode( #include<__decl__defaultVertex> // Attributes #define CUSTOM_VERTEX_BEGIN attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #ifdef TANGENT attribute vec4 tangent; #endif #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #ifdef VERTEXCOLOR attribute vec4 color; #endif #include<helperFunctions> #include<bonesDeclaration> // Uniforms #include<instancesDeclaration> #ifdef MAINUV1 varying vec2 vMainUV1; #endif #ifdef MAINUV2 varying vec2 vMainUV2; #endif #if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 varying vec2 vDiffuseUV; #endif #if defined(AMBIENT) && AMBIENTDIRECTUV == 0 varying vec2 vAmbientUV; #endif #if defined(OPACITY) && OPACITYDIRECTUV == 0 varying vec2 vOpacityUV; #endif #if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 varying vec2 vEmissiveUV; #endif #if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 varying vec2 vLightmapUV; #endif #if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0 varying vec2 vSpecularUV; #endif #if defined(BUMP) && BUMPDIRECTUV == 0 varying vec2 vBumpUV; #endif // Output varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #ifdef VERTEXCOLOR varying vec4 vColor; #endif #include<bumpVertexDeclaration> #include<clipPlaneVertexDeclaration> #include<fogVertexDeclaration> #include<__decl__lightFragment>[0..maxSimultaneousLights] #include<morphTargetsVertexGlobalDeclaration> #include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #include<logDepthDeclaration> #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 positionUpdated = position; #ifdef NORMAL vec3 normalUpdated = normal; #endif #ifdef TANGENT vec4 tangentUpdated = tangent; #endif #ifdef UV1 vec2 uvUpdated = uv; #endif #include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vPositionUVW = positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include<instancesVertex> #include<bonesVertex> vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); #ifdef MULTIVIEW if (gl_ViewID_OVR == 0u) { gl_Position = viewProjection * worldPos; } else { gl_Position = viewProjectionR * worldPos; } #else gl_Position = viewProjection * worldPos; #endif vPositionW = vec3(worldPos); #ifdef NORMAL mat3 normalWorld = mat3(finalWorld); #ifdef NONUNIFORMSCALING normalWorld = transposeMat3(inverseMat3(normalWorld)); #endif vNormalW = normalize(normalWorld * normalUpdated); #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vDirectionW = normalize(vec3(finalWorld * vec4(positionUpdated, 0.0))); #endif // Texture coordinates #ifndef UV1 vec2 uvUpdated = vec2(0., 0.); #endif #ifndef UV2 vec2 uv2 = vec2(0., 0.); #endif #ifdef MAINUV1 vMainUV1 = uvUpdated; #endif #ifdef MAINUV2 vMainUV2 = uv2; #endif #if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 if (vDiffuseInfos.x == 0.) { vDiffuseUV = vec2(diffuseMatrix * vec4(uvUpdated, 1.0, 0.0)); } else { vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0)); } #endif #if defined(AMBIENT) && AMBIENTDIRECTUV == 0 if (vAmbientInfos.x == 0.) { vAmbientUV = vec2(ambientMatrix * vec4(uvUpdated, 1.0, 0.0)); } else { vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0)); } #endif #if defined(OPACITY) && OPACITYDIRECTUV == 0 if (vOpacityInfos.x == 0.) { vOpacityUV = vec2(opacityMatrix * vec4(uvUpdated, 1.0, 0.0)); } else { vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0)); } #endif #if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 if (vEmissiveInfos.x == 0.) { vEmissiveUV = vec2(emissiveMatrix * vec4(uvUpdated, 1.0, 0.0)); } else { vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0)); } #endif #if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 if (vLightmapInfos.x == 0.) { vLightmapUV = vec2(lightmapMatrix * vec4(uvUpdated, 1.0, 0.0)); } else { vLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0)); } #endif #if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0 if (vSpecularInfos.x == 0.) { vSpecularUV = vec2(specularMatrix * vec4(uvUpdated, 1.0, 0.0)); } else { vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0)); } #endif #if defined(BUMP) && BUMPDIRECTUV == 0 if (vBumpInfos.x == 0.) { vBumpUV = vec2(bumpMatrix * vec4(uvUpdated, 1.0, 0.0)); } else { vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0)); } #endif #include<bumpVertex> #include<clipPlaneVertex> #include<fogVertex> #include<shadowsVertex>[0..maxSimultaneousLights] #ifdef VERTEXCOLOR // Vertex color vColor = color; #endif #include<pointCloudVertex> #include<logDepthVertex> #define CUSTOM_VERTEX_MAIN_END } )ShaderCode"; } // end of namespace BABYLON #endif // end of BABYLON_SHADERS_DEFAULT_VERTEX_FX_H
18285120651dcfae450dfa271bd74983cf51454b
377d69a058a0b5a1c66352fe7d5f27c9ef99a987
/core/dynamicarray.h
78e29a33469337626207640d905dd58ee50fbed6
[ "Apache-2.0" ]
permissive
frozenca/CLRS
45782d67343eb285f2d95d8c25184b9973079e65
408a86c4c0ec7d106bdaa6f5526b186df9f65c2e
refs/heads/main
2022-09-24T14:55:38.542993
2022-09-12T02:59:10
2022-09-12T02:59:10
337,278,655
55
15
null
null
null
null
UTF-8
C++
false
false
5,561
h
#ifndef __CLRS4_DYNAMIC_ARRAY_H__ #define __CLRS4_DYNAMIC_ARRAY_H__ #include <algorithm> #include <bit> #include <common.h> #include <memory> #include <ranges> #include <stdexcept> #include <vector> namespace frozenca { using namespace std; template <Containable T> class DynamicArray { ptrdiff_t size_ = 0; size_t capacity_ = 0; T *buf_ = nullptr; public: using size_type = ptrdiff_t; using value_type = T; using reference_type = T &; using const_reference_type = const T &; using pointer_type = T *; using const_pointer_type = const T *; using iterator_type = T *; using const_iterator_type = const T *; using reverse_iterator_type = reverse_iterator<iterator_type>; using const_reverse_iterator_type = reverse_iterator<const_iterator_type>; DynamicArray() = default; ~DynamicArray() noexcept { allocator<T>{}.deallocate(buf_, capacity_); } DynamicArray(ptrdiff_t size) : size_{size}, capacity_{bit_ceil(static_cast<size_t>(size))} { buf_ = allocator<T>{}.allocate(capacity_); } DynamicArray(ptrdiff_t size, const T &value) : DynamicArray(size) { ranges::uninitialized_fill_n(buf_, size_, value); } DynamicArray(const DynamicArray &l) : DynamicArray(l.size_) { ranges::uninitialized_copy_n(buf_, size_, l.buf_, l.buf_ + l.size_); } DynamicArray &operator=(const DynamicArray &l) { DynamicArray arr(l); swap(*this, arr); return *this; } DynamicArray(DynamicArray &&l) noexcept : size_{l.size_}, capacity_{bit_ceil(static_cast<size_t>(l.size_))}, buf_{l.buf_} { l.size_ = 0; l.capacity_ = 0; l.buf_ = nullptr; } DynamicArray &operator=(DynamicArray &&l) noexcept { DynamicArray arr(move(l)); swap(*this, arr); return *this; } [[nodiscard]] bool empty() const noexcept { return size_ == 0; } [[nodiscard]] ptrdiff_t size() const noexcept { return size_; } [[nodiscard]] ptrdiff_t capacity() const noexcept { return capacity_; } [[nodiscard]] iterator_type begin() noexcept { return buf_; } [[nodiscard]] const_iterator_type begin() const noexcept { return const_cast<const_pointer_type>(buf_); } [[nodiscard]] const_iterator_type cbegin() const noexcept { return const_cast<const_pointer_type>(buf_); } [[nodiscard]] iterator_type end() noexcept { return buf_ + size_; } [[nodiscard]] const_iterator_type end() const noexcept { return const_cast<const_pointer_type>(buf_ + size_); } [[nodiscard]] const_iterator_type cend() const noexcept { return const_cast<const_pointer_type>(buf_ + size_); } [[nodiscard]] reverse_iterator_type rbegin() noexcept { return reverse_iterator_type(end()); } [[nodiscard]] const_reverse_iterator_type rbegin() const noexcept { return const_reverse_iterator_type(end()); } [[nodiscard]] const_reverse_iterator_type crbegin() const noexcept { return const_reverse_iterator_type(end()); } [[nodiscard]] reverse_iterator_type rend() noexcept { return reverse_iterator_type(begin()); } [[nodiscard]] const_reverse_iterator_type rend() const noexcept { return const_reverse_iterator_type(begin()); } [[nodiscard]] const_reverse_iterator_type crend() const noexcept { return const_reverse_iterator_type(begin()); } reference_type operator[](size_type pos) { return *(buf_ + pos); } const_reference_type operator[](size_type pos) const { return *(const_cast<const_pointer_type>(buf_) + pos); } reference_type front() { return *(buf_); } const_reference_type front() const { return *(const_cast<const_pointer_type>(buf_)); } reference_type back() { return *(buf_ + size_ - 1); } const_reference_type back() const { return *(const_cast<const_pointer_type>(buf_) + size_ - 1); } private: void enlarge(size_type count) { assert(count > size_); auto new_capacity = bit_ceil(static_cast<size_t>(count)); if (new_capacity > capacity_) { auto new_buf = allocator<T>{}.allocate(new_capacity); ranges::uninitialized_move_n(buf_, size_, new_buf, new_buf + size_); allocator<T>{}.deallocate(buf_, capacity_); capacity_ = new_capacity; buf_ = new_buf; } } public: void resize(size_type count) { if (count < 0) { throw invalid_argument("negative size\n"); } if (count < size_) { auto new_last = buf_ + count; auto to_destroy = size_ - count; ranges::destroy_n(new_last, to_destroy); size_ = count; } else if (count > size_) { enlarge(count); auto to_construct = count - size_; auto old_end = buf_ + size_; for (index_t i = 0; i < to_construct; ++i) { ranges::construct_at(old_end++); } size_ = count; } } void push_back(const T &value) { enlarge(size_ + 1); ranges::construct_at(buf_ + size_, value); size_++; } void push_back(T &&value) { enlarge(size_ + 1); ranges::construct_at(buf_ + size_, move(value)); size_++; } template <typename... Args> reference_type emplace_back(Args &&...args) { enlarge(size_ + 1); ranges::construct_at(buf_ + size_, forward<Args>(args)...); auto ptr = buf_ + size_; size_++; return *ptr; } void pop_back() { ranges::destroy_at(buf_ + size_ - 1); size_--; } }; } // namespace frozenca #endif //__CLRS4_DYNAMIC_ARRAY_H__
ab1f7f9ca9ccc9c29e3f60f740ab7d7427283bff
0e18f02e56473117036ebec04c42c18878a538d8
/EX9/EX9/EX9View.cpp
30a410a5510bcc5b022dc8b8c968e2fd065bcfc2
[]
no_license
QinQian7/QXQ
140a2cc43b7382506dda55b636815d5b799a1c5f
e9cf240f7376f174610435ad125038a89b27b287
refs/heads/master
2021-04-01T09:10:41.066461
2020-07-05T15:34:20
2020-07-05T15:34:20
248,176,040
0
0
null
null
null
null
GB18030
C++
false
false
1,776
cpp
// EX9View.cpp : CEX9View 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "EX9.h" #endif #include "EX9Doc.h" #include "EX9View.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CEX9View IMPLEMENT_DYNCREATE(CEX9View, CView) BEGIN_MESSAGE_MAP(CEX9View, CView) ON_COMMAND(ID_FILE_OPEN, &CEX9View::OnFileOpen) END_MESSAGE_MAP() // CEX9View 构造/析构 CEX9View::CEX9View() { // TODO: 在此处添加构造代码 } CEX9View::~CEX9View() { } BOOL CEX9View::PreCreateWindow(CREATESTRUCT& cs) { // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 return CView::PreCreateWindow(cs); } // CEX9View 绘制 void CEX9View::OnDraw(CDC* pDC) { CEX9Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: 在此处为本机数据添加绘制代码 CPoint c; CRect cr; GetClientRect(&cr); c = cr.CenterPoint(); if (a==IDOK) { img.Draw(pDC->m_hDC, c.x - img.GetWidth() / 2, c.y - img.GetHeight() / 2, img.GetWidth(), img.GetHeight()); } } // CEX9View 诊断 #ifdef _DEBUG void CEX9View::AssertValid() const { CView::AssertValid(); } void CEX9View::Dump(CDumpContext& dc) const { CView::Dump(dc); } CEX9Doc* CEX9View::GetDocument() const // 非调试版本是内联的 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CEX9Doc))); return (CEX9Doc*)m_pDocument; } #endif //_DEBUG // CEX9View 消息处理程序 void CEX9View::OnFileOpen() { // TODO: 在此添加命令处理程序代码 CFileDialog cfd(true); a = cfd.DoModal(); if (a == IDOK) filename = cfd.GetPathName(); img.Load(filename); Invalidate(); }
ba313450bff0005afc32ac5ae9d9144a6ffbba3b
4179fd3d728cb0cb64f1b2106afdeac565c9efb1
/프로그래머스_kakao2019blind_후보키.cpp
b37c1337dae90cd87a103ff2cfb177508b79876b
[]
no_license
tnqkr98/Programmers_Solutions
5eb0e5c0734235cfcc59f0a50d28b7ee58adcc62
368bec54b862e55a9ab004c7a51b5a86a09b68e3
refs/heads/master
2023-08-15T00:35:58.314486
2021-10-08T17:56:42
2021-10-08T17:56:42
272,715,216
0
0
null
null
null
null
UHC
C++
false
false
1,259
cpp
#include <string> #include <vector> #include <set> using namespace std; vector<vector<string>> r; bool sel[8]; int answer = 0, colsiz, rowsiz; bool isUniqu(vector<bool> se) { set<string> s; // 유일성 검증용 집합 vector<string> record(20, ""); for (int i = 0; i < colsiz; i++) if (se[i]) for (int j = 0; j < rowsiz; j++) record[j] += r[j][i]; for (int i = 0; i < rowsiz; i++) { if (s.find(record[i]) == s.end()) s.insert(record[i]); else return false; } return true; } bool isMini(vector<bool> se) { for (int i = 0; i < colsiz; i++) if (se[i]) { se[i] = 0; if (isUniqu(se)) return false; se[i] = 1; } return true; } void proon(int idx) { vector<bool> se(8); int cnt = 0; for (int i = 0; i < colsiz; i++) { if (sel[i]) cnt++; se[i] = sel[i]; } if (isUniqu(se)) { if (cnt > 1 && isMini(se)) answer++; // 후보키 else if (cnt == 1) answer++; } else { // 유일성 만족 X for (int i = idx + 1; i < colsiz; i++) { sel[i] = 1; proon(i); sel[i] = 0; } } } int solution(vector<vector<string>> relation) { colsiz = relation[0].size(); rowsiz = relation.size(); r = relation; for (int i = 0; i < colsiz; i++) { sel[i] = 1; proon(i); sel[i] = 0; } return answer; }
81f6f2f67196cf2f788ce62f4c2fcfe961d00b85
a75f391cc6c5e0e1a503c332265b751d4404301b
/zadanie1/Node.cpp
1bbabbae9fbba1f2eb2f2f7647e6e93dccb38d57
[]
no_license
rafalrab/prefixes
a35fe12768848ccfa90f1163e37c28c84667e711
8af267f5d638b21eefe89306ce78ecc4ad971131
refs/heads/master
2022-05-30T06:26:12.770906
2020-05-04T19:25:39
2020-05-04T19:25:39
261,276,236
0
0
null
null
null
null
UTF-8
C++
false
false
190
cpp
#include "pch.h" #include "Node.h" #include <string> using namespace std; Node::Node() { isEndOfWord = false; for (int i = 0;i < 26;i++) { children[i] = NULL; } } Node::~Node() { }
5bc46ccca5d2714ffbf31a907dcb444b517d88f8
d939ea588d1b215261b92013e050993b21651f9a
/monitor/src/v20180724/model/DeleteServiceDiscoveryResponse.cpp
25749aba30de0846a28d0ab93ee322c2cdef7e66
[ "Apache-2.0" ]
permissive
chenxx98/tencentcloud-sdk-cpp
374e6d1349f8992893ded7aa08f911dd281f1bda
a9e75d321d96504bc3437300d26e371f5f4580a0
refs/heads/master
2023-03-27T05:35:50.158432
2021-03-26T05:18:10
2021-03-26T05:18:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,479
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/monitor/v20180724/model/DeleteServiceDiscoveryResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Monitor::V20180724::Model; using namespace rapidjson; using namespace std; DeleteServiceDiscoveryResponse::DeleteServiceDiscoveryResponse() { } CoreInternalOutcome DeleteServiceDiscoveryResponse::Deserialize(const string &payload) { Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Error("response `Response` is null or not object")); } Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId)); } return CoreInternalOutcome(true); }
37a4ba3a04b58266bfb85ff62cd5c55dda78ac9f
1cd3b20b42c959853f9439bf3c282393a6b83672
/track_moves_on_keyboard.cpp
25257a63546246f56276c7824f029fe282fbba3d
[]
no_license
prathy16/LeetCode
4f8556ad887198a22dc312fd49b597b6e98472e0
0297c0d8d06f0282f866d2e90b65a2cf65b87395
refs/heads/master
2020-03-23T02:39:24.851836
2019-01-15T07:25:05
2019-01-15T07:25:05
140,984,745
0
0
null
null
null
null
UTF-8
C++
false
false
880
cpp
// KEYBOARD // a b c d e f g // h i j k l m n // o p q r s t u // v w x y z #include<iostream> #include<vector> using namespace std; string moves(string word) { pair<int, int> curPos(0,0); string output; int x, y, temp; for(char c: word) { x = (c - 'a')/7; y = (c - 'a')%7; temp = x - curPos.first; if(temp < 0){ output.insert(output.end(), -temp, 'U'); } else if(temp > 0){ output.insert(output.end(), temp, 'D'); } temp = y - curPos.second; if(temp < 0){ output.insert(output.end(), -temp, 'L'); } else if(temp > 0){ output.insert(output.end(), temp, 'R'); } curPos = pair<int, int>(x, y); } return output; } int main() { string output = moves("prathy"); cout << output << endl; return 0; }
4e9064a1371210ab5b86c9d4cbfe83f7c55c3755
f621b77a182cde71445de3034221fe4881d3fb99
/libcef/common/main_delegate.cc
3b02881d9e3fd159360495037b25818a216c99dc
[ "BSD-3-Clause" ]
permissive
qnxdev/cef
9795eaa87ab30b9d22b9e5d7094d9cf2cb9ac039
30d83cb94a79e6548ecb4db4f8d6ad587f3b3177
refs/heads/master
2022-04-12T19:16:12.681550
2020-04-08T15:43:39
2020-04-08T15:43:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,148
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "libcef/common/main_delegate.h" #if defined(OS_LINUX) #include <dlfcn.h> #endif #include "libcef/browser/browser_message_loop.h" #include "libcef/browser/content_browser_client.h" #include "libcef/browser/context.h" #include "libcef/common/cef_switches.h" #include "libcef/common/command_line_impl.h" #include "libcef/common/crash_reporting.h" #include "libcef/common/extensions/extensions_util.h" #include "libcef/renderer/content_renderer_client.h" #include "base/at_exit.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/media/router/media_router_feature.h" #include "chrome/child/pdf_child_init.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #include "chrome/utility/chrome_content_utility_client.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/viz/common/features.h" #include "content/browser/browser_process_sub_thread.h" #include "content/browser/scheduler/browser_task_executor.h" #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "extensions/common/constants.h" #include "ipc/ipc_buildflags.h" #include "pdf/pdf_ppapi.h" #include "services/network/public/cpp/features.h" #include "services/service_manager/sandbox/switches.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_features.h" #include "ui/base/ui_base_paths.h" #include "ui/base/ui_base_switches.h" #if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED) #define IPC_MESSAGE_MACROS_LOG_ENABLED #include "content/public/common/content_ipc_logging.h" #define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \ content::RegisterIPCLogger(msg_id, logger) #include "libcef/common/cef_message_generator.h" #endif #if defined(OS_WIN) #include <Objbase.h> #include "base/win/registry.h" #endif #if defined(OS_MACOSX) #include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "content/public/common/content_paths.h" #include "libcef/common/util_mac.h" #endif #if defined(OS_LINUX) #include "base/environment.h" #include "base/nix/xdg_util.h" #endif namespace { const char* const kNonWildcardDomainNonPortSchemes[] = { extensions::kExtensionScheme}; const size_t kNonWildcardDomainNonPortSchemesSize = base::size(kNonWildcardDomainNonPortSchemes); #if defined(OS_MACOSX) base::FilePath GetResourcesFilePath() { return util_mac::GetFrameworkResourcesDirectory(); } // Use a "~/Library/Logs/<app name>_debug.log" file where <app name> is the name // of the running executable. base::FilePath GetDefaultLogFile() { std::string exe_name = util_mac::GetMainProcessPath().BaseName().value(); return base::mac::GetUserLibraryPath() .Append(FILE_PATH_LITERAL("Logs")) .Append(FILE_PATH_LITERAL(exe_name + "_debug.log")); } void OverrideFrameworkBundlePath() { base::FilePath framework_path = util_mac::GetFrameworkDirectory(); DCHECK(!framework_path.empty()); base::mac::SetOverrideFrameworkBundlePath(framework_path); } void OverrideOuterBundlePath() { base::FilePath bundle_path = util_mac::GetMainBundlePath(); DCHECK(!bundle_path.empty()); base::mac::SetOverrideOuterBundlePath(bundle_path); } void OverrideBaseBundleID() { std::string bundle_id = util_mac::GetMainBundleID(); DCHECK(!bundle_id.empty()); base::mac::SetBaseBundleID(bundle_id.c_str()); } void OverrideChildProcessPath() { base::FilePath child_process_path = base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kBrowserSubprocessPath); if (child_process_path.empty()) { child_process_path = util_mac::GetChildProcessPath(); DCHECK(!child_process_path.empty()); } // Used by ChildProcessHost::GetChildPath and PlatformCrashpadInitialization. base::PathService::Override(content::CHILD_PROCESS_EXE, child_process_path); } #else // !defined(OS_MACOSX) base::FilePath GetResourcesFilePath() { base::FilePath pak_dir; base::PathService::Get(base::DIR_ASSETS, &pak_dir); return pak_dir; } // Use a "debug.log" file in the running executable's directory. base::FilePath GetDefaultLogFile() { base::FilePath log_path; base::PathService::Get(base::DIR_EXE, &log_path); return log_path.Append(FILE_PATH_LITERAL("debug.log")); } #endif // !defined(OS_MACOSX) #if defined(OS_WIN) // Gets the Flash path if installed on the system. bool GetSystemFlashFilename(base::FilePath* out_path) { const wchar_t kPepperFlashRegistryRoot[] = L"SOFTWARE\\Macromedia\\FlashPlayerPepper"; const wchar_t kFlashPlayerPathValueName[] = L"PlayerPath"; base::win::RegKey path_key(HKEY_LOCAL_MACHINE, kPepperFlashRegistryRoot, KEY_READ); base::string16 path_str; if (FAILED(path_key.ReadValue(kFlashPlayerPathValueName, &path_str))) return false; *out_path = base::FilePath(path_str); return true; } #elif defined(OS_MACOSX) const base::FilePath::CharType kPepperFlashSystemBaseDirectory[] = FILE_PATH_LITERAL("Internet Plug-Ins/PepperFlashPlayer"); #endif void OverridePepperFlashSystemPluginPath() { base::FilePath plugin_filename; #if defined(OS_WIN) if (!GetSystemFlashFilename(&plugin_filename)) return; #elif defined(OS_MACOSX) if (!util_mac::GetLocalLibraryDirectory(&plugin_filename)) return; plugin_filename = plugin_filename.Append(kPepperFlashSystemBaseDirectory) .Append(chrome::kPepperFlashPluginFilename); #else // A system plugin is not available on other platforms. return; #endif if (!plugin_filename.empty()) { base::PathService::Override(chrome::FILE_PEPPER_FLASH_SYSTEM_PLUGIN, plugin_filename); } } #if defined(OS_LINUX) // Based on chrome/common/chrome_paths_linux.cc. // See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html // for a spec on where config files go. The net effect for most // systems is we use ~/.config/chromium/ for Chromium and // ~/.config/google-chrome/ for official builds. // (This also helps us sidestep issues with other apps grabbing ~/.chromium .) bool GetDefaultUserDataDirectory(base::FilePath* result) { std::unique_ptr<base::Environment> env(base::Environment::Create()); base::FilePath config_dir(base::nix::GetXDGDirectory( env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir)); *result = config_dir.Append(FILE_PATH_LITERAL("cef_user_data")); return true; } #elif defined(OS_MACOSX) // Based on chrome/common/chrome_paths_mac.mm. bool GetDefaultUserDataDirectory(base::FilePath* result) { if (!base::PathService::Get(base::DIR_APP_DATA, result)) return false; *result = result->Append(FILE_PATH_LITERAL("CEF")); *result = result->Append(FILE_PATH_LITERAL("User Data")); return true; } #elif defined(OS_WIN) // Based on chrome/common/chrome_paths_win.cc. bool GetDefaultUserDataDirectory(base::FilePath* result) { if (!base::PathService::Get(base::DIR_LOCAL_APP_DATA, result)) return false; *result = result->Append(FILE_PATH_LITERAL("CEF")); *result = result->Append(FILE_PATH_LITERAL("User Data")); return true; } #endif base::FilePath GetUserDataPath() { const CefSettings& settings = CefContext::Get()->settings(); if (settings.user_data_path.length > 0) return base::FilePath(CefString(&settings.user_data_path)); base::FilePath result; if (GetDefaultUserDataDirectory(&result)) return result; if (base::PathService::Get(base::DIR_TEMP, &result)) return result; NOTREACHED(); return result; } bool GetDefaultDownloadDirectory(base::FilePath* result) { // This will return the safe download directory if necessary. return chrome::GetUserDownloadsDirectory(result); } // From chrome/browser/download/download_prefs.cc. // Consider downloads 'dangerous' if they go to the home directory on Linux and // to the desktop on any platform. bool DownloadPathIsDangerous(const base::FilePath& download_path) { #if defined(OS_LINUX) base::FilePath home_dir = base::GetHomeDir(); if (download_path == home_dir) { return true; } #endif base::FilePath desktop_dir; if (!base::PathService::Get(base::DIR_USER_DESKTOP, &desktop_dir)) { NOTREACHED(); return false; } return (download_path == desktop_dir); } bool GetDefaultDownloadSafeDirectory(base::FilePath* result) { // Start with the default download directory. if (!GetDefaultDownloadDirectory(result)) return false; if (DownloadPathIsDangerous(*result)) { #if defined(OS_WIN) || defined(OS_LINUX) // Explicitly switch to the safe download directory. return chrome::GetUserDownloadsDirectorySafe(result); #else // No viable alternative on macOS. return false; #endif } return true; } // Returns true if |scale_factor| is supported by this platform. // Same as ui::ResourceBundle::IsScaleFactorSupported. bool IsScaleFactorSupported(ui::ScaleFactor scale_factor) { const std::vector<ui::ScaleFactor>& supported_scale_factors = ui::GetSupportedScaleFactors(); return std::find(supported_scale_factors.begin(), supported_scale_factors.end(), scale_factor) != supported_scale_factors.end(); } #if defined(OS_LINUX) // Look for binary files (*.bin, *.dat, *.pak, chrome-sandbox, libGLESv2.so, // libEGL.so, locales/*.pak, swiftshader/*.so) next to libcef instead of the exe // on Linux. This is already the default on Windows. void OverrideAssetPath() { Dl_info dl_info; if (dladdr(reinterpret_cast<const void*>(&OverrideAssetPath), &dl_info)) { base::FilePath path = base::FilePath(dl_info.dli_fname).DirName(); base::PathService::Override(base::DIR_ASSETS, path); } } #endif } // namespace // Used to run the UI on a separate thread. class CefUIThread : public base::PlatformThread::Delegate { public: explicit CefUIThread(base::OnceClosure setup_callback) : setup_callback_(std::move(setup_callback)) {} ~CefUIThread() override { Stop(); } void Start() { base::AutoLock lock(thread_lock_); bool success = base::PlatformThread::CreateWithPriority( 0, this, &thread_, base::ThreadPriority::NORMAL); if (!success) { LOG(FATAL) << "failed to UI create thread"; } } void Stop() { base::AutoLock lock(thread_lock_); if (!stopping_) { stopping_ = true; base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&CefUIThread::ThreadQuitHelper, Unretained(this))); } // Can't join if the |thread_| is either already gone or is non-joinable. if (thread_.is_null()) return; base::PlatformThread::Join(thread_); thread_ = base::PlatformThreadHandle(); stopping_ = false; } bool WaitUntilThreadStarted() const { DCHECK(owning_sequence_checker_.CalledOnValidSequence()); start_event_.Wait(); return true; } void InitializeBrowserRunner( const content::MainFunctionParams& main_function_params) { // Use our own browser process runner. browser_runner_ = content::BrowserMainRunner::Create(); // Initialize browser process state. Uses the current thread's message loop. int exit_code = browser_runner_->Initialize(main_function_params); CHECK_EQ(exit_code, -1); } protected: void ThreadMain() override { base::PlatformThread::SetName("CefUIThread"); #if defined(OS_WIN) // Initializes the COM library on the current thread. CoInitialize(nullptr); #endif start_event_.Signal(); std::move(setup_callback_).Run(); base::RunLoop run_loop; run_loop_ = &run_loop; run_loop.Run(); browser_runner_->Shutdown(); browser_runner_.reset(nullptr); content::BrowserTaskExecutor::Shutdown(); // Run exit callbacks on the UI thread to avoid sequence check failures. base::AtExitManager::ProcessCallbacksNow(); #if defined(OS_WIN) // Closes the COM library on the current thread. CoInitialize must // be balanced by a corresponding call to CoUninitialize. CoUninitialize(); #endif run_loop_ = nullptr; } void ThreadQuitHelper() { DCHECK(run_loop_); run_loop_->QuitWhenIdle(); } std::unique_ptr<content::BrowserMainRunner> browser_runner_; base::OnceClosure setup_callback_; bool stopping_ = false; // The thread's handle. base::PlatformThreadHandle thread_; mutable base::Lock thread_lock_; // Protects |thread_|. base::RunLoop* run_loop_ = nullptr; mutable base::WaitableEvent start_event_; // This class is not thread-safe, use this to verify access from the owning // sequence of the Thread. base::SequenceChecker owning_sequence_checker_; }; CefMainDelegate::CefMainDelegate(CefRefPtr<CefApp> application) : content_client_(application) { // Necessary so that exported functions from base_impl.cc will be included // in the binary. extern void base_impl_stub(); base_impl_stub(); #if defined(OS_LINUX) OverrideAssetPath(); #endif } CefMainDelegate::~CefMainDelegate() {} void CefMainDelegate::PreCreateMainMessageLoop() { InitMessagePumpFactoryForUI(); } bool CefMainDelegate::BasicStartupComplete(int* exit_code) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::string process_type = command_line->GetSwitchValueASCII(switches::kProcessType); #if defined(OS_POSIX) // Read the crash configuration file. Platforms using Breakpad also add a // command-line switch. On Windows this is done from chrome_elf. crash_reporting::BasicStartupComplete(command_line); #endif if (process_type.empty()) { // In the browser process. Populate the global command-line object. const CefSettings& settings = CefContext::Get()->settings(); if (settings.command_line_args_disabled) { // Remove any existing command-line arguments. base::CommandLine::StringVector argv; argv.push_back(command_line->GetProgram().value()); command_line->InitFromArgv(argv); const base::CommandLine::SwitchMap& map = command_line->GetSwitches(); const_cast<base::CommandLine::SwitchMap*>(&map)->clear(); } bool no_sandbox = settings.no_sandbox ? true : false; if (settings.browser_subprocess_path.length > 0) { base::FilePath file_path = base::FilePath(CefString(&settings.browser_subprocess_path)); if (!file_path.empty()) { command_line->AppendSwitchPath(switches::kBrowserSubprocessPath, file_path); #if defined(OS_WIN) // The sandbox is not supported when using a separate subprocess // executable on Windows. no_sandbox = true; #endif } } #if defined(OS_MACOSX) if (settings.framework_dir_path.length > 0) { base::FilePath file_path = base::FilePath(CefString(&settings.framework_dir_path)); if (!file_path.empty()) command_line->AppendSwitchPath(switches::kFrameworkDirPath, file_path); } if (settings.main_bundle_path.length > 0) { base::FilePath file_path = base::FilePath(CefString(&settings.main_bundle_path)); if (!file_path.empty()) command_line->AppendSwitchPath(switches::kMainBundlePath, file_path); } #endif if (no_sandbox) command_line->AppendSwitch(service_manager::switches::kNoSandbox); if (settings.user_agent.length > 0) { command_line->AppendSwitchASCII(switches::kUserAgent, CefString(&settings.user_agent)); } else if (settings.product_version.length > 0) { command_line->AppendSwitchASCII(switches::kProductVersion, CefString(&settings.product_version)); } if (settings.locale.length > 0) { command_line->AppendSwitchASCII(switches::kLang, CefString(&settings.locale)); } else if (!command_line->HasSwitch(switches::kLang)) { command_line->AppendSwitchASCII(switches::kLang, "en-US"); } base::FilePath log_file; bool has_log_file_cmdline = false; if (settings.log_file.length > 0) log_file = base::FilePath(CefString(&settings.log_file)); if (log_file.empty() && command_line->HasSwitch(switches::kLogFile)) { log_file = command_line->GetSwitchValuePath(switches::kLogFile); if (!log_file.empty()) has_log_file_cmdline = true; } if (log_file.empty()) log_file = GetDefaultLogFile(); DCHECK(!log_file.empty()); if (!has_log_file_cmdline) command_line->AppendSwitchPath(switches::kLogFile, log_file); if (settings.log_severity != LOGSEVERITY_DEFAULT) { std::string log_severity; switch (settings.log_severity) { case LOGSEVERITY_VERBOSE: log_severity = switches::kLogSeverity_Verbose; break; case LOGSEVERITY_INFO: log_severity = switches::kLogSeverity_Info; break; case LOGSEVERITY_WARNING: log_severity = switches::kLogSeverity_Warning; break; case LOGSEVERITY_ERROR: log_severity = switches::kLogSeverity_Error; break; case LOGSEVERITY_FATAL: log_severity = switches::kLogSeverity_Fatal; break; case LOGSEVERITY_DISABLE: log_severity = switches::kLogSeverity_Disable; break; default: break; } if (!log_severity.empty()) command_line->AppendSwitchASCII(switches::kLogSeverity, log_severity); } if (settings.javascript_flags.length > 0) { command_line->AppendSwitchASCII(switches::kJavaScriptFlags, CefString(&settings.javascript_flags)); } if (settings.pack_loading_disabled) { command_line->AppendSwitch(switches::kDisablePackLoading); } else { if (settings.resources_dir_path.length > 0) { base::FilePath file_path = base::FilePath(CefString(&settings.resources_dir_path)); if (!file_path.empty()) { command_line->AppendSwitchPath(switches::kResourcesDirPath, file_path); } } if (settings.locales_dir_path.length > 0) { base::FilePath file_path = base::FilePath(CefString(&settings.locales_dir_path)); if (!file_path.empty()) command_line->AppendSwitchPath(switches::kLocalesDirPath, file_path); } } if (settings.remote_debugging_port >= 1024 && settings.remote_debugging_port <= 65535) { command_line->AppendSwitchASCII( switches::kRemoteDebuggingPort, base::NumberToString(settings.remote_debugging_port)); } if (settings.uncaught_exception_stack_size > 0) { command_line->AppendSwitchASCII( switches::kUncaughtExceptionStackSize, base::NumberToString(settings.uncaught_exception_stack_size)); } std::vector<std::string> disable_features; if (network::features::kOutOfBlinkCors.default_state == base::FEATURE_ENABLED_BY_DEFAULT) { // TODO: Add support for out-of-Blink CORS (see issue #2716) disable_features.push_back(network::features::kOutOfBlinkCors.name); } #if defined(OS_WIN) if (features::kCalculateNativeWinOcclusion.default_state == base::FEATURE_ENABLED_BY_DEFAULT) { // TODO: Add support for occlusion detection in combination with native // parent windows (see issue #2805). disable_features.push_back(features::kCalculateNativeWinOcclusion.name); } #endif // defined(OS_WIN) if (!disable_features.empty()) { DCHECK(!base::FeatureList::GetInstance()); std::string disable_features_str = command_line->GetSwitchValueASCII(switches::kDisableFeatures); for (auto feature_str : disable_features) { if (!disable_features_str.empty()) disable_features_str += ","; disable_features_str += feature_str; } command_line->AppendSwitchASCII(switches::kDisableFeatures, disable_features_str); } std::vector<std::string> enable_features; if (media_router::kDialMediaRouteProvider.default_state == base::FEATURE_DISABLED_BY_DEFAULT) { // Enable discovery of DIAL devices. enable_features.push_back(media_router::kDialMediaRouteProvider.name); } if (media_router::kCastMediaRouteProvider.default_state == base::FEATURE_DISABLED_BY_DEFAULT) { // Enable discovery of Cast devices. enable_features.push_back(media_router::kCastMediaRouteProvider.name); } if (!enable_features.empty()) { DCHECK(!base::FeatureList::GetInstance()); std::string enable_features_str = command_line->GetSwitchValueASCII(switches::kEnableFeatures); for (auto feature_str : enable_features) { if (!enable_features_str.empty()) enable_features_str += ","; enable_features_str += feature_str; } command_line->AppendSwitchASCII(switches::kEnableFeatures, enable_features_str); } } if (content_client_.application().get()) { // Give the application a chance to view/modify the command line. CefRefPtr<CefCommandLineImpl> commandLinePtr( new CefCommandLineImpl(command_line, false, false)); content_client_.application()->OnBeforeCommandLineProcessing( CefString(process_type), commandLinePtr.get()); commandLinePtr->Detach(nullptr); } // Initialize logging. logging::LoggingSettings log_settings; const base::FilePath& log_file = command_line->GetSwitchValuePath(switches::kLogFile); DCHECK(!log_file.empty()); log_settings.log_file_path = log_file.value().c_str(); log_settings.lock_log = logging::DONT_LOCK_LOG_FILE; log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE; logging::LogSeverity log_severity = logging::LOG_INFO; std::string log_severity_str = command_line->GetSwitchValueASCII(switches::kLogSeverity); if (!log_severity_str.empty()) { if (base::LowerCaseEqualsASCII(log_severity_str, switches::kLogSeverity_Verbose)) { log_severity = logging::LOG_VERBOSE; } else if (base::LowerCaseEqualsASCII(log_severity_str, switches::kLogSeverity_Warning)) { log_severity = logging::LOG_WARNING; } else if (base::LowerCaseEqualsASCII(log_severity_str, switches::kLogSeverity_Error)) { log_severity = logging::LOG_ERROR; } else if (base::LowerCaseEqualsASCII(log_severity_str, switches::kLogSeverity_Fatal)) { log_severity = logging::LOG_FATAL; } else if (base::LowerCaseEqualsASCII(log_severity_str, switches::kLogSeverity_Disable)) { log_severity = LOGSEVERITY_DISABLE; } } if (log_severity == LOGSEVERITY_DISABLE) { log_settings.logging_dest = logging::LOG_NONE; // By default, ERROR and FATAL messages will always be output to stderr due // to the kAlwaysPrintErrorLevel value in base/logging.cc. We change the log // level here so that only FATAL messages are output. logging::SetMinLogLevel(logging::LOG_FATAL); } else { log_settings.logging_dest = logging::LOG_TO_ALL; logging::SetMinLogLevel(log_severity); } logging::InitLogging(log_settings); ContentSettingsPattern::SetNonWildcardDomainNonPortSchemes( kNonWildcardDomainNonPortSchemes, kNonWildcardDomainNonPortSchemesSize); content::SetContentClient(&content_client_); #if defined(OS_MACOSX) OverrideFrameworkBundlePath(); OverrideOuterBundlePath(); OverrideBaseBundleID(); #endif return false; } void CefMainDelegate::PreSandboxStartup() { const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); const std::string& process_type = command_line->GetSwitchValueASCII(switches::kProcessType); if (process_type.empty()) { // Only override these paths when executing the main process. #if defined(OS_MACOSX) OverrideChildProcessPath(); #endif OverridePepperFlashSystemPluginPath(); base::FilePath dir_default_download; base::FilePath dir_default_download_safe; if (GetDefaultDownloadDirectory(&dir_default_download)) { base::PathService::Override(chrome::DIR_DEFAULT_DOWNLOADS, dir_default_download); } if (GetDefaultDownloadSafeDirectory(&dir_default_download_safe)) { base::PathService::Override(chrome::DIR_DEFAULT_DOWNLOADS_SAFE, dir_default_download_safe); } const base::FilePath& user_data_path = GetUserDataPath(); base::PathService::Override(chrome::DIR_USER_DATA, user_data_path); // Path used for crash dumps. base::PathService::Override(chrome::DIR_CRASH_DUMPS, user_data_path); // Path used for spell checking dictionary files. base::PathService::OverrideAndCreateIfNeeded( chrome::DIR_APP_DICTIONARIES, user_data_path.AppendASCII("Dictionaries"), false, // May not be an absolute path. true); // Create if necessary. } if (command_line->HasSwitch(switches::kDisablePackLoading)) content_client_.set_pack_loading_disabled(true); // Initialize crash reporting state for this process/module. // chrome::DIR_CRASH_DUMPS must be configured before calling this function. crash_reporting::PreSandboxStartup(*command_line, process_type); InitializeResourceBundle(); MaybeInitializeGDI(); } void CefMainDelegate::SandboxInitialized(const std::string& process_type) { CefContentClient::SetPDFEntryFunctions(chrome_pdf::PPP_GetInterface, chrome_pdf::PPP_InitializeModule, chrome_pdf::PPP_ShutdownModule); } int CefMainDelegate::RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) { if (process_type.empty()) { const CefSettings& settings = CefContext::Get()->settings(); if (!settings.multi_threaded_message_loop) { // Use our own browser process runner. browser_runner_ = content::BrowserMainRunner::Create(); // Initialize browser process state. Results in a call to // CefBrowserMain::PreMainMessageLoopStart() which creates the UI message // loop. int exit_code = browser_runner_->Initialize(main_function_params); if (exit_code >= 0) return exit_code; } else { // Running on the separate UI thread. DCHECK(ui_thread_); ui_thread_->InitializeBrowserRunner(main_function_params); } return 0; } return -1; } bool CefMainDelegate::CreateUIThread(base::OnceClosure setup_callback) { DCHECK(!ui_thread_); ui_thread_.reset(new CefUIThread(std::move(setup_callback))); ui_thread_->Start(); ui_thread_->WaitUntilThreadStarted(); InitMessagePumpFactoryForUI(); return true; } void CefMainDelegate::ProcessExiting(const std::string& process_type) { ui::ResourceBundle::CleanupSharedInstance(); } #if defined(OS_LINUX) void CefMainDelegate::ZygoteForked() { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); const std::string& process_type = command_line->GetSwitchValueASCII(switches::kProcessType); // Initialize crash reporting state for the newly forked process. crash_reporting::ZygoteForked(command_line, process_type); } #endif content::ContentBrowserClient* CefMainDelegate::CreateContentBrowserClient() { browser_client_.reset(new CefContentBrowserClient); return browser_client_.get(); } content::ContentRendererClient* CefMainDelegate::CreateContentRendererClient() { renderer_client_.reset(new CefContentRendererClient); return renderer_client_.get(); } content::ContentUtilityClient* CefMainDelegate::CreateContentUtilityClient() { utility_client_.reset(new ChromeContentUtilityClient); return utility_client_.get(); } void CefMainDelegate::ShutdownBrowser() { if (browser_runner_.get()) { browser_runner_->Shutdown(); browser_runner_.reset(nullptr); } if (ui_thread_.get()) { // Blocks until the thread has stopped. ui_thread_->Stop(); ui_thread_.reset(); } } void CefMainDelegate::InitializeResourceBundle() { const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath cef_pak_file, cef_100_percent_pak_file, cef_200_percent_pak_file, cef_extensions_pak_file, devtools_pak_file, locales_dir; base::FilePath resources_dir; if (command_line->HasSwitch(switches::kResourcesDirPath)) { resources_dir = command_line->GetSwitchValuePath(switches::kResourcesDirPath); } if (resources_dir.empty()) resources_dir = GetResourcesFilePath(); if (!resources_dir.empty()) base::PathService::Override(chrome::DIR_RESOURCES, resources_dir); if (!content_client_.pack_loading_disabled()) { if (!resources_dir.empty()) { CHECK(resources_dir.IsAbsolute()); cef_pak_file = resources_dir.Append(FILE_PATH_LITERAL("cef.pak")); cef_100_percent_pak_file = resources_dir.Append(FILE_PATH_LITERAL("cef_100_percent.pak")); cef_200_percent_pak_file = resources_dir.Append(FILE_PATH_LITERAL("cef_200_percent.pak")); cef_extensions_pak_file = resources_dir.Append(FILE_PATH_LITERAL("cef_extensions.pak")); devtools_pak_file = resources_dir.Append(FILE_PATH_LITERAL("devtools_resources.pak")); } if (command_line->HasSwitch(switches::kLocalesDirPath)) locales_dir = command_line->GetSwitchValuePath(switches::kLocalesDirPath); if (!locales_dir.empty()) base::PathService::Override(ui::DIR_LOCALES, locales_dir); } std::string locale = command_line->GetSwitchValueASCII(switches::kLang); DCHECK(!locale.empty()); const std::string loaded_locale = ui::ResourceBundle::InitSharedInstanceWithLocale( locale, content_client_.GetCefResourceBundleDelegate(), ui::ResourceBundle::LOAD_COMMON_RESOURCES); if (!loaded_locale.empty() && g_browser_process) g_browser_process->SetApplicationLocale(loaded_locale); ui::ResourceBundle& resource_bundle = ui::ResourceBundle::GetSharedInstance(); if (!content_client_.pack_loading_disabled()) { if (loaded_locale.empty()) LOG(ERROR) << "Could not load locale pak for " << locale; content_client_.set_allow_pack_file_load(true); if (base::PathExists(cef_pak_file)) { resource_bundle.AddDataPackFromPath(cef_pak_file, ui::SCALE_FACTOR_NONE); } else { LOG(ERROR) << "Could not load cef.pak"; } // On OS X and Linux/Aura always load the 1x data pack first as the 2x data // pack contains both 1x and 2x images. const bool load_100_percent = #if defined(OS_WIN) IsScaleFactorSupported(ui::SCALE_FACTOR_100P); #else true; #endif if (load_100_percent) { if (base::PathExists(cef_100_percent_pak_file)) { resource_bundle.AddDataPackFromPath(cef_100_percent_pak_file, ui::SCALE_FACTOR_100P); } else { LOG(ERROR) << "Could not load cef_100_percent.pak"; } } if (IsScaleFactorSupported(ui::SCALE_FACTOR_200P)) { if (base::PathExists(cef_200_percent_pak_file)) { resource_bundle.AddDataPackFromPath(cef_200_percent_pak_file, ui::SCALE_FACTOR_200P); } else { LOG(ERROR) << "Could not load cef_200_percent.pak"; } } if (extensions::ExtensionsEnabled() || !command_line->HasSwitch(switches::kDisablePlugins)) { if (base::PathExists(cef_extensions_pak_file)) { resource_bundle.AddDataPackFromPath(cef_extensions_pak_file, ui::SCALE_FACTOR_NONE); } else { LOG(ERROR) << "Could not load cef_extensions.pak"; } } if (base::PathExists(devtools_pak_file)) { resource_bundle.AddDataPackFromPath(devtools_pak_file, ui::SCALE_FACTOR_NONE); } content_client_.set_allow_pack_file_load(false); } }
5e269eb18198ed36074784ca7dc0f6fc1d75f710
c800b353f17af40ff59917e7d791f2bc66b94a90
/ref/org.cpp
42b0959aa2b9f7a2b3feb4f48ad00360b47175e0
[ "MIT" ]
permissive
djsharman/TVEmulator
d33d0917f82f97b6c0b26536fc64de21982dd048
59938cc32bda5e097f5e25064e72cb8a4e4f755d
refs/heads/master
2020-07-04T05:11:15.968219
2019-08-23T00:55:43
2019-08-23T00:55:43
202,167,475
0
0
null
null
null
null
UTF-8
C++
false
false
961
cpp
startTime = millis(); for(;;) { elapsed = millis() - startTime; if(elapsed >= fadeTime) elapsed = fadeTime; if(fadeTime) { r = map(elapsed, 0, fadeTime, pr, nr); // 16-bit interp g = map(elapsed, 0, fadeTime, pg, ng); b = map(elapsed, 0, fadeTime, pb, nb); } else { // Avoid divide-by-zero in map() r = nr; g = ng; b = nb; } for(i=0; i<NUM_LEDS; i++) { r8 = r >> 8; // Quantize to 8-bit g8 = g >> 8; b8 = b >> 8; frac = (i << 8) / NUM_LEDS; // LED index scaled to 0-255 if((r8 < 255) && ((r & 0xFF) >= frac)) r8++; // Boost some fraction if((g8 < 255) && ((g & 0xFF) >= frac)) g8++; // of LEDs to handle if((b8 < 255) && ((b & 0xFF) >= frac)) b8++; // interp > 8bit strip.setPixelColor(i, r8, g8, b8); } strip.show(); if(elapsed >= fadeTime) break; } delay(holdTime); pr = nr; // Prev RGB = new RGB pg = ng; pb = nb;
2c88ef95f65eecac4391f5cfa25ead59f8a14560
13bb4f73b8a4b438e1ef484991076e3072bcf117
/kattis/judging/judging.cc
9040193a8684332682cd0c7f3765372508eb28fa
[]
no_license
viktorsieger/competitive-programming-solutions
0e921dc6671c0b61fe45fd3a63df5b5fd834fb90
5cbc54151253e6d30af1f8566a14ad0205c5ebff
refs/heads/master
2023-05-13T05:04:46.360932
2021-06-05T06:39:09
2021-06-05T06:39:09
264,195,507
0
0
null
null
null
null
UTF-8
C++
false
false
981
cc
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, i, maxSameResults = 0; string result; unordered_map<string, pair<int, int>> results; unordered_map<string, pair<int, int>>::iterator search; cin >> n; for(i = 0; i < n; ++i) { cin >> result; if((search = results.find(result)) != results.end()) { search->second.first++; } else { results.insert({result, {1, 0}}); } } for(i = 0; i < n; ++i) { cin >> result; if((search = results.find(result)) != results.end()) { search->second.second++; } } for(auto result : results) { maxSameResults += result.second.first < result.second.second ? result.second.first : result.second.second; } cout << maxSameResults << '\n'; return 0; }
796de053a8f3109d7bc3b516a9723f480fb1f034
5b11e17630f1ef1672d4f6c2297f89dbc4d32318
/QtHiRedis_Test/mainwidget.cpp
67741d3ad271430cea0924fab293ac5553cd51e4
[ "Apache-2.0" ]
permissive
xuchuanxin/QtHiRedis
3f1faf378916c82c8a24e51293a8e96002b0f578
e057fb768158c9e43ffad7c4a6169d60246f35cf
refs/heads/main
2023-05-28T10:42:16.388842
2021-04-24T14:52:37
2021-04-24T14:52:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,019
cpp
#include "mainwidget.h" #include "ui_mainwidget.h" //回调函数 void getCallback(redisAsyncContext *ctx, void *r, void *privdata) { qDebug() << "getCallback called"; redisReply *reply = static_cast<redisReply*>(r); MainWidget* mw = static_cast<MainWidget *>(privdata); //与界面进行数据交互 mw->appendMsg_slot(reply); if(reply == nullptr || mw == nullptr){ qDebug() << "The reply || mw is nullptr"; return; } //打印遍历到的所有键名 for(int i = 0; i < reply->elements; i++){ qDebug() << "key: " << reply->element[i]->str; } } MainWidget::MainWidget(QWidget *parent) : QWidget(parent) , ui(new Ui::MainWidget) { ui->setupUi(this); setWindowTitle("Qt连接Redis数据库Demo"); setFixedSize(570, 454); ui->textEdit->setReadOnly(true); ui->textEdit->setTextColor(Qt::red); ui->textEdit->setFontFamily("Consolas"); ui->textEdit->setFontPointSize(14); ui->addressLiEdit->setText("localhost"); ui->portLiEdit->setText("6379"); } MainWidget::~MainWidget() { delete ui; m_adapter.disconnect(); redisAsyncFree(m_ctx); } void MainWidget::on_connRedisBtn_clicked() { //初始化hiredis上下文 m_ctx = redisAsyncConnect(ui->addressLiEdit->text().toLatin1().data(), ui->portLiEdit->text().toInt()); if(m_ctx->err){ ui->textEdit->append("注意:Redis数据库连接失败!!!"); } else{ ui->textEdit->append("Redis数据库连接成功-_-"); } m_adapter.setContext(m_ctx); redisAsyncCommand(m_ctx, NULL, NULL, "SET Author %s", "键名"); redisAsyncCommand(m_ctx, getCallback, this, "KEYS *"); } void MainWidget::appendMsg_slot(redisReply *reply) { ui->textEdit->append("-----------打印数据库键名-----------"); for(int i = 0; i < reply->elements; i++){ ui->textEdit->append(reply->element[i]->str); } }
2d27fb946257a269fc1dbc604fd6e43c8403d144
434f95ee3d2131174d595761dd104e7832256878
/temClock/Program.cpp
cf355d32e201a4b7965d21158ec2ffb44dca52b7
[]
no_license
ohio813/win32playground
6c1fe12aae176424f868d99b3ad99a6865b17278
aff30689c7f88e54caf55b72e644630df021cfc9
refs/heads/master
2021-01-18T22:18:01.494113
2017-02-10T03:18:28
2017-02-10T03:18:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,420
cpp
#include <stdio.h> #include <limits.h> #include <Windows.h> #include <tchar.h> #include <WindowsX.h> #include "MaiTimer.h" #include "DwmFrame.h" #include "MyWinAPI/Uxtheme.h" #include "MyWinAPI/Create32bitBmp.h" #include "resource.h" typedef int i32_t; #define I32_MAX INT_MAX #define I32_MIN INT_MIN #define CLASS_NAME _T("MaiSoft.temClock") #define WND_TITLE _T("temClock") #define WND_STYLE (WS_OVERLAPPEDWINDOW) #define WIDTH_OF(rc) ((rc).right - (rc).left) #define HEIGHT_OF(rc) ((rc).bottom - (rc).top) #define INI_FILENAME _T("temClock.ini") #define FORECOLOR RGB( 0, 0, 0) #define STR_SIZE (1024) int dpi_y; HINSTANCE hInst; HWND hWnd; HFONT hFont, hFontSmall; LOGFONT lfFont, lfFontSmall; TCHAR *ontimeout_exec, *ontimeout_sound, *ini_filepath; // never NULL bool dwm_extend_frame; volatile bool timer_mode, stopw_mode; volatile i32_t timer_initial; // initial ms, before timer start volatile UINT timer_id; // from SetTimer() volatile i32_t stopw_lap1, stopw_lap2, stopw_lap3; MaiTimer timer, stopw; DwmFrame dwmf; volatile COLORREF bgcolor; struct OMO_STATE { volatile BYTE r, g, b; volatile bool r_inc, g_inc, b_inc; } omo = { 80, 200, 200, false, false, false }; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); VOID CALLBACK UpdateUiProc(HWND, UINT, UINT, DWORD); VOID CALLBACK AdvanceProc(HWND, UINT, UINT, DWORD); VOID CALLBACK OnTimerTimeout(HWND, UINT, UINT, DWORD); void OnPaint(HWND); void OnKey(HWND, UINT, BOOL, int, UINT); void OnRButtonUp(HWND, int, int, UINT); UINT OnNcHitTest(HWND hwnd, int x, int y); void stopw_StartPause(); void stopw_Reset(); void stopw_Lap(); void timer_StartPause(); void timer_Reset(); void timer_SetTimeout(); void CenterParent(HWND, HWND); void MsToMulti(i32_t, i32_t*, i32_t*, i32_t*, i32_t*); void PrintElapsedTime(TCHAR*, i32_t, bool show_ms = true); bool TryParseTextOf(HWND, int ctlId, i32_t*); bool TryAdd(i32_t, i32_t*); bool TryMultiply(i32_t, i32_t*); void ShowSettingsDlg(); void LoadSaveIni(HWND, bool); void MyDrawText(HDC, LPTSTR, LPRECT, UINT); // Timespan dialog ... BOOL CALLBACK TimespanDlgProc(HWND, UINT, WPARAM, LPARAM); BOOL dlgTimespan_OnCommand(HWND, int, HWND, UINT); BOOL dlgTimespan_OnInitDialog(HWND, HWND, LPARAM); void dlgTimespan_OnBtnOK(HWND hDlg); // Settings dialog ... LOGFONT dlgSettings_lfFont, dlgSettings_lfFontSmall; HFONT dlgSettings_hFontWebdings; BOOL CALLBACK SettingsDlgProc(HWND, UINT, WPARAM, LPARAM); BOOL dlgSettings_OnCommand(HWND, int, HWND, UINT); BOOL dlgSettings_OnInitDialog(HWND, HWND, LPARAM); void dlgSettings_UpdateCtrl(HWND); void dlgSettings_OnCheckBoxToggled(HWND); void dlgSettings_OnBtnOK(HWND); void dlgSettings_OnBtnSaveINI(HWND); void dlgSettings_OnBtnLoadINI(HWND); void dlgSettings_OnBtnSetFont(HWND); void dlgSettings_OnBtnSetMiniFont(HWND); void dlgSettings_OnBtnBrowseExe(HWND); void dlgSettings_OnBtnBrowseSound(HWND); void dlgSettings_OnBtnTestSound(HWND); int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR lpCmdLine, int nCmdShow) { bgcolor = RGB(omo.r, omo.g, omo.b); { HDC hdc = GetDC(NULL); dpi_y = GetDeviceCaps(hdc, LOGPIXELSY); ReleaseDC(NULL, hdc); }{ _tcscpy(lfFont.lfFaceName, _T("Arial")); lfFont.lfHeight = -MulDiv(24, dpi_y, 72); hFont = CreateFontIndirect(&lfFont); _tcscpy(lfFontSmall.lfFaceName, _T("Arial")); lfFontSmall.lfHeight = -MulDiv(14, dpi_y, 72); hFontSmall = CreateFontIndirect(&lfFontSmall); dlgSettings_hFontWebdings = CreateFont( -MulDiv(11, dpi_y, 72),0,0,0,0,0,0,0, SYMBOL_CHARSET,0,0,0,0,_T("Webdings")); }{ ontimeout_exec = new TCHAR[MAX_PATH]; *ontimeout_exec = '\0'; ontimeout_sound = new TCHAR[MAX_PATH]; *ontimeout_sound = '\0'; ini_filepath = new TCHAR[MAX_PATH]; TCHAR exepath[MAX_PATH], drive[MAX_PATH], dir[MAX_PATH]; GetModuleFileName(GetModuleHandle(NULL), exepath, MAX_PATH); _tsplitpath(exepath, drive, dir, NULL, NULL); _stprintf(ini_filepath, _T("%s%s%s"), drive, dir, INI_FILENAME); } hInst = hInstance; WNDCLASSEX wcex; ZeroMemory(&wcex, sizeof(wcex)); wcex.cbSize = sizeof(wcex); wcex.hbrBackground = (HBRUSH)(COLOR_BTNSHADOW); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpfnWndProc = WndProc; wcex.lpszClassName = CLASS_NAME; wcex.style = CS_HREDRAW | CS_VREDRAW; if (!RegisterClassEx(&wcex)) { return 1; } hWnd = CreateWindowEx(0, CLASS_NAME, WND_TITLE, WND_STYLE, CW_USEDEFAULT, 0, 600, 400, NULL, NULL, NULL, NULL); if (!hWnd) { return 2; } dwmf.SetHwnd(hWnd); ShowWindow(hWnd, nCmdShow); { SetTimer(NULL, 0, 0, UpdateUiProc); SetTimer(NULL, 0, 20, AdvanceProc); } MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Cleanup code omitted, as the program is exiting already return 0; } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM w, LPARAM l) { switch (msg) { case WM_ERASEBKGND: break; case WM_PAINT: HANDLE_WM_PAINT(hWnd, w, l, OnPaint); break; case WM_KEYDOWN: HANDLE_WM_KEYDOWN(hWnd, w, l, OnKey); break; //case WM_LBUTTONUP: HANDLE_WM_LBUTTONUP(hWnd, w, l, OnLButtonUp); break; case WM_NCRBUTTONUP: case WM_RBUTTONUP: HANDLE_WM_RBUTTONUP(hWnd, w, l, OnRButtonUp); break; case WM_DWMCOMPOSITIONCHANGED: dwmf.OnDwmCompositionChanged(); break; case WM_NCHITTEST: return HANDLE_WM_NCHITTEST(hWnd, w, l, OnNcHitTest); case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, w, l); } return 0; } VOID CALLBACK AdvanceProc(HWND, UINT, UINT, DWORD) { if (omo.r_inc) { omo.r += 2; } else { omo.r -= 2; } if (omo.g_inc) { ++omo.g; } else { --omo.g; } //if (omo.b_inc) { ++omo.b; } else { --omo.b; } if (omo.r >= 250) { omo.r_inc = false; } if (omo.r <= 100) { omo.r_inc = true; } if (omo.g >= 250) { omo.g_inc = false; } if (omo.g <= 100) { omo.g_inc = true; } //if (omo.b >= 250) { omo.b_inc = false; } //if (omo.b <= 100) { omo.b_inc = true; } bgcolor = RGB(omo.r, omo.g, omo.b); } VOID CALLBACK UpdateUiProc(HWND, UINT, UINT, DWORD) { InvalidateRect(hWnd, NULL, TRUE); } VOID CALLBACK OnTimerTimeout(HWND, UINT, UINT id, DWORD) { timer_Reset(); BOOL want_mute = FALSE; if (*ontimeout_sound) { want_mute = PlaySound(ontimeout_sound, NULL, SND_ASYNC | SND_FILENAME | SND_NODEFAULT); } if (*ontimeout_exec) { TCHAR *appname = NULL, *cmdline = NULL; // if exists, treat as appname, else treat as cmdline WIN32_FIND_DATA fdata; ZeroMemory(&fdata, sizeof(fdata)); HANDLE h = FindFirstFile(ontimeout_exec, &fdata); if (h != INVALID_HANDLE_VALUE) { appname = ontimeout_exec; } else { cmdline = ontimeout_exec; } // run ... STARTUPINFO sinfo; ZeroMemory(&sinfo, sizeof(sinfo)); sinfo.cb = sizeof(sinfo); sinfo.wShowWindow = SW_SHOWNORMAL; PROCESS_INFORMATION pinfo; ZeroMemory(&pinfo, sizeof(pinfo)); CreateProcess(appname, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo); } if (!want_mute) { MessageBox(hWnd, _T("Timeout!"), _T("Timer"), MB_OK | MB_ICONINFORMATION); } } void OnPaint(HWND hWnd) { RECT rc; GetClientRect(hWnd, &rc); PAINTSTRUCT ps; HDC real_hdc = BeginPaint(hWnd, &ps); HDC hdc = CreateCompatibleDC(real_hdc); HBITMAP hbm = Create32bitBmp(hdc, WIDTH_OF(rc), HEIGHT_OF(rc), NULL); HGDIOBJ old_hbm = SelectObject(hdc, hbm); HGDIOBJ old_hfo = SelectObject(hdc, hFont); // Clear HBRUSH hbrBg = CreateSolidBrush( dwmf.IsExtended() ? RGB(0,0,0) : bgcolor); FillRect(hdc, &rc, hbrBg); DeleteObject(hbrBg); // Draw text TCHAR str[STR_SIZE] = {0}; SetTextColor(hdc, FORECOLOR); SetBkMode(hdc, TRANSPARENT); if (timer_mode) { i32_t elapsed = timer.GetElapsedMs_i32(); _tcscpy(str, _T("~ Timer ~\n")); PrintElapsedTime(&str[_tcslen(str)], elapsed > timer_initial ? 0 : timer_initial - elapsed); } else if (stopw_mode) { _tcscpy(str, _T("~ Stopwatch ~\n")); PrintElapsedTime(&str[_tcslen(str)], stopw.GetElapsedMs_i32()); if (stopw_lap3) { _tcscat(str, _T("\nLap 3: ")); PrintElapsedTime(&str[_tcslen(str)], stopw_lap3); } if (stopw_lap2) { _tcscat(str, _T("\nLap 2: ")); PrintElapsedTime(&str[_tcslen(str)], stopw_lap2); } if (stopw_lap1) { _tcscat(str, _T("\nLap 1: ")); PrintElapsedTime(&str[_tcslen(str)], stopw_lap1); } } else /* clock_mode */ { SYSTEMTIME time; GetLocalTime(&time); _stprintf(str, _T("%.2u:%.2u:%.2u\n") _T("%u/%u/%u "), time.wHour, time.wMinute, time.wSecond, time.wDay, time.wMonth, time.wYear); switch (time.wDayOfWeek) { case 0: _tcscat(str, _T("Sun")); break; case 1: _tcscat(str, _T("Mon")); break; case 2: _tcscat(str, _T("Tue")); break; case 3: _tcscat(str, _T("Wed")); break; case 4: _tcscat(str, _T("Thu")); break; case 5: _tcscat(str, _T("Fri")); break; case 6: _tcscat(str, _T("Sat")); break; } } // Find out the Width and Height needed to store the text // When passing all-zero RECT for DT_CALCRECT, x and y will remain zero, // while .right and .bottom will be Width and Height. // Thus, we need to += them after calculating x and y. RECT rcText = {0}; MyDrawText(hdc, str, &rcText, DT_CALCRECT); rcText.right += rcText.left = (WIDTH_OF(rc) - WIDTH_OF(rcText)) / 2; rcText.bottom += rcText.top = (HEIGHT_OF(rc) - HEIGHT_OF(rcText)) / 2; MyDrawText(hdc, str, &rcText, DT_CENTER); // If timer/stopwatch is running on background, // show their status on 'Clock' screen. if (!timer_mode && !stopw_mode) { *str = '\0'; if (stopw.IsRunning()) { _tcscat(str, _T("Stopwatch: ")); PrintElapsedTime(&str[_tcslen(str)], stopw.GetElapsedMs_i32(), false); } if (timer.IsRunning()) { if (*str) { _tcscat(str, _T("\n")); } _tcscat(str, _T("Timer: ")); PrintElapsedTime(&str[_tcslen(str)], timer_initial - timer.GetElapsedMs_i32(), false); } RECT rcTest, rcMini = {3, 3}; SelectObject(hdc, hFontSmall); MyDrawText(hdc, str, &rcMini, DT_CALCRECT); if (!IntersectRect(&rcTest, &rcMini, &rcText)) { MyDrawText(hdc, str, &rcMini, 0); } } // Done BitBlt(real_hdc, 0, 0, WIDTH_OF(rc), HEIGHT_OF(rc), hdc, 0, 0, SRCCOPY); SelectObject(hdc, old_hbm); SelectObject(hdc, old_hfo); DeleteObject(hbm); DeleteDC(hdc); EndPaint(hWnd, &ps); } void OnKey(HWND hwnd, UINT vk, BOOL fDown, int cRepeat, UINT flags) { if (!fDown) { return; } if (vk == VK_ESCAPE) { ShowWindow(hWnd, SW_MINIMIZE); return; } if (vk == VK_TAB) { // Toggle screens if (HIBYTE(GetKeyState(VK_SHIFT))) { // holding SHIFT if (timer_mode) { stopw_mode = true; timer_mode = false; } else if (stopw_mode) { stopw_mode = timer_mode = false; } else { stopw_mode = false; timer_mode = true; } } else { if (stopw_mode) { stopw_mode = false; timer_mode = true; } else if (timer_mode) { stopw_mode = timer_mode = false; } else { stopw_mode = true; timer_mode = false; } } return; } if (vk == VK_F12) { ShowSettingsDlg(); return; } if (stopw_mode) { if (vk == VK_RETURN) { MessageBox(hWnd, _T("SPACE to start/pause, R to reset, L to lap.\n") _T("(Maximum 3 laps)\n\n") _T("Press BACK to return to Clock.\n") _T("Stopwatch will run in background.\n"), _T("Stopwatch"), MB_OK | MB_ICONINFORMATION); } else if (vk == VK_SPACE) { stopw_StartPause(); } else if (vk == 'R') { stopw.Reset(); } else if (vk == 'L') { stopw_Lap(); } else if (vk == VK_BACK) { stopw_mode = false; } } else if (timer_mode) { if (vk == VK_RETURN) { MessageBox(hWnd, _T("SPACE to start/pause, R to reset, Q to set timeout.\n\n") _T("Press BACK to return to Clock.\n") _T("Timer will run in background.\n"), _T("Timer"), MB_OK | MB_ICONINFORMATION); } else if (vk == VK_SPACE) { timer_StartPause(); } else if (vk == 'Q') { timer_SetTimeout(); } else if (vk == 'R') { timer_Reset(); } else if (vk == VK_BACK) { timer_mode = false; } } else /* clock mode */ { if (vk == VK_RETURN) { MessageBox(hWnd, _T("Press S for Stopwatch.\n") _T("Press T for Timer.\n") _T("Press TAB to toggle.\n") _T("Press F12 for Options.\n"), _T("Clock"), MB_OK | MB_ICONINFORMATION); } else if (vk == 'S') { stopw_mode = true; } else if (vk == 'T') { timer_mode = true; } } } void OnRButtonUp(HWND hWnd, int x, int y, UINT flags) { POINT pt; GetCursorPos(&pt); HMENU hMenu = CreatePopupMenu(); if (stopw_mode) { AppendMenu(hMenu, MF_BYCOMMAND, 1, _T("Start/Pause")); AppendMenu(hMenu, MF_BYCOMMAND, 2, _T("Lap")); AppendMenu(hMenu, MF_BYCOMMAND, 3, _T("Reset")); AppendMenu(hMenu, MF_SEPARATOR, 0, NULL); AppendMenu(hMenu, MF_BYCOMMAND, 12, _T("Timer...")); AppendMenu(hMenu, MF_BYCOMMAND, 10, _T("Clock...")); } else if (timer_mode) { AppendMenu(hMenu, MF_BYCOMMAND, 1, _T("Start/Pause")); AppendMenu(hMenu, MF_BYCOMMAND, 2, _T("Set timeout...")); AppendMenu(hMenu, MF_BYCOMMAND, 3, _T("Reset")); AppendMenu(hMenu, MF_SEPARATOR, 0, NULL); AppendMenu(hMenu, MF_BYCOMMAND, 11, _T("Stopwatch...")); AppendMenu(hMenu, MF_BYCOMMAND, 10, _T("Clock...")); } else /* clock mode */ { AppendMenu(hMenu, MF_BYCOMMAND, 11, _T("Stopwatch...")); AppendMenu(hMenu, MF_BYCOMMAND, 12, _T("Timer...")); } AppendMenu(hMenu, MF_SEPARATOR, 0, NULL); AppendMenu(hMenu, MF_BYCOMMAND, 13, _T("Settings...")); AppendMenu(hMenu, MF_GRAYED, 0, _T("temClock v1.1 by Raymai97")); int ret = TrackPopupMenu( hMenu, TPM_RIGHTBUTTON | TPM_RETURNCMD, pt.x, pt.y, 0, hWnd, NULL); DestroyMenu(hMenu); if (ret == 10) { stopw_mode = timer_mode = false; } else if (ret == 11) { stopw_mode = true; timer_mode = false; } else if (ret == 12) { stopw_mode = false; timer_mode = true; } else if (ret == 13) { ShowSettingsDlg(); } else if (stopw_mode) { if (ret == 1) { stopw_StartPause(); } else if (ret == 2) { stopw_Lap(); } else if (ret == 3) { stopw_Reset(); } } else if (timer_mode) { if (ret == 1) { timer_StartPause(); } else if (ret == 2) { timer_SetTimeout(); } else if (ret == 3) { timer_Reset(); } } } UINT OnNcHitTest(HWND hwnd, int x, int y) { POINT pt = {x, y}; ScreenToClient(hwnd, &pt); RECT rc = {0}; GetClientRect(hwnd, &rc); if (PtInRect(&rc, pt)) { return HTCAPTION; } return FORWARD_WM_NCHITTEST(hwnd, x, y, DefWindowProc); } void stopw_StartPause() { if (stopw.IsRunning()) { if (stopw.IsPaused()) { stopw.Resume(); } else { stopw.Pause(); } } else { stopw.Start(); } } void stopw_Reset() { stopw.Reset(); stopw_lap1 = stopw_lap2 = stopw_lap3 = 0; } void stopw_Lap() { if (!stopw_lap1) { stopw_lap1 = stopw.GetElapsedMs_i32(); } else if (!stopw_lap2) { stopw_lap2 = stopw.GetElapsedMs_i32(); } else if (!stopw_lap3) { stopw_lap3 = stopw.GetElapsedMs_i32(); } else { MessageBox(hWnd, _T("Maximum 3 laps only."), NULL, MB_OK | MB_ICONERROR); } } void timer_StartPause() { if (timer.IsRunning()) { if (timer.IsPaused()) { timer_id = SetTimer(NULL, NULL, timer_initial - timer.GetElapsedMs_i32(), OnTimerTimeout); timer.Resume(); } else { KillTimer(NULL, timer_id); timer.Pause(); } } else if (timer_initial) { timer_id = SetTimer(NULL, NULL, timer_initial, OnTimerTimeout); timer.Start(); } else { MessageBox(hWnd, _T("Please set timeout first."), _T("Timer"), MB_OK | MB_ICONINFORMATION); } } void timer_Reset() { timer.Reset(); KillTimer(NULL, timer_id); } void timer_SetTimeout() { if (timer.IsRunning()) { if (IDYES == MessageBox(hWnd, _T("You're trying to set timeout.\n") _T("If you continue, the current timer will be reset.\n") _T("Are you sure?"), _T("Sure?"), MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION)) { timer_Reset(); } else { return; } } DialogBox(hInst, MAKEINTRESOURCE(DLG_TIMESPAN), hWnd, TimespanDlgProc); } void CenterParent(HWND hChild, HWND hParent) { RECT rc, rc2; GetWindowRect(hParent, &rc); GetWindowRect(hChild, &rc2); SetWindowPos(hChild, HWND_TOP, rc.left + (WIDTH_OF(rc) - WIDTH_OF(rc2)) / 2, rc.top + (HEIGHT_OF(rc) - HEIGHT_OF(rc2)) / 2, 0, 0, SWP_NOSIZE); } void MsToMulti(i32_t total_ms, i32_t *h, i32_t *m, i32_t *s, i32_t *ms) { *ms = total_ms; *h = *ms / 60 / 60 / 1000; *ms -= (*h * 60 * 60 * 1000); *m = *ms / 60 / 1000; *ms -= (*m * 60 * 1000); *s = *ms / 1000; *ms -= (*s * 1000); } void PrintElapsedTime(TCHAR *str, i32_t total_ms, bool show_ms) { if (total_ms < 0) { _stprintf(str, _T("Overflow...")); return; } i32_t h = 0, m = 0, s = 0, ms = 0; MsToMulti(total_ms, &h, &m, &s, &ms); if (show_ms) { _stprintf(str, _T("%.2i:%.2i:%.2i.%.3i"), h, m, s, ms); } else { _stprintf(str, _T("%.2i:%.2i:%.2i"), h, m, s); } } // Behaves like .NET TryParse, but for user convenience, // it will assume 'zero-length input' as '0'. bool TryParseTextOf(HWND hDlg, int ctlId, i32_t *pDest) { HWND h = GetDlgItem(hDlg, ctlId); if (GetWindowTextLength(h) == 0) { *pDest = 0; return true; } TCHAR buf[20] = {0}, *pEnd = NULL; GetWindowText(h, buf, 20); i32_t ret = _tcstol(buf, &pEnd, 10); if (pEnd && *pEnd) { return false; } if (ret >= I32_MAX) { return false; } *pDest = ret; return true; } bool TryAdd(i32_t n, i32_t *p) { if ((n > 0) && (*p > I32_MAX - n)) { return false; } // overflow if ((n < 0) && (*p < I32_MIN - n)) { return false; } // underflow *p += n; return true; } bool TryMultiply(i32_t n, i32_t *p) { if (*p > I32_MAX / n) { return false; } // overflow if (*p < I32_MIN / n) { return false; } // underflow // try think 8-bit signed, // what would happen if -256 * -1 if ((*p == -1) && ( n == I32_MIN)) { return false; } if (( n == -1) && (*p == I32_MIN)) { return false; } *p *= n; return true; } void ShowSettingsDlg() { // Backup and copy to make sure completely undo-able dlgSettings_lfFont = lfFont; dlgSettings_lfFontSmall = lfFontSmall; // Keep change if return TRUE if (DialogBox(hInst, MAKEINTRESOURCE(DLG_SETTINGS), hWnd, SettingsDlgProc)) { lfFont = dlgSettings_lfFont; lfFontSmall = dlgSettings_lfFontSmall; } else { // revert change hFont = CreateFontIndirect(&lfFont); hFontSmall = CreateFontIndirect(&lfFontSmall); dwmf.DoExtend(dwm_extend_frame); } } void LoadSaveIni(HWND hDlg, bool save) { BOOL ok; TCHAR szMsg[STR_SIZE] = {0}; if (save) { #ifdef _UNICODE // If INI doesn't exist, we must manually create a blank // Unicode (UTF16-LE) text file, or it will be ANSI encoding. FILE *file = _tfopen(ini_filepath, _T("w,ccs=UNICODE")); if (file) { WORD utf16_le_bom = 0xFEFF; fwrite(&utf16_le_bom, sizeof(WORD), 1, file); fclose(file); } #endif TCHAR szExec[MAX_PATH] = {0}, szSound[MAX_PATH] = {0}; if (IsDlgButtonChecked(hDlg, CHK_EXECUTE)) { GetDlgItemText(hDlg, TXT_EXECUTE, szExec, MAX_PATH); } if (IsDlgButtonChecked(hDlg, CHK_PLAY_SOUND)) { GetDlgItemText(hDlg, TXT_SOUND, szSound, MAX_PATH); } ok = WritePrivateProfileStruct( _T("TemClock"), _T("Font"), &dlgSettings_lfFont, sizeof(LOGFONT), ini_filepath) && WritePrivateProfileStruct( _T("TemClock"), _T("MiniFont"), &dlgSettings_lfFontSmall, sizeof(LOGFONT), ini_filepath) && WritePrivateProfileString( _T("TemClock"), _T("DwmExtendFrame"), IsDlgButtonChecked(hDlg, CHK_DWM_EXTEND_FRAME) ? _T("1") : _T("0"), ini_filepath) && WritePrivateProfileString( _T("OnTimeout"), _T("Execute"), szExec, ini_filepath) && WritePrivateProfileString( _T("OnTimeout"), _T("Sound"), szSound, ini_filepath); if (!ok) { _tcscpy(szMsg, _T("Failed to write INI file.")); } } else { LOGFONT lf1, lf2; HFONT hfo1, hfo2; ok = GetPrivateProfileStruct( _T("TemClock"), _T("Font"), &lf1, sizeof(LOGFONT), ini_filepath) && GetPrivateProfileStruct( _T("TemClock"), _T("MiniFont"), &lf2, sizeof(LOGFONT), ini_filepath) && (hfo1 = CreateFontIndirect(&lf1)) && (hfo2 = CreateFontIndirect(&lf2)); if (!ok) { _tcscpy(szMsg, _T("Failed to load font.")); } else { DeleteObject(hFont); DeleteObject(hFontSmall); hFont = hfo1; hFontSmall = hfo2; dlgSettings_lfFont = lf1; dlgSettings_lfFontSmall = lf2; // Error handling omitted (too tedious to do so) TCHAR buf[MAX_PATH] = {0}; GetPrivateProfileString( _T("TemClock"), _T("DwmExtendFrame"), _T(""), buf, MAX_PATH, ini_filepath); dwm_extend_frame = (_tcscmp(buf, _T("1")) == 0); GetPrivateProfileString( _T("OnTimeout"), _T("Execute"), _T(""), ontimeout_exec, MAX_PATH, ini_filepath); GetPrivateProfileString( _T("OnTimeout"), _T("Sound"), _T(""), ontimeout_sound, MAX_PATH, ini_filepath); dlgSettings_UpdateCtrl(hDlg); dlgSettings_OnCheckBoxToggled(hDlg); } } if (ok) { _stprintf(szMsg, _T("Settings have been %s %s."), save ? _T("saved to") : _T("loaded from"), INI_FILENAME); } else { DWORD err_code = GetLastError(); TCHAR *err_msg; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, err_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&err_msg, 0, NULL); _stprintf(&szMsg[_tcslen(szMsg)], _T("\n%s(Error code: %lu)"), err_msg, err_code); } MessageBox(hDlg, szMsg, ok ? (save ? _T("Saved") : _T("Loaded")) : NULL, MB_OK | ok ? MB_ICONINFORMATION : MB_ICONERROR); } void MyDrawText(HDC hdcMem, LPTSTR szText, LPRECT prc, UINT dtFlags) { if (!(dtFlags & DT_CALCRECT) && dwmf.IsExtended()) { #ifdef UNICODE LPCWSTR wszText = szText; #else WCHAR wszText[STR_SIZE]; MultiByteToWideChar(CP_UTF8, 0, szText, -1, wszText, STR_SIZE); #endif UxtDrawTextOnDwmFrameOffscreen( hdcMem, wszText, prc->left, prc->top, WIDTH_OF(*prc), HEIGHT_OF(*prc), dtFlags, 10, RGB(0,0,0)); } else { DrawText(hdcMem, szText, -1, prc, dtFlags); } } // Timespan dialog ... BOOL CALLBACK TimespanDlgProc(HWND hDlg, UINT msg, WPARAM w, LPARAM l) { switch (msg) { case WM_COMMAND: return HANDLE_WM_COMMAND(hDlg, w, l, dlgTimespan_OnCommand); case WM_INITDIALOG: return HANDLE_WM_INITDIALOG(hDlg, w, l, dlgTimespan_OnInitDialog); } return FALSE; // return FALSE let system do the default stuff. } BOOL dlgTimespan_OnInitDialog(HWND hDlg, HWND, LPARAM) { CenterParent(hDlg, hWnd); // Set default value i32_t h = 0, m = 0, s = 0, ms = 0; MsToMulti(timer_initial, &h, &m, &s, &ms); HWND h_txtH = GetDlgItem(hDlg, TXT_H); HWND h_txtM = GetDlgItem(hDlg, TXT_M); HWND h_txtS = GetDlgItem(hDlg, TXT_S); HWND h_txtMs = GetDlgItem(hDlg, TXT_MS); TCHAR buf[40] = {0}; SetWindowText(h_txtH, _ultot(h, buf, 10)); SetWindowText(h_txtM, _ultot(m, buf, 10)); SetWindowText(h_txtS, _ultot(s, buf, 10)); SetWindowText(h_txtMs, _ultot(ms, buf, 10)); // Focus and Select All SetFocus(h_txtH); SendMessage(h_txtH, EM_SETSEL, 0, -1); return FALSE; } BOOL dlgTimespan_OnCommand(HWND hDlg, int id, HWND hCtl, UINT) { switch (id) { case IDOK: dlgTimespan_OnBtnOK(hDlg); break; case IDCANCEL: EndDialog(hDlg, FALSE); break; } return TRUE; } void dlgTimespan_OnBtnOK(HWND hDlg) { i32_t h = 0, m = 0, s = 0, ms = 0; LPTSTR szErrMsg = !TryParseTextOf(hDlg, TXT_H, &h) || !TryParseTextOf(hDlg, TXT_M, &m) || !TryParseTextOf(hDlg, TXT_S, &s) || !TryParseTextOf(hDlg, TXT_MS, &ms) ? _T("Parse integer failed!") : h < 0 || m < 0 || s < 0 || ms < 0 ? _T("Please enter positive number only!") : !TryMultiply(60 * 60 * 1000, &h) || !TryMultiply(60 * 1000, &m) || !TryMultiply(1000, &s) || !TryAdd(s, &ms) || !TryAdd(m, &ms) || !TryAdd(h, &ms) ? _T("Integer overflow! Please enter smaller value.") : NULL; if (szErrMsg) { MessageBox(hDlg, szErrMsg, NULL, MB_OK | MB_ICONERROR); return; } timer_initial = ms; EndDialog(hDlg, TRUE); } // Settings dialog ... BOOL CALLBACK SettingsDlgProc(HWND hDlg, UINT msg, WPARAM w, LPARAM l) { switch (msg) { case WM_COMMAND: return HANDLE_WM_COMMAND(hDlg, w, l, dlgSettings_OnCommand); case WM_INITDIALOG: return HANDLE_WM_INITDIALOG(hDlg, w, l, dlgSettings_OnInitDialog); } return FALSE; // return FALSE let system do the default stuff. } BOOL dlgSettings_OnInitDialog(HWND hDlg, HWND, LPARAM) { CenterParent(hDlg, hWnd); SetWindowFont(GetDlgItem(hDlg, BTN_TEST_SOUND), dlgSettings_hFontWebdings, TRUE); dlgSettings_UpdateCtrl(hDlg); dlgSettings_OnCheckBoxToggled(hDlg); SetFocus(GetDlgItem(hDlg, IDOK)); return FALSE; } void dlgSettings_UpdateCtrl(HWND hDlg) { SetDlgItemText(hDlg, TXT_EXECUTE, ontimeout_exec); SetDlgItemText(hDlg, TXT_SOUND, ontimeout_sound); CheckDlgButton(hDlg, CHK_EXECUTE, *ontimeout_exec ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(hDlg, CHK_PLAY_SOUND, *ontimeout_sound ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(hDlg, CHK_DWM_EXTEND_FRAME, dwm_extend_frame ? BST_CHECKED : BST_UNCHECKED); } void dlgSettings_OnCheckBoxToggled(HWND hDlg) { BOOL do_exec = IsDlgButtonChecked(hDlg, CHK_EXECUTE); BOOL do_play_sound = IsDlgButtonChecked(hDlg, CHK_PLAY_SOUND); HWND h_txtExec = GetDlgItem(hDlg, TXT_EXECUTE); HWND h_btnBrowseExe = GetDlgItem(hDlg, BTN_BROWSE_EXE); HWND h_txtSound = GetDlgItem(hDlg, TXT_SOUND); HWND h_btnBrowseSound = GetDlgItem(hDlg, BTN_BROWSE_SOUND); HWND h_btnTestSound = GetDlgItem(hDlg, BTN_TEST_SOUND); EnableWindow(h_txtExec, do_exec); EnableWindow(h_btnBrowseExe, do_exec); EnableWindow(h_txtSound, do_play_sound); EnableWindow(h_btnBrowseSound, do_play_sound); EnableWindow(h_btnTestSound, do_play_sound); dwmf.DoExtend(BST_CHECKED == IsDlgButtonChecked(hDlg, CHK_DWM_EXTEND_FRAME)); } BOOL dlgSettings_OnCommand(HWND hDlg, int id, HWND hCtl, UINT notify_code) { switch (id) { case IDOK: dlgSettings_OnBtnOK(hDlg); break; case IDCANCEL: EndDialog(hDlg, FALSE); break; case BTN_SET_FONT: dlgSettings_OnBtnSetFont(hDlg); break; case BTN_SET_MINI_FONT: dlgSettings_OnBtnSetMiniFont(hDlg); break; case CHK_EXECUTE: case CHK_PLAY_SOUND: case CHK_DWM_EXTEND_FRAME: dlgSettings_OnCheckBoxToggled(hDlg); break; case BTN_BROWSE_EXE: dlgSettings_OnBtnBrowseExe(hDlg); break; case BTN_BROWSE_SOUND: dlgSettings_OnBtnBrowseSound(hDlg); break; case BTN_TEST_SOUND: dlgSettings_OnBtnTestSound(hDlg); break; case BTN_SAVE_INI: dlgSettings_OnBtnSaveINI(hDlg); break; case BTN_LOAD_INI: dlgSettings_OnBtnLoadINI(hDlg); break; } return TRUE; } void dlgSettings_OnBtnOK(HWND hDlg) { BOOL do_exec = IsDlgButtonChecked(hDlg, CHK_EXECUTE); BOOL do_play_sound = IsDlgButtonChecked(hDlg, CHK_PLAY_SOUND); if (do_exec) { GetDlgItemText(hDlg, TXT_EXECUTE, ontimeout_exec, MAX_PATH); } else { *ontimeout_exec = '\0'; } if (do_play_sound) { GetDlgItemText(hDlg, TXT_SOUND, ontimeout_sound, MAX_PATH); } else { *ontimeout_sound = '\0'; } dwm_extend_frame = BST_CHECKED == IsDlgButtonChecked(hDlg, CHK_DWM_EXTEND_FRAME); EndDialog(hDlg, TRUE); } void dlgSettings_OnBtnSaveINI(HWND hDlg) { LoadSaveIni(hDlg, true); } void dlgSettings_OnBtnLoadINI(HWND hDlg) { LoadSaveIni(hDlg, false); } // On dlgSettings_Init... // lfFont and lfFontSmall are copied to dlgSettings_lf... // If pressed cancel, CreateFont using lfFont and lfFontSmall void dlgSettings_OnBtnSetFont(HWND hDlg) { CHOOSEFONT cf; ZeroMemory(&cf, sizeof(cf)); cf.lStructSize = sizeof(cf); cf.hwndOwner = hDlg; cf.Flags = CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT | CF_FORCEFONTEXIST; cf.lpLogFont = &dlgSettings_lfFont; if (ChooseFont(&cf)) { DeleteObject(hFont); hFont = CreateFontIndirect(&dlgSettings_lfFont); } } void dlgSettings_OnBtnSetMiniFont(HWND hDlg) { CHOOSEFONT cf; ZeroMemory(&cf, sizeof(cf)); cf.lStructSize = sizeof(cf); cf.hwndOwner = hDlg; cf.Flags = CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT | CF_FORCEFONTEXIST; cf.lpLogFont = &dlgSettings_lfFontSmall; if (ChooseFont(&cf)) { DeleteObject(hFontSmall); hFontSmall = CreateFontIndirect(&dlgSettings_lfFontSmall); } } void dlgSettings_OnBtnBrowseExe(HWND hDlg) { TCHAR buf[MAX_PATH] = {0}; OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST; ofn.hwndOwner = hDlg; ofn.lpstrFile = buf; ofn.nMaxFile = MAX_PATH; ofn.lpstrFilter = _T("Executable files\0") _T("*.exe\0"); if (GetOpenFileName(&ofn)) { SetDlgItemText(hDlg, TXT_EXECUTE, buf); } } void dlgSettings_OnBtnBrowseSound(HWND hDlg) { TCHAR buf[MAX_PATH] = {0}; OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST; ofn.hwndOwner = hDlg; ofn.lpstrFile = buf; ofn.nMaxFile = MAX_PATH; ofn.lpstrFilter = _T("WAV files\0") _T("*.wav\0"); if (GetOpenFileName(&ofn)) { SetDlgItemText(hDlg, TXT_SOUND, buf); } } void dlgSettings_OnBtnTestSound(HWND hDlg) { TCHAR szSound[MAX_PATH] = {0}; GetDlgItemText(hDlg, TXT_SOUND, szSound, MAX_PATH); PlaySound(szSound, NULL, SND_ASYNC | SND_FILENAME | SND_NODEFAULT); }
11725bed29664104c43f19dfa24b9ffc51120a4e
6a4a2eb5cb08ea805733bd677ec44c62fb32ee91
/interface/iBlockDevice.h
1f5efeb0475f037b53b79ed05e42c59834d9d29a
[]
no_license
agrigomi/pre-te-o
7b737dc715b6432880aeaa030421d35c0620d0c3
ed469c549b1571e1dadf186330ee4c44d001925e
refs/heads/master
2020-05-15T13:41:51.793581
2019-04-19T18:44:28
2019-04-19T18:44:28
182,310,069
0
0
null
null
null
null
UTF-8
C++
false
false
7,045
h
#ifndef __I_BLOCK_DEVICE__ #define __I_BLOCK_DEVICE__ #include "iDriver.h" #include "iMemory.h" #include "iSyncObject.h" #define I_BDCTRL_HOST "iBDCtrlHost" #define I_VOLUME "iVolume" // volume driver #define I_CACHE "iCache" #define I_IDE_CONTROLLER "iIDEController" #define I_IDE_CHANNEL "iIDEChannel" #define I_IDE_DEVICE "iIDEDevice" #define I_AHCI_CONTROLLER "iAHCIController" #define I_AHCI_DEVICE "iAHCIDevice" #define I_FD_CONTROLLER "iFDController" #define I_FD_DEVICE "iFDDevice" #define I_RAM_DEVICE "iRamDevice" class iBDCtrlHost:public iDriverBase { // host driver of block device controllers public: DECLARE_INTERFACE(I_BDCTRL_HOST, iBDCtrlHost, iDriverBase); }; #define MAX_VOLUME_IDENT 16 #define VF_READONLY (1<<0) #define VF_NOCACHE (1<<1) #define VF_HOSTCTRL (1<<2) typedef struct { _u8 _vol_flags_; _u8 _vol_cidx_; // controller index _u8 _vol_didx_; // drive index _u8 _vol_pidx_; // partition index (0 for whole device) _u8 _vol_ident_[MAX_VOLUME_IDENT]; // volume serial number void *_vol_pvd_; // volume implementation specific }_volume_t; class iVolume: public iDriverBase, public _volume_t { public: DECLARE_INTERFACE(I_VOLUME, iVolume, iDriverBase); virtual _str_t name(void)=0; virtual _str_t serial(void)=0; }; // cache I/O commands #define CIOCTL_READ 1 #define CIOCTL_WRITE 2 #define CIOCTL_FLUSH 3 typedef void* HCACHE; typedef struct { _u64 bstart; // start block _u16 boffset; // offset in first block _u32 bcount; // block count _u32 bsize; // transfer size in bytes _u8 *buffer; // io buffer (can be NULL for cache buffer request) void *p_udata; // cache user data HCACHE handle; // cache handle void *plock; // lock info HMUTEX hlock; // mutex handle for 'plock' }_cache_io_t; typedef _u32 _cb_cache_io_t(_u32 cmd, _cache_io_t *p_cio); typedef struct { _u16 block_size; // physical block size _u16 chunk_size; // number of physical blocks in one chunk _u16 num_chunks; // number of chunks _cb_cache_io_t *p_ccb; // cache callback void *p_udata; // user specific data }__attribute__((packed)) _cache_info_t; class iCache:public iBase { public: DECLARE_INTERFACE(I_CACHE, iCache, iBase); virtual HCACHE alloc(_cache_info_t *p_ci)=0; virtual void free(HCACHE handle)=0; virtual _u32 cache_ioctl(_u32 cmd, _cache_io_t *cio)=0; }; /////////////////////////////////////////////////////////////////////////////////////////////////// typedef struct { _u16 _ide_base_primary_; // primary base port _u16 _ide_ctrl_primary_; // primary ctrl port _u16 _ide_base_secondary_; // secondary base port _u16 _ide_ctrl_secondary_; // secondary ctrl port _u16 _ide_bus_master_; // bus master IDE _u8 _ide_prog_if_; // proramming interface byte _u8 _ide_irq_; // IRQ marker (PCI interrupt line) _u32 _ide_pci_index_; // PCI device index (0xffffffff for invalid index) }_ide_ctrl_t; class iIDEController:public iDriverBase, public _ide_ctrl_t { public: DECLARE_INTERFACE(I_IDE_CONTROLLER, iIDEController, iDriverBase); virtual _u8 read(_u8 channel, _u8 reg)=0; virtual void write(_u8 channel, _u8 reg, _u8 data)=0; virtual _u32 read(_u8 channel, _u8 *p_buffer, _u32 sz)=0; virtual _u32 write(_u8 channel, _u8 *p_buffer, _u32 sz)=0; virtual bool polling(_u8 channel)=0; virtual void wait(_u8 channel)=0; virtual void irq_on(_u8 channel)=0; virtual void irq_off(_u8 channel)=0; virtual void wait_irq(_u8 channel, _u32 timeout=EVENT_TIMEOUT_INFINITE)=0; }; typedef struct { _u8 _ch_index_; // ATA_PRIMARY or ATA_SECONDARY _u16 _ch_reg_base_; // I/O Base _u16 _ch_reg_ctrl_; // Controll base _u16 _ch_reg_bmide_; // Bus Master IDE _u8 _ch_int_; // enable/disable Interrupt _u8 _ch_ata_index_; // selected device (ATA_MASTER or ATA_SLAVE) iIDEController *_ch_ctrl_; // IDE controller }_ide_channel_t; class iIDEChannel:public iBase, public _ide_channel_t { public: DECLARE_INTERFACE(I_IDE_CHANNEL, iIDEChannel, iBase); virtual bool init(void)=0; virtual HMUTEX lock(HMUTEX hlock=0); virtual void unlock(HMUTEX hlock); virtual _u32 read_sector(_u8 ata_idx, _u64 lba, _u8 *p_buffer, _u16 count, HMUTEX hlock=0)=0; virtual _u32 write_sector(_u8 ata_idx, _u64 lba, _u8 *p_data, _u16 count, HMUTEX hlock=0)=0; virtual void eject(_u8 ata_idx)=0; }; typedef struct { _u8 _ata_index_; // device index (ATA_MASTER or ATA_SLAVE) _u8 _ata_type_; // device type (IDE_ATA or IDE_ATAPI) _u16 _ata_signature_; _u16 _ata_features_; _u32 _ata_command_sets_; _u32 _ata_size_; // size in sectors _u8 _ata_model_[42]; iIDEChannel *_ata_channel_; // IDE channel }_ide_device_t; class iIDEDevice:public iDriverBase, public _ide_device_t { public: DECLARE_INTERFACE(I_IDE_DEVICE, iIDEDevice, iDriverBase); }; /////////////////////////////////////////////////////////////////////////////////////////////////// typedef struct { _vaddr_t _ahci_abar_; // controller memory map _u8 _ahci_prog_if_; // proramming interface byte _u8 _ahci_irq_; // IRQ marker (PCI interrupt line) _u32 _ahci_pci_index_; // PCI device index (0xffffffff for invalid index) }_ahci_ctrl_t; class iAHCIController:public iDriverBase, public _ahci_ctrl_t { public: DECLARE_INTERFACE(I_AHCI_CONTROLLER, iAHCIController, iDriverBase); virtual void wait_irq(_u32 timeout=EVENT_TIMEOUT_INFINITE)=0; virtual _u32 read(_u8 reg)=0; // read HBA register virtual void write(_u8 reg, _u32 value)=0; // write HBA register }; typedef struct { _u8 _sata_index_; // sata index per controller (0..31) _vaddr_t _sata_port_; // port memory map _u8 _sata_max_cmd_count_; // max. number of commands _u32 _sata_command_sets_; _u8 _sata_model_[42]; }_ahci_device_t; class iAHCIDevice:public iDriverBase, public _ahci_device_t { public: DECLARE_INTERFACE(I_AHCI_DEVICE, iAHCIDevice, iDriverBase); }; ///////////////////////////////////////////////////////////////////////////////////////////////// typedef struct { _u32 _fdc_base_; _u8 _fdc_detect_; // high 4 bits for FDA & low 4 bits for FDB }_fd_ctrl_t; class iFDController:public iDriverBase, public _fd_ctrl_t { public: DECLARE_INTERFACE(I_FD_CONTROLLER, iFDController, iDriverBase); virtual _u8 read_reg(_u32 reg)=0; virtual void write_reg(_u32 reg, _u8 value)=0; virtual bool wait_irq(_u32 timeout=EVENT_TIMEOUT_INFINITE)=0; virtual void enable_irq(bool eirq=true)=0; virtual void select(_u8 dev_idx)=0; }; typedef struct { _u8 _fdd_index_; _u8 _fdd_data_rate_; _u8 _fdd_tracks_; // cylindres _u8 _fdd_heads_; _u8 _fdd_spt_; // sectors per track _u16 _fdd_sectors_; // total sectors per disk _u8 _fdd_gap_; _cstr_t _fdd_ident_; // ident text }_fd_device_t; class iFDDevice:public iDriverBase, public _fd_device_t { public: DECLARE_INTERFACE(I_FD_DEVICE, iFDDevice, iDriverBase); }; typedef struct { _u8 _ramd_idx_; // ram disk index _ulong _ramd_size_; // disk size in bytes }_ram_device_t; class iRamDevice:public iDriverBase, public _ram_device_t { public: DECLARE_INTERFACE(I_RAM_DEVICE, iRamDevice, iDriverBase); }; #endif
3883142d7e07ef4b270b2a81fcce1e28616a31fb
462386473c2da64f3215150627e1c058ba811755
/BattleTank/Source/BattleTank/Private/Tank.cpp
1bf40a0519c8c7a74a61d16e7c6284803b0f2bdb
[]
no_license
bomcon123456/BattleTank
bf941e954a6e3784982e8dc6a83a51e58ffbcc0a
b2c25eff24f3bf35a46b0f4cf348fa9cee54ba0c
refs/heads/master
2021-09-02T16:04:00.204082
2018-01-03T14:30:08
2018-01-03T14:30:08
113,677,168
0
0
null
null
null
null
UTF-8
C++
false
false
993
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Tank.h" // Sets default values ATank::ATank() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; } // Called when the game starts or when spawned void ATank::BeginPlay() { Super::BeginPlay(); } // Called to bind functionality to input void ATank::SetupPlayerInputComponent(class UInputComponent* InputComponent) { Super::SetupPlayerInputComponent(InputComponent); } float ATank::TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) { int32 DamagePoints = FPlatformMath::RoundToInt(DamageAmount); int32 DamageToApply = FMath::Clamp<int32>(DamagePoints,0, CurrentHealth); CurrentHealth -= DamageToApply; if (CurrentHealth <= 0) { UE_LOG(LogTemp, Warning, TEXT("Tank dies!!!!")) } return DamageToApply; }
5329469d1a072efba2399f6d82d6a46f8939b7da
4dd69f3df7d32a35b3318c226f6765d3e9a63b0a
/2019/2019down/Uva/Uva11286.cpp
16613ae1a628ea95822b99c82a696a8b149fedbb
[]
no_license
dereksodo/allcode
f921294fbb824ab59e64528cd78ccc1f3fcf218d
7d4fc735770ea5e09661824b0b0adadc7e74c762
refs/heads/master
2022-04-13T17:45:29.132307
2020-04-08T04:27:44
2020-04-08T04:27:44
197,805,259
1
1
null
null
null
null
UTF-8
C++
false
false
1,111
cpp
#include <iostream> #include <cstring> #include <cstdlib> #include <unordered_set> #include <vector> #include <map> #include <cstdio> #include <utility> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <cassert> #include <climits> using namespace std; typedef long long ll; #define DEBUG #ifdef DEBUG #define debug printf #else #define debug(...) #endif const int mod = 1e9 + 7; const int ht = 8999; const int n = 5; int a[n]; unordered_set<int> v; int maxp; map<int,int> mp; int hash_init() { sort(a,a + n); int ret = 0; for(int i = 0;i < n; ++i) { ret = (ret * ht % mod + a[i]) % mod; } mp[ret]++; maxp = max(maxp,mp[ret]); v.insert(ret); return ret; } int main(int argc, char const *argv[]) { int k; while(cin>>k && k) { v.clear(); mp.clear(); maxp = 0; for(int i = 0;i < k; ++i) { for(int j = 0;j < n; ++j) { scanf("%d",&a[j]); } hash_init(); } int ans = 0; for(unordered_set<int>::iterator iter = v.begin();iter != v.end(); ++iter) { if(mp[*iter] == maxp) { ans += maxp; } } cout<<ans<<endl; } return 0; }
[ "pi*7=7.17" ]
pi*7=7.17
61094ea6e9ee065faa1b57eacde1cd21af7c4671
786de89be635eb21295070a6a3452f3a7fe6712c
/psana/tags/V00-06-03/pyext/Scan.cpp
b26194787e8195ffcb797f543f2364416d6c8883
[]
no_license
connectthefuture/psdmrepo
85267cfe8d54564f99e17035efe931077c8f7a37
f32870a987a7493e7bf0f0a5c1712a5a030ef199
refs/heads/master
2021-01-13T03:26:35.494026
2015-09-03T22:22:11
2015-09-03T22:22:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,377
cpp
//-------------------------------------------------------------------------- // File and Version Information: // $Id$ // // Description: // Class Scan... // // Author List: // Andrei Salnikov // //------------------------------------------------------------------------ //----------------------- // This Class's Header -- //----------------------- #include "Scan.h" //----------------- // C/C++ Headers -- //----------------- //------------------------------- // Collaborating Class Headers -- //------------------------------- #include "EventIter.h" //----------------------------------------------------------------------- // Local Macros, Typedefs, Structures, Unions and Forward Declarations -- //----------------------------------------------------------------------- namespace { // type-specific methods PyObject* Scan_events(PyObject* self, PyObject*); PyObject* Scan_nonzero(PyObject* self, PyObject*); PyMethodDef methods[] = { { "events", Scan_events, METH_NOARGS, "self.events() -> iterator\n\nReturns iterator for contained events (:py:class:`EventIter`)" }, { "__nonzero__", Scan_nonzero, METH_NOARGS, "self.__nonzero__() -> bool\n\nReturns true for non-null object" }, {0, 0, 0, 0} }; char typedoc[] = "Python wrapper for psana Scan type. Run type represents data originating " "from a single scans (calib cycles) which contains events. This class provides way to " "iterate over individual events contained in a scan. Actual iteration is implemented in " ":py:class:`EventIter` class, this class serves as a factory for iterator instances."; } // ---------------------------------------- // -- Public Function Member Definitions -- // ---------------------------------------- void psana::pyext::Scan::initType(PyObject* module) { PyTypeObject* type = BaseType::typeObject() ; type->tp_doc = ::typedoc; type->tp_methods = ::methods; BaseType::initType("Scan", module); } namespace { PyObject* Scan_events(PyObject* self, PyObject* ) { psana::pyext::Scan* py_this = static_cast<psana::pyext::Scan*>(self); return psana::pyext::EventIter::PyObject_FromCpp(py_this->m_obj.events()); } PyObject* Scan_nonzero(PyObject* self, PyObject* ) { psana::pyext::Scan* py_this = static_cast<psana::pyext::Scan*>(self); return PyBool_FromLong(long(bool(py_this->m_obj))); } }
[ "[email protected]@b967ad99-d558-0410-b138-e0f6c56caec7" ]
[email protected]@b967ad99-d558-0410-b138-e0f6c56caec7
7a9bb803a8eff27330c24b12e83c6e9ab7dee176
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/00/750bf7564ab6d4/main.cpp
b7eb2cf40f345d23facbb9e03f714b58e130981a
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
3,151
cpp
#include <tuple> #include <iostream> namespace detail { template<bool c, bool v, bool lref, bool rref, class C, class Ret, class... Args> struct decompose_mem_fun_ptr_members { constexpr static bool is_const() { return c; } constexpr static bool is_volatile() { return v; } constexpr static bool is_lref() { return lref; } constexpr static bool is_rref() { return rref; } using return_type = Ret; using class_type = C; using arguments = std::tuple<Args...>; static void print() { std::cout << __PRETTY_FUNCTION__ << "\n"; } }; } template<class T> struct decompose_mem_fun_ptr; // no ref template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...)> : detail::decompose_mem_fun_ptr_members<false, false, false, false, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) const> : detail::decompose_mem_fun_ptr_members<true, false, false, false, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) volatile> : detail::decompose_mem_fun_ptr_members<false, true, false, false, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) const volatile> : detail::decompose_mem_fun_ptr_members<true, true, false, false, C, Ret, Args...> {}; // lref template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) &> : detail::decompose_mem_fun_ptr_members<false, false, true, false, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) const &> : detail::decompose_mem_fun_ptr_members<true, false, true, false, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) volatile &> : detail::decompose_mem_fun_ptr_members<false, true, true, false, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) const volatile &> : detail::decompose_mem_fun_ptr_members<true, true, true, false, C, Ret, Args...> {}; //rref template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) &&> : detail::decompose_mem_fun_ptr_members<false, false, false, true, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) const &&> : detail::decompose_mem_fun_ptr_members<true, false, false, true, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) volatile &&> : detail::decompose_mem_fun_ptr_members<false, true, false, true, C, Ret, Args...> {}; template<class C, class Ret, class... Args> struct decompose_mem_fun_ptr<Ret (C::*)(Args...) const volatile &&> : detail::decompose_mem_fun_ptr_members<true, true, false, true, C, Ret, Args...> {}; struct foo { bool bar(int, double, char) const &&; }; int main() { decompose_mem_fun_ptr<decltype(&foo::bar)>::print(); }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
071309bfe79589950cbcdc3ea79e514688263ed9
1cfeed65b135d0ab987160903a11023a9875a630
/wpilibc/src/test/native/cpp/LinearFilterNoiseTest.cpp
0bb10021c78e8171a3c194cf08d83887a61619e4
[ "BSD-3-Clause" ]
permissive
epicmonky/allwpilib
b82006e3ce67932c02ed710528cdc248cae8ac7a
65eab93527bcd87964fc229c6f9c2b29c983c744
refs/heads/master
2021-01-06T19:12:19.771548
2020-02-15T20:36:16
2020-02-15T20:36:16
241,454,073
1
0
NOASSERTION
2020-02-18T19:55:02
2020-02-18T19:55:02
null
UTF-8
C++
false
false
2,968
cpp
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2015-2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "frc/LinearFilter.h" // NOLINT(build/include_order) #include <cmath> #include <memory> #include <random> #include <units/units.h> #include <wpi/math> #include "gtest/gtest.h" // Filter constants static constexpr units::second_t kFilterStep = 0.005_s; static constexpr units::second_t kFilterTime = 2.0_s; static constexpr double kSinglePoleIIRTimeConstant = 0.015915; static constexpr int32_t kMovAvgTaps = 6; enum LinearFilterNoiseTestType { TEST_SINGLE_POLE_IIR, TEST_MOVAVG }; std::ostream& operator<<(std::ostream& os, const LinearFilterNoiseTestType& type) { switch (type) { case TEST_SINGLE_POLE_IIR: os << "LinearFilter SinglePoleIIR"; break; case TEST_MOVAVG: os << "LinearFilter MovingAverage"; break; } return os; } static double GetData(double t) { return 100.0 * std::sin(2.0 * wpi::math::pi * t); } class LinearFilterNoiseTest : public testing::TestWithParam<LinearFilterNoiseTestType> { protected: std::unique_ptr<frc::LinearFilter<double>> m_filter; void SetUp() override { switch (GetParam()) { case TEST_SINGLE_POLE_IIR: { m_filter = std::make_unique<frc::LinearFilter<double>>( frc::LinearFilter<double>::SinglePoleIIR(kSinglePoleIIRTimeConstant, kFilterStep)); break; } case TEST_MOVAVG: { m_filter = std::make_unique<frc::LinearFilter<double>>( frc::LinearFilter<double>::MovingAverage(kMovAvgTaps)); break; } } } }; /** * Test if the filter reduces the noise produced by a signal generator */ TEST_P(LinearFilterNoiseTest, NoiseReduce) { double noiseGenError = 0.0; double filterError = 0.0; std::random_device rd; std::mt19937 gen{rd()}; std::normal_distribution<double> distr{0.0, 10.0}; for (auto t = 0_s; t < kFilterTime; t += kFilterStep) { double theory = GetData(t.to<double>()); double noise = distr(gen); filterError += std::abs(m_filter->Calculate(theory + noise) - theory); noiseGenError += std::abs(noise - theory); } RecordProperty("FilterError", filterError); // The filter should have produced values closer to the theory EXPECT_GT(noiseGenError, filterError) << "Filter should have reduced noise accumulation but failed"; } INSTANTIATE_TEST_SUITE_P(Test, LinearFilterNoiseTest, testing::Values(TEST_SINGLE_POLE_IIR, TEST_MOVAVG));
e397fe56c25be752a5ee12c3c0265377fe495a32
04b1803adb6653ecb7cb827c4f4aa616afacf629
/ash/wm/desks/desk_mini_view.cc
0d8372b8e5c68ca87f24de2ff4348169109ec1e8
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
7,036
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/desks/desk_mini_view.h" #include <algorithm> #include "ash/wm/desks/close_desk_button.h" #include "ash/wm/desks/desk.h" #include "ash/wm/desks/desk_preview_view.h" #include "ash/wm/desks/desks_bar_view.h" #include "ash/wm/desks/desks_controller.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" namespace ash { namespace { constexpr int kLabelPreviewSpacing = 8; constexpr int kCloseButtonMargin = 4; constexpr gfx::Size kCloseButtonSize{24, 24}; constexpr SkColor kActiveColor = SkColorSetARGB(0xEE, 0xFF, 0xFF, 0xFF); constexpr SkColor kInactiveColor = SkColorSetARGB(0x50, 0xFF, 0xFF, 0xFF); constexpr SkColor kDraggedOverColor = SkColorSetARGB(0xFF, 0x5B, 0xBC, 0xFF); std::unique_ptr<DeskPreviewView> CreateDeskPreviewView( DeskMiniView* mini_view) { auto desk_preview_view = std::make_unique<DeskPreviewView>(mini_view); desk_preview_view->set_owned_by_client(); return desk_preview_view; } // The desk preview bounds are proportional to the bounds of the display on // which it resides, but always has a fixed height `kDeskPreviewHeight`. gfx::Rect GetDeskPreviewBounds(aura::Window* root_window) { const auto root_size = root_window->GetBoundsInRootWindow().size(); const int preview_height = DeskPreviewView::GetHeight(); return gfx::Rect(preview_height * root_size.width() / root_size.height(), preview_height); } } // namespace // ----------------------------------------------------------------------------- // DeskMiniView DeskMiniView::DeskMiniView(DesksBarView* owner_bar, aura::Window* root_window, Desk* desk, const base::string16& title) : views::Button(owner_bar), owner_bar_(owner_bar), root_window_(root_window), desk_(desk), desk_preview_(CreateDeskPreviewView(this)), label_(new views::Label(title)), close_desk_button_(new CloseDeskButton(this)) { desk_->AddObserver(this); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); label_->SetAutoColorReadabilityEnabled(false); label_->SetSubpixelRenderingEnabled(false); label_->set_can_process_events_within_subtree(false); label_->SetEnabledColor(SK_ColorWHITE); label_->SetLineHeight(10); close_desk_button_->SetVisible(false); // TODO(afakhry): Tooltips and accessible names. AddChildView(desk_preview_.get()); AddChildView(label_); AddChildView(close_desk_button_); SetFocusPainter(nullptr); SetInkDropMode(InkDropMode::OFF); UpdateBorderColor(); SchedulePaint(); } DeskMiniView::~DeskMiniView() { // In tests, where animations are disabled, the mini_view maybe destroyed // before the desk. if (desk_) desk_->RemoveObserver(this); } void DeskMiniView::SetTitle(const base::string16& title) { label_->SetText(title); } aura::Window* DeskMiniView::GetDeskContainer() const { DCHECK(desk_); return desk_->GetDeskContainerForRoot(root_window_); } void DeskMiniView::OnHoverStateMayHaveChanged() { // TODO(afakhry): In tablet mode, discuss showing the close button on long // press. // Don't show the close button when hovered while the dragged window is on // the DesksBarView. close_desk_button_->SetVisible(DesksController::Get()->CanRemoveDesks() && !owner_bar_->dragged_item_over_bar() && IsMouseHovered()); } void DeskMiniView::UpdateBorderColor() { DCHECK(desk_); if (owner_bar_->dragged_item_over_bar() && IsPointOnMiniView(owner_bar_->last_dragged_item_screen_location())) { desk_preview_->SetBorderColor(kDraggedOverColor); } else { desk_preview_->SetBorderColor(desk_->is_active() ? kActiveColor : kInactiveColor); } } const char* DeskMiniView::GetClassName() const { return "DeskMiniView"; } void DeskMiniView::Layout() { auto* root_window = GetWidget()->GetNativeWindow()->GetRootWindow(); DCHECK(root_window); const gfx::Rect preview_bounds = GetDeskPreviewBounds(root_window); desk_preview_->SetBoundsRect(preview_bounds); const gfx::Size label_size = label_->GetPreferredSize(); const gfx::Rect label_bounds{ (preview_bounds.width() - label_size.width()) / 2, preview_bounds.bottom() + kLabelPreviewSpacing, label_size.width(), label_size.height()}; label_->SetBoundsRect(label_bounds); close_desk_button_->SetBounds( preview_bounds.right() - kCloseButtonSize.width() - kCloseButtonMargin, kCloseButtonMargin, kCloseButtonSize.width(), kCloseButtonSize.height()); Button::Layout(); SchedulePaint(); } gfx::Size DeskMiniView::CalculatePreferredSize() const { auto* root_window = GetWidget()->GetNativeWindow()->GetRootWindow(); DCHECK(root_window); const gfx::Size label_size = label_->GetPreferredSize(); const gfx::Rect preview_bounds = GetDeskPreviewBounds(root_window); return gfx::Size{ std::max(preview_bounds.width(), label_size.width()), preview_bounds.height() + kLabelPreviewSpacing + label_size.height()}; } void DeskMiniView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK(desk_); if (sender != close_desk_button_) return; // Hide the close button so it can no longer be pressed. close_desk_button_->SetVisible(false); // This mini_view can no longer be pressed. listener_ = nullptr; auto* controller = DesksController::Get(); DCHECK(controller->CanRemoveDesks()); controller->RemoveDesk(desk_); } void DeskMiniView::OnContentChanged() { desk_preview_->RecreateDeskContentsMirrorLayers(); } void DeskMiniView::OnDeskDestroyed(const Desk* desk) { // Note that the mini_view outlives the desk (which will be removed after all // DeskController's observers have been notified of its removal) because of // the animation. // Note that we can't make it the other way around (i.e. make the desk outlive // the mini_view). The desk's existence (or lack thereof) is more important // than the existence of the mini_view, since it determines whether we can // create new desks or remove existing ones. This determines whether the close // button will show on hover, and whether the new_desk_button is enabled. We // shouldn't allow that state to be wrong while the mini_views perform the // desk removal animation. // TODO(afakhry): Consider detaching the layer and destroying the mini_view // directly. DCHECK_EQ(desk_, desk); desk_ = nullptr; // No need to remove `this` as an observer; it's done automatically. } bool DeskMiniView::IsPointOnMiniView(const gfx::Point& screen_location) const { gfx::Point point_in_view = screen_location; ConvertPointFromScreen(this, &point_in_view); return HitTestPoint(point_in_view); } } // namespace ash
f9c263578803fb04b1ac1b8994553abd7211c824
825e64b1cb17aac2a4d5c396d7bbeaca91aaaa10
/src/hxhim/ops/DELETE.cpp
e11d500688e2e7b1451ebb91c08e73fb53f31268
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cpshereda/hxhim
7cf7643228f44a7ce336bedf05762ad95d5b72bd
1ef69e33d320e629779df27fb36de102f587c829
refs/heads/master
2023-01-29T12:53:21.008388
2020-12-08T19:50:24
2020-12-08T19:50:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,995
cpp
#include "hxhim/Blob.hpp" #include "hxhim/hxhim.hpp" #include "hxhim/private/hxhim.hpp" /** * Delete * Add a DELETE into the work queue * * @param hx the HXHIM session * @param subject the subject to delete * @param subject_len the length of the subject to delete * @param prediate the prediate to delete * @param prediate_len the length of the prediate to delete * @return HXHIM_SUCCESS or HXHIM_ERROR */ int hxhim::Delete(hxhim_t *hx, void *subject, std::size_t subject_len, enum hxhim_data_t subject_type, void *predicate, std::size_t predicate_len, enum hxhim_data_t predicate_type) { if (!valid(hx) || !hx->p->running || !subject || !subject_len || !predicate || !predicate_len) { return HXHIM_ERROR; } ::Stats::Chronostamp del; del.start = ::Stats::now(); const int rc = hxhim::DeleteImpl(hx, hx->p->queues.deletes, ReferenceBlob(subject, subject_len, subject_type), ReferenceBlob(predicate, predicate_len, predicate_type)); del.end = ::Stats::now(); hx->p->stats.single_op[hxhim_op_t::HXHIM_DELETE].emplace_back(del); return rc; } /** * hxhimDelete * Add a DELETE into the work queue * * @param hx the HXHIM session * @param subject the subject to delete * @param subject_len the length of the subject to delete * @param prediate the prediate to delete * @param prediate_len the length of the prediate to delete * @return HXHIM_SUCCESS or HXHIM_ERROR */ int hxhimDelete(hxhim_t *hx, void *subject, size_t subject_len, enum hxhim_data_t subject_type, void *predicate, size_t predicate_len, enum hxhim_data_t predicate_type) { return hxhim::Delete(hx, subject, subject_len, subject_type, predicate, predicate_len, predicate_type); }
dfe0739cc25dde870094b447c4a6dc59adc67a77
2ca9965ed3c584899011ca0527e3c0425b9c70ba
/LRDuinoTD5.ino
567db5dbda8df6a7b33f9a236f7243ab4c29429a
[ "Beerware" ]
permissive
Salmon-Built-Designs/LRDuinoTD5
fd5e113f015308c8df0b91dcf6da296e7c44098f
042df73b852e3d53c4cb9856024bc036adcdb761
refs/heads/master
2021-10-16T10:46:03.646634
2019-02-10T17:54:34
2019-02-10T17:54:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,364
ino
// LRDuino by Ben Anderson // Version 0.014 // Please select your display type below by uncommenting ONLY your display type (lines 57-59) #include <SPI.h> #if defined ARDUINO_BLACK_F407VE || defined ARDUINO_BLACK_F407ZE || defined ARDUINO_BLACK_F407ZG || defined ARDUINO_FK407M1// STM Core & SDIO #include "LRDuinoDefs407VE.h" #define HAS_SDIO SPIClass SPI_2(PB15,PB14,PB13); // Max31856 on MOSI, MISO, CLK - SPI2 on F4, STM Core #define ARCH_DEFINED #endif #if defined ARDUINO_DIYMROE_F407VGT // STM Core SPI SD #include "LRDuinoDefs407VE.h" #define ARCH_DEFINED SPIClass SPI_2(PB15,PB14,PB13); // Max31856 on MOSI, MISO, CLK - SPI2 on F4, STM Core #endif #if defined BOARD_maple_mini || defined BOARD_generic_stm32f103c // Roger's Maple core SPI SD #include "LRDuinoDefsMM.h" SPIClass SPI_2(2); // Max31856 on SPI2 #define ARCH_DEFINED #endif #if defined ARDUINO_MAPLEMINI_F103CB || defined ARDUINO_BLUEPILL_F103C8 || defined ARDUINO_BLACKPILL_F103C8 // STM Core SPI SD #include "LRDuinoDefsMM.h" SPIClass SPI_2(PB15,PB14,PB13); // Max31856 on MOSI, MISO, CLK - SPI2 on F1, STM Core #define Serial SerialUSB #define ARCH_DEFINED #endif #if defined ARDUINO_ARCH_ESP32 // Espressif Core #include "LRDuinoDefsESP.h" static const int spiClk = 8000000; // 8 MHz SPIClass * vspi = NULL; // TODO Break MAX out onto 2nd SPI peripheral #define ARCH_DEFINED #endif #if defined HAS_SDIO // Setup SD #include <STM32SD.h> #ifndef SD_DETECT_PIN #define SD_DETECT_PIN SD_DETECT_NONE #endif File sdLogFile; #else #include <SdFat.h> SdFat sd; SdFile sdLogFile; #endif #ifndef ARCH_DEFINED #error Unsupported core \ board combination #endif // uncommment the define that matches your diaplsy type #define USE_SSD1306 //#define USE_SSD1331 //#define USE_SSD1351 #include <Adafruit_GFX.h> #if defined USE_SSD1306 #include <Adafruit_SSD1306.h> #define SCREEN_CHOSEN Adafruit_SSD1306 display1(OLED_DC, OLED_RESET, OLEDCS_1); #endif #if defined USE_SSD1331 #include <Adafruit_SSD1331.h> #define SCREEN_CHOSEN Adafruit_SSD1331 display1(OLEDCS_1, OLED_DC, OLED_RESET); #endif #if defined USE_SSD1351 #include <Adafruit_SSD1351.h> #define SCREEN_CHOSEN Adafruit_SSD1351 display1(128, 128, &SPI, OLEDCS_1, OLED_DC, OLED_RESET); #endif #ifndef SCREEN_CHOSEN #error Please choose a screen type by uncommenting one choice only eg "#define USE_SSD1306" #endif #include "Macros.h" #include "LRDuinoGFX.h" #include <Fonts/FreeSansBoldOblique9pt7b.h> #include <Fonts/FreeSansBoldOblique12pt7b.h> #include <Fonts/FreeSansBoldOblique18pt7b.h> #include <Fonts/FreeSansBoldOblique24pt7b.h> #include <menu.h> #include <menuIO/chainStream.h> #include <menuIO/adafruitGfxOut.h> #include <menuIO/serialIn.h> #include <Buttons.h> #include "td5comm.h" using namespace Menu; byte RegisterValues[] = {0x90, 0x03, 0xFC, 0x7F, 0xC0, 0x7F, 0xFF, 0x80, 0x00, 0x00 }; String RegisterNames[] = {"CR0", "CR1", "MASK", "CJHF", "CHLF", "LTHFTH", "LTHFTL", "LTLFTH", "LTLFTL", "CJTO"}; byte RegisterAddresses[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; Td5Comm td5; // setup ODBC object // Button initialisation Button btn_up(UPBUT, LOW); Button btn_down(DOWNBUT, LOW); Button btn_left(LEFTBUT, LOW); Button btn_right(RIGHTBUT, LOW); Button btn_enter(SELBUT, LOW); #include "td5sensors.h" // Insert code to read settings in here, and also set default states of sensors to hidden if hw is not present // end settings reading section uint8_t sensecount = 0; uint8_t rotation = 0; // incremented by 1 with each button press - it's used to tell the drawdisplay functions which sensor data they should output. // the follow variable is a long because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. unsigned long previousMillis = 0; // will store last time the displays were updated unsigned long OBDslowMillis = 0; unsigned long OBDfastMillis = 0; unsigned long menuMillis = 0; unsigned long inptimeoutMillis = 0; // MENUS #define textScale 1 #define fontX 5 #define fontY 9 bool inMenu = false; // if true then the menu should be output on display1 bool exitMenu = false; bool dataLog = false; // if true then we are writing data to SD bool sd_present = false; // changes to false if an SD card is inserted at startup result quitMenu() { inMenu = false; exitMenu = true; inptimeoutMillis = inptimeoutMillis - MENUTIMEOUT; return proceed; } MENU(setMenu,"Settings",doNothing,anyEvent,wrapStyle ,OP("Save Settings",doNothing,enterEvent) ,OP("Read Settings",doNothing,enterEvent) ,OP("Reset to Defaults",doNothing,enterEvent) ,EXIT("<Back") ); MENU(ecuMenu,"ECU",doNothing,anyEvent,wrapStyle ,OP("Connect to ECU",initOBD,enterEvent) ,OP("Read Faults",doNothing,enterEvent) ,OP("Clear Faults",doNothing,enterEvent) ,EXIT("<Back") ); TOGGLE(Sensors[0].hidden,sensor0Toggle, "Boost: ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[1].hidden,sensor1Toggle, "Tbox Temp: ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[2].hidden,sensor2Toggle, "EGT: ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[3].hidden,sensor3Toggle, "Oil Press/Tmp: ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[5].hidden,sensor5Toggle, "Coolent Lev: ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[6].hidden,sensor6Toggle, "RPM (OBD): ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[7].hidden,sensor7Toggle, "Speed (OBD): ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[8].hidden,sensor8Toggle, "ECT (OBD): ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[9].hidden,sensor9Toggle, "BtV (OBD): ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[10].hidden,sensor10Toggle, "InT (OBD): ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[11].hidden,sensor11Toggle, "FlT (OBD): ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); TOGGLE(Sensors[12].hidden,sensor12Toggle, "AAP (OBD): ",getSensecount,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",false,doNothing,noEvent) ,VALUE("Off",true,doNothing,noEvent) ); MENU(togsensMenu,"En/Dis(able) Sensors",doNothing,anyEvent,wrapStyle ,SUBMENU(sensor0Toggle) ,SUBMENU(sensor1Toggle) ,SUBMENU(sensor2Toggle) ,SUBMENU(sensor3Toggle) // No sensor4 because this is paired with 3 ,SUBMENU(sensor5Toggle) ,SUBMENU(sensor6Toggle) ,SUBMENU(sensor7Toggle) ,SUBMENU(sensor8Toggle) ,SUBMENU(sensor9Toggle) ,SUBMENU(sensor10Toggle) ,SUBMENU(sensor11Toggle) ,EXIT("<Back") ); MENU(lowarnMenu,"Low Warnings",doNothing,anyEvent,wrapStyle ,FIELD(Sensors[3].sensewarnlowvals,"Oil Pressure","psi",Sensors[3].senseminvals,Sensors[3].sensemaxvals,10,1,doNothing,noEvent,wrapStyle) ,EXIT("<Back") ); MENU(hiwarnMenu,"High Warnings",doNothing,anyEvent,wrapStyle ,FIELD(Sensors[0].sensewarnhivals,"Boost","psi",Sensors[0].senseminvals,Sensors[0].sensemaxvals,10,1,doNothing,noEvent,wrapStyle) ,FIELD(Sensors[1].sensewarnhivals,"Tbox Temp","C",Sensors[1].senseminvals,Sensors[1].sensemaxvals,10,1,doNothing,noEvent,wrapStyle) ,FIELD(Sensors[2].sensewarnhivals,"EGT","C",Sensors[2].senseminvals,Sensors[2].sensemaxvals,50,10,doNothing,noEvent,wrapStyle) ,FIELD(Sensors[3].sensewarnhivals,"Oil Pressure","psi",Sensors[3].senseminvals,Sensors[3].sensemaxvals,10,1,doNothing,noEvent,wrapStyle) ,FIELD(Sensors[4].sensewarnhivals,"Oil Temp","C",Sensors[4].senseminvals,Sensors[4].sensemaxvals,10,1,doNothing,noEvent,wrapStyle) ,FIELD(Sensors[8].sensewarnhivals,"Coolant Temp","C",Sensors[8].senseminvals,Sensors[8].sensemaxvals,10,1,doNothing,noEvent,wrapStyle) ,EXIT("<Back") ); MENU(sensorMenu,"Sensors",doNothing,anyEvent,wrapStyle ,SUBMENU(togsensMenu) ,OP("Change Order",doNothing,enterEvent) ,SUBMENU(lowarnMenu) ,SUBMENU(hiwarnMenu) ,EXIT("<Back") ); TOGGLE(dataLog, dataLogging, "Datalogging: ",toggleDatalog,enterEvent,wrapStyle//,doExit,enterEvent,noStyle ,VALUE("On",true,doNothing,noEvent) ,VALUE("Off",false,doNothing,noEvent) ); MENU(mainMenu,"Main menu",doNothing,noEvent,wrapStyle ,SUBMENU(sensorMenu) ,SUBMENU(dataLogging) ,SUBMENU(ecuMenu) ,SUBMENU(setMenu) ,OP("<Quit Menu",quitMenu,enterEvent) //,EXIT("<Quit Menu") ); const colorDef<uint16_t> colors[] MEMMODE={ {{BLACK,WHITE},{BLACK,WHITE,WHITE}},//bgColor {{WHITE,BLACK},{WHITE,BLACK,BLACK}},//fgColor {{WHITE,BLACK},{WHITE,BLACK,BLACK}},//valColor {{WHITE,BLACK},{WHITE,BLACK,BLACK}},//unitColor {{WHITE,BLACK},{BLACK,BLACK,BLACK}},//cursorColor {{WHITE,BLACK},{BLACK,WHITE,WHITE}},//titleColor }; MENU_OUTPUTS(out,MAX_DEPTH // ,SERIAL_OUT(Serial) ,ADAGFX_OUT(display1,colors,fontX,fontY,{0,0,128/fontX,64/fontY}) ,NONE//must have 2 items at least ); serialIn in(Serial); NAVROOT(nav,mainMenu,MAX_DEPTH,in,out); // END MENUS void setup() { //start serial connection //Serial.begin(57600); //uncomment to send serial debug info #if defined ARDUINO_ARCH_ESP32 vspi = new SPIClass(VSPI); vspi->begin(); analogReadResolution(12); //12 bits analogSetAttenuation(ADC_11db); //For all pins = 0-3.3v #endif #if defined ARDUINO_ARCH_STM32 #if defined BOARD_maple_mini || defined BOARD_generic_stm32f103c // do nothing #else analogReadResolution(12); //12 bits #endif #endif // Pin setup pinMode (OLEDCS_1, OUTPUT); digitalWrite(OLEDCS_1, HIGH); pinMode (MAX_CS, OUTPUT); digitalWrite(MAX_CS, HIGH); pinMode (SD_CS, OUTPUT); digitalWrite(SD_CS, HIGH); #if defined ARDUINO_BLACK_F407VE || defined ARDUINO_BLACK_F407ZE || defined ARDUINO_BLACK_F407ZG pinMode (PA0, INPUT_PULLDOWN); //Button K_UP #endif MAXInitializeChannel(MAX_CS); // Init the MAX31856 display1.begin(8000000); //construct our displays SCREEN_CLEAR(); // clears the screen and buffer SCREEN_DISPLAY(); //output to the screen to avoid adafruit logo // Ensure #define ENABLE_SPI_TRANSACTIONS 1 is set in SdFatConfig.h #if defined HAS_SDIO if (!SD.begin(SD_DETECT_PIN)) #else if (!sd.begin(SD_CS, SD_SCK_MHZ(8))) #endif { display1.fillScreen(BLACK); display1.setTextColor(RED); display1.setTextSize(1); display1.setCursor(0, 0); display1.println("SD init failed."); SCREEN_DISPLAY(); delay(200); display1.fillScreen(BLACK); sd_present = false; } else { sd_present = true; } initOBD(); // this also fires getSensecount() } // End Setup void loop() { unsigned long currentMillis = millis(); //store the time // USER INTERACTION if((currentMillis - inptimeoutMillis > MENUTIMEOUT) && (inMenu==true)) { //timeout the menu inMenu=false; SCREEN_CLEAR(); } if(exitMenu == true) { //clear the menu if we exited exitMenu=false; SCREEN_CLEAR(); } if ((!inMenu) && (btn_enter.sense() == buttons_held)) { inMenu=true; // turn the menu on if we have a long press on the enter button inptimeoutMillis = currentMillis; } if (inMenu) { if (currentMillis - menuMillis > BUT_DELAY) { menuMillis = currentMillis; if (btn_up.sense() == buttons_debounce) { nav.doNav(upCmd); // navigate up inptimeoutMillis = currentMillis; } else if (btn_down.sense() == buttons_debounce) { nav.doNav(downCmd); // navigate down inptimeoutMillis = currentMillis; } else if (btn_enter.sense() == buttons_debounce) { nav.doNav(enterCmd); // do current command inptimeoutMillis = currentMillis; } //nav.active().dirty=true;//for a menu //nav.navFocus->dirty=true;//should invalidate also full screen fields assert(nav.navFocus!=NULL) nav.doOutput(); //need to use this as .poll also processes input SCREEN_DISPLAY(); } } // left rotation requested if (btn_left.sense() == buttons_debounce) { if (currentMillis - previousMillis > BUT_DELAY) { rotation = rotation + 1; // rotate the screens if the button was pressed display1.fillScreen(BLACK); previousMillis = previousMillis - (INTERVAL + 1); // force an update of the screens. if (sensecount < NUM_DISPLAYS) { if (rotation == NUM_DISPLAYS) { // if we have less than 8 sensors, keep rotating until we hit the screen count rotation = 0; } } else { if (rotation == sensecount) { // otherwise rotate until we hit the last sensor rotation = 0; } } } } // right rotation requested if (btn_right.sense() == buttons_debounce) { if (currentMillis - previousMillis > BUT_DELAY) { rotation = rotation - 1; // rotate the screens if the button was pressed display1.fillScreen(BLACK); previousMillis = previousMillis - (INTERVAL + 1); // force an update of the screens. if (sensecount < NUM_DISPLAYS) { if (rotation == 0) { // if we have less than 8 sensors, keep rotating until we hit the screen count rotation = NUM_DISPLAYS; } } else { if (rotation == 0) { // otherwise rotate until we hit the last sensor rotation = sensecount; } } } } if (currentMillis - previousMillis > INTERVAL) { // only read the sensors and draw the screen if 250 millis have passed previousMillis = currentMillis; // save the last time we updated if(td5.ecuIsConnected()) { // keep ecu alive if(td5.getLastReceivedPidElapsedTime() > KEEP_ALIVE_TIME) { td5.getPid(&pidKeepAlive); } if (td5.getConsecutiveLostFrames() > 3) { // shutdown in case of too many frames lost disableOBDSensors(); td5.disconnectFromEcu(); } } // ********NEW********* for(uint8_t currentsensor=0; currentsensor < totalsensors; currentsensor++ ){ if (Sensors[currentsensor].senseactive) { Sensors[currentsensor].senselastvals = Sensors[currentsensor].sensevals; // stash the previous value switch(Sensors[currentsensor].sensetype) { // switch based upon the sensor type case ERR2081 : Sensors[currentsensor].sensevals = readERR2081(Sensors[currentsensor].sensepin, currentsensor); break; //optional case KTYPE : Sensors[currentsensor].sensevals = readMAX(currentsensor); // no pin supplied since this is over SPI break; //optional case BOOST3BAR : Sensors[currentsensor].sensevals = readBoost(Sensors[currentsensor].sensepin, currentsensor); break; //optional case CH100PSI : Sensors[currentsensor].sensevals = readPress(Sensors[currentsensor].sensepin, currentsensor); break; //optional case EARTHSW : Sensors[currentsensor].sensevals = readCoolantLevel(Sensors[currentsensor].sensepin, currentsensor); break; //optional case OBD : if (td5.ecuIsConnected()) { switch(Sensors[currentsensor].sensepin) { // if it's OBD switch based upon the PID case OBDRPM : if(td5.getPid(&pidRPM) > 0) { Sensors[currentsensor].sensevals = pidRPM.getlValue(); // RPM } break; case OBDSPD : if(td5.getPid(&pidVehicleSpeed) > 0) { Sensors[currentsensor].sensevals = pidVehicleSpeed.getbValue(0); // Speed } break; case OBDECT : if(td5.getPid(&pidTemperatures) > 0) { Sensors[currentsensor].sensevals = pidTemperatures.getfValue(0); // Coolant Temp } break; case OBDBTV : if(td5.getPid(&pidBatteryVoltage) > 0) { Sensors[currentsensor].sensevals = pidBatteryVoltage.getfValue(); // Battery Voltage } break; case OBDINT : if(td5.getPid(&pidTemperatures) > 0) { Sensors[currentsensor].sensevals = pidTemperatures.getfValue(1); // Inlet Temp } break; case OBDFLT : if(td5.getPid(&pidTemperatures) > 0) { Sensors[currentsensor].sensevals = pidTemperatures.getfValue(3); // Fuel Temp } break; case OBDAAP : if(td5.getPid(&pidAmbientPressure) > 0) { Sensors[currentsensor].sensevals = pidAmbientPressure.getfValue(1); // AAP } break; } // OBD PID switch } // if ECU is connected break; //optional } // Sensor type switch processPeak(currentsensor); // update the highest value if it's been exceeded - useful for graphs. audibleWARN(currentsensor); // issue tones if there's an issue } } if(dataLog == true) { writeDatalogline(); // write out the last readings if we're logging } // DRAW DISPLAYS if (!inMenu) { drawDISPLAY(display1, 1); } } } // Void Loop()
9e30db62228f91f3b2b3837f03ec06dbd839f0a8
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/android_ndk/sources/android/support/src/swprintf.cpp
01cfe5da2d575498bfc14baa8c3af9ca1c1cc1c1
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "SunPro", "BSD-3-Clause", "LicenseRef-scancode-red-hat-attribution", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
3,164
cpp
/* * Copyright (C) 2017 The Android Open Source Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <stdio.h> #include <wchar.h> #include "UniquePtr.h" namespace { const size_t MBS_FAILURE = static_cast<size_t>(-1); } int swprintf(wchar_t* wcs, size_t maxlen, const wchar_t* format, ...) { va_list ap; va_start(ap, format); int result = vswprintf(wcs, maxlen, format, ap); va_end(ap); return result; } int vswprintf(wchar_t* wcs, size_t maxlen, const wchar_t* fmt, va_list ap) { mbstate_t mbstate; memset(&mbstate, 0, sizeof(mbstate)); // At most, each wide character (UTF-32) can be expanded to four narrow // characters (UTF-8). const size_t max_mb_len = maxlen * 4; const size_t mb_fmt_len = wcslen(fmt) * 4 + 1; UniquePtr<char[]> mbfmt(new char[mb_fmt_len]); if (wcsrtombs(mbfmt.get(), &fmt, mb_fmt_len, &mbstate) == MBS_FAILURE) { return -1; } UniquePtr<char[]> mbs(new char[max_mb_len]); int nprinted = vsnprintf(mbs.get(), max_mb_len, mbfmt.get(), ap); if (nprinted == -1) { return -1; } const char* mbsp = mbs.get(); if (mbsrtowcs(wcs, &mbsp, maxlen, &mbstate) == MBS_FAILURE) { return -1; } // Can't use return value from vsnprintf because that number is in narrow // characters, not wide characters. int result = wcslen(wcs); // swprintf differs from snprintf in that it returns -1 if the output was // truncated. // // Truncation can occur in two places: // 1) vsnprintf truncated, in which case the return value is greater than the // length we passed. // 2) Since the char buffer we pass to vsnprintf might be oversized, that // might not truncate while mbsrtowcs will. In this case, mbsp will point // to the next unconverted character instead of nullptr. if (nprinted >= max_mb_len || mbsp != nullptr) { return -1; } return result; }
88a2a38dd72f9196c1eff97d1638f2e49d71135d
8fba05887ee1271be5f605b1a0e693726c9c3a95
/Documents/别人的代码/CodeCraft2019-master/include/element.h
9c0f235f5ddc0922f8e0c4a87b696bd53718949a
[]
no_license
YangzeXie/CodeCraft
f71daec9f8812569d14316a1f8bcf7c63d5db17d
546a715ae8f445559cb569ae7b10193f5ce39d5f
refs/heads/master
2020-04-27T20:29:34.584794
2019-03-26T14:27:47
2019-03-26T14:27:47
174,660,056
2
0
null
null
null
null
UTF-8
C++
false
false
14,081
h
// // Created by Zhibo Zhou on 2019-03-17. // #ifndef CODECRAFT_2019_ELEMENT_H #define CODECRAFT_2019_ELEMENT_H #include <vector> #include <iostream> #define STRAIGHT 0 #define LEFT 1 #define RIGHT 2 class DynamicArray { private: int row; int col; int **array2D; public: DynamicArray(int a = 0, int b = 0) { row = a; col = b; array2D = new int *[row]; if (array2D == NULL) { std::cout << "Allocation failure!\n"; exit(15); } for (int i = 0; i < row; ++i) { array2D[i] = new int[col]; if (array2D[i] == NULL) { std::cout << "Allocation failure!\n"; exit(15); } } for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { array2D[i][j] = -1; } } } DynamicArray(DynamicArray &arr) { row = arr.row; col = arr.col; array2D = new int *[row]; if (array2D == NULL) { std::cout << "Allocation failure!\n"; exit(15); } for (int i = 0; i < row; ++i) { array2D[i] = new int[col]; if (array2D[i] == NULL) { std::cout << "Allocation failure!\n"; exit(15); } } for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { array2D[i][j] = arr.getValue(i, j); } std::cout << '\n'; } } int getRowSize() { return row; } int getColSize() { return col; } void setValue(int x, int y, int value) { if (x < 0 || x > row - 1 || y < 0 || y > col - 1) { std::cout << "Error!" << std::endl; exit(16); } array2D[x][y] = value; } int getValue(int x, int y) { if (x < 0 || x > row - 1 || y < 0 || y > col - 1) { std::cout << "Error!" << std::endl; exit(16); } return array2D[x][y]; } void displayArray() { for (int i = 0; i < row; ++i) { std::cout << '\t'; for (int j = 0; j < col; ++j) { std::cout << array2D[i][j] << '\t'; } std::cout << '\n'; } } ~DynamicArray() { for (int i = 0; i < row; i++) { delete[] array2D[i]; } delete[] array2D; }; }; struct nextMove { int crossID; int roadID; }; class cross { private: int ID; int NumOfRoads; int roadIDSet[4]; public: std::vector<int> sortedRoadIDList; std::vector<int> sortedInRoadIDList; std::vector<int> sortedOutRoadIDList; int NumOfInRoads; int NumOfOutRoads; int carNumInWaiting; public: cross(int id, int r1, int r2, int r3, int r4) { ID = id; roadIDSet[0] = r1; roadIDSet[1] = r2; roadIDSet[2] = r3; roadIDSet[3] = r4; int tmp = 4; for (int i = 0; i < 4; ++i) { if (roadIDSet[i] < 0) { tmp--; } } NumOfRoads = tmp; NumOfInRoads = 0; NumOfOutRoads = 0; carNumInWaiting = 0; } int getCrossID() { return ID; } int getNumOfRoads() { return NumOfRoads; } int getRoadIDSet(int n) { return roadIDSet[n]; } void updateCrossID(int firstID) { ID -= firstID; } void updateRoadID(int firstID) { for (int i = 0; i < 4; ++i) { if (roadIDSet[i] != -1) { roadIDSet[i] -= firstID; } } } void sortRoadID() { for (int i = 0; i < 4; ++i) { if (roadIDSet[i] != -1) { sortedRoadIDList.push_back(roadIDSet[i]); } } std::sort(sortedRoadIDList.begin(), sortedRoadIDList.end()); } }; class simplexRoad { private: int NextLeftRoadID; int NextRightRoadID; int NextStraightRoadID; DynamicArray roadInfoArray; public: simplexRoad(int a, int b) : roadInfoArray(a, b) { int arrayRowSize = roadInfoArray.getRowSize(); int arrayColSize = roadInfoArray.getColSize(); // 初始化为-1,表示暂时该格上无车。 for (int i = 0; i < arrayRowSize; ++i) { for (int j = 0; j < arrayColSize; ++j) { roadInfoArray.setValue(i, j, -1); } } NextLeftRoadID = -1; NextRightRoadID = -1; NextStraightRoadID = -1; } simplexRoad(const simplexRoad &arr) { NextLeftRoadID = arr.NextLeftRoadID; NextRightRoadID = arr.NextRightRoadID; NextStraightRoadID = arr.NextStraightRoadID; roadInfoArray = arr.roadInfoArray; } void setNextRoadID(int direction, int roadId) { if (direction == STRAIGHT) { NextStraightRoadID = roadId; } if (direction == LEFT) { NextLeftRoadID = roadId; } if (direction == RIGHT) { NextRightRoadID = roadId; } } int getNextRoadID(int direction) { if (direction == STRAIGHT) { return NextStraightRoadID; } else if (direction == LEFT) { return NextLeftRoadID; } else if (direction == RIGHT) { return NextRightRoadID; } else { return -1; } } void setRoadInfo(int x, int y, int carId) { roadInfoArray.setValue(x, y, carId); } int getRoadInfo(int x, int y) { return roadInfoArray.getValue(x, y); } void display() { roadInfoArray.displayArray(); } }; class CarPlan { public: int roadID; int orientation; // 0:+,1:-; int nextDirection; }; class road { private: int ID; int IsDuplex; int Length; int NumOfLane; int StartCrossID; int EndCrossID; int MaxSpeed; simplexRoad road0; simplexRoad road1; public: road(int id, int isDuplex, int len, int laneNum, int startId, int endId, int maxspeed) : road0(laneNum, len), road1(laneNum, len) { ID = id; IsDuplex = isDuplex; Length = len; NumOfLane = laneNum; StartCrossID = startId; EndCrossID = endId; MaxSpeed = maxspeed; } road(const road &arr) : road0(arr.NumOfLane, arr.Length), road1(arr.NumOfLane, arr.Length) { ID = arr.ID; IsDuplex = arr.IsDuplex; Length = arr.Length; NumOfLane = arr.NumOfLane; StartCrossID = arr.StartCrossID; EndCrossID = arr.EndCrossID; MaxSpeed = arr.MaxSpeed; } int getRoadMaxSpeed() { return MaxSpeed; } int getRoadID() { return ID; } int getStartCrossID() { return StartCrossID; } int getEndCrossID() { return EndCrossID; } int getRoadLength() { return Length; } int getLaneNum() { return NumOfLane; } void updateRoadID(int firstID) { ID -= firstID; } void updateCrossID(int firstID) { StartCrossID -= firstID; EndCrossID -= firstID; } int isDuplex() { return IsDuplex; } void setSimplexRoadNextRoadID(int thisRoadDirection, int nextRoadDirection, int roadID) { if (thisRoadDirection == 0) { road0.setNextRoadID(nextRoadDirection, roadID); } if (thisRoadDirection == 1) { road1.setNextRoadID(nextRoadDirection, roadID); } } int getSimplexRoadNextRoadID(int thisRoadDirection, int nextRoadDirection) { if (thisRoadDirection == 0) { return road0.getNextRoadID(nextRoadDirection); } if (thisRoadDirection == 1) { return road1.getNextRoadID(nextRoadDirection); } } int getSimplexRoadStartCrossID(int thisRoadDirection) { if (thisRoadDirection == 1) { return EndCrossID; } if (thisRoadDirection == 0) { return StartCrossID; } } int getSimplexRoadEndCrossID(int thisRoadDirection) { if (thisRoadDirection == 0) { return EndCrossID; } if (thisRoadDirection == 1) { return StartCrossID; } } void changeGridState(int direction, int x, int y, int carId) { if (!IsDuplex && direction == 1) { std::cout << "[ERROR] Road " << ID << " is simplex." << std::endl; exit(17); } if (direction == 0) //start --> end, road0; { road0.setRoadInfo(x, y, carId); } if (direction == 1) //end --> start, road1; { road1.setRoadInfo(x, y, carId); } } int getGridState(int direction, int x, int y) { if (!IsDuplex && direction == 1) { std::cout << "[ERROR] Road " << ID << " is simplex." << std::endl; exit(17); } else if (direction == 0) //start --> end, road0; { return road0.getRoadInfo(x, y); } else if (direction == 1) //end --> start, road1; { return road1.getRoadInfo(x, y); } else { return -999; } } void display() { if (IsDuplex) { std::cout << "[ROAD INFO] " << EndCrossID + 1 << " <<<< " << ID + 501 << " <<<< " << StartCrossID + 1 << " :" << std::endl; road0.display(); std::cout << "[ROAD INFO] " << StartCrossID + 1 << " <<<< " << ID + 501 << " <<<< " << EndCrossID + 1 << " :" << std::endl; road1.display(); } else { std::cout << "[ROAD INFO] " << EndCrossID + 1 << " <<<< " << ID + 501 << " <<<< " << StartCrossID + 1 << " :" << std::endl; road0.display(); } std::cout << std::endl; } }; class car { public: int ID; int MaxCarSpeed; int StartPoint; int EndPoint; int MinTime; int PlannedTime; int ActualTime; int FinishedTime; int CarState; // -1:未出发;0:已完成调度(终止状态);1:正在调度(等待状态) class CarPosition { public: int roadID; int orientation; int laneID; int positionID; public: CarPosition(int a = 0, int b = 0, int c = 0, int d = -1) : roadID(a), laneID(b), positionID(c), orientation(d) {} } presentPosition, expectedPosition; std::vector<CarPlan> Plan; int PlanStep; public: car(int id = 0, int maxcarspeed = 0, int startpoint = 0, int endpoint = 0, int mintime = 0) : ID(id), MaxCarSpeed(maxcarspeed), StartPoint(startpoint), EndPoint(endpoint), MinTime(mintime) { CarState = -1; ActualTime = 0; PlannedTime = 0; PlanStep = -1; FinishedTime = 99999; } void pushCarPlan(CarPlan plan) { Plan.push_back(plan); PlanStep = 0; } void updateCarID(int firstID) { ID -= firstID; } void updateCrossID(int firstID) { StartPoint -= firstID; EndPoint -= firstID; } int getPresnetRoadID() { return presentPosition.roadID; } int getPresentRoadOri() { return presentPosition.orientation; } void displayPlan() { std::cout << "[CAR PLAN]" << '\t' << ID << '\n' << "Road_ID" << '\t' << "Orientation" << '\t' << "Next_Direction" << '\n'; for (int i = 0; i < Plan.size(); ++i) { std::cout << Plan[i].roadID + 501 << '\t' << Plan[i].orientation << '\t' << Plan[i].nextDirection << '\n'; } } }; class systemInfo { public: int Time; int TotalCarNum; int OnlineCarNum; int OfflineCarNum; int FinishedCarNum; int carNumInWaiting; std::vector<int> OnlineCarList; std::vector<int> OfflineCarList; std::vector<int> FinishedCarList; public: systemInfo() { Time = 0; OnlineCarNum = 0; FinishedCarNum = 0; carNumInWaiting = 0; } void inputCarVector(std::vector<int> caridvector) { OfflineCarList = caridvector; OfflineCarNum = OfflineCarList.size(); } int getOnlineCarNum() { return OnlineCarList.size(); } int getOfflineCarNum() { return OfflineCarList.size(); } int getFinishedCarNum() { return FinishedCarList.size(); } void finishOneCar(int carid) { OnlineCarNum--; FinishedCarNum++; FinishedCarList.push_back(carid); for (int i = 0; i < OnlineCarList.size(); ++i) { if (OnlineCarList[i] == carid) { OnlineCarList.erase(OnlineCarList.begin() + i); break; } } } void startOneCar(int carid) { OnlineCarNum++; OfflineCarNum--; OnlineCarList.push_back(carid); for (int i = 0; i < OfflineCarList.size(); ++i) { if (OfflineCarList[i] == carid) { OfflineCarList.erase(OfflineCarList.begin() + i); break; } } } void updateTime() { Time++; } int getTime() { return Time; } void displayCarList() { std::cout << '\n' << "Offline Car List:" << '\n'; for (int i = 0; i < OfflineCarList.size(); ++i) { std::cout << OfflineCarList[i] << '\t'; } std::cout << '\n' << "Online Car List:" << '\n'; for (int i = 0; i < OnlineCarList.size(); ++i) { std::cout << OnlineCarList[i] << '\t'; } std::cout << '\n' << "Finished Car List:" << '\n'; for (int i = 0; i < FinishedCarList.size(); ++i) { std::cout << FinishedCarList[i] << '\t'; } } }; #endif //CODECRAFT_2019_ELEMENT_H
b96ba54f8da5107ede422ecec8aa567cc25eb392
4eae27607916b0ffffd9ed7b8208fabe1b6ad64f
/Program 5/Main.cpp
a2bbee8dcca6e4a11ad6599f9aa00091776f0e88
[]
no_license
Drew-Childs/CS-201-Program-5
5fdb2ebaeb5a4c9084af785d5da6dc122e35f29d
5debe1c0e14cbdf7c82e91542d6b28b35181e3e6
refs/heads/master
2023-08-22T11:36:07.474099
2021-10-25T03:40:32
2021-10-25T03:40:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
71
cpp
//Drew Childs #include <iostream> using namespace std; int main() { }
8e1cd932bd2e73400432bab6110e61bf063cc60a
1d16fdcbd5fbd91d8325170cb74115a045cf24bb
/RealSpace2/Source/RSphere.cpp
eb48be06cafbcfeb74fddad5531f8bae8fecc81c
[]
no_license
kooksGame/life-marvelous
fc06a3c4e987dc5fbdb5275664e06f2934409b90
82b6dcb107346e980d5df31daf4bb14452e3450d
refs/heads/master
2021-01-10T08:32:53.353758
2013-07-28T18:15:09
2013-07-28T18:15:09
35,994,219
1
1
null
null
null
null
UTF-8
C++
false
false
1,378
cpp
#include "stdafx.h" #include "RSphere.h" #include "RealSpace2.h" using namespace RealSpace2; RSphere::RSphere(void) //:mCentre(0,0,0), mRadius(10), mSphere(0) { mCentre = rvector(0,0,0); mRadius = 10.f; mSphere = 0; } RSphere::~RSphere(void) { #ifdef _DEBUG SAFE_RELEASE( mSphere ); #endif } ////////////////////////////////////////////////////////////////////////// // isCollide ////////////////////////////////////////////////////////////////////////// bool RSphere::isCollide( CDInfo* data_, CDInfoType cdType_ ) { rvector distance = *data_->clothCD.v - mCentre; if( D3DXVec3LengthSq( &distance ) < ( mRadius * mRadius ) ) { *data_->clothCD.pos = mCentre + ( mRadius * *data_->clothCD.n); return true; } return false; } ////////////////////////////////////////////////////////////////////////// // draw ////////////////////////////////////////////////////////////////////////// void RSphere::draw() { #ifdef _DEBUG RGetDevice()->SetRenderState( D3DRS_FILLMODE, D3DFILL_WIREFRAME ); if(mSphere == 0) { D3DXCreateSphere( RGetDevice(), mRadius, 20, 20, &mSphere, NULL ); } RGetDevice()->SetRenderState( D3DRS_LIGHTING, FALSE ); RGetDevice()->SetTransform( D3DTS_WORLD, &mWorld ); mSphere->DrawSubset( 0 ); RGetDevice()->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); #endif }
[ "[email protected]@86145bcc-2932-641b-40bf-8db704073500" ]
[email protected]@86145bcc-2932-641b-40bf-8db704073500
cd71c841d2c2deff0d5432c46c7ca9956cda7913
6ff85b80c6fe1b3ad5416a304b93551a5e80de10
/Lua/ReadTableInC.cpp
a674bb0d991772659cb4305804aa4f31377e1a17
[ "MIT" ]
permissive
maniero/SOpt
c600cc2333e0a47ce013be3516bbb8080502ff2a
5d17e1a9cbf115eaea6d30af2079d0c92ffff7a3
refs/heads/master
2023-08-10T16:48:46.058739
2023-08-10T13:42:17
2023-08-10T13:42:17
78,631,930
1,002
136
MIT
2023-01-28T12:10:01
2017-01-11T11:19:24
C#
UTF-8
C++
false
false
1,123
cpp
#include <stdio.h> extern "C" { #include "lua/lua.h" #include "lua/lualib.h" #include "lua/lauxlib.h" } // In Lua 5.0 reference manual is a table traversal example at page 29. void PrintTable(lua_State *L) { lua_pushnil(L); while(lua_next(L, -2) != 0) { if(lua_isstring(L, -1)) printf("%s = %s\n", lua_tostring(L, -2), lua_tostring(L, -1)); else if(lua_isnumber(L, -1)) printf("%s = %d\n", lua_tostring(L, -2), lua_tonumber(L, -1)); else if(lua_istable(L, -1)) PrintTable(L); lua_pop(L, 1); } } void main() { lua_State *L = lua_open(); // Load file. if(luaL_loadfile(L, "seuCodigo.lua") || lua_pcall(L, 0, 0, 0)) { printf("Cannot run file\n"); return; } // Print table contents. lua_getglobal(L, "myTable"); PrintTable(L); // Print specific field. lua_getglobal(L, "myTable"); lua_pushstring(L, "one"); lua_gettable(L, -2); if(lua_isstring(L, -1)) printf("\myTable.one = %s\n", lua_tostring(L, -1)); lua_close(L); } //https://pt.stackoverflow.com/q/55230/101
adecdca79956368cb39e3e4e59f6bde361b7c44d
43a2fbc77f5cea2487c05c7679a30e15db9a3a50
/Cpp/Internal (Offsets Only)/SDK/BP_tattoo_01_Desc_classes.h
561ba5351380baa100c13dda45d32156ff850aa3
[]
no_license
zH4x/SoT-Insider-SDK
57e2e05ede34ca1fd90fc5904cf7a79f0259085c
6bff738a1b701c34656546e333b7e59c98c63ad7
refs/heads/main
2023-06-09T23:10:32.929216
2021-07-07T01:34:27
2021-07-07T01:34:27
383,638,719
0
0
null
null
null
null
UTF-8
C++
false
false
739
h
#pragma once // Name: SoT-Insider, Version: 1.102.2382.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_tattoo_01_Desc.BP_tattoo_01_Desc_C // 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0]) class UBP_tattoo_01_Desc_C : public UClothingDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_tattoo_01_Desc.BP_tattoo_01_Desc_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
e8868374412a425e907af9fcf80f485f73a3dd7e
86e4b39ab4314bb6a2b2d0a5849717cb68f5cc54
/Tree/Validate Binary Search Tree.cpp
61355be2c488f90b608232f176c817ae67d95665
[]
no_license
iamarjun45/leetcode
80360d5f3c9ae6dee8fe4dd2b6b3c27fb50aec5e
23fbefd337128201dc237c91634bd233ac92d86a
refs/heads/master
2023-01-07T09:00:37.012354
2020-11-08T18:29:23
2020-11-08T18:29:23
279,488,934
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
class Solution { bool isValidBST(TreeNode* root,long long left,long long right){ if(root==NULL) return true; if(root->val<left || root->val>right) return false; return isValidBST(root->left,left,(long long)root->val-1) && isValidBST(root->right,(long long)root->val+1,right); } public: bool isValidBST(TreeNode* root) { return isValidBST(root,LONG_MIN,LONG_MAX); } };
30d30bc75299cac6a4d950222a9d4e1dc68ffae9
ec68c973b7cd3821dd70ed6787497a0f808e18e1
/Cpp/SDK/Resource_Snow_GlacialScepter_classes.h
a5f69c97f801d8de85d1470943ea3fd4e1df582f
[]
no_license
Hengle/zRemnant-SDK
05be5801567a8cf67e8b03c50010f590d4e2599d
be2d99fb54f44a09ca52abc5f898e665964a24cb
refs/heads/main
2023-07-16T04:44:43.113226
2021-08-27T14:26:40
2021-08-27T14:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
746
h
#pragma once // Name: Remnant, Version: 1.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Resource_Snow_GlacialScepter.Resource_Snow_GlacialScepter_C // 0x0000 class AResource_Snow_GlacialScepter_C : public AItem_Material_Base_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Resource_Snow_GlacialScepter.Resource_Snow_GlacialScepter_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
ef015f93c31d9a84d8fc9fbaaa284bb80bb05268
51bab3f46f32652fb75926fb0eacfbb39793d8a8
/models/iris/interfaces/topology.h
ab8b4589c6133a0e604e34e83fa22e3cc6de160e
[]
no_license
iris-casl/iris_v2
4b95a8c66a23a89ac23037c1468d628dd3e5021d
d83056afe2862b3ccfcbd758c8a8714c7665506c
refs/heads/master
2020-05-16T22:30:59.891630
2011-03-22T17:43:21
2011-03-22T17:43:21
1,512,105
0
0
null
null
null
null
UTF-8
C++
false
false
1,563
h
/* * ===================================================================================== * *! \brief Filename: topology.h * * Description: This class describes the abstract base class for a generic topology * * Version: 1.0 * Created: 07/19/2010 10:01:20 AM * Revision: none * Compiler: gcc * * Author: Sharda Murthi, [email protected] * Company: Georgia Institute of Technology * * ===================================================================================== */ #ifndef TOPOLOGY_H_ #define TOPOLOGY_H_ #include "genericHeader.h" #include "irisTerminal.h" #include "irisInterface.h" #include "irisRouter.h" class Topology { public: virtual void parse_config(std::map<std::string,std::string>& p) = 0; virtual void connect_interface_terminal(void) = 0; virtual void connect_interface_routers(void) = 0; virtual void connect_routers(void) = 0; virtual void set_router_outports( uint router_no ) = 0; virtual void assign_node_ids ( component_type t) = 0; virtual std::string print_stats(component_type t) = 0; std::vector <IrisRouter*> routers; std::vector <IrisInterface*> interfaces; std::vector <IrisTerminal*> terminals; std::vector <manifold::kernel::CompId_t> router_ids; std::vector <manifold::kernel::CompId_t> interface_ids; std::vector <manifold::kernel::CompId_t> terminal_ids; }; #endif /* TOPOLOGY_H_ */
d0e3d74c83583b0d4e8d7fe1a04d904617c3df03
e783a3a15556eff92dd48302658a860d554c951c
/CPE Clock hands/CPE作業Clock hands/1031430.cpp
345848eebd325c5f2a1e3522616c6323bca5b3b3
[]
no_license
w5151381guy/CPE-code
e2f10d7258e344cea4019d21961cf52061b69516
4852ab5680ac8fad22472ac6fb0326e02ad8175f
refs/heads/master
2020-04-13T22:36:57.531326
2015-10-05T11:47:10
2015-10-05T11:47:10
null
0
0
null
null
null
null
BIG5
C++
false
false
624
cpp
#include<iostream> #include<iomanip> #include<cmath> using namespace std; int main() { int H,M; //H代表時針,M代表分針 char semicolon; //semicolon為分號 cout<<"Please enter the clockhands:"; while(cin>>H>>semicolon>>M) { if(H==0 && M==0) { break; } double H_angle=static_cast<double>(H)*30 + static_cast<double>(M)/60; double M_angle=static_cast<double>(M)*6; double angle=abs(H_angle-M_angle); if(angle > 180) { angle=abs(360-angle); } cout<<fixed<<setprecision(2)<<"The angle is: "<<angle<<endl; cout<<"Please enter the clockhands:"; } system("pause"); return 0; }
7e800a2017d3805c28fa038d04e4c0a150c5c3f8
88ada0a7ffe8849c7a7222f8524cc3dfa9eacee7
/insertionsort1.cpp
1ce575d4e8899b78b38be19e40b7683195e2c9a8
[]
no_license
shklqm/Hackerrank
89aefc57ae44efcd4b0606bbb96820700f18c1e0
36d316644e44bd892ec63c79d6247e8d6911049f
refs/heads/master
2021-05-31T02:19:43.261003
2016-03-10T18:25:01
2016-03-10T18:25:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
937
cpp
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; void insertionSort(vector <int> ar) { int i; for(i=ar.size()-1; i>0; i--) if(ar[i] < ar[i-1]) break; int elem = ar[i]; bool flag = false; for(i; i>0; i-- ) { if( elem < ar[i-1] ) ar[i] = ar[i-1]; else break; for(int j=0; j<ar.size(); j++) cout<<ar[j]<<" "; cout<<endl; } ar[i] = elem; for(int j=0; j<ar.size(); j++) cout<<ar[j]<<" "; cout<<endl; } int main(void) { vector <int> _ar; int _ar_size; cin >> _ar_size; for(int _ar_i=0; _ar_i<_ar_size; _ar_i++) { int _ar_tmp; cin >> _ar_tmp; _ar.push_back(_ar_tmp); } insertionSort(_ar); return 0; }
611181ba3a62dc8d815556648c5064c3138cd2a3
157c4426121dcd81c5e1e67a0f51aa5cfe4f76a4
/CS162/Final/Creature.cpp
c8a5b6d5998d7675963432ddf382a41ffdcb8e38
[]
no_license
bkooma/OSU_BSCS
ea99040ce325a52a9ffd71a05d8a1169d04b370d
b29734abc0d4ee438c83018ded3f324ba54f3bca
refs/heads/master
2021-01-01T18:58:54.061691
2017-08-24T22:46:19
2017-08-24T22:46:19
97,426,950
0
0
null
null
null
null
UTF-8
C++
false
false
7,750
cpp
/************************************************************************************* ** Creature.cpp is the Creature base class function implementation file. ** Author: Byron Kooima ** Date: 2017/08/06 ** Description: CS162 Week6 Project3 ** The Creature class represents a Creature Base Class for the combatGame. This class is ** an abstract class for all of the Creature subclasses. ***************************************************************************************/ #include "Creature.hpp" #include <ctime> #include "userMenu.hpp" /********************************************************************* ** Function: Creature::Creature ** Description: Default constructor for Creature. Sets all protected ** members to default values. ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Creature members set to default. *********************************************************************/ Creature::Creature(int strngth, int arm) { this->strength = strngth; this->armor = arm; defPoints = 0; name = ""; creatureInfo = ""; specialAttack = ""; dieNumAttack = 0; dieSidesAttack = 0; dieNumDefense = 0; dieSidesDefense = 0; uBelt = new UtilityBelt(); // Set seed for random function std::srand(static_cast<unsigned int>(time(0))); } // Getters /********************************************************************* ** Function: Creature::get_name() ** Description: Getter for returning the Creature name ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Returns a string of the Creature name. *********************************************************************/ std::string Creature::get_name() { return name; } /********************************************************************* ** Function: Creature::get_creatureInfo() ** Description: Getter for returning the Creature information ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Returns a string of the Creature information. *********************************************************************/ std::string Creature::get_creatureInfo() { return creatureInfo; } /********************************************************************* ** Function: Creature::get_strength() ** Description: Getter for returning the Creature strength ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Returns an int of the Creature strength. *********************************************************************/ int Creature::get_strength() { return strength; } /********************************************************************* ** Function: Creature::get_armor() ** Description: Getter for returning the Creature armor ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Returns an int of the Creature armor. *********************************************************************/ int Creature::get_armor() { return armor; } /********************************************************************* ** Function: Creature::get_points() ** Description: Getter for returning the Creature points ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Returns an int of the Creature points. *********************************************************************/ int Creature::get_defPoints() { return defPoints; } /********************************************************************* ** Function: Creature::get_special() ** Description: Getter for returning the Creature's special attack ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Returns a string of the Creature's special attack. *********************************************************************/ std::string Creature::get_special() { return specialAttack; } /********************************************************************* ** Function: Creature::defense(int) ** Description: Standard function for all creatures to determine the ** damage inflicted during a round ** Parameters: attack The value of the attack die roll ** Pre-Conditions: N/A ** Post-Conditions: Returns an int for the damage inflicted after ** calculating the offense roll minus the defense ** roll and armor. Will return 0 if the damage is ** less than 0 *********************************************************************/ int Creature::defense() { this->specialAttack = ""; // Call the die_roll function for defense die defPoints = die_roll(this->dieNumDefense, this->dieSidesDefense); return defPoints; } /********************************************************************* ** Function: Creature::attack() ** Description: Attack roll of the dice for the Creature. Passes the ** attack die to the die_roll function to get the attack ** value. ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Returns an int from the die_roll function. *********************************************************************/ int Creature::attack() { // Reset the special attack to nothing this->specialAttack = ""; // Call the die_roll function for attack die return die_roll(this->dieNumAttack, this->dieSidesAttack); } int Creature::pain(int attack, int defense) { // Calculation for subtracting the defending creatures total defense // from the attack roll int total_pain = attack - (defense + armor); if (total_pain > 0) { // If damage is greater than 0, subtract the damage from the strength strength = strength - total_pain; return total_pain; } // If damage is negative, return 0 return 0; } void Creature::add_inventory(std::string iName, std::string uName, int qInput, bool special) { uBelt->addItems(iName, uName, qInput, special); } void Creature::remove_inventory() { uBelt->removeItems(); } void Creature::transfer_qty(std::string iName, Creature* batman) { Item tempItem; if (search_items(iName)) { tempItem = uBelt->returnItem(iName); std::cout << "You received: " << tempItem.get_itemName() << std::endl; batman->add_inventory(tempItem.get_itemName(), tempItem.get_itemDesc(), 1, tempItem.get_special()); uBelt->removeQty(iName); } } void Creature::get_itemName() { uBelt->printItems(); } bool Creature::search_items(std::string iName) { return uBelt->searchItems(iName); } /********************************************************************* ** Function: Creature::die_roll(int, int) ** Description: Standard function for all creatures to roll the die ** for either offense or defense ** Parameters: dieNum The number of die for the roll ** dieSides The number of sides for the die ** Pre-Conditions: N/A ** Post-Conditions: Returns an int for the offensive or defensive roll ** of the dice. *********************************************************************/ int Creature::die_roll(int dieNum, int dieSides) { int dieSum = 0; // Step through a loop for the number of dice for (int i = 0; i < dieNum; i++) { // Randomly generate a number based on the dice sides // and add it to the sum dieSum = dieSum + rand() % dieSides + 1; } return dieSum; } /********************************************************************* ** Function: Creature::defeated() ** Description: Standard function for all creatures to determine if ** the Creature has been defeated ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: Returns a boolean value based on the strength left ** for the creature *********************************************************************/ bool Creature::defeated() { return strength <=0; } /********************************************************************* ** Function: Creature::~Creature() ** Description: Creature Destructor ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: N/A *********************************************************************/ Creature::~Creature() { delete uBelt; }
3d312588892dcaec4d8af9ab203b2ce82472079a
667a45fdd3be14b2048dcdb47ad46d6fa07a4a90
/include/fst.hpp
3798b1f97b9845139ae1fd43249e3932993e2cc7
[]
no_license
charlesmcclendon/stann-for-python
395fa7e4777de765b6fb921d6341cfb4b9129820
bec41d66ce75a12cf696d018f640905fc50ad00d
refs/heads/master
2021-01-11T04:15:56.088179
2016-12-08T03:37:28
2016-12-08T03:37:28
71,195,380
1
0
null
null
null
null
UTF-8
C++
false
false
4,955
hpp
/*****************************************************************************/ /* */ /* Header: fst.hpp */ /* */ /* Accompanies STANN Version 0.74 */ /* Nov 15, 2010 */ /* */ /* Copyright 2007, 2008 */ /* Michael Connor and Piyush Kumar */ /* Florida State University */ /* Tallahassee FL, 32306-4532 */ /* */ /*****************************************************************************/ #ifndef __STANN_FAIR_SPLT_TREE__ #define __STANN_FAIR_SPLT_TREE__ #include<limits> #include<vector> #include<iostream> template<typename Point> class dim_sort_pred { public: int dim; dim_sort_pred(int D) { dim=D; } bool operator()(const Point &a, const Point &b) { return a[dim]< b[dim]; } }; template<typename Point> class fst_node { typedef typename std::vector<fst_node<Point> >::size_type size_type; typedef typename std::vector<Point>::iterator PItr; public: Point lc; //Lower corner of the bounding box Point uc; //Upper corner of the bounding box PItr first; //Smallest point, according to the splitting dimenstion PItr last; //1 past the last point, according to splitting dimension PItr cut; //Point at which the node is split double radius; //Radius of bounding box. Equal to 1/2 the squared corner to corner distance fst_node<Point>* left; //left child of the node in the FST fst_node<Point>* right; //right child of the node in the FST int size; double node_distance(const fst_node<Point> *b) { double dist=0; for(unsigned int j=0;j < Point::__DIM;++j) { if(uc[j] < b->lc[j]) dist += (b->lc[j]-uc[j])*(b->lc[j]-uc[j]); else if(b->uc[j] < lc[j]) dist += (lc[j]-b->uc[j])*(lc[j]-b->uc[j]); } return dist; } }; template<typename Point> class fair_split_tree { typedef typename std::vector<fst_node<Point> >::size_type size_type; typedef typename std::vector<Point>::iterator PItr; public: fst_node<Point> root; int DIM; fair_split_tree(std::vector<Point> &points) { DIM = Point::__DIM; build_tree(points.begin(), points.end(), &root); } void build_tree(PItr begin, PItr end, fst_node<Point> *node) { node->first=begin; node->last=end; node->size = (int) (end-begin); if(node->size==0) { std::cout << "Error, no size!" << std::endl; return; } //if we're in an internal node if(node->size > 1) { int spread_dim; //Find the max and min coordinates PItr I = begin; for(int i=0;i < DIM;++i) { node->lc[i] = (*I)[i]; node->uc[i] = (*I)[i]; } I++; for(;I != end;++I) { for(int i=0;i < DIM;++i) { if(node->lc[i] > (*I)[i]) node->lc[i] = (*I)[i]; if(node->uc[i] < (*I)[i]) node->uc[i] = (*I)[i]; } } //Calculate the radius of the node node->radius=0; for(int i=0;i < DIM;++i) { node->radius= node->lc.sqr_dist(node->uc); } node->radius = node->radius*0.5; //std::cout << "LC: " << node->lc << std::endl; //std::cout << "UC: " << node->uc << std::endl; //std::cout << node->radius << std::endl; //exit(0); //Determine the dimension of greatest spread double spread; spread = node->uc[0]-node->lc[0]; spread_dim=0; for(int i=1;i < DIM;++i) { if((node->uc[i]-node->lc[i])> spread) { spread = node->uc[i]-node->lc[i]; spread_dim=i; } } //sort the points in the dimension of greatest spread dim_sort_pred<Point> lt(spread_dim); sort(begin, end, lt); //determine the cut spread=(spread*0.5)+(node->lc[spread_dim]); if(node->size == 2) { node->cut = begin+1; } else { node->cut = begin+(node->size/2); if((*node->cut)[spread_dim] < spread) while((*node->cut)[spread_dim] < spread) ++node->cut; else { while((*node->cut)[spread_dim] > spread) --node->cut; ++node->cut; } } //if(node->cut == end) std::cout << "Error, cut=end" << std::endl; //if(node->cut == begin) std::cout << "Error, cut=begin" << std::endl; //Recurse node->left = new fst_node<Point>; node->right = new fst_node<Point>; build_tree(begin, node->cut, node->left); build_tree(node->cut, end, node->right); } //Otherwise, we're in a leaf else { node->radius=0; node->uc = (*begin); node->lc = (*begin); node->left = NULL; node->right=NULL; } } }; #endif
b23967fb15e29ee0dc65097828645f609e511c4a
b2f4b72771122c015d76b9b81bce5d16d99cf78d
/main.h
c55af0f7cd925f39351181a4199cbf14b47b40c3
[]
no_license
watanany/20200716--LaserRecognizer
4eaa6e7b5fbcca1bb8e5dcac53aba15b62972e2b
1722352a8e4be45897a8289363d1640e49a9c3b7
refs/heads/master
2021-05-30T17:06:32.498454
2016-02-20T15:36:00
2016-02-20T15:36:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
721
h
#pragma once #include <iostream> #include <cstring> #include <opencv/cv.h> #include <opencv/highgui.h> #include <string> #include <vector> #include <map> #include "preprocess/preprocess.h" #include "recognition/recognition.h" #define REFDIR0 "Graffiti/number" #define REFDIR1 "Graffiti/alphabet" #define REFDIR2 "Graffiti/specialkey" #define REFDIR REFDIR0 #define STEP 15 #define K_ESC 27 #define K_SPACE 32 #define THRESHOLD_G 128 #define POINT_LIMIT 10000 #if 0 inline void Sleepy(unsigned int mill_seconds) { #if __linux__ struct timespec t; t.tv_sec = mill_seconds / 1000; t.tv_nsec = (mill_seconds % 1000) * 1000; nanosleep(&t, NULL); #elif defined _WIN32 Sleep(mill_seconds); #endif } #endif
4c21691bb66e76ee2026a469c86d0e9c6ad3d971
714d4d2796e9b5771a1850a62c9ef818239f5e77
/content/browser/compositor/reflector_impl_unittest.cc
228a596151fd2f620cb354ab04e9c347717ffbc4
[ "BSD-3-Clause" ]
permissive
CapOM/ChromiumGStreamerBackend
6c772341f815d62d4b3c4802df3920ffa815d52a
1dde005bd5d807839b5d45271e9f2699df5c54c9
refs/heads/master
2020-12-28T19:34:06.165451
2015-10-21T15:42:34
2015-10-23T11:00:45
45,056,006
2
0
null
2015-10-27T16:58:16
2015-10-27T16:58:16
null
UTF-8
C++
false
false
7,973
cc
// 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. #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "cc/test/fake_output_surface_client.h" #include "cc/test/test_context_provider.h" #include "cc/test/test_web_graphics_context_3d.h" #include "content/browser/compositor/browser_compositor_output_surface.h" #include "content/browser/compositor/browser_compositor_overlay_candidate_validator.h" #include "content/browser/compositor/reflector_impl.h" #include "content/browser/compositor/reflector_texture.h" #include "content/browser/compositor/test/no_transport_image_transport_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" #include "ui/compositor/test/context_factories_for_test.h" #if defined(USE_OZONE) #include "content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.h" #include "ui/ozone/public/overlay_candidates_ozone.h" #endif // defined(USE_OZONE) namespace content { namespace { class FakeTaskRunner : public base::SingleThreadTaskRunner { public: FakeTaskRunner() {} bool PostNonNestableDelayedTask(const tracked_objects::Location& from_here, const base::Closure& task, base::TimeDelta delay) override { return true; } bool PostDelayedTask(const tracked_objects::Location& from_here, const base::Closure& task, base::TimeDelta delay) override { return true; } bool RunsTasksOnCurrentThread() const override { return true; } protected: ~FakeTaskRunner() override {} }; #if defined(USE_OZONE) class TestOverlayCandidatesOzone : public ui::OverlayCandidatesOzone { public: TestOverlayCandidatesOzone() {} ~TestOverlayCandidatesOzone() override {} void CheckOverlaySupport(OverlaySurfaceCandidateList* surfaces) override { (*surfaces)[0].overlay_handled = true; } }; #endif // defined(USE_OZONE) scoped_ptr<BrowserCompositorOverlayCandidateValidator> CreateTestValidatorOzone() { #if defined(USE_OZONE) return scoped_ptr<BrowserCompositorOverlayCandidateValidator>( new BrowserCompositorOverlayCandidateValidatorOzone( 0, scoped_ptr<ui::OverlayCandidatesOzone>( new TestOverlayCandidatesOzone()))); #else return nullptr; #endif // defined(USE_OZONE) } class TestOutputSurface : public BrowserCompositorOutputSurface { public: TestOutputSurface( const scoped_refptr<cc::ContextProvider>& context_provider, const scoped_refptr<ui::CompositorVSyncManager>& vsync_manager) : BrowserCompositorOutputSurface(context_provider, nullptr, vsync_manager, CreateTestValidatorOzone().Pass()) { surface_size_ = gfx::Size(256, 256); device_scale_factor_ = 1.f; } void SetFlip(bool flip) { capabilities_.flipped_output_surface = flip; } void SwapBuffers(cc::CompositorFrame* frame) override {} void OnReflectorChanged() override { if (!reflector_) { reflector_texture_.reset(); } else { reflector_texture_.reset(new ReflectorTexture(context_provider())); reflector_->OnSourceTextureMailboxUpdated(reflector_texture_->mailbox()); } } #if defined(OS_MACOSX) void OnSurfaceDisplayed() override {} void SetSurfaceSuspendedForRecycle(bool suspended) override {} bool SurfaceShouldNotShowFramesAfterSuspendForRecycle() const override { return false; } #endif private: scoped_ptr<ReflectorTexture> reflector_texture_; }; const gfx::Rect kSubRect(0, 0, 64, 64); } // namespace class ReflectorImplTest : public testing::Test { public: void SetUp() override { bool enable_pixel_output = false; ui::ContextFactory* context_factory = ui::InitializeContextFactoryForTests(enable_pixel_output); ImageTransportFactory::InitializeForUnitTests( scoped_ptr<ImageTransportFactory>( new NoTransportImageTransportFactory)); message_loop_.reset(new base::MessageLoop()); task_runner_ = message_loop_->task_runner(); compositor_task_runner_ = new FakeTaskRunner(); compositor_.reset( new ui::Compositor(context_factory, compositor_task_runner_.get())); compositor_->SetAcceleratedWidgetAndStartCompositor( gfx::kNullAcceleratedWidget); context_provider_ = cc::TestContextProvider::Create( cc::TestWebGraphicsContext3D::Create().Pass()); output_surface_ = scoped_ptr<TestOutputSurface>( new TestOutputSurface(context_provider_, compositor_->vsync_manager())).Pass(); CHECK(output_surface_->BindToClient(&output_surface_client_)); root_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR)); compositor_->SetRootLayer(root_layer_.get()); mirroring_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR)); compositor_->root_layer()->Add(mirroring_layer_.get()); gfx::Size size = output_surface_->SurfaceSize(); mirroring_layer_->SetBounds(gfx::Rect(size.width(), size.height())); } void SetUpReflector() { reflector_ = make_scoped_ptr( new ReflectorImpl(compositor_.get(), mirroring_layer_.get())); reflector_->OnSourceSurfaceReady(output_surface_.get()); } void TearDown() override { if (reflector_) reflector_->RemoveMirroringLayer(mirroring_layer_.get()); cc::TextureMailbox mailbox; scoped_ptr<cc::SingleReleaseCallback> release; if (mirroring_layer_->PrepareTextureMailbox(&mailbox, &release, false)) { release->Run(0, false); } compositor_.reset(); ui::TerminateContextFactoryForTests(); ImageTransportFactory::Terminate(); } void UpdateTexture() { reflector_->OnSourcePostSubBuffer(kSubRect); } protected: scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner_; scoped_refptr<cc::ContextProvider> context_provider_; cc::FakeOutputSurfaceClient output_surface_client_; scoped_ptr<base::MessageLoop> message_loop_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; scoped_ptr<ui::Compositor> compositor_; scoped_ptr<ui::Layer> root_layer_; scoped_ptr<ui::Layer> mirroring_layer_; scoped_ptr<ReflectorImpl> reflector_; scoped_ptr<TestOutputSurface> output_surface_; }; namespace { TEST_F(ReflectorImplTest, CheckNormalOutputSurface) { output_surface_->SetFlip(false); SetUpReflector(); UpdateTexture(); EXPECT_TRUE(mirroring_layer_->TextureFlipped()); gfx::Rect expected_rect = kSubRect + gfx::Vector2d(0, output_surface_->SurfaceSize().height()) - gfx::Vector2d(0, kSubRect.height()); EXPECT_EQ(expected_rect, mirroring_layer_->damaged_region()); } TEST_F(ReflectorImplTest, CheckInvertedOutputSurface) { output_surface_->SetFlip(true); SetUpReflector(); UpdateTexture(); EXPECT_FALSE(mirroring_layer_->TextureFlipped()); EXPECT_EQ(kSubRect, mirroring_layer_->damaged_region()); } #if defined(USE_OZONE) TEST_F(ReflectorImplTest, CheckOverlayNoReflector) { cc::OverlayCandidateList list; cc::OverlayCandidate plane_1, plane_2; plane_1.plane_z_order = 0; plane_2.plane_z_order = 1; list.push_back(plane_1); list.push_back(plane_2); output_surface_->GetOverlayCandidateValidator()->CheckOverlaySupport(&list); EXPECT_TRUE(list[0].overlay_handled); } TEST_F(ReflectorImplTest, CheckOverlaySWMirroring) { SetUpReflector(); cc::OverlayCandidateList list; cc::OverlayCandidate plane_1, plane_2; plane_1.plane_z_order = 0; plane_2.plane_z_order = 1; list.push_back(plane_1); list.push_back(plane_2); output_surface_->GetOverlayCandidateValidator()->CheckOverlaySupport(&list); EXPECT_FALSE(list[0].overlay_handled); } #endif // defined(USE_OZONE) } // namespace } // namespace content
dc9abfd4bdce0e317c5754007e1b65e0dd59d228
629cc70db98140102a1662126a9b1c608ed86c3e
/7785.cpp
4a4dca110068822afe604337cee8d44d9eaef5b0
[]
no_license
woojoung/Algorithm
0b1e52d519febaad04239c4410c2a47bd8eee7f8
97444894dd4a5bef6b3de3c34c0bf536ef2c0191
refs/heads/master
2020-04-02T16:40:05.581945
2018-06-29T04:47:32
2018-06-29T04:47:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,158
cpp
#include <iostream> #include <string> #include <map> using namespace std; /* 백준 알고리즘 7785번 문제 풀이 작성자 ESENS 작성일 170129 1. 첫째 줄에 로그에 기록된 출입 기록의 수 n이 주어진다(양의 정수) 2. 다음 n개의 줄에는 출입기록이 순서대로 주어진다. 3. 출력은 이름을 사전 순의 역순으로 한줄에 한명씩. 4. 입력 조건에서 '순서대로' 라는 조건에 입장 순서인지 사전 순서인지에 대한 명시가 없으므로 사전 순서로 임의하여 간단하게 입력을 사전순으로 하여서 출력시 사전의 역순으로 출력하였다. */ int main() { string name, state; int number; map<string, int, greater<string> > mMap; map<string, int, greater<string> >::iterator iter; //입출력 기록의 size 입력 cin >> number; for (int i = 0; i < number; i++){ cin >> name >> state; //index의 값이 enter일때만 data를 1로 if (state == "enter"){ mMap[name] = 1; }else{ mMap[name] = 0; } } for ( iter = mMap.begin(); iter != mMap.end(); ++iter){ if (iter->second == 1) cout << iter->first << endl; } return 0; }
2c27917dcfbf74c72d31ee85d5aa059dec0c6f55
6eaab6b260d2b750c074d7b569ff19c930a3059f
/c++learning/user.cpp
0bbc5e851bb049569ae398c39669fde1d9ac8047
[]
no_license
kapuni/box
9b95505b2f00d7ad00e20cfe540d883dcbbb27b1
6187368e2bbcba2148c48b82a4979dae3cc9756a
refs/heads/master
2023-05-05T01:21:08.092428
2021-05-10T14:36:39
2021-05-10T14:36:39
164,998,826
1
0
null
null
null
null
UTF-8
C++
false
false
277
cpp
#include <iostream> #include <cmath> using namespace std; int main() { //int age; string name; cout << "Enter your name: "; //cin >> age; getline(cin, name); //cout << "You are " << age << " years old"; cout << "Hello " << name; return 0; }
2712618daf761f449450ea478e9433c821e32a8f
02be0e2d1592613c6546179c4915c3d5abc149c1
/Boost_Echo_Client/include/user.h
7731c171e14e9a4a68a72cc6cb1bd161b957e3d2
[]
no_license
MahajnaM/library---server-client
5926813e0083cf9b99aebbc298b0d704202c9455
c60a394f341dfb3f559c4603e69a0704466397dd
refs/heads/main
2023-08-31T04:33:16.448033
2021-10-28T18:17:08
2021-10-28T18:17:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
543
h
// // Created by [email protected] on 15/01/2020. // #ifndef UNTITLED2_USER_H #define UNTITLED2_USER_H #include <string> #include <vector> #include <map> #include "../include/Book.h" using namespace std; class user { private: map<string, vector<Book>> _allmyBooks; const string _userName; size_t _receipt_Id; public: user(string userName); const string &getUserName(); map<string, vector<Book >> &getUserBooks(); void addToUserBooks(string genre, string bookName); }; #endif //UNTITLED2_USER_H
191c7c9d1cfedcd5f67dcdac3a30e64086be505e
ad79dc448d048912a3d39bb77293600d80727001
/esp-idf/components/nvs_flash/src/nvs_api.cpp
e2256e4badbd2dd5bbb1bbfc84ecfd0e9a321c1c
[ "Apache-2.0" ]
permissive
ghsecuritylab/micropython_esp32_local
d94e1c12b37d0523f7d3158f7f77af275c581502
54234d75b0737ceb28c1ad9a421576a974571740
refs/heads/master
2021-02-26T13:17:55.948635
2018-01-24T06:36:41
2018-01-24T06:36:41
245,527,954
0
0
null
2020-03-06T22:27:58
2020-03-06T22:27:57
null
UTF-8
C++
false
false
9,946
cpp
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "nvs.hpp" #include "nvs_flash.h" #include "nvs_storage.hpp" #include "intrusive_list.h" #include "nvs_platform.hpp" #include "esp_partition.h" #include "sdkconfig.h" #ifdef ESP_PLATFORM // Uncomment this line to force output from this module // #define LOG_LOCAL_LEVEL ESP_LOG_DEBUG #include "esp_log.h" static const char* TAG = "nvs"; #else #define ESP_LOGD(...) #endif class HandleEntry : public intrusive_list_node<HandleEntry> { public: HandleEntry() {} HandleEntry(nvs_handle handle, bool readOnly, uint8_t nsIndex) : mHandle(handle), mReadOnly(readOnly), mNsIndex(nsIndex) { } nvs_handle mHandle; uint8_t mReadOnly; uint8_t mNsIndex; }; #ifdef ESP_PLATFORM SemaphoreHandle_t nvs::Lock::mSemaphore = NULL; #endif using namespace std; using namespace nvs; static intrusive_list<HandleEntry> s_nvs_handles; static uint32_t s_nvs_next_handle = 1; static nvs::Storage s_nvs_storage; extern "C" void nvs_dump() { Lock lock; s_nvs_storage.debugDump(); } extern "C" esp_err_t nvs_flash_init_custom(uint32_t baseSector, uint32_t sectorCount) { ESP_LOGD(TAG, "nvs_flash_init_custom start=%d count=%d", baseSector, sectorCount); s_nvs_handles.clear(); return s_nvs_storage.init(baseSector, sectorCount); } #ifdef ESP_PLATFORM extern "C" esp_err_t nvs_flash_init(void) { Lock::init(); Lock lock; if (s_nvs_storage.isValid()) { return ESP_OK; } const esp_partition_t* partition = esp_partition_find_first( ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, NULL); if (partition == NULL) { return ESP_ERR_NOT_FOUND; } return nvs_flash_init_custom(partition->address / SPI_FLASH_SEC_SIZE, partition->size / SPI_FLASH_SEC_SIZE); } #endif static esp_err_t nvs_find_ns_handle(nvs_handle handle, HandleEntry& entry) { auto it = find_if(begin(s_nvs_handles), end(s_nvs_handles), [=](HandleEntry& e) -> bool { return e.mHandle == handle; }); if (it == end(s_nvs_handles)) { return ESP_ERR_NVS_INVALID_HANDLE; } entry = *it; return ESP_OK; } extern "C" esp_err_t nvs_open(const char* name, nvs_open_mode open_mode, nvs_handle *out_handle) { Lock lock; ESP_LOGD(TAG, "%s %s %d", __func__, name, open_mode); uint8_t nsIndex; esp_err_t err = s_nvs_storage.createOrOpenNamespace(name, open_mode == NVS_READWRITE, nsIndex); if (err != ESP_OK) { return err; } uint32_t handle = s_nvs_next_handle; ++s_nvs_next_handle; *out_handle = handle; s_nvs_handles.push_back(new HandleEntry(handle, open_mode==NVS_READONLY, nsIndex)); return ESP_OK; } extern "C" void nvs_close(nvs_handle handle) { Lock lock; ESP_LOGD(TAG, "%s %d", __func__, handle); auto it = find_if(begin(s_nvs_handles), end(s_nvs_handles), [=](HandleEntry& e) -> bool { return e.mHandle == handle; }); if (it == end(s_nvs_handles)) { return; } s_nvs_handles.erase(it); delete static_cast<HandleEntry*>(it); } extern "C" esp_err_t nvs_erase_key(nvs_handle handle, const char* key) { Lock lock; ESP_LOGD(TAG, "%s %s\r\n", __func__, key); HandleEntry entry; auto err = nvs_find_ns_handle(handle, entry); if (err != ESP_OK) { return err; } if (entry.mReadOnly) { return ESP_ERR_NVS_READ_ONLY; } return s_nvs_storage.eraseItem(entry.mNsIndex, key); } extern "C" esp_err_t nvs_erase_all(nvs_handle handle) { Lock lock; ESP_LOGD(TAG, "%s\r\n", __func__); HandleEntry entry; auto err = nvs_find_ns_handle(handle, entry); if (err != ESP_OK) { return err; } if (entry.mReadOnly) { return ESP_ERR_NVS_READ_ONLY; } return s_nvs_storage.eraseNamespace(entry.mNsIndex); } template<typename T> static esp_err_t nvs_set(nvs_handle handle, const char* key, T value) { Lock lock; ESP_LOGD(TAG, "%s %s %d %d", __func__, key, sizeof(T), (uint32_t) value); HandleEntry entry; auto err = nvs_find_ns_handle(handle, entry); if (err != ESP_OK) { return err; } if (entry.mReadOnly) { return ESP_ERR_NVS_READ_ONLY; } return s_nvs_storage.writeItem(entry.mNsIndex, key, value); } extern "C" esp_err_t nvs_set_i8 (nvs_handle handle, const char* key, int8_t value) { return nvs_set(handle, key, value); } extern "C" esp_err_t nvs_set_u8 (nvs_handle handle, const char* key, uint8_t value) { return nvs_set(handle, key, value); } extern "C" esp_err_t nvs_set_i16 (nvs_handle handle, const char* key, int16_t value) { return nvs_set(handle, key, value); } extern "C" esp_err_t nvs_set_u16 (nvs_handle handle, const char* key, uint16_t value) { return nvs_set(handle, key, value); } extern "C" esp_err_t nvs_set_i32 (nvs_handle handle, const char* key, int32_t value) { return nvs_set(handle, key, value); } extern "C" esp_err_t nvs_set_u32 (nvs_handle handle, const char* key, uint32_t value) { return nvs_set(handle, key, value); } extern "C" esp_err_t nvs_set_i64 (nvs_handle handle, const char* key, int64_t value) { return nvs_set(handle, key, value); } extern "C" esp_err_t nvs_set_u64 (nvs_handle handle, const char* key, uint64_t value) { return nvs_set(handle, key, value); } extern "C" esp_err_t nvs_commit(nvs_handle handle) { Lock lock; // no-op for now, to be used when intermediate cache is added HandleEntry entry; return nvs_find_ns_handle(handle, entry); } extern "C" esp_err_t nvs_set_str(nvs_handle handle, const char* key, const char* value) { Lock lock; ESP_LOGD(TAG, "%s %s %s", __func__, key, value); HandleEntry entry; auto err = nvs_find_ns_handle(handle, entry); if (err != ESP_OK) { return err; } return s_nvs_storage.writeItem(entry.mNsIndex, nvs::ItemType::SZ, key, value, strlen(value) + 1); } extern "C" esp_err_t nvs_set_blob(nvs_handle handle, const char* key, const void* value, size_t length) { Lock lock; ESP_LOGD(TAG, "%s %s %d", __func__, key, length); HandleEntry entry; auto err = nvs_find_ns_handle(handle, entry); if (err != ESP_OK) { return err; } return s_nvs_storage.writeItem(entry.mNsIndex, nvs::ItemType::BLOB, key, value, length); } template<typename T> static esp_err_t nvs_get(nvs_handle handle, const char* key, T* out_value) { Lock lock; ESP_LOGD(TAG, "%s %s %d", __func__, key, sizeof(T)); HandleEntry entry; auto err = nvs_find_ns_handle(handle, entry); if (err != ESP_OK) { return err; } return s_nvs_storage.readItem(entry.mNsIndex, key, *out_value); } extern "C" esp_err_t nvs_get_i8 (nvs_handle handle, const char* key, int8_t* out_value) { return nvs_get(handle, key, out_value); } extern "C" esp_err_t nvs_get_u8 (nvs_handle handle, const char* key, uint8_t* out_value) { return nvs_get(handle, key, out_value); } extern "C" esp_err_t nvs_get_i16 (nvs_handle handle, const char* key, int16_t* out_value) { return nvs_get(handle, key, out_value); } extern "C" esp_err_t nvs_get_u16 (nvs_handle handle, const char* key, uint16_t* out_value) { return nvs_get(handle, key, out_value); } extern "C" esp_err_t nvs_get_i32 (nvs_handle handle, const char* key, int32_t* out_value) { return nvs_get(handle, key, out_value); } extern "C" esp_err_t nvs_get_u32 (nvs_handle handle, const char* key, uint32_t* out_value) { return nvs_get(handle, key, out_value); } extern "C" esp_err_t nvs_get_i64 (nvs_handle handle, const char* key, int64_t* out_value) { return nvs_get(handle, key, out_value); } extern "C" esp_err_t nvs_get_u64 (nvs_handle handle, const char* key, uint64_t* out_value) { return nvs_get(handle, key, out_value); } static esp_err_t nvs_get_str_or_blob(nvs_handle handle, nvs::ItemType type, const char* key, void* out_value, size_t* length) { Lock lock; ESP_LOGD(TAG, "%s %s", __func__, key); HandleEntry entry; auto err = nvs_find_ns_handle(handle, entry); if (err != ESP_OK) { return err; } size_t dataSize; err = s_nvs_storage.getItemDataSize(entry.mNsIndex, type, key, dataSize); if (err != ESP_OK) { return err; } if (length == nullptr) { return ESP_ERR_NVS_INVALID_LENGTH; } else if (out_value == nullptr) { *length = dataSize; return ESP_OK; } else if (*length < dataSize) { *length = dataSize; return ESP_ERR_NVS_INVALID_LENGTH; } return s_nvs_storage.readItem(entry.mNsIndex, type, key, out_value, dataSize); } extern "C" esp_err_t nvs_get_str(nvs_handle handle, const char* key, char* out_value, size_t* length) { return nvs_get_str_or_blob(handle, nvs::ItemType::SZ, key, out_value, length); } extern "C" esp_err_t nvs_get_blob(nvs_handle handle, const char* key, void* out_value, size_t* length) { return nvs_get_str_or_blob(handle, nvs::ItemType::BLOB, key, out_value, length); }
8011807bf40c98b9d96b8bb0c25dd9351457ae20
d3cc576a8b58336203022429919b8c4fd96b555e
/medium/conwaysequence.cpp
555099df7f1ffb0852b0a5aa71f90ff0aa848f46
[]
no_license
comp0zr/Codingame-Solutions
1aafb202b6bca48d1c3626b4d1e38ffce2afe373
24e104586bb1302ea4ab5d2bebfcb412bced5f33
refs/heads/master
2021-01-20T06:51:59.780753
2018-08-18T09:02:30
2018-08-18T09:02:33
89,937,228
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> using namespace std; stringstream ss; vector<int> Conway(vector<int> vec) { vector<int> newVec; for(int i=0; i<vec.size(); ) { int count=0, num=vec[i]; if(i!=vec.size()-1 && vec[i] == vec[i+1]) { int j=i; while(j<vec.size() && vec[j]==num) { count++; j++; } i=j; newVec.push_back(count); newVec.push_back(num); continue; } else count=1; newVec.push_back(count); newVec.push_back(num); i++; } return newVec; } int main() { int R; cin >> R; cin.ignore(); int L; cin >> L; cin.ignore(); vector<int> vec(1), conway; vec[0] = R; if(L==1) { cout<<R<<endl; return 0; } while(--L) { conway.clear(); conway=Conway(vec); vec = conway; } for(int i=0; i<conway.size(); i++) { cout<<conway[i]; if(i==conway.size()-1) cout<<endl; else cout<<' '; } }
d6022f66ddefb954092773c1caa7c22978291148
db690169352e5c1ee0273b2489fd244a6897be0a
/TeamProject/Classes/Character/Character.cpp
3d8d9cfde434cb249790ca57c9b161c65520b662
[]
no_license
bacph178/RacerMouse
a08aabfdcd2fe25a95e1382964cc0a3ca7ca76cd
d308a436a872bd2a59d6488e2b1713d37a011af2
refs/heads/master
2020-12-30T23:34:15.655072
2014-03-14T08:53:14
2014-03-14T08:53:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,968
cpp
// // Character.cpp // TeamProject // // Created by macbook_006 on 1/6/14. // // #include "Character.h" Character::Character(){ } Character::~Character(){ this->spr->release(); } void Character::autoRun(RMTiledMap* tileMap){ } void Character::create(){ } void Character::addToMap(CCPoint location, CCLayer* layer, RMTiledMap *tiledMap){ this->position = location; this->spr->setPosition(tiledMap->convertPosMapToPoint(location)); layer->addChild(spr); } bool Character::checkLeft(RMTiledMap *tiledMap, CCPoint currenPos){ if(currenPos.x == 0 && currenPos.y == 13){ return true; } if(currenPos.x <= 0) return false; CCString *type = tiledMap->typeAtTileCoord(ccp(currenPos.x - 1 , currenPos.y)); if (type && (type->compare("1") == 0 || type->compare("2") == 0) && currenPos.x > 0) { return true; } else if(type == NULL){ return true; } else return false; } bool Character::checkRight(RMTiledMap *tiledMap, CCPoint currenPos){ if(currenPos.x >= WIDTH - 1 && currenPos.y == 13){ return true; } if(currenPos.x >= WIDTH - 1) return false; CCString *type = tiledMap->typeAtTileCoord(ccp(currenPos.x + 1 , currenPos.y)); if (type && (type->compare("1") == 0 || type->compare("2") == 0) && currenPos.x < WIDTH - 1) { return true; } else if(type == NULL){ return true; } else return false; } bool Character::checkBelow(RMTiledMap *tiledMap, CCPoint currenPos){ if(currenPos.y >= HEIGHT - 1) return false; CCString *type = tiledMap->typeAtTileCoord(ccp(currenPos.x, currenPos.y + 1)); if (type && (type->compare("1") == 0 || type->compare("2") == 0)) { return true; } else if(type == NULL){ return true; } else return false; } bool Character::checkUpward(RMTiledMap *tiledMap, CCPoint currenPos){ if(currenPos.y <= 0) return false; CCString *type = tiledMap->typeAtTileCoord(ccp(currenPos.x, currenPos.y - 1)); if (type && (type->compare("1") == 0 || type->compare("2") == 0)) { return true; } else if(type == NULL){ return true; } else return false; } void Character::moveLeft(RMTiledMap *tiledMap){ if(this->getPosition().x == 0 && this->getPosition().y == 13){ this->setPosAgian(ccp(WIDTH - 1, 13), (CCLayer*)this->getSprite()->getParent() , tiledMap); this->setRunCurrent(2); } else if(checkLeft(tiledMap, this->position)){ this->spr->runAction(CCMoveBy::create(this->getVelocity(), ccp(tiledMap->getTiledMap()->getTileSize().width * (-1), 0))); this->position = ccp(this->position.x - 1, this->position.y); this->setRunCurrent(2); } } void Character::moveRight(RMTiledMap *tiledMap){ if(this->getPosition().x == WIDTH - 1 && this->getPosition().y == 13){ this->setPosAgian(ccp(0, 13), (CCLayer*)this->getSprite()->getParent(), tiledMap); this->setRunCurrent(1); } else if(checkRight(tiledMap, this->position)){ this->spr->runAction(CCMoveBy::create(this->getVelocity(), ccp(tiledMap->getTiledMap()->getTileSize().width, 0))); this->position = ccp(this->position.x + 1, this->position.y); this->setRunCurrent(1); } } void Character::moveBelow(RMTiledMap *tiledMap){ if(checkBelow(tiledMap, this->position)){ this->spr->runAction(CCMoveBy::create(this->getVelocity(), ccp(0, tiledMap->getTiledMap()->getTileSize().width * (-1)))); this->position = ccp(this->position.x, this->position.y + 1); this->setRunCurrent(4); } } void Character::moveUpward(RMTiledMap *tiledMap){ if(checkUpward(tiledMap, this->position)){ this->spr->runAction(CCMoveBy::create(this->getVelocity(), ccp(0, tiledMap->getTiledMap()->getTileSize().width))); this->position = ccp(this->position.x, this->position.y - 1); this->setRunCurrent(3); } } void Character::setPosAgian(CCPoint location, CCLayer* layer, RMTiledMap *tiledMap){ this->position = location; this->spr->setPosition(tiledMap->convertPosMapToPoint(location)); } void Character::transformation(int idCharac){ CCAnimation *animation = CCAnimation::create(); for (int i = 1; i <= 6; i++) { std::string str = static_cast<ostringstream*>(&(ostringstream() << i))->str(); str = "Animation/Transformation/fx0" + str + ".png"; animation->addSpriteFrameWithFileName(str.c_str()); } animation->setDelayPerUnit(0.02); animation->setLoops(1); animation->setRestoreOriginalFrame(true); CCAnimate *action = CCAnimate::create(animation); this->getSprite()->runAction(CCSequence::create(action, CCDelayTime::create(0.08), CCCallFuncND::create(this,callfuncND_selector(Character::setSpriteWithIDCharac),(void*)(new int(idCharac))), CCDelayTime::create(TIME_TRANSFORM), CCCallFunc::create(this,callfunc_selector(Character::setDefaultTransform)), NULL)); } void Character::setSpriteWithIDCharac(CCNode* sender, void* idCharac){ int* idCharacter = (int*)idCharac; switch (*idCharacter) { case 1: this->spr->setTexture(CCSprite::create("blue.png")->getTexture()); break; case 2: this->spr->setTexture(CCSprite::create("blue.png")->getTexture()); break; case 3: this->spr->setTexture(CCSprite::create("Character/boot.png")->getTexture()); break; case 4: this->spr->setTexture(CCSprite::create("2.png")->getTexture()); break; default: this->spr->setTexture(CCSprite::create("2.png")->getTexture()); break; } this->setIDCharac(*idCharacter); } void Character::setDefaultTransform(){ CCAnimation *animation = CCAnimation::create(); for (int i = 1; i <= 6; i++) { std::string str = static_cast<ostringstream*>(&(ostringstream() << i))->str(); str = "Animation/Transformation/fx0" + str + ".png"; animation->addSpriteFrameWithFileName(str.c_str()); } animation->setDelayPerUnit(0.02); animation->setLoops(1); animation->setRestoreOriginalFrame(true); CCAnimate *action = CCAnimate::create(animation); this->getSprite()->runAction(CCSequence::create(action, CCDelayTime::create(0.08), CCCallFuncND::create(this,callfuncND_selector(Character::setSpriteWithIDCharac),(void*)(new int(defaultID))), NULL)); } void Character::setDefaultIDCharac(){ this->setIDCharac(defaultID); }
8b78ff4a72886cec483fb1b1cdd9698ccb72eb20
2944629bfdfc55c628289355b10df1556078ea2d
/version3/Source/256/f32v3_FMA_FMA4_c12x4.h
249b1e9b3a4e4b22e63ff01ae63739c03013a5a6
[ "BSD-3-Clause" ]
permissive
travisdowns/Flops
5eea7173434a0623d68ecb136982fd2ecc7cb6be
03727e4c679f96b4cddcc7c39c0302ccd6ccdefe
refs/heads/master
2020-04-19T20:45:13.850835
2019-01-30T22:38:33
2019-01-30T22:38:33
168,423,528
1
0
BSD-3-Clause
2019-01-30T22:11:52
2019-01-30T22:11:52
null
UTF-8
C++
false
false
5,304
h
/* f32v3_FMA_FMA4_c12x4.h * * Author : Alexander J. Yee * Date Created : 03/29/2017 * Last Modified : 03/29/2017 * */ #ifndef _flops_f32v3_FMA_FMA4_c12x4_H #define _flops_f32v3_FMA_FMA4_c12x4_H //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Dependencies #ifndef _WIN32 #include <x86intrin.h> #endif #include <immintrin.h> #include <ammintrin.h> #include "../Tools.h" #include "../Benchmark.h" #include "f32v3_Reduce_AVX.h" namespace Flops{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// class f32v3_FMA_FMA4_c12x4 : public Benchmark{ public: f32v3_FMA_FMA4_c12x4() : Benchmark(48 * 2 * 8) {} virtual double run_kernel(size_t iterations) const override{ const __m256 mul0 = _mm256_set1_ps(1.4142135623730950488f); const __m256 mul1 = _mm256_set1_ps(1.7320508075688772935f); __m256 r0 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r1 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r2 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r3 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r4 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r5 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r6 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r7 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r8 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 r9 = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 rA = _mm256_set1_ps((float)(rdtsc() % 256)); __m256 rB = _mm256_set1_ps((float)(rdtsc() % 256)); do{ r0 = _mm256_macc_ps(mul0, mul1, r0); r1 = _mm256_macc_ps(mul0, mul1, r1); r2 = _mm256_macc_ps(mul0, mul1, r2); r3 = _mm256_macc_ps(mul0, mul1, r3); r4 = _mm256_macc_ps(mul0, mul1, r4); r5 = _mm256_macc_ps(mul0, mul1, r5); r6 = _mm256_macc_ps(mul0, mul1, r6); r7 = _mm256_macc_ps(mul0, mul1, r7); r8 = _mm256_macc_ps(mul0, mul1, r8); r9 = _mm256_macc_ps(mul0, mul1, r9); rA = _mm256_macc_ps(mul0, mul1, rA); rB = _mm256_macc_ps(mul0, mul1, rB); r0 = _mm256_nmacc_ps(mul0, mul1, r0); r1 = _mm256_nmacc_ps(mul0, mul1, r1); r2 = _mm256_nmacc_ps(mul0, mul1, r2); r3 = _mm256_nmacc_ps(mul0, mul1, r3); r4 = _mm256_nmacc_ps(mul0, mul1, r4); r5 = _mm256_nmacc_ps(mul0, mul1, r5); r6 = _mm256_nmacc_ps(mul0, mul1, r6); r7 = _mm256_nmacc_ps(mul0, mul1, r7); r8 = _mm256_nmacc_ps(mul0, mul1, r8); r9 = _mm256_nmacc_ps(mul0, mul1, r9); rA = _mm256_nmacc_ps(mul0, mul1, rA); rB = _mm256_nmacc_ps(mul0, mul1, rB); r0 = _mm256_macc_ps(mul0, mul1, r0); r1 = _mm256_macc_ps(mul0, mul1, r1); r2 = _mm256_macc_ps(mul0, mul1, r2); r3 = _mm256_macc_ps(mul0, mul1, r3); r4 = _mm256_macc_ps(mul0, mul1, r4); r5 = _mm256_macc_ps(mul0, mul1, r5); r6 = _mm256_macc_ps(mul0, mul1, r6); r7 = _mm256_macc_ps(mul0, mul1, r7); r8 = _mm256_macc_ps(mul0, mul1, r8); r9 = _mm256_macc_ps(mul0, mul1, r9); rA = _mm256_macc_ps(mul0, mul1, rA); rB = _mm256_macc_ps(mul0, mul1, rB); r0 = _mm256_nmacc_ps(mul0, mul1, r0); r1 = _mm256_nmacc_ps(mul0, mul1, r1); r2 = _mm256_nmacc_ps(mul0, mul1, r2); r3 = _mm256_nmacc_ps(mul0, mul1, r3); r4 = _mm256_nmacc_ps(mul0, mul1, r4); r5 = _mm256_nmacc_ps(mul0, mul1, r5); r6 = _mm256_nmacc_ps(mul0, mul1, r6); r7 = _mm256_nmacc_ps(mul0, mul1, r7); r8 = _mm256_nmacc_ps(mul0, mul1, r8); r9 = _mm256_nmacc_ps(mul0, mul1, r9); rA = _mm256_nmacc_ps(mul0, mul1, rA); rB = _mm256_nmacc_ps(mul0, mul1, rB); }while (--iterations); r0 = _mm256_add_ps(r0, r6); r1 = _mm256_add_ps(r1, r7); r2 = _mm256_add_ps(r2, r8); r3 = _mm256_add_ps(r3, r9); r4 = _mm256_add_ps(r4, rA); r5 = _mm256_add_ps(r5, rB); r0 = _mm256_add_ps(r0, r3); r1 = _mm256_add_ps(r1, r4); r2 = _mm256_add_ps(r2, r5); r0 = _mm256_add_ps(r0, r1); r0 = _mm256_add_ps(r0, r2); return reduce(r0); } }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// } #endif
ce2d789e2117e8eb55636331ef739537175fdafc
7ffecaaf37bc71fd27b2341ed67e003254fa77ed
/ipc_ros_bridge_examples/src/ipc_send_geometry.cpp
ba61fbeeaca7f41f42ead3683a8b186400ff0de6
[ "MIT" ]
permissive
CMU-TBD/ipc_ros_bridge_pkgs
58f45faed7797086ebf65cfae713ebbf773cbe33
a663262ee348c32bd06c1aa941accf77c6531b35
refs/heads/master
2023-03-25T04:12:04.936180
2021-03-18T23:36:26
2021-03-18T23:36:26
256,625,214
0
0
null
null
null
null
UTF-8
C++
false
false
808
cpp
#include <iostream> #include <chrono> #include <thread> #include "ipc.h" #include "ipc_ros_bridge/structure/geometry_msgs_pose.h" #define TASKNAME "ROS_IPC_Demo" #define MSGNAME "pose" int main() { // connect to IPC Central // will fail if doesn't find it IPC_connect(TASKNAME); // define message IPC_defineMsg(MSGNAME, IPC_VARIABLE_LENGTH, GEOMETRY_MSGS_POSE_FORMAT); geometry_msgs_pose pose; pose.orientation.w = -0.861; pose.orientation.x = -0.001; pose.orientation.y = -0.482; pose.orientation.z = 0.161; pose.position.x = 0.3; pose.position.y = 0.2; pose.position.z = 0.1; while(true){ // send the message IPC_publishData(MSGNAME, &pose); // sleep std::this_thread::sleep_for(std::chrono::seconds(1)); } }
e117a799aac87ac801fcbed7b4f6a4503bf6e4a9
2576195ce1e0fffde521bb80b3e0de689dd86fa0
/newtutorial/QVariant/main.cpp
42b5686bb76d3eaf76672390fa60c1bb689989e7
[]
no_license
woaitubage/QT
48e62937c4cba349aaf84d1bafaef61b26862a07
90d711dda23dff79c16fd76767cb7039200d5257
refs/heads/master
2021-01-01T03:32:21.507798
2016-05-04T07:42:51
2016-05-04T07:42:51
56,436,428
0
0
null
null
null
null
UTF-8
C++
false
false
906
cpp
#include <QCoreApplication> #include <QFile> #include <QDataStream> #include <QDebug> #include <QStringList> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); /* qDebug()<<"Qwriting..."; QFile file("D:/QT/file.txt"); file.open(QIODevice::WriteOnly); QDataStream out(&file); QVariant v(123); int x=v.toInt(); out<<v; qDebug()<<v; v=QVariant("hello"); v=QVariant(tr("hello")); int y=v.toInt(); QString s=v.toString(); out<<v; qDebug()<<v; file.flush(); file.close(); qDebug()<<"Reading"; file.open(QIODevice::ReadOnly); QDataStream in(&file); in>>v; int z=v.toInt(); qDebug()<<v; in>>v; if(v.canConvert<QStringList>()) { qDebug()<<v.toStringList(); } file.close(); */ MyClass mClass; QVariant v=QVariant::fromValue(mClass); return a.exec(); }
583cbfeae615547406019fa98bdbdb6d8c11acf3
5ee869c24397c2976dba81948aca9b8c3b6e58eb
/filtroMedia.cpp
e16b3ffce19eeda5df4bb168d8f099f7950a18f0
[]
no_license
marcelobiao/OpenCV-FiltroMediaeMediana
f4e085463ca5af913b43057d46e2a21cdca8e50a
3e8812e5be520ca63cf13b3129284bbcd27f2336
refs/heads/master
2021-01-20T06:26:01.511448
2017-05-03T21:27:46
2017-05-03T21:27:46
89,876,437
1
0
null
null
null
null
UTF-8
C++
false
false
1,335
cpp
//Número de imagens. int tam = 50; //Vetor para armazenar os pixels de todas as imagens de uma mesma coordenada. int vetor [tam]; //Vetor para armazenar todas as imagens. Mat seqImagem [tam]; //Caminho da localização das imagens. string strArquivos="satelite_ruido/%02i.png"; //Armazena todas as imagens que satisfazem o caminho no objeto VideoCapture. VideoCapture sequencia(strArquivos); //Verifica se a sequência de imagens foi aberta. if (!sequencia.isOpened()) { cerr << "Falha na abertura da sequência de imagens!\n" << endl; return 1; } //Transfere as imagens carregadas no objeto VideoCapture para o vetor de imagens. for (int i=0;i<tam;i++) { sequencia >> seqImagem[i]; } //Armazena o tamanho de linhas e colunas padrão da imagem. int height=seqImagem[0].rows; int width=seqImagem[0].cols; //Define as resoluções espaciais/contraste das matrizes que receberão o cálculo da média e mediana. cv::Mat media(height, width, CV_8U); cv::Mat mediana(height, width, CV_8U); //Varre os das coordenadas(x,y) de todas as imagens. for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { //Varre todas as imagens. for(int img=0; img< tam; img++) { //Armazena no vetor da mesma posição(x,y) todos os pixels das imagens. vetor[img]= seqImagem[img].at<uchar>(i,j); } //Fazer aqui o cálculo do vetor. } }
b8c23e890aca162198f428fb8a76368af47a0dd2
5f8d31c311e37e1b0af45f1b9705883ade20d077
/ns/src/Navigator/prefs/CSizePopup.cp
f1f9b711f0c9e6b5117aeca0c03f42f451d33e76
[]
no_license
acolchagoff/mozz
e64325b16ed135bbad4abb99dade0437e8ae5a7c
ff6798c307e3bbdae6dfe0da23cfe3c594908255
refs/heads/master
2023-06-23T14:44:03.842724
2018-03-06T13:10:33
2018-03-06T13:10:33
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
12,357
cp
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * The contents of this file are subject to the Netscape Public License * Version 1.0 (the "NPL"); you may not use this file except in * compliance with the NPL. You may obtain a copy of the NPL at * http://www.mozilla.org/NPL/ * * Software distributed under the NPL is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL * for the specific language governing rights and limitations under the * NPL. * * The Initial Developer of this code under the NPL is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1998 Netscape Communications Corporation. All Rights * Reserved. */ /* Portions copyright Metrowerks Corporation. */ #include "CSizePopup.h" #include "PascalString.h" #include "uerrmgr.h" #include "resgui.h" #include "macutil.h" #include "UModalDialogs.h" #include "UGraphicGizmos.h" #include <UNewTextDrawing.h> #include <UGAColorRamp.h> #include <UGraphicsUtilities.h> static const Char16 gsPopup_SmallMark = '¥'; // Mark used for small font popups static const Int16 gsPopup_ArrowButtonWidth = 22; // Width used in drawing the arrow only static const Int16 gsPopup_ArrowButtonHeight = 16; // Height used for drawing arrow only static const Int16 gsPopup_ArrowHeight = 5; // Actual height of the arrow static const Int16 gsPopup_ArrowWidth = 9; // Actual width of the arrow at widest //----------------------------------- CSizePopup::CSizePopup(LStream* inStream) //----------------------------------- : mFontNumber(0) , LGAPopup(inStream) { } //----------------------------------- Int32 CSizePopup::GetMenuSize() const //----------------------------------- { Int32 size = 0; MenuHandle menuH = const_cast<CSizePopup*>(this)->GetMacMenuH(); if (menuH) { size = ::CountMItems(menuH); } return size; } //----------------------------------- void CSizePopup::SetUpCurrentMenuItem(MenuHandle inMenuH, Int16 inCurrentItem ) //----------------------------------- { // ¥ If the current item has changed then make it so, this // also involves removing the mark from any old item if (inMenuH) { CStr255 sizeString; CStr255 itemString; Handle ellipsisHandle = nil; char ellipsisChar; short menuSize = ::CountMItems(inMenuH); ThrowIfNil_(ellipsisHandle = ::GetResource('elps', 1000)); ellipsisChar = **ellipsisHandle; ::ReleaseResource(ellipsisHandle); if (inCurrentItem == ::CountMItems(inMenuH)) { itemString = ::GetCString(OTHER_FONT_SIZE); ::StringParamText(itemString, (SInt32) GetFontSize(), 0, 0, 0); } else { itemString = ::GetCString(OTHER_RESID); itemString += ellipsisChar; } ::SetMenuItemText(inMenuH, menuSize, itemString); // ¥ Get the current value Int16 oldItem = GetValue(); // ¥ Remove the current mark ::SetItemMark(inMenuH, oldItem, 0); // ¥ Always make sure item is marked Char16 mark = GetMenuFontSize() < 12 ? gsPopup_SmallMark : checkMark; ::SetItemMark(inMenuH, inCurrentItem, mark); } } //----------------------------------- Int32 CSizePopup::GetFontSizeFromMenuItem(Int32 inMenuItem) const //----------------------------------- { Str255 sizeString; Int32 fontSize = 0; ::GetMenuItemText(const_cast<CSizePopup*>(this)->GetMacMenuH(), inMenuItem, sizeString); myStringToNum(sizeString, &fontSize); return fontSize; } //----------------------------------- void CSizePopup::SetFontSize(Int32 inFontSize) //----------------------------------- { mFontSize = inFontSize; if (inFontSize) { MenuHandle sizeMenu = GetMacMenuH(); short menuSize = ::CountMItems(sizeMenu); Boolean isOther = true; for (int i = 1; i <= menuSize; ++i) { CStr255 sizeString; ::GetMenuItemText(sizeMenu, i, sizeString); Int32 fontSize = 0; myStringToNum(sizeString, &fontSize); if (fontSize == inFontSize) { SetValue(i); if (i != menuSize) isOther = false; break; } } if (isOther) SetValue(menuSize); } } //----------------------------------- void CSizePopup::SetValue(Int32 inValue) //----------------------------------- { // ¥ We intentionally do not guard against setting the value to the // same value the popup current has. This is so that the other // size stuff works correctly. // ¥ Get the current item setup in the menu MenuHandle menuH = GetMacMenuH(); if ( menuH ) { SetUpCurrentMenuItem( menuH, inValue ); } if (inValue < mMinValue) { // Enforce min/max range inValue = mMinValue; } else if (inValue > mMaxValue) { inValue = mMaxValue; } mValue = inValue; // Store new value BroadcastValueMessage(); // Inform Listeners of value change // ¥ Now we need to get the popup redrawn so that the change // will be seen Draw( nil ); } // LGAPopup::SetValue //----------------------------------- Boolean CSizePopup::TrackHotSpot(Int16 inHotSpot, Point inPoint, Int16 inModifiers) //----------------------------------- { // Portions of this function are from LGAPopup.cp in PowerPlant // ¥ We only want the popup menu to appear if the mouse went down // in the our hot spot which is the popup portion of the control // not the label area if ( PointInHotSpot( inPoint, inHotSpot )) { // ¥ Get things started off on the right foot Boolean currInside = true; Boolean prevInside = false; HotSpotAction( inHotSpot, currInside, prevInside ); // ¥ We skip the normal tracking that is done in the control as // the call to PopupMenuSelect will take control of the tracking // once the menu is up // ¥ Now we need to handle the display of the actual popup menu // we start by setting up some values that we will need Int16 menuID = 0; Int16 menuItem = GetValue(); Int16 currItem = IsPulldownMenu() ? 1 : GetValue(); Point popLoc; GetPopupMenuPosition( popLoc ); // ¥ Call our utility function which handles the display of the menu // menu is disposed of inside this function HandlePopupMenuSelect( popLoc, currItem, menuID, menuItem ); if ( menuItem > 0) { if ( menuItem == ::CountMItems( GetMacMenuH() )) { StDialogHandler handler(Wind_OtherSizeDialog, nil); LWindow* dialog = handler.GetDialog(); LEditField *sizeField = (LEditField *)dialog->FindPaneByID(1504); Assert_(sizeField); sizeField->SetValue(GetFontSize()); sizeField->SelectAll(); // Run the dialog MessageT message = msg_Nothing; do { message = handler.DoDialog(); } while (message == msg_Nothing); if (msg_ChangeFontSize == message) { SetFontSize(sizeField->GetValue()); } } else { SetFontSize(GetFontSizeFromMenuItem(menuItem)); } } // ¥ Make sure that we get the HotSpotAction called one last time HotSpotAction( inHotSpot, false, true ); return menuItem > 0; } else return false; } //----------------------------------- void CSizePopup::MarkRealFontSizes(LGAPopup *fontPopup) //----------------------------------- { CStr255 fontName; ::GetMenuItemText( fontPopup->GetMacMenuH(), fontPopup->GetValue(), fontName); GetFNum(fontName, &mFontNumber); MarkRealFontSizes(mFontNumber); } //----------------------------------- void CSizePopup::MarkRealFontSizes(short fontNum) //----------------------------------- { Str255 itemString; MenuHandle sizeMenu; short menuSize; sizeMenu = GetMacMenuH(); menuSize = CountMItems(sizeMenu); for (short menuItem = 1; menuItem <= menuSize; ++menuItem) { Int32 fontSize; ::GetMenuItemText(sizeMenu, menuItem, itemString); fontSize = 0; myStringToNum(itemString, &fontSize); Style theSyle; if (fontSize && RealFont(fontNum, fontSize)) { theSyle = outline; } else { theSyle = normal; } ::SetItemStyle( sizeMenu, menuItem, theSyle); } } //----------------------------------- void CSizePopup::DrawPopupTitle() // DrawPopupTitle is overridden to draw in the outline style // as needed //----------------------------------- { StColorPenState theColorPenState; StTextState theTextState; // ¥ Get some loal variables setup including the rect for the title ResIDT textTID = GetTextTraitsID(); Rect titleRect; Str255 title; GetCurrentItemTitle( title ); // ¥ Figure out what the justification is from the text trait and // get the port setup with the text traits UTextTraits::SetPortTextTraits( textTID ); // ¥ Set outline style if it's an outline size if (GetMacMenuH() && GetValue() != ::CountMItems(GetMacMenuH())) { Int32 fontSize; CStr255 itemString; ::GetMenuItemText(GetMacMenuH(), GetValue(), itemString); fontSize = 0; myStringToNum(itemString, &fontSize); Style theSyle; if (fontSize && ::RealFont(mFontNumber, fontSize)) { theSyle = outline; } else { theSyle = normal; } ::TextFace(theSyle); } // ¥ Set up the title justification which is always left justified Int16 titleJust = teFlushLeft; // ¥ Get the current item's title Str255 currentItemTitle; GetCurrentItemTitle( currentItemTitle ); // ¥ Calculate the title rect CalcTitleRect( titleRect ); // ¥ Kludge for drawing (correctly) in outline style left-justified Rect actualRect; UNewTextDrawing::MeasureWithJustification( (char*) &currentItemTitle[1], currentItemTitle[0], titleRect, titleJust, actualRect); actualRect.right += 2; titleRect = actualRect; titleJust = teJustRight; // ¥ Set up the text color which by default is black RGBColor textColor; ::GetForeColor( &textColor ); // ¥ Loop over any devices we might be spanning and handle the drawing // appropriately for each devices screen depth StDeviceLoop theLoop( titleRect ); Int16 depth; while ( theLoop.NextDepth( depth )) { if ( depth < 4 ) // ¥ BLACK & WHITE { // ¥ If the control is dimmed then we use the grayishTextOr // transfer mode to draw the text if ( !IsEnabled()) { ::RGBForeColor( &UGAColorRamp::GetBlackColor() ); ::TextMode( grayishTextOr ); } else if ( IsEnabled() && IsHilited() ) { // ¥ When we are hilited we simply draw the title in white ::RGBForeColor( &UGAColorRamp::GetWhiteColor() ); } // ¥ Now get the actual title drawn with all the appropriate settings UTextDrawing::DrawWithJustification( (char*) &currentItemTitle[1], currentItemTitle[0], titleRect, titleJust); } else // ¥ COLOR { // ¥ If control is selected we always draw the text in the title // hilite color, if requested if ( IsHilited()) ::RGBForeColor( &UGAColorRamp::GetWhiteColor() ); // ¥ If the box is dimmed then we have to do our own version of the // grayishTextOr as it does not appear to work correctly across // multiple devices if ( !IsEnabled() || !IsActive()) { textColor = UGraphicsUtilities::Lighten( &textColor ); ::TextMode( srcOr ); ::RGBForeColor( &textColor ); } // ¥ Now get the actual title drawn with all the appropriate settings UTextDrawing::DrawWithJustification( (char*) &currentItemTitle[1], currentItemTitle[0], titleRect, titleJust); } } } // CSizePopup::DrawPopupTitle //----------------------------------- void CSizePopup::DrawPopupArrow() //----------------------------------- { StColorPenState theColorPenState; // ¥ Get the local popup frame rect Rect popupFrame; CalcLocalPopupFrameRect( popupFrame ); // ¥ Set up some variables used in the drawing loop Int16 start = (( UGraphicsUtilities::RectHeight( popupFrame ) - gsPopup_ArrowHeight) / 2) + 1; // ¥ Figure out the left and right edges based on whether we are drawing // only the arrow portion or the entire popup Int16 leftEdge = gsPopup_ArrowButtonWidth - 6; Int16 rightEdge = leftEdge - (gsPopup_ArrowWidth - 1); popupFrame.top = popupFrame.top + start; popupFrame.bottom = popupFrame.top + gsPopup_ArrowHeight - 1; popupFrame.left = popupFrame.right - leftEdge; popupFrame.right = popupFrame.right - rightEdge; UGraphicGizmos::DrawPopupArrow( popupFrame, IsEnabled(), IsActive(), IsHilited()); } // CSizePopup::DrawPopupArrow
62c198b3e0c04fe516059fc240e13eecfdad4dc7
bbf47e162e03ec3469a57ae37064b2546961f525
/Decoder.h
31e4502c21b36d896c0a3cb620f7e7365b12e170
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
harlowja/bencode
82004f9fba7c0afa1697f4b47efcaf65045b76e6
32179f1fcf2ca8ce020fc5a3a3aef0eb1c90ea80
refs/heads/master
2023-08-09T01:16:33.911072
2012-04-11T21:03:27
2012-04-11T21:03:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
569
h
#ifndef DECODER_H #define DECODER_H #include "ValueTypes.h" #include <string> #include <deque> namespace bencode { class Decoder { public: static Value decode(const std::string& encoded); private: static Value decode(std::deque<std::string>& tokens); static Value decodeInteger(std::deque<std::string>& tokens); static Value decodeString(std::deque<std::string>& tokens); static Value decodeVector(std::deque<std::string>& tokens); static Value decodeDictionary(std::deque<std::string>& tokens); Decoder(); }; }; #endif
a83000477f8b21d48cfa7aca6e66f41ffbd48d19
5009d73e25ddb307db18dc79567e586df415cafe
/mirror.ino
725e4ce92a327de81187eecc49094950a4958304
[]
no_license
stedaigle/mirror
f65b5c04c2d0ad9298ad5f27792592983d201f50
11914924df8d80252a1d2dd358fd6a4484e8109a
refs/heads/master
2021-01-07T17:38:07.307432
2020-02-20T02:45:52
2020-02-20T02:45:52
241,770,680
0
0
null
null
null
null
UTF-8
C++
false
false
6,300
ino
#include <Wire.h> #include <SFE_MicroOLED.h> #include <SparkFunBME280.h> // Global sensor objects BME280 myBME280; // Variables to hold the parsed data boolean newData = false; const byte numChars = 128; char receivedChars[numChars]; char tempChars[numChars]; // Temporary array for use when parsing char temp[16] = {0}; char humid[16] = {0}; char pres[16] = {0}; char alt[16] = {0}; char co2[16] = {0}; char tvoc[16] = {0}; char dest1[16] = {0}; char time1[16] = {0}; char dist1[16] = {0}; char dest2[16] = {0}; char time2[16] = {0}; char dist2[16] = {0}; unsigned long seconds = 1000L; unsigned long minutes = seconds * 60; String tempString = ""; ////////////////////////// // MicroOLED Definition // ////////////////////////// // The library assumes a reset pin is necessary. The Qwiic OLED has RST hard-wired, so pick an arbitrarty IO pin that is not being used #define PIN_RESET 9 // The DC_JUMPER is the I2C Address Select jumper. Set to 1 if the jumper is open (default), or set to 0 if it's closed. #define DC_JUMPER_0 0 #define DC_JUMPER_1 1 ////////////////////////////////// // MicroOLED Object Declaration // ////////////////////////////////// MicroOLED oled_0(PIN_RESET, DC_JUMPER_0); // I2C declaration for OLED 0 MicroOLED oled_1(PIN_RESET, DC_JUMPER_1); // I2C declaration for OLED 1 void setup() { Serial.begin(115200); Serial1.begin(115200); Serial.println("\n\rIntelligent Mirror Powered by Artemis ATP"); Serial.println("Waiting for data stream"); delay(100); Wire.begin(); oled_0.begin(); // Initialize the OLED oled_1.begin(); oled_0.clear(ALL); // Clear the display's internal memory oled_1.clear(ALL); oled_0.display(); // Display what's in the buffer (splashscreen) oled_1.display(); delay(1000); oled_0.clear(PAGE); // Clear the buffer oled_1.clear(PAGE); if (myBME280.beginI2C() == false) // Begin communication over I2C { ////Serial.println("The sensor did not respond. Please check wiring."); while(1); // Freeze } } void loop() { recvWithStartEndMarkers(); if (newData == true) { // This temporary copy is necessary to protect the original data // because strtok() used in parseData() replaces the commas with \0 strcpy(tempChars, receivedChars); parseData(); // Print data to serial monitor Serial.println(temp); Serial.println(humid); Serial.println(pres); Serial.println(alt); Serial.println(co2); Serial.println(tvoc); Serial.println(dest1); Serial.println(time1); Serial.println(dist1); Serial.println(dest2); Serial.println(time2); Serial.println(dist2); newData = false; } printTitle_0(" INSIDE"," TEMP"); printTitle_1(" WORK","TRAFFIC"); delay(2000); oled_0.clear(PAGE); oled_1.clear(PAGE); oled_0.setFontType(3); oled_0.setCursor(0, 0); // Set cursor to top-middle-left tempString = String(myBME280.readTempF(), 0); oled_0.print(tempString); oled_0.setCursor(32, 32); // Set cursor to bottom-middle oled_0.setFontType(1); oled_0.print("F"); oled_0.display(); // Draw on the screen oled_1.setFontType(3); oled_1.setCursor(0, 0); // Set cursor to top-middle-left oled_1.print(time1); oled_1.setCursor(32, 32); // Set cursor to bottom-middle oled_1.setFontType(1); oled_1.print("MIN"); oled_1.display(); // Draw on the screen delay(10000); printTitle_0("OUTSIDE"," TEMP"); printTitle_1(" SCHOOL","TRAFFIC"); delay(2000); oled_0.clear(PAGE); oled_1.clear(PAGE); oled_0.setFontType(3); oled_0.setCursor(0, 0); // Set cursor to top-middle-left oled_0.print(temp); oled_0.setCursor(32, 32); // Set cursor to bottom-middle oled_0.setFontType(1); oled_0.print("F"); oled_0.display(); // Draw on the screen oled_1.setFontType(3); oled_1.setCursor(0, 0); // Set cursor to top-middle-left oled_1.print(time2); oled_1.setCursor(32, 32); // Set cursor to bottom-middle oled_1.setFontType(1); oled_1.print("MIN"); oled_1.display(); // Draw on the screen delay(10000); } // Print a small title void printTitle_0(String title1, String title2) { oled_0.clear(PAGE); oled_0.setFontType(1); // Try to set the cursor in the middle of the screen oled_0.setCursor(0,8); // Print the title: oled_0.print(title1); oled_0.setCursor(0,24); oled_0.print(title2); oled_0.display(); } void printTitle_1(String title1, String title2) { oled_1.clear(PAGE); oled_1.setFontType(1); oled_1.setCursor(0,8); oled_1.print(title1); oled_1.setCursor(0,24); oled_1.print(title2); oled_1.display(); } void recvWithStartEndMarkers() { static boolean recvInProgress = false; static byte ndx = 0; char startMarker = '<'; char endMarker = '>'; char rc; while (Serial1.available() > 0 && newData == false) { rc = Serial1.read(); if (recvInProgress == true) { if (rc != endMarker) { receivedChars[ndx] = rc; ndx++; if (ndx >= numChars) { ndx = numChars - 1; } } else { receivedChars[ndx] = '\0'; // terminate the string recvInProgress = false; ndx = 0; newData = true; } } else if (rc == startMarker) { recvInProgress = true; } } } void parseData() { // Split the data into its parts char * strtokIndx; // This is used by strtok() as an index strtokIndx = strtok(tempChars,","); // Get the first part - the string strcpy(temp, strtokIndx); // Copy it to string strtokIndx = strtok(NULL, ","); // This continues where the previous call left off strcpy(humid, strtokIndx); // Copy this part to a string strtokIndx = strtok(NULL, ","); strcpy(pres, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(alt, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(co2, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(tvoc, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(dest1, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(time1, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(dist1, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(dest2, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(time2, strtokIndx); strtokIndx = strtok(NULL, ","); strcpy(dist2, strtokIndx); }
1f7432689970736b9e3b6dd941569a9001535d0e
f88c1945cb7770141fd26f69bbf1c2814f14bdc4
/Source/Scene/TankEntity.h
1aa1911a1702b26f505b75197a7877d518f92b6f
[]
no_license
aidenjones29/Tank-GD2Assignment
56709d3be90d603bae5d2a00a9304341f66dc27d
28550095a7e02a03e5e96050fd1fdeee50a91e66
refs/heads/master
2022-04-04T19:30:00.806356
2020-01-17T15:11:11
2020-01-17T15:11:11
231,422,191
0
0
null
null
null
null
UTF-8
C++
false
false
5,721
h
/******************************************* TankEntity.h Tank entity template and entity classes ********************************************/ #pragma once #include <string> using namespace std; #include "Defines.h" #include "CVector3.h" #include "Entity.h" namespace gen { /*----------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------- Tank Template Class ------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------*/ // A tank template inherits the type, name and mesh from the base template and adds further // tank specifications class CTankTemplate : public CEntityTemplate { ///////////////////////////////////// // Constructors/Destructors public: // Tank entity template constructor sets up the tank specifications - speed, acceleration and // turn speed and passes the other parameters to construct the base class CTankTemplate ( const string& type, const string& name, const string& meshFilename, TFloat32 maxSpeed, TFloat32 acceleration, TFloat32 turnSpeed, TFloat32 turretTurnSpeed, TUInt32 maxHP, TUInt32 shellDamage ) : CEntityTemplate( type, name, meshFilename ) { // Set tank template values m_MaxSpeed = maxSpeed; m_Acceleration = acceleration; m_TurnSpeed = turnSpeed; m_TurretTurnSpeed = turretTurnSpeed; m_MaxHP = maxHP; m_ShellDamage = shellDamage; } // No destructor needed (base class one will do) ///////////////////////////////////// // Public interface public: ///////////////////////////////////// // Getters TFloat32 GetMaxSpeed() { return m_MaxSpeed; } TFloat32 GetAcceleration() { return m_Acceleration; } TFloat32 GetTurnSpeed() { return m_TurnSpeed; } TFloat32 GetTurretTurnSpeed() { return m_TurretTurnSpeed; } TInt32 GetMaxHP() { return m_MaxHP; } TInt32 GetShellDamage() { return m_ShellDamage; } ///////////////////////////////////// // Private interface private: // Common statistics for this tank type (template) TFloat32 m_MaxSpeed; // Maximum speed for this kind of tank TFloat32 m_Acceleration; // Acceleration -"- TFloat32 m_TurnSpeed; // Turn speed -"- TFloat32 m_TurretTurnSpeed; // Turret turn speed -"- TUInt32 m_MaxHP; // Maximum (initial) HP for this kind of tank TUInt32 m_ShellDamage; // HP damage caused by shells from this kind of tank }; /*----------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------- Tank Entity Class ------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------*/ // A tank entity inherits the ID/positioning/rendering support of the base entity class // and adds instance and state data. It overrides the update function to perform the tank // entity behaviour // The shell code performs very limited behaviour to be rewritten as one of the assignment // requirements. You may wish to alter other parts of the class to suit your game additions // E.g extra member variables, constructor parameters, getters etc. class CTankEntity : public CEntity { ///////////////////////////////////// // Constructors/Destructors public: // Tank constructor intialises tank-specific data and passes its parameters to the base // class constructor CTankEntity ( CTankTemplate* tankTemplate, TEntityUID UID, TUInt32 team, const string& name = "", const CVector3& position = CVector3::kOrigin, const CVector3& rotation = CVector3(0.0f, 0.0f, 0.0f), const CVector3& scale = CVector3(1.0f, 1.0f, 1.0f) ); // No destructor needed ///////////////////////////////////// // Public interface public: ///////////////////////////////////// // Getters TFloat32 GetSpeed() { return m_Speed; } float getHP() { return m_HP; } string getState() { switch (m_State) { case Inactive: return "Inactive"; case Patrol: return "Patrol"; case Aim: return "Aim"; case Evade: return "Evade"; case Dead: return "Dead"; case Ammo: return "Ammo"; default: return "N/A"; } } int getTeam() { return m_Team; } int getFired() { return m_Fired; } int getAmmo() { return m_ammoCount; } ///////////////////////////////////// // Update // Update the tank - performs tank message processing and behaviour // Return false if the entity is to be destroyed // Keep as a virtual function in case of further derivation virtual bool Update( TFloat32 updateTime ); ///////////////////////////////////// // Private interface private: ///////////////////////////////////// // Types // States available for a tank - placeholders for shell code enum EState { Inactive, Patrol, Aim, Evade, Dead, Ammo, }; ///////////////////////////////////// // Data // The template holding common data for all tank entities CTankTemplate* m_TankTemplate; // Tank data TUInt32 m_Team; // Team number for tank (to know who the enemy is) TFloat32 m_Speed; // Current speed (in facing direction) TInt32 m_HP; // Current hit points for the tank int m_currentPoint; CVector3 m_patrolPoint[2]; TEntityUID m_Target; CVector3 m_EvadePoint; // Tank state EState m_State; // Current state TFloat32 m_Timer; // A timer used in the example update function int m_Fired; bool m_Facing; float m_deadSpeed; int m_ammoCount; }; } // namespace gen
7146ddb5cfd91162d86b24e07e284e03a89a4765
747ffe00fd06d35d57d339c3737cb0f0aab4119d
/ArmRL-master/plugins/ball_plugin.h
4d006ab0f2954a10376da21bb8aca22342d753b9
[ "MIT" ]
permissive
rbcommits/RobotLearning
cc55b5737cb1d3229dd047ec878a447d332bc5fb
86ce6fe1962252853a8db11c30f25784720fb01c
refs/heads/master
2021-08-30T13:38:19.276008
2017-12-18T05:45:15
2017-12-18T05:45:15
112,964,558
0
0
null
null
null
null
UTF-8
C++
false
false
178
h
#pragma once #include <vector> extern "C" { void ball_plugin_init(void); void ball_plugin_destroy(void); void ball_plugin_setPositions(double x, double y, double z); }
dd67bf38243cad54c0f42e2bcd461656d20211f6
66862c422fda8b0de8c4a6f9d24eced028805283
/slambook2/3rdparty/Pangolin/src/python/pypangolin/datalog.cpp
45ccb47dd39993fac6c0f4d61f450a026591f693
[ "MIT" ]
permissive
zhh2005757/slambook2_in_Docker
57ed4af958b730e6f767cd202717e28144107cdb
f0e71327d196cdad3b3c10d96eacdf95240d528b
refs/heads/main
2023-09-01T03:26:37.542232
2021-10-27T11:45:47
2021-10-27T11:45:47
416,666,234
17
6
MIT
2021-10-13T09:51:00
2021-10-13T09:12:15
null
UTF-8
C++
false
false
4,833
cpp
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) Andrey Mnatsakanov * * 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. */ #include "datalog.hpp" #include <pybind11/stl.h> #include <pangolin/plot/datalog.h> namespace py_pangolin { void bind_datalog(pybind11::module& m){ pybind11::class_<pangolin::DimensionStats >(m, "DimensionStats") .def(pybind11::init<>()) .def("Reset", &pangolin::DimensionStats::Reset) .def("Add", &pangolin::DimensionStats::Add) .def_readwrite("isMonotonic", &pangolin::DimensionStats::isMonotonic) .def_readwrite("sum", &pangolin::DimensionStats::sum) .def_readwrite("sum_sq", &pangolin::DimensionStats::sum_sq) .def_readwrite("min", &pangolin::DimensionStats::min) .def_readwrite("max", &pangolin::DimensionStats::max); pybind11::class_<pangolin::DataLogBlock>(m, "DataLogBlock") .def(pybind11::init<size_t,size_t,size_t>()) .def("Samples", &pangolin::DataLogBlock::Samples) .def("MaxSamples", &pangolin::DataLogBlock::MaxSamples) .def("SampleSpaceLeft", &pangolin::DataLogBlock::SampleSpaceLeft) .def("IsFull", &pangolin::DataLogBlock::IsFull) .def("AddSamples", &pangolin::DataLogBlock::AddSamples) .def("ClearLinked", &pangolin::DataLogBlock::ClearLinked) .def("NextBlock", &pangolin::DataLogBlock::NextBlock) .def("StartId", &pangolin::DataLogBlock::StartId) .def("DimData", &pangolin::DataLogBlock::DimData) .def("Dimensions", &pangolin::DataLogBlock::Dimensions) .def("Sample", &pangolin::DataLogBlock::Sample) .def("StartId", &pangolin::DataLogBlock::StartId); pybind11::class_<pangolin::DataLog>(m, "DataLog") .def(pybind11::init<unsigned int>(), pybind11::arg("block_samples_alloc")=10000) .def("SetLabels", &pangolin::DataLog::SetLabels) .def("Labels", &pangolin::DataLog::Labels) .def("Log", (void (pangolin::DataLog::*)(size_t, const float*, unsigned int))&pangolin::DataLog::Log, pybind11::arg("dimension"), pybind11::arg("vals"), pybind11::arg("samples")=1) .def("Log", (void (pangolin::DataLog::*)(float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float, float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float, float, float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float, float, float, float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float, float, float, float, float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float, float, float, float, float, float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float, float, float, float, float, float, float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(float, float, float, float, float, float, float, float, float, float))&pangolin::DataLog::Log) .def("Log", (void (pangolin::DataLog::*)(const std::vector<float>&))&pangolin::DataLog::Log) .def("Clear", &pangolin::DataLog::Clear) .def("Save", &pangolin::DataLog::Save) .def("FirstBlock", &pangolin::DataLog::FirstBlock) .def("LastBlock", &pangolin::DataLog::LastBlock) .def("Samples", &pangolin::DataLog::Samples) .def("Sample", &pangolin::DataLog::Sample) .def("Stats", &pangolin::DataLog::Stats); } } // py_pangolin
decd337d3f48655e1d740bde3e7b84204ffe2334
25dcf2bda9558e9621502d2575420cccf1b71b72
/mosaic.cpp
63f0f0d06f66244d204ef7df8caeb94cd957527d
[]
no_license
singhsterabhi/globous
b07c6533b37caf171b11b2700a8830da34150042
c1f3341151125cb4c1ff68ea5a5b16702a4fab74
refs/heads/master
2021-03-24T13:46:03.390193
2017-07-29T11:52:10
2017-07-29T11:52:10
95,944,731
2
1
null
null
null
null
UTF-8
C++
false
false
23,080
cpp
#include <stdio.h> #include <string.h> #include <iostream> #include<vector> #include "opencv2/xfeatures2d.hpp" #include "opencv2/core/core.hpp" #include "opencv2/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/xfeatures2d/nonfree.hpp" using namespace cv; using namespace std; //using std::vector; using namespace cv::xfeatures2d; #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/video/tracking.hpp" #include "opencv2/gpu/gpumat.hpp" #include "opencv2/gpu/gpu.hpp" //#include "opencv2/nonfree/nonfree.hpp" #include "opencv2/xfeatures2d.hpp" #include "opencv2/features2d/features2d.hpp" #include <iostream> #include <fstream> static void printUsage() { cout << "Real-time Video Mosaic.\n\n" "[email protected]\n\n" "Flags:\n" " --source <file address/device number> \n" " Feed the code from a device number or video file\n" " Example: --source c:.mp4 .\n" " Example: --source 0\n" " --x <double>\n" " This will manually set the x coordinate starting point of first image. Default is in the middle of field of view.\n" " Example --x 1.5\n" " --y <double>\n" " This will manually set the y coordinate of starting point of first image. Default is in the middle of field of view.\n" " Example --y 2.\n" " --xscale <double>\n" " This will manually set the field of view in X axis. Default is 4.\n" " Example --xsacle 5.\n" " --yscale <double>\n" " This will manually set the field of view in y axis. Default is 4.\n" " Example --ysacle 5.\n" "\nMotion Estimation Flags:\n" " --detector (fast|surf|orb|fast_grid|orb_grid|surf_grid|sift_grid) <number of features>" " You can manually select your detector type. \"fast\",\"surf\",\"orb\",\"fast_grid\",\"orb_grid\",\"surf_grid\" and \"sift_grid\" are available.\n" " Default detector is \"fast\" and default feature numbers is 300" " Example : --detector fast 400" " --descriptor (brisk|orb|brief|freak|surf)\n" " Type of features descriptor used for images matching. The default is BRISK.\n" " --match_filter (0|1)\n" " Type of filtering good matches. The default is 0. Number 2 means no filter.\n" " --save <file_name>\n" " Save file to <file_name> file. The default is \"panorama.jpg\"\n" " Example: --save panorama_Jahani.jpg" "\nCompositing Flags:\n" " --warp (affine|perspective)\n" " Warp surface type. The default is 'affine'.\n" " --log\n" " Saving the last FOV image automatically when an error occurs. Default is off.\n" "\n *****YOU CAN PRESS \"R\" TO RESET THE FOV> THE FOV WILL BE AUTOMATICALLY SAVED BEFORE RESET.\n" "\n *****YOU CAN PRESS \"E\" TO EXIT.\n" ; } //Default argumans string filename = "vid.avi"; double XScale = 4; double YScale = 4; bool log_flag = false; int device_num = -1; int features_num = 300; string detector_type = "fast"; string descriptor_type = "brisk"; string save_pano_to = "panorama.jpg"; string warp_type = "affine"; double x_start_scale = -1; double y_start_scale = -1; int detector_set_input = 10; int match_filter = 0; Mat H_kol = Mat::eye(3, 3, CV_32F); Mat H = cv::Mat::eye(3, 3, CV_64F); Mat H2 = Mat::eye(2, 3, CV_32F); Mat H_old = Mat::eye(3, 3, CV_32F); static int parseCmdArgs(int argc, char** argv) { if (argc == 0) { printUsage(); return -1; } for (int i = 1; i < argc; ++i) { if (string(argv[i]) == "--help" || string(argv[i]) == "/?") { printUsage(); return -1; } else if (string(argv[i]) == "--source") { filename = argv[i + 1]; try{ device_num = stoi(filename); } catch (...) { device_num = -1; } i++; } else if (string(argv[i]) == "--xscale") { XScale = atof(argv[i + 1]); i++; } else if (string(argv[i]) == "--yscale") { YScale = atof(argv[i + 1]); i++; } else if (string(argv[i]) == "--matchfilter") { if (string(argv[i + 1]) == "0" || string(argv[i + 1]) == "1"|| string(argv[i + 1]) == "1") match_filter = atof(argv[i + 1]); i++; } else if (string(argv[i]) == "--x") { x_start_scale = atof(argv[i + 1]); i++; } else if (string(argv[i]) == "--y") { y_start_scale = atof(argv[i + 1]); i++; } else if (string(argv[i]) == "--detector") { if (string(argv[i + 1]) == "orb_grid" || string(argv[i + 1]) == "fast_grid" || string(argv[i + 1]) == "surf_grid" || string(argv[i + 1]) == "sift_grid" || string(argv[i + 1]) == "fast" || string(argv[i + 1]) == "surf" || string(argv[i + 1]) == "orb") detector_type = argv[i + 1]; if (argc > i + 2){ if (atoi(argv[i + 2]) <= 0) i++; else { features_num = atoi(argv[i + 2]); i += 2; } } } else if (string(argv[i]) == "--save") { save_pano_to = argv[i + 1]; i++; } else if (string(argv[i]) == "--warp") { if (string(argv[i + 1]) == "perspective" || string(argv[i + 1]) == "affine") warp_type = string(argv[i + 1]); else std::cout << "Bad Warp method. You can use \"affine\" or \"perspective\". Processing with default method which is \"affine\"." << endl; i++; } else if (string(argv[i]) == "--log") { log_flag = true; } else if (string(argv[i]) == "--descriptor") { if (string(argv[i + 1]) == "brisk" || string(argv[i + 1]) == "freak" || string(argv[i + 1]) == "brief" || string(argv[i + 1]) == "orb" || string(argv[i + 1]) == "surf") descriptor_type = argv[i + 1]; else { cout << "Bad extractor type method. Using default : BRISK "; } i++; } } return 0; } bool cmpfun(DMatch a, DMatch b) { return a.distance < b.distance; } //this fuction automatically finds the argumans for feature detectors in order to have defined number of features. int automatic_feature_detection_set(Mat image) { cv::FeatureDetector* detectors = NULL; int minHessian = 400; int last_progress = 0; if (detector_type == "surf") //detectors = new SurfFeatureDetector(detector_set_input, true); Ptr<SURF> detectors = SURF::create( minHessian ); //else if (detector_type == "fast") //detectors = new FastFeatureDetector(detector_set_input, true); if ((detector_type == "surf") || (detector_type == "fast")) { vector< KeyPoint > keypoints_last; detectors->detect(image, keypoints_last); int max = keypoints_last.size(); while (keypoints_last.size() > features_num + 50) { detector_set_input += 3; //if (detector_type == "fast") detectors->set("threshold", detector_set_input); //if (detector_type == "surf") detectors->set("hessianThreshold", detector_set_input); detectors->detect(image, keypoints_last); int progress = 100 - ((keypoints_last.size() - 348) * 100 / max); if (progress >= 100 || progress<0) progress = 100; if (last_progress != progress) std::cout << "Please wait: It might take some minutes for configuration. " << progress << "%" << endl; last_progress = progress; } std::cout << "Configured successfully. The parameter for feature detector is " << detector_set_input << endl; } } int main(int argc, char* argv[]) { double time_algorithm=0; double time_complete=0; parseCmdArgs(argc, argv); double norms = 0; cv::Mat img, current_frame, gray_lastimage, gray_curimage; Mat img_last, img_last_key; Mat img_cur, img_cur_key; Mat mask; Mat img_last_scaled, img_cur_scaled; int fps = 0; //this part will open the file or camera device VideoCapture cap; if (device_num >= 0) { std::cout << "Opening camera device number " << device_num << ". Please wait..." << endl; if (!cap.open(device_num)) { std::cout << "Camera device number " << device_num << " does not exst or installed. Please select another device or read from video file." << endl; return -1; } } else { if (!cap.open(filename)) { std::cout << "Bad file name. Can't read this file." << endl; return -1; } } if (device_num >= 0) for (int k = 0; k < 10; k++) cap >> img; else cap >> img; cv::Mat offset = cv::Mat::eye(3, 3, CV_64F); int counter = 0; /////printing which method is going to be used : cout << "______________________________________________________________________________ " << endl; cout << "X-Sacle: " << XScale << " & Y-Scale: " << YScale << endl; cout <<"Detector type: "<< detector_type << " Features: "<<features_num<<endl; cout << "Descriptor type: " << descriptor_type << endl; cout << "Warping Mode: " << warp_type << endl; cout << "Filter Mode: " << match_filter << endl; cout << "______________________________________________________________________________ " << endl; //////////////////////////starting point double start_width; double start_height; //if the x and y are not set from arguments they will be in the middle of FOV if (x_start_scale < 0) start_width = img.cols*(XScale / 2 - 0.5); else start_width = img.cols*(x_start_scale); if (y_start_scale < 0) start_height = img.rows*(YScale / 2 - 0.5); else start_height = img.rows*(y_start_scale); // making the final image and copying the first frame in the middle of it Mat final_img(Size(img.cols * XScale, img.rows * YScale), CV_8UC3); Mat f_roi(final_img, Rect(start_width, start_height, img.cols, img.rows)); img.copyTo(f_roi); img.copyTo(img_last); //this will reduce the resuloution of the image to medium size inorder to be more robust for different resolutions Size size_wrap(final_img.cols, final_img.rows); char key; Mat rImg; double work_megapix = 0.7; double work_scale = min(1.0, sqrt(work_megapix * 1e6 / img.size().area())); resize(img_last, img_last_scaled, Size(), work_scale, work_scale); cv::cvtColor(img_last_scaled, gray_lastimage, CV_RGB2GRAY); automatic_feature_detection_set(gray_lastimage); // making feature detector object cv::FeatureDetector* detector = NULL; //if (detector_type == "fast_grid") //detector = new GridAdaptedFeatureDetector(new FastFeatureDetector(10, true), features_num, 3, 3); //else if (detector_type == "surf_grid") //detector = new GridAdaptedFeatureDetector(new SurfFeatureDetector(700, true), features_num, 3, 3); //else if (detector_type == "sift_grid") //detector = new GridAdaptedFeatureDetector(new SiftFeatureDetector(), features_num, 3, 3); //else if (detector_type == "orb_grid") //detector = new GridAdaptedFeatureDetector(new OrbFeatureDetector(), features_num, 3, 3); //else if (detector_type == "surf") //detector = new SurfFeatureDetector(detector_set_input, true); Ptr<SURF> detectors = SURF::create(400); //else if (detector_type == "orb") //detector = new OrbFeatureDetector(features_num); //else //detector = new FastFeatureDetector(detector_set_input, true); // making descriptor object. It is needed for matching. vector< KeyPoint > keypoints_last, keypoints_cur; detector->detect(gray_lastimage, keypoints_last); //DescriptorExtractor* extractor = NULL; //if (descriptor_type == "brisk") extractor = new BRISK; //else if (descriptor_type == "orb") extractor = new OrbDescriptorExtractor; //else if (descriptor_type == "freak") extractor = new FREAK; //else if (descriptor_type == "brief") extractor = new BriefDescriptorExtractor; //else if (descriptor_type == "surf") //SurfDescriptorExtractor extractor; Ptr<SURF> extractor = SURF::create( 400 ); //extractor=new SurfDescriptorExtractor; Mat descriptors_last, descriptors_cur; extractor->compute(gray_lastimage, keypoints_last, descriptors_last); double gui_time; int64 t, start_app,start_algorithm; Mat panorama_temp; int64 start_app_main = getTickCount(); bool last_err = false; bool first_time_4pointfound = false; bool second_time_4pointfound = false; //starting loop while (true) { //take the new frame start_app = getTickCount(); counter++; cout << "______________________________________________________________________________ " << endl; cout << counter << endl; cap >> img_cur; start_algorithm = getTickCount(); if (img_cur.empty()) break; cvNamedWindow("current video", CV_WINDOW_NORMAL); imshow("current video", img_cur); waitKey(1); resize(img_cur, img_cur_scaled, Size(), work_scale, work_scale); if (img_cur.empty()) break; //convert to grayscale cvtColor(img_cur_scaled, gray_curimage, CV_RGB2GRAY); //First step: feature extraction t = getTickCount(); detector->detect(gray_curimage, keypoints_cur); cout << "features= " << keypoints_cur.size() << endl; cout << "detecting time: " << ((getTickCount() - t) / getTickFrequency()) << endl; //Second step: descriptor extraction t = getTickCount(); extractor->compute(gray_curimage, keypoints_cur, descriptors_cur); cout << "descriptor time: " << ((getTickCount() - t) / getTickFrequency()) << endl; t = getTickCount(); //Third step: match with BFMatcher if (descriptors_last.type() != CV_32F) { descriptors_last.convertTo(descriptors_last, CV_32F); } if (descriptors_cur.type() != CV_32F) { descriptors_cur.convertTo(descriptors_cur, CV_32F); } vector< DMatch > matches; BFMatcher matcher(NORM_L2, true); matcher.match(descriptors_last, descriptors_cur, matches); if (matches.empty()){ last_err = false; continue; } vector< DMatch > good_matches; vector< DMatch > good_matches2; vector<Point2f> match1, match2; sort(matches.begin(), matches.end(), cmpfun); //matching filter number 0. It will calculate the distance of matches and the first 50 ones which has less 4 times distance than max distance will be considered. if (match_filter == 0) { double max_dist = 0; double min_dist = 100; for (int i = 0; i < matches.size(); i++) { double dist = matches[i].distance; if (dist < min_dist) min_dist = dist; if (dist > max_dist) max_dist = dist; } for (int i = 0; i < matches.size() && i < 50; i++) { if (matches[i].distance <= 4 * min_dist) { good_matches2.push_back(matches[i]); } } } //matching filter number 1. It will calculate the norms od distances and the it has the same matching filter number 0 at the end to reduce and find the best the matching features. else if (match_filter == 1) { int counterx; float res; for (int i = 0; i < (int)matches.size(); i++){ counterx = 0; for (int j = 0; j < (int)matches.size(); j++){ if (i != j){ res = cv::norm(keypoints_last[matches[i].queryIdx].pt - keypoints_last[matches[j].queryIdx].pt) - cv::norm(keypoints_cur[matches[i].trainIdx].pt - keypoints_cur[matches[j].trainIdx].pt); if (abs(res) < (img.rows*0.03 + 3)){ //this value(0.03) has to be adjusted counterx++; } } } if (counterx > (matches.size() / 10)){ good_matches.push_back(matches[i]); } } double max_dist = 0; double min_dist = 100; for (int i = 0; i < good_matches.size(); i++) { double dist = good_matches[i].distance; if (dist < min_dist) min_dist = dist; if (dist > max_dist) max_dist = dist; } cout << "max_dist:" << max_dist << endl; cout << "min_dist:" << min_dist << endl; //take just the good points if ((max_dist == 0) && (min_dist == 0)) { last_err = false; continue; } sort(good_matches.begin(), good_matches.end(), cmpfun); for (int i = 0; i < good_matches.size() && i < 50; i++) { if (good_matches[i].distance <= 4 * min_dist) { good_matches2.push_back(good_matches[i]); } } } //no filter else if (match_filter == 2) good_matches2 = matches; cout << "goodmatches features=" << good_matches2.size() << endl; vector< Point2f > obj_last; vector< Point2f > scene_cur; //take the keypoints for (int i = 0; i < good_matches2.size(); i++) { obj_last.push_back(keypoints_last[good_matches2[i].queryIdx].pt); scene_cur.push_back(keypoints_cur[good_matches2[i].trainIdx].pt); } cout << "match time: " << ((getTickCount() - t) / getTickFrequency()) << endl; t = getTickCount(); Mat mat_match; if (scene_cur.size() >= 4) { first_time_4pointfound = true; //drawing some features and matches drawMatches(img_last, keypoints_last, img_cur, keypoints_cur, good_matches2, mat_match); cvNamedWindow("match", WINDOW_NORMAL); imshow("match", mat_match); if (counter == 1) waitKey(0); // finding homography matrix if (warp_type == "affine") { H2 = estimateRigidTransform(scene_cur, obj_last, 0); if (H2.data == NULL) { last_err = false; good_matches.clear(); good_matches2.clear(); scene_cur.clear(); obj_last.clear(); continue; } H.at<double>(0, 0) = H2.at<double>(0, 0); H.at<double>(0, 1) = H2.at<double>(0, 1); H.at<double>(0, 2) = H2.at<double>(0, 2); H.at<double>(1, 0) = H2.at<double>(1, 0); H.at<double>(1, 1) = H2.at<double>(1, 1); H.at<double>(1, 2) = H2.at<double>(1, 2); cout << "H=" << H2 << endl; } else if (warp_type == "perspective") { H = findHomography(scene_cur, obj_last, CV_RANSAC, 3); if (H.empty()){ good_matches.clear(); good_matches2.clear(); scene_cur.clear(); obj_last.clear(); continue; } cout << "H=" << H << endl; } // using corelations and norms to find the errors and skip that frame. Bad matching can lead to bad homography matrix H.convertTo(H, CV_32F); H_old.convertTo(H_old, CV_32F); Mat correlation; matchTemplate(H_old, H, correlation, CV_TM_CCOEFF_NORMED); cout << "correlation:" << correlation << endl; double nownorms = norm(H - H_old, 2); H.convertTo(H, CV_64F); H_old.convertTo(H_old, CV_64F); cout << "now norm:" << nownorms << endl; cout << "miangin norm:" << norms << endl; if (norms == 0) norms = nownorms; if ((nownorms > 2 * norms) && (abs(correlation.at<float>(0)) < 0.8) || (nownorms > 10 * norms)) { if (!last_err && (counter != 1)) { cout << "Errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr" << endl; if (log_flag){ string name = "Error_frame_" + to_string(counter) + ".jpg"; imwrite(name, panorama_temp); } last_err = true; good_matches.clear(); good_matches2.clear(); scene_cur.clear(); obj_last.clear(); continue; } else last_err = false; } else{ norms = (norms* (counter - 1) + nownorms) / counter; last_err = false; } //take the x_offset and y_offset /*the offset matrix is of the type |1 0 x_offset | |0 1 y_offset | |0 0 1 | */ offset.at<double>(0, 2) = start_width; offset.at<double>(1, 2) = start_height; if (first_time_4pointfound == true && second_time_4pointfound == false) { H_kol = offset*H; second_time_4pointfound = true; } else { H_kol = H_kol*H; } cout << "Homography time: " << ((getTickCount() - t) / getTickFrequency()) << endl; t = getTickCount(); //using gpu for applying homography matrix to images gpu::GpuMat rImg_gpu, img_cur_gpu; img_cur_gpu.upload(img_cur); gpu::warpPerspective(img_cur_gpu, rImg_gpu, H_kol, size_wrap, INTER_NEAREST); rImg_gpu.download(rImg); cout << "warpPerspective time: " << ((getTickCount() - t) / getTickFrequency()) << endl; t = getTickCount(); //ROI for img1 t = getTickCount(); mask = cv::Mat::ones(final_img.size(), CV_8U) * 0; vector<Point2f> corners(4), corner_trans(4); corners[0] = Point2f(0, 0); corners[1] = Point2f(0, img.rows); corners[2] = Point2f(img.cols, 0); corners[3] = Point2f(img.cols, img.rows); perspectiveTransform(corners, corner_trans, H_kol); //making mask vector<Point> line1; int Most_top_x_corrner = 0; line1.push_back(corner_trans[0]); line1.push_back(corner_trans[2]); line1.push_back(corner_trans[3]); line1.push_back(corner_trans[1]); fillConvexPoly(mask, line1, Scalar::all(255), 4); line(mask, corner_trans[0], corner_trans[2], Scalar::all(0), 5, 4); line(mask, corner_trans[2], corner_trans[3], Scalar::all(0), 5, 4); line(mask, corner_trans[3], corner_trans[1], Scalar::all(0), 5, 4); line(mask, corner_trans[1], corner_trans[0], Scalar::all(0), 5, 4); cout << "mask time: " << ((getTickCount() - t) / getTickFrequency()) << endl; //applying img into final pano rImg.copyTo(final_img, mask); t = getTickCount(); //making gui red lines andd text for FPS final_img.copyTo(panorama_temp); line(final_img, corner_trans[0], corner_trans[2], CV_RGB(255, 0, 0), 5, 4); line(final_img, corner_trans[2], corner_trans[3], CV_RGB(255, 0, 0), 5, 4); line(final_img, corner_trans[3], corner_trans[1], CV_RGB(255, 0, 0), 5, 4); line(final_img, corner_trans[1], corner_trans[0], CV_RGB(255, 0, 0), 5, 4); fps = 1 / ((getTickCount() - start_app) / getTickFrequency()); putText(final_img, "fps=" + std::to_string(fps), Point2f(100, 100), CV_FONT_NORMAL, 1.5, CV_RGB(255, 0, 0), 4, 8); putText(final_img, "frame=" + std::to_string(counter), Point2f(100, 150), CV_FONT_NORMAL, 1.5, CV_RGB(255, 0, 0), 4, 8); namedWindow("Img", WINDOW_NORMAL); imshow("Img", final_img); gui_time = ((getTickCount() - t) / getTickFrequency()); cout << "GUI time: " << gui_time << endl; ////looop preparation t = getTickCount(); gray_curimage.copyTo(gray_lastimage); img_cur.copyTo(img_last); keypoints_last = keypoints_cur; descriptors_last = descriptors_cur; H.copyTo(H_old); last_err = false; time_algorithm+=(getTickCount() - start_algorithm) / getTickFrequency() - gui_time; time_complete+=(getTickCount() - start_app) / getTickFrequency() - gui_time; cout << "loop prepration time: " << ((getTickCount() - t) / getTickFrequency()) << endl; } else printf("match point are less than 3 or 4 for homography "); cout << "_________________________ " << endl; good_matches.clear(); good_matches2.clear(); key = waitKey(2); panorama_temp.copyTo(final_img); //exit if (key == 'e') break; //reseting fov if (key == 'r') { string name = "reset_frame_" + to_string(counter) + ".jpg"; imwrite(name, panorama_temp); panorama_temp = panorama_temp * 0; final_img = final_img * 0; H.at<double>(2, 0) = 0; H.at<double>(2, 1) = 0; H.at<double>(2, 2) = 1; H_kol.at<double>(0, 0) = 1; H_kol.at<double>(0, 1) = 0; H_kol.at<double>(0, 2) = 0; H_kol.at<double>(1, 0) = 0; H_kol.at<double>(1, 1) = 1; H_kol.at<double>(1, 2) = 0; H_kol.at<double>(2, 0) = 0; H_kol.at<double>(2, 1) = 0; H_kol.at<double>(2, 2) = 1; first_time_4pointfound = true; second_time_4pointfound = false; //copy current img in the middle of fov Mat f_roi(panorama_temp, Rect(start_width, start_height, img_last.cols, img_last.rows)); cap>>img_last; img_last.copyTo(f_roi); } } cout << "TOTal time from start: " << ((getTickCount() - start_app_main) / getTickFrequency()) << endl; cout << "Total time with hard/webcam consideration:" << time_complete<<endl; cout << "Total time algorithm:" << time_algorithm << endl; imwrite(save_pano_to, panorama_temp); }