blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f1a33c40a65080c979eb231ba14a87f629ade9ad | 11879f654578e4e0d7c96fa306926e0a632bedf3 | /Cadastro.C++ | 63bd74a84e106e41a1009299571bb1888cd3f90e | [] | no_license | Vimuniz6/A3.C- | c9a8b11f6de8caa3fa5bfc7b2d64566a89dab05d | a64ec69d311fe8b2c8e9f4b764b3950882efc7ee | refs/heads/main | 2023-08-01T01:09:43.767979 | 2021-09-26T15:57:27 | 2021-09-26T15:57:27 | 410,595,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,468 | # inclui <stdio.h>
# inclui <stdlib.h>
# inclui <string.h>
# inclua <locale.h>
typedef struct cadastro
{
int codigoCliente;
char nome [ 30 ];
int anoNasc;
float totalGasto;
} cliente;
void cadastrarCliente (cliente * cad, int * contador) {
getchar ();
printf ( " \ n Digite o Nome do cliente: \ n " );
scanf ( " % 30 [^ \ n] " , & (cad + * contador) -> nome);
printf ( " \ n Digite o ano de nascimente do cliente: \ n " );
scanf ( " % d " , & (cad + * contador) -> anoNasc);
printf ( " \ n Digite o gasto total do cliente: \ n " );
scanf ( " % f " , & (cad + * contador) -> totalGasto);
(cad + * contador) -> codigoCliente = * contador + 1 ;
* contador = * contador + 1 ;
}
void editarCliente (cliente * cad, int contador) {
codigo int , opcao;
printf ( " \ n Digite o id do cliente que deseja atualizar o montante de compras, ids disponíveis de 1 a% d \ n " , contador);
scanf ( " % d " , & codigo);
para ( int i = 0 ; i <contador; i ++)
{
if (codigo == (cad + i) -> codigoCliente)
{
printf ( " \ n Esse cliente que deseja atualizar o montante de compras? \ n " );
printf ( " \ n% d. \ t% s \ t% d \ t% .2f \ n " , (cad + i) -> codigoCliente, (cad + i) -> nome, (cad + i) -> anoNasc, (cad + i) -> Gasto total);
printf ( " \ n 1-Sim \ n 2-Não \ n " );
scanf ( " % d " , & opcao);
if (opcao == 1 )
{
printf ( " \ n Digite o novo montante de compraso \ n " );
scanf ( " % f " , & (cad + i) -> totalGasto);
printf ( " \ n% d. \ t% s \ t% d \ t% .2f \ n " , (cad + i) -> codigoCliente, (cad + i) -> nome, (cad + i) -> anoNasc, (cad + i) -> Gasto total);
}
pausa;
}
outro
{
printf ( " id do cliente não encontrado " );
}
}
}
int excluirCliente (cliente * cad, int contador, cliente * aux)
{
codigo int , opcao, x = 0 ;
printf ( " \ n Digite o id do cliente que deseja excluir% d \ n " , contador);
scanf ( " % d " , & codigo);
para ( int i = 0 ; i <contador; i ++)
{
if (codigo == (cad + i) -> codigoCliente)
{
printf ( " \ n Esse cliente que deseja excluir? \ n " );
printf ( " \ n% d. \ t% s \ t% d \ t% .2f \ n " , (cad + i) -> codigoCliente, (cad + i) -> nome, (cad + i) -> anoNasc, (cad + i) -> Gasto total);
printf ( " \ n 1-Sim \ n 2-Não \ n " );
scanf ( " % d " , & opcao);
if (opcao == 1 )
{
para ( int j = 0 ; j <contador; j ++)
{
if ((cad + j) -> codigoCliente! = codigo)
{
(aux + x) -> codigoCliente = (cad + j) -> codigoCliente;
strcpy ((aux + x) -> nome, (cad + j) -> nome);
(aux + x) -> anoNasc = (cad + j) -> anoNasc;
(aux + x) -> Gasto total = (cad + j) -> Gasto total;
x ++;
}
}
para ( int j = 0 ; j <x; j ++)
{
(cad + j) -> codigoCliente = j + 1 ;
strcpy ((cad + j) -> nome, (aux + j) -> nome);
(cad + j) -> anoNasc = (aux + j) -> anoNasc;
(cad + j) -> totalGasto = (aux + j) -> totalGasto;
}
}
retorno - 1 ;
}
outro
{
printf ( " id do cliente não encontrado " );
}
}
}
void zerarMontante (cliente * cad, int contador) {
para ( int i = 0 ; i <contador; i ++)
{
(cad + i) -> Gasto total = 0 ;
}
}
void melhorComprador (cliente * cad, int contador) {
int aux = cad-> totalGasto, cod;
para ( int i = 0 ; i <contador; i ++)
{
if (aux> (cad + i) -> totalGasto)
{
cod = (cad + i) -> codigoCliente;
}
}
printf ( " \ n \ t MELHOR CLIENTE \ n " );
printf ( " --------------------------------- " );
para ( int i = 0 ; i <contador; i ++)
{
if (cod == (cad + i) -> codigoCliente)
{
printf ( " \ n% d. \ t% s \ t% d \ t% .2f \ n " , (cad + i) -> codigoCliente, (cad + i) -> nome, (cad + i) -> anoNasc, (cad + i) -> Gasto total);
}
}
printf ( " --------------------------------- " );
}
void buscaCliente (cliente * cad, int contador) {
int cod;
printf ( " \ n Digite o id do cliente: \ n " );
scanf ( " % d " , & cod);
printf ( " \ n \ t CLIENTE \ n " );
printf ( " --------------------------------- " );
para ( int i = 0 ; i <contador; i ++)
{
if (cod == (cad + i) -> codigoCliente)
{
printf ( " \ n% d. \ t% s \ t% d \ t% .2f \ n " , (cad + i) -> codigoCliente, (cad + i) -> nome, (cad + i) -> anoNasc, (cad + i) -> Gasto total);
}
}
printf ( " --------------------------------- " );
}
void imprimir (cliente * cad, int contador) {
printf ( " \ n \ t LISTA DE CLIENTES \ n " );
printf ( " --------------------------------- " );
para ( int i = 0 ; i <contador; i ++)
{
printf ( " \ n% d. \ t% s \ t% d \ t% .2f \ n " , (cad + i) -> codigoCliente, (cad + i) -> nome, (cad + i) -> anoNasc, (cad + i) -> Gasto total);
}
printf ( " --------------------------------- " );
}
int main () {
setlocale (LC_ALL, " português " );
cliente * cad;
cliente * aux;
cad = (cliente *) calloc ( 10 , sizeof (cliente));
aux = (cliente *) calloc ( 10 , sizeof (cliente));
int opcao, contador = 0 ;
Faz
{
printf ( " \ n 1-Cadastro cliente \ n " );
printf ( " \ n 2-Atualizar o montante de compras \ n " );
printf ( " \ n 3-Remover cliente \ n " );
printf ( " \ n 4-Zerar todos os montantes de compras \ n " );
printf ( " \ n 5-Listar o cliente melhor comprador \ n " );
printf ( " \ n 6-Buscar cliente \ n " );
printf ( " \ n 7-Listar clientes \ n " );
printf ( " \ n 0-Sair \ n " );
printf ( " \ n \ n Digite a opção escolha: \ n " );
scanf ( " % d " , & opcao);
switch (opcao)
{
caso 1 :
cadastrarCliente (cad, & contador);
if (contador == 10 || contador% 10 == 0 )
{
printf ( " \ n Lista de cliente cheia, deseja criar mais 10 espaços para clientes? \ n " );
printf ( " \ n 1-Sim \ n 2-Não \ n " );
scanf ( " % d " , & opcao);
if (opcao)
{
cad = (cliente *) realloc (cad, ((((contador + 1 ) / 10 ) * 10 ) * sizeof (cliente)));
aux = (cliente *) realloc (cad, ((((contador + 1 ) / 10 ) * 10 ) * sizeof (cliente)));
}
outro
{
pausa;
}
}
pausa;
caso 2 :
editarCliente (cad, contador);
pausa;
caso 3 :
contador = contador + excluirCliente (cad, contador, aux);
pausa;
caso 4 :
zerarMontante (cad, contador);
imprimir (cad, contador);
pausa;
caso 5 :
melhorComprador (cad, contador);
pausa;
caso 6 :
buscaCliente (cad, contador);
pausa;
caso 7 :
imprimir (cad, contador);
pausa;
padrão:
if (opcao! = 0 )
{
printf ( " \ n Opção inválida \ n " );
}
pausa;
}
} enquanto (opcao! = 0 );
}
| [
"noreply@github.com"
] | noreply@github.com | |
dc36b66a463dfa56611657c7ca8375d0de120c40 | de7a47bbe1ce3cf04d338366188257cf61f8473c | /ConsoleApplication2/stdafx.h | add05d605662560c9607f8495db8de98f3fcd417 | [] | no_license | by1c/MemDllLoader | 422799d5f14fbb477a392dd191164b9b3098ca7a | 409b51cff56ead5ac2fdf7596daae0d1dc4c5700 | refs/heads/master | 2023-03-17T17:41:46.050655 | 2018-07-31T13:06:52 | 2018-07-31T13:06:52 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 469 | h | // stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: 在此处引用程序需要的其他头文件
#include <iostream>
#include <memory>
#include <string>
using namespace std;
#include <cstdlib>
#include <fstream>
#include <Windows.h>
#pragma comment(lib,"MemLoadLibLib.lib")
| [
"noreply@github.com"
] | noreply@github.com |
5f3a710ac999dc24f907abcfaf78d6ebde9868bc | f9ab50677516460292fa8f444b252195f40c6094 | /src/core/deel.boost.python/revise/boost/python/wrapper.hpp | 52701e8fc12ba23bb7887bde2586823c1c567b63 | [
"BSL-1.0"
] | permissive | DD-L/lproxy | d753f340c24de65a728082ba576a3b69003ee112 | 333db49d446faad445a49955c335c9cd230880d4 | refs/heads/master | 2020-05-22T08:09:20.209701 | 2016-09-25T07:23:47 | 2016-09-25T07:23:47 | 36,083,975 | 13 | 4 | null | 2016-08-23T06:35:37 | 2015-05-22T16:51:10 | C++ | UTF-8 | C++ | false | false | 1,123 | hpp | // Copyright David Abrahams 2004. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef WRAPPER_DWA2004720_HPP
# define WRAPPER_DWA2004720_HPP
# include <deel.boost.python/revise/boost/python/detail/wrapper_base.hpp>
# include <deel.boost.python/revise/boost/python/override.hpp>
# include <deel.boost.python/revise/boost/python/converter/registered.hpp>
# include <deel.boost.python/revise/boost/python/detail/sfinae.hpp>
namespace boost { namespace python {
template <class T>
class wrapper : public detail::wrapper_base
{
public:
// Do not touch this implementation detail!
typedef T _wrapper_wrapped_type_;
protected:
override get_override(char const* name) const
{
typedef detail::wrapper_base base;
converter::registration const& r
= converter::registered<T>::converters;
PyTypeObject* type = r.get_class_object();
return this->base::get_override(name, type);
}
};
}} // namespace boost::python
#endif // WRAPPER_DWA2004720_HPP
| [
"deel@d-l.top"
] | deel@d-l.top |
d220ea6711afb8560c604046034c78b1714e9a93 | 4d171a200367785d6ded244516fbb7e29d7c94c4 | /Python/for.cpp | 6f53dad90750a45faf6aa83028e27426f0e3ae89 | [] | no_license | furkanhtk/Microhomework | b43cbb1dbe94d86812e5be5cf533ab720c787c18 | d534653cd8b3a1030e4ad767e5e7effd75e0ac33 | refs/heads/master | 2022-09-11T07:27:18.308824 | 2020-05-28T18:34:42 | 2020-05-28T18:34:42 | 264,287,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 237 | cpp | int func_and(int num4, int num5)
{
return num4 && num5 ;
}
int func_or(int num4, int num5)
{
return num4 || num5 ;
}
int main () {
int output;
int output2;
output = func_and(10, 20);
output = func_or(10, 20);
}
| [
"furkanhtk"
] | furkanhtk |
29c4d7daa839cb3f691a14d78896017ae9242cc0 | 11d02726300fbf3eb8a4b04f01cb234e12532bbb | /Mariam1/C++ Projects/Classwork21.03.18/Age20-30Short.cpp | 43839e38cac1e1115b506cc138018553742319f9 | [] | no_license | mariam171196/group-2 | c672324b80d4f04feca1a89b8925b0b710d79ea5 | 84a6f838438e2167ec979f8dce80d738b28a4838 | refs/heads/master | 2021-04-26T22:30:38.730658 | 2018-05-10T05:50:02 | 2018-05-10T05:50:02 | 124,104,216 | 0 | 0 | null | 2018-03-06T16:12:07 | 2018-03-06T16:12:07 | null | UTF-8 | C++ | false | false | 194 | cpp | #include <iostream>
int main () {
int age;
int a;
std::cout << "Enter your age!\n";
std::cin >> age;
a = (age > 20 && age < 30) ? 1 : 0;
std::cout << a;
return 0;
}
| [
"Karapetyan.Mariam21@gmail.com"
] | Karapetyan.Mariam21@gmail.com |
88b9f9724f63505a951cc0a20b2e25135b1b25d0 | a1fbf16243026331187b6df903ed4f69e5e8c110 | /cs/sdk/3d_sdk/maya/ver-2008/devkit/plug-ins/hwToonShader_NV20.cpp | 1a769922ffad301d8a49b1452c3ab1eeff09f7a6 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | OpenXRay/xray-15 | ca0031cf1893616e0c9795c670d5d9f57ca9beff | 1390dfb08ed20997d7e8c95147ea8e8cb71f5e86 | refs/heads/xd_dev | 2023-07-17T23:42:14.693841 | 2021-09-01T23:25:34 | 2021-09-01T23:25:34 | 23,224,089 | 64 | 23 | NOASSERTION | 2019-04-03T17:50:18 | 2014-08-22T12:09:41 | C++ | UTF-8 | C++ | false | false | 35,706 | cpp | //-
// ==========================================================================
// Copyright (C) 1995 - 2006 Autodesk, Inc. and/or its licensors. All
// rights reserved.
//
// The coded instructions, statements, computer programs, and/or related
// material (collectively the "Data") in these files contain unpublished
// information proprietary to Autodesk, Inc. ("Autodesk") and/or its
// licensors, which is protected by U.S. and Canadian federal copyright
// law and by international treaties.
//
// The Data is provided for use exclusively by You. You have the right
// to use, modify, and incorporate this Data into other products for
// purposes authorized by the Autodesk software license agreement,
// without fee.
//
// The copyright notices in the Software and this entire statement,
// including the above license grant, this restriction and the
// following disclaimer, must be included in all copies of the
// Software, in whole or in part, and all derivative works of
// the Software, unless such copies or derivative works are solely
// in the form of machine-executable object code generated by a
// source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
// AUTODESK DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED
// WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF
// NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
// PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE, OR
// TRADE PRACTICE. IN NO EVENT WILL AUTODESK AND/OR ITS LICENSORS
// BE LIABLE FOR ANY LOST REVENUES, DATA, OR PROFITS, OR SPECIAL,
// DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK
// AND/OR ITS LICENSORS HAS BEEN ADVISED OF THE POSSIBILITY
// OR PROBABILITY OF SUCH DAMAGES.
//
// ==========================================================================
//+
///////////////////////////////////////////////////////////////////
//
// NOTE: PLEASE READ THE README.TXT FILE FOR INSTRUCTIONS ON
// COMPILING AND USAGE REQUIREMENTS.
//
// DESCRIPTION: NV20-specific (Geforce3) sample shader.
// This shader is meant to allow cartoon-like effects.
// It allows the user to specify a base decal texture,
// and a lighting look-up texture.
//
// This shader builds on the foundation demonstrated in the
// hwUnlitShader.
//
//
///////////////////////////////////////////////////////////////////
// Uncomment the #ifdef below if you want to debug the vertex program by
// output a COL0 value that corresponds to an intermediate calculation.
// The only sane way we could find to debug that thing.
//#define DEBUGGING_VERTEX_PROGRAM 1
#ifdef WIN32
#pragma warning( disable : 4786 ) // Disable STL warnings.
#endif
#include <maya/MIOStream.h>
#include <math.h>
#include <maya/MString.h>
#include <maya/MPlug.h>
#include <maya/MDagPath.h>
#include <maya/MDataBlock.h>
#include <maya/MDataHandle.h>
#include <maya/MArrayDataHandle.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MFnLightDataAttribute.h>
#include <maya/MFloatVector.h>
#include <maya/MFnLight.h>
#include <maya/MFnStringData.h>
#include <maya/MFnPlugin.h>
#include <maya/MGlobal.h>
#include <maya/MSceneMessage.h>
#include <maya/MPoint.h>
#include <maya/MMatrix.h>
#include <maya/MVector.h>
#include <maya/MEulerRotation.h>
#include <maya/MFnNonAmbientLight.h>
// Include NVIDIA's helper libraries. These libraries have
// copyright info in them so we cannot release them but we
// can use them to verify that the API works correctly.
//
#include <GL/gl.h>
#include <GL/glu.h>
#include <gl/glext.h>
#define GLH_EXT_SINGLE_FILE
#include "glh_extensions.h"
#undef GL_NV_vertex_array_range
#include "glh_genext.h"
#include "glh_obs.h"
using namespace glh;
#include "hwToonShader_NV20.h"
#include "ShadingConnection.h"
MTypeId hwToonShader_NV20::id( 0x00105443 );
/*static*/ const unsigned int hwToonShader_NV20::lookup_texture_size(256);
void hwToonShader_NV20::postConstructor( )
{
setMPSafe(false);
}
// Static attribute instances.
//
MObject hwToonShader_NV20::color;
MObject hwToonShader_NV20::colorR;
MObject hwToonShader_NV20::colorG;
MObject hwToonShader_NV20::colorB;
MObject hwToonShader_NV20::lightModel;
MObject hwToonShader_NV20::lightModelR;
MObject hwToonShader_NV20::lightModelG;
MObject hwToonShader_NV20::lightModelB;
MObject hwToonShader_NV20::camera;
MObject hwToonShader_NV20::cameraX;
MObject hwToonShader_NV20::cameraY;
MObject hwToonShader_NV20::cameraZ;
MObject hwToonShader_NV20::uCoord;
MObject hwToonShader_NV20::vCoord;
MObject hwToonShader_NV20::uvCoord;
MObject hwToonShader_NV20::uBias;
MObject hwToonShader_NV20::vBias;
MObject hwToonShader_NV20::uvFilterSize;
MObject hwToonShader_NV20::uvFilterSizeX;
MObject hwToonShader_NV20::uvFilterSizeY;
MObject hwToonShader_NV20::shininess;
MObject hwToonShader_NV20::lightColor;
MObject hwToonShader_NV20::lightColorR;
MObject hwToonShader_NV20::lightColorG;
MObject hwToonShader_NV20::lightColorB;
void hwToonShader_NV20::printGlError( const char *call )
{
GLenum error;
while( (error = glGetError()) != GL_NO_ERROR ) {
assert(0);
cerr << call << ":" << error << " is " << (const char *)gluErrorString( error ) << "\n";
}
}
// The Vertex Program for the textured-light-model shading effect.
// Meant to be used as a cartoon shader.
//
// CONSTANTS:
// 0- 3 4x4 ModelView-Projection composite matrix
// 4- 7 4x4 ModelView matrix
// 8-10 light amb/diff/spec
// 11 light dir vector (from surface to light, in object space)
// 12 camera position in object space (possibly not normalized)
// VERTEX REGISTERS (mapped so that standard gl calls work):
// 0 - coord
// 2 - normal
// 3 - primary color
// 8 - texcoord0 (lighting look-up table)
// 9 - texcoord1 (decal, optional)
// REGISTERS:
//
// R0 - normalized view (surface-to-camera) direction in object space.
// R1 - normalized surface normal in object space.
// R2 - normalized light (surface-to-light) direction.
//
//
char vertexProgramString[] =
"!!VP1.0\n"
// Multiply the vertex coords by the modelview-projection composite matrix,
// to get clip space coordinates.
"DP4 o[HPOS].x, c[0], v[0];"
"DP4 o[HPOS].y, c[1], v[0];"
"DP4 o[HPOS].z, c[2], v[0];"
"DP4 o[HPOS].w, c[3], v[0];"
// Normalize the N (normal), in case the modelview matrix is not a simple rotation.
"MOV R1, v[2];"
"DP3 R1.w, R1, R1;"
"RSQ R1.w, R1.w;"
"MUL R1.xyz, R1, R1.w;"
// Normalize the L (light) direction.
"MOV R2, c[11];"
"DP3 R2.w, R2, R2;"
"RSQ R2.w, R2.w;"
"MUL R2.xyz, R2, R2.w;"
// The vertex position, normal and light positions are expressed in object space at
// this point. We need to find the view direction in object space too.
"ADD R0, c[12], -v[0];" // view direction, from surface to camera.
"DP3 R0.w, R0, R0;" // normalize the view direction.
"RSQ R0.w, R0.w;"
"MUL R0.xyz, R0, R0.w;"
// Find the texture coordinates to fetch from the toon-param texture.
// u = N dot L.
// v = N dot V.
"DP3 o[TEX0].x, R1, R2;"
"DP3 o[TEX0].y, R1, R0;"
// Move the texture coordinates from tex 1 if appropriate.
"MOV o[TEX1], v[9];"
#ifndef DEBUGGING_VERTEX_PROGRAM
// Put diffuse lighting into color.
"MUL o[COL0], v[3], c[9];"
#else
// VISUALIZE VECTOR
"MOV o[COL0], R2;" // normalized light
#endif
"END";
char vertexProgramStringPoint[] =
"!!VP1.0\n"
// Multiply the vertex coords by the modelview-projection composite matrix,
// to get clip space coordinates.
"DP4 o[HPOS].x, c[0], v[0];"
"DP4 o[HPOS].y, c[1], v[0];"
"DP4 o[HPOS].z, c[2], v[0];"
"DP4 o[HPOS].w, c[3], v[0];"
// Normalize the N (normal), in case the modelview matrix is not a simple rotation.
"MOV R1, v[2];"
"DP3 R1.w, R1, R1;"
"RSQ R1.w, R1.w;"
"MUL R1.xyz, R1, R1.w;"
// Compute normalize the L (light) direction.
"ADD R2, c[11], -v[0];"
"DP3 R2.w, R2, R2;"
"RSQ R2.w, R2.w;"
"MUL R2.xyz, R2, R2.w;"
// The vertex position, normal and light positions are expressed in object space at
// this point. We need to find the view direction in object space too.
"ADD R0, c[12], -v[0];" // view direction, from surface to camera.
"DP3 R0.w, R0, R0;" // normalize the view direction.
"RSQ R0.w, R0.w;"
"MUL R0.xyz, R0, R0.w;"
// Find the texture coordinates to fetch from the toon-param texture.
// u = N dot L.
// v = N dot V.
"DP3 o[TEX0].x, R1, R2;"
"DP3 o[TEX0].y, R1, R0;"
// Move the texture coordinates from tex 1 if appropriate.
"MOV o[TEX1], v[9];"
#ifndef DEBUGGING_VERTEX_PROGRAM
// Put diffuse lighting into color.
"MUL o[COL0], v[3], c[9];"
// "MOV o[COL0], c[9];"
#else
// VISUALIZE VECTOR
"MOV o[COL0], R2;" // normalized light
#endif
"END";
char vertexProgramStringPointDecay[] =
"!!VP1.0\n"
// Multiply the vertex coords by the modelview-projection composite matrix,
// to get clip space coordinates.
"DP4 o[HPOS].x, c[0], v[0];"
"DP4 o[HPOS].y, c[1], v[0];"
"DP4 o[HPOS].z, c[2], v[0];"
"DP4 o[HPOS].w, c[3], v[0];"
// Normalize the N (normal), in case the modelview matrix is not a simple rotation.
"MOV R1, v[2];"
"DP3 R1.w, R1, R1;"
"RSQ R1.w, R1.w;"
"MUL R1.xyz, R1, R1.w;"
// Compute normalize the L (light) direction.
"ADD R2, c[11], -v[0];"
"DP3 R2.w, R2, R2;"
"RSQ R2.w, R2.w;"
"MUL R2.xyz, R2, R2.w;"
// The vertex position, normal and light positions are expressed in object space at
// this point. We need to find the view direction in object space too.
"ADD R0, c[12], -v[0];" // view direction, from surface to camera.
"DP3 R0.w, R0, R0;" // normalize the view direction.
"RSQ R0.w, R0.w;"
"MUL R0.xyz, R0, R0.w;"
// Find the texture coordinates to fetch from the toon-param texture.
// u = N dot L.
// v = N dot V.
"DP3 o[TEX0].x, R1, R2;"
"DP3 o[TEX0].y, R1, R0;"
// Move the texture coordinates from tex 1 if appropriate.
"MOV o[TEX1], v[9];"
#ifndef DEBUGGING_VERTEX_PROGRAM
// Multiply diffuse lighting into material color.
// Take into account decay
"MOV R4, c[9];"
"MOV R5, c[9];"
"MUL R5.xyz, R4, R2.w;"
"MUL o[COL0], v[3], R5;"
#else
// VISUALIZE VECTOR
"MOV o[COL0], R2;" // normalized light
#endif
"END";
void initVertexProgram(const char vertexProgramCode[], GLuint* pVertexProgramId)
{
// Allocate and initialize the vertex program.
glGenProgramsNV(1, pVertexProgramId);
GLenum error = glGetError();
assert(error == GL_NO_ERROR);
// Load the program.
unsigned int length = strlen(vertexProgramCode);
glLoadProgramNV(GL_VERTEX_PROGRAM_NV, *pVertexProgramId, length,
(const GLubyte *) vertexProgramCode);
error = glGetError();
// If an error occured, find the location in the vertex program
// code and assert.
if (error != GL_NO_ERROR)
{
// If an error occured, it's most likely due to a syntax or
// logic error in the vertex program. The error position
// below will contain the index in the vertex program
// string that is faulty. See the NV_vertex_program
// extension specification for more details.
if (error == GL_INVALID_OPERATION)
{
int error_position = -2;
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_NV, &error_position);
// Most likely a bug in the vertex program code...
assert(0);
}
}
}
// Load the vertexProgram and fill in the necessary constants used in the vertex program.
//
void hwToonShader_NV20::loadVertexProgramGL()
{
GLenum error = glGetError();
assert(!error);
// If the vertex programs haven't been loaded yet,
// do it now. (Note that they are shared between all contexts.)
if (!fVertexProgramsLoaded)
{
initVertexProgram(vertexProgramString, &fVertexProgramDirectional);
initVertexProgram(vertexProgramStringPointDecay, &fVertexProgramPointDecay);
initVertexProgram(vertexProgramStringPoint, &fVertexProgramPointNoDecay);
fVertexProgramsLoaded = true;
}
// Set up the constant values.
//
// CONSTANTS:
// 0- 3 4x4 ModelView-Projection composite matrix
// 4- 7 4x4 ModelView matrix
// 8-10 light amb/diff/spec
// 11 light dir vector (from surface to light)
//
glTrackMatrixNV(GL_VERTEX_PROGRAM_NV, 0, GL_MODELVIEW_PROJECTION_NV, GL_IDENTITY_NV);
glTrackMatrixNV(GL_VERTEX_PROGRAM_NV, 4, GL_MODELVIEW, GL_IDENTITY_NV);
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 8, 1, 1, 1, 1);
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 9, 1, 1, 1, 1);
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 10, 1, 1, 1, 1);
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 11, -lightRotation[0], -lightRotation[1], -lightRotation[2], 0); // light dir...
}
void hwToonShader_NV20::bind_lookup_table()
{
// make_lookup_texture();
lookup_texture->bind();
if (fLookupTextureReprocessed)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, lookup_texture_size, lookup_texture_size, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, lookup_table);
fLookupTextureReprocessed = false;
}
lookup_texture->parameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
lookup_texture->parameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
lookup_texture->parameter(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
lookup_texture->parameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
// Initialize the necessary OpenGL extensions
//
void hwToonShader_NV20::init_ext(const char * ext)
{
if(!glh_init_extension(ext))
{ cerr << "Failed to initialize " << ext << "!" << endl; exit(0); }
}
hwToonShader_NV20::hwToonShader_NV20()
{
// Get an reference to the singleton texture cache.
m_pTextureCache = MTextureCache::instance();
init_ext("GL_ARB_multitexture");
init_ext("GL_NV_register_combiners");
init_ext("GL_NV_vertex_program");
isDirectionalLight = true; // light's rotation is connected to the lightRotation attr
// Set the shininess and shininess scale to absurd values, so that the
// look-up table automatically get recomputed during the first update.
currentShininessValue = -1.0;
currentShininessScale = -1.0;
lookup_texture = NULL;
lookup_table = NULL;
fLookupTextureReprocessed = false;
// Initialize callbacks.
fBeforeNewCB = 0;
fBeforeOpenCB = 0;
fBeforeRemoveReferenceCB = 0;
fMayaExitingCB = 0;
attachSceneCallbacks();
// Initialize the vertex program ids...
fVertexProgramsLoaded = false;
fVertexProgramDirectional = 0;
fVertexProgramPointDecay = 0;
fVertexProgramPointNoDecay = 0;
// All vertex programs will get allocated and loaded
// during the first refresh.
}
hwToonShader_NV20::~hwToonShader_NV20()
{
detachSceneCallbacks();
}
void releaseVertexProgram(GLuint* pVertexProgramId)
{
// If the vertex program id is set...
if (*pVertexProgramId > 0)
{
// Unbind any vertex program...
glBindProgramNV(GL_VERTEX_PROGRAM_NV, 0);
glDeleteProgramsNV(1, pVertexProgramId);
// For sanity, set the id to 0.
*pVertexProgramId = 0;
}
}
void hwToonShader_NV20::releaseEverything()
{
release_lookup_texture();
// Release all loaded vertex programs.
if (fVertexProgramsLoaded)
{
releaseVertexProgram(&fVertexProgramDirectional);
releaseVertexProgram(&fVertexProgramPointDecay);
releaseVertexProgram(&fVertexProgramPointNoDecay);
fVertexProgramsLoaded = false;
}
// Release the texture cache through refcounting.
m_pTextureCache->release();
if(!MTextureCache::getReferenceCount())
{
m_pTextureCache = 0;
}
}
void hwToonShader_NV20::attachSceneCallbacks()
{
fBeforeNewCB = MSceneMessage::addCallback(MSceneMessage::kBeforeNew, releaseCallback, this);
fBeforeOpenCB = MSceneMessage::addCallback(MSceneMessage::kBeforeOpen, releaseCallback, this);
fBeforeRemoveReferenceCB = MSceneMessage::addCallback(MSceneMessage::kBeforeRemoveReference,
releaseCallback, this);
fMayaExitingCB = MSceneMessage::addCallback(MSceneMessage::kMayaExiting, releaseCallback, this);
}
/*static*/
void hwToonShader_NV20::releaseCallback(void* clientData)
{
hwToonShader_NV20 *pThis = (hwToonShader_NV20*) clientData;
pThis->releaseEverything();
}
void hwToonShader_NV20::detachSceneCallbacks()
{
if (fBeforeNewCB)
MMessage::removeCallback(fBeforeNewCB);
if (fBeforeOpenCB)
MMessage::removeCallback(fBeforeOpenCB);
if (fBeforeRemoveReferenceCB)
MMessage::removeCallback(fBeforeRemoveReferenceCB);
if (fMayaExitingCB)
MMessage::removeCallback(fMayaExitingCB);
fBeforeNewCB = 0;
fBeforeOpenCB = 0;
fBeforeRemoveReferenceCB = 0;
fMayaExitingCB = 0;
}
MStatus initializePlugin( MObject obj )
{
MStatus status;
const MString UserClassify( "shader/surface/utility" );
MFnPlugin plugin( obj, PLUGIN_COMPANY, "4.5", "Any");
status = plugin.registerNode( "hwToonShader_NV20", hwToonShader_NV20::id,
hwToonShader_NV20::creator, hwToonShader_NV20::initialize,
MPxNode::kHwShaderNode, &UserClassify );
if (!status) {
status.perror("registerNode");
return status;
}
return MS::kSuccess;
}
MStatus uninitializePlugin( MObject obj )
{
MStatus status;
MFnPlugin plugin( obj );
plugin.deregisterNode( hwToonShader_NV20::id );
if (!status) {
status.perror("deregisterNode");
return status;
}
return MS::kSuccess;
}
void * hwToonShader_NV20::creator()
{
return new hwToonShader_NV20();
}
// Initialize the plug-in. Called once when the plug-in is loaded.
// This mostly involve creating attributes.
MStatus hwToonShader_NV20::initialize()
{
MFnNumericAttribute nAttr;
MStatus status;
MFnTypedAttribute sAttr; // For string attributes
// Create input attributes
colorR = nAttr.create( "colorR", "cr",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f);
colorG = nAttr.create( "colorG", "cg",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(0.5f);
colorB = nAttr.create( "colorB", "cb",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(0.5f);
color = nAttr.create( "color", "c", colorR, colorG, colorB);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f, 0.5f, 0.5f);
nAttr.setUsedAsColor(true);
lightModelR = nAttr.create( "lightModelR", "c2r",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f);
lightModelG = nAttr.create( "lightModelG", "c2g",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f);
lightModelB = nAttr.create( "lightModelB", "c2b",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f);
lightModel = nAttr.create( "lightModel", "c2", lightModelR, lightModelG, lightModelB);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f, 1.0f, 1.0f);
nAttr.setUsedAsColor(true);
uCoord = nAttr.create( "uCoord", "u", MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(0.5f);
vCoord = nAttr.create( "vCoord", "v", MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(0.5f);
uvCoord = nAttr.create( "uvCoord","uv", uCoord, vCoord);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(0.5f, 0.5f );
nAttr.setHidden(true);
uBias = nAttr.create( "uBias", "bu", MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setMin(0.0f);
nAttr.setMax(1.0f);
nAttr.setKeyable(true);
nAttr.setDefault(0.5f);
vBias = nAttr.create( "vBias", "bv", MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setMin(0.0f);
nAttr.setMax(1.0f);
nAttr.setDefault(0.5f);
uvFilterSizeX = nAttr.create( "uvFilterSizeX", "fsx", MFnNumericData::kFloat);
nAttr.setStorable(false);
nAttr.setReadable(true);
nAttr.setWritable(true);
nAttr.setHidden(true);
uvFilterSizeY = nAttr.create( "uvFilterSizeY", "fsy", MFnNumericData::kFloat);
nAttr.setStorable(false);
nAttr.setReadable(true);
nAttr.setWritable(true);
nAttr.setHidden(true);
uvFilterSize = nAttr.create("uvFilterSize","fs",uvFilterSizeX,uvFilterSizeY);
nAttr.setStorable(false);
nAttr.setReadable(true);
nAttr.setWritable(true);
nAttr.setHidden(true);
cameraX = nAttr.create( "cameraX", "camx",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(0.0f);
cameraY = nAttr.create( "cameraY", "camy",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(0.0f);
cameraZ = nAttr.create( "cameraZ", "camz",MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f);
camera = nAttr.create( "camera", "cam", cameraX, cameraY, cameraZ);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(0.0f, 0.0f, 1.0f);
shininess = nAttr.create( "shininess", "sn", MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setMin(0.0f);
nAttr.setMax(1.0f);
nAttr.setDefault(0.5f);
lightColorR = nAttr.create( "lightColorR", "lcr", MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f);
lightColorG = nAttr.create( "lightColorG", "lcg", MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f);
lightColorB = nAttr.create( "lightColorB", "lcb", MFnNumericData::kFloat);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f);
lightColor = nAttr.create( "lightColor", "lc", lightColorR, lightColorG, lightColorB);
nAttr.setStorable(true);
nAttr.setKeyable(true);
nAttr.setDefault(1.0f, 1.0f, 1.0f);
nAttr.setUsedAsColor(true);
// Add the attributes here
addAttribute(color);
addAttribute(lightModel);
addAttribute(uvCoord);
addAttribute(uBias);
addAttribute(vBias);
addAttribute(uvFilterSize);
addAttribute(camera);
addAttribute(shininess);
addAttribute(lightColor);
attributeAffects (colorR, outColor);
attributeAffects (colorG, outColor);
attributeAffects (colorB, outColor);
attributeAffects (color, outColor);
attributeAffects (lightModelR, outColor);
attributeAffects (lightModelG, outColor);
attributeAffects (lightModelB, outColor);
attributeAffects (lightModel, outColor);
attributeAffects (uCoord, outColor);
attributeAffects (vCoord, outColor);
attributeAffects (uvCoord, outColor);
attributeAffects (uBias, outColor);
attributeAffects (vBias, outColor);
attributeAffects (cameraX, outColor);
attributeAffects (cameraY, outColor);
attributeAffects (cameraZ, outColor);
attributeAffects (camera, outColor);
attributeAffects (shininess, outColor);
attributeAffects (lightColorR, outColor);
attributeAffects (lightColorG, outColor);
attributeAffects (lightColorB, outColor);
attributeAffects (lightColor, outColor);
return MS::kSuccess;
}
// This function gets called by Maya to evaluate the texture.
// See "Writing a shading node plug-in" in the documentation
// for more information.
//
MStatus hwToonShader_NV20::compute(
const MPlug& plug,
MDataBlock& block )
{
// Get color and lightModel from the input block.
// Get UV coordinates from the input block.
bool k = false;
k |= (plug==outColor);
k |= (plug==outColorR);
k |= (plug==outColorG);
k |= (plug==outColorB);
if( !k ) return MS::kUnknownParameter;
MFloatVector resultColor(0.0,0.0,0.0);
float& u = block.inputValue( uCoord ).asFloat();
float& v = block.inputValue( vCoord ).asFloat();
float& bu = block.inputValue( uBias ).asFloat();
float& bv = block.inputValue( vBias ).asFloat();
if ( bu <= 0.0 ) bu = 0.001f;
if ( bv <= 0.0 ) bv = 0.001f;
MFloatVector& surfaceColor = block.inputValue( color ).asFloatVector();
MFloatVector& surfaceColor2 = block.inputValue( lightModel ).asFloatVector();
// normalize the UV coords
u = u - int(u);
v = v - int(v);
resultColor = surfaceColor;
// set ouput color attribute
MDataHandle outColorHandle = block.outputValue( outColor );
MFloatVector& outColor = outColorHandle.asFloatVector();
outColor = resultColor;
outColorHandle.setClean();
return MS::kSuccess;
}
// To get 3 float values from the node attribute
//
MStatus hwToonShader_NV20::getFloat3(MObject attr, float value[3])
{
MStatus status = MS::kSuccess;
// Get the attr to use
//
MPlug plug(thisMObject(), attr);
MObject object;
status = plug.getValue(object);
if (!status)
{
status.perror("hwToonShader_NV20::getFloat3 plug.getValue.");
return status;
}
MFnNumericData data(object, &status);
if (!status)
{
status.perror("hwToonShader_NV20::getFloat3 construct data.");
return status;
}
status = data.getData(value[0], value[1], value[2]);
if (!status)
{
status.perror("hwToonShader_NV20::getFloat3 get values.");
return status;
}
return status;
}
// To get a string value from the node attribute
//
MStatus hwToonShader_NV20::getString(MObject attr, MString &str)
{
MPlug plug(thisMObject(), attr);
MStatus status = plug.getValue( str );
return status;
}
/* virtual */
MStatus hwToonShader_NV20::bind(const MDrawRequest& request, M3dView& view)
{
MStatus status;
// Get the decal and lightModel map file names
//
MString decalName = "";
MString lightModelName = "";
ShadingConnection colorConnection(thisMObject(), request.multiPath().partialPathName(), "color");
ShadingConnection lightModelConnection (thisMObject(), request.multiPath().partialPathName(), "lightModel");
// If the lightModel attribute is ultimately connected to a file texture, find its filename.
// otherwise use the default lightModel texture.
if (lightModelConnection.type() == ShadingConnection::TEXTURE &&
lightModelConnection.texture().hasFn(MFn::kFileTexture))
{
// Get the filename of the texture.
MFnDependencyNode textureNode(lightModelConnection.texture());
MPlug filenamePlug( lightModelConnection.texture(), textureNode.attribute(MString("fileTextureName")) );
filenamePlug.getValue(lightModelName);
}
// Fail safe quit
//
if (lightModelName.length() == 0 )
{
view.beginGL();
glPushAttrib( GL_ALL_ATTRIB_BITS ); // This might be too conservative
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
view.endGL();
return MS::kSuccess;
}
view.beginGL();
glPushAttrib( GL_ALL_ATTRIB_BITS );
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
/* Starts Here... */
// stage 0 -- lighting model texture
glActiveTextureARB( GL_TEXTURE0_ARB );
glEnable(GL_TEXTURE_2D);
if(m_pTextureCache)
m_pTextureCache->bind(lightModelConnection.texture(), MTexture::RGBA, false);
// With light color and intensity
//
if (colorConnection.type() != ShadingConnection::TEXTURE)
{
MColor color = colorConnection.constantColor();
glColor4f(color.r, color.g, color.b, color.a);
}
// The register combiner will do the multiplication between
// the fetched light model result and the base (vertex or decal-textured) color
//
glEnable(GL_REGISTER_COMBINERS_NV);
glCombinerParameteriNV(GL_NUM_GENERAL_COMBINERS_NV, 1);
float constColor0[4];
constColor0[0] = constColor0[1] = constColor0[2] = constColor0[3] = 1.0;
glCombinerParameterfvNV(GL_CONSTANT_COLOR0_NV, constColor0);
#ifndef DEBUGGING_VERTEX_PROGRAM
// Combiner stage 0 does the illumination modulation on the vertex color
//
glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_PRIMARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB);
glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB);
glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_ALPHA);
glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_ALPHA);
glCombinerOutputNV(GL_COMBINER0_NV, GL_RGB, GL_SPARE1_NV, GL_DISCARD_NV, GL_DISCARD_NV,
GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE);
#else
// Simplified register combiners to help debugging vertex program.
glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_PRIMARY_COLOR_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB);
glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB);
glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_ALPHA);
glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_TEXTURE3_ARB, GL_UNSIGNED_IDENTITY_NV, GL_ALPHA);
glCombinerOutputNV(GL_COMBINER0_NV, GL_RGB, GL_SPARE1_NV, GL_DISCARD_NV, GL_DISCARD_NV,
GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE);
#endif // DEBUGGING_VERTEX_PROGRAM
// The final Combiner just pass through. May want to add fog later.
//
glFinalCombinerInputNV(GL_VARIABLE_A_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB);
glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB);
glFinalCombinerInputNV(GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB);
glFinalCombinerInputNV(GL_VARIABLE_D_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB);
view.endGL();
return MS::kSuccess;
}
/* virtual */
MStatus hwToonShader_NV20::unbind(const MDrawRequest& request,
M3dView& view)
{
view.beginGL();
glDisable(GL_REGISTER_COMBINERS_NV);
glActiveTextureARB( GL_TEXTURE0_ARB );
glDisable(GL_TEXTURE_2D);
glPopClientAttrib();
glPopAttrib();
view.endGL();
return MS::kSuccess;
}
/* virtual */
MStatus hwToonShader_NV20::geometry( const MDrawRequest& request,
M3dView& view,
int prim,
unsigned int writable,
int indexCount,
const unsigned int * indexArray,
int vertexCount,
const int * vertexIDs,
const float * vertexArray,
int normalCount,
const float ** normalArrays,
int colorCount,
const float ** colorArrays,
int texCoordCount,
const float ** texCoordArrays)
{
// We assume triangles here.
//
if (prim != GL_TRIANGLES)
return MS::kSuccess;
view.beginGL();
// Find out if we have a directional light before
// loading the vertex program since we use a different
// vertex program depending on whether the light is a directional
// one or not
//
isDirectionalLight = true; // Assume is directional
isNonAmbientLight = false;
boolean useDefaultLight = false;
unsigned int numLights;
MDagPath lightPath;
view.getLightCount( numLights );
if (numLights)
{
M3dView::LightingMode mode;
view.getLightingMode(mode);
if (mode == M3dView::kLightDefault)
{
useDefaultLight = true;
isDirectionalLight = true;
}
else
{
view.getLightPath( 0, lightPath );
MObject lightObj = lightPath.node();
isDirectionalLight = lightObj.hasFn( MFn::kDirectionalLight );
isNonAmbientLight = lightObj.hasFn( MFn::kNonAmbientLight );
if (isNonAmbientLight)
{
MFnNonAmbientLight mNonAmbientLight(lightObj);
if (mNonAmbientLight.decayRate() == 0)
isNonAmbientLight = false;
}
}
}
loadVertexProgramGL();
// Bind and enable the appropriate vertex program,
// depending on light type.
//
if (isDirectionalLight)
glBindProgramNV(GL_VERTEX_PROGRAM_NV, fVertexProgramDirectional);
else if (isNonAmbientLight)
glBindProgramNV(GL_VERTEX_PROGRAM_NV, fVertexProgramPointDecay);
else
glBindProgramNV(GL_VERTEX_PROGRAM_NV, fVertexProgramPointNoDecay);
// Assert if an error occurs after binding the vertex programs.
GLenum error = glGetError();
assert(error == GL_NO_ERROR);
// Enable the vertex program.
glEnable(GL_VERTEX_PROGRAM_NV);
// Get object's inverse matrix (ie: from world to object space.)
MDagPath objPath = request.multiPath();
MMatrix objMatrix = objPath.inclusiveMatrixInverse();
// Get the light direction in object space.
// This code assumes that there is a directional light in the scene,
// and that it is the first light in DAG order.
//
if (numLights)
{
// Handle default lighting mode
if (useDefaultLight )
{
// Provide the direction to the vertex program (constant 11)
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 11, 0, 0, 1, 1);
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 9, 1,1,1,1);
}
else
{
view.getLightPath( 0, lightPath );
MMatrix matrix = lightPath.inclusiveMatrix();
isDirectionalLight = lightPath.node().hasFn( MFn::kDirectionalLight );
// Get rotation of a directional light in object space
if (isDirectionalLight)
{
// Get rotation in world space
MVector lightDir(0,0,1); // origin
lightDir *= matrix;
// Transform into object space
lightDir *= objMatrix;
// Provide the direction to the vertex program (constant 11)
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 11, lightDir.x, lightDir.y, lightDir.z, 1);
}
// Get the position of a non-directional light in object space
else
{
MPoint lightPos(0,0,0); // origin
lightPos *= matrix;
// Transform into object space
lightPos *= objMatrix;
// Provide the position to the vertex program (constant 11)
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 11, lightPos.x, lightPos.y, lightPos.z, 1);
}
MFnLight mLight(lightPath.node());
// Set the light's color.
MColor lightColor = mLight.color();
float intensity = mLight.intensity();
lightColor.r *= intensity;
lightColor.g *= intensity;
lightColor.b *= intensity;
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 9, lightColor.r,
lightColor.g, lightColor.b, 1);
}
}
else
{
// Set some default values
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 11, 0, 0, 1, 1);
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 9, 1.0, 1.0, 1.0, 1);
}
// Find the camera position in geometry's object space
float cameraPos[4] = {0.0f, 0.0f, 0.0f, 0.0f};
{
MDagPath camDag;
view.getCamera(camDag);
MPoint cameraInObject(0,0,0);
MMatrix cameraToWorldMatrix = camDag.inclusiveMatrix();
cameraInObject *= cameraToWorldMatrix; // to world
cameraInObject *= objMatrix;
glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 12, cameraInObject.x, cameraInObject.y, cameraInObject.z, 1);
}
// VERTEX REGISTERS (Attributes):
// 0 - coord
// 2 - normal
glVertexAttribPointerNV( 0, 3, GL_FLOAT, 0, vertexArray );
glVertexAttribPointerNV( 2, 3, GL_FLOAT, 0, normalArrays[0] );
glEnableClientState( GL_VERTEX_ATTRIB_ARRAY0_NV );
glEnableClientState( GL_VERTEX_ATTRIB_ARRAY2_NV );
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, indexArray);
glDisableClientState( GL_VERTEX_ATTRIB_ARRAY0_NV );
glDisableClientState( GL_VERTEX_ATTRIB_ARRAY2_NV );
glDisable(GL_VERTEX_PROGRAM_NV);
glClientActiveTextureARB(GL_TEXTURE0_ARB);
view.endGL();
return MS::kSuccess;
}
/* virtual */
int hwToonShader_NV20::normalsPerVertex()
{
return 1;
}
/* virtual */
int hwToonShader_NV20::texCoordsPerVertex()
{
return 1;
}
// Release the lookup texture/image.
void hwToonShader_NV20::release_lookup_texture()
{
if (lookup_table)
{
delete lookup_table;
lookup_table = NULL;
}
if (lookup_texture)
{
delete lookup_texture;
lookup_table = NULL;
}
}
| [
"paul-kv@yandex.ru"
] | paul-kv@yandex.ru |
40208b916e30741715e7388b0b5272cd1a0828c0 | 60bb67415a192d0c421719de7822c1819d5ba7ac | /blaze/math/simd/Pow.h | 671e309acfaa66b1ff1ba110e0a95ce249ebdebc | [
"BSD-3-Clause"
] | permissive | rtohid/blaze | 48decd51395d912730add9bc0d19e617ecae8624 | 7852d9e22aeb89b907cb878c28d6ca75e5528431 | refs/heads/master | 2020-04-16T16:48:03.915504 | 2018-12-19T20:29:42 | 2018-12-19T20:29:42 | 165,750,036 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,152 | h | //=================================================================================================
/*!
// \file blaze/math/simd/Pow.h
// \brief Header file for the SIMD power functionality
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_MATH_SIMD_POW_H_
#define _BLAZE_MATH_SIMD_POW_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <blaze/math/simd/BasicTypes.h>
#include <blaze/system/Inline.h>
#include <blaze/system/Vectorization.h>
namespace blaze {
//=================================================================================================
//
// 32-BIT FLOATING POINT SIMD TYPES
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Computes the exponential value of a vector of single precision floating point values.
// \ingroup simd
//
// \param a The vector of single precision floating point base values.
// \param b The vector of single precision floating point exponents.
// \return The resulting vector.
//
// This operation is only available via the SVML for SSE, AVX, MIC, and AVX-512.
*/
template< typename T > // Type of the operands
BLAZE_ALWAYS_INLINE const SIMDfloat pow( const SIMDf32<T>& a, const SIMDf32<T>& b ) noexcept
#if BLAZE_SVML_MODE && ( BLAZE_AVX512F_MODE || BLAZE_MIC_MODE )
{
return _mm512_pow_ps( (~a).eval().value, (~b).eval().value );
}
#elif BLAZE_SVML_MODE && BLAZE_AVX_MODE
{
return _mm256_pow_ps( (~a).eval().value, (~b).eval().value );
}
#elif BLAZE_SVML_MODE && BLAZE_SSE_MODE
{
return _mm_pow_ps( (~a).eval().value, (~b).eval().value );
}
#else
= delete;
#endif
//*************************************************************************************************
//=================================================================================================
//
// 64-BIT FLOATING POINT SIMD TYPES
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Computes the exponential value of a vector of double precision floating point values.
// \ingroup simd
//
// \param a The vector of double precision floating point base values.
// \param b The vector of double precision floating point exponents.
// \return The resulting vector.
//
// This operation is only available via the SVML for SSE, AVX, MIC, and AVX-512.
*/
template< typename T > // Type of the operands
BLAZE_ALWAYS_INLINE const SIMDdouble pow( const SIMDf64<T>& a, const SIMDf64<T>& b ) noexcept
#if BLAZE_SVML_MODE && ( BLAZE_AVX512F_MODE || BLAZE_MIC_MODE )
{
return _mm512_pow_pd( (~a).eval().value, (~b).eval().value );
}
#elif BLAZE_SVML_MODE && BLAZE_AVX_MODE
{
return _mm256_pow_pd( (~a).eval().value, (~b).eval().value );
}
#elif BLAZE_SVML_MODE && BLAZE_SSE_MODE
{
return _mm_pow_pd( (~a).eval().value, (~b).eval().value );
}
#else
= delete;
#endif
//*************************************************************************************************
} // namespace blaze
#endif
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
4320895d00bcad6f36350f24fa1f90162bae8011 | 34e66b5cb29af806c19c0cd18981b9c7b5306292 | /Host.cpp | 68210291ef250710b8c9c2351a69bb65d15b5c5e | [] | no_license | iarihda/DVMRP | a5e29933125263ce9fcd570c2fd79bffa661b058 | 624715b528cd4a8a951b6c3fa2a9ea351240f7a8 | refs/heads/master | 2020-05-28T05:27:39.686258 | 2014-04-02T18:32:24 | 2014-04-02T18:32:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,641 | cpp | #include<iostream>
#include<cstring>
#include<fstream>
#include<ctime>
#include<cerrno>
#include<sstream>
#include<fstream>
#include<cstdlib>
#include<unistd.h>
using namespace std;
int num;
int lan;
char type[10];
int start_time;
int duration;
int count;
int lptr;
void sleep(int s)
{
int sec = int(s*1000000);
usleep(sec);
}
void initialize(char* line[])
{
count = lptr = 0;
num = line[1][0]-'0';
lan = line[2][0]-'0';
strcpy(type,line[3]);
if(strcmp(type,"sender")==0)
{
start_time = atoi(line[4]);
duration = atoi(line[5]);
}
else
{
start_time = 0;
duration = 0;
}
}
void print()
{
cout<<endl<<"Num="<<num<<"\tLan="<<lan<<"\tType="<<type<<"\tStartTime="<<start_time<<"\tDuration"<<duration;
}
string intToString(int n)
{
if(n==0) return "0";
string temp="";
string rv="";
while(n>0)
{
temp+=n%10+48;
n/=10;
}
for(int i=0;i<temp.length();i++)
rv+=temp[temp.length()-i-1];
return rv;
}
void sendData(string str)
{
string hfname = "hout";
hfname.append(intToString(num));
hfname.append(".txt");
ofstream myfile;
myfile.open(hfname.c_str(), fstream::out | fstream::app);
myfile<<str.c_str();
myfile<<"\r\n";
myfile.close();
if(strcmp(type,"sender")==0)
{
cout<<endl<<"In Host "<<num<<endl;
sleep(duration);
count=count+duration;
if(count>=100) exit(0);
sendData(str);
}
}
string* split(string str)
{
string* s=new string[50];
int ix=0;
for(int i=0;i<str.length();i++)
{
if(str[i]==' ')
{
ix++;
i++;
}
s[ix]+=str[i];
}
return s;
}
void readData()
{
cout<<endl<<"In Host "<<num<<endl;
string lfname = "lan";
lfname.append(intToString(lan));
lfname.append(".txt");
ifstream myfile(lfname.c_str());
myfile.seekg(lptr,ios::beg);
string* s=new string[50];
string line;
if(myfile.is_open())
{
while(getline(myfile,line))
{
s=split(line);
if(s[0]=="data")
{
string hfname = "hin";
hfname.append(intToString(num));
hfname.append(".txt");
ofstream myfile1;
myfile1.open(hfname.c_str(), fstream::out | fstream::app);
myfile1<<line;
myfile1<<"\r\n";
myfile1.close();
}
lptr=myfile.tellg();
}
myfile.close();
}
count++;
if(count%10==0)
{
string str="receiver ";
str.append(intToString(lan));
sendData(str);
}
if(count>=100) exit(0);
sleep(1);
readData();
}
int main(int argc, char* argv[])
{
initialize(argv);
string str="data ";
str.append(intToString(lan));
str.append(" ");
str.append(intToString(lan));
if(strcmp(type,"sender")==0)
{
sleep(start_time);
count=count+start_time;
sendData(str);
}
else if(strcmp(type,"receiver")==0)
readData();
return 0;
}
| [
"adhirai.manickam@gmail.com"
] | adhirai.manickam@gmail.com |
7b5cee1bcd99ea88c004df04ab1cb2cb562ce8c4 | 95efaa256914926ac30acbb1a8c89c320c19bf40 | /HePlugin/HCie1931ChartView.cpp | 0aa603a7ebccf3080869eab01d65ae49f3ab505d | [] | no_license | mabo0001/QtCode | bc2d80446a160d97b4034fa1c068324ba939cb20 | 9038f05da33c870c1e9808791f03467dcc19a4ab | refs/heads/master | 2022-08-26T13:36:14.021944 | 2019-07-15T01:12:51 | 2019-07-15T01:12:51 | 266,298,758 | 1 | 0 | null | 2020-05-23T08:54:08 | 2020-05-23T08:54:07 | null | UTF-8 | C++ | false | false | 4,193 | cpp | #include "HCie1931ChartView_p.h"
#include "HCie1931Chart.h"
#include "HPositionTracking.h"
#include "HPluginHelper.h"
#include <QtWidgets/QAction>
HCie1931ChartView::HCie1931ChartView(QWidget *parent) :
HZoomChartView(*new HCie1931ChartViewPrivate, nullptr, parent)
{
init();
}
HCie1931ChartView::~HCie1931ChartView()
{
}
void HCie1931ChartView::setEnableTracking(bool b)
{
Q_D(HCie1931ChartView);
d->tracking->setEnable(b);
d->positionItem->setVisible(b);
}
HCie1931Chart *HCie1931ChartView::chart()
{
Q_D(HCie1931ChartView);
return d->chart;
}
void HCie1931ChartView::init()
{
Q_D(HCie1931ChartView);
d->chart = new HCie1931Chart;
d->tracking = new HPositionTracking(this);
d->positionItem = new QGraphicsSimpleTextItem(d->chart);
d->positionItem->setZValue(100);
d->pointFocusItem = new QGraphicsSimpleTextItem(d->chart);
d->pointFocusItem->setPen(QPen(Qt::red));
d->pointFocusItem->setZValue(100);
d->pointFocusItem->setText(QString("(%1, %2)").arg(0.0, 0, 'f', 4).arg(0.0, 0, 'f', 4));
auto enableCIE = new QAction(tr("色品图(&E)"));
enableCIE->setCheckable(true);
enableCIE->setChecked(d->chart->isEnableCIE());
auto enableHorseshoe = new QAction(tr("马蹄线(&H)"));
enableHorseshoe->setCheckable(true);
enableHorseshoe->setChecked(d->chart->isEnableHorseshoe());
auto enablePlanckian = new QAction(tr("黑体轨迹(&P)"));
enablePlanckian->setCheckable(true);
enablePlanckian->setChecked(d->chart->isEnablePlanckian());
auto enableGrade = new QAction(tr("分级区域(&S)"));
enableGrade->setCheckable(true);
enableGrade->setChecked(d->chart->isEnableGrade());
auto enablePoint = new QAction(tr("打点记录(&O)"));
enablePoint->setCheckable(true);
enablePoint->setChecked(d->chart->isEnablePoint());
auto clearPoint = new QAction(tr("清除打点记录(&C)"));
HPluginHelper::addSeparator(this);
addAction(enableCIE);
addAction(enableHorseshoe);
addAction(enablePlanckian);
addAction(enableGrade);
HPluginHelper::addSeparator(this);
addAction(enablePoint);
addAction(clearPoint);
connect(d->chart, &HCie1931Chart::plotAreaChanged, this, &HCie1931ChartView::handlePlotAreaChanged);
connect(d->chart, &HCie1931Chart::pointFocusChanged, this, &HCie1931ChartView::handlePointFocusChanged);
connect(d->tracking, &HPositionTracking::positionChanged, this, &HCie1931ChartView::handlePositionChanged);
connect(enableCIE, &QAction::toggled, d->chart, &HCie1931Chart::setEnableCIE);
connect(enableHorseshoe, &QAction::toggled, d->chart, &HCie1931Chart::setEnableHorseshoe);
connect(enablePlanckian, &QAction::toggled, d->chart, &HCie1931Chart::setEnablePlanckian);
connect(enableGrade, &QAction::toggled, d->chart, &HCie1931Chart::setEnableGrade);
connect(enablePoint, &QAction::toggled, d->chart, &HCie1931Chart::setEnablePoint);
connect(clearPoint, &QAction::triggered, d->chart, &HCie1931Chart::clearPoint);
setChart(d->chart);
HZoomChartView::init();
}
void HCie1931ChartView::mouseMoveEvent(QMouseEvent *e)
{
Q_D(HCie1931ChartView);
d->tracking->mouseMoveEvent(e);
HZoomChartView::mouseMoveEvent(e);
}
void HCie1931ChartView::mouseDoubleClickEvent(QMouseEvent *e)
{
Q_D(HCie1931ChartView);
if (d->tracking->isEnable())
emit mouseDoubleClicked(chart()->mapToValue(e->pos()));
HZoomChartView::mouseMoveEvent(e);
}
void HCie1931ChartView::handlePlotAreaChanged(QRectF value)
{
Q_D(HCie1931ChartView);
d->tracking->setValidRegion(value);
d->positionItem->setPos(value.left() + 5, value.top() + 5);
d->pointFocusItem->setPos(value.right() - d->pointFocusItem->boundingRect().width() - 5, value.top() + 5);
}
void HCie1931ChartView::handlePointFocusChanged(QPointF pos)
{
Q_D(HCie1931ChartView);
d->pointFocusItem->setText(QString("(%1, %2)").arg(pos.x(), 0, 'f', 4).arg(pos.y(), 0, 'f', 4));
}
void HCie1931ChartView::handlePositionChanged(QPointF pos)
{
Q_D(HCie1931ChartView);
auto p = chart()->mapToValue(pos);
d->positionItem->setText(QString("(%1, %2)").arg(p.x(), 0, 'f', 4).arg(p.y(), 0, 'f', 4));
}
| [
"hexianqi@msn.com"
] | hexianqi@msn.com |
2a123266d147b1a56e7fc1b9809d16dd087ddc52 | 788da62dce9041878fd098e5347408fbf0679ace | /qcom/proprietary/mm-parser/Android_adaptation/src/SourcePort.cpp | 2d7d7fdbf1a95f75df381f51a6cad9c3cfb00537 | [] | no_license | Snapdragon-Computer-Vision-Engine-Team/msm8974-sources2 | e7daa0bf3096e09286fd6e9f3a4e078774e49565 | 8e8a1d7b8b840a7c93e39634d61614665974acb1 | refs/heads/master | 2021-12-15T03:28:26.619350 | 2017-07-25T06:50:38 | 2017-07-25T06:50:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,345 | cpp | /*
* Copyright (c) 2010 - 2012 Qualcomm Technologies, Inc. All Rights Reserved.
* Qualcomm Technologies Proprietary and Confidential.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "SourcePort"
#include <utils/Log.h>
#include "common_log.h"
#include "SourcePort.h"
namespace android {
SourcePort::SourcePort(const sp<DataSource> &source)
: mDataSource(source) {
mOffset = 0;
mRefCnt = 0;
}
SourcePort::~SourcePort() {
}
/**
Read data into the specified buffer (of given size).
return DS_SUCCESS - *pnRead indicates the amount of data read
(*pnRead = 0 and nBufSize > 0 signifies EOS)
DS_WAIT - no data available at the moment call Readable() to wait
DS_FAILURE - generic read failure
*/
iStreamPort::DataSourceReturnCode SourcePort::Read(/*rout*/ unsigned char* pBuf,
/*in*/ int nBufSize,
/*rout*/ int* pnRead){
if (!pBuf) {
LOGE(" Error :: Buffer is NULL \n");
return DS_FAILURE;
}
memset(pBuf, 0, nBufSize);
ssize_t nRet = mDataSource->readAt(mOffset, (void*)pBuf, nBufSize);
if (nRet == -EAGAIN) {
*pnRead = 0;
LOGV("SourcePort::read under-run @ %lld ",mOffset );
return DS_WAIT;
}
else if (nRet <= 0) {
*pnRead = 0;
LOGV("SourcePort::read failed @ %lld with error code %ld ",mOffset, nRet);
return DS_FAILURE;
}
*pnRead = (int)nRet;
return DS_SUCCESS;
}
/**
Repositions the read/write point in an open port to the specified offset.
*pnOutOffset gives the offset after a successful seek.
*/
iStreamPort::DataSourceReturnCode SourcePort::Seek(/*in*/ const int64 nOffset,
/*in*/ const int nWhence,
/*rout*/ int64* pnOutOffset) {
// TODO : check whence
int64 nOrigin = 0;
switch (nWhence) {
case DS_SEEK_SET:
nOrigin = 0;
break;
case DS_SEEK_CUR:
nOrigin = mOffset;
break;
case DS_SEEK_END:
mDataSource->getSize((off64_t*)nOrigin);
break;
default:
break;
}
*pnOutOffset = mOffset = (nOffset + nOrigin);
//LOGV("SourcePort::Seek nOffset = %lld nWhence = %d pnOutOffset = %lld\n",nOffset, nWhence, *pnOutOffset );
return DS_SUCCESS;
}
/**
Get the content length (in bytes).
*/
iStreamPort::DataSourceReturnCode SourcePort::GetContentLength(/*rout*/ int64* pContentLength){
status_t eRet = mDataSource->getSize((off64_t*)pContentLength);
return (OK == eRet ? DS_SUCCESS : DS_FAILURE);
}
/**
Get the underlying data source type.
*/
iStreamPort::DataSourceReturnCode SourcePort::GetSourceType(/*rout*/ DataSourceType* pSourceType){
if (mDataSource->flags() &
(DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) {
*pSourceType = DS_STREAMING_SOURCE;
} else {
*pSourceType = DS_FILE_SOURCE;
}
return DS_SUCCESS;
}
iStreamPort::DataSourceReturnCode SourcePort::GetNumBytesAvailable(/*rout*/ int64* pNumBytesAvailable){
status_t eRet = mDataSource->getSize((off64_t*)pNumBytesAvailable);
return (OK == eRet ? DS_SUCCESS : DS_FAILURE);
}
iStreamPort::DataSourceReturnCode SourcePort::GetStartOffset(/*rout*/ int64* pStartOffset){
if(pStartOffset == NULL)
{
return DS_FAILURE;
}
else
{
*pStartOffset = 0;
}
return DS_SUCCESS;
}
iStreamPort::DataSourceReturnCode SourcePort::GetAvailableOffset(/*rout*/ int64* pAvailableOffset,
/*rout*/ bool* pbEOS){
// NOTE: chaning, reason being if the pbEOS is false the caller thinks the entire data is not available
// in android file playback is treated as streaming, as streamport is used.
//*pbEOS = false;
*pbEOS = true;
status_t eRet = mDataSource->getSize((off64_t*)pAvailableOffset);
LOGV(" SourcePort::GetAvailableOffset pAvailableOffset = %ld \n", *pAvailableOffset);
// If DataSource is not able to provide stream length, then reset with -1
if((OK != eRet) || (0 == *pAvailableOffset))
{
eRet = OK;
*pAvailableOffset = -1;
}
return (OK == eRet ? DS_SUCCESS : DS_FAILURE);
}
/**
Register a callback interface to be invoked when data is available to be read
*(i.e. Read() would return something other than DS_WAIT).
*/
iStreamPort::DataSourceReturnCode SourcePort::Readable(/*in*/ iReadNotificationHandler const* pNotificationHandler){
return DS_SUCCESS;
}
/**
Write data from the specified buffer (of given size).
return DS_SUCCESS - *pnWritten indicates the amount of data written
* DS_FAILURE - generic write failure
*/
iStreamPort::DataSourceReturnCode SourcePort::Write(/*in*/ const unsigned char* pBuf,
/*in*/ int nBufSize,
/*rout*/ int* pnWritten){
return DS_SUCCESS;
}
void* SourcePort::QueryInterface(const AEEIID iid){
return this;
}
uint32 SourcePort::AddRef(){
return ++mRefCnt;
}
uint32 SourcePort::Release(){
return --mRefCnt;
}
/**
Close the data source port - port becomes unusable after this call.
*/
iStreamPort::DataSourceReturnCode SourcePort::Close(){
return DS_SUCCESS;
}
} // namespace android
| [
"xinhe.jiang@itel-mobile.com"
] | xinhe.jiang@itel-mobile.com |
2aabdc79c402021cea70ef83e127ec1b9ca4318a | 8fa761ae282809661933f62d240861281025bb9e | /top_k_optimal_selector.h | b173b0af1f6f16eb9eb8ba01c7bd0ac5a6b547f1 | [] | no_license | MichaelVoe/Masterarbeit | 6b0f35d745f22454ebd5d4b8c53625614938326a | 420471af4e7515a39a5d2b7814fdc66f8331c1af | refs/heads/master | 2022-10-26T21:16:07.316837 | 2020-06-16T06:30:38 | 2020-06-16T06:30:38 | 238,152,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | h | #ifndef SYMBOLIC_TOP_K_OPTIMAL_SELECTOR_H
#define SYMBOLIC_TOP_K_OPTIMAL_SELECTOR_H
#include "plan_database.h"
namespace symbolic {
class TopKSelectorOptimal : public PlanDataBase {
public:
TopKSelectorOptimal(const options::Options &opts);
~TopKSelectorOptimal() {};
void add_plan(const Plan& plan) override;
virtual bool found_enough_plans() const override {
return num_accepted_plans >= num_desired_plans || min_plan_cost == -1;
}
std::string tag() const override {
return "Optimal-Top-K";
}
protected:
int min_plan_cost;
};
}
#endif /* SYMBOLIC_TOP_K_OPTIMAL_SELECTOR_H */
| [
"noreply@github.com"
] | noreply@github.com |
3b3989f2e8435a8cd6874961c5c1f630cb0103ce | 2a077744d7d8d90fd1675a10b83a92dbf37b3770 | /vietnamese-compiler/FirstVisitor.h | 00ddb5098099eb30e4da57cfd92f23ac20d385c7 | [] | no_license | hadiyah97/wci | ed75692b8c2c51d30a54b4a06dbc9c2a8f212654 | 1aa0ba7a5cd61f6533458ac284c407f2dd775450 | refs/heads/master | 2021-02-28T09:48:56.021798 | 2020-10-30T22:07:41 | 2020-10-30T22:07:41 | 245,683,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,377 | h | /*
* FirstVisitor.h
*
* Created on: May 5, 2020
* Author: hadiyah
*/
#ifndef FIRSTVISITOR_H_
#define FIRSTVISITOR_H_
#include <iostream>
#include <unordered_map>
#include "wci/intermediate/TypeSpec.h"
#include "wci/intermediate/SymTabStack.h"
#include "wci/intermediate/SymTabEntry.h"
using namespace wci;
using namespace wci::intermediate;
#include "antlr4-runtime.h"
#include "VietProgVisitor.h"
#include "VietProgBaseVisitor.h"
/**
* This class extends the VietProgBaseVisitor, to create a visitor which only
* handles a subset of the available methods in the superclass.
*/
class FirstVisitor : public VietProgBaseVisitor {
private:
SymTabStack *st_stack;
vector<SymTabEntry *> var_id_list;
vector<VietProgParser::Var_idContext *> var_ctx_list;
bool function_flag;
unordered_map<string, int> local_func_variables;
int current_var_array_index;
public:
// constructor
FirstVisitor();
// destructor
virtual ~FirstVisitor() {}
// visitors
antlrcpp::Any visitProgram(VietProgParser::ProgramContext *ctx) override;
antlrcpp::Any visitDeclaration(VietProgParser::DeclarationContext *ctx);
antlrcpp::Any visitVar_list(VietProgParser::Var_listContext *ctx) override;
antlrcpp::Any visitVar_id(VietProgParser::Var_idContext *ctx) override;
antlrcpp::Any visitType_id(VietProgParser::Type_idContext *ctx) override;
antlrcpp::Any visitAdd_Sub_Expr(VietProgParser::Add_Sub_ExprContext *ctx) override;
antlrcpp::Any visitMul_Div_Expr(VietProgParser::Mul_Div_ExprContext *ctx) override;
antlrcpp::Any visitRelational_Expr(VietProgParser::Relational_ExprContext *ctx) override;
antlrcpp::Any visitVariable_Expr(VietProgParser::Variable_ExprContext *ctx) override;
antlrcpp::Any visitVariable(VietProgParser::VariableContext *ctx) override;
antlrcpp::Any visitNumber_Const_Expr(VietProgParser::Number_Const_ExprContext *ctx) override;
antlrcpp::Any visitNumber(VietProgParser::NumberContext *ctx) override;
antlrcpp::Any visitIntegerConst(VietProgParser::IntegerConstContext *ctx) override;
antlrcpp::Any visitFloatConst(VietProgParser::FloatConstContext *ctx) override;
antlrcpp::Any visitParen_Expr(VietProgParser::Paren_ExprContext *ctx) override;
antlrcpp::Any visitBoolean(VietProgParser::BooleanContext *ctx) override;
antlrcpp::Any visitFunction(VietProgParser::FunctionContext *ctx) override;
};
#endif /* FIRSTVISITOR_H_ */
| [
"48602985+hadiyah97@users.noreply.github.com"
] | 48602985+hadiyah97@users.noreply.github.com |
3a9748b807b6c15eb4133dcf974baf9acb51a847 | 7ee18aa256587f7ace1640ecc647dc5719c2da61 | /jni/exnihilope/registries/manager/IHeatDefaultRegistryProvider.h | 726e04036547d2c0ca698d13b5edbbf354367a8d | [
"Apache-2.0"
] | permissive | Virtualoso/ExNihiloPE | 3491ba06548075284114ff89178d5ffa50c03ad7 | 8a3636ff72456a6ae156f23ea79d871fa3721754 | refs/heads/master | 2021-06-21T09:31:44.923842 | 2017-07-27T16:29:20 | 2017-07-27T16:29:20 | 83,483,622 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 110 | h | #pragma once
class IHeatDefaultRegistryProvider {
public:
virtual void registerHeatRecipeDefaults() = 0;
};
| [
"trinitydevelopers4christ@gmail.com"
] | trinitydevelopers4christ@gmail.com |
8446bd163f505d02beecbed179610b7a25bb8d03 | 07462e8cc8e1bcdcc6a8bac76a7e8716d83d79d2 | /leetcode-Cpp/387.First Unique Character in a String.cpp | e548c2ced356de1eb13a84bc8525bc9afd6ed909 | [
"Apache-2.0"
] | permissive | Bigwode/3-leetcode-everyday | 0bc97133e06b2f89c2ef7e5c9596c18b49eab083 | 9380fffcfcb69c618cb771c2142302056c42782d | refs/heads/master | 2020-04-06T21:08:54.565561 | 2019-09-10T01:35:22 | 2019-09-10T01:35:22 | 157,794,100 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 757 | cpp | /*Method 1 需要遍历两遍*/
class Solution {
public:
int firstUniqChar(string s)
{
unordered_map<char, int>m;
for(char i: s)
{
if (m.count(i)) m[i]++;
else m[i]=1;
}
for(int j=0; j<s.size();j++)
{
if (m[s[j]] == 1) return j;
}
return -1;
}
};
/*Method 1 放到256个vector中快一点*/
class Solution {
public:
int firstUniqChar(string s)
{
vector<int> num_occurrences(256, 0);
for (char &c : s) {
++num_occurrences[c];
}
for (int i = 0; i < s.size(); ++i) {
if (num_occurrences[s[i]] == 1) {
return i;
}
}
return -1;
}
};
| [
"1165902905@qq.com"
] | 1165902905@qq.com |
e0fc701a37da7ca93f7dde75832613cdbc2d4729 | 85aed0bcac5d6aea781dff64029c2d23fcba984b | /netserverLib/s_COdbcGameInven.cpp | 17f469996205d55b35d1644bac89ce4ec5d3810e | [] | no_license | youdontknowme17/ura | 3c76bf05eccd38b454b389841f1db49b59217e46 | e31bc9fd9c2312175d250dc4dc1f9c656c7f2004 | refs/heads/master | 2020-03-28T15:49:00.379682 | 2018-09-15T09:57:49 | 2018-09-15T09:57:49 | 148,628,762 | 0 | 2 | null | null | null | null | UHC | C++ | false | false | 16,234 | cpp | #include "stdafx.h"
#include "s_COdbcManager.h"
#include "s_CDbAction.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
///////////////////////////////////////////////////////////////////////////
// 해당 락커 만료시간을 정한다.
// 1 번 5 번 락커는 정할 수 없음.
// 2, 3, 4 번 락커만 만료시간을 정할 수 있다.
// 입력
// nChaNum : 캐릭터번호
// nStorageNum : 스토리지 번호
// tTime : 만료시간
// 출력
// -1 : DB_ERROR
// 0 : DB_OK
int COdbcManager::SetChaStorageDate(int nUserNum, int nStorageNum, __time64_t tTime)
{
if (nStorageNum < 1 || nStorageNum > 3)
{
return DB_ERROR;
}
CTime cTemp(tTime);
CString strTime = cTemp.Format("%Y-%m-%d %H:%M:%S");
TCHAR szTemp[128] = {0};
//std::strstream strTemp;
//strTemp << "Update UserInven Set ";
switch (nStorageNum)
{
case 1:
_snprintf( szTemp, 128, "Update UserInven Set ChaStorage2='%s' WHERE UserNum=%d", strTime.GetString(), nUserNum );
//strTemp << "ChaStorage2='" << strTime.GetString() << "'";
break;
case 2:
_snprintf( szTemp, 128, "Update UserInven Set ChaStorage3='%s' WHERE UserNum=%d", strTime.GetString(), nUserNum );
//strTemp << "ChaStorage3='" << strTime.GetString() << "'";
break;
case 3:
_snprintf( szTemp, 128, "Update UserInven Set ChaStorage4='%s' WHERE UserNum=%d", strTime.GetString(), nUserNum );
//strTemp << "ChaStorage4='" << strTime.GetString() << "'";
break;
default:
return DB_ERROR;
break;
}
//strTemp << " WHERE UserNum=" << nUserNum;
//strTemp << std::ends;
int nReturn = m_pGameDB->ExecuteSQL(szTemp);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return nReturn;
}
///////////////////////////////////////////////////////////////////////////
// 해당 캐릭터의 인벤토리 추가 줄수를 세팅한다.
// 입력
// nChaNum : 캐릭터번호
// wInvenLine : 추가줄수
// 주의
// 최초 0 에서 한줄 추가시 1 을 입력
// 현재 한줄 상태에서 또 한줄 추가시 2 를 입력 (최종 줄수를 입력한다)
// 현재 두줄 상태에서 한줄 추가시 3 을 입력
// 최대 3까지만 입력가능.
int COdbcManager::SetChaInvenNum(int nChaNum, WORD wInvenLine)
{
if (wInvenLine < 1 || wInvenLine > 50 || nChaNum <= 0)
{
return DB_ERROR;
}
//std::strstream strTemp;
//strTemp << "Update ChaInfo Set ChaInvenLine=";
//strTemp << wInvenLine;
//strTemp << " WHERE ChaNum=" << nChaNum;
//strTemp << std::ends;
TCHAR szTemp[128] = {0};
_snprintf( szTemp, 128, "Update ChaInfo Set ChaInvenLine=%u WHERE ChaNum=%d", wInvenLine, nChaNum );
int nReturn = m_pGameDB->ExecuteSQL(szTemp);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return nReturn;
}
///////////////////////////////////////////////////////////////////////////
// 유저 인벤토리를 읽는다
int COdbcManager::ReadUserInven(SCHARDATA2* pChaData2)
{
bool bInven = CheckInven(CCfg::GetInstance()->GetServerGroup(), pChaData2->GetUserID());
if (!bInven)
{
MakeUserInven(CCfg::GetInstance()->GetServerGroup(), pChaData2->GetUserID());
}
// 유저인벤토리, money
ODBC_STMT* pConn = m_pGameDB->GetConnection();
if (!pConn) return DB_ERROR;
SQLRETURN sReturn = 0;
int nUserNum = 0;
//std::strstream strTemp;
//strTemp << "SELECT UserMoney, ChaStorage2, ChaStorage3, ChaStorage4 FROM UserInven WHERE UserNum=" << pChaData2->m_dwUserID; // << " AND ";
//// strTemp << "SGNum=" << CCfg::GetInstance()->GetServerGroup() ;
//strTemp << std::ends;
TCHAR szTemp[128] = {0};
_snprintf( szTemp, 128, "SELECT UserMoney, ChaStorage2, ChaStorage3, ChaStorage4 FROM UserInven WHERE UserNum=%u", pChaData2->GetUserID() );
sReturn = ::SQLExecDirect(pConn->hStmt,
(SQLCHAR*)szTemp,
SQL_NTS);
if ((sReturn != SQL_SUCCESS) && (sReturn != SQL_SUCCESS_WITH_INFO))
{
Print(szTemp);
Print(GetErrorString(pConn->hStmt));
m_pGameDB->FreeConnection(pConn);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return DB_ERROR;
}
LONGLONG llUserMoney = 0;
SQLINTEGER cbUserMoney = SQL_NTS;
TIMESTAMP_STRUCT sStorageDate2; SQLINTEGER cbStorageDate2 = SQL_NTS;
TIMESTAMP_STRUCT sStorageDate3; SQLINTEGER cbStorageDate3 = SQL_NTS;
TIMESTAMP_STRUCT sStorageDate4; SQLINTEGER cbStorageDate4 = SQL_NTS;
while(true)
{
sReturn = ::SQLFetch(pConn->hStmt);
if (sReturn == SQL_ERROR || sReturn == SQL_SUCCESS_WITH_INFO)
{
Print(szTemp);
Print(GetErrorString(pConn->hStmt));
m_pGameDB->FreeConnection(pConn);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return DB_ERROR;
}
if (sReturn == SQL_SUCCESS || sReturn == SQL_SUCCESS_WITH_INFO)
{
::SQLGetData(pConn->hStmt, 1, SQL_C_SBIGINT, &llUserMoney, 0, &cbUserMoney);
::SQLGetData(pConn->hStmt, 2, SQL_C_TYPE_TIMESTAMP, &sStorageDate2, 0, &cbStorageDate2);
::SQLGetData(pConn->hStmt, 3, SQL_C_TYPE_TIMESTAMP, &sStorageDate3, 0, &cbStorageDate3);
::SQLGetData(pConn->hStmt, 4, SQL_C_TYPE_TIMESTAMP, &sStorageDate4, 0, &cbStorageDate4);
pChaData2->m_lnStorageMoney = llUserMoney;
// 인벤토리 사용만료기간
// 1970-02-01 : Default
// 태국에서 TimeZone 세팅이 틀려서 오류가 발생
// 이 코드를 추가로 삽입한다.
if (sStorageDate2.year <= 1970 || sStorageDate2.year >= 2999)
{
sStorageDate2.year = 1970;
sStorageDate2.month = 2;
sStorageDate2.day = 1;
sStorageDate2.hour = 1;
sStorageDate2.minute = 1;
sStorageDate2.second = 1;
}
CTime cTemp2(sStorageDate2.year, sStorageDate2.month, sStorageDate2.day,
sStorageDate2.hour, sStorageDate2.minute, sStorageDate2.second);
pChaData2->m_tSTORAGE[0] = cTemp2.GetTime();
// 1970-02-01 : Default
// 태국에서 TimeZone 세팅이 틀려서 오류가 발생
// 이 코드를 추가로 삽입한다.
if (sStorageDate3.year <= 1970 || sStorageDate3.year >= 2999)
{
sStorageDate3.year = 1970;
sStorageDate3.month = 2;
sStorageDate3.day = 1;
sStorageDate3.hour = 1;
sStorageDate3.minute = 1;
sStorageDate3.second = 1;
}
CTime cTemp3(sStorageDate3.year, sStorageDate3.month, sStorageDate3.day,
sStorageDate3.hour, sStorageDate3.minute, sStorageDate3.second);
pChaData2->m_tSTORAGE[1] = cTemp3.GetTime();
// 1970-02-01 : Default
// 태국에서 TimeZone 세팅이 틀려서 오류가 발생
// 이 코드를 추가로 삽입한다.
if (sStorageDate4.year <= 1970 || sStorageDate4.year >= 2999)
{
sStorageDate4.year = 1970;
sStorageDate4.month = 2;
sStorageDate4.day = 1;
sStorageDate4.hour = 1;
sStorageDate4.minute = 1;
sStorageDate4.second = 1;
}
CTime cTemp4(sStorageDate4.year, sStorageDate4.month, sStorageDate4.day,
sStorageDate4.hour, sStorageDate4.minute, sStorageDate4.second);
pChaData2->m_tSTORAGE[2] = cTemp4.GetTime();
}
else
{
break;
}
Sleep( 0 );
}
m_pGameDB->FreeConnection(pConn);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
// image
CByteStream ByteStream;
sReturn = ReadUserInven(CCfg::GetInstance()->GetServerGroup(), pChaData2->GetUserID(), ByteStream);
if (sReturn == DB_ERROR)
return DB_ERROR;
pChaData2->SETSTORAGE_BYBUF(ByteStream);
return DB_OK;
}
///////////////////////////////////////////////////////////////////////////
// 사용자 인벤토리에서 데이타를 읽어온다.
int COdbcManager::ReadUserInven(int SGNum, DWORD dwUserNum, CByteStream &ByteStream)
{
SQLRETURN sReturn = 0;
ODBC_STMT* pConn = m_pGameDB->GetConnection();
if (!pConn) return DB_ERROR;
ByteStream.ClearBuffer();
//std::strstream strTemp;
//strTemp << "SELECT UserInven.UserInven FROM UserInven where (UserNum=" << dwUserNum << ")";
//strTemp << std::ends;
TCHAR szTemp[128] = {0};
_snprintf( szTemp, 128, "SELECT UserInven.UserInven FROM UserInven where (UserNum=%u)", dwUserNum );
// Create a result
sReturn = ::SQLExecDirect(pConn->hStmt, (SQLCHAR*)szTemp, SQL_NTS);
if (sReturn != SQL_SUCCESS && sReturn != SQL_SUCCESS_WITH_INFO)
{
Print(szTemp);
Print(GetErrorString(pConn->hStmt));
m_pGameDB->FreeConnection(pConn);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return DB_ERROR;
}
// Retrieve and display each row of data.
BYTE pBuffer[DB_IMAGE_BUF_SIZE] = {0};
SQLINTEGER lSize=0, lTotalSize=0;
while ((sReturn = ::SQLFetch(pConn->hStmt)) != SQL_NO_DATA)
{
while (1)
{
::ZeroMemory(pBuffer, DB_IMAGE_BUF_SIZE);
lSize = 0;
sReturn = ::SQLGetData(pConn->hStmt, 1, SQL_C_BINARY, pBuffer, DB_IMAGE_BUF_SIZE, &lSize);
if (lSize > 0)
{
if (lSize > DB_IMAGE_BUF_SIZE) lSize = DB_IMAGE_BUF_SIZE;
lTotalSize += lSize;
ByteStream.WriteBuffer((LPBYTE) pBuffer, lSize);
}
if (sReturn == SQL_NO_DATA || lSize == 0)
break;
Sleep( 0 );
}
if ( lTotalSize < DB_IMAGE_MIN_SIZE )
ByteStream.ClearBuffer ();
Sleep( 0 );
}
m_pGameDB->FreeConnection(pConn);
return lTotalSize;
}
///////////////////////////////////////////////////////////////////////////
// 유저인벤토리가 있는지 체크한다.
bool COdbcManager::CheckInven(int SGNum, DWORD dwUserNum)
{
//std::strstream strTemp;
//strTemp << "{call GetInvenCount(";
//strTemp << dwUserNum;
//strTemp << ",?)}";
//strTemp << std::ends;
TCHAR szTemp[128] = {0};
_snprintf( szTemp, 128, "{call GetInvenCount(%u,?)}", dwUserNum );
if (m_pGameDB->ExecuteSpInt(szTemp) > 0)
{
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return true;
}
else
{
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return false;
}
}
int COdbcManager::MakeUserInven(int SGNum, DWORD dwUserNum)
{
//std::strstream strTemp;
//strTemp << "{call MakeUserInven(";
//strTemp << SGNum << ",";
//strTemp << dwUserNum << ",";
//strTemp << "?)}";
//strTemp << std::ends;
TCHAR szTemp[128] = {0};
_snprintf( szTemp, 128, "{call MakeUserInven(%d,%u,?)}", SGNum, dwUserNum );
int nReturn = m_pGameDB->ExecuteSpInt(szTemp);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return nReturn;
}
///////////////////////////////////////////////////////////////////////////
// 사용자 인벤토리에 데이타를 저장한다.
int COdbcManager::WriteUserInven(
int SGNum,
LONGLONG llMoney /* LONGLONG __int64 */,
DWORD dwUserNum,
BYTE* pData,
int nSize)
{
/*
// User Inventory
// 1. Check User Inven
// 2. If exist skip
// 3. not exist, write iventory image
bool bInven = CheckInven(SGNum, dwUserNum);
if (!bInven)
{
MakeUserInven(SGNum, dwUserNum);
}
*/
// Update Money
//std::strstream strMoney;
//strMoney << "{call UpdateUserMoney(";
//strMoney << dwUserNum;
//strMoney << ",";
//strMoney << llMoney;
//strMoney << ")}";
//strMoney << std::ends;
TCHAR szTemp[128] = {0};
_snprintf( szTemp, 128, "{call UpdateUserMoney(%u,%I64d)}", dwUserNum, llMoney );
m_pGameDB->ExecuteSp( szTemp );
//strMoney.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
// Update Image
ODBC_STMT* pConn = m_pGameDB->GetConnection();
if (!pConn) return DB_ERROR;
//std::strstream strTemp;
//strTemp << "UPDATE UserInven SET UserInven = ? WHERE (UserNum=" << dwUserNum << ") ";
//strTemp << std::ends;
_snprintf( szTemp, 128, "UPDATE UserInven SET UserInven = ? WHERE (UserNum=%u)", dwUserNum );
SQLRETURN sReturn = 0; // SQL return value (short)
// Prepare parameter
sReturn = ::SQLPrepare(pConn->hStmt, (SQLCHAR*)szTemp, SQL_NTS);
if (sReturn != SQL_SUCCESS && sReturn != SQL_SUCCESS_WITH_INFO)
{
Print(szTemp);
Print(GetErrorString(pConn->hStmt));
m_pGameDB->FreeConnection(pConn);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return DB_ERROR;
}
// Bind parameter
SQLINTEGER cbBinaryParam = SQL_LEN_DATA_AT_EXEC(0);
sReturn = ::SQLBindParameter(pConn->hStmt,
1,
SQL_PARAM_INPUT,
SQL_C_BINARY,
SQL_LONGVARBINARY,
nSize,
0,
(SQLPOINTER) 2,
0,
&cbBinaryParam);
if (sReturn != SQL_SUCCESS && sReturn != SQL_SUCCESS_WITH_INFO)
{
Print(szTemp);
Print(GetErrorString(pConn->hStmt));
m_pGameDB->FreeConnection(pConn);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return DB_ERROR;
}
// Execute SQL
sReturn = ::SQLExecute(pConn->hStmt);
if (sReturn == SQL_ERROR || sReturn == SQL_SUCCESS_WITH_INFO)
{
Print(szTemp);
Print(GetErrorString(pConn->hStmt));
m_pGameDB->FreeConnection(pConn);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return DB_ERROR;
}
SQLPOINTER pToken = NULL;
while (sReturn == SQL_NEED_DATA)
{
sReturn = ::SQLParamData(pConn->hStmt, &pToken);
if (sReturn == SQL_NEED_DATA)
{
::SQLPutData(pConn->hStmt, pData, (SQLINTEGER) nSize);
}
Sleep( 0 );
}
m_pGameDB->FreeConnection(pConn);
//strTemp.freeze( false ); // Note : std::strstream의 freeze. 안 하면 Leak 발생.
return DB_OK;
}
int COdbcManager::UpdateUserMoneyAdd( DWORD dwUserID, LONGLONG lnUserMoney )
{
if ( lnUserMoney <= 0 ) return DB_ERROR;
TCHAR szTemp[128] = {0};
_snprintf( szTemp, 128, "{call sp_UpdateUserMoneyAdd(%u,%I64d,?)}", dwUserID, lnUserMoney );
int nReturn = m_pGameDB->ExecuteSpInt(szTemp);
return nReturn;
}
int COdbcManager::UpdateUserLastInfoAdd( DWORD dwUserID, LONGLONG lnUserMoney )
{
if ( lnUserMoney <= 0 ) return DB_ERROR;
SQLRETURN sReturn = 0;
ODBC_STMT* pConn = m_pGameDB->GetConnection();
if (!pConn) return DB_ERROR;
TCHAR szTemp[128] = {0};
_snprintf( szTemp, 128, "SELECT UserMoney FROM UserLastInfo WHERE UserNum=%u", dwUserID );
sReturn = ::SQLExecDirect(pConn->hStmt,
(SQLCHAR*)szTemp,
SQL_NTS);
if ((sReturn != SQL_SUCCESS) && (sReturn != SQL_SUCCESS_WITH_INFO))
{
Print(szTemp);
Print(GetErrorString(pConn->hStmt));
m_pGameDB->FreeConnection(pConn);
return DB_ERROR;
}
// UserLastInfo Table의 금액 컬럼의 암호화를 위해서 ChaMoney 컬럼의 DataType을 int -> varchar(100)으로 수정한다.
// LONGLONG llUserSaveMoney = 0;
// SQLINTEGER cbUserSaveMoney = SQL_NTS;
SQLCHAR szTempStorageMoney[CHAR_TEMPMONEY] = {0};
SQLINTEGER cbTempStorageMoney = SQL_NTS;
LONGLONG lnTempMoney = 0;
while (true)
{
sReturn = ::SQLFetch(pConn->hStmt);
if (sReturn == SQL_SUCCESS || sReturn == SQL_SUCCESS_WITH_INFO)
{
::SQLGetData(pConn->hStmt, 1, SQL_C_CHAR, szTempStorageMoney, CHAR_TEMPMONEY, &cbTempStorageMoney);
if (cbTempStorageMoney != 0 && cbTempStorageMoney != -1) // TempStorageMoney 값 복사
{
lnTempMoney = 0;
char szTempStorageMoney1[CHAR_TEMPMONEY], szTemp[2];
::StringCchCopy(szTempStorageMoney1, CHAR_TEMPMONEY, (const char*) szTempStorageMoney);
size_t i;
for( i = 0; i < strlen(szTempStorageMoney1); i++ )
{
szTempStorageMoney1[i] -= 20;
sprintf( szTemp, "%c", szTempStorageMoney1[i] );
lnTempMoney = ( lnTempMoney * 10 ) + atoi(szTemp);
}
lnTempMoney = lnTempMoney >> 0x04;
}
}
else
{
break;
}
Sleep( 0 );
}
char szTempMoney[CHAR_TEMPMONEY];
lnTempMoney += lnUserMoney;
lnTempMoney <<= 0x04;
sprintf( szTempMoney, "%I64d", lnTempMoney );
for( int i = 0; i < strlen(szTempMoney); i++ )
{
szTempMoney[i] += 20;
}
TCHAR szTemp2[256] = {0};
_snprintf( szTemp2, 512, "Exec sp_InsertUserLastInfo %u, '%s'",
dwUserID,szTempMoney);
if (m_pGameDB->ExecuteSQL(szTemp2) != DB_OK)
{
return DB_ERROR;
}
m_pGameDB->FreeConnection(pConn);
return DB_OK;
}
| [
"markcalimosa@gmail.com"
] | markcalimosa@gmail.com |
494a188e8c9c1e381498ad4d4a2ec875220e8657 | 81beaace24b74eb039ca6d1011850c06b3636041 | /Include/Poco/ClassLibrary.h | 4265eb02f26031c1894a8d4fd28183d9ccbb6e43 | [] | no_license | passionkk/Business | 7179c6f34ff3f1075c017b7fb11ce68e459aee73 | 7198c99fe74260dcced7060ed26301833192ceca | refs/heads/master | 2021-05-11T06:54:45.486522 | 2018-03-06T01:48:33 | 2018-03-06T01:48:33 | 118,002,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,450 | h | //
// ClassLibrary.h
//
// $Id: //poco/1.4/Foundation/include/Poco/ClassLibrary.h#1 $
//
// Library: Foundation
// Package: SharedLibrary
// Module: ClassLoader
//
// Definitions for class libraries.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Foundation_ClassLibrary_INCLUDED
#define Foundation_ClassLibrary_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Manifest.h"
#include <typeinfo>
#if defined(_WIN32)
#define POCO_LIBRARY_API __declspec(dllexport)
#else
#define POCO_LIBRARY_API
#endif
//
// the entry points for every class library
//
extern "C"
{
bool POCO_LIBRARY_API pocoBuildManifest(Poco::ManifestBase* pManifest);
void POCO_LIBRARY_API pocoInitializeLibrary();
void POCO_LIBRARY_API pocoUninitializeLibrary();
}
//
// additional support for named manifests
//
#define POCO_DECLARE_NAMED_MANIFEST(name) \
extern "C" \
{ \
bool POCO_LIBRARY_API POCO_JOIN(pocoBuildManifest, name)(Poco::ManifestBase* pManifest); \
}
//
// Macros to automatically implement pocoBuildManifest
//
// usage:
//
// POCO_BEGIN_MANIFEST(MyBaseClass)
// POCO_EXPORT_CLASS(MyFirstClass)
// POCO_EXPORT_CLASS(MySecondClass)
// ...
// POCO_END_MANIFEST
//
#define POCO_BEGIN_MANIFEST_IMPL(fnName, base) \
bool fnName(Poco::ManifestBase* pManifest_) \
{ \
typedef base _Base; \
typedef Poco::Manifest<_Base> _Manifest; \
std::string requiredType(typeid(_Manifest).name()); \
std::string actualType(pManifest_->className()); \
if (requiredType == actualType) \
{ \
Poco::Manifest<_Base>* pManifest = static_cast<_Manifest*>(pManifest_);
#define POCO_BEGIN_MANIFEST(base) \
POCO_BEGIN_MANIFEST_IMPL(pocoBuildManifest, base)
#define POCO_BEGIN_NAMED_MANIFEST(name, base) \
POCO_DECLARE_NAMED_MANIFEST(name) \
POCO_BEGIN_MANIFEST_IMPL(POCO_JOIN(pocoBuildManifest, name), base)
#define POCO_END_MANIFEST \
return true; \
} \
else return false; \
}
#define POCO_EXPORT_CLASS(cls) \
pManifest->insert(new Poco::MetaObject<cls, _Base>(#cls));
#define POCO_EXPORT_SINGLETON(cls) \
pManifest->insert(new Poco::MetaSingleton<cls, _Base>(#cls));
#endif // Foundation_ClassLibrary_INCLUDED
| [
"767313547@qq.com"
] | 767313547@qq.com |
da2f5cede241688cdd6d8555860c493f5f7e7fc3 | e689db2b5028508e317cd6a2fb205b5b02f59432 | /priority_queue/priority_queue.h | b7c0b2f11dbf3f48f6324649b08c78dfad3e8b79 | [] | no_license | VishaalK/DataStructures | e594bc7de1048285b2fb74aa195c6d581b7d28c3 | 3fd03886151116adfa6d42005184a9435601be74 | refs/heads/master | 2021-01-21T17:46:23.741452 | 2014-05-19T04:32:44 | 2014-05-19T04:32:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 362 | h | #ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H
class priority_queue {
public:
virtual ~priority_queue() {};
virtual void push(int) = 0;
virtual int top() = 0;
virtual void pop() = 0;
virtual int size() = 0;
virtual bool isEmpty() = 0;
virtual void clear() = 0;
// virtual void print() {};
};
#endif
| [
"vishaalk@umich.edu"
] | vishaalk@umich.edu |
0cac61dd750624a0caf2a3cce502917a2262861c | e8f52b45c57c6dd5af5df46e0c6b82fac91abab9 | /exe/MakeBetaIsoMat.cpp | b2eb7a962c9e323b010a9140e87d4b02b6c366f9 | [] | no_license | mb0316/EURoot | 5ea615572d6f473ee997ecce7a88b7e3020e4c6e | ff6fd5ded61bbd49d89be2aedbe73d1e41ec2661 | refs/heads/master | 2018-10-24T18:46:47.590108 | 2018-10-17T08:04:04 | 2018-10-17T08:04:04 | 103,235,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,503 | cpp | #include "TTree.h"
#include "EUTreeDecay.h"
#include "EUAnaMat.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "TFile.h"
#include "TH1D.h"
#include "TH2D.h"
#include <fstream>
#include "TApplication.h"
#include "TROOT.h"
#include "TCanvas.h"
using namespace std;
int main (int argc, char* argv[])
{
// TApplication theApp("test",0,0);
if (argc < 7 || argc > 8)
{
cout << "Please type 'MakeMAT #Z #Mass #statistics # mode #tstart #tend'." << endl;
cout << "Z : Proton number" << endl;
cout << "Mass : Mass number" << endl;
cout << "statistics : 0 for good statistics, 1 for bad statistics" << endl;
cout << "mode : 0 for 1 MeV, 1 for 2 MeV, 2 for 4 MeV, 3 for 8 MeV" << endl;
cout << "tstart : set first time cut for g-g matrix" << endl;
cout << "tend : set end time cut for g-g matrix" << endl;
return 0;
}
Int_t zpro = atoi(argv[1]);
Int_t mass = atoi(argv[2]);
Int_t stat = atoi(argv[3]);
Int_t mode = atoi(argv[4]);
Int_t tstart = atoi(argv[5]);
Int_t tend = atoi(argv[6]);
EUAnaMat* mat = new EUAnaMat(Form("../results/PID/Betadecay_%d_%d.root", zpro, mass), 0);
mat->MakeBIGG(stat, mode, tstart, tend);
mat->MakeBITG(stat, mode);
/*
TCanvas* cvs = new TCanvas("cvs", "", 1500, 1000);
cvs->Divide(2,2);
cvs->cd(1);
mat->gg_a->Draw("colz");
cvs->cd(2);
mat->gg_g->Draw("colz");
cvs->cd(3);
mat->tg_a->Draw("colz");
cvs->cd(4);
mat->tg_g->Draw("colz");
TCanvas* cvs1 = new TCanvas("cvs1", "", 1000, 800);
cvs1->Divide(1,2);
cvs1->cd(1);
mat->gcT_E->Draw("colz");
cvs1->cd(2);
mat->addT_E->Draw("colz");
*/
Int_t ch;
if (mode == 0) ch = 1;
if (mode == 1) ch = 2;
if (mode == 2) ch = 4;
if (mode == 3) ch = 8;
// cvs->SaveAs(Form("../results/MAT/Beta%d_%d_%dk.pdf", zpro, mass, ch));
// cvs1->SaveAs(Form("../results/MAT/Beta%d_%d_%dk_EvsT.pdf", zpro, mass, ch));
FILE* out_gga;
FILE* out_ggg;
FILE* out_tga;
FILE* out_tgg;
out_gga = fopen(Form("../results/MAT/BetaIso%d_%d_%dk_add_gg.mat", zpro, mass, ch), "wb");
out_ggg = fopen(Form("../results/MAT/BetaIso%d_%d_%dk_gc_gg.mat", zpro, mass, ch), "wb");
out_tga = fopen(Form("../results/MAT/BetaIso%d_%d_%dk_add_tg.mat", zpro, mass, ch), "wb");
out_tgg = fopen(Form("../results/MAT/BetaIso%d_%d_%dk_gc_tg.mat", zpro, mass, ch), "wb");
Short_t temp1[4096]={0};
Short_t temp2[4096]={0};
Short_t temp3[4096]={0};
Short_t temp4[4096]={0};
for (Int_t i = 0; i < 4096; i++)
{
for (Int_t j = 0; j < 4096; j++)
{
temp1[j] = mat->gg_a -> GetBinContent(i+1, j+1);
temp2[j] = mat->gg_g -> GetBinContent(i+1, j+1);
temp3[j] = mat->tg_a -> GetBinContent(i+1, j+1);
temp4[j] = mat->tg_g -> GetBinContent(i+1, j+1);
}
fwrite(temp1, sizeof(short), 4096, out_gga);
fwrite(temp2, sizeof(short), 4096, out_ggg);
fwrite(temp3, sizeof(short), 4096, out_tga);
fwrite(temp4, sizeof(short), 4096, out_tgg);
}
TFile* out1 = new TFile(Form("../results/MAT/BetaIso%d_%d_add_gg.root", zpro, mass), "RECREATE");
TFile* out2 = new TFile(Form("../results/MAT/BetaIso%d_%d_gc_gg.root", zpro, mass), "RECREATE");
TFile* out3 = new TFile(Form("../results/MAT/BetaIso%d_%d_add_tg.root", zpro, mass), "RECREATE");
TFile* out4 = new TFile(Form("../results/MAT/BetaIso%d_%d_gc_tg.root", zpro, mass), "RECREATE");
out1->cd();
mat->gg_a -> Write();
out1->Close();
out2->cd();
mat->gg_g -> Write();
out2->Close();
out3->cd();
mat->tg_a -> Write();
out3->Close();
out4->cd();
mat->tg_g -> Write();
out4->Close();
// theApp.Run();
return 0;
}
| [
"mb0316@nuclear.korea.ac.kr"
] | mb0316@nuclear.korea.ac.kr |
0602f334bbbec954c161ce9780eaf4b2c812c7a6 | 941136e02440c86f85cfcf96274cc79eb0c898c3 | /Engine/Source/Physics/Cloth.cpp | 09e617f2d9b566c4d8f02d783939d58af39cdebc | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive"
] | permissive | astrorog/EsenthelEngine | 5d5b5923e5540fb7019d924412ebee12d7a9c8c0 | fda4e2458509abfde9e8205edf7db5a63aff9e72 | refs/heads/master | 2023-02-27T03:13:12.165592 | 2020-12-14T13:15:37 | 2020-12-14T13:15:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,572 | cpp | /******************************************************************************/
#include "stdafx.h"
namespace EE{
#include "PhysX Stream.h"
/******************************************************************************/
#define CC4_CLMS CC4('C','L','M','S')
/******************************************************************************/
Cache<ClothMesh> ClothMeshes("Cloth Mesh"); // ClothMesh Cache
/******************************************************************************/
// CLOTH MESH
/******************************************************************************/
#if PHYSX
static PxClothFabric* CreateClothMesh(MeshBase &mesh, Flt scale) // assumes that 'mesh' doesn't contain quads
{
if(Physx.physics && mesh.vtxs() && mesh.tris())
{
PxClothMeshDesc desc;
desc.points .data =mesh.vtx.pos();
desc.points .count =mesh.vtxs();
desc.points .stride=SIZE(Vec);
desc.triangles.data =mesh.tri.ind();
desc.triangles.count =mesh.tris();
desc.triangles.stride=SIZE(VecI);
// scale
Vec *pos_scaled=null;
if(!Equal(scale, 1))
{
desc.points.data=Alloc(pos_scaled, mesh.vtxs()); REPA(mesh.vtx)pos_scaled[i]=mesh.vtx.pos(i)*scale;
}
// cook cloth mesh
OutputStream buf;
PxClothFabricCooker cook(desc, Physx.vec(Vec(0,-1,0)), true); cook.save(buf, false);
Free(pos_scaled);
if(!buf.data || !buf.pos)Exit("ClothMesh.create");
WriteLock lock(Physics._rws);
InputStream input(buf.data, buf.pos);
return Physx.physics->createClothFabric(input);
}
return null;
}
PxClothFabric* ClothMesh::scaledMesh(Flt scale)
{
// find existing
REPA(_scales)if(Equal(_scales[i].scale, scale))return _scales[i].mesh;
// create new one
if(PxClothFabric *mesh=CreateClothMesh(_phys, scale))
{
Scale &s=_scales.New();
s.scale=scale;
return s.mesh =mesh ;
}
return null;
}
#endif
/******************************************************************************/
ClothMesh& ClothMesh::del()
{
#if PHYSX
if(_scales.elms())
{
SafeWriteLock lock(Physics._rws);
if(Physx.physics)REPA(_scales)_scales[i].mesh->release();
}
#endif
_scales .del();
_phys .del();
_skin .del();
_ind_buf .del();
_bone_map.del();
_material=null;
_skeleton=null;
return T;
}
ClothMesh::ClothMesh()
{
REPAO(_skin_shader)=null;
REPAO(_phys_shader)=null;
_skin_frst=null;
_phys_frst=null;
_skeleton =null;
}
/******************************************************************************/
ClothMesh& ClothMesh::create(C MeshBase &mesh, C MaterialPtr &material, Skeleton *skeleton)
{
del();
if(!mesh.vtx.flag() || !mesh.vtx.matrix() || !mesh.vtx.blend()) // if we're putting the whole thing to phys
{
_phys.create(mesh, VTX_TEX0|VTX_FLAG).quadToTri();
}else
{
/* Rules:
Vtx:
All vtx with VTX_FLAG_CLOTH go to Cloth
Neighbor vtx of VTX_FLAG_CLOTH have unified skin and go to Cloth and MeshRender
Rest goes only to MeshRender
Tri:
At least one vtx with VTX_FLAG_CLOTH -> Cloth
No VTX_FLAG_CLOTH -> MeshRender
*/
MeshBase temp;
temp.create(mesh, VTX_NRM|VTX_TEX0|VTX_SKIN|VTX_FLAG).quadToTri();
// unify skin
Memt<Bool> cloth_neighbor; cloth_neighbor.setNumZero(temp.vtxs()); // cloth or neighbor
Memt<Bool> tri_as_cloth; tri_as_cloth.setNum(temp.tris());
Int tris_cloth=0,
tris_skin =0;
REPA(temp.tri)
{
Int *p=temp.tri.ind(i).c, p0=p[0], p1=p[1], p2=p[2];
if(tri_as_cloth[i]=FlagTest(temp.vtx.flag(p0)|temp.vtx.flag(p1)|temp.vtx.flag(p2), VTX_FLAG_CLOTH)) // if at least one vtx is meant for phys cloth
{
// set all to cloth and neighbor
cloth_neighbor[p0]=true;
cloth_neighbor[p1]=true;
cloth_neighbor[p2]=true;
tris_cloth++;
}else
{
tris_skin++;
}
}
if(tris_cloth && tris_skin<=8)REPA(temp.tri) // if only 8 tris left in skinning version, then put them also to cloth (this will probably be faster instead of additional overhead for separate MeshRender drawing)
{
if(!tri_as_cloth[i]) // if not yet added to cloth
{
Int *p=temp.tri.ind(i).c, p0=p[0], p1=p[1], p2=p[2];
tri_as_cloth [ i]=true;
cloth_neighbor[p0]=true;
cloth_neighbor[p1]=true;
cloth_neighbor[p2]=true;
}
}
REPA(temp.vtx)if(cloth_neighbor[i]) // is neighbor or cloth
{
// unify skinning
VecB4 &blend=temp.vtx.blend (i),
&bone =temp.vtx.matrix(i);
Swap(bone.c[0], bone.c[blend.maxI()]); // put most important bone to first slot
blend.set(255, 0, 0, 0); // set max weight for first bone
}
// create mesh
temp.splitFaces(_phys, null, tri_as_cloth, null, VTX_TEX0|VTX_MATRIX|VTX_FLAG); // move selected triangles cloth/neighbors to cloth keeping flags and bone indexes
_skin.create (temp ); // create remaining skinned part as MeshRender
T.skeleton(skeleton);
}
T._material=material;
if(_ind_buf.create(_phys.tris()*3, _phys.vtxs()<=0x10000))if(Ptr dest=_ind_buf.lock(LOCK_WRITE))
{
if(_ind_buf.bit16())Copy32To16(dest, _phys.tri.ind(), _ind_buf._ind_num);
else Copy32To32(dest, _phys.tri.ind(), _ind_buf._ind_num);
_ind_buf.unlock();
}
setShader();
return T;
}
/******************************************************************************/
ClothMesh& ClothMesh::skeleton(Skeleton *skeleton)
{
T._skeleton=skeleton;
if(skeleton && skeleton->is() && !_bone_map.same(*skeleton)) // remap only if new skeleton exists (in case it failed to load, then it could be null or have no bones, or the parameter could just have been specifically set to null in order to clear the skeleton link) and if the existing bone map is different than of the new skeleton
{
if(_bone_map.is()) // remap vertexes only if the mesh already had a bone map (otherwise the vertex bone could be set, but the bone map doesn't exist yet, and in that case the vertex bone data could be lost if we've performed remapping)
{
Memt<Byte, 256> old_to_new;
_bone_map.setRemap(*skeleton, old_to_new);
boneRemap(old_to_new, false); // set false to not waste time on adjusting the '_bone_map' itself, because we're going to recreate it anyway below
}
// setup new mesh bone info
_bone_map.create(*skeleton);
}
return T;
}
/******************************************************************************/
//Bool boneRename(C Str8 &src, C Str8 &dest ); // rename 'src' bone to 'dest' bone, returns true if a bone was renamed
//Bool ClothMesh::boneRename(C Str8 &src, C Str8 &dest) {return _bone_map.rename(src, dest);}
void ClothMesh::boneRemap(C CMemPtr<Byte, 256> &old_to_new, Bool remap_names)
{
_phys.boneRemap(old_to_new);
_skin.boneRemap(old_to_new);
if(remap_names)_bone_map.remap(old_to_new);
}
void ClothMesh::setShader()
{
DefaultShaders(_material(), _skin.flag() , 0, false).set(_skin_shader, &_skin_frst, null);
DefaultShaders(_material(), VTX_POS|VTX_NRM|VTX_TEX0, 0, false).set(_phys_shader, &_phys_frst, null);
}
/******************************************************************************/
Bool ClothMesh::saveData(File &f, CChar *path)C
{
f.cmpUIntV(2); // version
f._putStr(_material.name(path));
if(_phys .saveData(f))
if(_skin .saveData(f))
if(_ind_buf .save (f))
if(_bone_map.saveOld (f))
{
f._putStr(Skeletons.name(skeleton(), path));
// physx cooked data isn't saved, because later physx versions can't read older cloth versions (at least that's how it was in the past)
return f.ok();
}
return false;
}
Bool ClothMesh::loadData(File &f, CChar *path)
{
del();
switch(f.decUIntV()) // version
{
case 2:
{
_material.require(f._getStr(), path);
if(_phys .loadData(f))
if(_skin .loadData(f))
if(_ind_buf .load (f))
if(_bone_map.loadOld (f))
{
skeleton(Skeletons(f._getStr(), path));
setShader();
if(f.ok())return true;
}
}break;
case 1:
{
_material.require(f._getStr(), path);
if(!_phys.loadData(f))goto error;
if(!_skin.loadData(f))goto error;
if( _ind_buf.create(_phys.tris()*3, _phys.vtxs()<=0x10000))if(Ptr dest=_ind_buf.lock(LOCK_WRITE))
{
if(_ind_buf.bit16())Copy32To16(dest, _phys.tri.ind(), _ind_buf._ind_num);
else Copy32To32(dest, _phys.tri.ind(), _ind_buf._ind_num);
_ind_buf.unlock();
}
if(!_bone_map.loadOld(f))goto error;
skeleton(Skeletons(f._getStr(), path));
setShader();
if(f.ok())return true;
}break;
case 0:
{
_material.require(f._getStr(), path);
if(!_phys.loadData(f))goto error;
if(!_skin.loadData(f))goto error;
if( _ind_buf.create(_phys.tris()*3, _phys.vtxs()<=0x10000))if(Ptr dest=_ind_buf.lock(LOCK_WRITE))
{
if(_ind_buf.bit16())Copy32To16(dest, _phys.tri.ind(), _ind_buf._ind_num);
else Copy32To32(dest, _phys.tri.ind(), _ind_buf._ind_num);
_ind_buf.unlock();
}
setShader();
if(f.ok())return true;
}break;
}
error:
del(); return false;
}
Bool ClothMesh::save(File &f, CChar *path)C
{
f.putUInt(CC4_CLMS);
return saveData(f, path);
}
Bool ClothMesh::load(File &f, CChar *path)
{
if(f.getUInt()==CC4_CLMS)return loadData(f, path);
del(); return false;
}
Bool ClothMesh::save(C Str &name)C
{
File f; if(f.writeTry(name)){if(save(f, _GetPath(name)) && f.flush())return true; f.del(); FDelFile(name);}
return false;
}
Bool ClothMesh::load(C Str &name)
{
File f; if(f.readTry(name))return load(f, _GetPath(name));
del(); return false;
}
/******************************************************************************/
// CLOTH
/******************************************************************************/
Cloth::Cloth() {_update_count=0; _scale=1; _cloth_mesh=null; _vtxs=null; _vtx=null; _cloth=null; _lock=null;}
Cloth& Cloth::del()
{
unlock();
#if PHYSX
if(_cloth)
{
SafeWriteLock lock(Physics._rws);
if(_cloth)
{
if(Physx.physics)_cloth->release();
_cloth=null;
}
}
#else
// TODO: Bullet
#endif
_vtx_buf.del();
_update_count=Physics._update_count-1; _scale=1; _cloth_mesh=null;
return T;
}
Bool Cloth::create(ClothMesh &cloth_mesh, C Matrix &matrix)
{
del();
#if PHYSX
if(Physx.physics && Physx.world)
{
Matrix m=matrix;
_scale=m.x.normalize();
m.y.normalize();
m.z.normalize();
if(PxClothFabric *cm=cloth_mesh.scaledMesh(_scale))
{
Memt<PxClothParticle> particles;
particles.setNum(cloth_mesh._phys.vtxs());
REPA(particles)
{
particles[i].pos =Physx.vec(cloth_mesh._phys.vtx.pos(i)*matrix);
particles[i].invWeight=1.0f/1;
}
WriteLock lock(Physics._rws);
if(_cloth=Physx.physics->createCloth(PxTransform(PxIdentity), *cm, particles.data(), PxClothFlags()))
if(_vtx_buf.createNum(SIZE(Vtx), cloth_mesh._phys.vtxs(), true))
{
T._cloth_mesh=&cloth_mesh;
_cloth->setSolverFrequency(Physics.precision());
Physx.world->addActor(*_cloth);
return true;
}
}
del();
}
#endif
return false;
}
/******************************************************************************/
#if PHYSX
C Cloth::Particle* Cloth::lockRead()
{
#if !APPLE // fails to compile
ASSERT(SIZE (*_lock->particles )==SIZE (Particle ));
ASSERT(OFFSET(PxClothParticle, pos )==OFFSET(Particle, pos ));
ASSERT(OFFSET(PxClothParticle, invWeight)==OFFSET(Particle, inverse_mass));
#endif
if(_cloth && !_lock)_lock=_cloth->lockParticleData(PxDataAccessFlag::eREADABLE);
return _lock ? (Particle*)_lock->particles : null;
}
Cloth& Cloth::unlock()
{
if(_lock)
{
if(Physx.world)_lock->unlock(); // in case we're unlocking after deleting physics
_lock=null;
}
return T;
}
Cloth& Cloth::set(C Particle *particle, Int particles)
{
if(_cloth && particle && particles>=_cloth->getNbParticles())_cloth->setParticles((C PxClothParticle*)particle, null);
return T;
}
Cloth& Cloth::setCollisionBalls(C CMemPtr<Ball> &balls)
{
if(_cloth)
{
PxClothCollisionSphere sphere[32]; Int elms=Min(Elms(sphere), balls.elms());
REP(elms)
{
sphere[i].radius= balls[i].r ;
sphere[i].pos =Physx.vec(balls[i].pos);
}
_cloth->setCollisionSpheres(sphere, elms);
}
return T;
}
Cloth& Cloth::setCollisionCapsules(C CMemPtr<VecI2> &capsules)
{
if(_cloth)
{
// remove all
REP(_cloth->getNbCollisionCapsules())_cloth->removeCollisionCapsule(i);
// add
Int elms=Min(capsules.elms(), 32);
FREP(elms)_cloth->addCollisionCapsule(capsules[i].x, capsules[i].y);
}
return T;
}
#else
C Cloth::Particle* Cloth:: lockRead() {return null;}
Cloth& Cloth::unlock () {return T;}
Cloth& Cloth::set (C Particle *particle, Int particles) {return T;}
Cloth& Cloth::setCollisionBalls (C CMemPtr<Ball > &balls ) {return T;}
Cloth& Cloth::setCollisionCapsules(C CMemPtr<VecI2> &capsules) {return T;}
#endif
/******************************************************************************/
// GET / SET
/******************************************************************************/
#if PHYSX
Int Cloth::vtxs ( )C {return _cloth_mesh ? _cloth_mesh->_phys.vtxs() : 0;}
Ptr Cloth::obj ( )C {return _cloth ? (Ptr)_cloth->getName() : null;}
Cloth& Cloth::obj (Ptr obj ) {if (_cloth) _cloth->setName((char*)obj); return T;}
Bool Cloth::sleep( )C {return _cloth ? _cloth->isSleeping() : false;}
Cloth& Cloth::sleep(Bool sleep) {if (_cloth)if(sleep)_cloth->putToSleep();else _cloth->wakeUp(); return T;}
Vec Cloth::wind ( )C {return _cloth ? Physx.vec(_cloth->getExternalAcceleration()) : 0;}
Cloth& Cloth::wind (C Vec &accel) {if (_cloth) _cloth->setExternalAcceleration(Physx.vec(accel)); return T;}
Box Cloth::box ( )C {return _cloth ? Physx.box(_cloth->getWorldBounds()) : Box(0);}
Bool Cloth::ccd ( )C {return _cloth ? FlagTest((UInt)_cloth->getClothFlags(), PxClothFlag::eSWEPT_CONTACT) : false;}
Cloth& Cloth::ccd (Bool on) {if (_cloth) _cloth->setClothFlag ( PxClothFlag::eSWEPT_CONTACT, on); return T;}
Bool Cloth::gpu ( )C {return _cloth ? FlagTest((UInt)_cloth->getClothFlags(), PxClothFlag::eGPU ) : false;}
Cloth& Cloth::gpu (Bool on) {if (_cloth) _cloth->setClothFlag ( PxClothFlag::eGPU , on); return T;}
#else
Int Cloth::vtxs ( )C {return 0 ;}
Ptr Cloth::obj ( )C {return null ;}
Cloth& Cloth::obj (Ptr obj ) {return T ;}
Bool Cloth::sleep( )C {return false;}
Cloth& Cloth::sleep(Bool sleep) {return T ;}
Vec Cloth::wind ( )C {return 0 ;}
Cloth& Cloth::wind (C Vec &accel) {return T ;}
Bool Cloth::ccd ( )C {return false;}
Cloth& Cloth::ccd (Bool on) {return T ;}
Bool Cloth::gpu ( )C {return false;}
Cloth& Cloth::gpu (Bool on) {return T ;}
Box Cloth::box ( )C {return 0 ;}
#endif
/******************************************************************************/
// PARAMETERS
/******************************************************************************/
#if PHYSX
Flt Cloth::damping ()C {return _cloth ? _cloth->getDampingCoefficient ().x : 0;}
Flt Cloth::friction ()C {return _cloth ? _cloth->getFrictionCoefficient () : 0;}
Flt Cloth:: drag ()C {return _cloth ? _cloth->getLinearDragCoefficient ().x : 0;}
Flt Cloth::angDrag ()C {return _cloth ? _cloth->getAngularDragCoefficient().x : 0;}
Flt Cloth:: inertiaScale()C {return _cloth ? _cloth->getLinearInertiaScale ().x : 0;}
Flt Cloth::angInertiaScale()C {return _cloth ? _cloth->getAngularInertiaScale ().x : 0;}
Flt Cloth::bending ()C {return _cloth ? 1-_cloth->getStretchConfig(PxClothFabricPhaseType::eBENDING).stiffness : 0;}
Cloth& Cloth::damping (Flt damping ) {if(_cloth)_cloth->setDampingCoefficient (Physx.vec(Sat(damping ))); return T;}
Cloth& Cloth::friction (Flt friction) {if(_cloth)_cloth->setFrictionCoefficient ( Sat(friction) ); return T;}
Cloth& Cloth:: drag (Flt drag ) {if(_cloth)_cloth->setLinearDragCoefficient (Physx.vec(Sat(drag ))); return T;}
Cloth& Cloth::angDrag (Flt drag ) {if(_cloth)_cloth->setAngularDragCoefficient(Physx.vec(Sat(drag ))); return T;}
Cloth& Cloth:: inertiaScale(Flt scale ) {if(_cloth)_cloth->setLinearInertiaScale (Physx.vec(Sat(scale ))); return T;}
Cloth& Cloth::angInertiaScale(Flt scale ) {if(_cloth)_cloth->setAngularInertiaScale (Physx.vec(Sat(scale ))); return T;}
Cloth& Cloth::bending (Flt bending ) {if(_cloth){PxClothStretchConfig config; config.stiffness=1-bending; _cloth->setStretchConfig(PxClothFabricPhaseType::eBENDING, config);} return T;}
#else
Flt Cloth::damping ()C {return 0;}
Flt Cloth::friction ()C {return 0;}
Flt Cloth:: drag ()C {return 0;}
Flt Cloth::angDrag ()C {return 0;}
Flt Cloth:: inertiaScale()C {return 0;}
Flt Cloth::angInertiaScale()C {return 0;}
Flt Cloth::bending ()C {return 0;}
Cloth& Cloth::damping (Flt damping ) {return T;}
Cloth& Cloth::friction (Flt friction) {return T;}
Cloth& Cloth:: drag (Flt drag ) {return T;}
Cloth& Cloth::angDrag (Flt drag ) {return T;}
Cloth& Cloth:: inertiaScale(Flt scale ) {return T;}
Cloth& Cloth::angInertiaScale(Flt scale ) {return T;}
Cloth& Cloth::bending (Flt bending ) {return T;}
#endif
/******************************************************************************/
// DRAW
/******************************************************************************/
void Cloth::update()
{
if(_update_count!=Physics._update_count)
{
_update_count=Physics._update_count;
#if PHYSX
if(C Particle *particles=lockRead())
{
if(Vtx *vtx=(Vtx*)_vtx_buf.lock(LOCK_WRITE))
{
C Vec2 *tex=_cloth_mesh->_phys.vtx.tex0();
Vtx *v =vtx;
REPA(_cloth_mesh->_phys.vtx)
{
v->nrm.zero();
v->pos=(particles++)->pos;
if(tex)v->tex=*tex++;else v->tex.zero();
v++;
}
C VecI *ind=_cloth_mesh->_phys.tri.ind();
REPA(_cloth_mesh->_phys.tri)
{
Vec nrm=GetNormalU(vtx[ind->x].pos, vtx[ind->y].pos, vtx[ind->z].pos);
vtx[ind->x].nrm+=nrm;
vtx[ind->y].nrm+=nrm;
vtx[ind->z].nrm+=nrm;
ind++;
}
REPA(_cloth_mesh->_phys.vtx)vtx[i].nrm.normalize();
_vtx_buf.unlock();
}
unlock();
}
#endif
}
}
/******************************************************************************/
void Cloth::_drawPhysical()C
{
#if DX11
_vtx_buf.set();
_cloth_mesh->_ind_buf.set();
D3DC->DrawIndexed(_cloth_mesh->_ind_buf._ind_num, 0, 0);
#elif GL
SetDefaultVAO(); _vtx_buf.set(); _cloth_mesh->_ind_buf.set(); D.vf(VI._vf3D_cloth.vf); // OpenGL requires setting 1)VAO 2)VB+IB 3)VF
glDrawElements(GL_TRIANGLES, _cloth_mesh->_ind_buf._ind_num, _cloth_mesh->_ind_buf.bit16() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, null);
#endif
}
/******************************************************************************/
void Cloth::drawSkinnedOutline(C AnimatedSkeleton &anim_skel, C Color &color)C
{
DEBUG_ASSERT(Renderer()==RM_OUTLINE, "'Cloth.drawSkinnedOutline' called outside of RM_OUTLINE");
if(_cloth_mesh)if(Shader *shader=_cloth_mesh->_skin_shader[RM_OUTLINE])
{
anim_skel.setMatrix();
C Material &mtrl=GetMaterial(_cloth_mesh->material()());
Renderer.setOutline(color);
D.depth(true);
mtrl.setOutline(); D.cull(mtrl.cull);
shader->begin(); _cloth_mesh->_skin.set().draw();
}
}
INLINE void ClothInstances::addShadow(C Cloth &cloth, Shader &shader, C Material &material)
{
ClothInstance &ci=New();
ci.cloth =&cloth;
ci.shader =&shader;
ci.material =&material; material.incUsage();
}
INLINE void ClothInstances::add(C Cloth &cloth, Shader &shader, C Material &material)
{
ClothInstance &ci=New();
ci.cloth =&cloth;
ci.shader =&shader;
ci.material =&material; material.incUsage();
ci.highlight = Renderer._mesh_highlight;
}
INLINE void ClothInstances::add(C Cloth &cloth, FRST &frst, C Material &material)
{
ClothInstance &ci=New();
ci.cloth =&cloth;
ci.shader =&frst;
ci.material =&material; material.incUsage();
ci.highlight= Renderer._mesh_highlight;
}
void Cloth::drawPhysical()C
{
DEBUG_ASSERT(Renderer()==RM_PREPARE, "'Cloth.drawPhysical' called outside of RM_PREPARE");
if(_cloth && Frustum(box()))
{
ConstCast(T).update();
C Material &material=GetMaterial(_cloth_mesh->material()());
switch(Renderer._cur_type)
{
case RT_DEFERRED: if(Shader *shader=_cloth_mesh->_phys_shader[Renderer._solid_mode_index])
{
SolidClothInstances.add(T, *shader, material);
}break;
case RT_FORWARD: if(FRST *frst=_cloth_mesh->_phys_frst)if(Renderer.firstPass() || frst->all_passes)//if(Shader *shader=frst->getShader())
{
SolidClothInstances.add(T, *frst, material); // velocities not needed in forward renderer
}break;
}
}
}
void Cloth::drawPhysicalShadow()C
{
DEBUG_ASSERT(Renderer()==RM_SHADOW, "'Cloth.drawPhysicalShadow' called outside of RM_SHADOW");
if(_cloth && Frustum(box()))
if(Shader *shader=_cloth_mesh->_phys_shader[RM_SHADOW])
{
ConstCast(T).update();
ShadowClothInstances.addShadow(T, *shader, GetMaterial(_cloth_mesh->material()()));
}
}
void Cloth::drawPhysicalOutline(C Color &color)C
{
DEBUG_ASSERT(Renderer()==RM_OUTLINE, "'Cloth.drawPhysicalOutline' called outside of RM_OUTLINE");
if(_cloth && Frustum(box()))
if(Shader *shader=_cloth_mesh->_phys_shader[RM_OUTLINE])
{
ConstCast(T).update();
C Material &mtrl=GetMaterial(_cloth_mesh->material()());
Renderer.setOutline(color);
SetOneMatrixAndPrev(); // current cloth shaders might use velocity
D.depth(true);
SetDefaultVAO(); D.vf(VI._vf3D_cloth.vf); // OpenGL requires setting 1)VAO 2)VB+IB 3)VF
D.cull (mtrl.cull); mtrl.setOutline();
shader->begin(); _drawPhysical();
}
}
/******************************************************************************/
}
/******************************************************************************/
| [
"esenthel@hotmail.com"
] | esenthel@hotmail.com |
11933727456914b98cc15e23d94507e879779487 | ad78d2168925ec23d290d0186a5249ad4c6ea037 | /src/ENDFtk/section/6/LaboratoryAngleEnergy/AngularDistribution/src/ctor.hpp | b38bfdcb60ecee36b9a2ba74e5ba1bff2ee4145e | [
"BSD-2-Clause"
] | permissive | jkulesza/ENDFtk | f363a115f059df02195b9f248f81854935c8dbf4 | b6618b396f51e802b7ee19ba529533c27e6ac302 | refs/heads/master | 2023-03-11T01:36:52.086387 | 2020-10-29T17:36:01 | 2020-10-29T17:36:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,076 | hpp | AngularDistribution(
double energy,
std::vector< long >&& boundaries,
std::vector< long >&& interpolants,
std::vector< EnergyDistribution >&& distributions )
try : InterpolationSequenceRecord(
InterpolationRecord( 0.0, energy, 0, 0,
std::move( boundaries ),
std::move( interpolants ) ),
std::move( distributions ) ) {}
catch ( std::exception& e ) {
Log::info( "Encountered error while constructing angular distribution data "
"(LAW=7)" );
throw;
}
template< typename Iterator >
AngularDistribution( Iterator& it, const Iterator& end,
long& lineNumber, int MAT, int MF, int MT )
try : InterpolationSequenceRecord(
readInterpolationSequenceRecord< EnergyDistribution >(
it, end, lineNumber, MAT, MF, MT ) ) {}
catch ( std::exception& e ) {
Log::info( "Encountered error while reading angular distribution data "
"(LAW=7)" );
throw;
}
| [
"whaeck@gmail.com"
] | whaeck@gmail.com |
7bd9d19ff9eb582e56b428fd1c7edae39669545e | f1d2734ee5f700a78081177387ebe710e418e2cc | /Arrays and Searching/TypeOfArray.cpp | 1ccddcc45a2163e13e65020c48038f4aca56651c | [] | no_license | Raunaq-singh/SudoPlacement2019 | 29a645ef0cb0a43ed29b9bb80c0410b672b7d405 | e3b0be3b7e265d5aa7abd19c99beed19a5e78000 | refs/heads/master | 2020-06-03T11:21:18.871792 | 2019-07-06T10:06:29 | 2019-07-06T10:06:29 | 191,548,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cpp | #include<bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
ll t;
cin>>t;
while(t--){
ll n;
cin>>n;
ll a[n];
ll mx=-1;
ll mn=INT_MAX;
for(ll i=0;i<n;i++){
cin>>a[i];
mx=max(a[i],mx);
mn=min(a[i],mn);
}
if(mx==a[n-1] && mn==a[0]){
cout<<mx<<" 1\n";
}else if(mx==a[0] && mn==a[n-1]){
cout<<mx<<" 2\n";
}else if(a[n-1]>a[0]){
cout<<mx<<" 3\n";
}else{
cout<<mx<<" 4\n";
}
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
4e0a6c91cf643979dde275a28ff5766a0ef932d2 | 6474e1ce6fdc13d514e59da2a7025a35d7908218 | /week-07/day-1/11.cpp | 435f8c32e77fe18ab6d5963ed8276e170f4bd579 | [] | no_license | green-fox-academy/ImreCsete | 1cc62af0e9dfa7f8005c214d3be13bb5db33cf69 | f5fc58a4793f17efec0249eca1b0f192d1860ff8 | refs/heads/master | 2021-09-06T09:23:06.177864 | 2018-02-05T00:53:20 | 2018-02-05T00:53:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,345 | cpp | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <typeinfo>
using namespace std;
int main() {
srand(time(NULL)); // This initializes the random generator.
int rnd = 0;
for (int i = 0; i < 20; i++) {
rnd = rand() % 5; // generate a random number in the range [0, 4]
try {
switch (rnd) {
case 0:
throw 3.2f;
break;
case 1:
throw double(43.56);
break;
case 3:
throw "Abrakadabra";
break;
case 4:
throw false;
break;
default:
throw 12;
break;
}
}
// Write catch blocks for each possibly thrown exception.
// In each catch block write out what the exception's type was. And what the exceptions value was.
catch(float f) {
cout << "ERROR: " << f << "\t\tValue type: " << typeid(f).name() << endl;
}
catch(double d) {
cout << "ERROR: " << d << "\t\tValue type: " << typeid(d).name() << endl;
}
catch(char const *s) {
cout << "ERROR: " << s << "\tValue type: " << typeid(s).name() << endl;
}
catch(bool b) {
cout << "ERROR: " << boolalpha << b << "\t\tValue type: " << typeid(b).name() << endl;
}
catch(int x) {
cout << "ERROR: " << x << "\t\tValue type: " << typeid(x).name() << endl;
}
}
return 0;
}
| [
"csete_imre@hotmail.com"
] | csete_imre@hotmail.com |
3b85c79bcfa88ed987823a1be55b3b74e4d065b5 | 8c74008407dc93b74fb4cee5a986bb9cdae4adf2 | /tools/log viewer/Source.cpp | 0cc18c5aeb565cc23c6722d2755f6fe23e1994cc | [
"MIT"
] | permissive | Qazwar/RFC-Framework | 0d1581ac20b1637664cb3c958ebc7b85b75d15cf | 9c1881d412db6f9f7670b910a0918a631208cfd1 | refs/heads/master | 2023-06-01T21:36:21.394870 | 2021-06-17T06:26:22 | 2021-06-17T06:26:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,333 | cpp |
#include "rfc_amalgamated.h"
#define COL_WARNING_TEXT RGB(0, 128, 0)
#define COL_WARNING_BACK RGB(240, 240, 240)
#define COL_ERROR_TEXT RGB(149, 0, 0)
#define COL_ERROR_BACK RGB(255, 240, 240)
/**
custom drawn gridview to highlight warnings & errors.
for some components, custom drawing is easier than owner drawing.
see: https://www.codeproject.com/Articles/79/Neat-Stuff-to-Do-in-List-Controls-Using-Custom-Dra
*/
class KLogViewingGrid : public KGridView
{
public:
bool EventProc(UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *result)
{
if (msg == WM_NOTIFY)
{
if (((LPNMHDR)lParam)->code == NM_CUSTOMDRAW) // custom drawing msg received for this component
{
LPNMLVCUSTOMDRAW pLVCD = (LPNMLVCUSTOMDRAW) lParam;
*result = CDRF_DODEFAULT; // take the default processing unless we set this to something else below.
if (CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage) // it's the control's prepaint stage, tell Windows we want messages for every item.
{
*result = CDRF_NOTIFYITEMDRAW;
}
else if ( CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage ) // prepaint stage for an item. (subitems will use same values.)
{
if (pLVCD->nmcd.lItemlParam == KLogger::EVT_ERROR)
{
pLVCD->clrTextBk = COL_ERROR_BACK;
pLVCD->clrText = COL_ERROR_TEXT;
}
else if (pLVCD->nmcd.lItemlParam == KLogger::EVT_WARNING)
{
pLVCD->clrTextBk = COL_WARNING_BACK;
pLVCD->clrText = COL_WARNING_TEXT;
}
*result = CDRF_DODEFAULT; // tell Windows to paint the control itself.
}
return true; // indicate that we processed this msg & result is valid.
}
}
return KGridView::EventProc(msg, wParam, lParam, result); // pass unprocessed messages to parent
}
void InsertRecord(KString **columnsData, int eventType)
{
LVITEMW lvi = { 0 };
lvi.mask = LVIF_TEXT | LVIF_PARAM;
lvi.pszText = (wchar_t*)(const wchar_t*)(*columnsData[0]);
lvi.iItem = itemCount;
lvi.lParam = (LPARAM)eventType;
int row = (int)::SendMessageW(compHWND, LVM_INSERTITEMW, 0, (LPARAM)&lvi);
for (int i = 1; i < colCount; i++) // first column already added, lets add the others
{
LV_ITEMW lvi = { 0 };
lvi.iSubItem = i;
lvi.pszText = (wchar_t*)(const wchar_t*)(*columnsData[i]);
::SendMessageW(compHWND, LVM_SETITEMTEXTW, (WPARAM)row, (LPARAM)&lvi);
}
itemCount++;
}
/**
never used, but it's just here to show that we are using LPARAM to store event type.
*/
int GetEventTypeOfRecord(int rowIndex)
{
LV_ITEMW lvi = { 0 };
lvi.iItem = rowIndex;
lvi.mask = LVIF_PARAM;
ListView_GetItem(compHWND, &lvi);
return (int)lvi.lParam;
}
};
class MainWindow : public KOverlappedWindow, public KGridViewListener, public KMenuItemListener, public KThread
{
protected:
KLogViewingGrid gridView;
KMenuItem miOpenFile, miExit;
KMenu fileMenu;
KMenuBar menuBar;
KString logFilePath;
public:
MainWindow()
{
this->SetSize(800, 600);
this->SetText(CONST_TXT("Log Viewer"));
this->CreateComponent();
this->CenterScreen();
// create menu
miOpenFile.SetText(CONST_TXT("Open Log File..."));
miExit.SetText(CONST_TXT("Exit"));
miOpenFile.SetListener(this);
miExit.SetListener(this);
fileMenu.AddMenuItem(&miOpenFile);
fileMenu.AddSeperator();
fileMenu.AddMenuItem(&miExit);
menuBar.AddMenu(CONST_TXT("File"), &fileMenu);
menuBar.AddToWindow(this);
this->AddComponent(&gridView);
gridView.SetListener(this);
int clientWidth, clientHeight;
this->GetClientAreaSize(&clientWidth, &clientHeight);
gridView.SetSize(clientWidth, clientHeight);
gridView.CreateColumn(CONST_TXT("Time (sec : mills)"));
gridView.CreateColumn(CONST_TXT("Type"));
gridView.CreateColumn(CONST_TXT("Details"), clientWidth - (gridView.GetColumnWidth(0) + gridView.GetColumnWidth(1) + 40));
}
void OnMenuItemPress(KMenuItem *menuItem)
{
if (menuItem == &miOpenFile)
{
if (KCommonDialogBox::ShowOpenFileDialog(this, L"Open Log File...", L"Log Files (*.rlog)\0*.rlog\0", &logFilePath))
{
gridView.RemoveAll();
this->SetText(CONST_TXT("Log Viewer"));
StartThread();
}
}
else if (menuItem == &miExit)
{
this->ThreadShouldStop();
this->WaitUntilThreadFinish();
this->OnClose();
}
}
void Run()
{
KFile logFile;
if (logFile.OpenFile(logFilePath, KFile::KREAD))
{
char header[4];
logFile.ReadFile(header, 4);
if ((header[0] = 'R') && (header[1] = 'L') && (header[2] = 'O') && (header[3] = 'G'))
{
unsigned int totalEvents = 0;
logFile.ReadFile(&totalEvents, sizeof(unsigned int));
int errorEventsCount = 0;
int warningEventsCount = 0;
for (unsigned int i = 0; i < totalEvents; i++)
{
unsigned char eventType;
logFile.ReadFile(&eventType, 1);
if (eventType == KLogger::EVT_ERROR)
errorEventsCount++;
else if (eventType == KLogger::EVT_WARNING)
warningEventsCount++;
unsigned short secs;
logFile.ReadFile(&secs, sizeof(unsigned short));
unsigned short mills;
logFile.ReadFile(&mills, sizeof(unsigned short));
KString details;
while (true) // iterate through each params
{
unsigned char paramType;
logFile.ReadFile(¶mType, 1);
if (paramType == KLogger::PARAM_STRING)
{
unsigned char dataSize;
logFile.ReadFile(&dataSize, 1);
char buff[256];
logFile.ReadFile(buff, dataSize);
buff[dataSize] = 0;
details = details + KString(buff);
}
else if (paramType == KLogger::PARAM_INT32)
{
int data = 0;
logFile.ReadFile(&data, sizeof(int));
details = details + KString(data);
}
else if (paramType == KLogger::PARAM_SHORT16)
{
unsigned short data = 0;
logFile.ReadFile(&data, sizeof(unsigned short));
details = details + KString((int)data);
}
else if (paramType == KLogger::PARAM_FLOAT)
{
float data = 0;
logFile.ReadFile(&data, sizeof(float));
details = details + KString(data, 4, true);
}
else if (paramType == KLogger::PARAM_DOUBLE)
{
double data = 0;
logFile.ReadFile(&data, sizeof(double));
details = details + KString((float)data, 4, true);
}
else if (paramType == KLogger::EVT_END)
{
break;
}
else
{
MessageBoxW(this->GetHWND(), L"Invalid param type defined!", L"Error", MB_ICONERROR);
goto DONE;
}
}
char strMills[5];
sprintf(strMills, "%03d", (int)mills); // zero padded mills
AddRecord(KString((int)secs) + CONST_TXT(" : ") + KString(strMills, KString::USE_COPY_OF_TEXT), eventType, details);
if (threadShouldStop)
break;
}
this->SetText(CONST_TXT("Log Viewer - ") + KString(totalEvents) + CONST_TXT(" Events , ") + KString(errorEventsCount) + CONST_TXT(" Errors , ") + KString(warningEventsCount) + CONST_TXT(" Warnings"));
}
else{
MessageBoxW(this->GetHWND(), L"Invalid log file!", L"Error", MB_ICONERROR);
}
}
else{
MessageBoxW(this->GetHWND(), L"Cannot read log file!", L"Error", MB_ICONERROR);
}
DONE:
isThreadRunning = false;
}
void AddRecord(KString time, unsigned char eventType, KString details)
{
const wchar_t *eventTypes[3] = { L"Information", L"Warning", L"Error" };
KString eventStr(eventTypes[eventType - 1], KString::STATIC_TEXT_DO_NOT_FREE);
KString* items[3];
items[0] = &time;
items[1] = &eventStr;
items[2] = &details;
gridView.InsertRecord(items, eventType);
}
void OnGridViewItemRightClick(KGridView *gridView)
{
int row = gridView->GetSelectedRow();
if (row != -1)
{
// you can show popup menu in here...
}
}
void OnResized()
{
int clientWidth, clientHeight;
this->GetClientAreaSize(&clientWidth, &clientHeight);
gridView.SetSize(clientWidth, clientHeight);
gridView.SetColumnWidth(0, 100);
gridView.SetColumnWidth(1, 100);
gridView.SetColumnWidth(2, clientWidth - (gridView.GetColumnWidth(0) + gridView.GetColumnWidth(1) + 40));
}
~MainWindow()
{
}
};
class LogViewerApplication : public KApplication
{
public:
int Main(KString **argv, int argc)
{
MainWindow wnd;
wnd.SetVisible(true);
::DoMessagePump(false);
return 0;
}
};
START_RFC_APPLICATION_NO_CMD_ARGS(LogViewerApplication); | [
"ruchira66@gmail.com"
] | ruchira66@gmail.com |
abedb2bcba02167dfb4cfb9e0811ece9b0b09ef9 | 2ff9f9945f81637e513b06195dcce1f922c12248 | /src/backend/opencl/jit/kernel_generators.hpp | 8754ef858261d3beb2d3a3a55e7617f5a8307317 | [
"MIT",
"BSD-3-Clause",
"Zlib",
"BSL-1.0",
"Apache-2.0"
] | permissive | mlloreda/arrayfire | 256f246a74ec0a6a097fad34df03d332e887aa18 | 2bac5df9f8e46cda6a9110ef84efca1d6afa02c3 | refs/heads/master | 2020-12-03T09:20:29.442976 | 2018-11-16T14:44:40 | 2018-11-16T17:40:51 | 77,644,409 | 1 | 0 | null | 2016-12-29T22:46:36 | 2016-12-29T22:46:36 | null | UTF-8 | C++ | false | false | 4,301 | hpp | /*******************************************************
* Copyright (c) 2018, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <string>
#include <sstream>
namespace opencl {
namespace {
/// Creates a string that will be used to declare the parameter of kernel
void generateParamDeclaration(std::stringstream& kerStream, int id, bool is_linear,
const std::string& m_type_str) {
if (is_linear) {
kerStream << "__global " << m_type_str << " *in" << id
<< ", dim_t iInfo" << id << "_offset, \n";
} else {
kerStream << "__global " << m_type_str << " *in" << id
<< ", KParam iInfo" << id << ", \n";
}
}
/// Calls the setArg function to set the arguments for a kernel call
int setKernelArguments(int start_id, bool is_linear,
std::function<void(int id, const void* ptr, size_t arg_size)>& setArg,
const std::shared_ptr<cl::Buffer>& ptr, const KParam& info) {
setArg(start_id + 0, static_cast<const void*>(&ptr.get()->operator()()), sizeof(cl_mem));
if (is_linear) {
setArg(start_id + 1, static_cast<const void*>(&info.offset), sizeof(dim_t));
} else {
setArg(start_id + 1, static_cast<const void*>(&info), sizeof(KParam));
}
return start_id + 2;
}
/// Generates the code to calculate the offsets for a buffer
void generateBufferOffsets(std::stringstream &kerStream, int id, bool is_linear, const std::string& type_str) {
std::string idx_str = std::string("int idx") + std::to_string(id);
std::string info_str = std::string("iInfo") + std::to_string(id);
if (is_linear) {
kerStream << idx_str << " = idx + " << info_str << "_offset;\n";
} else {
kerStream << idx_str << " = (id3 < " << info_str << ".dims[3]) * "
<< info_str << ".strides[3] * id3 + (id2 < " << info_str << ".dims[2]) * "
<< info_str << ".strides[2] * id2 + (id1 < " << info_str << ".dims[1]) * "
<< info_str << ".strides[1] * id1 + (id0 < " << info_str << ".dims[0]) * id0 + "
<< info_str << ".offset;\n";
}
}
/// Generates the code to read a buffer and store it in a local variable
void generateBufferRead(std::stringstream &kerStream, int id, const std::string& type_str)
{
kerStream << type_str << " val" << id << " = in" << id << "[idx" << id << "];\n";
}
void generateShiftNodeOffsets(std::stringstream &kerStream, int id,
bool is_linear, const std::string& type_str) {
std::string idx_str = std::string("idx") + std::to_string(id);
std::string info_str = std::string("iInfo") + std::to_string(id);
std::string id_str = std::string("sh_id_") + std::to_string(id) + "_";
std::string shift_str = std::string("shift") + std::to_string(id) + "_";
for (int i = 0; i < 4; i++) {
kerStream << "int " << id_str << i
<< " = __circular_mod(id" << i
<< " + " << shift_str << i
<< ", " << info_str << ".dims[" << i << "]);\n";
}
kerStream << "int " << idx_str << " = (" << id_str << "3 < " << info_str << ".dims[3]) * "
<< info_str << ".strides[3] * " << id_str << "3;\n";
kerStream << idx_str << " += (" << id_str << "2 < " << info_str << ".dims[2]) * "
<< info_str << ".strides[2] * " << id_str << "2;\n";
kerStream << idx_str << " += (" << id_str << "1 < " << info_str << ".dims[1]) * "
<< info_str << ".strides[1] * " << id_str << "1;\n";
kerStream << idx_str << " += (" << id_str << "0 < " << info_str << ".dims[0]) * "
<< id_str << "0 + " << info_str << ".offset;\n";
}
void generateShiftNodeRead(std::stringstream &kerStream, int id,
const std::string& type_str) {
kerStream << type_str << " val" << id
<< " = in" << id << "[idx" << id << "];\n";
}
}
}
| [
"pradeep@arrayfire.com"
] | pradeep@arrayfire.com |
1ae459c3658efbf605faed4df4c2c59fa422bcb4 | 786cd2c3e735f24e1ccf9ce8e72bbafe5f22e1c1 | /Bematech_Termica/ImpressoraFiscalEcfRfd.cpp | 7a1465a889a43b238b9618ab90c1df6c39ba1169 | [] | no_license | Nilson-Xavier/Consigo | 0eea85e08160960b2225af5f0b9d119ae6fd56d3 | 4f22a03604132e56b34f687f805d82d7baf9474c | refs/heads/master | 2020-05-26T15:12:38.985619 | 2019-05-23T19:40:29 | 2019-05-23T19:40:29 | 188,280,296 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 22,521 | cpp | //---------------------------------------------------------------------------
#pragma hdrstop
#include "ImpressoraFiscalEcfRfd.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
__fastcall TImpressoraFiscalRfd::TImpressoraFiscalRfd( void ) {
}
//---------------------------------------------------------------------------
__fastcall TImpressoraFiscalRfd::~TImpressoraFiscalRfd( void ) {
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::AbrirCoxexaoSerial ( String *Erro ) {
int CodigoRetorno;
char Buffer[2048];
this->iHandleDll = LoadLibrary( "ECF32M.dll" );
if( iHandleDll == NULL ) {
*Erro = "Erro ao carregar a biblioteca ECF3E32.DLL.\r\rFavor verificar!";
return( false );
}
else {
OpenCif = ( OPENCIF ) GetProcAddress( iHandleDll , "OpenCif" );
CloseCif = ( CLOSECIF ) GetProcAddress( iHandleDll , "CloseCif" );
RespostaComando = ( ESPERARESPOSTA ) GetProcAddress( iHandleDll , "EsperaResposta" );
//AbreCupomFiscal = ( ABRECUPOM ) GetProcAddress( iHandleDll , "AbreCupomFiscal" );
AbreCupomFiscalCpfCnpjNome = ( ABRECUPOM ) GetProcAddress( iHandleDll , "AbreCupomFiscalCPF_CNPJ_NOME" );
VendaItem = ( VENDA ) GetProcAddress( iHandleDll , "VendaItemStr" );
CancelamentoItem = ( CANCELAMENTO ) GetProcAddress( iHandleDll , "CancelamentoItem" );
TotCupomSemDescAcres = ( TOTALIZA ) GetProcAddress( iHandleDll , "TotCupomSemDescAcres" );
Pgto = ( PGTO ) GetProcAddress( iHandleDll , "Pagamento" );
FechaCupom = ( FECHACUPOM ) GetProcAddress( iHandleDll , "FechaCupomFiscal" );
CancelaCupomFiscal = ( CANCELACUPOM ) GetProcAddress( iHandleDll , "CancelaCupomFiscal" );
PLeituraX = ( LEITURAX ) GetProcAddress( iHandleDll , "LeituraX" );
PReducaoZ = ( REDUCAOZ ) GetProcAddress( iHandleDll , "ReducaoZ" );
AbreCupomVinculado = ( ABRECUPV ) GetProcAddress( iHandleDll , "AbreCupomVinculado" );
AbreCupomNaoVinculado = ( ABRECUPNV ) GetProcAddress( iHandleDll , "AbreCupomNaoVinculado" );
ImprimeLinhaNaoFiscal = ( IMPLIN ) GetProcAddress( iHandleDll , "ImprimeLinhaNaoFiscal" );
ImprimeTextoNaoFiscal = ( IMPLINTEXTO ) GetProcAddress( iHandleDll , "ImprimeLinhaNaoFiscal" );
EncerraCupomNaoFiscal = ( ENCCUPOM ) GetProcAddress( iHandleDll , "EncerraCupomNaoFiscal" );
EsperaResposta = ( ESPERARESPOSTA ) GetProcAddress( iHandleDll , "EsperaResposta" );
ObterParEcf = ( TXPARECF ) GetProcAddress( iHandleDll , "EcfPar" );
pGerarArquivoRfd = ( GerarArquivoRFD ) GetProcAddress( iHandleDll , "GerarArquivoRFD" );
pValidarArquivoRfd = ( ValidarArquivoRFD ) GetProcAddress( iHandleDll , "ValidarArquivoRFD" );
if( ( OpenCif == NULL ) || ( CloseCif == NULL ) || ( RespostaComando == NULL ) ||
( AbreCupomFiscalCpfCnpjNome == NULL ) || ( VendaItem == NULL ) ||
( CancelamentoItem == NULL ) || ( TotCupomSemDescAcres == NULL ) ||
( Pgto == NULL ) || ( FechaCupom == NULL ) || ( CancelaCupomFiscal == NULL ) ||
( PLeituraX == NULL ) || ( PReducaoZ == NULL ) || ( AbreCupomVinculado == NULL ) ||
( AbreCupomNaoVinculado == NULL ) || ( ImprimeLinhaNaoFiscal == NULL ) ||
( ImprimeTextoNaoFiscal == NULL ) || ( EncerraCupomNaoFiscal == NULL ) ||
( EsperaResposta == NULL ) || ( ObterParEcf == NULL ) || ( pGerarArquivoRfd == NULL ) ||
( pValidarArquivoRfd == NULL ) ) {
FreeLibrary( this->iHandleDll );
*Erro = "Erro ao carregar as funções da biblioteca ECF32M.dll.\r\rFavor verificar!";
return( false );
}
else {
OpenCif( );
CodigoRetorno = RespostaComando( Buffer );
if( CodigoRetorno >= 0 ) {
return( true );
}
else {
*Erro = this->ObterMensagemRetorno( CodigoRetorno ) + String(Buffer);
return( false );
}
}
}
}
//---------------------------------------------------------------------------
void __fastcall TImpressoraFiscalRfd::FecharConexaoSerial( ) {
CloseCif( );
if( this->iHandleDll != NULL ) {
FreeLibrary( this->iHandleDll );
}
}
//---------------------------------------------------------------------------
/*
bool TImpressoraFiscalRfd::AbrirCupomFiscal( String *Erro ) {
this->AbreCupomFiscal( );
return( this->ObterRespostaComando( Erro ) );
}
*/
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::AbrirCupomFiscal( String *CpfCnpj, String *Nome, String *Erro ) {
int i;
String *CpfCnpjFmt;
try {
CpfCnpjFmt = new AnsiString( );
if( !CpfCnpj->IsEmpty( ) ) {
for( i = 1; i <= CpfCnpj->Length( ); i++ ) {
if( ( ( AnsiCompareStr( CpfCnpj->SubString( i, 1 ), "0" ) >= 0 ) && ( AnsiCompareStr( CpfCnpj->SubString( i, 1 ), "9" ) <= 0 ) ) ) {
*CpfCnpjFmt = *CpfCnpjFmt + CpfCnpj->SubString( i, 1 );
}
}
*CpfCnpjFmt = LeftStr( *CpfCnpjFmt, 14 );
}
*Nome = LeftStr( *Nome, 14 );
this->AbreCupomFiscalCpfCnpjNome( CpfCnpjFmt->c_str( ), Nome->c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
__finally {
delete CpfCnpjFmt;
}
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::LancarItemFiscal( String *Qtd, String *PrecoUnit, String *TaxaImposto,
String *Codigo, String *DescricaoProduto,
String *Erro ) {
String *Formato, *TipoDesconto, *ValorDesconto, *Unidade, *TamanhoDescricaoItem,
*LegendaOperacao;
try {
//formato dos digitos inteiros e decimais p/ quantidade e preco unitario
Formato = new AnsiString( "G" );
// formatando quantidade 4 dig inteiro e 3 dig decimais
while( Qtd->Length( ) < 4 ) {
Qtd->Insert( "0", 1 );
}
*Qtd = *Qtd + "000";
// formatando preco unitario 9 dig inteiro e 2 dig decimais
*PrecoUnit = StringReplace( *PrecoUnit, ".", "", TReplaceFlags( ) << rfReplaceAll );
*PrecoUnit = StringReplace( *PrecoUnit, ",", "", TReplaceFlags( ) << rfReplaceAll );
while( PrecoUnit->Length( ) < 11 ) {
PrecoUnit->Insert( "0", 1 );
}
// formatando taxa imposto icms
if( *TaxaImposto == "0" ) {
*TaxaImposto = "I00";
}
else if( *TaxaImposto == "2,15" ) {
*TaxaImposto = "T01";
}
else if( *TaxaImposto == "3,10" ) {
*TaxaImposto =="T02";
}
else if( *TaxaImposto == "5,00" ) {
*TaxaImposto = "T00";
}
else if( *TaxaImposto == "7,00" ) {
*TaxaImposto = "T04";
}
else if( *TaxaImposto == "12,00" ) {
*TaxaImposto = "T05";
}
else if( *TaxaImposto == "18,00" ) {
*TaxaImposto = "T03";
}
else {
*TaxaImposto = "I00";
}
//formato tipo de desconto
TipoDesconto = new AnsiString( "1" );
//formato valor do desconto
ValorDesconto = new AnsiString( "000000000000000" );
//formato da unidade do item
Unidade = new AnsiString( "pc" );
//formato do codigo do item
*Codigo = LeftStr( *Codigo, 13 );
while( Codigo->Length( ) < 13 ) {
Codigo->Insert( " ", 1 );
}
//formato do tamanho da descricao do item
if( DescricaoProduto->Length( ) < 20 ) {
TamanhoDescricaoItem = new AnsiString( "0" );
while( DescricaoProduto->Length( ) < 20 ) {
DescricaoProduto->Insert( " ", 1 );
}
}
else if( DescricaoProduto->Length( ) < 38 ) {
TamanhoDescricaoItem = new AnsiString( "1" );
while( DescricaoProduto->Length( ) < 38 ) {
DescricaoProduto->Insert( " ", 1 );
}
}
else if( DescricaoProduto->Length( ) < 76 ) {
TamanhoDescricaoItem = new AnsiString( "2" );
while( DescricaoProduto->Length( ) < 76 ) {
DescricaoProduto->Insert( " ", 1 );
}
}
else if( DescricaoProduto->Length( ) < 114 ) {
TamanhoDescricaoItem = new AnsiString( "3" );
while( DescricaoProduto->Length( ) < 114 ) {
DescricaoProduto->Insert( " ", 1 );
}
}
else if( DescricaoProduto->Length( ) < 152 ) {
TamanhoDescricaoItem = new AnsiString( "4" );
while( DescricaoProduto->Length( ) < 152 ) {
DescricaoProduto->Insert( " ", 1 );
}
}
else if( DescricaoProduto->Length( ) < 190 ) {
TamanhoDescricaoItem = new AnsiString( "5" );
while( DescricaoProduto->Length( ) < 190 ) {
DescricaoProduto->Insert( " ", 1 );
}
}
else {
TamanhoDescricaoItem = new AnsiString( "5" );
*DescricaoProduto = LeftStr( *DescricaoProduto, 190 );
}
LegendaOperacao = new AnsiString( );
this->VendaItem( Formato->c_str( ), Qtd->c_str( ), PrecoUnit->c_str( ), TaxaImposto->c_str( ), TipoDesconto->c_str( ), ValorDesconto->c_str( ), Unidade->c_str( ), Codigo->c_str( ), TamanhoDescricaoItem->c_str( ), DescricaoProduto->c_str( ), LegendaOperacao->c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
__finally {
delete Formato;
delete TipoDesconto;
delete ValorDesconto;
delete Unidade;
delete TamanhoDescricaoItem;
delete LegendaOperacao;
}
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::CancelarItem( int IndexItem, String *Erro ) {
this->CancelamentoItem( String(IndexItem).c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::TotalizarCupom( String *Erro ) {
this->TotCupomSemDescAcres( );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::Pagamento( String *ModoPagamento, String *VPgto, String *Erro ) {
// formatando o modo de pagamento
if( *ModoPagamento == "Dinheiro" ) {
*ModoPagamento = "00";
}
else if( *ModoPagamento == "Cheque" ) {
*ModoPagamento = "01";
}
else if( *ModoPagamento == "Cartao Debito" ) {
*ModoPagamento = "02";
}
else if( *ModoPagamento == "Cartao Credito" ) {
*ModoPagamento = "03";
}
else if( *ModoPagamento == "Financiado" ) {
*ModoPagamento = "04";
}
else {
*ModoPagamento = "00";
}
// formatando o valor do pagamento
*VPgto = StringReplace( *VPgto, ".", "", TReplaceFlags( ) << rfReplaceAll );
*VPgto = StringReplace( *VPgto, ",", "", TReplaceFlags( ) << rfReplaceAll );
while( VPgto->Length( ) < 15 ) {
VPgto->Insert( "0", 1 );
}
this->Pgto( ModoPagamento->c_str( ), VPgto->c_str( ), "1" );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::FecharCupomFiscal( String *Vendedor, String *Erro ) {
String *TamMensagem, *Mensagem;
try {
TamMensagem = new AnsiString( );
Mensagem = new AnsiString( );
*Mensagem = "Vendedor: " + *Vendedor;
while( Mensagem->Length( ) <= 48 ) {
*Mensagem = *Mensagem + " ";
}
*Mensagem = *Mensagem + " ";
*Mensagem = *Mensagem + " Visite Nosso Salao de Exposicao Consigo! ";
*Mensagem = *Mensagem + " CONSIGO - A CERTEZA DE UM BOM NEGOCIO ";
*Mensagem = *Mensagem + " TEL: (11)3214-2660 FAX: (11)3214-5896 ";
if( Mensagem->Length( ) >= 100 ) {
*TamMensagem = "S" + String( Mensagem->Length( ) );
}
else if( Mensagem->Length( ) >= 10 ) {
*TamMensagem = "S0" + String( Mensagem->Length( ) );
}
else{
*TamMensagem = "S00" + String( Mensagem->Length( ) );
}
this->FechaCupom( TamMensagem->c_str( ), Mensagem->c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
__finally {
delete TamMensagem;
delete Mensagem;
}
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::CancelarCupomFiscal( String *Erro ) {
this->CancelaCupomFiscal( );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::LeituraX( String *Erro ) {
AnsiString *RelatorioGerencial;
try {
RelatorioGerencial = new AnsiString( "0" );
this->PLeituraX( RelatorioGerencial->c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
__finally {
delete RelatorioGerencial;
}
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::ReducaoZ( String *Erro ) {
AnsiString *RelatorioGerencial;
try {
RelatorioGerencial = new AnsiString( "0" );
this->PReducaoZ( RelatorioGerencial->c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
__finally {
delete RelatorioGerencial;
}
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::AbrirCupomNaoFiscalVinculado( String *Erro ) {
this->AbreCupomVinculado( );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::AbrirCupomNaoFiscalNaoVinculado( String *Erro ) {
this->AbreCupomNaoVinculado( );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::ImprimirLinhaNaoFiscal( String *Texto, String *Erro ) {
*Texto = LeftStr( *Texto, 48 );
if( Texto->Length( ) < 48 ) {
while( Texto->Length( ) < 48 ) {
*Texto = *Texto + " ";
}
}
this->ImprimeLinhaNaoFiscal( "0", Texto->c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::ImprimirTextoNaoFiscal( String *Texto, String *Erro ) {
this->ImprimeTextoNaoFiscal( "0", (LeftStr( *Texto, 999 )).c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::FecharCupomNaoFiscal( String *Erro ) {
this->EncerraCupomNaoFiscal( );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::ObterNumeroUltimoCupomFiscal( int &UltimoCupom, String *Erro ) {
int CodRetorno, i;
char BufferRetorno[2048];
String *Numero;
try {
Numero = new AnsiString( );
CodRetorno = this->ObterParEcf( "41" );
if( CodRetorno < 0 ) {
*Erro = this->ObterMensagemRetorno( CodRetorno );
return( false );
}
else {
CodRetorno = this->EsperaResposta( BufferRetorno );
if( CodRetorno >= 0 ) {
*Numero = BufferRetorno;
*Numero = Numero->SubString( 6, 6 );
UltimoCupom = Numero->ToInt( );
UltimoCupom++;
*Erro = "";
return( true );
}
else {
*Erro = this->ObterMensagemRetorno( CodRetorno );
return( false );
}
}
}
__finally {
delete Numero;
}
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::GerarArquivoRfd( String *Data, String *CaminhoDaPastaDestino, String *Erro ) {
//StringReplace( *Data, "/", "", TReplaceFlags( ) << rfReplaceAll );
*Data = "";
this->pGerarArquivoRfd( Data->c_str( ), CaminhoDaPastaDestino->c_str( ) );
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::ValidarArquivoRfd( String *CaminhoDoArquivo, String *RetornoMd5, String *Erro ) {
char Buffer[32+1];
this->pValidarArquivoRfd( CaminhoDoArquivo->c_str( ), &Buffer[0], 32 );
*RetornoMd5 = Buffer;
return( this->ObterRespostaComando( Erro ) );
}
//---------------------------------------------------------------------------
bool TImpressoraFiscalRfd::ObterRespostaComando( String *Erro ) {
char Buffer[2048];
int CodigoRetornoComando;
CodigoRetornoComando = this->EsperaResposta( Buffer );
if( CodigoRetornoComando >= 0 ) {
*Erro = "";
return( true );
}
else {
*Erro = this->ObterMensagemRetorno( CodigoRetornoComando );
*Erro = *Erro + String(Buffer);
return( false );
}
}
//---------------------------------------------------------------------------
String TImpressoraFiscalRfd::ObterMensagemRetorno( int CodigoRetornoComando ) {
switch( char(CodigoRetornoComando) ) {
case 0: return( "Função executada com sucesso" );
case 1: return( "Função executada com sucesso. Detectado pouco papel");
case 2: return( "Função executada com sucesso. Cancelando Cupom");
case 3: return( "Função executada com sucesso.Abrindo Cupom Rel Gerencial");
case -1: return( "O cabeçalho contém caracteres inválidos");
case -2: return( "Comando inexistente");
case -3: return( "Valor não numérico em campo numérico");
case -4: return( "Valor fora da faixa entre 20h e 7Fh");
case -5: return( "Campo deveria iniciar com @, & ou %");
case -6: return( "Troco já realizado.");
case -7: return( "O intervalo é inconsistente. No caso de datas, valores anteriores a 01/01/1995 serão considerados como pertencentes ao intervalo 2000-2094");
case -9: return( "A string TOTAL não é aceita");
case -10: return( "A sintaxe do comando está errada");
case -11: return( "Execedeu o número máximo de linhas permitido pelo comando");
case -12: return( "O terminador enviado não está obedecendo o protocolo de comunicação");
case -13: return( "O checksum enviado está incorreto");
case -15: return( "A situação tributária deve iniciar com T, F ou N");
case -16: return( "Data inválida");
case -17: return( "Hora inválida");
case -18: return( "Alîquota não programada ou fora da intervalo");
case -19: return( "O campo de sinal está incorreto");
case -20: return( "Comando só aceito durante Intervenção Fiscal");
case -21: return( "Comando só aceito durante Modo Normal");
case -22: return( "Necessário abrir Cupom Fiscal");
case -23: return( "Comando não aceito durante Cupom Fiscal");
case -24: return( "Necessário abrir Cupom Não Fiscal");
case -25: return( "Comando não aceito durante Cupom Não Fiscal");
case -26: return( "O relógio já está em horário de verão");
case -27: return( "O relógio não está em horário de verão");
case -28: return( "Necessário realizar Redução Z");
case -29: return( "Fechamento do dia (Redução Z) já executado");
case -30: return( "Necessário programar legenda");
case -31: return( "Item já cancelado ou item inexistente");
case -32: return( "Cupom anterior não pode ser cancelado");
case -33: return( "Detectado Falta de Papel");
case -36: return( "Necessário programar os dados do estabelecimento");
case -37: return( "Necessário realizar Intervenção Fiscal");
case -38: return( "A Memória Fiscal não permite mais realizar vendas.Só é possível executar Leitura X ou Leitura da Memória Fiscal");
case -39: return( "A Memória Fiscal não permite mais realizar vendas.Só é possível executar Leitura X ou Leitura da Memória Fiscal.Ocorreu algum problema na memória NOVRAM.Será necessário realizar uma Intervenção Fiscal");
case -40: return( "Necessário programar a data do relógio");
case -41: return( "Número máximo de itens por cupom ultrapassado");
case -42: return( "Já foi realizado o ajuste de hora diário");
case -43: return( "Comando válido ainda em execução");
case -44: return( "Está em estado de impressão de cheques");
case -45: return( "Não está em estado de impressão de cheques");
case -46: return( "Necessário inserir o cheque");
case -47: return( "Necessário inserir nova bobina");
case -48: return( "Necessário executar uma Leitura X");
case -49: return( "Detectado algum problema na impressora (paper jam, sobretensão, etc)");
case -50: return( "Cupom já foi totalizado");
case -51: return( "Necessário totalizar Cupom antes de fechar");
case -52: return( "Necessário finalizar Cupom antes de fechar");
case -53: return( "Ocorreu erro de gravação da memória fiscal");
case -54: return( "Excedeu número máximo de estabelecimentos");
case -55: return( "Memória Fiscal não iniciada");
case -56: return( "Ultrapassou valor do pagamento");
case -57: return( "Registrador não programado ou troco já realizado");
case -58: return( "Falta completar valor do pagamento");
case -59: return( "Campo somente de caracteres não-numéricos");
case -60: return( "Excedeu campo máximo de caracteres");
case -61: return( "Troco não realizado");
case -62: return( "Comando desabilitado");
case -83: return( "Ocorreu Fim de Papel");
case -84: return( "Falha Geral");
case -85: return( "Comando nao recebido pelo ECF");
case -86: return( "Erro no arquivo Cif.ini");
case -87: return( "Erro na abertura da serial");
case -88: return( "Erro na alocacao de recursos do windows");
case -89: return( "Retorno nao identificado");
case -90: return( "Falha na leitura da serial");
case -91: return( "Temperatura da cabeça está alta");
case -92: return( "Detectado pouco papel");
case -94: return( "Erro Irrecuperavel");
case -95: return( "Erro Mecânico");
case -96: return( "A tampa está aberta. Verifique a impressora");
case -97: return( "Ainda não obteve retorno");
case -98: return( "Overflow");
case -99: return( "TimeOut na execucao do comando");
}
}
//--------------------------------------------------------------------------- | [
"noreply@github.com"
] | noreply@github.com |
a76e4111e900d563f7395ba7f027677ae72ce02d | 801f7ed77fb05b1a19df738ad7903c3e3b302692 | /refactoringOptimisation/differentiatedCAD/occt-min-topo-src/src/XCAFDimTolObjects/XCAFDimTolObjects_GeomToleranceModif.hxx | 77985bc50dd7f147164a89619e847a355fbe6935 | [] | no_license | salvAuri/optimisationRefactoring | 9507bdb837cabe10099d9481bb10a7e65331aa9d | e39e19da548cb5b9c0885753fe2e3a306632d2ba | refs/heads/master | 2021-01-20T03:47:54.825311 | 2017-04-27T11:31:24 | 2017-04-27T11:31:24 | 89,588,404 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,775 | hxx | // Created on: 2015-08-06
// Created by: Ilya Novikov
// Copyright (c) 2004-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _XCAFDimTolObjects_GeomToleranceModif_HeaderFile
#define _XCAFDimTolObjects_GeomToleranceModif_HeaderFile
//! Defines modifirs
enum XCAFDimTolObjects_GeomToleranceModif
{
XCAFDimTolObjects_GeomToleranceModif_Any_Cross_Section,
XCAFDimTolObjects_GeomToleranceModif_Common_Zone,
XCAFDimTolObjects_GeomToleranceModif_Each_Radial_Element,
XCAFDimTolObjects_GeomToleranceModif_Free_State,
XCAFDimTolObjects_GeomToleranceModif_Least_Material_Requirement,
XCAFDimTolObjects_GeomToleranceModif_Line_Element,
XCAFDimTolObjects_GeomToleranceModif_Major_Diameter,
XCAFDimTolObjects_GeomToleranceModif_Maximum_Material_Requirement,
XCAFDimTolObjects_GeomToleranceModif_Minor_Diameter,
XCAFDimTolObjects_GeomToleranceModif_Not_Convex,
XCAFDimTolObjects_GeomToleranceModif_Pitch_Diameter,
XCAFDimTolObjects_GeomToleranceModif_Reciprocity_Requirement,
XCAFDimTolObjects_GeomToleranceModif_Separate_Requirement,
XCAFDimTolObjects_GeomToleranceModif_Statistical_Tolerance,
XCAFDimTolObjects_GeomToleranceModif_Tangent_Plane
};
#endif // _XCAFDimTolObjects_GeomToleranceModif_HeaderFile
| [
"salvatore.auriemma@opencascade.com"
] | salvatore.auriemma@opencascade.com |
dc48da9fc8b6bac007b1bd49c31cfbd94d64651b | deb9334fc2e75fd105370e7cdd857d4f7c2caffb | /一本通/03数据结构/04图论基础/0405并查集/1385.cpp | efd83ef7e1ea01cb83bc6a78e7cdefd69fb02c20 | [] | no_license | liwei2088/oi | a641aa06cfeeaeff75673191c4e0bd3f5aae9de3 | 487acf4b1d4f97ab26614f9f396c9ca007c2b507 | refs/heads/master | 2021-06-12T00:00:02.767091 | 2021-03-27T06:21:09 | 2021-03-27T06:21:09 | 149,082,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 965 | cpp | #include <cstdio>
#include <iostream>
using namespace std;
int n, m, p[1005], q[1005];
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) p[i] = i;
while (m--) {
int t, x, y, u, v;
cin >> t >> x >> y;
if (t == 0) {
u = find(x), v = find(y);
if (u != v) p[u] = v;
} else {
//将x的敌人并入到y
if (q[x] == 0)
q[x] = y;
else {
u = find(q[x]), v = find(y);
if (u != v) p[u] = v;
}
//将y的敌人并入到x
if (q[y] == 0)
q[y] = x;
else {
u = find(x), v = find(q[y]);
if (u != v) p[u] = v;
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++)
if (p[i] == i) ans++;
cout << ans;
return 0;
} | [
"liwei2088@sohu.com"
] | liwei2088@sohu.com |
f0acf61977712ee9d9ef86e0c781f9d3caac2f6d | a9f0884bc8a2a117016936d0bdadfd1cd6bc9e28 | /编程练习/BFS与DFS走迷宫.cpp | d4e12bbf946dca267cf4fa744675de765ec1e0c9 | [] | no_license | StillNormal/WeeklyCode | 67f7fb5919d3e297e100ec3c505fa43bed230e4a | 8b1bb6c370ff811d186107a0e1822b974903b142 | refs/heads/master | 2021-04-03T08:25:36.359492 | 2019-12-17T05:28:27 | 2019-12-17T05:28:27 | 124,240,046 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,480 | cpp | #include <iostream>
#include <stack>
#include <queue>
using namespace std;
int maze[5][5] = {//迷宫数组 1为墙 左上到左下(0,0)->(4,4)
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
struct pos {
int x;
int y;
};
void deep_search() {//dfs 不可采用记录后继的方式 因为后继可能有多个 因此也无法判断多条到达终点的路
pos predecessor[5][5];//每个点都可以记录它前驱
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
predecessor[i][j].x = predecessor[i][j].y = 0;
stack<pos> path;//只是栈 存贮的不是解答路径
pos temp = {0,0};
maze[0][0] = -1;//将起点标记已走过然后压栈
path.push(temp);
while(!path.empty()) {
temp = path.top();
path.pop();//出栈
if(temp.x==4 && temp.y==4)//此点是终点
break;
if((temp.x-1)>=0 && maze[temp.x-1][temp.y] == 0) {//上 可走且未走过
maze[temp.x-1][temp.y] = -1;
predecessor[temp.x-1][temp.y] = temp; //记录前驱
pos a = {temp.x-1,temp.y};
path.push(a);
}
if((temp.x+1)<=4 && maze[temp.x+1][temp.y] == 0) {//下
maze[temp.x+1][temp.y] = -1;
predecessor[temp.x+1][temp.y] = temp;
pos a = {temp.x+1,temp.y};
path.push(a);
}
if((temp.y-1)>=0 && maze[temp.x][temp.y-1] == 0) {//左
maze[temp.x][temp.y-1] = -1;
predecessor[temp.x][temp.y-1] = temp;
pos a = {temp.x,temp.y-1};
path.push(a);
}
if((temp.y+1)<=4 && maze[temp.x][temp.y+1] == 0) {//右
maze[temp.x][temp.y+1] = -1;
predecessor[temp.x][temp.y+1] = temp;
pos a = {temp.x,temp.y+1};
path.push(a);
}
}
if(temp.x==4 && temp.y==4) {//依据前驱数组从终点向起点输出
cout << temp.x << "," << temp.y << endl;
while (predecessor[temp.x][temp.y].x!=0 || predecessor[temp.x][temp.y].y!=0) {//仍有前驱时
int x = predecessor[temp.x][temp.y].x;//temp.x = predecessor[temp.x][temp.y].x 这样写会在求temp.y时改变temp.x
temp.y = predecessor[temp.x][temp.y].y;
temp.x = x;
cout << temp.x << "," << temp.y << endl;
}
cout << "0,0" << endl;//补上起点的输出
}
else
cout << "无路可达终点" << endl;
}
void breadth_search() {//广度优先逐层拓展,会把当前所有可能都拓展出来再向下搜索 适合求最优解
pos predecessor[5][5];//每个点都可以记录它前驱
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
predecessor[i][j].x = predecessor[i][j].y = 0;
queue<pos> path;//队列
pos temp = {0,0};
maze[0][0] = -1;//将起点标记已走过然后压栈
path.push(temp);
while(!path.empty()) {
temp = path.front();
path.pop();//出队列
if(temp.x==4 && temp.y==4)//此点是终点
break;
if((temp.x-1)>=0 && maze[temp.x-1][temp.y] == 0) {//上 可走且未走过
maze[temp.x-1][temp.y] = -1;
predecessor[temp.x-1][temp.y] = temp; //记录前驱
pos a = {temp.x-1,temp.y};
path.push(a);
}
if((temp.x+1)<=4 && maze[temp.x+1][temp.y] == 0) {//下
maze[temp.x+1][temp.y] = -1;
predecessor[temp.x+1][temp.y] = temp;
pos a = {temp.x+1,temp.y};
path.push(a);
}
if((temp.y-1)>=0 && maze[temp.x][temp.y-1] == 0) {//左
maze[temp.x][temp.y-1] = -1;
predecessor[temp.x][temp.y-1] = temp;
pos a = {temp.x,temp.y-1};
path.push(a);
}
if((temp.y+1)<=4 && maze[temp.x][temp.y+1] == 0) {//右
maze[temp.x][temp.y+1] = -1;
predecessor[temp.x][temp.y+1] = temp;
pos a = {temp.x,temp.y+1};
path.push(a);
}
}
if(temp.x==4 && temp.y==4) {//依据前驱数组从终点向起点输出
cout << temp.x << "," << temp.y << endl;
while (predecessor[temp.x][temp.y].x!=0 || predecessor[temp.x][temp.y].y!=0) {
int x = predecessor[temp.x][temp.y].x;
temp.y = predecessor[temp.x][temp.y].y;
temp.x = x;
cout << temp.x << "," << temp.y << endl;
}
cout << "0,0" << endl;
}
else
cout << "无路可达终点" << endl;
}
int main() {
//deep_search();
//breadth_search();
system("pause");
}
//首先,bfs是每走一步,就把所有可能的下一步走法存入数组,然后数组指针向后移一位,也就是说bfs是把所有可能的走法全部同时走一遍,
//也就是说在同一时刻,走法的数组里还未判断的位置已经走过的步数是相同的(或者只差1),这样一来,当抵达终点后,那一个算法一定是走的步数最少的
//而dfs是把一条路走到底再换另一条,你可以想象一下,一条很绕的路碰巧走到终点,dfs就判断为计算出来了,当然不是最短 | [
"386811796@qq.com"
] | 386811796@qq.com |
6259bc4ce84a2df00689e14c4640ea598caf5120 | a336409f3a743664dc5e96680a026bd2bf04496b | /cpp/private/strings.cpp | a3fe0c526b5068110ce1a3732107f866c2926072 | [
"MIT"
] | permissive | rlei-weta/gofileseq | 7957f5ec738727ad521ceb9b7d4240cafc8cac9c | 97d877d68cdef5939f4db199f52e4424fe9a691a | refs/heads/master | 2023-04-30T21:49:18.716283 | 2020-12-16T20:58:52 | 2020-12-16T20:58:52 | 365,962,390 | 0 | 0 | MIT | 2021-05-10T08:47:50 | 2021-05-10T07:55:12 | null | UTF-8 | C++ | false | false | 1,363 | cpp |
#include "strings.h"
namespace fileseq {
namespace strings {
bool contains(const std::string &str, const std::string &substr) {
return (str.find(substr) != std::string::npos);
}
void replace_all(std::string &str, const std::string &from, const std::string &to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
}
void trim(std::string &str) {
static const std::string trim_chars(" \t\n\r");
size_t pos;
pos = str.find_last_not_of(trim_chars);
if ( pos != std::string::npos ) {
str.substr(0, pos+1).swap(str);
}
pos = str.find_first_not_of(trim_chars);
if ( pos != std::string::npos ) {
str.substr(pos).swap(str);
}
}
void path_split(std::string &dirname, std::string &basename, const std::string &path) {
size_t found = path.find_last_of("/\\");
if (found == std::string::npos) {
dirname.clear();
basename = path;
return;
}
dirname = path.substr(0, found);
basename = path.substr(found+1);
if ( dirname[dirname.size()-1] != kPathSep ) {
// Preserve the trailing slash
dirname.append(1, kPathSep);
}
}
} // strings
} // fileseq
| [
"justinisrael@gmail.com"
] | justinisrael@gmail.com |
3e8fc538018c599063328f2e6fe8931fec878cb1 | 18736948db3787c07a268dcd8ab64ff5173c2101 | /Classes/Logic/Commander.hpp | 504a687148fe4959fc1d23f22dbea4545217aa61 | [
"MIT"
] | permissive | FaithZL/DontCrash | 5f75beb05830c38c2b3e48bdfc60577025333d23 | fe8d51c6dbdb86f57158aa6f96a2c2c19dfd5f0c | refs/heads/master | 2021-01-10T17:16:33.356750 | 2016-02-04T02:33:42 | 2016-02-04T02:33:42 | 50,807,754 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | hpp | //
// Commander.hpp
// DontCrash
//
// Created by SATAN_Z on 16/1/29.
//
//
#ifndef Commander_hpp
#define Commander_hpp
#include "cocos2d.h"
#include "../utils/FSM/FSM.h"
#include "Scorer.hpp"
class Enemy;
enum GroupState {
g3,
g12,
g111
};
class Commander : public FSM , public cocos2d::Ref{
public:
~Commander();
Commander();
CREATE_FUNC(Commander);
virtual bool init();
virtual void initFSM();
void g3enter();
void g3update(float d);
void g12enter();
void g12update(float d);
void g111enter();
void g111update(float d);
bool isAllTheSame(int from , int to , std::string fieldName...);
virtual void update(float d);
virtual void reset();
inline void resetFSM(){
_delayedStateName = GroupState::g3;
_currentState = nullptr;
_previousState = nullptr;
}
inline void setScorer(Scorer * scorer){
_scorer = scorer;
_enemies = _scorer->getEnemies();
}
inline cocos2d::Vector<Enemy *> * getEnemies(){
return _enemies;
}
inline bool isRandSwitchOn(){
return _randSwitch;
}
void formation();
protected:
float _timer;
bool _bFormated;
bool _randSwitch;
Scorer * _scorer;
cocos2d::Vector<Enemy *> * _enemies;
};
#endif /* Commander_hpp */
| [
"249002031@qq.com"
] | 249002031@qq.com |
ad2eac4d8b19397db5f4ba4e39554edfd23f508a | d9f971681053469d4f0c28e6f25f7e1ac2045107 | /BOJ/Samsung/17825_주사위윷놀이/17825.cpp | dd2bc5b6c0c7a83b2ced694484204e59051c3ca9 | [] | no_license | jinwookss/algorithm-solutions | 7f85f7bc865fe6e6ed2687f9200ed31f4a72fa9c | 66576bdac4a4b092fe7775d17c0602a1c7450f78 | refs/heads/master | 2023-05-12T10:16:46.823225 | 2021-05-31T10:14:46 | 2021-05-31T10:14:46 | 239,338,482 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,063 | cpp | #include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
vector<int> inputs(10);
vector<vector<int>> map;
vector<int> idx = {0, 0, 0, 0};
vector<int> course = {0, 0, 0, 0};
int maxScore = 0;
// vector<int> v;
// vector<int> v2;
void dfs(int diceIdx, int score) {
if (diceIdx == 10) {
maxScore = max(maxScore, score);
// if (score > maxScore) {
// cout << "score = " << score << endl;
// for (int i : v) {
// cout << i << " ";
// }
// cout << endl;
// maxScore = score;
// for (int i : v2) {
// cout << i << " ";
// }
// cout << endl;
// maxScore = score;
// }
return;
}
for (int mal = 0; mal < 4; mal++) {
// 말이 이미 도착한 경우
if (idx[mal] == map[course[mal]].size() - 1) continue;
// 다음 주사위 위치
int before = idx[mal];
if (idx[mal] + inputs[diceIdx] >= map[course[mal]].size()) {
idx[mal] = map[course[mal]].size() - 1;
} else
idx[mal] += inputs[diceIdx];
int shortcut = 0;
if (course[mal] == 0) {
if (map[course[mal]][idx[mal]] == 10) {
course[mal] = 1;
shortcut = 1;
} else if (map[course[mal]][idx[mal]] == 20) {
course[mal] = 2;
shortcut = 2;
} else if (map[course[mal]][idx[mal]] == 30) {
course[mal] = 3;
shortcut = 3;
}
}
// 말 위치 중복 체크
bool isDuplicated = false;
for (int mal2 = 0; mal2 < 4; mal2++) {
if (mal == mal2) continue;
if (course[mal] == course[mal2] && idx[mal] == idx[mal2] && idx[mal] != map[course[mal]].size() - 1) {
isDuplicated = true;
break;
}
if ((map[course[mal]][idx[mal]] == 25 && map[course[mal2]][idx[mal2]] == 25)
|| (map[course[mal]][idx[mal]] == 30 && map[course[mal2]][idx[mal2]] == 30 && map[course[mal]][idx[mal] - 1] == 25 && map[course[mal2]][idx[mal2] - 1] == 25)
|| (map[course[mal]][idx[mal]] == 35 && map[course[mal2]][idx[mal2]] == 35)
|| (map[course[mal]][idx[mal]] == 40 && map[course[mal2]][idx[mal2]] == 40)) {
isDuplicated = true;
break;
}
}
if (isDuplicated) {
idx[mal] = before;
if (shortcut != 0) course[mal] = 0;
continue;
}
// v.push_back(map[course[mal]][idx[mal]]);
// v2.push_back(mal + 1);
dfs(diceIdx + 1, score + map[course[mal]][idx[mal]]);
// v.pop_back();
// v2.pop_back();
idx[mal] = before;
if (shortcut != 0) course[mal] = 0;
}
}
int main() {
ifstream cin("input.txt");
if (cin.fail()) return -1;
for (int i = 0; i < 10; i++) {
cin >> inputs[i];
}
vector<int> v1 = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 0};
vector<int> v2 = {0, 2, 4, 6, 8, 10, 13, 16, 19, 25, 30, 35, 40, 0};
vector<int> v3 = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 25, 30, 35, 40, 0};
vector<int> v4 = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 28, 27, 26, 25, 30, 35, 40, 0};
// 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 0
// 10, 13, 16, 19, 25, 30, 35, 40, 0
// 20, 22, 24, 25, 30, 35, 40, 0
// 30, 28, 27, 26, 25, 30, 35, 40, 0
map.push_back(v1);
map.push_back(v2);
map.push_back(v3);
map.push_back(v4);
dfs(0, 0);
cout << maxScore << endl;
return 0;
} | [
"jjw6215@gmail.com"
] | jjw6215@gmail.com |
3b7b0e9f9094f6e92785abed150186832d7de9c9 | 49292d25823cb9147408df62cda55d38ba1e782a | /test_run_dir/lab8/VExercise1__ALLsup.cpp | 3b1eaad18a45e369598bec8ac07d0a0d22f9abb5 | [] | no_license | Shahzaib2028/chisel-quickstart | 92d2da9a3d3b60fd02cab9579e8a50525a90dd22 | 877a68aee5c034db58288cd4e5a746fea9fe9119 | refs/heads/main | 2023-04-10T01:02:57.255688 | 2021-04-16T09:07:36 | 2021-04-16T09:07:36 | 349,036,502 | 2 | 0 | null | 2021-03-18T10:48:36 | 2021-03-18T10:48:36 | null | UTF-8 | C++ | false | false | 196 | cpp | // DESCRIPTION: Generated by verilator_includer via makefile
#define VL_INCLUDE_OPT include
#include "VExercise1__Trace.cpp"
#include "VExercise1__Syms.cpp"
#include "VExercise1__Trace__Slow.cpp"
| [
"noreply@github.com"
] | noreply@github.com |
5ae65201c9147800d6406e327ce1206219f9526b | 1a08c177538b8718861c4969a57d3b41ab5d2bb0 | /sai2-simulation-master/src/object/CDynJoint.cpp | b2adb023582ff6b83d44b1e202fc7d362936f3a4 | [] | no_license | michaellin/cs327a | 9be6aa4442e04d21f7ad455391114faeafc26171 | 032d447c98f96816b4ddb50b2b7dd3569e475867 | refs/heads/master | 2023-01-12T23:53:33.539482 | 2020-11-16T05:44:01 | 2020-11-16T05:44:01 | 268,144,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,344 | cpp | //===========================================================================
/*
This file is part of the dynamics library.
Copyright (C) 2014, Artificial Intelligence Laboratory,
Stanford University. All rights reserved.
\version $MAJOR.$MINOR.$RELEASE $Rev: 1242 $
*/
//===========================================================================
//---------------------------------------------------------------------------
#include "object/CDynJoint.h"
//---------------------------------------------------------------------------
#include <assert.h>
#include <string.h>
//---------------------------------------------------------------------------
#include "utility/CDynLogger.h"
#include "object/CDynObject.h"
#include "node/CDynJointLimit.h"
#include "node/CDynBaseNode.h"
#include "var/CDynVar.h"
//---------------------------------------------------------------------------
void cDynJoint::insert(cDynJoint** head, cDynJoint** tail)
{
prev_= *tail;
next_= NULL;
if (*head == NULL) *head = this;
if (*tail != NULL) (*tail)->next_=this;
*tail=this;
}
//---------------------------------------------------------------------------
void cDynJoint::remove(cDynJoint** head, cDynJoint** tail)
{
if (*head == this) *head=next_;
if (*tail == this) *tail=prev_;
if (next_ != NULL) next_->prev_=prev_;
if (prev_ != NULL) prev_->next_=next_;
obj_=NULL;
}
//---------------------------------------------------------------------------
cDynJoint::~cDynJoint()
{
assert(obj_ != NULL);
obj_->joint.remove(this);
if (q_ != NULL) delete q_;
if (sq_ != NULL) delete sq_;
if (jcol_ != NULL) delete jcol_;
if (hcol_ != NULL) delete hcol_;
if (jsphere_ != NULL) delete [] jsphere_;
if (tmp3_ != NULL) delete tmp3_;
}
//---------------------------------------------------------------------------
cDynJoint::cDynJoint(cDynObject* obj,cDynJointType type, cDynAxis axis, char* d)
{
assert(type != CDYN_SPHERICAL);
obj_=obj;
type_=type;
axis_=axis;
data(d);
localFrame_.identity();
prev_=NULL;
next_=NULL;
sq_=NULL;
q_ =new cDynJointVar();
bound_[0]=bound_[1]=NULL;
damping_=0.0f;
inertia_=0.0f;
jcol_=new cDynVector6;
hcol_=new cDynVector6;
jsphere_=NULL;
tmp_=0.0f;
tmp3_=NULL;
data_ = NULL;
controlParam_ = NULL;
}
//---------------------------------------------------------------------------
cDynJoint::cDynJoint(cDynObject* obj,cDynJointType type, char* d)
{
assert(type == CDYN_SPHERICAL);
obj_=obj;
type_=type;
//axis_=0;
data(d);
localFrame_.identity();
sq_=new cDynJointSphereVar();
q_ =NULL;
bound_[0]=bound_[1]=NULL;
damping_=0.0f;
inertia_=0.0f;
jcol_=NULL;
hcol_=NULL;
jsphere_=new cDynMatrix3[2];
tmp_=0.0f;
tmp3_=new cDynVector3;
data_ = NULL;
controlParam_ = NULL;
}
//---------------------------------------------------------------------------
cDynStateEntry* cDynJoint::state()
{
return((type_ != CDYN_SPHERICAL)?q_->state():sq_->state());
}
//---------------------------------------------------------------------------
void cDynJoint::state(cDynState* s)
{
if (type_ != CDYN_SPHERICAL)
q_->state(s);
else
sq_->state(s);
}
//---------------------------------------------------------------------------
void cDynJoint::inertia(double Im)
{
inertia_=Im;
}
//---------------------------------------------------------------------------
void cDynJoint::damping(double b)
{
damping_=b;
}
//---------------------------------------------------------------------------
void cDynJoint::position(double q)
{
assert(q_ != NULL);
if (q_->state())
q_->q(q);
else
q_->qCurrent(q);
}
//---------------------------------------------------------------------------
void cDynJoint::velocity(double v)
{
assert(q_ != NULL);
if (q_->state())
q_->v(v);
else
q_->vCurrent(v);
}
//---------------------------------------------------------------------------
void cDynJoint::positionSpherical(cDynQuaternion& q)
{
assert(sq_ != NULL);
if (sq_->state())
sq_->q(q);
else
sq_->qCurrent(q);
}
//---------------------------------------------------------------------------
void cDynJoint::velocitySpherical(cDynVector3& w)
{
assert(sq_ != NULL);
if (sq_->state())
sq_->v(w);
else
sq_->vCurrent(w);
}
//---------------------------------------------------------------------------
void cDynJoint::bound(cDynBoundType type, double value)
{
if (value == CDYN_NOBOUND)
{
unbound(type);
}
else
{
cDynJointLimit* l=bound_[(int)type];
if (l != NULL)
{
l->value(value);
}
else
{
l=bound_[(int)type] = new cDynJointLimit((type == CDYN_LOWER)?-1:1,value,CDYN_MIN_JOINT_ERROR,0.0f,this);
if (object()->baseNode())
{
object()->baseNode()->limit(CDYN_LIMIT_INVALID)->insert(l);
}
}
}
}
//---------------------------------------------------------------------------
void cDynJoint::unbound(const cDynBoundType type)
{
cDynJointLimit* l=bound_[(int)type];
if (l != NULL)
{
int state=l->state();
if (state >= 0)
object()->baseNode()->limit(state)->remove(l);
delete l;
bound_[(int)type]=NULL;
}
}
//---------------------------------------------------------------------------
void cDynJoint::invalid(const cDynBoundType type)
{
cDynJointLimit* l=bound_[(int)type];
assert(l != NULL);
if (l->state() != CDYN_LIMIT_INVALID)
{
if (l->state() >= 0)
object()->baseNode()->limit(l->state())->remove(l);
object()->baseNode()->limit(CDYN_LIMIT_INVALID)->insert(l);
cDynPrintf("Joint %s %c marked as valid\n",data(),(type == CDYN_LOWER)?'<':'>');
}
}
//---------------------------------------------------------------------------
void cDynJoint::error(const cDynBoundType type,const double value)
{
if (bound_[(int)type] != NULL) bound_[(int)type]->error(value);
}
//---------------------------------------------------------------------------
void cDynJoint::epsilon(const cDynBoundType type,const double value)
{
if (bound_[(int)type] != NULL) bound_[(int)type]->epsilon(value);
}
//---------------------------------------------------------------------------
double cDynJoint::bound(cDynBoundType type) const
{
if (bound_[(int)type] == NULL) return(CDYN_NOBOUND);
else return(bound_[(int)type]->value());
}
//---------------------------------------------------------------------------
double cDynJoint::error(cDynBoundType type) const
{
if (bound_[(int)type] == NULL) return(CDYN_NOBOUND);
else return(bound_[(int)type]->error());
}
//---------------------------------------------------------------------------
double cDynJoint::epsilon(const cDynBoundType type) const
{
if (bound_[(int)type] == NULL) return(CDYN_NOBOUND);
else return(bound_[(int)type]->epsilon());
}
//---------------------------------------------------------------------------
void cDynJoint::updateLocalTransformation(const cDynTime *time)
{
switch(type())
{
case CDYN_SPHERICAL:
localFrame_.set(time ? positionSphericalAt(*time) : sq());
break;
case CDYN_PRISMATIC:
// trans_local = transHome + RHome * q
localFrame_.translation(axis()) = time ? positionAt(*time) : q();
break;
case CDYN_REVOLUTE:
#if 1
cDynQuaternion tmpQ;
tmpQ.set(axis(), time ? positionAt(*time) : q());
localFrame_.set(tmpQ);
#else
// R_local = RHome * R_theta
cSetQ4S2(localFrame_.rotation(), axis(), q());
#endif
break;
}
}
//---------------------------------------------------------------------------
| [
"michaelv03@gmail.com"
] | michaelv03@gmail.com |
6d824fca0f02ce4ade5b25d42558092f45094de5 | 29a7bade00baf0153036b91c43c51fba2021219c | /operating systems/assign1/queue.cpp | 11e87a286a39a0868cdb7ccd78f57201b5a2df07 | [] | no_license | Tgriff073/school | 92fc1054bdc3f0fc9ca030efb7e94cfe66723207 | acb0cccb5b5780043dfe43bc4b77d16a73e7ead6 | refs/heads/master | 2021-09-10T02:47:34.442141 | 2018-03-20T19:30:40 | 2018-03-20T19:30:40 | 126,069,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,963 | cpp | /* Queue CPP file
* Jan Ocampo & Thomas Griffin
* CS 433 - Xiaoyu Zhang
* February 13, 2017
*
* This file defines all the method calls for the queue data structure, methods described are
* ctor, push, pop, display, and size
*
*/
#include "queue.h"
#include <iostream>
using namespace std;
//fucntion initializes a queue object, takes no input
//it modifies the front and rear pointer of the queue by setting them equal to null
//it also sets count to 0
Queue::Queue() {
rear = NULL;
front = NULL;
count = 0;
}
//function adds a new process to the queue, the parameter holds the process to be added to the queue
//the function also changes the status of the process to running
//if the queue is empty it the front and rear pointers will point to the process
//otherwise only the rear pointer will point to it
//the count of process in the queue is then incremented by 1
void Queue::push(PCB* temp)
{
temp->next = NULL;
temp->status = "RUNNING";
if (front == NULL)
{
front = rear = temp;
rear->next = NULL;
}
else
{
rear->next = temp;
rear = temp;
rear->next = NULL;
}
count++;
}
//pops the top of the queue off and returns the pid of the process removed
//if the queue is empty it will the function will return 0
//otherwise the output should be anywhere from 1-50
int Queue::pop()
{
int temp = 0;
if (front == NULL)
;
else
{
temp = front->PID;
front = front->next;
}
return temp;
}
//displays the Pid of all the processes in this queue
//the queue is not modified at all in this function
void Queue::display() {
PCB *temp = new PCB;
if (this->count)
{
temp = front;
if (front == NULL);
else {
while (temp != NULL) {
cout << "PID# " << temp->PID << endl;
temp = temp->next;
}
}
}
}
//returns the amount of items in the queue
//the queue is not modified at all in this function
int Queue::size()
{
return count;
}
| [
"griff073@cougars.csusm.edu"
] | griff073@cougars.csusm.edu |
bae33308d260717acf0d874778c66e472339c70d | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /components/storage_monitor/storage_monitor_chromeos.cc | c6f7661627ba0cffadf3d993b0c96070e7e65f24 | [
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 12,220 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/storage_monitor/storage_monitor_chromeos.h"
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/task/task_traits.h"
#include "base/task_runner_util.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "chromeos/disks/disk.h"
#include "components/storage_monitor/media_storage_util.h"
#include "components/storage_monitor/mtp_manager_client_chromeos.h"
#include "components/storage_monitor/removable_device_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/device_service.h"
using chromeos::disks::Disk;
using chromeos::disks::DiskMountManager;
namespace storage_monitor {
namespace {
// Constructs a device id using uuid or manufacturer (vendor and product) id
// details.
std::string MakeDeviceUniqueId(const Disk& disk) {
std::string uuid = disk.fs_uuid();
if (!uuid.empty())
return kFSUniqueIdPrefix + uuid;
// If one of the vendor or product information is missing, its value in the
// string is empty.
// Format: VendorModelSerial:VendorInfo:ModelInfo:SerialInfo
// TODO(kmadhusu) Extract serial information for the disks and append it to
// the device unique id.
const std::string& vendor = disk.vendor_id();
const std::string& product = disk.product_id();
if (vendor.empty() && product.empty())
return std::string();
return kVendorModelSerialPrefix + vendor + ":" + product + ":";
}
// Returns whether the requested device is valid. On success |info| will contain
// device information.
bool GetDeviceInfo(const DiskMountManager::MountPointInfo& mount_info,
bool has_dcim,
StorageInfo* info) {
DCHECK(info);
std::string source_path = mount_info.source_path;
const Disk* disk =
DiskMountManager::GetInstance()->FindDiskBySourcePath(source_path);
if (!disk || disk->device_type() == chromeos::DEVICE_TYPE_UNKNOWN)
return false;
std::string unique_id = MakeDeviceUniqueId(*disk);
if (unique_id.empty())
return false;
StorageInfo::Type type = has_dcim ?
StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM :
StorageInfo::REMOVABLE_MASS_STORAGE_NO_DCIM;
*info = StorageInfo(
StorageInfo::MakeDeviceId(type, unique_id), mount_info.mount_path,
base::UTF8ToUTF16(disk->device_label()),
base::UTF8ToUTF16(disk->vendor_name()),
base::UTF8ToUTF16(disk->product_name()), disk->total_size_in_bytes());
return true;
}
// Returns whether the requested device is valid. On success |info| will contain
// fixed storage device information.
bool GetFixedStorageInfo(const Disk& disk, StorageInfo* info) {
DCHECK(info);
std::string unique_id = MakeDeviceUniqueId(disk);
if (unique_id.empty())
return false;
*info = StorageInfo(
StorageInfo::MakeDeviceId(StorageInfo::FIXED_MASS_STORAGE, unique_id),
disk.mount_path(), base::UTF8ToUTF16(disk.device_label()),
base::UTF8ToUTF16(disk.vendor_name()),
base::UTF8ToUTF16(disk.product_name()), disk.total_size_in_bytes());
return true;
}
} // namespace
StorageMonitorCros::StorageMonitorCros() {}
StorageMonitorCros::~StorageMonitorCros() {
DiskMountManager* manager = DiskMountManager::GetInstance();
if (manager) {
manager->RemoveObserver(this);
}
}
void StorageMonitorCros::Init() {
DCHECK(DiskMountManager::GetInstance());
DiskMountManager::GetInstance()->AddObserver(this);
CheckExistingMountPoints();
// Tests may have already set a MTP manager.
if (!mtp_device_manager_) {
// Set up the connection with mojofied MtpManager.
content::GetDeviceService().BindMtpManager(
mtp_device_manager_.BindNewPipeAndPassReceiver());
}
// |mtp_manager_client_| needs to be initialized for both tests and
// production code, so keep it out of the if condition.
mtp_manager_client_ = std::make_unique<MtpManagerClientChromeOS>(
receiver(), mtp_device_manager_.get());
}
void StorageMonitorCros::CheckExistingMountPoints() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
for (const auto& it : DiskMountManager::GetInstance()->disks()) {
if (it.second->IsStatefulPartition()) {
AddFixedStorageDisk(*it.second);
break;
}
}
scoped_refptr<base::SequencedTaskRunner> blocking_task_runner =
base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(),
base::TaskPriority::BEST_EFFORT});
for (const auto& it : DiskMountManager::GetInstance()->mount_points()) {
base::PostTaskAndReplyWithResult(
blocking_task_runner.get(), FROM_HERE,
base::BindOnce(&MediaStorageUtil::HasDcim,
base::FilePath(it.second.mount_path)),
base::BindOnce(&StorageMonitorCros::AddMountedPath,
weak_ptr_factory_.GetWeakPtr(), it.second));
}
// Note: Relies on scheduled tasks on the |blocking_task_runner| being
// sequential. This block needs to follow the for loop, so that the DoNothing
// call on the |blocking_task_runner| happens after the scheduled metadata
// retrievals, meaning that the reply callback will then happen after all the
// AddMountedPath calls.
blocking_task_runner->PostTaskAndReply(
FROM_HERE, base::DoNothing(),
base::BindOnce(&StorageMonitorCros::MarkInitialized,
weak_ptr_factory_.GetWeakPtr()));
}
void StorageMonitorCros::OnBootDeviceDiskEvent(
DiskMountManager::DiskEvent event,
const Disk& disk) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!disk.IsStatefulPartition())
return;
switch (event) {
case DiskMountManager::DiskEvent::DISK_ADDED: {
AddFixedStorageDisk(disk);
break;
}
case DiskMountManager::DiskEvent::DISK_REMOVED: {
RemoveFixedStorageDisk(disk);
break;
}
case DiskMountManager::DiskEvent::DISK_CHANGED: {
// Although boot disks never change, this event is fired when the device
// is woken from suspend and re-enumerates the set of disks. The event
// could be changed to only fire when an actual change occurs, but that's
// not currently possible because the "re-enumerate on wake" behaviour is
// relied on to re-mount external media that was unmounted when the system
// was suspended.
break;
}
}
}
void StorageMonitorCros::OnMountEvent(
DiskMountManager::MountEvent event,
chromeos::MountError error_code,
const DiskMountManager::MountPointInfo& mount_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Ignore mount points that are not devices.
if (mount_info.mount_type != chromeos::MOUNT_TYPE_DEVICE)
return;
// Ignore errors.
if (error_code != chromeos::MOUNT_ERROR_NONE)
return;
if (mount_info.mount_condition != chromeos::disks::MOUNT_CONDITION_NONE)
return;
switch (event) {
case DiskMountManager::MOUNTING: {
if (base::Contains(mount_map_, mount_info.mount_path)) {
return;
}
base::PostTaskAndReplyWithResult(
FROM_HERE,
{base::ThreadPool(), base::MayBlock(),
base::TaskPriority::BEST_EFFORT},
base::BindOnce(&MediaStorageUtil::HasDcim,
base::FilePath(mount_info.mount_path)),
base::BindOnce(&StorageMonitorCros::AddMountedPath,
weak_ptr_factory_.GetWeakPtr(), mount_info));
break;
}
case DiskMountManager::UNMOUNTING: {
MountMap::iterator it = mount_map_.find(mount_info.mount_path);
if (it == mount_map_.end())
return;
receiver()->ProcessDetach(it->second.device_id());
mount_map_.erase(it);
break;
}
}
}
void StorageMonitorCros::SetMediaTransferProtocolManagerForTest(
mojo::PendingRemote<device::mojom::MtpManager> test_manager) {
DCHECK(!mtp_device_manager_);
mtp_device_manager_.Bind(std::move(test_manager));
}
bool StorageMonitorCros::GetStorageInfoForPath(
const base::FilePath& path,
StorageInfo* device_info) const {
DCHECK(device_info);
if (mtp_manager_client_->GetStorageInfoForPath(path, device_info)) {
return true;
}
if (!path.IsAbsolute())
return false;
base::FilePath current = path;
while (!base::Contains(mount_map_, current.value()) &&
current != current.DirName()) {
current = current.DirName();
}
MountMap::const_iterator info_it = mount_map_.find(current.value());
if (info_it == mount_map_.end())
return false;
*device_info = info_it->second;
return true;
}
// Callback executed when the unmount call is run by DiskMountManager.
// Forwards result to |EjectDevice| caller.
void NotifyUnmountResult(
base::OnceCallback<void(StorageMonitor::EjectStatus)> callback,
chromeos::MountError error_code) {
if (error_code == chromeos::MOUNT_ERROR_NONE)
std::move(callback).Run(StorageMonitor::EJECT_OK);
else
std::move(callback).Run(StorageMonitor::EJECT_FAILURE);
}
void StorageMonitorCros::EjectDevice(
const std::string& device_id,
base::OnceCallback<void(EjectStatus)> callback) {
StorageInfo::Type type;
if (!StorageInfo::CrackDeviceId(device_id, &type, NULL)) {
std::move(callback).Run(EJECT_FAILURE);
return;
}
if (type == StorageInfo::MTP_OR_PTP) {
mtp_manager_client_->EjectDevice(device_id, std::move(callback));
return;
}
std::string mount_path;
for (MountMap::const_iterator info_it = mount_map_.begin();
info_it != mount_map_.end(); ++info_it) {
if (info_it->second.device_id() == device_id)
mount_path = info_it->first;
}
if (mount_path.empty()) {
std::move(callback).Run(EJECT_NO_SUCH_DEVICE);
return;
}
DiskMountManager* manager = DiskMountManager::GetInstance();
if (!manager) {
std::move(callback).Run(EJECT_FAILURE);
return;
}
manager->UnmountPath(
mount_path, base::BindOnce(NotifyUnmountResult, std::move(callback)));
}
device::mojom::MtpManager*
StorageMonitorCros::media_transfer_protocol_manager() {
return mtp_device_manager_.get();
}
void StorageMonitorCros::AddMountedPath(
const DiskMountManager::MountPointInfo& mount_info,
bool has_dcim) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (base::Contains(mount_map_, mount_info.mount_path)) {
// CheckExistingMountPoints() added the mount point information in the map
// before the device attached handler is called. Therefore, an entry for
// the device already exists in the map.
return;
}
// Get the media device uuid and label if exists.
StorageInfo info;
if (!GetDeviceInfo(mount_info, has_dcim, &info))
return;
if (info.device_id().empty())
return;
mount_map_.insert(std::make_pair(mount_info.mount_path, info));
receiver()->ProcessAttach(info);
}
void StorageMonitorCros::AddFixedStorageDisk(const Disk& disk) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(disk.IsStatefulPartition());
StorageInfo info;
if (!GetFixedStorageInfo(disk, &info))
return;
if (base::Contains(mount_map_, disk.mount_path()))
return;
mount_map_.insert(std::make_pair(disk.mount_path(), info));
receiver()->ProcessAttach(info);
}
void StorageMonitorCros::RemoveFixedStorageDisk(const Disk& disk) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(disk.IsStatefulPartition());
StorageInfo info;
if (!GetFixedStorageInfo(disk, &info))
return;
size_t erased_count = mount_map_.erase(disk.mount_path());
if (!erased_count)
return;
receiver()->ProcessDetach((info.device_id()));
}
StorageMonitor* StorageMonitor::CreateInternal() {
return new StorageMonitorCros();
}
} // namespace storage_monitor
| [
"pcding@ucdavis.edu"
] | pcding@ucdavis.edu |
e03327db42211014dbfac95380585a8d600aac7e | 7e48d392300fbc123396c6a517dfe8ed1ea7179f | /RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/PhysicalMaterialMask.generated.h | 5bba73616aed3574522e69e6620a25eab6f5315e | [] | no_license | WestRyanK/Rodent-VR | f4920071b716df6a006b15c132bc72d3b0cba002 | 2033946f197a07b8c851b9a5075f0cb276033af6 | refs/heads/master | 2021-06-14T18:33:22.141793 | 2020-10-27T03:25:33 | 2020-10-27T03:25:33 | 154,956,842 | 1 | 1 | null | 2018-11-29T09:56:21 | 2018-10-27T11:23:11 | C++ | UTF-8 | C++ | false | false | 5,267 | h | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef ENGINE_PhysicalMaterialMask_generated_h
#error "PhysicalMaterialMask.generated.h already included, missing '#pragma once' in PhysicalMaterialMask.h"
#endif
#define ENGINE_PhysicalMaterialMask_generated_h
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_SPARSE_DATA
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_RPC_WRAPPERS
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_RPC_WRAPPERS_NO_PURE_DECLS
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUPhysicalMaterialMask(); \
friend struct Z_Construct_UClass_UPhysicalMaterialMask_Statics; \
public: \
DECLARE_CLASS(UPhysicalMaterialMask, UObject, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/Engine"), NO_API) \
DECLARE_SERIALIZER(UPhysicalMaterialMask)
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_INCLASS \
private: \
static void StaticRegisterNativesUPhysicalMaterialMask(); \
friend struct Z_Construct_UClass_UPhysicalMaterialMask_Statics; \
public: \
DECLARE_CLASS(UPhysicalMaterialMask, UObject, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/Engine"), NO_API) \
DECLARE_SERIALIZER(UPhysicalMaterialMask)
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UPhysicalMaterialMask(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UPhysicalMaterialMask) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UPhysicalMaterialMask); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UPhysicalMaterialMask); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UPhysicalMaterialMask(UPhysicalMaterialMask&&); \
NO_API UPhysicalMaterialMask(const UPhysicalMaterialMask&); \
public:
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UPhysicalMaterialMask(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UPhysicalMaterialMask(UPhysicalMaterialMask&&); \
NO_API UPhysicalMaterialMask(const UPhysicalMaterialMask&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UPhysicalMaterialMask); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UPhysicalMaterialMask); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UPhysicalMaterialMask)
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_PRIVATE_PROPERTY_OFFSET
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_22_PROLOG
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_PRIVATE_PROPERTY_OFFSET \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_SPARSE_DATA \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_RPC_WRAPPERS \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_INCLASS \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_PRIVATE_PROPERTY_OFFSET \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_SPARSE_DATA \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_RPC_WRAPPERS_NO_PURE_DECLS \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_INCLASS_NO_PURE_DECLS \
Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h_25_ENHANCED_CONSTRUCTORS \
static_assert(false, "Unknown access specifier for GENERATED_BODY() macro in class PhysicalMaterialMask."); \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> ENGINE_API UClass* StaticClass<class UPhysicalMaterialMask>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Engine_Source_Runtime_Engine_Classes_PhysicalMaterials_PhysicalMaterialMask_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"west.ryan.k@gmail.com"
] | west.ryan.k@gmail.com |
2ed5debed306e59026eeb38780d9555dea4e264c | 8d0ad4f1fa55790317d03649bcb17cbabcc80a76 | /src/robot_preview.h | 7ee9a379b7b6aa083189216c27016b4007b05a97 | [
"BSD-3-Clause"
] | permissive | rhololkeolke/robot_editor | 234e455ebd63ab46a6efed2cb857a2238b095be8 | 0621b61e83ea66c47b96d16c52ad5bacc84e37a1 | refs/heads/master | 2016-09-02T01:44:43.075208 | 2014-05-17T21:25:44 | 2014-05-17T21:25:44 | 19,705,595 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 509 | h | #ifndef ROBOT_EDITOR_ROBOT_PREVIEW_H_
#define ROBOT_EDITOR_ROBOT_PREVIEW_H_
#include <QWidget>
namespace rviz
{
class Display;
class RenderPanel;
class VisualizationManager;
}
class RobotPreview: public QWidget
{
Q_OBJECT
public:
RobotPreview(QWidget* parent=0);
virtual ~RobotPreview();
void refresh(const std::string& fixed_frame = "/map");
private:
rviz::VisualizationManager* manager_;
rviz::RenderPanel* render_panel_;
rviz::Display* grid_;
rviz::Display* robot_model_ = NULL;
};
#endif
| [
"digidevin@gmail.com"
] | digidevin@gmail.com |
73b471f2c78cce1e7cc5239b823eaf851a829e39 | 8c9568133d07c324a4e464efe362c240d9000388 | /Single Number II.cpp | a96e03db00fdddbeea8bbcd161207070f76f3565 | [] | no_license | Vikalp19041999/LeetCode-solutions | bc3f443243ca19d389b92331dfc83d5304282bc7 | fc07ea77e929ca35c68312e36c9543705cdad002 | refs/heads/main | 2023-08-15T13:58:18.829183 | 2021-09-20T15:56:51 | 2021-09-20T15:56:51 | 371,249,286 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 243 | cpp | class Solution {
public:
int singleNumber(vector<int>& nums) {
int one = 0;
int two = 0;
for(int i : nums) {
one = (one^i) & ~two;
two = (two^i) & ~one;
}
return one;
}
}; | [
"vicks548@gmail.com"
] | vicks548@gmail.com |
f50aa5a1cf1e7bb3b8de7dae3f5e84e825c29eda | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Trigger/TrigConfiguration/TrigConfL1Data/Root/TriggerItemNode.cxx | bb4bdf8fae1ddd6a0729a7d9113f39347b9df9a5 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,794 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "TrigConfL1Data/TriggerItemNode.h"
#include "TrigConfL1Data/TriggerThreshold.h"
#include <iomanip>
#include <iostream>
#include <string>
#include <cstdlib>
#include <inttypes.h>
#include <stdexcept>
#include <sys/types.h>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace TrigConf;
TrigConf::TriggerItemNode::TriggerItemNode(NodeType type) :
m_NodeType(type),
m_ThresholdName(""),
m_Position(0),
m_Multiplicity(0),
m_Threshold(0),
m_InternalTrigger(InternalType_t(L1DataDef::UNDEF,0))
{}
TrigConf::TriggerItemNode::~TriggerItemNode() {
for(TriggerItemNode * node : m_Children)
delete node;
}
TrigConf::TriggerItemNode::NodeType
TrigConf::TriggerItemNode::typeFromString(const std::string& type) {
if(type=="AND") return TriggerItemNode::AND;
if(type=="OR") return TriggerItemNode::OR;
if(type=="NOT") return TriggerItemNode::NOT;
if(type=="OBJ") return TriggerItemNode::OBJ;
if(type=="TriggerCondition") return TriggerItemNode::OBJ;
if(type=="InternalTrigger") return TriggerItemNode::OBJ;
return TriggerItemNode::UNDEF;
}
TriggerItemNode::NodeType
TriggerItemNode::typeFromChar(const char& c) {
if(c=='&') return TriggerItemNode::AND;
if(c=='|') return TriggerItemNode::OR;
if(c=='!') return TriggerItemNode::NOT;
return TriggerItemNode::UNDEF;
}
std::string
TrigConf::TriggerItemNode::typeAsString(NodeType type) {
static std::string typelabel[] = {"OBJ", "NOT", "AND", "OR", "UNDEF"};
return typelabel[type];
}
bool
TrigConf::TriggerItemNode::isThreshold() const {
return m_InternalTrigger.first == L1DataDef::UNDEF;
}
bool
TrigConf::TriggerItemNode::isInternalTrigger() const {
return m_InternalTrigger.first != L1DataDef::UNDEF;
}
void
TrigConf::TriggerItemNode::setTriggerThreshold(TriggerThreshold* thr ) {
if(thr->isInternal()) {
// from the database internal triggers are also loaded as TriggerThresholds
setInternalTrigger(thr->name());
} else {
m_InternalTrigger.first = L1DataDef::UNDEF;
m_InternalTrigger.second = 0;
}
m_Threshold = thr;
m_ThresholdName = thr->name();
}
void
TrigConf::TriggerItemNode::setInternalTrigger(L1DataDef::TriggerType x,
unsigned int thresholdNumber) {
m_InternalTrigger.first = x;
m_InternalTrigger.second = thresholdNumber;
m_ThresholdName = L1DataDef::typeConfig(x).name + boost::lexical_cast<string,unsigned int>(thresholdNumber);
m_Threshold = 0;
}
void
TrigConf::TriggerItemNode::setInternalTrigger(const string& name) {
string::size_type pos = name.find_first_of("0123456789");
L1DataDef::TriggerType tt = L1DataDef::stringAsType(name.substr(0,pos));
if( ! L1DataDef::typeConfig(tt).internal ) {
cerr << "TriggerItemNode::setInternalTrigger: type " << name << " is not an internal trigger" << endl;
throw runtime_error("TriggerItemNode::setInternalTrigger: type is not an internal trigger");
}
m_InternalTrigger.first = tt;
m_InternalTrigger.second = boost::lexical_cast<unsigned int,string>(name.substr(pos));
m_ThresholdName = name;
m_Threshold = 0;
}
void
TrigConf::TriggerItemNode::addChild(TriggerItemNode* node) {
if(type() == OBJ)
throw std::runtime_error("TriggerItemNode::addChild: trying to add child to leaf node");
m_Children.push_back(node);
}
void
TrigConf::TriggerItemNode::getAllFinalNodes(std::vector<const TriggerItemNode*>& vec) const {
if(type() == OBJ) {
vec.push_back(this);
} else {
for(TriggerItemNode * node : m_Children)
node->getAllFinalNodes(vec);
}
}
void
TrigConf::TriggerItemNode::getAllThresholds(std::vector<TriggerThreshold*>& vec) const {
if(type() == OBJ) {
if(!isInternalTrigger()) {
if(m_Threshold) vec.push_back(m_Threshold);
}
} else {
for(TriggerItemNode * node : m_Children)
node->getAllThresholds(vec);
}
}
// returns a bit-pattern for the bunchgroups
void
TrigConf::TriggerItemNode::getAllBunchGroups(std::vector<bool>& vec) const {
unsigned int max_bgrp = L1DataDef::typeConfig(L1DataDef::BGRP).max;
if(vec.size() < max_bgrp) vec.resize( max_bgrp );
if(type() == OBJ) {
if(internalTriggerType() == L1DataDef::BGRP)
vec[m_InternalTrigger.second] = true;
} else {
for(TriggerItemNode * node : m_Children)
node->getAllBunchGroups(vec);
}
}
// returns a bit-pattern for the just as the previous one but as uint16
void
TrigConf::TriggerItemNode::getBunchGroupsMask(uint16_t & bgmask) const {
if(type() == OBJ) {
if(internalTriggerType() == L1DataDef::BGRP) {
uint16_t mask(0x1);
bgmask |= (mask << m_InternalTrigger.second);
}
} else {
for(TriggerItemNode * node : m_Children)
node->getBunchGroupsMask(bgmask);
}
}
void
TrigConf::TriggerItemNode::getAllBunchGroups(std::vector<unsigned int>& vec) const {
if(type() == OBJ) {
if(internalTriggerType() == L1DataDef::BGRP)
vec.push_back(m_InternalTrigger.second);
} else {
for(TriggerItemNode * node : m_Children)
node->getAllBunchGroups(vec);
}
}
void
TrigConf::TriggerItemNode::getAllRandomTriggers(std::vector<unsigned int>& vec) const {
if(type() == OBJ) {
if(internalTriggerType() == L1DataDef::RNDM)
vec.push_back(m_InternalTrigger.second);
} else {
for(TriggerItemNode * node : m_Children)
node->getAllRandomTriggers(vec);
}
}
void
TrigConf::TriggerItemNode::getAllPrescaledClockTriggers(std::vector<unsigned int>& vec) const {
if(type() == OBJ) {
if(internalTriggerType() == L1DataDef::PCLK)
vec.push_back(m_InternalTrigger.second);
} else {
for(TriggerItemNode * node : m_Children)
node->getAllPrescaledClockTriggers(vec);
}
return;
}
void
TrigConf::TriggerItemNode::writeXML(std::ostream & xmlfile, int indentLevel, int indentWidth, bool /*omitDelimiter*/) const {
if (m_NodeType == OBJ) {
if(isInternalTrigger()) {
indent(xmlfile, indentLevel, indentWidth)
<< "<InternalTrigger name=\"" << m_ThresholdName << "\"/>" << endl;
} else {
indent(xmlfile, indentLevel, indentWidth)
<< "<TriggerCondition multi=\"" << m_Multiplicity
<< "\" name=\"" << m_ThresholdName << "_x" << m_Multiplicity
<< "\" triggerthreshold=\"" << m_ThresholdName << "\"/>" << endl;
}
} else if (m_NodeType == AND || m_NodeType == OR) {
std::string logic = (m_NodeType==AND?"AND":"OR");
indent(xmlfile, indentLevel, indentWidth) << "<" << logic << ">" << endl;
for(TriggerItemNode *node : children())
node->writeXML(xmlfile, indentLevel+1, indentWidth);
indent(xmlfile, indentLevel, indentWidth) << "</"<<logic<<">" << endl;
} else if (m_NodeType == NOT) {
indent(xmlfile, indentLevel, indentWidth) << "<NOT>" << endl;
children()[0]->writeXML(xmlfile, indentLevel+1, indentWidth);
indent(xmlfile, indentLevel, indentWidth) << "</NOT>" << endl;
}
}
void
TrigConf::TriggerItemNode::buildLogic(std::vector<std::string> & conditionList,
std::string & logic) const {
if (m_NodeType == OBJ) {
std::string condition("");
if (m_Threshold) {
if( m_Threshold->type() != L1DataDef::rndmType() &&
m_Threshold->type() != L1DataDef::pclkType() &&
m_Threshold->type() != L1DataDef::bgrpType()) {
std::string name = m_Threshold->name();
name += "_x" + std::to_string(m_Multiplicity);
condition += '0' + m_Multiplicity;
condition += "," + name;
condition += "," + m_Threshold->name();
} else {
condition = m_Threshold->name();
}
} else {
condition = thresholdName();
}
uint32_t pos = conditionList.size()+1;
if(pos>9) logic += '0'+pos/10;
logic += '0'+pos%10;
conditionList.push_back(condition);
} else if (m_NodeType == AND || m_NodeType == OR) {
logic += "(";
bool first = true;
for(TriggerItemNode *node : children()) {
if(!first) { logic += (m_NodeType==AND?"&":"|"); } else { first=false; }
node->buildLogic(conditionList, logic);
}
logic += ")";
} else if (m_NodeType == NOT) {
logic += "!";
children()[0]->buildLogic(conditionList, logic);
}
}
void
TrigConf::TriggerItemNode::print(const std::string& indent, unsigned int detail) const {
cout << indent << "TriggerItemNode: " << endl;
cout << indent << " type : " << (type()==OBJ?"OBJ":(type()==AND?"AND":(type()==OR?"OR":"NOT"))) << endl;
cout << indent << " position : " << m_Position << endl;
if (m_NodeType == OBJ) {
cout << indent << " multiplicity: " << m_Multiplicity << endl;
if (m_Threshold) {
cout << indent << " threshold : " << m_Threshold->name() << endl;
m_Threshold->print(indent + indent, detail);
} else if(isInternalTrigger()) {
cout << indent << " InternalTrigger: "
<< thresholdName() << endl;
} else {
cout << indent << thresholdName() << endl;
}
}
else {
for(TriggerItemNode * node : m_Children) {
cout << indent << " subnode : " << endl;
node->print(indent + indent);
}
}
}
std::ostream& TrigConf::TriggerItemNode::indent(std::ostream& o, int lvl, int size) const {
if(lvl*size==0) return o;
o << std::setw(lvl*size) << " ";
return o;
}
std::ostream &
TrigConf::operator<<(std::ostream & o, const TrigConf::TriggerItemNode & node) {
o << " TriggerItemNode: " << endl;
o << " type : " << (node.type()==TriggerItemNode::OBJ? "OBJ" : (node.type()==TriggerItemNode::AND?"AND":(node.type()==TriggerItemNode::OR?"OR":"NOT"))) << endl;
o << " position : " << node.position() << endl;
if (node.type() == TriggerItemNode::OBJ) {
o << " multiplicity: " << node.multiplicity() << endl;
if ( node.triggerThreshold() ) {
o << " threshold : " << node.thresholdName() << endl
<< node.triggerThreshold();
} else if( node.isInternalTrigger() ) {
o << " InternalTrigger: " << node.thresholdName() << endl;
} else {
o << node.thresholdName() << endl;
}
}
else {
for(TriggerItemNode* subnode: node.children()) {
o << " subnodes : " << *subnode << endl;
}
}
return o;
}
string
TriggerItemNode::__str__() const {
stringstream s;
s << *this;
return s.str();
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
41767e6148354b0c5094bf284ce448e92677c953 | bc3ba9aab0f483c94f310d976683abb83709a4f1 | /particles/ParticleSystemSnapShot.cpp | faa6b7d557b05c7decd6eeb70cec27f1a77b3f6c | [] | no_license | mkkellogg/Core | 283c83bb7b408e0edb0773d86ca167b5ab994b5e | a3de603df9b80ed90d7a603bd5536f9273fd55e9 | refs/heads/master | 2023-08-08T03:08:14.992663 | 2023-07-31T04:02:28 | 2023-07-31T04:02:28 | 134,364,838 | 3 | 3 | null | 2020-06-11T01:21:41 | 2018-05-22T05:28:43 | C++ | UTF-8 | C++ | false | false | 567 | cpp | #include "ParticleSystemSnapShot.h"
#include "../common/Exception.h"
namespace Core {
ParticleSystemSnapShot::ParticleSystemSnapShot() {}
void ParticleSystemSnapShot::addState(const ParticleState& state) {
this->particleStates.push_back(state);
}
const ParticleState& ParticleSystemSnapShot::getState(UInt32 index) const {
if (index >= this->particleStates.size()) {
throw OutOfRangeException("ParticleSystemSnapShot::getState -> 'index' is out of range.");
}
return this->particleStates[index];
}
} | [
"mkkellogg@gmail.com"
] | mkkellogg@gmail.com |
ee3c3c0d5ef66da57a8932c7dc16c793874926fe | 23f5c0d9c2094f75e19792c20c5bb3a67021c5db | /My_Mine/main.cpp | 0eb695bbafe845a825a90e847bf561e3c969bbbf | [] | no_license | qiuzhiqian/QT_Mine | 781210ac2fc7552493fcbab380b2772cbaa06aa2 | b6adda1c6bda68a61e8c79bd3f585f3f3ddadf8d | refs/heads/master | 2021-01-18T11:33:30.260109 | 2016-05-17T00:18:39 | 2016-05-17T00:18:39 | 58,976,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 160 | cpp | #include "myui.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyUI w;
w.show();
return a.exec();
}
| [
"xia_mengliang@163.com"
] | xia_mengliang@163.com |
d9e0a095e48ccc5493169854c7b86e7053da42f3 | e5122c6ef178cdd293fb4c68d9cdcc6fea96515d | /Classic/graphs/Dijkstry.cpp | 261d2f75afb4f4c2e7016cc6d74b0cd0686409e4 | [] | no_license | Dawidsoni/programming-competitions | 227b466c9cf9f90ede1d42b6abde8972ee6b2860 | 8314250d9777e57e3bdb2de9cdfad0d91975b265 | refs/heads/master | 2021-01-16T20:42:13.748820 | 2018-02-16T14:17:34 | 2018-02-16T14:17:34 | 62,567,916 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,482 | cpp | #include<iostream>
#include<vector>
#include<climits>
#include<queue>
using namespace std;
int result[10000000], startV, eCount, a, b, c, vCount;
bool isCounted[10000000];
typedef pair<int,int> IPair;
vector<vector<IPair> > graph;
priority_queue<IPair, vector<IPair>, greater<IPair> > minQueue;
int main() {
graph.resize(10000000);
cin >> vCount >> eCount;
for(int i=0; i < eCount; i++) {
cin >> a >> b >> c;
graph[a].push_back(IPair(c, b));
}
cin >> startV;
for(int i=1; i <= vCount; i++) {
result[i] = INT_MAX;
}
result[startV] = 0;
minQueue.push(IPair(0, startV));
while(!minQueue.empty()) {
while(true) {
if(minQueue.empty()) break;
if(isCounted[minQueue.top().second] == false)
break;
else {
minQueue.pop();
}
}
if(minQueue.empty()) break;
int num = minQueue.top().second;
isCounted[num] = true;
for(int i = 0; i < (int)graph[num].size(); i++) {
if(result[graph[num][i].second] > result[num] + graph[num][i].first) {
result[graph[num][i].second] = result[num] + graph[num][i].first;
minQueue.push(IPair(result[graph[num][i].first], graph[num][i].second));
}
}
minQueue.pop();
}
for(int i=1;i<vCount;i++)
cout << result[i] << " ";
return 0;
}
| [
"dawid.wegner@gmail.com"
] | dawid.wegner@gmail.com |
a5d608f77b72fbf3e94f7b93d41947944fe4465a | 4ef69f0044f45be4fbce54f7b7c0319e4c5ec53d | /include/cv/core/cmd/out/sgerq2.inl | d61f4e6412ad9dd41a0af54e4406d986a7ed3d2c | [] | no_license | 15831944/cstd | c6c3996103953ceda7c06625ee1045127bf79ee8 | 53b7e5ba73cbdc9b5bbc61094a09bf3d5957f373 | refs/heads/master | 2021-09-15T13:44:37.937208 | 2018-06-02T10:14:16 | 2018-06-02T10:14:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 79 | inl | #ifndef __sgerq2__
#define __sgerq2__
#include "sgerq2.c"
#endif // __sgerq2__
| [
"31720406@qq.com"
] | 31720406@qq.com |
13bb3ec288ae37b88dd51f01453bfd982d5c03a4 | ec230c77637a779e58e11c57f60f29c29740eb07 | /CSE335_inclass_TemplateMethodPattern/Student.h | 6b119416d746ad338f7f348df18e7e58e2c0fc53 | [] | no_license | MikeMei/CSE335 | 951ede53fdbbeb2bb54f8d66ee1249e201827803 | 431719494ca6fba3bf773ceabd2c2450b9894d78 | refs/heads/master | 2021-01-19T08:50:41.419499 | 2016-04-25T03:03:55 | 2016-04-25T03:03:55 | 50,695,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,739 | h | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Student.h
* Author: laptop-pc
*
* Created on February 4, 2016, 1:08 PM
*/
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
class Student{
protected:
string m_FirstName;
string m_LastName;
unsigned short m_BirthYear;
float m_Weight;
float m_GPA;
public:
Student(const string& firstName, const string& lastName, const unsigned short& birthYear,
const float& weight, const float& gpa) {
m_FirstName = firstName;
m_LastName = lastName;
m_BirthYear = birthYear;
m_Weight = weight;
m_GPA = gpa;
}
string getFirstName() const {
return m_FirstName;
}
string getLastName() const {
return m_LastName;
}
unsigned short getBirthYear() const {
return m_BirthYear;
}
float getWeight() const {
return m_Weight;
}
float getGPA() const {
return m_GPA;
}
void setFirstName(string firstName) {
m_FirstName = firstName;
}
void setLastName(string lastName) {
m_LastName = lastName;
}
void setBirthYear(unsigned short birthYear) {
m_BirthYear = birthYear;
}
void setWeight(float weight) {
m_Weight = weight;
}
void setGPA(float gpa) {
m_GPA = gpa;
}
void print() {
cout<<m_FirstName<<" "<<m_LastName<<"; "<<m_BirthYear<<" ;"<<
m_Weight<<"; "<<m_GPA<<endl;
}
};
#endif /* STUDENT_H */
| [
"mhmei95@gmail.com"
] | mhmei95@gmail.com |
30adad3a38c67e1263d0e9484f8b83d52b5ef2aa | fd85020456c57bc2f911e110df56655bec97bbb4 | /teachermaindialog.h | f4090f2275d919bd887337144f9cc2a5af426596 | [] | no_license | MrVozhde/MyLastVersion | 2896916ef75747427da96225eed6d5776444833c | 3a98c82438dccf9049633c91f23f56873f2c97bf | refs/heads/master | 2020-05-24T21:02:29.313566 | 2019-05-19T11:30:39 | 2019-05-19T11:30:39 | 187,467,860 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 489 | h | #ifndef TEACHERMAINDIALOG_H
#define TEACHERMAINDIALOG_H
#include <QDialog>
#include <teacherchangepassword.h>
namespace Ui {
class TeacherMainDialog;
}
class TeacherMainDialog : public QDialog
{
Q_OBJECT
public:
explicit TeacherMainDialog(QWidget *parent = nullptr);
~TeacherMainDialog();
private slots:
void on_pushButton_setting_clicked();
private:
Ui::TeacherMainDialog *ui;
TeacherChangePassword *teacherChangePassword ;
};
#endif // TEACHERMAINDIALOG_H
| [
"mhhz2013@gmail.com"
] | mhhz2013@gmail.com |
6cde08495c8bdbd676b33c2c47c8a3c01d11351c | 626f70480edda21388c09dec57fe24cac75e562e | /Hackerrank/101 Hack 47 B.cpp | 92eceec668ef5d08ba5894586f252d0d234ce81f | [] | no_license | arf111/Programming-Problems- | 48871be8c919016eafb0e82a4ca22bb65f0b6f14 | 088d2fe3b646a57b0f622406a60a24d02c690025 | refs/heads/master | 2020-09-09T21:35:57.762346 | 2018-01-22T05:13:26 | 2018-01-22T05:13:26 | 94,446,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 854 | cpp | #include <bits/stdc++.h>
using namespace std;
int flag[5000];
int main()
{
int n,p,q;
scanf("%d %d %d",&n,&p,&q);
vector<int> a(p);
for(int a_i = 0; a_i < p; a_i++)
{
cin >> a[a_i];
}
vector<int> b(q);
for(int b_i = 0; b_i < q; b_i++)
{
cin >> b[b_i];
}
int sop = 1;
for(int i=0; i<p; i++)
{
for(int j=0; j<q; j++)
{
int rem = (a[i] + b[j] ) / n;
rem += 1;
int divid = rem * n;
int dnttake = divid -( a[i] + b[j] );
flag[dnttake] = 1;
}
}
while(1)
{
if(flag[sop])
{
sop++;
}
else
{
break;
}
}
printf("%d\n",sop);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
6306d0fcba4ca66ce53b319948999389f7506c4d | e2f27c57a3a7a6be57f8db5112106d38b61a3f1e | /SpaceInvaders/Models/ECS/UColliderComponent.h | ff1e53245f7df64ff9761388e626ef490c2283f6 | [] | no_license | stefan-0905/SpaceInvaders | cd5b29794f0224ed418005351e88464fb5b39252 | b90db35dc0e02051c83eaa79eb60486b8428e1d6 | refs/heads/master | 2023-01-01T02:52:43.679584 | 2020-10-27T18:02:19 | 2020-10-27T18:02:19 | 278,060,659 | 0 | 0 | null | 2020-10-27T10:29:48 | 2020-07-08T10:33:53 | C++ | UTF-8 | C++ | false | false | 414 | h | #pragma once
#include "ECS.h"
#include <SFML\Graphics\Rect.hpp>
class UPositionComponent;
class UColliderComponent : public Component
{
private:
UPositionComponent* PositionComponent;
sf::FloatRect Collider;
public:
UColliderComponent(float width, float height);
virtual void Init() override;
virtual void Tick(float DeltaTime) override;
inline sf::FloatRect GetCollider() const { return Collider; }
}; | [
"stefan_0905@hotmail.com"
] | stefan_0905@hotmail.com |
f27634a0155ffde1c70bb5c89780b43ea681672e | 3fcbc5cc45cb7ce71ea8fd71aa52e6c8d9ff80ab | /15644.cpp | c185a5ccff12d72c9d73164f5a424e7513bca3b0 | [] | no_license | ploffer11/CPP | 83a14601dcc11894bbf5e9b8df1a462f4c494b3a | c47160a9f3f474cee630af0c6e020c6a980c9ab6 | refs/heads/master | 2020-12-06T15:19:10.331008 | 2020-10-04T13:51:53 | 2020-10-04T13:51:53 | 232,493,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,824 | cpp | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("O3")
using namespace std;
using ll = long long;
using pii = pair<int, int>;
const int INF = 987654321;
const int MOD = 1e9 + 7;
string dir = "DURL";
int _dr[] = {1, -1, 0, 0};
int _dc[] = {0, 0, 1, -1};
map<vector<vector<char>>, int> visit;
struct Board
{
vector<vector<char>> board;
int depth, n, m;
int r1, c1, r2, c2;
bool red, blue;
string s;
Board(int n, int m) : n(n), m(m), red(0), blue(0)
{
board.resize(n, vector<char>(m, 0));
}
bool check(int r, int c)
{
return (0 <= r && r < n && 0 <= c && c < m);
}
Board *next(int p)
{
Board *ptr;
ptr = new Board(n, m);
ptr->depth = this->depth + 1;
vector<vector<char>> ret = board;
int r1 = this->r1, c1 = this->c1, r2 = this->r2, c2 = this->c2;
bool red = false, blue = false;
int dr = _dr[p], dc = _dc[p];
bool flag = true;
while (1)
{
if (check(r1 + dr, c1 + dc) && (ret[r1 + dr][c1 + dc] == '.'))
{
swap(ret[r1][c1], ret[r1 + dr][c1 + dc]);
r1 += dr;
c1 += dc;
flag = false;
}
else if (check(r1 + dr, c1 + dc) && ret[r1 + dr][c1 + dc] == 'O')
{
ret[r1][c1] = '.';
red = true;
flag = false;
break;
}
else
break;
}
while (1)
{
if (check(r2 + dr, c2 + dc) && (ret[r2 + dr][c2 + dc] == '.'))
{
swap(ret[r2 + dr][c2 + dc], ret[r2][c2]);
r2 += dr;
c2 += dc;
flag = false;
}
else if (check(r2 + dr, c2 + dc) && ret[r2 + dr][c2 + dc] == 'O')
{
ret[r2][c2] = '.';
return NULL;
}
else
break;
}
while (1)
{
if (check(r1 + dr, c1 + dc) && (ret[r1 + dr][c1 + dc] == '.'))
{
swap(ret[r1][c1], ret[r1 + dr][c1 + dc]);
r1 += dr;
c1 += dc;
flag = false;
}
else if (check(r1 + dr, c1 + dc) && ret[r1 + dr][c1 + dc] == 'O')
{
ret[r1][c1] = '.';
red = true;
flag = false;
break;
}
else
break;
}
while (1)
{
if (check(r2 + dr, c2 + dc) && (ret[r2 + dr][c2 + dc] == '.'))
{
swap(ret[r2 + dr][c2 + dc], ret[r2][c2]);
r2 += dr;
c2 += dc;
flag = false;
}
else if (check(r2 + dr, c2 + dc) && ret[r2 + dr][c2 + dc] == 'O')
{
ret[r2][c2] = '.';
return NULL;
}
else
break;
}
if (flag || visit[ret])
return NULL;
visit[ret] = 1;
ptr->red = red;
ptr->blue = blue;
ptr->board = ret;
ptr->r1 = r1;
ptr->r2 = r2;
ptr->c1 = c1;
ptr->c2 = c2;
ptr->s = s + dir[p];
//ptr->debug();
return ptr;
}
void debug()
{
cout << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << board[i][j] << " ";
}
cout << endl;
}
}
};
int main()
{
cin.tie(0);
ios::sync_with_stdio(0);
int n, m;
cin >> n >> m;
Board InitialBoard(n, m);
InitialBoard.depth = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> InitialBoard.board[i][j];
if (InitialBoard.board[i][j] == 'R')
InitialBoard.r1 = i, InitialBoard.c1 = j;
else if (InitialBoard.board[i][j] == 'B')
InitialBoard.r2 = i, InitialBoard.c2 = j;
}
}
queue<Board> q;
q.push(InitialBoard);
while (!q.empty())
{
auto board = q.front();
q.pop();
//cout << board.depth << " " << board.blue << " " << board.blue << endl;
if (board.depth <= 10 && !board.blue && board.red)
{
cout << board.depth << '\n';
cout << board.s;
return 0;
}
else if (board.depth > 10)
break;
else if (board.blue)
continue;
for (int i = 0; i < 4; i++)
{
auto ret = board.next(i);
if (ret)
q.push(*ret);
}
}
cout << "-1";
}
| [
"ploffer11@naver.com"
] | ploffer11@naver.com |
ea9fc311ded535da8d5c8bfd790915819626ec04 | a97a53c58ae7eb110eab7aa6fde382eaada4d63d | /GE/XYZSurfaceSheet.h | b169971fc13cd8ee6387b6ce1ea20d239890b184 | [] | no_license | meintjesbekker/GE | 8d7a0f40110fd87a58870d9ce7390cc1f2d05f45 | 821323f42657763c03d30c4fadd607b758417c8a | refs/heads/master | 2021-12-08T10:56:51.533338 | 2019-08-08T19:39:56 | 2019-08-08T19:39:56 | 153,671,097 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,564 | h | /*--------------------------------------------------------------------------*/
/* XYZSurfaceSheet.h */
/* */
/* Purpose : Sheet for GUI pages of XYZ Surface. */
/* Author : Meintjes Bekker */
/* Date : Copyright (C) 2000 */
/* Project : Groundwater Explorer */
/* Version : 1 */
/* Notes : User's Guide, section 3.5 "XYZ Surface". */
/*--------------------------------------------------------------------------*/
#if !defined(AFX_XYZSURFACESHEET_H__9594B756_579D_11D3_B81E_0060084B410C__INCLUDED_)
#define AFX_XYZSURFACESHEET_H__9594B756_579D_11D3_B81E_0060084B410C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CXYZSurfaceSheet : public CPropertySheet
{
DECLARE_DYNAMIC(CXYZSurfaceSheet)
// public operations
public:
CXYZSurfaceSheet(UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);
CXYZSurfaceSheet(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);
virtual ~CXYZSurfaceSheet();
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CXYZSurfaceSheet)
//}}AFX_VIRTUAL
// protected operations
protected:
//{{AFX_MSG(CXYZSurfaceSheet)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
#endif // !defined(AFX_XYZSURFACESHEET_H__9594B756_579D_11D3_B81E_0060084B410C__INCLUDED_)
| [
"meintjesbekker@yahoo.com"
] | meintjesbekker@yahoo.com |
d337cc9e1eb0eafddca2997ac08783db95cfdaaa | 9a71f86a7917234d9d521a339e5ff621b085c231 | /cpp/examples/gridNetExamples/smartnos-developer-platform/smartnosapplicationframework/DomainClientSocket.cpp | 645e70781e458f8ae3d0bae601682303fe842fe6 | [] | no_license | projectsf/snippets | 58a42573175c2662e00c7f92aa0603c6c4eaf371 | f85f287a8b63d2e3ef5ddd861c01d60cc4f96cc4 | refs/heads/master | 2016-09-02T01:36:43.614212 | 2013-03-15T22:46:03 | 2013-03-15T22:46:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | cpp | /**
* Used in socket_main.cpp
*
* @file DomainClientSocket.cpp
*/
// Implementation of the DomainClientSocket class
#include "DomainClientSocket.hpp"
#include "DomainSocketException.hpp"
DomainClientSocket::DomainClientSocket ( std::string host, int port )
{
if ( ! DomainSocket::create() )
{
throw DomainSocketException ( "Could not create client socket." );
}
if ( ! DomainSocket::connect ( host, port ) )
{
throw DomainSocketException ( "Could not bind to port." );
}
}
const DomainClientSocket& DomainClientSocket::operator << ( const std::string& s ) const
{
if ( ! DomainSocket::send ( s ) )
{
throw DomainSocketException ( "Could not write to socket." );
}
return *this;
}
const DomainClientSocket& DomainClientSocket::operator >> ( std::string& s ) const
{
if ( ! DomainSocket::recv ( s ) )
{
throw DomainSocketException ( "Could not read from socket." );
}
return *this;
}
| [
"scott.maroney@gmail.com"
] | scott.maroney@gmail.com |
754145475a520dff49dd28ca538ffad73851b52a | c46eaf417ed24709c3ddf96cc104b6b66ae895be | /Need_DO/0.0.cpp | 9eaf5d7c40451d6a0a4e1b3ff176ac5ba322ca2f | [
"MIT"
] | permissive | AdorableGhost/CPP_learn | 6bcfea6446dda718a131b6c95479e1835775eb2b | a91c80119eda8d8f9f0c257ce460b4612d45f2d2 | refs/heads/master | 2022-12-09T21:20:17.494966 | 2020-09-13T02:13:25 | 2020-09-13T02:13:25 | 294,763,036 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 174 | cpp | /*
Clean One If Finished!
*/
1. QT First
2. DataStructure And Algorithm And Essential Knowndges For CPP doing
3.Linux CPP Programming
4.Windows Programming (If needed!) | [
"1244453862@qq.com"
] | 1244453862@qq.com |
15ff66bfa9e59f1126d20fc1a980617f58e74df2 | 788b4664f114e03e2d84060615f5451dc662d66e | /lingex/inheritance_man.cpp | 3e96ddcbef7d687109364615f55347ef28247933 | [] | no_license | zhouxindong/rola | dbdd7fb3bf034ed084ac67efcb9b59b6de0bb657 | 04b8b039b8786ee123c3a85467869c7708da185d | refs/heads/main | 2023-07-29T10:58:24.271940 | 2021-08-27T07:30:13 | 2021-08-27T07:30:13 | 305,242,132 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 842 | cpp | #include "inheritance.hpp"
#include <iostream>
#include <vector>
struct ICalculator
{
virtual long long compute(int input) const = 0;
virtual ~ICalculator() {};
};
struct BigCalculator : ICalculator
{
long long compute(int input) const override
{
std::cout << "BigCalculator::compute()" << std::endl;
return input * 5;
}
};
struct SmallCalculator : ICalculator
{
long long compute(int input) const override
{
std::cout << "SmallCalculator::compute()" << std::endl;
return input + 2;
}
};
using Calculator = rola::Implementation<ICalculator>;
int main_inheritance()
{
std::vector<Calculator> v;
v.push_back(BigCalculator());
v.push_back(SmallCalculator());
std::cout << v[0]->compute(3) << std::endl;
std::cout << v[1]->compute(3) << std::endl;
std::cout << "inheritance_main successful" << std::endl;
return 0;
} | [
"zhouxindong@163.com"
] | zhouxindong@163.com |
034a25d085e2e9bb761d4f972bd5b30bb743e7f7 | ab5c7e0a0d6f699f24f4ace5244c1f64acbe3563 | /core/test/lib/boost/boost/asio/ssl/impl/error.ipp | 0ab6d419aef3058c8f5e87250011f52df86f02ce | [
"MIT"
] | permissive | tmpfork/lib-ledger-core | e7c9d0426fe944c0f6a81d74744796e87542fa8a | 8741e84f38f863fd941d3bd56a470f37eb36da04 | refs/heads/master | 2020-04-21T09:42:37.184675 | 2019-01-23T13:15:43 | 2019-01-23T13:15:43 | 169,459,374 | 0 | 0 | MIT | 2019-02-06T18:58:46 | 2019-02-06T18:58:46 | null | UTF-8 | C++ | false | false | 2,223 | ipp | //
// ssl/impl/error.ipp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_SSL_IMPL_ERROR_IPP
#define BOOST_ASIO_SSL_IMPL_ERROR_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/detail/openssl_init.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace error {
namespace detail {
class ssl_category : public boost::system::error_category
{
public:
const char* name() const BOOST_ASIO_ERROR_CATEGORY_NOEXCEPT
{
return "asio.ssl";
}
std::string message(int value) const
{
const char* s = ::ERR_reason_error_string(value);
return s ? s : "asio.ssl error";
}
};
} // namespace detail
const boost::system::error_category& get_ssl_category()
{
static detail::ssl_category instance;
return instance;
}
} // namespace error
namespace ssl {
namespace error {
#if (OPENSSL_VERSION_NUMBER < 0x10100000L) && !defined(OPENSSL_IS_BORINGSSL)
const boost::system::error_category& get_stream_category()
{
return boost::asio::error::get_ssl_category();
}
#else
namespace detail {
class stream_category : public boost::system::error_category
{
public:
const char* name() const BOOST_ASIO_ERROR_CATEGORY_NOEXCEPT
{
return "asio.ssl.stream";
}
std::string message(int value) const
{
switch (value)
{
case stream_truncated: return "stream truncated";
default: return "asio.ssl.stream error";
}
}
};
} // namespace detail
const boost::system::error_category& get_stream_category()
{
static detail::stream_category instance;
return instance;
}
#endif
} // namespace error
} // namespace ssl
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_SSL_IMPL_ERROR_IPP
| [
"pollastri.p@gmail.com"
] | pollastri.p@gmail.com |
972955d9cebf786af7ae66ea972c706cb10082ff | 49b4153a6709c1b115dd459a115fc2bb1ca1a6b2 | /zetasql/reference_impl/value_expr.cc | a6a3833be290799d04692f47827a9abda8f90dfa | [
"Apache-2.0"
] | permissive | gbeanvamp/zetasql | a1651e6c963638f4e24fe552958fbaef681abf5f | 64f7ea4be8c0d5ab8eeb62ebcc1f95f754a14bc3 | refs/heads/master | 2021-01-08T10:12:44.395053 | 2020-03-03T20:01:29 | 2020-03-03T20:01:29 | 241,998,627 | 0 | 0 | Apache-2.0 | 2020-03-03T20:01:30 | 2020-02-20T21:56:07 | C++ | UTF-8 | C++ | false | false | 124,483 | cc | //
// Copyright 2019 ZetaSQL Authors
//
// 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.
//
// Implementations of the various ValueExprs.
#include <algorithm>
#include <array>
#include <functional>
#include <iterator>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "zetasql/base/logging.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/message.h"
#include "zetasql/common/internal_value.h"
#include "zetasql/public/language_options.h"
#include "zetasql/public/options.pb.h"
#include "zetasql/public/proto_util.h"
#include "zetasql/public/proto_value_conversion.h"
#include "zetasql/public/type.h"
#include "zetasql/public/type.pb.h"
#include "zetasql/public/value.h"
#include "zetasql/reference_impl/evaluation.h"
#include "zetasql/reference_impl/operator.h"
#include "zetasql/reference_impl/parameters.h"
#include "zetasql/reference_impl/tuple.h"
#include "zetasql/reference_impl/variable_id.h"
#include "zetasql/resolved_ast/resolved_ast.h"
#include "zetasql/resolved_ast/resolved_ast_enums.pb.h"
#include "zetasql/resolved_ast/resolved_column.h"
#include "zetasql/resolved_ast/resolved_node.h"
#include "zetasql/resolved_ast/resolved_node_kind.pb.h"
#include <cstdint>
#include "zetasql/base/cleanup.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "zetasql/base/map_util.h"
#include "zetasql/base/source_location.h"
#include "zetasql/base/ret_check.h"
#include "zetasql/base/status.h"
#include "zetasql/base/status_builder.h"
#include "zetasql/base/status_macros.h"
#include "zetasql/base/statusor.h"
using zetasql::values::Bool;
using zetasql::values::Int64;
namespace zetasql {
// -------------------------------------------------------
// ValueExpr
// -------------------------------------------------------
ValueExpr::~ValueExpr() {}
// -------------------------------------------------------
// TableAsArrayExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<TableAsArrayExpr>> TableAsArrayExpr::Create(
const std::string& table_name, const ArrayType* type) {
return absl::WrapUnique(new TableAsArrayExpr(table_name, type));
}
::zetasql_base::Status TableAsArrayExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> /* params_schemas */) {
// Eval() ignores the parameters.
return zetasql_base::OkStatus();
}
bool TableAsArrayExpr::Eval(absl::Span<const TupleData* const> /* params */,
EvaluationContext* context,
VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
const Value& array = context->GetTableAsArray(table_name());
if (!array.is_valid()) {
*status = zetasql_base::OutOfRangeErrorBuilder()
<< "Table not populated with array: " << table_name();
return false;
} else if (!output_type()->Equals(array.type())) {
*status = zetasql_base::OutOfRangeErrorBuilder()
<< "Type of populated table (as array) " << table_name()
<< " deviates from the "
<< "type reported in the catalog.\n"
<< "Actual: " << array.type()->DebugString() << "\n"
<< "Expected: " << output_type()->DebugString();
return false;
}
result->SetValue(array);
return true;
}
std::string TableAsArrayExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat("TableAsArrayExpr(", table_name(), ")");
}
TableAsArrayExpr::TableAsArrayExpr(const std::string& table_name,
const ArrayType* type)
: ValueExpr(type), table_name_(table_name) {}
// -------------------------------------------------------
// NewStructExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<NewStructExpr>> NewStructExpr::Create(
const StructType* type, std::vector<std::unique_ptr<ExprArg>> args) {
ZETASQL_RET_CHECK_EQ(type->num_fields(), args.size());
for (int i = 0; i < args.size(); i++) {
ZETASQL_RET_CHECK(args[i]->node()->AsValueExpr() != nullptr);
ZETASQL_RET_CHECK(type->field(i).type->Equals(args[i]->node()->output_type()));
ZETASQL_RET_CHECK(!args[i]->has_variable());
}
return absl::WrapUnique(new NewStructExpr(type, std::move(args)));
}
::zetasql_base::Status NewStructExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
for (ExprArg* arg : mutable_field_list()) {
ZETASQL_RETURN_IF_ERROR(
arg->mutable_value_expr()->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
bool NewStructExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
int64_t values_size = 0;
std::vector<Value> values(field_list().size());
for (int i = 0; i < field_list().size(); ++i) {
Value* field = &values[i];
std::shared_ptr<TupleSlot::SharedProtoState> field_shared_state;
VirtualTupleSlot field_result(field, &field_shared_state);
if (!field_list()[i]->value_expr()->Eval(params, context, &field_result,
status)) {
return false;
}
values_size += field->physical_byte_size();
if (values_size >= context->options().max_value_byte_size) {
*status = zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot construct struct Value larger than "
<< context->options().max_value_byte_size << " bytes";
return false;
}
}
result->SetValue(
Value::UnsafeStruct(output_type()->AsStruct(), std::move(values)));
return true;
}
std::string NewStructExpr::DebugInternal(const std::string& indent,
bool verbose) const {
std::string indent_child = indent + kIndentFork;
std::string result = absl::StrCat("NewStructExpr(", indent_child,
"type: ", output_type()->DebugString());
if (!field_list().empty()) {
int i = 0;
for (auto ch : field_list()) {
absl::StrAppend(&result, ",", indent_child, i, " ",
output_type()->AsStruct()->field(i).name, ": ",
ch->DebugInternal(indent + kIndentSpace, verbose));
++i;
}
}
absl::StrAppend(&result, ")");
return result;
}
NewStructExpr::NewStructExpr(const StructType* type,
std::vector<std::unique_ptr<ExprArg>> args)
: ValueExpr(type) {
SetArgs<ExprArg>(kField, std::move(args));
}
absl::Span<const ExprArg* const> NewStructExpr::field_list() const {
return GetArgs<ExprArg>(kField);
}
absl::Span<ExprArg* const> NewStructExpr::mutable_field_list() {
return GetMutableArgs<ExprArg>(kField);
}
// -------------------------------------------------------
// NewArrayExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<NewArrayExpr>> NewArrayExpr::Create(
const ArrayType* array_type,
std::vector<std::unique_ptr<ValueExpr>> elements) {
for (const auto& e : elements) {
ZETASQL_RET_CHECK(array_type->element_type()->Equals(e->output_type()));
}
return absl::WrapUnique(new NewArrayExpr(array_type, std::move(elements)));
}
::zetasql_base::Status NewArrayExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
for (ExprArg* arg : mutable_elements()) {
ZETASQL_RETURN_IF_ERROR(
arg->mutable_value_expr()->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
bool NewArrayExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
int64_t values_size = 0;
std::vector<Value> values(elements().size());
for (int i = 0; i < elements().size(); ++i) {
Value* element = &values[i];
std::shared_ptr<TupleSlot::SharedProtoState> element_shared_state;
VirtualTupleSlot element_result(element, &element_shared_state);
if (!elements()[i]->value_expr()->Eval(params, context, &element_result,
status)) {
return false;
}
values_size += element->physical_byte_size();
if (values_size >= context->options().max_value_byte_size) {
*status = zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot construct array Value larger than "
<< context->options().max_value_byte_size << " bytes";
return false;
}
}
result->SetValue(
Value::UnsafeArray(output_type()->AsArray(), std::move(values)));
return true;
}
std::string NewArrayExpr::DebugInternal(const std::string& indent,
bool verbose) const {
std::string indent_child = indent + kIndentSpace;
std::vector<std::string> fstr;
for (auto ch : elements()) {
fstr.push_back(ch->DebugInternal(indent_child, verbose));
}
return verbose
? absl::StrCat("NewArrayExpr(", indent_child,
"type: ", output_type()->DebugString(), ",",
indent_child,
absl::StrJoin(fstr, "," + indent_child), ")")
: absl::StrCat("NewArrayExpr(", absl::StrJoin(fstr, ", "), ")");
}
NewArrayExpr::NewArrayExpr(const ArrayType* array_type,
std::vector<std::unique_ptr<ValueExpr>> elements)
: ValueExpr(array_type) {
std::vector<std::unique_ptr<ExprArg>> args;
args.reserve(elements.size());
for (auto& e : elements) {
args.push_back(absl::make_unique<ExprArg>(std::move(e)));
}
SetArgs<ExprArg>(kElement, std::move(args));
}
absl::Span<const ExprArg* const> NewArrayExpr::elements() const {
return GetArgs<ExprArg>(kElement);
}
absl::Span<ExprArg* const> NewArrayExpr::mutable_elements() {
return GetMutableArgs<ExprArg>(kElement);
}
// -------------------------------------------------------
// ArrayNestExpr
// -------------------------------------------------------
std::string ArrayNestExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat(
"ArrayNestExpr(is_with_table=", is_with_table_,
ArgDebugString({"element", "input"}, {k1, k1}, indent, verbose), ")");
}
::zetasql_base::StatusOr<std::unique_ptr<ArrayNestExpr>> ArrayNestExpr::Create(
const ArrayType* array_type, std::unique_ptr<ValueExpr> element,
std::unique_ptr<RelationalOp> input, bool is_with_table) {
return absl::WrapUnique(new ArrayNestExpr(array_type, std::move(element),
std::move(input), is_with_table));
}
::zetasql_base::Status ArrayNestExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
ZETASQL_RETURN_IF_ERROR(mutable_input()->SetSchemasForEvaluation(params_schemas));
const std::unique_ptr<const TupleSchema> input_schema =
input()->CreateOutputSchema();
return mutable_element()->SetSchemasForEvaluation(
ConcatSpans(params_schemas, {input_schema.get()}));
}
bool ArrayNestExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
auto status_or_iter =
input()->CreateIterator(params, /*num_extra_slots=*/0, context);
if (!status_or_iter.ok()) {
*status = status_or_iter.status();
return false;
}
std::unique_ptr<TupleIterator> iter = std::move(status_or_iter).ValueOrDie();
const bool iter_originally_preserved_order = iter->PreservesOrder();
// We disable reordering when nesting a relation in an array for backwards
// compatibility with the text-based reference implementation compliance
// tests. Another advantage is that it effectively turns off scrambling for
// simple [prepare_database] statements in the compliance tests, which makes
// the results easier to read.
*status = iter->DisableReordering();
if (!status->ok()) return false;
// For WITH tables, the array represents multiple rows, so we must track the
// memory usage with a MemoryAccountant. For non-WITH tables, we simply ensure
// that the array is not too large.
MemoryAccountant* accountant = nullptr;
if (is_with_table_) {
accountant = context->memory_accountant();
}
std::vector<Value> output;
std::function<void()> return_bytes = [accountant, &output]() {
if (accountant != nullptr) {
for (const Value& value : output) {
accountant->ReturnBytes(value.physical_byte_size());
}
}
};
// If we fail early, return the accumulated bytes.
auto cleanup = zetasql_base::MakeCleanup(return_bytes);
int64_t output_byte_size = 0; // Valid if 'is_with_table_' is false.
while (true) {
const TupleData* tuple = iter->Next();
if (tuple == nullptr) {
*status = iter->Status();
if (!status->ok()) return false;
break;
}
TupleSlot slot;
if (!element()->EvalSimple(ConcatSpans(params, {tuple}), context, &slot,
status)) {
return false;
}
Value& value = *slot.mutable_value();
// Check for memory usage. See the comment for 'accountant' above.
if (accountant == nullptr) {
output_byte_size += value.physical_byte_size();
if (output_byte_size > context->options().max_value_byte_size) {
*status = zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot construct array Value larger than "
<< context->options().max_value_byte_size << " bytes";
return false;
}
} else {
if (!accountant->RequestBytes(value.physical_byte_size(), status)) {
return false;
}
}
output.push_back(std::move(value));
}
// Free the memory. Ideally we would not do this here and instead do it when
// the TupleIterator that stores the WITH table is deleted. But we have no way
// to easily hold a MemoryAccountant reservation after this method returns. So
// as a hack, we free the memory here and re-reserve it in the LetOp/LetExpr
// that ends up holding the WITH table.
return_bytes();
result->SetValue(InternalValue::ArrayNotChecked(
output_type()->AsArray(), iter_originally_preserved_order,
std::move(output))); // Invalidates 'output' (and therefore 'cleanup').
output.clear(); // Nothing for 'cleanup' to do.
return true;
}
ArrayNestExpr::ArrayNestExpr(const ArrayType* array_type,
std::unique_ptr<ValueExpr> element,
std::unique_ptr<RelationalOp> input,
bool is_with_table)
: ValueExpr(array_type), is_with_table_(is_with_table) {
SetArg(kInput, absl::make_unique<RelationalArg>(std::move(input)));
SetArg(kElement, absl::make_unique<ExprArg>(std::move(element)));
}
const ValueExpr* ArrayNestExpr::element() const {
return GetArg(kElement)->node()->AsValueExpr();
}
ValueExpr* ArrayNestExpr::mutable_element() {
return GetMutableArg(kElement)->mutable_node()->AsMutableValueExpr();
}
const RelationalOp* ArrayNestExpr::input() const {
return GetArg(kInput)->node()->AsRelationalOp();
}
RelationalOp* ArrayNestExpr::mutable_input() {
return GetMutableArg(kInput)->mutable_node()->AsMutableRelationalOp();
}
// -------------------------------------------------------
// DerefExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<DerefExpr>> DerefExpr::Create(
const VariableId& name, const Type* type) {
return absl::WrapUnique(new DerefExpr(name, type));
}
::zetasql_base::Status DerefExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
int first_schema_idx = -1;
int first_slot = -1;
for (int i = 0; i < params_schemas.size(); ++i) {
const TupleSchema* schema = params_schemas[i];
absl::optional<int> slot = schema->FindIndexForVariable(name_);
if (slot.has_value()) {
ZETASQL_RET_CHECK_EQ(first_slot, -1) << "Duplicate name detected: " << name_;
first_slot = slot.value();
first_schema_idx = i;
}
}
ZETASQL_RET_CHECK_GE(first_slot, 0) << "Missing name: " << name_;
idx_in_params_ = first_schema_idx;
slot_ = first_slot;
return zetasql_base::OkStatus();
}
bool DerefExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* /* status */) const {
DCHECK(idx_in_params_ >= 0 && slot_ >= 0)
<< "You forgot to call SetSchemasForEvaluation() " << name_;
result->CopyFromSlot(params[idx_in_params_]->slot(slot_));
return true;
}
std::string DerefExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return verbose ? absl::StrCat("DerefExpr(", name().ToString(), ")")
: absl::StrCat("$", name().ToString());
}
DerefExpr::DerefExpr(const VariableId& name, const Type* type)
: ValueExpr(type), name_(name) {}
// -------------------------------------------------------
// ConstExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<ConstExpr>> ConstExpr::Create(
const Value& value) {
return absl::WrapUnique(new ConstExpr(value));
}
::zetasql_base::Status ConstExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> /* params_schemas */) {
// Eval() ignores the parameters.
return zetasql_base::OkStatus();
}
bool ConstExpr::Eval(absl::Span<const TupleData* const> /* params */,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* /* status */) const {
result->CopyFromSlot(slot_);
return true;
}
std::string ConstExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat("ConstExpr(", value().DebugString(verbose), ")");
}
ConstExpr::ConstExpr(const Value& value) : ValueExpr(value.type()) {
slot_.SetValue(value);
}
// -------------------------------------------------------
// FieldValueExpr
// -------------------------------------------------------
static ::zetasql_base::StatusOr<int> GetFieldIndex(const StructType* type,
absl::string_view field_name) {
for (int i = 0; i < type->num_fields(); i++) {
if (type->field(i).name == field_name) {
return i;
}
}
ZETASQL_RET_CHECK_FAIL() << "No field " << field_name << " in "
<< type->DebugString();
}
::zetasql_base::StatusOr<std::unique_ptr<FieldValueExpr>> FieldValueExpr::Create(
absl::string_view field_name, std::unique_ptr<ValueExpr> expr) {
ZETASQL_ASSIGN_OR_RETURN(const int field_index,
GetFieldIndex(expr->output_type()->AsStruct(), field_name));
return Create(field_index, std::move(expr));
}
::zetasql_base::StatusOr<std::unique_ptr<FieldValueExpr>> FieldValueExpr::Create(
int field_index, std::unique_ptr<ValueExpr> expr) {
return absl::WrapUnique(new FieldValueExpr(field_index, std::move(expr)));
}
::zetasql_base::Status FieldValueExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
return mutable_input()->SetSchemasForEvaluation(params_schemas);
}
bool FieldValueExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
TupleSlot struct_slot;
if (!input()->EvalSimple(params, context, &struct_slot, status)) {
return false;
}
const Value& struct_value = struct_slot.value();
Value field_value = struct_value.is_null()
? Value::Null(output_type())
: struct_value.field(field_index());
result->SetValueAndMaybeSharedProtoState(
std::move(field_value), struct_slot.mutable_shared_proto_state());
return true;
}
std::string FieldValueExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat("FieldValueExpr(", field_index(), ":", field_name(), ", ",
input()->DebugInternal(indent, verbose), ")");
}
FieldValueExpr::FieldValueExpr(int field_index, std::unique_ptr<ValueExpr> expr)
: ValueExpr(expr->output_type()->AsStruct()->field(field_index).type),
field_name_(expr->output_type()->AsStruct()->field(field_index).name),
field_index_(field_index) {
SetArg(kStruct, absl::make_unique<ExprArg>(std::move(expr)));
}
const ValueExpr* FieldValueExpr::input() const {
return GetArg(kStruct)->node()->AsValueExpr();
}
ValueExpr* FieldValueExpr::mutable_input() {
return GetMutableArg(kStruct)->mutable_node()->AsMutableValueExpr();
}
// -------------------------------------------------------
// ProtoFieldReader
// -------------------------------------------------------
bool ProtoFieldReader::GetFieldValue(const TupleSlot& proto_slot,
EvaluationContext* context,
Value* field_value,
::zetasql_base::Status* status) const {
context->set_last_get_field_value_call_read_fields_from_proto(this, false);
const Value& proto_value = proto_slot.value();
if (proto_value.is_null()) {
if (access_info_.field_info.get_has_bit) {
if (access_info_.return_default_value_when_unset) {
*status = zetasql_base::InternalErrorBuilder()
<< "ProtoFieldAccessInfo.return_default_value_when_unset "
<< "must be false if field_info->get_has_bit is true";
return false;
}
*field_value = Value::NullBool();
return true;
}
if (access_info_.return_default_value_when_unset) {
*field_value = access_info_.field_info.default_value;
return true;
}
*field_value = Value::Null(access_info_.field_info.type);
return true;
}
ProtoFieldValueMapKey value_map_key;
value_map_key.proto_rep = InternalValue::GetProtoRep(proto_value);
value_map_key.registry = registry_;
// We store the ProtoFieldValueList in 'shared_state' if
// EvaluationOptions::store_proto_field_value_maps is true. Otherwise,
// 'value_list_owner' owns the ProtoFieldValueList.
std::unique_ptr<ProtoFieldValueList> value_list_owner;
std::shared_ptr<TupleSlot::SharedProtoState>& shared_state =
*proto_slot.mutable_shared_proto_state();
const std::unique_ptr<ProtoFieldValueList>* existing_value_list =
shared_state->has_value()
? FindOrNull(shared_state->value(), value_map_key)
: nullptr;
const ProtoFieldValueList* value_list =
existing_value_list == nullptr ? nullptr : existing_value_list->get();
if (value_list == nullptr) {
context->set_last_get_field_value_call_read_fields_from_proto(this, true);
context->set_num_proto_deserializations(
context->num_proto_deserializations() + 1);
std::vector<const ProtoFieldInfo*> field_infos;
field_infos.reserve(registry_->GetRegisteredFields().size());
for (const ProtoFieldAccessInfo* access_info :
registry_->GetRegisteredFields()) {
field_infos.push_back(&access_info->field_info);
}
value_list_owner = absl::make_unique<ProtoFieldValueList>();
value_list = value_list_owner.get();
const ::zetasql_base::Status read_status = ReadProtoFields(
field_infos, proto_value.ToCord(), value_list_owner.get());
if (!read_status.ok()) {
*status = read_status;
return false;
}
// Store 'value_list' in 'proto_slot' if
// EvaluationOptions::store_proto_field_value_maps is true.
if (context->options().store_proto_field_value_maps) {
if (!shared_state->has_value()) {
*shared_state = ProtoFieldValueMap();
}
(shared_state->value())[value_map_key] = std::move(value_list_owner);
}
}
if (access_info_registry_id_ >= value_list->size()) {
*status = zetasql_base::InternalErrorBuilder() << "Corrupt ProtoFieldValueList";
return false;
}
const ::zetasql_base::StatusOr<Value>& value =
(*value_list)[access_info_registry_id_];
if (!value.ok()) {
*status = value.status();
return false;
}
*field_value = value.ValueOrDie();
return true;
}
// -------------------------------------------------------
// GetProtoFieldExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<GetProtoFieldExpr>> GetProtoFieldExpr::Create(
std::unique_ptr<ValueExpr> proto_expr,
const ProtoFieldReader* field_reader) {
return absl::WrapUnique(
new GetProtoFieldExpr(std::move(proto_expr), field_reader));
}
::zetasql_base::Status GetProtoFieldExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
return mutable_proto_expr()->SetSchemasForEvaluation(params_schemas);
}
bool GetProtoFieldExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context,
VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
TupleSlot proto_slot;
if (!proto_expr()->EvalSimple(params, context, &proto_slot, status)) {
return false;
}
if (!field_reader_->GetFieldValue(proto_slot, context,
result->mutable_value(), status)) {
return false;
}
result->MaybeUpdateSharedProtoStateAfterSettingValue(
proto_slot.mutable_shared_proto_state());
return true;
}
GetProtoFieldExpr::GetProtoFieldExpr(std::unique_ptr<ValueExpr> proto_expr,
const ProtoFieldReader* field_reader)
: ValueExpr(field_reader->access_info().field_info.type),
field_reader_(field_reader) {
SetArg(kProtoExpr, absl::make_unique<ExprArg>(std::move(proto_expr)));
}
const ValueExpr* GetProtoFieldExpr::proto_expr() const {
return GetArg(kProtoExpr)->node()->AsValueExpr();
}
ValueExpr* GetProtoFieldExpr::mutable_proto_expr() {
return GetMutableArg(kProtoExpr)->mutable_node()->AsMutableValueExpr();
}
std::string GetProtoFieldExpr::DebugInternal(const std::string& indent,
bool verbose) const {
const ProtoFieldInfo& field_info = field_reader_->access_info().field_info;
return absl::StrCat(
"GetProtoFieldExpr(", (field_info.get_has_bit ? "has_" : ""),
field_info.descriptor->name(), ", ", proto_expr()->DebugString(),
" [fid=", field_reader_->id(), " rid=", field_reader_->registry_id(),
"])");
}
// -------------------------------------------------------
// SingleValueExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<SingleValueExpr>> SingleValueExpr::Create(
std::unique_ptr<ValueExpr> value, std::unique_ptr<RelationalOp> input) {
return absl::WrapUnique(
new SingleValueExpr(std::move(value), std::move(input)));
}
::zetasql_base::Status SingleValueExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
ZETASQL_RETURN_IF_ERROR(mutable_input()->SetSchemasForEvaluation(params_schemas));
const std::unique_ptr<const TupleSchema> input_schema =
input()->CreateOutputSchema();
return mutable_value()->SetSchemasForEvaluation(
ConcatSpans(params_schemas, {input_schema.get()}));
}
bool SingleValueExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
auto status_or_iter =
input()->CreateIterator(params, /*num_extra_slots=*/0, context);
if (!status_or_iter.ok()) {
*status = status_or_iter.status();
return false;
}
std::unique_ptr<TupleIterator> iter = std::move(status_or_iter).ValueOrDie();
const TupleData* tuple = iter->Next();
if (tuple == nullptr) {
*status = iter->Status();
if (!status->ok()) return false;
result->SetValue(Value::Null(output_type()));
return true;
}
if (!value()->Eval(ConcatSpans(params, {tuple}), context, result, status)) {
return false;
}
tuple = iter->Next();
if (tuple == nullptr) {
*status = iter->Status();
if (!status->ok()) return false;
return true;
}
*status = zetasql_base::OutOfRangeErrorBuilder() << "More than one element";
return false;
}
std::string SingleValueExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat(
"SingleValueExpr(",
ArgDebugString({"value", "input"}, {k1, k1}, indent, verbose), ")");
}
SingleValueExpr::SingleValueExpr(std::unique_ptr<ValueExpr> value,
std::unique_ptr<RelationalOp> input)
: ValueExpr(value->output_type()) {
SetArg(kInput, absl::make_unique<RelationalArg>(std::move(input)));
SetArg(kValue, absl::make_unique<ExprArg>(std::move(value)));
}
const RelationalOp* SingleValueExpr::input() const {
return GetArg(kInput)->node()->AsRelationalOp();
}
RelationalOp* SingleValueExpr::mutable_input() {
return GetMutableArg(kInput)->mutable_node()->AsMutableRelationalOp();
}
const ValueExpr* SingleValueExpr::value() const {
return GetArg(kValue)->node()->AsValueExpr();
}
ValueExpr* SingleValueExpr::mutable_value() {
return GetMutableArg(kValue)->mutable_node()->AsMutableValueExpr();
}
// -------------------------------------------------------
// ExistsExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<ExistsExpr>> ExistsExpr::Create(
std::unique_ptr<RelationalOp> input) {
return absl::WrapUnique(new ExistsExpr(std::move(input)));
}
::zetasql_base::Status ExistsExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
return mutable_input()->SetSchemasForEvaluation(params_schemas);
}
bool ExistsExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
auto status_or_iter =
input()->CreateIterator(params, /*num_extra_slots=*/0, context);
if (!status_or_iter.ok()) {
*status = status_or_iter.status();
return false;
}
std::unique_ptr<TupleIterator> iter = std::move(status_or_iter).ValueOrDie();
const TupleData* tuple = iter->Next();
if (tuple == nullptr) {
*status = iter->Status();
if (!status->ok()) return false;
result->SetValue(Bool(false));
return true;
}
result->SetValue(Bool(true));
return true;
}
std::string ExistsExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat("ExistsExpr(",
ArgDebugString({"input"}, {k1}, indent, verbose), ")");
}
ExistsExpr::ExistsExpr(std::unique_ptr<RelationalOp> input)
: ValueExpr(types::BoolType()) {
SetArg(kInput, absl::make_unique<RelationalArg>(std::move(input)));
}
const RelationalOp* ExistsExpr::input() const {
return GetArg(kInput)->node()->AsRelationalOp();
}
RelationalOp* ExistsExpr::mutable_input() {
return GetMutableArg(kInput)->mutable_node()->AsMutableRelationalOp();
}
// -------------------------------------------------------
// ScalarFunctionCallExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<ScalarFunctionCallExpr>>
ScalarFunctionCallExpr::Create(
std::unique_ptr<const ScalarFunctionBody> function,
std::vector<std::unique_ptr<ValueExpr>> exprs,
ResolvedFunctionCallBase::ErrorMode error_mode) {
ZETASQL_RET_CHECK(function != nullptr);
return absl::WrapUnique(new ScalarFunctionCallExpr(
std::move(function), std::move(exprs), error_mode));
}
::zetasql_base::Status ScalarFunctionCallExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
absl::Span<AlgebraArg* const> args = GetMutableArgs();
for (AlgebraArg* arg : args) {
ZETASQL_RETURN_IF_ERROR(
arg->mutable_value_expr()->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
bool ScalarFunctionCallExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context,
VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
const auto& args = GetArgs();
std::vector<Value> call_args(args.size());
for (int i = 0; i < args.size(); i++) {
std::shared_ptr<TupleSlot::SharedProtoState> arg_shared_state;
VirtualTupleSlot arg_result(&call_args[i], &arg_shared_state);
if (!args[i]->value_expr()->Eval(params, context, &arg_result, status)) {
return false;
}
}
if (!function_->Eval(call_args, context, result->mutable_value(), status)) {
if (ShouldSuppressError(*status, error_mode_)) {
*status = ::zetasql_base::OkStatus();
result->SetValue(Value::Null(output_type()));
return true;
}
return false;
}
result->MaybeResetSharedProtoState();
return true;
}
std::string ScalarFunctionCallExpr::DebugInternal(const std::string& indent,
bool verbose) const {
std::vector<std::string> sarg;
for (auto arg : GetArgs()) {
std::string indent_child = indent + kIndentSpace;
sarg.push_back(arg->value_expr()->DebugInternal(indent_child, verbose));
}
return absl::StrCat(function()->debug_name(), "(", absl::StrJoin(sarg, ", "),
")");
}
ScalarFunctionCallExpr::ScalarFunctionCallExpr(
std::unique_ptr<const ScalarFunctionBody> function,
std::vector<std::unique_ptr<ValueExpr>> exprs,
ResolvedFunctionCallBase::ErrorMode error_mode)
: ValueExpr(function->output_type()),
function_(std::move(function)),
error_mode_(error_mode) {
std::vector<std::unique_ptr<ExprArg>> args;
args.reserve(exprs.size());
for (auto& e : exprs) {
args.push_back(absl::make_unique<ExprArg>(std::move(e)));
}
SetArgs<ExprArg>(kArgument, std::move(args));
}
// -------------------------------------------------------
// AggregateFunctionCallExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<AggregateFunctionCallExpr>>
AggregateFunctionCallExpr::Create(
std::unique_ptr<const AggregateFunctionBody> function,
std::vector<std::unique_ptr<ValueExpr>> exprs) {
ZETASQL_RET_CHECK(function != nullptr);
return absl::WrapUnique(
new AggregateFunctionCallExpr(std::move(function), std::move(exprs)));
}
::zetasql_base::Status AggregateFunctionCallExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
absl::Span<AlgebraArg* const> args = GetMutableArgs();
for (AlgebraArg* arg : args) {
ZETASQL_RETURN_IF_ERROR(
arg->mutable_value_expr()->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
std::string AggregateFunctionCallExpr::DebugInternal(const std::string& indent,
bool verbose) const {
std::vector<std::string> sarg;
for (auto arg : GetArgs()) {
std::string indent_child = indent + kIndentSpace;
sarg.push_back(arg->value_expr()->DebugInternal(indent_child, verbose));
}
return absl::StrCat(function()->debug_name(), "(", absl::StrJoin(sarg, ", "),
")");
}
AggregateFunctionCallExpr::AggregateFunctionCallExpr(
std::unique_ptr<const AggregateFunctionBody> function,
std::vector<std::unique_ptr<ValueExpr>> exprs)
: ValueExpr(function->output_type()), function_(std::move(function)) {
std::vector<std::unique_ptr<ExprArg>> args;
args.reserve(exprs.size());
for (auto& e : exprs) {
args.push_back(absl::make_unique<ExprArg>(std::move(e)));
}
SetArgs<ExprArg>(kArgument, std::move(args));
}
bool AggregateFunctionCallExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context,
VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
*status = ::zetasql_base::InternalErrorBuilder()
<< "Use AggregateArg to evaluate an aggregate function";
return false;
}
// -------------------------------------------------------
// AnalyticFunctionCallExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<AnalyticFunctionCallExpr>>
AnalyticFunctionCallExpr::Create(
std::unique_ptr<const AnalyticFunctionBody> function,
std::vector<std::unique_ptr<ValueExpr>> non_const_arguments,
std::vector<std::unique_ptr<ValueExpr>> const_arguments) {
ZETASQL_RET_CHECK(function != nullptr);
return absl::WrapUnique(new AnalyticFunctionCallExpr(
std::move(function), std::move(non_const_arguments),
std::move(const_arguments)));
}
::zetasql_base::Status AnalyticFunctionCallExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
for (ExprArg* arg : mutable_non_const_arguments()) {
ZETASQL_RETURN_IF_ERROR(
arg->mutable_value_expr()->SetSchemasForEvaluation(params_schemas));
}
for (ExprArg* arg : mutable_const_arguments()) {
ZETASQL_RETURN_IF_ERROR(
arg->mutable_value_expr()->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
std::string AnalyticFunctionCallExpr::DebugInternal(const std::string& indent,
bool verbose) const {
std::vector<std::string> arg_strings;
for (auto arg : GetArgs()) {
std::string indent_child = indent + kIndentSpace;
arg_strings.push_back(
arg->value_expr()->DebugInternal(indent_child, verbose));
}
return absl::StrCat(function()->debug_name(), "(",
absl::StrJoin(arg_strings, ", "), ")");
}
absl::Span<const ExprArg* const> AnalyticFunctionCallExpr::non_const_arguments()
const {
return GetArgs<ExprArg>(kNonConstArgument);
}
absl::Span<ExprArg* const>
AnalyticFunctionCallExpr::mutable_non_const_arguments() {
return GetMutableArgs<ExprArg>(kNonConstArgument);
}
absl::Span<const ExprArg* const> AnalyticFunctionCallExpr::const_arguments()
const {
return GetArgs<ExprArg>(kConstArgument);
}
absl::Span<ExprArg* const> AnalyticFunctionCallExpr::mutable_const_arguments() {
return GetMutableArgs<ExprArg>(kConstArgument);
}
AnalyticFunctionCallExpr::AnalyticFunctionCallExpr(
std::unique_ptr<const AnalyticFunctionBody> function,
std::vector<std::unique_ptr<ValueExpr>> non_const_arguments,
std::vector<std::unique_ptr<ValueExpr>> const_arguments)
: ValueExpr(function->output_type()), function_(std::move(function)) {
std::vector<std::unique_ptr<ExprArg>> non_const_expr_args;
non_const_expr_args.reserve(non_const_arguments.size());
for (auto& non_const_argument : non_const_arguments) {
non_const_expr_args.push_back(
absl::make_unique<ExprArg>(std::move(non_const_argument)));
}
SetArgs<ExprArg>(kNonConstArgument, std::move(non_const_expr_args));
std::vector<std::unique_ptr<ExprArg>> const_expr_args;
const_expr_args.reserve(const_arguments.size());
for (auto& const_argument : const_arguments) {
const_expr_args.push_back(
absl::make_unique<ExprArg>(std::move(const_argument)));
}
SetArgs<ExprArg>(kConstArgument, std::move(const_expr_args));
}
bool AnalyticFunctionCallExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context,
VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
*status =
::zetasql_base::InternalErrorBuilder()
<< "Use NonAggregateAnalyticArg::Eval to evaluate an analytic function";
return false;
}
// -------------------------------------------------------
// IfExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<IfExpr>> IfExpr::Create(
std::unique_ptr<ValueExpr> condition, std::unique_ptr<ValueExpr> true_value,
std::unique_ptr<ValueExpr> false_value) {
ZETASQL_RET_CHECK(true_value->output_type()->Equals(false_value->output_type()));
return absl::WrapUnique(new IfExpr(
std::move(condition), std::move(true_value), std::move(false_value)));
}
::zetasql_base::Status IfExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
ZETASQL_RETURN_IF_ERROR(mutable_join_expr()->SetSchemasForEvaluation(params_schemas));
ZETASQL_RETURN_IF_ERROR(
mutable_true_value()->SetSchemasForEvaluation(params_schemas));
return mutable_false_value()->SetSchemasForEvaluation(params_schemas);
}
bool IfExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
TupleSlot slot;
if (!join_expr()->EvalSimple(params, context, &slot, status)) return false;
if (slot.value() == Bool(true)) {
return true_value()->Eval(params, context, result, status);
} else {
return false_value()->Eval(params, context, result, status);
}
}
std::string IfExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat("IfExpr(",
ArgDebugString({"condition", "true_value", "false_value"},
{k1, k1, k1}, indent, verbose),
")");
}
IfExpr::IfExpr(std::unique_ptr<ValueExpr> condition,
std::unique_ptr<ValueExpr> true_value,
std::unique_ptr<ValueExpr> false_value)
: ValueExpr(true_value->output_type()) {
SetArg(kCondition, absl::make_unique<ExprArg>(std::move(condition)));
SetArg(kTrueValue, absl::make_unique<ExprArg>(std::move(true_value)));
SetArg(kFalseValue, absl::make_unique<ExprArg>(std::move(false_value)));
}
const ValueExpr* IfExpr::join_expr() const {
return GetArg(kCondition)->node()->AsValueExpr();
}
ValueExpr* IfExpr::mutable_join_expr() {
return GetMutableArg(kCondition)->mutable_node()->AsMutableValueExpr();
}
const ValueExpr* IfExpr::true_value() const {
return GetArg(kTrueValue)->node()->AsValueExpr();
}
ValueExpr* IfExpr::mutable_true_value() {
return GetMutableArg(kTrueValue)->mutable_node()->AsMutableValueExpr();
}
const ValueExpr* IfExpr::false_value() const {
return GetArg(kFalseValue)->node()->AsValueExpr();
}
ValueExpr* IfExpr::mutable_false_value() {
return GetMutableArg(kFalseValue)->mutable_node()->AsMutableValueExpr();
}
// -------------------------------------------------------
// LetExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<LetExpr>> LetExpr::Create(
std::vector<std::unique_ptr<ExprArg>> assign,
std::unique_ptr<ValueExpr> body) {
return absl::WrapUnique(new LetExpr(std::move(assign), std::move(body)));
}
::zetasql_base::Status LetExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
// Initialize 'schema_ptrs' with 'params_schemas', then extend 'schema_ptrs'
// with new schemas owned by 'new_schemas'.
std::vector<std::unique_ptr<const TupleSchema>> new_schemas;
new_schemas.reserve(assign().size());
std::vector<const TupleSchema*> schema_ptrs;
schema_ptrs.reserve(params_schemas.size() + assign().size());
schema_ptrs.insert(schema_ptrs.end(), params_schemas.begin(),
params_schemas.end());
for (ExprArg* arg : mutable_assign()) {
ZETASQL_RETURN_IF_ERROR(
arg->mutable_value_expr()->SetSchemasForEvaluation(schema_ptrs));
auto new_schema = absl::make_unique<TupleSchema>(
std::vector<VariableId>{arg->variable()});
schema_ptrs.push_back(new_schema.get());
new_schemas.push_back(std::move(new_schema));
}
return mutable_body()->SetSchemasForEvaluation(schema_ptrs);
}
bool LetExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
// Initialize 'data_ptrs' with 'params', then extend 'data_ptrs' with new
// TupleDatas owned by 'new_datas'. We use a TupleDeque in case one of the
// parameters represents multiple rows (e.g., an array corresponding to a WITH
// table).
auto new_datas =
absl::make_unique<TupleDataDeque>(context->memory_accountant());
std::vector<const TupleData*> data_ptrs;
data_ptrs.reserve(params.size() + assign().size());
data_ptrs.insert(data_ptrs.end(), params.begin(), params.end());
for (const ExprArg* arg : assign()) {
auto new_data = absl::make_unique<TupleData>(/*num_slots=*/1);
if (!arg->value_expr()->EvalSimple(data_ptrs, context,
new_data->mutable_slot(0), status)) {
return false;
}
data_ptrs.push_back(new_data.get());
if (!new_datas->PushBack(std::move(new_data), status)) {
return false;
}
}
return body()->Eval(data_ptrs, context, result, status);
}
std::string LetExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat(
"LetExpr(", ArgDebugString({"assign", "body"}, {kN, k1}, indent, verbose),
")");
}
LetExpr::LetExpr(std::vector<std::unique_ptr<ExprArg>> assign,
std::unique_ptr<ValueExpr> body)
: ValueExpr(body->output_type()) {
SetArgs<ExprArg>(kAssign, std::move(assign));
SetArg(kBody, absl::make_unique<ExprArg>(std::move(body)));
}
absl::Span<const ExprArg* const> LetExpr::assign() const {
return GetArgs<ExprArg>(kAssign);
}
absl::Span<ExprArg* const> LetExpr::mutable_assign() {
return GetMutableArgs<ExprArg>(kAssign);
}
const ValueExpr* LetExpr::body() const {
return GetArg(kBody)->node()->AsValueExpr();
}
ValueExpr* LetExpr::mutable_body() {
return GetMutableArg(kBody)->mutable_node()->AsMutableValueExpr();
}
// -------------------------------------------------------
// DMLValueExpr
// -------------------------------------------------------
// This is a little gross, but implementing this class as an algebra node is
// kind of a hack anyway. One way to make this method better would be to print
// out scan_op_->DebugString() and somehow match up the ResolvedExprs with the
// corresponding ValueExpr::DebugString() in 'resolved_expr_map_'. But that
// doesn't seem to be worth the effort.
std::string DMLValueExpr::DebugInternal(const std::string& /*indent*/,
bool verbose) const {
if (verbose) {
const std::vector<std::string> lines =
absl::StrSplit(resolved_node_->DebugString(), '\n');
std::string ret;
for (const std::string& line : lines) {
absl::StrAppend(&ret, line, "\n");
}
return ret;
} else {
return ResolvedNodeKind_Name(resolved_node_->node_kind());
}
}
DMLValueExpr::DMLValueExpr(
const Table* table, const ArrayType* table_array_type,
const StructType* primary_key_type, const StructType* dml_output_type,
const ResolvedNode* resolved_node, const ResolvedColumnList* column_list,
std::unique_ptr<const ColumnToVariableMapping> column_to_variable_mapping,
std::unique_ptr<const ResolvedScanMap> resolved_scan_map,
std::unique_ptr<const ResolvedExprMap> resolved_expr_map)
: ValueExpr(dml_output_type),
table_(table),
table_array_type_(table_array_type),
primary_key_type_(primary_key_type),
dml_output_type_(dml_output_type),
resolved_node_(resolved_node),
column_list_(column_list),
column_to_variable_mapping_(std::move(column_to_variable_mapping)),
resolved_scan_map_(std::move(resolved_scan_map)),
resolved_expr_map_(std::move(resolved_expr_map)) {}
::zetasql_base::StatusOr<RelationalOp*> DMLValueExpr::LookupResolvedScan(
const ResolvedScan* resolved_scan) const {
const std::unique_ptr<RelationalOp>* relational_op =
zetasql_base::FindOrNull(*resolved_scan_map_, resolved_scan);
ZETASQL_RET_CHECK(relational_op != nullptr);
return relational_op->get();
}
::zetasql_base::StatusOr<ValueExpr*> DMLValueExpr::LookupResolvedExpr(
const ResolvedExpr* resolved_expr) const {
const std::unique_ptr<ValueExpr>* value_expr =
zetasql_base::FindOrNull(*resolved_expr_map_, resolved_expr);
ZETASQL_RET_CHECK(value_expr != nullptr);
return value_expr->get();
}
// Convenience helper to make ValueExpr::Eval() easier to call (at the cost of
// some performance, which doesn't matter for DML ValueExprs since they are just
// for compliance testing).
static ::zetasql_base::StatusOr<Value> EvalExpr(
const ValueExpr& value_expr, absl::Span<const TupleData* const> params,
EvaluationContext* context) {
TupleSlot slot;
::zetasql_base::Status status;
if (!value_expr.EvalSimple(params, context, &slot, &status)) {
return status;
}
return slot.value();
}
::zetasql_base::Status DMLValueExpr::VerifyNumRowsModified(
const ResolvedAssertRowsModified* assert_rows_modified,
absl::Span<const TupleData* const> params, int64_t actual_num_rows_modified,
EvaluationContext* context, bool print_array_elements) const {
if (assert_rows_modified != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* rows_modified,
LookupResolvedExpr(assert_rows_modified->rows()));
ZETASQL_ASSIGN_OR_RETURN(const Value expected_rows_modified,
EvalExpr(*rows_modified, params, context));
ZETASQL_RET_CHECK(expected_rows_modified.type()->IsInt64());
if (expected_rows_modified.is_null()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "ASSERT_ROWS_MODIFIED must have a non-NULL argument";
}
const int64_t expected = expected_rows_modified.int64_value();
if (expected != actual_num_rows_modified) {
const absl::string_view things_modified =
print_array_elements ? "array elements" : "rows";
return zetasql_base::OutOfRangeErrorBuilder()
<< "ASSERT_ROWS_MODIFIED expected " << expected << " "
<< things_modified << " modified, but found "
<< actual_num_rows_modified;
}
}
return zetasql_base::OkStatus();
}
::zetasql_base::StatusOr<std::vector<Value>>
DMLValueExpr::GetScannedTupleAsColumnValues(
const ResolvedColumnList& column_list, const Tuple& t) const {
std::vector<Value> values;
for (const ResolvedColumn& column : column_list) {
ZETASQL_ASSIGN_OR_RETURN(const Value value, GetColumnValue(column, t));
values.push_back(value);
}
return values;
}
::zetasql_base::StatusOr<Value> DMLValueExpr::GetColumnValue(
const ResolvedColumn& column, const Tuple& t) const {
ZETASQL_ASSIGN_OR_RETURN(
const VariableId variable_id,
column_to_variable_mapping_->LookupVariableNameForColumn(&column));
absl::optional<int> slot = t.schema->FindIndexForVariable(variable_id);
ZETASQL_RET_CHECK(slot.has_value()) << variable_id;
return t.data->slot(slot.value()).value();
}
::zetasql_base::Status DMLValueExpr::PopulatePrimaryKeyRowMap(
const std::vector<std::vector<Value>>& original_rows,
absl::string_view duplicate_primary_key_error_prefix,
EvaluationContext* context, PrimaryKeyRowMap* row_map,
bool* has_primary_key) const {
ZETASQL_ASSIGN_OR_RETURN(const absl::optional<std::vector<int>> primary_key_indexes,
GetPrimaryKeyColumnIndexes(context));
*has_primary_key = primary_key_indexes.has_value();
for (int64_t row_number = 0; row_number < original_rows.size(); ++row_number) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
const std::vector<Value>& row_values = original_rows[row_number];
RowNumberAndValues row_number_and_values;
row_number_and_values.row_number = row_number;
row_number_and_values.values = row_values;
ZETASQL_ASSIGN_OR_RETURN(const Value primary_key,
GetPrimaryKeyOrRowNumber(row_number_and_values, context));
auto insert_result =
row_map->insert(std::make_pair(primary_key, row_number_and_values));
if (!insert_result.second) {
return zetasql_base::OutOfRangeErrorBuilder()
<< duplicate_primary_key_error_prefix << " ("
<< primary_key.ShortDebugString() << ")";
}
}
return zetasql_base::OkStatus();
}
::zetasql_base::StatusOr<Value> DMLValueExpr::GetPrimaryKeyOrRowNumber(
const RowNumberAndValues& row_number_and_values, EvaluationContext* context,
bool* has_primary_key) const {
ZETASQL_ASSIGN_OR_RETURN(const absl::optional<std::vector<int>> primary_key_indexes,
GetPrimaryKeyColumnIndexes(context));
if (!primary_key_indexes.has_value()) {
return Value::Int64(row_number_and_values.row_number);
}
// For emulated primary keys, use the emulated value (value of the first
// column) directly instead of making a Struct from the value. This avoids
// breaking tests depending on query plans. We may later remove this special
// case and update the tests.
if (context->options().emulate_primary_keys) {
ZETASQL_RET_CHECK_EQ(primary_key_indexes->size(), 1);
ZETASQL_RET_CHECK_EQ((*primary_key_indexes)[0], 0);
const Value& value = row_number_and_values.values[0];
ZETASQL_RET_CHECK(value.is_valid());
return value;
}
std::vector<Value> key_column_values;
for (int index : *primary_key_indexes) {
const Value& value = row_number_and_values.values[index];
ZETASQL_RET_CHECK(value.is_valid());
key_column_values.push_back(value);
}
return Value::Struct(primary_key_type_, key_column_values);
}
zetasql_base::StatusOr<absl::optional<std::vector<int>>>
DMLValueExpr::GetPrimaryKeyColumnIndexes(EvaluationContext* context) const {
if (is_value_table()) {
return absl::optional<std::vector<int>>();
}
// The algebrizer can opt out of using primary key from the catalog.
if (primary_key_type_ == nullptr) {
return context->options().emulate_primary_keys
? absl::make_optional(std::vector<int>{0})
: absl::optional<std::vector<int>>();
}
ZETASQL_RET_CHECK(!context->options().emulate_primary_keys)
<< "Cannot emulate primary key while using the primary key set in Table";
return table_->PrimaryKey();
}
::zetasql_base::StatusOr<Value> DMLValueExpr::GetDMLOutputValue(
int64_t num_rows_modified,
const std::vector<std::vector<Value>>& dml_output_rows,
EvaluationContext* context) const {
for (const std::vector<Value>& dml_output_row : dml_output_rows) {
for (const Value& value : dml_output_row) {
ZETASQL_RET_CHECK(value.is_valid());
}
}
std::vector<Value> dml_output_values;
for (const std::vector<Value>& dml_output_row : dml_output_rows) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
ZETASQL_RET_CHECK_EQ(dml_output_row.size(), column_list_->size());
if (is_value_table()) {
ZETASQL_RET_CHECK_EQ(1, dml_output_row.size());
dml_output_values.push_back(dml_output_row[0]);
} else {
const Type* element_type = table_array_type_->element_type();
ZETASQL_RET_CHECK(element_type->IsStruct());
const StructType* table_row_type = element_type->AsStruct();
dml_output_values.push_back(
Value::Struct(table_row_type, dml_output_row));
}
}
// Table rows are not ordered.
const Value dml_output_row_array = InternalValue::ArrayNotChecked(
table_array_type_, InternalValue::kIgnoresOrder,
std::move(dml_output_values));
return Value::Struct(dml_output_type_,
std::array<Value, 2>{Value::Int64(num_rows_modified),
dml_output_row_array});
}
// Evaluates 'op' on 'params', then populates 'schema' and 'datas' with the
// corresponding TupleSchema and TupleDatas.
static zetasql_base::Status EvalRelationalOp(
const RelationalOp& op, absl::Span<const TupleData* const> params,
EvaluationContext* context, std::unique_ptr<TupleSchema>* schema,
std::vector<std::unique_ptr<TupleData>>* datas) {
ZETASQL_ASSIGN_OR_RETURN(std::unique_ptr<TupleIterator> iter,
op.CreateIterator(params, /*num_extra_slots=*/0, context));
*schema = absl::make_unique<TupleSchema>(iter->Schema().variables());
// We disable reordering when iterating over relations when processing DML
// statements for backwardws compatibility with the text-based reference
// implementation compliance tests. As another advantage, this effectively
// disables scrambling for simple statements, which makes the tests easier to
// understand.
ZETASQL_RETURN_IF_ERROR(iter->DisableReordering());
while (true) {
const TupleData* data = iter->Next();
if (data == nullptr) {
ZETASQL_RETURN_IF_ERROR(iter->Status());
break;
}
datas->push_back(absl::make_unique<TupleData>(*data));
}
return zetasql_base::OkStatus();
}
// -------------------------------------------------------
// DMLDeleteValueExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<DMLDeleteValueExpr>>
DMLDeleteValueExpr::Create(
const Table* table, const ArrayType* table_array_type,
const StructType* primary_key_type, const StructType* dml_output_type,
const ResolvedDeleteStmt* resolved_node,
const ResolvedColumnList* column_list,
std::unique_ptr<const ColumnToVariableMapping> column_to_variable_mapping,
std::unique_ptr<const ResolvedScanMap> resolved_scan_map,
std::unique_ptr<const ResolvedExprMap> resolved_expr_map) {
return absl::WrapUnique(new DMLDeleteValueExpr(
table, table_array_type, primary_key_type, dml_output_type, resolved_node,
column_list, std::move(column_to_variable_mapping),
std::move(resolved_scan_map), std::move(resolved_expr_map)));
}
::zetasql_base::Status DMLDeleteValueExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
if (stmt()->assert_rows_modified() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(
ValueExpr * rows,
LookupResolvedExpr(stmt()->assert_rows_modified()->rows()));
ZETASQL_RETURN_IF_ERROR(rows->SetSchemasForEvaluation(params_schemas));
}
ZETASQL_ASSIGN_OR_RETURN(RelationalOp * scan,
LookupResolvedScan(stmt()->table_scan()));
ZETASQL_RETURN_IF_ERROR(scan->SetSchemasForEvaluation(params_schemas));
const std::unique_ptr<const TupleSchema> scan_schema =
scan->CreateOutputSchema();
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * where_expr,
LookupResolvedExpr(stmt()->where_expr()));
return where_expr->SetSchemasForEvaluation(
ConcatSpans(params_schemas, {scan_schema.get()}));
}
::zetasql_base::StatusOr<Value> DMLDeleteValueExpr::Eval(
absl::Span<const TupleData* const> params,
EvaluationContext* context) const {
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* where_expr,
LookupResolvedExpr(stmt()->where_expr()));
int64_t num_rows_deleted = 0;
std::vector<std::vector<Value>> dml_output_rows;
ZETASQL_ASSIGN_OR_RETURN(const RelationalOp* relational_op,
LookupResolvedScan(stmt()->table_scan()));
std::unique_ptr<TupleSchema> tuple_schema;
std::vector<std::unique_ptr<TupleData>> tuple_datas;
ZETASQL_RETURN_IF_ERROR(EvalRelationalOp(*relational_op, params, context,
&tuple_schema, &tuple_datas));
for (const std::unique_ptr<TupleData>& tuple_data : tuple_datas) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
const Tuple tuple(tuple_schema.get(), tuple_data.get());
ZETASQL_ASSIGN_OR_RETURN(std::vector<Value> tuple_as_values,
GetScannedTupleAsColumnValues(*column_list_, tuple));
// The WHERE clause can reference column values and statement parameters.
ZETASQL_ASSIGN_OR_RETURN(
const Value where_value,
EvalExpr(*where_expr, ConcatSpans(params, {tuple.data}), context));
const bool deleted = (where_value == Bool(true));
if (deleted) {
++num_rows_deleted;
if (!context->options().return_all_rows_for_dml) {
dml_output_rows.push_back(tuple_as_values);
}
} else {
// In all_rows mode,the output contains the remaining rows.
if (context->options().return_all_rows_for_dml) {
dml_output_rows.push_back(tuple_as_values);
}
}
}
ZETASQL_RETURN_IF_ERROR(VerifyNumRowsModified(stmt()->assert_rows_modified(), params,
num_rows_deleted, context));
ZETASQL_RETURN_IF_ERROR(resolved_node_->CheckFieldsAccessed());
return GetDMLOutputValue(num_rows_deleted, dml_output_rows, context);
}
DMLDeleteValueExpr::DMLDeleteValueExpr(
const Table* table, const ArrayType* table_array_type,
const StructType* primary_key_type, const StructType* dml_output_type,
const ResolvedDeleteStmt* resolved_node,
const ResolvedColumnList* column_list,
std::unique_ptr<const ColumnToVariableMapping> column_to_variable_mapping,
std::unique_ptr<const ResolvedScanMap> resolved_scan_map,
std::unique_ptr<const ResolvedExprMap> resolved_expr_map)
: DMLValueExpr(table, table_array_type, primary_key_type, dml_output_type,
resolved_node, column_list,
std::move(column_to_variable_mapping),
std::move(resolved_scan_map), std::move(resolved_expr_map)) {
}
// -------------------------------------------------------
// DMLUpdateValueExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<DMLUpdateValueExpr>>
DMLUpdateValueExpr::Create(
const Table* table, const ArrayType* table_array_type,
const StructType* primary_key_type, const StructType* dml_output_type,
const ResolvedUpdateStmt* resolved_node,
const ResolvedColumnList* column_list,
std::unique_ptr<const ColumnToVariableMapping> column_to_variable_mapping,
std::unique_ptr<const ResolvedScanMap> resolved_scan_map,
std::unique_ptr<const ResolvedExprMap> resolved_expr_map) {
return absl::WrapUnique(new DMLUpdateValueExpr(
table, table_array_type, primary_key_type, dml_output_type, resolved_node,
column_list, std::move(column_to_variable_mapping),
std::move(resolved_scan_map), std::move(resolved_expr_map)));
}
::zetasql_base::Status DMLUpdateValueExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
ZETASQL_ASSIGN_OR_RETURN(RelationalOp * table_scan,
LookupResolvedScan(stmt()->table_scan()));
ZETASQL_RETURN_IF_ERROR(table_scan->SetSchemasForEvaluation(params_schemas));
const std::unique_ptr<const TupleSchema> table_scan_schema =
table_scan->CreateOutputSchema();
std::unique_ptr<const TupleSchema> from_scan_schema;
if (stmt()->from_scan() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(RelationalOp * from,
LookupResolvedScan(stmt()->from_scan()));
ZETASQL_RETURN_IF_ERROR(from->SetSchemasForEvaluation(params_schemas));
from_scan_schema = from->CreateOutputSchema();
}
std::vector<const TupleSchema*> joined_schemas =
ConcatSpans(params_schemas, {table_scan_schema.get()});
if (from_scan_schema != nullptr) {
joined_schemas =
ConcatSpans(absl::Span<const TupleSchema* const>(joined_schemas),
{from_scan_schema.get()});
}
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * where_expr,
LookupResolvedExpr(stmt()->where_expr()));
ZETASQL_RETURN_IF_ERROR(where_expr->SetSchemasForEvaluation(joined_schemas));
for (const std::unique_ptr<const ResolvedUpdateItem>& update_item :
stmt()->update_item_list()) {
ZETASQL_RETURN_IF_ERROR(
SetSchemasForEvaluationOfUpdateItem(update_item.get(), joined_schemas));
}
if (stmt()->assert_rows_modified() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(
ValueExpr * rows,
LookupResolvedExpr(stmt()->assert_rows_modified()->rows()));
ZETASQL_RETURN_IF_ERROR(rows->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
::zetasql_base::StatusOr<Value> DMLUpdateValueExpr::Eval(
absl::Span<const TupleData* const> params,
EvaluationContext* context) const {
// Schema of tuples from the from scan. NULL if there is no from scan.
std::unique_ptr<TupleSchema> from_schema;
// Consists of one tuple per row of the table in the from scan. NULL if there
// is no from scan.
std::unique_ptr<std::vector<std::unique_ptr<TupleData>>> from_tuples;
if (stmt()->from_scan() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(const RelationalOp* relational_op,
LookupResolvedScan(stmt()->from_scan()));
std::unique_ptr<TupleSchema> from_schema;
from_tuples = absl::make_unique<std::vector<std::unique_ptr<TupleData>>>();
ZETASQL_RETURN_IF_ERROR(EvalRelationalOp(*relational_op, params, context,
&from_schema, from_tuples.get()));
}
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* where_expr,
LookupResolvedExpr(stmt()->where_expr()));
int64_t num_rows_modified = 0;
std::vector<std::vector<Value>> dml_output_rows;
ZETASQL_ASSIGN_OR_RETURN(const RelationalOp* relational_op,
LookupResolvedScan(stmt()->table_scan()));
std::unique_ptr<TupleSchema> tuple_schema;
std::vector<std::unique_ptr<TupleData>> tuples;
ZETASQL_RETURN_IF_ERROR(EvalRelationalOp(*relational_op, params, context,
&tuple_schema, &tuples));
for (const std::unique_ptr<TupleData>& tuple_data : tuples) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
const Tuple tuple(tuple_schema.get(), tuple_data.get());
std::vector<const TupleData*> joined_tuple_datas;
ZETASQL_RETURN_IF_ERROR(GetJoinedTupleDatas(params, tuple_data.get(),
from_tuples.get(), where_expr, context,
&joined_tuple_datas));
if (joined_tuple_datas.empty()) {
ZETASQL_ASSIGN_OR_RETURN(const std::vector<Value> dml_output_row,
GetScannedTupleAsColumnValues(*column_list_, tuple));
if (context->options().return_all_rows_for_dml) {
dml_output_rows.push_back(dml_output_row);
}
continue;
}
++num_rows_modified;
UpdateMap update_map;
for (const std::unique_ptr<const ResolvedUpdateItem>& update_item :
stmt()->update_item_list()) {
ResolvedColumn update_column, update_target_column;
std::vector<UpdatePathComponent> prefix_components;
ZETASQL_RETURN_IF_ERROR(AddToUpdateMap(
update_item.get(), joined_tuple_datas, context, &update_column,
&update_target_column, &prefix_components, &update_map));
}
ZETASQL_ASSIGN_OR_RETURN(std::vector<Value> dml_output_row,
GetDMLOutputRow(tuple, update_map, context));
dml_output_rows.push_back(dml_output_row);
}
// Verify that there are no duplicate primary keys in the modified table.
absl::string_view duplicate_primary_key_error_prefix =
"Modification resulted in duplicate primary key";
PrimaryKeyRowMap row_map;
bool has_primary_key;
ZETASQL_RETURN_IF_ERROR(PopulatePrimaryKeyRowMap(
dml_output_rows, duplicate_primary_key_error_prefix, context, &row_map,
&has_primary_key));
ZETASQL_RETURN_IF_ERROR(VerifyNumRowsModified(stmt()->assert_rows_modified(), params,
num_rows_modified, context));
ZETASQL_RETURN_IF_ERROR(resolved_node_->CheckFieldsAccessed());
return GetDMLOutputValue(num_rows_modified, dml_output_rows, context);
}
::zetasql_base::StatusOr<Value> DMLUpdateValueExpr::UpdateNode::GetNewValue(
const Value& original_value) const {
if (is_leaf()) return leaf_value();
switch (original_value.type_kind()) {
case TYPE_STRUCT: {
if (original_value.is_null()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot set field of NULL "
<< original_value.type()->TypeName(
ProductMode::PRODUCT_EXTERNAL);
}
std::vector<Value> new_fields = original_value.fields();
for (const auto& entry : child_map()) {
const UpdatePathComponent& component = entry.first;
const UpdateNode& update_node = *entry.second;
ZETASQL_RET_CHECK(component.kind() == UpdatePathComponent::Kind::STRUCT_FIELD)
<< "Unexpected non-struct UpdatePathComponent::Kind in "
<< "GetNewValue(): "
<< UpdatePathComponent::GetKindString(component.kind());
const int64_t field_idx = component.struct_field_index();
ZETASQL_ASSIGN_OR_RETURN(const Value field_value,
update_node.GetNewValue(new_fields[field_idx]));
new_fields[field_idx] = field_value;
}
return Value::Struct(original_value.type()->AsStruct(), new_fields);
}
case TYPE_PROTO:
return GetNewProtoValue(original_value);
case TYPE_ARRAY: {
if (original_value.is_null()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot use [] to modify a NULL array of type "
<< original_value.type()->TypeName(
ProductMode::PRODUCT_EXTERNAL);
}
std::vector<Value> new_elements = original_value.elements();
for (const auto& entry : child_map()) {
const UpdatePathComponent& component = entry.first;
const UpdateNode& update_node = *entry.second;
ZETASQL_RET_CHECK(component.kind() == UpdatePathComponent::Kind::ARRAY_OFFSET)
<< "Unexpected non-struct UpdatePathComponent::Kind in "
<< "GetNewValue(): "
<< UpdatePathComponent::GetKindString(component.kind());
const int64_t offset = component.array_offset();
if (offset < 0 || offset >= new_elements.size()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot SET array offset " << offset << " of an "
<< original_value.type()->TypeName(
ProductMode::PRODUCT_EXTERNAL)
<< " of size " << new_elements.size();
}
ZETASQL_ASSIGN_OR_RETURN(const Value element_value,
update_node.GetNewValue(new_elements[offset]));
new_elements[offset] = element_value;
}
return Value::Array(original_value.type()->AsArray(), new_elements);
}
default:
ZETASQL_RET_CHECK_FAIL()
<< "Unexpected type kind for GetNewValue() on an internal "
<< "UpdateNode: " << TypeKind_Name(original_value.type_kind());
}
}
::zetasql_base::StatusOr<Value> DMLUpdateValueExpr::UpdateNode::GetNewProtoValue(
const Value& original_value) const {
ZETASQL_RET_CHECK_EQ(original_value.type_kind(), TYPE_PROTO);
if (original_value.is_null()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot set field of NULL "
<< original_value.type()->TypeName(ProductMode::PRODUCT_EXTERNAL);
}
// TODO: Serializing and deserializing the protos over and over seems
// wasteful, but this code is only for compliance tests, so this is fine.
TypeFactory type_factory;
google::protobuf::DynamicMessageFactory message_factory;
std::unique_ptr<google::protobuf::Message> new_message =
absl::WrapUnique(original_value.ToMessage(&message_factory));
for (const auto& entry : child_map()) {
const UpdatePathComponent& component = entry.first;
const UpdateNode& update_node = *entry.second;
ZETASQL_RET_CHECK(component.kind() == UpdatePathComponent::Kind::PROTO_FIELD)
<< "Unexpected non-proto UpdatePathComponent::Kind in "
<< "GetNewProtoValue(): "
<< UpdatePathComponent::GetKindString(component.kind());
const google::protobuf::FieldDescriptor* field_descriptor =
component.proto_field_descriptor();
const Type* field_type;
ZETASQL_RETURN_IF_ERROR(
type_factory.GetProtoFieldType(field_descriptor, &field_type));
// Read the original value of the field (as an array if it is repeated).
Value original_field_value;
ZETASQL_RETURN_IF_ERROR(ProtoFieldToValue(*new_message, field_descriptor,
/*index=*/-1, field_type,
/*use_wire_format_annotations=*/false,
&original_field_value));
// Compute the new value of the field.
ZETASQL_ASSIGN_OR_RETURN(const Value new_field_value,
update_node.GetNewValue(original_field_value));
// Overwrite the value of the field in 'new_message'.
if (field_descriptor->is_required() && new_field_value.is_null()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot clear required proto field "
<< field_descriptor->full_name();
}
ZETASQL_RET_CHECK_EQ(field_descriptor->is_repeated(),
new_field_value.type_kind() == TYPE_ARRAY);
if (field_descriptor->is_repeated() && !new_field_value.is_null()) {
for (const Value& value : new_field_value.elements()) {
if (value.is_null()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot store a NULL element in repeated proto field "
<< field_descriptor->full_name();
}
}
}
new_message->GetReflection()->ClearField(new_message.get(),
field_descriptor);
ZETASQL_RETURN_IF_ERROR(
MergeValueToProtoField(new_field_value, field_descriptor,
/*use_wire_format_annotations=*/false,
&message_factory, new_message.get()));
}
return Value::Proto(original_value.type()->AsProto(),
new_message->SerializeAsString());
}
DMLUpdateValueExpr::DMLUpdateValueExpr(
const Table* table, const ArrayType* table_array_type,
const StructType* primary_key_type, const StructType* dml_output_type,
const ResolvedUpdateStmt* resolved_node,
const ResolvedColumnList* column_list,
std::unique_ptr<const ColumnToVariableMapping> column_to_variable_mapping,
std::unique_ptr<const ResolvedScanMap> resolved_scan_map,
std::unique_ptr<const ResolvedExprMap> resolved_expr_map)
: DMLValueExpr(table, table_array_type, primary_key_type, dml_output_type,
resolved_node, column_list,
std::move(column_to_variable_mapping),
std::move(resolved_scan_map), std::move(resolved_expr_map)) {
}
::zetasql_base::Status DMLUpdateValueExpr::SetSchemasForEvaluationOfUpdateItem(
const ResolvedUpdateItem* update_item,
absl::Span<const TupleSchema* const> params_schemas) {
for (const std::unique_ptr<const ResolvedUpdateArrayItem>& update_array_item :
update_item->array_update_list()) {
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * offset_expr,
LookupResolvedExpr(update_array_item->offset()));
ZETASQL_RETURN_IF_ERROR(offset_expr->SetSchemasForEvaluation(params_schemas));
ZETASQL_RETURN_IF_ERROR(SetSchemasForEvaluationOfUpdateItem(
update_array_item->update_item(), params_schemas));
}
if (update_item->array_update_list().empty()) {
if (update_item->set_value() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * leaf_value_expr,
LookupResolvedExpr(update_item->set_value()->value()));
return leaf_value_expr->SetSchemasForEvaluation(params_schemas);
}
ZETASQL_RET_CHECK(!update_item->delete_list().empty() ||
!update_item->update_list().empty() ||
!update_item->insert_list().empty());
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * update_target_expr,
LookupResolvedExpr(update_item->target()));
ZETASQL_RETURN_IF_ERROR(
update_target_expr->SetSchemasForEvaluation(params_schemas));
const ResolvedColumn& element_column =
update_item->element_column()->column();
for (const std::unique_ptr<const ResolvedDeleteStmt>& nested_delete :
update_item->delete_list()) {
ZETASQL_RETURN_IF_ERROR(SetSchemasForEvaluationOfNestedDelete(
nested_delete.get(), element_column, params_schemas));
}
for (const std::unique_ptr<const ResolvedUpdateStmt>& nested_update :
update_item->update_list()) {
ZETASQL_RETURN_IF_ERROR(SetSchemasForEvaluationOfNestedUpdate(
nested_update.get(), element_column, params_schemas));
}
for (const std::unique_ptr<const ResolvedInsertStmt>& nested_insert :
update_item->insert_list()) {
ZETASQL_RETURN_IF_ERROR(SetSchemasForEvaluationOfNestedInsert(nested_insert.get(),
params_schemas));
}
}
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLUpdateValueExpr::SetSchemasForEvaluationOfNestedDelete(
const ResolvedDeleteStmt* nested_delete,
const ResolvedColumn& element_column,
absl::Span<const TupleSchema* const> params_schemas) {
ZETASQL_ASSIGN_OR_RETURN(const VariableId element_column_variable_id,
column_to_variable_mapping_->LookupVariableNameForColumn(
&element_column));
std::vector<VariableId> new_variables;
new_variables.push_back(element_column_variable_id);
if (nested_delete->array_offset_column() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(const VariableId array_offset_column_variable_id,
column_to_variable_mapping_->LookupVariableNameForColumn(
&nested_delete->array_offset_column()->column()));
new_variables.push_back(array_offset_column_variable_id);
}
const TupleSchema new_schema(new_variables);
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * where_expr,
LookupResolvedExpr(nested_delete->where_expr()));
ZETASQL_RETURN_IF_ERROR(where_expr->SetSchemasForEvaluation(
ConcatSpans(params_schemas, {&new_schema})));
if (nested_delete->assert_rows_modified() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(
ValueExpr * rows_expr,
LookupResolvedExpr(nested_delete->assert_rows_modified()->rows()));
ZETASQL_RETURN_IF_ERROR(rows_expr->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLUpdateValueExpr::SetSchemasForEvaluationOfNestedUpdate(
const ResolvedUpdateStmt* nested_update,
const ResolvedColumn& element_column,
absl::Span<const TupleSchema* const> params_schemas) {
ZETASQL_ASSIGN_OR_RETURN(const VariableId element_column_variable_id,
column_to_variable_mapping_->LookupVariableNameForColumn(
&element_column));
std::vector<VariableId> new_variables;
new_variables.push_back(element_column_variable_id);
if (nested_update->array_offset_column() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(const VariableId array_offset_column_variable_id,
column_to_variable_mapping_->LookupVariableNameForColumn(
&nested_update->array_offset_column()->column()));
new_variables.push_back(array_offset_column_variable_id);
}
const TupleSchema new_schema(new_variables);
const std::vector<const TupleSchema*> new_params_schemas =
ConcatSpans(params_schemas, {&new_schema});
for (const std::unique_ptr<const ResolvedUpdateItem>& update_item :
nested_update->update_item_list()) {
ZETASQL_RETURN_IF_ERROR(SetSchemasForEvaluationOfUpdateItem(update_item.get(),
new_params_schemas));
}
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * where_expr,
LookupResolvedExpr(nested_update->where_expr()));
ZETASQL_RETURN_IF_ERROR(where_expr->SetSchemasForEvaluation(new_params_schemas));
if (nested_update->assert_rows_modified() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(
ValueExpr * rows_expr,
LookupResolvedExpr(nested_update->assert_rows_modified()->rows()));
ZETASQL_RETURN_IF_ERROR(rows_expr->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLUpdateValueExpr::SetSchemasForEvaluationOfNestedInsert(
const ResolvedInsertStmt* nested_insert,
absl::Span<const TupleSchema* const> params_schemas) {
if (nested_insert->query() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(RelationalOp * query,
LookupResolvedScan(nested_insert->query()));
ZETASQL_RETURN_IF_ERROR(query->SetSchemasForEvaluation(params_schemas));
} else {
for (const std::unique_ptr<const ResolvedInsertRow>& insert_row :
nested_insert->row_list()) {
for (const std::unique_ptr<const ResolvedDMLValue>& dml_value :
insert_row->value_list()) {
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * value_expr,
LookupResolvedExpr(dml_value->value()));
ZETASQL_RETURN_IF_ERROR(value_expr->SetSchemasForEvaluation(params_schemas));
}
}
}
if (nested_insert->assert_rows_modified() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(
ValueExpr * rows_expr,
LookupResolvedExpr(nested_insert->assert_rows_modified()->rows()));
ZETASQL_RETURN_IF_ERROR(rows_expr->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLUpdateValueExpr::GetJoinedTupleDatas(
absl::Span<const TupleData* const> params, const TupleData* left_tuple,
const std::vector<std::unique_ptr<TupleData>>* right_tuples,
const ValueExpr* where_expr, EvaluationContext* context,
std::vector<const TupleData*>* joined_tuple_datas) const {
joined_tuple_datas->clear();
if (right_tuples == nullptr) {
ZETASQL_ASSIGN_OR_RETURN(
const Value where_value,
EvalExpr(*where_expr, ConcatSpans(params, {left_tuple}), context));
if (where_value == Bool(true)) {
*joined_tuple_datas = ConcatSpans(params, {left_tuple});
}
return zetasql_base::OkStatus();
}
for (const std::unique_ptr<TupleData>& right_tuple : *right_tuples) {
const std::vector<const TupleData*> candidate_joined_tuple_datas =
ConcatSpans(params, {left_tuple, right_tuple.get()});
ZETASQL_ASSIGN_OR_RETURN(
const Value where_value,
EvalExpr(*where_expr, candidate_joined_tuple_datas, context));
if (where_value == Bool(true)) {
if (!joined_tuple_datas->empty()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "UPDATE with join requires that each row of the table being "
<< "updated correspond with at most one joined row that matches "
<< "the WHERE clause";
}
*joined_tuple_datas = candidate_joined_tuple_datas;
}
}
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLUpdateValueExpr::AddToUpdateMap(
const ResolvedUpdateItem* update_item,
absl::Span<const TupleData* const> tuples_for_row,
EvaluationContext* context, ResolvedColumn* update_column,
ResolvedColumn* update_target_column,
std::vector<UpdatePathComponent>* prefix_components,
UpdateMap* update_map) const {
// Extract components from 'update_item->target()' and append them to
// 'prefix_components' for the duration of this function call.
std::vector<UpdatePathComponent> new_components;
ZETASQL_RETURN_IF_ERROR(PopulateUpdatePathComponents(
update_item->target(), update_target_column, &new_components));
if (prefix_components->empty()) {
*update_column = *update_target_column;
}
prefix_components->insert(prefix_components->end(), new_components.begin(),
new_components.end());
auto new_components_cleanup =
zetasql_base::MakeCleanup([prefix_components, &new_components] {
for (int i = 0; i < new_components.size(); ++i) {
prefix_components->pop_back();
}
});
// Iterate over each ResolvedUpdateArrayItem (if there are any) and recurse
// for each one.
std::unordered_set<int64_t> used_array_offsets;
for (const std::unique_ptr<const ResolvedUpdateArrayItem>& update_array_item :
update_item->array_update_list()) {
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* offset_expr,
LookupResolvedExpr(update_array_item->offset()));
ZETASQL_ASSIGN_OR_RETURN(const Value offset_value,
EvalExpr(*offset_expr, tuples_for_row, context));
ZETASQL_RET_CHECK_EQ(offset_value.type_kind(), TYPE_INT64);
if (offset_value.is_null()) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot SET a NULL offset of an "
<< update_item->target()->type()->TypeName(
ProductMode::PRODUCT_EXTERNAL);
}
const int64_t offset_int64 = offset_value.int64_value();
if (!zetasql_base::InsertIfNotPresent(&used_array_offsets, offset_int64)) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot perform multiple updates to offset " << offset_int64
<< " of an "
<< update_item->target()->type()->TypeName(
ProductMode::PRODUCT_EXTERNAL);
}
prefix_components->emplace_back(/*is_struct_field_index=*/false,
offset_int64);
auto cleanup = zetasql_base::MakeCleanup(
[prefix_components] { prefix_components->pop_back(); });
ResolvedColumn update_array_target_column;
ZETASQL_RETURN_IF_ERROR(AddToUpdateMap(update_array_item->update_item(),
tuples_for_row, context, update_column,
&update_array_target_column,
prefix_components, update_map));
ZETASQL_RET_CHECK(update_array_target_column ==
update_item->element_column()->column());
}
// If there are no ResolvedUpdateArrayItem children, then create the path of
// UpdateNodes corresponding to the chain of
// ResolvedUpdateItem->ResolvedUpdateArrayItem->...->ResolvedUpdateItem nodes
// that ends at 'update_item'.
if (update_item->array_update_list().empty()) {
const bool first_update_node_is_leaf = prefix_components->empty();
auto emplace_result = update_map->emplace(
*update_column,
absl::make_unique<UpdateNode>(first_update_node_is_leaf));
UpdateNode& first_update_node = *emplace_result.first->second;
// If this fails, the analyzer allowed conflicting updates.
ZETASQL_RET_CHECK_EQ(first_update_node_is_leaf, first_update_node.is_leaf());
ZETASQL_ASSIGN_OR_RETURN(const Value leaf_value,
GetLeafValue(update_item, tuples_for_row, context));
ZETASQL_RETURN_IF_ERROR(AddToUpdateNode(prefix_components->begin(),
prefix_components->end(), leaf_value,
&first_update_node));
}
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLUpdateValueExpr::PopulateUpdatePathComponents(
const ResolvedExpr* update_target, ResolvedColumn* column,
std::vector<UpdatePathComponent>* components) const {
switch (update_target->node_kind()) {
case RESOLVED_COLUMN_REF:
*column = update_target->GetAs<ResolvedColumnRef>()->column();
return zetasql_base::OkStatus();
case RESOLVED_GET_STRUCT_FIELD: {
const auto* get_struct_field =
update_target->GetAs<ResolvedGetStructField>();
ZETASQL_RETURN_IF_ERROR(PopulateUpdatePathComponents(get_struct_field->expr(),
column, components));
components->emplace_back(/*is_struct_field_index=*/true,
get_struct_field->field_idx());
return zetasql_base::OkStatus();
}
case RESOLVED_GET_PROTO_FIELD: {
const auto* get_proto_field =
update_target->GetAs<ResolvedGetProtoField>();
ZETASQL_RETURN_IF_ERROR(PopulateUpdatePathComponents(get_proto_field->expr(),
column, components));
components->emplace_back(get_proto_field->field_descriptor());
return zetasql_base::OkStatus();
}
default:
ZETASQL_RET_CHECK_FAIL()
<< "Unsupported node kind in PopulateUpdatePathComponents(): "
<< ResolvedNodeKind_Name(update_target->node_kind());
}
}
::zetasql_base::Status DMLUpdateValueExpr::AddToUpdateNode(
std::vector<UpdatePathComponent>::const_iterator start_component,
std::vector<UpdatePathComponent>::const_iterator end_component,
const Value& leaf_value, UpdateNode* update_node) const {
ZETASQL_RET_CHECK_EQ(update_node->is_leaf(), start_component == end_component);
if (update_node->is_leaf()) {
*update_node->mutable_leaf_value() = leaf_value;
return zetasql_base::OkStatus();
}
UpdateNode::ChildMap* child_map = update_node->mutable_child_map();
const UpdatePathComponent& next_component = *start_component;
++start_component;
// Sanity check that we aren't trying to add two different
// UpdatePathComponent::Kinds to 'child_map'.
if (!child_map->empty()) {
const UpdatePathComponent::Kind expected_kind =
child_map->begin()->first.kind();
ZETASQL_RET_CHECK(next_component.kind() == expected_kind)
<< "AddToUpdateNode() expected UpdatePathComponent::Kind "
<< UpdatePathComponent::GetKindString(expected_kind) << ", but found "
<< UpdatePathComponent::GetKindString(next_component.kind());
}
// Get the UpdateNode child corresponding to 'next_component', adding it to
// 'child_map' if necessary.
const bool is_leaf = (start_component == end_component);
auto emplace_result = child_map->emplace(
next_component, absl::make_unique<UpdateNode>(is_leaf));
UpdateNode& next_update_node = *emplace_result.first->second;
// If this fails, the analyzer allowed conflicting updates.
ZETASQL_RET_CHECK_EQ(is_leaf, next_update_node.is_leaf());
return AddToUpdateNode(start_component, end_component, leaf_value,
&next_update_node);
}
::zetasql_base::StatusOr<Value> DMLUpdateValueExpr::GetLeafValue(
const ResolvedUpdateItem* update_item,
absl::Span<const TupleData* const> tuples_for_row,
EvaluationContext* context) const {
ZETASQL_RET_CHECK(update_item->array_update_list().empty());
if (update_item->set_value() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* leaf_value_expr,
LookupResolvedExpr(update_item->set_value()->value()));
return EvalExpr(*leaf_value_expr, tuples_for_row, context);
}
ZETASQL_RET_CHECK(!update_item->delete_list().empty() ||
!update_item->update_list().empty() ||
!update_item->insert_list().empty());
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* update_target_expr,
LookupResolvedExpr(update_item->target()));
ZETASQL_ASSIGN_OR_RETURN(const Value original_value,
EvalExpr(*update_target_expr, tuples_for_row, context));
ZETASQL_RET_CHECK(original_value.type()->IsArray());
if (original_value.is_null()) {
absl::string_view statement_type =
!update_item->delete_list().empty()
? "DELETE"
: (!update_item->update_list().empty() ? "UPDATE" : "INSERT");
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot execute a nested " << statement_type
<< " statement on a NULL array value";
}
const std::vector<Value>& original_elements = original_value.elements();
const ResolvedColumn& element_column =
update_item->element_column()->column();
std::vector<UpdatedElement> updated_elements(original_elements.size());
for (const std::unique_ptr<const ResolvedDeleteStmt>& nested_delete :
update_item->delete_list()) {
ZETASQL_RETURN_IF_ERROR(ProcessNestedDelete(nested_delete.get(), tuples_for_row,
element_column, original_elements,
context, &updated_elements));
}
for (const std::unique_ptr<const ResolvedUpdateStmt>& nested_update :
update_item->update_list()) {
ZETASQL_RETURN_IF_ERROR(ProcessNestedUpdate(nested_update.get(), tuples_for_row,
element_column, original_elements,
context, &updated_elements));
}
for (const std::unique_ptr<const ResolvedInsertStmt>& nested_insert :
update_item->insert_list()) {
ZETASQL_RETURN_IF_ERROR(ProcessNestedInsert(nested_insert.get(), tuples_for_row,
original_elements, context,
&updated_elements));
}
std::vector<Value> new_elements;
ZETASQL_RET_CHECK_GE(updated_elements.size(), original_elements.size());
for (int i = 0; i < updated_elements.size(); ++i) {
const UpdatedElement& updated_element = updated_elements[i];
switch (updated_element.kind()) {
case UpdatedElement::Kind::UNMODIFIED:
new_elements.push_back(original_elements[i]);
break;
case UpdatedElement::Kind::DELETED:
// Nothing to do.
break;
case UpdatedElement::Kind::MODIFIED:
new_elements.push_back(updated_element.new_value());
break;
}
}
return Value::Array(original_value.type()->AsArray(), new_elements);
}
::zetasql_base::StatusOr<std::vector<Value>> DMLUpdateValueExpr::GetDMLOutputRow(
const Tuple& tuple, const UpdateMap& update_map,
EvaluationContext* context) const {
absl::flat_hash_set<int> key_index_set;
ZETASQL_ASSIGN_OR_RETURN(const absl::optional<std::vector<int>> key_indexes,
GetPrimaryKeyColumnIndexes(context));
if (key_indexes.has_value()) {
key_index_set.insert(key_indexes->begin(), key_indexes->end());
}
std::vector<Value> dml_output_row;
for (int i = 0; i < column_list_->size(); ++i) {
const ResolvedColumn& column = (*column_list_)[i];
ZETASQL_ASSIGN_OR_RETURN(const Value original_value, GetColumnValue(column, tuple));
const std::unique_ptr<UpdateNode>* update_node_or_null =
zetasql_base::FindOrNull(update_map, column);
if (update_node_or_null == nullptr) {
// 'column' was not modified by the statement.
dml_output_row.push_back(original_value);
} else {
ZETASQL_ASSIGN_OR_RETURN(const Value new_value,
(*update_node_or_null)->GetNewValue(original_value));
if (key_index_set.contains(i)) {
// Attempting to modify a primary key column.
const LanguageOptions& language_options = context->GetLanguageOptions();
if (language_options.LanguageFeatureEnabled(
FEATURE_DISALLOW_PRIMARY_KEY_UPDATES)) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot modify a primary key column with UPDATE";
}
if (new_value.is_null() && language_options.LanguageFeatureEnabled(
FEATURE_DISALLOW_NULL_PRIMARY_KEYS)) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot set a primary key column to NULL with UPDATE";
}
}
dml_output_row.push_back(new_value);
}
}
return dml_output_row;
}
::zetasql_base::Status DMLUpdateValueExpr::ProcessNestedDelete(
const ResolvedDeleteStmt* nested_delete,
absl::Span<const TupleData* const> tuples_for_row,
const ResolvedColumn& element_column,
const std::vector<Value>& original_elements, EvaluationContext* context,
std::vector<UpdatedElement>* new_elements) const {
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* where_expr,
LookupResolvedExpr(nested_delete->where_expr()));
int64_t num_values_deleted = 0;
ZETASQL_RET_CHECK_EQ(original_elements.size(), new_elements->size());
for (int i = 0; i < original_elements.size(); ++i) {
const Value& original_value = original_elements[i];
UpdatedElement& updated_element = (*new_elements)[i];
switch (updated_element.kind()) {
case UpdatedElement::Kind::UNMODIFIED: {
// As in SetSchemasForEvaluationOfNestedDelete(), first we put the
// original value, then maybe the offset.
std::vector<Value> new_values_for_where = {original_value};
if (nested_delete->array_offset_column() != nullptr) {
const Value array_offset_value = values::Int64(i);
new_values_for_where.push_back(array_offset_value);
}
const TupleData extra_data_for_where =
CreateTupleDataFromValues(new_values_for_where);
ZETASQL_ASSIGN_OR_RETURN(
const Value where_value,
EvalExpr(*where_expr,
ConcatSpans(tuples_for_row, {&extra_data_for_where}),
context));
if (where_value == Bool(true)) {
updated_element.delete_value();
++num_values_deleted;
}
break;
}
case UpdatedElement::Kind::DELETED:
// Nothing to do. (This can happen if we apply two nested deletes to the
// same array.)
break;
case UpdatedElement::Kind::MODIFIED:
ZETASQL_RET_CHECK_FAIL()
<< "Unexpected MODIFIED UpdatedElement in ProcessNestedDelete()";
}
}
return VerifyNumRowsModified(nested_delete->assert_rows_modified(),
tuples_for_row, num_values_deleted, context,
/*print_array_elements=*/true);
}
::zetasql_base::Status DMLUpdateValueExpr::ProcessNestedUpdate(
const ResolvedUpdateStmt* nested_update,
absl::Span<const TupleData* const> tuples_for_row,
const ResolvedColumn& element_column,
const std::vector<Value>& original_elements, EvaluationContext* context,
std::vector<UpdatedElement>* new_elements) const {
ZETASQL_ASSIGN_OR_RETURN(const VariableId element_column_variable_id,
column_to_variable_mapping_->LookupVariableNameForColumn(
&element_column));
absl::optional<VariableId> array_offset_column_variable_id;
if (nested_update->array_offset_column() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(array_offset_column_variable_id,
column_to_variable_mapping_->LookupVariableNameForColumn(
&nested_update->array_offset_column()->column()));
}
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* where_expr,
LookupResolvedExpr(nested_update->where_expr()));
int64_t num_values_modified = 0;
ZETASQL_RET_CHECK_EQ(original_elements.size(), new_elements->size());
for (int i = 0; i < original_elements.size(); ++i) {
const Value& original_value = original_elements[i];
UpdatedElement& updated_element = (*new_elements)[i];
// As in SetSchemasForEvaluationOfNestedUpdate(), first we put the
// original value, then maybe the offset.
std::vector<Value> values_for_element = {original_value};
if (nested_update->array_offset_column() != nullptr) {
const Value array_offset_value = values::Int64(i);
values_for_element.push_back(array_offset_value);
}
const TupleData data_for_element =
CreateTupleDataFromValues(values_for_element);
const std::vector<const TupleData*> tuples_with_element =
ConcatSpans(tuples_for_row, {&data_for_element});
ZETASQL_ASSIGN_OR_RETURN(const Value where_value,
EvalExpr(*where_expr, tuples_with_element, context));
if (where_value != Bool(true)) continue;
switch (updated_element.kind()) {
case UpdatedElement::Kind::UNMODIFIED: {
UpdateMap update_map;
for (const std::unique_ptr<const ResolvedUpdateItem>& update_item :
nested_update->update_item_list()) {
ResolvedColumn update_column, update_target_column;
std::vector<UpdatePathComponent> prefix_components;
ZETASQL_RETURN_IF_ERROR(AddToUpdateMap(
update_item.get(), tuples_with_element, context, &update_column,
&update_target_column, &prefix_components, &update_map));
}
// All of the ResolvedUpdateItems in a nested UPDATE modify
// 'element_column'.
ZETASQL_RET_CHECK_EQ(update_map.size(), 1);
const auto& update_map_entry = *update_map.begin();
ZETASQL_RET_CHECK(update_map_entry.first == element_column);
const UpdateNode& update_node = *update_map_entry.second;
ZETASQL_ASSIGN_OR_RETURN(const Value new_value,
update_node.GetNewValue(original_value));
updated_element.set_new_value(new_value);
++num_values_modified;
break;
}
case UpdatedElement::Kind::DELETED:
// Nothing to do.
break;
case UpdatedElement::Kind::MODIFIED:
return zetasql_base::OutOfRangeErrorBuilder()
<< "Attempted to modify an array element with multiple nested "
<< "UPDATE statements";
}
}
return VerifyNumRowsModified(nested_update->assert_rows_modified(),
tuples_for_row, num_values_modified, context,
/*print_array_elements=*/true);
}
::zetasql_base::Status DMLUpdateValueExpr::ProcessNestedInsert(
const ResolvedInsertStmt* nested_insert,
absl::Span<const TupleData* const> tuples_for_row,
const std::vector<Value>& original_elements, EvaluationContext* context,
std::vector<UpdatedElement>* new_elements) const {
const int64_t original_size_of_new_elements = new_elements->size();
ZETASQL_RET_CHECK_NE(nested_insert->query() == nullptr,
nested_insert->row_list().empty());
if (nested_insert->query() != nullptr) {
ZETASQL_RET_CHECK_EQ(nested_insert->query_output_column_list().size(), 1);
ZETASQL_ASSIGN_OR_RETURN(const VariableId query_output_variable_id,
column_to_variable_mapping_->LookupVariableNameForColumn(
&nested_insert->query_output_column_list()[0]));
ZETASQL_ASSIGN_OR_RETURN(const RelationalOp* relational_op,
LookupResolvedScan(nested_insert->query()));
std::unique_ptr<TupleSchema> tuple_schema;
std::vector<std::unique_ptr<TupleData>> tuples;
ZETASQL_RETURN_IF_ERROR(EvalRelationalOp(*relational_op, tuples_for_row, context,
&tuple_schema, &tuples));
const absl::optional<int> opt_query_output_variable_slot =
tuple_schema->FindIndexForVariable(query_output_variable_id);
ZETASQL_RET_CHECK(opt_query_output_variable_slot.has_value());
const int query_output_variable_slot =
opt_query_output_variable_slot.value();
for (const std::unique_ptr<TupleData>& query_tuple : tuples) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
const Value& new_value =
query_tuple->slot(query_output_variable_slot).value();
UpdatedElement new_element;
new_element.set_new_value(new_value);
new_elements->push_back(new_element);
}
} else {
for (const std::unique_ptr<const ResolvedInsertRow>& insert_row :
nested_insert->row_list()) {
for (const std::unique_ptr<const ResolvedDMLValue>& dml_value :
insert_row->value_list()) {
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* value_expr,
LookupResolvedExpr(dml_value->value()));
ZETASQL_ASSIGN_OR_RETURN(const Value new_value,
EvalExpr(*value_expr, tuples_for_row, context));
UpdatedElement new_element;
new_element.set_new_value(new_value);
new_elements->push_back(new_element);
}
}
}
const int64_t num_values_inserted =
new_elements->size() - original_size_of_new_elements;
return VerifyNumRowsModified(nested_insert->assert_rows_modified(),
tuples_for_row, num_values_inserted, context,
/*print_array_elements=*/true);
}
// -------------------------------------------------------
// DMLInsertValueExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<DMLInsertValueExpr>>
DMLInsertValueExpr::Create(
const Table* table, const ArrayType* table_array_type,
const StructType* primary_key_type, const StructType* dml_output_type,
const ResolvedInsertStmt* resolved_node,
const ResolvedColumnList* column_list,
std::unique_ptr<const ColumnToVariableMapping> column_to_variable_mapping,
std::unique_ptr<const ResolvedScanMap> resolved_scan_map,
std::unique_ptr<const ResolvedExprMap> resolved_expr_map) {
return absl::WrapUnique(new DMLInsertValueExpr(
table, table_array_type, primary_key_type, dml_output_type, resolved_node,
column_list, std::move(column_to_variable_mapping),
std::move(resolved_scan_map), std::move(resolved_expr_map)));
}
::zetasql_base::Status DMLInsertValueExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
if (stmt()->query() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(RelationalOp * query, LookupResolvedScan(stmt()->query()));
ZETASQL_RETURN_IF_ERROR(query->SetSchemasForEvaluation(params_schemas));
} else {
for (const std::unique_ptr<const ResolvedInsertRow>& row :
stmt()->row_list()) {
for (const std::unique_ptr<const ResolvedDMLValue>& value :
row->value_list()) {
ZETASQL_ASSIGN_OR_RETURN(ValueExpr * expr, LookupResolvedExpr(value->value()));
ZETASQL_RETURN_IF_ERROR(expr->SetSchemasForEvaluation(params_schemas));
}
}
}
ZETASQL_ASSIGN_OR_RETURN(RelationalOp * scan,
LookupResolvedScan(stmt()->table_scan()));
ZETASQL_RETURN_IF_ERROR(scan->SetSchemasForEvaluation(params_schemas));
if (stmt()->assert_rows_modified() != nullptr) {
ZETASQL_ASSIGN_OR_RETURN(
ValueExpr * rows,
LookupResolvedExpr(stmt()->assert_rows_modified()->rows()));
ZETASQL_RETURN_IF_ERROR(rows->SetSchemasForEvaluation(params_schemas));
}
return zetasql_base::OkStatus();
}
::zetasql_base::StatusOr<Value> DMLInsertValueExpr::Eval(
absl::Span<const TupleData* const> params,
EvaluationContext* context) const {
InsertColumnMap insert_column_map;
ZETASQL_RETURN_IF_ERROR(PopulateInsertColumnMap(&insert_column_map));
std::vector<std::vector<Value>> rows_to_insert;
ZETASQL_RETURN_IF_ERROR(PopulateRowsToInsert(insert_column_map, params, context,
&rows_to_insert));
std::vector<std::vector<Value>> original_rows;
ZETASQL_RETURN_IF_ERROR(PopulateRowsInOriginalTable(params, context, &original_rows));
absl::string_view duplicate_primary_key_error_prefix =
"Found two rows with primary key";
// We currently store all old rows into `row_map` even in the case where we
// are only returning new rows. This is because we have to do the error
// checking that we do not cause a primary key collision. A future
// optimization might do this checking without materializing the entire
// updated PrimaryKeyRowMap in this case.
PrimaryKeyRowMap row_map;
bool has_primary_key;
// Duplicate primary keys in the original table can only result from a problem
// with the input table.
ZETASQL_RETURN_IF_ERROR(PopulatePrimaryKeyRowMap(
original_rows, duplicate_primary_key_error_prefix, context, &row_map,
&has_primary_key));
if (!has_primary_key &&
stmt()->insert_mode() != ResolvedInsertStmt::OR_ERROR) {
return zetasql_base::OutOfRangeErrorBuilder()
<< "INSERT " << stmt()->GetInsertModeString()
<< " is not allowed because the table does not have a primary key";
}
ZETASQL_ASSIGN_OR_RETURN(
int64_t num_rows_modified,
InsertRows(insert_column_map, rows_to_insert, context, &row_map));
ZETASQL_RETURN_IF_ERROR(VerifyNumRowsModified(stmt()->assert_rows_modified(), params,
num_rows_modified, context));
ZETASQL_RETURN_IF_ERROR(resolved_node_->CheckFieldsAccessed());
return context->options().return_all_rows_for_dml
? GetDMLOutputValue(num_rows_modified, row_map, context)
: DMLValueExpr::GetDMLOutputValue(num_rows_modified,
rows_to_insert, context);
}
DMLInsertValueExpr::DMLInsertValueExpr(
const Table* table, const ArrayType* table_array_type,
const StructType* primary_key_type, const StructType* dml_output_type,
const ResolvedInsertStmt* resolved_node,
const ResolvedColumnList* column_list,
std::unique_ptr<const ColumnToVariableMapping> column_to_variable_mapping,
std::unique_ptr<const ResolvedScanMap> resolved_scan_map,
std::unique_ptr<const ResolvedExprMap> resolved_expr_map)
: DMLValueExpr(table, table_array_type, primary_key_type, dml_output_type,
resolved_node, column_list,
std::move(column_to_variable_mapping),
std::move(resolved_scan_map), std::move(resolved_expr_map)) {
}
::zetasql_base::Status DMLInsertValueExpr::PopulateInsertColumnMap(
InsertColumnMap* insert_column_map) const {
const std::vector<ResolvedColumn>& insert_column_list =
stmt()->insert_column_list();
// Populate 'insert_column_map', leaving InsertColumnOffsets.column_offset
// unset for now.
for (int i = 0; i < insert_column_list.size(); ++i) {
const ResolvedColumn& insert_column = insert_column_list[i];
InsertColumnOffsets offsets;
offsets.insert_column_offset = i;
// 'offsets.column_offset' is populated below.
ZETASQL_RET_CHECK(insert_column_map->emplace(insert_column, offsets).second);
}
// Populate InsertColumnOffsets.column_offset.
int num_column_offsets_set = 0;
for (int i = 0; i < column_list_->size(); ++i) {
const ResolvedColumn& column = (*column_list_)[i];
InsertColumnOffsets* offsets = zetasql_base::FindOrNull(*insert_column_map, column);
if (offsets != nullptr) {
ZETASQL_RET_CHECK_EQ(-1, offsets->column_offset);
offsets->column_offset = i;
++num_column_offsets_set;
}
}
ZETASQL_RET_CHECK_EQ(insert_column_list.size(), num_column_offsets_set);
ZETASQL_RET_CHECK_EQ(insert_column_list.size(), insert_column_map->size());
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLInsertValueExpr::PopulateRowsToInsert(
const InsertColumnMap& insert_column_map,
absl::Span<const TupleData* const> params, EvaluationContext* context,
std::vector<std::vector<Value>>* rows_to_insert) const {
// One element for each row being inserted, storing only the columns being
// inserted.
std::vector<std::vector<Value>> columns_to_insert;
ZETASQL_RETURN_IF_ERROR(PopulateColumnsToInsert(insert_column_map, params, context,
&columns_to_insert));
for (const std::vector<Value>& columns_to_insert_for_row :
columns_to_insert) {
std::vector<Value> row_to_insert;
for (int i = 0; i < column_list_->size(); ++i) {
const ResolvedColumn& column = (*column_list_)[i];
const InsertColumnOffsets* insert_column_offsets =
zetasql_base::FindOrNull(insert_column_map, column);
if (insert_column_offsets == nullptr) {
// Fill in NULL for any values that are not being inserted.
row_to_insert.push_back(Value::Null(column.type()));
} else {
ZETASQL_RET_CHECK_EQ(i, insert_column_offsets->column_offset);
const int insert_column_offset =
insert_column_offsets->insert_column_offset;
row_to_insert.push_back(
columns_to_insert_for_row[insert_column_offset]);
}
}
rows_to_insert->push_back(row_to_insert);
}
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLInsertValueExpr::PopulateColumnsToInsert(
const InsertColumnMap& insert_column_map,
absl::Span<const TupleData* const> params, EvaluationContext* context,
std::vector<std::vector<Value>>* columns_to_insert) const {
if (stmt()->query() != nullptr) {
const ResolvedScan* query = stmt()->query();
ZETASQL_ASSIGN_OR_RETURN(const RelationalOp* relational_op,
LookupResolvedScan(query));
std::unique_ptr<TupleSchema> tuple_schema;
std::vector<std::unique_ptr<TupleData>> tuples;
ZETASQL_RETURN_IF_ERROR(EvalRelationalOp(*relational_op, params, context,
&tuple_schema, &tuples));
for (const std::unique_ptr<TupleData>& tuple : tuples) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
ZETASQL_ASSIGN_OR_RETURN(const std::vector<Value> columns_to_insert_for_row,
GetScannedTupleAsColumnValues(
stmt()->query_output_column_list(),
Tuple(tuple_schema.get(), tuple.get())));
columns_to_insert->push_back(columns_to_insert_for_row);
}
} else {
for (const std::unique_ptr<const ResolvedInsertRow>& resolved_insert_row :
stmt()->row_list()) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
const std::vector<std::unique_ptr<const ResolvedDMLValue>>& dml_values =
resolved_insert_row->value_list();
ZETASQL_RET_CHECK_EQ(dml_values.size(), insert_column_map.size());
std::vector<Value> columns_to_insert_for_row;
for (const std::unique_ptr<const ResolvedDMLValue>& dml_value :
dml_values) {
ZETASQL_ASSIGN_OR_RETURN(const ValueExpr* value_expr,
LookupResolvedExpr(dml_value->value()));
ZETASQL_ASSIGN_OR_RETURN(const Value value,
EvalExpr(*value_expr, params, context));
columns_to_insert_for_row.push_back(value);
}
columns_to_insert->push_back(columns_to_insert_for_row);
}
}
return zetasql_base::OkStatus();
}
::zetasql_base::Status DMLInsertValueExpr::PopulateRowsInOriginalTable(
absl::Span<const TupleData* const> params, EvaluationContext* context,
std::vector<std::vector<Value>>* original_rows) const {
ZETASQL_ASSIGN_OR_RETURN(const RelationalOp* relational_op,
LookupResolvedScan(stmt()->table_scan()));
std::unique_ptr<TupleSchema> tuple_schema;
std::vector<std::unique_ptr<TupleData>> tuples;
ZETASQL_RETURN_IF_ERROR(EvalRelationalOp(*relational_op, params, context,
&tuple_schema, &tuples));
for (const std::unique_ptr<TupleData>& tuple : tuples) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
ZETASQL_ASSIGN_OR_RETURN(
const std::vector<Value> column_values,
GetScannedTupleAsColumnValues(*column_list_,
Tuple(tuple_schema.get(), tuple.get())));
original_rows->push_back(column_values);
}
return zetasql_base::OkStatus();
}
::zetasql_base::StatusOr<int64_t> DMLInsertValueExpr::InsertRows(
const InsertColumnMap& insert_column_map,
const std::vector<std::vector<Value>>& rows_to_insert,
EvaluationContext* context, PrimaryKeyRowMap* row_map) const {
std::unordered_set<Value, ValueHasher> modified_primary_keys;
const int64_t max_original_row_number = row_map->size() - 1;
bool found_primary_key_collision = false;
for (int i = 0; i < rows_to_insert.size(); ++i) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
const std::vector<Value>& row_to_insert = rows_to_insert[i];
RowNumberAndValues row_number_and_values;
row_number_and_values.values = row_to_insert;
// The only use of this row number is as the primary key if the table does
// not have a real primary key, so we set it to the next row number.
row_number_and_values.row_number = row_map->size();
ZETASQL_ASSIGN_OR_RETURN(const Value primary_key,
GetPrimaryKeyOrRowNumber(row_number_and_values, context));
if (context->GetLanguageOptions().LanguageFeatureEnabled(
FEATURE_DISALLOW_NULL_PRIMARY_KEYS)) {
bool primary_key_has_null;
if (primary_key_type_ == nullptr) {
primary_key_has_null = primary_key.is_null();
} else {
ZETASQL_RET_CHECK(primary_key.type()->IsStruct());
ZETASQL_RET_CHECK(!primary_key.is_null());
primary_key_has_null = std::any_of(
primary_key.fields().begin(), primary_key.fields().end(),
[](const Value& v) { return v.is_null(); });
}
if (primary_key_has_null) {
// Ideally this logic would be in the analyzer, but the analyzer cannot
// determine whether an expression is NULL. So the reference
// implementation must respect this feature for the sake of compliance
// testing other engines.
return zetasql_base::OutOfRangeErrorBuilder()
<< "Cannot INSERT a NULL value into a primary key column";
}
}
auto insert_result =
row_map->insert(std::make_pair(primary_key, row_number_and_values));
if (insert_result.second) {
// The row was successfully inserted.
ZETASQL_RET_CHECK(modified_primary_keys.insert(primary_key).second);
} else {
// The primary key of the new row is in the table, possibly corresponding
// to a row that was previously inserted.
RowNumberAndValues& old_row = insert_result.first->second;
found_primary_key_collision = true;
switch (stmt()->insert_mode()) {
case ResolvedInsertStmt::OR_ERROR: {
const std::string row_indent = " ";
return zetasql_base::OutOfRangeErrorBuilder()
<< "Failed to insert row with primary key ("
<< primary_key.ShortDebugString() << ")"
<< " due to previously "
<< (old_row.row_number <= max_original_row_number ? "existing"
: "inserted")
<< " row";
}
case ResolvedInsertStmt::OR_IGNORE:
// Skip this row.
break;
case ResolvedInsertStmt::OR_REPLACE:
// Replace the old row with the new row, using the same primary key.
old_row.values = row_to_insert;
modified_primary_keys.insert(primary_key);
break;
case ResolvedInsertStmt::OR_UPDATE: {
// Update the old row according to the new row, using the same primary
// key. Unlike OR_REPLACE, here we only change the columns being
// inserted.
ZETASQL_RET_CHECK_EQ(old_row.values.size(), row_to_insert.size());
for (const auto& elt : insert_column_map) {
const int column_offset = elt.second.column_offset;
old_row.values[column_offset] = row_to_insert[column_offset];
}
modified_primary_keys.insert(primary_key);
break;
}
default:
ZETASQL_RET_CHECK_FAIL() << "Unsupported insert mode "
<< ResolvedInsertStmtEnums_InsertMode_Name(
stmt()->insert_mode());
}
}
}
if (!found_primary_key_collision) {
// Dummy access of the insert mode. It does not matter in this case, but we
// require that all fields in the resolved AST are explicitly accessed at
// some point.
stmt()->insert_mode();
}
return modified_primary_keys.size();
}
::zetasql_base::StatusOr<Value> DMLInsertValueExpr::GetDMLOutputValue(
int64_t num_rows_modified, const PrimaryKeyRowMap& row_map,
EvaluationContext* context) const {
std::vector<std::vector<Value>> dml_output_rows(row_map.size());
for (const auto& elt : row_map) {
// It is expensive to call this for every row, but this code is only used
// for compliance testing, so it's ok.
ZETASQL_RETURN_IF_ERROR(context->VerifyNotAborted());
const int64_t row_number = elt.second.row_number;
dml_output_rows[row_number] = elt.second.values;
}
return DMLValueExpr::GetDMLOutputValue(num_rows_modified, dml_output_rows,
context);
}
// -------------------------------------------------------
// RootExpr
// -------------------------------------------------------
::zetasql_base::StatusOr<std::unique_ptr<RootExpr>> RootExpr::Create(
std::unique_ptr<ValueExpr> value_expr,
std::unique_ptr<RootData> root_data) {
return absl::WrapUnique(
new RootExpr(std::move(value_expr), std::move(root_data)));
}
::zetasql_base::Status RootExpr::SetSchemasForEvaluation(
absl::Span<const TupleSchema* const> params_schemas) {
return mutable_value_expr()->SetSchemasForEvaluation(params_schemas);
}
bool RootExpr::Eval(absl::Span<const TupleData* const> params,
EvaluationContext* context, VirtualTupleSlot* result,
::zetasql_base::Status* status) const {
return value_expr()->Eval(params, context, result, status);
}
std::string RootExpr::DebugInternal(const std::string& indent,
bool verbose) const {
return absl::StrCat("RootExpr(", value_expr()->DebugInternal(indent, verbose),
")");
}
RootExpr::RootExpr(std::unique_ptr<ValueExpr> value_expr,
std::unique_ptr<RootData> root_data)
: ValueExpr(value_expr->output_type()), root_data_(std::move(root_data)) {
SetArg(kValueExpr, absl::make_unique<ExprArg>(std::move(value_expr)));
}
const ValueExpr* RootExpr::value_expr() const {
return GetArg(kValueExpr)->node()->AsValueExpr();
}
ValueExpr* RootExpr::mutable_value_expr() {
return GetMutableArg(kValueExpr)->mutable_node()->AsMutableValueExpr();
}
} // namespace zetasql
| [
"matthewbr@google.com"
] | matthewbr@google.com |
32fc2a6adca2de8d3e0819ddb0821292df4c23ce | 297497957c531d81ba286bc91253fbbb78b4d8be | /gfx/skia/skia/src/pdf/SkPDFDevice.h | c021d371bdf8948853c2f3ebc7086a4749ec0abb | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | marco-c/gecko-dev-comments-removed | 7a9dd34045b07e6b22f0c636c0a836b9e639f9d3 | 61942784fb157763e65608e5a29b3729b0aa66fa | refs/heads/master | 2023-08-09T18:55:25.895853 | 2023-08-01T00:40:39 | 2023-08-01T00:40:39 | 211,297,481 | 0 | 0 | NOASSERTION | 2019-09-29T01:27:49 | 2019-09-27T10:44:24 | C++ | UTF-8 | C++ | false | false | 6,386 | h |
#ifndef SkPDFDevice_DEFINED
#define SkPDFDevice_DEFINED
#include "include/core/SkBitmap.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkData.h"
#include "include/core/SkPaint.h"
#include "include/core/SkRect.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkStream.h"
#include "src/core/SkClipStack.h"
#include "src/core/SkClipStackDevice.h"
#include "src/core/SkTHash.h"
#include "src/core/SkTextBlobPriv.h"
#include "src/pdf/SkKeyedImage.h"
#include "src/pdf/SkPDFGraphicStackState.h"
#include "src/pdf/SkPDFTypes.h"
#include <vector>
namespace sktext {
class GlyphRun;
class GlyphRunList;
}
class SkKeyedImage;
class SkPDFArray;
class SkPDFDevice;
class SkPDFDict;
class SkPDFDocument;
class SkPDFFont;
class SkPDFObject;
class SkPath;
class SkRRect;
struct SkPDFIndirectReference;
class SkPDFDevice final : public SkClipStackDevice {
public:
SkPDFDevice(SkISize pageSize, SkPDFDocument* document,
const SkMatrix& initialTransform = SkMatrix::I());
sk_sp<SkPDFDevice> makeCongruentDevice() {
return sk_make_sp<SkPDFDevice>(this->size(), fDocument);
}
~SkPDFDevice() override;
void drawPaint(const SkPaint& paint) override;
void drawPoints(SkCanvas::PointMode mode,
size_t count, const SkPoint[],
const SkPaint& paint) override;
void drawRect(const SkRect& r, const SkPaint& paint) override;
void drawOval(const SkRect& oval, const SkPaint& paint) override;
void drawRRect(const SkRRect& rr, const SkPaint& paint) override;
void drawPath(const SkPath& origpath, const SkPaint& paint, bool pathIsMutable) override;
void drawImageRect(const SkImage*,
const SkRect* src,
const SkRect& dst,
const SkSamplingOptions&,
const SkPaint&,
SkCanvas::SrcRectConstraint) override;
void onDrawGlyphRunList(SkCanvas*,
const sktext::GlyphRunList&,
const SkPaint& initialPaint,
const SkPaint& drawingPaint) override;
void drawVertices(const SkVertices*, sk_sp<SkBlender>, const SkPaint&, bool) override;
#ifdef SK_ENABLE_SKSL
void drawMesh(const SkMesh&, sk_sp<SkBlender>, const SkPaint&) override;
#endif
void drawSprite(const SkBitmap& bitmap, int x, int y,
const SkPaint& paint);
std::unique_ptr<SkPDFDict> makeResourceDict();
std::unique_ptr<SkStreamAsset> content();
SkISize size() const { return this->imageInfo().dimensions(); }
SkIRect bounds() const { return this->imageInfo().bounds(); }
const SkMatrix& initialTransform() const { return fInitialTransform; }
protected:
sk_sp<SkSurface> makeSurface(const SkImageInfo&, const SkSurfaceProps&) override;
void drawAnnotation(const SkRect&, const char key[], SkData* value) override;
void drawDevice(SkBaseDevice*, const SkSamplingOptions&, const SkPaint&) override;
void drawSpecial(SkSpecialImage*, const SkMatrix&, const SkSamplingOptions&,
const SkPaint&) override;
sk_sp<SkSpecialImage> makeSpecial(const SkBitmap&) override;
sk_sp<SkSpecialImage> makeSpecial(const SkImage*) override;
SkImageFilterCache* getImageFilterCache() override;
private:
friend class ScopedContentEntry;
SkMatrix fInitialTransform;
SkTHashSet<SkPDFIndirectReference> fGraphicStateResources;
SkTHashSet<SkPDFIndirectReference> fXObjectResources;
SkTHashSet<SkPDFIndirectReference> fShaderResources;
SkTHashSet<SkPDFIndirectReference> fFontResources;
int fNodeId;
SkDynamicMemoryWStream fContent;
SkDynamicMemoryWStream fContentBuffer;
bool fNeedsExtraSave = false;
SkPDFGraphicStackState fActiveStackState;
SkPDFDocument* fDocument;
SkBaseDevice* onCreateDevice(const CreateInfo&, const SkPaint*) override;
SkPDFIndirectReference makeFormXObjectFromDevice(bool alpha = false);
SkPDFIndirectReference makeFormXObjectFromDevice(SkIRect bbox, bool alpha = false);
void drawFormXObjectWithMask(SkPDFIndirectReference xObject,
SkPDFIndirectReference sMask,
SkBlendMode,
bool invertClip);
SkDynamicMemoryWStream* setUpContentEntry(const SkClipStack* clipStack,
const SkMatrix& matrix,
const SkPaint& paint,
SkScalar,
SkPDFIndirectReference* dst);
void finishContentEntry(const SkClipStack*, SkBlendMode, SkPDFIndirectReference, SkPath*);
bool isContentEmpty();
void internalDrawGlyphRun(
const sktext::GlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint);
void drawGlyphRunAsPath(
const sktext::GlyphRun& glyphRun, SkPoint offset, const SkPaint& runPaint);
void internalDrawImageRect(SkKeyedImage,
const SkRect* src,
const SkRect& dst,
const SkSamplingOptions&,
const SkPaint&,
const SkMatrix& canvasTransformationMatrix);
void internalDrawPath(const SkClipStack&,
const SkMatrix&,
const SkPath&,
const SkPaint&,
bool pathIsMutable);
void internalDrawPathWithFilter(const SkClipStack& clipStack,
const SkMatrix& ctm,
const SkPath& origPath,
const SkPaint& paint);
bool handleInversePath(const SkPath& origPath, const SkPaint& paint, bool pathIsMutable);
void clearMaskOnGraphicState(SkDynamicMemoryWStream*);
void setGraphicState(SkPDFIndirectReference gs, SkDynamicMemoryWStream*);
void drawFormXObject(SkPDFIndirectReference xObject, SkDynamicMemoryWStream*);
bool hasEmptyClip() const { return this->cs().isEmpty(this->bounds()); }
void reset();
using INHERITED = SkClipStackDevice;
};
#endif
| [
"mcastelluccio@mozilla.com"
] | mcastelluccio@mozilla.com |
b67ae046438eac98bf6f2c3866bea5a46b5c1e3d | 5d15e7dfba2b8d6b9a8bb14973d4907b753d3ab9 | /Screenwriting/EditWidget.cpp | ea62356370369603f44984911051aaeb4108f9b9 | [] | no_license | giurgiumatei/Object-Oriented-Programming | b7957c9e14711ec4910563104d114a70d874b9b2 | 2ab019f1b7f9aaa03b634453fbe2ac2914320923 | refs/heads/main | 2023-03-10T00:14:25.892419 | 2021-02-22T14:53:57 | 2021-02-22T14:53:57 | 341,146,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 149 | cpp | #include "EditWidget.h"
EditWidget::EditWidget(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
}
EditWidget::~EditWidget()
{
}
| [
"noreply@github.com"
] | noreply@github.com |
13357256c7f01b11626ecd9b25b0a480210a758b | d0eb99a27084d0decd07e72be416ea36db003df6 | /LilleBuddha/LilleBuddha.ino | 7d0d6b241f67d09663ecc9a908df6bcc877b7ae5 | [] | no_license | passelig/arduino | 6e690e577605fe38c8e96ded8db16d2156a17863 | f7382a2c135fe6a32a5442a54bc52b5770a0c9ef | refs/heads/master | 2023-05-28T04:50:57.927627 | 2023-05-02T19:34:18 | 2023-05-02T19:34:18 | 301,216,228 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,386 | ino | /**
* @example CompNumber.ino
*
* @par How to Use
* This example shows that ,when the "+" component on the Nextion screen is released,
* the value of number component will plus 1,when the "-" component released ,the value of
* number component will minus 1 every time.
*
* @author huang xianming (email:<xianming.huang@itead.cc>)
* @date 2015/11/10
* @updated 2016/12/25 bring HMI up to v0.32 to avoid too old issues
* @convert by Patrick Martin, no other changes made
* @copyright
* Copyright (C) 2014-2015 ITEAD Intelligent Systems Co., Ltd. \n
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*/
#include "Nextion.h"
//void n0PopCallback(void *ptr);
//void b0PopCallback(void *ptr);
//void b1PopCallback(void *ptr);
/*
* Declare a number object [page id:0,component id:3, component name: "n0"].
*/
NexNumber batteryPercent = NexNumber(0, 4, "batteryPercent");
/*
* Declare a button object [page id:0,component id:1, component name: "b0"].
*/
//NexButton b0 = NexButton(0, 1, "b0");
/*
* Declare a button object [page id:0,component id:2, component name: "b1"].
*/
//NexButton b1 = NexButton(0, 2, "b1");
char buffer[100] = {0};
/*
* Register object n0, b0, b1, to the touch event list.
*/
//NexTouch *nex_listen_list[] =
//{
// &n0,
// &b0,
// &b1,
// NULL
//};
//
/*
* number component pop callback function.
*/
//void n0PopCallback(void *ptr)
//{
// dbSerialPrintln("n0PopCallback");
// n0.setValue(50);
//}
/*
* Button0 component pop callback function.
* In this example,the value of the number component will plus one every time when button0 is released.
*/
//void b0PopCallback(void *ptr)
//{
// uint32_t number;
//
// dbSerialPrintln("b0PopCallback");
//
// n0.getValue(&number);
//
// number += 1;
//
// n0.setValue(number);
//}
/*
* Button1 component pop callback function.
* In this example,the value of the number component will minus one every time when button1 is released.
*/
//void b1PopCallback(void *ptr)
//{
// uint32_t number;
//
// dbSerialPrintln("b1PopCallback");
//
// n0.getValue(&number);
//
// number -= 1;
//
// n0.setValue(number);
//}
void setup(void)
{
/* Set the baudrate which is for debug and communicate with Nextion screen. */
nexInit();
/* Register the pop event callback function of the current number component. */
//n0.attachPop(n0PopCallback);
/* Register the pop event callback function of the current button0 component. */
//b0.attachPop(b0PopCallback);
/* Register the pop event callback function of the current button1 component. */
//b1.attachPop(b1PopCallback);
dbSerialPrintln("setup done");
}
void loop(void)
{
/*
* When a pop or push event occured every time,
* the corresponding component[right page id and component id] in touch event list will be asked.
*/
//nexLoop(nex_listen_list);
batteryPercent.setValue(25);
delay(1000);
batteryPercent.setValue(25);
delay(1000);
batteryPercent.setValue(50);
delay(1000);
batteryPercent.setValue(75);
delay(1000);
batteryPercent.setValue(100);
delay(1000);
}
| [
"gunnar.storebo@gmail.com"
] | gunnar.storebo@gmail.com |
83bd2bee7482f86e994151eedefcec3f4e00c0cd | 4c6ee3c60a0bcd35a1775274bc60f7d41dfbf11b | /swo/ue07/src/wmb/motor.hpp | c8ed9241a9f5b61ecdae08b56748df0717cb443b | [] | no_license | TangoTwo/nv-hgb | 01e19deab3b2b12668f8c4faab9622355698885c | fabe9751b0687a8c783118a9a592808666994446 | refs/heads/master | 2020-04-03T11:45:45.175196 | 2019-02-02T16:31:46 | 2019-02-02T16:31:46 | 155,231,000 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | hpp | #pragma once
#include <string>
#include <chrono>
#include <iostream>
/**
* All types of fuels (that are supported by this
* totally legitimate business software).
*/
enum class fuel_t
{
DIESEL, GASOLINE
};
class motor_t
{
public: // typedefs
/**
* Horse power.
*/
using hp = float;
public: // methods
motor_t() = default;
/**
* Creates a motor by reading the supplied input stream.
* @param is The stream containing motor details.
*/
explicit motor_t(std::istream &is);
/**
* Prints a few motor details to the supplied output stream.
* @param os The output stream to write the details to.
* @return The output stream (to allow for chaining).
*/
std::ostream & print(std::ostream &os) const;
private: // members
unsigned _serial {};
// "MY BLOOD IS GASOLINEEE" (R&M Reference)
fuel_t _fuel {fuel_t::GASOLINE};
hp _hp {};
float _avg_consumption {};
time_t _production_date {};
};
std::ostream & operator<<(std::ostream &os, const motor_t &motor);
std::istream & operator>>(std::istream &is, motor_t &motor);
| [
"vest.niklas@gmail.com"
] | vest.niklas@gmail.com |
df8b0fcaf847b27a47b50860ec1976f62e6b4826 | 0d46e0823a2de35927cee433229675e54361725e | /Lab/lab12/room.cpp | 4c823e55899404da07b64312ea2dfa50a3652d2d | [] | no_license | ipx97/CS1570 | 329a716e2995b4786c4d94d690e1f6bc5a9dbfee | 40fc31db0be6e001c0680fe13089b82413acd07a | refs/heads/master | 2021-09-13T08:35:15.937143 | 2018-04-27T06:32:31 | 2018-04-27T06:32:31 | 119,192,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 763 | cpp | #include "room.h"
#include "res.h"
Crime_room::Crime_room(){
m_murderCommitted = false;
m_deadGuy = "";
m_hair = 0;
}
void Crime_room::meeting(Resident & a,Resident & b){
if(murder()){
m_murderCommitted = true;
//Randomizes who committed the murder
if (rand() % 2 == 1){
m_deadGuy = a.m_name;
a.m_isAlive = false;
b.m_isMurderer = true;
m_hair = b.m_hair;
}
else{
m_deadGuy = b.m_name;
b.m_isAlive = false;
a.m_isMurderer = true;
m_hair = a.m_hair;
}
}
return;
}
bool Crime_room::murder(){
if (rand() % 2 == 1)
return true;
else
return false;
}
void Crime_room::check_room(){
if (m_murderCommitted)
cout<<m_deadGuy<<" has been murdered!!!\n";
return;
}
| [
"ipiskulic17@gmail.com"
] | ipiskulic17@gmail.com |
859f99296aeec2c7491bcbe90d354e8698d787fe | 107b558561055314d9d40010e9c748888bffc3d8 | /multievent/interface/ReferenceControlT.h | 176427cd78b4ca5b511615e31a83567c55655a64 | [] | no_license | dq5070410/multievent | 44b2b228bbd86cde118769554584a2b7c1a654cb | 2006427c03202b68c0587494d87ec38bfc3c6824 | refs/heads/master | 2020-06-18T11:21:38.424426 | 2017-05-26T07:27:03 | 2017-05-26T07:27:03 | 75,140,434 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,490 | h | /**
* 引用计数类
*
*
* History
* 12/11/2012 Created
*/
#ifndef __REFERENCE_CONTROL_T_H_
#define __REFERENCE_CONTROL_T_H_
#include "AtomicOperationT.h"
ME_NAME_SPACE_BEGIN
/**
* 引用计数类
*
* 基于原子操作CMEAtomicOperationT
*/
class IMEReferenceControl
{
public:
virtual ~IMEReferenceControl() {}
public:
/**
* 增加引用计数1
*
* 返回值:
* 递增之后的引用计数, DWORD
*/
virtual DWORD AddReference() = 0;
/**
* 减少引用计数1
*
* 返回值:
* 递减之后的引用计数, DWORD
*/
virtual DWORD RemoveReference() = 0;
};
template <class LockType>
class CMEReferenceControlT : public IMEReferenceControl
{
public:
virtual DWORD AddReference();
virtual DWORD RemoveReference();
/**
* 取得当前引用计数
*
* 返回值:
* DWORD值
*/
virtual DWORD GetReference();
protected:
/**
* 当引用计数为0时, 这个事件将会发生
*
* 它默认的行为是删除自己
* 继承类如果有特殊要求, 可以重载这个函数, 但一定要记住
* 在执行特定逻辑之后, 不要忘了调用CMEReferenceControlT<xx>::OnReferenceRelease()
* 或者在重载之后的OnReferenceRelease()增加delete this
*
* 返回值:
* 无
*/
virtual void OnReferenceRelease();
protected:
CMEAtomicOperationT<LockType> m_Atomic;
};
#include "ReferenceControlT.hpp"
ME_NAME_SPACE_END
#endif // __REFERENCE_CONTROL_T_H_
| [
"dq5070410@126.com"
] | dq5070410@126.com |
80f2768ffb10ee16e312b2d8f27ab4e2e69ee5af | 98f92b1375d23823a4f36136b7762ac79d33e5a4 | /src/ping_data.hpp | bada3b96decde374d659c5d4db123c8e78ceb2b5 | [
"MIT"
] | permissive | cooky451/pingstats | d60f5e311c30e35da65a18b6df121d081430133f | ed908ff6ed8fed40623c9eb8d4ae255c3c188061 | refs/heads/master | 2021-01-15T15:25:51.179585 | 2017-09-22T04:56:58 | 2017-09-22T04:56:58 | 50,164,393 | 19 | 5 | null | 2017-09-23T22:19:13 | 2016-01-22T07:08:20 | C++ | UTF-8 | C++ | false | false | 6,602 | hpp | /*
* Copyright (c) 2016 - 2017 cooky451
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#pragma once
#include "utility/utility.hpp"
#include "ping_monitor.hpp"
#include <string>
#include <vector>
namespace pingstats // export
{
using namespace utility::literals;
namespace cr = std::chrono;
namespace ut = utility;
class PingData
{
std::vector<IcmpEchoResult> _traceResults;
std::vector<IcmpEchoResult> _pingResults;
const IcmpEchoResult* _lastResult{};
std::size_t _historySize = { 2 * 3600 };
std::string _lastResponder;
double _meanWeight{ 80.0 };
double _jitterWeight{ 40.0 };
double _lossWeight{ 40.0 };
double _lastPing{};
double _meanPing{};
double _maxPing{};
double _squaredJitter{};
double _jitter{};
double _loss{};
double _lossPercentage{};
double _pixelPerMs{ 1.0 };
double _pingOffsetMs{};
double _gridSizeY{ 50.0 };
public:
PingData(ut::TreeConfigNode& config)
{
auto& statscfg{ *config.findOrAppendNode("stats") };
statscfg.loadOrStore("historySize", _historySize);
statscfg.loadOrStore("averagePingWeight", _meanWeight);
statscfg.loadOrStore("averageJitterWeight", _jitterWeight);
statscfg.loadOrStore("averageLossWeight", _lossWeight);
}
auto lastResult() const
{
return _lastResult;
}
auto& traceResults() const
{
return _traceResults;
}
auto& pingResults() const
{
return _pingResults;
}
auto& lastResponder() const
{
return _lastResponder;
}
auto lastPing() const
{
return _lastPing;
}
auto meanPing() const
{
return _meanPing;
}
auto jitter() const
{
return _jitter;
}
auto lossPercentage() const
{
return _lossPercentage;
}
auto gridSizeY() const
{
return _gridSizeY;
}
auto pixelPerMs() const
{
return _pixelPerMs;
}
auto pingOffsetMs() const
{
return _pingOffsetMs;
}
void insertPingResult(const IcmpEchoResult& echoResult)
{
_lastResponder = echoResult.responder.name();
// Usually near the end.
auto insertionPoint{ std::upper_bound(
_pingResults.begin(),
_pingResults.end(),
echoResult,
[](const auto& lhs, const auto& rhs) {
return lhs.sentTime < rhs.sentTime;
}
) };
const auto& result{ *_pingResults.insert(insertionPoint, echoResult) };
const auto isLost{ result.errorCode != 0 || result.statusCode != 0 };
const auto lw{ std::max(1.0 / _lossWeight, 1.0 / _pingResults.size()) };
_loss = _loss * (1.0 - lw) + isLost * lw;
_lossPercentage = 100.0 * _loss;
if (!isLost)
{
calculateStats(result);
}
if (_pingResults.size() >= _historySize * 2)
{
std::copy(_pingResults.end() - _historySize,
_pingResults.end(), _pingResults.begin());
_pingResults.resize(_historySize);
}
_lastResult = &_pingResults.back();
}
void insertTraceResult(const IcmpEchoResult& traceResult)
{
_lastResponder = traceResult.responder.name();
_traceResults.push_back(std::move(traceResult));
if (_traceResults.size() >= _historySize * 2)
{
std::copy(_traceResults.end() - _historySize,
_traceResults.end(), _traceResults.begin());
_traceResults.resize(_historySize);
}
_lastResult = &_traceResults.back();
}
private:
void calculateStats(const IcmpEchoResult& result)
{
_lastPing = ut::milliseconds_f64(result.latency).count();
_maxPing = std::max(_maxPing, _lastPing);
const auto mw{ std::max(1.0 / _meanWeight, 1.0 / _pingResults.size()) };
_meanPing = (1.0 - mw) * _meanPing + mw * _lastPing;
const auto jw{ std::max(1.0 / _jitterWeight, 1.0 / _pingResults.size()) };
const auto sd{ (_meanPing - _lastPing) * (_meanPing - _lastPing) };
_squaredJitter = (1.0 - jw) * _squaredJitter + jw * sd;
_jitter = std::sqrt(_squaredJitter);
constexpr auto HEIGHT{ 200.0 };
const auto optimalPixelPerMs{ HEIGHT / ((_meanPing) * 2.0 + _jitter) };
const auto pixelPerMsDiff{ std::abs(optimalPixelPerMs - _pixelPerMs) };
if (pixelPerMsDiff / optimalPixelPerMs > 0.2)
{
if (optimalPixelPerMs >= HEIGHT / 5.0)
{
_pixelPerMs = HEIGHT / 5.0;
_pingOffsetMs = 0.0;
_gridSizeY = 1.0;
}
else
{
_pixelPerMs = std::min(HEIGHT / 20.0, optimalPixelPerMs);
_pingOffsetMs = 0.0;
const auto assumedHeight{ HEIGHT / _pixelPerMs };
_gridSizeY =
assumedHeight >= 300.0 ?
100.0 : assumedHeight >= 150.0 ?
50.0 : assumedHeight >= 75.0 ?
25.0 : assumedHeight >= 30.0 ?
10.0 : 5.0;
}
}
}
};
std::time_t makeTimeStamp(cr::steady_clock::time_point tp)
{
const auto dur{ cr::duration_cast<
cr::system_clock::duration>(tp - cr::steady_clock::now()) };
return cr::system_clock::to_time_t(cr::system_clock::now() + dur);
}
std::string makeTimestampString(cr::steady_clock::time_point tp)
{
auto stamp{ makeTimeStamp(tp) };
std::tm tm;
localtime_s(&tm, &stamp);
return ut::formatString("%02d-%02d-%02d %02d:%02d:%02d",
1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
}
std::string makeLogString(const std::vector<IcmpEchoResult>& results)
{
std::string str;
for (auto& result : results)
{
str += ut::formatString(
"[%s] Error %5u | Status %5u | Responder %15s"
" | Latency %7.2f ms | SysLatency %4d ms\r\n",
makeTimestampString(result.sentTime).c_str(),
result.errorCode, result.statusCode,
result.responder.name().c_str(),
ut::milliseconds_f64{ result.latency }.count(),
result.sysLatency);
}
return str;
}
}
| [
"cooky451@gmail.com"
] | cooky451@gmail.com |
719a2ea7146dbb72218cddfa4cba569d5c5ff73e | 710f2cf5524cb1101ea11b5941b1b139e7469ec6 | /InsertAtTailLL.cpp | c0003aab6b4453d0c4a1cafdd29b5fd601c67753 | [] | no_license | themennice/programming-challenges | 2bbf49f9848e84c5062f9c3718232f3095d45e4f | c62d2a84ec43076f4c8db101e7d88b2a27eb37a8 | refs/heads/master | 2023-04-06T16:22:23.298137 | 2021-04-06T03:00:42 | 2021-04-06T03:00:42 | 230,023,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,252 | cpp | /*
Insert at tail of a linked list.
https://www.hackerrank.com/challenges/30-linked-list/problem
*/
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
Node* insert(Node *head, int data)
{
// Create a node with data to insert
Node* inserted = new Node(data);
// Make the node the new head if the list is empty
if(head == NULL)
head = inserted;
// Otherwise, go to the end of the list and append the new node at the end
else {
Node* currHead = head;
while(currHead->next != NULL)
currHead = currHead->next;
currHead->next = inserted;
}
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
mylist.display(head);
} | [
"dziubiiden@gmail.com"
] | dziubiiden@gmail.com |
d3a5f10fe9c4e8fab24e2ae128a5954ad61d4a3a | 60e49824f399df40bc2330f723b1d89bdda7e977 | /BrewPiLess/TimeKeeper.h | 6763d16e5ff805faa9028ff6423f8eceebd264c0 | [] | no_license | jalexandre0/BrewPiLess | 6f211c6c974aa37e3001de624f2158fb28db908a | d21cb15fbf569d3ed6566c7e698cf521a7d16d99 | refs/heads/master | 2020-06-25T02:28:29.844873 | 2017-07-06T21:15:27 | 2017-07-06T21:15:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,021 | h | #ifndef TimeKeeper_H
#define TimeKeeper_H
class TimeKeeperClass
{
public:
TimeKeeperClass(void):_referenceSeconds(0),_referenceSystemTime(0){}
void begin(char* server1,char* server2,char* server3);
void begin(void);
time_t getTimeSeconds(void); // get Epoch time
const char *getDateTimeStr(void);
void setInternetAccessibility(bool connected){ _online=connected; }
void setCurrentTime(time_t current);
private:
time_t _referenceSeconds;
time_t _referenceSystemTime;
bool _online;
time_t _lastSaved;
void saveTime(time_t t);
time_t loadTime(void);
};
extern TimeKeeperClass TimeKeeper;
#endif
| [
"vitotai@mail.com"
] | vitotai@mail.com |
69d5c19aee981b344c6fdee1dea8c4ecf2b04102 | 087559124a37bb857a1fd6b5952dd44d2cb71bc6 | /tutorial1.cpp | ce45923b140a85c5f01ebab75e627f69419b899e | [] | no_license | lterrazas/CS4830Exploration4 | eefd30f4a5d572702fbd87d17af5b61c1b528478 | eb02fe22f2a569237f6810173ff0c6868aa7c484 | refs/heads/master | 2016-08-02T22:21:37.580138 | 2014-11-07T02:09:18 | 2014-11-07T02:09:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | cpp | #include "opencv2\highgui\highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char** argv)
{
Mat img = imread("opencv-logo.png", CV_LOAD_IMAGE_UNCHANGED); //read the image data in the file "MyPic.JPG" and store it in 'img'
if (img.empty()) //check whether the image is loaded or not
{
cout << "Error : Image cannot be loaded..!!" << endl;
//system("pause"); //wait for a key press
return -1;
}
namedWindow("MyWindow", CV_WINDOW_AUTOSIZE); //create a window with the name "MyWindow"
imshow("MyWindow", img); //display the image which is stored in the 'img' in the "MyWindow" window
waitKey(0); //wait infinite time for a keypress
destroyWindow("MyWindow"); //destroy the window with the name, "MyWindow"
return 0;
}
| [
"itslarissat@gmail.com"
] | itslarissat@gmail.com |
843a0c7791684ed90f594bcbbdf9dfb3696865db | 1ecef5939c99cda2a92bcc17770fcbd883ae15b6 | /llvm/projects/test-suite/SingleSource/Benchmarks/Shootout-C++/hash.cpp | 9864058cc4aa286e54f165761010f5b6bb5738e7 | [
"NCSA"
] | permissive | yahnik/TaintTracking | 52316fc2ce60c0e9d11b8e3f4dea39293b43fdd2 | 71569ccc1ca84904ea22440cb0172c4f1464a29b | refs/heads/master | 2021-05-31T05:27:09.467947 | 2013-01-01T21:33:57 | 2013-01-01T21:33:57 | 6,711,409 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 838 | cpp | // -*- mode: c++ -*-
// $Id: hash.cpp 59315 2008-11-14 20:29:00Z edwin $
// http://www.bagley.org/~doug/shootout/
#include <stdio.h>
#include <iostream>
#include <ext/hash_map>
#include <cstring>
using namespace std;
using namespace __gnu_cxx;
struct eqstr {
bool operator()(const char* s1, const char* s2) const {
return strcmp(s1, s2) == 0;
}
};
int
main(int argc, char *argv[]) {
#ifdef SMALL_PROBLEM_SIZE
#define LENGTH 50000
#else
#define LENGTH 500000
#endif
int n = ((argc == 2) ? atoi(argv[1]) : LENGTH);
char buf[16];
typedef hash_map<const char*, int, hash<const char*>, eqstr> HM;
HM X;
for (int i=1; i<=n; i++) {
sprintf(buf, "%x", i);
X[strdup(buf)] = i;
}
int c = 0;
for (int i=n; i>0; i--) {
sprintf(buf, "%d", i);
if (X[strdup(buf)]) c++;
}
cout << c << endl;
}
| [
"djonik08@gmail.com"
] | djonik08@gmail.com |
ea15e362ca6e77c297ddc57938fc7965a1617e4f | c74fc6d883e719703bcc91eab7aedf1f676667c0 | /neteq/tick_timer.cc | 3182d4d5e17d40d7d7b0d2eb5de4658f72f79e2a | [] | no_license | lanyuliuyun/webrtc-research | 5a118d7b7241f50275b1cd9827a43ff07789118b | 962bd0e73aa0069c6ffd18a1ae9a73a90f7e464f | refs/heads/master | 2022-06-13T19:33:07.737571 | 2022-03-08T04:33:53 | 2022-03-08T04:33:53 | 95,969,947 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cc | /*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "tick_timer.h"
namespace webrtc {
TickTimer::Stopwatch::Stopwatch(const TickTimer& ticktimer)
: ticktimer_(ticktimer), starttick_(ticktimer.ticks()) {}
TickTimer::Countdown::Countdown(const TickTimer& ticktimer,
uint64_t ticks_to_count)
: stopwatch_(ticktimer.GetNewStopwatch()),
ticks_to_count_(ticks_to_count) {}
TickTimer::Countdown::~Countdown() = default;
} // namespace webrtc
| [
"lanyuliuyun@foxmail.com"
] | lanyuliuyun@foxmail.com |
2e8e2becb579dd727d6b87de1d87c125baa12a56 | 018e83709b0a00b7fc012a57259f21bf5e5deed9 | /longest_valid_parentheses/Solution.cpp | 047142aed8b56fe07b2a29fcb0ed735c8af2a235 | [] | no_license | lxyu0405/leetcode-pratice | 79daa472b6bbb96afad38e18deb6053b988052ae | 57eec096bd4de4c0a7afda7c699181ca5c2af3a0 | refs/heads/master | 2021-01-17T02:31:32.965245 | 2016-10-16T02:42:22 | 2016-10-16T02:42:22 | 52,575,038 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,547 | cpp | #include <vector>
#include <string>
#include <stack>
#include <utility>
#include <iostream>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s) {
if (s.length() < 2) {
return 0;
}
stack<pair<char, int>> bracketStack;
vector<int> longestPare(s.length(),0);
// Initialization
longestPare[0] = 0;
if (s[0] == '(') {
bracketStack.push({'(',0});
}
// Use a stack to find parentheses pairs
for (int i = 1; i < s.length(); i++) {
if (s[i] == '(') {
bracketStack.push({'(',i});
}else{
// s[i] == ')'
if (!bracketStack.empty()) {
auto topPair = bracketStack.top();
if (topPair.first == '(') {
bracketStack.pop();
longestPare[topPair.second] = 1;
longestPare[i] = 1;
}
}
}
}
// Analyze the longest sequence
int longest = 0;
int pre = 0, now = 0;
for (; now < s.length(); now++) {
if (longestPare[now] == 1) {
pre = now;
while (now < s.length() && longestPare[now] == 1) {
now++;
}
int thisLength = now - pre;
longest = longest > thisLength ? longest : thisLength;
}
}
return longest;
}
};
| [
"xiaoyu.lu0405@gmail.com"
] | xiaoyu.lu0405@gmail.com |
c24679e83f72ecce4053e321e5f82060fcec16d6 | 786a89a4bd31e0a5953094c7880021cc98f78f98 | /ABC/ABC230/e.cpp | f20beabf431b6e3d918a2c19649fefa2babe993f | [] | no_license | enjoy82/atcodersyozin | c12eb9cc04e61cedcdc13643b84e8c87c13ff4b1 | c8a73577d1d75db2d5c22eab028f942f75f2fba7 | refs/heads/master | 2022-10-04T04:47:16.835712 | 2022-09-30T07:15:47 | 2022-09-30T07:15:47 | 243,669,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,710 | cpp | // execute g++-11 main.cpp -std=c++14 -I C:\Users\naoya\Desktop\code\Atcoder
#include<bits/stdc++.h>
//#include<atcoder/all>
typedef long long ll;
typedef long double ld;
using namespace std;
//using namespace atcoder;
using Pii = pair<int, int>;
using Pll = pair<ll, ll>;
//ordered_set 重複不可
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// use set_function + find_by_order(select itr-num)
#define REP(i, l, n) for(int i=(l), i##_len=(n); i<i##_len; ++i)
#define ALL(x) (x).begin(),(x).end()
#define pb push_back
struct Edge {
long long to;
long long cost;
};
using Graph = vector<vector<Edge>>;
ll gcd(ll a,ll b){return b ? gcd(b,a%b) : a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
template<class T>inline bool chmax(T &a, T b) {if(a < b) {a = b;return true;}return false;}
template<class T>inline bool chmin(T &a, T b) {if(a > b) {a = b;return true;}return false;}
template <class T>
inline vector<T> make_vec(size_t a, T val) {
return vector<T>(a, val);
}
template <class... Ts>
inline auto make_vec(size_t a, Ts... ts) {
return vector<decltype(make_vec(ts...))>(a, make_vec(ts...));
}
template <class T>
vector<int> arg_sort(vector<T> &lis){
vector<int> idx(lis.size());
iota(ALL(idx), 0);
sort(ALL(idx), [&](auto &l, auto &r){
return lis[l] < lis[r];
});
return idx;
}
template <class T>
int compression(vector<T> &A){
std::map<T,int> mem;
for(auto p: A) mem[p] = 0;
int sz = 0;
for(auto &p: mem) p.second = sz++;
for(auto &p: A) p = mem[p];
return sz;
}
char alpha[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char Alpha[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, 1, -1};
const long long LINF = 1LL << 62;
const int INF = 1LL << 30;
const ll MOD = 1e9+7;
ll modpow(ll x, ll n){
if(n == 0)
return 1;
if(n % 2 == 0)
return modpow(x * x % MOD, n / 2);
else
return x * modpow(x, n - 1) % MOD;
}
//逆元でもっておいて復元する
ll modinv(ll a, ll mod) {
ll b = mod, u = 1, v = 0;
while (b) {
ll t = a / b;
a -= t * b; swap(a, b);
u -= t * v; swap(u, v);
}
u %= mod;
if (u < 0) u += mod;
return u;
}
int main(){
ll n; cin >> n;
ll ans = 0;
ll i = 1;
for(; n >= i * i; i++){
ans += (n / i) * 2;
}
i--;
cout << ans - (i*i) << endl;
} | [
"naoya990506@gmail.com"
] | naoya990506@gmail.com |
0adcfaa67c5d09b64c88488f16a61bf101e759d3 | f426ab0481f35eddbcdd63bd4cfb3b0f8e1949a8 | /style_test.cpp | 239d748fe1810a027d86c9d04bcf59a7c3dad674 | [
"Unlicense"
] | permissive | cengizkandemir/.emacs.d | 5d258492a4103753abafb5b9b14cc77ee59d0455 | 189c8d506a8bb47396f73e7b2302412db6b72949 | refs/heads/master | 2022-06-27T17:57:24.312088 | 2022-05-09T13:02:58 | 2022-05-09T13:02:58 | 182,718,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,196 | cpp | #include <iostream>
#define SOME_MACRO_DEF(arg1, arg2) \
if(arg1 > arg2) { \
; \
} \
else { \
; \
}
namespace
{
int values[] =
{
1,
2,
3
};
template <typename SomeReallyReallyLongTypeParam,
typename SomeMoreReallyReallyLongTypeParam, typename T, typename L,
typename S>
void some_templated_func(SomeReallyReallyLongTypeParam arg1,
SomeMoreReallyReallyLongTypeParam arg2, T arg3, L arg4, S arg5)
{
;
}
} // anonymous
namespace foo_bar
{
class foo
{
enum class enum_t : int
{
a,
b,
c
};
using int_t = int;
using this_needs_to_be_a_long_type_name = int;
private:
foo(int_t first, int_t second)
: first_(first)
, second_(second)
{
std::cout << "foo" << std::endl;
}
void bar(enum_t val) const;
int fancy_func(this_needs_to_be_a_long_type_name arg1,
int arg2, int arg3, this_needs_to_be_a_long_type_name arg4);
int fancy_func_2(
this_needs_to_be_a_long_type_name this_needs_to_be_long_var_name,
int yet_another_long_var_name) const;
public:
int_t first_;
int_t second_;
};
void foo::bar(enum_t val) const
{
if(true) {
some_label:
std::cout << "bar" << std::endl;
}
else if(false) {
;
}
else {
;
}
switch(val) {
case enum_t::a:
{
break;
}
case enum_t::b:
break;
case enum_t::c:
break;
default:
break;
}
do {
;
} while(false);
try {
;
}
catch(...) {
;
}
some_other_label:
return;
}
} // foo_bar
int main(int argc, char* argv[])
{
#ifndef SOME_MACRO
std::cout << "hello, world!" << " some more random strings, "
<< "even more random strings" << std::endl;
#endif
SOME_MACRO_DEF(1, 2);
some_templated_func(
[=]() {
if (true) {
;
}
},
2, 3, 4, 5);
return 0;
}
| [
"cengizkandemir@live.com"
] | cengizkandemir@live.com |
b72fbcfd6e96e74ef4b994d3fe0d6521a2efb3d6 | 163128554c1d26f17739cc77702cfbde520b406e | /task2_parser/tests/bad/bad006.cc | 7909a7000a9d9da9e72a40af103731b8c66cb54e | [] | no_license | sils/compiler-construction-haskell | 7700a278b9033c7a39947b112a8dc68d3cfb4904 | 4c58e1b43077a7049aee205d57bf16d2bc333211 | refs/heads/master | 2021-05-29T00:58:08.356159 | 2015-06-18T14:12:03 | 2015-06-18T14:13:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46 | cc | using cout::5;
int main () {
return 0;
}
| [
"lasse.schuirmann@gmail.com"
] | lasse.schuirmann@gmail.com |
77e6c591e76d6cc150236d1fe4fe8f04fd6bb1b8 | 1e2c2688150ddcc894d9049fc353029cd75c8d87 | /supporting libraries/pyside/PySide-1.2.4/pyside_build/py3.5-qt4.8.7-64bit-release/pyside/PySide/QtCore/PySide/QtCore/qmargins_wrapper.cpp | 242a29344bafeb2e5a23f5838d213d1fcd77e1d8 | [] | no_license | tryanaditya/mainmain | f3f9559230a520b69bdafc8bf9e36ebbf14147fa | fc82048e17587af3b56b977bea476a7f2506a7ba | refs/heads/master | 2021-01-11T03:11:00.020758 | 2016-10-16T23:55:05 | 2016-10-16T23:55:05 | 71,084,893 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,830 | cpp | /*
* This file is part of PySide: Python for Qt
*
* Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
*
* Contact: PySide team <contact@pyside.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
//workaround to access protected functions
#define protected public
// default includes
#include <shiboken.h>
#include <pysidesignal.h>
#include <pysideproperty.h>
#include <pyside.h>
#include <destroylistener.h>
#include <typeresolver.h>
#include <typeinfo>
#include "pyside_qtcore_python.h"
#include "qmargins_wrapper.h"
// Extra includes
// Target ---------------------------------------------------------
extern "C" {
static int
Sbk_QMargins_Init(PyObject* self, PyObject* args, PyObject* kwds)
{
SbkObject* sbkSelf = reinterpret_cast<SbkObject*>(self);
if (Shiboken::Object::isUserType(self) && !Shiboken::ObjectType::canCallConstructor(self->ob_type, Shiboken::SbkType< ::QMargins >()))
return -1;
::QMargins* cptr = 0;
int overloadId = -1;
PythonToCppFunc pythonToCpp[] = { 0, 0, 0, 0 };
SBK_UNUSED(pythonToCpp)
int numArgs = PyTuple_GET_SIZE(args);
PyObject* pyArgs[] = {0, 0, 0, 0};
// invalid argument lengths
if (numArgs == 2 || numArgs == 3)
goto Sbk_QMargins_Init_TypeError;
if (!PyArg_UnpackTuple(args, "QMargins", 0, 4, &(pyArgs[0]), &(pyArgs[1]), &(pyArgs[2]), &(pyArgs[3])))
return -1;
// Overloaded function decisor
// 0: QMargins()
// 1: QMargins(QMargins)
// 2: QMargins(int,int,int,int)
if (numArgs == 0) {
overloadId = 0; // QMargins()
} else if (numArgs == 4
&& (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[0])))
&& (pythonToCpp[1] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[1])))
&& (pythonToCpp[2] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[2])))
&& (pythonToCpp[3] = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArgs[3])))) {
overloadId = 2; // QMargins(int,int,int,int)
} else if (numArgs == 1
&& (pythonToCpp[0] = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (pyArgs[0])))) {
overloadId = 1; // QMargins(QMargins)
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QMargins_Init_TypeError;
// Call function/method
switch (overloadId) {
case 0: // QMargins()
{
if (!PyErr_Occurred()) {
// QMargins()
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QMargins();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
case 1: // QMargins(const QMargins & QMargins)
{
if (!Shiboken::Object::isValid(pyArgs[0]))
return -1;
::QMargins cppArg0_local = ::QMargins();
::QMargins* cppArg0 = &cppArg0_local;
if (Shiboken::Conversions::isImplicitConversion((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], pythonToCpp[0]))
pythonToCpp[0](pyArgs[0], &cppArg0_local);
else
pythonToCpp[0](pyArgs[0], &cppArg0);
if (!PyErr_Occurred()) {
// QMargins(QMargins)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QMargins(*cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
case 2: // QMargins(int left, int top, int right, int bottom)
{
int cppArg0;
pythonToCpp[0](pyArgs[0], &cppArg0);
int cppArg1;
pythonToCpp[1](pyArgs[1], &cppArg1);
int cppArg2;
pythonToCpp[2](pyArgs[2], &cppArg2);
int cppArg3;
pythonToCpp[3](pyArgs[3], &cppArg3);
if (!PyErr_Occurred()) {
// QMargins(int,int,int,int)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cptr = new ::QMargins(cppArg0, cppArg1, cppArg2, cppArg3);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
break;
}
}
if (PyErr_Occurred() || !Shiboken::Object::setCppPointer(sbkSelf, Shiboken::SbkType< ::QMargins >(), cptr)) {
delete cptr;
return -1;
}
if (!cptr) goto Sbk_QMargins_Init_TypeError;
Shiboken::Object::setValidCpp(sbkSelf, true);
Shiboken::BindingManager::instance().registerWrapper(sbkSelf, cptr);
return 1;
Sbk_QMargins_Init_TypeError:
const char* overloads[] = {"", "PySide.QtCore.QMargins", "int, int, int, int", 0};
Shiboken::setErrorAboutWrongArguments(args, "PySide.QtCore.QMargins", overloads);
return -1;
}
static PyObject* Sbk_QMarginsFunc_bottom(PyObject* self)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// bottom()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
int cppResult = const_cast<const ::QMargins*>(cppSelf)->bottom();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython(Shiboken::Conversions::PrimitiveTypeConverter<int>(), &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QMarginsFunc_isNull(PyObject* self)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// isNull()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
bool cppResult = const_cast<const ::QMargins*>(cppSelf)->isNull();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython(Shiboken::Conversions::PrimitiveTypeConverter<bool>(), &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QMarginsFunc_left(PyObject* self)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// left()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
int cppResult = const_cast<const ::QMargins*>(cppSelf)->left();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython(Shiboken::Conversions::PrimitiveTypeConverter<int>(), &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QMarginsFunc_right(PyObject* self)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// right()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
int cppResult = const_cast<const ::QMargins*>(cppSelf)->right();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython(Shiboken::Conversions::PrimitiveTypeConverter<int>(), &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QMarginsFunc_setBottom(PyObject* self, PyObject* pyArg)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
int overloadId = -1;
PythonToCppFunc pythonToCpp;
SBK_UNUSED(pythonToCpp)
// Overloaded function decisor
// 0: setBottom(int)
if ((pythonToCpp = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArg)))) {
overloadId = 0; // setBottom(int)
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QMarginsFunc_setBottom_TypeError;
// Call function/method
{
int cppArg0;
pythonToCpp(pyArg, &cppArg0);
if (!PyErr_Occurred()) {
// setBottom(int)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cppSelf->setBottom(cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
}
if (PyErr_Occurred()) {
return 0;
}
Py_RETURN_NONE;
Sbk_QMarginsFunc_setBottom_TypeError:
const char* overloads[] = {"int", 0};
Shiboken::setErrorAboutWrongArguments(pyArg, "PySide.QtCore.QMargins.setBottom", overloads);
return 0;
}
static PyObject* Sbk_QMarginsFunc_setLeft(PyObject* self, PyObject* pyArg)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
int overloadId = -1;
PythonToCppFunc pythonToCpp;
SBK_UNUSED(pythonToCpp)
// Overloaded function decisor
// 0: setLeft(int)
if ((pythonToCpp = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArg)))) {
overloadId = 0; // setLeft(int)
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QMarginsFunc_setLeft_TypeError;
// Call function/method
{
int cppArg0;
pythonToCpp(pyArg, &cppArg0);
if (!PyErr_Occurred()) {
// setLeft(int)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cppSelf->setLeft(cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
}
if (PyErr_Occurred()) {
return 0;
}
Py_RETURN_NONE;
Sbk_QMarginsFunc_setLeft_TypeError:
const char* overloads[] = {"int", 0};
Shiboken::setErrorAboutWrongArguments(pyArg, "PySide.QtCore.QMargins.setLeft", overloads);
return 0;
}
static PyObject* Sbk_QMarginsFunc_setRight(PyObject* self, PyObject* pyArg)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
int overloadId = -1;
PythonToCppFunc pythonToCpp;
SBK_UNUSED(pythonToCpp)
// Overloaded function decisor
// 0: setRight(int)
if ((pythonToCpp = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArg)))) {
overloadId = 0; // setRight(int)
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QMarginsFunc_setRight_TypeError;
// Call function/method
{
int cppArg0;
pythonToCpp(pyArg, &cppArg0);
if (!PyErr_Occurred()) {
// setRight(int)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cppSelf->setRight(cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
}
if (PyErr_Occurred()) {
return 0;
}
Py_RETURN_NONE;
Sbk_QMarginsFunc_setRight_TypeError:
const char* overloads[] = {"int", 0};
Shiboken::setErrorAboutWrongArguments(pyArg, "PySide.QtCore.QMargins.setRight", overloads);
return 0;
}
static PyObject* Sbk_QMarginsFunc_setTop(PyObject* self, PyObject* pyArg)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
int overloadId = -1;
PythonToCppFunc pythonToCpp;
SBK_UNUSED(pythonToCpp)
// Overloaded function decisor
// 0: setTop(int)
if ((pythonToCpp = Shiboken::Conversions::isPythonToCppConvertible(Shiboken::Conversions::PrimitiveTypeConverter<int>(), (pyArg)))) {
overloadId = 0; // setTop(int)
}
// Function signature not found.
if (overloadId == -1) goto Sbk_QMarginsFunc_setTop_TypeError;
// Call function/method
{
int cppArg0;
pythonToCpp(pyArg, &cppArg0);
if (!PyErr_Occurred()) {
// setTop(int)
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
cppSelf->setTop(cppArg0);
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
}
}
if (PyErr_Occurred()) {
return 0;
}
Py_RETURN_NONE;
Sbk_QMarginsFunc_setTop_TypeError:
const char* overloads[] = {"int", 0};
Shiboken::setErrorAboutWrongArguments(pyArg, "PySide.QtCore.QMargins.setTop", overloads);
return 0;
}
static PyObject* Sbk_QMarginsFunc_top(PyObject* self)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
PyObject* pyResult = 0;
// Call function/method
{
if (!PyErr_Occurred()) {
// top()const
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
int cppResult = const_cast<const ::QMargins*>(cppSelf)->top();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
pyResult = Shiboken::Conversions::copyToPython(Shiboken::Conversions::PrimitiveTypeConverter<int>(), &cppResult);
}
}
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyObject* Sbk_QMargins___copy__(PyObject* self)
{
if (!Shiboken::Object::isValid(self))
return 0;
::QMargins& cppSelf = *(((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self)));
PyObject* pyResult = Shiboken::Conversions::copyToPython((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], &cppSelf);
if (PyErr_Occurred() || !pyResult) {
Py_XDECREF(pyResult);
return 0;
}
return pyResult;
}
static PyMethodDef Sbk_QMargins_methods[] = {
{"bottom", (PyCFunction)Sbk_QMarginsFunc_bottom, METH_NOARGS},
{"isNull", (PyCFunction)Sbk_QMarginsFunc_isNull, METH_NOARGS},
{"left", (PyCFunction)Sbk_QMarginsFunc_left, METH_NOARGS},
{"right", (PyCFunction)Sbk_QMarginsFunc_right, METH_NOARGS},
{"setBottom", (PyCFunction)Sbk_QMarginsFunc_setBottom, METH_O},
{"setLeft", (PyCFunction)Sbk_QMarginsFunc_setLeft, METH_O},
{"setRight", (PyCFunction)Sbk_QMarginsFunc_setRight, METH_O},
{"setTop", (PyCFunction)Sbk_QMarginsFunc_setTop, METH_O},
{"top", (PyCFunction)Sbk_QMarginsFunc_top, METH_NOARGS},
{"__copy__", (PyCFunction)Sbk_QMargins___copy__, METH_NOARGS},
{0} // Sentinel
};
static int Sbk_QMargins___nb_bool(PyObject* self)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return -1;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
int result;
PyThreadState* _save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS
result = !cppSelf->isNull();
PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS
return result;
}
// Rich comparison
static PyObject* Sbk_QMargins_richcompare(PyObject* self, PyObject* pyArg, int op)
{
if (!Shiboken::Object::isValid(self))
return 0;
::QMargins& cppSelf = *(((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self)));
SBK_UNUSED(cppSelf)
PyObject* pyResult = 0;
PythonToCppFunc pythonToCpp;
SBK_UNUSED(pythonToCpp)
switch (op) {
case Py_NE:
if ((pythonToCpp = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (pyArg)))) {
// operator!=(const QMargins & m2)
if (!Shiboken::Object::isValid(pyArg))
return 0;
::QMargins cppArg0_local = ::QMargins();
::QMargins* cppArg0 = &cppArg0_local;
if (Shiboken::Conversions::isImplicitConversion((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], pythonToCpp))
pythonToCpp(pyArg, &cppArg0_local);
else
pythonToCpp(pyArg, &cppArg0);
bool cppResult = cppSelf != (*cppArg0);
pyResult = Shiboken::Conversions::copyToPython(Shiboken::Conversions::PrimitiveTypeConverter<bool>(), &cppResult);
} else {
pyResult = Py_True;
Py_INCREF(pyResult);
}
break;
case Py_EQ:
if ((pythonToCpp = Shiboken::Conversions::isPythonToCppReferenceConvertible((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (pyArg)))) {
// operator==(const QMargins & m2)
if (!Shiboken::Object::isValid(pyArg))
return 0;
::QMargins cppArg0_local = ::QMargins();
::QMargins* cppArg0 = &cppArg0_local;
if (Shiboken::Conversions::isImplicitConversion((SbkObjectType*)SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], pythonToCpp))
pythonToCpp(pyArg, &cppArg0_local);
else
pythonToCpp(pyArg, &cppArg0);
bool cppResult = cppSelf == (*cppArg0);
pyResult = Shiboken::Conversions::copyToPython(Shiboken::Conversions::PrimitiveTypeConverter<bool>(), &cppResult);
} else {
pyResult = Py_False;
Py_INCREF(pyResult);
}
break;
default:
goto Sbk_QMargins_RichComparison_TypeError;
}
if (pyResult && !PyErr_Occurred())
return pyResult;
Sbk_QMargins_RichComparison_TypeError:
PyErr_SetString(PyExc_NotImplementedError, "operator not implemented.");
return 0;
}
} // extern "C"
static int Sbk_QMargins_traverse(PyObject* self, visitproc visit, void* arg)
{
return reinterpret_cast<PyTypeObject*>(&SbkObject_Type)->tp_traverse(self, visit, arg);
}
static int Sbk_QMargins_clear(PyObject* self)
{
return reinterpret_cast<PyTypeObject*>(&SbkObject_Type)->tp_clear(self);
}
extern "C"
{
static PyObject* Sbk_QMargins__repr__(PyObject* self)
{
::QMargins* cppSelf = 0;
SBK_UNUSED(cppSelf)
if (!Shiboken::Object::isValid(self))
return 0;
cppSelf = ((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)self));
QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDebug dbg(&buffer);
dbg << *cppSelf;
buffer.close();
QByteArray str = buffer.data();
int idx = str.indexOf('(');
if (idx >= 0)
str.replace(0, idx, Py_TYPE(self)->tp_name);
PyObject* mod = PyDict_GetItemString(Py_TYPE(self)->tp_dict, "__module__");
if (mod)
return Shiboken::String::fromFormat("<%s.%s at %p>", Shiboken::String::toCString(mod), str.constData(), self);
else
return Shiboken::String::fromFormat("<%s at %p>", str.constData(), self);
}
} // extern C
// Class Definition -----------------------------------------------
extern "C" {
static PyNumberMethods Sbk_QMargins_TypeAsNumber;
static SbkObjectType Sbk_QMargins_Type = { { {
PyVarObject_HEAD_INIT(&SbkObjectType_Type, 0)
/*tp_name*/ "PySide.QtCore.QMargins",
/*tp_basicsize*/ sizeof(SbkObject),
/*tp_itemsize*/ 0,
/*tp_dealloc*/ &SbkDeallocWrapper,
/*tp_print*/ 0,
/*tp_getattr*/ 0,
/*tp_setattr*/ 0,
/*tp_compare*/ 0,
/*tp_repr*/ Sbk_QMargins__repr__,
/*tp_as_number*/ 0,
/*tp_as_sequence*/ 0,
/*tp_as_mapping*/ 0,
/*tp_hash*/ 0,
/*tp_call*/ 0,
/*tp_str*/ 0,
/*tp_getattro*/ 0,
/*tp_setattro*/ 0,
/*tp_as_buffer*/ 0,
/*tp_flags*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_GC,
/*tp_doc*/ 0,
/*tp_traverse*/ Sbk_QMargins_traverse,
/*tp_clear*/ Sbk_QMargins_clear,
/*tp_richcompare*/ Sbk_QMargins_richcompare,
/*tp_weaklistoffset*/ 0,
/*tp_iter*/ 0,
/*tp_iternext*/ 0,
/*tp_methods*/ Sbk_QMargins_methods,
/*tp_members*/ 0,
/*tp_getset*/ 0,
/*tp_base*/ reinterpret_cast<PyTypeObject*>(&SbkObject_Type),
/*tp_dict*/ 0,
/*tp_descr_get*/ 0,
/*tp_descr_set*/ 0,
/*tp_dictoffset*/ 0,
/*tp_init*/ Sbk_QMargins_Init,
/*tp_alloc*/ 0,
/*tp_new*/ SbkObjectTpNew,
/*tp_free*/ 0,
/*tp_is_gc*/ 0,
/*tp_bases*/ 0,
/*tp_mro*/ 0,
/*tp_cache*/ 0,
/*tp_subclasses*/ 0,
/*tp_weaklist*/ 0
}, },
/*priv_data*/ 0
};
} //extern
// Type conversion functions.
// Python to C++ pointer conversion - returns the C++ object of the Python wrapper (keeps object identity).
static void QMargins_PythonToCpp_QMargins_PTR(PyObject* pyIn, void* cppOut) {
Shiboken::Conversions::pythonToCppPointer(&Sbk_QMargins_Type, pyIn, cppOut);
}
static PythonToCppFunc is_QMargins_PythonToCpp_QMargins_PTR_Convertible(PyObject* pyIn) {
if (pyIn == Py_None)
return Shiboken::Conversions::nonePythonToCppNullPtr;
if (PyObject_TypeCheck(pyIn, (PyTypeObject*)&Sbk_QMargins_Type))
return QMargins_PythonToCpp_QMargins_PTR;
return 0;
}
// C++ to Python pointer conversion - tries to find the Python wrapper for the C++ object (keeps object identity).
static PyObject* QMargins_PTR_CppToPython_QMargins(const void* cppIn) {
PyObject* pyOut = (PyObject*)Shiboken::BindingManager::instance().retrieveWrapper(cppIn);
if (pyOut) {
Py_INCREF(pyOut);
return pyOut;
}
const char* typeName = typeid(*((::QMargins*)cppIn)).name();
return Shiboken::Object::newObject(&Sbk_QMargins_Type, const_cast<void*>(cppIn), false, false, typeName);
}
// C++ to Python copy conversion.
static PyObject* QMargins_COPY_CppToPython_QMargins(const void* cppIn) {
return Shiboken::Object::newObject(&Sbk_QMargins_Type, new ::QMargins(*((::QMargins*)cppIn)), true, true);
}
// Python to C++ copy conversion.
static void QMargins_PythonToCpp_QMargins_COPY(PyObject* pyIn, void* cppOut) {
*((::QMargins*)cppOut) = *((::QMargins*)Shiboken::Conversions::cppPointer(SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX], (SbkObject*)pyIn));
}
static PythonToCppFunc is_QMargins_PythonToCpp_QMargins_COPY_Convertible(PyObject* pyIn) {
if (PyObject_TypeCheck(pyIn, (PyTypeObject*)&Sbk_QMargins_Type))
return QMargins_PythonToCpp_QMargins_COPY;
return 0;
}
void init_QMargins(PyObject* module)
{
// type has number operators
memset(&Sbk_QMargins_TypeAsNumber, 0, sizeof(PyNumberMethods));
SBK_NB_BOOL(Sbk_QMargins_TypeAsNumber) = Sbk_QMargins___nb_bool;
Sbk_QMargins_Type.super.ht_type.tp_as_number = &Sbk_QMargins_TypeAsNumber;
SbkPySide_QtCoreTypes[SBK_QMARGINS_IDX] = reinterpret_cast<PyTypeObject*>(&Sbk_QMargins_Type);
if (!Shiboken::ObjectType::introduceWrapperType(module, "QMargins", "QMargins",
&Sbk_QMargins_Type, &Shiboken::callCppDestructor< ::QMargins >)) {
return;
}
// Register Converter
SbkConverter* converter = Shiboken::Conversions::createConverter(&Sbk_QMargins_Type,
QMargins_PythonToCpp_QMargins_PTR,
is_QMargins_PythonToCpp_QMargins_PTR_Convertible,
QMargins_PTR_CppToPython_QMargins,
QMargins_COPY_CppToPython_QMargins);
Shiboken::Conversions::registerConverterName(converter, "QMargins");
Shiboken::Conversions::registerConverterName(converter, "QMargins*");
Shiboken::Conversions::registerConverterName(converter, "QMargins&");
Shiboken::Conversions::registerConverterName(converter, typeid(::QMargins).name());
// Add Python to C++ copy (value, not pointer neither reference) conversion to type converter.
Shiboken::Conversions::addPythonToCppValueConversion(converter,
QMargins_PythonToCpp_QMargins_COPY,
is_QMargins_PythonToCpp_QMargins_COPY_Convertible);
qRegisterMetaType< ::QMargins >("QMargins");
}
| [
"tryan.aditya@yahoo.com"
] | tryan.aditya@yahoo.com |
71ebbde9c6859e308390a2d52fd7df2befe91e42 | 7414a260dccb2e6876af4736aac40ec10f562a29 | /ActorGraph.hpp | 68ff35f0308dd2a5d85f7734a98a5df99d4a49e9 | [] | no_license | enoorzay/compress | 582241ee84a6351cc0cf26be17ed2bb80a4e36c9 | bf45c5827913a3b9d2df53370de32759bba30fab | refs/heads/master | 2021-01-11T16:03:21.628764 | 2017-01-25T07:44:14 | 2017-01-25T07:44:14 | 79,993,229 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,463 | hpp | /*
* ActorGraph.cpp
* Author: <Edrees Noorzay>
* Date: <06/02/2016>
*
* This is the header for the ActorGraph class and its functions. The class implements
* a graph of ActorNode vertices and ActorEdge edges, along with methods to
* traverse the graph.
*/
#ifndef ACTORGRAPH_HPP
#define ACTORGRAPH_HPP
#define ERROR "No connection"
#include <unordered_map>
#include <fstream>
#include <iostream>
#include <string.h>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <queue>
#include <stack>
#include "ActorNode.hpp"
#include "ActorEdge.hpp"
using namespace std;
class ActorGraph {
protected:
// Holds actor object at key of its name
unordered_map<string, ActorNode * > actors;
// movie title key containing cast of movie
unordered_map<string, vector <ActorNode *> > movies;
// Movie titles sorted by year
unordered_map<int, vector <string> > sortedmovies;
vector<ActorEdge *> allEdges;
/* Holds all the pairs which are scanned for connections together when
* adding edges by year
*/
vector<string> Actorpairs;
public:
// earliest year a connection exists
int earliest;
ActorGraph(void);
vector<ActorNode *> allNodes;
/* This function reads from the input file and calls the appropriate
* graph building function depending on the parameter passed to it
*/
bool loadFromFile(const char* in_filename, bool use_weighted_edges, bool blank );
/* This function adds an actor to a movie's cast, creating the actor
* and movie if either do not exist, otherwise gets the movies cast
* and adds an edge from each of them to the new actor. Called iteratively
* from LoadfromFile and addYear.
*/
bool buildGraph (string actor_name, string movie_title);
/* This function behaves exactly like buildGraph but does not add edges,
* simply initializes actor objects and stores movie info.
*/
bool buildBlank(string actor_name, string movie_title, int movieyear);
/* This function does a Breadthfirst search of the graph, going from
* actor1 to actor2. Used when looking for unweighted paths. Returns
* string containing path info.
*/
string Breadthfirst(string actor_1, string actor_2, bool connecting);
/* This function is used to find shortest path between two
* nodes with weighted edges. Returns the path output
*/
string Dijkstra(string actor_1, string actor_2);
/* This function adds the edges that come along from
* an individual year of movies to the graph. Returns
* false if no movies stored in that year.
*/
bool addYear(int year);
/* This function reads pairfiles and sends them to be processed to the
* correct function based on the parameters given to it.
*/
bool readPairs(const char* in_filename, const char* out_filename, bool weighted, bool connection);
/* This function is called after all pairs are read and stored
* in a graph data member vector so that it can add edges by year
* and check all pairs for connections
*/
void connectionFinder(const char* out_filename);
/* This function abstracts finding an actor from the
* hash map given its name, which is used as the key
*/
ActorNode * findActor(string name);
/* Destroys and deinitializes */
~ActorGraph();
};
#endif // ACTORGRAPH_HPP | [
"enoorzay@gmail.com"
] | enoorzay@gmail.com |
9204909705ea871dae3bddb7be108f4bbdc4c38d | 55a565712300b73fa4cce94bdf4d275cbf7802af | /SEI/recapitulare/gn/gn/gnDlg.h | ecfb6b3973e5ec3488332091c0ecb8ef9f204d78 | [] | no_license | scorpionipx/ETTIM1 | 18effb605c1f957ed43012db051a4e3d8c633aec | ff1348a0581b49e48ca034849f5cc738f5aa2839 | refs/heads/master | 2020-03-30T12:57:16.890238 | 2019-07-15T11:21:00 | 2019-07-15T11:21:00 | 151,249,532 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 619 | h | // gnDlg.h : header file
//
#pragma once
#include "afxwin.h"
// CgnDlg dialog
class CgnDlg : public CDialog
{
// Construction
public:
CgnDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_GN_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
#if defined(_DEVICE_RESOLUTION_AWARE) && !defined(WIN32_PLATFORM_WFSP)
afx_msg void OnSize(UINT /*nType*/, int /*cx*/, int /*cy*/);
#endif
DECLARE_MESSAGE_MAP()
public:
CEdit eb;
};
| [
"scorpionipx@gmail.com"
] | scorpionipx@gmail.com |
4e916ce6a0ea4f9c56d4bb5c98c44694f0b76ced | 2b6263485f7b45d048387744f82198abe3230505 | /VS/Arduino.VC/MiniCNC/MiniCNC.cpp | a87832b53bcb4f1cf0a6a2bd4cbe02c877348da3 | [] | no_license | unkaMoMo/CNCStepper | b7338ae368ab670b24c69b28c4d3e3f826857bd6 | 672206dc37b775dcd07a49dc926b39b6900f9a53 | refs/heads/master | 2020-04-01T00:21:36.099052 | 2018-09-23T20:41:16 | 2018-09-23T20:41:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | cpp | ////////////////////////////////////////////////////////
/*
This file is part of CNCLib - A library for stepper motors.
Copyright (c) 2013-2018 Herbert Aitenbichler
CNCLib is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CNCLib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
http://www.gnu.org/licenses/
*/
////////////////////////////////////////////////////////
#include "stdafx.h"
#include <math.h>
#include "..\MsvcStepper\MsvcStepper.h"
#include "TestTools.h"
#include "..\..\..\sketch\MiniCNC\MiniCNC\MyControl.h"
CSerial Serial;
static void setup();
static void loop();
static void Idle();
CMsvcStepper MyStepper;
class CStepper& Stepper = MyStepper;
int _tmain(int /* argc */, _TCHAR* /* argv */ [])
{
digitalReadEvent = [](short pin)
{
switch (pin)
{
#ifdef KILL_PIN
case KILL_PIN: return HIGH;
#endif
}
return DIGITALREADNOVALUE;
};
setup();
while (!CGCodeParserBase::_exit)
{
loop();
}
MyStepper.EndTest();
}
void setup()
{
MyStepper.DelayOptimization = false;
MyStepper.UseSpeedSign = true;
MyStepper.CacheSize = 50000;
MyStepper.InitTest("MiniCNC.csv");
Serial.SetIdle(Idle);
}
void loop()
{
Control.Run();
}
static void Idle()
{
MyStepper.HandleIdle();
}
| [
"h.aitenbichler@eduhi.at"
] | h.aitenbichler@eduhi.at |
b6094ef8f22b01926bbb5421239169d50d4a8716 | b1784318c8c6c48f55f7d3af92bf53eca43f0f05 | /M5Stack_7SegMovie/M5Stack_7SegMovie.ino | 14e6b9f7614dee3afb3ac230cccfd62df91a6f8d | [
"MIT"
] | permissive | MhageGH/M5Stack_7SegMovie | 5ebea2de9946b2279b05700198ef07346148ae39 | d28fdf490ef27069eed5daa82afa0e51fa17631c | refs/heads/master | 2020-03-26T08:36:52.351535 | 2018-08-14T13:52:20 | 2018-08-14T13:52:20 | 144,711,214 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | ino | #include <Wire.h>
#include <M5Stack.h>
void setup() {
M5.begin();
M5.Lcd.drawJpgFile(SD, "/7SegMovie.jpg");
File file = SD.open("/7SegMovie.dat", "r");
Wire.begin();
for (int k = 0; k < 4400; ++k) {
for (int j = 0; j < 8; ++j) {
Wire.beginTransmission(0x70 + j);
Wire.write(0x21);
Wire.endTransmission();
Wire.beginTransmission(0x70 + j);
Wire.write(0x00);
for (int i = 0; i < 16; ++i) Wire.write(file.read());
Wire.endTransmission();
Wire.beginTransmission(0x70 + j);
Wire.write(0x81);
Wire.endTransmission();
}
delay(26);
}
}
void loop() {
}
| [
"noreply@github.com"
] | noreply@github.com |
f53b147eb8f84a76b2fa54d2c9b74a80e183620a | 0ee94d9799a12d1efd0347bc5e498057623a93d1 | /Library/Source/GameControl/Settings.h | de05769982af17f9bb9cedd7dc953c543f60730a | [] | no_license | Regalixx/FrameworkSP3 | 9059c5e7975f61cd7773b909440345559060c3c2 | c40b859581f92f28842bdd28713ab04281f1aa34 | refs/heads/master | 2023-07-14T23:44:03.494552 | 2021-08-29T11:39:48 | 2021-08-29T11:39:48 | 396,223,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,777 | h | /**
CSettings
By: Toh Da Jun
Date: Mar 2020
*/
#pragma once
// Include SingletonTemplate
#include "../DesignPatterns/SingletonTemplate.h"
#include <Windows.h>
// Include GLEW
#ifndef GLEW_STATIC
#define GLEW_STATIC
#include <GL/glew.h>
#endif
// Include GLFW
#include <GLFW/glfw3.h>
class CSettings : public CSingletonTemplate<CSettings>
{
friend CSingletonTemplate<CSettings>;
public:
enum AXIS
{
x = 0,
y = 1,
z = 2,
NUM_AXIS
};
// File information
char* logl_root; // Root directory for loading digital assets
// GLFW Information
GLFWwindow* pWindow;
bool bUse4XAntiliasing = true;
// Windows Information
// Should make these not hard-coded :P
unsigned int iWindowWidth = 1920;
unsigned int iWindowHeight = 1080;
unsigned int iWindowPosX = 50;
unsigned int iWindowPosY = 50;
bool bDisableMousePointer = false;
bool bShowMousePointer = true;
// Frame Rate Information
const unsigned char FPS = 30; // FPS of this game
const unsigned int frameTime = 1000 / FPS; // time for each frame
// Input control
//const bool bActivateMouseInput
// 2D Settings
// The variables which stores the specifications of the map
unsigned int NUM_TILES_XAXIS;
unsigned int NUM_TILES_YAXIS;
float TILE_WIDTH;
float TILE_HEIGHT;
float NUM_STEPS_PER_TILE_XAXIS;
float NUM_STEPS_PER_TILE_YAXIS;
float MICRO_STEP_XAXIS;
float MICRO_STEP_YAXIS;
// Update the specifications of the map
void UpdateSpecifications(void);
void setFps(int frames);
char getFps(void);
// Convert an index number of a tile to a coordinate in UV Space
float ConvertIndexToUVSpace(const AXIS sAxis, const int iIndex, const bool bInvert, const float fOffset = 0.0f);
protected:
// Constructor
CSettings(void);
// Destructor
virtual ~CSettings(void);
};
| [
"204122U@mymail.nyp.edu.sg"
] | 204122U@mymail.nyp.edu.sg |
9b6a7a348b8e8da343dd390cb52baaaa6a3f3f8c | 515cb8eb07eeaae2dfea0084891057068562c5df | /ThreatLevel.cpp | dde421aa5a2cabf4b7bac428f5cf3b061248685e | [] | no_license | openbracketret/cos214project | 54946be54be763f11d6ff47932384ebc19c7d994 | 2b786e265764fb70cc98fac99d1c63aca4cb1aab | refs/heads/master | 2020-08-04T00:24:35.615691 | 2019-10-28T05:44:03 | 2019-10-28T05:44:03 | 211,934,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24 | cpp | #include "ThreatLevel.h" | [
"lukegreen.dev@gmail.com"
] | lukegreen.dev@gmail.com |
6e4815840f5d1290e4e1938f0e6589e9188710ab | 00a2acb5951a723f8285e04b4efc1600b042728c | /lfr_new.cp | 45356a69ccfb861bcb736d531738998a1d5461a9 | [] | no_license | Xcrater/PIC-Projects | bfc360f2edd896cd43d27464253c6ce06e6b92ae | 7589e71383ce0d959c9a6ee9c6c71678dec59bc2 | refs/heads/master | 2023-04-27T21:36:29.060476 | 2015-11-05T09:35:41 | 2015-11-05T09:35:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,227 | cp | #line 1 "C:/Documents and Settings/rajesh/Desktop/pic_codes/lfr_new.c"
#line 10 "C:/Documents and Settings/rajesh/Desktop/pic_codes/lfr_new.c"
unsigned int s1,s2,s3,s4,s5,s6,s7,s8;
unsigned short int basespeed = 150, Kp = 100, Ki = 5, Kd = 10;
float rightpulse=0,leftpulse=0,perror=0,error=0,PROPORTIONAL=0,INTEGRAL=0,DERIVATIVE=0,correction=0;
char lastreading;
unsigned int counter;
void initport()
{
ADCON1 =0x06;
PORTA = 0;
PORTE = 0;
TRISA = 0x3F;
TRISE = 0x03;
TRISD = 0x00;
TRISC = 0b00000000;
T1CON.TMR1CS = 0;
T1CON.T1CKPS1 = 1;
T1CON.T1CKPS0 = 1;
TMR1H = 0xFF;
TMR1L = 0x83;
PIE1.TMR1IE = 1;
PIR1.TMR1IF = 0;
INTCON.PEIE = 1;
INTCON.GIE = 1;
}
void initpwm()
{
PWM1_Init(5000);
PWM2_Init(5000);
Pwm1_Start();
Pwm2_Start();
}
void motor_RF()
{
PORTC.F7 = 1;
PORTC.F6 = 0;
}
void motor_RB()
{
PORTC.F7 = 0;
PORTC.F6 = 1;
}
void motor_LF()
{
PORTC.F5 = 1;
PORTC.F4 = 0;
}
void motor_LB()
{
PORTC.F5 = 0;
PORTC.F4 = 1;
}
void interrupt()
{
if (PIR1.TMR1IF == 1)
{
counter++;
PIR1.TMR1IF = 0;
TMR1H = 0xFF;
TMR1L = 0x83;
}
}
void indicator()
{
PORTD.F7 = PORTA.F0;
PORTD.F6 = PORTA.F1;
PORTD.F5 = PORTA.F2;
PORTD.F4 = PORTA.F3;
PORTD.F3 = PORTA.F4;
PORTD.F2 = PORTA.F5;
PORTD.F1 = PORTE.F0;
PORTD.F0 = PORTE.F1;
}
void CalcError()
{
s1 = 0;
s2 = 0;
s3 = 0;
s4 = 0;
s5 = 0;
s6 = 0;
s7 = 0;
s8 = 0;
if(PORTA.F0)
{
lastreading='r';
s1 = 1;
}
if(PORTA.F1)
{
s2 = 1;
}
if(PORTA.F2)
{
s3 = 1;
}
if(PORTA.F3)
{
s4 = 1;
}
if(PORTA.F4)
{
s5 = 1;
}
if(PORTA.F5)
s6 = 1;
if(PORTE.F0)
{
s7 = 1;
}
if(PORTE.F1)
{
lastreading='l';
s8 = 1;
}
perror = error;
error = (s1 * 1) + (s2 * 2) + (s3 * 3) + (s4 * 4) + (s5 * 5) + (s6 * 6) +(s7 * 7) + (s8*8);
error = (error)/(s1+s2+s3+s4+s5+s6+s7+s8);
error = error - 4.5;
}
void main()
{
initport();
initpwm();
while(1)
{
indicator();
CalcError();
if((error == 0) && (s4+s5==2))
{
T1CON.TMR1ON = 0;
motor_LF();
motor_RF();
PWM1_CHANGE_DUTY(255);
PWM2_CHANGE_DUTY(255);
delay_ms(10);
}
if((s1+s2+s3+s4+s5+s6+s7+s8) == 0)
{
T1CON.TMR1ON = 0;
if(lastreading == 'r')
{
T1CON.TMR1ON = 0;
motor_RB();
motor_LF();
PWM1_CHANGE_DUTY(255);
PWM2_CHANGE_DUTY(255);
delay_ms(10);
}
else if(lastreading == 'l')
{
T1CON.TMR1ON = 0;
motor_LB();
motor_RF();
PWM1_CHANGE_DUTY(255);
PWM2_CHANGE_DUTY(255);
delay_ms(10);
}
}
if ( counter>200)
{
T1CON.TMR1ON = 0;
PORTC.F7 = 0;
PORTC.F6 = 0;
PORTC.F5 = 0;
PORTC.F4 = 0;
while(1);
}
if( (s1+s2+s3+s4+s5+s6+s7) == 7 || (s2+s3+s4+s5+s6+s7+s8) == 7 || (s1+s2+s3+s4+s5+s6+s7+s8) == 8)
{
T1CON.TMR1ON = 1;
#line 206 "C:/Documents and Settings/rajesh/Desktop/pic_codes/lfr_new.c"
}
else
{
T1CON.TMR1ON = 0;
PROPORTIONAL = error * kp;
INTEGRAL += error ;
INTEGRAL *= ki;
DERIVATIVE = (error - perror);
correction = ( (PROPORTIONAL) + (INTEGRAL) + (DERIVATIVE*kd));
rightpulse = basespeed + (correction/2);
leftpulse = basespeed - (correction/2);
motor_RF();
motor_LF();
if(leftpulse > 255)
leftpulse = 255;
if(rightpulse > 255)
rightpulse = 255;
if(leftpulse < 0)
leftpulse = 0;
if(rightpulse < 0)
rightpulse = 0;
PWM1_CHANGE_DUTY(rightpulse);
PWM2_CHANGE_DUTY(leftpulse);
}
delay_ms(10);
}
}
| [
"rajesh.raveendran@student.tut.fi"
] | rajesh.raveendran@student.tut.fi |
89a6825c4a43d39817e79032bb72df79e46545a3 | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/webrtc/sdk/android/src/jni/pc/statsobserver.cc | ef73c9bfbfce728dd224e83f2492776f6c6a715b | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-google-patent-license-webrtc",
"GPL-1.0-or-later",
"LicenseRef-scancode-takuya-ooura",
"MIT",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown",
... | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 2,766 | cc | /*
* Copyright 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "sdk/android/src/jni/pc/statsobserver.h"
#include <vector>
#include "sdk/android/generated_peerconnection_jni/jni/StatsObserver_jni.h"
#include "sdk/android/generated_peerconnection_jni/jni/StatsReport_jni.h"
#include "sdk/android/native_api/jni/java_types.h"
#include "sdk/android/src/jni/jni_helpers.h"
namespace webrtc {
namespace jni {
namespace {
ScopedJavaLocalRef<jobject> NativeToJavaStatsReportValue(
JNIEnv* env,
const rtc::scoped_refptr<StatsReport::Value>& value_ptr) {
// Should we use the '.name' enum value here instead of converting the
// name to a string?
return Java_Value_Constructor(
env, NativeToJavaString(env, value_ptr->display_name()),
NativeToJavaString(env, value_ptr->ToString()));
}
ScopedJavaLocalRef<jobjectArray> NativeToJavaStatsReportValueArray(
JNIEnv* env,
const StatsReport::Values& value_map) {
// Ignore the keys and make an array out of the values.
std::vector<StatsReport::ValuePtr> values;
for (const auto& it : value_map)
values.push_back(it.second);
return NativeToJavaObjectArray(env, values,
org_webrtc_StatsReport_00024Value_clazz(env),
&NativeToJavaStatsReportValue);
}
ScopedJavaLocalRef<jobject> NativeToJavaStatsReport(JNIEnv* env,
const StatsReport& report) {
return Java_StatsReport_Constructor(
env, NativeToJavaString(env, report.id()->ToString()),
NativeToJavaString(env, report.TypeToString()), report.timestamp(),
NativeToJavaStatsReportValueArray(env, report.values()));
}
} // namespace
StatsObserverJni::StatsObserverJni(JNIEnv* jni,
const JavaRef<jobject>& j_observer)
: j_observer_global_(jni, j_observer) {}
void StatsObserverJni::OnComplete(const StatsReports& reports) {
JNIEnv* env = AttachCurrentThreadIfNeeded();
ScopedJavaLocalRef<jobjectArray> j_reports =
NativeToJavaObjectArray(env, reports, org_webrtc_StatsReport_clazz(env),
[](JNIEnv* env, const StatsReport* report) {
return NativeToJavaStatsReport(env, *report);
});
Java_StatsObserver_onComplete(env, j_observer_global_, j_reports);
}
} // namespace jni
} // namespace webrtc
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
d509905574552710f5d9825c16fda7813d47c66d | f08e4be57512d0555b24d13b38978f2d2c593fd1 | /leetcode/generateParenthese.h | 5ce6f61b6a4d17a4d201d30ba6c030a4c186284c | [] | no_license | FLOWERCLOUD/LeetcodePracticeByHuayun | 6f07ed86b9f4c0af1c58f4c212df826f63dd6e8e | da31b3473f6f4e02bbf69872fb4c4edfcc6bd687 | refs/heads/master | 2021-01-10T17:14:21.817412 | 2016-03-17T04:39:30 | 2016-03-17T04:39:30 | 43,479,625 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,812 | h | #include <string>
#include <vector>
using namespace std;
class parentheseNode{
public:
parentheseNode()
{
leftNum =0;
rightNum =0;
num = 0;
isWorking = true;
}
parentheseNode(const parentheseNode& node)
{
this->leftNum = node.leftNum;
this->rightNum = node.rightNum;
this->num =node.num;
this->isWorking = node.isWorking;
this->result = node.result;
}
parentheseNode& operator= (const parentheseNode& node)
{
this->leftNum = node.leftNum;
this->rightNum = node.rightNum;
this->num =node.num;
this->isWorking = node.isWorking;
this->result = node.result;
return *this;
}
void insertLeft()
{
++leftNum;
++num;
result.push_back('(');
}
void insetRight()
{
if(leftNum >0){
--leftNum;
++num;
result.push_back(')');
}else{
isWorking = false;
}
}
string toString()
{
string tmp;
for(int i = 0 ;i < result.size() ;++i){
tmp += result[i];
}
return tmp;
}
vector<char> result;
int leftNum;
int rightNum;
int num;
bool isWorking;
};
class parentheseSolution {
public:
vector<string> generateParenthesis(int n) {
vector<parentheseNode> result;
parentheseNode firstnode;
firstnode.insertLeft();
result.push_back(firstnode);
for( int i = 1 ; i < n*2 ; ++i)
{
vector<parentheseNode> tmp;
for( int i = 0 ;i < result.size() ; ++i){
parentheseNode left = result[i];
left.insertLeft();
parentheseNode right = result[i];
right.insetRight();
if(left.isWorking) tmp.push_back(left);
if(right.isWorking) tmp.push_back(right);
}
result = tmp;
}
vector<string> stringResult;
for(int i = 0 ; i< result.size() ;++i){
if(result[i].leftNum == 0)
stringResult.push_back(result[i].toString());
}
return stringResult;
}
};
class parentheseSolution2 {
public:
// l is left parentheses used, r is right parentheses used
// cur is initialized with ')'
void search(int l, int r, int n, string& cur, vector<string> &ret) {
if (l == n) {
ret.push_back(cur);
return;
}
if (r < l) search(l, r+1, n, cur, ret);
cur[l+r] = '(';
search(l+1, r, n, cur, ret);
cur[l+r] = ')';
}
vector<string> generateParenthesis(int n) {
string cur;
vector<string> ret;
cur.resize(2*n, ')');
ret.reserve(2 * n);
search(0, 0, n, cur, ret);
return ret;
}
};
class parentheseSolution3 {
public:
void generate(int leftNum,int rightNum,string s,vector<string> &result)
{
if(leftNum==0&&rightNum==0)
{
result.push_back(s);
}
if(leftNum>0)
{
generate(leftNum-1,rightNum,s+'(',result);
}
if(rightNum>0&&leftNum<rightNum)
{
generate(leftNum,rightNum-1,s+')',result);
}
}
vector<string> generateParenthesis(int n) {
vector<string> result;
string tmp;
generate( n , n ,tmp , result);
return result;
}
}; | [
"528450012@qq.com"
] | 528450012@qq.com |
f4dd7b130754261ffadad5854d1cbdd761d3e628 | 63168b3cc1a8019583b331ebc8c4ec58c241753c | /inference-engine/src/low_precision_transformations/src/fuse_convert.cpp | 3533bb662136531761b0972b3b9e5c7da1258ca9 | [
"Apache-2.0"
] | permissive | generalova-kate/openvino | 2e14552ab9b1196fe35af63b5751a96d0138587a | 72fb7d207cb61fd5b9bb630ee8785881cc656b72 | refs/heads/master | 2023-08-09T20:39:03.377258 | 2021-09-07T09:43:33 | 2021-09-07T09:43:33 | 300,206,718 | 0 | 0 | Apache-2.0 | 2020-10-01T08:35:46 | 2020-10-01T08:35:45 | null | UTF-8 | C++ | false | false | 5,590 | cpp | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision/fuse_convert.hpp"
#include <memory>
#include <vector>
#include <ngraph/pattern/op/wrap_type.hpp>
#include <ngraph/pattern/op/or.hpp>
#include "low_precision/common/ie_lpt_exception.hpp"
#include "low_precision/network_helper.hpp"
namespace ngraph {
namespace pass {
namespace low_precision {
NGRAPH_RTTI_DEFINITION(ngraph::pass::low_precision::FuseConvertTransformation, "FuseConvertTransformation", 0);
FuseConvertTransformation::FuseConvertTransformation(const Params& params) : LayerTransformation(params) {
auto multiply = pattern::wrap_type<opset1::Multiply>({ pattern::wrap_type<opset1::Convert>(), pattern::wrap_type<opset1::Constant>() });
auto subtract = pattern::wrap_type<opset1::Subtract>({ pattern::wrap_type<opset1::Convert>(), pattern::wrap_type<opset1::Constant>() });
auto add = pattern::wrap_type<opset1::Add>({ pattern::wrap_type<opset1::Convert>(), pattern::wrap_type<opset1::Constant>() });
auto matcher = std::make_shared<ngraph::pattern::Matcher>(
std::make_shared<pattern::op::Or>(OutputVector{ multiply, subtract, add }),
"FuseConvertTransformation");
ngraph::graph_rewrite_callback callback = [this](pattern::Matcher& m) {
auto op = m.get_match_root();
if (transformation_callback(op)) {
return false;
}
return transform(*context, m);
};
this->register_matcher(matcher, callback);
}
std::shared_ptr<Node> removeConvertIfPossibleForSubtract(
const std::shared_ptr<opset1::Convert>& convert,
const std::shared_ptr<opset1::Subtract>& subtract) {
std::shared_ptr<Node> newSubtract;
const element::Type precisionBeforeConvert = convert->input(0).get_element_type();
if (NetworkHelper::checkConstantValuePrecision(precisionBeforeConvert, subtract->get_input_node_shared_ptr(1))) {
newSubtract = std::make_shared<ngraph::op::TypeRelaxed<opset1::Subtract>>(
std::vector<ngraph::element::Type>{ element::f32, element::f32 }, std::vector<ngraph::element::Type>{},
ngraph::op::TemporaryReplaceOutputType(convert->get_input_source_output(0), element::f32).get(),
ngraph::op::TemporaryReplaceOutputType(subtract->get_input_node_shared_ptr(1), element::f32).get());
NetworkHelper::setOutDataPrecisionForTypeRelaxed(newSubtract, subtract->get_output_element_type(0));
replace_node(subtract, newSubtract);
}
return newSubtract;
}
bool FuseConvertTransformation::transform(TransformationContext& context, ngraph::pattern::Matcher &m) {
const auto op = m.get_match_root();
if (!canBeTransformed(context, op)) {
return false;
}
const auto convert = ov::as_type_ptr<opset1::Convert>(op->get_input_node_shared_ptr(0));
std::shared_ptr<Node> parent = convert->get_input_node_shared_ptr(0);
if (ov::is_type<opset1::Constant>(parent)) {
auto convertedConstant = foldConvert(parent, convert->get_convert_element_type());
NetworkHelper::copyInfo(parent, convertedConstant);
replace_node(convert, convertedConstant);
} else {
std::shared_ptr<Node> newOp;
if (ov::is_type<opset1::Subtract>(op)) {
auto subtract = ov::as_type_ptr<opset1::Subtract>(op);
newOp = removeConvertIfPossibleForSubtract(convert, subtract);
} else if (ov::is_type<opset1::Multiply>(op)) {
newOp = std::make_shared<ngraph::op::TypeRelaxed<opset1::Multiply>>(
std::vector<ngraph::element::Type>{ element::f32, element::f32 }, std::vector<ngraph::element::Type>{},
ngraph::op::TemporaryReplaceOutputType(convert->get_input_source_output(0), element::f32).get(),
ngraph::op::TemporaryReplaceOutputType(op->get_input_node_shared_ptr(1), element::f32).get());
NetworkHelper::setOutDataPrecisionForTypeRelaxed(newOp, op->get_output_element_type(0));
replace_node(op, newOp);
} else if (ov::is_type<opset1::Add>(op)) {
newOp = std::make_shared<ngraph::op::TypeRelaxed<opset1::Add>>(
std::vector<ngraph::element::Type>{ element::f32, element::f32 }, std::vector<ngraph::element::Type>{},
ngraph::op::TemporaryReplaceOutputType(convert->get_input_source_output(0), element::f32).get(),
ngraph::op::TemporaryReplaceOutputType(op->get_input_node_shared_ptr(1), element::f32).get());
NetworkHelper::setOutDataPrecisionForTypeRelaxed(newOp, op->get_output_element_type(0));
replace_node(op, newOp);
}
if (newOp == nullptr) {
return false;
}
ngraph::copy_runtime_info({ convert, op }, newOp);
newOp->set_friendly_name(op->get_friendly_name());
register_new_node(newOp);
}
return true;
}
bool FuseConvertTransformation::canBeTransformed(const TransformationContext& context, std::shared_ptr<Node> op) const {
const auto convert = ov::as_type_ptr<opset1::Convert>(op->get_input_node_shared_ptr(0));
// issue #40395
if (convert == nullptr) {
return false;
}
const auto destType = convert->get_destination_type();
if ((destType != element::f16) && (destType != element::f32)) {
return false;
}
return true;
}
bool FuseConvertTransformation::isPrecisionPreserved(std::shared_ptr<Node> layer) const noexcept {
return false;
}
} // namespace low_precision
} // namespace pass
} // namespace ngraph
| [
"noreply@github.com"
] | noreply@github.com |
28c0e41433f78605cd8025f9b72858276761f011 | ff69e73ba648407fd8f7d1628f794b9887dcef2e | /include/linear_tri2dmesh_neohookean_dq.h | 887a898bca4b25ccefe217ce906aaf71dc612565 | [] | no_license | itsvismay/Bartels | 87bae94d7f8f51a50c419b26b5ad745503b44495 | f9c33ada4f934ea727ea647a4c556d175cbb72e6 | refs/heads/master | 2022-04-25T23:41:12.394557 | 2020-04-17T22:06:54 | 2020-04-17T22:06:54 | 259,399,718 | 0 | 0 | null | 2020-04-27T17:12:19 | 2020-04-27T17:12:19 | null | UTF-8 | C++ | false | false | 1,155 | h | #ifndef SIM_linear_tri2dmesh_neohookean_dq_H
#define SIM_linear_tri2dmesh_neohookean_dq_H
#include <Eigen/Dense>
#include <EigenTypes.h>
#include <assemble.h>
#include <linear_tri2d_neohookean_dq.h>
namespace sim {
//some c++ trickery to allow for default call backs
auto default_callback = [](auto &element_matrix){};
template<typename DerivedRet, typename DerivedV, typename DerivedQ, typename DefoType, typename DerivedVol,
typename DerivedParam, class ElementMatrixCallback = decltype(default_callback)>
void linear_tri2dmesh_neohookean_dq(Eigen::VectorXx<DerivedRet> &H, Eigen::DenseBase<DerivedV> &V, Eigen::Ref<const Eigen::MatrixXi> E,
const Eigen::MatrixBase<DerivedQ> &q,
const Eigen::MatrixBase<DefoType> &dXinv, const Eigen::MatrixBase<DerivedVol> &volume,
const Eigen::MatrixBase<DerivedParam> ¶ms,
const ElementMatrixCallback func = default_callback);
}
#ifndef SIM_STATIC_LIBRARY
# include <../src/linear_tri2dmesh_neohookean_dq.cpp>
#endif
#endif
| [
"dilevin@csail.mit.edu"
] | dilevin@csail.mit.edu |
6ce09c730bada11e8c9e20bba542310ecb950da9 | c30c3466c34c41b49e8c8b2791e0d44ae6277cb2 | /Suffix Tree/src/Suffix Tree.cpp | 503c6a76579913920fd529c8222f3e0c73d95300 | [] | no_license | theAnton-forks/Competitive-Programming-Portfolio | 784eb9ff5441f1a81f5501d690f9094698bc34c7 | fb3f099d7ecc37b9117d64faa4c1bdf89e1f18d2 | refs/heads/master | 2022-12-14T03:18:04.941318 | 2020-09-03T05:22:46 | 2020-09-03T05:22:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 165 | cpp | #include <iostream>
typedef long long ll;
int main() {
std::string str;
std::cin >> str;
for(int i = 0; i <= str.length(); i++){
}
return 0;
}
| [
"vlade.maksimovski@gmail.com"
] | vlade.maksimovski@gmail.com |
b2ea7ec3e8c42e52ccceec16a0f19c71adb659cb | 6d1b158548b2da4e1e2a1761a6bb05a9bffe3bb4 | /Unique_Binary_Search_Trees_II/Unique_Binary_Search_Trees_II_ULT/Unique_Binary_Search_Trees_II_ULT.cpp | f8ff5b0074d17f59a9d197fc885393468e4d55b5 | [] | no_license | SoltiHo/LeetRepository | 636d37f80f62ac59da56ecaf8601441944105f03 | e1353e4a7ecb62898b83edb4cd64c09a4b9b93f7 | refs/heads/master | 2021-01-19T07:46:10.900494 | 2015-07-20T03:05:27 | 2015-07-20T03:05:27 | 25,610,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | #include "gtest/gtest.h" // access test macro
#include "Unique_Binary_Search_Trees_II.h"
TEST(Leet, Basic02){
Solution_DP sol;
sol.generateTrees(5);
}
TEST(Leet, Basic01){
Solution_DP sol;
sol.generateTrees(4);
}
// --------------------------------------------------------------------
| [
"Solti.Ho@Gmail.com"
] | Solti.Ho@Gmail.com |
899f2c82df86acf82375170f960e7f72b23f9185 | a2808ac35b2a639e34d740cde5440511408560f5 | /tests/events_service_ut.cpp | b847adab8fe7cffa7ec31b87e4a962456522f000 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | cisco-aarhodes/sonic-swss-common | a172404ca8e689de006ad22523e15628267bb0b7 | c396ff7b9ecf6a0fe6ae53e84a3f3539dfc9a9a3 | refs/heads/master | 2023-05-26T16:25:26.437472 | 2023-05-17T07:58:41 | 2023-05-17T07:58:41 | 178,019,413 | 0 | 1 | NOASSERTION | 2019-03-27T15:09:34 | 2019-03-27T15:09:34 | null | UTF-8 | C++ | false | false | 4,323 | cpp | #include <iostream>
#include <memory>
#include <thread>
#include <algorithm>
#include <deque>
#include <regex>
#include "gtest/gtest.h"
#include "common/events_common.h"
#include "common/events_service.h"
using namespace std;
static bool do_terminate = false;
static void *zmq_ctx = NULL;
static event_service service_cl, service_svr;
static int server_rd_code, server_ret;
static event_serialized_lst_t server_rd_lst, server_wr_lst;
/* Mimic the eventd service that handles service requests via dedicated thread */
void serve_commands()
{
int code;
event_serialized_lst_t lst, opt_lst;
EXPECT_EQ(0, service_svr.init_server(zmq_ctx, 1000));
while(!do_terminate) {
if (0 != service_svr.channel_read(code, lst)) {
/* check client service status, before blocking on read */
continue;
}
server_rd_code = code;
server_rd_lst = lst;
switch(code) {
case EVENT_CACHE_INIT:
server_ret = 0;
server_wr_lst.clear();
break;
case EVENT_CACHE_START:
server_ret = 0;
server_wr_lst.clear();
break;
case EVENT_CACHE_STOP:
server_ret = 0;
server_wr_lst.clear();
break;
case EVENT_CACHE_READ:
server_ret = 0;
server_wr_lst = { "rerer", "rrrr", "cccc" };
break;
case EVENT_ECHO:
server_ret = 0;
server_wr_lst = lst;
break;
case EVENT_OPTIONS:
server_ret = 0;
if (lst.empty()) {
server_wr_lst = opt_lst;
}
else {
opt_lst = lst;
server_wr_lst.clear();
}
break;
default:
EXPECT_TRUE(false);
server_ret = -1;
break;
}
EXPECT_EQ(0, service_svr.channel_write(server_ret, server_wr_lst));
}
service_svr.close_service();
EXPECT_FALSE(service_svr.is_active());
}
TEST(events_common, cache_cmds)
{
event_serialized_lst_t lst_start, lst;
#if 0
{
/* Direct log messages to stdout */
string dummy, op("STDOUT");
swss::Logger::swssOutputNotify(dummy, op);
swss::Logger::setMinPrio(swss::Logger::SWSS_DEBUG);
}
#endif
zmq_ctx = zmq_ctx_new();
EXPECT_TRUE(NULL != zmq_ctx);
/* Start mock service in a separate thread */
thread thr(&serve_commands);
EXPECT_EQ(0, service_cl.init_client(zmq_ctx));
EXPECT_EQ(0, service_cl.cache_init());
/* Cache init sends echo upon success */
EXPECT_EQ(EVENT_ECHO, server_rd_code);
EXPECT_TRUE(server_rd_lst.empty());
EXPECT_EQ(server_rd_lst, server_wr_lst);
/*
* Bunch of serialized internal_event_t as strings
* Sending random for test purpose
*/
lst_start = event_serialized_lst_t(
{ "hello", "world", "ok" });
EXPECT_EQ(0, service_cl.cache_start(lst_start));
EXPECT_EQ(EVENT_CACHE_START, server_rd_code);
EXPECT_EQ(lst_start, server_rd_lst);
EXPECT_TRUE(server_wr_lst.empty());
EXPECT_EQ(0, service_cl.cache_stop());
EXPECT_EQ(EVENT_CACHE_STOP, server_rd_code);
EXPECT_TRUE(server_rd_lst.empty());
EXPECT_TRUE(server_wr_lst.empty());
EXPECT_EQ(0, service_cl.cache_read(lst));
EXPECT_EQ(EVENT_CACHE_READ, server_rd_code);
EXPECT_TRUE(server_rd_lst.empty());
EXPECT_EQ(server_wr_lst, lst);
string s("hello"), s1;
EXPECT_EQ(0, service_cl.echo_send(s));
EXPECT_EQ(0, service_cl.echo_receive(s1));
EXPECT_EQ(EVENT_ECHO, server_rd_code);
EXPECT_FALSE(server_rd_lst.empty());
EXPECT_EQ(s1, s);
string sopt("{\"HEARTBEAT_INTERVAL\": 2000, \"OFFLINE_CACHE_SIZE\": 500}");
char rd_opt[100];
rd_opt[0] = 0;
EXPECT_EQ(0, service_cl.global_options_set(sopt.c_str()));
EXPECT_LT(0, service_cl.global_options_get(rd_opt, (int)sizeof(rd_opt)));
EXPECT_EQ(EVENT_OPTIONS, server_rd_code);
EXPECT_EQ(sopt, string(rd_opt));
do_terminate = true;
service_cl.close_service();
EXPECT_FALSE(service_cl.is_active());
thr.join();
zmq_ctx_term(zmq_ctx);
}
| [
"noreply@github.com"
] | noreply@github.com |
7c33ab39a65fc3c1bcc73eaeedc92dea700bc9fd | 88f51675ccd4b2b48433bb367f3ebaf9c45049a1 | /Source/DX2DEngine/tga2d/shaders/shader_distance_field_instanced.h | 58344f5b1e7bd0433f832a02016a6de4125444a3 | [] | no_license | PekaOchKlickaGrupp7/PekaOchKlicka | 041c430d1f068d12c28e65b5aa47d339e71c04bd | 8fac3296a2f27c59ba39bb07c8d4415bd415eb01 | refs/heads/master | 2021-01-10T16:01:18.619325 | 2016-02-26T16:57:09 | 2016-02-26T16:57:09 | 49,209,774 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | h | #pragma once
#include "shader.h"
#include "math/vector2.h"
#include "math/vector4.h"
#include "shader_common.h"
namespace DX2D
{
class CTexturedQuadBatch;
class CSprite;
class CShaderDistanceFieldInstanced : public CShader
{
public:
CShaderDistanceFieldInstanced(CEngine* aEngine);
bool Init() override;
void Render(CTexturedQuadBatch* aObject, ID3D11Buffer* aInstanceBuffer, ID3D11Buffer* aVertexBuffer);
protected:
private:
void SetShaderParameters(std::vector<CSprite*>& someSprites, CTexturedQuadBatch* aBatch, ID3D11Buffer* aInstanceBuffer, ID3D11Buffer* aVertexBuffer);
std::vector<ObjectBufferInstanceType> myBufferedObjects;
};
} | [
"linus@neuman.io"
] | linus@neuman.io |
205ddf69fffff0aee04ebcf4f816e8f4d202b146 | 0fbfce2abb13ca88a7f6150f8ba0c3bd6a87ed27 | /source/tools/reference_vector.h | ec4375edcc1f77fcf0d249dd7c2bc6fb602f8481 | [] | no_license | mmore500/Empirical | cb8ee861892f0f5cb0a203d1765b88006330ee7e | 43edffcebb0538182426fe67c0cb0cff35760375 | refs/heads/master | 2023-06-25T17:17:53.374977 | 2020-10-16T23:09:10 | 2020-10-16T23:10:00 | 109,316,865 | 0 | 0 | null | 2017-11-02T20:43:32 | 2017-11-02T20:43:31 | null | UTF-8 | C++ | false | false | 3,636 | h | /**
* @note This file is part of Empirical, https://github.com/devosoft/Empirical
* @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md
* @date 2019
*
* @file reference_vector.h
* @brief A version of vector that holds only references to objects. Be careful!
* @note Status: ALPHA
**/
#ifndef EMP_REFERENCE_VECTOR_H
#define EMP_REFERENCE_VECTOR_H
#include "../base/Ptr.h"
#include "../base/vector.h"
namespace emp {
template <typename T>
class reference_vector {
private:
using this_t = reference_vector<T>;
using vec_t = emp::vector< emp::Ptr<T> >;
vec_t vals;
class Iterator {
/// @todo Add a const interator, and probably a reverse iterator.
private:
typename vec_t::iterator it;
public:
Iterator(this_t & v, size_t pos=0) : it(v.vals.begin() + pos) { ; }
Iterator(const typename vec_t::iterator & in_it) : it(in_it) { ; }
Iterator(const Iterator &) = default;
Iterator & operator=(const Iterator &) = default;
Iterator & operator++() { ++it; return *this; }
Iterator & operator--() { --it; return *this; }
/// Iterator comparisons
bool operator==(const Iterator& in) const { return it == in.it; }
bool operator!=(const Iterator& in) const { return it != in.it; }
bool operator< (const Iterator& in) const { return it < in.it; }
bool operator<=(const Iterator& in) const { return it <= in.it; }
bool operator> (const Iterator& in) const { return it > in.it; }
bool operator>=(const Iterator& in) const { return it >= in.it; }
/// Return a reference to the element pointed to by this iterator; may advance iterator.
T & operator*() { return *(*it); }
/// Return a const reference to the element pointed to by this iterator.
const T & operator*() const { return *(*it); }
/// Is this iterator pointing to a valid position in the vector?
operator bool() const { return (bool) it; }
/// Return an iterator pointing to the first position in the vector.
Iterator begin() { return Iterator(it.begin()); }
/// Return a const iterator pointing to the first position in the vector.
const Iterator begin() const { return Iterator(it.begin()); }
/// Return an iterator pointing to just past the end of the vector.
Iterator end() { return Iterator(it.end()); }
/// Return a const iterator pointing to just past the end of the vector.
const Iterator end() const { return Iterator(it.end()); }
};
using iterator_t = Iterator;
public:
reference_vector() = default;
reference_vector(const reference_vector &) = default;
reference_vector(reference_vector &&) = default;
~reference_vector() { }
this_t & operator=(const reference_vector &) = default;
this_t & operator=(reference_vector &&) = default;
size_t size() const { return vals.size(); }
void resize(size_t new_size) {
emp_assert(new_size <= vals.size(),
"A reference_vector can only be resized smaller; grow using push_back()",
new_size, size());
vals.resize(new_size);
}
T & operator[](size_t id) { return *(vals[id]); }
const T & operator[](size_t id) const { return *(vals[id]); }
void push_back(T & val) { vals.push_back(&val); }
// Iterators
Iterator begin() { return Iterator(vals.begin()); }
const Iterator begin() const { return Iterator(vals.begin()); }
Iterator end() { return Iterator(vals.end()); }
const Iterator end() const { return Iterator(vals.end()); }
};
}
#endif | [
"charles.ofria@gmail.com"
] | charles.ofria@gmail.com |
44e4609e3d304d103890c668cafb46fc30b39006 | 22d3c41426e0aee42c60916bbebb6728d4f91900 | /source/tnn/device/opencl/opencl_utils.h | 43a5fde3d5ee643469e3bb504926efddbbbdb197 | [
"BSD-3-Clause"
] | permissive | airockchip/TNN | ff5e095a9acf35d39e78cb7d3592d9661f9d5ccf | 3d35e9cc4d608fcc9434413207642cbda9056b75 | refs/heads/master | 2022-12-12T14:06:51.757881 | 2020-08-11T11:48:06 | 2020-08-12T05:32:20 | 287,201,899 | 1 | 1 | NOASSERTION | 2020-08-13T06:41:45 | 2020-08-13T06:41:45 | null | UTF-8 | C++ | false | false | 6,032 | h | // Tencent is pleased to support the open source community by making TNN available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 TNN_SOURCE_TNN_DEVICE_OPENCL_OPENCL_UTILES_H_
#define TNN_SOURCE_TNN_DEVICE_OPENCL_OPENCL_UTILES_H_
#include <string>
#include <vector>
#include "tnn/device/opencl/opencl_context.h"
#include "tnn/device/opencl/opencl_execute_unit.h"
#include "tnn/device/opencl/opencl_memory.h"
#include "tnn/device/opencl/opencl_runtime.h"
#include "tnn/core/blob.h"
#include "tnn/interpreter/raw_buffer.h"
namespace TNN_NS {
enum OpenCLBufferFormat {
CONV2D_FILTER = 0,
NHWC_BUFFER = 1,
ARGUMENT = 2,
DW_CONV2D_FILTER = 3,
NCHW_BUFFER = 4,
NHWC4_BUFFER = 5,
};
template <typename T, typename Dim>
inline void IOHW2OIHW(const T *src, T *dst, Dim O, Dim I, Dim H, Dim W) {
for (Dim i = 0; i < I; i++) {
for (Dim o = 0; o < O; o++) {
for (Dim h = 0; h < H; h++) {
for (Dim w = 0; w < W; w++) {
dst[o * I * H * W + i * H * W + h * W + w] = src[i * O * H * W + o * H * W + h * W + w];
}
}
}
}
}
enum GroupWeightsFormat { GOIHW, GIOHW };
template <typename T, typename Dim>
inline void GROUP_PADDING(const T *src, T *dst, Dim G, Dim O, Dim I, Dim H, Dim W, GroupWeightsFormat src_format) {
int input_channel_per_group = I / G;
int group_size_in_o = O / G;
for (Dim o = 0; o < O; o++) {
for (Dim i = 0; i < I; i++) {
for (Dim h = 0; h < H; h++) {
for (Dim w = 0; w < W; w++) {
int dst_idx = o * I * H * W + i * H * W + h * W + w;
int group_id = o / group_size_in_o;
int valid_i_b = group_id * input_channel_per_group;
int valid_i_e = valid_i_b + input_channel_per_group;
if (i < valid_i_b || i >= valid_i_e) {
dst[dst_idx] = 0;
} else {
int g_idx = group_id;
int o_idx = o % group_size_in_o;
int i_idx = i % input_channel_per_group;
int h_idx = h;
int w_idx = w;
// src is GOIHW
int src_idx;
if (src_format == GOIHW) {
src_idx = g_idx * group_size_in_o * input_channel_per_group * H * W +
o_idx * input_channel_per_group * H * W + i_idx * H * W + h_idx * W + w_idx;
} else {
// src is GIOHW
src_idx = g_idx * input_channel_per_group * group_size_in_o * H * W +
i_idx * group_size_in_o * H * W + o_idx * H * W + h_idx * W + w_idx;
}
dst[dst_idx] = src[src_idx];
}
}
}
}
}
}
inline cl::Buffer &GetOpenCLBuffer(const OpenCLMemory *blob) {
return (*(cl::Buffer *)(blob->GetData()));
}
inline cl::Image &GetOpenCLImage(const OpenCLMemory *blob) {
return (*(cl::Image *)(blob->GetData()));
}
std::shared_ptr<float> GetFloatFromRawBuffer(RawBuffer &raw_buffer);
std::vector<int> GetImageShape(const OpenCLMemory *image);
void GetProfilingTime(const cl::Event *event, double &kernel_time, double &event_queued, double &event_submit,
double &event_start, double &event_end);
Status RunKernel(const cl::Kernel &kernel, const std::vector<uint32_t> &gws, const std::vector<uint32_t> &lws,
cl::CommandQueue *command_queue, std::string name = "", OpenCLProfilingData *pdata = nullptr);
std::vector<uint32_t> AdrenoLocalSize2D(const std::vector<uint32_t> &gws, const GpuInfo gpu_info,
const uint32_t compute_units, const uint32_t max_workgroup_size,
const uint32_t subgroup_size);
std::vector<uint32_t> LocalWS3DDefault(OpenCLExecuteUnit &unit);
std::vector<uint32_t> LocalWS3DDefault(const std::vector<uint32_t> &gws, const uint32_t max_workgroup_size,
const uint32_t subgroup_size = 0);
std::vector<uint32_t> LocalWS2DDefault(OpenCLExecuteUnit &unit);
std::vector<uint32_t> LocalWS2DDefault(const std::vector<uint32_t> &gws, const uint32_t max_workgroup_size,
const uint32_t subgroup_size = 0);
Status CopyBufferToImage(OpenCLRuntime *runtime, OpenCLContext *context, const cl::Buffer &buffer,
const cl::Image &image, int w, int h, bool need_wait = false);
Status CopyImageToImage(OpenCLRuntime *runtime, OpenCLContext *context, const cl::Image &src, const cl::Image &dst,
int w, int h, bool need_wait = false, OpenCLProfilingData *pdata = nullptr);
uint32_t gcd(uint32_t number1, uint32_t number2);
Status CreateExecuteUnit(OpenCLExecuteUnit &unit, const std::string &program_name, const std::string &kernel_name,
const std::set<std::string> &build_opt = {});
uint32_t SetExecuteUnit3DSizeInfoDefault(OpenCLExecuteUnit &unit, DimsVector dims);
uint32_t SetExecuteUnit2DSizeInfoDefault(OpenCLExecuteUnit &unit, DimsVector dims);
} // namespace TNN_NS
#endif // TNN_SOURCE_TNN_DEVICE_OPENCL_OPENCL_UTILES_H_
| [
"darrenyao@tencent.com"
] | darrenyao@tencent.com |
7bf604288e049d47d392e44f2974ccaaafb3ce2f | b08a4eeabc5495d24f309d9a9ea6da7104277f4a | /All Them Pixels/All Them Pixels/ValueBar.h | fc2b2854beb6d87b2fd82ae6bd7de696bd383d65 | [] | no_license | Kanel/AllThemPixels | f776b49005eeff7cb99e32184c86dfcea55c2339 | 61be150419c46ac2a832a06f95f3bdc3af3c7125 | refs/heads/master | 2021-01-10T19:32:32.066249 | 2013-09-22T17:07:52 | 2013-09-22T17:07:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 769 | h | #pragma once
#include "Vector2fMath.h"
#include "Collision.h"
#include <SFML\Graphics.hpp>
using namespace sf;
class ValueBar : public Drawable
{
private:
float min;
float max;
float value;
float size;
float margin;
Vector2f start;
Vector2f end;
Vertex background[4];
Vertex foreground[4];
public:
ValueBar(Vector2f start, Vector2f end, float margin, float size, float min = 0, float max = 100, float value = 0);
void setPoints(Vector2f start, Vector2f end);
float getValue();
ConvexHull getConvexHull();
bool containsPoint(Vector2f point);
void update(Vector2f point);
virtual void draw(RenderTarget& target, RenderStates states) const;
private:
void generateBackground();
void generateForeground();
}; | [
"joakim@celestus.se"
] | joakim@celestus.se |
58418ed647ee87c4e164ec7b0d76de7d6b5ca0f2 | 71305fba783f04a7925cf2baef6bbd348f443ebb | /check_qobject/test/widget2.h | 05c083e8c5adff968c8faa44d9802ea0afd4d7ac | [] | no_license | zhugp125/PythonProject | 2c237207586b26846dfd28400b6f60722eaa7734 | 2f007fcd7f51a1c80631e7dce338e8e6f4e92777 | refs/heads/master | 2020-04-29T06:24:54.460646 | 2019-04-27T00:51:14 | 2019-04-27T00:51:14 | 110,132,953 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 187 | h | #ifndef WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget* parent = NULL);
public slots:
void onclicked();
};
#endif // !WIDGET_H | [
"18811475054@163.com"
] | 18811475054@163.com |
e706d35e12710bc1e4ad9117969583b6a1ddf590 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /DP/2634.cpp | 7963bc64cc0bb23e6f749b67215dcc23a481e2e5 | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | #include <bits/stdc++.h>
std::vector<int> ans;
void init() {
for (int i = 10; i <= 20000000; i ++) {
int x = i, digit = 0;
while (x) {
digit += x % 10;
x /= 10;
}
if (digit == 10) {
ans.push_back(i);
}
}
}
int main() {
init();
int k;
std::cin >> k;
std::cout << ans[k - 1] << '\n';
return 0;
}
| [
"mukeshchugani10@gmail.com"
] | mukeshchugani10@gmail.com |
cc6598d5fd9a26322e1a1aa0bc4034096dba5766 | 4c1d515719425db127ba5285b5be4f03af10d5a1 | /URI-Judge/URI_1195.cpp | d330768042837c6c8a97aa54fab86ae8451fceb3 | [] | no_license | matheusmtta/Competitive-Programming | 26e51741332aed223b9231da33749940f5a1b977 | e254b80090cc75bc213aad0a7957875842e90f1a | refs/heads/master | 2023-04-28T18:08:51.417470 | 2023-04-24T21:09:00 | 2023-04-24T21:09:00 | 223,605,672 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,603 | cpp | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define MP make_pair
#define PB push_back
typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
struct node{
int value;
struct node *left, *right;
};
struct node *newNode(int x){
struct node *tmp = new node;
tmp->value = x;
tmp->left = tmp->right = nullptr;
return tmp;
}
struct node* insert(struct node* node, int x){
if (node == nullptr) return newNode(x);
if (x < node->value)
node->left = insert(node->left, x);
else if (x > node->value)
node->right = insert(node->right, x);
return node;
}
void get_infix(struct node *v){
if (v != nullptr){
get_infix(v->left);
cout << " " << v->value;
get_infix(v->right);
}
}
void get_post(struct node *v){
if (v != nullptr){
get_post(v->left);
get_post(v->right);
cout << " " << v->value;
}
}
void get_prefix(struct node *v){
if (v != nullptr){
cout << " " << v->value;
get_prefix(v->left);
get_prefix(v->right);
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t; cin >> t;
int q = 1;
while (t--){
cout << "Case " << q << ":" << endl;
int n; cin >> n;
struct node *root = nullptr;
int x; cin >> x;
root = insert(root, x);
for (int i = 1; i < n; i++){
int x; cin >> x;
insert(root, x);
}
cout << "Pre.:";
get_prefix(root);
cout << endl;
cout << "In..:";
get_infix(root);
cout << endl;
cout << "Post:";
get_post(root);
cout << endl;
q++;
cout << endl;
}
return 0;
} | [
"matheusaquino199@gmail.com"
] | matheusaquino199@gmail.com |
a4c6e915717ad22fb9064c5357a259b1ee4897f7 | bf740abedafd4096203f5f45a388df808bada16f | /src/timer/tcsr.h | e23bbd66c9b8a87cb40308000d80d355a5e09bfa | [] | no_license | shimomura1004/h8_emulator | e96c9fe87ce52ba0b5f0f08264a2e1edd5d6bd08 | 16b3c2467f9912a28aacc0df3c587c79200f0ad5 | refs/heads/master | 2023-07-24T14:30:59.244751 | 2021-09-01T07:01:19 | 2021-09-01T07:01:19 | 327,459,845 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | h | #ifndef _TIMER_TCSR_INCLUDED_
#define _TIMER_TCSR_INCLUDED_
#include <cstdint>
class TCSR {
uint8_t reg;
public:
TCSR(uint8_t channel) : reg(channel != 2 ? 0x00 : 0x10) {}
uint8_t get_raw();
void set_raw(uint8_t value);
bool get_tcsr_cmfb();
bool get_tcsr_cmfa();
bool get_tcsr_ovf();
bool get_tcsr_adte_ice();
uint8_t get_tcsr_ois();
void set_tcsr_cmfb(bool b);
void set_tcsr_cmfa(bool b);
void set_tcsr_ovf(bool b);
};
#endif
| [
"graueule@gmail.com"
] | graueule@gmail.com |
e292eed20d63387dece66547b421b5face7e3d1b | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_repos_function_2180_curl-7.55.1.cpp | 2809e983f09f43661646b1e8e41b6c2d510f74db | [] | 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 | 2,769 | cpp | int
Curl_getaddrinfo_ex(const char *nodename,
const char *servname,
const struct addrinfo *hints,
Curl_addrinfo **result)
{
const struct addrinfo *ai;
struct addrinfo *aihead;
Curl_addrinfo *cafirst = NULL;
Curl_addrinfo *calast = NULL;
Curl_addrinfo *ca;
size_t ss_size;
int error;
*result = NULL; /* assume failure */
error = getaddrinfo(nodename, servname, hints, &aihead);
if(error)
return error;
/* traverse the addrinfo list */
for(ai = aihead; ai != NULL; ai = ai->ai_next) {
/* ignore elements with unsupported address family, */
/* settle family-specific sockaddr structure size. */
if(ai->ai_family == AF_INET)
ss_size = sizeof(struct sockaddr_in);
#ifdef ENABLE_IPV6
else if(ai->ai_family == AF_INET6)
ss_size = sizeof(struct sockaddr_in6);
#endif
else
continue;
/* ignore elements without required address info */
if((ai->ai_addr == NULL) || !(ai->ai_addrlen > 0))
continue;
/* ignore elements with bogus address size */
if((size_t)ai->ai_addrlen < ss_size)
continue;
ca = malloc(sizeof(Curl_addrinfo));
if(!ca) {
error = EAI_MEMORY;
break;
}
/* copy each structure member individually, member ordering, */
/* size, or padding might be different for each platform. */
ca->ai_flags = ai->ai_flags;
ca->ai_family = ai->ai_family;
ca->ai_socktype = ai->ai_socktype;
ca->ai_protocol = ai->ai_protocol;
ca->ai_addrlen = (curl_socklen_t)ss_size;
ca->ai_addr = NULL;
ca->ai_canonname = NULL;
ca->ai_next = NULL;
ca->ai_addr = malloc(ss_size);
if(!ca->ai_addr) {
error = EAI_MEMORY;
free(ca);
break;
}
memcpy(ca->ai_addr, ai->ai_addr, ss_size);
if(ai->ai_canonname != NULL) {
ca->ai_canonname = strdup(ai->ai_canonname);
if(!ca->ai_canonname) {
error = EAI_MEMORY;
free(ca->ai_addr);
free(ca);
break;
}
}
/* if the return list is empty, this becomes the first element */
if(!cafirst)
cafirst = ca;
/* add this element last in the return list */
if(calast)
calast->ai_next = ca;
calast = ca;
}
/* destroy the addrinfo list */
if(aihead)
freeaddrinfo(aihead);
/* if we failed, also destroy the Curl_addrinfo list */
if(error) {
Curl_freeaddrinfo(cafirst);
cafirst = NULL;
}
else if(!cafirst) {
#ifdef EAI_NONAME
/* rfc3493 conformant */
error = EAI_NONAME;
#else
/* rfc3493 obsoleted */
error = EAI_NODATA;
#endif
#ifdef USE_WINSOCK
SET_SOCKERRNO(error);
#endif
}
*result = cafirst;
/* This is not a CURLcode */
return error;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
6e3d90761eaae81d0be8c3df2263d9f3c3ef1d48 | eb9eea5631cfc247a8e780b98e3220ccd7682223 | /CS2040C/Kattis/oddities.cpp | 5dd60ef82cee1a1fe0c6ac6a0c38ebd920c0e4bb | [] | no_license | px1099/CS2040C-C-files | 2b7520fe2015c2f6f35e12f13c330c1f6a5cb4ea | 677bcc81ae16e7c6a198eb8cab9d90770dcef5f7 | refs/heads/master | 2020-03-17T09:33:23.891641 | 2019-04-22T09:16:31 | 2019-04-22T09:16:31 | 133,479,667 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | // oddities
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, x;
cin >> n;
for (int i=0; i<n; i++) {
cin >> x;
cout << x << " is " << ((x%2==0) ? "even" : "odd") << endl;
}
return 0;
} | [
"px1099@gmail.com"
] | px1099@gmail.com |
20146d67ab2062e28da3340f144f4eeacdd7be8a | 864dc68b63491e6286b43ad7e9ef6c615cb6d672 | /200-str C++/200-str C++/Source.cpp | bfa2092d56cd57cad6f3619bddebd8d0e47e02e1 | [] | no_license | HristoHristov95/C-- | 849b65859b17f81f5f7c19218c38474b44ba7616 | a3cb964cf931f3b2c11eb2ed0fe8841fd0d0c5ac | refs/heads/master | 2021-01-01T03:51:38.704768 | 2016-04-15T18:03:18 | 2016-04-15T18:03:18 | 56,339,634 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 125 | cpp | #include<iostream>
using namespace std;
class myclass
{
int x, y;
public:
myclass(int i = 0, int j = 0){ x = i; y = j; }
}; | [
"hristo_ultimeted@yahoo.com"
] | hristo_ultimeted@yahoo.com |
797650a11162a7e530a0fe627892de076765785b | ad10052619b7bc79d311940bd2419772c4bc8a53 | /topcoder-master-2/RepaintTheChessboard.cpp | ee65d346cd74b698df0f51eea89f6f76b0617fe3 | [] | no_license | bluepine/topcoder | 3af066a5b1ac6c448c50942f98deb2aa382ba040 | d300c8a349a8346dba4a5fe3b4f43b17207627a1 | refs/heads/master | 2021-01-19T08:15:06.539102 | 2014-04-02T21:10:58 | 2014-04-02T21:10:58 | 18,381,690 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,860 | cpp | // BEGIN CUT HERE
// END CUT HERE
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <numeric>
// BEGIN CUT HERE
#include "cout.hpp"
// END CUT HERE
using namespace std;
class RepaintTheChessboard {
public:
int minimumChanges(vector <string> board) {
int ret = 64;
int i, j, k, l;
char board1[8][8] = {{'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B'}, {'B', 'W', 'B', 'W', 'B', 'W', 'B', 'W'},
{'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B'}, {'B', 'W', 'B', 'W', 'B', 'W', 'B', 'W'},
{'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B'}, {'B', 'W', 'B', 'W', 'B', 'W', 'B', 'W'},
{'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B'}, {'B', 'W', 'B', 'W', 'B', 'W', 'B', 'W'}};
char board2[8][8] = {{'B', 'W', 'B', 'W', 'B', 'W', 'B', 'W'}, {'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B'},
{'B', 'W', 'B', 'W', 'B', 'W', 'B', 'W'}, {'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B'},
{'B', 'W', 'B', 'W', 'B', 'W', 'B', 'W'}, {'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B'},
{'B', 'W', 'B', 'W', 'B', 'W', 'B', 'W'}, {'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B'}};
for (i=0; i<=board.size()-8; i++)
for (j=0; j<=board[0].size()-8; j++) {
int tmp1 = 0, tmp2 = 0;
for (k=0; k<8; k++)
for (l=0; l<8; l++)
if (board[i+k][j+l] != board1[k][l])
tmp1++;
for (k=0; k<8; k++)
for (l=0; l<8; l++)
if (board[i+k][j+l] != board2[k][l])
tmp2++;
ret = min(ret, min(tmp1, tmp2));
}
return ret;
}
// BEGIN CUT HERE
public:
void run_test(int Case) {
if ((Case == -1) || (Case == 0)) test_case_0();
if ((Case == -1) || (Case == 1)) test_case_1();
if ((Case == -1) || (Case == 2)) test_case_2();
if ((Case == -1) || (Case == 3)) test_case_3();
if ((Case == -1) || (Case == 4)) test_case_4();
if ((Case == -1) || (Case == 5)) test_case_5();
if ((Case == -1) || (Case == 6)) test_case_6();
if ((Case == -1) || (Case == 7)) test_case_7();
}
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() {
string Arr0[] = {"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB"}
;
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
int Arg1 = 0;
verify_case(0, Arg1, minimumChanges(Arg0)); }
void test_case_1() {
string Arr0[] = {"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBBBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW"};
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
int Arg1 = 1;
verify_case(1, Arg1, minimumChanges(Arg0)); }
void test_case_2() {
string Arr0[] = {"BBBBBBBBBBBBBBBBBBBBBBB",
"BBBBBBBBBBBBBBBBBBBBBBB",
"BBBBBBBBBBBBBBBBBBBBBBB",
"BBBBBBBBBBBBBBBBBBBBBBB",
"BBBBBBBBBBBBBBBBBBBBBBB",
"BBBBBBBBBBBBBBBBBBBBBBB",
"BBBBBBBBBBBBBBBBBBBBBBB",
"BBBBBBBBBBBBBBBBBBBBBBB",
"BBBBBBBBBBBBBBBBBBBBBBW"}
;
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
int Arg1 = 31;
verify_case(2, Arg1, minimumChanges(Arg0)); }
void test_case_3() {
string Arr0[] = {"BBBBBBBBBB",
"BBWBWBWBWB",
"BWBWBWBWBB",
"BBWBWBWBWB",
"BWBWBWBWBB",
"BBWBWBWBWB",
"BWBWBWBWBB",
"BBWBWBWBWB",
"BWBWBWBWBB",
"BBBBBBBBBB"};
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
int Arg1 = 0;
verify_case(3, Arg1, minimumChanges(Arg0)); }
void test_case_4() {
string Arr0[] = {"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBBBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWWWB",
"BWBWBWBW"};
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
int Arg1 = 2;
verify_case(4, Arg1, minimumChanges(Arg0)); }
void test_case_5() {
string Arr0[] = {"BWWBWWBWWBWW",
"BWWBWBBWWBWW",
"WBWWBWBBWWBW",
"BWWBWBBWWBWW",
"WBWWBWBBWWBW",
"BWWBWBBWWBWW",
"WBWWBWBBWWBW",
"BWWBWBWWWBWW",
"WBWWBWBBWWBW",
"BWWBWBBWWBWW",
"WBWWBWBBWWBW"}
;
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
int Arg1 = 15;
verify_case(5, Arg1, minimumChanges(Arg0)); }
void test_case_6() {
string Arr0[] = {"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB"}
;
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
int Arg1 = 0;
verify_case(6, Arg1, minimumChanges(Arg0)); }
void test_case_7() {
string Arr0[] = {"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB",
"BWBWBWBW",
"WBWBWBWB"}
;
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
int Arg1 = 0;
verify_case(7, Arg1, minimumChanges(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
RepaintTheChessboard ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"1983.song.wei@gmail.com"
] | 1983.song.wei@gmail.com |
f9a50cda5f317d7599bd5a5cdcc3ccc8da63219a | 7dbad8f9f2269476c8883ae9c4e23d53d4e5bbda | /udemy/FirstProgram/src/main.cpp | 147f1b9b19d24a5374c146fabfea9ed55b5e884a | [] | no_license | Geschoss/beginning-c-plus-plus | 422cf6c707eece4d3f33617d61a7d7c83b5351fb | a28806c29f308fe43df83cc290790a62ac6fb649 | refs/heads/master | 2022-03-09T18:28:11.657722 | 2022-01-22T09:25:31 | 2022-01-22T09:25:31 | 232,835,657 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 695 | cpp | #include <iostream>
using std::cout;
using std::endl;
using std::cin;
using std::to_string;
template <typename T>
void log(T str) {
cout << str << endl;
}
int main()
{
int favorite_number;
log("Enter you favorite number between 1 and 100");
cin >> favorite_number;
if (favorite_number > 18)
log("Пес " + to_string(favorite_number));
else
log(favorite_number);
while (favorite_number != 0)
{
log("while " + to_string(favorite_number));
favorite_number--;
}
for (int i=0; i < 5; i++)
log("for " + to_string(i));
// this is comment
/*
sdfsdf
sdfsdf
*/
return 0;
} | [
"p.e.kolomnikov@tinkoff.ru"
] | p.e.kolomnikov@tinkoff.ru |
48f3a396d5ed1bfa00c1d34ab2fae33085f5a1e3 | ef91a0d2742274151949b848e34f3398e75a7b5b | /PyoFilter_win/JuceLibraryCode/modules/juce_core/juce_core.cpp | b27511bdaad0072694cb84059865545b91fed779 | [] | no_license | JVanBuskirk/PyoFilter | 6a6e5784cad6298ca56774cb4d884a2685464efc | 0698e7c41ec4cde533a841f5b18f0c5ec88c27e4 | refs/heads/master | 2021-03-19T11:53:59.100450 | 2018-07-25T01:02:50 | 2018-07-25T01:02:50 | 98,043,005 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,221 | cpp | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#ifdef JUCE_CORE_H_INCLUDED
/* When you add this cpp file to your project, you mustn't include it in a file where you've
already included any other headers - just put it inside a file on its own, possibly with your config
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
header files that the compiler may be using.
*/
#error "Incorrect use of JUCE cpp file"
#endif
#define JUCE_CORE_INCLUDE_OBJC_HELPERS 1
#define JUCE_CORE_INCLUDE_COM_SMART_PTR 1
#define JUCE_CORE_INCLUDE_NATIVE_HEADERS 1
#include "juce_core.h"
#include <locale>
#include <cctype>
#include <cstdarg>
#if ! JUCE_ANDROID
#include <sys/timeb.h>
#include <cwctype>
#endif
#if JUCE_WINDOWS
#include <ctime>
#if ! JUCE_MINGW
#pragma warning (push)
#pragma warning (disable: 4091)
#include <Dbghelp.h>
#pragma warning (pop)
#if ! JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES
#pragma comment (lib, "DbgHelp.lib")
#endif
#endif
#if JUCE_MINGW
#include <ws2spi.h>
#endif
#else
#if JUCE_LINUX || JUCE_ANDROID
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <unistd.h>
#include <netinet/in.h>
#endif
#if JUCE_LINUX
#include <stdio.h>
#include <langinfo.h>
#include <ifaddrs.h>
#include <sys/resource.h>
#if JUCE_USE_CURL
#include <curl/curl.h>
#endif
#endif
#include <pwd.h>
#include <fcntl.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/time.h>
#include <net/if.h>
#include <sys/ioctl.h>
#if ! JUCE_ANDROID
#include <execinfo.h>
#endif
#endif
#if JUCE_MAC || JUCE_IOS
#include <xlocale.h>
#include <mach/mach.h>
#endif
#if JUCE_ANDROID
#include <android/log.h>
#endif
#undef check
//==============================================================================
#ifndef JUCE_STANDALONE_APPLICATION
JUCE_COMPILER_WARNING ("Please re-save your project with the latest Projucer version to avoid this warning")
#define JUCE_STANDALONE_APPLICATION 0
#endif
//==============================================================================
namespace juce
{
#include "containers/juce_AbstractFifo.cpp"
#include "containers/juce_NamedValueSet.cpp"
#include "containers/juce_ListenerList.cpp"
#include "containers/juce_PropertySet.cpp"
#include "containers/juce_Variant.cpp"
#include "files/juce_DirectoryIterator.cpp"
#include "files/juce_File.cpp"
#include "files/juce_FileInputStream.cpp"
#include "files/juce_FileOutputStream.cpp"
#include "files/juce_FileSearchPath.cpp"
#include "files/juce_TemporaryFile.cpp"
#include "javascript/juce_JSON.cpp"
#include "javascript/juce_Javascript.cpp"
#include "containers/juce_DynamicObject.cpp"
#include "logging/juce_FileLogger.cpp"
#include "logging/juce_Logger.cpp"
#include "maths/juce_BigInteger.cpp"
#include "maths/juce_Expression.cpp"
#include "maths/juce_Random.cpp"
#include "memory/juce_MemoryBlock.cpp"
#include "misc/juce_RuntimePermissions.cpp"
#include "misc/juce_Result.cpp"
#include "misc/juce_Uuid.cpp"
#include "misc/juce_StdFunctionCompat.cpp"
#include "network/juce_MACAddress.cpp"
#include "network/juce_NamedPipe.cpp"
#include "network/juce_Socket.cpp"
#include "network/juce_IPAddress.cpp"
#include "streams/juce_BufferedInputStream.cpp"
#include "streams/juce_FileInputSource.cpp"
#include "streams/juce_InputStream.cpp"
#include "streams/juce_MemoryInputStream.cpp"
#include "streams/juce_MemoryOutputStream.cpp"
#include "streams/juce_SubregionStream.cpp"
#include "system/juce_SystemStats.cpp"
#include "text/juce_CharacterFunctions.cpp"
#include "text/juce_Identifier.cpp"
#include "text/juce_LocalisedStrings.cpp"
#include "text/juce_String.cpp"
#include "streams/juce_OutputStream.cpp"
#include "text/juce_StringArray.cpp"
#include "text/juce_StringPairArray.cpp"
#include "text/juce_StringPool.cpp"
#include "text/juce_TextDiff.cpp"
#include "text/juce_Base64.cpp"
#include "threads/juce_ReadWriteLock.cpp"
#include "threads/juce_Thread.cpp"
#include "threads/juce_ThreadPool.cpp"
#include "threads/juce_TimeSliceThread.cpp"
#include "time/juce_PerformanceCounter.cpp"
#include "time/juce_RelativeTime.cpp"
#include "time/juce_Time.cpp"
#include "unit_tests/juce_UnitTest.cpp"
#include "xml/juce_XmlDocument.cpp"
#include "xml/juce_XmlElement.cpp"
#include "zip/juce_GZIPDecompressorInputStream.cpp"
#include "zip/juce_GZIPCompressorOutputStream.cpp"
#include "zip/juce_ZipFile.cpp"
#include "files/juce_FileFilter.cpp"
#include "files/juce_WildcardFileFilter.cpp"
//==============================================================================
#if JUCE_ANDROID
#include "native/juce_android_JNIHelpers.h"
#endif
#if ! JUCE_WINDOWS
#include "native/juce_posix_SharedCode.h"
#include "native/juce_posix_NamedPipe.cpp"
#endif
//==============================================================================
#if JUCE_MAC || JUCE_IOS
#include "native/juce_mac_Files.mm"
#include "native/juce_mac_Network.mm"
#include "native/juce_mac_Strings.mm"
#include "native/juce_mac_SystemStats.mm"
#include "native/juce_mac_Threads.mm"
//==============================================================================
#elif JUCE_WINDOWS
#include "native/juce_win32_Files.cpp"
#include "native/juce_win32_Network.cpp"
#include "native/juce_win32_Registry.cpp"
#include "native/juce_win32_SystemStats.cpp"
#include "native/juce_win32_Threads.cpp"
//==============================================================================
#elif JUCE_LINUX
#include "native/juce_linux_CommonFile.cpp"
#include "native/juce_linux_Files.cpp"
#include "native/juce_linux_Network.cpp"
#if JUCE_USE_CURL
#include "native/juce_curl_Network.cpp"
#endif
#include "native/juce_linux_SystemStats.cpp"
#include "native/juce_linux_Threads.cpp"
//==============================================================================
#elif JUCE_ANDROID
#include "native/juce_linux_CommonFile.cpp"
#include "native/juce_android_Files.cpp"
#include "native/juce_android_Misc.cpp"
#include "native/juce_android_Network.cpp"
#include "native/juce_android_SystemStats.cpp"
#include "native/juce_android_Threads.cpp"
#include "native/juce_android_RuntimePermissions.cpp"
#endif
#include "threads/juce_ChildProcess.cpp"
#include "threads/juce_HighResolutionTimer.cpp"
#include "network/juce_URL.cpp"
#include "network/juce_WebInputStream.cpp"
//==============================================================================
/*
As the very long class names here try to explain, the purpose of this code is to cause
a linker error if not all of your compile units are consistent in the options that they
enable before including JUCE headers. The reason this is important is that if you have
two cpp files, and one includes the juce headers with debug enabled, and the other doesn't,
then each will be generating code with different memory layouts for the classes, and
you'll get subtle and hard-to-track-down memory corruption bugs!
*/
#if JUCE_DEBUG
this_will_fail_to_link_if_some_of_your_compile_units_are_built_in_debug_mode
::this_will_fail_to_link_if_some_of_your_compile_units_are_built_in_debug_mode() noexcept {}
#else
this_will_fail_to_link_if_some_of_your_compile_units_are_built_in_release_mode
::this_will_fail_to_link_if_some_of_your_compile_units_are_built_in_release_mode() noexcept {}
#endif
}
| [
"JVanBuskirk@users.noreply.github.com"
] | JVanBuskirk@users.noreply.github.com |
7f45cd49f40195dd4ba6ab9935904537eebffa79 | bb20ba88cc104e320374612e00fdddd5fefe86d8 | /C++/3rd_Party/CGAL/include/CGAL/Cartesian/Circle_3.h | 48940e21d775befd0cfd48ce83b021982ec431e9 | [] | no_license | cbtogu/3DLearning | 5949e22d16f14a57ab04e0eec0ef1c4364747c76 | 9cfc64ad1e0473aff4e2aef34da50731249d3433 | refs/heads/master | 2022-01-31T10:37:58.177148 | 2017-07-06T15:11:43 | 2017-07-06T15:11:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,783 | h | // Copyright (c) 2000
// Utrecht University (The Netherlands),
// ETH Zurich (Switzerland),
// INRIA Sophia-Antipolis (France),
// Max-Planck-Institute Saarbruecken (Germany),
// and Tel-Aviv University (Israel). All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id: Circle_3.h,v 1.4 2017/02/06 12:37:04 Emmanuel.Pot Exp $
//
// Author(s) : Monique Teillaud, Pedro Machado, Sebastien Loriot
#ifndef CGAL_CARTESIAN_CIRCLEC3_H
#define CGAL_CARTESIAN_CIRCLEC3_H
#include <CGAL/Interval_nt.h>
namespace CGAL {
template <class R_ >
class CircleC3 {
typedef typename R_::Sphere_3 Sphere_3;
typedef typename R_::Plane_3 Plane_3;
typedef typename R_::Point_3 Point_3;
typedef typename R_::Vector_3 Vector_3;
typedef typename R_::Direction_3 Direction_3;
typedef typename R_::FT FT;
typedef std::pair<Sphere_3, Plane_3> Rep;
typedef typename R_::template Handle<Rep>::type Base;
Base base;
public:
typedef R_ R;
CircleC3() {}
CircleC3(const Point_3& center, const FT& squared_r, const Direction_3& d)
{
CGAL_kernel_assertion(squared_r >= FT(0));
// non-degenerated Direction
CGAL_kernel_assertion((d.dx() != FT(0)) || (d.dy() != FT(0)) || (d.dz() != FT(0)));
base = Rep(Sphere_3(center,squared_r),
plane_from_point_direction(center, d));
}
CircleC3(const Point_3& center, const FT& squared_r, const Vector_3& normal)
{
CGAL_kernel_assertion(squared_r >= FT(0));
// non-degenerated Vector
CGAL_kernel_assertion((normal.x() != FT(0)) ||
(normal.y() != FT(0)) ||
(normal.z() != FT(0)));
base = Rep(Sphere_3(center,squared_r),
Plane_3(center, normal.direction()));
}
CircleC3(const Point_3& center, const FT& squared_r, const Plane_3& p)
{
// the plane contains the center and it is not degenerate
CGAL_kernel_assertion(!R().is_degenerate_3_object()(p));
CGAL_kernel_assertion((p.a() * center.x() +
p.b() * center.y() +
p.c() * center.z() +
p.d()) == CGAL::ZERO);
CGAL_kernel_assertion(squared_r >= FT(0));
base = Rep(Sphere_3(center,squared_r), p);
}
CircleC3(const Sphere_3 &s1, const Sphere_3 &s2) {
Object obj = R().intersect_3_object()(s1, s2);
// s1,s2 must intersect
CGAL_kernel_precondition(!(obj.is_empty()));
const typename R::Circle_3* circle_ptr=object_cast<typename R::Circle_3>(&obj);
if(circle_ptr!=NULL)
base = Rep(circle_ptr->diametral_sphere(), circle_ptr->supporting_plane());
else {
const typename R::Point_3* point=object_cast<typename R::Point_3>(&obj);
CGAL_kernel_precondition(point!=NULL);
CircleC3 circle = CircleC3(*point, FT(0), Vector_3(FT(1),FT(0),FT(0)));
base = Rep(circle.diametral_sphere(), circle.supporting_plane());
}
}
CircleC3(const Plane_3 &p, const Sphere_3 &s, int) : base(s, p) {}
CircleC3(const Plane_3 &p, const Sphere_3 &s) {
Object obj = R().intersect_3_object()(p, s);
// s1,s2 must intersect
CGAL_kernel_precondition(!(obj.is_empty()));
const typename R::Circle_3* circle_ptr=object_cast<typename R::Circle_3>(&obj);
if(circle_ptr!=NULL)
base = Rep(circle_ptr->diametral_sphere(), circle_ptr->supporting_plane());
else {
const typename R::Point_3* point=object_cast<typename R::Point_3>(&obj);
CGAL_kernel_precondition(point!=NULL);
CircleC3 circle = CircleC3(*point, FT(0), Vector_3(FT(1),FT(0),FT(0)));
base = Rep(circle.diametral_sphere(), circle.supporting_plane());
}
}
CircleC3(const Point_3 &p, const Point_3 &q, const Point_3 &r) {
// p, q, r are not collinear
CGAL_kernel_precondition(!R().collinear_3_object()(p, q, r));
Plane_3 p1 = R().construct_plane_3_object()(p, q, r);
Plane_3 p2 = R().construct_bisector_3_object()(p, q);
Plane_3 p3 = R().construct_bisector_3_object()(p, r);
Object obj = R().intersect_3_object()(p1, p2, p3);
// must be a point, otherwise they are collinear
const Point_3& center=*object_cast<Point_3>(&obj);
FT sqr = R().compute_squared_distance_3_object()(center, r);
Sphere_3 s = R().construct_sphere_3_object()(center, sqr);
base = Rep(s, p1);
}
const Plane_3& supporting_plane() const
{
return get_pointee_or_identity(base).second;
}
const Sphere_3& supporting_sphere() const
{
return diametral_sphere();
}
Point_3 center() const
{
return diametral_sphere().center();
}
FT squared_radius() const
{
return diametral_sphere().squared_radius();
}
const Sphere_3& diametral_sphere() const
{
return get_pointee_or_identity(base).first;
}
double approximate_area() const
{
return CGAL_PI * to_double(squared_radius());
}
double approximate_squared_length() const
{
return CGAL_PI * CGAL_PI * 4.0 * to_double(squared_radius());
}
FT area_divided_by_pi() const
{
return squared_radius();
}
FT squared_length_divided_by_pi_square() const
{
return 4 * squared_radius();
}
// this bbox function
// can be optimize by doing different cases
// for each variable = 0 (cases with is_zero)
CGAL::Bbox_3 bbox() const
{
typedef CGAL::Interval_nt<false> Interval;
CGAL::Interval_nt<false>::Protector ip;
const Sphere_3 &s = diametral_sphere();
const FT &sq_r = s.squared_radius();
const Point_3 &p = s.center();
if(sq_r == FT(0)) return p.bbox();
const Plane_3 &plane = supporting_plane();
const Interval a = CGAL::to_interval(plane.a());
const Interval b = CGAL::to_interval(plane.b());
const Interval c = CGAL::to_interval(plane.c());
const Interval x = CGAL::to_interval(p.x());
const Interval y = CGAL::to_interval(p.y());
const Interval z = CGAL::to_interval(p.z());
const Interval r2 = CGAL::to_interval(sq_r);
const Interval r = CGAL::sqrt(r2); // maybe we can work with r2
// in order to save this operation
// but if the coefficients are to high
// the multiplication would lead to inf
// results
const Interval a2 = CGAL::square(a);
const Interval b2 = CGAL::square(b);
const Interval c2 = CGAL::square(c);
const Interval sqr_sum = a2 + b2 + c2;
const Interval mx = r * CGAL::sqrt((sqr_sum - a2)/sqr_sum);
const Interval my = r * CGAL::sqrt((sqr_sum - b2)/sqr_sum);
const Interval mz = r * CGAL::sqrt((sqr_sum - c2)/sqr_sum);
return CGAL::Bbox_3((x-mx).inf(),(y-my).inf(),(z-mz).inf(),
(x+mx).sup(),(y+my).sup(),(z+mz).sup());
}
bool operator==(const CircleC3 &) const;
bool operator!=(const CircleC3 &) const;
bool has_on(const Point_3 &p) const;
bool has_on_bounded_side(const Point_3 &p) const;
bool has_on_unbounded_side(const Point_3 &p) const;
Bounded_side bounded_side(const Point_3 &p) const;
bool is_degenerate() const
{
return diametral_sphere().is_degenerate();
}
};
template < class R >
inline
bool
CircleC3<R>::
has_on(const typename CircleC3<R>::Point_3 &p) const
{
return R().has_on_3_object()(diametral_sphere(),p) &&
R().has_on_3_object()(supporting_plane(),p);
}
template < class R >
inline
bool
CircleC3<R>::
has_on_bounded_side(const typename CircleC3<R>::Point_3 &p) const
{
CGAL_kernel_precondition(R().has_on_3_object()(supporting_plane(), p));
return squared_distance(center(),p) < squared_radius();
}
template < class R >
inline
bool
CircleC3<R>::
has_on_unbounded_side(const typename CircleC3<R>::Point_3 &p) const
{
CGAL_kernel_precondition(R().has_on_3_object()(supporting_plane(), p));
return squared_distance(center(),p) > squared_radius();
}
template < class R >
CGAL_KERNEL_INLINE
Bounded_side
CircleC3<R>::
bounded_side(const typename CircleC3<R>::Point_3 &p) const
{
CGAL_kernel_precondition(is_degenerate() || R().has_on_3_object()(supporting_plane(), p));
return diametral_sphere().bounded_side(p);
}
template < class R >
CGAL_KERNEL_INLINE
bool
CircleC3<R>::operator==(const CircleC3<R> &t) const
{
if (CGAL::identical(base, t.base))
return true;
if(!(center() == t.center() &&
squared_radius() == t.squared_radius())) return false;
const typename R::Plane_3 p1 = supporting_plane();
const typename R::Plane_3 p2 = t.supporting_plane();
if(is_zero(p1.a())) {
if(!is_zero(p2.a())) return false;
if(is_zero(p1.b())) {
if(!is_zero(p2.b())) return false;
return p1.c() * p2.d() == p1.d() * p2.c();
}
return (p2.c() * p1.b() == p1.c() * p2.b()) &&
(p2.d() * p1.b() == p1.d() * p2.b());
}
return (p2.b() * p1.a() == p1.b() * p2.a()) &&
(p2.c() * p1.a() == p1.c() * p2.a()) &&
(p2.d() * p1.a() == p1.d() * p2.a());
}
template < class R >
CGAL_KERNEL_INLINE
bool
CircleC3<R>::operator!=(const CircleC3<R> &t) const
{
return !(*this == t);
}
} //namespace CGAL
#endif // CGAL_CARTESIAN_CIRCLEC3_H
| [
"Etienne.Houze@polytechnique.edu"
] | Etienne.Houze@polytechnique.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.