blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
30a1a6ace8f97497f77b428f862a8eae50044595
|
1ab5a08b2993b0a7d61f8ff35557ad8cfcd70963
|
/src/rdtree_cursor.hpp
|
c3d3ee3aff3f6b3d02cdb919418661206899ee67
|
[
"BSD-3-Clause"
] |
permissive
|
rvianello/chemicalite
|
1a5346a216293e26ba5199cf61874e9f04af06db
|
79db94d394fca9d7e30f28ea2095446f98590382
|
refs/heads/master
| 2023-06-02T02:28:58.306742
| 2023-05-30T19:31:34
| 2023-05-30T19:31:34
| 9,153,859
| 39
| 5
|
NOASSERTION
| 2021-05-08T11:52:17
| 2013-04-01T19:08:41
|
C
|
UTF-8
|
C++
| false
| false
| 728
|
hpp
|
rdtree_cursor.hpp
|
#ifndef CHEMICALITE_RDTREE_CURSOR_INCLUDED
#define CHEMICALITE_RDTREE_CURSOR_INCLUDED
#include <memory>
#include <vector>
#include <sqlite3ext.h>
extern const sqlite3_api_routines *sqlite3_api;
class RDtreeNode;
class RDtreeConstraint;
/*
** Structure to store a deserialized rd-tree record.
*/
class RDtreeCursor : public sqlite3_vtab_cursor {
public:
using Constraints = std::vector<std::shared_ptr<RDtreeConstraint>>;
RDtreeNode *node; /* Node cursor is currently pointing at */
int item; /* Index of current item in pNode */
int strategy; /* Copy of idxNum search parameter */
Constraints constraints; /* Search constraints. */
};
#endif
|
58f2dcd8ecfeaecce480a6d9c8dce99061c72f81
|
c485cb363d29d81212427d3268df1ddcda64d952
|
/dependencies/CEGUI/Samples/common/include/CEGuiD3D9BaseApplication.h
|
86cf509bb78c08c4e514e1e6a8450bfa8453844f
|
[] |
no_license
|
peplopez/El-Rayo-de-Zeus
|
66e4ed24d7d1d14a036a144d9414ca160f65fb9c
|
dc6f0a98f65381e8280d837062a28dc5c9b3662a
|
refs/heads/master
| 2021-01-22T04:40:57.358138
| 2013-10-04T01:19:18
| 2013-10-04T01:19:18
| 7,038,026
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,965
|
h
|
CEGuiD3D9BaseApplication.h
|
/***********************************************************************
filename: CEGuiD3D9BaseApplication.h
created: 24/9/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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 _CEGuiD3D9BaseApplication_h_
#define _CEGuiD3D9BaseApplication_h_
#include "CEGuiBaseApplication.h"
#include "CEGUIGeometryBuffer.h"
#if defined( __WIN32__ ) || defined( _WIN32 )
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
// undefine Microsoft macro evilness
# undef min
# undef max
#endif
//Updated for linking of static libs
#if defined(_WIN32)
# pragma comment(lib, "d3d9.lib")
# if defined(_DEBUG)
# if defined(CEGUI_STATIC)
# pragma comment(lib, "CEGUIDirect3D9Renderer_Static_d.lib")
# else
# pragma comment(lib, "CEGUIDirect3D9Renderer_d.lib")
# endif
# else
# if defined(CEGUI_STATIC)
# pragma comment(lib, "CEGUIDirect3D9Renderer_Static.lib")
# else
# pragma comment(lib, "CEGUIDirect3D9Renderer.lib")
# endif
# endif
#endif
struct CEGuiBaseApplicationImpl;
class CEGuiD3D9BaseApplication : public CEGuiBaseApplication
{
public:
/*!
\brief
Constructor.
*/
CEGuiD3D9BaseApplication();
/*!
\brief
Destructor.
*/
~CEGuiD3D9BaseApplication();
// Implementation of base class abstract methods.
bool execute(CEGuiSample* sampleApp);
void cleanup();
protected:
/*************************************************************************
Implementation Methods
*************************************************************************/
/*!
\brief
Initialises Direct3D system.
*/
bool initialiseDirect3D(unsigned int width, unsigned int height, unsigned int adapter, bool windowed);
/*!
\brief
Do reset of Direct3D device
\return
- true if the device was reset successfully
- false if the device was not reset.
*/
bool resetDirect3D(void);
void doFPSUpdate(void);
bool overlayHandler(const CEGUI::EventArgs& args);
/*************************************************************************
Data fields
*************************************************************************/
CEGuiBaseApplicationImpl* pimpl;;
// counter used to track elapsed time (for time pulse injection)
DWORD d_lastFrameTime;
// FPS stuff
DWORD d_fps_lastTime;
int d_fps_frames;
int d_fps_value;
char d_fps_textbuff[16];
CEGUI::GeometryBuffer* d_fps_geometry;
CEGUI::GeometryBuffer* d_logo_geometry;
};
#endif // end of guard _CEGuiD3D9BaseApplication_h_
|
a6d15d3351714fc958fe5483c9c3133e11aaa5db
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_function_4812.cpp
|
ef804529fc25728cdee679d3305f4d24631941be
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,837
|
cpp
|
httpd_function_4812.cpp
|
void ssl_pphrase_Handle(server_rec *s, apr_pool_t *p)
{
SSLModConfigRec *mc = myModConfig(s);
SSLSrvConfigRec *sc;
server_rec *pServ;
char *cpVHostID;
char szPath[MAX_STRING_LEN];
EVP_PKEY *pPrivateKey;
ssl_asn1_t *asn1;
unsigned char *ucp;
long int length;
X509 *pX509Cert;
BOOL bReadable;
apr_array_header_t *aPassPhrase;
int nPassPhrase;
int nPassPhraseCur;
char *cpPassPhraseCur;
int nPassPhraseRetry;
int nPassPhraseDialog;
int nPassPhraseDialogCur;
BOOL bPassPhraseDialogOnce;
char **cpp;
int i, j;
ssl_algo_t algoCert, algoKey, at;
char *an;
char *cp;
apr_time_t pkey_mtime = 0;
apr_status_t rv;
/*
* Start with a fresh pass phrase array
*/
aPassPhrase = apr_array_make(p, 2, sizeof(char *));
nPassPhrase = 0;
nPassPhraseDialog = 0;
/*
* Walk through all configured servers
*/
for (pServ = s; pServ != NULL; pServ = pServ->next) {
sc = mySrvConfig(pServ);
if (!sc->enabled)
continue;
cpVHostID = ssl_util_vhostid(p, pServ);
ap_log_error(APLOG_MARK, APLOG_INFO, 0, pServ,
"Loading certificate & private key of SSL-aware server");
/*
* Read in server certificate(s): This is the easy part
* because this file isn't encrypted in any way.
*/
if (sc->server->pks->cert_files[0] == NULL
&& sc->server->pkcs7 == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, pServ,
"Server should be SSL-aware but has no certificate "
"configured [Hint: SSLCertificateFile] (%s:%d)",
pServ->defn_name, pServ->defn_line_number);
ssl_die();
}
algoCert = SSL_ALGO_UNKNOWN;
algoKey = SSL_ALGO_UNKNOWN;
for (i = 0, j = 0; i < SSL_AIDX_MAX
&& (sc->server->pks->cert_files[i] != NULL
|| sc->server->pkcs7); i++) {
if (sc->server->pkcs7) {
STACK_OF(X509) *certs = ssl_read_pkcs7(pServ,
sc->server->pkcs7);
pX509Cert = sk_X509_value(certs, 0);
i = SSL_AIDX_MAX;
} else {
apr_cpystrn(szPath, sc->server->pks->cert_files[i],
sizeof(szPath));
if ((rv = exists_and_readable(szPath, p, NULL))
!= APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Init: Can't open server certificate file %s",
szPath);
ssl_die();
}
if ((pX509Cert = SSL_read_X509(szPath, NULL, NULL)) == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
"Init: Unable to read server certificate from"
" file %s", szPath);
ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
ssl_die();
}
}
/*
* check algorithm type of certificate and make
* sure only one certificate per type is used.
*/
at = ssl_util_algotypeof(pX509Cert, NULL);
an = ssl_util_algotypestr(at);
if (algoCert & at) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
"Init: Multiple %s server certificates not "
"allowed", an);
ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
ssl_die();
}
algoCert |= at;
/*
* Insert the certificate into global module configuration to let it
* survive the processing between the 1st Apache API init round (where
* we operate here) and the 2nd Apache init round (where the
* certificate is actually used to configure mod_ssl's per-server
* configuration structures).
*/
cp = asn1_table_vhost_key(mc, p, cpVHostID, an);
length = i2d_X509(pX509Cert, NULL);
ucp = ssl_asn1_table_set(mc->tPublicCert, cp, length);
(void)i2d_X509(pX509Cert, &ucp); /* 2nd arg increments */
/*
* Free the X509 structure
*/
X509_free(pX509Cert);
/*
* Read in the private key: This is the non-trivial part, because the
* key is typically encrypted, so a pass phrase dialog has to be used
* to request it from the user (or it has to be alternatively gathered
* from a dialog program). The important point here is that ISPs
* usually have hundrets of virtual servers configured and a lot of
* them use SSL, so really we have to minimize the pass phrase
* dialogs.
*
* The idea is this: When N virtual hosts are configured and all of
* them use encrypted private keys with different pass phrases, we
* have no chance and have to pop up N pass phrase dialogs. But
* usually the admin is clever enough and uses the same pass phrase
* for more private key files (typically he even uses one single pass
* phrase for all). When this is the case we can minimize the dialogs
* by trying to re-use already known/entered pass phrases.
*/
if (sc->server->pks->key_files[j] != NULL)
apr_cpystrn(szPath, sc->server->pks->key_files[j++], sizeof(szPath));
/*
* Try to read the private key file with the help of
* the callback function which serves the pass
* phrases to OpenSSL
*/
myCtxVarSet(mc, 1, pServ);
myCtxVarSet(mc, 2, p);
myCtxVarSet(mc, 3, aPassPhrase);
myCtxVarSet(mc, 4, &nPassPhraseCur);
myCtxVarSet(mc, 5, &cpPassPhraseCur);
myCtxVarSet(mc, 6, cpVHostID);
myCtxVarSet(mc, 7, an);
myCtxVarSet(mc, 8, &nPassPhraseDialog);
myCtxVarSet(mc, 9, &nPassPhraseDialogCur);
myCtxVarSet(mc, 10, &bPassPhraseDialogOnce);
nPassPhraseCur = 0;
nPassPhraseRetry = 0;
nPassPhraseDialogCur = 0;
bPassPhraseDialogOnce = TRUE;
pPrivateKey = NULL;
for (;;) {
/*
* Try to read the private key file with the help of
* the callback function which serves the pass
* phrases to OpenSSL
*/
if ((rv = exists_and_readable(szPath, p,
&pkey_mtime)) != APR_SUCCESS ) {
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Init: Can't open server private key file "
"%s",szPath);
ssl_die();
}
/*
* if the private key is encrypted and SSLPassPhraseDialog
* is configured to "builtin" it isn't possible to prompt for
* a password after httpd has detached from the tty.
* in this case if we already have a private key and the
* file name/mtime hasn't changed, then reuse the existing key.
* we also reuse existing private keys that were encrypted for
* exec: and pipe: dialogs to minimize chances to snoop the
* password. that and pipe: dialogs might prompt the user
* for password, which on win32 for example could happen 4
* times at startup. twice for each child and twice within
* each since apache "restarts itself" on startup.
* of course this will not work for the builtin dialog if
* the server was started without LoadModule ssl_module
* configured, then restarted with it configured.
* but we fall through with a chance of success if the key
* is not encrypted or can be handled via exec or pipe dialog.
* and in the case of fallthrough, pkey_mtime and isatty()
* are used to give a better idea as to what failed.
*/
if (pkey_mtime) {
int i;
for (i=0; i < SSL_AIDX_MAX; i++) {
const char *key_id =
ssl_asn1_table_keyfmt(p, cpVHostID, i);
ssl_asn1_t *asn1 =
ssl_asn1_table_get(mc->tPrivateKey, key_id);
if (asn1 && (asn1->source_mtime == pkey_mtime)) {
ap_log_error(APLOG_MARK, APLOG_INFO,
0, pServ,
"%s reusing existing "
"%s private key on restart",
cpVHostID, ssl_asn1_keystr(i));
return;
}
}
}
cpPassPhraseCur = NULL;
ssl_pphrase_server_rec = s; /* to make up for sslc flaw */
/* Ensure that the error stack is empty; some SSL
* functions will fail spuriously if the error stack
* is not empty. */
ERR_clear_error();
bReadable = ((pPrivateKey = SSL_read_PrivateKey(szPath, NULL,
ssl_pphrase_Handle_CB, s)) != NULL ? TRUE : FALSE);
/*
* when the private key file now was readable,
* it's fine and we go out of the loop
*/
if (bReadable)
break;
/*
* when we have more remembered pass phrases
* try to reuse these first.
*/
if (nPassPhraseCur < nPassPhrase) {
nPassPhraseCur++;
continue;
}
/*
* else it's not readable and we have no more
* remembered pass phrases. Then this has to mean
* that the callback function popped up the dialog
* but a wrong pass phrase was entered. We give the
* user (but not the dialog program) a few more
* chances...
*/
#ifndef WIN32
if ((sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
|| sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE)
#else
if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE
#endif
&& cpPassPhraseCur != NULL
&& nPassPhraseRetry < BUILTIN_DIALOG_RETRIES ) {
apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect "
"(%d more retr%s permitted).\n",
(BUILTIN_DIALOG_RETRIES-nPassPhraseRetry),
(BUILTIN_DIALOG_RETRIES-nPassPhraseRetry) == 1 ? "y" : "ies");
nPassPhraseRetry++;
if (nPassPhraseRetry > BUILTIN_DIALOG_BACKOFF)
apr_sleep((nPassPhraseRetry-BUILTIN_DIALOG_BACKOFF)
* 5 * APR_USEC_PER_SEC);
continue;
}
#ifdef WIN32
if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
"Init: SSLPassPhraseDialog builtin is not "
"supported on Win32 (key file "
"%s)", szPath);
ssl_die();
}
#endif /* WIN32 */
/*
* Ok, anything else now means a fatal error.
*/
if (cpPassPhraseCur == NULL) {
if (nPassPhraseDialogCur && pkey_mtime &&
!isatty(fileno(stdout))) /* XXX: apr_isatty() */
{
ap_log_error(APLOG_MARK, APLOG_ERR, 0,
pServ,
"Init: Unable to read pass phrase "
"[Hint: key introduced or changed "
"before restart?]");
ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, pServ);
}
else {
ap_log_error(APLOG_MARK, APLOG_ERR, 0,
pServ, "Init: Private key not found");
ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, pServ);
}
if (writetty) {
apr_file_printf(writetty, "Apache:mod_ssl:Error: Private key not found.\n");
apr_file_printf(writetty, "**Stopped\n");
}
}
else {
ap_log_error(APLOG_MARK, APLOG_ERR, 0,
pServ, "Init: Pass phrase incorrect");
ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, pServ);
if (writetty) {
apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect.\n");
apr_file_printf(writetty, "**Stopped\n");
}
}
ssl_die();
}
if (pPrivateKey == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
"Init: Unable to read server private key from "
"file %s [Hint: Perhaps it is in a separate file? "
" See SSLCertificateKeyFile]", szPath);
ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
ssl_die();
}
/*
* check algorithm type of private key and make
* sure only one private key per type is used.
*/
at = ssl_util_algotypeof(NULL, pPrivateKey);
an = ssl_util_algotypestr(at);
if (algoKey & at) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
"Init: Multiple %s server private keys not "
"allowed", an);
ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
ssl_die();
}
algoKey |= at;
/*
* Log the type of reading
*/
if (nPassPhraseDialogCur == 0) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, pServ,
"unencrypted %s private key - pass phrase not "
"required", an);
}
else {
if (cpPassPhraseCur != NULL) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
pServ,
"encrypted %s private key - pass phrase "
"requested", an);
}
else {
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
pServ,
"encrypted %s private key - pass phrase"
" reused", an);
}
}
/*
* Ok, when we have one more pass phrase store it
*/
if (cpPassPhraseCur != NULL) {
cpp = (char **)apr_array_push(aPassPhrase);
*cpp = cpPassPhraseCur;
nPassPhrase++;
}
/*
* Insert private key into the global module configuration
* (we convert it to a stand-alone DER byte sequence
* because the SSL library uses static variables inside a
* RSA structure which do not survive DSO reloads!)
*/
cp = asn1_table_vhost_key(mc, p, cpVHostID, an);
length = i2d_PrivateKey(pPrivateKey, NULL);
ucp = ssl_asn1_table_set(mc->tPrivateKey, cp, length);
(void)i2d_PrivateKey(pPrivateKey, &ucp); /* 2nd arg increments */
if (nPassPhraseDialogCur != 0) {
/* remember mtime of encrypted keys */
asn1 = ssl_asn1_table_get(mc->tPrivateKey, cp);
asn1->source_mtime = pkey_mtime;
}
/*
* Free the private key structure
*/
EVP_PKEY_free(pPrivateKey);
}
}
/*
* Let the user know when we're successful.
*/
if (nPassPhraseDialog > 0) {
sc = mySrvConfig(s);
if (writetty) {
apr_file_printf(writetty, "\n"
"OK: Pass Phrase Dialog successful.\n");
}
}
/*
* Wipe out the used memory from the
* pass phrase array and then deallocate it
*/
if (aPassPhrase->nelts) {
pphrase_array_clear(aPassPhrase);
ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
"Init: Wiped out the queried pass phrases from memory");
}
/* Close the pipes if they were opened
*/
if (readtty) {
apr_file_close(readtty);
apr_file_close(writetty);
readtty = writetty = NULL;
}
return;
}
|
1b5ef6b4d02239a1f65d5ae49a9d914eabae3518
|
e96140fe29ac734c9985ba8835b13a38deda8a23
|
/extension/test/gui/test-style.cpp
|
b652605be85d329b5e3c373fef0c6b1f3bf30c00
|
[
"MIT"
] |
permissive
|
fanzcsoft/wxExtension
|
33efbd379188584d6ef6a2a08fff07ed7fc3e374
|
e99bd2c83502fac64db0aece657a480d0352d2ba
|
refs/heads/master
| 2020-03-27T04:36:04.115835
| 2018-08-17T18:45:56
| 2018-08-17T18:45:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,604
|
cpp
|
test-style.cpp
|
////////////////////////////////////////////////////////////////////////////////
// Name: test-style.cpp
// Purpose: Implementation for wxExtension unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2015 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <numeric>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/style.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/stc.h>
#include "test.h"
TEST_CASE("wxExStyle")
{
SUBCASE("Default constructor")
{
REQUIRE(!wxExStyle().IsOk() );
}
SUBCASE("Constructor using no and value")
{
for (const auto& style : std::vector<
std::pair<
std::pair<std::string,std::string>,
std::pair<std::string,std::string>>> {
{{"MARK_CIRCLE",""}, {"ugly","global"}},
{{"mark_circle","0 "}, {"ugly","global"}},
{{"512",""}, {"ugly","global"}},
{{"number,string,comment","1 4 6 "}, {"fore:blue", "cpp"}},
{{"number,string,xxx","4 6 "}, {"fore:black", "cpp"}},
{{"xxx",""}, {"fore:black", "cpp"}}})
{
// no, value, macro
const wxExStyle test(
style.first.first, style.second.first, style.second.second);
if (!style.first.second.empty())
{
REQUIRE( test.IsOk());
REQUIRE( test.GetNo() == style.first.second);
REQUIRE( test.GetValue() == style.second.first);
}
else
{
REQUIRE(!test.IsOk());
}
}
}
SUBCASE("Constructor using xml node")
{
pugi::xml_document doc;
REQUIRE( doc.load_string("<style no = \"2\">string</style>"));
REQUIRE( std::stoi(wxExStyle(doc.document_element(), "").GetNo()) == 2);
REQUIRE( wxExStyle(doc.document_element(), "").GetValue() == "fore:blue");
REQUIRE( std::stoi(wxExStyle(doc.document_element(), "cpp").GetNo()) == 2);
REQUIRE( wxExStyle(doc.document_element(), "").GetValue() == "fore:blue");
REQUIRE( doc.load_string("<style no = \"2\">styledefault+comment</style>"));
REQUIRE( wxExStyle(doc.document_element(), "cpp").GetValue().find("default") == std::string::npos);
REQUIRE( wxExStyle(doc.document_element(), "cpp").GetValue().find("comment") == std::string::npos);
REQUIRE( wxExStyle(doc.document_element(), "cpp").GetValue().find("+") == std::string::npos);
}
SUBCASE("Apply")
{
wxExStyle style("mark_circle", "0");
style.Apply(GetSTC());
REQUIRE( style.IsOk());
REQUIRE(!style.ContainsDefaultStyle());
wxExStyle().Apply(GetSTC());
}
}
|
049eead99ae0b0b911fec4908aaa332251a67709
|
9db8fe57921d005d3e4fd077fb084148ac2b2464
|
/mainwindow.cpp
|
af6821189da5ad493453b55b1178f1136c1c4650
|
[] |
no_license
|
cyt2017/caliberate
|
213aa803c810acfd59bbe31461940ebb04a6b7d7
|
50808d8838e3c9b90ee1277812548c1d17b0a2dd
|
refs/heads/master
| 2021-01-22T02:52:38.230678
| 2018-01-14T12:03:18
| 2018-01-14T12:03:18
| 102,255,064
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 8,443
|
cpp
|
mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->lineEdit_boardX->setText(QString::number(8));
ui->lineEdit_boardY->setText(QString::number(6));
ui->lineEdit_boardSize->setText("108.0");
connect(ui->startBtn,SIGNAL(clicked(bool)),this,SLOT(onStartBtn()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::qualifiedImage()
{
QString path = "./img/";
QDir dir(path);//!根据放图片的文件夹遍历图片
ui->textEdit->append(QString::fromLocal8Bit("正在进入目录:./img/\n"));
if(!dir.exists())
{
printf("dir empty...\n");
return ;
}
vecMat.clear();//!清空缓存图像
image_points_seq.clear();//!清空缓存 亚像素焦点检测到的关键点
image_size = Size(0,0);//!初始化图像大小
boardX = ui->lineEdit_boardX->text().toInt();//!从界面获取棋盘格的横向黑格数和纵向黑格数
boardY = ui->lineEdit_boardY->text().toInt();
board_size = Size(boardX,boardY);//!设置棋盘格的格子数目
boardSize = ui->lineEdit_boardSize->text().toFloat();
dir.setFilter(QDir::Files | QDir::NoSymLinks);
QFileInfoList imgList = dir.entryInfoList();
vector<Point2f> image_points_buf;
//!从文件夹遍历图片
for(int i=0;i<imgList.count();i++)
{
//!防止卡顿 设置响应事件的时间
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
fflush(NULL);
QString imgName = imgList[i].absoluteFilePath();
ui->textEdit->append(QString::fromLocal8Bit("正在处理"));
ui->textEdit->append(imgName);
Mat src = imread(imgName.toStdString());
if(src.empty())
{
printf("src.empty...\n");
continue;
}
//!把从文件读取的图像进行opencv中的棋盘格角点检测函数(findChessboardCorners),
//!如果检测不到角点返回NULL
if(0 == findChessboardCorners(src,board_size,image_points_buf))
{
printf("no corners\n");
continue;
}
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
fflush(NULL);
//!如果是输入的第一张图像,将图像的大小设置成第一张图像的大小,
//!使之后的图像的大小和第一张图像保持一致
if (image_size.width == 0)
{
image_size.width = src.cols;
image_size.height =src.rows;
}
else
{
if(image_size.width != src.cols || image_size.height !=src.rows)
{
printf("image_size error...\n");
exit(1);
}
}
//!把能通过棋盘格角点检测的图像保存到缓存中
vecMat.push_back(src);
Mat view_gray;
cvtColor(src,view_gray,CV_RGB2GRAY);//!图像灰度处理
//!为了找到精确度更高的角点位置,使用opencv的亚像素级焦点检测,
//!针对灰度图像把获取的角点保存起来
find4QuadCornerSubpix(view_gray,image_points_buf,Size(5,5));
image_points_seq.push_back(image_points_buf);
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
fflush(NULL);
}
}
void MainWindow::calibrate()
{//!进行标定
//!设置方格大小
Size square_size = Size(boardSize,boardSize);
vector<vector<Point3f> > object_points;
//!单目摄像头的内参数矩阵
Mat cameraMatrix=Mat(3,3,CV_32FC1,Scalar::all(0));
vector<int> point_counts;
//!单目摄像头的畸变矩阵
Mat distCoeffs=Mat(1,5,CV_32FC1,Scalar::all(0));
vector<Mat> tvecsMat;//!位移向量
vector<Mat> rvecsMat;//!旋转向量
ui->textEdit->append(QString::fromLocal8Bit("正在开始标定"));
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
fflush(NULL);
int image_count = vecMat.size();
int i,j,t;
for (t=0;t<image_count;t++)
{
vector<Point3f> tempPointSet;
for (i=0;i<board_size.height;i++)
{
for (j=0;j<board_size.width;j++)
{
Point3f realPoint;
realPoint.x = i*square_size.width;
realPoint.y = j*square_size.height;
realPoint.z = 0;
tempPointSet.push_back(realPoint);
}
}
//!世界坐标系中的点
object_points.push_back(tempPointSet);
}
for (i=0;i<image_count;i++)
{
point_counts.push_back(board_size.width*board_size.height);
}
//!相机标定
//!根据世界坐标系中的点和通过opencv亚像素查找到的点,
//!图像的大小,以及相机的内参和畸变参数获得平移和旋转变量
calibrateCamera(object_points,image_points_seq,image_size,cameraMatrix,distCoeffs,rvecsMat,tvecsMat,0);
cout<<"Calibrate………………done\n";
ui->textEdit->append(QString::fromLocal8Bit("标定结束,正在计算误差..."));
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
fflush(NULL);
cout<<"score precision………………\n";
double total_err = 0.0;
double err = 0.0;
vector<Point2f> image_points2;
// cout<<"\t每幅图像的标定误差:\n";
//// fout<<"每幅图像的标定误差:\n";
for (i=0;i<image_count;i++)
{
vector<Point3f> tempPointSet=object_points[i];
//!将世界坐标系中的点经过之前得到的旋转向量、平移向量、
//!相机内参和畸变参数,投影形成一张新图像(作用:可以使用该函数得到新的角点图像,
//!然后拿新图像与亚像素角点检测到的点进行误差运算)
projectPoints(tempPointSet,rvecsMat[i],tvecsMat[i],cameraMatrix,distCoeffs,image_points2);
//!得到亚像素图像中的某张图像中的角点
vector<Point2f> tempImagePoint = image_points_seq[i];
//!创建亚像素角点图像和世界坐标系中转换来的角点图像
Mat tempImagePointMat = Mat(1,tempImagePoint.size(),CV_32FC2);
Mat image_points2Mat = Mat(1,image_points2.size(), CV_32FC2);
//!给以上创建的图像进行赋值操作
for (int j = 0 ; j < tempImagePoint.size(); j++)
{
image_points2Mat.at<Vec2f>(0,j) = Vec2f(image_points2[j].x, image_points2[j].y);
tempImagePointMat.at<Vec2f>(0,j) = Vec2f(tempImagePoint[j].x, tempImagePoint[j].y);
}
//!通过亚像素图像和新角点图像计算误差
err = norm(image_points2Mat, tempImagePointMat, NORM_L2);
total_err += err/= point_counts[i];
// std::cout<<"第"<<i+1<<"幅图像的平均误差:"<<err<<"像素"<<endl;
// fout<<"第"<<i+1<<"幅图像的平均误差:"<<err<<"像素"<<endl;
}
std::cout<<"total_err:"<<total_err/image_count<<"pix"<<endl;
// fout<<"total_err:"<<total_err/image_count<<"pix"<<endl;
ui->textEdit->append(QString::fromLocal8Bit("误差:")+QString::number(total_err/image_count)+"pix");
std::cout<<"finish!"<<endl;
ui->textEdit->append(QString::fromLocal8Bit("标定完成:"));
QString str;
int ii = CV_ELEM_SIZE1(DataType<float>::depth);
int jj = cameraMatrix.elemSize1();
printf("ii:%d,jj:%d\n",ii,jj);
std::cout<<cameraMatrix;
fflush(NULL);
//!将相机内参和畸变参数打印出来
str.sprintf("cameraMatrix:\n%f,%f,%f\n%f,%f,%f\n%f,%f,%f\n",\
cameraMatrix.at<double>(0,0),cameraMatrix.at<double>(0,1),cameraMatrix.at<double>(0,2),\
cameraMatrix.at<double>(1,0),cameraMatrix.at<double>(1,1),cameraMatrix.at<double>(1,2),\
cameraMatrix.at<double>(2,0),cameraMatrix.at<double>(2,1),cameraMatrix.at<double>(2,2));
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
fflush(NULL);
ui->textEdit->append(str);
str.sprintf("distCoeffs:\n%f,%f,%f,%f,%f\n",\
distCoeffs.at<double>(0,0),distCoeffs.at<double>(0,1),distCoeffs.at<double>(0,2),\
distCoeffs.at<double>(0,3),distCoeffs.at<double>(0,4));
ui->textEdit->append(str);
QCoreApplication::processEvents(QEventLoop::AllEvents,10);
fflush(NULL);
}
void MainWindow::onStartBtn()
{
qualifiedImage();
calibrate();
}
|
24923ffa725f6de5911e51bd4c46b65c6895af9f
|
39fe085377f3c7327e82d92dcb38083d039d8447
|
/core/sql/optimizer/QRDescGenerator.cpp
|
4cb561ccefbf124888cab5d9a2cd5ffb6372e02e
|
[
"Apache-2.0"
] |
permissive
|
naveenmahadevuni/incubator-trafodion
|
0da8d4c7d13a47d3247f260b4e67618c0fae1539
|
ed24b19436530b2c214e4bf73280bc8e3f419669
|
refs/heads/master
| 2021-01-22T04:40:52.402291
| 2015-07-16T00:02:50
| 2015-07-16T00:02:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 120,514
|
cpp
|
QRDescGenerator.cpp
|
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// (C) Copyright 2008-2014 Hewlett-Packard Development Company, L.P.
//
// 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.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
**************************************************************************
*
* File: QRDescGenerator.cpp
* Description: Construction of query descriptor from QueryAnalysis
* Created: 01/24/2008
* Language: C++
*
**************************************************************************
*/
#include "Analyzer.h"
#include "QRDescGenerator.h"
#include "QRSharedPtr.h"
#include "RelGrby.h"
#include "NumericType.h"
#include "ItemLog.h"
#include "QRLogger.h"
#include "QRExprElement.h"
#include "RelUpdate.h"
const UInt32 QRDescGenerator::GENERATED_JBBID_START = 10000;
ULng32 hashString(const NAString& str) { return str.hash(); }
ULng32 hashValueId(const QRValueId& vid) { return vid; }
Visitor::VisitResult SetRefVisitor::visit(QRElementPtr caller)
{
NAString ref = caller->getRef();
if (ref == "")
return VR_Continue;
// Skip if not column, table, or joinpred
if (!strchr("CTJ", *ref.data()))
return VR_Continue;
QRElementPtr elem = idHash_.getFirstValue(&ref);
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
elem != NULL, QRLogicException,
"Referenced element %s does not exist.", ref.toCharStar());
caller->setReferencedElement(elem);
return VR_Continue;
}
//
// XmlValidatorVisitor
//
Visitor::VisitResult XmlValidatorVisitor::visit(QRElementPtr caller)
{
if (caller->getElementType() == ET_StringVal)
{
QRStringValPtr stringVal = static_cast<QRStringValPtr>(caller);
const NAString& value = stringVal->getValue();
if (value.contains('&') ||
value.contains('%') )
{
foundProblem_ = TRUE;
return VR_Stop;
}
}
else if (caller->getElementType() == ET_WStringVal)
{
QRWStringValPtr stringVal = static_cast<QRWStringValPtr>(caller);
const NAWString& value = stringVal->getWideValue();
if (na_wcschr(value, NAWCHR('&')) ||
na_wcschr(value, NAWCHR('%')) )
{
foundProblem_ = TRUE;
return VR_Stop;
}
}
return VR_Continue;
}
void EqualitySet::determineType()
{
QRTRACER("EqualitySet::determineType()");
if (isEmpty())
{
// I don't think this should happen.
// LCOV_EXCL_START :rfi
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
"determineType() called for empty EqualitySet.");
return;
// LCOV_EXCL_STOP
}
NABoolean isExact = FALSE, wasExact, isSigned = FALSE, isNullable = FALSE;
Lng32 magnitude = 0, otherMagnitude, scale = 0;
// Go through each member of the equality set, getting the parameters for the
// narrowest type common to them all (excluding a constant, if any).
NABoolean typeInitialized = FALSE;
for (CollIndex i=0; i<entries(); i++)
{
// Don't let the constant's type influence the eqset type.
if (at(i)->getOperatorType() == ITM_CONSTANT)
continue;
const NAType& t = at(i)->getValueId().getType();
if (t.getTypeQualifier() != NA_NUMERIC_TYPE)
{
// Eventually we should synthesize non-numeric types as well, but for
// now, just make sure the type is not null.
type_ = t.newCopy(heap_);
return;
}
const NumericType& nt = static_cast<const NumericType&>(t);
if (!typeInitialized)
{
// Initalize the type parameters to those of the first member.
// Regarding the computation of magnitude for float types, see the
// sad tale of precision for those types in the comment for
// NumericType::getTruePrecision(), and also note that getMagnitude()
// uses getPrecision() (which apparently can return 0 for floating
// point types) instead of getTruePrecision(). We add 1 to the
// calculated magnitude so it can be easily distinguished from
// decimal-precision exact numerics when we decide what type to
// create at the end of this function.
typeInitialized = TRUE;
isExact = nt.isExact();
isSigned = nt.isSigned();
isNullable = nt.supportsSQLnull();
magnitude = isExact ? nt.getMagnitude()
: nt.getTruePrecision() * 10 + 1;
scale = nt.getScale();
}
else
{
// Modify any type parameters that are more restrictive than those
// of this member.
wasExact = isExact;
if (nt.isExact())
isExact = TRUE;
if (!nt.isSigned())
isSigned = FALSE;
if (!nt.supportsSQLnull())
isNullable = FALSE;
otherMagnitude = nt.isExact() ? nt.getMagnitude()
: nt.getTruePrecision() * 10 + 1;
if (magnitude > otherMagnitude)
magnitude = otherMagnitude;
if (scale > nt.getScale() || !wasExact)
scale = nt.getScale();
}
}
// Create the type that supports a range of values common to all members of
// the equality set. Magnitude is divisible by 10 for decimal precision exact
// numerics.
if (magnitude % 10 > 0)
{
// Binary precision smallint, int, largeint, real, double)
if (magnitude < 50)
type_ = new(heap_) SQLSmall(isSigned, isNullable, heap_);
else if (magnitude < 100)
type_ = new(heap_) SQLInt(isSigned, isNullable, heap_);
else if (magnitude < 200)
type_ = new(heap_) SQLLargeInt(isSigned, isNullable, heap_);
else if (magnitude < 500)
type_ = new(heap_) SQLReal(isNullable, heap_);
else
type_ = new(heap_) SQLDoublePrecision(isNullable, heap_);
}
else
{
// @ZX need to amend this (and elsewhere) for SQLBigNum.
// Numeric or Decimal -- type will be generated as Numeric
const Int16 DisAmbiguate = 0;
type_ = new(heap_) SQLNumeric(isSigned, (magnitude / 10) + scale, scale,
DisAmbiguate, // added for 64bit proj.
isNullable);
}
} // determineType()
QRDescGenerator::~QRDescGenerator()
{
QRTRACER("QRDescGenerator::~QRDescGenerator()");
for (CollIndex i=0; i<allEqualitySets_.entries(); i++)
delete allEqualitySets_[i];
}
NABoolean QRDescGenerator::typeSupported(const NAType* type)
{
QRTRACER("QRDescGenerator::typeSupported()");
switch (type->getTypeQualifier())
{
case NA_NUMERIC_TYPE:
{
const NumericType* numType = static_cast<const NumericType*>(type);
// All approx numerics are ok.
if (!numType->isExact())
return TRUE;
// Don't handle software-supported types yet. This is of type BigNum only
if (numType->isBigNum())
return FALSE;
else
return TRUE;
}
case NA_CHARACTER_TYPE:
{
if ((CmpCommon::getDefault(MODE_SPECIAL_1) == DF_ON)||
(CmpCommon::getDefault(MODE_SPECIAL_2) == DF_ON))
return FALSE;
return ((CharType*)type)->getCollation() == CharInfo::DefaultCollation;
}
case NA_INTERVAL_TYPE:
{
// For interval types, we have to take into account that we represent
// values in terms of the lowest possible field for the interval
// category (year-month or day-time). Thus, we can't support the max
// leading field precision for specific interval types even when they
// don't include those lower fields.
const IntervalType* intvType = static_cast<const IntervalType*>(type);
switch (intvType->getStartField())
{
case REC_DATE_YEAR:
return (SQLInterval::MAX_LEADING_PRECISION >=
IntervalType::getPrecision(intvType->getStartField(),
intvType->getLeadingPrecision(),
REC_DATE_MONTH,
0));
case REC_DATE_MONTH:
return TRUE;
default:
// All day-time interval values are expressed in terms of microseconds.
return (SQLInterval::MAX_LEADING_PRECISION >=
IntervalType::getPrecision(intvType->getStartField(),
intvType->getLeadingPrecision(),
REC_DATE_SECOND,
SQLInterval::MAX_FRACTION_PRECISION));
}
}
case NA_DATETIME_TYPE:
// Remaining types are not yet supported.
//case NA_BOOLEAN_TYPE
//case NA_UNKNOWN_TYPE:
//case NA_USER_SUPPLIED_TYPE:
//case NA_RECORD_TYPE:
//case NA_ROWSET_TYPE:
return TRUE;
default:
return FALSE;
}
}
// -----------------------------------------------------------------------
NABoolean
QRDescGenerator::getTableId(ValueId vid,
CANodeId& nodeID, // OUT
ValueId& cvid, // OUT
ValueId& vegrefVid, // OUT
NAString& baseColName, // OUT
NABoolean& isExtraHub, // OUT
Int32& colIndex) // OUT
{
QRTRACER("QRDescGenerator::getTableId()");
ItemExpr *pExpr = vid.getItemExpr();
BaseColumn *pBC = 0;
cvid = vid;
vegrefVid = NULL_VALUE_ID;
if (pExpr->getOperatorType() == ITM_VEG_REFERENCE)
{
vegrefVid = vid;
const ValueIdSet &vegMembers = static_cast<VEGReference*>(pExpr)
->getVEG()->getAllValues();
// Search the veg members for a base column, so we can get its table id.
for (ValueId someMemberId=vegMembers.init();
!pBC && vegMembers.next(someMemberId);
vegMembers.advance(someMemberId))
{
if (someMemberId.getItemExpr()->getOperatorType() == ITM_BASECOLUMN)
{
cvid = someMemberId;
pBC = static_cast<BaseColumn*>(someMemberId.getItemExpr());
}
}
}
else if (pExpr->getOperatorType() == ITM_BASECOLUMN)
pBC = static_cast<BaseColumn*>(pExpr);
else if (pExpr->getOperatorType() == ITM_INDEXCOLUMN)
{
cvid = static_cast<IndexColumn*>(pExpr)->getDefinition();
pBC = static_cast<BaseColumn*>(cvid.getItemExpr());
}
if (pBC)
{
baseColName = pBC->getNAColumn()->getTableName()->getQualifiedNameAsAnsiString()
+ "." + pBC->getColName();
colIndex = pBC->getColNumber();
TableDesc *pTD = pBC->getTableDesc();
if (pTD)
{
if (vegrefVid == NULL_VALUE_ID)
{
ValueIdList baseCols;
ValueIdList vegCols;
baseCols.insert(pBC->getValueId());
pTD->getEquivVEGCols(baseCols, vegCols);
ItemExpr* ie = vegCols[0].getItemExpr();
if (ie->getOperatorType() == ITM_VEG_REFERENCE)
vegrefVid = ie->getValueId();
}
const TableAnalysis *pTA = pTD->getTableAnalysis();
if (pTA)
{
NodeAnalysis *pNA = pTA->getNodeAnalysis();
if (pNA)
{
nodeID = pNA->getId();
isExtraHub = pNA->isExtraHub();
return TRUE;
}
}
}
}
nodeID = NULL_CA_ID;
return FALSE;
} // getTableId()
CANodeId QRDescGenerator::getNodeId(ValueId vid)
{
QRTRACER("QRDescGenerator::getNodeId()");
// Required arguments to getTableId(). All we want here is the node id.
CANodeId nodeId;
ValueId dummyVid;
ValueId dummyVid2;
NAString dummyString;
NABoolean dummyBool;
Int32 colIndex;
getTableId(vid, nodeId, dummyVid, dummyVid2, dummyString, dummyBool, colIndex);
return nodeId;
}
// -----------------------------------------------------------------------
QRColumnPtr QRDescGenerator::genQRColumn(ValueId vid,
UInt32 joinPredId /*= 0*/,
NABoolean markAsUsed /*= TRUE*/)
{
QRTRACER("QRDescGenerator::genQRColumn()");
NABoolean isExtraHub;
CANodeId nodeID;
ValueId col_vid;
ValueId vegref_vid;
NAString baseColName;
Int32 colIndex;
NABoolean gotNodeID = getTableId(vid, nodeID, col_vid, vegref_vid,
baseColName, isExtraHub, colIndex);
if (!gotNodeID)
{
// This should be a vegref to an instantiate_null for a LOJ.
ItemExpr* itemExpr = vid.getItemExpr();
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
isInstNull(itemExpr), QRDescriptorException,
"genQRColumn called for ValueID that is neither column nor "
"instantiate_null function");
return skipInstNull(itemExpr);
}
QRColumnPtr columnElement = new(mvqrHeap_) QRColumn(ADD_MEMCHECK_ARGS(mvqrHeap_));
if (bGenColumnRefs_)
{
if (mColumnsUsed_.contains(col_vid))
{
// Note the early return if we reference an existing column,
// which avoids setting other column properties below.
columnElement->setRefFromInt(col_vid, FALSE);
columnElement->setReferencedElement(getElementForValueID('C', col_vid));
if (mExtraHubColumnsUsed_.contains(col_vid))
columnElement->setExtraHub(TRUE);
return columnElement;
}
else if (markAsUsed) // not when called by setPredBitmap()
{
mColumnsUsed_ += col_vid;
if (isExtraHub)
mExtraHubColumnsUsed_ += col_vid;
}
}
columnElement->setFullyQualifiedColumnName(baseColName);
columnElement->setAndRegisterID(col_vid, colTblIdHash_);
columnElement->setTableID((Int32)nodeID);
columnElement->setExtraHub(isExtraHub);
columnElement->setVegrefId(vegref_vid);
columnElement->setColIndex(colIndex);
columnElement->setNullable(vid.getType().supportsSQLnull());
// If col_vid is the value id of a column used in a join pred, it should
// reference the id of the join pred.
ValueId mappedVid, vegVid;
colToJoinPredMap_.mapValueIdUp(mappedVid, col_vid);
if (mappedVid != col_vid) // returns same value if not mapped
{
ItemExpr* cvie = col_vid.getItemExpr();
if (cvie->getOperatorType() == ITM_BASECOLUMN)
{
BaseColumn* bc = static_cast<BaseColumn*>(cvie);
vegVid = bc->getTableDesc()->getColumnVEGList()[bc->getColNumber()];
}
else
vegVid = mappedVid;
if (mappedVid == vegVid)
{
columnElement->setVegrefId(vegref_vid);
}
}
return columnElement;
} // genQRColumn()
NABoolean QRDescGenerator::isInstNull(ItemExpr* itemExpr)
{
QRTRACER("isInstNull()");
if (itemExpr->getOperatorType() == ITM_INSTANTIATE_NULL)
return TRUE;
if (itemExpr->getOperatorType() != ITM_VEG_REFERENCE)
return FALSE;
const ValueIdSet& vegMembers =
((VEGReference*)itemExpr)->getVEG()->getAllValues();
ValueId firstMemberId = vegMembers.init();
vegMembers.next(firstMemberId); // 1st call to next positions it on 1st member
ItemExpr* firstMemberExpr = firstMemberId.getItemExpr();
return (firstMemberExpr->getOperatorType() == ITM_INSTANTIATE_NULL);
}
QRColumnPtr QRDescGenerator::skipInstNull(ItemExpr* itemExpr)
{
QRTRACER("QRDescGenerator::skipInstNull()");
QRColumnPtr result = NULL;
OperatorTypeEnum opType = itemExpr->getOperatorType();
if (opType == ITM_VEG_REFERENCE)
{
const ValueIdSet& vegMembers =
((VEGReference*)itemExpr)->getVEG()->getAllValues();
ValueId firstMemberId = vegMembers.init();
vegMembers.next(firstMemberId); // 1st call to next positions it on 1st member
itemExpr = firstMemberId.getItemExpr();
opType = itemExpr->getOperatorType();
}
if (opType == ITM_INSTANTIATE_NULL)
{
// The instantiated null column is part of a join pred.
// Do not reference that join pred, and create a full QRColumn element instead.
setGenColumnRefs(FALSE);
result = genQRColumn(itemExpr->child(0));
setGenColumnRefs(TRUE);
NAString* idstr = new(mvqrHeap_) NAString(result->getID());
result->setAndRegisterID(itemExpr->getValueId(), colTblIdHash_); // Set the ID of the InstantiateNull function.
colTblIdHash_.insert(idstr, result);
}
return result;
}
// Static nonmember helper function, called by QRDescGenerator::getExprTree()
// to add extra parameters to certain functions.
static void addFunctionParameters(ItemExpr* ie,
NAMemory* heap,
QRFunctionPtr function)
{
QRTRACER("addFunctionParameters()");
QRParameterPtr param = new(heap) QRParameter(ADD_MEMCHECK_ARGS(heap));
switch (ie->getOperatorType())
{
case ITM_EXTRACT:
case ITM_EXTRACT_ODBC:
{
Extract* extractFn = static_cast<Extract*>(ie);
param->setName("extractField");
param->setValue((Int32)extractFn->getExtractField());
function->addHiddenParam(param);
}
break;
case ITM_TRIM:
{
Trim* trimFn = static_cast<Trim*>(ie);
param->setName("mode");
param->setValue((Int32)trimFn->getTrimMode());
function->addHiddenParam(param);
}
break;
case ITM_TRANSLATE:
{
Translate* translateFn = static_cast<Translate*>(ie);
param->setName("mapTableId");
param->setValue((Int32)translateFn->getTranslateMapTableId());
function->addHiddenParam(param);
}
break;
case ITM_DATEFORMAT:
{
// Only include the parameter if it is one of the predefined values
// DEFAULT, USA, or EUROPEAN. The other possible values indicate that
// a format string is used to determine the format, and this takes
// the form of an explicit operand in the ItemExpr tree.
DateFormat* dateFormatFn = static_cast<DateFormat*>(ie);
Int32 dateFormat = dateFormatFn->getDateFormat();
if (dateFormat == DateFormat::DEFAULT ||
dateFormat == DateFormat::USA ||
dateFormat == DateFormat::EUROPEAN)
{
param->setName("dateFormat");
param->setValue(dateFormat);
function->addHiddenParam(param);
}
else
deletePtr(param);
}
break;
case ITM_COMP_ENCODE:
case ITM_COMP_DECODE:
{
CompEncode* encodeFn = static_cast<CompEncode*>(ie);
param->setName("descFlag");
param->setValue(encodeFn->getDescFlag());
function->addHiddenParam(param);
param = new(heap) QRParameter(ADD_MEMCHECK_ARGS(heap));
param->setName("caseInsensitiveEncode");
param->setValue(encodeFn->getCaseInsensitiveEncode());
function->addHiddenParam(param);
param = new(heap) QRParameter(ADD_MEMCHECK_ARGS(heap));
param->setName("encodedCollation");
param->setValue(encodeFn->getEncodedCollation());
function->addHiddenParam(param);
param = new(heap) QRParameter(ADD_MEMCHECK_ARGS(heap));
param->setName("collationType");
param->setValue(encodeFn->getCollationType());
function->addHiddenParam(param);
}
break;
case ITM_FORMAT:
{
Format* formatFn = static_cast<Format*>(ie);
param->setName("formatStr");
param->setValue(formatFn->getFormatStr());
function->addHiddenParam(param);
param = new(heap) QRParameter(ADD_MEMCHECK_ARGS(heap));
param->setName("formatType");
param->setValue(formatFn->getFormatType());
function->addHiddenParam(param);
param = new(heap) QRParameter(ADD_MEMCHECK_ARGS(heap));
param->setName("formatCharToDate");
param->setValue(formatFn->getFormatCharToDate());
function->addHiddenParam(param);
}
break;
// We will hit this for OLAP and sequence functions for the time being.
// These are not handled by MVQR yet, and the hidden parameters for these
// functions have not been addressed.
default:
deletePtr(param);
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
FALSE, QRDescriptorException,
"Unhandled function type in addFunctionParameters(): %d",
ie->getOperatorType());
break;
}
}
QRExplicitExprPtr QRDescGenerator::getExprTree(ItemExpr* itemExpr)
{
QRTRACER("QRDescGenerator::getExprTree()");
NABoolean valueWasSet=FALSE;
if (itemExpr->getOperatorType() == ITM_RANGE_SPEC_FUNC)
{
RangeSpecRef* range = static_cast<RangeSpecRef*>(itemExpr);
itemExpr = range->getRangeObject()->getRangeItemExpr();
}
else if (itemExpr->getOperatorType() == ITM_INSTANTIATE_NULL)
{
return getExprTree(itemExpr->child(0));
}
switch (itemExpr->getQRExprElem())
{
case QR::QRFunctionElem:
case QR::QRFunctionWithParameters:
{
QRFunctionPtr function =
new(mvqrHeap_) QRFunction(ADD_MEMCHECK_ARGS(mvqrHeap_));
function->setID(itemExpr->getValueId());
function->setFunctionName(itemExpr->getText());
if (itemExpr->isAnAggregate())
{
Aggregate* aggrFunc = static_cast<Aggregate*>(itemExpr);
function->setAggregateFunc(itemExpr->getOperatorType(), aggrFunc->isDistinct());
}
for (Int32 argInx=0; argInx<itemExpr->getArity(); argInx++)
function->addArgument(getExprTree(itemExpr->child(argInx)));
// Extra work for functions like ExtractOdbc that take non-ItemExpr
// parameters.
if (itemExpr->getQRExprElem() == QR::QRFunctionWithParameters)
addFunctionParameters(itemExpr, mvqrHeap_, function);
return function;
}
break;
case QR::QRBinaryOperElem:
{
QRBinaryOperPtr binaryOper =
new(mvqrHeap_) QRBinaryOper(ADD_MEMCHECK_ARGS(mvqrHeap_));
binaryOper->setID(itemExpr->getValueId());
binaryOper->setOperator(itemExpr->getText());
binaryOper->setFirstOperand(getExprTree(itemExpr->child(0)));
binaryOper->setSecondOperand(getExprTree(itemExpr->child(1)));
return binaryOper;
}
break;
case QR::QRUnaryOperElem:
{
QRUnaryOperPtr unaryOper =
new(mvqrHeap_) QRUnaryOper(ADD_MEMCHECK_ARGS(mvqrHeap_));
unaryOper->setID(itemExpr->getValueId());
unaryOper->setOperator(itemExpr->getText());
unaryOper->setOperand(getExprTree(itemExpr->child(0)));
return unaryOper;
}
break;
case QR::QRColumnElem:
{
QRElementPtr elem = NULL;
if (isInstNull(itemExpr))
return skipInstNull(itemExpr);
// VEGReference will return QRColumnElem. If this is a vegref, use a
// constant member of the veg if there is one. An expr with more than
// one column won't be accepted by qms as a range pred.
if (itemExpr->getOperatorType() == ITM_VEG_REFERENCE)
{
ValueId constVid =
static_cast<VEGReference*>(itemExpr)->getVEG()->getAConstant(TRUE);
if (constVid != NULL_VALUE_ID)
return getExprTree(constVid.getItemExpr());
}
// If a vegref, it may have an instantiate_null as the first veg
// member if outer joins are involved.
elem = genQRColumn(itemExpr->getValueId());
ElementType elemType = elem->getElementType();
if (elemType == ET_Column)
return elem->downCastToQRColumn();
else if (elemType == ET_Function)
return elem->downCastToQRFunction();
else
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
FALSE, QRDescriptorException,
"Unhandled element type returned from genQRColumn() in getExprTree(): %d",
elemType);
}
break;
case QR::QRScalarValueElem:
{
ConstValue* constVal;
OperatorTypeEnum op = itemExpr->getOperatorType();
if (op == ITM_CACHE_PARAM)
constVal = (static_cast<ConstantParameter*>(itemExpr))->getConstVal();
else
{
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
op == ITM_CONSTANT, QRDescriptorException,
"In getExprTree(), expected ITM_CONSTANT but got %d",
op);
constVal = static_cast<ConstValue*>(itemExpr);
}
if (constVal->isNull())
return new (mvqrHeap_) QRNullVal(ADD_MEMCHECK_ARGS(mvqrHeap_));
const NAType* type = constVal->getType();
QRScalarValuePtr scalar = NULL;
switch (type->getTypeQualifier())
{
case NA_NUMERIC_TYPE:
if (((NumericType*)type)->isExact())
{
scalar = new (mvqrHeap_)
QRNumericVal(ADD_MEMCHECK_ARGS(mvqrHeap_));
((QRNumericValPtr)scalar)->setScale(istring(type->getScale()));
}
else
scalar = new (mvqrHeap_) QRFloatVal(ADD_MEMCHECK_ARGS(mvqrHeap_));
break;
case NA_DATETIME_TYPE:
case NA_INTERVAL_TYPE:
scalar = new (mvqrHeap_)
QRNumericVal(ADD_MEMCHECK_ARGS(mvqrHeap_));
((QRNumericValPtr)scalar)->setScale(istring(type->getScale()));
break;
case NA_CHARACTER_TYPE:
if (((CharType*)type)->getBytesPerChar() == 1)
scalar = new (mvqrHeap_) QRStringVal(ADD_MEMCHECK_ARGS(mvqrHeap_));
else
{
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
((CharType*)type)->getBytesPerChar() == 2,
QRDescriptorException,
"Unhandled bytes-per-char: %d",
((CharType*)type)->getBytesPerChar());
QRWStringValPtr wideScalar = new (mvqrHeap_) QRWStringVal(ADD_MEMCHECK_ARGS(mvqrHeap_));
wideScalar->setWideValue(constVal->getConstWStr());
scalar = wideScalar;
valueWasSet = TRUE;
}
break;
default:
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
"Unhandled data type: %d (%s)",
type->getTypeQualifier(), type->getTypeName().toCharStar());
scalar = new (mvqrHeap_) QRStringVal(ADD_MEMCHECK_ARGS(mvqrHeap_));
break;
}
if (scalar)
{
if (!valueWasSet)
scalar->setValue(constVal->getText());
scalar->setID(itemExpr->getValueId());
if (isDumpMvMode())
{
// Add the "official" unparsed text of the expression as a sub-element.
NAString unparsedText;
itemExpr->unparse(unparsedText, OPTIMIZER_PHASE, QUERY_FORMAT);
scalar->setSql(unparsedText);
}
}
return scalar;
}
break;
// LCOV_EXCL_START :rfi
case QR::QRNoElem:
default:
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
FALSE, QRDescriptorException,
"Unhandled ExprElement enum value: %d",
itemExpr->getQRExprElem());
return NULL;
// LCOV_EXCL_STOP
}
// make the compiler happy
return NULL;
} // getExprTree()
// -----------------------------------------------------------------------
QRExprPtr
QRDescGenerator::genQRExpr(ItemExpr* pExpr,
NABoolean isResidual,
UInt32 joinPredId)
{
QRExprPtr exprElement;
QRTRACER("QRDescGenerator::genQRExpr()");
NABoolean isNotProvided = FALSE;
// Was this expression already generated?
QRElementPtr existingElem = getElementForValueID('X', pExpr->getValueId());
if (existingElem)
{
// Yes, just reference the other element.
exprElement = new(mvqrHeap_) QRExpr(isResidual, ADD_MEMCHECK_ARGS(mvqrHeap_));
exprElement->setRef(existingElem->getID());
exprElement->setReferencedElement(existingElem);
return exprElement;
}
Lng32 treeDepth = 0;
Lng32 exprSize = pExpr->getTreeSize(treeDepth, 0);
if (exprSize > maxExprSize_ || treeDepth > maxExprDepth_)
{
if (isQueryMode() || isDumpMvMode())
isNotProvided = TRUE;
else
throw QRDescriptorException("Expression too complex");
}
// If the expression is a member of an equality set, it consists of a ref
// attribute to the join pred for that equality set.
if (joinPredId)
{
exprElement = new(mvqrHeap_) QRExpr(isResidual, ADD_MEMCHECK_ARGS(mvqrHeap_));
exprElement->setRefFromInt(joinPredId, TRUE);
return exprElement;
}
exprElement = new(mvqrHeap_) QRExpr(isResidual, ADD_MEMCHECK_ARGS(mvqrHeap_));
exprElement->setAndRegisterID(pExpr->getValueId(), colTblIdHash_);
if (isDumpMvMode())
{
// Add the "official" unparsed text of the expression as a sub-element.
NAString unparsedText;
pExpr->unparse(unparsedText, OPTIMIZER_PHASE, QUERY_FORMAT);
if (unparsedText.first('%') != NA_NPOS ||
unparsedText.first('&') != NA_NPOS )
{
// Can't handle special characters that cause XML parsing problems
// or sprintf() problems.
isNotProvided = TRUE;
}
if (!isNotProvided)
{
QRInfoPtr info = new QRInfo(ADD_MEMCHECK_ARGS(mvqrHeap_));
info->setText(unparsedText);
exprElement->setInfo(info);
}
}
if (isNotProvided)
{
// This expression is either too big or using the '%' or '&' characters,
// which can cause problems during XML parsing or SQL generation, so we
// skip it and mark it as NotProvided for QMS. We just need to provide
// the expression's input columns.
exprElement->setResult(QRElement::NotProvided);
// Use a fake function element to hold the list of input columns.
QRFunctionPtr fakeFunction = new(mvqrHeap_) QRFunction(ADD_MEMCHECK_ARGS(mvqrHeap_));
fakeFunction->setID(pExpr->getValueId());
fakeFunction->setFunctionName("fake function");
ValueIdSet vegrefsInExpr;
pExpr->findAll(ITM_VEG_REFERENCE, vegrefsInExpr, FALSE, FALSE);
for (ValueId vegrefVid=vegrefsInExpr.init();
vegrefsInExpr.next(vegrefVid);
vegrefsInExpr.advance(vegrefVid))
{
ItemExpr* itemExpr = vegrefVid.getItemExpr();
QRColumnPtr col = genQRColumn(itemExpr->getValueId());
fakeFunction->addArgument(col);
}
exprElement->setExprRoot(fakeFunction);
}
else
{
// Generate the tree-structured representation of the expression.
QRExplicitExprPtr treeExpr = getExprTree(pExpr);
exprElement->setExprRoot(treeExpr);
}
return exprElement;
} // genQRExpr()
// -----------------------------------------------------------------------
// LCOV_EXCL_START :cnu
NABoolean
QRDescGenerator::normalizeColumnInExpression(NAString& pExprText,
ValueId colvid,
short paramIndex)
{
QRTRACER("QRDescGenerator::normalizeColumnInExpression()");
NABoolean bColFound = FALSE;
NABoolean bFirst = TRUE;
NAString sReplacement = "@A";
NAString sFQColName;
sFQColName = ((BaseColumn *) colvid.getItemExpr())->getText();
size_t dPos = 0;
size_t dIndex = 0;
NABoolean bDone = FALSE;
while (!bDone)
{
dIndex = pExprText.index(sFQColName, dPos, NAString::exact);
if (dIndex != NA_NPOS)
{
if (bFirst)
{
sReplacement += istring(paramIndex);
bColFound = TRUE;
bFirst = FALSE;
}
pExprText.replace(dIndex, sFQColName.length(), sReplacement);
dPos += sReplacement.length();
}
else
{
bDone = TRUE;
}
}
return bColFound;
} // normalizeColumnInExpression()
// LCOV_EXCL_STOP
void QRDescGenerator::markColumnsAsResidual(ValueIdSet& vegrefsInExpr)
{
QRTRACER("QRDescGenerator::markColumnsAsResidual()");
ValueIdSet baseColsInExpr;
// Iterate over vegrefs in the expression. For each of those, find all the base
// columns in its veg. Mark them all as being used in a residual predicate.
// Avoid including base columns that are equated to a constant.
for (ValueId vegrefVid=vegrefsInExpr.init();
vegrefsInExpr.next(vegrefVid);
vegrefsInExpr.advance(vegrefVid))
{
ItemExpr* itemExpr = vegrefVid.getItemExpr();
if (itemExpr->getOperatorType() == ITM_VEG_REFERENCE &&
static_cast<VEGReference*>(itemExpr)->getVEG()->getAConstant()
== NULL_VALUE_ID)
vegrefVid.getItemExpr()->findAll(ITM_BASECOLUMN, baseColsInExpr, TRUE, TRUE);
else if (itemExpr->getOperatorType() == ITM_BASECOLUMN)
baseColsInExpr.addElement(vegrefVid);
}
// Have all the columns used in the residual predicate, now set their bits in
// the residual pred bitmap.
for (ValueId colVid=baseColsInExpr.init();
baseColsInExpr.next(colVid);
baseColsInExpr.advance(colVid))
{
setPredBitmap(colVid, ET_ResidualPred); // mark use of resid pred on col
}
}
// -----------------------------------------------------------------------
void QRDescGenerator::processResidualPredicate(ValueId predVid,
QRJBBPtr jbbElement)
{
QRTRACER("QRDescGenerator::processResidualPredicate()");
ItemExpr* predItemExpr = predVid.getItemExpr();
QRExprPtr residualPredExpr = genQRExpr(predItemExpr, TRUE);
// Set bits in residual predicate bitmap for all columns referenced in the
// expression.
ValueIdSet vegrefsInExpr;
predItemExpr->findAll(ITM_VEG_REFERENCE, vegrefsInExpr, FALSE, FALSE);
markColumnsAsResidual(vegrefsInExpr);
// Residual predicates can only be on Hub tables.
jbbElement->getHub()->getResidualPredList()->addItem(residualPredExpr);
}
// -----------------------------------------------------------------------
void QRDescGenerator::processGroupBy(RelExpr* groupByNode,
CANodeId gbID,
QRJBBPtr jbbElement)
{
if (groupByNode->getOperator() != REL_GROUPBY)
return;
QRTRACER("QRDescGenerator::processGroupBy()");
GroupByAgg* groupBy = (GroupByAgg *)groupByNode;
QRGroupByPtr groupByElement = new(mvqrHeap_) QRGroupBy(ADD_MEMCHECK_ARGS(mvqrHeap_));
jbbElement->setGroupBy(groupByElement);
QRElementPtr groupItem = NULL;
ValueIdSet gbvis = groupBy->groupExpr();
// Both the hub and extra-hub GroupBy can have the same ID since they are both
// based on the same RelExpr node with the same NodeID. In QMS, the ID from the
// hub GroupBy element will be the only one actually used.
groupByElement->setID(gbID);
for (ValueId gbvid = gbvis.init();
gbvis.next(gbvid);
gbvis.advance(gbvid))
{
ItemExpr *pExpr = gbvid.getItemExpr();
if (isInstNull(pExpr))
groupItem = skipInstNull(pExpr);
else if (pExpr->getOperatorType() == ITM_VEG_REFERENCE)
groupItem = genQRColumn(gbvid);
else
{
// This is an expression.
groupItem = genQRExpr(pExpr, FALSE);
}
groupByElement->getPrimaryList()->addElement(groupItem);
}
} // processGroupBy()
// -----------------------------------------------------------------------
void
QRDescGenerator::processOutputList(const ValueIdSet& normOutputs,
QRJBBPtr jbbElement)
{
QRTRACER("QRDescGenerator::processOutputList()");
QROutputListPtr outputListElement = jbbElement->getOutputList();
const ColumnDescList* mvColList = (isMvMode()
? relExpr_->getRETDesc()->getColumnList()
: NULL);
CollIndex mvNumCols = (mvColList ? mvColList->entries() : 0);
CollIndex outInx, cdInx;
ValueId cvid;
for (cvid = normOutputs.init(), outInx = 0;
normOutputs.next(cvid);
normOutputs.advance(cvid), outInx++)
{
ItemExpr *cvExpr = cvid.getItemExpr();
QROutputPtr qro_p = new(mvqrHeap_) QROutput(ADD_MEMCHECK_ARGS(mvqrHeap_));
if (mvColList)
{
NABoolean found = FALSE;
const OperatorTypeEnum cvExprOp = cvExpr->getOperatorType();
for (cdInx=0; cdInx<mvNumCols && !found; cdInx++)
{
ValueId mvColVid = mvColList->at(cdInx)->getValueId();
if (cvid == mvColVid)
found = TRUE;
// Note that we can't just break out of the for loop if 'found'
// becomes true, because code after the loop makes assumptions
// about the loop index value.
if (!found)
{
ItemExpr* mvExpr = mvColVid.getItemExpr();
OperatorTypeEnum op = mvExpr->getOperatorType();
while (op == ITM_CAST || op == ITM_INSTANTIATE_NULL)
{
mvExpr = mvExpr->child(0);
op = mvExpr->getOperatorType();
}
mvColVid = mvExpr->getValueId();
if (cvid == mvColVid)
found = TRUE;
}
if (!found && cvExprOp == ITM_VEG_REFERENCE)
{
const ValueIdSet& cvVegVids =
((VEGReference*)cvExpr)->getVEG()->getAllValues();
found = cvVegVids.contains(mvColVid);
}
}
// If we did not find the ordinal number of the column, throw an
// exception now, so that an MV descriptor will not be created.
Int32 cvid_i = cvid;
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
found, QRDescriptorException,
"No matching MV column found for output item with "
"ValueId %d", cvid_i);
// Set the ordinal position of the output item within the MV's select
// list, so we can match it to the right column name once the column
// names are known for sure.
qro_p->setColPos((Int32)cdInx-1);
}
if (isInstNull(cvExpr))
{
QRColumnPtr col = skipInstNull(cvExpr);
qro_p->setOutputItem(col);
}
else if (cvExpr->getOperatorType() != ITM_VEG_REFERENCE)
{
QRExprPtr exprElement = genQRExpr(cvExpr, FALSE);
qro_p->setOutputItem(exprElement);
}
else
{
QRElementPtr element = genQRColumn(cvid);
qro_p->setOutputItem(element);
}
qro_p->setID(cvid);
outputListElement->addItem(qro_p);
}
} // processOutputList()
// Nonmember function to write the graphviz specification of the join order
// predecessor requirements to the log.
static void logJBBCPredecessorGraph(CANodeIdSet& jbbcs)
{
NAString graphString(STMTHEAP);
graphString += "\n#STARTJOINORDER\n"
"digraph \"\"\n"
"{\n"
" label=\"Predecessor Relationships\"\n";
char buf[200];
for (CANodeId nodeId = jbbcs.init(); jbbcs.next(nodeId); jbbcs.advance(nodeId))
{
NodeAnalysis* nodeAnalysis = nodeId.getNodeAnalysis();
if (!nodeAnalysis)
continue;
JBBC* jbbc = nodeAnalysis->getJBBC();
if (!jbbc)
continue;
TableAnalysis* tableAnalysis = nodeAnalysis->getTableAnalysis();
if (!tableAnalysis)
continue;
CorrName& corrName = tableAnalysis->getTableDesc()->getCorrNameObj();
NAString nodeLabel = corrName.getCorrNameAsString();
if (nodeLabel.length() == 0)
nodeLabel = corrName.getQualifiedNameAsString();
sprintf(buf, " n%d [label=\"%s\"];\n", (CollIndex)nodeId, nodeLabel.data());
graphString += buf;
const CANodeIdSet& predecessors = jbbc->getPredecessorJBBCs();
for (CANodeId predNodeId = predecessors.init();
predecessors.next(predNodeId);
predecessors.advance(predNodeId))
{
sprintf(buf, " n%d->n%d;\n", (CollIndex)predNodeId, (CollIndex)nodeId);
graphString += buf;
}
}
graphString += "}\n"
"#ENDJOINORDER\n";
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG, graphString.data());
}
// Nonmember helper function for processJBBCList; returns array of join order
// group numbers indexed by node number.
static Int32* getJoinOrderInfo(const CANodeIdSet* const const_jbbcs, size_t& arrSize)
{
CANodeIdSet jbbcs(*const_jbbcs); // Need a copy we can change
CANodeIdSet reached;
CANodeId nodeId, predNodeId;
Int32 currGroupOrderNum = 1;
NABoolean foundOne = FALSE;
Int32 numSkipped;
// Find needed size for array.
CollIndex maxNodeId = NULL_CA_ID;
for (nodeId = jbbcs.init(); jbbcs.next(nodeId); jbbcs.advance(nodeId))
{
if (nodeId > maxNodeId)
maxNodeId = nodeId;
}
// Allocate array of join order group numbers we will return.
arrSize = maxNodeId + 1; // assign output param
Int32* joinOrderGroupNumbers = new(STMTHEAP) Int32[arrSize];
if (QRLogger::isCategoryInDebug(CAT_SQL_COMP_QR_DESC_GEN))
logJBBCPredecessorGraph(jbbcs);
while (jbbcs.entries() > 0)
{
numSkipped = 0;
for (nodeId = jbbcs.init(); jbbcs.next(nodeId); jbbcs.advance(nodeId))
{
NodeAnalysis* nodeAnalysis = nodeId.getNodeAnalysis();
if (!nodeAnalysis)
{
numSkipped++;
continue;
}
JBBC* jbbc = nodeAnalysis->getJBBC();
if (!jbbc)
{
numSkipped++;
continue;
}
NABoolean reachable = TRUE;
const CANodeIdSet& predecessors = jbbc->getPredecessorJBBCs();
for (predNodeId = predecessors.init();
reachable && predecessors.next(predNodeId);
predecessors.advance(predNodeId))
{
if (reached.containsThisId(predNodeId))
continue;
reachable = FALSE; // haven't reached all its predecessors yet
} // each predecessor
if (reachable)
{
// Set the node's join order group number and add it to set of
// nodes we have processed. It also needs to be removed from the
// list of jbbcs, but we can't do that while we're iterating
// over it. After the current pass, the set of reached nodes will
// be removed from the jbbcs set, prior to the next loop over the
// jbbcs.
joinOrderGroupNumbers[nodeId] = currGroupOrderNum;
reached += nodeId;
foundOne = TRUE;
}
} // each jbbc
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
foundOne || numSkipped == jbbcs.entries(),
QRDescriptorException,
"One or more nodes not reachable via required predecessor nodes");
foundOne = FALSE;
currGroupOrderNum++;
jbbcs -= reached;
} // while
return joinOrderGroupNumbers;
}
// -----------------------------------------------------------------------
void QRDescGenerator::processJBBCList(CANodeIdSet* jbbcNodeIds,
QRJBBPtr jbbElement,
ValueIdSet &jbbOutputs,
CANodeId& groupJbbcNodeId)
{
QRTRACER("QRDescGenerator::processJBBCList()");
QRTablePtr *qrtableArray = 0;
qrtableArray = (QRTablePtr *)calloc(jbbcNodeIds->entries(),
sizeof(QRTablePtr));
short numTables = 0;
// Get array of join order groups, indexed by node number. This array is
// allocated in the function called, and we have to delete it.
size_t joinOrderArrSize;
Int32* joinOrders = getJoinOrderInfo(jbbcNodeIds, joinOrderArrSize);
groupJbbcNodeId = NULL_CA_ID; // Unless we find one
// Create an array of JBBCs
for (CANodeId nodeId = jbbcNodeIds->init();
jbbcNodeIds->next(nodeId);
jbbcNodeIds->advance(nodeId))
{
NodeAnalysis* nodeAnalysis = nodeId.getNodeAnalysis();
if (!nodeAnalysis) // It is possible there is no node analysis, but I'm not
continue; // sure why that is the case
TableAnalysis* tableAnalysis = nodeAnalysis->getTableAnalysis();
if (tableAnalysis)
{
// Table
const NATable* tbl = tableAnalysis->getTableDesc()->getNATable();
NAString tblName = tbl->getTableName().getQualifiedNameAsAnsiString();
QRTablePtr tableElement = new(mvqrHeap_)
QRTable(ADD_MEMCHECK_ARGS(mvqrHeap_));
tableElement->setAndRegisterID(nodeId, colTblIdHash_);
tableElement->setTableName(tblName);
tableElement->setExtraHub(nodeAnalysis->isExtraHub());
char sRedeftime[30];
memset(sRedeftime, 0, sizeof(sRedeftime));
convertInt64ToAscii(tbl->getRedefTime(), sRedeftime);
tableElement->setTimestamp(NAString(sRedeftime));
tableElement->setIsAnMV(tbl->isAnMV());
tableElement->setNumCols(tbl->getNAColumnArray().entries());
tableElement->setJoinOrder(joinOrders[nodeId]);
if (nodeAnalysis->getJBBC()->parentIsLeftJoin())
tableElement->setLOJParent(TRUE);
if (isDumpMvMode())
{
const NAString& exposedName = tableAnalysis->getTableDesc()->getCorrNameObj().getExposedNameAsAnsiString();
const NAString& corrName = strchr(exposedName, '.') ?
tableAnalysis->getTableDesc()->getCorrNameObj().getQualifiedNameObj().getObjectName() :
exposedName;
tableElement->setCorrelationName(corrName);
}
processKeys(tableAnalysis, tableElement, jbbOutputs);
qrtableArray[numTables++] = tableElement;
}
else
{
// Handle linked JBBs here.
QRJBBPtr groupJbb = new(mvqrHeap_) QRJBB(genJBBid(),
(CollIndex)NULL_CA_ID,
ADD_MEMCHECK_ARGS(mvqrHeap_));
const JBBSubset* jbbSubset = nodeAnalysis->getOriginalExpr()
->getGroupAnalysis()->getLocalJBBView();
if (jbbSubset)
{
groupJbb->setRefFromInt(jbbSubset->getJBB()->getJBBId());
jbbElement->getHub()->getJbbcList()->addElement(groupJbb);
}
else if (nodeAnalysis->getOriginalExpr()->getOperatorType() == REL_GROUPBY)
{
groupJbbcNodeId = nodeId;
}
else
{
// LCOV_EXCL_START :rfi
deletePtr(groupJbb);
Int32 nodeIdVal = nodeId;
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
FALSE, QRDescriptorException,
"Unsupported operator: %s",
nodeAnalysis->getOriginalExpr()->getText().data());
// LCOV_EXCL_STOP
}
}
}
// Finished with join order array.
NADELETEARRAY(joinOrders, joinOrderArrSize, Int32, STMTHEAP);
// Sort the array by table name.
if (numTables > 0)
{
opt_qsort(qrtableArray, numTables, sizeof(QRTablePtr),
//QRDescGenerator::cmpQRTableName);
QRElement::cmpQRElement);
}
// Add the sorted tables to the descriptor.
for (short iTableIndex = 0; iTableIndex < numTables; iTableIndex++)
{
QRTablePtr tableElement = qrtableArray[iTableIndex];
// Is this a hub or extra-hub table?
if (tableElement->isExtraHub())
jbbElement->getExtraHub()->addTable(tableElement);
else
jbbElement->getHub()->getJbbcList()->addElement(tableElement);
}
free(qrtableArray);
} // processJBBCList()
// -----------------------------------------------------------------------
void QRDescGenerator::processKeys(TableAnalysis* tableAnalysis,
QRTablePtr tableElement,
ValueIdSet& jbbOutputs)
{
QRTRACER("QRDescGenerator::processKeys()");
// Generate the content of the <Key> element using the clustering index.
// The primary key serves this purpose if one is available, otherwise SYSKEY.
ValueIdSet keyCols(tableAnalysis->getTableDesc()->getClusteringIndex()
->getClusteringKeyCols());
QRKeyPtr keyElement = NULL;
if (isQueryMode())
keyElement = new(mvqrHeap_) QRKey(ADD_MEMCHECK_ARGS(mvqrHeap_));
//check if the key columns are covered by the jbb outputs
NABoolean keyCovered = TRUE;
for (ValueId vid=keyCols.init();
keyCols.next(vid);
keyCols.advance(vid))
{
if (isQueryMode())
{
QRElementPtr keyColumn = genQRColumn(vid);
keyElement->addElement(keyColumn);
}
if (!jbbOutputs.containsTheGivenValue(vid))
keyCovered = FALSE;
}
if (isQueryMode())
tableElement->setKey(keyElement);
if (keyCovered && (!isQueryMode()))
tableElement->setIsKeyCovered(TRUE);
}
// -----------------------------------------------------------------------
void QRDescGenerator::getSingleTableJBBs(QRDescriptorPtr desc, RelExpr* expr)
{
QRTRACER("QRDescGenerator::getSingleTableJBBs()");
RelExpr* subtree;
Scan* scanExpr;
NodeAnalysis* nodeAnalysis;
const NATable* naTable;
// Traverse query tree, looking for table scans that are not part of a JBB.
// We will treat these as single-JBBC JBBs for the purpose of query rewrite.
char sRedeftime[30];
Int32 arity = expr->getArity();
for (Int32 i = 0; i < arity; i++)
{
subtree = expr->child(i).getPtr();
OperatorType op = subtree->getOperator();
// If the node is a GroupBy that is not part of a JBB (its GBAnalyis is
// null), skip over it and look for a Scan node below. This can happen when
// the GB is on a primary key and will eventually be discarded as unnecessary.
// Use a loop in case of cascaded groupbys as in the case of "select distinct"
// with a grouping query.
while (op.match(REL_GROUPBY) &&
static_cast<GroupByAgg*>(subtree)->getGBAnalysis() == NULL)
{
subtree = subtree->child(0).getPtr();
op = subtree->getOperator();
}
if (op.match(REL_SCAN) &&
(desc->getElementType() == ET_MVDescriptor || // always for MV desc
qrNeededForTable(expr, subtree)))
{
scanExpr = static_cast<Scan*>(subtree);
nodeAnalysis = scanExpr->getGroupAnalysis()->getNodeAnalysis();
QRJBBPtr jbb = new(mvqrHeap_) QRJBB(genJBBid(),
(CollIndex)(nodeAnalysis->getId()),
ADD_MEMCHECK_ARGS(mvqrHeap_));
desc->addJBB(jbb);
QRTablePtr tableElement = new(mvqrHeap_) QRTable(ADD_MEMCHECK_ARGS(mvqrHeap_));
naTable = scanExpr->getTableDesc()->getNATable();
tableElement->setAndRegisterID(nodeAnalysis->getId(), colTblIdHash_);
tableElement->setTableName(naTable->getTableName().getQualifiedNameAsAnsiString());
tableElement->setExtraHub(nodeAnalysis->isExtraHub());
memset(sRedeftime, 0, sizeof(sRedeftime));
convertInt64ToAscii(naTable->getRedefTime(), sRedeftime);
tableElement->setTimestamp(NAString(sRedeftime));
tableElement->setIsAnMV(naTable->isAnMV());
tableElement->setNumCols(naTable->getNAColumnArray().entries());
if (isDumpMvMode())
{
const NAString& exposedName = scanExpr->getTableDesc()->getCorrNameObj().getExposedNameAsAnsiString();
const NAString& corrName = strchr(exposedName, '.') ?
scanExpr->getTableDesc()->getCorrNameObj().getQualifiedNameObj().getObjectName() :
exposedName;
tableElement->setCorrelationName(corrName);
}
ValueIdSet jbbOutputs = nodeAnalysis->
getOriginalExpr()->
getGroupAttr()->
getCharacteristicOutputs();
processKeys(nodeAnalysis->getTableAnalysis(), tableElement, jbbOutputs);
if (tableElement->isExtraHub())
jbb->getExtraHub()->addTable(tableElement);
else
jbb->getHub()->getJbbcList()->addElement(tableElement);
if (expr->getOperator() == REL_GROUPBY)
processGroupBy(expr, 0, jbb);
// Use characteristic outputs of the parent if it is a groupby node.
if (expr->getOperator().match(REL_GROUPBY))
processOutputList(expr->getGroupAttr()->getCharacteristicOutputs(), jbb);
else
processOutputList(scanExpr->getGroupAttr()->getCharacteristicOutputs(), jbb);
}
else if (op.match(REL_UNARY_UPDATE))
{
// Need to create a qrtable for the update node and add its id to the hash
// table to prevent an assertion failure when placing its preds in range
// or residual bitmaps.
QRTablePtr tableElement = new(mvqrHeap_) QRTable(ADD_MEMCHECK_ARGS(mvqrHeap_));
Update* updExpr = static_cast<Update*>(subtree);
CANodeId id = updExpr->getTableDesc()->getTableAnalysis()
->getNodeAnalysis()->getId();
tableElement->setAndRegisterID(id, colTblIdHash_);
}
// cut off recursion at root of JBB
// assume outer joins are part of JBB
//else if (!op.match(REL_ANY_JOIN) && !op.match(REL_MULTI_JOIN))
else if (!op.match(REL_ANY_JOIN) && !op.match(REL_MULTI_JOIN) && !op.match(REL_GROUPBY))
{
getSingleTableJBBs(desc, subtree);
}
}
} // getSingleTableJBBs
QRJBBPtr QRDescGenerator::createJbb(JBB* jbb)
{
QRTRACER("QRDescGenerator::createJbb()");
QRJBBPtr jbbElement = new(mvqrHeap_) QRJBB(jbb->getJBBId(), jbb,
ADD_MEMCHECK_ARGS(mvqrHeap_));
CANodeIdSet jbbcs = jbb->getJBBCs();
ValueIdSet jbbOutputs;
if (jbb->getGBAnalysis())
jbbOutputs = jbb->getNormOutputs();
else if (jbb->getJBBCs().entries() == 1)
jbbOutputs = jbb->getJBBCs().getFirst().getNodeAnalysis()->
getOriginalExpr()->getGroupAttr()->
getCharacteristicOutputs();
else
jbbOutputs = jbb->getNormOutputs();
// JBBC List
CANodeId groupJbbcNodeId = NULL_CA_ID;
processJBBCList(&jbbcs, jbbElement, jbbOutputs, groupJbbcNodeId);
// Predicates. GB node needed to find having pred on count(*), which is not
// pushed down to a scan node.
GBAnalysis* gbAnalysis = jbb->getGBAnalysis();
// Group By
// For some nested queries with GB that constitute a separate JBB, the JBB
// does not have a GBAnalysis object. The GB original expr must be
// obtained from the NodeAnalysis of the grouping node itself.
// However the GroupByAgg* is derived, it must be saved in the QRJBB object
// for the eventual call to processReferencingPreds() for the jbb.
if (gbAnalysis != NULL)
{
processGroupBy(gbAnalysis->getOriginalGBExpr(),
gbAnalysis->getGroupingNodeId(),
jbbElement);
jbbElement->setGbExpr(gbAnalysis->getOriginalGBExpr());
}
else if (groupJbbcNodeId != NULL_CA_ID)
{
RelExpr* relExpr = groupJbbcNodeId.getNodeAnalysis()->getOriginalExpr();
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_ERROR,
relExpr->getOperatorType() == REL_GROUPBY,
QRDescriptorException,
"Expected grouping JBBC, but op type was %d.",
relExpr->getOperatorType());
processGroupBy(static_cast<GroupByAgg*>(relExpr),
groupJbbcNodeId, jbbElement);
jbbElement->setGbExpr(static_cast<GroupByAgg*>(relExpr));
}
// Output List
processOutputList(jbb->getNormOutputs(), jbbElement);
return jbbElement;
} // createJbb()
NABoolean QRDescGenerator::hasRewriteEnabledMVs(TableDesc* tableDesc)
{
QRTRACER("QRDescGenerator::hasRewriteEnabledMVs()");
const UsingMvInfoList& mvList = tableDesc->getNATable()->getMvsUsingMe();
for (CollIndex i=0; i<mvList.entries(); i++)
{
if (mvList[i]->isRewriteEnabled())
return TRUE;
}
return FALSE;
}
NABoolean QRDescGenerator::qrNeededForTable(RelExpr* parent, RelExpr* scanExpr)
{
QRTRACER("QRDescGenerator::qrNeededForTable()");
if (putAllJBBsInQD_)
return TRUE;
Scan* scan = static_cast<Scan*>(scanExpr);
// If there are no MVs on the table, no rewrite is possible.
if (!hasRewriteEnabledMVs(scan->getTableDesc()))
{
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG,
"Omitting single table JBB %s from query descriptor -- no "
"rewrite-enabled MVs are defined on it.",
scan->getTableDesc()->getNATable()->getTableName().getObjectName().data());
return FALSE;
}
return TRUE;
}
NABoolean QRDescGenerator::qrNeededForJBB(JBB* jbb)
{
QRTRACER("QRDescGenerator::qrNeededForJBB()");
if (putAllJBBsInQD_)
return TRUE;
NodeAnalysis* nodeAnalysis;
TableAnalysis* tableAnalysis;
CANodeIdSet jbbcs = jbb->getJBBCs();
// Count the JBBCs that have MVs defined on them. We need at least two, or
// one plus a Group By.
for (CANodeId jbbc = jbbcs.init();
jbbcs.next(jbbc);
jbbcs.advance(jbbc))
{
nodeAnalysis = jbbc.getNodeAnalysis();
if (!nodeAnalysis->isExtraHub()) // Only check hub tables.
{
tableAnalysis = nodeAnalysis->getTableAnalysis();
if (tableAnalysis && hasRewriteEnabledMVs(tableAnalysis->getTableDesc()))
return TRUE; // found a base table that uses an mv
}
}
return FALSE;
}
// See if a jbbsubset uses any semijoins or TSJs. This supports a temporary
// restriction that is checked in processJBBs() below. Since the need for this
// check is temporary, we make it through this local nonmember function instead
// of further complicating the JBBSubsetAnalysis class with a member function.
static NABoolean noSemiOrTSJ(JBBSubsetAnalysis* jbbSubsetAnalysis)
{
CANodeId node;
const CANodeIdSet& jbbcs = jbbSubsetAnalysis->getJBBCs();
for (node = jbbcs.init(); jbbcs.next(node); jbbcs.advance(node))
{
Join* parentJoin = node.getNodeAnalysis()->getJBBC()->getOriginalParentJoin();
if (parentJoin)
{
OperatorType op = parentJoin->getOperator();
if (op.match(REL_ANY_SEMIJOIN) || op.match(REL_ANY_TSJ))
return FALSE;
}
}
return TRUE; // no semijoins or TSJs
}
NABoolean QRDescGenerator::processJBBs(QRDescriptorPtr descPtr,
QueryAnalysis* qa)
{
QRTRACER("QRDescGenerator::processJBBs()");
// This is a reference to the descriptor's list of JBBs, to which will
// first be added the pseudo-JBBs we create for table scans that are not
// part of any JBB, and later in this function, the actual Analyzer JBBs.
const NAPtrList<QRJBBPtr>& qrJbbList = descPtr->getJbbList();
if (isDumpMvMode())
{
// Don't bother with single table queries in WA mode.
const CANodeIdSet& allTables = qa->getTables();
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
allTables.entries() > 1,
QRDescriptorException,
"This query has a single table.");
}
// Look for table scans that are not part of a JBB, and create pseudo-JBBs
// for them. Note that these will be reflected in the contents of qrJbbList
// upon return.
getSingleTableJBBs(descPtr, relExpr_);
// Initialize return value to false if previous step created no JBBs.
NABoolean jbbElemsWereCreated = !qrJbbList.isEmpty();
// Check if any single-table (pseudo) JBBs use an MV. If so, we can skip this
// step for any actual JBBs later in this function.
// If the cqd MVQR_ALL_JBBS_IN_QD is ON (putAllJBBsInQD_), we don't need to
// check this, the descriptor is created regardless of MV usage.
NABoolean usesEnabledMVs = FALSE;
CollIndex i;
if (jbbElemsWereCreated && !putAllJBBsInQD_)
for (i = 0; !usesEnabledMVs && i < qrJbbList.entries(); i++)
{
// getNodeId() returns a CollIndex, so we have to cast it to CANodeId.
NodeAnalysis* nodeAnalysis =
static_cast<CANodeId>(qrJbbList[i]->getNodeId()).getNodeAnalysis();
if (!nodeAnalysis->isExtraHub() &&
hasRewriteEnabledMVs(nodeAnalysis->getTableAnalysis()->getTableDesc()))
{
usesEnabledMVs = TRUE; // table is used by an MV
}
}
const ARRAY(JBB*)& jbbArray = qa->getJBBs();
CollIndex remainingJBBs = jbbArray.entries();
if (isDumpMvMode())
{
Int32 totalJBBs = remainingJBBs + descPtr->getJbbList().entries();
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
totalJBBs == 1,
QRDescriptorException,
"This query has %d JBBs.", totalJBBs);
}
// For a query descriptor, make sure some table involved is used by an MV
// before going further. We used to leave out individual JBBs on this basis,
// but there are typically inter-JBB column references that can result in an
// exception being thrown if some JBBs are not processed (see bug 2502).
// If the cqd MVQR_ALL_JBBS_IN_QD is ON (putAllJBBsInQD_), we don't need to
// check this, the descriptor is created regardless of MV usage.
if (!usesEnabledMVs && !putAllJBBsInQD_ && isQueryMode())
{
for (i = 0; !usesEnabledMVs && remainingJBBs > 0; i++)
{
if (jbbArray.used(i))
{
remainingJBBs--;
currentJBB_ = jbbArray[i];
usesEnabledMVs = qrNeededForJBB(currentJBB_);
}
}
if (!usesEnabledMVs)
{
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG,
"Query descriptor not generated: no JBBC of any JBB is used in "
"a rewrite-enabled MV.");
return FALSE;
}
}
// Now revisit each JBB and create a descriptor element for it.
remainingJBBs = jbbArray.entries();
for (i = 0; remainingJBBs > 0; i++)
{
if (jbbArray.used(i))
{
remainingJBBs--;
currentJBB_ = jbbArray[i];
// Semijoins and TSJs not handled yet.
JBBSubsetAnalysis* jbbSubsetAnalysis =
currentJBB_->getMainJBBSubset().getJBBSubsetAnalysis();
if (noSemiOrTSJ(jbbSubsetAnalysis))
{
QRJBBPtr jbb = createJbb(currentJBB_);
jbbElemsWereCreated = TRUE;
descPtr->addJBB(jbb);
}
else
{
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG,
"Omitting JBB #%d from descriptor because it contains "
"semijoins, anti-semijoins, or TSJs", currentJBB_->getJBBId());
if (isDumpMvMode())
{
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
FALSE,
QRDescriptorException,
"SemiJoins are not supported yet.");
}
}
}
}
// The processing of predicates is deferred until after the descriptor
// elements for all JBBs have been created. This avoids the problem where
// a predicate refers to a column for which the table hasn't been processed,
// which leads to a failure in getting the table's range or residual pred
// bitmap because it hasn't been set up yet.
QRJBBPtr qrJbbPtr = NULL;
for (CollIndex qrJbbInx=0; qrJbbInx<qrJbbList.entries(); qrJbbInx++)
{
qrJbbPtr = qrJbbList[qrJbbInx];
currentJBB_ = qrJbbPtr->getJBB();
if (currentJBB_)
{
CANodeIdSet jbbcs = currentJBB_->getJBBCs();
processReferencingPreds(&jbbcs,
qrJbbPtr->getGbExpr(),
qrJbbPtr);
}
else
{
CANodeId nodeId = (CANodeId)(qrJbbPtr->getNodeId());
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
nodeId != NULL_CA_ID,
QRDescriptorException,
"QRJBB at position %d in list had neither a JBB* nor a node id",
qrJbbInx);
CANodeIdSet nodes;
nodes.addElement(nodeId);
RelExpr* expr = nodeId.getNodeAnalysis()->getOriginalExpr();
processReferencingPreds(&nodes,
expr->getOperator() == REL_GROUPBY ? expr : NULL,
qrJbbPtr);
}
}
currentJBB_ = NULL; // No longer processing a specific JBB
// Now that all predicates have been processed, the range predicates we have
// kept in a hash table are guaranteed to be complete, and can be added to
// the appropriate range predicate list.
if (jbbElemsWereCreated)
addRangePredicates();
// Return true if one or more JBB elements were found. Returning false
// prevents a descriptor from being generated.
return jbbElemsWereCreated;
}
// LCOV_EXCL_START :cnu
void QRDescGenerator::logColumnBitmap(QRTablePtr table,
const XMLBitmap& bitmap,
ElementType predType)
{
// Exit immediately if logging is not in DEBUG level.
if (!QRLogger::isCategoryInDebug(CAT_SQL_COMP_QR_DESC_GEN))
return;
QRTRACER("QRDescGenerator::logColumnBitmap()");
// Log which bitmap this is.
if (predType == ET_RangePred)
{
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG,
"For table %s, the following columns have range predicates:",
table->getTableName().data());
}
else if (predType == ET_ResidualPred)
{
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG,
"For table %s, the following columns have residual predicates:",
table->getTableName().data());
}
else
{
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG,
"Table %s has these columns set in bitmap of element type %d:",
table->getTableName().data(), predType);
}
// If nothing set, log a message noting that and return.
if (bitmap.isEmpty())
{
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG, " <none>");
return;
}
// At least one column is marked in the bitmap. List the ones that are.
CANodeId tblNodeId = table->getIDNum();
const NAColumnArray& colsInTable =
tblNodeId.getNodeAnalysis()->getTableAnalysis()->getTableDesc()
->getNATable()->getNAColumnArray();
assertLogAndThrow2(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
table->getNumCols() == colsInTable.entries(),
QRDescriptorException,
"logColumnBitmap() expected %d columns, but found %d in list",
table->getNumCols(), colsInTable.entries());
for (CollIndex i=0; i<colsInTable.entries(); i++)
{
if (bitmap.testBit(i))
{
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_DEBUG,
" %s", colsInTable[i]->getColName().data());
}
}
} // logColumnBitmap()
// LCOV_EXCL_STOP
QRQueryDescriptorPtr QRDescGenerator::createQueryDescriptor(QueryAnalysis* qa,
RelExpr* expr)
{
QRTRACER("QRDescGenerator::createQueryDescriptor()");
QRQueryDescriptorPtr queryDesc;
queryDesc = new (mvqrHeap_) QRQueryDescriptor(ADD_MEMCHECK_ARGS(mvqrHeap_));
descriptorType_ = ET_QueryDescriptor;
relExpr_ = expr;
// Initialize the return value to null, and leave it null if no JBBs are
// present.
if (!processJBBs(queryDesc, qa))
{
deletePtr(queryDesc);
queryDesc = NULL;
return NULL;
}
queryDesc->setVersion(createVersionElement());
NAString mvAgeValue;
CmpCommon::getDefault(MV_AGE, mvAgeValue, 0);
queryDesc->getMisc()->setMVAge(mvAgeValue);
Int32 level = CmpCommon::getDefaultLong(MVQR_REWRITE_LEVEL);
queryDesc->getMisc()->setRewriteLevel((MvqrRewriteLevel)level);
return queryDesc;
} // createQueryDescriptor()
QRMVDescriptorPtr QRDescGenerator::createMvDescriptor(QueryAnalysis* qa,
RelExpr* expr)
{
QRTRACER("QRDescGenerator::createMvDescriptor()");
QRMVDescriptorPtr mvDesc = new(mvqrHeap_) QRMVDescriptor(ADD_MEMCHECK_ARGS(mvqrHeap_));
descriptorType_ = ET_MVDescriptor;
relExpr_ = expr;
if (processJBBs(mvDesc, qa))
{
mvDesc->setVersion(createVersionElement());
return mvDesc;
}
else
{
// LCOV_EXCL_START :rfi processJBBs should not return false for mv
deletePtr(mvDesc);
return NULL;
// LCOV_EXCL_STOP
}
} // createMvDescriptor()
QRVersionPtr QRDescGenerator::createVersionElement()
{
QRTRACER("QRDescGenerator::createVersionElement()");
NAString versionString(QR::CURRENT_VERSION);
QRVersionPtr descVersion = new (mvqrHeap_) QRVersion(ADD_MEMCHECK_ARGS(mvqrHeap_));
descVersion->setVersionString(versionString);
return descVersion;
}
XMLString* QRDescGenerator::createXmlText(QRElementPtr desc)
{
QRTRACER("QRDescGenerator::createXmlText()");
XMLString* xmlText = NULL;
// Formatted XML takes much more space, especially when very large
// expressions are used.
// if (isDumpMvMode())
// bFormatted_ = FALSE;
if (bFormatted_)
xmlText = (XMLFormattedString *) new(mvqrHeap_) XMLFormattedString(mvqrHeap_);
else
xmlText = new (mvqrHeap_) XMLString(mvqrHeap_);
desc->toXML(*xmlText);
return xmlText;
}
// Sort the join columns, distinguish between hub vs. extra-hub, and add to
// result.
void QRDescGenerator::addJoinPred(QRJBBPtr jbbElem,
QRElementPtr* qrElemArray,
Int32* idArray,
Int32 eqCount,
UInt32& hubJoinPredId)
{
QRTRACER("QRDescGenerator::addJoinPred()");
QRJoinPredPtr hubJoinPred = NULL;
QRJoinPredPtr extraHubJoinPred = NULL;
// Sort the list of columns and expressions.
if (bSortJoinPredicateCols_)
opt_qsort(qrElemArray, eqCount, sizeof(QRElementPtr),
QRElement::cmpQRElement);
// Assign each element in the sorted array to either a hub or extrahub join
// pred. The id of the join pred is derived from that of the first element
// added to it.
for (Int32 i=0; i<eqCount; i++)
{
if (qrElemArray[i]->isExtraHub())
{
if (!extraHubJoinPred)
{
extraHubJoinPred =
new (mvqrHeap_) QRJoinPred(ADD_MEMCHECK_ARGS(mvqrHeap_));
QRValueId id(idArray[i]);
EqualitySet* eqSet = vegsUsedHash_.getFirstValue(&id);
if (eqSet && eqSet->getJoinPredId())
extraHubJoinPred->setAndRegisterID(eqSet->getJoinPredId(),
colTblIdHash_);
else
extraHubJoinPred->setAndRegisterID(idArray[i], colTblIdHash_);
}
extraHubJoinPred->addElement(qrElemArray[i]);
colToJoinPredMap_.addMapEntry(idArray[i],
qrElemArray[i]->getReferencedElement()->getIDNum());
}
else
{
if (!hubJoinPred)
{
// hubJoinPredId will have been set to the value id of a veg pred
// if the equality set was derived from one.
if (hubJoinPredId == NULL_VALUE_ID)
hubJoinPredId = idArray[i]; // returned to caller
hubJoinPred =
new (mvqrHeap_) QRJoinPred(ADD_MEMCHECK_ARGS(mvqrHeap_));
hubJoinPred->setAndRegisterID(hubJoinPredId, colTblIdHash_);
}
hubJoinPred->addElement(qrElemArray[i]);
colToJoinPredMap_.addMapEntry(hubJoinPredId,
qrElemArray[i]->getReferencedElement()->getIDNum());
}
}
// Now lets look at the result and figure out how to insert it.
QRJoinPredListPtr hubJoinPredList = jbbElem->getHub()->getJoinPredList();
QRJoinPredListPtr extraHubJoinPredList = jbbElem->getExtraHub()->getJoinPredList();
if (hubJoinPred == NULL)
{
// Insert the extra-hub join pred to the JBB.
if (!extraHubJoinPred->isRedundant())
extraHubJoinPredList->addItem(extraHubJoinPred);
else
deletePtr(extraHubJoinPred);
}
else if (hubJoinPred->entries() < 2)
{
// Since we have only a single hub member and we know there are two or more
// members, there must be at least one extra-hub member.
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
extraHubJoinPred, QRDescriptorException,
"In addJoinPred(): single hub member and no extra-hub");
// When there is only one entry in the hub list, we don't add the list to
// hubJoinPredList; instead we add the single hub member to extraHubJoinPred.
const QRElementPtr hubItem = hubJoinPred->getEqualityListElement(0);
extraHubJoinPred->addElement(hubItem); // @ZX -- needs to be in order
hubJoinPred->removeItem(hubItem);
deletePtr(hubJoinPred);
// Insert the extra-hub join pred to the JBB.
if (!extraHubJoinPred->isRedundant())
extraHubJoinPredList->addItem(extraHubJoinPred);
else
deletePtr(extraHubJoinPred);
}
else
{
// The hub list has at least 2 columns - insert it.
if (!hubJoinPred->isRedundant())
hubJoinPredList->addItem(hubJoinPred);
else
deletePtr(hubJoinPred);
// extraHubJoinPred is only NULL if there are no extra-hub tables among the
// tables represented in the join pred.
if (extraHubJoinPred)
{
// The extra-hub list has at least 1 column in it.
// Insert it too, after adding a ref to the hub join pred.
QRJoinPredPtr hubJoinPredRef =
new(mvqrHeap_) QRJoinPred(ADD_MEMCHECK_ARGS(mvqrHeap_));
hubJoinPredRef->setRefFromInt(hubJoinPred->getIDNum());
extraHubJoinPred->addElement(hubJoinPredRef);
if (!extraHubJoinPred->isRedundant())
extraHubJoinPredList->addItem(extraHubJoinPred);
else
deletePtr(extraHubJoinPred);
}
}
} // addJoinPred()
// This function is part of the temporary restriction on a range predicate that
// disallows referring to the same column more than once in an expression that
// is the subject of a range predicate.
static void getLeafValueIds(ItemExpr* itemExpr, ValueIdList &lv)
{
QRTRACER("getLeafValueIds()");
Int32 nc = itemExpr->getArity();
// if this is a leaf node, add its value id
if (nc == 0)
{
lv.insertSet(itemExpr->getValueId());
}
else
{
// else add the leaf value ids of all the children
for (Lng32 i = 0; i < (Lng32)nc; i++)
{
getLeafValueIds(itemExpr->child(i), lv);
}
}
}
// This function is temporary, and will be used as long as the restriction
// disallowing >1 reference to the same column in a range predicate persists.
// When this restriction is lifted, remove this function and uncomment the one
// with the same name immediately below it. The present solution uses a list
// instead of a set so that use of the same column more than once can be detected.
// The static function getLeafValueIds() defined immediately above here can be
// removed at the same time this function is.
CANodeId QRDescGenerator::getExprNode(ItemExpr* itemExpr)
{
QRTRACER("QRDescGenerator::getExprNode()");
// Find and return the expression's containing node, or NULL_CA_ID if it is
// a multi-node expression.
//
// There is currently a restriction that keeps a single node expression from
// being used with a range predicate if it references more than one column,
// or even the same column more than once. So for now, NULL_CA_ID is returned
// in this case even if there is only a single node.
ValueIdList vids;
NABoolean isMultiNode = FALSE;
CANodeId exprNodeId = NULL_CA_ID;
CANodeId itemNodeId;
ItemExpr* leafItemExpr;
ValueId vid;
Int32 inputCount = 0;
getLeafValueIds(itemExpr, vids);
for (CollIndex i=0; i<vids.entries(); i++)
{
vid = vids[i];
leafItemExpr = vid.getItemExpr();
switch (leafItemExpr->getOperatorType())
{
case ITM_VEG_REFERENCE:
// If a veg contains a constant, it will be used in the range expr,
// so only count it if it contains no constants.
if (static_cast<VEGReference*>(leafItemExpr)->getVEG()->getAConstant(TRUE)
== NULL_VALUE_ID)
inputCount++;
break;
//case ITM_CONSTANT:
case ITM_REFERENCE:
case ITM_BASECOLUMN:
case ITM_INDEXCOLUMN:
//case ITM_HOSTVAR:
//case ITM_DYN_PARAM:
case ITM_SEL_INDEX:
case ITM_VALUEIDREF:
case ITM_VALUEIDUNION:
case ITM_VEG:
case ITM_VEG_PREDICATE:
//case ITM_DEFAULT_SPECIFICATION:
//case ITM_SAMPLE_VALUE:
//case ITM_CACHE_PARAM:
inputCount++;
break;
default:
break;
}
itemNodeId = getNodeId(vid);
if (itemNodeId != NULL_CA_ID)
{
if (exprNodeId == NULL_CA_ID)
exprNodeId = itemNodeId;
else if (itemNodeId != exprNodeId)
isMultiNode = TRUE;
}
}
if (exprNodeId)
return (isMultiNode || inputCount != 1)
? NULL_CA_ID
: exprNodeId;
else if (itemExpr->containsAnAggregate())
{
// exprNodeId will be NULL_CA_ID if only count(*) is used.
if (!currentJBB_)
// Called from Normalizer. Analysis not done yet, have to settle for
// residual pred.
return NULL_CA_ID;
else
{
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
currentJBB_->getGBAnalysis(), QRDescriptorException,
"No GBAnalysis for JBB %d, although an aggfn was used",
currentJBB_->getJBBId());
return currentJBB_->getGBAnalysis()->getGroupingNodeId();
}
}
else
{
NAString predText;
itemExpr->unparse(predText);
QRLogger::log(CAT_SQL_COMP_QR_DESC_GEN, LL_WARN,
"Predicate encountered with no columns and no count(*), will treat "
"as residual predicate -- %s", predText.data());
return NULL_CA_ID;
}
}
// DON'T REMOVE THIS CODE -- it will be restored when the temporary restriction
// described at the top of the previous function is
// eliminated.
//CANodeId QRDescGenerator::getExprNode(ItemExpr* itemExpr)
//{
// QRTRACER("getExprNode");
//
// // Find and return the expression's containing node, or NULL_CA_ID if it is
// // a multi-node expression.
// //
// // There is currently a restriction that keeps a single node expression from
// // being used with a range predicate if it references more than one column,
// // So for now, NULL_CA_ID is returned in this case even if there is only a
// // single node.
// ValueIdSet vids;
// NABoolean isMultiNode = FALSE;
// CANodeId exprNodeId = NULL_CA_ID;
// CANodeId itemNodeId;
// ItemExpr* leafItemExpr;
// int inputCount = 0;
//
// itemExpr->getLeafValueIds(vids);
//
// for (ValueId vid=vids.init();
// !isMultiNode && inputCount < 2 && vids.next(vid);
// vids.advance(vid))
// {
// leafItemExpr = vid.getItemExpr();
// switch (leafItemExpr->getOperatorType())
// {
// //case ITM_CONSTANT:
// case ITM_REFERENCE:
// case ITM_BASECOLUMN:
// case ITM_INDEXCOLUMN:
// //case ITM_HOSTVAR:
// //case ITM_DYN_PARAM:
// case ITM_SEL_INDEX:
// case ITM_VALUEIDREF:
// case ITM_VALUEIDUNION:
// case ITM_VEG:
// case ITM_VEG_PREDICATE:
// case ITM_VEG_REFERENCE:
// //case ITM_DEFAULT_SPECIFICATION:
// //case ITM_SAMPLE_VALUE:
// //case ITM_CACHE_PARAM:
// inputCount++;
// break;
// default:
// break;
// }
// itemNodeId = getNodeId(vid);
// if (itemNodeId != NULL_CA_ID)
// {
// if (exprNodeId == NULL_CA_ID)
// exprNodeId = itemNodeId;
// else if (itemNodeId != exprNodeId)
// isMultiNode = TRUE;
// }
// }
//
// return (isMultiNode || inputCount != 1)
// ? NULL_CA_ID
// : exprNodeId;
//}
void QRDescGenerator::processEqualitySet(QRJBBPtr jbbElem,
EqualitySet& eqSet)
{
QRTRACER("QRDescGenerator::processEqualitySet()");
CollIndex i;
ItemExpr* itemExpr;
OperatorTypeEnum op;
CANodeId itemNodeId;
// Keep track of the CA nodes represented by the join pred members. Only one
// col/expr per node is placed in the join pred.
CANodeIdSet joinPredNodes;
// Retain a ptr to the first item expression added to the list of join pred
// members. If it turns out to be the only one, there is no join and we add
// it to the list of residual pred operands.
ItemExpr* firstJoinPredItem = NULL;
// List to store members of the equality set that are not part of a JoinPred.
// This includes expressions involving more than a single node, cols/exprs
// other than the first from each represented node, dynamic params, etc.
// When a join pred is derived from a subset of the members of the equality
// set, each remaining equality set member will appear in the query descriptor
// either as
// 1) a residual predicate equated to a reference to the join pred created
// from the equality set. This is the case when
// a) there is no constant in the equality set
// b) there is a constant, but the given eq set member is a multinode
// expression
// 2) a range predicate equated to the constant member of the eq set, except
// for a multinode expression
// If no join pred comes out of the equality set and there is no constant, we
// will form a chain of equality residual predicates involving all members of
// the eq set.
NAList<ItemExpr*> nonJoinPredOperands(mvqrHeap_);
// This keeps track of which members can NOT be used in a range predicate
// (multi-node expressions).
NABitVector rangeIneligible(mvqrHeap_);
// Stores the constant value, if any (max of 1 is possible), from the equality
// set. Used to create a range pred on the join columns.
ConstValue* constItem = NULL;
CollIndex joinPredElemCount = 0;
CollIndex eqCount = eqSet.entries();
NAString exprText;
// Array to put elements in so they can be sorted, and array of corresponding
// ids that can be used for the created join preds (for hub and extrahub).
QRElementPtr* qrElemArray = new(mvqrHeap_) QRElementPtr[eqCount];
Int32* idArray = new(mvqrHeap_) Int32[eqCount];
for (i=0; i<eqCount; i++)
{
itemExpr = eqSet[i];
op = itemExpr->getOperatorType();
if (op == ITM_BASECOLUMN)
{
const TableAnalysis* tableAnalysis =
((BaseColumn*)itemExpr)->getTableDesc()->getTableAnalysis();
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
tableAnalysis, QRDescriptorException,
"TableDesc has null table analysis");
itemNodeId = tableAnalysis->getNodeAnalysis()->getId();
//itemNodeId = ((BaseColumn*)itemExpr)->getTableDesc()->getTableAnalysis()
// ->getNodeAnalysis()->getId();
if (!joinPredNodes.containsThisId(itemNodeId))
{
joinPredNodes.insert(itemNodeId);
if (joinPredElemCount == 0)
firstJoinPredItem = itemExpr;
else
{
// Avoid call to genQRColumn until we're sure there is more than
// one join pred element. Otherwise we'll have to retract it,
// and the created col elem will not be used, but will be
// referenced by subsequent occurrences of the column.
if (joinPredElemCount == 1)
{
if (isInstNull(firstJoinPredItem))
qrElemArray[0] = skipInstNull(firstJoinPredItem);
else if (firstJoinPredItem->getOperatorType() == ITM_BASECOLUMN)
qrElemArray[0] =
genQRColumn(firstJoinPredItem->getValueId());
else
qrElemArray[0] = genQRExpr(firstJoinPredItem, FALSE);
idArray[0] = firstJoinPredItem->getValueId();
}
qrElemArray[joinPredElemCount] =
genQRColumn(itemExpr->getValueId());
idArray[joinPredElemCount] = itemExpr->getValueId();
}
joinPredElemCount++;
}
else
nonJoinPredOperands.insert(itemExpr);
}
else if (op == ITM_CONSTANT)
constItem = static_cast<ConstValue*>(itemExpr);
else if (op == ITM_CACHE_PARAM)
{
// Substitute an itemexpr representing the constant value underlying
// the parameter.
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
!constItem, QRDescriptorException,
"Equality set contains more than one constant");
constItem = (static_cast<ConstantParameter*>(itemExpr))->getConstVal();
}
else if (itemExpr->doesExprEvaluateToConstant(FALSE, FALSE))
nonJoinPredOperands.insert(itemExpr);
else if (op != ITM_INDEXCOLUMN)
{
// If more than one node is involved in an expression, it is treated
// as a residual pred of the form ref(J1)=expr.
// First, see if the expression is multi-node, and find the single
// node if it is not.
CANodeId exprNodeId = getExprNode(itemExpr);
// The expression will NOT be part of a join pred if any of the
// following hold true:
// 1) the expression references more than one node
// 2) the single referenced node is already in the join pred list
// 3) the expression contains an aggregate function
// Upon failing the join pred test, the expression can be part of a
// range pred if it only references a single node. Otherwise, it can
// only be part of a residual pred.
if (exprNodeId == NULL_CA_ID
|| joinPredNodes.containsThisId(exprNodeId)
|| itemExpr->containsAnAggregate())
{
if (exprNodeId == NULL_CA_ID)
rangeIneligible += nonJoinPredOperands.entries();
nonJoinPredOperands.insert(itemExpr);
}
else
{
joinPredNodes.insert(exprNodeId);
if (joinPredElemCount == 0)
firstJoinPredItem = itemExpr;
else
{
// Avoid call to genQRExpr until we're sure there is more than
// one join pred element. Otherwise we'll have to retract it,
// and the created col elems will not be used, but will be
// referenced by subsequent occurrences of those columns.
if (joinPredElemCount == 1)
{
if (firstJoinPredItem->getOperatorType() == ITM_BASECOLUMN)
qrElemArray[0] =
genQRColumn(firstJoinPredItem->getValueId());
else
qrElemArray[0] = genQRExpr(firstJoinPredItem, FALSE);
idArray[0] = firstJoinPredItem->getValueId();
}
qrElemArray[joinPredElemCount] = genQRExpr(itemExpr, FALSE);
idArray[joinPredElemCount] = itemExpr->getValueId();
}
joinPredElemCount++;
}
}
} // for each member of equality set
// Create a JoinPred object if there is more than 1 table represented. If only
// one, add it to the residual preds operand list.
UInt32 hubJoinPredId = 0;
if (joinPredElemCount > 1)
{
hubJoinPredId = eqSet.getJoinPredId();
addJoinPred(jbbElem, qrElemArray, idArray, joinPredElemCount,
hubJoinPredId); // will be set only if it has no value
}
else if (joinPredElemCount == 1)
nonJoinPredOperands.insert(firstJoinPredItem);
// If a hub join pred was created from the equality set, save its id. Range
// and residual preds that use a column of the equality set will reference the
// equality set using this id.
eqSet.setJoinPredId(hubJoinPredId);
NABoolean useConstItem = FALSE;
if (constItem)
{
if (typeSupported(constItem->getType()))
useConstItem = TRUE;
else
nonJoinPredOperands.insert(constItem);
}
// If a constant was part of the equality set, create a range predicate for
// each eligible (i.e., single-node) non-joinpred member of the set, and a
// residual pred for the ineligible ones. If there is a join pred, create a
// range predicate for it.
if (useConstItem)
{
for (CollIndex i=0; i<nonJoinPredOperands.entries(); i++)
{
if (rangeIneligible.testBit(i))
addEqualityResidPred(jbbElem, nonJoinPredOperands[i], constItem);
else
addEqualityRangePred(nonJoinPredOperands[i], eqSet.getType(),
jbbElem, constItem);
}
if (hubJoinPredId)
addEqualityRangePred(hubJoinPredId, eqSet.getType(), jbbElem, constItem);
}
else if (hubJoinPredId)
{
// Create residual preds that link each nonjoin operand to the hub join pred.
for (CollIndex i=0; i<nonJoinPredOperands.entries(); i++)
addEqualityResidPred(jbbElem, nonJoinPredOperands[i], NULL,
hubJoinPredId);
}
else
{
// No hub join pred to reference. Just produce a series of equality
// residual predicates relating the equality set members.
for (CollIndex i=0; i<nonJoinPredOperands.entries()-1; i++)
addEqualityResidPred(jbbElem, nonJoinPredOperands[i],
nonJoinPredOperands[i+1]);
}
// Don't delete the element array, because the elements are used in JoinPreds
// as well as in the array. However, we can delete the parallel id array.
NADELETEBASIC(idArray, mvqrHeap_);
} // processEqualitySet()
VEGPredicate* QRDescGenerator::getVegPredicate(UInt32 hubJoinPredId)
{
QRTRACER("QRDescGenerator::getVegPredicate()");
ValueId vegRefVid = (ValueId)hubJoinPredId;
ItemExpr* ie = vegRefVid.getItemExpr();
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
ie->getOperatorType() == ITM_VEG_REFERENCE,
QRDescriptorException,
"Hub join pred id is not ValueId of vegref -- %d",
hubJoinPredId);
return (static_cast<VEGReference*>(ie))->getVEG()->getVEGPredicate();
}
void QRDescGenerator::addEqualityRangePred(ItemExpr* rangeItemExpr,
const NAType* type,
QRJBBPtr jbbElem,
ConstValue* constItem)
{
QRTRACER("QRDescGenerator::addEqualityRangePred()");
OptRangeSpec* range = new (mvqrHeap_) OptRangeSpec(this, mvqrHeap_);
if (rangeItemExpr->getOperatorType() == ITM_BASECOLUMN)
range->setRangeColValueId(rangeItemExpr->getValueId());
else
range->setRangeExpr(rangeItemExpr);
range->setType(&rangeItemExpr->getValueId().getType());
range->addSubrange(constItem, constItem, TRUE, TRUE);
ItemExpr* eqItemExpr = new(mvqrHeap_) BiRelat(ITM_EQUAL, rangeItemExpr, constItem);
eqItemExpr->synthTypeAndValueId(TRUE);
range->setID(eqItemExpr->getValueId());
range->log();
storeRangeInfo(range, jbbElem);
}
void QRDescGenerator::addEqualityRangePred(UInt32 hubJoinPredId,
const NAType* type,
QRJBBPtr jbbElem,
ConstValue* constItem)
{
QRTRACER("QRDescGenerator::addEqualityRangePred()");
OptRangeSpec* range = new (mvqrHeap_) OptRangeSpec(this, mvqrHeap_);
range->setRangeJoinPredId(hubJoinPredId);
range->setID(getVegPredicate(hubJoinPredId)->getValueId());
range->setType(type);
range->addSubrange(constItem, constItem, TRUE, TRUE);
range->log();
storeRangeInfo(range, jbbElem);
}
void QRDescGenerator::addEqualityResidPred(QRJBBPtr jbbElem,
ItemExpr* op1,
ItemExpr* op2,
ValueId hubJoinPredId)
{
QRTRACER("QRDescGenerator::addEqualityResidPred()");
ItemExpr* residExpr;
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
op1, QRDescriptorException,
"op1 of equality resid pred is null");
if (op2)
residExpr = new(mvqrHeap_) BiRelat(ITM_EQUAL, op1, op2);
else
{
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
hubJoinPredId, QRDescriptorException,
"Neither op2 nor hubJoinPredId is given");
residExpr = new(mvqrHeap_) BiRelat(ITM_EQUAL,
op1, hubJoinPredId.getItemExpr());
}
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
relExpr_,
QRDescriptorException,
"No RelExpr* stored for QRDescGenerator");
residExpr->bindNode(relExpr_->getRETDesc()->getBindWA());
processResidualPredicate(residExpr->getValueId(), jbbElem);
}
void QRDescGenerator::processReferencingPreds(CANodeIdSet* nodeSet,
RelExpr* gbNode,
QRJBBPtr jbbElem)
{
QRTRACER("QRDescGenerator::processReferencingPreds()");
ValueIdSet preds;
NodeAnalysis* nodeAnalysis;
TableAnalysis* tableAnalysis;
// Gather all the predicates referencing a member of the nodeset.
for (CANodeId node = nodeSet->init();
nodeSet->next(node);
nodeSet->advance(node))
{
nodeAnalysis = node.getNodeAnalysis();
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
nodeAnalysis, QRDescriptorException,
"No NodeAnalysis found for CA node id %ud", node.toUInt32());
tableAnalysis = nodeAnalysis->getTableAnalysis();
if (tableAnalysis)
{
preds.addSet(tableAnalysis->getReferencingPreds());
// Constant preds, like return_false (for a combination of preds that
// can't be satisfied), or a pred on current_date, etc., appear only
// in localPreds, so add those.
preds.addSet(tableAnalysis->getLocalPreds());
}
}
// Add any predicates attached to the Group By node. Count(*) will not have
// been pushed down to one of the scan nodes.
if (gbNode)
preds.addSet(gbNode->getSelectionPredicates());
// Identify equality sets implied by vegpreds and equality conditions, and
// translate these to joinpred/range/residual predicates in the descriptor.
NAList<EqualitySet*> equalitySets;
formEqualitySets(preds, equalitySets);
for (CollIndex i=0; i<equalitySets.entries(); i++)
processEqualitySet(jbbElem, *equalitySets[i]);
// Iterate over the remaining preds and generate range or residual predicates
// as needed. The preds involved in equality sets have been removed by
// formEqualitySets().
for (ValueId predVid=preds.init(); preds.next(predVid); preds.advance(predVid))
{
OptRangeSpec* range = OptRangeSpec::createRangeSpec(this,
predVid.getItemExpr(),
mvqrHeap_);
if (range)
storeRangeInfo(range, jbbElem);
else // residual predicate
processResidualPredicate(predVid, jbbElem);
}
// Delete the equality sets and clean up the hash tables that reference them.
discardEqualitySets(equalitySets);
// Move eqset ptrs to QRDescGenerator member var before exiting scope. They
// may be used later to rewrite a vegpred.
for (CollIndex i=0; i<equalitySets.entries(); i++)
allEqualitySets_.insert(equalitySets[i]);
}
void QRDescGenerator::discardEqualitySets(NAList<EqualitySet*>& equalitySets)
{
QRTRACER("QRDescGenerator::discardEqualitySets()");
// Iterate over all keys in the vid->eqset hash table and delete them.
NAHashDictionaryIterator<QRValueId, EqualitySet> vegsHashIter(vegsUsedHash_);
QRValueId* vidKey;
EqualitySet* value;
for (CollIndex i=0; i<vegsHashIter.entries(); i++)
{
vegsHashIter.getNext(vidKey, value);
delete vidKey;
}
// Now delete the keys in the exprtext->eqset hash table.
NAHashDictionaryIterator<const NAString, EqualitySet>
exprsHashIter(exprsUsedHash_);
const NAString* exprKey;
for (CollIndex i=0; i<exprsHashIter.entries(); i++)
{
exprsHashIter.getNext(exprKey, value);
delete exprKey;
}
// Empty the hash tables so they will be clean for the next JBB processed.
// Can't let them delete their contents, because the key to value relationship
// is many to one, so some of the values (EqualitySets) would be deleted more
// than once. You can't request that only keys be deleted, so we have to
// delete both the keys (above) and values (below, by iterating over the list
// of equality sets) ourselves.
vegsUsedHash_.clear(FALSE);
exprsUsedHash_.clear(FALSE);
// Delete all the equality sets, which were dynamically allocated so a
// persistent pointer could be used as the value referenced in the hash
// tables.
//@ZXeqset
//for (CollIndex i=0; i<equalitySets.entries(); i++)
// delete equalitySets[i];
}
void QRDescGenerator::combineEqSets(EqualitySet* source,
EqualitySet* destination,
NAList<EqualitySet*>& equalitySets)
{
QRTRACER("QRDescGenerator::combineEqSets()");
// Combine the two lists.
destination->insert(*source);
delete source;
equalitySets.remove(source);
// Change ptrs in hash tables from source to destination list.
NAHashDictionaryIterator<QRValueId, EqualitySet>
vegsHashIter(vegsUsedHash_);
NAHashDictionaryIterator<const NAString, EqualitySet>
exprsHashIter(exprsUsedHash_);
// Iterate over all key/value pairs in the hash table (iterator doesn't allow
// iterating over a selected value alone), selecting those keys that have the
// source equality set as a value. I'm not sure how manipulating the hash
// table in mid-iteration would affect the iteration, so we keep the keys in
// a list, and delete/reinsert them with the new equality set after completing
// the iteration.
QRValueId* vidKey;
EqualitySet* ptrListValue;
NAList<QRValueId*> vidsToRemove(mvqrHeap_);
CollIndex i;
for (i=0; i<vegsHashIter.entries(); i++)
{
vegsHashIter.getNext(vidKey, ptrListValue); // get key and value
if (ptrListValue == source)
vidsToRemove.insert(vidKey);
}
// Remove and reinsert keys referencing the old (source) equality set.
for (i=0; i<vidsToRemove.entries(); i++)
{
vegsUsedHash_.remove(vidsToRemove[i]);
vegsUsedHash_.insert(vidsToRemove[i], destination);
}
// Now iterate over the hash table that uses expression text as a key, the
// same as with the ValueId keys above.
const NAString* exprKey;
NAList<const NAString*> exprsToRemove(mvqrHeap_);
for (i=0; i<exprsHashIter.entries(); i++)
{
exprsHashIter.getNext(exprKey, ptrListValue);
if (ptrListValue == source)
exprsToRemove.insert(exprKey);
}
// Remove and reinsert expression text keys referencing the old (source)
// equality set.
for (i=0; i<exprsToRemove.entries(); i++)
{
exprsUsedHash_.remove(exprKey);
exprsUsedHash_.insert(exprKey, destination);
}
} // combineEqSets()
// If no members were found in any other list, create a new equality list,
// populate it with the members of the vegpred, and add it to the list of lists.
// Also add the ValueId or expression text of each member to the appropriate
// hash table, with the address of the containing list as the value. The ValueId
// of the veg itself is also added as a key, so an equality operator that uses
// a vegref will find it. We have to create heap-allocated copies of the hash
// keys, because they need to persist beyond this function.
//
// Takes ValueIdSet and veg vid instead of VEG because we may remove one or more
// members from a local copy of a veg member list before making this call.
void QRDescGenerator::putVegMembersInEqualitySet(
ItemExpr* vegPred, // NULL if called for equality pred
const ValueId& vegVid,
const ValueIdSet& vegVals,
EqualitySet*& eqSet, // will be set if NULL
NAList<EqualitySet*>& equalitySets)
{
QRTRACER("QRDescGenerator::putVegMembersInEqualitySet()");
// Make sure they weren't all removed because they were already members of
// other separate-but-equal lists.
if (vegVals.isEmpty())
return;
// Create list if one was not passed in, which is the case when an existing
// compatible equality set is not found.
if (!eqSet)
{
eqSet = new(mvqrHeap_) EqualitySet(mvqrHeap_);
equalitySets.insert(eqSet);
}
// If this fn was called for a vegpred instead of a simple equality pred, use
// the vegpred's value id as the joinpred id. If no vegpreds contribute to this
// equality set, the value id of one of the members of the equality set will
// be used.
if (vegPred)
eqSet->setJoinPredId(((VEGPredicate*)vegPred)->getVEG()->getVEGReference()
->getValueId());
// Put the value id of this veg in the hash table. The ValueIds of the
// individual members will be added as well. NAHashDictionary is pointer-based,
// so we have to allocate a copy of the ValueId on the heap, so it will
// persist beyond this function. Note that ValueId is not an NABasicObject,
// so we use the system heap.
//
QRValueId* vegVidPtr = new QRValueId(vegVid);
vegsUsedHash_.insert(vegVidPtr, eqSet);
// Put the veg members in the list and in the hash tables.
ItemExpr* itemExpr;
OperatorTypeEnum op;
QRValueId* vidPtr;
NAString* exprTextPtr;
for (ValueId vid=vegVals.init(); vegVals.next(vid); vegVals.advance(vid))
{
itemExpr = vid.getItemExpr();
op = itemExpr->getOperatorType();
if (op == ITM_BASECOLUMN)
{
eqSet->insert(itemExpr);
vidPtr = new QRValueId(vid);
vegsUsedHash_.insert(vidPtr, eqSet);
}
else if (op != ITM_INDEXCOLUMN)
{
// Constants are lumped in with general expressions, because when
// query caching is enabled they are converted to params with
// distinct ValueIds for each occurrence.
eqSet->insert(itemExpr);
exprTextPtr = new(mvqrHeap_) NAString(mvqrHeap_);
itemExpr->unparse(*exprTextPtr, OPTIMIZER_PHASE, MVINFO_FORMAT);
exprsUsedHash_.insert(exprTextPtr, eqSet);
}
}
} // putVegMembersInEqualitySet()
void QRDescGenerator::addVegPredToEqualitySets(
VEGPredicate* vegPred,
NAList<EqualitySet*>& equalitySets)
{
QRTRACER("QRDescGenerator::addVegPredToEqualitySets()");
ValueIdSet vegVals;
vegPred->getVEG()->getAndExpandAllValues(vegVals);
EqualitySet* eqSet;
EqualitySet* targetEqSet = NULL;
ItemExpr* itemExpr;
NAString exprText;
OperatorTypeEnum op;
QRValueId vidNum;
for (ValueId vid=vegVals.init(); vegVals.next(vid); vegVals.advance(vid))
{
itemExpr = vid.getItemExpr();
op = itemExpr->getOperatorType();
if (op == ITM_BASECOLUMN)
{
// Probe with base col vid. These are in hash table as well as veg
// vids, to handle all cases.
vidNum = vid;
eqSet = vegsUsedHash_.getFirstValue(&vidNum);
}
else if (op != ITM_INDEXCOLUMN)
{
// Constants are lumped in with general expressions, because when
// query caching is enabled they are converted to params with
// distinct ValueIds for each occurrence.
// @ZX -- maybe add case for caching turned off
exprText = "";
itemExpr->unparse(exprText, OPTIMIZER_PHASE, MVINFO_FORMAT);
eqSet = exprsUsedHash_.getFirstValue(&exprText);
}
else
eqSet = NULL;
if (eqSet)
{
// Remove the item that was found in the hash table, because it is
// already in an existing list that the members of this vegpred will
// be merged with.
vegVals.subtractElement(vid);
// If this is not the first list we've found, merge it into the target
// list (the one the members of this vegpred will be added to).
if (targetEqSet)
{
if (eqSet != targetEqSet)
combineEqSets(eqSet, targetEqSet, equalitySets);
}
else
targetEqSet = eqSet;
}
}
// Add the members to targetEqSet, or if it is null, create a new list.
putVegMembersInEqualitySet(vegPred, vegPred->getVEG()->getValueId(), vegVals,
targetEqSet, equalitySets);
} // addVegPredToEqualitySets()
void QRDescGenerator::addEqPredToEqualitySets(
ItemExpr* pred,
NAList<EqualitySet*>& equalitySets)
{
QRTRACER("QRDescGenerator::addEqPredToEqualitySets()");
EqualitySet* eqSet;
EqualitySet* targetEqSet = NULL;
ItemExpr* eqOperand;
OperatorTypeEnum op;
NAString exprText;
QRValueId vid;
NABoolean moveToTarget[] = {TRUE, TRUE};
assertLogAndThrow(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
pred->getOperatorType() == ITM_EQUAL,
QRDescriptorException,
"addEqPredToEqualitySets() called for non-equality predicate");
for (Int32 i=0; i<2; i++)
{
eqOperand = pred->child(i);
op = eqOperand->getOperatorType();
if (op == ITM_VEG_REFERENCE)
{
vid = ((VEGReference*)eqOperand)->getVEG()->getValueId();
eqSet = vegsUsedHash_.getFirstValue(&vid);
}
else
{
exprText = "";
eqOperand->unparse(exprText, OPTIMIZER_PHASE, MVINFO_FORMAT);
eqSet = exprsUsedHash_.getFirstValue(&exprText);
}
if (eqSet)
{
moveToTarget[i] = FALSE; // already there
// If this is not the first list we've found (the one we will add the
// eq operands to), merge it into the target list.
if (targetEqSet)
{
if (eqSet != targetEqSet)
combineEqSets(eqSet, targetEqSet, equalitySets);
}
else
targetEqSet = eqSet;
}
}
// Put the equality operands in a list (either new or created) and hash
// tables, unless they were already members of a separate-but-equal list.
for (Int32 i=0; i<2; i++)
{
if (!moveToTarget[i])
continue; // already in target list
eqOperand = pred->child(i);
op = eqOperand->getOperatorType();
if (op == ITM_VEG_REFERENCE)
{
VEG* veg = ((VEGReference*)eqOperand)->getVEG();
// This will create targetEqSet if it is NULL.
putVegMembersInEqualitySet(NULL,
veg->getValueId(), veg->getAllValues(),
targetEqSet, equalitySets);
}
else
{
if (!targetEqSet)
{
targetEqSet = new(mvqrHeap_) EqualitySet(mvqrHeap_);
equalitySets.insert(targetEqSet);
}
targetEqSet->insert(eqOperand);
NAString* exprTextPtr = new(mvqrHeap_) NAString(mvqrHeap_);
eqOperand->unparse(*exprTextPtr, OPTIMIZER_PHASE, MVINFO_FORMAT);
exprsUsedHash_.insert(exprTextPtr, targetEqSet);
}
}
} // addEqPredToEqualitySets()
void QRDescGenerator::formEqualitySets(ValueIdSet& preds, // processed preds removed
NAList<EqualitySet*>& equalitySets)
{
QRTRACER("QRDescGenerator::formEqualitySets()");
ValueId predVid;
ItemExpr* predExpr;
OperatorTypeEnum op;
// To form equality groups, we look at vegpreds and equality operators (and
// remove them from the passed set of pred ValueIds after processing them).
// The operands of each will either constitute a new equality set, or be
// merged with an existing one. In some cases, 2 or more operands may
// correspond to members of different equality sets, in which case they
// will all be merged.
for (predVid=preds.init(); preds.next(predVid); preds.advance(predVid))
{
predExpr = predVid.getItemExpr();
op = predExpr->getOperatorType();
// If it's a range spec operator, sub in the actual predicate from the
// right subtree.
if (op == ITM_RANGE_SPEC_FUNC)
{
predExpr = predExpr->child(1);
op = predExpr->getOperatorType();
}
if (op == ITM_VEG_PREDICATE)
{
addVegPredToEqualitySets((VEGPredicate*)predExpr, equalitySets);
preds.subtractElement(predVid);
}
else if (op == ITM_EQUAL)
{
addEqPredToEqualitySets(predExpr, equalitySets);
preds.subtractElement(predVid);
}
}
} // formEqualitySets()
void QRDescGenerator::setPredBitmap(QRValueId colVid, ElementType elemType)
{
QRTRACER("QRDescGenerator::setPredBitmap()");
QRElementPtr elem = getElementForValueID('C', colVid);
if (!elem)
{
ValueId vid = colVid;
OperatorTypeEnum opType = vid.getItemExpr()->getOperatorType();
if (opType == ITM_BASECOLUMN)
// Pass FALSE to prevent adding the col to the list of used cols. This
// col element is created to find its table's id and position in the
// table; it is not added to the descriptor.
elem = genQRColumn(vid, 0, FALSE);
else if (opType == ITM_VEG_REFERENCE)
{
// For a range pred on a member of a vegref, we need to set the bitmap
// entry for each column in the veg. Make recursive calls to this fn
// for each column in the veg, then exit.
ValueIdSet vegMembers =
static_cast<VEGReference*>(vid.getItemExpr())->getVEG()->getAllValues();
for (ValueId id=vegMembers.init();
vegMembers.next(id);
vegMembers.advance(id))
{
if (id.getItemExpr()->getOperatorType() == ITM_BASECOLUMN)
setPredBitmap(id, elemType);
}
return;
}
else
{
// LCOV_EXCL_START :rfi
Int32 vidInt = vid;
assertLogAndThrow2(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
FALSE, QRDescriptorException,
"ValueId %d is not a base col or veg ref -- op type = %d",
vidInt, opType);
// LCOV_EXCL_STOP
}
}
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
elem, QRDescriptorException,
"Column id not found in hash table -- %d", (UInt32)colVid);
QRColumnPtr col = elem->getReferencedElement()->downCastToQRColumn();
const NAString& tblID = col->getTableID();
elem = colTblIdHash_.getFirstValue(&tblID);
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
elem, QRDescriptorException,
"Table id not found in hash table -- %s", tblID.data());
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL,
elem->getElementType() == ET_Table, QRDescriptorException,
"Expected a Table element type, not %d",
elem->getElementType());
// Set the column's bit in the appropriate bitmap, using its ordinal position
// in the table.
if (elemType == ET_RangePred)
elem->downCastToQRTable()->setRangeBit(col->getColIndex());
else if (elemType == ET_ResidualPred)
elem->downCastToQRTable()->setResidualBit(col->getColIndex());
else
assertLogAndThrow1(CAT_SQL_COMP_QR_DESC_GEN, LL_MVQR_FAIL, // LCOV_EXCL_LINE :rfi
FALSE, QRDescriptorException,
"Wrong element type sent to setPredBitmap() -- %d",
elemType);
}
void QRDescGenerator::storeRangeInfo(OptRangeSpec* range, QRJBBPtr jbbElem)
{
QRTRACER("QRDescGenerator::storeRangeInfo()");
RangeInfo* rangeInfo = NULL;
NAString* exprText = NULL;
QRValueId* key = new QRValueId(range->getRangeJoinPredId());
if (*key != NULL_VALUE_ID)
rangeInfo = rangeColHash_.getFirstValue(key);
else if (range->getRangeColValueId() != NULL_VALUE_ID)
{
*key = range->getRangeColValueId();
rangeInfo = rangeColHash_.getFirstValue(key);
}
else
{
exprText = new NAString(range->getRangeExprText());
rangeInfo = rangeExprHash_.getFirstValue(exprText);
}
// If a range was already created for another predicate on this column or
// expression, intersect it with this range.
if (rangeInfo)
{
rangeInfo->getRangeSpec()->intersectRange(range);
// Don't need these since new hash entry was not created.
delete key;
delete exprText;
delete range;
range = NULL; // makes it easier to debug use after deletion
}
else if (*key != NULL_VALUE_ID)
rangeColHash_.insert(key, new(mvqrHeap_) RangeInfo(range, jbbElem));
else
{
rangeExprHash_.insert(exprText, new(mvqrHeap_) RangeInfo(range, jbbElem));
delete key;
}
}
NABoolean QRDescGenerator::isRangeSupported(QRRangePredPtr rangePred)
{
Int32 rangeExprSize = rangePred->getSize();
if (rangeExprSize > maxExprSize_)
return FALSE;
return TRUE;
}
void QRDescGenerator::addRangePredicates()
{
QRTRACER("QRDescGenerator::addRangePredicates()");
QRValueId* vid;
const NAString* exprText;
RangeInfo* rangeInfo;
OptRangeSpec* rangeSpec;
QRRangePredPtr rangePred;
NAHashDictionaryIterator<QRValueId, RangeInfo> vidIter(rangeColHash_);
for (CollIndex i=0; i<vidIter.entries(); i++)
{
vidIter.getNext(vid, rangeInfo);
rangeSpec = rangeInfo->getRangeSpec();
rangeSpec->addColumnsUsed(this);
rangeSpec->addConstraints(this);
if (rangeSpec->isFalse())
{
// Unsatisfiable condition; generate FALSE as a residual predicate.
BindWA bindWA(ActiveSchemaDB(), CmpCommon::context());
ItemExpr* expr = new(mvqrHeap_) BoolVal(ITM_RETURN_FALSE);
expr->bindNode(&bindWA);
processResidualPredicate(expr->getValueId(), rangeInfo->getJbbElem());
}
else
{
rangePred = rangeSpec->createRangeElem();
// The OptRangeSpec may involve a tautology (e.g., a>20 OR a<25 OR
// a is null), which is equivalent to no range restriction at all.
if (rangePred)
{
if ((isQueryMode() || isDumpMvMode()) &&
!isRangeSupported(rangePred))
{
// This range predicate is too big, or unsuitable for a descriptor
// for some other reason. Replace it with an empty range pred
// marked as NotProvided.
QRRangePredPtr notProvidedRangePred = new(mvqrHeap_)
QRRangePred(ADD_MEMCHECK_ARGS(mvqrHeap_));
QRElementPtr rangeItem = rangePred->getRangeItem();
rangePred->setRangeItem(NULL);
notProvidedRangePred->setRangeItem(rangeItem);
notProvidedRangePred->setID(rangePred->getIDNum());
notProvidedRangePred->setResult(QRElement::NotProvided);
// Now delete the full range pred and use the empty one instead.
deletePtr(rangePred);
rangePred = notProvidedRangePred;
}
// Add the RangePred to the appropriate RangePredList, and set the
// column's bit in the range predicate bitmap.
rangeInfo->getOwningList()->addItemOrdered(rangePred);
setPredBitmap(*vid, ET_RangePred);
}
}
}
rangeColHash_.clear(TRUE);
NAHashDictionaryIterator<const NAString, RangeInfo> exprIter(rangeExprHash_);
for (CollIndex i=0; i<exprIter.entries(); i++)
{
exprIter.getNext(exprText, rangeInfo);
rangePred = rangeInfo->getRangeSpec()->createRangeElem();
// The OptRangeSpec may involve a tautology (e.g., a>20 or a<25), which is
// equivalent to no range restriction at all.
if (rangePred)
rangeInfo->getOwningList()->addItemOrdered(rangePred);
}
rangeExprHash_.clear(TRUE);
}
QRElementPtr QRDescGenerator::getElementForValueID(char firstChar, UInt32 id) const
{
QRTRACER("QRDescGenerator::getElementForValueID()");
char buff[12];
QRValueId vid(id);
buff[0] = firstChar;
str_itoa(vid, buff+1);
NAString idStr(buff);
return colTblIdHash_.getFirstValue(&idStr);
}
void QRDescGenerator::mergeDescGenerator(const QRDescGenerator* other)
{
mColumnsUsed_ += other->mColumnsUsed_;
mExtraHubColumnsUsed_ += other->mExtraHubColumnsUsed_;
const NAString* key;
QRElementPtr value;
QRElementHashIterator otherIter(other->colTblIdHash_);
for (CollIndex i=0; i<otherIter.entries(); i++)
{
otherIter.getNext(key, value);
colTblIdHash_.insert(key, value);
}
}
|
ec80431b6bce7aa0b55b055e536fd00764d7346d
|
9eb2245869dcc3abd3a28c6064396542869dab60
|
/benchspec/CPU/510.parest_r/build/build_base_mytest-64.0000/source/libparest/parameter/field_discretization.cc
|
316d98f72842627c511b6f15985a3bc2467f875b
|
[] |
no_license
|
lapnd/CPU2017
|
882b18d50bd88e0a87500484a9d6678143e58582
|
42dac4b76117b1ba4a08e41b54ad9cfd3db50317
|
refs/heads/master
| 2023-03-23T23:34:58.350363
| 2021-03-24T10:01:03
| 2021-03-24T10:01:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,980
|
cc
|
field_discretization.cc
|
#include <base/quadrature_lib.h>
#include <base/parameter_handler.h>
#include <lac/vector.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_constraints.h>
#include <dofs/dof_tools.h>
#include <fe/fe.h>
#include <fe/fe_dgq.h>
#include <libparest/utilities.h>
#include <libparest/parameter/bounds.h>
#include <libparest/parameter/field_discretization.h>
namespace libparest
{
namespace Parameter
{
namespace Field
{
/* ---------------------- Triangulations ------------------ */
template <int dim>
Triangulations<dim>::Triangulations (const Triangulation<dim> &old_parameter,
const GridTransfer::Base<dim> &mesh_refinement)
{
parameter.copy_triangulation (old_parameter);
mesh_refinement.refine_grid (parameter);
}
template <int dim>
Triangulations<dim>::~Triangulations ()
{}
/* ---------------------- FiniteElements ------------------ */
template <int dim>
void
FiniteElements<dim>::Parameters::declare_parameters (ParameterHandler &prm)
{
prm.enter_subsection ("Distributed parameter field");
prm.declare_entry ("Finite element", "discontinuous constant",
Patterns::Anything ());
prm.leave_subsection ();
}
template <int dim>
void
FiniteElements<dim>::Parameters::parse_parameters (ParameterHandler &prm)
{
prm.enter_subsection ("Distributed parameter field");
name = prm.get ("Finite element");
prm.leave_subsection ();
}
template <int dim>
void
FiniteElements<dim>::Parameters::delete_parameters ()
{
name = "";
}
template <int dim>
FiniteElements<dim>::FiniteElements (const Parameters &parms)
:
fe (FEHelper<dim>::get_fe(parms.name)),
quadrature (FEHelper<dim>::get_quadrature (parms.name)),
face_quadrature (dim != 1 ?
FEHelper<dim>::get_quadrature_face (parms.name) :
*static_cast<const Quadrature<dim-1>*>(0))
{}
template <int dim>
FiniteElements<dim>::~FiniteElements ()
{}
/* ---------------------- DoFHandlers ------------------ */
template <int dim>
DoFHandlers<dim>::DoFHandlers (Triangulations<dim> &triangulations,
const FiniteElements<dim> &fe)
:
parameter (triangulations.parameter),
fe (&fe),
triangulations (&triangulations)
{
reinitialize ();
}
template <int dim>
void
DoFHandlers<dim>::reinitialize ()
{
parameter.distribute_dofs (fe->fe);
parameter_constraints.clear ();
DoFTools::make_hanging_node_constraints (parameter, parameter_constraints);
parameter_constraints.close ();
}
template <int dim>
DoFHandlers<dim>::~DoFHandlers ()
{}
/* ---------------------- DiscretizedField ------------------ */
template <int dim>
DiscretizedField<dim>::
DiscretizedField (Triangulations *triangulations,
FiniteElements *finite_elements,
const Bounds::Base<dim> ¶meter_bounds)
:
triangulations (triangulations),
finite_elements (finite_elements),
dof_handlers (0),
parameter_bounds (¶meter_bounds)
{
dof_handlers = new DoFHandlers (*triangulations,
*finite_elements);
recompute_bounds ();
}
template <int dim>
DiscretizedField<dim>::~DiscretizedField ()
{
delete_ptr (dof_handlers);
delete_ptr (finite_elements);
delete_ptr (triangulations);
}
template <int dim>
void
DiscretizedField<dim>::
refine_parameterization (const std::vector<bool> &refinement_indicators,
const std::vector<bool> &coarsening_indicators)
{
triangulations->parameter.load_refine_flags (refinement_indicators);
triangulations->parameter.load_coarsen_flags (coarsening_indicators);
#ifdef DEBUG
{
std::vector<bool> tmp1 (refinement_indicators.size());
std::vector<bool> tmp2 (refinement_indicators.size());
triangulations->parameter.prepare_coarsening_and_refinement ();
triangulations->parameter.save_refine_flags (tmp1);
triangulations->parameter.save_coarsen_flags (tmp2);
Assert (refinement_indicators == tmp1, ExcInternalError());
Assert (coarsening_indicators == tmp2, ExcInternalError());
}
#endif
triangulations->parameter.execute_coarsening_and_refinement ();
dof_handlers->reinitialize ();
recompute_bounds ();
}
template <int dim>
void
DiscretizedField<dim>::
set_back_to_bounds (Vector<double> &v) const
{
Assert (v.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (lower_bounds.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (upper_bounds.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
for (unsigned int i=0; i<v.size(); ++i)
if (v(i) < lower_bounds[i])
v(i) = lower_bounds[i];
else
if (v(i) > upper_bounds[i])
v(i) = upper_bounds[i];
}
template <int dim>
bool
DiscretizedField<dim>::
satisfies_bounds (const Vector<double> &v) const
{
Assert (v.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (lower_bounds.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (upper_bounds.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
for (unsigned int i=0; i<v.size(); ++i)
if ((v(i) < lower_bounds[i]) ||
(v(i) > upper_bounds[i]))
return false;
return true;
}
template <int dim>
void
DiscretizedField<dim>::
at_lower_bounds (const Vector<double> &v,
std::vector<bool> &flags) const
{
Assert (v.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (v.size() == flags.size(), ExcInternalError());
Assert (lower_bounds.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (upper_bounds.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
for (unsigned int i=0; i<v.size(); ++i)
flags[i] = (v(i) <= lower_bounds[i]);
}
template <int dim>
void
DiscretizedField<dim>::
at_upper_bounds (const Vector<double> &v,
std::vector<bool> &flags) const
{
Assert (v.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (v.size() == flags.size(), ExcInternalError());
Assert (lower_bounds.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (upper_bounds.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
for (unsigned int i=0; i<v.size(); ++i)
flags[i] = (v(i) >= upper_bounds[i]);
}
template <int dim>
void
DiscretizedField<dim>::
recompute_bounds ()
{
lower_bounds.resize (dof_handlers->parameter.n_dofs());
upper_bounds.resize (dof_handlers->parameter.n_dofs());
parameter_bounds->get_bounds (dof_handlers->parameter,
lower_bounds,
upper_bounds);
}
template <int dim>
void
DiscretizedField<dim>::
set_to_mean_of_bounds (Vector<double> &v) const
{
Assert (v.size() == dof_handlers->parameter.n_dofs(), ExcInternalError());
Assert (v.size() == lower_bounds.size(), ExcInternalError());
Assert (v.size() == upper_bounds.size(), ExcInternalError());
for (unsigned int i=0; i<v.size(); ++i)
v(i) = (lower_bounds[i] + upper_bounds[i]) / 2;
}
}
namespace Field
{
template class Triangulations<deal_II_dimension>;
template class FiniteElements<deal_II_dimension>;
template class DoFHandlers<deal_II_dimension>;
template class DiscretizedField<deal_II_dimension>;
}
}
}
|
9a9b42e5dd99adbe22ba17bb4da373f26b11c917
|
04866171457b2527f72a6c6d69c58f5a40188f75
|
/alarm/src/alarm.ino
|
afd8e3b3e797fc818947342ece017e8c9efff47d
|
[] |
no_license
|
meisteg/TempAlarmFirmware
|
379a1a4a977f11f72ba87a995a37ce1a3c911e9c
|
b39c341a09018f8efadcfd31f2f47c7d592be6ed
|
refs/heads/master
| 2021-07-06T14:52:33.217724
| 2021-04-10T20:11:18
| 2021-04-10T20:11:18
| 228,218,435
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,579
|
ino
|
alarm.ino
|
/*
* Copyright (C) 2020 Gregory S. Meiste <http://gregmeiste.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define SERIAL Serial // USB port
//#define SERIAL Serial1 // TX/RX pins
#define SERIAL_BAUD 115200
// Not defined by DeviceOS for some reason
#define RGB_COLOR_NONE 0x00000000
#define PIN_PIEZO D0
#define ALARM_FREQ 4000
#define NOTE_G3 2551
#define NOTE_G4 1276
#define NOTE_C5 956
#define NOTE_E5 759
#define NOTE_G5 638
#define RELEASE 20
#define BPM 100
// Notes in the startup melody:
int melody[] = {NOTE_E5,NOTE_E5,0,NOTE_E5,0,NOTE_C5,NOTE_E5,0,NOTE_G5,0,0,NOTE_G4};
// Note durations: 4 = quarter note, 2 = half note, etc.:
int noteDurations[] = {4,4,4,4,4,4,4,4,4,2,4,4};
LEDStatus blinkRed(RGB_COLOR_RED, LED_PATTERN_BLINK, LED_SPEED_NORMAL, LED_PRIORITY_IMPORTANT);
// Used to setup the system LED theme: disable the breathing cyan on cloud connection
LEDSystemTheme theme;
void sensor_data(const char *event, const char *data)
{
SERIAL.printlnf("%s: %s", event, data);
// Maybe someday we'll do more with this data...
}
void temp_alarm(const char *event, const char *data)
{
SERIAL.printlnf("%s: %s", event, data);
blinkRed.setActive(true);
tone(PIN_PIEZO, ALARM_FREQ, 60000);
}
void button_press(system_event_t event, int param)
{
SERIAL.printlnf("button_press: param=%d", param);
// Zero means press, non-zero is duration
if (param == 0)
{
// Priority is to handle the alarm event
if (blinkRed.isActive())
{
blinkRed.setActive(false);
noTone(PIN_PIEZO);
}
// Enable/disable breathing cyan if not alarming
else if (theme.color(LED_SIGNAL_CLOUD_CONNECTED) == RGB_COLOR_NONE)
{
theme.setColor(LED_SIGNAL_CLOUD_CONNECTED, RGB_COLOR_CYAN);
theme.apply();
}
else
{
theme.setColor(LED_SIGNAL_CLOUD_CONNECTED, RGB_COLOR_NONE);
theme.apply();
}
}
}
int set_tone(String freq)
{
tone(PIN_PIEZO, atoi(freq.c_str()), 2000);
return 0;
}
void setup() {
SERIAL.begin(SERIAL_BAUD);
SERIAL.println("Temperature alarm initializing");
Particle.subscribe("sensorData", sensor_data, MY_DEVICES);
Particle.subscribe("tempAlarm", temp_alarm, MY_DEVICES);
System.on(button_status, button_press);
theme.setColor(LED_SIGNAL_CLOUD_CONNECTED, RGB_COLOR_NONE);
theme.apply();
Particle.function("toneFreq", set_tone);
// Iterate over the notes of the startup melody:
for (unsigned int note = 0; note < (sizeof(melody) / sizeof(melody[0])); note++)
{
// To calculate the note duration, take one second
// divided by the note type.
// e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 60 * 1000 / BPM / noteDurations[note];
tone(PIN_PIEZO, (melody[note] != 0) ? (500000/melody[note]) : 0, noteDuration - RELEASE);
// Blocking delay needed because tone() does not block
delay(noteDuration);
}
}
void loop() {
// Nothing to do
}
|
ec30b270b36ec2be51c545694fe09e31ee3d3e46
|
592a279f868ebe8c0fbdffc1136461c85e818cad
|
/algo/acm/codeforces/1-14/6b.cc
|
98de7f2872e64f597c29533b58cf19eb790ad9ff
|
[
"Unlicense"
] |
permissive
|
seckcoder/lang-learn
|
ad0e849e7575a47bd5cd88d1ff4c56a4eec8ec65
|
1e0d6f412bbd7f89b1af00293fd907ddb3c1b571
|
refs/heads/master
| 2021-01-20T06:56:49.322037
| 2015-10-28T22:25:05
| 2015-10-28T22:25:05
| 13,863,341
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,166
|
cc
|
6b.cc
|
//#define SECK_DEBUG
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <cstdlib>
#include <numeric>
#include <ctime>
#include <algorithm>
#include <set>
#include <string>
#include <iomanip>
#include <cmath>
#include <map>
#include <functional>
#include <climits>
#include <cstdio>
#include <cassert>
using std::cout;
using std::endl;
using std::vector;
using std::set;
using std::cin;
using std::string;
using std::map;
using std::cerr;
using std::ostream;
using std::istream;
#define PI 3.14159265359
#define IS_ODD(v) ((v) & 1)
//#define IS_EVEN(v) (((v) - (((v) >> 1) << 1)) == 0)
typedef long long int int64;
typedef unsigned char uint8;
ostream &operator<<(ostream &os, const uint8 v) {
os << (int)v;
return os;
}
istream &operator>>(istream &is, uint8 &v) {
int tmp;
is >> tmp;
v = (uint8)tmp;
return is;
}
class Point {
public:
uint8 x;
uint8 y;
};
#define L 100
#define W 100
class Rect {
public:
Point ll, ur;
Rect() {
ll.x = L;
ll.y = W;
ur.x = 0;
ur.y = 0;
}
void update(uint8 x, uint8 y) {
ll.x = std::min(ll.x, x);
ll.y = std::min(ll.y, y);
ur.x = std::max(ur.x, x);
ur.y = std::max(ur.y, y);
}
};
int main(int argc, const char *argv[])
{
#ifdef SECK_DEBUG
freopen("test.in", "r", stdin);
#endif
uint8 l, w;
char c;
cin >> l >> w >> c;
string room[W];
for (int i = l-1; i >= 0; i--) {
cin >> room[i];
}
Rect president;
for (int i = 0; i < l; i++) {
for (int j = 0; j < w; j++) {
//cout << room[i][j] << endl;
if (room[i][j] == c) {
president.update(j,i);
}
}
}
/*cout << president.ll.x << " " << president.ur.x << endl
<< president.ll.y << " " << president.ur.y << endl;*/
if (president.ll.x > president.ur.x
|| president.ll.y > president.ur.y) {
printf("0");
} else {
bool deputies[26] = {false};
// up
if (president.ur.y < l-1) {
int y = president.ur.y + 1;
for (int x = president.ll.x; x <= president.ur.x; x++) {
if (room[y][x] != '.') {
deputies[room[y][x]-'A'] = true;
}
}
}
// left
if (president.ll.x > 0) {
int x = president.ll.x - 1;
for (int y = president.ll.y; y <= president.ur.y; y++) {
if (room[y][x] != '.') {
deputies[room[y][x]-'A'] = true;
}
}
}
// right
if (president.ur.x < w-1) {
int x = president.ur.x + 1;
for (int y = president.ll.y; y <= president.ur.y; y++) {
if (room[y][x] != '.') {
deputies[room[y][x]-'A'] = true;
}
}
}
// down
if (president.ll.y > 0) {
int y = president.ll.y - 1;
for (int x = president.ll.x; x <= president.ur.x; x++) {
if (room[y][x] != '.') {
deputies[room[y][x]-'A'] = true;
}
}
}
int ans = 0;
for (int i = 0; i < 26; i++) {
if (deputies[i]) {
//cout << char(i + 'A') << endl;
ans += 1;
}
}
cout << ans << endl;
}
#ifdef SECK_DEBUG
cerr << "\nTime = " << 1000* (double(clock()) / CLOCKS_PER_SEC) << "ms" << endl;
#endif
return 0;
}
|
127e543f0bad8ebbc4928e187a8a832372f444d2
|
eda03521b87da8bdbef6339b5b252472a5be8d23
|
/Kernel/FileSystem/FATFS/Definitions.h
|
938fc064b3aec6da2901d08d010fe59b553687d7
|
[
"BSD-2-Clause"
] |
permissive
|
SerenityOS/serenity
|
6ba3ffb242ed76c9f335bd2c3b9a928329cd7d98
|
ef9b6c25fafcf4ef0b44a562ee07f6412aeb8561
|
refs/heads/master
| 2023-09-01T13:04:30.262106
| 2023-09-01T08:06:28
| 2023-09-01T10:45:38
| 160,083,795
| 27,256
| 3,929
|
BSD-2-Clause
| 2023-09-14T21:00:04
| 2018-12-02T19:28:41
|
C++
|
UTF-8
|
C++
| false
| false
| 1,921
|
h
|
Definitions.h
|
/*
* Copyright (c) 2022, Undefine <undefine@undefine.pl>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/DOSPackedTime.h>
#include <AK/EnumBits.h>
#include <AK/Types.h>
namespace Kernel {
struct [[gnu::packed]] FAT32BootRecord {
u8 boot_jump[3];
char oem_identifier[8];
u16 bytes_per_sector;
u8 sectors_per_cluster;
u16 reserved_sector_count;
u8 fat_count;
u16 root_directory_entry_count;
u16 unused1;
u8 media_descriptor_type;
u16 unused2;
u16 sectors_per_track;
u16 head_count;
u32 hidden_sector_count;
u32 sector_count;
u32 sectors_per_fat;
u16 flags;
u16 fat_version;
u32 root_directory_cluster;
u16 fs_info_sector;
u16 backup_boot_sector;
u8 unused3[12];
u8 drive_number;
u8 unused4;
u8 signature;
u32 volume_id;
char volume_label_string[11];
char system_identifier_string[8];
};
static_assert(sizeof(FAT32BootRecord) == 90);
enum class FATAttributes : u8 {
ReadOnly = 0x01,
Hidden = 0x02,
System = 0x04,
VolumeID = 0x08,
Directory = 0x10,
Archive = 0x20,
LongFileName = 0x0F
};
AK_ENUM_BITWISE_OPERATORS(FATAttributes);
struct [[gnu::packed]] FATEntry {
char filename[8];
char extension[3];
FATAttributes attributes;
u8 unused1;
u8 creation_time_seconds;
DOSPackedTime creation_time;
DOSPackedDate creation_date;
DOSPackedDate last_accessed_date;
u16 first_cluster_high;
DOSPackedTime modification_time;
DOSPackedDate modification_date;
u16 first_cluster_low;
u32 file_size;
};
static_assert(sizeof(FATEntry) == 32);
struct [[gnu::packed]] FATLongFileNameEntry {
u8 entry_index;
u16 characters1[5];
FATAttributes attributes;
u8 entry_type;
u8 checksum;
u16 characters2[6];
u16 zero;
u16 characters3[2];
};
static_assert(sizeof(FATLongFileNameEntry) == 32);
}
|
ddc144d85bd9cab8e46fe175b6af9c5c61af42e0
|
ef21d605f07fb9b342f050b0ce4ecfb8dd5f3aab
|
/Classes/TSStagePlayLayerCommon.cpp
|
fb4deb1ce55f4951cb8894142cb5a991a14cf5b3
|
[] |
no_license
|
timxie2008/TreasuresGleaner
|
532384b09969408f2545278e41237a8192f92ac8
|
ba325746c5b66345ab99399b27e235c766a3653f
|
refs/heads/master
| 2021-01-22T01:33:14.331450
| 2012-11-16T05:18:20
| 2012-11-16T05:18:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 320
|
cpp
|
TSStagePlayLayerCommon.cpp
|
#include "TSStagePlayLayerCommon.h"
TSStagePlayLayerCommon::TSStagePlayLayerCommon(CAStage* pstage, CAStageLayer* playerParent) : CAStageLayer(pstage, playerParent)
{
_Trace("%s allocated", __FUNCTION__);
}
TSStagePlayLayerCommon::~TSStagePlayLayerCommon(void)
{
_Trace("%s destroyed", __FUNCTION__);
}
|
cd33e1bc0ec9b8bc589eee57acd520b62b5a27c2
|
2d5aaa49e25a54ad67d2e3af147da40de823afdb
|
/c++/constructores.cpp
|
b00dde326a8fce6a5f4e0bab6ee823deebc9fc4c
|
[] |
no_license
|
Juanp-Romero/Programacion_21_I_H1
|
b014d10f927604b8ef132d21ef8dc78e58cf0f0a
|
b2a102be60f04e353d7772905c5ff0b85ab97c48
|
refs/heads/main
| 2023-07-18T19:47:44.431377
| 2021-09-24T15:29:18
| 2021-09-24T15:29:18
| 395,780,985
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,049
|
cpp
|
constructores.cpp
|
/******************************************************************************
Name: Principios de constructores
Author: Juan Romero
Date: 31/08/2021
Purpose: Explicar los principios básicos de constructores
Usage:
*******************************************************************************/
#include <stdio.h>
#include <iostream>
using namespace std;
#include <iomanip>
class Universidad{
public:
int N_estudiantes;
int N_escuelas;
string Ubicacion;
Universidad(int _N_estudiantes, int _N_escuelas, string _Ubicacion);
private:
long int presupuesto;
};
Universidad::Universidad (int _N_estudiantes, int _N_escuelas, string _Ubicacion){
N_estudiantes = _N_estudiantes;
N_escuelas = _N_escuelas;
Ubicacion = _Ubicacion;
};
int main() {
setlocale(LC_ALL, "spanish");
Universidad UIS(28000,12, "Cr 9 calle 27");
// UIS.N_estudiantes = 28000;
// UIS.N_escuelas = 12;
// UIS.Ubicacion = "Cr 9 calle 27";
cout << "El número de estudiantes es: " << UIS.N_estudiantes <<endl;
return 0;
}
|
08459c8f4c62f44931ddf6aa14b9f3982e96e5f8
|
6f75b8771085d4809611c1a6d8981bc86afa533f
|
/CodeChef/Junelong/fifth_tire2.cpp
|
47d1ec03079e521f505873af3dc0ffbfaaf210bc
|
[] |
no_license
|
ohil17yo36/CodeChef-Long
|
507ba9ce398294876eb563f940417b327917f6be
|
688a03858c6d9787aaec0e0ac3187be752eb7d11
|
refs/heads/master
| 2021-01-13T02:08:11.572643
| 2015-09-03T12:31:31
| 2015-09-03T12:31:31
| 41,857,237
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,335
|
cpp
|
fifth_tire2.cpp
|
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
#define lli long long int
#define mod 1000000007
inline lli scan( )
{
lli n1 = 0;
char c;
for( c = getchar_unlocked(); c==' ' || c=='\n' || c == '\t'; c = getchar_unlocked());
for( ; c > 0x2f && c < 0x3a; c = getchar_unlocked())
n1 = (n1 * 10) + (c & 0x0f);
return n1;
}
lli t,n,q,idx,k,count[5005],ans[5005];
lli factorial[5005];
char ch,str[5005];
struct trie_node
{
lli substr_cnt;
std::vector<int> child_index;
struct trie_node *child[26];
}*root;
struct trie_node *newNode()
{
struct trie_node *temp;
temp=(struct trie_node *)malloc(sizeof(struct trie_node));
temp->substr_cnt=1;
temp->child_index.clear();
for(int i=0;i<26;i++)
temp->child[i]=NULL;
return temp;
}
void insertWord(lli start)
{
struct trie_node *temp=root;
for(lli i=start;i<n;i++)
{
if(temp->child[str[i]-'a']==NULL)
{
temp->child[str[i]-'a']=newNode();
temp->child_index.push_back(str[i]-'a');
}
else
temp->child[str[i]-'a']->substr_cnt++;
temp=temp->child[str[i]-'a'];
}
}
void traverse(struct trie_node *temp)
{
for (std::vector<int>::iterator i = temp->child_index.begin(); i != temp->child_index.end(); ++i)
{
count[temp->child[*i]->substr_cnt]++;
traverse(temp->child[*i]);
}
}
void factorialinit(lli N)
{
factorial[0]=1;
for(lli i=1;i<N;i++)
{
factorial[i]=(factorial[i-1]*i);
if(factorial[i]>=mod)
factorial[i]=factorial[i]%mod;
}
}
void ExtEuc(long long int a,long long int b,long long int& x,long long int& y)
{
if(a%b==0)
{
x=0;
y=1;
return;
}
ExtEuc(b,a%b,x,y);
long long int temp=x;
x=y;
y=(temp-y*(a/b));
}
long long int InverseEuler(long long int a)
{
lli m=mod;
long long int x,y;
ExtEuc(a,m,x,y);
if(x<0)
x+=m;
return x;
}
lli nck_fast(lli N1,lli M1)
{
if(M1==0 || M1==N1)
return 1;
if(M1==1 || M1==(N1-1))
return N1%mod;
lli res;
lli No=N1%mod;
N1/=mod;
lli Mo=M1%mod;
M1/=mod;
if(Mo>No)
res=0;
else
res=(((((((factorial[No])*(InverseEuler(factorial[Mo])))%mod)*((InverseEuler(factorial[No-Mo]))))%mod)%mod)*((((((factorial[N1])*(InverseEuler(factorial[M1])))%mod)*((InverseEuler(factorial[N1-M1]))))%mod)%mod))%mod;
return res;
}
int main(int argc, char const *argv[])
{
factorialinit(5005);
t=scan();
while(t--)
{
n=scan(),q=scan(),idx=0;
while((ch=getchar_unlocked())!='\n')
str[idx++]=ch;
str[idx]='\0';
root=newNode();
root->substr_cnt=0;
for(lli i=0;i<n;i++)
insertWord(i),count[i]=0;
count[n]=0;
traverse(root);
for(lli i=1;i<=n;i++)
{
ans[i]=0;
for(lli j=i;j<=n;j++)
if(count[j]>0)
{
ans[i]=(ans[i]+((count[j])*nck_fast(j,i)));
if(ans[i]>=mod)
ans[i]=ans[i]%mod;
}
}
while(q--)
{
scanf("%lld",&k);
if(k>n || k<1)
printf("0\n");
else
printf("%lld\n",ans[k]);
}
}
return 0;
}
|
4a779c94ae7ab3ff779886d4683fabbe7e28b7ed
|
58a49ee5a72d6788963dcc89a9af5b905ab7c5c8
|
/pipes/split.h
|
4772e05fc82ddc3adec8c0d26225bb9bd1cf60a2
|
[] |
no_license
|
dzendmitry/pp-stepic
|
5f383b3f8a5621f6e94f3a7474bf072590b289a0
|
6de3ae1c9fac068977e8d88f5827c83e4a6906e1
|
refs/heads/master
| 2021-01-10T12:26:08.833407
| 2016-02-28T14:20:35
| 2016-02-28T14:20:35
| 48,170,027
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 712
|
h
|
split.h
|
#include <sstream>
#include <string>
#include "trim.h"
struct s_split
{
enum empties_t { empties_ok, no_empties };
};
template <typename Container>
Container& split(
Container& result,
const typename Container::value_type& s,
typename Container::value_type::value_type delimiter,
s_split::empties_t empties = s_split::empties_ok )
{
result.clear();
std::istringstream ss( s );
while (!ss.eof())
{
typename Container::value_type field;
getline( ss, field, delimiter );
if ((empties == s_split::no_empties) && field.empty()) continue;
field = trim_copy(field);
result.push_back( field );
}
return result;
}
|
5f8be55834cbe21ac7ed6f6dfdbb4a72fae85cf7
|
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
|
/engine/core/render/base/shader/editor/node/math/shader_node_abs.cpp
|
d9af4e564066d0fe3d14d6c6625577e9d5a6e78e
|
[
"MIT"
] |
permissive
|
timi-liuliang/echo
|
2935a34b80b598eeb2c2039d686a15d42907d6f7
|
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
|
refs/heads/master
| 2023-08-17T05:35:08.104918
| 2023-08-11T18:10:35
| 2023-08-11T18:10:35
| 124,620,874
| 822
| 102
|
MIT
| 2021-06-11T14:29:03
| 2018-03-10T04:07:35
|
C++
|
UTF-8
|
C++
| false
| false
| 1,519
|
cpp
|
shader_node_abs.cpp
|
#include "shader_node_abs.h"
#include "shader_node_operation_rules.h"
#ifdef ECHO_EDITOR_MODE
namespace Echo
{
ShaderNodeAbs::ShaderNodeAbs()
: ShaderNode()
{
m_inputDataTypes =
{
{"any", "A"},
};
m_inputs.resize(m_inputDataTypes.size());
m_outputs.resize(1);
m_outputs[0] = std::make_shared<DataInvalid>(this);
m_outputs[0]->setVariableName(getVariableName());
}
void ShaderNodeAbs::bindMethods()
{
}
void ShaderNodeAbs::setInData(std::shared_ptr<NodeData> nodeData, QtNodes::PortIndex portIndex)
{
m_inputs[portIndex] = std::dynamic_pointer_cast<ShaderData>(nodeData);
if (m_inputs[0])
{
m_outputs[0] = OperationRules::instance().NewShaderData( DataAny::getInternalData(m_inputs[0])->type().id, this);
m_outputs[0]->setVariableName(getVariableName());
}
else
{
m_outputs[0] = std::make_shared<DataInvalid>(this);
m_outputs[0]->setVariableName(getVariableName());
}
Q_EMIT dataUpdated(0);
}
bool ShaderNodeAbs::generateCode(Echo::ShaderCompiler& compiler)
{
if (m_inputs[0])
{
compiler.addCode(Echo::StringUtil::Format("\t%s %s = abs(%s);\n",
m_outputs[0]->type().id.c_str(),
m_outputs[0]->getVariableName().c_str(),
DataAny::getInternalData(m_inputs[0])->getVariableName().c_str()));
}
return true;
}
}
#endif
|
00f3000ae2db939682125c6702ee533c2fbff95c
|
8c9940503495a5db7f9536e1132ebac8347a209d
|
/hdbextractor/cpp/tags/release-0.90.0/qt/hdbextractor-qt/src/qhdbxconnectionevent.h
|
bffb54dff05f5d451ea8e8e7611177236bc5841a
|
[] |
no_license
|
bourtemb/hdbpp-test
|
38ed2694af4c55fe27fc2b822a46affedcd0f627
|
cd74223a7a3f38e98457db7dd340837966a686d3
|
refs/heads/master
| 2021-01-11T08:40:53.915159
| 2016-12-13T14:20:23
| 2016-12-13T14:20:23
| 76,670,118
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 688
|
h
|
qhdbxconnectionevent.h
|
#ifndef QHDBXCONNECTIONEVENT_H
#define QHDBXCONNECTIONEVENT_H
#include <qhdbxevent.h>
#include <hdbextractor.h>
#include <QString>
class QHdbXConnectionEvent : public QHdbXEvent
{
public:
explicit QHdbXConnectionEvent(Hdbextractor::DbType dbType,
const QString & host,
const QString & db,
const QString & user,
const QString & passwd,
unsigned short port = 3306);
Hdbextractor::DbType dbType;
QString host, user, pass, dbnam;
unsigned short port;
private:
};
#endif // QHDBXCONNECTIONEVENT_H
|
03196d7226a01b3151911c5dbbe8b8f7551dbfb5
|
14b72f948bc838f17973d6672565fe9b8ec02ef3
|
/ezio/Backtrace.cpp
|
f422242eed36197091782bb906b52851f3df936e
|
[] |
no_license
|
cout/ezio
|
ddf5e02050252ae3c5b8c485309d1767688cba2b
|
fdeb7d23a3ec9b1cb82e96c364a66f6ca0975074
|
refs/heads/master
| 2021-03-12T20:26:24.509546
| 2011-12-23T17:39:21
| 2011-12-23T17:39:21
| 1,016,576
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,316
|
cpp
|
Backtrace.cpp
|
#include "Backtrace.hpp"
#include "Regex.hpp"
#include "cxx_demangle.hpp"
#include <sstream>
#include <cstdlib>
#include <execinfo.h>
ezio::Backtrace::
Backtrace(size_t ignore_frames)
: locations_()
{
size_t n;
void * buffer[8192];
n = ::backtrace((void **)&buffer, sizeof(buffer));
char * * strings = backtrace_symbols(buffer, n);
if (!strings)
{
// error, but since this object is probably getting constructed in
// an exceptional case, we don't want to throw another exception and
// perhaps obscure the real problem so just return
return;
}
for(size_t idx = ignore_frames; idx < n; ++idx)
{
locations_.push_back(demangle_location(strings[idx]));
}
std::free(strings);
}
ezio::Backtrace::Location
ezio::Backtrace::
demangle_location(Location const & location) const
{
Regex regex(
"(.*?)\\((.*?)\\+(.*?)\\)\\s*\\[(.*?)\\]");
Regex::Match match(4);
if (regex.match(location, &match))
{
std::string filename = match.str(1);
std::string funcname = cxx_demangle(match.str(2));
std::string offset = match.str(3);
std::string addr = match.str(4);
std::stringstream result;
result << filename << "(" << funcname << "+" << offset << ")" << " [" << addr << "]";
return result.str();
}
else
{
return location;
}
}
|
f239ac83616a84ff7780f3a6b03b1fdb2a4bfbe9
|
13e60c8f5ca481ad171843288665c00e3530c178
|
/exec/src/tests/OrnsteinUhlenbeckProblem.cpp
|
eed67c8137393b397f9c081389d4a92fd954ae6f
|
[] |
no_license
|
Inchman/Inchman
|
54b08b925041d839a8c4b9427c717be2f009599b
|
f9d3576c998a0f50a984eab91c12ad07ff785109
|
refs/heads/master
| 2021-03-12T22:03:38.735495
| 2014-08-25T17:50:08
| 2014-08-25T17:50:08
| 15,157,306
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,557
|
cpp
|
OrnsteinUhlenbeckProblem.cpp
|
#include "OrnsteinUhlenbeckProblem.h"
#include "Compartment.h"
namespace gpgmp {
/**
Sets up the species and the source compartment. We use the pre-defined
drift-diffusion method gpgmp::DT_ORNSTEIN_UHLENBECK and set the kernel
parameters accordingly.
\see setComputeDriftDiffusivityMethod
\see setParameter
*/
OrnsteinUhlenbeckProblem::OrnsteinUhlenbeckProblem(Real length, int dx, int dy,
Real diffusivityX, Real diffusivityY,
Real gxx, Real gxy, Real gyx, Real gyy,
int numMolecules)
: DiffusionModel(length, dx, dy)
{
// one species
Species *speciesA = addSpecies("A", 1.);
// set boundary mask
const cl_int4 boundaryMask = {{1, 1, 1, 1}};
const cl_int4 sourceMask = {{0, 0, 0, 0}};
setBoundaryMasks(boundaryMask, sourceMask);
// add source compartment
Compartment *compartmentSource = new Compartment("TrueSource", dx/4,dy/4, dx/4, dy/4);
compartmentSource->setInitialAmount(speciesA, numMolecules, gpgmp::HomogeneousDistribution);
addCompartment(compartmentSource);
// add user parameters for kernel
setParameter("diffX", diffusivityX);
setParameter("diffY", diffusivityY);
setParameter("gammaXX", gxx);
setParameter("gammaXY", gxy);
setParameter("gammaYX", gyx);
setParameter("gammaYY", gyy);
// set OU method
setComputeDriftDiffusivityMethod(gpgmp::DT_ORNSTEIN_UHLENBECK);
}
} // namespace gpgmp
|
e83b8bd110741941edc40fa87312139c2d189657
|
d55d0b8e7432cf834df42a193206f32b9c0c9e1c
|
/Hello/Hello.cpp
|
43f7079da5c8a451a071efe6fdbd0414ebf0cdd6
|
[] |
no_license
|
Hongwei-L/Win10EffectivePowermode
|
ade9763e1e361a0c75e4f2db201614e293729241
|
e880b8f67a01d47f4c9b39c3947bf5f6d0ad851c
|
refs/heads/master
| 2023-01-07T14:49:20.057865
| 2020-11-05T09:41:02
| 2020-11-05T09:41:02
| 310,253,762
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,068
|
cpp
|
Hello.cpp
|
// Hello.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <windows.h>
#include <powersetting.h>
#pragma comment(lib, "Powrprof.lib")
const TCHAR* Effective_PowerMode[]{
__TEXT("BatterySaver"),
__TEXT("BetterBattery"),
__TEXT("Balanced"),
__TEXT("HighPerformance"),
__TEXT("MaxPerformance"), // v1 last supported
__TEXT("GameMode"),
__TEXT("MixedReality"), // v2 last supported
};
VOID
WINAPI
Effective_powermode_CB(
_In_ EFFECTIVE_POWER_MODE Mode,
_In_opt_ VOID* Context
)
{
std::wcout << L"Mode changed to:" << Effective_PowerMode[Mode] << std::endl;
}
EFFECTIVE_POWER_MODE_CALLBACK;
int main()
{
VOID* pCBHandle = NULL;
PowerRegisterForEffectivePowerModeNotifications(
EFFECTIVE_POWER_MODE_V2,
Effective_powermode_CB,
NULL,
&pCBHandle
);
std::cout << "enter to quite!\n";
char ch;
do {
std::cin >> ch;
if (ch == 'q')
break;
} while (true);
}
|
c919377f23dd206e0047258d0d172be91607db74
|
bf5bc8f2dc8533b0a329e6dc0217a8c768c65e68
|
/tp1/include/ColorImage.h
|
b4f775f3f24d26a9cb23c7991da58cd3fa9e720a
|
[] |
no_license
|
guillaume-gomez/Rep-Code
|
598fd908f9c4e3cf7db29385b5ca99e257dcc094
|
8dd41059fa76174bf3d12e65e8a8373be16491ff
|
refs/heads/master
| 2021-06-27T14:16:43.692061
| 2017-01-29T18:45:14
| 2017-01-29T18:45:14
| 27,116,612
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 553
|
h
|
ColorImage.h
|
#ifndef COLORIMAGE_H_INCLUDED
#define COLORIMAGE_H_INCLUDED
typedef unsigned short int ushort;
typedef unsigned char ubyte;
typedef unsigned int uint;
#include "Color.h"
class ColorImage
{
private :
ushort width;
ushort height;
Color * array;
public :
ColorImage(ushort w, ushort h);
ColorImage(const ColorImage& original);
void clear();
Color pixel(ushort x, ushort y) const;
Color& pixel(ushort x, ushort y);
~ColorImage();
};
#endif // COLORIMAGE_H_INCLUDED
|
fbc9e933c100f051c04258f67c5e0c3cbcba9958
|
121c754ec3cf9e5844eece7ce8808e2d616dc947
|
/src/lighting/ShadowVolume.cpp
|
1826319b7ed77e8f98ff6b9a9cd7350f198c4410
|
[] |
no_license
|
forry/Lexoanim
|
57eaa5bbac1da2d41b16efe1549a4b95a0ff43de
|
05adf8a39ad7f19e2171f010577f194d504bd723
|
refs/heads/master
| 2016-09-06T09:09:07.503852
| 2011-10-27T13:29:14
| 2011-10-27T13:30:52
| 2,619,825
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 34,835
|
cpp
|
ShadowVolume.cpp
|
/**
* @file
* ShadowVolume class implementation.
*
* @author PCJohn (Jan Pečiva), Foreigner (Tomas Starka)
*/
#include <osg/BlendFunc>
#include <osg/CullFace>
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/LightModel>
#include <osg/Material>
#include <osg/Stencil>
#include <osg/StencilTwoSided>
#include <osg/TriangleFunctor>
#include <osg/GraphicsContext>
#include <osgShadow/ShadowedScene>
#include <osgViewer/ViewerBase>
#include <osgViewer/View>
#include <iostream>
#include <osg/PolygonMode>
#include "ShadowVolume.h"
#include "ClearGLBuffersDrawable.h"
//#include "SVKeyboardHandler.h"
//#include "RealizeOperation.h"
#include "shader_utils.h"
using namespace osg;
using namespace osgShadow;
#define DEBUG_SHOW_WIREFRAME_VOLUMES 0
static const std::string volumeVertexShader(
"#version 120\n"
"\n"
"void main()\n"
"{\n"
" gl_Position = gl_ModelViewMatrix * gl_Vertex;\n"
"}" );
static const std::string volumeFragmentShader(
"#version 120\n"
"\n"
"void main()\n"
"{\n"
" gl_FragColor = gl_Color;\n"
"}" );
static const std::string volumeGeometryShader(
"#version 120\n"
"#extension GL_EXT_geometry_shader4 : enable\n"
"\n"
"uniform vec4 lightpos;\n"
"\n"
"void main()\n"
"{\n"
" // color and vertices\n"
" vec4 color;\n"
" vec4 v0 = gl_PositionIn[0];\n"
" vec4 v1;\n"
" vec4 v2;\n"
"\n"
" // detect facing\n"
" vec4 edg1 = gl_PositionIn[1] - gl_PositionIn[0];\n"
" vec4 edg2 = gl_PositionIn[2] - gl_PositionIn[0];\n"
" vec3 norm = cross( edg1.xyz, edg2.xyz );\n"
"\n"
" // depending on light-facing of the triangle we must change winding\n"
" vec4 ref = lightpos - gl_PositionIn[0];\n"
" if( dot( norm, ref.xyz ) >= 0 ) {\n"
" color = vec4(0.0,0.5,1.0,1.0); // color for debuging purposes\n"
" v1 = gl_PositionIn[1];\n"
" v2 = gl_PositionIn[2];\n"
" } else {\n"
" color = vec4(0.5,0.0,1.0,1.0);\n"
" v1 = gl_PositionIn[2];\n"
" v2 = gl_PositionIn[1];\n"
" }\n"
"\n"
" // vertices in infinity\n"
" vec4 v0inf = gl_ProjectionMatrix * vec4( v0.xyz - lightpos.xyz, 0.0 );\n"
" vec4 v1inf = gl_ProjectionMatrix * vec4( v1.xyz - lightpos.xyz, 0.0 );\n"
" vec4 v2inf = gl_ProjectionMatrix * vec4( v2.xyz - lightpos.xyz, 0.0 );\n"
"\n"
" v0 = gl_ProjectionMatrix * v0;\n"
" v1 = gl_ProjectionMatrix * v1;\n"
" v2 = gl_ProjectionMatrix * v2;\n"
"\n"
" // 1st side\n"
" gl_FrontColor = color;\n"
" gl_Position = v0;\n"
" EmitVertex();\n"
" gl_FrontColor = color;\n"
" gl_Position = v0inf;\n"
" EmitVertex();\n"
" gl_FrontColor = color;\n"
" gl_Position = v1;\n"
" EmitVertex();\n"
" gl_FrontColor = color;\n"
" gl_Position = v1inf;\n"
" EmitVertex();\n"
"\n"
" //2nd side\n"
" gl_FrontColor = color;\n"
" gl_Position = v2;\n"
" EmitVertex();\n"
" gl_FrontColor = color;\n"
" gl_Position = v2inf;\n"
" EmitVertex();\n"
"\n"
" //3rd side\n"
" gl_FrontColor = color;\n"
" gl_Position = v0;\n"
" EmitVertex();\n"
" gl_FrontColor = color;\n"
" gl_Position = v0inf;\n"
" EmitVertex();\n"
"}" );
ShadowVolume::ShadowVolume():
//_occluders_dirty(true),
ShadowTechnique(),
_initialized(false),
_mode(ShadowVolumeGeometryGenerator::CPU_RAW),
_exts(0),
_stencilImplementation(STENCIL_AUTO),
_ambientPassDisabled(false),
_updateStrategy(MANUAL_INVALIDATE),
_clearDrawable(new ClearGLBuffersDrawable(GL_STENCIL_BUFFER_BIT))
{
init();
}
ShadowVolume::~ShadowVolume()
{
}
void ShadowVolume::setLight( Light* light )
{
_light = light;
//Vec4 lp3 = light->getPosition();
//
// First pass state set
//
_ss1 = new StateSet;
_ss1->setRenderBinDetails( 1, "RenderBin" );
// disable the light
if( _light )
_ss1->setMode( GL_LIGHT0 + _light->getLightNum(),
StateAttribute::OFF | StateAttribute::OVERRIDE );
// lighting should be on
_ss1->setMode( GL_LIGHTING, StateAttribute::ON | StateAttribute::OVERRIDE );
}
void ShadowVolume::init()
{
/**
* This var has currently no effect on whether to perform init or don't.
* It is set from various location as ShadowedScene::setShadowTechnique
* which I deem wrong. So I have _initialized var to ensure, that this
* function is executed only once or, in future, when someone knows
* exactly what he does - Currently not supported.
*/
_dirty = false;
if(_initialized) return;
_initialized = true;
_clearDrawable->setUseDisplayList( false );
_clearDrawable->getOrCreateStateSet()->setRenderBinDetails( 1, "RenderBin" );
//notify(NOTICE)<<"INIT"<<std::endl;
/* FIXME: shaders programs are allocated on heap and there is no handle to release them.
* Could try to use some OSG string with ref_ptr if any.
*/
//_volumeShader = createProgram("shadowtest.vert","shadowtest.glsl","shadowtest.frag");
_volumeShader = new Program;
_volumeShader->addShader( new Shader( Shader::VERTEX, volumeVertexShader ) );
_volumeShader->addShader( new Shader( Shader::GEOMETRY, volumeGeometryShader ) );
_volumeShader->addShader( new Shader( Shader::FRAGMENT, volumeFragmentShader ) );
// _volumeShader = createProgram("shadowtest.vert",NULL,"shadowtest.frag");
_lightPosUniform = new Uniform("lightpos", Vec4());
_mode_unif = new Uniform("mode",_mode);
_just_sides = new Uniform("just_caps",0);
_just_caps = new Uniform("just_caps",1);
_volumeShader->setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, 8 );
_volumeShader->setParameter( GL_GEOMETRY_INPUT_TYPE_EXT, GL_TRIANGLES );
_volumeShader->setParameter( GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP );
//
// First pass state set
//
// _ss1 is initialized in setLight() method
//
//
// Second and third pass
//
_ss2 = new StateSet;
_ss2->setRenderBinDetails( 2, "RenderBin" );
_ss3 = new StateSet;
_ss3->setRenderBinDetails( 3, "RenderBin" );
//shaders
_ss2->addUniform(_lightPosUniform);
_ss2->addUniform(_mode_unif);
_ss2->addUniform(_just_sides);
_ss3->addUniform(_lightPosUniform);
_ss3->addUniform(_mode_unif);
_ss3->addUniform(_just_sides);
// no lighting
_ss2->setMode( GL_LIGHTING, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss3->setMode( GL_LIGHTING, StateAttribute::OFF | StateAttribute::OVERRIDE );
#if DEBUG_SHOW_WIREFRAME_VOLUMES // debugging code to display wireframe of shadow volumes
// blend
BlendFunc* blend2 = new BlendFunc;
blend2->setFunction( BlendFunc::ONE, BlendFunc::ONE );
_ss2->setAttributeAndModes( blend2, StateAttribute::ON | StateAttribute::OVERRIDE );
// depthFunc to LEQUAL (LESS does not work!)
Depth* depth2 = new Depth;
depth2->setWriteMask( false );
depth2->setFunction( Depth::LEQUAL );
_ss2->setAttributeAndModes( depth2, StateAttribute::ON );
#else
//debug
//ColorMask *colorMask1 = new ColorMask;
//colorMask1->setMask( false, false, false, false );
//_ss1->setAttribute( colorMask1 );
// do not write to color buffers
ColorMask *colorMask23 = new ColorMask;
colorMask23->setMask( false, false, false, false );
_ss2->setAttribute( colorMask23 );
_ss3->setAttribute( colorMask23 );
/*BlendFunc* blend = new BlendFunc;
blend->setFunction( BlendFunc::ONE, BlendFunc::ONE );*/
//_ss2->setAttributeAndModes( blend, StateAttribute::ON | StateAttribute::OVERRIDE );
//_ss3->setAttributeAndModes( blend, StateAttribute::ON | StateAttribute::OVERRIDE );
// depth
Depth *depth23 = new Depth;
depth23->setWriteMask( false );
depth23->setFunction( Depth::LEQUAL );
_ss2->setAttributeAndModes( depth23, StateAttribute::ON );
_ss3->setAttributeAndModes( depth23, StateAttribute::ON );
// stencil function (pass 2)
Stencil* stencil2 = new Stencil;
stencil2->setFunction( Stencil::ALWAYS, 0, ~0u );
stencil2->setOperation( Stencil::KEEP, Stencil::KEEP, Stencil::INCR_WRAP );
_ss2->setAttributeAndModes( stencil2, StateAttribute::ON );
// stencil function (pass 3)
Stencil* stencil3 = new Stencil;
stencil3->setFunction( Stencil::ALWAYS, 0, ~0u );
stencil3->setOperation( Stencil::KEEP, Stencil::KEEP, Stencil::DECR_WRAP );
_ss3->setAttributeAndModes( stencil3, StateAttribute::ON );
// cull back faces (pass 2)
CullFace *cullFace2 = new CullFace;
cullFace2->setMode( CullFace::BACK );
_ss2->setAttributeAndModes( cullFace2, StateAttribute::ON | StateAttribute::OVERRIDE );
// cull front faces (pass 3)
CullFace *cullFace3 = new CullFace;
cullFace3->setMode( CullFace::FRONT );
_ss3->setAttributeAndModes( cullFace3, StateAttribute::ON | StateAttribute::OVERRIDE );
#endif
/* TwoSided Stencil state set */
_ss23 = new StateSet;
_ss23->setRenderBinDetails( 2, "RenderBin" );
_ss23->addUniform(_lightPosUniform);
_ss23->addUniform(_mode_unif);
_ss23->addUniform(_just_sides);
StencilTwoSided *stencil23 = new StencilTwoSided;
stencil23->setFunction(StencilTwoSided::FRONT, StencilTwoSided::ALWAYS, 0, ~0u);
stencil23->setOperation(StencilTwoSided::FRONT, StencilTwoSided::KEEP, StencilTwoSided::KEEP, StencilTwoSided::INCR_WRAP);
stencil23->setFunction(StencilTwoSided::BACK, StencilTwoSided::ALWAYS, 0, ~0u);
stencil23->setOperation(StencilTwoSided::BACK, StencilTwoSided::KEEP, StencilTwoSided::KEEP, StencilTwoSided::DECR_WRAP);
_ss23->setMode( GL_LIGHTING, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss23->setMode( GL_CULL_FACE, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss23->setAttribute( colorMask23 );
_ss23->setAttributeAndModes( depth23, StateAttribute::ON );
_ss23->setAttributeAndModes( stencil23, StateAttribute::ON );
/* Caps StateSets */
_ss2_caps = new StateSet;
_ss2_caps->setRenderBinDetails( 2, "RenderBin" );
Stencil* stencil_caps2 = new Stencil;
stencil_caps2->setFunction( Stencil::NEVER, 0, ~0u );
stencil_caps2->setOperation( Stencil::INCR_WRAP, Stencil::KEEP, Stencil::KEEP );
_ss2_caps->setMode( GL_DEPTH_TEST, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss2_caps->setAttributeAndModes( cullFace2, StateAttribute::ON | StateAttribute::OVERRIDE );
//_ss2_caps->setMode( GL_CULL_FACE, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss2_caps->setAttributeAndModes( stencil_caps2, StateAttribute::ON );
_ss2_caps->addUniform(_lightPosUniform);
_ss2_caps->addUniform(_mode_unif);
_ss2_caps->addUniform(_just_caps);
_ss2_caps->setMode( GL_LIGHTING, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss2_caps->setAttribute( colorMask23 );
_ss3_caps = new StateSet;
_ss3_caps->setRenderBinDetails( 3, "RenderBin" );
Stencil* stencil_caps3 = new Stencil;
stencil_caps3->setFunction( Stencil::NEVER, 0, ~0u );
stencil_caps3->setOperation( Stencil::DECR_WRAP, Stencil::KEEP, Stencil::KEEP );
_ss3_caps->setMode( GL_DEPTH_TEST, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss3_caps->setAttributeAndModes( cullFace3, StateAttribute::ON | StateAttribute::OVERRIDE );
_ss3_caps->setAttributeAndModes( stencil_caps3, StateAttribute::ON );
//_ss3_caps->setMode( GL_CULL_FACE, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss3_caps->addUniform(_lightPosUniform);
_ss3_caps->addUniform(_mode_unif);
_ss3_caps->addUniform(_just_caps);
_ss3_caps->setMode( GL_LIGHTING, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss3_caps->setAttribute( colorMask23 );
_ss23_caps = new StateSet;
_ss23_caps->setRenderBinDetails( 2, "RenderBin" );
_ss23_caps->addUniform(_lightPosUniform);
_ss23_caps->addUniform(_mode_unif);
/*Depth *depth23_debug = new Depth;
depth23_debug->setWriteMask( false );
depth23_debug->setFunction( Depth::ALWAYS );
_ss23_caps->setAttributeAndModes(depth23_debug);*/
//_ss23_caps->setAttribute(cullFace3);
StencilTwoSided *stencil23_caps = new StencilTwoSided;
stencil23_caps->setFunction(StencilTwoSided::FRONT, StencilTwoSided::NEVER, 0, ~0u);
stencil23_caps->setOperation(StencilTwoSided::FRONT, StencilTwoSided::INCR_WRAP, StencilTwoSided::KEEP, StencilTwoSided::KEEP);
stencil23_caps->setFunction(StencilTwoSided::BACK, StencilTwoSided::NEVER, 0, ~0u);
stencil23_caps->setOperation(StencilTwoSided::BACK, StencilTwoSided::DECR_WRAP, StencilTwoSided::KEEP, StencilTwoSided::KEEP);
_ss23_caps->setMode( GL_LIGHTING, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss23_caps->setMode( GL_CULL_FACE, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss23_caps->setMode( GL_DEPTH_TEST, StateAttribute::OFF | StateAttribute::OVERRIDE );
_ss23_caps->setAttribute( colorMask23 );
_ss23_caps->addUniform(_lightPosUniform);
_ss23_caps->addUniform(_mode_unif);
_ss23_caps->addUniform(_just_caps);
_ss23_caps->setAttributeAndModes( stencil23_caps, StateAttribute::ON );
//
// Fourth pass state set
//
_ss4 = new StateSet;
_ss4->setRenderBinDetails( 4, "RenderBin" );
// lighting have to be ON
_ss4->setMode( GL_LIGHTING, StateAttribute::ON | StateAttribute::OVERRIDE );
/*_ss4->setMode( GL_LIGHT0 + _light->getLightNum(),
StateAttribute::ON | StateAttribute::OVERRIDE );*/
// blend
BlendFunc* blend4 = new BlendFunc;
blend4->setFunction( BlendFunc::ONE, BlendFunc::ONE );
_ss4->setAttributeAndModes( blend4, StateAttribute::ON | StateAttribute::OVERRIDE );
// depthFunc to LEQUAL (LESS does not work!)
Depth* depth4 = new Depth;
depth4->setWriteMask( false );
depth4->setFunction( Depth::LEQUAL );
_ss4->setAttributeAndModes( depth4, StateAttribute::ON );
// ambient intensity to zero
// FIXME: what about other LightModel components?
LightModel* lm4 = new LightModel;
lm4->setAmbientIntensity( Vec4( 0., 0., 0., 0. ) );
_ss4->setAttribute(lm4);
Stencil *stencil4 = new Stencil;
stencil4->setFunction( Stencil::EQUAL, 0, ~0u );
stencil4->setOperation( Stencil::KEEP, Stencil::KEEP, Stencil::KEEP );
_ss4->setAttributeAndModes( stencil4, StateAttribute::ON );
//debuging stateset for wireframe
//PolygonMode *polygMode = new PolygonMode(PolygonMode::FRONT, PolygonMode::LINE);
//_ss4->setAttributeAndModes(polygMode,StateAttribute::ON | StateAttribute::OVERRIDE);
//debuging stateset for silhouette
_ssd = new StateSet();
_ssd->setMode( GL_LIGHTING, StateAttribute::OFF | StateAttribute::OVERRIDE );
}
void ShadowVolume::update( NodeVisitor& nv )
{
}
void ShadowVolume::cull( osgUtil::CullVisitor& cv )
{
//notify(NOTICE)<<"CULL BEGIN"<<std::endl;
// if no light, render scene default way
if( !_light ) {
_shadowedScene->Group::traverse( cv );
return;
}
// pass 4: add light using stencil
// The pass is culled in the first place as it is always culled (in contrary to pass 1).
// Its traversed lights are used in following getLightPositionalState.
// Note: traversing order of passes 1 to 4 does not matter. Rendering order is given
// by RenderBin's setRenderBinDetails().
cv.pushStateSet( _ss4 );
_shadowedScene->Group::traverse( cv );
cv.popStateSet();
// clear stencil buffer - bin number 1 schedules it before 2nd and 3rd pass
if( _clearStencil)
//_clearDrawable->setBufferMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
cv.addDrawable( _clearDrawable, cv.getModelViewMatrix() );
// pass 1: ambient pass
if(!_ambientPassDisabled)
{
cv.pushStateSet( _ss1 );
_shadowedScene->Group::traverse( cv );
cv.popStateSet();
}
// get light positional state,
// if no light, return
Vec4 lightPos;
Vec3 lightDir;
if( !getLightPositionalState( cv, _light, lightPos, lightDir ) )
return;
/******************PASS 2,3/: Shadow geometry into stencil buffer*********************/
if( _mode == ShadowVolumeGeometryGenerator::CPU_FIND_GPU_EXTRUDE
|| _mode == ShadowVolumeGeometryGenerator::GPU_RAW
|| _mode == ShadowVolumeGeometryGenerator::GPU_SILHOUETTE)
{
//notify(NOTICE)<<"LIGHTPOS: "<<lightPos.x()<<" "<<lightPos.y()<<" "<<lightPos.z()<<" "<<std::endl;
_lightPosUniform->set(lightPos);
}
if(_updateStrategy == UPDATE_EACH_FRAME)
_svgg.dirty();
if(_svgg.isDirty()){
//_svgg.clearGeometry();
_svgg.setup(lightPos);
_shadowedScene->Group::traverse( _svgg );
}
if(_mode == ShadowVolumeGeometryGenerator::SILHOUETTES_ONLY){
cv.pushStateSet(_ssd);
ref_ptr< Drawable > d = _svgg.createGeometry();
d->setUseDisplayList( false );
ref_ptr< Geode > geode = new Geode;
geode->addDrawable( d );
geode->accept( cv );
cv.popStateSet();
return;
}
bool twoSidedStencil = _stencilImplementation == STENCIL_TWO_SIDED;
if( _stencilImplementation == STENCIL_AUTO )
{
GraphicsContext *gc = cv.getState()->getGraphicsContext();
if( gc->isGLExtensionSupported( 2.0, "GL20_separate_stencil" ) ||
gc->isGLExtensionSupported( "GL_EXT_stencil_two_side" ) ||
gc->isGLExtensionSupported( "GL_ATI_separate_stencil" ) )
{
twoSidedStencil = true;
}
}
if(twoSidedStencil){
cv.pushStateSet( _ss23 );
ref_ptr< Drawable > d = _svgg.createGeometry();
d->setUseDisplayList( false );
ref_ptr< Geode > geode = new Geode;
geode->addDrawable( d );
geode->accept( cv );
cv.popStateSet();
if(_svgg.getMethod() == ShadowVolumeGeometryGenerator::ZFAIL){
if( _svgg.getMode() == ShadowVolumeGeometryGenerator::CPU_RAW
|| _svgg.getMode() == ShadowVolumeGeometryGenerator::CPU_SILHOUETTE)
{
ref_ptr< Drawable > caps;
caps = _svgg.getCapsGeometry();
caps->setUseDisplayList( false );
ref_ptr< Geode > geode_caps = new Geode;
geode_caps->addDrawable( caps );
cv.pushStateSet( _ss23_caps );
geode_caps->accept( cv );
cv.popStateSet();
}
else if( _svgg.getMode() == ShadowVolumeGeometryGenerator::GPU_RAW
|| _svgg.getMode() == ShadowVolumeGeometryGenerator::GPU_SILHOUETTE)
{
cv.pushStateSet( _ss23_caps );
geode->accept( cv );
cv.popStateSet();
}
}
}
else{
ref_ptr< Drawable > d = _svgg.createGeometry();
d->setUseDisplayList( false );
ref_ptr< Geode > geode = new Geode;
geode->addDrawable( d );
cv.pushStateSet( _ss2 );
geode->accept( cv );
cv.popStateSet();
// pass 3
cv.pushStateSet( _ss3 );
geode->accept( cv );
cv.popStateSet();
if(_svgg.getMethod() == ShadowVolumeGeometryGenerator::ZFAIL){
if( _svgg.getMode() == ShadowVolumeGeometryGenerator::CPU_RAW
|| _svgg.getMode() == ShadowVolumeGeometryGenerator::CPU_SILHOUETTE)
{
ref_ptr< Drawable > caps;
ref_ptr< Geode > geode_caps = new Geode;
caps = _svgg.getCapsGeometry();
caps->setUseDisplayList( false );
geode_caps->addDrawable( caps );
cv.pushStateSet( _ss2_caps );
geode_caps->accept( cv );
cv.popStateSet();
cv.pushStateSet( _ss3_caps );
geode_caps->accept( cv );
cv.popStateSet();
}
else if( _svgg.getMode() == ShadowVolumeGeometryGenerator::GPU_RAW
|| _svgg.getMode() == ShadowVolumeGeometryGenerator::GPU_SILHOUETTE)
{
//_just_caps->set(1);
cv.pushStateSet( _ss2_caps );
geode->accept( cv );
cv.popStateSet();
cv.pushStateSet( _ss3_caps );
geode->accept( cv );
cv.popStateSet();
//_just_caps->set(0);
}
}
}
//notify(NOTICE)<<"CULL END!!!"<<std::endl;
}
void ShadowVolume::cleanSceneGraph()
{
}
bool ShadowVolume::getLightPositionalState( osgUtil::CullVisitor& cv,
const Light* light, Vec4& lightPos, Vec3& lightDir )
{
if( !light )
return false;
// get positional state
osgUtil::RenderStage* rs = cv.getRenderStage();
osgUtil::PositionalStateContainer::AttrMatrixList& aml =
rs->getPositionalStateContainer()->getAttrMatrixList();
RefMatrix* matrix = NULL;
bool found = false;
// find the light and its matrix
// note: it finds the last light occurence with its associated matrix
for( osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin();
itr != aml.end();
++itr )
{
const Light* l = dynamic_cast< const Light* >( itr->first.get() );
if( l && l == light )
{
found = true;
matrix = itr->second.get();
}
}
if( !found )
return false;
// transform light to world space
Matrix localToWorld = Matrix::inverse( *cv.getModelViewMatrix() );
if( matrix ) localToWorld.preMult( *matrix );
lightPos = light->getPosition();
if( lightPos[3] == 0 )
lightDir.set( -lightPos[0], -lightPos[1], -lightPos[2] );
else
lightDir = light->getDirection();
lightPos = lightPos * localToWorld;
lightDir = Matrix::transform3x3( lightDir, localToWorld );
lightDir.normalize();
return true;
}
void ShadowVolume::setMode(ShadowVolumeGeometryGenerator::Modes mode){
if(_mode == mode) return;
_mode_unif->set(mode);
if( mode == ShadowVolumeGeometryGenerator::CPU_FIND_GPU_EXTRUDE
|| mode == ShadowVolumeGeometryGenerator::GPU_RAW
|| mode == ShadowVolumeGeometryGenerator::GPU_SILHOUETTE)
{
if(!( _mode == ShadowVolumeGeometryGenerator::CPU_FIND_GPU_EXTRUDE
|| _mode == ShadowVolumeGeometryGenerator::GPU_RAW
|| _mode == ShadowVolumeGeometryGenerator::GPU_SILHOUETTE) )
{
//notify(NOTICE)<<"adding shaders to statesets"<<std::endl;
_ss2->setAttribute(_volumeShader);
_ss3->setAttribute(_volumeShader);
_ss23->setAttribute(_volumeShader);
_ss2_caps->setAttribute(_volumeShader);
_ss3_caps->setAttribute(_volumeShader);
_ss23_caps->setAttribute(_volumeShader);
}
}
if( mode == ShadowVolumeGeometryGenerator::CPU_RAW
|| mode == ShadowVolumeGeometryGenerator::CPU_SILHOUETTE)
{
if(!( _mode == ShadowVolumeGeometryGenerator::CPU_RAW
|| _mode == ShadowVolumeGeometryGenerator::CPU_SILHOUETTE) )
{
//notify(NOTICE)<<"removing shaders from statesets"<<std::endl;
_ss2->removeAttribute(StateAttribute::PROGRAM);
_ss3->removeAttribute(StateAttribute::PROGRAM);
_ss23->removeAttribute(StateAttribute::PROGRAM);
_ss2_caps->removeAttribute(StateAttribute::PROGRAM);
_ss3_caps->removeAttribute(StateAttribute::PROGRAM);
_ss23_caps->removeAttribute(StateAttribute::PROGRAM);
}
}
_mode_unif->set(_mode);
_mode = mode;
_svgg.setMode(mode);
}
void ShadowVolume::setMethod(ShadowVolumeGeometryGenerator::Methods met){
if(_svgg.getMethod() == met) return;
if(met == ShadowVolumeGeometryGenerator::ZPASS){
//shader
_volumeShader->setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, 8 );
// stencil function (pass 2)
Stencil* stencil2 = new Stencil;
stencil2->setFunction( Stencil::ALWAYS, 0, ~0u );
stencil2->setOperation( Stencil::KEEP, Stencil::KEEP, Stencil::INCR_WRAP );
_ss2->setAttributeAndModes( stencil2, StateAttribute::ON );
CullFace *cullFace2 = new CullFace;
cullFace2->setMode( CullFace::BACK );
_ss2->setAttributeAndModes( cullFace2, StateAttribute::ON | StateAttribute::OVERRIDE );
// stencil function (pass 3)
Stencil* stencil3 = new Stencil;
stencil3->setFunction( Stencil::ALWAYS, 0, ~0u );
stencil3->setOperation( Stencil::KEEP, Stencil::KEEP, Stencil::DECR_WRAP );
_ss3->setAttributeAndModes( stencil3, StateAttribute::ON );
CullFace *cullFace3 = new CullFace;
cullFace3->setMode( CullFace::FRONT );
_ss3->setAttributeAndModes( cullFace3, StateAttribute::ON | StateAttribute::OVERRIDE );
// stencil two-sided function
StencilTwoSided *stencil23 = new StencilTwoSided;
stencil23->setFunction(StencilTwoSided::FRONT, StencilTwoSided::ALWAYS, 0, ~0u);
stencil23->setOperation(StencilTwoSided::FRONT, StencilTwoSided::KEEP, StencilTwoSided::KEEP, StencilTwoSided::INCR_WRAP);
stencil23->setFunction(StencilTwoSided::BACK, StencilTwoSided::ALWAYS, 0, ~0u);
stencil23->setOperation(StencilTwoSided::BACK, StencilTwoSided::KEEP, StencilTwoSided::KEEP, StencilTwoSided::DECR_WRAP);
_ss23->setAttributeAndModes( stencil23, StateAttribute::ON );
}
else{ //ZFAIL
//shader
// stencil function (pass 2)
Stencil* stencil2 = new Stencil;
stencil2->setFunction( Stencil::ALWAYS, 0, ~0u );
stencil2->setOperation( Stencil::KEEP, Stencil::INCR_WRAP, Stencil::KEEP );
_ss2->setAttributeAndModes( stencil2, StateAttribute::ON );
CullFace *cullFace2 = new CullFace;
cullFace2->setMode( CullFace::BACK );
_ss2->setAttributeAndModes( cullFace2, StateAttribute::ON | StateAttribute::OVERRIDE );
// stencil function (pass 3)
Stencil* stencil3 = new Stencil;
stencil3->setFunction( Stencil::ALWAYS, 0, ~0u );
stencil3->setOperation( Stencil::KEEP, Stencil::DECR_WRAP, Stencil::KEEP );
_ss3->setAttributeAndModes( stencil3, StateAttribute::ON );
CullFace *cullFace3 = new CullFace;
cullFace3->setMode( CullFace::FRONT );
_ss3->setAttributeAndModes( cullFace3, StateAttribute::ON | StateAttribute::OVERRIDE );
// stencil two-sided function
StencilTwoSided *stencil23 = new StencilTwoSided;
stencil23->setFunction(StencilTwoSided::FRONT, StencilTwoSided::ALWAYS, 0, ~0u);
stencil23->setOperation(StencilTwoSided::FRONT, StencilTwoSided::KEEP, StencilTwoSided::INCR_WRAP, StencilTwoSided::KEEP);
stencil23->setFunction(StencilTwoSided::BACK, StencilTwoSided::ALWAYS, 0, ~0u);
stencil23->setOperation(StencilTwoSided::BACK, StencilTwoSided::KEEP, StencilTwoSided::DECR_WRAP, StencilTwoSided::KEEP);
_ss23->setAttributeAndModes( stencil23, StateAttribute::ON );
}
_svgg.setMethod(met);
}
void ShadowVolume::setup( osgViewer::View *view )
{
setupDisplaySettings( view );
setupCamera( view->getCamera() );
}
static Matrixd makeFrustumInfiniteZFar( double left,
double right,
double bottom,
double top,
double zNear )
{
double x, y, a, b, c, d;
x = (2.0 * zNear) / (right - left);
y = (2.0 * zNear) / (top - bottom);
a = (right + left) / (right - left);
b = (top + bottom) / (top - bottom);
c = -1.0;
d = -2.0 * zNear;
return Matrixd( x, 0, 0, 0,
0, y, 0, 0,
a, b, c, -1,
0, 0, d, 0 );
}
void ShadowVolume::setupCamera( osg::Camera *camera )
{
// setup zFar to infinity (required by shadow volume algorithm)
double left, right, bottom, top, zNear, zFar;
camera->getProjectionMatrixAsFrustum( left, right, bottom, top, zNear, zFar );
camera->setProjectionMatrix( makeFrustumInfiniteZFar( left, right, bottom, top, zNear ) );
//camera->setProjectionMatrixAsFrustum( left, right, bottom, top, zNear, FLT_MAX );
camera->setComputeNearFarMode( CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
// clear stencil
camera->setClearMask( camera->getClearMask() | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
}
void ShadowVolume::setupDisplaySettings( osg::DisplaySettings *ds )
{
// forces allocation of stencil and depth buffer
ds->setMinimumNumStencilBits( 8 );
ds->setDepthBuffer( true );
}
void ShadowVolume::setupDisplaySettings( osgViewer::View *view )
{
// test whether ViewerBase is still not realized
osgViewer::ViewerBase *vb = view->getViewerBase();
if( vb->isRealized() ) {
OSG_FATAL << "ViewerBase is already realized. Can not setup osgViewer::View's "
"DisplaySettings for use with shadow volumes." << std::endl;
return;
}
// allocate display settings if required (by copying global display settings object)
if( !view->getDisplaySettings() )
view->setDisplaySettings( new DisplaySettings( *DisplaySettings::instance().get() ) );
// setup settings
setupDisplaySettings( view->getDisplaySettings() );
}
//#include <osgDB/ReadFile>
//#include <osgViewer/Viewer>
//#include <osgViewer/ViewerEventHandlers>
//
//using namespace osg;
//using namespace osgViewer;
//
//
//class FindLightVisitor : public NodeVisitor
//{
// typedef NodeVisitor inherited;
//public:
//
// FindLightVisitor() :
// NodeVisitor( NodeVisitor::TRAVERSE_ALL_CHILDREN ),
// _light( NULL )
// {
// }
//
// META_NodeVisitor( "", "FindLightVisitor" )
//
// Light* getLight() const { return _light; }
//
// virtual void reset()
// {
// inherited::reset();
// _light = NULL;
// }
//
// virtual void apply( LightSource& ls )
// {
// Light *l = ls.getLight();
// if( l && !_light ) {
// _light = l;
// }
// }
//
//protected:
// ref_ptr< Light > _light;
//};
//int main(int argc, char **argv)
//{
//
// osg::ArgumentParser arguments(&argc,argv);
//
// arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
// arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example application for Shadow Volumes technique.");
// arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" filename");
//
// arguments.getApplicationUsage()->addKeyboardMouseBinding("F1","Set CPU_RAW mode (Default).");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("F2","Set CPU_SILHOUETTE mode.");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("F3","Set GPU_RAW mode.");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("t","Turn on two-sided stencil. Only if it is supported.");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("o","turn on one-sided stencil (Default).");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("p","Z-pass method (Default).");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("i","Z-fail method.");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("s","Turn on stats handler.");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("f","Toggle windowed/fullscreen mode.");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("Space","Returns camera to its home position.");
// arguments.getApplicationUsage()->addKeyboardMouseBinding("Esc","Quit.");
//
// unsigned int helpType = 0;
// if ((helpType = arguments.readHelpType()))
// {
// arguments.getApplicationUsage()->write(std::cout, helpType);
// return 1;
// }
// if (arguments.errors())
// {
// arguments.writeErrorMessages(std::cout);
// return 1;
// }
// if (arguments.argc()<=1)
// {
// arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
// return 1;
// }
// // load scene
// osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
// //Node *model = osgDB::readNodeFile( "./models/cubemap-test.osg" );
// //Node *model = osgDB::readNodeFile( "./models/PointLight_Cubes10x10.osg" );
// //Node *model = osgDB::readNodeFile( "./models/PointLight_Cubes40x25.osg" );
// //Node *model = osgDB::readNodeFile( "./models/treppeWithLights.osg" );
// /*StateSet *set = model->getOrCreateStateSet();
// set->setMode( GL_LIGHTING, StateAttribute::ON | StateAttribute::OVERRIDE );
// set->setMode( GL_LIGHT0, StateAttribute::ON | StateAttribute::OVERRIDE );*/
// //set->setMode( GL_LIGHT1, StateAttribute::ON | StateAttribute::OVERRIDE );
//
// if( !model ) {
// notify(FATAL) << "Can not load model." << std::endl;
// return -1;
// }
//
// // find light
// FindLightVisitor flv;
// model->accept( flv );
// if( !flv.getLight() )
// notify(WARN) << "No light in the model. No shadows will be displayed." << std::endl;
//
// // setup shadows
// osgShadow::ShadowedScene *ss = new osgShadow::ShadowedScene;
// ss->addChild( model );
// osgShadow::ShadowVolume *sv = new osgShadow::ShadowVolume;
// sv->setLight( flv.getLight() );
// ss->setShadowTechnique( sv );
//
// // setup keyboard handler
// ref_ptr<SVKeyboardHandler> svkh = new SVKeyboardHandler(sv);
//
//
// // setup viewer
// ref_ptr<RealizeOperation> operation = new RealizeOperation;
// Viewer viewer(arguments);
// viewer.setRealizeOperation(operation);
// viewer.addEventHandler(svkh);
//
// arguments.reportRemainingOptionsAsUnrecognized();
// if (arguments.errors())
// {
// arguments.writeErrorMessages(std::cout);
// return 1;
// }
//
// // forces allocation of stencil buffer////
// DisplaySettings::instance()->setMinimumNumStencilBits( 8 );
// //ref_ptr<GraphicsContext::Traits> traits = new GraphicsContext::Traits;
// //traits->vsync = false;
// //ref_ptr<GraphicsContext> gc = GraphicsContext::createGraphicsContext(traits);
// //viewer.getCamera()->setGraphicsContext(gc);
// ///
// viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded); //for keyboard implementation change isn't yet thread safe
// ///
// viewer.addEventHandler( new osgViewer::StatsHandler );
// viewer.addEventHandler(new osgViewer::WindowSizeHandler);
// viewer.setSceneData( ss );
// //viewer.setSceneData( model );
// double left, right, bottom, top, zNear, zFar;
// viewer.getCamera()->getProjectionMatrixAsFrustum( left, right, bottom, top, zNear, zFar );
// viewer.getCamera()->setProjectionMatrixAsFrustum( left, right, bottom, top, zNear, FLT_MAX );
// viewer.getCamera()->setComputeNearFarMode( CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
// viewer.getCamera()->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
// viewer.realize();
//
// viewer.run();
//
// return 0;
//}
|
31864f43f593259ce7d5ffe9279f9f86ea11c50f
|
b27d06a03ef7a0b20afc4942f6d917619500b3f1
|
/poprawka kolokwium 1 - 2014.cpp
|
91417d24c2bb46a7317cba36c330c2a786e08060
|
[] |
no_license
|
StanczakDominik/algi
|
a860111820f03c59fc874525570a0ac9125c5c84
|
9312fb2ad661b8a4e2656de415999395981d3edc
|
refs/heads/master
| 2021-01-10T15:46:20.887535
| 2016-01-20T19:13:31
| 2016-01-20T19:13:31
| 46,993,694
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,797
|
cpp
|
poprawka kolokwium 1 - 2014.cpp
|
Węzeł drzewa dwumianowego
struct node
{
int key;
int h;
node *child, *prev, *next;
}
node *head;
void AddTreeToQueue(node *tree)
{
int h = tree->h;
node *p = head;
if(!p) head = tree;
while(p->h<h)
{
p = p->next;
}
if(p->next->h == h) p->next = MergeTree(Extract(p), tree);
else
{
tree->prev = p->prev;
tree->next = p;
p->prev = tree;
}
}
Kolejka priorytetowa to ADT jest rozszerzeniem zwykłej kolejki lub stosu, w którym każdy element ma własny priorytet. Elementy są zazwyczaj usuwane z kolejki w kolejności według najwyższego priorytetu.
2.
node **Search(node *elem)
{
int b = rand() %2; //0 lub 1
node **p;
if(b) //idziemy w prawe poddrzewo
{
p = &(elem->right);
while((*p)->left)
{
p = &((*p)->left);
}
}
else
{
p = &(elem->left);
while((*p)->right)
{
p=&((*p)->right);
}
}
return p;
}
Złożoność rzędu O(h(poddrzewa)) przez konieczność przejścia na dno kopca, co daje O(log(h_p)).
3. Zrównoważenie dla AVL, przy założeniu że spełniamy wszystkie warunki zwykłych BST:
współczynnik balansu równy wysokości lewego poddrzewa minus wysokości prawego poddrzewa równy -1, 0, lub 1 W KAŻDYM ELEMENCIE
dla drzew CC.
każda ścieżka od dowolnego node do nulla zawiera taką samą liczbę czarnych node'ów.
(pozostałe warunki: wszystkie nulle czarne, czerwony ma czarne dzieci, root jest czarny)
Złożoność inserta w AVL: ograniczona od góry przez 1.44logn, ogólnie logn.
Złożoność w 2-3-4: pesymistyczna 2logn, około logn średnia
Przykładowe zadania na słowniki
void InsertToPageR(node *root, int &v, node *&pr)
{
}
|
23457fee812334b0e00ca80b5106088f7c4d25b1
|
9bb2bd52ad9831ac4c64ae9ef4a86965e74c0160
|
/contests/abc029/d.cpp
|
f8b8fe1655bc51eaef0f450d6ca0938e01b0dc75
|
[] |
no_license
|
hiranoo/atcoder
|
f31560a60ee8f94379b4e958e598d0e733b0f2b3
|
aab6709d5819521b7a213cbf78dc6b33de69269e
|
refs/heads/master
| 2023-08-12T05:00:02.984971
| 2021-09-28T12:08:02
| 2021-09-28T12:08:02
| 370,005,724
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,774
|
cpp
|
d.cpp
|
#include <vector>
#include <algorithm>
#include <math.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <bitset>
#include <stack>
#include <queue>
#include <bits/stdc++.h>
#include <atcoder/segtree>
#include <time.h>
#define rep(i, s, t) for(int i = (s); i <= (t); i++)
#define repd(i, s, t) for(int i = (s); i >= (t); i--)
#define all(v) v.begin(), v.end()
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const ll MOD = 1e9+7;
int main(){
string n_str; cin >> n_str;
vector<int> digit;
digit.push_back(0);
for(auto v : n_str) digit.push_back(v);
int len = n_str.size();
int dp[len+1][2][2][10];
rep(i, 0, len) rep(j, 0, 1) rep(k, 0, 1) rep(l, 0, 9) dp[i][j][k][l] = 0;
dp[0][0][1][0] = 1;
ll ans = 0;
rep(i, 1, len) {
rep(j, 0, 9){
if(digit[i] == 1) dp[i][0][1][j+1] += dp[i-1][0][1][j];
else dp[i][0][1][j] += dp[i-1][0][1][j];
rep(k, 0, digit[i]-1){
if(k == 1) dp[i][1][1][j+1] += dp[i-1][0][1][j];
else dp[i][1][1][j] += dp[i-1][0][1][j];
}
rep(k, 1, 9){
if(k == 1) dp[i][1][1][j+1] += dp[i-1][1][0][j];
else dp[i][1][1][j] += dp[i-1][1][0][j];
}
rep(k, 0, 9){
if(k == 1) dp[i][1][1][j+1] += dp[i-1][1][1][j];
else dp[i][1][1][j] += dp[i-1][1][1][j];
}
}
}
rep(i, 1, len) {
cout << i << endl;
rep(j, 0, 2){
cout << " " << j << endl;
cout << " same, non-zero:" << dp[i][0][1][j] << endl;
cout << " less, zero: " << dp[i][1][0][j] << endl;
cout << " less, non-zero:" << dp[i][1][1][j] << endl;
}
}
rep(j, 1, 9) ans += j * (dp[len][0][1][j] + dp[len][1][1][j]);
cout << ans << endl;
}
|
2bb212561d1dc05926cddd20cd35875ed73f839c
|
9270b70d8c92062b5636100b09d2105b22a274ad
|
/Battleship/inc/GameData.h
|
731dd73539b814a99d7b756d05e022ddf337adc3
|
[] |
no_license
|
naelektryzowany/Battleship
|
bff2b4c413ee0be2da05b547956d767e25102be6
|
aac880360011fb547b3569e61854f81816978417
|
refs/heads/master
| 2020-11-23T22:16:19.226695
| 2020-01-26T17:43:37
| 2020-01-26T17:43:37
| 227,843,713
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 381
|
h
|
GameData.h
|
#ifndef GAME_DATA_H
#define GAME_DATA_H
class GameData {
public:
GameData(double ratio, int shipsLeft, int shipsDown) : mRatio(ratio), mShipsLeft(shipsLeft), mShipsDown(shipsDown) {}
double getRatio() const;
int getSipsLeft() const;
int getShipsDown() const;
private:
double mRatio;
int mShipsLeft;
int mShipsDown;
};
#endif
|
60a117e41d1a06af66a47f1c48c3346ee022b025
|
cf4e7cfba5f4aa4e88778d87418d017096d21d54
|
/Elections - cpp/party.cpp
|
0ca9124df2ee894029e117a9ce8e930917b2988c
|
[] |
no_license
|
MayCesana/Elections-cpp
|
e0acf2dc3a4c0594b8b4748a537701e44a4b63ba
|
790897eafb5f61a9cbd80fb35708e5e139a53ebf
|
refs/heads/main
| 2023-04-09T09:35:15.410266
| 2021-04-28T09:49:39
| 2021-04-28T09:49:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,720
|
cpp
|
party.cpp
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "party.h"
using namespace std;
namespace Elections
{
party::party(const string& name, const citizen& prime, int serial, int numOfDistricts) : serial(serial),
PrimeCandidate(prime), partyName(name)
{
if (numOfDistricts < 0)
throw invalid_argument("invalid Rep Size.");
reps = new DynamicArray<repToDistrict>(numOfDistricts); //creates dynamicArray
for (int i = 0; i < numOfDistricts; ++i)
{
insertDistrictToPartyRes(0);
}
}
bool party::updateDistrictToParty(int disNum, int repsNum)
{
if ((*reps).size() <= disNum)
{
insertDistrictToPartyRes(repsNum);
}
return true;
}
void party::insertDistrictToPartyRes(int repsNum)
{
repToDistrict* rtd = new repToDistrict;
rtd->numberOfReps = repsNum;
rtd->repList = new list<citizen*>();
(*reps).insert((*reps).end(), *rtd);
}
bool party::enoughReps(int index) const
{
if ((*reps)[index].numberOfReps == (*reps)[index].currReps)
return true;
else
return false;
}
ostream& operator<<(ostream& os, const party& p)
{
os << "PARTY " << p.serial + 1 << endl << "Party's serial number: " << p.serial << ", Party's name: " << p.partyName << endl
<< "Party's prime minister candidate: " << p.PrimeCandidate << endl;
return os;
}
bool party::operator==(const party& other)const
{
if ((partyName == other.partyName) && (serial == other.serial))
return true;
else
return false;
}
void party::printReps()
{
cout << "REPRESENTATIVES LIST:" << endl;
for (int i = 0; i < (*reps).size(); ++i)
{
cout << "District number: " << i << endl;
cout << "Representatives: " << endl;
list<citizen*>& lst = *((*reps)[i].repList);
if (lst.empty())
throw invalid_argument("There are no citizens.");
else
printList(lst);
cout << endl;
}
cout << endl;
}
void party::save(ofstream& file) const
{
int nameSize = partyName.length();
file.write(rcastcc(&nameSize), sizeof(int));//number of bytes for name
file.write(rcastcc(partyName.data()), nameSize);
file.write(rcastcc(&serial), sizeof(int)); //party serial number
int primeID = PrimeCandidate.getID();
file.write(rcastcc(&primeID), sizeof(int));
int repsSize = reps->size();
file.write(rcastcc(&repsSize), sizeof(int)); //districts number (to array)
for (int i = 0; i < repsSize; ++i)
{
file.write(rcastcc(&((*reps)[i].numberOfReps)), sizeof(int));
for (auto itr = (*reps)[i].repList->begin(); itr != (*reps)[i].repList->end(); ++itr)
{
int repID = (*(*itr)).getID();
file.write(rcastcc(&repID), sizeof(int));
}
}
}
}
|
6731fbcf27c1fd5df2031fe99323edef96b32e7d
|
b67cce54b0b1456aadb32a25455d37e87323871e
|
/test/perft.cpp
|
98f3dd86e98b515658668bdc5cb1ba56cab76a9c
|
[] |
no_license
|
ngynkvn/chess
|
19b65679be287a9b0651a2ee353d051db51e345f
|
6432c102ef9ce34a53fc9c7dcd6ddcdbca12093f
|
refs/heads/master
| 2021-04-12T08:13:57.600201
| 2019-10-03T16:48:43
| 2019-10-03T16:48:43
| 126,072,403
| 0
| 13
| null | 2019-05-08T16:09:28
| 2018-03-20T19:36:08
|
C++
|
UTF-8
|
C++
| false
| false
| 1,253
|
cpp
|
perft.cpp
|
#include "Board.h"
#include "Search.h"
#include "Move.h"
#include "pertf.h"
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <map>
//Based off perft function here:
//http://chessprogramming.wikispaces.com/Perft
/*
* Perft functions allow for the testing of move generation algorithms and verify that they correctly
* generate all possible board states from a given position up to a certain depth.
* We have included helper code to also test amounts of captures and checks to further validify our code.
*/
u64 perft_nodes(Board &b, int depth, u64 &captures, u64 &checks)
{
std::vector<Move> moves = Search::generateMoveList(b);
if (depth == 1)
{
for (auto i : moves)
{
if(b.getPiece(i.to) != epcEmpty)
captures++;
}
return moves.size();
}
u64 nodes = 0;
for (auto i : moves)
{
b.makeMove(i);
nodes += perft_nodes(b, depth - 1, captures, checks);
b.unmakeMove();
}
return nodes;
}
std::tuple<u64, u64, u64> perft(Board &b, int depth)
{
u64 captures = 0;
u64 checks = 0;
u64 nodes = perft_nodes(b, depth, captures, checks);
return std::make_tuple(nodes, captures, checks);
}
|
6f3c9153d8c22614fc4dd1b1533343aace28c0a6
|
66f53c945a91158a9439e1bbea8cb8b823df556b
|
/include/DTL/Utility/Copy.hpp
|
5a07fc0ad8970825b2351db968d176768871b1c4
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] |
permissive
|
sitRyo/DungeonTemplateLibrary
|
cded163e2953b6c3218668a4fb6ab1b820d81d90
|
d8964db68fef28a292790ce9661e881cc3a5fa2d
|
refs/heads/master
| 2020-08-15T13:17:50.391650
| 2019-10-15T02:06:37
| 2019-10-15T02:06:37
| 215,349,428
| 1
| 0
|
BSL-1.0
| 2019-10-15T16:46:02
| 2019-10-15T16:46:02
| null |
UTF-8
|
C++
| false
| false
| 3,692
|
hpp
|
Copy.hpp
|
/*#######################################################################################
Made by Kasugaccho
Made by As Project
https://github.com/Kasugaccho/DungeonTemplateLibrary
wanotaitei@gmail.com
This code is licensed under CC0.
#######################################################################################*/
#ifndef INCLUDED_DUNGEON_TEMPLATE_LIBRARY_DTL_UTILITY_COPY_HPP
#define INCLUDED_DUNGEON_TEMPLATE_LIBRARY_DTL_UTILITY_COPY_HPP
///// DTL Only /////
#include <DTL/Macros/constexpr.hpp>
#include <DTL/Type/SizeT.hpp>
/*#######################################################################################
[概要] "dtl名前空間"とは"DungeonTemplateLibrary"の全ての機能が含まれる名前空間である。
[Summary] The "dtl" is a namespace that contains all the functions of "DungeonTemplateLibrary".
#######################################################################################*/
namespace dtl {
inline namespace utility { //"dtl::utility"名前空間に属する
namespace tool {
//キャストしてコピー
template<typename Matrix_Var_, typename Value_Int_>
DTL_VERSIONING_CPP14_CONSTEXPR
void castCopyValue(Matrix_Var_& value_, const Value_Int_& value2_) noexcept {
value_ = static_cast<Matrix_Var_>(value2_);
}
template<typename Matrix_>
DTL_VERSIONING_CPP14_CONSTEXPR
void copyMatrix(Matrix_& matrix_, const Matrix_& matrix2_) noexcept {
matrix_ = matrix2_;
}
} //namespace
namespace stl {
template<typename Matrix_, typename Matrix2_>
DTL_VERSIONING_CPP14_CONSTEXPR
void copyMatrix(Matrix_& matrix_, const Matrix2_& matrix2_) noexcept {
for (::dtl::type::size row{}; row < matrix_.size(); ++row)
for (::dtl::type::size col{}; col < matrix_[row].size(); ++col)
matrix_[row][col] = matrix2_[row][col];
}
} //namespace
namespace normal {
template<typename Matrix_, typename Matrix2_>
DTL_VERSIONING_CPP14_CONSTEXPR
void copyMatrix(Matrix_& matrix_, const Matrix2_& matrix2_, const ::dtl::type::size x_, const ::dtl::type::size y_) noexcept {
for (::dtl::type::size row{}; row < y_; ++row)
for (::dtl::type::size col{}; col < x_; ++col)
matrix_[row][col] = matrix2_[row][col];
}
} //namespace
namespace array {
template<typename Matrix_, typename Matrix2_>
DTL_VERSIONING_CPP14_CONSTEXPR
void copyMatrix(Matrix_& matrix_, const Matrix2_& matrix2_, const ::dtl::type::size x_, const ::dtl::type::size y_) noexcept {
for (::dtl::type::size row{}; row < y_; ++row)
for (::dtl::type::size col{}; col < x_; ++col)
matrix_[row * x_ + col] = matrix2_[row * x_ + col];
}
} //namespace
namespace layer {
namespace stl {
template<typename Matrix_, typename Matrix2_>
DTL_VERSIONING_CPP14_CONSTEXPR
void copyMatrix(Matrix_& matrix_, const Matrix2_& matrix2_, const ::dtl::type::size layer_) noexcept {
for (::dtl::type::size row{}; row < matrix_.size(); ++row)
for (::dtl::type::size col{}; col < matrix_[row].size(); ++col)
matrix_[row][col][layer_] = matrix2_[row][col][layer_];
}
} //namespace
}
namespace layer {
namespace normal {
template<typename Matrix_, typename Matrix2_>
DTL_VERSIONING_CPP14_CONSTEXPR
void copyMatrix(Matrix_& matrix_, const Matrix2_& matrix2_, const ::dtl::type::size layer_, const ::dtl::type::size x_, const ::dtl::type::size y_) noexcept {
for (::dtl::type::size row{}; row < y_; ++row)
for (::dtl::type::size col{}; col < x_; ++col)
matrix_[row][col][layer_] = matrix2_[row][col][layer_];
}
} //namespace
}
}
}
#endif //Included Dungeon Template Library
|
42b4642b5e1d366df83586997278f4c02d79e415
|
661bb25db192b744bd10d6c3ca702a7e307c602d
|
/TribesAscendSDK/HeaderDump/Engine.ChannelDownload.h
|
a0721e6e0066cf17e6d4a85cd94388b9929312ef
|
[] |
no_license
|
Orvid/TASDK
|
9582682f0f60a6f6fce5caea3cdd978f401565b3
|
6057c26b8185b08bc47c58ddecefe0f14becf566
|
refs/heads/master
| 2020-12-25T01:06:16.876697
| 2013-08-02T16:26:25
| 2013-08-02T16:26:25
| 11,539,096
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 168
|
h
|
Engine.ChannelDownload.h
|
#pragma once
namespace UnrealScript
{
class ChannelDownload;
}
#include "Engine.Download.h"
namespace UnrealScript
{
class ChannelDownload : public Download
{
};
}
|
fbda0bc6a37a8595a0933f67d5606726795c39ae
|
64589428b06258be0b9b82a7e7c92c0b3f0778f1
|
/Codeforces/Rounds/977/E.cpp
|
767cd8d5f3466197df6031341e2bdbc5ac8cd3e1
|
[] |
no_license
|
splucs/Competitive-Programming
|
b6def1ec6be720c6fbf93f2618e926e1062fdc48
|
4f41a7fbc71aa6ab8cb943d80e82d9149de7c7d6
|
refs/heads/master
| 2023-08-31T05:10:09.573198
| 2023-08-31T00:40:32
| 2023-08-31T00:40:32
| 85,239,827
| 141
| 27
| null | 2023-01-08T20:31:49
| 2017-03-16T20:42:37
|
C++
|
UTF-8
|
C++
| false
| false
| 857
|
cpp
|
E.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define MAXN 200009
#define MAXM ((1e+18) + 100)
#define MOD 1000000007
#define INF 1000000009
#define EPS 1e-9
#define FOR(x,n) for(int x=0; (x)<(n); (x)++)
#define FOR1(x,n) for(int x=1; (x)<=(n); (x)++)
#define pb push_back
#define all(x) x.begin(), x.end()
typedef pair<int, int> ii;
typedef long long ll;
#define EPS 1e-9
vector<int> g[MAXN];
bool vis[MAXN], ok[MAXN];
bool dfs(int u, int p) {
if (vis[u]) return ok[u];
vis[u] = true;
ok[u] = true;
if (g[u].size() != 2u) ok[u] = false;
for(int v : g[u]) {
ok[u] = ok[u] && dfs(v, u);
}
return ok[u];
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
FOR(k, m) {
int u, v;
scanf("%d %d", &u, &v);
g[u].pb(v);
g[v].pb(u);
}
int ans = 0;
FOR1(u, n) {
if (!vis[u] && dfs(u, -1)) {
ans++;
}
}
printf("%d\n", ans);
return 0;
}
|
9417220708ed05a0ed0ce533e73ffeb3ee536a0a
|
1495647af9e5941772ab7d383b4cf78cdb0fb77f
|
/Tree/Home/tree_global.cpp
|
f11b26ee5a73b7f262920c2476c582ccef0102d7
|
[] |
no_license
|
Imran4424/Data-Structure
|
aa7e33b567406dd9bf25be7cc35d72f0cee761a9
|
9b6b8e5367849e133aa437040946794db63399b1
|
refs/heads/master
| 2022-04-07T12:47:23.894934
| 2022-02-10T16:13:12
| 2022-02-10T16:13:12
| 124,618,740
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 862
|
cpp
|
tree_global.cpp
|
#include <iostream>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
node *root = new node;
node *ptr;
void insert_tree(int info)
{
node *temp = new node;
temp->data = info;
temp->left = NULL;
temp->right = NULL;
if(root == NULL){
root = temp;
}
else if(info <= ptr->data){
ptr = ptr->left;
insert_tree(info);
}
else if (info > ptr->data){
ptr = ptr->right;
insert_tree(info);
}
}
void print_preorder()
{
if(ptr){
cout<<ptr->data<<endl;
ptr = ptr->left;
print_preorder();
ptr = ptr->right;
print_preorder();
}
}
int main()
{
root = NULL;
ptr = root;
int i, inf;
for(i=1;i<=5;i++){
cin>>inf;
insert_tree(inf);
}
print_preorder();
return 0;
}
|
f8972c6245b16ea513f277f1a2f0058726624f23
|
91a882547e393d4c4946a6c2c99186b5f72122dd
|
/Source/XPSP1/NT/inetsrv/iis/ui/admin/comprop/machine.cpp
|
0ccb1e68f709ed81ae7f2c9be1785fc8f38b6f4e
|
[] |
no_license
|
IAmAnubhavSaini/cryptoAlgorithm-nt5src
|
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
|
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
|
refs/heads/master
| 2023-09-02T10:14:14.795579
| 2021-11-20T13:47:06
| 2021-11-20T13:47:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,726
|
cpp
|
machine.cpp
|
/*++
Copyright (c) 1994-1998 Microsoft Corporation
Module Name :
machine.cpp
Abstract:
IIS Machine properties page
Author:
Ronald Meijer (ronaldm)
Project:
Internet Services Manager
Revision History:
--*/
//
// Include Files
//
#include "stdafx.h"
#include "comprop.h"
#include "mime.h"
#define DLL_BASED __declspec(dllimport)
#include "mmc.h"
#include "machine.h"
#include "inetprop.h"
#include "..\mmc\constr.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CIISMachinePage, CPropertyPage)
typedef struct tagMASTER_DLL
{
LPCTSTR lpszDllName;
UINT nID;
} MASTER_DLL;
MASTER_DLL rgMasters[] =
{
//
// Note: path should not be neccesary for these
// config DLLs, because they should really already
// be loaded by inetmgr at this point.
//
{ _T("W3SCFG.DLL"), IDS_WWW_MASTER },
{ _T("FSCFG.DLL"), IDS_FTP_MASTER },
};
#define NUM_MASTER_DLL ARRAY_SIZE(rgMasters)
CMasterDll::CMasterDll(
IN UINT nID,
IN LPCTSTR lpszDllName,
IN LPCTSTR lpszMachineName
)
/*++
Routine Description:
Construct master dll object
Arguments:
UINT nID : Resource ID
LPCTSTR lpszDllName : Dll filename and path
LPCTSTR lpszMachineName : Current machine name
Return Value:
N/A
--*/
: m_hDll(NULL),
m_pfnConfig(NULL),
m_strText()
{
m_hDll = ::AfxLoadLibrary(lpszDllName);
if (m_hDll != NULL)
{
//
// Check to see if this service is installed
//
pfnQueryServerInfo pfnInfo = (pfnQueryServerInfo)
::GetProcAddress(m_hDll, SZ_SERVERINFO_PROC);
if (pfnInfo != NULL)
{
ISMSERVERINFO ism;
ism.dwSize = ISMSERVERINFO_SIZE;
CError err((*pfnInfo)(lpszMachineName, &ism));
if (err.Succeeded())
{
m_pfnConfig = (pfnConfigure)::GetProcAddress(
m_hDll,
SZ_CONFIGURE_PROC
);
if (m_pfnConfig != NULL)
{
HINSTANCE hOld = AfxGetResourceHandle();
AfxSetResourceHandle(GetModuleHandle(COMPROP_DLL_NAME));
VERIFY(m_strText.LoadString(nID));
AfxSetResourceHandle(hOld);
//
// Success!
//
return;
}
}
}
}
//
// Library didn't exist, was bogus, or unable to provide information
// about itself.
//
SAFE_AFXFREELIBRARY(m_hDll);
}
CMasterDll::~CMasterDll()
/*++
Routine Description:
Destructor -- decrement library reference count
Arguments:
N/A
Return Value:
N/A
--*/
{
TRACEEOLID("Deleting: " << m_strText);
SAFE_AFXFREELIBRARY(m_hDll);
}
/* static */
void
CIISMachinePage::ParseMaxNetworkUse(
IN OUT CILong & nMaxNetworkUse,
OUT BOOL & fLimitNetworkUse
)
/*++
Routine Description:
Break out max network use function
Arguments:
CILong & nMaxNetworkUse : Maximum network value (will be changed)
BOOL & fLimitMaxNetworkUse : TRUE if max network is not infinite
Return Value
None/
--*/
{
fLimitNetworkUse = (nMaxNetworkUse != INFINITE_BANDWIDTH);
nMaxNetworkUse = fLimitNetworkUse
? (nMaxNetworkUse / KILOBYTE)
: (DEF_BANDWIDTH / KILOBYTE);
}
CIISMachinePage::CIISMachinePage(
IN LPCTSTR lpstrMachineName,
IN HINSTANCE hInstance
)
/*++
Routine Description:
Constructor for IIS Machine property page
Arguments:
LPCTSTR lpstrMachineName : Machine name
HINSTANCE hInstance : Instance handle
Return Value:
N/A
--*/
: CPropertyPage(CIISMachinePage::IDD),
m_strMachineName(lpstrMachineName),
m_fLocal(IsServerLocal(lpstrMachineName)),
m_ppropMimeTypes(NULL),
m_ppropMachine(NULL),
m_lstMasterDlls(),
m_hr(S_OK)
{
#if 0 // Keep class wizard happy
//{{AFX_DATA_INIT(CIISMachinePage)
m_fLimitNetworkUse = FALSE;
m_nMasterType = -1;
//}}AFX_DATA_INIT
m_nMaxNetworkUse = 0;
#endif
m_nMasterType = 0;
//
// Data will be fetched later to prevent marshalling across
// threads errors. The dialog is constructed in one thread,
// and operates in another.
//
}
CIISMachinePage::~CIISMachinePage()
/*++
Routine Description:
Destructor
Arguments:
N/A
Return Value:
N/A
--*/
{
}
//
// COMPILER ISSUE::: Inlining this function doesn't
// work on x86 using NT 5!
//
HRESULT CIISMachinePage::QueryResult() const
{
return m_hr;
}
void
CIISMachinePage::DoDataExchange(
IN CDataExchange * pDX
)
/*++
Routine Description:
Initialise/Store control data
Arguments:
CDataExchange * pDX - DDX/DDV control structure
Return Value:
None
--*/
{
//
// Make sure data was fetched
//
ASSERT(m_ppropMachine != NULL);
ASSERT(m_ppropMimeTypes != NULL);
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CIISMachinePage)
DDX_CBIndex(pDX, IDC_COMBO_MASTER_TYPE, m_nMasterType);
DDX_Control(pDX, IDC_EDIT_MAX_NETWORK_USE, m_edit_MaxNetworkUse);
DDX_Control(pDX, IDC_STATIC_THROTTLE_PROMPT, m_static_ThrottlePrompt);
DDX_Control(pDX, IDC_STATIC_MAX_NETWORK_USE, m_static_MaxNetworkUse);
DDX_Control(pDX, IDC_STATIC_KBS, m_static_KBS);
DDX_Control(pDX, IDC_BUTTON_EDIT_DEFAULT, m_button_EditDefault);
DDX_Control(pDX, IDC_CHECK_LIMIT_NETWORK_USE, m_check_LimitNetworkUse);
DDX_Control(pDX, IDC_COMBO_MASTER_TYPE, m_combo_MasterType);
DDX_Check(pDX, IDC_CHECK_LIMIT_NETWORK_USE, m_fLimitNetworkUse);
//}}AFX_DATA_MAP
if (m_edit_MaxNetworkUse.IsWindowEnabled())
{
DDX_Text(pDX, IDC_EDIT_MAX_NETWORK_USE, m_nMaxNetworkUse);
DDV_MinMaxLong(pDX, m_nMaxNetworkUse, 1, UD_MAXVAL);
}
}
//
// Message Map
//
BEGIN_MESSAGE_MAP(CIISMachinePage, CPropertyPage)
//{{AFX_MSG_MAP(CIISMachinePage)
ON_BN_CLICKED(IDC_CHECK_LIMIT_NETWORK_USE, OnCheckLimitNetworkUse)
ON_BN_CLICKED(IDC_BUTTON_EDIT_DEFAULT, OnButtonEditDefault)
ON_BN_CLICKED(IDC_BUTTON_FILE_TYPES, OnButtonFileTypes)
ON_COMMAND(ID_HELP, OnHelp)
ON_COMMAND(ID_CONTEXT_HELP, OnHelp)
ON_WM_DESTROY()
ON_WM_HELPINFO()
//}}AFX_MSG_MAP
ON_EN_CHANGE(IDC_EDIT_MAX_NETWORK_USE, OnItemChanged)
END_MESSAGE_MAP()
BOOL
CIISMachinePage::SetControlStates()
/*++
Routine Description:
Set button states depending on contents of the controls.
Return whether or not "Limit network use" is on.
Arguments:
None
Return Value:
TRUE if "Limit network use" is checked
--*/
{
BOOL fLimitOn = m_check_LimitNetworkUse.GetCheck() > 0;
m_static_MaxNetworkUse.EnableWindow(fLimitOn);
m_static_ThrottlePrompt.EnableWindow(fLimitOn);
m_edit_MaxNetworkUse.EnableWindow(fLimitOn);
m_static_KBS.EnableWindow(fLimitOn);
return fLimitOn;
}
HRESULT
CIISMachinePage::LoadDelayedValues()
/*++
Routine Description:
Load the metabase parameters
Arguments:
None
Return Value:
HRESULT
--*/
{
//
// Fetch the properties from the metabase
//
ASSERT(m_ppropMachine == NULL);
ASSERT(m_ppropMimeTypes == NULL);
//
// Share interface between the objects here
//
m_ppropMachine = new CMachineProps(m_strMachineName);
if (NULL == m_ppropMachine)
return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
else if (FAILED(m_ppropMachine->QueryResult()))
return m_ppropMachine->QueryResult();
m_ppropMimeTypes = new CMimeTypes(m_ppropMachine);
if (NULL == m_ppropMimeTypes)
return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
else if (FAILED(m_ppropMimeTypes->QueryResult()))
return m_ppropMimeTypes->QueryResult();
m_hr = m_ppropMachine->LoadData();
if (SUCCEEDED(m_hr))
{
m_nMaxNetworkUse = m_ppropMachine->m_nMaxNetworkUse;
ParseMaxNetworkUse(m_nMaxNetworkUse, m_fLimitNetworkUse);
m_hr = m_ppropMimeTypes->LoadData();
if (SUCCEEDED(m_hr))
{
m_strlMimeTypes = m_ppropMimeTypes->m_strlMimeTypes;
}
}
return S_OK;
}
//
// Message Handlers
//
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
void
CIISMachinePage::OnHelp()
/*++
Routine Description:
'Help' button handler
Arguments:
None
Return Value:
None
--*/
{
if (m_strHelpFile.IsEmpty())
{
CRMCRegKey rk(REG_KEY, SZ_PARAMETERS, KEY_READ);
rk.QueryValue(SZ_HELPPATH, m_strHelpFile, EXPANSION_ON);
m_strHelpFile += _T("\\inetmgr.hlp");
TRACEEOLID("Initialized help file " << m_strHelpFile);
}
CWnd * pWnd = ::AfxGetMainWnd();
HWND hWndParent = pWnd != NULL
? pWnd->m_hWnd
: NULL;
::WinHelp(m_hWnd, m_strHelpFile, HELP_CONTEXT, HIDD_IIS_MACHINE);
}
BOOL
CIISMachinePage::OnHelpInfo(HELPINFO * pHelpInfo)
{
OnHelp();
return FALSE;
}
void
CIISMachinePage::OnCheckLimitNetworkUse()
/*++
Routine Description:
The "limit network use" checkbox has been clicked
Enable/disable the "max network use" controls.
Arguments:
None
Return Value:
None
--*/
{
if (SetControlStates())
{
m_edit_MaxNetworkUse.SetSel(0,-1);
m_edit_MaxNetworkUse.SetFocus();
}
OnItemChanged();
}
void
CIISMachinePage::OnItemChanged()
/*++
Routine Description:
All EN_CHANGE messages map to this function
Arguments:
None
Return Value:
None
--*/
{
SetModified(TRUE);
}
void
CIISMachinePage::OnButtonEditDefault()
/*++
Routine Description:
'edit default' button handler
Arguments:
None
Return Value:
None
--*/
{
//
// Get selection, and convert to index into server table
// via associative array.
//
CError err;
int nSel = m_combo_MasterType.GetCurSel();
ASSERT(nSel >= 0 && nSel < NUM_MASTER_DLL);
POSITION pos = m_lstMasterDlls.FindIndex(nSel);
ASSERT(pos != NULL);
CMasterDll * pDll = m_lstMasterDlls.GetAt(pos);
ASSERT(pDll != NULL);
//
// Allocate string with 2 terminating NULLS
//
int nLen = m_strMachineName.GetLength();
LPTSTR lpServers = AllocTString(nLen + 2);
if (lpServers == NULL)
{
err = ERROR_NOT_ENOUGH_MEMORY;
}
else
{
::lstrcpy(lpServers, m_strMachineName);
lpServers[nLen + 1] = _T('\0');
err = pDll->Config(m_hWnd, lpServers);
}
SAFE_FREEMEM(lpServers);
err.MessageBoxOnFailure();
}
void
CIISMachinePage::OnButtonFileTypes()
/*++
Routine Description:
'file types' button handler - bring up mime types dialog.
Arguments:
None
Return Value:
None
--*/
{
HINSTANCE hOld = AfxGetResourceHandle();
AfxSetResourceHandle(GetModuleHandle(COMPROP_DLL_NAME));
CMimeDlg dlg(m_strlMimeTypes, this);
if (dlg.DoModal() == IDOK)
{
OnItemChanged();
}
AfxSetResourceHandle(hOld);
}
BOOL
CIISMachinePage::OnInitDialog()
/*++
Routine Description:
WM_INITDIALOG handler. Initialize the dialog.
Arguments:
None.
Return Value:
TRUE if no focus is to be set automatically, FALSE if the focus
is already set.
--*/
{
CServerCapabilities caps(m_strMachineName, SZ_MBN_WEB);
BOOL fHasThrottling = caps.HasBwThrottling();
CError err(LoadDelayedValues());
if (err.Failed())
{
fHasThrottling = FALSE;
}
CPropertyPage::OnInitDialog();
//
// Fill the master combo box
//
int cServices = 0;
CMasterDll * pDll;
for (int n = 0; n < NUM_MASTER_DLL; ++n)
{
pDll = new CMasterDll(
rgMasters[n].nID,
rgMasters[n].lpszDllName,
m_strMachineName
);
if (pDll == NULL)
{
err = ERROR_NOT_ENOUGH_MEMORY;
break;
}
if (pDll->IsLoaded())
{
m_combo_MasterType.AddString(*pDll);
m_lstMasterDlls.AddTail(pDll);
++cServices;
}
else
{
//
// Dll didn't load, toss it.
//
delete pDll;
}
}
if (cServices == 0)
{
//
// No master-programmable services installed, so disallow
// master editing.
//
GetDlgItem(IDC_BUTTON_EDIT_DEFAULT)->EnableWindow(FALSE);
GetDlgItem(IDC_GROUP_MASTER)->EnableWindow(FALSE);
GetDlgItem(IDC_STATIC_MASTER_PROMPT1)->EnableWindow(FALSE);
GetDlgItem(IDC_STATIC_MASTER_PROMPT2)->EnableWindow(FALSE);
m_combo_MasterType.EnableWindow(FALSE);
}
m_check_LimitNetworkUse.EnableWindow(fHasThrottling);
m_combo_MasterType.SetCurSel(0);
SetControlStates();
err.MessageBoxOnFailure();
return TRUE;
}
BOOL
CIISMachinePage::OnApply()
/*++
Routine Description:
'Apply' button handler. Called when OK or APPLY is pressed.
Arguments:
None.
Return Value:
TRUE to continue, FALSE otherwise
--*/
{
//
// Don't use m_nMaxNetworkUse, because it would
// alter the values on the screen when DDX happens next.
//
CILong nMaxNetworkUse = m_nMaxNetworkUse;
BuildMaxNetworkUse(nMaxNetworkUse, m_fLimitNetworkUse);
m_ppropMachine->m_nMaxNetworkUse = nMaxNetworkUse;
CError err(m_ppropMachine->WriteDirtyProps());
if (err.Succeeded())
{
m_ppropMimeTypes->m_strlMimeTypes = m_strlMimeTypes;
err = m_ppropMimeTypes->WriteDirtyProps();
}
if (err.Succeeded())
{
return CPropertyPage::OnApply();
}
//
// Failed
//
err.MessageBox();
return FALSE;
}
void
CIISMachinePage::OnDestroy()
/*++
Routine Description:
Window is being destroyed. Time to clean up
Arguments:
None.
Return Value:
None.
--*/
{
ASSERT(m_ppropMachine != NULL);
ASSERT(m_ppropMimeTypes != NULL);
SAFE_DELETE(m_ppropMachine);
SAFE_DELETE(m_ppropMimeTypes);
while (!m_lstMasterDlls.IsEmpty())
{
CMasterDll * pDll = m_lstMasterDlls.RemoveHead();
delete pDll;
}
//
// Remove the help window if it's currently open
//
::WinHelp(m_hWnd, NULL, HELP_QUIT, 0L);
CPropertyPage::OnDestroy();
}
void
CIISMachinePage::PostNcDestroy()
/*++
Routine Description:
handle destruction of the window by freeing the this
pointer (as this modeless dialog must have been created
on the heap)
Arguments:
None.
Return Value:
None
--*/
{
delete this;
}
|
4f404688ac9594382a55b9732c5fe1433ed47161
|
eeedb5c3368637421ae7335dcc921ad9366f9e09
|
/healthbarhandler.cpp
|
baae85a6e7a8064d498861551fe78f513645fc2a
|
[] |
no_license
|
CaptainDreamcast/House
|
520ecc5efb6b4b133d2eaac29aa43b2eec754bd2
|
3967c8f54274a80723c5e756c2026b53986577bf
|
refs/heads/master
| 2020-04-19T06:51:58.774149
| 2019-01-28T20:24:45
| 2019-01-28T20:24:45
| 168,030,053
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,671
|
cpp
|
healthbarhandler.cpp
|
#include "healthbarhandler.h"
#include <prism/blitz.h>
#include "gamescreen.h"
#include "playerhandler.h"
#include "titlehandler.h"
#include "backgroundhandler.h"
static struct {
int mHouseMaxHealth;
int mHouseCurrentHealth;
int mPlayerMaxHealth;
int mPlayerCurrentHealth;
int mHouseBGAnimationID;
int mHouseFGAnimationID;
int mHouseTextID;
int mPlayerBGAnimationID;
int mPlayerFGAnimationID;
int mIsActive;
} gHealthBarHandler;
static void resetHealth() {
gHealthBarHandler.mHouseMaxHealth = 30000;
gHealthBarHandler.mHouseCurrentHealth = gHealthBarHandler.mHouseMaxHealth;
gHealthBarHandler.mPlayerMaxHealth = 4;
gHealthBarHandler.mPlayerCurrentHealth = gHealthBarHandler.mPlayerMaxHealth;
}
static void loadHealthBarHandler(void* tData) {
(void)tData;
resetHealth();
gHealthBarHandler.mIsActive = 0;
}
ActorBlueprint getHealthBarHandler()
{
return makeActorBlueprint(loadHealthBarHandler);
}
void setHealthbarsActive()
{
gHealthBarHandler.mHouseBGAnimationID = addMugenAnimation(getMugenAnimation(getGameAnimations(), 6000), getGameSprites(), makePosition(21, 2, 20));
gHealthBarHandler.mHouseFGAnimationID = addMugenAnimation(getMugenAnimation(getGameAnimations(), 6001), getGameSprites(), makePosition(21, 2, 21));
gHealthBarHandler.mHouseTextID = addMugenTextMugenStyle("House", makePosition(160, 13, 22), makeVector3DI(1, 0, 0));
gHealthBarHandler.mPlayerBGAnimationID = addMugenAnimation(getMugenAnimation(getGameAnimations(), 6002), getGameSprites(), makePosition(160 - 25, 80, 20));
gHealthBarHandler.mPlayerFGAnimationID = addMugenAnimation(getMugenAnimation(getGameAnimations(), 6003), getGameSprites(), makePosition(160 - 25, 80, 21));
gHealthBarHandler.mIsActive = 1;
}
void setHealthbarsInactive()
{
removeMugenAnimation(gHealthBarHandler.mHouseBGAnimationID);
removeMugenAnimation(gHealthBarHandler.mHouseFGAnimationID);
removeMugenText(gHealthBarHandler.mHouseTextID);
removeMugenAnimation(gHealthBarHandler.mPlayerBGAnimationID);
removeMugenAnimation(gHealthBarHandler.mPlayerFGAnimationID);
gHealthBarHandler.mIsActive = 0;
}
void decreasePlayerHealth()
{
gHealthBarHandler.mPlayerCurrentHealth--;
double percentage = gHealthBarHandler.mPlayerCurrentHealth / (double)gHealthBarHandler.mPlayerMaxHealth;
setMugenAnimationRectangleWidth(gHealthBarHandler.mPlayerFGAnimationID, percentage * 50);
}
void resetPlayerHealth()
{
if (!gHealthBarHandler.mIsActive) return;
gHealthBarHandler.mPlayerCurrentHealth = gHealthBarHandler.mPlayerMaxHealth;
double percentage = gHealthBarHandler.mPlayerCurrentHealth / (double)gHealthBarHandler.mPlayerMaxHealth;
setMugenAnimationRectangleWidth(gHealthBarHandler.mPlayerFGAnimationID, percentage * 50);
}
int getPlayerHealth()
{
return gHealthBarHandler.mPlayerCurrentHealth;
}
void decreaseHouseHealth()
{
gHealthBarHandler.mHouseCurrentHealth--;
double percentage = gHealthBarHandler.mHouseCurrentHealth / (double)gHealthBarHandler.mHouseMaxHealth;
setMugenAnimationRectangleWidth(gHealthBarHandler.mHouseFGAnimationID, percentage * 277);
if (gHealthBarHandler.mHouseCurrentHealth == 0) {
setHouseCollapsed();
if (!isPlayerActive()) return;
setPlayerInactive();
startGameOver();
}
}
void increaseHouseHealth(int tMoney)
{
if (!gHealthBarHandler.mIsActive) return;
gHealthBarHandler.mHouseCurrentHealth += tMoney * 50;
gHealthBarHandler.mHouseCurrentHealth = fmin(gHealthBarHandler.mHouseCurrentHealth, gHealthBarHandler.mHouseMaxHealth);
double percentage = gHealthBarHandler.mHouseCurrentHealth / (double)gHealthBarHandler.mHouseMaxHealth;
setMugenAnimationRectangleWidth(gHealthBarHandler.mHouseFGAnimationID, percentage * 277);
}
|
882118a4ab4049c5cbd5df58c69855807173e991
|
5ca1c8bee4fb4decde14e4bc92034086add8130d
|
/Release/Qt/AttentivenessParameter/mainwindow.cpp
|
2a515d2b0fc7c23c6b4c8a940675b47b634d687c
|
[] |
no_license
|
BlackBerryPi/Attentiveness-Parameter
|
f5a72a695efebbf3174825482ab13d2ddda6ecf6
|
49e3669ea48601ae1c6c4189c5cf19b2850ccb19
|
refs/heads/master
| 2021-09-11T19:43:08.249838
| 2018-04-02T12:54:19
| 2018-04-02T12:54:19
| 125,729,787
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,763
|
cpp
|
mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QString>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->BaudRateSpinBox->setValue(9600);
const auto infos = QSerialPortInfo::availablePorts();
for (const QSerialPortInfo &info : infos)
ui->serialPortComboBox->addItem(info.portName());
setWindowTitle(tr("AttentivenessParameter"));
ui->serialPortComboBox->setFocus();
tempWidget = new DrawWidget(ui->tempTab);
resistWidget = new DrawWidget(ui->resistTab);
gyroXWidget = new DrawWidget(ui->GyroXTab);
gyroYWidget = new DrawWidget(ui->GyroYTab);
gyroZWidget = new DrawWidget(ui->GyroZTab);
connect(ui->runButton, &QPushButton::clicked, this, &MainWindow::startSlave);
connect(&m_thread, &SlaveThread::request, this,&MainWindow::showRequest);
connect(&m_thread, &SlaveThread::error, this, &MainWindow::processError);
connect(&m_thread, &SlaveThread::timeout, this, &MainWindow::processTimeout);
connect(ui->serialPortComboBox, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
this, &MainWindow::activateRunButton);
connect(ui->BaudRateSpinBox, QOverload<const QString &>::of(&QSpinBox::valueChanged),
this, &MainWindow::activateRunButton);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::startSlave()
{
// drawWidget = new DrawWidget();
// drawWidget->move(this->x(), this->y()+this->height()+40);
// drawWidget->show();
ui->runButton->setEnabled(false);
// ui->runButton->setText("Stop");
ui->statusLabel->setText(tr("Status: Running, connected to port %1.")
.arg(ui->serialPortComboBox->currentText()));
if(threadRunFlag)
{
qDebug() << "run";
m_thread.startSlave(ui->serialPortComboBox->currentText(),
ui->BaudRateSpinBox->value(),
"a");
}
}
void MainWindow::showRequest(const QString &s)
{
// ui->trafficLabel->setText(tr("Traffic, transaction #%1:"
// "\n\r-request: %2"
// "\n\r-response: %3")
// .arg(++m_transactionCount)
// .arg(s)
// .arg(""));
//qDebug() << "Request: "<< tr("%1").arg(s);
qDebug() << "Receives: " << s;
QStringList sList = s.split(';');
for(QStringList::iterator it = sList.begin(); it != sList.end(); it++)
{
if(!((*it).mid(0,1).compare("T")))
{
qDebug() << "T" << *(it);
tempWidget->setData(((*it).mid(1).toInt()));
}
else if(!((*it).mid(0,1).compare("R")))
{
resistWidget->setData(((*it).mid(1).toInt()));
}
else if(!((*it).mid(0,1).compare("X")))
{
gyroXWidget->setData(((*it).mid(1).toInt())/2);
}
else if(!((*it).mid(0,1).compare("Y")))
{
gyroYWidget->setData(((*it).mid(1).toInt())/2);
}
else if(!((*it).mid(0,1).compare("Z")))
{
gyroZWidget->setData(((*it).mid(1).toInt())/2);
}
}
// drawWidget->setData(s.mid(0,1), s.mid(1).toInt());
}
void MainWindow::processError(const QString &s)
{
activateRunButton();
ui->statusLabel->setText(tr("Status: Not running, %1.").arg(s));
ui->trafficLabel->setText(tr("No traffic."));
}
void MainWindow::processTimeout(const QString &s)
{
ui->statusLabel->setText(tr("Status: Running, %1.").arg(s));
ui->trafficLabel->setText(tr("No traffic."));
}
void MainWindow::activateRunButton()
{
ui->runButton->setEnabled(true);
}
|
40ae859f68f345dda1c72cb291316af0ff6a1b8e
|
f5798b166c808c8d5f69afd77285243bb74db8f2
|
/main.cpp
|
a529ec3227200f3bf6e035b9b9748bc1bda70313
|
[
"MIT"
] |
permissive
|
LorieMc/Demo
|
fd7f31122a9adba6bf9f85660d20f35966e3af0a
|
35360e2de7635e426941f889ce38c00b7e53cbe1
|
refs/heads/master
| 2021-01-17T18:52:56.328385
| 2015-06-14T21:57:04
| 2015-06-14T21:57:04
| 37,427,632
| 0
| 0
| null | 2015-06-14T20:03:18
| 2015-06-14T20:03:18
| null |
WINDOWS-1252
|
C++
| false
| false
| 27,350
|
cpp
|
main.cpp
|
/*-------------\
| main.cpp | Demo Challenge OpenGL 3.3 Framework
\*-------------/ ------------------------------------------------------------------------------------------*\
Version 3.3 - 06/05/2015
Author: Godvalve
Email: godvalve@hotmail.com
Participate in the Demo Challenge. Visit: http://demochronicles.mccolm.org/compete.php
Description: A simple OpenGL framework derived from the default project produced by the Code::Blocks project wizard.
Read a thorough description of how this file works at http://demochronicles.mccolm.org/build.php?mode=nextPage&article=10
\*----------------------------------------------------------------------------------------------------------*/
#include <windows.h>
#include <iostream>
#include <stdio.h> // Used of fprintf and stderr
#include <GL/glew.h> // Used for OpenGL types like GLuint
#include <GL/wglew.h> // Windows specific OpenGL Extension Wrangler library definitions
#include <GL/glext.h> // OpenGL extension definitions (OpenGL Working Group)
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform2.hpp>
using namespace glm;
#include "resource.h" // The reouce class with program icons and launcher dialogue box
#include "Shader.h" // Our GLSL Shader class
using std::string;
using std::ifstream;
using std::vector;
//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
float fTime=0.f, fDeltaTime=0.f;
char szAppName[] = "-= Demo Challenge Framework =-";
static BOOL fullscreen;
int iScreenWidth;
int iScreenHeight;
int iBitsPerPel;
float fAspectRatio;
float fFieldOfView;
Shader *demoShader; // Declare a Shader object
LARGE_INTEGER TimerFreq; // Timer Frequency.
LARGE_INTEGER TimeStart; // Time of start.
LARGE_INTEGER TimeCur; // Current time.
glm::mat4 projectionMatrix;
glm::mat4 viewMatrix;
glm::mat4 modelMatrix;
glm::mat4 MVP;
GLuint mvpMatrixLocationInShader;
GLuint vertexBuffer; // This will identify our vertex buffer
GLuint colorBuffer; // Our color buffer
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
BOOL CALLBACK DlgProc(HWND, UINT, WPARAM, LPARAM);
void EnableOpenGL(HWND hWnd, HDC*, HGLRC*);
void DisableOpenGL(HWND, HDC, HGLRC);
void ConfigureViewport(GLsizei, GLsizei);
void ResizeViewport(GLsizei, GLsizei);
void InitializeDemo();
void RenderNextDemoFrame();
void ChangeDisplayMode();
void RestoreDisplayMode();
void createSquare();
#define BUFFER_OFFSET(i) ((char*)NULL + (i))
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
WNDCLASSEX wcex;
HWND hWnd;
HDC hDC;
HGLRC hRC;
MSG msg;
BOOL bQuit = FALSE;
fullscreen = TRUE;
// Only shows on the console window if in debug build. Use release mode or change build options to remove console window.
std::cout << "OpenGL Demo Framework version 3.3 (June 05, 2015)\n";
/* Display the Demo Challenge Launcher to get user's preferences for fullscreen and resolution */
if(DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DemoLauncher), HWND_DESKTOP, DlgProc, 0) == FALSE)
{
return 0;
}
/* Register window class */
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_OWNDC;
wcex.lpfnWndProc = WindowProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_SMICON);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szAppName;
wcex.hIconSm = LoadIcon(hInstance, (LPCTSTR)IDI_SMICON);
if (!RegisterClassEx(&wcex))
return 0;
/* Create main window */
if(fullscreen == FALSE)
{
hWnd = CreateWindowEx(0,
szAppName,
szAppName,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
iScreenWidth + GetSystemMetrics(SM_CXSIZEFRAME) * 2,
iScreenHeight + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYSIZEFRAME) * 2,
NULL,
NULL,
hInstance,
NULL);
}
else
{
/* Bring up the application in fullscreen mode */
hWnd = CreateWindow(
szAppName,
szAppName,
WS_POPUP,
0, 0,
iScreenWidth, iScreenHeight,
NULL, NULL,
hInstance,
0 );
}
/* Reset the timer variables */
QueryPerformanceFrequency(&TimerFreq);
QueryPerformanceCounter(&TimeStart);
if(fullscreen)
{
ShowCursor(FALSE);
ChangeDisplayMode();
}
/* Enable OpenGL for the window */
EnableOpenGL(hWnd, &hDC, &hRC);
ShowWindow(hWnd, nCmdShow);
InitializeDemo(); // new
/* Program main loop */
while (!bQuit)
{
/* Check for messages */
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
/* Handle or dispatch messages */
if (msg.message == WM_QUIT)
{
bQuit = TRUE;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
/* Get the current time, and update the time controller. */
QueryPerformanceCounter(&TimeCur);
float fOldTime = fTime;
fTime = (float)((double)(TimeCur.QuadPart-TimeStart.QuadPart)/(double)TimerFreq.QuadPart);
fDeltaTime = fTime - fOldTime;
/* Render the next frame in our demo */
RenderNextDemoFrame(); // new
/* Change logical order of back and front buffer */
SwapBuffers(hDC);
}
}
/* Shutdown OpenGL */
DisableOpenGL(hWnd, hDC, hRC);
/* Destroy the window explicitly */
DestroyWindow(hWnd);
return msg.wParam;
}
//--------------------------------------------------------------------------------------
// Set the rendering area to accomodate the selected aspect ratio
//--------------------------------------------------------------------------------------
void ConfigureViewport(GLsizei width, GLsizei height)
{
/* Prevent a divide by Zero */
if( height == 0 )
height = 1;
GLfloat fActualAspectRatio = ((GLfloat)width/(GLfloat)height);
GLsizei x_offset = 0;
GLsizei y_offset = 0;
GLsizei viewPortWidth = width;
GLsizei viewPortHeight = height;
if(fAspectRatio < fActualAspectRatio)
{
GLfloat visibleWidth = (GLfloat)height * fAspectRatio;
x_offset = (GLsizei)((width-(int)visibleWidth)/2.0f);
viewPortWidth = (int)visibleWidth;
}
else if(fAspectRatio > fActualAspectRatio)
{
GLfloat visibleHeight = (GLfloat)width/fAspectRatio;
y_offset =(GLsizei)((height-(int)visibleHeight)/2.0f);
viewPortHeight = (int)visibleHeight;
}
/* Set viewport to our new dimensions. */
glViewport( x_offset, y_offset, viewPortWidth, viewPortHeight);
}
//--------------------------------------------------------------------------------------
// Resize the window and reset the projection matrix
//--------------------------------------------------------------------------------------
void ResizeViewport(GLsizei width, GLsizei height)
{
/* Set the viewport to conform to selected aspect ratio */
ConfigureViewport(width, height);
projectionMatrix = glm::perspective(fFieldOfView, fAspectRatio, 0.1F, 100.0F); // Creates a perspective projection matrix
}
//--------------------------------------------------------------------------------------
// Set screen to fullscreen mode
//--------------------------------------------------------------------------------------
void ChangeDisplayMode()
{
DEVMODE device_mode;
memset(&device_mode, 0, sizeof(DEVMODE));
device_mode.dmSize = sizeof(DEVMODE);
device_mode.dmPelsWidth = iScreenWidth;
device_mode.dmPelsHeight = iScreenHeight;
device_mode.dmBitsPerPel = iBitsPerPel;
device_mode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
ChangeDisplaySettings(&device_mode, CDS_FULLSCREEN);
}
//--------------------------------------------------------------------------------------
// Set screen to windowed mode using values in registry
//--------------------------------------------------------------------------------------
void RestoreDisplayMode()
{
ChangeDisplaySettings(NULL, 0);
}
//--------------------------------------------------------------------------------------
// Called every time the application receives a message
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
{
switch (wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
break;
}
}
break;
/* Catch and handle window resize event */
case WM_SIZE:
ResizeViewport(LOWORD(lParam),HIWORD(lParam)); // LoWord= width, HiWord= height
break;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
//--------------------------------------------------------------------------------------
// Called every time the Demo Challenge Launcher receives a message
//--------------------------------------------------------------------------------------
BOOL CALLBACK DlgProc (HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
/* Select fullscreen option by default */
HWND hCkBxFullscreen = GetDlgItem(hDlg, IDC_FULLSCREEN);
PostMessage(hCkBxFullscreen, BM_SETCHECK,BST_CHECKED,0);
HWND hResolutionList = GetDlgItem(hDlg, IDC_RESOLUTION);
DWORD iDevNum = 0;
DWORD iModeNum = 0;
DISPLAY_DEVICE ddi;
DEVMODE dmi;
TCHAR szBuffer [100];
ZeroMemory(&ddi, sizeof(ddi));
ddi.cb = sizeof(ddi);
ZeroMemory(&dmi, sizeof(dmi));
dmi.dmSize = sizeof(dmi);
while(EnumDisplayDevices (NULL, iDevNum++, &ddi, 0))
{
while(EnumDisplaySettings (ddi.DeviceName, iModeNum++, &dmi))
{
if(((ddi.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) > 0) && (dmi.dmBitsPerPel >= 32))
{
wsprintf(szBuffer, "%ix%i, %i bpp @ %iHz", dmi.dmPelsWidth,
dmi.dmPelsHeight, dmi.dmBitsPerPel, dmi.dmDisplayFrequency);
SendMessage(hResolutionList, LB_INSERTSTRING,0,(LPARAM)szBuffer); // p. 403 Petzold
ZeroMemory(&dmi, sizeof(dmi));
dmi.dmSize = sizeof(dmi);
}
}
ZeroMemory(&ddi, sizeof(ddi));
ddi.cb = sizeof(ddi);
iModeNum = 0;
}
SendMessage(hResolutionList, LB_SETCURSEL, 0, 0); // p. 403 Petzold
HWND hAspectRatioList = GetDlgItem(hDlg, IDC_ASPECT);
SendMessage(hAspectRatioList, LB_INSERTSTRING,(WPARAM)-1,(LPARAM)"Auto");
SendMessage(hAspectRatioList, LB_INSERTSTRING,(WPARAM)-1,(LPARAM)"4:3");
SendMessage(hAspectRatioList, LB_INSERTSTRING,(WPARAM)-1,(LPARAM)"16:9");
SendMessage(hAspectRatioList, LB_INSERTSTRING,(WPARAM)-1,(LPARAM)"16:10");
SendMessage(hAspectRatioList, LB_SETCURSEL, 0, 0);
return TRUE;
}
break;
case WM_COMMAND:
{
switch(LOWORD (wParam))
{
/* User pressed the 'Launch!' button */
case IDLAUNCH:
{
/* Check to see if fullscreen is selected and set our global fullscreen variable */
fullscreen = (IsDlgButtonChecked(hDlg, IDC_FULLSCREEN) == BST_CHECKED);
/* Grab the selected resolution */
HWND hResolutionList = GetDlgItem(hDlg, IDC_RESOLUTION); // p. 404 Petzold
int iIndex = SendMessage(hResolutionList, LB_GETCURSEL, 0, 0);
int iLength = SendMessage(hResolutionList, LB_GETTEXTLEN, iIndex, 0);
char* szResolutionBuffer = new char[iLength+1];;
SendMessage(hResolutionList, LB_GETTEXT, iIndex, (LPARAM)szResolutionBuffer);
int iCount = 1;
char * pch;
pch = strtok(szResolutionBuffer,"x");
while(pch != NULL)
{
switch(iCount)
{
case 1:
iScreenWidth = (int)atof(pch);
break;
case 2:
iScreenHeight = (int)atof(pch);
break;
case 3:
iBitsPerPel = (int)atof(pch);
break;
}
pch = strtok (NULL, " ,H");
iCount++;
}
/* Get the selected aspect ratio */
HWND hAspectRatioList = GetDlgItem(hDlg, IDC_ASPECT);
iIndex = SendMessage(hAspectRatioList, LB_GETCURSEL, 0, 0);
GLfloat iWidthRatio;
GLfloat iHeightRatio;
if(iIndex == 0)
{
/* Use the native aspect ratio */
fAspectRatio = (GLfloat)iScreenWidth / (GLfloat)iScreenHeight;
}
else
{
/* Use the selected aspect ratio */
iLength = SendMessage(hAspectRatioList, LB_GETTEXTLEN, iIndex, 0);
char* szAspectBuffer = new char[iLength+1];
SendMessage(hAspectRatioList, LB_GETTEXT, iIndex, (LPARAM)szAspectBuffer);
iCount = 1;
pch = strtok(szAspectBuffer,":");
while(pch != NULL)
{
switch(iCount)
{
case 1:
iWidthRatio = (GLfloat)atof(pch);
break;
case 2:
iHeightRatio = (GLfloat)atof(pch);
break;
}
pch = strtok (NULL, ":");
iCount++;
}
/* Use selected aspect ratio */
fAspectRatio = iWidthRatio / iHeightRatio;
}
EndDialog (hDlg, 1); // User is ready to launch the demo
return TRUE;
}
/* Handle default Win32 keyboard logic for dialog windows (ESC key pressed) */
case IDCANCEL:
/* User pressed the 'Exit' button */
case IDEXIT:
EndDialog (hDlg, 0); // User cancelled the dialog window
return TRUE;
}
}
break;
/* Moves the window when the user clicks anywhere not covered by a control. HTCAPTION specifies */
/* that all button clicks originate in the title bar area - even when the window has no title bar. */
case WM_LBUTTONDOWN:
{
PostMessage(hDlg, WM_NCLBUTTONDOWN, HTCAPTION,0);
break;
}
}
return FALSE;
}
//--------------------------------------------------------------------------------------
// Set the application's pixel format and create a rendering context
//--------------------------------------------------------------------------------------
void EnableOpenGL(HWND hWnd, HDC* hDC, HGLRC* hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int iFormat;
/* get the device context (DC) */
*hDC = GetDC(hWnd);
/* set the pixel format for the DC */
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ChoosePixelFormat(*hDC, &pfd);
SetPixelFormat(*hDC, iFormat, &pfd);
HGLRC tempContext;
/* create and enable a temporary OpenGL 2.1 rendering context (RC) */
tempContext = wglCreateContext(*hDC);
/*WGL functions are extensions to Win32 specifically for OpenGL (used for remembering OGL settings and commands)*/
wglMakeCurrent(*hDC, tempContext); // Make the OpenGL 2.1 context current and active
int attributes[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 3, // Set the MAJOR version of OpenGL to 3
WGL_CONTEXT_MINOR_VERSION_ARB, 3, // Set the MINOR version of OpenGL to 3
//WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, // Set our OpenGL context to be forward compatible
0
};
GLenum error = glewInit(); // Enable GLEW so we can use extensions required to use shaders
if (error != GLEW_OK){ // If GLEW fails
MessageBox(NULL, "GLEW failed to intialize", "Error", MB_ICONERROR | MB_OK);
}
if (wglewIsSupported("WGL_ARB_create_context") == 1) { // If the OpenGL 3.x context creation extension is available
*hRC = wglCreateContextAttribsARB(*hDC, NULL, attributes); // Create and OpenGL 3.x context based on the given attributes
wglMakeCurrent(NULL, NULL); // Remove the temporary context from being active
wglDeleteContext(tempContext); // Delete the temporary OpenGL 2.1 context
wglMakeCurrent(*hDC, *hRC); // Make our OpenGL 3.x context current
}
else {
*hRC = tempContext; // If we didn't have support for OpenGL 3.x and up, use the OpenGL 2.1 context
}
int glVersion[2] = {-1, -1}; // Set some default values for the version
glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); // Get back the OpenGL MAJOR version we are using
glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); // Get back the OpenGL MAJOR version we are using
std::cout << "Using OpenGL: " << glVersion[0] << "." << glVersion[1] << std::endl; // Output which version of OpenGL we are using On Windows, you won’t get a console for a Win32 Application, but a nifty trick to get console output, is to open up Command Prompt, navigate to your directory with your executable file, and use something like: “program.exe > temp.txt”
*hRC = wglCreateContextAttribsARB(*hDC, 0, attributes);
wglDeleteContext(tempContext);
wglMakeCurrent(*hDC, *hRC);
}
//--------------------------------------------------------------------------------------
// Release rendering context, reset display mode, and release the device context
//--------------------------------------------------------------------------------------
void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hRC);
/* Restore graphics mode to values stored in registry */
if(fullscreen)
{
RestoreDisplayMode();
ShowCursor(TRUE);
}
ReleaseDC(hWnd, hDC);
}
//--------------------------------------------------------------------------------------
// Initialize the OpenGL state machine. Set up projection matrix and other initial states
//--------------------------------------------------------------------------------------
void InitializeDemo() // Setup our scene
{
glClearColor(0.4f, 0.6f, 0.9f, 0.0f); // Set the clear colour based on Microsoft's CornflowerBlue (default in XNA)
demoShader = new Shader("basic-fixed.vert", "basic-fixed.frag"); // Initialize our Shader object with the file names of our shader files. Shader files are located inthe same directory as the compiled application.
fFieldOfView = 45.0F; // Set to 60.0F
ConfigureViewport(iScreenWidth, iScreenHeight); // Set the viewport to the selected aspect ratio and compute the projection matrix
viewMatrix = glm::lookAt(glm::vec3(4,3,3), glm::vec3(0,0,0), glm::vec3(0,1,0));
modelMatrix = glm::mat4(1.0f);
projectionMatrix = glm::perspective(fFieldOfView, fAspectRatio, 0.1F, 100.0F); // Creates a perspective projection matrix
MVP = projectionMatrix * viewMatrix * modelMatrix;
mvpMatrixLocationInShader = glGetUniformLocation(demoShader->id(), "MVP"); // Get the location of the projection matrix in the shader
createSquare();
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
}
//--------------------------------------------------------------------------------------
// The location of your OpenGL code
//--------------------------------------------------------------------------------------
void RenderNextDemoFrame()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
demoShader->Bind();
//glRotatef(fTime*120, 0.2f, 1.0f, 0.2f);
modelMatrix = glm::rotate(modelMatrix,fDeltaTime,glm::vec3(0.2f, 1.0f, 0.2f)); //rotate
MVP = projectionMatrix * viewMatrix * modelMatrix;
glUniformMatrix4fv(mvpMatrixLocationInShader, 1, GL_FALSE, &MVP[0][0]);
// 1st attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the vertex shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : colors
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glVertexAttribPointer(
1, // attribute 1. No particular reason for 1, but must match the layout in the vertex shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 12*3); // Starting from vertex 0; 3 vertices total -> 1 triangle
glDisableVertexAttribArray(0);
demoShader->unbind();
}
void createSquare() {
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID); // Create our Vertex Array Object
glBindVertexArray(VertexArrayID); // Bind our Vertex Array Object so we can use it
// Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
// A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f,-1.0f,-1.0f, // triangle 1 : begin
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f, // triangle 1 : end
1.0f, 1.0f,-1.0f, // triangle 2 : begin
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f, // triangle 2 : end
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f
};
// One color for each vertex. They were generated randomly.
static const GLfloat g_color_buffer_data[] = {
0.583f, 0.771f, 0.014f,
0.609f, 0.115f, 0.436f,
0.327f, 0.483f, 0.844f,
0.822f, 0.569f, 0.201f,
0.435f, 0.602f, 0.223f,
0.310f, 0.747f, 0.185f,
0.597f, 0.770f, 0.761f,
0.559f, 0.436f, 0.730f,
0.359f, 0.583f, 0.152f,
0.483f, 0.596f, 0.789f,
0.559f, 0.861f, 0.639f,
0.195f, 0.548f, 0.859f,
0.014f, 0.184f, 0.576f,
0.771f, 0.328f, 0.970f,
0.406f, 0.615f, 0.116f,
0.676f, 0.977f, 0.133f,
0.971f, 0.572f, 0.833f,
0.140f, 0.616f, 0.489f,
0.997f, 0.513f, 0.064f,
0.945f, 0.719f, 0.592f,
0.543f, 0.021f, 0.978f,
0.279f, 0.317f, 0.505f,
0.167f, 0.620f, 0.077f,
0.347f, 0.857f, 0.137f,
0.055f, 0.953f, 0.042f,
0.714f, 0.505f, 0.345f,
0.783f, 0.290f, 0.734f,
0.722f, 0.645f, 0.174f,
0.302f, 0.455f, 0.848f,
0.225f, 0.587f, 0.040f,
0.517f, 0.713f, 0.338f,
0.053f, 0.959f, 0.120f,
0.393f, 0.621f, 0.362f,
0.673f, 0.211f, 0.457f,
0.820f, 0.883f, 0.371f,
0.982f, 0.099f, 0.879f
};
glGenBuffers(1, &vertexBuffer); // Generate 1 buffer, put the resulting identifier in vertexBuffer
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); // The following commands will talk about our 'vertexBuffer' buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); // Give our vertices to OpenGL.
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data), g_color_buffer_data, GL_STATIC_DRAW);
}
|
32041a6c824dc865aba71761a8beb4e40702c94e
|
2c78b4a6c5479bd388669b2f954b10cfa3e5a67f
|
/include/bm/bm_sim/queue.h
|
309a9c98d484af0f9406ca2bff18b7cb4b591de6
|
[
"Apache-2.0"
] |
permissive
|
p4lang/behavioral-model
|
f543d155215df7b37843b36e5d11d63712404218
|
7d7c3c7c5b82c14a8d70ecd82ad15635425f01d9
|
refs/heads/main
| 2023-09-03T19:31:48.415229
| 2023-08-21T16:45:31
| 2023-08-21T16:45:31
| 29,883,110
| 507
| 399
|
Apache-2.0
| 2023-09-08T00:58:09
| 2015-01-26T21:43:23
|
C++
|
UTF-8
|
C++
| false
| false
| 4,112
|
h
|
queue.h
|
/* Copyright 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
//! @file queue.h
#ifndef BM_BM_SIM_QUEUE_H_
#define BM_BM_SIM_QUEUE_H_
#include <condition_variable>
#include <deque>
#include <mutex>
#include <utility>
namespace bm {
/* TODO(antonin): implement non blocking read behavior */
//! A utility queueing class made available to all targets. It could be used
//! -for example- to queue packets between an ingress thread and an egress
//! thread. This is a very simple class, which does not implement anything fancy
//! (e.g. rate limiting, priority queueing, fair scheduling, ...) but can be
//! used as a base class to build something more advanced.
//! Queue includes a mutex and is thread-safe.
template <class T>
class Queue {
public:
//! Implementation behavior when an item is pushed to a full queue
enum WriteBehavior {
//! block and wait until a slot is available
WriteBlock,
//! return immediately
WriteReturn
};
//! Implementation behavior when an element is popped from an empty queue
enum ReadBehavior {
//! block and wait until the queue becomes non-empty
ReadBlock,
//! not implemented yet
ReadReturn
};
public:
Queue()
: capacity(1024), wb(WriteBlock), rb(ReadBlock) { }
//! Constructs a queue with specified \p capacity and read / write behaviors
Queue(size_t capacity,
WriteBehavior wb = WriteBlock, ReadBehavior rb = ReadBlock)
: capacity(capacity), wb(wb), rb(rb) {}
//! Makes a copy of \p item and pushes it to the front of the queue
void push_front(const T &item) {
std::unique_lock<std::mutex> lock(q_mutex);
while (!is_not_full()) {
if (wb == WriteReturn) return;
q_not_full.wait(lock);
}
queue.push_front(item);
lock.unlock();
q_not_empty.notify_one();
}
//! Moves \p item to the front of the queue
void push_front(T &&item) {
std::unique_lock<std::mutex> lock(q_mutex);
while (!is_not_full()) {
if (wb == WriteReturn) return;
q_not_full.wait(lock);
}
queue.push_front(std::move(item));
lock.unlock();
q_not_empty.notify_one();
}
//! Pops an element from the back of the queue: moves the element to `*pItem`.
void pop_back(T* pItem) {
std::unique_lock<std::mutex> lock(q_mutex);
while (!is_not_empty())
q_not_empty.wait(lock);
*pItem = std::move(queue.back());
queue.pop_back();
lock.unlock();
q_not_full.notify_one();
}
//! Get queue occupancy
size_t size() const {
std::unique_lock<std::mutex> lock(q_mutex);
return queue.size();
}
//! Change the capacity of the queue
void set_capacity(const size_t c) {
// change capacity but does not discard elements
std::unique_lock<std::mutex> lock(q_mutex);
capacity = c;
}
//! Deleted copy constructor
Queue(const Queue &) = delete;
//! Deleted copy assignment operator
Queue &operator =(const Queue &) = delete;
//! Deleted move constructor (class includes mutex)
Queue(Queue &&) = delete;
//! Deleted move assignment operator (class includes mutex)
Queue &&operator =(Queue &&) = delete;
private:
bool is_not_empty() const { return queue.size() > 0; }
bool is_not_full() const { return queue.size() < capacity; }
size_t capacity;
std::deque<T> queue;
WriteBehavior wb;
ReadBehavior rb;
mutable std::mutex q_mutex;
mutable std::condition_variable q_not_empty;
mutable std::condition_variable q_not_full;
};
} // namespace bm
#endif // BM_BM_SIM_QUEUE_H_
|
85c37a3ccb110dc3a682cc57c69074dea52b4757
|
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
|
/main/source/src/core/scoring/rna/chemical_shift/RNA_ChemicalShiftEnergy.cc
|
228eb58d041a47dbaceb95c2078d2dda54177d1c
|
[] |
no_license
|
MedicaicloudLink/Rosetta
|
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
|
01affdf77abb773ed375b83cdbbf58439edd8719
|
refs/heads/master
| 2020-12-07T17:52:01.350906
| 2020-01-10T08:24:09
| 2020-01-10T08:24:09
| 232,757,729
| 2
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,088
|
cc
|
RNA_ChemicalShiftEnergy.cc
|
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file core/scoring/rna/chemical_shift/RNA_ChemicalShiftEnergy.cc
/// @brief Energy score based on the agreement between experimentally determined and theoretically calculated NMR chemical_shift
/// @author Parin Sripakdeevong (sripakpa@stanford.edu)
// Unit headers
#include <core/scoring/rna/chemical_shift/RNA_ChemicalShiftEnergy.hh>
#include <core/scoring/rna/chemical_shift/RNA_ChemicalShiftEnergyCreator.hh>
#include <core/scoring/ScoringManager.hh>
// Project headers
#include <core/pose/Pose.hh>
#include <core/conformation/Residue.hh>
#include <core/conformation/Atom.hh>
// Utility headers
//Auto Headers
#include <core/id/AtomID.hh>
#include <core/scoring/EnergyMap.hh>
////////////////////////////////////////////////////////
// C++
namespace core {
namespace scoring {
namespace rna {
namespace chemical_shift {
/// @details This must return a fresh instance of the RNA_ChemicalShiftEnergy class,
/// never an instance already in use
methods::EnergyMethodOP
RNA_ChemicalShiftEnergyCreator::create_energy_method(
methods::EnergyMethodOptions const &
) const {
return utility::pointer::make_shared< RNA_ChemicalShiftEnergy >();
}
ScoreTypes
RNA_ChemicalShiftEnergyCreator::score_types_for_method() const {
ScoreTypes sts;
sts.push_back( rna_chem_shift );
return sts;
}
/// c-tor
RNA_ChemicalShiftEnergy::RNA_ChemicalShiftEnergy():
parent( utility::pointer::make_shared< RNA_ChemicalShiftEnergyCreator >() ),
rna_chemical_shift_potential_( ScoringManager::get_instance()->get_RNA_ChemicalShiftPotential() )
{}
/// clone
methods::EnergyMethodOP
RNA_ChemicalShiftEnergy::clone() const
{
return utility::pointer::make_shared< RNA_ChemicalShiftEnergy >();
}
/////////////////////////////////////////////////////////////////////////////
// scoring
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
void
RNA_ChemicalShiftEnergy::setup_for_scoring( pose::Pose &, ScoreFunction const & ) const
{
//MIGHT BENEFIT FROM SOME BOOKKEEPING such as MAPPING atom_namerealatomdata_index/ to atom_index for fast look-up;
}
/////////////////////////////////////////////////////////////////////////////
void
RNA_ChemicalShiftEnergy::setup_for_derivatives( pose::Pose &, ScoreFunction const & ) const
{
//MIGHT BENEFIT FROM SOME BOOKKEEPING such as MAPPING atom_namerealatomdata_index/ to atom_index for fast look-up;
//or precalculate the calc_chem_shift values of the atoms with CS_data
//this assumes that the pose conformation does change between the call to setup_for_derivative() and the calls to eval_atom_derivative()
}
///////////////////////////////////////////////////////////////////////////////
void
RNA_ChemicalShiftEnergy::finalize_total_energy(
pose::Pose & pose,
ScoreFunction const &,
EnergyMap & totals
) const {
rna_chemical_shift_potential_.finalize_total_energy( pose, totals );
} // finalize_total_energy
///////////////////////////////////////////////////////////////////////////////
void
RNA_ChemicalShiftEnergy::eval_atom_derivative(
id::AtomID const & atom_id,
pose::Pose const & pose,
kinematics::DomainMap const & domain_map,
ScoreFunction const &,
EnergyMap const & weights,
Vector & F1,
Vector & F2
) const
{
rna_chemical_shift_potential_.eval_atom_derivative( atom_id, pose, domain_map, weights, F1, F2 );
} // eval atom derivative
core::Size
RNA_ChemicalShiftEnergy::version() const
{
return 1; // Initial versioning
}
} //chemical_shift
} //rna
} //scoring
} //core
|
f6e945fefff452c64d9eff9d52e1cbbd8b730475
|
6d8adaaa4d85dfb33f903770d7e5a8ef4c60773f
|
/MOOS_Aug2322/MOOSCore/Core/libMOOS/Comms/EndToEndAudit.cpp
|
23e20508822a483e5d432d26ceaf3112ee8397c1
|
[] |
no_license
|
moos-ivp/svn-mirror
|
3509614f054dbc9d2ecc19d503b3f20298138f66
|
d537fa58f7891688bb64220e35c267ae6ef4f476
|
refs/heads/master
| 2023-06-25T15:10:16.009010
| 2023-06-14T12:45:58
| 2023-06-14T12:45:58
| 82,476,527
| 6
| 9
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,826
|
cpp
|
EndToEndAudit.cpp
|
#include "MOOS/libMOOS/Comms/EndToEndAudit.h"
///////////////////////////////////////////////////////////////////////////
//
// This file is part of the MOOS project
//
// MOOS : Mission Oriented Operating Suite A suit of
// Applications and Libraries for Mobile Robotics Research
// Copyright (C) Paul Newman
//
// This software was written by Paul Newman at MIT 2001-2002 and
// the University of Oxford 2003-2013
//
// email: pnewman@robots.ox.ac.uk.
//
// This source code and the accompanying materials
// are made available under the terms of the GNU Lesser Public License v2.1
// which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl.txt 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.
//
////////////////////////////////////////////////////////////////////////////
namespace MOOS{
static const std::string kDefaultEndToEndAuditMulticastChannel = "224.1.1.8";
static const int kDefaultEndToEndAuditMulticastPort = 4000;
void EndToEndAudit::MessageStatistic::ToString(std::string & out){
MOOSAddValToString(out,"src",source_client);
MOOSAddValToString(out,"dest",destination_client);
MOOSAddValToString(out,"name",message_name);
MOOSAddValToString(out,"size",message_size);
MOOSAddValToString(out,"tx",source_time);
MOOSAddValToString(out,"rx",receive_time);
MOOSAddValToString(out,"load",cpu_load);
}
void EndToEndAudit::MessageStatistic::FromString(const std::string & in){
MOOSValFromString(source_client,in,"src");
MOOSValFromString(destination_client,in,"dest");
MOOSValFromString(message_name,in,"name");
MOOSValFromString(message_size,in,"size");
MOOSValFromString(source_time,in,"tx");
MOOSValFromString(receive_time,in,"rx");
MOOSValFromString(cpu_load,in,"load");
}
/**************************************************************************/
EndToEndAudit::EndToEndAudit(){
}
/**************************************************************************/
void EndToEndAudit::Start(){
multicaster_.Configure(kDefaultEndToEndAuditMulticastChannel,
kDefaultEndToEndAuditMulticastPort);
multicaster_.Run(true,false);
transmit_thread_.Initialise(ThreadDispatch,this);
transmit_thread_.Start();
}
/**************************************************************************/
void EndToEndAudit::AddForAudit(const CMOOSMsg & msg,
const std::string & client_name,
double time_now){
MessageStatistic ms;
ms.source_client = msg.GetSource();
ms.destination_client =client_name;
ms.receive_time = int64_t(time_now*1e6);
ms.source_time = int64_t(msg.GetTime()*1e6);
ms.message_name = msg.GetKey();
ms.message_size=msg.GetSizeInBytesWhenSerialised();
proc_info_.GetPercentageCPULoad(ms.cpu_load);
MOOS::ScopedLock lock(audit_lock_);
message_statistics_.push_back(ms);
}
/**************************************************************************/
bool EndToEndAudit::TransmitWorker(){
while(!transmit_thread_.IsQuitRequested()){
MOOSPause(1000);
MessageStatistics message_stats_to_send;
{
MOOS::ScopedLock lock(audit_lock_);
message_stats_to_send.swap(message_statistics_);
}
if(message_stats_to_send.empty()){
continue;
}
MessageStatistics::iterator q;
for(q = message_stats_to_send.begin();
q!=message_stats_to_send.end();
++q){
std::string message;
q->ToString(message);
multicaster_.Write(message);
}
}
return true;
}
}
|
a6240d9f2ecfee708072ab438d6ee89a963cedbc
|
437af6dbbcd4d4150575803173abd3603e824064
|
/02-24/1/ac/ethan.cpp
|
b10873a910465cc346b9140cf89270caae4bee7d
|
[] |
no_license
|
masonsbro/spring-2017-contests-solutions
|
7aead43b0646c86aecfe5071df504a2d6505c3dd
|
7b071514f59333d817f93465cb92c1676a3356d1
|
refs/heads/master
| 2021-01-22T05:10:18.115948
| 2017-02-26T02:10:46
| 2017-02-26T02:10:46
| 81,625,115
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 398
|
cpp
|
ethan.cpp
|
#include <cstdio>
#include <cassert>
using namespace std;
int t, c, g;
int main() {
scanf(" %d", &t);
assert(1 <= t && t <= 100);
for (int q = 0; q < t; q++) {
scanf(" %d %d", &c, &g);
assert(c != g);
assert(1 <= c && c <= 1000);
assert(1 <= g && g <= 1000);
if (c < g) printf("RIGHT\n");
else printf("LEFT\n");
}
return 0;
}
|
a93aea9ca98c57003300077d477fb31145a44d8f
|
353c425bb93fa21fead24c5c6766a017289ccbea
|
/leimoban2/leimoban2/类模板与继承.cpp
|
4cee5f4f3c6ee356252ed256c74a7467c4ca3c6a
|
[] |
no_license
|
kass31415926/Play
|
7b51ddd9b0657e6f53833f0569ceff117cca2029
|
9f7a92d79127513e72bd799220593e99fd0c3be5
|
refs/heads/master
| 2023-06-24T03:50:42.819532
| 2021-07-22T10:30:27
| 2021-07-22T10:30:27
| 347,595,022
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 491
|
cpp
|
类模板与继承.cpp
|
//#include <iostream>
//using namespace std;
//#include <string>
//
////类模板与继承
////
//
//
//template<class T>
//class Base
//{
//public:
//
// T m;
//};
//
//
////class Son :public Base//需要知道父类中的T的类型
//class Son:public Base<int>
//{
//
//};
//
//void test01()
//{
// Son s1;
//}
//
//template<class T1,class T2>
//class Son2 :public Base<T2>
//{
// T1 obj;
//};
//
//void test02()
//{
// Son2<int, char>S2;
//}
//int main()
//{
// test01();
// return 0;
//}
|
00209e2242fc520a2ff336fae04b2211b74b0b88
|
9e778aec516e3faaf9f7b926f49298a900cdff54
|
/Platform Game/Motor2D/GUI_Logo.cpp
|
b87051da7bdbff43e2cb041565ba02e4f28d2e5f
|
[
"MIT"
] |
permissive
|
Sebi-Lopez/DevGame
|
a6e1795b7c7fd3340800639b97a266996b880f54
|
03ea048fcf1f60816c621d24ab08828a71d7d737
|
refs/heads/master
| 2020-03-31T02:44:08.014203
| 2018-12-23T22:52:11
| 2018-12-23T22:52:11
| 151,837,836
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 357
|
cpp
|
GUI_Logo.cpp
|
#include "GUI_Logo.h"
#include "SDL/include/SDL_rect.h"
#include "j1GUI.h"
#include "j1App.h"
#include"j1Textures.h"
GUI_Logo::GUI_Logo(int x, int y, SDL_Rect& atlasrect, GUI_Object* parent) : GUI_Object(x, y, parent)
{
position.x = x;
position.y = y;
section = atlasrect;
}
GUI_Logo::~GUI_Logo() {
App->tex->UnLoad(texture);
texture = nullptr;
}
|
0a22ad71bf056dbb3eeeb9ed81c11063829bb878
|
59bb7cd19de46a5402198d9f69c88bc39e0c13a4
|
/gyro_code (1).ino
|
582653e73d29a7e46b9dd1a648c61c6564690dea
|
[] |
no_license
|
FENIL2909/one_dimensional_flight_controller
|
955b1b18a7938ae9b518d191f9b6d0495e15bfdf
|
06cdfbaab6ffe89a76355eea3bf5bc19994728d1
|
refs/heads/master
| 2020-03-27T09:11:27.005009
| 2018-08-27T16:00:55
| 2018-08-27T16:00:55
| 146,320,484
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,801
|
ino
|
gyro_code (1).ino
|
#include <Wire.h>
#include <Servo.h>
//for taking raw values from accelerometer:
double raw_accel_x, raw_accel_y, raw_accel_z;
//corrected values:
double gforce_x, gforce_y, gforce_z;
//for taking raw values from gyro:
double raw_gyro_x,raw_gyro_y,raw_gyro_z;
//for corrected values:
double rot_x, rot_y, rot_z;
// variables for PID data
double p_error, i_error, d_error, current_value, set_value=0.0, total_value,kp, ki, kd, pid_error, last_p_error;
Servo left_motor, right_motor;
void setup() {
// put your setup code here, to run once:
wire.begin();
wire.beginTransmission();
serial.begin(9600);
MPUsetup();
left_motor.attach(D10); //assigning pins to the BLDc motor...
right_motor.attach(D11);
}
void loop() {
//I2C address of MPU6050:
wire.begin(0b110100);
//data register reading data from accelerometer:
wire.write(0x3B);
wire.endTransmission();
wire.requestFrom(0b1101000,6)
while(wire.available()<=6)
{
// reading data from the registers byte by byte as the data is 16 bit long so taking 8 bits at a time:
raw_accel_x=wire.read()<<8|wire.read();
raw_accel_y=wire.read()<<8|wire.read();
raw_accel_z=wire.read()<<8|wire.read();
}
gforce_x=raw_accel_x/16384.0; //converting raw data into meaningful:
gforce_y=raw_accel_y/16384.0;
gforce_z=raw_accel_z/16384.0;
Serial.println("Accelerometer Data");
Serial.print("X axis");
Serial.print(gforce_X);
Serial.print("Y axis");
Serial.print(gforce_Y);
Serial.print("Z axis");
Serial.print(gforce_Z);
// put your main code here, to run repeatedly:
//I2C address of MPU6050:
wire.begin(0b110100);
//data register reading data from accelerometer:
wire.write(0x43);
wire.endTransmission();
wire.requestFrom(0b1101000,6)
while(wire.available()<=6)
{
raw_gyro_x=wire.read()<<8|wire.read();
raw_gyro_y=wire.read()<<8|wire.read();
raw_gyro_z=wire.read()<<8|wire.read();
}
rot_gyro_x=raw_gyro_x/131.0; //finding angular velocity from raw data:
rot_gyro_y=raw_gyro_y/131.0;
rot_gyro_z=raw_gyro_z/131.0;
Serial.println("Gyro Data");
Serial.print("X axis");
Serial.print(rot_gyro_x);
Serial.print("Y axis");
Serial.print(rot_gyro_Y);
Serial.print("Z axis");
Serial.print(rot_gyro_Z);
pid_error = PIDData();
pid_error = map(pid_error,value1, value2, -500, 500); // value 1 and value 2 can be infered from the readings we are getting from the gyro and accelerometer through the serial monitor.
// initially assuming pid_error to be positive when tilted in the right hand side direction.....
left_motor = writeMicroseconds(1500-pid_error);
right_motor = writeMicroseconds(1500+pid_error);
}
void MPUsetup()
{
//power:
wire.begin(0b1101000);
wire.write(0x6B);
wire.write(0b0000000);
wire.endTransmission();
//gyro:
wire.begin(0b1101000);
wire.write(0x1B);
wire.write(0b0000000);
wire.endTransmission();
//accelerometer:
wire.begin(0b1101000);
wire.write(0x1C);
wire.write(0b0000000);
wire.endTransmission();
}
double PIDData(){
p_error = current_value - set_value; // current value can be obtained from the calculations of angles from data obtained from MPU 6050...
i_error = p_error + last_p_error;
d_error = p_error - last_p_error;
last_p_error = p_error;
total_value = kp*p_error + ki*i_error + kd*d_error; // calculating total error for PID...
Serial.print(total_value);
return total_value;
}
|
8691e5e8d8d1230d3f98ad5fa1e27a585d6eb20a
|
316d364b4be050ba1f04c4079ad5db49e61bf234
|
/ISO15765Proxy/iso15765.h
|
8cd00c3285de2c36151cdbe79a414eb40fb2f289
|
[] |
no_license
|
diorcety/j2534-tools
|
a49d4f53c1a807b8fe830f0bb39907b59fed9a3e
|
1ba06377ef1e889ec3dbee8f98dda92f24e82f1e
|
refs/heads/master
| 2021-01-17T18:09:11.869420
| 2016-08-15T14:24:14
| 2016-08-15T14:24:14
| 65,738,110
| 8
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,485
|
h
|
iso15765.h
|
#pragma once
#ifndef __ISO15765_H
#define __ISO15765_H
#include "internal.h"
#include "configurable_channel.h"
#include <list>
DEFINE_SHARED(TransferISO15765)
DEFINE_SHARED(MessageFilterISO15765)
DEFINE_SHARED(ChannelISO15765)
DEFINE_SHARED(DeviceISO15765)
DEFINE_SHARED(LibraryISO15765)
class LibraryISO15765: public Library {
public:
LibraryISO15765(const LibraryPtr &library);
virtual ~LibraryISO15765();
virtual DevicePtr open(void *pName) override;
virtual void close(const DevicePtr &devicePtr) override;
virtual void getLastError(char *pErrorDescription) override;
protected:
std::list<DevicePtr> mDevices;
LibraryPtr mLibrary;
};
class DeviceISO15765: public Device {
friend class LibraryISO15765;
public:
DeviceISO15765(const LibraryISO15765Ptr &library, const DevicePtr &device);
virtual ~DeviceISO15765();
virtual ChannelPtr connect(unsigned long ProtocolID, unsigned long Flags, unsigned long BaudRate) override;
virtual void disconnect(const ChannelPtr &channelPtr) override;
virtual void setProgrammingVoltage(unsigned long PinNumber, unsigned long Voltage) override;
virtual void readVersion(char *pFirmwareVersion, char *pDllVersion, char *pApiVersion) override;
virtual void ioctl(unsigned long IoctlID, void *pInput, void *pOutput) override;
virtual LibraryWeakPtr getLibrary() const override;
protected:
LibraryISO15765WeakPtr mLibrary;
std::list<ChannelPtr> mChannels;
DevicePtr mDevice;
};
class ChannelISO15765: public ConfigurableChannel {
friend class TransferISO15765;
friend class DeviceISO15765;
public:
ChannelISO15765(unsigned long protocolId, const DeviceISO15765Ptr &device, const ChannelPtr &channel);
virtual ~ChannelISO15765();
virtual MessageFilterPtr startMsgFilter(unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg,
PASSTHRU_MSG *pFlowControlMsg) override;
virtual void stopMsgFilter(const MessageFilterPtr &messageFilter) override;
virtual void readMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) override;
virtual void writeMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) override;
virtual PeriodicMessagePtr startPeriodicMsg(PASSTHRU_MSG *pMsg, unsigned long TimeInterval) override;
virtual void stopPeriodicMsg(const PeriodicMessagePtr &periodicMessage) override;
virtual DeviceWeakPtr getDevice() const override;
protected:
virtual bool getConfig(SCONFIG *config) const override;
virtual bool setConfig(SCONFIG *config) override;
virtual bool clearTxBuffers() override;
virtual bool clearRxBuffers() override;
virtual bool clearPeriodicMessages() override;
virtual bool clearMessageFilters() override;
virtual bool handle_ioctl(unsigned long IoctlID, void *pInput, void *pOutput) override;
virtual void ioctl(unsigned long IoctlID, void *pInput, void *pOutput) override;
TransferISO15765Ptr getTransferByFlowControl(const PASSTHRU_MSG &msg);
TransferISO15765Ptr getTransferByPattern(const PASSTHRU_MSG &msg);
protected:
unsigned long mProtocolId;
DeviceISO15765WeakPtr mDevice;
std::list<MessageFilterPtr> mMessageFilters;
ChannelPtr mChannel;
};
class TransferISO15765 {
public:
TransferISO15765(Configuration &configuration, Channel &channel, const PASSTHRU_MSG &pMaskMsg, const PASSTHRU_MSG &pPatternMsg, const PASSTHRU_MSG &pFlowControlMsg);
~TransferISO15765();
void clear();
bool writeMsg(const PASSTHRU_MSG &msg, unsigned long Timeout);
bool readMsg(const PASSTHRU_MSG &in_msg, PASSTHRU_MSG &out_msg, unsigned long Timeout);
uint32_t getMaskPid();
uint32_t getPatternPid();
uint32_t getFlowControlPid();
private:
enum TransferState {
START_STATE = 0,
FLOW_CONTROL_STATE,
BLOCK_STATE
};
enum PCIFrameName {
SingleFrame = 0,
FirstFrame,
ConsecutiveFrame,
FlowControl,
UnknownFrame
};
static PCIFrameName getFrameName(uint8_t pci);
static uint8_t getPci(PCIFrameName frameName);
static size_t getRemainingSize(const PASSTHRU_MSG &msg, off_t offset);
static void prepareSentMessageHeaders(PASSTHRU_MSG &out_msg, const PASSTHRU_MSG &in_msg);
static void prepareReceivedMessageHeaders(PASSTHRU_MSG &out_msg, const PASSTHRU_MSG &in_msg);
static void paddingMessage(PASSTHRU_MSG &smsg);
bool sendFlowControlMessage(unsigned long Timeout);
Configuration &mChannelConfiguration;
Channel &mChannel;
uint32_t mMaskPid;
uint32_t mPatternPid;
uint32_t mFlowControlPid;
unsigned long mBs;
unsigned long mStmin;
unsigned int mSequence;
PASSTHRU_MSG mMessage;
TransferState mState;
off_t mOffset;
};
class MessageFilterISO15765: public MessageFilter {
friend class ChannelISO15765;
public:
MessageFilterISO15765(const ChannelISO15765Ptr &channel, const MessageFilterPtr &messageFilter, const TransferISO15765Ptr &transfer);
virtual ~MessageFilterISO15765();
virtual ChannelWeakPtr getChannel() const override;
virtual TransferISO15765Ptr& getTransfer();
private:
ChannelISO15765WeakPtr mChannel;
TransferISO15765Ptr mTransfer;
MessageFilterPtr mMessageFilter;
};
#endif //__ISO15765_H
|
5747c5cebeb587663eb3b973be8cbc2a53534337
|
303e4568e29ede8059e3a5d61124246baaf5bdc6
|
/kja_main.ino
|
6460be10590eaf5f51a47088909597d0e0bafcfc
|
[] |
no_license
|
onuryunus/kja
|
f006f3914750d843bb13b33ef70bc30af29fdccc
|
2a08434cfce2695e568ef32b99551db4370c79a3
|
refs/heads/master
| 2020-03-15T04:01:56.712338
| 2018-06-01T08:44:37
| 2018-06-01T08:44:37
| 131,955,970
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,435
|
ino
|
kja_main.ino
|
#include <EEPROM.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include <ADXL345dual.h>
#include <Wire.h>
File myFile;
ADXL345 device;
String fileName = String();
const int rxpin = 7;
const int txpin = 6;
char k = 'A';
unsigned int filenumber;
SoftwareSerial bluetooth(rxpin, txpin);
int Sdo = 9;
int Cs = 8;
int Button_start = 2 ;
int Button_stop = 4 ;
int Button_bluetooth = 3;
int buzzer = 5;
int firstsensor = 0;
int secondsensor = 1;
volatile bool recycle;
char inputString [100];
char inputChar;
int stringIndex = 0;
void setup()
{
recycle = false;
pinMode(Cs, OUTPUT);
pinMode(6, OUTPUT);
pinMode(buzzer, OUTPUT);
digitalWrite(Cs, HIGH);
pinMode(Sdo, OUTPUT);
digitalWrite(Sdo, HIGH);
pinMode(Button_start, INPUT_PULLUP);
pinMode(Button_stop, INPUT_PULLUP);
pinMode(Button_bluetooth, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("SD kart yukleniyor.");
if (!SD.begin(10)) {
Serial.println("Yukleme basarisiz!");
while (1);
}
Serial.println("SD kart yukleme basarılı.");
bluetooth.begin(115200);
device.begin(firstsensor);
device.setDataRate(firstsensor, ADXL345_DATARATE_200HZ);
device.setRange(firstsensor, ADXL345_RANGE_2G);
device.begin(secondsensor);
device.setDataRate(secondsensor, ADXL345_DATARATE_200HZ);
device.setRange(secondsensor, ADXL345_RANGE_2G);
}
void loop() {
if (!digitalRead(Button_start))
{
recycle = true;
delay(10);
initSD();
delay(10);
myFile = SD.open(fileName, FILE_WRITE);
beep();
}
if (!digitalRead(Button_stop))
{
recycle = false;
delay(10);
myFile.close();
beep();
}
if (!digitalRead(Button_bluetooth))
{
recycle = false;
beep();
unsigned long start;
start = millis();
while (( millis() - start) < 30000)
{
if (bluetooth.available())
{
k = bluetooth.read();
if ( k == 'H' )
{
EEPROM.get(0, filenumber);
fileName = "Ex_";
fileName += filenumber;
fileName += ".txt";
Serial.println("Sending...");
myFile = SD.open(fileName);
if (myFile)
{
while (myFile.available())
{
bluetooth.write(myFile.read() );
delay(1);
}
myFile.close();
}
Serial.print('T');
}
}
else
Serial.println("No DATA");
delay(1);
}
Serial.print("TIME OUT");
}
if (recycle)
{
if (myFile)
{
char data[32];
Vector raw1 = device.readRaw(firstsensor);
Vector raw2 = device.readRaw(secondsensor);
sprintf(data, "%d,%d,%d,%d,%d,%d", int(raw1.XAxis), int(raw1.YAxis), int(raw1.ZAxis), int(raw2.XAxis), int(raw2.YAxis), int(raw2.ZAxis));
Serial.println(data);
myFile.println(data);
delay(10);
}
else {
Serial.println("error opening test.txt");
}
}
}
void initSD()
{
unsigned int filenumber = 1;
while (!filenumber == 0) {
fileName = "Ex_";
fileName += filenumber;
fileName += ".txt";
while (SD.exists(fileName)) {
filenumber++;
fileName = "Ex_";
fileName += filenumber;
fileName += ".txt";
}
EEPROM.put(0, filenumber);
myFile = SD.open(fileName, FILE_WRITE);
myFile.close();
return;
}
}
void beep()
{
digitalWrite(buzzer, HIGH);
delay(100);
digitalWrite(buzzer, LOW);
}
|
0ef229df46a9b7f7a262bb4b0582650298ee7eaf
|
d871ce70c7c3c8d58dbd90f9abbbc68e2c986e39
|
/TodoWindow.h
|
7ac12ff61429bf0633193f81c2e8b0a4bc4fbbfc
|
[] |
no_license
|
gidzzz/qalendar
|
28dd4f677ec218b4b0352cf68a82c01d8c8cc807
|
5a6c75bf6919e94a0aa664f5468bce8fe2032a4c
|
refs/heads/master
| 2020-12-24T15:49:43.176869
| 2015-07-30T20:58:12
| 2015-07-30T20:58:12
| 37,643,821
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 625
|
h
|
TodoWindow.h
|
#ifndef TODOWINDOW_H
#define TODOWINDOW_H
#include "ui_TodoWindow.h"
#include <CTodo.h>
#include "ChangeClient.h"
class TodoWindow : public QMainWindow, public ChangeClient
{
Q_OBJECT
public:
TodoWindow(CTodo *todo, QWidget *parent);
~TodoWindow();
void onChange();
private:
Ui::TodoWindow *ui;
CTodo *todo;
void reload();
void changeEvent(QEvent *e);
void contextMenuEvent(QContextMenuEvent *e);
void closeEvent(QCloseEvent *e);
private slots:
void editTodo();
void cloneTodo();
void deleteTodo();
void enableLinks(bool enable);
};
#endif // TODOWINDOW_H
|
f2c284cf1d28be4c88439e8aa73139b616eacb2f
|
3e8fea939b969905d058ef9584ad83dcc3b2e391
|
/client/src/gui/gfx/PlayerDrawable.cpp
|
383c22bbf674bdceaebc2cabeb5654d7e765da6a
|
[] |
no_license
|
NiceTwice/rtype
|
2a508dc4ccba0e229435cfdbaa40845dd71bf3f1
|
6a5f2a13955e6d8e90ad70156efa5f6dd6d50225
|
refs/heads/master
| 2020-03-20T00:52:36.997634
| 2018-06-12T12:59:31
| 2018-06-12T12:59:31
| 137,059,091
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,918
|
cpp
|
PlayerDrawable.cpp
|
//
// PlayerDrawable.cpp for rtype in /home/lanquemar/rendu/rtype
//
// Made by Adrien Vasseur
// Login <adrien.vasseur@epitech.eu>
//
// Started on Wed Dec 28 17:54:04 2016 Adrien Vasseur
// Last update Wed Dec 28 17:54:04 2016 Adrien Vasseur
//
#include <tools/Chrono.hpp>
#include <gui/MainWindow.hpp>
#include "gui/gfx/PlayerDrawable.hpp"
#include "gui/res/ResPool.hpp"
PlayerDrawable::PlayerDrawable(MovableEntity *entity) : ADrawable(entity)
{
}
PlayerDrawable::PlayerDrawable() : ADrawable(nullptr)
{
}
PlayerDrawable::~PlayerDrawable()
{
}
bool PlayerDrawable::create()
{
if (ResPool::getInstance().getImage("ship-0x" + std::to_string(this->_entity->getSprite())) != NULL &&
ResPool::getInstance().getImage("ship-1x" + std::to_string(this->_entity->getSprite())) != NULL &&
ResPool::getInstance().getImage("ship-2x" + std::to_string(this->_entity->getSprite())) != NULL &&
ResPool::getInstance().getImage("ship-3x" + std::to_string(this->_entity->getSprite())) != NULL &&
ResPool::getInstance().getImage("ship-4x" + std::to_string(this->_entity->getSprite())) != NULL &&
ResPool::getInstance().getImage("explosion-0x0") != NULL &&
ResPool::getInstance().getImage("explosion-1x0") != NULL &&
ResPool::getInstance().getImage("explosion-2x0") != NULL &&
ResPool::getInstance().getImage("explosion-3x0") != NULL &&
ResPool::getInstance().getImage("explosion-4x0") != NULL &&
ResPool::getInstance().getImage("explosion-5x0") != NULL &&
ResPool::getInstance().getImage("explosion-6x0") != NULL)
{
this->_downAnimation.addFrame(ResPool::getInstance().getImage("ship-2x" + std::to_string(this->_entity->getSprite())));
this->_downAnimation.addFrame(ResPool::getInstance().getImage("ship-1x" + std::to_string(this->_entity->getSprite())));
this->_downAnimation.addFrame(ResPool::getInstance().getImage("ship-0x" + std::to_string(this->_entity->getSprite())));
this->_downAnimation.setRepeated(false);
this->_downAnimation.setInterval(200);
this->_upAnimation.addFrame(ResPool::getInstance().getImage("ship-2x" + std::to_string(this->_entity->getSprite())));
this->_upAnimation.addFrame(ResPool::getInstance().getImage("ship-3x" + std::to_string(this->_entity->getSprite())));
this->_upAnimation.addFrame(ResPool::getInstance().getImage("ship-4x" + std::to_string(this->_entity->getSprite())));
this->_upAnimation.setRepeated(false);
this->_upAnimation.setInterval(200);
this->_aliveAnimation.setImage(ResPool::getInstance().getImage("ship-2x" + std::to_string(this->_entity->getSprite())));
this->_aliveAnimation.setInterval(500);
this->_aliveAnimation.setRepeated(true);
this->_deadAnimation.addFrame(ResPool::getInstance().getImage("explosion-0x0"));
this->_deadAnimation.addFrame(ResPool::getInstance().getImage("explosion-1x0"));
this->_deadAnimation.addFrame(ResPool::getInstance().getImage("explosion-2x0"));
this->_deadAnimation.addFrame(ResPool::getInstance().getImage("explosion-3x0"));
this->_deadAnimation.addFrame(ResPool::getInstance().getImage("explosion-4x0"));
this->_deadAnimation.addFrame(ResPool::getInstance().getImage("explosion-5x0"));
this->_deadAnimation.addFrame(ResPool::getInstance().getImage("explosion-6x0"));
this->_deadAnimation.setRepeated(false);
this->_deadAnimation.setInterval(100);
this->_normalMode = ResPool::getInstance().getImage("ship-2x" + std::to_string(this->_entity->getSprite()));
}
this->_creationDate = Chrono::getCurrentTime();
return (true);
}
void PlayerDrawable::viewportCollision(Vector2f &vec) const
{
if (vec.getX() < 0)
vec.setX(0);
if (vec.getY() < 0)
vec.setY(0);
if (vec.getX() > MainWindow::getInstance().getWidth() - this->_normalMode->getSize().getX())
vec.setX(MainWindow::getInstance().getWidth() - this->_normalMode->getSize().getX());
if (vec.getY() > MainWindow::getInstance().getHeight() - this->_normalMode->getSize().getY())
vec.setY(MainWindow::getInstance().getHeight() - this->_normalMode->getSize().getY());
}
void PlayerDrawable::display()
{
Vector2f newPos;
if (Chrono::getDiffTime(this->_entity->getLastUpdate()) < DEATH_TIMEOUT)
{
newPos = this->_entity->getPosition() + this->_entity->getDir() * this->_entity->getVelocity() * Chrono::getDiffTime(this->_entity->getLastUpdate());
viewportCollision(newPos);
if (Chrono::getDiffTime(this->_creationDate) < 3000)
{
if (!this->_aliveAnimation.isRunning())
this->_aliveAnimation.start();
this->_aliveAnimation.setPosition(newPos);
this->_aliveAnimation.display();
}
else if (this->_entity->getDir().getY() < 0.0f)
{
if (!this->_upAnimation.isRunning())
this->_upAnimation.start();
this->_upAnimation.setPosition(newPos);
this->_upAnimation.display();
this->_downAnimation.stop();
}
else if (this->_entity->getDir().getY() > 0.0f)
{
if (!this->_downAnimation.isRunning())
this->_downAnimation.start();
this->_downAnimation.setPosition(newPos);
this->_downAnimation.display();
this->_upAnimation.stop();
}
else
{
this->_normalMode->setPosition(newPos);
this->_normalMode->display();
this->_upAnimation.stop();
this->_downAnimation.stop();
}
}
else if (Chrono::getDiffTime(this->_entity->getLastUpdate()) < DEATH_TIMEOUT + 650)
{
if (!this->_deadAnimation.isRunning())
this->_deadAnimation.start();
this->_deadAnimation.setPosition(this->_entity->getPosition() + this->_entity->getDir() * this->_entity->getVelocity() * DEATH_TIMEOUT);
this->_deadAnimation.display();
}
else
this->_entity->setDeleted(true);
}
void PlayerDrawable::destroy()
{
}
ADrawable *PlayerDrawable::clone(MovableEntity *entity)
{
return (new PlayerDrawable(entity));
}
|
8286c7427b3b00c245ca82b4e6c36a4e4de212e0
|
3a851c70709912dae1e034380a9f62fcb6927058
|
/Linked Lists/Segregating Even and Odd LL.cpp
|
9f729ba7edd34d6eda1692d35af0cbeec29db1db
|
[] |
no_license
|
talrejamohit03/DataStructuresAndAlgorithms
|
3ee0fc35f8fc75bb4b3cfdf75eaf9875a35fccbc
|
f8d2db7040ed69e85331f489963ae9b7ff7ae5ac
|
refs/heads/main
| 2023-02-18T09:28:29.959585
| 2021-01-21T08:32:55
| 2021-01-21T08:32:55
| 331,559,406
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,800
|
cpp
|
Segregating Even and Odd LL.cpp
|
#include <iostream>
using namespace std;
struct lnode{
int data;
lnode *next;
};
typedef lnode* LPTR;
void inpLL(LPTR &L){
LPTR T;
int n;
cout<<"New Linked List\n";
cout<<"Enter element (-1 to terminate): ";
cin>>n;
while(n!=-1){
LPTR temp;
temp=new(lnode);
temp->data=n;
temp->next=NULL;
if(L==NULL){
L=temp;
T=L;
}else{
T->next=temp;
T=T->next;
}
cout<<"Enter next element (-1 to terminate): ";
cin>>n;
}
}
int main(){
LPTR L1=NULL,T,headE=NULL,TE,TO,headO=NULL,E2;
inpLL(L1);
T=L1;
while(T!=NULL){
if((T->data)%2==0){
if(headE==NULL){
headE=T;
TE=headE;
}
else{
TE->next=T;
TE=TE->next;
}
}else{
if(headO==NULL){
headO=T;
TO=headO;
}
else{
TO->next=T;
TO=TO->next;
}
}
T=T->next;
}
TE->next=headO;
TO->next=NULL;
/*while(E->next!=NULL){
E=E->next;
E2=E2->next;
}
if((L1->data)%2!=0){
LPTR temp=new(lnode);
temp->data=L1->data;
temp->next=NULL;
E->next=temp;
E=E->next;
L1=L1->next;
}
T=L1;
while(T!=E2){
if((T->next->data)%2!=0){
LPTR temp=new(lnode);
temp->data=T->data;
temp->next=NULL;
E->next=temp;
E=E->next;
T->next=T->next->next;
continue;
}
T=T->next;
}*/
while(headE!=NULL){
cout<<headE->data<<" ";
headE=headE->next;
}
return 0;
}
|
e0c22d558b6ab54a4d3a31f83a5c2aa0ccee4d2b
|
cab700fb27171e2cadeefff2aab6d970d8dd9714
|
/VSIPerf/include/ModularAlgorithmBase.h
|
6a83becfa382b0f9edbf84981446aad97ea1e85c
|
[] |
no_license
|
rushioda/Seed_perf
|
a298e38c86afd76bc0e2c59ffe0931e76676b3ec
|
716f4f65233f6e29ddfae879a4e91845fe26db5d
|
refs/heads/main
| 2023-04-08T08:54:06.135237
| 2021-04-18T13:46:30
| 2021-04-18T13:46:30
| 359,153,618
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,135
|
h
|
ModularAlgorithmBase.h
|
#ifndef ModularAlgorithmBase_H
#define ModularAlgorithmBase_H
#include <EventLoop/Algorithm.h>
#include <include/TreeManager.h>
#include <include/ProcessorBase.h>
class TH1;
class ModularAlgorithmBase : public EL::Algorithm
{
public:
int prop_do_selectRegion;
std::string prop_regionName;
std::string prop_outputName;
std::string prop_outputFileName;
protected:
unsigned long m_eventCount; //!
std::map<std::string, TH1*> m_histos; //!
std::unique_ptr<TreeManager> m_treeManager; //!
std::vector< std::unique_ptr<ProcessorBase> > m_processors; //!
void registerVariables();
virtual void initProcessors() {};
public:
// this is a standard constructor
ModularAlgorithmBase();
virtual ~ModularAlgorithmBase() {};
// these are the functions inherited from Algorithm
virtual EL::StatusCode initialize ();
virtual EL::StatusCode execute ();
virtual EL::StatusCode finalize ();
// this is needed to distribute the algorithm to the workers
ClassDef(ModularAlgorithmBase, 1);
};
#endif
|
96b88228e516f5b74d48eac9412fb64abb38eef8
|
58daa687cadfc694190ff26b6733f6397d845e17
|
/9dp/wordBreak.cpp
|
b3d8bbf36df7556fdf60504206bbd97754517ffd
|
[] |
no_license
|
xiaoyongaz/jslintcode
|
d40dcac86b9062b9b0fe9a03fde80abf3ce5aa9a
|
a13f5ddffa44be151d4edb32887a9cdf21dc2cb9
|
refs/heads/master
| 2022-12-09T21:03:35.050902
| 2020-04-20T21:55:16
| 2020-04-20T21:55:16
| 240,986,322
| 0
| 1
| null | 2022-12-06T17:29:13
| 2020-02-17T00:01:37
|
JavaScript
|
UTF-8
|
C++
| false
| false
| 1,575
|
cpp
|
wordBreak.cpp
|
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool wordBreakHelper(string &s, int start, int end, vector<vector<int>> &wordMap, unordered_set<string> &dict){
if(wordMap[start][end] != -1){
return wordMap[start][end] == 1;
}
auto sub = s.substr(start, end-start);
if(dict.find(sub) != dict.end()){
wordMap[start][end] = 1;
return true;
}
for(int i = start + 1; i < end; i++){
auto seek1 = wordBreakHelper(s, start, i, wordMap, dict);
auto seek2 = wordBreakHelper(s, i, end, wordMap, dict);
if(seek1 == 1 && seek2 == 1) {
wordMap[start][end] = 1;
return 1;
}
}
wordMap[start][end] = 0;
return 0;
}
/*
* @param s: A string
* @param dict: A dictionary of words dict
* @return: A boolean
*/
bool wordBreak(string &s, unordered_set<string> &dict) {
if(s.size() == 0) return true;
vector<vector<int>> wordMap;
for(int i = 0; i <= s.size(); i++){
wordMap.push_back({});
for(int j = 0; j <= s.size(); j++){
wordMap[i].push_back(-1);
}
}
auto r = wordBreakHelper(s, 0, s.size(), wordMap, dict);
return r;
}
};
int main(){
Solution sol;
return 0;
}
|
cdc3e573199c994c133e36b4e7ccf23d5764836f
|
5d4f3ccfbea9e92f4cb0907f50e618d728059941
|
/student_details.cpp
|
754a5f4d0d1daaafec38e18726767e168b53edbf
|
[
"MIT"
] |
permissive
|
govind1996/COMPETITIVE-PROGRAMMING
|
b563a369bc76b498e6ab8d0d9a350d8d4216ea57
|
338d5a7026a444a509f65bccfce5eab9c91c5a03
|
refs/heads/master
| 2018-12-22T13:32:17.328655
| 2018-10-03T15:00:45
| 2018-10-03T15:00:45
| 108,137,687
| 2
| 2
|
MIT
| 2018-10-03T15:00:47
| 2017-10-24T14:21:36
|
C++
|
UTF-8
|
C++
| false
| false
| 669
|
cpp
|
student_details.cpp
|
#include<bits/stdc++.h>
using namespace std;
class student
{
string name;
int roll;
string adr;
public:
student(string sname,int sroll,string sadr)
{
name=sname;
roll=sroll;
adr=sadr;
}
~student()
{
cout<<"Student's name is "<<name<<endl;
cout<<"student's roll is "<<roll<<endl;
cout<<"student's address is "<<adr<<endl;
}
};
int main()
{
string name,adr;
int roll;
cout<<"Enter student's name \n";
getline(cin,name);
cout<<"Enter student's address \n";
getline(cin,adr);
cout<<"Enter student's roll \n";
cin>>roll;
student s1(name,roll,adr);
}
|
577490725c4fdf2f14f14de721caa0f4347bddff
|
6d5f2e99ae89e6c59bdafed707f5a5db673dec23
|
/src/misc/readLinesFromFile.cpp
|
486d5f48a05c0e7277beeb8eb8774892df796bc7
|
[
"MIT"
] |
permissive
|
bencabrera/grawitas
|
b633ae1dbbbb3da8a37b61b2cb48c493d7c299d2
|
8eda68846ed283afe70d56d68375525a1140de70
|
refs/heads/master
| 2022-03-27T08:27:16.948509
| 2018-01-19T09:48:37
| 2018-01-19T09:48:37
| 81,924,748
| 7
| 7
|
MIT
| 2022-01-25T18:14:46
| 2017-02-14T08:49:49
|
C++
|
UTF-8
|
C++
| false
| false
| 371
|
cpp
|
readLinesFromFile.cpp
|
#include "readLinesFromFile.h"
#include <boost/algorithm/string/trim.hpp>
std::vector<std::string> read_lines_from_file(std::istream& input)
{
std::vector<std::string> lines;
std::string line;
while(std::getline(input,line))
{
boost::trim(line);
if(!line.empty() && line.front() != '#')
lines.push_back(line);
}
return lines;
}
|
9f93d73df5f7ca2d4277ea3ca24781f2c01d2980
|
67ed6034aa03c89fa11c4d73a2643f999fdca30c
|
/1570_dot_product_sparse_vector.cc
|
f2d8b43f857dfa43854170f4d42a5e80ebc3a62b
|
[] |
no_license
|
yichen-git/leetcode
|
092037624c99fc4d1af3b0b62e03d8bd5a9fe187
|
02f1ad3c869d83b356c60a6e9bddb29d747123dd
|
refs/heads/master
| 2023-01-22T13:18:00.572925
| 2020-11-22T21:31:58
| 2020-11-22T21:31:58
| 177,897,759
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 772
|
cc
|
1570_dot_product_sparse_vector.cc
|
class SparseVector {
public:
map<int, int> omap;
SparseVector(vector<int> &nums) {
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0)
this->omap.insert(make_pair(i, nums[i]));
}
}
// Return the dotProduct of two sparse vectors
int dotProduct(SparseVector& vec) {
int sum = 0;
for (auto it = this->omap.begin(); it != this->omap.end(); it++) {
auto ptr = vec.omap.find(it->first);
if (ptr != vec.omap.end())
sum += it->second * ptr->second;
}
return sum;
}
};
// Your SparseVector object will be instantiated and called as such:
// SparseVector v1(nums1);
// SparseVector v2(nums2);
// int ans = v1.dotProduct(v2);
|
f244a77104c625bc6c33c786c4d57fb4358025d1
|
78a3cc861b46d0385c7efc54ceda9d62818e12a2
|
/include/skland/graphic/font.hpp
|
6a3265bbbb87958774c7a9d7e773a2b4664a7f35
|
[
"Apache-2.0"
] |
permissive
|
zhanggyb/skland
|
90f618ae713996b115170860092703bb2099f348
|
055d91a6830b95d248d407c37a8a2fa20b148efd
|
refs/heads/master
| 2020-06-15T17:17:37.258046
| 2017-11-12T15:04:19
| 2017-11-12T15:04:19
| 75,276,770
| 20
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,404
|
hpp
|
font.hpp
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* 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.
*/
#ifndef SKLAND_GRAPHIC_FONT_HPP_
#define SKLAND_GRAPHIC_FONT_HPP_
#include "../core/types.hpp"
#include "font-style.hpp"
#include "typeface.hpp"
#include <memory>
class SkTypeface;
namespace skland {
namespace graphic {
class Typeface;
/**
* @ingroup graphic
* @brief Text encoding
*/
enum TextEncoding {
kTextEncodingUTF8,
kTextEncodingUTF16,
kTextEncodingUTF32,
kTextEncodingGlyphID
};
/**
* @ingroup graphic
* @brief Font
*/
class Font {
public:
enum Flags {
kFlagEnableAutoHints = 1 << 0,
kFlagEnableByteCodeHints = 1 << 1,
kFlagEmbeddedBitmaps = 1 << 2,
kFlagUseNonlinearMetrics = 1 << 3,
kFlagVertical = 1 << 4,
kFlagGenA8FromLCD = 1 << 5,
kFlagEmbolden = 1 << 6,
kFlagDevKern = 1 << 7
};
enum MaskType {
kMaskBW,
kMaskA8,
kMaskLCD
};
/**
* @brief Create default font
* @param style An enum value of Typeface::Style
* @param size
* @param mask_type
* @param flags
*/
Font(Typeface::Style style = Typeface::kNormal,
float size = 12.f,
MaskType mask_type = kMaskBW,
uint32_t flags = kFlagEnableAutoHints);
Font(const char *family_name,
FontStyle font_style,
float size,
MaskType mask_type = kMaskBW,
uint32_t flags = kFlagEnableAutoHints);
Font(const Typeface &typeface,
float size,
MaskType mask_type = kMaskBW,
uint32_t flags = kFlagEnableAutoHints);
Font(const Typeface &typeface,
float size,
float scale_x,
float skew_x,
MaskType mask_type = kMaskBW,
uint32_t flags = kFlagEnableAutoHints);
Font(const Font &other);
~Font();
Font &operator=(const Font &other);
/**
* @brief Get pointer to the native skia typeface
* @return
*/
SkTypeface *GetSkTypeface() const;
float GetSize() const;
float GetScaleX() const;
float GetSkewX() const;
uint32_t GetFlags() const;
MaskType GetMaskType() const;
bool IsBold() const;
bool IsItalic() const;
bool IsVertical() const;
bool IsEmbolden() const;
bool IsEnableAutoHints() const;
bool IsEnableByteCodeHints() const;
bool IsUseNonLinearMetrics() const;
bool IsDevKern();
int TextToGlyphs(const void *text,
size_t byte_length,
TextEncoding encoding,
GlyphID glyphs[],
int max_glyph_count) const;
int CountText(const void *text, size_t byte_length, TextEncoding encoding) {
return TextToGlyphs(text, byte_length, encoding, nullptr, 0);
}
float MeasureText(const void *text, size_t byte_length, TextEncoding encoding) const;
private:
struct Private;
std::unique_ptr<Private> p_;
};
} // namespace graphic
} // namespace skland
#endif // SKLAND_GRAPHIC_FONT_HPP_
|
f3b1857767be6b79e911ad962095d31c53a88f69
|
1d9e60a377ce2b0b94234e90c3156f212f2a7e9b
|
/4/ListEx/ListExDlg.cpp
|
ec20d5e1a21cfaaed0bfe16954e5e25ff68940e9
|
[] |
no_license
|
seehunter/visual_c-_reff_skill_code
|
fd13ceec2c34bd827f2556638bbc190be46d9b93
|
1a99bd875c32a04cbcc07c785b61270821c58341
|
refs/heads/master
| 2020-04-09T21:28:33.030596
| 2018-12-06T01:59:25
| 2018-12-06T01:59:25
| 160,603,401
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,246
|
cpp
|
ListExDlg.cpp
|
// ListExDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "ListEx.h"
#include "ListExDlg.h"
#include ".\listexdlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CListExDlg 对话框
CListExDlg::CListExDlg(CWnd* pParent /*=NULL*/)
: CDialog(CListExDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CListExDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, m_SourData);
DDX_Control(pDX, IDC_LIST2, m_AimData);
}
BEGIN_MESSAGE_MAP(CListExDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDB_ADD, OnBnClickedAdd)
ON_BN_CLICKED(IDB_DELETE, OnBnClickedDelete)
ON_BN_CLICKED(IDB_CLEAR, OnBnClickedClear)
END_MESSAGE_MAP()
// CListExDlg 消息处理程序
BOOL CListExDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 将\“关于...\”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
m_SourData.AddString("示例一");
m_SourData.AddString("示例二");
m_SourData.AddString("示例三");
m_SourData.AddString("示例四");
m_SourData.AddString("示例五");
m_SourData.AddString("示例六");
m_SourData.AddString("示例七");
m_SourData.AddString("示例八");
m_SourData.SetCurSel(0);
//// TODO: 在此添加额外的初始化代码
return TRUE; // 除非设置了控件的焦点,否则返回 TRUE
}
void CListExDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CListExDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标显示。
HCURSOR CListExDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CListExDlg::OnBnClickedAdd()
{
// TODO: 在此添加控件通知处理程序代码
CString str;
//for (int i = 0; i < m_SourData.GetCount(); i++){
/*if (m_SourData.GetSel(i)){
m_SourData.GetText(i, str);
m_AimData.AddString(str);
}*/
m_SourData.GetText(m_SourData.GetCurSel(), str);
m_AimData.AddString(str);
//}
}
void CListExDlg::OnBnClickedDelete()
{
// TODO: 在此添加控件通知处理程序代码
for (int i = m_AimData.GetCount() - 1; i > -1; i--){
if (m_AimData.GetSel(i)) {
m_AimData.DeleteString(i);
}
}
}
void CListExDlg::OnBnClickedClear()
{
// TODO: 在此添加控件通知处理程序代码
m_AimData.ResetContent();
}
|
889b1bc2e6ba6f2ff94b77eb16d65effa81b8409
|
c7bec767654da14be79942ae694e2f884e797a07
|
/Validation/GEMCosmicMuonStand/interface/gemcrValidation.h
|
25b0a10ab6134e4e5fa2463806707f20cd8810f3
|
[] |
no_license
|
hyunyong/QC8
|
0b880d69834613eba2c9f2dd0ea740bcf7279008
|
432e37364ea8d9505ef2889e5c5b190d051ad265
|
refs/heads/master
| 2020-04-28T03:44:48.693885
| 2019-03-11T07:36:58
| 2019-03-11T07:36:58
| 174,949,365
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,882
|
h
|
gemcrValidation.h
|
#ifndef gemcrValidation_H
#define gemcrValidation_H
#include "Validation/MuonGEMHits/interface/GEMBaseValidation.h"
#include <DataFormats/GEMRecHit/interface/GEMRecHit.h>
#include <DataFormats/GEMRecHit/interface/GEMRecHitCollection.h>
#include <DataFormats/TrackReco/interface/Track.h>
#include <DataFormats/TrackingRecHit/interface/TrackingRecHit.h>
#include "RecoMuon/TrackingTools/interface/MuonServiceProxy.h"
#include "DataFormats/MuonDetId/interface/GEMDetId.h"
#include "Geometry/GEMGeometry/interface/GEMChamber.h"
#include "Geometry/GEMGeometry/interface/GEMGeometry.h"
#include "Geometry/Records/interface/MuonGeometryRecord.h"
#include "RecoMuon/CosmicMuonProducer/interface/CosmicMuonSmoother.h"
#include "TrackingTools/KalmanUpdators/interface/KFUpdator.h"
#include "RecoMuon/TransientTrackingRecHit/interface/MuonTransientTrackingRecHit.h"
#include "RecoMuon/StandAloneTrackFinder/interface/StandAloneMuonSmoother.h"
#include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h"
#include "SimDataFormats/Track/interface/SimTrack.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include <TFile.h>
#include <TTree.h>
class gemcrValidation : public GEMBaseValidation
{
public:
explicit gemcrValidation( const edm::ParameterSet& );
~gemcrValidation();
void bookHistograms(DQMStore::IBooker &, edm::Run const &, edm::EventSetup const &) override;
void analyze(const edm::Event& e, const edm::EventSetup&) override;
int findIndex(GEMDetId id_);
int findVFAT(float x, float a, float b);
const GEMGeometry* initGeometry(edm::EventSetup const & iSetup);
double maxCLS, minCLS,maxRes, trackChi2, trackResY, trackResX, MulSigmaOnWindow;
std::vector<std::string> SuperChamType;
std::vector<double> vecChamType;
bool makeTrack, isMC;
private:
const GEMGeometry* GEMGeometry_;
std::vector<GEMChamber> gemChambers;
int n_ch;
MuonServiceProxy* theService;
CosmicMuonSmoother* theSmoother;
KFUpdator* theUpdator;
edm::EDGetToken InputTagToken_, InputTagToken_RH, InputTagToken_TR, InputTagToken_TS, InputTagToken_TJ, InputTagToken_TI, InputTagToken_TT, InputTagToken_DG, InputTagToken_US;
TH1D *goodVStriggeredEvts;
TH3D *hitsVFATnum;
TH3D *hitsVFATdenom;
TH3D *digiStrips;
TH3D *recHits3D;
TH1D *clusterSize;
TH1D *residualPhi;
TH1D *residualEta;
TH1D *recHitsPerTrack;
TTree *tree;
int run;
int lumi;
int nev;
int nrecHit;
int nTraj;
float trajTheta;
float trajPhi;
float trajX;
float trajY;
float trajZ;
float trajPx;
float trajPy;
float trajPz;
float testTrajHitX[30];
float testTrajHitY[30];
float testTrajHitZ[30];
float confTestHitX[30];
float confTestHitY[30];
float confTestHitZ[30];
int nTrajHit; // number of trajHits
int nTrajRecHit; // number of confirmed trajHits
};
#endif
|
be57877c9a1ddc8a200a3914501b93c21bf15a7d
|
6465889bd2d49d3c6e02146d1fbeaf0edb4d9271
|
/140-Suma de digitos.cpp
|
773edc671667d5d9ba3683da0e2b54ee74905f0a
|
[
"MIT"
] |
permissive
|
MiguelJiRo/Acepta-el-reto
|
aef75839875d49eeea8f84b52a9cc8e82b1c2c4f
|
d34e24be2ba685010c0747bde904803a6b9e4cea
|
refs/heads/master
| 2021-06-25T03:55:32.109208
| 2020-11-18T15:16:36
| 2020-11-18T15:16:36
| 150,131,722
| 2
| 1
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 786
|
cpp
|
140-Suma de digitos.cpp
|
// Miguel Jiménez Rodríguez
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool resuelve();
int resuelveCaso(int num);
int main() {
// Para la entrada por fichero.
/*#ifndef DOMJUDGE
std::ifstream in("casos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf());
#endif*/
while (resuelve());
/*#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif*/
return 0;
}
bool resuelve() {
int num;
cin >> num;
if (num < 0)
return false;
int suma = resuelveCaso(num);
cout << " = " << suma << "\n";
return true;
}
int resuelveCaso(int n) {
int num;
if (n / 10 == 0) {
num = n;
cout << n;
}
else {
num = n % 10 + resuelveCaso(n / 10);
cout << " + " << n % 10;
}
return num;
}
|
696dd230512275a3bed5c95f662ac5c182ef7965
|
a93cf8f695c1d1d97b8d0b9ccec6932c5e499ff8
|
/Cpp/jaewon/solveac_lv3/1764 듣보잡/1764 듣보잡/1764 듣보잡.cpp
|
c8952e46c5b932d9a379a98ddf1b57f52f091a12
|
[] |
no_license
|
tmdwns1101/AlgorithmStudy
|
0abc108a7a73895934da2633998c7a90137d49ea
|
e8ca069e202f40e074b7311626fe8da8af057589
|
refs/heads/master
| 2021-07-22T11:32:30.817108
| 2020-05-20T16:28:27
| 2020-05-20T16:28:27
| 165,377,838
| 0
| 1
| null | 2020-02-07T07:56:16
| 2019-01-12T11:02:59
|
C++
|
UTF-8
|
C++
| false
| false
| 1,415
|
cpp
|
1764 듣보잡.cpp
|
/*
문제
김진영이 듣도 못한 사람의 명단과, 보도 못한 사람의 명단이 주어질 때, 듣도 보도 못한 사람의 명단을 구하는 프로그램을 작성하시오.
입력
첫째 줄에 듣도 못한 사람의 수 N, 보도 못한 사람의 수 M이 주어진다.
이어서 둘째 줄부터 N개의 줄에 걸쳐 듣도 못한 사람의 이름과, N+2째 줄부터 보도 못한 사람의 이름이 순서대로 주어진다.
이름은 띄어쓰기 없이 영어 소문자로만 이루어지며, 그 길이는 20 이하이다.
N, M은 500,000 이하의 자연수이다.
출력
듣보잡의 수와 그 명단을 사전순으로 출력한다.
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int n, m;
map <string, bool> mp; // 듣지 못한것에서 보지 못한것들을 문자열로 검색하기 위함.
vector <string> ans;
string strTemp;
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> strTemp;
mp.insert(make_pair(strTemp, true)); // 듣지 못한것들을 true로 저장
}
for (int i = 0; i < m; i++) {
cin >> strTemp;
if (mp[strTemp]) { // 듣지 못한것들에 있다면
ans.push_back(strTemp); // 정답으로 빼기
}
}
sort(ans.begin(),ans.end()); // 사전순으로 정리
cout << ans.size() << '\n';
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << '\n';
}
}
|
e8d67aaed5d9eac7d92531d0924a7bb212e4009a
|
ebe1eaf68b4ebe941e564ecaf536a06d625e1eda
|
/Engine/include/XSEIMaterialReader.h
|
76bd5db675dcaf59c35715480ca965ca0dd20b94
|
[] |
no_license
|
przemyslaw-szymanski/x-source-engine
|
54a23e9ad740f7ab1b4a439f87733c366233eb58
|
1afa8c0dea628b6a252ee40aef39c31ec99d3c97
|
refs/heads/master
| 2020-12-24T15:41:01.851654
| 2015-08-07T14:37:12
| 2015-08-07T14:37:12
| 13,867,990
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 348
|
h
|
XSEIMaterialReader.h
|
#ifndef XSE_IMATERIAL_READER_H
#define XSE_IMATERIAL_READER_H
#include "XSECommon.h"
namespace XSE
{
namespace Resources
{
class CMaterial;
}
class IMaterialReader
{
public:
virtual ~IMaterialReader() {}
virtual i32 Read(Resources::CMaterial* pMat, xst_unknown pData, cul32& ulDataSize) = 0;
protected:
};
}//xse
#endif
|
bb3872945c687406df63c30a4c543a21aeb984fa
|
21837a0df7796db604b94f82c4f146f96e2c6bcc
|
/model/manager/singleshotmanager.cpp
|
7ff488fe5e50396fe455372d94d609e2703145dc
|
[] |
no_license
|
yonderfx/yonder
|
b17b3312d13a3f3f93fb666dc4a4ddfd19caffe4
|
56bd5b0b8e822b0338752b41debf2e7514f2a25b
|
refs/heads/master
| 2020-04-22T14:18:13.696362
| 2014-07-23T19:24:22
| 2014-07-23T19:24:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,156
|
cpp
|
singleshotmanager.cpp
|
#include "singleshotmanager.h"
/*!
* Performs default startup
*/
SingleshotManager::SingleshotManager(QString project_path, QSqlDatabase db, MediaManager *media, QObject *parent) :
SoundManager(project_path, QString("singleshot"), db, media, parent)
{
this->path = QString("%1/%2").arg(this->project_path, "sfx");
this->library_identifier = QString("sfx_library");
createTables();
library_model = new LibraryModel(library_identifier);
objects_model = new ObjectsModel(objects_identifier);
objects_tracks_model = new ObjectsTracksModel(objects_tracks_identifier, library_identifier);
rescanLibrary();
createObjectsList();
connect(objects_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(createObjectsList()));
}
/*!
* Creates list of all known objects
*/
void SingleshotManager::createObjectsList() {
objects = QList<QStringList>();
QSqlQuery query;
query.prepare(QString("SELECT `id`, `name` FROM \"%1\"").arg(objects_identifier));
query.exec();
while(query.next()) {
QStringList object;
object.append(query.value(0).toString()); // DIRRRTY
object.append(query.value(1).toString());
objects.append(object);
//qDebug() << identifier << "object add" << object;
}
createChannels();
}
/*!
* Overwriting SoundManager::createChannels(int)
*/
void SingleshotManager::createChannels() {
for(int i=0; i<this->objects.length(); i++) {
container.append(media->createContainer());
container.at(i)->setOID(objects.at(i)[0].toInt());
container.at(i)->setChannel(i);
channels++;
}
}
/*!
* Changes channel state to opposite
*/
void SingleshotManager::playPause(int channel) {
if(container.at(channel)->isPlaying() == true) {
pause(channel);
} else {
play(channel);
}
}
/*!
* Starts playing on channel
*/
void SingleshotManager::play(int channel) {
if(enqueue(channel)) {
container.at(channel)->play();
qDebug() << identifier << "playing on channel" << channel;
} else {
qDebug() << identifier << "nothing to play on channel" << channel;
emit playbackError(channel);
}
}
/*!
* Pauses on channel
*/
void SingleshotManager::pause(int channel) {
container.at(channel)->pause();
qDebug() << identifier << "pausing on channel" << channel;
}
/*!
* Stops on channel and erases queue
*/
void SingleshotManager::stop(int channel) {
container.at(channel)->stop();
}
/*!
* Enqueues track on channel
*/
bool SingleshotManager::enqueue(int channel) {
objects_tracks_model->selectObject(container.at(channel)->getOID());
int tid = objects_tracks_model->selectRandomTrack();
QString current_library_filter = library_model->filter();
library_model->setFilter(QString("id=%1").arg(tid));
QString choice_filename = library_model->data(library_model->index(0, 1)).toString();
library_model->setFilter(current_library_filter);
if(choice_filename.isEmpty()) {
return false;
}
container.at(channel)->loadFile(absoluteFilePath(choice_filename), false);
return true;
}
|
ada495ccd4a193b7eb5b29cbd3454d86505cb339
|
2b30d2124f46e335fab96012feb1d98e60711a79
|
/uva/t.cpp
|
5f965d17bbaddfecc38fa1e827cd27a3ab5255b7
|
[] |
no_license
|
ldfaiztt/algorithm-3
|
9ac150c5a1b67dccbe8f56c386f809fa99d3d4be
|
8a1f078b291723459047b91064ee4d7b9da5e889
|
refs/heads/master
| 2021-01-15T10:36:09.657594
| 2014-07-09T18:23:48
| 2014-07-09T18:23:48
| 39,565,754
| 6
| 5
| null | 2015-07-23T12:21:18
| 2015-07-23T12:21:18
| null |
UTF-8
|
C++
| false
| false
| 607
|
cpp
|
t.cpp
|
#include <iostream>
#include <list>
using namespace std;
int graph[100][100];
int n, x, y, steps;
list<int> path;
void walk(int pos){
for(int i = 0; i < n; i++){
if(graph[pos][i] > 0){
graph[pos][i] --;
graph[i][pos] --;
walk(i);
}
}
path.push_back(pos+1);
}
int main(){
cin >> n;
for(int i = 0; i < n; i++){
cin >> x >> y;
graph[x-1][y-1] ++; //we are using zero index
graph[y-1][x-1] ++;
}
walk(0);
while(!path.empty()){
cout << path.back() << ' ';
path.pop_back();
}
}
|
320b6d8adbd3ebe6532b3360845578b1e064645b
|
ce7a9b1afd0f10b028353b50cf8092bb65c6e713
|
/include/xtrainer/tools/log.h
|
301f7186bf4b010b8a632b45e8c3868a7cbf7bfa
|
[
"MIT"
] |
permissive
|
carbonXIII/xTrainer
|
471b8cf561f5884d4a15a9be1f8215c0ba2fa9fd
|
f3d615f35b21986cc2078028311306207fe00801
|
refs/heads/master
| 2022-05-22T13:54:32.726639
| 2019-10-11T02:38:27
| 2019-10-11T02:38:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,739
|
h
|
log.h
|
/*
* log.h
*
* Created on: Dec 18, 2017
* Author: Jordan Richards
*/
#ifndef TOOLS_LOG_H_
#define TOOLS_LOG_H_
#include <iostream>
#include <fstream>
namespace xtrainer{
//A simple logger that uses macros to prepend messages with the function signature
struct Logger{
Logger() {}
void useStdErr(bool use){
_useStdErr = use;
}
void openLogFile(const char* filename){
logFile.open(filename, std::ios_base::app | std::ios_base::out);
}
void closeLogFile(){
logFile.close();
}
template <typename T>
Logger& operator << (const T& a){
if(_useStdErr)std::cerr << a;
if(logFile.is_open())logFile << a;
return *this;
}
~Logger(){
closeLogFile();
}
private:
std::ofstream logFile;
bool _useStdErr = false;
};
extern Logger default_logger;
//define function name macro based on compiler
#ifndef __FUNCTION_NAME__
#ifdef __GNUG__//G++ (MinGW, Linux)
#define __FUNCTION_NAME__ __PRETTY_FUNCTION__
#else
#ifdef _MSC_VER//Visual Studio
#define __FUNCTION_NAME__ __FUNCDNAME__
#else
#define __FUNCTION_NAME__ ""//Empty String if Unavailable
#endif
#endif
#endif
#if (defined (_WIN32) || defined (_WIN64))
#define __FILE_SEP__ "\\"
#else
#define __FILE_SEP__ "/"
#endif
#define __FILENAME__ strrchr(__FILE_SEP__ __FILE__, __FILE_SEP__[0]) + 1
#define LOG _log(default_logger, (__FUNCTION_NAME__),(__FILENAME__),(__LINE__))//Logging macro (captures function name, file name, and line number)
#define CLOG ( logger ) _log((logger), (__FUNCTION_NAME__),(__FILENAME__),(__LINE__))//Custom logger (function-like)
extern Logger& _log(Logger& logger, const char* func_name, const char* file_name, long line_number);//Logging helper function
}//namespace xtrainer
#endif /* TOOLS_LOG_H_ */
|
0b12f3132fe2baca7c066cdbe5f2f568795330a5
|
c36597e246af0c633e54a61cc0be4a6f2871be53
|
/Practice2/src/circleCollider.cpp
|
c165266826d2513da94b3c35538ebde66fc4407a
|
[] |
no_license
|
Andresmag/U-TAD_AudioProgramming
|
5d379dc4889f97c70a75604032e7b3d5a431b6de
|
b9b807c1049ac99f111efd709f51c70a518aac4c
|
refs/heads/master
| 2023-01-09T16:45:05.084772
| 2020-11-05T13:12:42
| 2020-11-05T13:12:42
| 310,293,987
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 774
|
cpp
|
circleCollider.cpp
|
#include "vec2.h"
#include "circleCollider.h"
CircleCollider::CircleCollider(const Vec2& _vCenter, float _fRadius)
: m_vCenter(_vCenter)
, m_fRadius(_fRadius)
{
}
bool CircleCollider::collides(const Collider& other) const
{
return other.collides(m_vCenter, m_fRadius);
}
bool CircleCollider::collides(const Vec2& circlePos, float circleRadius) const
{
return checkCircleCircle(m_vCenter, m_fRadius, circlePos, circleRadius);
}
bool CircleCollider::collides(const Vec2& rectPos, const Vec2& rectSize) const
{
return checkCircleRect(m_vCenter, m_fRadius, rectPos, rectSize);
}
bool CircleCollider::collides(const Vec2& pixelsPos, const Vec2& pixelsSize, const uint8_t* pixels) const
{
return checkCirclePixels(m_vCenter, m_fRadius, pixelsPos, pixelsSize, pixels);
}
|
82c8d76a6b1948f61d62924f972322bb3f28b01f
|
1b2b44b1b91be455918a069c9788b5978fabca44
|
/Arduino/Text_Scrolling_Static/Text_Scrolling_Static.ino
|
91aa016f89c6d9ad0b264bc1e595d703408ef644
|
[] |
no_license
|
ckuzma/rgb-led-light-board
|
f2b737745696603124dd63d53de78d290438d38d
|
7e0eb0fd2cc76e684a9ae70a8a6fe3f83f4e1586
|
refs/heads/master
| 2023-06-08T02:48:35.345300
| 2023-05-23T19:52:10
| 2023-05-23T19:52:10
| 248,360,529
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,815
|
ino
|
Text_Scrolling_Static.ino
|
// Arduino OTA stuff
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
// Get configuration values
#include "config.h"
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "OTA-RGB-LED-LightBoard";
// NeoMatrix stuff
#include <Adafruit_NeoMatrix.h>
// Change these to fit your setup
#define PIN D3
#define WIDTH 16
#define HEIGHT 8
// Array initialization
Adafruit_NeoMatrix Matrix = Adafruit_NeoMatrix(
WIDTH, HEIGHT,
PIN,
NEO_MATRIX_BOTTOM + NEO_MATRIX_RIGHT +
NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
NEO_GRB + NEO_KHZ800
);
// Text setup
const char text[] = "happy hour";
const int scroll_width = -65;
const int color_count = 5;
const uint16_t colors[] = {
Matrix.Color(255,186,21),
Matrix.Color(249,251,79),
Matrix.Color(19,249,246),
Matrix.Color(64,166,250),
Matrix.Color(240,61,248)
};
// Some initial variable instantiations
int x = Matrix.width();
int pass = 0;
void setup() {
// Get WiFi up and going for OTA purposes
Serial.begin(115200);
Serial.println("Booting");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
WiFi.begin(ssid, password);
Serial.println("Retrying connection...");
}
ArduinoOTA.setHostname(host);
ArduinoOTA.begin();
Matrix.begin();
Matrix.setTextWrap(false);
Matrix.setBrightness(255);
Matrix.setTextColor(colors[0]);
}
void loop() {
ArduinoOTA.handle();
Matrix.fillScreen(0);
Matrix.setCursor(x, 0);
Matrix.print(text);
if(--x < scroll_width){
x = Matrix.width();
if(++pass >= color_count){
pass = 0;
}
Matrix.setTextColor(colors[pass]);
}
Matrix.show();
delay(100);
}
|
f4dcb4778cb97b823c89d8b524958fc208cdb2df
|
e4a2d8c37af0f2e42e826618d5a680fcd371aba2
|
/cCollectionsPractices/main.cpp
|
b80e092ce41ebb2f78f5ef8bb02bb68b8473c01a
|
[] |
no_license
|
bajieSummer/HelloWorld
|
9dca7193317a92fa859fb08a6342a717bf851ec0
|
49e8468cc5407bf185608c1c368c3c63caeb4dec
|
refs/heads/master
| 2021-03-22T05:10:24.102867
| 2018-01-04T06:40:57
| 2018-01-04T06:40:57
| 111,384,148
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 359
|
cpp
|
main.cpp
|
#include<iostream>
//#include<iterator>
#include<array>
int main(){
std::cout<<"hello world array";
typedef std::array<int,3> MyIntArray;
MyIntArray marray = {2,3,4};
MyIntArray::iterator iter = marray.begin();
while(iter!=marray.end()){
std::cout<<*iter;
iter++;
}
// std::iterator<MyIntArray> = marray.begin();
}
|
f46f706835ce68d414b6a6c5c59e9501674f4c2d
|
505e3b9d89454a7811d8a2f39a48b9837d6f3efb
|
/curve/src/main.cpp
|
e4d62094a71464b69a89b23a23a81fced2c32542
|
[
"MIT"
] |
permissive
|
msmania/curve
|
83ce9689d90d508159f0b198121c14282fe7fc19
|
ca38ec48799e445a830bd5defea8a211aa3f0e3e
|
refs/heads/master
| 2021-07-10T15:36:55.740662
| 2017-10-14T00:08:18
| 2017-10-14T00:08:18
| 105,320,182
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,237
|
cpp
|
main.cpp
|
#include <windows.h>
#include <iostream>
#include <fstream>
#include <curvecore.h>
using namespace curve;
void Log(LPCWSTR format, ...) {
va_list v;
va_start(v, format);
vwprintf(format, v);
va_end(v);
}
void show_usage() {
std::wcout
<< L"Usage: curve [command] [args...]" << std::endl
<< std::endl
<< L" -s <endpoint> Run as an RPC server" << std::endl
<< std::endl
<< L"Command as an RPC client:" << std::endl
<< L" -q <endpoint> -- Quit RPC server" << std::endl
<< L" -g <endpoint> <url> <viewWidth> <viewHeight> -- Navigate to URL" << std::endl
<< L" -ga <endpoint> <url> <viewWidth> <viewHeight> -- Navigate async to URL" << std::endl
<< L" -m <endpoint> [backFile] -- Set mapping file" << std::endl
<< L" -c <endpoint> <bitCount> <captureLocal> -- Capture the window" << std::endl
<< L" -d <endpoint1> <endpoint2>" << std::endl
<< L" <url> <wait> <viewWidth> <viewHeight>" << std::endl
<< L" <backFile1> <backFile1> <algo> [diffImage] -- Image diff'ing" << std::endl
<< L" (algo: 0=skip | 1=average | 2=max | 3=min | 4=triangle | 5=erosion)" << std::endl
<< L" -batch <endpoint> <bitCount>" << std::endl
<< L" <backFile1> <backFile1> -- Batch run" << std::endl
<< std::endl;
}
int wmain(int argc, wchar_t *argv[]) {
if (argc >= 3 && wcscmp(argv[1], L"-s") == 0) {
RunAsServer(argv[2]);
}
else if (argc >= 3 && wcscmp(argv[1], L"-q") == 0) {
Shutdown(argv[2]);
}
else if (argc >= 6 && wcscmp(argv[1], L"-g") == 0) {
Navigate(argv[2],
argv[3],
_wtoi(argv[4]),
_wtoi(argv[5]),
/*async*/false);
}
else if (argc >= 6 && wcscmp(argv[1], L"-ga") == 0) {
Navigate(argv[2],
argv[3],
_wtoi(argv[4]),
_wtoi(argv[5]),
/*async*/true);
}
else if (argc >= 3 && wcscmp(argv[1], L"-m") == 0) {
EnsureFileMapping(argv[2],
argc >= 4 ? argv[3] : nullptr,
/*forceUpdate*/true,
/*section*/nullptr);
}
else if (argc >= 5 && wcscmp(argv[1], L"-c") == 0) {
Capture(argv[2], _wtoi(argv[3]), argv[4]);
}
else if (argc >= 11 && wcscmp(argv[1], L"-d") == 0) {
DiffInput in;
in.endpoint1 = argv[2];
in.endpoint2 = argv[3];
in.url = argv[4];
in.waitInMilliseconds = _wtoi(argv[5]);
in.viewWidth = _wtoi(argv[6]);
in.viewHeight = _wtoi(argv[7]);
in.backFile1 = argv[8];
in.backFile2 = argv[9];
in.algo = static_cast<DiffAlgorithm>(_wtoi(argv[10]));
in.diffImage = argc >= 12 ? argv[11] : nullptr;
DiffOutput out;
if (SUCCEEDED(DiffImage(in, out))) {
Log(L"Diff score: %f %f %f\n",
out.psnr_area_vs_smooth,
out.psnr_target_vs_area,
out.psnr_target_vs_smooth);
}
}
else if (argc >= 6 && wcscmp(argv[1], L"-batch") == 0) {
BatchRun(std::cin, argv[2], argv[3], argv[4], argv[5]);
//std::ifstream is("BATCH");
//if (is.is_open()) {
// BatchRun(is, argv[2], argv[3], argv[4], argv[5]);
//}
}
else {
show_usage();
}
return 0;
}
|
46769b175180c3313d36a181ee3d8124a221e3d7
|
120bc89da1229dcd49bd45b741b1ee42156fa697
|
/UWPProjects/com.mtaulty.AJHoloServer/AJHoloServerServiceEventArgs.h
|
733436de5fd1dd24352c23d71e142b8ef0b90e43
|
[
"MIT"
] |
permissive
|
mtaulty/AllJoynHoloSharing
|
fa55a3d1d9c077038b07b2be1ef1cf0dd4604579
|
211ebfc4eb68d2bdbcd41ba3fc3a60014b6cfa82
|
refs/heads/master
| 2020-12-03T03:46:31.519793
| 2017-06-29T11:55:51
| 2017-06-29T11:55:51
| 95,772,309
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,887
|
h
|
AJHoloServerServiceEventArgs.h
|
//-----------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
// </auto-generated>
//-----------------------------------------------------------------------------
#pragma once
namespace com { namespace mtaulty { namespace AJHoloServer {
// Methods
public ref class AJHoloServerAddWorldAnchorCalledEventArgs sealed
{
public:
AJHoloServerAddWorldAnchorCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ Platform::String^ interfaceMemberAnchorId, _In_ uint32 interfaceMemberByteStart, _In_ uint32 interfaceMemberByteLength, _In_ bool interfaceMemberLastBlock, _In_ Windows::Foundation::Collections::IVectorView<byte>^ interfaceMemberAnchorData);
property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
{
Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
}
property AJHoloServerAddWorldAnchorResult^ Result
{
AJHoloServerAddWorldAnchorResult^ get() { return m_result; }
void set(_In_ AJHoloServerAddWorldAnchorResult^ value) { m_result = value; }
}
property Platform::String^ AnchorId
{
Platform::String^ get() { return m_interfaceMemberAnchorId; }
}
property uint32 ByteStart
{
uint32 get() { return m_interfaceMemberByteStart; }
}
property uint32 ByteLength
{
uint32 get() { return m_interfaceMemberByteLength; }
}
property bool LastBlock
{
bool get() { return m_interfaceMemberLastBlock; }
}
property Windows::Foundation::Collections::IVectorView<byte>^ AnchorData
{
Windows::Foundation::Collections::IVectorView<byte>^ get() { return m_interfaceMemberAnchorData; }
}
Windows::Foundation::Deferral^ GetDeferral();
static Windows::Foundation::IAsyncOperation<AJHoloServerAddWorldAnchorResult^>^ GetResultAsync(AJHoloServerAddWorldAnchorCalledEventArgs^ args)
{
args->InvokeAllFinished();
auto t = concurrency::create_task(args->m_tce);
return concurrency::create_async([t]() -> concurrency::task<AJHoloServerAddWorldAnchorResult^>
{
return t;
});
}
private:
void Complete();
void InvokeAllFinished();
void InvokeCompleteHandler();
bool m_raised;
int m_completionsRequired;
concurrency::task_completion_event<AJHoloServerAddWorldAnchorResult^> m_tce;
std::mutex m_lock;
Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
AJHoloServerAddWorldAnchorResult^ m_result;
Platform::String^ m_interfaceMemberAnchorId;
uint32 m_interfaceMemberByteStart;
uint32 m_interfaceMemberByteLength;
bool m_interfaceMemberLastBlock;
Windows::Foundation::Collections::IVectorView<byte>^ m_interfaceMemberAnchorData;
};
public ref class AJHoloServerAddHologramToAnchorCalledEventArgs sealed
{
public:
AJHoloServerAddHologramToAnchorCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ Platform::String^ interfaceMemberAnchorId, _In_ Platform::String^ interfaceMemberHoloId, _In_ Platform::String^ interfaceMemberHoloTypeName, _In_ AJHoloServerPosition^ interfaceMemberPosition);
property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
{
Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
}
property AJHoloServerAddHologramToAnchorResult^ Result
{
AJHoloServerAddHologramToAnchorResult^ get() { return m_result; }
void set(_In_ AJHoloServerAddHologramToAnchorResult^ value) { m_result = value; }
}
property Platform::String^ AnchorId
{
Platform::String^ get() { return m_interfaceMemberAnchorId; }
}
property Platform::String^ HoloId
{
Platform::String^ get() { return m_interfaceMemberHoloId; }
}
property Platform::String^ HoloTypeName
{
Platform::String^ get() { return m_interfaceMemberHoloTypeName; }
}
property AJHoloServerPosition^ Position
{
AJHoloServerPosition^ get() { return m_interfaceMemberPosition; }
}
Windows::Foundation::Deferral^ GetDeferral();
static Windows::Foundation::IAsyncOperation<AJHoloServerAddHologramToAnchorResult^>^ GetResultAsync(AJHoloServerAddHologramToAnchorCalledEventArgs^ args)
{
args->InvokeAllFinished();
auto t = concurrency::create_task(args->m_tce);
return concurrency::create_async([t]() -> concurrency::task<AJHoloServerAddHologramToAnchorResult^>
{
return t;
});
}
private:
void Complete();
void InvokeAllFinished();
void InvokeCompleteHandler();
bool m_raised;
int m_completionsRequired;
concurrency::task_completion_event<AJHoloServerAddHologramToAnchorResult^> m_tce;
std::mutex m_lock;
Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
AJHoloServerAddHologramToAnchorResult^ m_result;
Platform::String^ m_interfaceMemberAnchorId;
Platform::String^ m_interfaceMemberHoloId;
Platform::String^ m_interfaceMemberHoloTypeName;
AJHoloServerPosition^ m_interfaceMemberPosition;
};
public ref class AJHoloServerRemoveHologramCalledEventArgs sealed
{
public:
AJHoloServerRemoveHologramCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ Platform::String^ interfaceMemberHoloId);
property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
{
Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
}
property AJHoloServerRemoveHologramResult^ Result
{
AJHoloServerRemoveHologramResult^ get() { return m_result; }
void set(_In_ AJHoloServerRemoveHologramResult^ value) { m_result = value; }
}
property Platform::String^ HoloId
{
Platform::String^ get() { return m_interfaceMemberHoloId; }
}
Windows::Foundation::Deferral^ GetDeferral();
static Windows::Foundation::IAsyncOperation<AJHoloServerRemoveHologramResult^>^ GetResultAsync(AJHoloServerRemoveHologramCalledEventArgs^ args)
{
args->InvokeAllFinished();
auto t = concurrency::create_task(args->m_tce);
return concurrency::create_async([t]() -> concurrency::task<AJHoloServerRemoveHologramResult^>
{
return t;
});
}
private:
void Complete();
void InvokeAllFinished();
void InvokeCompleteHandler();
bool m_raised;
int m_completionsRequired;
concurrency::task_completion_event<AJHoloServerRemoveHologramResult^> m_tce;
std::mutex m_lock;
Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
AJHoloServerRemoveHologramResult^ m_result;
Platform::String^ m_interfaceMemberHoloId;
};
public ref class AJHoloServerGetWorldAnchorCalledEventArgs sealed
{
public:
AJHoloServerGetWorldAnchorCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ Platform::String^ interfaceMemberAnchorId, _In_ uint32 interfaceMemberByteIndex, _In_ uint32 interfaceMemberByteLength);
property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
{
Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
}
property AJHoloServerGetWorldAnchorResult^ Result
{
AJHoloServerGetWorldAnchorResult^ get() { return m_result; }
void set(_In_ AJHoloServerGetWorldAnchorResult^ value) { m_result = value; }
}
property Platform::String^ AnchorId
{
Platform::String^ get() { return m_interfaceMemberAnchorId; }
}
property uint32 ByteIndex
{
uint32 get() { return m_interfaceMemberByteIndex; }
}
property uint32 ByteLength
{
uint32 get() { return m_interfaceMemberByteLength; }
}
Windows::Foundation::Deferral^ GetDeferral();
static Windows::Foundation::IAsyncOperation<AJHoloServerGetWorldAnchorResult^>^ GetResultAsync(AJHoloServerGetWorldAnchorCalledEventArgs^ args)
{
args->InvokeAllFinished();
auto t = concurrency::create_task(args->m_tce);
return concurrency::create_async([t]() -> concurrency::task<AJHoloServerGetWorldAnchorResult^>
{
return t;
});
}
private:
void Complete();
void InvokeAllFinished();
void InvokeCompleteHandler();
bool m_raised;
int m_completionsRequired;
concurrency::task_completion_event<AJHoloServerGetWorldAnchorResult^> m_tce;
std::mutex m_lock;
Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
AJHoloServerGetWorldAnchorResult^ m_result;
Platform::String^ m_interfaceMemberAnchorId;
uint32 m_interfaceMemberByteIndex;
uint32 m_interfaceMemberByteLength;
};
public ref class AJHoloServerGetWorldAnchorIdsCalledEventArgs sealed
{
public:
AJHoloServerGetWorldAnchorIdsCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info);
property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
{
Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
}
property AJHoloServerGetWorldAnchorIdsResult^ Result
{
AJHoloServerGetWorldAnchorIdsResult^ get() { return m_result; }
void set(_In_ AJHoloServerGetWorldAnchorIdsResult^ value) { m_result = value; }
}
Windows::Foundation::Deferral^ GetDeferral();
static Windows::Foundation::IAsyncOperation<AJHoloServerGetWorldAnchorIdsResult^>^ GetResultAsync(AJHoloServerGetWorldAnchorIdsCalledEventArgs^ args)
{
args->InvokeAllFinished();
auto t = concurrency::create_task(args->m_tce);
return concurrency::create_async([t]() -> concurrency::task<AJHoloServerGetWorldAnchorIdsResult^>
{
return t;
});
}
private:
void Complete();
void InvokeAllFinished();
void InvokeCompleteHandler();
bool m_raised;
int m_completionsRequired;
concurrency::task_completion_event<AJHoloServerGetWorldAnchorIdsResult^> m_tce;
std::mutex m_lock;
Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
AJHoloServerGetWorldAnchorIdsResult^ m_result;
};
public ref class AJHoloServerGetHologramIdsAndNamesCalledEventArgs sealed
{
public:
AJHoloServerGetHologramIdsAndNamesCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info);
property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
{
Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
}
property AJHoloServerGetHologramIdsAndNamesResult^ Result
{
AJHoloServerGetHologramIdsAndNamesResult^ get() { return m_result; }
void set(_In_ AJHoloServerGetHologramIdsAndNamesResult^ value) { m_result = value; }
}
Windows::Foundation::Deferral^ GetDeferral();
static Windows::Foundation::IAsyncOperation<AJHoloServerGetHologramIdsAndNamesResult^>^ GetResultAsync(AJHoloServerGetHologramIdsAndNamesCalledEventArgs^ args)
{
args->InvokeAllFinished();
auto t = concurrency::create_task(args->m_tce);
return concurrency::create_async([t]() -> concurrency::task<AJHoloServerGetHologramIdsAndNamesResult^>
{
return t;
});
}
private:
void Complete();
void InvokeAllFinished();
void InvokeCompleteHandler();
bool m_raised;
int m_completionsRequired;
concurrency::task_completion_event<AJHoloServerGetHologramIdsAndNamesResult^> m_tce;
std::mutex m_lock;
Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
AJHoloServerGetHologramIdsAndNamesResult^ m_result;
};
public ref class AJHoloServerGetHologramTransformsCalledEventArgs sealed
{
public:
AJHoloServerGetHologramTransformsCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info);
property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
{
Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
}
property AJHoloServerGetHologramTransformsResult^ Result
{
AJHoloServerGetHologramTransformsResult^ get() { return m_result; }
void set(_In_ AJHoloServerGetHologramTransformsResult^ value) { m_result = value; }
}
Windows::Foundation::Deferral^ GetDeferral();
static Windows::Foundation::IAsyncOperation<AJHoloServerGetHologramTransformsResult^>^ GetResultAsync(AJHoloServerGetHologramTransformsCalledEventArgs^ args)
{
args->InvokeAllFinished();
auto t = concurrency::create_task(args->m_tce);
return concurrency::create_async([t]() -> concurrency::task<AJHoloServerGetHologramTransformsResult^>
{
return t;
});
}
private:
void Complete();
void InvokeAllFinished();
void InvokeCompleteHandler();
bool m_raised;
int m_completionsRequired;
concurrency::task_completion_event<AJHoloServerGetHologramTransformsResult^> m_tce;
std::mutex m_lock;
Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
AJHoloServerGetHologramTransformsResult^ m_result;
};
// Readable Properties
public ref class AJHoloServerGetDeviceConnectedCountRequestedEventArgs sealed
{
public:
AJHoloServerGetDeviceConnectedCountRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info);
property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
{
Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
}
property AJHoloServerGetDeviceConnectedCountResult^ Result
{
AJHoloServerGetDeviceConnectedCountResult^ get() { return m_result; }
void set(_In_ AJHoloServerGetDeviceConnectedCountResult^ value) { m_result = value; }
}
Windows::Foundation::Deferral^ GetDeferral();
static Windows::Foundation::IAsyncOperation<AJHoloServerGetDeviceConnectedCountResult^>^ GetResultAsync(AJHoloServerGetDeviceConnectedCountRequestedEventArgs^ args)
{
args->InvokeAllFinished();
auto t = concurrency::create_task(args->m_tce);
return concurrency::create_async([t]() -> concurrency::task<AJHoloServerGetDeviceConnectedCountResult^>
{
return t;
});
}
private:
void Complete();
void InvokeAllFinished();
void InvokeCompleteHandler();
bool m_raised;
int m_completionsRequired;
concurrency::task_completion_event<AJHoloServerGetDeviceConnectedCountResult^> m_tce;
std::mutex m_lock;
Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
AJHoloServerGetDeviceConnectedCountResult^ m_result;
};
// Writable Properties
} } }
|
b1d79d7b86b00c7cc0eebd8da602c1b5c8e7da61
|
c09ffb7701d38365123beea17150a056d7e6090c
|
/HDU/HDU2175 汉诺塔IX.cpp
|
17e62700fbbe9cdbf499668ab3158d59d4a4c5b2
|
[] |
no_license
|
Reno-Jarrison/Code-Repository-for-Problem-Solving
|
f100aa1190c3a7d23955d4756a9afa8353c8edbe
|
b2715b696cdb4b0416e334a5bd231beea66cfca0
|
refs/heads/main
| 2023-04-12T08:08:16.151731
| 2021-05-11T01:29:07
| 2021-05-11T01:29:07
| 315,653,788
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 172
|
cpp
|
HDU2175 汉诺塔IX.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)&&n)
{
int cnt=0;
while(!(m&1)) cnt++,m>>=1;
printf("%d\n",cnt+1);
}
}
|
29546ce4494f4a63e77b756c11f59bcc2569d26d
|
67e0183f9731e48637c315fadc7ec0b81cd62cde
|
/assignment10/assignment10/assignment10.cpp
|
af0ac0c691eff5ead14443d6ff8c5c3e3695e4de
|
[] |
no_license
|
szhongren/H212
|
5a8dcf1de654edc2baf436c7ae81363251e7f3e2
|
2f812fabe9bc9f3b3404aa2b9047ed4eeff11441
|
refs/heads/master
| 2016-09-01T23:11:24.375538
| 2014-10-16T20:07:57
| 2014-10-16T20:07:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,427
|
cpp
|
assignment10.cpp
|
// Zhongren Shao, Assignment 10
#include "std_lib_facilities.h"
//pool class for managing the memory allocations, contains pointers to the first and last unsigned chars of the pool
class Pool
{
public:
// default constructor, takes a parameter specifying the size of pool
Pool (int size)
{
// loop to ensure that the initial size of pool is sufficient
while (size <= 16)
{
cout << "The size you specified is too small for a memory pool. Please enter a size larger than or equal to 20." << endl;
cin >> size;
}
// sets start and end of the pool
pool = new unsigned char[size];
end = pool + size;
// data is arranged like this: [size][ptr_to_prev][ptr_to_next], in int, long, long respectively
int* nodeSize = (int*) pool;
*nodeSize = size;
long* prev = (long*) (nodeSize + 1);
*prev = NULL;
long* next = prev + 1;
*next = NULL;
cout << "Memory pool of " << size << " bytes created!" << endl;
}
//class function for allocating the specified number of bytes
void* allocate (unsigned int bytes)
{
// finds the first empty space
unsigned char* pos = (unsigned char*) findFirst();
// if first points to null -> there is no empty space
if (!pos)
{
cout << "There is no memory left in the pool." << endl;
return NULL;
}
unsigned char* last = (unsigned char*) findLast(pos);
long* prev, * next;
int* chunkSize;
do
{
chunkSize = (int*) pos;
prev = getPrev(pos);
next = getNext(pos);
if (*chunkSize > bytes + 2 * sizeof(int) + 2 * sizeof(long))
{
int* newNode = (int*) (pos + bytes + sizeof(int));
*newNode = *chunkSize - sizeof(int) - bytes;
*chunkSize = bytes;
long* nprev = getPrev((unsigned char*) newNode);
*nprev = *prev;
*prev = 1;
long* nnext = getNext((unsigned char*) newNode);
*nnext = *next;
updateList((unsigned char*) newNode);
cout << bytes << " bytes of memory allocated successfully. You have a maximum of " << freeMem() << " bytes of memory left for use." << endl;
return pos + sizeof(int);
}
else if (*chunkSize == bytes + sizeof(int))
{
*chunkSize = bytes;
remNode(pos);
*prev = 1;
cout << bytes << " bytes of memory allocated successfully. You have a maximum of " << freeMem() << " bytes of memory left for use." << endl;
return pos + sizeof(int);
}
else if (pos != last)
pos = (unsigned char*) *next;
} while (pos != last);
cout << "Allocation of " << bytes << " bytes unsuccessful. Please create a bigger pool, or try allocating a smaller block of memory." << endl;
return NULL;
};
//class function for deallocating the memory chunk at the location specified by the pointer
void deallocate (void* ptr)
{
if (!ptr)
{
cout << "Pointer is null. No deallocation performed." << endl;
return;
}
int* size = (((int*) ptr) - 1);
long* next = getNext((unsigned char*) size);
long* prev = getPrev((unsigned char*) size);
unsigned char* first = (unsigned char*) findFirst();
unsigned char* last = (unsigned char*) findLast(first);
*size += sizeof(int);
if (!first)
{
*next = NULL;
*prev = NULL;
}
else if (ptr < first)
{
*prev = NULL;
*next = (long) first;
long* fprev = getPrev(first);
*fprev = (long) size;
}
else if (ptr > last)
{
*next = NULL;
*prev = (long) last;
long* lnext = getNext(last);
*lnext = (long) size;
}
else
{
unsigned char* pos = first;
unsigned char* pos2 = (unsigned char*) *getNext(first);
while (pos2 < ptr)
{
pos = pos2;
pos2 = (unsigned char*) getNext(pos2);
}
long* temp = getNext(pos);
*temp = (long) ((unsigned char*) ptr - 4);
temp = getPrev(pos2);
*temp = (long) ((unsigned char*) ptr - 4);
*next = (long) pos2;
*prev = (long) pos;
}
cout << "Deallocation of " << *size - sizeof(int) << " bytes successful. There are " << freeMem() << " bytes now available for use." << endl;
mergeFree((unsigned char*) ptr - 4);
};
private:
//helper function for finding the beginning of the linked list in the pool
void* findFirst()
{
unsigned char* pos = pool;
long* prev;
while (pos < end)
{
int* chunkSize = (int*) pos;
prev = (long*) (chunkSize + 1);
if (*prev == NULL)
return pos;
else
pos += sizeof(int) + *chunkSize;
}
return NULL;
}
//helper function for finding the end of the linked list in the pool
void* findLast(unsigned char* pos)
{
if (!pos)
return NULL;
long* next;
do
{
next = getNext(pos);
if (*next != NULL)
pos = (unsigned char*) *next;
} while (*next != NULL);
return pos;
}
//helper function, returns a pointer to the address in memory holding the address of the next link in the list
long* getPrev(unsigned char* node)
{
return (long*) (node + sizeof(int));
}
//helper function, returns a pointer to the address in memory holding the address of the previous link in the list
long* getNext(unsigned char* node)
{
return (long*) (node + sizeof(int) + sizeof(long));
}
//updates other links in the linked list given a pointer to the modified link in the list
void updateList(unsigned char* newNode)
{
long* prev = getPrev(newNode);
long* next = getNext(newNode);
if (*prev)
{
long* pnext = getNext((unsigned char*) *prev);
*pnext = (long) newNode;
}
if (*next)
{
long* nprev = getPrev((unsigned char*) *next);
*nprev = (long) newNode;
}
}
//removes a node from the list
void remNode(unsigned char* node)
{
long* prev = getPrev(node);
long* next = getNext(node);
if (*prev != NULL)
{
long* pnext = getNext((unsigned char*) *prev);
*pnext = *next;
}
if (*next != NULL)
{
long* nprev = getPrev((unsigned char*) *next);
*nprev = *prev;
}
}
//diagnostic function, calculates the available space remaining in bytes
int freeMem()
{
int* pos = (int*) findFirst();
if (!pos)
return 0;
int mem = *pos;
int* last = (int*) findLast((unsigned char*) pos);
while (pos != last)
{
pos = (int*) *getNext((unsigned char*) pos);
mem += *pos;
}
return mem;
}
//helper function, merges adjacent free spaces together given the address of a deallocated chunk of memory
void mergeFree(unsigned char* ptr)
{
long* prev = getPrev(ptr);
long* next = getNext(ptr);
int* size = (int*) ptr;
if (*next)
{
unsigned char* cnext = (unsigned char*) (ptr + *size);
if ((unsigned char*) *next == cnext)
{
*size += *((int*) *next);
*next = *getNext(cnext);
}
updateList(ptr);
}
if (*prev)
{
long* pcnext = (long*) (*prev + *((int*) *prev));
if (ptr == (unsigned char*) pcnext)
{
*((int*) *prev) += *size;
long* plnext = getNext((unsigned char*) *prev);
*plnext = *getNext(ptr);
}
updateList((unsigned char*) *prev);
}
}
unsigned char* pool;
unsigned char* end;
};
//entry point, modify the allocation function calls here to test
int main ()
{
int size;
cout << "Please input the amount of memory in bytes that you would like to reserve for use." << endl;
cin >> size;
Pool pool(size);
int *x = (int *)pool.allocate(32);
double *y = (double *)pool.allocate(16);
pool.deallocate(x);
pool.deallocate(y);
}
|
05bf8f82662314b567cf8231f188aa4e9fb3206e
|
6064006ee42ab5c8a31d586277ac92e68e0d73ea
|
/udp_process/external_measurement_data.pb.h
|
5f05fe9c401b20fd42a560366f5498b01056883b
|
[] |
no_license
|
xxsmall/PAE_predict
|
43f0f65717f656e821ce9b64a6a884593c61ddb6
|
b51bf186bca28b5316542cde4b0cd3ec3c9cb8d5
|
refs/heads/master
| 2020-05-30T05:22:39.398957
| 2019-05-31T08:34:30
| 2019-05-31T08:34:30
| 189,558,166
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| true
| 34,528
|
h
|
external_measurement_data.pb.h
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: external_measurement_data.proto
#ifndef PROTOBUF_INCLUDED_external_5fmeasurement_5fdata_2eproto
#define PROTOBUF_INCLUDED_external_5fmeasurement_5fdata_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3007000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3007000 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/timestamp.pb.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_external_5fmeasurement_5fdata_2eproto
// Internal implementation detail -- do not use these members.
struct TableStruct_external_5fmeasurement_5fdata_2eproto {
static const ::google::protobuf::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::google::protobuf::internal::ParseTable schema[3]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
void AddDescriptors_external_5fmeasurement_5fdata_2eproto();
namespace tutorial {
class ExternalMeasurementDataBean;
class ExternalMeasurementDataBeanDefaultTypeInternal;
extern ExternalMeasurementDataBeanDefaultTypeInternal _ExternalMeasurementDataBean_default_instance_;
class ParameterBody;
class ParameterBodyDefaultTypeInternal;
extern ParameterBodyDefaultTypeInternal _ParameterBody_default_instance_;
class PredictDataBody;
class PredictDataBodyDefaultTypeInternal;
extern PredictDataBodyDefaultTypeInternal _PredictDataBody_default_instance_;
} // namespace tutorial
namespace google {
namespace protobuf {
template<> ::tutorial::ExternalMeasurementDataBean* Arena::CreateMaybeMessage<::tutorial::ExternalMeasurementDataBean>(Arena*);
template<> ::tutorial::ParameterBody* Arena::CreateMaybeMessage<::tutorial::ParameterBody>(Arena*);
template<> ::tutorial::PredictDataBody* Arena::CreateMaybeMessage<::tutorial::PredictDataBody>(Arena*);
} // namespace protobuf
} // namespace google
namespace tutorial {
// ===================================================================
class ExternalMeasurementDataBean final :
public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tutorial.ExternalMeasurementDataBean) */ {
public:
ExternalMeasurementDataBean();
virtual ~ExternalMeasurementDataBean();
ExternalMeasurementDataBean(const ExternalMeasurementDataBean& from);
inline ExternalMeasurementDataBean& operator=(const ExternalMeasurementDataBean& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
ExternalMeasurementDataBean(ExternalMeasurementDataBean&& from) noexcept
: ExternalMeasurementDataBean() {
*this = ::std::move(from);
}
inline ExternalMeasurementDataBean& operator=(ExternalMeasurementDataBean&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor() {
return default_instance().GetDescriptor();
}
static const ExternalMeasurementDataBean& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ExternalMeasurementDataBean* internal_default_instance() {
return reinterpret_cast<const ExternalMeasurementDataBean*>(
&_ExternalMeasurementDataBean_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
void Swap(ExternalMeasurementDataBean* other);
friend void swap(ExternalMeasurementDataBean& a, ExternalMeasurementDataBean& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline ExternalMeasurementDataBean* New() const final {
return CreateMaybeMessage<ExternalMeasurementDataBean>(nullptr);
}
ExternalMeasurementDataBean* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<ExternalMeasurementDataBean>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const ExternalMeasurementDataBean& from);
void MergeFrom(const ExternalMeasurementDataBean& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
#else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ExternalMeasurementDataBean* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// .tutorial.ParameterBody parameter = 1;
bool has_parameter() const;
void clear_parameter();
static const int kParameterFieldNumber = 1;
const ::tutorial::ParameterBody& parameter() const;
::tutorial::ParameterBody* release_parameter();
::tutorial::ParameterBody* mutable_parameter();
void set_allocated_parameter(::tutorial::ParameterBody* parameter);
// .tutorial.PredictDataBody predictData = 2;
bool has_predictdata() const;
void clear_predictdata();
static const int kPredictDataFieldNumber = 2;
const ::tutorial::PredictDataBody& predictdata() const;
::tutorial::PredictDataBody* release_predictdata();
::tutorial::PredictDataBody* mutable_predictdata();
void set_allocated_predictdata(::tutorial::PredictDataBody* predictdata);
// @@protoc_insertion_point(class_scope:tutorial.ExternalMeasurementDataBean)
private:
class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::tutorial::ParameterBody* parameter_;
::tutorial::PredictDataBody* predictdata_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::TableStruct_external_5fmeasurement_5fdata_2eproto;
};
// -------------------------------------------------------------------
class PredictDataBody final :
public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tutorial.PredictDataBody) */ {
public:
PredictDataBody();
virtual ~PredictDataBody();
PredictDataBody(const PredictDataBody& from);
inline PredictDataBody& operator=(const PredictDataBody& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
PredictDataBody(PredictDataBody&& from) noexcept
: PredictDataBody() {
*this = ::std::move(from);
}
inline PredictDataBody& operator=(PredictDataBody&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor() {
return default_instance().GetDescriptor();
}
static const PredictDataBody& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const PredictDataBody* internal_default_instance() {
return reinterpret_cast<const PredictDataBody*>(
&_PredictDataBody_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
void Swap(PredictDataBody* other);
friend void swap(PredictDataBody& a, PredictDataBody& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline PredictDataBody* New() const final {
return CreateMaybeMessage<PredictDataBody>(nullptr);
}
PredictDataBody* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<PredictDataBody>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const PredictDataBody& from);
void MergeFrom(const PredictDataBody& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
#else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(PredictDataBody* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// string dataStr = 1;
void clear_datastr();
static const int kDataStrFieldNumber = 1;
const ::std::string& datastr() const;
void set_datastr(const ::std::string& value);
#if LANG_CXX11
void set_datastr(::std::string&& value);
#endif
void set_datastr(const char* value);
void set_datastr(const char* value, size_t size);
::std::string* mutable_datastr();
::std::string* release_datastr();
void set_allocated_datastr(::std::string* datastr);
// @@protoc_insertion_point(class_scope:tutorial.PredictDataBody)
private:
class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr datastr_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::TableStruct_external_5fmeasurement_5fdata_2eproto;
};
// -------------------------------------------------------------------
class ParameterBody final :
public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tutorial.ParameterBody) */ {
public:
ParameterBody();
virtual ~ParameterBody();
ParameterBody(const ParameterBody& from);
inline ParameterBody& operator=(const ParameterBody& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
ParameterBody(ParameterBody&& from) noexcept
: ParameterBody() {
*this = ::std::move(from);
}
inline ParameterBody& operator=(ParameterBody&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor() {
return default_instance().GetDescriptor();
}
static const ParameterBody& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ParameterBody* internal_default_instance() {
return reinterpret_cast<const ParameterBody*>(
&_ParameterBody_default_instance_);
}
static constexpr int kIndexInFileMessages =
2;
void Swap(ParameterBody* other);
friend void swap(ParameterBody& a, ParameterBody& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline ParameterBody* New() const final {
return CreateMaybeMessage<ParameterBody>(nullptr);
}
ParameterBody* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<ParameterBody>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const ParameterBody& from);
void MergeFrom(const ParameterBody& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
#else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ParameterBody* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// string spatialEncoding = 1;
void clear_spatialencoding();
static const int kSpatialEncodingFieldNumber = 1;
const ::std::string& spatialencoding() const;
void set_spatialencoding(const ::std::string& value);
#if LANG_CXX11
void set_spatialencoding(::std::string&& value);
#endif
void set_spatialencoding(const char* value);
void set_spatialencoding(const char* value, size_t size);
::std::string* mutable_spatialencoding();
::std::string* release_spatialencoding();
void set_allocated_spatialencoding(::std::string* spatialencoding);
// string beginTime = 2;
void clear_begintime();
static const int kBeginTimeFieldNumber = 2;
const ::std::string& begintime() const;
void set_begintime(const ::std::string& value);
#if LANG_CXX11
void set_begintime(::std::string&& value);
#endif
void set_begintime(const char* value);
void set_begintime(const char* value, size_t size);
::std::string* mutable_begintime();
::std::string* release_begintime();
void set_allocated_begintime(::std::string* begintime);
// string endTime = 3;
void clear_endtime();
static const int kEndTimeFieldNumber = 3;
const ::std::string& endtime() const;
void set_endtime(const ::std::string& value);
#if LANG_CXX11
void set_endtime(::std::string&& value);
#endif
void set_endtime(const char* value);
void set_endtime(const char* value, size_t size);
::std::string* mutable_endtime();
::std::string* release_endtime();
void set_allocated_endtime(::std::string* endtime);
// string deviceName = 4;
void clear_devicename();
static const int kDeviceNameFieldNumber = 4;
const ::std::string& devicename() const;
void set_devicename(const ::std::string& value);
#if LANG_CXX11
void set_devicename(::std::string&& value);
#endif
void set_devicename(const char* value);
void set_devicename(const char* value, size_t size);
::std::string* mutable_devicename();
::std::string* release_devicename();
void set_allocated_devicename(::std::string* devicename);
// @@protoc_insertion_point(class_scope:tutorial.ParameterBody)
private:
class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr spatialencoding_;
::google::protobuf::internal::ArenaStringPtr begintime_;
::google::protobuf::internal::ArenaStringPtr endtime_;
::google::protobuf::internal::ArenaStringPtr devicename_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::TableStruct_external_5fmeasurement_5fdata_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// ExternalMeasurementDataBean
// .tutorial.ParameterBody parameter = 1;
inline bool ExternalMeasurementDataBean::has_parameter() const {
return this != internal_default_instance() && parameter_ != nullptr;
}
inline void ExternalMeasurementDataBean::clear_parameter() {
if (GetArenaNoVirtual() == nullptr && parameter_ != nullptr) {
delete parameter_;
}
parameter_ = nullptr;
}
inline const ::tutorial::ParameterBody& ExternalMeasurementDataBean::parameter() const {
const ::tutorial::ParameterBody* p = parameter_;
// @@protoc_insertion_point(field_get:tutorial.ExternalMeasurementDataBean.parameter)
return p != nullptr ? *p : *reinterpret_cast<const ::tutorial::ParameterBody*>(
&::tutorial::_ParameterBody_default_instance_);
}
inline ::tutorial::ParameterBody* ExternalMeasurementDataBean::release_parameter() {
// @@protoc_insertion_point(field_release:tutorial.ExternalMeasurementDataBean.parameter)
::tutorial::ParameterBody* temp = parameter_;
parameter_ = nullptr;
return temp;
}
inline ::tutorial::ParameterBody* ExternalMeasurementDataBean::mutable_parameter() {
if (parameter_ == nullptr) {
auto* p = CreateMaybeMessage<::tutorial::ParameterBody>(GetArenaNoVirtual());
parameter_ = p;
}
// @@protoc_insertion_point(field_mutable:tutorial.ExternalMeasurementDataBean.parameter)
return parameter_;
}
inline void ExternalMeasurementDataBean::set_allocated_parameter(::tutorial::ParameterBody* parameter) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete parameter_;
}
if (parameter) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
parameter = ::google::protobuf::internal::GetOwnedMessage(
message_arena, parameter, submessage_arena);
}
} else {
}
parameter_ = parameter;
// @@protoc_insertion_point(field_set_allocated:tutorial.ExternalMeasurementDataBean.parameter)
}
// .tutorial.PredictDataBody predictData = 2;
inline bool ExternalMeasurementDataBean::has_predictdata() const {
return this != internal_default_instance() && predictdata_ != nullptr;
}
inline void ExternalMeasurementDataBean::clear_predictdata() {
if (GetArenaNoVirtual() == nullptr && predictdata_ != nullptr) {
delete predictdata_;
}
predictdata_ = nullptr;
}
inline const ::tutorial::PredictDataBody& ExternalMeasurementDataBean::predictdata() const {
const ::tutorial::PredictDataBody* p = predictdata_;
// @@protoc_insertion_point(field_get:tutorial.ExternalMeasurementDataBean.predictData)
return p != nullptr ? *p : *reinterpret_cast<const ::tutorial::PredictDataBody*>(
&::tutorial::_PredictDataBody_default_instance_);
}
inline ::tutorial::PredictDataBody* ExternalMeasurementDataBean::release_predictdata() {
// @@protoc_insertion_point(field_release:tutorial.ExternalMeasurementDataBean.predictData)
::tutorial::PredictDataBody* temp = predictdata_;
predictdata_ = nullptr;
return temp;
}
inline ::tutorial::PredictDataBody* ExternalMeasurementDataBean::mutable_predictdata() {
if (predictdata_ == nullptr) {
auto* p = CreateMaybeMessage<::tutorial::PredictDataBody>(GetArenaNoVirtual());
predictdata_ = p;
}
// @@protoc_insertion_point(field_mutable:tutorial.ExternalMeasurementDataBean.predictData)
return predictdata_;
}
inline void ExternalMeasurementDataBean::set_allocated_predictdata(::tutorial::PredictDataBody* predictdata) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete predictdata_;
}
if (predictdata) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
predictdata = ::google::protobuf::internal::GetOwnedMessage(
message_arena, predictdata, submessage_arena);
}
} else {
}
predictdata_ = predictdata;
// @@protoc_insertion_point(field_set_allocated:tutorial.ExternalMeasurementDataBean.predictData)
}
// -------------------------------------------------------------------
// PredictDataBody
// string dataStr = 1;
inline void PredictDataBody::clear_datastr() {
datastr_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& PredictDataBody::datastr() const {
// @@protoc_insertion_point(field_get:tutorial.PredictDataBody.dataStr)
return datastr_.GetNoArena();
}
inline void PredictDataBody::set_datastr(const ::std::string& value) {
datastr_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:tutorial.PredictDataBody.dataStr)
}
#if LANG_CXX11
inline void PredictDataBody::set_datastr(::std::string&& value) {
datastr_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:tutorial.PredictDataBody.dataStr)
}
#endif
inline void PredictDataBody::set_datastr(const char* value) {
GOOGLE_DCHECK(value != nullptr);
datastr_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:tutorial.PredictDataBody.dataStr)
}
inline void PredictDataBody::set_datastr(const char* value, size_t size) {
datastr_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:tutorial.PredictDataBody.dataStr)
}
inline ::std::string* PredictDataBody::mutable_datastr() {
// @@protoc_insertion_point(field_mutable:tutorial.PredictDataBody.dataStr)
return datastr_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* PredictDataBody::release_datastr() {
// @@protoc_insertion_point(field_release:tutorial.PredictDataBody.dataStr)
return datastr_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void PredictDataBody::set_allocated_datastr(::std::string* datastr) {
if (datastr != nullptr) {
} else {
}
datastr_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), datastr);
// @@protoc_insertion_point(field_set_allocated:tutorial.PredictDataBody.dataStr)
}
// -------------------------------------------------------------------
// ParameterBody
// string spatialEncoding = 1;
inline void ParameterBody::clear_spatialencoding() {
spatialencoding_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& ParameterBody::spatialencoding() const {
// @@protoc_insertion_point(field_get:tutorial.ParameterBody.spatialEncoding)
return spatialencoding_.GetNoArena();
}
inline void ParameterBody::set_spatialencoding(const ::std::string& value) {
spatialencoding_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:tutorial.ParameterBody.spatialEncoding)
}
#if LANG_CXX11
inline void ParameterBody::set_spatialencoding(::std::string&& value) {
spatialencoding_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:tutorial.ParameterBody.spatialEncoding)
}
#endif
inline void ParameterBody::set_spatialencoding(const char* value) {
GOOGLE_DCHECK(value != nullptr);
spatialencoding_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:tutorial.ParameterBody.spatialEncoding)
}
inline void ParameterBody::set_spatialencoding(const char* value, size_t size) {
spatialencoding_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:tutorial.ParameterBody.spatialEncoding)
}
inline ::std::string* ParameterBody::mutable_spatialencoding() {
// @@protoc_insertion_point(field_mutable:tutorial.ParameterBody.spatialEncoding)
return spatialencoding_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* ParameterBody::release_spatialencoding() {
// @@protoc_insertion_point(field_release:tutorial.ParameterBody.spatialEncoding)
return spatialencoding_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void ParameterBody::set_allocated_spatialencoding(::std::string* spatialencoding) {
if (spatialencoding != nullptr) {
} else {
}
spatialencoding_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), spatialencoding);
// @@protoc_insertion_point(field_set_allocated:tutorial.ParameterBody.spatialEncoding)
}
// string beginTime = 2;
inline void ParameterBody::clear_begintime() {
begintime_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& ParameterBody::begintime() const {
// @@protoc_insertion_point(field_get:tutorial.ParameterBody.beginTime)
return begintime_.GetNoArena();
}
inline void ParameterBody::set_begintime(const ::std::string& value) {
begintime_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:tutorial.ParameterBody.beginTime)
}
#if LANG_CXX11
inline void ParameterBody::set_begintime(::std::string&& value) {
begintime_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:tutorial.ParameterBody.beginTime)
}
#endif
inline void ParameterBody::set_begintime(const char* value) {
GOOGLE_DCHECK(value != nullptr);
begintime_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:tutorial.ParameterBody.beginTime)
}
inline void ParameterBody::set_begintime(const char* value, size_t size) {
begintime_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:tutorial.ParameterBody.beginTime)
}
inline ::std::string* ParameterBody::mutable_begintime() {
// @@protoc_insertion_point(field_mutable:tutorial.ParameterBody.beginTime)
return begintime_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* ParameterBody::release_begintime() {
// @@protoc_insertion_point(field_release:tutorial.ParameterBody.beginTime)
return begintime_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void ParameterBody::set_allocated_begintime(::std::string* begintime) {
if (begintime != nullptr) {
} else {
}
begintime_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), begintime);
// @@protoc_insertion_point(field_set_allocated:tutorial.ParameterBody.beginTime)
}
// string endTime = 3;
inline void ParameterBody::clear_endtime() {
endtime_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& ParameterBody::endtime() const {
// @@protoc_insertion_point(field_get:tutorial.ParameterBody.endTime)
return endtime_.GetNoArena();
}
inline void ParameterBody::set_endtime(const ::std::string& value) {
endtime_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:tutorial.ParameterBody.endTime)
}
#if LANG_CXX11
inline void ParameterBody::set_endtime(::std::string&& value) {
endtime_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:tutorial.ParameterBody.endTime)
}
#endif
inline void ParameterBody::set_endtime(const char* value) {
GOOGLE_DCHECK(value != nullptr);
endtime_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:tutorial.ParameterBody.endTime)
}
inline void ParameterBody::set_endtime(const char* value, size_t size) {
endtime_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:tutorial.ParameterBody.endTime)
}
inline ::std::string* ParameterBody::mutable_endtime() {
// @@protoc_insertion_point(field_mutable:tutorial.ParameterBody.endTime)
return endtime_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* ParameterBody::release_endtime() {
// @@protoc_insertion_point(field_release:tutorial.ParameterBody.endTime)
return endtime_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void ParameterBody::set_allocated_endtime(::std::string* endtime) {
if (endtime != nullptr) {
} else {
}
endtime_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), endtime);
// @@protoc_insertion_point(field_set_allocated:tutorial.ParameterBody.endTime)
}
// string deviceName = 4;
inline void ParameterBody::clear_devicename() {
devicename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& ParameterBody::devicename() const {
// @@protoc_insertion_point(field_get:tutorial.ParameterBody.deviceName)
return devicename_.GetNoArena();
}
inline void ParameterBody::set_devicename(const ::std::string& value) {
devicename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:tutorial.ParameterBody.deviceName)
}
#if LANG_CXX11
inline void ParameterBody::set_devicename(::std::string&& value) {
devicename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:tutorial.ParameterBody.deviceName)
}
#endif
inline void ParameterBody::set_devicename(const char* value) {
GOOGLE_DCHECK(value != nullptr);
devicename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:tutorial.ParameterBody.deviceName)
}
inline void ParameterBody::set_devicename(const char* value, size_t size) {
devicename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:tutorial.ParameterBody.deviceName)
}
inline ::std::string* ParameterBody::mutable_devicename() {
// @@protoc_insertion_point(field_mutable:tutorial.ParameterBody.deviceName)
return devicename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* ParameterBody::release_devicename() {
// @@protoc_insertion_point(field_release:tutorial.ParameterBody.deviceName)
return devicename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void ParameterBody::set_allocated_devicename(::std::string* devicename) {
if (devicename != nullptr) {
} else {
}
devicename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), devicename);
// @@protoc_insertion_point(field_set_allocated:tutorial.ParameterBody.deviceName)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace tutorial
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_external_5fmeasurement_5fdata_2eproto
|
77709f12264ca826304e72412338b8cc0a99e759
|
15d545d0af08dbc091256ef3d591b2d5a5e37656
|
/laboratorio 4 y 5/level05.cpp
|
61bc789b2f5d82b1b5adb1cf6b78fbac92aa60e8
|
[] |
no_license
|
MarvikDC/lenguaje_de_programacion_1_
|
733418e816dd4ff807d94c0ea3ecbfb96fe1eb7f
|
37b639d7630ab96afde2146644a1ae303aa05457
|
refs/heads/master
| 2021-06-04T12:29:19.137694
| 2018-12-08T14:00:25
| 2018-12-08T14:00:25
| 148,730,995
| 1
| 1
| null | 2020-05-14T17:19:44
| 2018-09-14T03:30:38
|
C++
|
UTF-8
|
C++
| false
| false
| 348
|
cpp
|
level05.cpp
|
#include <iostream>
#include<vector>
#include<math.h>
using namespace std;
int g(int& x);
int f(int& x);
void h(int x, int y){
int i=7;
int& r=i;
r=9;
i=10;
cout<<r<<' '<<i<<'\n';
vector<vector<double>>v;
double val = v[f(x)][g(y)];
double& var = v[f(x)][g(y)];
var = var/2+sqrt(var);
}
|
ea3a2b6212eb33d0daf58fe2c5692353fabfdfad
|
0ba2b9e668087c335cac87f610f56a3dff763f69
|
/Software-Render/draw.cpp
|
f7185668c3b5cbfab6ff25bf0c6151cc8bdb84d6
|
[] |
no_license
|
Prakosza/Software-Render
|
bff8c22716c807d9fdaf582a077831a7a6ff2b7a
|
d706031d66193a14a82d43e9ddc2234aa893f0d2
|
refs/heads/master
| 2020-12-30T13:46:24.592804
| 2017-05-27T21:12:40
| 2017-05-27T21:12:40
| 91,252,773
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,526
|
cpp
|
draw.cpp
|
#include "stdafx.h"
#include<iostream>
#include "vecs.h"
#include "tgaimage.h"
#include "vecs.h"
#include "model.h"
#include "draw.h"
void triangle(Vec2<int> a,Vec2<int> b,Vec2<int> c,TGAImage &image, TGAColor &color)
{
int minx=999999,maxx=0,miny=999999,maxy=0;
Vec3<int> produkt;
if(a.x>maxx)
maxx=a.x;
if(a.x<minx)
minx=a.x;
if(a.y>maxy)
maxy=a.y;
if(a.y<miny)
miny=a.y;
if(b.x>maxx)
maxx=b.x;
if(b.x<minx)
minx=b.x;
if(b.y>maxy)
maxy=b.y;
if(b.y<miny)
miny=b.y;
if(c.x>maxx)
maxx=c.x;
if(c.x<minx)
minx=c.x;
if(c.y>maxy)
maxy=c.y;
if(c.y<miny)
miny=c.y;//maks i min
maxx=min(image.get_width(),maxx);
minx=max(0,minx);
maxy=min(image.get_height(),maxy);
miny=max(0,miny);
//cout << minx << " " << maxx << " " << miny << " " << maxy << "\n";
for(;minx<=maxx;minx++)
{
for(int i=miny;i<=maxy;i++)
{
produkt=Vec3<int>::cross(Vec3<int>(b.x-a.x,c.x-a.x,a.x-minx),Vec3<int>(b.y-a.y,c.y-a.y,a.y-i));
if(!( 1-((float) (produkt.x+produkt.y))/produkt.z < 0 || ((float) produkt.x)/produkt.z < 0 || ((float) produkt.y)/produkt.z < 0 ))
{
image.set(minx,i,color);
//cout << minx << " " << i << " " << 1-((float) (produkt.x+produkt.y))/produkt.z << " " << ((float) produkt.x)/produkt.z << " " << ((float) produkt.y)/produkt.z << "\n";
}
}
//cout << minx << " " << maxx << "\n";
}
}
void triangle(Vec3<Vec3<float>> cord,float *zbuffer,TGAImage &image, const Vec3<Vec2<float>> &colors,float intensity,TGAImage &textures)
{
Vec3<float> a=cord.x;Vec3<float> b=cord.y;Vec3<float> c=cord.z;
int minx=999999,maxx=0,miny=999999,maxy=0;
Vec3<float> produkt;
if(a.x>maxx)
maxx=a.x;
if(a.x<minx)
minx=a.x;
if(a.y>maxy)
maxy=a.y;
if(a.y<miny)
miny=a.y;
if(b.x>maxx)
maxx=b.x;
if(b.x<minx)
minx=b.x;
if(b.y>maxy)
maxy=b.y;
if(b.y<miny)
miny=b.y;
if(c.x>maxx)
maxx=c.x;
if(c.x<minx)
minx=c.x;
if(c.y>maxy)
maxy=c.y;
if(c.y<miny)
miny=c.y;
Vec3<Vec2<float>> newColors;
Vec2<float> tex;
maxx=min(image.get_width(),maxx);
minx=max(0,minx);
maxy=min(image.get_height(),maxy);
miny=max(0,miny);
float z;
//cout << minx << " " << maxx << " " << miny << " " << maxy << "\n";
for(;minx<=maxx;minx++)
{
for(int i=miny;i<=maxy;i++)
{
produkt=Vec3<float>::cross(Vec3<float>(b.x-a.x,c.x-a.x,a.x-minx),Vec3<float>(b.y-a.y,c.y-a.y,a.y-i));
produkt=Vec3<float>(1-((produkt.x+produkt.y))/produkt.z,( produkt.x)/produkt.z,(produkt.y)/produkt.z);
if(!(produkt.x < 0 || produkt.y < 0 || produkt.z < 0 ))
{
z=0;
z+=a.z*produkt.x;
z+=b.z*produkt.y;
z+=c.z*produkt.z;
newColors.x=colors.x*produkt.x;
newColors.y=colors.y*produkt.y;
newColors.z=colors.z*produkt.z;
tex=newColors.sum();
//cout << minx << " " << i << " " << produkt.x << " " << produkt.y << " " << produkt.z << " " << tex.x << " " << tex.y << " " <<
if(zbuffer[minx*image.get_height()+i]<z)
{
zbuffer[minx*image.get_height()+i]=z;
image.set(minx,i,textures.get((int) tex.x,(int) tex.y)*intensity);
}
//cout << minx << " " << i << " " << produkt.x << " " << produkt.y << " " << produkt.z << " " << (unsigned int) (newColors.x+newColors.z+newColors.y).r << " " << ( unsigned int) (newColors.x+newColors.z+newColors.y).g << " " << (unsigned int) (newColors.x+newColors.z+newColors.y).b << " " << intensity << "\n";
//cin >> z;
}
}
//cout << minx << " " << maxx << "\n";
}
}
void oldTriangle(Vec2<int> a,Vec2<int> b,Vec2<int> c,TGAImage &image, TGAColor &color)
{
//cout << "in\n";
if(a.y>b.y) swap(a,b);
if(b.y>c.y) swap(b,c);
if(a.y>b.y) swap(a,b);
float dabx=(a.x-b.x);
//cout << "dabx: " << dabx << "\n";
float daby=(b.y-a.y);
// cout << "daby: " << daby << "\n";
float dacx=(a.x-c.x);
//cout << "dacx: " << dacx << "\n";
float dacy=(c.y-a.y);
//cout << "dacy: " << dacy << "\n";
float dbcx=(b.x-c.x);
//cout << "dbcx: " << dbcx << "\n";
float dbcy=(c.y-b.y);
//cout << "dbcy: " << dbcy << "\n";
float dac=dacx/dacy;
//cout << "dac: " << dac << "\n";
float dab=dabx/daby;
// cout << "dab: " << dab << "\n";
float dbc=dbcx/dbcy;
//cout << "dbc: " << dbc << "\n";
float x0,y0,x1,p,e;
int z=0;
x0=c.x; x1=c.x;
//cout << "somehow here\n";
for(y0=c.y;y0>b.y;y0--)
{
//cout << z << " " << y0 << " " << x0 << " " << x1 << "\n";
if(x0<x1)
{
p=(int) x0;
e=(int) x1;
}
else
{
p=(int) x1;
e=(int) x0;
}
for(;p<e;p++)
{
image.set(p,y0,color);
}
x0+=dac;
x1+=dbc;
//string s="output";
//s+=to_string(z);
//s+=+".tga";
//image.write_tga_file(s.c_str());
z++;
}
//cout << "jump\n";
x1=b.x;
for(;y0>=a.y;y0--)
{
//cout << z << " " << y0 << " " << x0 << " " << x1 << "\n";
if(x0<x1)
{
p=(int) x0;
e=(int) x1;
}
else
{
p=(int) x1;
e=(int) x0;
}
for(;p<e;p++)
{
image.set(p,y0,color);
}
x0+=dac;
x1+=dab;
//string s="output";
// s+=to_string(z);
// s+=+".tga";
// image.write_tga_file(s.c_str());
z++;
}
//cout << "out\n";
}
void line(int x0,int x1,int y0,int y1,TGAImage &image, TGAColor color)
{
int dx=abs(x1-x0);
int dy=abs(y1-y0);
bool step=false;
if(dy>dx)
{
swap(x0,y0);
swap(x1,y1);
swap(dx,dy);
step=true;
}
if(x0>x1)
{
swap(x1,x0);
swap(y1,y0);
}
int addery=1;
if(y1<y0)
addery=-1;
int dif=dy*2;
int compdif=dx*2;
int coldif=0;
for(;x0<=x1;x0++)
{//a
if(step)
image.set(y0,x0,color);
else
image.set(x0,y0,color);
coldif+=dif;
if(coldif>dx)
{
coldif-=compdif;
y0+=addery;
}
}
}
|
0d136c5917d62349f723e330885e19c04df818a5
|
44956a1a7dac852c59316c3d7f8d71eb91cb2b91
|
/mainwindow.cpp
|
406554a35c36907eed6560783f2d2db011b9f472
|
[] |
no_license
|
duny31030/Production_System
|
666fbd4babe8010c46f392522bd9b47b6f85f9ad
|
4e582b1a5a644874c12ce3b3e7071b1b5a420e75
|
refs/heads/master
| 2020-05-19T16:41:45.825241
| 2019-05-19T02:20:31
| 2019-05-19T02:20:31
| 185,116,163
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,725
|
cpp
|
mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtGui>
#include <QtWidgets>
#include <QMap>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <string.h>
#include <QString>
#include <QDebug>
#include <QChar>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
init();
ui->setupUi(this);
connect(ui->showKonw, &QPushButton::pressed, this, &MainWindow::showFile);
connect(ui->openKonw, &QPushButton::pressed, this, &MainWindow::openFile);
connect(ui->saveKonw, &QPushButton::pressed, this, &MainWindow::saveFile);
connect(ui->outKonw, &QPushButton::pressed, this, &MainWindow::savetoFile);
// setCentralWidget(ui->showK);
connect(ui->quit, &QPushButton::pressed, this, [=]()
{
int ret = QMessageBox::warning(this, "退出", "确认要退出吗?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if(ret == QMessageBox::Yes){ qApp->quit(); }
}
);
setWindowTitle("动物识别系统 v1.0");
//
// 菜单栏
//
QMenuBar *mBar = menuBar();
setMenuBar(mBar);
// 添加菜单
QMenu *pKnow = mBar->addMenu("知识库");
QMenu *pReson = mBar->addMenu("推理");
QMenu *pAbout = mBar->addMenu("关于作者");
// 知识库
QAction *pShow = pKnow->addAction("显示知识库");
connect(pShow, &QAction::triggered, this, &MainWindow::showFile);
QAction *pOpen = pKnow->addAction("导入知识库");
connect(pOpen, &QAction::triggered, this, &MainWindow::openFile);
QAction *pSave = pKnow->addAction("保存知识库");
connect(pSave, &QAction::triggered, this, &MainWindow::saveFile);
QAction *pOut = pKnow->addAction(tr("导出知识库"));
connect(pOut, &QAction::triggered, this, &MainWindow::savetoFile);
// 推理
QAction *pForward = pReson->addAction("正向推理");
QAction *pReverse = pReson->addAction("反向推理");
connect(pForward, &QAction::triggered, this, &MainWindow::forwardPush);
connect(ui->Forward, &QPushButton::pressed, this, &MainWindow::forwardPush);
connect(pReverse, &QAction::triggered, this, &MainWindow::reversePush);
connect(ui->Reverse, &QPushButton::pressed, this, &MainWindow::reversePush);
// 关于作者
QAction *pAuthor = pAbout->addAction("关于");
QAction *pGit = pAbout->addAction("Github");
QAction *pBlog = pAbout->addAction("Blog");
connect(pAuthor, &QAction::triggered, [=](){QMessageBox::about(this, "关于","产生式系统(动物识别系统)\n\n作者:杜宁元\n版本:v1.0\n联系方式:461336274\n");});
connect(pGit, &QAction::triggered, [=](){openGit();});
connect(pBlog, &QAction::triggered, [=](){openBlog();});
QTextEdit *hit = new QTextEdit(this);
hit->append("<font color=\"#FF0000\">请在左侧文本框内输入对应特征前的序号,使用空格分割。然后点击</font><font color = \"#0000FF\">正向推理</font>");
hit->append(initShow);
(ui->ruleInit)->setWidget(hit);
}
void MainWindow::openGit()
{
QString link = gitHub;
QDesktopServices::openUrl(QUrl(link));
}
void MainWindow::openBlog()
{
QString link = myBlog;
QDesktopServices::openUrl(QUrl(link));
}
void MainWindow::showFile()
{
if(!savePath.isEmpty())
{
QFile file(savePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::warning(this, tr("Read File"), tr("错误,无法打开文件:\n%1 \n请检查目录下是否有对应文件").arg(savePath));
return;
}
QTextStream in(&file);
(ui->showK)->setText(in.readAll());
file.close();
}
else
{
QMessageBox::warning(this, tr("Path"), tr("文件打开过程中出错,请先手动选择导入知识库\n!"));
}
}
void MainWindow::openFile()
{
QString path = QFileDialog::getOpenFileName(this, tr("Open File"), ".", tr("Text Files(*.txt)"));
// qDebug() << path;
savePath = path;
if(!path.isEmpty())
{
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::warning(this, tr("Read File"), tr("错误,无法打开文件:\n%1").arg(path));
return;
}
QTextStream in(&file);
(ui->showK)->setText(in.readAll());
file.close();
}
else
{
QMessageBox::warning(this, tr("Path"), tr("你没有选择任何文件!"));
}
}
void MainWindow::saveFile()
{
if(!savePath.isEmpty())
{
QFile file(savePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::warning(this, tr("Write File"), tr("无法写入到目录:\n%1").arg(savePath));
return;
}
QTextStream out(&file);
out << ui->showK->toPlainText();
file.close();
}
else
{
QMessageBox::warning(this, tr("Path"), tr("保存知识库过程中出错,请手动选择导出知识库."));
}
}
void MainWindow::savetoFile()
{
QString path = QFileDialog::getSaveFileName(this, tr("Save File"), ".", tr("Text Files(*.txt)"));
if(!path.isEmpty())
{
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::warning(this, tr("Write File"), tr("Cannot open file:\n%1").arg(path));
return;
}
QTextStream out(&file);
out << ui->showK->toPlainText();
file.close();
}
else
{
QMessageBox::warning(this, tr("Path"), tr("You did not select any file."));
}
}
void MainWindow::forwardPush()
{
scanStr = (ui->scanRule)->toPlainText();
init2();
scan(scanStr);
reasoning();
Judge_last();
(ui->resonResult)->setPlainText(rst);
}
void MainWindow::reversePush()
{
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::init()
{
m[1] = "有毛发";m[2] = "产奶";m[3] = "有羽毛";m[4] = "不会飞";
m[5] = "会下蛋";m[6] = "吃肉";m[7] = "有犬齿";m[8] = "有爪";
m[9] = "眼盯前方";m[10] = "有蹄";m[11] = "反刍";m[12] = "黄褐色";
m[13] = "有斑点";m[14] = "有黑色条纹";m[15] = "长脖";m[16] = "长腿";
m[17] = "不会飞";m[18] = "会游泳";m[19] = "黑白二色";m[20] = "善飞";
m[21] = "哺乳类";m[22] = "鸟类";m[23] = "食肉类";m[24] = "蹄类";
m[25] = "金钱豹";m[26] = "虎";m[27] = "长颈鹿";m[28] = "斑马";
m[29] = "鸵鸟";m[30] = "企鹅";m[31] = "信天翁";
}
void MainWindow::init2()
{
for(int i = 1;i < 32;i++) m2[i] = 0;
}
void MainWindow::scan(QString str)
{
std::string st = str.toStdString();
st += " ";
int len = st.length();
int tmp = 0;
for(int i = 0;i < len;i++)
{
if(st[i] == ' ')
{
qDebug() << m[tmp];
if(tmp) m2[tmp] = 1;
tmp = 0;
}
else
{
tmp = tmp*10+st[i]-'0';
}
}
}
void MainWindow::reasoning()
{
QString tmp;
if(!m2[21])
{
if(m2[1])
{
tmp += (m[1] + "->" + m[21] + "\n"); m2[21] = 1;
}
else
{
if(m2[2])
{
tmp += (m[2] + "->" + m[21] + "\n"); m[21] = 1;
}
else
{
if(m2[6])
{
tmp += (m[6] + "->" + m[21] + "\n"); m2[21] = 1;
}
else
{
if(m2[10])
{
tmp += (m[6] + "->" + m[21] + "\n"); m2[21] = 1;
}
}
}
}
}
if(m2[3] && !m2[22])
{
tmp += (m[3] + "->" + m[22] + "\n"); m2[22] = 1;
}
if(m2[7] && m2[8] && m2[9] && !m2[23])
{
tmp += (m[7] + "," + m[8] + "," + m[9] + "->" + m[23] + "\n"); m2[23] = 1;
}
if(m2[11] && m2[21] && !m2[24])
{
tmp += (m[11] + "," + m[21] + "->" + m[24] + "\n"); m2[24] = 1;
}
rst += ("推理过程如下:\n"+ tmp);
}
void MainWindow::Judge_last()
{
bool flag = 0;
// 信天翁
if(m2[20] && m2[22])
{
prin(20,22,31); prin2(31); flag = 1;
}
// 鸵鸟
if(m2[4] && m2[22] && m2[15] && m2[16])
{
prin(4,22,15,16,29); prin2(29); flag = 1;
}
// 企鹅
if(m2[4] && m2[22] && m2[18] && m2[19])
{
prin(4,22,18,19,30); prin2(30); flag = 1;
}
// 金钱豹
if(m2[23] && m2[12] && m2[21] && m2[13])
{
prin(23,12,21,13,25); prin2(25); flag = 1;
}
// 虎
if(m2[23] && m2[12] && m2[21] && m2[13])
{
prin(23,13,21,14,26); prin2(26); flag = 1;
}
// 斑马
if(m2[14] && m2[24])
{
prin(14,24,28); prin2(28); flag = 1;
}
// 长颈鹿
if(m2[24] && m2[13] && m2[15] && m2[16])
{
prin(24,13,15,16,27); prin2(27); flag = 1;
}
if(!flag)
{
rst += "根据所给条件无法判断为何种动物\n";
}
}
void MainWindow::prin(int a,int b,int c,int d,int e)
{
if(c == 0)
{
rst += (m[a] + "->" + m[b] + "\n");
}
else
{
if(d == 0)
{
rst += (m[a] + "," + m[b] + "->" + m[c] + "\n");
}
else
{
if(e == 0)
{
rst += (m[a] + "," + m[b] + "," + m[c] + "->" + m[d] + "\n");
}
else
{
rst += (m[a] + "," + m[b] + "," + m[c] + "," + m[d] + "->" + m[e] + "\n");
}
}
}
}
void MainWindow::prin2(int a)
{
rst += ("所识别动物为" + m[a] + "\n");
}
|
8efd8e0061decc89608c5630d0e60bf7492e0dbc
|
bb73c18c5873e9af485b8d82a6d70536297cbf10
|
/tests/common/registeredgadget2.cpp
|
d4b40e95554b59fd4915ca3c4576632640db76a4
|
[
"Apache-2.0"
] |
permissive
|
SnowMoon-Dev/underline
|
a229b2d5bea5c09a0642d9b9cbc1502e54e12cad
|
ae3f5a225e3f6e896bf9cf4d6ce3bd68be2d250f
|
refs/heads/master
| 2022-02-14T17:19:51.946605
| 2019-07-14T05:12:19
| 2019-07-14T05:12:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 433
|
cpp
|
registeredgadget2.cpp
|
#include <QCoreApplication>
#include "registeredgadget.h"
#include "underline.h"
#include "registeredgadget2.h"
RegisteredGadget2::RegisteredGadget2()
{
}
QList<RegisteredGadget> RegisteredGadget2::list() const
{
return m_list;
}
void RegisteredGadget2::setList(const QList<RegisteredGadget> &list)
{
m_list = list;
}
static void init() {
_::registerQtType<RegisteredGadget2>();
}
Q_COREAPP_STARTUP_FUNCTION(init);
|
a7bf7fe10dac1e82d79e6755fa42524d091ede1a
|
1213bcf770a94a89b39be8dc7b99a3f7e35fd369
|
/src/alloy/compiler/passes/simplification_pass.h
|
19e1023fbbca2f9458efb51d40faced116cec147
|
[] |
no_license
|
wtfaremyinitials/xenia
|
c86e4625a1dd084d97d44c3242e2faf208bca2b8
|
16b3ecd5897051f82bc236ad9a4d0ab5cab22e87
|
refs/heads/master
| 2020-12-31T02:43:53.168712
| 2014-01-14T22:06:05
| 2014-01-14T22:06:05
| 15,918,955
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,232
|
h
|
simplification_pass.h
|
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#ifndef ALLOY_COMPILER_PASSES_SIMPLIFICATION_PASS_H_
#define ALLOY_COMPILER_PASSES_SIMPLIFICATION_PASS_H_
#include <alloy/compiler/compiler_pass.h>
namespace alloy {
namespace compiler {
namespace passes {
class SimplificationPass : public CompilerPass {
public:
SimplificationPass();
virtual ~SimplificationPass();
virtual int Run(hir::HIRBuilder* builder);
private:
void EliminateConversions(hir::HIRBuilder* builder);
void CheckTruncate(hir::Instr* i);
void CheckByteSwap(hir::Instr* i);
void SimplifyAssignments(hir::HIRBuilder* builder);
hir::Value* CheckValue(hir::Value* value);
};
} // namespace passes
} // namespace compiler
} // namespace alloy
#endif // ALLOY_COMPILER_PASSES_SIMPLIFICATION_PASS_H_
|
a1acca2de0c1eb739ad6dc65f17517cd39d01055
|
73397c5d441334a7fc80cbfb3885343a664e5f3a
|
/wam_dir/devel/.private/wam_srvs/include/wam_srvs/OrtnMove.h
|
0d118b234a554264ca85ddd83735adb8e2003697
|
[] |
no_license
|
shardrv/RobotArm
|
17d827a4bd32f77f642bfe3b2fa22e627a6d456f
|
6d1aa7ed9cc02517aea4f626d39b8ba9eac7468f
|
refs/heads/master
| 2020-08-09T03:42:26.453931
| 2020-02-11T19:39:01
| 2020-02-11T19:39:01
| 213,982,341
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,537
|
h
|
OrtnMove.h
|
// Generated by gencpp from file wam_srvs/OrtnMove.msg
// DO NOT EDIT!
#ifndef WAM_SRVS_MESSAGE_ORTNMOVE_H
#define WAM_SRVS_MESSAGE_ORTNMOVE_H
#include <ros/service_traits.h>
#include <wam_srvs/OrtnMoveRequest.h>
#include <wam_srvs/OrtnMoveResponse.h>
namespace wam_srvs
{
struct OrtnMove
{
typedef OrtnMoveRequest Request;
typedef OrtnMoveResponse Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
}; // struct OrtnMove
} // namespace wam_srvs
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::wam_srvs::OrtnMove > {
static const char* value()
{
return "86f723fe9a4be8979be87cd065276584";
}
static const char* value(const ::wam_srvs::OrtnMove&) { return value(); }
};
template<>
struct DataType< ::wam_srvs::OrtnMove > {
static const char* value()
{
return "wam_srvs/OrtnMove";
}
static const char* value(const ::wam_srvs::OrtnMove&) { return value(); }
};
// service_traits::MD5Sum< ::wam_srvs::OrtnMoveRequest> should match
// service_traits::MD5Sum< ::wam_srvs::OrtnMove >
template<>
struct MD5Sum< ::wam_srvs::OrtnMoveRequest>
{
static const char* value()
{
return MD5Sum< ::wam_srvs::OrtnMove >::value();
}
static const char* value(const ::wam_srvs::OrtnMoveRequest&)
{
return value();
}
};
// service_traits::DataType< ::wam_srvs::OrtnMoveRequest> should match
// service_traits::DataType< ::wam_srvs::OrtnMove >
template<>
struct DataType< ::wam_srvs::OrtnMoveRequest>
{
static const char* value()
{
return DataType< ::wam_srvs::OrtnMove >::value();
}
static const char* value(const ::wam_srvs::OrtnMoveRequest&)
{
return value();
}
};
// service_traits::MD5Sum< ::wam_srvs::OrtnMoveResponse> should match
// service_traits::MD5Sum< ::wam_srvs::OrtnMove >
template<>
struct MD5Sum< ::wam_srvs::OrtnMoveResponse>
{
static const char* value()
{
return MD5Sum< ::wam_srvs::OrtnMove >::value();
}
static const char* value(const ::wam_srvs::OrtnMoveResponse&)
{
return value();
}
};
// service_traits::DataType< ::wam_srvs::OrtnMoveResponse> should match
// service_traits::DataType< ::wam_srvs::OrtnMove >
template<>
struct DataType< ::wam_srvs::OrtnMoveResponse>
{
static const char* value()
{
return DataType< ::wam_srvs::OrtnMove >::value();
}
static const char* value(const ::wam_srvs::OrtnMoveResponse&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // WAM_SRVS_MESSAGE_ORTNMOVE_H
|
bbc9d093535923050e3a2d3b0fbad8fb5ac67cac
|
03685ac2a6c0a7b9bef79616b827774a23a0c367
|
/server/include/head_controller.h
|
6ed02099213ad4a406f4f54bfa5b76eeef67f65f
|
[
"MIT"
] |
permissive
|
jenny5-robot/jenny5-html5
|
99370e30894833531a5f6aaa18629f0c764961df
|
b23ab10d6a0896cbf8d7c5728fa6fdb4b4327e9c
|
refs/heads/master
| 2020-12-30T16:15:59.607396
| 2019-10-17T17:10:59
| 2019-10-17T17:10:59
| 90,975,811
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,019
|
h
|
head_controller.h
|
// Author: Mihai Oltean, https://mihaioltean.github.io, mihai.oltean@gmail.com
// More details: https://jenny5.org, https://jenny5-robot.github.io/
// Source code: github.com/jenny5-robot
// License: MIT
// ---------------------------------------------------------------------------
#ifndef head_controller_H
#define head_controller_H
#include <opencv2\objdetect\objdetect.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include "scufy_lib.h"
#define HEAD_MOTOR_NECK 0
#define HEAD_MOTOR_FACE 1
#define HEAD_POTENTIOMETER_NECK_INDEX 0
#define HEAD_POTENTIOMETER_FACE_INDEX 1
#define HEAD_ULTRASONIC_FACE_INDEX 0
#define HEAD_CAMERA_INDEX 0
// head
#define _head_horizontal_motor_potentiometer_min 160
#define _head_horizontal_motor_potentiometer_max 730
#define _head_horizontal_motor_potentiometer_home 460
#define _head_vertical_motor_potentiometer_min 332
#define _head_vertical_motor_potentiometer_max 832
#define _head_vertical_motor_potentiometer_home 515
#define HEAD_MOTOR_GEAR_REDUCTION 27
#define HEAD_RADIUS_TO_REVERT 70
#define HEAD_RADIUS_TOLERANCE 20
#define CAM_PIXELS_TOLERANCE 100
#define CANNOT_CONNECT_TO_JENNY5_HEAD_STR "CANNOT_CONNECT_TO_JENNY5_HEAD\n"
#define CANNOT_CONNECT_TO_JENNY5_HEAD_ERROR 1
#define Head_does_not_respond_STR "Head does not respond! Game over!\n"
#define Head_does_not_respond_ERROR 2
#define CANNOT_CONNECT_TO_HEAD_CAMERA_STR "CANNOT_CONNECT_TO_HEAD_CAMERA\n"
#define CANNOT_CONNECT_TO_HEAD_CAMERA_ERROR 3
#define CANNOT_WRITE_HEAD_CAMERA_IMAGE_TO_DISK_STR "CANNOT_WRITE_HEAD_CAMERA_IMAGE_TO_DISK\n"
#define CANNOT_WRITE_HEAD_CAMERA_IMAGE_TO_DISK_ERROR 4
#define CANNOT_CAPTURE_IMAGE_FROM_HEAD_CAMERA 5
#define NOT_CONNECTED_TO_HE
#define Connected_to_head_STR "Connected to head\n"
//-------------------------------------------------------------
class t_head_controller {
public:
cv::VideoCapture cam;
t_scufy_lib head_arduino_controller;
t_head_controller();
int connect(const char* port);
bool is_connected(void);
void disconnect(void);
bool setup(char* error_string);
void send_get_arduino_firmware_version(void);
void send_get_sensors_value(void);
void send_home_all(void);
void send_neck_home(void);
void send_face_home(void);
void send_neck_to_sensor_position(int head_neck_new_position);
void send_face_to_sensor_position(int head_face_new_position);
void send_HEAD_MOTOR_NECK_move(int num_steps/*, int speed, int accelleration*/);
void send_HEAD_MOTOR_FACE_move(int num_steps/*, int speed, int accelleration*/);
void send_stop_motor(int motor_index);
void send_stop_motors(void);
// send home and blocks until returns
bool home_all_motors(char* error_string);
void send_disable_motors(void);
const char *error_to_string(int error);
bool open_camera(void);
void release_camera(void);
int capture_camera_and_save_to_disk(const char *file_name);
int capture_camera_save_to_disk_and_release(const char *file_name);
};
extern t_head_controller jenny5_head_controller;
#endif
|
2db58c43ab1b1086145cfa1b25a42df242b053c0
|
d6c0360526df8cc1760ca9465a3bb8a7ef26b445
|
/ptree/ptree.cpp
|
61cba6e9dcfba7c6b8996a58e37af988b8e8e339
|
[] |
no_license
|
alekseibutiaev/experience
|
44eda6a54e24abeca16291d6885970c88d34f7c2
|
354dc415d937996842a37cd8f215b60a8ae8115e
|
refs/heads/master
| 2023-08-17T15:09:18.318428
| 2023-08-12T17:53:40
| 2023-08-12T17:53:40
| 109,396,253
| 2
| 0
| null | 2022-05-20T20:48:40
| 2017-11-03T13:03:20
|
C
|
UTF-8
|
C++
| false
| false
| 3,195
|
cpp
|
ptree.cpp
|
// ptree.cpp : Defines the entry point for the console application.
//
#if defined( WIN32 ) || defined( WIN64 )
#include "stdafx.h"
#endif
#include <cassert>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#if 0
void camera_config::load_config( const std::string& f_configure ) {
try {
boost::property_tree::ptree pt;
boost::property_tree::read_xml( f_configure, pt );
for( boost::property_tree::ptree::const_iterator it = pt.begin(); it != pt.end(); it++ )
std::cout << "Here " << it->first << " " << std::endl;
BOOST_FOREACH( boost::property_tree::ptree::value_type& p1, pt.get_child( "fast_camera.config" ) ) {
boost::property_tree::ptree& p = p1.second.get_child( "<xmlattr>" );
axis_x_min = p.get< float >( "axis_x_min" );
axis_x_max = p.get< float >( "axis_x_max" );
axis_x_scene_zero = p.get< float >( "axis_x_scene_zero" );
axis_x_scene_range = p.get< float >( "axis_x_scene_range" );
axis_y_min = p.get< float >( "axis_y_min" );
axis_y_max = p.get< float >( "axis_y_max" );
axis_y_scene_zero = p.get< float >( "axis_y_scene_zero" );
axis_y_scene_range = p.get< float >( "axis_y_scene_range" );
axis_z_min = p.get< float >( "axis_z_min" );
axis_z_max = p.get< float >( "axis_z_max" );
axis_z_scene_zero = p.get< float >( "axis_z_scene_zero" );
axis_z_scene_range = p.get< float >( "axis_z_scene_range" );
axis_dist_min = p.get< float >( "axis_dist_min" );
axis_dist_max = p.get< float >( "axis_dist_max" );
axis_dist_scene_zero = p.get< float >( "axis_dist_scene_zero" );
axis_dist_scene_range = p.get< float >( "axis_dist_scene_range" );
}
}
catch( const boost::property_tree::ptree_error& e ) {
std::cerr << e.what() << std::endl;
}
return;
}
#endif
const char* file = "fast_camera.xml";
#if defined( WIN32 ) || defined( WIN64 )
int _tmain( int ac, _TCHAR* av[] ) {
#else
int main( int ac, char* av[] ) {
#endif
try {
boost::property_tree::ptree pt;
boost::property_tree::read_xml( file, pt );
for( boost::property_tree::ptree::const_iterator it = pt.begin(); it != pt.end(); it++ ) {
std::cout << "Here " << it->first << " " << std::endl;
for( boost::property_tree::ptree::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++ ) {
std::cout << "Here1 " << it1->first << " " << std::endl;
for( boost::property_tree::ptree::const_iterator it2 = it1->second.begin(); it2 != it1->second.end(); it2++ ) {
std::cout << "Here2 " << it2->first << " " << std::endl;
if( "property" == it2->first ) {
const boost::property_tree::ptree& p = it2->second.get_child( "<xmlattr>" );
std::cout << "" << p.get< int >( "axis_x_min" ) << std::endl;
}
}
}
}
}
catch( const boost::property_tree::ptree_error& e ) {
std::cerr << e.what() << std::endl;
}
return 0;
}
|
f596e128211042fd027971879bdff648e4344872
|
f6d541fd92ace6e4f6bd34fa218216b6b64ccb2e
|
/AmandasUtilityLibrary/Public/aul/rw_recursive_mutex.h
|
f944eeff20b8e3b0fafb6486c951781d8e684775
|
[] |
no_license
|
ameythaler/AmandasUtilityLibrary
|
478ab23158c35f39b22ccccec20a0bb691a68889
|
1b5ad368a105bd31b608bfcd264814bee5f11b1a
|
refs/heads/master
| 2021-07-14T19:39:40.634605
| 2019-03-22T05:43:26
| 2019-03-22T05:43:26
| 167,513,284
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,001
|
h
|
rw_recursive_mutex.h
|
#pragma once
#if AUL_MSVC
#include "Windows.h"
#elif AUL_STD
#include <mutex>
#endif // AUL_MSVC
#include <atomic>
#include "aul/lockable.h"
#include "aul/synchronizer.h"
namespace aul
{
class rw_recursive_mutex : public rw_lockable
{
public:
rw_recursive_mutex();
#if AUL_MSVC
~rw_recursive_mutex() { DeleteCriticalSection(&_writelock); }
#endif // AUL_MSVC
virtual void lock_read();
virtual void lock_write();
virtual void unlock_read();
virtual void unlock_write();
inline virtual uint32_t get_readlock_count() const { return _read_count; }
inline virtual bool is_writelocked() const { return _writelock_count > 0; }
private:
#if AUL_MSVC
CRITICAL_SECTION _writelock;
#elif AUL_STD
std::recursive_mutex _writelock;
#endif // AUL_MSVC
synchronizer _waitlock;
std::atomic<uint32_t> _read_count;
std::atomic<uint32_t> _writelock_count;
};
}
#include "aul/scope_lock.h"
|
43c844d131d94b95bcbbd0c25e8c816da2ef3528
|
51fd60e6b377e7150dfd0b5f56f5314a79e38aad
|
/src/emu/console.cpp
|
7a39b30c9ea6fbf768526493c0442728e35779ac
|
[] |
no_license
|
fsword7/mse.old
|
106d32598f64854401577d36eaab526cb22186eb
|
27ed81142845b930ff1b6746cc16fc60479ef11e
|
refs/heads/master
| 2022-03-08T21:00:27.821539
| 2019-10-29T02:52:51
| 2019-10-29T02:52:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,367
|
cpp
|
console.cpp
|
#include "emu/emucore.h"
#include "emu/commands.h"
std::vector<std::string> split(std::string const &line)
{
std::istringstream buffer(line);
std::vector<std::string> ret;
std::copy(std::istream_iterator<std::string>(buffer),
std::istream_iterator<std::string>(),
std::back_inserter(ret));
return ret;
}
console_base::console_base()
//: cdev(dev), sdev(nullptr)
{
}
console_base::~console_base()
{
}
void console_base::printf(const char *format, ...) const
{
char out[2048];
va_list args;
va_start(args, format);
vsprintf(out, format, args);
fflush(stdout);
std::cout << out;
// All done, release arguments.
va_end(args);
}
void console_base::prompt()
{
command_handler cmd;
std::string cmdLine;
args_t args;
cmdStatus st = cmdOk;
while(st == cmdOk) {
std::cout << "mse> ";
std::getline(std::cin, cmdLine);
// std::cout << "Entered line: " << cmdLine << std::endl;
st = cmd.execute(this, cmdLine);
if (st == cmdInvalid) {
std::cerr << "Invalid command" << std::endl;
st = cmdOk;
}
}
}
void console_base::script(std::string fname)
{
// std::ifstream in;
// std::string cmdLine;
// args_t args;
// int lineno = 0;
// int rc;
// in.exceptions(std::ifstream::failbit | std::ifstream::badbit);
// try {
// in.open(fname);
//
// while(!in.eof()) {
// std::getline(in, cmdLine);
// lineno++;
//
// if (cmdLine[0] == '#' || cmdLine[0] == ';')
// continue;
//
// args = split(cmdLine);
// if (args.size() == 0)
// continue;
//
// rc = executeCommand(args);
// if (rc != CMD_OK) {
// std::cout.flush();
// std::cerr << lineno << ": " << cmdLine << std::endl;
//
// switch (rc) {
// case CMD_NOTFOUND:
// std::cerr << cdev->getName() << ": Unknown command "
// << args[0] << " at line " << lineno << std::endl;
// break;
//
// default:
// std::cerr << cdev->getName() << ": Command error at line "
// << lineno << std::endl;
// break;
// }
// }
// }
//
// in.close();
// }
//
// catch (std::system_error& e) {
// std::cout.flush();
// std::cerr << "File '" << fname << "' error: " << e.code().message() << std::endl;
// return;
// }
}
|
1a0fdb815df463d3b69cfe63f3518943bc74b3d3
|
318f4c88ea77251660e7dbee9182ca138d7b95d9
|
/Cplusplus/isCousins.cpp
|
117080f8f4c026ebf43a77334ce7fe23b629a45d
|
[] |
no_license
|
Sahil12S/LeetCode
|
b1548aec56c7eb30139b0f2975329c6ed9034379
|
5a9916827e969cd4adbc394779e1bb3ba576f6e2
|
refs/heads/master
| 2021-06-02T07:39:00.503814
| 2020-09-23T03:21:53
| 2020-09-23T03:21:53
| 145,740,842
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,027
|
cpp
|
isCousins.cpp
|
/**
* In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
* Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
* We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
* Return true if and only if the nodes corresponding to the values x and y are cousins.
*/
#include <vector>
#include <queue>
/**
* Definition for a binary tree node.
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
/* RECURSION
class Solution
{
TreeNode *helper(TreeNode *node, int val, int curr_height, int &height)
{
if (!node)
{
return nullptr;
}
if ((node->left && node->left->val == val) || (node->right && node->right->val == val))
{
height = curr_height;
// cout << height << endl;
return node;
}
TreeNode *left = helper(node->left, val, curr_height + 1, height);
if (left)
return left;
TreeNode *right = helper(node->right, val, curr_height + 1, height);
if (right)
return right;
return nullptr;
}
public:
bool isCousins(TreeNode *root, int x, int y)
{
int x_d = 0;
int y_d = 0;
TreeNode *first = helper(root, x, 1, x_d);
TreeNode *second = helper(root, y, 1, y_d);
// cout << x_d << " " << y_d << '\n';
return (x_d == y_d && first != second);
}
};
*/
///* BFS
class Solution
{
public:
bool isCousins(TreeNode *root, int x, int y)
{
if (root == nullptr)
{
return false;
}
if (root->val == x || root->val == y)
{
return false;
}
std::vector<TreeNode *> parents;
std::queue<TreeNode *> q;
q.push(root);
while (!q.empty() && parents.size() != 2)
{
int width = q.size();
while (width && parents.size() != 2)
{
TreeNode *curr = q.front();
q.pop();
if (curr->left)
{
if (curr->left->val == x || curr->left->val == y)
{
parents.emplace_back(curr);
}
q.push(curr->left);
}
if (curr->right)
{
if (curr->right->val == x || curr->right->val == y)
{
parents.emplace_back(curr);
}
q.push(curr->right);
}
width--;
}
// If we only found one value on current level
if (parents.size() == 1)
{
return false;
}
}
return parents[0] != parents[1];
}
};
//*/
|
b299b6e9e5f2135721a895baca43be7873461c35
|
d6f21c8a208d74be24f274bcb3a701a2da7a9494
|
/src/gl/Object.hpp
|
e4491cdae2f608d2883fe6d42b39fa6a8ff9c303
|
[] |
no_license
|
hstefan/HelloTriangle
|
9af76043bde472febd84d7544a7132644382a984
|
047c49d4a0603c9d3262b7b03b84d7a80adcaa8a
|
refs/heads/master
| 2016-09-10T03:28:56.175689
| 2013-12-28T04:57:58
| 2013-12-28T04:57:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 279
|
hpp
|
Object.hpp
|
#pragma once
#include <GL3/gl3w.h>
namespace gl
{
template <class T = GLuint>
class Object
{
public:
inline const T& identifier() const;
protected:
T _id;
};
template <class T>
inline const T& Object<T>::identifier() const
{
return _id;
}
}
|
c5ceeec87c3c77ece32e2a9341b9e9c0e610fdba
|
b0899eb26a5213f7d86b5f8be60f1e8dc7db6d03
|
/include/AmbientOcclusion.h
|
4809a175f9e0b68354acac60b2df324c7dd99434
|
[] |
no_license
|
redclock/GIEngine
|
bbdb440fa0d1ded2233ce728083c7c5ae5114f65
|
0c95238e6b3f81a27eccca6f2c97a0e5f3c08580
|
refs/heads/master
| 2021-01-23T10:44:50.191656
| 2014-06-30T03:25:37
| 2014-06-30T03:25:37
| 21,327,591
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,234
|
h
|
AmbientOcclusion.h
|
#pragma once
#include <d3dx9.h>
#include "Point3.h"
#include "DynamicTexture.h"
class CDeferredShade;
class CAmbientOcclusion
{
private:
LPD3DXEFFECT m_effect;
CDynamicTexture m_texRandom;
CDynamicTexture m_texSSRandom;
UINT m_samples;
UINT m_patternCount;
void CreateRandomTexture(UINT samples, UINT count);
public:
CAmbientOcclusion();
~CAmbientOcclusion();
void SetEnvMap(LPDIRECT3DTEXTURE9 tex);
void RenderAO(UINT width, UINT height, CDeferredShade& defer,
const Point3& eyepos, float radius);
void RenderDirect(UINT width, UINT height, CDeferredShade& defer,
const Point3& eyepos, LPDIRECT3DTEXTURE9 texLight, int lightCount,
float lightOffsetU, float lightOffsetV);
void SetLightRotMat(const D3DXMATRIX& mat);
void RenderDiffuse(UINT width, UINT height, CDeferredShade& defer,
LPDIRECT3DTEXTURE9 texDiffuse);
void RenderDirectSplit(UINT width, UINT height, UINT gridw, UINT gridh,
CDeferredShade& defer, LPDIRECT3DTEXTURE9 texPos, const Point3& eyepos, float radius,
LPDIRECT3DTEXTURE9 texLight, int lightCount,
float lightOffsetU, float lightOffsetV);
};
|
1b3b36a8b59dec5a0ed8c97761a4cbd7de81ed1b
|
05600d518eff5fb576db96f9b1f75c85a31dae54
|
/Testing/Testing.ino
|
7e5ee810ecb0e0d0756d2577248c14e5dc387a93
|
[] |
no_license
|
chattah/Arduino-Testing
|
244e452fce1da6d1d165cb42fb4108485af80b26
|
f98f8ed127d28b52e04ad5e5c080b744416f3ad8
|
refs/heads/master
| 2021-01-01T04:59:10.773851
| 2017-07-15T02:31:47
| 2017-07-15T02:31:47
| 97,285,143
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 463
|
ino
|
Testing.ino
|
/*
Name: Testing.ino
Created: 7/14/2017 8:43:19 PM
Author: JoelL
*/
int led = 13;
// the setup function runs once when you press reset or power the board
void setup() {
pinMode(led, OUTPUT);
}
// the loop function runs over and over again until power down or reset
void loop() {
Serial.println("ON");
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
Serial.println("OFF");
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}
|
d56605e32e5b44a9ce55988f7a8e52664735f9bf
|
5722258ec3ce781cd5ec13e125d71064a67c41d4
|
/java/util/stream/LongStreamProxy.cpp
|
7c7b9f8cde412dcd89c10667a9da83d4a6a9dcea
|
[] |
no_license
|
ISTE-SQA/HamsterJNIPP
|
7312ef3e37c157b8656aa10f122cbdb510d53c2f
|
b29096d0baa9d93ec0aa21391b5a11b154928940
|
refs/heads/master
| 2022-03-19T11:27:03.765328
| 2019-10-24T15:06:26
| 2019-10-24T15:06:26
| 216,854,309
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,065
|
cpp
|
LongStreamProxy.cpp
|
#include "net/sourceforge/jnipp/JNIEnvHelper.h"
#include "LongStreamProxy.h"
// includes for parameter and return type proxy classes
#include "java\util\function\LongPredicateProxy.h"
#include "java\util\function\SupplierProxy.h"
#include "java\util\function\ObjLongConsumerProxy.h"
#include "java\util\function\BiConsumerProxy.h"
#include "java\lang\ObjectProxy.h"
#include "java\util\LongSummaryStatisticsProxy.h"
#include "java\util\OptionalDoubleProxy.h"
#include "java\util\OptionalLongProxy.h"
#include "java\util\function\LongBinaryOperatorProxy.h"
#include "java\util\PrimitiveIterator_OfLongProxy.h"
#include "java\util\Spliterator_OfLongProxy.h"
#include "java\util\stream\DoubleStreamProxy.h"
#include "java\util\function\LongToDoubleFunctionProxy.h"
#include "java\util\function\LongToIntFunctionProxy.h"
#include "java\util\stream\IntStreamProxy.h"
#include "java\util\function\LongFunctionProxy.h"
#include "java\util\function\LongUnaryOperatorProxy.h"
#include "java\util\function\LongConsumerProxy.h"
#include "java\util\stream\StreamProxy.h"
#include "java\util\function\LongSupplierProxy.h"
#include "java\util\stream\LongStream_BuilderProxy.h"
using namespace net::sourceforge::jnipp;
using namespace java::util::stream;
std::string LongStreamProxy::className = "java/util/stream/LongStream";
jclass LongStreamProxy::objectClass = NULL;
jclass LongStreamProxy::_getObjectClass()
{
if ( objectClass == NULL )
objectClass = static_cast<jclass>( JNIEnvHelper::NewGlobalRef( JNIEnvHelper::FindClass( className.c_str() ) ) );
return objectClass;
}
LongStreamProxy::LongStreamProxy(void* unused)
{
}
jobject LongStreamProxy::_getPeerObject() const
{
return peerObject;
}
jclass LongStreamProxy::getObjectClass()
{
return _getObjectClass();
}
LongStreamProxy::operator jobject()
{
return _getPeerObject();
}
// constructors
LongStreamProxy::LongStreamProxy(jobject obj)
{
peerObject = JNIEnvHelper::NewGlobalRef( obj );
}
LongStreamProxy::~LongStreamProxy()
{
JNIEnvHelper::DeleteGlobalRef( peerObject );
}
LongStreamProxy& LongStreamProxy::operator=(const LongStreamProxy& rhs)
{
JNIEnvHelper::DeleteGlobalRef( peerObject );
peerObject = JNIEnvHelper::NewGlobalRef( rhs.peerObject );
return *this;
}
// methods
jboolean LongStreamProxy::allMatch(::java::util::function::LongPredicateProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "allMatch", "(Ljava/util/function/LongPredicate;)Z" );
return JNIEnvHelper::CallBooleanMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) );
}
jboolean LongStreamProxy::anyMatch(::java::util::function::LongPredicateProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "anyMatch", "(Ljava/util/function/LongPredicate;)Z" );
return JNIEnvHelper::CallBooleanMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) );
}
jboolean LongStreamProxy::noneMatch(::java::util::function::LongPredicateProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "noneMatch", "(Ljava/util/function/LongPredicate;)Z" );
return JNIEnvHelper::CallBooleanMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) );
}
::java::lang::ObjectProxy LongStreamProxy::collect(::java::util::function::SupplierProxy p0, ::java::util::function::ObjLongConsumerProxy p1, ::java::util::function::BiConsumerProxy p2)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "collect", "(Ljava/util/function/Supplier;Ljava/util/function/ObjLongConsumer;Ljava/util/function/BiConsumer;)Ljava/lang/Object;" );
return ::java::lang::ObjectProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ), static_cast<jobject>( p1 ), static_cast<jobject>( p2 ) ) );
}
::java::util::LongSummaryStatisticsProxy LongStreamProxy::summaryStatistics()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "summaryStatistics", "()Ljava/util/LongSummaryStatistics;" );
return ::java::util::LongSummaryStatisticsProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::OptionalDoubleProxy LongStreamProxy::average()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "average", "()Ljava/util/OptionalDouble;" );
return ::java::util::OptionalDoubleProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::OptionalLongProxy LongStreamProxy::findAny()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "findAny", "()Ljava/util/OptionalLong;" );
return ::java::util::OptionalLongProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::OptionalLongProxy LongStreamProxy::findFirst()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "findFirst", "()Ljava/util/OptionalLong;" );
return ::java::util::OptionalLongProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::OptionalLongProxy LongStreamProxy::max()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "max", "()Ljava/util/OptionalLong;" );
return ::java::util::OptionalLongProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::OptionalLongProxy LongStreamProxy::min()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "min", "()Ljava/util/OptionalLong;" );
return ::java::util::OptionalLongProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::OptionalLongProxy LongStreamProxy::reduce(::java::util::function::LongBinaryOperatorProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "reduce", "(Ljava/util/function/LongBinaryOperator;)Ljava/util/OptionalLong;" );
return ::java::util::OptionalLongProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) ) );
}
::java::util::PrimitiveIterator_OfLongProxy LongStreamProxy::iterator()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "iterator", "()Ljava/util/PrimitiveIterator$OfLong;" );
return ::java::util::PrimitiveIterator_OfLongProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::Spliterator_OfLongProxy LongStreamProxy::spliterator()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "spliterator", "()Ljava/util/Spliterator$OfLong;" );
return ::java::util::Spliterator_OfLongProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::stream::DoubleStreamProxy LongStreamProxy::asDoubleStream()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "asDoubleStream", "()Ljava/util/stream/DoubleStream;" );
return ::java::util::stream::DoubleStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::stream::DoubleStreamProxy LongStreamProxy::mapToDouble(::java::util::function::LongToDoubleFunctionProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "mapToDouble", "(Ljava/util/function/LongToDoubleFunction;)Ljava/util/stream/DoubleStream;" );
return ::java::util::stream::DoubleStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) ) );
}
::java::util::stream::IntStreamProxy LongStreamProxy::mapToInt(::java::util::function::LongToIntFunctionProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "mapToInt", "(Ljava/util/function/LongToIntFunction;)Ljava/util/stream/IntStream;" );
return ::java::util::stream::IntStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::distinct()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "distinct", "()Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::filter(::java::util::function::LongPredicateProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "filter", "(Ljava/util/function/LongPredicate;)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::flatMap(::java::util::function::LongFunctionProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "flatMap", "(Ljava/util/function/LongFunction;)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::limit(jlong p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "limit", "(J)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, p0 ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::map(::java::util::function::LongUnaryOperatorProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "map", "(Ljava/util/function/LongUnaryOperator;)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::parallel()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "parallel", "()Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::peek(::java::util::function::LongConsumerProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "peek", "(Ljava/util/function/LongConsumer;)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::sequential()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "sequential", "()Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::skip(jlong p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "skip", "(J)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, p0 ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::sorted()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "sorted", "()Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::stream::StreamProxy LongStreamProxy::boxed()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "boxed", "()Ljava/util/stream/Stream;" );
return ::java::util::stream::StreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
::java::util::stream::StreamProxy LongStreamProxy::mapToObj(::java::util::function::LongFunctionProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "mapToObj", "(Ljava/util/function/LongFunction;)Ljava/util/stream/Stream;" );
return ::java::util::stream::StreamProxy( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) ) );
}
jlong LongStreamProxy::count()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "count", "()J" );
return JNIEnvHelper::CallLongMethod( _getPeerObject(), mid );
}
jlong LongStreamProxy::reduce(jlong p0, ::java::util::function::LongBinaryOperatorProxy p1)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "reduce", "(JLjava/util/function/LongBinaryOperator;)J" );
return JNIEnvHelper::CallLongMethod( _getPeerObject(), mid, p0, static_cast<jobject>( p1 ) );
}
jlong LongStreamProxy::sum()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "sum", "()J" );
return JNIEnvHelper::CallLongMethod( _getPeerObject(), mid );
}
::net::sourceforge::jnipp::JLongArrayHelper<1> LongStreamProxy::toArray()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "toArray", "()[J" );
return ::net::sourceforge::jnipp::JLongArrayHelper<1>( JNIEnvHelper::CallObjectMethod( _getPeerObject(), mid ) );
}
void LongStreamProxy::forEach(::java::util::function::LongConsumerProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "forEach", "(Ljava/util/function/LongConsumer;)V" );
JNIEnvHelper::CallVoidMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) );
}
void LongStreamProxy::forEachOrdered(::java::util::function::LongConsumerProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetMethodID( _getObjectClass(), "forEachOrdered", "(Ljava/util/function/LongConsumer;)V" );
JNIEnvHelper::CallVoidMethod( _getPeerObject(), mid, static_cast<jobject>( p0 ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::concat(::java::util::stream::LongStreamProxy p0, ::java::util::stream::LongStreamProxy p1)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "concat", "(Ljava/util/stream/LongStream;Ljava/util/stream/LongStream;)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid, static_cast<jobject>( p0 ), static_cast<jobject>( p1 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::empty()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "empty", "()Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::generate(::java::util::function::LongSupplierProxy p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "generate", "(Ljava/util/function/LongSupplier;)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid, static_cast<jobject>( p0 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::iterate(jlong p0, ::java::util::function::LongUnaryOperatorProxy p1)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "iterate", "(JLjava/util/function/LongUnaryOperator;)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid, p0, static_cast<jobject>( p1 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::of(jlong p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "of", "(J)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid, p0 ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::of(::net::sourceforge::jnipp::JLongArrayHelper<1> p0)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "of", "([J)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid, static_cast<jlongArray>( p0 ) ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::range(jlong p0, jlong p1)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "range", "(JJ)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid, p0, p1 ) );
}
::java::util::stream::LongStreamProxy LongStreamProxy::rangeClosed(jlong p0, jlong p1)
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "rangeClosed", "(JJ)Ljava/util/stream/LongStream;" );
return ::java::util::stream::LongStreamProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid, p0, p1 ) );
}
::java::util::stream::LongStream_BuilderProxy LongStreamProxy::builder()
{
static jmethodID mid = NULL;
if ( mid == NULL )
mid = JNIEnvHelper::GetStaticMethodID( _getObjectClass(), "builder", "()Ljava/util/stream/LongStream$Builder;" );
return ::java::util::stream::LongStream_BuilderProxy( JNIEnvHelper::CallStaticObjectMethod( _getObjectClass(), mid ) );
}
|
c5581cc61c212769399591f00e5605291844b4b8
|
9852ff4c9cdee2d23811c6802d5b64e67e2c0e3a
|
/Source/TreasureHunter/Public/Widget/Lobby/CreateSessionWidget.h
|
50b34bbc7a5feb19da12326ed814c9658084d43c
|
[] |
no_license
|
RedChiken/TreasureHunter
|
a29c17da78e1c33f00d639d077fa37b1c17a72de
|
4b7e4e19ceb9857425661ea0e436a7cd7b034583
|
refs/heads/master
| 2022-12-01T10:09:03.969448
| 2020-04-02T09:09:05
| 2020-04-02T09:09:05
| 82,168,825
| 0
| 0
| null | 2020-04-02T09:52:25
| 2017-02-16T10:27:59
|
C++
|
UTF-8
|
C++
| false
| false
| 652
|
h
|
CreateSessionWidget.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "THOutGameDefines.h"
#include "CreateSessionWidget.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnCreateSession, FString, HostName, int32, MaxPlayer);
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnCancelCreateSession);
/**
*
*/
UCLASS()
class TREASUREHUNTER_API UCreateSessionWidget : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintCallable)
FOnCreateSession OnCreateSession;
UPROPERTY(BlueprintCallable)
FOnCancelCreateSession OnCancelCreateSession;
};
|
d4908afd90b8b92d3b494ee78016bc67367cac23
|
61eb3c918ea2ac1949a71edfa63781ed56b474d4
|
/src/solar/math/Math.h
|
ef0705b63898c21de203dea2c0d973606ac5d985
|
[] |
no_license
|
jacob-doll/SolarEngine
|
aa3a11011aa488bb1d41a72956105cb361a4902d
|
e5557586189ad6efb29afe65b7e8ff09e9fed19c
|
refs/heads/master
| 2021-08-17T07:24:56.944246
| 2017-11-20T22:30:08
| 2017-11-20T22:30:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 496
|
h
|
Math.h
|
#pragma once
namespace solar
{
#undef M_PI
static const float M_PI = 3.14159265358979323846264338327950288f;
static const float M_HALF_PI = M_PI * 0.5f;
static const float M_DEGTORAD = M_PI / 180.0f;
static const float M_DEGTORAD_2 = M_PI / 360.0f; // M_DEGTORAD / 2.f
static const float M_RADTODEG = 1.0f / M_DEGTORAD;
template <class T>
inline T Clamp(T value, T min, T max)
{
if (value < min)
return min;
else if (value > max)
return max;
else
return value;
}
}
|
82806a054c316bff6a212a1de99c7d97c0018d5a
|
c80f25d24cee6ed8dba1513c227886c07d83cf75
|
/WeaponGirl_1/Client/trunk/Classes/Network/Login/MsgLoginCreateNewUser.cpp
|
d34b445d348754a7533d13b2805fd706a915ab03
|
[
"MIT"
] |
permissive
|
cnsuhao/newProBase
|
c250e54ead43efb57363347d1700649a35617d15
|
4fe81d30740a2a0857ca6e09a281fed1146e6202
|
refs/heads/master
| 2021-08-23T14:19:24.568828
| 2015-11-27T13:37:54
| 2015-11-27T13:37:54
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,346
|
cpp
|
MsgLoginCreateNewUser.cpp
|
////////////////////////////////////////////////////////////////////////
// Copyright(c) 2011-2014, WuHan GoodGame, All Rights Reserved
// Moudle: MsgLoginCreateNewUser.cpp
// Author: 彭文奇(Peng Wenqi)
// Created: 2014-11-4
////////////////////////////////////////////////////////////////////////
#include "./MsgLoginCreateNewUser.h"
#include "Root.h"
#include "SceneLogin/SceneLogin.h"
#include "MsgLoginAction.h"
#include "MyCocosCommon/LayerHint.h"
//////////////////////////////////////////////////////////////////////////
CMsgLoginCreateNewUser::CMsgLoginCreateNewUser()
{
Init();
m_pInfo =(MSG_Info *)m_bufMsg;
m_head.usType = _MSG_LOGIN_CREATE_NEW_USER;
m_head.usSize = sizeof(MSG_Info);
}
//////////////////////////////////////////////////////////////////////////
CMsgLoginCreateNewUser::~CMsgLoginCreateNewUser()
{
}
//////////////////////////////////////////////////////////////////////////
void CMsgLoginCreateNewUser::Process()
{
if (MSG_LOGIN_CREATE_NEW_USER_RESULT_SUCCESS != m_pInfo->nResult)
{
std::string strMessageBox = "Create Error";
switch (m_pInfo->nResult)
{
case MSG_LOGIN_CREATE_NEW_USER_RESULT_NAME_CHECK:
{
strMessageBox = ConstTableMgr::getInstance()->GetConfigText(CONFIG_TEXT_ID_NAME_CHECK_ERROR);
}
break;
// case MSG_LOGIN_CREATE_NEW_USER_RESULT_CODE_REPEAT:
// {
// strMessageBox = "Name repeat";
// ConstTableMgr::getInstance()->GetConfigText(CONFIG_TEXT_ID_NAME_REPEAT, strMessageBox);
// }
// break;
case MSG_LOGIN_CREATE_NEW_USER_RESULT_COUNT_FULL:
{
strMessageBox = ConstTableMgr::getInstance()->GetConfigText(CONFIG_TEXT_ID_CAN_NOT_MORE_PLAYER);
}
break;
default:
{
strMessageBox = ConstTableMgr::getInstance()->GetConfigText(CONFIG_TEXT_ID_CREATE_FAILED);
}
break;
}
::AddHint(strMessageBox);
return;
}
// 保存角色数据
LogicDataMgr::getInstance()->SetMemoryDataAttr(LOGIC_DATA_userinfo_sex, m_pInfo->nSex);
LogicDataMgr::getInstance()->SetMemoryDataAttr(LOGIC_DATA_userinfo_lookface, m_pInfo->nLookface);
LogicDataMgr::getInstance()->SetMemoryDataAttr(LOGIC_DATA_userinfo_user_id, m_pInfo->nUserID);
LogicDataMgr::getInstance()->SetMemoryStringAttr(LOGIC_STRING_UserName, m_pInfo->szName);
// 关闭创建界面, 打开载入界面
auto sceneLogin = Root::getInstance()->getSceneLogin();
CHECK(sceneLogin);
sceneLogin->popLayerLoad();
// 选择角色
CMsgLoginAction msg;
CHECK(msg.CreateChooseUser(m_pInfo->nUserID));
NetworkServe::getInstance()->sendMsg(msg);
}
////////////////////////////////////////////////////////////////////////
// Description: 创建新角色消息创建
// Arguments: 性别在服务器写死
// Author: 彭文奇(Peng Wenqi)
// Return Value: bool
////////////////////////////////////////////////////////////////////////
bool CMsgLoginCreateNewUser::createCreateNewPlayer(const char* pszName, int nLookface, int nJob)
{
CHECKF(pszName);
this->Init();
::SafeCopy(m_pInfo->szName, pszName, sizeof(m_pInfo->szName));
m_pInfo->nJob = nJob;
m_pInfo->nLookface = nLookface;
m_pInfo->nResult = MSG_LOGIN_CREATE_NEW_USER_RESULT_SUCCESS;
m_head.usType = _MSG_LOGIN_CREATE_NEW_USER;
m_head.usSize = sizeof(MSG_Info);
return true;
}
|
55cde06813e41b1ceea4a4f758feae9803f0d40f
|
6c93d85f5b2c36a3288b0c4a2db1c255a14e2c77
|
/src/CreateColor.cpp
|
d64ffb938dcf3d9776bc58a4618179ef0449897d
|
[] |
no_license
|
TANG-Kai/pyfx
|
af30bfc8e0f5c93132f02916eb1f9ea95c13d4b7
|
9fa4bd738ce90a8d40e68c4e0490601df78cceba
|
refs/heads/master
| 2021-01-25T06:49:22.308713
| 2013-11-12T22:58:10
| 2013-11-12T22:58:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 688
|
cpp
|
CreateColor.cpp
|
#include "CreateColor.h"
using namespace vr;
const Color CreateColor::eval(const Vector &p) const
{
return Color(
evalIf(m_R, p),
evalIf(m_G, p),
evalIf(m_B, p),
evalIf(m_A, p));
}
const float CreateColor::evalIf(const ScalarField *v, const Vector &p) const
{
return (v != NULL) ? v->eval(p) : 0.0f;
}
/*
const int CreateColor::grad(const Vector &p) const
{
throw std::exception("Not implemented.");
}
*/
const Box CreateColor::getBBox() const
{
Box b;
if(m_R != NULL) b = b.expand(m_R->getBBox());
if(m_G != NULL) b = b.expand(m_G->getBBox());
if(m_B != NULL) b = b.expand(m_B->getBBox());
if(m_A != NULL) b = b.expand(m_A->getBBox());
return b;
}
|
7f1dc2a99e95cd20200762a6f343767d24626f5b
|
a33aac97878b2cb15677be26e308cbc46e2862d2
|
/program_data/PKU_raw/60/1031.c
|
6f52610f94c7a840d248e6d16da693fcc6d25e90
|
[] |
no_license
|
GabeOchieng/ggnn.tensorflow
|
f5d7d0bca52258336fc12c9de6ae38223f28f786
|
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
|
refs/heads/master
| 2022-05-30T11:17:42.278048
| 2020-05-02T11:33:31
| 2020-05-02T11:33:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 448
|
c
|
1031.c
|
int main()
{
int n,i,j,count=0,prime=0;
scanf("%d",&n);
int su[10000];
for(i=1;i<=n;i++){
for(j=1;j<i;j++){
if(i%j==0){
count+=1;
}
}
if(count==1){
su[prime]=i;
prime+=1;
}
count=0;
}
count=0;
for(i=0;i<prime;i++){
if(su[i+1]-su[i]==2){
printf("%d %d\n",su[i],su[i+1]);
count+=1;
}
}
if(count==0)
printf("empty");
return 0;
}
|
869a75808b62cd9e25cb970b6f46d3e345a386d9
|
773302a87be49038487bb12af120fa716df08921
|
/src/core/script/parser_unittest.cpp
|
7b713bf2c89fdb907c1d58c0dfb49d93f7b60355
|
[
"BSL-1.0"
] |
permissive
|
williamnagels/linker
|
c2a4fac1740f711967ab182b4e18203ffd5d7a8d
|
a1e309c11e6ad8ed956475d90ddc8aa498049b66
|
refs/heads/master
| 2018-09-28T19:50:43.941416
| 2018-06-07T16:15:13
| 2018-06-07T16:15:13
| 106,322,418
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,221
|
cpp
|
parser_unittest.cpp
|
#include <boost/test/unit_test.hpp>
#include "src/include/core/script/parser.h"
BOOST_AUTO_TEST_SUITE(parser)
BOOST_AUTO_TEST_CASE(parse_some_script)
{
N_Core::N_Parser::Parser parser("testfiles/simple_script");
BOOST_CHECK_EQUAL(std::distance(std::begin(parser), std::end(parser)), 3);
BOOST_CHECK_EQUAL(parser[0]._name, ".text");
BOOST_CHECK_EQUAL(parser[1]._name, ".data");
BOOST_CHECK_EQUAL(parser[2]._name, ".bss");
BOOST_CHECK_EQUAL(*parser._entry_point, "main");
BOOST_CHECK(N_Core::N_Parser::is_valid("front.text",parser[0]));
BOOST_CHECK(not N_Core::N_Parser::is_valid(".text.duh",parser[0]));
BOOST_CHECK(not N_Core::N_Parser::is_valid("front.text.duh",parser[0]));
BOOST_CHECK(N_Core::N_Parser::is_valid(".text",parser[0]));
BOOST_CHECK(N_Core::N_Parser::is_valid(".data.back",parser[1]));
BOOST_CHECK(not N_Core::N_Parser::is_valid(".back.data",parser[1]));
BOOST_CHECK(not N_Core::N_Parser::is_valid(".dat",parser[1]));
BOOST_CHECK(N_Core::N_Parser::is_valid(".data",parser[1]));
BOOST_CHECK(N_Core::N_Parser::is_valid("front.bssback",parser[2]));
BOOST_CHECK(N_Core::N_Parser::is_valid(".bss",parser[2]));
}
BOOST_AUTO_TEST_SUITE_END()
|
da578ef925272955521dc2976bd38d486596dbd9
|
9ab80aff674b22544e4f73aec960ee2bd69e5939
|
/VideoTranscoder.h
|
27003f7d75b02c3414c893bab6381f4201cb7b7e
|
[] |
no_license
|
savasozkan/video-transcoder
|
ec1576ee74ff72c5715333a22ca882148c482ad6
|
db6b4b488a45fea30c4b89ec8c21d96841cc1afa
|
refs/heads/master
| 2021-01-10T04:07:12.706768
| 2015-10-07T13:38:37
| 2015-10-07T13:38:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,634
|
h
|
VideoTranscoder.h
|
/*!
**************************************************************************************
* \file VideoTranscoder.h
* \author
* - Savas Ozkan
*************************************************************************************
*/
#pragma once
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavfilter/avfiltergraph.h"
#include "libavfilter/avcodec.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "libavcodec/avfft.h"
}
#include <iostream>
#include <auto_ptr.h>
#include <string>
#include <vector>
#include <exception>
/*!
* This class mainly comprises an algorithm which transcodes an input media to an output media by
* letting user to make changes on output media's configurations according to his/her demand.
* Most of the code in this class is taken from an example that is given in
* "http://ffmpeg.org/doxygen/trunk/transcoding_8c-example.html".However, due to the fact that
* this example has immense number of bugs particularly on lack of audio and video formats encoding,
* the code is modified and most of the bugs are solved. Furthermore, the trancoding example
* is written within class structure which ease to use.
*
* There might still be some more bugs even in this code. If you encounter any of those, please contact with
* the author via "http://www.savasozkan.com".
*/
using namespace std;
/***************/
/* Error Class */
/***************/
class Error : public exception
{
public:
explicit Error(const string& message) throw() { m_message = message; }
virtual ~Error() throw() {}
virtual const char* what() const throw() { return m_message.c_str() ; }
private:
string m_message;
};
/**************************/
/* VideoTranscoder Class */
/**************************/
class VideoTranscoder
{
public:
struct st_filtering_context
{
AVFilterContext *m_buffersink_ctx;
AVFilterContext *m_buffersrc_ctx;
AVFilterGraph *m_filter_graph;
};
VideoTranscoder();
virtual ~VideoTranscoder();
void transcode(string pth_input_media, string pth_output_media);
private:
int open_input_file(string pth_media);
int open_output_file(string pth_media);
void input_video_properties();
int init_filters();
int init_filter(st_filtering_context* f_ctx, AVCodecContext *dec_ctx, AVCodecContext *enc_ctx, const char *filter_spec);
bool find_next_packet(AVPacket& packet);
bool decode_packet(AVPacket& packet);
int decode_media(AVFormatContext* context, AVPacket& packet, AVFrame* dec_frame, int& b_frame);
bool encode_frame(int stream_index);
int encode_media(AVFormatContext* context, AVPacket& packet, AVFrame* dec_frame, int stream_index, int& b_frame);
int filter_encode_write_frame(AVFrame *frame, unsigned int stream_index);
int encode_write_frame(AVFrame *filt_frame, int stream_index, int& b_frame);
void aac_packet_filter(int stream_index, AVPacket& packet);
int flush_encoder(unsigned int stream_index);
int decode_frame_in_buffer(int stream_index);
int time_to_frame(int stream_index, double time);
double global_time_to_seconds(int64_t global_time) const;
int64_t stream_time_to_global_time(AVRational time_base, int64_t nStreamTime) const;
int64_t seconds_to_global_time(double seconds) const;
void free_transcode_buffer();
void free_open_buffer();
AVFormatContext* m_ifmt_ctx;
AVFormatContext* m_ofmt_ctx;
st_filtering_context* m_filter_ctx;
auto_ptr<AVPacket> m_packet;
AVFrame* m_dec_frame;
vector<double> m_v_duration;
vector<int> m_v_numof_frames;
vector<vector<int64_t> > m_v_timestamps;
};
|
96b683f2302649d8db31b72cab9569f550a1fbd7
|
f251f8ed67493aaf89fad9535b29adf0d2f995a1
|
/soj_1009.cpp
|
a808507d7d0dd6d08fc4e02706a0cd7f393ee338
|
[] |
no_license
|
443singer/soj
|
4fe391c908e9f0b90201bb7367245753a90ec8a5
|
d98ed24d5d0796cc85b2979bae82bd0728f529f2
|
refs/heads/master
| 2021-08-30T19:42:04.328587
| 2017-12-19T07:13:32
| 2017-12-19T07:13:32
| 114,731,725
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,103
|
cpp
|
soj_1009.cpp
|
#include <cstdio>
#include <iostream>
using namespace std;
const int N = 1003;
long long dp[N][13];
int a[10] = {1000,400,200,100,40,20,10,4,2,1};
bool flag = false;
long long dfs(int n,int u) {
if(n==0) return 1;
for(int i = u ; i < 10 ; ++i) {
if(n-a[i]>=0) {
if(dp[n-a[i]][i]) dp[n][u] += dp[n-a[i]][i];
else dp[n][u] += dfs(n-a[i],i);
}
}
return dp[n][u];
}
int main() {
for(int i = 1 ; i <= 1000 ; ++i)
dfs(i,0);
double x;
while(cin>>x) {
if(x-0.00<1e-4) break;
int haha = x;
int cnt2 = 0;
while(haha) {
cnt2++;
haha /= 10;
}
if(cnt2!=2) printf(" ");
printf("%.2lf",x);
x*=100;
int n = x;
if(n==0) break;
n /= 5;
long long tmp = dp[n][0];
int cnt = 0;
while(tmp) {
cnt++;
tmp /= 10;
}
for(int i = 1 ; i <= 12-cnt ; ++i) {
printf(" ");
}
cout << dp[n][0] << endl;
}
}
|
cd8b2ada5310c50e7edbcb52203a14f784dbf6cd
|
245ed7c43ecb4923b6e8d5298b7bba34cf525c10
|
/leetcode_169_majority element.cpp
|
8b281aab82cfc4d2a351259e69b3b6cc16641f86
|
[] |
no_license
|
Elaine-DWL/shuati_record
|
86f2ed7c458a986808261abedc60864a4ff87e2a
|
300fbea8cf5c8658d111966624fba69d6a82cebd
|
refs/heads/master
| 2022-12-18T01:32:52.516446
| 2020-09-05T10:28:25
| 2020-09-05T10:28:25
| 293,052,250
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,207
|
cpp
|
leetcode_169_majority element.cpp
|
// 这道题是要求数组中的众数,且其数量 > n/2
#include <iostream>
#include <map>
#include <vector>
using namespace std;
// 法1 遍历 借助hash 66.3% 16ms
class Solution{
public:
int majorityElement(vector<int>& nums){
map<int, int> myhash;
int maj = nums[0];
int num_maj=1;
for(int i=0; i<nums.size(); i++){
if(myhash.count(nums[i])==0) myhash[nums[i]] = 1;
else myhash[nums[i]]++;
if(myhash[nums[i]] > num_maj){
num_maj = myhash[nums[i]];
maj = nums[i];
}
}
return maj;
}
};
//-----------讨论区参考
//解法总结: https://leetcode.com/problems/majority-element/discuss/51612/6-Suggested-Solutions-in-C++-with-Explanations
public class Solution {
public int majorityElement(int[] num) {
int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
}
return major;
}
}
int main()
{
cout << "Hello world!" << endl;
return 0;
}
|
782a83b8fcffc3eec993b7979fb2eb68181cc306
|
68684e53c3d5db80c60e40ddd678e9821042c5fa
|
/d08/ex01/span.hpp
|
bb7ba8e5c21fc2c60246cccfb9a98ef5af4b76b6
|
[] |
no_license
|
pacifistes/Piscine_cpp
|
fdb550d1a2d4fba428ca37b2b6e056b272871fb8
|
063fe4387d0e31141e0eb3863f5722e5ccf3a50a
|
refs/heads/master
| 2021-03-16T09:42:49.760895
| 2018-10-16T19:23:34
| 2018-10-16T19:23:34
| 90,257,399
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,274
|
hpp
|
span.hpp
|
#ifndef SPAN_CLASS_H
# define SPAN_CLASS_H
#include <vector>
#include <iostream>
#include <exception>
#include <algorithm>
class Span {
public :
Span(void);
Span(unsigned int maxElem);
virtual ~Span(void);
Span(Span const &span);
Span & operator=(Span const &span);
void addNumber(int Number);
void addNumbers(std::vector<int> vectorElems);
unsigned int shortestSpan();
unsigned int longestSpan();
class TooMuchElemException : public std::exception {
public:
virtual ~TooMuchElemException(void) throw();
TooMuchElemException(TooMuchElemException const &tooMuchElemException) throw();
Span::TooMuchElemException & operator=(TooMuchElemException const &tooMuchElemException) throw();
TooMuchElemException(void) throw();
virtual const char *what() const throw();
};
class TooFewElemException : public std::exception {
public:
virtual ~TooFewElemException(void) throw();
TooFewElemException(TooFewElemException const &tooFewElemException) throw();
Span::TooFewElemException & operator=(TooFewElemException const &tooFewElemException) throw();
TooFewElemException(void) throw();
virtual const char *what() const throw();
};
private:
unsigned int _maxElem;
std::vector<int> _myVector;
};
#endif
|
70a6fb54e7ea8d1a176d3c02da8e1fcd36540f89
|
ab615e46f9e941503f73c37d39c350ac990bce65
|
/src/engine/datatype/3D/Quaternion.cpp
|
7558b939244e57c36d34793307e49e270de89978
|
[] |
no_license
|
minhtri258gb/GameEngine
|
89b6a2ab65e4a3b6246e24363ef513f3346785c6
|
84ff04c689998069127fbda45c72c1a96dff629a
|
refs/heads/main
| 2023-05-25T16:34:55.432557
| 2023-05-15T11:49:45
| 2023-05-15T11:49:45
| 217,287,861
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,653
|
cpp
|
Quaternion.cpp
|
#define __MT_QUATERNION_CPP__
#include <sstream>
#include <cmath>
#include <limits>
#include "Math3D.h"
#include "../../exception/BoundingException.h"
using namespace std;
using namespace mt;
Quaternion::Quaternion()
{
set(0.0f, 0.0f, 0.0f, 1.0f);
}
Quaternion::Quaternion(float x, float y, float z, float w)
{
set(x, y, z, w);
}
Quaternion::Quaternion(float pitch, float yaw, float roll)
{
set(pitch, yaw, roll);
}
Quaternion::Quaternion(float angle, Vector3 axis)
{
set(angle, axis);
}
Quaternion::Quaternion(Vector3 normalized)
{
set(normalized);
}
Quaternion::Quaternion(const Vector4& v)
{
set(v);
}
Quaternion::Quaternion(const Matrix3x3& m)
{
set(m);
}
Quaternion::Quaternion(const Quaternion &q)
{
set(q);
}
Quaternion::~Quaternion()
{
}
Quaternion Quaternion::normalize() const
{
float l = length();
return Quaternion(x/l, y/l, z/l, w/l);
}
Quaternion Quaternion::conjugate() const
{
return Quaternion(-x, -y, -z, w);
}
Quaternion Quaternion::interpolate(const Quaternion& start, const Quaternion& end, float factor)
{
// calc cosine theta
float cosom = start.x * end.x + start.y * end.y + start.z * end.z + start.w * end.w;
// adjust signs (if necessary)
Quaternion endTmp = end;
if (cosom < 0.0f)
{
cosom = -cosom;
endTmp.x = -endTmp.x; // Reverse all signs
endTmp.y = -endTmp.y;
endTmp.z = -endTmp.z;
endTmp.w = -endTmp.w;
}
// Calculate coefficients
float sclp, sclq;
if ((1.0f - cosom) > 0.0001f) // 0.0001 -> some epsillon
{
// Standard case (slerp)
float omega, sinom;
omega = acosf(cosom); // extract theta from dot product's cos theta
sinom = sinf(omega);
sclp = sinf((1.0f - factor) * omega) / sinom;
sclq = sinf(factor * omega) / sinom;
} else
{
// Very close, do linear interp (because it's faster)
sclp = 1.0f - factor;
sclq = factor;
}
return Quaternion(
sclp * start.x + sclq * endTmp.x,
sclp * start.y + sclq * endTmp.y,
sclp * start.z + sclq * endTmp.z,
sclp * start.w + sclq * endTmp.w
);
}
void Quaternion::set(float _x, float _y, float _z, float _w)
{
x = _x;
y = _y;
z = _z;
w = _w;
}
void Quaternion::set(float pitch, float yaw, float roll)
{
const float fSinPitch(sinf(pitch * 0.5f));
const float fCosPitch(cosf(pitch * 0.5f));
const float fSinYaw(sinf(yaw * 0.5f));
const float fCosYaw(cosf(yaw * 0.5f));
const float fSinRoll(sinf(roll * 0.5f));
const float fCosRoll(cosf(roll * 0.5f));
const float fCosPitchCosYaw(fCosPitch * fCosYaw);
const float fSinPitchSinYaw(fSinPitch * fSinYaw);
x = fSinRoll * fCosPitchCosYaw - fCosRoll * fSinPitchSinYaw;
y = fCosRoll * fSinPitch * fCosYaw + fSinRoll * fCosPitch * fSinYaw;
z = fCosRoll * fCosPitch * fSinYaw - fSinRoll * fSinPitch * fCosYaw;
w = fCosRoll * fCosPitchCosYaw + fSinRoll * fSinPitchSinYaw;
}
void Quaternion::set(float angle, Vector3 axis)
{
axis = axis.normalize();
angle /= 2.0f;
const float sin_a = sinf(angle);
x = axis.x * sin_a;
y = axis.y * sin_a;
z = axis.z * sin_a;
w = cosf(angle);
}
void Quaternion::set(Vector3 normalized)
{
x = normalized.x;
y = normalized.y;
z = normalized.z;
const float t = 1.0f - (x*x) - (y*y) - (z*z);
if (t < 0.0f)
w = 0.0f;
else
w = sqrtf(t);
}
void Quaternion::set(const Vector4& v)
{
x = v.x;
y = v.y;
z = v.z;
w = v.w;
}
void Quaternion::set(const Matrix3x3& m)
{
float t = m[0] + m[4] + m[8];
// large enough
if (t > 0.0f)
{
float s = sqrtf(1 + t) * 2.0f;
x = (m[7] - m[5]) / s;
y = (m[2] - m[6]) / s;
z = (m[3] - m[1]) / s;
w = 0.25f * s;
} // else we have to check several cases
else if (m[0] > m[4] && m[0] > m[8])
{
// Column 0:
float s = sqrtf(1.0f + m[0] - m[4] - m[8]) * 2.0f;
x = 0.25f * s;
y = (m[3] + m[1]) / s;
z = (m[2] + m[6]) / s;
w = (m[7] - m[5]) / s;
}
else if( m[4] > m[8])
{
// Column 1:
float s = sqrtf(1.0f + m[4] - m[0] - m[8]) * 2.0f;
x = (m[3] + m[1]) / s;
y = 0.25f * s;
z = (m[7] + m[5]) / s;
w = (m[2] - m[6]) / s;
} else
{
// Column 2:
float s = sqrtf(1.0f + m[8] - m[0] - m[4]) * 2.0f;
x = (m[2] + m[6]) / s;
y = (m[7] + m[5]) / s;
z = 0.25f * s;
w = (m[3] - m[1]) / s;
}
}
void Quaternion::set(const Quaternion &q)
{
x = q.x;
y = q.y;
z = q.z;
w = q.w;
}
bool Quaternion::equal(const Quaternion& v, double epsilon) const
{
return
abs(x - v.x) <= epsilon &&
abs(y - v.y) <= epsilon &&
abs(z - v.z) <= epsilon &&
abs(w - v.w) <= epsilon;
}
Quaternion Quaternion::slerp(const Quaternion& q, float factor)
{
quat x = *this;
quat z = q;
float cosTheta = x * q;
if (cosTheta < 0.0f)
{
z = -q;
cosTheta = -cosTheta;
}
if (cosTheta > 1.0f - numeric_limits<float>::epsilon())
{
// Linear interpolation
return quat(x.x + (z.x - x.x) * factor,
x.y + (z.y - x.y) * factor,
x.z + (z.z - x.z) * factor,
x.w + (z.w - x.w) * factor);
}
else
{
// Essential Mathematics, page 467
float angle = acos(cosTheta);
return (x * sin((1.0f - factor) * angle) + z * sin(factor * angle)) / sin(angle);
}
}
float Quaternion::operator * (const Quaternion& q) const
{
return x * q.x + y * q.y + z * q.z + w * q.w;
}
Quaternion Quaternion::operator * (float f) const
{
return Quaternion(x*f, y*f, z*f, w*f);
}
Quaternion Quaternion::operator ^ (const Quaternion& q) const
{
return Quaternion(
w*q.x + x*q.w + y*q.z - z*q.y,
w*q.y + y*q.w + z*q.x - x*q.z,
w*q.z + z*q.w + x*q.y - y*q.x,
w*q.w - x*q.x - y*q.y - z*q.z
);
}
bool Quaternion::operator == (const Quaternion& q) const
{
return x == q.x && y == q.y && z == q.z && w == q.w;
}
bool Quaternion::operator != (const Quaternion& q) const
{
return x != q.x || y != q.y || z != q.z || w != q.w;
}
|
5ff173d91503f6392df67c84a40611c3a44c6b75
|
d2d04505217dabff3d85130d1ab57a16c6d1e7c8
|
/src/Loader.cpp
|
949a2ef8bfd3c49a9025fd6bfd7c1cd3f922006b
|
[] |
no_license
|
hanglove34/arcade
|
4762724abfb17295b4d1bb14f372ef9777ce8d82
|
1ed80ef773aa0a0cb88ff7c6e5562b2c55917bc0
|
refs/heads/master
| 2023-03-31T12:57:28.001146
| 2021-04-01T13:01:16
| 2021-04-01T13:01:16
| 353,701,033
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,599
|
cpp
|
Loader.cpp
|
//
// EPITECH PROJECT, 2019
// Arcade
// File description:
// src
//
#include "Loader.hpp"
#include "IDisplayModule.hpp"
#include "IGameModule.hpp"
template<>
IGameModule *DLLoader<IGameModule>::getInstance(const std::string &path) {
const std::string comp(".so");
if (path.find(comp) == std::string::npos)
exit(84);
void *handle = dlopen(path.c_str(), RTLD_LAZY);
if (!handle) {
std::cout << dlerror() << std::endl;
exit(84);
}
if (!dlsym(handle, "gamecheck"))
exit (84);
IGameModule *(*entryPoint)(void);
void *fptr = dlsym(handle, "entryPoint");
entryPoint = (IGameModule *(*)())fptr;
if (!entryPoint)
return NULL;
IGameModule *instance = entryPoint();
instance->init();
instance->setHandle(handle);
instance->setName(pathToName(path));
return (instance);
}
template<>
IDisplayModule *DLLoader<IDisplayModule>::getInstance(const std::string &path) {
const std::string comp(".so");
if (path.find(comp) == std::string::npos)
exit(84);
void *handle = dlopen(path.c_str(), RTLD_LAZY);
if (!handle) {
std::cout << dlerror() << std::endl;
exit(84);
}
if (!dlsym(handle, "libcheck"))
exit (84);
IDisplayModule *(*entryPoint)(void);
void *fptr = dlsym(handle, "entryPoint");
entryPoint = (IDisplayModule *(*)())fptr;
if (!entryPoint)
return NULL;
IDisplayModule *instance = entryPoint();
instance->init();
instance->setHandle(handle);
instance->setName(pathToName(path));
return (instance);
}
|
296228e857efca9fcd8996995ce88765bac2ebe5
|
8aea173f3ec466d39547ae9f60ed36650103baf7
|
/Implementations/11 - Math (4)/11.2 - Combinatorics (5)/Combo Plus.cpp
|
4e45bc98fa95521e324bafdfeef4d556721022dd
|
[] |
no_license
|
arvindr9/USACO
|
8593936a1e7a373050991b25b345e64d1da9457f
|
9ea3acc92d841452abfce01622029789a9a3ba76
|
refs/heads/master
| 2021-04-06T11:55:39.456470
| 2018-03-11T14:40:04
| 2018-03-11T14:40:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,127
|
cpp
|
Combo Plus.cpp
|
/**
* Description: Extends combo to a power of a prime
* Verification: https://dmoj.ca/problem/tle17c4p5
*/
typedef pair<ll,ll> pll;
template<int SZ> struct ComboExtended {
pll fac[SZ+1], ifac[SZ+1], mod;
ll MOD = 1;
void init(pll _mod) { // prime, power
mod = _mod; F0R(i,mod.s) MOD *= mod.f;
fac[0] = ifac[0] = {1,0};
FOR(i,1,SZ+1) {
fac[i] = fac[i-1];
int I = i, z = 0;
while (I % mod.f == 0) I /= mod.f, z++;
fac[i].f = fac[i].f*I%MOD; fac[i].s += z;
ifac[i] = {inv(fac[i].f,MOD),fac[i].s};
}
}
ll inv(ll a, ll b) { // 0 < a < b, gcd(a,b) = 1
a %= b;
if (a <= 1) return a;
ll i = inv(b%a,a);
ll tmp = -((b/a)*i+((b%a)*i)/a) % b;
while (tmp < 0) tmp += b;
return tmp;
}
ll comb(ll a, ll b) {
if (a < b) return 0;
ll tmp = (fac[a].f*ifac[b].f%MOD)*ifac[a-b].f % MOD;
ll z = fac[a].s-fac[b].s-fac[a-b].s;
if (z >= mod.s) return 0;
F0R(i,z) tmp = tmp*mod.f % MOD;
return tmp;
}
};
|
de4635a13a1db8b670cd146c75786aaf7c737deb
|
037b3e6bb59ab23a13178c4466628a14b9dd3f01
|
/felicia/drivers/imu/imu_format.h
|
b13e61ce65ee45cc7d9bca46ef2aa60c9fcd7e55
|
[
"BSD-3-Clause"
] |
permissive
|
hyunjunekim/felicia
|
ce8ec8c8802f5008f85acc0caf7ccc19cd86c3ad
|
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
|
refs/heads/master
| 2022-04-01T03:22:18.649612
| 2019-12-10T16:24:54
| 2019-12-10T16:24:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,366
|
h
|
imu_format.h
|
// Copyright (c) 2019 The Felicia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FELICIA_DRIVERS_IMU_IMU_FORMAT_H_
#define FELICIA_DRIVERS_IMU_IMU_FORMAT_H_
#include <vector>
#include "felicia/core/lib/base/export.h"
#include "felicia/drivers/imu/imu_format_message.pb.h"
namespace felicia {
namespace drivers {
class FEL_EXPORT ImuFormat {
public:
ImuFormat();
ImuFormat(float frame_rate);
ImuFormat(const ImuFormat& other);
ImuFormat& operator=(const ImuFormat& other);
std::string ToString() const;
float frame_rate() const;
void set_frame_rate(float frame_rate);
ImuFormatMessage ToImuFormatMessage() const;
bool operator==(const ImuFormat& other);
private:
float frame_rate_ = 0;
};
FEL_EXPORT std::ostream& operator<<(std::ostream& os,
const ImuFormat& imu_format);
using ImuFormats = std::vector<ImuFormat>;
// Compares the priority of the imu formats. Returns true if |lhs| is the
// preferred imu format in comparison with |rhs|. Returns false otherwise.
FEL_EXPORT bool CompareCapability(const ImuFormat& requested,
const ImuFormat& lhs, const ImuFormat& rhs);
} // namespace drivers
} // namespace felicia
#endif // FELICIA_DRIVERS_IMU_IMU_FORMAT_H_
|
55ca18e73565883fbb9c16a0456b7947fb38ce94
|
462a984c485d8ba2071749a073cd2e7e7d9e596c
|
/Classes/PlayerScene.h
|
dfd6819d8d457c74338fa1ff366c3c08899bf5a3
|
[
"MIT"
] |
permissive
|
phuocpeter/Monopoly-Wireless
|
fceb31d53a4b6101e763a7f72944427d108754d3
|
5895c937d9cbe1924c8ed5dca2059dc3432310f3
|
refs/heads/master
| 2021-06-01T04:12:58.044823
| 2016-06-22T19:42:38
| 2016-06-22T19:42:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,550
|
h
|
PlayerScene.h
|
//
// PlayerScene.hpp
// MGM
//
// Created by Tran Thai Phuoc on 2016-06-13.
//
//
#ifndef __PLAYER_SCENE_H__
#define __PLAYER_SCENE_H__
#include "cocos2d.h"
#include "extensions/cocos-ext.h"
#include "ui/CocosGUI.h"
#include "network/HttpClient.h"
USING_NS_CC;
USING_NS_CC_EXT;
class PlayerScene: public Layer
{
public:
static cocos2d::Scene* createScene(char* jsonString, std::string serverAddress, std::string info);
virtual bool init();
// implement the "static create()" method manually
CREATE_FUNC(PlayerScene);
// Textfield Handler
void amountTextFieldEvent(Ref* sender, ui::TextField::EventType type);
// Button handler
void sendButtonTapped(Ref* sender, ui::Widget::TouchEventType type);
void refreshButtonTapped(Ref* sender, ui::Widget::TouchEventType type);
void bankSceneChange(Ref* sender);
// Slider handler
void sliderEvent(Ref* sender, ui::Slider::EventType type);
// Network Handler
void onHttpRequestCompleted(network::HttpClient* sender, network::HttpResponse* response);
private:
Sprite* _loadingPlaceholder;
network::HttpRequest *_request;
Label* _recipentLabel;
Label* _errorLabel;
ui::Button* _sendBtn;
ui::Button* _refreshBtn;
ui::LoadingBar* _loadingBar;
std::string _plainSendData;
std::string _sessionID;
std::string _playerName;
std::string _recipentName;
const char* _dataToSend;
const char* _player1;
const char* _player2;
const char* _player3;
int _numOfPlayers;
int _amount;
int _money;
};
#endif /* __PLAYER_SCENE_H__ */
|
7812e919957bd4509118e912fb887a5a6a68ee3d
|
2366a20ebed64eeec04bfd8262bc2296981aa61e
|
/MainMenuState.hpp
|
5ff06af0a62ca50b0f766cbf697c7aa0a26c95a5
|
[] |
no_license
|
NotAPenguin0/KeiyakuGame
|
5f494a62dc2c567e493ca0dcf40abe7c731505ed
|
027c5818cbf91f6c91124fa4424c8bdf22d48c92
|
refs/heads/master
| 2020-03-18T20:04:28.917827
| 2018-06-04T16:36:51
| 2018-06-04T16:36:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,130
|
hpp
|
MainMenuState.hpp
|
#ifndef KEIYAKU_MAIN_MENU_STATE_HPP_
#define KEIYAKU_MAIN_MENU_STATE_HPP_
#include "GameState.hpp"
#include "depend/resource_manager/MusicManager.hpp"
#include "depend/resource_manager/FontManager.hpp"
#include "depend/ui/Button.hpp"
#include <SFML\Graphics\Sprite.hpp>
#include <SFML\Graphics\Text.hpp>
namespace Keiyaku
{
class MainMenuState : public GameState
{
public:
virtual ~MainMenuState();
virtual void onStart() override;
virtual void onExit() override;
virtual void update() override;
virtual void draw() override;
private:
void startGame();
/*Constants*/
static constexpr int TitleYOffset = -200;
static constexpr int TitleXOffset = -100;
static constexpr int ButtonXOffset = 100;
static constexpr int StartButtonYOffset = -100;
static constexpr int CreditsButtonYOffset = -20;
static constexpr int QuitButtonYOffset = 60;
/*Resources*/
MusicResource m_backgroundMusic;
FontResource m_font;
/*Actual drawable objects*/
sf::Sprite m_background;
sf::Text m_titleText;
UI::Button m_startButton;
UI::Button m_creditsButton;
UI::Button m_quitButton;
};
}
#endif
|
fcc4b13c6a6623173f80f86e743eeeda0dfa0e58
|
4ae279d209ae03b58a2d413055b7444f3f79eaf1
|
/qtfiles/qt_mainwindow.cpp
|
4e45a2914f857cdff4605c25e40750a833b96016
|
[] |
no_license
|
Mehooz/Movie-Crawler
|
834ad63c822dce2ec5576838ea33c4c253d96454
|
5628f89953c967e4566e14aa4f98826b918e995f
|
refs/heads/master
| 2021-01-05T18:29:22.158599
| 2020-04-05T02:40:10
| 2020-04-05T02:40:10
| 241,102,581
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,124
|
cpp
|
qt_mainwindow.cpp
|
#include "qt_mainwindow.h"
#include <QIcon>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QWidget* widget=new QWidget;
this->setCentralWidget(widget);
setWindowTitle("Information Collection Sys");
toolbar=addToolBar("Tool");
statusbar=statusBar();
//QAction
//image!!
initAction();
initMenu();
//size and position control
this->resize(400,300);
//levelmain
LevelMain* levelmain=new LevelMain(widget,this);
addLevel(levelmain);
levelmain->show();
}
//TODO images connect
void MainWindow::initTarget(){
webs[DouBan]=new Action(QIcon(":/DouBan.ico"),tr("DouBan"),this);
webs[RottenTomatoes]=new Action(QIcon(":/RottenTomatoes.ico"),tr("RottenTomatoes"),this);
webs[IMDB]=new Action(QIcon(":/IMDB.ico"),tr("IMDB"),this);
for(int i=0;i<webnum;i++){
webs[i]->setCheckable(true);
connect(webs[i],SIGNAL(actrigered(Action*)),this,SLOT(on_action(Action*)));
}
objs[Movie]=new Action(tr("Movie"),this);
objs[Tv]=new Action(tr("Tv"),this);
for(int i=0;i<objnum;i++){
objs[i]->setCheckable(true);
connect(objs[i],SIGNAL(actrigered(Action*)),this,SLOT(on_action(Action*)));
}
//connect mode!!
connect(searchac,SIGNAL(triggered(bool)),this,SLOT(searchac_action()));
//set default
webindex=DouBan;//DouBan
webs[DouBan]->setChecked(true);
objindex=Movie;//Movie
objs[Movie]->setChecked(true);
}
//TODO images
void MainWindow::initAction(){
//image!!!
//startac=new Action(tr("%Start"),this);
back2mainac=new Action(tr("Back to Main"),this);
back2mainac->setStatusTip(tr("back to the main level"));
toolbar->addAction(back2mainac);
statusbar->addAction(back2mainac);
connect(back2mainac,SIGNAL(triggered(bool)),this,SLOT(back2m()));
back2upperac=new Action(tr("&Back to UpperLevel"),this);
back2upperac->setStatusTip(tr("back to upper level"));
toolbar->addAction(back2upperac);
statusbar->addAction(back2upperac);
connect(back2upperac,SIGNAL(triggered(bool)),this,SLOT(back2u()));
rankac=new Action(tr("&Rank"),this);
rankac->setStatusTip(tr("search Ranks"));
//connect
searchac=new Action(tr("SearchName"));
searchac->setStatusTip(tr("search by name"));
//connect
initTarget();
}
void MainWindow::initMenu(){
operation=menuBar()->addMenu(tr("Operation"));
operation->addAction(back2mainac);
operation->addAction(back2upperac);
mode=menuBar()->addMenu(tr("Mode"));
mode->addAction(rankac);
mode->addAction(searchac);
target=menuBar()->addMenu(tr("Target"));
web=target->addMenu(tr("Web"));
object=target->addMenu(tr("Object"));
for(int i=0;i<webnum;i++){
web->addAction(webs[i]);
}
for(int i=0;i<objnum;i++){
object->addAction(objs[i]);
}
}
void MainWindow::addLevel(Level *level){
stack.push_back(level);
connect(level,SIGNAL(passLevel(Level*)),this,SLOT(addLevel(Level*)));
//judge special level
//because name in levelsearch should connect with the action obj
LevelSearch* levelsearch=dynamic_cast<LevelSearch*>(level);
if(levelsearch!=nullptr){//right
qDebug() << "levelsearch!!";
for(int i=0;i<objnum;i++){
connect(objs[i],SIGNAL(actrigered(Action*)),levelsearch,SLOT(name_change(Action*)));
}
}
else
qDebug() << "is not levelsearch";
//hide all expect the latest
for(unsigned int i=0;i<stack.size()-1;i++){
stack[i]->hide();
}
}
void MainWindow::on_action(Action *checkedone){
checkedone->setChecked(true); //check
for(int i=0;i<webnum;i++){
if(checkedone==webs[i]){
for(int j=0;j<webnum;j++){
if(i!=j) webs[j]->setChecked(false);
}
return;
}
}
for(int i=0;i<objnum;i++){
if(checkedone==objs[i]){
for(int j=0;j<objnum;j++){
if(i!=j) objs[j]->setChecked(false);
}
return;
}
}
}
void MainWindow::searchac_action(){ //when searchac(mode->searchname) triggered
//add levelsearch
//if current level is levelsearch, do nothing
LevelSearch* levelsearch=dynamic_cast<LevelSearch*>(stack[stack.size()-1]);
if(levelsearch!=nullptr){
qDebug()<< "current level is already levelsearch!!";
return; //do nothing
}
LevelMain* levelmain=dynamic_cast<LevelMain*>(stack[0]); //stack[0] must levelmain
if(levelmain==nullptr){
qDebug()<<"fatal error !! stack[0] isnot levelmain";
return;
}
levelmain->searchbtn_clicked();
}
void MainWindow::back2m(){ //back to main level
if(stack.size()==1) return;
while(stack.size()>1){
stack[stack.size()-1]->hide();
delete stack[stack.size()-1];
stack.pop_back();
}
stack[0]->show();
}
void MainWindow::back2u(){
if(stack.size()==1) return;
stack[stack.size()-1]->hide();
delete stack[stack.size()-1];
stack.pop_back();
stack[stack.size()-1]->show();
}
MainWindow::~MainWindow()
{
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.