blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f9535061fe9047163a155e8e8a70ae2fb7a978b1
77e135a1f54afc219c3ec63ab5b0ff11070c426f
/UnitTests/stdafx.h
9694174d1b322f5baeb40e5c180b9d3b75508089
[]
no_license
ossewawiel/CWinSysInfo
31b60809030149834f0adcf0abfcfb978002a498
c71de534010b37518b596c8160b350247cb100ba
refs/heads/master
2021-05-15T07:58:15.213211
2017-10-30T19:02:27
2017-10-30T19:02:27
108,739,883
0
0
null
null
null
null
UTF-8
C++
false
false
536
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> #include <atlbase.h> #include <atlcom.h> #include <comdef.h> #include <lm.h> #include <string> #include <gtest\gtest.h> #include <gmock\gmock.h> #include "..\CWinSysInfo\CWinSysInfo_i.c" #include "..\CWinSysInfo\CWinSysInfo_i.h" // TODO: reference additional headers your program requires here
[ "marsel.pretorius@gmail.com" ]
marsel.pretorius@gmail.com
356c58771198b6a0426e8f63a116fff52cc92125
c0aa25fd6c9b9bb8fd2565a8478a304d4bcbd765
/Headers/Motherboard.h
a2d4d39eb900f29bfea0a0efcb97441467b361f0
[]
no_license
O1Dii/OOP2_4
b43c6f3aa034a3f75f92d217a606226e7091a4fe
51ed33d39d6c4ec1b49d5892693ed6dd8a574988
refs/heads/master
2020-04-27T19:16:10.695321
2019-03-08T21:04:01
2019-03-08T21:04:01
174,610,087
0
0
null
null
null
null
UTF-8
C++
false
false
844
h
// // Created by alexey on 3/8/19. // #ifndef OOP2_MOTHERBOARD_H #define OOP2_MOTHERBOARD_H #include "Product.h" #include "RamException.h" class Motherboard : public Product { public: Motherboard(const Motherboard &obj) : Product(obj) { std::cout << "Сработал конструктор копирования" << std::endl; }; virtual ~Motherboard(); Motherboard(int price, int amount, std::string model, std::string manufacturer, std::string socketType, int ramAmount, int usbAmount); std::string getSocketType(); int getRamAmount(); int getUsbAmount(); void setSocketType(std::string socketType); void setRamAmount(int ramAmount); void setUsbAmount(int usbAmount); private: std::string socketType; int ramAmount; int usbAmount; }; #endif //OOP2_MOTHERBOARD_H
[ "oldi730051@mail.ru" ]
oldi730051@mail.ru
e211258338b127a892093a2f464035c079b36565
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/TemperatureSensor/UNIX_TemperatureSensor_LINUX.hxx
856ab6d7abf8f990d1187ad2987bc33c1b22e728
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
130
hxx
#ifdef PEGASUS_OS_LINUX #ifndef __UNIX_TEMPERATURESENSOR_PRIVATE_H #define __UNIX_TEMPERATURESENSOR_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
04b7eb8e7301f7ad054e7a9f2a28ff5fae30e60f
5c397470370373417afa88ef8e5b27708dfbeea6
/digit_sum.cpp
0c2c6ee5c66146b0b0d68b9a768456002554f44b
[]
no_license
hando95/baekjoon
0012d2b9e7f040bc074bb07887f22879cad02e10
c1e5e0fe099e6fceeea326402bf0f2fc75558dfb
refs/heads/main
2023-08-15T18:08:01.713757
2021-10-05T08:38:33
2021-10-05T08:38:33
380,245,863
0
0
null
null
null
null
UTF-8
C++
false
false
223
cpp
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { int n, i, sum = 0; char num[100] = { 0, }; scanf("%d", &n); scanf("%s", num); for (i = 0; i < n; i++) { sum += num[i] - '0'; } printf("%d\n", sum); }
[ "sllover95@gmail.com" ]
sllover95@gmail.com
53c20395debcbf0cb6e3e62df055302b1a7abd1c
b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1
/tensorflow/core/kernels/resource_variable_ops.h
8700e2322aeeb47be56ab19bc5807a0af68388e3
[ "Apache-2.0" ]
permissive
uve/tensorflow
e48cb29f39ed24ee27e81afd1687960682e1fbef
e08079463bf43e5963acc41da1f57e95603f8080
refs/heads/master
2020-11-29T11:30:40.391232
2020-01-11T13:43:10
2020-01-11T13:43:10
230,088,347
0
0
Apache-2.0
2019-12-25T10:49:15
2019-12-25T10:49:14
null
UTF-8
C++
false
false
2,052
h
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_KERNELS_RESOURCE_VARIABLE_OPS_H_ #define TENSORFLOW_CORE_KERNELS_RESOURCE_VARIABLE_OPS_H_ #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/resource_mgr.h" namespace tensorflow { class VarHandleOp : public OpKernel { public: explicit VarHandleOp(OpKernelConstruction* c); void Compute(OpKernelContext* ctx) override; private: // Same fields as in ResourceHandleOp. string container_; string name_; mutex mutex_; Tensor resource_; std::atomic<bool> initialized_{false}; DtypeAndPartialTensorShape dtype_and_shape_; }; class ReadVariableOp : public OpKernel { public: explicit ReadVariableOp(OpKernelConstruction* c); void Compute(OpKernelContext* ctx) override; private: DataType dtype_; }; class ReadVariablesOp : public OpKernel { public: explicit ReadVariablesOp(OpKernelConstruction* c); void Compute(OpKernelContext* ctx) override; bool IsExpensive() override { return false; } private: DataTypeVector dtypes_; }; class DestroyResourceOp : public OpKernel { public: explicit DestroyResourceOp(OpKernelConstruction* ctx); void Compute(OpKernelContext* ctx) override; private: bool ignore_lookup_error_; }; } // namespace tensorflow #endif // TENSORFLOW_CORE_KERNELS_RESOURCE_VARIABLE_OPS_H_
[ "v-grniki@microsoft.com" ]
v-grniki@microsoft.com
e37b60fffd04e626f07ece5e2d41531298f14648
a5c1fd8f391a5ea117666d28d942be0c4e1b2298
/modules/utilities/src/Aquila/utilities/ColorMapping.hpp
6b2187a6f2731af88e2a13cc0d3d38a6b95bbf64
[]
no_license
Essarelle/Aquila
f8d6b8ea0a160780a78ff351c6ae8b27ee0f7473
60fc3fff68974708342f6d013e49c595d5928825
refs/heads/master
2021-09-07T14:08:57.491176
2018-02-24T02:32:36
2018-02-24T02:32:36
105,085,916
0
0
null
2017-09-28T01:08:15
2017-09-28T01:08:15
null
UTF-8
C++
false
false
309
hpp
#pragma once #include "Aquila/core/detail/Export.hpp" #include <Aquila/rcc/external_includes/cv_core.hpp> #include <Aquila/rcc/external_includes/cv_imgproc.hpp> #include <functional> #include <map> namespace aq{ void AQUILA_EXPORTS createColormap(cv::Mat& lut, int num_classes, int ignore_class = -1); }
[ "dtmoodie@gmail.com" ]
dtmoodie@gmail.com
513bb6f2cf99f2b117f0b36ed4c79ac2e1c64733
d870d9a905306a0c8b4d7db9066cfc604dfc4c7a
/qt4-design/sender.cc
7965dc047b7447d40f14d1cb4a5f42e3d8e31f15
[]
no_license
zdenekzc/qtdesigner-integration
26df15409fbcb3b12828687fac5e64da5ad4d1a8
17e8d667016576834c09860a5b7f556cdfa153e7
refs/heads/master
2022-04-30T07:25:38.806460
2022-04-03T12:14:18
2022-04-03T12:14:18
229,125,847
0
0
null
null
null
null
UTF-8
C++
false
false
930
cc
#include "sender.h" #include "ui_sender.h" #include <QDBusConnection> #include <QDBusInterface> #include <QDBusReply> Sender::Sender(QWidget *parent) : QMainWindow(parent), ui(new Ui::Sender) { ui->setupUi(this); } Sender::~Sender() { delete ui; } void Sender::on_actionRun_triggered () { QDBusConnection bus = QDBusConnection::sessionBus(); if (bus.isConnected ()) { QDBusInterface ifc ("org.example.receiver", "/", "", bus); if (ifc.isValid()) { ifc.call ("hello", "Hello from Qt"); ui->textEdit->append ("Message sent"); QDBusReply <QString> reply = ifc.call ("hello2", "Hello2 from Qt"); if (reply.isValid()) ui->textEdit->append ("Reply was: " + reply.value()); } } } int main (int argc, char *argv[]) { QApplication a(argc, argv); Sender w; w.show(); return a.exec(); }
[ "zdenek.culik@fjfi.cvut.cz" ]
zdenek.culik@fjfi.cvut.cz
2e997a9b7e5ef778b2bd12e49b988c8a7820ca08
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-sagemaker/source/model/ProcessingJob.cpp
808d8c0b1e22fb68e0b07bf113b1201e77ca60dd
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
10,527
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/sagemaker/model/ProcessingJob.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SageMaker { namespace Model { ProcessingJob::ProcessingJob() : m_processingInputsHasBeenSet(false), m_processingOutputConfigHasBeenSet(false), m_processingJobNameHasBeenSet(false), m_processingResourcesHasBeenSet(false), m_stoppingConditionHasBeenSet(false), m_appSpecificationHasBeenSet(false), m_environmentHasBeenSet(false), m_networkConfigHasBeenSet(false), m_roleArnHasBeenSet(false), m_experimentConfigHasBeenSet(false), m_processingJobArnHasBeenSet(false), m_processingJobStatus(ProcessingJobStatus::NOT_SET), m_processingJobStatusHasBeenSet(false), m_exitMessageHasBeenSet(false), m_failureReasonHasBeenSet(false), m_processingEndTimeHasBeenSet(false), m_processingStartTimeHasBeenSet(false), m_lastModifiedTimeHasBeenSet(false), m_creationTimeHasBeenSet(false), m_monitoringScheduleArnHasBeenSet(false), m_autoMLJobArnHasBeenSet(false), m_trainingJobArnHasBeenSet(false), m_tagsHasBeenSet(false) { } ProcessingJob::ProcessingJob(JsonView jsonValue) : m_processingInputsHasBeenSet(false), m_processingOutputConfigHasBeenSet(false), m_processingJobNameHasBeenSet(false), m_processingResourcesHasBeenSet(false), m_stoppingConditionHasBeenSet(false), m_appSpecificationHasBeenSet(false), m_environmentHasBeenSet(false), m_networkConfigHasBeenSet(false), m_roleArnHasBeenSet(false), m_experimentConfigHasBeenSet(false), m_processingJobArnHasBeenSet(false), m_processingJobStatus(ProcessingJobStatus::NOT_SET), m_processingJobStatusHasBeenSet(false), m_exitMessageHasBeenSet(false), m_failureReasonHasBeenSet(false), m_processingEndTimeHasBeenSet(false), m_processingStartTimeHasBeenSet(false), m_lastModifiedTimeHasBeenSet(false), m_creationTimeHasBeenSet(false), m_monitoringScheduleArnHasBeenSet(false), m_autoMLJobArnHasBeenSet(false), m_trainingJobArnHasBeenSet(false), m_tagsHasBeenSet(false) { *this = jsonValue; } ProcessingJob& ProcessingJob::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ProcessingInputs")) { Array<JsonView> processingInputsJsonList = jsonValue.GetArray("ProcessingInputs"); for(unsigned processingInputsIndex = 0; processingInputsIndex < processingInputsJsonList.GetLength(); ++processingInputsIndex) { m_processingInputs.push_back(processingInputsJsonList[processingInputsIndex].AsObject()); } m_processingInputsHasBeenSet = true; } if(jsonValue.ValueExists("ProcessingOutputConfig")) { m_processingOutputConfig = jsonValue.GetObject("ProcessingOutputConfig"); m_processingOutputConfigHasBeenSet = true; } if(jsonValue.ValueExists("ProcessingJobName")) { m_processingJobName = jsonValue.GetString("ProcessingJobName"); m_processingJobNameHasBeenSet = true; } if(jsonValue.ValueExists("ProcessingResources")) { m_processingResources = jsonValue.GetObject("ProcessingResources"); m_processingResourcesHasBeenSet = true; } if(jsonValue.ValueExists("StoppingCondition")) { m_stoppingCondition = jsonValue.GetObject("StoppingCondition"); m_stoppingConditionHasBeenSet = true; } if(jsonValue.ValueExists("AppSpecification")) { m_appSpecification = jsonValue.GetObject("AppSpecification"); m_appSpecificationHasBeenSet = true; } if(jsonValue.ValueExists("Environment")) { Aws::Map<Aws::String, JsonView> environmentJsonMap = jsonValue.GetObject("Environment").GetAllObjects(); for(auto& environmentItem : environmentJsonMap) { m_environment[environmentItem.first] = environmentItem.second.AsString(); } m_environmentHasBeenSet = true; } if(jsonValue.ValueExists("NetworkConfig")) { m_networkConfig = jsonValue.GetObject("NetworkConfig"); m_networkConfigHasBeenSet = true; } if(jsonValue.ValueExists("RoleArn")) { m_roleArn = jsonValue.GetString("RoleArn"); m_roleArnHasBeenSet = true; } if(jsonValue.ValueExists("ExperimentConfig")) { m_experimentConfig = jsonValue.GetObject("ExperimentConfig"); m_experimentConfigHasBeenSet = true; } if(jsonValue.ValueExists("ProcessingJobArn")) { m_processingJobArn = jsonValue.GetString("ProcessingJobArn"); m_processingJobArnHasBeenSet = true; } if(jsonValue.ValueExists("ProcessingJobStatus")) { m_processingJobStatus = ProcessingJobStatusMapper::GetProcessingJobStatusForName(jsonValue.GetString("ProcessingJobStatus")); m_processingJobStatusHasBeenSet = true; } if(jsonValue.ValueExists("ExitMessage")) { m_exitMessage = jsonValue.GetString("ExitMessage"); m_exitMessageHasBeenSet = true; } if(jsonValue.ValueExists("FailureReason")) { m_failureReason = jsonValue.GetString("FailureReason"); m_failureReasonHasBeenSet = true; } if(jsonValue.ValueExists("ProcessingEndTime")) { m_processingEndTime = jsonValue.GetDouble("ProcessingEndTime"); m_processingEndTimeHasBeenSet = true; } if(jsonValue.ValueExists("ProcessingStartTime")) { m_processingStartTime = jsonValue.GetDouble("ProcessingStartTime"); m_processingStartTimeHasBeenSet = true; } if(jsonValue.ValueExists("LastModifiedTime")) { m_lastModifiedTime = jsonValue.GetDouble("LastModifiedTime"); m_lastModifiedTimeHasBeenSet = true; } if(jsonValue.ValueExists("CreationTime")) { m_creationTime = jsonValue.GetDouble("CreationTime"); m_creationTimeHasBeenSet = true; } if(jsonValue.ValueExists("MonitoringScheduleArn")) { m_monitoringScheduleArn = jsonValue.GetString("MonitoringScheduleArn"); m_monitoringScheduleArnHasBeenSet = true; } if(jsonValue.ValueExists("AutoMLJobArn")) { m_autoMLJobArn = jsonValue.GetString("AutoMLJobArn"); m_autoMLJobArnHasBeenSet = true; } if(jsonValue.ValueExists("TrainingJobArn")) { m_trainingJobArn = jsonValue.GetString("TrainingJobArn"); m_trainingJobArnHasBeenSet = true; } if(jsonValue.ValueExists("Tags")) { Array<JsonView> tagsJsonList = jsonValue.GetArray("Tags"); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { m_tags.push_back(tagsJsonList[tagsIndex].AsObject()); } m_tagsHasBeenSet = true; } return *this; } JsonValue ProcessingJob::Jsonize() const { JsonValue payload; if(m_processingInputsHasBeenSet) { Array<JsonValue> processingInputsJsonList(m_processingInputs.size()); for(unsigned processingInputsIndex = 0; processingInputsIndex < processingInputsJsonList.GetLength(); ++processingInputsIndex) { processingInputsJsonList[processingInputsIndex].AsObject(m_processingInputs[processingInputsIndex].Jsonize()); } payload.WithArray("ProcessingInputs", std::move(processingInputsJsonList)); } if(m_processingOutputConfigHasBeenSet) { payload.WithObject("ProcessingOutputConfig", m_processingOutputConfig.Jsonize()); } if(m_processingJobNameHasBeenSet) { payload.WithString("ProcessingJobName", m_processingJobName); } if(m_processingResourcesHasBeenSet) { payload.WithObject("ProcessingResources", m_processingResources.Jsonize()); } if(m_stoppingConditionHasBeenSet) { payload.WithObject("StoppingCondition", m_stoppingCondition.Jsonize()); } if(m_appSpecificationHasBeenSet) { payload.WithObject("AppSpecification", m_appSpecification.Jsonize()); } if(m_environmentHasBeenSet) { JsonValue environmentJsonMap; for(auto& environmentItem : m_environment) { environmentJsonMap.WithString(environmentItem.first, environmentItem.second); } payload.WithObject("Environment", std::move(environmentJsonMap)); } if(m_networkConfigHasBeenSet) { payload.WithObject("NetworkConfig", m_networkConfig.Jsonize()); } if(m_roleArnHasBeenSet) { payload.WithString("RoleArn", m_roleArn); } if(m_experimentConfigHasBeenSet) { payload.WithObject("ExperimentConfig", m_experimentConfig.Jsonize()); } if(m_processingJobArnHasBeenSet) { payload.WithString("ProcessingJobArn", m_processingJobArn); } if(m_processingJobStatusHasBeenSet) { payload.WithString("ProcessingJobStatus", ProcessingJobStatusMapper::GetNameForProcessingJobStatus(m_processingJobStatus)); } if(m_exitMessageHasBeenSet) { payload.WithString("ExitMessage", m_exitMessage); } if(m_failureReasonHasBeenSet) { payload.WithString("FailureReason", m_failureReason); } if(m_processingEndTimeHasBeenSet) { payload.WithDouble("ProcessingEndTime", m_processingEndTime.SecondsWithMSPrecision()); } if(m_processingStartTimeHasBeenSet) { payload.WithDouble("ProcessingStartTime", m_processingStartTime.SecondsWithMSPrecision()); } if(m_lastModifiedTimeHasBeenSet) { payload.WithDouble("LastModifiedTime", m_lastModifiedTime.SecondsWithMSPrecision()); } if(m_creationTimeHasBeenSet) { payload.WithDouble("CreationTime", m_creationTime.SecondsWithMSPrecision()); } if(m_monitoringScheduleArnHasBeenSet) { payload.WithString("MonitoringScheduleArn", m_monitoringScheduleArn); } if(m_autoMLJobArnHasBeenSet) { payload.WithString("AutoMLJobArn", m_autoMLJobArn); } if(m_trainingJobArnHasBeenSet) { payload.WithString("TrainingJobArn", m_trainingJobArn); } if(m_tagsHasBeenSet) { Array<JsonValue> tagsJsonList(m_tags.size()); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); } payload.WithArray("Tags", std::move(tagsJsonList)); } return payload; } } // namespace Model } // namespace SageMaker } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
c2d831c4cfc2b6bf09700afc4890f0f06a5d66f9
a09eebf36957a1b0bb2ce2224246e926032be673
/Games/Ninja/src/implementations/background.cpp
2e5421afa9de814500bd16f7caf2a487aa7a8b2b
[]
no_license
havel-therock/portfolio
ec22e56aeda801e122c76040ce335445cff47988
ad6bd5479cdd7a503707e1b68c307e56a0a71e96
refs/heads/master
2021-05-18T05:55:07.620738
2020-03-30T10:46:21
2020-03-30T10:46:21
251,145,136
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include "../headers/background.h" Background::Background(SDL_Renderer* gRenderer){ Texture* t = new Texture(); t->loadFromFile("res/IMG/background.png", gRenderer); bg.push_back(t); } Background::~Background(){ bg.clear(); }
[ "kacper.szatan@gmail.com" ]
kacper.szatan@gmail.com
22c6660b04665f1a2569eff0fb5a4553f667bba2
a75df4bc2dc8951b1f30191c3395172500285f82
/modules/srccolor.h
a5e6d6037410d2de5f5fde8a3755e732c3d51031
[]
no_license
jotroick/DCT_JPEG_encoder
07492765c097c0c16cb8d34fd124f4dcaa8688bd
1bb1458acd3bd6a1ae93e7bcdef30f12206efc47
refs/heads/master
2021-01-10T09:22:33.529531
2015-12-10T12:47:39
2015-12-10T12:47:39
47,761,290
0
0
null
null
null
null
UTF-8
C++
false
false
489
h
/* srccolor.h */ #ifndef _SRCCOLOR #define _SRCCOLOR #include <systemc.h> #include "add2systemc.h" #include "srcgeneral.h" class srccolor: public srcgeneral { public: sc_fifo_out<int> output_red; sc_fifo_out<int> output_green; sc_fifo_out<int> output_blue; SC_HAS_PROCESS(srccolor); srccolor(sc_module_name name, const char* _filename, unsigned _maxwidth): srcgeneral(name, _filename, _maxwidth) { SC_THREAD(process); } ~srccolor() { } void process(); }; #endif
[ "jotroick@gmail.com" ]
jotroick@gmail.com
e2746b224b2a7e89a3acfa8bcf6e42f3025f8681
ae9010597a3fa9bea80cb3b449e41cefb0523d92
/src/sdk/sdk-eventbus/src/EventBusThreadSafeImpl.h
43ee332b598f451e5271484405069ec26c0832d7
[ "MIT" ]
permissive
barry-ran/learn-design-pattern
0c956607c5213c3c4e7c6587969a486bdc275d53
71c0aeea30ec49323adb88835ba1f0042d1e0095
refs/heads/main
2023-08-28T06:16:23.598842
2021-11-11T09:45:08
2021-11-11T09:45:08
331,289,101
0
0
null
null
null
null
UTF-8
C++
false
false
2,066
h
#pragma once #include "IEventBus.h" class EventBusDataModel { public: bool IsModuleDescExist(const std::string &moduleId) const; ModuleDesc GetModuleDesc(const std::string &moduleId) const; bool AddModuleDesc(const std::string &moduleId, const ModuleDesc &desc); ModuleDesc RemoveModuleDesc(const std::string &moduleId); std::vector<std::string> GetModules(); private: std::map<std::string, ModuleDesc> m_mapModuleDesc; mutable std::mutex m_dataAccessMutex; }; class EventBusThreadSafeImpl : public IEventBus, public SDK_COMMON::Singleton<EventBusThreadSafeImpl> { EventBusThreadSafeImpl(const EventBusThreadSafeImpl &) = delete; EventBusThreadSafeImpl &operator=(const EventBusThreadSafeImpl &) = delete; private: typedef std::function<bool(uint64_t requestId, void *)> RequestHandler; private: EventBusDataModel m_dataModel; std::map<std::string, std::vector<std::string>> m_mapPackage; std::map<std::string, ModuleDesc> m_mapModuleDesc; private: SDKEventLoopContext m_contextEventLoop; public: EventBusThreadSafeImpl(); ~EventBusThreadSafeImpl(); public: bool Init(SDKEventLoopContext contextEventLoop); // and the deps of module bool Uninit(); bool RegisterObserver(const char *moduleId, PFNOnModuleNotify observer); bool RevokeObserver(const char *moduleId, PFNOnModuleNotify observer); bool RegisterObserverModule(const char *moduleId, const char *moduleIdObserver); bool RevokeObserverModule(const char *moduleId, const char *moduleIdObserver); bool InitModule(const std::string &moduleId, const std::string &moduleFile); bool UninitModule(const std::string &moduleId); void *CallModuleEvent(const std::string &moduleIdTo, uint64_t eventId, void *event); void CallModuleDrop(const std::string &moduleIdTo, uint64_t eventId, void *drop); private: bool initModule(const std::string &moduleId, const std::string &fileName, ModuleDesc &desc); bool uninitModule(module_handle_t handle); };
[ "rankun@bytedance.com" ]
rankun@bytedance.com
8ebb7cb292b26340d554f7507692b3ed1c94a257
43ee6c2191c42c67cff20fdf68c9342fca402570
/DataMgr/ForeignStorage/CsvShared.cpp
b7922a5354aa797ef86f03dc26e429993263324b
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
Jambez-hub/omniscidb
b1e2845811e35dc9cbfd26c7459b5d5474c1ae96
94e878916991e7cf76bcd85b4091119b1ec66012
refs/heads/master
2023-03-11T20:53:58.692325
2021-02-16T17:37:38
2021-02-16T17:42:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,553
cpp
/* * Copyright 2021 OmniSci, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CsvShared.h" #include "CsvDataWrapper.h" #include "DataMgr/ForeignStorage/ForeignTableSchema.h" #include "ImportExport/CopyParams.h" #include "Utils/DdlUtils.h" namespace foreign_storage { namespace Csv { namespace { std::string validate_and_get_string_with_length(const ForeignTable* foreign_table, const std::string& option_name, const size_t expected_num_chars) { if (auto it = foreign_table->options.find(option_name); it != foreign_table->options.end()) { if (it->second.length() != expected_num_chars) { throw std::runtime_error{"Value of \"" + option_name + "\" foreign table option has the wrong number of " "characters. Expected " + std::to_string(expected_num_chars) + " character(s)."}; } return it->second; } return ""; } std::optional<bool> validate_and_get_bool_value(const ForeignTable* foreign_table, const std::string& option_name) { if (auto it = foreign_table->options.find(option_name); it != foreign_table->options.end()) { if (boost::iequals(it->second, "TRUE")) { return true; } else if (boost::iequals(it->second, "FALSE")) { return false; } else { throw std::runtime_error{"Invalid boolean value specified for \"" + option_name + "\" foreign table option. " "Value must be either 'true' or 'false'."}; } } return std::nullopt; } } // namespace bool validate_and_get_is_s3_select(const ForeignTable* foreign_table) { static constexpr const char* S3_DIRECT = "S3_DIRECT"; static constexpr const char* S3_SELECT = "S3_SELECT"; static constexpr const char* S3_ACCESS_TYPE = "S3_ACCESS_TYPE"; auto access_type = foreign_table->options.find(S3_ACCESS_TYPE); if (access_type != foreign_table->options.end()) { auto& server_options = foreign_table->foreign_server->options; if (server_options.find(ForeignServer::STORAGE_TYPE_KEY)->second != ForeignServer::S3_STORAGE_TYPE) { throw std::runtime_error{std::string{S3_ACCESS_TYPE} + " option only valid for tables using servers with " + std::string{ForeignServer::STORAGE_TYPE_KEY} + " = " + std::string{ForeignServer::S3_STORAGE_TYPE} + "."}; } if (access_type->second != S3_DIRECT && access_type->second != S3_SELECT) { throw std::runtime_error{"Invalid value provided for the " + std::string{S3_ACCESS_TYPE} + " option. Value must be \"" + S3_DIRECT + "\" or \"" + S3_SELECT + "\"."}; } return (access_type->second == S3_SELECT); } else { return false; } } void validate_options(const ForeignTable* foreign_table) { validate_and_get_copy_params(foreign_table); validate_and_get_is_s3_select(foreign_table); validate_file_path(foreign_table); } void validate_file_path(const ForeignTable* foreign_table) { auto& server_options = foreign_table->foreign_server->options; if (server_options.find(ForeignServer::STORAGE_TYPE_KEY)->second == ForeignServer::LOCAL_FILE_STORAGE_TYPE) { ddl_utils::validate_allowed_file_path(foreign_table->getFullFilePath(), ddl_utils::DataTransferType::IMPORT); } } import_export::CopyParams validate_and_get_copy_params( const ForeignTable* foreign_table) { import_export::CopyParams copy_params{}; copy_params.plain_text = true; if (const auto& value = validate_and_get_string_with_length(foreign_table, "ARRAY_DELIMITER", 1); !value.empty()) { copy_params.array_delim = value[0]; } if (const auto& value = validate_and_get_string_with_length(foreign_table, "ARRAY_MARKER", 2); !value.empty()) { copy_params.array_begin = value[0]; copy_params.array_end = value[1]; } if (auto it = foreign_table->options.find("BUFFER_SIZE"); it != foreign_table->options.end()) { copy_params.buffer_size = std::stoi(it->second); } if (const auto& value = validate_and_get_string_with_length(foreign_table, "DELIMITER", 1); !value.empty()) { copy_params.delimiter = value[0]; } if (const auto& value = validate_and_get_string_with_length(foreign_table, "ESCAPE", 1); !value.empty()) { copy_params.escape = value[0]; } auto has_header = validate_and_get_bool_value(foreign_table, "HEADER"); if (has_header.has_value()) { if (has_header.value()) { copy_params.has_header = import_export::ImportHeaderRow::HAS_HEADER; } else { copy_params.has_header = import_export::ImportHeaderRow::NO_HEADER; } } if (const auto& value = validate_and_get_string_with_length(foreign_table, "LINE_DELIMITER", 1); !value.empty()) { copy_params.line_delim = value[0]; } copy_params.lonlat = validate_and_get_bool_value(foreign_table, "LONLAT").value_or(copy_params.lonlat); if (auto it = foreign_table->options.find("NULLS"); it != foreign_table->options.end()) { copy_params.null_str = it->second; } if (const auto& value = validate_and_get_string_with_length(foreign_table, "QUOTE", 1); !value.empty()) { copy_params.quote = value[0]; } copy_params.quoted = validate_and_get_bool_value(foreign_table, "QUOTED").value_or(copy_params.quoted); return copy_params; } std::unique_ptr<ForeignDataWrapper> get_csv_data_wrapper( int db_id, const ForeignTable* foreign_table) { if (validate_and_get_is_s3_select(foreign_table)) { UNREACHABLE(); return nullptr; } else { return std::make_unique<CsvDataWrapper>(db_id, foreign_table); } } } // namespace Csv } // namespace foreign_storage
[ "dev@aas.io" ]
dev@aas.io
bdb9d7ee3671cb986c82a402f785f30a90565dc5
40a633132eb309eacd4c28773ef8285cb6484318
/net/SocketsOps.h
40ff9d601fd59cf67008447cafcf7d7374d8ea67
[]
no_license
7421/MyWeb
57e604859ff0375ef76b3402267cad4b13c58d43
c0486cc9384c4fff2bbb5c33aece48da7c629162
refs/heads/master
2022-11-13T12:26:40.298871
2020-07-06T04:37:51
2020-07-06T04:37:51
277,443,538
0
0
null
null
null
null
GB18030
C++
false
false
1,352
h
#pragma once #include <arpa/inet.h> #include <endian.h> namespace sockets { //主机存储次序转网络存储次序 inline uint64_t hostToNetwork64(uint64_t host64) { return htobe64(host64); } inline uint32_t hostToNetwork32(uint32_t host32) { return htonl(host32); } inline uint16_t hostToNetwork16(uint16_t host16) { return htons(host16); } //网络存储次序转主机存储次序 inline uint64_t networkToHost64(uint64_t net64) { return be64toh(net64); } inline uint32_t networkToHost32(uint32_t net32) { return ntohl(net32); } inline uint16_t networkToHost16(uint16_t net16) { return ntohs(net16); } //创建一个非阻塞套接字文件描述符 int createNonblockingOrDie(); int connect(int sockfd, const struct sockaddr_in& addr); void bindOrDie(int sockfd, const struct sockaddr_in& addr); void listenOrDie(int sockfd); int accept(int sockfd, struct sockaddr_in* addr); void close(int sockfd); void shutdownWrite(int sockfd); void toHostPort(char* buf, size_t size, const struct sockaddr_in& addr); void fromHostPort(const char* ip, uint16_t port, struct sockaddr_in* addr); //获得sockfd套接字捆绑的本地协议地址 struct sockaddr_in getLocalAddr(int sockfd); struct sockaddr_in getPeerAddr(int sockfd); int getSocketError(int sockfd); bool isSelfConnect(int sockfd); }
[ "18815094400@163.com" ]
18815094400@163.com
ee2c4a05b2e98fa69f2217c75a965bd9cf5e217a
fdb1e74102edccd4922f5192f7b930ad4c5709c0
/P2PSharer/P2PSharer.cpp
778a77dd37f27cba098f6d1e6fcc5d22ba497835
[]
no_license
foxbryant88/P2PSharer
3799c1127ffcb80160cec7106e4610de065b392e
95c9fb4baeee811e72820bed99115182a9158f54
refs/heads/master
2020-06-01T04:36:55.724338
2015-10-18T23:07:55
2015-10-18T23:07:55
40,537,709
1
1
null
null
null
null
GB18030
C++
false
false
2,718
cpp
// P2PSharer.cpp : 定义应用程序的类行为。 // #include "stdafx.h" #include "P2PSharer.h" #include "P2PSharerDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CP2PSharerApp BEGIN_MESSAGE_MAP(CP2PSharerApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CP2PSharerApp 构造 CP2PSharerApp::CP2PSharerApp() { // 支持重新启动管理器 m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: 在此处添加构造代码, // 将所有重要的初始化放置在 InitInstance 中 } // 唯一的一个 CP2PSharerApp 对象 CP2PSharerApp theApp; // CP2PSharerApp 初始化 BOOL CP2PSharerApp::InitInstance() { // 如果一个运行在 Windows XP 上的应用程序清单指定要 // 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式, //则需要 InitCommonControlsEx()。 否则,将无法创建窗口。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 将它设置为包括所有要在应用程序中使用的 // 公共控件类。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // 创建 shell 管理器,以防对话框包含 // 任何 shell 树视图控件或 shell 列表视图控件。 CShellManager *pShellManager = new CShellManager; // 激活“Windows Native”视觉管理器,以便在 MFC 控件中启用主题 CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("应用程序向导生成的本地应用程序")); CP2PSharerDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: 在此放置处理何时用 // “确定”来关闭对话框的代码 } else if (nResponse == IDCANCEL) { // TODO: 在此放置处理何时用 // “取消”来关闭对话框的代码 } else if (nResponse == -1) { TRACE(traceAppMsg, 0, "警告: 对话框创建失败,应用程序将意外终止。\n"); TRACE(traceAppMsg, 0, "警告: 如果您在对话框上使用 MFC 控件,则无法 #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS。\n"); } // 删除上面创建的 shell 管理器。 if (pShellManager != NULL) { delete pShellManager; } // 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序, // 而不是启动应用程序的消息泵。 return FALSE; }
[ "307065422@qq.com" ]
307065422@qq.com
5db56f7492c5bb5c52443b539bd79a62f5c45a3f
71cbe0696208ed9a4c3af39dc7e553f82b7956e0
/src/telegramapi.cpp
d1f284189ed53a4a105cd8c495777ce2ea3b9a32
[]
no_license
unloquer/espTelegramInterface
c053200650cbf573b8ba9306eeabead95625bff0
9aaa3ca311990befc1236f95ad4324f120f0bf5e
refs/heads/master
2020-06-27T11:19:53.275226
2019-08-06T11:54:03
2019-08-06T11:54:03
199,939,180
0
0
null
null
null
null
UTF-8
C++
false
false
3,579
cpp
#include "telegramapi.h" String BASE_URL = "https://api.telegram.org"; // telegram base api String TOKEN = "your_bot_token"; TelegramBot::TelegramBot () { pinMode(EL_RESET,OUTPUT); delay(2); digitalWrite(EL_RESET, HIGH); wifiMulti.addAP(BOT_SSID, PASSWORD); Serial.println("Connecting ..."); while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above delay(250); Serial.print('.'); } Serial.print('\n'); Serial.print("Connected to "); Serial.println(WiFi.SSID()); // Tell us what network we're connected to Serial.print("IP address:\t"); Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer Serial.print('\n'); } TelegramBot::~TelegramBot () { Serial.println("ON telegram bot desctructor"); //delete client; } void TelegramBot::getTelegramUpdates (unsigned long timeout) { unsigned long start = millis(); do { if (wifiMulti.run() == WL_CONNECTED) { client = new BearSSL::WiFiClientSecure(); client->setFingerprint(fingerprint); String url = BASE_URL+"/bot"+TOKEN+"/getUpdates?offset="+String(this->update_offset)+"&limit=1"; if (https.begin(*client, url)) { Serial.print("[HTTP] GET...\n"); Serial.println(ESP.getFreeHeap()); int httpCode = https.GET(); if (httpCode > 0) { if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { response = new DynamicJsonDocument(700); String payload = https.getString(); DeserializationError error = deserializeJson(*response, payload); // Test if parsing succeeds. if (error) { Serial.print(F("deserializeJson() failed: ")); Serial.println(error.c_str()); return; } JsonObject obj = response->as<JsonObject>(); String hasResult = obj["result"][0]; String chat_offset = obj["result"][0]["update_id"]; setUpdateOffset(chat_offset); if (hasResult != "null") { String msg = obj["result"][0]["message"]["text"]; if (msg == "reset" || msg == "Reset") { digitalWrite(EL_RESET,LOW); delay(3000); digitalWrite(EL_RESET, HIGH); } else { Serial.print("got message: "); Serial.println(msg); } } Serial.print("[HTTP] GET success...\n"); serializeJsonPretty(*response, Serial); Serial.println(ESP.getFreeHeap()); } } else { Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); } Serial.printf("freeing response, ending https....\n"); delete response; https.end(); } else { Serial.printf("HTTPS UNABLE TO CONNECT\n"); } Serial.printf("freeing client,....\n"); delete client; yield(); } } while (millis() - start < timeout); } void TelegramBot::setUpdateOffset(String update) { int tmp = update.toInt(); if(tmp > 0) { this->update_offset = tmp + 1; } else { this->update_offset = 0; } } int TelegramBot::getResetPin(void) { return this->reset_pin; } void TelegramBot::resetCallback(unsigned long timeout) { this->reset_pin = LOW; delay(timeout); this->reset_pin = HIGH; }
[ "miguelito.vargasf@gmail.com" ]
miguelito.vargasf@gmail.com
d56693fcdb4fafcfe26b0b6ddc4fbc8b28b0fa81
6dc23ba6bdbd65566e2c69bebaf76c656ad016bd
/structures/memo.h
54501fd08d76a3b4ff3c4b7f12659226b3ac5860
[]
no_license
schenlap/ecam
3cb62e8d686ab7f4214211aa874d622845544845
6e23b3ba32564f920baf3550df3fa5133e51f123
refs/heads/master
2023-01-31T19:56:33.032080
2020-12-10T19:53:42
2020-12-10T19:53:42
320,020,423
0
0
null
null
null
null
UTF-8
C++
false
false
499
h
#ifndef MEMO_H #define MEMO_H #include <QObject> class Memo : public QObject { Q_OBJECT public: enum MemoPrio { LEVEL3, // Highest LEVEL2, LEVEL1, ADVISORY, MEMO }; Memo(QString *text, QString *textval, MemoPrio prio, bool active = true, QObject *parent = 0); QString name(); QString val(); void set_active(bool act); bool is_active() {return _active; } signals: public slots: private: QString *_text; QString *_textval; MemoPrio _prio; bool _active; }; #endif // MEMO_H
[ "memo5@gmx.at" ]
memo5@gmx.at
aa81d77b7cf5c64bd24322aec07ca54447315641
1645afae29879ef5500eab16ebf7c277f4746e5d
/A1033.cpp
8388601b115757e44c6f5ace39380eb3e8829de3
[]
no_license
macshun/algorithm_2
30186729a1b48ac117269df17ae41a1ae4ce1af1
41e1d75663bf4583c0df5bbbe20efba2598ca98d
refs/heads/master
2021-07-23T01:41:14.996863
2019-01-08T10:32:13
2019-01-08T10:32:13
148,030,024
0
0
null
null
null
null
GB18030
C++
false
false
1,879
cpp
/* Name: 贪心 -- A1033 To Fill or not to fill Copyright: 算法笔记 Author: macs Date: 12/10/18 18:53 Description: 给定油箱容量,所到城市距离,汽车每单位油量行驶距离,和中途的油站数量, 然后分别给出油站油价和距离当前城市距离,求出途中最少油钱?到达不了就给出最大行驶距离。 */ #include <iostream> #include <cstdio> #include <algorithm> using namespace std; const int maxn = 510; const int max_price = 100000; struct station{ double P,D; }s[maxn]; bool cmp(station a,station b){ return a.D < b.D; } int main() { int n; double cp = 0.0,c,d,davg; scanf("%lf%lf%lf%d",&c,&d,&davg,&n); for(int i = 0; i < n; i++){ scanf("%lf%lf",&s[i].P,&s[i].D); } s[n].P = 0; s[n].D = d; //终点 //先将油站按距离排列 sort(s, s + n, cmp); if(s[0].D != 0){ printf("The maximum travel distance = 0.00\n"); return 0; } int now = 0; double ans = 0,gas = 0,max = c*davg; while(now < n){ int k = -1; double pmin = max_price; for(int i = now + 1; i <= n && s[i].D - s[now].D <= max; i++){ if(s[i].P < pmin){ //寻找在距离内油价最低的油站 pmin = s[i].P; k = i; if(pmin < s[now].P) break; } } if(k == -1) //油满情况下找不到站 break; double need_gas = (s[k].D - s[now].D) / davg; if(pmin < s[now].P){ //如果要到达的站油价小于当前油价,只需加到达下一站油量即可 if(gas < need_gas){ ans += (need_gas - gas) * s[now].P; gas = 0; //到达下一站时将油量置为零 }else gas -= need_gas; }else{ ans += (c - gas) * s[now].P; //如果到达的站油价大于当前油价,将油量加满 gas = c - need_gas; } now = k; } if(now == n){ printf("%.2lf\n",ans); }else printf("The maximum travel distance = %.2lf\n",s[now].D + max); return 0; }
[ "changshunma@gmail.com" ]
changshunma@gmail.com
803db2cd554100c1d2b64d6eadf37e3b383a2ab4
165be8367f5753b03fae11430b1c3ebf48aa834a
/source/backend/nnapi/execution/NNAPIReduction.hpp
7275dfff353ddb85c381441229cd7774bc8bbb9c
[ "Apache-2.0" ]
permissive
alibaba/MNN
f21b31e3c62d9ba1070c2e4e931fd9220611307c
c442ff39ec9a6a99c28bddd465d8074a7b5c1cca
refs/heads/master
2023-09-01T18:26:42.533902
2023-08-22T11:16:44
2023-08-22T11:16:44
181,436,799
8,383
1,789
null
2023-09-07T02:01:43
2019-04-15T07:40:18
C++
UTF-8
C++
false
false
651
hpp
// // NNAPIReduction.hpp // MNN // // Created by MNN on 2022/10/26. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef MNN_NNAPIREDUCTION_HPP #define MNN_NNAPIREDUCTION_HPP #include "NNAPIBackend.hpp" #include "NNAPICommonExecution.hpp" namespace MNN { class NNAPIReduction : public NNAPICommonExecution { public: NNAPIReduction(Backend *b, const Op *op, const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs); ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs); virtual ~NNAPIReduction() = default; }; } // namespace MNN #endif // MNN_NNAPIREDUCTION_HPP
[ "xiaotang.jxt@alibaba-inc.com" ]
xiaotang.jxt@alibaba-inc.com
73cc71fd00e9c30983e03adc42ca32a82e8bb1ce
514a2d1475507525cc9407060ebf3ef2b3079abb
/snmp_fetch/api/asyncio.cpp
59963680bd148b077d8b32a748e4336fdb7bd2c2
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
higherorderfunctor/snmp-fetch
7b33bb38d4c39da42bac8d075177e9adcdf20c62
c95e9f60d38901c500456dc6f07af343b36b4938
refs/heads/master
2022-07-24T01:30:19.780059
2019-11-27T18:50:01
2019-11-27T18:50:01
208,316,608
0
1
CC0-1.0
2022-07-15T22:04:01
2019-09-13T17:47:11
C++
UTF-8
C++
false
false
5,957
cpp
/** * asyncio.hpp */ #include "asyncio.hpp" namespace snmp_fetch { /** * async_sessions_send */ void async_sessions_send( std::list<async_state> &sessions, netsnmp_callback cb ) { // iterate through each session for (auto &&st: sessions) { // skip session that are not idle if (st.async_status != ASYNC_IDLE) continue; // create the request PDU netsnmp_pdu *pdu = snmp_pdu_create(st.pdu_type); // log PDU creation failures if (!pdu) { st.errors->push_back(SnmpError( CREATE_REQUEST_PDU_ERROR, st.host, {}, {}, {}, {}, {}, "Failed to allocate memory for the request PDU" )); return; } // set PDU options based on PDU type switch (st.pdu_type) { case SNMP_MSG_GETBULK: pdu->non_repeaters = 0; pdu->max_repetitions = st.config->max_bulk_repetitions; break; }; // iterate through each of the next_var_binds in the current partition and add to the PDU for (auto &&vb: st.next_var_binds.front()) // skip empty var_binds, they are complete if (!vb.empty()) { snmp_add_null_var( pdu, (const unsigned long *)vb.data(), vb.size() ); } // set the state to waiting st.async_status = ASYNC_WAITING; // dispatch the PDU, free and log on error if (!snmp_sess_async_send(st.session, pdu, cb, &st)) { char *message; int sys_errno; int snmp_errno; snmp_sess_error(st.session, &sys_errno, &snmp_errno, &message); st.errors->push_back(SnmpError( SEND_ERROR, st.host, sys_errno, snmp_errno, {}, {}, {}, std::string(message) )); snmp_free_pdu(pdu); SNMP_FREE(message); } } } /** * async_sessions_read */ void async_sessions_read( std::list<async_state> &sessions ) { // iterate through each session for (auto &&st: sessions) { // Check that the session is not idle. This function triggers the callback which is // responsible for setting the status. A state other than ASYNC_IDLE indicates the // response PDU has not been read and processed. if (st.async_status == ASYNC_IDLE) continue; /* The remainder of this code is very specifc to how linux reads socket data and is not * specific to net-snmp. See "man select" for additional information. */ // init a socket set to hold the session socket fd_set fdset; FD_ZERO(&fdset); // init the highest numbered socket id + 1 in the set to 0 int nfds = 0; // init a timeout parameter struct timeval timeout; // init socket reads to be blocking int block = NETSNMP_SNMPBLOCK; // let net-snmp fill all the parameters above for select snmp_sess_select_info(st.session, &nfds, &fdset, &timeout, &block); // make the syscall to select to read the session socket int count = select(nfds, &fdset, NULL, NULL, block ? NULL : &timeout); // check if the socket is ready to read if (count) { // read the socket data; this triggers the callback function snmp_sess_read(st.session, &fdset); } else { // retry or timeout otherwise, this also triggers the callback function for both // cases with the appropriate op code in the callback snmp_sess_timeout(st.session); } } } /* * run */ void run( int pdu_type, std::vector<host_t> &hosts, std::vector<var_bind_t> &var_binds, std::vector<std::vector<uint8_t>> &results, std::vector<SnmpError> &errors, SnmpConfig &config ) { // do NOT init net-snmp to disable config loading and mib processing //init_snmp("snmp_fetch"); // init a list of pending hosts in reverse to work back to front to reduce copies as hosts are // removed std::vector<host_t> pending_hosts(hosts.size()); std::reverse_copy(hosts.begin(), hosts.end(), pending_hosts.begin()); // Define an active sessions list which MUST be a data structure which does not move the // memory location of the sessions. net-snmp will store the location of the session via a // pointer once the PDU is sent. Using a vector could cause the memory to move as sessions // are removed. Sessions will last multiple iterations of the event loop during retries. std::list<async_state> active_sessions; // run the event loop until no pending hosts/active sessions are left while (!(pending_hosts.empty() && active_sessions.empty())) { // remove active sessions with no more work close_completed_sessions(active_sessions); // Move pending hosts to active sessions up to config.max_active_sessions. Pending hosts // should be consumed from the back else the entire pending hosts vector will need to be moved // in memory. while ( active_sessions.size() <= config.max_active_sessions && !pending_hosts.empty() ) { // Create the state wrapped net-snmp session and append to active sessions. If this fails // the append will not occur and the host will be discarded. create_session is responsible // for logging the error. create_session( pdu_type, pending_hosts.back(), var_binds, results, errors, config, active_sessions ); // remove the host from pending hosts pending_hosts.erase(pending_hosts.end() - 1); } // send the async requests async_sessions_send(active_sessions, async_cb); // receive the async requests which triggers the session's callback async_sessions_read(active_sessions); } } }
[ "noreply@github.com" ]
higherorderfunctor.noreply@github.com
1d8c8c8c9406c2ea960359228844adab29e94a1b
526d2af9ad55675caf987c09c63108f00b176d96
/PenguinV/performance_tests/cuda/performance_tests_cuda.cpp
bee69cf2ba9d8a6cb7d1d0bf3a473a6804ac5eea
[ "BSD-3-Clause" ]
permissive
filipaog/penguinV
8c86fe2623574518893bdfea105750c0b3966ce9
750ae3a1a7f18c438e02709274b8c5203c278817
refs/heads/master
2021-01-18T16:57:07.891176
2017-08-07T06:56:25
2017-08-07T06:56:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
782
cpp
// This application is designed to run performance tests on penguinV library #include <iostream> #include "performance_test_image_function_cuda.h" #include "../performance_test_framework.h" #include "../../Library/cuda/cuda_memory.cuh" int main() { // The main purpose of this application is to test everything within library // To do this we need an engine (framework) and a bunch of tests // We preallocate memory (32 MB) Cuda_Memory::MemoryAllocator::instance().reserve( 32 * 1024 * 1024 ); // We create a framework Performance_Test::PerformanceTestFramework framework; // We add tests Performance_Test::addTests_Image_Function_Cuda( framework ); // Just run the framework what will handle all tests framework.run(); return 0; }
[ "ihar.hubchyk@gmail.com" ]
ihar.hubchyk@gmail.com
4baa0aac9190a6e51fe38eef260fc27067572ea2
e3d63a08e0c44183536bfa5a7caa47df21b496b5
/Main.cpp
aeee15a6db42ae2b56bb18d983b430b4167251c6
[]
no_license
hackerofunderworld/magical-swapping
43efc15bfa61d100b8fa861003a351b4c6731534
c3484fc679fcc12a9372352a93659b8030969c70
refs/heads/main
2023-08-02T09:35:07.410565
2021-10-03T14:50:28
2021-10-03T14:50:28
413,106,085
0
1
null
2021-10-04T09:41:03
2021-10-03T14:47:48
C++
UTF-8
C++
false
false
3,763
cpp
#include <iostream> #include <Vector> #include <stdlib.h> #include <time.h> #include <QTime> using namespace std; void sort_hoar(vector<int> &arr, int left, int right); void sort_merge (vector<int> &arr, int left, int right, int num); void sort_bubble (vector<int> &arr, int num); void show (vector<int> arr, int num); void copy (vector<int> arr, vector<int> &arr_temp, int num); int main() { srand(time(0)); vector<int> arr; int num=10000; //Количество элементов в массиве cout<<"Work in progress..."<<endl; for (int i=0; i<num; i++) { int temp=rand()%21; arr.push_back(temp); } // show(arr, num); // cout<<endl; vector<int> arr_temp; arr_temp.resize(num); copy(arr, arr_temp, num); QTime time_bubble; time_bubble.start(); //Запуск таймера sort_bubble(arr_temp, num); int t_bubble=time_bubble.elapsed(); //Показ времени таймера // show(arr_temp, num); //Вывод отсортированного массива cout<<"Bubble sorting time: "<<t_bubble<<endl; copy(arr, arr_temp, num); QTime time_hoar; time_hoar.start(); sort_hoar(arr_temp, 0, num-1); int t_hoar=time_hoar.elapsed(); // show(arr_temp, num); cout<<"Hoar sorting time: "<<t_bubble<<endl; copy(arr, arr_temp, num); QTime time_merge; time_merge.start(); sort_merge(arr_temp, 0, num-1, num); int t_merge=time_merge.elapsed(); // show(arr_temp, num); cout<<"Merge sorting time: "<<t_merge<<endl; copy(arr, arr_temp, num); QTime time_sort; time_sort.start(); sort(arr_temp.begin(), arr_temp.begin()+num); //Стандартная сортировка С++ int t_sort=time_sort.elapsed(); // show(arr_temp, num); cout<<"Standart sorting time: "<<t_sort<<endl; return 0; } void sort_bubble (vector<int> &arr, int num) //Сортировка пузырем { for (int i=0; i<num-1; i++) for (int j=0; j<num-i-1; j++) if (arr[j]>arr[j+1]) swap(arr[i], arr[i+1]); } void sort_hoar(vector<int> &arr, int left, int right) //Сортировка Хоар { int i=left; int j=right; int middle=(left+right+1)/2; do { while(arr[i]<arr[middle]) i++; while(arr[j]>arr[middle]) j--; if (i<=j) { swap(arr[i], arr[j]); i++; j--; } } while (i<=j); if (i<right) sort_hoar(arr, i, right); if (left<j) sort_hoar(arr, left, j); } void sort_merge (vector<int> &arr, int left, int right, int num) //Сортировка слиянием { if (left==right) return; if (right-left==1) { if (arr[left]>arr[right]) swap(arr[left], arr[right]); return; } int mid=(left+right)/2; sort_merge(arr, left, mid, num); sort_merge(arr, mid+1, right, num); vector<int> arr_temp; arr_temp.resize(num); int _left=left; int _right=mid+1; int cur=0; while (right-left+1 != cur) { if (_left>mid) arr_temp[cur++]=arr[_right++]; else if (_right>right) arr_temp[cur++]=arr[_left++]; else if (arr[_left]>arr[_right]) arr_temp[cur++]=arr[_right++]; else arr_temp[cur++]=arr[_left++]; } for (int i=0; i<cur; i++) arr[i+left]=arr_temp[i]; } void copy (vector<int> arr, vector<int> &arr_temp, int num) { for (int i=0; i<num; i++) arr_temp[i]=arr[i]; } void show (vector<int> arr, int num) { for (int i=0; i<num; i++) cout<<arr[i]<<" "; cout<<endl; }
[ "noreply@github.com" ]
hackerofunderworld.noreply@github.com
c024f6fa90535042024f0a26e00a1f7f819da93d
c3bc715b253bbf856ca5227a53f797aecc0e5f86
/src/Slave/Slave/ErrorsLogger.cpp
ab85486da1c993af5a6372f1e1f29eace29ed7df
[ "MIT" ]
permissive
averkhaturau/Tarificator
ec7832f287d96109bbb670ecdac632a7ab7509d2
90a976d16ecab8c6a1cd75f4cb6a860dc4c76ce5
refs/heads/master
2020-06-08T12:55:18.387329
2019-06-22T13:06:07
2019-06-22T13:06:07
193,231,681
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,327
cpp
#include "stdafx.h" #include "ErrorsLogger.h" CErrorsLogger::~CErrorsLogger() { } // End of ~CErrorsLogger() void CErrorsLogger::AddLogEntry(CAnyLogableException* pException) { if (!pException) return; // Иначе - вылетает, если еще не прочиталось из реестра имя m_pLogFileName /*if ( !(m_pLogFileName->size()) ) return; bool bCheckHistory = CheckLogHistoryEntry(pException->what()); bool bNotProhibited = CheckProhibition(pException->what()); if ( (bCheckHistory || pException->GetWriteDuplicatesToLog()) && (bNotProhibited) ) { DoAddLogEntry(pException->what()); }*/ CLogger::AddLogEntry(pException->what(), pException->GetWriteDuplicatesToLog()); } // End of AddLogEntry void CErrorsLogger::AddLogEntry(const char* pCharArray, bool bIsWriteDuplicates) { CLogger::AddLogEntry(pCharArray, bIsWriteDuplicates); } // End of AddLogEntry void CErrorsLogger::WriteString(FILE* pFile, const char* pCharArray) { DoWriteTimeStamp(pFile, CurrentTime().GetTime()); // Собственно сообщение об ошибке DoWriteString(pFile, pCharArray); // Перевод строки std::string StringToWrite = "\n"; DoWriteString(pFile, StringToWrite.c_str()); } // End of WriteString()
[ "AlVerkhaturau@luxoft.com" ]
AlVerkhaturau@luxoft.com
e9a3d06677c97f1f400e4fae870d89569737cb26
d85b1f3ce9a3c24ba158ca4a51ea902d152ef7b9
/testcases/CWE789_Uncontrolled_Mem_Alloc/s01/CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82_goodB2G.cpp
ff62f8fcd7acaae6101ffbd7ebae266788101bf0
[]
no_license
arichardson/juliet-test-suite-c
cb71a729716c6aa8f4b987752272b66b1916fdaa
e2e8cf80cd7d52f824e9a938bbb3aa658d23d6c9
refs/heads/master
2022-12-10T12:05:51.179384
2022-11-17T15:41:30
2022-12-01T15:25:16
179,281,349
34
34
null
2022-12-01T15:25:18
2019-04-03T12:03:21
null
UTF-8
C++
false
false
1,882
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82_goodB2G.cpp Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml Template File: sources-sinks-82_goodB2G.tmpl.cpp */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82.h" #define HELLO_STRING "hello" namespace CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82 { void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_82_goodB2G::action(size_t data) { { char * myString; /* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough * for the strcpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > strlen(HELLO_STRING) && data < 100) { myString = (char *)malloc(data*sizeof(char)); if (myString == NULL) {exit(-1);} /* Copy a small string into myString */ strcpy(myString, HELLO_STRING); printLine(myString); free(myString); } else { printLine("Input is less than the length of the source string or too large"); } } } } #endif /* OMITGOOD */
[ "Alexander.Richardson@cl.cam.ac.uk" ]
Alexander.Richardson@cl.cam.ac.uk
5250328d9fced83dd7144e3418a92b140096f0ee
78a3e5d9581fa0fea8e5c089470a8e33c04ea300
/Create Your Own Langauge/ComputerMemory.cpp
e2accf9b47e087d32a40351f5f6a220852c9d197
[]
no_license
RebelAngel98/CreateYourOwnLanguage
be9ea2a2384e14fc1766d1bd7488fa40b108f632
de68d22ec0a308c35d847bdad1d8c70b8e325652
refs/heads/main
2023-07-01T04:25:07.013566
2021-07-25T23:32:49
2021-07-25T23:32:49
389,460,344
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
#include "ComputerMemory.h" void ComputerMemory::SetRAMValue(int address, int value) //inputting address & value for code { //todo: //todo: RAM[address] = value; } int ComputerMemory::GetRAMValue(int address)//just the address for the code { return RAM[address]; }
[ "noreply@github.com" ]
RebelAngel98.noreply@github.com
0e67862b612ee7cae5b64da09e6638755a031b6a
470fae08316b55246ab01675ac5013febfb13eee
/src/server/scripts/Zandalar/TheEternalPalace/boss_orgozoa.cpp
94f4c2630f06c0e45cc06217f7093124d3fef5b3
[]
no_license
adde13372/shadowcore
8db6fb6ccc99821e6bd40237a0c284ce7cf543c2
aa87944193ce02f6e99f7b35eceac5023abfca1b
refs/heads/main
2023-04-01T07:38:39.359558
2021-04-03T07:54:17
2021-04-03T07:54:17
354,320,611
4
8
null
2021-04-03T15:02:49
2021-04-03T15:02:49
null
UTF-8
C++
false
false
38,105
cpp
#include "eternal_palace.h" #include "SpellAuraDefines.h" #include "SpellAuraEffects.h" #include "AreaTriggerAI.h" #include "AreaTrigger.h" #include "AreaTriggerTemplate.h" enum Spells { SPELL_DRIBBLING_ICHOR_MISSILE = 298077, SPELL_DRIBBLING_ICHOR_CAST = 299095, SPELL_DRIBBLING_ICHOR_DAMAGE = 298087, SPELL_INCUBATION_FLUID_DUMMY = 298242, SPELL_INCUBATION_FLUID_DAMAGE = 298314, SPELL_INCUBATION_FLUID_AURA = 298306, SPELL_ARCING_CURRENT = 295825, SPELL_CHAOTIC_GROWTH = 296914, SPELL_PERVASIVE_SHOCK = 295161, SPELL_AMNIOTIC_SPLATTER_AT = 307253, SPELL_AMNIOTIC_SPLATTER_DAMAGE = 298458, SPELL_AMNIOTIC_ERRUPTION = 298459, SPELL_AMNIOTIC_SPLATTER_VISUAL = 298435, SPELL_DESENSITIZING_STING = 298156, SPELL_HEART_STOPPING_PARALYSIS = 298164, SPELL_MASSIVE_INCUBATOR_AURA = 305347, SPELL_MASSIVE_INCUBATOR_CAST = 298548, SPELL_HATCHERY_MOULTING_AURA = 298522, SPELL_HATCHERY_MOULTING_MISSILE = 298525, SPELL_HATCHERY_MOULTING_DAMAGE = 298526, SPELL_HATCHERY_EGG_AT_MARK = 300276, SPELL_EGGSPLOSION = 300308, SPELL_AQUA_LANCE_MISSILE = 295799, SPELL_AQUA_LANCE_AURA = 295779, SPELL_AQUA_LANCE_AT = 295808, SPELL_RAGING_RAPIDS_AURA = 300244, SPELL_SHOCKING_LIGHTNING = 295818, SPELL_CONDUCTIVE_PULSE = 295822, SPELL_POWERFUL_STOMP = 296691, SPELL_REVERBERATING_TREMOR = 296698, }; enum OrgozoaEvents { EVENT_INCUBATION_FLUID = 1, EVENT_ARCING_CURRENT, EVENT_DRIBBLING_ICHOR_PHASE_1, EVENT_DRIBBLING_ICHOR_PHASE_2, EVENT_ENERGY_CHECK, EVENT_SUMMON_ADDS_PHASE_1, EVENT_DESENSITIZING_STING, EVENT_SUMMON_ADDS_PHASE_2, EVENT_AQUA_LANCE, EVENT_SHOCKING_LIGHTNING, EVENT_CONDUCTIVE_PULSE, EVENT_POWERFUL_STOMP, EVENT_PERVASIVE_SHOCK, }; enum Timers { TIMER_INCUBATION_FLUID = 23 * IN_MILLISECONDS, TIMER_ARCING_CURRENT = 9 * IN_MILLISECONDS, TIMER_DRIBBLING_ICHON = 1 * IN_MILLISECONDS, TIMER_ENERGY_CHECK = 2 * IN_MILLISECONDS, TIMER_SUMMON_ADDS_PHASE_1 = 15 * IN_MILLISECONDS, TIMER_DESENSITIZING_STING = 7 * IN_MILLISECONDS, TIMER_SUMMON_ADDS_PHASE_2 = 15 * IN_MILLISECONDS, TIMER_AQUA_LANCE = 15 * IN_MILLISECONDS, TIMER_POWERFUL_STOMP = 30 * IN_MILLISECONDS, TIMER_SHOCKING_LIGHTNING = 15 * IN_MILLISECONDS, TIMER_CONDUCTIVE_PULSE = 15 * IN_MILLISECONDS, TIMER_PERVASIVE_SHOCK = 10 * IN_MILLISECONDS, }; enum MovementEvents { EVENT_ACTION_MOVE_2 = 20, EVENT_ACTION_MOVE_3, EVENT_ACTION_MOVE_4, EVENT_ACTION_MOVE_5, EVENT_ACTION_MOVE_6, EVENT_ACTION_MOVE_7, EVENT_ACTION_MOVE_8, }; enum Points { POINT_1 = 200, POINT_2, POINT_3, POINT_4, POINT_5, POINT_6, POINT_7, POINT_8_FINAL, // cast }; Position phase1Adds[2] = { {236.22f, 707.51f, 1060.93f}, {290.85f, 700.58f, 1060.94f}, }; Position phase2Adds[2] = { {192.17f, 823.58f, 1010.77f}, {252.74f, 818.31f, 1010.98f}, }; Position phase2Intermission[8] = { {268.44f, 721.32f, 1060.82f}, {272.97f, 741.00f, 1060.25f}, {326.45f, 737.38f, 1051.20f}, {346.47f, 762.44f, 1043.44f}, {326.42f, 798.75f, 1034.46f}, {212.08f, 774.73f, 1010.85f}, {211.57f, 809.72f, 1010.75f}, {220.20f, 818.42f, 1010.81f}, }; const Position firstPlatform = { 267.31f, 703.25f, 1060.80f }; //30y const Position secondPlatform = { 220.20f, 818.42f, 1010.81f }; //50y Position hatcheryEgg[25] = { { 218.68f, 778.92f, 1010.92f }, {231.12f, 774.02f, 1014.37f}, {238.68f, 782.15f, 1017.11f}, {245.94f, 776.49f, 1019.71f}, {259.33f, 774.78f, 1023.61f,}, {273.67f, 779.43f, 1025.80f}, {267.61f, 787.05f, 1025.38f}, {283.98f, 796.09f, 1026.94f}, {296.16f, 790.87f, 1028.03f}, {304.71f, 799.31f, 1029.78f}, {316.43f, 793.76f, 1032.32f}, {321.22f, 800.04f, 1033.25f}, {327.51f, 790.89f, 1035.81f}, {336.40f, 783.79f, 1038.50f}, {346.83f, 778.13f, 1040.27f}, {337.77f, 763.72f, 1043.83f}, {344.07f, 753.08f, 1045.55f}, {334.71f, 748.83f, 1047.64f}, {325.72f, 739.09f, 1051.20f}, {314.48f, 741.38f, 1053.99f,}, {311.12f, 729.96f, 1054.75f}, {302.14f, 737.68f, 1057.32f}, {292.33f, 741.42f, 1059.23f}, {284.90f, 737.96f, 1060.05f}, {279.57f, 745.14f, 1060.55f}, }; //used for swirly pos 2-3 patches on every pos struct checkIncubation : public std::unary_function<Unit*, bool> { checkIncubation() {} bool operator() (const Unit* pTarget) { Player* player = const_cast<Player*>(pTarget->ToPlayer()); return (!player->HasAura(SPELL_INCUBATION_FLUID_AURA)); } }; // texts, miscs, 17048 @FIXME visual //152128 class bfa_boss_orgozoa : public CreatureScript { public: bfa_boss_orgozoa() : CreatureScript("bfa_boss_orgozoa") { } struct bfa_boss_orgozoa_AI : public BossAI { bfa_boss_orgozoa_AI(Creature* creature) : BossAI(creature, DATA_ORGOZOA), summons(me) { instance = creature->GetInstanceScript(); me->SetPowerType(POWER_ENERGY); me->SetMaxPower(POWER_ENERGY, 0); me->SetPower(POWER_ENERGY, 0); me->SetSpeed(MOVE_RUN, 5.5f); me->SetSpeed(MOVE_WALK, 5.5f); me->SetSpeed(MOVE_FLIGHT, 5.5f); } InstanceScript* instance; EventMap events; SummonList summons; bool intermission; bool phase1_check; bool phase2_check; uint8 dribblingIchor; void Reset() { intermission = false; phase1_check = false; phase2_check = false; events.Reset(); RemoveIncubationFluid(); DespawnCreatureEntry(NPC_ZANJIR_MYRMIDON); DespawnCreatureEntry(NPC_DREADCOIL_HULK); DespawnCreatureEntry(NPC_AZSHARI_WITCH); DespawnCreatureEntry(NPC_ZOATROID); DespawnCreatureEntry(NPC_HATCHERY_EGG); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } void JustDied(Unit*) { RemoveIncubationFluid(); DespawnCreatureEntry(NPC_ZANJIR_MYRMIDON); DespawnCreatureEntry(NPC_DREADCOIL_HULK); DespawnCreatureEntry(NPC_AZSHARI_WITCH); DespawnCreatureEntry(NPC_ZOATROID); DespawnCreatureEntry(NPC_HATCHERY_EGG); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } void EnterEvadeMode(EvadeReason w) { _DespawnAtEvade(15); } void RemoveIncubationFluid() { Map::PlayerList const& playerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = playerList.begin(); i != playerList.end(); ++i) if (Player* player = i->GetSource()) if (player->HasAura(SPELL_INCUBATION_FLUID_AURA)) player->RemoveAura(SPELL_INCUBATION_FLUID_AURA); } void HandlePhases(uint32 phaseId) { switch (phaseId) { case 1: { me->GetMotionMaster()->Clear(); dribblingIchor = 1; phase1_check = true; me->SetPower(POWER_ENERGY, 0); events.Reset(); events.ScheduleEvent(EVENT_INCUBATION_FLUID, TIMER_INCUBATION_FLUID); events.ScheduleEvent(EVENT_ENERGY_CHECK, TIMER_ENERGY_CHECK); events.ScheduleEvent(EVENT_DESENSITIZING_STING, TIMER_DESENSITIZING_STING); events.ScheduleEvent(EVENT_SUMMON_ADDS_PHASE_1, TIMER_SUMMON_ADDS_PHASE_1); break; } case 2: { for (uint32 i = 0; i < 25; ++i) me->SummonCreature(NPC_HATCHERY_EGG, hatcheryEgg[i], TEMPSUMMON_MANUAL_DESPAWN); RemoveIncubationFluid(); phase1_check = false; events.Reset(); me->GetMotionMaster()->MovePoint(POINT_1, phase2Intermission[0], false); break; } case 3: { DespawnCreatureEntry(NPC_HATCHERY_EGG); me->GetMotionMaster()->Clear(); GripPlayers(); dribblingIchor = 2; phase2_check = true; events.Reset(); me->SetPower(POWER_ENERGY, 0); events.ScheduleEvent(EVENT_INCUBATION_FLUID, TIMER_INCUBATION_FLUID); events.ScheduleEvent(EVENT_ENERGY_CHECK, TIMER_ENERGY_CHECK); events.ScheduleEvent(EVENT_DESENSITIZING_STING, TIMER_DESENSITIZING_STING); events.ScheduleEvent(EVENT_SUMMON_ADDS_PHASE_2, TIMER_SUMMON_ADDS_PHASE_2); break; } } } void GripPlayers() { Map::PlayerList const& playerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = playerList.begin(); i != playerList.end(); ++i) if (Player* player = i->GetSource()) { if (!player->IsGameMaster() && player->GetPositionZ() > 1011.00f) { player->GetMotionMaster()->MoveJump(204.53f, 781.75f, 1010.81f, 0.0f, 30.0f, 20.0f); } } } void CheckAddsNearby() { std::list<Creature*> creatureList; me->GetCreatureListWithEntryInGrid(creatureList, NPC_ZOATROID, 200.0f); if (creatureList.size()) { for (auto creature : creatureList) { if (me->GetDistance(creature) <= 15.0f) { creature->AddAura(SPELL_CHAOTIC_GROWTH, creature); } else creature->RemoveAura(SPELL_CHAOTIC_GROWTH); } } } void DespawnCreatureEntry(uint32 entry) { std::list<Creature*> creatureList; me->GetCreatureListWithEntryInGrid(creatureList, entry, 500.0f); if (creatureList.size()) { for (auto creature : creatureList) creature->DespawnOrUnsummon(); } } void DamageTaken(Unit* at, uint32& damage) { if (me->HealthBelowPct(40) && !intermission) { intermission = true; HandlePhases(2); } } void OnSpellCastInterrupt(SpellInfo const* spell) override { switch (spell->Id) { case SPELL_MASSIVE_INCUBATOR_CAST: HandlePhases(3); break; } } void EnterCombat(Unit*) { me->SetPower(POWER_ENERGY, 0); instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me); HandlePhases(1); } void MovementInform(uint32 type, uint32 pointId) { switch (pointId) { case POINT_1: events.ScheduleEvent(EVENT_ACTION_MOVE_2, 500); break; case POINT_2: events.ScheduleEvent(EVENT_ACTION_MOVE_3, 500); break; case POINT_3: events.ScheduleEvent(EVENT_ACTION_MOVE_4, 500); break; case POINT_4: events.ScheduleEvent(EVENT_ACTION_MOVE_5, 500); break; case POINT_5: events.ScheduleEvent(EVENT_ACTION_MOVE_6, 500); break; case POINT_6: events.ScheduleEvent(EVENT_ACTION_MOVE_7, 500); break; case POINT_7: events.ScheduleEvent(EVENT_ACTION_MOVE_8, 500); break; case POINT_8_FINAL: me->AddAura(SPELL_MASSIVE_INCUBATOR_AURA, me); me->CastSpell(me, SPELL_MASSIVE_INCUBATOR_CAST); break; } } void JustSummoned(Creature* summon) { summons.Summon(summon); switch (summon->GetEntry()) { case NPC_AZSHARI_WITCH: case NPC_DREADCOIL_HULK: case NPC_ZANJIR_MYRMIDON: case NPC_ZOATROID: summon->SetInCombatWithZone(); break; case NPC_HATCHERY_EGG: summon->SetUnitFlags(UNIT_FLAG_NON_ATTACKABLE); summon->SetUnitFlags(UNIT_FLAG_NOT_SELECTABLE); summon->AddAura(SPELL_HATCHERY_EGG_AT_MARK, summon); summon->AddAura(SPELL_HATCHERY_MOULTING_AURA, summon); break; } } void HandlePhase1Adds() { for (uint8 i = 0; i < 2; ++i) me->SummonCreature(NPC_ZOATROID, phase1Adds[0], TEMPSUMMON_MANUAL_DESPAWN); me->SummonCreature(NPC_ZOATROID, phase1Adds[1], TEMPSUMMON_MANUAL_DESPAWN); } void HandlePhase2Adds() { std::vector<uint32> possibleCreature; if (me->GetMap()->IsNormal()) { possibleCreature.push_back(NPC_AZSHARI_WITCH); possibleCreature.push_back(NPC_ZANJIR_MYRMIDON); possibleCreature.push_back(NPC_DREADCOIL_HULK); } else { possibleCreature.push_back(NPC_ZOATROID); possibleCreature.push_back(NPC_AZSHARI_WITCH); possibleCreature.push_back(NPC_ZANJIR_MYRMIDON); possibleCreature.push_back(NPC_DREADCOIL_HULK); } if (possibleCreature.size() >= 2) possibleCreature.resize(2); if (possibleCreature.size()) { for (auto creature : possibleCreature) { for (uint8 i = 0; i < 2; ++i) me->SummonCreature(creature, phase2Adds[i]); } } } void HandleArcingCurrent() { std::list<Player*> playerList; me->GetPlayerListInGrid(playerList, 200.0f); playerList.remove_if(checkIncubation()); if (me->GetMap()->IsMythic()) { if (!playerList.empty()) { for (auto player : playerList) { me->CastSpell(player, SPELL_ARCING_CURRENT, true); } } } else { if (playerList.size() >= 1) playerList.resize(1); if (!playerList.empty()) { for (auto player : playerList) me->CastSpell(player, SPELL_ARCING_CURRENT, true); } } } void UpdateAI(uint32 diff) override { events.Update(diff); if (!UpdateVictim()) return; if (me->IsInCombat()) CheckAddsNearby(); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_INCUBATION_FLUID: { me->CastSpell(me, SPELL_INCUBATION_FLUID_DUMMY); events.ScheduleEvent(EVENT_ARCING_CURRENT, TIMER_ARCING_CURRENT); break; } case EVENT_ARCING_CURRENT: { HandleArcingCurrent(); events.ScheduleEvent(EVENT_INCUBATION_FLUID, TIMER_INCUBATION_FLUID); break; } case EVENT_DESENSITIZING_STING: { if (Unit* target = me->GetVictim()) me->CastSpell(target, SPELL_DESENSITIZING_STING); events.ScheduleEvent(EVENT_DESENSITIZING_STING, TIMER_DESENSITIZING_STING); break; } case EVENT_ENERGY_CHECK: { if (me->GetPower(POWER_ENERGY) >= 100) { if (phase1_check) events.ScheduleEvent(EVENT_DRIBBLING_ICHOR_PHASE_1, 500); else if (phase2_check) events.ScheduleEvent(EVENT_DRIBBLING_ICHOR_PHASE_2, 500); me->SetPower(POWER_ENERGY, 0); } me->SetPower(POWER_ENERGY, urand(1, 2)); events.ScheduleEvent(EVENT_ENERGY_CHECK, TIMER_ENERGY_CHECK); break; } case EVENT_DRIBBLING_ICHOR_PHASE_1: { me->CastSpell(me, SPELL_DRIBBLING_ICHOR_CAST); events.ScheduleEvent(EVENT_DRIBBLING_ICHOR_PHASE_1, TIMER_SUMMON_ADDS_PHASE_1); break; } case EVENT_DRIBBLING_ICHOR_PHASE_2: { me->CastSpell(me, SPELL_DRIBBLING_ICHOR_CAST); events.ScheduleEvent(EVENT_SUMMON_ADDS_PHASE_2, TIMER_SUMMON_ADDS_PHASE_2); break; } case EVENT_SUMMON_ADDS_PHASE_2: { HandlePhase2Adds(); break; } case EVENT_SUMMON_ADDS_PHASE_1: { HandlePhase1Adds(); break; } case EVENT_ACTION_MOVE_2: { me->GetMotionMaster()->MovePoint(POINT_2, phase2Intermission[1], false); break; } case EVENT_ACTION_MOVE_3: { me->GetMotionMaster()->MovePoint(POINT_3, phase2Intermission[2], false); break; } case EVENT_ACTION_MOVE_4: { me->GetMotionMaster()->MovePoint(POINT_4, phase2Intermission[3], false); break; } case EVENT_ACTION_MOVE_5: { me->GetMotionMaster()->MovePoint(POINT_5, phase2Intermission[4], false); break; } case EVENT_ACTION_MOVE_6: { me->GetMotionMaster()->MovePoint(POINT_6, phase2Intermission[5], false); break; } case EVENT_ACTION_MOVE_7: { me->GetMotionMaster()->MovePoint(POINT_7, phase2Intermission[6], false); break; } case EVENT_ACTION_MOVE_8: { me->GetMotionMaster()->MovePoint(POINT_8_FINAL, phase2Intermission[7], false); break; } } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new bfa_boss_orgozoa_AI(creature); } }; // 299095 // spellmgr change SPELL_AURA_PERIODIC_DUMMY effect 1 class bfa_spell_dribbling_ichor : public SpellScriptLoader { public: bfa_spell_dribbling_ichor() : SpellScriptLoader("bfa_spell_dribbling_ichor") { } class bfa_spell_dribbling_ichor_AuraScript : public AuraScript { PrepareAuraScript(bfa_spell_dribbling_ichor_AuraScript); uint8 ichor; bool Load() { ichor = 0; return true; } void OnPeriodic(AuraEffect const* aurEff) { Unit* caster = GetCaster(); if (!caster) return; if (aurEff->GetTickNumber() % 3) { if (Unit* orgozoa = caster->ToCreature()) { bfa_boss_orgozoa::bfa_boss_orgozoa_AI* ai = CAST_AI(bfa_boss_orgozoa::bfa_boss_orgozoa_AI, orgozoa->GetAI()); ichor = ai->dribblingIchor; } if (ichor == 1) { for (uint32 i = 0; i < 12; i++) { Position randomPattern = caster->GetRandomPoint(firstPlatform, 30.0f); caster->CastSpell(randomPattern, SPELL_DRIBBLING_ICHOR_MISSILE, true); } } else if (ichor == 2) { for (uint32 i = 0; i < 24; i++) { Position randomPatter = caster->GetRandomPoint(secondPlatform, 40.0f); caster->CastSpell(randomPatter, SPELL_DRIBBLING_ICHOR_MISSILE, true); } } } } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(bfa_spell_dribbling_ichor_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; AuraScript* GetAuraScript() const { return new bfa_spell_dribbling_ichor_AuraScript; } }; // 298156 class bfa_spell_desensiizing_sting : public SpellScriptLoader { public: bfa_spell_desensiizing_sting() : SpellScriptLoader("bfa_spell_desensiizing_sting") { } class bfa_spell_desensiizing_sting_AuraScript : public AuraScript { PrepareAuraScript(bfa_spell_desensiizing_sting_AuraScript); void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes mode) { Unit* caster = GetCaster(); Unit* target = GetTarget()->ToPlayer(); if (!caster || !target) return; if (this->GetStackAmount() > 9) caster->CastSpell(target, SPELL_HEART_STOPPING_PARALYSIS, true); } void Register() { OnEffectApply += AuraEffectApplyFn(bfa_spell_desensiizing_sting_AuraScript::OnApply, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new bfa_spell_desensiizing_sting_AuraScript; } }; // 298548 class bfa_spell_massive_incubator : public SpellScriptLoader { public: bfa_spell_massive_incubator() : SpellScriptLoader("bfa_spell_massive_incubator") { } class bfa_spell_massive_incubator_SpellScript : public SpellScript { PrepareSpellScript(bfa_spell_massive_incubator_SpellScript); void HandleAfterCast() { Unit* caster = GetCaster(); if (!caster) return; std::list<Player*> playerList; caster->GetPlayerListInGrid(playerList, 200.0f); if (!playerList.empty()) { for (auto player : playerList) { player->Kill(player, false); } } } void Register() { AfterCast += SpellCastFn(bfa_spell_massive_incubator_SpellScript::HandleAfterCast); } }; SpellScript* GetSpellScript() const { return new bfa_spell_massive_incubator_SpellScript; } }; // 298242 class bfa_spell_incubation_fluid : public SpellScriptLoader { public: bfa_spell_incubation_fluid() : SpellScriptLoader("bfa_spell_incubation_fluid") { } class bfa_spell_incubation_fluid_SpellScript : public SpellScript { PrepareSpellScript(bfa_spell_incubation_fluid_SpellScript); void HandleAfterCast() { Unit* caster = GetCaster(); if (!caster) return; std::list<Player*> playerList; caster->GetPlayerListInGrid(playerList, 200.0f); if (playerList.size() >= (caster->GetMap()->IsMythic() ? 6 : 3)) playerList.resize(caster->GetMap()->IsMythic() ? 6 : 3); if (!playerList.empty()) { for (auto player : playerList) { caster->CastSpell(player, SPELL_INCUBATION_FLUID_AURA, true); } } } void Register() { AfterCast += SpellCastFn(bfa_spell_incubation_fluid_SpellScript::HandleAfterCast); } }; SpellScript* GetSpellScript() const { return new bfa_spell_incubation_fluid_SpellScript; } }; class bfa_npc_zoatroid : public CreatureScript { public: bfa_npc_zoatroid() : CreatureScript("bfa_npc_zoatroid") { } struct bfa_npc_zoatroid_AI : public ScriptedAI { bfa_npc_zoatroid_AI(Creature* creature) : ScriptedAI(creature) { } EventMap events; bool _dead; void Reset() { _dead = false; events.Reset(); } void DamageTaken(Unit* at, uint32& damage) { if (damage >= me->GetHealth() && !_dead) { _dead = true; me->SetUnitFlags(UNIT_FLAG_NON_ATTACKABLE); me->SetUnitFlags(UNIT_FLAG_NOT_SELECTABLE); me->SetStandState(UNIT_STAND_STATE_DEAD); damage = 0; me->AddAura(SPELL_AMNIOTIC_SPLATTER_AT, me); me->AddAura(SPELL_AMNIOTIC_SPLATTER_VISUAL, me); me->GetScheduler().Schedule(6s, [this](TaskContext /*context*/) { me->DespawnOrUnsummon(500); }); } } void EnterCombat(Unit*) { events.ScheduleEvent(EVENT_PERVASIVE_SHOCK, TIMER_PERVASIVE_SHOCK); } void UpdateAI(uint32 diff) { events.Update(diff); if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_PERVASIVE_SHOCK: if (Unit* target = me->GetVictim()) me->CastSpell(target, SPELL_PERVASIVE_SHOCK, true); events.ScheduleEvent(EVENT_PERVASIVE_SHOCK, TIMER_PERVASIVE_SHOCK); break; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new bfa_npc_zoatroid_AI(creature); } }; // 298443 class bfa_spell_amniotic_splatter_filter : public SpellScriptLoader { public: bfa_spell_amniotic_splatter_filter() : SpellScriptLoader("bfa_spell_amniotic_splatter_filter") { } class bfa_spell_amniotic_splatter_filter_SpellScript : public SpellScript { PrepareSpellScript(bfa_spell_amniotic_splatter_filter_SpellScript); void HandleAfterCast() { Unit* caster = GetCaster(); if (!caster) return; std::list<Player*> playerList; caster->GetPlayerListInGrid(playerList, 2.5f); if (playerList.empty()) { caster->CastSpell(caster, SPELL_AMNIOTIC_ERRUPTION, true); } else if (!playerList.empty()) { for (auto player : playerList) { if (player->HasAura(SPELL_DESENSITIZING_STING)) player->RemoveAura(SPELL_DESENSITIZING_STING); caster->CastSpell(player, SPELL_AMNIOTIC_SPLATTER_DAMAGE, true); } } } void Register() { AfterCast += SpellCastFn(bfa_spell_amniotic_splatter_filter_SpellScript::HandleAfterCast); } }; SpellScript* GetSpellScript() const { return new bfa_spell_amniotic_splatter_filter_SpellScript; } }; class bfa_npc_azshari_witch : public CreatureScript { public: bfa_npc_azshari_witch() : CreatureScript("bfa_npc_azshari_witch") { } struct bfa_npc_azshari_witch_AI : public ScriptedAI { bfa_npc_azshari_witch_AI(Creature* creature) : ScriptedAI(creature) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit*) { events.ScheduleEvent(EVENT_SHOCKING_LIGHTNING, TIMER_SHOCKING_LIGHTNING); } void UpdateAI(uint32 diff) { events.Update(diff); if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SHOCKING_LIGHTNING: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true, 0)) me->CastSpell(target, SPELL_SHOCKING_LIGHTNING); events.ScheduleEvent(EVENT_CONDUCTIVE_PULSE, TIMER_CONDUCTIVE_PULSE); break; case EVENT_CONDUCTIVE_PULSE: if (Unit* target = me->GetVictim()) me->CastSpell(target, SPELL_CONDUCTIVE_PULSE); events.ScheduleEvent(EVENT_SHOCKING_LIGHTNING, TIMER_SHOCKING_LIGHTNING); break; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new bfa_npc_azshari_witch_AI(creature); } }; class bfa_npc_dreadcoil_hulk : public CreatureScript { public: bfa_npc_dreadcoil_hulk() : CreatureScript("bfa_npc_dreadcoil_hulk") { } struct bfa_npc_dreadcoil_hulk_AI : public ScriptedAI { bfa_npc_dreadcoil_hulk_AI(Creature* creature) : ScriptedAI(creature) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit*) { events.ScheduleEvent(EVENT_POWERFUL_STOMP, TIMER_POWERFUL_STOMP); } void UpdateAI(uint32 diff) { events.Update(diff); if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_POWERFUL_STOMP: me->CastSpell(me->GetVictim(), SPELL_POWERFUL_STOMP); events.ScheduleEvent(EVENT_POWERFUL_STOMP, TIMER_POWERFUL_STOMP); break; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new bfa_npc_dreadcoil_hulk_AI(creature); } }; // 296691 class bfa_spell_powerful_stomp : public SpellScriptLoader { public: bfa_spell_powerful_stomp() : SpellScriptLoader("bfa_spell_powerful_stomp") { } class bfa_spell_powerful_stomp_SpellScript : public SpellScript { PrepareSpellScript(bfa_spell_powerful_stomp_SpellScript); uint32 targetList; bool Load() override { targetList = 0; return true; } void CheckTargets(std::list<WorldObject*>& targets) { targetList = targets.size(); } void RecalculateDamage(SpellEffIndex index) { if (targetList > 1) SetHitDamage(GetHitDamage() / targetList); else GetCaster()->CastSpell(GetCaster(), SPELL_REVERBERATING_TREMOR, true); } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(bfa_spell_powerful_stomp_SpellScript::CheckTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(bfa_spell_powerful_stomp_SpellScript::RecalculateDamage, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE); } }; SpellScript* GetSpellScript() const { return new bfa_spell_powerful_stomp_SpellScript(); } }; class bfa_npc_zanjir_myrmidon : public CreatureScript { public: bfa_npc_zanjir_myrmidon() : CreatureScript("bfa_npc_zanjir_myrmidon") { } struct bfa_npc_zanjir_myrmidon_AI : public ScriptedAI { bfa_npc_zanjir_myrmidon_AI(Creature* creature) : ScriptedAI(creature) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit*) { events.ScheduleEvent(EVENT_AQUA_LANCE, TIMER_AQUA_LANCE); } void UpdateAI(uint32 diff) { events.Update(diff); if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_AQUA_LANCE: { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true, 0)) { std::ostringstream str; str << target->GetName() << " has been targeted for |cFFF00000|h[Aqua Lance]|h|r"; me->TextEmote(str.str().c_str(), 0, true); me->CastSpell(target, SPELL_AQUA_LANCE_MISSILE); } break; } } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new bfa_npc_zanjir_myrmidon_AI(creature); } }; // 295808 class bfa_spell_aqua_lance : public SpellScriptLoader { public: bfa_spell_aqua_lance() : SpellScriptLoader("bfa_spell_aqua_lance") { } class bfa_spell_aqua_lance_SpellScript : public SpellScript { PrepareSpellScript(bfa_spell_aqua_lance_SpellScript); void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* caster = GetCaster()) if (WorldLocation const* target = GetExplTargetDest()) caster->CastSpell(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), SPELL_AQUA_LANCE_AT, true); } void Register() override { OnEffectHitTarget += SpellEffectFn(bfa_spell_aqua_lance_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_CREATE_AREATRIGGER); } }; SpellScript* GetSpellScript() const override { return new bfa_spell_aqua_lance_SpellScript(); } }; // 17048 class bfa_at_aqua_lance : public AreaTriggerEntityScript { public: bfa_at_aqua_lance() : AreaTriggerEntityScript("bfa_at_aqua_lance") { } struct bfa_at_aqua_lance_AI : AreaTriggerAI { bfa_at_aqua_lance_AI(AreaTrigger* areatrigger) : AreaTriggerAI(areatrigger) { } void OnUpdate(uint32 diff) { std::list<Player*> playerList; at->GetPlayerListInGrid(playerList, 5.0f); if (!playerList.empty()) { for (auto player : playerList) { if (!player->HasAura(SPELL_RAGING_RAPIDS_AURA)) { if (Aura* rapids = player->AddAura(SPELL_RAGING_RAPIDS_AURA, player)) { rapids->SetMaxDuration(2000); rapids->SetDuration(2000); } } } } } }; AreaTriggerAI* GetAI(AreaTrigger* areatrigger) const override { return new bfa_at_aqua_lance_AI(areatrigger); } }; class bfa_npc_hattchery_eggs : public CreatureScript { public: bfa_npc_hattchery_eggs() : CreatureScript("bfa_npc_hattchery_eggs") { } struct bfa_npc_hattchery_eggs_AI : public ScriptedAI { bfa_npc_hattchery_eggs_AI(Creature* creature) : ScriptedAI(creature) { creature->AddUnitState(UNIT_STATE_ROOT); } bool eggxploded; void Reset() { eggxploded = false; } void UpdateAI(uint32 diff) { Map::PlayerList const& playerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = playerList.begin(); i != playerList.end(); ++i) if (Player* player = i->GetSource()) { if (!player->IsGameMaster() && player->GetDistance(me) <= 4.0f && !eggxploded) { eggxploded = true; me->CastSpell(me, SPELL_EGGSPLOSION); } } } void OnSpellFinished(SpellInfo const* spellInfo) override { switch (spellInfo->Id) { case SPELL_EGGSPLOSION: me->DespawnOrUnsummon(500); break; } } }; CreatureAI* GetAI(Creature* creature) const override { return new bfa_npc_hattchery_eggs_AI(creature); } }; void AddSC_boss_orgozoa() { new bfa_boss_orgozoa(); new bfa_at_aqua_lance(); new bfa_npc_azshari_witch(); new bfa_npc_dreadcoil_hulk(); new bfa_npc_hattchery_eggs(); new bfa_npc_zanjir_myrmidon(); new bfa_npc_zoatroid(); new bfa_spell_amniotic_splatter_filter(); new bfa_spell_aqua_lance(); new bfa_spell_massive_incubator(); new bfa_spell_desensiizing_sting(); new bfa_spell_dribbling_ichor(); new bfa_spell_incubation_fluid(); new bfa_spell_powerful_stomp(); }
[ "81566364+NemoPRM@users.noreply.github.com" ]
81566364+NemoPRM@users.noreply.github.com
4a6f62ea5756beff72fdc9732a23b55f33d7a51f
2edec3849716c2822d2fa5f693a631aafbf0b8f8
/fin/neuron.h
5c97a5ea35909826a13fdf29a4783002b0f3ef71
[]
no_license
akkeh/so3
ce31614e0efd2e6a67a6aaaa189824034c2a622f
ba3feef1e761c1419245a3abafcc68727d1ee5d3
refs/heads/master
2016-08-12T06:58:55.365322
2015-10-12T13:33:50
2015-10-12T13:33:50
43,680,380
0
0
null
null
null
null
UTF-8
C++
false
false
443
h
#ifndef __NEURON_H_ #define __NEURON_H_ #include "math.h" class Neuron; class Neuron { public: float eval(float** x); void won(); unsigned long get_id(); Neuron(float** x, unsigned long M, unsigned long N, float t_c, unsigned long t_id); ~Neuron(); private: float** w; // weighting unsigned long N; unsigned long M; unsigned long id; float c; // weigthing change factor float y; float** last_x; void update_w(); }; #endif
[ "akkeaccu@msn.com" ]
akkeaccu@msn.com
6f39199caa9e86a4a20b80dc9be45b8506d90613
ee98932afd138bb843b9a2548da512adba0bde85
/reaxdetect/reaxreader.h
fa556daf602d5712e9604f0679f4cd7a79aa51cf
[]
no_license
yanzewu/reaxdetect
8ae89e7473306de6e66b555d5e2a08c7552b4125
323f2f3ae07b65c5958d1c71f1e3bc0af6dae240
refs/heads/master
2020-05-05T06:23:59.234869
2019-12-28T04:07:27
2019-12-28T04:07:27
179,786,894
0
0
null
null
null
null
UTF-8
C++
false
false
4,782
h
#pragma once #ifndef REACTIONSTAT_H #define REACTIONSTAT_H #include "typedef.h" #include "trajectory.h" #include "smiles/smiles.h" #include <deque> #include <vector> #include <list> using namespace std; #define MAX_ATOM_TYPE 256 /* Append in 9/5/2016. Version 2.1.3 */ //recording indices of reagants and products in a reaction //basic statistics about the reaction and molecules class ReaxReader { public: typedef vector<list<pair<int, int> > > Matrix; typedef bool* Mark; struct Config { size_t buffer_size; int recognize_interval; int recognize_limit; int recognize_begin; unsigned verbose_interval; Config() : buffer_size(2), recognize_begin(0), verbose_interval(100) { } }; //Frequecy of molecules and reactions in a frame struct FrameStat { double t; // time stamp Array mol_freq; vector<diint> reaction_freq; }; // Inner representation of reaction, using molecule ID (int) of reactants and products. struct Reaction { Array reagants; Array products; Reaction() {} Reaction(const Array& reagants, const Array& products) : reagants(reagants), products(products) { } bool check_valid(); bool operator==(const Reaction&)const; bool operator!=(const Reaction&)const; Reaction operator-()const; // reverse reaction string to_string(const vector<string>&)const; }; vector<FrameStat> fss; // reaction and species frequency in each frame vector<smiles> molecules; // global species list vector<string> species; // global species name list vector<Reaction> reactions; // global reaction list ReaxReader() : config() { } ReaxReader(const Config& c) : config(c) { } //handles data from trajectory, including the file reading loop. int HandleData(TrajReader&, const Simulation&); //check (use only in debug) void Check(); private: // Intermediate representation of molecule. Faster than SMILES, but cannot guarantee uniqueness -- // Same MatMolecule ==> maybe same molecule; Different MatMolecule ==> must be different molecule. struct MatMolecule { list<int> atoms; Matrix* pbondmatrix; Array* pscores; MatMolecule(Matrix* const pbm, Array* const pscr) : pbondmatrix(pbm), pscores(pscr) { } void push_back(int index); bool operator==(const MatMolecule&)const; bool has_same_atoms(MatMolecule&); // If two MatMolecules are Identical --- with exactly same atom IDs smiles to_smiles()const; // generate canonical SMILES representation }; // Working environment of ReaxReader in one frame struct BufferPage { Array mol_id; // global id of each molecule vector<MatMolecule> molecule; // MatMolecule list vector<Reaction> raw_reaction; // reaction buffer for raw reactions vector<Reaction> reaction; // real reaction buffer Array mol_of_atom; // which molecule the atom belongs to Array atom_score; // atom score, used by MatMolecule Matrix bond_matrix; // connectivity adjacent list, used by MatMolecule }; Config config; BufferPage* _crt_buffer; // pointer to current buffer std::deque<BufferPage*> _prev_buffer; // Previous buffer queue //detect molecule and write into buffer page. void RecognizeMolecule(const TrajFrame& frm, const Arrayd& atomWeights, int atomNumber, FrameStat& fs); //detect reaction and remove repeatance. void RecognizeReaction(const TrajFrame& frm); //commit reaction into lists void CommitReaction(FrameStat& fs_commit); //initiating a new buffer, push the old one into _prev_buffer void RenewBuffer(unsigned max_buffer_num, size_t max_atom_idx); /*molecule generating subfunctions*/ //[DFS] Scan raw scores of each atom. [Do not use directly] static void scan_score(int index, const Arrayd& atom_weights, BufferPage* buffer, Mark marks, Array& molRoots); //[DFS] Scan molecule chain. [Do not use directly] static void scan_molecule(int index, BufferPage* buffer, Mark marks, MatMolecule& molecule); //[DFS] Scan reaction between two frames. [Do not use directly] static void create_reaction(int index, const BufferPage* page_1, const BufferPage* page_2, vector<bool>* marks, Reaction& reac, Reaction& raw_reac, unsigned char flag); //checking if two raw reactions contains same molecules static bool check_reaction(Reaction & reaction_1, BufferPage* buffer_1_prod, BufferPage* buffer_1_reac, Reaction & reaction_2, BufferPage* buffer_2_prod, BufferPage* buffer_2_reac); //generate score to raw score static int totmpscore(int weight, int nhcon, int bond, int terminalh); //make tmp score to smiles score static int tmpscore2score(int tmpscore); //test if an atom is terminal hydrogen static bool isterminalhydrogen(int tmpscore); }; #endif // !REACTIONSTAT_H
[ "wuyanze0@gmail.com" ]
wuyanze0@gmail.com
7af4088ed341e6cc333cb595c465a4dcb6e9bf9c
dacd36f57f531525fb8f7ff3974ef07fe3dcacb3
/VMXAudioFix/WinHelper.cpp
40fb56cadade172d585092af8a45177108451681
[]
no_license
xlfdll/VMXAudioFix
382f84efe49de2759ed254315e7a629a8ea64e1a
56dda65fabec2ef40ce091352e9598b4ff28b15b
refs/heads/master
2023-05-05T16:51:28.736272
2021-05-24T03:58:24
2021-05-24T03:58:24
351,255,493
7
0
null
null
null
null
UTF-8
C++
false
false
5,846
cpp
#include "WinHelper.h" BOOL GetOSVersionInfo(OSVERSIONINFOEX* pOSVersionInfo) { if (pOSVersionInfo == NULL) { return FALSE; } ZeroMemory(pOSVersionInfo, sizeof(OSVERSIONINFOEX)); pOSVersionInfo->dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); return GetVersionEx((OSVERSIONINFO*)pOSVersionInfo); } BOOL CheckOSVersion() { OSVERSIONINFOEX osVersionInfo; if (GetOSVersionInfo(&osVersionInfo)) { return (osVersionInfo.dwMajorVersion == 5); } else { return FALSE; } } BOOL CheckSingleInstance() { HANDLE mutex = CreateMutex(NULL, FALSE, TEXT("Global\\VMXAUDIOFIX_SINGLE_INSTANCE_MUTEX")); if (GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(mutex); return FALSE; } return TRUE; } std::tstring LoadResourceString(HINSTANCE hInstance, UINT uID) { PTSTR pStr; int rVal = LoadString(hInstance, uID, (PTSTR)&pStr, 0); if (rVal) { return std::tstring(pStr, rVal); } else { return std::tstring(); } } BOOL CreateTrayIcon(HINSTANCE hInstance, HWND hwnd) { NOTIFYICONDATA data; OSVERSIONINFOEX osVersionInfo; BOOL isWhistler = (GetOSVersionInfo(&osVersionInfo) && osVersionInfo.dwMinorVersion == 1); data.cbSize = sizeof(NOTIFYICONDATA); data.hWnd = hwnd; data.uID = 0; data.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; data.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE (isWhistler ? IDI_APP_ICON : IDI_APP_ICON_SMALL_2K)); data.uCallbackMessage = WM_APP_NOTIFYICON_CALLBACK; LoadString(hInstance, IDS_APP_TITLE, data.szTip, sizeof(data.szTip)); Shell_NotifyIcon(NIM_ADD, &data); // Need to set version explicitly to support new features (such as context menu) data.uVersion = NOTIFYICON_VERSION; return Shell_NotifyIcon(NIM_SETVERSION, &data); } BOOL DestroyTrayIcon(HWND hwnd) { NOTIFYICONDATA data; data.cbSize = sizeof(NOTIFYICONDATA); data.hWnd = hwnd; data.uID = 0; return Shell_NotifyIcon(NIM_DELETE, &data); } void ShowTrayIconMenu(HINSTANCE hInstance, HWND hwnd, POINT point) { HMENU hMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDR_MENU_TRAY_ICON)); if (hMenu) { HMENU hSubMenu = GetSubMenu(hMenu, 0); if (hSubMenu) { SetForegroundWindow(hwnd); UINT uFlags = TPM_RIGHTBUTTON; if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) { uFlags |= TPM_RIGHTALIGN; } else { uFlags |= TPM_LEFTALIGN; } SetRunOnStartupMenuItemState(hSubMenu, GetRunOnStartupState(hInstance)); // Popup menu must be a submenu under an existing menu // Otherwise no menu items would be shown TrackPopupMenuEx(hSubMenu, uFlags, point.x, point.y, hwnd, NULL); } DestroyMenu(hMenu); } } BOOL SetRunOnStartupMenuItemState(HMENU hMenu, BOOL state) { if (hMenu) { MENUITEMINFO menuItemInfo; menuItemInfo.cbSize = sizeof(MENUITEMINFO); menuItemInfo.fMask = MIIM_STATE; menuItemInfo.fState = state ? MFS_CHECKED : MFS_UNCHECKED; if (!SetMenuItemInfo (hMenu, IDR_MENU_ITEM_RUN_ON_STARTUP, FALSE, &menuItemInfo)) { return FALSE; } } return TRUE; } BOOL GetRunOnStartupState(HINSTANCE hInstance) { std::tstring appTitle = LoadResourceString(hInstance, IDS_APP_TITLE); HKEY hKey; BOOL result; LONG status = RegOpenKeyEx (HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, KEY_READ, &hKey); if (status != ERROR_SUCCESS) { return FALSE; } status = RegQueryValueEx (hKey, appTitle.c_str(), NULL, NULL, NULL, NULL); result = (status == ERROR_SUCCESS); RegCloseKey(hKey); return result; } LONG SetRunOnStartupState(HINSTANCE hInstance, BOOL runOnStartup) { std::tstring appTitle = LoadResourceString(hInstance, IDS_APP_TITLE); TCHAR currentProcessPath[MAX_PATH + 1]; GetModuleFileName(NULL, currentProcessPath, MAX_PATH); HKEY hKey; LONG status = RegOpenKeyEx (HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, KEY_WRITE, &hKey); if (status != ERROR_SUCCESS) { return status; } if (runOnStartup) { status = RegSetValueEx (hKey, appTitle.c_str(), 0, REG_SZ, (LPCBYTE)currentProcessPath, (lstrlen(currentProcessPath) + 1) * sizeof(TCHAR)); } else { status = RegDeleteValue(hKey, appTitle.c_str()); } return status; } std::tstring GetProductVersion() { std::tstringstream ss; TCHAR currentProcessPath[MAX_PATH + 1]; GetModuleFileName(NULL, currentProcessPath, MAX_PATH); DWORD dummy; DWORD verInfoSize = GetFileVersionInfoSize(currentProcessPath, &dummy); if (verInfoSize > 0) { BYTE* verInfoBuffer = (BYTE*)LocalAlloc(LPTR, verInfoSize); if (GetFileVersionInfo(currentProcessPath, NULL, verInfoSize, verInfoBuffer)) { LPVOID productVersion; UINT productVersionLength; if (VerQueryValue (verInfoBuffer, TEXT("\\StringFileInfo\\040904b0\\ProductVersion"), &productVersion, &productVersionLength)) { ss << (LPCTSTR)productVersion; LocalFree(verInfoBuffer); } } } std::tstring result = ss.str(); return result.size() > 0 ? result : std::tstring(TEXT("N/A")); }
[ "xlfdll@gmail.com" ]
xlfdll@gmail.com
75fcfdad2ea2a74adaa77a51c2782cec23b8c1e0
488706ddcd860941510ddd5c8f35bbd065de9ca1
/visualtext3/cj/SkinFramework/XTPSkinObjectStatusBar.h
bfa88ba59cdefc1c89ceca4d0e1493bf1f83e5ce
[]
no_license
VisualText/legacy
8fabbf1da142dfac1a47f4759103671c84ee64fe
73d3dee26ab988e61507713ca37c4e9c0416aee5
refs/heads/main
2023-08-14T08:14:25.178165
2021-09-27T22:41:00
2021-09-27T22:41:00
411,052,445
0
0
null
2021-09-27T22:40:55
2021-09-27T21:48:09
C++
UTF-8
C++
false
false
2,274
h
// XTPSkinObjectStatusBar.h: interface for the CXTPSkinObjectStatusBar class. // // This file is a part of the XTREME SKINFRAMEWORK MFC class library. // (c)1998-2013 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTPSKINOBJECTSTATUSBAR_H__) #define __XTPSKINOBJECTSTATUSBAR_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //=========================================================================== // Summary: // CXTPSkinObjectStatusBar is a CXTPSkinObjectFrame derived class. // It implements standard status bar control //=========================================================================== class _XTP_EXT_CLASS CXTPSkinObjectStatusBar : public CXTPSkinObjectFrame { DECLARE_DYNCREATE(CXTPSkinObjectStatusBar) public: //----------------------------------------------------------------------- // Summary: // Constructs a CXTPSkinObjectStatusBar object. //----------------------------------------------------------------------- CXTPSkinObjectStatusBar(); //----------------------------------------------------------------------- // Summary: // Destroys a CXTPSkinObjectStatusBar object, handles cleanup and deallocation. //----------------------------------------------------------------------- virtual ~CXTPSkinObjectStatusBar(); protected: //{{AFX_CODEJOCK_PRIVATE void RefreshMetrics(); protected: DECLARE_MESSAGE_MAP() //{{AFX_VIRTUAL(CXTPSkinObjectStatusBar) //}}AFX_VIRTUAL //{{AFX_MSG(CXTPSkinObjectStatusBar) int OnCreate(LPCREATESTRUCT lpCreateStruct); //}}AFX_MSG //}}AFX_CODEJOCK_PRIVATE }; #endif // !defined(__XTPSKINOBJECTSTATUSBAR_H__)
[ "david.dehilster@lexisnexisrisk.com" ]
david.dehilster@lexisnexisrisk.com
1485528813a27b255419e64cf5912047dc55b21d
12422c7488cd937e9d2a3739cc7e794c6c30d931
/lab3/TVTests/TVTests.cpp
dee548b6cd2e83048e5a8cf595c7c087c3b00345
[ "MIT" ]
permissive
licar/oop2015
d89557f84ad3aa7537219d0d74b9d6aed07aeb42
3184ed7c8eb921cd52c19f3c0c5dec12faa4d906
refs/heads/master
2021-01-12T22:20:42.975450
2015-05-26T21:15:33
2015-05-26T21:15:33
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,638
cpp
// TVTests.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "../TV/TVSet.h" struct TVSetFixture { CTVSet tv; }; /* Телевизор - изначально выключен - может быть включен - может быть выключен - в выключенном состоянии должен быть на 0 канале - при первом включении телевизор включается на первом канале - позволяет выбрать с 1 по 99 канал во включенном состоянии */ BOOST_FIXTURE_TEST_SUITE(TVSet, TVSetFixture) BOOST_AUTO_TEST_CASE(TurnedOffByDefault) { BOOST_CHECK(!tv.IsTurnedOn()); } BOOST_AUTO_TEST_CASE(CanBeTurnedOn) { BOOST_CHECK(tv.TurnOn()); BOOST_CHECK(tv.IsTurnedOn()); } BOOST_AUTO_TEST_CASE(CanBeTurnedOff) { tv.TurnOn(); BOOST_CHECK(tv.TurnOff()); BOOST_CHECK(!tv.IsTurnedOn()); } BOOST_AUTO_TEST_CASE(IsAtChannel0WhenTurnedOff) { BOOST_CHECK_EQUAL(tv.GetChannel(), 0); tv.TurnOn(); tv.TurnOff(); BOOST_CHECK_EQUAL(tv.GetChannel(), 0); } BOOST_AUTO_TEST_CASE(InitiallyIsTurnedOnAtChannel1) { tv.TurnOn(); BOOST_CHECK_EQUAL(tv.GetChannel(), 1); } BOOST_AUTO_TEST_CASE(CanSelectChannelFrom1To99WhenIsOn) { tv.TurnOn(); BOOST_CHECK(!tv.SelectChannel(0)); BOOST_CHECK_EQUAL(tv.GetChannel(), 1); BOOST_CHECK(tv.SelectChannel(99)); BOOST_CHECK_EQUAL(tv.GetChannel(), 99); BOOST_CHECK(!tv.SelectChannel(100)); BOOST_CHECK_EQUAL(tv.GetChannel(), 99); BOOST_CHECK(tv.SelectChannel(1)); BOOST_CHECK_EQUAL(tv.GetChannel(), 1); } BOOST_AUTO_TEST_SUITE_END()
[ "alexey.malov@cpslabs.net" ]
alexey.malov@cpslabs.net
3f0546afdcae5f8c544120f9966f22bdfc581330
a63126cb4eb9bd8f702bde1fc8d52fc4025ee3f1
/Code/Motor2D/EntityBat.cpp
20c9a83fed123ae54c5873cec934672f4779188e
[]
no_license
PolGannau/GameDevelopment
91a1fe76f7a75e26291b95429da6de3e958c681c
e965c96411777118295c6e7c98d60c30cbff57cb
refs/heads/master
2020-03-31T02:29:32.782169
2018-12-16T13:32:28
2018-12-16T13:32:28
149,129,792
0
0
null
null
null
null
UTF-8
C++
false
false
4,315
cpp
#include "EntityBat.h" #include "j1Entity.h" #include "j1ModuleEntity.h" #include "Player.h" #include "p2Defs.h" #include "p2Log.h" #include "p2Point.h" #include "j1App.h" #include "j1Audio.h" #include "j1Input.h" #include "j1Map.h" #include "j1Pathfinding.h" #include "j1Textures.h" #include "ModuleFadeToBack.h" #include "j1Collision.h" #include "j1Render.h" #include "Brofiler/Brofiler.h" EntityBat::EntityBat(fPoint pos,Animation* anim, SDL_Texture* tex, entities_types type):j1Entity(pos,tex, type) { for (uint AnimNum = 0; AnimNum < (uint)BatState::STATE_MAX; ++AnimNum) { anim_bat[AnimNum].speed = anim[AnimNum].speed; for (int j = 0; j < anim[AnimNum].numFrames; ++j) { anim_bat[AnimNum].PushBack(anim[AnimNum].ReturnFrame(j)); } } pugi::xml_node nodeBat = App->entity->entitiesNodeDoc.child("bat"); pugi::xml_node nodeCol = nodeBat.child("collider"); rectMesure = { nodeCol.attribute("w").as_int(), nodeCol.attribute("h").as_int() }; SDL_Rect playerBat = { (pos.x - rectMesure.x / 2), (pos.y - rectMesure.y), rectMesure.x, rectMesure.y }; collider = App->collision->AddCollider(playerBat, COLLIDER_ENTITY, App->entity); batdeath_fx = true; } EntityBat::~EntityBat() { } bool EntityBat::PreUpdate(float dt) { BROFILER_CATEGORY("PreUpdate_EntityBat.cpp", Profiler::Color::Salmon) this->dt = dt; if (state == BatState::STATE_DEATH && batdeath_fx) { App->audio->PlayFx(App->entity->fx_batdeath); batdeath_fx = false; } if (timer.ReadSec() > 1.0F) { iPoint origin = App->map->WorldToMap((int)position.x, (int)position.y- halfTileSize); iPoint p = App->map->WorldToMap(App->entity->entity_player->position.x, App->entity->entity_player->position.y - halfTileSize); int manhattan = origin.DistanceManhattan(p); if (manhattan < 10 && App->pathfinding->CreatePath(origin, p, FLYING)==1) { bat_path.Clear(); const p2DynArray<iPoint>* path = App->pathfinding->GetLastPath(); for (int pathIpoint = 0; pathIpoint < path->Count(); pathIpoint++) { bat_path.PushBack(*path->At(pathIpoint)); } } } collider->SetPos((position.x + speed.x * dt) - collider->rect.w / 2, (position.y + speed.y * dt) - collider->rect.h); return true; } void EntityBat::Move(float dt) { BROFILER_CATEGORY("Move_EntityBat.cpp", Profiler::Color::Black) uint sizePath = 0; sizePath = bat_path.Count(); if (sizePath > 0) { sizePath -= 1; iPoint batPos = App->map->WorldToMap((int)position.x, (int)position.y - halfTileSize); int aux_i = 0; bool findPositionOnPath = false; for (aux_i; aux_i < sizePath; ++aux_i) { if (*bat_path.At(aux_i) == batPos) { findPositionOnPath = true; break; } } if (findPositionOnPath && aux_i < sizePath) { speed.x = bat_path[aux_i + 1].x - bat_path[aux_i].x; speed.y = bat_path[aux_i + 1].y - bat_path[aux_i].y; } } else { speed = { 0,0 }; } position.x += speed.x*dt*40; position.y += speed.y*dt*40; if (speed.x > 0) { left = false; } else { left = true; } collider->SetPos(position.x - collider->rect.w / 2, position.y - collider->rect.h); } void EntityBat::Draw() { BROFILER_CATEGORY("Draw_EntityBat.cpp", Profiler::Color::AliceBlue) if (state == BatState::STATE_DEATH && anim_bat[(uint)BatState::STATE_DEATH].Finished()) { toDelete = true; } SDL_Rect frameAnim = anim_bat[(uint)state].GetCurrentFrame(dt); if (left) App->render->Blit(texture, position.x - frameAnim.w / 2, position.y - frameAnim.h, &frameAnim); else App->render->Blit(texture, position.x - frameAnim.w / 2, position.y - frameAnim.h, &frameAnim, SDL_FLIP_HORIZONTAL); if (App->input->GetKey(SDL_SCANCODE_F9) == KEY_DOWN) showPath = !showPath; if (showPath) { for (uint i = 0; i < bat_path.Count(); ++i) { iPoint pos = App->map->MapToWorld(bat_path.At(i)->x, bat_path.At(i)->y); App->render->Blit(App->pathfinding->debug_tex, pos.x, pos.y); } } } void EntityBat::OnCollision(Collider * otherCollider) { if (otherCollider->type == COLLIDER_PLAYER) { bool PlayerIsOn = otherCollider->rect.y + otherCollider->rect.h*0.5F < collider->rect.y ; if (PlayerIsOn) { EntityBat::state = BatState::STATE_DEATH; collider->to_delete = true; } else { otherCollider->to_delete = true; } } }
[ "36154632+MarcRosellH@users.noreply.github.com" ]
36154632+MarcRosellH@users.noreply.github.com
ad1b15279dd9193c5b0f053e4f0a21464fb909f2
9d78836faeb6df6f4eff6c6b95d3a17a0a9ab087
/External Libarys/leddarLib/include/comm/Modbus/LtComLeddarVu8Modbus.h
6de04badf41ccd56f5eb5e10259196b4072017e7
[ "MIT" ]
permissive
yisea123/PowerLineThesis
ff566cacc9e036dfca3f5fbee4698594bae3440d
76d0dc5c05ede392636b9771b341418762a899c4
refs/heads/master
2020-06-29T19:38:28.386050
2019-06-17T23:39:56
2019-06-17T23:39:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,490
h
/// **************************************************************************** /// /// \file comm\Modbus\LtComLeddarVu8Modbus.h /// /// \brief Structure definition for Vu8 sensor using Modbus communication /// /// \author David Levy /// /// \since September 2017 /// /// \copyright (c) 2017 LeddarTech Inc. All rights reserved. /// /// *************************************************************************** #pragma once #include "comm/Modbus/LtComModbus.h" namespace LtComLeddarVu8Modbus { #define LEDDARVU8_MAX_SERIAL_DETECTIONS 40 #define LEDDARVU8_MAX_CAN_DETECTIONS 96 #define LEDDARVU8_CHANNEL_COUNT 8 #define LEDDARVU8_DISTANCE_SCALE 1 #define LEDDARVU8_AMPLITUDE_SCALE 64 #define LEDDARVU8_THRESHOLD_SCALE 64 #define LEDDARVU8_MIN_SMOOTHING -16 #define LEDDARVU8_MAX_SMOOTHING 16 #define LEDDARVU8_WAIT_AFTER_REQUEST 5 //Time to wait in ms after a request to be sure the next request is properly transmitted. 2ms should be enough in most cases enum _eLtCommPlatformVu8ModbusAcqOptions { VU8_ACQ_OPTIONS_NONE = 0x0000, ///< No acquisition options selected. VU8_ACQ_OPTIONS_AUTO_LED_POWER = 0x0001, ///< Automatic light source power VU8_ACQ_OPTIONS_DEMERGE_OBJECT = 0x0002, ///< Demerge object VU8_ACQ_OPTIONS_STATIC_NOISE_REMOVAL = 0x0004, ///< Static noise removal VU8_ACQ_OPTIONS_PRECISION = 0x0008, ///Precision/smoothing VU8_ACQ_OPTIONS_SATURATION_COMPENSATION = 0x0010, ///Saturation compensation VU8_ACQ_OPTIONS_OVERSHOOT_MANAGEMENT = 0x0020 ///Overshoot management }; enum eDeviceId { DID_ACCUMULATION_EXP = 0, DID_OVERSAMPLING_EXP = 1, DID_BASE_POINT_COUNT = 2, DID_THRESHOLD_OFFSET = 4, DID_LED_INTENSITY = 5, DID_ACQ_OPTIONS = 6, DID_CHANGE_DELAY = 7, DID_PRECISION = 11, DID_SEGMENT_ENABLE = 12 }; #pragma pack(push, 1) typedef struct { uint16_t mDistance; uint16_t mAmplitude; uint8_t mFlag; uint8_t mSegment; } sLeddarVu8ModbusDetections; typedef struct { uint32_t mTimestamp; uint8_t mLedPower; uint16_t mAcquisitionStatus; } sLeddarVu8ModbusDetectionsTrailing; /// \struct sModbusServerId /// \brief Modbus server ID structure. typedef struct { uint8_t mNbBytes; ///< Number of structure byte excluded this field. char mSerialNumber[ 32 ]; ///< Receiver serial number. uint8_t mRunIndicator; ///< Run indicator. char mDeviceName[ 32 ]; ///< Receiver device name. char mHardwarePartNumber[ 32 ]; ///< Receiver hardware part number. char mSoftwarePartNumber[ 32 ]; ///< Receiver software part number. uint16_t mFirwareVersion[ 4 ]; ///< Receiver software version. uint16_t mBootloaderVersion[ 4 ]; ///< Receiver bootloader version. uint16_t mFpgaVersion; ///< Receiver FPGA version. uint32_t mDeviceOptions; ///< Receiver device options. uint16_t mDeviceId; ///< Receiver device ID. } sLeddarVu8ModbusServerId; typedef struct { uint8_t mLogicalPortNumber; ///< Serial logical port number. uint32_t mBaudrate; ///< Serial port baudrate. uint8_t mDataSize; ///< Serial port data size. uint8_t mParity; ///< Serial port parity mode. uint8_t mStopBits; ///< Serial port stop bits. uint8_t mFlowControl; ///< Serial port flow control. uint8_t mAddress; ///< Serial port ModBus address. uint8_t mMaxEchoes; ///< Max echoes to send by serial port. uint16_t mEchoesResolution; ///< Echoes distance resolution. } sLeddarVu8ModbusSerialPortSettings; typedef struct { uint8_t mLogicalPortNumber; ///< Can logical port number. uint32_t mBaudrate; ///< Can port baudrate. uint8_t mFrameFormat; ///< Frame format uint32_t mTxBaseId; ///< Tx base ID uint32_t mRxBaseId; ///< Rx base ID uint8_t mMaxEchoes; ///< Max echoes to send by can port. uint16_t mEchoesResolution; ///< Echoes distance resolution. uint16_t mInterMsgDelay; ///< Inter-message delay 0 trhough 65535 milliseconds uint16_t mInterCycleDelay; ///< Inter-cycle delay 0 through 65535 milliseconds } sLeddarVu8ModbusCanPortSettings; typedef struct { char mHardwarePartNumber[ 32 ]; ///< Hardware part number char mHardwareSerialNumber[ 32 ]; ///< Hardware serial number uint32_t mCarrierDeviceOption; ///< Carrier device option } sLeddarVu8ModbusCarrierInfo; typedef struct { char mFirmwarePartNumber[ 32 ]; ///< Firmware part number uint16_t mFirmwareVersion[ 4 ]; ///< Firmware version } sLeddarVu8ModbusCarrierFirmwareInfo; #pragma pack(pop) }
[ "osbow17@student.sdu.dk" ]
osbow17@student.sdu.dk
24b3692e1a8441561b992a49be9d8deab2baba2a
fac52aacf1a7145d46f420bb2991528676e3be3f
/SDK/Canned_Corn_classes.h
cf897479da9c9fea1595975482af85c6c55c76b2
[]
no_license
zH4x-SDK/zSCUM-SDK
2342afd6ee54f4f0b14b0a0e9e3920d75bdb4fed
711376eb272b220521fec36d84ca78fc11d4802a
refs/heads/main
2023-07-15T16:02:22.649492
2021-08-27T13:44:21
2021-08-27T13:44:21
400,522,163
2
0
null
null
null
null
UTF-8
C++
false
false
605
h
#pragma once // Name: SCUM, Version: 4.20.3 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Canned_Corn.Canned_Corn_C // 0x0000 (0x09A8 - 0x09A8) class ACanned_Corn_C : public AFoodItem { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Canned_Corn.Canned_Corn_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
ab1ac619401d59cc7b55029f175c76ed917db210
5f9e1fdca6d730e98b77d03e328202df24e55286
/ImgWidget/DRAWING/CPolyGonItem.cpp
5b87663e4a535afc0842a8386090e31cae2e80c9
[]
no_license
summsu84/map-editor
148259968f715f560e434e181e1b076ee6f96f90
4e1a76fc6095bd422cca270c495e4e90b6b7dc22
refs/heads/master
2020-06-21T05:44:20.473560
2019-07-29T01:41:34
2019-07-29T01:41:34
197,359,007
0
0
null
null
null
null
UTF-8
C++
false
false
3,045
cpp
/* * CPolyGonItem.cpp * * Created on: 2013. 7. 8. * Author: jiwon */ #include "CPolyGonItem.h" #include "../LATLON/LatLonConvert.h" int CPolyGonItem::id = 0; CPolyGonItem::CPolyGonItem() { } CPolyGonItem::CPolyGonItem(QPointF initPoint) { // TODO Auto-generated constructor stub setInitPoint(initPoint); org_point_list.append(initPoint); isFixed = false; //qDebug()<<"org_point_list : "<<org_point_list; id++; isFirst = true; } CPolyGonItem::~CPolyGonItem() { // TODO Auto-generated destructor stub } void CPolyGonItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget * /* widget */) { //qDebug()<<"[CLineItem - paint] paint is called.."; //painter->setPen(QPen(QBrush(), 4)); qDebug()<<"[CPolygonItem-paint] called.."; if(isFirst == true){ if(isFixed == true){ //qDebug()<<"h1"; QPolygonF polygonF(org_point_list); polygon = polygonF; }else{ //qDebug()<<"currentPoitn : "<<currentPoint; if(currentPoint.isNull() != true){ point_list = org_point_list; point_list.append(currentPoint); QPolygonF polygonF(point_list); polygon = polygonF; } } painter->setBrush(brush); painter->setPen(pen); painter->drawPolygon(polygon); }else{ QPolygon tmpPolygon; for(int i = 0 ; i < latlonPoint_list.size() ; i++){ QPoint point = LatLonConvert::getInstance().latlonToScreen(latlonPoint_list[i]); tmpPolygon.append(point); } qDebug()<<"Polygon : "<<polygon; qDebug()<<"tmpPolygon : "<<tmpPolygon; painter->setBrush(brush); painter->setPen(pen); painter->drawPolygon(tmpPolygon); } //qDebug()<<"[CPolygonItem-paint] called.. Polygon : "<<polygon; //painter->drawLine(this->line()); } QRectF CPolyGonItem::boundingRect() const { qreal adjust = 0.5; QRectF rect; if(polygon.size() >= 2){ rect = polygon.boundingRect(); }else{ rect = QRectF(adjust, adjust, LatLonConvert::getInstance().srcRect().width() * 1.0, LatLonConvert::getInstance().srcRect().height() * 1.0); } //qDebug()<<"[CPolygonItem - boundingRect] rect : "<<rect<<", polygon bounding : "<<polygon.boundingRect()<<", polygon count : "<<polygon.size(); return rect; } void CPolyGonItem::setFixedPoint(QPointF fixedPoint) { this->fixedPoint = fixedPoint; pointCnt++; isFixed = true; genPointList(this->fixedPoint); } /* * 마우스 클릭시 고정된 지점에 대한 리스트 */ void CPolyGonItem::genPointList(QPointF point) { //point_list.clear(); /// org_point_list.append(initPoint); org_point_list.append(fixedPoint); } /* * 폴리곤 생성을 종료 한다. */ void CPolyGonItem::completePoint(QPointF curPoint) { setFixedPoint(curPoint); } /* * 마우스가 릴리즈 되었을 때 최종 Polygon 리스트를 위경도 좌표로 변환한다. */ void CPolyGonItem::setComplete() { for(int i = 0 ; i < polygon.size() ; i++){ qDebug()<<"[Polygon List : "<<polygon<<"] "; QPointF point = LatLonConvert::getInstance().screenToDecimal(polygon[i].toPoint()); latlonPoint_list.append(point); } isFirst = false; }
[ "q900mu@shinsegae.com" ]
q900mu@shinsegae.com
30b1204740763fc45c56bf2f6266c86c2a1c846e
c67cbd22f9bc3c465fd763fdf87172f2c8ec77d4
/Desktop/Please Work/build/Android/Preview/app/src/main/include/Fuse.Controls.Text.h
be19f2f724c12bb5d205b9be39923bb003df21a5
[]
no_license
AzazelMoreno/Soteria-project
7c58896d6bf5a9ad919bde6ddc2a30f4a07fa0d4
04fdb71065941176867fb9007ecf38bbf851ad47
refs/heads/master
2020-03-11T16:33:22.153713
2018-04-19T19:47:55
2018-04-19T19:47:55
130,120,337
0
0
null
null
null
null
UTF-8
C++
false
false
1,459
h
// This file was generated based on C:/Users/rudy0/AppData/Local/Fusetools/Packages/Fuse.Controls.Primitives/1.8.1/TextControls/Text.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.Controls.TextControl.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.ITemplateSource.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Fuse.Triggers.Actions-ea70af1f.h> #include <Fuse.Triggers.IValue-1.h> #include <Fuse.Visual.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.String.h> #include <Uno.UX.IPropertyListener.h> namespace g{namespace Fuse{namespace Controls{struct Text;}}} namespace g{ namespace Fuse{ namespace Controls{ // public class Text :15 // { ::g::Fuse::Controls::TextControl_type* Text_typeof(); void Text__ctor_7_fn(Text* __this); void Text__get_LoadAsync_fn(Text* __this, bool* __retval); void Text__set_LoadAsync_fn(Text* __this, bool* value); void Text__New3_fn(Text** __retval); struct Text : ::g::Fuse::Controls::TextControl { void ctor_7(); bool LoadAsync(); void LoadAsync(bool value); static Text* New3(); }; // } }}} // ::g::Fuse::Controls
[ "rudy0604594@gmail.com" ]
rudy0604594@gmail.com
db1a72e50bec04b55fa94e4c3ce4485931382a32
1091574ca39b33d356ca6a9a8ff50c626695ece5
/sensors/exemple/RelayActuator/RelayActuator.ino
393d4f286c604bc8b5cf9b1d8a6bdee0e3b6e697
[]
no_license
corhaneanusergiu/cshass
f56b052722a22c3a5389142bb59d6de7014e5ae3
243db9c8c00efee7e99efe7dad88d21742f81a87
refs/heads/master
2021-01-20T04:39:49.258502
2017-05-25T15:59:28
2017-05-25T15:59:28
89,712,089
0
0
null
null
null
null
UTF-8
C++
false
false
2,068
ino
/** * * REVISION HISTORY * Version 1.0 - Henrik Ekblad * * DESCRIPTION * Example sketch showing how to control physical relays. * This example will remember relay state after power failure. * http://www.mysensors.org/build/relay */ // Enable debug prints to serial monitor #define MY_DEBUG // Enable and select radio type attached #define MY_RADIO_NRF24 //#define MY_RADIO_RFM69 // Enable repeater functionality for this node #define MY_REPEATER_FEATURE #include <SPI.h> #include <MySensor.h> #define RELAY_1 3 // Arduino Digital I/O pin number for first relay (second on pin+1 etc) #define NUMBER_OF_RELAYS 1 // Total number of attached relays #define RELAY_ON 1 // GPIO value to write to turn on attached relay #define RELAY_OFF 0 // GPIO value to write to turn off attached relay void before() { for (int sensor=1, pin=RELAY_1; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) { // Then set relay pins in output mode pinMode(pin, OUTPUT); // Set relay to last known state (using eeprom storage) digitalWrite(pin, loadState(sensor)?RELAY_ON:RELAY_OFF); } } void setup() { } void presentation() { // Send the sketch version information to the gateway and Controller sendSketchInfo("Relay", "1.0"); for (int sensor=1, pin=RELAY_1; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) { // Register all sensors to gw (they will be created as child devices) present(sensor, S_LIGHT); } } void loop() { } void receive(const MyMessage &message) { // We only expect one type of message from controller. But we better check anyway. if (message.type==V_LIGHT) { // Change relay state digitalWrite(message.sensor-1+RELAY_1, message.getBool()?RELAY_ON:RELAY_OFF); // Store state in eeprom saveState(message.sensor, message.getBool()); // Write some debug info Serial.print("Incoming change for sensor:"); Serial.print(message.sensor); Serial.print(", New status: "); Serial.println(message.getBool()); } }
[ "noreply@github.com" ]
corhaneanusergiu.noreply@github.com
930ddd52d76bdd1cfac6a68a7eabc9904884c079
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-ssm-incidents/include/aws/ssm-incidents/model/DeleteResourcePolicyRequest.h
8b0b484205e97ff39e6f0596b0beb638c10bec0b
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
4,500
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/ssm-incidents/SSMIncidents_EXPORTS.h> #include <aws/ssm-incidents/SSMIncidentsRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace SSMIncidents { namespace Model { /** */ class AWS_SSMINCIDENTS_API DeleteResourcePolicyRequest : public SSMIncidentsRequest { public: DeleteResourcePolicyRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DeleteResourcePolicy"; } Aws::String SerializePayload() const override; /** * <p>The ID of the resource policy you're deleting.</p> */ inline const Aws::String& GetPolicyId() const{ return m_policyId; } /** * <p>The ID of the resource policy you're deleting.</p> */ inline bool PolicyIdHasBeenSet() const { return m_policyIdHasBeenSet; } /** * <p>The ID of the resource policy you're deleting.</p> */ inline void SetPolicyId(const Aws::String& value) { m_policyIdHasBeenSet = true; m_policyId = value; } /** * <p>The ID of the resource policy you're deleting.</p> */ inline void SetPolicyId(Aws::String&& value) { m_policyIdHasBeenSet = true; m_policyId = std::move(value); } /** * <p>The ID of the resource policy you're deleting.</p> */ inline void SetPolicyId(const char* value) { m_policyIdHasBeenSet = true; m_policyId.assign(value); } /** * <p>The ID of the resource policy you're deleting.</p> */ inline DeleteResourcePolicyRequest& WithPolicyId(const Aws::String& value) { SetPolicyId(value); return *this;} /** * <p>The ID of the resource policy you're deleting.</p> */ inline DeleteResourcePolicyRequest& WithPolicyId(Aws::String&& value) { SetPolicyId(std::move(value)); return *this;} /** * <p>The ID of the resource policy you're deleting.</p> */ inline DeleteResourcePolicyRequest& WithPolicyId(const char* value) { SetPolicyId(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the resource you're deleting the policy * from.</p> */ inline const Aws::String& GetResourceArn() const{ return m_resourceArn; } /** * <p>The Amazon Resource Name (ARN) of the resource you're deleting the policy * from.</p> */ inline bool ResourceArnHasBeenSet() const { return m_resourceArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the resource you're deleting the policy * from.</p> */ inline void SetResourceArn(const Aws::String& value) { m_resourceArnHasBeenSet = true; m_resourceArn = value; } /** * <p>The Amazon Resource Name (ARN) of the resource you're deleting the policy * from.</p> */ inline void SetResourceArn(Aws::String&& value) { m_resourceArnHasBeenSet = true; m_resourceArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the resource you're deleting the policy * from.</p> */ inline void SetResourceArn(const char* value) { m_resourceArnHasBeenSet = true; m_resourceArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the resource you're deleting the policy * from.</p> */ inline DeleteResourcePolicyRequest& WithResourceArn(const Aws::String& value) { SetResourceArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the resource you're deleting the policy * from.</p> */ inline DeleteResourcePolicyRequest& WithResourceArn(Aws::String&& value) { SetResourceArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the resource you're deleting the policy * from.</p> */ inline DeleteResourcePolicyRequest& WithResourceArn(const char* value) { SetResourceArn(value); return *this;} private: Aws::String m_policyId; bool m_policyIdHasBeenSet; Aws::String m_resourceArn; bool m_resourceArnHasBeenSet; }; } // namespace Model } // namespace SSMIncidents } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
a7f1ffca23dc18d6ad0d9e895032d93131a6dcb9
2de766db3b23b1ae845396fbb30615c01cc1604e
/aoj/Course/Algorithms and Data Structures I/Lesson 02 Sort I/Stability.cc
bf980fe94d163f0a68217dc16d7d5f94082b150d
[]
no_license
delta4d/AlgoSolution
313c5d0ff72673927ad3862ee7b8fb432943b346
5f6f89578d5aa37247a99b2d289d638f76c71281
refs/heads/master
2020-04-21T01:28:35.690529
2015-01-29T13:38:54
2015-01-29T13:38:54
8,221,423
1
0
null
2013-04-09T15:10:20
2013-02-15T16:09:33
C++
UTF-8
C++
false
false
1,305
cc
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 36; char A[MAXN][3], B[MAXN][3], C[MAXN][3]; bool is_stable(char X[][3], const int n) { for (int k=1; k<=9; ++k) { int i=0, j=0; while (i < n && j < n) { for (; i<n&&A[i][1]!='0'+k; ++i); for (; j<n&&X[j][1]!='0'+k; ++j); if (i < n && j >= n || i >= n && j < n) return false; if (i < n && j < n && A[i][0] != X[j][0]) return false; ++i, ++j; } } return true; } void BubbleSort(const int n) { for (int i=0; i<n; ++i) { for (int j=n-1; j>=i+1; --j) { if (B[j][1] < B[j-1][1]) { swap(B[j][0], B[j-1][0]); swap(B[j][1], B[j-1][1]); } } } for (int i=0; i<n; ++i) printf("%s%s", B[i], i==n-1?"\n":" "); printf("%s\n", is_stable(B, n)?"Stable":"Not stable"); } void SelectionSort(const int n) { for (int i=0; i<n; ++i) { int mn = i; for (int j=i; j<n; ++j) if (C[j][1] < C[mn][1]) mn = j; swap(C[i][0], C[mn][0]); swap(C[i][1], C[mn][1]); } for (int i=0; i<n; ++i) printf("%s%s", C[i], i==n-1?"\n":" "); printf("%s\n", is_stable(C, n)?"Stable":"Not stable"); } int main() { int i, j, k; int m, n; for (scanf("%d", &n), i=0; i<n; scanf("%s", A[i]), strcpy(B[i], A[i]), strcpy(C[i], A[i]), ++i); BubbleSort(n); SelectionSort(n); return 0; }
[ "delta4d@gmail.com" ]
delta4d@gmail.com
7351fe9c69bf5d881483560da635df8c5501bd36
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/make/new_hunk_234.cpp
4c4fcd9e47f704962a6da7d7dfc5688321760f0e
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
case ENFILE: #endif case ENOMEM: { const char *err = strerror (makefile_errno); OS (fatal, reading_file, "%s", err); } } /* If the makefile wasn't found and it's either a makefile from
[ "993273596@qq.com" ]
993273596@qq.com
d7f1c29d87fdf16b7990c09a5c6f3a15235b828d
ec4fdc9d42991a456dfd2b9b1fcfe12e1a9543ae
/src/User/Effect/EffectScore.h
d67ec708f938e35665c94f465afdbf0923773257
[]
no_license
yumayo/KarakuriNinja
43ad73c4df556aaa16d7118e255f0b29495e3fdf
a010913356aacf794e7761db64208ea7742a42d3
refs/heads/master
2020-07-16T15:06:43.452503
2016-11-16T18:35:43
2016-11-16T18:35:43
73,949,105
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
454
h
# pragma once # include "EffectBase.h" # include "../Utilitys/Yumayo.h" namespace User { // Effectは画像の左上を基点として表示されます。 class EffectScore : public EffectBase { float alpha = 0.0F; int score; Fonts font; public: EffectScore( cinder::Vec2f position, int scoreNum ); protected: virtual void Update( ) override; virtual void Draw( ) override; }; }
[ "scha-taz0@outlook.jp" ]
scha-taz0@outlook.jp
33b417346e9cebf6eb1fd850d81eda7fa8d98e95
13a32b92b1ba8ffb07e810dcc8ccdf1b8b1671ab
/home--tommy--mypy/mypy/lib/python2.7/site-packages/pystan/stan/lib/stan_math/test/unit/math/mix/mat/fun/columns_dot_product_test.cpp
92b49f853c7960af8f97b0cab0acdbc5936f3dcd
[ "Unlicense", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
tommybutler/mlearnpy2
8ec52bcd03208c9771d8d02ede8eaa91a95bda30
9e5d377d0242ac5eb1e82a357e6701095a8ca1ff
refs/heads/master
2022-10-24T23:30:18.705329
2022-10-17T15:41:37
2022-10-17T15:41:37
118,529,175
0
2
Unlicense
2022-10-15T23:32:18
2018-01-22T23:27:10
Python
UTF-8
C++
false
false
27,300
cpp
#include <stan/math/mix/mat.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/mat/fun/util.hpp> TEST(AgradMixMatrixColumnsDotProduct, vector_vector_fv_1stDeriv) { using stan::math::vector_d; using stan::math::vector_fv; using stan::math::fvar; using stan::math::var; fvar<var> a(1.0,1.0); fvar<var> b(3.0,1.0); fvar<var> c(-5.0,1.0); fvar<var> d(4.0,1.0); fvar<var> e(-2.0,1.0); fvar<var> f(-1.0,1.0); vector_d vd_1(3), vd_2(3); vector_fv vv_1(3), vv_2(3); vd_1 << 1, 3, -5; vv_1 << a,b,c; vd_2 << 4, -2, -1; vv_2 << d,e,f; EXPECT_FLOAT_EQ( 3, columns_dot_product(vv_1, vd_2)(0).val_.val()); EXPECT_FLOAT_EQ( 3, columns_dot_product(vd_1, vv_2)(0).val_.val()); EXPECT_FLOAT_EQ( 3, columns_dot_product(vv_1, vv_2)(0).val_.val()); EXPECT_FLOAT_EQ( 1, columns_dot_product(vv_1, vd_2)(0).d_.val()); EXPECT_FLOAT_EQ(-1, columns_dot_product(vd_1, vv_2)(0).d_.val()); EXPECT_FLOAT_EQ( 0, columns_dot_product(vv_1, vv_2)(0).d_.val()); AVEC z = createAVEC(a.val(),b.val(),c.val(),d.val(),e.val(),f.val()); VEC h; columns_dot_product(vv_1, vd_2)(0).val_.grad(z,h); EXPECT_FLOAT_EQ(4.0,h[0]); EXPECT_FLOAT_EQ(-2.0,h[1]); EXPECT_FLOAT_EQ(-1.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, vector_vector_fv_2ndDeriv) { using stan::math::vector_d; using stan::math::vector_fv; using stan::math::fvar; using stan::math::var; fvar<var> a(1.0,1.0); fvar<var> b(3.0,1.0); fvar<var> c(-5.0,1.0); fvar<var> d(4.0,1.0); fvar<var> e(-2.0,1.0); fvar<var> f(-1.0,1.0); vector_d vd_1(3), vd_2(3); vector_fv vv_1(3), vv_2(3); vd_1 << 1, 3, -5; vv_1 << a,b,c; vd_2 << 4, -2, -1; vv_2 << d,e,f; AVEC z = createAVEC(a.val(),b.val(),c.val(),d.val(),e.val(),f.val()); VEC h; columns_dot_product(vv_1, vd_2)(0).d_.grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, vector_vector_fv_exception) { using stan::math::vector_d; using stan::math::vector_fv; using stan::math::fvar; using stan::math::var; vector_d d1(3); d1.setZero(); vector_fv v1(3); v1.setZero(); vector_d d2(2); d2.setZero(); vector_fv v2(4); v2.setZero(); EXPECT_THROW(columns_dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixColumnsDotProduct, rowvector_vector_fv_exceptions) { using stan::math::vector_d; using stan::math::vector_fv; using stan::math::row_vector_d; using stan::math::row_vector_fv; using stan::math::fvar; using stan::math::var; row_vector_d d1(3); d1.setZero(); row_vector_fv v1(3); v1.setZero(); vector_d d2(3); d2.setZero(); vector_fv v2(3); v2.setZero(); EXPECT_THROW(columns_dot_product(v1,d2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v2), std::invalid_argument); } TEST(AgradMixMatrixColumnsDotProduct, vector_rowvector_fv_exceptions) { using stan::math::vector_d; using stan::math::vector_fv; using stan::math::row_vector_d; using stan::math::row_vector_fv; using stan::math::fvar; using stan::math::var; vector_d d1(3); d1.setZero(); vector_fv v1(3); v1.setZero(); row_vector_d d2(3); d2.setZero(); row_vector_fv v2(3); v2.setZero(); EXPECT_THROW(columns_dot_product(v1,d2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v2), std::invalid_argument); } TEST(AgradMixMatrixColumnsDotProduct, rowvector_rowvector_fv_1stDeriv) { using stan::math::row_vector_d; using stan::math::row_vector_fv; using stan::math::fvar; using stan::math::var; fvar<var> a(1.0,1.0); fvar<var> b(3.0,1.0); fvar<var> c(-5.0,1.0); fvar<var> d(4.0,1.0); fvar<var> e(-2.0,1.0); fvar<var> f(-1.0,1.0); row_vector_d d1(3), d2(3); row_vector_fv v1(3), v2(3); d1 << 1, 3, -5; v1 << a,b,c; d2 << 4, -2, -1; v2 << d,e,f; row_vector_fv output; output = columns_dot_product(v1,d2); EXPECT_FLOAT_EQ( 4, output(0).val_.val()); EXPECT_FLOAT_EQ(-6, output(1).val_.val()); EXPECT_FLOAT_EQ( 5, output(2).val_.val()); EXPECT_FLOAT_EQ( 4, output(0).d_.val()); EXPECT_FLOAT_EQ(-2, output(1).d_.val()); EXPECT_FLOAT_EQ(-1, output(2).d_.val()); AVEC z = createAVEC(a.val(),b.val(),c.val(),d.val(),e.val(),f.val()); VEC h; output(0).val_.grad(z,h); EXPECT_FLOAT_EQ(4.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, rowvector_rowvector_fv_2ndDeriv) { using stan::math::row_vector_d; using stan::math::row_vector_fv; using stan::math::fvar; using stan::math::var; fvar<var> a(1.0,1.0); fvar<var> b(3.0,1.0); fvar<var> c(-5.0,1.0); fvar<var> d(4.0,1.0); fvar<var> e(-2.0,1.0); fvar<var> f(-1.0,1.0); row_vector_d d1(3), d2(3); row_vector_fv v1(3), v2(3); d1 << 1, 3, -5; v1 << a,b,c; d2 << 4, -2, -1; v2 << d,e,f; row_vector_fv output; output = columns_dot_product(v1,d2); AVEC z = createAVEC(a.val(),b.val(),c.val(),d.val(),e.val(),f.val()); VEC h; output(0).d_.grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, matrix_matrix_fv_1stDeriv) { using stan::math::matrix_d; using stan::math::matrix_fv; using stan::math::row_vector_fv; using stan::math::fvar; using stan::math::var; fvar<var> a(1.0,1.0); fvar<var> b(3.0,1.0); fvar<var> c(-5.0,1.0); fvar<var> d(4.0,1.0); fvar<var> e(-2.0,1.0); fvar<var> f(-1.0,1.0); matrix_d d1(3,3), d2(3,3); matrix_fv v1(3,3), v2(3,3); d1 << 1, 1, 1, 3, 3, 3, -5, -5, -5; v1 << a,a,a,b,b,b,c,c,c; d2 << 4, 4, 4, -2, -2, -2, -1, -1, -1; v2 << d,d,d,e,e,e,f,f,f; row_vector_fv output; output = columns_dot_product(v1,d2); EXPECT_FLOAT_EQ( 3, output(0).val_.val()); EXPECT_FLOAT_EQ( 3, output(1).val_.val()); EXPECT_FLOAT_EQ( 3, output(2).val_.val()); EXPECT_FLOAT_EQ( 1, output(0).d_.val()); EXPECT_FLOAT_EQ( 1, output(1).d_.val()); EXPECT_FLOAT_EQ( 1, output(2).d_.val()); output = columns_dot_product(d1, v2); EXPECT_FLOAT_EQ( 3, output(0).val_.val()); EXPECT_FLOAT_EQ( 3, output(1).val_.val()); EXPECT_FLOAT_EQ( 3, output(2).val_.val()); EXPECT_FLOAT_EQ(-1, output(0).d_.val()); EXPECT_FLOAT_EQ(-1, output(1).d_.val()); EXPECT_FLOAT_EQ(-1, output(2).d_.val()); output = columns_dot_product(v1, v2); EXPECT_FLOAT_EQ( 3, output(0).val_.val()); EXPECT_FLOAT_EQ( 3, output(1).val_.val()); EXPECT_FLOAT_EQ( 3, output(2).val_.val()); EXPECT_FLOAT_EQ( 0, output(0).d_.val()); EXPECT_FLOAT_EQ( 0, output(1).d_.val()); EXPECT_FLOAT_EQ( 0, output(2).d_.val()); AVEC z = createAVEC(a.val(),b.val(),c.val(),d.val(),e.val(),f.val()); VEC h; output(0).val_.grad(z,h); EXPECT_FLOAT_EQ(4.0,h[0]); EXPECT_FLOAT_EQ(-2.0,h[1]); EXPECT_FLOAT_EQ(-1.0,h[2]); EXPECT_FLOAT_EQ(1.0,h[3]); EXPECT_FLOAT_EQ(3.0,h[4]); EXPECT_FLOAT_EQ(-5.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, matrix_matrix_fv_2ndDeriv) { using stan::math::matrix_d; using stan::math::matrix_fv; using stan::math::row_vector_fv; using stan::math::fvar; using stan::math::var; fvar<var> a(1.0,1.0); fvar<var> b(3.0,1.0); fvar<var> c(-5.0,1.0); fvar<var> d(4.0,1.0); fvar<var> e(-2.0,1.0); fvar<var> f(-1.0,1.0); matrix_d d1(3,3), d2(3,3); matrix_fv v1(3,3), v2(3,3); d1 << 1, 1, 1, 3, 3, 3, -5, -5, -5; v1 << a,a,a,b,b,b,c,c,c; d2 << 4, 4, 4, -2, -2, -2, -1, -1, -1; v2 << d,d,d,e,e,e,f,f,f; row_vector_fv output; output = columns_dot_product(v1, v2); AVEC z = createAVEC(a.val(),b.val(),c.val(),d.val(),e.val(),f.val()); VEC h; output(0).d_.grad(z,h); EXPECT_FLOAT_EQ(1.0,h[0]); EXPECT_FLOAT_EQ(1.0,h[1]); EXPECT_FLOAT_EQ(1.0,h[2]); EXPECT_FLOAT_EQ(1.0,h[3]); EXPECT_FLOAT_EQ(1.0,h[4]); EXPECT_FLOAT_EQ(1.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, matrix_matrix_fv_exception) { using stan::math::matrix_d; using stan::math::matrix_fv; using stan::math::columns_dot_product; using stan::math::fvar; using stan::math::var; fvar<var> a(1.0,1.0); fvar<var> b(3.0,1.0); fvar<var> c(-5.0,1.0); fvar<var> d(4.0,1.0); fvar<var> e(-2.0,1.0); fvar<var> f(-1.0,1.0); matrix_d d1(3,3); matrix_d d2(3,2); matrix_d d3(2,3); matrix_fv v1(3,3); matrix_fv v2(3,3); matrix_fv v3(3,2); matrix_fv v4(3,2); matrix_fv v5(2,3); matrix_fv v6(2,3); d1 << 1, 3, -5, 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; v1 << a,b,c,a,b,c,a,b,c; v2 << d,e,f,d,e,f,d,e,f; v3 << d,e,f,d,e,f; v4 << d,e,f,d,e,f; v5 << d,e,f,d,e,f; v6 << d,e,f,d,e,f; EXPECT_THROW(columns_dot_product(v1,d2), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,d3), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v3), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v4), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v5), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v6), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v3), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v4), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v5), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v6), std::invalid_argument); EXPECT_THROW(columns_dot_product(d2,v1), std::invalid_argument); EXPECT_THROW(columns_dot_product(d2,v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d2,v5), std::invalid_argument); EXPECT_THROW(columns_dot_product(d2,v6), std::invalid_argument); EXPECT_THROW(columns_dot_product(d3,v1), std::invalid_argument); EXPECT_THROW(columns_dot_product(d3,v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d3,v3), std::invalid_argument); EXPECT_THROW(columns_dot_product(d3,v4), std::invalid_argument); } TEST(AgradMixMatrixColumnsDotProduct, vector_vector_ffv_1stDeriv) { using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); vector_d vd_1(3), vd_2(3); vector_ffv vv_1(3), vv_2(3); vd_1 << 1, 3, -5; vv_1 << a,b,c; vd_2 << 4, -2, -1; vv_2 << d,e,f; EXPECT_FLOAT_EQ( 3, columns_dot_product(vv_1, vd_2)(0).val_.val().val()); EXPECT_FLOAT_EQ( 3, columns_dot_product(vd_1, vv_2)(0).val_.val().val()); EXPECT_FLOAT_EQ( 3, columns_dot_product(vv_1, vv_2)(0).val_.val().val()); EXPECT_FLOAT_EQ( 1, columns_dot_product(vv_1, vd_2)(0).d_.val().val()); EXPECT_FLOAT_EQ(-1, columns_dot_product(vd_1, vv_2)(0).d_.val().val()); EXPECT_FLOAT_EQ( 0, columns_dot_product(vv_1, vv_2)(0).d_.val().val()); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; columns_dot_product(vv_1, vd_2)(0).val_.val().grad(z,h); EXPECT_FLOAT_EQ(4.0,h[0]); EXPECT_FLOAT_EQ(-2.0,h[1]); EXPECT_FLOAT_EQ(-1.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, vector_vector_ffv_2ndDeriv_1) { using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); vector_d vd_1(3), vd_2(3); vector_ffv vv_1(3), vv_2(3); vd_1 << 1, 3, -5; vv_1 << a,b,c; vd_2 << 4, -2, -1; vv_2 << d,e,f; AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; columns_dot_product(vv_1, vd_2)(0).val_.d_.grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, vector_vector_ffv_2ndDeriv_2) { using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); vector_d vd_1(3), vd_2(3); vector_ffv vv_1(3), vv_2(3); vd_1 << 1, 3, -5; vv_1 << a,b,c; vd_2 << 4, -2, -1; vv_2 << d,e,f; AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; columns_dot_product(vv_1, vd_2)(0).d_.val().grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, vector_vector_ffv_3rdDeriv) { using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); a.val_.d_ = 1.0; b.val_.d_ = 1.0; c.val_.d_ = 1.0; d.val_.d_ = 1.0; e.val_.d_ = 1.0; f.val_.d_ = 1.0; vector_d vd_1(3), vd_2(3); vector_ffv vv_1(3), vv_2(3); vd_1 << 1, 3, -5; vv_1 << a,b,c; vd_2 << 4, -2, -1; vv_2 << d,e,f; AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; columns_dot_product(vv_1, vd_2)(0).d_.d_.grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, vector_vector_ffv_exception) { using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::fvar; using stan::math::var; vector_d d1(3); vector_ffv v1(3); vector_d d2(2); vector_ffv v2(4); EXPECT_THROW(columns_dot_product(v1, d2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1, v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixColumnsDotProduct, rowvector_vector_ffv_exceptions) { using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::row_vector_d; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; row_vector_d d1(3); d1.setZero(); row_vector_ffv v1(3); v1.setZero(); vector_d d2(3); d2.setZero(); vector_ffv v2(3); v2.setZero(); EXPECT_THROW(columns_dot_product(v1,d2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v2), std::invalid_argument); } TEST(AgradMixMatrixColumnsDotProduct, vector_rowvector_ffv_exceptions) { using stan::math::vector_d; using stan::math::vector_ffv; using stan::math::row_vector_d; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; vector_d d1(3); d1.setZero(); vector_ffv v1(3); v1.setZero(); row_vector_d d2(3); d2.setZero(); row_vector_ffv v2(3); v2.setZero(); EXPECT_THROW(columns_dot_product(v1,d2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v2), std::invalid_argument); } TEST(AgradMixMatrixColumnsDotProduct, rowvector_rowvector_ffv_1stDeriv) { using stan::math::row_vector_d; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); row_vector_d d1(3), d2(3); row_vector_ffv v1(3), v2(3); d1 << 1, 3, -5; v1 << a,b,c; d2 << 4, -2, -1; v2 << d,e,f; row_vector_ffv output; output = columns_dot_product(v1,d2); EXPECT_FLOAT_EQ( 4, output(0).val_.val().val()); EXPECT_FLOAT_EQ(-6, output(1).val_.val().val()); EXPECT_FLOAT_EQ( 5, output(2).val_.val().val()); EXPECT_FLOAT_EQ( 4, output(0).d_.val().val()); EXPECT_FLOAT_EQ(-2, output(1).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(2).d_.val().val()); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; output(0).val_.val().grad(z,h); EXPECT_FLOAT_EQ(4.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, rowvector_rowvector_ffv_2ndDeriv_1) { using stan::math::row_vector_d; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); row_vector_d d1(3), d2(3); row_vector_ffv v1(3), v2(3); d1 << 1, 3, -5; v1 << a,b,c; d2 << 4, -2, -1; v2 << d,e,f; row_vector_ffv output; output = columns_dot_product(v1,d2); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; output(0).val().d_.grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, rowvector_rowvector_ffv_2ndDeriv_2) { using stan::math::row_vector_d; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); row_vector_d d1(3), d2(3); row_vector_ffv v1(3), v2(3); d1 << 1, 3, -5; v1 << a,b,c; d2 << 4, -2, -1; v2 << d,e,f; row_vector_ffv output; output = columns_dot_product(v1,d2); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; output(0).d_.val().grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, rowvector_rowvector_ffv_3rdDeriv) { using stan::math::row_vector_d; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); a.val_.d_ = 1.0; b.val_.d_ = 1.0; c.val_.d_ = 1.0; d.val_.d_ = 1.0; e.val_.d_ = 1.0; f.val_.d_ = 1.0; row_vector_d d1(3), d2(3); row_vector_ffv v1(3), v2(3); d1 << 1, 3, -5; v1 << a,b,c; d2 << 4, -2, -1; v2 << d,e,f; row_vector_ffv output; output = columns_dot_product(v1,d2); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; output(0).d_.d_.grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, matrix_matrix_ffv_1stDeriv) { using stan::math::matrix_d; using stan::math::matrix_ffv; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); matrix_d d1(3,3), d2(3,3); matrix_ffv v1(3,3), v2(3,3); d1 << 1, 1, 1, 3, 3, 3, -5, -5, -5; v1 << a,a,a,b,b,b,c,c,c; d2 << 4, 4, 4, -2, -2, -2, -1, -1, -1; v2 << d,d,d,e,e,e,f,f,f; row_vector_ffv output; output = columns_dot_product(v1,d2); EXPECT_FLOAT_EQ( 3, output(0).val_.val().val()); EXPECT_FLOAT_EQ( 3, output(1).val_.val().val()); EXPECT_FLOAT_EQ( 3, output(2).val_.val().val()); EXPECT_FLOAT_EQ( 1, output(0).d_.val().val()); EXPECT_FLOAT_EQ( 1, output(1).d_.val().val()); EXPECT_FLOAT_EQ( 1, output(2).d_.val().val()); output = columns_dot_product(d1, v2); EXPECT_FLOAT_EQ( 3, output(0).val_.val().val()); EXPECT_FLOAT_EQ( 3, output(1).val_.val().val()); EXPECT_FLOAT_EQ( 3, output(2).val_.val().val()); EXPECT_FLOAT_EQ(-1, output(0).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(1).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(2).d_.val().val()); output = columns_dot_product(v1, v2); EXPECT_FLOAT_EQ( 3, output(0).val_.val().val()); EXPECT_FLOAT_EQ( 3, output(1).val_.val().val()); EXPECT_FLOAT_EQ( 3, output(2).val_.val().val()); EXPECT_FLOAT_EQ( 0, output(0).d_.val().val()); EXPECT_FLOAT_EQ( 0, output(1).d_.val().val()); EXPECT_FLOAT_EQ( 0, output(2).d_.val().val()); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; output(0).val_.val().grad(z,h); EXPECT_FLOAT_EQ(4.0,h[0]); EXPECT_FLOAT_EQ(-2.0,h[1]); EXPECT_FLOAT_EQ(-1.0,h[2]); EXPECT_FLOAT_EQ(1.0,h[3]); EXPECT_FLOAT_EQ(3.0,h[4]); EXPECT_FLOAT_EQ(-5.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, matrix_matrix_ffv_2ndDeriv_1) { using stan::math::matrix_d; using stan::math::matrix_ffv; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); matrix_d d1(3,3), d2(3,3); matrix_ffv v1(3,3), v2(3,3); d1 << 1, 1, 1, 3, 3, 3, -5, -5, -5; v1 << a,a,a,b,b,b,c,c,c; d2 << 4, 4, 4, -2, -2, -2, -1, -1, -1; v2 << d,d,d,e,e,e,f,f,f; row_vector_ffv output; output = columns_dot_product(v1, v2); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; output(0).val().d_.grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, matrix_matrix_ffv_2ndDeriv_2) { using stan::math::matrix_d; using stan::math::matrix_ffv; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); matrix_d d1(3,3), d2(3,3); matrix_ffv v1(3,3), v2(3,3); d1 << 1, 1, 1, 3, 3, 3, -5, -5, -5; v1 << a,a,a,b,b,b,c,c,c; d2 << 4, 4, 4, -2, -2, -2, -1, -1, -1; v2 << d,d,d,e,e,e,f,f,f; row_vector_ffv output; output = columns_dot_product(v1, v2); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; output(0).d_.val().grad(z,h); EXPECT_FLOAT_EQ(1.0,h[0]); EXPECT_FLOAT_EQ(1.0,h[1]); EXPECT_FLOAT_EQ(1.0,h[2]); EXPECT_FLOAT_EQ(1.0,h[3]); EXPECT_FLOAT_EQ(1.0,h[4]); EXPECT_FLOAT_EQ(1.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, matrix_matrix_ffv_3rdDeriv) { using stan::math::matrix_d; using stan::math::matrix_ffv; using stan::math::row_vector_ffv; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); a.val_.d_ = 1.0; b.val_.d_ = 1.0; c.val_.d_ = 1.0; d.val_.d_ = 1.0; e.val_.d_ = 1.0; f.val_.d_ = 1.0; matrix_d d1(3,3), d2(3,3); matrix_ffv v1(3,3), v2(3,3); d1 << 1, 1, 1, 3, 3, 3, -5, -5, -5; v1 << a,a,a,b,b,b,c,c,c; d2 << 4, 4, 4, -2, -2, -2, -1, -1, -1; v2 << d,d,d,e,e,e,f,f,f; row_vector_ffv output; output = columns_dot_product(v1, v2); AVEC z = createAVEC(a.val().val(),b.val().val(),c.val().val(),d.val().val(),e.val().val(),f.val().val()); VEC h; output(0).d_.d_.grad(z,h); EXPECT_FLOAT_EQ(0.0,h[0]); EXPECT_FLOAT_EQ(0.0,h[1]); EXPECT_FLOAT_EQ(0.0,h[2]); EXPECT_FLOAT_EQ(0.0,h[3]); EXPECT_FLOAT_EQ(0.0,h[4]); EXPECT_FLOAT_EQ(0.0,h[5]); } TEST(AgradMixMatrixColumnsDotProduct, matrix_matrix_ffv_exception) { using stan::math::matrix_d; using stan::math::matrix_ffv; using stan::math::columns_dot_product; using stan::math::fvar; using stan::math::var; fvar<fvar<var> > a(1.0,1.0); fvar<fvar<var> > b(3.0,1.0); fvar<fvar<var> > c(-5.0,1.0); fvar<fvar<var> > d(4.0,1.0); fvar<fvar<var> > e(-2.0,1.0); fvar<fvar<var> > f(-1.0,1.0); matrix_d d1(3,3); matrix_d d2(3,2); matrix_d d3(2,3); matrix_ffv v1(3,3); matrix_ffv v2(3,3); matrix_ffv v3(3,2); matrix_ffv v4(3,2); matrix_ffv v5(2,3); matrix_ffv v6(2,3); d1 << 1, 3, -5, 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; d2 << 1, 3, -5, 1, 3, -5; v1 << a,b,c,a,b,c,a,b,c; v2 << d,e,f,d,e,f,d,e,f; v3 << d,e,f,d,e,f; v4 << d,e,f,d,e,f; v5 << d,e,f,d,e,f; v6 << d,e,f,d,e,f; EXPECT_THROW(columns_dot_product(v1,d2), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,d3), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v3), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v4), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v5), std::invalid_argument); EXPECT_THROW(columns_dot_product(v1,v6), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v3), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v4), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v5), std::invalid_argument); EXPECT_THROW(columns_dot_product(d1,v6), std::invalid_argument); EXPECT_THROW(columns_dot_product(d2,v1), std::invalid_argument); EXPECT_THROW(columns_dot_product(d2,v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d2,v5), std::invalid_argument); EXPECT_THROW(columns_dot_product(d2,v6), std::invalid_argument); EXPECT_THROW(columns_dot_product(d3,v1), std::invalid_argument); EXPECT_THROW(columns_dot_product(d3,v2), std::invalid_argument); EXPECT_THROW(columns_dot_product(d3,v3), std::invalid_argument); EXPECT_THROW(columns_dot_product(d3,v4), std::invalid_argument); }
[ "tbutler.github@internetalias.net" ]
tbutler.github@internetalias.net
80dd36307db06296e1b5cc708fbd86c3412521ef
3ae963293c0d6302ff71762dbd1760d8c605f98f
/Time-Varying Volume-graphInfo/proj/GeneratedFiles/Debug/moc_VolumeRender.cpp
c2dc06ac54aedec404c4c55122379026c52c332e
[]
no_license
Smlience/Tracking-TimeVarying-Data
b8bda6609d722aa1f2a47c773b8cd2d9101c072e
3c2ab3e9069dbe9c5ae919aea5d0d80f96a0c57e
refs/heads/master
2021-01-20T23:17:22.145255
2014-08-22T04:41:58
2014-08-22T04:41:58
23,099,760
1
0
null
null
null
null
UTF-8
C++
false
false
5,938
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'VolumeRender.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.1.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../src/render/VolumeRender.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'VolumeRender.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.1.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_VolumeRender_t { QByteArrayData data[15]; char stringdata[147]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ offsetof(qt_meta_stringdata_VolumeRender_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData) \ ) static const qt_meta_stringdata_VolumeRender_t qt_meta_stringdata_VolumeRender = { { QT_MOC_LITERAL(0, 0, 12), QT_MOC_LITERAL(1, 13, 10), QT_MOC_LITERAL(2, 24, 0), QT_MOC_LITERAL(3, 25, 13), QT_MOC_LITERAL(4, 39, 15), QT_MOC_LITERAL(5, 55, 5), QT_MOC_LITERAL(6, 61, 11), QT_MOC_LITERAL(7, 73, 8), QT_MOC_LITERAL(8, 82, 11), QT_MOC_LITERAL(9, 94, 8), QT_MOC_LITERAL(10, 103, 12), QT_MOC_LITERAL(11, 116, 1), QT_MOC_LITERAL(12, 118, 7), QT_MOC_LITERAL(13, 126, 14), QT_MOC_LITERAL(14, 141, 4) }, "VolumeRender\0dataLoaded\0\0const Volume*\0" "sendFileDirName\0char*\0fileDirName\0" "loadData\0const char*\0filename\0" "onDataLoaded\0v\0set1DTF\0unsigned char*\0" "data\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_VolumeRender[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 6, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 44, 2, 0x05, 1, 0, 47, 2, 0x05, 4, 1, 48, 2, 0x05, // slots: name, argc, parameters, tag, flags 7, 1, 51, 2, 0x0a, 10, 1, 54, 2, 0x0a, 12, 1, 57, 2, 0x0a, // signals: parameters QMetaType::Void, 0x80000000 | 3, 2, QMetaType::Void, QMetaType::Void, 0x80000000 | 5, 6, // slots: parameters QMetaType::Void, 0x80000000 | 8, 9, QMetaType::Void, 0x80000000 | 3, 11, QMetaType::Void, 0x80000000 | 13, 14, 0 // eod }; void VolumeRender::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { VolumeRender *_t = static_cast<VolumeRender *>(_o); switch (_id) { case 0: _t->dataLoaded((*reinterpret_cast< const Volume*(*)>(_a[1]))); break; case 1: _t->dataLoaded(); break; case 2: _t->sendFileDirName((*reinterpret_cast< char*(*)>(_a[1]))); break; case 3: _t->loadData((*reinterpret_cast< const char*(*)>(_a[1]))); break; case 4: _t->onDataLoaded((*reinterpret_cast< const Volume*(*)>(_a[1]))); break; case 5: _t->set1DTF((*reinterpret_cast< unsigned char*(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (VolumeRender::*_t)(const Volume * ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VolumeRender::dataLoaded)) { *result = 0; } } { typedef void (VolumeRender::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VolumeRender::dataLoaded)) { *result = 1; } } { typedef void (VolumeRender::*_t)(char * ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VolumeRender::sendFileDirName)) { *result = 2; } } } } const QMetaObject VolumeRender::staticMetaObject = { { &QGLCanvas::staticMetaObject, qt_meta_stringdata_VolumeRender.data, qt_meta_data_VolumeRender, qt_static_metacall, 0, 0} }; const QMetaObject *VolumeRender::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *VolumeRender::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_VolumeRender.stringdata)) return static_cast<void*>(const_cast< VolumeRender*>(this)); return QGLCanvas::qt_metacast(_clname); } int VolumeRender::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QGLCanvas::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 6) qt_static_metacall(this, _c, _id, _a); _id -= 6; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 6) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 6; } return _id; } // SIGNAL 0 void VolumeRender::dataLoaded(const Volume * _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void VolumeRender::dataLoaded() { QMetaObject::activate(this, &staticMetaObject, 1, 0); } // SIGNAL 2 void VolumeRender::sendFileDirName(char * _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } QT_END_MOC_NAMESPACE
[ "smilence@zju.edu.cn" ]
smilence@zju.edu.cn
c20b1b4ce57d3504dc98d1af8f17d9bdc13f9a19
fd0f01d316c0caef60235549ee84c28c0431711f
/main.cc
73ba07fddad50ebe07a8b0b27334392c08604b06
[]
no_license
gssbzn/proyecto_calculo_2006
df9a25878f14be0466fdfc7de17210695a94a46b
cf13aff22eeb0d9b959483fe29ce94f98bcef115
refs/heads/master
2016-09-05T20:15:00.828327
2012-06-18T23:28:31
2012-06-18T23:28:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,602
cc
#include "matriz.h" #include "matriz.cc" using namespace std; //Menu de la Aplicacion int menu(); //Para cargar "matriz.in" en 2 matrices, una con los valores de x y otra con los //f(x) bool cargaMatriz(matriz *, matriz *); //Para cargar "matriz.in" en 1 matriz, con los valores de x, f(x) y f'(x) bool cargaMatriz2(matriz *); int main() { int o; float tol, w; double x; double *xi; matriz Q, Xi; matriz A, b; system("clear"); do{ o=menu(); switch(o){ case 1: cout<<"Eliminacion Gaussiana\n\n"; cargaMatriz2(&A); x=new double[A.getN()]; if(A.eliGauss(x)){ for(int i=0; i<A.getN(); i++) cout<<"X["<<i<<"]= "<<xi[i]<<" "; } else cout<<"Error\n\n"; free(x); break; case 2: cargaMatriz2(&A); cout<<"Eliminacion Gaussiana con Pivoteo Parcial\n\n"; x=new double[A.getN()]; if(A.eliGaussPivotPar(x)){ for(int i=0; i<A.getN(); i++) cout<<"X["<<i<<"]= "<<xi[i]<<" "; } else cout<<"Error\n\n"; free(x); break; case 3: cout<<"Eliminacion Gaussiana con Pivoteo Parcial Escalado\n\n"; cargaMatriz2(&A); x=new double[A.getN()]; if(A.eliGaussPivotParEsc(x)){ for(int i=0; i<A.getN(); i++) cout<<"X["<<i<<"]= "<<xi[i]<<" "; } else cout<<"Error\n\n"; free(x); break; case 4: cargaMatriz(&A, &b); cout<<"Factorizacion LU\n\n"; A.factLU(&b); break; case 5: cargaMatriz(&A, &b); cout<<"Jacobi\n\n"; cout<<"Numero de iteraciones: "; cin>>N; cout<<"Tolerancia: "; cin>>tol; x=new double[A.getN()]; A.jacobi(&b, x, N, tol); for(int i=0; i<A.getN(); i++) cout<<"X["<<i<<"]= "<<xi[i]<<" "; free(x); break; case 6: cargaMatriz(&A, &b); cout<<"Gauss-Seidel\n\n"; cout<<"Numero de iteraciones: "; cin>>N; cout<<"Tolerancia: "; cin>>tol; x=new double[A.getN()]; A.gaussSeidel(&b, x, N, tol); for(int i=0; i<A.getN(); i++) cout<<"X["<<i<<"]= "<<xi[i]<<" "; free(x); break; case 7: cargaMatriz2(&A); cout<<"SOR\n\n"; cout<<"Numero de iteraciones: "; cin>>N; cout<<"Tolerancia: "; cin>>tol; cout<<"W: "; cin>>w; A.sor(N,tol,w); break; case 8: cout<<"Metodo de Diferencias Divididas\n\n"; if(cargaMatriz(&Xi, &Q)){ Q.diferenciasDivididas(&Xi); cout<<Q<<endl; } else cerr << "\n\n\n***ERROR*** No se ha podido encontrar el archivo\n\b"; break; case 9: cout<<"Metodo de Neville\n\n"; if(cargaMatriz(&Xi, &Q)){ cout<<"Introduzca el valor de x para el cual\naproximar f(x): "; cin>>x; Q.neville(&Xi,x); cout<<Q<<endl; } else cerr << "\n\n\n***ERROR*** No se ha podido encontrar el archivo\n\b"; break; case 10: cout<<"Metodo de Hermite\n\n"; if(cargaMatriz2(&Xi)){ Q.crear(2*Xi.getN(), 2*Xi.getN()); Q.hermite(&Xi); cout<<Q<<endl; } else cerr << "\n\n\n***ERROR*** No se ha podido encontrar el archivo\n\b"; break; case 11: cout<<"Metodo de Lagrange\n\n"; if(cargaMatriz(&Q, &Xi)){ cout<<"Introduzca el valor de x para el cual\naproximar f(x): "; cin>>x; cout<<"f("<<x<<")= "<<Q.lagrange(&Xi,x)<<endl; } else cerr << "\n\n\n***ERROR*** No se ha podido encontrar el archivo\n\b"; break; case 0: cout<<endl<<"Adios"<<endl; break; default: cerr<<"opcion erronea\n\n"; break; } }while(o!=5); return EXIT_SUCCESS; } /******************************************************************************/ int menu() { char res[20]; cout<<"\n\nEscoja el metodo para la solucion del sistema\n\n\n"; cout<<"1.-Eliminacion Gaussiana\n"; cout<<"2.-Eliminacion Gaussiana con Pivoteo Parcial\n"; cout<<"3.-Eliminacion Gaussiana con Pivoteo Parcial Escalado\n"; cout<<"4.-Descomposicion L.U.\n"; cout<<"5.-Jacobi\n"; cout<<"6.-Gauss-Seidel\n"; cout<<"7.-SOR\n"; cout<<"8.-Metodo de Diferencias Divididas\n"; cout<<"9.-Metodo de Neville\n"; cout<<"10.-Metodo de Hermite\n"; cout<<"11.-Metodo de Lagrange\n\n"; cout<<"0.-Salir\n"; cin>>res; system("clear"); return atoi(res); } /******************************************************************************/ bool cargaMatriz(matriz *A, matriz *b){ ifstream entrada; int n,m; //Carga del archivo de entrada matriz.in entrada.open("matriz.in", ios:: in); if (entrada==NULL)/*SI NO SE PUEDE ABRIR EL FICHERO*/ return false; else { entrada >> n >> m; //Lectura A A->crear(n,1); for(int i=0;i<A->getN();i++) { double num; entrada >> num; A->setElemento(i,0,num); } //Lectura b b->crear(n,n); for(int i=0;i<b->getN();i++) { double num; entrada >> num; b->setElemento(i,0,num); } } entrada.close(); return true; } /******************************************************************************/ bool cargaMatriz2(matriz *A){ ifstream entrada; int n,m; //Carga del archivo de entrada matriz.in entrada.open("matriz.in", ios:: in); if (entrada==NULL)/*SI NO SE PUEDE ABRIR EL FICHERO*/ return false; else { entrada >> n >> m; //Lectura A A->crear(n,m); for(int j=0;j<A->getM();j++) { for(int i=0;i<A->getN();i++) { double num; entrada >> num; A->setElemento(i,j,num); } } } entrada.close(); return true; } /******************************************************************************/
[ "gssbzn@gmail.com" ]
gssbzn@gmail.com
b4f6e26aa6a7b44088de5606eb53c7a1d2d63dc2
105eb633ff77c9e31e3bb755fa6ac407e7635d46
/Project2/sprawdzenie_ukladu.cpp
3ba80c32fe33e39f4757c22d2e7e56219497169e
[]
no_license
Iartur221/Poker-in-strings
67fe9022824f6b220114031163c69629b5d3712e
1bf1ef4ba8e99d72486b59f651d55b1100e1e3e4
refs/heads/master
2023-03-05T03:28:51.197314
2021-02-16T19:55:38
2021-02-16T19:55:38
339,514,445
0
0
null
null
null
null
UTF-8
C++
false
false
20,342
cpp
#include "deklaracje.h" int uklady(string user[5]) { //para, 2pary, trojka, kareta, full bool para{}; bool pary2{}; bool trojka{}; bool kareta{}; bool full{}; for (int i = 0; i < 4; i++) //i mniejsze od 4 bo dalej [i + 1] { string first = user[i]; string second = user[i + 1]; char pierwsza = first[1]; char druga = second[1]; if (pierwsza == druga) { if (i < 3) // jezeli jest mozliwosc wystapienia sprawdz czy jest trojka { string third = user[i + 2]; char trzecia = third[1]; if (druga == trzecia)//trojka { trojka = true; if (i < 2)//jezeli jest mozliwosc sprawdz czy jest kareta { string fourth = user[i + 3]; char czwarta = fourth[1]; if (trzecia == czwarta) { kareta = true; } } if (i == 0)// teraz sprawdz czy moze byc full trojka x para { string fourth = user[i + 3]; string fifth = user[i + 4]; char czwarta = fourth[1]; char piata = fifth[1]; if (czwarta == piata) { full = true; } } if (full == true || kareta == true) { trojka = false; } } } para = true; if (para == true && i < 2) { string third = user[i + 2]; string fourth = user[i + 3]; char trzecia = third[1]; char czwarta = fourth[1]; if (trzecia == czwarta)// 2 pary-cos lub full { if (i == 0) // sprawdz fulla para x trojka i para-cos-para { string fifth = user[i + 4]; char piata = fifth[1]; if (czwarta == piata) { full = true; } } pary2 = true; } if (i == 0) { string fifth = user[i + 4]; // sprawdz uklad para - cos - para char piata = fifth[1]; if (czwarta == piata) { pary2 = true; } } if (full == true) { pary2 = false; } } } if (trojka == true || kareta == true) { pary2 = false; } // wykluczenie 2 ukladow naraz if (kareta == true || full == true || trojka == true || pary2 == true) { para = false; } } if (para == true) { return 1; } // zwracanie odpowiedniej wartosci wg starszenstwa ukladow else if (pary2 == true) { return 2; } else if (trojka == true) { return 3; } else if (kareta == true) { return 7; } else if (full == true) { return 6; } // zmiana J, Q, K, A na 11, 12, 13, 14, jezeli nie ma ukladow powyzej string Pik = "Pik"; string Kier = "Kier"; string Karo = "Karo"; string Trefl = "Trefl"; for (int i = 0; i < 5; i++) { string karta = user[i]; if (user[i].find(Pik) != string::npos) { if (karta[1] == 'J') { user[i] = "[11]Pik"; } if (karta[1] == 'Q') { user[i] = "[12]Pik"; } if (karta[1] == 'K') { user[i] = "[13]Pik"; } if (karta[1] == 'A') { user[i] = "[14]Pik"; } } if (user[i].find(Kier) != string::npos) { if (karta[1] == 'J') { user[i] = "[11]Kier"; } if (karta[1] == 'Q') { user[i] = "[12]Kier"; } if (karta[1] == 'K') { user[i] = "[13]Kier"; } if (karta[1] == 'A') { user[i] = "[14]Kier"; } } if (user[i].find(Karo) != string::npos) { if (karta[1] == 'J') { user[i] = "[11]Karo"; } if (karta[1] == 'Q') { user[i] = "[12]Karo"; } if (karta[1] == 'K') { user[i] = "[13]Karo"; } if (karta[1] == 'A') { user[i] = "[14]Karo"; } } if (user[i].find(Trefl) != string::npos) { if (karta[1] == 'J') { user[i] = "[11]Trefl"; } if (karta[1] == 'Q') { user[i] = "[12]Trefl"; } if (karta[1] == 'K') { user[i] = "[13]Trefl"; } if (karta[1] == 'A') { user[i] = "[14]Trefl"; } } } //sprawdzenie strita int a = {}; string karta1 = user[0]; char x = karta1[1]; if (x == '1') { x = karta1[2]; a = x - '0' + 10; } else { a = x - '0'; } int b = {}; karta1 = user[1]; x = karta1[1]; if (x == '1') { x = karta1[2]; b = x - '0' + 10; } else { b = x - '0'; } int c = {}; karta1 = user[2]; x = karta1[1]; if (x == '1') { x = karta1[2]; c = x - '0' + 10; } else { c = x - '0'; } int d = {}; karta1 = user[3]; x = karta1[1]; if (x == '1') { x = karta1[2]; d = x - '0' + 10; } else { d = x - '0'; } int e = {}; karta1 = user[4]; x = karta1[1]; if (x == '1') { x = karta1[2]; e = x - '0' + 10; } else { e = x - '0'; } bool strit{}; if (a + 1 == b) { if (b + 1 == c) { if (c + 1 == d) { if (d + 1 == e) { strit = true; } } } } bool kolor = {}; // sprawdzenie koloru if (user[0].find(Pik) != string::npos && user[1].find(Pik) != string::npos && user[2].find(Pik) != string::npos && user[3].find(Pik) != string::npos && user[4].find(Pik) != string::npos) { kolor = true; } else if (user[0].find(Kier) != string::npos && user[1].find(Kier) != string::npos && user[2].find(Kier) != string::npos && user[3].find(Kier) != string::npos && user[4].find(Kier) != string::npos) { kolor = true; } else if (user[0].find(Karo) != string::npos && user[1].find(Karo) != string::npos && user[2].find(Karo) != string::npos && user[3].find(Karo) != string::npos && user[4].find(Karo) != string::npos) { kolor = true; } else if (user[0].find(Trefl) != string::npos && user[1].find(Trefl) != string::npos && user[2].find(Trefl) != string::npos && user[3].find(Trefl) != string::npos && user[4].find(Trefl) != string::npos) { kolor = true; } bool poker{}; if (kolor == true && strit == true) { poker = true; strit = false; kolor = false; } bool pokerkrolewski{}; if (poker == true) { string karty = user[0]; if (karty[1] == '1') // poker ktory zaczyna sie od 10 { pokerkrolewski = true; poker = false; } } for (int i = 0; i < 5; i++) // przeksztalcenie z powrotem na symbole { string karta = user[i]; if (user[i].find(Pik) != string::npos) { if (karta[1] == '1' && karta[2] == '1') { user[i] = "[J]Pik"; } if (karta[1] == '1' && karta[2] == '2') { user[i] = "[Q]Pik"; } if (karta[1] == '1' && karta[2] == '3') { user[i] = "[K]Pik"; } if (karta[1] == '1' && karta[2] == '4') { user[i] = "[A]Pik"; } } if (user[i].find(Kier) != string::npos) { if (karta[1] == '1' && karta[2] == '1') { user[i] = "[J]Kier"; } if (karta[1] == '1' && karta[2] == '2') { user[i] = "[Q]Kier"; } if (karta[1] == '1' && karta[2] == '3') { user[i] = "[K]Kier"; } if (karta[1] == '1' && karta[2] == '4') { user[i] = "[A]Kier"; } } if (user[i].find(Karo) != string::npos) { if (karta[1] == '1' && karta[2] == '1') { user[i] = "[J]Karo"; } if (karta[1] == '1' && karta[2] == '2') { user[i] = "[Q]Karo"; } if (karta[1] == '1' && karta[2] == '3') { user[i] = "[K]Karo"; } if (karta[1] == '1' && karta[2] == '4') { user[i] = "[A]Karo"; } } if (user[i].find(Trefl) != string::npos) { if (karta[1] == '1' && karta[2] == '1') { user[i] = "[J]Trefl"; } if (karta[1] == '1' && karta[2] == '2') { user[i] = "[Q]Trefl"; } if (karta[1] == '1' && karta[2] == '3') { user[i] = "[K]Trefl"; } if (karta[1] == '1' && karta[2] == '4') { user[i] = "[A]Trefl"; } } } if (pokerkrolewski == true) // zwracanie odpowiedniej wartosci wg starszenstwa ukladow { return 9; } if (poker == true) { return 8; } if (kolor == true) { return 5; } if (strit == true) { return 4; } else return 0; } int wygrana(string user[5], string computer[5]) { int x = uklady(user); int y = uklady(computer); if (x == 0) { cout << "Masz najwyzsza karte: " << user[4] << endl; } //done if (x == 1) { cout << "Masz Pare" << endl; } //done if (x == 2) { cout << "Masz 2 Pary" << endl; } //done if (x == 3) { cout << "Masz Trojke" << endl; } //done if (x == 7) { cout << "Masz Karete" << endl; } //done if (x == 6) { cout << "Masz Fulla" << endl; } //done if (x == 9) { cout << "Masz Pokera krolewskiego" << endl; } //done if (x == 8) { cout << "Masz Pokera" << endl; } // done if (x == 5) { cout << "Masz Kolor" << endl; } //done if (x == 4) { cout << "Masz Strit" << endl; } //done if (y == 0) { cout << "Przeciwnik ma najwyzsza karte: " << computer[4] << endl; } //done if (y == 1) { cout << "Przeciwnik ma Pare" << endl; } //done if (y == 2) { cout << "Przeciwnik ma 2 Pary" << endl; } //done if (y == 3) { cout << "Przeciwnik ma Trojke" << endl; } //done if (y == 7) { cout << "Przeciwnik ma Karete" << endl; } //done if (y == 6) { cout << "Przeciwnik ma Fulla" << endl; } //done if (y == 9) { cout << "Przeciwnik ma Pokera krolewskiego" << endl; } //done if (y == 8) { cout << "Przeciwnik ma Pokera" << endl; } // done if (y == 5) { cout << "Przeciwnik ma Kolor" << endl; } //done if (y == 4) { cout << "Przeciwnik ma Strit" << endl; } //done if (x > y) { return 1; } if (x < y) { return 0; } if (x == y) { if (x == 4 || x == 8) //strit vs strit. Wyzszy strit lub poker ma wyzsza pierwsza karte { //char 0 = int 48 string karta1 = user[0]; string karta2 = computer[0]; char test1 = karta1[1]; char test2 = karta2[1]; int j; int k; if (test1 == '1') { j = 58; } else { j = test1; } if (test2 == '1') { k = 58; } else { k = test2; } if (j > k) { return 1; } if (j < k) { return 0; } if (j == k) { return 2; } } if (x == 9) { return 2; } // 2 pokery krolewskie daja remis if (x == 6 || x == 7 || x == 3) // trzecia karta w kolejnosci zawsze jest w trojce, wygrywa wyzsza trojka i nie moga wystapic 2 takie same trojki, kareta analogicznie { string karta1 = user[2]; string karta2 = computer[2]; char test1 = karta1[1]; char test2 = karta2[1]; int j; int k; if (test1 == '1') { j = 58; } else if (test1 == 'J') { j = 59; } else if (test1 == 'Q') { j = 60; } else if (test1 == 'K') { j = 61; } else if (test1 == 'A') { j = 62; } else { j = test1; } if (test2 == '1') { k = 58; } else if (test2 == 'J') { k = 59; } else if (test2 == 'Q') { k = 60; } else if (test2 == 'K') { k = 61; } else if (test2 == 'A') { k = 62; } else { k = test2; } if (j > k) { return 1; } if (j < k) { return 0; } } if (x == 5) //kolor vs kolor wygrywa wyzsza najwyzsza karta { string karta1 = user[4]; string karta2 = computer[4]; char test1 = karta1[1]; char test2 = karta2[1]; int j; int k; if (test1 == '1') { j = 58; } else if (test1 == 'J') { j = 59; } else if (test1 == 'Q') { j = 60; } else if (test1 == 'K') { j = 61; } else if (test1 == 'A') { j = 62; } else { j = test1; } if (test2 == '1') { k = 58; } else if (test2 == 'J') { k = 59; } else if (test2 == 'Q') { k = 60; } else if (test2 == 'K') { k = 61; } else if (test2 == 'A') { k = 62; } else { k = test2; } if (j > k) { return 1; } if (j < k) { return 0; } } if (x == 2) // 2pary vs 2pary { int k = 0; int j = 0; for (int i = 4; i > 0; i--) // czy jest jakas wyzsza para? { string karta1 = user[i]; string karta2 = user[i - 1]; char parauser = 0; if (karta1[1] == karta2[1])//para znaleziona spisz jej wartosc { parauser = karta1[1]; if (parauser == '1') { k = 58; } else if (parauser == 'J') { k = 59; } else if (parauser == 'Q') { k = 60; } else if (parauser == 'K') { k = 61; } else if (parauser == 'A') { k = 62; } else { k = parauser; } } string karta3 = computer[i]; string karta4 = computer[i - 1]; char paracomputer = 0; if (karta3[1] == karta4[1])//para znaleziona spisz jej wartosc { paracomputer = karta3[1]; if (paracomputer == '1') { j = 58; } else if (paracomputer == 'J') { j = 59; } else if (paracomputer == 'Q') { j = 60; } else if (paracomputer == 'K') { j = 61; } else if (paracomputer == 'A') { j = 62; } else { j = paracomputer; } } if (k != 0 && j != 0) { if (k > j) { return 1; } if (k < j) { return 0; } if (k == j)//1 silniejsza para taka sama szukaj drugiej pary i porownaj je { k = 0; // wyzerowanie zmiennych j = 0; } } } for (int i = 0; i < 5; i++)// obie pary byly takie same, sprawdz czy jest wyzsza piata karta { if (i == 0) // 1 karta uklad 1-2-2 { string karta1 = user[i]; string karta2 = user[i + 1]; char kartauser = 0; if (karta1[1] != karta2[1])//karta nie tworzy pary { kartauser = karta1[1]; if (kartauser == '1') { k = 58; } else if (kartauser == 'J') { k = 59; } else if (kartauser == 'Q') { k = 60; } else if (kartauser == 'K') { k = 61; } else if (kartauser == 'A') { k = 62; } else { k = kartauser; } } string karta3 = computer[i]; string karta4 = computer[i + 1]; char kartacomp = 0; if (karta3[1] != karta4[1])//karta nie tworzy pary { kartacomp = karta3[1]; if (kartacomp == '1') { j = 58; } else if (kartacomp == 'J') { j = 59; } else if (kartacomp == 'Q') { j = 60; } else if (kartacomp == 'K') { j = 61; } else if (kartacomp == 'A') { j = 62; } else { j = kartacomp; } } } if (i == 2) //karta nie tworzy pary do tylu i do przodu (uklad para-1-para) { string karta1 = user[i]; string karta2 = user[i + 1]; string karta3 = user[i - 1]; char kartauser = 0; if (karta1[1] != karta2[1] && karta1[1] != karta3[1]) { kartauser = karta1[1]; if (kartauser == '1') { k = 58; } else if (kartauser == 'J') { k = 59; } else if (kartauser == 'Q') { k = 60; } else if (kartauser == 'K') { k = 61; } else if (kartauser == 'A') { k = 62; } else { k = kartauser; } } string karta4 = computer[i]; string karta5 = computer[i + 1]; string karta6 = computer[i - 1]; char kartacomp = 0; if (karta4[1] != karta5[1] && karta4[1] != karta6[1])//karta nie tworzy pary do tylu i do przodu (uklad para-1-para) { kartacomp = karta4[1]; if (kartacomp == '1') { j = 58; } else if (kartacomp == 'J') { j = 59; } else if (kartacomp == 'Q') { j = 60; } else if (kartacomp == 'K') { j = 61; } else if (kartacomp == 'A') { j = 62; } else { j = kartacomp; } } } if (i == 4) // ostatnia karta uklad 2-2-1 { string karta1 = user[i]; char kartauser = 0; kartauser = karta1[1]; if (kartauser == '1') { k = 58; } else if (kartauser == 'J') { k = 59; } else if (kartauser == 'Q') { k = 60; } else if (kartauser == 'K') { k = 61; } else if (kartauser == 'A') { k = 62; } else { k = kartauser; } string karta3 = computer[i]; char kartacomp = 0; kartacomp = karta3[1]; if (kartacomp == '1') { j = 58; } else if (kartacomp == 'J') { j = 59; } else if (kartacomp == 'Q') { j = 60; } else if (kartacomp == 'K') { j = 61; } else if (kartacomp == 'A') { j = 62; } else { j = kartacomp; } } if (k != 0 && j != 0) { if (k > j) { return 1; }// karta usera mocniejsza if (k < j) { return 0; } if (k == j) { return 2; } // remis } } } if (x == 0) // najwyzsza karta wygrywa { for (int i = 4; i >= 0; i--) { string karta1 = user[i]; string karta2 = computer[i]; char a = karta1[1]; char b = karta2[1]; int k{}; int j{}; if (a == '1') { j = 58; } else if (a == 'J') { j = 59; } else if (a == 'Q') { j = 60; } else if (a == 'K') { j = 61; } else if (a == 'A') { j = 62; } else { j = a; } if (b == '1') { k = 58; } else if (b == 'J') { k = 59; } else if (b == 'Q') { k = 60; } else if (b == 'K') { k = 61; } else if (b == 'A') { k = 62; } else { k = b; } if (j > k) { return 1; }//user wygral if (j < k) { return 0; } if (j == k) { if (i == 0) { return 2; //remis } } } } if (x == 1) // para vs para { int k = 0; int j = 0; for (int i = 4; i > 0; i--) // czy jest jakas wyzsza para? { string karta1 = user[i]; string karta2 = user[i - 1]; char parauser = 0; if (karta1[1] == karta2[1])//para { parauser = karta1[1]; if (parauser == '1') { k = 58; } else if (parauser == 'J') { k = 59; } else if (parauser == 'Q') { k = 60; } else if (parauser == 'K') { k = 61; } else if (parauser == 'A') { k = 62; } else { k = parauser; } } string karta3 = computer[i]; string karta4 = computer[i - 1]; char paracomputer = 0; if (karta3[1] == karta4[1])//para { paracomputer = karta3[1]; if (paracomputer == '1') { j = 58; } else if (paracomputer == 'J') { j = 59; } else if (paracomputer == 'Q') { j = 60; } else if (paracomputer == 'K') { j = 61; } else if (paracomputer == 'A') { j = 62; } else { j = paracomputer; } } if (k != 0 && j != 0) // jezeli znajdzie obie pary porownaj je { if (k > j) { return 1; } if (k < j) { return 0; } if (k == j) //takie same pary sprawdzaj dalej karty { k = 0; j = 0; break; } } } int x = 0; int z = 0; for (int i = 4; i >= 0; i--) { if (i == 4) { string karta1 = user[i]; string karta2 = user[i - 1]; char kartauser = 0; if (karta1[1] != karta2[1])//karta nie tworzy pary { kartauser = karta1[1]; if (kartauser == '1') { k = 58; } else if (kartauser == 'J') { k = 59; } else if (kartauser == 'Q') { k = 60; } else if (kartauser == 'K') { k = 61; } else if (kartauser == 'A') { k = 62; } else { k = kartauser; } } string karta3 = computer[i]; string karta4 = computer[i - 1]; char kartacomp = 0; if (karta3[1] != karta4[1])//karta nie tworzy pary { kartacomp = karta3[1]; if (kartacomp == '1') { j = 58; } else if (kartacomp == 'J') { j = 59; } else if (kartacomp == 'Q') { j = 60; } else if (kartacomp == 'K') { j = 61; } else if (kartacomp == 'A') { j = 62; } else { j = kartacomp; } } } if (i != 4 && i != 0) //karta nie tworzy pary z karta do tylu i do przodu { string karta1 = user[i]; string karta2 = user[i + 1]; string karta3 = user[i - 1]; char kartauser = 0; if (karta1[1] != karta2[1] && karta1[1] != karta3[1]) { kartauser = karta1[1]; if (kartauser == '1') { x = 58; } else if (kartauser == 'J') { x = 59; } else if (kartauser == 'Q') { x = 60; } else if (kartauser == 'K') { x = 61; } else if (kartauser == 'A') { x = 62; } else { x = kartauser; } } string karta4 = computer[i]; string karta5 = computer[i + 1]; string karta6 = computer[i - 1]; char kartacomp = 0; if (karta4[1] != karta5[1] && karta4[1] != karta6[1])//brak pary { kartacomp = karta4[1]; if (kartacomp == '1') { z = 58; } else if (kartacomp == 'J') { z = 59; } else if (kartacomp == 'Q') { z = 60; } else if (kartacomp == 'K') { z = 61; } else if (kartacomp == 'A') { z = 62; } else { z = kartacomp; } } if (k > x) { k = x; } // jezeli k = 0 zastap go nowa karta, k i j zeruje sie w przypadku 2 takich samych figur u komputera i uzytkownika if (z > j) { j = z; } // jezeli j = 0 zastap go nowa karta } if (i == 0) { string karta1 = user[i]; string karta2 = user[i - 1]; char kartauser = 0; if (karta1[1] != karta2[1])//brak pary { kartauser = karta1[1]; if (kartauser == '1') { k = 58; } else if (kartauser == 'J') { k = 59; } else if (kartauser == 'Q') { k = 60; } else if (kartauser == 'K') { k = 61; } else if (kartauser == 'A') { k = 62; } else { k = kartauser; } } string karta3 = computer[i]; string karta4 = computer[i - 1]; char kartacomp = 0; if (karta3[1] != karta4[1])//brak pary { kartacomp = karta3[1]; if (kartacomp == '1') { j = 58; } else if (kartacomp == 'J') { j = 59; } else if (kartacomp == 'Q') { j = 60; } else if (kartacomp == 'K') { j = 61; } else if (kartacomp == 'A') { j = 62; } else { j = kartacomp; } } } if (k != 0 && j != 0) { if (k > j) { return 1; } if (k < j) { return 0; } if (k == j) { k = 0; // wyzeruj sprawdzane karty zeby przejsc dalej j = 0; if (i == 0) { return 2; } // remis } } } } } return 0; }
[ "artuiwa818@student.polsl.pl" ]
artuiwa818@student.polsl.pl
ebc28f498af08116e6b1effbcade11fc891b7c6f
98b2ee5a57d66c957f8b924e0c99e28be9ce51d8
/leetcode/234_PalindromeLinkedList/main.cpp
cdb326b3f5baa44743c70163474320444ca04bb4
[]
no_license
sauleddy/C_plus
c990aeecedcb547fc3afcbf387d2b51aa94d08cc
69d6a112d1dd9ac2d99c4b630bb6769b09032252
refs/heads/master
2021-01-19T04:49:07.240672
2017-06-07T05:51:10
2017-06-07T05:51:10
87,397,291
0
0
null
null
null
null
UTF-8
C++
false
false
375
cpp
/* * 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: main.cpp * Author: eddy * * Created on May 18, 2017, 8:51 AM */ #include <cstdlib> using namespace std; /* * */ int main(int argc, char** argv) { return 0; }
[ "sauleddy38@gmail.com" ]
sauleddy38@gmail.com
023541491c75b03072253b888375ef364795e54d
18476e38d4f7b5183b02a489103188fc81ba27a3
/readNas/readNas/gmshSurface.h
2a65be0f20728c7efd787e07f7cb27d287ce3c42
[]
no_license
chapman2014/ioNas
e1a0870aa66331f3bb14f335c05e229b29b26bb9
9fb0ee33c17debe6c7e863fdc2c1d456698ffa94
refs/heads/master
2020-12-14T13:25:00.912105
2015-08-29T03:54:17
2015-08-29T03:54:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,555
h
#ifndef _GMSH_SURFACE_H_ #define _GMSH_SURFACE_H_ #include <math.h> #include <map> //#include "Pair.h" #include "Range.h" #include "SPoint2.h" #include "SPoint3.h" #include "SVector3.h" #include "SBoundingBox3d.h" //#include "Numeric.h" class gmshSurface { protected: static std::map<int, gmshSurface*> allGmshSurfaces; public: //there are points define in this surface parameterization bool vertex_defined_on_surface; virtual ~gmshSurface(){} static void reset() { std::map<int, gmshSurface*>::iterator it = allGmshSurfaces.begin(); for (; it != allGmshSurfaces.end(); ++it){ if(!it->second->vertex_defined_on_surface) delete it->second; } allGmshSurfaces.clear(); }; static gmshSurface* getSurface(int tag); virtual Range<double> parBounds(int i) const = 0; /// Underlying geometric representation of this entity. enum gmshSurfaceType { Plane, Nurbs, Cylinder, Sphere, Cone, Torus, ParametricSurface, PolarSphere }; virtual gmshSurface::gmshSurfaceType geomType() const = 0; virtual SPoint3 point(double par1, double par2) const = 0; virtual SPoint3 point(const SPoint2 &p) const { return point(p.x(), p.y()); } virtual SPoint2 parFromPoint(double x, double y, double z); // Return the normal to the face at the given parameter location. virtual SVector3 normal(const SPoint2 &param) const; // Return the first derivate of the face at the parameter location. // virtual Pair<SVector3,SVector3> firstDer(const SPoint2 &param); virtual double getMetricEigenvalue(const SPoint2 &); }; #endif
[ "pointfly@163.com" ]
pointfly@163.com
7459cabe1072eafea7a1f0e1e4b0362bbe1daadd
c360a6cd4bce42c7ab5c1159b076d4a427bc6d4b
/2-trabalhos-entregues/projeto2/questao2/main.cpp
9f91a0a4df3796d3273e2ede7d18b8ef543979f5
[]
no_license
robertsonasc/UFC-Estrutura-de-Dados
a4a970154cdab241cf03d3384fa60a97c29afd3a
42eaedc7aaf43b69a43b4cc6ef8717199acc66aa
refs/heads/main
2023-08-11T07:34:17.863784
2021-09-20T19:04:17
2021-09-20T19:04:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,976
cpp
//Robertson Nascimento - 391242 #include <iostream> #include "Conjunto.h" //#include <Windows.h> Descomentar essa linha caso for compilar em windows. using namespace std; struct Elemento{ int unidadeConj; }; int main(){ //SetConsoleOutputCP(CP_UTF8); Descomentar essa linha caso for compilar em windows. int opcao; int contConjuntos = 0; int tam = 20; Conjunto *bancoConjuntos[tam]; while(opcao != 13){ string menu; cout << "-------------------------------------------------------------------------" << endl; cout << "Total de Conjuntos ativos: " << contConjuntos << endl; for(int i=0; i < contConjuntos; i++){ cout << "Conjunto " << i+1 << ": "; for(int j=0; j < bancoConjuntos[i]->getTamanho(); j++){ Elemento e = bancoConjuntos[i]->getElementoVetor(j); cout << e.unidadeConj << " "; } cout << endl; } menu += "Digite uns dos comandos a seguir para realizar a tarefa desejada: \n\n"; menu += " 1 | Para criar um conjunto.\n"; menu += " 2 | Para deletar um conjunto.\n"; menu += " 3 | Para inserir um elemento em um conjunto.\n"; menu += " 4 | Para criar um conjunto união de dois conjunto existentes e salva-lo no final da nossa lista de conjuntos. C (C = A ∪ B).\n"; menu += " 5 | Para criar uma cópia de um conjunto e salva-la no final da nossa lista de conjuntos.\n"; menu += " 6 | Para criar um conjunto da intersecção de dois conjuntos existentes e salva-lo no final da lista de conjuntos. (C = A ∩ B).\n"; menu += " 7 | Para criar um conjunto da diferença entre dois conjuntos existentes e salva-lo no final da lista de conjuntos.\n"; menu += " 8 | Para criar um conjunto da diferença simétrica entre dois conjuntos existentes e salva-lo no final da lista de conjuntos.\n"; menu += " 9 | Para remover um elemento de um conjunto existente.\n"; menu += " 10 | Para retornar o valor máximo de um conjunto.\n"; menu += " 11 | Para retornar o valor mínimo de um conjunto.\n"; menu += " 12 | Para retornar verdadeiro se um conjuntos é igual a outro, falso caso contrário.\n"; menu += " 13 | Para fechar o programa.\n\n"; cout << menu; cin >> opcao; switch(opcao){ case 1:{ if(contConjuntos < tam){ bancoConjuntos[contConjuntos] = new Conjunto(); contConjuntos++; cout << "Conjunto criado com sucesso." << endl; } else{ cout << "Conjunto não criado, capacidade para criação de novos conjuntos excedida." << endl; } break; } case 2:{ cout << "Informe qual conjunto você deseja excluir: " << endl; int number; cin >> number; if(number > 0 && number <= contConjuntos){ delete bancoConjuntos[number-1]; for(int i=number-1+1; i < contConjuntos; i++){ bancoConjuntos[i-1] = bancoConjuntos[i]; } contConjuntos--; cout << "Conjunto deletado com sucesso." << endl; } else{ cout << "O conjunto informado não existe." << endl; } break; } case 3:{ cout << "Informe em qual conjunto deseja fazer a inserção do elemento:" << endl; int number; cin >> number; if(number > 0 && number <= contConjuntos){ cout << "Informe o elemento que deseja inserir no conjunto:" << endl; int elem; cin >> elem; Elemento e; e.unidadeConj = elem; if(bancoConjuntos[number-1]->insere(e)){ cout << "Elemento inserido com sucesso." << endl; break; } else{ cout << "Impossível realizar inserção, o elemento já está no conjunto." << endl; break; } } else{ cout << "O conjunto informado não existe." << endl; } break; } case 4:{ cout << "Informe respectivamente dois conjuntos que deseja realizar a união entre eles:" << endl; int c1, c2; cin >> c1 >> c2; if(c1 > 0 && c2 > 0 && c1 <= contConjuntos && c2 <= contConjuntos){ if(contConjuntos < tam){ bancoConjuntos[contConjuntos] = new Conjunto(); contConjuntos++; Conjunto::uniao(bancoConjuntos[c1-1], bancoConjuntos[c2-1], bancoConjuntos[contConjuntos-1]); cout << "Conjunto da união criado e salvo com sucesso." << endl; } else{ cout << "Impossível realizar união, capacidade de conjuntos que podem ser criados foi exedida." << endl; } break; } else{ cout <<"Erro: O Conjunto informado não existe." << endl; } break; } case 5:{ cout << "Informe qual conjunto deseja copiar:" << endl; int c; cin >> c; if(c > 0 && c <= contConjuntos){ if(contConjuntos < tam){ bancoConjuntos[contConjuntos] = new Conjunto(); contConjuntos++; bancoConjuntos[c-1]->copia(bancoConjuntos[c-1], bancoConjuntos[contConjuntos-1]); cout << "Cópia ralizada com sucesso." << endl; break; } else{ cout << "Impossível realizar união, capacidade de conjuntos que podem ser criados exedida." << endl; break; } } else{ cout << "O conjunto informado não existe." << endl; } break; } case 6:{ cout << "Informe respectivamente dois conjuntos que deseja criar o conjunto intersecção entre eles:" << endl; int c1, c2; cin >> c1 >> c2; if(c1 > 0 && c2 > 0 && c1 <= contConjuntos && c2 <= contConjuntos){ if(contConjuntos < tam){ bancoConjuntos[contConjuntos] = new Conjunto(); contConjuntos++; Conjunto::interseccao(bancoConjuntos[c1-1], bancoConjuntos[c2-1], bancoConjuntos[contConjuntos-1]); cout << "Conjunto da intersecção criado e salvo com sucesso." << endl; } else{ cout << "Impossível realizar intersecção, capacidade de conjuntos que podem ser criados foi exedida." << endl; } break; } else{ cout << "Erro: O conjunto informado não existe." << endl; } break; } case 7:{ cout << "Informe respectivamente dois conjuntos que deseja criar o conjunto da diferença entre eles:" << endl; int c1, c2; cin >> c1 >> c2; if(c1 > 0 && c2 > 0 && c1 <= contConjuntos && c2 <= contConjuntos){ if(contConjuntos < tam){ bancoConjuntos[contConjuntos] = new Conjunto(); contConjuntos++; Conjunto::diferenca(bancoConjuntos[c1-1], bancoConjuntos[c2-1], bancoConjuntos[contConjuntos-1]); cout << "Conjunto da diferença criado e salvo com sucesso." << endl; } else{ cout << "Impossível realizar diferença, capacidade de conjuntos que podem ser criados foi exedida." << endl; } break; } else{ cout << "Erro: O Conjunto informado não existe." << endl; } break; } case 8:{ cout << "Informe respectivamente os conjuntos que deseja criar o conjunto da diferença simétrica entre eles:" << endl; int c1, c2; cin >> c1 >> c2; if(c1 > 0 && c2 > 0 && c1 <= contConjuntos && c2 <= contConjuntos){ if(contConjuntos < tam){ bancoConjuntos[contConjuntos] = new Conjunto(); contConjuntos++; Conjunto::diferencaSimetrica(bancoConjuntos[c1-1], bancoConjuntos[c2-1], bancoConjuntos[contConjuntos-1]); cout << "Conjunto da diferença simétrica criado e salvo com sucesso." << endl; } else{ cout << "Impossível realizar diferença simétrica, capacidade de conjuntos que podem ser criados foi exedida." << endl; } break; } else{ cout << "Erro: O Conjunto informado não existe." << endl; } break; } case 9:{ cout << "Informe de qual conjunto deseja remover um elemento:" << endl; int c; cin >> c; if(c > 0 && c <= contConjuntos){ cout << "Informe qual elemento deseja remover do conjunto:" << endl; int elem; cin >> elem; Elemento e; e.unidadeConj = elem; if(Conjunto::remove(e, bancoConjuntos[c-1])) cout << "Elemento removido com sucesso." << endl; else cout << "Remoção não realizada, o elemento informado não está no conjunto." << endl; } else{ cout << "O conjunto informado não existe." << endl; } break; } case 10:{ cout << "Informe de qual conjunto deseja obter seu maior elemento:" << endl; int c; cin >> c; if(c > 0 && c <= contConjuntos){ if(bancoConjuntos[c-1]->getTamanho() > 0){ cout << "O maior elemento desse conjunto é: " << Conjunto::max(bancoConjuntos[c-1]) << endl; } else{ cout << "Este conjunto está vazio." << endl; } } else{ cout << "O conjunto informado não existe." << endl; } break; } case 11:{ cout << "Informe de qual conjunto deseja obter seu menor elemento:" << endl; int c; cin >> c; if(c > 0 && c <= contConjuntos){ if(bancoConjuntos[c-1]->getTamanho() > 0){ cout << "O menor elemento desse conjunto é: " << Conjunto::min(bancoConjuntos[c-1]) << endl; } else{ cout << "Este conjunto está vazio." << endl; } } else{ cout << "O conjunto informado não existe." << endl; } break; } case 12:{ cout << "Informe respectivamente dois conjuntos que deseja saber se são, ou não, iguais entre si:" << endl; int c1, c2; cin >> c1 >> c2; if(c1 > 0 && c2 > 0 && c1 <= contConjuntos && c2 <= contConjuntos){ if(Conjunto::iguais(bancoConjuntos[c1-1], bancoConjuntos[c2-1])) cout << "Conjuntos iguais." << endl; else cout << "Conjuntos diferentes." << endl; } else{ cout << "O conjunto informado não existe." << endl; } break; } case 13:{ for(int i=0; i < contConjuntos; i++){ delete bancoConjuntos[i]; } cout << "Memórias desalocadas. Programa fechando." << endl; break; } default: cout << "Opção inválida" << endl; break; } } return 0; }
[ "robertsonascimento99@gmail.com" ]
robertsonascimento99@gmail.com
59b7eeff0cbe3fe478e236c3a6885ac270f10177
71501709864eff17c873abbb97ffabbeba4cb5e3
/llvm8.0.0/clang-tools-extra/include-fixer/SymbolIndexManager.cpp
e4312bf166bfd374db3729ba071762d77740f8cf
[ "NCSA" ]
permissive
LEA0317/LLVM-VideoCore4
d08ba6e6f26f7893709d3285bdbd67442b3e1651
7ae2304339760685e8b5556aacc7e9eee91de05c
refs/heads/master
2022-06-22T15:15:52.112867
2022-06-09T08:45:24
2022-06-09T08:45:24
189,765,789
1
0
NOASSERTION
2019-06-01T18:31:29
2019-06-01T18:31:29
null
UTF-8
C++
false
false
6,212
cpp
//===-- SymbolIndexManager.cpp - Managing multiple SymbolIndices-*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SymbolIndexManager.h" #include "find-all-symbols/SymbolInfo.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Path.h" #define DEBUG_TYPE "include-fixer" namespace clang { namespace include_fixer { using find_all_symbols::SymbolInfo; using find_all_symbols::SymbolAndSignals; // Calculate a score based on whether we think the given header is closely // related to the given source file. static double similarityScore(llvm::StringRef FileName, llvm::StringRef Header) { // Compute the maximum number of common path segements between Header and // a suffix of FileName. // We do not do a full longest common substring computation, as Header // specifies the path we would directly #include, so we assume it is rooted // relatively to a subproject of the repository. int MaxSegments = 1; for (auto FileI = llvm::sys::path::begin(FileName), FileE = llvm::sys::path::end(FileName); FileI != FileE; ++FileI) { int Segments = 0; for (auto HeaderI = llvm::sys::path::begin(Header), HeaderE = llvm::sys::path::end(Header), I = FileI; HeaderI != HeaderE && *I == *HeaderI && I != FileE; ++I, ++HeaderI) { ++Segments; } MaxSegments = std::max(Segments, MaxSegments); } return MaxSegments; } static void rank(std::vector<SymbolAndSignals> &Symbols, llvm::StringRef FileName) { llvm::DenseMap<llvm::StringRef, double> Score; for (const auto &Symbol : Symbols) { // Calculate a score from the similarity of the header the symbol is in // with the current file and the popularity of the symbol. double NewScore = similarityScore(FileName, Symbol.Symbol.getFilePath()) * (1.0 + std::log2(1 + Symbol.Signals.Seen)); double &S = Score[Symbol.Symbol.getFilePath()]; S = std::max(S, NewScore); } // Sort by the gathered scores. Use file name as a tie breaker so we can // deduplicate. std::sort(Symbols.begin(), Symbols.end(), [&](const SymbolAndSignals &A, const SymbolAndSignals &B) { auto AS = Score[A.Symbol.getFilePath()]; auto BS = Score[B.Symbol.getFilePath()]; if (AS != BS) return AS > BS; return A.Symbol.getFilePath() < B.Symbol.getFilePath(); }); } std::vector<find_all_symbols::SymbolInfo> SymbolIndexManager::search(llvm::StringRef Identifier, bool IsNestedSearch, llvm::StringRef FileName) const { // The identifier may be fully qualified, so split it and get all the context // names. llvm::SmallVector<llvm::StringRef, 8> Names; Identifier.split(Names, "::"); bool IsFullyQualified = false; if (Identifier.startswith("::")) { Names.erase(Names.begin()); // Drop first (empty) element. IsFullyQualified = true; } // As long as we don't find a result keep stripping name parts from the end. // This is to support nested classes which aren't recorded in the database. // Eventually we will either hit a class (namespaces aren't in the database // either) and can report that result. bool TookPrefix = false; std::vector<SymbolAndSignals> MatchedSymbols; do { std::vector<SymbolAndSignals> Symbols; for (const auto &DB : SymbolIndices) { auto Res = DB.get()->search(Names.back()); Symbols.insert(Symbols.end(), Res.begin(), Res.end()); } LLVM_DEBUG(llvm::dbgs() << "Searching " << Names.back() << "... got " << Symbols.size() << " results...\n"); for (auto &SymAndSig : Symbols) { const SymbolInfo &Symbol = SymAndSig.Symbol; // Match the identifier name without qualifier. bool IsMatched = true; auto SymbolContext = Symbol.getContexts().begin(); auto IdentiferContext = Names.rbegin() + 1; // Skip identifier name. // Match the remaining context names. while (IdentiferContext != Names.rend() && SymbolContext != Symbol.getContexts().end()) { if (SymbolContext->second == *IdentiferContext) { ++IdentiferContext; ++SymbolContext; } else if (SymbolContext->first == find_all_symbols::SymbolInfo::ContextType::EnumDecl) { // Skip non-scoped enum context. ++SymbolContext; } else { IsMatched = false; break; } } // If the name was qualified we only want to add results if we evaluated // all contexts. if (IsFullyQualified) IsMatched &= (SymbolContext == Symbol.getContexts().end()); // FIXME: Support full match. At this point, we only find symbols in // database which end with the same contexts with the identifier. if (IsMatched && IdentiferContext == Names.rend()) { // If we're in a situation where we took a prefix but the thing we // found couldn't possibly have a nested member ignore it. if (TookPrefix && (Symbol.getSymbolKind() == SymbolInfo::SymbolKind::Function || Symbol.getSymbolKind() == SymbolInfo::SymbolKind::Variable || Symbol.getSymbolKind() == SymbolInfo::SymbolKind::EnumConstantDecl || Symbol.getSymbolKind() == SymbolInfo::SymbolKind::Macro)) continue; MatchedSymbols.push_back(std::move(SymAndSig)); } } Names.pop_back(); TookPrefix = true; } while (MatchedSymbols.empty() && !Names.empty() && IsNestedSearch); rank(MatchedSymbols, FileName); // Strip signals, they are no longer needed. std::vector<SymbolInfo> Res; for (auto &SymAndSig : MatchedSymbols) Res.push_back(std::move(SymAndSig.Symbol)); return Res; } } // namespace include_fixer } // namespace clang
[ "kontoshi0317@gmail.com" ]
kontoshi0317@gmail.com
f54705b3fc5683261983da6d4d2b035dcbff51df
dffa22967839eabc7216a5fe5a5560fd06ac3ebd
/topcoder/450_practice/OrderedNim.cpp
f26d6082a0f1b24e9f0beb5d1ca4e2c675748a3f
[]
no_license
adityasinghhh/coding
a4d7d69615b98c909fbaf8555104ddeab2e73738
f62297228da0d6331d9a993c8ca86e87df1aae65
refs/heads/master
2021-06-02T17:17:07.122212
2018-02-07T04:46:51
2018-02-07T04:46:51
10,299,145
0
1
null
2017-12-06T14:49:17
2013-05-26T14:49:44
C++
UTF-8
C++
false
false
5,377
cpp
#include<algorithm> #include<assert.h> #include<climits> #include<cmath> #include<cstdio> #include<cstdlib> #include<cstring> #include<deque> #include<iostream> #include<map> #include<memory.h> #include<queue> #include<set> #include<stack> #include<string> #include<utility> #include<vector> using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef pair<int,int> PI; #define LL long long int #define SI ({int _x; scanf("%d",&_x); _x;}) #define SC ({char _x; scanf("%c",&_x); _x;}) #define SLL ({LL _x; scanf("%lld",&_x); _x;}) #define SLF ({double _x; scanf("%lf",&_x); _x;}) #define lc(i) (i<<1) #define rc(i) ((i<<1)+1) #define iscan(n) scanf("%d",&n) #define cscan(n) scanf("%c",&n) #define llscan(n) scanf("%lld",&n) #define lfscan(n) scanf("%lf",&n) #define sscan(n) scanf("%s",n) #define FOR(i,a,b) for(int i=a;i<b;++i) #define FORD(i,a,b) for(int i=b-1;i>=a;--i) #define REP(i,b) for(int i=0;i<b;++i) #define REPD(i,b) for(int i=b-1;i>=0;--i) #define MP(a,b) make_pair(a,b) #define PB(a) push_back(a) #define FILL(a,b) memset(a,b,sizeof a) #define MAX(a,b) ((a)>(b)?(a):(b)) #define MIN(a,b) ((a)<(b)?(a):(b)) #define ABS(a) ((a)<0?-(a):(a)) #define ALL(a) a.begin(),a.end() #define SORT(a) sort(ALL(a)) #define TR(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) class OrderedNim { public: string winner(vector <int>); }; string OrderedNim::winner(vector <int> v) { int sz = v.size(); if(sz == 1) { return "Alice"; } string win = winner(vector<int> (v.begin()+1, v.end())); if(win == "Alice") { if(v[0] == 1) { return "Bob"; } else { return "Alice"; } } else { return "Alice"; } } double test0() { int t0[] = {5}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); OrderedNim * obj = new OrderedNim(); clock_t start = clock(); string my_answer = obj->winner(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; string p1 = "Alice"; cout <<"Desired answer: " <<endl; cout <<"\t\"" << p1 <<"\"" <<endl; cout <<"Your answer: " <<endl; cout <<"\t\"" << my_answer<<"\"" <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } double test1() { int t0[] = {1,2}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); OrderedNim * obj = new OrderedNim(); clock_t start = clock(); string my_answer = obj->winner(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; string p1 = "Bob"; cout <<"Desired answer: " <<endl; cout <<"\t\"" << p1 <<"\"" <<endl; cout <<"Your answer: " <<endl; cout <<"\t\"" << my_answer<<"\"" <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } double test2() { int t0[] = {2,1}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); OrderedNim * obj = new OrderedNim(); clock_t start = clock(); string my_answer = obj->winner(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; string p1 = "Alice"; cout <<"Desired answer: " <<endl; cout <<"\t\"" << p1 <<"\"" <<endl; cout <<"Your answer: " <<endl; cout <<"\t\"" << my_answer<<"\"" <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } double test3() { int t0[] = {10,9,8,7,6,5,4,3,2,1}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); OrderedNim * obj = new OrderedNim(); clock_t start = clock(); string my_answer = obj->winner(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; string p1 = "Alice"; cout <<"Desired answer: " <<endl; cout <<"\t\"" << p1 <<"\"" <<endl; cout <<"Your answer: " <<endl; cout <<"\t\"" << my_answer<<"\"" <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } double test4() { int t0[] = {1,1,1,1}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); OrderedNim * obj = new OrderedNim(); clock_t start = clock(); string my_answer = obj->winner(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; string p1 = "Bob"; cout <<"Desired answer: " <<endl; cout <<"\t\"" << p1 <<"\"" <<endl; cout <<"Your answer: " <<endl; cout <<"\t\"" << my_answer<<"\"" <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } int main() { int time; bool errors = false; time = test0(); if (time < 0) errors = true; time = test1(); if (time < 0) errors = true; time = test2(); if (time < 0) errors = true; time = test3(); if (time < 0) errors = true; time = test4(); if (time < 0) errors = true; if (!errors) cout <<"You're a stud (at least on the example cases)!" <<endl; else cout <<"Some of the test cases had errors." <<endl; } //Powered by [KawigiEdit] 2.0!
[ "adityasinghhh@gmail.com" ]
adityasinghhh@gmail.com
6632b418cef2c472850bf3a678ab771fa6183c92
1736988b9f920cb33481574b6ae720915a4a92b5
/Silent Classroom.cpp
5cbbd732dcf913e62f821a5ee230b241bbd40166
[]
no_license
abhisheksingh24/random_codes_i_ever_wrote
03d91fca88c3ca02ad260fb2191b1c796ca68ae9
176a1b6af49fb40ec29dfc8000eea19fc7f81234
refs/heads/master
2022-11-13T11:22:45.668479
2020-07-03T15:25:28
2020-07-03T15:25:28
276,584,215
0
0
null
null
null
null
UTF-8
C++
false
false
471
cpp
#include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<int> cnt(26); for(int i = 0; i < n; i++){ string s; cin >> s; cnt[s[0] - 'a']++; } int res = 0; for(int i: cnt){ int j = i / 2, k = (i + 1) / 2; res += ((j * (j - 1)) / 2); res += ((k * (k - 1)) / 2); } cout << res << endl; }
[ "abhisheksingh_24@rediffmail.com" ]
abhisheksingh_24@rediffmail.com
209c021e978c8df0e3b9fb6c4a4fe89e97fe98a7
1fee6477804f3ade3be2535b3ace49591862f9ed
/bomberman/bomberman/WallWithBombBiggerDist.cpp
bebb938b82736373595d45113d6ab1fd3a75fbbd
[]
no_license
monkok96/study
7109b008b287f88da521d2f88d181ba0a3e15bbe
a574b921b2fea1f2dee0c36ae00e2741a48b0ecc
refs/heads/master
2021-04-27T20:44:07.534735
2018-07-11T20:30:51
2018-07-11T20:30:51
122,384,826
0
0
null
null
null
null
UTF-8
C++
false
false
705
cpp
#include "WallWithBombBiggerDist.h" #include "BombBiggerDist.h" #include "GetOut.h" WallWithBombBiggerDist::WallWithBombBiggerDist(const sf::Vector2f& elem_size, const sf::Vector2f& position) : DynamicWall(elem_size,position) { } bool WallWithBombBiggerDist::PlayerAction(Player &player, sf::RenderWindow &window, std::unique_ptr<BoardElem> &elem) { return true; } void WallWithBombBiggerDist::ReactionToABomb(std::unique_ptr<BoardElem> &elem, unsigned int &count_elems) { if (--count_elems == 0) elem = std::make_unique<GetOut>(elem->GetElem().getSize(), elem->GetElem().getPosition()); else elem = std::make_unique<BombBiggerDist>(elem->GetElem().getSize(), elem->GetElem().getPosition()); }
[ "monikakokot96@gmail.com" ]
monikakokot96@gmail.com
e660a7954700739dcec21d7a69a680c6290ca337
9da42e04bdaebdf0193a78749a80c4e7bf76a6cc
/third_party/gecko-10/win32/include/mozIAsyncHistory.h
c9113d98d572dbc3f783acfdc07f5fbd67ae5ffb
[ "Apache-2.0" ]
permissive
bwp/SeleniumWebDriver
9d49e6069881845e9c23fb5211a7e1b8959e2dcf
58221fbe59fcbbde9d9a033a95d45d576b422747
refs/heads/master
2021-01-22T21:32:50.541163
2012-11-09T16:19:48
2012-11-09T16:19:48
6,602,097
1
0
null
null
null
null
UTF-8
C++
false
false
15,320
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/toolkit/components/places/mozIAsyncHistory.idl */ #ifndef __gen_mozIAsyncHistory_h__ #define __gen_mozIAsyncHistory_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif #include "jspubtd.h" /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIURI; /* forward declaration */ class nsIVariant; /* forward declaration */ #include "jsapi.h" /* starting interface: mozIVisitInfo */ #define MOZIVISITINFO_IID_STR "1a3b1260-4bdb-45d0-a306-dc377dd9baa4" #define MOZIVISITINFO_IID \ {0x1a3b1260, 0x4bdb, 0x45d0, \ { 0xa3, 0x06, 0xdc, 0x37, 0x7d, 0xd9, 0xba, 0xa4 }} class NS_NO_VTABLE NS_SCRIPTABLE mozIVisitInfo : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(MOZIVISITINFO_IID) /* readonly attribute long long visitId; */ NS_SCRIPTABLE NS_IMETHOD GetVisitId(PRInt64 *aVisitId) = 0; /* readonly attribute PRTime visitDate; */ NS_SCRIPTABLE NS_IMETHOD GetVisitDate(PRTime *aVisitDate) = 0; /* readonly attribute unsigned long transitionType; */ NS_SCRIPTABLE NS_IMETHOD GetTransitionType(PRUint32 *aTransitionType) = 0; /* readonly attribute nsIURI referrerURI; */ NS_SCRIPTABLE NS_IMETHOD GetReferrerURI(nsIURI * *aReferrerURI) = 0; /* readonly attribute long long sessionId; */ NS_SCRIPTABLE NS_IMETHOD GetSessionId(PRInt64 *aSessionId) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(mozIVisitInfo, MOZIVISITINFO_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_MOZIVISITINFO \ NS_SCRIPTABLE NS_IMETHOD GetVisitId(PRInt64 *aVisitId); \ NS_SCRIPTABLE NS_IMETHOD GetVisitDate(PRTime *aVisitDate); \ NS_SCRIPTABLE NS_IMETHOD GetTransitionType(PRUint32 *aTransitionType); \ NS_SCRIPTABLE NS_IMETHOD GetReferrerURI(nsIURI * *aReferrerURI); \ NS_SCRIPTABLE NS_IMETHOD GetSessionId(PRInt64 *aSessionId); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_MOZIVISITINFO(_to) \ NS_SCRIPTABLE NS_IMETHOD GetVisitId(PRInt64 *aVisitId) { return _to GetVisitId(aVisitId); } \ NS_SCRIPTABLE NS_IMETHOD GetVisitDate(PRTime *aVisitDate) { return _to GetVisitDate(aVisitDate); } \ NS_SCRIPTABLE NS_IMETHOD GetTransitionType(PRUint32 *aTransitionType) { return _to GetTransitionType(aTransitionType); } \ NS_SCRIPTABLE NS_IMETHOD GetReferrerURI(nsIURI * *aReferrerURI) { return _to GetReferrerURI(aReferrerURI); } \ NS_SCRIPTABLE NS_IMETHOD GetSessionId(PRInt64 *aSessionId) { return _to GetSessionId(aSessionId); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_MOZIVISITINFO(_to) \ NS_SCRIPTABLE NS_IMETHOD GetVisitId(PRInt64 *aVisitId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetVisitId(aVisitId); } \ NS_SCRIPTABLE NS_IMETHOD GetVisitDate(PRTime *aVisitDate) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetVisitDate(aVisitDate); } \ NS_SCRIPTABLE NS_IMETHOD GetTransitionType(PRUint32 *aTransitionType) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTransitionType(aTransitionType); } \ NS_SCRIPTABLE NS_IMETHOD GetReferrerURI(nsIURI * *aReferrerURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetReferrerURI(aReferrerURI); } \ NS_SCRIPTABLE NS_IMETHOD GetSessionId(PRInt64 *aSessionId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSessionId(aSessionId); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class _MYCLASS_ : public mozIVisitInfo { public: NS_DECL_ISUPPORTS NS_DECL_MOZIVISITINFO _MYCLASS_(); private: ~_MYCLASS_(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(_MYCLASS_, mozIVisitInfo) _MYCLASS_::_MYCLASS_() { /* member initializers and constructor code */ } _MYCLASS_::~_MYCLASS_() { /* destructor code */ } /* readonly attribute long long visitId; */ NS_IMETHODIMP _MYCLASS_::GetVisitId(PRInt64 *aVisitId) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute PRTime visitDate; */ NS_IMETHODIMP _MYCLASS_::GetVisitDate(PRTime *aVisitDate) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long transitionType; */ NS_IMETHODIMP _MYCLASS_::GetTransitionType(PRUint32 *aTransitionType) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIURI referrerURI; */ NS_IMETHODIMP _MYCLASS_::GetReferrerURI(nsIURI * *aReferrerURI) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long long sessionId; */ NS_IMETHODIMP _MYCLASS_::GetSessionId(PRInt64 *aSessionId) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: mozIPlaceInfo */ #define MOZIPLACEINFO_IID_STR "ad83e137-c92a-4b7b-b67e-0a318811f91e" #define MOZIPLACEINFO_IID \ {0xad83e137, 0xc92a, 0x4b7b, \ { 0xb6, 0x7e, 0x0a, 0x31, 0x88, 0x11, 0xf9, 0x1e }} class NS_NO_VTABLE NS_SCRIPTABLE mozIPlaceInfo : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(MOZIPLACEINFO_IID) /* readonly attribute long long placeId; */ NS_SCRIPTABLE NS_IMETHOD GetPlaceId(PRInt64 *aPlaceId) = 0; /* readonly attribute ACString guid; */ NS_SCRIPTABLE NS_IMETHOD GetGuid(nsACString & aGuid) = 0; /* readonly attribute nsIURI uri; */ NS_SCRIPTABLE NS_IMETHOD GetUri(nsIURI * *aUri) = 0; /* readonly attribute AString title; */ NS_SCRIPTABLE NS_IMETHOD GetTitle(nsAString & aTitle) = 0; /* readonly attribute long long frecency; */ NS_SCRIPTABLE NS_IMETHOD GetFrecency(PRInt64 *aFrecency) = 0; /* [implicit_jscontext] readonly attribute jsval visits; */ NS_SCRIPTABLE NS_IMETHOD GetVisits(JSContext* cx, JS::Value *aVisits) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(mozIPlaceInfo, MOZIPLACEINFO_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_MOZIPLACEINFO \ NS_SCRIPTABLE NS_IMETHOD GetPlaceId(PRInt64 *aPlaceId); \ NS_SCRIPTABLE NS_IMETHOD GetGuid(nsACString & aGuid); \ NS_SCRIPTABLE NS_IMETHOD GetUri(nsIURI * *aUri); \ NS_SCRIPTABLE NS_IMETHOD GetTitle(nsAString & aTitle); \ NS_SCRIPTABLE NS_IMETHOD GetFrecency(PRInt64 *aFrecency); \ NS_SCRIPTABLE NS_IMETHOD GetVisits(JSContext* cx, JS::Value *aVisits); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_MOZIPLACEINFO(_to) \ NS_SCRIPTABLE NS_IMETHOD GetPlaceId(PRInt64 *aPlaceId) { return _to GetPlaceId(aPlaceId); } \ NS_SCRIPTABLE NS_IMETHOD GetGuid(nsACString & aGuid) { return _to GetGuid(aGuid); } \ NS_SCRIPTABLE NS_IMETHOD GetUri(nsIURI * *aUri) { return _to GetUri(aUri); } \ NS_SCRIPTABLE NS_IMETHOD GetTitle(nsAString & aTitle) { return _to GetTitle(aTitle); } \ NS_SCRIPTABLE NS_IMETHOD GetFrecency(PRInt64 *aFrecency) { return _to GetFrecency(aFrecency); } \ NS_SCRIPTABLE NS_IMETHOD GetVisits(JSContext* cx, JS::Value *aVisits) { return _to GetVisits(cx, aVisits); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_MOZIPLACEINFO(_to) \ NS_SCRIPTABLE NS_IMETHOD GetPlaceId(PRInt64 *aPlaceId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPlaceId(aPlaceId); } \ NS_SCRIPTABLE NS_IMETHOD GetGuid(nsACString & aGuid) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetGuid(aGuid); } \ NS_SCRIPTABLE NS_IMETHOD GetUri(nsIURI * *aUri) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUri(aUri); } \ NS_SCRIPTABLE NS_IMETHOD GetTitle(nsAString & aTitle) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTitle(aTitle); } \ NS_SCRIPTABLE NS_IMETHOD GetFrecency(PRInt64 *aFrecency) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFrecency(aFrecency); } \ NS_SCRIPTABLE NS_IMETHOD GetVisits(JSContext* cx, JS::Value *aVisits) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetVisits(cx, aVisits); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class _MYCLASS_ : public mozIPlaceInfo { public: NS_DECL_ISUPPORTS NS_DECL_MOZIPLACEINFO _MYCLASS_(); private: ~_MYCLASS_(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(_MYCLASS_, mozIPlaceInfo) _MYCLASS_::_MYCLASS_() { /* member initializers and constructor code */ } _MYCLASS_::~_MYCLASS_() { /* destructor code */ } /* readonly attribute long long placeId; */ NS_IMETHODIMP _MYCLASS_::GetPlaceId(PRInt64 *aPlaceId) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute ACString guid; */ NS_IMETHODIMP _MYCLASS_::GetGuid(nsACString & aGuid) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIURI uri; */ NS_IMETHODIMP _MYCLASS_::GetUri(nsIURI * *aUri) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AString title; */ NS_IMETHODIMP _MYCLASS_::GetTitle(nsAString & aTitle) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long long frecency; */ NS_IMETHODIMP _MYCLASS_::GetFrecency(PRInt64 *aFrecency) { return NS_ERROR_NOT_IMPLEMENTED; } /* [implicit_jscontext] readonly attribute jsval visits; */ NS_IMETHODIMP _MYCLASS_::GetVisits(JSContext* cx, JS::Value *aVisits) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: mozIVisitInfoCallback */ #define MOZIVISITINFOCALLBACK_IID_STR "1f266877-2859-418b-a11b-ec3ae4f4f93d" #define MOZIVISITINFOCALLBACK_IID \ {0x1f266877, 0x2859, 0x418b, \ { 0xa1, 0x1b, 0xec, 0x3a, 0xe4, 0xf4, 0xf9, 0x3d }} class NS_NO_VTABLE NS_SCRIPTABLE mozIVisitInfoCallback : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(MOZIVISITINFOCALLBACK_IID) /* void handleError (in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo); */ NS_SCRIPTABLE NS_IMETHOD HandleError(nsresult aResultCode, mozIPlaceInfo *aPlaceInfo) = 0; /* void handleResult (in mozIPlaceInfo aPlaceInfo); */ NS_SCRIPTABLE NS_IMETHOD HandleResult(mozIPlaceInfo *aPlaceInfo) = 0; /* void handleCompletion (); */ NS_SCRIPTABLE NS_IMETHOD HandleCompletion(void) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(mozIVisitInfoCallback, MOZIVISITINFOCALLBACK_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_MOZIVISITINFOCALLBACK \ NS_SCRIPTABLE NS_IMETHOD HandleError(nsresult aResultCode, mozIPlaceInfo *aPlaceInfo); \ NS_SCRIPTABLE NS_IMETHOD HandleResult(mozIPlaceInfo *aPlaceInfo); \ NS_SCRIPTABLE NS_IMETHOD HandleCompletion(void); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_MOZIVISITINFOCALLBACK(_to) \ NS_SCRIPTABLE NS_IMETHOD HandleError(nsresult aResultCode, mozIPlaceInfo *aPlaceInfo) { return _to HandleError(aResultCode, aPlaceInfo); } \ NS_SCRIPTABLE NS_IMETHOD HandleResult(mozIPlaceInfo *aPlaceInfo) { return _to HandleResult(aPlaceInfo); } \ NS_SCRIPTABLE NS_IMETHOD HandleCompletion(void) { return _to HandleCompletion(); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_MOZIVISITINFOCALLBACK(_to) \ NS_SCRIPTABLE NS_IMETHOD HandleError(nsresult aResultCode, mozIPlaceInfo *aPlaceInfo) { return !_to ? NS_ERROR_NULL_POINTER : _to->HandleError(aResultCode, aPlaceInfo); } \ NS_SCRIPTABLE NS_IMETHOD HandleResult(mozIPlaceInfo *aPlaceInfo) { return !_to ? NS_ERROR_NULL_POINTER : _to->HandleResult(aPlaceInfo); } \ NS_SCRIPTABLE NS_IMETHOD HandleCompletion(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->HandleCompletion(); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class _MYCLASS_ : public mozIVisitInfoCallback { public: NS_DECL_ISUPPORTS NS_DECL_MOZIVISITINFOCALLBACK _MYCLASS_(); private: ~_MYCLASS_(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(_MYCLASS_, mozIVisitInfoCallback) _MYCLASS_::_MYCLASS_() { /* member initializers and constructor code */ } _MYCLASS_::~_MYCLASS_() { /* destructor code */ } /* void handleError (in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo); */ NS_IMETHODIMP _MYCLASS_::HandleError(nsresult aResultCode, mozIPlaceInfo *aPlaceInfo) { return NS_ERROR_NOT_IMPLEMENTED; } /* void handleResult (in mozIPlaceInfo aPlaceInfo); */ NS_IMETHODIMP _MYCLASS_::HandleResult(mozIPlaceInfo *aPlaceInfo) { return NS_ERROR_NOT_IMPLEMENTED; } /* void handleCompletion (); */ NS_IMETHODIMP _MYCLASS_::HandleCompletion() { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: mozIAsyncHistory */ #define MOZIASYNCHISTORY_IID_STR "f79ca67c-7e57-4511-a400-ea31001c762f" #define MOZIASYNCHISTORY_IID \ {0xf79ca67c, 0x7e57, 0x4511, \ { 0xa4, 0x00, 0xea, 0x31, 0x00, 0x1c, 0x76, 0x2f }} class NS_NO_VTABLE NS_SCRIPTABLE mozIAsyncHistory : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(MOZIASYNCHISTORY_IID) /* [implicit_jscontext] void updatePlaces (in jsval aPlaceInfo, [optional] in mozIVisitInfoCallback aCallback); */ NS_SCRIPTABLE NS_IMETHOD UpdatePlaces(const JS::Value & aPlaceInfo, mozIVisitInfoCallback *aCallback, JSContext* cx) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(mozIAsyncHistory, MOZIASYNCHISTORY_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_MOZIASYNCHISTORY \ NS_SCRIPTABLE NS_IMETHOD UpdatePlaces(const JS::Value & aPlaceInfo, mozIVisitInfoCallback *aCallback, JSContext* cx); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_MOZIASYNCHISTORY(_to) \ NS_SCRIPTABLE NS_IMETHOD UpdatePlaces(const JS::Value & aPlaceInfo, mozIVisitInfoCallback *aCallback, JSContext* cx) { return _to UpdatePlaces(aPlaceInfo, aCallback, cx); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_MOZIASYNCHISTORY(_to) \ NS_SCRIPTABLE NS_IMETHOD UpdatePlaces(const JS::Value & aPlaceInfo, mozIVisitInfoCallback *aCallback, JSContext* cx) { return !_to ? NS_ERROR_NULL_POINTER : _to->UpdatePlaces(aPlaceInfo, aCallback, cx); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class _MYCLASS_ : public mozIAsyncHistory { public: NS_DECL_ISUPPORTS NS_DECL_MOZIASYNCHISTORY _MYCLASS_(); private: ~_MYCLASS_(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(_MYCLASS_, mozIAsyncHistory) _MYCLASS_::_MYCLASS_() { /* member initializers and constructor code */ } _MYCLASS_::~_MYCLASS_() { /* destructor code */ } /* [implicit_jscontext] void updatePlaces (in jsval aPlaceInfo, [optional] in mozIVisitInfoCallback aCallback); */ NS_IMETHODIMP _MYCLASS_::UpdatePlaces(const JS::Value & aPlaceInfo, mozIVisitInfoCallback *aCallback, JSContext* cx) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_mozIAsyncHistory_h__ */
[ "haleokekahuna@gmail.com" ]
haleokekahuna@gmail.com
312aafc2802f13e30436eed270c1399aa97785e2
44ea78720cf1fbbbb57a204d462f08ef8ccb7c42
/ABC/ABC047/B/main.cpp
01db54a0f4c399f88fe28b722dce4db9c9b85f5c
[]
no_license
kironbot/AtCoder
854a85d55e2d3c0c8ef76589ad905af20d9c567d
4c05bf806413f5c601baa7432b9d85b102ba34b7
refs/heads/master
2021-06-29T16:14:47.667960
2020-09-27T06:17:02
2020-09-27T06:17:02
138,470,049
0
0
null
null
null
null
UTF-8
C++
false
false
1,245
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <set> #include <stack> #include <deque> #include <cmath> #include <map> using ll = long long; using namespace std; int main() { int w, h, n; cin >> w >> h >> n; int x[n], y[n], a[n]; for (int i = 0; i < n; i++) cin >> x[i] >> y[i] >> a[i]; int rec[w][h]; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { rec[i][j] = 1; } } for (int i = 0; i < n; i++) { if (a[i] == 1) { for (int ii = 0; ii < x[i]; ii++) { for (int jj = 0; jj < h; jj++) { rec[ii][jj] = 0; } } } if (a[i] == 2) { for (int ii = x[i]; ii < w; ii++) { for (int jj = 0; jj < h; jj++) { rec[ii][jj] = 0; } } } if (a[i] == 3) { for (int ii = 0; ii < w; ii++) { for (int jj = 0; jj < y[i]; jj++) { rec[ii][jj] = 0; } } } if (a[i] == 4) { for (int ii = 0; ii < w; ii++) { for (int jj = y[i]; jj < h; jj++) { rec[ii][jj] = 0; } } } } int ans = 0; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { ans += rec[i][j]; } } cout << ans << endl; }
[ "sgr.araki@gmail.com" ]
sgr.araki@gmail.com
46189bb175f9041758623aadb5e81aabbdf7e5a2
54b9e39a6b4b412223f234e9791a208a1368be9e
/char_in_str.cpp
4a39aabe9cee35029f928edc93561911b02afa87
[]
no_license
RKMVCC-BSc-Comp-Sci-2020-21/Programming-C-Cpp-Sem1
90272d55002c7beec1e2d542c5fe3446cd0c4719
6cda8177e95f5d368881ed52c499cc4e1a2bb680
refs/heads/main
2023-03-31T02:57:04.662744
2021-03-30T14:52:44
2021-03-30T14:52:44
315,950,354
9
35
null
2021-03-22T15:31:14
2020-11-25T13:38:49
C++
UTF-8
C++
false
false
332
cpp
#include <iostream> using namespace std; int main() { char str[100]; char c ; cout<<"Enter the String: "; cin>>str; cout<<"Enter the character: "; cin>>c; int count = 0; for(int i = 0; str[i] != '\0'; i++) { if(str[i] == c) count++; } cout<<"Number of Occurrence of "<<c<<" in the string is "<<count; return 0; }
[ "noreply@github.com" ]
RKMVCC-BSc-Comp-Sci-2020-21.noreply@github.com
050babcf29d498f4d8d2c04d90ff6fdbbf351d28
022561d46bd00e31df46e2f4e4ce8ce97946d135
/streamingMusicTest/streaming/node-v8.12.0/src/connection_wrap.h
096672efddaae218576deb3ef0cfa379366ec3fe
[ "LicenseRef-scancode-unicode", "Artistic-2.0", "NTP", "MIT", "BSD-3-Clause", "NAIST-2003", "Zlib", "ICU", "ISC", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-openssl", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "Apache-2.0", "LGPL-2.0-or-later", "GPL-...
permissive
edwardgoodnow/BetterMythTVRemote
fd44128ff32a048b1a219ee18fab3be3d5c04d82
f03afa3f3ef23c7868b78df7b2acfc2a70e7a67d
refs/heads/master
2022-12-10T15:28:51.279671
2019-05-25T21:58:23
2019-05-25T21:58:23
135,066,888
0
0
MIT
2022-12-08T14:43:35
2018-05-27T17:19:16
C++
UTF-8
C++
false
false
775
h
#ifndef SRC_CONNECTION_WRAP_H_ #define SRC_CONNECTION_WRAP_H_ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #include "env.h" #include "stream_wrap.h" #include "v8.h" namespace node { template <typename WrapType, typename UVType> class ConnectionWrap : public LibuvStreamWrap { public: UVType* UVHandle() { return &handle_; } static void OnConnection(uv_stream_t* handle, int status); static void AfterConnect(uv_connect_t* req, int status); protected: ConnectionWrap(Environment* env, v8::Local<v8::Object> object, ProviderType provider); ~ConnectionWrap() { } UVType handle_; }; } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #endif // SRC_CONNECTION_WRAP_H_
[ "edward.goodnow@gmail.com" ]
edward.goodnow@gmail.com
62cf980139de41a6441ed5396f34d57860127213
3fa65f0c711a0ba395bb1c43c89e404bb89cfef6
/peatpanel.cpp
c66e4fce282df25fbfda68457660b8320549b8b9
[]
no_license
rakeeb-hossain/PEAT_V2
6fb288761519a34796024db6d6beefe9c2edd156
a3dedd20b7fc8962ff54eb7157bce16fd8fcc1fa
refs/heads/master
2022-04-22T23:32:23.028559
2020-04-27T19:58:13
2020-04-27T19:58:13
183,953,230
1
0
null
null
null
null
UTF-8
C++
false
false
2,785
cpp
#include "peatpanel.h" #include "ui_peatpanel.h" PEATPanel::PEATPanel(QWidget *parent) : QMainWindow(parent), ui(new Ui::PEATPanel) { ui->setupUi(this); this->setWindowTitle("UW Trace Center Photosensitive Epilepsy Analysis Tool (PEAT)"); setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint); this->resize(QSize(900,580)); player = new QMediaPlayer; playlist = new QMediaPlaylist; } PEATPanel::~PEATPanel() { delete ui; } void mainFrame::on_folderButton_clicked() { QString filename = QFileDialog::getOpenFileName(this, "Open a Video File", "", "Video File (*.*)"); if(!filename.isEmpty()) { playlist->addMedia(QUrl::fromLocalFile(filename)); playlist->setCurrentIndex(1); player->setPlaylist(playlist); player->setVideoOutput(ui->videoWidget); ui->videoWidget->show(); player->play(); ui->rewindButton->setStyleSheet("#rewindButton { background-image: url(:/images/Res/FastBackUp.bmp); border-image: url(:/images/Res/FastBackUp.bmp); } #rewindButton:hover { border-image: url(:/images/Res/FastBackDownHilite.bmp); } #rewindButton:pressed { border-image: url(:/images/Res/FastBackPressed.bmp); }"); ui->playButton->setStyleSheet("#playButton { background-image: url(:/images/Res/PlayUp.bmp); border-image: url(:/images/Res/PlayUp.bmp); } #playButton:hover { border-image: url(:/images/Res/PlayDownHilite.bmp); } #playButton:pressed { border-image: url(:/images/Res/PlayPressed.bmp); }"); ui->pauseButton->setStyleSheet("#pauseButton { background-image: url(:/images/Res/StopUp.bmp); border-image: url(:/images/Res/StopUp.bmp); } #pauseButton:hover { border-image: url(:/images/Res/StopDownHilite.bmp); } #pauseButton:pressed { border-image: url(:/images/Res/StopPressed.bmp); }"); ui->forwardButton->setStyleSheet("#forwardButton { background-image: url(:/images/Res/FFwdUp.bmp); border-image: url(:/images/Res/FFwdUp.bmp); } #forwardButton:hover { border-image: url(:/images/Res/FFwdDownHilite.bmp); } #forwardButton:pressed { border-image: url(:/images/Res/FFwdPressed.bmp); }"); } else { QMessageBox messageBox; messageBox.warning(this, "Error", "Uploading file went wrong !"); messageBox.setFixedSize(500,200); } } void mainFrame::on_playButton_clicked() { player->play(); } void mainFrame::on_pauseButton_clicked() { player->pause(); } void mainFrame::on_forwardButton_clicked() { if (x < 32.0) { x = 2.0*x; rate = x; player->setPlaybackRate(rate); } } void mainFrame::on_rewindButton_clicked() { if (x > 0.03125) { x = 0.5*x; player->setPlaybackRate(x); } }
[ "sakeeb.hossain1@gmail.com" ]
sakeeb.hossain1@gmail.com
f3090a54b1c0514de80ce6cd3f29ae323852bb08
fded81a37e53d5fc31cacb9a0be86377825757b3
/buhg_g/l_uosgrbu.cpp
783d73a865d21a08be3a1aee8fc269a950949b05
[]
no_license
iceblinux/iceBw_GTK
7bf28cba9d994e95bab0f5040fea1a54a477b953
a4f76e1fee29baa7dce79e8a4a309ae98ba504c2
refs/heads/main
2023-04-02T21:45:49.500587
2021-04-12T03:51:53
2021-04-12T03:51:53
356,744,886
0
0
null
null
null
null
UTF-8
C++
false
false
23,580
cpp
/*$Id: l_uosgrbu.c,v 1.21 2013/12/31 11:49:15 sasa Exp $*/ /*08.05.2015 18.10.2007 Белых А.И. l_uosgrbu.c Работа со списком групп бухгалтерского учёта в учёте основных средств */ #include <errno.h> #include "iceb_libbuh.h" #include "l_uosgrbu.h" enum { COL_KOD, COL_NAIM, COL_PROC, COL_AR, COL_DATA_VREM, COL_KTO, NUM_COLUMNS }; enum { FK2, FK3, SFK3, FK4, FK5, FK10, SFK2, KOL_F_KL }; class l_uosgrbu_data { public: l_uosgrbu_rek poisk; iceb_u_str kodv; iceb_u_str naimv; iceb_u_str kod_podr_tv; //только что введённая единица измерения GtkWidget *label_kolstr; GtkWidget *label_poisk; GtkWidget *sw; GtkWidget *treeview; GtkWidget *window; GtkWidget *knopka[KOL_F_KL]; class iceb_u_str name_window; int kl_shift; //0-отжата 1-нажата int snanomer; //номер записи на которую надостать или -2 int kolzap; //Количество записей short metka_poi; //0-без поиска 1-с поиском int metka_voz; //0-выбрали 1-нет short metka_rr; //0-работа со списком 1-выбор //Конструктор l_uosgrbu_data() { snanomer=0; metka_rr=metka_voz=kl_shift=metka_poi=0; window=treeview=NULL; kod_podr_tv.plus(""); } }; gboolean l_uosgrbu_key_press(GtkWidget *widget,GdkEventKey *event,class l_uosgrbu_data *data); void l_uosgrbu_vibor(GtkTreeSelection *selection,class l_uosgrbu_data *data); void l_uosgrbu_v_row(GtkTreeView *treeview,GtkTreePath *arg1,GtkTreeViewColumn *arg2, class l_uosgrbu_data *data); void l_uosgrbu_knopka(GtkWidget *widget,class l_uosgrbu_data *data); void l_uosgrbu_add_columns (GtkTreeView *treeview); void l_uosgrbu_udzap(class l_uosgrbu_data *data); int l_uosgrbu_prov_row(SQL_str row,class l_uosgrbu_data *data); void l_uosgrbu_rasp(class l_uosgrbu_data *data); int l_uosgrbu_pvu(int,const char *kod,GtkWidget *wpredok); void l_uosgrbu_create_list (class l_uosgrbu_data *data); int l_uosgrbu_v(class iceb_u_str *kod_gr,GtkWidget *wpredok); int l_uosgrbu_p(class l_uosgrbu_rek *rek_poi,GtkWidget *wpredok); void l_gruppdok_unk(class l_uosgrbu_data *data); extern SQL_baza bd; int l_uosgrbu(int metka_rr, //0-ввод и корек. 1-выбор iceb_u_str *kod,iceb_u_str *naim,GtkWidget *wpredok) { int gor=0; int ver=0; class l_uosgrbu_data data; char bros[512]; data.poisk.clear_data(); data.metka_rr=metka_rr; data.name_window.plus(__FUNCTION__); data.window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_position( GTK_WINDOW(data.window),ICEB_POS_CENTER); gtk_window_set_modal(GTK_WINDOW(data.window),TRUE); if(data.metka_rr == 1) { if(iceb_sizwr(data.name_window.ravno(),&gor,&ver) == 0) gtk_window_set_default_size (GTK_WINDOW (data.window),gor,ver); } sprintf(bros,"%s %s",iceb_get_namesystem(),gettext("Список групп бухгалтерского учёта")); gtk_window_set_title (GTK_WINDOW (data.window),bros); gtk_container_set_border_width (GTK_CONTAINER (data.window), 5); g_signal_connect(data.window,"delete_event",G_CALLBACK(gtk_widget_destroy),NULL); g_signal_connect(data.window,"destroy",G_CALLBACK(gtk_main_quit),NULL); if(wpredok != NULL) { gdk_window_set_cursor(gtk_widget_get_window(wpredok),gdk_cursor_new_for_display(gtk_widget_get_display(wpredok),ICEB_CURSOR_GDITE)); //Удерживать окно над породившем его окном всегда gtk_window_set_transient_for(GTK_WINDOW(data.window),GTK_WINDOW(wpredok)); //Закрыть окно если окно предок удалено gtk_window_set_destroy_with_parent(GTK_WINDOW(data.window),TRUE); } g_signal_connect_after(data.window,"key_press_event",G_CALLBACK(l_uosgrbu_key_press),&data); g_signal_connect_after(data.window,"key_release_event",G_CALLBACK(iceb_key_release),&data.kl_shift); GtkWidget *hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 1); gtk_box_set_homogeneous (GTK_BOX(hbox),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет gtk_container_add (GTK_CONTAINER (data.window), hbox); GtkWidget *vbox1 = gtk_box_new (GTK_ORIENTATION_VERTICAL, 1); gtk_box_set_homogeneous (GTK_BOX(vbox1),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет GtkWidget *vbox2 = gtk_box_new (GTK_ORIENTATION_VERTICAL, 1); gtk_box_set_homogeneous (GTK_BOX(vbox2),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет gtk_box_pack_start (GTK_BOX (hbox), vbox1, FALSE, FALSE, 0); gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 0); gtk_widget_show(hbox); data.label_kolstr=gtk_label_new(gettext("Список групп бухгалтерского учёта")); gtk_box_pack_start (GTK_BOX (vbox2),data.label_kolstr,FALSE, FALSE, 0); gtk_widget_show(vbox1); gtk_widget_show(vbox2); data.label_poisk=gtk_label_new (""); gtk_box_pack_start (GTK_BOX (vbox2),data.label_poisk,FALSE, FALSE, 0); data.sw = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (data.sw),GTK_SHADOW_ETCHED_IN); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (data.sw),GTK_POLICY_AUTOMATIC,GTK_POLICY_AUTOMATIC); gtk_box_pack_end (GTK_BOX (vbox2), data.sw, TRUE, TRUE, 0); //Кнопки sprintf(bros,"F2 %s",gettext("Запись")); data.knopka[FK2]=gtk_button_new_with_label(bros); gtk_box_pack_start(GTK_BOX(vbox1), data.knopka[FK2], TRUE, TRUE, 0); g_signal_connect(data.knopka[FK2], "clicked",G_CALLBACK(l_uosgrbu_knopka),&data); gtk_widget_set_tooltip_text(data.knopka[FK2],gettext("Ввод новой записи")); gtk_widget_set_name(data.knopka[FK2],iceb_u_inttochar(FK2)); gtk_widget_show(data.knopka[FK2]); sprintf(bros,"%sF2 %s",RFK,gettext("Корректировать")); data.knopka[SFK2]=gtk_button_new_with_label(bros); gtk_box_pack_start(GTK_BOX(vbox1), data.knopka[SFK2],TRUE,TRUE, 0); g_signal_connect(data.knopka[SFK2], "clicked",G_CALLBACK(l_uosgrbu_knopka),&data); gtk_widget_set_tooltip_text(data.knopka[SFK2],gettext("Корректировка выбранной записи")); gtk_widget_set_name(data.knopka[SFK2],iceb_u_inttochar(SFK2)); gtk_widget_show(data.knopka[SFK2]); sprintf(bros,"F3 %s",gettext("Удалить")); data.knopka[FK3]=gtk_button_new_with_label(bros); gtk_box_pack_start(GTK_BOX(vbox1), data.knopka[FK3],TRUE,TRUE, 0); g_signal_connect(data.knopka[FK3], "clicked",G_CALLBACK(l_uosgrbu_knopka),&data); gtk_widget_set_tooltip_text(data.knopka[FK3],gettext("Удаление выбранной записи")); gtk_widget_set_name(data.knopka[FK3],iceb_u_inttochar(FK3)); gtk_widget_show(data.knopka[FK3]); sprintf(bros,"%sF3 %s",RFK,gettext("Удалить")); data.knopka[SFK3]=gtk_button_new_with_label(bros); gtk_box_pack_start(GTK_BOX(vbox1), data.knopka[SFK3],TRUE,TRUE, 0); g_signal_connect(data.knopka[SFK3], "clicked",G_CALLBACK(l_uosgrbu_knopka),&data); gtk_widget_set_tooltip_text(data.knopka[SFK3],gettext("Удалить неиспользуемые коды")); gtk_widget_set_name(data.knopka[SFK3],iceb_u_inttochar(SFK3)); gtk_widget_show(data.knopka[SFK3]); sprintf(bros,"F4 %s",gettext("Поиск")); data.knopka[FK4]=gtk_button_new_with_label(bros); g_signal_connect(data.knopka[FK4], "clicked",G_CALLBACK(l_uosgrbu_knopka),&data); gtk_box_pack_start(GTK_BOX(vbox1), data.knopka[FK4],TRUE,TRUE, 0); gtk_widget_set_tooltip_text(data.knopka[FK4],gettext("Поиск нужных записей")); gtk_widget_set_name(data.knopka[FK4],iceb_u_inttochar(FK4)); gtk_widget_show(data.knopka[FK4]); sprintf(bros,"F5 %s",gettext("Печать")); data.knopka[FK5]=gtk_button_new_with_label(bros); gtk_box_pack_start(GTK_BOX(vbox1), data.knopka[FK5],TRUE,TRUE, 0); g_signal_connect(data.knopka[FK5], "clicked",G_CALLBACK(l_uosgrbu_knopka),&data); gtk_widget_set_tooltip_text(data.knopka[FK5],gettext("Распечатка записей")); gtk_widget_set_name(data.knopka[FK5],iceb_u_inttochar(FK5)); gtk_widget_show(data.knopka[FK5]); sprintf(bros,"F10 %s",gettext("Выход")); data.knopka[FK10]=gtk_button_new_with_label(bros); gtk_box_pack_start(GTK_BOX(vbox1),data.knopka[FK10],TRUE,TRUE, 0); gtk_widget_set_tooltip_text(data.knopka[FK10],gettext("Завершение работы в этом окне")); g_signal_connect(data.knopka[FK10], "clicked",G_CALLBACK(l_uosgrbu_knopka),&data); gtk_widget_set_name(data.knopka[FK10],iceb_u_inttochar(FK10)); gtk_widget_show(data.knopka[FK10]); gtk_widget_realize(data.window); gdk_window_set_cursor(gtk_widget_get_window(data.window),gdk_cursor_new_for_display(gtk_widget_get_display(data.window),ICEB_CURSOR)); //gtk_widget_grab_focus(data.knopka[FK10]); l_uosgrbu_create_list(&data); gtk_widget_show(data.window); if(metka_rr == 0) gtk_window_maximize(GTK_WINDOW(data.window)); gtk_main(); if(data.metka_voz == 0) { kod->new_plus(data.kodv.ravno()); naim->new_plus(data.naimv.ravno()); } if(wpredok != NULL) gdk_window_set_cursor(gtk_widget_get_window(wpredok),gdk_cursor_new_for_display(gtk_widget_get_display(wpredok),ICEB_CURSOR)); return(data.metka_voz); } /***********************************/ /*Создаем список для просмотра */ /***********************************/ void l_uosgrbu_create_list (class l_uosgrbu_data *data) { iceb_clock sss(data->window); GtkListStore *model=NULL; GtkTreeIter iter; SQLCURSOR cur; char strsql[512]; int kolstr=0; SQL_str row; data->kl_shift=0; //0-отжата 1-нажата if(data->treeview != NULL) gtk_widget_destroy(data->treeview); data->treeview = gtk_tree_view_new(); gtk_container_add (GTK_CONTAINER (data->sw), data->treeview); g_signal_connect(data->treeview,"row_activated",G_CALLBACK(l_uosgrbu_v_row),data); GtkTreeSelection *selection=gtk_tree_view_get_selection(GTK_TREE_VIEW(data->treeview)); gtk_tree_selection_set_mode(selection,GTK_SELECTION_SINGLE); g_signal_connect(selection,"changed",G_CALLBACK(l_uosgrbu_vibor),data); gtk_tree_selection_set_mode (gtk_tree_view_get_selection (GTK_TREE_VIEW (data->treeview)),GTK_SELECTION_SINGLE); model = gtk_list_store_new (NUM_COLUMNS+1, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT); sprintf(strsql,"select * from Uosgrup1 order by kod asc"); if((kolstr=cur.make_cursor(&bd,strsql)) < 0) { iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window); return; } //gtk_list_store_clear(model); class iceb_u_str ss; data->kolzap=0; while(cur.read_cursor(&row) != 0) { // printf("%s %s %s %s\n",row[0],row[1],row[2],row[3]); if(l_uosgrbu_prov_row(row,data) != 0) continue; if(iceb_u_SRAV(data->kod_podr_tv.ravno(),row[0],0) == 0) data->snanomer=data->kolzap; if(atoi(row[5]) == 0) ss.new_plus(gettext("От начальной балансовой стоимости")); else ss.new_plus(gettext("От остаточной балансовой стоимости")); gtk_list_store_append (model, &iter); gtk_list_store_set (model, &iter, COL_KOD,row[0], COL_NAIM,row[1], COL_PROC,row[2], COL_AR,ss.ravno(), COL_DATA_VREM,iceb_u_vremzap(row[4]), COL_KTO,iceb_kszap(row[3],data->window), NUM_COLUMNS,data->kolzap, -1); data->kolzap++; } data->kod_podr_tv.new_plus(""); gtk_tree_view_set_model (GTK_TREE_VIEW(data-> treeview),GTK_TREE_MODEL (model)); g_object_unref (GTK_TREE_MODEL (model)); l_uosgrbu_add_columns (GTK_TREE_VIEW (data->treeview)); if(data->kolzap == 0) { gtk_widget_set_sensitive(GTK_WIDGET(data->knopka[FK3]),FALSE);//Недоступна gtk_widget_set_sensitive(GTK_WIDGET(data->knopka[FK5]),FALSE);//Недоступна gtk_widget_set_sensitive(GTK_WIDGET(data->knopka[SFK2]),FALSE);//Недоступна gtk_widget_set_sensitive(GTK_WIDGET(data->knopka[SFK3]),FALSE);//Недоступна } else { gtk_widget_set_sensitive(GTK_WIDGET(data->knopka[FK3]),TRUE);//Доступна gtk_widget_set_sensitive(GTK_WIDGET(data->knopka[FK5]),TRUE);//Доступна gtk_widget_set_sensitive(GTK_WIDGET(data->knopka[SFK2]),TRUE);//Доступна gtk_widget_set_sensitive(GTK_WIDGET(data->knopka[SFK3]),TRUE);//Доступна } gtk_widget_show (data->treeview); gtk_widget_show (data->sw); //Стать подсветкой стороки на нужный номер строки iceb_snanomer(data->kolzap,&data->snanomer,data->treeview); iceb_u_str stroka; iceb_u_str zagolov; zagolov.plus(gettext("Список групп бухгалтерского учёта")); sprintf(strsql,". %s:%d",gettext("Количество записей"),data->kolzap); zagolov.plus(strsql); gtk_label_set_text(GTK_LABEL(data->label_kolstr),zagolov.ravno()); if(data->metka_poi == 1) { zagolov.new_plus(gettext("Поиск")); zagolov.plus(" !!!"); iceb_str_poisk(&zagolov,data->poisk.kod.ravno(),gettext("Код")); iceb_str_poisk(&zagolov,data->poisk.naim.ravno(),gettext("Наименование")); iceb_label_set_text_color(data->label_poisk,zagolov.ravno(),"red"); gtk_widget_show(data->label_poisk); } else gtk_widget_hide(data->label_poisk); gtk_widget_show(data->label_kolstr); } /*****************/ /*Создаем колонки*/ /*****************/ void l_uosgrbu_add_columns(GtkTreeView *treeview) { GtkCellRenderer *renderer; renderer = gtk_cell_renderer_text_new (); gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview), -1,gettext("Код"), renderer,"text", COL_KOD,NULL); renderer = gtk_cell_renderer_text_new (); gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview), -1,gettext("Наименование"), renderer,"text", COL_NAIM,NULL); renderer = gtk_cell_renderer_text_new (); gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview), -1,gettext("Процент"), renderer,"text", COL_PROC,NULL); renderer = gtk_cell_renderer_text_new (); gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview), -1,gettext("Алгоритм амортизации"), renderer,"text",COL_AR,NULL); renderer = gtk_cell_renderer_text_new (); gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview),-1, gettext("Дата и время записи"), renderer,"text", COL_DATA_VREM,NULL); renderer = gtk_cell_renderer_text_new (); gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview),-1, gettext("Кто записал"), renderer, "text", COL_KTO,NULL); } /****************************/ /*Выбор строки*/ /**********************/ void l_uosgrbu_vibor(GtkTreeSelection *selection,class l_uosgrbu_data *data) { GtkTreeModel *model; GtkTreeIter iter; if(gtk_tree_selection_get_selected(selection,&model,&iter) != TRUE) return; gchar *kod; gchar *naim; gint nomer; gtk_tree_model_get(model,&iter,0,&kod,1,&naim,NUM_COLUMNS,&nomer,-1); data->kodv.new_plus(kod); data->naimv.new_plus(naim); data->snanomer=nomer; g_free(kod); g_free(naim); //printf("%s %s %d\n",data->kodv.ravno(),data->naimv.ravno(),nomer); } /*****************************/ /*Обработчик нажатия кнопок */ /*****************************/ void l_uosgrbu_knopka(GtkWidget *widget,class l_uosgrbu_data *data) { //char bros[512]; iceb_u_str repl; int knop=atoi(gtk_widget_get_name(widget)); //g_print("l_uosgrbu_knopka knop=%d\n",knop); data->kl_shift=0; //0-отжата 1-нажата switch (knop) { case FK2: l_uosgrbu_v(&data->kod_podr_tv,data->window); l_uosgrbu_create_list(data); return; case SFK2: if(data->kolzap == 0) return; l_uosgrbu_v(&data->kodv,data->window); l_uosgrbu_create_list(data); return; case FK3: if(data->kolzap == 0) return; if(iceb_menu_danet(gettext("Удалить запись ? Вы уверены ?"),2,data->window) != 1) return; l_uosgrbu_udzap(data); l_uosgrbu_create_list(data); return; case SFK3: if(data->kolzap == 0) return; if(iceb_menu_danet(gettext("Удалить неиспользуемые коды ? Вы уверены ?"),2,data->window) != 1) return; l_gruppdok_unk(data); l_uosgrbu_create_list(data); return; case FK4: if(l_uosgrbu_p(&data->poisk,data->window) == 0) data->metka_poi=1; else data->metka_poi=0; l_uosgrbu_create_list(data); return; case FK5: l_uosgrbu_rasp(data); return; case FK10: if(data->metka_rr == 1) iceb_sizww(data->name_window.ravno(),data->window); data->metka_voz=1; gtk_widget_destroy(data->window); return; } } /*********************************/ /*Обработка нажатия клавиш */ /*********************************/ gboolean l_uosgrbu_key_press(GtkWidget *widget,GdkEventKey *event,class l_uosgrbu_data *data) { switch(event->keyval) { case GDK_KEY_F2: if(data->kl_shift == 0) g_signal_emit_by_name(data->knopka[FK2],"clicked"); else g_signal_emit_by_name(data->knopka[SFK2],"clicked"); return(TRUE); case GDK_KEY_F3: if(data->kl_shift == 0) g_signal_emit_by_name(data->knopka[FK3],"clicked"); else g_signal_emit_by_name(data->knopka[SFK3],"clicked"); return(TRUE); case GDK_KEY_F4: g_signal_emit_by_name(data->knopka[FK4],"clicked"); return(TRUE); case GDK_KEY_F5: g_signal_emit_by_name(data->knopka[FK5],"clicked"); return(TRUE); case GDK_KEY_Escape: case GDK_KEY_F10: g_signal_emit_by_name(data->knopka[FK10],"clicked"); return(FALSE); case ICEB_REG_L: case ICEB_REG_R: data->kl_shift=1; return(TRUE); default: printf("Не выбрана клавиша !\n"); break; } return(TRUE); } /****************************/ /*Выбор строки*/ /**********************/ void l_uosgrbu_v_row(GtkTreeView *treeview,GtkTreePath *arg1,GtkTreeViewColumn *arg2, class l_uosgrbu_data *data) { if(data->metka_rr == 0) { g_signal_emit_by_name(data->knopka[SFK2],"clicked"); return; } iceb_sizww(data->name_window.ravno(),data->window); data->metka_voz=0; gtk_widget_destroy(data->window); } /*****************************/ /*Удаление записи */ /*****************************/ void l_uosgrbu_udzap(class l_uosgrbu_data *data) { if(l_uosgrbu_pvu(1,data->kodv.ravno(),data->window) != 0) return; char strsql[512]; sprintf(strsql,"delete from Uosgrup1 where kod='%s'",data->kodv.ravno()); if(iceb_sql_zapis(strsql,0,0,data->window) != 0) return; } /****************************/ /*Проверка записей */ /*****************************/ int l_uosgrbu_prov_row(SQL_str row,class l_uosgrbu_data *data) { if(data->metka_poi == 0) return(0); //Полное сравнение if(iceb_u_proverka(data->poisk.kod.ravno(),row[0],0,0) != 0) return(1); //Поиск образца в строке if(data->poisk.naim.ravno()[0] != '\0' && iceb_u_strstrm(row[1],data->poisk.naim.ravno()) == 0) return(1); return(0); } /*************************************/ /*Распечатка записей */ /*************************************/ void l_uosgrbu_rasp(class l_uosgrbu_data *data) { char strsql[512]; SQL_str row; FILE *ff; SQLCURSOR cur; iceb_u_spisok imaf; iceb_u_spisok naimot; int kolstr=0; sprintf(strsql,"select * from Uosgrup1 order by kod asc"); if((kolstr=cur.make_cursor(&bd,strsql)) < 0) { iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window); return; } sprintf(strsql,"ugrbu%d.lst",getpid()); imaf.plus(strsql); naimot.plus(gettext("Список групп бухгалтерского учёта")); if((ff = fopen(strsql,"w")) == NULL) { iceb_er_op_fil(strsql,"",errno,data->window); return; } iceb_zagolov(gettext("Список групп бухгалтерского учёта"),0,0,0,0,0,0,ff,data->window); if(data->metka_poi == 1) { if(data->poisk.kod.getdlinna() > 1) fprintf(ff,"%s:%s\n",gettext("Код"),data->poisk.kod.ravno()); if(data->poisk.naim.getdlinna() > 1) fprintf(ff,"%s:%s\n",gettext("Наименование"),data->poisk.naim.ravno()); } fprintf(ff,"\ -------------------------------------------------------------\n"); fprintf(ff,gettext("\ Код | Наименование группы |Год.н.а.|Алгоритм аморт.|\n")); /* */ fprintf(ff,"\ -------------------------------------------------------------\n"); class iceb_u_str tipam(""); while(cur.read_cursor(&row) != 0) { if(atoi(row[5]) == 0) tipam.new_plus(gettext("От начальной балансовой стоимости")); else tipam.new_plus(gettext("От остаточной балансовой стоимости")); fprintf(ff,"%-4s %-*.*s %8s %-*.*s\n", row[0], iceb_u_kolbait(30,row[1]),iceb_u_kolbait(30,row[1]),row[1], row[2], iceb_u_kolbait(15,tipam.ravno()),iceb_u_kolbait(15,tipam.ravno()),tipam.ravno()); } fprintf(ff,"\ -------------------------------------------------------------\n"); iceb_podpis(ff,data->window); fclose(ff); iceb_ustpeh(imaf.ravno(0),3,data->window); iceb_rabfil(&imaf,&naimot,data->window); } /*****************************/ /*Проверить возможность удаления*/ /********************************/ //Если вернули 0-можно удалять 1-нет int l_uosgrbu_pvu(int met,const char *kod,GtkWidget *wpredok) { char strsql[512]; sprintf(strsql,"select hnaby from Uosinp where hnaby='%s' limit 1",kod); if(iceb_sql_readkey(strsql,wpredok) > 0) { if(met != 0) { iceb_u_str soob; sprintf(strsql,"%s Uosinp",gettext("Удалить невозможно ! Есть записи в таблице")); soob.plus(strsql); iceb_menu_soob(&soob,wpredok); } return(1); } sprintf(strsql,"select hna from Uosamor1 where hna='%s' limit 1",kod); if(iceb_sql_readkey(strsql,wpredok) > 0) { if(met != 0) { iceb_u_str soob; sprintf(strsql,"%s Uosamor1",gettext("Удалить невозможно ! Есть записи в таблице")); soob.plus(strsql); iceb_menu_soob(&soob,wpredok); } return(1); } return(0); } /**********************************/ /*Удаление неиспользуемых кодов групп*/ /**************************************/ void l_gruppdok_unk(class l_uosgrbu_data *data) { SQL_str row; SQLCURSOR cur; char strsql[512]; sprintf(strsql,"select kod from Uosgrup1"); int kolstr=0; if((kolstr=cur.make_cursor(&bd,strsql)) < 0) { iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window); return; } int koludzap=0; while(cur.read_cursor(&row) != 0) { if(l_uosgrbu_pvu(0,row[0],data->window) != 0) continue; sprintf(strsql,"delete from Uosgrup1 where kod=%d",atoi(row[0])); if(iceb_sql_zapis(strsql,0,0,data->window) != 0) break; koludzap++; } sprintf(strsql,"%s:%d",gettext("Количество удалённых записей"),koludzap); iceb_menu_soob(strsql,data->window); }
[ "root@calculate.local" ]
root@calculate.local
9155f318247154d518ca69cac491fcc77205de34
e537ccf5cec931491ab74bec6eda6603cd3db173
/catchFish/webitem.cpp
81ea9223b4a38b6a9e270a93f9c95c45ddd6737b
[]
no_license
H-K-ai/Qt-4.7.4
47b8f5e84a96a1448c78f690b63453f296d67561
b5f857e75799e711e48bda1e29e023c17557cfe6
refs/heads/master
2021-05-28T07:22:34.300373
2015-03-02T19:10:15
2015-03-02T19:10:15
null
0
0
null
null
null
null
GB18030
C++
false
false
697
cpp
#include "webitem.h" webItem::webItem() { webWidth = 116; webHeight = 118; webTime = 0; } QRectF webItem::boundingRect() const { //绘制item大概的区域 qreal adjust = 2; return QRectF(-(webWidth-adjust)/2, -(webHeight-adjust)/2, (webWidth+adjust), (webHeight+adjust)); } void webItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { painter->drawPixmap(boundingRect().topLeft(), QPixmap(":/images/web.png")); } void webItem::advance(int step) { if (!step) return; webTime++; if(webTime == 15) { scene()->removeItem(this); } } int webItem::type() const { //返回类型 return WEBITEM; }
[ "llwslc@gmail.com" ]
llwslc@gmail.com
f98d723152ecd32b855838e27d0bd3cdb103a8f7
7529345d1495507ec20b8203f9f7e50475b4854b
/OpenCV/opencv-hololens-contrib/modules/stereo/test/test_descriptors.cpp
b466ecf319f1561ae489d9661c99388054be2246
[ "BSD-3-Clause" ]
permissive
Firifire/OpenCvSharp-UWP
49b484df8e41068a865b50528af2dc032036fa8f
f8b1c182f8d995c2cc86921268851bb2baaa5918
refs/heads/master
2023-02-01T09:31:46.579601
2018-03-30T13:25:24
2020-12-19T12:53:14
122,069,012
15
4
null
null
null
null
UTF-8
C++
false
false
17,414
cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include <limits.h> using namespace cv; using namespace cv::stereo; using namespace std; class CV_DescriptorBaseTest : public cvtest::BaseTest { public: CV_DescriptorBaseTest(); ~CV_DescriptorBaseTest(); protected: virtual void imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2) = 0; virtual void imageTransformation(const Mat &img1, Mat &out1) = 0; void testROI(const Mat &img); void testMonotonicity(const Mat &img, Mat &out); void run(int ); Mat censusImage[2]; Mat censusImageSingle[2]; Mat left; Mat right; int kernel_size, descriptor_type; }; //we test to see if the descriptor applied on a roi //has the same value with the descriptor from the original image //tested at the roi boundaries void CV_DescriptorBaseTest::testROI(const Mat &img) { int pt, pb,w,h; //initialize random values for the roi top and bottom pt = rand() % 100; pb = rand() % 100; //calculate the new width and height w = img.cols; h = img.rows - pt - pb; int start = pt + kernel_size / 2 + 1; int stop = h - kernel_size/2 - 1; //set the region of interest according to above values Rect region_of_interest = Rect(0, pt, w, h); Mat image_roi1 = img(region_of_interest); Mat p1,p2; //create 2 images where to put our output p1.create(image_roi1.rows, image_roi1.cols, CV_32SC4); p2.create(img.rows, img.cols, CV_32SC4); imageTransformation(image_roi1,p1); imageTransformation(img,p2); int *roi_data = (int *)p1.data; int *img_data = (int *)p2.data; //verify result for(int i = start; i < stop; i++) { for(int j = 0; j < w ; j++) { if(roi_data[(i - pt) * w + j] != img_data[(i) * w + j]) { ts->printf(cvtest::TS::LOG, "Something wrong with ROI \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT); return; } } } } CV_DescriptorBaseTest::~CV_DescriptorBaseTest() { left.release(); right.release(); censusImage[0].release(); censusImage[1].release(); censusImageSingle[0].release(); censusImageSingle[1].release(); } CV_DescriptorBaseTest::CV_DescriptorBaseTest() { //read 2 images from file left = imread(ts->get_data_path() + "stereomatching/datasets/tsukuba/im2.png", IMREAD_GRAYSCALE); right = imread(ts->get_data_path() + "stereomatching/datasets/tsukuba/im6.png", IMREAD_GRAYSCALE); if(left.empty() || right.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } ts->printf(cvtest::TS::LOG, "Data loaded \n"); } //verify if we don't have an image with all pixels the same( except when all input pixels are equal) void CV_DescriptorBaseTest::testMonotonicity(const Mat &img, Mat &out) { //verify if input data is correct if(img.rows != out.rows || img.cols != out.cols || img.empty() || out.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output dimension \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } //verify that for an input image with different pxels the values of the //output pixels are not the same int same = 0; uint8_t *data = img.data; uint8_t val = data[1]; int stride = (int)img.step; for(int i = 0 ; i < img.rows && !same; i++) { for(int j = 0; j < img.cols; j++) { if(val != data[i * stride + j]) { same = 1; break; } } } int value_descript = out.data[1]; int accept = 0; uint8_t *outData = out.data; for(int i = 0 ; i < img.rows && !accept; i++) { for(int j = 0; j < img.cols; j++) { //we verify for the output image if the iage pixels are not all the same of an input //image with different pixels if(value_descript != outData[i * stride + j] && same) { //if we found a value that is different we accept accept = 1; break; } } } if(accept == 1 && same == 0) { ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT); ts->printf(cvtest::TS::LOG, "The image has all values the same \n"); return; } if(accept == 0 && same == 1) { ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT); ts->printf(cvtest::TS::LOG, "For correct image we get all descriptor values the same \n"); return; } ts->set_failed_test_info(cvtest::TS::OK); } /////////////////////////////////// //census transform class CV_CensusTransformTest: public CV_DescriptorBaseTest { public: CV_CensusTransformTest(); protected: void imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2); void imageTransformation(const Mat &img1, Mat &out1); }; CV_CensusTransformTest::CV_CensusTransformTest() { kernel_size = 11; descriptor_type = CV_SPARSE_CENSUS; } void CV_CensusTransformTest::imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2) { //verify if input data is correct if(img1.rows != out1.rows || img1.cols != out1.cols || img1.empty() || out1.empty() || img2.rows != out2.rows || img2.cols != out2.cols || img2.empty() || out2.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } if(kernel_size % 2 == 0) { ts->printf(cvtest::TS::LOG, "Wrong kernel size;Kernel should be odd \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } censusTransform(img1,img2,kernel_size,out1,out2,descriptor_type); } void CV_CensusTransformTest::imageTransformation(const Mat &img1, Mat &out1) { //verify if input data is correct if(img1.rows != out1.rows || img1.cols != out1.cols || img1.empty() || out1.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } if(kernel_size % 2 == 0) { ts->printf(cvtest::TS::LOG, "Wrong kernel size;Kernel should be odd \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } censusTransform(img1,kernel_size,out1,descriptor_type); } ////////////////////////////////// //symetric census class CV_SymetricCensusTest: public CV_DescriptorBaseTest { public: CV_SymetricCensusTest(); protected: void imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2); void imageTransformation(const Mat &img1, Mat &out1); }; CV_SymetricCensusTest::CV_SymetricCensusTest() { kernel_size = 7; descriptor_type = CV_CS_CENSUS; } void CV_SymetricCensusTest::imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2) { //verify if input data is correct if(img1.rows != out1.rows || img1.cols != out1.cols || img1.empty() || out1.empty() || img2.rows != out2.rows || img2.cols != out2.cols || img2.empty() || out2.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } if(kernel_size % 2 == 0) { ts->printf(cvtest::TS::LOG, "Wrong kernel size;Kernel should be odd \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } symetricCensusTransform(img1,img2,kernel_size,out1,out2,descriptor_type); } void CV_SymetricCensusTest::imageTransformation(const Mat &img1, Mat &out1) { //verify if input data is correct if(img1.rows != out1.rows || img1.cols != out1.cols || img1.empty() || out1.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } if(kernel_size % 2 == 0) { ts->printf(cvtest::TS::LOG, "Wrong kernel size;Kernel should be odd \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } symetricCensusTransform(img1,kernel_size,out1,descriptor_type); } ////////////////////////////////// //modified census transform class CV_ModifiedCensusTransformTest: public CV_DescriptorBaseTest { public: CV_ModifiedCensusTransformTest(); protected: void imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2); void imageTransformation(const Mat &img1, Mat &out1); }; CV_ModifiedCensusTransformTest::CV_ModifiedCensusTransformTest() { kernel_size = 9; descriptor_type = CV_MODIFIED_CENSUS_TRANSFORM; } void CV_ModifiedCensusTransformTest::imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2) { //verify if input data is correct if(img1.rows != out1.rows || img1.cols != out1.cols || img1.empty() || out1.empty() || img2.rows != out2.rows || img2.cols != out2.cols || img2.empty() || out2.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } if(kernel_size % 2 == 0) { ts->printf(cvtest::TS::LOG, "Wrong kernel size;Kernel should be odd \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } modifiedCensusTransform(img1,img2,kernel_size,out1,out2,descriptor_type); } void CV_ModifiedCensusTransformTest::imageTransformation(const Mat &img1, Mat &out1) { if(img1.rows != out1.rows || img1.cols != out1.cols || img1.empty() || out1.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } if(kernel_size % 2 == 0) { ts->printf(cvtest::TS::LOG, "Wrong kernel size;Kernel should be odd \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } modifiedCensusTransform(img1,kernel_size,out1,descriptor_type); } ////////////////////////////////// //star kernel census class CV_StarKernelCensusTest: public CV_DescriptorBaseTest { public: CV_StarKernelCensusTest(); protected: void imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2); void imageTransformation(const Mat &img1, Mat &out1); }; CV_StarKernelCensusTest :: CV_StarKernelCensusTest() { kernel_size = 9; descriptor_type = CV_STAR_KERNEL; } void CV_StarKernelCensusTest :: imageTransformation(const Mat &img1, const Mat &img2, Mat &out1, Mat &out2) { //verify if input data is correct if(img1.rows != out1.rows || img1.cols != out1.cols || img1.empty() || out1.empty() || img2.rows != out2.rows || img2.cols != out2.cols || img2.empty() || out2.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } if(kernel_size % 2 == 0) { ts->printf(cvtest::TS::LOG, "Wrong kernel size;Kernel should be odd \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } starCensusTransform(img1,img2,kernel_size,out1,out2); } void CV_StarKernelCensusTest::imageTransformation(const Mat &img1, Mat &out1) { if(img1.rows != out1.rows || img1.cols != out1.cols || img1.empty() || out1.empty()) { ts->printf(cvtest::TS::LOG, "Wrong input / output data \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } if(kernel_size % 2 == 0) { ts->printf(cvtest::TS::LOG, "Wrong kernel size;Kernel should be odd \n"); ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } starCensusTransform(img1,kernel_size,out1); } void CV_DescriptorBaseTest::run(int ) { if (left.empty() || right.empty()) { ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); ts->printf(cvtest::TS::LOG, "No input images detected\n"); return; } testROI(left); censusImage[0].create(left.rows, left.cols, CV_32SC4); censusImage[1].create(left.rows, left.cols, CV_32SC4); censusImageSingle[0].create(left.rows, left.cols, CV_32SC4); censusImageSingle[1].create(left.rows, left.cols, CV_32SC4); censusImage[0].setTo(0); censusImage[1].setTo(0); censusImageSingle[0].setTo(0); censusImageSingle[1].setTo(0); imageTransformation(left, right, censusImage[0], censusImage[1]); imageTransformation(left, censusImageSingle[0]); imageTransformation(right, censusImageSingle[1]); testMonotonicity(left,censusImage[0]); testMonotonicity(right,censusImage[1]); testMonotonicity(left,censusImageSingle[0]); testMonotonicity(right,censusImageSingle[1]); if (censusImage[0].empty() || censusImage[1].empty() || censusImageSingle[0].empty() || censusImageSingle[1].empty()) { ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT); ts->printf(cvtest::TS::LOG, "The descriptor images are empty \n"); return; } int *datl1 = (int *)censusImage[0].data; int *datr1 = (int *)censusImage[1].data; int *datl2 = (int *)censusImageSingle[0].data; int *datr2 = (int *)censusImageSingle[1].data; for(int i = 0; i < censusImage[0].rows - kernel_size/ 2; i++) { for(int j = 0; j < censusImage[0].cols; j++) { if(datl1[i * censusImage[0].cols + j] != datl2[i * censusImage[0].cols + j]) { ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT); ts->printf(cvtest::TS::LOG, "Mismatch for left images %d \n",descriptor_type); return; } if(datr1[i * censusImage[0].cols + j] != datr2[i * censusImage[0].cols + j]) { ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT); ts->printf(cvtest::TS::LOG, "Mismatch for right images %d \n",descriptor_type); return; } } } int min = numeric_limits<int>::min(); int max = numeric_limits<int>::max(); //check if all values are between int min and int max and not NAN if (0 != cvtest::check(censusImage[0], min, max, 0)) { ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return; } //check if all values are between int min and int max and not NAN if (0 != cvtest::check(censusImage[1], min, max, 0)) { ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); return ; } } TEST(DISABLED_census_transform_testing, accuracy) { CV_CensusTransformTest test; test.safe_run(); } TEST(DISABLED_symetric_census_testing, accuracy) { CV_SymetricCensusTest test; test.safe_run(); } TEST(DISABLED_Dmodified_census_testing, accuracy) { CV_ModifiedCensusTransformTest test; test.safe_run(); } TEST(DISABLED_Dstar_kernel_testing, accuracy) { CV_StarKernelCensusTest test; test.safe_run(); }
[ "firifire@gmail.com" ]
firifire@gmail.com
c6d3b76bb233d13b3c0ae70f0b80b6431488b1e4
aa178113806fe0d7b41cfe0f7750c75e13cc5689
/libs/ff/buffer.hpp
b1ce51e71e284523ecb529a5db5ce0f60a74a771
[]
no_license
Binipro/iol-parallel-video-generator
0135742678e6dbb95aa3122a35f964d06413b834
33dc9b530348c49364edb6533affec9d153bed57
refs/heads/master
2022-10-30T14:38:45.976197
2020-06-19T16:59:28
2020-06-19T16:59:28
273,492,075
1
0
null
null
null
null
UTF-8
C++
false
false
15,067
hpp
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /*! * \file buffer.hpp * \ingroup building_blocks * * \brief This file contains the definition of the bounded \p SPSC channel * buffer used in FastFlow * * Single-Writer Single-Reader circular buffer. * No lock is needed around pop and push methods. * Wait-free and fence-free (in the TSO model). * * A single NULL value is used to indicate buffer full and * buffer empty conditions. * * More details about the SWSR_Ptr_Buffer implementation * can be found in: * * Massimo Torquati, "Single-Producer/Single-Consumer Queue on Shared Cache * Multi-Core Systems", TR-10-20, Computer Science Department, University * of Pisa Italy,2010 * ( http://compass2.di.unipi.it/TR/Files/TR-10-20.pdf.gz ) * * M. Aldinucci, M. Danelutto, P. Kilpatrick, M. Meneghin, and M. Torquati, * "An Efficient Unbounded Lock-Free Queue for Multi-core Systems," * in Proc. of 18th Intl. Euro-Par 2012 Parallel Processing, Rhodes Island, * Greece, 2012, pp. 662-673. doi:10.1007/978-3-642-32820-6_65 */ /* *************************************************************************** * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * **************************************************************************** */ /* Author: Massimo Torquati * */ #ifndef FF_SWSR_PTR_BUFFER_HPP #define FF_SWSR_PTR_BUFFER_HPP #include <cstdlib> #include <cstring> //#include <atomic> //#include <ff/atomic/abstraction_dcas.h> #include <ff/sysdep.h> #include <ff/config.hpp> #if defined(__APPLE__) #include <AvailabilityMacros.h> #endif #include <ff/platforms/platform.h> namespace ff { // 64 bytes is the common size of a cache line static const int longxCacheLine = (CACHE_LINE_SIZE/sizeof(long)); /*! * \class SWSR_Ptr_Buffer * \ingroup building_blocks * * \brief SPSC bound channel (Single-Writer/Single-Reader) * * This class describes the SWSR circular buffer, used in FastFlow to * implement a lock-free (wait-free) bounded FIFO queue. No lock is needed * around pop and push methods. * * A single NULL value is used to indicate buffer full and buffer empty * conditions. * * This class is defined in \ref buffer.hpp * */ class SWSR_Ptr_Buffer { /** * experimentally we found that a good value is between * 2 and 6 cache lines (16 to 48 entries respectively) */ enum {MULTIPUSH_BUFFER_SIZE=16}; private: // Padding is required to avoid false-sharing between // core's private cache #if defined(NO_VOLATILE_POINTERS) unsigned long pread; long padding1[longxCacheLine-1]; unsigned long pwrite; long padding2[longxCacheLine-1]; #else ALIGN_TO_PRE(CACHE_LINE_SIZE) volatile unsigned long pread; ALIGN_TO_POST(CACHE_LINE_SIZE) ALIGN_TO_PRE(CACHE_LINE_SIZE) volatile unsigned long pwrite; ALIGN_TO_POST(CACHE_LINE_SIZE) #endif const unsigned long size; void ** buf; #if defined(SWSR_MULTIPUSH) /* massimot: experimental code (see multipush) * */ long padding3[longxCacheLine-2]; // local multipush buffer used by the mpush method void * multipush_buf[MULTIPUSH_BUFFER_SIZE]; int mcnt; #endif public: /* pointer to member function for the push method */ bool (SWSR_Ptr_Buffer::*pushPMF)(void * const); /* pointer to member function for the ppop method */ bool (SWSR_Ptr_Buffer::*popPMF)(void **); public: /** * Constructor. * * \param n the size of the buffer */ SWSR_Ptr_Buffer(unsigned long n, const bool=true): pread(0),pwrite(0),size(n),buf(0) { pushPMF=&SWSR_Ptr_Buffer::push; popPMF =&SWSR_Ptr_Buffer::pop; // Avoid unused private field warning on padding1, padding2 //(void)padding1; //(void)padding2; } /** * Default destructor */ ~SWSR_Ptr_Buffer() { // freeAlignedMemory is a function defined in 'sysdep.h' freeAlignedMemory(buf); } /** * It initialise the buffer. Allocate space (\p size) of possibly aligned * memory and reset the pointers (read pointer and write pointer) by * placing them at the beginning of the buffer. * * \return TODO */ bool init(const bool startatlineend=false) { if (buf || (size==0)) return false; #if defined(SWSR_MULTIPUSH) if (size<MULTIPUSH_BUFFER_SIZE) return false; #endif // getAlignedMemory is a function defined in 'sysdep.h' buf=(void**)getAlignedMemory(longxCacheLine*sizeof(long),size*sizeof(void*)); if (!buf) return false; reset(startatlineend); return true; } /** * It returns true if the buffer is empty. */ inline bool empty() { #if defined(NO_VOLATILE_POINTERS) return ((*(volatile unsigned long *)(&buf[pread]))==0); #else return (buf[pread]==NULL); #endif } /** * It returns true if there is at least one room in the buffer. */ inline bool available() { #if defined(NO_VOLATILE_POINTERS) return ((*(volatile unsigned long *)(&buf[pwrite]))==0); #else return (buf[pwrite]==NULL); #endif } /** * It returns the size of the buffer. * * \return The size of the buffer. */ inline size_t buffersize() const { return size; }; /** * Push method: push the input value into the queue. A Write Memory * Barrier (WMB) ensures that all previous memory writes are visible to * the other processors before any later write is executed. This is an * "expensive" memory fence operation needed in all the architectures with * a weak-ordering memory model, where stores can be executed out-of-order * (e.g. PowerPc). This is a no-op on Intel x86/x86-64 CPUs. * * \param data Element to be pushed in the buffer * * \return TODO */ inline bool push(void * const data) { /* modify only pwrite pointer */ assert(data != NULL); if (available()) { /** * Write Memory Barrier: ensure all previous memory write * are visible to the other processors before any later * writes are executed. This is an "expensive" memory fence * operation needed in all the architectures with a weak-ordering * memory model where stores can be executed out-or-order * (e.g. Powerpc). This is a no-op on Intel x86/x86-64 CPUs. */ WMB(); //std::atomic_thread_fence(std::memory_order_release); buf[pwrite] = data; pwrite += (pwrite+1 >= size) ? (1-size): 1; // circular buffer return true; } return false; } /** * The multipush method, which pushes a batch of elements (array) in the * queue. NOTE: len should be a multiple of longxCacheLine/sizeof(void*) * */ inline bool multipush(void * const data[], int len) { if ((unsigned)len>=size) return false; unsigned long last = pwrite + ((pwrite+ --len >= size) ? (len-size): len); unsigned long r = len-(last+1), l=last; unsigned long i; if (buf[last]==NULL) { if (last < pwrite) { for(i=len;i>r;--i,--l) buf[l] = data[i]; for(i=(size-1);i>=pwrite;--i,--r) buf[i] = data[r]; } else for(int i=len;i>=0;--i) buf[pwrite+i] = data[i]; WMB(); pwrite = (last+1 >= size) ? 0 : (last+1); #if defined(SWSR_MULTIPUSH) mcnt = 0; // reset mpush counter #endif return true; } return false; } #if defined(SWSR_MULTIPUSH) // massimot: experimental code /** * This method provides the same interface of the \p push method, but it * allows to provide a batch of items to * the consumer, thus ensuring better cache locality and * lowering the cache trashing. * * \param data Element to be pushed in the buffer */ inline bool mpush(void * const data) { assert(data); if (mcnt==MULTIPUSH_BUFFER_SIZE) return multipush(multipush_buf,MULTIPUSH_BUFFER_SIZE); multipush_buf[mcnt++]=data; if (mcnt==MULTIPUSH_BUFFER_SIZE) return multipush(multipush_buf,MULTIPUSH_BUFFER_SIZE); return true; } /* REW -- ? */ inline bool flush() { return (mcnt ? multipush(multipush_buf,mcnt) : true); } #endif /* SWSR_MULTIPUSH */ /** * It is like pop but doesn't copy any data. * * \return \p true is alway returned. */ inline bool inc() { buf[pread]=NULL; pread += (pread+1 >= size) ? (1-size): 1; // circular buffer return true; } /** * Pop method: get the next value from the FIFO buffer. * * \param data Pointer to the location where to store the * data popped from the buffer. */ inline bool pop(void ** data) { /* modify only pread pointer */ if (empty()) return false; *data = buf[pread]; //std::atomic_thread_fence(std::memory_order_acquire); return inc(); } /** * It returns the "head" of the buffer, i.e. the element pointed by the read * pointer (it is a FIFO queue, so \p push on the tail and \p pop from the * head). * * \return The head of the buffer. */ inline void * top() const { return buf[pread]; } /** * Reset the buffer and move \p read and \p write pointers to the beginning * of the buffer (i.e. position 0). Also, the entire buffer is cleaned and * set to 0 */ inline void reset(const bool startatlineend=false) { if (startatlineend) { /** * This is a good starting point if the multipush method will be * used in order to reduce cache trashing. */ pwrite = longxCacheLine-1; pread = longxCacheLine-1; } else { pread=pwrite=0; } #if defined(SWSR_MULTIPUSH) mcnt = 0; #endif if (size<=512) for(unsigned long i=0;i<size;++i) buf[i]=0; else memset(buf,0,size*sizeof(void*)); } /** * It returns the length of the buffer * (i.e. the actual number of elements it contains) */ inline unsigned long length() const { long tpread=pread, tpwrite=pwrite; long len = tpwrite-tpread; if (len>0) return (unsigned long)len; if (len<0) return (unsigned long)(size+len); if (buf[tpwrite]==NULL) return 0; return size; } // Not yet implemented inline bool mp_push(void *const data) { abort(); return false; } // Not yet implemented inline bool mc_pop(void ** data) { abort(); return false; } inline bool isFixedSize() const { return true; } }; /*! * \class Lamport_Buffer. * \ingroup aux_classes * * \brief Implementation of the well-known Lamport's wait-free circular * buffer. Not currently used. * * */ class Lamport_Buffer { private: // Padding is required to avoid false-sharing between // core's private cache volatile unsigned long pread; long padding1[longxCacheLine-1]; volatile unsigned long pwrite; long padding2[longxCacheLine-1]; const size_t size; void ** buf; public: /** * Constructor */ Lamport_Buffer(unsigned long n, const bool=true): pread(0),pwrite(0),size(n),buf(0) { // Avoid unused private field warning on padding1, padding2 (void)padding1; (void)padding2; } /** * Destructor */ ~Lamport_Buffer() { freeAlignedMemory(buf); } /** * It initialize the circular buffer. * * \return If successful \p true is returned, otherwise \p false is * returned. */ bool init() { assert(buf==0); buf=(void**)getAlignedMemory(longxCacheLine*sizeof(long),size*sizeof(void*)); if (!buf) return false; reset(); return true; } /** * It return true if the buffer is empty */ inline bool empty() { return (pwrite == pread); } /** * It return true if there is at least one room in the buffer */ inline bool available() { const unsigned long next = pwrite + ((pwrite+1>=size)?(1-size):1); return (next != pread); } /** * TODO */ inline size_t buffersize() const { return size; }; /** * TODO */ inline bool push(void * const data) { assert(data); const unsigned long next = pwrite + ((pwrite+1>=size)?(1-size):1); if (next != pread) { buf[pwrite] = data; /* We have to ensure that all writes have been committed * in memory before we change the value of the pwrite * reference otherwise the reader can read stale data. */ WMB(); pwrite =next; return true; } return false; } /** * TODO */ inline bool pop(void ** data) { assert(data); if (empty()) return false; *data = buf[pread]; pread += (pread+1 >= size) ? (1-size): 1; return true; } /** * TODO */ inline void reset() { pread=pwrite=0; if (size<=512) for(unsigned long i=0;i<size;++i) buf[i]=0; else memset(buf,0,size*sizeof(void*)); } /** * TODO */ inline unsigned long length() const { // long len = pwrite-pread; // if (len>=0) return len; //return size+len; long tpread=pread, tpwrite=pwrite; long len = tpwrite-tpread; if (len>0) return (unsigned long)len; if (len<0) return (unsigned long)(size+len); if (buf[tpwrite]==NULL) return 0; return size; } }; /*! * @} * \endlink */ } // namespace ff #endif /* FF_SWSR_PTR_BUFFER_HPP */
[ "noreply@github.com" ]
Binipro.noreply@github.com
284ddb275dbc2fcc82d1981b8188702317f069c2
569998fc0c7e7455e84f9e3c98bdd198f4952354
/src/test/torcontrol_tests.cpp
7720e685e163954092e91cd6e3d916d499f6df45
[ "MIT" ]
permissive
j00v/BALLcoin
dab6bae8cad26906ab208fa495e7069af3299afc
77b8407ba4e9d788b374b7a4fdc58f165115c8da
refs/heads/master
2022-12-24T22:54:07.169753
2020-10-01T14:09:32
2020-10-01T14:09:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,150
cpp
// Copyright (c) 2017 The Zcash developers // Copyright (c) 2017 The BALLcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "torcontrol.cpp" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(torcontrol_tests) void CheckSplitTorReplyLine(std::string input, std::string command, std::string args) { BOOST_TEST_MESSAGE(std::string("CheckSplitTorReplyLine(") + input + ")"); auto ret = SplitTorReplyLine(input); BOOST_CHECK_EQUAL(ret.first, command); BOOST_CHECK_EQUAL(ret.second, args); } BOOST_AUTO_TEST_CASE(util_SplitTorReplyLine) { // Data we should receive during normal usage CheckSplitTorReplyLine( "PROTOCOLINFO BALLERSION", "PROTOCOLINFO", "BALLERSION"); CheckSplitTorReplyLine( "AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE=\"/home/x/.tor/control_auth_cookie\"", "AUTH", "METHODS=COOKIE,SAFECOOKIE COOKIEFILE=\"/home/x/.tor/control_auth_cookie\""); CheckSplitTorReplyLine( "AUTH METHODS=NULL", "AUTH", "METHODS=NULL"); CheckSplitTorReplyLine( "AUTH METHODS=HASHEDPASSWORD", "AUTH", "METHODS=HASHEDPASSWORD"); CheckSplitTorReplyLine( "VERSION Tor=\"0.2.9.8 (git-a0df013ea241b026)\"", "VERSION", "Tor=\"0.2.9.8 (git-a0df013ea241b026)\""); CheckSplitTorReplyLine( "AUTHCHALLENGE SERVERHASH=aaaa SERVERNONCE=bbbb", "AUTHCHALLENGE", "SERVERHASH=aaaa SERVERNONCE=bbbb"); // Other valid inputs CheckSplitTorReplyLine("COMMAND", "COMMAND", ""); CheckSplitTorReplyLine("COMMAND SOME ARGS", "COMMAND", "SOME ARGS"); // These inputs are valid because PROTOCOLINFO accepts an OtherLine that is // just an OptArguments, which enables multiple spaces to be present // between the command and arguments. CheckSplitTorReplyLine("COMMAND ARGS", "COMMAND", " ARGS"); CheckSplitTorReplyLine("COMMAND EVEN+more ARGS", "COMMAND", " EVEN+more ARGS"); } void CheckParseTorReplyMapping(std::string input, std::map<std::string,std::string> expected) { BOOST_TEST_MESSAGE(std::string("CheckParseTorReplyMapping(") + input + ")"); auto ret = ParseTorReplyMapping(input); BOOST_CHECK_EQUAL(ret.size(), expected.size()); auto r_it = ret.begin(); auto e_it = expected.begin(); while (r_it != ret.end() && e_it != expected.end()) { BOOST_CHECK_EQUAL(r_it->first, e_it->first); BOOST_CHECK_EQUAL(r_it->second, e_it->second); r_it++; e_it++; } } BOOST_AUTO_TEST_CASE(util_ParseTorReplyMapping) { // Data we should receive during normal usage CheckParseTorReplyMapping( "METHODS=COOKIE,SAFECOOKIE COOKIEFILE=\"/home/x/.tor/control_auth_cookie\"", { {"METHODS", "COOKIE,SAFECOOKIE"}, {"COOKIEFILE", "/home/x/.tor/control_auth_cookie"}, }); CheckParseTorReplyMapping( "METHODS=NULL", { {"METHODS", "NULL"}, }); CheckParseTorReplyMapping( "METHODS=HASHEDPASSWORD", { {"METHODS", "HASHEDPASSWORD"}, }); CheckParseTorReplyMapping( "Tor=\"0.2.9.8 (git-a0df013ea241b026)\"", { {"Tor", "0.2.9.8 (git-a0df013ea241b026)"}, }); CheckParseTorReplyMapping( "SERVERHASH=aaaa SERVERNONCE=bbbb", { {"SERVERHASH", "aaaa"}, {"SERVERNONCE", "bbbb"}, }); CheckParseTorReplyMapping( "ServiceID=exampleonion1234", { {"ServiceID", "exampleonion1234"}, }); CheckParseTorReplyMapping( "PrivateKey=RSA1024:BLOB", { {"PrivateKey", "RSA1024:BLOB"}, }); CheckParseTorReplyMapping( "ClientAuth=bob:BLOB", { {"ClientAuth", "bob:BLOB"}, }); // Other valid inputs CheckParseTorReplyMapping( "Foo=Bar=Baz Spam=Eggs", { {"Foo", "Bar=Baz"}, {"Spam", "Eggs"}, }); CheckParseTorReplyMapping( "Foo=\"Bar=Baz\"", { {"Foo", "Bar=Baz"}, }); CheckParseTorReplyMapping( "Foo=\"Bar Baz\"", { {"Foo", "Bar Baz"}, }); // Escapes CheckParseTorReplyMapping( "Foo=\"Bar\\ Baz\"", { {"Foo", "Bar Baz"}, }); CheckParseTorReplyMapping( "Foo=\"Bar\\Baz\"", { {"Foo", "BarBaz"}, }); CheckParseTorReplyMapping( "Foo=\"Bar\\@Baz\"", { {"Foo", "Bar@Baz"}, }); CheckParseTorReplyMapping( "Foo=\"Bar\\\"Baz\" Spam=\"\\\"Eggs\\\"\"", { {"Foo", "Bar\"Baz"}, {"Spam", "\"Eggs\""}, }); CheckParseTorReplyMapping( "Foo=\"Bar\\\\Baz\"", { {"Foo", "Bar\\Baz"}, }); // C escapes CheckParseTorReplyMapping( "Foo=\"Bar\\nBaz\\t\" Spam=\"\\rEggs\" Octals=\"\\1a\\11\\17\\18\\81\\377\\378\\400\\2222\" Final=Check", { {"Foo", "Bar\nBaz\t"}, {"Spam", "\rEggs"}, {"Octals", "\1a\11\17\1" "881\377\37" "8\40" "0\222" "2"}, {"Final", "Check"}, }); CheckParseTorReplyMapping( "Valid=Mapping Escaped=\"Escape\\\\\"", { {"Valid", "Mapping"}, {"Escaped", "Escape\\"}, }); CheckParseTorReplyMapping( "Valid=Mapping Bare=\"Escape\\\"", {}); CheckParseTorReplyMapping( "OneOctal=\"OneEnd\\1\" TwoOctal=\"TwoEnd\\11\"", { {"OneOctal", "OneEnd\1"}, {"TwoOctal", "TwoEnd\11"}, }); // Special handling for null case // (needed because string comparison reads the null as end-of-string) BOOST_TEST_MESSAGE(std::string("CheckParseTorReplyMapping(Null=\"\\0\")")); auto ret = ParseTorReplyMapping("Null=\"\\0\""); BOOST_CHECK_EQUAL(ret.size(), 1); auto r_it = ret.begin(); BOOST_CHECK_EQUAL(r_it->first, "Null"); BOOST_CHECK_EQUAL(r_it->second.size(), 1); BOOST_CHECK_EQUAL(r_it->second[0], '\0'); // A more complex valid grammar. PROTOCOLINFO accepts a VersionLine that // takes a key=value pair followed by an OptArguments, making this valid. // Because an OptArguments contains no semantic data, there is no point in // parsing it. CheckParseTorReplyMapping( "SOME=args,here MORE optional=arguments here", { {"SOME", "args,here"}, }); // Inputs that are effectively invalid under the target grammar. // PROTOCOLINFO accepts an OtherLine that is just an OptArguments, which // would make these inputs valid. However, // - This parser is never used in that situation, because the // SplitTorReplyLine parser enables OtherLine to be skipped. // - Even if these were valid, an OptArguments contains no semantic data, // so there is no point in parsing it. CheckParseTorReplyMapping("ARGS", {}); CheckParseTorReplyMapping("MORE ARGS", {}); CheckParseTorReplyMapping("MORE ARGS", {}); CheckParseTorReplyMapping("EVEN more=ARGS", {}); CheckParseTorReplyMapping("EVEN+more ARGS", {}); } BOOST_AUTO_TEST_SUITE_END()
[ "matthew@waterfall-family.co.uk" ]
matthew@waterfall-family.co.uk
f8321ebe252e4c88dd76c882437b824a23f2790f
88f1ecced6c151aa8f313db7d457ebd4aec5ec7f
/MultipleFileClass/MultipleFileClass/Complex.h
6b26c068a9df80976f9bcbbab57aea8db2f3a171
[]
no_license
kalyanramu/LocalGitRepo
a99f239a4d3bb71fe820f67064bf265fbbe47a53
d73c4c95b07988ac1ba3b1093c24efd0c05b37cd
refs/heads/master
2021-01-19T11:03:09.682042
2013-11-06T17:38:43
2013-11-06T17:38:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
217
h
class Complex { private: double real, imaginary; public: Complex(double x=0.0, double y=0.0):real(x),imaginary(y){}; double re(); double im(); double mag(); void operator+(const Complex& number); ~Complex(); };
[ "kalyanramu@gmail.com" ]
kalyanramu@gmail.com
3c66e0431f66c6596243d0cbe5cb8ffc035bc45b
a78aa555b175e699c96553e3d714066bcc281ed8
/model/owner.h
ee08a948cdc62a1aa37280efd9001c1b1f968ab4
[ "Apache-2.0" ]
permissive
rdffg/bcaa_importer
0cb503c289002e573bcf8996178381cf001da742
f92e0b39673b5c557540154d4567c53a15adadcd
refs/heads/master
2021-08-28T16:05:39.936780
2021-08-20T20:00:53
2021-08-20T20:00:53
92,878,678
0
0
null
null
null
null
UTF-8
C++
false
false
2,302
h
#ifndef OWNER_H #define OWNER_H #include <memory> #include "QDjangoModel.h" #define OWNERSHIPGROUP_PROPERTY "ownershipGroup" namespace model { class OwnershipGroup; class Owner : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString firstname READ firstname WRITE setFirstname) Q_PROPERTY(QString middleName READ middleName WRITE setMiddleName) Q_PROPERTY(QString middleInitial READ middleInitial WRITE setMiddleInitial) Q_PROPERTY(QString companyOrLastName READ companyOrLastName WRITE setCompanyOrLastName) Q_PROPERTY(QString equityType READ equityType WRITE setEquityType) Q_PROPERTY(QString equityTypeDescription READ equityTypeDescription WRITE setEquityTypeDescription) Q_PROPERTY(QString ownerSequenceID READ ownerSequenceID WRITE setOwnerSequenceID) Q_PROPERTY(QString id READ id WRITE setId) Q_CLASSINFO("__meta__", "db_table=owner") Q_CLASSINFO("firstname", "null=true") Q_CLASSINFO("middleName", "null=true") Q_CLASSINFO("middleInitial", "null=true") Q_CLASSINFO("companyOrLastName","null=true") Q_CLASSINFO("equityType", "null=true") Q_CLASSINFO("equityTypeDescription", "null=true") Q_CLASSINFO("ownerSequenceID", "null=true max_length=32") Q_CLASSINFO("id", "primary_key=true max_length=32") public: Owner(QObject *parent=0); QString firstname() const; void setFirstname(const QString &firstname); QString middleName() const; void setMiddleName(const QString &middleName); QString middleInitial() const; void setMiddleInitial(const QString &middleInitial); QString companyOrLastName() const; void setCompanyOrLastName(const QString &companyOrLastName); QString equityType() const; void setEquityType(const QString &equityType); QString equityTypeDescription() const; void setEquityTypeDescription(const QString &equityTypeDescription); QString ownerSequenceID() const; void setOwnerSequenceID(const QString &ownerSequenceID); QString id() const; void setId(const QString &bca_id); private: QString m_id; QString m_firstname; QString m_middleName; QString m_middleInitial; QString m_companyOrLastName; QString m_equityType; QString m_equityTypeDescription; QString m_ownerSequenceID; }; } #endif // OWNER_H
[ "dmahoney@rdffg.bc.ca" ]
dmahoney@rdffg.bc.ca
0493c25cc052694284339fcffd1413cedbbf30e4
eda7f1e5c79682bf55cfa09582a82ce071ee6cee
/aspects/fluid/source/GunnsFluidSourceBoundary.hh
27eb6b577beaae08a468aa715cb547f04a3fe035
[ "LicenseRef-scancode-us-govt-public-domain", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nasa/gunns
923f4f7218e2ecd0a18213fe5494c2d79a566bb3
d5455e3eaa8b50599bdb16e4867a880705298f62
refs/heads/master
2023-08-30T06:39:08.984844
2023-07-27T12:18:42
2023-07-27T12:18:42
235,422,976
34
11
NOASSERTION
2023-08-30T15:11:41
2020-01-21T19:21:16
C++
UTF-8
C++
false
false
10,969
hh
#ifndef GunnsFluidSourceBoundary_EXISTS #define GunnsFluidSourceBoundary_EXISTS /** @file @brief GUNNS Fluid Source Boundary Link declarations @defgroup TSM_GUNNS_FLUID_SOURCE_BOUNDARY GUNNS Fluid Source Boundary Link @ingroup TSM_GUNNS_FLUID_SOURCE @copyright Copyright 2019 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. @details PURPOSE: - (Classes for the GUNNS Fluid Source Boundary link.) REFERENCE: - (TBD) ASSUMPTIONS AND LIMITATIONS: - (TBD) LIBRARY DEPENDENCY: - ((GunnsFluidSourceBoundary.o)) PROGRAMMERS: - ((Jason Harvey) (L-3 Communications) (2016-01) (Initial)) @{ */ #include "core/GunnsFluidLink.hh" #include "software/SimCompatibility/TsSimCompatibility.hh" //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Fluid Source Boundary Configuration Data /// /// @details The sole purpose of this class is to provide a data structure for the Fluid Source /// Boundary configuration data. //////////////////////////////////////////////////////////////////////////////////////////////////// class GunnsFluidSourceBoundaryConfigData : public GunnsFluidLinkConfigData { public: bool mFlipFlowSign; /**< (--) trick_chkpnt_io(**) True makes positive flow rate go out of the node. */ bool mTraceCompoundsOnly; /**< (--) trick_chkpnt_io(**) True only flows trace compounds, not bulk fluid. */ /// @brief Default constructs this Fluid Source Boundary configuration data. GunnsFluidSourceBoundaryConfigData(const std::string& name = "", GunnsNodeList* nodes = 0, const bool flipFlowSign = false, const bool traceCompoundsOnly = false); /// @brief Default destructs this Fluid Source Boundary configuration data. virtual ~GunnsFluidSourceBoundaryConfigData(); /// @brief Copy constructs this Fluid Source Boundary configuration data. GunnsFluidSourceBoundaryConfigData(const GunnsFluidSourceBoundaryConfigData& that); private: /// @brief Assignment operator unavailable since declared private and not implemented. GunnsFluidSourceBoundaryConfigData& operator =(const GunnsFluidSourceBoundaryConfigData&); }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Fluid Source Boundary Input Data /// /// @details The sole purpose of this class is to provide a data structure for the Fluid Source /// Boundary input data. //////////////////////////////////////////////////////////////////////////////////////////////////// class GunnsFluidSourceBoundaryInputData : public GunnsFluidLinkInputData { public: double mFlowDemand; /**< (kg/s) trick_chkpnt_io(**) Initial demanded mass flow rate of the link. */ PolyFluidInputData* mInternalFluid; /**< (--) trick_chkpnt_io(**) Initial fluid properties of the link flow. */ /// @brief Default constructs this Fluid Source Boundary input data. GunnsFluidSourceBoundaryInputData(const bool malfBlockageFlag = false, const double malfBlockageValue = 0.0, const double flowDemand = 0.0, PolyFluidInputData* internalFluid = 0); /// @brief Default destructs this Fluid Source Boundary input data. virtual ~GunnsFluidSourceBoundaryInputData(); /// @brief Copy constructs this Fluid Source Boundary input data. GunnsFluidSourceBoundaryInputData(const GunnsFluidSourceBoundaryInputData& that); private: /// @details Assignment operator unavailable since declared private and not implemented. GunnsFluidSourceBoundaryInputData& operator =(const GunnsFluidSourceBoundaryInputData&); }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief GUNNS Fluid Source Boundary class /// /// @details This link forces fluid with specified properties into or out of a single fluid node. /// This can be used as a flow boundary condition at the attached node. This link /// controls the flow fluid mixture and temperature, allowing for specific fluid /// components to flow independently of each other or the attached node properties. /// /// This link is similar to GunnsFluidSource except for these key differences: /// - This link is a 1-port link. /// - It allows the sign convention of the mFlowDemand input to be reversed. /// - It defines the internal fluid, whereas GunnsFluidSource doesn't. /// - The internal fluid can contain trace compounds, making this link a source of trace /// compounds to/from the node. //////////////////////////////////////////////////////////////////////////////////////////////////// class GunnsFluidSourceBoundary : public GunnsFluidLink { TS_MAKE_SIM_COMPATIBLE(GunnsFluidSourceBoundary); public: /// @brief Default Constructor. GunnsFluidSourceBoundary(); /// @brief Default Destructor. virtual ~GunnsFluidSourceBoundary(); /// @brief Initialize void initialize(const GunnsFluidSourceBoundaryConfigData& configData, const GunnsFluidSourceBoundaryInputData& inputData, std::vector<GunnsBasicLink*>& networkLinks, const int port0); /// @brief Step method for updating the link. virtual void step(const double dt); /// @brief Method for computing the flows across the link. virtual void computeFlows(const double dt); /// @brief Method for transporting the flows across the link. virtual void transportFlows(const double dt); /// @brief Sets the flow demand for the link. virtual void setFlowDemand(const double toFlowDemand); /// @brief Sets the flow state of the link. virtual void setFlowState(PolyFluid* withState); /// @brief Returns the flow demand of the link. virtual double getFlowDemand() const; /// @brief Moves the internal fluid to or from the attached node. virtual void transportFluid(const bool forcedOutflow, const int fromPort = 0, const int toPort = 1); protected: bool mFlipFlowSign; /**< (--) trick_chkpnt_io(**) True makes positive flow rate go out of the node. */ bool mTraceCompoundsOnly; /**< (--) trick_chkpnt_io(**) True only flows trace compounds, not bulk fluid. */ double mFlowDemand; /**< (kg/s) User demanded mass flow rate through the link. */ double* mTraceCompoundRates; /**< (--) trick_chkpnt_io(**) Source flow rate of the trace compounds relative to mFlowDemand. */ /// @brief Virtual method for derived links to perform their restart functions. virtual void restartModel(); /// @brief Builds the source vector terms of the links contribution to the network. virtual void buildSource(); /// @brief Validates the initialization of this GUNNS Fluid Source Boundary. void validate(const GunnsFluidSourceBoundaryConfigData& configData, const GunnsFluidSourceBoundaryInputData& inputData) const; /// @brief Computes mPower for the aspect-specific implementation. virtual void computePower(); private: /// @details Define the number of ports this link class has. All objects of the same link /// class always have the same number of ports. We use an enum rather than a /// static const int so that we can reuse the NPORTS name and allow each class to /// define its own value. enum {NPORTS = 1}; /// @brief Copy constructor unavailable since declared private and not implemented. GunnsFluidSourceBoundary(const GunnsFluidSourceBoundary& that); /// @brief Assignment operator unavailable since declared private and not implemented. GunnsFluidSourceBoundary& operator =(const GunnsFluidSourceBoundary& that); }; /// @} //////////////////////////////////////////////////////////////////////////////////////////////////// /// @return double (kg/s) Returns the flow demand. /// /// @details Returns the flow demand. //////////////////////////////////////////////////////////////////////////////////////////////////// inline double GunnsFluidSourceBoundary::getFlowDemand() const { return mFlowDemand; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @param[in] toFlowDemand (kg/s) flow demand. /// /// @details Sets the state of the fluid inside the fluid source link. //////////////////////////////////////////////////////////////////////////////////////////////////// inline void GunnsFluidSourceBoundary::setFlowDemand(const double toFlowDemand) { mFlowDemand = toFlowDemand; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @param[in] withState (--) Fluid State information. /// /// @details Sets the state of the fluid inside the fluid source link. //////////////////////////////////////////////////////////////////////////////////////////////////// inline void GunnsFluidSourceBoundary::setFlowState(PolyFluid* withState) { mInternalFluid->setState(withState); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Builds the source vector terms of the link's contribution to the network. //////////////////////////////////////////////////////////////////////////////////////////////////// inline void GunnsFluidSourceBoundary::buildSource() { mSourceVector[0] = mFlux; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Hydraulic power in the link is volumetric flow * potential drop. Note that this is /// positive for flow going into the node, since the link is adding power to the network. /// Since potential is in units of kPa we must convert it to Pa to express power in Watts. //////////////////////////////////////////////////////////////////////////////////////////////////// inline void GunnsFluidSourceBoundary::computePower() { mPower = UnitConversion::PA_PER_KPA * mVolFlowRate * mPotentialVector[0]; } #endif
[ "jason.l.harvey@nasa.gov" ]
jason.l.harvey@nasa.gov
2fc91a02683c914b17d8aaecc3146747a118a775
b16d370b74422644e2cc92cb1573f2495bb6c637
/c/cf/cf798b.cc
51ea26b0182fc70013c278ee6e7c23db47d9a779
[]
no_license
deniskokarev/practice
8646a3a29b9e4f9deca554d1a277308bf31be188
7e6742b6c24b927f461857a5509c448ab634925c
refs/heads/master
2023-09-01T03:37:22.286458
2023-08-22T13:01:46
2023-08-22T13:01:46
76,293,257
0
0
null
null
null
null
UTF-8
C++
false
false
748
cc
#include <iostream> #include <vector> /* CodeForces CF798B problem */ using namespace std; // transform a->b int diff(const string &a, const string &b) { if (a.length() != b.length()) return -1; int l = a.length(); for (int i=0; i<l; i++) { for (int j=0; j<l; j++) { int n; for (n=0; n<l && a[(i+n)%l]==b[(j+n)%l]; n++); if (n == l) return j; } } return -1; } int main(int argc, char **argv) { int n; cin >> n; vector<string> ss(n); for (auto &s:ss) cin >> s; int mn = INT_MAX; for (int i=0; i<n; i++) { int sum = 0; for (int j=0; j<n; j++) { int d = diff(ss[i], ss[j]); if (d < 0) { cout << -1 << endl; return 0; } sum += d; } mn = min(mn, sum); } cout << mn << endl; return 0; }
[ "d_kokarev@mail.ru" ]
d_kokarev@mail.ru
1593202e1acc640f457beb9fca79fc70856cc781
816f5be4c67e710ee26bc94bc259790227677faf
/balloonride/proj.android/jni/BalloonRide/main.cpp
bbe27077a179d82525fa19c20ed0b649e935c4a4
[]
no_license
diegohcg/cocos2dx-examples
8f4862ad55eff9296a12fa3bbfbe3a80e0654edb
a3f1127fcabc93d488517b99bcda0998150ed6db
refs/heads/master
2021-01-20T12:00:50.715983
2014-03-12T21:38:14
2014-03-12T21:38:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,125
cpp
#include "AppDelegate.h" #include "platform/android/jni/JniHelper.h" #include <jni.h> #include <android/log.h> #define LOG_TAG "main" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #include <cocos2d.h> using namespace cocos2d; extern "C" { jint JNI_OnLoad(JavaVM *vm, void *reserved) { JniHelper::setJavaVM(vm); return JNI_VERSION_1_4; } void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h) { if (!CCDirector::sharedDirector()->getOpenGLView()) { CCEGLView *view = CCEGLView::sharedOpenGLView(); view->setFrameSize(w, h); AppDelegate *pAppDelegate = new AppDelegate(); CCApplication::sharedApplication()->run(); } else { ccDrawInit(); ccGLInvalidateStateCache(); CCShaderCache::sharedShaderCache()->reloadDefaultShaders(); CCTextureCache::reloadAllTextures(); //CCNotificationCenter::sharedNotificationCenter()->postNotification(EVNET_COME_TO_FOREGROUND, NULL); CCDirector::sharedDirector()->setGLDefaultValues(); } } }
[ "diego.gonzalez@openbossa.org" ]
diego.gonzalez@openbossa.org
a11dc375082e28087fcc1bd6735d6afcb610228a
0b4a483d33ee5bce73729bafa163b97f608074b6
/Assignments/BST/BSTree.h
e29be5466ccb207fee61822b495fa7c4b1f35672
[]
no_license
edgar2020/colaborative_labs_and_assignments_CS10C
0a3617448855dad571e0e84050a4bd043fda5371
902c58b0d9bc5b39f9c8926ca9c06c64acdd5dbc
refs/heads/master
2023-05-19T21:42:51.840792
2021-06-03T16:33:48
2021-06-03T16:33:48
352,845,409
0
0
null
2021-06-03T16:33:49
2021-03-30T02:25:09
C++
UTF-8
C++
false
false
3,307
h
#ifndef __BSTREE_H__ #define __BSTREE_H__ #include "Node.h" #include <string> #include <sstream> #include <fstream> #include <iostream> class BSTree { private: Node *root; void preOrder(Node*) const; void postOrder(Node*) const; void inOrder(Node*) const; int height(const string&, Node*) const; void visualizeTree(ofstream &, Node*); void remove(Node*, const string &key); bool search(const string&, Node*) const; public: /* Constructors */ /* Default constructor */ BSTree(); ~BSTree(); void destructorHelper(Node*); /* Mutators */ /* Insert an item into the binary search tree. Be sure to keep BST properties. When an item is first inserted into the tree the count should be set to 1. When adding a duplicate string (case sensitive), rather than adding another node, the count variable should be incremented */ void insert(const string &newString); /* Remove a specified string from the tree. Be sure to maintain all bianry search tree properties. If removing a node with a count greater than 1, just decrement the count, otherwise, if the count is simply 1, remove the node. You MUST follow the remove algorithm shown in the slides and discussed in class or else your program will not pass the test functions. When removing, if removing a leaf node, simply remove the leaf. Otherwise, if the node to remove has a left child, replace the node to remove with the largest string value that is smaller than the current string to remove (i.e. find the largest value in the left subtree of the node to remove). If the node has no left child, replace the node to remove with the smallest value larger than the current string to remove (i.e. find the smallest value in the right subtree of the node to remove. */ void remove(const string &key); /* Accessors */ /* Search for a string in the binary search tree. It should return true if the string is in the tree, and false otherwise. */ bool search(const string &key) const; /* Find and return the largest value in the tree. Return an empty string if the tree is empty */ string largest() const; /* Find and return the smallest value in the tree. Return an emtpy string if the tree is empty */ string smallest() const; /* Compute and return the height of a particular string in the tree. The height of a leaf node is 0 (count the number of edges on the longest path). Return -1 if the string does not exist. */ int height(const string&) const; /* Printing */ /* For all printing orders, each node should be displayed as follows: <string> (<count>) e.g. goodbye(1), Hello World(3) */ void preOrder() const; void postOrder() const; void inOrder() const; void visualizeTree(const string &); }; #endif // __BSTREE_H__
[ "evmelendrez@gmail.com" ]
evmelendrez@gmail.com
36e4c5c38a4816fcc1fafd8a00a581abb92f4a11
61ba304e703f0eff40e4ad3424a8667f09afe5ee
/c++/shell_sort.cpp
4981306fdf61bd4c9246688ed855e65195e871c3
[]
no_license
sagarbabalsure/Codes-of-All-Languages
68ccea920a5d60330c222746085d1f9edea6b22c
78fc45fbbd53949f7d3114060f1b8f47131b2f53
refs/heads/master
2023-02-01T19:42:27.384375
2020-12-19T05:55:36
2020-12-19T05:55:36
313,943,421
0
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
#include<iostream> using namespace std; void ShellSort(int a[],int n) { for(int gap=n/2;gap>0;gap=gap/2){ for(int i=0,g=gap;i<gap,g<n;i++,g++){ if(a[i]>a[g]) { int temp=a[i]; a[i]=a[g]; a[g]=temp; } } } } int main() { int a[100],n; cin>>n; for (int i = 0; i < n; ++i) { cin>>a[i]; } ShellSort(a,n); for (int i = 0; i < n; ++i) { cout<<a[i]<<" "; } return 0; }
[ "sagarbabalsure@gmail.com" ]
sagarbabalsure@gmail.com
24b5dace9253080cebe8da3844bee9102dd26b81
13bbebfac96cfaf50ac80c0f72fa5d462ee6bdf2
/src/2798_blackjack.cpp
5bb75ee9fe371f2275c0418ba3ab4c1f0760e748
[ "Apache-2.0" ]
permissive
programrubber/algo_dic
2e4c309d5e9a188b43441f3ea4ca0f3c9f132bc8
aa0e380795c09dbc6d6b351547ccc7b08054ca90
refs/heads/master
2021-06-29T22:38:30.204453
2020-10-31T19:11:05
2020-10-31T19:11:05
180,481,779
0
0
null
null
null
null
UTF-8
C++
false
false
1,646
cpp
// https://www.acmicpc.net/submit/2798 왜 인지 모르겠지만 런타임 오류가 발생하고 있음... #include "iostream" #define CARDSIZE 101 using namespace std; // 딜러는 N장의 카드를 보이도록 놓는다. 그런 후 딜러는 숫자 M을 외친다. // 플레이어는 3장의 카드를 골라야 한다. // 플레이어는 M을 넘지 않으면서 M과 근접하도록 해야한다. int N, M; // N: 카드의 갯수, M을 외침 // 조합 int K = 3; // 고를수 있는 카드 수 int cards[CARDSIZE]; int choise[4]; int combCnt=0; int combList[CARDSIZE][4]; int pointList[CARDSIZE]; void comb(int num, int idx) { if (K<idx) { for (int i=1; i<=K; i++) { combList[combCnt][i] = choise[i]; } combCnt++; return; } if (N<num) return; choise[idx] = cards[num]; comb(num+1, idx+1); comb(num+1, idx); } void pointCalc() { for (int i=0; i<combCnt; i++) { int tot = 0; for (int j=1; j<=K; j++) { tot += combList[i][j]; } pointList[i] = tot; } } void pointSelect() { int val = 0; for (int i=0; i<combCnt; i++) { int tot = pointList[i]; if (M < tot) continue; if (val < tot) { val = tot; } } printf() cout << val; } int main () { cin >> N; cin >> M; if (3>N || N>100) return 0; if (10>M || M>300000) return 0; for (int i=1; i<=N; i++) { cin >> cards[i]; } comb(1, 1); // 조합을 구한다. pointCalc(); // 조합의 포인트를 계산한다. pointSelect(); // 선택된 부분을 출력한다. }
[ "noreply@github.com" ]
programrubber.noreply@github.com
38423216f492ab32faa5923d0596038810607956
d17b8c418f619acf257da9bc873ee32c92a05735
/ContraRemake/Client/Message.cpp
5b434ad9f73afbd55796ac294138d86bc26b5570
[]
no_license
Giova262/Taller-de-Programacion-I
1195c0bc5e050aa96d66eb875b0582ac6a7c27fb
174d00f1e173de7a684ad25b86bc8f525d3ef2fb
refs/heads/master
2020-03-27T20:57:43.185540
2018-11-23T14:01:02
2018-11-23T14:01:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
891
cpp
/* * Message.cpp * * Created on: Oct 12, 2018 * Author: maximiliano */ #include "Message.hh" Message::Message(std::string unique_param) { std::strcpy(messageContent, unique_param.c_str()); } Message::Message(MsgHeader header1, MsgHeader header2, std::string param1, std::string param2, std::string param3, std::string param4) { std::string str = (std::to_string(header1) + "," + std::to_string(header2) + "," + param1 + "," + param2 + "," + param3 + "," + param4 + ";"); std::strcpy(messageContent, str.c_str()); } Message::Message(MsgHeader header1, MsgHeader header2, int param1, int param2, int param3, int param4) { std::string str = (std::to_string(header1) + "," + std::to_string(header2) + "," + std::to_string(param1) + "," + std::to_string(param2) + "," + std::to_string(param3) + "," + std::to_string(param4) + ";"); std::strcpy(messageContent, str.c_str()); }
[ "masterpat45@gmail.com" ]
masterpat45@gmail.com
51f2019e8851f4f650f4c5ae39e0bec15609800d
4b630e22db0216720e3097bdebe62a884e554012
/1110/permu.cpp
d60bfb8313bc108c985cd2224c01b381633e719c
[]
no_license
nyanshell/Gestapolur-Code-Storage
98da5662164cf4dac931a876200e595ae2b667df
3bd949da41dc8d7cacfe1792a2b3acaaeaa38c66
refs/heads/master
2021-05-28T04:37:29.718337
2012-05-30T07:26:04
2012-05-30T07:26:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
846
cpp
/* All Permulation Solutions write by gestapolur 2011-10-08 */ #include<iostream> #define MAXN 10005 using namespaces std; int n ; int con[ MAXN ] , st[ MAXN ] , org[ MAXN ] , pre[ MAXN ]; bool hash[ MAXN ]; void dfs() { int pos ; do{ if( pos > n ) { for( i = 1 ; i <= n ; ++ i ) cout<<org[ con[ i ] ]<<" "; cout<<"\n"; y st[ ++ st[ 0 ] ] = con[ i ]; } else { if( con[ pos ] == n ) st[ ++ st[ 0 ] ] = con[ pos -- ]; else { tmp = con[ ++ pos ] con[ ++ pos ] = st[ st[ 0 ] -- ] ; } } }while( pos > 0 ) } void init() { cin>>n; st[ 0 ] = n ; for( int i = 1 ; i <= n ; ++ i ) { cin>>org[ i ]; st[ i ] = n - i + 1 ; con[ i ] = 1 ; } } int main() { return 0 ; }
[ "gestapolur@gmail" ]
gestapolur@gmail
085f7f72c6bffa717a9cbd7f308f74484c95a2c9
403d878a64fa6db384eb2de1170eb87dba598664
/src/menu_text.cpp
8f5eed47d81b4d8b5f865e15c7083c5b08f57617
[]
no_license
stefanbankow/SDL2.0_BreakoutClone
82f6b9d32bb76af563328ca4f5897c2d30793dbc
fc8eafe3f67421c23f8a265623930efba843e9e2
refs/heads/master
2023-04-30T10:28:05.832392
2021-05-15T14:10:09
2021-05-15T14:10:09
359,973,520
2
0
null
null
null
null
UTF-8
C++
false
false
1,109
cpp
#include "menu_text.hpp" MenuText::MenuText(TTF_Font *font, std::string text, SDL_Color color, SDL_Renderer *renderer, int x_pos, int y_pos, int dst_w, int dst_h) { SDL_Color white = {255, 255, 255}; SDL_Surface *tmp_surface = TTF_RenderText_Blended(font, text.c_str(), white); text_texture = SDL_CreateTextureFromSurface(renderer, tmp_surface); SDL_SetTextureColorMod(text_texture, color.r, color.g, color.b); //Use color modulation instead of directly setting the color in order to make it easier to change it when it's active SDL_FreeSurface(tmp_surface); //Memory isn't used anymore so it should be freed this->x_pos = x_pos; this->y_pos = y_pos; this->dst_w = dst_w; this->dst_h = dst_h; } void MenuText::set_color(Uint8 r, Uint8 g, Uint8 b) { SDL_SetTextureColorMod(text_texture, r, g, b); } MenuText::~MenuText() { SDL_DestroyTexture(text_texture); } void MenuText::render(SDL_Renderer *renderer) { SDL_Rect dst_rect = {x_pos, y_pos, dst_w, dst_h}; SDL_RenderCopy(renderer, text_texture, nullptr, &dst_rect); }
[ "stefanbankow@gmail.com" ]
stefanbankow@gmail.com
b7c4c9f523be4ebf4559731cf2487e326a5c7ab8
a06a9ae73af6690fabb1f7ec99298018dd549bb7
/_Library/_Include/boost/fusion/include/make_fused_procedure.hpp
7492ee8eec675bb855991f3aeb5562b9eed48d44
[ "BSL-1.0" ]
permissive
longstl/mus12
f76de65cca55e675392eac162dcc961531980f9f
9e1be111f505ac23695f7675fb9cefbd6fa876e9
refs/heads/master
2021-05-18T08:20:40.821655
2020-03-29T17:38:13
2020-03-29T17:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
761
hpp
/*============================================================================= Copyright (c) 2001-2007 Joel de Guzman 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) ==============================================================================*/ #if !defined(FUSION_INCLUDE_MAKE_FUSED_PROCEDURE) #define FUSION_INCLUDE_MAKE_FUSED_PROCEDURE #include <boost/fusion/support/config.hpp> #include <boost/fusion/functional/generation/make_fused_procedure.hpp> #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "adm.fael.hs@gmail.com" ]
adm.fael.hs@gmail.com
af9119abe77422346212f9638e0e5d02108d1ec1
ca35e86a0e481fd0eec78b8b71581a168eec6411
/src/controller.h
ea262d4c7a84676f5fc0a26ad8280e19d6f29fcd
[]
no_license
zwh42/TRexRun
bc67a09aadaf52af5a21ddebf00d2df5460f6ce6
93faf9bacdafedf076d6c8f27da9ea1ded7b8be4
refs/heads/master
2020-08-03T19:09:18.895533
2019-10-14T18:03:21
2019-10-14T18:03:21
211,856,099
1
0
null
null
null
null
UTF-8
C++
false
false
153
h
#ifndef CONTROLLER_H #define CONTROLLER_H #include "trex.h" class Controller { public: void handel_event(bool &is_running, TRex *trex); }; #endif
[ "zhaowenhao@outlook.com" ]
zhaowenhao@outlook.com
781c07cbcb1f90b3ad8c0f6f49b1c510250e8849
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/locationsrv/location_triggering_api/inc/lbtbctest.h
c8e771bc26182f525315e6d3832f5f61c1194419
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
15,037
h
/* * Copyright (c) 2002 - 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: ?Description * */ #ifndef LBTBCTEST_H #define LBTBCTEST_H // INCLUDES #include <StifLogger.h> #include <TestScripterInternal.h> #include <StifTestModule.h> #include <TestclassAssert.h> // CONSTANTS //const ?type ?constant_var = ?constant; // MACROS //#define ?macro ?macro_def #define TEST_CLASS_VERSION_MAJOR 51 #define TEST_CLASS_VERSION_MINOR 9 #define TEST_CLASS_VERSION_BUILD 52 // Logging path _LIT( KlbtbctestLogPath, "\\logs\\testframework\\lbtbctest\\" ); // Log file _LIT( KlbtbctestLogFile, "lbtbctest.txt" ); _LIT( KlbtbctestLogFileWithTitle, "lbtbctest_[%S].txt" ); // FUNCTION PROTOTYPES //?type ?function_name(?arg_list); // FORWARD DECLARATIONS //class ?FORWARD_CLASSNAME; class Clbtbctest; // DATA TYPES //enum ?declaration //typedef ?declaration //extern ?data_type; // CLASS DECLARATION /** * Clbtbctest test class for STIF Test Framework TestScripter. * ?other_description_lines * * @lib ?library * @since ?Series60_version */ NONSHARABLE_CLASS(Clbtbctest) : public CScriptBase { public: // Constructors and destructor /** * Two-phased constructor. */ static Clbtbctest* NewL( CTestModuleIf& aTestModuleIf ); /** * Destructor. */ virtual ~Clbtbctest(); public: // New functions /** * ?member_description. * @since ?Series60_version * @param ?arg1 ?description * @return ?description */ //?type ?member_function( ?type ?arg1 ); public: // Functions from base classes /** * From CScriptBase Runs a script line. * @since ?Series60_version * @param aItem Script line containing method name and parameters * @return Symbian OS error code */ virtual TInt RunMethodL( CStifItemParser& aItem ); protected: // New functions /** * ?member_description. * @since ?Series60_version * @param ?arg1 ?description * @return ?description */ //?type ?member_function( ?type ?arg1 ); protected: // Functions from base classes /** * From ?base_class ?member_description */ //?type ?member_function(); private: /** * C++ default constructor. */ Clbtbctest( CTestModuleIf& aTestModuleIf ); /** * By default Symbian 2nd phase constructor is private. */ void ConstructL(); // Prohibit copy constructor if not deriving from CBase. // ?classname( const ?classname& ); // Prohibit assigment operator if not deriving from CBase. // ?classname& operator=( const ?classname& ); /** * Frees all resources allocated from test methods. * @since ?Series60_version */ void Delete(); /** * Test methods are listed below. */ /** * Example test method. * @since ?Series60_version * @param aItem Script line containing parameters. * @return Symbian OS error code. */ void AssertTrueL( TBool aCondition,const TDesC& aMessage); virtual TInt TestRlbtOpen1L( CStifItemParser& aItem ); virtual TInt TestRlbtOpen2L( CStifItemParser& aItem ); virtual TInt TestRlbtConnect1L( CStifItemParser& aItem ); virtual TInt TestRlbtCreateTriggerL( CStifItemParser& aItem ); virtual TInt TestRlbtCreateTrigger2L( CStifItemParser& aItem ); virtual TInt TestRlbtCreateTrigger3L( CStifItemParser& aItem ); virtual TInt TestRlbtCreateTrigger4L( CStifItemParser& aItem ); virtual TInt TestRlbtCreateTrigger5L( CStifItemParser& aItem ); virtual TInt TestRlbtCancelCreateTriggerL( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggerL( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggers1L( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggers2L( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggers3L( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggers4L( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggers5L( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggers6L( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggers7L( CStifItemParser& aItem ); virtual TInt TestRlbtDeleteTriggers8L( CStifItemParser& aItem ); virtual TInt TestRlbtCancelDeleteTriggersL( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggerLCL( CStifItemParser& aItem ); virtual TInt TestRlbtUpdateTriggerL( CStifItemParser& aItem ); virtual TInt TestRlbtUpdateTrigger2L( CStifItemParser& aItem ); virtual TInt TestRlbtUpdateTrigger3L( CStifItemParser& aItem ); virtual TInt TestRlbtUpdateTrigger4L( CStifItemParser& aItem ); virtual TInt TestRlbtUpdateTrigger5L( CStifItemParser& aItem ); virtual TInt TestRlbtUpdateTrigger6L( CStifItemParser& aItem ); virtual TInt TestRlbtUpdateTrigger7L( CStifItemParser& aItem ); virtual TInt TestRlbtUpdateTrigger8L( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggerStateL( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggersState1L( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggersState2L( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggersState3L( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggersState4L( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggersState5L( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggersState6L( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggersState7L( CStifItemParser& aItem ); virtual TInt TestRlbtSetTriggersState8L( CStifItemParser& aItem ); virtual TInt TestRlbtCancelSetTriggersStateL( CStifItemParser& aItem ); virtual TInt TestRlbtListTriggerIds1L( CStifItemParser& aItem ); virtual TInt TestRlbtListTriggerIds2L( CStifItemParser& aItem ); virtual TInt TestRlbtListTriggerIds3L( CStifItemParser& aItem ); virtual TInt TestRlbtListTriggerIds4L( CStifItemParser& aItem ); virtual TInt TestRlbtListTriggerIds5L( CStifItemParser& aItem ); virtual TInt TestRlbtListTriggerIds6L( CStifItemParser& aItem ); virtual TInt TestRlbtListTriggerIds7L( CStifItemParser& aItem ); virtual TInt TestRlbtListTriggerIds8L( CStifItemParser& aItem ); virtual TInt TestRlbtCancelListTriggerIdsL( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggers1L( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggers2L( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggers3L( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggers4L( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggers5L( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggers6L( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggers7L( CStifItemParser& aItem ); virtual TInt TestRlbtCancelGetTriggersL( CStifItemParser& aItem ); virtual TInt TestRlbtCreateGetTriggerIterator1L( CStifItemParser& aItem ); virtual TInt TestRlbtCreateGetTriggerIterator2L( CStifItemParser& aItem ); virtual TInt TestRlbtCreateGetTriggerIterator3L( CStifItemParser& aItem ); virtual TInt TestRlbtCancelCreateTriggerIteratorL( CStifItemParser& aItem ); virtual TInt TestRlbtNotifyTriggerChangeEventL( CStifItemParser& aItem ); virtual TInt TestRlbtNotifyTriggerChangeEvent2L( CStifItemParser& aItem ); virtual TInt TestRlbtNotifyTriggerFiredL( CStifItemParser& aItem ); virtual TInt TestRlbtNotifyTriggerFired2L( CStifItemParser& aItem ); virtual TInt TestRlbtCancelNotifyTriggerFiredL( CStifItemParser& aItem ); virtual TInt TestRlbtGetFiredTriggersL( CStifItemParser& aItem ); virtual TInt TestRlbtNotifyTriggeringSystemSettingChangeL( CStifItemParser& aItem ); virtual TInt TestRlbtCancelNotifyTriggeringSystemSettingChangeL( CStifItemParser& aItem ); virtual TInt TestRlbtGetTriggeringSystemSettingsL( CStifItemParser& aItem ); virtual TInt TestRlbtCancelAllL( CStifItemParser& aItem ); virtual TInt TestCLbtGeoCell1L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCell2L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCell3L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCell4L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCell5L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCell6L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCell7L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCircle1L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCircle2L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCircle3L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCircle4L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCircle5L(CStifItemParser& aItem); virtual TInt TestCLbtGeoCircle6L(CStifItemParser& aItem); virtual TInt TestCLbtGeoRect1L(CStifItemParser& aItem); virtual TInt TestCLbtGeoRect2L(CStifItemParser& aItem); virtual TInt TestCLbtGeoRect3L(CStifItemParser& aItem); virtual TInt TestCLbtGeoRect4L(CStifItemParser& aItem); virtual TInt TestCLbtGeoRect5L(CStifItemParser& aItem); virtual TInt TestCLbtListTriggerOptions1L(CStifItemParser& aItem); virtual TInt TestCLbtListTriggerOptions2L(CStifItemParser& aItem); virtual TInt TestCLbtListTriggerOptions3L(CStifItemParser& aItem); virtual TInt TestCLbtListTriggerOptions4L(CStifItemParser& aItem); virtual TInt TestCLbtListTriggerOptions5L(CStifItemParser& aItem); virtual TInt TestCLbtListTriggerOptions6L(CStifItemParser& aItem); virtual TInt TestRLbtServerL(CStifItemParser& aItem); virtual TInt TestCLbtSessionTrigger1L(CStifItemParser& aItem); virtual TInt TestCLbtSessionTrigger2L(CStifItemParser& aItem); virtual TInt TestCLbtSessionTrigger3L(CStifItemParser& aItem); virtual TInt TestCLbtSessionTrigger4L(CStifItemParser& aItem); virtual TInt TestCLbtSessionTrigger5L(CStifItemParser& aItem); virtual TInt TestCLbtStartupTrigger1L(CStifItemParser& aItem); virtual TInt TestCLbtStartupTrigger2L(CStifItemParser& aItem); virtual TInt TestCLbtStartupTrigger3L(CStifItemParser& aItem); virtual TInt TestCLbtStartupTrigger4L(CStifItemParser& aItem); virtual TInt TestCLbtStartupTrigger5L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerChangeEventNotifierL(CStifItemParser& aItem); virtual TInt TestCLbtTriggerConditionArea1L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerConditionArea2L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerConditionArea3L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerConditionArea4L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerConditionArea5L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerConditionArea6L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerConditionArea7L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerConditionArea8L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerEntry1L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerEntry2L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByArea1L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByArea2L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByArea3L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByArea4L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByArea5L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByArea6L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByArea7L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByArea8L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByAttribute1L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByAttribute2L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterByAttribute3L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterComposite1L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterComposite2L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterComposite3L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFilterComposite4L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerFiringEventNotifierL(CStifItemParser& aItem); virtual TInt TestCLbtTriggerInfo1L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerInfo2L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerInfo3L(CStifItemParser& aItem); virtual TInt TestCLbtTriggerInfo4L(CStifItemParser& aItem); virtual TInt TestTLbtTriggeringSystemSettingsL(CStifItemParser& aItem); virtual TInt TestCLbtTriggeringSystemSettingsChangeEventNotifier1L(CStifItemParser& aItem); virtual TInt TestRLbtAsyncUpdate1L(CStifItemParser& aItem); virtual TInt TestRLbtAsyncUpdate2L(CStifItemParser& aItem); virtual TInt TestRLbtAsyncUpdate3L(CStifItemParser& aItem); virtual TInt TestRLbtAsyncUpdate4L(CStifItemParser& aItem); virtual TInt TestRLbtAsyncUpdate5L(CStifItemParser& aItem); virtual TInt TestRLbtAsyncUpdate6L(CStifItemParser& aItem); virtual TInt TestRLbtAsyncUpdate7L(CStifItemParser& aItem); virtual TInt TestRLbtCancelUpdateTriggerL(CStifItemParser& aItem); /** * Method used to log version of test class */ void SendTestClassVersion(); //ADD NEW METHOD DEC HERE //[TestMethods] - Do not remove public: // Data // ?one_line_short_description_of_data //?data_declaration; protected: // Data // ?one_line_short_description_of_data //?data_declaration; private: // Data // ?one_line_short_description_of_data //?data_declaration; // Reserved pointer for future extension //TAny* iReserved; public: // Friend classes //?friend_class_declaration; protected: // Friend classes //?friend_class_declaration; private: // Friend classes //?friend_class_declaration; }; #endif // LBTBCTEST_H // End of File
[ "none@none" ]
none@none
31affcdd7c31df6813c449e8daef3139bf560872
bd1cbd63c59d1f0c7fe11f7284b89f778c54f905
/prx_simulation/prx/simulation/trajectory.hpp
d9283f9a6a31673276d007396e0d7d4acc688084
[]
no_license
warehouse-picking-automation-challenges/rutgers_arm
e40019bec4b00838909c593466f8d3af320752fa
647f5f7a3a87ad5fdc5dae04d61fc252885199c9
refs/heads/master
2021-06-03T20:08:16.371078
2016-08-26T16:37:56
2016-08-26T16:37:56
65,869,656
1
1
null
null
null
null
UTF-8
C++
false
false
11,280
hpp
/** * @file trajectory.hpp * * @copyright Software License Agreement (BSD License) * Copyright (c) 2013, Rutgers the State University of New Jersey, New Brunswick * All Rights Reserved. * For a full description see the file named LICENSE. * * Authors: Andrew Dobson, Andrew Kimmel, Athanasios Krontiris, Zakary Littlefield, Kostas Bekris * * Email: pracsys@googlegroups.com */ #pragma once #ifndef PRACSYS_BUFFERED_TRAJECTORY_HPP #define PRACSYS_BUFFERED_TRAJECTORY_HPP #include "prx/utilities/definitions/defs.hpp" #include "prx/utilities/spaces/space.hpp" #include "prx/simulation/state.hpp" #include <deque> namespace prx { namespace sim { class distance_from_goal_t; /** * A class to maintain information about a trajectory. The trajectory will hold all the states of a system * along an execution, or after a planner will plan for this system. * * @brief <b> Maintains a trajectory for a system </b> * * @author Zakary Littlefield */ class trajectory_t { friend class distance_from_goal_t; public: typedef std::deque<state_t*>::iterator iterator; typedef std::deque<state_t*>::const_iterator const_iterator; trajectory_t(); /** * Constructor of creating a new trajectory with the appropriate \ref util::space_t for coping/deleting the * states that the trajectory maintains. * * @param new_space The \ref util::space_t that the trajectory is using for the states it stores. */ trajectory_t(const util::space_t* new_space); /** * Copy constructor, copies the trajectory from the \c t to the current trajectory. * @param t The source trajectory from where we need to copy the states of the trajectory. */ trajectory_t(const trajectory_t& t); virtual ~trajectory_t(); /** * Returns the size of the trajectory in number of states. * * @brief Returns the size of the trajectory. * * @return The size of the trajectory. */ inline unsigned size() const { return num_states; } /** * Operator overload for the operator[]. * * @brief Operator overload for the operator[]. * * @param index The index on the trajectory for the state that we seek. This * index has to be less than \c num_states. * @return A pointer to the state in the position \c index. */ inline state_t* operator[](unsigned index)const { PRX_ASSERT(index < num_states); return states[index]; } /** * Returns a pointer to the last element in the trajectory. * * @brief Returns a pointer to the last element in the trajectory. * * @return A pointer to the last element in the trajectory. */ inline state_t* back() { PRX_ASSERT(num_states != 0); return states[num_states - 1]; } /** * Returns an iterator to the first position of the trajectory. * * @brief Returns an iterator to the first position of the trajectory. * * @return An iterator to the first position of the trajectory. */ inline iterator begin() { return states.begin(); } /** * Returns an iterator to the last position of the trajectory. * * @brief Returns an iterator to the last position of the trajectory. * * @return An iterator to the last position of the trajectory. */ inline iterator end() { return end_state; } /** * Returns a \c const iterator to the first position of the trajectory. * * @brief Returns a \c const iterator to the first position of the trajectory. * * @return A \c const iterator to the first position of the trajectory. */ inline const_iterator begin() const { return states.begin(); } /** * Returns a \c const iterator to the last position of the trajectory. * * @brief Returns a \c const iterator to the last position of the trajectory. * * @return A \c const iterator to the last position of the trajectory. */ inline const_iterator end() const { return const_end_state; } /** * Returns a pointer to the element at the position \c index. * * @brief Returns a pointer to the element at the position \c index. * * @return A pointer to the element at the position \c index. */ state_t* at(unsigned index) const { PRX_ASSERT(index < num_states); return states[index]; } /** * Links the appropriate \ref util::space_t in the trajectory. Same work can be done through * the constructor. If during the construction the \ref util::space_t is not available then * you can link it to the trajectory through this function. It is mandatory for the * trajectory to store/delete the states that contains, and allocate memory. * * @brief Links the \ref util::space_t in the trajectory. * * @param in_space The appropriate \ref util::space_t for the trajectory. */ void link_space(const util::space_t* in_space); /** * Returns the sum of the distances between each point in the trajectory. * This uses the default space distance function, so no custom distance functions * can be used here. * * @brief Returns the sum of the distances between each point in the trajectory. * * @return The length of the path */ double length() const; /** * Copies the points into this trajectory's buffer. No ownership is passed. * * @brief Copies the points into this trajectory's buffer. * * @param t The trajectory to copy points from * @return Self for nested assignment. */ trajectory_t& operator=(const trajectory_t& t); /** * Append the other trajectory's points by copying the values in. * No ownership is passed between the two trajectories. * * @brief Append the other trajectory's points by copying the values in. * * @param t The trajectory to copy points from. * @return Self for nested statements. */ trajectory_t& operator+=(const trajectory_t& t); /** * Marks the trajectory as empty. Does not delete any buffered memory. * * @brief Marks the trajectory as empty. */ void clear(); /** * Saves the trajectory to a file. * * @brief Saves the trajectory to a file. * * @param filename The name of the file to create. */ void save_to_file(std::string filename, unsigned precision = 20 ); /** * Saves the trajectory to a stream. * * @brief Saves the trajectory to a stream. * * @param output_stream The stream that the trajectory will be saved. */ void save_to_stream(std::ofstream& output_stream, unsigned precision = 20 ); /** * Reads a trajectory from a file. There is no error checking for state_space compatibility. * * @brief Reads a trajectory from a file. * * @param filename The name of the file to read from. */ void read_from_file(std::string filename); /** * Reads a trajectory from a stream. There is no error checking for state_space compatibility. * * @brief Reads a trajectory from a stream. * * @param input_stream The stream that we will read the trajectory. */ void read_from_stream(std::ifstream& input_stream); /** * Copies the given state to the back of the trajectory. * The caller is responsible for the passed point. Ownership is NOT passed to * the buffered trajectory. * * @brief Copies the given state to the back of the trajectory. * * @param state The state to copy. */ void copy_onto_back(state_t* state); /** * Copies the given state to the front of the trajectory. Will shift the other points over. * The caller is responsible for the passed point. Ownership is NOT passed to * the buffered trajectory. * * @brief Copies the given state to the front of the trajectory. * * @param state The state to copy. */ void copy_onto_front(state_t* state); /** * Copies an interval (segment) of states from this trajectory * into a destination trajectory. Assumes empty destination trajectory. * * @param start_index * @param end_index * @param copy_destination */ void copy_segment(int start_index, int end_index, trajectory_t* copy_destination); /** * Resizes the trajectory. The new maximum size of the trajectory will be \c num_size. * * @brief Resizes the trajectory. * * @param num_size The new size of the trajectory. */ void resize(unsigned num_size); /** * * @param splice_begin : Beginning index of the subtrajectory to remove * @param splice_end : End index of the subtrajectory to remove * @param t : Trajectory to insert in spliced section */ void splice(unsigned int splice_begin, unsigned int splice_end, const trajectory_t& t); /** * * @param splice_begin : Beginning index of the subtrajectory to remove * @param splice_end : End index of the subtrajectory to remove */ void splice(unsigned int splice_begin, unsigned int splice_end); void chop(unsigned size); /** * Reverses the trajectory. Includes both the last and the first position. * * @param t the trajectory that we need to reverse. */ void reverse_trajectory(const trajectory_t& t); /** * Prints the trajectory out * * @brief Prints the trajectory * @return The printed trajectory */ std::string print(unsigned precision = 20 ) const; /** * Get the collision flag. * * @brief Get the collision flag. * */ bool in_collision() const { return collision_found; } /** * Set the collision flag. * * @brief Set the collision flag. * */ void set_collision(bool collision_value) { collision_found = collision_value; } protected: /** * @brief Used in planning, lets other planning modules know if this trajectory was generated with collisions. */ bool collision_found; /** * Increases the buffer of the trajectory every time that the number of the states reaches the * maximum size of the buffer. * * @brief Increases the buffer of the trajectory * */ void increase_buffer(); /** @brief The \ref util::space_t for the trajectory. */ const util::space_t* state_space; /** @brief The iterator pointing at the end of the trajectory. */ iterator end_state; /** @brief \c Const iterator for the final position of the trajectory.*/ const_iterator const_end_state; /** @brief The current number of states in the trajectory.*/ unsigned num_states; /** @brief The maximum number of states that the trajectory can store.*/ unsigned max_num_states; /** @brief The data structure that maintains the trajectory.*/ std::deque<state_t*> states; }; } } #endif
[ "vincentzhu122@gmail.com" ]
vincentzhu122@gmail.com
b21583cb7bcdbbb35c31e6662ece122c8b6b167d
fbd128056ae0fd1f2103ed110f3880c10a744351
/aquarium1/FeedEvent.h
654890a63772641ac3383e24d98e6bec6928dd6e
[]
no_license
gardero/aquarium
ca789ae07d01888f125ec95d92ba419b1418dea7
3ac44f24981067b330a263f527ceeaf0cfd2d193
refs/heads/master
2021-01-21T12:21:31.025539
2015-08-14T10:54:26
2015-08-14T10:54:26
40,710,542
0
0
null
null
null
null
UTF-8
C++
false
false
619
h
/* * FeedEvent.h * * Created on: Jul 28, 2015 * Author: gardero */ #ifndef FEEDEVENT_H_ #define FEEDEVENT_H_ #define STEPS 100 #define IN1 8 #define IN2 9 #define IN3 10 #define IN4 11 #include "Stepper.h" #include "EventHandler.h" #include "Arduino.h" class FeedEvent : public EventHandler{ private: // Stepper stepper = Stepper(STEPS, 8,10,a11,9); Stepper stepper = Stepper(STEPS, 11,13,12,10); public: FeedEvent(){ stepper.setSpeed(100); } virtual ~FeedEvent(); void begin(); void activate(); void performAction(); void deactivate(); void end(); }; #endif /* FEEDEVENT_H_ */
[ "gardero@gmail.com" ]
gardero@gmail.com
42637cd0cc391ed5b300fd7396824f333aebb260
ee699f74b0bc0dd76d607f3becd2651ceca6f4ad
/boost/property_map/traits/value_type.hpp
6eb83ce4467bbc6abd665b5c680afac72cbb7f35
[ "BSL-1.0" ]
permissive
ericniebler/time_series
fe26a377230a2d0f003bf421894a8f60791dc864
4040119366cc21f25c7734bb355e4a647296a96d
refs/heads/master
2016-09-06T11:56:21.128720
2013-03-19T17:32:56
2013-03-19T17:32:56
8,884,331
11
4
null
null
null
null
UTF-8
C++
false
false
925
hpp
// Copyright David Abrahams 2006. 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_PROPERTY_MAP_TRAITS_VALUE_TYPE_DWA200655_HPP # define BOOST_PROPERTY_MAP_TRAITS_VALUE_TYPE_DWA200655_HPP # include <boost/iterator/iterator_traits.hpp> # include <boost/type_traits/remove_reference.hpp> # include <boost/type_traits/remove_cv.hpp> # include <boost/utility/result_of.hpp> namespace boost { namespace property_maps { namespace traits { template<typename F, typename I> struct value_type : remove_cv< typename remove_reference< typename result_of< F(typename iterator_reference<I>::type) >::type >::type > {}; }}} // namespace boost::property_maps::traits #endif // BOOST_PROPERTY_MAP_TRAITS_VALUE_TYPE_DWA200655_HPP
[ "niebler@industrial-perception.com" ]
niebler@industrial-perception.com
c8c5ca3dc96c8dd9554aedc2deb0275ac1e92bd5
029c481b44b44c42605a8a828c358af39679300f
/basic/2739.cpp
0b50f7286e81e79a6d55c013f8b1053fcaaeb836
[]
no_license
cbajs12/BOJ
93f4406c8820b834a48166f18abf89b7481cab7e
1e6ac6c98fe1336dd48db146199f8ebe7c4e216f
refs/heads/master
2020-05-29T12:23:11.757012
2019-06-08T12:14:58
2019-06-08T12:14:58
68,577,265
0
0
null
null
null
null
UTF-8
C++
false
false
276
cpp
#include <iostream> using namespace std; int main(void){ int num1; int i; cin>>num1; if(num1 < 1 || num1 > 9) return 0; for(i=1; i<=9; ++i){ printf("%d * %d = %d", num1, i, num1*i); if(i != 9) printf("\n"); } }
[ "cbajs20@gmail.com" ]
cbajs20@gmail.com
1fa367d55af6e04c7bcb4163473c225171220d3d
1890b475dc4e7b856f973252080814b14bb52d57
/aws/v7.1/Samples/netds/nap/shv/stdafx.h
ea3e143508fa7803a6b661f33446438e9c4c9b7f
[]
no_license
nfouka/InnoSetup5
065629007b00af7c14ae9b202011e12b46eea257
df39fc74995a6955d2d8ee12feed9cff9e5c37db
refs/heads/master
2020-04-20T02:51:58.072759
2019-01-31T21:53:45
2019-01-31T21:53:45
168,582,148
2
2
null
null
null
null
UTF-8
C++
false
false
815
h
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. #ifndef __STDAFX_H__ #define __STDAFX_H__ #pragma once #ifndef STRICT #define STRICT #endif #define _ATL_FREE_THREADED #define _ATL_NO_AUTOMATIC_NAMESPACE #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off ATL's hiding of some common and often safely ignored warning messages #define _ATL_ALL_WARNINGS #include "resource.h" #include <atlbase.h> #include <atlcom.h> using namespace ATL; #endif // __STDAFX_H__
[ "nadir.foukagmail.com" ]
nadir.foukagmail.com
0715fa587ad7d105845dec6fa7f08e53902dd340
feaeb579f3a8d4d86ea9ddcae5bbfa8b4d100655
/VisualStuido2019/rigid_simul/main.cpp
c67a16e19ed5d0919c3ae4866b78391fa2c3c9e9
[]
no_license
LEE-JAE-HYUN179/simple-rigidbody-simulation
92021deace9df1980998802ffc71370a8fcede01
a3c387a8afabc17d801f8d3cad9b99199d1ee0f0
refs/heads/master
2023-02-22T00:13:05.838442
2021-01-23T18:03:56
2021-01-23T18:03:56
305,069,288
4
0
null
null
null
null
UTF-8
C++
false
false
3,853
cpp
// // main.cpp // rigid_simul // // Created by 이재현 on 2020/10/17. // #include <iostream> #include <GL/glew.h> #include <GL/GLU.h> #include <GL/glut.h> #include <GLFW/glfw3.h> #include "Sphere.hpp" GLFWwindow* window; int WINDOW_WIDTH=0; int WINDOW_HEIGHT=0; int init(){ if (!glfwInit()) { std::cout << "glfw init failed!!\n"; return 1; } glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); WINDOW_WIDTH=1000; WINDOW_HEIGHT=1000; window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "opengl_playground", NULL, NULL); if (!window) { std::cout << "window creation failed!\n"; glfwTerminate(); return 1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; GLenum errorCode = glewInit(); if (GLEW_OK != errorCode) { glfwTerminate(); exit(EXIT_FAILURE); } glClearColor( 0.9, 0.9, 0.9, 1.0f); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); return 0; } void setCamera(){ //set camera glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, float(400)/float(400), 0.1, 1000.0); gluLookAt(250, 150, 30, 0, 0, 30, 0, 0, 1); glPopMatrix(); glFlush(); } void drawCoord(){ //draw x,y,z, coordinate glPushMatrix(); glBegin(GL_LINES); glColor3f(0, 0, 0); glVertex3f(0, 0, -1000); glVertex3f(0, 0, 1000); glEnd(); glPopMatrix(); glPushMatrix(); glBegin(GL_LINES); glColor3f(0, 0, 0); glVertex3f(0, -1000, -50); glVertex3f(0, 1000, -50); glEnd(); glPopMatrix(); glPushMatrix(); glBegin(GL_LINES); glColor3f(0, 0, 0); glVertex3f(-1000, 0, -50); glVertex3f(1000, 0, -50); glEnd(); glPopMatrix(); } void drawCube(){ //draw cube glPushMatrix(); glColor3f(1.0f, 153.f/255, 1.0f); glRectf(-100, -100, 100, 100); glPopMatrix(); glFlush(); glPushMatrix(); glColor3f(1.0f,0, 1.0f); glBegin(GL_QUADS); glVertex3f(100, 100, 0); glVertex3f(100, 100, -100); glVertex3f(100, -100, -100); glVertex3f(100, -100, 0); glEnd(); glPopMatrix(); glFlush(); glPushMatrix(); glColor3f(0.0f,1.0f, 0.0f); glBegin(GL_QUADS); glVertex3f(100, 100, 0); glVertex3f(100, 100, -100); glVertex3f(-100, 100, -100); glVertex3f(-100, 100, 0); glEnd(); glPopMatrix(); glFlush(); } void setLight(){ glPushMatrix(); // 0번 광원 배치. glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); GLfloat ambient[4] = {1.0, 1.0, 1.0, 0.0}; GLfloat diffuse[4] = {1.0, 1.0, 1.0, 0.0}; GLfloat specular[4] = {0, 0, 0, 0.0}; GLfloat position[4] = {30, 30, 30, 1}; glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, specular); glLightfv(GL_LIGHT0, GL_POSITION, position); glPopMatrix(); } int main(int argc, char ** argv) { //init glfw and glew init(); Sphere sphere; //set gravity glm::vec3 gravity(0,0,-9.8); while (!glfwWindowShouldClose(window)) { setCamera(); setLight(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); sphere.applyForce(gravity*sphere.mass); sphere.step(); sphere.render(); //sphere.dump(); drawCube(); //drawCoord(); glfwSwapBuffers(window); glfwPollEvents(); } return 0; }
[ "leejaehyun1223@gmail.com" ]
leejaehyun1223@gmail.com
512bd8a82365e4393ff8c59397f29aebbc2b5f30
c4e6fb201848da3ad00fa653972db90579aed1f0
/src/lighting/03_materials.cpp
bb8bcfea1b23f374be67a6745f514b77fa3edb07
[ "Apache-2.0" ]
permissive
clsrfish/learnogl
7fe9860a5c7a998061e23a9e8759bb155e1ea554
3e1cc42a595dd12779268ba587ef68fa4991e1f5
refs/heads/master
2023-01-01T08:57:09.123070
2020-10-22T16:50:06
2020-10-22T16:50:06
299,946,579
0
0
null
null
null
null
UTF-8
C++
false
false
10,393
cpp
// // 03_materials.cpp // // Created by Clsrfish on 08/10/2020 // #include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "../gl/shader.h" #include "../gl/camera.h" #include "../gl/gl_utils.h" #include "../utils/log.h" namespace lighting { namespace materials { float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f}; int screenWidth = 800; int screenHeight = 600; Camera camera; bool everMoved = false; double lastCursorX = 0.0; double lastCursorY = 0.0; void processCursorMove(GLFWwindow *window, double xpos, double ypos) { if (!everMoved) { lastCursorX = xpos; lastCursorY = ypos; everMoved = true; } double xoffset = xpos - lastCursorX; double yoffset = lastCursorY - ypos; lastCursorX = xpos; lastCursorY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void processMouseScroll(GLFWwindow *window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); } float lastFrameTime = -1.0f; void processKeyboard(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { LOG_I("Escape pressed, exiting."); glfwSetWindowShouldClose(window, GLFW_TRUE); } float currentFrameTime = glfwGetTime(); if (lastFrameTime < 0.0f) { lastFrameTime = currentFrameTime; } float deltaTime = currentFrameTime - lastFrameTime; lastFrameTime = currentFrameTime; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera.ProcessKeyboard(FORWARD, deltaTime); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera.ProcessKeyboard(BACKWARD, deltaTime); } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera.ProcessKeyboard(LEFT, deltaTime); } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera.ProcessKeyboard(RIGHT, deltaTime); } } int main() { LOG_I(__FILENAME__); glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #if defined(__APPLE__) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); #endif GLFWwindow *window = glfwCreateWindow(screenWidth, screenHeight, __FILENAME__, nullptr, nullptr); if (window == nullptr) { LOG_E("Failed to create GLFW window"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { LOG_E("Failed to initialize GLAD loader"); glfwTerminate(); return -1; } printGLInfo(); glViewport(0, 0, screenWidth, screenHeight); glfwSetFramebufferSizeCallback(window, [](GLFWwindow *, int w, int h) { screenWidth = w; screenHeight = h; glViewport(0, 0, w, h); }); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPosCallback(window, processCursorMove); glfwSetScrollCallback(window, processMouseScroll); unsigned int cubeVAO; glGenVertexArrays(1, &cubeVAO); glBindVertexArray(cubeVAO); // cube unsigned int cubeVBO; glGenBuffers(1, &cubeVBO); glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 6, (void *)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 6, (void *)(sizeof(float) * 3)); glEnableVertexAttribArray(1); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // light unsigned int lightVAO; glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); unsigned int lightVBO; glGenBuffers(1, &lightVBO); glBindBuffer(GL_ARRAY_BUFFER, lightVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 6, (void *)0); glEnableVertexAttribArray(0); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); Shader *cubeShader = new Shader("shaders/lighting/03/cube.vs", "shaders/lighting/03/cube.fs"); Shader *lightShader = new Shader("shaders/lighting/03/light.vs", "shaders/lighting/03/light.fs"); glfwSwapInterval(1); while (!glfwWindowShouldClose(window)) { processKeyboard(window); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glEnable(GL_DEPTH_TEST); glm::vec3 lightPos(1.2f, 1.0f, 2.0f); glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), static_cast<float>(screenWidth) / screenHeight, 0.1f, 100.0f); if (cubeShader->Use()) { glBindVertexArray(cubeVAO); glm::mat4 model = glm::mat4(1.0f); cubeShader->SetMatrix4("u_Model", glm::value_ptr(model)); cubeShader->SetMatrix4("u_View", glm::value_ptr(view)); cubeShader->SetMatrix4("u_Projection", glm::value_ptr(projection)); cubeShader->SetVec3("u_ViewPos", camera.Position.x, camera.Position.y, camera.Position.z); cubeShader->SetVec3("u_Material.ambient", 1.0f, 0.5f, 0.31f); cubeShader->SetVec3("u_Material.diffuse", 1.0f, 0.5f, 0.31f); cubeShader->SetVec3("u_Material.specular", 0.5f, 0.5f, 0.5f); cubeShader->SetFloat("u_Material.shineness", 32.0f); cubeShader->SetVec3("u_Light.pos", lightPos.x, lightPos.y, lightPos.z); glm::vec3 lightColor; lightColor.x = sin(glfwGetTime() * 2.0f); lightColor.y = sin(glfwGetTime() * 0.7f); lightColor.z = sin(glfwGetTime() * 1.3f); glm::vec3 diffuseColor = lightColor * glm::vec3(0.5f); glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f); cubeShader->SetVec3("u_Light.ambient", ambientColor.r, ambientColor.g, ambientColor.b); cubeShader->SetVec3("u_Light.diffuse", diffuseColor.x, diffuseColor.y, diffuseColor.z); cubeShader->SetVec3("u_Light.specular", 1.0f, 1.0f, 1.0f); glDrawArrays(GL_TRIANGLES, 0, 36); } else { break; } if (lightShader->Use()) { glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.2f)); lightShader->SetMatrix4("u_Model", glm::value_ptr(model)); lightShader->SetMatrix4("u_View", glm::value_ptr(view)); lightShader->SetMatrix4("u_Projection", glm::value_ptr(projection)); glBindVertexArray(lightVAO); glDrawArrays(GL_TRIANGLES, 0, 36); } else { break; } glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } } // namespace materials } // namespace lighting
[ "clsrfish@gmail.com" ]
clsrfish@gmail.com
4c8087e32dac5084d7b773020a50c7898979115e
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/c2/4e2c0d114add0a/main.cpp
bd94bcce93e5bacb67991b63ff8c3993627834f2
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
2,521
cpp
// listdir_recursive.c // Osmar D. G // Imprime el contenide de un directorio de manera recursiva #include <iostream> #include <string> #include <unistd.h> #include <sys/stat.h> #include <dirent.h> #include <cstdlib> #include <cerrno> #include <memory> namespace { using dirent_entry = struct dirent; //using file_status = struct stat; constexpr const char * pwd="."; constexpr const char * parent_dir=".."; class file_status { public: file_status()=default; explicit file_status(std::string file_name): file_name_{file_name} { init(); } bool is_directory() { return (stat_buf_.st_mode & S_IFMT)==S_IFDIR; } bool is_equal(const char * dirname) { return file_name_.compare(dirname)==0;} private: void init(){ lstat(file_name_.c_str(), &stat_buf_); } std::string file_name_; struct stat stat_buf_; }; auto list_directory(std::string dir, const size_t tab_size=0)->void{ dirent_entry * entry; // cambiar por std::unique_ptr //auto dirptr = opendir(dir.c_str()); // std::unique_ptr<DIR, decltype(closedir)> dirptr(opendir(dir.c_str()), closedir); std::unique_ptr< DIR, std::function< int(DIR*) > > dirptr( opendir(dir.c_str()), closedir ); // *** if(dirptr==nullptr){ std::cerr << "No se pudo abrir el directorio...\n"; exit(errno); } //Nos vamos al directorio chdir(dir.c_str()); std::string tab (tab_size, ' '); while( (entry=readdir(dirptr.get())) not_eq nullptr) { file_status stats{entry->d_name}; if(stats.is_directory()){ if(stats.is_equal(pwd) or stats.is_equal(parent_dir)) continue; std::cout << tab << entry->d_name << std::endl; list_directory(entry->d_name, tab_size+2); } std::cout << tab << entry->d_name << std::endl; } chdir(parent_dir); //closedir(dirptr); } } int main(int argc, char** argv){ using namespace std::literals::string_literals; const char* top_dir = nullptr; if(argc not_eq 2) top_dir = pwd; else top_dir=argv[1]; std::cout << "Scaneando el directorio: "s + top_dir + "\n"s << std::flush; list_directory(top_dir); std::cout << "listo....." << std::endl; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
d0415e45e09131d170898affa6c28fddae342539
688dfa72cf3e80e37f859617c66c59a99538f562
/vs2015/ootb/MyWorkspace/Win32ConsoleApplication/Win32ConsoleApplication.cpp
a81a337c4e9f1b3bb2e8861e1c456f736f3e2ca5
[ "MIT" ]
permissive
starkos/premake-reference
813d9d65a6d0e62f9a7120ee51df17c749d85ce3
bf2c7d869c02f675ce96a4f28cf67ec702892bf3
refs/heads/master
2023-02-23T20:47:47.595220
2021-01-28T13:24:34
2021-01-28T13:24:58
257,704,171
1
0
null
null
null
null
UTF-8
C++
false
false
142
cpp
// Win32ConsoleApplication.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main() { return 0; }
[ "starkos@industriousone.com" ]
starkos@industriousone.com
37688406cb616c9b3775f0721ec4203957ab722d
930a2c0078e8c68f96c10370224d8057161cd647
/dbtkd1711/examples/dynamic programming/JLIS.cpp
0433cd31b2c50b0a5eec5d607d7aab97cd2b24db
[]
no_license
JaechanAn/algorithm-study
bbc45f638bca00230a455e8fb5ef468b568ccce2
01b74f662cc4210f4c646f6a303cb3b8ba26ed99
refs/heads/master
2022-07-07T06:42:45.095078
2020-05-13T07:07:13
2020-05-13T07:07:13
175,931,313
0
0
null
null
null
null
UTF-8
C++
false
false
422
cpp
#include <iostream> #include <vector> using namespace std; int C, n, m, input; vector <int> A, B; int main() { cin >> C; for(int i = 0 ; i < C ; i++) { cin >> n >> m; for(int j = 0 ; j < n ; j++) { cin >> input; A.push_back(input); } for(int j = 0 ; j < m ; j++) { cin >> input; B.push_back(input); } } return 0; }
[ "dbtkd1711@naver.com" ]
dbtkd1711@naver.com
d908fc5d40bc112efdc07577fb4d237a32f26854
51762d7e6d31381d86b395bee03cc6c5e8b14ca6
/BookCHM.cpp
746042f8d97b35abe68f6aabe380d37b3f2fc198
[]
no_license
qtnc/6reader
51c36152f51ea2af722270421aeb737a5c04f0de
f7a3a50fd7163883b1439dfda22e0fe3f4d8d4e3
refs/heads/master
2023-06-28T10:57:36.729269
2021-04-21T07:22:13
2021-04-21T07:22:13
360,067,265
2
1
null
2021-08-01T16:48:08
2021-04-21T07:12:18
C++
UTF-8
C++
false
false
3,422
cpp
#include "BookCHM.hpp" #include "wxWidgets.hpp" #include <wx/xml/xml.h> #include <wx/sstream.h> #include <wx/wfstream.h> #include <wx/filename.h> #include "stringUtils.hpp" #include "XMLHelpers.hpp" #include "cpprintf.hpp" #include "App.hpp" using namespace std; std::shared_ptr<Resource> BookCHM::findResourceByURI (const std::string& uri) { auto resource = make_shared<Resource>(); resource->uri = uri; return resource; } bool tryDecompileHH (string& filename, const string& hashname) { filename = makeAbsolutePath(filename); auto ff = make_unique<wxFFileInputStream>(U(filename)); if (!ff || !ff->IsOk()) { println("Couldn't open %s", filename); return false; } char buf[4] = {0}; ff->Read(buf,4); if (ff->LastRead()!=4) { println("Couldn't read %s", filename); return false; } if (strncmp(buf, "ITSF", 4)) { println("%s isn't a CHM ITSF file", filename); return false; } println("%s recognized as CHM ITSF file", filename); ff.reset(); auto tmpdir = U(wxGetApp() .userDir); //U(wxFileName::GetTempDir()); if (ends_with(tmpdir, "/") || ends_with(tmpdir, "\\")) tmpdir = tmpdir.substr(0, tmpdir.size() -1); auto hhdir = tmpdir + "\\" + hashname; if (wxDirExists(U(hhdir))) { filename=hhdir; return true; } println("Decompiling CHM ITSF file %s into directory %s...", filename, hhdir); auto cmd = format("hh -decompile %s %s", hhdir, filename); auto result = wxExecute(U(cmd), wxEXEC_SYNC | wxEXEC_NOEVENTS | wxEXEC_HIDE_CONSOLE); println("Command %s returned %d", cmd, result); if (result) return false; filename=hhdir; return wxDirExists(U(hhdir)); } void loadToc (shared_ptr<TocEntry> toc, wxXmlNode* root) { for (auto li: FindNodes(root, ByTag("li"))) { auto node = FindNode(li, ByTag("object")); if (!node) continue; auto paramName = FindNode(node, And(ByTag("param"), ByAttrVal("name", "Name"))); if (!paramName) continue; auto label = U(paramName->GetAttribute("value")); if (label.empty()) continue; auto paramLocal = FindNode(node, And(ByTag("param"), ByAttrVal("name", "Local"))); auto uri = paramLocal? U(paramLocal->GetAttribute("value")) :""; auto entry = make_shared<TocEntry>(); entry->label = label; entry->uri = uri; toc->children.push_back(entry); node = FindNode(li, ByTag("ul")); if (node) loadToc(entry, node); }} shared_ptr<Book> BookCHM::open (const string& filename) { auto book = make_shared<BookCHM>(); if (book->load(filename)) return book; else return nullptr; } bool BookCHM::load (const string& fn) { filename=fn; if (!tryDecompileHH(filename, getHashName()) || !BookZip::load(filename)) return false; auto zf = openFile([&](const string& name){ return iends_with(name, ".hhc"); }); if (!zf) { println("Couldn't find HTML help content file (HHC) in %s", filename); return false; } auto hhc = ReadAll(*zf); auto doc = LoadHTML(hhc); if (!doc) { println("HTML help content file (HHC) parse error in %s", filename); return false; } auto root = doc->GetRoot(); if (!root) return false; root = FindNode(root, ByTag("body")); if (!root) return false; root = FindNode(root, ByTag("ul")); if (!root) return false; toc = make_shared<TocEntry>(); loadToc(toc, root); return true; } string findFirstNonEmptyURI (shared_ptr<TocEntry> toc) { string re; if (toc) for (auto entry: toc->children) { if (entry->uri.size()) re = entry->uri; else re = findFirstNonEmptyURI(entry); if (re.size()) return re; } return re; } std::string BookCHM::getFirstPageURI () { return findFirstNonEmptyURI(toc); }
[ "webmaster@quentinc.net" ]
webmaster@quentinc.net
3bbdd032e8093262df8abd0cd48c25040a778f11
5b947316624979a5a0f4cca3e9db13bc87e5a92a
/DialogTools/src/undo.cpp
d7993385c7c73ba01d75a2f06121a26fe0e33975
[]
no_license
trexinc/evil-programmers
c23cc0e0d100f5b6083a3d2ca718f9b353872788
3fe7a0d97e41cdb57eb10639bb399dfca7dd3dab
refs/heads/master
2023-07-19T01:19:14.691343
2023-07-05T19:17:08
2023-07-05T19:17:08
32,504,532
66
36
null
2022-04-27T19:12:21
2015-03-19T06:22:19
C++
UTF-8
C++
false
false
6,268
cpp
/* undo.cpp Copyright (C) 2004 Vadim Yegorov Copyright (C) 2008 zg 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dt.hpp" #include "guid.hpp" #include "avl.hpp" struct UndoItem { TCHAR *data; COORD pos; long unchanged; UndoItem *next; }; class UndoData { private: UndoItem* Top; UndoItem* Stack; HANDLE Dialog; intptr_t Item; private: UndoData(); UndoData(const UndoData& value); UndoData& operator=(const UndoData& value); void Restore(UndoItem* Data); public: UndoData(HANDLE value,intptr_t item); ~UndoData(); void Add(HANDLE value,intptr_t item); void Pop(void); void SetTop(void) {Top=Stack;} void Undo(void); void Redo(void); friend class UndoTree; }; UndoData::UndoData(HANDLE value,intptr_t item): Top(NULL),Stack(NULL),Dialog(value),Item(item) { } UndoData::~UndoData() { UndoItem* curr_stack; while(Stack) { curr_stack=Stack; Stack=Stack->next; if(curr_stack->data) HeapFree(GetProcessHeap(),0,curr_stack->data); HeapFree(GetProcessHeap(),0,curr_stack); } } void UndoData::Add(HANDLE value,intptr_t item) { UndoItem* NewStack=(UndoItem*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(UndoItem)); if(NewStack) { size_t length=Info.SendDlgMessage(value,DM_GETTEXT,item,0); NewStack->data=(TCHAR*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,(length+1)*sizeof(TCHAR)); if(NewStack->data) { FarDialogItemData getdata={sizeof(FarDialogItemData),length,NewStack->data}; Info.SendDlgMessage(value,DM_GETTEXT,item,&getdata); NewStack->unchanged=Info.SendDlgMessage(value,DM_EDITUNCHANGEDFLAG,item,(void*)-1); Info.SendDlgMessage(value,DM_GETCURSORPOS,item,&NewStack->pos); NewStack->next=Stack; Stack=NewStack; } else { HeapFree(GetProcessHeap(),0,NewStack); } } } void UndoData::Pop(void) { if(Stack) { UndoItem* curr_stack; while(Stack&&Stack->next!=Top) { curr_stack=Stack; Stack=Stack->next; if(curr_stack->data) HeapFree(GetProcessHeap(),0,curr_stack->data); HeapFree(GetProcessHeap(),0,curr_stack); } } } static int inside_undo=0; void UndoData::Restore(UndoItem* Data) { inside_undo++; Info.SendDlgMessage(Dialog,DM_SETTEXTPTR,Item,Data->data); Info.SendDlgMessage(Dialog,DM_SETCURSORPOS,Item,&Data->pos); Info.SendDlgMessage(Dialog,DM_EDITUNCHANGEDFLAG,Item,(void*)(intptr_t)Data->unchanged); inside_undo--; } void UndoData::Undo(void) { if(Top) { Restore(Top); Top=Top->next; } } void UndoData::Redo(void) { if(Stack->next!=Top) { UndoItem* NewTop=Stack; while(NewTop->next&&NewTop->next->next!=Top) NewTop=NewTop->next; if(NewTop->next) { Restore(NewTop); Top=NewTop->next; } } } class UndoTree: public avl_tree<UndoData> { public: UndoTree(); ~UndoTree(); long compare(avl_node<UndoData> *first,UndoData *second); UndoData *query(HANDLE value,intptr_t item); void Undo(HANDLE value,intptr_t item); void Redo(HANDLE value,intptr_t item); }; UndoTree::UndoTree() { clear(); } UndoTree::~UndoTree() { clear(); } long UndoTree::compare(avl_node<UndoData> *first,UndoData *second) { long result=reinterpret_cast<intptr_t>(second->Dialog)-reinterpret_cast<intptr_t>(first->data->Dialog); if(!result) result=second->Item-first->data->Item; return result; } UndoData *UndoTree::query(HANDLE value,intptr_t item) { UndoData Get(value,item); return avl_tree<UndoData>::query(&Get); } void UndoTree::Undo(HANDLE value,intptr_t item) { UndoData* data=query(value,item); if(data) data->Undo(); } void UndoTree::Redo(HANDLE value,intptr_t item) { UndoData* data=query(value,item); if(data) data->Redo(); } static UndoTree* GUndo=NULL; void InitUndo(void) { GUndo=new UndoTree; } void FinishUndo(void) { delete GUndo; } void DoUndo(HANDLE aDlg) { intptr_t itemID=Info.SendDlgMessage(aDlg,DM_GETFOCUS,0,0); FarMenuItem MenuItems[]={{MIF_SELECTED,_T(""),{0},0,{0,0}},{0,_T(""),{0},0,{0,0}}}; INIT_MENU_TEXT(0,GetMsg(mUndo)); INIT_MENU_TEXT(1,GetMsg(mRedo)); int MenuCode=Info.Menu(&MainGuid,&UndoMenuGuid,-1,-1,0,FMENU_AUTOHIGHLIGHT|FMENU_WRAPMODE,GetMsg(mNameUndo),NULL,NULL,NULL,NULL,MenuItems,ArraySize(MenuItems)); if(MenuCode>=0) { FarDialogItem DialogItem; Info.SendDlgMessage(aDlg,DM_GETDLGITEMSHORT,itemID,&DialogItem); if(DialogItem.Type==DI_EDIT) { switch(MenuCode) { case 0: GUndo->Undo(aDlg,itemID); break; case 1: GUndo->Redo(aDlg,itemID); break; } } } } void FilterUndoInit(HANDLE aDlg,intptr_t aMsg,intptr_t aParam1,void* aParam2) { if(inside_undo) return; if(DN_EDITCHANGE==aMsg||DN_GOTFOCUS==aMsg) { FarDialogItem DialogItem; Info.SendDlgMessage(aDlg,DM_GETDLGITEMSHORT,aParam1,&DialogItem); if(DialogItem.Type==DI_EDIT) { bool forceadd=true; UndoData* data=GUndo->query(aDlg,aParam1); if(!data) { data=new UndoData(aDlg,aParam1); data=GUndo->insert(data); } else { if(DN_GOTFOCUS==aMsg) forceadd=false; else data->Pop(); } if(forceadd) { data->SetTop(); data->Add(aDlg,aParam1); } } } } void FilterUndoEnd(HANDLE aDlg,intptr_t aMsg,intptr_t aParam1,void* aParam2,intptr_t Result) { if(DN_CLOSE==aMsg&&Result) { FarDialogItem dialog_item; for(size_t ii=0;Info.SendDlgMessage(aDlg,DM_GETDLGITEMSHORT,ii,&dialog_item);++ii) { UndoData del(aDlg,ii); GUndo->remove(&del); } } }
[ "oo.zg.oo@gmail.com" ]
oo.zg.oo@gmail.com
d8655e7de578a67c18f3ae06d2b0494a133697d9
9ac8570177bebcac786b587adf5c55d8306347e3
/HelloWorld/access_file_data.h
324219dc30eeeff6f7f0133c8a1122e0614b1016
[]
no_license
ksenya96/WEB_service
fc896d0066657ed328887268bec8a9c60a1d0942
a78b84ceff4d3a2b54c67f4972fed11f644102d3
refs/heads/master
2020-03-29T15:52:23.774530
2018-12-07T18:30:12
2018-12-07T18:30:12
150,084,605
0
0
null
null
null
null
UTF-8
C++
false
false
196
h
#pragma once #include <vector> #include "Record.h" std::vector<Record> findAll(); std::vector<Record> getResultsByUserName(std::string name); std::string addRecord(cppcms::json::value input);
[ "noreply@github.com" ]
ksenya96.noreply@github.com
d0c52bf4eed4ab7bdf7a635aa01b30c83eb00029
3c283cd167fb7b06ffafb40b4be7f644c48380dc
/src/strawgraphics/view/Button.cc
998da746becfb12a94e2fea206b6eb8ca9e65fe1
[ "Apache-2.0" ]
permissive
arnozhang/strawframework
40f47efb1b33cfb221e671c0f04ea84b2f99b9f1
630a9a543cc819d966f888211717423eed9a8497
refs/heads/master
2023-08-05T10:20:09.301655
2023-04-05T08:49:04
2023-04-05T08:49:04
70,670,573
17
2
null
null
null
null
UTF-8
C++
false
false
164
cc
#include "graphics/view/Button.h" sf::Button::Button(const Context& context) : ElementInherit(context) { setClickable(true); } sf::Button::~Button() { }
[ "zyfgood12@gmail.com" ]
zyfgood12@gmail.com
39fe213c396213de4f3138fa998f29727183a702
49bc99e5dce51af20a9137157d8035890f234c71
/lib/adapter/ButtonEdgeDetector.h
a482dedb179b95f5fa31079d391bf75c09dca807
[ "MIT" ]
permissive
dniklaus/nRF52-test
04b2d1d2d9f42e710a81fdc864a9892d6244046f
bc31943aa736af9587f4edddf157e0191e815f19
refs/heads/master
2021-08-04T15:48:07.817527
2021-01-25T01:46:52
2021-01-25T01:46:52
240,330,252
0
0
null
null
null
null
UTF-8
C++
false
false
733
h
/* * ButtonEdgeDetector.h * * Created on: 17.02.2020 * Author: dev */ #ifndef LIB_ADAPTER_BUTTONEDGEDETECTOR_H_ #define LIB_ADAPTER_BUTTONEDGEDETECTOR_H_ #include <EdgeDetector.h> #include <DetectorStrategy.h> class DbgTrace_Port; class ButtonEdgeDetector : public EdgeDetector { private: DbgTrace_Port* m_trPort; unsigned long int m_count; public: ButtonEdgeDetector(const char* name); virtual ~ButtonEdgeDetector(); void onEdge(bool newState); private: // forbidden functions ButtonEdgeDetector(const ButtonEdgeDetector& src); // copy constructor ButtonEdgeDetector& operator = (const ButtonEdgeDetector& src); // assignment operator }; #endif /* LIB_ADAPTER_BUTTONEDGEDETECTOR_H_ */
[ "dieter.niklaus@ypsomed.com" ]
dieter.niklaus@ypsomed.com
99f81c63f57da45b181b72b155bcf30cff9a31f7
7fc9d6c59c6a40d7bb3fa40a7d89f896753d25ee
/uoj/104.cpp
444117de22af5763c86830fa97c8b360c1682195
[]
no_license
yzcmf/oicode
902116f8d50c870e1a251083c6421c4563bab4fa
69d687e267a54ca64fc957595ef5327de37c005a
refs/heads/master
2020-07-25T14:17:00.186895
2016-08-08T03:07:15
2016-08-08T03:07:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,494
cpp
/* UOJ-#104. 【APIO2014】Split the sequence * 斜率优化 */ #include <cstdio> #include <algorithm> const int MaxN = 100010, MaxK = 210; int now, q[MaxN], prev[MaxK][MaxN]; long long f[2][MaxN], y[2][MaxN]; long long sum[MaxN]; double slope(int a, int b) { if(sum[a] == sum[b]) return 1.0e100; return double(y[now ^ 1][a] - y[now ^ 1][b]) / double(sum[a] - sum[b]); } void print_ans(int k, int now) { if(k == 0) return; print_ans(k - 1, prev[k][now]); std::printf("%d ", prev[k][now]); } void solve(int n, int k) { now = 0; for(int i = 1; i <= n; ++i) y[now][i] = sum[i] * sum[i]; for(int i = 1; i <= k; ++i) { now ^= 1; int h = 0, t = 0; q[t] = 0; for(int j = 1; j <= n; ++j) { while(h < t && y[now ^ 1][q[h]] - y[now ^ 1][q[h + 1]] >= sum[j] * (sum[q[h]] - sum[q[h + 1]])) h++; // while(h < t && slope(q[h], q[h + 1]) <= sum[j]) h++; f[now][j] = f[now ^ 1][q[h]] + sum[q[h]] * (sum[j] - sum[q[h]]); y[now][j] = sum[j] * sum[j] - f[now][j]; prev[i][j] = q[h]; while(h < t && (y[now ^ 1][j] - y[now ^ 1][q[t]]) * (sum[q[t]] - sum[q[t - 1]]) <= (y[now ^ 1][q[t]] - y[now ^ 1][q[t - 1]]) * (sum[j] - sum[q[t]])) --t; // while(h < t && slope(j, q[t]) <= slope(q[t], q[t - 1])) --t; q[++t] = j; } } std::printf("%lld\n", f[now][n]); print_ans(k, n); } int main() { int n, k; std::scanf("%d %d", &n, &k); for(int i = 1; i <= n; ++i) { int v; std::scanf("%d", &v); sum[i] = sum[i - 1] + v; } solve(n, k); return 0; }
[ "miskcoo@gmail.com" ]
miskcoo@gmail.com
5f2f5adb6b04ac58f9fbbc4e086dcc6cef38d4fd
111fcd58e6c1bfb199397f2a24ab73303fa60e9a
/procmon/tests/plot_test2.cpp
cfef775fc216e51675c20a482b696bc1cc2a4895
[]
no_license
yqsy/linux_socket_test
1e13eb6d6783cb70b259dfef058e7d66c96a06a2
0e93cd73ef2ee19a46948b09caf24825c0f70cd5
refs/heads/master
2021-09-08T05:07:22.169104
2018-03-04T14:12:27
2018-03-04T14:12:27
110,062,669
0
0
null
null
null
null
UTF-8
C++
false
false
4,773
cpp
#include <algorithm> #include <assert.h> #include <cmath> #include <fstream> #include <iostream> #include <limits> #include <math.h> #include <random> #include <string> #include <vector> #include <muduo/base/Types.h> #include <boost/format.hpp> #include <gd.h> #include <gdfonts.h> using namespace muduo; typedef struct gdImageStruct *gdImagePtr; std::vector<double> gen_doubles(int num) { assert(num > 0); std::mt19937 gen(std::random_device{}()); std::uniform_real_distribution<> dis(0, 100); std::vector<double> r0; for (int i = 0; i < num; ++i) { auto d = dis(gen); r0.push_back(d); } return r0; } bool are_same(double a, double b) { return std::fabs(a - b) < std::numeric_limits<double>::epsilon(); } // 精确到十分位 std::string format_double(double d) { return boost::str(boost::format("%.1f") % d); } // 精确到百分位 std::string format_double2(double d) { return boost::str(boost::format("%.2f") % d); } // round up 十分位 double round_up_tenths(double d) { return ceil(d * 10.0) / 10.0; } // round up 靠近0.0或者0.5 double round_up_half(double d) { assert(d > 0.0); // 先round up 到十分位 d = ceil(d * 10.0) / 10.0; double fractpart, intpart; fractpart = modf(d, &intpart); if (are_same(fractpart, 0.0) || are_same(fractpart, 0.5)) { return d; } else if (fractpart < 0.5) { return intpart + 0.5; } else { return intpart + 1.0; } } void print_doubles(const std::vector<double> &doubles) { for (auto d : doubles) { assert(are_same(d, 0.0) || d > 0.0); std::cout << format_double(d) << " "; } std::cout << std::endl; } double get_max(const std::vector<double> &doubles) { auto max = *std::max_element(doubles.begin(), doubles.end()); return max; } // 水平分割线,分割线最少有8根 // max_d 不能太小,因为不够切分了 std::vector<double> split_section(double max_d) { auto section_point = max_d / 7; std::vector<double> doubles{0.0}; double one_val = section_point; for (int i = 0; i < 7; i++) { doubles.push_back(one_val); one_val += section_point; } return doubles; } int main(int argc, char *argv[]) { const double margin = 15; const double width = 700 + margin * 2; const double height = 165; // 一共要塞满300个横轴点 const int max_points = 300; // 过去10分钟, 600s, 周期为2, 一共300个点 auto doubles = gen_doubles(300); print_doubles(doubles); // 打印至百分位 std::cout << "max: " << format_double2(get_max(doubles)) << std::endl; // round up 靠近0.0或者0.5 std::cout << "round up max: " << format_double(round_up_half(get_max(doubles))) << std::endl; auto max = std::max(1.0, round_up_half(get_max(doubles))); // 纵轴集合点(数值,非坐标点)(时间维度是递增)(数值维度) // auto y_collections = split_section(max); auto y_collections = doubles; std::cout << "y_collections: "; print_doubles(y_collections); // 纵轴集合点转换成纵轴坐标集合点 for (size_t i = 0; i < y_collections.size(); i++) { y_collections[i] = (1 - y_collections[i] / max) * height; } // 给纵轴集合点加上时间维度 // 递增画上时间点 // 考虑到点可能不会充足,所以从左至右画时要加上补填的长度 std::vector<double> x_collections; double draw_points_len = ((double)y_collections.size() / (double)max_points) * (double)width; double fill_points_len = width - draw_points_len; for (size_t i = 0; i < y_collections.size(); ++i) { double x = margin / 2 + fill_points_len + draw_points_len * ((double)i / (double)y_collections.size()); x_collections.push_back(x); } assert(y_collections.size() == x_collections.size()); gdImagePtr image = gdImageCreate(width, height); // 背景灰色线 // const int background_line_color = gdImageColorAllocate(image, 230, 233, // 235); // 背景白色线 const int background_color = gdImageColorAllocate(image, 255, 255, 255); gdImageFilledRectangle(image, 0, 0, width, height, background_color); gdImageSetThickness(image, 2); // 统计蓝色线 const int statistics_color = gdImageColorAllocate(image, 51, 132, 225); // 连线 for (size_t i = 0; i < x_collections.size() - 1; ++i) { double x1 = x_collections[i]; double y1 = y_collections[i]; double x2 = x_collections[i + 1]; double y2 = y_collections[i + 1]; gdImageLine(image, x1, y1, x2, y2, statistics_color); } int size = 0; void *png = gdImagePngPtr(image, &size); string result(static_cast<char *>(png), size); std::ofstream file; file.open("xx.png"); file << result; file.close(); gdFree(png); gdImageDestroy(image); return 0; }
[ "yqsy021@126.com" ]
yqsy021@126.com
21f0830f9c2245d9c1b33b4eeb3391ff12dc31bc
54a80fe158ba3f00554a955106fde800688d70e5
/include/human_sort.hpp
de89b1565ccbf23b04791bfc6103de009db4fc95
[ "Apache-2.0" ]
permissive
ibm-openbmc/bmcweb
0064f2db78203884b3e8d71b28d0b199352ebb9f
d2b4d0a024720ffcd8737949a140e6ce32056611
refs/heads/1050
2023-08-17T19:27:25.250536
2023-08-08T14:25:46
2023-08-08T14:25:46
195,868,401
13
166
Apache-2.0
2023-09-13T14:53:02
2019-07-08T18:45:17
C++
UTF-8
C++
false
false
2,937
hpp
#pragma once #include <charconv> #include <iterator> #include <string_view> namespace details { // This implementation avoids the complexity of using std::isdigit, which pulls // in all of <locale>, and likely has other consequences. inline bool simpleIsDigit(const char c) { return c >= '0' && c <= '9'; } enum class ModeType { STRING, NUMBER }; } // namespace details inline int alphanumComp(const std::string_view left, const std::string_view right) { std::string_view::const_iterator l = left.begin(); std::string_view::const_iterator r = right.begin(); details::ModeType mode = details::ModeType::STRING; while (l != left.end() && r != right.end()) { if (mode == details::ModeType::STRING) { // check if this are digit characters const bool lDigit = details::simpleIsDigit(*l); const bool rDigit = details::simpleIsDigit(*r); // if both characters are digits, we continue in NUMBER mode if (lDigit && rDigit) { mode = details::ModeType::NUMBER; continue; } // if only the left character is a digit, we have a result if (lDigit) { return -1; } // if only the right character is a digit, we have a result if (rDigit) { return +1; } // compute the difference of both characters const int diff = *l - *r; // if they differ we have a result if (diff != 0) { return diff; } // otherwise process the next characters l++; r++; } else // mode==NUMBER { // get the left number int lInt = 0; auto fc = std::from_chars(&(*l), &(*left.end()), lInt); l += std::distance(l, fc.ptr); // get the right number int rInt = 0; fc = std::from_chars(&(*r), &(*right.end()), rInt); r += std::distance(r, fc.ptr); // if the difference is not equal to zero, we have a comparison // result const int diff = lInt - rInt; if (diff != 0) { return diff; } // otherwise we process the next substring in STRING mode mode = details::ModeType::STRING; } } if (r == right.end() && l == left.end()) { return 0; } if (r == right.end()) { return 1; } return -1; } // A generic template type compatible with std::less that can be used on generic // containers (set, map, ect) template <class Type> struct AlphanumLess { bool operator()(const Type& left, const Type& right) const { return alphanumComp(left, right) < 0; } };
[ "ed@tanous.net" ]
ed@tanous.net
5d9e62d0cfa6c3cbdab93abc13733856d9896f4d
8112ddd6ead2604b37930fabf07394ca8c7c7031
/JuggleClip.h
f462391b8490d7f19e1bec8a88756a50e6e6caa2
[]
no_license
xuexl/juggle
c3e72b8efe6196e19b2f161366ecea798f982dc0
afebaeb6d06848a415ea0536b12779e3787e54ee
refs/heads/master
2022-11-11T16:10:12.658774
2020-07-03T11:16:39
2020-07-03T11:16:39
269,339,315
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
h
/** * @class JuggleClip * @brief clip class */ #ifndef JUGGLECLIP_H #define JUGGLECLIP_H #include<string> #include<vtkSmartPointer.h> #include<vtkImplicitFunction.h> class vtkJuggleRenderer; class JuggleClip { public: enum ClipTools { C_PLANE }; /** *change current clip tool. */ void ChangeClipTool(ClipTools ct); /** * hide the actors that are already there, * show the actors that are created by clipping */ void Clip(vtkJuggleRenderer* ren); /** * remove the actors that are created by clipping, * and show the actors that are already there. */ void Restore(vtkJuggleRenderer* ren); JuggleClip(); ~JuggleClip(); protected: // ClipTools CurrentClipTool = C_PLANE; vtkSmartPointer<vtkImplicitFunction> ImplicitFunction; const std::string ClipActorTag = "CLIP"; void CreatePlane(); private: JuggleClip(JuggleClip const&) = delete; void operator=(JuggleClip const&) = delete; }; #endif // JUGGLECLIP_H
[ "xilin.xue@shmedo.cn" ]
xilin.xue@shmedo.cn
39a552727f56254573fa175cce9ef4179e672bcf
d53dca57f6e7f7915acea1aa1609575505488c8b
/Cpp/PG9.cpp
1f1b9d2067eb2d401e4f0e9a6811530ad328b85f
[]
no_license
Yeeenaa/study
0d4f519ed57ba2f65a9f1366875dee538266cc25
1eaa5db1c041b310dfdcf890dde1aad78c68b39e
refs/heads/master
2023-02-19T20:30:03.655706
2021-01-06T13:39:17
2021-01-06T13:39:17
323,650,611
0
0
null
null
null
null
UTF-8
C++
false
false
313
cpp
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; string solution(string s) { string answer = ""; sort(s.begin(), s.end()); for (int a = s.length(); a > 0; a--) { answer+=(s.at(a-1)); } cout << answer; return answer; } int main() { solution("Zbcdefg"); }
[ "ginto29@gmail.com" ]
ginto29@gmail.com
1776a1051a9b25f036efa179b555c1390f047972
05b8ceb85880245663723fff23ffcf73c8e5c3e2
/bench/SkSLBench.cpp
4175e395fcd038f5ce0a1f475140beb8d18fc340
[ "BSD-3-Clause" ]
permissive
RainwayApp/skia
307e562bb197914f638e3d65b9ac1a62cbfc09dd
f5583b4936ad13c4efe170807fbaf9b2decd0618
refs/heads/master
2020-12-15T20:19:20.358046
2020-07-15T16:46:54
2020-07-15T16:46:54
235,236,299
2
0
NOASSERTION
2020-07-15T17:17:37
2020-01-21T02:02:45
C++
UTF-8
C++
false
false
5,782
cpp
/* * Copyright 2019 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "bench/Benchmark.h" #include "bench/ResultsWriter.h" #include "bench/SkSLBench.h" #include "src/sksl/SkSLCompiler.h" class SkSLBench : public Benchmark { public: SkSLBench(SkSL::String name, const char* src) : fName("sksl_" + name) , fSrc(src) {} protected: const char* onGetName() override { return fName.c_str(); } bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; } void onDraw(int loops, SkCanvas*) override { for (int i = 0; i < loops; i++) { std::unique_ptr<SkSL::Program> program = fCompiler.convertProgram( SkSL::Program::kFragment_Kind, fSrc, fSettings); if (!fCompiler.errorCount()) { fCompiler.optimize(*program); } else { printf("%s\n", fCompiler.errorText().c_str()); SK_ABORT("shader compilation failed"); } } } private: SkSL::String fName; SkSL::String fSrc; SkSL::Compiler fCompiler; SkSL::Program::Settings fSettings; typedef Benchmark INHERITED; }; /////////////////////////////////////////////////////////////////////////////// DEF_BENCH(return new SkSLBench("tiny", "void main() { sk_FragColor = half4(1); }"); ) DEF_BENCH(return new SkSLBench("huge", R"( uniform half2 uDstTextureUpperLeft_Stage1; uniform half2 uDstTextureCoordScale_Stage1; uniform sampler2D uDstTextureSampler_Stage1; noperspective in half4 vQuadEdge_Stage0; noperspective in half4 vinColor_Stage0; out half4 sk_FragColor; half luminance_Stage1(half3 color) { return dot(half3(0.3, 0.59, 0.11), color); } half3 set_luminance_Stage1(half3 hueSat, half alpha, half3 lumColor) { half diff = luminance_Stage1(lumColor - hueSat); half3 outColor = hueSat + diff; half outLum = luminance_Stage1(outColor); half minComp = min(min(outColor.r, outColor.g), outColor.b); half maxComp = max(max(outColor.r, outColor.g), outColor.b); if (minComp < 0.0 && outLum != minComp) { outColor = outLum + ((outColor - half3(outLum, outLum, outLum)) * outLum) / (outLum - minComp); } if (maxComp > alpha && maxComp != outLum) { outColor = outLum +((outColor - half3(outLum, outLum, outLum)) * (alpha - outLum)) / (maxComp - outLum); } return outColor; } void main() { half4 outputColor_Stage0; half4 outputCoverage_Stage0; { // Stage 0, QuadEdge outputColor_Stage0 = vinColor_Stage0; half edgeAlpha; half2 duvdx = half2(dFdx(vQuadEdge_Stage0.xy)); half2 duvdy = half2(dFdy(vQuadEdge_Stage0.xy)); if (vQuadEdge_Stage0.z > 0.0 && vQuadEdge_Stage0.w > 0.0) { edgeAlpha = min(min(vQuadEdge_Stage0.z, vQuadEdge_Stage0.w) + 0.5, 1.0); } else { half2 gF = half2(2.0 * vQuadEdge_Stage0.x * duvdx.x - duvdx.y, 2.0 * vQuadEdge_Stage0.x * duvdy.x - duvdy.y); edgeAlpha = (vQuadEdge_Stage0.x*vQuadEdge_Stage0.x - vQuadEdge_Stage0.y); edgeAlpha = saturate(0.5 - edgeAlpha / length(gF)); } outputCoverage_Stage0 = half4(edgeAlpha); } { // Xfer Processor: Custom Xfermode if (all(lessThanEqual(outputCoverage_Stage0.rgb, half3(0)))) { discard; } // Read color from copy of the destination. half2 _dstTexCoord = (half2(sk_FragCoord.xy) - uDstTextureUpperLeft_Stage1) * uDstTextureCoordScale_Stage1; _dstTexCoord.y = 1.0 - _dstTexCoord.y; half4 _dstColor = sample(uDstTextureSampler_Stage1, _dstTexCoord); sk_FragColor.a = outputColor_Stage0.a + (1.0 - outputColor_Stage0.a) * _dstColor.a; half4 srcDstAlpha = outputColor_Stage0 * _dstColor.a; sk_FragColor.rgb = set_luminance_Stage1(_dstColor.rgb * outputColor_Stage0.a, srcDstAlpha.a, srcDstAlpha.rgb); sk_FragColor.rgb += (1.0 - outputColor_Stage0.a) * _dstColor.rgb + (1.0 - _dstColor.a) * outputColor_Stage0.rgb; sk_FragColor = outputCoverage_Stage0 * sk_FragColor + (half4(1.0) - outputCoverage_Stage0) * _dstColor; } } )"); ) #if defined(SK_BUILD_FOR_UNIX) #include <malloc.h> // These benchmarks aren't timed, they produce memory usage statistics. They run standalone, and // directly add their results to the nanobench log. void RunSkSLMemoryBenchmarks(NanoJSONResultsWriter* log) { auto heap_bytes_used = []() { return mallinfo().uordblks; }; auto bench = [log](const char* name, int bytes) { log->beginObject(name); // test log->beginObject("meta"); // config log->appendS32("bytes", bytes); // sub_result log->endObject(); // config log->endObject(); // test }; { int before = heap_bytes_used(); SkSL::Compiler compiler; int after = heap_bytes_used(); bench("sksl_compiler_baseline", after - before); } } #else void RunSkSLMemoryBenchmarks(NanoJSONResultsWriter*) {} #endif
[ "skia-commit-bot@chromium.org" ]
skia-commit-bot@chromium.org
9cdcf34541a409556441463c74f110f4e85b25b4
d04a03e59e9914268187211221c3942899d860ab
/src/editor/BsdfDisplay.hpp
082182c01256cee208928bd4f2260ef5f83a7d64
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "Zlib", "BSD-3-Clause", "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
01alchemist/tungsten
feb3a9e038471f447ee3a5ed82fe7db61bf437cb
787b1b3170c1bfa8a447b36d8e6f55e02540aad4
refs/heads/master
2021-01-25T06:36:26.068392
2017-08-05T03:09:20
2017-08-05T03:09:20
93,596,217
2
0
null
2017-08-05T03:09:20
2017-06-07T05:32:33
C++
UTF-8
C++
false
false
896
hpp
#ifndef BSDFDISPLAY_HPP_ #define BSDFDISPLAY_HPP_ #include <QLabel> #include <memory> class QImage; namespace Tungsten { class TraceableScene; class Primitive; class Scene; class Bsdf; class BsdfDisplay : public QLabel { Q_OBJECT enum PrimitiveMode { PRIMITIVE_SPHERE, PRIMITIVE_CUBE, PRIMITIVE_PLANE, }; int _w, _h; QImage _image; int _spp; PrimitiveMode _mode; std::unique_ptr<Scene> _scene; std::vector<std::shared_ptr<Primitive>> _prims; std::unique_ptr<TraceableScene> _flattenedScene; std::shared_ptr<Bsdf> _bsdf; void rebuildImage(); private slots: void finishRender(); public: BsdfDisplay(int w, int h, QWidget *parent = nullptr); ~BsdfDisplay(); public slots: void changeBsdf(std::shared_ptr<Bsdf> &bsdf); signals: void rendererFinished(); }; } #endif /* BSDFDISPLAY_HPP_ */
[ "mail@noobody.org" ]
mail@noobody.org
18e2386f79b7be44ab2b478c03c2759115ea5998
bd351c4d6b71836686aac138aa1ec253773ffd30
/mcrouter/routes/test/RateLimitRouteTest.cpp
4dd668547c9c37cc5b03287589e0d25b7fc01310
[ "BSD-3-Clause" ]
permissive
denveloper/mcrouter
30b5b96550df5d6dfbd31c9da7ec563dafacea17
918d8df9dd9d16958b81ea6b3beefd790bedf10b
refs/heads/master
2020-12-27T15:03:01.701596
2014-11-20T02:30:41
2014-11-20T02:30:41
26,824,719
0
1
null
null
null
null
UTF-8
C++
false
false
2,922
cpp
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <memory> #include <random> #include <vector> #include <gtest/gtest.h> #include <folly/json.h> #include "mcrouter/lib/test/RouteHandleTestUtil.h" #include "mcrouter/routes/RateLimitRoute.h" using namespace facebook::memcache; using namespace facebook::memcache::mcrouter; using std::make_shared; using std::string; using std::vector; /* These tests simply ensure that the various settings are read correctly. TokenBucket has its own tests */ namespace { template <class Data, class Operation> void test(Data data, Operation, mc_res_t ok, mc_res_t reject, const std::string& type, bool burst = false) { vector<std::shared_ptr<TestHandle>> normalHandle{ make_shared<TestHandle>(std::move(data)), }; auto normalRh = get_route_handles(normalHandle)[0]; auto json = folly::parseJson( (burst ? string("{\"") + type + "_rate\": 4.0, \"" + type + "_burst\": 3.0}" : string("{\"") + type + "_rate\": 2.0}")); TestRouteHandle<RateLimitRoute<TestRouteHandleIf>> rh( normalRh, RateLimiter(json)); if (burst) { usleep(1001000); /* Rate is 4/sec, but we can only have 3 at a time */ auto reply = rh.route(McRequest("key"), Operation()); EXPECT_EQ(reply.result(), ok); reply = rh.route(McRequest("key"), Operation()); EXPECT_EQ(reply.result(), ok); reply = rh.route(McRequest("key"), Operation()); EXPECT_EQ(reply.result(), ok); reply = rh.route(McRequest("key"), Operation()); EXPECT_EQ(reply.result(), reject); } else { usleep(501000); auto reply = rh.route(McRequest("key"), Operation()); EXPECT_EQ(reply.result(), ok); reply = rh.route(McRequest("key"), Operation()); EXPECT_EQ(reply.result(), reject); } } void testSets(bool burst = false) { test(UpdateRouteTestData(mc_res_stored), McOperation<mc_op_set>(), mc_res_stored, mc_res_notstored, "sets", burst); } void testGets(bool burst = false) { test(GetRouteTestData(mc_res_found, "a"), McOperation<mc_op_get>(), mc_res_found, mc_res_notfound, "gets", burst); } void testDeletes(bool burst = false) { test(DeleteRouteTestData(mc_res_deleted), McOperation<mc_op_delete>(), mc_res_deleted, mc_res_notfound, "deletes", burst); } } // namespace TEST(rateLimitRouteTest, setsBasic) { testSets(); } TEST(rateLimitRouteTest, setsBurst) { testSets(true); } TEST(rateLimitRouteTest, getsBasic) { testGets(); } TEST(rateLimitRouteTest, getsBurst) { testGets(true); } TEST(rateLimitRouteTest, deletesBasic) { testDeletes(); } TEST(rateLimitRouteTest, deletesBurst) { testDeletes(true); }
[ "alikhtarov@fb.com" ]
alikhtarov@fb.com
406071c35272d327d1752f91f2cdc5c21b3888e0
e3ff9bd01096c88aee3968ecfaecc4b2781c1608
/bitstream/boost/bitstream/bitstream_mainpage.hpp
55d91a401143f8aacbf56af2c5f49a1a7920433b
[]
no_license
dplong/bitstream
f4035ba62e15b7554655cbf6011f37526eb7b3b8
5a8d09613fe8ac847c25b6162a553f5d7f5f9a6b
refs/heads/master
2021-01-23T18:52:04.680003
2015-07-13T00:00:01
2015-07-13T00:00:01
11,407,008
2
0
null
null
null
null
UTF-8
C++
false
false
1,461
hpp
// Copyright Paul Long 2013 // Copyright Paul A. Bristow 2013 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org for updates, documentation, and revision history. #IFNDEF BOOST_BITSTREAM_DOXYGEN_MAINPAGE_HPP #DEFINE BOOST_BITSTREAM_DOXYGEN_MAINPAGE_HPP /*! \file \brief Bitstream documentation. \details Doxygen mainpage. \mainpage \b Bitstream mainpage. This is the front page of the \b Boost Bitstream documentation. \n Bitstream. The Boost.Bitstream library provides a succinct means to read and write binary data using the extraction and insertion operators. Its semantics mirror std::stringstream, it supports big- and little-endian integrals, can be extended to support user-defined types, and its performance is comparable to hand-coded codecs. This Doxygen mainpage also gives hyperlinks to the full html and pdf versions that also provide the full Quickbook/Doxygen generated information, with indexes: https://svn.boost.org/svn/boost/trunk/libs/bitstream/doc/html/index.html bitstream html Manual. https://svn.boost.org/svn/boost/trunk/libs/bitstream/doc/bitstream/.pdf bitstream PDF Manual. Or locally file:///I:/boost-sandbox/bitstream/libs/bitstream/doc/circular_buffer.pdf file:///I:/boost-sandbox/bitstream/libs/bitstream/doc/html/index.html */ #ENDIF BOOST_BITSTREAM_DOXYGEN_MAINPAGE_HPP
[ "plong@packetizer.com" ]
plong@packetizer.com
5a76f0160a3d94223c838bfcd75210262c1cc299
7c9136d87b8895ac6532ef2af58edf3ecc29d175
/StringStatusDlg.h
ea6afecf1722368d996bca0cb0b0ec18891ecef2
[]
no_license
khhubb/csda-new-ssb
038d75858cba1e029f4f1315d6ebba95e5d9fb91
96eaf896ba6c91914f69671171f5488cf0fb5d3f
refs/heads/master
2020-07-01T03:36:45.777439
2016-08-17T22:00:09
2016-08-17T22:00:09
74,102,071
0
0
null
null
null
null
UTF-8
C++
false
false
3,031
h
#if !defined(AFX_STRINGSTATUSDLG_H__09E93CEC_B711_11D1_806D_006097B38214__INCLUDED_) #define AFX_STRINGSTATUSDLG_H__09E93CEC_B711_11D1_806D_006097B38214__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // StringStatusDlg.h : header file // #include "StringStatusGrid.h" class CCasterScen; class CCastString; class CCastStringHeat; class CSuperScen; class CLongOpn; #include "CastString.h" #include "Snapshot.h" ///////////////////////////////////////////////////////////////////////////// // CStringStatusDlg dialog class CSnapScenChangeRecord { public: CCastString::E_StringStatus m_snapStatus; CCastString* m_pSnapString; CCastString* m_pScenString; UploadChangeType m_action; CString m_strStatus; CString m_strChoices; CString m_strAction; bool m_bEqual; CSnapScenChangeRecord( CCastString* pSnapString, CCastString* pScenString ); CSnapScenChangeRecord(); // default c-tor needed for vector bool operator<(const CSnapScenChangeRecord& x) const { return this < &x; } bool operator==(const CSnapScenChangeRecord& x) const { return this == &x; } }; class CStringStatusDlg : public CDialog { // Construction public: CStringStatusDlg(CWnd* pParent = NULL); // standard constructor enum COLUMNS { COL_CASTER = 1, COL_ID, COL_TONS, COL_HEATS, COL_ORIG_ID, COL_STATUS, COL_ACTION, COL_TAB_NUM, COL_SPEC, COL_CREATE_DATE }; CStringStatusGrid m_wndGrid; CCasterScen* m_pCasterScen; CCasterScen* m_pSnapScen; CSuperScen* m_pSuperScen; vector<CSnapScenChangeRecord> m_changeRecords; int m_currentStringIndex; void AnalyzeScenario(); void SetRows(); void SetRow(int nRow, CSnapScenChangeRecord& record); afx_msg BOOL OnNcActivate(BOOL bActive); CCastString* GetCurrentCastString(); void SetHeatListHeader(); void SetHeatListItems(); void AddItemForHeat(const CCastStringHeat& rHeat, int index); void OnMovedCurrentCell(ROWCOL nrow,ROWCOL ncol); void WriteUploadRecords(CLongOpn* pOpn); void FixHeatStatuses(); void FixSnapScen(); void FixOtherScens(); void FixOtherScen( CCasterScen* pScen ); void Archive910s(); // Dialog Data //{{AFX_DATA(CStringStatusDlg) enum { IDD = IDD_DLG_STRING_STATUS }; CListCtrl m_listHeats; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CStringStatusDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CStringStatusDlg) virtual BOOL OnInitDialog(); afx_msg void OnButtonHeatDetails(); virtual void OnOK(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_STRINGSTATUSDLG_H__09E93CEC_B711_11D1_806D_006097B38214__INCLUDED_)
[ "dmiller2718@gmail.com" ]
dmiller2718@gmail.com