blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4f04e3b836d64f0db3058fc5f02631ad30dfea2c | 04fec4cbb69789d44717aace6c8c5490f2cdfa47 | /include/wx/mmedia/sndcodec.h | d176d753e5b8a30c6ca6d31285a95fd6b0353af6 | [] | no_license | aaryanapps/whiteTiger | 04f39b00946376c273bcbd323414f0a0b675d49d | 65ed8ffd530f20198280b8a9ea79cb22a6a47acd | refs/heads/master | 2021-01-17T12:07:15.264788 | 2010-10-11T20:20:26 | 2010-10-11T20:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | h | // --------------------------------------------------------------------------
// Name: sndcodec.h
// Purpose:
// Date: 08/11/1999
// Author: Guilhem Lavaux <lavaux@easynet.fr> (C) 1999
// CVSID: $Id: sndcodec.h,v 1.5 2005/09/23 12:47:04 MR Exp $
// License: wxWindows license
// --------------------------------------------------------------------------
#ifndef _WX_SNDCODEC_H
#define _WX_SNDCODEC_H
#include "wx/defs.h"
#include "wx/mmedia/defs.h"
#include "wx/mmedia/sndbase.h"
class WXDLLIMPEXP_MMEDIA wxSoundStreamCodec: public wxSoundStream {
public:
wxSoundStreamCodec(wxSoundStream& snd_io);
~wxSoundStreamCodec();
bool StartProduction(int evt);
bool StopProduction();
wxUint32 GetBestSize() const;
protected:
wxSoundStream *m_sndio;
};
#endif
| [
"smehta@aaryanapps.com"
] | smehta@aaryanapps.com |
73c9ae73e759ee400a2d1375d44e51fc840e8927 | 5bc868bdf3cdba43954c868b802aed15e53e0ec0 | /cFont.cpp | 9a06c8e27ab228c4e5655144f8a5689ff622340f | [] | no_license | beythli/Harvest-Heights | 9e99d3444a98a5303d8ff58509de892f113e3d13 | fd15fcd9f008f6b94b3758d2de58fcf191f61c6b | refs/heads/master | 2020-09-30T10:17:19.820974 | 2019-12-11T04:37:26 | 2019-12-11T04:37:26 | 227,267,820 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,306 | cpp | /*
==========================================================================
cFont.cpp
==========================================================================
*/
//#pragma warning ( disable : 4996 )
#include "cFont.h"
using namespace std;
/*
==========================================================================
Default Constructor
==========================================================================
*/
cFont::cFont()
{
theFont = NULL;
}
/*
==========================================================================
Destructor
==========================================================================
*/
cFont::~cFont()
{
TTF_CloseFont(theFont);
}
/*
==========================================================================
Load the desiered font
==========================================================================
*/
bool cFont::loadFont(LPCSTR fontFileName, int fontSize)
{
theFont = TTF_OpenFont(fontFileName, fontSize);
if (theFont == NULL)
{
cout << " Failed to load font : " << SDL_GetError() << endl;
return false;
}
cout << "Font '" << fontFileName << "' loaded successfully" << endl;
return true;
}
/*
==========================================================================
get the pointer to the font
==========================================================================
*/
TTF_Font* cFont::getFont()
{
return theFont;
}
/*
==========================================================================
Render the text using the desired font
==========================================================================
*/
SDL_Texture* cFont::createTextTexture(SDL_Renderer* theRenderer, LPCSTR text, textType txtType, SDL_Color txtColour, SDL_Color txtBkgd)
{
SDL_Texture* theTxtTexture = NULL;
SDL_Surface* theTxtSurface = NULL;
switch (txtType)
{
case textType::solid:
{
theTxtSurface = TTF_RenderText_Solid(theFont, text, txtColour);
}
break;
case textType::blended:
{
theTxtSurface = TTF_RenderText_Blended(theFont, text, txtColour);
}
break;
case textType::shaded:
{
theTxtSurface = TTF_RenderText_Shaded(theFont, text, txtColour, txtBkgd);
}
break;
default:
break;
}
theTxtTexture = SDL_CreateTextureFromSurface(theRenderer, theTxtSurface);
SDL_FreeSurface(theTxtSurface);
return theTxtTexture;
} | [
"robert.law@gcu.ac.uk"
] | robert.law@gcu.ac.uk |
1fb671d25210bd28dde019d395f518eccf47fbc3 | 26ad4cc35496d364b31396e43a863aee08ef2636 | /SDK/SoT_BP_tattoo_18_Desc_functions.cpp | 68483dee9f0760afe02340219602bb5f8aa1d0a7 | [] | no_license | cw100/SoT-SDK | ddb9b19ce6ae623299b2b02dee51c29581537ba1 | 3e6f12384c8e21ed83ef56f00030ca0506d297fb | refs/heads/master | 2020-05-05T12:09:55.938323 | 2019-03-20T14:11:57 | 2019-03-20T14:11:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 354 | cpp | // Sea of Thieves (1.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_tattoo_18_Desc_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
cb00f6789649136acf249c1c729f34964c0cc874 | 6e10cbb2edb9ca5c8511784eb00fc83bf7092f12 | /source/Game/Camera.cpp | 56005beb9ec5525d8d8e4529eb6153a73067e4a4 | [
"BSD-3-Clause",
"MIT"
] | permissive | tamwaiban/nextgame | 65246dfd4c18ffa54d218a9ce371fa4fc75170d6 | a2d2f21341489792bafa2519f33287a0b89927ee | refs/heads/master | 2020-11-28T11:23:59.969262 | 2014-09-24T12:24:24 | 2014-09-24T12:24:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,035 | cpp | #include "Game/Camera.h"
#include "Core/Utils.h"
#include <cstdio>
void PlayerCamera::apply_transform()
{
get_camera_vectors(&look_dir, &up, &right, transform.orientation);
frustum = ::transform(frustum_identity, transform);
}
void PlayerCamera::set_perspective(float fov, float aspect, float znear, float zfar)
{
frustum_identity = Frustum_Perspective(fov, aspect, znear, zfar);
projection = Mat4_Perspective(fov, aspect, znear, zfar);
half_plane_wh = frustum_plane_wh(fov, aspect, 1.0) / Vec2(2);
projection_ratio = ::projection_ratio(znear, zfar);
}
void ShadowCamera::apply_transform()
{
frustum = ::transform(frustum_identity, transform);
}
void ShadowCamera::set_from_sphere(const Sphere &bsphere, float zextend)
{
frustum_identity = Frustum_Shadow(bsphere, zextend);
projection = Mat4_Shadow(bsphere, zextend);
}
void get_camera_vectors(Vec3 *look_dir, Vec3 *up, Vec3 *right, const Quat &orient)
{
NG_ASSERT(look_dir != nullptr);
NG_ASSERT(up != nullptr);
NG_ASSERT(right != nullptr);
const Mat4 m = to_mat4(inverse(orient));
*right = { m[0], m[4], m[8]};
*up = { m[1], m[5], m[9]};
*look_dir = {-m[2], -m[6], -m[10]};
}
Vec3 get_walk_direction(unsigned state, const Vec3 &look_dir,
const Vec3 &right, bool strip_y)
{
constexpr float sincos_45 = 0.7071067f;
float fb_move = 0.0f;
float lr_move = 0.0f;
if (state & PCS_MOVING_FORWARD)
fb_move += 1.0f;
if (state & PCS_MOVING_BACKWARD)
fb_move -= 1.0f;
if (state & PCS_MOVING_LEFT)
lr_move -= 1.0f;
if (state & PCS_MOVING_RIGHT)
lr_move += 1.0f;
if (state & (PCS_MOVING_FORWARD | PCS_MOVING_BACKWARD) &&
state & (PCS_MOVING_LEFT | PCS_MOVING_RIGHT))
{
fb_move *= sincos_45;
lr_move *= sincos_45;
}
Vec3 fb = look_dir;
if (strip_y) {
fb.y = 0.0f;
fb = normalize(fb);
}
return fb * Vec3(fb_move) + right * Vec3(lr_move);
}
Quat mouse_rotate(const Quat &in, float x, float y, float sensitivity)
{
const Quat xq(Vec3_Y(), -x * sensitivity);
const Quat yq(Vec3_X(), -y * sensitivity);
return xq * (in * yq);
}
| [
"no.smile.face@gmail.com"
] | no.smile.face@gmail.com |
1c0d4c8fa1cca69954d04a8d3bd951620a66acf2 | b6ed2145ed73919ec42f3d34ccb67a7ecc621b3a | /algorithm/summer/nine/f.cpp | 4bcd03a7ffe691d404a6a540ff51a30939f4e67f | [] | no_license | gilsaia/college-study | 26d9813ab5e5f125618aec787c942e442b0fb630 | 66d2dda1b322077fd58abe56ba602da5260856be | refs/heads/master | 2021-06-03T06:23:05.770868 | 2019-09-22T14:22:22 | 2019-09-22T14:22:22 | 138,689,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | #include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n;
while(~scanf("%d",&n))
{
vector<int> enmy;
for(int i=0;i<n;++i)
{
int tmp;
scanf("%d",&tmp);
enmy.push_back(tmp);
}
int ans=0,nowhei=0;
while(!enmy.empty())
{
++ans;
nowhei=0;
vector<int> toshoot;
for(int i=0;i<enmy.size();++i)
{
if(enmy[i]>=nowhei)
{
nowhei=enmy[i];
}
else
{
toshoot.push_back(enmy[i]);
}
}
enmy=toshoot;
}
printf("%d\n",ans);
}
return 0;
} | [
"794433219@qq.com"
] | 794433219@qq.com |
8de03011bae8d43bfcd4f5391b93779218879756 | a127724a1ae23af66095de3ac14714305d4a5e69 | /JSBM_C++/cal_pi.cpp | bf547a6e551707619a962888216f78d63b42e5bf | [] | no_license | pengfzhou/BPGCN | a311cd7bf9440869bfaf5338f57ac14cf27045f3 | b0f65bd50486f3717ab52accda139aab4e357ac2 | refs/heads/master | 2020-09-22T19:38:41.763890 | 2020-06-26T01:11:35 | 2020-06-26T01:11:35 | 225,308,325 | 12 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 726 | cpp | #include <math.h>
#include<iostream>
#include "mpi.h"
using namespace std;
int main(int argc, char *argv[])
{
int n=10, rank, size, i;
double PI25DT = 3.141592653589793238462643;
double mypi, pi, h, sum, x;
MPI::Init(argc, argv);
size = MPI::COMM_WORLD.Get_size( );
rank = MPI::COMM_WORLD.Get_rank( );
MPI::COMM_WORLD.Bcast(&n, 1, MPI::INT, 0);
h = 1.0 / (double) n;
sum = 0.0;
for (i = rank + 1; i <= n; i += size) {
x = h * ((double)i - 0.5);
sum += (4.0 / (1.0 + x*x));
}
mypi = h * sum;
cout<<mypi<<endl;
MPI::COMM_WORLD.Reduce(&mypi, &pi, 1, MPI::DOUBLE, MPI::SUM, 0);
if (rank == 0) cout<< "pi is approximately "<< pi << ", Error is " << fabs(pi - PI25DT) << endl;
MPI::Finalize( );
return 0;
}
| [
"zhoupengfei@itp.ac.cn"
] | zhoupengfei@itp.ac.cn |
0229680f0f24ceb6f54356a62495510002eea648 | 4352b5c9e6719d762e6a80e7a7799630d819bca3 | /tutorials/eulerVortex.twitch/eulerVortex.cyclic.twitch.test.test/processor1/1.53/e | 535fa2e429f83e9eb742219acaf6e11569ed1d76 | [] | no_license | dashqua/epicProject | d6214b57c545110d08ad053e68bc095f1d4dc725 | 54afca50a61c20c541ef43e3d96408ef72f0bcbc | refs/heads/master | 2022-02-28T17:20:20.291864 | 2019-10-28T13:33:16 | 2019-10-28T13:33:16 | 184,294,390 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,961 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1.53";
object e;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField nonuniform List<scalar>
5625
(
973.764
960.125
944.167
926.639
908.517
890.879
874.82
861.369
851.414
845.61
844.329
847.742
855.851
868.352
884.393
902.58
921.279
939.038
954.852
968.213
979.009
987.384
993.63
998.104
1001.18
1003.21
1004.49
1005.27
1005.73
1005.99
1006.14
1006.21
1006.25
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
978.945
967.172
953.238
937.804
921.744
906.044
891.706
879.678
870.786
865.625
864.53
867.649
874.978
886.207
900.518
916.616
933.042
948.531
962.245
973.774
983.049
990.217
995.544
999.349
1001.96
1003.68
1004.76
1005.43
1005.82
1006.04
1006.16
1006.22
1006.26
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
983.814
973.916
962.054
948.776
934.848
921.151
908.59
898.028
890.221
885.7
884.766
887.558
894.067
903.979
916.505
930.463
944.578
957.789
969.413
979.138
986.929
992.928
997.37
1000.53
1002.7
1004.12
1005.02
1005.57
1005.9
1006.08
1006.18
1006.23
1006.26
1006.27
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
988.198
980.093
970.257
959.117
947.322
935.635
924.86
915.77
909.04
905.144
904.352
906.806
912.489
921.074
931.811
943.644
955.493
966.496
976.118
984.129
990.523
995.428
999.05
1001.62
1003.38
1004.53
1005.26
1005.71
1005.97
1006.12
1006.2
1006.24
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
992.004
985.533
977.584
968.479
958.738
949.004
939.971
932.321
926.642
923.347
922.694
924.821
929.701
936.986
945.98
955.77
965.469
974.406
982.175
988.617
993.739
997.658
1000.54
1002.59
1003.98
1004.9
1005.47
1005.83
1006.03
1006.15
1006.22
1006.25
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
995.213
990.164
983.899
976.647
968.808
960.903
953.517
947.235
942.554
939.838
939.33
941.162
945.276
951.32
958.664
966.55
974.281
981.351
987.467
992.52
996.527
999.583
1001.83
1003.42
1004.5
1005.21
1005.66
1005.93
1006.09
1006.18
1006.23
1006.26
1006.27
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
997.857
993.998
989.176
983.541
977.392
971.14
965.26
960.236
956.483
954.317
953.962
955.529
958.924
963.808
969.637
975.809
981.802
987.248
991.941
995.807
998.866
1001.19
1002.9
1004.11
1004.93
1005.47
1005.81
1006.02
1006.14
1006.21
1006.25
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
999.99
997.1
993.471
989.198
984.498
979.683
975.131
971.226
968.308
966.651
966.446
967.767
970.497
974.323
978.808
983.496
988.011
992.096
995.604
998.49
1000.77
1002.5
1003.77
1004.67
1005.28
1005.68
1005.93
1006.08
1006.18
1006.23
1006.26
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1001.68
999.557
996.886
993.723
990.221
986.615
983.19
980.247
978.058
976.848
976.77
977.854
979.977
982.874
986.211
989.665
992.973
995.954
998.513
1000.62
1002.28
1003.54
1004.46
1005.11
1005.55
1005.84
1006.03
1006.14
1006.21
1006.24
1006.26
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1002.98
1001.46
999.539
997.255
994.716
992.09
989.591
987.444
985.862
985.023
985.029
985.884
987.469
989.583
991.987
994.456
996.814
998.936
1000.76
1002.25
1003.43
1004.33
1004.99
1005.45
1005.76
1005.97
1006.1
1006.18
1006.23
1006.26
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1003.97
1002.9
1001.55
999.946
998.155
996.299
994.531
993.018
991.919
991.361
991.408
992.046
993.182
994.669
996.346
998.062
999.699
1001.17
1002.44
1003.48
1004.3
1004.93
1005.38
1005.7
1005.92
1006.07
1006.16
1006.21
1006.25
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1004.7
1003.97
1003.04
1001.94
1000.71
999.441
998.229
997.199
996.462
996.103
996.158
996.609
997.389
998.4
999.536
1000.7
1001.81
1002.81
1003.67
1004.37
1004.93
1005.36
1005.67
1005.89
1006.04
1006.14
1006.2
1006.24
1006.26
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1005.22
1004.74
1004.12
1003.38
1002.56
1001.72
1000.91
1000.23
999.751
999.523
999.568
999.872
1000.39
1001.05
1001.8
1002.57
1003.3
1003.97
1004.54
1005.01
1005.38
1005.67
1005.87
1006.02
1006.12
1006.19
1006.23
1006.25
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1005.59
1005.27
1004.87
1004.39
1003.86
1003.31
1002.79
1002.36
1002.05
1001.91
1001.94
1002.13
1002.46
1002.89
1003.37
1003.87
1004.34
1004.77
1005.15
1005.45
1005.7
1005.88
1006.02
1006.11
1006.18
1006.22
1006.25
1006.27
1006.27
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1005.84
1005.64
1005.39
1005.08
1004.75
1004.4
1004.07
1003.8
1003.61
1003.52
1003.53
1003.65
1003.86
1004.13
1004.43
1004.75
1005.05
1005.32
1005.56
1005.75
1005.91
1006.03
1006.11
1006.18
1006.22
1006.25
1006.26
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.01
1005.88
1005.73
1005.54
1005.33
1005.12
1004.92
1004.75
1004.63
1004.57
1004.58
1004.65
1004.78
1004.94
1005.13
1005.33
1005.51
1005.68
1005.83
1005.95
1006.05
1006.13
1006.18
1006.22
1006.24
1006.26
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.12
1006.04
1005.95
1005.83
1005.71
1005.58
1005.46
1005.36
1005.28
1005.25
1005.25
1005.3
1005.37
1005.47
1005.58
1005.7
1005.81
1005.92
1006.01
1006.08
1006.14
1006.19
1006.22
1006.24
1006.26
1006.27
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.19
1006.14
1006.09
1006.02
1005.94
1005.87
1005.8
1005.74
1005.69
1005.67
1005.67
1005.7
1005.74
1005.8
1005.87
1005.94
1006
1006.07
1006.12
1006.16
1006.2
1006.23
1006.25
1006.26
1006.27
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.23
1006.2
1006.17
1006.13
1006.09
1006.04
1006
1005.97
1005.94
1005.93
1005.93
1005.94
1005.97
1006
1006.04
1006.08
1006.12
1006.16
1006.19
1006.22
1006.24
1006.25
1006.26
1006.27
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.26
1006.24
1006.22
1006.2
1006.18
1006.15
1006.13
1006.11
1006.09
1006.08
1006.08
1006.09
1006.11
1006.13
1006.15
1006.17
1006.19
1006.21
1006.23
1006.25
1006.26
1006.27
1006.27
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.27
1006.26
1006.25
1006.24
1006.23
1006.21
1006.2
1006.19
1006.18
1006.17
1006.18
1006.18
1006.19
1006.2
1006.21
1006.22
1006.23
1006.25
1006.26
1006.26
1006.27
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.27
1006.27
1006.26
1006.25
1006.25
1006.24
1006.23
1006.23
1006.23
1006.23
1006.23
1006.23
1006.24
1006.25
1006.25
1006.26
1006.26
1006.27
1006.27
1006.28
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.28
1006.28
1006.27
1006.27
1006.27
1006.26
1006.26
1006.26
1006.26
1006.25
1006.26
1006.26
1006.26
1006.26
1006.27
1006.27
1006.27
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.27
1006.27
1006.27
1006.27
1006.27
1006.27
1006.27
1006.27
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
boundaryField
{
emptyPatches_empt
{
type empty;
}
top_cyc
{
type cyclic;
}
bottom_cyc
{
type cyclic;
}
inlet_cyc
{
type cyclic;
}
outlet_cyc
{
type cyclic;
}
procBoundary1to0
{
type processor;
value nonuniform List<scalar>
75
(
984.64
988.206
991.493
994.407
996.913
999.018
1000.75
1002.15
1003.26
1004.12
1004.77
1005.24
1005.59
1005.83
1006
1006.1
1006.18
1006.22
1006.25
1006.27
1006.28
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
}
procBoundary1to0throughoutlet_cyc
{
type processorCyclic;
value nonuniform List<scalar>
75
(
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
}
procBoundary1to3
{
type processor;
value nonuniform List<scalar>
75
(
968.508
953.1
935.238
915.748
895.69
876.232
858.554
843.76
832.797
826.364
824.877
828.536
837.365
851.053
868.719
888.874
909.732
929.663
947.509
962.662
974.958
984.535
991.701
996.847
1000.39
1002.73
1004.21
1005.12
1005.65
1005.95
1006.11
1006.2
1006.24
1006.27
1006.28
1006.28
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
}
procBoundary1to3throughbottom_cyc
{
type processorCyclic;
value nonuniform List<scalar>
75
(
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
}
}
// ************************************************************************* //
| [
"tdg@debian"
] | tdg@debian | |
e678027480cc03a36cc298059ecc79734558468b | 084006eb442b60b82b3d85d61a3b53d21c5c8855 | /shared/Irrlicht/include/SceneParameters.h | 2dbe69f59092c21393b957c9adcb7ec1bf20f6bf | [
"XFree86-1.1",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"Zlib"
] | permissive | SethRobinson/proton | 7aadcb38bc676c136dce01b8f6773fd75fa33d55 | 6b1474e75a2acf48d848c70fcb043ce8223001a9 | refs/heads/master | 2023-08-31T11:04:21.575522 | 2023-08-29T07:44:50 | 2023-08-29T07:44:50 | 142,253,855 | 81 | 31 | NOASSERTION | 2023-08-07T22:02:41 | 2018-07-25T05:55:38 | C++ | UTF-8 | C++ | false | false | 6,914 | h | // Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_SCENE_PARAMETERS_H_INCLUDED__
#define __I_SCENE_PARAMETERS_H_INCLUDED__
/*! \file SceneParameters.h
\brief Header file containing all scene parameters for modifying mesh loading etc.
This file includes all parameter names which can be set using ISceneManager::getParameters()
to modify the behaviour of plugins and mesh loaders.
*/
namespace irr
{
namespace scene
{
//! Name of the parameter for changing how Irrlicht handles the ZWrite flag for transparent (blending) materials
/** The default behavior in Irrlicht is to disable writing to the
z-buffer for all really transparent, i.e. blending materials. This
avoids problems with intersecting faces, but can also break renderings.
If transparent materials should use the SMaterial flag for ZWriteEnable
just as other material types use this attribute.
Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
\endcode
**/
const c8* const ALLOW_ZWRITE_ON_TRANSPARENT = "Allow_ZWrite_On_Transparent";
//! Name of the parameter for changing the texture path of the built-in csm loader.
/** Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::CSM_TEXTURE_PATH, "path/to/your/textures");
\endcode
**/
const c8* const CSM_TEXTURE_PATH = "CSM_TexturePath";
//! Name of the parameter for changing the texture path of the built-in lmts loader.
/** Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::LMTS_TEXTURE_PATH, "path/to/your/textures");
\endcode
**/
const c8* const LMTS_TEXTURE_PATH = "LMTS_TexturePath";
//! Name of the parameter for changing the texture path of the built-in my3d loader.
/** Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::MY3D_TEXTURE_PATH, "path/to/your/textures");
\endcode
**/
const c8* const MY3D_TEXTURE_PATH = "MY3D_TexturePath";
//! Name of the parameter specifying the COLLADA mesh loading mode
/**
Specifies if the COLLADA loader should create instances of the models, lights and
cameras when loading COLLADA meshes. By default, this is set to false. If this is
set to true, the ISceneManager::getMesh() method will only return a pointer to a
dummy mesh and create instances of all meshes and lights and cameras in the collada
file by itself. Example:
\code
SceneManager->getParameters()->setAttribute(scene::COLLADA_CREATE_SCENE_INSTANCES, true);
\endcode
*/
const c8* const COLLADA_CREATE_SCENE_INSTANCES = "COLLADA_CreateSceneInstances";
//! Name of the parameter for changing the texture path of the built-in DMF loader.
/** This path is prefixed to the file names defined in the Deled file when loading
textures. This allows to alter the paths for a specific project setting.
Use it like this:
\code
SceneManager->getStringParameters()->setAttribute(scene::DMF_TEXTURE_PATH, "path/to/your/textures");
\endcode
**/
const c8* const DMF_TEXTURE_PATH = "DMF_TexturePath";
//! Name of the parameter for preserving DMF textures dir structure with built-in DMF loader.
/** If this parameter is set to true, the texture directory defined in the Deled file
is ignored, and only the texture name is used to find the proper file. Otherwise, the
texture path is also used, which allows to use a nicer media layout.
Use it like this:
\code
//this way you won't use this setting (default)
SceneManager->getParameters()->setAttribute(scene::DMF_IGNORE_MATERIALS_DIRS, false);
\endcode
\code
//this way you'll use this setting
SceneManager->getParameters()->setAttribute(scene::DMF_IGNORE_MATERIALS_DIRS, true);
\endcode
**/
const c8* const DMF_IGNORE_MATERIALS_DIRS = "DMF_IgnoreMaterialsDir";
//! Name of the parameter for setting reference value of alpha in transparent materials.
/** Use it like this:
\code
//this way you'll set alpha ref to 0.1
SceneManager->getParameters()->setAttribute(scene::DMF_ALPHA_CHANNEL_REF, 0.1);
\endcode
**/
const c8* const DMF_ALPHA_CHANNEL_REF = "DMF_AlphaRef";
//! Name of the parameter for choose to flip or not tga files.
/** Use it like this:
\code
//this way you'll choose to flip alpha textures
SceneManager->getParameters()->setAttribute(scene::DMF_FLIP_ALPHA_TEXTURES, true);
\endcode
**/
const c8* const DMF_FLIP_ALPHA_TEXTURES = "DMF_FlipAlpha";
//! Name of the parameter for changing the texture path of the built-in obj loader.
/** Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::OBJ_TEXTURE_PATH, "path/to/your/textures");
\endcode
**/
const c8* const OBJ_TEXTURE_PATH = "OBJ_TexturePath";
//! Flag to avoid loading group structures in .obj files
/** Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_GROUPS, true);
\endcode
**/
const c8* const OBJ_LOADER_IGNORE_GROUPS = "OBJ_IgnoreGroups";
//! Flag to avoid loading material .mtl file for .obj files
/** Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
\endcode
**/
const c8* const OBJ_LOADER_IGNORE_MATERIAL_FILES = "OBJ_IgnoreMaterialFiles";
//! Flag to ignore the b3d file's mipmapping flag
/** Instead Irrlicht's texture creation flag is used. Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::B3D_LOADER_IGNORE_MIPMAP_FLAG, true);
\endcode
**/
const c8* const B3D_LOADER_IGNORE_MIPMAP_FLAG = "B3D_IgnoreMipmapFlag";
//! Name of the parameter for changing the texture path of the built-in b3d loader.
/** Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::B3D_TEXTURE_PATH, "path/to/your/textures");
\endcode
**/
const c8* const B3D_TEXTURE_PATH = "B3D_TexturePath";
//! Flag set as parameter when the scene manager is used as editor
/** In this way special animators like deletion animators can be stopped from
deleting scene nodes for example */
const c8* const IRR_SCENE_MANAGER_IS_EDITOR = "IRR_Editor";
//! Name of the parameter for setting the length of debug normals.
/** Use it like this:
\code
SceneManager->getParameters()->setAttribute(scene::DEBUG_NORMAL_LENGTH, 1.5f);
\endcode
**/
const c8* const DEBUG_NORMAL_LENGTH = "DEBUG_Normal_Length";
//! Name of the parameter for setting the color of debug normals.
/** Use it like this:
\code
SceneManager->getParameters()->setAttributeAsColor(scene::DEBUG_NORMAL_COLOR, video::SColor(255, 255, 255, 255));
\endcode
**/
const c8* const DEBUG_NORMAL_COLOR = "DEBUG_Normal_Color";
} // end namespace scene
} // end namespace irr
#endif
| [
"seth@rtsoft.com"
] | seth@rtsoft.com |
c3321eef813a90b9a3521c618524cfe31a7485f8 | 71c1c86b30c1518e21728f7d5e0f09b5e602baac | /Algo_Engine/Bullseye/main.cpp | 1f9e4145f8298d2572c99fe45f5a226253d3a8bb | [] | no_license | ssh352/ronin | 3ddf360fec5f106015c6902b5107aedefe934836 | 33301b6c5e68fa9d02c7d54bc86f6b7732985fc2 | refs/heads/master | 2023-05-03T11:00:39.368460 | 2021-05-17T18:41:08 | 2021-05-17T18:41:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,700 | cpp | // ACE
#include <ace/Get_Opt.h>
// Application
#include "Application_Reactor_Thread_Pool.hpp"
#include "../ROM_Handler/Connection_Manager.hpp"
#include <ROM_Handler/Session_Control_Strategy.hpp>
#include <ROM_Handler/Session.hpp>
#include "Configurator/configuration.h"
#include <decision_engine/algo_manager.hpp>
#include <market_data/wombat_market_data_source.hpp>
#include <libdarthttp/http_server_singleton.hpp>
#include <Market_Data/Generic_DLL_Market_Data_Source.hpp>
#include "DART_Log.hpp"
#include "Decision_Engine/Volume_Profile_Data_Source.hpp"
// TODO: Excise as many platform specific dependencies
// as possible, use ACE as the platform.
// Platform SDK
#include <windows.h> // GetPrivateProfileIntA
// CRT
#include <ctime> // time_t, time (), gmtime (), strftime ()
#include <io.h> // _access
// Standard C++
#include <fstream> // std::ofstream
#include <string> // std::string
#include <iostream>
void app_invalid_param_handler(const wchar_t *expression,
const wchar_t *function,
const wchar_t *file,
unsigned int line,
uintptr_t /*reserved*/)
{
if (expression&&function&&file)
{
wchar_t widebuffer[128];
memset(widebuffer,
0,
sizeof(widebuffer));
swprintf(widebuffer,
sizeof(widebuffer)/sizeof(wchar_t),
L"%s:%d %s:%s",
file,
line,
function,
expression);
char narrowbuffer[128];
memset(narrowbuffer,
0,
sizeof(narrowbuffer));
wcstombs(narrowbuffer,
widebuffer,
sizeof(narrowbuffer));
ACE_DEBUG((LM_DEBUG,
"Invalid parameter handler invocation: %s\n",
narrowbuffer));
}
else
ACE_DEBUG((LM_DEBUG,"Invalid parameter handler invocation\n"));
}
int init_volume_profile_data() {
// Configure the volume profile data source for the VWAP algorithm
const std::string vwap_profile_dir
(CONFIGURATION::instance()->get("VWAP","VolumeProfileDirectory"));
if (vwap_profile_dir.empty()) {
DART_CRITICAL("No [VWAP]VolumeProfileDirectory INI section found\n");
return -1;
}
if (VOLUME_PROFILE_DATA_SOURCE::instance()->init
(vwap_profile_dir.c_str())==-1) {
DART_CRITICAL
("Volume profile directory (%s) doesn't exist or is not accessible\n",
vwap_profile_dir.c_str());
return -1;
}
return 0;
}
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
HANDLE named_mutex=NULL;
named_mutex=CreateMutex(NULL,TRUE,"Global\\Bullseye");
if (named_mutex==NULL || GetLastError()==ERROR_ALREADY_EXISTS)
{
DART_CRITICAL ("Another instance of Bullseye.exe is running\n");
return 1;
}
std::string log_file_name ("bullseye");
// Set the ACE logger to use our own logger
// Create a filename based on the date:
const time_t now (time (0));
const tm *ptm = gmtime (&now);
if (ptm)
{
char time_str [64];
memset (time_str, 0, sizeof (time_str));
if (strftime (time_str, sizeof (time_str), "%Y%m%d", ptm) > 0)
{
log_file_name += '-';
log_file_name += time_str;
log_file_name += ".log";
}
}
ACE_OSTREAM_TYPE *output = new std::ofstream
(log_file_name.c_str (), std::ios::out | std::ios::app);
ACE_LOG_MSG->msg_ostream (output, true);
ACE_LOG_MSG->set_flags (ACE_Log_Msg::OSTREAM);
DART_INFO ("Bullseye v0.0.0.2 starting up\n");
// Log command line
std::string commandline(argv[0]);
for (int i=1; i<argc; ++i)
{
commandline += ' ';
commandline += argv [i];
}
DART_INFO("Command line: %s\n", commandline.c_str());
// Setup our invalid parameter handler.
_set_invalid_parameter_handler(app_invalid_param_handler);
ACE_Get_Opt opt (argc, argv, "f:t:");
const char *configfile = 0;
size_t thread_count=4;
for (int c; (c = opt ()) != -1;)
{
if (c == 'f')
configfile = opt.opt_arg ();
else if (c == 't')
thread_count=ACE_OS::atoi(opt.opt_arg());
}
if (thread_count==0)
ACE_ERROR_RETURN((LM_ERROR, "Illegal thread count\n"), 1);
if (!configfile) {
ACE_DEBUG ((LM_DEBUG, "usage: Bullseye config-file\n"));
return 1;
}
// Get port from configuration file
if (_access (configfile, 0) == -1) {
ACE_DEBUG ((LM_DEBUG, "Cannot access configfile %s\n", configfile));
return 1;
}
CONFIGURATION::instance()->filename(configfile);
if (init_volume_profile_data()!=0)
return 1;
UINT port = atoi(CONFIGURATION::instance()->get("Bullseye", "ServerPort").c_str());
if (port == 0) {
ACE_DEBUG ((LM_DEBUG,
"Cannot find ServerPort key in the Bullseye section of %s\n",
configfile));
return 1;
}
#ifdef HTTP_INTERFACE
// Startup the HTTP interface
try
{
HTTP_SERVER::instance()->init();
HTTP_SERVER::instance()->start();
}
catch (const std::exception &e)
{
std::cerr
<< "HTTP server initialization/start failed: "
<< e.what() << std::endl;
}
#endif // HTTP_INTERFACE
const std::string configsection
(CONFIGURATION::instance()->get("MarketData","Section"));
const std::string dll
(CONFIGURATION::instance()->get("MarketData","Dll"));
if (!dll.empty()
&& dart::GENERIC_MD_SOURCE::instance()->open
(dll.c_str(), configfile, configsection.c_str())==-1)
{
ACE_ERROR_RETURN((LM_ERROR,"Error opening market data source\n"),1);
}
/*
* Setup the reactor model for our application. The application architecture
* is designed for a pool of threads servicing a single reactor. The single
* reactor is set as the default singleton reactor instance for convenience,
* there is no need to pass around reactor references when setting up tasks.
* The multiple threads give concurrency to the application. The exact number
* of threads used for the reactor can be configured at application startup
* or dynamically determined based on the hardware the application is being
* run on.
*/
Application_Reactor_Thread_Pool thread_pool;
Connection_Manager *conn_mgr = CONNECTION_MANAGER::instance ();
if (conn_mgr->open () == -1)
ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("mgr.open")), 1);
// TODO: Eventually we might want to get this from the Session_Registrar, we
// could allow the Session_Registrar to make decisions about how to find
// files, etc.
Session *market_dest_session = new Session(new Client_Session_Control_Strategy);
Logon_Credentials credentials;
credentials.username = CONFIGURATION::instance()->get("Bullseye", "ClientUsername");
credentials.password = CONFIGURATION::instance()->get("Bullseye", "ClientPassword");
market_dest_session->logon_credentials(credentials);
const std::string dest
(CONFIGURATION::instance()->get ("Bullseye","OutboundHost"));
if (dest.empty())
{
DART_CRITICAL ("No outbound ROM host specified in configuration\n");
return 1;
}
const std::string destport
(CONFIGURATION::instance()->get("Bullseye","OutboundPort"));
if (destport.empty())
{
DART_CRITICAL ("No outbound ROM port specified in configuration\n");
return 1;
}
int destportnum (ACE_OS::atoi (destport.c_str()));
if (destportnum==0 || destportnum > std::numeric_limits<u_short>::max())
{
DART_CRITICAL ("Invalid outbound ROM port '%s'\n",destport.c_str());
return 1;
}
if (!conn_mgr->destination
(ACE_INET_Addr(static_cast <u_short> (destportnum), dest.c_str()),
market_dest_session))
ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Unable to add destination\n")), 1);
// Make sure the ALGO_MANAGER Singleton is initialized
dart::Algo_Manager *algoman = dart::ALGO_MANAGER::instance();
if (algoman->open() != 0)
ACE_ERROR_RETURN((LM_ERROR,
ACE_TEXT("(%t) %s: algo_manager open failed"),
ACE_TEXT(__FUNCTION__)), -1);
algoman->set_market_data_source(dart::GENERIC_MD_SOURCE::instance());
algoman->outbound_connection(market_dest_session);
DART_DEBUG ("Spawning %d threads\n",thread_count);
if (thread_pool.activate (THR_NEW_LWP | THR_JOINABLE, thread_count) == -1)
ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("activate")), 1);
ACE_Thread_Manager::instance ()->wait ();
return 0;
}
void Session::logon_credentials(const Logon_Credentials &logon_credentials)
{
this->logon_credentials_ = logon_credentials;
}
| [
"pflynn@sumocap.com"
] | pflynn@sumocap.com |
7f8422018c9c462bb8bb7f4235c1558a71176811 | 8583b5bfc594b994f51d24d012e92ae66bf2e5ea | /src/BabylonCpp/src/meshes/builders/tiled_box_builder.cpp | d3542b2042b2a198663a71dcb9f3b33a69987296 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | samdauwe/BabylonCpp | 84b8e51b59f04a847681a97fa6fe0a5c554e9e1f | 3dad13a666299cbcf2e2db5b24575c19743e1000 | refs/heads/master | 2022-01-09T02:49:55.057544 | 2022-01-02T19:27:12 | 2022-01-02T19:27:12 | 77,682,359 | 309 | 41 | Apache-2.0 | 2020-11-06T12:16:17 | 2016-12-30T11:29:05 | C++ | UTF-8 | C++ | false | false | 732 | cpp | #include <babylon/meshes/builders/tiled_box_builder.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
namespace BABYLON {
MeshPtr TiledBoxBuilder::CreateTiledBox(const std::string& name, TiledBoxOptions& options,
Scene* scene)
{
const auto box = Mesh::New(name, scene);
options.sideOrientation = Mesh::_GetDefaultSideOrientation(options.sideOrientation);
box->_originalBuilderSideOrientation = *options.sideOrientation;
const auto vertexData = VertexData::CreateTiledBox(options);
vertexData->applyToMesh(*box, options.updatable);
return box;
}
} // end of namespace BABYLON
| [
"sam.dauwe@gmail.com"
] | sam.dauwe@gmail.com |
0d2ac4363c4102c68f43f5c248f342f1d6a2a732 | b2571f919ae552c4dff006be9c825184d272dd75 | /uri/1038.cpp | 75756f0a96684fa64ff455c6babf716a029b1238 | [] | no_license | juanplopes/icpc | 22877ca4ebf67138750f53293ee9af341c21ec40 | 3e65ffe9f59973714ff25f3f9bb061b98455f781 | refs/heads/master | 2020-12-25T17:35:04.254195 | 2017-10-27T23:53:25 | 2017-10-27T23:53:25 | 2,492,274 | 121 | 44 | null | null | null | null | UTF-8 | C++ | false | false | 322 | cpp | //1038
//Snack
//Misc;Beginner
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
int x, y;
while(cin >> x >> y) {
double price = x==1 ? 4 : x==2 ? 4.5 : x==3 ? 5 : x==4 ? 2 : 1.5;
cout << "Total: R$ " << fixed << setprecision(2) << y*price << endl;
}
}
| [
"me@juanlopes.net"
] | me@juanlopes.net |
f70913330c4e98d6724bb184195cdcd847ba4d14 | ec9886f2347a8d62b6ca7bc1ed8bfa18141386d0 | /Clappy3/src/Subsystems/Climber.cpp | f99bfe2e052b74de7d27c90f0b30625f7b9d0afe | [] | no_license | craftgarrick04401/Clappy3 | edb5d7f0cec073ad13072deb119925d6b7f3c8d6 | ac488e9da7501992da342f929e3dcdb1d6fb4a7a | refs/heads/master | 2021-01-19T09:32:19.166722 | 2017-08-24T22:54:35 | 2017-08-24T22:54:35 | 82,125,314 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | #include "Climber.h"
#include "../Commands/ControlClimbmotor.h"
#include "../RobotMap.h"
Climber::Climber() : Subsystem("Climber") {
climbMotor = RobotMap::climbMotor;
}
void Climber::InitDefaultCommand() {
// Set the default command for a subsystem here.
// SetDefaultCommand(new MySpecialCommand());
SetDefaultCommand(new ControlClimbmotor());
}
void Climber::SetMotorSpeed(double speed)
{
climbMotor->Set(speed);
}
void Climber::StopMotor()
{
climbMotor->StopMotor();
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
| [
"craftgarrick04401@gmail.com"
] | craftgarrick04401@gmail.com |
34abf86e74d9a98f67afa7ff99dbaf7358dbd259 | 21df65712af0b9d095ccdc376a821563c9f525cb | /Source/BlueprintInsights/Public/BlueprintInsights.h | 595364bd205ae9f8046c39591cf81d221eb412a9 | [
"MIT"
] | permissive | sleepCOW/BlueprintInsights | af3cfa8b9fdb139784f9cd0721581d1e088b62ff | f2ea205f8ec3e30ee1b8a84e4cf9601493007516 | refs/heads/main | 2023-04-21T17:44:35.309672 | 2021-05-06T22:54:26 | 2021-05-06T22:54:26 | 365,052,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
class FBlueprintInsightsModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};
| [
"olexthelake@gmail.com"
] | olexthelake@gmail.com |
93911ea4583efcf12255641ffe97c063cf615e2a | f04eca8d3952e419e3f5ab45a360393c9c331346 | /cpp/0191NumberOf1Bits.cpp | 682adebe8d03576ac1818d03f9adeb3c12a97154 | [] | no_license | diordnar/leetCode | 9c41290dc4072d81581a0506299472531cce5105 | d3b373ec49e717c6d8b259b5494b43414b9050f7 | refs/heads/master | 2021-08-10T21:46:01.704325 | 2021-01-17T11:01:44 | 2021-01-17T11:01:44 | 242,065,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | cpp | // 191. 位1的个数
// 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数
//(也被称为汉明重量)。
// 示例 1:
// 输入:00000000000000000000000000001011
// 输出:3
// 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
// 示例 2:
// 输入:00000000000000000000000010000000
// 输出:1
// 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
// 示例 3:
// 输入:11111111111111111111111111111101
// 输出:31
// 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/number-of-1-bits
// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#include <iostream>
#include <cstdint> //c++11 uint32_t
using namespace std;
class Solution
{
public:
int hammingWeight(uint32_t n)
{
int cnt = 0;
while (n != 0)
{
n = n & (n - 1);
++cnt;
}
return cnt;
}
};
int main()
{
return 0;
} | [
"torrey.tsui@outlook.com"
] | torrey.tsui@outlook.com |
8efd143cef01cd09ee1f2f42970c1baffbec0a03 | 45679fd220f9a696d82703fe4d6b6e999953090e | /examples/SMTP/Send_Access_Token/Send_Access_Token.ino | 5083c31b515802bbf1fd6eb3fe6f2b49fb3663db | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | RoSchmi/ESP-Mail-Client | cc57211cbdd143f68fd605010baf9d2e07d9a4b2 | 74a4824a9b5f0436212c1913e1d7b6adda201f6f | refs/heads/master | 2023-08-25T11:17:28.306010 | 2021-11-10T22:24:59 | 2021-11-10T22:24:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,232 | ino |
/**
*This example will log in with the SASL XOAUTH2 mechanisme using OAuth2.0 access token.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
//To use send Email for Gmail to port 465 (SSL), less secure app option should be enabled. https://myaccount.google.com/lesssecureapps?pli=1
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
//To use only SMTP functions, you can exclude the IMAP from compilation, see ESP_Mail_FS.h.
#define WIFI_SSID "<ssid>"
#define WIFI_PASSWORD "<password>"
#define SMTP_HOST "<host>"
/** The smtp port e.g.
* 25 or esp_mail_smtp_port_25
* 465 or esp_mail_smtp_port_465
* 587 or esp_mail_smtp_port_587
*/
#define SMTP_PORT 25
/* The user Email for OAuth2.0 access token */
#define AUTHOR_EMAIL "<email>"
/** The OAuth2.0 access token
* The generation, exchange and refresh of the access token are not available
* in this library.
*
* To test this using GMail, get the OAuth2.0 access token from this web site
* https://developers.google.com/oauthplayground/
*
* You can use the ESP Signer library to generate OAuth2.0 access token
* The library is available here https://github.com/mobizt/ESP-Signer
*
* 1. Select the following scope (in Step 1) from Gmail API V1
* https://mail.google.com/
* https://mail.google.com/
*
* 2. Click Authorize APIs button.
* 3. Cick Exchangeauthorization code for tokens.
* 4. From the response, look at access_token from the JSON payload node.
* 5. Copy that access token and paste to the AUTHOR_ACCESS_TOKEN value.
*
* The token will be expired in 3600 seconds (1 Hr).
* The AUTHOR_EMAIL above is the Email address that you granted to access the Gmail services.
*/
#define AUTHOR_ACCESS_TOKEN "<access token>"
/* The SMTP Session object used for Email sending */
SMTPSession smtp;
/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status);
void setup()
{
Serial.begin(115200);
#if defined(ARDUINO_ARCH_SAMD)
while (!Serial)
;
Serial.println();
Serial.println("**** Custom built WiFiNINA firmware need to be installed.****\nTo install firmware, read the instruction here, https://github.com/mobizt/ESP-Mail-Client#install-custom-built-wifinina-firmware");
#endif
Serial.println();
Serial.print("Connecting to AP");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(200);
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
/** Enable the debug via Serial port
* none debug or 0
* basic debug or 1
*
* Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h
*/
smtp.debug(1);
/* Set the callback function to get the sending results */
smtp.callback(smtpCallback);
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = SMTP_HOST;
session.server.port = SMTP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.accessToken = AUTHOR_ACCESS_TOKEN;
session.login.user_domain = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending Email using Access token";
message.addRecipient("Admin", "change_this@your_mail_dot_com");
message.text.content = "This is simple plain text message";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
//message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;
/* Connect to server with the session config */
if (!smtp.connect(&session))
return;
/* Set the custom message header */
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
/* Start sending Email and close the session */
if (!MailClient.sendMail(&smtp, &message))
Serial.println("Error sending Email, " + smtp.errorReason());
//to clear sending result log
//smtp.sendingResult.clear();
ESP_MAIL_PRINTF("Free Heap: %d\n", MailClient.getFreeHeap());
}
void loop()
{
}
/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Print the sending result */
if (status.success())
{
Serial.println("----------------");
ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());
ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());
Serial.println("----------------\n");
struct tm dt;
for (size_t i = 0; i < smtp.sendingResult.size(); i++)
{
/* Get the result item */
SMTP_Result result = smtp.sendingResult.getItem(i);
time_t ts = (time_t)result.timestamp;
localtime_r(&ts, &dt);
ESP_MAIL_PRINTF("Message No: %d\n", i + 1);
ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");
ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);
ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients);
ESP_MAIL_PRINTF("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
//You need to clear sending result as the memory usage will grow up as it keeps the status, timstamp and
//pointer to const char of recipients and subject that user assigned to the SMTP_Message object.
//Because of pointer to const char that stores instead of dynamic string, the subject and recipients value can be
//a garbage string (pointer points to undefind location) as SMTP_Message was declared as local variable or the value changed.
//smtp.sendingResult.clear();
}
}
| [
"k_suwatchai@hotmail.com"
] | k_suwatchai@hotmail.com |
d50dcb6a4584a0995dd20a4354d56b8da6dc7a81 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/boost/hof/detail/noexcept.hpp | 621111d8eac2bc2ed41587ebe9b01c84eab54a14 | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 646 | hpp | /*=============================================================================
Copyright (c) 2016 Paul Fultz II
noexcept.hpp
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef BOOST_HOF_GUARD_DETAIL_NOEXCEPT_HPP
#define BOOST_HOF_GUARD_DETAIL_NOEXCEPT_HPP
#include <sstd/boost/hof/config.hpp>
#if BOOST_HOF_HAS_NOEXCEPT_DEDUCTION
#define BOOST_HOF_NOEXCEPT(...) noexcept(__VA_ARGS__)
#else
#define BOOST_HOF_NOEXCEPT(...)
#endif
#endif
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
840753e7b43e6b413c8289e90d11fbc102924acd | e8c4cedaa0965aee84d3ee4b00b5b3887889dc32 | /BMH/uwbmh.cpp | d50813308abe5ae8d72da8c5bfb1a53a9fca9aed | [] | no_license | cmperezg/UWRAM | 66ebe2682bf123e3886dd7cdb3ca31aacc8d5cbf | 5084066ac120d08b5e7c78e23dcba86120b2aea3 | refs/heads/master | 2021-01-23T21:43:19.306690 | 2017-03-08T20:13:30 | 2017-03-08T20:13:30 | 59,245,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,969 | cpp | #include <cstdio>
#include <vector>
#include <chrono>
#include <tuple>
#include <list>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <fstream>
#include <string>
#include <iostream>
#include "ultraword.h"
//compile: g++ uwbmh.cpp ultraword.cpp -o uwbmh -std=c++11
void printlongbits(unsigned long long int n){
long long int i;
for(i=63;i>=0;i--){
unsigned long long int mask = ((unsigned long long int)1)<<i;
unsigned long long int maskedn = n&mask;
unsigned long long int thebit = maskedn >> i;
printf("%u",(unsigned int)thebit);
if(i%8==0){
printf(" ");
}
//printf("%llu",n);
}
//printf("%llu",n);
printf("\n");
}
void printUWc(UltraWord& u){
unsigned long long int blocks[UltraWord::BLOCK_SIZE];
unsigned long long int *a = u.getBlocks();
unsigned long long int mask8 = (unsigned long long int)0xFF<<56;
int i;
int j;
for(i=0;i<UltraWord::NUM_BLOCKS;i++){
blocks[i] = a[i];
}
for(i=0;i<UltraWord::NUM_BLOCKS;i++){
for(j=0;j<(UltraWord::BLOCK_SIZE/8);j++){
printf("%c",(int)(blocks[i]>>56));
//printf("i: %d j: %d \n",i,j);
//printlongbits(blocks[i]);
blocks[i] = blocks[i]<<8;
}
}
std::cout<< std::endl;
}
std::list<int> uwbmh(std::string text, std::string pat){
std::list<int> res;
int cs = 8; //char size in bits
int cn = 8; //number of chars to pack per int
int i = 0; //charcounter
int j = 0; //int counter
int strlen = text.size();
int patlen = pat.size();
UltraWord t; //text
UltraWord p; //pattern
//pack first UW
unsigned long long int tempblocks[64]={0};
unsigned long long int temp;
int shift = 0;
//tempblocks[0] = 0;
while(i<strlen & j<UltraWord::NUM_BLOCKS){
temp = text.at(i);
shift = cn*cs - ((i%cn)+1)*cs;
tempblocks[j] = tempblocks[j] | (temp<<shift);
if((i+1)%cn == 0){
j++;
//tempblocks[j] = 0;
}
i++;
}
std::cout << "i after packing" << i << " \n";
t.setBlocks(tempblocks);
//pack pattern into UW. pattern should be shorter than 512 chars
unsigned long long int tempblocks2[64]={0};
int k=0; j=0;
while(k<patlen){
temp = pat.at(k);
shift = cn*cs - ((k%cn)+1)*cs;
std::cout<< "shift: " << shift << "\n";
tempblocks2[j] = tempblocks2[j] | (temp<<shift);
if((k+1)%cn == 0){
j++;
//tempblocks[j] = 0;
}
k++;
}
p.setBlocks(tempblocks2);
printUWc(t);
printUWc(p);
//UW window mask
UltraWord wmask;
UltraWord one;
wmask=1;
one =1;
for(j=0;j<(patlen*8)-1;j++){
wmask = (wmask<<1)|one;
}
wmask = wmask<<(UltraWord::WORD_SIZE-(patlen*8));
UltraWord testequal;
int shcount = strlen - patlen; //number of shifts needed to cover all windows
int rotcount = strlen - (UltraWord::WORD_SIZE/8); // number of rotations needed to add whole text to UW.
int count = 0; // number of shifts so far
std::cout << "shcount" << shcount << " \n";
std::cout << "rotcount" << rotcount << " \n";
bool finished = false;
UltraWord rot;
while(!finished){
//std::cout<<"printingyay! \n";
//printUWc(t);
testequal = t&wmask;
testequal = testequal-p;
if(testequal.iszeros()){
//match
res.push_back(count);
}
if(count<shcount){
t = t<<8;
if(count<rotcount){
rot = text.at(i);
t = t|rot;
}
}else{
finished = true;
}
i++;
count++;
}
return res;
}
void printResults(const std::list<int>& s){
std::cout<< "found pattern at: ";
std::list<int>::const_iterator i;
for(i=s.begin();i!=s.end();++i){
std::cout<<*i << " ";
}
std::cout<< "\n";
}
int main(){
std::ifstream infile {"lidata10.txt"};
std::string fst{std::istreambuf_iterator<char>(infile),std::istreambuf_iterator<char>()};
std::transform(fst.begin(),fst.end(),fst.begin(),::tolower);
std::string pattern = "vestibulum";
printResults(uwbmh(fst,pattern));
return 0;
}
| [
"cmperezg@DESKTOP-8VM9T77.localdomain"
] | cmperezg@DESKTOP-8VM9T77.localdomain |
37d1a6bedca54ad85949370bc21708d34d697779 | fc80c9504e3392c1ed3a23b80faa09f6f49289b3 | /movie.h | 55a152085715bafc4a8876717c9c25ae9a2d15c8 | [] | no_license | Muhammadkamranlive/data-structure-project-c-file-processing | dcb030964cd135738a6c086fd2509c04ea062cd7 | 85a438f80681876910887a0f5862efbe42204027 | refs/heads/main | 2023-07-13T23:10:33.552288 | 2021-08-22T13:23:17 | 2021-08-22T13:23:17 | 398,804,553 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,852 | h | #include<iostream>
#include<fstream>
using namespace std;
class Movie_Node{
private:
string movie_name;
string movie_type;
string movie_release_date;
string theaters_available;
Movie_Node* next;
public:
string Getmovie_name();
string Getmovie_release_date();
string Getmovie_type();
string Gettheaters_available();
Movie_Node* Getnext();
void Setmovie_name(string movie_name);
void Setmovie_release_date(string movie_release_date);
void Settheaters_available(string theaters_available);
void Setmovie_type(string movie_type);
void Setnext(Movie_Node* next);
};
string Movie_Node::Getmovie_name(){
return this->movie_name;
}
string Movie_Node::Getmovie_release_date(){
return this->movie_release_date;
}
string Movie_Node::Getmovie_type(){
return this->movie_type;
}
string Movie_Node::Gettheaters_available(){
return this->theaters_available;
}
Movie_Node* Movie_Node::Getnext(){
return this->next;
}
void Movie_Node::Setmovie_name(string movie_name){
this->movie_name=movie_name;
}
void Movie_Node::Setmovie_release_date(string movie_release_date){
this->movie_release_date=movie_release_date;
}
void Movie_Node::Settheaters_available(string theaters_available){
this->theaters_available=theaters_available;
}
void Movie_Node::Setmovie_type(string movie_type){
this->movie_type=movie_type;
}
void Movie_Node::Setnext(Movie_Node* next){
this->next=next;
}
class Movie_list{
private:
Movie_Node* currentlocation;
public:
Movie_list();
void insert_movie_list(string,string,string,string);
void save_movie_list(string,string,string,string);
void print_movie_list();
};
Movie_list::Movie_list(){
currentlocation=NULL;
}
void Movie_list::insert_movie_list(string movie_name,string movie_release_date,string movie_type,string theaters_available){
Movie_Node* newNode= new Movie_Node();
newNode->Setmovie_name(movie_name);
newNode->Setmovie_release_date(movie_release_date);
newNode->Setmovie_type(movie_type);
newNode->Settheaters_available(theaters_available);
Movie_Node* tempNode=currentlocation;
if(tempNode!=NULL){
while(tempNode->Getnext()!=NULL){
tempNode=tempNode->Getnext();
}
tempNode->Setnext(newNode);
}
else{
currentlocation=newNode;
}
}
void Movie_list::save_movie_list(string movie_name,string movie_release_date,string movie_type,string theaters_available){
ofstream outfile;
outfile.open("movie.txt",ios::app);
if(!outfile){
cout<<"sorry rating file is not opened"<<endl;
}
else{
outfile<<movie_name<<"\t\t"<<movie_release_date<<"\t\t"<<movie_type<<"\t\t"<<theaters_available<<endl;
outfile.close();
}
}
void Movie_list::print_movie_list(){
Movie_Node* tempNode= new Movie_Node();
tempNode=currentlocation;
if(tempNode==NULL){
cout<<"sorry movie list is empty"<<endl;
}
else if(tempNode->Getnext()==NULL){
cout<<"\t\tþþþþþþþþþþþþþ Movie Records þþþþþþþþþþþþþþ\n\n\n"<<endl;
cout<<"\t\tMovie name \t\tþþþþþþ"<<tempNode->Getmovie_name()<<endl;
cout<<"\t\tMovie release date\t\tþþþþþþ"<<tempNode->Getmovie_release_date()<<endl;
cout<<"\t\tMovie type \t\tþþþþþþ"<<tempNode->Getmovie_type()<<endl;
cout<<"\t\tTheaters avaialable\t\tþþþþþþ"<<tempNode->Gettheaters_available()<<endl;
}
else{
while(tempNode!=NULL){
cout<<"\t\tþþþþþþþþþþþþþ Movie Records þþþþþþþþþþþþþþ\n\n\n"<<endl;
cout<<"\t\tMovie name \t\tþþþþþþ"<<tempNode->Getmovie_name()<<endl;
cout<<"\t\tMovie release date\t\tþþþþþþ"<<tempNode->Getmovie_release_date()<<endl;
cout<<"\t\tMovie type \t\tþþþþþþ"<<tempNode->Getmovie_type()<<endl;
cout<<"\t\tTheaters avaialable\t\tþþþþþþ"<<tempNode->Gettheaters_available()<<endl;
tempNode=tempNode->Getnext();
}
}
}
| [
"89290897+Muhammadkamranlive@users.noreply.github.com"
] | 89290897+Muhammadkamranlive@users.noreply.github.com |
b987180329d41ee02414b6c18e708504f59cb719 | 2c1e5a69ca68fe185cc04c5904aa104b0ba42e32 | /src/game/ASpriteInstance.cpp | d240eec7d3ac2e166123b0f83621607827ce3db0 | [] | no_license | dogtwelve/newsiderpg | e3f8284a7cd9938156ef8d683dca7bcbd928c593 | 303566a034dca3e66cf0f29cf9eaea1d54d63e4a | refs/heads/master | 2021-01-10T13:03:31.986204 | 2010-06-27T05:36:33 | 2010-06-27T05:36:33 | 46,550,247 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 19,519 | cpp | #include "ASpriteInstance.h"
#include "ASprite.h"
/*int ASpriteInstance::x;
int ASpriteInstance::y;
int ASpriteInstance::_posX;
int ASpriteInstance::_posY;*/
#include "Macro.h"
ASpriteInstance::ASpriteInstance(ASprite* spr, int posX, int posY, ASpriteInstance* parent)
{
CameraX=0;
CameraY=0;
m_lastX = m_posX = posX;
m_lastY = m_posY = posY;
// m_flags = 0;
m_pal = 0;
m_sprite = spr;
m_nState = 0;
m_nCrtModule = 0;
m_nCrtFrame = 0;
m_nCrtAnimation = 0;
m_rect = GL_NEW int[4];
m_bLoop = true;
// m_parent = parent;
}
ASpriteInstance::~ASpriteInstance()
{
SAFE_DEL_ARRAY(m_rect);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::SetModule(int id)
{//SangHo - 그리기 속성을 Module로 바꿔준다
//행동이 바뀌면 기존의 마지막 좌표는 초기화 시켜준다
m_lastAniX=0;
m_lastAniZ=0;
m_nState = 2;
m_nCrtAnimation = -2;//SangHo - -2 일 경우 Animation 작동하지않는다
m_nCrtModule = id;
//m_nCrtFrame = -1;//SangHo - -1 일 경우 Frame 작동하지않는다
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::SetFrame(int id)
{//SangHo - 그리기 속성을 Frame로 바꿔준다
//행동이 바뀌면 기존의 마지막 좌표는 초기화 시켜준다
m_lastAniX=0;
m_lastAniZ=0;
m_nState = 1;
m_nCrtAnimation = -2;//SangHo - -2 일 경우 Animation 작동하지않는다
m_nCrtModule = -1;//SangHo - -1 일 경우 Module 작동하지않는다
m_nCrtFrame = id;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool ASpriteInstance::SetAnim(int id)
{//SangHo - 그리기 속성을 Animation로 바꿔준다
//if(!m_bLoop)
//{
//m_bAnimIsOver = false;
//행동이 바뀌면 기존의 마지막 좌표는 초기화 시켜준다
m_lastAniX=0;
m_lastAniZ=0;
m_nState = 0;
m_nCrtModule = id;
m_nCrtFrame = 0;
m_nCrtAnimation = -1;//SangHo - 0대신 -1인 이유는 Paint 전에 항상 키값에 대한 업데이트를 수행해야 하므로 첫프레임을 못찍는 구조적 한계때문
is_aniDone = false;
return true;
//}
//else
//{
// if (id != m_nCrtModule)
// {
// //m_bAnimIsOver = false;
// m_nCrtModule = id;
// m_nCrtFrame = 0;
// m_nCrtAnimation = 0;
// is_aniDone = false;
// return true;
// }
//}
//return false;
}
//void ASpriteInstance::SetAniLoop(bool _loop)
void ASpriteInstance::RewindAnim(int id)
{//SangHo - id Anim 으로 교체후 초기화
//m_bAnimIsOver = false;
m_nCrtModule = id;
m_nCrtFrame = 0;
m_nCrtAnimation = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::SetToLastFrame()
{//SangHo - Anim의 마지막 인덱스값으로 이동
m_nCrtFrame = m_sprite->GetAFrames(m_nCrtModule) - 1;
m_nCrtAnimation = m_sprite->GetAFrameTime(m_nCrtModule, m_nCrtFrame) - 1;
}
void ASpriteInstance::setAnimStop( )
{//SangHo - Anim을 재생중단후 인덱스 초기화
is_aniDone = true;
m_nCrtFrame = 0;
}
void ASpriteInstance::setCamera(int _CameraX, int _CameraY)
{//SangHo - Anim을 재생중단후 인덱스 초기화
CameraX = _CameraX;
CameraY = _CameraY;
}
bool ASpriteInstance::IsAnimEnded()
{//SangHo - Anim가 현재 재생중인지 아닌지를 알려준다
if(is_aniDone)
{
return true;
}
//if (m_bReverse)
//{
// if (m_nCrtFrame != 0)
// {
// return false;
// }
//}
else if (m_nCrtFrame != m_sprite->GetAFrames(m_nCrtModule) - 1)
{
return false;
}
int time = m_sprite->GetAFrameTime(m_nCrtModule, m_nCrtFrame);
return ((time == 0) || (m_nCrtAnimation == time - 1));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::Get_AFrameXZ(int* tmpXZ){//그리기 전에 좌표 확인이 필요할때
m_sprite->Get_AFrameXY(tmpXZ , m_nCrtModule, m_nCrtFrame, m_posX + m_lastAniX, 0, m_flags, 0, 0);
}
void ASpriteInstance::PaintSprite(CGraphics* g,int flags)//SangHo - flags값을 넣지않을경우 0으로 간주한다
{
m_flags = flags;
PaintSprite(g);
}
void ASpriteInstance::PaintSprite(CGraphics* g,int posX,int posY,int flags)//SangHo - flags값을 넣지않을경우 0으로 간주한다
{
m_posX = posX;
m_posY = posY;
m_flags = flags;
PaintSprite(g);
}
void ASpriteInstance::PaintSprite(CGraphics* g)//SangHo - flags값에 따라 좌우상하반전 또는 90도 회전을 지원한다
{//CameraX,CameraY 는 맵 배경 스크롤에 따른 보정 수치
//const static byte FLAG_FLIP_X = 0x01;
//const static byte FLAG_FLIP_Y = 0x02;
//const static byte FLAG_ROT_90 = 0x04;
// m_flags = flags;
//m_bAnimIsOver = false;
if (m_sprite == NULL)
return;
//if ((m_flags & FLAG_DONTDRAW) != 0)
//{
// return;
//}
//if ((m_layer & 4) != 0)
//{
// return;
//}
m_sprite->changePal(m_pal);
m_sprite->SetBlendCustom(s_Blend.blendCustom,s_Blend.overWrite,s_Blend.Blend_Kind,s_Blend.Blend_Percent);
if (m_nCrtAnimation >= -1)//-2 일 경우에 에니메이션이 아닌 프레임또는 모듈을 그린다
{
m_sprite->PaintAFrame(g, m_nCrtModule, m_nCrtFrame,CameraX+ m_posX + m_lastAniX, CameraY+ (m_posY + m_posZ) + m_lastAniZ, m_flags, 0, 0);
if(!b_MoveLock){
m_posX-=m_sprite->m_nowAniX - m_lastAniX;
m_posZ-=m_sprite->m_nowAniZ - m_lastAniZ;
//갱신이 끝난 좌표에 전프레임 좌표를 뺀값만큼을 더해준다
m_lastAniX = m_sprite->m_nowAniX;
m_lastAniZ = m_sprite->m_nowAniZ;
m_stopFlag = m_sprite->m_nowFlag;
}
}
else if (m_nCrtModule >= 0) // m_nCrtModule --> module
{
// 앵커는 임시로 쓰임
m_sprite->PaintModule(g, m_nCrtModule, CameraX+ m_posX, CameraY+ (m_posY + m_posZ), m_flags, g->BOTTOM | g->HCENTER );
}
else if (m_nCrtFrame >= 0) // m_nCrtFrame --> frame
{
m_sprite->PaintFrame(g, m_nCrtFrame,CameraX+ m_posX, CameraY+ (m_posY + m_posZ), m_flags, 0, 0);
}
//m_bAnimIsOver = IsAnimEnded();
m_lastX =m_posX; //SangHo - 인스턴스의 현 좌표를 반영한다. - 몸통체크를 위해서(전좌표로 쓰인다)
m_lastY =m_posY; //SangHo - 인스턴스의 현 좌표를 반영한다. - 몸통체크를 위해서(전좌표로 쓰인다)
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//SangHo - 구조적 문제 해결위해 다시제작 (2008.12.19)
bool ASpriteInstance::UpdateSpriteAnim()
{//SangHo - Animation의 현재값을 1증가시킨다.
//return true - 애니메이션 재생중
//return false - 애니메이션 종료
int _m_time = 0;//총 Time 값 (딜레이수치 디폴값은 0)
int _m_frame = 0;//총 프레임값 (프레임 맥스값)
_m_time = m_sprite->GetAFrameTime(m_nCrtModule, m_nCrtFrame); // 해당 프레임의 Time값
_m_frame = m_sprite->GetAFrames(m_nCrtModule);//m_nCrtModule 는 애니메이션 넘버
{//무결성 체크
if (m_sprite == NULL) return true;
if (m_nCrtAnimation < -1) return true;//업데이트 수행시 time 값을 무조건 ++ 시키므로 초기값은 -1, 루프후는 0으로 돌아간다
if ((m_flags & FLAG_PAUSED) != 0) return true;//일시정지시 무조건 return
}
//{//예외값 통일화 처리
// if (m_nCrtAnimation < 0)
// m_nCrtAnimation=0;
//}
{//프레임의 Time 값을 체크한다 ----- Time 값만큼 딜레이 후에 다음 프레임으로 넘어간다
m_nCrtAnimation++; //인스턴스의 time 값 1증가
if (m_nCrtAnimation < _m_time) //프레임의 타임값보다 작다면 1증가 하고 한번더 그림
if (m_nCrtAnimation == (_m_time-1) && m_nCrtFrame == (_m_frame -1) ){//&&!m_bLoop) //마지막Time 일때 다음으로 증가할 프레임이 없다면 false 가 되야한다
return false;
}else
return true;
}
{//애니의 프레임 값을 체크한다 ----- 마지막 프레임일 경우 (드로잉종료, 루프) 여부 판단
if (m_nCrtFrame < (_m_frame -1)){ //프레임 갯수(-1) 보다 현재 프레임인덱스가 작다면 프레임인덱스를 1증가 시킨다
m_nCrtAnimation=0;//프레임의 타임값 초기화
m_nCrtFrame++;//다음프레임으로
{//만약 넘어간 프레임이 마지막 프레임 & time 1 이면 미리 체크를 해줘야 한다-안그러면 마지막 프레임을 한번더 그린다
_m_time = m_sprite->GetAFrameTime(m_nCrtModule, m_nCrtFrame); // 해당 프레임의 Time값
if((m_nCrtFrame == (_m_frame -1) && _m_time == 1 )&&!m_bLoop)
return false;
else
return true;
}
}else{//업데이트 마지막 값 도달
if(m_bLoop){//루프애니메이션일 경우
m_nCrtAnimation=0;//프레임의 타임값 초기화
m_nCrtFrame = 0;//첫프레임으로
m_lastAniX=0;
m_lastAniZ=0;
//if(Move)UpdateTempXZ(APPLY_X|APPLY_Z);//루프가 돌면 최종좌표를 반영해야한다
return true;
}else{//1회성 애니메이션일 경우
return false;//////////////////////////// 에니메이션 종료 ////////////////////////////
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int ASpriteInstance::GetCurrentAFrameOff(bool bY)
{//SangHo - 현재 Off값 구하는 부분이긴하나 활용예상부분을 모르겠음
int off = (m_sprite->_anims_af_start[m_nCrtModule] + m_nCrtFrame) * 5;
if (bY)
{
return m_sprite->_aframes[off + 3];
}
return m_sprite->_aframes[off + 2];
}
int ASpriteInstance::GetLastAFrameOff(bool bY)
{//SangHo - 마지막 Off값 구하는 부분이긴하나 활용예상부분을 모르겠음
int lastAFrame = m_sprite->GetAFrames(m_nCrtModule) - 1;
int off = (m_sprite->_anims_af_start[m_nCrtModule] + lastAFrame) * 5;
if (bY)
{
return m_sprite->_aframes[off + 3];
}
return m_sprite->_aframes[off + 2];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int* ASpriteInstance::GetRect(bool bColRect)
{//SangHo - LCD기준의 좌,상,너비,높이 4개인자값을 리턴한다.
if (m_rect == NULL)
{
m_rect = GL_NEW int[4];
}
int posX = m_posX;
int posY = m_posY;
if (m_sprite != NULL)
{
if (m_nCrtModule >= 0)
{
if (m_nCrtAnimation >= 0)
{
m_sprite->GetAFrameRect(m_rect, m_nCrtModule, m_nCrtFrame, posX, posY, m_flags, 0, 0);//bColRect
}
else
{
m_sprite->GetModuleRect(m_rect, m_nCrtModule, posX, posY);
}
}
else if (m_nCrtFrame >= 0)
{
m_sprite->GetFrameRect(m_rect, m_nCrtFrame, posX, posY, m_flags, 0, 0);//bColRect
}
}
return m_rect;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int* ASpriteInstance::GetAbsoluteRect(bool bColRect)
{//SangHo - 원점기준의 좌,상,너비,높이 4개인자값을 리턴한다.
if (m_rect == NULL)
{
m_rect = GL_NEW int[4];
}
if (m_sprite != NULL)
{
/*if (bColRect && m_sprite->_frames_coll == NULL)
{
return NULL;
}*/
if (m_nCrtAnimation >= 0)
{
m_sprite->GetAFrameRect(m_rect, m_nCrtModule, m_nCrtFrame, 0, 0, m_flags, 0, 0);//bColRect
}
else if (m_nCrtModule >= 0)
{
m_sprite->GetModuleRect(m_rect, m_nCrtModule, 0, 0);
}
else if (m_nCrtFrame >= 0)
{
m_sprite->GetFrameRect(m_rect, m_nCrtFrame, 0, 0, m_flags, 0, 0);//bColRect
}
}
return m_rect;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int* ASpriteInstance::GetFModuleRect(int module,int posX, int posY, int flags, int hx, int hy)
{//SangHo - 현재 인스턴스가 그리고있는 Animation Frame 의 module번째 모듈의 좌표를 리턴한다(원점기준, 하이퍼 프레임은 해당되지않음)
if (m_rect == NULL)
{
m_rect = GL_NEW int[4];
}
//System.out.println("m_nCrtFrame::::::::::"+m_nCrtFrame);
//System.out.println("GetAnimFrame(m_nCrtModule,m_nCrtFrame):"+m_sprite->GetAnimFrame(m_nCrtModule,m_nCrtFrame));
if(m_sprite != NULL)
{
m_sprite->GetFModuleRect(m_rect,GetAnimFrame(),module,posX,posY,flags,hx,hy);
return m_rect;
}
return NULL;
}
int ASpriteInstance::GetAnimFrame()
{//SangHo - 현재 인스턴스가 그리고있는 Animation Frame 의 고유Index 값을 리턴한다(Ani off값 아님)
if(m_sprite != NULL)
{
return m_sprite->GetAnimFrame(m_nCrtModule,m_nCrtFrame);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool ASpriteInstance::IsRectCrossing(int rect1[], int rect2[])
{//SangHo - 두 면적이 충돌하였는지를 판단한다
if (rect1[0] > rect2[2]) return false;
if (rect1[2] < rect2[0]) return false;
if (rect1[1] > rect2[3]) return false;
if (rect1[3] < rect2[1]) return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool ASpriteInstance::IsPointInRect(int x, int y, int rect[])
{//SangHo - 한지점이 면적 안에 들어가있는지 아닌지를 체크한다
if (x < rect[0]) return false;
if (x > rect[2]) return false;
if (y < rect[1]) return false;
if (y > rect[3]) return false;
return true;
}
bool ASpriteInstance::SetBlendCustom(bool blendCustom, bool overWrite, int Blend_Kind,int Blend_Percent){
//SangHo - 블랜드를 지정하자마자 그리는것이 아니라 List 에 넣은뒤 정렬후에 한꺼번에 그리기때문에 값을 저장할 필요성이 있음
s_Blend.blendCustom = blendCustom;
s_Blend.overWrite = overWrite;
s_Blend.Blend_Kind = Blend_Kind;
s_Blend.Blend_Percent = Blend_Percent;
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// static int ZOOM_IN_X(int x) { return (((x)*ZOOM_X)/ZOOM_X_DIV); }
// static int ZOOM_IN_Y(int y) { return (((y)*ZOOM_Y)/ZOOM_Y_DIV); }
// static int ZOOM_OUT_X(int x) { return (((x)*ZOOM_X_DIV)/ZOOM_X); }
// static int ZOOM_OUT_Y(int y) { return (((y)*ZOOM_Y_DIV)/ZOOM_Y); }
//static int ZOOM_IN_FIXED_X(int x) { return ((((x)>>FIXED_PRECISION)*ZOOM_X)/ZOOM_X_DIV); }
//static int ZOOM_IN_FIXED_Y(int y) { return ((((y)>>FIXED_PRECISION)*ZOOM_Y)/ZOOM_Y_DIV); }
// [Sinh.2007/02/22] optimize for Triplets
// static int ZOOM_OUT_FIXED_X(int x) { return ((((x)<<FIXED_PRECISION)*ZOOM_X_DIV)/ZOOM_X); }
// static int ZOOM_OUT_FIXED_Y(int y) { return ((((y)<<FIXED_PRECISION)*ZOOM_Y_DIV)/ZOOM_Y); }
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////▽폐소스 - SangHo/////////////////////////////////////////
///////////////////////////////////////////▽폐소스 - SangHo/////////////////////////////////////////
/*
int* ASpriteInstance::GetSpriteRect(int _m_posX, int _m_posY)
{//SangHo - _m_posX,_m_posY 을 기준점으로 가정된 좌,상,너비,높이 4개인자값을 리턴한다.
if (m_rect == NULL)
{
m_rect = GL_NEW int[4];
}
if (m_sprite != NULL)
{
if (m_nCrtAnimation >= 0)
m_sprite->GetAFrameRect(m_rect, m_nCrtModule, m_nCrtFrame, _m_posX, _m_posY, m_flags, 0, 0);
else if (m_nCrtModule >= 0)
m_sprite->GetModuleRect(m_rect, m_nCrtModule, _m_posX, _m_posY);
else if (m_nCrtFrame >= 0)
m_sprite->GetFrameRect(m_rect, m_nCrtFrame, _m_posX, _m_posY, m_flags, 0, 0);
//m_rect[1] -= m_posZ;
//m_rect[3] -= m_posZ;
return m_rect;
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::PaintSprite_NO_ZOOM(CGraphics* g)
{//SangHo - PaintSprite로 대체
if (m_sprite == NULL)
return;
int posX = m_posX,
posY = m_posY;
for (ASpriteInstance* o = m_parent; o != NULL; o = o->m_parent)
{
posX += o->m_posX;
posY += o->m_posY;
}
posX = ( posX >>FIXED_PRECISION ) + SV_X;
posY = ( posY >>FIXED_PRECISION ) + SV_Y;
// System.out.println("PaintSprite("+posX+", "+posY+")...");
m_sprite->SetCurrentPalette(m_pal);
if (m_nCrtAnimation >= 0)
m_sprite->PaintAFrame(g, m_nCrtModule, m_nCrtFrame, posX, posY, m_flags, 0, 0);
else if (m_nCrtModule >= 0) // m_nCrtModule --> module
m_sprite->PaintModule(g, m_nCrtModule, posX, posY, m_flags);
else if (m_nCrtFrame >= 0) // m_nCrtFrame --> frame
m_sprite->PaintFrame(g, m_nCrtFrame, posX, posY, m_flags, 0, 0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::ApplyAnimOff()//좌표에 가중치 계산을 하는부분 쓸모없어보임
{
// if (bASSERT) DBG.ASSERT(m_sprite != NULL);
m_posX -= m_posOffX;
m_posY -= m_posOffY;
//////////
// m_sprite->GetAFrameOffset(&m_posOffX, &m_posOffY);
int off = (m_sprite->_anims_af_start[m_nCrtModule] + m_nCrtFrame) * 5;
// m_posOffX = ZOOM_OUT_FIXED_X(m_sprite->_aframes[off+2] << FIXED_PRECISION);
m_posOffX = (m_sprite->_aframes[off+2] << FIXED_PRECISION) * ZOOM_X_DIV / ZOOM_X;
if ((m_flags & FLAG_FLIP_X) != 0) m_posOffX = -m_posOffX;
// m_posOffY = ZOOM_OUT_FIXED_Y(m_sprite->_aframes[off+3] << FIXED_PRECISION);
m_posOffY = (m_sprite->_aframes[off+3] << FIXED_PRECISION) * ZOOM_Y_DIV / ZOOM_Y;
if ((m_flags & FLAG_FLIP_Y) != 0) m_posOffY = -m_posOffY;
//////////
m_posX += m_posOffX;
m_posY += m_posOffY;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ASpriteInstance::OnScreenTest()
{//SangHo - 사용하지 않음
// _vis = 1 + 2 + 4 + 8;
int ox = 0, oy = 0;
for (ASpriteInstance* o = m_parent; o != NULL; o = o->m_parent)
{
ox += o->m_posX;
oy += o->m_posY;
}
int* rect = GetRect(false);
rect[0] += ox - (GV_W << FIXED_PRECISION);
rect[1] += oy - (GV_H << FIXED_PRECISION);
rect[2] += ox;
rect[3] += oy;
_vis = 0;
if (rect[0] < 0 && rect[2] >= 0 && rect[1] < 0 && rect[3] >= 0)
{
_vis = 1 + 2 + 4 + 8;
}
else
{
//...
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool ASpriteInstance::IsOnScreen(int style)
{//SangHo - 사용하지 않음
return ((_vis & style) != 0);
}
int ASpriteInstance::getAniFrameOffY(){
int off = (m_sprite->_anims_af_start[m_nCrtModule] + m_nCrtFrame) * 5;
int m_posOffY = (m_sprite->_aframes[off+3] << FIXED_PRECISION) * ZOOM_Y_DIV / ZOOM_Y;
if ((m_flags & FLAG_FLIP_Y) != 0) m_posOffY = -m_posOffY;
return m_posOffY;
}
*/ | [
"secret5374@hotmail.com"
] | secret5374@hotmail.com |
71b4405dbdf29de691ea97320366ba817f2124c7 | cdd60a2c8d2cf4008b56dfa8016406c593591c61 | /source/common/quic/core/frames/quic_blocked_frame.h | fda4554027ac3de3dc2852db9f1ab5133c7bf129 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | juvexp/envoy | 794aa204c8b9fafd922ddf28a23191819c438416 | e7e6b61ea97b751f2c1b77cf968679dd5cbd18fe | refs/heads/master | 2021-05-12T05:18:19.481585 | 2018-04-12T15:32:01 | 2018-04-12T20:19:23 | 117,185,284 | 0 | 0 | null | 2018-01-12T03:06:38 | 2018-01-12T03:06:37 | null | UTF-8 | C++ | false | false | 1,601 | h | // Copyright 2018 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.
#ifndef GFE_QUIC_CORE_FRAMES_QUIC_BLOCKED_FRAME_H_
#define GFE_QUIC_CORE_FRAMES_QUIC_BLOCKED_FRAME_H_
#include <ostream>
#include "common/quic/core/frames/quic_control_frame.h"
namespace gfe_quic {
// The BLOCKED frame is used to indicate to the remote endpoint that this
// endpoint believes itself to be flow-control blocked but otherwise ready to
// send data. The BLOCKED frame is purely advisory and optional.
// Based on SPDY's BLOCKED frame (undocumented as of 2014-01-28).
struct QUIC_EXPORT_PRIVATE QuicBlockedFrame : public QuicControlFrame {
QuicBlockedFrame();
QuicBlockedFrame(QuicControlFrameId control_frame_id, QuicStreamId stream_id);
friend QUIC_EXPORT_PRIVATE std::ostream& operator<<(
std::ostream& os,
const QuicBlockedFrame& b);
// The stream this frame applies to. 0 is a special case meaning the overall
// connection rather than a specific stream.
QuicStreamId stream_id;
};
} // namespace gfe_quic
#endif // GFE_QUIC_CORE_FRAMES_QUIC_BLOCKED_FRAME_H_
| [
"wub@google.com"
] | wub@google.com |
cfffd905fa157c33f9c74349f97b2c5be9313841 | 2953124cc090a3fb1d67111895d092992b2f496e | /8_1_2/Article.cpp | fb13ec5ac671a055a07a34a6b460d4fd46a10cb6 | [] | no_license | LukasH-1849700/OGP_Oef | eaf5b99f4e6ced4d496f711e487f66b27d420fba | fb4dc65a2b148b2101c316b75588141262ea7292 | refs/heads/master | 2022-04-14T16:34:12.665206 | 2020-03-10T09:52:49 | 2020-03-10T09:52:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 453 | cpp | #include "Article.h"
#include <string>
#include <iostream>
Article::Article(const std::string& name, const double& price) : m_name{name}, m_price{price}
{}
void Article::print() const
{
std::cout << "\nName: " << m_name
<< "\nPrice: " << m_price
<< '\n';
}
std::string Article::get_name() const
{
return m_name;
}
double Article::get_price() const
{
return m_price;
}
void Article::set_price(const double& price)
{
m_price = price;
}
| [
"lukas.hotterbeekx@student.uhasselt.be"
] | lukas.hotterbeekx@student.uhasselt.be |
5da3dd2595be784d770e2cdf797082a6e1183b7c | b54d7fb9cd70ae13b0bbba0169fdcccbe845c8ba | /c++11/c/Base.cpp | 43776180a54bbdfb4002278cb1bb00d3c7c3796e | [] | no_license | nxjm/C11 | fc10fabaf3274c19ca44a7b98ed0735e0364f6b5 | 2c0ccbeadfabc1cf1469b0594848b393333b919e | refs/heads/master | 2020-07-01T04:14:47.521994 | 2019-08-15T15:03:09 | 2019-08-15T15:03:09 | 201,045,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 207 | cpp | #include "Base.h"
using namespace std;
Base::Base(){
cout << "Base::Base()" << endl;
}
Base::~Base(){
cout << "Base::~Base()" << endl;
}
void Base::func1(){
cout << "Base::func1()" << endl;
}
| [
"aut456@163.com"
] | aut456@163.com |
6679c54956504df35cdd70947060540e0c32b512 | 4a544d6903abc37953e77235395baa64115cf144 | /libcamera/SecCameraHWInterface.cpp | 322753961287cc36a4d18c3e8806bc8959d0db8c | [
"Apache-2.0"
] | permissive | randomstuffpaul/insignal_hardware_samsung_slsi_exynos4 | d5068cdaf29f0eeb5638e6150ae4e50575ad0b67 | 9f576f58e54df58fdcb17501246671f64236bf6f | refs/heads/exynos-ics | 2021-01-18T03:16:29.772870 | 2012-12-12T02:20:13 | 2012-12-12T02:20:18 | 85,834,830 | 0 | 0 | null | 2017-03-22T14:03:58 | 2017-03-22T14:03:57 | null | UTF-8 | C++ | false | false | 116,979 | cpp | /*
**
** Copyright 2008, The Android Open Source Project
** Copyright 2010, Samsung Electronics Co. LTD
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "CameraHardwareSec"
#include <utils/Log.h>
#include "SecCameraHWInterface.h"
#include <utils/threads.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <camera/Camera.h>
#include <media/stagefright/MetadataBufferType.h>
#define VIDEO_COMMENT_MARKER_H 0xFFBE
#define VIDEO_COMMENT_MARKER_L 0xFFBF
#define VIDEO_COMMENT_MARKER_LENGTH 4
#define JPEG_EOI_MARKER 0xFFD9
#define HIBYTE(x) (((x) >> 8) & 0xFF)
#define LOBYTE(x) ((x) & 0xFF)
#define BACK_CAMERA_AUTO_FOCUS_DISTANCES_STR "0.10,1.20,Infinity"
#define BACK_CAMERA_MACRO_FOCUS_DISTANCES_STR "0.10,0.20,Infinity"
#define BACK_CAMERA_INFINITY_FOCUS_DISTANCES_STR "0.10,1.20,Infinity"
#define FRONT_CAMERA_FOCUS_DISTANCES_STR "0.20,0.25,Infinity"
//#define USE_EGL
// This hack does two things:
// -- it sets preview to NV21 (YUV420SP)
// -- it sets gralloc to YV12
//
// The reason being: the samsung encoder understands only yuv420sp, and gralloc
// does yv12 and rgb565. So what we do is we break up the interleaved UV in
// separate V and U planes, which makes preview look good, and enabled the
// encoder as well.
//
// FIXME: Samsung needs to enable support for proper yv12 coming out of the
// camera, and to fix their video encoder to work with yv12.
// FIXME: It also seems like either Samsung's YUV420SP (NV21) or img's YV12 has
// the color planes switched. We need to figure which side is doing it
// wrong and have the respective party fix it.
namespace android {
struct addrs {
uint32_t type; // make sure that this is 4 byte.
unsigned int addr_y;
unsigned int addr_cbcr;
unsigned int buf_index;
unsigned int reserved;
};
struct addrs_cap {
unsigned int addr_y;
unsigned int width;
unsigned int height;
};
static const int INITIAL_SKIP_FRAME = 3;
static const int EFFECT_SKIP_FRAME = 1;
gralloc_module_t const* CameraHardwareSec::mGrallocHal;
CameraHardwareSec::CameraHardwareSec(int cameraId, camera_device_t *dev)
:
mCaptureInProgress(false),
mParameters(),
mFrameSizeDelta(0),
mCameraSensorName(NULL),
mUseInternalISP(false),
mSkipFrame(0),
mNotifyCb(0),
mDataCb(0),
mDataCbTimestamp(0),
mCallbackCookie(0),
mMsgEnabled(CAMERA_MSG_RAW_IMAGE),
mRecordRunning(false),
mPostViewWidth(0),
mPostViewHeight(0),
mPostViewSize(0),
mCapIndex(0),
mRecordHint(false),
mTouched(0),
mHalDevice(dev)
{
LOGV("%s :", __func__);
memset(&mCapBuffer, 0, sizeof(struct SecBuffer));
int ret = 0;
mPreviewWindow = NULL;
mSecCamera = SecCamera::createInstance();
mRawHeap = NULL;
mPreviewHeap = NULL;
for(int i = 0; i < BUFFER_COUNT_FOR_ARRAY; i++)
mRecordHeap[i] = NULL;
if (!mGrallocHal) {
ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, (const hw_module_t **)&mGrallocHal);
if (ret)
LOGE("ERR(%s):Fail on loading gralloc HAL", __func__);
}
ret = mSecCamera->CreateCamera(cameraId);
if (ret < 0) {
LOGE("ERR(%s):Fail on mSecCamera init", __func__);
mSecCamera->DestroyCamera();
}
initDefaultParameters(cameraId);
mExitAutoFocusThread = false;
mExitPreviewThread = false;
/* whether the PreviewThread is active in preview or stopped. we
* create the thread but it is initially in stopped state.
*/
mPreviewRunning = false;
mPreviewStartDeferred = false;
mPreviewThread = new PreviewThread(this);
mAutoFocusThread = new AutoFocusThread(this);
mPictureThread = new PictureThread(this);
#ifdef IS_FW_DEBUG
if (mUseInternalISP) {
mPrevOffset = 0;
mCurrOffset = 0;
mPrevWp = 0;
mCurrWp = 0;
mDebugVaddr = 0;
mDebugThread = new DebugThread(this);
mDebugThread->run("debugThread", PRIORITY_DEFAULT);
}
#endif
}
int CameraHardwareSec::getCameraId() const
{
return mSecCamera->getCameraId();
}
void CameraHardwareSec::initDefaultParameters(int cameraId)
{
if (mSecCamera == NULL) {
LOGE("ERR(%s):mSecCamera object is NULL", __func__);
return;
}
CameraParameters p;
CameraParameters ip;
mCameraSensorName = mSecCamera->getCameraSensorName();
if (mCameraSensorName == NULL) {
LOGE("ERR(%s):mCameraSensorName is NULL", __func__);
return;
}
LOGV("CameraSensorName: %s", mCameraSensorName);
int preview_max_width = 0;
int preview_max_height = 0;
int snapshot_max_width = 0;
int snapshot_max_height = 0;
mCameraID = cameraId;
mUseInternalISP = mSecCamera->getUseInternalISP();
if (cameraId == SecCamera::CAMERA_ID_BACK) {
if (mUseInternalISP) {
//3H2
p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES,
"720x480,640x384,640x360,640x480,320x240,528x432,176x144");
p.set(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES,
"3248x2436,3216x2144,3200x1920,3072x1728,2592x1944,1920x1080,1440x1080,1280x720,1232x1008,800x480,720x480,640x480");
p.set(CameraParameters::KEY_SUPPORTED_VIDEO_SIZES,
"1920x1080,1280x720,640x480,176x144");
} else {
//M5MO
p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES,
"3264x2448,1920x1080,1280x720,800x480,720x480,640x480,320x240,528x432,176x144");
p.set(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES,
"3264x2448,3264x1968,2048x1536,2048x1232,800x480,640x480");
}
} else {
if (mUseInternalISP) {
//6A3
p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES,
"640x480,640x360,480x480,352x288,320x240,176x144");
p.set(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES,
"1392x1392,1280x960,1280x720,880x720,640x480");
p.set(CameraParameters::KEY_SUPPORTED_VIDEO_SIZES,
"1280x720,640x480,176x144");
}
}
p.getSupportedPreviewSizes(mSupportedPreviewSizes);
String8 parameterString;
// If these fail, then we are using an invalid cameraId and we'll leave the
// sizes at zero to catch the error.
if (mSecCamera->getPreviewMaxSize(&preview_max_width,
&preview_max_height) < 0)
LOGE("getPreviewMaxSize fail (%d / %d)",
preview_max_width, preview_max_height);
if (mSecCamera->getSnapshotMaxSize(&snapshot_max_width,
&snapshot_max_height) < 0)
LOGE("getSnapshotMaxSize fail (%d / %d)",
snapshot_max_width, snapshot_max_height);
parameterString = CameraParameters::PIXEL_FORMAT_YUV420P;
parameterString.append(",");
parameterString.append(CameraParameters::PIXEL_FORMAT_YUV420SP);
p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FORMATS, parameterString);
p.setPreviewFormat(CameraParameters::PIXEL_FORMAT_YUV420P);
mFrameSizeDelta = 16;
p.set(CameraParameters::KEY_VIDEO_FRAME_FORMAT, CameraParameters::PIXEL_FORMAT_YUV420SP);
p.setPreviewSize(preview_max_width, preview_max_height);
p.setPictureFormat(CameraParameters::PIXEL_FORMAT_JPEG);
p.setPictureSize(snapshot_max_width, snapshot_max_height);
p.set(CameraParameters::KEY_JPEG_QUALITY, "100"); // maximum quality
p.set(CameraParameters::KEY_SUPPORTED_PICTURE_FORMATS,
CameraParameters::PIXEL_FORMAT_JPEG);
p.set(CameraParameters::KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO, "1280x720");
#ifdef USE_FACE_DETECTION
if (mUseInternalISP) {
p.set(CameraParameters::KEY_MAX_NUM_DETECTED_FACES_HW, "5");
} else {
p.set(CameraParameters::KEY_MAX_NUM_DETECTED_FACES_HW, "0");
}
#endif
if (cameraId == SecCamera::CAMERA_ID_BACK) {
parameterString = CameraParameters::FOCUS_MODE_AUTO;
/* TODO : sensor will be support this mode */
//parameterString.append(",");
//parameterString.append(CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO);
if (mUseInternalISP) {
parameterString.append(",");
parameterString.append(CameraParameters::FOCUS_MODE_INFINITY);
parameterString.append(",");
parameterString.append(CameraParameters::FOCUS_MODE_MACRO);
parameterString.append(",");
parameterString.append(CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE);
}
p.set(CameraParameters::KEY_SUPPORTED_FOCUS_MODES,
parameterString.string());
p.set(CameraParameters::KEY_FOCUS_MODE,
CameraParameters::FOCUS_MODE_AUTO);
p.set(CameraParameters::KEY_FOCUS_DISTANCES,
BACK_CAMERA_AUTO_FOCUS_DISTANCES_STR);
#ifdef USE_TOUCH_AF
if (mUseInternalISP)
p.set(CameraParameters::KEY_MAX_NUM_FOCUS_AREAS, "1");
#endif
p.set(CameraParameters::KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES,
"320x240,0x0");
p.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, "320");
p.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, "240");
p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FRAME_RATES, "7,15,30");
p.setPreviewFrameRate(30);
} else {
p.set(CameraParameters::KEY_FOCUS_MODE, NULL);
p.set(CameraParameters::KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES,
"160x120,0x0");
p.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, "160");
p.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, "120");
p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FRAME_RATES,
"7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,50,60");
p.setPreviewFrameRate(30);
}
parameterString = CameraParameters::EFFECT_NONE;
parameterString.append(",");
parameterString.append(CameraParameters::EFFECT_MONO);
parameterString.append(",");
parameterString.append(CameraParameters::EFFECT_NEGATIVE);
parameterString.append(",");
parameterString.append(CameraParameters::EFFECT_SEPIA);
p.set(CameraParameters::KEY_SUPPORTED_EFFECTS, parameterString.string());
if (cameraId == SecCamera::CAMERA_ID_BACK) {
parameterString = CameraParameters::FLASH_MODE_ON;
parameterString.append(",");
parameterString.append(CameraParameters::FLASH_MODE_OFF);
parameterString.append(",");
parameterString.append(CameraParameters::FLASH_MODE_AUTO);
parameterString.append(",");
parameterString.append(CameraParameters::FLASH_MODE_TORCH);
p.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES,
parameterString.string());
p.set(CameraParameters::KEY_FLASH_MODE,
CameraParameters::FLASH_MODE_OFF);
/* we have two ranges, 4-30fps for night mode and
* 15-30fps for all others
*/
p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, "(15000,30000)");
p.set(CameraParameters::KEY_PREVIEW_FPS_RANGE, "15000,30000");
p.set(CameraParameters::KEY_FOCAL_LENGTH, "3.43");
} else {
p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, "(7500,30000)");
p.set(CameraParameters::KEY_PREVIEW_FPS_RANGE, "7500,30000");
p.set(CameraParameters::KEY_FOCAL_LENGTH, "0.9");
}
parameterString = CameraParameters::SCENE_MODE_AUTO;
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_PORTRAIT);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_LANDSCAPE);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_BEACH);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_SNOW);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_FIREWORKS);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_SPORTS);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_PARTY);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_CANDLELIGHT);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_NIGHT);
parameterString.append(",");
parameterString.append(CameraParameters::SCENE_MODE_SUNSET);
p.set(CameraParameters::KEY_SUPPORTED_SCENE_MODES,
parameterString.string());
p.set(CameraParameters::KEY_SCENE_MODE,
CameraParameters::SCENE_MODE_AUTO);
parameterString = CameraParameters::WHITE_BALANCE_AUTO;
parameterString.append(",");
parameterString.append(CameraParameters::WHITE_BALANCE_INCANDESCENT);
parameterString.append(",");
parameterString.append(CameraParameters::WHITE_BALANCE_FLUORESCENT);
parameterString.append(",");
parameterString.append(CameraParameters::WHITE_BALANCE_DAYLIGHT);
parameterString.append(",");
parameterString.append(CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT);
p.set(CameraParameters::KEY_SUPPORTED_WHITE_BALANCE,
parameterString.string());
p.set(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY, "100");
p.set(CameraParameters::KEY_ROTATION, 0);
p.set(CameraParameters::KEY_WHITE_BALANCE, CameraParameters::WHITE_BALANCE_AUTO);
p.set(CameraParameters::KEY_EFFECT, CameraParameters::EFFECT_NONE);
p.set("contrast", 0);
p.set("iso", "auto");
p.set("metering", "center");
p.set("wdr", 0);
ip.set("chk_dataline", 0);
if (cameraId == SecCamera::CAMERA_ID_FRONT) {
ip.set("vtmode", 0);
ip.set("blur", 0);
}
p.set(CameraParameters::KEY_HORIZONTAL_VIEW_ANGLE, "51.2");
p.set(CameraParameters::KEY_VERTICAL_VIEW_ANGLE, "39.4");
p.set(CameraParameters::KEY_EXPOSURE_COMPENSATION, "0");
p.set(CameraParameters::KEY_MAX_EXPOSURE_COMPENSATION, "4");
p.set(CameraParameters::KEY_MIN_EXPOSURE_COMPENSATION, "-4");
p.set(CameraParameters::KEY_EXPOSURE_COMPENSATION_STEP, "1");
p.set("brightness", 0);
p.set("brightness-max", 2);
p.set("brightness-min", -2);
p.set("saturation", 0);
p.set("saturation-max", 2);
p.set("saturation-min", -2);
p.set("sharpness", 0);
p.set("sharpness-max", 2);
p.set("sharpness-min", -2);
p.set("hue", 0);
p.set("hue-max", 2);
p.set("hue-min", -2);
parameterString = CameraParameters::ANTIBANDING_AUTO;
parameterString.append(",");
parameterString.append(CameraParameters::ANTIBANDING_50HZ);
parameterString.append(",");
parameterString.append(CameraParameters::ANTIBANDING_60HZ);
parameterString.append(",");
parameterString.append(CameraParameters::ANTIBANDING_OFF);
p.set(CameraParameters::KEY_SUPPORTED_ANTIBANDING,
parameterString.string());
p.set(CameraParameters::KEY_ANTIBANDING, CameraParameters::ANTIBANDING_OFF);
if (mUseInternalISP) {
p.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK_SUPPORTED, "true");
p.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK, "false");
}
if (mUseInternalISP) {
p.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED, "true");
p.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, "false");
}
p.set(CameraParameters::KEY_RECORDING_HINT, "false");
#ifdef VIDEO_SNAPSHOT
if (mUseInternalISP)
p.set(CameraParameters::KEY_VIDEO_SNAPSHOT_SUPPORTED, "true");
#endif
if (!mUseInternalISP) {
p.set(CameraParameters::KEY_ZOOM_SUPPORTED, "true");
p.set(CameraParameters::KEY_MAX_ZOOM, ZOOM_LEVEL_MAX - 1);
p.set(CameraParameters::KEY_ZOOM_RATIOS, "31,4.0");
}
mPreviewRunning = false;
mParameters = p;
mInternalParameters = ip;
/* make sure mSecCamera has all the settings we do. applications
* aren't required to call setParameters themselves (only if they
* want to change something.
*/
setParameters(p);
}
CameraHardwareSec::~CameraHardwareSec()
{
LOGV("%s", __func__);
mSecCamera->DestroyCamera();
}
status_t CameraHardwareSec::setPreviewWindow(preview_stream_ops *w)
{
int min_bufs;
mPreviewWindow = w;
LOGV("%s: mPreviewWindow %p", __func__, mPreviewWindow);
if (!w) {
LOGE("preview window is NULL!");
return OK;
}
mPreviewLock.lock();
if (mPreviewRunning && !mPreviewStartDeferred) {
LOGI("stop preview (window change)");
stopPreviewInternal();
}
if (w->get_min_undequeued_buffer_count(w, &min_bufs)) {
LOGE("%s: could not retrieve min undequeued buffer count", __func__);
return INVALID_OPERATION;
}
if (min_bufs >= BUFFER_COUNT_FOR_GRALLOC) {
LOGE("%s: min undequeued buffer count %d is too high (expecting at most %d)", __func__,
min_bufs, BUFFER_COUNT_FOR_GRALLOC - 1);
}
LOGV("%s: setting buffer count to %d", __func__, BUFFER_COUNT_FOR_GRALLOC);
if (w->set_buffer_count(w, BUFFER_COUNT_FOR_GRALLOC)) {
LOGE("%s: could not set buffer count", __func__);
return INVALID_OPERATION;
}
int preview_width;
int preview_height;
mParameters.getPreviewSize(&preview_width, &preview_height);
int hal_pixel_format;
const char *str_preview_format = mParameters.getPreviewFormat();
LOGV("%s: preview format %s", __func__, str_preview_format);
mFrameSizeDelta = 16;
hal_pixel_format = HAL_PIXEL_FORMAT_YV12; // default
if (!strcmp(str_preview_format,
CameraParameters::PIXEL_FORMAT_RGB565)) {
hal_pixel_format = HAL_PIXEL_FORMAT_RGB_565;
mFrameSizeDelta = 0;
} else if (!strcmp(str_preview_format,
CameraParameters::PIXEL_FORMAT_RGBA8888)) {
hal_pixel_format = HAL_PIXEL_FORMAT_RGBA_8888;
mFrameSizeDelta = 0;
} else if (!strcmp(str_preview_format,
CameraParameters::PIXEL_FORMAT_YUV420SP)) {
hal_pixel_format = HAL_PIXEL_FORMAT_YCrCb_420_SP;
} else if (!strcmp(str_preview_format,
CameraParameters::PIXEL_FORMAT_YUV420P))
hal_pixel_format = HAL_PIXEL_FORMAT_YV12; // HACK
#ifdef USE_EGL
if (w->set_usage(w, GRALLOC_USAGE_SW_WRITE_OFTEN)) {
LOGE("%s: could not set usage on gralloc buffer", __func__);
return INVALID_OPERATION;
}
#else
if (w->set_usage(w, GRALLOC_USAGE_SW_WRITE_OFTEN
| GRALLOC_USAGE_HW_FIMC1 | GRALLOC_USAGE_HWC_HWOVERLAY)) {
LOGE("%s: could not set usage on gralloc buffer", __func__);
return INVALID_OPERATION;
}
#endif
if (w->set_buffers_geometry(w,
preview_width, preview_height,
hal_pixel_format)) {
LOGE("%s: could not set buffers geometry to %s",
__func__, str_preview_format);
return INVALID_OPERATION;
}
if (mPreviewRunning && mPreviewStartDeferred) {
LOGV("start/resume preview");
status_t ret = startPreviewInternal();
if (ret == OK) {
mPreviewStartDeferred = false;
mPreviewCondition.signal();
}
}
mPreviewLock.unlock();
return OK;
}
void CameraHardwareSec::setCallbacks(camera_notify_callback notify_cb,
camera_data_callback data_cb,
camera_data_timestamp_callback data_cb_timestamp,
camera_request_memory get_memory,
void *user)
{
mNotifyCb = notify_cb;
mDataCb = data_cb;
mDataCbTimestamp = data_cb_timestamp;
mGetMemoryCb = get_memory;
mCallbackCookie = user;
}
void CameraHardwareSec::enableMsgType(int32_t msgType)
{
LOGV("%s : msgType = 0x%x, mMsgEnabled before = 0x%x",
__func__, msgType, mMsgEnabled);
mMsgEnabled |= msgType;
mPreviewLock.lock();
if ((msgType & (CAMERA_MSG_PREVIEW_FRAME | CAMERA_MSG_VIDEO_FRAME)) &&
mPreviewRunning && mPreviewStartDeferred) {
LOGV("%s: starting deferred preview", __func__);
if (startPreviewInternal() == OK) {
mPreviewStartDeferred = false;
mPreviewCondition.signal();
}
}
mPreviewLock.unlock();
LOGV("%s : mMsgEnabled = 0x%x", __func__, mMsgEnabled);
}
void CameraHardwareSec::disableMsgType(int32_t msgType)
{
LOGV("%s : msgType = 0x%x, mMsgEnabled before = 0x%x",
__func__, msgType, mMsgEnabled);
mMsgEnabled &= ~msgType;
LOGV("%s : mMsgEnabled = 0x%x", __func__, mMsgEnabled);
}
bool CameraHardwareSec::msgTypeEnabled(int32_t msgType)
{
return (mMsgEnabled & msgType);
}
void CameraHardwareSec::setSkipFrame(int frame)
{
Mutex::Autolock lock(mSkipFrameLock);
if (frame < mSkipFrame)
return;
mSkipFrame = frame;
}
int CameraHardwareSec::previewThreadWrapper()
{
LOGI("%s: starting", __func__);
while (1) {
mPreviewLock.lock();
while (!mPreviewRunning) {
LOGI("%s: calling mSecCamera->stopPreview() and waiting", __func__);
mSecCamera->stopPreview();
/* signal that we're stopping */
mPreviewStoppedCondition.signal();
mPreviewCondition.wait(mPreviewLock);
LOGI("%s: return from wait", __func__);
}
mPreviewLock.unlock();
if (mExitPreviewThread) {
LOGI("%s: exiting", __func__);
mSecCamera->stopPreview();
return 0;
}
previewThread();
}
}
int CameraHardwareSec::previewThread()
{
int index;
nsecs_t timestamp;
SecBuffer previewAddr, recordAddr;
static int numArray = 0;
void *virAddr[3];
camera_frame_metadata_t fdmeta;
camera_face_t caface[5];
struct addrs *addrs;
fdmeta.faces = caface;
index = mSecCamera->getPreview(&fdmeta);
mFaceData = &fdmeta;
if (index < 0) {
LOGE("ERR(%s):Fail on SecCamera->getPreview()", __func__);
return UNKNOWN_ERROR;
}
#ifdef ZERO_SHUTTER_LAG
if (mUseInternalISP && !mRecordHint) {
mCapIndex = mSecCamera->getSnapshot();
if (mCapIndex >= 0) {
if (mSecCamera->setSnapshotFrame(mCapIndex) < 0) {
LOGE("%s: Fail qbuf, index(%d)", __func__, mCapIndex);
return INVALID_OPERATION;
}
}
}
#endif
mSkipFrameLock.lock();
if (mSkipFrame > 0) {
mSkipFrame--;
mSkipFrameLock.unlock();
LOGV("%s: index %d skipping frame", __func__, index);
if (mSecCamera->setPreviewFrame(index) < 0) {
LOGE("%s: Could not qbuff[%d]!!", __func__, index);
return UNKNOWN_ERROR;
}
return NO_ERROR;
}
mSkipFrameLock.unlock();
timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
int width, height, frame_size, offset;
mSecCamera->getPreviewSize(&width, &height, &frame_size);
offset = frame_size * index;
if (mPreviewWindow && mGrallocHal && mPreviewRunning) {
if (0 != mPreviewWindow->dequeue_buffer(mPreviewWindow, &mBufferHandle[numArray], &mStride[numArray])) {
LOGE("%s: Could not dequeue gralloc buffer[%d]!!", __func__, numArray);
goto callbacks;
}
if (!mGrallocHal->lock(mGrallocHal,
*mBufferHandle[numArray],
GRALLOC_USAGE_SW_WRITE_OFTEN | GRALLOC_USAGE_YUV_ADDR,
0, 0, width, height, virAddr)) {
char *frame = ((char *)mPreviewHeap->data) + offset;
int total = frame_size + mFrameSizeDelta;
int h = 0;
char *src = frame;
/* TODO : Need to fix size of planes for supported color fmt.
Currnetly we support only YV12(3 plane) and NV21(2 plane)*/
// Y
memcpy(virAddr[0],src, width * height);
src += width * height;
if (mPreviewFmtPlane == PREVIEW_FMT_2_PLANE) {
memcpy(virAddr[1], src, width * height / 2);
} else if (mPreviewFmtPlane == PREVIEW_FMT_3_PLANE) {
// U
memcpy(virAddr[1], src, width * height / 4);
src += width * height / 4;
// V
memcpy(virAddr[2], src, width * height / 4);
}
mGrallocHal->unlock(mGrallocHal, **mBufferHandle);
}
else
LOGE("%s: could not obtain gralloc buffer", __func__);
if (mSecCamera->setPreviewFrame(index) < 0) {
LOGE("%s: Fail qbuf, index(%d)", __func__, index);
goto callbacks;
}
index = 0;
if (0 != mPreviewWindow->enqueue_buffer(mPreviewWindow, *mBufferHandle)) {
LOGE("Could not enqueue gralloc buffer!");
goto callbacks;
}
}
callbacks:
// Notify the client of a new frame.
if (mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME && mPreviewRunning)
mDataCb(CAMERA_MSG_PREVIEW_FRAME, mPreviewHeap, index, NULL, mCallbackCookie);
#ifdef USE_FACE_DETECTION
if (mUseInternalISP && (mMsgEnabled & CAMERA_MSG_PREVIEW_METADATA) && mPreviewRunning)
mDataCb(CAMERA_MSG_PREVIEW_METADATA, mFaceDataHeap, 0, mFaceData, mCallbackCookie);
#endif
Mutex::Autolock lock(mRecordLock);
if (mRecordRunning == true) {
int recordingIndex = 0;
index = mSecCamera->getRecordFrame();
if (index < 0) {
LOGE("ERR(%s):Fail on SecCamera->getRecordFrame()", __func__);
return UNKNOWN_ERROR;
}
#ifdef VIDEO_SNAPSHOT
if (mUseInternalISP && mRecordHint) {
mCapIndex = mSecCamera->getSnapshot();
if (mSecCamera->setSnapshotFrame(mCapIndex) < 0) {
LOGE("%s: Fail qbuf, index(%d)", __func__, mCapIndex);
return INVALID_OPERATION;
}
}
#endif
recordingIndex = index;
mSecCamera->getRecordAddr(index, &recordAddr);
LOGV("record PhyY(0x%08x) phyC(0x%08x) ", recordAddr.phys.extP[0], recordAddr.phys.extP[1]);
if (recordAddr.phys.extP[0] == 0xffffffff || recordAddr.phys.extP[1] == 0xffffffff) {
LOGE("ERR(%s):Fail on SecCamera getRectPhyAddr Y addr = %0x C addr = %0x", __func__,
recordAddr.phys.extP[0], recordAddr.phys.extP[1]);
return UNKNOWN_ERROR;
}
addrs = (struct addrs *)(*mRecordHeap)->data;
addrs[index].type = kMetadataBufferTypeCameraSource;
addrs[index].addr_y = recordAddr.phys.extP[0];
addrs[index].addr_cbcr = recordAddr.phys.extP[1];
addrs[index].buf_index = index;
// Notify the client of a new frame.
if (mMsgEnabled & CAMERA_MSG_VIDEO_FRAME)
mDataCbTimestamp(timestamp, CAMERA_MSG_VIDEO_FRAME,
mRecordHeap[numArray], recordingIndex, mCallbackCookie);
else
mSecCamera->releaseRecordFrame(index);
}
return NO_ERROR;
}
#ifdef IS_FW_DEBUG
bool CameraHardwareSec::debugThread()
{
sleep(20);
LOGD("++ Firmware debug message starting");
mCurrWp = mIs_debug_ctrl.write_point;
mCurrOffset = mCurrWp - FIMC_IS_FW_DEBUG_REGION_ADDR;
if (mCurrWp != mPrevWp) {
*(char *)(mDebugVaddr + mCurrOffset + 1) = '\0';
if ((mCurrWp - mPrevWp) > 0) {
LOGD("%s", mDebugVaddr + mPrevOffset);
} else {
*(char *)(mDebugVaddr + FIMC_IS_FW_DEBUG_REGION_SIZE - 1) = '\0';
LOGD("%s", mDebugVaddr + mPrevOffset);
LOGD("%s", mDebugVaddr);
}
}
mPrevWp = mIs_debug_ctrl.write_point;
mPrevOffset = mPrevWp - FIMC_IS_FW_DEBUG_REGION_ADDR;
LOGD("-- Firmware debug message stop");
return true;
}
#endif
status_t CameraHardwareSec::startPreview()
{
int ret = 0;
LOGV("%s :", __func__);
Mutex::Autolock lock(mStateLock);
if (mCaptureInProgress) {
LOGE("%s : capture in progress, not allowed", __func__);
return INVALID_OPERATION;
}
mPreviewLock.lock();
if (mPreviewRunning) {
// already running
LOGE("%s : preview thread already running", __func__);
mPreviewLock.unlock();
return INVALID_OPERATION;
}
mPreviewRunning = true;
mPreviewStartDeferred = false;
if (!mPreviewWindow &&
!(mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME) &&
!(mMsgEnabled & CAMERA_MSG_VIDEO_FRAME)) {
LOGI("%s : deferring", __func__);
mPreviewStartDeferred = true;
mPreviewLock.unlock();
return NO_ERROR;
}
ret = startPreviewInternal();
if (ret == OK)
mPreviewCondition.signal();
mPreviewLock.unlock();
return ret;
}
status_t CameraHardwareSec::startPreviewInternal()
{
LOGV("%s", __func__);
int width, height, frame_size;
mSecCamera->getPreviewSize(&width, &height, &frame_size);
LOGD("mPreviewHeap(fd(%d), size(%d), width(%d), height(%d))",
mSecCamera->getCameraFd(SecCamera::PREVIEW), frame_size + mFrameSizeDelta, width, height);
int ret = mSecCamera->startPreview();
LOGV("%s : mSecCamera->startPreview() returned %d", __func__, ret);
if (ret < 0) {
LOGE("ERR(%s):Fail on mSecCamera->startPreview()", __func__);
return UNKNOWN_ERROR;
}
setSkipFrame(INITIAL_SKIP_FRAME);
if (mPreviewHeap) {
mPreviewHeap->release(mPreviewHeap);
mPreviewHeap = 0;
}
for(int i=0; i<BUFFER_COUNT_FOR_ARRAY; i++){
if (mRecordHeap[i] != NULL) {
mRecordHeap[i]->release(mRecordHeap[i]);
mRecordHeap[i] = 0;
}
}
mPreviewHeap = mGetMemoryCb((int)mSecCamera->getCameraFd(SecCamera::PREVIEW),
frame_size + mFrameSizeDelta,
MAX_BUFFERS,
0); // no cookie
mFaceDataHeap = mGetMemoryCb(-1, 1, 1, 0);
mSecCamera->getPostViewConfig(&mPostViewWidth, &mPostViewHeight, &mPostViewSize);
LOGV("CameraHardwareSec: mPostViewWidth = %d mPostViewHeight = %d mPostViewSize = %d",
mPostViewWidth,mPostViewHeight,mPostViewSize);
#ifdef IS_FW_DEBUG
if (mUseInternalISP) {
int ret = mSecCamera->getDebugAddr(&mDebugVaddr);
if (ret < 0) {
LOGE("ERR(%s):Fail on SecCamera->getDebugAddr()", __func__);
return UNKNOWN_ERROR;
}
mIs_debug_ctrl.write_point = *((unsigned int *)(mDebugVaddr + FIMC_IS_FW_DEBUG_REGION_SIZE));
mIs_debug_ctrl.assert_flag = *((unsigned int *)(mDebugVaddr + FIMC_IS_FW_DEBUG_REGION_SIZE + 4));
mIs_debug_ctrl.pabort_flag = *((unsigned int *)(mDebugVaddr + FIMC_IS_FW_DEBUG_REGION_SIZE + 8));
mIs_debug_ctrl.dabort_flag = *((unsigned int *)(mDebugVaddr + FIMC_IS_FW_DEBUG_REGION_SIZE + 12));
}
#endif
return NO_ERROR;
}
void CameraHardwareSec::stopPreviewInternal()
{
LOGV("%s :", __func__);
/* request that the preview thread stop. */
if (mPreviewRunning) {
mPreviewRunning = false;
if (!mPreviewStartDeferred) {
mPreviewCondition.signal();
/* wait until preview thread is stopped */
mPreviewStoppedCondition.wait(mPreviewLock);
}
else
LOGV("%s : preview running but deferred, doing nothing", __func__);
} else
LOGI("%s : preview not running, doing nothing", __func__);
}
void CameraHardwareSec::stopPreview()
{
LOGV("%s :", __func__);
/* request that the preview thread stop. */
mPreviewLock.lock();
stopPreviewInternal();
mPreviewLock.unlock();
}
bool CameraHardwareSec::previewEnabled()
{
Mutex::Autolock lock(mPreviewLock);
LOGV("%s : %d", __func__, mPreviewRunning);
return mPreviewRunning;
}
status_t CameraHardwareSec::startRecording()
{
LOGV("%s :", __func__);
Mutex::Autolock lock(mRecordLock);
for(int i = 0; i<BUFFER_COUNT_FOR_ARRAY; i++){
if (mRecordHeap[i] != NULL) {
mRecordHeap[i]->release(mRecordHeap[i]);
mRecordHeap[i] = 0;
}
mRecordHeap[i] = mGetMemoryCb(-1, sizeof(struct addrs), MAX_BUFFERS, NULL);
if (!mRecordHeap[i]) {
LOGE("ERR(%s): Record heap[%d] creation fail", __func__, i);
return UNKNOWN_ERROR;
}
}
LOGV("mRecordHeaps alloc done");
if (mRecordRunning == false) {
if (mSecCamera->startRecord(mRecordHint) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->startRecord()", __func__);
return UNKNOWN_ERROR;
}
mRecordRunning = true;
}
return NO_ERROR;
}
void CameraHardwareSec::stopRecording()
{
LOGV("%s :", __func__);
Mutex::Autolock lock(mRecordLock);
if (mRecordRunning == true) {
if (mSecCamera->stopRecord() < 0) {
LOGE("ERR(%s):Fail on mSecCamera->stopRecord()", __func__);
return;
}
mRecordRunning = false;
}
}
bool CameraHardwareSec::recordingEnabled()
{
LOGV("%s :", __func__);
LOGV("%s : %d", __func__, mPreviewRunning);
return mRecordRunning;
}
void CameraHardwareSec::releaseRecordingFrame(const void *opaque)
{
struct addrs *addrs = (struct addrs *)opaque;
mSecCamera->releaseRecordFrame(addrs->buf_index);
}
int CameraHardwareSec::autoFocusThread()
{
int count =0;
int af_status =0 ;
LOGV("%s : starting", __func__);
/* block until we're told to start. we don't want to use
* a restartable thread and requestExitAndWait() in cancelAutoFocus()
* because it would cause deadlock between our callbacks and the
* caller of cancelAutoFocus() which both want to grab the same lock
* in CameraServices layer.
*/
mFocusLock.lock();
/* check early exit request */
if (mExitAutoFocusThread) {
mFocusLock.unlock();
LOGV("%s : exiting on request0", __func__);
return NO_ERROR;
}
mFocusCondition.wait(mFocusLock);
/* check early exit request */
if (mExitAutoFocusThread) {
mFocusLock.unlock();
LOGV("%s : exiting on request1", __func__);
return NO_ERROR;
}
mFocusLock.unlock();
/* TODO : Currently only possible auto focus at BACK caemra
We need to modify to check that sensor can support auto focus */
if (mCameraID == SecCamera::CAMERA_ID_BACK) {
LOGV("%s : calling setAutoFocus", __func__);
if (mTouched == 0) {
if (mSecCamera->setAutofocus() < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setAutofocus()", __func__);
return UNKNOWN_ERROR;
}
} else {
if (mSecCamera->setTouchAF() < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setAutofocus()", __func__);
return UNKNOWN_ERROR;
}
}
}
/* TODO */
/* This is temperary implementation.
When camera support AF blocking mode, this code will be removed
Continous AutoFocus is not need to success */
const char *focusModeStr = mParameters.get(CameraParameters::KEY_FOCUS_MODE);
int isContinousAF = !strncmp(focusModeStr, CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO, 7);
if (mUseInternalISP && !isContinousAF) {
int i, err = -1;
for (i = 0; i < 400; i++) {
usleep(10000);
af_status = mSecCamera->getAutoFocusResult();
if ((af_status & 0x2)) {
err = 0;
break;
}
}
} else {
af_status = mSecCamera->getAutoFocusResult();
}
if (af_status == 0x01) {
LOGV("%s : AF Cancelled !!", __func__);
if (mMsgEnabled & CAMERA_MSG_FOCUS)
mNotifyCb(CAMERA_MSG_FOCUS, true, 0, mCallbackCookie);
} else if (af_status == 0x02) {
LOGV("%s : AF Success !!", __func__);
if (mMsgEnabled & CAMERA_MSG_FOCUS) {
/* CAMERA_MSG_FOCUS only takes a bool. true for
* finished and false for failure. cancel is still
* considered a true result.
*/
mNotifyCb(CAMERA_MSG_FOCUS, true, 0, mCallbackCookie);
}
} else {
LOGV("%s : AF Fail !!", __func__);
LOGV("%s : mMsgEnabled = 0x%x", __func__, mMsgEnabled);
if (mMsgEnabled & CAMERA_MSG_FOCUS)
mNotifyCb(CAMERA_MSG_FOCUS, false, 0, mCallbackCookie);
}
LOGV("%s : exiting with no error", __func__);
return NO_ERROR;
}
status_t CameraHardwareSec::autoFocus()
{
LOGV("%s :", __func__);
/* signal autoFocusThread to run once */
mFocusCondition.signal();
return NO_ERROR;
}
status_t CameraHardwareSec::cancelAutoFocus()
{
LOGV("%s :", __func__);
if (mSecCamera->cancelAutofocus() < 0) {
LOGE("ERR(%s):Fail on mSecCamera->cancelAutofocus()", __func__);
return UNKNOWN_ERROR;
}
return NO_ERROR;
}
int CameraHardwareSec::save_jpeg( unsigned char *real_jpeg, int jpeg_size)
{
FILE *yuv_fp = NULL;
char filename[100], *buffer = NULL;
/* file create/open, note to "wb" */
yuv_fp = fopen("/data/camera_dump.jpeg", "wb");
if (yuv_fp == NULL) {
LOGE("Save jpeg file open error");
return -1;
}
LOGV("[BestIQ] real_jpeg size ========> %d", jpeg_size);
buffer = (char *) malloc(jpeg_size);
if (buffer == NULL) {
LOGE("Save YUV] buffer alloc failed");
if (yuv_fp)
fclose(yuv_fp);
return -1;
}
memcpy(buffer, real_jpeg, jpeg_size);
fflush(stdout);
fwrite(buffer, 1, jpeg_size, yuv_fp);
fflush(yuv_fp);
if (yuv_fp)
fclose(yuv_fp);
if (buffer)
free(buffer);
return 0;
}
void CameraHardwareSec::save_postview(const char *fname, uint8_t *buf, uint32_t size)
{
int nw;
int cnt = 0;
uint32_t written = 0;
LOGD("opening file [%s]", fname);
int fd = open(fname, O_RDWR | O_CREAT);
if (fd < 0) {
LOGE("failed to create file [%s]: %s", fname, strerror(errno));
return;
}
LOGD("writing %d bytes to file [%s]", size, fname);
while (written < size) {
nw = ::write(fd, buf + written, size - written);
if (nw < 0) {
LOGE("failed to write to file %d [%s]: %s",written,fname, strerror(errno));
break;
}
written += nw;
cnt++;
}
LOGD("done writing %d bytes to file [%s] in %d passes",size, fname, cnt);
::close(fd);
}
bool CameraHardwareSec::scaleDownYuv422(char *srcBuf, uint32_t srcWidth, uint32_t srcHeight,
char *dstBuf, uint32_t dstWidth, uint32_t dstHeight)
{
int32_t step_x, step_y;
int32_t iXsrc, iXdst;
int32_t x, y, src_y_start_pos, dst_pos, src_pos;
if (dstWidth % 2 != 0 || dstHeight % 2 != 0) {
LOGE("scale_down_yuv422: invalid width, height for scaling");
return false;
}
step_x = srcWidth / dstWidth;
step_y = srcHeight / dstHeight;
dst_pos = 0;
for (uint32_t y = 0; y < dstHeight; y++) {
src_y_start_pos = (y * step_y * (srcWidth * 2));
for (uint32_t x = 0; x < dstWidth; x += 2) {
src_pos = src_y_start_pos + (x * (step_x * 2));
dstBuf[dst_pos++] = srcBuf[src_pos ];
dstBuf[dst_pos++] = srcBuf[src_pos + 1];
dstBuf[dst_pos++] = srcBuf[src_pos + 2];
dstBuf[dst_pos++] = srcBuf[src_pos + 3];
}
}
return true;
}
bool CameraHardwareSec::YUY2toNV21(void *srcBuf, void *dstBuf, uint32_t srcWidth, uint32_t srcHeight)
{
int32_t x, y, src_y_start_pos, dst_cbcr_pos, dst_pos, src_pos;
unsigned char *srcBufPointer = (unsigned char *)srcBuf;
unsigned char *dstBufPointer = (unsigned char *)dstBuf;
dst_pos = 0;
dst_cbcr_pos = srcWidth*srcHeight;
for (uint32_t y = 0; y < srcHeight; y++) {
src_y_start_pos = (y * (srcWidth * 2));
for (uint32_t x = 0; x < (srcWidth * 2); x += 2) {
src_pos = src_y_start_pos + x;
dstBufPointer[dst_pos++] = srcBufPointer[src_pos];
}
}
for (uint32_t y = 0; y < srcHeight; y += 2) {
src_y_start_pos = (y * (srcWidth * 2));
for (uint32_t x = 0; x < (srcWidth * 2); x += 4) {
src_pos = src_y_start_pos + x;
dstBufPointer[dst_cbcr_pos++] = srcBufPointer[src_pos + 3];
dstBufPointer[dst_cbcr_pos++] = srcBufPointer[src_pos + 1];
}
}
return true;
}
int CameraHardwareSec::pictureThread()
{
LOGV("%s :", __func__);
int jpeg_size = 0;
int ret = NO_ERROR;
unsigned char *jpeg_data = NULL;
int postview_offset = 0;
unsigned char *postview_data = NULL;
unsigned char *addr = NULL;
int mPostViewWidth, mPostViewHeight, mPostViewSize;
int mThumbWidth, mThumbHeight, mThumbSize;
int cap_width, cap_height, cap_frame_size;
int JpegImageSize = 0;
mSecCamera->getPostViewConfig(&mPostViewWidth, &mPostViewHeight, &mPostViewSize);
mSecCamera->getThumbnailConfig(&mThumbWidth, &mThumbHeight, &mThumbSize);
int postviewHeapSize = mPostViewSize;
if (!mRecordRunning)
mSecCamera->getSnapshotSize(&cap_width, &cap_height, &cap_frame_size);
else
mSecCamera->getVideosnapshotSize(&cap_width, &cap_height, &cap_frame_size);
int mJpegHeapSize;
if (!mUseInternalISP)
mJpegHeapSize = cap_frame_size * SecCamera::getJpegRatio();
else
mJpegHeapSize = cap_frame_size;
LOGV("[5B] mPostViewWidth = %d mPostViewHeight = %d\n",mPostViewWidth,mPostViewHeight);
camera_memory_t *JpegHeap = mGetMemoryCb(-1, mJpegHeapSize, 1, 0);
mThumbnailHeap = new MemoryHeapBase(mThumbSize);
if (mMsgEnabled & CAMERA_MSG_RAW_IMAGE) {
int picture_size, picture_width, picture_height;
mSecCamera->getSnapshotSize(&picture_width, &picture_height, &picture_size);
int picture_format = mSecCamera->getSnapshotPixelFormat();
unsigned int thumb_addr, phyAddr;
// Modified the shutter sound timing for Jpeg capture
if (!mUseInternalISP) {
mSecCamera->setSnapshotCmd();
if (mMsgEnabled & CAMERA_MSG_SHUTTER)
mNotifyCb(CAMERA_MSG_SHUTTER, 0, 0, mCallbackCookie);
jpeg_data = mSecCamera->getJpeg(&JpegImageSize, &mThumbSize, &thumb_addr, &phyAddr);
if (jpeg_data == NULL) {
LOGE("ERR(%s):Fail on SecCamera->getJpeg()", __func__);
ret = UNKNOWN_ERROR;
}
memcpy((unsigned char *)mThumbnailHeap->base(), (unsigned char *)thumb_addr, mThumbSize);
memcpy(JpegHeap->data, jpeg_data, JpegImageSize);
} else {
if (mMsgEnabled & CAMERA_MSG_SHUTTER)
mNotifyCb(CAMERA_MSG_SHUTTER, 0, 0, mCallbackCookie);
#ifdef ZERO_SHUTTER_LAG
mSecCamera->getCaptureAddr(mCapIndex, &mCapBuffer);
if (mCapBuffer.virt.extP[0] == NULL) {
LOGE("ERR(%s):Fail on SecCamera getCaptureAddr = %0x ",
__func__, mCapBuffer.virt.extP[0]);
return UNKNOWN_ERROR;
}
scaleDownYuv422((char *)mCapBuffer.virt.extP[0], cap_width, cap_height,
(char *)mThumbnailHeap->base(), mThumbWidth, mThumbHeight);
#endif
if (mSecCamera->getSnapshotAndJpeg(&mCapBuffer, mCapIndex,
(unsigned char*)JpegHeap->data, &JpegImageSize) < 0) {
mStateLock.lock();
mCaptureInProgress = false;
mStateLock.unlock();
JpegHeap->release(JpegHeap);
return UNKNOWN_ERROR;
}
LOGI("snapshotandjpeg done");
#ifdef ZERO_SHUTTER_LAG
if (!mRecordRunning)
stopPreview();
memset(&mCapBuffer, 0, sizeof(struct SecBuffer));
#else
scaleDownYuv422((char *)mCapBuffer.virt.extP[0], cap_width, cap_height,
(char *)mThumbnailHeap->base(), mThumbWidth, mThumbHeight);
#endif
}
}
int rawHeapSize = cap_frame_size;
LOGV("mRawHeap : MemoryHeapBase(previewHeapSize(%d))", rawHeapSize);
mRawHeap = mGetMemoryCb((int)mSecCamera->getCameraFd(SecCamera::PICTURE), rawHeapSize, 1, 0);
if (!mRawHeap)
LOGE("ERR(%s): Raw heap creation fail", __func__);
if (mMsgEnabled & CAMERA_MSG_RAW_IMAGE)
mDataCb(CAMERA_MSG_RAW_IMAGE, mRawHeap, 0, NULL, mCallbackCookie);
mStateLock.lock();
mCaptureInProgress = false;
mStateLock.unlock();
if (mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE) {
camera_memory_t *ExifHeap =
mGetMemoryCb(-1, EXIF_FILE_SIZE + mThumbSize, 1, 0);
int JpegExifSize = mSecCamera->getExif((unsigned char *)ExifHeap->data,
(unsigned char *)mThumbnailHeap->base(),
mThumbSize);
LOGV("JpegExifSize=%d", JpegExifSize);
if (JpegExifSize < 0) {
ret = UNKNOWN_ERROR;
goto out;
}
int mJpegHeapSize_out = JpegImageSize + JpegExifSize;
camera_memory_t *JpegHeap_out = mGetMemoryCb(-1, mJpegHeapSize_out, 1, 0);
unsigned char *ExifStart = (unsigned char *)JpegHeap_out->data + 2;
unsigned char *ImageStart = ExifStart + JpegExifSize;
memcpy(JpegHeap_out->data, JpegHeap->data, 2);
memcpy(ExifStart, ExifHeap->data, JpegExifSize);
memcpy(ImageStart, JpegHeap->data + 2, JpegImageSize - 2);
mDataCb(CAMERA_MSG_COMPRESSED_IMAGE, JpegHeap_out, 0, NULL, mCallbackCookie);
if (ExifHeap) {
ExifHeap->release(ExifHeap);
ExifHeap = 0;
}
if (JpegHeap_out) {
JpegHeap_out->release(JpegHeap_out);
JpegHeap_out = 0;
}
}
LOGV("%s : pictureThread end", __func__);
out:
if (JpegHeap) {
JpegHeap->release(JpegHeap);
JpegHeap = 0;
}
if (mRawHeap) {
mRawHeap->release(mRawHeap);
mRawHeap = 0;
}
if (!mUseInternalISP && !mRecordRunning)
mSecCamera->endSnapshot();
return ret;
}
status_t CameraHardwareSec::takePicture()
{
LOGV("%s :", __func__);
#ifdef ZERO_SHUTTER_LAG
if (!mUseInternalISP) {
stopPreview();
}
#else
stopPreview();
#endif
Mutex::Autolock lock(mStateLock);
if (mCaptureInProgress) {
LOGE("%s : capture already in progress", __func__);
return INVALID_OPERATION;
}
if (mPictureThread->run("CameraPictureThread", PRIORITY_DEFAULT) != NO_ERROR) {
LOGE("%s : couldn't run picture thread", __func__);
return INVALID_OPERATION;
}
mCaptureInProgress = true;
return NO_ERROR;
}
status_t CameraHardwareSec::cancelPicture()
{
LOGV("%s", __func__);
if (mPictureThread.get()) {
LOGV("%s: waiting for picture thread to exit", __func__);
mPictureThread->requestExitAndWait();
LOGV("%s: picture thread has exited", __func__);
}
return NO_ERROR;
}
bool CameraHardwareSec::CheckVideoStartMarker(unsigned char *pBuf)
{
if (!pBuf) {
LOGE("CheckVideoStartMarker() => pBuf is NULL");
return false;
}
if (HIBYTE(VIDEO_COMMENT_MARKER_H) == * pBuf && LOBYTE(VIDEO_COMMENT_MARKER_H) == *(pBuf + 1) &&
HIBYTE(VIDEO_COMMENT_MARKER_L) == *(pBuf + 2) && LOBYTE(VIDEO_COMMENT_MARKER_L) == *(pBuf + 3))
return true;
return false;
}
bool CameraHardwareSec::CheckEOIMarker(unsigned char *pBuf)
{
if (!pBuf) {
LOGE("CheckEOIMarker() => pBuf is NULL");
return false;
}
// EOI marker [FF D9]
if (HIBYTE(JPEG_EOI_MARKER) == *pBuf && LOBYTE(JPEG_EOI_MARKER) == *(pBuf + 1))
return true;
return false;
}
bool CameraHardwareSec::FindEOIMarkerInJPEG(unsigned char *pBuf, int dwBufSize, int *pnJPEGsize)
{
if (NULL == pBuf || 0 >= dwBufSize) {
LOGE("FindEOIMarkerInJPEG() => There is no contents.");
return false;
}
unsigned char *pBufEnd = pBuf + dwBufSize;
while (pBuf < pBufEnd) {
if (CheckEOIMarker(pBuf++))
return true;
(*pnJPEGsize)++;
}
return false;
}
bool CameraHardwareSec::SplitFrame(unsigned char *pFrame, int dwSize,
int dwJPEGLineLength, int dwVideoLineLength, int dwVideoHeight,
void *pJPEG, int *pdwJPEGSize,
void *pVideo, int *pdwVideoSize)
{
LOGV("===========SplitFrame Start==============");
if (NULL == pFrame || 0 >= dwSize) {
LOGE("There is no contents (pFrame=%p, dwSize=%d", pFrame, dwSize);
return false;
}
if (0 == dwJPEGLineLength || 0 == dwVideoLineLength) {
LOGE("There in no input information for decoding interleaved jpeg");
return false;
}
unsigned char *pSrc = pFrame;
unsigned char *pSrcEnd = pFrame + dwSize;
unsigned char *pJ = (unsigned char *)pJPEG;
int dwJSize = 0;
unsigned char *pV = (unsigned char *)pVideo;
int dwVSize = 0;
bool bRet = false;
bool isFinishJpeg = false;
while (pSrc < pSrcEnd) {
// Check video start marker
if (CheckVideoStartMarker(pSrc)) {
int copyLength;
if (pSrc + dwVideoLineLength <= pSrcEnd)
copyLength = dwVideoLineLength;
else
copyLength = pSrcEnd - pSrc - VIDEO_COMMENT_MARKER_LENGTH;
// Copy video data
if (pV) {
memcpy(pV, pSrc + VIDEO_COMMENT_MARKER_LENGTH, copyLength);
pV += copyLength;
dwVSize += copyLength;
}
pSrc += copyLength + VIDEO_COMMENT_MARKER_LENGTH;
} else {
// Copy pure JPEG data
int size = 0;
int dwCopyBufLen = dwJPEGLineLength <= pSrcEnd-pSrc ? dwJPEGLineLength : pSrcEnd - pSrc;
if (FindEOIMarkerInJPEG((unsigned char *)pSrc, dwCopyBufLen, &size)) {
isFinishJpeg = true;
size += 2; // to count EOF marker size
} else {
if ((dwCopyBufLen == 1) && (pJPEG < pJ)) {
unsigned char checkBuf[2] = { *(pJ - 1), *pSrc };
if (CheckEOIMarker(checkBuf))
isFinishJpeg = true;
}
size = dwCopyBufLen;
}
memcpy(pJ, pSrc, size);
dwJSize += size;
pJ += dwCopyBufLen;
pSrc += dwCopyBufLen;
}
if (isFinishJpeg)
break;
}
if (isFinishJpeg) {
bRet = true;
if (pdwJPEGSize)
*pdwJPEGSize = dwJSize;
if (pdwVideoSize)
*pdwVideoSize = dwVSize;
} else {
LOGE("DecodeInterleaveJPEG_WithOutDT() => Can not find EOI");
bRet = false;
if (pdwJPEGSize)
*pdwJPEGSize = 0;
if (pdwVideoSize)
*pdwVideoSize = 0;
}
LOGV("===========SplitFrame end==============");
return bRet;
}
int CameraHardwareSec::decodeInterleaveData(unsigned char *pInterleaveData,
int interleaveDataSize,
int yuvWidth,
int yuvHeight,
int *pJpegSize,
void *pJpegData,
void *pYuvData)
{
if (pInterleaveData == NULL)
return false;
bool ret = true;
unsigned int *interleave_ptr = (unsigned int *)pInterleaveData;
unsigned char *jpeg_ptr = (unsigned char *)pJpegData;
unsigned char *yuv_ptr = (unsigned char *)pYuvData;
unsigned char *p;
int jpeg_size = 0;
int yuv_size = 0;
int i = 0;
LOGV("decodeInterleaveData Start~~~");
while (i < interleaveDataSize) {
if ((*interleave_ptr == 0xFFFFFFFF) || (*interleave_ptr == 0x02FFFFFF) ||
(*interleave_ptr == 0xFF02FFFF)) {
// Padding Data
interleave_ptr++;
i += 4;
} else if ((*interleave_ptr & 0xFFFF) == 0x05FF) {
// Start-code of YUV Data
p = (unsigned char *)interleave_ptr;
p += 2;
i += 2;
// Extract YUV Data
if (pYuvData != NULL) {
memcpy(yuv_ptr, p, yuvWidth * 2);
yuv_ptr += yuvWidth * 2;
yuv_size += yuvWidth * 2;
}
p += yuvWidth * 2;
i += yuvWidth * 2;
// Check End-code of YUV Data
if ((*p == 0xFF) && (*(p + 1) == 0x06)) {
interleave_ptr = (unsigned int *)(p + 2);
i += 2;
} else {
ret = false;
break;
}
} else {
// Extract JPEG Data
if (pJpegData != NULL) {
memcpy(jpeg_ptr, interleave_ptr, 4);
jpeg_ptr += 4;
jpeg_size += 4;
}
interleave_ptr++;
i += 4;
}
}
if (ret) {
if (pJpegData != NULL) {
// Remove Padding after EOI
for (i = 0; i < 3; i++) {
if (*(--jpeg_ptr) != 0xFF) {
break;
}
jpeg_size--;
}
*pJpegSize = jpeg_size;
}
// Check YUV Data Size
if (pYuvData != NULL) {
if (yuv_size != (yuvWidth * yuvHeight * 2)) {
ret = false;
}
}
}
LOGV("decodeInterleaveData End~~~");
return ret;
}
status_t CameraHardwareSec::dump(int fd) const
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
const Vector<String16> args;
if (mSecCamera != 0) {
mSecCamera->dump(fd);
mParameters.dump(fd, args);
mInternalParameters.dump(fd, args);
snprintf(buffer, 255, " preview running(%s)\n", mPreviewRunning?"true": "false");
result.append(buffer);
} else
result.append("No camera client yet.\n");
write(fd, result.string(), result.size());
return NO_ERROR;
}
bool CameraHardwareSec::isSupportedPreviewSize(const int width,
const int height) const
{
unsigned int i;
for (i = 0; i < mSupportedPreviewSizes.size(); i++) {
if (mSupportedPreviewSizes[i].width == width &&
mSupportedPreviewSizes[i].height == height)
return true;
}
return false;
}
bool CameraHardwareSec::getVideosnapshotSize(int *width, int *height)
{
unsigned int i;
Vector<Size> pictureSizes, videoSizes;
int ratio = FRM_RATIO(*width, *height);
mParameters.getSupportedPictureSizes(pictureSizes);
mParameters.getSupportedVideoSizes(videoSizes);
for (i = 0; i < pictureSizes.size(); i++) {
if (FRM_RATIO(pictureSizes[i].width, pictureSizes[i].height) == ratio) {
if (mRecordHint) {
if (pictureSizes[i].width <= videoSizes[0].width) {
*width = pictureSizes[i].width;
*height = pictureSizes[i].height;
LOGV("%s(width(%d), height(%d))", __func__, *width, *height);
return true;
}
} else {
*width = pictureSizes[i].width;
*height = pictureSizes[i].height;
LOGV("%s(width(%d), height(%d))", __func__, *width, *height);
return true;
}
}
}
return false;
}
status_t CameraHardwareSec::setParameters(const CameraParameters& params)
{
LOGV("%s :", __func__);
status_t ret = NO_ERROR;
const char *new_record_hint_str = params.get(CameraParameters::KEY_RECORDING_HINT);
const char *curr_record_hint_str = mParameters.get(CameraParameters::KEY_RECORDING_HINT);
LOGV("new_record_hint_str: %s", new_record_hint_str);
if (new_record_hint_str) {
if (strncmp(new_record_hint_str, curr_record_hint_str, 5)) {
mRecordHint = !strncmp(new_record_hint_str, "true", 4);
if (mSecCamera->setMode(mRecordHint) < 0) {
LOGE("ERR(%s):fail on mSecCamera->setMode(%d)", __func__, mRecordHint);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_RECORDING_HINT, new_record_hint_str);
}
if (mUseInternalISP) {
if (mSecCamera->initSetParams() < 0) {
LOGE("ERR(%s):fail on mSecCamera->initSetParams()", __func__);
ret = UNKNOWN_ERROR;
}
}
}
}
/* if someone calls us while picture thread is running, it could screw
* up the sensor quite a bit so return error. we can't wait because
* that would cause deadlock with the callbacks
*/
mStateLock.lock();
if (mCaptureInProgress) {
mStateLock.unlock();
LOGE("%s : capture in progress, not allowed", __func__);
return UNKNOWN_ERROR;
}
mStateLock.unlock();
// preview size
int new_preview_width = 0;
int new_preview_height = 0;
int new_preview_format = 0;
params.getPreviewSize(&new_preview_width, &new_preview_height);
if (mUseInternalISP) {
int videosnapshot_width = new_preview_width;
int videosnapshot_height = new_preview_height;
if (!getVideosnapshotSize(&videosnapshot_width, &videosnapshot_height)) {
LOGE("ERR(%s):fail on getVideosnapshotSize(width(%d), height(%d))",
__func__, videosnapshot_width, videosnapshot_height);
ret = UNKNOWN_ERROR;
}
if (mSecCamera->setVideosnapshotSize(videosnapshot_width, videosnapshot_height) < 0) {
LOGE("ERR(%s):fail on mSecCamera->setVideosnapshotSize(width(%d), height(%d))",
__func__, videosnapshot_width, videosnapshot_height);
ret = UNKNOWN_ERROR;
}
}
const char *new_str_preview_format = params.getPreviewFormat();
LOGV("%s : new_preview_width x new_preview_height = %dx%d, format = %s",
__func__, new_preview_width, new_preview_height, new_str_preview_format);
if (0 < new_preview_width && 0 < new_preview_height &&
new_str_preview_format != NULL &&
isSupportedPreviewSize(new_preview_width, new_preview_height)) {
mFrameSizeDelta = 16;
if (!strcmp(new_str_preview_format,
CameraParameters::PIXEL_FORMAT_RGB565)) {
new_preview_format = V4L2_PIX_FMT_RGB565;
mFrameSizeDelta = 0;
}
else if (!strcmp(new_str_preview_format,
CameraParameters::PIXEL_FORMAT_RGBA8888)) {
new_preview_format = V4L2_PIX_FMT_RGB32;
mFrameSizeDelta = 0;
}
else if (!strcmp(new_str_preview_format,
CameraParameters::PIXEL_FORMAT_YUV420SP)) {
new_preview_format = V4L2_PIX_FMT_NV21;
mPreviewFmtPlane = PREVIEW_FMT_2_PLANE;
}
else if (!strcmp(new_str_preview_format,
CameraParameters::PIXEL_FORMAT_YUV420P)) {
new_preview_format = V4L2_PIX_FMT_YVU420;
mPreviewFmtPlane = PREVIEW_FMT_3_PLANE;
}
else if (!strcmp(new_str_preview_format, "yuv420sp_custom"))
new_preview_format = V4L2_PIX_FMT_NV12T;
else if (!strcmp(new_str_preview_format, "yuv422i"))
new_preview_format = V4L2_PIX_FMT_YUYV;
else if (!strcmp(new_str_preview_format, "yuv422p"))
new_preview_format = V4L2_PIX_FMT_YUV422P;
else
new_preview_format = V4L2_PIX_FMT_NV21; //for 3rd party
int current_preview_width, current_preview_height, current_frame_size;
mSecCamera->getPreviewSize(¤t_preview_width,
¤t_preview_height,
¤t_frame_size);
int current_pixel_format = mSecCamera->getPreviewPixelFormat();
if (current_preview_width != new_preview_width ||
current_preview_height != new_preview_height ||
current_pixel_format != new_preview_format) {
if (mSecCamera->setPreviewSize(new_preview_width, new_preview_height,
new_preview_format) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setPreviewSize(width(%d), height(%d), format(%d))",
__func__, new_preview_width, new_preview_height, new_preview_format);
ret = UNKNOWN_ERROR;
} else {
if (mPreviewWindow) {
if (mPreviewRunning && !mPreviewStartDeferred) {
LOGE("ERR(%s): preview is running, cannot change size and format!", __func__);
ret = INVALID_OPERATION;
}
LOGV("%s: mPreviewWindow (%p) set_buffers_geometry", __func__, mPreviewWindow);
LOGV("%s: mPreviewWindow->set_buffers_geometry (%p)", __func__,
mPreviewWindow->set_buffers_geometry);
mPreviewWindow->set_buffers_geometry(mPreviewWindow,
new_preview_width, new_preview_height,
V4L2_PIX_2_HAL_PIXEL_FORMAT(new_preview_format));
LOGV("%s: DONE mPreviewWindow (%p) set_buffers_geometry", __func__, mPreviewWindow);
}
mParameters.setPreviewSize(new_preview_width, new_preview_height);
mParameters.setPreviewFormat(new_str_preview_format);
}
}
} else {
LOGE("%s: Invalid preview size(%dx%d)",
__func__, new_preview_width, new_preview_height);
ret = INVALID_OPERATION;
}
// picture size
int new_picture_width = 0;
int new_picture_height = 0;
params.getPictureSize(&new_picture_width, &new_picture_height);
LOGV("%s : new_picture_width x new_picture_height = %dx%d", __func__, new_picture_width, new_picture_height);
int current_picture_width, current_picture_height, current_picture_size;
mSecCamera->getSnapshotSize(¤t_picture_width, ¤t_picture_height, ¤t_picture_size);
if (new_picture_width != current_picture_width ||
new_picture_height != current_picture_height) {
if (mSecCamera->setSnapshotSize(new_picture_width, new_picture_height) < 0) {
LOGE("ERR(%s):fail on mSecCamera->setSnapshotSize(width(%d), height(%d))",
__func__, new_picture_width, new_picture_height);
ret = UNKNOWN_ERROR;
} else {
#ifdef ZERO_SHUTTER_LAG
mSecCamera->stopSnapshot();
if (mUseInternalISP && !mRecordHint && mPreviewRunning){
mSecCamera->startSnapshot(NULL);
}
#endif
mParameters.setPictureSize(new_picture_width, new_picture_height);
}
}
// picture format
const char *new_str_picture_format = params.getPictureFormat();
LOGV("%s : new_str_picture_format %s", __func__, new_str_picture_format);
if (new_str_picture_format != NULL) {
int new_picture_format = 0;
if (!strcmp(new_str_picture_format, CameraParameters::PIXEL_FORMAT_RGB565))
new_picture_format = V4L2_PIX_FMT_RGB565;
else if (!strcmp(new_str_picture_format, CameraParameters::PIXEL_FORMAT_RGBA8888))
new_picture_format = V4L2_PIX_FMT_RGB32;
else if (!strcmp(new_str_picture_format, CameraParameters::PIXEL_FORMAT_YUV420SP))
new_picture_format = V4L2_PIX_FMT_NV21;
else if (!strcmp(new_str_picture_format, "yuv420sp_custom"))
new_picture_format = V4L2_PIX_FMT_NV12T;
else if (!strcmp(new_str_picture_format, "yuv420p"))
new_picture_format = V4L2_PIX_FMT_YUV420;
else if (!strcmp(new_str_picture_format, "yuv422i"))
new_picture_format = V4L2_PIX_FMT_YUYV;
else if (!strcmp(new_str_picture_format, "uyv422i_custom")) //Zero copy UYVY format
new_picture_format = V4L2_PIX_FMT_UYVY;
else if (!strcmp(new_str_picture_format, "uyv422i")) //Non-zero copy UYVY format
new_picture_format = V4L2_PIX_FMT_UYVY;
else if (!strcmp(new_str_picture_format, CameraParameters::PIXEL_FORMAT_JPEG))
new_picture_format = V4L2_PIX_FMT_YUYV;
else if (!strcmp(new_str_picture_format, "yuv422p"))
new_picture_format = V4L2_PIX_FMT_YUV422P;
else
new_picture_format = V4L2_PIX_FMT_NV21; //for 3rd party
if (mSecCamera->setSnapshotPixelFormat(new_picture_format) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setSnapshotPixelFormat(format(%d))", __func__, new_picture_format);
ret = UNKNOWN_ERROR;
} else
mParameters.setPictureFormat(new_str_picture_format);
}
// JPEG image quality
int new_jpeg_quality = params.getInt(CameraParameters::KEY_JPEG_QUALITY);
LOGV("%s : new_jpeg_quality %d", __func__, new_jpeg_quality);
/* we ignore bad values */
if (new_jpeg_quality >=1 && new_jpeg_quality <= 100) {
if (mSecCamera->setJpegQuality(new_jpeg_quality) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setJpegQuality(quality(%d))", __func__, new_jpeg_quality);
ret = UNKNOWN_ERROR;
} else
mParameters.set(CameraParameters::KEY_JPEG_QUALITY, new_jpeg_quality);
}
// JPEG thumbnail size
int new_jpeg_thumbnail_width = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH);
int new_jpeg_thumbnail_height= params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT);
if (0 <= new_jpeg_thumbnail_width && 0 <= new_jpeg_thumbnail_height) {
if (mSecCamera->setJpegThumbnailSize(new_jpeg_thumbnail_width, new_jpeg_thumbnail_height) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setJpegThumbnailSize(width(%d), height(%d))", __func__, new_jpeg_thumbnail_width, new_jpeg_thumbnail_height);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, new_jpeg_thumbnail_width);
mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, new_jpeg_thumbnail_height);
}
}
// JPEG thumbnail quality
int new_jpeg_thumbnail_quality = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY);
LOGV("%s : new_jpeg_thumbnail_quality %d", __func__, new_jpeg_thumbnail_quality);
/* we ignore bad values */
if (new_jpeg_thumbnail_quality >=1 && new_jpeg_thumbnail_quality <= 100) {
if (mSecCamera->setJpegThumbnailQuality(new_jpeg_thumbnail_quality) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setJpegThumbnailQuality(quality(%d))",
__func__, new_jpeg_thumbnail_quality);
ret = UNKNOWN_ERROR;
} else
mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY, new_jpeg_thumbnail_quality);
}
// frame rate
int new_frame_rate = params.getPreviewFrameRate();
/* ignore any fps request, we're determine fps automatically based
* on scene mode. don't return an error because it causes CTS failure.
*/
if (mRecordHint) {
if (new_frame_rate) {
if (mUseInternalISP && (mSecCamera->setFrameRate(new_frame_rate) < 0)){
LOGE("ERR(%s):Fail on mSecCamera->setFrameRate(%d)", __func__, new_frame_rate);
ret = UNKNOWN_ERROR;
} else {
mParameters.setPreviewFrameRate(new_frame_rate);
}
}
}
// rotation
int new_rotation = params.getInt(CameraParameters::KEY_ROTATION);
LOGV("%s : new_rotation %d", __func__, new_rotation);
if (0 <= new_rotation) {
LOGV("%s : set orientation:%d", __func__, new_rotation);
if (mSecCamera->setExifOrientationInfo(new_rotation) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setExifOrientationInfo(%d)", __func__, new_rotation);
ret = UNKNOWN_ERROR;
} else
mParameters.set(CameraParameters::KEY_ROTATION, new_rotation);
}
// zoom
int new_zoom = params.getInt(CameraParameters::KEY_ZOOM);
int current_zoom = mParameters.getInt(CameraParameters::KEY_ZOOM);
LOGV("%s : new_zoom %d", __func__, new_zoom);
if (0 <= new_zoom) {
if (new_zoom != current_zoom) {
if (mSecCamera->setZoom(new_zoom) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setZoom(zoom(%d))", __func__, new_zoom);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_ZOOM, new_zoom);
}
}
}
// brightness
int new_brightness = params.getInt("brightness");
int max_brightness = params.getInt("brightness-max");
int min_brightness = params.getInt("brightness-min");
LOGV("%s : new_brightness %d", __func__, new_brightness);
if ((min_brightness <= new_brightness) &&
(max_brightness >= new_brightness)) {
if (mSecCamera->setBrightness(new_brightness) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setBrightness(brightness(%d))", __func__, new_brightness);
ret = UNKNOWN_ERROR;
} else {
mParameters.set("brightness", new_brightness);
}
}
// saturation
int new_saturation = params.getInt("saturation");
int max_saturation = params.getInt("saturation-max");
int min_saturation = params.getInt("saturation-min");
LOGV("%s : new_saturation %d", __func__, new_saturation);
if ((min_saturation <= new_saturation) &&
(max_saturation >= new_saturation)) {
if (mSecCamera->setSaturation(new_saturation) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setSaturation(saturation(%d))", __func__, new_saturation);
ret = UNKNOWN_ERROR;
} else {
mParameters.set("saturation", new_saturation);
}
}
// sharpness
int new_sharpness = params.getInt("sharpness");
int max_sharpness = params.getInt("sharpness-max");
int min_sharpness = params.getInt("sharpness-min");
LOGV("%s : new_sharpness %d", __func__, new_sharpness);
if ((min_sharpness <= new_sharpness) &&
(max_sharpness >= new_sharpness)) {
if (mSecCamera->setSharpness(new_sharpness) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setSharpness(sharpness(%d))", __func__, new_sharpness);
ret = UNKNOWN_ERROR;
} else {
mParameters.set("sharpness", new_sharpness);
}
}
// hue
int new_hue = params.getInt("hue");
int max_hue = params.getInt("hue-max");
int min_hue = params.getInt("hue-min");
LOGV("%s : new_hue %d", __func__, new_hue);
if ((min_hue <= new_hue) &&
(max_hue >= new_hue)) {
if (mSecCamera->setHue(new_hue) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setHue(hue(%d))", __func__, new_hue);
ret = UNKNOWN_ERROR;
} else {
mParameters.set("hue", new_hue);
}
}
// exposure
int new_exposure_compensation = params.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION);
int max_exposure_compensation = params.getInt(CameraParameters::KEY_MAX_EXPOSURE_COMPENSATION);
int min_exposure_compensation = params.getInt(CameraParameters::KEY_MIN_EXPOSURE_COMPENSATION);
LOGV("%s : new_exposure_compensation %d", __func__, new_exposure_compensation);
if ((min_exposure_compensation <= new_exposure_compensation) &&
(max_exposure_compensation >= new_exposure_compensation)) {
if (mSecCamera->setExposure(new_exposure_compensation) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setExposure(exposure(%d))", __func__, new_exposure_compensation);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_EXPOSURE_COMPENSATION, new_exposure_compensation);
}
}
const char *new_AE_lock = params.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK);
const char *old_AE_lock = mParameters.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK);
if ((new_AE_lock != NULL) && mUseInternalISP && mPreviewRunning) {
if (strncmp(new_AE_lock, old_AE_lock, 4)) {
int ae_value = !strncmp(new_AE_lock, "true", 4);
if (mSecCamera->setAutoExposureLock(ae_value) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setExposureLock", __func__);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK, new_AE_lock);
}
}
}
// ISO
const char *new_iso_str = params.get("iso");
LOGV("%s : new_iso_str %s", __func__, new_iso_str);
if (new_iso_str != NULL) {
int new_iso = -1;
if (!strcmp(new_iso_str, "auto")) {
new_iso = ISO_AUTO;
} else if (!strcmp(new_iso_str, "50")) {
new_iso = ISO_50;
} else if (!strcmp(new_iso_str, "100")) {
new_iso = ISO_100;
} else if (!strcmp(new_iso_str, "200")) {
new_iso = ISO_200;
} else if (!strcmp(new_iso_str, "400")) {
new_iso = ISO_400;
} else if (!strcmp(new_iso_str, "800")) {
new_iso = ISO_800;
} else if (!strcmp(new_iso_str, "1600")) {
new_iso = ISO_1600;
} else {
LOGE("ERR(%s):Invalid iso value(%s)", __func__, new_iso_str);
ret = UNKNOWN_ERROR;
}
if (0 <= new_iso) {
if (mSecCamera->setISO(new_iso) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setISO(iso(%d))", __func__, new_iso);
ret = UNKNOWN_ERROR;
} else {
mParameters.set("iso", new_iso_str);
}
}
}
// Metering
const char *new_metering_str = params.get("metering");
LOGV("%s : new_metering_str %s", __func__, new_metering_str);
if (new_metering_str != NULL) {
int new_metering = -1;
if (!strcmp(new_metering_str, "center")) {
new_metering = METERING_CENTER;
} else if (!strcmp(new_metering_str, "spot")) {
new_metering = METERING_SPOT;
} else if (!strcmp(new_metering_str, "matrix")) {
new_metering = METERING_MATRIX;
} else {
LOGE("ERR(%s):Invalid metering value(%s)", __func__, new_metering_str);
ret = UNKNOWN_ERROR;
}
if (0 <= new_metering) {
if (mSecCamera->setMetering(new_metering) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setMetering(metering(%d))", __func__, new_metering);
ret = UNKNOWN_ERROR;
} else {
mParameters.set("metering", new_metering_str);
}
}
}
// AFC
const char *new_antibanding_str = params.get(CameraParameters::KEY_ANTIBANDING);
LOGV("%s : new_antibanding_str %s", __func__, new_antibanding_str);
if (new_antibanding_str != NULL) {
int new_antibanding = -1;
if (!strcmp(new_antibanding_str, CameraParameters::ANTIBANDING_AUTO)) {
if (mUseInternalISP)
new_antibanding = IS_AFC_AUTO;
else
new_antibanding = ANTI_BANDING_AUTO;
} else if (!strcmp(new_antibanding_str, CameraParameters::ANTIBANDING_50HZ)) {
if (mUseInternalISP)
new_antibanding = IS_AFC_MANUAL_50HZ;
else
new_antibanding = ANTI_BANDING_50HZ;
} else if (!strcmp(new_antibanding_str, CameraParameters::ANTIBANDING_60HZ)) {
if (mUseInternalISP)
new_antibanding = IS_AFC_MANUAL_60HZ;
else
new_antibanding = ANTI_BANDING_60HZ;
} else if (!strcmp(new_antibanding_str, CameraParameters::ANTIBANDING_OFF)) {
if (mUseInternalISP)
new_antibanding = IS_AFC_DISABLE;
else
new_antibanding = ANTI_BANDING_OFF;
} else {
LOGE("ERR(%s):Invalid antibanding value(%s)", __func__, new_antibanding_str);
ret = UNKNOWN_ERROR;
}
if (0 <= new_antibanding) {
if (mSecCamera->setAntiBanding(new_antibanding) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setAntiBanding(antibanding(%d))", __func__, new_antibanding);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_ANTIBANDING, new_antibanding_str);
}
}
}
// scene mode
const char *new_scene_mode_str = params.get(CameraParameters::KEY_SCENE_MODE);
const char *current_scene_mode_str = mParameters.get(CameraParameters::KEY_SCENE_MODE);
// fps range
int new_min_fps = 0;
int new_max_fps = 0;
int current_min_fps, current_max_fps;
params.getPreviewFpsRange(&new_min_fps, &new_max_fps);
mParameters.getPreviewFpsRange(¤t_min_fps, ¤t_max_fps);
/* our fps range is determined by the sensor, reject any request
* that isn't exactly what we're already at.
* but the check is performed when requesting only changing fps range
*/
if (new_scene_mode_str && current_scene_mode_str) {
if (!strcmp(new_scene_mode_str, current_scene_mode_str)) {
if ((new_min_fps != current_min_fps) || (new_max_fps != current_max_fps)) {
LOGW("%s : requested new_min_fps = %d, new_max_fps = %d not allowed",
__func__, new_min_fps, new_max_fps);
/* TODO : We need policy for fps. */
LOGW("%s : current_min_fps = %d, current_max_fps = %d",
__func__, current_min_fps, current_max_fps);
//ret = UNKNOWN_ERROR;
}
}
} else {
/* Check basic validation if scene mode is different */
if ((new_min_fps > new_max_fps) ||
(new_min_fps < 0) || (new_max_fps < 0))
ret = UNKNOWN_ERROR;
}
const char *new_flash_mode_str = params.get(CameraParameters::KEY_FLASH_MODE);
const char *new_focus_mode_str = params.get(CameraParameters::KEY_FOCUS_MODE);
const char *new_white_str = params.get(CameraParameters::KEY_WHITE_BALANCE);
// fps range is (15000,30000) by default.
mParameters.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, "(15000,30000)");
mParameters.set(CameraParameters::KEY_PREVIEW_FPS_RANGE, "15000,30000");
if ((new_scene_mode_str != NULL) && (current_scene_mode_str != NULL) && strncmp(new_scene_mode_str, current_scene_mode_str, 5)) {
int new_scene_mode = -1;
if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_AUTO)) {
new_scene_mode = SCENE_MODE_NONE;
} else {
// defaults for non-auto scene modes
new_focus_mode_str = CameraParameters::FOCUS_MODE_AUTO;
new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
new_white_str = CameraParameters::WHITE_BALANCE_AUTO;
mParameters.set(CameraParameters::KEY_WHITE_BALANCE, new_white_str);
if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_PORTRAIT)) {
new_scene_mode = SCENE_MODE_PORTRAIT;
if (mCameraID == SecCamera::CAMERA_ID_BACK)
new_flash_mode_str = CameraParameters::FLASH_MODE_AUTO;
} else if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_LANDSCAPE)) {
new_scene_mode = SCENE_MODE_LANDSCAPE;
} else if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_SPORTS)) {
new_scene_mode = SCENE_MODE_SPORTS;
} else if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_PARTY)) {
new_scene_mode = SCENE_MODE_PARTY_INDOOR;
if (mCameraID == SecCamera::CAMERA_ID_BACK)
new_flash_mode_str = CameraParameters::FLASH_MODE_AUTO;
} else if ((!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_BEACH)) ||
(!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_SNOW))) {
new_scene_mode = SCENE_MODE_BEACH_SNOW;
} else if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_SUNSET)) {
new_scene_mode = SCENE_MODE_SUNSET;
} else if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_NIGHT)) {
new_scene_mode = SCENE_MODE_NIGHTSHOT;
mParameters.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, "(4000,30000)");
mParameters.set(CameraParameters::KEY_PREVIEW_FPS_RANGE, "4000,30000");
} else if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_FIREWORKS)) {
new_scene_mode = SCENE_MODE_FIREWORKS;
} else if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_CANDLELIGHT)) {
new_scene_mode = SCENE_MODE_CANDLE_LIGHT;
} else {
LOGE("%s::unmatched scene_mode(%s)",
__func__, new_scene_mode_str); //action, night-portrait, theatre, steadyphoto
ret = UNKNOWN_ERROR;
}
}
if (0 <= new_scene_mode) {
if (mSecCamera->setSceneMode(new_scene_mode) < 0) {
LOGE("%s::mSecCamera->setSceneMode(%d) fail", __func__, new_scene_mode);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_SCENE_MODE, new_scene_mode_str);
}
}
}
// focus mode
/* TODO : currently only posible focus modes at BACK camera */
if ((new_focus_mode_str != NULL) && (mCameraID == SecCamera::CAMERA_ID_BACK)) {
int new_focus_mode = -1;
if (!strcmp(new_focus_mode_str,
CameraParameters::FOCUS_MODE_AUTO)) {
new_focus_mode = FOCUS_MODE_AUTO;
mParameters.set(CameraParameters::KEY_FOCUS_DISTANCES,
BACK_CAMERA_AUTO_FOCUS_DISTANCES_STR);
} else if (!strcmp(new_focus_mode_str,
CameraParameters::FOCUS_MODE_MACRO)) {
new_focus_mode = FOCUS_MODE_MACRO;
mParameters.set(CameraParameters::KEY_FOCUS_DISTANCES,
BACK_CAMERA_MACRO_FOCUS_DISTANCES_STR);
} else if (!strcmp(new_focus_mode_str,
CameraParameters::FOCUS_MODE_INFINITY)) {
new_focus_mode = FOCUS_MODE_INFINITY;
mParameters.set(CameraParameters::KEY_FOCUS_DISTANCES,
BACK_CAMERA_INFINITY_FOCUS_DISTANCES_STR);
} else if (!strcmp(new_focus_mode_str,
CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO) ||
!strcmp(new_focus_mode_str,
CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE)) {
new_focus_mode = FOCUS_MODE_CONTINOUS;
} else {
/* TODO */
/* This is temperary implementation.
When camera support all AF mode, this code will be changing */
LOGE("%s::unmatched focus_mode(%s)", __func__, new_focus_mode_str);
ret = UNKNOWN_ERROR;
}
if (0 <= new_focus_mode) {
if (mSecCamera->setFocusMode(new_focus_mode) < 0) {
LOGE("%s::mSecCamera->setFocusMode(%d) fail", __func__, new_focus_mode);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_FOCUS_MODE, new_focus_mode_str);
}
}
}
// flash..
if (new_flash_mode_str != NULL) {
int new_flash_mode = -1;
if (!strcmp(new_flash_mode_str, CameraParameters::FLASH_MODE_OFF))
new_flash_mode = FLASH_MODE_OFF;
else if (!strcmp(new_flash_mode_str, CameraParameters::FLASH_MODE_AUTO))
new_flash_mode = FLASH_MODE_AUTO;
else if (!strcmp(new_flash_mode_str, CameraParameters::FLASH_MODE_ON))
new_flash_mode = FLASH_MODE_ON;
else if (!strcmp(new_flash_mode_str, CameraParameters::FLASH_MODE_TORCH))
new_flash_mode = FLASH_MODE_TORCH;
else {
LOGE("%s::unmatched flash_mode(%s)", __func__, new_flash_mode_str); //red-eye
ret = UNKNOWN_ERROR;
}
if (0 <= new_flash_mode) {
if (mSecCamera->setFlashMode(new_flash_mode) < 0) {
LOGE("%s::mSecCamera->setFlashMode(%d) fail", __func__, new_flash_mode);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_FLASH_MODE, new_flash_mode_str);
}
}
}
// whitebalance
LOGV("%s : new_white_str %s", __func__, new_white_str);
if ((new_scene_mode_str != NULL) && !strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_AUTO)) {
if (new_white_str != NULL) {
int new_white = -1;
if (!strcmp(new_white_str, CameraParameters::WHITE_BALANCE_AUTO)) {
new_white = WHITE_BALANCE_AUTO;
} else if (!strcmp(new_white_str,
CameraParameters::WHITE_BALANCE_DAYLIGHT)) {
new_white = WHITE_BALANCE_SUNNY;
} else if (!strcmp(new_white_str,
CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT)) {
new_white = WHITE_BALANCE_CLOUDY;
} else if (!strcmp(new_white_str,
CameraParameters::WHITE_BALANCE_FLUORESCENT)) {
new_white = WHITE_BALANCE_FLUORESCENT;
} else if (!strcmp(new_white_str,
CameraParameters::WHITE_BALANCE_INCANDESCENT)) {
new_white = WHITE_BALANCE_TUNGSTEN;
} else {
LOGE("ERR(%s):Invalid white balance(%s)", __func__, new_white_str); //twilight, shade, warm_flourescent
ret = UNKNOWN_ERROR;
}
if (0 <= new_white) {
if (mSecCamera->setWhiteBalance(new_white) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setWhiteBalance(white(%d))", __func__, new_white);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_WHITE_BALANCE, new_white_str);
}
}
}
}
const char *new_AWB_lock = params.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK);
const char *old_AWB_lock = mParameters.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK);
if (new_AWB_lock != NULL && mUseInternalISP && mPreviewRunning) {
if (strncmp(new_AWB_lock, old_AWB_lock, 4)) {
int awb_value = !strncmp(new_AWB_lock, "true", 4);
if (mSecCamera->setAutoWhiteBalanceLock(awb_value) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setoAutoWhiteBalanceLock()", __func__);
ret = UNKNOWN_ERROR;
} else {
mParameters.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, new_AWB_lock);
}
}
}
const char *new_touch_rect_str = params.get(CameraParameters::KEY_FOCUS_AREAS);
LOGV("Touched rect is '%s'", new_touch_rect_str);
if (new_touch_rect_str != NULL) {
int left = 0, top = 0, right = 0, bottom = 0, touched = 0;
int objx, objy;
char *end;
char delim = ',';
left = (int)strtol(new_touch_rect_str+1, &end, 10);
if (*end != delim) {
LOGE("Cannot find '%c' in str=%s", delim, new_touch_rect_str);
return -1;
}
top = (int)strtol(end+1, &end, 10);
if (*end != delim) {
LOGE("Cannot find '%c' in str=%s", delim, new_touch_rect_str);
return -1;
}
right = (int)strtol(end+1, &end, 10);
if (*end != delim) {
LOGE("Cannot find '%c' in str=%s", delim, new_touch_rect_str);
return -1;
}
bottom = (int)strtol(end+1, &end, 10);
if (*end != delim) {
LOGE("Cannot find '%c' in str=%s", delim, new_touch_rect_str);
return -1;
}
touched = (int)strtol(end+1, &end, 10);
if (*end != ')') {
LOGE("Cannot find ')' in str=%s", new_touch_rect_str);
return -1;
}
/* TODO : Converting axis and Calcurating center of rect. Because driver need (x, y) point. */
objx = (int)((1023 * (left + 1000)) / 2000) + 97;
objy = (int)((1023 * (top + 1000)) / 2000) + 128;
mTouched = touched;
mSecCamera->setObjectPosition(objx, objy);
}
// image effect
const char *new_image_effect_str = params.get(CameraParameters::KEY_EFFECT);
if (new_image_effect_str != NULL) {
int new_image_effect = -1;
if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_NONE)) {
new_image_effect = IMAGE_EFFECT_NONE;
} else if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_MONO)) {
new_image_effect = IMAGE_EFFECT_BNW;
} else if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_SEPIA)) {
new_image_effect = IMAGE_EFFECT_SEPIA;
} else if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_AQUA))
new_image_effect = IMAGE_EFFECT_AQUA;
else if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_NEGATIVE)) {
new_image_effect = IMAGE_EFFECT_NEGATIVE;
} else {
//posterize, whiteboard, blackboard, solarize
LOGE("ERR(%s):Invalid effect(%s)", __func__, new_image_effect_str);
ret = UNKNOWN_ERROR;
}
if (new_image_effect >= 0) {
if (mSecCamera->setImageEffect(new_image_effect) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setImageEffect(effect(%d))", __func__, new_image_effect);
ret = UNKNOWN_ERROR;
} else {
const char *old_image_effect_str = mParameters.get(CameraParameters::KEY_EFFECT);
if (old_image_effect_str) {
if (strcmp(old_image_effect_str, new_image_effect_str)) {
setSkipFrame(EFFECT_SKIP_FRAME);
}
}
mParameters.set(CameraParameters::KEY_EFFECT, new_image_effect_str);
}
}
}
//contrast
const char *new_contrast_str = params.get("contrast");
LOGV("%s : new_contrast_str %s", __func__, new_contrast_str);
if (new_contrast_str != NULL) {
int new_contrast = -1;
if (!strcmp(new_contrast_str, "auto")) {
if (mUseInternalISP)
new_contrast = IS_CONTRAST_AUTO;
else
LOGW("WARN(%s):Invalid contrast value (%s)", __func__, new_contrast_str);
} else if (!strcmp(new_contrast_str, "-2")) {
if (mUseInternalISP)
new_contrast = IS_CONTRAST_MINUS_2;
else
new_contrast = CONTRAST_MINUS_2;
} else if (!strcmp(new_contrast_str, "-1")) {
if (mUseInternalISP)
new_contrast = IS_CONTRAST_MINUS_1;
else
new_contrast = CONTRAST_MINUS_1;
} else if (!strcmp(new_contrast_str, "0")) {
if (mUseInternalISP)
new_contrast = IS_CONTRAST_DEFAULT;
else
new_contrast = CONTRAST_DEFAULT;
} else if (!strcmp(new_contrast_str, "1")) {
if (mUseInternalISP)
new_contrast = IS_CONTRAST_PLUS_1;
else
new_contrast = CONTRAST_PLUS_1;
} else if (!strcmp(new_contrast_str, "2")) {
if (mUseInternalISP)
new_contrast = IS_CONTRAST_PLUS_2;
else
new_contrast = CONTRAST_PLUS_2;
} else {
LOGE("ERR(%s):Invalid contrast value(%s)", __func__, new_contrast_str);
ret = UNKNOWN_ERROR;
}
if (0 <= new_contrast) {
if (mSecCamera->setContrast(new_contrast) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setContrast(contrast(%d))", __func__, new_contrast);
ret = UNKNOWN_ERROR;
} else {
mParameters.set("contrast", new_contrast_str);
}
}
}
//WDR
int new_wdr = params.getInt("wdr");
LOGV("%s : new_wdr %d", __func__, new_wdr);
if (0 <= new_wdr) {
if (mSecCamera->setWDR(new_wdr) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setWDR(%d)", __func__, new_wdr);
ret = UNKNOWN_ERROR;
}
}
//anti shake
int new_anti_shake = mInternalParameters.getInt("anti-shake");
if (0 <= new_anti_shake) {
if (mSecCamera->setAntiShake(new_anti_shake) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setWDR(%d)", __func__, new_anti_shake);
ret = UNKNOWN_ERROR;
}
}
// gps latitude
const char *new_gps_latitude_str = params.get(CameraParameters::KEY_GPS_LATITUDE);
if (mSecCamera->setGPSLatitude(new_gps_latitude_str) < 0) {
LOGE("%s::mSecCamera->setGPSLatitude(%s) fail", __func__, new_gps_latitude_str);
ret = UNKNOWN_ERROR;
} else {
if (new_gps_latitude_str) {
mParameters.set(CameraParameters::KEY_GPS_LATITUDE, new_gps_latitude_str);
} else {
mParameters.remove(CameraParameters::KEY_GPS_LATITUDE);
}
}
// gps longitude
const char *new_gps_longitude_str = params.get(CameraParameters::KEY_GPS_LONGITUDE);
if (mSecCamera->setGPSLongitude(new_gps_longitude_str) < 0) {
LOGE("%s::mSecCamera->setGPSLongitude(%s) fail", __func__, new_gps_longitude_str);
ret = UNKNOWN_ERROR;
} else {
if (new_gps_longitude_str) {
mParameters.set(CameraParameters::KEY_GPS_LONGITUDE, new_gps_longitude_str);
} else {
mParameters.remove(CameraParameters::KEY_GPS_LONGITUDE);
}
}
// gps altitude
const char *new_gps_altitude_str = params.get(CameraParameters::KEY_GPS_ALTITUDE);
if (mSecCamera->setGPSAltitude(new_gps_altitude_str) < 0) {
LOGE("%s::mSecCamera->setGPSAltitude(%s) fail", __func__, new_gps_altitude_str);
ret = UNKNOWN_ERROR;
} else {
if (new_gps_altitude_str) {
mParameters.set(CameraParameters::KEY_GPS_ALTITUDE, new_gps_altitude_str);
} else {
mParameters.remove(CameraParameters::KEY_GPS_ALTITUDE);
}
}
// gps timestamp
const char *new_gps_timestamp_str = params.get(CameraParameters::KEY_GPS_TIMESTAMP);
if (mSecCamera->setGPSTimeStamp(new_gps_timestamp_str) < 0) {
LOGE("%s::mSecCamera->setGPSTimeStamp(%s) fail", __func__, new_gps_timestamp_str);
ret = UNKNOWN_ERROR;
} else {
if (new_gps_timestamp_str) {
mParameters.set(CameraParameters::KEY_GPS_TIMESTAMP, new_gps_timestamp_str);
} else {
mParameters.remove(CameraParameters::KEY_GPS_TIMESTAMP);
}
}
// gps processing method
const char *new_gps_processing_method_str = params.get(CameraParameters::KEY_GPS_PROCESSING_METHOD);
if (mSecCamera->setGPSProcessingMethod(new_gps_processing_method_str) < 0) {
LOGE("%s::mSecCamera->setGPSProcessingMethod(%s) fail", __func__, new_gps_processing_method_str);
ret = UNKNOWN_ERROR;
} else {
if (new_gps_processing_method_str) {
mParameters.set(CameraParameters::KEY_GPS_PROCESSING_METHOD, new_gps_processing_method_str);
} else {
mParameters.remove(CameraParameters::KEY_GPS_PROCESSING_METHOD);
}
}
// Recording size
/* TODO */
/* GED application don't set different recording size before recording button is pushed */
int new_recording_width = 0;
int new_recording_height = 0;
params.getVideoSize(&new_recording_width, &new_recording_height);
LOGV("new_recording_width (%d) new_recording_height (%d)",
new_recording_width, new_recording_height);
int current_recording_width, current_recording_height;
mParameters.getVideoSize(¤t_recording_width, ¤t_recording_height);
LOGV("current_recording_width (%d) current_recording_height (%d)",
current_recording_width, current_recording_height);
if (current_recording_width != new_recording_width ||
current_recording_height != new_recording_height) {
if (0 < new_recording_width && 0 < new_recording_height) {
if (mSecCamera->setRecordingSize(new_recording_width, new_recording_height) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setRecordingSize(width(%d), height(%d))",
__func__, new_recording_width, new_recording_height);
ret = UNKNOWN_ERROR;
}
mParameters.setVideoSize(new_recording_width, new_recording_height);
}
}
//gamma
const char *new_gamma_str = mInternalParameters.get("video_recording_gamma");
if (new_gamma_str != NULL) {
int new_gamma = -1;
if (!strcmp(new_gamma_str, "off"))
new_gamma = GAMMA_OFF;
else if (!strcmp(new_gamma_str, "on"))
new_gamma = GAMMA_ON;
else {
LOGE("%s::unmatched gamma(%s)", __func__, new_gamma_str);
ret = UNKNOWN_ERROR;
}
if (0 <= new_gamma) {
if (mSecCamera->setGamma(new_gamma) < 0) {
LOGE("%s::mSecCamera->setGamma(%d) fail", __func__, new_gamma);
ret = UNKNOWN_ERROR;
}
}
}
//slow ae
const char *new_slow_ae_str = mInternalParameters.get("slow_ae");
if (new_slow_ae_str != NULL) {
int new_slow_ae = -1;
if (!strcmp(new_slow_ae_str, "off"))
new_slow_ae = SLOW_AE_OFF;
else if (!strcmp(new_slow_ae_str, "on"))
new_slow_ae = SLOW_AE_ON;
else {
LOGE("%s::unmatched slow_ae(%s)", __func__, new_slow_ae_str);
ret = UNKNOWN_ERROR;
}
if (0 <= new_slow_ae) {
if (mSecCamera->setSlowAE(new_slow_ae) < 0) {
LOGE("%s::mSecCamera->setSlowAE(%d) fail", __func__, new_slow_ae);
ret = UNKNOWN_ERROR;
}
}
}
/*Camcorder fix fps*/
int new_sensor_mode = mInternalParameters.getInt("cam_mode");
if (0 <= new_sensor_mode) {
if (mSecCamera->setSensorMode(new_sensor_mode) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setSensorMode(%d)", __func__, new_sensor_mode);
ret = UNKNOWN_ERROR;
}
} else {
new_sensor_mode=0;
}
/*Shot mode*/
int new_shot_mode = mInternalParameters.getInt("shot_mode");
if (0 <= new_shot_mode) {
if (mSecCamera->setShotMode(new_shot_mode) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setShotMode(%d)", __func__, new_shot_mode);
ret = UNKNOWN_ERROR;
}
} else {
new_shot_mode=0;
}
// chk_dataline
int new_dataline = mInternalParameters.getInt("chk_dataline");
if (0 <= new_dataline) {
if (mSecCamera->setDataLineCheck(new_dataline) < 0) {
LOGE("ERR(%s):Fail on mSecCamera->setDataLineCheck(%d)", __func__, new_dataline);
ret = UNKNOWN_ERROR;
}
}
LOGV("%s return ret = %d", __func__, ret);
return ret;
}
CameraParameters CameraHardwareSec::getParameters() const
{
LOGV("%s :", __func__);
return mParameters;
}
status_t CameraHardwareSec::sendCommand(int32_t command, int32_t arg1, int32_t arg2)
{
/* TODO */
/* CAMERA_CMD_START_FACE_DETECTION and CAMERA_CMD_STOP_FACE_DETECTION
for Face Detection */
if(command == CAMERA_CMD_START_FACE_DETECTION) {
if (mSecCamera->setFaceDetect(FACE_DETECTION_ON) < 0) {
LOGE("ERR(%s): Fail on mSecCamera->startFaceDetection()", __func__);
return BAD_VALUE;
} else {
return NO_ERROR;
}
}
if(command == CAMERA_CMD_STOP_FACE_DETECTION) {
if (mSecCamera->setFaceDetect(FACE_DETECTION_OFF) < 0) {
LOGE("ERR(%s): Fail on mSecCamera->stopFaceDetection()", __func__);
return BAD_VALUE;
} else {
return NO_ERROR;
}
}
return BAD_VALUE;
}
void CameraHardwareSec::release()
{
LOGV("%s", __func__);
/* shut down any threads we have that might be running. do it here
* instead of the destructor. we're guaranteed to be on another thread
* than the ones below. if we used the destructor, since the threads
* have a reference to this object, we could wind up trying to wait
* for ourself to exit, which is a deadlock.
*/
if (mPreviewThread != NULL) {
/* this thread is normally already in it's threadLoop but blocked
* on the condition variable or running. signal it so it wakes
* up and can exit.
*/
mPreviewThread->requestExit();
mExitPreviewThread = true;
mPreviewRunning = true; /* let it run so it can exit */
mPreviewCondition.signal();
mPreviewThread->requestExitAndWait();
mPreviewThread.clear();
}
if (mAutoFocusThread != NULL) {
/* this thread is normally already in it's threadLoop but blocked
* on the condition variable. signal it so it wakes up and can exit.
*/
mFocusLock.lock();
mAutoFocusThread->requestExit();
mExitAutoFocusThread = true;
mFocusCondition.signal();
mFocusLock.unlock();
mAutoFocusThread->requestExitAndWait();
mAutoFocusThread.clear();
}
if (mPictureThread != NULL) {
mPictureThread->requestExitAndWait();
mPictureThread.clear();
}
#ifdef IS_FW_DEBUG
if (mDebugThread != NULL) {
mDebugThread->requestExitAndWait();
mDebugThread.clear();
}
#endif
if (mRawHeap) {
mRawHeap->release(mRawHeap);
mRawHeap = 0;
}
if (mPreviewHeap) {
mPreviewHeap->release(mPreviewHeap);
mPreviewHeap = 0;
}
for(int i = 0; i < BUFFER_COUNT_FOR_ARRAY; i++) {
if (mRecordHeap[i]) {
mRecordHeap[i]->release(mRecordHeap[i]);
mRecordHeap[i] = 0;
}
}
/* close after all the heaps are cleared since those
* could have dup'd our file descriptor.
*/
mSecCamera->DestroyCamera();
}
static CameraInfo sCameraInfo[] = {
{
CAMERA_FACING_BACK,
90, /* orientation */
},
{
CAMERA_FACING_FRONT,
90, /* orientation */
}
};
status_t CameraHardwareSec::storeMetaDataInBuffers(bool enable)
{
// FIXME:
// metadata buffer mode can be turned on or off.
// Samsung needs to fix this.
if (!enable) {
LOGE("Non-metadata buffer mode is not supported!");
return INVALID_OPERATION;
}
return OK;
}
/** Close this device */
static camera_device_t *g_cam_device;
static int HAL_camera_device_close(struct hw_device_t* device)
{
LOGI("%s", __func__);
if (device) {
camera_device_t *cam_device = (camera_device_t *)device;
delete static_cast<CameraHardwareSec *>(cam_device->priv);
free(cam_device);
g_cam_device = 0;
}
return 0;
}
static inline CameraHardwareSec *obj(struct camera_device *dev)
{
return reinterpret_cast<CameraHardwareSec *>(dev->priv);
}
/** Set the preview_stream_ops to which preview frames are sent */
static int HAL_camera_device_set_preview_window(struct camera_device *dev,
struct preview_stream_ops *buf)
{
LOGV("%s", __func__);
return obj(dev)->setPreviewWindow(buf);
}
/** Set the notification and data callbacks */
static void HAL_camera_device_set_callbacks(struct camera_device *dev,
camera_notify_callback notify_cb,
camera_data_callback data_cb,
camera_data_timestamp_callback data_cb_timestamp,
camera_request_memory get_memory,
void* user)
{
LOGV("%s", __func__);
obj(dev)->setCallbacks(notify_cb, data_cb, data_cb_timestamp,
get_memory,
user);
}
/**
* The following three functions all take a msg_type, which is a bitmask of
* the messages defined in include/ui/Camera.h
*/
/**
* Enable a message, or set of messages.
*/
static void HAL_camera_device_enable_msg_type(struct camera_device *dev, int32_t msg_type)
{
LOGV("%s", __func__);
obj(dev)->enableMsgType(msg_type);
}
/**
* Disable a message, or a set of messages.
*
* Once received a call to disableMsgType(CAMERA_MSG_VIDEO_FRAME), camera
* HAL should not rely on its client to call releaseRecordingFrame() to
* release video recording frames sent out by the cameral HAL before and
* after the disableMsgType(CAMERA_MSG_VIDEO_FRAME) call. Camera HAL
* clients must not modify/access any video recording frame after calling
* disableMsgType(CAMERA_MSG_VIDEO_FRAME).
*/
static void HAL_camera_device_disable_msg_type(struct camera_device *dev, int32_t msg_type)
{
LOGV("%s", __func__);
obj(dev)->disableMsgType(msg_type);
}
/**
* Query whether a message, or a set of messages, is enabled. Note that
* this is operates as an AND, if any of the messages queried are off, this
* will return false.
*/
static int HAL_camera_device_msg_type_enabled(struct camera_device *dev, int32_t msg_type)
{
LOGV("%s", __func__);
return obj(dev)->msgTypeEnabled(msg_type);
}
/**
* Start preview mode.
*/
static int HAL_camera_device_start_preview(struct camera_device *dev)
{
LOGV("%s", __func__);
return obj(dev)->startPreview();
}
/**
* Stop a previously started preview.
*/
static void HAL_camera_device_stop_preview(struct camera_device *dev)
{
LOGV("%s", __func__);
obj(dev)->stopPreview();
}
/**
* Returns true if preview is enabled.
*/
static int HAL_camera_device_preview_enabled(struct camera_device *dev)
{
LOGV("%s", __func__);
return obj(dev)->previewEnabled();
}
/**
* Request the camera HAL to store meta data or real YUV data in the video
* buffers sent out via CAMERA_MSG_VIDEO_FRAME for a recording session. If
* it is not called, the default camera HAL behavior is to store real YUV
* data in the video buffers.
*
* This method should be called before startRecording() in order to be
* effective.
*
* If meta data is stored in the video buffers, it is up to the receiver of
* the video buffers to interpret the contents and to find the actual frame
* data with the help of the meta data in the buffer. How this is done is
* outside of the scope of this method.
*
* Some camera HALs may not support storing meta data in the video buffers,
* but all camera HALs should support storing real YUV data in the video
* buffers. If the camera HAL does not support storing the meta data in the
* video buffers when it is requested to do do, INVALID_OPERATION must be
* returned. It is very useful for the camera HAL to pass meta data rather
* than the actual frame data directly to the video encoder, since the
* amount of the uncompressed frame data can be very large if video size is
* large.
*
* @param enable if true to instruct the camera HAL to store
* meta data in the video buffers; false to instruct
* the camera HAL to store real YUV data in the video
* buffers.
*
* @return OK on success.
*/
static int HAL_camera_device_store_meta_data_in_buffers(struct camera_device *dev, int enable)
{
LOGV("%s", __func__);
return obj(dev)->storeMetaDataInBuffers(enable);
}
/**
* Start record mode. When a record image is available, a
* CAMERA_MSG_VIDEO_FRAME message is sent with the corresponding
* frame. Every record frame must be released by a camera HAL client via
* releaseRecordingFrame() before the client calls
* disableMsgType(CAMERA_MSG_VIDEO_FRAME). After the client calls
* disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is the camera HAL's
* responsibility to manage the life-cycle of the video recording frames,
* and the client must not modify/access any video recording frames.
*/
static int HAL_camera_device_start_recording(struct camera_device *dev)
{
LOGV("%s", __func__);
return obj(dev)->startRecording();
}
/**
* Stop a previously started recording.
*/
static void HAL_camera_device_stop_recording(struct camera_device *dev)
{
LOGV("%s", __func__);
obj(dev)->stopRecording();
}
/**
* Returns true if recording is enabled.
*/
static int HAL_camera_device_recording_enabled(struct camera_device *dev)
{
LOGV("%s", __func__);
return obj(dev)->recordingEnabled();
}
/**
* Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
*
* It is camera HAL client's responsibility to release video recording
* frames sent out by the camera HAL before the camera HAL receives a call
* to disableMsgType(CAMERA_MSG_VIDEO_FRAME). After it receives the call to
* disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is the camera HAL's
* responsibility to manage the life-cycle of the video recording frames.
*/
static void HAL_camera_device_release_recording_frame(struct camera_device *dev,
const void *opaque)
{
LOGV("%s", __func__);
obj(dev)->releaseRecordingFrame(opaque);
}
/**
* Start auto focus, the notification callback routine is called with
* CAMERA_MSG_FOCUS once when focusing is complete. autoFocus() will be
* called again if another auto focus is needed.
*/
static int HAL_camera_device_auto_focus(struct camera_device *dev)
{
LOGV("%s", __func__);
return obj(dev)->autoFocus();
}
/**
* Cancels auto-focus function. If the auto-focus is still in progress,
* this function will cancel it. Whether the auto-focus is in progress or
* not, this function will return the focus position to the default. If
* the camera does not support auto-focus, this is a no-op.
*/
static int HAL_camera_device_cancel_auto_focus(struct camera_device *dev)
{
LOGV("%s", __func__);
return obj(dev)->cancelAutoFocus();
}
/**
* Take a picture.
*/
static int HAL_camera_device_take_picture(struct camera_device *dev)
{
LOGV("%s", __func__);
return obj(dev)->takePicture();
}
/**
* Cancel a picture that was started with takePicture. Calling this method
* when no picture is being taken is a no-op.
*/
static int HAL_camera_device_cancel_picture(struct camera_device *dev)
{
LOGV("%s", __func__);
return obj(dev)->cancelPicture();
}
/**
* Set the camera parameters. This returns BAD_VALUE if any parameter is
* invalid or not supported.
*/
static int HAL_camera_device_set_parameters(struct camera_device *dev,
const char *parms)
{
LOGV("%s", __func__);
String8 str(parms);
CameraParameters p(str);
return obj(dev)->setParameters(p);
}
/** Return the camera parameters. */
char *HAL_camera_device_get_parameters(struct camera_device *dev)
{
LOGV("%s", __func__);
String8 str;
CameraParameters parms = obj(dev)->getParameters();
str = parms.flatten();
return strdup(str.string());
}
static void HAL_camera_device_put_parameters(struct camera_device *dev, char *parms)
{
LOGV("%s", __func__);
free(parms);
}
/**
* Send command to camera driver.
*/
static int HAL_camera_device_send_command(struct camera_device *dev,
int32_t cmd, int32_t arg1, int32_t arg2)
{
LOGV("%s", __func__);
return obj(dev)->sendCommand(cmd, arg1, arg2);
}
/**
* Release the hardware resources owned by this object. Note that this is
* *not* done in the destructor.
*/
static void HAL_camera_device_release(struct camera_device *dev)
{
LOGV("%s", __func__);
obj(dev)->release();
}
/**
* Dump state of the camera hardware
*/
static int HAL_camera_device_dump(struct camera_device *dev, int fd)
{
LOGV("%s", __func__);
return obj(dev)->dump(fd);
}
static int HAL_getNumberOfCameras()
{
LOGV("%s", __func__);
int cam_fd;
static struct v4l2_input input;
cam_fd = open(CAMERA_DEV_NAME, O_RDONLY);
if (cam_fd < 0) {
LOGE("ERR(%s):Cannot open %s (error : %s)", __func__, CAMERA_DEV_NAME, strerror(errno));
return -1;
}
input.index = 0;
while (ioctl(cam_fd, VIDIOC_ENUMINPUT, &input) == 0) {
LOGI("Name of input channel[%d] is %s", input.index, input.name);
input.index++;
}
close(cam_fd);
return --input.index;
}
static int HAL_getCameraInfo(int cameraId, struct camera_info *cameraInfo)
{
LOGV("%s", __func__);
memcpy(cameraInfo, &sCameraInfo[cameraId], sizeof(CameraInfo));
return 0;
}
#define SET_METHOD(m) m : HAL_camera_device_##m
static camera_device_ops_t camera_device_ops = {
SET_METHOD(set_preview_window),
SET_METHOD(set_callbacks),
SET_METHOD(enable_msg_type),
SET_METHOD(disable_msg_type),
SET_METHOD(msg_type_enabled),
SET_METHOD(start_preview),
SET_METHOD(stop_preview),
SET_METHOD(preview_enabled),
SET_METHOD(store_meta_data_in_buffers),
SET_METHOD(start_recording),
SET_METHOD(stop_recording),
SET_METHOD(recording_enabled),
SET_METHOD(release_recording_frame),
SET_METHOD(auto_focus),
SET_METHOD(cancel_auto_focus),
SET_METHOD(take_picture),
SET_METHOD(cancel_picture),
SET_METHOD(set_parameters),
SET_METHOD(get_parameters),
SET_METHOD(put_parameters),
SET_METHOD(send_command),
SET_METHOD(release),
SET_METHOD(dump),
};
#undef SET_METHOD
static int HAL_camera_device_open(const struct hw_module_t* module,
const char *id,
struct hw_device_t** device)
{
LOGV("%s", __func__);
int cameraId = atoi(id);
if (cameraId < 0 || cameraId >= HAL_getNumberOfCameras()) {
LOGE("Invalid camera ID %s", id);
return -EINVAL;
}
if (g_cam_device) {
if (obj(g_cam_device)->getCameraId() == cameraId) {
LOGV("returning existing camera ID %s", id);
goto done;
} else {
LOGE("Cannot open camera %d. camera %d is already running!",
cameraId, obj(g_cam_device)->getCameraId());
return -ENOSYS;
}
}
g_cam_device = (camera_device_t *)malloc(sizeof(camera_device_t));
if (!g_cam_device)
return -ENOMEM;
g_cam_device->common.tag = HARDWARE_DEVICE_TAG;
g_cam_device->common.version = 1;
g_cam_device->common.module = const_cast<hw_module_t *>(module);
g_cam_device->common.close = HAL_camera_device_close;
g_cam_device->ops = &camera_device_ops;
LOGI("%s: open camera %s", __func__, id);
g_cam_device->priv = new CameraHardwareSec(cameraId, g_cam_device);
done:
*device = (hw_device_t *)g_cam_device;
LOGI("%s: opened camera %s (%p)", __func__, id, *device);
return 0;
}
static hw_module_methods_t camera_module_methods = {
open : HAL_camera_device_open
};
extern "C" {
struct camera_module HAL_MODULE_INFO_SYM = {
common : {
tag : HARDWARE_MODULE_TAG,
version_major : 1,
version_minor : 0,
id : CAMERA_HARDWARE_MODULE_ID,
name : "orion camera HAL",
author : "Samsung Corporation",
methods : &camera_module_methods,
},
get_number_of_cameras : HAL_getNumberOfCameras,
get_camera_info : HAL_getCameraInfo
};
}
}; // namespace android
| [
"hs1218.kang@samsung.com"
] | hs1218.kang@samsung.com |
7b8b06c232fed805d0f7d92624408434b7777dfe | 1f87e5c08045479291b91770a2b2370c0db97112 | /Src/AutoGenerated/GPUPerfAPICounterGenerator/PublicCounterDefsCLGfx8_Fiji.cpp | ac8ff80adac44df1785835926b46b16c81f6ef11 | [
"MIT"
] | permissive | mstroehle/gpu_performance_api | 08a92ec9023cb84614fd46ff0217ba01f46a11e1 | a8a04214dea25d57bfe7caa1577e02c6940e73c2 | refs/heads/master | 2021-03-27T02:43:06.448132 | 2019-12-13T22:37:23 | 2019-12-13T22:47:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,042 | cpp | //==============================================================================
// Copyright (c) 2010-2019 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief PublicCounterDefinitions for CLGFX8_FIJI
//==============================================================================
#include "GPACounter.h"
#include "PublicCounterDefsCLGfx8_Fiji.h"
// *** Note, this is an auto-generated file. Do not edit. Execute PublicCounterCompiler to rebuild.
#include "GPAHWCounterGfx8_Fiji.h"
namespace CLGfx8_Fiji
{
bool UpdatePublicAsicSpecificCounters(GDT_HW_GENERATION desiredGeneration, GDT_HW_ASIC_TYPE asicType, GPA_DerivedCounters& c)
{
UNREFERENCED_PARAMETER(desiredGeneration);
UNREFERENCED_PARAMETER(c); // Unreferenced if there are no ASIC specific block instance registers
if (!CounterGfx8_Fiji::MatchAsic(asicType))
{
return false;
}
CounterGfx8_Fiji::OverrideBlockInstanceCounters(asicType);
return true;
}
} // namespace CLGfx8_Fiji
| [
"christopher.hesik@amd.com"
] | christopher.hesik@amd.com |
b2a1d894a31c2212922660cd77d2ff7d177e584e | 4702ca170053f7ff8d83312f4f71e95b94570cd5 | /src/qt/bitcoinunits.cpp | 8bc7344e44f020805bb8dc1c3d6b027ee9bd44d2 | [
"MIT"
] | permissive | yahwehtech/izzcoin | cb0e79140228a0c9b6d9a748aeeb4dcaa019df73 | dba4cf0dcb64ac432ec506907094d973b83a4371 | refs/heads/master | 2020-03-28T14:21:08.546150 | 2018-12-21T12:25:48 | 2018-12-21T12:25:48 | 148,480,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,475 | cpp | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("IZZ");
case mBTC: return QString("mIZZ");
case uBTC: return QString::fromUtf8("μIZZ");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("IZZcoins");
case mBTC: return QString("Milli-IZZcoins (1 / 1,000)");
case uBTC: return QString("Micro-IZZcoins (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
| [
"mahesh@blockaitech.com"
] | mahesh@blockaitech.com |
b91c5c14cd0d7877370228d616fbabca4f62a183 | 29be909661dd09bd4aa53a9b26a26bb07cb689fa | /leetcode/prove/levelOrder3.cpp | 6d36507b82be73e61d224696fd6a10221beaafa9 | [] | no_license | 1398978500/study | b66bb23400ba2576e362017479dfcb5802bb7d66 | e635821f59293655b94b651e9d207b6aa0f1bb68 | refs/heads/main | 2023-05-26T12:01:44.691783 | 2023-05-11T15:05:49 | 2023-05-11T15:05:49 | 540,799,753 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,765 | cpp | /*
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
提示:
节点总数 <= 1000
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> vRes;
if(root == nullptr) {
return vRes;
}
queue<TreeNode*> qNode;
qNode.emplace(root);
int iLevel = 0; // 记录第几层 根为第0层
while(!qNode.empty()) {
int len = qNode.size();
vector<int> vLevel(len, 0);
for(int i = 0; i < len; i++) {
int index = i;
// 奇数层则倒序
if((iLevel & 1) == 1) {
index = len - 1 - i;
}
// 记录当前层
auto tmp = qNode.front();
qNode.pop();
vLevel[index] = (tmp->val);
// 添加下一层节点
if(tmp->left != nullptr) {
qNode.emplace(tmp->left);
}
if(tmp->right != nullptr) {
qNode.emplace(tmp->right);
}
}
vRes.emplace_back(vLevel);
iLevel++;
}
return vRes;
}
};
| [
"1398978500@qq.com"
] | 1398978500@qq.com |
8390fe956a8c94b49389c29ee4d9bddec91296d9 | 3008e91f81f419781def2693378af8831cac1cda | /src/bench/ecdsa.cpp | 5c2722e44893cc0c581e8b5e7d949a3ebb11f4aa | [
"MIT"
] | permissive | ZenyattaAbosom/Abosom | 475fa03038117ca94b33c246af09c57c81154ea8 | 9ffa021e92e7c6136c63a4bba0af0a1284a70d98 | refs/heads/master | 2020-12-26T08:33:45.868521 | 2020-08-16T13:46:25 | 2020-08-16T13:46:25 | 237,447,993 | 2 | 2 | MIT | 2020-06-29T16:40:26 | 2020-01-31T14:35:56 | C++ | UTF-8 | C++ | false | false | 2,034 | cpp | // Copyright (c) 2018 The Abosom Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bench.h"
#include "key.h"
static void ECDSASign(benchmark::State& state)
{
std::vector<CKey> keys;
std::vector<uint256> hashes;
for (size_t i = 0; i < 100; i++) {
CKey k;
k.MakeNewKey(false);
keys.emplace_back(k);
hashes.emplace_back(::SerializeHash((int)i));
}
// Benchmark.
size_t i = 0;
while (state.KeepRunning()) {
std::vector<unsigned char> sig;
keys[i].Sign(hashes[i], sig);
i = (i + 1) % keys.size();
}
}
static void ECDSAVerify(benchmark::State& state)
{
std::vector<CPubKey> keys;
std::vector<uint256> hashes;
std::vector<std::vector<unsigned char>> sigs;
for (size_t i = 0; i < 100; i++) {
CKey k;
k.MakeNewKey(false);
keys.emplace_back(k.GetPubKey());
hashes.emplace_back(::SerializeHash((int)i));
std::vector<unsigned char> sig;
k.Sign(hashes[i], sig);
sigs.emplace_back(sig);
}
// Benchmark.
size_t i = 0;
while (state.KeepRunning()) {
keys[i].Verify(hashes[i], sigs[i]);
i = (i + 1) % keys.size();
}
}
static void ECDSAVerify_LargeBlock(benchmark::State& state)
{
std::vector<CPubKey> keys;
std::vector<uint256> hashes;
std::vector<std::vector<unsigned char>> sigs;
for (size_t i = 0; i < 1000; i++) {
CKey k;
k.MakeNewKey(false);
keys.emplace_back(k.GetPubKey());
hashes.emplace_back(::SerializeHash((int)i));
std::vector<unsigned char> sig;
k.Sign(hashes[i], sig);
sigs.emplace_back(sig);
}
// Benchmark.
while (state.KeepRunning()) {
for (size_t i = 0; i < keys.size(); i++) {
keys[i].Verify(hashes[i], sigs[i]);
}
}
}
BENCHMARK(ECDSASign)
BENCHMARK(ECDSAVerify)
BENCHMARK(ECDSAVerify_LargeBlock)
| [
"60512811+ZenyattaAbosom@users.noreply.github.com"
] | 60512811+ZenyattaAbosom@users.noreply.github.com |
986fccaaae054309393b5bbb2ab6a655997af6fa | 27e3f7528bf006126311cf9473cd85f373f6e3dd | /ui/ozone/platform/wayland/host/wayland_connection.cc | 48e7674ae918efb5c81a5e86395ac453c801d68b | [
"BSD-3-Clause"
] | permissive | yuanhui-yang/chromium | 7f1d6c17880290613fedef862f53d52237a0601b | d181eb08e0cf84f6399ef38205f86519914b8f06 | refs/heads/master | 2023-03-10T00:49:57.143282 | 2020-05-07T07:29:03 | 2020-05-07T07:29:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,154 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/ozone/platform/wayland/host/wayland_connection.h"
#include <xdg-shell-client-protocol.h>
#include <xdg-shell-unstable-v6-client-protocol.h>
#include <algorithm>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop_current.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
#include "ui/gfx/swap_result.h"
#include "ui/ozone/platform/wayland/common/wayland_object.h"
#include "ui/ozone/platform/wayland/host/wayland_buffer_manager_host.h"
#include "ui/ozone/platform/wayland/host/wayland_cursor.h"
#include "ui/ozone/platform/wayland/host/wayland_drm.h"
#include "ui/ozone/platform/wayland/host/wayland_event_source.h"
#include "ui/ozone/platform/wayland/host/wayland_input_method_context.h"
#include "ui/ozone/platform/wayland/host/wayland_output_manager.h"
#include "ui/ozone/platform/wayland/host/wayland_pointer.h"
#include "ui/ozone/platform/wayland/host/wayland_shm.h"
#include "ui/ozone/platform/wayland/host/wayland_touch.h"
#include "ui/ozone/platform/wayland/host/wayland_window.h"
#include "ui/ozone/platform/wayland/host/wayland_zwp_linux_dmabuf.h"
namespace ui {
namespace {
constexpr uint32_t kMaxCompositorVersion = 4;
constexpr uint32_t kMaxGtkPrimarySelectionDeviceManagerVersion = 1;
constexpr uint32_t kMaxLinuxDmabufVersion = 3;
constexpr uint32_t kMaxSeatVersion = 4;
constexpr uint32_t kMaxShmVersion = 1;
constexpr uint32_t kMaxXdgShellVersion = 1;
constexpr uint32_t kMaxDeviceManagerVersion = 3;
constexpr uint32_t kMaxWpPresentationVersion = 1;
constexpr uint32_t kMaxTextInputManagerVersion = 1;
constexpr uint32_t kMinWlDrmVersion = 2;
constexpr uint32_t kMinWlOutputVersion = 2;
} // namespace
WaylandConnection::WaylandConnection() = default;
WaylandConnection::~WaylandConnection() = default;
bool WaylandConnection::Initialize() {
static const wl_registry_listener registry_listener = {
&WaylandConnection::Global,
&WaylandConnection::GlobalRemove,
};
display_.reset(wl_display_connect(nullptr));
if (!display_) {
LOG(ERROR) << "Failed to connect to Wayland display";
return false;
}
registry_.reset(wl_display_get_registry(display_.get()));
if (!registry_) {
LOG(ERROR) << "Failed to get Wayland registry";
return false;
}
// Now that the connection with the display server has been properly
// estabilished, initialize the wayland event source.
DCHECK(!event_source_);
event_source_ = std::make_unique<WaylandEventSource>(display_.get());
wl_registry_add_listener(registry_.get(), ®istry_listener, this);
while (!wayland_output_manager_ ||
!wayland_output_manager_->IsOutputReady()) {
wl_display_roundtrip(display_.get());
}
buffer_manager_host_ = std::make_unique<WaylandBufferManagerHost>(this);
if (!compositor_) {
LOG(ERROR) << "No wl_compositor object";
return false;
}
if (!shm_) {
LOG(ERROR) << "No wl_shm object";
return false;
}
if (!shell_v6_ && !shell_) {
LOG(ERROR) << "No Wayland shell found";
return false;
}
// When we are running tests with weston in headless mode, the seat is not
// announced.
if (!seat_)
LOG(WARNING) << "No wl_seat object. The functionality may suffer.";
return true;
}
void WaylandConnection::ScheduleFlush() {
// When we are in tests, the message loop is set later when the
// initialization of the OzonePlatform complete. Thus, just
// flush directly. This doesn't happen in normal run.
if (!base::MessageLoopCurrentForUI::IsSet()) {
Flush();
} else if (!scheduled_flush_) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&WaylandConnection::Flush, base::Unretained(this)));
scheduled_flush_ = true;
}
}
void WaylandConnection::SetCursorBitmap(const std::vector<SkBitmap>& bitmaps,
const gfx::Point& location) {
if (!cursor_)
return;
cursor_->UpdateBitmap(bitmaps, location, serial_);
}
int WaylandConnection::GetKeyboardModifiers() const {
int modifiers = 0;
if (keyboard_)
modifiers = keyboard_->modifiers();
return modifiers;
}
void WaylandConnection::StartDrag(const ui::OSExchangeData& data,
int operation) {
if (!dragdrop_data_source_)
dragdrop_data_source_ = data_device_manager_->CreateSource();
dragdrop_data_source_->Offer(data);
dragdrop_data_source_->SetAction(operation);
data_device_->StartDrag(dragdrop_data_source_->data_source(), data);
}
void WaylandConnection::FinishDragSession(uint32_t dnd_action,
WaylandWindow* source_window) {
if (source_window)
source_window->OnDragSessionClose(dnd_action);
data_device_->ResetSourceData();
dragdrop_data_source_.reset();
}
void WaylandConnection::DeliverDragData(const std::string& mime_type,
std::string* buffer) {
data_device_->DeliverDragData(mime_type, buffer);
}
void WaylandConnection::RequestDragData(
const std::string& mime_type,
base::OnceCallback<void(const std::vector<uint8_t>&)> callback) {
data_device_->RequestDragData(mime_type, std::move(callback));
}
bool WaylandConnection::IsDragInProgress() {
// |data_device_| can be null when running on headless weston.
if (!data_device_)
return false;
return data_device_->IsDragEntered() || drag_data_source();
}
void WaylandConnection::ResetPointerFlags() {
if (pointer_)
pointer_->ResetFlags();
}
void WaylandConnection::Flush() {
wl_display_flush(display_.get());
scheduled_flush_ = false;
}
void WaylandConnection::UpdateInputDevices(wl_seat* seat,
uint32_t capabilities) {
DCHECK(seat);
DCHECK(event_source_);
auto has_pointer = capabilities & WL_SEAT_CAPABILITY_POINTER;
auto has_keyboard = capabilities & WL_SEAT_CAPABILITY_KEYBOARD;
auto has_touch = capabilities & WL_SEAT_CAPABILITY_TOUCH;
if (!has_pointer) {
pointer_.reset();
cursor_.reset();
wayland_cursor_position_.reset();
} else if (wl_pointer* pointer = wl_seat_get_pointer(seat)) {
pointer_ = std::make_unique<WaylandPointer>(
pointer, this, event_source_->GetDispatchCallback());
cursor_ = std::make_unique<WaylandCursor>(pointer_.get(), this);
wayland_cursor_position_ = std::make_unique<WaylandCursorPosition>();
} else {
LOG(ERROR) << "Failed to get wl_pointer from seat";
}
if (!has_keyboard) {
keyboard_.reset();
} else if (wl_keyboard* keyboard = wl_seat_get_keyboard(seat)) {
auto* layout_engine =
KeyboardLayoutEngineManager::GetKeyboardLayoutEngine();
keyboard_ = std::make_unique<WaylandKeyboard>(
keyboard, this, layout_engine, event_source_->GetDispatchCallback());
} else {
LOG(ERROR) << "Failed to get wl_keyboard from seat";
}
if (!has_touch) {
touch_.reset();
} else if (wl_touch* touch = wl_seat_get_touch(seat)) {
touch_ = std::make_unique<WaylandTouch>(
touch, this, event_source_->GetDispatchCallback());
} else {
LOG(ERROR) << "Failed to get wl_touch from seat";
}
}
void WaylandConnection::EnsureDataDevice() {
if (!data_device_manager_ || !seat_)
return;
DCHECK(!data_device_);
wl_data_device* data_device = data_device_manager_->GetDevice();
data_device_ = std::make_unique<WaylandDataDevice>(this, data_device);
if (primary_selection_device_manager_) {
primary_selection_device_ = std::make_unique<GtkPrimarySelectionDevice>(
this, primary_selection_device_manager_->GetDevice());
}
clipboard_ = std::make_unique<WaylandClipboard>(
data_device_manager_.get(), data_device_.get(),
primary_selection_device_manager_.get(), primary_selection_device_.get());
}
// static
void WaylandConnection::Global(void* data,
wl_registry* registry,
uint32_t name,
const char* interface,
uint32_t version) {
static const wl_seat_listener seat_listener = {
&WaylandConnection::Capabilities,
&WaylandConnection::Name,
};
static const xdg_wm_base_listener shell_listener = {
&WaylandConnection::Ping,
};
static const zxdg_shell_v6_listener shell_v6_listener = {
&WaylandConnection::PingV6,
};
WaylandConnection* connection = static_cast<WaylandConnection*>(data);
if (!connection->compositor_ && strcmp(interface, "wl_compositor") == 0) {
connection->compositor_ = wl::Bind<wl_compositor>(
registry, name, std::min(version, kMaxCompositorVersion));
connection->compositor_version_ = version;
if (!connection->compositor_)
LOG(ERROR) << "Failed to bind to wl_compositor global";
} else if (!connection->subcompositor_ &&
strcmp(interface, "wl_subcompositor") == 0) {
connection->subcompositor_ = wl::Bind<wl_subcompositor>(registry, name, 1);
if (!connection->subcompositor_)
LOG(ERROR) << "Failed to bind to wl_subcompositor global";
} else if (!connection->shm_ && strcmp(interface, "wl_shm") == 0) {
wl::Object<wl_shm> shm =
wl::Bind<wl_shm>(registry, name, std::min(version, kMaxShmVersion));
connection->shm_ = std::make_unique<WaylandShm>(shm.release(), connection);
if (!connection->shm_)
LOG(ERROR) << "Failed to bind to wl_shm global";
} else if (!connection->seat_ && strcmp(interface, "wl_seat") == 0) {
connection->seat_ =
wl::Bind<wl_seat>(registry, name, std::min(version, kMaxSeatVersion));
if (!connection->seat_) {
LOG(ERROR) << "Failed to bind to wl_seat global";
return;
}
wl_seat_add_listener(connection->seat_.get(), &seat_listener, connection);
connection->EnsureDataDevice();
} else if (!connection->shell_v6_ &&
strcmp(interface, "zxdg_shell_v6") == 0) {
// Check for zxdg_shell_v6 first.
connection->shell_v6_ = wl::Bind<zxdg_shell_v6>(
registry, name, std::min(version, kMaxXdgShellVersion));
if (!connection->shell_v6_) {
LOG(ERROR) << "Failed to bind to zxdg_shell_v6 global";
return;
}
zxdg_shell_v6_add_listener(connection->shell_v6_.get(), &shell_v6_listener,
connection);
} else if (!connection->shell_v6_ && !connection->shell_ &&
strcmp(interface, "xdg_wm_base") == 0) {
connection->shell_ = wl::Bind<xdg_wm_base>(
registry, name, std::min(version, kMaxXdgShellVersion));
if (!connection->shell_) {
LOG(ERROR) << "Failed to bind to xdg_wm_base global";
return;
}
xdg_wm_base_add_listener(connection->shell_.get(), &shell_listener,
connection);
} else if (base::EqualsCaseInsensitiveASCII(interface, "wl_output")) {
if (version < kMinWlOutputVersion) {
LOG(ERROR)
<< "Unable to bind to the unsupported wl_output object with version= "
<< version << ". Minimum supported version is "
<< kMinWlOutputVersion;
return;
}
wl::Object<wl_output> output = wl::Bind<wl_output>(registry, name, version);
if (!output) {
LOG(ERROR) << "Failed to bind to wl_output global";
return;
}
if (!connection->wayland_output_manager_) {
connection->wayland_output_manager_ =
std::make_unique<WaylandOutputManager>();
}
connection->wayland_output_manager_->AddWaylandOutput(name,
output.release());
} else if (!connection->data_device_manager_ &&
strcmp(interface, "wl_data_device_manager") == 0) {
wl::Object<wl_data_device_manager> data_device_manager =
wl::Bind<wl_data_device_manager>(
registry, name, std::min(version, kMaxDeviceManagerVersion));
if (!data_device_manager) {
LOG(ERROR) << "Failed to bind to wl_data_device_manager global";
return;
}
connection->data_device_manager_ =
std::make_unique<WaylandDataDeviceManager>(
data_device_manager.release(), connection);
connection->EnsureDataDevice();
} else if (!connection->primary_selection_device_manager_ &&
strcmp(interface, "gtk_primary_selection_device_manager") == 0) {
wl::Object<gtk_primary_selection_device_manager> manager =
wl::Bind<gtk_primary_selection_device_manager>(
registry, name, kMaxGtkPrimarySelectionDeviceManagerVersion);
connection->primary_selection_device_manager_ =
std::make_unique<GtkPrimarySelectionDeviceManager>(manager.release(),
connection);
} else if (!connection->zwp_dmabuf_ &&
(strcmp(interface, "zwp_linux_dmabuf_v1") == 0)) {
wl::Object<zwp_linux_dmabuf_v1> zwp_linux_dmabuf =
wl::Bind<zwp_linux_dmabuf_v1>(
registry, name, std::min(version, kMaxLinuxDmabufVersion));
connection->zwp_dmabuf_ = std::make_unique<WaylandZwpLinuxDmabuf>(
zwp_linux_dmabuf.release(), connection);
} else if (!connection->presentation_ &&
(strcmp(interface, "wp_presentation") == 0)) {
connection->presentation_ =
wl::Bind<wp_presentation>(registry, name, kMaxWpPresentationVersion);
} else if (!connection->text_input_manager_v1_ &&
strcmp(interface, "zwp_text_input_manager_v1") == 0) {
connection->text_input_manager_v1_ = wl::Bind<zwp_text_input_manager_v1>(
registry, name, std::min(version, kMaxTextInputManagerVersion));
if (!connection->text_input_manager_v1_) {
LOG(ERROR) << "Failed to bind to zwp_text_input_manager_v1 global";
return;
}
} else if (!connection->drm_ && (strcmp(interface, "wl_drm") == 0) &&
version >= kMinWlDrmVersion) {
auto wayland_drm = wl::Bind<struct wl_drm>(registry, name, version);
connection->drm_ =
std::make_unique<WaylandDrm>(wayland_drm.release(), connection);
}
connection->ScheduleFlush();
}
// static
void WaylandConnection::GlobalRemove(void* data,
wl_registry* registry,
uint32_t name) {
WaylandConnection* connection = static_cast<WaylandConnection*>(data);
// The Wayland protocol distinguishes global objects by unique numeric names,
// which the WaylandOutputManager uses as unique output ids. But, it is only
// possible to figure out, what global object is going to be removed on the
// WaylandConnection::GlobalRemove call. Thus, whatever unique |name| comes,
// it's forwarded to the WaylandOutputManager, which checks if such a global
// output object exists and removes it.
if (connection->wayland_output_manager_)
connection->wayland_output_manager_->RemoveWaylandOutput(name);
}
// static
void WaylandConnection::Capabilities(void* data,
wl_seat* seat,
uint32_t capabilities) {
WaylandConnection* self = static_cast<WaylandConnection*>(data);
DCHECK(self);
self->UpdateInputDevices(seat, capabilities);
self->ScheduleFlush();
}
// static
void WaylandConnection::Name(void* data, wl_seat* seat, const char* name) {}
// static
void WaylandConnection::PingV6(void* data,
zxdg_shell_v6* shell_v6,
uint32_t serial) {
WaylandConnection* connection = static_cast<WaylandConnection*>(data);
zxdg_shell_v6_pong(shell_v6, serial);
connection->ScheduleFlush();
}
// static
void WaylandConnection::Ping(void* data, xdg_wm_base* shell, uint32_t serial) {
WaylandConnection* connection = static_cast<WaylandConnection*>(data);
xdg_wm_base_pong(shell, serial);
connection->ScheduleFlush();
}
} // namespace ui
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
efb905d6e38153942431159f87a16ff8b544d05a | 1df9106e475d7f1b4de615cb4f8122cc93305b7b | /Engine/SearchHierarchy.cpp | 777be66548676111c0c616303fb993f9a85ae1f9 | [] | no_license | mcferront/anttrap-engine | 54517007911389a347e25542c928a0dd4276b730 | c284f7800becaa973101a14bf0b7ffb0d6b732b4 | refs/heads/master | 2021-06-26T08:48:59.814404 | 2019-02-16T05:37:43 | 2019-02-16T05:37:43 | 148,593,261 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,481 | cpp | #include "EnginePch.h"
#include "SearchHierarchy.h"
#include "Viewport.h"
#include "Renderer.h"
#include "RenderObject.h"
#include "Node.h"
#include "Light.h"
#include "MaterialObject.h"
void FrustumCullRenderModifier::Begin( void )
{
m_TotalRenderables = 0;
m_TotalLights = 0;
m_RenderablesCulled = 0;
m_LightsCulled = 0;
}
void FrustumCullRenderModifier::Process(
RendererDesc *pRendererDesc
)
{
Frustum frustum;
pRendererDesc->viewport.GetCamera( )->GetFrustum( &frustum );
m_Renderables.Clear( );
m_Renderables.CopyFrom( pRendererDesc->renderObjectDescs );
m_Lights.Clear( );
m_Lights.CopyFrom( pRendererDesc->lightDescs );
m_TotalRenderables += m_Renderables.GetSize( );
m_TotalLights += m_Lights.GetSize( );
pRendererDesc->renderObjectDescs.Clear( );
pRendererDesc->lightDescs.Clear( );
for ( uint32 i = 0; i < m_Renderables.GetSize( ); i++ )
{
RenderObjectDesc *pDesc = m_Renderables.GetAt( i );
if ( true == m_Renderables.GetAt( i )->pObject->IsVisible(frustum) )
pRendererDesc->renderObjectDescs.Add( pDesc );
else
++m_RenderablesCulled;
}
for ( uint32 i = 0; i < m_Lights.GetSize( ); i++ )
{
LightDesc *pDesc = m_Lights.GetPointer( i );
if ( true == pDesc->pLight->IsVisible(frustum) )
pRendererDesc->lightDescs.Add( *pDesc );
else
++m_LightsCulled;
}
}
void TransparentSortRenderModifier::Begin( void )
{
}
void TransparentSortRenderModifier::Process(
RendererDesc *pRendererDesc
)
{
m_Renderables.Clear( );
m_Renderables.CopyFrom( pRendererDesc->renderObjectDescs );
pRendererDesc->renderObjectDescs.Clear( );
uint32 i;
for ( i = 0; i < m_Renderables.GetSize( ); i++ )
{
RenderObjectDesc *pDesc = m_Renderables.GetAt( i );
if ( false == pDesc->pMaterial->HasAlpha(pRendererDesc->pPass) )
pRendererDesc->renderObjectDescs.Add( pDesc );
}
uint32 start = pRendererDesc->renderObjectDescs.GetSize( );
uint32 zNewCount = m_Renderables.GetSize( ) - start;
if ( zNewCount > m_ZOldCount )
{
m_ZOldCount = zNewCount;
m_pZOrders = (ZOrder *) realloc( m_pZOrders, zNewCount * sizeof( ZOrder ) );
}
Vector look = pRendererDesc->viewport.GetCamera( )->GetWorldTransform( )->GetLook( );
Vector cam = pRendererDesc->viewport.GetCamera( )->GetWorldTransform( )->GetTranslation( );
int index = 0;
Transform worldTransform;
//Gather up pivot distance from camera
for ( i = 0; i < m_Renderables.GetSize( ); i++ )
{
RenderObjectDesc *pDesc = pRendererDesc->renderObjectDescs.GetAt( i );
if ( true == pDesc->pMaterial->HasAlpha(pRendererDesc->pPass) )
{
pDesc->pObject->GetWorldTransform( &worldTransform );
Vector p = worldTransform.GetTranslation( );
float z = Math::DotProduct( look, p - cam );
ZOrder zOrder = { m_Renderables.GetAt( i ), z };
m_pZOrders[ index++ ] = zOrder;
}
}
//Sort by pivot distance from camera
qsort( m_pZOrders, zNewCount, sizeof( ZOrder ), ZCompare );
//Add sorted back to the end of the render list
for ( i = 0; i < zNewCount; i++ )
pRendererDesc->renderObjectDescs.Add( m_pZOrders[ i ].pObject );
}
int TransparentSortRenderModifier::ZCompare( const void *pA, const void *pB )
{
float d = ( (ZOrder *) pA )->z - ( (ZOrder *) pB )->z;
if ( d < 0 ) return 1;
if ( d > 0 ) return -1;
return 0;
}
| [
"trapper@trapzz.com"
] | trapper@trapzz.com |
91f55d620d6e02020f4969328e44b7debbf3c8ec | 4487c896b6844cc41824f8e4a55fedb8dc1f6e4f | /cpp/Graph/euler_path_and_cycle.cpp | bba9c7094aa1d308033c780134b39ea2b6be3fbd | [] | no_license | arjan-bal/competitive-coding-library | 3ba2db1d3a740e7e96aab978207aa949904f1186 | 7df28eabff6d178d13133413998a400171d4b858 | refs/heads/master | 2023-07-21T10:00:01.797981 | 2023-07-16T19:53:42 | 2023-07-16T19:53:42 | 197,349,165 | 19 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 1,427 | cpp | /*
Finds Euler Path / Cycle in O(M + N)
Remember to call reset before finding answer
Path will be present in ans
ans will contain the edge ids of the path
*/
int n, m;
vector<pair<int, int>> edges;
vector<bool> used;
vector<int> ans, pos;
vector<int> adj[N];
void reset()
{
ans.clear();
pos.assign(n + 1, 0);
used.assign(m, 0);
}
// returns other side of edge
int getOther(int id, int v)
{
return edges[id].first ^ edges[id].second ^ v;
}
// finds euler path/cycle ending at v
// for cycle check that oddCount in checkEuler is 0
void dfs(int v)
{
// need to keep pos array since we might
// visit v again, wouldn't want to start over
while(pos[v] < (int)adj[v].size()) {
int id = adj[v][pos[v]];
pos[v]++;
if (used[id]) continue;
used[id] = 1;
dfs(getOther(id, v));
ans.pb(id);
}
}
vector<int> getVertices(int ending, vector<int> edges)
{
vector<int> path;
reverse(all(edges));
int cur = ending;
ans.pb(cur);
for (auto i : edges) {
cur = getOther(i, cur);
path.pb(cur);
}
reverse(all(path));
return path;
}
void checkEuler(int src)
{
int oddCount = 0;
for (int i = 1; i <= n; ++i) {
bool parity = 0;
for (auto j : adj[i]) {
parity ^= !used[j];
}
if (parity && i != src) ++oddCount;
}
if (oddCount > 1) return ;
// oddCount of 1 => src is definately odd parity
// since sum of degrees of all vertices is even = 2 * |E|
// oddCount 0 => Euler Cycle
dfs(src);
} | [
"arjan.bal@nutanix.com"
] | arjan.bal@nutanix.com |
faeccff51cf3e007e59d73cc8426f499a2f73471 | b58d9d9b12114fa967db026061cb00facfea26a5 | /catkin_wkspace/devel/include/ex/ex_srvRequest.h | 95c7eafdd2e487a610a42c88b08b684fd366106b | [] | no_license | caseroboticsclub/case-nasa | 95e11a70eb7c22912c48607b627d0e4f65e94c0b | 9dcb94129069a36f3e0bdd590d78a007a4dbaee0 | refs/heads/master | 2016-09-05T16:53:54.696811 | 2015-05-13T20:37:25 | 2015-05-13T20:37:25 | 31,144,175 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,890 | h | // Generated by gencpp from file ex/ex_srvRequest.msg
// DO NOT EDIT!
#ifndef EX_MESSAGE_EX_SRVREQUEST_H
#define EX_MESSAGE_EX_SRVREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace ex
{
template <class ContainerAllocator>
struct ex_srvRequest_
{
typedef ex_srvRequest_<ContainerAllocator> Type;
ex_srvRequest_()
: first(0)
, second(0) {
}
ex_srvRequest_(const ContainerAllocator& _alloc)
: first(0)
, second(0) {
}
typedef int32_t _first_type;
_first_type first;
typedef int32_t _second_type;
_second_type second;
typedef boost::shared_ptr< ::ex::ex_srvRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::ex::ex_srvRequest_<ContainerAllocator> const> ConstPtr;
}; // struct ex_srvRequest_
typedef ::ex::ex_srvRequest_<std::allocator<void> > ex_srvRequest;
typedef boost::shared_ptr< ::ex::ex_srvRequest > ex_srvRequestPtr;
typedef boost::shared_ptr< ::ex::ex_srvRequest const> ex_srvRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::ex::ex_srvRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::ex::ex_srvRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace ex
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'ex': ['/home/saruman/workspaces/ros_workspace/case_robotics/nasa/catkin_wkspace/src/ex/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::ex::ex_srvRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::ex::ex_srvRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ex::ex_srvRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ex::ex_srvRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ex::ex_srvRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ex::ex_srvRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::ex::ex_srvRequest_<ContainerAllocator> >
{
static const char* value()
{
return "05577f62131ad26921bff0de6b2cb722";
}
static const char* value(const ::ex::ex_srvRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x05577f62131ad269ULL;
static const uint64_t static_value2 = 0x21bff0de6b2cb722ULL;
};
template<class ContainerAllocator>
struct DataType< ::ex::ex_srvRequest_<ContainerAllocator> >
{
static const char* value()
{
return "ex/ex_srvRequest";
}
static const char* value(const ::ex::ex_srvRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::ex::ex_srvRequest_<ContainerAllocator> >
{
static const char* value()
{
return "\n\
int32 first\n\
int32 second\n\
";
}
static const char* value(const ::ex::ex_srvRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::ex::ex_srvRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.first);
stream.next(m.second);
}
ROS_DECLARE_ALLINONE_SERIALIZER;
}; // struct ex_srvRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::ex::ex_srvRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ex::ex_srvRequest_<ContainerAllocator>& v)
{
s << indent << "first: ";
Printer<int32_t>::stream(s, indent + " ", v.first);
s << indent << "second: ";
Printer<int32_t>::stream(s, indent + " ", v.second);
}
};
} // namespace message_operations
} // namespace ros
#endif // EX_MESSAGE_EX_SRVREQUEST_H
| [
"rmf61@cas.edu"
] | rmf61@cas.edu |
05a797e483524df9b76026b3bc8e9e3e214f89ce | f3e813535f75fb461e2306f1ad18596ac233e758 | /odb_api_bundle-0.17.6-Source/eckit/src/eckit/io/DblBuffer.cc | c1de63c9b901bb787d47a15f09a1f8c329d93b2b | [
"Apache-2.0"
] | permissive | vyesubabu/metview | 47f9de3eb5f1bf418e513ed306aa2279635b79c7 | 74c2b9bc28673001fd02e00194e92c53a897fb62 | refs/heads/master | 2021-05-17T16:42:41.697859 | 2018-04-09T15:08:19 | 2018-04-09T15:08:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,208 | cc | /*
* (C) Copyright 1996-2017 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include "eckit/thread/AutoLock.h"
#include "eckit/io/Buffer.h"
#include "eckit/log/Bytes.h"
#include "eckit/io/DblBuffer.h"
#include "eckit/log/Log.h"
#include "eckit/thread/MutexCond.h"
#include "eckit/log/Progress.h"
#include "eckit/thread/Thread.h"
#include "eckit/thread/ThreadControler.h"
#include "eckit/log/Timer.h"
#include "eckit/runtime/Monitor.h"
//-----------------------------------------------------------------------------
namespace eckit {
//-----------------------------------------------------------------------------
class DblBufferError : public Exception {
public:
DblBufferError(const std::string& what)
{
reason(std::string("Double buffer error: ") + what);
}
};
struct OneBuffer {
MutexCond cond_;
bool full_;
long length_;
char* buffer_;
OneBuffer():
full_(false), length_(0), buffer_(0) {}
};
class DblBufferTask : public Thread {
DblBuffer& owner_;
DataHandle& out_;
Length estimate_;
OneBuffer* buffers_;
long parent_;
public:
DblBufferTask(DataHandle&, DblBuffer&, OneBuffer*, const Length&, long parent);
virtual void run();
};
DblBuffer::DblBuffer(long count, long size, TransferWatcher& watcher):
count_(count),
bufSize_(size),
error_(false),
restart_(false),
restartFrom_(0),
watcher_(watcher)
{
Log::info() << "Double buffering: " <<
count_ << " buffers of " << Bytes(size) << " is " << Bytes(count * size)
<< std::endl;
}
DblBuffer::~DblBuffer()
{
}
inline void DblBuffer::error(const std::string& why)
{
AutoLock<Mutex> lock(mutex_);
error_ = true;
why_ = why;
}
inline bool DblBuffer::error()
{
AutoLock<Mutex> lock(mutex_);
return error_;
}
void DblBuffer::restart(RestartTransfer& retry)
{
AutoLock<Mutex> lock(mutex_);
Log::warning() << "Retrying transfer from " << retry.from()
<< " (" << Bytes(retry.from()) << ")" << std::endl;
error_ = true;
restart_ = true;
restartFrom_ = retry.from();
}
Length DblBuffer::copy(DataHandle& in, DataHandle& out)
{
Timer timer("Double buffer");
in.compress();
Length estimate = in.openForRead(); AutoClose c1(in);
out.openForWrite(estimate); AutoClose c2(out);
Length total = estimate;
bool more = true;
while (more)
{
more = false;
try {
Length copied = copy(in, out, estimate);
Log::info() << "Copied: " << copied << ", estimate: " << estimate << std::endl;
ASSERT(copied == estimate);
}
catch (RestartTransfer& retry)
{
Log::warning() << "Retrying transfer from " << retry.from() << " (" << Bytes(retry.from()) << ")" << std::endl;
in.restartReadFrom(retry.from());
out.restartWriteFrom(retry.from());
estimate = total - retry.from();
more = true;
}
}
Log::info() << "Transfer rate " << Bytes(estimate, timer) << std::endl;
return total;
}
Length DblBuffer::copy(DataHandle& in, DataHandle& out, const Length& estimate)
{
Buffer bigbuf(count_ * bufSize_);
OneBuffer* buffers = new OneBuffer[count_];
char *addr = bigbuf;
for (int j = 0; j < count_; j++)
{
buffers[j].buffer_ = addr;
addr += bufSize_;
}
Progress progress("Reading data", 0, estimate);
error_ = false;
inBytes_ = outBytes_ = 0;
ThreadControler thread(new DblBufferTask(out, *this, buffers, estimate, Monitor::instance().self()), false);
thread.start();
int i = 0;
Timer reader("Double buffer reader");
double rate = 0;
double first = 0;
watcher_.watch(0, 0);
while (!error())
{
Log::message() << "Wait " << i << std::endl;
AutoLock<MutexCond> lock(buffers[i].cond_);
while (buffers[i].full_)
buffers[i].cond_.wait();
if (error())
break;
Log::message() << "Read " << i << std::endl;
try {
double x = reader.elapsed();
buffers[i].length_ = in.read(buffers[i].buffer_, bufSize_);
double s = reader.elapsed() - x;
Log::status() << Bytes(estimate) << " at " << Bytes(buffers[i].length_ / s) << "/s" << std::endl;
rate += s;
if (first == 0) first = rate;
watcher_.watch(buffers[i].buffer_, buffers[i].length_);
}
catch (RestartTransfer& retry)
{
Log::warning() << "RestartTransfer: Exiting reader thread" << std::endl;
buffers[i].length_ = -1;
restart(retry);
}
catch (std::exception& e)
{
Log::error() << "** " << e.what()
<< " Caught in " << Here() << std::endl;
Log::error() << "** Exception is handled" << std::endl;
buffers[i].length_ = -1;
error(e.what());
}
Log::message() << "" << std::endl;
buffers[i].full_ = true;
if (buffers[i].length_ == 0)
{
buffers[i].cond_.signal();
break;
}
if (buffers[i].length_ < 0)
{
ASSERT(error());
Log::warning() << "Read error... " << why_ << std::endl;
buffers[i].cond_.signal();
break;
}
inBytes_ += buffers[i].length_;
progress(inBytes_);
buffers[i].cond_.signal();
i++;
i %= count_;
}
Log::info() << "Read done " << Bytes(inBytes_) << std::endl;
Log::info() << "Read rate " << Bytes(inBytes_ / rate) << "/s" << std::endl;
if (first != rate)
Log::info() << "Read rate no mount " << Bytes(inBytes_ / (rate - first)) << "/s" << std::endl;
thread.wait();
delete[] buffers;
if (error_) {
if (restart_) throw RestartTransfer(restartFrom_);
throw DblBufferError(why_);
}
PANIC(inBytes_ != outBytes_);
return inBytes_;
}
DblBufferTask::DblBufferTask(DataHandle& out, DblBuffer& owner, OneBuffer* buffers,
const Length& estimate,
long parent):
Thread(false),
owner_(owner),
out_(out),
estimate_(estimate),
buffers_(buffers),
parent_(parent)
{
}
void DblBufferTask::run()
{
Monitor::instance().parent(parent_);
Log::status() << "Double buffering " << Bytes(estimate_) << std::endl;
Progress progress("Writing data", 0, estimate_);
int i = 0;
Timer writer("Double buffer writer");
double rate = 0;
double first = 0;
while (!owner_.error())
{
Log::message() << "Wait " << i << std::endl;
AutoLock<MutexCond> lock(buffers_[i].cond_);
while (!buffers_[i].full_)
buffers_[i].cond_.wait();
if (owner_.error())
break;
if (buffers_[i].length_ == 0)
break;
long length = -1;
Log::message() << "Write " << i << std::endl;
try {
double x = writer.elapsed();
length = out_.write(buffers_[i].buffer_, buffers_[i].length_);
double s = writer.elapsed() - x;
Log::status() << Bytes(buffers_[i].length_ / s) << "/s" << std::endl;
rate += s;
if (first == 0) first = rate;
ASSERT(length == buffers_[i].length_);
}
catch (RestartTransfer& retry)
{
Log::warning() << "RestartTransfer: Exiting writer thread" << std::endl;
length = -1;
owner_.restart(retry);
}
catch (std::exception& e)
{
Log::error() << "** " << e.what() << " Caught in " <<
Here() << std::endl;
Log::error() << "** Exception is handled" << std::endl;
length = -1;
owner_.error(e.what());
}
Log::message() << "" << std::endl;
buffers_[i].full_ = false;
if (length < 0)
{
ASSERT(owner_.error());
buffers_[i].cond_.signal();
break;
}
ASSERT(length == buffers_[i].length_);
owner_.outBytes_ += length;
progress(owner_.outBytes_);
buffers_[i].cond_.signal();
i++;
i %= owner_.count_;
}
Log::info() << "Write done " << Bytes(owner_.outBytes_) << std::endl;
Log::info() << "Write rate " << Bytes(owner_.outBytes_ / rate) << "/s" << std::endl;
if (rate != first)
Log::info() << "Write rate no mount " << Bytes(owner_.outBytes_ / (rate - first)) << "/s" << std::endl;
}
//-----------------------------------------------------------------------------
} // namespace eckit
| [
"Xin.L.Zhang@noaa.gov"
] | Xin.L.Zhang@noaa.gov |
c66c133bc27deafb6555d55cebb332c6c86afa3e | 145f9616480e621b5ec5f16c21d4dcf4b7be27da | /entities/Nexus.hpp | b2e5492222d01733f786181a0139ebed1b122fe2 | [] | no_license | DavidSaxon/Advanced-Evolutionary-Tatics-LD24 | 4821eaf8b6fc7068fe3ca3059435b9312d852da5 | c5a7ed6390780e972cc062f5b60877f7efa0218d | refs/heads/master | 2016-09-05T20:27:56.842691 | 2012-08-26T23:29:44 | 2012-08-26T23:29:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | hpp | /*********************************************************\
| The nexus is where the units for each team are produced |
\*********************************************************/
#ifndef _NEXUS_H_
#define _NEXUS_H_
#include <iostream>
#include <math.h>
#include "../Entity.hpp"
using namespace std;
class Nexus : public Entity {
private:
//VARIABLES
GLuint* bodyTex; //the main texture of the nexus
GLuint* colourTex; //the nexus colour texture
public:
//CONSTRUCTOR
Nexus(int x, int y, bool p, GLuint* tb, GLuint* tc);
//DESTRUCTOR
~Nexus();
//FUNCTIONS
/*update the nexus*/
void update();
/*draw the nexus*/
void draw(int offsetX, int offsetY);
};
#endif
| [
"david.saxon@windowslive.com"
] | david.saxon@windowslive.com |
7aa91f11a1fb967837827b172be297465f3fa4b4 | 22658e2f8e87cf0567bce0fa99108fc7d9cd24a6 | /src/segmenter/cws_module/lexicon_feature_layer.h | 9e6c049bad42239356e35164431509bb059d2a86 | [] | no_license | zldeng/sequence-labeling-by-nn | 78c4c18d1d1ff6b99296d3f7a094eca2d616902c | 6436f3b93dda8f0a97631408f4a8db8920bd3cfc | refs/heads/master | 2021-06-17T18:03:59.349615 | 2017-02-12T08:20:45 | 2017-02-12T08:20:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,212 | h | #ifndef SLNN_SEGMENTER_CWS_MODULE_LEXICON_FEATURE_LAYER_H_
#define SLNN_SEGMENTER_CWS_MODULE_LEXICON_FEATURE_LAYER_H_
#include "lexicon_feature.h"
#include "dynet/dynet.h"
#include "dynet/expr.h"
namespace slnn{
class LexiconFeatureLayer
{
public :
LexiconFeatureLayer(dynet::Model *dynet_m, unsigned start_here_dict_size, unsigned start_here_dim,
unsigned pass_here_dict_size, unsigned pass_here_dim,
unsigned end_here_dict_size, unsigned end_here_dim);
LexiconFeatureLayer(dynet::Model *dynet_m, const LexiconFeature &lexicon_feature);
void new_graph(dynet::ComputationGraph &cg);
dynet::expr::Expression build_lexicon_feature(const LexiconFeatureData &lexicon_feature);
void build_lexicon_feature(const LexiconFeatureDataSeq &lexicon_feature_seq,
std::vector<dynet::expr::Expression> &lexicon_feature_exprs);
private:
dynet::LookupParameter start_here_lookup_param;
dynet::LookupParameter pass_here_lookup_param;
dynet::LookupParameter end_here_lookup_param;
dynet::ComputationGraph *pcg;
};
inline
void LexiconFeatureLayer::new_graph(dynet::ComputationGraph &cg)
{
pcg = &cg;
}
inline
dynet::expr::Expression LexiconFeatureLayer::build_lexicon_feature(const LexiconFeatureData &lexicon_feature_data)
{
return dynet::expr::concatenate({
dynet::expr::lookup(*pcg, start_here_lookup_param, lexicon_feature_data.get_start_here_feature_index()),
dynet::expr::lookup(*pcg, pass_here_lookup_param, lexicon_feature_data.get_pass_here_feature_index()),
dynet::expr::lookup(*pcg, end_here_lookup_param, lexicon_feature_data.get_end_here_feature_index())
});
}
inline
void LexiconFeatureLayer::build_lexicon_feature(const LexiconFeatureDataSeq &lexicon_feature_seq,
std::vector<dynet::expr::Expression> &lexicon_feature_exprs)
{
using std::swap;
size_t seq_len = lexicon_feature_seq.size();
std::vector<dynet::expr::Expression> tmp_lexicon_feature_exprs(seq_len);
for( size_t i = 0; i < seq_len; ++i )
{
tmp_lexicon_feature_exprs[i] = build_lexicon_feature(lexicon_feature_seq[i]);
}
swap(lexicon_feature_exprs, tmp_lexicon_feature_exprs);
}
} // end of namespace slnn
#endif | [
"readonlyfile@hotmail.com"
] | readonlyfile@hotmail.com |
a4d5e84ca0e3d3572e77114be30bb860515d2935 | fd7d1350eefac8a9bbd952568f074284663f2794 | /dds/DCPS/transport/multicast/MulticastSessionFactory.cpp | 095de1944f9986babe7b3b1737a6996729509fbf | [
"MIT"
] | permissive | binary42/OCI | 4ceb7c4ed2150b4edd0496b2a06d80f623a71a53 | 08191bfe4899f535ff99637d019734ed044f479d | refs/heads/master | 2020-06-02T08:58:51.021571 | 2015-09-06T03:25:05 | 2015-09-06T03:25:05 | 41,980,019 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | cpp | /*
* $Id: MulticastSessionFactory.cpp 4223 2011-02-04 23:01:46Z mitza $
*
*
* Distributed under the OpenDDS License.
* See: http://www.opendds.org/license.html
*/
#include "MulticastSessionFactory.h"
namespace OpenDDS {
namespace DCPS {
MulticastSessionFactory::~MulticastSessionFactory()
{
}
} // namespace DCPS
} // namespace OpenDDS
| [
"jimbolysses@gmail.com"
] | jimbolysses@gmail.com |
c9f91e48cc34f6391c014a70285b9fa3f0020fc1 | 7942bdac0f71f9b6abb2dc085393172f3bbc4d02 | /src/httpserver.cpp | 7318278ded2e7a6b520088c8f751bf404c9c7346 | [
"MIT"
] | permissive | Nabbers/BitTrivia | cae20b1d0528279dba0b4ed5044b863637df1700 | 23c5d2d35c3bd6377578c21380acf67e2573d45b | refs/heads/master | 2020-03-17T07:52:51.134148 | 2018-05-17T15:23:41 | 2018-05-17T15:23:41 | 133,416,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,417 | cpp | // Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "httpserver.h"
#include "chainparamsbase.h"
#include "compat.h"
#include "util.h"
#include "netbase.h"
#include "rpc/protocol.h" // For HTTP status codes
#include "sync.h"
#include "ui_interface.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/thread.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h>
#ifdef EVENT__HAVE_NETINET_IN_H
#include <netinet/in.h>
#ifdef _XOPEN_SOURCE_EXTENDED
#include <arpa/inet.h>
#endif
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
/** Maximum size of http request (request line + headers) */
static const size_t MAX_HEADERS_SIZE = 8192;
/** HTTP request work item */
class HTTPWorkItem : public HTTPClosure
{
public:
HTTPWorkItem(HTTPRequest* req, const std::string &path, const HTTPRequestHandler& func):
req(req), path(path), func(func)
{
}
void operator()()
{
func(req.get(), path);
}
boost::scoped_ptr<HTTPRequest> req;
private:
std::string path;
HTTPRequestHandler func;
};
/** Simple work queue for distributing work over multiple threads.
* Work items are simply callable objects.
*/
template <typename WorkItem>
class WorkQueue
{
private:
/** Mutex protects entire object */
CWaitableCriticalSection cs;
CConditionVariable cond;
/* XXX in C++11 we can use std::unique_ptr here and avoid manual cleanup */
std::deque<WorkItem*> queue;
bool running;
size_t maxDepth;
int numThreads;
/** RAII object to keep track of number of running worker threads */
class ThreadCounter
{
public:
WorkQueue &wq;
ThreadCounter(WorkQueue &w): wq(w)
{
boost::lock_guard<boost::mutex> lock(wq.cs);
wq.numThreads += 1;
}
~ThreadCounter()
{
boost::lock_guard<boost::mutex> lock(wq.cs);
wq.numThreads -= 1;
wq.cond.notify_all();
}
};
public:
WorkQueue(size_t maxDepth) : running(true),
maxDepth(maxDepth),
numThreads(0)
{
}
/*( Precondition: worker threads have all stopped
* (call WaitExit)
*/
~WorkQueue()
{
while (!queue.empty()) {
delete queue.front();
queue.pop_front();
}
}
/** Enqueue a work item */
bool Enqueue(WorkItem* item)
{
boost::unique_lock<boost::mutex> lock(cs);
if (queue.size() >= maxDepth) {
return false;
}
queue.push_back(item);
cond.notify_one();
return true;
}
/** Thread function */
void Run()
{
ThreadCounter count(*this);
while (true) {
WorkItem* i = 0;
{
boost::unique_lock<boost::mutex> lock(cs);
while (running && queue.empty())
cond.wait(lock);
if (!running)
break;
i = queue.front();
queue.pop_front();
}
(*i)();
delete i;
}
}
/** Interrupt and exit loops */
void Interrupt()
{
boost::unique_lock<boost::mutex> lock(cs);
running = false;
cond.notify_all();
}
/** Wait for worker threads to exit */
void WaitExit()
{
boost::unique_lock<boost::mutex> lock(cs);
while (numThreads > 0){
cond.wait(lock);
}
}
/** Return current depth of queue */
size_t Depth()
{
boost::unique_lock<boost::mutex> lock(cs);
return queue.size();
}
};
struct HTTPPathHandler
{
HTTPPathHandler() {}
HTTPPathHandler(std::string prefix, bool exactMatch, HTTPRequestHandler handler):
prefix(prefix), exactMatch(exactMatch), handler(handler)
{
}
std::string prefix;
bool exactMatch;
HTTPRequestHandler handler;
};
/** HTTP module state */
//! libevent event loop
static struct event_base* eventBase = 0;
//! HTTP server
struct evhttp* eventHTTP = 0;
//! List of subnets to allow RPC connections from
static std::vector<CSubNet> rpc_allow_subnets;
//! Work queue for handling longer requests off the event loop thread
static WorkQueue<HTTPClosure>* workQueue = 0;
//! Handlers for (sub)paths
std::vector<HTTPPathHandler> pathHandlers;
//! Bound listening sockets
std::vector<evhttp_bound_socket *> boundSockets;
/** Check if a network address is allowed to access the HTTP server */
static bool ClientAllowed(const CNetAddr& netaddr)
{
if (!netaddr.IsValid())
return false;
BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets)
if (subnet.Match(netaddr))
return true;
return false;
}
/** Initialize ACL list for HTTP server */
static bool InitHTTPAllowList()
{
rpc_allow_subnets.clear();
CNetAddr localv4;
CNetAddr localv6;
LookupHost("127.0.0.1", localv4, false);
LookupHost("::1", localv6, false);
rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
if (mapMultiArgs.count("-rpcallowip")) {
const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH (std::string strAllow, vAllow) {
CSubNet subnet;
LookupSubNet(strAllow.c_str(), subnet);
if (!subnet.IsValid()) {
uiInterface.ThreadSafeMessageBox(
strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow),
"", CClientUIInterface::MSG_ERROR);
return false;
}
rpc_allow_subnets.push_back(subnet);
}
}
std::string strAllowed;
BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets)
strAllowed += subnet.ToString() + " ";
LogPrint("http", "Allowing HTTP connections from: %s\n", strAllowed);
return true;
}
/** HTTP request method as string - use for logging only */
static std::string RequestMethodString(HTTPRequest::RequestMethod m)
{
switch (m) {
case HTTPRequest::GET:
return "GET";
break;
case HTTPRequest::POST:
return "POST";
break;
case HTTPRequest::HEAD:
return "HEAD";
break;
case HTTPRequest::PUT:
return "PUT";
break;
default:
return "unknown";
}
}
/** HTTP request callback */
static void http_request_cb(struct evhttp_request* req, void* arg)
{
std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
LogPrint("http", "Received a %s request for %s from %s\n",
RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
// Early address-based allow check
if (!ClientAllowed(hreq->GetPeer())) {
hreq->WriteReply(HTTP_FORBIDDEN);
return;
}
// Early reject unknown HTTP methods
if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
hreq->WriteReply(HTTP_BADMETHOD);
return;
}
// Find registered handler for prefix
std::string strURI = hreq->GetURI();
std::string path;
std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
for (; i != iend; ++i) {
bool match = false;
if (i->exactMatch)
match = (strURI == i->prefix);
else
match = (strURI.substr(0, i->prefix.size()) == i->prefix);
if (match) {
path = strURI.substr(i->prefix.size());
break;
}
}
// Dispatch to worker thread
if (i != iend) {
std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(hreq.release(), path, i->handler));
assert(workQueue);
if (workQueue->Enqueue(item.get()))
item.release(); /* if true, queue took ownership */
else
item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
} else {
hreq->WriteReply(HTTP_NOTFOUND);
}
}
/** Callback to reject HTTP requests after shutdown. */
static void http_reject_request_cb(struct evhttp_request* req, void*)
{
LogPrint("http", "Rejecting request while shutting down\n");
evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
}
/** Event dispatcher thread */
static void ThreadHTTP(struct event_base* base, struct evhttp* http)
{
RenameThread("bittrivia-http");
LogPrint("http", "Entering http event loop\n");
event_base_dispatch(base);
// Event loop will be interrupted by InterruptHTTPServer()
LogPrint("http", "Exited http event loop\n");
}
/** Bind HTTP server to specified addresses */
static bool HTTPBindAddresses(struct evhttp* http)
{
int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
std::vector<std::pair<std::string, uint16_t> > endpoints;
// Determine what addresses to bind to
if (!mapArgs.count("-rpcallowip")) { // Default to loopback if not allowing external IPs
endpoints.push_back(std::make_pair("::1", defaultPort));
endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
if (mapArgs.count("-rpcbind")) {
LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
}
} else if (mapArgs.count("-rpcbind")) { // Specific bind address
const std::vector<std::string>& vbind = mapMultiArgs["-rpcbind"];
for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
int port = defaultPort;
std::string host;
SplitHostPort(*i, port, host);
endpoints.push_back(std::make_pair(host, port));
}
} else { // No specific bind address specified, bind to any
endpoints.push_back(std::make_pair("::", defaultPort));
endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
}
// Bind addresses
for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
LogPrint("http", "Binding RPC on address %s port %i\n", i->first, i->second);
evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second);
if (bind_handle) {
boundSockets.push_back(bind_handle);
} else {
LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
}
}
return !boundSockets.empty();
}
/** Simple wrapper to set thread name and run work queue */
static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
{
RenameThread("bittrivia-httpworker");
queue->Run();
}
/** libevent event log callback */
static void libevent_log_cb(int severity, const char *msg)
{
#ifndef EVENT_LOG_WARN
// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
# define EVENT_LOG_WARN _EVENT_LOG_WARN
#endif
if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
LogPrintf("libevent: %s\n", msg);
else
LogPrint("libevent", "libevent: %s\n", msg);
}
bool InitHTTPServer()
{
struct evhttp* http = 0;
struct event_base* base = 0;
if (!InitHTTPAllowList())
return false;
if (GetBoolArg("-rpcssl", false)) {
uiInterface.ThreadSafeMessageBox(
"SSL mode for RPC (-rpcssl) is no longer supported.",
"", CClientUIInterface::MSG_ERROR);
return false;
}
// Redirect libevent's logging to our own log
event_set_log_callback(&libevent_log_cb);
#if LIBEVENT_VERSION_NUMBER >= 0x02010100
// If -debug=libevent, set full libevent debugging.
// Otherwise, disable all libevent debugging.
if (LogAcceptCategory("libevent"))
event_enable_debug_logging(EVENT_DBG_ALL);
else
event_enable_debug_logging(EVENT_DBG_NONE);
#endif
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
base = event_base_new(); // XXX RAII
if (!base) {
LogPrintf("Couldn't create an event_base: exiting\n");
return false;
}
/* Create a new evhttp object to handle requests. */
http = evhttp_new(base); // XXX RAII
if (!http) {
LogPrintf("couldn't create evhttp. Exiting.\n");
event_base_free(base);
return false;
}
evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
evhttp_set_max_body_size(http, MAX_SIZE);
evhttp_set_gencb(http, http_request_cb, NULL);
if (!HTTPBindAddresses(http)) {
LogPrintf("Unable to bind any endpoint for RPC server\n");
evhttp_free(http);
event_base_free(base);
return false;
}
LogPrint("http", "Initialized HTTP server\n");
int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
eventBase = base;
eventHTTP = http;
return true;
}
boost::thread threadHTTP;
bool StartHTTPServer()
{
LogPrint("http", "Starting HTTP server\n");
int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
threadHTTP = boost::thread(boost::bind(&ThreadHTTP, eventBase, eventHTTP));
for (int i = 0; i < rpcThreads; i++)
boost::thread(boost::bind(&HTTPWorkQueueRun, workQueue));
return true;
}
void InterruptHTTPServer()
{
LogPrint("http", "Interrupting HTTP server\n");
if (eventHTTP) {
// Unlisten sockets
BOOST_FOREACH (evhttp_bound_socket *socket, boundSockets) {
evhttp_del_accept_socket(eventHTTP, socket);
}
// Reject requests on current connections
evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
}
if (workQueue)
workQueue->Interrupt();
}
void StopHTTPServer()
{
LogPrint("http", "Stopping HTTP server\n");
if (workQueue) {
LogPrint("http", "Waiting for HTTP worker threads to exit\n");
#ifndef WIN32
// ToDo: Disabling WaitExit() for Windows platforms is an ugly workaround for the wallet not
// closing during a repair-restart. It doesn't hurt, though, because threadHTTP.timed_join
// below takes care of this and sends a loopbreak.
workQueue->WaitExit();
#endif
delete workQueue;
}
if (eventBase) {
LogPrint("http", "Waiting for HTTP event thread to exit\n");
// Give event loop a few seconds to exit (to send back last RPC responses), then break it
// Before this was solved with event_base_loopexit, but that didn't work as expected in
// at least libevent 2.0.21 and always introduced a delay. In libevent
// master that appears to be solved, so in the future that solution
// could be used again (if desirable).
// (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
#if BOOST_VERSION >= 105000
if (!threadHTTP.try_join_for(boost::chrono::milliseconds(2000))) {
#else
if (!threadHTTP.timed_join(boost::posix_time::milliseconds(2000))) {
#endif
LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
event_base_loopbreak(eventBase);
threadHTTP.join();
}
}
if (eventHTTP) {
evhttp_free(eventHTTP);
eventHTTP = 0;
}
if (eventBase) {
event_base_free(eventBase);
eventBase = 0;
}
LogPrint("http", "Stopped HTTP server\n");
}
struct event_base* EventBase()
{
return eventBase;
}
static void httpevent_callback_fn(evutil_socket_t, short, void* data)
{
// Static handler: simply call inner handler
HTTPEvent *self = ((HTTPEvent*)data);
self->handler();
if (self->deleteWhenTriggered)
delete self;
}
HTTPEvent::HTTPEvent(struct event_base* base, bool deleteWhenTriggered, const boost::function<void(void)>& handler):
deleteWhenTriggered(deleteWhenTriggered), handler(handler)
{
ev = event_new(base, -1, 0, httpevent_callback_fn, this);
assert(ev);
}
HTTPEvent::~HTTPEvent()
{
event_free(ev);
}
void HTTPEvent::trigger(struct timeval* tv)
{
if (tv == NULL)
event_active(ev, 0, 0); // immediately trigger event in main thread
else
evtimer_add(ev, tv); // trigger after timeval passed
}
HTTPRequest::HTTPRequest(struct evhttp_request* req) : req(req),
replySent(false)
{
}
HTTPRequest::~HTTPRequest()
{
if (!replySent) {
// Keep track of whether reply was sent to avoid request leaks
LogPrintf("%s: Unhandled request\n", __func__);
WriteReply(HTTP_INTERNAL, "Unhandled request");
}
// evhttpd cleans up the request, as long as a reply was sent.
}
std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
{
const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
assert(headers);
const char* val = evhttp_find_header(headers, hdr.c_str());
if (val)
return std::make_pair(true, val);
else
return std::make_pair(false, "");
}
std::string HTTPRequest::ReadBody()
{
struct evbuffer* buf = evhttp_request_get_input_buffer(req);
if (!buf)
return "";
size_t size = evbuffer_get_length(buf);
/** Trivial implementation: if this is ever a performance bottleneck,
* internal copying can be avoided in multi-segment buffers by using
* evbuffer_peek and an awkward loop. Though in that case, it'd be even
* better to not copy into an intermediate string but use a stream
* abstraction to consume the evbuffer on the fly in the parsing algorithm.
*/
const char* data = (const char*)evbuffer_pullup(buf, size);
if (!data) // returns NULL in case of empty buffer
return "";
std::string rv(data, size);
evbuffer_drain(buf, size);
return rv;
}
void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
{
struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
assert(headers);
evhttp_add_header(headers, hdr.c_str(), value.c_str());
}
/** Closure sent to main thread to request a reply to be sent to
* a HTTP request.
* Replies must be sent in the main loop in the main http thread,
* this cannot be done from worker threads.
*/
void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
{
assert(!replySent && req);
// Send event to main http thread to send reply message
struct evbuffer* evb = evhttp_request_get_output_buffer(req);
assert(evb);
evbuffer_add(evb, strReply.data(), strReply.size());
HTTPEvent* ev = new HTTPEvent(eventBase, true,
boost::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL));
ev->trigger(0);
replySent = true;
req = 0; // transferred back to main thread
}
CService HTTPRequest::GetPeer()
{
evhttp_connection* con = evhttp_request_get_connection(req);
CService peer;
if (con) {
// evhttp retains ownership over returned address string
const char* address = "";
uint16_t port = 0;
evhttp_connection_get_peer(con, (char**)&address, &port);
peer = LookupNumeric(address, port);
}
return peer;
}
std::string HTTPRequest::GetURI()
{
return evhttp_request_get_uri(req);
}
HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
{
switch (evhttp_request_get_command(req)) {
case EVHTTP_REQ_GET:
return GET;
break;
case EVHTTP_REQ_POST:
return POST;
break;
case EVHTTP_REQ_HEAD:
return HEAD;
break;
case EVHTTP_REQ_PUT:
return PUT;
break;
default:
return UNKNOWN;
break;
}
}
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
{
LogPrint("http", "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
}
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
{
std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
for (; i != iend; ++i)
if (i->prefix == prefix && i->exactMatch == exactMatch)
break;
if (i != iend)
{
LogPrint("http", "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
pathHandlers.erase(i);
}
}
| [
"jackmcnabb@hotmail.co.uk"
] | jackmcnabb@hotmail.co.uk |
0912b7242ab2c9aef01b7d74f36dc5fc579df36e | 09f1fc62f8bd413b16a96d4f7d69858ebd90e690 | /InterviewStreet Interview/toSend/solve.cpp | b310e2724cd0475820186ff9d1c3649a7184da96 | [] | no_license | shivam043/Random_Contests | f2f493011e4d29450f8bf63c53be091e514243fa | 6a89da5f889f500f2f5af5dc5978c07f28aee1cd | refs/heads/master | 2021-01-01T19:44:54.990947 | 2013-12-09T18:22:03 | 2013-12-09T18:22:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,984 | cpp | //Name : Shinchan Nohara
//Age : 5 years
//Organisation : Kasukabe Defense Force
#include <iostream>
#include <ctime>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cassert>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <iterator>
#include <fstream>
using namespace std;
typedef long long int64;
typedef vector<int> vi;
typedef string ST;
typedef stringstream SS;
typedef vector< vector<int> > vvi;
typedef pair<int,int> ii;
typedef vector<string> vs;
/*
#ifdef __cplusplus
#undef __cplusplus
#define __cplusplus 199712L
#endif
#if __cplusplus > 199711L // for g++0x, value of __cplusplus must be greater thana 199711L.
#define tr(i, c) for(auto i = begin(c); i != end(c); i++)
#else
#define tr(i, c) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#endif
*/
#define DEBUG(x) cout << #x << " = " << x << "\n"
#define endl ("\n")
#define tr(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define PI M_PI
#define E M_E
#define ep 1e-9
#define Sf scanf
#define Pf printf
#define forn(i, n) for(int i = 0, lets_stop_here = (int)n; i < lets_stop_here; i++)
#define forab(i, a, b) for(int i = a, lets_stop_here = (int)b; i <= lets_stop_here; i++)
#define rep(i, a, b) for(int i = a, lets_stop_here = (int)b; i >= lets_stop_here; i--)
#define all(c) (c).begin(), (c).end()
#define CL(a, b) memset(a, b, sizeof(a))
#define mp make_pair
#define pb push_back
#define present(x, c) ((c).find(x) != (c).end()) //map & set//
#define cpresent(x, c) (find( (c).begin(), (c).end(), x) != (c).end()) //vector & list//
#define read(n) scanf("%d", &n)
#define write(n) printf("%d ", n)
#define writeln(n) printf("%d\n", n)
// a^x mod m
int64 pow(int64 a, int64 x, int64 m) {
if(x == 0)
return 1ll;
int64 ret = pow(a, x/2, m);
ret = (ret*ret)%m;
if(x % 2 == 1)
ret = (ret * a) % m;
return ret;
}
/* h*(k^x) + m*y = d y <- [-inf, inf]
* => h*(k^x) = d (mod m)
* find x using discrete logarithm
*/
int64 solve(int64 h, int64 k, int64 m, int64 d) {
int64 n = (int64)sqrt(m + 0.0) + 1;
int64 ret = -1LL;
map <int64, int64> vals;
vals.clear();
int64 kn = pow(k, n, m); // kn = k^n
int64 cur = (h*kn) % m; // cur = h * (k^n)
for(int64 p = 1; p <= n; p++) {
if(vals.find(cur) == vals.end())
vals[cur] = p;
cur = (cur * kn) % m; // cur = h * (k^n)^p
}
cur = d; // cur = d
for(int64 q = 0; q <= n; q++) {
if(vals.find(cur) != vals.end()) {
if(ret < 0)
ret = vals[cur]*n - q;
else
ret = min(ret, vals[cur]*n-q);
}
cur = (cur * k) % m; // cur = d * k^q
}
return ret;
}
int main()
{
int64 h, k, m, d;
cin >> h >> k >> m >> d;
cout << solve(h, k, m, d) << endl;
return 0;
}
| [
"abhiranjan.kumar00@gmail.com"
] | abhiranjan.kumar00@gmail.com |
dab18ee9db940a1acbb7d73001415c7ea54cabb4 | 15cec5616a1c10924ebfd7d1db2134dbcc4e5598 | /atcoder.jp/abc054/abc054_a/Main.cpp | 92a499ef1c9847f8d34ef796680775a49ef09dc7 | [] | no_license | shuto1441/atcoder_archive | 2c474a379b6b3df8783504335cc678b3e45fc0e8 | 8c3cc31ebe39746e26f8fdef4f6ac289d34f91a0 | refs/heads/main | 2023-07-11T00:03:38.661106 | 2021-08-21T11:16:28 | 2021-08-21T11:16:28 | 397,816,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
if(a==1&&b!=1)
cout<<"Alice"<<endl;
else if(a!=1&&b==1)
cout<<"Bob"<<endl;
else if(a==b)
cout<<"Draw"<<endl;
else if(a>b)
cout<<"Alice"<<endl;
else
cout<<"Bob"<<endl;
}
| [
"shuto1441@gmail.com"
] | shuto1441@gmail.com |
7e9c82771dee32d491f2da50a322eca28525f148 | 4f842edb9d575d33c07f93a46a79865d7f78208f | /or_planning/local_planner/teb_test.cpp | 5493f273cba263f81415f0199a15db45205ebea5 | [] | no_license | SiChiTong/OrchardRover | 3e3e6e8a33ecb9022661d28318c93faa602be4ce | 7c1a9b612ba64e35c6a6a4d6679289763f3adf2f | refs/heads/master | 2023-06-10T09:44:19.477025 | 2021-06-29T02:50:04 | 2021-06-29T02:50:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,254 | cpp | //
// Created by cxn on 2020/7/21.
//
#include <interactive_markers/interactive_marker_server.h>
#include <visualization_msgs/Marker.h>
#include "include/obstacle.h"
#include "include/local_visualization.h"
#include "include/robot_footprint_model.h"
#include "timed_elastic_band/include/teb_optimal.h"
#include "timed_elastic_band/proto/timed_elastic_band.pb.h"
using namespace or_local_planner;
TebOptimalPtr planner;
std::vector<ObstaclePtr> obst_vector;
LocalVisualizationPtr visual;
ViaPointContainer via_points;
unsigned int no_fixed_obstacles;
void CB_mainCycle(const ros::TimerEvent &e);
void CB_publishCycle(const ros::TimerEvent &e);
void CreateInteractiveMarker(const double &init_x, const double &init_y, unsigned int id, std::string frame,
interactive_markers::InteractiveMarkerServer *marker_server,
interactive_markers::InteractiveMarkerServer::FeedbackCallback feedback_cb);
void CB_obstacle_marker(const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback);
int main(int argc, char **argv) {
ros::init(argc, argv, "test_optim_node");
ros::NodeHandle nh;
or_local_planner::Config param_config_;
std::string full_path = ros::package::getPath("or_planning") +
"/local_planner/timed_elastic_band/config/timed_elastic_band.prototxt";
or_common::ReadProtoFromTextFile(full_path.c_str(), ¶m_config_);
ros::Timer cycle_timer = nh.createTimer(ros::Duration(0.025), CB_mainCycle);
ros::Timer publish_timer = nh.createTimer(ros::Duration(0.1), CB_publishCycle);
interactive_markers::InteractiveMarkerServer marker_server("marker_obstacles");
obst_vector.emplace_back(std::make_shared<PointObstacle>(-3, 1));
obst_vector.emplace_back(std::make_shared<PointObstacle>(6, 2));
obst_vector.emplace_back(std::make_shared<PointObstacle>(0, 0.1));
obst_vector.emplace_back(std::make_shared<PointObstacle>(-4, 1));
obst_vector.emplace_back(std::make_shared<PointObstacle>(5, 2));
obst_vector.emplace_back(std::make_shared<PointObstacle>(1, 0.1));
obst_vector.emplace_back(std::make_shared<PointObstacle>(-3, 2));
obst_vector.emplace_back(std::make_shared<PointObstacle>(5, 3));
obst_vector.emplace_back(std::make_shared<PointObstacle>(4, 0));
obst_vector.emplace_back(std::make_shared<PointObstacle>(4, 1));
obst_vector.emplace_back(std::make_shared<PointObstacle>(3, 2));
obst_vector.emplace_back(std::make_shared<PointObstacle>(2, 2));
std::string map_frame;
for (unsigned int i = 0; i < obst_vector.size(); ++i) {
std::shared_ptr<PointObstacle> pobst = std::dynamic_pointer_cast<PointObstacle>(obst_vector.at(i));
if (pobst) {
CreateInteractiveMarker(pobst->Position().coeff(0), pobst->Position().coeff(1),
i, "odom", &marker_server, &CB_obstacle_marker);
}
}
marker_server.applyChanges();
// Setup visualization
visual = LocalVisualizationPtr(new LocalVisualization(nh, "odom"));
RobotFootprintModelPtr model = std::make_shared<PointRobotFootprint>();
planner = TebOptimalPtr(new TebOptimal(param_config_, &obst_vector, model, visual, &via_points));
no_fixed_obstacles = (unsigned int) obst_vector.size();
ros::spin();
return 0;
}
void CreateInteractiveMarker(const double &init_x, const double &init_y, unsigned int id, std::string frame,
interactive_markers::InteractiveMarkerServer *marker_server,
interactive_markers::InteractiveMarkerServer::FeedbackCallback feedback_cb) {
// create an interactive marker for our server
visualization_msgs::InteractiveMarker i_marker;
i_marker.header.frame_id = frame;
i_marker.header.stamp = ros::Time::now();
std::ostringstream oss;
//oss << "obstacle" << id;
oss << id;
i_marker.name = oss.str();
i_marker.description = "Obstacle";
i_marker.pose.position.x = init_x;
i_marker.pose.position.y = init_y;
// create a grey box marker
visualization_msgs::Marker box_marker;
box_marker.type = visualization_msgs::Marker::CUBE;
box_marker.id = id;
box_marker.scale.x = 0.2;
box_marker.scale.y = 0.2;
box_marker.scale.z = 0.2;
box_marker.color.r = 100;
box_marker.color.g = 0.5;
box_marker.color.b = 0.5;
box_marker.color.a = 1.0;
// create a non-interactive control which contains the box
visualization_msgs::InteractiveMarkerControl box_control;
box_control.always_visible = 1;
box_control.markers.push_back(box_marker);
// add the control to the interactive marker
i_marker.controls.push_back(box_control);
// create a control which will move the box, rviz will insert 2 arrows
visualization_msgs::InteractiveMarkerControl move_control;
move_control.name = "move_x";
move_control.orientation.w = sqrt(2) / 2;
move_control.orientation.x = 0;
move_control.orientation.y = sqrt(2) / 2;
move_control.orientation.z = 0;
move_control.interaction_mode = visualization_msgs::InteractiveMarkerControl::MOVE_PLANE;
// add the control to the interactive marker
i_marker.controls.push_back(move_control);
// add the interactive marker to our collection
marker_server->insert(i_marker);
marker_server->setCallback(i_marker.name, feedback_cb);
}
// Planning loop
void CB_mainCycle(const ros::TimerEvent &e) {
auto start_pose = DataConverter::LocalConvertCData(-4, 0, 0);
auto end_pose = DataConverter::LocalConvertCData(4, 0, 0);
planner->Optimal(DataBase(start_pose.first, start_pose.second), DataBase(end_pose.first, end_pose.second));
}
// Visualization loop
void CB_publishCycle(const ros::TimerEvent &e) {
planner->Visualize();
}
void CB_obstacle_marker(const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback) {
std::stringstream ss(feedback->marker_name);
unsigned int index;
ss >> index;
if (index >= no_fixed_obstacles)
return;
PointObstacle *pobst = dynamic_cast<PointObstacle *>(obst_vector.at(index).get());
pobst->Position() = Eigen::Vector2d(feedback->pose.position.x, feedback->pose.position.y);
} | [
"1344618323@qq.com"
] | 1344618323@qq.com |
0a9492f53a033665e9c898c1c80e86fc3f1a3b20 | ef897e834c0e4a6af19c3f349d3d0e0af0f88bb4 | /rellic/AST/Z3ConvVisitor.cpp | bc6617ced59cf574e6c14fdcf97e9b038f031e85 | [
"Apache-2.0"
] | permissive | JarLob/rellic | 587fff9fb729a28eee64bef4f5d3525e893c1c08 | bd16b1c071f17aa10ec1f44a95065e6dc13e567e | refs/heads/master | 2021-04-10T20:09:15.735199 | 2020-03-12T19:26:30 | 2020-03-12T19:26:44 | 248,961,811 | 1 | 0 | Apache-2.0 | 2020-03-21T11:26:38 | 2020-03-21T11:26:38 | null | UTF-8 | C++ | false | false | 25,159 | cpp | /*
* Copyright (c) 2018 Trail of Bits, 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.
*/
#define GOOGLE_STRIP_LOG 1
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "rellic/AST/Util.h"
#include "rellic/AST/Z3ConvVisitor.h"
namespace rellic {
namespace {
static unsigned GetZ3SortSize(z3::sort sort) {
switch (sort.sort_kind()) {
case Z3_BOOL_SORT:
return 1;
break;
case Z3_BV_SORT:
return sort.bv_size();
break;
case Z3_FLOATING_POINT_SORT: {
auto &ctx = sort.ctx();
return Z3_fpa_get_sbits(ctx, sort) + Z3_fpa_get_ebits(ctx, sort);
} break;
case Z3_UNINTERPRETED_SORT:
return 0;
break;
default:
LOG(FATAL) << "Unknown Z3 sort: " << sort;
break;
}
}
static std::string CreateZ3DeclName(clang::NamedDecl *decl) {
std::stringstream ss;
ss << std::hex << decl << std::dec;
ss << '_' << decl->getNameAsString();
return ss.str();
}
static z3::expr CreateZ3BitwiseCast(z3::expr expr, size_t src, size_t dst,
bool sign) {
CHECK(expr.is_bv()) << "z3::expr is not a bitvector!";
int64_t diff = dst - src;
// extend
if (diff > 0) {
return sign ? z3::sext(expr, diff) : z3::zext(expr, diff);
}
// truncate
if (diff < 0) {
return expr.extract(dst, 1);
}
// nothing
return expr;
}
} // namespace
Z3ConvVisitor::Z3ConvVisitor(clang::ASTContext *c_ctx, z3::context *z3_ctx)
: ast_ctx(c_ctx),
z3_ctx(z3_ctx),
z3_expr_vec(*z3_ctx),
z3_decl_vec(*z3_ctx) {}
// Inserts a `clang::Expr` <=> `z3::expr` mapping into
void Z3ConvVisitor::InsertZ3Expr(clang::Expr *c_expr, z3::expr z_expr) {
auto iter = z3_expr_map.find(c_expr);
CHECK(iter == z3_expr_map.end());
z3_expr_map[c_expr] = z3_expr_vec.size();
z3_expr_vec.push_back(z_expr);
}
// Retrieves a `z3::expr` corresponding to `c_expr`.
// The `z3::expr` needs to be created and inserted by
// `Z3ConvVisistor::InsertZ3Expr` first.
z3::expr Z3ConvVisitor::GetZ3Expr(clang::Expr *c_expr) {
auto iter = z3_expr_map.find(c_expr);
CHECK(iter != z3_expr_map.end());
return z3_expr_vec[iter->second];
}
// Inserts a `clang::ValueDecl` <=> `z3::func_decl` mapping into
void Z3ConvVisitor::InsertZ3Decl(clang::ValueDecl *c_decl,
z3::func_decl z_decl) {
auto iter = z3_decl_map.find(c_decl);
CHECK(iter == z3_decl_map.end());
z3_decl_map[c_decl] = z3_decl_vec.size();
z3_decl_vec.push_back(z_decl);
}
// Retrieves a `z3::func_decl` corresponding to `c_decl`.
// The `z3::func_decl` needs to be created and inserted by
// `Z3ConvVisistor::InsertZ3Decl` first.
z3::func_decl Z3ConvVisitor::GetZ3Decl(clang::ValueDecl *c_decl) {
auto iter = z3_decl_map.find(c_decl);
CHECK(iter != z3_decl_map.end());
return z3_decl_vec[iter->second];
}
// If `expr` is not boolean, returns a `z3::expr` that corresponds
// to the non-boolean to boolean expression cast in C. Otherwise
// returns `expr`.
z3::expr Z3ConvVisitor::Z3BoolCast(z3::expr expr) {
if (expr.is_bool()) {
return expr;
} else {
auto cast = expr != z3_ctx->num_val(0, expr.get_sort());
return cast.simplify();
}
}
void Z3ConvVisitor::InsertCExpr(z3::expr z_expr, clang::Expr *c_expr) {
auto hash = z_expr.hash();
auto iter = c_expr_map.find(hash);
CHECK(iter == c_expr_map.end())
<< "Z3 equivalent for C declaration already exists!";
c_expr_map[hash] = c_expr;
}
clang::Expr *Z3ConvVisitor::GetCExpr(z3::expr z_expr) {
auto hash = z_expr.hash();
auto iter = c_expr_map.find(hash);
CHECK(iter != c_expr_map.end()) << "No Z3 equivalent for C declaration!";
return c_expr_map[hash];
}
void Z3ConvVisitor::InsertCValDecl(z3::func_decl z_decl,
clang::ValueDecl *c_decl) {
auto id = Z3_get_func_decl_id(*z3_ctx, z_decl);
auto iter = c_decl_map.find(id);
CHECK(iter == c_decl_map.end())
<< "C equivalent for Z3 declaration already exists!";
c_decl_map[id] = c_decl;
}
clang::ValueDecl *Z3ConvVisitor::GetCValDecl(z3::func_decl z_decl) {
auto id = Z3_get_func_decl_id(*z3_ctx, z_decl);
auto iter = c_decl_map.find(id);
CHECK(iter != c_decl_map.end()) << "No C equivalent for Z3 declaration!";
return c_decl_map[id];
}
z3::sort Z3ConvVisitor::GetZ3Sort(clang::QualType type) {
// Booleans
if (type->isBooleanType()) {
return z3_ctx->bool_sort();
}
// Structures
if (type->isStructureType()) {
auto decl = clang::cast<clang::RecordType>(type)->getDecl();
auto name = decl->getNameAsString().c_str();
return z3_ctx->uninterpreted_sort(name);
}
auto bitwidth = ast_ctx->getTypeSize(type);
// Floating points
if (type->isRealFloatingType()) {
switch (bitwidth) {
case 16:
// return z3_ctx.fpa_sort<16>();
return z3::to_sort(*z3_ctx, Z3_mk_fpa_sort_16(*z3_ctx));
break;
case 32:
return z3::to_sort(*z3_ctx, Z3_mk_fpa_sort_32(*z3_ctx));
break;
case 64:
return z3::to_sort(*z3_ctx, Z3_mk_fpa_sort_64(*z3_ctx));
break;
case 128:
return z3::to_sort(*z3_ctx, Z3_mk_fpa_sort_128(*z3_ctx));
break;
default:
LOG(FATAL) << "Unsupported floating-point bitwidth!";
break;
}
}
// Default to bitvectors
return z3::to_sort(*z3_ctx, Z3_mk_bv_sort(*z3_ctx, bitwidth));
}
clang::Expr *Z3ConvVisitor::CreateLiteralExpr(z3::expr z_expr) {
DLOG(INFO) << "Creating literal clang::Expr for " << z_expr;
auto sort = z_expr.get_sort();
clang::Expr *result = nullptr;
switch (sort.sort_kind()) {
case Z3_BOOL_SORT: {
auto type = ast_ctx->UnsignedIntTy;
auto size = ast_ctx->getIntWidth(type);
llvm::APInt val(size, z_expr.bool_value() == Z3_L_TRUE ? 1 : 0);
result = CreateIntegerLiteral(*ast_ctx, val, type);
} break;
case Z3_BV_SORT: {
auto type = ast_ctx->getIntTypeForBitwidth(GetZ3SortSize(sort), 0);
auto size = ast_ctx->getIntWidth(type);
llvm::APInt val(size, Z3_get_numeral_string(z_expr.ctx(), z_expr), 10);
if (type->isCharType()) {
result = CreateCharacterLiteral(*ast_ctx, val, type);
} else {
result = CreateIntegerLiteral(*ast_ctx, val, type);
}
} break;
case Z3_FLOATING_POINT_SORT: {
auto type = ast_ctx->getRealTypeForBitwidth(GetZ3SortSize(sort));
auto size = ast_ctx->getTypeSize(type);
const llvm::fltSemantics *semantics;
switch (size) {
case 16:
semantics = &llvm::APFloat::IEEEhalf();
break;
case 32:
semantics = &llvm::APFloat::IEEEsingle();
break;
case 64:
semantics = &llvm::APFloat::IEEEdouble();
break;
case 128:
semantics = &llvm::APFloat::IEEEquad();
break;
default:
LOG(FATAL) << "Unknown Z3 floating-point sort!";
break;
}
llvm::APInt ival(size, Z3_get_numeral_string(z_expr.ctx(), z_expr), 10);
llvm::APFloat fval(*semantics, ival);
result = CreateFloatingLiteral(*ast_ctx, fval, type);
} break;
default:
LOG(FATAL) << "Unknown Z3 sort: " << sort;
break;
}
return result;
}
// Retrieves or creates`z3::expr`s from `clang::Expr`.
z3::expr Z3ConvVisitor::GetOrCreateZ3Expr(clang::Expr *c_expr) {
if (!z3_expr_map.count(c_expr)) {
TraverseStmt(c_expr);
}
return GetZ3Expr(c_expr);
}
z3::func_decl Z3ConvVisitor::GetOrCreateZ3Decl(clang::ValueDecl *c_decl) {
if (!z3_decl_map.count(c_decl)) {
TraverseDecl(c_decl);
}
auto z_decl = GetZ3Decl(c_decl);
auto id = Z3_get_func_decl_id(*z3_ctx, z_decl);
if (!c_decl_map.count(id)) {
InsertCValDecl(z_decl, c_decl);
}
return z_decl;
}
// Retrieves or creates `clang::Expr` from `z3::expr`.
clang::Expr *Z3ConvVisitor::GetOrCreateCExpr(z3::expr z_expr) {
if (!c_expr_map.count(z_expr.hash())) {
VisitZ3Expr(z_expr);
}
return GetCExpr(z_expr);
}
bool Z3ConvVisitor::VisitVarDecl(clang::VarDecl *var) {
auto name = var->getNameAsString().c_str();
DLOG(INFO) << "VisitVarDecl: " << name;
if (z3_decl_map.count(var)) {
DLOG(INFO) << "Re-declaration of " << name << "; Returning.";
return true;
}
auto z_name = CreateZ3DeclName(var);
auto z_sort = GetZ3Sort(var->getType());
auto z_const = z3_ctx->constant(z_name.c_str(), z_sort);
InsertZ3Decl(var, z_const.decl());
return true;
}
bool Z3ConvVisitor::VisitFieldDecl(clang::FieldDecl *field) {
auto name = field->getNameAsString().c_str();
DLOG(INFO) << "VisitFieldDecl: " << name;
if (z3_decl_map.count(field)) {
DLOG(INFO) << "Re-declaration of " << name << "; Returning.";
return true;
}
auto z_name = CreateZ3DeclName(field->getParent()) + "_" + name;
auto z_sort = GetZ3Sort(field->getType());
auto z_const = z3_ctx->constant(z_name.c_str(), z_sort);
InsertZ3Decl(field, z_const.decl());
return true;
}
bool Z3ConvVisitor::VisitFunctionDecl(clang::FunctionDecl *func) {
DLOG(INFO) << "VisitFunctionDecl";
LOG(FATAL) << "Unimplemented FunctionDecl visitor";
return true;
}
bool Z3ConvVisitor::VisitCStyleCastExpr(clang::CStyleCastExpr *c_cast) {
DLOG(INFO) << "VisitCStyleCastExpr";
if (z3_expr_map.count(c_cast)) {
return true;
}
// C exprs
auto c_sub = c_cast->getSubExpr();
// C types
auto t_src = c_sub->getType();
auto t_dst = c_cast->getType();
// C type sizes
auto t_src_size = ast_ctx->getTypeSize(t_src);
auto t_dst_size = ast_ctx->getTypeSize(t_dst);
// Z3 exprs
auto z_sub = GetOrCreateZ3Expr(c_sub);
auto z_cast = CreateZ3BitwiseCast(z_sub, t_src_size, t_dst_size,
t_src->isSignedIntegerType());
// Z3 cast function
// auto ZCastFunc = [this, &z_sub, &z_cast](const char *name) {
// auto s_src = z_sub.get_sort();
// auto s_dst = z_cast.get_sort();
// auto z_func = z3_ctx->function(name, s_src, s_dst);
// return z_func(z_sub);
// };
switch (c_cast->getCastKind()) {
case clang::CastKind::CK_PointerToIntegral: {
auto s_src = z_sub.get_sort();
auto s_dst = z_cast.get_sort();
auto z_func = z3_ctx->function("PtrToInt", s_src, s_dst);
z_cast = z_func(z_sub);
} break;
case clang::CastKind::CK_IntegralToPointer: {
auto s_src = z_sub.get_sort();
auto s_dst = z_cast.get_sort();
auto t_dst_opaque_ptr_val =
reinterpret_cast<uint64_t>(t_dst.getAsOpaquePtr());
auto z_ptr = z3_ctx->bv_val(t_dst_opaque_ptr_val, 8 * sizeof(void *));
auto s_ptr = z_ptr.get_sort();
auto z_func = z3_ctx->function("IntToPtr", s_ptr, s_src, s_dst);
z_cast = z_func(z_ptr, z_sub);
} break;
case clang::CastKind::CK_IntegralCast:
case clang::CastKind::CK_NullToPointer:
break;
default:
LOG(FATAL) << "Unsupported cast type: " << c_cast->getCastKindName();
break;
}
// Save
InsertZ3Expr(c_cast, z_cast);
return true;
}
bool Z3ConvVisitor::VisitImplicitCastExpr(clang::ImplicitCastExpr *c_cast) {
DLOG(INFO) << "VisitImplicitCastExpr";
if (z3_expr_map.count(c_cast)) {
return true;
}
auto c_sub = c_cast->getSubExpr();
auto z_sub = GetOrCreateZ3Expr(c_sub);
switch (c_cast->getCastKind()) {
case clang::CastKind::CK_ArrayToPointerDecay: {
CHECK(z_sub.is_bv()) << "Pointer cast operand is not a bit-vector";
auto s_ptr = GetZ3Sort(c_cast->getType());
auto s_arr = z_sub.get_sort();
auto z_func = z3_ctx->function("PtrDecay", s_arr, s_ptr);
InsertZ3Expr(c_cast, z_func(z_sub));
} break;
default:
LOG(FATAL) << "Unsupported cast type: " << c_cast->getCastKindName();
break;
}
return true;
}
bool Z3ConvVisitor::VisitArraySubscriptExpr(clang::ArraySubscriptExpr *sub) {
DLOG(INFO) << "VisitArraySubscriptExpr";
if (z3_expr_map.count(sub)) {
return true;
}
// Get base
auto z_base = GetOrCreateZ3Expr(sub->getBase());
auto base_sort = z_base.get_sort();
CHECK(base_sort.is_bv()) << "Invalid Z3 sort for base expression";
// Get index
auto z_idx = GetOrCreateZ3Expr(sub->getIdx());
auto idx_sort = z_idx.get_sort();
CHECK(idx_sort.is_bv()) << "Invalid Z3 sort for index expression";
// Get result
auto elm_sort = GetZ3Sort(sub->getType());
// Create a z_function
auto z_arr_sub = z3_ctx->function("ArraySub", base_sort, idx_sort, elm_sort);
// Create a z3 expression
InsertZ3Expr(sub, z_arr_sub(z_base, z_idx));
// Done
return true;
}
bool Z3ConvVisitor::VisitMemberExpr(clang::MemberExpr *expr) {
DLOG(INFO) << "VisitMemberExpr";
if (z3_expr_map.count(expr)) {
return true;
}
auto z_mem = GetOrCreateZ3Decl(expr->getMemberDecl())();
auto z_base = GetOrCreateZ3Expr(expr->getBase());
auto z_mem_expr = z3_ctx->function("Member", z_base.get_sort(),
z_mem.get_sort(), z_mem.get_sort());
InsertZ3Expr(expr, z_mem_expr(z_base, z_mem));
return true;
}
bool Z3ConvVisitor::VisitCallExpr(clang::CallExpr *call) {
LOG(FATAL) << "Unimplemented CallExpr visitor";
return true;
}
// Translates clang unary operators expressions to Z3 equivalents.
bool Z3ConvVisitor::VisitParenExpr(clang::ParenExpr *parens) {
DLOG(INFO) << "VisitParenExpr";
if (z3_expr_map.count(parens)) {
return true;
}
auto z_sub = GetOrCreateZ3Expr(parens->getSubExpr());
switch (z_sub.decl().decl_kind()) {
// Parens may affect semantics of C expressions
case Z3_OP_UNINTERPRETED: {
auto sort = z_sub.get_sort();
auto z_paren = z3_ctx->function("Paren", sort, sort);
InsertZ3Expr(parens, z_paren(z_sub));
} break;
// Default to ignoring the parens, Z3 should know how
// to interpret them.
default:
InsertZ3Expr(parens, z_sub);
break;
}
return true;
}
// Translates clang unary operators expressions to Z3 equivalents.
bool Z3ConvVisitor::VisitUnaryOperator(clang::UnaryOperator *c_op) {
DLOG(INFO) << "VisitUnaryOperator: "
<< c_op->getOpcodeStr(c_op->getOpcode()).str();
if (z3_expr_map.count(c_op)) {
return true;
}
// Get operand
auto operand = GetOrCreateZ3Expr(c_op->getSubExpr());
// Create z3 unary op
switch (c_op->getOpcode()) {
case clang::UO_LNot: {
InsertZ3Expr(c_op, !Z3BoolCast(operand));
} break;
case clang::UO_AddrOf: {
auto ptr_sort = GetZ3Sort(c_op->getType());
auto z_addrof = z3_ctx->function("AddrOf", operand.get_sort(), ptr_sort);
InsertZ3Expr(c_op, z_addrof(operand));
} break;
case clang::UO_Deref: {
auto elm_sort = GetZ3Sort(c_op->getType());
auto z_deref = z3_ctx->function("Deref", operand.get_sort(), elm_sort);
InsertZ3Expr(c_op, z_deref(operand));
} break;
default:
LOG(FATAL) << "Unknown clang::UnaryOperator operation!";
break;
}
return true;
}
// Translates clang binary operators expressions to Z3 equivalents.
bool Z3ConvVisitor::VisitBinaryOperator(clang::BinaryOperator *c_op) {
DLOG(INFO) << "VisitBinaryOperator: " << c_op->getOpcodeStr().str();
if (z3_expr_map.count(c_op)) {
return true;
}
// Get operands
auto lhs = GetOrCreateZ3Expr(c_op->getLHS());
auto rhs = GetOrCreateZ3Expr(c_op->getRHS());
// Create z3 binary op
switch (c_op->getOpcode()) {
case clang::BO_LAnd:
InsertZ3Expr(c_op, Z3BoolCast(lhs) && Z3BoolCast(rhs));
break;
case clang::BO_LOr:
InsertZ3Expr(c_op, Z3BoolCast(lhs) || Z3BoolCast(rhs));
break;
case clang::BO_EQ:
InsertZ3Expr(c_op, lhs == rhs);
break;
case clang::BO_NE:
InsertZ3Expr(c_op, lhs != rhs);
break;
case clang::BO_Rem:
InsertZ3Expr(c_op, z3::srem(lhs, rhs));
break;
case clang::BO_Add:
InsertZ3Expr(c_op, lhs + rhs);
break;
case clang::BO_Sub:
InsertZ3Expr(c_op, lhs - rhs);
break;
case clang::BO_And:
InsertZ3Expr(c_op, lhs & rhs);
break;
case clang::BO_Xor:
InsertZ3Expr(c_op, lhs ^ rhs);
break;
case clang::BO_Shr:
InsertZ3Expr(c_op, c_op->getLHS()->getType()->isSignedIntegerType()
? z3::ashr(lhs, rhs)
: z3::lshr(lhs, rhs));
break;
default:
LOG(FATAL) << "Unknown clang::BinaryOperator operation!";
break;
}
return true;
}
// Translates clang variable references to Z3 constants.
bool Z3ConvVisitor::VisitDeclRefExpr(clang::DeclRefExpr *c_ref) {
auto ref_decl = c_ref->getDecl();
auto ref_name = ref_decl->getNameAsString();
DLOG(INFO) << "VisitDeclRefExpr: " << ref_name;
if (z3_expr_map.count(c_ref)) {
return true;
}
auto z_const = GetOrCreateZ3Decl(ref_decl);
InsertZ3Expr(c_ref, z_const());
return true;
}
// Translates clang character literals references to Z3 numeral values.
bool Z3ConvVisitor::VisitCharacterLiteral(clang::CharacterLiteral *c_lit) {
auto c_val = c_lit->getValue();
DLOG(INFO) << "VisitCharacterLiteral: " << c_val;
if (z3_expr_map.count(c_lit)) {
return true;
}
auto z_sort = GetZ3Sort(c_lit->getType());
auto z_val = z3_ctx->num_val(c_val, z_sort);
InsertZ3Expr(c_lit, z_val);
return true;
}
// Translates clang integer literals references to Z3 numeral values.
bool Z3ConvVisitor::VisitIntegerLiteral(clang::IntegerLiteral *c_lit) {
auto c_val = c_lit->getValue().getLimitedValue();
DLOG(INFO) << "VisitIntegerLiteral: " << c_val;
if (z3_expr_map.count(c_lit)) {
return true;
}
auto z_sort = GetZ3Sort(c_lit->getType());
auto z_val = z_sort.is_bool() ? z3_ctx->bool_val(c_val != 0)
: z3_ctx->num_val(c_val, z_sort);
InsertZ3Expr(c_lit, z_val);
return true;
}
void Z3ConvVisitor::VisitZ3Expr(z3::expr z_expr) {
if (z_expr.is_app()) {
for (auto i = 0U; i < z_expr.num_args(); ++i) {
GetOrCreateCExpr(z_expr.arg(i));
}
switch (z_expr.decl().arity()) {
case 0:
VisitConstant(z_expr);
break;
case 1:
VisitUnaryApp(z_expr);
break;
case 2:
VisitBinaryApp(z_expr);
break;
default:
LOG(FATAL) << "Unexpected Z3 operation!";
break;
}
} else if (z_expr.is_quantifier()) {
LOG(FATAL) << "Unexpected Z3 quantifier!";
} else {
LOG(FATAL) << "Unexpected Z3 variable!";
}
}
void Z3ConvVisitor::VisitConstant(z3::expr z_const) {
DLOG(INFO) << "VisitConstant: " << z_const;
CHECK(z_const.is_const()) << "Z3 expression is not a constant!";
// Create C literals and variable references
auto kind = z_const.decl().decl_kind();
clang::Expr *c_expr = nullptr;
switch (kind) {
// Boolean literals
case Z3_OP_TRUE:
case Z3_OP_FALSE:
// Arithmetic numerals
case Z3_OP_ANUM:
// Bitvector numerals
case Z3_OP_BNUM:
c_expr = CreateLiteralExpr(z_const);
break;
// Internal constants handled by parent Z3 exprs
case Z3_OP_INTERNAL:
break;
// Uninterpreted constants
case Z3_OP_UNINTERPRETED:
c_expr = CreateDeclRefExpr(*ast_ctx, GetCValDecl(z_const.decl()));
break;
// Unknowns
default:
LOG(FATAL) << "Unknown Z3 constant!";
break;
}
InsertCExpr(z_const, c_expr);
}
void Z3ConvVisitor::VisitUnaryApp(z3::expr z_op) {
DLOG(INFO) << "VisitUnaryApp: " << z_op;
CHECK(z_op.is_app() && z_op.decl().arity() == 1)
<< "Z3 expression is not a unary operator!";
// Get operand
auto c_sub = GetCExpr(z_op.arg(0));
auto t_sub = c_sub->getType();
// Get z3 function declaration
auto z_func = z_op.decl();
// Create C unary operator
clang::Expr *c_op = nullptr;
switch (z_func.decl_kind()) {
case Z3_OP_NOT:
c_op = CreateNotExpr(*ast_ctx, c_sub);
break;
case Z3_OP_EXTRACT: {
CHECK(t_sub->isIntegerType()) << "Extract operand is not an integer";
auto s_size = GetZ3SortSize(z_op.get_sort());
auto t_sign = t_sub->isSignedIntegerType();
auto t_op = ast_ctx->getIntTypeForBitwidth(s_size, t_sign);
c_op = CreateCStyleCastExpr(*ast_ctx, t_op,
clang::CastKind::CK_IntegralCast, c_sub);
} break;
case Z3_OP_UNINTERPRETED: {
// Resolve opcode
auto z_func_name = z_func.name().str();
if (z_func_name == "AddrOf") {
auto t_op = ast_ctx->getPointerType(t_sub);
c_op = CreateUnaryOperator(*ast_ctx, clang::UO_AddrOf, c_sub, t_op);
} else if (z_func_name == "Deref") {
CHECK(t_sub->isPointerType()) << "Deref operand type is not a pointer";
auto t_op = t_sub->getPointeeType();
c_op = CreateUnaryOperator(*ast_ctx, clang::UO_Deref, c_sub, t_op);
} else if (z_func_name == "Paren") {
c_op = CreateParenExpr(*ast_ctx, c_sub);
} else if (z_func_name == "PtrDecay") {
CHECK(t_sub->isArrayType()) << "PtrDecay operand type is not an array";
auto t_op = ast_ctx->getArrayDecayedType(t_sub);
c_op = CreateImplicitCastExpr(
*ast_ctx, t_op, clang::CastKind::CK_ArrayToPointerDecay, c_sub);
} else if (z_func_name == "PtrToInt") {
auto s_size = GetZ3SortSize(z_op.get_sort());
auto t_op = ast_ctx->getIntTypeForBitwidth(s_size, /*sign=*/0);
c_op = CreateCStyleCastExpr(
*ast_ctx, t_op, clang::CastKind::CK_PointerToIntegral, c_sub);
} else {
LOG(FATAL) << "Unknown Z3 uninterpreted function";
}
} break;
default:
LOG(FATAL) << "Unknown Z3 unary operator!";
break;
}
// Save
InsertCExpr(z_op, c_op);
}
void Z3ConvVisitor::VisitBinaryApp(z3::expr z_op) {
DLOG(INFO) << "VisitBinaryApp: " << z_op;
CHECK(z_op.is_app() && z_op.decl().arity() == 2)
<< "Z3 expression is not a binary operator!";
// Get operands
auto lhs = GetCExpr(z_op.arg(0));
auto rhs = GetCExpr(z_op.arg(1));
// Get result type for integers
auto GetIntResultType = [this, &lhs, &rhs] {
auto lht = lhs->getType();
auto rht = rhs->getType();
auto order = ast_ctx->getIntegerTypeOrder(lht, rht);
return order < 0 ? rht : lht;
};
// Get z3 function declaration
auto z_func = z_op.decl();
// Create C binary operator
clang::Expr *c_op = nullptr;
switch (z_func.decl_kind()) {
case Z3_OP_EQ:
c_op = CreateBinaryOperator(*ast_ctx, clang::BO_EQ, lhs, rhs,
ast_ctx->BoolTy);
break;
case Z3_OP_AND: {
c_op = lhs;
for (auto i = 1U; i < z_op.num_args(); ++i) {
rhs = GetCExpr(z_op.arg(i));
c_op = CreateBinaryOperator(*ast_ctx, clang::BO_LAnd, c_op, rhs,
ast_ctx->BoolTy);
}
} break;
case Z3_OP_OR: {
c_op = lhs;
for (auto i = 1U; i < z_op.num_args(); ++i) {
rhs = GetCExpr(z_op.arg(i));
c_op = CreateBinaryOperator(*ast_ctx, clang::BO_LOr, c_op, rhs,
ast_ctx->BoolTy);
}
} break;
case Z3_OP_BADD:
c_op = CreateBinaryOperator(*ast_ctx, clang::BO_Add, lhs, rhs,
GetIntResultType());
break;
case Z3_OP_BSREM:
case Z3_OP_BSREM_I:
c_op = CreateBinaryOperator(*ast_ctx, clang::BO_Rem, lhs, rhs,
GetIntResultType());
break;
case Z3_OP_UNINTERPRETED: {
auto name = z_func.name().str();
// Resolve opcode
if (name == "ArraySub") {
auto base_type = lhs->getType()->getAs<clang::PointerType>();
CHECK(base_type) << "Operand is not a clang::PointerType";
c_op = CreateArraySubscriptExpr(*ast_ctx, lhs, rhs,
base_type->getPointeeType());
} else if (name == "Member") {
auto mem = GetCValDecl(z_op.arg(1).decl());
c_op = CreateMemberExpr(*ast_ctx, lhs, mem, mem->getType(),
/*is_arrow=*/false);
} else if (name == "IntToPtr") {
auto c_lit = clang::cast<clang::IntegerLiteral>(lhs);
auto t_dst_opaque_ptr_val = c_lit->getValue().getLimitedValue();
auto t_dst_opaque_ptr = reinterpret_cast<void *>(t_dst_opaque_ptr_val);
auto t_dst = clang::QualType::getFromOpaquePtr(t_dst_opaque_ptr);
c_op = CreateCStyleCastExpr(*ast_ctx, t_dst,
clang::CastKind::CK_IntegralToPointer, rhs);
} else {
LOG(FATAL) << "Unknown Z3 uninterpreted function";
}
} break;
// Unknowns
default:
LOG(FATAL) << "Unknown Z3 binary operator!";
break;
}
// Save
InsertCExpr(z_op, c_op);
}
} // namespace rellic | [
"marek.surovic@gmail.com"
] | marek.surovic@gmail.com |
bc3855660fdcae2d560f1c77afc36a2519a46c49 | 31ef235aec8599f703ebcd2636040b199bb5c2ca | /forTesting.cpp | f8b1982d541e1c9d1389d08f65d2556873264e2b | [] | no_license | dachev1919/cpp03_2020 | fc74af0cfefd9073bb2744494a903a8518f61c8d | 7015a9f6a6215753648d6398368fa51b00e63942 | refs/heads/master | 2022-12-15T09:37:52.043989 | 2020-09-15T19:02:54 | 2020-09-15T19:02:54 | 295,822,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,941 | cpp | package com.company;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
// імпортування статичних змінних і методів класу Math
public class Main {
public static void main(String[] args) {
Main prog = new Main();
prog.run();
}
private static void date(){
// Инициализация объекта date
Date date = new Date();
// Вывод текущей даты с использованием toString()
System.out.printf("%1$s %2$td %2$tB %2$tY", "Дата:", date);
}
private void print(double a, double b, double t) {
System.out.println("a = "+a);
System.out.println("b = "+b);
System.out.println("t = "+t);
double y = exp(-b * t) * sin(a * t + b) - sqrt(abs(b * t + a));
System.out.println("y = exp(-b * t) * sin(a * t + b) - sqrt(abs(b * t + a))");
System.out.println("y = "+y);
}
private double calcSquare(double x){
return x * x;
}
private void primer(){
Scanner sc = new Scanner(System.in);
System.out.printf("------------------------------------------------");
System.out.printf("\na - ");
double a = sc.nextDouble();
System.out.printf("b - ");
double b = sc.nextDouble();
System.out.printf("t - ");
double t = sc.nextDouble();
double s = b * sin(calcSquare((a*t)) * cos(2 * t)) -1;
System.out.println("s = b * sin(calcSquare((a*t)) * cos(2 * t)) -1");
System.out.println("s = "+s);
}
private void run() {
Scanner s = new Scanner(System.in);
System.out.printf("a - ");
double a = s.nextDouble();
System.out.printf("b - ");
double b = s.nextDouble();
System.out.printf("t - ");
double t = s.nextDouble();
print(a, b, t);
primer();
date();
}
}
| [
"dachev1919@gmail.com"
] | dachev1919@gmail.com |
7bb33e8e29aa12bbd8e0f7992fb5bb5ae4b1dfdd | 84864f862dec9171e958920f2c8e7c920fcef056 | /LeetCode/713. Subarray Product Less Than K.cpp | ff6b96061e138b56241d0fc64e348c43513df334 | [] | no_license | Orcuslc/Learning | 7704950f8c09232dadbbde81ed82ddc0ca65172d | ffa856febd85235d17358178f1e288ffae7856cb | refs/heads/master | 2020-03-26T11:59:54.093395 | 2018-05-29T04:19:36 | 2018-05-29T04:19:36 | 47,269,920 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 430 | cpp | class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int res = (nums[0] < k);
for(int i = 1; i < nums.size(); i++) {
int local = nums[i];
res += (local < k);
for(int j = i-1; j >= 0; j--) {
local *= nums[j];
if(local >= k) break;
else res++;
}
}
return res;
}
}; | [
"orcuslc@hotmail.com"
] | orcuslc@hotmail.com |
42803c8ca3a13f1b82c74fbd7a41e2b64c622961 | 7ff782c3a22da72588e457c5bc7cf6507652de03 | /ECore/ECore/src/EFrustum.cpp | d0b499ea5120959498ceb9c2dbb0db10c80059b5 | [] | no_license | bingxue102685/E3D | 7804ac643cbae1863982c7ed1330c31433cf1d56 | ef4ee5d2da116e50fe53ca19fd35e70a45a56d7e | refs/heads/master | 2020-08-23T20:34:20.113058 | 2019-11-08T04:46:33 | 2019-11-08T04:46:33 | 216,702,285 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,750 | cpp | #include "EFrustum.h"
#include "ECore.h"
namespace E3D
{
EFrustum::EFrustum(CAMERA_TYPE mode, const EVector4D &pos, const EVector4D &dir, const EVector4D &target, EFloat nearZ, EFloat farZ,
EFloat fieldofview, EFloat viewportWidth, EFloat viewportHeight)
{
camMode = mode;
position = pos;
dirction = dir;
camTarget = target;
clip_z_near = nearZ;
clip_z_far = farZ;
fov = fieldofview;
viewport_width = viewportWidth;
viewport_height = viewportHeight;
camUp = EVector4D::UNIT_Y;
camRight = EVector4D::UNIT_X;
camLook = EVector4D::UNIT_Z;
mWorldToCamera = EMatrix44::IDENTITY;
mCameraToPerspective = EMatrix44::IDENTITY;
mPerspectiveToScreen = EMatrix44::IDENTITY;
viewport_center_X = (viewport_width - 1) * 0.5f;
viewport_center_Y = (viewport_height - 1) * 0.5f;
aspect_ratio = viewport_width / viewport_height;
viewplane_width = 2.0f;
viewplane_height = 2.0f / aspect_ratio;
EFloat tan_fow_div2 = tan(Degree2Radian(fov * 0.5f));
view_dist = 0.5 * viewplane_width / tan_fow_div2;
//相机坐标系
EVector4D point = EVector4D::ZERO;
//右裁剪面
EVector4D normalR = EVector4D(-view_dist, 0, viewplane_width * 0.5f);
clip_plane_R = EPlane3D(point, normalR);
//左裁剪面
EVector4D normalL = EVector4D(view_dist, 0, viewplane_width * 0.5f);
clip_plane_L = EPlane3D(point, normalL);
//上裁剪面
EVector4D normalT = EVector4D(0, -view_dist, viewplane_height * 0.5f);
clip_plane_T = EPlane3D(point, normalT);
//下裁剪面
EVector4D normalB = EVector4D(0, view_dist, viewplane_height * 0.5f);
clip_plane_B = EPlane3D(point, normalB);
mPerspectiveToScreen = EMatrix44(
view_dist, 0, 0, 0,
0, view_dist * aspect_ratio, 0, 0,
0, 0, 1, 1,
0, 0, 0, 0);
}
} | [
"zhanghongjie@ztgame.com"
] | zhanghongjie@ztgame.com |
6b695cc28041be97e4306445e0d6f96f5f85605a | 2e8f4cdb4468af7673882ec017824c2203a47af7 | /src/phony/fwk/smgr.hpp | 84f0c3cbfc9a9856c9ec29494db27645e706ff19 | [] | no_license | tuttlem/phony | 7cd43a71c53c1a1f88dc952d0be996038bdb5ad4 | 111f3a3a75774dbaffb9c4bb09b718aa10849c04 | refs/heads/master | 2023-04-14T18:44:40.353300 | 2023-04-08T05:30:42 | 2023-04-08T05:30:42 | 3,051,334 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,777 | hpp |
#ifndef __phony_smgr_hpp_
#define __phony_smgr_hpp_
namespace phony {
class sound_effect {
public:
sound_effect(void);
sound_effect(Mix_Chunk *sound);
virtual ~sound_effect(void);
Mix_Chunk* chunk(void);
private:
Mix_Chunk *_chunk;
};
class music_piece {
public:
music_piece(void);
music_piece(Mix_Music *sound);
virtual ~music_piece(void);
Mix_Music* music(void);
private:
Mix_Music *_music;
};
/** Centralises sound and music management for the application */
class sound_manager : public singleton_manager<sound_manager> {
public:
const bool load_sound_from_wav(const std::string &key, const std::string &filename);
const bool load_music_from_wav(const std::string &key, const std::string &filename);
void toggle_music(void);
void stop_music(void);
const bool music_playing(void);
void play_sound(const std::string &key);
void play_music(const std::string &key);
/** Removes and destroys all sounds from the store */
virtual void clear(void);
private:
std::map<std::string, std::unique_ptr<sound_effect>> _sounds;
std::map<std::string, std::unique_ptr<music_piece>> _musics;
};
inline sound_effect::sound_effect(void) : _chunk(nullptr) { }
inline sound_effect::sound_effect(Mix_Chunk *sound) : _chunk(sound) { }
inline Mix_Chunk* sound_effect::chunk() { return _chunk; }
inline music_piece::music_piece(void) : _music(nullptr) { }
inline music_piece::music_piece(Mix_Music *sound) : _music(sound) { }
inline Mix_Music* music_piece::music() { return _music; }
}
#endif //__phony_smgr_hpp_
| [
"tuttlem@gmail.com"
] | tuttlem@gmail.com |
966a687fbf16ccecd1868235111e975406465cb8 | 613f88ac75206a18b2ed4b1220974f046268e27d | /server.cpp | d6163edb6c42607f7031ffc0f718c15bd3823414 | [] | no_license | serenityFX/Web_server_boost_asio_CPP | 6bca8e4334f9808de2db83b7e730c0deae83e496 | ecacf8ebcddf9079f7244706ea347dd5552cd9eb | refs/heads/master | 2021-01-10T04:17:46.074767 | 2016-02-22T14:56:50 | 2016-02-22T14:56:50 | 52,224,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,351 | cpp | #include "server.h"
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
namespace http {
namespace server3 {
server::server(const std::string& address, const std::string& port,
const std::string& doc_root, std::size_t thread_pool_size)
: thread_pool_size_(thread_pool_size),
signals_(io_service_),
acceptor_(io_service_),
new_connection_(),
request_handler_(doc_root)
{
// Register to handle the signals that indicate when the server should exit.
// It is safe to register for the same signal multiple times in a program,
// provided all registration for the specified signal is made through Asio.
signals_.add(SIGINT);
signals_.add(SIGTERM);
#if defined(SIGQUIT)
signals_.add(SIGQUIT);
#endif // defined(SIGQUIT)
signals_.async_wait(boost::bind(&server::handle_stop, this));
// Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
boost::asio::ip::tcp::resolver resolver(io_service_);
boost::asio::ip::tcp::resolver::query query(address, port);
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
acceptor_.open(endpoint.protocol());
acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor_.bind(endpoint);
acceptor_.listen();
start_accept();
}
void server::run()
{
// Create a pool of threads to run all of the io_services.
std::vector<boost::shared_ptr<boost::thread> > threads;
for (std::size_t i = 0; i < thread_pool_size_; ++i)
{
boost::shared_ptr<boost::thread> thread(new boost::thread(
boost::bind(&boost::asio::io_service::run, &io_service_)));
threads.push_back(thread);
}
// Wait for all threads in the pool to exit.
for (std::size_t i = 0; i < threads.size(); ++i)
threads[i]->join();
}
void server::start_accept()
{
new_connection_.reset(new connection(io_service_, request_handler_));
acceptor_.async_accept(new_connection_->socket(),
boost::bind(&server::handle_accept, this,
boost::asio::placeholders::error));
}
void server::handle_accept(const boost::system::error_code& e)
{
if (!e)
{
new_connection_->start();
}
start_accept();
}
void server::handle_stop()
{
io_service_.stop();
}
} // namespace server3
} // namespace http
| [
"victoryagudaev@gmail.com"
] | victoryagudaev@gmail.com |
0acf788079782aa4a7c56e41f1e13a0013fdf498 | e8a562e13ca47764ba96cb47b9e0c477447a6296 | /graph/shortest_path/sol/correct.cpp | 3eb1d9701f62de8ffb5a1a5bda028dc56d04c8ac | [
"Apache-2.0"
] | permissive | yosupo06/library-checker-problems | 0600700ee39a7b32fdec635076d75ee270c0e636 | 9d8930c908153adc3bd3f50999d782c89f666725 | refs/heads/master | 2023-08-22T19:59:02.303444 | 2023-08-10T07:58:08 | 2023-08-10T07:58:08 | 189,480,738 | 440 | 129 | Apache-2.0 | 2023-09-12T08:39:13 | 2019-05-30T20:49:42 | C++ | UTF-8 | C++ | false | false | 1,215 | cpp | #include <vector>
#include <queue>
#include <utility>
#include <stdint.h>
#include <algorithm>
#include "../fastio.h"
#define INF 1000000000000000000
template<typename T> using pqueue_inv = std::priority_queue<T, std::vector<T>, std::greater<T> >;
int main() {
int n = ri();
int m = ri();
int s = ri();
int t = ri();
std::vector<std::vector<std::pair<int, int> > > hen(n);
for (int i = 0; i < m; i++) {
int a = ri();
int b = ri();
int c = ri();
hen[a].push_back({b, c});
}
std::vector<int64_t> dist(n, INF);
std::vector<int> from(n, -1);
pqueue_inv<std::pair<int64_t, int> > que;
que.push({dist[s] = 0, s});
while (que.size()) {
auto i = que.top();
que.pop();
if (i.first != dist[i.second]) continue;
for (auto j : hen[i.second]) if (dist[j.first] > i.first + j.second)
que.push({dist[j.first] = i.first + j.second, j.first}), from[j.first] = i.second;
}
if (dist[t] == INF) println("-1");
else {
std::vector<int> path;
for (int cur = t; cur != -1; cur = from[cur]) path.push_back(cur);
std::reverse(path.begin(), path.end());
println(dist[t], ' ', path.size() - 1);
for (int i = 0; i + 1 < (int) path.size(); i++) println(path[i], ' ', path[i + 1]);
}
return 0;
}
| [
"rin20042004@gmail.com"
] | rin20042004@gmail.com |
b4a18719106625fdfbe4d4657023363a11d69a32 | faa8eb80660a7d6fff4d365fde1bab2528bab234 | /src/graphics.cpp | ccc4f3de4184b01802faf19045b285b9250b3461 | [
"MIT"
] | permissive | qwook/spine | 54aad04d552a6bf79b9083a62423439abf6af33a | 7a6aa696a3ce97629b46c682745d208bfcc70341 | refs/heads/master | 2020-04-16T08:13:28.719409 | 2013-03-27T20:19:07 | 2013-03-27T20:19:07 | 7,635,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,550 | cpp | /*
Copyright (C) 2013 Henry Tran
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.
*/
/* Welcome to Suburbia. */
#include "imath.h"
#include "ifilesystem.h"
#include "iclient.h"
#include "graphics.h"
#include <iostream>
#include <string>
#include <map>
#include <stdio.h>
#include <cmath>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GL/glfw.h>
#include "imagedata.h"
#include "fonts.h"
std::map<std::string, GLuint> shaders;
std::map<std::string, GLuint> programs;
std::map<std::string, Material> materials;
Font *test;
void MousePressedCallback(int i, int b)
{
if (b == 0) {
client->mouseDown(i);
}
else if (b == 1) {
client->mouseUp(i);
}
}
void CGraphicsModule::initDriver( short width, short height )
{
offsetX = 0;
offsetY = 0;
this->width = width;
this->height = height;
if (!glfwInit()) {
printf("Failed to start GLFW.");
exit(1);
}
#ifdef USE_OPENGL_3
glfwOpenWindowHint( GLFW_OPENGL_VERSION_MAJOR, 3 );
glfwOpenWindowHint( GLFW_OPENGL_VERSION_MINOR, 2 );
glfwOpenWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
#endif
glfwOpenWindowHint( GLFW_WINDOW_NO_RESIZE, GL_TRUE );
glfwOpenWindow( width, height, 0, 0, 0, 0, 8, 0, GLFW_WINDOW );
glfwSetWindowTitle( "Spine" );
const GLubyte* version = glGetString(GL_VERSION);
const GLubyte* renderer = glGetString(GL_RENDERER);
const GLubyte* vendor = glGetString(GL_VENDOR);
const GLubyte* glslvers = glGetString(GL_SHADING_LANGUAGE_VERSION);
printf("Version: %s\nRenderer: %s\nVendor: %s\nGLSLVersion: %s\n", version, renderer, vendor, glslvers);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
printf( "Error loading glew!" );
exit(1);
} else {
printf( "Using GLEW: %s %d\n", glewGetString(GLEW_VERSION), glewIsSupported("GL_ARB_fragment_program") );
}
// Compile all the shaders.
DirectoryList list = filesystem->getDirectoryList("./shaders/");
for (DirectoryList::iterator i = list.begin(); i != list.end(); ++i) {
char name[50];
char exten[10];
util->getFileName(name, (*i).c_str());
util->getFileExtension(exten, (*i).c_str());
Buffer buffer;
File *file = filesystem->open((*i).c_str());
file->readBuffer(&buffer);
if (strcmp(exten, ".fsh") == 0) {
const char *c_str = buffer.data;
GLuint fragmentShader = glCreateShader( GL_FRAGMENT_SHADER );
glShaderSource( fragmentShader, 1, &c_str, NULL );
glCompileShader( fragmentShader );
shaders[name] = fragmentShader;
GLint status;
glGetShaderiv( fragmentShader, GL_COMPILE_STATUS, &status );
if (status == GL_TRUE) {
printf("Loaded fragment shader: %s (%d)\n", name, fragmentShader);
} else {
char buffer[512];
glGetShaderInfoLog( fragmentShader, 512, NULL, buffer );
printf("Error loading fragment shader: %s (%d)\n", name, fragmentShader);
printf("%s\n", buffer);
}
} else if (strcmp(exten, ".vsh") == 0) {
const char *c_str = buffer.data;
GLuint vertexShader = glCreateShader( GL_VERTEX_SHADER );
glShaderSource( vertexShader, 1, &c_str, NULL );
glCompileShader( vertexShader );
shaders[name] = vertexShader;
GLint status;
glGetShaderiv( vertexShader, GL_COMPILE_STATUS, &status );
if (status == GL_TRUE) {
printf("Loaded vertex shader: %s (%d)\n", name, vertexShader);
} else {
char buffer[512];
glGetShaderInfoLog( vertexShader, 512, NULL, buffer );
printf("Error loading vertex shader: %s (%d)\n", name, vertexShader);
printf("%s\n", buffer);
}
}
delete file;
}
// Compile all the programs.
for (DirectoryList::iterator i = list.begin(); i != list.end(); ++i) {
char exten[10];
util->getFileExtension(exten, (*i).c_str());
if (strcmp(exten, ".kv") == 0) {
char name[50];
util->getFileName(name, (*i).c_str());
util->getFileNameNoExtension(name, name);
Buffer buffer;
File *file = filesystem->open((*i).c_str());
file->readBuffer(&buffer);
KeyValue *kv = util->parseKeyValue(&buffer);
GLuint shaderProgram = glCreateProgram();
KeyValue *shadermembers = kv->getMember("shaders");
if (shadermembers != NULL) {
unsigned int b = 0;
KeyValue *member = shadermembers->getMember(b);
while ((member = shadermembers->getMember(b)) != NULL) {
glAttachShader( shaderProgram, shaders[member->getString()] );
b++;
}
}
KeyValue *fragdatamembers = kv->getMember("fragdata");
if (fragdatamembers != NULL) {
unsigned int b = 0;
KeyValue *member = fragdatamembers->getMember(b);
while ((member = fragdatamembers->getMember(b)) != NULL) {
glBindFragDataLocation( shaderProgram, b, member->getString().c_str());
b++;
}
}
glLinkProgram( shaderProgram );
glUseProgram( shaderProgram );
GLint posAttrib = glGetAttribLocation( shaderProgram, "position" );
glEnableVertexAttribArray( posAttrib );
glVertexAttribPointer( posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0 );
programs[name] = shaderProgram;
printf("Loaded program: %s (%d)\n", name, shaderProgram);
kv->release();
file->release();
}
}
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glBlendEquation( GL_FUNC_ADD );
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
loadMaterial("disttex.tga");
loadMaterial("8.tga");
// load default textures
ImageData white(1, 1);
white.setPixel(0, 0, Color(255, 255, 255));
loadMaterial("white", &white);
ImageData black(1, 1);
black.setPixel(0, 0, Color(0, 0, 0));
loadMaterial("black", &black);
glfwSetMouseButtonCallback(&MousePressedCallback);
}
Font *CGraphicsModule::loadFont(const char *fontFile, int size)
{
return new Font(fontFile, size, 128, 128);
}
void CGraphicsModule::drawText( Font *font, const char *text, Vector2Df pos ) {
font->drawString(text, pos);
}
Material CGraphicsModule::loadMaterial(const char *matName, ImageData *data) {
Material material = materials[matName];
if (material.mat) {
return useMaterial(matName);
}
GLuint textureID;
glGenTextures( 1, &textureID );
glActiveTexture(GL_TEXTURE0);
glBindTexture( GL_TEXTURE_2D, textureID );
unsigned int format = GL_RGBA;
unsigned int level = 0;
glTexImage2D( GL_TEXTURE_2D, level, format,
data->width, data->height, 0, format,
GL_UNSIGNED_BYTE, (void*) data->data );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
Material ret = { (unsigned int)textureID, data->width, data->height };
materials[matName] = ret;
return ret;
}
Material CGraphicsModule::loadMaterial(const char *matName) {
Material material = materials[matName];
if (material.mat) {
return useMaterial(matName);
}
GLuint textureID;
glGenTextures( 1, &textureID );
GLFWimage teximg; // Use intermediate GLFWimage to get width and height
if(!glfwReadImage(matName, &teximg, GLFW_NO_RESCALE_BIT))
printf("I/O error %s", "Failed to load distance texture from TGA file.");
glActiveTexture(GL_TEXTURE0);
glBindTexture( GL_TEXTURE_2D, textureID );
glfwLoadTextureImage2D( &teximg, 0 );
unsigned int width = teximg.Width, height = teximg.Height;
// The special shader used to render this texture performs its own minification
// and magnification. Specify nearest neighbor sampling to avoid trampling
// over the distance values split over two channels as 8.8 fixed-point data.
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glfwFreeImage(&teximg); // Clean up the malloc()'ed data pointer
Material ret = { (unsigned int)textureID, width, height };
materials[matName] = ret;
return ret;
}
Material CGraphicsModule::useMaterial(const char *matName) {
Material material = materials[matName];
if (material.mat) {
glActiveTexture(GL_TEXTURE0);
glBindTexture( GL_TEXTURE_2D, material.mat );
return material;
}
Material ret = {0, 0, 0};
return ret;
}
Material CGraphicsModule::useMaterial(unsigned int mat) {
glActiveTexture(GL_TEXTURE0);
glBindTexture( GL_TEXTURE_2D, mat );
int width, height;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
Material ret = { (unsigned int)mat, (unsigned int)width, (unsigned int)height };
return ret;
}
unsigned int CGraphicsModule::useProgram(const char *programName) {
GLuint program = programs[programName];
if (program) {
glUseProgram(program);
return program;
}
return 0;
}
unsigned int CGraphicsModule::useProgram(unsigned int program) {
glUseProgram(program);
return program;
}
void CGraphicsModule::setProgramVar1f(unsigned int program, const char *var, float i) {
GLint location = glGetUniformLocation( program, var );
glUniform1f( location, i );
}
void CGraphicsModule::setProgramVar1i(unsigned int program, const char *var, int i) {
GLint location = glGetUniformLocation( program, var );
glUniform1i( location, i );
}
void CGraphicsModule::drawQuad(float x, float y, float width, float height) {
glBegin( GL_QUADS );
glTexCoord2f( 0.0f, 1.0f );
glVertex2f( x+offsetX, y+height+offsetY );
glTexCoord2f( 1.0f, 1.0f );
glVertex2f( x+width+offsetX, y+height+offsetY );
glTexCoord2f( 1.0f, 0.0f );
glVertex2f( x+width+offsetX, y+offsetY );
glTexCoord2f( 0.0f, 0.0f );
glVertex2f( x+offsetX, y+offsetY );
glEnd();
}
void CGraphicsModule::drawQuadUV(float x, float y, float width, float height, float u1, float u2, float v1, float v2) {
glBegin( GL_QUADS );
glTexCoord2f( u1, v2 );
glVertex2f( x+offsetX, y+height+offsetY );
glTexCoord2f( v1, v2 );
glVertex2f( x+width+offsetX, y+height+offsetY );
glTexCoord2f( v1, u2 );
glVertex2f( x+width+offsetX, y+offsetY );
glTexCoord2f( u1, u2 );
glVertex2f( x+offsetX, y+offsetY );
glEnd();
}
void CGraphicsModule::setColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
glColor4f((float)r/255.0f, (float)g/255.0f, (float)b/255.0f, (float)a/255.0f);
}
void CGraphicsModule::init( IModuleManager* modulemanager ) {
}
void CGraphicsModule::release() {
glfwTerminate();
}
bool CGraphicsModule::isWindowOpen() {
if ( glfwGetKey( GLFW_KEY_ESC ) == GLFW_PRESS ) {
return false;
}
if ( !glfwGetWindowParam( GLFW_OPENED ) ) {
return false;
}
return true;
}
void CGraphicsModule::clear() {
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDepthMask(true);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho(0.0f, 1.0f*getWidth(), 1.0f*getHeight(), 0.0f, 0.0f, 1.0f);
//glOrtho(0.0f, 1.0f*800, 0.0f, 1.0f*600, -1.0f, 100.0f);
//gluPerspective( 45.0f, (GLfloat)800/(GLfloat)600, 1.0f, 100.0f );
//glViewport( 0, 0, 640, 480 );
glDepthMask(false);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
offsetX = 0;
offsetY = 0;
while ( scissorStack.size() > 0 ) {
popScissor();
}
}
void CGraphicsModule::setCursorVisible( bool visible ) {
if ( visible ) {
glfwEnable( GLFW_MOUSE_CURSOR );
} else {
glfwDisable( GLFW_MOUSE_CURSOR );
}
}
Vector2Df CGraphicsModule::getCursorPos() {
int x, y;
glfwGetMousePos(&x, &y);
return Vector2Df((float)x, (float)y);
}
void CGraphicsModule::update() {
glfwSwapBuffers();
}
void CGraphicsModule::pushScissor(bool enable, int x, int y, int width, int height, bool offset) {
int cutx = 0;
int cuty = 0;
int cutwidth = 0;
int cutheight = 0;
int nX = x;
int nY = y;
int nWidth = width;
int nHeight = height;
if ( enable ) {
glEnable(GL_SCISSOR_TEST);
if ( scissorStack.size() > 0 ) {
Scissor s = *scissorStack.end()--;
if ( x < s.x ) {
cutx = s.x - x;
}
if ( y < s.y ) {
cuty = s.y - y;
}
if ( x + width > s.x + s.width ) {
cutwidth = (x + width) - (s.x + s.width);
}
if ( y + height > s.y + s.height ) {
cutheight = (y + height) - (s.y + s.height);
}
}
nX = x - cutx;
nY = getHeight() - y - cuty - height;
nWidth = width - cutx - cutwidth;
nHeight = height - cuty - cutheight;
glScissor(nX, nY, nWidth, nHeight);
} else {
glDisable(GL_SCISSOR_TEST);
}
if (offset == true) {
offsetX += x;
offsetY += y;
}
scissorStack.push_back(Scissor(enable, nX, nY, nWidth, nHeight, offset, x, y));
}
void CGraphicsModule::popScissor(){
if ( scissorStack.size() > 0 ) {
Scissor s = *scissorStack.rbegin();
if ( s.offset == true ) {
offsetX -= s.ox;
offsetY -= s.oy;
}
}
scissorStack.pop_back();
if ( scissorStack.size() > 0 ) {
Scissor s = *scissorStack.end()--;
if ( s.enable ) {
glEnable(GL_SCISSOR_TEST);
glScissor(s.x, s.y, s.width, s.height);
} else {
glDisable(GL_SCISSOR_TEST);
}
} else {
glDisable(GL_SCISSOR_TEST);
}
}
short CGraphicsModule::getWidth() {
return width;
}
short CGraphicsModule::getHeight() {
return height;
}
extern "C" IModule * SPINE_DLLEXPORT loadModule() {
graphics = new CGraphicsModule();
return graphics;
}
extern "C" void SPINE_DLLEXPORT unloadModule() {
delete (CGraphicsModule *)graphics;
} | [
"henrytran@Henrys-MacBook-Pro.local"
] | henrytran@Henrys-MacBook-Pro.local |
634d3ac4e756bfd74c994500c2ba71c4260ddc9e | 2360305c0a9d7a4a642144aa1e44a93d45c0dca4 | /src/osinterface/OSVirtualScreen.h | cb7b9421a34dfaae4c28bbdd6cb5ea23df78a9be | [] | no_license | vdods/os-controls | 96e4fcefac1143d841291e20bbc35b84e6af5abc | 4ce5dbcebbf855f6e036f5d42db85c60d9d74de4 | refs/heads/master | 2021-06-06T12:42:13.958298 | 2014-09-19T01:16:22 | 2014-09-19T01:16:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,121 | h | // Copyright (c) 2010 - 2014 Leap Motion. All rights reserved. Proprietary and confidential.
#pragma once
#include "OSScreen.h"
#include "OSCursor.h"
#include <vector>
#include <mutex>
class OSCursor;
class OSVirtualScreenListener {
public:
OSVirtualScreenListener(void) {}
virtual ~OSVirtualScreenListener(void) {}
virtual void OnChange(void) = 0;
};
class OSVirtualScreen :
public ContextMember,
public OSScreenBase
{
public:
OSVirtualScreen();
virtual ~OSVirtualScreen();
static OSVirtualScreen* New(void);
std::vector<OSScreen> Screens() const {
std::lock_guard<std::mutex> lock(m_mutex);
return m_screens;
}
OSScreen PrimaryScreen() const;
OSScreen ClosestScreen(const OSPoint& position) const;
protected:
virtual std::vector<OSScreen> GetScreens() const = 0;
void Update();
private:
OSRect ComputeBounds(const std::vector<OSScreen>& screens);
OSPoint ClipPosition(const OSPoint& position, uint32_t* index) const;
mutable std::mutex m_mutex;
std::vector<OSScreen> m_screens;
AutoRequired<OSCursor> m_cursor;
};
| [
"jmarsden@leapmotion.com"
] | jmarsden@leapmotion.com |
c30175c73150bd4a68391bbf9deaa0d5eaef4d8f | 8164dd9ec33a14acdeda6c148c33de5ff30c91ae | /src/CreationalPattern/AbstractFactory/AbstractFactory/AbstractFactory.h | 91ba1444de31dbbd007e4239c80f0d584a1e829a | [] | no_license | kingdekong/Design-Patterns | a4ff6d5e91d5d401f8de5b2943a2de2d25d3f805 | cf0dc873d92f45d3457405b5dc670f290974eac6 | refs/heads/master | 2020-03-29T08:37:34.061320 | 2018-09-21T08:56:23 | 2018-09-21T08:56:23 | 149,719,919 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | h | #ifndef _HEADER_AbstractFactory_
#define _HEADER_AbstractFactory_
#include "AbstractProductA.h"
#include "AbstractProductB.h"
class AbstractFactory
{
public:
AbstractFactory();
virtual ~AbstractFactory();
virtual AbstractProductA* createProductA() = 0;
virtual AbstractProductB* createProductB() = 0;
private:
};
#endif // !_HEADER_AbstractFactory_
| [
"degang_jin@htc.com"
] | degang_jin@htc.com |
41a4e1a6888895cd1ad3598b03cfba6c87b0d730 | 805109c841a3431bc6f543ee9b3ab3da07b5460d | /isSymmetric/isSymmetric/main.cpp | 25a72199327febe5bb1193e7c57eaaaa4ab4d95a | [] | no_license | jingninc/algorithm | bc4f8e3ecd845596e418c297bf11da917e868241 | 481406c8d5763585ff645a85db26f9deb5376cab | refs/heads/master | 2016-09-05T16:12:32.324491 | 2015-02-02T19:00:23 | 2015-02-02T19:00:23 | 30,202,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,023 | cpp | //
// main.cpp
// isSymmetric
//
// Created by JINGNING CAO on 1/11/15.
// Copyright (c) 2015 JINGNING CAO. All rights reserved.
//
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <sstream>
#include <unordered_set>
#include <unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
bool isSame(TreeNode* root1, TreeNode* root2){
if (!root1 && !root2) return true;
if (!root1 || !root2) return false;
if (root1->val != root2->val) return false;
return isSame(root1->left, root2->right) && isSame(root1->right, root2->left);
}
bool isSymmetric(TreeNode *root) {
if (!root) return true;
return isSame(root->left, root->right);
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
| [
"caojn909224@gmail.com"
] | caojn909224@gmail.com |
4a6dbe6d34bc83a5aea452c028b75bc5aebc81bf | bdeb62dc7c23535b3be863c3cea2c88f43c13420 | /Codes/Q12.CPP | 73542c5f826ef4568e6dd97e2aabd960d27d8174 | [
"MIT"
] | permissive | Shetty073/Cpp-practical-codes | 4cf9b7bec6c6eb802abc6b78e1f676111e77f49a | 13a9b169f10579985606456af564148c57c514f1 | refs/heads/master | 2020-05-15T12:52:36.571661 | 2019-04-24T13:43:01 | 2019-04-24T13:43:01 | 182,280,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | cpp | #include <iostream.h>
#include <conio.h>
class Cities
{
char city[30];
public:
void read();
void display();
};
void Cities::read()
{
cin.getline(city,30);
}
void Cities::display()
{
if(city[0] == 'B' || city[0] == 'C'|| city[0] == 'b'|| city[0] == 'c')
{
cout<<city<<" ";
}
}
void main()
{
clrscr();
cout<<"Enter the name of the cities: ";
Cities c[5];
for(int i=0; i<5; i++)
{
c[i].read();
}
cout<<"Cities with name starting from 'B' or 'C': ";
for(i = 0; i < 5; i++)
{
c[i].display();
}
getch();
}
| [
"30448930+Shetty073@users.noreply.github.com"
] | 30448930+Shetty073@users.noreply.github.com |
0e699652f693c6acb0c99dbadeb3bd2cd1ff9d1e | 92642c8c20ed4fec0c25689677c57321965c8984 | /Source/UnrealFlecs/Private/UnrealFlecsModule.cpp | 7252457de1ec197947402069921eab1baaddc868 | [
"MIT"
] | permissive | Junho2009/UnrealFlecsQuickstart | 6dd94ded960acf722b066b461aa1363984a73862 | 53ecc500b6946fa115f61a73232ca66de942c355 | refs/heads/master | 2023-04-11T15:06:56.569526 | 2021-03-23T20:46:48 | 2021-03-23T20:46:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | // Copyright 2021 Red J
#include "UnrealFlecs/Public/UnrealFlecsModule.h"
#include "Modules/ModuleManager.h"
#include "Modules/ModuleInterface.h"
IMPLEMENT_GAME_MODULE(FUnrealFlecsModule, UnrealFlecs);
DEFINE_LOG_CATEGORY(UnrealFlecs);
#define LOCTEXT_NAMESPACE "UnrealFlecs"
void FUnrealFlecsModule::StartupModule()
{
UE_LOG(UnrealFlecs, Warning, TEXT("UnrealFlecs module has started!"));
}
void FUnrealFlecsModule::ShutdownModule()
{
UE_LOG(UnrealFlecs, Warning, TEXT("UnrealFlecs module has shut down"));
}
#undef LOCTEXT_NAMESPACE
// Add default functionality here for any IUnrealFlecsModule functions that are not pure virtual.
| [
"jtferson@gmail.com"
] | jtferson@gmail.com |
90bd3848b8ed8fbda73fad84955ef0cc1c131fc8 | 87e3fdaf3d40618eb980e1af6cd5909cfab548e3 | /BeTrains/inc/Controller/Controller.h | 202f2adcb110a45e8fa56d6b65613f68fa3594b4 | [] | no_license | bartbru/BeTrains.Bada | e768cf769cad0f8d539dbe56722a88d395682553 | 7493c459130c93286248dc94ccc83156b1ab355c | refs/heads/master | 2016-09-06T16:08:47.658844 | 2010-11-21T18:53:37 | 2010-11-21T18:53:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 225 | h | /*
* Controller.h
*
* Created on: 21-nov-2010
* Author: Bart Bruynooghe
*/
#ifndef CONTROLLER_H_
#define CONTROLLER_H_
class Controller {
public:
Controller();
virtual ~Controller();
};
#endif /* CONTROLLER_H_ */
| [
"bart.bruynooghe@gmail.com"
] | bart.bruynooghe@gmail.com |
5c2bf4968ccf50621b80a917ba0f8bdbabd41e62 | 2d209723d1a723df319d60c3805aa598f0677f6f | /include/AttributeInfo.h | f9470a91307bb00eaa9eb59dfbce271d81b2100d | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | HDFGroup/psh5x | d81bcf7a4b92cc59b43ef0e3c508de53e2193eb9 | 4d1521ed79cd894b34329ab019213bd783721e6b | refs/heads/master | 2020-05-18T11:20:23.635946 | 2015-07-15T20:57:53 | 2015-07-15T20:57:53 | 39,159,932 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,828 | h | #pragma once
extern "C" {
#include "H5Apublic.h"
#include "H5Opublic.h"
}
namespace PSH5X
{
public ref class AttributeInfo
{
public:
property System::String^ AttributeName
{
System::String^ get() { return m_attribute_name; }
}
property bool CreationOrderIsValid
{
bool get() { return (m_corder_valid > 0); }
}
property long long CreationOrder
{
long long get() { return safe_cast<long long>(m_corder); }
}
property System::String^ AttributeNameCharacterSet
{
System::String^ get() { return m_cset; }
}
property hsize_t DataSizeBytes
{
hsize_t get() { return m_data_size; }
}
AttributeInfo(System::String^ name, H5A_info_t* info)
{
m_attribute_name = name;
m_corder_valid = info->corder_valid;
m_corder = info->corder;
switch (info->cset)
{
case H5T_CSET_ASCII:
m_cset = gcnew System::String("ASCII");
break;
case H5T_CSET_UTF8:
m_cset = gcnew System::String("UTF-8");
break;
default:
m_cset = gcnew System::String("UNKNOWN");
break;
}
m_data_size = info->data_size;
}
~AttributeInfo()
{
delete m_attribute_name;
delete m_cset;
}
private:
System::String^ m_attribute_name;
hbool_t m_corder_valid;
int64_t m_corder;
System::String^ m_cset;
hsize_t m_data_size;
};
} | [
"gheber@bc1736a7-42db-4d61-a5e1-31a1cdc50de3"
] | gheber@bc1736a7-42db-4d61-a5e1-31a1cdc50de3 |
4ad20458f9bffd0ec6ef965b916ff0d51803e74e | edfaf7367f0298cc921c96b9e783df41a952f0f5 | /5766.cpp | 0fd584731d9b71ae134c1b5abd1627edd222acd0 | [] | no_license | urrburu/baekjoon-algo | 4993beabc68cc97b6ea19a3deed2607e9df1e0ed | 5090a9f7395e53dbcf423e1c1cc1a966b19996e3 | refs/heads/master | 2021-11-09T22:39:01.096357 | 2021-11-03T11:38:26 | 2021-11-03T11:38:26 | 190,715,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 555 | cpp | #include<iostream>
#include<queue>
using namespace std;
int main() {
int n, m;
while (1) {
cin >> n >> m; int point[10001] = { 0, };
if (n == 0 && m == 0)break;
for (int i = 0; i < n * m; ++i) {
int tmp; cin >> tmp; point[tmp]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > pq;
for (int i = 1; i < 10001; ++i) {
pq.push({ -point[i],i });
}
pq.pop();
int tar = pq.top().first;
while (pq.top().first == tar) {
cout << pq.top().second << " ";
pq.pop();
}
cout << "\n";
}
} | [
"bbs4614@naver.com"
] | bbs4614@naver.com |
7df9523a01bf9a54c740cd7ba7310730e06575b8 | 0e4599175e153ed73ed26b9226f28a01928bfde0 | /rf_pipelines_internals.hpp | c67befe0c9ec10faf84e5665922185a81d702a7a | [] | no_license | dstndstn/rf_pipelines | 8d1250eefa5133a22e38f0b62bbd304a9f9f5b72 | af1e9e1df73dc5e8912471481bd5036a8d6a826c | refs/heads/master | 2021-01-11T20:35:18.958563 | 2017-02-21T17:06:20 | 2017-02-21T17:06:20 | 79,148,402 | 0 | 0 | null | 2017-01-16T18:48:13 | 2017-01-16T18:48:13 | null | UTF-8 | C++ | false | false | 9,764 | hpp | #ifndef _RF_PIPELINES_INTERNALS_HPP
#define _RF_PIPELINES_INTERNALS_HPP
#if (__cplusplus < 201103) && !defined(__GXX_EXPERIMENTAL_CXX0X__)
#error "This source file needs to be compiled with C++0x support (g++ -std=c++0x)"
#endif
#include <cmath>
#include <cstring>
#include <sstream>
#include <stdexcept>
#include <sys/time.h>
#include <thread>
#include <condition_variable>
#include "rf_pipelines.hpp"
// Branch predictor hint
#ifndef _unlikely
#define _unlikely(cond) (__builtin_expect(cond,0))
#endif
// rf_assert(): like assert, but throws an exception in order to work smoothly with python.
#define rf_assert(cond) rf_assert2(cond, __LINE__)
#define rf_assert2(cond,line) \
do { \
if (_unlikely(!(cond))) { \
const char *msg = "rf_pipelines: assertion '" __STRING(cond) "' failed (" __FILE__ ":" __STRING(line) ")\n"; \
throw std::runtime_error(msg); \
} \
} while (0)
namespace rf_pipelines {
#if 0
}; // pacify emacs c-mode
#endif
//
// A note for the future: if rf_pipelines is ever made multithreaded, then there are
// some race conditions related to the output_tracker which will need to be fixed. The
// basename_set should be protected by a lock, and we also probably want a lock to
// protect the wi_transform::output_output_tracker pointer itself. We may also want the
// output_tracker to create a lockfile in the output directory.
//
struct outdir_manager {
std::string outdir; // can be an empty string, otherwise includes trailing slash
bool clobber_ok = true;
std::set<std::string> basename_set;
// Constructor creates the output directory.
outdir_manager(const std::string &outdir, bool clobber_ok);
// Returns the full pathname, throws exception if filename has already been written in this pipeline run.
std::string add_file(const std::string &basename);
void write_per_substream_json_file(int isubstream, const Json::Value &data, int verbosity);
static bool is_json_basename(const std::string &basename);
};
struct plot_group {
std::string name;
int nt_per_pix = 0;
int ny = 0;
bool is_empty = true;
int64_t curr_it0 = 0;
int64_t curr_it1 = 0;
Json::Value files;
plot_group(const std::string &name_, int nt_per_pix_, int ny_) :
name(name_), nt_per_pix(nt_per_pix_), ny(ny_)
{
if (nt_per_pix < 1)
throw std::runtime_error("rf_pipelines::plot_group: nt_per_pix must be >= 1");
if (ny < 1)
throw std::runtime_error("rf_pieplines::plot_group: ny must be >= 1");
}
};
// -------------------------------------------------------------------------------------------------
//
// log_2(2^n) -> n
inline bool is_power_of_two(int n)
{
rf_assert(n >= 1);
return (n & (n-1)) == 0;
}
struct integer_log2_lookup_table {
int nmax;
std::vector<int> v;
integer_log2_lookup_table(int nmax)
{
rf_assert((nmax > 0) && is_power_of_two(nmax));
this->v = std::vector<int> (nmax+1,-1);
for (int i = 0; (1<<i) <= nmax; i++)
v[1<<i] = i;
}
// Caller must check 0 <= n <= nmax.
// If n is not a power of two, then (-1) will be returnd.
inline int operator()(int n) { return v[n]; }
};
// Compile-time integer-valued log_2()
template<unsigned int D, typename std::enable_if<(D==1),int>::type = 0>
inline constexpr int IntegerLog2() { return 0; }
template<unsigned int D, typename std::enable_if<(D>1 && (D%2)==0),int>::type = 0>
inline constexpr int IntegerLog2() { return IntegerLog2<(D/2)>() + 1; }
// -------------------------------------------------------------------------------------------------
//
// timing_thread (general-purpose timing thread), and transform_timing_thread (subclass for timing wi_transforms).
class timing_thread_pool {
public:
const int nthreads;
timing_thread_pool(int nthreads);
typedef struct timeval time_t;
time_t start_timer();
double stop_timer(const time_t &start_time);
// Helper function called by timing_thread.
int get_and_increment_thread_id();
protected:
std::mutex lock;
std::condition_variable cond0;
std::condition_variable cond1;
std::condition_variable cond2;
double total_dt = 0.0;
int threads_so_far = 0;
int ix0 = 0;
int ix1 = 0;
int ix2 = 0;
};
class timing_thread {
public:
const std::shared_ptr<timing_thread_pool> pool;
const bool pinned_to_core;
const int thread_id;
const int nthreads;
static void _thread_main(timing_thread *t);
virtual ~timing_thread() { }
protected:
timing_thread(const std::shared_ptr<timing_thread_pool> &pool, bool pin_to_core);
virtual void thread_body() = 0;
timing_thread_pool::time_t start_time;
bool timer_is_running = false;
// Thread-collective: all threads wait at a barrier, then initialize their local timers.
void start_timer();
// Thread-collective: the returned time is the average taken over all threads.
// If 'name' is non-null, then timing will be announced on thread ID zero.
double stop_timer(const char *name=nullptr);
};
struct transform_timing_thread : public timing_thread
{
const int nfreq;
const int nt_chunk;
const int stride;
const int num_chunks = 16;
float *intensity = nullptr;
float *weights = nullptr;
std::vector<std::shared_ptr<wi_transform>> transform_list;
int ntransforms = 0;
transform_timing_thread(const std::shared_ptr<timing_thread_pool> &pool, int nfreq, int nt_chunk, int stride,
const std::vector<std::shared_ptr<wi_transform>> &transform_list);
~transform_timing_thread();
// Noncopyable
transform_timing_thread(const transform_timing_thread &) = delete;
transform_timing_thread &operator=(const transform_timing_thread &) = delete;
virtual void thread_top(); // default thread_top(): prints nfreq, nt_chunk, stride on thread_id 0
virtual void thread_body() override; // overrides timing_thread::thread_body(), times transforms in transform_list
virtual void thread_bottom() {} // optional: if the timing thread should do anything else, it can go here
};
// Can be called for any subclass T of timing_thread (including T=transform_timing_thread)
template<typename T, typename... Args>
std::thread spawn_timing_thread(Args... args)
{
timing_thread *t = new T(args...);
return std::thread(timing_thread::_thread_main, t);
}
// -------------------------------------------------------------------------------------------------
// Non-inline helper functions (more to come?)
extern bool file_exists(const std::string &filename);
extern void makedirs(const std::string &dirname);
extern std::vector<std::string> listdir(const std::string &dirname);
// The "wrms_hack_for_testing" is explained in test-cpp-python-equivalence.py
extern void _wrms_hack_for_testing1(std::vector<float> &mean_hint, const float *intensity, const float *weights, int nfreq, int nt, int stride, int niter, double sigma, bool two_pass);
extern void _wrms_hack_for_testing2(float &mean, float &rms, const float *intensity, const float *weights, int nfreq, int nt, int stride, const std::vector<float> &mean_hint);
// Inlines follow...
template<typename T>
inline T square(T x)
{
return x*x;
}
inline double uniform_rand()
{
return (rand() + 0.5) / (RAND_MAX + 1.0);
}
inline double uniform_rand(double lo, double hi)
{
return lo + (hi-lo)*uniform_rand();
}
inline ssize_t randint(ssize_t lo, ssize_t hi)
{
rf_assert(lo < hi);
ssize_t ret = lo + (ssize_t)((hi-lo)*uniform_rand());
ret = std::max(ret, lo); // should be redundant
ret = std::min(ret, hi-1); // should be redundant
return ret;
}
inline double dist(double x, double y)
{
return fabs(x-y);
}
inline double reldist(double x, double y)
{
return fabs(x-y) / (fabs(x) + fabs(y));
}
// round up m to nearest multiple of n
inline ssize_t round_up(ssize_t m, ssize_t n)
{
rf_assert(m >= 0);
rf_assert(n > 0);
return ((m+n-1)/n) * n;
}
inline ssize_t gcd(ssize_t m, ssize_t n)
{
if (m < n)
std::swap(m, n);
if (n < 0)
throw std::runtime_error("gcd() called with negative argument");
while (n > 0) {
ssize_t d = m % n;
m = n;
n = d;
}
return m;
}
template<typename T>
inline std::string stringify(const T &x)
{
std::stringstream ss;
ss << x;
return ss.str();
}
inline bool startswith(const std::string &str, const std::string &prefix)
{
return std::equal(prefix.begin(), prefix.end(), str.begin());
}
inline bool endswith(const std::string &str, const std::string &suffix)
{
return std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
}
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&& ...args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<typename T>
inline T *aligned_alloc(size_t nelts)
{
if (nelts == 0)
return NULL;
// align to 64-byte cache lines
void *p = NULL;
if (posix_memalign(&p, 64, nelts * sizeof(T)) != 0)
throw std::runtime_error("couldn't allocate memory");
memset(p, 0, nelts * sizeof(T));
return reinterpret_cast<T *> (p);
}
// std::vector doesn't provide a member function which guarantees deallocation!
template<typename T> static inline void deallocate(std::vector<T> &v)
{
std::vector<T> w;
v.swap(w);
}
inline double time_diff(const struct timeval &tv1, const struct timeval &tv2)
{
return (tv2.tv_sec - tv1.tv_sec) + 1.0e-6 * (tv2.tv_usec - tv1.tv_usec);
}
inline struct timeval get_time()
{
struct timeval ret;
if (gettimeofday(&ret, NULL) < 0)
throw std::runtime_error("gettimeofday() failed");
return ret;
}
} // namespace rf_pipelines
#endif // _RF_PIPELINES_INTERNALS_HPP
| [
"kmsmith@perimeterinstitute.ca"
] | kmsmith@perimeterinstitute.ca |
49041f3de27a7e9efce11ee41df5911472ec4bec | 674a19eae7fc0d5f98c8b8a8b87b093d17e79480 | /src/olac/Arguments.cpp | 3f5023653209b6c227299bf4eb199a73d07c1fc8 | [] | no_license | citiral/Ola | f6d6ebac0433ca7d7c4d92e7ad0bb0c81af584c0 | 7f39546a2c5ee7d9b6da8cbf09cb5245b5a536f5 | refs/heads/master | 2021-01-18T23:19:12.550577 | 2016-07-18T12:01:56 | 2016-07-18T12:01:56 | 41,514,192 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,819 | cpp | //
// Created by Citiral on 8/11/2015.
//
#include "Arguments.h"
#include "defines.h"
namespace olac {
Arguments::Arguments() {
}
void Arguments::parseArguments(int count, char** args) {
//loop over each argument
for (int i = 0 ; i < count ; i++)
{
//get the name of the argument
std::string name = args[i];
//if the argument starts with '--', remove the dashes
if (name[0] == '-' && name[1] == '-') {
name = name.substr(2, std::string::npos);
}//if the argument starts with '-', remove the dash and expand it
else if (name[0] == '-' && name[1] != '-') {
//remove the dashes from the name
name = name.substr(1, std::string::npos);
//if it has an expansion, expand it
auto expansion = _argumentExpansions.find(name);
if (expansion != _argumentExpansions.end())
name = expansion->second;
}//if the argument doesn't start with '-', it is an argumentless value
else if (name[0] != '-') {
_argumentlessValues.push_back(name);
continue;
}
//now look up the type of the argument
auto typeIter = _argumentTypes.find(name);
//if it has no type, throw a warning and skip it
if (typeIter == _argumentTypes.end()) {
WARNING("Unknown argument " << name);
continue;
}
//get the actual type value
ArgumentType type = typeIter->second;
switch (type) {
case ArgumentType::Flag:
_argumentValues[name] = "true";
break;
case ArgumentType::Value:
//if this is the last argument, throw a warning
if (i == count - 1) {
WARNING("Expected value after argument " << name);
continue;
}
_argumentValues[name] = args[i+1];
i++;
break;
}
}
}
std::string Arguments::getArgumentValue(std::string name) {
return _argumentValues[name];
}
std::string Arguments::getArgumentlessValue(u32 index) {
return _argumentlessValues[index];
}
bool Arguments::argumentValueEquals(std::string name, std::string value) {
return _argumentValues[name].compare(value) == 0;
}
bool Arguments::argumentlessValueEquals(u32 index, std::string value) {
return _argumentlessValues[index].compare(value) == 0;
}
u32 Arguments::getArgumentlessValuesCount() {
return _argumentlessValues.size();
}
void Arguments::registerArgumentType(std::string name, ArgumentType type) {
_argumentTypes[name] = type;
}
void Arguments::registerArgumentExpansion(std::string shortname, std::string longname) {
_argumentExpansions[shortname] = longname;
}
void Arguments::registerRequiredArgument(std::string name) {
_requiredArguments.push_front(name);
}
bool Arguments::checkValidity() {
bool validity = true;
//for each required argument
for (std::string& name : _requiredArguments) {
//if there is no value for it, set the validity to false and throw a warning about the missing argument
if (_argumentValues.find(name) == _argumentValues.end()) {
validity = false;
WARNING("Missing required argument " << name);
}
}
return validity;
}
} | [
"olivier4@telenet.be"
] | olivier4@telenet.be |
81aef4ef388b4fd92c0e9c89a97c1937abf6cf96 | b461fdf61932e694ad51fff61ee628cfef1f6b4e | /atmega8l/ReflowingHandler.h | af01e17b0b59199168e8ca3381303fda81296fbf | [] | no_license | AtomSoftTech/awreflow2 | 32127399493f42d1763ac64d49be021d880af8d4 | 05d1e8bbc982c020c1324d6d42512c102c96a78c | refs/heads/master | 2020-12-03T07:52:26.016207 | 2015-07-12T09:24:50 | 2015-07-12T09:24:50 | 39,167,938 | 1 | 0 | null | 2015-07-16T00:30:06 | 2015-07-16T00:30:04 | null | UTF-8 | C++ | false | false | 4,950 | h | /*
* Andy's Workshop Reflow Controller ATMega328p firmware
* Copyright (c) 2015 Andy Brown. http://www.andybrown.me.uk
* Please see website for licensing terms.
*/
#pragma once
namespace awreflow {
/*
* Handler for the reflowing state
*/
class ReflowingHandler {
protected:
enum class ActionTaken : uint8_t {
NOTHING,
UPDATED,
STOP
};
ActionButton& _actionButton;
OvenControl& _oven;
ReflowProfile _profile;
Pid _pid;
int16_t _desiredTemperature;
int16_t _temperatureStep;
uint16_t _currentTime;
uint16_t _currentRegion;
uint32_t _lastTick;
bool paused;
UiReflowingDisplay _display;
protected:
ActionTaken reflow();
void calcTemperatureStep();
public:
ReflowingHandler(TemperatureSensor& temperatureSensor,ActionButton& actionButton,OvenControl& oven);
~ReflowingHandler();
ProgramState loop();
};
/*
* Constructor
*/
inline ReflowingHandler::ReflowingHandler(TemperatureSensor& temperatureSensor,ActionButton& actionButton,OvenControl& oven)
: _actionButton(actionButton),
_oven(oven),
_display(temperatureSensor) {
uint16_t p,i,d;
// set up the PID class
p=Eeprom::Reader::Reader::constant(Eeprom::Location::PROPORTIONAL);
i=Eeprom::Reader::Reader::constant(Eeprom::Location::INTEGER);
d=Eeprom::Reader::Reader::constant(Eeprom::Location::DERIVATIVE);
_pid.setup(p,i,d);
// get the appropriate profile
if(static_cast<ReflowProfileName>(Eeprom::Reader::readByte(Eeprom::Location::PROFILE))==ReflowProfileName::LEADED)
_profile=ReflowProfile::leaded();
else
_profile=ReflowProfile::leadFree();
_desiredTemperature=25; // all profiles start at 25
_currentTime=0;
_currentRegion=0;
_lastTick=MillisecondTimer::millis();
calcTemperatureStep();
}
/*
* Destructor
*/
inline ReflowingHandler::~ReflowingHandler() {
// turn off the oven
_oven.setDutyCycle(0,false);
}
/*
* Main Loop
*/
inline ProgramState ReflowingHandler::loop() {
do {
// main loops
_display.loop();
_actionButton.loop();
} while(reflow()!=ActionTaken::STOP && !_actionButton.isPressed());
// back to the start
return ProgramState::REMOTING;
}
/*
* Program logic for the reflow. Return true if we updated during this call or false
* if it was too soon (we update once per second).
*/
inline ReflowingHandler::ActionTaken ReflowingHandler::reflow() {
uint8_t dutyCycle;
// get the current sensor state
const TemperatureSensor::Response& lastTemperature(_display.getTemperatureSensor().getLastTemperature());
// do nothing if we're back before a second has elapsed or we're too early and the first
// temperature reading as not yet been taken
if(!MillisecondTimer::hasTimedOut(_lastTick,1000) || lastTemperature.status==TemperatureSensor::Status::UNKNOWN)
return ActionTaken::NOTHING;
// if there's been a hardware failure in the temperature sensor then bail out
if(lastTemperature.status!=TemperatureSensor::Status::OK)
return ActionTaken::STOP;
// reset for the next update (now, not after we've burned some cycles doing our update)
_lastTick=MillisecondTimer::millis();
// if we're in the first second and we are below the starting temperature then auto-pause
// until we've heated up to the starting temperature (25 degrees)
if(_currentTime || lastTemperature.celsius>=_desiredTemperature) {
// get the current region out of PROGMEM
ReflowRegion region=_profile.getRegion(_currentRegion);
// update seconds and see if we've hit the end
if(region.endingTime==_currentTime) {
// we have hit the ending time of the current region. if this is the last region
// then the whole process has completed
_currentRegion++;
if(_currentRegion==_profile.regionCount)
return ActionTaken::STOP;
// we're in a new region. set up the parameters for this leg.
calcTemperatureStep();
}
// update time and desired temperature
_currentTime++;
_desiredTemperature+=_temperatureStep;
}
// run the PID algorithm and set the relay PWM value from the output
dutyCycle=_pid.loop(_desiredTemperature,lastTemperature.celsius);
_oven.setDutyCycle(dutyCycle,false);
// update the display
_display.setStatus(_currentTime,_desiredTemperature,dutyCycle);
// continue
return ActionTaken::UPDATED;
}
/*
* Calculate the temperature step value
*/
inline void ReflowingHandler::calcTemperatureStep() {
ReflowRegion region=_profile.getRegion(_currentRegion);
_temperatureStep=(region.endingTemperature-_desiredTemperature)/(region.endingTime-_currentTime);
}
}
| [
"andy@andybrown.me.uk"
] | andy@andybrown.me.uk |
ea722b027a178c31ef3d8a3c84a0467c29be10e9 | a9a7f08ebf49cf514f84f24492eea340e0efbb78 | /tests/auto/md/topologybuilder/topologybuildertest.h | 11b22c1f232c5709977f7de9715ba51ed7665e11 | [
"BSD-3-Clause"
] | permissive | soplwang/chemkit | d535e91ddd2cea733554eef647dd488049dc0429 | 8d8e150160d44a4c770e343a22dee9e462b10694 | refs/heads/master | 2021-01-15T22:56:45.583833 | 2012-07-13T20:00:07 | 2012-07-13T20:00:07 | 3,108,867 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,093 | h | /******************************************************************************
**
** Copyright (C) 2009-2012 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the chemkit project 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
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#ifndef TOPOLOGYBUILDERTEST_H
#define TOPOLOGYBUILDERTEST_H
#include <QtTest>
class TopologyBuilderTest : public QObject
{
Q_OBJECT
private slots:
void phenol();
};
#endif // TOPOLOGYBUILDERTEST_H
| [
"kyle.r.lutz@gmail.com"
] | kyle.r.lutz@gmail.com |
c270b17e44001db987279226b5422228c7ba07e5 | e27f9d4c48355b5ea6d562aae35b7ca46ed3fc1c | /src/lib/DebugInfo/DWARF/DWARFDebugFrame.cpp | 7d772901e7f41f3b6975e59096594318c720e929 | [
"NCSA"
] | permissive | dongAxis/clang-700.0.72 | 67c4bb38b77e63da966e5dbd4e6ea7b6725b2484 | 513e64095d87e15954b41a22da367552a1c4dcc4 | refs/heads/master | 2021-01-10T12:17:26.230788 | 2016-02-04T04:29:53 | 2016-02-04T04:29:53 | 51,051,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,693 | cpp | //===-- DWARFDebugFrame.h - Parsing of .debug_frame -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
#include <vector>
using namespace llvm;
using namespace dwarf;
/// \brief Abstract frame entry defining the common interface concrete
/// entries implement.
class llvm::FrameEntry {
public:
enum FrameKind {FK_CIE, FK_FDE};
FrameEntry(FrameKind K, uint64_t Offset, uint64_t Length)
: Kind(K), Offset(Offset), Length(Length) {}
virtual ~FrameEntry() {
}
FrameKind getKind() const { return Kind; }
virtual uint64_t getOffset() const { return Offset; }
/// \brief Parse and store a sequence of CFI instructions from Data,
/// starting at *Offset and ending at EndOffset. If everything
/// goes well, *Offset should be equal to EndOffset when this method
/// returns. Otherwise, an error occurred.
virtual void parseInstructions(DataExtractor Data, uint32_t *Offset,
uint32_t EndOffset);
/// \brief Dump the entry header to the given output stream.
virtual void dumpHeader(raw_ostream &OS) const = 0;
/// \brief Dump the entry's instructions to the given output stream.
virtual void dumpInstructions(raw_ostream &OS) const;
protected:
const FrameKind Kind;
/// \brief Offset of this entry in the section.
uint64_t Offset;
/// \brief Entry length as specified in DWARF.
uint64_t Length;
/// An entry may contain CFI instructions. An instruction consists of an
/// opcode and an optional sequence of operands.
typedef std::vector<uint64_t> Operands;
struct Instruction {
Instruction(uint8_t Opcode)
: Opcode(Opcode)
{}
uint8_t Opcode;
Operands Ops;
};
std::vector<Instruction> Instructions;
/// Convenience methods to add a new instruction with the given opcode and
/// operands to the Instructions vector.
void addInstruction(uint8_t Opcode) {
Instructions.push_back(Instruction(Opcode));
}
void addInstruction(uint8_t Opcode, uint64_t Operand1) {
Instructions.push_back(Instruction(Opcode));
Instructions.back().Ops.push_back(Operand1);
}
void addInstruction(uint8_t Opcode, uint64_t Operand1, uint64_t Operand2) {
Instructions.push_back(Instruction(Opcode));
Instructions.back().Ops.push_back(Operand1);
Instructions.back().Ops.push_back(Operand2);
}
};
// See DWARF standard v3, section 7.23
const uint8_t DWARF_CFI_PRIMARY_OPCODE_MASK = 0xc0;
const uint8_t DWARF_CFI_PRIMARY_OPERAND_MASK = 0x3f;
void FrameEntry::parseInstructions(DataExtractor Data, uint32_t *Offset,
uint32_t EndOffset) {
while (*Offset < EndOffset) {
uint8_t Opcode = Data.getU8(Offset);
// Some instructions have a primary opcode encoded in the top bits.
uint8_t Primary = Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK;
if (Primary) {
// If it's a primary opcode, the first operand is encoded in the bottom
// bits of the opcode itself.
uint64_t Op1 = Opcode & DWARF_CFI_PRIMARY_OPERAND_MASK;
switch (Primary) {
default: llvm_unreachable("Impossible primary CFI opcode");
case DW_CFA_advance_loc:
case DW_CFA_restore:
addInstruction(Primary, Op1);
break;
case DW_CFA_offset:
addInstruction(Primary, Op1, Data.getULEB128(Offset));
break;
}
} else {
// Extended opcode - its value is Opcode itself.
switch (Opcode) {
default: llvm_unreachable("Invalid extended CFI opcode");
case DW_CFA_nop:
case DW_CFA_remember_state:
case DW_CFA_restore_state:
case DW_CFA_GNU_window_save:
// No operands
addInstruction(Opcode);
break;
case DW_CFA_set_loc:
// Operands: Address
addInstruction(Opcode, Data.getAddress(Offset));
break;
case DW_CFA_advance_loc1:
// Operands: 1-byte delta
addInstruction(Opcode, Data.getU8(Offset));
break;
case DW_CFA_advance_loc2:
// Operands: 2-byte delta
addInstruction(Opcode, Data.getU16(Offset));
break;
case DW_CFA_advance_loc4:
// Operands: 4-byte delta
addInstruction(Opcode, Data.getU32(Offset));
break;
case DW_CFA_restore_extended:
case DW_CFA_undefined:
case DW_CFA_same_value:
case DW_CFA_def_cfa_register:
case DW_CFA_def_cfa_offset:
// Operands: ULEB128
addInstruction(Opcode, Data.getULEB128(Offset));
break;
case DW_CFA_def_cfa_offset_sf:
// Operands: SLEB128
addInstruction(Opcode, Data.getSLEB128(Offset));
break;
case DW_CFA_offset_extended:
case DW_CFA_register:
case DW_CFA_def_cfa:
case DW_CFA_val_offset:
// Operands: ULEB128, ULEB128
addInstruction(Opcode, Data.getULEB128(Offset),
Data.getULEB128(Offset));
break;
case DW_CFA_offset_extended_sf:
case DW_CFA_def_cfa_sf:
case DW_CFA_val_offset_sf:
// Operands: ULEB128, SLEB128
addInstruction(Opcode, Data.getULEB128(Offset),
Data.getSLEB128(Offset));
break;
case DW_CFA_def_cfa_expression:
case DW_CFA_expression:
case DW_CFA_val_expression:
// TODO: implement this
report_fatal_error("Values with expressions not implemented yet!");
}
}
}
}
namespace {
/// \brief DWARF Common Information Entry (CIE)
class CIE : public FrameEntry {
public:
// CIEs (and FDEs) are simply container classes, so the only sensible way to
// create them is by providing the full parsed contents in the constructor.
CIE(uint64_t Offset, uint64_t Length, uint8_t Version,
SmallString<8> Augmentation, uint64_t CodeAlignmentFactor,
int64_t DataAlignmentFactor, uint64_t ReturnAddressRegister)
: FrameEntry(FK_CIE, Offset, Length), Version(Version),
Augmentation(std::move(Augmentation)),
CodeAlignmentFactor(CodeAlignmentFactor),
DataAlignmentFactor(DataAlignmentFactor),
ReturnAddressRegister(ReturnAddressRegister) {}
~CIE() {
}
uint64_t getCodeAlignmentFactor() const { return CodeAlignmentFactor; }
int64_t getDataAlignmentFactor() const { return DataAlignmentFactor; }
void dumpHeader(raw_ostream &OS) const override {
OS << format("%08x %08x %08x CIE",
(uint32_t)Offset, (uint32_t)Length, DW_CIE_ID)
<< "\n";
OS << format(" Version: %d\n", Version);
OS << " Augmentation: \"" << Augmentation << "\"\n";
OS << format(" Code alignment factor: %u\n",
(uint32_t)CodeAlignmentFactor);
OS << format(" Data alignment factor: %d\n",
(int32_t)DataAlignmentFactor);
OS << format(" Return address column: %d\n",
(int32_t)ReturnAddressRegister);
OS << "\n";
}
static bool classof(const FrameEntry *FE) {
return FE->getKind() == FK_CIE;
}
private:
/// The following fields are defined in section 6.4.1 of the DWARF standard v3
uint8_t Version;
SmallString<8> Augmentation;
uint64_t CodeAlignmentFactor;
int64_t DataAlignmentFactor;
uint64_t ReturnAddressRegister;
};
/// \brief DWARF Frame Description Entry (FDE)
class FDE : public FrameEntry {
public:
// Each FDE has a CIE it's "linked to". Our FDE contains is constructed with
// an offset to the CIE (provided by parsing the FDE header). The CIE itself
// is obtained lazily once it's actually required.
FDE(uint64_t Offset, uint64_t Length, int64_t LinkedCIEOffset,
uint64_t InitialLocation, uint64_t AddressRange,
CIE *Cie)
: FrameEntry(FK_FDE, Offset, Length), LinkedCIEOffset(LinkedCIEOffset),
InitialLocation(InitialLocation), AddressRange(AddressRange),
LinkedCIE(Cie) {}
~FDE() {
}
CIE *getLinkedCIE() const { return LinkedCIE; }
void dumpHeader(raw_ostream &OS) const override {
OS << format("%08x %08x %08x FDE ",
(uint32_t)Offset, (uint32_t)Length, (int32_t)LinkedCIEOffset);
OS << format("cie=%08x pc=%08x...%08x\n",
(int32_t)LinkedCIEOffset,
(uint32_t)InitialLocation,
(uint32_t)InitialLocation + (uint32_t)AddressRange);
}
static bool classof(const FrameEntry *FE) {
return FE->getKind() == FK_FDE;
}
private:
/// The following fields are defined in section 6.4.1 of the DWARF standard v3
uint64_t LinkedCIEOffset;
uint64_t InitialLocation;
uint64_t AddressRange;
CIE *LinkedCIE;
};
/// \brief Types of operands to CF instructions.
enum OperandType {
OT_Unset,
OT_None,
OT_Address,
OT_Offset,
OT_FactoredCodeOffset,
OT_SignedFactDataOffset,
OT_UnsignedFactDataOffset,
OT_Register,
OT_Expression
};
} // end anonymous namespace
/// \brief Initialize the array describing the types of operands.
static ArrayRef<OperandType[2]> getOperandTypes() {
static OperandType OpTypes[DW_CFA_restore+1][2];
#define DECLARE_OP2(OP, OPTYPE0, OPTYPE1) \
do { \
OpTypes[OP][0] = OPTYPE0; \
OpTypes[OP][1] = OPTYPE1; \
} while (0)
#define DECLARE_OP1(OP, OPTYPE0) DECLARE_OP2(OP, OPTYPE0, OT_None)
#define DECLARE_OP0(OP) DECLARE_OP1(OP, OT_None)
DECLARE_OP1(DW_CFA_set_loc, OT_Address);
DECLARE_OP1(DW_CFA_advance_loc, OT_FactoredCodeOffset);
DECLARE_OP1(DW_CFA_advance_loc1, OT_FactoredCodeOffset);
DECLARE_OP1(DW_CFA_advance_loc2, OT_FactoredCodeOffset);
DECLARE_OP1(DW_CFA_advance_loc4, OT_FactoredCodeOffset);
DECLARE_OP1(DW_CFA_MIPS_advance_loc8, OT_FactoredCodeOffset);
DECLARE_OP2(DW_CFA_def_cfa, OT_Register, OT_Offset);
DECLARE_OP2(DW_CFA_def_cfa_sf, OT_Register, OT_SignedFactDataOffset);
DECLARE_OP1(DW_CFA_def_cfa_register, OT_Register);
DECLARE_OP1(DW_CFA_def_cfa_offset, OT_Offset);
DECLARE_OP1(DW_CFA_def_cfa_offset_sf, OT_SignedFactDataOffset);
DECLARE_OP1(DW_CFA_def_cfa_expression, OT_Expression);
DECLARE_OP1(DW_CFA_undefined, OT_Register);
DECLARE_OP1(DW_CFA_same_value, OT_Register);
DECLARE_OP2(DW_CFA_offset, OT_Register, OT_UnsignedFactDataOffset);
DECLARE_OP2(DW_CFA_offset_extended, OT_Register, OT_UnsignedFactDataOffset);
DECLARE_OP2(DW_CFA_offset_extended_sf, OT_Register, OT_SignedFactDataOffset);
DECLARE_OP2(DW_CFA_val_offset, OT_Register, OT_UnsignedFactDataOffset);
DECLARE_OP2(DW_CFA_val_offset_sf, OT_Register, OT_SignedFactDataOffset);
DECLARE_OP2(DW_CFA_register, OT_Register, OT_Register);
DECLARE_OP2(DW_CFA_expression, OT_Register, OT_Expression);
DECLARE_OP2(DW_CFA_val_expression, OT_Register, OT_Expression);
DECLARE_OP1(DW_CFA_restore, OT_Register);
DECLARE_OP1(DW_CFA_restore_extended, OT_Register);
DECLARE_OP0(DW_CFA_remember_state);
DECLARE_OP0(DW_CFA_restore_state);
DECLARE_OP0(DW_CFA_GNU_window_save);
DECLARE_OP1(DW_CFA_GNU_args_size, OT_Offset);
DECLARE_OP0(DW_CFA_nop);
#undef DECLARE_OP0
#undef DECLARE_OP1
#undef DECLARE_OP2
return ArrayRef<OperandType[2]>(&OpTypes[0], DW_CFA_restore+1);
}
static ArrayRef<OperandType[2]> OpTypes = getOperandTypes();
/// \brief Print \p Opcode's operand number \p OperandIdx which has
/// value \p Operand.
static void printOperand(raw_ostream &OS, uint8_t Opcode, unsigned OperandIdx,
uint64_t Operand, uint64_t CodeAlignmentFactor,
int64_t DataAlignmentFactor) {
assert(OperandIdx < 2);
OperandType Type = OpTypes[Opcode][OperandIdx];
switch (Type) {
case OT_Unset:
OS << " Unsupported " << (OperandIdx ? "second" : "first") << " operand to";
if (const char *OpcodeName = CallFrameString(Opcode))
OS << " " << OpcodeName;
else
OS << format(" Opcode %x", Opcode);
break;
case OT_None:
break;
case OT_Address:
OS << format(" %" PRIx64, Operand);
break;
case OT_Offset:
// The offsets are all encoded in a unsigned form, but in practice
// consumers use them signed. It's most certainly legacy due to
// the lack of signed variants in the first Dwarf standards.
OS << format(" %+" PRId64, int64_t(Operand));
break;
case OT_FactoredCodeOffset: // Always Unsigned
if (CodeAlignmentFactor)
OS << format(" %" PRId64, Operand * CodeAlignmentFactor);
else
OS << format(" %" PRId64 "*code_alignment_factor" , Operand);
break;
case OT_SignedFactDataOffset:
if (DataAlignmentFactor)
OS << format(" %" PRId64, int64_t(Operand) * DataAlignmentFactor);
else
OS << format(" %" PRId64 "*data_alignment_factor" , int64_t(Operand));
break;
case OT_UnsignedFactDataOffset:
if (DataAlignmentFactor)
OS << format(" %" PRId64, Operand * DataAlignmentFactor);
else
OS << format(" %" PRId64 "*data_alignment_factor" , Operand);
break;
case OT_Register:
OS << format(" reg%" PRId64, Operand);
break;
case OT_Expression:
OS << " expression";
break;
}
}
void FrameEntry::dumpInstructions(raw_ostream &OS) const {
uint64_t CodeAlignmentFactor = 0;
int64_t DataAlignmentFactor = 0;
const CIE *Cie = dyn_cast<CIE>(this);
if (!Cie)
Cie = cast<FDE>(this)->getLinkedCIE();
if (Cie) {
CodeAlignmentFactor = Cie->getCodeAlignmentFactor();
DataAlignmentFactor = Cie->getDataAlignmentFactor();
}
for (const auto &Instr : Instructions) {
uint8_t Opcode = Instr.Opcode;
if (Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK)
Opcode &= DWARF_CFI_PRIMARY_OPCODE_MASK;
OS << " " << CallFrameString(Opcode) << ":";
for (unsigned i = 0; i < Instr.Ops.size(); ++i)
printOperand(OS, Opcode, i, Instr.Ops[i], CodeAlignmentFactor,
DataAlignmentFactor);
OS << '\n';
}
}
DWARFDebugFrame::DWARFDebugFrame() {
}
DWARFDebugFrame::~DWARFDebugFrame() {
}
static void LLVM_ATTRIBUTE_UNUSED dumpDataAux(DataExtractor Data,
uint32_t Offset, int Length) {
errs() << "DUMP: ";
for (int i = 0; i < Length; ++i) {
uint8_t c = Data.getU8(&Offset);
errs().write_hex(c); errs() << " ";
}
errs() << "\n";
}
void DWARFDebugFrame::parse(DataExtractor Data) {
uint32_t Offset = 0;
DenseMap<uint32_t, CIE *> CIEs;
while (Data.isValidOffset(Offset)) {
uint32_t StartOffset = Offset;
bool IsDWARF64 = false;
uint64_t Length = Data.getU32(&Offset);
uint64_t Id;
if (Length == UINT32_MAX) {
// DWARF-64 is distinguished by the first 32 bits of the initial length
// field being 0xffffffff. Then, the next 64 bits are the actual entry
// length.
IsDWARF64 = true;
Length = Data.getU64(&Offset);
}
// At this point, Offset points to the next field after Length.
// Length is the structure size excluding itself. Compute an offset one
// past the end of the structure (needed to know how many instructions to
// read).
// TODO: For honest DWARF64 support, DataExtractor will have to treat
// offset_ptr as uint64_t*
uint32_t EndStructureOffset = Offset + static_cast<uint32_t>(Length);
// The Id field's size depends on the DWARF format
Id = Data.getUnsigned(&Offset, IsDWARF64 ? 8 : 4);
bool IsCIE = ((IsDWARF64 && Id == DW64_CIE_ID) || Id == DW_CIE_ID);
if (IsCIE) {
// Note: this is specifically DWARFv3 CIE header structure. It was
// changed in DWARFv4. We currently don't support reading DWARFv4
// here because LLVM itself does not emit it (and LLDB doesn't
// support it either).
uint8_t Version = Data.getU8(&Offset);
const char *Augmentation = Data.getCStr(&Offset);
uint64_t CodeAlignmentFactor = Data.getULEB128(&Offset);
int64_t DataAlignmentFactor = Data.getSLEB128(&Offset);
uint64_t ReturnAddressRegister = Data.getULEB128(&Offset);
auto Cie = make_unique<CIE>(StartOffset, Length, Version,
StringRef(Augmentation), CodeAlignmentFactor,
DataAlignmentFactor, ReturnAddressRegister);
CIEs[StartOffset] = Cie.get();
Entries.emplace_back(std::move(Cie));
} else {
// FDE
uint64_t CIEPointer = Id;
uint64_t InitialLocation = Data.getAddress(&Offset);
uint64_t AddressRange = Data.getAddress(&Offset);
Entries.emplace_back(new FDE(StartOffset, Length, CIEPointer,
InitialLocation, AddressRange,
CIEs[CIEPointer]));
}
Entries.back()->parseInstructions(Data, &Offset, EndStructureOffset);
if (Offset != EndStructureOffset) {
std::string Str;
raw_string_ostream OS(Str);
OS << format("Parsing entry instructions at %lx failed", StartOffset);
report_fatal_error(Str);
}
}
}
void DWARFDebugFrame::dump(raw_ostream &OS) const {
OS << "\n";
for (const auto &Entry : Entries) {
Entry->dumpHeader(OS);
Entry->dumpInstructions(OS);
OS << "\n";
}
}
| [
"amo260@gmail.com"
] | amo260@gmail.com |
f4f1551168dcd821b42785879854c3ebdba98ba6 | f693dd89335702ee88a7748506cc91b7973408ba | /cpp/ebisu/utils/streamers/set.hpp | 04c22e417fef6b0617ac361fd7393a4da303ac6c | [] | no_license | patefacio/cpp_ebisu | 7aecaeb6be870e3bc05ba6efab99f126ee991652 | 6b54fe1e9e169301d69c8bedab7baac76e18e5fc | refs/heads/master | 2021-01-22T00:13:09.736723 | 2017-10-04T19:28:43 | 2017-10-04T19:28:43 | 24,698,632 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 657 | hpp | #ifndef __EBISU_UTILS_STREAMERS_SET_HPP__
#define __EBISU_UTILS_STREAMERS_SET_HPP__
#include "ebisu/utils/streamers/streamers.hpp"
#include <iosfwd>
#include <set>
namespace ebisu {
namespace utils {
namespace streamers {
// custom <FcbBeginNamespace set>
//! Support for streaming std::list
template <typename T, typename PR, typename ALLOC>
inline std::ostream& operator<<(std::ostream& out,
std::set<T, PR, ALLOC> const& l) {
return print_scalar_collection(out, l);
}
// end <FcbBeginNamespace set>
} // namespace streamers
} // namespace utils
} // namespace ebisu
#endif // __EBISU_UTILS_STREAMERS_SET_HPP__
| [
"dbdavidson@yahoo.com"
] | dbdavidson@yahoo.com |
6abf6227d890fad8a0906312eb37109426622ba4 | c465968827df5b1b716f3ba2e3c3628985b8f125 | /src/Cubpack++/Code/E2interf.cpp | e163886808fe1474d7a2e55698f73b2c34359ca2 | [] | no_license | F-Feng/ResearchCode | 17a5733574c7169b08f671892ea02522b818bd66 | f0fa4d949c500d1c3e8d76a0102116f216b7b244 | refs/heads/master | 2021-06-11T03:29:30.082341 | 2015-09-04T14:58:57 | 2015-09-04T14:58:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,475 | cpp | /////////////////////////////////////////////////////////
// //
// Cubpack++ //
// //
// A Package For Automatic Cubature //
// //
// Authors : Ronald Cools //
// Dirk Laurie //
// Luc Pluym //
// //
/////////////////////////////////////////////////////////
///////////
//File E2interf.c
// History:
// (date) (version)
// 19 Aug 1994 V0.1 (first limited distribution)
// 25 Jun 1996 V0.2 (detect degenerate regions)
// 1 Aug 1996 V1.0 (paper accepted by ACM TOMS)
////////////////
#include "E2interf.h"
#include "E2adapt.h"
///////////////////////
PLANE::PLANE()
{
StoreAtomic(new Plane,new PlaneAdaptive);
}
//////////////////////////////////////////////
PLANE::PLANE(const Point& Center)
{
StoreAtomic(new Plane(Center),new PlaneAdaptive);
}
//////////////////////////////////////////////
PLANE::PLANE(const Point& Center, real ScaleX, real ScaleY)
{
Error((ScaleX <= 0)||(ScaleY <= 0),"A PLANE has zero or negative Scale.");
StoreAtomic(new Plane(Center,ScaleX, ScaleY),new PlaneAdaptive);
}
///////////////////////////////////////////////
| [
"Kyle@melissa7.wei.com"
] | Kyle@melissa7.wei.com |
c4d969f43ed693d96d7f3f6a4063241d6d88f7da | 90c95fd7a5687b1095bf499892b8c9ba40f59533 | /sprout/math/not_equal_to.hpp | 7a75c183127cad2dbd0a3f1f4c73b056ecd05dff | [
"BSL-1.0"
] | permissive | CreativeLabs0X3CF/Sprout | af60a938fd12e8439a831d4d538c4c48011ca54f | f08464943fbe2ac2030060e6ff20e4bb9782cd8e | refs/heads/master | 2021-01-20T17:03:24.630813 | 2016-08-15T04:44:46 | 2016-08-15T04:44:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | hpp | /*=============================================================================
Copyright (c) 2011-2016 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_MATH_NOT_EQUAL_TO_HPP
#define SPROUT_MATH_NOT_EQUAL_TO_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/math/equal_to.hpp>
#include <sprout/type_traits/enabler_if.hpp>
namespace sprout {
namespace math {
//
// not_equal_to
//
template<
typename T, typename U,
typename sprout::enabler_if<std::is_arithmetic<T>::value && std::is_arithmetic<U>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR bool
not_equal_to(T x, U y) {
return !sprout::math::equal_to(x, y);
}
} // namespace math
} // namespace sprout
#endif // #ifndef SPROUT_MATH_NOT_EQUAL_TO_HPP
| [
"bolero.murakami@gmail.com"
] | bolero.murakami@gmail.com |
e21dcb13b199e44988e7247e78db463b205cc524 | f5884f3ab6d4c57e658a49a0ccf4e24aaf45ff06 | /mds3d_td3/src/viewer.h | 88b2b3262413b0936fda4a7e71d677dfce2426a0 | [] | no_license | Komroh/Monde3D | 894fa2a846b91f1ca2516913dd419d54c07062b5 | fd139c4c548ef55efcbe96618e4a8d67785cab3c | refs/heads/master | 2021-11-30T09:13:39.536731 | 2019-03-21T11:25:25 | 2019-03-21T11:25:25 | 170,553,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | h | #ifndef VIEWER_H
#define VIEWER_H
#include "opengl.h"
#include "shader.h"
#include "camera.h"
#include "trackball.h"
#include "mesh.h"
#include <iostream>
class Viewer{
public:
//! Constructor
Viewer();
virtual ~Viewer();
// gl stuff
void init(int w, int h);
void drawScene2D();
void drawScene();
void updateAndDrawScene();
void reshape(int w, int h);
void loadShaders();
// events
void mousePressed(GLFWwindow* window, int button, int action);
void mouseMoved(int x, int y);
void mouseScroll(double x, double y);
void keyPressed(int key, int action, int mods);
void charPressed(int key);
private:
int _winWidth, _winHeight;
Camera _cam;
Shader _shader;
Mesh _mesh;
float _value;
float _theta;
Eigen::Vector2f _translat;
// Mouse parameters for the trackball
enum TrackMode
{
TM_NO_TRACK=0, TM_ROTATE_AROUND, TM_ZOOM,
TM_LOCAL_ROTATE, TM_FLY_Z, TM_FLY_PAN
};
TrackMode _trackingMode = TM_NO_TRACK;
Trackball _trackball;
Eigen::Vector2i _lastMousePos;
};
#endif
| [
"maxime.pacaud@etu.u-bordeaux.fr"
] | maxime.pacaud@etu.u-bordeaux.fr |
f8eb820e525bdabae85caa9edb1c37fe5c54f97f | 9fb6548b22463f0f5afd42e9b9186e0785c1b28e | /src/error/BianFuErrorListener.h | ad39d0c7c0db087c72ec9d7a7e5157bbd0c0dc68 | [] | no_license | lingfeishengtian/BianFu | 39e4d27ee0b7d5bee5bfb3d543353b03a464af9c | b629f489567585299571607ee1af27a26ad7c3d0 | refs/heads/master | 2022-06-13T15:02:08.460508 | 2020-05-04T20:12:17 | 2020-05-04T20:12:17 | 221,089,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | h | //
// Created by Hunter Han on 2020-04-28.
//
#include "antlr4-runtime.h"
#ifndef BIANFU_BIANFUERRORLISTENER_H
#define BIANFU_BIANFUERRORLISTENER_H
class BianFuErrorListener : public antlr4::BaseErrorListener{
public:
~BianFuErrorListener() override;
void
syntaxError(antlr4::Recognizer *recognizer, antlr4::Token *offendingSymbol, size_t line, size_t charPositionInLine,
const std::string &msg, std::exception_ptr e) override;
void reportAmbiguity(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa, size_t startIndex, size_t stopIndex,
bool exact, const antlrcpp::BitSet &ambigAlts, antlr4::atn::ATNConfigSet *configs) override;
void reportAttemptingFullContext(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa, size_t startIndex,
size_t stopIndex, const antlrcpp::BitSet &conflictingAlts,
antlr4::atn::ATNConfigSet *configs) override;
void reportContextSensitivity(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa, size_t startIndex,
size_t stopIndex, size_t prediction, antlr4::atn::ATNConfigSet *configs) override;
};
#endif //BIANFU_BIANFUERRORLISTENER_H
| [
"hunter.han@gmail.com"
] | hunter.han@gmail.com |
6ce40a61b9934fbfc4041b41b7b5f2ece1f308d0 | 370086b6bbe0120b2158c3c96216e3f3e7fccea9 | /1-semester/1 HomeTask/1-7/1-7.cpp | 6f38961539e45c85a33ff70f2fb207b5819147cb | [] | no_license | kbatoev/SpbSU-Homeworks | 67c2e33aa4b1b9e66f878d20a15c7220bb10fe33 | c4df40b86a326bbf726e7fdf6d4cf5a18fda252b | refs/heads/master | 2020-04-15T17:27:56.142568 | 2017-05-25T14:51:40 | 2017-05-25T14:51:40 | 30,765,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | cpp | #include <stdio.h>
int main() {
const int first = 2;
const int maxSize = 10000;
bool array[maxSize];
for (int i = 0; i < maxSize; i++)
array[i] = true;
int number = 0;
printf("Enter number, that is more than 2 :\n");
scanf("%d", &number);
for (int i = first; i <= number; i++)
if (array[i])
for (int j = 2 * i; j <= number; j += i)
array[j] = false;
printf("All prime numbers from 2 to entered number are:\n");
for (int i = first; i <= number; i++)
if (array[i])
printf("%d ", i);
printf("\n");
return 0;
} | [
"kbatoev@mail.ru"
] | kbatoev@mail.ru |
6788bd59c3d185ed6a885843aaa7cb4d35488af0 | cf31cf192c3ebba2b180fd0d5385c6ca0a76acf3 | /LogMaker/FunctionTracer/call_cust.cpp | d9bb67489635527a24a128b400fe0e65ec2fb473 | [
"MIT"
] | permissive | pranjalsingh008/secREtary | fe0a66249589b7344096f49d68b954ac23750dc1 | c590085c1883a45103b7d8d075b3af75a54ef6fc | refs/heads/master | 2023-03-23T21:53:15.720718 | 2021-03-18T05:12:35 | 2021-03-18T05:12:35 | 255,242,523 | 0 | 0 | MIT | 2020-04-13T05:49:35 | 2020-04-13T05:49:34 | null | UTF-8 | C++ | false | false | 7,573 | cpp |
#include "pin.H"
#include <iostream>
#include <fstream>
/* ===================================================================== */
/* Global Variables */
/* ===================================================================== */
std::ofstream TraceFile;
std::vector<string> calls_list;
std::map<std::string, int> countMap;
/* ===================================================================== */
/* Commandline Switches */
/* ===================================================================== */
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "calltrace.out", "specify trace file name");
KNOB<BOOL> KnobPrintArgs(KNOB_MODE_WRITEONCE, "pintool", "a", "0", "print call arguments ");
KNOB<BOOL> KnobAllCalls(KNOB_MODE_WRITEONCE, "pintool", "c", "0", "print all calls ");
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage()
{
cerr << "This tool produces a call trace." << endl << endl;
cerr << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
string invalid = "$";
/* ===================================================================== */
const string *Target2String(ADDRINT target)
{
string name = RTN_FindNameByAddress(target);
if (name == "")
return &invalid;
else
return new string(name);
}
/* ===================================================================== */
VOID do_call_args(const string *s, ADDRINT arg0)
{
TraceFile << *s << "(" << arg0 << ",...)" << endl;
}
/* ===================================================================== */
VOID do_call_args_indirect(ADDRINT target, BOOL taken, ADDRINT arg0)
{
if( !taken ) return;
const string *s = Target2String(target);
do_call_args(s, arg0);
if (s != &invalid)
delete s;
}
/* ===================================================================== */
VOID do_call(const string *s)
{
// Here we check for _Exit because that's the last call happening before the binary teminates.
if(*s != "_Exit")
calls_list.push_back(*s);
else if(*s == "_Exit"){
for(unsigned int i = 0; i < calls_list.size();i++)
{
string ser = calls_list[i];
//Switch cases for parsing the list we have
switch (ser[0])
{
case '.':
break;
case '_':
break;
case '$':
break;
case '(':
break;
case '#':
break;
case '@':
break;
default:
//cout << ser[0] << endl;
//TraceFile << ser << endl;
auto result = countMap.insert(std::pair<std::string, int>(ser, 1));
if (result.second == false)
result.first->second++;
break;
}
}
if ( std::find(calls_list.begin(), calls_list.end(), "ptrace@plt") != calls_list.end() )
{
cout << "================Analysis Complete================"<<endl;
cout << "PTRACE detected" <<endl;
cout << "======================Stats ====================="<<endl;
}
for (auto & elem : countMap){
// If frequency count is greater than 1 then its a duplicate element
if (elem.second >= 1){
std::cout << elem.first << " was called " << elem.second << " times."<< std::endl;
}
}
}
}
/* ===================================================================== */
VOID do_call_indirect(ADDRINT target, BOOL taken)
{
if( !taken ) return;
const string *s = Target2String(target);
do_call( s );
if (s != &invalid)
delete s;
}
/* ===================================================================== */
VOID Trace(TRACE trace, VOID *v)
{
const BOOL print_args = KnobPrintArgs.Value();
for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl))
{
INS tail = BBL_InsTail(bbl);
if( INS_IsCall(tail) )
{
if( INS_IsDirectBranchOrCall(tail) )
{
const ADDRINT target = INS_DirectBranchOrCallTargetAddress(tail);
if( print_args )
{
INS_InsertPredicatedCall(tail, IPOINT_BEFORE, AFUNPTR(do_call_args),
IARG_PTR, Target2String(target), IARG_FUNCARG_CALLSITE_VALUE, 0, IARG_END);
}
else
{
INS_InsertPredicatedCall(tail, IPOINT_BEFORE, AFUNPTR(do_call),
IARG_PTR, Target2String(target), IARG_END);
}
}
else
{
if( print_args )
{
INS_InsertCall(tail, IPOINT_BEFORE, AFUNPTR(do_call_args_indirect),
IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_FUNCARG_CALLSITE_VALUE, 0, IARG_END);
}
else
{
INS_InsertCall(tail, IPOINT_BEFORE, AFUNPTR(do_call_indirect),
IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_END);
}
}
}
else
{
// sometimes code is not in an image
RTN rtn = TRACE_Rtn(trace);
// also track stup jumps into share libraries
if( RTN_Valid(rtn) && !INS_IsDirectBranchOrCall(tail) && ".plt" == SEC_Name( RTN_Sec( rtn ) ))
{
if( print_args )
{
INS_InsertCall(tail, IPOINT_BEFORE, AFUNPTR(do_call_args_indirect),
IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_FUNCARG_CALLSITE_VALUE, 0, IARG_END);
}
else
{
INS_InsertCall(tail, IPOINT_BEFORE, AFUNPTR(do_call_indirect),
IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_END);
}
}
}
}
}
/* ===================================================================== */
VOID Fini(INT32 code, VOID *v)
{
TraceFile << "# eof" << endl;
TraceFile.close();
}
/* ===================================================================== */
/* Main */
/* ===================================================================== */
int main(int argc, char *argv[])
{
PIN_InitSymbols();
if( PIN_Init(argc,argv) )
{
return Usage();
}
TraceFile.open(KnobOutputFile.Value().c_str());
TraceFile << hex;
TraceFile.setf(ios::showbase);
string trace_header = string("#\n"
"# Call Trace Generated By Pin\n"
"#\n");
TraceFile.write(trace_header.c_str(),trace_header.size());
TRACE_AddInstrumentFunction(Trace, 0);
PIN_AddFiniFunction(Fini, 0);
// Never returns
PIN_StartProgram();
return 0;
}
/* ===================================================================== */
/* eof */
/* ===================================================================== */
| [
"kssuraj15@gmail.com"
] | kssuraj15@gmail.com |
9006a4faa45ebc490ef330fc34675fb7ad654667 | 9919439e5f02eb2d219929a10d43ab72a603c299 | /helpers.h | 7f15596d3f7ab6f036b0dc6376c9777f6cabd12a | [] | no_license | maneyko/leetcode | 9b23dd0774ce1276c9b8cd45b8a5dbd1f13473f0 | 51696526120306917e751403d0bd575819d0bab7 | refs/heads/master | 2020-05-25T01:11:36.142689 | 2019-06-03T02:31:53 | 2019-06-03T02:31:53 | 187,548,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | h | #ifndef HELPERS_H
#define HELPERS_H
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
void print_ivec(vector<int>& vec) {
cout << "[";
for (int i = 0; i < vec.size(); i++) {
cout << vec[i];
if (i < vec.size()-1)
cout << ", ";
else
cout << "]" << endl;
}
}
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* create_SLL(vector<int>& vec) {
ListNode *head = new ListNode(vec[0]);
ListNode *l_iter = head;
for (int i = 1; i < vec.size(); i++) {
l_iter->next = new ListNode(vec[i]);
l_iter = l_iter->next;
}
return head;
}
void print_SLL(ListNode* l1) {
ListNode *l1_iter = l1;
cout << "(";
while (l1_iter) {
cout << l1_iter->val;
if (l1_iter->next)
cout << " -> ";
else
cout << ")" << endl;
l1_iter = l1_iter->next;
}
}
#endif
| [
"pmaneyko@gmail.com"
] | pmaneyko@gmail.com |
85c56c178f93eef6a252193f31f930f52782225c | 42f60ea81e9dd9f85c592254c53e46fffe4f3df4 | /10_days_of_stats/Day7/Spearman's Rank Correlation Coefficient/solution.cpp | 1681812d45ea7a261c91d7ba09ad73d53baa7326 | [] | no_license | KARTHEEKCIC/Hackerrank_solutions | a009a66b5724521688f0c9d016cc2182c37caaf2 | f907264f2e6aca41c18e7b38ebaed6ba467f01e7 | refs/heads/master | 2022-07-07T22:03:17.578971 | 2022-06-25T14:53:05 | 2022-06-25T14:53:05 | 140,273,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp | #include <iostream>
#include <cmath>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
struct Data {
double X, Y;
int rX, rY;
};
bool X_comp(Data d1, Data d2) {
return d1.X<d2.X;
}
bool Y_comp(Data d1, Data d2) {
return d1.Y<d2.Y;
}
int main() {
int n;
cin>>n;
Data d[n];
for(int i=0 ; i<n ; i++) {
cin>>d[i].X;
d[i].rX=0;
}
for(int i=0 ; i<n ; i++) {
cin>>d[i].Y;
d[i].rY=0;
}
sort(d,d+n,X_comp);
for(int i=0 ; i<n ; i++) {
d[i].rX = i+1;
}
sort(d,d+n,Y_comp);
for(int i=0 ; i<n ; i++) {
d[i].rY = i+1;
}
double sp_rank=0;
for(int i=0 ; i<n ; i++) {
sp_rank+=pow(d[i].rX-d[i].rY,2);
}
sp_rank = 1-(6*sp_rank/((n)*(pow(n,2)-1)));
cout<<fixed<<setprecision(3)<<sp_rank<<endl;
return 0;
}
| [
"bkartheekreddy@gmail.com"
] | bkartheekreddy@gmail.com |
b745c6a66ee0580393dc83807fa99027e361e7f5 | 99f1550e0a3c2e21088e2ffc72bc5dadabb1188f | /ui/UISDK/Src/Base/Message/imessage.cpp | d478cabd00058be048e24ccc4528b3b0c6158ebd | [] | no_license | flymolon/UI2017 | 0d0bb1c173e015e7fe26ada47358b4581f3b0e29 | e7182b19d9227abe6d3f91600e85d13c85917e71 | refs/heads/master | 2020-04-11T01:42:49.336393 | 2017-02-12T04:15:19 | 2017-02-12T04:15:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,320 | cpp | #include "stdafx.h"
#include "message.h"
namespace UI
{
IMessage::IMessage(E_BOOL_CREATE_IMPL b)
{
if (b)
m_pImpl = new Message(this);
else
m_pImpl = NULL;
}
IMessage::~IMessage()
{
SAFE_DELETE(m_pImpl);
}
Message* IMessage::GetImpl()
{
return m_pImpl;
}
BOOL IMessage::ProcessMessage(UIMSG* pMsg, int nMsgMapID, bool bDoHook)
{
UI::UIMSG* pOldMsg = NULL;
if (m_pImpl)
pOldMsg = m_pImpl->GetCurMsg();
BOOL bRet = virtualProcessMessage(pMsg, nMsgMapID, bDoHook);
if (m_pImpl)
m_pImpl->SetCurMsg(pOldMsg);
return bRet;
}
void IMessage::Release()
{
this->virtual_delete_this();
}
BOOL IMessage::IsMsgHandled()const
{
return m_pImpl->IsMsgHandled();
}
void IMessage::SetMsgHandled(BOOL b)
{
m_pImpl->SetMsgHandled(b);
}
UIMSG* IMessage::GetCurMsg()
{
return m_pImpl->GetCurMsg();
}
void IMessage::SetCurMsg(UIMSG* p)
{
m_pImpl->SetCurMsg(p);
}
BOOL IMessage::DoHook(UIMSG* pMsg, int nMsgMapID)
{
return m_pImpl->DoHook(pMsg, nMsgMapID);
}
BOOL IMessage::virtualProcessMessage(UIMSG* pMsg, int nMsgMapID, bool bDoHook)
{
return FALSE;
}
void IMessage::virtual_delete_this()
{
delete this;
}
// BOOL IMessage::DoHook(UIMSG* pMsg, int nMsgMapID)
// {
// return m_pImpl->DoHook(pMsg, nMsgMapID);
// }
void IMessage::ClearNotify()
{
return m_pImpl->ClearNotify();
}
void IMessage::SetNotify(IMessage* pObj, int nMsgMapID)
{
return m_pImpl->SetNotify(pObj, nMsgMapID);
}
void IMessage::CopyNotifyTo(IMessage* pObjCopyTo)
{
if (NULL == pObjCopyTo)
return;
return m_pImpl->CopyNotifyTo(pObjCopyTo);
}
long IMessage::DoNotify(UIMSG* pMsg)
{
return m_pImpl->DoNotify(pMsg);
}
IMessage* IMessage::GetNotifyObj()
{
return m_pImpl->GetNotifyObj();
}
void IMessage::AddHook(IMessage* pObj, int nMsgMapIDToHook, int nMsgMapIDToNotify )
{
if (NULL == pObj)
return;
return m_pImpl->AddHook(pObj/*->GetMessageImpl()*/, nMsgMapIDToHook, nMsgMapIDToNotify);
}
void IMessage::RemoveHook(IMessage* pObj, int nMsgMapIDToHook, int nMsgMapIDToNotify )
{
if (NULL == pObj)
return;
return m_pImpl->RemoveHook(pObj/*->GetMessageImpl()*/, nMsgMapIDToHook, nMsgMapIDToNotify);
}
void IMessage::RemoveHook(IMessage* pObj)
{
if (!pObj)
return;
return m_pImpl->RemoveHook(pObj/*->GetMessageImpl()*/);
}
void IMessage::ClearHook()
{
return m_pImpl->ClearHook();
}
void IMessage::AddDelayRef(void** pp)
{
if (!m_pImpl)
{
m_pImpl = new Message(this);
}
return m_pImpl->AddDelayRef(pp);
}
void IMessage::RemoveDelayRef(void** pp)
{
if (m_pImpl)
m_pImpl->RemoveDelayRef(pp);
}
void* IMessage::QueryInterface(REFIID iid)
{
return (void*)UISendMessage(this, UI_MSG_QUERYINTERFACE, (WPARAM)&iid);
}
MessageProxy::MessageProxy(IMessage* p)
: m_pImpl(p->GetImpl())
{
}
MessageProxy::~MessageProxy()
{
}
BOOL MessageProxy::IsMsgHandled()const
{
return m_pImpl->IsMsgHandled();
}
void MessageProxy::SetMsgHandled(BOOL b)
{
return m_pImpl->SetMsgHandled(b);
}
UIMSG* MessageProxy::GetCurMsg()
{
return m_pImpl->GetCurMsg();
}
void MessageProxy::SetCurMsg(UIMSG* p)
{
m_pImpl->SetCurMsg(p);
}
BOOL MessageProxy::DoHook(UIMSG* pMsg, int nMsgMapID)
{
return m_pImpl->DoHook(pMsg, nMsgMapID);
}
} | [
"libo30@lenovo.com"
] | libo30@lenovo.com |
a0bb92267d8a62cd4c0a0eca9de6d91e9cd43719 | 1341ebf56cee66f15431236c74e8bb1db02558ac | /components/password_manager/core/browser/password_save_manager.h | 02a3297c9176609d21befb95b6b28377b29953a0 | [
"BSD-3-Clause"
] | permissive | nerdooit/chromium | 41584349b52e0b941ec45ebb5ba5695268e5872f | de77d445d3428ef72455c3b0d9be7e050d447135 | refs/heads/master | 2023-01-11T20:03:40.846099 | 2020-01-25T12:45:08 | 2020-01-25T12:45:08 | 236,195,538 | 1 | 0 | BSD-3-Clause | 2020-01-25T16:25:12 | 2020-01-25T16:25:11 | null | UTF-8 | C++ | false | false | 3,643 | h | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_SAVE_MANAGER_H_
#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_SAVE_MANAGER_H_
#include "base/macros.h"
#include "components/password_manager/core/browser/password_store.h"
namespace autofill {
struct FormData;
struct PasswordForm;
} // namespace autofill
namespace password_manager {
class PasswordManagerClient;
class FormFetcher;
class VotesUploader;
class FormSaver;
class PasswordFormMetricsRecorder;
class PasswordManagerDriver;
// Implementations of this interface should encapsulate the password Save/Update
// logic. One implementation of this class will provide the Save/Update logic in
// case of multiple password stores. This ensures that the PasswordFormManager
// stays agnostic to whether one password store or multiple password stores are
// active. While FormSaver abstracts the implementation of different
// operations (e.g. Save()), PasswordSaveManager is responsible for deciding
// what and where to Save().
class PasswordSaveManager {
public:
PasswordSaveManager() = default;
virtual ~PasswordSaveManager() = default;
virtual void Init(PasswordManagerClient* client,
const FormFetcher* form_fetcher,
scoped_refptr<PasswordFormMetricsRecorder> metrics_recorder,
VotesUploader* votes_uploader) = 0;
virtual const autofill::PasswordForm* GetPendingCredentials() const = 0;
virtual const base::string16& GetGeneratedPassword() const = 0;
virtual FormSaver* GetFormSaver() const = 0;
// Create pending credentials from |parsed_submitted_form| and
// |parsed_observed_form| and |submitted_form|.
virtual void CreatePendingCredentials(
const autofill::PasswordForm& parsed_submitted_form,
const autofill::FormData& observed_form,
const autofill::FormData& submitted_form,
bool is_http_auth,
bool is_credential_api_save) = 0;
virtual void Save(const autofill::FormData& observed_form,
const autofill::PasswordForm& parsed_submitted_form) = 0;
virtual void Update(const autofill::PasswordForm& credentials_to_update,
const autofill::FormData& observed_form,
const autofill::PasswordForm& parsed_submitted_form) = 0;
virtual void PermanentlyBlacklist(
const PasswordStore::FormDigest& form_digest) = 0;
virtual void Unblacklist(const PasswordStore::FormDigest& form_digest) = 0;
// Called when generated password is accepted or changed by user.
virtual void PresaveGeneratedPassword(autofill::PasswordForm parsed_form) = 0;
// Called when user wants to start generation flow for |generated|.
virtual void GeneratedPasswordAccepted(
autofill::PasswordForm parsed_form,
base::WeakPtr<PasswordManagerDriver> driver) = 0;
// Signals that the user cancels password generation.
virtual void PasswordNoLongerGenerated() = 0;
// Moves the pending credentials together with any other PSL matched ones from
// the profile store to the account store.
virtual void MoveCredentialsToAccountStore() = 0;
virtual bool IsNewLogin() const = 0;
virtual bool IsPasswordUpdate() const = 0;
virtual bool HasGeneratedPassword() const = 0;
virtual std::unique_ptr<PasswordSaveManager> Clone() = 0;
private:
DISALLOW_COPY_AND_ASSIGN(PasswordSaveManager);
};
} // namespace password_manager
#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_SAVE_MANAGER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
6f60eb5f14e640a636e1a23e01411d850273dfaf | e27f9d4c48355b5ea6d562aae35b7ca46ed3fc1c | /src/tools/clang/tools/extra/modularize/ModuleAssistant.cpp | 3d2b99414b8ff29c81fbf72ccb9ce4557402cd4b | [
"NCSA"
] | permissive | dongAxis/clang-700.0.72 | 67c4bb38b77e63da966e5dbd4e6ea7b6725b2484 | 513e64095d87e15954b41a22da367552a1c4dcc4 | refs/heads/master | 2021-01-10T12:17:26.230788 | 2016-02-04T04:29:53 | 2016-02-04T04:29:53 | 51,051,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,733 | cpp | //===--- ModuleAssistant.cpp - Module map generation manager -*- C++ -*---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//
//
// This file defines the module generation entry point function,
// createModuleMap, a Module class for representing a module,
// and various implementation functions for doing the underlying
// work, described below.
//
// The "Module" class represents a module, with members for storing the module
// name, associated header file names, and sub-modules, and an "output"
// function that recursively writes the module definitions.
//
// The "createModuleMap" function implements the top-level logic of the
// assistant mode. It calls a loadModuleDescriptions function to walk
// the header list passed to it and creates a tree of Module objects
// representing the module hierarchy, represented by a "Module" object,
// the "RootModule". This root module may or may not represent an actual
// module in the module map, depending on the "--root-module" option passed
// to modularize. It then calls a writeModuleMap function to set up the
// module map file output and walk the module tree, outputting the module
// map file using a stream obtained and managed by an
// llvm::tool_output_file object.
//
//===---------------------------------------------------------------------===//
#include "Modularize.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ToolOutputFile.h"
#include <vector>
// Local definitions:
namespace {
// Internal class definitions:
// Represents a module.
class Module {
public:
Module(llvm::StringRef Name);
Module();
~Module();
bool output(llvm::raw_fd_ostream &OS, int Indent);
Module *findSubModule(llvm::StringRef SubName);
public:
std::string Name;
std::vector<std::string> HeaderFileNames;
std::vector<Module *> SubModules;
};
} // end anonymous namespace.
// Module functions:
// Constructors.
Module::Module(llvm::StringRef Name) : Name(Name) {}
Module::Module() {}
// Destructor.
Module::~Module() {
// Free submodules.
while (!SubModules.empty()) {
Module *last = SubModules.back();
SubModules.pop_back();
delete last;
}
}
// Write a module hierarchy to the given output stream.
bool Module::output(llvm::raw_fd_ostream &OS, int Indent) {
// If this is not the nameless root module, start a module definition.
if (Name.size() != 0) {
OS.indent(Indent);
OS << "module " << Name << " {\n";
Indent += 2;
}
// Output submodules.
for (std::vector<Module *>::iterator I = SubModules.begin(),
E = SubModules.end();
I != E; ++I) {
if (!(*I)->output(OS, Indent))
return false;
}
// Output header files.
for (std::vector<std::string>::iterator I = HeaderFileNames.begin(),
E = HeaderFileNames.end();
I != E; ++I) {
OS.indent(Indent);
OS << "header \"" << *I << "\"\n";
}
// If this module has header files, output export directive.
if (HeaderFileNames.size() != 0) {
OS.indent(Indent);
OS << "export *\n";
}
// If this is not the nameless root module, close the module definition.
if (Name.size() != 0) {
Indent -= 2;
OS.indent(Indent);
OS << "}\n";
}
return true;
}
// Lookup a sub-module.
Module *Module::findSubModule(llvm::StringRef SubName) {
for (std::vector<Module *>::iterator I = SubModules.begin(),
E = SubModules.end();
I != E; ++I) {
if ((*I)->Name == SubName)
return *I;
}
return nullptr;
}
// Implementation functions:
// Reserved keywords in module.map syntax.
// Keep in sync with keywords in module map parser in Lex/ModuleMap.cpp,
// such as in ModuleMapParser::consumeToken().
static const char *ReservedNames[] = {
"config_macros", "export", "module", "conflict", "framework",
"requires", "exclude", "header", "private", "explicit",
"link", "umbrella", "extern", "use", nullptr // Flag end.
};
// Convert module name to a non-keyword.
// Prepends a '_' to the name if and only if the name is a keyword.
static std::string
ensureNoCollisionWithReservedName(llvm::StringRef MightBeReservedName) {
std::string SafeName = MightBeReservedName;
for (int Index = 0; ReservedNames[Index] != nullptr; ++Index) {
if (MightBeReservedName == ReservedNames[Index]) {
SafeName.insert(0, "_");
break;
}
}
return SafeName;
}
// Add one module, given a header file path.
static bool addModuleDescription(Module *RootModule,
llvm::StringRef HeaderFilePath,
llvm::StringRef HeaderPrefix,
DependencyMap &Dependencies) {
Module *CurrentModule = RootModule;
DependentsVector &FileDependents = Dependencies[HeaderFilePath];
std::string FilePath;
// Strip prefix.
// HeaderFilePath should be compared to natively-canonicalized Prefix.
llvm::SmallString<256> NativePath, NativePrefix;
llvm::sys::path::native(HeaderFilePath, NativePath);
llvm::sys::path::native(HeaderPrefix, NativePrefix);
if (NativePath.startswith(NativePrefix))
FilePath = NativePath.substr(NativePrefix.size() + 1);
else
FilePath = HeaderFilePath;
int Count = FileDependents.size();
// Headers that go into modules must not depend on other files being
// included first. If there are any dependents, warn user and omit.
if (Count != 0) {
llvm::errs() << "warning: " << FilePath
<< " depends on other headers being included first,"
" meaning the module.map won't compile."
" This header will be omitted from the module map.\n";
return true;
}
// Make canonical.
std::replace(FilePath.begin(), FilePath.end(), '\\', '/');
// Insert module into tree, using subdirectories as submodules.
for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(FilePath),
E = llvm::sys::path::end(FilePath);
I != E; ++I) {
if ((*I)[0] == '.')
continue;
std::string Stem = llvm::sys::path::stem(*I);
Stem = ensureNoCollisionWithReservedName(Stem);
Module *SubModule = CurrentModule->findSubModule(Stem);
if (!SubModule) {
SubModule = new Module(Stem);
CurrentModule->SubModules.push_back(SubModule);
}
CurrentModule = SubModule;
}
// Add header file name to headers.
CurrentModule->HeaderFileNames.push_back(FilePath);
return true;
}
// Create the internal module tree representation.
static Module *loadModuleDescriptions(
llvm::StringRef RootModuleName, llvm::ArrayRef<std::string> HeaderFileNames,
DependencyMap &Dependencies, llvm::StringRef HeaderPrefix) {
// Create root module.
Module *RootModule = new Module(RootModuleName);
llvm::SmallString<256> CurrentDirectory;
llvm::sys::fs::current_path(CurrentDirectory);
// If no header prefix, use current directory.
if (HeaderPrefix.size() == 0)
HeaderPrefix = CurrentDirectory;
// Walk the header file names and output the module map.
for (llvm::ArrayRef<std::string>::iterator I = HeaderFileNames.begin(),
E = HeaderFileNames.end();
I != E; ++I) {
// Add as a module.
if (!addModuleDescription(RootModule, *I, HeaderPrefix, Dependencies))
return nullptr;
}
return RootModule;
}
// Kick off the writing of the module map.
static bool writeModuleMap(llvm::StringRef ModuleMapPath,
llvm::StringRef HeaderPrefix, Module *RootModule) {
llvm::SmallString<256> HeaderDirectory(ModuleMapPath);
llvm::sys::path::remove_filename(HeaderDirectory);
llvm::SmallString<256> FilePath;
// Get the module map file path to be used.
if ((HeaderDirectory.size() == 0) && (HeaderPrefix.size() != 0)) {
FilePath = HeaderPrefix;
// Prepend header file name prefix if it's not absolute.
llvm::sys::path::append(FilePath, ModuleMapPath);
llvm::sys::path::native(FilePath);
} else {
FilePath = ModuleMapPath;
llvm::sys::path::native(FilePath);
}
// Set up module map output file.
std::error_code EC;
llvm::tool_output_file Out(FilePath, EC, llvm::sys::fs::F_Text);
if (EC) {
llvm::errs() << Argv0 << ": error opening " << FilePath << ":"
<< EC.message() << "\n";
return false;
}
// Get output stream from tool output buffer/manager.
llvm::raw_fd_ostream &OS = Out.os();
// Output file comment.
OS << "// " << ModuleMapPath << "\n";
OS << "// Generated by: " << CommandLine << "\n\n";
// Write module hierarchy from internal representation.
if (!RootModule->output(OS, 0))
return false;
// Tell tool_output_file that we want to keep the file.
Out.keep();
return true;
}
// Global functions:
// Module map generation entry point.
bool createModuleMap(llvm::StringRef ModuleMapPath,
llvm::ArrayRef<std::string> HeaderFileNames,
DependencyMap &Dependencies, llvm::StringRef HeaderPrefix,
llvm::StringRef RootModuleName) {
// Load internal representation of modules.
std::unique_ptr<Module> RootModule(loadModuleDescriptions(
RootModuleName, HeaderFileNames, Dependencies, HeaderPrefix));
if (!RootModule.get())
return false;
// Write module map file.
return writeModuleMap(ModuleMapPath, HeaderPrefix, RootModule.get());
}
| [
"amo260@gmail.com"
] | amo260@gmail.com |
ef649af7a31c50e84d352f211aabf5ab487d9c19 | 48298469e7d828ab1aa54a419701c23afeeadce1 | /Login/Packets/WLRetCharLoginHandler.cpp | 38cdeb007e169de80892ec0870e07d9cb0eb3989 | [] | no_license | brock7/TianLong | c39fccb3fd2aa0ad42c9c4183d67a843ab2ce9c2 | 8142f9ccb118e76a5cd0a8b168bcf25e58e0be8b | refs/heads/master | 2021-01-10T14:19:19.850859 | 2016-02-20T13:58:55 | 2016-02-20T13:58:55 | 52,155,393 | 5 | 3 | null | null | null | null | GB18030 | C++ | false | false | 7,620 | cpp | #include "stdafx.h"
#include "WLRetCharLogin.h"
#include "ProcessManager.h"
#include "ProcessPlayerManager.h"
#include "ServerManager.h"
#include "LoginPlayer.h"
#include "LCRetCharLogin.h"
#include "PlayerPool.h"
#include "TimeManager.h"
#include "DBLogicManager.h"
#include "DBCharFullData.h"
#include "DB_Struct.h"
#include "LWAskCharLogin.h"
#include "PacketFactoryManager.h"
#include "Log.h"
#include "DBThreadManager.h"
UINT WLRetCharLoginHandler::Execute(WLRetCharLogin* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
TID CurrentThreadID = MyGetCurrentThreadID();
if(CurrentThreadID == g_pServerManager->m_ThreadID)
{
g_pProcessManager->SendPacket(pPacket,pPacket->GetPlayerID());
return PACKET_EXE_NOTREMOVE;
}
else if(CurrentThreadID == g_pProcessPlayerManager->m_ThreadID)
{
PlayerID_t PlayerID = pPacket->GetPlayerID();
LoginPlayer* pLoginPlayer = g_pPlayerPool->GetPlayer(PlayerID);
Assert(pLoginPlayer);
if(strcmp(pLoginPlayer->GetAccount(),pPacket->GetAccount())!= 0)
{
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....acc error,acc=%s,packacc=%s",
pPacket->GetAccount(),pPacket->GetAccount());
return PACKET_EXE_CONTINUE;
}
if(pPacket->GetHoldStatus() == TRUE) //用户在线
{
LCRetCharLogin Msg;
Msg.SetResult(pPacket->GetResult());
if(pPacket->GetResult() == ASKCHARLOGIN_SERVER_STOP)
{
pLoginPlayer->SendPacket(&Msg);
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....User is Online ,Server is CrashDown\
Account = %s,GUID = %d",pPacket->GetAccount(),pPacket->GetPlayerGUID());
return PACKET_EXE_CONTINUE;
}
if(pPacket->GetResult() == ASKCHARLOGIN_SUCCESS)
{
//计算角色所在服务器信息
ID_t ServerID = pPacket->GetPlayerServerID();
INT index = g_Config.m_ServerInfo.m_HashServer[ServerID] ;
_SERVER_DATA* pServerData = &(g_Config.m_ServerInfo.m_pServer[index]);
Assert(pServerData);
Msg.SetServerIP(pServerData->m_IP0);
Msg.SetServerPort(pServerData->m_Port0);
//取得用户登陆Key值
Msg.SetUserKey(pLoginPlayer->GetUserKey());
pLoginPlayer->SendPacket(&Msg);
pLoginPlayer->SetPlayerStatus(PS_LOGIN_SERVER_READY);
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()...Online ,Acc=%s,GUID=%X,IP=%s,Port=%d,SID=%d",
pPacket->GetAccount(),pPacket->GetPlayerGUID(),
pServerData->m_IP0,pServerData->m_Port0,
ServerID);
return PACKET_EXE_CONTINUE;
}
}
else //用户不在线 ,需要Load 数据
{
//对数据库操作频繁度判断
UINT uTime = g_pTimeManager->CurrentTime();
if(uTime<pLoginPlayer->m_LastDBOpTime+DB_OPERATION_TIME)
{
//用户操作过于频繁
LCRetCharLogin Msg;
Msg.SetResult(ASKCHARLOGIN_OP_TIMES);
pLoginPlayer->SendPacket(&Msg);
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....User Need Load From DB Account = %s,GUID = %X",pPacket->GetAccount(),pPacket->GetPlayerGUID());
return PACKET_EXE_CONTINUE;
}
//
if(pPacket->GetResult() == ASKCHARLIST_WORLD_FULL
|| pPacket->GetResult() == ASKCHARLOGIN_SERVER_STOP)
{
LCRetCharLogin Msg;
Msg.SetResult(pPacket->GetResult());
pLoginPlayer->SendPacket(&Msg);
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....User Can't Login Account = %s,GUID = %X ,Result = %d",pPacket->GetAccount(),pPacket->GetPlayerGUID(),pPacket->GetResult());
return PACKET_EXE_CONTINUE;
}
if (pPacket->GetResult() == ASKCHARLOGIN_LOADDB_ERROR)
{
if(g_pDBThreadManager->SendPacket(pPacket,pLoginPlayer->PlayerID()))
{//加入成功,将消息发送到DB处理
pLoginPlayer->m_LastDBOpTime = uTime;
return PACKET_EXE_NOTREMOVE;
}
else
{
//DB 压力过大,让用户重新尝试
LCRetCharLogin Msg;
Msg.SetResult(ASKCHARLOGIN_SERVER_BUSY);
pLoginPlayer->SendPacket(&Msg);
pLoginPlayer->m_LastDBOpTime = uTime;
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....Server Busy Account = %s,GUID = %X",pPacket->GetAccount(),pPacket->GetPlayerGUID());
return PACKET_EXE_CONTINUE;
}
}
}
}
else if(g_pDBThreadManager->IsPoolTID(CurrentThreadID))
{
PlayerID_t PlayerID = pPacket->GetPlayerID();
GUID_t PlayerCharGUID = pPacket->GetPlayerGUID();
LoginPlayer* pLoginPlayer = static_cast<LoginPlayer*>(pPlayer);
Assert(pLoginPlayer);
if(pLoginPlayer->GetDBOperating() == TRUE||!g_pDBThreadManager->GetInterface(CurrentThreadID)->IsConnected())
{
LCRetCharLogin* pRetCharLoginMsg =
(LCRetCharLogin*)g_pPacketFactoryManager->CreatePacket(PACKET_LC_RETCHARLOGIN);
if(!pRetCharLoginMsg)
{
AssertEx(FALSE,"创建 LCRetCharLogin 消息失败");
}
pRetCharLoginMsg->SetResult(ASKCHARLOGIN_SERVER_BUSY);
g_pProcessManager->SendPacket(pRetCharLoginMsg,PlayerID);
Log::SaveLog( LOGIN_LOGFILE, "WLRetCharLoginHandler::Execute()....数据库操作冲突!") ;
return PACKET_EXE_CONTINUE;
}
pLoginPlayer->SetDBOperating(TRUE);
ODBCInterface* pInterface = g_pDBThreadManager->GetInterface(CurrentThreadID);
Assert(pInterface);
DBCharFullData CharFullDataObject(pInterface);
CharFullDataObject.SetCharGuid(PlayerCharGUID);
BOOL bRetLoad = CharFullDataObject.Load();
INT ResultCount = CharFullDataObject.GetResultCount();
if(!bRetLoad)
{
Log::SaveLog(LOGIN_LOGFILE,"CharFullDataObject.Load()....Get Errors: %s",CharFullDataObject.GetErrorMessage());
LCRetCharLogin* pRetCharLoginMsg =
(LCRetCharLogin*)g_pPacketFactoryManager->CreatePacket(PACKET_LC_RETCHARLOGIN);
if(!pRetCharLoginMsg)
{
AssertEx(FALSE,"创建 LCRetCharLogin 消息失败");
}
pRetCharLoginMsg->SetResult(ASKCHARLOGIN_LOADDB_ERROR);
g_pProcessManager->SendPacket(pRetCharLoginMsg,PlayerID);
pLoginPlayer->SetDBOperating(FALSE);
return PACKET_EXE_NOTREMOVE;
}
if(ResultCount == 0)
{
Assert(FALSE);
LCRetCharLogin* pRetCharLoginMsg =
(LCRetCharLogin*)g_pPacketFactoryManager->CreatePacket(PACKET_LC_RETCHARLOGIN);
pRetCharLoginMsg->SetResult(ASKCHARLOGIN_LOADDB_ERROR);
g_pProcessManager->SendPacket(pRetCharLoginMsg,PlayerID);
pLoginPlayer->SetDBOperating(FALSE);
return PACKET_EXE_NOTREMOVE;
}
LWAskCharLogin* pMsg =
(LWAskCharLogin*)g_pPacketFactoryManager->CreatePacket(PACKET_LW_ASKCHARLOGIN);
if(!pMsg)
{
AssertEx(FALSE,"创建 LWAskCharLogin 消息失败");
}
UINT res1, res2, res3, res4;
INT nRet = CharFullDataObject.ParseResult(pMsg->GetUserData(),res1, res2, res3, res4);
if( nRet == 2 || nRet == 3 )
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....Get Errors:(Ret=%d) %d,%d,%d,%d", nRet, res1, res2, res3, res4);
pMsg->GetUserData()->m_Human.m_LastLoginTime = g_pTimeManager->CurrentDate();
pMsg->SetAskStatus(ALS_SENDDATA);
pMsg->SetAccount(pLoginPlayer->GetAccount());
pMsg->SetPlayerID(PlayerID);
pMsg->SetPlayerGUID(PlayerCharGUID);
pMsg->SetUserKey(pLoginPlayer->GetUserKey());
pMsg->SetUserAge(pLoginPlayer->GetPlayerAge());
g_pServerManager->SendPacket(pMsg,WORLD_PLAYER_ID);
pLoginPlayer->SetDBOperating(FALSE);
}
else
{
AssertEx(FALSE,"WLRetCharLoginHandler 线程资源执行错误!");
}
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....OK!");
return PACKET_EXE_CONTINUE;
__LEAVE_FUNCTION
return PACKET_EXE_ERROR;
} | [
"xiaowave@gmail.com"
] | xiaowave@gmail.com |
3a543800a7368b90afec7978766bee7892e4c891 | 9fa292d97ceb374068d355bd41097d0407d68bd3 | /src/rspf/plugin/rspfSharedObjectBridge.cpp | e3d04c041b114dfcb82dbe97f16b8f7c84a3a40e | [] | no_license | mfkiwl/rspf_v2.0 | 4d90153b92cc416663c798e05f87e348ad8792ef | f22d2707b775a4776fc8359a255f39c26ecc96a3 | refs/heads/master | 2021-05-27T04:36:34.132569 | 2013-07-16T04:04:12 | 2013-07-16T04:04:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63 | cpp | #include <rspf/plugin/rspfSharedObjectBridge.h>
extern "C"
{
}
| [
"loongfee@gmail.com"
] | loongfee@gmail.com |
fa169bd33732aebbd9cfc9205d54a94bf5002da8 | 80f2fa4f1f4d56eef9471174f80b62838db9fc3b | /xdl/ps-plus/ps-plus/common/test/hdfs_test.cc | b30068e9857eb0be01aaf4136048c9c9402148e5 | [
"Apache-2.0"
] | permissive | laozhuang727/x-deeplearning | a54f2fef1794274cbcd6fc55680ea19760d38f8a | 781545783a4e2bbbda48fc64318fb2c6d8bbb3cc | refs/heads/master | 2020-05-09T17:06:00.495080 | 2019-08-15T01:45:40 | 2019-08-15T01:45:40 | 181,295,053 | 1 | 0 | Apache-2.0 | 2019-08-15T01:45:41 | 2019-04-14T10:51:53 | PureBasic | UTF-8 | C++ | false | false | 1,479 | cc | #include "gtest/gtest.h"
#include "ps-plus/common/data_source.h"
#include "ps-plus/common/hdfs_data_source.h"
#include "test/util/hdfs_launcher.h"
using ps::Status;
using ps::DataClosure;
using ps::HdfsDataSource;
class MockHdfsDS : public HdfsDataSource {
public:
MockHdfsDS(const std::string &file_path, size_t file_num) : HdfsDataSource(file_path, file_num) {}
Status Call(const std::string &stream) {
return InitFromFile(stream);
}
};
class HdfsDataSourceTest : public testing::Test {
public:
static void SetUpTestCase() {}
static void TearDownTestCase() {}
};
TEST_F(HdfsDataSourceTest, HdfsDataSource) {
int hdfs_port = xdl::HDFSLauncher::Instance()->GetPort();
std::string hdfs_prefix = "hdfs://127.0.0.1:" + std::to_string(hdfs_port);
std::string dir = hdfs_prefix + "/test_data/data_io/";
{
std::unique_ptr<HdfsDataSource> hds(new HdfsDataSource(dir, 1));
ASSERT_NE(hds, nullptr);
Status st = hds->Init(1, 1, 100);
ASSERT_EQ(st, Status::Ok());
DataClosure dc;
st = hds->Get(1, &dc);
ASSERT_NE(st, Status::Ok());
std::vector<int64_t> ids;
ids.push_back(1);
ids.push_back(2);
std::vector<DataClosure> cs;
st = hds->BatchGet(ids, &cs);
ASSERT_EQ(cs.size(), 1);
std::vector<int64_t> rst;
hds->BatchGetV2(ids, &cs, &rst);
ASSERT_EQ(cs.size(), 0);
}
{
auto ds = new MockHdfsDS(dir, 1);
Status st = ds->Call(dir);
ASSERT_NE(st, Status::Ok());
delete ds;
}
}
| [
"yue.song@alibaba-inc.com"
] | yue.song@alibaba-inc.com |
aa579ede8adf9dfa06e8ca81f5a421ccbf12c2b9 | 5a5328c0ad39230779aa52c9ae57ec193b88941e | /tesseract4android/src/main/cpp/tesseract/src/src/textord/bbgrid.cpp | e186cc15a2d842d32368e5ad5079213c533b7de8 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | adaptech-cz/Tesseract4Android | 66978579ccc80587b8a0ae3eebe79f152fa382cd | 8ae584f54502d5457c8b9d62401eaa99551352c3 | refs/heads/master | 2023-07-21T16:49:39.617935 | 2023-07-18T12:13:29 | 2023-07-18T12:13:29 | 168,021,668 | 517 | 101 | Apache-2.0 | 2021-03-29T11:52:21 | 2019-01-28T19:21:34 | C | UTF-8 | C++ | false | false | 10,537 | cpp | ///////////////////////////////////////////////////////////////////////
// File: bbgrid.cpp
// Description: Class to hold BLOBNBOXs in a grid for fast access
// to neighbours.
// Author: Ray Smith
//
// (C) Copyright 2007, Google 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 "bbgrid.h"
#include "helpers.h"
#include "ocrblock.h"
namespace tesseract {
///////////////////////////////////////////////////////////////////////
// BBGrid IMPLEMENTATION.
///////////////////////////////////////////////////////////////////////
GridBase::GridBase(int gridsize, const ICOORD &bleft, const ICOORD &tright) {
Init(gridsize, bleft, tright);
}
// Destructor.
// It is defined here, so the compiler can create a single vtable
// instead of weak vtables in every compilation unit.
GridBase::~GridBase() = default;
// (Re)Initialize the grid. The gridsize is the size in pixels of each cell,
// and bleft, tright are the bounding box of everything to go in it.
void GridBase::Init(int gridsize, const ICOORD &bleft, const ICOORD &tright) {
gridsize_ = gridsize;
bleft_ = bleft;
tright_ = tright;
if (gridsize_ == 0) {
gridsize_ = 1;
}
gridwidth_ = (tright.x() - bleft.x() + gridsize_ - 1) / gridsize_;
gridheight_ = (tright.y() - bleft.y() + gridsize_ - 1) / gridsize_;
gridbuckets_ = gridwidth_ * gridheight_;
}
// Compute the given grid coordinates from image coords.
void GridBase::GridCoords(int x, int y, int *grid_x, int *grid_y) const {
*grid_x = (x - bleft_.x()) / gridsize_;
*grid_y = (y - bleft_.y()) / gridsize_;
ClipGridCoords(grid_x, grid_y);
}
// Clip the given grid coordinates to fit within the grid.
void GridBase::ClipGridCoords(int *x, int *y) const {
*x = ClipToRange(*x, 0, gridwidth_ - 1);
*y = ClipToRange(*y, 0, gridheight_ - 1);
}
IntGrid::IntGrid() {
grid_ = nullptr;
}
IntGrid::IntGrid(int gridsize, const ICOORD &bleft, const ICOORD &tright) : grid_(nullptr) {
Init(gridsize, bleft, tright);
}
IntGrid::~IntGrid() {
delete[] grid_;
}
// (Re)Initialize the grid. The gridsize is the size in pixels of each cell,
// and bleft, tright are the bounding box of everything to go in it.
void IntGrid::Init(int gridsize, const ICOORD &bleft, const ICOORD &tright) {
GridBase::Init(gridsize, bleft, tright);
delete[] grid_;
grid_ = new int[gridbuckets_];
Clear();
}
// Clear all the ints in the grid to zero.
void IntGrid::Clear() {
for (int i = 0; i < gridbuckets_; ++i) {
grid_[i] = 0;
}
}
// Rotate the grid by rotation, keeping cell contents.
// rotation must be a multiple of 90 degrees.
// NOTE: due to partial cells, cell coverage in the rotated grid will be
// inexact. This is why there is no Rotate for the generic BBGrid.
// TODO(rays) investigate fixing this inaccuracy by moving the origin after
// rotation.
void IntGrid::Rotate(const FCOORD &rotation) {
ASSERT_HOST(rotation.x() == 0.0f || rotation.y() == 0.0f);
ICOORD old_bleft(bleft());
// ICOORD old_tright(tright());
int old_width = gridwidth();
int old_height = gridheight();
TBOX box(bleft(), tright());
box.rotate(rotation);
int *old_grid = grid_;
grid_ = nullptr;
Init(gridsize(), box.botleft(), box.topright());
// Iterate over the old grid, copying data to the rotated position in the new.
int oldi = 0;
FCOORD x_step(rotation);
x_step *= gridsize();
for (int oldy = 0; oldy < old_height; ++oldy) {
FCOORD line_pos(old_bleft.x(), old_bleft.y() + gridsize() * oldy);
line_pos.rotate(rotation);
for (int oldx = 0; oldx < old_width; ++oldx, line_pos += x_step, ++oldi) {
int grid_x, grid_y;
GridCoords(static_cast<int>(line_pos.x() + 0.5), static_cast<int>(line_pos.y() + 0.5),
&grid_x, &grid_y);
grid_[grid_y * gridwidth() + grid_x] = old_grid[oldi];
}
}
delete[] old_grid;
}
// Returns a new IntGrid containing values equal to the sum of all the
// neighbouring cells. The returned grid must be deleted after use.
// For ease of implementation, edge cells are double counted, to make them
// have the same range as the non-edge cells.
IntGrid *IntGrid::NeighbourhoodSum() const {
auto *sumgrid = new IntGrid(gridsize(), bleft(), tright());
for (int y = 0; y < gridheight(); ++y) {
for (int x = 0; x < gridwidth(); ++x) {
int cell_count = 0;
for (int yoffset = -1; yoffset <= 1; ++yoffset) {
for (int xoffset = -1; xoffset <= 1; ++xoffset) {
int grid_x = x + xoffset;
int grid_y = y + yoffset;
ClipGridCoords(&grid_x, &grid_y);
cell_count += GridCellValue(grid_x, grid_y);
}
}
if (GridCellValue(x, y) > 1) {
sumgrid->SetGridCell(x, y, cell_count);
}
}
}
return sumgrid;
}
// Returns true if more than half the area of the rect is covered by grid
// cells that are over the threshold.
bool IntGrid::RectMostlyOverThreshold(const TBOX &rect, int threshold) const {
int min_x, min_y, max_x, max_y;
GridCoords(rect.left(), rect.bottom(), &min_x, &min_y);
GridCoords(rect.right(), rect.top(), &max_x, &max_y);
int total_area = 0;
for (int y = min_y; y <= max_y; ++y) {
for (int x = min_x; x <= max_x; ++x) {
int value = GridCellValue(x, y);
if (value > threshold) {
TBOX cell_box(x * gridsize_, y * gridsize_, (x + 1) * gridsize_, (y + 1) * gridsize_);
cell_box &= rect; // This is in-place box intersection.
total_area += cell_box.area();
}
}
}
return total_area * 2 > rect.area();
}
// Returns true if any cell value in the given rectangle is zero.
bool IntGrid::AnyZeroInRect(const TBOX &rect) const {
int min_x, min_y, max_x, max_y;
GridCoords(rect.left(), rect.bottom(), &min_x, &min_y);
GridCoords(rect.right(), rect.top(), &max_x, &max_y);
for (int y = min_y; y <= max_y; ++y) {
for (int x = min_x; x <= max_x; ++x) {
if (GridCellValue(x, y) == 0) {
return true;
}
}
}
return false;
}
// Returns a full-resolution binary pix in which each cell over the given
// threshold is filled as a black square. pixDestroy after use.
// Edge cells, which have a zero 4-neighbour, are not marked.
Image IntGrid::ThresholdToPix(int threshold) const {
Image pix = pixCreate(tright().x() - bleft().x(), tright().y() - bleft().y(), 1);
int cellsize = gridsize();
for (int y = 0; y < gridheight(); ++y) {
for (int x = 0; x < gridwidth(); ++x) {
if (GridCellValue(x, y) > threshold && GridCellValue(x - 1, y) > 0 &&
GridCellValue(x + 1, y) > 0 && GridCellValue(x, y - 1) > 0 &&
GridCellValue(x, y + 1) > 0) {
pixRasterop(pix, x * cellsize, tright().y() - ((y + 1) * cellsize), cellsize, cellsize,
PIX_SET, nullptr, 0, 0);
}
}
}
return pix;
}
// Make a Pix of the correct scaled size for the TraceOutline functions.
static Image GridReducedPix(const TBOX &box, int gridsize, ICOORD bleft, int *left, int *bottom) {
// Compute grid bounds of the outline and pad all round by 1.
int grid_left = (box.left() - bleft.x()) / gridsize - 1;
int grid_bottom = (box.bottom() - bleft.y()) / gridsize - 1;
int grid_right = (box.right() - bleft.x()) / gridsize + 1;
int grid_top = (box.top() - bleft.y()) / gridsize + 1;
*left = grid_left;
*bottom = grid_bottom;
return pixCreate(grid_right - grid_left + 1, grid_top - grid_bottom + 1, 1);
}
// Helper function to return a scaled Pix with one pixel per grid cell,
// set (black) where the given outline enters the corresponding grid cell,
// and clear where the outline does not touch the grid cell.
// Also returns the grid coords of the bottom-left of the Pix, in *left
// and *bottom, which corresponds to (0, 0) on the Pix.
// Note that the Pix is used upside-down, with (0, 0) being the bottom-left.
Image TraceOutlineOnReducedPix(C_OUTLINE *outline, int gridsize, ICOORD bleft, int *left,
int *bottom) {
const TBOX &box = outline->bounding_box();
Image pix = GridReducedPix(box, gridsize, bleft, left, bottom);
int wpl = pixGetWpl(pix);
l_uint32 *data = pixGetData(pix);
int length = outline->pathlength();
ICOORD pos = outline->start_pos();
for (int i = 0; i < length; ++i) {
int grid_x = (pos.x() - bleft.x()) / gridsize - *left;
int grid_y = (pos.y() - bleft.y()) / gridsize - *bottom;
SET_DATA_BIT(data + grid_y * wpl, grid_x);
pos += outline->step(i);
}
return pix;
}
#if 0 // Example code shows how to use TraceOutlineOnReducedPix.
C_OUTLINE_IT ol_it(blob->cblob()->out_list());
int grid_left, grid_bottom;
Pix* pix = TraceOutlineOnReducedPix(ol_it.data(), gridsize_, bleft_,
&grid_left, &grid_bottom);
grid->InsertPixPtBBox(grid_left, grid_bottom, pix, blob);
pix.destroy();
#endif
// As TraceOutlineOnReducedPix above, but on a BLOCK instead of a C_OUTLINE.
Image TraceBlockOnReducedPix(BLOCK *block, int gridsize, ICOORD bleft, int *left, int *bottom) {
const TBOX &box = block->pdblk.bounding_box();
Image pix = GridReducedPix(box, gridsize, bleft, left, bottom);
int wpl = pixGetWpl(pix);
l_uint32 *data = pixGetData(pix);
ICOORDELT_IT it(block->pdblk.poly_block()->points());
for (it.mark_cycle_pt(); !it.cycled_list();) {
ICOORD pos = *it.data();
it.forward();
ICOORD next_pos = *it.data();
ICOORD line_vector = next_pos - pos;
int major, minor;
ICOORD major_step, minor_step;
line_vector.setup_render(&major_step, &minor_step, &major, &minor);
int accumulator = major / 2;
while (pos != next_pos) {
int grid_x = (pos.x() - bleft.x()) / gridsize - *left;
int grid_y = (pos.y() - bleft.y()) / gridsize - *bottom;
SET_DATA_BIT(data + grid_y * wpl, grid_x);
pos += major_step;
accumulator += minor;
if (accumulator >= major) {
accumulator -= major;
pos += minor_step;
}
}
}
return pix;
}
} // namespace tesseract.
| [
"posel@adaptech.cz"
] | posel@adaptech.cz |
e777c48e5f243922c0bddf40b612eab02555a808 | 5bbb7a0aacf260e5c85b2411c877f68576035a58 | /Unit6/split_str6.cpp | cc22be01de6b56c36550211bb6daa896eac62e81 | [] | no_license | HeidiTran/accelerated-c-barbara-moo-andrew-koenig | 80ed03c62f99fe895c6b1da77584fc2e4dd8bb5c | 8205d590ac6b08c83b0cccc3e2ba50ddcf650025 | refs/heads/master | 2022-04-10T21:40:48.581780 | 2020-03-08T15:58:24 | 2020-03-08T15:58:24 | 160,249,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,788 | cpp | // This program break a line of input into words
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <algorithm>
#include <iterator>
#include <list>
using namespace std;
bool isSpace(const char& c)
{
return isspace(c);
}
bool not_space(const char& c)
{
return !isspace(c);
}
// Split and return a vector contain words
vector<string> split(const string& str)
{
typedef string::const_iterator iter;
vector<string> ret;
iter i = str.begin();
while (i != str.end())
{
i = find_if(i, str.end(), not_space);
iter j = find_if(i, str.end(), isSpace);
ret.push_back(string(i, j));
i = j;
}
return ret;
}
// Out: output iterator. We can use split with any kind of iterator (forward, bidirectional, random-access iterators)
// EXCEPT a pure Input iterator such as istream_iterator
template <class Out>
void split(const string& str, Out os)
{
typedef string::const_iterator iter;
iter i = str.begin();
while (i != str.end())
{
i = find_if(i, str.end(), not_space);
iter j = find_if(i, str.end(), isSpace);
if (i != str.end())
*os++ = string(i, j);
i = j;
}
}
int main() {
string s;
/*
// Write words into almost any kind of container + use different types of iterators
// This example append the words after split function to a list called word_list
list<string> word_list;
while (getline(cin, s))
{
split(s, back_inserter(word_list));
//split(s, front_inserter(word_list));
for (list<string>::iterator it = word_list.begin(); it != word_list.end(); it++)
cout << *it << endl;
}
*/
// Seperate the input line into separate words, and writes those words onto the standard output
while (getline(cin, s))
{
split(s, ostream_iterator<string>(cout, "\n"));
}
return 0;
} | [
"HeidiTran1410@gmail.com"
] | HeidiTran1410@gmail.com |
37196b6e131ba535a1c189d610ed0f17a2c2e504 | 75e6a8b381afd2d7cb597004a9a6496d439b3a2b | /lib/rc-switch/RCSwitch.h | 36a28407d368d9dbdce224948f8d376e6ad5abd2 | [
"MIT"
] | permissive | SmbatYeranyan/firmware-iot-home-control | 32564ba38b85a4cf79a8fc5c204ee1beaa3ec66d | eed8d214c9d5b55e372868925ce25603e024c42e | refs/heads/master | 2020-12-25T15:17:58.201103 | 2016-11-02T08:55:59 | 2016-11-02T08:55:59 | 64,009,256 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 4,938 | h | /*
RCSwitch - Arduino libary for remote control outlet switches
Copyright (c) 2011 Suat Özgür. All right reserved.
Contributors:
- Andre Koehler / info(at)tomate-online(dot)de
- Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com
- Skineffect / http://forum.ardumote.com/viewtopic.php?f=2&t=46
- Dominik Fischer / dom_fischer(at)web(dot)de
- Frank Oltmanns / <first name>.<last name>(at)gmail(dot)com
Project home: http://code.google.com/p/rc-switch/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _RCSwitch_h
#define _RCSwitch_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#elif defined(ENERGIA) // LaunchPad, FraunchPad and StellarPad specific
#include "Energia.h"
#else
#include "WProgram.h"
#endif
// At least for the ATTiny X4/X5, receiving has to be disabled due to
// missing libm depencies (udivmodhi4)
#if defined( __AVR_ATtinyX5__ ) or defined ( __AVR_ATtinyX4__ )
#define RCSwitchDisableReceiving
#endif
// Number of maximum High/Low changes per packet.
// We can handle up to (unsigned long) => 32 bit * 2 H/L changes per bit + 2 for sync
#define RCSWITCH_MAX_CHANGES 67
#define PROTOCOL3_SYNC_FACTOR 71
#define PROTOCOL3_0_HIGH_CYCLES 4
#define PROTOCOL3_0_LOW_CYCLES 11
#define PROTOCOL3_1_HIGH_CYCLES 9
#define PROTOCOL3_1_LOW_CYCLES 6
class RCSwitch {
public:
RCSwitch();
void switchOn(int nGroupNumber, int nSwitchNumber);
void switchOff(int nGroupNumber, int nSwitchNumber);
void switchOn(char* sGroup, int nSwitchNumber);
void switchOff(char* sGroup, int nSwitchNumber);
void switchOn(char sFamily, int nGroup, int nDevice);
void switchOff(char sFamily, int nGroup, int nDevice);
void switchOn(char* sGroup, char* sDevice);
void switchOff(char* sGroup, char* sDevice);
void switchOn(char sGroup, int nDevice);
void switchOff(char sGroup, int nDevice);
void sendTriState(char* Code);
void send(unsigned long Code, unsigned int length);
void send(char* Code);
#if not defined( RCSwitchDisableReceiving )
void enableReceive(int interrupt);
void enableReceive();
void disableReceive();
bool available();
void resetAvailable();
unsigned long getReceivedValue();
unsigned int getReceivedBitlength();
unsigned int getReceivedDelay();
unsigned int getReceivedProtocol();
unsigned int* getReceivedRawdata();
#endif
void enableTransmit(int nTransmitterPin);
void disableTransmit();
void setPulseLength(int nPulseLength);
void setRepeatTransmit(int nRepeatTransmit);
#if not defined( RCSwitchDisableReceiving )
void setReceiveTolerance(int nPercent);
#endif
void setProtocol(int nProtocol);
void setProtocol(int nProtocol, int nPulseLength);
private:
char* getCodeWordB(int nGroupNumber, int nSwitchNumber, boolean bStatus);
char* getCodeWordA(char* sGroup, int nSwitchNumber, boolean bStatus);
char* getCodeWordA(char* sGroup, char* sDevice, boolean bStatus);
char* getCodeWordC(char sFamily, int nGroup, int nDevice, boolean bStatus);
char* getCodeWordD(char group, int nDevice, boolean bStatus);
void sendT0();
void sendT1();
void sendTF();
void send0();
void send1();
void sendSync();
void transmit(int nHighPulses, int nLowPulses);
static char* dec2binWzerofill(unsigned long dec, unsigned int length);
static char* dec2binWcharfill(unsigned long dec, unsigned int length, char fill);
#if not defined( RCSwitchDisableReceiving )
static void handleInterrupt();
static bool receiveProtocol1(unsigned int changeCount);
static bool receiveProtocol3(unsigned int changeCount);
int nReceiverInterrupt;
#endif
int nTransmitterPin;
int nPulseLength;
int nRepeatTransmit;
char nProtocol;
#if not defined( RCSwitchDisableReceiving )
static int nReceiveTolerance;
static unsigned long nReceivedValue;
static unsigned int nReceivedBitlength;
static unsigned int nReceivedDelay;
static unsigned int nReceivedProtocol;
#endif
/*
* timings[0] contains sync timing, followed by a number of bits
*/
static unsigned int timings[RCSWITCH_MAX_CHANGES];
};
#endif
| [
"smbat.yeranyan@gmail.com"
] | smbat.yeranyan@gmail.com |
8fc1fcfe48157816f39c1b961a75fd81dbc832d7 | 56b063c7daaa33fe03d15373261d9432b7204626 | /examples/01_Polling/ErriezMCP23017_MultiplePins/ErriezMCP23017_MultiplePins.ino | bc59ebac25bdcdb95be8769ea3128dc2e7b43a51 | [
"MIT"
] | permissive | Erriez/ErriezMCP23017 | d16e6c280db0036cb736d0f150cf5d7f2f64b23c | 93b431d8059bff3590e6c2baa0433f3005477a2b | refs/heads/master | 2021-05-26T22:53:44.806736 | 2020-09-06T09:34:06 | 2020-09-06T09:34:06 | 254,180,771 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,741 | ino | /*
* MIT License
*
* Copyright (c) 2020 Erriez
*
* 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.
*/
/*!
* \brief MCP23017 I2C 16-pin IO-expander example for Arduino
* \details
* Source: https://github.com/Erriez/ErriezMCP23017
* Documentation: https://erriez.github.io/ErriezMCP23017
*
* This example demonstrates the "Arduino easy" way to handle inputs and
* outputs. Handling inputs and outputs simultanesouly is not possible,
* because this example uses a blocking delay(). Please refer to PinPort
* example to handle inputs and outputs currently.
*
* Hardware:
* - MCP23017 SDA, SCL connected to MCU I2C (TWI) pins
* - PA0..PA7: Button input with pull-up
* - PB0..PB7: LED output
*/
#include <Arduino.h>
#include <Wire.h>
#include <ErriezMCP23017.h>
// Default I2C Address 0x20
#define MCP23017_I2C_ADDRESS 0x20
// Create MCP23017 object
ErriezMCP23017 mcp = ErriezMCP23017(MCP23017_I2C_ADDRESS);
static void handleOutputs()
{
Serial.println(F("Shift output PORTB..."));
// Pins B0..B7 HIGH with a blocking delay
for (uint8_t outputPin = 8; outputPin <= 15; outputPin++) {
mcp.digitalWrite(outputPin, HIGH);
delay(100);
}
// Pins B0..B7 LOW with a blocking delay
for (uint8_t outputPin = 15; outputPin >= 7; outputPin--) {
mcp.digitalWrite(outputPin, LOW);
delay(100);
}
}
static void handleInputs()
{
Serial.println(F("Input PORTA:"));
// Print state input pins PORTA
for (uint8_t inputPin = 0; inputPin <= 7; inputPin++) {
Serial.print(F(" A"));
Serial.print(inputPin);
Serial.print(F(": "));
if (mcp.digitalRead(inputPin)) {
Serial.println(F("HIGH"));
} else {
Serial.println(F("LOW"));
}
}
}
void setup()
{
// Initialize Serial
Serial.begin(115200);
Serial.println(F("\nErriez MCP23017 I2C IO-expander Multiple Pin example"));
// Initialize Wire
Wire.begin();
Wire.setClock(400000);
// Initialize MCP23017
while (!mcp.begin()) {
Serial.print(F("Error: MCP23017 not found, code: "));
Serial.println(mcp.getI2CStatus());
delay(3000);
}
// Pins A0..A7 input with pull-up enabled
for (uint8_t inputPin = 0; inputPin <= 7; inputPin++) {
mcp.pinMode(inputPin, INPUT_PULLUP);
}
// Pins B0..B7 output
for (uint8_t outputPin = 8; outputPin <= 15; outputPin++) {
mcp.pinMode(outputPin, OUTPUT);
}
// Print registers
// mcp.dumpRegisters(&Serial);
}
void loop()
{
// Synchronous call to handle outputs
handleOutputs();
// Handle inputs
handleInputs();
}
| [
"erriez@users.noreply.github.com"
] | erriez@users.noreply.github.com |
6e9bb3a2414ebe55ef2522d87b36d2c1ea27db6f | 8b69b0fa5665d972658b9a0b8609e2f6722658dd | /QtUtility/minidump.cpp | f5b6c534dbe4cb8364598e77e2bfa48851c6a386 | [] | no_license | hcz362329/hcz362329-QtUtility | 19cbdb59a920573d0882a053d599e016a7237beb | b7c16fdad89b1b917e4b463838f81502dc9b00ee | refs/heads/master | 2022-11-15T08:16:43.047133 | 2020-07-08T03:55:04 | 2020-07-08T03:55:04 | 250,267,308 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,249 | cpp | #include "MiniDump.h"
#include "Shlwapi.h"
#pragma comment(lib,"Shlwapi.lib")
static void hprintf(HANDLE LogFile, LPCTSTR format, ...)
{
TCHAR buffer[2000]; // wvsprintf never prints more than one K.
va_list arglist;
va_start(arglist, format);
wvsprintf(buffer, format, arglist);
va_end(arglist);
DWORD NumBytes;
WriteFile(LogFile, buffer, lstrlen(buffer) * sizeof(TCHAR), &NumBytes, 0);
}
static BOOL GetLogicalAddress(PVOID addr, PTSTR szModule, DWORD len, DWORD& section, DWORD& offset)
{
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQuery(addr, &mbi, sizeof(mbi)))
return FALSE;
DWORD hMod = (DWORD)mbi.AllocationBase;
if (!GetModuleFileName((HMODULE)hMod, szModule, len))
return FALSE;
// Point to the DOS header in memory
PIMAGE_DOS_HEADER pDosHdr = (PIMAGE_DOS_HEADER)hMod;
// From the DOS header, find the NT (PE) header
PIMAGE_NT_HEADERS pNtHdr = (PIMAGE_NT_HEADERS)(hMod + pDosHdr->e_lfanew);
PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION(pNtHdr);
DWORD rva = (DWORD)addr - hMod; // RVA is offset from module load address
// Iterate through the section table, looking for the one that encompasses
// the linear address.
for (unsigned i = 0;
i < pNtHdr->FileHeader.NumberOfSections;
i++, pSection++)
{
DWORD sectionStart = pSection->VirtualAddress;
DWORD sectionEnd = sectionStart
+ max(pSection->SizeOfRawData, pSection->Misc.VirtualSize);
// Is the address in this section???
if ((rva >= sectionStart) && (rva <= sectionEnd))
{
// Yes, address is in the section. Calculate section and offset,
// and store in the "section" & "offset" params, which were
// passed by reference.
section = i + 1;
offset = rva - sectionStart;
return TRUE;
}
}
return FALSE; // Should never get here!
}
MiniDump::MiniDump()
{
}
MiniDump::~MiniDump()
{
}
void MiniDump::EnableAutoDump(bool bEnable)
{
if (bEnable)
{
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
}
}
LONG MiniDump::ApplicationCrashHandler(EXCEPTION_POINTERS *pException)
{
/*if (IsDebuggerPresent())
{
return EXCEPTION_CONTINUE_SEARCH;
}*/
static int n = 0;
n++;
TCHAR szDumpDir[MAX_PATH] = { 0 };
TCHAR szDumpFile[MAX_PATH] = { 0 };
TCHAR szMsg[MAX_PATH] = { 0 };
SYSTEMTIME stTime = { 0 };
// 构建dump文件路径;
GetLocalTime(&stTime);
GetModuleFileName(NULL, szDumpDir, MAX_PATH);
*(wcsrchr(szDumpDir,'\\'))=0;
//::GetCurrentDirectory(MAX_PATH, szDumpDir);
TSprintf(szDumpFile, _T("%s\\%04d%02d%02d_%02d%02d%02d-%d.dmp"), szDumpDir,
stTime.wYear, stTime.wMonth, stTime.wDay,
stTime.wHour, stTime.wMinute, stTime.wSecond,n);
// 创建dump文件;
//::MessageBox(0, 0, 0, 0);
WriteErrorLog(pException);
CreateDumpFile(szDumpFile, pException);
// 弹出一个错误对话框或者提示上传, 并退出程序;
TSprintf(szMsg, _T("I'm so sorry, but the program crashed.\r\ndump file : %s"), szDumpFile);
//FatalAppExit(-1, szMsg);
return EXCEPTION_EXECUTE_HANDLER;
}
void MiniDump::CreateDumpFile(LPCWSTR strPath, EXCEPTION_POINTERS *pException)
{
// 创建Dump文件;
HANDLE hDumpFile = CreateFile(strPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// Dump信息;
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = FALSE;
// 写入Dump文件内容;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, (MINIDUMP_TYPE)(MiniDumpNormal | MiniDumpWithDataSegs), &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
void MiniDump::WriteErrorLog(PEXCEPTION_POINTERS pExInfo) {
PEXCEPTION_RECORD pException = pExInfo->ExceptionRecord;
PCONTEXT pContext = pExInfo->ContextRecord;
MEMORY_BASIC_INFORMATION memInfo;
TCHAR szDumpDir[MAX_PATH] = {0};
GetModuleFileName(NULL, szDumpDir, MAX_PATH);
*(wcsrchr(szDumpDir, '\\')) = 0;
TCHAR szErrorLog[MAX_PATH * 2] = { 0 };
lstrcat(szErrorLog, _T("./Error.Log"));
TSprintf(szErrorLog, _T("%s\\Error.Log"), szDumpDir);
BOOL bFileExists = PathFileExists(szErrorLog);
HANDLE hLogFile = CreateFile(szErrorLog, GENERIC_WRITE, 0, 0,
bFileExists ? OPEN_EXISTING : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
if (hLogFile != INVALID_HANDLE_VALUE)
{
TCHAR szTemp[256];
if (bFileExists)
{
// 末尾追加
SetFilePointer(hLogFile, 0, NULL, FILE_END);
hprintf(hLogFile, _T("\r\n--------------------\r\n"));
}
SYSTEMTIME stTime = { 0 };
// 构建dump文件路径;
GetLocalTime(&stTime);
wsprintf(szTemp, _T("%02d-%02d-%02d %02d:%02d:%02d\r\n"),
stTime.wYear, stTime.wMonth, stTime.wDay,
stTime.wHour, stTime.wMinute, stTime.wSecond);
hprintf(hLogFile, szTemp);
hprintf(hLogFile, _T("qtutility log\r\n"));
//Program Information:
hprintf(hLogFile, _T("\r\nProgram Information:\r\n"));
//System Information:
hprintf(hLogFile, _T("\r\nSystem Information:\r\n"));
//操作系统信息
//DirectX信息
//显示设备信息
//CPU类型
//内存
MEMORYSTATUSEX memoryStatus;
memset(&memoryStatus, sizeof(MEMORYSTATUS), 0);
memoryStatus.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatusEx(&memoryStatus);
hprintf(hLogFile, _T("Memory: [Available]%I64dM / [Total]%I64dM \r\n"), memoryStatus.ullAvailPhys >> 20, memoryStatus.ullTotalPhys >> 20);
//硬盘
TCHAR szBuffer[MAX_PATH];
ZeroMemory(szBuffer, sizeof(szBuffer));
GetWindowsDirectory(szBuffer, sizeof(szBuffer));
TCHAR szHarddisk[MAX_PATH];
lstrcpy(szHarddisk, szBuffer);
TCHAR * pszDisk = wcschr(szHarddisk, _T(':'));
if (pszDisk != NULL)
{
szHarddisk[pszDisk - szHarddisk + 1] = 0;
}
if (GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "GetDiskFreeSpaceExA"))
{
ULARGE_INTEGER ulAvailable;
ULARGE_INTEGER ulTotal;
ULARGE_INTEGER ulFree;
GetDiskFreeSpaceEx(szHarddisk, &ulAvailable, &ulTotal, &ulFree);
hprintf(hLogFile, _T("System Disk: [Available]%ldM / [Total]%ldM\r\n"), (ulFree.HighPart << (32 - 20)) + (ulFree.LowPart >> 20),
(ulTotal.HighPart << (32 - 20)) + (ulTotal.LowPart >> 20));
}
else
{
DWORD dwSectorsPerCluster; // sectors per cluster
DWORD dwBytesPerSector; // bytes per sector
DWORD dwNumberOfFreeClusters; // free clusters
DWORD dwTotalNumberOfClusters; // total clusters
GetDiskFreeSpace(szHarddisk, &dwSectorsPerCluster, &dwBytesPerSector, &dwNumberOfFreeClusters, &dwTotalNumberOfClusters);
hprintf(hLogFile, _T("System Disk: [Available]%ldM / [Total]%ldM\r\n"), ((((dwNumberOfFreeClusters*dwSectorsPerCluster) >> 10)*dwBytesPerSector) >> 10,
(((dwTotalNumberOfClusters*dwSectorsPerCluster) >> 10)*dwBytesPerSector) >> 10));
}
//网络
//是否设置了代理服务器
//是否在防火墙内
//IP地址
//Error Information:
hprintf(hLogFile, _T("\r\nError Information:\r\n"));
TCHAR szCrashModuleName[MAX_PATH] = { _T("Unknown") };
if (VirtualQuery((void*)pContext->Eip, &memInfo, sizeof(memInfo)) &&
GetModuleFileName((HINSTANCE)memInfo.AllocationBase, szCrashModuleName, sizeof(szCrashModuleName)) > 0)
{
}
hprintf(hLogFile, _T("Error Module:%s \r\n"), szCrashModuleName);
hprintf(hLogFile, _T("Code: 0x%08x \r\n"), pException->ExceptionCode);
hprintf(hLogFile, _T("Flag: 0x%08x \r\n"), pException->ExceptionFlags);
hprintf(hLogFile, _T("Addr: 0x%08x \r\n"), pException->ExceptionAddress);
if (EXCEPTION_ACCESS_VIOLATION == pException->ExceptionCode)
{
for (int i = 0; i < (int)pException->NumberParameters; i++)
{
hprintf(hLogFile, _T("%d: %d(0x%08x)\r\n"), i, pException->ExceptionInformation[i], pException->ExceptionInformation[i]);
}
if (pException->NumberParameters >= 2)
{
TCHAR szReadWrite[256] = { 0 };
if (pException->ExceptionInformation[0])
{
lstrcpy(szReadWrite, _T("Write to"));
}
else
{
lstrcpy(szReadWrite, _T("Read from"));
}
hprintf(hLogFile, _T("%s location %08x caused an access violation.\r\n"), szReadWrite, pException->ExceptionInformation[1]);
}
}
hprintf(hLogFile, _T("Caused error at %04x:%08x.\r\n"), pContext->SegCs, pContext->Eip);
hprintf(hLogFile, _T("\r\nRegisters:\r\n"));
hprintf(hLogFile, _T("EAX=%08x CS=%04x EIP=%08x EFLGS=%08x\r\n"),
pContext->Eax, pContext->SegCs, pContext->Eip, pContext->EFlags);
hprintf(hLogFile, _T("EBX=%08x SS=%04x ESP=%08x EBP=%08x\r\n"),
pContext->Ebx, pContext->SegSs, pContext->Esp, pContext->Ebp);
hprintf(hLogFile, _T("ECX=%08x DS=%04x ESI=%08x FS=%04x\r\n"),
pContext->Ecx, pContext->SegDs, pContext->Esi, pContext->SegFs);
hprintf(hLogFile, _T("EDX=%08x ES=%04x EDI=%08x GS=%04x\r\n"),
pContext->Edx, pContext->SegEs, pContext->Edi, pContext->SegGs);
int NumCodeBytes = 16; // Number of code bytes to record.
hprintf(hLogFile, _T("Bytes at CS:EIP:\r\n"));
unsigned char *code = (unsigned char*)pContext->Eip;
for (int codebyte = 0; codebyte < NumCodeBytes; codebyte++)
{
__try
{
hprintf(hLogFile, _T("%02x "), code[codebyte]);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
hprintf(hLogFile, _T("?? "));
}
}
hprintf(hLogFile, _T("\r\n"));
hprintf(hLogFile, _T("Call Stack:\r\n"));
DWORD pc = pContext->Eip;
PDWORD pFrame, pPrevFrame;
pFrame = (PDWORD)pContext->Ebp;
do
{
TCHAR szModule[MAX_PATH] = _T("");
DWORD section = 0, offset = 0;
__try
{
if (GetLogicalAddress((PVOID)pc, szModule, sizeof(szModule), section, offset) == FALSE)
{
break;
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
break;
}
hprintf(hLogFile, _T("%08X %04X:%08X %s\r\n"), pc, section, offset, szModule);
pc = pFrame[1];
pPrevFrame = pFrame;
pFrame = (PDWORD)pFrame[0]; // precede to next higher frame on stack
if ((DWORD)pFrame & 3) // Frame pointer must be aligned on a
break; // DWORD boundary. Bail if not so.
if (pFrame <= pPrevFrame)
break;
// Can two DWORDs be read from the supposed frame address?
if (IsBadWritePtr(pFrame, sizeof(PVOID) * 2))
break;
} while (1);
hprintf(hLogFile, _T("\r\n"));
hprintf(hLogFile, _T("\r\nqtutility error log end......\r\n"));
CloseHandle(hLogFile);
}
else
{
}
} | [
"hcz362329@163.com"
] | hcz362329@163.com |
4c12c938b71e24c55c0ca8884a012fa9d8ca3166 | a93f5a41959faa793f4f22c439ad4c1ea92668b8 | /AntsBook/2_3_7/main03.cpp | 7d28f1fd7e099e0566a856969134e46d08b4c4e4 | [] | no_license | admiswalker/i-am-learning-coding | 08a473da773d0e2e67d44462c2d7dee83fa0adac | 9c0d152d313aae06affdf0823fd59a188705d8f8 | refs/heads/master | 2021-07-07T05:21:09.871137 | 2020-12-21T23:55:42 | 2020-12-21T23:55:42 | 218,574,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | cpp | // ref of base: ants book page. 66
#include <bits/stdc++.h>
using namespace std;
void dps(const int n, const int m, const int mod){
vector<int> dp(m+1, 0);
dp[0] = 1;
for(int i=1; i<=m; ++i){
for(int j=0; j<=n; ++j){
if(j-i>=0){
dp[j] += dp[j-i];
dp[j] %= mod;
}else{
dp[j] = dp[i-1];
dp[j] %= mod;
}
}
}
printf("%d\n", dp[m]);
}
int main(){
int n=4;
int m=3;
int mod=10000;
dps(n, m, mod);
return 0;
}
/*
4
3
10000
*/
| [
"admiswalker@gmail.com"
] | admiswalker@gmail.com |
e354035c7126ffec8166505540f358db6739ebad | 299d2a05d40c2962332abc83e203a3160906d53b | /w1_SimpleEcho/eServer.cpp | bd874e9448d8da8ca764869bdb4aa0921d96f11d | [] | no_license | woodok/w1_SimpleEcho | de49bc275f49926e9b6af21e3cc79f5a25777346 | 99af62f2e5f4186c0a7787885ba4ba961fce9446 | refs/heads/master | 2020-12-24T14:01:19.998896 | 2015-07-08T06:02:28 | 2015-07-08T06:02:28 | 37,452,633 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,483 | cpp | #include <iostream>
//#include <stdio.h>
#include <cstdio>
//#include <stdlib.h>
#include <cstdlib>
#include <process.h>
#include <WinSock2.h>
#include <Windows.h>
#define BUF_SIZE 100
#define READ 3
#define WRITE 5
typedef struct
{
SOCKET hClntSock;
SOCKADDR_IN clntAdr;
} PER_HANDLE_DATA, *LPPER_HANDLE_DATA;
typedef struct
{
OVERLAPPED overlapped;
WSABUF wsaBuf;
char buffer[BUF_SIZE];
int rwMode; // read mode / write mode distinguisher
} PER_IO_DATA, *LPPER_IO_DATA;
DWORD WINAPI EchoThreadMain(LPVOID CompletionPortIO);
void ErrorHandling(char * mesaage);
int main(int argc, char * argv[])
{
WSADATA wsaData;
HANDLE hComPort;
SYSTEM_INFO sysInfo;
LPPER_IO_DATA ioInfo;
LPPER_HANDLE_DATA handleInfo;
SOCKET hServSock;
SOCKADDR_IN servAdr;
int recvBytes, i, flags = 0;
if (argc != 2) {
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
ErrorHandling("WSAStartup() error");
hComPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
GetSystemInfo(&sysInfo);
for (i = 0; i < (int)(sysInfo.dwNumberOfProcessors); i++)
_beginthreadex(NULL, 0, (unsigned int (__stdcall *)(void *))EchoThreadMain, (LPVOID)hComPort, 0, NULL);
hServSock = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
memset(&servAdr, 0, sizeof(servAdr));
servAdr.sin_family = AF_INET;
servAdr.sin_addr.s_addr = htonl(INADDR_ANY);
servAdr.sin_port = htons(atoi(argv[1]));
bind(hServSock, (SOCKADDR *)&servAdr, sizeof(servAdr));
listen(hServSock, 5);
while (1)
{
SOCKET hClntSock;
SOCKADDR_IN clntAdr;
int addrLen = sizeof(clntAdr);
hClntSock = accept(hServSock, (SOCKADDR *)&clntAdr, &addrLen);
handleInfo = (LPPER_HANDLE_DATA)malloc(sizeof(PER_HANDLE_DATA));
handleInfo->hClntSock = hClntSock;
memcpy(&(handleInfo->clntAdr), &clntAdr, addrLen);
CreateIoCompletionPort((HANDLE)hClntSock, hComPort, (DWORD)handleInfo, 0);
ioInfo = (LPPER_IO_DATA)malloc(sizeof(PER_IO_DATA));
memset(&(ioInfo->overlapped), 0, sizeof(OVERLAPPED));
ioInfo->wsaBuf.len = BUF_SIZE;
ioInfo->wsaBuf.buf = ioInfo->buffer;
ioInfo->rwMode = READ;
WSARecv(handleInfo->hClntSock, &(ioInfo->wsaBuf), 1, (LPDWORD)&recvBytes, (LPDWORD)&flags, &(ioInfo->overlapped), NULL);
}
return 0;
}
DWORD WINAPI EchoThreadMain(LPVOID pComPort)
{
HANDLE hComPort = (HANDLE)pComPort;
SOCKET sock;
DWORD bytesTrans;
LPPER_HANDLE_DATA handleInfo;
LPPER_IO_DATA ioInfo;
DWORD flags = 0;
while (1)
{
GetQueuedCompletionStatus(hComPort, &bytesTrans, (LPDWORD)&handleInfo, (LPOVERLAPPED *)&ioInfo, INFINITE);
sock = handleInfo->hClntSock;
if (ioInfo->rwMode == READ)
{
puts("message received");
if (bytesTrans == 0) // EOF Àü¼Û½Ã
{
closesocket(sock);
free(handleInfo); free(ioInfo);
continue;
}
memset(&(ioInfo->overlapped), 0, sizeof(OVERLAPPED));
ioInfo->wsaBuf.len = bytesTrans;
ioInfo->rwMode = WRITE;
WSASend(sock, &(ioInfo->wsaBuf), 1, NULL, 0, &(ioInfo->overlapped), NULL);
ioInfo = (LPPER_IO_DATA)malloc(sizeof(PER_IO_DATA));
memset(&(ioInfo->overlapped), 0, sizeof(OVERLAPPED));
ioInfo->wsaBuf.len = BUF_SIZE;
ioInfo->wsaBuf.buf = ioInfo->buffer;
ioInfo->rwMode = READ;
WSARecv(sock, &(ioInfo->wsaBuf), 1, NULL, &flags, &(ioInfo->overlapped), NULL);
}
else
{
puts("message sent");
free(ioInfo);
}
}
return 0;
}
void ErrorHandling(char * message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
} | [
"newwoodok@gmail.com"
] | newwoodok@gmail.com |
0e20fdbd84c58b50c7371ecf21d8b78d3b5591b5 | 4351f7b1d0f8e9a7168525ae17515cc802b6c254 | /W452. Minimum Number of Arrows to Burst Balloons.cpp | 78dce7f8391b294b157cd003646259573675bf82 | [] | no_license | PluckyCoward/WCH_IS_DEAD | a55034e0e5ea0f3a32e1bbec871fdcaf3be8a129 | db20f4ab3388bb310d9cdf9ffdd13e863f9159ec | refs/heads/master | 2023-02-17T19:08:25.082897 | 2021-01-15T09:59:42 | 2021-01-15T09:59:42 | 234,245,320 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cpp | class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if(points.empty())
return 0;
sort(points.begin(), points.end(), [](const vector<int> &u, const vector<int> &v){
return u[1] < v[1];
});
int pos = points[0][1];
int res = 1;
for (auto p : points) {
if (p[0] > pos) {
pos = p[1];
res++;
}
}
return res;
}
}; | [
"Wchoward@users.noreply.github.com"
] | Wchoward@users.noreply.github.com |
648c59e40264057e7f76dd20d811ae6b6f6c48ec | ee6a7af57576d722e4c1fe8a0ac1cf47f6c2aa46 | /2-C++E-commerce platform-2021-lab2/src/screen_jump.cpp | 9e80924331b7c82806e62b72c181f55fe074eba6 | [] | no_license | WZH-hub/C-E-commerce-platform-2021 | 3e544e034b4b349e035c9a598c84ef6d5417770a | 9f4b65d742b4ae75978670a12d20c8ac15f7cef1 | refs/heads/master | 2023-06-25T09:42:33.380862 | 2021-07-29T07:48:14 | 2021-07-29T07:48:14 | 390,638,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,199 | cpp | #include "screen_jump.h"
using namespace std;
user_func user;
int screen_jump::screen_01()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_02()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_03()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_04()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_05(int change)
{
if (change == 1) //商家
return 7;
else if (change == 2) //消费者
return 6;
else if (change == 3) //管理员
return 14;
else
return 1;
}
int screen_jump::screen_06()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) recharge." << endl;
cout << "7) change password." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "11) pay for your order." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10 && change != 11) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return change;
case 6:
return 8;
case 7:
return 10;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
case 11:
return 18;
}
return 1;
}
int screen_jump::screen_07()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) change goods information." << endl;
cout << "7) change password." << endl;
cout << "8) add goods." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return change;
case 6:
return 9;
case 7:
return 10;
case 8:
return 11;
}
return 1;
}
int screen_jump::screen_08(int change)
{
//根据反馈的情况进行跳转
//消费者登录且充值成功,返回1;未登录,返回2;放弃充值,返回0
if (change == 1 || change == 0)
return 6;
else //未登录的话跳转到登录界面
return 5;
}
int screen_jump::screen_09()
{
return 7;
}
int screen_jump::screen_10(int change)
{
if (change == 1) //商家
return 7;
else if (change == 2) //消费者
return 6;
else //还没有登录
return 5;
}
int screen_jump::screen_11()
{
return 7;
}
int screen_jump::screen_14()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_15()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return change;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
}
return 1;
}
int screen_jump::screen_16()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "11) pay or cancel your order." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10 && change != 11) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return change;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
case 11:
return 18;
}
return 1;
}
int screen_jump::screen_17()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "11) pay or cancel your order." << endl;
//cout << "11) pay for your order." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10 && change != 11) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return change;
case 6:
return 8;
case 7:
return 10;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
case 11:
return 18;
}
return 1;
}
int screen_jump::screen_18()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "11) recharge." << endl;
cout << "12) pay or cancel your order." << endl;
//cout << "11) pay for your order." << endl;
cout
<< "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10 && change != 11) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return change;
case 6:
return 6;
case 7:
return 7;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
case 11:
return 8;
case 12:
return 18;
}
return 1;
} | [
"wangzhenhao137@163.com"
] | wangzhenhao137@163.com |
ac49f19d18ce1d80ece1f16509d2b29b441cffed | 54cfb83f5ad185d343562b812723b8fc59c75d5b | /Mega Man X3/Mega Man X3/QuadTree.h | ea1405d2102a3399caa15950edb694abbea93dc2 | [] | no_license | vantranguit920/Game-MegamanX3 | 3a98db9be2471c6d83b15f02553d8f34b40ad9ff | 58fe7924d7c3395a7b361a30bd55a28961a4fdf5 | refs/heads/master | 2022-01-31T06:18:25.652911 | 2019-06-05T08:04:17 | 2019-06-05T08:04:17 | 190,344,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | h | #pragma once
#include <d3dx9.h>
#include <d3d9.h>
#include <vector>
#include "Viewport.h"
#include "Object.h"
class QuadTree
{
protected:
int GetIndex(RECT r);
void Split();
bool IsContain(RECT r);
public:
QuadTree();
QuadTree(int level, RECT bound);
~QuadTree();
void Clear();
void InsertObject(Object *object);
void GetObjectsCollideAble(std::vector<Object*> &listObject, std::vector<Object*> &listWall, RECT rect);
void GetAllObject(std::vector<Object*> &listObject, RECT rect);
int GetTotalObject();
RECT Bound;
int mLevel;
std::vector<Object*> mListObject;
QuadTree **Nodes;
}; | [
"="
] | = |
20ba8558a6045e8c83e646c9c12c01dbaea8c24b | 081642f0c0486db9bede51f2e9308baf257ac097 | /PDFWriter3_6/PDFWriterTestPlayground/WindowsPath.cpp | 5598495389c6bd7fbef8d9ec789cfd55ab88b85c | [
"Apache-2.0"
] | permissive | Hopding/hummus-ios-build | 3f1d1f70f3832e58f52930d4e609b43192f7f4a3 | 28292bfdb2a8551bdcb87a4d1a009e16455d2e41 | refs/heads/master | 2021-01-16T19:08:45.999760 | 2018-02-25T16:43:07 | 2018-02-25T16:43:07 | 100,146,456 | 2 | 1 | null | 2018-02-25T16:43:08 | 2017-08-13T01:24:08 | C | UTF-8 | C++ | false | false | 4,419 | cpp | #include "WindowsPath.h"
#include <sstream>
WindowsPath::WindowsPath(void)
{
}
WindowsPath::WindowsPath(const string& inPath)
{
SetPathFromString(inPath);
}
WindowsPath::~WindowsPath(void)
{
}
void WindowsPath::SetPathFromString(const string& inPath)
{
// path is expected to be either <driveLetter>:\<folder1>\<folder2>....
// or <folder1>\<folder2>...
mPathComponents.clear();
mDriveLetter = "";
string::size_type searchPosition = 0;
if(inPath.size() > 1 && inPath.at(1) == ':')
{
mDriveLetter = inPath.substr(0,1);
searchPosition = 3; // may be eitehr c: or c:\...., which should be equivelent
}
string newComponent;
while(searchPosition < inPath.length())
{
string::size_type findResult = inPath.find("\\",searchPosition);
if(findResult == inPath.npos)
newComponent = inPath.substr(searchPosition,findResult);
else
newComponent = inPath.substr(searchPosition,findResult-searchPosition);
// with .. i'm doing some calculation already of sparing interim folders.
// as a result if there are still ..s they will be only at the beginning of the path
if(newComponent == ".." && mPathComponents.size() > 0 && mPathComponents.back() != "..")
PopPathComponent();
else if(newComponent != ".")
PushPathComponent(newComponent);
searchPosition = (findResult == inPath.npos) ? inPath.length() : findResult+1;
}
}
bool WindowsPath::IsAbsolute() const
{
return mDriveLetter.length() > 0;
}
WindowsPath WindowsPath::GetFolder() const
{
WindowsPath newPath;
// in edge case of drive letter only, will return the same path. in empty relative, will enter empty relative
// in all other cases will return a path which is the same drive letter, and with one less component from the component list
newPath.SetDriveLetter(mDriveLetter);
newPath.mPathComponents = mPathComponents;
newPath.PopPathComponent();
return newPath;
}
WindowsPath WindowsPath::InterpretFrom(const WindowsPath& inPath) const
{
if(IsAbsolute()) // for absolute paths retain as is
return *this;
// otherwise, construct a new path from the two paths, and return
WindowsPath newPath = inPath;
StringList::const_iterator it = mPathComponents.begin();
for(; it != mPathComponents.end();++it)
{
if(*it == "..")
newPath.PopPathComponent();
else
newPath.PushPathComponent(*it);
}
return newPath;
}
string WindowsPath::ToString() const
{
stringstream pathStream;
if(mDriveLetter != "")
pathStream<<mDriveLetter<<":\\";
if(mPathComponents.size() > 0)
{
StringList::const_iterator it = mPathComponents.begin();
pathStream<<*it;
++it;
for(; it != mPathComponents.end();++it)
pathStream<<"\\"<<*it;
}
return pathStream.str();
}
void WindowsPath::PushPathComponent(const string& inComponent)
{
mPathComponents.push_back(inComponent);
}
void WindowsPath::PopPathComponent()
{
if(mPathComponents.size() > 0)
mPathComponents.pop_back();
}
void WindowsPath::SetDriveLetter(const string& inDriveLetter)
{
mDriveLetter = inDriveLetter;
}
FileURL WindowsPath::ToFileURL() const
{
FileURL aFileURL;
if(IsAbsolute())
{
// a drive letter is written to path like this: file:// /c|
aFileURL.PushPathComponent(mDriveLetter + "|");
aFileURL.SetIsAbsolute(true);
}
StringList::const_iterator it = mPathComponents.begin();
for(; it != mPathComponents.end(); ++it)
aFileURL.PushPathComponent(*it);
return aFileURL;
}
void WindowsPath::FromFileURL(const FileURL& inFileURL)
{
SingleValueContainerIterator<const StringList> itComponents = inFileURL.GetComponentsIterator();
mPathComponents.clear();
mDriveLetter = "";
// move to first component (if empty...just return)
if(!itComponents.MoveNext())
return;
// check first component, if it's a drive letter
if(itComponents.GetItem().at(itComponents.GetItem().length() - 1) == '|')
mDriveLetter = itComponents.GetItem().substr(0,itComponents.GetItem().length() - 1);
else
mPathComponents.push_back(itComponents.GetItem());
while(itComponents.MoveNext())
mPathComponents.push_back(itComponents.GetItem());
}
| [
"andrew.dillon.j@gmail.com"
] | andrew.dillon.j@gmail.com |
06267d7d1ca36e8e64fc0dd7c0b5efea8ee4c380 | 4bb00c27ab23f3410adbe990d1f26c5b57eebadc | /CPAR-Project1/MatrixMultiplicationCLI.cpp | 3ea329ff19bc72baabc1bed65a604035e8be033e | [] | no_license | carlosmccosta/Distributed-Prime-Sieve | 680d4d8e94643f5e26cb49aab4df53d08b24342c | dd6ac055f44c5d48732c5b75049fe62ee1f5ddd2 | refs/heads/master | 2016-09-05T17:11:48.374641 | 2014-11-26T14:16:39 | 2014-11-26T14:16:39 | 17,256,999 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,647 | cpp | #include "MatrixMultiplicationCLI.h"
MatrixMultiplicationCLI::MatrixMultiplicationCLI(void) {}
MatrixMultiplicationCLI::~MatrixMultiplicationCLI(void) {}
int main() {
ConsoleInput::getInstance()->clearConsoleScreen();
int option = 1;
bool roundLoaded = false;
do {
ConsoleInput::getInstance()->clearConsoleScreen();
cout << "############### Parallel computing - Project 1 - Carlos Costa #####################\n";
cout << " >>> Matrix multiplication <<< \n";
cout << "#######################################################################################\n\n\n";
cout << " 1 - Basic matrix multiplication\n";
cout << " 2 - Line matrix multiplication\n";
cout << " 3 - Block matrix multiplication\n\n";
cout << " 0 - Exit\n\n\n" << endl;
option = ConsoleInput::getInstance()->getIntCin(" >>> Option: ", " -> Insert one of the listed options!\n", 0, 4);
if (option == 0) {
break;
}
bool validOption = true;
bool loadFromFiles = false;
BidimensionalMatrix *leftMatrix, *rightMatrix;
MatrixMultiplication* matrixMultAlgorithm;
string leftMatrixFilename;
string rightMatrixFilename;
string resultFile = "";
unsigned int blockColumnSize = 1, blockLineSize = 1;
loadFromFiles = ConsoleInput::getInstance()->getYesNoCin("\n ## Load matrices from files? (Y/N): ");
if (loadFromFiles) {
cout << " # Left matrix file: ";
leftMatrixFilename = ConsoleInput::getInstance()->getLineCin();
leftMatrix = new BidimensionalMatrix();
if (!leftMatrix->initializeMatrixFromFile(leftMatrixFilename)) {
ConsoleInput::getInstance()->getUserInput();
continue;
}
cout << " # Right matrix file: ";
rightMatrixFilename = ConsoleInput::getInstance()->getLineCin();
rightMatrix = new BidimensionalMatrix();
if (!rightMatrix->initializeMatrixFromFile(rightMatrixFilename)) {
ConsoleInput::getInstance()->getUserInput();
continue;
}
bool loadResultFile = ConsoleInput::getInstance()->getYesNoCin("\n ## Load result file to compare? (Y/N): ");
if (loadResultFile) {
cout << " # Result matrix file: ";
resultFile = ConsoleInput::getInstance()->getLineCin();
}
} else {
cout << " > Using default initialization...\n\n";
unsigned int numberOfColumnsOfLeftMatrix = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Number of columns of left matrix: ", " -> Insert a number > 1!\n", 2, INT_MAX);
unsigned int numberOfLinesOfLeftMatrix = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Number of lines of left matrix: ", " -> Insert a number > 1!\n", 2, INT_MAX);
unsigned int numberOfColumnsOfRightMatrix = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Number of columns of right matrix: ", " -> Insert a number > 1!\n", 2, INT_MAX);
leftMatrix = new BidimensionalMatrix(numberOfColumnsOfLeftMatrix, numberOfLinesOfLeftMatrix);
leftMatrix->initializeMatrix();
rightMatrix = new BidimensionalMatrix(numberOfColumnsOfRightMatrix, numberOfColumnsOfLeftMatrix);
rightMatrix->initializeMatrixWithSequenceOnLines();
}
switch (option) {
case 1: {
matrixMultAlgorithm = new MatrixMultiplicationBasic();
break;
}
case 2: {
matrixMultAlgorithm = new MatrixMultiplicationLine();
break;
}
case 3: {
blockColumnSize = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Block column size: ", " -> Insert a number > 1!\n", 2, INT_MAX);
blockLineSize = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Block line size: ", " -> Insert a number > 1!\n", 2, INT_MAX);
matrixMultAlgorithm = new MatrixMultiplicationBlock();
break;
}
default: {
validOption = false;
break;
}
}
if (validOption) {
cout << endl << "\n > Multiplying matrices...";
shared_ptr<BidimensionalMatrix> resultMatrix = matrixMultAlgorithm->performMultiplication(*leftMatrix, *rightMatrix, blockColumnSize, blockLineSize);
cout << "\n -> Multiplication finished in " << matrixMultAlgorithm->getPerformanceTimer().getElapsedTimeInSec() << " seconds\n" << endl;
bool validationResult;
if (loadFromFiles) {
cout << " > Validating result matrix with result file supplied...\n";
validationResult = resultMatrix->validateResultFromFile(resultFile);
} else {
cout << " > Validating result matrix from default initialization (result should be sum of powers)...\n";
validationResult = resultMatrix->validateResultOfDefaultMatrixInitialization(rightMatrix->getNumberLines());
}
if (validationResult) {
cout << " -> Result matrix validated!\n\n";
} else {
cout << " -> Result matrix incorrect!\n\n";
}
int exportType = ConsoleInput::getInstance()->getIntCin(" ## Export matrices? (1-Only result, 2-All, 0-None): ", " -> Insert the number of the option!\n", 0, 3);
if (exportType == 2) {
leftMatrix->exportMatrixToFile("leftMatrix.txt");
cout << " > Exporting left matrix to leftMatrix.txt...\n";
rightMatrix->exportMatrixToFile("rightMatrix.txt");
cout << " > Exporting right matrix to rightMatrix.txt...\n";
}
if (exportType == 1 || exportType == 2) {
cout << " > Exporting result matrix to resultMatrix.txt...\n";
resultMatrix->exportMatrixToFile("resultMatrix.txt");
}
cout << " -> Export finished!\n";
delete leftMatrix;
delete rightMatrix;
resultMatrix.reset();
delete matrixMultAlgorithm;
cout << endl << endl;
ConsoleInput::getInstance()->getUserInput();
}
} while (option != 0);
return 0;
}
| [
"carloscosta.cmcc@gmail.com"
] | carloscosta.cmcc@gmail.com |
8b318fecee9b8af41fd28f50b728bb9aa4733253 | 773357b475f59bbdde3a2de632638fef976e330a | /src/TopDownCameraController.h | c74ac1e19a181dede2df9f9f066c7fbe290501c0 | [
"MIT"
] | permissive | q4a/GLKeeper | 568544cc86a88536f104f7f38d6e018a62e47510 | a2207e2a459a254cbc703306ef92a09ecf714090 | refs/heads/master | 2022-11-25T08:32:44.100454 | 2020-06-26T11:36:25 | 2020-06-26T11:36:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | h | #pragma once
#include "CameraController.h"
class TopDownCameraController: public CameraController
{
public:
TopDownCameraController();
// set 3rd person camera params
// @param yawDegrees, pitchDegrees: Yaw and pitch specified in degrees
// @param distance: Distance to focus point
void Set3rdPersonParams(float yawDegrees, float pitchDegrees, float distance);
// set camera focus position
// @param position: Position
void SetFocusPoint(const glm::vec3& position);
// stop moving or rotating
void StopCameraActivity();
// process frame logic
void HandleUpdateFrame(float deltaTime) override;
// process controller is attached to game scene
void HandleSceneAttach() override;
// process controller is detached from game scene
void HandleSceneDetach() override;
// process input event
// @param inputEvent: Event data
void HandleInputEvent(MouseButtonInputEvent& inputEvent) override;
void HandleInputEvent(MouseMovedInputEvent& inputEvent) override;
void HandleInputEvent(MouseScrollInputEvent& inputEvent) override;
void HandleInputEvent(KeyInputEvent& inputEvent) override;
void HandleInputEvent(KeyCharEvent& inputEvent) override;
void HandleScreenResolutionChanged();
private:
void SetupCameraView();
void SetupCameraProjection();
private:
// current viewer params
float mDegYaw;
float mDegPitch;
float mDistance;
float mFOVy;
glm::vec3 mFocusPoint;
// current activity flags
bool mIncreasingFov;
bool mDecreasingFov;
bool mIncreasingPitch;
bool mDecreasingPitch;
bool mZoomingIn;
bool mZoomingOut;
bool mMovingN;
bool mMovingE;
bool mMovingS;
bool mMovingW;
bool mMovingAltMode;
};
| [
"codename.cpp@gmail.com"
] | codename.cpp@gmail.com |
cd3644731dac7b60a6ff028e0f100a23c0adb291 | 740fdf1cca74bdb8f930a7907a48f9bdd9b5fbd3 | /content/shell/android/linker_test_apk/chromium_linker_test_android.cc | 6e8ef567e98c644416f235d22613e8c800c91688 | [
"BSD-3-Clause"
] | permissive | hefen1/chromium | a1384249e2bb7669df189235a1ff49ac11fc5790 | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | refs/heads/master | 2016-09-05T18:20:24.971432 | 2015-03-23T14:53:29 | 2015-03-23T14:53:29 | 32,579,801 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,495 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/jni_android.h"
#include "base/android/jni_onload_delegate.h"
#include "content/public/app/content_jni_onload.h"
#include "content/public/app/content_main.h"
#include "content/public/browser/android/compositor.h"
#include "content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.h"
#include "content/shell/android/shell_jni_registrar.h"
#include "content/shell/app/shell_main_delegate.h"
namespace {
class ChromiumLinkerTestJNIOnLoadDelegate :
public base::android::JNIOnLoadDelegate {
public:
bool RegisterJNI(JNIEnv* env) override {
// To be called only from the UI thread. If loading the library is done on
// a separate thread, this should be moved elsewhere.
if (!content::android::RegisterShellJni(env))
return false;
if (!content::RegisterLinkerTestsJni(env))
return false;
return true;
}
bool Init() override {
content::Compositor::Initialize();
content::SetContentMainDelegate(new content::ShellMainDelegate());
return true;
}
};
} // namespace
// This is called by the VM when the shared library is first loaded.
JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
ChromiumLinkerTestJNIOnLoadDelegate delegate;
if (!content::android::OnJNIOnLoad(vm, &delegate))
return -1;
return JNI_VERSION_1_4;
}
| [
"hefen2007303257@gmail.com"
] | hefen2007303257@gmail.com |
0cfae3b02d745d15d02ae92df60e227fb43ed663 | b5d6cd3d27534f169789e0c8abca3a6de47b31d3 | /Util/Socket.cpp | b88a7925d87b5764f7de6cb7d6ff45065f80abad | [] | no_license | luxigo/metricsphere | faea406ef745e075674e28fb816189e663fb0969 | 18005d143de38f6edadf371b272cb493f39b3665 | refs/heads/master | 2020-06-07T10:00:32.700737 | 2014-09-19T15:27:40 | 2014-09-19T15:27:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,259 | cpp | /*
Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of the Johns Hopkins University 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/
#include "Socket.h"
int MyWinSock::_wsaCount = 0;
WSADATA MyWinSock::_wsaData;
CRITICAL_SECTION MyWinSock::stdinLock;
CRITICAL_SECTION MyWinSock::stderrLock;
CRITICAL_SECTION MyWinSock::systemLock;
#if STORE_CONNECTION_TABLE
hash_map< int , ConnectionData > MyWinSock::ConnectionTable;
#endif // STORE_CONNECTION_TABLE
void printfId(const char* format,...)
{
va_list args;
va_start(args,format);
printf( "%d] " , GetCurrentThreadId() );
vprintf(format,args);
va_end(args);
}
void fprintfId(FILE* fp , const char* format,...)
{
va_list args;
va_start( args , format );
fprintf( fp , "%d] " , GetCurrentThreadId() );
vfprintf( fp , format , args );
va_end( args);
}
bool MyWaitForSingleObject( HANDLE hHandle , DWORD milliseconds , const char* deadlockMessage , ... )
{
#if DEBUG_DEADLOCK
int state;
while( (state = WaitForSingleObject( hHandle , milliseconds ) ) == WAIT_TIMEOUT )
{
MyWinSock::fprintfId( stderr , "Possible single deadlock: " );
MyWinSock::StderrLock lock;
va_list args;
va_start( args , deadlockMessage );
vfprintf( stderr , deadlockMessage , args );
va_end( args );
fprintf( stderr , "\n" );
}
if( state != WAIT_OBJECT_0 )
{
MyWinSock::fprintfId( stderr , "Failed to wait for single event: " ) , PrintError();
return false;
}
#else // !DEBUG_DEADLOCK
if( WaitForSingleObject( hHandle , INFINITE ) != WAIT_OBJECT_0 )
{
MyWinSock::StderrLock lock;
fprintf( stderr , "Failed to wait for single event: " ) , PrintError();
return false;
}
#endif // DEADLOCK
return true;
}
bool MyWaitForMultipleObjects( DWORD nCount , const HANDLE* lpHandles , DWORD milliseconds , const char* deadlockMessage , ... )
{
#if DEBUG_DEADLOCK
int state;
while( (state = WaitForMultipleObjects( nCount , lpHandles , TRUE , milliseconds ) ) == WAIT_TIMEOUT )
{
MyWinSock::fprintfId( stderr , "Possible multiple deadlock: " );
MyWinSock::StderrLock lock;
va_list args;
va_start( args , deadlockMessage );
vfprintf( stderr , deadlockMessage , args );
va_end( args );
fprintf( stderr , "\n" );
}
if( state != WAIT_OBJECT_0 )
{
MyWinSock::fprintfId( stderr , "Failed to wait for multiple events: " ) , PrintError();
MyWinSock::StderrLock lock;
va_list args;
va_start( args , deadlockMessage );
vfprintf( stderr , deadlockMessage , args );
va_end( args );
fprintf( stderr , "\n" );
return false;
}
#else // !DEBUG_DEADLOCK
if( WaitForMultipleObjects( nCount , lpHandles , TRUE , INFINITE ) != WAIT_OBJECT_0 )
{
MyWinSock::StderrLock lock;
fprintf( stderr , "Failed to wait for multiple events: " ) , PrintError();
return false;
}
#endif // DEADLOCK
return false;
}
void MyWinSock::Load( void )
{
if(!_wsaCount)
{
InitializeCriticalSection( &stdinLock );
InitializeCriticalSection( &stderrLock );
InitializeCriticalSection( &systemLock );
if( WSAStartup( MAKEWORD(2,2), &_wsaData ) ) fprintfId( stderr , "WSAStartup failed: %s\n", LastSocketError() ) , exit(0);
}
_wsaCount++;
}
void MyWinSock::UnLoad( void )
{
_wsaCount--;
if(!_wsaCount)
{
WSACleanup();
DeleteCriticalSection( &stdinLock );
DeleteCriticalSection( &stderrLock );
DeleteCriticalSection( &systemLock );
}
}
void MyWinSock::fprintfId( FILE* fp , const char* format,...)
{
EnterCriticalSection( &stdinLock );
va_list args;
va_start(args,format);
fprintf( fp , "%d] " , GetCurrentThreadId() );
vfprintf( fp , format , args );
va_end(args);
LeaveCriticalSection( &stdinLock );
}
void MyWinSock::printfId(const char* format,...)
{
EnterCriticalSection( &stdinLock );
va_list args;
va_start(args,format);
printf( "%d] " , GetCurrentThreadId() );
vprintf(format,args);
va_end(args);
LeaveCriticalSection( &stdinLock );
}
//////////////////
void StartReceiveOnSocket( SOCKET& s , bool blockingSend , const char* errorMessage , ... )
{
if( blockingSend )
{
#if DEBUG_SOCKET
printfId( " Sending Acknowledgement (%d)\n" , s );
#endif // DEBUG_SOCKET
int ack;
if( !SendOnSocket( s , GetPointer( ack ) , sizeof(ack) ) )
{
fprintfId( stderr , "Failed to send acknowledgement (%d)\n" , s );
{
MyWinSock::StderrLock lock;
va_list args;
va_start( args , errorMessage );
vfprintf( stderr , errorMessage , args );
va_end( args );
fprintf( stderr , "\n" );
}
exit(0);
}
#if DEBUG_SOCKET
printfId( " Done (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
}
}
void EndSendOnSocket( SOCKET& s , bool blockingSend , const char* errorMessage , ... )
{
if( blockingSend )
{
#if DEBUG_SOCKET
printfId( " Receiving Acknowledgement (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
int ack;
if( !ReceiveOnSocket( s , GetPointer( ack ) , sizeof(ack) ) )
{
fprintfId( stderr , "Failed to receive acknowledgement (%d)\n" , s );
{
MyWinSock::StderrLock lock;
va_list args;
va_start( args , errorMessage );
vfprintf( stderr , errorMessage , args );
va_end( args );
fprintf( stderr , "\n" );
}
exit(0);
}
#if DEBUG_SOCKET
printfId( " Done (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
}
}
bool StartReceiveOnSocket( SOCKET& s , bool blockingSend )
{
if( blockingSend )
{
#if DEBUG_SOCKET
printfId( " Sending Acknowledgement (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
int ack;
if( !SendOnSocket( s , GetPointer( ack ) , sizeof(ack) ) )
{
fprintfId( stderr , "Failed to send acknowledgement (%d)\n" , s );
return false;
}
#if DEBUG_SOCKET
printfId( " Done (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
}
return true;
}
bool EndSendOnSocket( SOCKET& s , bool blockingSend )
{
if( blockingSend )
{
#if DEBUG_SOCKET
printfId( " Receiving Acknowledgement (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
int ack;
if( !ReceiveOnSocket( s , GetPointer( ack ) , sizeof(ack) ) )
{
fprintfId( stderr , "Failed to receive acknowledgement (%d)\n" , s );
return false;
}
#if DEBUG_SOCKET
printfId( " Done (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
}
return true;
}
void PrintHostAddress( void )
{
MyWinSock::SystemLock lock;
char hostName[512];
gethostname( hostName , 512 );
hostent* host = gethostbyname( hostName );
for( int i=0 ; ; i++ )
if( host->h_addr_list[i] == NULL ) break;
else printf( "Address[%d]: %s\n" , i , inet_ntoa( *(struct in_addr*)host->h_addr_list[i] ) ) , fflush( stdout );
for( int i=0 ; ; i++ )
if( host->h_aliases[i] == NULL ) break;
else printf( "Aliases[%d]: %s\n" , i , host->h_aliases[i] ) , fflush( stdout );
}
void GetHostAddress( char* address , char* prefix)
{
char hostName[512];
gethostname( hostName , 512 );
{
MyWinSock::SystemLock lock;
hostent* host = gethostbyname( hostName );
if( !prefix )
{
strcpy( address , inet_ntoa(*(struct in_addr*)host->h_addr) );
return;
}
for( int i=0 ; ; i++ )
if( host->h_addr_list[i] == NULL ) break;
else if( strstr( inet_ntoa( *(struct in_addr*)host->h_addr_list[i] ) , prefix ) )
{
strcpy( address , inet_ntoa(*(struct in_addr*)host->h_addr_list[i]) );
return;
}
strcpy( address , inet_ntoa(*(struct in_addr*)host->h_addr) );
}
}
int GetLocalSocketPort( SOCKET& s )
{
struct sockaddr_in local;
int len=sizeof(local);
if( getsockname ( s , (struct sockaddr*) &local , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
return -1;
}
return int(ntohs(local.sin_port));
}
const char* GetLocalSocketAddress( SOCKET& s )
{
struct sockaddr_in local;
int len=sizeof(local);
if( getsockname ( s , (struct sockaddr*) &local , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
return NULL;
}
return inet_ntoa( local.sin_addr );
}
int GetPeerSocketPort( SOCKET& s )
{
struct sockaddr_in peer;
int len = sizeof( peer );
if( getpeername ( s , (struct sockaddr*) &peer , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getpeername(): %s\n" , LastSocketError() );
return -1;
}
return int(ntohs( peer.sin_port) );
}
const char* GetPeerSocketAddress( SOCKET& s )
{
struct sockaddr_in peer;
int len=sizeof( peer );
if( getpeername ( s , (struct sockaddr*) &peer , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getpeername(): %s\n" , LastSocketError() );
return NULL;
}
return inet_ntoa( peer.sin_addr );
}
SOCKET GetConnectSocket( const char* address , int port , int ms , bool progress )
{
in_addr addr;
inet_aton( address , &addr );
return GetConnectSocket( addr , port , ms , progress );
}
SOCKET GetConnectSocket( in_addr address , int port , int ms , bool progress )
{
struct sockaddr_in addr_in;
memset( &addr_in, 0, sizeof(addr_in) );
addr_in.sin_family = AF_INET;
addr_in.sin_addr = address;
addr_in.sin_port= htons ( port );
SOCKET sock = socket( AF_INET, SOCK_STREAM , 0);
if ( sock == INVALID_SOCKET )
{
fprintfId( stderr , "Error at GetConnectSocket( ... , %d ): %s\n" , port , LastSocketError() );
return INVALID_SOCKET;
}
long long sleepCount = 0;
while (connect( sock, (const sockaddr*)&addr_in, sizeof(addr_in) ) == SOCKET_ERROR)
{
sleepCount++;
Sleep( 1 );
if( progress && !(sleepCount%ms) ) printf( "." );
}
if( progress ) printf( "\n" ) , fflush( stdout );
int val = 1;
setsockopt( sock , IPPROTO_TCP , TCP_NODELAY , (char*)&val , sizeof(val) );
#if STORE_CONNECTION_TABLE
if( sock!=INVALID_SOCKET )
{
MyWinSock::SystemLock lock;
ConnectionData& data = MyWinSock::ConnectionTable[ sock ];
struct sockaddr_in addr;
int len = sizeof( addr );
if( getsockname ( sock , (struct sockaddr*) &addr , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
return NULL;
}
memcpy( &data.localAddr , &addr.sin_addr , sizeof( addr.sin_addr ) );
data.localPort = int( ntohs( addr.sin_port ) );
if( getpeername ( sock , (struct sockaddr*) &addr , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getpeername(): %s\n" , LastSocketError() );
return NULL;
}
memcpy( &data.peerAddr , &addr.sin_addr , sizeof( addr.sin_addr ) );
data.peerPort = int( ntohs( addr.sin_port ) );
}
#endif // STORE_CONNECTION_TABLE
return sock;
}
SOCKET AcceptSocket( SOCKET listen )
{
SOCKET sock = accept( listen , NULL , NULL );
if ( sock == INVALID_SOCKET )
{
fprintfId( stderr , "accept failed: %s\n" , LastSocketError() );
return INVALID_SOCKET;
}
int val = 1;
setsockopt( sock , IPPROTO_TCP , TCP_NODELAY , (char*)&val , sizeof(val) );
#if STORE_CONNECTION_TABLE
if( sock!=INVALID_SOCKET )
{
MyWinSock::SystemLock lock;
ConnectionData& data = MyWinSock::ConnectionTable[ sock ];
struct sockaddr_in addr;
int len = sizeof( addr );
if( getsockname ( sock , (struct sockaddr*) &addr , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
return NULL;
}
memcpy( &data.localAddr , &addr.sin_addr , sizeof( addr.sin_addr ) );
data.localPort = int( ntohs( addr.sin_port ) );
if( getpeername ( sock , (struct sockaddr*) &addr , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getpeername(): %s\n" , LastSocketError() );
return NULL;
}
memcpy( &data.peerAddr , &addr.sin_addr , sizeof( addr.sin_addr ) );
data.peerPort = int( ntohs( addr.sin_port ) );
}
#endif // STORE_CONNECTION_TABLE
return sock;
}
SOCKET GetListenSocket( int& port )
{
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, 0);
if (listenSocket == INVALID_SOCKET)
{
fprintfId( stderr , "Error at socket(): %s\n", LastSocketError());
return INVALID_SOCKET;
}
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_port = htons(port);
local.sin_family = AF_INET;
// Setup the TCP listening socket
if (bind( listenSocket, (const sockaddr*)&local, sizeof(local) ) == SOCKET_ERROR)
{
fprintfId( stderr , "bind failed: %s\n" , LastSocketError());
closesocket(listenSocket);
return INVALID_SOCKET;
}
if ( listen( listenSocket, SOMAXCONN ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at listen(): %s\n" , LastSocketError() );
closesocket(listenSocket);
return INVALID_SOCKET;
}
int len=sizeof(local);
if(getsockname(listenSocket,(struct sockaddr*)&local,&len) == SOCKET_ERROR)
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
closesocket(listenSocket);
return INVALID_SOCKET;
}
port=int(ntohs(local.sin_port));
return listenSocket;
}
void CloseSocket( SOCKET& s )
{
#if STORE_CONNECTION_TABLE
if( s!=INVALID_SOCKET )
{
MyWinSock::SystemLock lock;
MyWinSock::ConnectionTable.erase( s );
}
#endif // STORE_CONNECTION_TABLE
if( s!=INVALID_SOCKET ) closesocket( s );
s = INVALID_SOCKET;
}
int inet_aton(const char *cp, struct in_addr *inp)
{
unsigned int a = 0, b = 0, c = 0, d = 0;
int n = 0, r;
unsigned long int addr = 0;
r = sscanf(cp, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n);
if (r == 0 || n == 0) return 0;
cp += n;
if (*cp) return 0;
if (a > 255 || b > 255 || c > 255 || d > 255) return 0;
if (inp) {
addr += a; addr <<= 8;
addr += b; addr <<= 8;
addr += c; addr <<= 8;
addr += d;
inp->s_addr = htonl(addr);
}
return 1;
}
static const char *wstrerror(int err)
{
switch (err)
{
case WSAEINTR: return "Interrupted function call";
case WSAEACCES: return "Permission denied";
case WSAEFAULT: return "Bad address";
case WSAEINVAL: return "Invalid argument";
case WSAEMFILE: return "Too many open files";
case WSAEWOULDBLOCK: return "Resource temporarily unavailable";
case WSAEINPROGRESS: return "Operation now in progress";
case WSAEALREADY: return "Operation already in progress";
case WSAENOTSOCK: return "Socket operation on nonsocket";
case WSAEDESTADDRREQ: return "Destination address required";
case WSAEMSGSIZE: return "Message too long";
case WSAEPROTOTYPE: return "Protocol wrong type for socket";
case WSAENOPROTOOPT: return "Bad protocol option";
case WSAEPROTONOSUPPORT: return "Protocol not supported";
case WSAESOCKTNOSUPPORT: return "Socket type not supported";
case WSAEOPNOTSUPP: return "Operation not supported";
case WSAEPFNOSUPPORT: return "Protocol family not supported";
case WSAEAFNOSUPPORT: return "Address family not supported by protocol family";
case WSAEADDRINUSE: return "Address already in use";
case WSAEADDRNOTAVAIL: return "Cannot assign requested address";
case WSAENETDOWN: return "Network is down";
case WSAENETUNREACH: return "Network is unreachable";
case WSAENETRESET: return "Network dropped connection on reset";
case WSAECONNABORTED: return "Software caused connection abort";
case WSAECONNRESET: return "Connection reset by peer";
case WSAENOBUFS: return "No buffer space available";
case WSAEISCONN: return "Socket is already connected";
case WSAENOTCONN: return "Socket is not connected";
case WSAESHUTDOWN: return "Cannot send after socket shutdown";
case WSAETIMEDOUT: return "Connection timed out";
case WSAECONNREFUSED: return "Connection refused";
case WSAEHOSTDOWN: return "Host is down";
case WSAEHOSTUNREACH: return "No route to host";
case WSAEPROCLIM: return "Too many processes";
case WSASYSNOTREADY: return "Network subsystem is unavailable";
case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range";
case WSANOTINITIALISED: return "Successful WSAStartup not yet performed";
case WSAEDISCON: return "Graceful shutdown in progress";
case WSAHOST_NOT_FOUND: return "Host not found";
case WSATRY_AGAIN: return "Nonauthoritative host not found";
case WSANO_RECOVERY: return "Nonrecoverable name lookup error";
case WSANO_DATA: return "Valid name, no data record of requested type";
default: return "Unknown error";
}
}
//static const char* LastSocketError(void) { return wstrerror( WSAGetLastError() ); }
const char* LastSocketError(void) { return wstrerror( WSAGetLastError() ); }
///////////////////////////
// DataStreamConstructor //
///////////////////////////
DataStreamConstructor::DataStreamConstructor( void )
{
_sock = INVALID_SOCKET;
_stream = NULL;
char address[512];
_myPID = GetCurrentProcessId( );
GetHostAddress( address );
inet_aton( address, &_myAddr );
}
void DataStreamConstructor::init( SOCKET sock , bool master , bool cleanUp )
{
_sock = sock;
_master = master;
_cleanUp = cleanUp;
}
DataStream* DataStreamConstructor::getDataStream( void ) { return _stream; }
void DataStreamConstructor::doStep( int sNum )
{
switch( sNum )
{
case 0:
if( !_master )
{
SendOnSocket( _sock , GetPointer(_myAddr) , sizeof(_myAddr) );
SendOnSocket( _sock , GetPointer(_myPID ) , sizeof(_myPID) );
}
break;
case 1:
if( _master )
{
in_addr addr;
int pid;
ReceiveOnSocket( _sock , GetPointer(addr) , sizeof(addr) );
ReceiveOnSocket( _sock , GetPointer(pid ) , sizeof(pid) );
if( _myAddr.s_addr == addr.s_addr && _myPID == pid )
{
SharedMemoryBuffer::StreamPair sPair;
SharedMemoryBuffer::StreamPair::CreateSharedBufferPair( sPair );
SendOnSocket( _sock , GetPointer(sPair.second) , sizeof( sPair.second ) );
_stream = sPair.first;
if( _cleanUp ) CloseSocket( _sock );
}
else
{
SharedMemoryBuffer::SecondStream* sStream = NULL;
SendOnSocket( _sock , GetPointer(sStream) , sizeof( sStream ) );
_stream = new Socket( _sock );
}
}
break;
case 2:
if( !_master )
{
SharedMemoryBuffer::SecondStream* sStream;
ReceiveOnSocket( _sock , GetPointer(sStream) , sizeof( sStream ) );
if( sStream )
{
if( _cleanUp ) CloseSocket( _sock );
_stream = sStream;
}
else _stream = new Socket( _sock );
}
break;
}
}
////////////////
// DataStream //
////////////////
DataStream* DataStream::GetDataStream( SOCKET sock , bool master , bool cleanUp )
{
char address[512];
in_addr myAddr , addr;
int pid , myPID = GetCurrentProcessId( );
GetHostAddress( address );
inet_aton( address, &myAddr );
if( master )
{
ReceiveOnSocket( sock , GetPointer(addr) , sizeof(addr) );
ReceiveOnSocket( sock , GetPointer(pid ) , sizeof(pid) );
if( myAddr.s_addr == addr.s_addr && myPID == pid )
{
SharedMemoryBuffer::StreamPair sPair;
SharedMemoryBuffer::StreamPair::CreateSharedBufferPair( sPair );
SendOnSocket( sock , GetPointer(sPair.second) , sizeof( sPair.second ) );
if( cleanUp ) CloseSocket( sock );
return sPair.first;
}
else
{
SharedMemoryBuffer::SecondStream* sStream = NULL;
SendOnSocket( sock , GetPointer(sStream) , sizeof( sStream ) );
return new Socket( sock );
}
}
else
{
SendOnSocket( sock , GetPointer(myAddr) , sizeof(myAddr) );
SendOnSocket( sock , GetPointer(myPID ) , sizeof(myPID) );
SharedMemoryBuffer::SecondStream* sStream;
ReceiveOnSocket( sock , GetPointer(sStream) , sizeof( sStream ) );
if( sStream )
{
if( cleanUp ) CloseSocket( sock );
return sStream;
}
else return new Socket( sock );
}
}
////////////
// Socket //
////////////
Socket::Socket( SOCKET sock ) { _sock = sock; _mySocket = false; }
Socket::Socket( const char* address , int port , int ms , bool progress )
{
_sock = GetConnectSocket( address , port , ms , progress );
_mySocket = true;
}
Socket::Socket( in_addr address , int port , int ms , bool progress )
{
_sock = GetConnectSocket( address , port , ms , progress );
_mySocket = true;
}
Socket::~Socket( void ) { if( _mySocket ) CloseSocket( _sock); }
bool Socket::write( ConstPointer( byte ) buf , int len ) { return SendOnSocket ( _sock , buf , len ); }
bool Socket::read ( Pointer( byte ) buf , int len ){ return ReceiveOnSocket( _sock , buf , len ); }
////////////////////////
// SharedMemoryBuffer //
////////////////////////
SharedMemoryBuffer::SharedMemoryBuffer( void )
{
_buf1 = NullPointer< byte >( );
_buf2 = NullPointer< byte >( );
_bufSize1 = _bufSize2 = 0;
_loadHandle1 = CreateEvent( NULL , false , false , NULL );
_loadHandle2 = CreateEvent( NULL , false , false , NULL );
_unloadHandle1 = CreateEvent( NULL , false , true , NULL );
_unloadHandle2 = CreateEvent( NULL , false , true , NULL );
}
SharedMemoryBuffer::~SharedMemoryBuffer( void )
{
FreeArray( _buf1 ) , _bufSize1 = 0;
FreeArray( _buf2 ) , _bufSize2 = 0;
CloseHandle( _loadHandle1 ) , _loadHandle1 = NULL;
CloseHandle( _loadHandle2 ) , _loadHandle2 = NULL;
CloseHandle( _unloadHandle1 ) , _unloadHandle1 = NULL;
CloseHandle( _unloadHandle2 ) , _unloadHandle2 = NULL;
}
SharedMemoryBuffer::FirstStream::FirstStream ( SharedMemoryBuffer* smb ) { _smb = smb; }
SharedMemoryBuffer::SecondStream::SecondStream( SharedMemoryBuffer* smb ) { _smb = smb; }
SharedMemoryBuffer::FirstStream::~FirstStream ( void ) { if( _smb ) delete _smb , _smb = NULL; }
SharedMemoryBuffer::SecondStream::~SecondStream( void ) { _smb = NULL; }
// The first stream reads on buf1 and writes on buf2
bool SharedMemoryBuffer::FirstStream::read( Pointer( byte ) buf , int len )
{
if( WaitForSingleObject( _smb->_loadHandle1 , INFINITE ) != WAIT_OBJECT_0 ) fprintfId( stderr , "Wait for single failed: " ) , PrintError();
if( len>_smb->_bufSize1 )
{
printf( "Uh oh 1\n" ) , fflush( stdout );
return false;
}
memcpy( buf , _smb->_buf1 , len );
SetEvent( _smb->_unloadHandle1 );
return true;
}
bool SharedMemoryBuffer::FirstStream::write( ConstPointer( byte ) buf , int len )
{
if( WaitForSingleObject( _smb->_unloadHandle2 , INFINITE ) != WAIT_OBJECT_0 ) fprintfId( stderr , "Wait for single failed: " ) , PrintError();
if( len>_smb->_bufSize2 )
{
FreeArray( _smb->_buf2 );
_smb->_bufSize2 = 0;
_smb->_buf2 = AllocArray< byte >( len , 1 , "SharedMemoryBuffer::FirstStream::write (_smb->_buf2)" );
if( !_smb->_buf2 )
{
printf( "Uh oh 2\n" ) , fflush( stdout );
return false;
}
_smb->_bufSize2 = len;
}
memcpy( _smb->_buf2 , buf , len );
SetEvent( _smb->_loadHandle2 );
return true;
}
bool SharedMemoryBuffer::SecondStream::read( Pointer( byte ) buf , int len )
{
if( WaitForSingleObject( _smb->_loadHandle2 , INFINITE ) != WAIT_OBJECT_0 ) fprintfId( stderr , "Wait for single failed: " ) , PrintError();
if( len>_smb->_bufSize2 )
{
printf( "Uh oh 3\n" ) , fflush( stdout );
return false;
}
memcpy( buf , _smb->_buf2 , len );
SetEvent( _smb->_unloadHandle2 );
return true;
}
bool SharedMemoryBuffer::SecondStream::write( ConstPointer( byte ) buf , int len )
{
if( WaitForSingleObject( _smb->_unloadHandle1 , INFINITE ) != WAIT_OBJECT_0 ) fprintfId( stderr , "Wait for single failed: " ) , PrintError();
if( len>_smb->_bufSize1 )
{
FreeArray( _smb->_buf1 );
_smb->_bufSize1 = 0;
_smb->_buf1 = AllocArray< byte >( len , 1 , "SharedMemoryBuffer::SecondStream::write (_smb->_buf1)" );
if( !_smb->_buf1 )
{
printf( "Uh oh 4\n" ) , fflush( stdout );
return false;
}
_smb->_bufSize1 = len;
}
memcpy( _smb->_buf1 , buf , len );
SetEvent( _smb->_loadHandle1 );
return true;
}
bool SharedMemoryBuffer::StreamPair::CreateSharedBufferPair( StreamPair& pair )
{
SharedMemoryBuffer* smb = new SharedMemoryBuffer( );
pair.first = new SharedMemoryBuffer::FirstStream ( smb );
pair.second = new SharedMemoryBuffer::SecondStream( smb );
if( !pair.first || !pair.second )
{
fprintf( stderr , "Failed to create shared buffer pair\n" );
return false;
}
return true;
}
SharedMemoryBuffer::StreamPair::StreamPair( void )
{
first = NULL;
second = NULL;
}
| [
"luc.deschenaux@freesurf.ch"
] | luc.deschenaux@freesurf.ch |
99dd3e134bcd8195c630cd63bfc6fcff87c543c2 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-networkmanager/source/model/DisassociateCustomerGatewayRequest.cpp | 4efe4b511fa98be672f358814b63b0f386e09290 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 628 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/networkmanager/model/DisassociateCustomerGatewayRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::NetworkManager::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DisassociateCustomerGatewayRequest::DisassociateCustomerGatewayRequest() :
m_globalNetworkIdHasBeenSet(false),
m_customerGatewayArnHasBeenSet(false)
{
}
Aws::String DisassociateCustomerGatewayRequest::SerializePayload() const
{
return {};
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
1347f8d6ffe50fbb53937df29c2e8c2c428c4733 | 1af1f8f18ef5b8e2218133f20aac1bbd0060ec55 | /CSound Manager/CSound/CSoundComponent.h | 0ad0c67a44c5cb346aeefe1e716a51c2bc479935 | [] | no_license | ReDEnergy/3DSound-Prototypying | c589ba3a13b2a2bb7cd458faec0b4b1db1e969dc | 9e7c2daa09739460bd634f977d2f95f918ec338a | refs/heads/master | 2021-01-10T16:15:52.761219 | 2017-07-03T19:57:17 | 2017-07-03T19:57:17 | 49,384,240 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | h | #pragma once
#include <vector>
#include <CSound/CSoundEntity.h>
#include <CSound/CSoundForward.h>
#include <CSound/CSoundComponentProperty.h>
#include <CSound/Templates/CSoundList.h>
class DLLExport CSoundComponent
: public CSoundEntity
, public CSoundList<CSoundComponentProperty, CSoundComponent>
{
public:
CSoundComponent();
CSoundComponent(const CSoundComponent &Comp);
~CSoundComponent();
void Update();
void InitControlChannels();
void AddControlChannel(const char* channel);
const std::vector<std::string>& GetControlChannels() const;
void SetParent(CSoundInstrument *instrument);
void SetParent(CSoundInstrumentBlock *instrument) {};
private:
CSoundInstrument *parent;
std::vector<std::string> controlChannels;
std::vector<std::string> controls;
};
| [
"gabriel.ivanica@gmail.com"
] | gabriel.ivanica@gmail.com |
4179c5a6a547b10dc36bd13fb2c3ece17ff8a315 | 82bba04be05e518845b99d749a3293668725e9e7 | /QHG3/common/PolyLine.h | 5cdaac7b1170fd4424fb64bb0653d1e25bc4ac17 | [] | no_license | Achandroth/QHG | e914618776f38ed765da3f9c64ec62b983fc3df3 | 7e64d82dc3b798a05f2a725da4286621d2ba9241 | refs/heads/master | 2023-06-04T06:24:41.078369 | 2018-07-04T11:01:08 | 2018-07-04T11:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | h | /*============================================================================
| PolyLine
|
| representation of a piecewise linear function
|
| Author: Jody Weissmann
\===========================================================================*/
#ifndef __POLYLINE_H__
#define __POLYLINE_H__
#include <vector>
#include <stdio.h>
#include "zlib.h"
class PolyLine {
public:
PolyLine(unsigned int iNumSegments);
PolyLine(PolyLine *pPL);
~PolyLine();
void addPoint(unsigned int i, double fX, double fV) {
m_afX[i] = fX;
m_afV[i] = fV;
if (i > 0) {
m_afA[i-1] = (m_afV[i] - m_afV[i-1])/(m_afX[i] - m_afX[i-1]);
}
}
double getVal(double fX);
void write(FILE *fOut);
void display(const char *pIndent, const char *pCaption);
static PolyLine *readFromString(const char *pData);
unsigned int m_iNumSegments;
double *m_afX;
double *m_afV;
double *m_afA;
};
#endif
| [
"jody@aim.uzh.ch"
] | jody@aim.uzh.ch |
88acb98f2abdaf02ec07fc34165a6637d154f116 | 948a6bbb8ef60a97c4350bf1fbccbc972bbfcb4f | /thirdparty/Indy10/C18/Win32/Release/IdSASL_CRAMBase.hpp | c90708b74a4536c49d46173c6c250099116d99ee | [] | no_license | hotsoft/components | 504c6935b892c74796a8cbec91736185507ed149 | 2d41768ff68c0c6535a1ee40f3e8abc90cb19c9b | refs/heads/master | 2023-09-03T22:46:13.153273 | 2023-08-18T13:16:19 | 2023-08-18T13:16:19 | 14,142,719 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,466 | hpp | // CodeGear C++Builder
// Copyright (c) 1995, 2013 by Embarcadero Technologies, Inc.
// All rights reserved
// (DO NOT EDIT: machine generated header) 'IdSASL_CRAMBase.pas' rev: 25.00 (Windows)
#ifndef Idsasl_crambaseHPP
#define Idsasl_crambaseHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <IdHMACSHA1.hpp> // Pascal unit
#include <IdSASL.hpp> // Pascal unit
#include <IdSASLUserPass.hpp> // Pascal unit
#include <IdBaseComponent.hpp> // Pascal unit
#include <System.Classes.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Idsasl_crambase
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TIdSASLCRAMBase;
#pragma pack(push,4)
class PASCALIMPLEMENTATION TIdSASLCRAMBase : public Idsasluserpass::TIdSASLUserPass
{
typedef Idsasluserpass::TIdSASLUserPass inherited;
public:
__classmethod virtual System::UnicodeString __fastcall BuildKeydAuth(const System::UnicodeString APassword, const System::UnicodeString AChallenge);
virtual System::UnicodeString __fastcall StartAuthenticate(const System::UnicodeString AChallenge, const System::UnicodeString AHost, const System::UnicodeString AProtocolName);
virtual System::UnicodeString __fastcall ContinueAuthenticate(const System::UnicodeString ALastResponse, const System::UnicodeString AHost, const System::UnicodeString AProtocolName);
public:
/* TIdSASL.Destroy */ inline __fastcall virtual ~TIdSASLCRAMBase(void) { }
public:
/* TIdBaseComponent.Create */ inline __fastcall TIdSASLCRAMBase(System::Classes::TComponent* AOwner)/* overload */ : Idsasluserpass::TIdSASLUserPass(AOwner) { }
public:
/* TIdInitializerComponent.Create */ inline __fastcall TIdSASLCRAMBase(void)/* overload */ : Idsasluserpass::TIdSASLUserPass() { }
};
#pragma pack(pop)
//-- var, const, procedure ---------------------------------------------------
} /* namespace Idsasl_crambase */
#if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_IDSASL_CRAMBASE)
using namespace Idsasl_crambase;
#endif
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // Idsasl_crambaseHPP
| [
"desenv7@labplus.com.br"
] | desenv7@labplus.com.br |
2684fbb6d34fc189b3ebd26e490a26db85da0658 | 8cc6d6f590285ef00e0f30e0151c4d407847b651 | /build_test/windows-build/Sources/include/kha/Resource.h | 469d20cbde6723c63ce05f3a900bd23936d2c707 | [] | no_license | piboistudios/ArmoryDeformIssues | e087d5097af74f958fd89dd8dd17ca57627bf6d1 | 84e8b14c5098a4a4db310c5177c5dcd46f40212d | refs/heads/master | 2020-03-24T11:42:11.270376 | 2018-07-28T16:33:45 | 2018-07-28T16:33:45 | 142,692,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 582 | h | // Generated by Haxe 3.4.4 (git build master @ 99b08bb)
#ifndef INCLUDED_kha_Resource
#define INCLUDED_kha_Resource
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS1(kha,Resource)
namespace kha{
class HXCPP_CLASS_ATTRIBUTES Resource_obj {
public:
typedef hx::Object super;
HX_DO_INTERFACE_RTTI;
void (hx::Object :: *_hx_unload)();
static inline void unload( ::Dynamic _hx_) {
(_hx_.mPtr->*( static_cast< ::kha::Resource_obj *>(_hx_.mPtr->_hx_getInterface(0xf962acd2)))->_hx_unload)();
}
};
} // end namespace kha
#endif /* INCLUDED_kha_Resource */
| [
"gabriel.speed.bullock@gmail.com"
] | gabriel.speed.bullock@gmail.com |
55b45ca44eec1e742434e575279ceafe49bec09b | e2d8baee41d39d078aa4c866f11e3f70b006407b | /XMLlib/SRC/XMLNameSpace.h | 1fdaa702004e1c5e33bb9448ae97f06052129218 | [] | no_license | b-swat/XML | 0a909827f39d7e8e4e28367b464392a6069ce5fa | 9e0d5f161cd0a55090e90cf41000683cb4c79bd4 | refs/heads/master | 2021-09-27T19:51:50.621381 | 2018-11-11T03:05:41 | 2018-11-11T03:05:41 | 143,589,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | h | #pragma once
#include <vector>
#include "../stdafx.h"
#include "XMLNode.h"
#include "XMLString.h"
namespace XML
{
class XMLNameSpace
{
char m_quote;
XMLString m_name;
XMLString m_path;
public:
XMLNode *nodeOwner;
XMLNameSpace(XMLString &_name, XMLString &_path, char _quote);
~XMLNameSpace();
std::wstring toWString();
XMLString* getFullName();
XMLString* getPath();
std::wstring getName();
};
}
| [
"work@ELIS"
] | work@ELIS |
89ba0fa00df3fdb92accdec1a870195cc8a5f302 | 5568848932432e0b913c8052ada26a56620525ac | /tensorflow/core/kernels/sparse_xent_op.h | cf28d4a07ef49e94c126847e334b940ec414c12e | [
"Apache-2.0"
] | permissive | agouwin/udacity_deep_learning_homework | 96eb49b99817bd050e4d011f2aad84e9eefb6e36 | bbfa69be8685a5070c4a97d50e94bd4b37c5ce44 | refs/heads/master | 2022-12-25T07:15:27.941679 | 2016-03-06T18:38:46 | 2016-03-06T18:38:46 | 52,696,105 | 0 | 0 | Apache-2.0 | 2022-12-14T18:17:08 | 2016-02-28T00:34:23 | C++ | UTF-8 | C++ | false | false | 7,702 | h | /* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_KERNELS_XENT_OP_H_
#define TENSORFLOW_KERNELS_XENT_OP_H_
// Functor definition for SparseXentOp, must be compilable by nvcc.
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace sparse_xent_helpers {
template <typename T>
typename TTypes<const T, 1>::Tensor32Bit To32BitConst(
typename TTypes<T>::Vec in) {
return To32Bit(typename TTypes<T>::ConstVec(in.data(), in.dimensions()));
}
template <typename T>
typename TTypes<const T, 2>::Tensor32Bit To32BitConst(
typename TTypes<T>::Matrix in) {
return To32Bit(typename TTypes<T>::ConstMatrix(in.data(), in.dimensions()));
}
} // namespace sparse_xent_helpers
namespace generator {
// Generator for calculation of the sparse Xent loss.
// This generator takes the logits, the sum of the exponentiated
// logits, and the label indices. For each minibatch entry, ignoring
// the batch index b, it calculates:
//
// loss[j] = (log(sum_exp_logits) - logits[j]) * 1{ j == label }
//
// for j = 0 .. num_classes. This value must be summed over all j for
// the final loss.
template <typename T>
class SparseXentLossGenerator {
public:
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE SparseXentLossGenerator(
typename TTypes<const T, 2>::Tensor32Bit logits,
typename TTypes<const T, 1>::Tensor32Bit sum_exp_logits,
TTypes<const int64, 1>::Tensor32Bit labels)
: logits_(logits), sum_exp_logits_(sum_exp_logits), labels_(labels) {}
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T
operator()(const Eigen::array<int, 2>& coords) const {
int batch = coords[0];
int depth = coords[1];
return (labels_(batch) == depth)
? (std::log(sum_exp_logits_(batch)) - logits_(coords))
: T(0.0);
};
private:
typename TTypes<const T, 2>::Tensor32Bit logits_;
typename TTypes<const T, 1>::Tensor32Bit sum_exp_logits_;
TTypes<const int64, 1>::Tensor32Bit labels_;
};
// Generator for calculation of the sparse Xent gradient.
// This generator takes the logits, the sum of the exponentiated
// logits, and the label indices. For each minibatch entry, ignoring
// the batch index b, it calculates:
//
// exp(logits[j]) / sum_exp_logits - 1{ j == label }
//
// for j = 0 .. num_classes.
template <typename T>
class SparseXentGradGenerator {
public:
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE SparseXentGradGenerator(
typename TTypes<const T, 2>::Tensor32Bit logits,
typename TTypes<const T, 1>::Tensor32Bit sum_exp_logits,
TTypes<const int64, 1>::Tensor32Bit labels)
: logits_(logits), sum_exp_logits_(sum_exp_logits), labels_(labels) {}
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T
operator()(const Eigen::array<int, 2>& coords) const {
int batch = coords[0];
int depth = coords[1];
T subtract = (depth == labels_(batch)) ? T(1.0) : T(0.0);
return std::exp(logits_(coords)) / sum_exp_logits_(batch) - subtract;
};
private:
typename TTypes<const T, 2>::Tensor32Bit logits_;
typename TTypes<const T, 1>::Tensor32Bit sum_exp_logits_;
TTypes<const int64, 1>::Tensor32Bit labels_;
};
} // namespace generator
namespace functor {
// Functor used by SparseXentOp to do the computations.
template <typename Device, typename T>
struct SparseXentFunctor {
// Computes Cross Entropy loss and backprop.
//
// logits: batch_size, num_classes.
// labels: num_classes.
// scratch: temporary tensor, dims: batch_size, 1
// loss: output tensor for the loss, dims: batch_size.
// backprop: output tensor for the backprop, dims: batch_size, num_classes.
void operator()(const Device& d, typename TTypes<T>::ConstMatrix logits,
typename TTypes<int64>::ConstVec labels,
typename TTypes<T>::Vec scratch, typename TTypes<T>::Vec loss,
typename TTypes<T>::Matrix backprop);
};
// Eigen code implementing SparseXentFunctor::operator().
// This code works for both CPU and GPU and is used by the functor
// specializations for both device types.
template <typename Device, typename T>
struct SparseXentEigenImpl {
static void Compute(const Device& d, typename TTypes<T>::ConstMatrix logits,
typename TTypes<int64>::ConstVec labels,
typename TTypes<T>::Vec scratch,
typename TTypes<T>::Vec loss,
typename TTypes<T>::Matrix backprop) {
// NOTE(touts): This duplicates some of the computations in softmax_op
// because we need the intermediate (logits -max(logits)) values to
// avoid a log(exp()) in the computation of the loss.
const int kBatchDim = 0;
const int kClassDim = 1;
const int batch_size = logits.dimension(kBatchDim);
const int num_classes = logits.dimension(kClassDim);
// These arrays are used to reduce along the class dimension, and broadcast
// the resulting value to all classes.
#if !defined(EIGEN_HAS_INDEX_LIST)
Eigen::array<int, 1> along_class;
along_class[0] = kClassDim;
Eigen::array<int, 1> batch_only;
batch_only[0] = batch_size;
Eigen::array<int, 2> batch_by_one;
batch_by_one[0] = batch_size;
batch_by_one[1] = 1;
Eigen::array<int, 2> one_by_class;
one_by_class[0] = 1;
one_by_class[1] = num_classes;
#else
Eigen::IndexList<Eigen::type2index<kClassDim> > along_class;
Eigen::IndexList<int, Eigen::type2index<1> > batch_by_one;
batch_by_one.set(0, batch_size);
Eigen::IndexList<int> batch_only;
batch_only.set(0, batch_size);
Eigen::IndexList<Eigen::type2index<1>, int> one_by_class;
one_by_class.set(1, num_classes);
#endif
// scratch = max_logits along classes.
To32Bit(scratch).device(d) = To32Bit(logits).maximum(along_class);
// backprop = logits - max_logits.
To32Bit(backprop).device(d) =
To32Bit(logits) -
To32Bit(scratch).reshape(batch_by_one).broadcast(one_by_class);
// scratch = sum(exp(logits - max_logits)) along classes.
To32Bit(scratch).device(d) = To32Bit(backprop).exp().sum(along_class);
// sum(-labels *
// ((logits - max_logits) - log(sum(exp(logits - max_logits)))))
// along classes
generator::SparseXentLossGenerator<T> sparse_xent_loss_gen(
sparse_xent_helpers::To32BitConst<T>(backprop),
sparse_xent_helpers::To32BitConst<T>(scratch), To32Bit(labels));
To32Bit(loss).device(d) =
To32Bit(backprop).generate(sparse_xent_loss_gen).sum(along_class);
// backprop: prob - labels, where
// prob = exp(logits - max_logits) / sum(exp(logits - max_logits))
generator::SparseXentGradGenerator<T> sparse_xent_grad_gen(
sparse_xent_helpers::To32BitConst<T>(backprop),
sparse_xent_helpers::To32BitConst<T>(scratch), To32Bit(labels));
To32Bit(backprop).device(d) =
To32Bit(backprop).generate(sparse_xent_grad_gen);
}
};
} // namespace functor
} // namespace tensorflow
#endif // TENSORFLOW_KERNELS_XENT_OP_H_
| [
"vrv@google.com"
] | vrv@google.com |
943f8e268e15c88c2b00eac0c9a41ee547ebae28 | 8934affdf9942be1ad55c40833e32d630b0712a7 | /LumenEngine-core/Material.cpp | 7f285d1bb37c982fc9a340c576b944044e4c5a3b | [] | no_license | wyattjhammond/LumenEngine | 0a665dee203f5138069ae2a7d04ded8117652b9e | 62572114fad82c2364e6e90d5b0881577dc39b41 | refs/heads/master | 2021-06-17T22:50:48.663676 | 2017-06-27T14:24:09 | 2017-06-27T14:24:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | cpp | #include "Material.h"
Material::Material(unsigned numOfShaders, const char ** shaders)
{
m_numOfShaders = numOfShaders;
m_shaderPaths = new char*[numOfShaders];
for (unsigned i = 0; i < numOfShaders; ++i) {
unsigned len = strlen(shaders[i]) + 1;
m_shaderPaths[i] = new char[len];
strcpy_s(m_shaderPaths[i], len, shaders[i]);
}
}
Material::Material(unsigned numOfShaders, std::string * shaders)
{
m_numOfShaders = numOfShaders;
m_shaderPaths = new char*[numOfShaders];
for (unsigned i = 0; i < numOfShaders; ++i) {
unsigned len = shaders[i].length() + 1;
m_shaderPaths[i] = new char[len];
strcpy_s(m_shaderPaths[i], len, shaders[i].c_str());
}
}
Material::~Material()
{
for (unsigned i = 0; i < m_numOfShaders; ++i)
delete[] m_shaderPaths[i];
delete[] m_shaderPaths;
}
| [
"stonegrump@gmail.com"
] | stonegrump@gmail.com |
a7b19ca098742591ab146cc560787106cdb43e2b | 841322eddd57db0b12f6abd685dd399f28be0c68 | /qt_creator_basic/4/build-4_3_myBuddy-Desktop_Qt_5_10_1_MinGW_32bit-Debug/debug/moc_mywidget.cpp | 22b8099f0f4a9b3e3196daed93939698f8c0d474 | [] | no_license | cat1984x/Learning_Qt | c52e030850d254b4a5541968d86c56b5cdf504f7 | 4deaa4e86112c263f5421d2f91b0ba1ca14e482a | refs/heads/master | 2022-01-08T10:24:08.201942 | 2018-05-02T07:19:03 | 2018-05-02T07:19:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,604 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mywidget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../4_3_myBuddy/mywidget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mywidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.10.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MyWidget_t {
QByteArrayData data[1];
char stringdata0[9];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MyWidget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MyWidget_t qt_meta_stringdata_MyWidget = {
{
QT_MOC_LITERAL(0, 0, 8) // "MyWidget"
},
"MyWidget"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MyWidget[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MyWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject MyWidget::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_MyWidget.data,
qt_meta_data_MyWidget, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *MyWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MyWidget::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MyWidget.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int MyWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"chenyushen1989@gmail.com"
] | chenyushen1989@gmail.com |
ec3704a1b8734cc7aeeecf7a901e39d017d005e0 | 1cbb4b9f4cf513846622d4124588f50347e22eac | /CPP-Programming/week07/assignment/string_op.cpp | c8d7519b03daf7fc0bb713feedf659dd88b193b5 | [] | no_license | googed/coursera-Foundamentals-of-Programming-and-Algorithms | 51831718bebf7cc94aadc80e9ca1339ac06c07f8 | edc394a9d67cb1300c30eef513a588f12a7eea22 | refs/heads/master | 2021-01-15T22:51:37.054239 | 2017-02-26T18:20:14 | 2017-02-26T18:20:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,404 | cpp | #include <iostream>
#include <string>
#include <stdlib.h>
#include <cstdio>
using namespace std;
const int kMaxNum = 20;
string str[kMaxNum];
int number = 0;
char* strItoa = new char[101];
int GotNXL();
string GotS();
string copy();
string add();
int find();
int rfind();
void insert();
void reset();
void print();
void printall();
int GotNXL() {
string NXL;
int nxl;
cin >> NXL;
if (NXL == "find")
nxl = find();
else if (NXL == "rfind")
nxl = rfind();
else
nxl = atoi(NXL.c_str());
return nxl;
}
string GotS() {
string S, result;
cin >> S;
result = S;
if (S == "add")
result = add();
else if (S == "copy")
result = copy();
return result;
}
string copy() {
string result;
int n, x, l;
n = GotNXL();
x = GotNXL();
l = GotNXL();
result = str[n - 1].substr(x, l);
return result;
}
string add() {
string S1, S2;
S1 = GotS();
S2 = GotS();
for (int i = 0; i < S1.size(); i++)
{
if (S1.at(i) < '0' || S1.at(i) > '9')
{
return S1 + S2;
}
}
for (int i = 0; i < S2.size(); i++)
{
if (S2.at(i) < '0' || S2.at(i) > '9')
{
return S1 + S2;
}
}
long a = atoi(S1.c_str());
long b = atoi(S2.c_str());
if (a >= 0 && a <= 99999 && b >= 0 && b <= 99999)
{
long c = a + b;
sprintf(strItoa, "%d", c);
return strItoa;
}
else
return S1 + S2;
}
int find() {
string S;
int n, pos;
S = GotS();
n = GotNXL();
pos = str[n - 1].find(S);
if (pos == string::npos)
return str[n - 1].size();
else
return pos;
}
int rfind() {
string S;
int n, pos;
S = GotS();
n = GotNXL();
pos = str[n - 1].rfind(S);
if (pos == string::npos)
return str[n - 1].size();
else
return pos;
}
void insert() {
string S;
int n, x;
S = GotS();
n = GotNXL();
x = GotNXL();
str[n - 1].insert(x, S);
}
void reset() {
string S;
int n;
S = GotS();
n = GotNXL();
str[n - 1] = S;
}
void print() {
int n;
n = GotNXL();
cout << str[n - 1] << endl;
}
void printall() {
for (int i = 0; i < number; ++i)
cout << str[i] << endl;
}
int main(int argc, char const *argv[])
{
string order;
cin >> number;
for (int i = 0; i < number; ++i)
{
cin >> str[i];
}
while (1) {
cin >> order;
if (order == "over")
break;
else if (order == "insert")
insert();
else if (order == "reset")
reset();
else if (order == "print")
print();
else if (order == "printall")
printall();
else if (order == "insert")
insert();
}
return 0;
} | [
"zipan@paypal.com"
] | zipan@paypal.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.