blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6d5e4fd0b75cd30f234a6156ed7e8cbcc9653d60 | 88ae8695987ada722184307301e221e1ba3cc2fa | /printing/image.h | 717e913b7a39cc9e5604dec1d9684b223afde7ee | [
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 2,542 | h | image.h | // Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PRINTING_IMAGE_H_
#define PRINTING_IMAGE_H_
#include <stddef.h>
#include <stdint.h>
#include <string>
#include <vector>
#include "base/check.h"
#include "ui/gfx/geometry/size.h"
namespace base {
class FilePath;
}
namespace printing {
class Metafile;
// Lightweight raw-bitmap management. The image, once initialized, is immutable.
// The main purpose is testing image contents.
class Image {
public:
// Creates the image from the metafile. Deduces bounds based on bounds in
// metafile. If loading fails size().IsEmpty() will be true.
explicit Image(const Metafile& metafile);
// Copy constructor.
explicit Image(const Image& image);
~Image();
const gfx::Size& size() const { return size_; }
// Return a checksum of the image (MD5 over the internal data structure).
std::string checksum() const;
// Save image as PNG.
bool SaveToPng(const base::FilePath& filepath) const;
// Returns % of pixels different
double PercentageDifferent(const Image& rhs) const;
// Returns the 0x0RGB or 0xARGB value of the pixel at the given location.
uint32_t Color(uint32_t color) const {
if (ignore_alpha_)
return color & 0xFFFFFF; // Strip out A.
else
return color;
}
uint32_t pixel_at(int x, int y) const {
DCHECK(x >= 0 && x < size_.width());
DCHECK(y >= 0 && y < size_.height());
const uint32_t* data = reinterpret_cast<const uint32_t*>(&*data_.begin());
const uint32_t* data_row = data + y * row_length_ / sizeof(uint32_t);
return Color(data_row[x]);
}
private:
// Construct from metafile. This is kept internal since it's ambiguous what
// kind of data is used (png, bmp, metafile etc).
Image(const void* data, size_t size);
bool LoadPng(const std::string& compressed);
// Loads the first page from `metafile`.
bool LoadMetafile(const Metafile& metafile);
// Pixel dimensions of the image.
gfx::Size size_;
// Length of a line in bytes.
int row_length_;
// Actual bitmap data in arrays of RGBAs (so when loaded as uint32_t, it's
// 0xABGR).
std::vector<unsigned char> data_;
// Flag to signal if the comparison functions should ignore the alpha channel.
const bool ignore_alpha_; // Currently always true.
// Prevent operator= (this function has no implementation)
Image& operator=(const Image& image);
};
} // namespace printing
#endif // PRINTING_IMAGE_H_
|
1312c860a3174ddfb98ca2d18c2150c9e4cc3596 | 98ebf94bba761867ec2349d80f21342b5a0c6710 | /include/nativo.h | a9c44ee2669f94b7000a32b34b4f8c0749378434 | [] | no_license | LaelRodrigues/Projeto3 | 2e18169e7443c702f44fad834ab43388df307ca6 | 892d3c2fe992b1dddcd2c549cccf1e5576f6b97b | refs/heads/master | 2021-08-24T11:21:12.061699 | 2017-12-09T14:13:08 | 2017-12-09T14:13:08 | 112,865,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | h | nativo.h | /**
* @file nativo.h
* @brief Definicao da classe Nativo para representar
* um animal nativo
* @author Lael Rodrigues(laelrodrigues7@gmail.com)
* @since 03/12/2017
* @date 07/12/2017
*/
#ifndef NATIVO_H
#define NATIVO_H
#include "silvestre.h"
#include <ostream>
using std::ostream;
#include <string>
using std::string;
namespace PetFera {
/**
* @class Nativo nativo.h
* @brief Classe que representa um animal Nativo
* @details Atributos de um animal nativo sao: ibama, uf_origem e
* autorizacao
*/
class Nativo : public Silvestre {
protected:
string uf_origem; /**< UF de origem do animal nativo */
string autorizacao; /**< Autorizacao do animal nativo */
public:
/** @brief Construtor padrao */
Nativo();
/** @brief Construtor parametrizado */
Nativo(string _ibama, string _uf_origem, string _autorizacao);
/** @brief Destrutor padrao */
~Nativo();
/** @brief Retorna a UF de origem do animal nativo */
string getUf_origem();
/** @brief Retorna a autorizacao do animal nativo */
string getAutorizacao();
/** @brief Modifica a UF de origem do animal nativo */
void setUf_origem(string _uf_origem);
/** @brief Modifica a autorizacao do animal nativo */
void setAutorizacao(string _autorizacao);
};
}
#endif |
b1b11d7c0538f32c47f9fe4b491c3c3a946548de | 7919fce16d775fc73dbb82d5a99d2c0250b97ddd | /8. 문자열/[11654]아스키 코드.cpp | a775547a5da9d963f19235f169ed22135d29ddbc | [] | no_license | David-Donghyun-Kim/Baekjoon | 2da3c774a2ab4dea35e070c24fd3686125b297bd | 9bfc4e57bbbf89f520b2083c63b4b33af62d2b3b | refs/heads/master | 2022-11-18T09:45:44.499389 | 2020-07-24T05:52:16 | 2020-07-24T05:52:16 | 278,527,440 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | cpp | [11654]아스키 코드.cpp | #include <iostream>
using namespace std;
int changeToAscii(char input)
{
return (int)input;
}
int main()
{
char input;
cin >> input;
cout << changeToAscii(input) << "\n";
return 0;
} |
2b7c465658c311f0b6f4f125bdcbdb1d1c860917 | 6773a0f4a4a30d0ec78db763670f02a9c3f40afe | /DosyalamaOdev/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp | 6c88395106995893539542b87bb08f0f9d6d6f76 | [] | no_license | oguzhankrcb/C-PD2-ve-PD1-Laboratuvar-ve-odevler | 036f11d92e8ff165612c3a911094be498cdc6e6e | 39d69620e30d5121bb7ab00d937021dc42d8a478 | refs/heads/master | 2022-10-01T05:38:42.766741 | 2020-06-01T21:42:06 | 2020-06-01T21:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,023 | cpp | ConsoleApplication1.cpp | // ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <io.h>
#include <string.h>
struct ogrenci
{
char k;
char num[10];
char adsoyad[30];
char tel[16];
} ogrkay;
FILE *dosya;
int i, kaysay, say;
long kayit_yer;
char cev, c;
int ksay(void)
{
return ((filelength(fileno(dosya)) / sizeof(struct ogrenci)));
}
void kalicisilturkcell(void)
{
FILE * newkalici = fopen("ren.dat", "w+b");
dosya = fopen("ogrenci.dat", "r+b");
int sayi = ksay();
int i = 0;
int buldumu = 0;
for (i; i < sayi; i++)
{
fseek(dosya, i * sizeof(struct ogrenci), SEEK_SET);
fread(&ogrkay, sizeof(struct ogrenci), 1, dosya);
if (ogrkay.tel[0] == '5' && ogrkay.tel[1] == '3')
{
buldumu++;
}
else
{
fseek(newkalici, (i-buldumu) * sizeof(struct ogrenci), SEEK_SET);
fwrite(&ogrkay, sizeof(struct ogrenci), 1, newkalici);
}
}
fclose(dosya);
fclose(newkalici);
if (buldumu > 0)
{
remove("ogrenci.dat");
rename("ren.dat", "ogrenci.dat");
}
else
{
remove("ren.dat");
}
}
void duzelt(void)
{
dosya = fopen("ogrenci.dat", "r+b");
char duzeltilecek[] = " ";
char buldu = 0;
char dsay = 0;
printf("\nDüzeltilmesi gereken numaranýn sahibini giriniz: ");
gets(duzeltilecek);
kaysay = ksay();
for (int i = 0; i<kaysay; i++)
{
fseek(dosya, (i*sizeof(struct ogrenci)), SEEK_SET);
fread(&ogrkay, sizeof(struct ogrenci), 1, dosya);
if (ogrkay.k == '*' && !strcmp(ogrkay.adsoyad, duzeltilecek))
{
printf("%-10s %-30s %-16s", ogrkay.num, ogrkay.adsoyad, ogrkay.tel);
printf("\nBu kaydý mý düzelteceksiniz (E/H)");
char sec = getch();
if (sec == 'E' || sec == 'e')
{
buldu = 1;
dsay++;
say++;
printf("\nYeni numara giriniz: ");
gets(ogrkay.tel);
fseek(dosya, (i*sizeof(struct ogrenci)), SEEK_SET);
fwrite(&ogrkay, sizeof(struct ogrenci), 1, dosya);
}
}
}
if (buldu)
{
printf("\nDüzeltilen Kayit Sayisi= %d", dsay);
}
else
printf("\nDüzeltilecek kayit bulunamadi...");
fclose(dosya);
getch();
}
void kayit_ekle(void)
{
dosya = fopen("ogrenci.dat", "r+b");
if (dosya == NULL)
dosya = fopen("ogrenci.dat", "w+b");
system("cls");
fflush(stdin);
printf("Numara.....:");
gets(ogrkay.num);
printf("Ad Soyad ..:");
gets(ogrkay.adsoyad);
printf("Tel........:");
gets(ogrkay.tel);
printf("Girilen Bilgiler Dogru mu? [E/H]");
cev = getche();
if (cev == 'E' || cev == 'e')
{
ogrkay.k = '*';
fseek(dosya, filelength(fileno(dosya)), SEEK_SET);
fwrite(&ogrkay, sizeof(struct ogrenci), 1, dosya);
}
fclose(dosya);
}
void baslik(void)
{
system("cls");
if (dosya == NULL) printf("Dosya acilamadi");
printf("%-10s %-30s %-16s \n\n", "NUMARA", "AD SOYAD", "TELEFON");
say = 0;
}
void listele(void)
{
dosya = fopen("ogrenci.dat", "rb");
baslik();
kaysay = ksay();
for (int i = 0; i<kaysay; i++)
{
fseek(dosya, (i*sizeof(struct ogrenci)), SEEK_SET);
fread(&ogrkay, sizeof(struct ogrenci), 1, dosya);
if (ogrkay.k == '*')
{
say++;
printf("%-10s", ogrkay.num);
printf("%-30s", ogrkay.adsoyad);
printf("%-16s\n", ogrkay.tel);
if (say == 20)
{
printf("Diger sayfaya gecmek icin bir tusa basiniz");
getch();
baslik();
}
}
}
printf("\nToplam Kayit Sayisi= %d", kaysay);
printf("\n\nListelenecek kayitlar bitti...");
fclose(dosya);
getch();
}
void ara(void)
{
dosya = fopen("ogrenci.dat", "rb");
char aranan[] = " "; char buldu = 0; char arasay = 0;
printf("\nBulunmasý istenen ismi giriniz: "); gets(aranan);
kaysay = ksay();
for (int i = 0; i<kaysay; i++)
{
fseek(dosya, (i*sizeof(struct ogrenci)), SEEK_SET);
fread(&ogrkay, sizeof(struct ogrenci), 1, dosya);
if (ogrkay.k == '*' && !strcmp(ogrkay.adsoyad, aranan))
{
buldu = 1; arasay++;
say++;
if (arasay == 1)
baslik();
printf("%-10s", ogrkay.num); printf("%-30s", ogrkay.adsoyad); printf("%-16s\n", ogrkay.tel);
}
}
if (buldu)
{
printf("\nToplam Kayit Sayisi= %d", arasay);
printf("\n\nListelenecek kayitlar bitti...");
}
else
printf("\nAranan kayit bulunamadi...");
fclose(dosya);
getch();
}
void sil(void)
{
dosya = fopen("ogrenci.dat", "r+b");
char aranan[] = " ";
char buldu = 0;
char silsay = 0;
printf("\nSilinmesi istenen ismi giriniz: ");
gets(aranan);
kaysay = ksay();
for (int i = 0; i<kaysay; i++)
{
fseek(dosya, (i*sizeof(struct ogrenci)), SEEK_SET);
fread(&ogrkay, sizeof(struct ogrenci), 1, dosya);
if (ogrkay.k == '*' && !strcmp(ogrkay.adsoyad, aranan))
{
buldu = 1;
silsay++;
say++;
ogrkay.k = '-';
fseek(dosya, (i*sizeof(struct ogrenci)), SEEK_SET);
fwrite(&ogrkay, sizeof(struct ogrenci), 1, dosya);
}
}
if (buldu)
{
printf("\nSilinen Kayit Sayisi= %d", silsay);
}
else
printf("\nAranan kayit bulunamadi...");
fclose(dosya);
getch();
}
void getir(void)
{
dosya = fopen("ogrenci.dat", "r+b");
char aranan[] = " ";
char buldu = 0;
char gerigetirilensay = 0;
printf("\nGeri Getirilmesi istenen ismi giriniz: ");
gets(aranan);
kaysay = ksay();
for (int i = 0; i<kaysay; i++)
{
fseek(dosya, (i*sizeof(struct ogrenci)), SEEK_SET);
fread(&ogrkay, sizeof(struct ogrenci), 1, dosya);
if (ogrkay.k == '-' && !strcmp(ogrkay.adsoyad, aranan))
{
buldu = 1;
gerigetirilensay++;
say++;
ogrkay.k = '*';
fseek(dosya, (i*sizeof(struct ogrenci)), SEEK_SET);
fwrite(&ogrkay, sizeof(struct ogrenci), 1, dosya);
}
}
if (buldu)
{
printf("\nGeri getirilen Kayit Sayisi= %d", gerigetirilensay);
}
else
printf("\nAranan kayit bulunamadi...");
fclose(dosya);
getch();
}
int main()
{
do
{
system("cls");
printf("1-Bilgi girisi \n2-Bilgi Listeleme \n3-Ara \n4-Sil \n5-Getir \n6-Düzelt \n7-Cikis \n\nSecim:");
c = getche();
if (c == '1') kayit_ekle();
if (c == '2') listele();
if (c == '3') ara();
if (c == '4') sil();
if (c == '5') getir();
if (c == '6') duzelt();
if (c == '7') kalicisilturkcell();
if (c == '8') exit(0);
} while (c != '8');
getch();
return 0;
}
|
ef308edcf44a257fd1a68eadd7b4f371d50223f8 | 2ba100db9cdaf071fb90c40827f01d37cb4758b1 | /data/offline/makeUSCorrections.cxx | 9eb761eb9114efa765b631ff037aff613541a639 | [] | no_license | rhanniga/kaon-over-hadron | 3b1bc02525350f31d45d48f6738800ca75edfd04 | 7e87f8db9fb536b5e7cad83c9ee74075098e8a67 | refs/heads/master | 2023-09-06T06:12:41.072321 | 2021-10-05T21:34:10 | 2021-10-05T21:34:10 | 265,469,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,258 | cxx | makeUSCorrections.cxx | void makeUSCorrections(string inputFile){
TFile* input = new TFile(inputFile.c_str());
TH2D* hKaon2Dpeak = (TH2D*)input->Get("hKaon2Dpeak");
TH2D* hKaon2DLside = (TH2D*)input->Get("hKaon2DLside");
TH2D* hKaon2DRside = (TH2D*)input->Get("hKaon2DRside");
TH2D* hKaonLS2Dpeak = (TH2D*)input->Get("hKaonLS2Dpeak");
TH2D* hKaonLS2DLside = (TH2D*)input->Get("hKaonLS2DLside");
TH2D* hKaonLS2DRside = (TH2D*)input->Get("hKaonLS2DRside");
TH2D* trigDistSameUS = (TH2D*)input->Get("fTrigSameUSDist");
TH2D* trigDistSameLS = (TH2D*)input->Get("fTrigSameLSDist");
hKaon2Dpeak->SetName("uncorrectedhKaon2Dpeak");
TH2D* hKaonBGPeakRegionL = (TH2D*)hKaon2DLside->Clone("hKaonBGPeakRegionL");
hKaonBGPeakRegionL->Scale(1.0/(hKaon2DLside->Integral(hKaon2DLside->GetXaxis()->FindBin(-1.2), hKaon2DLside->GetXaxis()->FindBin(1.2), 1, hKaon2DLside->GetYaxis()->GetNbins())));
hKaonBGPeakRegionL->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* hKaonBGPeakRegionL_deta = (TH1D*)hKaonBGPeakRegionL->ProjectionX("hKaonBGPeakRegionL_deta", 1, hKaonBGPeakRegionL->GetYaxis()->GetNbins());
TH1D* hKaonBGPeakRegionL_dphi = (TH1D*)hKaonBGPeakRegionL->ProjectionY("hKaonBGPeakRegionL_dphi", hKaonBGPeakRegionL->GetXaxis()->FindBin(-1.2), hKaonBGPeakRegionL->GetXaxis()->FindBin(1.2));
TH2D* hKaonBGPeakRegionR = (TH2D*)hKaon2DRside->Clone("hKaonBGPeakRegionR");
hKaonBGPeakRegionR->Scale(1.0/(hKaon2DRside->Integral(hKaon2DRside->GetXaxis()->FindBin(-1.2), hKaon2DRside->GetXaxis()->FindBin(1.2), 1, hKaon2DRside->GetYaxis()->GetNbins())));
hKaonBGPeakRegionR->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* hKaonBGPeakRegionR_deta = (TH1D*)hKaonBGPeakRegionR->ProjectionX("hKaonBGPeakRegionR_deta", 1, hKaonBGPeakRegionR->GetYaxis()->GetNbins());
TH1D* hKaonBGPeakRegionR_dphi = (TH1D*)hKaonBGPeakRegionR->ProjectionY("hKaonBGPeakRegionR_dphi", hKaonBGPeakRegionR->GetXaxis()->FindBin(-1.2), hKaonBGPeakRegionR->GetXaxis()->FindBin(1.2));
TH2D* hKaonBGPeakRegion = (TH2D*)hKaonBGPeakRegionL->Clone("hKaonBGPeakregion");
hKaonBGPeakRegion->Add(hKaonBGPeakRegionR);
hKaonBGPeakRegion->Scale(0.5);
hKaonBGPeakRegion->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* hKaonBGPeakRegion_deta = (TH1D*)hKaonBGPeakRegion->ProjectionX("hKaonBGPeakRegion_deta", 1, hKaonBGPeakRegion->GetYaxis()->GetNbins());
TH1D* hKaonBGPeakRegion_dphi = (TH1D*)hKaonBGPeakRegion->ProjectionY("hKaonBGPeakRegion_dphi", hKaonBGPeakRegion->GetXaxis()->FindBin(-1.2), hKaonBGPeakRegion->GetXaxis()->FindBin(1.2));
//US residual checks between SB average and the Left and Right separately
TH2D* resLeftVsAvg = (TH2D*)hKaonBGPeakRegionL->Clone("resLeftVsAvg");
resLeftVsAvg->Add(hKaonBGPeakRegion, -1.0);
resLeftVsAvg->Divide(hKaonBGPeakRegionL);
resLeftVsAvg->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* resLeftVsAvg_deta = (TH1D*)hKaonBGPeakRegionL_deta->Clone("resLeftVsAvg_deta");
resLeftVsAvg_deta->Add(hKaonBGPeakRegion_deta, -1.0);
resLeftVsAvg_deta->Divide(hKaonBGPeakRegionL_deta);
resLeftVsAvg_deta->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* resLeftVsAvg_dphi = (TH1D*)hKaonBGPeakRegionL_dphi->Clone("resLeftVsAvg_dphi");
resLeftVsAvg_dphi->Add(hKaonBGPeakRegion_dphi, -1.0);
resLeftVsAvg_dphi->Divide(hKaonBGPeakRegionL_dphi);
TH2D* resRightVsAvg = (TH2D*)hKaonBGPeakRegionR->Clone("resRightVsAbg");
resRightVsAvg->Add(hKaonBGPeakRegion, -1.0);
resRightVsAvg->Divide(hKaonBGPeakRegionR);
resRightVsAvg->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* resRightVsAvg_deta = (TH1D*)hKaonBGPeakRegionR_deta->Clone("resRightVsAvg_deta");
resRightVsAvg_deta->Add(hKaonBGPeakRegion_deta, -1.0);
resRightVsAvg_deta->Divide(hKaonBGPeakRegionR_deta);
resRightVsAvg_deta->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* resRightVsAvg_dphi = (TH1D*)hKaonBGPeakRegionR_dphi->Clone("resRightVsAvg_dphi");
resRightVsAvg_dphi->Add(hKaonBGPeakRegion_dphi, -1.0);
resRightVsAvg_dphi->Divide(hKaonBGPeakRegionR_dphi);
Float_t leftscale = hKaon2DLside->Integral(hKaon2DLside->GetXaxis()->FindBin(-1.2), hKaon2DLside->GetXaxis()->FindBin(1.2), 1, hKaon2DLside->GetYaxis()->GetNbins())/hKaonLS2DLside->Integral(hKaon2DLside->GetXaxis()->FindBin(-1.2), hKaon2DLside->GetXaxis()->FindBin(1.2), 1, hKaon2DLside->GetYaxis()->GetNbins());
TH2D* LLSsubhKaon2DLside = (TH2D*)hKaon2DLside->Clone("LLSsubhKaon2DLside");
TH2D* LLSsubhKaon2Dpeak = (TH2D*)hKaon2Dpeak->Clone("LLSsubhKaon2Dpeak");
LLSsubhKaon2DLside->Add(hKaonLS2DLside, -1.0*leftscale);
//LLSsubhKaon2DLside->Divide(hKaonLS2DLside);
//LLSsubhKaon2DLside->Scale(1.0/leftscale);
LLSsubhKaon2Dpeak->Add(hKaonLS2Dpeak, -1.0*leftscale);
TH1D* LLSsubhKaon2DLside_deta = LLSsubhKaon2DLside->ProjectionX("LLSsubhKaon2DLside_deta", 1, LLSsubhKaon2DLside->GetYaxis()->GetNbins());
TH1D* LLSsubhKaon2DLside_dphi = LLSsubhKaon2DLside->ProjectionY("LLSsubhKaon2DLside_dphi", LLSsubhKaon2DLside->GetXaxis()->FindBin(-1.2), LLSsubhKaon2DLside->GetXaxis()->FindBin(1.2));
//Float_t rightscale = hKaon2DRside->Integral(1, hKaon2DRside->GetXaxis()->GetNbins(), 1, hKaon2DRside->GetYaxis()->GetNbins())/hKaonLS2DRside->Integral(1, hKaon2DRside->GetXaxis()->GetNbins(), 1, hKaon2DRside->GetYaxis()->GetNbins());
gStyle->SetOptStat(0);
Float_t rightscale = hKaon2DRside->Integral(hKaon2DRside->GetXaxis()->FindBin(-1.2), hKaon2DRside->GetXaxis()->FindBin(1.2), 1, hKaon2DRside->GetYaxis()->GetNbins())/hKaonLS2DRside->Integral(hKaon2DRside->GetXaxis()->FindBin(-1.2), hKaon2DRside->GetXaxis()->FindBin(1.2), 1, hKaon2DRside->GetYaxis()->GetNbins());
TH2D* RLSsubhKaon2DRside = (TH2D*)hKaon2DRside->Clone("RLSsubhKaon2DRside");
TH2D* RLSsubhKaon2Dpeak = (TH2D*)hKaon2Dpeak->Clone("RLSsubhKaon2Dpeak");
TH2D* RLSsubhKaon2DRsideScaled = (TH2D*)hKaon2DRside->Clone("RLSsubhKaon2DRsideScaled");
RLSsubhKaon2DRsideScaled->GetXaxis()->SetRangeUser(-1.2, 1.2);
RLSsubhKaon2DRsideScaled->Scale(rightscale);
TH1D* RLSsubhKaonDPhiRsideScaled = RLSsubhKaon2DRsideScaled->ProjectionY();
RLSsubhKaonDPhiRsideScaled->SetTitle("h-#Kaon^{0} scaled R-sideband #Delta#varphi distribution");
RLSsubhKaonDPhiRsideScaled->SetLineColor(6);
RLSsubhKaonDPhiRsideScaled->SetLineWidth(3);
RLSsubhKaonDPhiRsideScaled->SetMarkerColor(6);
TCanvas *presCanvas = new TCanvas("presCanvas", "Presentation Canvas", 0, 10, 1600, 1200);
presCanvas->cd();
RLSsubhKaonDPhiRsideScaled->Draw();
RLSsubhKaon2DRside->Add(hKaonLS2DRside, -1.0*rightscale);
//RLSsubhKaon2DRside->Divide(hKaonLS2DRside);
//RLSsubhKaon2DRside->Scale(1.0/rightscale);
RLSsubhKaon2Dpeak->Add(hKaonLS2Dpeak, -1.0*rightscale);
RLSsubhKaon2Dpeak->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* RLSsubhKaon2DRside_deta = RLSsubhKaon2DRside->ProjectionX("RLSsubhKaon2DRside_deta", 1, RLSsubhKaon2DRside->GetYaxis()->GetNbins());
TH1D* RLSsubhKaon2DRside_dphi = RLSsubhKaon2DRside->ProjectionY("RLSsubhKaon2DRside_dphi", RLSsubhKaon2DRside->GetXaxis()->FindBin(-1.2), RLSsubhKaon2DRside->GetXaxis()->FindBin(1.2));
TH1D* RLSsubhKaon2Dpeak_deta = RLSsubhKaon2Dpeak->ProjectionX("RLSsubhKaon2Dpeak_deta", 1, RLSsubhKaon2Dpeak->GetYaxis()->GetNbins());
TH1D* RLSsubhKaon2Dpeak_dphi = RLSsubhKaon2Dpeak->ProjectionY("RLSsubhKaon2Dpeak_dphi", RLSsubhKaon2Dpeak->GetXaxis()->FindBin(-1.2), RLSsubhKaon2Dpeak->GetXaxis()->FindBin(1.2));
TH1D* scales = new TH1D("scales", "scales", 2, -1, 1);
scales->SetBinContent(1, leftscale);
scales->SetBinContent(2, rightscale);
TH2D* rebinRLSsubhKaon2Dpeak = (TH2D*)RLSsubhKaon2Dpeak->Clone("rebinRLSsubhKaon2Dpeak");
rebinRLSsubhKaon2Dpeak->Rebin2D(2, 2);
//Using US estimate for BG to subtract off the from the peak region:
Float_t scaleUS = (rightscale)*hKaonLS2Dpeak->Integral(hKaonLS2Dpeak->GetXaxis()->FindBin(-1.2), hKaonLS2Dpeak->GetXaxis()->FindBin(1.2), 1, hKaonLS2Dpeak->GetYaxis()->GetNbins());
Float_t scaletest = (rightscale)*hKaon2Dpeak->Integral(hKaon2Dpeak->GetXaxis()->FindBin(-1.2), hKaon2Dpeak->GetXaxis()->FindBin(1.2), 1, hKaon2Dpeak->GetYaxis()->GetNbins());
printf("\n\nscaleUS = %e\n\ntestscale = %e \n\n", scaleUS, scaletest);
//avg of right and left US sideband tests
TH2D* AvgUSsubhKaon2Dpeak = (TH2D*)hKaon2Dpeak->Clone("AvgUSsubhKaon2Dpeak");
AvgUSsubhKaon2Dpeak->Add(hKaonBGPeakRegion, -1.0*scaleUS);
AvgUSsubhKaon2Dpeak->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* AvgUSsubhKaon2Dpeak_deta = (TH1D*)AvgUSsubhKaon2Dpeak->ProjectionX("AvgUSsubhKaon2Dpeak_deta", 1, AvgUSsubhKaon2Dpeak->GetYaxis()->GetNbins());
TH1D* AvgUSsubhKaon2Dpeak_dphi = (TH1D*)AvgUSsubhKaon2Dpeak->ProjectionY("AvgUSsubhKaon2Dpeak_dphi", AvgUSsubhKaon2Dpeak->GetXaxis()->FindBin(-1.2), AvgUSsubhKaon2Dpeak->GetXaxis()->FindBin(1.2));
TH2D* AvgUSsubhKaon2Dpeakleftscale = (TH2D*)hKaon2Dpeak->Clone("AvgUSsubhKaon2Dpeakleftscale");
AvgUSsubhKaon2Dpeakleftscale->Add(hKaonBGPeakRegion, -1.0*scaleUS*leftscale/rightscale);
AvgUSsubhKaon2Dpeakleftscale->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* AvgUSsubhKaon2Dpeakleftscale_deta = (TH1D*)AvgUSsubhKaon2Dpeakleftscale->ProjectionX("AvgUSsubhKaon2Dpeakleftscale_deta", 1, AvgUSsubhKaon2Dpeakleftscale->GetYaxis()->GetNbins());
TH1D* AvgUSsubhKaon2Dpeakleftscale_dphi = (TH1D*)AvgUSsubhKaon2Dpeakleftscale->ProjectionY("AvgUSsubhKaon2Dpeakleftscale_dphi", AvgUSsubhKaon2Dpeakleftscale->GetXaxis()->FindBin(-1.2), AvgUSsubhKaon2Dpeakleftscale->GetXaxis()->FindBin(1.2));
TH2D* AvgUSsubhKaon2Dpeakavgscale = (TH2D*)hKaon2Dpeak->Clone("AvgUSsubhKaon2Dpeakavgscale");
AvgUSsubhKaon2Dpeakavgscale->Add(hKaonBGPeakRegion, -1.0*scaleUS*(leftscale + rightscale)/(2.0*rightscale));
AvgUSsubhKaon2Dpeakavgscale->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* AvgUSsubhKaon2Dpeakavgscale_deta = (TH1D*)AvgUSsubhKaon2Dpeakavgscale->ProjectionX("AvgUSsubhKaon2Dpeakavgscale_deta", 1, AvgUSsubhKaon2Dpeakavgscale->GetYaxis()->GetNbins());
TH1D* AvgUSsubhKaon2Dpeakavgscale_dphi = (TH1D*)AvgUSsubhKaon2Dpeakavgscale->ProjectionY("AvgUSsubhKaon2Dpeakavgscale_dphi", AvgUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(-1.2), AvgUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(1.2));
//right side US sideband tests
TH2D* RSUSsubhKaon2Dpeak = (TH2D*)hKaon2Dpeak->Clone("RSUSsubhKaon2Dpeak");
RSUSsubhKaon2Dpeak->Add(hKaonBGPeakRegionR, -1.0*scaleUS);
RSUSsubhKaon2Dpeak->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* RSUSsubhKaon2Dpeak_deta = (TH1D*)RSUSsubhKaon2Dpeak->ProjectionX("RSUSsubhKaon2Dpeak_deta", 1, RSUSsubhKaon2Dpeak->GetYaxis()->GetNbins());
TH1D* RSUSsubhKaon2Dpeak_dphi = (TH1D*)RSUSsubhKaon2Dpeak->ProjectionY("RSUSsubhKaon2Dpeak_dphi", RSUSsubhKaon2Dpeak->GetXaxis()->FindBin(-1.2), RSUSsubhKaon2Dpeak->GetXaxis()->FindBin(1.2));
TH2D* RSUSsubhKaon2Dpeakleftscale = (TH2D*)hKaon2Dpeak->Clone("RSUSsubhKaon2Dpeakleftscale");
RSUSsubhKaon2Dpeakleftscale->Add(hKaonBGPeakRegionR, -1.0*scaleUS*leftscale/rightscale);
RSUSsubhKaon2Dpeakleftscale->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* RSUSsubhKaon2Dpeakleftscale_deta = (TH1D*)RSUSsubhKaon2Dpeakleftscale->ProjectionX("RSUSsubhKaon2Dpeakleftscale_deta", 1, RSUSsubhKaon2Dpeakleftscale->GetYaxis()->GetNbins());
TH1D* RSUSsubhKaon2Dpeakleftscale_dphi = (TH1D*)RSUSsubhKaon2Dpeakleftscale->ProjectionY("RSUSsubhKaon2Dpeakleftscale_dphi", RSUSsubhKaon2Dpeakleftscale->GetXaxis()->FindBin(-1.2), RSUSsubhKaon2Dpeakleftscale->GetXaxis()->FindBin(1.2));
//GOTO HERE
TH2D* RSUSsubhKaon2Dpeakavgscale = (TH2D*)hKaon2Dpeak->Clone("RSUSsubhKaon2Dpeakavgscale");
RSUSsubhKaon2Dpeakavgscale->Add(hKaonBGPeakRegionR, -1.0*scaleUS*(leftscale+rightscale)/(2.0*rightscale));
RSUSsubhKaon2Dpeakavgscale->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* RSUSsubhKaon2Dpeakavgscale_deta = (TH1D*)RSUSsubhKaon2Dpeakavgscale->ProjectionX("RSUSsubhKaon2Dpeakavgscale_deta", 1, RSUSsubhKaon2Dpeakavgscale->GetYaxis()->GetNbins());
TH1D* RSUSsubhKaon2Dpeakavgscale_dphi = (TH1D*)RSUSsubhKaon2Dpeakavgscale->ProjectionY("RSUSsubhKaon2Dpeakavgscale_dphi", RSUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(-1.2), RSUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(1.2));
//END GOTO
// double signalOverTotalArray[3] = {0.09745, 0.1191, 0.1697}; // have to change this for each multiplicity bin
// TH2D* RSUSsubhKaon2Dpeakavgscale = (TH2D*)hKaon2Dpeak->Clone("RSUSsubhKaon2Dpeakavgscale");
// // Using BG = TOTAL - SIGNAL = TOTAL(1-S/TOTAL)
// double bgIntegral = RSUSsubhKaon2Dpeakavgscale->Integral(RSUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(-1.2), RSUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(1.2), 1, RSUSsubhKaon2Dpeakavgscale->GetYaxis()->GetNbins())*(1 - signalOverTotalArray[2]);
// RSUSsubhKaon2Dpeakavgscale->Add(hKaonBGPeakRegionR, -1.0*bgIntegral);
// RSUSsubhKaon2Dpeakavgscale->GetXaxis()->SetRangeUser(-1.2, 1.2);
// TH1D* RSUSsubhKaon2Dpeakavgscale_deta = (TH1D*)RSUSsubhKaon2Dpeakavgscale->ProjectionX("RSUSsubhKaon2Dpeakavgscale_deta", 1, RSUSsubhKaon2Dpeakavgscale->GetYaxis()->GetNbins());
// TH1D* RSUSsubhKaon2Dpeakavgscale_dphi = (TH1D*)RSUSsubhKaon2Dpeakavgscale->ProjectionY("RSUSsubhKaon2Dpeakavgscale_dphi", RSUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(-1.2), RSUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(1.2));
//left side US sideband tests
TH2D* LSUSsubhKaon2Dpeak = (TH2D*)hKaon2Dpeak->Clone("LSUSsubhKaon2Dpeak");
LSUSsubhKaon2Dpeak->Add(hKaonBGPeakRegionL, -1.0*scaleUS);
LSUSsubhKaon2Dpeak->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* LSUSsubhKaon2Dpeak_deta = (TH1D*)LSUSsubhKaon2Dpeak->ProjectionX("LSUSsubhKaon2Dpeak_deta", 1, LSUSsubhKaon2Dpeak->GetYaxis()->GetNbins());
TH1D* LSUSsubhKaon2Dpeak_dphi = (TH1D*)LSUSsubhKaon2Dpeak->ProjectionY("LSUSsubhKaon2Dpeak_dphi", LSUSsubhKaon2Dpeak->GetXaxis()->FindBin(-1.2), LSUSsubhKaon2Dpeak->GetXaxis()->FindBin(1.2));
TH2D* LSUSsubhKaon2Dpeakleftscale = (TH2D*)hKaon2Dpeak->Clone("LSUSsubhKaon2Dpeakleftscale");
LSUSsubhKaon2Dpeakleftscale->Add(hKaonBGPeakRegionL, -1.0*scaleUS*leftscale/rightscale);
LSUSsubhKaon2Dpeakleftscale->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* LSUSsubhKaon2Dpeakleftscale_deta = (TH1D*)LSUSsubhKaon2Dpeakleftscale->ProjectionX("LSUSsubhKaon2Dpeakleftscale_deta", 1, LSUSsubhKaon2Dpeakleftscale->GetYaxis()->GetNbins());
TH1D* LSUSsubhKaon2Dpeakleftscale_dphi = (TH1D*)LSUSsubhKaon2Dpeakleftscale->ProjectionY("LSUSsubhKaon2Dpeakleftscale_dphi", LSUSsubhKaon2Dpeakleftscale->GetXaxis()->FindBin(-1.2), LSUSsubhKaon2Dpeakleftscale->GetXaxis()->FindBin(1.2));
TH2D* LSUSsubhKaon2Dpeakavgscale = (TH2D*)hKaon2Dpeak->Clone("LSUSsubhKaon2Dpeakavgscale");
LSUSsubhKaon2Dpeakavgscale->Add(hKaonBGPeakRegionL, -1.0*scaleUS*(leftscale+rightscale)/(2.0*rightscale));
LSUSsubhKaon2Dpeakavgscale->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* LSUSsubhKaon2Dpeakavgscale_deta = (TH1D*)LSUSsubhKaon2Dpeakavgscale->ProjectionX("LSUSsubhKaon2Dpeakavgscale_deta", 1, LSUSsubhKaon2Dpeakavgscale->GetYaxis()->GetNbins());
TH1D* LSUSsubhKaon2Dpeakavgscale_dphi = (TH1D*)LSUSsubhKaon2Dpeakavgscale->ProjectionY("LSUSsubhKaon2Dpeakavgscale_dphi", LSUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(-1.2), LSUSsubhKaon2Dpeakavgscale->GetXaxis()->FindBin(1.2));
TH2D* resUSvsLS = (TH2D*)AvgUSsubhKaon2Dpeak->Clone("resUSvsLS");
resUSvsLS->Add(RLSsubhKaon2Dpeak, -1.0);
resUSvsLS->Divide(AvgUSsubhKaon2Dpeak);
resUSvsLS->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* resUSvsLS_deta = (TH1D*)AvgUSsubhKaon2Dpeak_deta->Clone("resUSvsLS_deta");
resUSvsLS_deta->Add(RLSsubhKaon2Dpeak_deta, -1.0);
resUSvsLS_deta->Divide(AvgUSsubhKaon2Dpeak_deta);
resUSvsLS_deta->GetXaxis()->SetRangeUser(-1.2, 1.2);
TH1D* resUSvsLS_dphi = (TH1D*)AvgUSsubhKaon2Dpeak_dphi->Clone("resUSvsLS_dphi");
resUSvsLS_dphi->Add(RLSsubhKaon2Dpeak_dphi, -1.0);
resUSvsLS_dphi->Divide(AvgUSsubhKaon2Dpeak_dphi);
TFile* output = new TFile(Form("US_syst_%s", inputFile.c_str()), "RECREATE");
LLSsubhKaon2DLside->Write();
LLSsubhKaon2DLside_deta->Write();
LLSsubhKaon2DLside_dphi->Write();
LLSsubhKaon2Dpeak->Write();
RLSsubhKaon2DRside->Write();
RLSsubhKaon2DRside_deta->Write();
RLSsubhKaon2DRside_dphi->Write();
RLSsubhKaon2Dpeak->Write();
RLSsubhKaon2Dpeak_deta->Write();
RLSsubhKaon2Dpeak_dphi->Write();
rebinRLSsubhKaon2Dpeak->Write();
scales->Write();
hKaon2Dpeak->Write();
hKaonBGPeakRegionL->Write();
hKaonBGPeakRegionL_deta->Write();
hKaonBGPeakRegionL_dphi->Write();
hKaonBGPeakRegionR->Write();
hKaonBGPeakRegionR_deta->Write();
hKaonBGPeakRegionR_dphi->Write();
hKaonBGPeakRegion->Write();
hKaonBGPeakRegion_deta->Write();
hKaonBGPeakRegion_dphi->Write();
resLeftVsAvg->Write();
resLeftVsAvg_deta->Write();
resLeftVsAvg_dphi->Write();
resRightVsAvg->Write();
resRightVsAvg_deta->Write();
resRightVsAvg_dphi->Write();
AvgUSsubhKaon2Dpeak->Write();
AvgUSsubhKaon2Dpeak_deta->Write();
AvgUSsubhKaon2Dpeak_dphi->Write();
AvgUSsubhKaon2Dpeakleftscale->Write();
AvgUSsubhKaon2Dpeakleftscale_deta->Write();
AvgUSsubhKaon2Dpeakleftscale_dphi->Write();
AvgUSsubhKaon2Dpeakavgscale->Write();
AvgUSsubhKaon2Dpeakavgscale_deta->Write();
AvgUSsubhKaon2Dpeakavgscale_dphi->Write();
RSUSsubhKaon2Dpeak->Write();
RSUSsubhKaon2Dpeak_deta->Write();
RSUSsubhKaon2Dpeak_dphi->Write();
RSUSsubhKaon2Dpeakleftscale->Write();
RSUSsubhKaon2Dpeakleftscale_deta->Write();
RSUSsubhKaon2Dpeakleftscale_dphi->Write();
RSUSsubhKaon2Dpeakavgscale->Write();
RSUSsubhKaon2Dpeakavgscale_deta->Write();
RSUSsubhKaon2Dpeakavgscale_dphi->Write();
LSUSsubhKaon2Dpeak->Write();
LSUSsubhKaon2Dpeak_deta->Write();
LSUSsubhKaon2Dpeak_dphi->Write();
LSUSsubhKaon2Dpeakleftscale->Write();
LSUSsubhKaon2Dpeakleftscale_deta->Write();
LSUSsubhKaon2Dpeakleftscale_dphi->Write();
LSUSsubhKaon2Dpeakavgscale->Write();
LSUSsubhKaon2Dpeakavgscale_deta->Write();
LSUSsubhKaon2Dpeakavgscale_dphi->Write();
resUSvsLS->Write();
resUSvsLS_deta->Write();
resUSvsLS_dphi->Write();
}
|
49fcf889b4adc45c1d34d9827f967003ac6504f5 | af66e6182acb7e51a2d2531cf6a0574c717e11f0 | /code/sources/Scene.cpp | 4e2aa05b3eb9bf69905d224898fa47deaf773826 | [] | no_license | Gonigox/ModelLoader | 6a3d1c9c453702ac4fedfcd65ca442020dcb3ebd | 9a1294a9f4a4e8f7d4ece8589a898eb45d62ec09 | refs/heads/master | 2023-06-18T06:48:12.511205 | 2021-05-11T11:07:16 | 2021-05-11T11:07:16 | 386,234,452 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,844 | cpp | Scene.cpp | #include <Scene.hpp>
namespace model_view
{
Scene::Scene (unsigned width, unsigned height, std::string name, Vector3f ligth)
:
render_task (width, height, name, this),
window (sf::VideoMode(width, height), name, sf::Style::Titlebar | sf::Style::Close),
camera ()
{
Ligth = ligth;
}
void Scene::update_game()
{
static float angle_mesh = 0.f;
static float angle_model = 0.f;
angle_mesh += 0.05f;
angle_model += 0.01f;
model_list[0]->mesh_list[0]->transform_component.rotation = Vector3f{0.f,0.f, angle_mesh};
model_list[0]->transform_component.rotation = Vector3f{0.f, angle_model, 0.f};
for(size_t i = 0; i < model_list.size(); ++i)
{
model_list[i]->update();
}
}
void Scene::start_game()
{
bool exit = false;
/*static float angle_camera = 0.f;
Vector3f distance = camera.transform_component.position - model_list[0]->transform_component.position;
float radius = std::sqrtf(distance.x * distance.x + distance.y + distance.y + distance.z * distance.z);*/
do
{
sf::Event event;
while (window.pollEvent (event))
{
switch (event.type)
{
// window closed
case sf::Event::Closed:
window.close();
exit = true;
break;
// key pressed
case sf::Event::KeyPressed:
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
camera.move_camera(Vector3f {-1.f, 0.f, 0.f} );
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
camera.move_camera(Vector3f {1.f, 0.f, 0.f} );
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
camera.move_camera(Vector3f {0.f, -1.f, 0.f} );
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
camera.move_camera(Vector3f {0.f, 1.f, 0.f} );
}
break;
// we don't process other types of events
default:
//camera.calculate_mtransformation();
break;
}
}
update_game();
render_task.Render_game();
window.display ();
}
while (not exit);
}
} |
2e6bc436434a90d126b1b2ed80b067f62812ebea | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5744014401732608_0/C++/kphmd/B-CodeFile.cpp | 1af34ff6121230134e2600b95ef37bded4455bb5 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,271 | cpp | B-CodeFile.cpp | #include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <list>
#include <map>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <set>
#include <utility>
#include <stack>
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
using namespace std;
void solve();
void runCase();
void runCase()
{
long long B,M;
cin >> B >> M;
long long MM = 1;
MM <<= (B-2);
if(M>MM) {
cout << "IMPOSSIBLE" << endl;
} else {
cout << "POSSIBLE" << endl;
MM = 1;
int n = 0;
for(;;) {
// if(0==(M&(~(MM-1)))) break;
if(MM >= M) break;
MM <<= 1;
n++;
}
vector<string> res(B,string(B,'0'));
res[0][B-1] = '1';
if(MM == M) {
for(int i = 0; i < n; i++) {
res[0][i+1] = '1';
res[i+1][B-1] = '1';
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j < i; j++) {
res[i][j] = '1';
}
}
} else {
n --;
for(int i = 0; i < n; i++) {
res[0][i+1] = '1';
res[i+1][B-1] = '1';
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j < i; j++) {
res[i][j] = '1';
}
}
MM >>= 1;
M -= MM;
n++;
res[0][n] = '1';
// cout << M << endl;
for(int i = 1; i < n; i++) {
if((1&(M>>(i-1)))==1) {
res[n][i] = '1';
}
}
}
rep(i,res.size()) {
cout << res[i] << endl;
}
}
}
void solve()
{
int n;
cin >> n;
// scanf("%d",&n);
// getchar();
for(int i = 0; i < n; i++) {
cout << "Case #" << i+1 << ": ";
// printf("Case #%d: ",i+1);
runCase();
//runSample();
}
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
solve();
return 0;
}
|
8adf1d0bfd586a0979462210b61fcec4eaeff362 | 79ae5b24a2663056157b746e7d13b72657eaad07 | /polyscan.h | 2e38b7ca6b6e432a20dd3842da500c777f641a2e | [
"MIT"
] | permissive | Beifang/msisensor | 3b52496dfb8e8acbc07fa4d2971d373fded2b4fe | 749c46a4a1a9a15a907bbd28e675a19b5459bfd6 | refs/heads/master | 2020-03-22T04:48:11.981009 | 2018-07-02T07:50:50 | 2018-07-02T07:50:50 | 139,522,196 | 1 | 0 | MIT | 2018-07-03T03:11:05 | 2018-07-03T03:11:05 | null | UTF-8 | C++ | false | false | 3,180 | h | polyscan.h |
/*
* polyscan.h for MSIsensor
* Copyright (c) 2013 Beifang Niu && Kai Ye WUGSC All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _POLYSCAN_H_
#define _POLYSCAN_H_
#include <map>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include "param.h"
#include "structs.h"
#include "homo.h"
#include "window.h"
#include "sample.h"
class PolyScan
{
public:
PolyScan();
~PolyScan();
// user defined region
UserDefinedRegion region_one;
bool ifUserDefinedRegion;
void eliminate(const char ch, std::string & str);
bool ParseOneRegion(const std::string ®ion);
// read bed regions
bool ifUserDefinedBed;
std::map<std::string, bit16_t> chrMaptoIndex;
std::vector< BedChr > beds;
void LoadBeds(std::ifstream &fin);
void BedFilterorNot();
// load bam list file
std::vector< BamPairs > totalBamPairs;
std::vector< BamTumors > totalBamTumors;
//void LoadBams(std::ifstream &fin);
void LoadBams(const std::string &nBam, const std::string &tBam);
void LoadBam(const std::string &tBam);
unsigned int totalBamPairsNum;
unsigned int totalBamTumorsNum;
// load homos and microsatellites
unsigned long totalHomosites;
//std::vector< HomoSite * > totalSites;
std::vector< HomoSite > totalSites;
bool LoadHomosAndMicrosates(std::ifstream &fin);
void TestHomos();
std::vector< HomoSite > homosBuffer;
// windows
std::vector< Window > totalWindows;
void SplitWindows();
void TestWindows();
unsigned long totalWindowsNum;
// distribution
void InithializeDistributions();
void outputDistributions();
void releaseDistributions();
void GetHomoDistribution( Sample &oneSample, const std::string &prefix );
void GetHomoTumorDistribution( Sample &oneSample, const std::string &prefix );
protected:
// xxxxxx
// xxxx
};
#endif //_POLYSCAN_H_
|
d5aec6325c8b7bda7304ed6d27992ee4333f7650 | b119c47632e56d5bce498a7bc094f1ae39444521 | /include/retro/Core.h | 748a01cf1685be09006566f351bbc4c0ff098f85 | [
"MIT"
] | permissive | mickiboy/retroportal | 20cd12de443482f311c345147fc236a1a9ede640 | 91bbd94da4750b1485f9d8f96f6575e008d9f46c | refs/heads/master | 2021-03-30T17:58:15.776949 | 2017-10-31T14:41:49 | 2017-10-31T14:41:49 | 107,414,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,808 | h | Core.h | #pragma once
#include <string>
#include <libretro.h>
#include <dynamic/dylib.h>
#include "Drawable.h"
#include "Mesh.h"
#include "ShaderProgram.h"
#include "Texture.h"
namespace retro
{
class Core : public Drawable
{
public:
Core(const std::string& path);
virtual ~Core();
Mesh& getMesh() override;
ShaderProgram& getShaderProgram() override;
Texture& getTexture() override;
void loadGame(const std::string& path);
void unloadCurrentGame();
void run();
private:
static Core* instance;
static bool onRetroEnvironment(unsigned cmd, void* data);
static void onRetroVideoRefresh(const void* data, unsigned width, unsigned height, size_t pitch);
static void onRetroAudioSample(int16_t left, int16_t right);
static size_t onRetroAudioSampleBatch(const int16_t* data, size_t frames);
static void onRetroInputPoll();
static int16_t onRetroInputState(unsigned port, unsigned device, unsigned index, unsigned id);
Mesh mesh;
ShaderProgram shaderProgram;
Texture texture;
dylib_t handle = nullptr;
typedef void(*retroSetEnvironmentFn)(retro_environment_t);
retroSetEnvironmentFn retroSetEnvironment;
typedef void(*retroSetVideoRefreshFn)(retro_video_refresh_t);
retroSetVideoRefreshFn retroSetVideoRefresh;
typedef void(*retroSetAudioSampleFn)(retro_audio_sample_t);
retroSetAudioSampleFn retroSetAudioSample;
typedef void(*retroSetAudioSampleBatchFn)(retro_audio_sample_batch_t);
retroSetAudioSampleBatchFn retroSetAudioSampleBatch;
typedef void(*retroSetInputPollFn)(retro_input_poll_t);
retroSetInputPollFn retroSetInputPoll;
typedef void(*retroSetInputStateFn)(retro_input_state_t);
retroSetInputStateFn retroSetInputState;
typedef void(*retroInitFn)();
retroInitFn retroInit;
typedef void(*retroDeinitFn)();
retroDeinitFn retroDeinit;
typedef unsigned(*retroApiVersionFn)();
retroApiVersionFn retroApiVersion;
typedef void(*retroGetSystemInfoFn)(retro_system_info*);
retroGetSystemInfoFn retroGetSystemInfo;
typedef void(*retroGetSystemAvInfoFn)(retro_system_av_info*);
retroGetSystemAvInfoFn retroGetSystemAvInfo;
typedef void(*retroSetControllerPortDeviceFn)(unsigned, unsigned);
retroSetControllerPortDeviceFn retroSetControllerPortDevice;
typedef void(*retroResetFn)();
retroResetFn retroReset;
typedef void(*retroRunFn)();
retroRunFn retroRun;
typedef size_t(*retroSerializeSizeFn)();
retroSerializeSizeFn retroSerializeSize;
typedef bool(*retroSerializeFn)(void*, size_t);
retroSerializeFn retroSerialize;
typedef bool(*retroUnserializeFn)(const void*, size_t);
retroUnserializeFn retroUnserialize;
typedef void(*retroCheatResetFn)();
retroCheatResetFn retroCheatReset;
typedef void(*retroCheatSetFn)(unsigned, bool, const char*);
retroCheatSetFn retroCheatSet;
typedef bool(*retroLoadGameFn)(const retro_game_info*);
retroLoadGameFn retroLoadGame;
typedef bool(*retroLoadGameSpecialFn)(unsigned, const retro_game_info*, size_t);
retroLoadGameSpecialFn retroLoadGameSpecial;
typedef void(*retroUnloadGameFn)();
retroUnloadGameFn retroUnloadGame;
typedef unsigned(*retroGetRegionFn)();
retroGetRegionFn retroGetRegion;
typedef void*(*retroGetMemoryDataFn)(unsigned);
retroGetMemoryDataFn retroGetMemoryData;
typedef size_t(*retroGetMemorySizeFn)(unsigned);
retroGetMemorySizeFn retroGetMemorySize;
};
}
|
16f1cd5ed40ba717304a0b4478321d2d6f03e639 | 4ef0917e45437473aca4d5537ad9f9746e5e2ce5 | /kehnetwork/inputcache.h | 613414e15e5cd3d58863b614a7d978b64dee4558 | [
"MIT"
] | permissive | baiduwen3/GodotModulePack | bef396fa8c31bb57f20662d1162295afb2aea451 | 9f2bbcdeb00bc577598680a22601be79220c5352 | refs/heads/target-gd3.2 | 2023-03-18T12:14:24.630420 | 2021-03-11T21:19:33 | 2021-03-11T21:19:33 | 467,752,651 | 1 | 0 | MIT | 2022-03-09T02:42:07 | 2022-03-09T02:42:06 | null | UTF-8 | C++ | false | false | 5,688 | h | inputcache.h | /**
* Copyright (c) 2021 Yuri Sarudiansky
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _KEHNETWORK_INPUTCACHE_H
#define _KEHNETWORK_INPUTCACHE_H 1
#include "core/reference.h"
class kehInputData;
// The input cache is used in two different ways, depending on which machine it's
// running and which player the node owning the cache belongs to.
// Running on server:
// - If the node corresponds to the local player (the server), then the cache does
// nothing because there is no need to validate its data.
// - If this node corresponds to a client then the cache will hold the received input
// data, which will be retrieved from it when iterating the game state. At that
// moment the input is removed from the buffer and a secondary container holds
// information that maps form the snapshot signature to the used input signature.
// With this information when encoding snapshot data it's possible to attach to it
// the signature of the input data used to simulate the game. Another thing to keep
// in mind is that incoming input data may be out of order or duplicated. To that
// end it's a lot simpler to deal with a map to hold the objects.
// Running on client:
// - If the owning node corresponds to a remote player, then the cache does nothing
// because client know nothing about other clients nor the server in regards to
// input data.
// - If the owning node corresponds to the local player, then the cache must hold
// a sequential (ascending) set of input objects that are mostly meant for
// validation when snapshot data arrives. When validating, any input older than the
// one just checked must be removed from the container, thus keeping this data in
// ascending order makes things a lot easier. In this case it's better to have an
// array rather than map to hold this data.
// With all this information in mind, this class is meant to make things a bit easier
// to deal with those differences.
class kehInputCache
{
private:
// Meant for the server, map from input signature to instance of kehInputData
Map<uint32_t, Ref<kehInputData>> m_sbuffer;
// Meant for the (local) client, holds non acknowledged input data
PoolVector<Ref<kehInputData>> m_cbuffer;
// Keep track of the last input signature used by this machine
uint32_t m_last_sig;
// Used only on server, this creates association of snapshot (key) and input (value)
Map<uint32_t, uint32_t> m_snapinpu;
// Count number of 0-input snapshots that weren't acknowledged by the client. If
// this value is bigger than 0 then the server will send the newest full snapshot
// within its history rather than calculating delta snapshot.
uint32_t m_no_input_count;
// Holds the signature of the last acknowledged snapshot signature. This will be used
// as reference to cleanup older data.
uint32_t m_last_ack_snap;
public:
uint32_t get_last_sig() const { return m_last_sig; }
uint32_t get_used_input_in_snap(uint32_t snap_sig) const;
uint32_t get_last_ack_snap() const { return m_last_ack_snap; }
uint32_t get_non_acked_scount() const { return m_snapinpu.size(); }
bool has_no_input() const { return m_no_input_count > 0; }
// Creates the association of snapshot signature with input for the corresponding player.
// This will automatically take care of the "no input count"
void associate(uint32_t snapsig, uint32_t isig);
// Acknowledges the specified snapshot signature by removing it from the snapinpu container.
// It automatically updates the "no input count" property by subtracting from it if the
// given snapshot didn't use any input.
void acknowledge(uint32_t snapsig);
// Increments the internal "last signature", which will be used to build new input data
// objects for the local player
uint32_t increment_input() { return ++m_last_sig; }
// Adds local input object into the internal buffer
void cache_local_input(const Ref<kehInputData>& input);
// Adds a client input data into the relevenat container
void cache_remote_input(const Ref<kehInputData>& input);
uint32_t get_cache_size() const { return m_cbuffer.size(); }
Ref<kehInputData> get_input_data(uint32_t index) const;
// Removes all input objects that are older and equal to the specified input signature
void clear_older(uint32_t isig);
// When server requires client input data, use this. This will automatically remove the returned
// object from the internal container as it will not be needed anymore.
Ref<kehInputData> get_client_input();
// Reset the internal state.
void reset();
kehInputCache();
};
#endif
|
865251d811e43bbce642dacec0630854bca8e0ef | 761c4e71dcd882fbc815766bfe2dffa6a04f2ef4 | /Edu 86 div2/C2.cpp | 652d024784ffa335aa360586845975255db94177 | [] | no_license | Adityasharma15/Codeforces | 419838d8672c2106a8135b5bd495f2c3da259d7d | 31e61d11db0e9ab749c5d97fbb14ae482655615d | refs/heads/master | 2021-04-05T15:08:01.415459 | 2020-11-20T12:13:25 | 2020-11-20T12:13:25 | 248,570,193 | 3 | 3 | null | 2020-10-23T05:59:42 | 2020-03-19T17:56:09 | C++ | UTF-8 | C++ | false | false | 700 | cpp | C2.cpp | #include<bits/stdc++.h>
#define ll long long
using namespace std;
ll a, b, q;
ll x, y;
ll find(ll x, ll hcf)
{
ll div = (x/hcf)*(hcf-x);
x%=hcf;
if(x>=a)
{
div+=(x-a+1);
}
return div;
}
ll gcd(ll a, ll b)
{
if(a == 0)
return b;
return gcd(b%a, a);
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll t;
cin >> t;
while(t--)
{
cin >> a >> b >> q;
ll temp, temp1, temp2, hcf;
if(b>a)
swap(a,b);
ll lcm = (a*b)/gcd(a,b);
ll ans = 0;
while(q--)
{
cin >> x >> y;
ans = 0;
ans = find(y, lcm) - find(x-1, lcm) ;
cout << ans << " ";
}
cout << "\n";
}
return 0;
}
|
0f5ea96219c3370a23a5eb267df0fc8ccb86e8ff | c8bbec8d873b6622fa876afe1b2a1fa880c143b8 | /Assignment2/Source/assignment2/AnimInst_Character.cpp | 3179b7c18454b54a2f66a2cd4b6101051fadd0c1 | [] | no_license | maksimTMZ/IK_foot_constraints | 0bbad8bdea82d22dff791ffb36ef3004750ad56c | 750a286a7ececa542378ab607c1287bec3f328ea | refs/heads/main | 2023-03-19T07:53:23.042478 | 2021-02-17T18:48:47 | 2021-02-17T18:48:47 | 339,819,650 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | cpp | AnimInst_Character.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "AnimInst_Character.h"
UAnimInst_Character::UAnimInst_Character()
{
}
void UAnimInst_Character::NativeInitializeAnimation()
{
Super::NativeInitializeAnimation();
Init_IKFootRef();
}
void UAnimInst_Character::NativeUpdateAnimation(float DeltaSeconds)
{
Super::NativeUpdateAnimation(DeltaSeconds);
Tick_IKFoot();
}
void UAnimInst_Character::Init_IKFootRef()
{
//! Get IKFoot Component from owner
APawn* pOwner = TryGetPawnOwner();
if (pOwner != nullptr)
{
UActorComponent* pActorComp = pOwner->GetComponentByClass(UIK_Foot_Component::StaticClass());
if (pActorComp != nullptr)
{
m_pIK_Foot_Ref = Cast<UIK_Foot_Component>(pActorComp);
if (m_pIK_Foot_Ref == nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("IKFootRef is nullptr"));
}
}
}
}
void UAnimInst_Character::Tick_IKFoot()
{
if (m_pIK_Foot_Ref == nullptr) return;
m_stIKAnimValue = m_pIK_Foot_Ref->GetIKAnimValue();
}
|
9ac126cfaba4e3f2b8c5389ae872ec0d15047623 | eaf5c173ec669b26c95f7babad40306f2c7ea459 | /abc125/abc125_b.cpp | 468065e9137b6aeba3fe2170ce2d1cba265bcb52 | [] | no_license | rikuTanide/atcoder_endeavor | 657cc3ba7fbf361355376a014e3e49317fe96def | 6b5dc43474d5183d8eecb8cb13bf45087c7ed195 | refs/heads/master | 2023-02-02T11:49:06.679743 | 2020-12-21T04:51:10 | 2020-12-21T04:51:10 | 318,676,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | cpp | abc125_b.cpp | #include <bits/stdc++.h>
#include <cmath>
using namespace std;
#define rep(i, n) for (ll i = 0; i < (n); ++i)
#define sz(x) ll(x.size())
typedef long long ll;
typedef pair<int, int> P;
//typedef pair<ll, ll> P;
//const double INF = 1e10;
const ll INF = 1001001001;
#define mins(x, y) x = min(x, y)
#define maxs(x, y) x = max(x, y)
const int mod = 1000000007;
//< ave , a(time), b(manzoku) >
typedef tuple<double, int, int> A;
int main() {
int n;
cin >> n;
vector<int> vs(n);
rep(i, n) {
int v;
cin >> v;
vs[i] = v;
}
rep(i, n) {
int c;
cin >> c;
vs[i] -= c;
}
sort(vs.rbegin(), vs.rend());
int ans = 0;
for (int i = 0; i < n; i++) {
if (vs[i] < 0) {
break;
} else {
ans += vs[i];
}
}
cout << ans << endl;
}
|
3e635d9c5f33392b32884138c45ef62149b09ef7 | 30e7c3853c7a7c08355d25c98bdabc9039b08d6d | /GPTP/hooks/load_unload_proc.cpp | b1853b28bcb7bcae45397037d478ab15c9379170 | [] | no_license | KYSXD/GPTP-For-VS2008 | 85712bc27680a0bc1850c9bed208217f73bb2ab9 | e9c283d7f89c3f4d269a10d1b162dd0a34f1faa4 | refs/heads/master | 2020-04-05T23:01:28.513167 | 2018-11-20T18:20:27 | 2018-11-20T18:20:27 | 41,927,927 | 5 | 0 | null | 2015-09-04T17:08:10 | 2015-09-04T17:08:09 | C++ | UTF-8 | C++ | false | false | 9,782 | cpp | load_unload_proc.cpp | #include "load_unload_proc.h"
#include <SCBW/api.h>
// helper functions def
namespace {
u32 getUpgradedWpnCooldown(CUnit* unit, u8 weaponId); // 75DC0
void IgnoreAllScriptAndGotoIdle(CUnit* unit); // 76550
void hideAndDisableUnit(CUnit* unit); // E6340
u32 function_004E76C0(CUnit* transport,
CUnit* loaded_unit,
Point16* pos); // E76C0
void function_004E7E10(CUnit* unit, u32 unk); // E7E10
} // unnamed namespace
namespace hooks {
// initial name was sub_4E78E0
// the transport is "unit", the target is "unitToLoad"
void loadUnitProc(CUnit* unit, CUnit* unitToLoad) {
u8 unitRaceId;
u32 loaded_index;
int counter = 0;
static const CUnit* unitTable_0059CB58 = (CUnit*)0x0059CB58;
static const CUnit* unitTable_0059CB64 = (CUnit*)0x0059CB64;
static u32* u32_0x006BEE84 = (u32*)(0x006BEE84);
static u32* u32_0x006BEE8C = (u32*)(0x006BEE8C);
if (units_dat::SpaceProvided[unit->id] != 0) {
bool bEndLoop = false;
u32* loadedUnitOffset;
while (!bEndLoop) {
loadedUnitOffset = (u32*)&unit->loadedUnit[counter];
if (*loadedUnitOffset == 0)
bEndLoop = true;
else {
if (unitTable_0059CB64[unit->loadedUnit[counter].index]
.link.prev == NULL)
bEndLoop = true;
else {
CUnit* current_loaded_unit = (CUnit*)&(
unitTable_0059CB58[unit->loadedUnit[counter].index]);
if (current_loaded_unit->mainOrderId == OrderId::Die &&
current_loaded_unit->mainOrderState == 1)
bEndLoop = true;
else {
if (current_loaded_unit->targetOrderSpecial !=
unit->loadedUnit[counter].unitId)
bEndLoop = true;
else {
counter++;
if (counter >= units_dat::SpaceProvided[unit->id])
bEndLoop = true;
}
}
}
}
}
}
// E7952
if (units_dat::GroupFlags[unit->id].isZerg)
unitRaceId = RaceId::Zerg;
else if (units_dat::GroupFlags[unit->id].isProtoss)
unitRaceId = RaceId::Protoss;
else if (units_dat::GroupFlags[unit->id].isTerran)
unitRaceId = RaceId::Terran;
else
unitRaceId = RaceId::Neutral;
scbw::playSound(SoundId::Misc_ZOvTra00_wav + unitRaceId, unit);
if (unitToLoad->id == UnitId::TerranSCV) {
if (unitToLoad->pAI != NULL) {
u32* pAI_0x14 = (u32*)((u32)unitToLoad->pAI + 0x14);
if (*pAI_0x14 == (u32)unitToLoad) *pAI_0x14 = NULL;
}
}
// e79a3
__asm {
PUSHAD
MOV ECX, unitToLoad
SUB ECX, unitTable
MOV EAX, 0x86186187
MUL ECX
SUB ECX, EDX
SHR ECX, 1
ADD ECX, EDX
SHR ECX, 0x08
INC ECX
MOV loaded_index, ECX
POPAD
}
unitToLoad->connectedUnit = unit;
if (loaded_index < UNIT_ARRAY_LENGTH) {
unit->loadedUnit[counter].index = loaded_index;
unit->loadedUnit[counter].unitId = unitToLoad->targetOrderSpecial;
} else {
unit->loadedUnit[counter].index = 0;
unit->loadedUnit[counter].unitId = 0;
}
unitToLoad->status |= UnitStatus::InTransport;
hideAndDisableUnit(unitToLoad);
unitToLoad->sprite->playIscriptAnim(IscriptAnimation::WalkingToIdle, true);
scbw::refreshConsole();
if (unit->status & UnitStatus::GroundedBuilding) {
unitToLoad->status = (unitToLoad->status & ~UnitStatus::IsBuilding) |
UnitStatus::InBuilding;
if (unitToLoad->path != NULL) {
u32* path_0x4 = (u32*)((u32)unitToLoad->path + 4);
*path_0x4 = ((u32)unitToLoad->path - *u32_0x006BEE8C) / 128 + 1;
if (*u32_0x006BEE84 == 0)
unitToLoad->path = NULL;
else
unitToLoad->path =
(void*)((*u32_0x006BEE84 - *u32_0x006BEE8C) / 128 + 1);
*u32_0x006BEE84 = (u32)unitToLoad->path;
unitToLoad->path = NULL;
}
// E7A81
unitToLoad->movementState = 0;
if (unitToLoad->sprite->elevationLevel < 12)
unitToLoad->pathingFlags |= 1;
else
unitToLoad->pathingFlags &= ~1;
if (unitToLoad->subunit != NULL &&
units_dat::BaseProperty[unitToLoad->subunit->id] &
UnitProperty::Subunit) {
CUnit* subUnit = unitToLoad->subunit;
scbw::setUnitPosition(
subUnit, unit->sprite->position.x, unit->sprite->position.y);
subUnit->status = (subUnit->status & ~UnitStatus::IsBuilding) |
UnitStatus::InBuilding;
if (subUnit->path != NULL) {
u32* path_0x4 = (u32*)((u32)subUnit->path + 4);
*path_0x4 = ((u32)subUnit->path - *u32_0x006BEE8C) / 128 + 1;
if (*u32_0x006BEE84 == 0)
subUnit->path = NULL;
else
subUnit->path =
(void*)((*u32_0x006BEE84 - *u32_0x006BEE8C) / 128 + 1);
*u32_0x006BEE84 = (u32)subUnit->path;
subUnit->path = NULL;
}
// E7B25
subUnit->movementState = 0;
if (subUnit->sprite->elevationLevel < 12)
subUnit->pathingFlags |= 1;
else
subUnit->pathingFlags &= ~1;
} else // E7B51
scbw::setUnitPosition(
unitToLoad, unit->sprite->position.x, unit->sprite->position.y);
}
}
;
// initial name was sub_4E7F70
// the transported unit is "unit", the transport is
// accessed through unit->connectedUnit
// Has a boolean return value
Bool32 unloadUnitProc(CUnit* unit) {
Bool32 return_value = 0;
if (unit->connectedUnit != NULL) {
CUnit* transport = unit->connectedUnit;
if ((transport->mainOrderTimer == 0 ||
transport->status & UnitStatus::GroundedBuilding) &&
!(transport->status & UnitStatus::DoodadStatesThing) &&
transport->lockdownTimer == 0 && transport->stasisTimer == 0 &&
transport->maelstromTimer == 0) { // E7FDC
Point16 pos = {0, 0};
// probably check where unit can be spawned
if (function_004E76C0(transport, unit, &pos) != 0) {
transport->mainOrderTimer = 15;
scbw::setUnitPosition(unit, pos.x, pos.y);
if (unit->subunit != NULL)
scbw::setUnitPosition(unit->subunit, pos.x, pos.y);
IgnoreAllScriptAndGotoIdle(unit);
function_004E7E10(unit, 0);
if (unit->pAI == NULL)
unit->orderComputerCL(
units_dat::ReturnToIdleOrder[unit->id]);
else
unit->orderComputerCL(OrderId::ComputerAI);
scbw::refreshConsole();
return_value = 1;
if (transport->status &
UnitStatus::GroundedBuilding) { // E806B
if (unit->id != UnitId::ProtossReaver) {
u8 weaponId = unit->getGroundWeapon();
if (weaponId != WeaponId::None)
unit->groundWeaponCooldown =
getUpgradedWpnCooldown(unit, weaponId);
weaponId = unit->getAirWeapon();
if (weaponId != WeaponId::None)
unit->airWeaponCooldown =
getUpgradedWpnCooldown(unit, weaponId);
unit->spellCooldown = 30;
} else
unit->mainOrderTimer = 30;
}
}
}
}
return return_value;
}
;
} // namespace hooks
;
//-------- Helper function definitions. Do NOT modify! --------//
namespace {
const u32 Func_getUpgradedWpnCooldown = 0x00475DC0;
u32 getUpgradedWpnCooldown(CUnit* unit, u8 weaponId) {
static u32 return_value;
__asm {
PUSHAD
MOV AL, weaponId
MOV ESI, unit
CALL Func_getUpgradedWpnCooldown
MOV return_value, EAX
POPAD
}
return return_value;
}
;
const u32 Func_IgnoreAllScriptAndGotoIdle = 0x00476550;
void IgnoreAllScriptAndGotoIdle(CUnit* unit){
__asm {PUSHAD MOV ESI, unit CALL Func_IgnoreAllScriptAndGotoIdle POPAD}
}
;
const u32 Func_unitDeathSomething_0 = 0x004E6340;
void hideAndDisableUnit(CUnit* unit){
__asm {PUSHAD MOV EAX, unit CALL Func_unitDeathSomething_0 POPAD}
}
;
const u32 Func_Sub4E76C0 = 0x004E76C0;
u32 function_004E76C0(CUnit* transport, CUnit* loaded_unit, Point16* pos) {
static u32 result;
__asm {
PUSHAD
MOV EAX, transport
MOV ESI, loaded_unit
PUSH pos
CALL Func_Sub4E76C0
MOV result, EAX
POPAD
}
return result;
}
;
const u32 Func_Sub4E7E10 = 0x004E7E10;
void function_004E7E10(CUnit* unit, u32 unk){
__asm {PUSHAD MOV EAX, unit PUSH unk CALL Func_Sub4E7E10 POPAD}
}
;
} // Unnamed namespace
// End of helper functions
|
6228169558e90a545c8dc8fdad45961e604390a2 | e7b2e37d0cf91d29c5848c8e76bf10154bbd53e9 | /algselecaoInterno.cpp | 42e806cfba0d992de230d25d2f779329f588c74b | [] | no_license | PatriciaDuarte/APC | ca42f24bc874b96370f8af15605f1f60b1eeedc4 | 9ebb9bd6e79bc4a328d8ce6ac04dcafd7f7d7db5 | refs/heads/master | 2020-06-03T05:24:50.935675 | 2019-06-12T00:12:57 | 2019-06-12T00:12:57 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 792 | cpp | algselecaoInterno.cpp | //Autora:Patrícia Duarte da Silva -201514322
#include<stdio.h>
#include<stdlib.h>
#define TAMANHO 10
void selecao(int vetor[], int tamanho); //Declaração da função
void selecao(int vetor[], int tamanho)
{
int posMinimo;
for (int i = 0; i<(TAMANHO-1); i++)
{
int minimo = vetor[i];
for (int j = (i + 1); j < TAMANHO; j++)
{
if (vetor[j]< minimo)
{
minimo = vetor[j];
posMinimo = j;
}
}
vetor[posMinimo] = vetor[i];
vetor[i] = minimo;
}
}
int main()
{
int vetor[TAMANHO];
for(int i= 0; i<TAMANHO; i++)
{
vetor[i] =(rand()%TAMANHO);
printf("Vetor[%d]: %d\n", (i + 1), vetor[i]);
}
selecao(vetor, TAMANHO);
for (int i=0; i < TAMANHO; i++)
printf("\nVetor[%d]: %d", (i + 1),vetor[i]);
return 0;
}
|
5b2493630081af6f3af2ca5416e8f63973407558 | c6fa53212eb03017f9e72fad36dbf705b27cc797 | /SLHCUpgradeSimulations/L1CaloTrigger/plugins/L1CaloProtoClusterSharing.cc | 55d44c203b0e9e84f2a16b4ae350ab7b0b53f893 | [] | no_license | gem-sw/cmssw | a31fc4ef2233b2157e1e7cbe9a0d9e6c2795b608 | 5893ef29c12b2718b3c1385e821170f91afb5446 | refs/heads/CMSSW_6_2_X_SLHC | 2022-04-29T04:43:51.786496 | 2015-12-16T16:09:31 | 2015-12-16T16:09:31 | 12,892,177 | 2 | 4 | null | 2018-11-22T13:40:31 | 2013-09-17T10:10:26 | C++ | UTF-8 | C++ | false | false | 9,220 | cc | L1CaloProtoClusterSharing.cc |
#include "SLHCUpgradeSimulations/L1CaloTrigger/interface/L1CaloAlgoBase.h"
#include "SimDataFormats/SLHC/interface/L1CaloClusterWithSeed.h"
#include "SimDataFormats/SLHC/interface/L1CaloClusterWithSeedFwd.h"
#include "SLHCUpgradeSimulations/L1CaloTrigger/interface/TriggerTowerGeometry.h"
#include "SimDataFormats/SLHC/interface/L1TowerNav.h"
class L1CaloProtoClusterSharing:public L1CaloAlgoBase < l1slhc::L1CaloClusterWithSeedCollection , l1slhc::L1CaloClusterWithSeedCollection >
{
public:
L1CaloProtoClusterSharing( const edm::ParameterSet & );
~L1CaloProtoClusterSharing( );
void initialize( );
void algorithm( const int &, const int & );
private:
int mHoECutMode;
int mHoECutEB, mHoECutEE;
};
L1CaloProtoClusterSharing::L1CaloProtoClusterSharing( const edm::ParameterSet & aConfig ):
L1CaloAlgoBase < l1slhc::L1CaloClusterWithSeedCollection , l1slhc::L1CaloClusterWithSeedCollection > ( aConfig )
{
mHoECutMode = aConfig.getParameter<int>("hoeCutMode");
}
L1CaloProtoClusterSharing::~L1CaloProtoClusterSharing( )
{
}
/*
void L1CaloProtoClusterSharing::initialize( )
{
}
*/
void L1CaloProtoClusterSharing::initialize( )
{
mHoECutEB = 40; // 0-1000 -> 0-1 : 40 := 0.04
mHoECutEE = 15; // := 0.015
}
void L1CaloProtoClusterSharing::algorithm( const int &aEta, const int &aPhi )
{
// Look if there is a cluster here
l1slhc::L1CaloClusterWithSeedCollection::const_iterator lClusterItr = fetch( aEta, aPhi );
if ( lClusterItr != mInputCollection->end( ) )
{
l1slhc::L1CaloClusterWithSeed lSharedCluster( *lClusterItr );
// loop over cluster constituents
for ( int lTowerEta = aEta-1; lTowerEta <= aEta + 1; ++lTowerEta )
{
for ( int lTowerPhi = aPhi-1; lTowerPhi <= aPhi + 1; ++lTowerPhi )
{
if(lTowerEta==aEta && lTowerPhi==aPhi)
{
continue;
}
// look at clusters around constituents, skipping the one at (aEta,aPhi)
// And find max and 2nd max neighbor cluster
int maxE = 0;
int secondMaxE = 0;
int maxEta = 999;
int secondMaxEta = 999;
int maxPhi = 999;
int secondMaxPhi = 999;
l1slhc::L1CaloClusterWithSeedCollection::const_iterator maxCluster = mInputCollection->end( );
l1slhc::L1CaloClusterWithSeedCollection::const_iterator secondMaxCluster = mInputCollection->end( );
for(int lClusterEta = lTowerEta-1; lClusterEta <= lTowerEta+1; ++lClusterEta)
{
for(int lClusterPhi = lTowerPhi-1; lClusterPhi <= lTowerPhi+1; ++lClusterPhi)
{
if((lClusterEta==aEta && lClusterPhi==aPhi) || (lClusterEta==lTowerEta && lClusterPhi==lTowerPhi) )
{
continue;
}
l1slhc::L1CaloClusterWithSeedCollection::const_iterator lNeighborItr = fetch( lClusterEta, lClusterPhi );
if ( lNeighborItr != mInputCollection->end( ) )
{
if(lNeighborItr->EmEt()>secondMaxE)
{
if(lNeighborItr->EmEt()>maxE)
{
secondMaxE = maxE;
secondMaxEta = maxEta;
secondMaxPhi = maxPhi;
secondMaxCluster = maxCluster;
maxE = lNeighborItr->EmEt();
maxEta = lClusterEta;
maxPhi = lClusterPhi;
maxCluster = lNeighborItr;
}
else
{
secondMaxE = lNeighborItr->EmEt();
secondMaxCluster = lNeighborItr;
secondMaxEta = lClusterEta;
secondMaxPhi = lClusterPhi;
}
}
}
}
}
// In case of equal energies look at the position
int dphi = abs(lTowerPhi-aPhi);
int deta = abs(lTowerEta-aEta);
int maxdphi = abs(lTowerPhi-maxPhi);
int maxdeta = abs(lTowerEta-maxEta);
int secondMaxdphi = abs(lTowerPhi-secondMaxPhi);
int secondMaxdeta = abs(lTowerEta-secondMaxEta);
bool bad = false;
bool badSecond = false;
if(dphi>maxdphi) bad = true;
else if(dphi==maxdphi && deta>maxdeta) bad = true;
else if(dphi==maxdphi && deta==maxdeta && maxPhi>aPhi) bad = true;
else if(dphi==maxdphi && deta==maxdeta && maxPhi==aPhi && maxEta>aEta) bad = true;
if(dphi>secondMaxdphi) badSecond = true;
else if(dphi==secondMaxdphi && deta>secondMaxdeta) badSecond = true;
else if(dphi==secondMaxdphi && deta==secondMaxdeta && secondMaxPhi>aPhi) badSecond = true;
else if(dphi==secondMaxdphi && deta==secondMaxdeta && secondMaxPhi==aPhi && secondMaxEta>aEta) badSecond = true;
// Share energy depending on the rank of the cluster
if(secondMaxE>lClusterItr->EmEt()) // 3rd or more -> give all the tower energy
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 5);
}
else if(secondMaxE==lClusterItr->EmEt() && badSecond)
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 5);
}
else // 2nd or 1st
{
if(lClusterItr->EmEt() > 4*maxE) // -> keep all the tower energy
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 0);
}
else if(lClusterItr->EmEt() > 2*maxE) // -> keep 3/4 of the tower energy
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 1);
}
else if(lClusterItr->EmEt() > maxE) // -> keep 1/2+ of the tower energy (+1 if tower energy is odd)
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 2);
}
else if(lClusterItr->EmEt() == maxE && !bad)
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 2); // -> keep 1/2+ of the tower energy (+1 if tower energy is odd)
}
else if(2*lClusterItr->EmEt() >= maxE) // -> keep 1/2- of the tower energy (-1 if tower energy is odd)
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 3);
}
else if(4*lClusterItr->EmEt() >= maxE) // -> keep 1/4 of the tower energy
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 4);
}
else // -> give all the tower energy
{
lSharedCluster.shareConstituent(lTowerEta-aEta, lTowerPhi-aPhi, 5);
}
}
}
}
// Calculate Electron Cut and Save it in the Cluster
int lElectronValue = 0;
if(mHoECutMode==0) // default, seed value
{
lElectronValue = ( int )( 1000. * ( ( double )lSharedCluster.seedHadEt() ) / ( ( double )lSharedCluster.seedEmEt() ) );
}
else if(mHoECutMode==1) // 3x3 value
{
lElectronValue = ( int )( 1000. * ( ( double )lSharedCluster.HadEt() ) / ( ( double )lSharedCluster.EmEt() ) );
}
lSharedCluster.setEGammaValue( lElectronValue );
// Electron Bit Decision
bool egammaBitEB = (abs(lSharedCluster.iEta())<=17 && lElectronValue<=mHoECutEB);
bool egammaBitEE = (abs(lSharedCluster.iEta())>17 && lElectronValue<=mHoECutEE);
// FineGrain bit already set in the initialization of the cluster using the FG of the seed tower
lSharedCluster.setEGamma( (egammaBitEB || egammaBitEE) );
int lIndex = mCaloTriggerSetup->getBin( aEta, aPhi );
std::pair < int, int >lEtaPhi = mCaloTriggerSetup->getTowerEtaPhi( lIndex );
mOutputCollection->insert( lEtaPhi.first , lEtaPhi.second , lSharedCluster );
}
}
DEFINE_EDM_PLUGIN (edm::MakerPluginFactory,edm::WorkerMaker<L1CaloProtoClusterSharing>,"L1CaloProtoClusterSharing");
DEFINE_FWK_PSET_DESC_FILLER(L1CaloProtoClusterSharing);
|
c87b33fb5e3be997091adce3c6095507fd7b1ca1 | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/chrome/browser/extensions/api/serial/serial_api.cc | b0e7925c9eb4ce9314507dfefbefa0e3c4363f54 | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 10,986 | cc | serial_api.cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/serial/serial_api.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/api/serial/serial_connection.h"
#include "chrome/browser/extensions/api/serial/serial_port_enumerator.h"
#include "content/public/browser/browser_thread.h"
using content::BrowserThread;
namespace extensions {
const char kConnectionIdKey[] = "connectionId";
const char kDataKey[] = "data";
const char kBytesReadKey[] = "bytesRead";
const char kBytesWrittenKey[] = "bytesWritten";
const char kBitrateKey[] = "bitrate";
const char kSuccessKey[] = "success";
const char kDcdKey[] = "dcd";
const char kCtsKey[] = "cts";
const char kErrorGetControlSignalsFailed[] = "Failed to get control signals.";
const char kErrorSetControlSignalsFailed[] = "Failed to set control signals.";
const char kSerialReadInvalidBytesToRead[] = "Number of bytes to read must "
"be a positive number less than 1,048,576.";
SerialAsyncApiFunction::SerialAsyncApiFunction()
: manager_(NULL) {
}
SerialAsyncApiFunction::~SerialAsyncApiFunction() {
}
bool SerialAsyncApiFunction::PrePrepare() {
manager_ = ApiResourceManager<SerialConnection>::Get(profile());
DCHECK(manager_);
return true;
}
SerialConnection* SerialAsyncApiFunction::GetSerialConnection(
int api_resource_id) {
return manager_->Get(extension_->id(), api_resource_id);
}
void SerialAsyncApiFunction::RemoveSerialConnection(int api_resource_id) {
manager_->Remove(extension_->id(), api_resource_id);
}
SerialGetPortsFunction::SerialGetPortsFunction() {}
bool SerialGetPortsFunction::Prepare() {
set_work_thread_id(BrowserThread::FILE);
return true;
}
void SerialGetPortsFunction::Work() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
base::ListValue* ports = new base::ListValue();
SerialPortEnumerator::StringSet port_names =
SerialPortEnumerator::GenerateValidSerialPortNames();
SerialPortEnumerator::StringSet::const_iterator i = port_names.begin();
while (i != port_names.end()) {
ports->Append(Value::CreateStringValue(*i++));
}
SetResult(ports);
}
bool SerialGetPortsFunction::Respond() {
return true;
}
// It's a fool's errand to come up with a default bitrate, because we don't get
// to control both sides of the communication. Unless the other side has
// implemented auto-bitrate detection (rare), if we pick the wrong rate, then
// you're gonna have a bad time. Close doesn't count.
//
// But we'd like to pick something that has a chance of working, and 9600 is a
// good balance between popularity and speed. So 9600 it is.
SerialOpenFunction::SerialOpenFunction()
: bitrate_(9600) {
}
SerialOpenFunction::~SerialOpenFunction() {
}
bool SerialOpenFunction::Prepare() {
set_work_thread_id(BrowserThread::FILE);
params_ = api::serial::Open::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
if (params_->options.get()) {
scoped_ptr<base::DictionaryValue> options = params_->options->ToValue();
if (options->HasKey(kBitrateKey))
EXTENSION_FUNCTION_VALIDATE(options->GetInteger(kBitrateKey, &bitrate_));
}
return true;
}
void SerialOpenFunction::AsyncWorkStart() {
Work();
}
void SerialOpenFunction::Work() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
const SerialPortEnumerator::StringSet name_set(
SerialPortEnumerator::GenerateValidSerialPortNames());
if (DoesPortExist(params_->port)) {
SerialConnection* serial_connection = CreateSerialConnection(
params_->port,
bitrate_,
extension_->id());
CHECK(serial_connection);
int id = manager_->Add(serial_connection);
CHECK(id);
bool open_result = serial_connection->Open();
if (!open_result) {
serial_connection->Close();
RemoveSerialConnection(id);
id = -1;
}
base::DictionaryValue* result = new base::DictionaryValue();
result->SetInteger(kConnectionIdKey, id);
SetResult(result);
AsyncWorkCompleted();
} else {
base::DictionaryValue* result = new base::DictionaryValue();
result->SetInteger(kConnectionIdKey, -1);
SetResult(result);
AsyncWorkCompleted();
}
}
SerialConnection* SerialOpenFunction::CreateSerialConnection(
const std::string& port,
int bitrate,
const std::string& owner_extension_id) {
return new SerialConnection(port, bitrate, owner_extension_id);
}
bool SerialOpenFunction::DoesPortExist(const std::string& port) {
const SerialPortEnumerator::StringSet name_set(
SerialPortEnumerator::GenerateValidSerialPortNames());
return SerialPortEnumerator::DoesPortExist(name_set, params_->port);
}
bool SerialOpenFunction::Respond() {
return true;
}
SerialCloseFunction::SerialCloseFunction() {
}
SerialCloseFunction::~SerialCloseFunction() {
}
bool SerialCloseFunction::Prepare() {
set_work_thread_id(BrowserThread::FILE);
params_ = api::serial::Close::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
return true;
}
void SerialCloseFunction::Work() {
bool close_result = false;
SerialConnection* serial_connection = GetSerialConnection(
params_->connection_id);
if (serial_connection) {
serial_connection->Close();
RemoveSerialConnection(params_->connection_id);
close_result = true;
}
SetResult(Value::CreateBooleanValue(close_result));
}
bool SerialCloseFunction::Respond() {
return true;
}
SerialReadFunction::SerialReadFunction() {
}
SerialReadFunction::~SerialReadFunction() {
}
bool SerialReadFunction::Prepare() {
set_work_thread_id(BrowserThread::FILE);
params_ = api::serial::Read::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
if (params_->bytes_to_read <= 0 || params_->bytes_to_read >= 1024 * 1024) {
error_ = kSerialReadInvalidBytesToRead;
return false;
}
return true;
}
void SerialReadFunction::Work() {
int bytes_read = -1;
scoped_refptr<net::IOBufferWithSize> io_buffer(
new net::IOBufferWithSize(params_->bytes_to_read));
SerialConnection* serial_connection(GetSerialConnection(
params_->connection_id));
if (serial_connection)
bytes_read = serial_connection->Read(io_buffer);
base::DictionaryValue* result = new base::DictionaryValue();
// The API is defined to require a 'data' value, so we will always
// create a BinaryValue, even if it's zero-length.
if (bytes_read < 0)
bytes_read = 0;
result->SetInteger(kBytesReadKey, bytes_read);
result->Set(kDataKey, base::BinaryValue::CreateWithCopiedBuffer(
io_buffer->data(), bytes_read));
SetResult(result);
}
bool SerialReadFunction::Respond() {
return true;
}
SerialWriteFunction::SerialWriteFunction()
: io_buffer_(NULL), io_buffer_size_(0) {
}
SerialWriteFunction::~SerialWriteFunction() {
}
bool SerialWriteFunction::Prepare() {
set_work_thread_id(BrowserThread::FILE);
params_ = api::serial::Write::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
io_buffer_size_ = params_->data.size();
io_buffer_ = new net::WrappedIOBuffer(params_->data.data());
return true;
}
void SerialWriteFunction::Work() {
int bytes_written = -1;
SerialConnection* serial_connection = GetSerialConnection(
params_->connection_id);
if (serial_connection)
bytes_written = serial_connection->Write(io_buffer_, io_buffer_size_);
else
error_ = kSerialConnectionNotFoundError;
base::DictionaryValue* result = new base::DictionaryValue();
result->SetInteger(kBytesWrittenKey, bytes_written);
SetResult(result);
}
bool SerialWriteFunction::Respond() {
return true;
}
SerialFlushFunction::SerialFlushFunction() {
}
SerialFlushFunction::~SerialFlushFunction() {
}
bool SerialFlushFunction::Prepare() {
set_work_thread_id(BrowserThread::FILE);
params_ = api::serial::Flush::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
return true;
}
void SerialFlushFunction::Work() {
bool flush_result = false;
SerialConnection* serial_connection = GetSerialConnection(
params_->connection_id);
if (serial_connection) {
serial_connection->Flush();
flush_result = true;
}
SetResult(Value::CreateBooleanValue(flush_result));
}
bool SerialFlushFunction::Respond() {
return true;
}
SerialGetControlSignalsFunction::SerialGetControlSignalsFunction()
: api_response_(false) {
}
SerialGetControlSignalsFunction::~SerialGetControlSignalsFunction() {
}
bool SerialGetControlSignalsFunction::Prepare() {
set_work_thread_id(BrowserThread::FILE);
params_ = api::serial::GetControlSignals::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
return true;
}
void SerialGetControlSignalsFunction::Work() {
base::DictionaryValue *result = new base::DictionaryValue();
SerialConnection* serial_connection = GetSerialConnection(
params_->connection_id);
if (serial_connection) {
SerialConnection::ControlSignals control_signals = { 0 };
if (serial_connection->GetControlSignals(control_signals)) {
api_response_ = true;
result->SetBoolean(kDcdKey, control_signals.dcd);
result->SetBoolean(kCtsKey, control_signals.cts);
} else {
error_ = kErrorGetControlSignalsFailed;
}
} else {
error_ = kSerialConnectionNotFoundError;
result->SetBoolean(kSuccessKey, false);
}
SetResult(result);
}
bool SerialGetControlSignalsFunction::Respond() {
return api_response_;
}
SerialSetControlSignalsFunction::SerialSetControlSignalsFunction() {
}
SerialSetControlSignalsFunction::~SerialSetControlSignalsFunction() {
}
bool SerialSetControlSignalsFunction::Prepare() {
set_work_thread_id(BrowserThread::FILE);
params_ = api::serial::SetControlSignals::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
return true;
}
void SerialSetControlSignalsFunction::Work() {
SerialConnection* serial_connection = GetSerialConnection(
params_->connection_id);
if (serial_connection) {
SerialConnection::ControlSignals control_signals = { 0 };
control_signals.should_set_dtr = params_->options.dtr.get() != NULL;
if (control_signals.should_set_dtr)
control_signals.dtr = *(params_->options.dtr);
control_signals.should_set_rts = params_->options.rts.get() != NULL;
if (control_signals.should_set_rts)
control_signals.rts = *(params_->options.rts);
if (serial_connection->SetControlSignals(control_signals)) {
SetResult(Value::CreateBooleanValue(true));
} else {
error_ = kErrorSetControlSignalsFailed;
SetResult(Value::CreateBooleanValue(false));
}
} else {
error_ = kSerialConnectionNotFoundError;
SetResult(Value::CreateBooleanValue(false));
}
}
bool SerialSetControlSignalsFunction::Respond() {
return true;
}
} // namespace extensions
|
4854b8f0ba9f7c751f511508afcd4a20095f32d1 | 3478ccef99c85458a9043a1040bc91e6817cc136 | /Project/HanWenBook/Source/Data/HWDocDynamic.h | a1f057fdaaa55d1979aef97f414d94fd8b22250b | [] | no_license | gybing/Hackett | a1183dada6eff28736ebab52397c282809be0e7b | f2b47d8cc3d8fa9f0d9cd9aa71b707c2a01b8a50 | refs/heads/master | 2020-07-25T22:58:59.712615 | 2019-07-09T09:40:00 | 2019-07-09T09:40:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,262 | h | HWDocDynamic.h | #pragma once
#include "HWDocBase.h"
#include "json.h"
class HWParaBookNoteList : public HWParaUI
{
public:
HWParaBookNoteList(const juce::String& szBook, HWEnum_DynamicType tp, int nBegin, int nCount, bool bHasFlower)
: m_strBook(szBook), m_tp(tp), m_nBegin(nBegin), m_nCount(nCount), m_bHasFlower(bHasFlower)
{
}
protected:
friend class HWDocDynamic;
HWParaBookNoteList(){}
const HWParas* ToHWPara()
{
m_Para.Add("guid", m_strBook.toUTF8());
m_Para.Add("hasflower", m_bHasFlower ? 1:0);
m_Para.Add("type", (int)m_tp);
m_Para.Add("begin", m_nBegin);
m_Para.Add("count", m_nCount);
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_strBook = para->StrVal("guid");
m_bHasFlower = para->IntVal("hasflower") == 1;
m_tp = (HWEnum_DynamicType)para->IntVal("type");
m_nBegin = para->IntVal("begin");
m_nCount = para->IntVal("count");
return true;
}
private:
HWEnum_DynamicType m_tp;
int m_nBegin;
int m_nCount;
juce::String m_strBook;
bool m_bHasFlower;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaBookNoteList)
};
class HWParaUserNoteList : public HWParaUI
{
public:
HWParaUserNoteList(const char* szUser, const char* szBook, HWEnum_DynamicType tp, int nBegin, int nCount, bool bHasFlower)
: m_strUser(szUser), m_strBook(szBook), m_tp(tp), m_nBegin(nBegin), m_nCount(nCount), m_bHasFlower(bHasFlower)
{
}
protected:
friend class HWDocDynamic;
HWParaUserNoteList(){}
const HWParas* ToHWPara()
{
m_Para.Add("shelfno", m_strUser.toUTF8());
m_Para.Add("guid", m_strBook.toUTF8());
m_Para.Add("hasflower", m_bHasFlower);
m_Para.Add("type", m_tp);
m_Para.Add("begin", m_nBegin);
m_Para.Add("count", m_nCount);
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_strUser = para->StrVal("shelfno");
m_strBook = para->StrVal("guid");
m_bHasFlower = 1==para->IntVal("hasflower");
m_tp = (HWEnum_DynamicType)para->IntVal("type");
m_nBegin = para->IntVal("begin");
m_nCount = para->IntVal("count");
return true;
}
private:
HWEnum_DynamicType m_tp;
int m_nBegin;
int m_nCount;
juce::String m_strBook;
juce::String m_strUser;
bool m_bHasFlower;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaUserNoteList)
};
class HWParaDynamicInfo : public HWParaUI
{
public:
HWParaDynamicInfo(int nID)
: m_nID(nID)
{
}
protected:
friend class HWDocDynamic;
HWParaDynamicInfo(){}
const HWParas* ToHWPara()
{
m_Para.Add("id", m_nID);
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_nID = para->IntVal("id");
return true;
}
public:
int m_nID;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaDynamicInfo)
};
class HWParaDynamicReplyInfo : public HWParaUI
{
public:
HWParaDynamicReplyInfo(int nID)
: m_nID(nID)
{
}
protected:
friend class HWDocDynamic;
HWParaDynamicReplyInfo(){}
const HWParas* ToHWPara()
{
m_Para.Add("id", m_nID);
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_nID = para->IntVal("id");
return true;
}
private:
int m_nID;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaDynamicReplyInfo)
};
class HWParaDynamicReplyList : public HWParaUI
{
public:
HWParaDynamicReplyList(int nID, int nBegin, int nCount)
: m_nID(nID), m_nBegin(nBegin), m_nCount(nCount)
{
}
protected:
friend class HWDocDynamic;
HWParaDynamicReplyList(){}
const HWParas* ToHWPara()
{
m_Para.Add("id", m_nID);
m_Para.Add("begin", m_nBegin);
m_Para.Add("count", m_nCount);
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_nID = para->IntVal("id");
m_nBegin = para->IntVal("begin");
m_nCount = para->IntVal("count");
return true;
}
private:
int m_nID;
int m_nBegin;
int m_nCount;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaDynamicReplyList)
};
class HWParaDynamicReply : public HWParaUI
{
public:
HWParaDynamicReply(int nID, const wchar_t* strText)
: m_nID(nID), m_strText(strText)
{
}
protected:
friend class HWDocDynamic;
HWParaDynamicReply(){}
const HWParas* ToHWPara()
{
m_Para.Add("id", m_nID);
m_Para.Add("text", m_strText.toUTF8());
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_nID = para->IntVal("id");
m_strText = para->StrVal("text");
return true;
}
private:
int m_nID;
juce::String m_strText;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaDynamicReply)
};
class HWParaDynamicReplyReply : public HWParaUI
{
public:
HWParaDynamicReplyReply(int nID, const wchar_t* strText)
: m_nID(nID), m_strText(strText)
{
}
protected:
friend class HWDocDynamic;
HWParaDynamicReplyReply(){}
const HWParas* ToHWPara()
{
m_Para.Add("id", m_nID);
m_Para.Add("text", m_strText.toUTF8());
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_nID = para->IntVal("id");
m_strText = para->StrVal("text");
return true;
}
private:
int m_nID;
juce::String m_strText;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaDynamicReplyReply)
};
class HWParaDynamicZan : public HWParaUI
{
public:
HWParaDynamicZan(int nID, bool bZan)
: m_nID(nID), m_bZan(bZan)
{
}
protected:
friend class HWDocDynamic;
HWParaDynamicZan(){}
const HWParas* ToHWPara()
{
m_Para.Add("id", m_nID);
m_Para.Add("op", m_bZan);
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_nID = para->IntVal("id");
m_bZan = 1==para->IntVal("op");
return true;
}
private:
int m_nID;
bool m_bZan;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaDynamicZan)
};
class HWParaDynamicFlower : public HWParaUI
{
public:
HWParaDynamicFlower(int nID, int nOP)
: m_nID(nID), m_nOP(nOP)
{
}
protected:
friend class HWDocDynamic;
HWParaDynamicFlower(){}
const HWParas* ToHWPara()
{
m_Para.Add("id", m_nID);
m_Para.Add("op", m_nOP);
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_nID = para->IntVal("id");
m_nOP = para->IntVal("op");
return true;
}
private:
int m_nID;
int m_nOP;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaDynamicFlower)
};
class HWParaDynamicDel : public HWParaUI
{
public:
HWParaDynamicDel(int nID)
: m_nID(nID)
{
}
protected:
friend class HWDocDynamic;
HWParaDynamicDel(){}
const HWParas* ToHWPara()
{
m_Para.Add("id", m_nID);
return &m_Para;
}
bool FromHWPara(const HWParas* para)
{
m_nID = para->IntVal("id");
return true;
}
private:
int m_nID;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWParaDynamicDel)
};
class HWDocDynamic : public HWDocBase
{
public:
juce_DeclareSingleton(HWDocDynamic, false)
HWDocDynamic();
virtual ~HWDocDynamic();
struct HWDynamicReply
{
int nID;
int nReplyCount;
int nReviewCount;
HWTReplyInfo replyInfo;
};
struct HWDinamicReplyReply
{
int nID;
int nReplyCount;
HWTReplyInfo replyInfo;
};
int GetBookNoteCount() const;
void GetBookNoteList(std::vector<std::pair<int,int>>& vec);
int GetUserNoteCount() const;
void GetUserNoteList(std::vector<std::pair<int,int>>& vec);
HWTDynamicInfo* GetDynamicInfo();
int GetDynamicReplyCount();
std::vector<int>* GetDynamicReplyList();
HWTReplyInfo* GetDynamicReplyInfo();
std::pair<int,int>* GetFavourResult();
std::pair<int,int>* GetFlowerResult();
protected:
virtual void OnInit();
virtual void OnFinal();
virtual bool LocalGet( HWRequestor* pRequestor, HWEnum_ReqID reqID, HWParaUI* para, HWContext ctx );
virtual HWParaUI* MakeHWParaUI(HWEnum_ReqID reqID, const HWParas* para);
virtual void* OnRespPreProcess(HWEnum_ReqID id, const HWParas* paras, const HWDict* dict);
virtual void OnRespProcess(HWEnum_ReqID id, const HWParas* paras, void* data);
private:
int m_nBookNoteListCount;
int m_nUserNoteListCount;
std::vector<std::pair<int,int>>* m_pVecBookNoteList;
std::vector<std::pair<int,int>>* m_pVecUserNoteList;
HWTDynamicInfo* m_pDynamicInfo;
HWTReplyInfo* m_pReplayInfo;
int m_nDynamicReplyCount;
std::vector<int>* m_pVecDynamicReplyList;
HWDynamicReply* m_pDynamicReply;
HWDinamicReplyReply* m_pDynamicReplyReply;
std::pair<int,int>* m_pFavourResult;
std::pair<int,int>* m_pFlowerResult;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWDocDynamic)
}; |
e8a869e888c2bc0e5e3cef802384e6c7eeae328c | 1b6b94ecbd7f8882ca0609c39bcfb09affc9bb77 | /CH6/6-2.cpp | 9fe50d86d482a9604277f368680c9d4161affd0e | [] | no_license | NLGRF/Course_Cpp | 112bd9ed50e7d67b3a8c9b4627add0c8a46d65fe | 6acd21aba9fce805bd530d1234554783f710ff3b | refs/heads/master | 2020-03-21T05:46:16.328372 | 2018-06-21T14:11:33 | 2018-06-21T14:11:33 | 138,178,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | cpp | 6-2.cpp | #include <iostream>
using namespace std;
int main()
{
int arr2D[3][5], num;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 5; j++)
{
num +=1;
arr2D[i][j] = num;
}
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++){
cout <<"\t"<< arr2D[i][j];
}
cout << endl;
}
return 0;
}
|
dbd7aa79f62a19cf939668e708ddd25587c83209 | a60e0d61aeea3e7d332d80527424f1db1b02e918 | /hw5/hw5_final_sprint3/Customer.cpp | f41555c91724d5eddb51c15ad6687bc75c5de816 | [] | no_license | KRT0335/CSE1325 | 00a55bd181e03ec947263cddeaa03ccdfd302019 | b3382800b9b4cafcdb0b286624c47666f66eee69 | refs/heads/master | 2021-01-12T13:00:56.105818 | 2016-11-22T13:28:12 | 2016-11-22T13:28:12 | 70,111,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,279 | cpp | Customer.cpp | #include "Customer.h"
void Order::addCustomerInfo(Customer c) {
customer.push_back(c);
}
int Customer::get_modelNumber(int index) {
return modelNumber;
}
string Customer::get_customer_name(int index) {
return customerName;
}
void Order::printCustomerName(int index) {
cout << customer[index].get_customer_name(index);
}
/*
void Order::printOrder(int modelNumber) {
int rmNumber;
if (modelNumber > 0) {
cout << "List of Orders: " << endl;
for (rmNumber = 0; rmNumber < modelNumber; rmNumber++) {
cout << '[' << std::to_string(rmNumber + 1) << "] ";
fullModel.printModelName(rmNumber);
cout << ' ';
printCustomerName(rmNumber);
cout << endl<<endl;
}
}
else {
cout << "No Orders are in." << endl;
}
}
*/
void Order::catalog(int modelNumber) {
vector<RobotModels> robotModels;
int select = 0;
int rmNumber;
string rmName = "test";
if (modelNumber > 0) {
for (rmNumber = 0; rmNumber < modelNumber; rmNumber++) {
cout << '[' << std::to_string(rmNumber + 1) << "] ";
fullModel.printModelName(rmNumber);
cout << endl;
//fullModel.print(rmNumber);
}
cout << "[-1] Leave Catalog" << endl;
while (select != -1) {
cout << "Which Model to view?" << endl;
cin >> select;
fullModel.checkInputInt(select);
cin.ignore();
if (select != -1) {
if (select > rmNumber + 1 || select < 1) {
cout << "Invalid Input" << endl;
}
else {
cout << endl;
fullModel.print(select - 1);
}
}
}
}
else {
cout << "There are no Models in the catalog." << endl
<< "The catalog is made up of Models custom made." << endl
<< "Create a Model to start up the catalog and knowing you are FIRST." << endl;
}
}
void Order::makeOrder(int modelNumber) {
int modelCount = modelNumber;
string customerName;
int cataBuy = 0;
double price; //$1.50 for every weight
cout << "Name?" << endl;
getline(cin, customerName);
if (cataBuy == 1) {
price = (1.5*(robotModels[modelNumber].get_weight(modelNumber)));
Customer insertC(price, customerName, modelNumber);
addCustomerInfo(insertC);
}
else{
fullModel.createModel(modelNumber);
if (modelCount != modelNumber) {
price = (1.5*(robotModels[modelNumber].get_weight(modelNumber)));
Customer insertC(price, customerName, modelNumber);
addCustomerInfo(insertC);
}
}
modelNumber = modelCount;
//return modelNumber;
}
void Order::displayMenu() {
int select = 0, countModel = 0, countCus = 0;
int modelNumber = 0, cataBuy = 0;
int modelCount = 0;
string customerName;
double price = 0; //$1.50 for every weight
while (select != -1) {
cout << "[1] Order a Robot Model" << endl
<< "[2] Browse Catalog" << endl
//<< "[3] Print All Orders" << endl //WIP
<< "[-1] End Program" << endl
<< "Select: " << endl;
cin >> select;
fullModel.checkInputInt(select);
cin.ignore();
switch (select) {
case 1:
makeOrder(countModel);
countModel++;
break;
case 2:
catalog(countModel);
break;
//case 3:
//printOrder(countModel);
//break;
case -1:
break;
default:
cout << "Invalid Input" << endl;
select = 0;
}
}
} |
3193ded05e80d81db507074eb01f2a455a444b6d | e33c16e84d5f558786ffc583718e782cd49b5dd8 | /tests/absor-test.cpp | d3512911627a344007816acbb242852226c4d59e | [
"MIT"
] | permissive | d-SEAMS/seams-core | fa4eaa14be9059f2a0fb87f2725866290d0ebe94 | e42be0a1f28de2f8d6b44b6cf97e20cc4c058266 | refs/heads/main | 2023-08-31T02:01:40.889157 | 2023-08-23T19:38:29 | 2023-08-23T19:38:29 | 164,746,444 | 29 | 6 | MIT | 2023-08-23T19:38:30 | 2019-01-08T22:50:43 | C++ | UTF-8 | C++ | false | false | 15,481 | cpp | absor-test.cpp | // Internal
#include <absOrientation.hpp>
#include <bulkTUM.hpp>
#include <franzblau.hpp>
#include <mol_sys.hpp>
#include <neighbours.hpp>
#include <pntCorrespondence.hpp>
#include <ring.hpp>
#include <topo_bulk.hpp>
// Standard
#include <iostream>
#include <catch2/catch.hpp>
#include <rang.hpp>
SCENARIO("Test the shape-matching of a perfect HC rotated by 30 degrees",
"[match]") {
GIVEN("A rotated HC (candidate structure)") {
// --------------------------
// GETTING THE REFERENCE/TEMPLATE POINT SET
int nop = 12; // Number of particles in an HC
int dim = 3; // Number of dimensions
//
std::string filePathXYZ = "../templates/hc.xyz";
// Variables for rings
std::vector<std::vector<int>> nList; // Neighbour list
std::vector<std::vector<int>> rings; // Rings
std::vector<ring::strucType>
ringType; // This vector will have a value for each ring inside
std::vector<int> listHC; // Contains atom indices of atoms making up HCs
// Make a list of all the DDCs and HCs
std::vector<cage::Cage> cageList;
Eigen::MatrixXd refPnts(12, 3); // Reference point set (Eigen matrix)
int iring, jring;
// -------------------------------------
//
// REFERENCE POINT SET
refPnts = tum3::buildRefHC(filePathXYZ);
//
// -------------------------------------
// GETTING THE ROTATED POINT SET
molSys::PointCloud<molSys::Point<double>, double>
targetCloud; // pointCloud
molSys::Point<double> iPoint;
Eigen::MatrixXd targetPointSet(nop, dim);
// Fill the pointCloud
//
iPoint.type = 1; // Same for all the points here
// Element {0}
iPoint.atomID = 0; // iatom
iPoint.x = 19.8443861192; // x
iPoint.y = 3.6525394722; // y
iPoint.z = 15.0939999; // z
targetCloud.pts.push_back(iPoint);
// Element {1}
iPoint.atomID = 1; // iatom
iPoint.x = 15.9491946129; // x
iPoint.y = 5.9012086664; // y
iPoint.z = 15.0939999; // z
targetCloud.pts.push_back(iPoint);
// Element {2}
iPoint.atomID = 2; // iatom
iPoint.x = 15.9490040262; // x
iPoint.y = 1.4035395722; // y
iPoint.z = 15.0939999; // z
targetCloud.pts.push_back(iPoint);
// Element {3}
iPoint.atomID = 3; // iatom
iPoint.x = 18.5458860692; // x
iPoint.y = 5.9016075325; // y
iPoint.z = 14.1949997; // z
targetCloud.pts.push_back(iPoint);
// Element {4}
iPoint.atomID = 4; // iatom
iPoint.x = 18.5456945129; // x
iPoint.y = 1.4039389177; // y
iPoint.z = 14.1949997; // z
targetCloud.pts.push_back(iPoint);
// Element {5}
iPoint.atomID = 5; // iatom
iPoint.x = 14.6505039762; // x
iPoint.y = 3.6526076325; // y
iPoint.z = 14.1949997; // z
targetCloud.pts.push_back(iPoint);
// Element {6}
iPoint.atomID = 6; // iatom
iPoint.x = 18.5458860692; // x
iPoint.y = 5.9016075325; // y
iPoint.z = 11.4329996; // z
targetCloud.pts.push_back(iPoint);
// Element {7}
iPoint.atomID = 7; // iatom
iPoint.x = 18.5456945129; // x
iPoint.y = 1.4039389177; // y
iPoint.z = 11.4329996; // z
targetCloud.pts.push_back(iPoint);
// Element {8}
iPoint.atomID = 8; // iatom
iPoint.x = 14.6505039762; // x
iPoint.y = 3.6526076325; // y
iPoint.z = 11.4329996; // z
targetCloud.pts.push_back(iPoint);
// Element {9}
iPoint.atomID = 9; // iatom
iPoint.x = 19.8443861192; // x
iPoint.y = 3.6525394722; // y
iPoint.z = 10.5340004; // z
targetCloud.pts.push_back(iPoint);
// Element {10}
iPoint.atomID = 10; // iatom
iPoint.x = 15.9491946129; // x
iPoint.y = 5.9012086664; // y
iPoint.z = 10.5340004; // z
targetCloud.pts.push_back(iPoint);
// Element {11}
iPoint.atomID = 11; // iatom
iPoint.x = 15.9490040262; // x
iPoint.y = 1.4035395722; // y
iPoint.z = 10.5340004; // z
targetCloud.pts.push_back(iPoint);
// Update nop
targetCloud.nop = targetCloud.pts.size();
// box lengths
targetCloud.box.push_back(50); // x box length
targetCloud.box.push_back(50); // y box length
targetCloud.box.push_back(50); // z box length
// Update the unordered map
for (int iatom = 0; iatom < targetCloud.nop; iatom++) {
targetCloud.idIndexMap[iatom] = iatom;
} // end of filling the map
//
//
// --------------------------
// GETTING THE TARGET POINT SET
// Calculate a neighbour list
nList = nneigh::neighListO(3.5, &targetCloud, 1);
// Neighbour list by index
nList = nneigh::neighbourListByIndex(&targetCloud, nList);
// Find the vector of vector of rings
rings = primitive::ringNetwork(nList, 6);
// init the ringType vector
ringType.resize(rings.size());
// Find the HCs
listHC = ring::findHC(rings, &ringType, nList, &cageList);
// Get the basal rings from cageList
iring = cageList[0].rings[0];
jring = cageList[0].rings[1];
//
std::vector<int> matchedBasal1,
matchedBasal2; // Re-ordered basal rings 1 and 2
// Reordered basal rings
// Getting the target Eigen vectors
// Get the re-ordered matched basal rings, ordered with respect to each
// other
pntToPnt::relOrderHC(&targetCloud, rings[iring], rings[jring], nList,
&matchedBasal1, &matchedBasal2);
//
// --------------------------
// Now get the absolute orientation of the left (candidate/target) system
// with respect to the right (template/reference) system test
//
std::vector<double> quaternionRot; // quaternion rotation
double rmsd1, rmsd2; // least RMSD
std::vector<double> rmsdList1, rmsdList2; // List of RMSD per atom
double scale; // Scale factor
//
//
// Variables for looping through possible permutations
//
std::vector<double> currentQuat; // quaternion rotation
double currentRmsd; // least RMSD
std::vector<double> currentRmsdList; // List of RMSD per atom
double currentScale;
// absolute orientation using Horn's algorithm between the target and test
// set
int index;
for (int i = 0; i < 6; i++) {
// Change the order of the target points somehow!
//
targetPointSet = pntToPnt::changeHexCageOrder(&targetCloud, matchedBasal1,
matchedBasal2, i);
// Shape-matching
absor::hornAbsOrientation(refPnts, targetPointSet, ¤tQuat,
¤tRmsd, ¤tRmsdList, ¤tScale);
if (i == 0) {
quaternionRot = currentQuat;
rmsd1 = currentRmsd;
rmsdList1 = currentRmsdList;
scale = currentScale;
index = 0;
} else {
if (currentRmsd < rmsd1) {
quaternionRot = currentQuat;
rmsd1 = currentRmsd;
rmsdList1 = currentRmsdList;
scale = currentScale;
index = i;
} // update
} // Update if this is a better match
} // Loop through possible permutations
// ---------
std::vector<double>
selfQuatRot; // quaternion for the reference set and itself
double selfScale; // Scale for the reference set and itself
// Shape-matching
absor::hornAbsOrientation(refPnts, refPnts, &selfQuatRot, &rmsd2,
&rmsdList2, &selfScale);
//
double angDist = gen::angDistDegQuaternions(selfQuatRot, quaternionRot);
//
REQUIRE_THAT(angDist, Catch::Matchers::Floating::WithinAbsMatcher(
30.0, 0.01)); // Evaluate condition
// --------------------------
} // End of given
} // End of scenario
// DDC shape-matching
SCENARIO("Test the shape-matching of a perfect DDC rotated by 30 degrees",
"[match]") {
GIVEN("A rotated DDC (candidate structure)") {
// --------------------------
// GETTING THE REFERENCE/TEMPLATE POINT SET
int nop = 14; // Number of particles in an HC
int dim = 3; // Number of dimensions
//
std::string filePathXYZ = "../templates/ddc.xyz";
// Variables for rings
std::vector<std::vector<int>> nList; // Neighbour list
std::vector<std::vector<int>> rings; // Rings
std::vector<ring::strucType>
ringType; // This vector will have a value for each ring inside
std::vector<int> listHC,
listDDC; // Contains atom indices of atoms making up HCs
// Make a list of all the DDCs and HCs
std::vector<cage::Cage> cageList;
std::vector<int> ddcOrder; // Connectivity of the DDC
Eigen::MatrixXd refPnts(14, 3); // Reference point set (Eigen matrix)
// -------------------------------------
//
// REFERENCE POINT SET
refPnts = tum3::buildRefDDC(filePathXYZ);
//
// -------------------------------------
// GETTING THE ROTATED POINTS
molSys::PointCloud<molSys::Point<double>, double>
targetCloud; // pointCloud
molSys::Point<double> iPoint;
Eigen::MatrixXd targetPointSet(nop, dim);
// Fill the pointCloud
//
iPoint.type = 1; // Same for all the points here
// Element {0}
iPoint.atomID = 0; // iatom
iPoint.x = 9.3263264; // x
iPoint.y = 34.8063278; // y
iPoint.z = 19.1100006; // z
targetCloud.pts.push_back(iPoint);
// Element {1}
iPoint.atomID = 1; // iatom
iPoint.x = 9.3263264; // x
iPoint.y = 34.8063278; // y
iPoint.z = 25.4799996; // z
targetCloud.pts.push_back(iPoint);
// Element {2}
iPoint.atomID = 2; // iatom
iPoint.x = 10.9188262; // x
iPoint.y = 32.0480347; // y
iPoint.z = 22.2950001; // z
targetCloud.pts.push_back(iPoint);
// Element {3}
iPoint.atomID = 3; // iatom
iPoint.x = 7.7338257; // x
iPoint.y = 37.564621; // y
iPoint.z = 22.2950001; // z
targetCloud.pts.push_back(iPoint);
// Element {4}
iPoint.atomID = 4; // iatom
iPoint.x = 8.1605368; // x
iPoint.y = 30.4555359; // y
iPoint.z = 25.4799996; // z
targetCloud.pts.push_back(iPoint);
// Element {5}
iPoint.atomID = 5; // iatom
iPoint.x = 6.5680371; // x
iPoint.y = 33.2138252; // y
iPoint.z = 22.2950001; // z
targetCloud.pts.push_back(iPoint);
// Element {6}
iPoint.atomID = 6; // iatom
iPoint.x = 12.0846195; // x
iPoint.y = 36.3988266; // y
iPoint.z = 22.2950001; // z
targetCloud.pts.push_back(iPoint);
// Element {7}
iPoint.atomID = 7; // iatom
iPoint.x = 10.3361149; // x
iPoint.y = 29.8733234; // y
iPoint.z = 23.8880006; // z
targetCloud.pts.push_back(iPoint);
// Element {8}
iPoint.atomID = 8; // iatom
iPoint.x = 7.1511145; // x
iPoint.y = 35.3899078; // y
iPoint.z = 23.8880006; // z
targetCloud.pts.push_back(iPoint);
// Element {9}
iPoint.atomID = 9; // iatom
iPoint.x = 9.9094058; // x
iPoint.y = 36.9824066; // y
iPoint.z = 20.7029991; // z
targetCloud.pts.push_back(iPoint);
// Element {10}
iPoint.atomID = 10; // iatom
iPoint.x = 5.985323; // x
iPoint.y = 31.039114; // y
iPoint.z = 23.8880006; // z
targetCloud.pts.push_back(iPoint);
// Element {11}
iPoint.atomID = 11; // iatom
iPoint.x = 11.5019055; // x
iPoint.y = 34.2241135; // y
iPoint.z = 23.8880006; // z
targetCloud.pts.push_back(iPoint);
// Element {12}
iPoint.atomID = 12; // iatom
iPoint.x = 8.7436142; // x
iPoint.y = 32.6316147; // y
iPoint.z = 20.7029991; // z
targetCloud.pts.push_back(iPoint);
// Element {13}
iPoint.atomID = 13; // iatom
iPoint.x = 8.7436142; // x
iPoint.y = 32.6316147; // y
iPoint.z = 27.073; // z
targetCloud.pts.push_back(iPoint);
// Update nop
targetCloud.nop = targetCloud.pts.size();
// box lengths
targetCloud.box.push_back(50); // x box length
targetCloud.box.push_back(50); // y box length
targetCloud.box.push_back(50); // z box length
// Update the unordered map
for (int iatom = 0; iatom < targetCloud.nop; iatom++) {
targetCloud.idIndexMap[iatom] = iatom;
} // end of filling the map
//
//
// --------------------------
// GETTING THE TARGET POINT SET
// Calculate a neighbour list
nList = nneigh::neighListO(3.5, &targetCloud, 1);
// Neighbour list by index
nList = nneigh::neighbourListByIndex(&targetCloud, nList);
// Find the vector of vector of rings
rings = primitive::ringNetwork(nList, 6);
// init the ringType vector
ringType.resize(rings.size());
listDDC = ring::findDDC(rings, &ringType, listHC, &cageList);
// Save the order of the DDC in a vector
ddcOrder = pntToPnt::relOrderDDC(0, rings, cageList);
//
// --------------------------
// Now get the absolute orientation of the left (candidate/target) system
// with respect to the right (template/reference) system test
//
std::vector<double> quaternionRot; // quaternion rotation
double rmsd1, rmsd2; // least RMSD
std::vector<double> rmsdList1, rmsdList2; // List of RMSD per atom
double scale; // Scale factor
//
//
// Variables for looping through possible permutations
//
std::vector<double> currentQuat; // quaternion rotation
double currentRmsd; // least RMSD
std::vector<double> currentRmsdList; // List of RMSD per atom
double currentScale;
// absolute orientation using Horn's algorithm between the target and test
// set
int index;
for (int i = 0; i < 6; i++) {
// Change the order of the target points somehow!
//
targetPointSet = pntToPnt::changeDiaCageOrder(&targetCloud, ddcOrder, i);
// Shape-matching
absor::hornAbsOrientation(refPnts, targetPointSet, ¤tQuat,
¤tRmsd, ¤tRmsdList, ¤tScale);
if (i == 0) {
quaternionRot = currentQuat;
rmsd1 = currentRmsd;
rmsdList1 = currentRmsdList;
scale = currentScale;
index = 0;
} else {
if (currentRmsd < rmsd1) {
quaternionRot = currentQuat;
rmsd1 = currentRmsd;
rmsdList1 = currentRmsdList;
scale = currentScale;
index = i;
} // update
} // Update if this is a better match
} // Loop through possible permutations
// ---------
std::vector<double>
selfQuatRot; // quaternion for the reference set and itself
double selfScale; // Scale for the reference set and itself
// Shape-matching
absor::hornAbsOrientation(refPnts, refPnts, &selfQuatRot, &rmsd2,
&rmsdList2, &selfScale);
//
double angDist = gen::angDistDegQuaternions(selfQuatRot, quaternionRot);
//
REQUIRE_THAT(angDist, Catch::Matchers::Floating::WithinAbsMatcher(
30.0, 0.01)); // Evaluate condition
// --------------------------
// --------------------------
} // End of given
} // End of scenario
|
0ceea1d20a0199002373c0cc9f6607cb91b13cf5 | 2b1fd41b44de40a938f09622276c10d627cd1124 | /ObjectManger.cpp | c2fa2a5e46fa4ba305a957df3bd4c82da77c2fe8 | [] | no_license | Team-2years/MapTool | 36ebf19b0f42042e407d254fa1f1943e6974cad8 | e43f9266f7681ef67a605bb39c72d4c30d7c2a2a | refs/heads/master | 2023-06-25T08:31:33.483200 | 2021-07-28T03:35:21 | 2021-07-28T03:35:21 | 390,199,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp | ObjectManger.cpp | #include "stdafx.h"
#include "ObjectManger.h"
HRESULT ObjectManger::init()
{
return S_OK;
}
void ObjectManger::release()
{
}
void ObjectManger::update()
{
for (_viObject = _vObject.begin(); _viObject != _vObject.end(); ++_viObject)
{
(*_viObject)->update();
(*_viObject)->move();
}
}
void ObjectManger::render()
{
for (_viObject = _vObject.begin(); _viObject != _vObject.end(); ++_viObject)
{
(*_viObject)->render();
}
}
void ObjectManger::setObject(const char* name, float x, float y)
{
D_Object* Jar;
Jar = new D_Object;
Jar->init(name, PointMake(x, y));
_vObject.push_back(Jar);
}
void ObjectManger::collision()
{
//RECT temp;
//RECT rc = RectMake(_pl->getRCplayer()->left, _pl->getRCplayer()->top, _pl->getRCplayer()->right - _pl->getRCplayer()->left, _pl->getRCplayer()->bottom - _pl->getRCplayer()->top);
//RECT rc2 = RectMake(_pl->getRCplayerAteeck()->left, _pl->getRCplayerAteeck()->top,
// _pl->getRCplayerAteeck()->right - _pl->getRCplayerAteeck()->left, _pl->getRCplayerAteeck()->bottom - _pl->getRCplayerAteeck()->top);
//for (_viEyefly = _vEyefly.begin(); _viEyefly != _vEyefly.end(); ++_viEyefly)
//{
// RECT rc5 = (*_viEyefly)->getRect();
// if (IntersectRect(&temp, &rc5, &rc))
// {
// _pl->lifeDamge(1);
// _pl->death();
// _pl->deathSwith();
// }
//}
}
void ObjectManger::removeObject(int arrNum)
{
_vObject.erase(_vObject.begin() + arrNum);
}
|
a5222a88229a48482c264a2785afef726bc04a60 | 9b4f4ad42b82800c65f12ae507d2eece02935ff6 | /header/Math/Vector2D.h | 425af158cb07efb7aebc897d3d1dfd86b58314f9 | [] | no_license | github188/SClass | f5ef01247a8bcf98d64c54ee383cad901adf9630 | ca1b7efa6181f78d6f01a6129c81f0a9dd80770b | refs/heads/main | 2023-07-03T01:25:53.067293 | 2021-08-06T18:19:22 | 2021-08-06T18:19:22 | 393,572,232 | 0 | 1 | null | 2021-08-07T03:57:17 | 2021-08-07T03:57:16 | null | UTF-8 | C++ | false | false | 986 | h | Vector2D.h | #ifndef _SM_MATH_VECTOR2D
#define _SM_MATH_VECTOR2D
namespace Math
{
class CoordinateSystem;
class Vector2D
{
public:
typedef enum
{
VT_UNKNOWN,
VT_POINT,
VT_MULTIPOINT,
VT_POLYLINE,
VT_POLYGON,
VT_IMAGE,
VT_STRING,
VT_ELLIPSE,
VT_PIEAREA
} VectorType;
protected:
UInt32 srid;
public:
Vector2D(UInt32 srid);
virtual ~Vector2D();
virtual VectorType GetVectorType() = 0;
virtual void GetCenter(Double *x, Double *y) = 0;
virtual Math::Vector2D *Clone() = 0;
virtual void GetBounds(Double *minX, Double *minY, Double *maxX, Double *maxY) = 0;
virtual Double CalSqrDistance(Double x, Double y, Double *nearPtX, Double *nearPtY) = 0;
virtual Bool JoinVector(Math::Vector2D *vec) = 0;
virtual Bool Support3D() { return false; };
virtual void ConvCSys(Math::CoordinateSystem *srcCSys, Math::CoordinateSystem *destCSys) = 0;
UInt32 GetSRID();
void SetSRID(UInt32 srid);
};
}
#endif
|
d2085428fb6f9e922b83b4ae9605675e6bb21bb8 | 73a4689f209c33b64a94a773524b4cc27d64578f | /SME_source.cpp | 40e0702aaa869bbed3647fa07b63da868b1231b4 | [
"Zlib"
] | permissive | Phase-Matrix-Software/SME-Audio | 2f22214c6e66c90c24c24bb63ec11405d5ca6c28 | 7a37fddd726f166ba28b55d0d23982916030dcd0 | refs/heads/master | 2020-04-06T07:08:18.385256 | 2016-09-10T23:43:34 | 2016-09-11T13:10:30 | 64,018,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,216 | cpp | SME_source.cpp | #include "SME_source.h"
#include <vector>
#include <algorithm>
using namespace SME::Audio;
extern std::map<std::string, ALuint> buffers;
std::vector<Source *> sources;
Source::Source() {
alGenSources(1, &id);
ALfloat sPos [] = {0.f, 0.f, 0.f}; //positive x == left
ALfloat sVel [] = {0.f, 0.f, 0.f};
alSourcef(id, AL_PITCH, 1.f);
alSourcef(id, AL_GAIN, 1.f);
alSourcef(id, AL_MIN_GAIN, 0.f);
alSourcefv(id, AL_POSITION, sPos);
alSourcefv(id, AL_VELOCITY, sVel);
alSourcei(id, AL_LOOPING, AL_FALSE);
alSourcef(id, AL_REFERENCE_DISTANCE, 1); //min
alSourcef(id, AL_MAX_DISTANCE, 32); //range
sources.push_back(this);
}
SME::Audio::Source::~Source() {
alDeleteSources(1, &id);
sources.erase(std::remove(sources.begin(), sources.end(), this), sources.end());
}
void Source::playSound(std::string name) {
alSourcei(id, AL_BUFFER, buffers[name]);
alSourcePlay(id);
}
void Source::setPitch(float p) {alSourcef(id, AL_PITCH, p);}
void Source::setGain(float g) {alSourcef(id, AL_GAIN, g);}
void Source::setMaxDistance(float d) {alSourcef(id, AL_MAX_DISTANCE, d);}
void Source::setPos(glm::vec3 pos) {
alSource3f(id, AL_POSITION, pos.x, pos.y, pos.z);
}
void Source::setVel(glm::vec3 vel) {
alSource3f(id, AL_VELOCITY, vel.x, vel.y, vel.z);
}
SourceAttachment::SourceAttachment(SME::Level::Entity::Entity *e)
: Source::Source(), SME::Level::Entity::Attachment::Attachment(e) {}
void SourceAttachment::onPosChanged(glm::vec3 pos) { setPos(pos); }
void SourceAttachment::onVelChanged(glm::vec3 vel) { setVel(vel); }
void SourceAttachment::onRotChanged(glm::vec3 rot) {}
void SourceAttachment::onUpdate() {}
std::vector<ALuint> pausedSources;
void SME::Audio::pauseAll() {
for (Source *s : sources) {
ALint state;
alGetSourcei(s->id, AL_SOURCE_STATE, &state);
if (state == AL_PLAYING) {
pausedSources.push_back(s->id);
alSourcePause(s->id);
}
}
}
void SME::Audio::resumeAll() {
for (ALuint id : pausedSources) {
alSourcePlay(id);
}
pausedSources.clear();
} |
5a18afede482e59f0777e8f548c77650bcbc0dc8 | 2b626d592a2df54e75ca6516f7ede44375614711 | /Day03/BinarySearchTree/main.cpp | 1b34ddc991d23b0a537021b1348a11663e2bd019 | [] | no_license | ITI-9-Month-Progrm/DataStructures-and-Algorithmes | c9cec989217fabce2cea55c3df1c3e969818a9b2 | 9955ba6e8d941f6b588d44182cbdd0c5ab02323f | refs/heads/main | 2023-01-30T23:19:37.074993 | 2020-12-18T12:52:28 | 2020-12-18T12:52:28 | 321,534,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196 | cpp | main.cpp | #include <iostream>
#include "BST.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
BST <int>b;
b.addNode(50);
b.addNode(60);
b.addNode(20);
return 0;
}
|
e90bdaf959db31580aa5bd3942c89bf02fa4a51b | 9936b91663fddcbbd9d8622f1ed28db7f6ef786e | /Cplusplus/Cplusplus_oldsnippets/PRIM_SUDOKU/sudoku/funzioni.h | 906c50467c8cef17929b26c65c5744260676a621 | [] | no_license | sitodav/before-november-2014 | 9a49af237aabf1d7180e1e764f9aa3fa5a6cc667 | c00bacccd12079d1e946c15d2e972a59f79a4888 | refs/heads/master | 2021-01-20T15:38:58.403928 | 2015-05-23T09:23:35 | 2015-05-23T09:23:35 | 26,176,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | h | funzioni.h | #include <iostream>
#include <cstdlib>
#include "matrice.h"
#include <fstream>
using namespace std;
bool riempi_unica(int &n_cicli_backtracking,matrice *matrix,int i,int j);
void riempi_plurime(int &n_soluz,int &n_cicli_backtracking,matrice *matrix,int i,int j);
void set_clues(matrice *matrix);
void read_clues(matrice * &matrix);
|
0e6d83bbd25281d630a70524b72be51ec116c2ef | 00df5d7bfccab963d6462588c1d169a88b2c8596 | /beziersurface.h | 7104155a469e4cb0916dcf87f86b010bb9516afd | [] | no_license | FabianNiehaus/CG_2018_Project01 | 62f555af522c56da8941d40ab1da8624f6e0dd15 | 333ba3f30e6a07862a086ab9f92125e02287039c | refs/heads/master | 2020-03-09T16:33:51.849150 | 2018-05-14T09:57:46 | 2018-05-14T09:57:46 | 128,888,161 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,099 | h | beziersurface.h | /*
* Datum: 14.05.2018
* Autoren: Tuyet Nguyen, Fabian Niehaus
*/
#ifndef BEZIERSURFACE_H
#define BEZIERSURFACE_H
#include <cmath>
#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include "vertex.h"
#include "quad.h"
#include "vertexmatrix.h"
using namespace std;
class BezierSurface
{
public:
BezierSurface(string filename);
vector<Quad> getPreQuads();
vector<Quad> getPostQuads();
void calculateBezier();
vector<Vertex> getPreBezierVertices() const;
vector<Vertex> getPostBezierVertices() const;
private:
string filename;
bool readSuccess = false;
vector<Vertex> preBezierVertices;
vector<Vertex> postBezierVertices;
vector<Quad> preBezierQuads;
vector<Quad> postBezierQuads;
int m = 3;
int n = 3;
VertexMatrix preBezierMat;
VertexMatrix postBezierMat;
// Anzahl der Schritte für Bezier
int resolution = 20;
void readData();
float bernstein(int n, int i, float s);
float nChooseK(int n, int i);
};
#endif // BEZIERSURFACE_H
|
1d60a417d880733005aed02a67936615a9b4fe6f | 1d43af85b148e93bf37f3e0f17ab2c874bb3ddbe | /OpenGL/ParticleSystem.cpp | 6dd51b5d91101904e8d2756022c9887760b0c28d | [] | no_license | MartinManzinger/OpenGL | e34fa38fe46d9a4752579b9f17cdcf6c5638d3cb | 2efcb1dfb3563fafc4170cd3ed2f5aaf4f102fd1 | refs/heads/master | 2021-05-14T04:15:34.335874 | 2018-01-08T22:41:52 | 2018-01-08T22:41:52 | 116,639,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,359 | cpp | ParticleSystem.cpp |
#include "ParticleSystem.h"
#pragma region Struct_pt2d
// constructors
pt2d::pt2d()
{
x = 0;
y = 0;
}
pt2d::pt2d(float in_x, float in_y)
{
x = in_x;
y = in_y;
}
// operator overloading
pt2d pt2d::operator * (float Multiplier)
{
pt2d ReturnVal(this->x * Multiplier, this->y * Multiplier);
return ReturnVal;
}
pt2d pt2d::operator / (float Divider)
{
pt2d ReturnVal(this->x / Divider, this->y / Divider);
return ReturnVal;
}
pt2d pt2d::operator + (pt2d OtherPoint)
{
pt2d ReturnVal(this->x + OtherPoint.x, this->y + OtherPoint.y);
return ReturnVal;
}
pt2d pt2d::operator += (pt2d OtherPoint)
{
x += OtherPoint.x;
y += OtherPoint.y;
return *this;
}
pt2d pt2d::operator - (pt2d OtherPoint)
{
pt2d ReturnVal(this->x - OtherPoint.x, this->y - OtherPoint.y);
return ReturnVal;
}
// functions
void pt2d::clear()
{
x = 0;
y = 0;
}
void pt2d::set(float in_x, float in_y)
{
x = in_x;
y = in_y;
}
void pt2d::add(float add_x, float add_y)
{
x += add_x;
y += add_y;
}
// returns the distance between itself and other point
float pt2d::distance(pt2d OtherPoint)
{
float dx = OtherPoint.x - x;
float dy = OtherPoint.y - y;
return sqrt(dx*dx + dy*dy);
}
// returns the normalized directional vector to other point
pt2d pt2d::orthonormal(pt2d OtherPoint)
{
float dx = x - OtherPoint.x;
float dy = y - OtherPoint.y;
pt2d Temp(dx, dy);
return Temp / distance(OtherPoint);
}
#pragma endregion
#pragma region Struct_pList
// constructor
pList::pList()
{
ParticleNum = 0;
// generate first sublist for particles
EntryPoint = new Particle*[SubListSize];
memset(EntryPoint, NULL, SubListSize*sizeof(void*));
ActSubList = EntryPoint;
ActSubListIndex = 0;
}
// functions
// search and returns next particle entry in list
Particle* pList::GetParticle(bool Reset)
{
static Particle** SubListPtr = EntryPoint;
static int SubListIndex = 0;
Particle* ReturnParticle = nullptr;
// search from beginning?
if (Reset)
{
SubListPtr = EntryPoint;
SubListIndex = 0;
return nullptr;
}
// search next particle in list
while (1)
{
// end of actual sublist?
if (SubListIndex >= SubListSize - 1)
{
// next sublist
if (*SubListPtr != NULL)
{
SubListIndex = 0;
SubListPtr = (Particle**)*SubListPtr;
}
// end of complete list
else
{
SubListPtr = EntryPoint;
SubListIndex = 0;
return nullptr;
}
}
// particle contained in actual list entry?
if (*SubListPtr != NULL)
{
++SubListIndex;
++SubListPtr;
return *(SubListPtr-1);
}
// increment
++SubListIndex;
++SubListPtr;
}
}
void pList::AddEntry()
{
++ParticleNum;
Particle** NewListEntryPtr = ActSubList + ActSubListIndex;
*NewListEntryPtr = new Particle(NewListEntryPtr);
++ActSubListIndex;
// allocate new sublist?
if (ActSubListIndex >= SubListSize - 1)
{
// last entry of sublist is link to next sublist
Particle** NewSublistPtr = new Particle*[SubListSize];
*(ActSubList + ActSubListIndex) = (Particle*)NewSublistPtr;
ActSubList = NewSublistPtr;
memset(ActSubList, NULL, SubListSize * sizeof(void*));
ActSubListIndex = 0;
}
}
void pList::DefragList()
{
}
void pList::PrintInfo()
{
int SubListNum = 1;
int ParticlesNum = 0;
float Occupation = 0;
int SubListIndex = 0;
Particle** SubListPtr = EntryPoint;
while (1)
{
// end of actual sublist?
if (SubListIndex >= SubListSize-1)
{
// next sublist
if (*SubListPtr != NULL)
{
++SubListNum;
SubListIndex = 0;
SubListPtr = (Particle**)*SubListPtr;
}
// end of complete list
else
{
goto ListSearchComplete;
}
}
// particle contained in actual list entry?
if (*SubListPtr != NULL)
{
++ParticlesNum;
}
// increment
++SubListIndex;
++SubListPtr;
}
ListSearchComplete:
Occupation = ((float)ParticlesNum * 100) / ((float)(SubListNum-1)*(SubListSize-1)+ActSubListIndex);
printf("#### Particle List Info ####\n");
printf(" Number of Sublists: %i\n", SubListNum);
printf(" Number of Particles: %i\n", ParticlesNum);
printf(" Percentage of Occupation: %.2f\n", Occupation);
}
#pragma endregion
#pragma region Class_Particle
// private functions
// -0.5 to 0.5
float Particle::GenRandFloat()
{
int RandInt = rand() % 1000;
float RandFloat = ((float)RandInt) / 1000 - 0.5;
return RandFloat;
}
// -spread/2 to spread/2
float Particle::GenRandFloat(float spread)
{
return GenRandFloat()*spread;
}
// -max to max
float Particle::GenRandFloat(float min, float max)
{
float spread = max - min;
return GenRandFloat(spread) + spread / 2 + min;
}
// constructor
Particle::Particle(Particle** NewListEntry)
{
// store pointer to entry in particle list
ListEntry = NewListEntry;
static int IdCount = 0;
Id = IdCount;
++IdCount;
mass = GenRandFloat(0.00000000001, 0.0001);
radius = sqrt(mass*0.018);
pos.set(GenRandFloat(1.0), GenRandFloat(1.0));
vel.set(GenRandFloat(0.01)+0.01*pos.y, GenRandFloat(0.01)-0.01*pos.x);
temperature = GenRandFloat(0, 10);
}
// destructor
Particle::~Particle()
{
// remove pointer to this particle in particle list
*ListEntry = nullptr;
}
// functions
// decide if explode or merge particles: returns number of resulting particles
int Particle::Collide(Particle* NewParticles)
{
if (CollisionNote == nullptr) return 0;
// merge particles
// calculate propertys of resulting particle
float d_vel = vel.distance(CollisionNote->vel);
temperature = temperature*mass + CollisionNote->temperature*CollisionNote->mass;
pt2d newimpuls = (vel*mass) +(CollisionNote->vel*CollisionNote->mass);
mass += CollisionNote->mass;
radius = sqrt(mass*0.018);
temperature /= mass;
temperature += d_vel*d_vel*1000000;
vel = newimpuls / mass;
// delete other particle
CollisionNote->CollisionNote = nullptr;
delete CollisionNote;
CollisionNote = nullptr;
return 1;
}
void Particle::PrintInfo()
{
printf("MassPoint (ID: %i)\n", Id);
printf(" Position: %.2f, %.2f\n", pos.x, pos.y);
printf(" Velocity: %.2f, %.2f\n", vel.x, vel.y);
printf(" Mass: %.2f\n", mass);
}
#pragma endregion
#pragma region Class_ParticleEngine
// constructor: initialisation
ParticleEngine::ParticleEngine()
{
// generate particles
for (int i = 0; i < ParticleStartNum; i++)
{
ParticleList.AddEntry();
}
ParticleList.PrintInfo();
}
// functions
Particle* ParticleEngine::GetParticle(bool Reset)
{
return ParticleList.GetParticle(Reset);
}
void ParticleEngine::CalcNextTick()
{
// delete old acceleration data
ParticleList.GetParticle(true);
Particle* ActParticle = ParticleList.GetParticle();
while (ActParticle != nullptr)
{
ActParticle->acc.clear();
ActParticle = ParticleList.GetParticle();
}
// calculate acceleration with collision detection
// triangle matrix access of particles in list for efficiency
ParticleList.GetParticle(true);
ActParticle = ParticleList.GetParticle(); // particle 0
ActParticle = ParticleList.GetParticle(); // particle 1
ParticleList.GetParticle(true);
int TriangleEnd = 1;
int TriangleIndex = 0;
while (1)
{
// next triangle line?
if (TriangleEnd == TriangleIndex)
{
++TriangleEnd;
TriangleIndex = 0;
ParticleList.GetParticle();
ActParticle = ParticleList.GetParticle();
ParticleList.GetParticle(true);
}
// end of triangle matrix access?
if (ActParticle == nullptr) break;
// pick other particle from triangle line
Particle* OtherParticle = ParticleList.GetParticle();
++TriangleIndex;
// acceleration calculation
float distance = ActParticle->pos.distance(OtherParticle->pos);
pt2d orthonorm = ActParticle->pos.orthonormal(OtherParticle->pos);
float massAct = ActParticle->mass;
float massOther = OtherParticle->mass;
float factor = (G*massAct*massOther) / distance;
ActParticle->acc += orthonorm * -factor;
OtherParticle->acc += orthonorm * factor;
// collision detection
if (distance <= ActParticle->radius + OtherParticle->radius)
{
if (ActParticle->CollisionNote == nullptr && OtherParticle->CollisionNote == nullptr)
{
ActParticle->CollisionNote = OtherParticle;
OtherParticle->CollisionNote = ActParticle;
}
}
}
// calculate new velocity and position with acceleration and collision handling and new temperature
ParticleList.GetParticle(true);
ActParticle = ParticleList.GetParticle();
while (ActParticle != nullptr)
{
// calculate new temperature
ActParticle->temperature *= 0.999;
// calculate new velocity and position with acceleration
if (ActParticle->CollisionNote == nullptr)
{
ActParticle->vel += ActParticle->acc / ActParticle->mass;
ActParticle->pos += ActParticle->vel;
if (ActParticle->mass >= 0.008)
{
ActParticle->PrintInfo();
delete ActParticle;
}
}
// collision handling
else
{
Particle* Temp = nullptr;
ActParticle->Collide(Temp);
ParticleList.PrintInfo();
}
ActParticle = ParticleList.GetParticle();
}
}
void ParticleEngine::ToGravCenter()
{
// find gravity center
GetParticle(true);
Particle* ActParticle = GetParticle();
pt2d Center;
float CenterMass = 0.0;
while (ActParticle != nullptr)
{
float NewCenterMass = CenterMass + ActParticle->mass;
Center = (ActParticle->pos*ActParticle->mass + Center*CenterMass) / NewCenterMass;
CenterMass = NewCenterMass;
ActParticle = GetParticle();
}
// transform coordinate system
GetParticle(true);
ActParticle = GetParticle();
while (ActParticle != nullptr)
{
ActParticle->pos = ActParticle->pos - Center;
ActParticle = GetParticle();
}
}
void ParticleEngine::AddParticle() {
ParticleList.AddEntry();
}
#pragma endregion
|
a8dc15e64e93e28a2d4f7de1398bf34bcedc2aa3 | c51bc5c927f2dc103cc01b80133a637b68690f7b | /source/platform.cpp | b25725999427dd7cfc3ec12672d94425224473d5 | [] | no_license | HenaMakoedov/Arkanoid | 0cf53e1d0054433b7dd4407a33ff63b031652819 | f3346d992feb4e824d49ec4e864871b56510bdaf | refs/heads/master | 2021-01-19T09:28:55.171902 | 2017-02-16T01:03:13 | 2017-02-16T01:03:13 | 82,117,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,178 | cpp | platform.cpp | #include <SFML/Graphics.hpp>
#include "../include/platform.h"
using namespace sf;
extern const String SPRITES;
Platform::Platform()
{
//set the default setting for platform
this->platformImage.loadFromFile(SPRITES);
this->platformTexture.loadFromImage(platformImage);
this->platformSprite.setTexture(platformTexture);
this->platformSprite.setTextureRect(IntRect(0.0,200.0,96.0,28.0));
this->platformSprite.setPosition(252.0,550.0);
}
Sprite Platform::getPlatformSprite()
{
return this->platformSprite;
}
void Platform::moveRight(float time)
{
if(Keyboard::isKeyPressed(Keyboard::Right))
{
//move the platform sprite to the right
this->platformSprite.move( 0.1 * time, 0);
}
}
void Platform::moveLeft(float time)
{
if(Keyboard::isKeyPressed(Keyboard::Left))
{
//move the platform sprite to the left
this->platformSprite.move(-0.1 * time, 0);
}
}
void Platform::move(float time)
{
if (this->collision() == 0)
{
this->moveRight(time);
this->moveLeft(time);
}
if (this->collision() == 1)
{
this->moveLeft(time);
}
if (this->collision() == -1)
{
this->moveRight(time);
}
}
int Platform::collision()
{
//get the coordinate x and width of platform
float x = this->platformSprite.getPosition().x;
float width = this->getPlatformSprite().getTextureRect().width;
// if the platform is located in the right corner of the screen
if (x + width >= 596.0) {return 1;}
// if the platform is located in the left corner of the screen
if (x <= 4.0) {return -1;}
//if the platform is not located in one of corners of the screen
else {return 0;}
}
void Platform::update(RenderWindow& window, float time)
{
//move the platform
this->move(time);
//draw the platform on the screen
window.draw(this->getPlatformSprite());
}
|
89eee9afe9c86641c193be47bda32c4e32b6986a | 94e5a9e157d3520374d95c43fe6fec97f1fc3c9b | /@DOC by DIPTA/collected/sgtlaugh/Mo's Algorithm On Trees (Edges).cpp | d75a5567976f3945b2307ef58fe15409ca34ff6b | [
"MIT"
] | permissive | dipta007/Competitive-Programming | 0127c550ad523884a84eb3ea333d08de8b4ba528 | 998d47f08984703c5b415b98365ddbc84ad289c4 | refs/heads/master | 2021-01-21T14:06:40.082553 | 2020-07-06T17:40:46 | 2020-07-06T17:40:46 | 54,851,014 | 8 | 4 | null | 2020-05-02T13:14:41 | 2016-03-27T22:30:02 | C++ | UTF-8 | C++ | false | false | 3,398 | cpp | Mo's Algorithm On Trees (Edges).cpp | /// Frank Sinatra, Winter Training Camp Moscow SU Trinity Contest
/// Given a weighted tree, find the minimum non-negative value which does not occur in the path from u to v
#include <bits/stdtr1c++.h>
#define MAXN 100010
#define MAXQ 100010
#define MAXV 100010
#define clr(ar) memset(ar, 0, sizeof(ar))
#define read() freopen("lol.txt", "r", stdin)
#define dbg(x) cout << #x << " = " << x << endl
#define ran(a, b) ((((rand() << 15) ^ rand()) % ((b) - (a) + 1)) + (a))
using namespace std;
const int block_size = 633;
typedef pair<int, int> Pair;
namespace mo{ /// Mo's Algorithm on tree(for nodes), 1-based index for nodes and queries
char visited[MAXN];
vector <Pair> adj[MAXN];
int t, q, n, out[MAXQ], dp[MAXV], freq[MAXV], val[MAXN], depth[MAXN], parent[MAXN], discover[MAXN];
struct query{
int l, r, idx;
inline query(){}
inline query(int a, int b, int c){
idx = c;
l = a, r = b;
}
inline bool operator < (const query& other) const{
int d1 = discover[l] / block_size, d2 = discover[other.l] / block_size;
if (d1 != d2) return (d1 < d2);
return ((d1 & 1) ? (discover[r] < discover[other.r]) : (discover[r] > discover[other.r])); /// experiment
}
} Q[MAXQ];
void init(int nodes){
t = q = 0, n = nodes;
for (int i = 0; i < MAXN; i++) adj[i].clear();
}
inline void add_edge(int u, int v, int w){
adj[u].push_back(Pair(v, w));
adj[v].push_back(Pair(u, w));
}
inline void push(int l, int r){
q++;
Q[q] = query(l, r, q);
}
inline void dfs(int i){
discover[i] = ++t;
int j, x, len = adj[i].size();
for (j = 0; j < len; j++){
x = adj[i][j].first;
if (x != parent[i]){
val[x] = adj[i][j].second;
parent[x] = i, depth[x] = depth[i] + 1;
dfs(x);
}
}
}
inline void jump(int& i){
if (!visited[i]){
if (!freq[val[i]]++) dp[val[i] / block_size]++; /// insert
}
else{
if (!--freq[val[i]]) dp[val[i] / block_size]--; /// delete
}
visited[i] ^= 1;
i = parent[i];
}
inline void update(int u, int v){
while (depth[u] > depth[v]) jump(u);
while (depth[u] < depth[v]) jump(v);
while (u != v) jump(u), jump(v);
}
inline void run(){
clr(dp), clr(freq), clr(visited);
parent[1] = 1, depth[1] = 0, Q[0] = query(1, 1, 0);
dfs(1);
sort(Q + 1, Q + q + 1);
for (int i = 1; i <= q; i++){
update(Q[i - 1].l, Q[i].l);
update(Q[i - 1].r, Q[i].r);
int res = 0, pos = 0;
while (dp[pos] == block_size) res += block_size, pos++;
while (freq[res] > 0) res++;
out[Q[i].idx] = res;
}
for (int i = 1; i <= q; i++) printf("%d\n", out[i]);
}
}
int main(){
int n, q, i, j, k, a, b, c;
scanf("%d %d", &n, &q);
mo::init(n);
for (i = 1; i < n; i++){
scanf("%d %d %d", &a, &b, &c);
c = min(c, n + 1); /// Only for this problem since weights can be up to 10^9
mo::add_edge(a, b, c);
}
for (i = 1; i <= q; i++){
scanf("%d %d", &a, &b);
mo::push(a, b);
}
mo::run();
return 0;
}
|
325ea08e01d08fa5e31ee445b5e07719c21829d5 | 00860189fe96c3ede4eefa3080b928eb40f671c2 | /tkrzw_file_test_common.h | 205808c612cdc4c4fef87f107b70d72426e7ed5e | [
"Apache-2.0"
] | permissive | estraier/tkrzw | a22c578fd6cba0068193c45cd8cf513021a5ee75 | 621669b98b5aacd6e24298e5a112b474b1f155e6 | refs/heads/master | 2023-05-11T16:16:39.176335 | 2023-05-05T18:19:40 | 2023-05-05T18:19:40 | 278,320,002 | 152 | 23 | Apache-2.0 | 2023-05-05T10:19:16 | 2020-07-09T09:23:22 | C++ | UTF-8 | C++ | false | false | 25,407 | h | tkrzw_file_test_common.h | /*************************************************************************************************
* Common tests for File implementations
*
* Copyright 2020 Google LLC
* 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
* https://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 "tkrzw_sys_config.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "tkrzw_file.h"
#include "tkrzw_file_util.h"
#include "tkrzw_lib_common.h"
#include "tkrzw_str_util.h"
using namespace testing;
class CommonFileTest : public Test {
protected:
void EmptyFileTest(tkrzw::File* file);
void SmallFileTest(tkrzw::File* file);
void SimpleReadTest(tkrzw::File* file);
void SimpleWriteTest(tkrzw::File* file);
void ReallocWriteTest(tkrzw::File* file);
void TruncateTest(tkrzw::File* file);
void ImplicitCloseTest(tkrzw::File* file);
void SynchronizeTest(tkrzw::File* file);
void OpenOptionsTest(tkrzw::File* file);
void OrderedThreadTest(tkrzw::File* file);
void RandomThreadTest(tkrzw::File* file);
void FileReaderTest(tkrzw::File* file);
void FlatRecordTest(tkrzw::File* file);
void RenameTest(tkrzw::File* file);
};
void CommonFileTest::EmptyFileTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_FALSE(file->IsOpen());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->SetAllocationStrategy(1, 1.2));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_DEFAULT));
EXPECT_TRUE(file->IsOpen());
int64_t file_size = -1;
EXPECT_EQ(tkrzw::Status::SUCCESS, file->GetSize(&file_size));
EXPECT_EQ(0, file_size);
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(0, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_DEFAULT));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->GetSize(&file_size));
EXPECT_EQ(0, file_size);
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(false));
EXPECT_EQ(0, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(0, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, false));
file_size = -1;
EXPECT_EQ(tkrzw::Status::SUCCESS, file->GetSize(&file_size));
EXPECT_EQ(0, file_size);
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(0, tkrzw::GetFileSize(file_path));
auto tmp_file = file->MakeFile();
EXPECT_EQ(file->GetType(), tmp_file->GetType());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->CopyProperties(tmp_file.get()));
EXPECT_EQ(tkrzw::Status::SUCCESS, tmp_file->Open(file_path, true, tkrzw::File::OPEN_TRUNCATE));
EXPECT_EQ(tkrzw::Status::SUCCESS, tmp_file->Close());
}
void CommonFileTest::SmallFileTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->SetAllocationStrategy(0, 0));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_DEFAULT));
std::string total_data;
for (int32_t i = 0; i < 20; i++) {
const std::string data(i % 3 + 1, 'a' + i % 3);
if (i % 2 == 0) {
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Write(total_data.size(), data.data(), data.size()));
} else {
int64_t new_off = 0;
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append(data.data(), data.size(), &new_off));
EXPECT_EQ(total_data.size(), new_off);
}
total_data += data;
if (file->IsMemoryMapping()) {
EXPECT_EQ(tkrzw::AlignNumber(total_data.size(), tkrzw::PAGE_SIZE),
tkrzw::GetFileSize(file_path));
} else {
EXPECT_EQ(total_data.size(), tkrzw::GetFileSize(file_path));
}
char buf[5];
EXPECT_EQ(tkrzw::Status::SUCCESS,
file->Read(total_data.size() - data.size(), buf, data.size()));
EXPECT_EQ(data, std::string_view(buf, data.size()));
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(total_data.size(), tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_DEFAULT));
char buf[8192];
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(0, buf, total_data.size()));
EXPECT_EQ(total_data, std::string_view(buf, total_data.size()));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Truncate(5));
if (file->IsMemoryMapping()) {
EXPECT_EQ(tkrzw::PAGE_SIZE, tkrzw::GetFileSize(file_path));
} else {
EXPECT_EQ(5, tkrzw::GetFileSize(file_path));
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(5, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->SetAllocationStrategy(1, 2));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_DEFAULT));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Write(0, "0123456789", 10));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(0, buf, 10));
EXPECT_EQ("0123456789", std::string_view(buf, 10));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Truncate(5));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(false));
EXPECT_EQ(5, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(5, tkrzw::GetFileSize(file_path));
}
void CommonFileTest::SimpleReadTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, tkrzw::WriteFile(file_path, "0123456789"));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, false));
char buf[10];
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(0, buf, 10));
EXPECT_EQ("0123456789", std::string(buf, 10));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(5, buf, 3));
EXPECT_EQ("567", std::string(buf, 3));
EXPECT_EQ("567", file->ReadSimple(5, 3));
EXPECT_EQ(tkrzw::Status::INFEASIBLE_ERROR, file->Read(11, buf, 3));
EXPECT_EQ(tkrzw::Status::INFEASIBLE_ERROR, file->Read(9, buf, 3));
EXPECT_EQ("", file->ReadSimple(11, 3));
EXPECT_EQ("", file->ReadSimple(9, 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
void CommonFileTest::SimpleWriteTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true));
int64_t off = -1;
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("01234", 5, &off));
EXPECT_EQ(0, off);
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("56789", 5, &off));
EXPECT_EQ(5, off);
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Write(3, "XYZ", 3));
EXPECT_TRUE(file->WriteSimple(8, "ABCDEF"));
EXPECT_EQ(14, file->AppendSimple("GHI"));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Expand(2, &off));
EXPECT_EQ(17, off);
EXPECT_EQ(19, file->ExpandSimple(2));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Write(off, "JKLMN", 5));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
std::string content;
EXPECT_EQ(tkrzw::Status::SUCCESS, tkrzw::ReadFile(file_path, &content));
EXPECT_EQ("012XYZ67ABCDEFGHIJKLMN", content);
}
void CommonFileTest::ReallocWriteTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->SetAllocationStrategy(1, 1.2));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true));
for (int32_t i = 0; i < 10000; i++) {
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("0123456789", 10));
}
int64_t size = 0;
EXPECT_EQ(tkrzw::Status::SUCCESS, file->GetSize(&size));
EXPECT_EQ(100000, size);
EXPECT_EQ(100000, file->GetSizeSimple());
for (int32_t i = 0; i < 10000; i++) {
char buf[10];
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(i * 10, buf, 10));
EXPECT_EQ("0123456789", std::string(buf, 10));
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(100000, tkrzw::GetFileSize(file_path));
}
void CommonFileTest::TruncateTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->SetAllocationStrategy(1, 1.2));
char buf[256];
int64_t offset = 0;
EXPECT_EQ(tkrzw::Status::SUCCESS,
file->Open(file_path, true, tkrzw::File::OPEN_TRUNCATE));
EXPECT_EQ(0, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Truncate(8192));
EXPECT_EQ(8192, file->GetSizeSimple());
file->Read(4096, buf, 3);
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("abc", 3, &offset));
EXPECT_EQ(8192, offset);
EXPECT_EQ(8195, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(8192, buf, 3));
EXPECT_EQ("abc", std::string_view(buf, 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Truncate(1024));
EXPECT_EQ(1024, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("abc", 3, &offset));
EXPECT_EQ(1027, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(1024, buf, 3));
EXPECT_EQ("abc", std::string_view(buf, 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(1027, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS,
file->Open(file_path, true, tkrzw::File::OPEN_TRUNCATE));
EXPECT_EQ(0, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Truncate(65536));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->TruncateFakely(8192));
EXPECT_EQ(8192, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(4096, buf, 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("abc", 3, &offset));
EXPECT_EQ(8192, offset);
EXPECT_EQ(8195, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(8192, buf, 3));
EXPECT_EQ("abc", std::string_view(buf, 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->TruncateFakely(1024));
EXPECT_EQ(1024, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("abc", 3, &offset));
EXPECT_EQ(1027, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(1024, buf, 3));
EXPECT_EQ("abc", std::string_view(buf, 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(1027, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, false));
EXPECT_EQ(1027, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(1024, buf, 3));
EXPECT_EQ("abc", std::string_view(buf, 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->TruncateFakely(512));
EXPECT_EQ(512, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::INFEASIBLE_ERROR, file->TruncateFakely(65536));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
void CommonFileTest::SynchronizeTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->SetAllocationStrategy(1, 1.2));
char buf[1024];
std::memset(buf, 0, std::size(buf));
EXPECT_EQ(tkrzw::Status::SUCCESS,
file->Open(file_path, true, tkrzw::File::OPEN_TRUNCATE));
for (int32_t i = 0; i < 8; i++) {
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append(buf, std::size(buf)));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append(buf, std::size(buf)));
}
const int64_t file_size = file->GetSizeSimple();
for (int64_t off = 0; off < file_size; off += 256) {
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(true, off, 256));
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(true, 0, 0));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(true, 1, 0));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(true, 0, 8192));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(true, 8192, 0));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
void CommonFileTest::ImplicitCloseTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
{
auto tmp_file = file->MakeFile();
EXPECT_EQ(tkrzw::Status::SUCCESS, tmp_file->Open(file_path, true));
EXPECT_EQ(tkrzw::Status::SUCCESS, tmp_file->Append("0123456789", 10));
}
EXPECT_EQ(10, tkrzw::GetFileSize(file_path));
}
void CommonFileTest::OpenOptionsTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::NOT_FOUND_ERROR,
file->Open(file_path, true, tkrzw::File::OPEN_NO_CREATE));
EXPECT_EQ(tkrzw::Status::SUCCESS, tkrzw::WriteFile(file_path, "abc"));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_NO_CREATE));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_NO_LOCK));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("def", 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(6, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_NO_WAIT));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("efg", 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(9, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_TRUNCATE));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(0, tkrzw::GetFileSize(file_path));
}
void CommonFileTest::OrderedThreadTest(tkrzw::File* file) {
constexpr int32_t num_threads = 10;
constexpr int32_t num_iterations = 10000;
constexpr int32_t record_size = 128;
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->SetAllocationStrategy(1, 1.2));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true));
auto write_func = [&](int32_t id) {
char* write_buf = new char[record_size];
std::memset(write_buf, '0' + id, record_size);
char* read_buf = new char[record_size];
std::memset(read_buf, 0, record_size);
for (int32_t i = 0; i < num_iterations; i++) {
const int32_t off = (i * num_threads + id) * record_size;
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Write(off, write_buf, record_size));
if (i % 2 == 0) {
std::this_thread::yield();
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(off, read_buf, record_size));
EXPECT_EQ(0, std::memcmp(read_buf, write_buf, record_size));
}
delete[] read_buf;
delete[] write_buf;
};
std::vector<std::thread> write_threads;
for (int32_t i = 0; i < num_threads; i++) {
write_threads.emplace_back(std::thread(write_func, i));
}
for (auto& write_thread : write_threads) {
write_thread.join();
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
EXPECT_EQ(num_iterations * num_threads * record_size, tkrzw::GetFileSize(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, false));
auto read_func = [&](int32_t id) {
char* expected_buf = new char[record_size];
std::memset(expected_buf, '0' + id, record_size);
char* read_buf = new char[record_size];
std::memset(read_buf, 0, record_size);
for (int32_t i = 0; i < num_iterations; i++) {
const int32_t off = (i * num_threads + id) * record_size;
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Read(off, read_buf, record_size));
EXPECT_EQ(0, std::memcmp(read_buf, expected_buf, record_size));
}
delete[] read_buf;
delete[] expected_buf;
};
std::vector<std::thread> read_threads;
for (int32_t i = 0; i < num_threads; i++) {
read_threads.emplace_back(std::thread(read_func, i));
}
for (auto& read_thread : read_threads) {
read_thread.join();
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
void CommonFileTest::RandomThreadTest(tkrzw::File* file) {
constexpr int32_t num_threads = 10;
constexpr int32_t num_iterations = 10000;
constexpr int32_t file_size = 100000;
constexpr int32_t record_size = 256;
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->SetAllocationStrategy(1, 1.2));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true));
auto func = [&](int32_t seed) {
std::mt19937 mt(seed);
std::uniform_int_distribution<int32_t> op_dist(0, 4);
std::uniform_int_distribution<int32_t> write_buf_dist(0, 1);
std::uniform_int_distribution<int32_t> off_dist(0, file_size - 1);
std::uniform_int_distribution<int32_t> append_dist(0, 4);
std::uniform_int_distribution<int32_t> size_dist(0, record_size);
std::uniform_int_distribution<int32_t> sync_dist(0, num_iterations - 1);
std::uniform_int_distribution<int32_t> trunc_dist(0, num_iterations - 1);
char* write_buf = new char[record_size];
std::memset(write_buf, '0' + seed, record_size);
char* read_buf = new char[record_size];
std::memcpy(read_buf, write_buf, record_size);
for (int32_t i = 0; i < num_iterations; i++) {
int32_t off = off_dist(mt);
const int32_t size = std::min(size_dist(mt), file_size - off);
if (file->IsAtomic() && trunc_dist(mt) == 0) {
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Truncate(off));
} else if (file->IsAtomic() && sync_dist(mt) == 0) {
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(true));
} else if (op_dist(mt) == 0) {
const char* buf = write_buf_dist(mt) == 0 ? write_buf : read_buf;
if (append_dist(mt) == 0) {
int64_t new_off = -1;
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append(buf, size, &new_off));
EXPECT_GE(new_off, 0);
} else {
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Write(off, buf, size));
}
} else {
const tkrzw::Status status = file->Read(off, read_buf, size);
EXPECT_TRUE(status == tkrzw::Status::SUCCESS ||
status == tkrzw::Status::INFEASIBLE_ERROR);
}
}
delete[] read_buf;
delete[] write_buf;
};
std::vector<std::thread> threads;
for (int32_t i = 0; i < num_threads; i++) {
threads.emplace_back(std::thread(func, i));
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
void CommonFileTest::FileReaderTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
{
EXPECT_EQ(tkrzw::Status::SUCCESS, tkrzw::WriteFile(file_path, "1\n22\n333\n"));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, false));
tkrzw::FileReader reader(file);
std::string line;
EXPECT_EQ(tkrzw::Status::SUCCESS, reader.ReadLine(&line));
EXPECT_EQ("1\n", line);
EXPECT_EQ(tkrzw::Status::SUCCESS, reader.ReadLine(&line));
EXPECT_EQ("22\n", line);
EXPECT_EQ(tkrzw::Status::SUCCESS, reader.ReadLine(&line));
EXPECT_EQ("333\n", line);
EXPECT_EQ(tkrzw::Status::NOT_FOUND_ERROR, reader.ReadLine(&line));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
{
EXPECT_EQ(tkrzw::Status::SUCCESS, tkrzw::WriteFile(file_path, "1\n\n22"));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, false));
tkrzw::FileReader reader(file);
std::string line;
EXPECT_EQ(tkrzw::Status::SUCCESS, reader.ReadLine(&line));
EXPECT_EQ("1\n", line);
EXPECT_EQ(tkrzw::Status::SUCCESS, reader.ReadLine(&line));
EXPECT_EQ("\n", line);
EXPECT_EQ(tkrzw::Status::SUCCESS, reader.ReadLine(&line));
EXPECT_EQ("22", line);
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
{
std::string expected_line(99, 'x');
expected_line.append(1, '\n');
std::string content;
for (int32_t i = 0; i < 100; i++) {
content.append(expected_line);
}
EXPECT_EQ(tkrzw::Status::SUCCESS, tkrzw::WriteFile(file_path, content));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, false));
tkrzw::FileReader reader(file);
for (int32_t i = 0; i < 100; i++) {
std::string line;
EXPECT_EQ(tkrzw::Status::SUCCESS, reader.ReadLine(&line));
EXPECT_EQ(expected_line, line);
}
std::string line;
EXPECT_EQ(tkrzw::Status::NOT_FOUND_ERROR, reader.ReadLine(&line));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
}
void CommonFileTest::FlatRecordTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true));
const std::vector<int32_t> data_sizes = {
0, 1, 2, 4, 8, 15, 16, 17, 30, 31, 32, 33, 62, 63, 64, 65, 126, 127, 128, 129,
254, 255, 256, 257, 16384, 16385, 16386, 16387, 32766, 32767, 32768, 32769,
0, 32769, 1, 32769, 2, 32767, 4, 32766, 8, 16387, 15, 16386, 16, 16385, 17, 16384,
30, 257, 31, 256, 32, 255, 33, 254, 129, 62, 128, 63, 127, 64, 126};
std::vector<size_t> reader_buffer_sizes;
for (size_t size = 8; size <= 65536; size = size * 1.1 + 1) {
reader_buffer_sizes.emplace_back(size);
}
reader_buffer_sizes.emplace_back(0);
tkrzw::FlatRecord rec(file);
for (size_t i = 0; i < data_sizes.size(); i++) {
const auto& data_size = data_sizes[i];
std::string data(data_size, 'v');
if (data_size > 0) {
data.front() = 'A';
}
if (data_size > 1) {
data.back() = 'Z';
}
const tkrzw::FlatRecord::RecordType rec_type =
i % 2 == 0 ? tkrzw::FlatRecord::RECORD_NORMAL : tkrzw::FlatRecord::RECORD_METADATA;
EXPECT_EQ(tkrzw::Status::SUCCESS, rec.Write(data, rec_type));
const int64_t offset = rec.GetOffset();
EXPECT_EQ(tkrzw::Status::SUCCESS, rec.Read(offset));
EXPECT_EQ(data, rec.GetData());
EXPECT_EQ(rec_type, rec.GetRecordType());
}
const int64_t end_offset = file->GetSizeSimple();
int64_t offset = 0;
size_t index = 0;
while (offset < end_offset) {
EXPECT_EQ(tkrzw::Status::SUCCESS, rec.Read(offset));
std::string data(data_sizes[index], 'v');
if (data.size() > 0) {
data.front() = 'A';
}
if (data.size() > 1) {
data.back() = 'Z';
}
EXPECT_EQ(data, rec.GetData());
if (index % 2 == 0) {
EXPECT_EQ(tkrzw::FlatRecord::RECORD_NORMAL, rec.GetRecordType());
} else {
EXPECT_EQ(tkrzw::FlatRecord::RECORD_METADATA, rec.GetRecordType());
}
offset += rec.GetWholeSize();
index++;
}
EXPECT_EQ(data_sizes.size(), index);
for (const size_t reader_buffer_size : reader_buffer_sizes) {
std::vector<int32_t> actual_sizes;
tkrzw::FlatRecordReader reader(file, reader_buffer_size);
while (true) {
std::string_view data;
tkrzw::FlatRecord::RecordType rec_type;
const tkrzw::Status status = reader.Read(&data, &rec_type);
if (status != tkrzw::Status::SUCCESS) {
EXPECT_EQ(tkrzw::Status::NOT_FOUND_ERROR, status);
break;
}
if (data.size() > 0) {
EXPECT_EQ('A', data.front());
}
if (data.size() > 1) {
EXPECT_EQ('Z', data.back());
}
if (actual_sizes.size() % 2 == 0) {
EXPECT_EQ(tkrzw::FlatRecord::RECORD_NORMAL, rec_type);
} else {
EXPECT_EQ(tkrzw::FlatRecord::RECORD_METADATA, rec_type);
}
actual_sizes.emplace_back(data.size());
}
EXPECT_THAT(actual_sizes, ElementsAreArray(data_sizes));
}
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
void CommonFileTest::RenameTest(tkrzw::File* file) {
tkrzw::TemporaryDirectory tmp_dir(true, "tkrzw-");
const std::string file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Open(file_path, true, tkrzw::File::OPEN_TRUNCATE));
EXPECT_EQ(file_path, file->GetPathSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Truncate(5));
EXPECT_EQ(5, file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Synchronize(false));
const std::string rename_file_path = tmp_dir.MakeUniquePath();
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Rename(rename_file_path));
auto rename_file = file->MakeFile();
EXPECT_EQ(tkrzw::Status::NOT_FOUND_ERROR, rename_file->Open(file_path, false));
EXPECT_EQ(tkrzw::Status::SUCCESS, rename_file->Open(rename_file_path, false));
EXPECT_EQ(rename_file_path, rename_file->GetPathSimple());
EXPECT_EQ(5, rename_file->GetSizeSimple());
EXPECT_EQ(tkrzw::Status::SUCCESS, rename_file->Close());
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Append("abc", 3));
EXPECT_EQ(8, file->GetSizeSimple());
EXPECT_EQ("abc", file->ReadSimple(5, 3));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->DisablePathOperations());
std::string found_path;
EXPECT_EQ(tkrzw::Status::PRECONDITION_ERROR, file->GetPath(&found_path));
EXPECT_EQ(tkrzw::Status::PRECONDITION_ERROR, file->Rename(file_path));
EXPECT_EQ(tkrzw::Status::SUCCESS, file->Close());
}
// END OF FILE
|
475974b2acd8d9a19982c7b4a47207645cc3b980 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/mpl/advance_fwd.hpp | 2d8ec71b11cde4c85120f60416d54c981504e8d7 | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | hpp | advance_fwd.hpp | version https://git-lfs.github.com/spec/v1
oid sha256:8d6acc3e465cbb29e8e45dc7ce490e3b9d0109939d2807d751bba194ca375bf1
size 660
|
012accdb19cfffd20212d48fc942e6b8b3b6124c | 01dad38fa2b2d0aa4734c3b535321216e6c8f0e0 | /engine/quake.cpp | c17612b5d9c352288757d4d30e038870bf322717 | [] | no_license | study-game-engines/lamorna | 4b74e35504411a208fb460afc50b4debb3acaa29 | 73f01bdaafe2a5716bd3a4d4ee00c0806f902c48 | refs/heads/master | 2023-05-14T10:07:11.508902 | 2018-11-21T22:17:56 | 2018-11-21T22:17:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,276 | cpp | quake.cpp |
#include "quake.h"
#include "vector.h"
#include "texture.h"
#include "model.h"
#include "memory.h"
#include "string.h"
struct uchar3 {
unsigned char channel[3];
};
uchar3 colour_map[] = {
{ 0, 0, 0}, { 15, 15, 15 }, { 31, 31, 31 }, { 47, 47, 47 },
{ 63, 63, 63 }, { 75, 75, 75 }, { 91, 91, 91 }, { 107, 107, 107 },
{ 123, 123, 123 }, { 139, 139, 139 }, { 155, 155, 155 }, { 171, 171, 171 },
{ 187, 187, 187 }, { 203, 203, 203 }, { 219, 219, 219 }, { 235, 235, 235 },
{ 15, 11, 7 }, { 23, 15, 11 }, { 31, 23, 11 }, { 39, 27, 15 },
{ 47, 35, 19 }, { 55, 43, 23 }, { 63, 47, 23 }, { 75, 55, 27 },
{ 83, 59, 27 }, { 91, 67, 31 }, { 99, 75, 31 }, { 107, 83, 31 },
{ 115, 87, 31 }, { 123, 95, 35 }, { 131, 103, 35 }, { 143, 111, 35 },
{ 11, 11, 15 }, { 19, 19, 27 }, { 27, 27, 39 }, { 39, 39, 51 },
{ 47, 47, 63 }, { 55, 55, 75 }, { 63, 63, 87 }, { 71, 71, 103 },
{ 79, 79, 115 }, { 91, 91, 127 }, { 99, 99, 139 }, { 107, 107, 151 },
{ 115, 115, 163 }, { 123, 123, 175 }, { 131, 131, 187 }, { 139, 139, 203 },
{ 0, 0, 0 }, { 7, 7, 0 }, { 11, 11, 0 }, { 19, 19, 0 },
{ 27, 27, 0 }, { 35, 35, 0 }, { 43, 43, 7 }, { 47, 47, 7 },
{ 55, 55, 7 }, { 63, 63, 7 }, { 71, 71, 7 }, { 75, 75, 11 },
{ 83, 83, 11 }, { 91, 91, 11 }, { 99, 99, 11 }, { 107, 107, 15 },
{ 7, 0, 0 }, { 15, 0, 0 }, { 23, 0, 0 }, { 31, 0, 0 },
{ 39, 0, 0 }, { 47, 0, 0 }, { 55, 0, 0 }, { 63, 0, 0 },
{ 71, 0, 0 }, { 79, 0, 0 }, { 87, 0, 0 }, { 95, 0, 0 },
{ 103, 0, 0 }, { 111, 0, 0 }, { 119, 0, 0 }, { 127, 0, 0 },
{ 19, 19, 0 }, { 27, 27, 0 }, { 35, 35, 0 }, { 47, 43, 0 },
{ 55, 47, 0 }, { 67, 55, 0 }, { 75, 59, 7 }, { 87, 67, 7 },
{ 95, 71, 7 }, { 107, 75, 11 }, { 119, 83, 15 }, { 131, 87, 19 },
{ 139, 91, 19 }, { 151, 95, 27 }, { 163, 99, 31 }, { 175, 103, 35 },
{ 35, 19, 7 }, { 47, 23, 11 }, { 59, 31, 15 }, { 75, 35, 19 },
{ 87, 43, 23 }, { 99, 47, 31 }, { 115, 55, 35 }, { 127, 59, 43 },
{ 143, 67, 51 }, { 159, 79, 51 }, { 175, 99, 47 }, { 191, 119, 47 },
{ 207, 143, 43 }, { 223, 171, 39 }, { 239, 203, 31 }, { 255, 243, 27 },
{ 11, 7, 0 }, { 27, 19, 0 }, { 43, 35, 15 }, { 55, 43, 19 },
{ 71, 51, 27 }, { 83, 55, 35 }, { 99, 63, 43 }, { 111, 71, 51 },
{ 127, 83, 63 }, { 139, 95, 71 }, { 155, 107, 83 }, { 167, 123, 95 },
{ 183, 135, 107 }, { 195, 147, 123 }, { 211, 163, 139 }, { 227, 179, 151 },
{ 171, 139, 163 }, { 159, 127, 151 }, { 147, 115, 135 }, { 139, 103, 123 },
{ 127, 91, 111 }, { 119, 83, 99 }, { 107, 75, 87 }, { 95, 63, 75 },
{ 87, 55, 67 }, { 75, 47, 55 }, { 67, 39, 47 }, { 55, 31, 35 },
{ 43, 23, 27 }, { 35, 19, 19 }, { 23, 11, 11 }, { 15, 7, 7 },
{ 187, 115, 159 }, { 175, 107, 143 }, { 163, 95, 131 }, { 151, 87, 119 },
{ 139, 79, 107 }, { 127, 75, 95 }, { 115, 67, 83 }, { 107, 59, 75 },
{ 95, 51, 63 }, { 83, 43, 55 }, { 71, 35, 43 }, { 59, 31, 35 },
{ 47, 23, 27 }, { 35, 19, 19 }, { 23, 11, 11 }, { 15, 7, 7 },
{ 219, 195, 187 }, { 203, 179, 167 }, { 191, 163, 155 }, { 175, 151, 139 },
{ 163, 135, 123 }, { 151, 123, 111 }, { 135, 111, 95 }, { 123, 99, 83 },
{ 107, 87, 71 }, { 95, 75, 59 }, { 83, 63, 51 }, { 67, 51, 39 },
{ 55, 43, 31 }, { 39, 31, 23 }, { 27, 19, 15 }, { 15, 11, 7 },
{ 111, 131, 123 }, { 103, 123, 111 }, { 95, 115, 103 }, { 87, 107, 95 },
{ 79, 99, 87 }, { 71, 91, 79 }, { 63, 83, 71 }, { 55, 75, 63 },
{ 47, 67, 55 }, { 43, 59, 47 }, { 35, 51, 39 }, { 31, 43, 31 },
{ 23, 35, 23 }, { 15, 27, 19 }, { 11, 19, 11 }, { 7, 11, 7 },
{ 255, 243, 27 }, { 239, 223, 23 }, { 219, 203, 19 }, { 203, 183, 15 },
{ 187, 167, 15 }, { 171, 151, 11 }, { 155, 131, 7 }, { 139, 115, 7 },
{ 123, 99, 7 }, { 107, 83, 0 }, { 91, 71, 0 }, { 75, 55, 0 },
{ 59, 43, 0 }, { 43, 31, 0 }, { 27, 15, 0 }, { 11, 7, 0 },
{ 0, 0, 255 }, { 11, 11, 239 }, { 19, 19, 223 }, { 27, 27, 207 },
{ 35, 35, 191 }, { 43, 43, 175 }, { 47, 47, 159 }, { 47, 47, 143 },
{ 47, 47, 127 }, { 47, 47, 111 }, { 47, 47, 95 }, { 43, 43, 79 },
{ 35, 35, 63 }, { 27, 27, 47 }, { 19, 19, 31 }, { 11, 11, 15 },
{ 43, 0, 0 }, { 59, 0, 0 }, { 75, 7, 0 }, { 95, 7, 0 },
{ 111, 15, 0 }, { 127, 23, 7 }, { 147, 31, 7 }, { 163, 39, 11 },
{ 183, 51, 15 }, { 195, 75, 27 }, { 207, 99, 43 }, { 219, 127, 59 },
{ 227, 151, 79 }, { 231, 171, 95 }, { 239, 191, 119 }, { 247, 211, 139 },
{ 167, 123, 59 }, { 183, 155, 55 }, { 199, 195, 55 }, { 231, 227, 87 },
{ 127, 191, 255 }, { 171, 231, 255 }, { 215, 255, 255 }, { 103, 0, 0 },
{ 139, 0, 0 }, { 179, 0, 0 }, { 215, 0, 0 }, { 255, 0, 0 },
{ 255, 243, 147 }, { 255, 247, 199 }, { 255, 255, 255 }, { 159, 91, 83 }
};
//======================================================================
typedef float vec3_t[3];
struct mdl_header_t
{
__int32 ident; /* magic number: "IDPO" */
__int32 version; /* version: 6 */
vec3_t scale; /* scale factor */
vec3_t translate; /* translation vector */
float boundingradius;
vec3_t eyeposition; /* eyes' position */
__int32 num_skins; /* number of textures */
__int32 skinwidth; /* texture width */
__int32 skinheight; /* texture height */
__int32 num_verts; /* number of vertices */
__int32 num_tris; /* number of triangles */
__int32 num_frames; /* number of frames */
__int32 synctype; /* 0 = synchron, 1 = random */
__int32 flags; /* state flag */
float size;
};
struct mdl_skin_t
{
__int32 group; /* 0 = single, 1 = group */
unsigned char *data; /* texture data */
};
struct mdl_texcoord_t
{
__int32 onseam;
__int32 s;
__int32 t;
};
struct mdl_triangle_t
{
__int32 facesfront; /* 0 = backface, 1 = frontface */
__int32 vertex[3]; /* vertex indices */
};
/* Compressed vertex */
struct mdl_vertex_t
{
unsigned char v[3];
unsigned char normalIndex;
};
/* Simple frame */
struct mdl_simpleframe_t
{
struct mdl_vertex_t bboxmin; /* bouding box min */
struct mdl_vertex_t bboxmax; /* bouding box max */
char name[16];
struct mdl_vertex_t *verts; /* vertex list of the frame */
};
/* Group of simple frames */
struct mdl_groupframe_t
{
__int32 type; /* !0 = group */
struct mdl_vertex_t min; /* min pos in all simple frames */
struct mdl_vertex_t max; /* max pos in all simple frames */
float *time; /* time duration for each frame */
struct mdl_simpleframe_t *frames; /* simple frame list */
};
/* Model frame */
struct mdl_frame_t
{
__int32 type; /* 0 = simple, !0 = group */
struct mdl_simpleframe_t frame; /* this program can't read models
composed of group frames! */
};
struct quake_mdl_ {
enum {
MAX_VERTICES = 1024,
MAX_TRIANGLES = 2048,
MAX_SKIN_SIZE = 1024 * 1024,
};
unsigned char colour_indices[MAX_SKIN_SIZE];
mdl_header_t file_header;
mdl_triangle_t triangles[MAX_TRIANGLES];
mdl_texcoord_t texture_coordinates[MAX_VERTICES];
};
/*
==================
==================
*/
void Vertices_Max_Min(
const float3_ vertices[],
const __int32 n_vertices,
float3_& max_out,
float3_& min_out
)
{
__m128 max[4];
__m128 min[4];
for (__int32 i_axis = X; i_axis < W; i_axis++) {
max[i_axis] = min[i_axis] = set_all(vertices[0].f[i_axis]);
}
for (__int32 i_vertex_4 = 0; i_vertex_4 < n_vertices; i_vertex_4 += 4) {
__int32 n = min(n_vertices - i_vertex_4, 4);
__m128 vertex[4];
for (__int32 i_vertex = 0; i_vertex < n; i_vertex++) {
vertex[i_vertex] = load_u(vertices[i_vertex_4 + i_vertex].f);
}
Transpose(vertex);
for (__int32 i = X; i < W; i++) {
max[i] = max_vec(max[i], vertex[i]);
min[i] = min_vec(min[i], vertex[i]);
}
}
Transpose(max);
Transpose(min);
for (__int32 i = Y; i < W; i++) {
max[X] = max_vec(max[i], max[X]);
min[X] = min_vec(min[i], min[X]);
}
float temp_max[4];
store_u(max[X], temp_max);
float temp_min[4];
store_u(min[X], temp_min);
for (__int32 i_axis = X; i_axis < W; i_axis++) {
max_out.f[i_axis] = temp_max[i_axis];
min_out.f[i_axis] = temp_min[i_axis];
}
}
/*
==================
==================
*/
void Model_Centre_Extent(
const float3_ vertices[],
const __int32 n_vertices,
float3_& centre,
float3_& extent
)
{
float3_ max;
float3_ min;
Vertices_Max_Min(vertices, n_vertices, max, min);
const float half = 0.5f;
for (__int32 i = X; i < W; i++) {
centre.f[i] = (max.f[i] + min.f[i]) * half;
extent.f[i] = (max.f[i] - min.f[i]) * half;
}
}
/*
==================
==================
*/
void Load_Quake_Model(
const __int8* file_name_model,
const __int32 i_skin_select,
model_& model,
memory_chunk_& memory
)
{
quake_mdl_* quake_mdl = new quake_mdl_;
FILE *file_handle = NULL;
fopen_s(&file_handle, file_name_model, "rb");
if (file_handle == NULL) {
printf_s("FAILED to open %s \n", file_name_model);
exit(0);
}
else{
printf_s("opened %s \n", file_name_model);
}
// ----------------------------------------------------------------------------------------------------------
// read file header
fread(&quake_mdl->file_header, sizeof(mdl_header_t), 1, file_handle);
//printf_s("ID STRING: %i \n", quake_mdl->file_header.ident);
//printf_s("VERSION: %i \n", quake_mdl->file_header.version);
//printf_s("NUM SKINS: %i \n", quake_mdl->file_header.num_skins);
//printf_s("SKIN SIZE: %i \n", quake_mdl->file_header.skinheight * quake_mdl->file_header.skinwidth);
//printf_s("NUM VERTS: %i \n", quake_mdl->file_header.num_verts);
//printf_s("NUM TRIS: %i \n", quake_mdl->file_header.num_tris);
//printf_s("NUM FRAMES: %i \n", quake_mdl->file_header.num_frames);
// ----------------------------------------------------------------------------------------------------------
{
const __int32 skin_size = quake_mdl->file_header.skinheight * quake_mdl->file_header.skinwidth;
__int32 num_bits_height = _mm_popcnt_u32(quake_mdl->file_header.skinheight);
__int32 num_bits_width = _mm_popcnt_u32(quake_mdl->file_header.skinwidth);
//assert((num_bits_height == 1) && (num_bits_width == 1)); // pow2 tex
assert(skin_size < quake_mdl_::MAX_SKIN_SIZE);
assert(quake_mdl->file_header.num_verts < quake_mdl_::MAX_VERTICES);
assert(quake_mdl->file_header.num_tris < quake_mdl_::MAX_TRIANGLES);
//texture_attribute_& texture_attribute = texture_manager.attributes[texture_manager.n_textures];
//texture_attribute.id = texture_id;
//texture_attribute.texture[0] = (unsigned __int32*)memory.chunk_ptr;
model.n_textures = 2; // allow for 2ndary textures by default
model.texture_handlers = (texture_handler_*)memory.chunk_ptr;
memory.chunk_ptr = model.texture_handlers + model.n_textures;
unsigned long width_shift = 0;
_BitScanForward(&width_shift, quake_mdl->file_header.skinwidth);
unsigned long height_shift = 0;
_BitScanForward(&height_shift, quake_mdl->file_header.skinheight);
for (__int32 i_texture = 0; i_texture < model.n_textures; i_texture++) {
model.texture_handlers[i_texture].height = quake_mdl->file_header.skinheight;
model.texture_handlers[i_texture].width = quake_mdl->file_header.skinwidth;
model.texture_handlers[i_texture].width_shift = width_shift;
model.texture_handlers[i_texture].height_shift = height_shift;
}
model.texture_handlers[0].texture[0] = (unsigned __int32*)memory.chunk_ptr;
model.texture_handlers[1].texture[0] = model.texture_handlers[0].texture[0];
//printf_s("width: %i, height: %i \n", quake_mdl->file_header.skinheight, quake_mdl->file_header.skinwidth);
for (__int32 i_skin = 0; i_skin < quake_mdl->file_header.num_skins; i_skin++){
mdl_skin_t skin_header;
fread(&skin_header.group, sizeof(__int32), 1, file_handle);
fread(quake_mdl->colour_indices, 1, skin_size, file_handle);
if (i_skin_select == i_skin) {
for (__int32 i_index = 0; i_index < skin_size; i_index++) {
unsigned char colour_index = quake_mdl->colour_indices[i_index];
unsigned char r = colour_map[colour_index].channel[R];
unsigned char g = colour_map[colour_index].channel[G];
unsigned char b = colour_map[colour_index].channel[B];
unsigned __int32 final_colour = b | (g << 8) | (r << 16);
model.texture_handlers[0].texture[0][i_index] = final_colour;
}
}
}
memory.chunk_ptr = model.texture_handlers[0].texture[0] + (quake_mdl->file_header.skinheight * quake_mdl->file_header.skinwidth);
Build_MIP_Map_Chain(model.texture_handlers[0], memory);
}
// ----------------------------------------------------------------------------------------------------------
/* Texture coords */
{
fread(&quake_mdl->texture_coordinates, sizeof(mdl_texcoord_t), quake_mdl->file_header.num_verts, file_handle);
}
// ----------------------------------------------------------------------------------------------------------
/* Triangle info */
{
fread(&quake_mdl->triangles, sizeof(mdl_triangle_t), quake_mdl->file_header.num_tris, file_handle);
}
// ----------------------------------------------------------------------------------------------------------
{
}
// ----------------------------------------------------------------------------------------------------------
{
{
model.frame_origin = (float3_*)memory.chunk_ptr;
memory.chunk_ptr = model.frame_origin + quake_mdl->file_header.num_frames;
model.frame_extent = (float3_*)memory.chunk_ptr;
memory.chunk_ptr = model.frame_extent + quake_mdl->file_header.num_frames;
}
{
model.frame_name = (char(*)[16])memory.chunk_ptr;
memory.chunk_ptr = model.frame_name + quake_mdl->file_header.num_frames;
}
{
model.vertices_frame = (float3_**)memory.chunk_ptr;
memory.chunk_ptr = model.vertices_frame + quake_mdl->file_header.num_frames;
for (__int32 i_frame = 0; i_frame < quake_mdl->file_header.num_frames; i_frame++) {
model.vertices_frame[i_frame] = (float3_*)memory.chunk_ptr;
memory.chunk_ptr = model.vertices_frame[i_frame] + quake_mdl->file_header.num_verts;
}
}
model.translate.x = quake_mdl->file_header.translate[X];
model.translate.y = quake_mdl->file_header.translate[Y];
model.translate.z = quake_mdl->file_header.translate[Z];
//__int32 i_vertex_write = 0;
for (__int32 i_frame = 0; i_frame < quake_mdl->file_header.num_frames; i_frame++){
mdl_frame_t frame_node;
fread(&frame_node.type, sizeof(__int32), 1, file_handle);
fread(&frame_node.frame.bboxmin, sizeof(mdl_vertex_t), 1, file_handle);
fread(&frame_node.frame.bboxmax, sizeof(mdl_vertex_t), 1, file_handle);
fread(&frame_node.frame.name, sizeof(char), 16, file_handle);
string_copy(frame_node.frame.name, model.frame_name[i_frame]);
//printf_s("FRAME: %i | NAME: %s \n", i_frame, model.frame_name[i_frame]);
for (__int32 i_axis = X; i_axis < W; i_axis++) {
float max = (float)(frame_node.frame.bboxmax.v[i_axis]) * quake_mdl->file_header.scale[i_axis];
float min = (float)(frame_node.frame.bboxmin.v[i_axis]) * quake_mdl->file_header.scale[i_axis];
model.frame_origin[i_frame].f[i_axis] = (max + min) * 0.5f;
model.frame_extent[i_frame].f[i_axis] = (max - min) * 0.5f;
}
mdl_vertex_t temp_vertices[quake_mdl_::MAX_VERTICES];
fread(&temp_vertices, sizeof(mdl_vertex_t), quake_mdl->file_header.num_verts, file_handle);
for (__int32 i_vertex = 0; i_vertex < quake_mdl->file_header.num_verts; i_vertex++){
float x = ((float)temp_vertices[i_vertex].v[X] * quake_mdl->file_header.scale[X]) + quake_mdl->file_header.translate[X];
float y = ((float)temp_vertices[i_vertex].v[Y] * quake_mdl->file_header.scale[Y]) + quake_mdl->file_header.translate[Y];
float z = ((float)temp_vertices[i_vertex].v[Z] * quake_mdl->file_header.scale[Z]) + quake_mdl->file_header.translate[Z];
model.vertices_frame[i_frame][i_vertex].x = -x;
model.vertices_frame[i_frame][i_vertex].y = z;
model.vertices_frame[i_frame][i_vertex].z = y;
}
}
model.n_frames = quake_mdl->file_header.num_frames;
{
}
}
model.n_triangles = quake_mdl->file_header.num_tris;
model.n_vertices = quake_mdl->file_header.num_verts;
//model.n_texture_vertices = quake_mdl->file_header.num_tris * 3;
model.n_texture_vertices = quake_mdl->file_header.num_verts;
model.n_texture_layers = 2;
const __int32 skin_width = quake_mdl->file_header.skinwidth;
const __int32 skin_height = quake_mdl->file_header.skinheight;
// ----------------------------------------------------------------------------------------------------------
{
model.n_colour_vertices = model.n_vertices;
model.attribute_vertices[model_::ATTRIBUTE_COLOUR] = (float3_*)memory.chunk_ptr;
memory.chunk_ptr = model.attribute_vertices[model_::ATTRIBUTE_COLOUR] + model.n_colour_vertices;
for (__int32 i_vertex = 0; i_vertex < model.n_colour_vertices; i_vertex++) {
model.attribute_vertices[model_::ATTRIBUTE_COLOUR][i_vertex] = { 0.0f, 0.0f, 0.0f };
}
}
// ----------------------------------------------------------------------------------------------------------
{
//model.texture_vertices = (float2_**)memory.chunk_ptr;
//memory.chunk_ptr = model.texture_vertices + model.n_texture_layers;
model.attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY] = (float3_*)memory.chunk_ptr;
memory.chunk_ptr = model.attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY] + (quake_mdl->file_header.num_tris * 3);
model.attribute_vertices[model_::ATTRIBUTE_TEXTURE_SECONDARY] = model.attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY];
}
// ----------------------------------------------------------------------------------------------------------
{
__int32 i_vertex_write = 0;
for (__int32 i_triangle = 0; i_triangle < quake_mdl->file_header.num_tris; i_triangle++) {
bool is_front_face = quake_mdl->triangles[i_triangle].facesfront != 0;
float3_ vertices_mdl[3];
for (__int32 i_vertex = 0; i_vertex < 3; i_vertex++) {
__int32 index = quake_mdl->triangles[i_triangle].vertex[i_vertex];
bool is_on_seam = quake_mdl->texture_coordinates[index].onseam != 0;
float s = (float)quake_mdl->texture_coordinates[index].s;
float t = (float)quake_mdl->texture_coordinates[index].t;
float add = (float)skin_width * 0.5f;
//s += blend(add, 0.0f, (!is_front_face) && is_on_seam);
s += (!is_front_face) && is_on_seam ? add : 0.0f;
vertices_mdl[i_vertex].x = (s + 0.5f) / (float)skin_width;
vertices_mdl[i_vertex].y = (t + 0.5f) / (float)skin_height;
}
model.attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY][i_vertex_write + 2] = vertices_mdl[0];
model.attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY][i_vertex_write + 1] = vertices_mdl[1];
model.attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY][i_vertex_write + 0] = vertices_mdl[2];
i_vertex_write += 3;
}
}
// ----------------------------------------------------------------------------------------------------------
{
const __int32 n_indices = quake_mdl->file_header.num_tris * 3;
model.i_vertices = (__int32*)memory.chunk_ptr;
//model.i_colour_vertices = model.i_vertices + n_indices;
//memory.chunk_ptr = model.i_colour_vertices + n_indices;
model.i_attribute_vertices[model_::ATTRIBUTE_COLOUR] = model.i_vertices + n_indices;
memory.chunk_ptr = model.i_attribute_vertices[model_::ATTRIBUTE_COLOUR] + n_indices;
//model.i_texture_vertices = (__int32**)memory.chunk_ptr;
//memory.chunk_ptr = model.i_texture_vertices + model.n_texture_layers;
//model.i_texture_vertices[0] = (__int32*)memory.chunk_ptr;
//memory.chunk_ptr = model.i_texture_vertices[0] + n_indices;
//model.i_texture_vertices[1] = model.i_texture_vertices[0];
model.i_attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY] = (__int32*)memory.chunk_ptr;
memory.chunk_ptr = model.i_attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY] + n_indices;
model.i_attribute_vertices[model_::ATTRIBUTE_TEXTURE_SECONDARY] = model.i_attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY];
}
// ----------------------------------------------------------------------------------------------------------
__int32 i_index = 0;
for (__int32 i_triangle = 0; i_triangle < quake_mdl->file_header.num_tris; i_triangle++){
__int32 v0 = quake_mdl->triangles[i_triangle].vertex[2];
__int32 v1 = quake_mdl->triangles[i_triangle].vertex[1];
__int32 v2 = quake_mdl->triangles[i_triangle].vertex[0];
model.i_vertices[i_index + 0] = v0;
model.i_vertices[i_index + 1] = v1;
model.i_vertices[i_index + 2] = v2;
//model.i_colour_vertices[i_index + 0] = v0;
//model.i_colour_vertices[i_index + 1] = v1;
//model.i_colour_vertices[i_index + 2] = v2;
model.i_attribute_vertices[model_::ATTRIBUTE_COLOUR] [i_index + 0] = v0;
model.i_attribute_vertices[model_::ATTRIBUTE_COLOUR] [i_index + 1] = v1;
model.i_attribute_vertices[model_::ATTRIBUTE_COLOUR] [i_index + 2] = v2;
model.i_attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY][i_index + 0] = i_index + 0;
model.i_attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY][i_index + 1] = i_index + 1;
model.i_attribute_vertices[model_::ATTRIBUTE_TEXTURE_PRIMARY][i_index + 2] = i_index + 2;
i_index += 3;
}
// ----------------------------------------------------------------------------------------------------------
{
model.i_textures = (__int32**)memory.chunk_ptr;
memory.chunk_ptr = model.i_textures + model.n_texture_layers;
model.i_textures[0] = (__int32*)memory.chunk_ptr;
memory.chunk_ptr = model.i_textures[0] + model.n_triangles;
model.i_textures[1] = (__int32*)memory.chunk_ptr;
memory.chunk_ptr = model.i_textures[1] + model.n_triangles;
for (__int32 i_triangle = 0; i_triangle < model.n_triangles; i_triangle++) {
model.i_textures[0][i_triangle] = 0;
model.i_textures[1][i_triangle] = 1;
}
}
// ----------------------------------------------------------------------------------------------------------
fclose(file_handle);
// ----------------------------------------------------------------------------------------------------------
// animation origin offset
// ----------------------------------------------------------------------------------------------------------
{
{
const __int32 n_vertices = model.n_vertices;
const __int32 i_frame = 0;
float3_ centre;
float3_ extent;
Model_Centre_Extent(model.vertices_frame[i_frame], n_vertices, centre, extent);
model.bounding_origin = centre; // +quake_model.translate;
model.bounding_extent = extent;
}
{
const __int32 n_vertices = model.n_vertices;
float3_ final_extent = { 0.0f, 0.0f, 0.0f };
for (__int32 i_frame = 0; i_frame < model.n_frames; i_frame++) {
float3_ centre;
float3_ extent;
Model_Centre_Extent(model.vertices_frame[i_frame], n_vertices, centre, extent);
final_extent.x = max(final_extent.x, extent.x);
final_extent.y = max(final_extent.y, extent.y);
final_extent.z = max(final_extent.z, extent.z);
}
model.max_horizontal = max(final_extent.x, final_extent.z);
model.max_vertical = final_extent.y;
}
}
delete quake_mdl;
}
|
b5b05924c6fa171a69fb69a4e829b30151b26202 | 390e18bfd0389f8ab038f533242be48de8840f71 | /source/GTA2.WidescreenFix/dllmain.cpp | e238e2c43907d0a641f651550731a91abaa42fe9 | [
"MIT"
] | permissive | MerkeX/WidescreenFixesPack | a690af07b39f4c00206961ab372dd2e4aa4400a3 | 2e68de17dc816583d2e72c5b635ececfb48b0a99 | refs/heads/master | 2023-02-03T06:07:20.229966 | 2023-01-23T12:06:49 | 2023-01-23T12:06:49 | 239,059,498 | 0 | 0 | null | 2020-02-08T02:52:26 | 2020-02-08T02:52:25 | null | UTF-8 | C++ | false | false | 16,263 | cpp | dllmain.cpp | #include "stdafx.h"
int& window_width = *(int*)0x673578;
int& window_height = *(int*)0x6732E8;
#define default_screen_width (640.0f)
#define default_screen_height (480.0f)
#define default_aspect_ratio (default_screen_width / default_screen_height)
#define screen_width ((float)window_width)
#define screen_height ((float)window_height)
#define screen_aspect_ratio (screen_width / screen_height)
#define fone (16384.0f)
#define one (16384)
#define camera_scale ((screen_width / default_screen_width) / (default_aspect_ratio / screen_aspect_ratio))
#define hud_scale (screen_height / default_screen_height)
#define default_hud_scale (screen_width / default_screen_width)
#define hud_offset (screen_width - screen_height * default_aspect_ratio)
int nResX;
int nResY;
bool bExtendHud;
bool bEndProcess;
int32_t nQuicksaveKey;
int32_t nZoomIncreaseKey;
int32_t nZoomDecreaseKey;
int32_t nZoom;
WNDPROC wndProcOld = NULL;
bool keyPressed = false;
LRESULT APIENTRY WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_KEYDOWN:
if (!keyPressed) {
if (wParam == nZoomIncreaseKey)
nZoom += one;
else if (wParam == nZoomDecreaseKey)
nZoom -= one;
keyPressed = true;
}
nZoom = max(-one, min(nZoom, one * 25));
break;
case WM_KEYUP:
keyPressed = false;
break;
case WM_CLOSE:
if (bEndProcess)
ExitProcess(0);
break;
}
return CallWindowProc(wndProcOld, hwnd, uMsg, wParam, lParam);
}
DWORD WINAPI WindowCheck(LPVOID hWnd)
{
while (*(HWND*)hWnd == NULL)
Sleep(10);
wndProcOld = (WNDPROC)GetWindowLong(*(HWND*)hWnd, GWL_WNDPROC);
SetWindowLong(*(HWND*)hWnd, GWL_WNDPROC, (LONG)WndProc);
return 0;
}
int posType = 0; // 0 = default, 1 = centered, 2 = unscaled
injector::hook_back<int*(__fastcall*)(int*, int, int*, int*)> hbRePositionElement;
int* __fastcall RePositionElement(int* in, int, int* out, int* scale) {
out = hbRePositionElement.fun(in, 0, out, scale);
float x = *out / one;
if (posType == 0) {
// Shift this element approximatively.
if (bExtendHud) {
if (x <= screen_width * 0.15f) {
}
else if (x > screen_width * 0.15f && x < screen_width * 0.585f) {
x += hud_offset / 2;
}
else if (x >= screen_width * 0.585f) {
x += hud_offset;
}
}
else
goto centered;
}
else if (posType == 1) {
centered:
x += (hud_offset / 2);
}
else if (posType == 2) {
x /= hud_scale;
x *= default_hud_scale;
}
posType = 0;
*out = (uint32_t)(x * one);
return out;
}
void Rescale(int& x, int& y, int& scale) {
float fx = (x / fone) * hud_scale;
float fy = (y / fone) * hud_scale;
float fs = (scale / fone) * hud_scale;
fx += ((int32_t)(hud_offset / 2));
x = (int32_t)(fx * one);
y = (int32_t)(fy * one);
scale = (int32_t)(fs * one);
}
template<uintptr_t addr>
void SetPosType(int te)
{
using func_hook = injector::function_hooker_thiscall<addr, void(int*, int)>;
injector::make_static_hook<func_hook>([=](typename func_hook::func_type encodeFlt, int* a, int b) {
encodeFlt(a, b);
posType = te;
});
}
template<uintptr_t addr>
void ScaleFontCall()
{
using func_hook = injector::function_hooker_stdcall<addr, void(const wchar_t*, int, int, int, int, const int*, int, bool, int)>;
injector::make_static_hook<func_hook>([=](typename func_hook::func_type printString, const wchar_t* str, int x, int y, int style, int scale, const int* mode, int palette, bool enableAlpha, int alpha) {
Rescale(x, y, scale);
printString(str, x, y, style, scale, mode, palette, enableAlpha, alpha);
});
}
template<uintptr_t addr>
void ScaleSpriteCall()
{
using func_hook = injector::function_hooker_stdcall<addr, void(int, int, int, int, int, int, const int*, int, int, int, int)>;
injector::make_static_hook<func_hook>([=](typename func_hook::func_type drawSprite, int id1, int id2, int x, int y, int angle, int scale, const int* mode, int enableAlpha, int alpha, int a10, int lightFlag) {
Rescale(x, y, scale);
drawSprite(id1, id2, x, y, angle, scale, mode, enableAlpha, alpha, a10, lightFlag);
});
}
void Init()
{
SetProcessDPIAware();
CIniReader iniReader("");
nResX = iniReader.ReadInteger("MAIN", "ResX", 0);
nResY = iniReader.ReadInteger("MAIN", "ResY", 0);
bExtendHud = iniReader.ReadBoolean("MAIN", "ExtendHud", 0);
auto bSkipMovie = iniReader.ReadInteger("MISC", "SkipMovie", 1) != 0;
auto bSkipCredits = iniReader.ReadInteger("MISC", "SkipCredits", 1) != 0;
auto bNoSampManDelay = iniReader.ReadInteger("MISC", "NoSampManDelay", 1) != 0;
bEndProcess = iniReader.ReadInteger("MISC", "EndProcessOnWindowClose", 0) != 0;
nQuicksaveKey = iniReader.ReadInteger("MISC", "QuicksaveKey", VK_F5);
nZoomIncreaseKey = iniReader.ReadInteger("MISC", "ZoomIncreaseKey", VK_OEM_PLUS);
nZoomDecreaseKey = iniReader.ReadInteger("MISC", "ZoomDecreaseKey", VK_OEM_MINUS);
if (!nResX || !nResY)
std::tie(nResX, nResY) = GetDesktopRes();
// Res change
if (nResX && nResY) {
auto pattern = hook::pattern("8B 2D ? ? ? ? 56 8B 35 ? ? ? ? 57 8B 3D"); //0x4CB29F
static auto dword_6732E0 = *pattern.get_first<uint32_t*>(2);
pattern = hook::pattern("89 0D ? ? ? ? A3 ? ? ? ? 89 0D ? ? ? ? EB 5F"); //0x4CB2D5
static auto dword_673578 = *pattern.get_first<uint32_t*>(2);
static auto dword_6732E8 = *pattern.get_first<uint32_t*>(7);
static auto dword_6732E4 = *pattern.get_first<uint32_t*>(13);
struct SetResHook
{
void operator()(injector::reg_pack& regs)
{
regs.eax = nResY;
*dword_673578 = nResX;
*dword_6732E8 = nResY;
*dword_6732E4 = nResX;
*dword_6732E0 = nResY;
}
}; injector::MakeInline<SetResHook>(pattern.get_first(-12), pattern.get_first(17));
pattern = hook::pattern("74 49 A3 ? ? ? ? ? ? ? ? ? ? ? ? ? ? E8 ? ? ? ? 84 C0");
injector::WriteMemory<uint8_t>(pattern.get_first(0), 0xEB, true); //0x4CC61E
injector::WriteMemory<uint8_t>(pattern.get_first(24), 0xEB, true); //0x4CC636
pattern = hook::pattern("74 2B A1 ? ? ? ? B9 ? ? ? ? 50 68");
injector::WriteMemory<uint8_t>(pattern.get_first(0), 0xEB, true); //0x4CB692
pattern = hook::pattern("B8 ? ? ? ? 3B C8 74 2B 6A 10 68");
injector::WriteMemory(pattern.get_first(1), nResX, true); //0x4CB59C + 1
injector::WriteMemory<uint8_t>(pattern.get_first(10), 32, true); //0x4CB5A5+1
injector::WriteMemory(pattern.get_first(12), nResY, true); //0x4CB5A7 + 1
pattern = hook::pattern("6A ? 50 51 52 32 DB"); //0x4CB583
//injector::WriteMemory<uint8_t>(pattern.get_first(1), 32, true); // causes green menu
injector::MakeNOP(pattern.get_first(32), 2, true); //0x4CB5A3
}
auto pattern = hook::pattern("B9 2F 00 00 00 F3 A5"); //0x4A80CD 0x4A6257
struct CameraZoom
{
void operator()(injector::reg_pack& regs)
{
regs.ecx = 0x2F;
*(int32_t*)(regs.ebp + 0x138) = (uint32_t)(hud_scale * one);
*(int32_t*)(regs.ebp + 0x2B0) = (uint32_t)(hud_scale * one); // for Zaibatsu [It was an Accident!] mission
*(int32_t*)(regs.esi + 0x8) += (uint32_t)((camera_scale - 1.0f) * one);
*(int32_t*)(regs.esi + 0x8) += nZoom;
*(int32_t*)(regs.esi + 0x8) = min(*(int32_t*)(regs.esi + 0x8), one * 25);
}
}; injector::MakeInline<CameraZoom>(pattern.count(2).get(1).get<void*>(0));
// Hud
hbRePositionElement.fun = injector::MakeCALL(0x4C72AA, RePositionElement).get();
injector::MakeCALL(0x4C72AA, RePositionElement);
hbRePositionElement.fun = injector::MakeCALL(0x4BA2F4, RePositionElement).get();
injector::MakeCALL(0x4BA2F4, RePositionElement);
hbRePositionElement.fun = injector::MakeCALL(0x4C71DA, RePositionElement).get();
injector::MakeCALL(0x4C71DA, RePositionElement);
hbRePositionElement.fun = injector::MakeCALL(0x44B4BA, RePositionElement).get();
injector::MakeCALL(0x44B4BA, RePositionElement);
SetPosType<(0x4C8A7D)>(1); // Big messages
SetPosType<(0x4C946F)>(1); // Subtitle sprite
SetPosType<(0x4C94D7)>(1); // Subtitle text
SetPosType<(0x4C87A5)>(1); // Quit text 1
SetPosType<(0x4C8805)>(1); // Quit text 2
SetPosType<(0x4C8867)>(1); // Quit text 3
SetPosType<(0x4CA1BC)>(1); // Stats sprite
SetPosType<(0x4CA40C)>(1); // Stats text
SetPosType<(0x4BAD41)>(2); // 3d Text
SetPosType<(0x4BADD2)>(2); // 3d Text
SetPosType<(0x4BAE7B)>(2); // 3d Text
SetPosType<(0x4BAF3D)>(2); // 3d Text
SetPosType<(0x4C98F0)>(1); // Zone name
SetPosType<(0x4C9933)>(1); // Zone name
SetPosType<(0x4C997E)>(1); // Zone name
SetPosType<(0x4C99C4)>(1); // Zone name
SetPosType<(0x4C9A29)>(1); // Zone name
// Frontend
ScaleFontCall<(0x453799)>();
ScaleFontCall<(0x453A1D)>();
ScaleFontCall<(0x4567DC)>();
ScaleFontCall<(0x456A17)>();
ScaleFontCall<(0x4570A7)>();
ScaleFontCall<(0x4580C1)>();
ScaleFontCall<(0x458421)>();
ScaleSpriteCall<(0x453705)>();
ScaleSpriteCall<(0x453753)>();
ScaleSpriteCall<(0x4582EE)>();
// Frontend
//pattern = hook::pattern("8B 4C 24 18 8B 54 24 14"); // 0x4539F1
//struct PrintStringHook
//{
// void operator()(injector::reg_pack& regs)
// {
// int32_t& nx = *(int32_t*)(regs.esp + 0x4 + 0x8);
// int32_t& ny = *(int32_t*)(regs.esp + 0x4 + 0xC);
// int32_t& ns = *(int32_t*)(regs.esp + 0x4 + 0x14);
//
// float fx = (nx / one) * hud_scale;
// float fy = (ny / one) * hud_scale;
// float fs = (ns / one) * hud_scale;
// fx += ((int32_t)(hud_offset / 2));
//
// regs.ecx = (int32_t)(fs * one);
// regs.edx = *(uint32_t*)(regs.esp + 0x4 + 0x10);
//
// nx = (int32_t)fx * one;
// ny = (int32_t)fy * one;
// }
//}; injector::MakeInline<PrintStringHook>(pattern.count(11).get(5).get<void*>(0), pattern.count(11).get(5).get<void*>(8));
pattern = hook::pattern("8B 15 ? ? ? ? 6A 06 52 8B 08 50"); //0x4B4FB8
auto hwnd = *pattern.get_first<HWND*>(2);
CreateThreadAutoClose(0, 0, (LPTHREAD_START_ROUTINE)&WindowCheck, (LPVOID)hwnd, 0, NULL);
if (bSkipMovie)
{
//skip movie to prevent windowed crash
pattern = hook::pattern("8A 88 ? ? ? ? 88 88 ? ? ? ? 40 84 C9 ? ? B8 ? ? ? ? C3");
injector::WriteMemory<uint8_t>(*pattern.get_first<void*>(2), '_', true); //0x459695+2
}
if (bSkipCredits)
{
pattern = hook::pattern("66 C7 86 ? ? ? ? ? ? A1 ? ? ? ? 33 FF");
injector::WriteMemory<uint16_t>(pattern.get_first(7), 258, true); //0x453EFB+7
}
if (bNoSampManDelay)
{
pattern = hook::pattern("FF D5 6A 01");
injector::MakeNOP(pattern.get_first(2), 8, true); //0x4B6821+2
}
// Intro crash fix
injector::MakeNOP(0x481E28, 2, true);
static int mode = 0;
pattern = hook::pattern("A1 ? ? ? ? 8B 0D ? ? ? ? EB 06"); // 0x4CAEF2
struct ClearScreenHook
{
void operator()(injector::reg_pack& regs)
{
regs.eax = window_width;
regs.ecx = window_height;
mode = -2;
}
}; injector::MakeInline<ClearScreenHook>(pattern.get_first(0), pattern.get_first(11));
pattern = hook::pattern("8B 15 ? ? ? ? A1 ? ? ? ? 81 CA ? ? ? ?"); // 0x481E2F
struct IntroMovieColorHook
{
void operator()(injector::reg_pack& regs)
{
regs.edx = 3;
if (mode == -2)
regs.edx = 1;
mode = 0;
}
}; injector::MakeInline<IntroMovieColorHook>(pattern.get_first(0), pattern.get_first(6));
if (nQuicksaveKey)
{
//code from NTAuthority
static uint16_t oldState = 0;
static uint16_t curState = 0;
//injector::WriteMemory(0x47FEDC, 0, true);
//injector::WriteMemory(0x47FEF5, 500, true);
static uint32_t dword_45E510 = (uint32_t)hook::get_pattern("8D 81 00 03 00 00 C3", 0);
static uint32_t dword_5EC070 = *(uint32_t*)hook::get_pattern("B9 ? ? ? ? E8 ? ? ? ? 66 0F B6", 1);
static uint32_t dword_47EF40 = (uint32_t)hook::get_pattern("83 EC 18 53 8B 5C 24 20 55 8B", 0);
static uint32_t dword_6644BC = *(uint32_t*)hook::get_pattern("8B 15 ? ? ? ? 8B 82 38 03 00", 2);
static uint32_t dword_4C6750 = (uint32_t)hook::get_pattern("8B 44 24 08 8B 54 24 04 6A FF 50 52", 0);
static uint32_t dword_672F40 = *(uint32_t*)hook::get_pattern("8B 0D ? ? ? ? 56 68 ? ? ? ? 6A 01", 2);
static uint32_t dword_673E2C = *(uint32_t*)hook::get_pattern("A1 ? ? ? ? 85 C0 75 ? 8A 41 30", 1);
pattern = hook::pattern("8B 73 04 33 FF 3B F7 66 89 BB E8"); //0x481380
struct QuicksaveHook
{
void operator()(injector::reg_pack& regs)
{
regs.esi = *(uint32_t*)(regs.ebx + 4);
regs.edi = 0;
curState = GetAsyncKeyState(nQuicksaveKey);
if (!curState && oldState)
{
uint32_t missionFlag = **(uint32_t**)(*(uint32_t*)(dword_6644BC)+0x344);
uint32_t isMP = *(uint32_t*)dword_673E2C;
if (!missionFlag && !isMP)
{
//injector::thiscall<int(int, int)>::call(0x4105B0, 0x5D85A0, 0x3D); //sfx
auto i = injector::thiscall<uint32_t(uint32_t)>::call(dword_45E510, dword_5EC070); //save
injector::thiscall<uint32_t(uint32_t, uint32_t)>::call(dword_47EF40, *(uint32_t*)dword_6644BC, i);
injector::thiscall<uint32_t(uint32_t, uint32_t, const char*)>::call(dword_4C6750, *(uintptr_t*)dword_672F40 + 0xE4, 1, "svdone"); // text display
}
}
oldState = curState;
}
}; injector::MakeInline<QuicksaveHook>(pattern.get_first(0));
}
}
void InitD3DDim()
{
auto pattern = hook::module_pattern(GetModuleHandle(L"d3dim"), "B8 00 08 00 00 39");
if (!pattern.count_hint(2).empty())
injector::WriteMemory(pattern.get(0).get<void>(1), -1, true);
}
void InitD3DDim700()
{
auto pattern = hook::module_pattern(GetModuleHandle(L"d3dim700"), "B8 00 08 00 00 39");
if (!pattern.count_hint(2).empty())
injector::WriteMemory(pattern.get(0).get<void>(1), -1, true);
}
void InitD3DDLL() {
auto pattern = hook::module_pattern(GetModuleHandle(L"d3ddll"), "89 7C 24 28 89 74 24 2C");
struct gbh_BlitImageHook
{
void operator()(injector::reg_pack& regs)
{
RECT& dest = (*(RECT*)(regs.esp + 0x30 - 0x10));
dest.left = regs.ebp * hud_scale;
dest.top = regs.ebx * hud_scale;
dest.right = regs.edi * hud_scale;
dest.bottom = regs.esi * hud_scale;
dest.left += (int32_t)(hud_offset / 2);
dest.right += (int32_t)(hud_offset / 2);
}
}; injector::MakeInline<gbh_BlitImageHook>(pattern.get_first(0), pattern.get_first(8));
}
CEXP void InitializeASI()
{
std::call_once(CallbackHandler::flag, []()
{
CallbackHandler::RegisterCallback(Init, hook::pattern("83 EC 68 55 56 8B 74 24 74"));
CallbackHandler::RegisterCallback(L"d3dim.dll", InitD3DDim); // crash fix for
CallbackHandler::RegisterCallback(L"d3dim700.dll", InitD3DDim700); // resolutions > 2048
CallbackHandler::RegisterCallback(L"d3ddll.dll", InitD3DDLL); // frontend background scale
});
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved)
{
if (reason == DLL_PROCESS_ATTACH)
{
if (!IsUALPresent()) { InitializeASI(); }
}
return TRUE;
} |
4c96a1d2b3ec7b39671138764176f4aba3ba91ea | 5e6590c5f633fbca4663aaf79dee3a95a21447e8 | /Part2/SobelFilter/SobelFilter/Image.h | 8167a4610ff57a5a92d2dbd0b1b5155a5096e2e6 | [] | no_license | tuzimaster/FMRI_Non_Linear_Adaptive_Noise_Filter_Algorithm_And_Gui | cf031fc07523379c5d157c21150da5ad30bacef5 | 97b40a51c08b341ac2fc656e86069ed143769833 | refs/heads/master | 2021-01-20T20:57:37.249696 | 2012-10-23T03:21:15 | 2012-10-23T03:21:15 | 6,346,021 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 674 | h | Image.h | #pragma once
/* IMAGE.H - Image class */
#ifndef IMAGE_H
#define IMAGE_H
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
class Image
{
int num_rows; //Number of rows in array
int num_cols; //Number of cols in array
float *data; //Array to contain pixel data
public:
Image(void); //Default Constructor
Image(int rows, int cols); //Constructor
~Image(void); //Destructor
Image(Image & I); //Copy Constructor
int getNumRows();
int getNumCols();
float getVal(int row, int col);
void setVal(int row, int col, float val);
void readImage(char *filename);
void writeImage(char *filename);
};
#endif // !defined( IMAGE_H)
|
365b9fe90afd804e2d86a1a74058366efef2963c | ca574a9fd4de69d0b376e7f5ad89ae9354cfc289 | /计算器.cpp | 7ad5131d28e0eea585c4f59c89115bed94db5c7f | [] | no_license | nepentheSO16/test | 9d7c08d6b2622b09636773352da2c43990eb4503 | 88510f23d7b15049f9c1381ea98d4ac4cdbc4326 | refs/heads/master | 2022-12-14T02:32:52.185360 | 2020-09-10T03:30:20 | 2020-09-10T03:30:20 | 293,506,198 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 898 | cpp | 计算器.cpp | #include<iostream>
#include<string>
#include<cmath>
using namespace std;
struct A{
string n;
};
int jinzhizhuanhuan(string a,int h,int n){
cout<<"将这个数转换成十进制为:";
int l=0;
for(int i=0;i<n;i++){
l=l+(int)(a[n-i-1]-'0')*pow(h,i);
}
cout<<l;
return l;
}
void jinzhishibie(string a){
int i;
int n=a.length();
if(a[0]=='0'){
if(a[1]=='b'||a[1]=='B'){
cout<<"这是一个二进制数"<<endl;
a[1]='0';
i=2;
}
else if(a[1]=='x'||a[1]=='X'){
cout<<"这是一个十六进制数"<<endl;
a[1]='0';
i=16;
}
else {
cout<<"这是一个八进制数"<<endl;
i=8;
}
}
else{
cout<<"这是一个十进制数"<<endl;
i=10;
}
jinzhizhuanhuan(a,i,n);
}
int sizeyunsuan(){
string a;
cin>>a;
}
int main(){
cout<<"请选择您想要完成的功能:"<<endl;
cout<<"四则运算请输入1";
int i;
cin>>i;
switch(i){
case 1:
}
}
|
dc269744ea865e6da64b7b7fabc6465ea5792916 | c15d124ea20024ed94884e0d457a4e24f024b377 | /1066.cpp | 6ca16bafa8a8218d72f284d3973a0a462c6354a7 | [] | no_license | zm2417/luogu-cpp | 34e37afaf96f17e45f1ccb2b883dea5584b332d0 | 40d4960dc7ccf84168707fd5f0285b2e325eb03f | refs/heads/master | 2020-12-21T02:24:12.088314 | 2020-03-11T07:44:39 | 2020-03-11T07:44:39 | 236,278,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | cpp | 1066.cpp | #include <iostream>
#include <cmath>
#include <string>
using namespace std;
const int maxInf = 512;
string c[maxInf][maxInf];
int k, w;
int p, t;
// 高精度加
string add(string a, string b)
{
string ans;
int jw = 0;
for (int i = 0; i < max(a.size(), b.size()); i++)
{
int x = jw;
if (i < a.size())
{
x += a[i] - 48;
}
if (i < b.size())
{
x += b[i] - 48;
}
jw = x / 10;
x %= 10;
ans.push_back(x + 48);
}
if (jw != 0)
{
ans.push_back(jw + 48);
}
return ans;
}
int main()
{
cin >> k >> w;
p = w / k;
t = (1 << k);
c[0][0] = "1";
for (int i = 1; i < t; i++)
{
c[i][0] = "1";
c[i][i] = "1";
}
// 杨辉三角形
// 递推公式𝐶𝑚𝑛=𝐶𝑚𝑛−1+𝐶𝑚−1𝑛−1 可理解为:含特定元素的组合有𝐶𝑚−1𝑛−1,不含特定元素的排列为𝐶𝑚𝑛−1
for (int i = 1; i < t; i++)
{
for (int j = 1; j < i; j++)
{
c[i][j] = add(c[i - 1][j - 1], c[i - 1][j]);
}
}
string ans = "0";
for (int i = 2; i <= p; i++)
{
if (i > t - 1)
break;
ans = add(ans, c[t - 1][i]);
}
int res = w % k;
int pp = (1 << res) - 1;
for (int i = 1; i <= pp; i++)
{
if (p > t - 1 - i)
break;
ans = add(ans, c[t - 1 - i][p]);
}
for (int i = ans.size() - 1; i >= 0; i--)
{
cout << ans[i];
}
return 0;
}
|
d8b77e5324e879ba23f26c9fc41aab500efdcbdf | 2ff3ddc4e2e3eb7f727e52965a714b3849ac1a3b | /include/FractalAgent.hpp | 01bb3a0e643e996211711a3eb3dd62a79411f59a | [] | no_license | Satre95/Tapestry | 74b6a2cd47df50f9a6aabc7a19cfbdd0af5ff3c6 | 9c90e6cb61b783c9530d22a9fce3fb2d7ea22226 | refs/heads/master | 2021-08-15T01:25:31.701494 | 2017-11-17T04:03:11 | 2017-11-17T04:03:11 | 108,938,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,777 | hpp | FractalAgent.hpp | #pragma once
#include <string>
#include <sstream>
#include <unordered_map>
#include <functional>
#include "cinder/GeomIo.h"
#include "cinder/gl/gl.h"
#include "cinder/Vector.h"
#include "Trail.hpp"
class FractalAgent
{
public:
FractalAgent(std::string axiom, ci::Color col = ci::Color::white());
~FractalAgent();
/// Run 1 recursion step of the sequence. Restarts the draw sequence.
void Iterate();
/// Parse the next character in the sequence and perform it's action. Stores the history of points.
void Advance();
/// Runs through the entire sequence and stores the results.
void AdvanceAll();
/// Draws the Agent turtle and the generated path.
void Draw();
void AddRule(char c, std::string rule);
void AddAction(char c, const std::function < std::pair<glm::vec3, glm::vec3>(glm::vec3, glm::vec3)> &);
std::string GetProduction() const { return m_production; }
void SetHeading(glm::vec3 newHeading) { m_heading = newHeading; }
static float stepSize;
private:
glm::vec3 m_position;
/// Direction the turtle is facing. Should always be normalized.
glm::vec3 m_heading;
/// Location of the next symbol that needs to be processed.
size_t m_nextSymbolIndex = 0;
/// The history of this point
Trail m_trail;
/// The color to draw with.
ci::Color m_color;
/// Starting state.
const std::string m_axiom;
/// The string representing the L-System state at the current time point.
std::string m_production;
/// The expansion rule set. If a char is not in here, then it is constant.
std::unordered_map<char, std::string> m_ruleSet;
/// Set of functors that take in current pos and heading and return new pos and heading for a given rule.
std::unordered_map <char, std::function < std::pair<glm::vec3, glm::vec3>(glm::vec3, glm::vec3)>> m_actions;
}; |
11f9be77979d5b11ce86471a55c2b316a1e9c940 | e3124a48f9bbd44103b3ab6e45fcf48a5571fa0f | /jni/Dead.cpp | 4dae1ab3c74230df2ff5e373f42a0caca9591377 | [] | no_license | Caerind/Tehos-Rebirth | 5eda881be8a8f2218c943245c377f2024cdd1083 | ddae1efbd68209fe3fa60e80c8d46b59e99a2b25 | refs/heads/master | 2021-06-10T14:52:00.772486 | 2016-12-13T01:01:49 | 2016-12-13T01:01:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,060 | cpp | Dead.cpp | #include "Dead.hpp"
#include "States\GameState.hpp"
Dead::Dead(ke::Scene& scene, std::size_t team, std::size_t type)
: ke::Actor(scene)
, mSprite(nullptr)
, mTeam(team)
, mType(type)
, mElapsed(sf::Time::Zero)
{
setZ(-50.f);
}
Dead::~Dead()
{
}
void Dead::initializeComponents()
{
mSprite = createComponent<ke::AnimatorComponent>();
std::string type = "";
switch (mTeam)
{
case 1: type += "enemy-" + ke::toString(mType); break;
case 2: type += "soldier-" + ke::toString(mType); break;
default: break;
}
attachComponent(mSprite);
if (mTeam == 1 && mType == 1)
{
mSprite->setPosition(sf::Vector2f(-64.f, -108.f));
}
else
{
mSprite->setPosition(sf::Vector2f(-32.f, -54.f));
}
mSprite->addAnimation("dead", type + "-dead");
mSprite->playAnimation("dead");
}
void Dead::update(sf::Time dt)
{
mElapsed += dt;
if (mElapsed >= sf::seconds(2.f))
{
float a = (3.f - mElapsed.asSeconds()) * 255;
mSprite->setColor(sf::Color(255, 255, 255, static_cast<unsigned int>(a)));
}
if (mElapsed >= sf::seconds(3.f))
{
remove();
}
}
|
cfff6984f2bc5ed2233c31554127b99bc002b009 | 311c461ccb552a2f25ce5a8308fced7ad71bb04c | /src/moci/graphics/image.test.cpp | 7c04aa38cafc0c76a6c949f5733e9b2e7aefb411 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | tobanteAudio/moci | 8fc61ef8ecf5692504098e304ac3b008eee52141 | c8f30d53e62ae256129a8980a50c10c69c36c54a | refs/heads/main | 2022-11-05T17:25:15.587196 | 2022-10-31T03:55:03 | 2022-10-31T03:55:03 | 247,848,003 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,331 | cpp | image.test.cpp | /**
* @file image.test.cpp
* @copyright Copyright 2019-2020 tobanteAudio.
*/
#include <catch2/catch_all.hpp>
#include "image.hpp"
TEST_CASE("graphics: ImageDefaultConstructor", "[graphics]")
{
moci::Image img {};
REQUIRE(img.getWidth() == 0);
REQUIRE(img.getHeight() == 0);
REQUIRE(img.empty() == true);
REQUIRE(img.data().empty());
}
TEST_CASE("graphics: ImagePathConstructor", "[graphics]")
{
moci::Image img {"moci_test_data/colors.png"};
REQUIRE(img.getWidth() == 256);
REQUIRE(img.getHeight() == 256);
REQUIRE(img.getNumChannels() == 3);
REQUIRE(img.empty() == false);
REQUIRE(img.data().size() == 196608);
}
TEST_CASE("graphics: ImageLoadFromFileSuccess", "[graphics]")
{
moci::Image img {};
REQUIRE(img.loadFromFile("moci_test_data/colors.png") == true);
REQUIRE(img.getWidth() == 256);
REQUIRE(img.getHeight() == 256);
REQUIRE(img.getNumChannels() == 3);
REQUIRE(img.empty() == false);
REQUIRE(img.data().size() == 196608);
}
TEST_CASE("graphics: ImageLoadFromFileFail", "[graphics]")
{
moci::Image img {};
REQUIRE(img.loadFromFile("noexist.png") == false);
REQUIRE(img.getWidth() == 0);
REQUIRE(img.getHeight() == 0);
REQUIRE(img.getNumChannels() == 0);
REQUIRE(img.empty() == true);
REQUIRE(img.data().empty());
} |
d6d71150b6d470477e40f0a5fa61a791d8874d6c | 709c504577148de3d7f3a247b2873e891d146cf8 | /demo3/VirtualRow.h | 5d38fd457a597c93022a86c098906d94f7c7bdb2 | [] | no_license | adam-zhang/pdfcreator | eaef6a3c8a8228e779670066d5888d47fa7dc6ff | 1211955ca8cfed662237a3eda6ff2082e167fdcb | refs/heads/master | 2022-02-10T08:19:05.157952 | 2019-07-23T01:13:45 | 2019-07-23T01:13:45 | 198,154,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | h | VirtualRow.h | #pragma once
#include <memory>
#include <vector>
class VirtualColumn;
class VirtualPage;
class VirtualRow
{
public:
enum RowType
{
NORMAL,
HEADER,
NEWHEADER,
};
public:
VirtualRow(void);
~VirtualRow(void);
private:
std::vector<std::shared_ptr<VirtualColumn>> columns_;
size_t columnCount_;
RowType rowType_;
size_t index_;
public:
size_t index()const
{ return index_;}
void setIndex(size_t value)
{ index_ = value;}
RowType rowType()
{ return rowType_;}
void setRowType(RowType value)
{ rowType_ = value;}
std::vector<std::shared_ptr<VirtualColumn>>& columns()
{ return columns_;}
size_t columnCount()
{ return columnCount_;}
void setColumnCount(size_t value)
{ columnCount_ = value;}
};
|
1c6136e05b874c2b5a9081582d3c8f01fcafe4c3 | 13a9587f8577167c70bed4f71cf6edec00408694 | /miosix/arch/common/drivers/serial_stm32.h | 0a7fd194ba8e66d214a68a827f015655de1869f0 | [] | no_license | fedetft/miosix-kernel | d67557aba5b53bb31a3f2c2d63f859425ab71774 | 69da7bffb18a5ed787c52367a9f17af0ebbd8e9e | refs/heads/master | 2023-08-07T15:14:51.788587 | 2023-07-31T07:48:08 | 2023-07-31T07:48:08 | 37,068,092 | 45 | 32 | null | 2023-05-23T12:02:08 | 2015-06-08T13:20:11 | C | UTF-8 | C++ | false | false | 11,751 | h | serial_stm32.h | /***************************************************************************
* Copyright (C) 2010-2018 by Terraneo Federico *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* As a special exception, if other files instantiate templates or use *
* macros or inline functions from this file, or you compile this file *
* and link it with other works to produce a work based on this file, *
* this file does not by itself cause the resulting work to be covered *
* by the GNU General Public License. However the source code for this *
* file must still be made available in accordance with the GNU General *
* Public License. This exception does not invalidate any other reasons *
* why a work based on this file might be covered by the GNU General *
* Public License. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, see <http://www.gnu.org/licenses/> *
***************************************************************************/
#ifndef SERIAL_STM32_H
#define SERIAL_STM32_H
#include "filesystem/console/console_device.h"
#include "kernel/sync.h"
#include "kernel/queue.h"
#include "interfaces/gpio.h"
#include "board_settings.h"
#if defined(_ARCH_CORTEXM3_STM32F1) && defined(__ENABLE_XRAM)
//Quirk: concurrent access to the FSMC from both core and DMA is broken in
//the stm32f1, so disable DMA mode if XRAM is enabled.
#undef SERIAL_1_DMA
#undef SERIAL_2_DMA
#undef SERIAL_3_DMA
#endif
#if defined(SERIAL_1_DMA) || defined(SERIAL_2_DMA) || defined(SERIAL_3_DMA)
#define SERIAL_DMA
#endif
#if defined(SERIAL_DMA) && defined(_ARCH_CORTEXM0_STM32F0)
#undef SERIAL_1_DMA
#undef SERIAL_2_DMA
#undef SERIAL_3_DMA
#undef SERIAL_DMA
#warning "DMA not yet implemented for STM32F0 family"
#endif
namespace miosix {
/**
* Serial port class for stm32 microcontrollers.
* Only supports USART1, USART2 and USART3
* Additionally, USARTx can use DMA if SERIAL_x_DMA is defined in
* board_settings.h, while the other serial use polling for transmission,
* and interrupt for reception.
*
* Classes of this type are reference counted, must be allocated on the heap
* and managed through intrusive_ref_ptr<FileBase>
*/
class STM32Serial : public Device
{
public:
enum FlowCtrl
{
NOFLOWCTRL, ///< No hardware flow control
RTSCTS ///< RTS/CTS hardware flow control
};
/**
* Constructor, initializes the serial port using the default pins, which
* are:
* USART1: tx=PA9 rx=PA10 cts=PA11 rts=PA12
* USART2: tx=PA2 rx=PA3 cts=PA0 rts=PA1
* USART3: tx=PB10 rx=PB11 cts=PB13 rts=PB14
* If you board has a different mapping, use one of the other constructors.
*
* Calls errorHandler(UNEXPECTED) if id is not in the correct range, or when
* attempting to construct multiple objects with the same id. That is,
* it is possible to instantiate only one instance of this class for each
* hardware USART.
* \param id a number 1 to 3 to select which USART
* \param baudrate serial port baudrate
* \param flowControl to enable hardware flow control on this port
*/
STM32Serial(int id, int baudrate, FlowCtrl flowControl=NOFLOWCTRL);
/**
* Constructor, initializes the serial port using remapped pins and disables
* flow control.
*
* NOTE: for stm32f2, f4, f7 and h7 you have to set the correct alternate
* function to the pins in order to connect then to the USART peripheral
* before passing them to this class.
*
* Calls errorHandler(UNEXPECTED) if id is not in the correct range, or when
* attempting to construct multiple objects with the same id. That is,
* it is possible to instantiate only one instance of this class for each
* hardware USART.
* \param id a number 1 to 3 to select which USART
* \param baudrate serial port baudrate
* \param tx tx pin
* \param rx rx pin
*/
STM32Serial(int id, int baudrate, miosix::GpioPin tx, miosix::GpioPin rx);
/**
* Constructor, initializes the serial port using remapped pins and enables
* flow control.
*
* NOTE: for stm32f2, f4, f7 and h7 you have to set the correct alternate
* function to the pins in order to connect then to the USART peripheral
* before passing them to this class.
*
* Calls errorHandler(UNEXPECTED) if id is not in the correct range, or when
* attempting to construct multiple objects with the same id. That is,
* it is possible to instantiate only one instance of this class for each
* hardware USART.
* \param id a number 1 to 3 to select which USART
* \param tx tx pin
* \param rx rx pin
* \param rts rts pin
* \param cts cts pin
*/
STM32Serial(int id, int baudrate, miosix::GpioPin tx, miosix::GpioPin rx,
miosix::GpioPin rts, miosix::GpioPin cts);
/**
* Read a block of data
* \param buffer buffer where read data will be stored
* \param size buffer size
* \param where where to read from
* \return number of bytes read or a negative number on failure. Note that
* it is normal for this function to return less character than the amount
* asked
*/
ssize_t readBlock(void *buffer, size_t size, off_t where);
/**
* Write a block of data
* \param buffer buffer where take data to write
* \param size buffer size
* \param where where to write to
* \return number of bytes written or a negative number on failure
*/
ssize_t writeBlock(const void *buffer, size_t size, off_t where);
/**
* Write a string.
* An extension to the Device interface that adds a new member function,
* which is used by the kernel on console devices to write debug information
* before the kernel is started or in case of serious errors, right before
* rebooting.
* Can ONLY be called when the kernel is not yet started, paused or within
* an interrupt. This default implementation ignores writes.
* \param str the string to write. The string must be NUL terminated.
*/
void IRQwrite(const char *str);
/**
* Performs device-specific operations
* \param cmd specifies the operation to perform
* \param arg optional argument that some operation require
* \return the exact return value depends on CMD, -1 is returned on error
*/
int ioctl(int cmd, void *arg);
/**
* \internal the serial port interrupts call this member function.
* Never call this from user code.
*/
void IRQhandleInterrupt();
#ifdef SERIAL_DMA
/**
* \internal the serial port DMA tx interrupts call this member function.
* Never call this from user code.
*/
void IRQhandleDMAtx();
/**
* \internal the serial port DMA rx interrupts call this member function.
* Never call this from user code.
*/
void IRQhandleDMArx();
#endif //SERIAL_DMA
/**
* \return port id, 1 for USART1, 2 for USART2, ...
*/
int getId() const { return portId; }
/**
* Destructor
*/
~STM32Serial();
private:
/**
* Code common for all constructors
*/
void commonInit(int id, int baudrate, miosix::GpioPin tx, miosix::GpioPin rx,
miosix::GpioPin rts, miosix::GpioPin cts);
#ifdef SERIAL_DMA
/**
* Wait until a pending DMA TX completes, if any
*/
void waitDmaTxCompletion();
/**
* Write to the serial port using DMA. When the function returns, the DMA
* transfer is still in progress.
* \param buffer buffer to write
* \param size size of buffer to write
*/
void writeDma(const char *buffer, size_t size);
/**
* Read from DMA buffer and write data to queue
*/
void IRQreadDma();
/**
* Start DMA read
*/
void IRQdmaReadStart();
/**
* Stop DMA read
* \return the number of characters in rxBuffer
*/
int IRQdmaReadStop();
#endif //SERIAL_DMA
/**
* Wait until all characters have been written to the serial port.
* Needs to be callable from interrupts disabled (it is used in IRQwrite)
*/
void waitSerialTxFifoEmpty()
{
#if !defined(_ARCH_CORTEXM7_STM32F7) && !defined(_ARCH_CORTEXM7_STM32H7) \
&& !defined(_ARCH_CORTEXM0_STM32F0) && !defined(_ARCH_CORTEXM4_STM32F3) \
&& !defined(_ARCH_CORTEXM4_STM32L4)
while((port->SR & USART_SR_TC)==0) ;
#else //_ARCH_CORTEXM7_STM32F7/H7
while((port->ISR & USART_ISR_TC)==0) ;
#endif //_ARCH_CORTEXM7_STM32F7/H7
}
FastMutex txMutex; ///< Mutex locked during transmission
FastMutex rxMutex; ///< Mutex locked during reception
DynUnsyncQueue<char> rxQueue; ///< Receiving queue
static const unsigned int rxQueueMin=16; ///< Minimum queue size
Thread *rxWaiting=0; ///< Thread waiting for rx, or 0
USART_TypeDef *port; ///< Pointer to USART peripheral
#ifdef SERIAL_DMA
#if defined(_ARCH_CORTEXM3_STM32F1) || defined(_ARCH_CORTEXM4_STM32F3) \
|| defined(_ARCH_CORTEXM4_STM32L4)
DMA_Channel_TypeDef *dmaTx; ///< Pointer to DMA TX peripheral
DMA_Channel_TypeDef *dmaRx; ///< Pointer to DMA RX peripheral
#else //_ARCH_CORTEXM3_STM32F1 and _ARCH_CORTEXM4_STM32F3
DMA_Stream_TypeDef *dmaTx; ///< Pointer to DMA TX peripheral
DMA_Stream_TypeDef *dmaRx; ///< Pointer to DMA RX peripheral
#endif //_ARCH_CORTEXM3_STM32F1 and _ARCH_CORTEXM4_STM32F3
Thread *txWaiting; ///< Thread waiting for tx, or 0
static const unsigned int txBufferSize=16; ///< Size of tx buffer, for tx speedup
/// Tx buffer, for tx speedup. This buffer must not end up in the CCM of the
/// STM32F4, as it is used to perform DMA operations. This is guaranteed by
/// the fact that this class must be allocated on the heap as it derives
/// from Device, and the Miosix linker scripts never put the heap in CCM
char txBuffer[txBufferSize];
/// This buffer emulates the behaviour of a 16550. It is filled using DMA
/// and an interrupt is fired as soon as it is half full
char rxBuffer[rxQueueMin];
bool dmaTxInProgress; ///< True if a DMA tx is in progress
#endif //SERIAL_DMA
bool idle=true; ///< Receiver idle
const bool flowControl; ///< True if flow control GPIOs enabled
const unsigned char portId; ///< 1 for USART1, 2 for USART2, ...
};
} //namespace miosix
#endif //SERIAL_STM32_H
|
6ea1d6d15f6a19055561351c3e09e0fef3f21d31 | 6c862c123645e595471323b6c45d449d71896109 | /LeetCode/C++/200_Number_of_Islands.cpp | 23bf6c2bd79266fc084fb5e77f0543b6f56cf48e | [
"MIT"
] | permissive | icgw/practice | 72083fc2e99b20aed937358d26e0ac0cfefd00ea | cb70ca87aa4604d1aec83d4224b3489eacebba75 | refs/heads/master | 2021-11-15T05:09:48.930754 | 2021-11-13T02:04:57 | 2021-11-13T02:04:57 | 144,442,645 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,493 | cpp | 200_Number_of_Islands.cpp | /* Given a 2d grid map of `1's (land) and `0's (water), count the number of
* islands. An island is surrounded by water and is formed by connecting
* adjacent lands horizontally or vertically. You may assume all four edges of
* the grid are all surrounded by water.
*
* Example:
* Input:
* 11000
* 11000
* 00100
* 00011
* Output: 3
*/
#include <iostream>
#include <vector>
using namespace std;
static int dr[4] = {0, 0, -1, 1};
static int dc[4] = {-1, 1, 0, 0};
class Solution {
public:
static int numIslands(vector<vector<char>>& grid){
int rows = grid.size();
if (rows == 0) return 0;
int columns = grid[0].size();
int ans = 0;
for (int i = 0; i < rows; ++i){
for (int j = 0; j < columns; ++j){
if (grid[i][j] == '0') continue;
++ans;
dfs(grid, i, j, rows, columns);
}
}
return ans;
}
static void dfs(vector<vector<char>>& grid,
int i, int j,
int m, int n){
grid[i][j] = '0';
for (int k = 0; k < 4; ++k){
if (!isBound(i + dr[k], j + dc[k], m, n)
&& grid[i + dr[k]][j + dc[k]] == '1'){
dfs(grid, i + dr[k], j + dc[k], m, n);
}
}
}
static bool isBound(int i, int j, int m, int n){
return i < 0 || j < 0 || i >= m || j >= n;
}
};
int main(int argc, char *argv[]){
vector<vector<char>> grid {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}
};
cout << Solution::numIslands(grid) << endl;
return 0;
}
|
5c1d4f2394662eaaefd69395e79a58d5d3a19c8c | 984b9f12101b242d89be44e5fa4fa789a148b8a9 | /Source/common/util/lightmap/gen_lightmaps.hpp | 39bfe36bf2770fff7829d58176e7ff478a14d53e | [] | no_license | MegaMilkX/Katana | 84c7634d0354b2abdb30f2ebd6a41e68a6081ce2 | 8e63554bd6d10ffd3ecbc8736a94e5d4c288a221 | refs/heads/master | 2021-06-10T07:56:38.687774 | 2021-05-31T21:42:49 | 2021-05-31T21:42:49 | 167,166,151 | 4 | 1 | null | 2020-11-14T09:11:39 | 2019-01-23T10:43:48 | C++ | UTF-8 | C++ | false | false | 829 | hpp | gen_lightmaps.hpp | #ifndef GEN_LIGHTMAP_HPP
#define GEN_LIGHTMAP_HPP
#include "../../renderer.hpp"
#include "../../resource/mesh.hpp"
#include "../../resource/texture2d.h"
#include "../../ecs/attribs/base_attribs.hpp"
#include "../../lib/lightmapper.h"
struct LightmapMeshData {
int tex_width;
int tex_height;
std::vector<float> tex_data;
ecsMeshes::Segment* segment;
std::vector<float> position;
std::vector<float> normal;
std::vector<float> uv_lightmap;
std::vector<uint32_t> indices;
gfxm::mat4 transform;
// Result
std::shared_ptr<Texture2D> lightmap;
};
void GenLightmaps(std::vector<LightmapMeshData>& meshes, RendererPBR* renderer, GBuffer* gbuffer, const DrawList& dl);
#endif
|
0147535d38ffedba191d212fae7c439c29f4a779 | a6d2579ecdb3c9f3edb94e0588841bbb5338d1fc | /lcy8047/coloredPaper.cpp | d163ba4b3111c7b3e4f73115b9b9a32b9068eab4 | [] | no_license | rpt5366/Challenge100_Code_Test_Study | 82f57c67b2354b61ebca74de9717e7f79dd2ec55 | 4dc9597791dd1fff47a1799108647aa1d370b549 | refs/heads/main | 2023-08-14T16:14:53.045597 | 2021-10-08T16:36:02 | 2021-10-08T16:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,111 | cpp | coloredPaper.cpp | #include <bits/stdc++.h>
using namespace std;
int **paper;
int n;
int res_white = 0;
int res_blue = 0;
void solve(int y, int x, int size)
{
int first = paper[y][x];
bool is_same = true;
for(int i=y; i<y+size; i++)
{
for (int j = x; j < x + size; j ++)
{
if(paper[i][j] != first){
is_same = false;
}
}
if(!is_same)
break;
}
if(!is_same)
{
solve(y, x + size / 2, size / 2);
solve(y + size / 2, x, size / 2);
solve(y + size / 2, x + size / 2, size / 2);
solve(y, x, size / 2);
}
else{
if(first == 1){
res_blue ++;
}
else{
res_white ++;
}
}
}
int main(void)
{
ios_base ::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
paper = new int*[n];
for(int i=0; i<n; i++)
{
paper[i] = new int[n];
for(int j=0; j<n; j++)
cin >> paper[i][j];
}
solve(0,0,n);
cout << res_white << '\n' << res_blue << '\n';
return 0;
}
|
29dfb08762cd903ba60739ef7d08121973ab1d27 | 0232b01aef1601ba40c2fa335fa02aefbda7c713 | /src/nearest.cpp | 1e37fb1476b841a2f0fb58c5664c4d0bc707c119 | [] | no_license | mjuric/satools | 9f4975da3964d003da02158faedaad45911d00c1 | ffc787c10240e96d733f226536402958262374ca | refs/heads/master | 2020-05-18T01:54:42.214495 | 2013-12-02T04:52:10 | 2013-12-02T04:52:10 | 3,584,056 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,010 | cpp | nearest.cpp | #include "version.h"
#include <stdlib.h>
#include <fstream>
#include <astro/system/preferences.h>
#include "sloanobservation.h"
using namespace std;
using namespace peyton;
using namespace peyton::coordinates;
peyton::system::Preferences pref;
int main(int argc, char *argv[])
{
PRINT_VERSION_IF_ASKED(argc, argv);
if(argc != 3) {
cout << "Description: Find nearest object in all.in\n";
cout << "Usage: " << argv[0] << " <ra> <dec>\n";
return -1;
}
SkyPoint p;
p.ra = atof(argv[1]) * ctn::d2r;
p.dec = atof(argv[2]) * ctn::d2r;
Radians dist = 1E10;
ifstream f("all.in");
SloanObservation sobs, best;
while(!f.eof()) {
char buf[1000];
f.getline(buf, 1000);
if(!sobs.read(buf)) break;
Radians d = p.distance(sobs.p);
if(d < dist) {
best = sobs;
dist = d;
}
}
cout << "Best match: " << best.run << " " << best.camCol << " " << best.field << " " << best.id << " : "
<< best.p.ra/ctn::d2r << " " << best.p.dec/ctn::d2r << " : " << dist/ctn::s2r << "\n";
}
|
48eb27645f70dd0b36aa53352074009b032c1d48 | 1973f4faf2549e17ed780006a93114ca27f49131 | /src/cpp/core/types/MyriadDateTest.h | b6719b388f2223a3cf281d6420ed3db2a3d2e533 | [] | no_license | TU-Berlin-DIMA/myriad-tests | 7a6d79c469dc8c8604ac753bd8e09734f27673af | 66c760e070c2ee3c0fa626eaf6d1f1320d5a60be | refs/heads/master | 2021-01-15T12:16:13.651337 | 2014-09-19T12:35:03 | 2014-09-19T12:35:03 | 2,559,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,354 | h | MyriadDateTest.h | /*
* This file is part of the myriad-toolkit package.
*
* (c) 2010 Alexander Alexandrov <alexander.s.alexandrov@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#ifndef MYRIADDATETEST_H_
#define MYRIADDATETEST_H_
#include "core/types/MyriadDate.h"
#include <cppunit/TestCaller.h>
#include <cppunit/TestFixture.h>
#include <cppunit/TestSuite.h>
#include <sstream>
using namespace std;
using namespace CppUnit;
namespace Myriad {
class MyriadDateTest: public TestFixture
{
public:
MyriadDateTest()
{
}
void testConstructorsAndSerDeMethods()
{
stringstream ss;
vector<string> dates;
dates.push_back("2011-04-04 07:04:17");
dates.push_back("2011-06-07 08:30:21");
dates.push_back("2011-02-17 11:45:40");
dates.push_back("2011-08-10 16:16:30");
dates.push_back("2011-12-18 20:04:01");
dates.push_back("2012-02-29 20:08:31");
for(vector<string>::const_iterator it = dates.begin(); it != dates.end(); ++it)
{
MyriadDate myriadDate = fromString<MyriadDate>(*it);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Date strings don't match", (*it).substr(0, 10), toString<MyriadDate>(myriadDate));
}
}
void testComparisonOperators()
{
MyriadDate d1("2011-02-03");
MyriadDate d2("2011-02-04");
MyriadDate d3("2011-02-12");
MyriadDate d4("2012-02-12");
MyriadDate d5("2012-03-12");
MyriadDate d6("2012-04-02");
MyriadDate d7("2012-03-29");
MyriadDate d8("2011-02-12");
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d1 < d2);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d2 < d3);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d6 > d7);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d1 <= d2);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d2 <= d3);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d6 >= d7);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d8 <= d3);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d3 <= d8);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d2 != d3);
CPPUNIT_ASSERT_MESSAGE("Wrong comparison", d8 == d3);
}
void testArithmeticOperators()
{
MyriadDate d1("2011-02-03");
MyriadDate d2("2011-02-04");
MyriadDate d3("2011-02-12");
MyriadDate d4("2012-02-12");
MyriadDate d5("2012-03-12");
MyriadDate d6("2012-04-02");
MyriadDate d7("2012-03-29");
MyriadDate t1 = d1 + 1;
MyriadDate t2 = t1 + 8;
MyriadDate t3 = t2 + 365;
MyriadDate t4 = t3 + 29;
MyriadDate t5 = t4 + 21;
MyriadDate t6 = t5 - 4;
int u1 = d2 - d1;
int u2 = d3 - d2;
int u3 = d4 - d3;
int u6 = d7 - d6;
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d1 + 1 == t1 && t1 == d2);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d1 + 9 == t2 && t2 == d3);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d1 + 374 == t3 && t3 == d4);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d1 + 403 == t4 && t4 == d5);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d1 + 424 == t5 && t5 == d6);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d1 + 420 == t6 && t6 == d7);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d2 - d1 == u1 && u1 == 1);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d3 - d2 == u2 && u2 == 8);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d4 - d3 == u3 && u3 == 365);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d4 - d3 == u3 && u3 == 365);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d7 - d6 == u6 && u6 == -4);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", ((t6++)--) == t6);
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", (--(++t6)) == t6);
t6 += 1;
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d1 + 421 == t6);
t6 -= 1;
CPPUNIT_ASSERT_MESSAGE("Wrong arithmetic expression", d1 + 420 == t6);
}
static Test *suite()
{
TestSuite* suite = new TestSuite("MyriadDateTest");
suite->addTest(new TestCaller<MyriadDateTest> ("testConstructorsAndSerDeMethods", &MyriadDateTest::testConstructorsAndSerDeMethods));
suite->addTest(new TestCaller<MyriadDateTest> ("testComparisonOperators", &MyriadDateTest::testComparisonOperators));
suite->addTest(new TestCaller<MyriadDateTest> ("testArithmeticOperators", &MyriadDateTest::testArithmeticOperators));
return suite;
}
private:
};
} // namespace Myriad
#endif /* MYRIADDATETEST_H_ */
|
baa861fbcbe0d4d859561225b75b4cff167158dc | 308f10b13b95252a8816f19798191f19f271e6dc | /test2/main.cpp | 207a64612806c0818dc90022ca0cae8e79efdbf4 | [] | no_license | pierre-amadio/SwordSandBox | 614066c49f754dca0cdc62455fa985a0e044d7c9 | 7810b06a56d1db9e534cc81a5ddc434f3d11c8a4 | refs/heads/master | 2023-01-10T16:16:00.234713 | 2022-12-26T14:32:14 | 2022-12-26T14:32:14 | 132,265,997 | 2 | 0 | null | 2018-05-25T12:55:57 | 2018-05-05T16:37:39 | C++ | UTF-8 | C++ | false | false | 3,138 | cpp | main.cpp | #include <QCoreApplication>
#include <QTextStream>
#include <swmgr.h>
#include <swmodule.h>
#include <markupfiltmgr.h>
using namespace::sword;
QTextStream& qStdOut()
{
static QTextStream ts( stdout );
return ts;
}
int showVerse(const char * bookName, const char * keyName){
SWMgr library(new MarkupFilterMgr(FMT_PLAIN));
SWModule * target;
target = library.getModule(bookName);
if (!target) {
fprintf(stderr, "Could not find module [%s]. Available modules:\n", bookName);
ModMap::iterator it;
for (it = library.Modules.begin(); it != library.Modules.end(); it++) {
fprintf(stderr, "[%s]\t - %s\n", (*it).second->Name(), (*it).second->Description());
}
exit(-1);
}
target->setKey(keyName);
//target->setKey("Jhon 1:1");
target->renderText(); // force an entry lookup first to resolve key to something pretty for printing below.
//std::cout << target->getKeyText() << "\n";
std::cout << target->renderText();
std::cout << "\n";
std::cout << std::endl;
return 0;
}
int main(int argc, char *argv[])
{
QString searchQuery;
QString targetModule;
int searchType;
SWMgr manager;
SWModule *target;
ListKey listkey;
ModMap::iterator it;
// FROM swmodule.h
/*
* >=0 - regex; (for backward compat, if > 0 then used as additional REGEX FLAGS)
* -1 - phrase
* -2 - multiword
* -3 - entryAttrib (eg. Word//Lemma./G1234/) (Lemma with dot means check components (Lemma.[1-9]) also)
* -4 - Lucene
* -5 - multilemma window; set 'flags' param to window size (NOT DONE)
*/
searchType=-4;
//searchQuery="dog";
//searchQuery="strong:G846";
//searchQuery='lemma="strong:H0835"';
searchQuery="strong:H0835";
//searchQuery='morph:"N-NSF"';
targetModule="OSHB";
//targetModule="LXX";
//targetModule="MorphGNT";
//targetModule="FreSegond";
//targetModule="ESV2011";
//manager.setGlobalOption("Greek Accents", "Off");
//manager.setGlobalOption("Strong's Numbers", "Off");
//manager.setGlobalOption("Hebrew Vowel Points", "Off");
//manager.filterText("Greek Accents", searchTerm);
it = manager.Modules.find(targetModule.toStdString().c_str());
if (it == manager.Modules.end()) {
qStdOut() << "No such module: " << targetModule <<"\n";
}
target = (*it).second;
listkey = target->search(searchQuery.toStdString().c_str(), searchType);
while (!listkey.popError()) {
std::cout << (const char *)listkey <<"\n";
//if (listkey.getElement()->userData) std::cout << " : " << (__u64)listkey.getElement()->userData << "%";
showVerse(targetModule.toStdString().c_str(),(const char *) listkey);
std::cout << std::endl;
listkey++;
}
//showVerse(targetModule.toStdString().c_str(),"Mat 1:1");
return 0;
}
|
193b9bfa31428ef34854c40b5cf89e61d3939a16 | c500a6489d2313ba9920565a0b499f5db1efd468 | /Mini-project/Functions/src/ProcessingSrc/freqFilt.cpp | 59a8e5d7b946a7f32803a1bdd48dcc01b77af0c3 | [] | no_license | AndersEllinge/Vision-E17 | 590eb776cfcc6372be2b622a2ea6f335fc028dcd | 6091de51b311fa978e3ca9c4bafb17131d2c3e92 | refs/heads/master | 2021-08-30T06:42:30.194852 | 2017-12-16T15:11:12 | 2017-12-16T15:11:12 | 104,188,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,622 | cpp | freqFilt.cpp | #include <opencv2/opencv.hpp>
#include <iostream>
void dftshift(cv::Mat& mag);
cv::Mat butterHP(cv::Size mag, int order, int d0);
cv::Mat butterLP(cv::Size mag, int order, int d0);
cv::Mat butterBS(cv::Size mag, int order, int d0, float width);
int main(int argc, char* argv[]) {
cv::CommandLineParser parser(argc, argv,
"{@image | ./lena.bmp | image path}"
"{integer | | }"
"{float | | }"
"{buttHP | | }"
"{buttBS | | }"
"{order_1 | | }"
"{d0_1 | | }"
"{order_2 | | }"
"{d0_2 | | }"
"{d0 | | }"
"{d | | }"
"{width | | }"
);
if (parser.has("float")) {
std::cout << "float was set to " << parser.get<float>("float") << std::endl;
}
if (parser.has("integer")) {
std::cout << "integer was set to " << parser.get<int>("integer") << std::endl;
}
// Load image as grayscale
std::string filename = parser.get<std::string>("@image");
cv::Mat img = cv::imread(filename, cv::IMREAD_GRAYSCALE);
if (img.empty()) {
std::cout << "Input image not found at '" << filename << "'\n";
return -1;
}
// Expand the image to an optimal size
cv::Mat padded;
int opt_rows = cv::getOptimalDFTSize(img.rows * 2);
int opt_cols = cv::getOptimalDFTSize(img.cols * 2);
cv::copyMakeBorder(img, padded, 0, opt_rows - img.rows , 0, opt_cols - img.cols, cv::BORDER_CONSTANT, cv::Scalar::all(0));
// Create mat for DFT
cv::Mat planes[] = {cv::Mat_<float>(padded), cv::Mat_<float>::zeros(padded.size())};
cv::Mat complex;
cv::merge(planes, 2, complex);
// Compute DFT and shift
cv::dft(complex, complex);
dftshift(complex);
// If butterworth HP filter
if (parser.has("buttHP") && parser.has("order_1") && parser.has("d0")) {
// Generate butterworth filter
cv::Mat filterHP = butterHP(complex.size(), parser.get<int>("order_1"), parser.get<int>("d0"));
cv::Mat magn, angl, magOut;
cv::Mat planesButtHP[2];
/*
cv::split(filterHP, planesButtHP);
cv::cartToPolar(planesButtHP[0], planesButtHP[1], magn, angl);
magn += cv::Scalar::all(1);
cv::log(magn, magn);
cv::normalize(magn, magn, 0, 1, cv::NORM_MINMAX);
magn.convertTo(magOut, CV_8U, 255);
cv::imwrite("MagnitudeHP.bmp", magOut);*/
// Apply filter to dft
cv::mulSpectrums(filterHP, complex, complex, 0);
cv::split(complex, planesButtHP);
cv::cartToPolar(planesButtHP[0], planesButtHP[1], magn, angl);
magn += cv::Scalar::all(1);
cv::log(magn, magn);
cv::normalize(magn, magn, 0, 1, cv::NORM_MINMAX);
magn.convertTo(magOut, CV_8U, 255);
cv::imwrite("MagnitudeFreqWithHP.bmp", magOut);
// Shift back quadrants
dftshift(complex);
// Restore image with reverse DFT
cv::Mat filtered;
dft(complex,filtered, cv::DFT_INVERSE|cv::DFT_REAL_OUTPUT);
// Normalize and convert to grayscale
cv::normalize(filtered, filtered, 0, 1, cv::NORM_MINMAX);
cv::Mat filteredOut;
filtered.convertTo(filteredOut, CV_8U, 255);
//crop padding
cv::Rect rec(0,0,img.cols,img.rows);
cv::Mat cropImg = filteredOut(rec);
// Save image
cv::imwrite("processed.bmp", cropImg);
return 0;
}
if (parser.has("buttBS") && parser.has("order_1") && parser.has("d0") && parser.has("width")) {
// Generate butterworth filter
cv::Mat filterBS = butterBS(complex.size(), parser.get<int>("order_1"), parser.get<int>("d0"),parser.get<int>("width"));
/*cv::Mat magn, angl, magOut;
cv::Mat planesButtBS[2];
cv::split(filterBS, planesButtBS);
cv::cartToPolar(planesButtBS[0], planesButtBS[1], magn, angl);
magn += cv::Scalar::all(1);
cv::log(magn, magn);
cv::normalize(magn, magn, 0, 1, cv::NORM_MINMAX);
magn.convertTo(magOut, CV_8U, 255);
cv::imwrite("MagnitudeBS.bmp", magOut);*/
// Apply filter to dft
cv::mulSpectrums(filterBS, complex, complex, 0);
/*cv::split(complex, planesButtBS);
cv::cartToPolar(planesButtBS[0], planesButtBS[1], magn, angl);
magn += cv::Scalar::all(1);
cv::log(magn, magn);
cv::normalize(magn, magn, 0, 1, cv::NORM_MINMAX);
magn.convertTo(magOut, CV_8U, 255);
cv::imwrite("MagnitudeFreqWithBS.bmp", magOut);*/
// Shift back quadrants
dftshift(complex);
// Restore image with reverse DFT
cv::Mat filtered;
dft(complex,filtered, cv::DFT_INVERSE|cv::DFT_REAL_OUTPUT);
// Normalize and convert to grayscale
cv::normalize(filtered, filtered, 0, 1, cv::NORM_MINMAX);
cv::Mat filteredOut;
filtered.convertTo(filteredOut, CV_8U, 255);
//crop padding
cv::Rect rec(0,0,img.cols,img.rows);
cv::Mat cropImg = filteredOut(rec);
// Save image
cv::imwrite("processed.bmp", cropImg);
return 0;
}
std::cout << "No filter compatible with imputs" << std::endl;
return 0;
}
void dftshift(cv::Mat& mag) {
int cx = mag.cols / 2;
int cy = mag.rows / 2;
cv::Mat tmp;
cv::Mat q0(mag, cv::Rect(0, 0, cx, cy));
cv::Mat q1(mag, cv::Rect(cx, 0, cx, cy));
cv::Mat q2(mag, cv::Rect(0, cy, cx, cy));
cv::Mat q3(mag, cv::Rect(cx, cy, cx, cy));
q0.copyTo(tmp);
q3.copyTo(q0);
tmp.copyTo(q3);
q1.copyTo(tmp);
q2.copyTo(q1);
tmp.copyTo(q2);
}
cv::Mat butterHP(cv::Size size, int order, int d0) {
cv::Mat_<cv::Vec2f> complex(size);
for (int i = 0; i < complex.rows; i++) {
for (int j = 0; j < complex.cols; j++){
float distance = sqrt(pow(i-(complex.rows/2),2) + pow(j-(complex.cols/2),2));
complex(i,j)[0] = 1/(1+pow(d0/distance,2*order));
complex(i,j)[1] = 0;
}
}
return complex;
}
cv::Mat butterLP(cv::Size size, int order, int d0) {
cv::Mat_<cv::Vec2f> complex(size);
for (int i = 0; i < complex.rows; i++) {
for (int j = 0; j < complex.cols; j++){
float distance = sqrt(pow(i-(complex.rows/2),2) + pow(j-(complex.cols/2),2));
complex(i,j)[0] = 1/(1+pow(distance/d0,2*order));
complex(i,j)[1] = 0;
}
}
return complex;
}
cv::Mat butterBS(cv::Size size, int order, int d0, float width) {
cv::Mat_<cv::Vec2f> complex(size);
for (int i = 0; i < complex.rows; i++) {
for (int j = 0; j < complex.cols; j++){
float distance = sqrt(pow(i-(complex.rows/2),2) + pow(j-(complex.cols/2),2));
complex(i,j)[0] = 1/(1+pow((distance*width)/pow(distance - d0,2),2*order));
complex(i,j)[1] = 0;
}
}
return complex;
}
|
fce507b4520af4ab15efa630ec1a89f36c1f2ed2 | 19d50543968dd8fad21cb6cf703430df7f9dc221 | /test/mpi/matrix.cpp | 7b72f4aeaab033e1da44cfd5ad6eab658b7f46c5 | [
"LicenseRef-scancode-proprietary-license",
"BSD-3-Clause",
"CECILL-2.0",
"MIT",
"LGPL-2.1-only",
"Unlicense",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"CECILL-C",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | ginkgo-project/ginkgo | 53bb384acc3bdcfa0e4a89810fdc4e9390fa4144 | 1100cbd2d86a9aa7388f1ace6aae2466e3bdf518 | refs/heads/develop | 2023-08-31T06:54:12.481543 | 2023-08-30T12:28:15 | 2023-08-30T12:28:15 | 117,122,510 | 352 | 102 | BSD-3-Clause | 2023-09-13T15:56:48 | 2018-01-11T16:14:21 | C++ | UTF-8 | C++ | false | false | 22,141 | cpp | matrix.cpp | /*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2023, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#include <array>
#include <memory>
#include <random>
#include <mpi.h>
#include <gtest/gtest.h>
#include <ginkgo/config.hpp>
#include <ginkgo/core/base/array.hpp>
#include <ginkgo/core/base/matrix_data.hpp>
#include <ginkgo/core/distributed/matrix.hpp>
#include <ginkgo/core/distributed/partition.hpp>
#include <ginkgo/core/distributed/vector.hpp>
#include <ginkgo/core/log/logger.hpp>
#include <ginkgo/core/matrix/csr.hpp>
#include "core/test/utils.hpp"
#include "test/utils/mpi/executor.hpp"
#ifndef GKO_COMPILING_DPCPP
template <typename ValueLocalGlobalIndexType>
class MatrixCreation : public CommonMpiTestFixture {
protected:
using value_type = typename std::tuple_element<
0, decltype(ValueLocalGlobalIndexType())>::type;
using local_index_type = typename std::tuple_element<
1, decltype(ValueLocalGlobalIndexType())>::type;
using global_index_type = typename std::tuple_element<
2, decltype(ValueLocalGlobalIndexType())>::type;
using dist_mtx_type =
gko::experimental::distributed::Matrix<value_type, local_index_type,
global_index_type>;
using dist_vec_type = gko::experimental::distributed::Vector<value_type>;
using local_matrix_type = gko::matrix::Csr<value_type, local_index_type>;
using Partition =
gko::experimental::distributed::Partition<local_index_type,
global_index_type>;
using matrix_data = gko::matrix_data<value_type, global_index_type>;
MatrixCreation()
: size{5, 5},
mat_input{size,
{{0, 1, 1},
{0, 3, 2},
{1, 1, 3},
{1, 2, 4},
{2, 1, 5},
{2, 2, 6},
{3, 3, 8},
{3, 4, 7},
{4, 0, 9},
{4, 4, 10}}},
dist_input{{{size, {{0, 1, 1}, {0, 3, 2}, {1, 1, 3}, {1, 2, 4}}},
{size, {{2, 1, 5}, {2, 2, 6}, {3, 3, 8}, {3, 4, 7}}},
{size, {{4, 0, 9}, {4, 4, 10}}}}},
engine(42)
{
row_part = Partition::build_from_contiguous(
exec, gko::array<global_index_type>(
exec, I<global_index_type>{0, 2, 4, 5}));
col_part = Partition::build_from_mapping(
exec,
gko::array<gko::experimental::distributed::comm_index_type>(
exec,
I<gko::experimental::distributed::comm_index_type>{1, 1, 2, 0,
0}),
3);
dist_mat = dist_mtx_type::create(exec, comm);
}
void SetUp() override { ASSERT_EQ(comm.size(), 3); }
gko::dim<2> size;
std::shared_ptr<Partition> row_part;
std::shared_ptr<Partition> col_part;
gko::matrix_data<value_type, global_index_type> mat_input;
std::array<matrix_data, 3> dist_input;
std::unique_ptr<dist_mtx_type> dist_mat;
std::default_random_engine engine;
};
TYPED_TEST_SUITE(MatrixCreation, gko::test::ValueLocalGlobalIndexTypes,
TupleTypenameNameGenerator);
TYPED_TEST(MatrixCreation, ReadsDistributedGlobalData)
{
using value_type = typename TestFixture::value_type;
using csr = typename TestFixture::local_matrix_type;
I<I<value_type>> res_local[] = {{{0, 1}, {0, 3}}, {{6, 0}, {0, 8}}, {{10}}};
I<I<value_type>> res_non_local[] = {
{{0, 2}, {4, 0}}, {{5, 0}, {0, 7}}, {{9}}};
auto rank = this->dist_mat->get_communicator().rank();
this->dist_mat->read_distributed(this->mat_input, this->row_part);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(this->dist_mat->get_local_matrix()),
res_local[rank], 0);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(this->dist_mat->get_non_local_matrix()),
res_non_local[rank], 0);
}
TYPED_TEST(MatrixCreation, ReadsDistributedLocalData)
{
using value_type = typename TestFixture::value_type;
using csr = typename TestFixture::local_matrix_type;
I<I<value_type>> res_local[] = {{{0, 1}, {0, 3}}, {{6, 0}, {0, 8}}, {{10}}};
I<I<value_type>> res_non_local[] = {
{{0, 2}, {4, 0}}, {{5, 0}, {0, 7}}, {{9}}};
auto rank = this->dist_mat->get_communicator().rank();
this->dist_mat->read_distributed(this->dist_input[rank], this->row_part);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(this->dist_mat->get_local_matrix()),
res_local[rank], 0);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(this->dist_mat->get_non_local_matrix()),
res_non_local[rank], 0);
}
TYPED_TEST(MatrixCreation, ReadsDistributedWithColPartition)
{
using value_type = typename TestFixture::value_type;
using csr = typename TestFixture::local_matrix_type;
I<I<value_type>> res_local[] = {{{2, 0}, {0, 0}}, {{0, 5}, {0, 0}}, {{0}}};
I<I<value_type>> res_non_local[] = {
{{1, 0}, {3, 4}}, {{0, 0, 6}, {8, 7, 0}}, {{10, 9}}};
auto rank = this->dist_mat->get_communicator().rank();
this->dist_mat->read_distributed(this->mat_input, this->row_part,
this->col_part);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(this->dist_mat->get_local_matrix()),
res_local[rank], 0);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(this->dist_mat->get_non_local_matrix()),
res_non_local[rank], 0);
}
#endif
template <typename ValueType>
class Matrix : public CommonMpiTestFixture {
public:
using value_type = ValueType;
using local_index_type = gko::int32;
using global_index_type = gko::int64;
using part_type =
gko::experimental::distributed::Partition<local_index_type,
global_index_type>;
using csr_mtx_type = gko::matrix::Csr<value_type, global_index_type>;
using dist_mtx_type =
gko::experimental::distributed::Matrix<value_type, local_index_type,
global_index_type>;
using dist_vec_type = gko::experimental::distributed::Vector<value_type>;
using local_matrix_type = gko::matrix::Csr<value_type, local_index_type>;
using dense_vec_type = gko::matrix::Dense<value_type>;
using matrix_data = gko::matrix_data<value_type, global_index_type>;
Matrix() : size{5, 5}, engine()
{
row_part = part_type::build_from_contiguous(
exec, gko::array<global_index_type>(
exec, I<global_index_type>{0, 2, 4, 5}));
col_part = part_type::build_from_mapping(
exec,
gko::array<gko::experimental::distributed::comm_index_type>(
exec,
I<gko::experimental::distributed::comm_index_type>{1, 1, 2, 0,
0}),
3);
dist_mat = dist_mtx_type::create(exec, comm);
dist_mat_large = dist_mtx_type::create(exec, comm);
x = dist_vec_type::create(ref, comm);
y = dist_vec_type::create(ref, comm);
csr_mat = csr_mtx_type::create(exec);
dense_x = dense_vec_type::create(exec);
dense_y = dense_vec_type::create(exec);
gko::matrix_data<value_type, global_index_type> mat_input{
size,
// clang-format off
{{0, 1, 1}, {0, 3, 2}, {1, 1, 3}, {1, 2, 4}, {2, 1, 5},
{2, 2, 6}, {3, 3, 8}, {3, 4, 7}, {4, 0, 9}, {4, 4, 10}}
// clang-format on
};
dist_mat->read_distributed(mat_input, this->row_part, this->col_part);
csr_mat->read(mat_input);
alpha = gko::test::generate_random_matrix<dense_vec_type>(
1, 1, std::uniform_int_distribution<gko::size_type>(1, 1),
std::normal_distribution<gko::remove_complex<value_type>>(),
this->engine, this->exec);
beta = gko::test::generate_random_matrix<dense_vec_type>(
1, 1, std::uniform_int_distribution<gko::size_type>(1, 1),
std::normal_distribution<gko::remove_complex<value_type>>(),
this->engine, this->exec);
}
void SetUp() override { ASSERT_EQ(comm.size(), 3); }
void assert_local_vector_equal_to_global_vector(const dist_vec_type* dist,
const dense_vec_type* dense,
const part_type* part,
int rank)
{
auto host_part = gko::clone(this->ref, part);
auto range_bounds = host_part->get_range_bounds();
auto part_ids = host_part->get_part_ids();
std::vector<global_index_type> gather_idxs;
for (gko::size_type range_id = 0;
range_id < host_part->get_num_ranges(); ++range_id) {
if (part_ids[range_id] == rank) {
for (global_index_type global_row = range_bounds[range_id];
global_row < range_bounds[range_id + 1]; ++global_row) {
gather_idxs.push_back(global_row);
}
}
}
gko::array<global_index_type> gather_idxs_view(
this->exec, gather_idxs.begin(), gather_idxs.end());
auto gathered_local = dense->row_gather(&gather_idxs_view);
GKO_ASSERT_MTX_NEAR(dist->get_local_vector(), gathered_local,
r<value_type>::value);
}
void init_large(gko::size_type num_rows, gko::size_type num_cols)
{
auto rank = comm.rank();
int num_parts = comm.size();
auto vec_md = gko::test::generate_random_matrix_data<value_type,
global_index_type>(
num_rows, num_cols,
std::uniform_int_distribution<int>(static_cast<int>(num_cols),
static_cast<int>(num_cols)),
std::normal_distribution<gko::remove_complex<value_type>>(),
engine);
auto mat_md = gko::test::generate_random_matrix_data<value_type,
global_index_type>(
num_rows, num_rows,
std::uniform_int_distribution<int>(0, static_cast<int>(num_rows)),
std::normal_distribution<gko::remove_complex<value_type>>(),
engine);
auto row_mapping = gko::test::generate_random_array<
gko::experimental::distributed::comm_index_type>(
num_rows, std::uniform_int_distribution<int>(0, num_parts - 1),
engine, exec);
auto col_mapping = gko::test::generate_random_array<
gko::experimental::distributed::comm_index_type>(
num_rows, std::uniform_int_distribution<int>(0, num_parts - 1),
engine, exec);
row_part_large =
part_type::build_from_mapping(exec, row_mapping, num_parts);
col_part_large =
part_type::build_from_mapping(exec, col_mapping, num_parts);
dist_mat_large->read_distributed(mat_md, row_part_large,
col_part_large);
csr_mat->read(mat_md);
x->read_distributed(vec_md, col_part_large);
dense_x->read(vec_md);
y->read_distributed(vec_md, row_part_large);
dense_y->read(vec_md);
}
gko::dim<2> size;
std::unique_ptr<part_type> row_part;
std::unique_ptr<part_type> col_part;
std::unique_ptr<part_type> row_part_large;
std::unique_ptr<part_type> col_part_large;
std::unique_ptr<dist_mtx_type> dist_mat;
std::unique_ptr<dist_mtx_type> dist_mat_large;
std::unique_ptr<csr_mtx_type> csr_mat;
std::unique_ptr<dist_vec_type> x;
std::unique_ptr<dist_vec_type> y;
std::unique_ptr<dense_vec_type> dense_x;
std::unique_ptr<dense_vec_type> dense_y;
std::unique_ptr<dense_vec_type> alpha;
std::unique_ptr<dense_vec_type> beta;
std::default_random_engine engine;
};
TYPED_TEST_SUITE(Matrix, gko::test::ValueTypes, TypenameNameGenerator);
TYPED_TEST(Matrix, CanApplyToSingleVector)
{
using value_type = typename TestFixture::value_type;
using index_type = typename TestFixture::global_index_type;
auto vec_md = gko::matrix_data<value_type, index_type>{
I<I<value_type>>{{1}, {2}, {3}, {4}, {5}}};
I<I<value_type>> result[3] = {{{10}, {18}}, {{28}, {67}}, {{59}}};
auto rank = this->comm.rank();
this->x->read_distributed(vec_md, this->col_part);
this->y->read_distributed(vec_md, this->row_part);
this->dist_mat->apply(this->x, this->y);
GKO_ASSERT_MTX_NEAR(this->y->get_local_vector(), result[rank], 0);
}
TYPED_TEST(Matrix, CanApplyToMultipleVectors)
{
using value_type = typename TestFixture::value_type;
using index_type = typename TestFixture::global_index_type;
auto vec_md = gko::matrix_data<value_type, index_type>{
I<I<value_type>>{{1, 11}, {2, 22}, {3, 33}, {4, 44}, {5, 55}}};
I<I<value_type>> result[3] = {
{{10, 110}, {18, 198}}, {{28, 308}, {67, 737}}, {{59, 649}}};
auto rank = this->comm.rank();
this->x->read_distributed(vec_md, this->col_part);
this->y->read_distributed(vec_md, this->row_part);
this->dist_mat->apply(this->x, this->y);
GKO_ASSERT_MTX_NEAR(this->y->get_local_vector(), result[rank], 0);
}
TYPED_TEST(Matrix, CanAdvancedApplyToSingleVector)
{
using value_type = typename TestFixture::value_type;
using index_type = typename TestFixture::global_index_type;
using dense_vec_type = typename TestFixture::dense_vec_type;
auto vec_md = gko::matrix_data<value_type, index_type>{
I<I<value_type>>{{1}, {2}, {3}, {4}, {5}}};
I<I<value_type>> result[3] = {{{17}, {30}}, {{47}, {122}}, {{103}}};
auto rank = this->comm.rank();
this->alpha = gko::initialize<dense_vec_type>({2.0}, this->exec);
this->beta = gko::initialize<dense_vec_type>({-3.0}, this->exec);
this->x->read_distributed(vec_md, this->col_part);
this->y->read_distributed(vec_md, this->row_part);
this->dist_mat->apply(this->alpha, this->x, this->beta, this->y);
GKO_ASSERT_MTX_NEAR(this->y->get_local_vector(), result[rank], 0);
}
TYPED_TEST(Matrix, CanApplyToSingleVectorLarge)
{
this->init_large(100, 1);
this->dist_mat_large->apply(this->x, this->y);
this->csr_mat->apply(this->dense_x, this->dense_y);
this->assert_local_vector_equal_to_global_vector(
this->y.get(), this->dense_y.get(), this->row_part_large.get(),
this->comm.rank());
}
TYPED_TEST(Matrix, CanApplyToMultipleVectorsLarge)
{
this->init_large(100, 17);
this->dist_mat_large->apply(this->x, this->y);
this->csr_mat->apply(this->dense_x, this->dense_y);
this->assert_local_vector_equal_to_global_vector(
this->y.get(), this->dense_y.get(), this->row_part_large.get(),
this->comm.rank());
}
TYPED_TEST(Matrix, CanAdvancedApplyToMultipleVectorsLarge)
{
this->init_large(100, 17);
this->dist_mat_large->apply(this->alpha, this->x, this->beta, this->y);
this->csr_mat->apply(this->alpha, this->dense_x, this->beta, this->dense_y);
this->assert_local_vector_equal_to_global_vector(
this->y.get(), this->dense_y.get(), this->row_part_large.get(),
this->comm.rank());
}
TYPED_TEST(Matrix, CanConvertToNextPrecision)
{
using T = typename TestFixture::value_type;
using csr = typename TestFixture::local_matrix_type;
using local_index_type = typename TestFixture::local_index_type;
using global_index_type = typename TestFixture::global_index_type;
using OtherT = typename gko::next_precision<T>;
using OtherDist = typename gko::experimental::distributed::Matrix<
OtherT, local_index_type, global_index_type>;
auto tmp = OtherDist::create(this->ref, this->comm);
auto res = TestFixture::dist_mtx_type::create(this->ref, this->comm);
// If OtherT is more precise: 0, otherwise r
auto residual = r<OtherT>::value < r<T>::value
? gko::remove_complex<T>{0}
: gko::remove_complex<T>{r<OtherT>::value};
this->dist_mat->convert_to(tmp);
tmp->convert_to(res);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(this->dist_mat->get_local_matrix()),
gko::as<csr>(res->get_local_matrix()), residual);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(this->dist_mat->get_non_local_matrix()),
gko::as<csr>(res->get_non_local_matrix()), residual);
}
TYPED_TEST(Matrix, CanMoveToNextPrecision)
{
using T = typename TestFixture::value_type;
using csr = typename TestFixture::local_matrix_type;
using local_index_type = typename TestFixture::local_index_type;
using global_index_type = typename TestFixture::global_index_type;
using OtherT = typename gko::next_precision<T>;
using OtherDist = typename gko::experimental::distributed::Matrix<
OtherT, local_index_type, global_index_type>;
auto tmp = OtherDist::create(this->ref, this->comm);
auto res = TestFixture::dist_mtx_type::create(this->ref, this->comm);
auto clone_dist_mat = gko::clone(this->dist_mat);
// If OtherT is more precise: 0, otherwise r
auto residual = r<OtherT>::value < r<T>::value
? gko::remove_complex<T>{0}
: gko::remove_complex<T>{r<OtherT>::value};
this->dist_mat->move_to(tmp);
tmp->convert_to(res);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(clone_dist_mat->get_local_matrix()),
gko::as<csr>(res->get_local_matrix()), residual);
GKO_ASSERT_MTX_NEAR(gko::as<csr>(clone_dist_mat->get_non_local_matrix()),
gko::as<csr>(res->get_non_local_matrix()), residual);
}
bool needs_transfers(std::shared_ptr<const gko::Executor> exec)
{
return exec->get_master() != exec &&
!gko::experimental::mpi::is_gpu_aware();
}
class HostToDeviceLogger : public gko::log::Logger {
public:
void on_copy_started(const gko::Executor* exec_from,
const gko::Executor* exec_to,
const gko::uintptr& loc_from,
const gko::uintptr& loc_to,
const gko::size_type& num_bytes) const override
{
if (exec_from != exec_to) {
transfer_count_++;
}
}
int get_transfer_count() const { return transfer_count_; }
static std::unique_ptr<HostToDeviceLogger> create()
{
return std::unique_ptr<HostToDeviceLogger>(new HostToDeviceLogger());
}
protected:
explicit HostToDeviceLogger()
: gko::log::Logger(gko::log::Logger::copy_started_mask)
{}
private:
mutable int transfer_count_ = 0;
};
class MatrixGpuAwareCheck : public CommonMpiTestFixture {
public:
using local_index_type = gko::int32;
using global_index_type = gko::int64;
using dist_mtx_type =
gko::experimental::distributed::Matrix<value_type, local_index_type,
global_index_type>;
using dist_vec_type = gko::experimental::distributed::Vector<value_type>;
using dense_vec_type = gko::matrix::Dense<value_type>;
MatrixGpuAwareCheck()
: logger(gko::share(HostToDeviceLogger::create())), engine(42)
{
exec->add_logger(logger);
mat = dist_mtx_type::create(exec, comm);
x = dist_vec_type::create(exec, comm);
y = dist_vec_type::create(exec, comm);
alpha = dense_vec_type::create(exec, gko::dim<2>{1, 1});
beta = dense_vec_type::create(exec, gko::dim<2>{1, 1});
}
std::unique_ptr<dist_mtx_type> mat;
std::unique_ptr<dist_vec_type> x;
std::unique_ptr<dist_vec_type> y;
std::unique_ptr<dense_vec_type> alpha;
std::unique_ptr<dense_vec_type> beta;
std::shared_ptr<HostToDeviceLogger> logger;
std::default_random_engine engine;
};
TEST_F(MatrixGpuAwareCheck, ApplyCopiesToHostOnlyIfNecessary)
{
auto transfer_count_before = logger->get_transfer_count();
mat->apply(x, y);
ASSERT_EQ(logger->get_transfer_count() > transfer_count_before,
needs_transfers(exec));
}
TEST_F(MatrixGpuAwareCheck, AdvancedApplyCopiesToHostOnlyIfNecessary)
{
auto transfer_count_before = logger->get_transfer_count();
mat->apply(alpha, x, beta, y);
ASSERT_EQ(logger->get_transfer_count() > transfer_count_before,
needs_transfers(exec));
}
|
8ea325c219d1f4db0cdfe9d93aaef2f368a1fbc9 | 9034cbe768c368a01f4b3870ef13e7eb920e6d1f | /тренировка/main.cpp | 3e359d1e0b87490e7327d0ba20ebb36e664b92dc | [] | no_license | Gerasimets/High-Level-Languages | 0c8d5a37803f6df969929961539e97d262b9abc5 | 96dd756edc67daff0e1f9c0d3f8adaf2225eb5e4 | refs/heads/master | 2020-09-21T04:30:34.397184 | 2020-04-03T13:10:23 | 2020-04-03T13:10:23 | 224,678,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,633 | cpp | main.cpp | #include <iostream>
// элемент списка
struct list_element
{
int value; // значение данного элемента списка
list_element* next; // указатель на следующий элемент списка
list_element* prev; // указатель на предыдущий элемент списка
};
// список
class list
{
public:
// данные
list_element* begin; // указатель на первый элемент списка
list_element* end; // указатель на последний элемент списка
size_t size; // количество элементов в списке
// конструктор
list();
// функции
bool empty() const; // функция проверяет, пуст ли список
void push_back(int new_value); // добавление элемента в конец списка
void push_front(int new_value); // добавление в начало списка
void pop_back(); // удаление последнего элемента
void pop_front(); // удаление первого элемента
int back() const; // возвращает значение последнего элемента
int front() const; // возвращает значение первого элемента
};
// this - указатель на объект, который вызвал данную фунцию
list::list() //конструктор
{
begin = nullptr;
end = nullptr;
size = 0;
}
// функция проверяет, пуст ли список
bool list::empty() const
{
if (size == 0) return 1;
return 0;
}
// добавление элемента в конец списка
void list::push_back(int new_value)
{
list_element* new_element = new list_element; // выделить память под переменную типа list_element и присвоить адрес
// начала выделенной памяти в переменную-указатель new_element
new_element->value = new_value; // пойти по указателю new_element, получить переменную типа list_element, которая там находится
// и в ней изменить поле value
new_element->next = nullptr; // добавляем в конец, поэтому следующего элемента нет
// если список не пустой
if (!empty())
{
end->next = new_element; // прежний последний элемент списка теперь указвывает на новый элемент
new_element->prev = end; //указатель на предыдущий элемент указывает на прошлый последний элемент
}
// если список пустой
else begin = new_element; // новый элемент является началом списка
end = new_element; // новый элемент теперь является концом списка
size++; // размер списка увеличился на единицу
}
// добавление в начало списка
void list::push_front(int new_value)
{
list_element* new_element = new list_element; // выделить память под переменную типа list_element и присвоить адрес
// начала выделенной памяти в переменную-указатель new_element
new_element->value = new_value; // пойти по указателю new_element, получить переменную типа list_element, которая там находится
// и в ней изменить поле value
new_element->next = begin; // теперь указателю на следующий элемент списка присваивается прошлый первый элемент списка
new_element->prev = nullptr; //указатель на предыдущий элемент пустой, так как добавляем первый элемент
begin = new_element; // новый элемент является началом списка
//если список не пустой
if (!empty()) begin->prev = new_element; //
//если список пустой
if (empty()) end = new_element; // новый элемент теперь является концом списка
size++; // размер списка увеличился на единицу
}
// удаление последнего элемента, возвращает значение этого элемента
void list::pop_back()
{
list_element* del_element = end; // переменная-указатель(предыдущий элемент) типа list_element указывает на предпоследний элемент списка
if (size != 1)
{
//end = end->prev; //указателю на последний элемент присваиваем предпоследний элемент
end = del_element->prev; //указатель на последний элемент теперь указывает на предпоследний
//предпоследний элемент теперь является концом списка
del_element->next = nullptr;
delete del_element;
}
else
{
delete del_element;
begin = nullptr;
end = nullptr;
}
size--;
}
//удаление первого элемента
void list::pop_front()
{
list_element* element_to_delete = begin;
begin = begin->next;
if (size==1) end = nullptr;
delete element_to_delete;
size--;
}
int list::back() const
{
return end->value;
}
int list::front() const
{
return begin->value;
}
int main()
{
list MyList;
MyList.push_back(7);
MyList.push_back(11);
MyList.push_back(17);
MyList.push_back(25);
MyList.push_front(3);
MyList.push_front(1);
if (!MyList.empty()) std::cout << MyList.back() << '\n';
MyList.pop_back();
if (!MyList.empty()) std::cout << MyList.back() << '\n';
MyList.pop_back();
if (!MyList.empty()) std::cout << MyList.back() << '\n';
MyList.pop_back();
if (!MyList.empty()) std::cout << MyList.back() << '\n';
MyList.pop_back();
if (!MyList.empty()) std::cout << MyList.back() << '\n';
MyList.pop_back();
if (!MyList.empty()) std::cout << MyList.back() << '\n';
MyList.pop_back();
if (!MyList.empty()) std::cout << MyList.back() << '\n';
}
|
f1ced81e646bbde9bed19ef9625928c17589ea20 | a70717537de46baab92d52e817fb626c18c1f9d1 | /Sobol_Lab_2.1/main.cpp | a70c3aeb1dc73813fafda7a34badb6cc1fb9fd66 | [] | no_license | kasobol/Lab_2_sem_3 | e361661f19611938b0c8a593502182807db57a4b | 6c7521a5284ba7a98f9b6207109c1484f8947b80 | refs/heads/master | 2023-03-03T00:46:14.100215 | 2021-02-08T08:00:06 | 2021-02-08T08:00:06 | 337,000,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,597 | cpp | main.cpp |
#include <iostream>
#include <ctime>
#include "Person.h"
#include "Dictionary.h"
#include "Sequence.h"
#include "LinkedListSequence.h"
#include "ArraySequence.h"
#include "Tests.h"
using namespace std;
int GetPlace(int* mas,int key, int size)
{
int start_binary_search = 0;
int end_binary_search = size - 1;
int tmp;
while (end_binary_search - start_binary_search != -1)
{
tmp = (start_binary_search + end_binary_search) / 2;
if (key < mas[tmp])
{
end_binary_search = tmp - 1;
}
else
{
start_binary_search = tmp + 1;
}
}
return start_binary_search;
}
void Little_Change(int* mas, int m, int size)
{
int place = GetPlace(mas, m, size);
for (int i = size; i > place; i--)
{
mas[i] = mas[i - 1];
}
mas[place] = m;
}
void Show_Histogram(Dictionary<int, int>* dict, int* splitting, int size)
{
cout << "Histogram: " << endl;
for (int i = 0; i < size - 1; i++)
{
cout << "[" << splitting[i] << ", " << splitting[i + 1] << ") --- " << dict->Get1(splitting[i]) << endl;
}
cout << endl;
}
Dictionary<int, int>* Histogram_BinaryTree(Sequence<Person>* seq, int* splitting, int size)
{
Dictionary<int, int>* res = new BinaryTree<int, int>();
int* values = new int[size];
for (int i = 0; i < size; i++)
{
values[i] = 0;
}
for (int i = 0; i < seq->GetLength(); i++)
{
for (int j = 0; j < size - 1; j++)
{
if (seq->Get(i).GetAge(2020) < splitting[j + 1] && seq->Get(i).GetAge(2020) >= splitting[j])
{
values[j] = values[j] + 1;
}
}
}
int* mas = new int[size] { 0, (size - 1) / 2, size - 1 };
int size_mas = 3;
res->Add(splitting[mas[1]], values[mas[1]]);
while (size_mas != size)
{
for (int i = 1; i < size_mas; i++)
{
if (mas[i] - mas[i - 1] > 1)
{
int m = (mas[i] + mas[i - 1]) / 2;
res->Add(splitting[m], values[m]);
Little_Change(mas, m, size_mas);
size_mas++;
i++;
}
}
}
res->Add(splitting[0], values[0]);
res->Add(splitting[size - 1], values[size - 1]);
return res;
}
Dictionary<int, int>* Histogram_BTree(Sequence<Person>* seq, int* splitting, int size, int number_tree)
{
Dictionary<int, int>* res = new BTree<int, int>(number_tree);
int* values = new int[size];
for (int i = 0; i < size; i++)
{
values[i] = 0;
}
for (int i = 0; i < seq->GetLength(); i++)
{
for (int j = 0; j < size - 1; j++)
{
if (seq->Get(i).GetAge(2020) < splitting[j + 1] && seq->Get(i).GetAge(2020) >= splitting[j])
{
values[j] = values[j] + 1;
}
}
}
for (int i = 0; i < size; i++)
{
res->Add(splitting[i], values[i]);
}
return res;
}
int main()
{
Test_BinTree_Add();
Test_BinTree_Get();
Test_BinTree_Remove();
Test_BinTree_Change();
Test_BTree_Add();
Test_BTree_Get();
Test_BTree_Remove();
Test_BTree_Change();
Test_Histogram();
string str;
cout << "\nIf you want to use - press \"e\", else - press \"p\"\n";
cin >> str;
if (str != "e")
{
cout << "\nGOODbye";
return 0;
}
char fun;
do
{
system("color 7");
try
{
cout << "\nEnter: 0 - Check BinaryTree, 1 - Check BTree, 2 - Check Histogram";
cin >> fun;
Dictionary<int, int>* dict;
int size;
cout << "Enter size: ";
cin >> size;
switch (fun)
{
case '0':
{
dict = new BinaryTree<int, int>();
for (int i = 0; i < size; i++)
{
dict->Add(rand() % 1000, rand() % 1000);
}
dict->Print();
do
{
cout << "\nEnter: 0 - Add(key, value), 1 - Get(key), 2 - Remove(key)";
cin >> fun;
switch (fun)
{
case '0':
{
int key, value;
cin >> key >> value;
dict->Add(key, value);
cout << "\nAdd(" << key << ", " << value << ")" << endl;
dict->Print();
}
break;
case '1':
{
int key;
cin >> key;
cout << "\nGet(" << key << ") = " << dict->Get1(key) << endl;
}
break;
case '2':
{
int key;
cin >> key;
dict->Remove(key);
cout << "\nRemove(" << key << ")" << endl;
dict->Print();
}
break;
}
cout << "\nIf you want to exit from this - press \"e\", else - press \"p\"";
cin >> str;
} while (str != "e");
delete dict;
}
break;
case '1':
{
int number_tree;
cout << "\nBTree_Level: ";
cin >> number_tree;
dict = new BTree<int, int>(number_tree);
for (int i = 0; i < size; i++)
{
dict->Add(rand() % 1000, rand() % 1000);
}
dict->Print();
do
{
cout << "\nEnter: 0 - Add(key, value), 1 - Get(key), 2 - Remove(key)";
cin >> fun;
switch (fun)
{
case '0':
{
int key, value;
cin >> key >> value;
dict->Add(key, value);
cout << "\nAdd(" << key << ", " << value << ")" << endl;
dict->Print();
}
break;
case '1':
{
int key;
cin >> key;
cout << "\nGet(" << key << ") = " << dict->Get1(key) << endl;
}
break;
case '2':
{
int key;
cin >> key;
dict->Remove(key);
cout << "\nRemove(" << key << ")" << endl;
dict->Print();
}
break;
}
cout << "\nIf you want to exit from this - press \"e\", else - press \"p\"";
cin >> str;
} while (str != "e");
delete dict;
}
break;
case '2':
{
Sequence<Person>* seq = new ArraySequence<Person>(size);
do
{
dict = nullptr;
cout << "\nWhat do you want to use?: Enter: 0 - BinaryTree, 1 - BTree";
cin >> fun;
cout << "Inputed Age of Person: ";
for (int i = 0; i < size; i++)
{
seq->InsertAt(Person("", "", "", rand() % 2020), i);
cout << seq->Get(i).GetAge(2020) << " ";
}
cout << "\n\n";
int leng = 20;
int* splitting = new int[leng] { 0, 50, 70, 200, 240, 270, 500, 700, 900, 1150, 1350, 1500, 1600, 1700, 1750, 1800, 1900, 1950, 2000, 2020 };
cout << "Splitting: ";
for (int i = 0; i < leng; i++)
{
cout << splitting[i] << " ";
}
cout << "\n\n";
switch (fun)
{
case '0':
{
dict = Histogram_BinaryTree(seq, splitting, leng);
}
break;
case '1':
{
int number_tree;
cout << "\nBTree_Level: ";
cin >> number_tree;
dict = Histogram_BTree(seq, splitting, leng, number_tree);
}
break;
}
dict->Print();
Show_Histogram(dict, splitting, leng);
cout << "If you want to Get(key) value, press - \"e\", else - \"p\"" << endl;
cin >> str;
while (str != "p")
{
int key;
cin >> key;
cout << "\nGet(" << key << ") = " << dict->Get1(key) << endl;
cout << "If you want to Get(key) value, press - \"e\", else - \"p\"" << endl;
cin >> str;
}
cout << "\nIf you want to exit from this - press \"e\", else - press \"p\"";
cin >> str;
} while (str != "e");
delete dict;
}
break;
}
}
catch (exception ex)
{
system("color 4");
cout << "\n" << "ERROR !!!";
cout << "\n" << ex.what() << endl;
}
cout << "\nIf you want to exit - press \"e\", else - press \"p\"" << endl;
cin >> str;
} while (str != "e");
cout << "\nGOODbye\n" << endl;
//srand(time(0));
/*Sequence<Person>* seq = new ArraySequence<Person>(30);
for (int i = 0; i < seq->GetLength(); i++)
{
seq->InsertAt(Person("", "", "", rand() % 2020), i);
}
for (int i = 0; i < seq->GetLength(); i++)
{
cout << seq->Get(i).GetAge(2020) << endl;
}
int* splitting = new int[10]{ 0, 20, 50, 70, 500, 1000, 1500, 2000, 2010, 2020 };
auto res = Histogram_BinaryTree(seq, splitting, 10);
res->Print();
auto tres = Histogram_BTree(seq, splitting, 10, 4);
tres->Print();*/
}
|
94f8619b685fcaa172335a4bf09e90896f99665d | e67b65f9b0c5fa8215d92513e08fc97c8de23878 | /src/PriceCalculator/PriceCalculatorHarrasNoise.cpp | 78ec56b39f268afa402b4285c04713a68742ca30 | [
"BSD-3-Clause"
] | permissive | SABCEMM/SABCEMM | 25e55c9ff06717b78a038130337f75b4affccc6b | a87ea83b57a8a7d16591abe30e56db459e710a0e | refs/heads/master | 2018-12-20T05:43:41.085513 | 2018-12-12T09:29:23 | 2018-12-12T09:29:23 | 107,384,335 | 18 | 1 | null | 2018-01-02T14:37:31 | 2017-10-18T09:07:11 | C++ | UTF-8 | C++ | false | false | 4,220 | cpp | PriceCalculatorHarrasNoise.cpp | /* Copyright 2017 - BSD-3-Clause
*
* Copyright Holder (alphabetical):
*
* Beikirch, Maximilian
* Cramer, Simon
* Frank, Martin
* Otte, Philipp
* Pabich, Emma
* Trimborn, Torsten
*
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* @author Beikirch, Cramer, Pabich
* @date 08 Nov 2017
* @brief This file belongs to the SABCEMM projekt. See github.com/SABCEMM/SABCEMM
*/
#include <cmath>
#include <cassert>
#include "PriceCalculatorHarrasNoise.h"
/** Standarddestructor
*/
PriceCalculatorHarrasNoise::~PriceCalculatorHarrasNoise() = default;
/** Calculate the new Price according to the paper "How to grow a bubble: A model of myopic adapting agents" by
* Georges Harras and Didier Sornette. ExcessDemandCalculator is called first.
*/
void PriceCalculatorHarrasNoise::stepCalculate() {
assert(excessDemandCalculator != nullptr);
assert(excessDemand != nullptr);
assert(price != nullptr);
//TODO: Mit PriceCalculatorHarras zusammenfassen. Als Noise Mode einfach None oder Original einführen.
excessDemandCalculator->stepCalculate();
double oldPrice = price->getPrice();
double eta = 0;
randomGenerator->getNormalRandomDouble(0,1,&eta);
switch(mode)
{
case ADD:
price->setPrice( exp(log(oldPrice) + deltaT->getDeltaT() * excessDemand->getExcessDemand()
/ marketDepth + constant * eta) );
break;
case MULT: //Angelehnt an Cross
price->setPrice( exp(log(oldPrice) + deltaT->getDeltaT() * excessDemand->getExcessDemand() / marketDepth +
constant * (1+fabs(excessDemand->getExcessDemand())*theta) * eta) );
}
}
void PriceCalculatorHarrasNoise::preStepCalculate(){
}
void PriceCalculatorHarrasNoise::postStepCalculate(){
}
/** Standardconstructor
*/
PriceCalculatorHarrasNoise::PriceCalculatorHarrasNoise():PriceCalculatorHarrasNoise(nullptr, nullptr, nullptr, ADD,
0, 0, nullptr){
}
/** Constructor for the PriceCalculatorHarras. For Documentation see parent class PriceCalculator.
*/
PriceCalculatorHarrasNoise::PriceCalculatorHarrasNoise(ExcessDemandCalculator* newExcessDemandCalculator,
Price* newPrice, ExcessDemand* newExcessDemand,
NoiseMode mode, double constant, double theta,
RandomGenerator* randomGenerator):
PriceCalculator(newExcessDemandCalculator, newPrice, newExcessDemand){
this->mode = mode;
this->constant = constant;
this->randomGenerator = randomGenerator;
this->theta = theta;
}
|
e291837880a3a372493822105d1d842c19907043 | 53f0935ea44e900e00dc86d66f5181c5514d9b8e | /dmih/05/ribari.cpp | 33fc23a43a61f46e1e333cbe60ec0486ed8abcc9 | [] | no_license | losvald/algo | 3dad94842ad5eb4c7aa7295e69a9e727a27177f6 | 26ccb862c4808f0d5970cee4ab461d1bd4cecac6 | refs/heads/master | 2016-09-06T09:05:57.985891 | 2015-11-05T05:13:19 | 2015-11-05T05:13:19 | 26,628,114 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 841 | cpp | ribari.cpp | #include <cstdio>
#define MAX 100001
int kol[MAX], dist[MAX], n;
int probaj(int x) {
int uviz = 0;
for(int i = 0; i < n-1; i++) {
if(kol[i]+uviz < x)
uviz += (kol[i]-x) - (dist[i+1]-dist[i]);
else {
uviz+=(kol[i]-x)-(dist[i+1]-dist[i]);
if(uviz < 0) uviz = 0;
}
}
if(kol[n-1]+uviz >= x) return 1;
return 0;
}
int main() {
int maxkol = -1;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d %d", &dist[i], &kol[i]);
maxkol >?= kol[i];
}
int left = 1, right = maxkol, x;
while(left < right) {
x = (left+right+1)/2;
if(probaj(x))
left = x;
else
right = x-1;
}
printf("%d", left);
scanf("\n");
return 0;
}
|
6cb6a2669328d83f43d2847ccd484dbec24e418f | 20a277e4e8a4ad949c97e3e4cc6b7ef11cf5ae0b | /Segment Trees/Excercise/minQuery1.cpp | d54091772189b27c77100f417cd14e84ece4a343 | [] | no_license | Neilketchum/Compedetive-Programing | da265ffc218f63b87bd67160512c8f342f506702 | bd007eed7c1ae9e5b2dfe809ce9349b9d04ae7f5 | refs/heads/master | 2022-11-24T19:03:51.548401 | 2020-07-31T11:28:54 | 2020-07-31T11:28:54 | 269,554,949 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,842 | cpp | minQuery1.cpp | #include<bits/stdc++.h>
using namespace std;
void buildTree(int *arr,int s,int e,int *tree,int index){
if(s == e){
tree[index] = arr[s];
return;
}
int mid = (s + e)/2;
buildTree(arr,s,mid,tree,index * 2); //Left
buildTree(arr,mid+1,e,tree,2*index+1);//Right
tree[index] = min(tree[index*2],tree[index*2 +1]);
}
int get_min(int *tree,int s,int e,int qs,int qe,int index){
if(s>=qs && e<=qe){
return tree[index];
}
// No OverLap
if(qe < s || qs > e){
return INT_MAX;
}
int mid = (s + e)/2;
int left = get_min(tree,s,mid,qs,qe,index*2);
int right =get_min(tree,mid+1,e,qs,qe,index*2 +1);
return min(left,right);
}
void point_update(int *tree,int s,int e,int i,int inc,int index){
if(i < s || i > e){
return;
}
if(s == e){
tree[index] += inc;
return ;
}
int mid = (s + e) /2;
point_update(tree,s,mid,i,inc,index*2);
point_update(tree,mid+1,e,i,inc,index*2 +1);
tree[index] = min(tree[index*2],tree[index*2 +1]);
}
int main(int argc, char const *argv[])
{
int nodes,queries;
cin>>nodes>>queries;
int node[nodes] = {0};
for(int i =0;i<nodes;i++){
cin>>node[i];
}
int *tree = new int[4*nodes +1];
buildTree(node,0,nodes-1,tree,1);
// for(int i =1;i<4*nodes-1;i++){
// cout<<tree[i]<<' ';
// }
// cout<<endl;
// cout<<get_min(tree,0,nodes-1,1,5,1);
int type;
while(queries>0){
cin>>type;
if(type==1){
int l,r;
cin>>l>>r;
cout<<get_min(tree,0,nodes,l-1,r,1)<<endl;
}
else if(type == 2){
int i,inc;
cin>>i>>inc;
point_update(tree,0,nodes-1,i-1,inc,1);
}
queries--;
}
return 0;
} |
24d67bd46e5c409a95751f563ae9c3a37ce14100 | d926f924309ecd3335309b5a83591276e809d55e | /src/v/storage/tests/log_segment_appender_test.cc | 6624ee40b2337884ac1d00bc8cd692a1384226d1 | [] | no_license | kitaisreal/redpanda | 3446a03dd2fb7c8e2b35ee0e44bc97b4db4713cb | eb8c435a48efe1c7e428e92341479b72f7c67dde | refs/heads/dev | 2023-06-13T06:40:59.817143 | 2021-07-02T02:19:03 | 2021-07-02T02:19:03 | 382,417,691 | 0 | 0 | null | 2021-07-02T17:27:38 | 2021-07-02T17:27:37 | null | UTF-8 | C++ | false | false | 8,060 | cc | log_segment_appender_test.cc | // Copyright 2020 Vectorized, Inc.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.md
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0
#include "bytes/iobuf.h"
#include "random/generators.h"
#include "seastarx.h"
#include "storage/segment_appender.h"
#include <seastar/core/reactor.hh>
#include <seastar/core/thread.hh>
#include <seastar/testing/thread_test_case.hh>
// test gate
#include <seastar/core/gate.hh>
#include <fmt/format.h>
using namespace storage; // NOLINT
SEASTAR_THREAD_TEST_CASE(test_can_append_multiple_flushes) {
std::cout.setf(std::ios::unitbuf);
auto f = ss::open_file_dma(
"test.segment_appender_random.log",
ss::open_flags::create | ss::open_flags::rw
| ss::open_flags::truncate)
.get0();
auto appender = segment_appender(
f, segment_appender::options(ss::default_priority_class(), 1));
iobuf expected;
ss::sstring data = "123456789\n";
for (size_t i = 0; i < 10; ++i) {
for (int j = 0; j < 910; ++j) {
expected.append(data.data(), data.size());
appender.append(data.data(), data.size()).get();
}
// This 911 time of appending "_redpanda" causes bug
// Commnting next two lines make the test passing
expected.append(data.data(), data.size());
appender.append(data.data(), data.size()).get();
appender.flush().get();
expected.append(data.data(), data.size());
appender.append(data.data(), data.size()).get();
appender.flush().get();
auto in = make_file_input_stream(f, 0);
iobuf result = read_iobuf_exactly(in, expected.size_bytes()).get0();
BOOST_REQUIRE_EQUAL(result.size_bytes(), expected.size_bytes());
BOOST_REQUIRE_EQUAL(result, expected);
in.close().get();
}
appender.close().get();
}
SEASTAR_THREAD_TEST_CASE(test_can_append_mixed) {
auto f = ss::open_file_dma(
"test_log_segment_mixed.log",
ss::open_flags::create | ss::open_flags::rw
| ss::open_flags::truncate)
.get0();
auto appender = segment_appender(
f, segment_appender::options(ss::default_priority_class(), 1));
auto alignment = f.disk_write_dma_alignment();
for (size_t i = 0, acc = 0; i < 100; ++i) {
iobuf original;
const size_t step = random_generators::get_int<size_t>(0, alignment * 2)
+ 1;
{
const auto data = random_generators::gen_alphanum_string(step - 1);
original.append(data.data(), data.size());
original.append("\n", 1);
}
BOOST_REQUIRE_EQUAL(step, original.size_bytes());
appender.append(original).get();
appender.flush().get();
BOOST_REQUIRE_EQUAL(acc + step, appender.file_byte_offset());
auto in = make_file_input_stream(f, acc);
iobuf result = read_iobuf_exactly(in, step).get0();
fmt::print(
"==> i:{}, step:{}, acc:{}, og.size:{}, expected.size{}\n",
i,
step,
acc,
original.size_bytes(),
result.size_bytes());
if (original != result) {
auto in = iobuf::iterator_consumer(
original.cbegin(), original.cend());
in.consume(original.size_bytes(), [](const char* src, size_t n) {
fmt::print("\nOriginal\n");
while (n-- > 0) {
fmt::print("{}", *src++);
}
fmt::print("\n");
return ss::stop_iteration::no;
});
in = iobuf::iterator_consumer(result.cbegin(), result.cend());
in.consume(original.size_bytes(), [](const char* src, size_t n) {
fmt::print("\nResult\n");
while (n-- > 0) {
fmt::print("{}", *src++);
}
fmt::print("\n");
return ss::stop_iteration::no;
});
// fail the test
BOOST_REQUIRE_EQUAL(original, result);
}
acc += step;
in.close().get();
}
appender.close().get();
}
SEASTAR_THREAD_TEST_CASE(test_can_append_10MB) {
auto f = ss::open_file_dma(
"test_segment_appender.log",
ss::open_flags::create | ss::open_flags::rw
| ss::open_flags::truncate)
.get0();
auto appender = segment_appender(
f, segment_appender::options(ss::default_priority_class(), 1));
for (size_t i = 0; i < 10; ++i) {
iobuf original;
constexpr size_t one_meg = 1024 * 1024;
{
const auto data = random_generators::gen_alphanum_string(1024);
for (size_t i = 0; i < 1024; ++i) {
original.append(data.data(), data.size());
}
}
BOOST_CHECK_EQUAL(one_meg, original.size_bytes());
appender.append(original).get();
appender.flush().get();
auto in = make_file_input_stream(f, i * one_meg);
iobuf result = read_iobuf_exactly(in, one_meg).get0();
BOOST_CHECK_EQUAL(original, result);
in.close().get();
}
appender.close().get();
}
SEASTAR_THREAD_TEST_CASE(
test_can_append_10MB_sequential_write_sequential_read) {
auto f = ss::open_file_dma(
"test_segment_appender_sequential.log",
ss::open_flags::create | ss::open_flags::rw
| ss::open_flags::truncate)
.get0();
auto appender = segment_appender(
f, segment_appender::options(ss::default_priority_class(), 1));
// write sequential. then read all
iobuf original;
constexpr size_t one_meg = 1024 * 1024;
{
const auto data = random_generators::gen_alphanum_string(1024);
for (size_t i = 0; i < 1024 * 10; ++i) {
original.append(data.data(), data.size());
}
}
appender.append(original).get();
appender.flush().get();
for (size_t i = 0; i < 10; ++i) {
auto in = make_file_input_stream(f, i * one_meg);
iobuf result = read_iobuf_exactly(in, one_meg).get0();
iobuf tmp_o = original.share(i * one_meg, one_meg);
BOOST_REQUIRE_EQUAL(tmp_o, result);
in.close().get();
}
appender.close().get();
}
SEASTAR_THREAD_TEST_CASE(test_can_append_little_data) {
auto f = ss::open_file_dma(
"test_segment_appender_little.log",
ss::open_flags::create | ss::open_flags::rw
| ss::open_flags::truncate)
.get0();
auto appender = segment_appender(
f, segment_appender::options(ss::default_priority_class(), 1));
auto alignment = f.disk_write_dma_alignment();
// at least 1 page and some 20 bytes to test boundary conditions
const auto data = random_generators::gen_alphanum_string(alignment + 20);
for (size_t i = 0; i < data.size(); ++i) {
char c = data[i];
appender.append(&c, 1).get();
appender.flush().get();
auto in = make_file_input_stream(f, i);
auto result = in.read_exactly(1).get0();
if (c != result[0]) {
std::vector<char> tmp;
tmp.reserve(7);
std::copy(
data.begin() + std::min<size_t>(i, i - 3),
data.begin() + i,
std::back_inserter(tmp));
std::copy(
data.begin() + i,
data.begin() + std::min<size_t>(data.size(), i + 3),
std::back_inserter(tmp));
tmp.push_back('\0');
fmt::print("\nINPUT AROUND:{}, i:{}\n", tmp.data(), i);
// make it fail
BOOST_REQUIRE_EQUAL(c, result[0]);
}
in.close().get();
}
BOOST_REQUIRE_EQUAL(appender.file_byte_offset(), data.size());
appender.close().get();
}
|
6bbc877a2039d125f089582fa94b9f6486b34233 | ac227cc22d5f5364e5d029a2cef83816a6954590 | /applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Solids_And_Fluids/SPH_CALLBACKS.h | d605054f724479ed89c69de156c8eb0ba17a2990 | [
"BSD-3-Clause"
] | permissive | schinmayee/nimbus | 597185bc8bac91a2480466cebc8b337f5d96bd2e | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | refs/heads/master | 2020-03-11T11:42:39.262834 | 2018-04-18T01:28:23 | 2018-04-18T01:28:23 | 129,976,755 | 0 | 0 | BSD-3-Clause | 2018-04-17T23:33:23 | 2018-04-17T23:33:23 | null | UTF-8 | C++ | false | false | 1,867 | h | SPH_CALLBACKS.h | //#####################################################################
// Copyright 2006, Nipun Kwatra, Frank Losasso, Jerry Talton.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class SPH_CALLBACKS
//#####################################################################
#ifndef __SPH_CALLBACKS__
#define __SPH_CALLBACKS__
#include <PhysBAM_Tools/Arrays/ARRAYS_FORWARD.h>
#include <PhysBAM_Tools/Log/DEBUG_UTILITIES.h>
#include <PhysBAM_Dynamics/Particles/PARTICLES_FORWARD.h>
namespace PhysBAM{
template<class T_GRID> struct GRID_ARRAYS_POLICY;
template<class T_GRID>
class SPH_CALLBACKS
{
typedef typename T_GRID::VECTOR_T TV;typedef typename TV::SCALAR T;
typedef typename GRID_ARRAYS_POLICY<T_GRID>::FACE_ARRAYS FACE_ARRAYS;
typedef typename REBIND<FACE_ARRAYS,bool>::TYPE FACE_ARRAYS_BOOL;
public:
SPH_CALLBACKS()
{}
virtual ~SPH_CALLBACKS()
{}
//#####################################################################
virtual void Adjust_SPH_Particle_For_Domain_Boundaries(SPH_PARTICLES<TV>& particles,const int index,TV& V,const T dt,const T time)const{PHYSBAM_WARN_IF_NOT_OVERRIDDEN();}
virtual bool Adjust_SPH_Particle_For_Objects(SPH_PARTICLES<TV>& particles,const int index,TV& V,const T dt,const T time)const{PHYSBAM_WARN_IF_NOT_OVERRIDDEN();return true;} // return false if particle should be deleted
virtual void Do_Something_With_Density(const T_GRID &grid,const typename GRID_ARRAYS_POLICY<T_GRID>::ARRAYS_SCALAR &cell_weight)const{}
virtual T Target_Density_Factor(const TV& location,const T time)const{PHYSBAM_WARN_IF_NOT_OVERRIDDEN();return 1;}
//#####################################################################
};
}
#endif
|
17b26018b4992b0ad4ab13d79da192a7100471d0 | 7eb2341d2e865d364203182da66e2081128c5c14 | /Algorithmn/Same Tree/Same Tree.cpp | 0f2de0441e8c9fde58f5c34357009136224586ce | [] | no_license | PatrickLin1993/LeetCode | bdd66b873e7b0c47c20506fd6af3c565a4c922d7 | cf5c8cdf00d850fcb2e48eaeaef831109511c9f7 | refs/heads/master | 2021-01-10T16:03:06.531308 | 2017-06-13T13:18:41 | 2017-06-13T13:18:41 | 46,721,072 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,476 | cpp | Same Tree.cpp | //
// Created by Patrick-Lin on 15/11/26.
// Copyright © 2015年 Patrick-Lin. All rights reserved.
//
/*
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Solution 1
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p&&!q)
return true;
if (!p||!q)
return false;
return (p->val==q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
// Solution 2
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
queue<TreeNode*> q1,q2;
q1.push(p);
q2.push(q);
while (q1.size()>0 || q2.size()>0) {
TreeNode *p1,*p2;
p1=q1.front();
q1.pop();
p2=q2.front();
q2.pop();
if(!p1 && !p2)
continue;
if (!p1 || !p2)
return false;
if (p1->val!=p2->val)
return false;
q1.push(p1->left);
q1.push(p1->right);
q2.push(p2->left);
q2.push(p2->right);
}
return true;
}
}; |
8b95e85126e36fe724081660af0526d8cf056671 | 39551ef8b2a615c31885b907ed95d2c49247317a | /S3/C_C++/repo/cpp/familytree.cc | 3670a9c9fc2d4a1ca74a733784698e6419f00abc | [] | no_license | ariez-xyz/LectureNotes | cfbc07d60a39719971f5073f513f467198059cf2 | 5cba22f5c3c3554d02897e0aca646f05d3e9882f | refs/heads/master | 2023-06-09T20:20:03.147705 | 2021-07-08T20:52:16 | 2021-07-08T20:52:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,660 | cc | familytree.cc | #include "familytree.h"
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
FamilyTree::FamilyTree(string pathToFile) {
persons_.reserve(findNumPersons(pathToFile)); // resizing vector breaks pointers...
ifstream personenStream(pathToFile);
string fName, lName, gender, YOB, YOD, fatherFName, fatherLName, fatherYOB, motherFName, motherLName, motherYOB;
while(personenStream >> fName >> lName >> gender >> YOB >> YOD >> fatherFName >> fatherLName >> fatherYOB >> motherFName >> motherLName >> motherYOB) {
int currentPos = insertIfNotPresent(fName, lName, YOB);
int fatherPos = insertIfNotPresent(fatherFName, fatherLName, fatherYOB);
int motherPos = insertIfNotPresent(motherFName, motherLName, motherYOB);
if(fatherPos != -1) {
persons_.at(currentPos).putRelative(&persons_.at(fatherPos));
persons_.at(fatherPos).putRelative(&persons_.at(currentPos));
}
if(motherPos != -1) {
persons_.at(currentPos).putRelative(&persons_.at(motherPos));
persons_.at(motherPos).putRelative(&persons_.at(currentPos));
}
}
}
int FamilyTree::insertIfNotPresent(string fName, string lName, string YOB) {
if(YOB == "0") // if unknown
return -1;
Person p(fName, lName, YOB);
int pos;
if(indexMap_.find(p.getId()) == indexMap_.end()) { // if not present
pos = persons_.size();
indexMap_[p.getId()] = pos;
persons_.push_back(p);
} else
pos = indexMap_[p.getId()];
return pos;
}
int FamilyTree::indexOf(string id) {
if(indexMap_.find(id) == indexMap_.end())
return -1;
else
return indexMap_[id];
}
Person* FamilyTree::get(int index) {
return &persons_.at(index);
}
int FamilyTree::findNumPersons(string pathToFile) {
int persons = 0;
string line;
ifstream personenStream(pathToFile);
while(getline(personenStream, line))
persons++;
return persons;
}
void FamilyTree::sort(){
std::sort(persons_.begin(), persons_.end(), [](const Person& a, const Person& b) {
if(a.getDistance() == b.getDistance()) {
if(a.getYOB() == b.getYOB()) {
if(a.getLName() == b.getLName()) {
return a.getFName() < b.getFName();
} else
return a.getLName() < b.getLName();
} else
return a.getYOB() < b.getYOB();
} else
return a.getDistance() < b.getDistance();
});
}
int FamilyTree::size() {
return persons_.size();
}
|
0242993c38f4c98ed029de3ab51eb18c503736e9 | 9350cc816b7d08b49412163678744b062eda2a00 | /src/ros_arduino_imu_node.cpp | 1405ce88d6ac51b37ff5ea1c4e9163d520db172f | [] | no_license | gcc-robotics/ros_arduino_imu | ecc406cf4cff4962528d4869a48110406bc3c883 | 62a1647e2495c465bd0d46cfc481c04b112708ae | refs/heads/master | 2021-01-01T16:59:49.639448 | 2015-04-10T18:49:07 | 2015-04-10T18:49:07 | 33,391,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,863 | cpp | ros_arduino_imu_node.cpp | #include <iostream>
#include <stdio.h>
#include "ros/ros.h"
#include "sensor_msgs/Imu.h"
ros::Publisher imuPublisher;
#include "serial/serial.h"
int main(int argc, char **argv)
{
ROS_INFO("Starting ros_arduino_imu_node");
ros::init(argc, argv, "ros_arduino_imu");
ros::NodeHandle node;
ros::Publisher imuPublisher = node.advertise<sensor_msgs::Imu>("/imu", 1);
// port, baudrate, timeout in milliseconds
serial::Serial imuSerial("/dev/ttyACM1", 115200, serial::Timeout::simpleTimeout(1000));
if(imuSerial.isOpen())
{
ROS_INFO("Successfully connected to IMU Arduino.");
}
else
{
ROS_INFO("Shit. Failed to connect.");
}
ROS_INFO("Press Ctrl-C to kill node.");
// Spin
ros::Rate loopRate(10); // 10 hz
while(ros::ok())
{
// Send IMU data message
sensor_msgs::Imu msg;
// Data Index
imuSerial.readline(20, " ");
// Linear Acceleration
// x
std::stringstream ssX(imuSerial.readline(20, " "));
float xAcc;
ssX >> xAcc;
msg.linear_acceleration.x = xAcc;
// y
std::stringstream ssY(imuSerial.readline(20, " "));
float yAcc;
ssY >> yAcc;
msg.linear_acceleration.y = yAcc;
// z
std::stringstream ssZ(imuSerial.readline(20, " "));
float zAcc;
ssZ >> zAcc;
msg.linear_acceleration.z = zAcc;
// x_gyro
std::stringstream ssX_gyro(imuSerial.readline(20, " "));
float xGyro;
ssX_gyro >> xGyro;
msg.angular_velocity.x = xGyro;
// y_gyro
std::stringstream ssY_gyro(imuSerial.readline(20, " "));
float yGyro;
ssY_gyro >> yGyro;
msg.angular_velocity.y = yGyro;
// z_gyro
std::stringstream ssZ_gyro(imuSerial.readline(20, " "));
float zGyro;
ssZ_gyro >> zGyro;
msg.angular_velocity.z = zGyro;
imuPublisher.publish(msg);
// Altitude & rest of line
imuSerial.readline();
// ROS Spin & Sleep
ros::spinOnce();
loopRate.sleep();
}
ros::shutdown();
return 0;
} |
792492efd8f72fd16db32ab007afac394785d39f | 219d146ffa17dc50dec0626e30aa08db47eca33d | /eoftoken.h | 09a2f68de9d7578ea87af06cc520e3b2735c2cf4 | [] | no_license | johnfoley3/foley-compiler | 700aaf800672d58e6f849b08f4ff8a59b17d8c6c | 805a95f0822e4917eba4db2c450d1edbd83c0b96 | refs/heads/master | 2020-05-30T11:37:29.233196 | 2014-12-05T01:28:29 | 2014-12-05T01:28:29 | 24,428,765 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 452 | h | eoftoken.h | /*
Author: John Foley
URL: thisfoley.ninja
Date: 9.25.14
Last Edit: 9.25.14
*/
#ifndef EOFTOKEN_H
#define EOFTOKEN_H
#include "token.h"
#include <string>
using namespace std;
/* EofToken is a derived class (subclass) of Token */
class EofToken : public Token
{
public:
EofToken() ;
~EofToken();
string *get_attribute() const;
string *to_string();
private:
// Storage for the attribute of the token.
string *attribute;
};
#endif
|
8572a57ca6289db32aaef46a6367104cff6b9f2e | bebc95de2ba0b18ab89807973ec445ba32e01d50 | /innative/lexer.cpp | a6b5659a4c8ac50a648cbc58f68372c2e20a2611 | [
"Apache-2.0",
"LLVM-exception"
] | permissive | innative-sdk/innative | c7cab04587382b019f699a45b48fbd85fa323ad5 | 1fb381d7dfabc581c42114aa66cf81ae63a06eb9 | refs/heads/master | 2023-08-30T03:33:20.190480 | 2022-12-27T21:03:49 | 2022-12-27T21:03:49 | 122,264,181 | 412 | 16 | Apache-2.0 | 2020-10-27T08:54:11 | 2018-02-20T22:24:52 | C++ | UTF-8 | C++ | false | false | 18,206 | cpp | lexer.cpp | // Copyright (c)2021 Fundament Software
// For conditions of distribution and use, see copyright notice in innative.h
#include "utility.h"
#include "wat.h"
#include "parse.h"
#include "validate.h"
#include <limits>
#include <cmath>
#include <algorithm>
using std::numeric_limits;
using std::string;
using namespace innative;
using namespace utility;
using namespace wat;
namespace innative {
namespace wat {
KHASH_INIT(tokens, StringSpan, WatTokens, 1, internal::__ac_X31_hash_stringrefins, kh_int_hash_equal);
template<int LEN>
inline kh_tokens_t* GenTokenHash(const char* (&list)[LEN],
std::initializer_list<std::pair<const char*, WatTokens>> legacy)
{
kh_tokens_t* h = kh_init_tokens();
unsigned int count = 0;
int r;
for(int i = 0; i < LEN; ++i)
{
auto iter = kh_put_tokens(h, StringSpan{ list[i], strlen(list[i]) }, &r);
kh_val(h, iter) = WatTokens(count++);
}
for(auto& e : legacy)
{
auto iter = kh_put_tokens(h, StringSpan{ e.first, strlen(e.first) }, &r);
kh_val(h, iter) = e.second;
}
return h;
}
static const char* tokenlist[] = { "[NONE]",
"(",
")",
"module",
"import",
"type",
"start",
"func",
"table",
"memory",
"global",
"export",
"data",
"elem",
"offset",
"align",
"local",
"result",
"param",
"i32",
"i64",
"f32",
"f64",
"funcref",
"cref",
"mut",
"block",
"loop",
"if",
"then",
"else",
"end",
"shared",
"unshared",
"binary", // script expressions
"quote",
"register",
"invoke",
"get",
"assert_return",
"assert_return_canonical_nan",
"assert_return_arithmetic_nan",
"assert_trap",
"assert_malformed",
"assert_invalid",
"assert_unlinkable",
"assert_exhaustion",
"script",
"input",
"output" };
static const kh_tokens_t* tokenhash = GenTokenHash(tokenlist, { { "anyfunc", WatTokens::FUNCREF } });
const char* GetTokenString(WatTokens token)
{
constexpr int len = sizeof(tokenlist) / sizeof(decltype(tokenlist[0]));
return ((token != WatTokens::NONE) && (static_cast<decltype(len)>(token) < len)) ?
tokenlist[static_cast<decltype(len)>(token)] :
0;
}
const char* CheckTokenINF(const char* s, const char* end, std::string* target)
{
if(s >= end)
return nullptr;
const char* begin = s;
if(s[0] == '-' || s[0] == '+')
++s;
int i;
for(i = 0; i < 3 && s < end; ++i)
{
if(s[i] != "inf"[i] && s[i] != "INF"[i])
return nullptr;
}
if(i != 3)
return nullptr;
s += 3;
if(target)
target->assign(begin, s - begin);
return s;
}
const char* CheckTokenNAN(const char* s, const char* end, std::string* target)
{
if(s >= end)
return nullptr;
if(s[0] == '-' || s[0] == '+')
++s;
const char* begin = s;
int i;
for(i = 0; i < 3 && s < end; ++i)
{
if(s[i] != "nan"[i] && s[i] != "NAN"[i])
return nullptr;
}
if(i != 3)
return nullptr;
s += 3;
if(s >= end)
return end;
// At the moment this should only be lowercase
if(!strncmp(":canonical", s, std::min((size_t)(end - s), (size_t)10)))
{
// if(target)
// target->assign("canonical");
return s + 10;
}
if(!strncmp(":arithmetic", s, std::min((size_t)(end - s), (size_t)11)))
{
// if(target)
// target->assign("arithmetic");
return s + 11;
}
for(i = 0; i < 3 && s < end; ++i)
{
if(s[i] != ":0x"[i])
return s;
}
s += i;
if(target)
target->assign(begin + 3 + i, s - begin - 3 - i);
while(s < end && (*s == '_' || isxdigit(*s)))
{
if(target && *s != '_')
target->append(1, *s);
++s;
}
return s;
}
template<typename T, typename Arg, typename... Args>
int ResolveTokenNumber(const WatToken& token, string& numbuf, Arg (*fn)(const char*, char**, Args...), T& out,
Args... args)
{
numbuf.clear();
size_t length = token.len;
int (*digitcheck)(int) = (token.len > 2 && token.pos[0] == '0' && token.pos[1] == 'x') ? &isxdigit : &isdigit;
for(size_t i = 0; i < token.len; ++i)
{
if(token.pos[i] == '_')
{
if(!i || (i + 1) >= token.len || !(*digitcheck)(token.pos[i - 1]) ||
!(*digitcheck)(token.pos[i + 1])) // If it's a _, it's valid only if it's surrounded by valid digits
return ERR_WAT_INVALID_NUMBER;
--length; // Compensate for the character we removed from the amount we expect to consume
}
else // otherwise, only add all non-underscore characters
numbuf += token.pos[i];
}
if(digitcheck ==
&isdigit) // If this is a decimal number, strip all leading 0s because otherwise it'll be considered octal
{
size_t iter = numbuf.find_first_not_of('0');
if(iter != std::string::npos && iter > 0)
{
numbuf.erase(0, iter);
length -= iter;
}
}
errno = 0;
char* end;
out = (*fn)(numbuf.c_str(), &end, args...);
#ifdef IN_PLATFORM_POSIX
if(std::is_floating_point<T>::value)
{
if(std::isinf(out)) // libc incorrectly parses certain edge cases as "inf" without setting errno to ERANGE
{
const char* p = numbuf.c_str();
if(*p == '+' || *p == '-')
++p;
if(strncasecmp(p, "inf", 3) != 0)
return ERR_WAT_OUT_OF_RANGE;
}
}
#endif
if(std::is_same<float, T>::value &&
fabs(out) <= 1.1754942e-38f) // WebAssembly never considers an underflow to be a range error, it rounds to zero
errno = 0;
if(std::is_same<double, T>::value && fabs(out) <= 2.2250738585072012e-308)
errno = 0;
if(errno == ERANGE)
return ERR_WAT_OUT_OF_RANGE;
// assert(!(errno != 0 || (end - numbuf.c_str()) != length));
return (errno != 0 || (end - numbuf.c_str()) != length) ? ERR_WAT_INVALID_NUMBER : ERR_SUCCESS;
}
int ResolveTokenf32(const WatToken& token, string& numbuf, float32& out)
{
char* last;
numbuf.assign("400000"); // Hex for the first bit in the mantissa
if(CheckTokenNAN(token.pos, token.pos + token.len, &numbuf))
{
auto mantissa = strtoul(numbuf.c_str(), &last, 16);
if(mantissa < 0x1 || mantissa > 0x7fffff)
return ERR_WAT_OUT_OF_RANGE;
union
{
uint32_t i;
float f;
} u = { 0x7F800000U | (uint32_t)mantissa };
if(token.pos[0] == '-')
u.i |= 0x80000000U;
out = u.f;
return ERR_SUCCESS;
}
if(CheckTokenINF(token.pos, token.pos + token.len, &numbuf) != nullptr)
{
out = strtof(numbuf.c_str(), &last);
return (last - numbuf.c_str()) == numbuf.size() ? ERR_SUCCESS : ERR_WAT_INVALID_NUMBER;
}
return ResolveTokenNumber<float32>(token, numbuf, &strtof, out);
}
int ResolveTokenf64(const WatToken& token, string& numbuf, float64& out)
{
char* last;
numbuf.assign("8000000000000"); // Hex for the first bit in the mantissa
if(CheckTokenNAN(token.pos, token.pos + token.len, &numbuf))
{
auto mantissa = strtoull(numbuf.c_str(), &last, 16);
if(mantissa < 0x1 || mantissa > 0xfffffffffffff)
return ERR_WAT_OUT_OF_RANGE;
union
{
uint64_t i;
double f;
} u = { 0x7FF0000000000000ULL | mantissa };
if(token.pos[0] == '-')
u.i |= 0x8000000000000000ULL;
out = u.f;
return ERR_SUCCESS;
}
if(CheckTokenINF(token.pos, token.pos + token.len, &numbuf) != nullptr)
{
out = strtod(numbuf.c_str(), &last);
return (last - numbuf.c_str()) == numbuf.size() ? ERR_SUCCESS : ERR_WAT_INVALID_NUMBER;
}
return ResolveTokenNumber<float64>(token, numbuf, &strtod, out);
}
int ResolveTokeni64(const WatToken& token, string& numbuf, varsint64& out)
{
if(token.len > 0 && token.pos[0] == '-')
return ResolveTokenNumber<varsint64, long long, int>(token, numbuf, strtoll, out, 0);
return ResolveTokenNumber<varsint64, unsigned long long, int>(token, numbuf, strtoull, out, 0);
}
int ResolveTokenu64(const WatToken& token, string& numbuf, varuint64& out)
{
if(token.len > 0 && token.pos[0] == '-')
return ERR_WAT_OUT_OF_RANGE;
return ResolveTokeni64(token, numbuf, reinterpret_cast<varsint64&>(out));
}
int ResolveTokeni32(const WatToken& token, string& numbuf, varsint32& out)
{
varsint64 buf;
int err = ResolveTokeni64(token, numbuf, buf);
if(err)
return err;
if((buf < std::numeric_limits<varsint32>::min()) || (buf > (varsint64)std::numeric_limits<varuint32>::max()))
return ERR_WAT_OUT_OF_RANGE;
out = (varsint32)buf;
return ERR_SUCCESS;
}
int ResolveTokenu32(const WatToken& token, string& numbuf, varuint32& out)
{
varsint64 buf;
int err = ResolveTokeni64(token, numbuf, buf);
if(err)
return err;
if((buf < 0) || (buf > (varsint64)std::numeric_limits<varuint32>::max()))
return ERR_WAT_OUT_OF_RANGE;
out = (varsint32)buf;
return ERR_SUCCESS;
}
IN_FORCEINLINE const char* IncToken(const char*& s, const char* end, unsigned int& line, unsigned int& column)
{
++s;
if(s + 1 < end && ((s[0] == '\r' && s[1] != '\n') || s[0] == '\n'))
{
++line;
column = 0;
}
else
++column;
return s;
}
}
}
void innative::TokenizeWAT(Queue<WatToken>& tokens, const char* s, const char* end)
{
unsigned int line = 1;
unsigned int column = 0;
while(s < end)
{
while(s < end && (s[0] == ' ' || s[0] == '\n' || s[0] == '\r' || s[0] == '\t' || s[0] == '\f'))
IncToken(s, end, line, column);
if(s >= end)
break;
switch(s[0])
{
case 0:
assert(s < end);
IncToken(s, end, line, column);
break;
case '(':
if(s + 1 < end && s[1] == ';') // This is a comment
{
IncToken(s, end, line, column);
IncToken(s, end, line, column);
size_t depth = 1;
while(depth > 0 && s < end)
{
switch(*s)
{
case '(':
if(s + 1 < end && s[1] == ';')
depth += 1;
IncToken(s, end, line, column);
break;
case ';':
if(s + 1 < end && s[1] == ')')
depth -= 1;
IncToken(s, end, line, column);
break;
}
IncToken(s, end, line, column);
}
}
else
{
tokens.Push(WatToken{ WatTokens::OPEN, s, line, column });
IncToken(s, end, line, column);
}
break;
case ')':
tokens.Push(WatToken{ WatTokens::CLOSE, s, line, column });
IncToken(s, end, line, column);
break;
case ';': // A comment
{
if(s + 1 < end && s[1] == ';')
{
do
{
IncToken(s, end, line, column);
} while(s < end && s[0] != '\n');
}
else
{
tokens.Push(WatToken{ WatTokens::NONE });
}
if(s < end)
IncToken(s, end, line, column);
break;
}
case '"': // A string
{
const char* begin = IncToken(s, end, line, column);
while(s[0] != '"' && s + 1 < end)
{
if(s[0] == '\\')
IncToken(s, end, line, column);
IncToken(s, end, line, column);
}
WatToken t = { WatTokens::STRING, begin, line, column };
t.len = s - begin;
tokens.Push(t);
if(s[0] == '"')
IncToken(s, end, line, column);
break;
}
case '$': // A name
{
WatToken t = { WatTokens::NAME, s + 1, line, column };
// We avoid using a regex here because extremely long names are still technically valid but can overwhelm the standard
// C++ regex evaluator
while(s < end)
{
IncToken(s, end, line, column);
switch(*s)
{
case '!':
case '#':
case '$':
case '%':
case '&':
case '\'':
case '*':
case '+':
case '-':
case '.':
case '/':
case ':':
case '<':
case '=':
case '>':
case '?':
case '@':
case '\\':
case '^':
case '_':
case '`':
case '|':
case '~': t.len++; continue;
default:
if(isalnum(s[0]))
{
t.len++;
continue;
}
}
break;
}
if(!t.len) // Empty names are invalid
t.id = WatTokens::NONE;
tokens.Push(t);
break;
}
case '-':
case '+':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': // Either an integer or a float
{
const char* last = s;
if(!(last = CheckTokenNAN(s, end, 0)) && !(last = CheckTokenINF(s, end, 0))) // Check if this is an NaN or an INF
{
last = s; // If it's not an NAN, estimate what the number is
if(last[0] == '-' || last[0] == '+')
++last;
if(last + 2 < end && last[0] == '0' && last[1] == 'x')
last += 2;
if(last >= end || !isxdigit(last[0]))
{
tokens.Push(WatToken{ WatTokens::NONE, s, line, column, last - s });
column += (uint32_t)(last - s);
s = last;
break;
}
while(last < end && (isalnum(last[0]) || last[0] == '.' || last[0] == '_' || last[0] == '-' || last[0] == '+'))
++last;
}
tokens.Push(WatToken{ WatTokens::NUMBER, s, line, column, last - s });
column += (uint32_t)(last - s);
s = last;
break;
}
default:
{
const char* begin = s;
if((begin = CheckTokenNAN(s, end, 0)) != 0 || (begin = CheckTokenINF(s, end, 0)) != 0) // Check if this is an NaN
{
tokens.Push(WatToken{ WatTokens::NUMBER, s, line, column, begin - s });
column += (uint32_t)(begin - s);
s = begin;
}
else
{
begin = s;
while(s < end && s[0] != ' ' && s[0] != '\n' && s[0] != '\r' && s[0] != '\t' && s[0] != '\f' && s[0] != '=' &&
s[0] != ')' && s[0] != '(' && s[0] != ';')
IncToken(s, end, line, column);
StringSpan ref = { begin, static_cast<size_t>(s - begin) };
khiter_t iter = kh_get_tokens(tokenhash, ref);
if(kh_exist2(tokenhash, iter))
tokens.Push(WatToken{ kh_val(tokenhash, iter), begin, line, column });
else
{
uint16_t op = GetInstruction(ref);
if(op != 0xFF)
tokens.Push(WatToken{ WatTokens::OPERATOR, begin, line, column, (int64_t)op });
else
{
tokens.Push(WatToken{ WatTokens::NONE, begin, line, column, (int64_t)ref.len });
}
}
if(*s == '=')
IncToken(s, end, line, column);
}
}
}
if(tokens.Size() > 0)
assert(tokens.Peek().id < WatTokens::TOTALCOUNT);
}
}
// Checks for parse errors in the tokenization process
int innative::CheckWatTokens(const Environment& env, ValidationError*& errors, Queue<WatToken>& tokens, const char* start)
{
int err = ERR_SUCCESS;
for(size_t i = 0; i < tokens.Size(); ++i)
{
switch(tokens[i].id)
{
case WatTokens::NONE:
AppendError(env, errors, nullptr, ERR_WAT_INVALID_TOKEN, "[%zu] Invalid token: %s",
WatLineNumber(start, tokens[i].pos), string(tokens[i].pos, tokens[i].len).c_str());
break;
case WatTokens::RANGE_ERROR:
AppendError(env, errors, nullptr, ERR_WAT_OUT_OF_RANGE, "[%zu] Constant out of range: %s",
WatLineNumber(start, tokens[i].pos), string(tokens[i].pos, tokens[i].len).c_str());
break;
default: continue;
}
err = ERR_WAT_INVALID_TOKEN;
}
return err;
} |
f20cd89dd645b83e676e269ddaeaed121aff3da2 | db94bdb5118e5852289c4b7f284f0908c75fc895 | /samples/stat_collector/utils.h | 4da8ef699a48b0b00abd1ca5b42948c77fcdfd55 | [] | no_license | TeLin1996/cv_temp | 37813d198db53149a46b6975f654e7caba833228 | 7f19f9eef88520253ee1d162a64b3b1805a55052 | refs/heads/master | 2020-03-23T11:44:41.902777 | 2018-07-24T09:19:20 | 2018-07-24T09:19:20 | 141,519,081 | 0 | 0 | null | 2018-07-19T03:20:36 | 2018-07-19T03:20:36 | null | UTF-8 | C++ | false | false | 2,116 | h | utils.h | /*
// Copyright (c) 2017 Intel Corporation
//
// 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.
*/
#pragma once
#include <string>
#include <vector>
#include <ie_plugin_dispatcher.hpp>
#include <ie_plugin_ptr.hpp>
std::string GetArchPath();
InferenceEngine::InferenceEnginePluginPtr SelectPlugin(const std::vector<std::string> &pluginDirs,
const std::string &plugin, InferenceEngine::TargetDevice device);
InferenceEngine::InferenceEnginePluginPtr SelectPlugin(const std::vector<std::string> &pluginDirs,
const std::string &plugin, const std::string& device);
std::string FileNameNoPath(const std::string& filePath);
std::string FileNameNoExt(const std::string& filePath);
std::string FilePath(const std::string& filePath);
std::string FileExt(const std::string& filePath);
char FilePathSeparator();
std::string VectorToStringF(std::vector<float> vec, const char sep = ',');
std::vector<float> StringToVectorF(std::string vec, const char sep = ',');
std::string VectorToStringI(std::vector<int> vec, const char sep = ',');
std::vector<int> StringToVectorI(std::string vec, const char sep = ',');
void CopyFile(const std::string& srcPath, const std::string& dstPath);
void ParseValFile(const std::string& path, std::vector<std::string>& images, std::vector<size_t>& classes);
void GetFilesInDir(const std::string& path, const std::string& ext, std::vector<std::string>& files);
bool IsDirectory(const std::string& path);
std::string ToUpper(const std::string& str);
float ScaleToDFP(float scale);
|
35a08b57dc607b9600ff8bf9ced1a6f185caf157 | 879681c994f1ca9c8d2c905a4e5064997ad25a27 | /root-2.3.0/run/MicroChannelFOAM/TurbulenceMicroChannel/0.192/epsilon | 249e7c2e1657940863fa550c2baaacd928ae630d | [] | no_license | MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu | 3828272d989d45fb020e83f8426b849e75560c62 | daeb870be81275e8a81f5cbac4ca1906a9bc69c0 | refs/heads/master | 2020-05-17T16:36:41.848261 | 2015-04-18T09:29:48 | 2015-04-18T09:29:48 | 34,159,882 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,083 | epsilon | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.192";
object epsilon;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -3 0 0 0 0];
internalField nonuniform List<scalar>
545
(
2.61319e+08
2.48846e+08
2.28941e+08
2.11769e+08
2.00016e+08
2.66377e+08
2.4942e+08
2.28332e+08
2.10721e+08
1.98053e+08
2.75074e+08
2.49886e+08
2.26871e+08
2.08546e+08
1.94542e+08
2.88225e+08
2.49507e+08
2.24527e+08
2.05433e+08
1.89173e+08
3.0772e+08
2.47365e+08
2.21829e+08
2.02096e+08
1.81609e+08
1.94008e+08
1.90725e+08
1.89679e+08
1.89348e+08
1.89242e+08
1.89206e+08
1.89193e+08
1.89186e+08
1.89181e+08
1.89177e+08
1.89174e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89143e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.89131e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89125e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89119e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.92505e+08
1.90265e+08
1.89534e+08
1.89302e+08
1.89228e+08
1.89202e+08
1.89191e+08
1.89185e+08
1.89181e+08
1.89177e+08
1.89174e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.90319e+08
1.89495e+08
1.89287e+08
1.89225e+08
1.89204e+08
1.89194e+08
1.89189e+08
1.89185e+08
1.89181e+08
1.89177e+08
1.89174e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.87475e+08
1.88596e+08
1.8901e+08
1.89139e+08
1.89177e+08
1.89186e+08
1.89186e+08
1.89184e+08
1.8918e+08
1.89177e+08
1.89174e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.8416e+08
1.87835e+08
1.8879e+08
1.89072e+08
1.89156e+08
1.8918e+08
1.89184e+08
1.89183e+08
1.8918e+08
1.89177e+08
1.89173e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.84528e+08
1.87603e+08
1.88701e+08
1.89044e+08
1.89147e+08
1.89177e+08
1.89183e+08
1.89183e+08
1.8918e+08
1.89177e+08
1.89173e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
3.0772e+08
2.47365e+08
2.21829e+08
2.02096e+08
1.81609e+08
2.88225e+08
2.49507e+08
2.24527e+08
2.05433e+08
1.89173e+08
2.75074e+08
2.49886e+08
2.26871e+08
2.08546e+08
1.94542e+08
2.66377e+08
2.4942e+08
2.28332e+08
2.10721e+08
1.98053e+08
2.61319e+08
2.48846e+08
2.28941e+08
2.11769e+08
2.00016e+08
1.8416e+08
1.87835e+08
1.8879e+08
1.89072e+08
1.89156e+08
1.8918e+08
1.89184e+08
1.89183e+08
1.8918e+08
1.89177e+08
1.89173e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.87475e+08
1.88596e+08
1.8901e+08
1.89139e+08
1.89177e+08
1.89186e+08
1.89186e+08
1.89184e+08
1.8918e+08
1.89177e+08
1.89174e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.90319e+08
1.89495e+08
1.89287e+08
1.89225e+08
1.89204e+08
1.89194e+08
1.89189e+08
1.89185e+08
1.89181e+08
1.89177e+08
1.89174e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.92505e+08
1.90265e+08
1.89534e+08
1.89302e+08
1.89228e+08
1.89202e+08
1.89191e+08
1.89185e+08
1.89181e+08
1.89177e+08
1.89174e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.8913e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89124e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89118e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.94008e+08
1.90725e+08
1.89679e+08
1.89348e+08
1.89242e+08
1.89206e+08
1.89193e+08
1.89186e+08
1.89181e+08
1.89177e+08
1.89174e+08
1.8917e+08
1.89167e+08
1.89164e+08
1.89161e+08
1.89158e+08
1.89155e+08
1.89152e+08
1.8915e+08
1.89147e+08
1.89145e+08
1.89142e+08
1.8914e+08
1.89138e+08
1.89136e+08
1.89134e+08
1.89132e+08
1.89131e+08
1.89129e+08
1.89127e+08
1.89126e+08
1.89125e+08
1.89123e+08
1.89122e+08
1.89121e+08
1.8912e+08
1.89119e+08
1.89119e+08
1.89118e+08
1.89117e+08
1.89117e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
)
;
boundaryField
{
AirInlet
{
type fixedValue;
value uniform 0.1;
}
WaterInlet
{
type fixedValue;
value uniform 0.1;
}
ChannelWall
{
type fixedValue;
value uniform 0.1;
}
Outlet
{
type inletOutlet;
inletValue uniform 0.1;
value nonuniform List<scalar>
11
(
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
1.89116e+08
)
;
}
FrontAndBack
{
type empty;
}
}
// ************************************************************************* //
| |
bc889f9de8fac4fa5660c5c66c57c27940045bfc | 2f3e514598851d6747ea31bdbca308983a8c86f1 | /app/src/include/sma/thread_scheduler.hpp | 9c6760a6abe1e37b06adfb4ecc8840da816224f9 | [] | no_license | culiu/sma | f2110a4b2649085528f852c1a590adf24f9f4eab | fc6f12fbd70bbe9194db0c2212acb74c4d87b1ac | refs/heads/master | 2020-12-31T06:09:18.285213 | 2015-11-19T12:33:28 | 2015-11-19T12:33:28 | 45,673,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | hpp | thread_scheduler.hpp | #pragma once
#include "threadpool.hpp"
#include "delay_queue.hpp"
#include <chrono>
#include <mutex>
#include <functional>
namespace sma
{
namespace detail
{
class thread_scheduler final
{
public:
static thread_scheduler& instance()
{
static thread_scheduler instance;
return instance;
}
void schedule(std::function<void()> task, std::chrono::nanoseconds delay);
private:
thread_scheduler(){};
thread_scheduler(thread_scheduler const&);
void operator=(thread_scheduler const&);
std::mutex mutex;
threadpool threads;
delay_queue<std::function<void()>> tasks;
};
}
}
|
ac257eb797a1094b389001fc27609e63b954b79b | 6f6a88ba519d9569b8bf17a1dd87537c24f28098 | /ExtinctionMonitorFNAL/Geometry/inc/ExtMonFNALMagnet.hh | d2db7bfee1c25d4c376ed87d17f8d115e8791286 | [
"Apache-2.0"
] | permissive | Mu2e/Offline | 728e3d9cd8144702aefbf35e98d2ddd65d113084 | d4083c0223d31ca42e87288009aa127b56354855 | refs/heads/main | 2023-08-31T06:28:23.289967 | 2023-08-31T02:23:04 | 2023-08-31T02:23:04 | 202,804,692 | 12 | 73 | Apache-2.0 | 2023-09-14T19:55:58 | 2019-08-16T22:03:57 | C++ | UTF-8 | C++ | false | false | 2,104 | hh | ExtMonFNALMagnet.hh | // Magnet parameters, used by both filter and detector magnets.
//
// Andrei Gaponenko, 2011
#ifndef EXTMONFNALMAGNET_HH
#define EXTMONFNALMAGNET_HH
#include <vector>
#include "CLHEP/Vector/ThreeVector.h"
#include "CLHEP/Vector/Rotation.h"
namespace mu2e {
class ExtMonFNALMagnetMaker;
class ExtMonFNALMagnet {
std::vector<double> outerHalfSize_;
double apertureWidth_;
double apertureHeight_;
CLHEP::Hep3Vector bfield_;
double magneticLength_;
double nominalMomentum_;
CLHEP::Hep3Vector refPointInMu2e_;
CLHEP::HepRotation inRotationInMu2e_;
CLHEP::HepRotation outRotationInMu2e_;
CLHEP::HepRotation magnetRotationInMu2e_;
CLHEP::Hep3Vector geometricCenterInMu2e_;
public:
ExtMonFNALMagnet();
// An initialized instance of this class should be obtained via ExtMonFNALMagnetMaker
friend class ExtMonFNALMagnetMaker;
const std::vector<double>& outerHalfSize() const { return outerHalfSize_; }
double apertureWidth() const { return apertureWidth_; }
double apertureHeight() const { return apertureHeight_; }
const CLHEP::Hep3Vector& bfield() const { return bfield_; }
double magneticLength() const { return magneticLength_; }
double nominalMomentum() const { return nominalMomentum_; }
// derived:
double trackBendRadius(double momentum) const;
double trackBendHalfAngle(double momentum) const;
double trackPinvFromRinv(double rinv) const { return trackBendRadius(rinv); }
double nominalBendHalfAngle() const { return trackBendHalfAngle(nominalMomentum()); }
// placement
const CLHEP::Hep3Vector& refPointInMu2e() const { return refPointInMu2e_; }
const CLHEP::HepRotation& inRotationInMu2e() const { return inRotationInMu2e_; }
const CLHEP::HepRotation& outRotationInMu2e() const { return outRotationInMu2e_; }
const CLHEP::HepRotation& magnetRotationInMu2e() const { return magnetRotationInMu2e_; }
const CLHEP::Hep3Vector& geometricCenterInMu2e() const { return geometricCenterInMu2e_; }
};
}// namespace mu2e
#endif/*EXTMONFNALMAGNET_HH*/
|
a50398c9a4d70872563416cdffb6800e151a4d95 | cd995785dbbb8aef4d94a907fbd4f29d4a57b9bf | /SignalRLibraries/SignalRServer/Infrastructure/Connection.cpp | 0225cedae2fe115c6cadb7d63ec325a6c21cab50 | [
"BSD-3-Clause"
] | permissive | haseebshujja/signalr-qt | 977d0e13dd034221df667571efefe1900746a914 | 6c91cfed14f4f02f3372e64e571f04f1787ba822 | refs/heads/master | 2021-01-17T23:47:08.403236 | 2014-05-12T12:53:35 | 2014-05-12T12:53:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | cpp | Connection.cpp | #include "Connection.h"
namespace P3 { namespace SignalR { namespace Server {
Connection::Connection()
{
}
}}}
|
37863792bc3be98605d5cc2f25de624eb10ca10e | a3bbe685d6189ad457a74a4ae37a043aa057ce29 | /testing/ecal/clientserver_test/src/clientserver_getservices.cpp | 2a0f3d9988c3e8621c1cbb3fcb7cdae0681d91ad | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-protobuf",
"LicenseRef-scancode-proprietary-license",
"BSL-1.0",
"LGPL-3.0-only",
"LGPL-2.0-only",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-only"
] | permissive | FlorianReimold/ecal | 907c6b0a1afd892b127da38f03b44f29fb11a3b1 | 3caed0408453ad07b7c52474f78612e5db072ce0 | refs/heads/master | 2023-04-29T16:13:55.718136 | 2023-04-14T09:26:50 | 2023-04-14T09:26:50 | 246,595,576 | 0 | 0 | Apache-2.0 | 2020-03-11T14:36:58 | 2020-03-11T14:36:58 | null | UTF-8 | C++ | false | false | 4,852 | cpp | clientserver_getservices.cpp | /* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* 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.
*
* ========================= eCAL LICENSE =================================
*/
#include <ecal/ecal.h>
#include <gtest/gtest.h>
#define CMN_MONITORING_TIMEOUT 5000
TEST(IO, GetServices)
{
// initialize eCAL API
eCAL::Initialize(0, nullptr, "clientserver_getservices");
std::map<std::tuple<std::string, std::string>, eCAL::Util::SServiceMethodInfo> service_info_map;
// add and expire simple service
{
// create server
eCAL::CServiceServer server("foo::service");
// add a description only
server.AddDescription("foo::method1", "foo::req_type1", "foo::req_desc1", "foo::resp_type1", "foo::resp_desc1");
// get all service
eCAL::Util::GetServices(service_info_map);
// check size
EXPECT_EQ(service_info_map.size(), 1);
// let's wait a monitoring timeout long
eCAL::Process::SleepMS(CMN_MONITORING_TIMEOUT);
// get all services again, service should not be expired
eCAL::Util::GetServices(service_info_map);
// check size
EXPECT_EQ(service_info_map.size(), 1);
}
// let's unregister them
eCAL::Process::SleepMS(CMN_MONITORING_TIMEOUT + 1000);
// get all services again, now all services
// should be removed from the map
eCAL::Util::GetServices(service_info_map);
// check size
EXPECT_EQ(service_info_map.size(), 0);
// add a service with method callback
{
// create server
eCAL::CServiceServer server("foo::service");
auto method_callback = [&](const std::string& /*method_*/, const std::string& /*req_type_*/, const std::string& /*resp_type_*/, const std::string& /*request_*/, std::string& /*response_*/) -> int
{
return 42;
};
// add method callback
server.AddMethodCallback("foo::method1", "foo::req_type1", "foo::resp_type1", method_callback);
// get all service
eCAL::Util::GetServices(service_info_map);
// check size
EXPECT_EQ(service_info_map.size(), 1);
// check attributes
std::string req_type, resp_type;
std::string req_desc, resp_desc;
eCAL::Util::GetServiceTypeNames("foo::service", "foo::method1", req_type, resp_type);
EXPECT_EQ(req_type, "foo::req_type1");
EXPECT_EQ(resp_type, "foo::resp_type1");
eCAL::Util::GetServiceDescription("foo::service", "foo::method1", req_desc, resp_desc);
EXPECT_EQ(req_desc, "");
EXPECT_EQ(resp_desc, "");
// change attributes
bool ret1 = server.AddDescription("foo::method1", "foo::req_type1-1", "foo::req_desc1-1", "foo::resp_type1-1", "foo::resp_desc1-1");
EXPECT_EQ(ret1, true);
// check attributes
eCAL::Util::GetServiceTypeNames("foo::service", "foo::method1", req_type, resp_type);
EXPECT_EQ(req_type, "foo::req_type1-1");
EXPECT_EQ(resp_type, "foo::resp_type1-1");
eCAL::Util::GetServiceDescription("foo::service", "foo::method1", req_desc, resp_desc);
EXPECT_EQ(req_desc, "foo::req_desc1-1");
EXPECT_EQ(resp_desc, "foo::resp_desc1-1");
// change attributes again (this will not overwrite the attributes anymore)
bool ret2 = server.AddDescription("foo::method1", "foo::req_type1-2", "foo::req_desc1-2", "foo::resp_type1-2", "foo::resp_desc1-2");
EXPECT_EQ(ret2, false);
// check attributes
eCAL::Util::GetServiceTypeNames("foo::service", "foo::method1", req_type, resp_type);
EXPECT_EQ(req_type, "foo::req_type1-1");
EXPECT_EQ(resp_type, "foo::resp_type1-1");
eCAL::Util::GetServiceDescription("foo::service", "foo::method1", req_desc, resp_desc);
EXPECT_EQ(req_desc, "foo::req_desc1-1");
EXPECT_EQ(resp_desc, "foo::resp_desc1-1");
// let's wait a monitoring timeout long
eCAL::Process::SleepMS(CMN_MONITORING_TIMEOUT);
// get all services again, service should not be expired
eCAL::Util::GetServices(service_info_map);
// check size
EXPECT_EQ(service_info_map.size(), 1);
}
// let's unregister them
eCAL::Process::SleepMS(CMN_MONITORING_TIMEOUT + 1000);
// get all services again, now all services
// should be removed from the map
eCAL::Util::GetServices(service_info_map);
// check size
EXPECT_EQ(service_info_map.size(), 0);
// finalize eCAL API
eCAL::Finalize();
}
|
352f86f8c4fce1d4f33b536dd5d719ff29846d37 | 634120df190b6262fccf699ac02538360fd9012d | /Develop/Game/UnitTest/TestFieldInfo.cpp | 2013b49ed8bfdcba3437c227b0276f6e9bb36a2d | [] | no_license | ktj007/Raiderz_Public | c906830cca5c644be384e68da205ee8abeb31369 | a71421614ef5711740d154c961cbb3ba2a03f266 | refs/heads/master | 2021-06-08T03:37:10.065320 | 2016-11-28T07:50:57 | 2016-11-28T07:50:57 | 74,959,309 | 6 | 4 | null | 2016-11-28T09:53:49 | 2016-11-28T09:53:49 | null | UTF-8 | C++ | false | false | 879 | cpp | TestFieldInfo.cpp | #include "stdafx.h"
#include "XFieldInfo.h"
SUITE(FieldInfo)
{
class FFieldInfo
{
public:
FFieldInfo()
{
}
~FFieldInfo()
{
}
void AddPvpArea(MRect rcArea)
{
PVP_AREA_INFO areaInfo;
areaInfo.rcArea = rcArea;
m_FieldInfo.m_PvPAreas.push_back(areaInfo);
}
XFieldInfo m_FieldInfo;
};
TEST_FIXTURE(FFieldInfo, FieldInfo_Cook_PvPAreas)
{
m_FieldInfo.m_fMinX = 0.0f;
m_FieldInfo.m_fMinY = 0.0f;
m_FieldInfo.m_fMaxX = 10000.0f;
m_FieldInfo.m_fMaxY = 10000.0f;
// #define FIELD_ATTR_CELL_SIZE 300 // cm
AddPvpArea(MRect(250.0f, 350.0f, 3001.0f, 3001.0f));
m_FieldInfo.Cook();
CHECK_EQUAL(0.0f, m_FieldInfo.m_PvPAreas[0].rcArea.left);
CHECK_EQUAL(300.0f, m_FieldInfo.m_PvPAreas[0].rcArea.top);
CHECK_EQUAL(3300.0f, m_FieldInfo.m_PvPAreas[0].rcArea.right);
CHECK_EQUAL(3300.0f, m_FieldInfo.m_PvPAreas[0].rcArea.bottom);
}
} |
538f6ea03795f9fc23810650e54957e69ac43cbf | 966f2f0abd134c9b66ac408480c84bd9dc9a8858 | /testing/test_ui_engine/src/main.cpp | 9c14da6222b987810458e969c5b55cf1b44db707 | [
"Apache-2.0"
] | permissive | DimonSE/OpenRC | c4a5237e5056a40aaeace226a0d1f73e6ed6d518 | 87ed34d7588c876a44e7bac51f6ae3ca48771ca7 | refs/heads/master | 2020-05-30T00:04:05.837041 | 2015-02-11T19:42:52 | 2015-02-11T19:42:52 | 30,492,453 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,498 | cpp | main.cpp | #include <avr/io.h>
#include <stdlib.h>
#include <stdio.h>
#include <avr/interrupt.h>
#include "../../../src/def.h"
#include "../../../src/Graphic.h"
#include "../../../src/UI_Engine.h"
#include "../../../src/Tasks.h"
#include <util/delay.h>
static volatile uint8_t KbdStat = 0;
//
// Interrupt
//
ISR (TIMER1_COMPA_vect)
{
static bool InterruptEnterFlag = false;
if(InterruptEnterFlag)
return;
// Иначе устанавливаем флаг, что мы уже находимся в данном прерывании
InterruptEnterFlag = true;
KeyboardDriver_Task();
InterruptEnterFlag = false;
return;
}
//
// Keyboard driver
//
void KeyboardDriver_Task()
{
uint8_t NewKbdStat = 0;
static uint8_t OldKbdStat = 0;
if(HB_UP) NewKbdStat |= B_UP;
if(HB_DOWN) NewKbdStat |= B_DOWN;
if(HB_LEFT) NewKbdStat |= B_LEFT;
if(HB_RIGHT) NewKbdStat |= B_RIGHT;
if(HB_BACK) NewKbdStat |= B_BACK;
if(HB_ENTER) NewKbdStat |= B_ENTER;
if(NewKbdStat != OldKbdStat)
OldKbdStat = NewKbdStat;
else
if(NewKbdStat != KbdStat)
KbdStat = NewKbdStat;
}
// Delay in msec
void WaitEmptyButtons(uint16_t Delay)
{
if(Delay == 0)
{
while(KbdStat)
;
}
else
{
while(KbdStat)
{
_delay_ms(1);
Delay--;
if(Delay == 0)
break;
};
}
}
uint8_t WaitButtonPress(uint8_t mask)
{
while(!(KbdStat & mask))
;
return KbdStat;
}
uint8_t AskButtons()
{
return KbdStat;
}
//
// Public functions
//
void ShowResult(const int8_t result)
{
gfx_ClearBuf();
char resultStr[12];
sprintf(resultStr, "Result=%i", result);
gfx_PrintString(20, TFT_ScreenHeight / 2, resultStr, COLOR_FRONT, Font_8x12);
gfx_Refresh();
_delay_ms(1000);
}
// Print MsgBox
void demo0(int8_t dummy)
{
MsgBox("Hello World!\nThis is a testing\nstring with \nmultiline\nsupport.", Font_8x12, "Test...", Font_8x8, 0);
WaitButtonPress(B_ANY);
WaitEmptyButtons();
}
void demo1(int8_t mode)
{
static const char* SelectBoxSmall[] = {
"Test1",
"Test2",
"And 3"
};
static const char* SelectBoxBig[] = {
"First ",
"Second",
"Third ",
"4 ",
"And Fv",
"----6-",
"---7--",
"---8--",
"---9--",
"--10--",
"--11--",
"--12--",
"--13--",
"--14--",
"--15--",
"--16--"
};
const char** Strings = mode ? SelectBoxBig : SelectBoxSmall;
const uint8_t Count = mode ? ARRAY_SIZE(SelectBoxBig) : ARRAY_SIZE(SelectBoxSmall);
int8_t result = SelectBox(Strings, Count, 0, Font_8x8, "Test Select", Font_6x8);
ShowResult(result);
}
void demo2(int8_t dummy)
{
static int16_t num = 5;
EditNumDlg(&num, PTR_INT16, -20, 20, 100, "Enter number:");
ShowResult(num);
}
void demo3(int8_t dummy)
{
static char Str[11] = "Name 1 ";
EditStrDlg(Str, 10, Font_8x12, "Enter a name:", Font_6x8);
}
void StartDemoMenu()
{
CMenu::Item items[] = {
{"Start MsgBox demo", demo0, NULL, 0},
{"Start Select small", demo1, NULL, 0},
{"Start Select big", demo1, NULL, 1},
{"Start Edit num", demo2, NULL, 0},
{"Start Edit name", demo3, NULL, 0}
};
CMenu menu("Test Menu", items, ARRAY_SIZE(items), Font_8x8);
menu.Run();
}
int main(void)
{
// PORTA use for menu buttons
PORTA = 0xFF;
DDRA = 0x00;
// PORTB.0, PORTB.1, PORTB.2 and PORTB.3 use by SPI in TFT display
PORTB = 0xFF;
DDRB = 0x0F;
// PORTL.0, PORTL.1 and PORTL.2 use as GPIO in TFT display
PORTL = 0xFF;
DDRL = 0x07;
// Timer/Counter 1 initialization
TCCR1B |= (1 << WGM12); // Configure timer 1 for CTC mode
TIMSK1 |= (1 << OCIE1A); // Enable CTC interrupt
sei(); // Enable global interrupts
OCR1A = 12500; // Set CTC compare value to 20Hz at 16MHz AVR clock, with a prescaler of 64
TCCR1B |= ((1 << CS10) | (1 << CS11)); // Start timer at Fcpu/64
gfx_Init();
while (1)
{
StartDemoMenu();
}
} |
9ca3cfe19b06e7e046e1f0461fb0ce831df460da | 932c87114caf22cb821d590788f0a6dba51fe354 | /src/entities/csprite3d.cpp | 131eb75cdeaa49843ea4c937c61bd472b7e8eb4a | [
"MIT"
] | permissive | meoblast001/citrine | bef772ecf0c95d57b92af55a0405087a05e9acf6 | 9e97484d33860213555d865ec81b301c59b0657c | refs/heads/master | 2021-01-20T17:54:23.277007 | 2016-06-26T22:00:32 | 2016-06-26T22:00:32 | 62,010,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | cpp | csprite3d.cpp | /*
Copyright (C) 2010 Braden Walters
This software may be modified and distributed under the terms of the MIT
license. See the LICENSE file for details.
*/
#include "csprite3d.h"
using namespace Citrine;
SmartPointer<Texture> Citrine::Sprite3D::GetTexture()
{
return texture;
}
void Citrine::Sprite3D::SetTexture(SmartPointer<Texture> texture)
{
this->texture = texture;
}
Transform* Citrine::Sprite3D::GetTransform()
{
return &transformation;
}
|
26da823378863a69e7efa19806f6fe8ad854aaac | 3e0405e67a035d3b9ce31a6e83bd805b6dc94041 | /src/windows/kernel/nt/syscall/types/token_information/TOKEN_OWNER_IMPL.cc | fa07cec47fcb0fcecc81875efdff5286c8a8539e | [
"Apache-2.0"
] | permissive | IntroVirt/IntroVirt | 33ec7fab4424656717d6ccb9ee87ba77e8f69b1f | e0953d1c9a12b6e501f6a876a07d188b7b80254a | refs/heads/main | 2022-12-22T05:47:27.038862 | 2022-12-15T22:52:21 | 2022-12-16T00:50:10 | 339,445,106 | 46 | 10 | Apache-2.0 | 2022-12-08T17:01:42 | 2021-02-16T15:37:13 | C++ | UTF-8 | C++ | false | false | 2,470 | cc | TOKEN_OWNER_IMPL.cc | /*
* Copyright 2021 Assured Information Security, 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 "TOKEN_OWNER_IMPL.hh"
#include "windows/kernel/nt/types/SID_IMPL.hh"
#include <introvirt/core/exception/BufferTooSmallException.hh>
#include <introvirt/util/compiler.hh>
namespace introvirt {
namespace windows {
namespace nt {
template <typename PtrType>
guest_ptr<void> TOKEN_OWNER_IMPL<PtrType>::OwnerPtr() const {
return this->ptr_->Owner.get(this->ptr_);
}
template <typename PtrType>
void TOKEN_OWNER_IMPL<PtrType>::OwnerPtr(const guest_ptr<void>& ptr) {
this->ptr_->Owner.set(ptr);
Owner_.reset();
}
template <typename PtrType>
SID* TOKEN_OWNER_IMPL<PtrType>::Owner() {
const auto* const_this = this;
return const_cast<SID*>(const_this->Owner());
}
template <typename PtrType>
const SID* TOKEN_OWNER_IMPL<PtrType>::Owner() const {
{
std::lock_guard lock(owner_initialized_);
if (!Owner_)
Owner_.emplace(this->ptr_->Owner.get(this->ptr_));
}
if (Owner_)
return (&*Owner_);
else
return nullptr;
}
template <typename PtrType>
void TOKEN_OWNER_IMPL<PtrType>::write(std::ostream& os, const std::string& linePrefix) const {
TOKEN_OWNER_IMPL_BASE::write(os, linePrefix);
os << linePrefix << "SID: ";
if (Owner())
os << *Owner() << '\n';
else
os << "null\n";
}
template <typename PtrType>
Json::Value TOKEN_OWNER_IMPL<PtrType>::json() const {
Json::Value result = TOKEN_OWNER_IMPL_BASE::json();
result["Owner"] = Owner()->json();
return result;
}
template <typename PtrType>
TOKEN_OWNER_IMPL<PtrType>::TOKEN_OWNER_IMPL(const guest_ptr<void>& ptr, uint32_t buffer_size)
: TOKEN_OWNER_IMPL_BASE(TOKEN_INFORMATION_CLASS::TokenOwner, ptr, buffer_size) {}
template class TOKEN_OWNER_IMPL<uint32_t>;
template class TOKEN_OWNER_IMPL<uint64_t>;
} // namespace nt
} // namespace windows
} // namespace introvirt |
1d354af58ceeda23eda6fd60419b9fee71874f88 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/4b/307cbf8e876540/main.cpp | 830036a3a5d9debeaedcee4f9dbf631537b6e4a2 | [] | 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 | 473 | cpp | main.cpp | #include <cassert>
#include <cmath>
struct precondition_call { };
struct in_call { };
template<typename F>
void operator+(precondition_call const&, F&& f) {
f();
}
template<typename F>
void operator+(in_call const&, F&& f) {
}
#define REQUIRE { precondition_call() + [&]
#define IN() (); in_call() +
#define ENSURE () + postcondition_call()
double sqrt(double x)
REQUIRE {
assert(x >= 0.0);
} IN {
} ENSURE (auto result) {
}
int main() {
} |
6f3cece9fd35f985beb9ff74321e3315fc5876f2 | f8588bc44fcf34d5ee90a1dd7d2200295d0f5ca4 | /算法提高/ADV-158.新建Microsoft Word文档.cpp | 614f45b73fe7c0b8c7c47b9cbff7d022fc54edee | [] | no_license | makixi/-OJ | cc389e8cd6c4d144c7456a89ed3692dee68a53de | 766228236b60579e4c794f5d55cd242f56e3b32f | refs/heads/master | 2021-09-08T15:58:46.474371 | 2018-03-11T01:27:40 | 2018-03-11T01:27:40 | 108,692,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 523 | cpp | ADV-158.新建Microsoft Word文档.cpp | #include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
bool num[2015];
int curr=1;
void findnext(){
for(int i=curr+1;true;++i)
if(!num[i]){
curr=i;break;
}
}
int main(){
int n;
scanf("%d",&n);
while(n--){
string op;
cin>>op;
if(op[0]=='N'){
cout<<curr<<"\n";
num[curr]=true;
findnext();
}else{
int a;
scanf("%d",&a);
if(!num[a])cout<<"Failed\n";
else{
cout<<"Successful\n";
num[a]=false;
curr=min(curr,a);
}
}
}
return 0;
}
|
cc55c85d6cc9c52662cc6c23f042e9921256c36d | ff2d7d46222a142c00062a1a1bac7ccfb991e5a3 | /SD_Micro/SD_Micro.ino | 628ec25be453adae389cc21c0269d346c99758b7 | [] | no_license | boeingnut/ArduinoProject | 041975b1a6f590e1d68a8cfb6b089ca4d8ad8d2c | e25e0a0a186b97a80bff7f7efaf029d017dbdd66 | refs/heads/master | 2020-03-07T13:35:15.266170 | 2018-03-31T06:58:36 | 2018-03-31T06:58:36 | 127,504,785 | 0 | 3 | null | 2019-10-30T15:30:36 | 2018-03-31T06:15:15 | C | UTF-8 | C++ | false | false | 739 | ino | SD_Micro.ino | #include <SPI.h>
#include <SD.h>
File datafile;
void setup() {
Serial.begin(9600);
//Serial1.begin(9600);
pinMode(10, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(10)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1) ;
}
Serial.println("card initialized.");
}
void loop() {
String dat=Serial.readString();
Serial.println(dat);// Read a byte of the serial port
datafile.close();
datafile = SD.open("data.txt", FILE_WRITE);
if (! datafile) {
//Serial.println("error opening datalog.txt");
// Wait forever since we cant write data
while (1) ;
}
datafile.println(dat);
datafile.flush();
}
|
fdb77b6fbc3e0feae040700ab8ec601e4f137932 | c1ff552e9be0baffd41786e86841fd726c43bb90 | /Top 100 most liked problems/palindromLinkedList.cpp | eb6b1c05a24653b9f0ce113c757e5f76ddfd0592 | [] | no_license | Rashi-Singh1/LeetCode | 4defe54fb8b90898c8c3576e5c2cc89ad8a9aee6 | 1cd4fa2c779340d8701138894894820654f444c5 | refs/heads/master | 2023-01-10T22:22:18.607348 | 2020-11-02T14:26:41 | 2020-11-02T14:26:41 | 225,888,208 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,272 | cpp | palindromLinkedList.cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* getReverse(ListNode* cur){
if(cur == NULL) return cur;
ListNode *prev = NULL, *next = cur->next;
while(cur){
cur->next = prev;
prev = cur;
cur = next;
next = cur == NULL ? NULL : cur->next;
}
return prev;
}
bool isPalindrome(ListNode* A) {
if(A == NULL || A->next == NULL) return true;
ListNode *cur = A, *prev = NULL;
long long int size = 0;
while(cur){
cur = cur->next;
size++;
}
size =(size+1ll)/2ll;
cur = A;
while(size > 0){
size--;
prev = cur;
cur = cur->next;
}
cur = getReverse(cur);
if(prev) prev->next = cur;
while(A && cur){
if(A->val != cur->val) return false;
cur = cur->next;
A = A->next;
}
return true;
}
}; |
620cc43518be2eaf72c04c2c6bcda55a87775984 | 621fb41f3e9956f8fbb42d738a0264e28ee0f09c | /lua_wrapper/lua_wrapper/MetaUtility.h | 7eb163bae14c5a78041154019e430c15071fc4df | [
"MIT"
] | permissive | androlua/lua-cpp-wrapper | f266f99a8067a7b76ec2dc0fc0e0a4a08217f75d | 9cb39e2c9275e3dfdf9942a4942b3003f861351f | refs/heads/master | 2020-03-20T20:40:29.569719 | 2018-04-21T16:07:58 | 2018-04-21T16:07:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,049 | h | MetaUtility.h | #pragma once
#include <tuple>
#include "MacroDefBase.h"
SHARELIB_BEGIN_NAMESPACE
//----把指针或引用统一转化为引用-------------------------------------------------------------------------------
namespace Internal
{
template<class T,
bool isPointer = std::is_pointer<typename std::remove_reference<T>::type>::value,
bool = std::is_lvalue_reference<T>::value>
struct ReferenceTypeHelper
{
enum : bool { is_pointer = isPointer };
using type = typename std::remove_pointer<typename std::remove_reference<T>::type>::type &;
};
template<class T>
struct ReferenceTypeHelper<T, false, false>
{
enum : bool { is_pointer = false };
using type = typename std::remove_pointer<typename std::remove_reference<T>::type>::type &&;
};
template<class T, bool = ReferenceTypeHelper<T>::is_pointer>
struct ToReferenceImpl
{
static typename ReferenceTypeHelper<T>::type ToReference(T && arg)
{
return static_cast<typename ReferenceTypeHelper<T>::type>(*arg);
}
};
template<class T>
struct ToReferenceImpl<T, false>
{
static typename ReferenceTypeHelper<T>::type ToReference(T && arg)
{
return static_cast<typename ReferenceTypeHelper<T>::type>(arg);
}
};
}
//把指针或引用统一转化为引用
template<class T>
typename Internal::ReferenceTypeHelper<T>::type to_reference(T && arg)
{
return Internal::ToReferenceImpl<T>::ToReference(std::forward<T>(arg));
}
//----生成参数序列-----------------------------------------------------------------------
template<size_t ... Index>
struct IntegerSequence
{};
namespace Internal
{
template<class T, size_t N>
struct MakeSequenceHelper;
template<size_t ... Index>
struct MakeSequenceHelper<IntegerSequence<Index...>, 0>
{
using type = IntegerSequence<Index...>;
};
template<size_t ... Index, size_t N>
struct MakeSequenceHelper<IntegerSequence<Index...>, N>
: public MakeSequenceHelper<IntegerSequence<N - 1, Index...>, N - 1>
{};
}
//根据可变参数生成参数序列,从0开始
template<size_t N>
struct MakeSequence
: public Internal::MakeSequenceHelper<IntegerSequence<>, N>
{
};
//----判断类是否有成员类型------------------------------------------------------------------------
namespace Internal
{
struct WrapInt
{
WrapInt(int){};
};
template<class T>
struct Identity
{
using type = T;
const T & operator()(const T & _Left) const
{ // apply identity operator to operand
return (_Left);
}
};
}
/* 判断类是否有成员
使用方法: 定义下面的类
template<class _ClassType>
struct HasMember...
HAS_MEMBER_TYPE_IMPL(membername)
之后就可用 HasMember...<className>::value 来判断一个类是否有某成员
实现细节: 两个静态函数必须用模板
1. 重载的函数,所有重载版本都会编译成二进制代码,遇到非法的就编译不过;
2. 模板是选择性编译,不是重载,只会选择一个合法的版本编译成二进制代码,非法的版本就不会编译,也就不会导致编译不过;
*/
//是否有成员(函数,静态变量), 有bug, 当类是模板时总是true,屏蔽
/*
#define HAS_MEMBER_IMPL(memberName) \
{ \
private: \
template<class T>static auto DeclFunc(int, decltype(typename T::memberName) * = 0)->std::true_type; \
template<class T>static auto DeclFunc(Internal::WrapInt)->std::false_type; \
public: \
static const bool value = decltype(DeclFunc<_ClassType>(0))::value; \
};
*/
//是否有成员(类型)
#define HAS_MEMBER_TYPE_IMPL(memberType) \
{ \
private: \
template<class T>static auto DeclFunc(int, typename T::memberType * = 0)->std::true_type; \
template<class T>static auto DeclFunc(Internal::WrapInt)->std::false_type; \
public: \
enum{ value = decltype(DeclFunc<_ClassType>(0))::value }; \
};
//----函数类型辅助----------------------------------------------------------------------------
namespace Internal
{
// 空,用来给宏传递空参数
#define NON_PARAM
// 下面的宏用来定义函数调用类型
#if defined(_WIN32) && defined(_M_IX86)
#ifndef NON_MEMBER_CALL_MACRO
#define NON_MEMBER_CALL_MACRO(FUNC) \
FUNC(__cdecl) \
FUNC(__stdcall) \
FUNC(__fastcall)
#endif // !NON_MEMBER_CALL_MACRO
#ifndef MEMBER_CALL_MACRO
#define MEMBER_CALL_MACRO(FUNC, CV_OPT) \
FUNC(__thiscall, CV_OPT) \
FUNC(__cdecl, CV_OPT) \
FUNC(__stdcall, CV_OPT) \
FUNC(__fastcall, CV_OPT)
#endif // !MEMBER_CALL_MACRO
#else
#ifndef NON_MEMBER_CALL_MACRO
#define NON_MEMBER_CALL_MACRO(FUNC) \
FUNC(NON_PARAM)
#endif // !NON_MEMBER_CALL_MACRO
#ifndef MEMBER_CALL_MACRO
#define MEMBER_CALL_MACRO(FUNC, CV_OPT) \
FUNC(NON_PARAM, CV_OPT)
#endif // !MEMBER_CALL_MACRO
#endif
//下面定义的宏, 用来生成模板特化
/* 指针变量本身的const,volatile属性并不需要专门特化,只要对变量应用 std::remove_cv_t 即可.
如果对它们专门特化, 生成的特化版本就太多了, 另外也会额外引入一些宏名字
*/
#ifndef MEMBER_CALL_CV_MACRO
#define MEMBER_CALL_CV_MACRO(FUNC) \
MEMBER_CALL_MACRO(FUNC, NON_PARAM) \
MEMBER_CALL_MACRO(FUNC, const) \
MEMBER_CALL_MACRO(FUNC, volatile) \
MEMBER_CALL_MACRO(FUNC, const volatile)
#endif // !MEMBER_CALL_CV_MACRO
}
//类型值
enum class CallType
{
FUNCTION,
POINTER_TO_FUNCTION,
POINTER_TO_MEMBER_FUNCTION,
POINTER_TO_MEMBER_DATA,
FUNCTION_OBJECT
};
/* 调用类型辅助
覆盖了函数,函数指针,成员函数指针,成员指针,函数对象,定义了以下几种类型别名:
result_t, 返回值类型;
arg_tuple_t, 参数绑定成tuple的类型;
arg_index_t, 参数的序列号类型, IntegerSequence<...>
class_t, (只有成员函数指针和成员指针才定义), 类类型
call_type, 值,CallType中定义的类型值
*/
template<class T, bool= std::is_class<T>::value>
struct CallableTypeHelper;
//函数类型特化
#define FUNCTION_HELPER(CALL_OPT) \
template<class _RetType, class... _ArgType> \
struct CallableTypeHelper<_RetType CALL_OPT (_ArgType...), false> \
{ \
using result_t = _RetType; \
using arg_tuple_t = std::tuple<_ArgType...>; \
using arg_index_t = typename MakeSequence<sizeof...(_ArgType)>::type; \
static const CallType call_type = CallType::FUNCTION; \
};
NON_MEMBER_CALL_MACRO(FUNCTION_HELPER)
#undef FUNCTION_HELPER
//函数指针类型特化
#define POINTER_TO_FUNCTION_HELPER(CALL_OPT) \
template<class _RetType, class... _ArgType> \
struct CallableTypeHelper<_RetType(CALL_OPT * )(_ArgType...), false> \
{ \
using result_t = _RetType; \
using arg_tuple_t = std::tuple<_ArgType...>; \
using arg_index_t = typename MakeSequence<sizeof...(_ArgType)>::type; \
static const CallType call_type = CallType::POINTER_TO_FUNCTION; \
};
NON_MEMBER_CALL_MACRO(POINTER_TO_FUNCTION_HELPER)
#undef POINTER_TO_FUNCTION_HELPER
//成员函数指针类型特化
#define POINTER_TO_MEMBER_FUNCTION_HELPER(CALL_OPT, CV_OPT) \
template<class _RetType, class _ClassType, class... _ArgType> \
struct CallableTypeHelper<_RetType(CALL_OPT _ClassType::* )(_ArgType...) CV_OPT, false> \
{ \
using class_t = _ClassType; \
using result_t = _RetType; \
using arg_tuple_t = std::tuple<_ArgType...>; \
using arg_index_t = typename MakeSequence<sizeof...(_ArgType)>::type; \
static const CallType call_type = CallType::POINTER_TO_MEMBER_FUNCTION; \
};
MEMBER_CALL_CV_MACRO(POINTER_TO_MEMBER_FUNCTION_HELPER)
#undef POINTER_TO_MEMBER_FUNCTION_HELPER
//成员指针类型特化
template<class _RetType, class _ClassType>
struct CallableTypeHelper<_RetType _ClassType::*, false>
{
using class_t = _ClassType;
using result_t = _RetType;
using arg_tuple_t = std::tuple<>;
using arg_index_t = typename MakeSequence<0>::type;
static const CallType call_type = CallType::POINTER_TO_MEMBER_DATA;
};
//函数对象、Lambda表达式类型特化
template<class T>
struct CallableTypeHelper<T, true>
{
using class_t = std::decay_t<T>;
using result_t = typename CallableTypeHelper<decltype(&class_t::operator()), false>::result_t;
using arg_tuple_t = typename CallableTypeHelper<decltype(&class_t::operator()), false>::arg_tuple_t;
using arg_index_t = typename CallableTypeHelper<decltype(&class_t::operator()), false>::arg_index_t;
static const CallType call_type = CallType::FUNCTION_OBJECT;
};
#undef NON_PARAM
#undef NON_MEMBER_CALL_MACRO
#undef MEMBER_CALL_MACRO
#undef MEMBER_CALL_CV_MACRO
SHARELIB_END_NAMESPACE
|
5b405a80068323d938ea856cc9457d5202c312b2 | 1245ab5de0f08f18fcb95011b88db264cd2f52f2 | /fem-dt-stokes-test/solverfactory.cpp | 110a3e151b4339aad55f12a1e464ec91ddcbe144 | [] | no_license | zhc/fem-dt-stokes-test | b9f4a25e63aca9b7449af609da58484bf133ac1c | e0e6e168b8e48eb0d7209013eb0e4f8008cf3db3 | refs/heads/master | 2020-05-21T12:51:10.917378 | 2013-08-15T01:07:18 | 2013-08-15T01:07:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,514 | cpp | solverfactory.cpp | #include "solverfactory.h"
#include "cnscheme.h"
#include "drscheme.h"
#include "prscheme.h"
#include "lbscheme.h"
#include "imscheme.h"
#include "vrscheme.h"
#include <map>
SolverFactory::SolverFactory(Settings &settings) : _settings(settings)
{
}
BaseSolver *SolverFactory::createEx()
{
_settings.prepareEx();
return create();
}
BaseSolver *SolverFactory::createTest()
{
_settings.prepareTest();
return create();
}
BaseSolver *SolverFactory::create()
{
std::map<std::string, BaseSolver*> solvers;
std::string solverNames;
BaseSolver *solver;
solver = new CNScheme(_settings);
solvers[solver->name()] = solver;
solver = new DRScheme(_settings);
solvers[solver->name()] = solver;
solver = new PRScheme(_settings);
solvers[solver->name()] = solver;
solver = new LBScheme(_settings);
solvers[solver->name()] = solver;
solver = new IMScheme(_settings);
solvers[solver->name()] = solver;
solver = new VRScheme(_settings);
solvers[solver->name()] = solver;
solver = 0;
for(std::map<std::string, BaseSolver*>::iterator it = solvers.begin(); it != solvers.end(); it++){
solverNames += it->first + " ";
if (it->first == _settings.scheme){
solver = it->second;
} else {
delete it->second;
}
}
if (!solver){
std::cerr << "Unknown scheme: " << _settings.scheme << ". Available schemes: "<< solverNames << std::endl;
exit(-1);
}
return solver;
}
|
fe9d7db74d9c9c73282c2377cadbf92f9b36befd | 7afe50d5d02ba4930daf3d6ffaa8075fb8f77c58 | /DPL/Topic_5/5_B.cpp | 91bf0e25767ad8ee30a22a24414333e79ac4aa4a | [] | no_license | Zu-rin/AOJ-Courses | 48dcd2789590227d17952a522f3b81e10e96ba87 | 9eb7cbc079613b922af24846aa2c248a48506e4a | refs/heads/master | 2023-03-18T10:14:14.239598 | 2021-02-26T05:45:10 | 2021-02-26T05:45:10 | 303,151,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | cpp | 5_B.cpp | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#define rep(i, n) for(i = 0; i < (n); i++)
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
#define MOD 1000000007
#define PI 3.14159265358979323846
#define INF 1 << 30
using namespace std;
typedef long long ll;
typedef pair<int, int> pp;
ll Pow(ll n, ll k) {
ll ans = 1, a = n % MOD;
while (k > 0) {
if (k & 1) {
ans *= a;
ans %= MOD;
}
a *= a;
a %= MOD;
k >>= 1;
}
return ans;
}
ll Inverse(ll a) {
return Pow(a, MOD - 2);
}
ll Combi(ll n, ll k) {
chmin(k, n - k);
if (k < 0)
return 0;
ll i, ans = 1;
for (i = 1; i <= k; i++) {
ans *= n--;
ans %= MOD;
ans *= Inverse(i);
ans %= MOD;
}
return ans;
}
int main(void) {
ll num, k, ans;
cin >> num >> k;
ans = Combi(k, num);
while (num > 0) {
ans *= num--;
ans %= MOD;
}
cout << ans << "\n";
return 0;
} |
89a05d235518e9b76571a89f2954181c8ac84bf7 | 69005ab4c8cc5d88d7996d47ac8def0b28730b95 | /msvc-cluster-realistic-1000/src/dir_6/perf348.cpp | f3bc794ee5fdb5d8d1b01edba0bd094e121ae494 | [] | no_license | sakerbuild/performance-comparisons | ed603c9ffa0d34983a7da74f7b2b731dc3350d7e | 78cd8d7896c4b0255ec77304762471e6cab95411 | refs/heads/master | 2020-12-02T19:14:57.865537 | 2020-05-11T14:09:40 | 2020-05-11T14:09:40 | 231,092,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | cpp | perf348.cpp | #include <Windows.h>
#include <vector>
#include <inc_9/header_192.h>
static_assert(sizeof(GenClass_192) > 0, "failed");
#include <inc_1/header_38.h>
static_assert(sizeof(GenClass_38) > 0, "failed");
#include <inc_4/header_94.h>
static_assert(sizeof(GenClass_94) > 0, "failed");
#include <inc_8/header_167.h>
static_assert(sizeof(GenClass_167) > 0, "failed");
std::vector<int> perf_func_348() {
LoadLibrary("abc.dll");
return {348};
}
|
7868900b614d0aeb45c208fd1ba963f0311189ae | 30f8f7477c38d2c4e0b995f28a96e7732dfe651e | /tests/fsm_retx_win.cc | 073ecb4388541c392815e4ae4a92e7d8d67f9ecb | [] | no_license | KinglittleQ/cs144 | 86e79d96759237ab303efcf6c693ceb23d739fb6 | 13fe156c60c7faf72f69fe3c15b90f624d64ee31 | refs/heads/master | 2022-12-17T01:38:18.389694 | 2020-09-08T06:21:47 | 2020-09-08T06:26:29 | 271,963,190 | 8 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,972 | cc | fsm_retx_win.cc | #include "fsm_retx.hh"
#include "tcp_config.hh"
#include "util.hh"
#include <algorithm>
#include <cstdlib>
#include <iostream>
using namespace std;
using State = TCPTestHarness::State;
int main() {
try {
TCPConfig cfg{};
cfg.recv_capacity = 65000;
auto rd = get_random_generator();
// multiple segments with intervening ack
{
WrappingInt32 tx_ackno(rd());
TCPTestHarness test_2 = TCPTestHarness::in_established(cfg, tx_ackno - 1, tx_ackno - 1);
string d1 = "asdf";
string d2 = "qwer";
test_2.execute(Write{d1});
test_2.execute(Tick(1));
test_2.execute(Tick(20));
test_2.execute(Write{d2});
test_2.execute(Tick(1));
test_2.execute(ExpectSegmentAvailable{}, "test 2 failed: cannot read after write()s");
check_segment(test_2, d1, true, __LINE__);
check_segment(test_2, d2, false, __LINE__);
test_2.execute(Tick(cfg.rt_timeout - 23));
test_2.execute(ExpectNoSegment{}, "test 2 failed: re-tx too fast");
test_2.execute(Tick(4));
check_segment(test_2, d1, false, __LINE__);
test_2.execute(Tick(2 * cfg.rt_timeout - 2));
test_2.execute(ExpectNoSegment{}, "test 2 failed: re-tx too fast");
test_2.send_ack(tx_ackno, tx_ackno + 4); // make sure RTO timer restarts on successful ACK
test_2.execute(Tick(cfg.rt_timeout - 2));
test_2.execute(ExpectNoSegment{}, "test 2 failed: re-tx of 2nd seg after ack for 1st seg too fast");
test_2.execute(Tick(3));
check_segment(test_2, d2, false, __LINE__);
}
// multiple segments without intervening ack
{
WrappingInt32 tx_ackno(rd());
TCPTestHarness test_3 = TCPTestHarness::in_established(cfg, tx_ackno - 1, tx_ackno - 1);
string d1 = "asdf";
string d2 = "qwer";
test_3.execute(Write{d1});
test_3.execute(Tick(1));
test_3.execute(Tick(20));
test_3.execute(Write{d2});
test_3.execute(Tick(1));
test_3.execute(ExpectSegmentAvailable{}, "test 3 failed: cannot read after write()s");
check_segment(test_3, d1, true, __LINE__);
check_segment(test_3, d2, false, __LINE__);
test_3.execute(Tick(cfg.rt_timeout - 23));
test_3.execute(ExpectNoSegment{}, "test 3 failed: re-tx too fast");
test_3.execute(Tick(4));
check_segment(test_3, d1, false, __LINE__);
test_3.execute(Tick(2 * cfg.rt_timeout - 2));
test_3.execute(ExpectNoSegment{}, "test 3 failed: re-tx of 2nd seg too fast");
test_3.execute(Tick(3));
check_segment(test_3, d1, false, __LINE__);
}
// check that ACK of new data resets exponential backoff and restarts timer
auto backoff_test = [&](const unsigned int num_backoffs) {
WrappingInt32 tx_ackno(rd());
TCPTestHarness test_4 = TCPTestHarness::in_established(cfg, tx_ackno - 1, tx_ackno - 1);
string d1 = "asdf";
string d2 = "qwer";
test_4.execute(Write{d1});
test_4.execute(Tick(1));
test_4.execute(Tick(20));
test_4.execute(Write{d2});
test_4.execute(Tick(1));
test_4.execute(ExpectSegmentAvailable{}, "test 4 failed: cannot read after write()s");
check_segment(test_4, d1, true, __LINE__);
check_segment(test_4, d2, false, __LINE__);
test_4.execute(Tick(cfg.rt_timeout - 23));
test_4.execute(ExpectNoSegment{}, "test 4 failed: re-tx too fast");
test_4.execute(Tick(4));
check_segment(test_4, d1, false, __LINE__);
for (unsigned i = 1; i < num_backoffs; ++i) {
test_4.execute(Tick((cfg.rt_timeout << i) - i)); // exponentially increasing delay length
test_4.execute(ExpectNoSegment{}, "test 4 failed: re-tx too fast after timeout");
test_4.execute(Tick(i));
check_segment(test_4, d1, false, __LINE__);
}
test_4.send_ack(tx_ackno, tx_ackno + 4); // make sure RTO timer restarts on successful ACK
test_4.execute(Tick(cfg.rt_timeout - 2));
test_4.execute(ExpectNoSegment{},
"test 4 failed: re-tx of 2nd seg after ack for 1st seg too fast after " +
to_string(num_backoffs) + " backoffs");
test_4.execute(Tick(3));
check_segment(test_4, d2, false, __LINE__);
};
for (unsigned int i = 0; i < TCPConfig::MAX_RETX_ATTEMPTS; ++i) {
backoff_test(i);
}
} catch (const exception &e) {
cerr << e.what() << endl;
return 1;
}
return EXIT_SUCCESS;
}
|
73fed9ec1efc694e9045dc20e4292ea2bf337aa4 | 7a5a2709a34d08a91911e875779e22af19ec70c0 | /cone.cpp | 4c9f7aecb417a093b23f1d65b655d3b051267fa1 | [] | no_license | shawnto/EyeSimulation | ef674abd359ca9d9b3f9415d08fa29130cc82035 | 7357087da81e0aa2d5058b75cd2c9a7569ffd4b0 | refs/heads/main | 2023-03-12T08:04:08.011135 | 2021-02-26T06:28:56 | 2021-02-26T06:28:56 | 342,484,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | cpp | cone.cpp | #include "cone.h"
Cone::Cone() {
texture = NULL;
pixels = NULL;
pitch = NULL;
this->roiBounds = cv::Rect();
}
Cone::Cone(cv::Rect roiBounds){
texture = NULL;
pixels = NULL;
pitch = NULL;
this->roiBounds = roiBounds;
}
Cone::~Cone() {
free();
}
void Cone::free() {
if (texture != NULL) {
SDL_DestroyTexture(texture);
}
}
bool Cone::initForRender(SDL_Renderer* render) {
texture = SDL_CreateTexture(render, SDL_PIXELFORMAT_BGR24, SDL_TEXTUREACCESS_STREAMING, roiBounds.width, roiBounds.height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
if (texture == NULL) {
return false;
}
return true;
}
bool Cone::lockTexture() {
SDL_LockTexture(texture, NULL, &pixels, &pitch);
if (pixels == NULL) {
return false;
}
return true;
}
bool Cone::unlockTexture() {
if (pixels == NULL) {
return false;
}
SDL_UnlockTexture(texture);
pixels = NULL;
pitch = 0;
return true;
}
bool Cone::updateTexture() {
if (!lockTexture()) {
return false;
}
std::memcpy(pixels, data.data, data.step * data.rows);
return unlockTexture();
}
bool Cone::hasDiff(cv::Mat* newData){
cv::Mat tmp;
//auto point = data->at<uchar>(cv::Point(x, y));
cv::absdiff(data, *newData, tmp);
return tmp.empty() == false;
}
void Cone::diffMatrix(cv::Mat* diff) {
cv::absdiff(*diff, data, newInput);
diff->copyTo(data);
}
void Cone::digestInput(cv::Mat* inputData) {
/*
Cone is a smaller but more detailed ROI of world. Get ROI, process data from that.
*/
cv::Mat sample = inputData->operator()(roiBounds);
if (data.data == NULL) {
sample.copyTo(data);
updatePending = true;
}
else {
updatePending = hasDiff(&sample);
if(updatePending) {
diffMatrix(&sample);
}
}
}
void Cone::renderState(SDL_Renderer* render) {
if (!updateTexture()) {
return;
}
SDL_Rect dst;
dst.x = roiBounds.x;
dst.y = roiBounds.y;
dst.w = roiBounds.width;
dst.h = roiBounds.height;
SDL_RenderCopy(render, texture, NULL, &dst);
} |
bb2c8a51bcdb464aeb3c48282be10f0ede593e01 | 13204a429a75d37b4645bce4dd947731400700ec | /Controll/Controll.ino | 98dbb3cbcc0735c9cee06c1bc283eed4a37b349c | [] | no_license | ISHAN-SACHINTHA/Arduino-projects | 5c3a04e534215e386d406d9b9eb49c6d3d438672 | 2c2753c1ac88623398950e79d01016233d70177c | refs/heads/main | 2023-02-03T15:05:51.071894 | 2020-12-15T04:06:46 | 2020-12-15T04:06:46 | 321,547,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 961 | ino | Controll.ino | int incomingByte = 0; // for incoming serial data
void setup()
{
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
}
void loop()
{
// send data only when you receive data:
if (Serial.available() > 0)
{ // read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
if (incomingByte==48)
digitalWrite(8, LOW);
digitalWrite(7, LOW);
analogWrite (9, 0);
if (incomingByte==49)
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
analogWrite (9, 50);
if (incomingByte==50)
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
analogWrite (9, 100);
if (incomingByte==51)
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
analogWrite (9, 100);
if (incomingByte==52)
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
analogWrite (9, 200);
}
|
d3fcedbd661ab3a95a12b57658b53effd13d5deb | 4d332a73a20a3eb86bcb34d4b09fc100c3f11325 | /07_Distance2Servo/07_Distance2Servo.ino | c9a1962489e57638768055366acd6932f3881209 | [] | no_license | sktomor/fluid-networks | ff4b287e407d1c2966b67ab2982938832b34cb48 | 9548735d705ce51f4edbb2e4189d33d1905958f8 | refs/heads/master | 2023-04-07T17:49:51.543480 | 2021-04-15T17:26:59 | 2021-04-15T17:26:59 | 357,229,007 | 1 | 0 | null | 2021-04-15T17:27:00 | 2021-04-12T14:40:51 | null | UTF-8 | C++ | false | false | 1,132 | ino | 07_Distance2Servo.ino | /*
Example taken from Seeestudio Wiki
for the Grove Ultrasonic Ranger
https://wiki.seeedstudio.com/Grove-Ultrasonic_Ranger/
adapted to work with Arduino Grove Carrier (on MKR1010)
https://www.arduino.cc/en/Guide/MKRConnectorCarrier
and with Servo
by Davide Gomba
Library here
https://github.com/Seeed-Studio/Seeed_Arduino_UltrasonicRanger/archive/master.zip
Install Library Sketch>include Library> Add Zip Library
*/
#include <Servo.h>
#include "Ultrasonic.h"
int led = 5;
Servo myservo; // create servo object to control a servo
Ultrasonic ultrasonic(0);
int val; // variable to read the value from the analog pin
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
myservo.attach(4); // attaches the servo on pin 4 to the servo object
}
void loop()
{
long RangeInCentimeters;
RangeInCentimeters = ultrasonic.MeasureInCentimeters(); // two measurements should keep an interval
Serial.println(RangeInCentimeters);//0~400cm
val = map(RangeInCentimeters, 0, 250, 0, 180); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val);
delay(25);
}
|
2ad8f950f5f0163805ab9990ba6af92677e35d58 | 5a3c37ff858defe9716dcba3d8fb23ad701d4d45 | /Survival_Days.cpp | f50360c19c8a2953373455d291b7b9168a50a579 | [] | no_license | Ashish-A-Kulkarni/HackerRank_SE-A_Assignment | 04775e9f0dc76fb2f8cfbe71b2d961deb566c6b6 | 64140adfc4b45027dc8cfac52086124b5161068e | refs/heads/master | 2022-10-16T03:43:59.106474 | 2020-06-08T13:47:50 | 2020-06-08T13:47:50 | 270,680,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | cpp | Survival_Days.cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
if (x == 7 && y == 3)
{
cout << "9\n";
}
else
{
int a = 0, b, c = x % y;
b = x / y;
a = b + x;
c = c + b;
while ((c / y) >= 1)
{
a = a + c / y;
c = (c / y) + (c % y);
}
cout << a << "\n";
}
return 0;
} |
0631bb9626ee261899f15b3a64f7af6dabd43fb7 | 83c33d30a207ede9eb38568fef840147c4b452f1 | /include/uc/libmitdb.h | ea56fbd93d6235920f211c0bf185c110cbcd66d0 | [] | no_license | guohong365/ZN3000 | f10a7c3255a4c29fd2c47b35eb649efa3eee7ce4 | 5cb466884887da4bcd3db7e57bd52be76f984efd | refs/heads/master | 2020-03-29T04:51:02.645262 | 2019-07-02T14:39:09 | 2019-07-02T14:39:09 | 149,551,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | h | libmitdb.h | #pragma once
#include <uc/libuc.h>
#ifdef LIBMITDB_EXPORTS
#define LIB_MITDB_API __declspec(dllexport)
#define LIB_MITDB_CLASS __declspec(dllexport)
#define LIB_MITDB_EXTERN
#else
#define LIB_MITDB_API __declspec(dllimport)
#define LIB_MITDB_CLASS __declspec(dllimport)
#define LIB_MITDB_EXTERN extern
#endif
namespace uc{
namespace signals
{
void LIB_MITDB_API wfdbSetup(const char *database_path);
void LIB_MITDB_API initMitdb(const char *database_path=nullptr);
}
}
#ifndef LIBMITDB_EXPORTS
#pragma comment(lib, "libmitdb" _UC_PLATFORM ".lib")
#endif |
33ea5662ade5b763ddbe1f93b9ac1f1a851e7b09 | 93176e72508a8b04769ee55bece71095d814ec38 | /Testing/Code/BasicFilters/otbStreamingInnerProductVectorImageFilter.cxx | e9a3abd0d6f6d8c510223b57df1c102da12ba739 | [] | no_license | inglada/OTB | a0171a19be1428c0f3654c48fe5c35442934cf13 | 8b6d8a7df9d54c2b13189e00ba8fcb070e78e916 | refs/heads/master | 2021-01-19T09:23:47.919676 | 2011-06-29T17:29:21 | 2011-06-29T17:29:21 | 1,982,100 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | cxx | otbStreamingInnerProductVectorImageFilter.cxx | /*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbStreamingInnerProductVectorImageFilter.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include <fstream>
int otbStreamingInnerProductVectorImageFilter(int argc, char* argv[])
{
const char * inputFileName = argv[1];
const char * outfname = argv[2];
const bool centerdata = atoi(argv[3]);
typedef double PixelType;
const unsigned int Dimension = 2;
// Typedef
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingInnerProductVectorImageFilter<ImageType> FilterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inputFileName);
// Instantiation object
FilterType::Pointer filter = FilterType::New();
filter->GetStreamer()->SetNumberOfLinesStrippedStreaming( 10 );
filter->SetCenterData(centerdata);
filter->SetInput(reader->GetOutput());
filter->Update();
std::ofstream file;
file.open(outfname);
file.precision(10);
file << std::fixed;
file << "Inner Product: Dim [" << filter->GetInnerProduct().size() << "]:" << std::endl;
file << filter->GetInnerProduct() << std::endl;
file.close();
return EXIT_SUCCESS;
}
|
a5a7e6b51b026eae0aeacc9c314c17c094c993d8 | 59b2d9114592a1151713996a8888456a7fbfe56c | /hdu/1521.cpp | d19edee22997cdf0eb5c62cc5b0241377f3aace0 | [] | no_license | 111qqz/ACM-ICPC | 8a8e8f5653d8b6dc43524ef96b2cf473135e28bf | 0a1022bf13ddf1c1e3a705efcc4a12df506f5ed2 | refs/heads/master | 2022-04-02T21:43:33.759517 | 2020-01-18T14:14:07 | 2020-01-18T14:14:07 | 98,531,401 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,605 | cpp | 1521.cpp | /* ***********************************************
Author :111qqz
Created Time :2016年02月27日 星期六 19时48分31秒
File Name :code/hdu/1521.cpp
************************************************ */
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define fst first
#define sec second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ms(a,x) memset(a,x,sizeof(a))
typedef long long LL;
#define pi pair < int ,int >
#define MP make_pair
using namespace std;
const double eps = 1E-8;
const int dx4[4]={1,0,0,-1};
const int dy4[4]={0,-1,1,0};
const int inf = 0x3f3f3f3f;
double a[15],tmp[15],f[15];
int n,m;
int num[15];
void pre()
{
f[0] = 1.0;
for ( int i = 1 ;i <= 10 ; i++)
{
f[i] = f[i-1]*i*1.0;
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("code/in.txt","r",stdin);
#endif
pre();
while (scanf("%d %d",&n,&m)!=EOF)
{
for ( int i = 1 ; i <= n ; i++) scanf("%d",&num[i]);
ms(a,0);
ms(tmp,0);
for ( int i = 0 ; i <= num[1] ; i++)
{
a[i] = 1.0/f[i];
}
for ( int i = 2 ; i <= n ; i++)
{
for ( int j = 0 ; j <= m ; j++)
{
for ( int k = 0 ; k+j<=m&&k<=num[k] ; k++)
{
tmp[j+k] += a[j]/f[k];
}
}
for ( int j = 0 ; j <= m ; j++)
{
a[j] = tmp[j];
tmp[j] = 0.0;
}
}
double ans = a[m]*f[m];
printf("%d\n",int(ans+0.5));
}
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0;
}
|
309fd7d97648bc9312764d1b23354a36a6815e9e | 83b23e966934902b08205f4aa4d60eb68e0dd395 | /hozzavalo.h | 05f449ffa09e0fd75e2e359c9456558b5b790c0a | [] | no_license | Shaat123/nhf | a0c4e2cd85eaa543688256b73bc67c32c695bd90 | 1527ca33ae1b93cfdf5eaf3989b45be0f677202f | refs/heads/master | 2020-04-08T21:01:13.650558 | 2015-05-08T14:03:27 | 2015-05-08T14:03:27 | 35,282,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | h | hozzavalo.h | #ifndef HOZZAVALO_H_INCLUDED
#define HOZZAVALO_H_INCLUDED
#include <iostream>
#include "String.h"
#include "memtrace.h"
class Hozzavalo{
int sorszam;
double mennyiseg;
String mertekegyseg;
String anyag;
public:
Hozzavalo():sorszam(0), mennyiseg(0), mertekegyseg(), anyag(){}
Hozzavalo(int s, double am, String& unit, String& mat) :sorszam(s), mennyiseg(am), mertekegyseg(unit), anyag(mat){}
void operator=(Hozzavalo& h);
void kiir(std::ostream&);
};
#endif // HOZZAVALO_H_INCLUDED
|
62aca8a6503963b52d1db8743eb2dbe4f79495ef | 9a67cfce5187e0c88c52b72cf0fab15e0af43e58 | /src/SequenceView.cpp | d7646c9d872cb2323a086f21f677b081581acd6f | [] | no_license | helenginn/breathalyser | 0e4e2dce5d1ff1c3a1b819d2de4ded3e3e130c0b | 152e3cbb9995475c86fdd71bad17bc37ca5c3d52 | refs/heads/master | 2023-04-08T18:46:28.447279 | 2021-04-17T16:03:29 | 2021-04-17T16:03:29 | 330,400,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,882 | cpp | SequenceView.cpp | // breathalyser
// Copyright (C) 2019 Helen Ginn
//
// 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 <https://www.gnu.org/licenses/>.
//
// Please email: vagabond @ hginn.co.uk for more details.
#include "SequenceView.h"
#include "FastaMaster.h"
#include "FastaGroup.h"
#include "Fasta.h"
#include <QScrollArea>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QCheckBox>
#include <QVBoxLayout>
#include <hcsrc/FileReader.h>
QBoxLayout *SequenceView::setupWindow()
{
QWidget *w = centralWidget();
if (w != NULL)
{
w->hide();
w->deleteLater();
}
QScrollArea *area = new QScrollArea(NULL);
QVBoxLayout *areaBox = new QVBoxLayout();
area->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
area->setLayout(areaBox);
setCentralWidget(area);
return areaBox;
}
SequenceView::SequenceView(QWidget *parent, FastaMaster *m)
: QMainWindow(parent)
{
setStyleSheet("background-color:light gray;");
setAutoFillBackground( true );
_master = m;
_master->setSequenceView(this);
setupWindow();
_fasta = NULL;
_group = NULL;
}
void standardiseWidths(std::vector<QLabel *> labels)
{
int biggest = 0;
for (size_t i = 0; i < labels.size(); i++)
{
QLabel *l = labels[i];
int width = l->fontMetrics().boundingRect(l->text()).width();
biggest = std::max(width, biggest);
}
for (size_t i = 0; i < labels.size(); i++)
{
labels[i]->setMaximumSize(biggest + 10, 20);
}
}
QLabel *SequenceView::addToLayout(QBoxLayout *box, std::string left,
std::string right)
{
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setAlignment(Qt::AlignTop);
hbox->setSizeConstraint(QLayout::SetMinAndMaxSize);
QLabel *l = new QLabel(QString::fromStdString(left), this);
QLabel *r = new QLabel(QString::fromStdString(right), this);
hbox->addWidget(l);
hbox->addWidget(r);
box->addLayout(hbox);
return l;
}
void SequenceView::populate(FastaGroup *g)
{
_group = g;
_group = NULL;
QBoxLayout *box = setupWindow();
std::vector<QLabel *> labels;
QVBoxLayout *metaBox = new QVBoxLayout();
metaBox->setAlignment(Qt::AlignTop);
{
std::string text = g->generateText();
QLabel *l = addToLayout(metaBox, "Group name:", text);
labels.push_back(l);
}
{
std::string text = i_to_str(g->fastaCount());
QLabel *l = addToLayout(metaBox, "Sequence count:", text);
labels.push_back(l);
}
std::string text = g->countDescription();
QLabel *l = addToLayout(metaBox, "Representative mutations:", text);
labels.push_back(l);
standardiseWidths(labels);
box->addLayout(metaBox);
}
void SequenceView::populate(Fasta *f)
{
_fasta = f;
_group = NULL;
QBoxLayout *box = setupWindow();
std::vector<QLabel *> labels;
QVBoxLayout *metaBox = new QVBoxLayout();
metaBox->setAlignment(Qt::AlignTop);
metaBox->setSizeConstraint(QLayout::SetMinAndMaxSize);
for (size_t i = 0; i < _master->titleCount(); i++)
{
QHBoxLayout *hbox = new QHBoxLayout();
QString title = QString::fromStdString(_master->title(i));
std::string val = _master->valueForKey(f, _master->title(i));
QLabel *l = new QLabel(title, this);
labels.push_back(l);
QLabel *r = new QLabel(QString::fromStdString(val), this);
hbox->addWidget(l);
hbox->addWidget(r);
metaBox->addLayout(hbox);
}
standardiseWidths(labels);
box->addLayout(metaBox);
}
|
055d0881795498ec4e5fad9b65509b98fef8ee6a | a3cc0a92c2fc07efaf763441673ede7d435d7bc7 | /8 recursion/subsetsof array.cpp | 2faa6f67675eff06292062010bea3b56d123278f | [] | no_license | codeboy47/Coding-Problems | 73abbf820f35093bcc591eecd304964d640882a3 | eefe6a246abf81705aafc325035e5c419239eee2 | refs/heads/master | 2021-06-11T11:58:11.044063 | 2017-01-14T20:39:18 | 2017-01-14T20:39:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 517 | cpp | subsetsof array.cpp | #include<iostream>
using namespace std;
void subsets(int *a,int n,int index,int *s){
if(*a==0){
for(int i=0;i<index;i++){
cout<<s[i];
}
cout<<endl;
return ;
}
//cout<<*a<<" ";
subsets(a+1,n,index,s);
s[index]=*a;
s[index+1]=0;
subsets(a+1,n,index+1,s);
return;
}
int main(){
int i,a[100],n,s[100];
cout<<"n ";
cin>>n;
for(i=0;i<n;i++){
cin>>a[i];
}
a[n]=0;
s[0]=a[n];
subsets(a,n,0,s);
}
|
103f87c257732e5c8bc4f807e75d43feae1720a9 | 4221155626b6aafa7ece33cd094070517a88b129 | /Data.cpp | 2312c86d4edaee494b72bb59e874e31f81c01cce | [] | no_license | alexandremendoncaalvaro/temperatura-aqui | 8d57e3adbc5efe456985e7fe30404f86b522e486 | 8b40a736ca5ad033d63027c1507a7a8dcd0a147a | refs/heads/master | 2020-04-24T15:18:17.657653 | 2019-02-24T23:04:44 | 2019-02-24T23:04:44 | 172,060,528 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,046 | cpp | Data.cpp | #include "Data.h"
bool Parameters::mountFileSystem()
{
Serial.print(F("Mounting system file.."));
if (!SPIFFS.begin())
{
Serial.println(F("Fail!"));
return false;
}
Serial.println(F("OK!"));
return true;
}
bool Parameters::loadParameters()
{
Serial.print(F("Load parameters from config file..."));
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile)
{
Serial.println(F("Fail!"));
return false;
}
size_t size = configFile.size();
if (size > 1024)
{
Serial.println(F("The config file is to big!"));
return false;
}
std::unique_ptr<char[]> buffer(new char[size]);
configFile.readBytes(buffer.get(), size);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buffer.get());
if (!json.success())
{
Serial.println(F("Fail on parse to Json!"));
return false;
}
strcpy(parameters.wifiSsid, json["wifiSsid"]);
strcpy(parameters.wifiPassword, json["wifiPassword"]);
strcpy(parameters.deviceId, json["deviceId"]);
strcpy(parameters.minutesSleeping, json["minutesSleeping"]);
strcpy(parameters.mqttServer, json["mqttServidor"]);
strcpy(parameters.mqttPort, json["mqttPorta"]);
strcpy(parameters.mqttUser, json["mqttUsuario"]);
strcpy(parameters.mqttPassword, json["mqttPassword"]);
strcpy(parameters.mqttTopic, json["mqttTopic"]);
delay(1000);
Serial.println(F("OK!"));
configFile.close();
return true;
}
bool Parameters::saveParameters()
{
Serial.print(F("Saving parameters..."));
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["wifiSsid"] = parameters.wifiSsid;
json["wifiPassword"] = parameters.wifiPassword;
json["deviceId"] = parameters.deviceId;
json["minutesSleeping"] = parameters.minutesSleeping;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile)
{
Serial.println("Fail when open config file to write!");
return false;
}
json.printTo(configFile);
delay(1000);
Serial.println(F("OK!"));
configFile.close();
return true;
}
void Parameters::printParameters()
{
Serial.println(F("--------------------------"));
Serial.println(F("CURRENT PARAMETERS:"));
Serial.print(F("SSID: "));
Serial.println(parameters.wifiSsid);
Serial.print(F("Password: "));
Serial.println(parameters.wifiPassword);
Serial.print(F("Device ID: "));
Serial.println(parameters.deviceId);
Serial.print(F("Minutes Sleeping: "));
Serial.println(parameters.minutesSleeping);
Serial.print(F("MQTT Server: "));
Serial.print(parameters.mqttServer);
Serial.print(F(":"));
Serial.println(parameters.mqttPort);
Serial.print(F("MQTT User: "));
Serial.println(parameters.mqttUser);
Serial.print(F("MQTT Password: "));
Serial.println(parameters.mqttPassword);
Serial.print(F("MQTT Topic: "));
Serial.println(parameters.mqttTopic);
Serial.println(F("--------------------------"));
}
bool Parameters::begin()
{
if (!parameters.mountFileSystem()) return false;
if (!parameters.loadParameters()) return false;
parameters.printParameters();
return true;
}
Parameters parameters; |
9da9a5da4e05d3bcbd724dfdbb80a266b8f5701e | 8096035ff91117f760419362ec008aaf3154610c | /Examples/iostreams_225/iostreams_225.cpp | 4169d7f52ba7e0348649c015b9eafc45d847fd4c | [] | no_license | kk2491/CPP_Quick_Tour | 15f64f66df1e99f1dcf5774d7f4127ab2f8640d4 | acbd781864ce02bbe0e27e60eaedac729c8aa4fc | refs/heads/main | 2023-07-19T19:03:16.769720 | 2021-01-21T09:17:27 | 2021-01-21T09:17:27 | 316,258,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | iostreams_225.cpp | #include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream in_file;
std::string str;
int num_1;
double num_2;
in_file.open("check.txt");
if (!in_file.is_open()) {
std::cerr << "Not open" << std::endl;
return 1;
}
std::cout << "File is open" << std::endl;
// in_file << str << num_1 << num_2;
in_file >> str; // This just reads the file till next whitespace or enter
std::cout << str << std::endl;
in_file >> num_1;
std::cout << num_1 << std::endl;
in_file >> num_2;
std::cout << num_2 << std::endl;
in_file.close();
return 0;
} |
d906fc72abfd8f8447a518af12aec77c4f940b9e | 3a35ec06045139d57b9013006e83fd9ad09f7e82 | /emulator/src/fun.cpp | 8c2ef76957629c9b27881c8460494985954ddb7a | [] | no_license | Agerran/gluonvm | f1d6b80fa6bab071acbc5bda5240e639b375309a | 142b07182c8c02ebc9087fe5c257e1948c85939f | refs/heads/master | 2021-01-20T06:55:09.144876 | 2015-11-09T00:52:23 | 2015-11-09T00:52:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | cpp | fun.cpp | #include "fun.h"
#include <string.h>
#include "heap.h"
namespace gluon {
namespace fun {
BoxedFun* box_fun(FunEntry* fe, Word* mem, Term pid, Term* frozen) {
BoxedFun* bf = (BoxedFun*)mem;
// pack nfree and arity, then create_subtag() will shift it and tag as
// boxedfun
bf->hdr =
term_tag::BoxedFun::create_subtag((fe->num_free << 8) | fe->mfa.arity);
G_ASSERT(pid.is_pid());
bf->pid = pid;
bf->module = fe->mfa.mod;
bf->index = fe->index;
std::copy(fe->uniq, fe->uniq + 4, bf->uniq);
//::memcpy(&bf->uniq, fe->uniq, sizeof(u32_t) * 4);
bf->old_index = fe->old_index;
bf->old_uniq = fe->old_uniq;
bf->fun_entry = fe;
std::copy(frozen, frozen + fe->num_free, bf->frozen);
//::memcpy(bf->frozen, frozen, fe->num_free * sizeof(Term));
return bf;
}
Term box_fun(proc::Heap* heap, FunEntry* fe, Term pid, Term* frozen) {
Word* p8 = heap->allocate<Word>(
calculate_word_size(sizeof(BoxedFun) + fe->num_free));
BoxedFun* p = fun::box_fun(fe, p8, pid, frozen);
return FunObject::make(p);
}
} // ns fun
} // ns gluon
|
4b8ad6e6d8266e7fa60a8f138df62a813b3a8447 | 0d4864ca111609a82e95f0cfe79d0816073c3244 | /include/bloombergdata.h | f1b16fff4eadd2e28747e87eedd83c8c85fa645b | [] | no_license | Ilya-Grigoryan/Cornerstone_FVM | 1c5772894474c07fab6219ede9219faf8c43760f | 4dc88655aae1b9b013505b480b67caa8a9f6ef94 | refs/heads/master | 2020-04-27T18:27:21.437077 | 2014-02-13T21:07:20 | 2014-02-13T21:07:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,629 | h | bloombergdata.h | #pragma once
#define PX_CLOSE_QTD "PX_CLOSE_QTD"
#define PX_CLOSE_1D "PX_CLOSE_1D"
#define T12M_DIL_EPS_CONT_OPS "T12M_DIL_EPS_CONT_OPS"
#define IS_AVG_NUM_SH_FOR_EPS "IS_AVG_NUM_SH_FOR_EPS"
#define ARD_DEPREC_DEPLETION_AMORT "ARD_DEPREC_DEPLETION_AMORT"
#define BS_SH_OUT "BS_SH_OUT"
#define BS_TOT_ASSET "BS_TOT_ASSET"
#define BS_GOODWILL "BS_GOODWILL"
#define BS_TOT_LIAB2 "BS_TOT_LIAB2"
#define BS_NET_FIX_ASSET "BS_NET_FIX_ASSET"
#define ARD_EXPLORATION_EXPENSE "ARD_EXPLORATION_EXPENSE"
#define OIL_PRODUCTION_WORLD "OIL_PRODUCTION_WORLD"
#define GAS_PRODUCTION_WORLD "GAS_PRODUCTION_WORLD"
#define OIL_END_YEAR_WORLD "OIL_END_YEAR_WORLD"
#define GAS_END_YEAR_WORLD "GAS_END_YEAR_WORLD"
//////////////////////////////////////////////////////////////////
struct CEnergyData
{
public:
char m_szTicker[64];
double m_fPriceQtr;
double m_fPrice1D;
double m_fEps12M;
double m_fSharesAvgEps;
double m_fDeprAmort;
double m_fShares;
double m_fAssets;
double m_fGoodwill;
double m_fLiabs;
double m_fFixedAssets;
double m_fExporationExpense;
double m_fOilProduction;
double m_fGasProduction;
double m_fOilReserve;
double m_fGasReserve;
};
typedef CArray<CEnergyData, CEnergyData> CEnergyDataArray;
//////////////////////////////////////////////////////////////////
class _declspec(dllexport) CBloombergData
{
public:
CBloombergData(void);
~CBloombergData(void);
public:
static bool GetEnergyData(CStringArray &arTickers, CEnergyDataArray& arData);
protected:
static bool ProcessResponseEnergyData(void* pEvent, CEnergyDataArray& arData);
};
|
a00ddb5abeb2c92c05cedfc8aec187bc54717a45 | 4b4a48bfd4dfaa27c5c4e1fecf719766a82a92a6 | /LIB/WXRTL/XRWIN.CPP | d55ceb9d28b5e7b826d82f6326c5c5b7b347865b | [] | no_license | codecandiescom/ktelnet-V2.00.950 | 1b062c56ecfc98a8f026addc9dfc29b401b5b5f9 | 95be69fee6bba4a0266ed6daace705f5cc5ae040 | refs/heads/master | 2020-04-20T20:47:54.683641 | 2019-02-04T14:10:40 | 2019-02-04T14:10:40 | 169,088,045 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 11,755 | cpp | XRWIN.CPP | /*
* Copyright (c) 1998-2000 Thomas Nyström and Stacken Computer Club
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Kungliga Tekniska
* Högskolan and its contributors.
*
* 4. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE 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.
*/
#define STRICT
#define _WXRTL_DLL
#include "wxrtl.h"
#pragma hdrstop
#include <owl\decmdifr.h>
#include <string.h>
//================================================================
//
// Common routines
//
//================================================================
static int
_WXSetupAttr(TWindow &w, Registry *RegData)
{
int nCmdShow, i;
char buf[128];
try {
RegData->Open();
strcpy(buf, RegData->GetString("WindowPos", 128));
if (sscanf(buf, "%d, %d",
&w.Attr.X, &w.Attr.Y) != 2)
throw RegistryFail("");
strcpy(buf, RegData->GetString("WindowSize", 128));
RegData->Close();
if (sscanf(buf, "%d, %d, %d",
&i, &w.Attr.W, &w.Attr.H) != 3)
throw RegistryFail("");
switch (i) {
case SIZE_MAXIMIZED:
nCmdShow = SW_SHOWMAXIMIZED;
w.Attr.Style |= WS_MAXIMIZE;
break;
case SIZE_MINIMIZED:
nCmdShow = SW_SHOWMINIMIZED;
w.Attr.Style |= WS_MINIMIZE;
break;
case SIZE_RESTORED:
nCmdShow = SW_RESTORE;
break;
case -1:
nCmdShow = SW_RESTORE;
w.Attr.Style &= ~WS_VISIBLE;
break;
default:
nCmdShow = SW_SHOWMAXIMIZED;
w.Attr.Style |= WS_MAXIMIZE;
break;
}
}
catch (RegistryFail) {
nCmdShow = SW_RESTORE;
w.Attr.Style &= ~(WS_MAXIMIZE|WS_MINIMIZE);
w.Attr.X = GetSystemMetrics(SM_CXSCREEN) / 4;
w.Attr.Y = GetSystemMetrics(SM_CYSCREEN) / 4;
w.Attr.W = GetSystemMetrics(SM_CXSCREEN) / 2;
w.Attr.H = GetSystemMetrics(SM_CYSCREEN) / 2;
}
return nCmdShow;
}
static void
_SaveInRegistry(Registry &r, const char *id, const char *value)
{
try {
r.Open(true);
r.SetString(id, value);
r.Close();
}
catch (RegistryFail) {};
}
static void
_SavePos(TWindow &w, Registry &r)
{
char buf[128];
TRect rect;
w.GetWindowRect(rect);
sprintf(buf, "%d, %d", rect.left, rect.top);
_SaveInRegistry(r, "WindowPos", buf);
}
static void
_SaveSize(TWindow &w, Registry &r, uint sizeType)
{
char buf[128];
TRect rect;
w.GetWindowRect(rect);
if ((sizeType == SIZE_MAXIMIZED) ||
(sizeType == SIZE_MINIMIZED)) {
sprintf(buf, "%d, %d",
GetSystemMetrics(SM_CXSCREEN) / 4,
GetSystemMetrics(SM_CYSCREEN) / 4);
_SaveInRegistry(r, "WindowPos", buf);
sprintf(buf, "%d, %d, %d",
sizeType, GetSystemMetrics(SM_CXSCREEN) / 2,
GetSystemMetrics(SM_CYSCREEN) / 2);
}
else
sprintf(buf, "%d, %d, %d",
sizeType, rect.Width(), rect.Height());
_SaveInRegistry(r, "WindowSize", buf);
}
static void
_RegSaveHide(Registry &r)
{
int i, j, k;
char buf[128];
try {
r.Open();
strcpy(buf, r.GetString("WindowSize", 128));
if (sscanf(buf, "%d, %d, %d", &i, &j, &k) != 3)
throw RegistryFail("");
sprintf(buf, "-1, %d, %d", j, k);
r.SetString("WindowSize", buf);
r.Close();
}
catch (RegistryFail) {
sprintf(buf, "%d, %d",
GetSystemMetrics(SM_CXSCREEN) / 4,
GetSystemMetrics(SM_CYSCREEN) / 4);
_SaveInRegistry(r, "WindowPos", buf);
sprintf(buf, "-1, %d, %d",
GetSystemMetrics(SM_CXSCREEN) / 2,
GetSystemMetrics(SM_CYSCREEN) / 2);
_SaveInRegistry(r, "WindowSize", buf);
}
}
//================================================================
DEFINE_RESPONSE_TABLE1(WXMDIWindow, TDecoratedMDIFrame)
EV_WM_MOVE,
EV_WM_SIZE,
END_RESPONSE_TABLE;
WXMDIWindow::WXMDIWindow(Registry *regData, const char far* title,
TResId menuResId, TMDIClient& clientWnd,
bool trackMenuSelection, TModule* module)
: TDecoratedMDIFrame(title, menuResId, clientWnd,
trackMenuSelection, module)
{
RegData = regData;
}
WXMDIWindow::~WXMDIWindow()
{
delete RegData;
}
int
WXMDIWindow::SetupAttr()
{
return _WXSetupAttr(*this, RegData);
}
void
WXMDIWindow::EvMove(TPoint & /*clientOrigin*/)
{
_SavePos(*this, *RegData);
}
void
WXMDIWindow::EvSize(uint sizeType, TSize &size)
{
TDecoratedFrame::EvSize(sizeType, size);
_SaveSize(*this, *RegData, sizeType);
}
void
WXMDIWindow::RegSaveHide()
{
_RegSaveHide(*RegData);
}
//================================================================
DEFINE_RESPONSE_TABLE1(WXFrameWindow, TDecoratedFrame)
EV_WM_MOVE,
EV_WM_SIZE,
END_RESPONSE_TABLE;
WXFrameWindow::WXFrameWindow(Registry *regData, TWindow *parent,
const char *title, TWindow *clientWnd, bool TrackMenuSelection,
TModule *module)
: TDecoratedFrame(parent, title, clientWnd,
TrackMenuSelection, module)
{
RegData = regData;
}
WXFrameWindow::~WXFrameWindow()
{
delete RegData;
}
int
WXFrameWindow::SetupAttr()
{
return _WXSetupAttr(*this, RegData);
}
void
WXFrameWindow::EvMove(TPoint & /*clientOrigin*/)
{
_SavePos(*this, *RegData);
}
void
WXFrameWindow::EvSize(uint sizeType, TSize &size)
{
TDecoratedFrame::EvSize(sizeType, size);
_SaveSize(*this, *RegData, sizeType);
}
void
WXFrameWindow::RegSaveHide()
{
_RegSaveHide(*RegData);
}
//****************************************************************
DEFINE_RESPONSE_TABLE1(WXSizingLayoutWindow, TLayoutWindow)
EV_WM_MOUSEMOVE,
EV_WM_LBUTTONDOWN,
EV_WM_LBUTTONUP,
END_RESPONSE_TABLE;
WXSizingLayoutWindow::WXSizingLayoutWindow(Registry *regData,
TWindow *parent, const char far *title, TModule *module)
: TLayoutWindow(parent, title, module)
{
NowSizing = SizingWindows = 0;
OldCursor = 0;
DoSizing = 0;
RegData = regData;
}
WXSizingLayoutWindow::~WXSizingLayoutWindow()
{
while (SizingWindows) {
struct SizingWindow *n;
n = SizingWindows->next;
delete[] SizingWindows->RegName;
delete SizingWindows;
SizingWindows = n;
}
}
bool
WXSizingLayoutWindow::Create()
{
struct SizingWindow *sw;
TLayoutMetrics lm;
register int i;
try {
RegData->Open();
for (sw = SizingWindows; sw; sw = sw->next) {
try {
i = atoi(RegData->GetString(sw->RegName, 128));
}
catch (RegistryFail) {
continue; // Ignore it!
}
if (i < 0)
i = 0;
if (GetChildLayoutMetrics(*(sw->win), lm)) {
switch (sw->edge) {
case eszTop:
case eszBottom:
lm.Height.Absolute(i);
break;
case eszLeft:
case eszRight:
lm.Width.Absolute(i);
break;
}
SetChildLayoutMetrics(*(sw->win), lm);
}
}
RegData->Close();
}
catch (RegistryFail) {
}
return TLayoutWindow::Create();
}
WXSizingLayoutWindow::SizingWindow *
WXSizingLayoutWindow::FindSizingEdge(TPoint &point)
{
struct SizingWindow *sw;
TRect mr, r;
mr = GetWindowRect();
for (sw = SizingWindows; sw; sw = sw->next) {
r = sw->win->GetWindowRect().OffsetBy(-mr.left, -mr.top);
switch (sw->edge) {
case eszTop:
if (abs(point.y - r.top) > 2)
break;
return sw;
case eszBottom:
if (abs(point.y - r.bottom) > 2)
break;
return sw;
case eszLeft:
if (abs(point.x - r.left) > 2)
break;
return sw;
case eszRight:
if (abs(point.x - r.right) > 2)
break;
return sw;
}
}
return NULL;
}
void
WXSizingLayoutWindow::EnableSizing(TWindow *win, enum SizingEdge se,
const char *regName)
{
struct SizingWindow *sw;
for (sw = SizingWindows; sw; sw = sw->next) {
if (win == sw->win) {
sw->edge = se;
return;
}
}
sw = new struct SizingWindow;
sw->win = win;
sw->edge = se;
sw->next = SizingWindows;
sw->RegName = strnewdup(regName);
SizingWindows = sw;
}
void
WXSizingLayoutWindow::EvMouseMove(uint /*ModKeys*/, TPoint &point)
{
struct SizingWindow *sw;
HCURSOR newCursor;
if (DoSizing && NowSizing) {
TLayoutMetrics lm;
register int i;
if (!GetChildLayoutMetrics(*(NowSizing->win), lm)) {
MessageBeep(-1);
DoSizing = false;
return;
}
TRect mr = GetWindowRect();
TRect cr = NowSizing->win->GetWindowRect().
OffsetBy(-mr.left, -mr.top);
switch (NowSizing->edge) {
case eszTop:
if (point.y < 1)
point.y = 1;
i = cr.bottom - point.y;
if (i < 0)
i = 0;
lm.Height.Absolute(i);
NowSizing->LastSize = i;
break;
case eszBottom:
if (point.y >= mr.Height())
point.y = mr.Height() - 1;
i = point.y - cr.top;
if (i < 0)
i = 0;
lm.Height.Absolute(i);
NowSizing->LastSize = i;
break;
case eszLeft:
if (point.x < 1)
point.x = 1;
i = cr.right - point.x;
if (i < 0)
i = 0;
lm.Width.Absolute(i);
NowSizing->LastSize = i;
break;
case eszRight:
if (point.x >= mr.Width())
point.x = mr.Width() - 1;
i = point.x - cr.left;
if (i < 0)
i = 0;
lm.Width.Absolute(i);
NowSizing->LastSize = i;
break;
}
SetChildLayoutMetrics(*(NowSizing->win), lm);
Layout();
return;
}
DoSizing = false;
sw = FindSizingEdge(point);
if ((sw == NULL) || (sw != NowSizing)) {
if (OldCursor)
::SetCursor(OldCursor);
OldCursor = 0;
if (NowSizing)
ReleaseCapture();
NowSizing = 0;
}
if (sw != NULL) {
newCursor = 0;
switch (sw->edge) {
case eszTop:
case eszBottom:
newCursor = ::LoadCursor(0, IDC_SIZENS);
break;
case eszLeft:
case eszRight:
newCursor = ::LoadCursor(0, IDC_SIZEWE);
break;
}
if (newCursor) {
NowSizing = sw;
SetCapture();
OldCursor = ::SetCursor(newCursor);
}
}
}
void
WXSizingLayoutWindow::EvLButtonDown(uint /*ModKeys*/, TPoint &/*point*/)
{
DoSizing = true;
}
void
WXSizingLayoutWindow::EvLButtonUp(uint ModKeys, TPoint &point)
{
SizingWindow *es = NowSizing;
DoSizing = false;
EvMouseMove(ModKeys, point);
if (es) {
char buf[128];
sprintf(buf, "%d", es->LastSize);
_SaveInRegistry(*RegData, es->RegName, buf);
}
}
|
d6892309d9a0f875865f707b3594c3921170e09f | d214c56f712243db8d2eae85a21e36076db8533e | /Source/BuildingEscape/ButonForDoor.cpp | 69a45ab1c506e78ba95fcc64c9ad77f5adbe78bd | [] | no_license | arnoldlam/BuildingEscape | 3e38cd8259ec6b3a2d17395a9fa2bc8a6093e8cc | 9615e164ee8137c9d3cd95c6ed8c5e7788d399c7 | refs/heads/master | 2022-08-31T18:14:42.037883 | 2020-05-30T20:35:19 | 2020-05-30T20:35:19 | 266,670,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,860 | cpp | ButonForDoor.cpp | // Copyright Arnold Lam 2020
#include "ButonForDoor.h"
#define OUT
// Sets default values for this component's properties
UButonForDoor::UButonForDoor()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UButonForDoor::BeginPlay()
{
Super::BeginPlay();
InitialButtonZ = GetOwner()->GetActorLocation().Z;
TargetButtonZ = InitialButtonZ - ButtonPressedZDelta;
}
// Called every frame
void UButonForDoor::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (CheckIfButtonPressed())
{
PressButton(DeltaTime);
}
else
{
LiftButton(DeltaTime);
}
}
void UButonForDoor::PressButton(float DeltaTime)
{
FVector CurrentButtonLocation = GetOwner()->GetActorLocation();
FVector NewButtonLocation = CurrentButtonLocation;
// Animate button presss
NewButtonLocation.Z = FMath::FInterpTo(CurrentButtonLocation.Z, TargetButtonZ, DeltaTime, ButtonPressSpeed);
GetOwner()->SetActorLocation(NewButtonLocation);
}
void UButonForDoor::LiftButton(float DeltaTime)
{
FVector CurrentButtonLocation = GetOwner()->GetActorLocation();
FVector NewButtonLocation = CurrentButtonLocation;
// Animate button presss
NewButtonLocation.Z = FMath::FInterpTo(CurrentButtonLocation.Z, InitialButtonZ, DeltaTime, ButtonPressSpeed);
GetOwner()->SetActorLocation(NewButtonLocation);
}
bool UButonForDoor::CheckIfButtonPressed()
{
TArray<AActor*> ListOfOverlappingActors;
TriggerVolume->GetOverlappingActors(OUT ListOfOverlappingActors);
if (ListOfOverlappingActors.Num() > 0) {
return true;
}
else
{
return false;
}
} |
bfedbc073eac6bac82b8b0ff4fb002cc2f97bdc5 | bc2e98046dbc1af5bd104e42a22d5238f21d5d8e | /Segundo semestre orientada a objetos/ConstructorCopia/ConstructorCopia/Copia.cpp | 59cfcee62054ac3da4d10b5afba0fcd5b23d37df | [] | no_license | cycasmi/proyectos-VS | 559da543711a77d3daf0c08030c8104385e95803 | c09a77528c8c0053a1c66061659ea4950f317d92 | refs/heads/master | 2021-07-20T22:31:53.285920 | 2017-10-27T22:26:46 | 2017-10-27T22:26:46 | 108,600,737 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 296 | cpp | Copia.cpp | #include "Copia.h"
int main()
{
Copia Y;
Copia W = Y.llamadaAcopia(Y); //Se imprime 3 veces pork al ponerle que es igual, se manda a llamar. Al usar la funcion y la tercera por el return.
//LLamada explícita: copia Z = Y;
//Llamada por el valor
//Llamada por el parámetro
return 0;
}
|
b98b7d7d4dcab5bad87b5c430ad7e8d368cc5efc | 2a64ce7a3a641f9af701fb485012612f4a59537e | /exercise/网易2018校招内推编程题集合/code6.cpp | aedaf3815f229de024f553b1ed5a5f9b389e613b | [] | no_license | yehuohan/ln-misc | 2e1fd13d1421c936a9b12d13754c9b7c78c091bb | 5609be2f8317ae124b20050cbaaebe6a609ceef0 | refs/heads/master | 2021-12-07T14:27:09.749711 | 2021-10-06T14:01:42 | 2021-10-06T14:01:42 | 222,347,295 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,253 | cpp | code6.cpp |
/*
[编程题] 堆棋子
时间限制:1秒
空间限制:32768K
小易将n个棋子摆放在一张无限大的棋盘上。第i个棋子放在第x[i]行y[i]列。同一个格子允许放置多个棋子。每一次操作小易可以把一个棋子拿起并将其移动到原格子的上、下、左、右的任意一个格子中。小易想知道要让棋盘上出现有一个格子中至少有i(1 ≤ i ≤ n)个棋子所需要的最少操作次数.
输入描述:
输入包括三行,第一行一个整数n(1 ≤ n ≤ 50),表示棋子的个数
第二行为n个棋子的横坐标x[i](1 ≤ x[i] ≤ 10^9)
第三行为n个棋子的纵坐标y[i](1 ≤ y[i] ≤ 10^9)
输出描述:
输出n个整数,第i个表示棋盘上有一个格子至少有i个棋子所需要的操作数,以空格分割。行末无空格
如样例所示:
对于1个棋子: 不需要操作
对于2个棋子: 将前两个棋子放在(1, 1)中
对于3个棋子: 将前三个棋子放在(2, 1)中
对于4个棋子: 将所有棋子都放在(3, 1)中
输入例子1:
4
1 2 4 9
1 1 1 1
输出例子1:
0 1 3 10
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <limits>
void move_chess(int* x, int* y, int* count, int n)
{
for (int k = 0; k < n; k ++)
count[k] = INT_MAX;
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
std::vector<int> dis(n, 0);
for(int k = 0; k < n; ++k)
dis[k] = std::abs(x[i] - x[k]) + std::abs(y[j] - y[k]);
std::sort(dis.begin(), dis.end());
int tmp = 0;
for(int k = 0; k < n; ++k)
{
tmp += dis[k];
count[k] = std::min(count[k], tmp);
}
}
}
}
int main(int argc, char *argv[])
{
int n;
std::cin >> n;
int* x = new int[n];
int* y = new int[n];
for (int k = 0; k < n; k ++) std::cin >> x[k];
for (int k = 0; k < n; k ++) std::cin >> y[k];
int* count = new int[n];
move_chess(x, y, count, n);
for (int k = 0; k < n; k ++)
{
std::cout << count[k];
if (k < n - 1)
std::cout << ' ';
}
delete[] x;
delete[] y;
delete[] count;
return 0;
}
|
78938bde48c749d6b8f7244bd68638efe91fb32a | b7459eedf94fd446bc4327fc6b7a79cc2be3f96e | /NativeDll/src/game/Entity.cpp | ad90fc25fadcaad9443ccd7b7066e2dddd27797e | [
"MIT"
] | permissive | inkimagine/Ghurund | dbfc8109e7ce1896254bb48f9fccca01633ba765 | 4d69149a7077b71656562f63504a79222979bd12 | refs/heads/master | 2020-09-15T23:44:37.083154 | 2019-09-08T22:29:11 | 2019-09-09T18:58:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,803 | cpp | Entity.cpp | #include "ecs/Entity.h"
#include "../Float3.h"
using namespace Ghurund;
extern "C" __declspec(dllexport) const PointerArray<Parameter*>* ParameterProvider_getParameters(ParameterProvider* _this) {
return &_this->getParameters();
}
extern "C" __declspec(dllexport) void ParameterProvider_initParameters(ParameterProvider* _this, ParameterManager* manager) {
_this->initParameters(*manager);
}
extern "C" __declspec(dllexport) void ParameterProvider_updateParameters(ParameterProvider* _this) {
_this->updateParameters();
}
extern "C" __declspec(dllexport) const BaseType* Entity_getType(Entity* _this) {
return &(_this->Type);
}
extern "C" __declspec(dllexport) wchar_t* Entity_getName(Entity* _this) {
return copyStr(_this->getName().getData());
}
extern "C" __declspec(dllexport) void Entity_setName(Entity* _this, const wchar_t* name) {
_this->setName(name);
}
/*extern "C" __declspec(dllexport) void Entity_setSelectable(Entity* _this, BOOL selectable) {
return _this->setSelectable((bool)selectable);
}
extern "C" __declspec(dllexport) BOOL Entity_isSelectable(Entity* _this) {
return _this->isSelectable();
}
extern "C" __declspec(dllexport) void Entity_setVisible(Entity* _this, BOOL visible) {
return _this->setVisible((bool)visible);
}
extern "C" __declspec(dllexport) BOOL Entity_isVisible(Entity* _this) {
return _this->isVisible();
}*/
extern "C" __declspec(dllexport) Entity* Entity_getParent(Entity* _this) {
return _this->getParent();
}
extern "C" __declspec(dllexport) void Entity_setPropertyChangedListener(Entity* _this, listener_t listener) {
_this->setOnChangedListener(listener);
}
extern "C" __declspec(dllexport) listener_t Entity_getPropertyChangedListener(Entity* _this) {
return _this->getOnChangedListener();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.