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
053711ba4b3655172c13c483f96d05360d3ab44f
6679e05cd5edf31142f936883e949a02eb20e317
/src/role.h
d3925de4808ab7ca737c6f642d1ce6e58da7097c
[ "MIT" ]
permissive
DAHeath/emp-ot
e4c8c85bd8184d6b416dc88ebed9e59300ad18f7
711bd92b1a89167abd045667ea060108fcd36ac7
refs/heads/master
2023-05-31T19:14:54.807348
2021-06-17T18:08:40
2021-06-17T18:08:40
258,282,830
0
0
NOASSERTION
2020-04-23T17:37:56
2020-04-23T17:37:55
null
UTF-8
C++
false
false
173
h
#ifndef GT_OT_ROLE_H__ #define GT_OT_ROLE_H__ #include <bitset> enum class OTRole { Sender, Receiver }; enum class OTModel { Malicious, Semihonest }; #endif
[ "heath.davidanthony@gmail.com" ]
heath.davidanthony@gmail.com
b901a9104e0d75a8f56f9c1bde964ee5bdf928fa
4d3400c2ead58e8fc2b25f685c1dbb7a9ce139ff
/service/dedup-blocks/DedupBlocks.h
cf4f2e0226ff8959c85c512082f7628333668c80
[ "MIT" ]
permissive
shining1984/redex
d05ce218c12be191a9b07073164bf1bbc4a24167
bca8ac9e96068ff84ab2a4c53595f7e53b31ec91
refs/heads/master
2022-11-27T22:51:39.059695
2020-08-05T20:22:03
2020-08-05T20:23:36
285,579,899
1
0
MIT
2020-08-06T13:33:12
2020-08-06T13:33:11
null
UTF-8
C++
false
false
1,049
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include "DexClass.h" namespace dedup_blocks_impl { struct Config { std::unordered_set<DexMethod*> method_black_list; static const unsigned int DEFAULT_BLOCK_SPLIT_MIN_OPCODE_COUNT = 1; unsigned int block_split_min_opcode_count = DEFAULT_BLOCK_SPLIT_MIN_OPCODE_COUNT; bool split_postfix = true; bool debug = false; }; struct Stats { int eligible_blocks{0}; int blocks_removed{0}; int blocks_split{0}; // map from block size to number of blocks with that size std::unordered_map<size_t, size_t> dup_sizes; Stats& operator+=(const Stats& that); }; class DedupBlocks { public: DedupBlocks(const Config* config, DexMethod* method); const Stats& get_stats() const { return m_stats; } void run(); private: const Config* m_config; DexMethod* m_method; Stats m_stats; }; } // namespace dedup_blocks_impl
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
5dc0bb3f7bd5eea512f79983560bf2ed56f9c12b
34ca8311d0b2cbd7b83610d2678148d4c1a77e83
/Problem/Code Ground/Practice/연습문제/프로그래밍경진대회.cpp
1d390444aa5a10e383d75af7b18596681d0af084
[]
no_license
kr-MATAGI/Coding-Problem
d3f68c1f331d706b9aa72f2c3b19d6e63ca93f9c
ac76a56eeb25634bec7e37740c83b3b8acec714b
refs/heads/master
2023-03-25T11:06:03.202742
2021-03-28T10:55:45
2021-03-28T10:55:45
226,618,880
1
1
null
null
null
null
UTF-8
C++
false
false
1,313
cpp
#include <iostream> #include <stdio.h> #include <algorithm> #include <vector> int main() { setbuf(stdout, NULL); int testCase = 0; scanf("%d", &testCase); for(int tIdx = 0; tIdx < testCase; tIdx++) { int result = 0; int NCnt = 0; scanf("%d", &NCnt); // SET INPUT std::vector<int> inputList; inputList.reserve(NCnt); for(int nIdx = 0; nIdx < NCnt; nIdx++) { int inputData = 0; scanf("%d", &inputData); inputList.push_back(inputData); } // CACULATION MAX std::sort(inputList.begin(), inputList.end()); std::vector<int> maxCalcList(inputList); int maxValue = -1; for(int nIdx = 0; nIdx < NCnt; nIdx++) { maxCalcList.at(nIdx) = maxCalcList.at(nIdx) + (NCnt - nIdx); if( maxValue < maxCalcList.at(nIdx)) { maxValue = maxCalcList.at(nIdx); } } // CALCULATION RESULT for(int nIdx = 0; nIdx < NCnt; nIdx++) { if( maxValue <= inputList.at(nIdx) + NCnt ) { result++; } } // PRINT RESULT printf("Case #%d\n%d\n", (tIdx+1), result); } return 0; }
[ "dev_matagi@kakao.com" ]
dev_matagi@kakao.com
c11747974e2df3c6aa1d5bbb64a946941de0b373
d7c94f4a713aaf0fbb3dbb9b56c9f6945e0479c1
/URI Online Judge/uri1533.cpp
8c7e3108cc0f267226aa519b7db099f94acbd451
[]
no_license
fonte-nele/Competitive-Programming
2dabb4aab6ce2e6dc552885464fefdd485f9218c
faf0c6077ae0115f121968f7b70f4d68f9ce922b
refs/heads/master
2021-06-28T09:24:07.708562
2020-12-27T14:45:15
2020-12-27T14:45:15
193,268,717
3
0
null
null
null
null
UTF-8
C++
false
false
703
cpp
#include <bits/stdc++.h> int main () { int n; while (1) { scanf("%d", &n); if (n == 0) break; int sus[1050]; memset(sus, 0, sizeof(sus)); int max = 0; int imax; for (int i = 1; i <= n; i++) { int num; scanf("%d", &num); sus[i] = num; if (num > max) { max = num; imax = i; } } int max2 = 0; int imax2; for (int i = 1; i <= n; i++) { if (sus[i] > max2 and imax != i) { max2 = sus[i]; imax2 = i; } } printf("%d\n", imax2); } return 0; }
[ "felipephontinelly@hotmail.com" ]
felipephontinelly@hotmail.com
2dc9a1e3ac93fb87c17b1c1d46cdc377a1b8e31a
a5bb688ef005c0a6e1bfff44e18965e84f78386d
/Source/VRCPP/VRCPPScripts/Objects/Public/VRMovementComponent.h
e3faabcf8013ce821834ebe7f6367c008fd0f628
[]
no_license
PearsonLawrence/VRCPP_Template
8092c42c2c02c03ecc6f4836449d24d29c41f7e5
cca44fc599f18a62bada284d1e2b27417a9d10e2
refs/heads/master
2020-03-23T04:01:17.613681
2019-11-13T04:22:59
2019-11-13T04:22:59
141,061,195
0
0
null
null
null
null
UTF-8
C++
false
false
3,615
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "VRMovementComponent.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class VRCPP_API UVRMovementComponent : public UCharacterMovementComponent { GENERATED_BODY() UVRMovementComponent(); protected: public: //-------------- Teleport Variables --------------// UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Teleport") bool bIsTeleporterActive; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Teleport") bool bIsValidTeleportDestitination; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Teleport") bool bLastFrameValidDestination; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Teleport") FVector TeleportDestination; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Teleport") FRotator TeleportRotation; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Teleport") float TeleportLaunchVelocity; ///////////////////// Functions ////////////////////// //-------------- Base Functions --------------// //-------------- SetDefaults Functions --------------// UFUNCTION(BlueprintCallable, DisplayName = "SetMovementDefaults", Category = "VRCPP Smooth Movement") void SetMovementDefaults(float NewMaxStepHeight, float NewWalkableFloorAngle, float NewGroundFriction, float NewMaxWalkSpeed, float NewBreakingSpeed); //-------------- Teleportation Functions --------------// UFUNCTION(BlueprintCallable, DisplayName = "ActivateTeleporter", Category = "VRCPP Teleportation") void ActivateTeleporterForActor(AActor* Owner, UStaticMeshComponent* RoomScaleMesh = nullptr); UFUNCTION(BlueprintCallable, DisplayName = "DisableTeleporter", Category = "VRCPP Teleportation") void DisableTeleporter(AActor* ActorToTeleport, FVector NewTeleportLocation, FRotator NewTeleportRotation, float TeleportationHeightOffset, bool bAutoActivateTeleport = true, UStaticMeshComponent* TeleportCylinder = nullptr, UStaticMeshComponent* RoomScaleMesh = nullptr); UFUNCTION(BlueprintCallable, DisplayName = "UpdateTeleportationMeshes", Category = "VRCPP Teleportation") void UpdateTeleportationMeshes(FVector NewMeshLocation, FRotator NewMeshRotation, bool bVisibility, UStaticMeshComponent* TeleportCylinder = nullptr, UStaticMeshComponent* RoomScaleMesh = nullptr); UFUNCTION(BlueprintCallable, DisplayName = "TraceTeleportDestination", Category = "VRCPP Teleportation") void TraceTeleportDestination(FVector Start, FVector Direction, ECollisionChannel TraceChannel, bool& OutSuccess, FVector& OutNavMeshLocation, FVector& OutTraceLocation, float TeleportTraceDistance = 500.0f, bool bDrawLineTrace = false, float LineThickness = 1, FColor TraceColor = FColor::Red, bool bChangeLineTraceColorOnHit = false, FColor TraceHitColor = FColor::Green); UFUNCTION(BlueprintCallable, DisplayName = "ExecuteTeleport", Category = "VRCPP Teleportation") void ExecuteTeleport(AActor* ActorToTeleport, FVector NewLocation, FRotator NewRotation, float ZOffset = 0); //-------------- Smooth Movement Functions --------------// UFUNCTION(BlueprintCallable, DisplayName = "CharacterBaseMovement", Category = "VRCPP Smooth Movement") void CharacterBaseMovement(ACharacter* Character, FVector ForwardOrientation, FVector RightOrientation, float XAxisValue, float YAxisValue, float Speed, bool bForce); };
[ "pearson.lawrence.official@gmail.com" ]
pearson.lawrence.official@gmail.com
4dec975062d28c289bf3f33792c7564eda20195d
330a0aef3a41ade80af90ffa1172335736e63843
/src/pg/pg2_optix/structs.h
472a44e7576e17d51d82dda763aa37a77ed7d209
[]
no_license
KNE0035/pg2_optix
97421071141ee621c13d38762228db2cefee98c4
59d16ee6bdafab9bb09807ba3f3e1ea222aecd07
refs/heads/master
2021-07-09T07:28:07.019796
2020-08-07T12:27:05
2020-08-07T12:27:05
174,206,484
0
0
null
null
null
null
UTF-8
C++
false
false
2,818
h
#ifndef STRUCTS #define STRUCTS #pragma once #include "vector3.h" /* a single vertex position structure matching Embree format */ struct Vertex3f { float x, y, z; operator Vector3() const; }; struct Normal3f : public Vertex3f { /*float dot( const Vector3 & v ) const { return x * v.x + y * v.y + z * v.z; }*/ Normal3f( const float x, const float y, const float z ) { this->x = x; this->y = y; this->z = z; } /* reorient the normal vector againt the incoming ray with direction (v_x, v_y, v_z) */ void unify( const float v_x, const float v_y, const float v_z ) { if ( ( x * v_x + y * v_y + z * v_z ) > 0.0f ) { x *= -1.0f; y *= -1.0f; z *= -1.0f; } // !!! always renormalize the normal otherwise bright artifacts at face edges will appear !!! Vector3 n( x, y, z ); n.Normalize(); x = n.x; y = n.y; z = n.z; } Normal3f operator* ( const float a ) const; }; struct Coord2f { float u, v; }; // texture coord structure Coord2f operator+ ( const Coord2f & x, const Coord2f & y ); Coord2f operator- ( const Coord2f & x, const Coord2f & y ); struct Triangle3ui { unsigned int v0, v1, v2; }; // indicies of a single triangle, the struct must match certain format, e.g. RTC_FORMAT_UINT3 inline float c_linear( const float c_srgb, const float gamma = 2.4f ) { if ( c_srgb <= 0.0f ) return 0.0f; else if ( c_srgb >= 1.0f ) return 1.0f; assert( ( c_srgb >= 0.0f ) && ( c_srgb <= 1.0f ) ); if ( c_srgb <= 0.04045f ) { return c_srgb / 12.92f; } else { const float a = 0.055f; return powf( ( c_srgb + a ) / ( 1.0f + a ), gamma ); } } inline float c_srgb( const float c_linear, const float gamma = 2.4f ) { if ( c_linear <= 0.0f ) return 0.0f; else if ( c_linear >= 1.0f ) return 1.0f; assert( ( c_linear >= 0.0f ) && ( c_linear <= 1.0f ) ); if ( c_linear <= 0.0031308f ) { return 12.92f * c_linear; } else { const float a = 0.055f; return ( 1.0f + a ) * powf( c_linear, 1.0f / gamma ) - a; } } struct Color4f; struct Color3f { float r, g, b; Color3f( const float r = 0.0f, const float g = 0.0f, const float b = 0.0f ) : r( r ), g( g ), b( b ) { } operator Color4f() const; Color3f operator* ( const float x ) const; Color3f linear( const float gamma = 2.4f ) const; Color3f srgb( const float gamma = 2.4f ) const; float max_value() const; template<typename T> static Color3f make_from_bgr( BYTE * p ) { return Color3f{ float( ( ( T* )( p ) )[2] ), float( ( ( T* )( p ) )[1] ), float( ( ( T* )( p ) )[0] ) }; } bool is_zero() const; }; Color3f operator+ ( const Color3f & x, const Color3f & y ); Color3f operator* ( const Color3f & x, const Color3f & y ); struct Color4f /*: public Color3f*/ { float r, g, b; float a; // a = 1.0 means that the pixel is fully opaque bool is_valid() const; }; #endif // !STRUCTS
[ "kne0035@vsb.cz" ]
kne0035@vsb.cz
a24026c5b0270e05bd5e6b962c886abea30dc6b5
64e62233f9293269cfdd70ff605d123f0f2c14d1
/src/crypto/sha512.cpp
2e52750441709a68633128a8a4e751143b88695a
[ "MIT" ]
permissive
Zigridar/bitcoin-v-12.1
ab8e801ecaea10710f67e7568af950d118bca943
14a4318fc62f09f6959b23a9858cc8383353282f
refs/heads/master
2020-05-21T15:43:16.405854
2019-07-02T15:12:06
2019-07-02T15:12:06
186,097,926
0
1
MIT
2019-06-26T11:28:54
2019-05-11T06:45:25
C++
UTF-8
C++
false
false
11,006
cpp
// Copyright (c) 2014 The Newcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypto/sha512.h" #include "crypto/common.h" #include <string.h> // Internal implementation code. namespace { /// Internal SHA-512 implementation. namespace sha512 { uint64_t inline Ch(uint64_t x, uint64_t y, uint64_t z) { return z ^ (x & (y ^ z)); } uint64_t inline Maj(uint64_t x, uint64_t y, uint64_t z) { return (x & y) | (z & (x | y)); } uint64_t inline Sigma0(uint64_t x) { return (x >> 28 | x << 36) ^ (x >> 34 | x << 30) ^ (x >> 39 | x << 25); } uint64_t inline Sigma1(uint64_t x) { return (x >> 14 | x << 50) ^ (x >> 18 | x << 46) ^ (x >> 41 | x << 23); } uint64_t inline sigma0(uint64_t x) { return (x >> 1 | x << 63) ^ (x >> 8 | x << 56) ^ (x >> 7); } uint64_t inline sigma1(uint64_t x) { return (x >> 19 | x << 45) ^ (x >> 61 | x << 3) ^ (x >> 6); } /** One round of SHA-512. */ void inline Round(uint64_t a, uint64_t b, uint64_t c, uint64_t& d, uint64_t e, uint64_t f, uint64_t g, uint64_t& h, uint64_t k, uint64_t w) { uint64_t t1 = h + Sigma1(e) + Ch(e, f, g) + k + w; uint64_t t2 = Sigma0(a) + Maj(a, b, c); d += t1; h = t1 + t2; } /** Initialize SHA-256 state. */ void inline Initialize(uint64_t* s) { s[0] = 0x6a09e667f3bcc908ull; s[1] = 0xbb67ae8584caa73bull; s[2] = 0x3c6ef372fe94f82bull; s[3] = 0xa54ff53a5f1d36f1ull; s[4] = 0x510e527fade682d1ull; s[5] = 0x9b05688c2b3e6c1full; s[6] = 0x1f83d9abfb41bd6bull; s[7] = 0x5be0cd19137e2179ull; } /** Perform one SHA-512 transformation, processing a 128-byte chunk. */ void Transform(uint64_t* s, const unsigned char* chunk) { uint64_t a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7]; uint64_t w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15; Round(a, b, c, d, e, f, g, h, 0x428a2f98d728ae22ull, w0 = ReadBE64(chunk + 0)); Round(h, a, b, c, d, e, f, g, 0x7137449123ef65cdull, w1 = ReadBE64(chunk + 8)); Round(g, h, a, b, c, d, e, f, 0xb5c0fbcfec4d3b2full, w2 = ReadBE64(chunk + 16)); Round(f, g, h, a, b, c, d, e, 0xe9b5dba58189dbbcull, w3 = ReadBE64(chunk + 24)); Round(e, f, g, h, a, b, c, d, 0x3956c25bf348b538ull, w4 = ReadBE64(chunk + 32)); Round(d, e, f, g, h, a, b, c, 0x59f111f1b605d019ull, w5 = ReadBE64(chunk + 40)); Round(c, d, e, f, g, h, a, b, 0x923f82a4af194f9bull, w6 = ReadBE64(chunk + 48)); Round(b, c, d, e, f, g, h, a, 0xab1c5ed5da6d8118ull, w7 = ReadBE64(chunk + 56)); Round(a, b, c, d, e, f, g, h, 0xd807aa98a3030242ull, w8 = ReadBE64(chunk + 64)); Round(h, a, b, c, d, e, f, g, 0x12835b0145706fbeull, w9 = ReadBE64(chunk + 72)); Round(g, h, a, b, c, d, e, f, 0x243185be4ee4b28cull, w10 = ReadBE64(chunk + 80)); Round(f, g, h, a, b, c, d, e, 0x550c7dc3d5ffb4e2ull, w11 = ReadBE64(chunk + 88)); Round(e, f, g, h, a, b, c, d, 0x72be5d74f27b896full, w12 = ReadBE64(chunk + 96)); Round(d, e, f, g, h, a, b, c, 0x80deb1fe3b1696b1ull, w13 = ReadBE64(chunk + 104)); Round(c, d, e, f, g, h, a, b, 0x9bdc06a725c71235ull, w14 = ReadBE64(chunk + 112)); Round(b, c, d, e, f, g, h, a, 0xc19bf174cf692694ull, w15 = ReadBE64(chunk + 120)); Round(a, b, c, d, e, f, g, h, 0xe49b69c19ef14ad2ull, w0 += sigma1(w14) + w9 + sigma0(w1)); Round(h, a, b, c, d, e, f, g, 0xefbe4786384f25e3ull, w1 += sigma1(w15) + w10 + sigma0(w2)); Round(g, h, a, b, c, d, e, f, 0x0fc19dc68b8cd5b5ull, w2 += sigma1(w0) + w11 + sigma0(w3)); Round(f, g, h, a, b, c, d, e, 0x240ca1cc77ac9c65ull, w3 += sigma1(w1) + w12 + sigma0(w4)); Round(e, f, g, h, a, b, c, d, 0x2de92c6f592b0275ull, w4 += sigma1(w2) + w13 + sigma0(w5)); Round(d, e, f, g, h, a, b, c, 0x4a7484aa6ea6e483ull, w5 += sigma1(w3) + w14 + sigma0(w6)); Round(c, d, e, f, g, h, a, b, 0x5cb0a9dcbd41fbd4ull, w6 += sigma1(w4) + w15 + sigma0(w7)); Round(b, c, d, e, f, g, h, a, 0x76f988da831153b5ull, w7 += sigma1(w5) + w0 + sigma0(w8)); Round(a, b, c, d, e, f, g, h, 0x983e5152ee66dfabull, w8 += sigma1(w6) + w1 + sigma0(w9)); Round(h, a, b, c, d, e, f, g, 0xa831c66d2db43210ull, w9 += sigma1(w7) + w2 + sigma0(w10)); Round(g, h, a, b, c, d, e, f, 0xb00327c898fb213full, w10 += sigma1(w8) + w3 + sigma0(w11)); Round(f, g, h, a, b, c, d, e, 0xbf597fc7beef0ee4ull, w11 += sigma1(w9) + w4 + sigma0(w12)); Round(e, f, g, h, a, b, c, d, 0xc6e00bf33da88fc2ull, w12 += sigma1(w10) + w5 + sigma0(w13)); Round(d, e, f, g, h, a, b, c, 0xd5a79147930aa725ull, w13 += sigma1(w11) + w6 + sigma0(w14)); Round(c, d, e, f, g, h, a, b, 0x06ca6351e003826full, w14 += sigma1(w12) + w7 + sigma0(w15)); Round(b, c, d, e, f, g, h, a, 0x142929670a0e6e70ull, w15 += sigma1(w13) + w8 + sigma0(w0)); Round(a, b, c, d, e, f, g, h, 0x27b70a8546d22ffcull, w0 += sigma1(w14) + w9 + sigma0(w1)); Round(h, a, b, c, d, e, f, g, 0x2e1b21385c26c926ull, w1 += sigma1(w15) + w10 + sigma0(w2)); Round(g, h, a, b, c, d, e, f, 0x4d2c6dfc5ac42aedull, w2 += sigma1(w0) + w11 + sigma0(w3)); Round(f, g, h, a, b, c, d, e, 0x53380d139d95b3dfull, w3 += sigma1(w1) + w12 + sigma0(w4)); Round(e, f, g, h, a, b, c, d, 0x650a73548baf63deull, w4 += sigma1(w2) + w13 + sigma0(w5)); Round(d, e, f, g, h, a, b, c, 0x766a0abb3c77b2a8ull, w5 += sigma1(w3) + w14 + sigma0(w6)); Round(c, d, e, f, g, h, a, b, 0x81c2c92e47edaee6ull, w6 += sigma1(w4) + w15 + sigma0(w7)); Round(b, c, d, e, f, g, h, a, 0x92722c851482353bull, w7 += sigma1(w5) + w0 + sigma0(w8)); Round(a, b, c, d, e, f, g, h, 0xa2bfe8a14cf10364ull, w8 += sigma1(w6) + w1 + sigma0(w9)); Round(h, a, b, c, d, e, f, g, 0xa81a664bbc423001ull, w9 += sigma1(w7) + w2 + sigma0(w10)); Round(g, h, a, b, c, d, e, f, 0xc24b8b70d0f89791ull, w10 += sigma1(w8) + w3 + sigma0(w11)); Round(f, g, h, a, b, c, d, e, 0xc76c51a30654be30ull, w11 += sigma1(w9) + w4 + sigma0(w12)); Round(e, f, g, h, a, b, c, d, 0xd192e819d6ef5218ull, w12 += sigma1(w10) + w5 + sigma0(w13)); Round(d, e, f, g, h, a, b, c, 0xd69906245565a910ull, w13 += sigma1(w11) + w6 + sigma0(w14)); Round(c, d, e, f, g, h, a, b, 0xf40e35855771202aull, w14 += sigma1(w12) + w7 + sigma0(w15)); Round(b, c, d, e, f, g, h, a, 0x106aa07032bbd1b8ull, w15 += sigma1(w13) + w8 + sigma0(w0)); Round(a, b, c, d, e, f, g, h, 0x19a4c116b8d2d0c8ull, w0 += sigma1(w14) + w9 + sigma0(w1)); Round(h, a, b, c, d, e, f, g, 0x1e376c085141ab53ull, w1 += sigma1(w15) + w10 + sigma0(w2)); Round(g, h, a, b, c, d, e, f, 0x2748774cdf8eeb99ull, w2 += sigma1(w0) + w11 + sigma0(w3)); Round(f, g, h, a, b, c, d, e, 0x34b0bcb5e19b48a8ull, w3 += sigma1(w1) + w12 + sigma0(w4)); Round(e, f, g, h, a, b, c, d, 0x391c0cb3c5c95a63ull, w4 += sigma1(w2) + w13 + sigma0(w5)); Round(d, e, f, g, h, a, b, c, 0x4ed8aa4ae3418acbull, w5 += sigma1(w3) + w14 + sigma0(w6)); Round(c, d, e, f, g, h, a, b, 0x5b9cca4f7763e373ull, w6 += sigma1(w4) + w15 + sigma0(w7)); Round(b, c, d, e, f, g, h, a, 0x682e6ff3d6b2b8a3ull, w7 += sigma1(w5) + w0 + sigma0(w8)); Round(a, b, c, d, e, f, g, h, 0x748f82ee5defb2fcull, w8 += sigma1(w6) + w1 + sigma0(w9)); Round(h, a, b, c, d, e, f, g, 0x78a5636f43172f60ull, w9 += sigma1(w7) + w2 + sigma0(w10)); Round(g, h, a, b, c, d, e, f, 0x84c87814a1f0ab72ull, w10 += sigma1(w8) + w3 + sigma0(w11)); Round(f, g, h, a, b, c, d, e, 0x8cc702081a6439ecull, w11 += sigma1(w9) + w4 + sigma0(w12)); Round(e, f, g, h, a, b, c, d, 0x90befffa23631e28ull, w12 += sigma1(w10) + w5 + sigma0(w13)); Round(d, e, f, g, h, a, b, c, 0xa4506cebde82bde9ull, w13 += sigma1(w11) + w6 + sigma0(w14)); Round(c, d, e, f, g, h, a, b, 0xbef9a3f7b2c67915ull, w14 += sigma1(w12) + w7 + sigma0(w15)); Round(b, c, d, e, f, g, h, a, 0xc67178f2e372532bull, w15 += sigma1(w13) + w8 + sigma0(w0)); Round(a, b, c, d, e, f, g, h, 0xca273eceea26619cull, w0 += sigma1(w14) + w9 + sigma0(w1)); Round(h, a, b, c, d, e, f, g, 0xd186b8c721c0c207ull, w1 += sigma1(w15) + w10 + sigma0(w2)); Round(g, h, a, b, c, d, e, f, 0xeada7dd6cde0eb1eull, w2 += sigma1(w0) + w11 + sigma0(w3)); Round(f, g, h, a, b, c, d, e, 0xf57d4f7fee6ed178ull, w3 += sigma1(w1) + w12 + sigma0(w4)); Round(e, f, g, h, a, b, c, d, 0x06f067aa72176fbaull, w4 += sigma1(w2) + w13 + sigma0(w5)); Round(d, e, f, g, h, a, b, c, 0x0a637dc5a2c898a6ull, w5 += sigma1(w3) + w14 + sigma0(w6)); Round(c, d, e, f, g, h, a, b, 0x113f9804bef90daeull, w6 += sigma1(w4) + w15 + sigma0(w7)); Round(b, c, d, e, f, g, h, a, 0x1b710b35131c471bull, w7 += sigma1(w5) + w0 + sigma0(w8)); Round(a, b, c, d, e, f, g, h, 0x28db77f523047d84ull, w8 += sigma1(w6) + w1 + sigma0(w9)); Round(h, a, b, c, d, e, f, g, 0x32caab7b40c72493ull, w9 += sigma1(w7) + w2 + sigma0(w10)); Round(g, h, a, b, c, d, e, f, 0x3c9ebe0a15c9bebcull, w10 += sigma1(w8) + w3 + sigma0(w11)); Round(f, g, h, a, b, c, d, e, 0x431d67c49c100d4cull, w11 += sigma1(w9) + w4 + sigma0(w12)); Round(e, f, g, h, a, b, c, d, 0x4cc5d4becb3e42b6ull, w12 += sigma1(w10) + w5 + sigma0(w13)); Round(d, e, f, g, h, a, b, c, 0x597f299cfc657e2aull, w13 += sigma1(w11) + w6 + sigma0(w14)); Round(c, d, e, f, g, h, a, b, 0x5fcb6fab3ad6faecull, w14 + sigma1(w12) + w7 + sigma0(w15)); Round(b, c, d, e, f, g, h, a, 0x6c44198c4a475817ull, w15 + sigma1(w13) + w8 + sigma0(w0)); s[0] += a; s[1] += b; s[2] += c; s[3] += d; s[4] += e; s[5] += f; s[6] += g; s[7] += h; } } // namespace sha512 } // namespace ////// SHA-512 CSHA512::CSHA512() : bytes(0) { sha512::Initialize(s); } CSHA512& CSHA512::Write(const unsigned char* data, size_t len) { const unsigned char* end = data + len; size_t bufsize = bytes % 128; if (bufsize && bufsize + len >= 128) { // Fill the buffer, and process it. memcpy(buf + bufsize, data, 128 - bufsize); bytes += 128 - bufsize; data += 128 - bufsize; sha512::Transform(s, buf); bufsize = 0; } while (end >= data + 128) { // Process full chunks directly from the source. sha512::Transform(s, data); data += 128; bytes += 128; } if (end > data) { // Fill the buffer with what remains. memcpy(buf + bufsize, data, end - data); bytes += end - data; } return *this; } void CSHA512::Finalize(unsigned char hash[OUTPUT_SIZE]) { static const unsigned char pad[128] = {0x80}; unsigned char sizedesc[16] = {0x00}; WriteBE64(sizedesc + 8, bytes << 3); Write(pad, 1 + ((239 - (bytes % 128)) % 128)); Write(sizedesc, 16); WriteBE64(hash, s[0]); WriteBE64(hash + 8, s[1]); WriteBE64(hash + 16, s[2]); WriteBE64(hash + 24, s[3]); WriteBE64(hash + 32, s[4]); WriteBE64(hash + 40, s[5]); WriteBE64(hash + 48, s[6]); WriteBE64(hash + 56, s[7]); } CSHA512& CSHA512::Reset() { bytes = 0; sha512::Initialize(s); return *this; }
[ "safonenko.max@yandex.ru" ]
safonenko.max@yandex.ru
45fc5ca7e57f5200aae20faabe683b56d34a064f
82751ca8cd84cf2b2fbac850e33c162e9ec77960
/fish/mbed/LPCExpress/Basic_Serial/Basic_Serial/ros_lib/control_msgs/GripperCommandActionGoal.h
8a093017a22ef8f68045a495deca35bec1d99ffc
[ "MIT" ]
permissive
arizonat/softroboticfish7
c4b1b3a866d42c04f7785088010ba0d6a173dc79
777fd37ff817e131106392a85f65c700198b0197
refs/heads/master
2022-12-13T02:59:16.290695
2022-11-28T21:01:03
2022-11-28T21:01:03
255,442,610
2
0
MIT
2020-04-13T21:11:31
2020-04-13T21:11:30
null
UTF-8
C++
false
false
1,347
h
#ifndef _ROS_control_msgs_GripperCommandActionGoal_h #define _ROS_control_msgs_GripperCommandActionGoal_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "std_msgs/Header.h" #include "actionlib_msgs/GoalID.h" #include "control_msgs/GripperCommandGoal.h" namespace control_msgs { class GripperCommandActionGoal : public ros::Msg { public: std_msgs::Header header; actionlib_msgs::GoalID goal_id; control_msgs::GripperCommandGoal goal; GripperCommandActionGoal(): header(), goal_id(), goal() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->header.serialize(outbuffer + offset); offset += this->goal_id.serialize(outbuffer + offset); offset += this->goal.serialize(outbuffer + offset); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->header.deserialize(inbuffer + offset); offset += this->goal_id.deserialize(inbuffer + offset); offset += this->goal.deserialize(inbuffer + offset); return offset; } const char * getType(){ return "control_msgs/GripperCommandActionGoal"; }; const char * getMD5(){ return "aa581f648a35ed681db2ec0bf7a82bea"; }; }; } #endif
[ "jtwright@mit.edu" ]
jtwright@mit.edu
8f11c9703b6cda08e66310df4eac1f9bea26bfd2
0a88dae66af4391818e91ec37d39b67f4ef186b7
/union_find.cpp
7600e1f130385ea4956a686ba078b4fe897ddd22
[]
no_license
xuhw16/master_coder
61991169106ebef73b58d2da0c627c41bf13142a
e96eb6b5b1f64a48199f69b113288a593f5f9b3b
refs/heads/master
2021-06-20T04:29:13.193044
2019-08-27T13:00:47
2019-08-27T13:00:47
143,100,411
3
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
#include<iostream> #include<vector> #include<cmath> #include<algorithm> #include<string> /* union_find sets: */ using namespace std; int find(vector<int>&s, int x) { if (s[x] < 0) return x; else { return s[x] = find(s, s[x]); } } void union_f(vector<int> & s, int root1, int root2) { if (find(s, root1) == find(s,root2)) return; else { s[root2] = root1; } } int main() { int N,M; cin >> N>>M; vector<int> union_find(N+1, -1); for (int i = 0; i < M; i++) { int a, b; cin >> a >> b; union_f(union_find, a, b); } return 0; }
[ "xuhw16@mails.tsinghua.edu.cn" ]
xuhw16@mails.tsinghua.edu.cn
66f7b9fc7c1943d7e4dd9b43156773b9c05248b2
8dc84558f0058d90dfc4955e905dab1b22d12c08
/components/password_manager/core/browser/password_store_default_unittest.cc
15a5b4322c872de1cbb3aec0b532e86b6d5c71bc
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
10,699
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/password_manager/core/browser/password_store_default.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_task_environment.h" #include "base/time/time.h" #include "components/os_crypt/os_crypt_mocker.h" #include "components/password_manager/core/browser/login_database.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_store_change.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "components/password_manager/core/browser/password_store_origin_unittest.h" #include "components/prefs/pref_service.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using autofill::PasswordForm; using testing::ElementsAre; using testing::ElementsAreArray; using testing::IsEmpty; using testing::_; namespace password_manager { namespace { class MockPasswordStoreConsumer : public PasswordStoreConsumer { public: MOCK_METHOD1(OnGetPasswordStoreResultsConstRef, void(const std::vector<std::unique_ptr<PasswordForm>>&)); // GMock cannot mock methods with move-only args. void OnGetPasswordStoreResults( std::vector<std::unique_ptr<PasswordForm>> results) override { OnGetPasswordStoreResultsConstRef(results); } }; // A mock LoginDatabase that simulates a failing Init() method. class BadLoginDatabase : public LoginDatabase { public: BadLoginDatabase() : LoginDatabase(base::FilePath()) {} ~BadLoginDatabase() override {} // LoginDatabase: bool Init() override { return false; } private: DISALLOW_COPY_AND_ASSIGN(BadLoginDatabase); }; PasswordFormData CreateTestPasswordFormData() { PasswordFormData data = {PasswordForm::SCHEME_HTML, "http://bar.example.com", "http://bar.example.com/origin", "http://bar.example.com/action", L"submit_element", L"username_element", L"password_element", L"username_value", L"password_value", true, 1}; return data; } class PasswordStoreDefaultTestDelegate { public: PasswordStoreDefaultTestDelegate(); explicit PasswordStoreDefaultTestDelegate( std::unique_ptr<LoginDatabase> database); ~PasswordStoreDefaultTestDelegate(); PasswordStoreDefault* store() { return store_.get(); } void FinishAsyncProcessing(); private: void SetupTempDir(); void ClosePasswordStore(); scoped_refptr<PasswordStoreDefault> CreateInitializedStore( std::unique_ptr<LoginDatabase> database); base::FilePath test_login_db_file_path() const; base::test::ScopedTaskEnvironment scoped_task_environment_; base::ScopedTempDir temp_dir_; scoped_refptr<PasswordStoreDefault> store_; DISALLOW_COPY_AND_ASSIGN(PasswordStoreDefaultTestDelegate); }; PasswordStoreDefaultTestDelegate::PasswordStoreDefaultTestDelegate() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) { OSCryptMocker::SetUp(); SetupTempDir(); store_ = CreateInitializedStore( std::make_unique<LoginDatabase>(test_login_db_file_path())); } PasswordStoreDefaultTestDelegate::PasswordStoreDefaultTestDelegate( std::unique_ptr<LoginDatabase> database) : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) { OSCryptMocker::SetUp(); SetupTempDir(); store_ = CreateInitializedStore(std::move(database)); } PasswordStoreDefaultTestDelegate::~PasswordStoreDefaultTestDelegate() { ClosePasswordStore(); OSCryptMocker::TearDown(); } void PasswordStoreDefaultTestDelegate::FinishAsyncProcessing() { scoped_task_environment_.RunUntilIdle(); } void PasswordStoreDefaultTestDelegate::SetupTempDir() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } void PasswordStoreDefaultTestDelegate::ClosePasswordStore() { store_->ShutdownOnUIThread(); FinishAsyncProcessing(); ASSERT_TRUE(temp_dir_.Delete()); } scoped_refptr<PasswordStoreDefault> PasswordStoreDefaultTestDelegate::CreateInitializedStore( std::unique_ptr<LoginDatabase> database) { scoped_refptr<PasswordStoreDefault> store( new PasswordStoreDefault(std::move(database))); store->Init(syncer::SyncableService::StartSyncFlare(), nullptr); return store; } base::FilePath PasswordStoreDefaultTestDelegate::test_login_db_file_path() const { return temp_dir_.GetPath().Append(FILE_PATH_LITERAL("login_test")); } } // anonymous namespace INSTANTIATE_TYPED_TEST_CASE_P(Default, PasswordStoreOriginTest, PasswordStoreDefaultTestDelegate); TEST(PasswordStoreDefaultTest, NonASCIIData) { PasswordStoreDefaultTestDelegate delegate; PasswordStoreDefault* store = delegate.store(); // Some non-ASCII password form data. static const PasswordFormData form_data[] = { {PasswordForm::SCHEME_HTML, "http://foo.example.com", "http://foo.example.com/origin", "http://foo.example.com/action", L"มีสีสัน", L"お元気ですか?", L"盆栽", L"أحب كرة", L"£éä국수çà", true, 1}, }; // Build the expected forms vector and add the forms to the store. std::vector<std::unique_ptr<PasswordForm>> expected_forms; for (unsigned int i = 0; i < arraysize(form_data); ++i) { expected_forms.push_back(FillPasswordFormWithData(form_data[i])); store->AddLogin(*expected_forms.back()); } MockPasswordStoreConsumer consumer; // We expect to get the same data back, even though it's not all ASCII. EXPECT_CALL( consumer, OnGetPasswordStoreResultsConstRef( password_manager::UnorderedPasswordFormElementsAre(&expected_forms))); store->GetAutofillableLogins(&consumer); delegate.FinishAsyncProcessing(); } TEST(PasswordStoreDefaultTest, Notifications) { PasswordStoreDefaultTestDelegate delegate; PasswordStoreDefault* store = delegate.store(); std::unique_ptr<PasswordForm> form = FillPasswordFormWithData(CreateTestPasswordFormData()); MockPasswordStoreObserver observer; store->AddObserver(&observer); const PasswordStoreChange expected_add_changes[] = { PasswordStoreChange(PasswordStoreChange::ADD, *form), }; EXPECT_CALL(observer, OnLoginsChanged(ElementsAreArray(expected_add_changes))); // Adding a login should trigger a notification. store->AddLogin(*form); // Change the password. form->password_value = base::ASCIIToUTF16("a different password"); const PasswordStoreChange expected_update_changes[] = { PasswordStoreChange(PasswordStoreChange::UPDATE, *form), }; EXPECT_CALL(observer, OnLoginsChanged(ElementsAreArray(expected_update_changes))); // Updating the login with the new password should trigger a notification. store->UpdateLogin(*form); const PasswordStoreChange expected_delete_changes[] = { PasswordStoreChange(PasswordStoreChange::REMOVE, *form), }; EXPECT_CALL(observer, OnLoginsChanged(ElementsAreArray(expected_delete_changes))); // Deleting the login should trigger a notification. store->RemoveLogin(*form); // Run the tasks to allow all the above expected calls to take place. delegate.FinishAsyncProcessing(); store->RemoveObserver(&observer); } // Verify that operations on a PasswordStore with a bad database cause no // explosions, but fail without side effect, return no data and trigger no // notifications. TEST(PasswordStoreDefaultTest, OperationsOnABadDatabaseSilentlyFail) { PasswordStoreDefaultTestDelegate delegate( std::make_unique<BadLoginDatabase>()); PasswordStoreDefault* bad_store = delegate.store(); delegate.FinishAsyncProcessing(); ASSERT_EQ(nullptr, bad_store->login_db()); testing::StrictMock<MockPasswordStoreObserver> mock_observer; bad_store->AddObserver(&mock_observer); // Add a new autofillable login + a blacklisted login. std::unique_ptr<PasswordForm> form = FillPasswordFormWithData(CreateTestPasswordFormData()); std::unique_ptr<PasswordForm> blacklisted_form(new PasswordForm(*form)); blacklisted_form->signon_realm = "http://foo.example.com"; blacklisted_form->origin = GURL("http://foo.example.com/origin"); blacklisted_form->action = GURL("http://foo.example.com/action"); blacklisted_form->blacklisted_by_user = true; bad_store->AddLogin(*form); bad_store->AddLogin(*blacklisted_form); delegate.FinishAsyncProcessing(); // Get all logins; autofillable logins; blacklisted logins. testing::StrictMock<MockPasswordStoreConsumer> mock_consumer; EXPECT_CALL(mock_consumer, OnGetPasswordStoreResultsConstRef(IsEmpty())); bad_store->GetLogins(PasswordStore::FormDigest(*form), &mock_consumer); delegate.FinishAsyncProcessing(); testing::Mock::VerifyAndClearExpectations(&mock_consumer); EXPECT_CALL(mock_consumer, OnGetPasswordStoreResultsConstRef(IsEmpty())); bad_store->GetAutofillableLogins(&mock_consumer); delegate.FinishAsyncProcessing(); testing::Mock::VerifyAndClearExpectations(&mock_consumer); EXPECT_CALL(mock_consumer, OnGetPasswordStoreResultsConstRef(IsEmpty())); bad_store->GetBlacklistLogins(&mock_consumer); delegate.FinishAsyncProcessing(); testing::Mock::VerifyAndClearExpectations(&mock_consumer); // Report metrics. bad_store->ReportMetrics("Test Username", true); delegate.FinishAsyncProcessing(); // Change the login. form->password_value = base::ASCIIToUTF16("a different password"); bad_store->UpdateLogin(*form); delegate.FinishAsyncProcessing(); // Delete one login; a range of logins. bad_store->RemoveLogin(*form); delegate.FinishAsyncProcessing(); base::RunLoop run_loop; bad_store->RemoveLoginsCreatedBetween(base::Time(), base::Time::Max(), run_loop.QuitClosure()); run_loop.Run(); bad_store->RemoveLoginsSyncedBetween(base::Time(), base::Time::Max()); delegate.FinishAsyncProcessing(); // Ensure no notifications and no explosions during shutdown either. bad_store->RemoveObserver(&mock_observer); } } // namespace password_manager
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
d012ba990dfb18fd211fce55d5b540406b223590
1fc7a6ff8d4f93c9716a2074c71911f192745d95
/VisualizationLibrary/src/vlGraphics/ClipPlane.cpp
721f7263b72c65d7a214a01eaafb2ae466b6c2ae
[ "BSD-2-Clause" ]
permissive
playbar/gllearn
14dc6e671f5161cac768884771e2a6401a5ed5b7
19e20ffd681eadff2559f13a42af12763b00b03e
refs/heads/master
2021-12-06T05:15:10.299208
2021-11-09T11:00:46
2021-11-09T11:00:46
180,532,777
0
2
null
2020-10-13T12:55:49
2019-04-10T08:04:15
C++
UTF-8
C++
false
false
4,383
cpp
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2020, Michele Bosi */ /* 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. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include <vlGraphics/ClipPlane.hpp> using namespace vl; //----------------------------------------------------------------------------- ClipPlane::ClipPlane(real o, vec3 n) { VL_DEBUG_SET_OBJECT_NAME() mPlane.setNormal(n); mPlane.setOrigin(o); mEnabled = true; } //----------------------------------------------------------------------------- ClipPlane::ClipPlane(const vec3& o, const vec3& n) { VL_DEBUG_SET_OBJECT_NAME() mPlane.setNormal(n); mPlane.setOrigin(dot(o, n)); mEnabled = true; } //----------------------------------------------------------------------------- void ClipPlane::apply(int index, const Camera* camera, OpenGLContext*) const { VL_CHECK(index>=0 && index<6); // we do our own transformations if (enabled()) { glEnable(GL_CLIP_PLANE0 + index); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); mat4 mat; if ( boundTransform() ) mat = camera->viewMatrix() * boundTransform()->worldMatrix(); vec3 pt1 = mPlane.normal() * mPlane.origin(); vec3 pt2 = mPlane.normal() * mPlane.origin() + mPlane.normal(); pt1 = mat * pt1; pt2 = mat * pt2; vec3 n = pt2 - pt1; real orig = dot(n, pt1); #if defined(VL_OPENGL_ES1) float equation[] = { n.x(), n.y(), n.z(), -orig }; glClipPlanef(GL_CLIP_PLANE0 + index, equation); #else double equation[] = { n.x(), n.y(), n.z(), -orig }; glClipPlane(GL_CLIP_PLANE0 + index, equation); #endif glPopMatrix(); } else { glDisable(GL_CLIP_PLANE0 + index); } } //-----------------------------------------------------------------------------
[ "" ]
42a4294aaf2f5f6e44265518fe7443571f3b4414
01204b228054d6d3240961f5a115a7d6ce6296ad
/src/progress_bar.cpp
17f39dca961c76d2aa6019010f9e9e51124e4e77
[]
no_license
rbarcellos/MScPack
90e111f10ad0eaf66984909a321e151aea7d0951
687b10b626613beae4770a28932a032f5917547a
refs/heads/master
2020-05-29T17:12:55.723706
2014-07-06T20:12:06
2014-07-06T20:12:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
#include <Rcpp.h> using namespace Rcpp; // funcao que insere barra de progresso void progress_bar(double x, double N) { // how wide you want the progress meter to be int totaldotz=40; double fraction = x / N; // part of the progressmeter that's already "full" int dotz = round(fraction * totaldotz); // create the "meter" int ii=0; printf("\r%3.0f%% [",fraction*100); // part that's full already for ( ; ii < dotz;ii++) { printf("="); } // remaining part (spaces) for ( ; ii < totaldotz;ii++) { printf(" "); } // and back to line begin - do not forget the fflush to avoid output buffering problems! printf("]\r"); fflush(stdout); }
[ "rafaelmbarcellos@gmail.com" ]
rafaelmbarcellos@gmail.com
e5ffaf2f7cde181672a0404b4c1307abc6a3934d
ffec6afb933366239cafbc8e4f977b7e41ec46d2
/rrgraph.h
a706f99b54c9afcc7da6b5f07ac4252c0b9737d9
[]
no_license
lynxgav/genvar
59cff369723695e2fd21958fed80e20412c63968
f4028383a5e0368a1711dcfc082f51d9f7ab3410
refs/heads/master
2021-01-18T13:50:35.840278
2013-02-19T08:16:29
2013-02-19T08:16:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,719
h
#ifndef RRGRAPH_H #define RRGRAPH_H #include"network.h" class CRRGraph : public CNetwork { public: CRRGraph(unsigned int n, unsigned int k); bool generate(unsigned int n, unsigned int k); unsigned int K; private: }; CRRGraph::CRRGraph(unsigned int n, unsigned int k){ N=n; K=k; ERROR(K>=N, "Number of links exceeds that of the complete graph") ERROR(is_odd(K) and is_odd(N), "Either N or K should be even"); while(!generate(N, K)){}; } bool CRRGraph::generate(unsigned int n, unsigned int k){ clear(); N=n; K=k; vector<CNode *> temp; for(unsigned int i=0; i<N; i++){ CNode *p_node=new CNode(i); nodes.push_back(p_node); temp.push_back(p_node); } unsigned int nlinks=N*K/2; while(nlinks>0){ unsigned int tempN=temp.size(); if(tempN==1)return false; //Not possible to add more links, only one node left std::tr1::uniform_int<unsigned int> unif(0, tempN-1); unsigned int pos1,pos2; int attempt=0; pos1=unif(eng); do{ pos2=unif(eng); attempt++; WARNING(attempt>50,stringify(pos1)+" "+stringify(pos2)); if(attempt>50) return false; //Cannot find suitable pairs of nodes } while(pos1==pos2); bool success1=temp.at(pos1)->add_neighbour(temp.at(pos2), true); bool success2=temp.at(pos2)->add_neighbour(temp.at(pos1), true); assert(success1==success2); if(success1==false)continue;//the link already exists if(temp.at(pos1)->degree == K) { temp.at(pos1)=temp.back(); if(pos2==tempN-1) pos2=pos1; temp.pop_back(); } if(temp.at(pos2)->degree == K) { temp.at(pos2)=temp.back(); temp.pop_back(); } nlinks--; } assert(temp.size()==0); assert(nlinks==0); return true;//successfully generated } #endif /* RRGRAPH_H */
[ "lynxgav@gmail.com" ]
lynxgav@gmail.com
39c14d3d5040d3555869fcc6b0d62bf499a9601f
32d1fbbdbce7003756f98961cfc9bdbcf059f827
/third_party/mosquitto/test/lib/c/02-unsubscribe.c
c757f510bbc9516d404a70443803c31e99fc9ba4
[ "BSD-3-Clause", "EPL-1.0", "CPL-1.0", "LicenseRef-scancode-generic-export-compliance", "MPL-1.1", "Apache-1.1", "Apache-2.0", "LGPL-2.1-only", "MIT" ]
permissive
jkrvivian/create_chid_benchmark
45d7c8f7999b6c0316ff515eec90d67f68c71085
f6bfa387c834aeafe27bc0aa33bc03bb1cedccbc
refs/heads/master
2020-11-28T17:06:16.831238
2019-12-24T05:31:45
2019-12-24T05:56:50
229,876,385
0
0
MIT
2019-12-24T05:28:32
2019-12-24T05:28:32
null
UTF-8
C++
false
false
929
c
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <mosquitto.h> static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ exit(1); }else{ mosquitto_unsubscribe(mosq, NULL, "unsubscribe/test"); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { run = rc; } void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid) { mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("unsubscribe-test", true, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_lib_cleanup(); return run; }
[ "vulxj0j8j8@gmail.com" ]
vulxj0j8j8@gmail.com
c2961adf539fa9cb6763c23137123e9b2e7fa795
470acbd6b3e1967186a4f66f2fad9e002d851e78
/tests/repository/mysql_collection_schema_change_test.cc
59d19c9549d288e35d3442fdb889446fba3e4006
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
chendianzhang/proximabilin
901d307efdc50815d3f3342215fd3463fce318ad
d539519d0c38aa07376746d473d45d3b8372b9f6
refs/heads/master
2023-09-04T11:45:53.194344
2021-11-02T02:27:12
2021-11-02T02:27:12
418,355,309
0
0
null
null
null
null
UTF-8
C++
false
false
8,391
cc
/** * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. * \author Dianzhang.Chen * \date Dec 2020 * \brief */ #include <gmock/gmock.h> #define private public #define protected public #include "repository/repository_common/config.h" #undef private #undef protected #include "repository/mysql_collection.h" #include "mock_index_agent_server.h" #include "mock_mysql_handler.h" #include "port_helper.h" const std::string collection_name = "mysql_collection_test.info"; static int PORT = 8010; static int PID = 0; //////////////////////////////////////////////////////////////////// class MysqlCollectionSchemaChangeTest2 : public ::testing::Test { protected: MysqlCollectionSchemaChangeTest2() {} ~MysqlCollectionSchemaChangeTest2() {} void SetUp() { PortHelper::GetPort(&PORT, &PID); std::cout << "Server port: " << PORT << std::endl; std::string index_uri = "127.0.0.1:" + std::to_string(PORT); proxima::be::repository::Config::Instance() .repository_config_.mutable_repository_config() ->set_index_agent_addr(index_uri); std::cout << "Set index addr: " << index_uri << std::endl; proxima::be::repository::Config::Instance() .repository_config_.mutable_repository_config() ->set_batch_interval(1000000); std::cout << "Set batch_interval to 1s" << std::endl; } void TearDown() { PortHelper::RemovePortFile(PID); } }; TEST_F(MysqlCollectionSchemaChangeTest2, TestGeneral) { brpc::Server server_; MockGeneralProximaServiceImpl svc_; brpc::ServerOptions options; ASSERT_EQ(0, server_.AddService(&svc_, brpc::SERVER_DOESNT_OWN_SERVICE)); ASSERT_EQ(0, server_.Start(PORT, &options)); { proto::CollectionConfig config; config.set_collection_name(collection_name); CollectionPtr collection{nullptr}; MockMysqlHandlerPtr mysql_handler = std::make_shared<MockMysqlHandler>(config); EXPECT_CALL(*mysql_handler, init(_)) .WillRepeatedly(Return(0)) .RetiresOnSaturation(); EXPECT_CALL(*mysql_handler, start(_)) .WillRepeatedly(Return(0)) .RetiresOnSaturation(); EXPECT_CALL(*mysql_handler, get_next_row_data(Matcher<proto::WriteRequest::Row *>(_), Matcher<LsnContext *>(_))) .WillOnce(Invoke( [](proto::WriteRequest::Row *row_data, LsnContext *context) -> int { row_data->set_primary_key(1); row_data->mutable_lsn_context()->set_lsn(1); context->status = RowDataStatus::NORMAL; return 0; })) .WillOnce(Invoke( [](proto::WriteRequest::Row *row_data, LsnContext *context) -> int { row_data->set_primary_key(2); row_data->mutable_lsn_context()->set_lsn(2); context->status = RowDataStatus::NORMAL; return 0; })) .WillOnce(Invoke( [](proto::WriteRequest::Row *row_data, LsnContext *context) -> int { row_data->set_primary_key(3); context->status = RowDataStatus::SCHEMA_CHANGED; return 0; })) .WillOnce(Invoke( [](proto::WriteRequest::Row *row_data, LsnContext *context) -> int { row_data->set_primary_key(3); row_data->mutable_lsn_context()->set_lsn(3); context->status = RowDataStatus::NORMAL; return 0; })) .WillOnce(Invoke( [](proto::WriteRequest::Row *row_data, LsnContext *context) -> int { row_data->set_primary_key(4); row_data->mutable_lsn_context()->set_lsn(4); context->status = RowDataStatus::NORMAL; return 0; })) .WillRepeatedly(Invoke( [](proto::WriteRequest::Row *row_data, LsnContext *context) -> int { row_data->set_primary_key(3); context->status = RowDataStatus::NO_MORE_DATA; return 0; })) .RetiresOnSaturation(); EXPECT_CALL(*mysql_handler, reset_status(Matcher<ScanMode>(_), Matcher<const proto::CollectionConfig &>(_), Matcher<const LsnContext &>(_))) // EXPECT_CALL(*mysql_handler, reset_status(_, _, _)) .WillRepeatedly(Return(0)) .RetiresOnSaturation(); EXPECT_CALL(*mysql_handler, get_fields_meta(_)) .WillOnce(Invoke([](proto::WriteRequest::RowMeta *meta) -> int { meta->add_index_column_metas()->set_column_name("index1"); meta->add_index_column_metas()->set_column_name("index2"); meta->add_forward_column_names("forward1"); meta->add_forward_column_names("forward2"); return 0; })) .WillOnce(Invoke([](proto::WriteRequest::RowMeta *meta) -> int { meta->add_index_column_metas()->set_column_name("new-index1"); meta->add_index_column_metas()->set_column_name("new-index2"); meta->add_forward_column_names("new-forward1"); meta->add_forward_column_names("new-forward2"); return 0; })) .WillRepeatedly(Return(0)) .RetiresOnSaturation(); EXPECT_CALL(*mysql_handler, get_table_snapshot(_, _)) .WillRepeatedly(Return(0)) .RetiresOnSaturation(); collection.reset(new (std::nothrow) MysqlCollection(config, mysql_handler)); int ret = collection->init(); ASSERT_EQ(ret, 0); CollectionStatus current_state = collection->state(); ASSERT_EQ(current_state, CollectionStatus::INIT); collection->run(); sleep(1); // check value ASSERT_EQ(svc_.get_server_called_count(), 2); proto::WriteRequest request; std::string request_str = svc_.get_request_string(0); ASSERT_EQ(request_str.empty(), false); ret = request.ParseFromString(request_str); ASSERT_EQ(ret, true); auto rows = request.rows(); ASSERT_EQ(rows.size(), 2); auto row1 = rows[0]; auto row2 = rows[1]; // row1 ASSERT_EQ(row1.primary_key(), 1); ASSERT_EQ(row1.lsn_context().lsn(), 1); // row2 ASSERT_EQ(row2.primary_key(), 2); ASSERT_EQ(row2.lsn_context().lsn(), 2); // meta auto meta = request.row_meta(); auto index_column_metas = meta.index_column_metas(); ASSERT_EQ(index_column_metas[0].column_name(), "index1"); ASSERT_EQ(index_column_metas[1].column_name(), "index2"); ASSERT_EQ(meta.index_column_metas_size(), 2); auto forward_column_names = meta.forward_column_names(); ASSERT_EQ(forward_column_names[0], "forward1"); ASSERT_EQ(forward_column_names[1], "forward2"); proto::WriteRequest request2; request_str = svc_.get_request_string(1); ASSERT_EQ(request_str.empty(), false); ret = request.ParseFromString(request_str); ASSERT_EQ(ret, true); rows = request.rows(); ASSERT_EQ(rows.size(), 2); row1 = rows[0]; row2 = rows[1]; // row1 ASSERT_EQ(row1.primary_key(), 3); ASSERT_EQ(row1.lsn_context().lsn(), 3); // row2 ASSERT_EQ(row2.primary_key(), 4); ASSERT_EQ(row2.lsn_context().lsn(), 4); // meta meta = request.row_meta(); index_column_metas = meta.index_column_metas(); ASSERT_EQ(index_column_metas[0].column_name(), "new-index1"); ASSERT_EQ(index_column_metas[1].column_name(), "new-index2"); ASSERT_EQ(meta.index_column_metas_size(), 2); forward_column_names = meta.forward_column_names(); ASSERT_EQ(forward_column_names[0], "new-forward1"); ASSERT_EQ(forward_column_names[1], "new-forward2"); // exit collection->stop(); sleep(2); LOG_INFO("MysqlCollectionTest2::TestGeneral PASS"); } ASSERT_EQ(0, server_.Stop(0)); ASSERT_EQ(0, server_.Join()); }
[ "hechong.xyf@alibaba-inc.com" ]
hechong.xyf@alibaba-inc.com
961eb5c767df1942ba26304087564523ff6314e2
8959cb9af30421568a7e26a254b2fa4cc6637c91
/graph_algo/graphRepresentation.cpp
9149d5d7bc9f2c6cfac7d3f339b6ed1c0a738b3a
[]
no_license
shekhar-321/practise
ac1a703f8f9b499af7baf9ca8f1a4e5e88a7e4ac
f24231d09cb0ebba3ab14b26f42e845d60c0e119
refs/heads/master
2022-07-21T21:16:02.818235
2022-07-01T21:14:03
2022-07-01T21:14:03
154,138,959
0
2
null
null
null
null
UTF-8
C++
false
false
1,065
cpp
#include<iostream> #include<string> #include<vector> //Adjancecy list represenation of graph// using namespace std; class Graph{ private: int vertex; vector <int> edge; public: Graph(){ vertex=0; } void addNode(int vertex,int ed){ this->vertex=vertex; edge.push_back(ed); } void printGraph(){ cout<<"vertex ->"<<this->vertex; for (unsigned int i=0;i<this->edge.size();i++){ cout<<"edge - >"<<this->edge[i]; } cout<<endl; } }; //void printGraph(vector<Graph>&v){ //for(unsigned iterator=0;iterator<v.size();iterator++){ //cout<<"vertex ->"<<v[iterator].vertex; //for(unsigned it=0;it<v[iterator].edge.size();it++) //cout<<"edge - >"<<v[iterator].edge[it]; //cout<<endl; //} //} int main(){ vector<Graph>graph(5,Graph()); graph[0].addNode(0,1); graph[0].addNode(0,2); graph[1].addNode(1,3); graph[1].addNode(1,4); graph[2].addNode(2,0); graph[2].addNode(2,3); graph[3].addNode(3,1); graph[3].addNode(3,2); graph[3].addNode(3,4); graph[4].addNode(4,1); graph[4].addNode(4,3); //printGraph(graph); for (unsigned int i=0;i<5;i++) graph[i].printGraph(); return 0; }
[ "singh.shekhar@vector.com" ]
singh.shekhar@vector.com
fc5ec8163a5f70e308134f92fe0b0ea7758b7c9e
d54916fe57f229a05361b822a22b881d15819c7f
/CONTEST/Archive/658_DIV_2/fourth.cpp
a7ab4ac055e08200486e8f41db0a5cf7835f6e10
[]
no_license
ksb451/Cpp_DSA
73dc8773fc4b5d896b133410809efce97437b9aa
10544373f3e6558cf57d2270a30550b4761b0715
refs/heads/master
2023-06-25T10:48:04.473323
2021-07-22T17:04:31
2021-07-22T17:04:31
168,570,132
0
1
null
2020-10-26T15:03:34
2019-01-31T17:53:57
C++
UTF-8
C++
false
false
2,191
cpp
#include <bits/stdc++.h> #include <algorithm> using namespace std; #define fast \ ios_base::sync_with_stdio(false); \ cout.tie(NULL); \ cin.tie(NULL); #define IN cin >> #define OUT cout << #define nl "\n" #define all(a) (a).begin(), (a).end() #define pb push_back #define write(a) \ for (auto x : a) \ { \ cout << x << " "; \ } \ cout << nl; #define read(a) \ for (auto &x : a) \ { \ cin >> x; \ } using ll = long long int; using ld = long double; using pll = pair<ll, ll>; using pii = pair<int, int>; using vll = vector<ll>; using vi = vector<int>; const ll mod = (ll)(1e9) + 7LL; const ll M = 988244353LL; char neg(char a) { if (a == '1') { return '0'; } else { return '1'; } } void rev(string &a, int n) { int i = 0; int j = n - 1; while (i <= j) { if (i == j) { a[i] = neg(a[j]); } else { char aa = a[i]; char bb = a[j]; a[i] = neg(bb); a[j] = neg(aa); } i++; j--; } } void solve() { ll n; cin >> n; string a, b; cin.get(); getline(cin, a); getline(cin, b); vector<ll> ans; char first = a[0]; for (int i = 0; i < n; i++) { int first; if (i % 2 == 0) { first = (a[i / 2] - '0') ^ 0; } else { first = (a[n - 1 - (i / 2)] - '0') ^ 1; } //cout << first << " "; if (('0' + first) == b[n - 1 - i]) { ans.push_back(1); //rev(a, 1); ans.push_back(n - i); //rev(a, n - i); } else { ans.push_back(n - i); //rev(a, n - i); } //cout << a << " "; } cout << ans.size() << endl; for (auto i : ans) { cout << i << " "; } cout << endl; } int main() { fast; ll tc = 1; IN tc; while (tc--) { solve(); } return 0; }
[ "iec2018043@iiita.ac.in" ]
iec2018043@iiita.ac.in
59c750ac59c42508685df574bb1411a7b7aa1e5c
30ec7200d75d3aae19724172c60387a07ec89a2c
/src/kernel.cpp
394257e84f556727cd607f39ca780dacf2cb1f73
[ "MIT" ]
permissive
EatonChips/doscoin-master
d03d1318d435cfbd3f084807dd8910ead9491941
5b21ce28a1d76016aae88b2f43bb89dae1c79673
refs/heads/master
2021-05-28T16:11:05.384920
2014-08-02T07:16:54
2014-08-02T07:16:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,810
cpp
// Copyright (c) 2012-2013 The doscoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "kernel.h" #include "txdb.h" using namespace std; extern unsigned int nStakeMaxAge; extern unsigned int nTargetSpacing; typedef std::map<int, unsigned int> MapModifierCheckpoints; // Hard checkpoints of stake modifiers to ensure they are deterministic static std::map<int, unsigned int> mapStakeModifierCheckpoints = boost::assign::map_list_of ( 0, 0x0e00670bu ) ; // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet) static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet = boost::assign::map_list_of ( 0, 0x0e00670bu ) ; // Get time weight int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd) { // Kernel hash weight starts from 0 at the min age // this change increases active coins participating the hash and helps // to secure the network when proof-of-stake difficulty is low return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64_t)nStakeMaxAge); } // Get the last stake modifier and its generation time from a given block static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime) { if (!pindex) return error("GetLastStakeModifier: null pindex"); while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier()) pindex = pindex->pprev; if (!pindex->GeneratedStakeModifier()) return error("GetLastStakeModifier: no generation at genesis block"); nStakeModifier = pindex->nStakeModifier; nModifierTime = pindex->GetBlockTime(); return true; } // Get selection interval section (in seconds) static int64_t GetStakeModifierSelectionIntervalSection(int nSection) { assert (nSection >= 0 && nSection < 64); return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)))); } // Get stake modifier selection interval (in seconds) static int64_t GetStakeModifierSelectionInterval() { int64_t nSelectionInterval = 0; for (int nSection=0; nSection<64; nSection++) nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection); return nSelectionInterval; } // select a block from the candidate blocks in vSortedByTimestamp, excluding // already selected blocks in vSelectedBlocks, and with timestamp up to // nSelectionIntervalStop. static bool SelectBlockFromCandidates(vector<pair<int64_t, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks, int64_t nSelectionIntervalStop, uint64_t nStakeModifierPrev, const CBlockIndex** pindexSelected) { bool fSelected = false; uint256 hashBest = 0; *pindexSelected = (const CBlockIndex*) 0; BOOST_FOREACH(const PAIRTYPE(int64_t, uint256)& item, vSortedByTimestamp) { if (!mapBlockIndex.count(item.second)) return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str()); const CBlockIndex* pindex = mapBlockIndex[item.second]; if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop) break; if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0) continue; // compute the selection hash by hashing its proof-hash and the // previous proof-of-stake modifier uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash(); CDataStream ss(SER_GETHASH, 0); ss << hashProof << nStakeModifierPrev; uint256 hashSelection = Hash(ss.begin(), ss.end()); // the selection hash is divided by 2**32 so that proof-of-stake block // is always favored over proof-of-work block. this is to preserve // the energy efficiency property if (pindex->IsProofOfStake()) hashSelection >>= 32; if (fSelected && hashSelection < hashBest) { hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } else if (!fSelected) { fSelected = true; hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } } if (fDebug && GetBoolArg("-printstakemodifier")) printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str()); return fSelected; } // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. // Stake modifier consists of bits each of which is contributed from a // selected block of a given block group in the past. // The selection of a block is based on a hash of the block's proof-hash and // the previous stake modifier. // Stake modifier is recomputed at a fixed time interval instead of every // block. This is to make it difficult for an attacker to gain control of // additional bits in the stake modifier, even after generating a chain of // blocks. bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier) { nStakeModifier = 0; fGeneratedStakeModifier = false; if (!pindexPrev) { fGeneratedStakeModifier = true; return true; // genesis block's modifier is 0 } // First find current stake modifier and its generation block time // if it's not old enough, return the same stake modifier int64_t nModifierTime = 0; if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime)) return error("ComputeNextStakeModifier: unable to get last modifier"); if (fDebug) { printf("ComputeNextStakeModifier: prev modifier=0x%016"PRIx64" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str()); } if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval) return true; // Sort candidate blocks by timestamp vector<pair<int64_t, uint256> > vSortedByTimestamp; vSortedByTimestamp.reserve(64 * nModifierInterval / nTargetSpacing); int64_t nSelectionInterval = GetStakeModifierSelectionInterval(); int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval; const CBlockIndex* pindex = pindexPrev; while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) { vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash())); pindex = pindex->pprev; } int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0; reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); // Select 64 blocks from candidate blocks to generate stake modifier uint64_t nStakeModifierNew = 0; int64_t nSelectionIntervalStop = nSelectionIntervalStart; map<uint256, const CBlockIndex*> mapSelectedBlocks; for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++) { // add an interval section to the current selection round nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound); // select a block from the candidates of current round if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex)) return error("ComputeNextStakeModifier: unable to select block at round %d", nRound); // write the entropy bit of the selected block nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound); // add the selected block from candidates to selected list mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex)); if (fDebug && GetBoolArg("-printstakemodifier")) printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit()); } // Print selection map for visualization of the selected blocks if (fDebug && GetBoolArg("-printstakemodifier")) { string strSelectionMap = ""; // '-' indicates proof-of-work blocks not selected strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-'); pindex = pindexPrev; while (pindex && pindex->nHeight >= nHeightFirstCandidate) { // '=' indicates proof-of-stake blocks not selected if (pindex->IsProofOfStake()) strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "="); pindex = pindex->pprev; } BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks) { // 'S' indicates selected proof-of-stake blocks // 'W' indicates selected proof-of-work blocks strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W"); } printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str()); } if (fDebug) { printf("ComputeNextStakeModifier: new modifier=0x%016"PRIx64" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str()); } nStakeModifier = nStakeModifierNew; fGeneratedStakeModifier = true; return true; } // The stake modifier used to hash for a stake kernel is chosen as the stake // modifier about a selection interval later than the coin generating the kernel static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake) { nStakeModifier = 0; if (!mapBlockIndex.count(hashBlockFrom)) return error("GetKernelStakeModifier() : block not indexed"); const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom]; nStakeModifierHeight = pindexFrom->nHeight; nStakeModifierTime = pindexFrom->GetBlockTime(); int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval(); const CBlockIndex* pindex = pindexFrom; // loop to find the stake modifier later by a selection interval while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) { if (!pindex->pnext) { // reached best block; may happen if node is behind on block chain if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime())) return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s", pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str()); else return false; } pindex = pindex->pnext; if (pindex->GeneratedStakeModifier()) { nStakeModifierHeight = pindex->nHeight; nStakeModifierTime = pindex->GetBlockTime(); } } nStakeModifier = pindex->nStakeModifier; return true; } // doscoin kernel protocol // coinstake must meet hash target according to the protocol: // kernel (input 0) must meet the formula // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight // this ensures that the chance of getting a coinstake is proportional to the // amount of coin age one owns. // The reason this hash is chosen is the following: // nStakeModifier: scrambles computation to make it very difficult to precompute // future proof-of-stake at the time of the coin's confirmation // txPrev.block.nTime: prevent nodes from guessing a good timestamp to // generate transaction for future advantage // txPrev.offset: offset of txPrev inside block, to reduce the chance of // nodes generating coinstake at the same time // txPrev.nTime: reduce the chance of nodes generating coinstake at the same // time // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes // generating coinstake at the same time // block/tx hash should not be used here as they can be generated in vast // quantities so as to generate blocks faster, degrading the system back into // a proof-of-work situation. // bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake) { if (nTimeTx < txPrev.nTime) // Transaction timestamp violation return error("CheckStakeKernelHash() : nTime violation"); unsigned int nTimeBlockFrom = blockFrom.GetBlockTime(); if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement return error("CheckStakeKernelHash() : min age violation"); CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); int64_t nValueIn = txPrev.vout[prevout.n].nValue; uint256 hashBlockFrom = blockFrom.GetHash(); CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)txPrev.nTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60); targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256(); // Calculate hash CDataStream ss(SER_GETHASH, 0); uint64_t nStakeModifier = 0; int nStakeModifierHeight = 0; int64_t nStakeModifierTime = 0; if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake)) return false; ss << nStakeModifier; ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx; hashProofOfStake = Hash(ss.begin(), ss.end()); if (fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRIx64" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : check modifier=0x%016"PRIx64" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } // Now check if proof-of-stake hash meets target protocol if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay) return false; if (fDebug && !fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRIx64" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : pass modifier=0x%016"PRIx64" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } return true; } // Check kernel hash target and coinstake signature bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake) { if (!tx.IsCoinStake()) return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str()); // Kernel (input 0) must match the stake hash target per coin age (nBits) const CTxIn& txin = tx.vin[0]; // First try finding the previous transaction in database CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download // Verify signature if (!VerifySignature(txPrev, tx, 0, 0)) return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str())); // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug)) return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync return true; } // Check whether the coinstake timestamp meets protocol bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx) { // v0.3 protocol return (nTimeBlock == nTimeTx); } // Get stake modifier checksum unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex) { assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); // Hash previous checksum with flags, hashProofOfStake and nStakeModifier CDataStream ss(SER_GETHASH, 0); if (pindex->pprev) ss << pindex->pprev->nStakeModifierChecksum; ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier; uint256 hashChecksum = Hash(ss.begin(), ss.end()); hashChecksum >>= (256 - 32); return hashChecksum.Get64(); } // Check stake modifier hard checkpoints bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum) { MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints); if (checkpoints.count(nHeight)) return nStakeModifierChecksum == checkpoints[nHeight]; return true; }
[ "crust800@gmail.com" ]
crust800@gmail.com
d7edbadb203e43c7dd507a38de5fc924f9e4a141
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/chrome/browser/banners/app_banner_settings_helper.h
034083f7dcafade170a9dda95d21f6709f6fb8f9
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
7,628
h
// 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. #ifndef CHROME_BROWSER_BANNERS_APP_BANNER_SETTINGS_HELPER_H_ #define CHROME_BROWSER_BANNERS_APP_BANNER_SETTINGS_HELPER_H_ #include <set> #include <string> #include <vector> #include "base/macros.h" #include "base/time/time.h" #include "chrome/browser/installable/installable_logging.h" #include "ui/base/page_transition_types.h" namespace content { class WebContents; } // namespace content class GURL; class Profile; // Utility class to record banner events for the given package or start url. // // These events are used to decide when banners should be shown, using a // heuristic based on how many different days in a recent period of time (for // example the past two weeks) the banner could have been shown, when it was // last shown, when it was last blocked, and when it was last installed (for // ServiceWorker style apps - native apps can query whether the app was // installed directly). // // The desired effect is to have banners appear once a user has demonstrated // an ongoing relationship with the app, and not to pester the user too much. // // For most events only the last event is recorded. The exception are the // could show events. For these a list of the events is maintained. At most // one event is stored per day, and events outside the window the heuristic // uses are discarded. Local times are used to enforce these rules, to ensure // what we count as a day matches what the user perceives to be days. class AppBannerSettingsHelper { public: // TODO(mariakhomenko): Rename events to reflect that they are used in more // contexts now. enum AppBannerEvent { APP_BANNER_EVENT_COULD_SHOW, APP_BANNER_EVENT_DID_SHOW, APP_BANNER_EVENT_DID_BLOCK, APP_BANNER_EVENT_DID_ADD_TO_HOMESCREEN, APP_BANNER_EVENT_NUM_EVENTS, }; enum AppBannerRapporMetric { WEB, NATIVE, }; static const char kInstantAppsKey[]; // BannerEvents record the time that a site was accessed, along with an // engagement weight representing the importance of the access. struct BannerEvent { base::Time time; double engagement; }; // The content setting basically records a simplified subset of history. // For privacy reasons this needs to be cleared. The ClearHistoryForURLs // function removes any information from the banner content settings for the // given URls. static void ClearHistoryForURLs(Profile* profile, const std::set<GURL>& origin_urls); // Record a banner installation event, for either a WEB or NATIVE app. static void RecordBannerInstallEvent( content::WebContents* web_contents, const std::string& package_name_or_start_url, AppBannerRapporMetric rappor_metric); // Record a banner dismissal event, for either a WEB or NATIVE app. static void RecordBannerDismissEvent( content::WebContents* web_contents, const std::string& package_name_or_start_url, AppBannerRapporMetric rappor_metric); // Record a banner event. Should not be used for could show events, as they // require a transition type. static void RecordBannerEvent(content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url, AppBannerEvent event, base::Time time); // Record a banner could show event, with a specified transition type. static void RecordBannerCouldShowEvent( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url, base::Time time, ui::PageTransition transition_type); // Determine if the banner should be shown, given the recorded events for the // supplied app. Returns an InstallableStatusCode indicated the reason why the // banner shouldn't be shown, or NO_ERROR_DETECTED if it should be shown. static InstallableStatusCode ShouldShowBanner( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url, base::Time time); // Gets the could have been shown events that are stored for the given package // or start url. This is only exposed for testing. static std::vector<BannerEvent> GetCouldShowBannerEvents( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url); // Get the recorded event for an event type that only records the last event. // Should not be used with APP_BANNER_EVENT_COULD_SHOW. This is only exposed // for testing. static base::Time GetSingleBannerEvent( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url, AppBannerEvent event); // Returns true if |total_engagement| is sufficiently high to warrant // triggering a banner, or if the command-line flag to bypass engagement // checking is true. static bool HasSufficientEngagement(double total_engagement); // Record a UMA statistic measuring the minutes between the first visit to the // site and the first showing of the banner. static void RecordMinutesFromFirstVisitToShow( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url, base::Time time); // Returns true if any site under |origin| was launched from homescreen in the // last ten days. This allows services outside app banners to utilise the // content setting that ensures app banners are not shown for sites which ave // already been added to homescreen. static bool WasLaunchedRecently(Profile* profile, const GURL& origin_url, base::Time now); // Set the number of days which dismissing/ignoring the banner should prevent // a banner from showing. static void SetDaysAfterDismissAndIgnoreToTrigger(unsigned int dismiss_days, unsigned int ignore_days); // Set the engagement weights assigned to direct and indirect navigations. static void SetEngagementWeights(double direct_engagement, double indirect_engagement); // Set the minimum number of minutes between banner visits that will // trigger a could show banner event. This must be less than the // number of minutes in a day, and evenly divide the number of minutes // in a day. static void SetMinimumMinutesBetweenVisits(unsigned int minutes); // Set the total engagement weight required to trigger a banner. static void SetTotalEngagementToTrigger(double total_engagement); // Resets the engagement weights, minimum minutes, and total engagement to // trigger to their default values. static void SetDefaultParameters(); // Bucket a given time to the given resolution in local time. static base::Time BucketTimeToResolution(base::Time time, unsigned int minutes); // Updates all values from field trial. static void UpdateFromFieldTrial(); // Returns true if the app banner trigger condition should use the site // engagement score instead of the navigation-based heuristic. static bool ShouldUseSiteEngagementScore(); private: DISALLOW_IMPLICIT_CONSTRUCTORS(AppBannerSettingsHelper); }; #endif // CHROME_BROWSER_BANNERS_APP_BANNER_SETTINGS_HELPER_H_
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
6a902610aa2309ae4b19dc2d7ac0e3af50be32c4
8c86759e276a231ae2e962979cf2c68d5c27cc83
/src/table/parser.cpp
be674c6f324e568cc5719cb134d6150c672fd760
[]
no_license
Caturra000/vSQL-remaster
01ffb9d7f76fe31434d8521c6598b355e2d0da7d
c3bfecf153b433e615a44c52d3ddc5bbe8dd44b6
refs/heads/master
2023-01-19T15:42:46.605429
2020-11-24T12:42:25
2020-11-24T12:42:25
315,620,771
1
0
null
null
null
null
UTF-8
C++
false
false
5,812
cpp
#include <cstring> #include "parser.h" void parser::decode(sqlite3_context *ctx, col_type type, value v) { static std::function<void(sqlite3_context*,value)> mapping[] = { /*[UNKNOWN] = */[](sqlite3_context *ctx, value v) { }, /*[INT] = */[](sqlite3_context *ctx, value v) { sqlite3_result_int(ctx,v.i32); }, /*[CHAR] = */[](sqlite3_context *ctx, value v) { sqlite3_result_text(ctx, v.ptr, -1, SQLITE_TRANSIENT); }, /*[VARCHAR] = */[](sqlite3_context *ctx, value v) { sqlite3_result_text(ctx, v.ptr, -1, SQLITE_TRANSIENT); }, /*[BIGINT] = */[](sqlite3_context *ctx, value v) { sqlite3_result_int64(ctx,v.i64); }, /*[BOOLEAN] = */[](sqlite3_context *ctx, value v) { sqlite3_result_int(ctx,v.i32); }, /*[DOUBLE] = */[](sqlite3_context *ctx, value v) { sqlite3_result_int(ctx,v.f64); }, /*[SMALLINT] = */[](sqlite3_context *ctx, value v) { sqlite3_result_int(ctx,v.i32); }, /*[TINYINT] = */[](sqlite3_context *ctx, value v) { sqlite3_result_int(ctx,v.i32); }, }; mapping[type](ctx,v); } void parser::encode(sqlite3_value *sv, col_type type, value &v) { static std::function<void(sqlite3_value*, value&)> mapping[] = { /*[UNKNOWN] = */[](sqlite3_value *sv, value &v) { }, /*[INT] = */[](sqlite3_value *sv, value &v) { v = sqlite3_value_int(sv); }, /*[VARCHAR] = */[](sqlite3_value *sv, value &v) { auto str = reinterpret_cast<const char *>(sqlite3_value_text(sv)); auto len = strlen(str)+1; v.ptr = new char[len]; memcpy(v.ptr, str, len); }, /*[CHAR] = */[](sqlite3_value *sv, value &v) { auto str = reinterpret_cast<const char *>(sqlite3_value_text(sv)); auto len = strlen(str)+1; v.ptr = new char[len]; memcpy(v.ptr, str, len); }, /*[BIGINT] = */[](sqlite3_value *sv, value &v) { v = sqlite3_value_int64(sv); }, /*[BOOLEAN] = */[](sqlite3_value *sv, value &v) { v = sqlite3_value_int(sv); }, /*[DOUBLE] = */[](sqlite3_value *sv, value &v) { v = sqlite3_value_double(sv); }, /*[SMALLINT] = */[](sqlite3_value *sv, value &v) { v = sqlite3_value_int(sv); }, /*[TINYINT] = */[](sqlite3_value *sv, value &v) { v = sqlite3_value_int(sv); }, }; mapping[type](sv,v); } parser::parser(table &table) : belong_to(table) { } // TODO 提高这个函数的性能和代码可读性 record parser::raw2rec(const char *raw, size_t raw_size) { auto &schema = belong_to.get_schema(); auto &cols = schema.get_columns(); auto offset = schema.get_offset(); auto cur_offset = 0; std::vector<value> values; std::vector<record::var_ptr> var_info; column_id_t cid = 0; for(const auto &col : cols) { auto type = col.get_type(); value v { }; if(type == col_type::CHAR || type == col_type::VARCHAR) { auto str = raw + offset; auto info = reinterpret_cast<const uint32_t*>(raw + cur_offset); auto off = info[0]; auto len = info[1]; // 带有结束符位置了 debug_only( std::cout << "in raw2rec: [off] = " << off << " [len] = " << len << std::endl; ); offset += len; v.ptr = new char[len]; memcpy(v.ptr, str, len); debug_only( std::cout << "in raw2rec: [pointer] = " << v.ptr << std::endl; // OK ); var_info.emplace_back(cid, off, len); } else { if(type == col_type::DOUBLE) v.f64 = *reinterpret_cast<const double*>(raw + cur_offset); else if(type == col_type::BIGINT) v.i64 = *reinterpret_cast<const int64_t*>(raw + cur_offset); else v.i32 = *reinterpret_cast<const int32_t*>(raw + cur_offset); // TODO 添加更多类型支持 } cur_offset += col_type_handler::size(type); ++cid; values.push_back(v); } return record(values, var_info, raw_size, true); // TODO 这种诡异写法有空改改,如果换成move就不用这样了 } size_t parser::rec2raw(const record &rec, char *&raw) { // 感觉没错 auto &schema = belong_to.get_schema(); auto &cols = schema.get_columns(); // assert cols.size() == rec.size() auto n = cols.size(); auto cur_offset = 0; // 类型的占位字节数 size_t n_byte = schema.get_offset(); // 全局 raw = new char[rec.get_raw_size()]; for(auto i = 0, j = 0; i < n; ++i) { auto &col = cols[i]; auto type = col.get_type(); auto v = rec.get(i); if(type == col_type::CHAR || type == col_type::VARCHAR) { auto &var_info = rec.get_var(j++); auto off = std::get<1>(var_info); auto len = std::get<2>(var_info); auto start = reinterpret_cast<uint32_t*>(raw + cur_offset); start[0] = off; start[1] = len; memcpy(raw + off, v.ptr, len); debug_only( std::cout << "[raw]: {" << (char*)(raw+off) << "}" << std::endl; // OK ); n_byte += len; } else { if(type == col_type::DOUBLE) *reinterpret_cast<double*>(raw + cur_offset) = v.f64; else if(type == col_type::BIGINT) *reinterpret_cast<int64_t*>(raw + cur_offset) = v.i64; else *reinterpret_cast<int32_t*>(raw + cur_offset) = v.i32; } auto size = col_type_handler::size(type); // n_byte += size; cur_offset += size; } return n_byte; }
[ "wasdjkl233@gmail.com" ]
wasdjkl233@gmail.com
b94183531713fcd66acb6d1e0b787ace5539abf9
2b6144aeefe48a5a9244c3560ffc91ed202f2fb6
/volna_init/external/boost/mpl/aux_/basic_bind.hpp
e825f09b32b90ab8a2af0f9a33b9e71636bcd608
[ "BSD-2-Clause" ]
permissive
reguly/volna
b867a63c3bd09fa234264cb2d01b8d8dd353ae27
6656d994c75f93d0f29673a8fc0da10926fa8d4a
refs/heads/master
2023-08-19T07:19:35.315350
2022-11-05T19:46:49
2022-11-05T19:46:49
40,645,334
4
8
BSD-2-Clause
2021-11-15T13:16:52
2015-08-13T07:36:57
C++
UTF-8
C++
false
false
659
hpp
#ifndef BOOST_MPL_AUX_BASIC_BIND_HPP_INCLUDED #define BOOST_MPL_AUX_BASIC_BIND_HPP_INCLUDED // Copyright Peter Dimov 2001 // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: basic_bind.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $ // $Revision: 49267 $ #define BOOST_MPL_CFG_NO_UNNAMED_PLACEHOLDER_SUPPORT #include <boost/mpl/bind.hpp> #endif // BOOST_MPL_AUX_BASIC_BIND_HPP_INCLUDED
[ "regulyistvan@gmail.com" ]
regulyistvan@gmail.com
82799e7f687707ee7df710817eb9bf17b901a5e3
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Trigger/TrigHypothesis/TrigAFPHypo/src/components/AFPJetHypo_entries.cxx
286e27c9de7a511b81c4e7d735df3fd2c476a442
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
415
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #include "TrigAFPHypo/TrigAFPJetAllTE.h" #include "GaudiKernel/DeclareFactoryEntries.h" DECLARE_ALGORITHM_FACTORY(TrigAFPJetAllTE) DECLARE_FACTORY_ENTRIES(TrigAFPHypo) { DECLARE_ALGORITHM(TrigAFPHypo) }
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
3502489bb1054537591ebaa17fb34bfbc9b9ee3d
68fcdd7779d30ec1fccbc3a2ab9839e9c5ddabed
/src/IEUCWFilteredESub.h
c25016b1e1101ce8927fb1397c73324337f6fe4c
[]
no_license
mjlyu/memory_repair_algoritm_sim
eede723da8c3d486294a428b882dd2a025d058b9
76af878f1002068edc6bc8b4362d6c2b016ffec0
refs/heads/master
2023-06-22T13:50:51.274143
2023-06-12T05:14:57
2023-06-12T05:14:57
224,158,821
1
0
null
null
null
null
UTF-8
C++
false
false
923
h
#ifndef _IEUCWFILTEREDESUB_H_ #define _IEUCWFILTEREDESUB_H_ #include "EUCDSub.h" class IEUCWFilteredSub:public EUCDSub { public: IEUCWFilteredSub(); IEUCWFilteredSub(const SubArray&); IEUCWFilteredSub(const EUCDSub&); IEUCWFilteredSub(const IEUCWFilteredSub&); ~IEUCWFilteredSub(); bool IEUCWs_repair(); // repair isolated EUCWs with remaining spares bool must_repair(); bool early_abort(); virtual bool repair_with_spare_row(uint32_t eRow); virtual bool repair_with_spare_col(uint32_t eCol); void isolated_EUCW_filter(void); virtual void initial(void); void update_EUCDCnt(void); void update_rowEUCWCnt(void); void update_EUCDsInIEUCWs(void); public: vector<EUCW> IEUCWs; // isolated EUCWs vector<ErrorNode> EUCDsInIEUCWs; // EUCDs in isolated EUCWs map<uint32_t, uint32_t> rowEUCDCnt; map<uint32_t, uint32_t> colEUCDCnt; map<uint32_t, uint32_t> rowEUCWCnt; }; #endif
[ "major.lyu@gmail.com" ]
major.lyu@gmail.com
11b40b9746aa21886c3648df42106bac86cfc5ce
b8a05a2e902632d1b02db12fb55ed0a7708405ba
/muduo/base/tests/ThreadLocal_test.cc
b43abe8f6ba29a95cb521b79225b740c440840b4
[ "BSD-3-Clause" ]
permissive
capeskychung/muduo2.0.0-with-comments
b7ff142db27826018bdfe141f093e08d8a46e972
c15f6ae747985728f4d5708c426a44a6e0cf5400
refs/heads/master
2021-10-09T00:25:51.793056
2018-12-19T08:17:48
2018-12-19T08:17:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
cc
#include <muduo/base/ThreadLocal.h> #include <muduo/base/CurrentThread.h> #include <muduo/base/Thread.h> #include <stdio.h> class Test : muduo::noncopyable { public: Test() { printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this); } ~Test() { printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str()); } const muduo::string& name() const { return name_; } void setName(const muduo::string& n) { name_ = n; } private: muduo::string name_; }; muduo::ThreadLocal<Test> testObj1; muduo::ThreadLocal<Test> testObj2; void print() { printf("tid=%d, obj1 %p name=%s\n", muduo::CurrentThread::tid(), &testObj1.value(), testObj1.value().name().c_str()); printf("tid=%d, obj2 %p name=%s\n", muduo::CurrentThread::tid(), &testObj2.value(), testObj2.value().name().c_str()); } void threadFunc() { print(); testObj1.value().setName("changed 1"); testObj2.value().setName("changed 42"); print(); } int main() { testObj1.value().setName("main one"); print(); muduo::Thread t1(threadFunc); t1.start(); t1.join(); testObj2.value().setName("main two"); print(); pthread_exit(0); //主线程退出,退当前线程 }
[ "yuying@iscas.ac.cn" ]
yuying@iscas.ac.cn
aa4f4267c6df47efa8755f7defebfad0aeb412b4
805e83058e2cb1c4042fe31a0c5f2aacf76eca63
/Glanda/DlgUndoRedo.h
0ef33870c82987bda38525edc5bf8ee0ca25d800
[]
no_license
progmalover/vc-stgld
70ee037f3f27857fcdbb344b5ee8533c724b43b9
96055b2a2deca44eed5bb2c6e1e3f6cb1aff3a6b
refs/heads/master
2021-01-12T05:17:05.334966
2017-01-12T14:49:44
2017-01-12T14:49:44
77,895,327
0
0
null
null
null
null
UTF-8
C++
false
false
718
h
#pragma once #include "UndoListBox.h" // CDlgUndo dialog class CDlgUndo : public CDialog { DECLARE_DYNAMIC(CDlgUndo) public: CDlgUndo(CWnd* pParent = NULL); // standard constructor virtual ~CDlgUndo(); // Dialog Data enum { IDD = IDD_UNDO }; DECLARE_SINGLETON(CDlgUndo) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: afx_msg LRESULT OnFloatStatus(WPARAM wParam, LPARAM); afx_msg void OnKillFocusList(); BOOL m_bUndo; CUndoListBox m_list; void LoadList(BOOL bUndo); BOOL TrackMessage(); void UpdateStatus(int nCurSel); virtual BOOL OnInitDialog(); afx_msg void OnStnClickedStaticStatus(); };
[ "zhangxiangyang@os-easy.com" ]
zhangxiangyang@os-easy.com
be655170196334ec6b495ebac9ac1972f8b229a4
37d0a09ac0e1934b7be49499dcbbb5ede4f51bff
/PRF192/PE/PE-03.31.20/Q6.cpp
b4f2fa9c6435eacabee07ac65c6eb7e0ca8a5daf
[]
no_license
phuongnv192/fptu-code
381878d74934a564710e2444fb59578b16b5f8ca
544a487bf2f195e4e718960092159df0be7aeed9
refs/heads/master
2023-06-15T22:02:02.964770
2021-07-13T11:30:38
2021-07-13T11:30:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
836
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> bool symmetric(int a[], int size) { int mid; if (size%2 == 1) mid = size/2; else mid = size/2 - 1; for (int i = 0; i <= mid; i++) { if (a[i] != a[size-1 - i]) { return false; } } return true; } int main() { system("cls"); //INPUT - @STUDENT:ADD YOUR CODE FOR INPUT HERE: int a[10], n; bool check = true; scanf("%d", &n); for (int i = 0; i<n; i++) { scanf("%d", &a[i]); } for (int i = 0; i<n; i++) { if (a[i]%2 == 0) { check = false; break; } } if (symmetric(a, n) == false) check = false; // Fixed Do not edit anything here. printf("\nOUTPUT:\n"); //@STUDENT: WRITE YOUR OUTPUT HERE: printf("%d", check); //--FIXED PART - DO NOT EDIT ANY THINGS HERE printf("\n"); system ("pause"); return(0); }
[ "46595837+lovegnouhp@users.noreply.github.com" ]
46595837+lovegnouhp@users.noreply.github.com
25b38bec9c55cae2db0d49f66feb066918d46655
76f0efb245ff0013e0428ee7636e72dc288832ab
/out/Default/gen/components/filesystem/public/interfaces/directory.mojom.cc
4076d0264f773b395c666bed369364a32ec2f9de
[]
no_license
dckristiono/chromium
e8845d2a8754f39e0ca1d3d3d44d01231957367c
8ad7c1bd5778bfda3347cf6b30ef60d3e4d7c0b9
refs/heads/master
2020-04-22T02:34:41.775069
2016-08-24T14:05:09
2016-08-24T14:05:09
66,465,243
0
2
null
null
null
null
UTF-8
C++
false
false
185,853
cc
// Copyright 2013 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. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4056) #pragma warning(disable:4065) #pragma warning(disable:4756) #endif #include "components/filesystem/public/interfaces/directory.mojom.h" #include <math.h> #include <stdint.h> #include <utility> #include "base/logging.h" #include "base/trace_event/trace_event.h" #include "mojo/public/cpp/bindings/lib/message_builder.h" #include "mojo/public/cpp/bindings/lib/serialization_util.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h" namespace filesystem { namespace mojom { namespace { class Directory_Read_ParamsDataView { public: Directory_Read_ParamsDataView() {} Directory_Read_ParamsDataView( internal::Directory_Read_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::Directory_Read_Params_Data* data_ = nullptr; }; class Directory_Read_ResponseParamsDataView { public: Directory_Read_ResponseParamsDataView() {} Directory_Read_ResponseParamsDataView( internal::Directory_Read_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } inline void GetDirectoryContentsDataView( mojo::ArrayDataView<::filesystem::mojom::DirectoryEntryDataView>* output); template <typename UserType> bool ReadDirectoryContents(UserType* output) { auto pointer = data_->directory_contents.Get(); return mojo::internal::Deserialize<mojo::Array<::filesystem::mojom::DirectoryEntryPtr>>( pointer, output, context_); } private: internal::Directory_Read_ResponseParams_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_Read_ResponseParamsDataView::GetDirectoryContentsDataView( mojo::ArrayDataView<::filesystem::mojom::DirectoryEntryDataView>* output) { auto pointer = data_->directory_contents.Get(); *output = mojo::ArrayDataView<::filesystem::mojom::DirectoryEntryDataView>(pointer, context_); } class Directory_OpenFile_ParamsDataView { public: Directory_OpenFile_ParamsDataView() {} Directory_OpenFile_ParamsDataView( internal::Directory_OpenFile_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } ::filesystem::mojom::FileRequest TakeFile() { ::filesystem::mojom::FileRequest result; bool ret = mojo::internal::Deserialize<::filesystem::mojom::FileRequest>( &data_->file, &result, context_); DCHECK(ret); return result; } uint32_t open_flags() const { return data_->open_flags; } private: internal::Directory_OpenFile_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_OpenFile_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_OpenFile_ResponseParamsDataView { public: Directory_OpenFile_ResponseParamsDataView() {} Directory_OpenFile_ResponseParamsDataView( internal::Directory_OpenFile_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } private: internal::Directory_OpenFile_ResponseParams_Data* data_ = nullptr; }; class Directory_OpenFileHandle_ParamsDataView { public: Directory_OpenFileHandle_ParamsDataView() {} Directory_OpenFileHandle_ParamsDataView( internal::Directory_OpenFileHandle_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } uint32_t open_flags() const { return data_->open_flags; } private: internal::Directory_OpenFileHandle_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_OpenFileHandle_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_OpenFileHandle_ResponseParamsDataView { public: Directory_OpenFileHandle_ResponseParamsDataView() {} Directory_OpenFileHandle_ResponseParamsDataView( internal::Directory_OpenFileHandle_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } mojo::ScopedHandle TakeFileHandle() { mojo::ScopedHandle result; bool ret = mojo::internal::Deserialize<mojo::ScopedHandle>( &data_->file_handle, &result, context_); DCHECK(ret); return result; } private: internal::Directory_OpenFileHandle_ResponseParams_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Directory_OpenFileHandles_ParamsDataView { public: Directory_OpenFileHandles_ParamsDataView() {} Directory_OpenFileHandles_ParamsDataView( internal::Directory_OpenFileHandles_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetFilesDataView( mojo::ArrayDataView<FileOpenDetailsDataView>* output); template <typename UserType> bool ReadFiles(UserType* output) { auto pointer = data_->files.Get(); return mojo::internal::Deserialize<mojo::Array<::filesystem::mojom::FileOpenDetailsPtr>>( pointer, output, context_); } private: internal::Directory_OpenFileHandles_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_OpenFileHandles_ParamsDataView::GetFilesDataView( mojo::ArrayDataView<FileOpenDetailsDataView>* output) { auto pointer = data_->files.Get(); *output = mojo::ArrayDataView<FileOpenDetailsDataView>(pointer, context_); } class Directory_OpenFileHandles_ResponseParamsDataView { public: Directory_OpenFileHandles_ResponseParamsDataView() {} Directory_OpenFileHandles_ResponseParamsDataView( internal::Directory_OpenFileHandles_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetResultsDataView( mojo::ArrayDataView<FileOpenResultDataView>* output); template <typename UserType> bool ReadResults(UserType* output) { auto pointer = data_->results.Get(); return mojo::internal::Deserialize<mojo::Array<::filesystem::mojom::FileOpenResultPtr>>( pointer, output, context_); } private: internal::Directory_OpenFileHandles_ResponseParams_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_OpenFileHandles_ResponseParamsDataView::GetResultsDataView( mojo::ArrayDataView<FileOpenResultDataView>* output) { auto pointer = data_->results.Get(); *output = mojo::ArrayDataView<FileOpenResultDataView>(pointer, context_); } class Directory_OpenDirectory_ParamsDataView { public: Directory_OpenDirectory_ParamsDataView() {} Directory_OpenDirectory_ParamsDataView( internal::Directory_OpenDirectory_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } DirectoryRequest TakeDirectory() { DirectoryRequest result; bool ret = mojo::internal::Deserialize<::filesystem::mojom::DirectoryRequest>( &data_->directory, &result, context_); DCHECK(ret); return result; } uint32_t open_flags() const { return data_->open_flags; } private: internal::Directory_OpenDirectory_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_OpenDirectory_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_OpenDirectory_ResponseParamsDataView { public: Directory_OpenDirectory_ResponseParamsDataView() {} Directory_OpenDirectory_ResponseParamsDataView( internal::Directory_OpenDirectory_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } private: internal::Directory_OpenDirectory_ResponseParams_Data* data_ = nullptr; }; class Directory_Rename_ParamsDataView { public: Directory_Rename_ParamsDataView() {} Directory_Rename_ParamsDataView( internal::Directory_Rename_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } inline void GetNewPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadNewPath(UserType* output) { auto pointer = data_->new_path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } private: internal::Directory_Rename_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_Rename_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } inline void Directory_Rename_ParamsDataView::GetNewPathDataView( mojo::StringDataView* output) { auto pointer = data_->new_path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_Rename_ResponseParamsDataView { public: Directory_Rename_ResponseParamsDataView() {} Directory_Rename_ResponseParamsDataView( internal::Directory_Rename_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } private: internal::Directory_Rename_ResponseParams_Data* data_ = nullptr; }; class Directory_Delete_ParamsDataView { public: Directory_Delete_ParamsDataView() {} Directory_Delete_ParamsDataView( internal::Directory_Delete_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } uint32_t delete_flags() const { return data_->delete_flags; } private: internal::Directory_Delete_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_Delete_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_Delete_ResponseParamsDataView { public: Directory_Delete_ResponseParamsDataView() {} Directory_Delete_ResponseParamsDataView( internal::Directory_Delete_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } private: internal::Directory_Delete_ResponseParams_Data* data_ = nullptr; }; class Directory_Exists_ParamsDataView { public: Directory_Exists_ParamsDataView() {} Directory_Exists_ParamsDataView( internal::Directory_Exists_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } private: internal::Directory_Exists_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_Exists_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_Exists_ResponseParamsDataView { public: Directory_Exists_ResponseParamsDataView() {} Directory_Exists_ResponseParamsDataView( internal::Directory_Exists_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } bool exists() const { return data_->exists; } private: internal::Directory_Exists_ResponseParams_Data* data_ = nullptr; }; class Directory_IsWritable_ParamsDataView { public: Directory_IsWritable_ParamsDataView() {} Directory_IsWritable_ParamsDataView( internal::Directory_IsWritable_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } private: internal::Directory_IsWritable_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_IsWritable_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_IsWritable_ResponseParamsDataView { public: Directory_IsWritable_ResponseParamsDataView() {} Directory_IsWritable_ResponseParamsDataView( internal::Directory_IsWritable_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } bool is_writable() const { return data_->is_writable; } private: internal::Directory_IsWritable_ResponseParams_Data* data_ = nullptr; }; class Directory_Flush_ParamsDataView { public: Directory_Flush_ParamsDataView() {} Directory_Flush_ParamsDataView( internal::Directory_Flush_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::Directory_Flush_Params_Data* data_ = nullptr; }; class Directory_Flush_ResponseParamsDataView { public: Directory_Flush_ResponseParamsDataView() {} Directory_Flush_ResponseParamsDataView( internal::Directory_Flush_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } private: internal::Directory_Flush_ResponseParams_Data* data_ = nullptr; }; class Directory_StatFile_ParamsDataView { public: Directory_StatFile_ParamsDataView() {} Directory_StatFile_ParamsDataView( internal::Directory_StatFile_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } private: internal::Directory_StatFile_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_StatFile_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_StatFile_ResponseParamsDataView { public: Directory_StatFile_ResponseParamsDataView() {} Directory_StatFile_ResponseParamsDataView( internal::Directory_StatFile_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } inline void GetFileInformationDataView( ::filesystem::mojom::FileInformationDataView* output); template <typename UserType> bool ReadFileInformation(UserType* output) { auto pointer = data_->file_information.Get(); return mojo::internal::Deserialize<::filesystem::mojom::FileInformationPtr>( pointer, output, context_); } private: internal::Directory_StatFile_ResponseParams_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_StatFile_ResponseParamsDataView::GetFileInformationDataView( ::filesystem::mojom::FileInformationDataView* output) { auto pointer = data_->file_information.Get(); *output = ::filesystem::mojom::FileInformationDataView(pointer, context_); } class Directory_Clone_ParamsDataView { public: Directory_Clone_ParamsDataView() {} Directory_Clone_ParamsDataView( internal::Directory_Clone_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } DirectoryRequest TakeDirectory() { DirectoryRequest result; bool ret = mojo::internal::Deserialize<::filesystem::mojom::DirectoryRequest>( &data_->directory, &result, context_); DCHECK(ret); return result; } private: internal::Directory_Clone_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Directory_ReadEntireFile_ParamsDataView { public: Directory_ReadEntireFile_ParamsDataView() {} Directory_ReadEntireFile_ParamsDataView( internal::Directory_ReadEntireFile_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } private: internal::Directory_ReadEntireFile_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_ReadEntireFile_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } class Directory_ReadEntireFile_ResponseParamsDataView { public: Directory_ReadEntireFile_ResponseParamsDataView() {} Directory_ReadEntireFile_ResponseParamsDataView( internal::Directory_ReadEntireFile_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } inline void GetDataDataView( mojo::ArrayDataView<uint8_t>* output); template <typename UserType> bool ReadData(UserType* output) { auto pointer = data_->data.Get(); return mojo::internal::Deserialize<mojo::Array<uint8_t>>( pointer, output, context_); } private: internal::Directory_ReadEntireFile_ResponseParams_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_ReadEntireFile_ResponseParamsDataView::GetDataDataView( mojo::ArrayDataView<uint8_t>* output) { auto pointer = data_->data.Get(); *output = mojo::ArrayDataView<uint8_t>(pointer, context_); } class Directory_WriteFile_ParamsDataView { public: Directory_WriteFile_ParamsDataView() {} Directory_WriteFile_ParamsDataView( internal::Directory_WriteFile_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetPathDataView( mojo::StringDataView* output); template <typename UserType> bool ReadPath(UserType* output) { auto pointer = data_->path.Get(); return mojo::internal::Deserialize<mojo::String>( pointer, output, context_); } inline void GetDataDataView( mojo::ArrayDataView<uint8_t>* output); template <typename UserType> bool ReadData(UserType* output) { auto pointer = data_->data.Get(); return mojo::internal::Deserialize<mojo::Array<uint8_t>>( pointer, output, context_); } private: internal::Directory_WriteFile_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void Directory_WriteFile_ParamsDataView::GetPathDataView( mojo::StringDataView* output) { auto pointer = data_->path.Get(); *output = mojo::StringDataView(pointer, context_); } inline void Directory_WriteFile_ParamsDataView::GetDataDataView( mojo::ArrayDataView<uint8_t>* output) { auto pointer = data_->data.Get(); *output = mojo::ArrayDataView<uint8_t>(pointer, context_); } class Directory_WriteFile_ResponseParamsDataView { public: Directory_WriteFile_ResponseParamsDataView() {} Directory_WriteFile_ResponseParamsDataView( internal::Directory_WriteFile_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> bool ReadError(UserType* output) const { auto data_value = data_->error; return mojo::internal::Deserialize<::filesystem::mojom::FileError>( data_value, output); } ::filesystem::mojom::FileError error() const { return static_cast<::filesystem::mojom::FileError>(data_->error); } private: internal::Directory_WriteFile_ResponseParams_Data* data_ = nullptr; }; } // namespace// static FileOpenDetailsPtr FileOpenDetails::New() { FileOpenDetailsPtr rv; mojo::internal::StructHelper<FileOpenDetails>::Initialize(&rv); return rv; } FileOpenDetails::FileOpenDetails() : path(nullptr), open_flags() { } FileOpenDetails::~FileOpenDetails() { }// static FileOpenResultPtr FileOpenResult::New() { FileOpenResultPtr rv; mojo::internal::StructHelper<FileOpenResult>::Initialize(&rv); return rv; } FileOpenResult::FileOpenResult() : path(nullptr), error(), file_handle() { } FileOpenResult::~FileOpenResult() { } const char Directory::Name_[] = "filesystem::mojom::Directory"; const uint32_t Directory::Version_; bool Directory::Read(::filesystem::mojom::FileError* error, mojo::Array<::filesystem::mojom::DirectoryEntryPtr>* directory_contents) { NOTREACHED(); return false; } bool Directory::OpenFile(const mojo::String& path, ::filesystem::mojom::FileRequest file, uint32_t open_flags, ::filesystem::mojom::FileError* error) { NOTREACHED(); return false; } bool Directory::OpenFileHandle(const mojo::String& path, uint32_t open_flags, ::filesystem::mojom::FileError* error, mojo::ScopedHandle* file_handle) { NOTREACHED(); return false; } bool Directory::OpenFileHandles(mojo::Array<FileOpenDetailsPtr> files, mojo::Array<FileOpenResultPtr>* results) { NOTREACHED(); return false; } bool Directory::OpenDirectory(const mojo::String& path, DirectoryRequest directory, uint32_t open_flags, ::filesystem::mojom::FileError* error) { NOTREACHED(); return false; } bool Directory::Rename(const mojo::String& path, const mojo::String& new_path, ::filesystem::mojom::FileError* error) { NOTREACHED(); return false; } bool Directory::Delete(const mojo::String& path, uint32_t delete_flags, ::filesystem::mojom::FileError* error) { NOTREACHED(); return false; } bool Directory::Exists(const mojo::String& path, ::filesystem::mojom::FileError* error, bool* exists) { NOTREACHED(); return false; } bool Directory::IsWritable(const mojo::String& path, ::filesystem::mojom::FileError* error, bool* is_writable) { NOTREACHED(); return false; } bool Directory::Flush(::filesystem::mojom::FileError* error) { NOTREACHED(); return false; } bool Directory::StatFile(const mojo::String& path, ::filesystem::mojom::FileError* error, ::filesystem::mojom::FileInformationPtr* file_information) { NOTREACHED(); return false; } bool Directory::ReadEntireFile(const mojo::String& path, ::filesystem::mojom::FileError* error, mojo::Array<uint8_t>* data) { NOTREACHED(); return false; } bool Directory::WriteFile(const mojo::String& path, mojo::Array<uint8_t> data, ::filesystem::mojom::FileError* error) { NOTREACHED(); return false; } class Directory_Read_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_Read_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error, mojo::Array<::filesystem::mojom::DirectoryEntryPtr>* out_directory_contents) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error), out_directory_contents_(out_directory_contents) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_; mojo::Array<::filesystem::mojom::DirectoryEntryPtr>* out_directory_contents_;DISALLOW_COPY_AND_ASSIGN(Directory_Read_HandleSyncResponse); }; bool Directory_Read_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_Read_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Read_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; mojo::Array<::filesystem::mojom::DirectoryEntryPtr> p_directory_contents{}; Directory_Read_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!input_data_view.ReadDirectoryContents(&p_directory_contents)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Read response deserializer"); return false; } *out_error_ = std::move(p_error); *out_directory_contents_ = std::move(p_directory_contents); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_Read_ForwardToCallback : public mojo::MessageReceiver { public: Directory_Read_ForwardToCallback( const Directory::ReadCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::ReadCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Read_ForwardToCallback); }; bool Directory_Read_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_Read_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Read_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; mojo::Array<::filesystem::mojom::DirectoryEntryPtr> p_directory_contents{}; Directory_Read_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!input_data_view.ReadDirectoryContents(&p_directory_contents)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Read response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error), std::move(p_directory_contents)); } return true; } class Directory_OpenFile_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_OpenFile_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_;DISALLOW_COPY_AND_ASSIGN(Directory_OpenFile_HandleSyncResponse); }; bool Directory_OpenFile_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_OpenFile_ResponseParams_Data* params = reinterpret_cast<internal::Directory_OpenFile_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_OpenFile_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFile response deserializer"); return false; } *out_error_ = std::move(p_error); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_OpenFile_ForwardToCallback : public mojo::MessageReceiver { public: Directory_OpenFile_ForwardToCallback( const Directory::OpenFileCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::OpenFileCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_OpenFile_ForwardToCallback); }; bool Directory_OpenFile_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_OpenFile_ResponseParams_Data* params = reinterpret_cast<internal::Directory_OpenFile_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_OpenFile_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFile response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error)); } return true; } class Directory_OpenFileHandle_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_OpenFileHandle_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error, mojo::ScopedHandle* out_file_handle) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error), out_file_handle_(out_file_handle) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_; mojo::ScopedHandle* out_file_handle_;DISALLOW_COPY_AND_ASSIGN(Directory_OpenFileHandle_HandleSyncResponse); }; bool Directory_OpenFileHandle_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_OpenFileHandle_ResponseParams_Data* params = reinterpret_cast<internal::Directory_OpenFileHandle_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; mojo::ScopedHandle p_file_handle{}; Directory_OpenFileHandle_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; p_file_handle = input_data_view.TakeFileHandle(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFileHandle response deserializer"); return false; } *out_error_ = std::move(p_error); *out_file_handle_ = std::move(p_file_handle); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_OpenFileHandle_ForwardToCallback : public mojo::MessageReceiver { public: Directory_OpenFileHandle_ForwardToCallback( const Directory::OpenFileHandleCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::OpenFileHandleCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_OpenFileHandle_ForwardToCallback); }; bool Directory_OpenFileHandle_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_OpenFileHandle_ResponseParams_Data* params = reinterpret_cast<internal::Directory_OpenFileHandle_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; mojo::ScopedHandle p_file_handle{}; Directory_OpenFileHandle_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; p_file_handle = input_data_view.TakeFileHandle(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFileHandle response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error), std::move(p_file_handle)); } return true; } class Directory_OpenFileHandles_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_OpenFileHandles_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, mojo::Array<FileOpenResultPtr>* out_results) : serialization_context_(std::move(group_controller)), result_(result), out_results_(out_results) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; mojo::Array<FileOpenResultPtr>* out_results_;DISALLOW_COPY_AND_ASSIGN(Directory_OpenFileHandles_HandleSyncResponse); }; bool Directory_OpenFileHandles_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_OpenFileHandles_ResponseParams_Data* params = reinterpret_cast<internal::Directory_OpenFileHandles_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::Array<FileOpenResultPtr> p_results{}; Directory_OpenFileHandles_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadResults(&p_results)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFileHandles response deserializer"); return false; } *out_results_ = std::move(p_results); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_OpenFileHandles_ForwardToCallback : public mojo::MessageReceiver { public: Directory_OpenFileHandles_ForwardToCallback( const Directory::OpenFileHandlesCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::OpenFileHandlesCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_OpenFileHandles_ForwardToCallback); }; bool Directory_OpenFileHandles_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_OpenFileHandles_ResponseParams_Data* params = reinterpret_cast<internal::Directory_OpenFileHandles_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::Array<FileOpenResultPtr> p_results{}; Directory_OpenFileHandles_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadResults(&p_results)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFileHandles response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_results)); } return true; } class Directory_OpenDirectory_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_OpenDirectory_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_;DISALLOW_COPY_AND_ASSIGN(Directory_OpenDirectory_HandleSyncResponse); }; bool Directory_OpenDirectory_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_OpenDirectory_ResponseParams_Data* params = reinterpret_cast<internal::Directory_OpenDirectory_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_OpenDirectory_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenDirectory response deserializer"); return false; } *out_error_ = std::move(p_error); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_OpenDirectory_ForwardToCallback : public mojo::MessageReceiver { public: Directory_OpenDirectory_ForwardToCallback( const Directory::OpenDirectoryCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::OpenDirectoryCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_OpenDirectory_ForwardToCallback); }; bool Directory_OpenDirectory_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_OpenDirectory_ResponseParams_Data* params = reinterpret_cast<internal::Directory_OpenDirectory_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_OpenDirectory_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenDirectory response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error)); } return true; } class Directory_Rename_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_Rename_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_;DISALLOW_COPY_AND_ASSIGN(Directory_Rename_HandleSyncResponse); }; bool Directory_Rename_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_Rename_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Rename_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_Rename_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Rename response deserializer"); return false; } *out_error_ = std::move(p_error); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_Rename_ForwardToCallback : public mojo::MessageReceiver { public: Directory_Rename_ForwardToCallback( const Directory::RenameCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::RenameCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Rename_ForwardToCallback); }; bool Directory_Rename_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_Rename_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Rename_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_Rename_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Rename response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error)); } return true; } class Directory_Delete_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_Delete_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_;DISALLOW_COPY_AND_ASSIGN(Directory_Delete_HandleSyncResponse); }; bool Directory_Delete_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_Delete_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Delete_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_Delete_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Delete response deserializer"); return false; } *out_error_ = std::move(p_error); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_Delete_ForwardToCallback : public mojo::MessageReceiver { public: Directory_Delete_ForwardToCallback( const Directory::DeleteCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::DeleteCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Delete_ForwardToCallback); }; bool Directory_Delete_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_Delete_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Delete_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_Delete_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Delete response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error)); } return true; } class Directory_Exists_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_Exists_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error, bool* out_exists) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error), out_exists_(out_exists) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_; bool* out_exists_;DISALLOW_COPY_AND_ASSIGN(Directory_Exists_HandleSyncResponse); }; bool Directory_Exists_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_Exists_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Exists_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; bool p_exists{}; Directory_Exists_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; p_exists = input_data_view.exists(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Exists response deserializer"); return false; } *out_error_ = std::move(p_error); *out_exists_ = std::move(p_exists); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_Exists_ForwardToCallback : public mojo::MessageReceiver { public: Directory_Exists_ForwardToCallback( const Directory::ExistsCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::ExistsCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Exists_ForwardToCallback); }; bool Directory_Exists_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_Exists_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Exists_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; bool p_exists{}; Directory_Exists_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; p_exists = input_data_view.exists(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Exists response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error), std::move(p_exists)); } return true; } class Directory_IsWritable_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_IsWritable_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error, bool* out_is_writable) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error), out_is_writable_(out_is_writable) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_; bool* out_is_writable_;DISALLOW_COPY_AND_ASSIGN(Directory_IsWritable_HandleSyncResponse); }; bool Directory_IsWritable_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_IsWritable_ResponseParams_Data* params = reinterpret_cast<internal::Directory_IsWritable_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; bool p_is_writable{}; Directory_IsWritable_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; p_is_writable = input_data_view.is_writable(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::IsWritable response deserializer"); return false; } *out_error_ = std::move(p_error); *out_is_writable_ = std::move(p_is_writable); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_IsWritable_ForwardToCallback : public mojo::MessageReceiver { public: Directory_IsWritable_ForwardToCallback( const Directory::IsWritableCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::IsWritableCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_IsWritable_ForwardToCallback); }; bool Directory_IsWritable_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_IsWritable_ResponseParams_Data* params = reinterpret_cast<internal::Directory_IsWritable_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; bool p_is_writable{}; Directory_IsWritable_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; p_is_writable = input_data_view.is_writable(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::IsWritable response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error), std::move(p_is_writable)); } return true; } class Directory_Flush_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_Flush_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_;DISALLOW_COPY_AND_ASSIGN(Directory_Flush_HandleSyncResponse); }; bool Directory_Flush_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_Flush_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Flush_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_Flush_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Flush response deserializer"); return false; } *out_error_ = std::move(p_error); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_Flush_ForwardToCallback : public mojo::MessageReceiver { public: Directory_Flush_ForwardToCallback( const Directory::FlushCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::FlushCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Flush_ForwardToCallback); }; bool Directory_Flush_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_Flush_ResponseParams_Data* params = reinterpret_cast<internal::Directory_Flush_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_Flush_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Flush response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error)); } return true; } class Directory_StatFile_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_StatFile_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error, ::filesystem::mojom::FileInformationPtr* out_file_information) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error), out_file_information_(out_file_information) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_; ::filesystem::mojom::FileInformationPtr* out_file_information_;DISALLOW_COPY_AND_ASSIGN(Directory_StatFile_HandleSyncResponse); }; bool Directory_StatFile_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_StatFile_ResponseParams_Data* params = reinterpret_cast<internal::Directory_StatFile_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; ::filesystem::mojom::FileInformationPtr p_file_information{}; Directory_StatFile_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!input_data_view.ReadFileInformation(&p_file_information)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::StatFile response deserializer"); return false; } *out_error_ = std::move(p_error); *out_file_information_ = std::move(p_file_information); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_StatFile_ForwardToCallback : public mojo::MessageReceiver { public: Directory_StatFile_ForwardToCallback( const Directory::StatFileCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::StatFileCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_StatFile_ForwardToCallback); }; bool Directory_StatFile_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_StatFile_ResponseParams_Data* params = reinterpret_cast<internal::Directory_StatFile_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; ::filesystem::mojom::FileInformationPtr p_file_information{}; Directory_StatFile_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!input_data_view.ReadFileInformation(&p_file_information)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::StatFile response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error), std::move(p_file_information)); } return true; } class Directory_ReadEntireFile_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_ReadEntireFile_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error, mojo::Array<uint8_t>* out_data) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error), out_data_(out_data) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_; mojo::Array<uint8_t>* out_data_;DISALLOW_COPY_AND_ASSIGN(Directory_ReadEntireFile_HandleSyncResponse); }; bool Directory_ReadEntireFile_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_ReadEntireFile_ResponseParams_Data* params = reinterpret_cast<internal::Directory_ReadEntireFile_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; mojo::Array<uint8_t> p_data{}; Directory_ReadEntireFile_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!input_data_view.ReadData(&p_data)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::ReadEntireFile response deserializer"); return false; } *out_error_ = std::move(p_error); *out_data_ = std::move(p_data); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_ReadEntireFile_ForwardToCallback : public mojo::MessageReceiver { public: Directory_ReadEntireFile_ForwardToCallback( const Directory::ReadEntireFileCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::ReadEntireFileCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_ReadEntireFile_ForwardToCallback); }; bool Directory_ReadEntireFile_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_ReadEntireFile_ResponseParams_Data* params = reinterpret_cast<internal::Directory_ReadEntireFile_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; mojo::Array<uint8_t> p_data{}; Directory_ReadEntireFile_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!input_data_view.ReadData(&p_data)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::ReadEntireFile response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error), std::move(p_data)); } return true; } class Directory_WriteFile_HandleSyncResponse : public mojo::MessageReceiver { public: Directory_WriteFile_HandleSyncResponse( scoped_refptr<mojo::AssociatedGroupController> group_controller, bool* result, ::filesystem::mojom::FileError* out_error) : serialization_context_(std::move(group_controller)), result_(result), out_error_(out_error) { DCHECK(!*result_); } bool Accept(mojo::Message* message) override; private: mojo::internal::SerializationContext serialization_context_; bool* result_; ::filesystem::mojom::FileError* out_error_;DISALLOW_COPY_AND_ASSIGN(Directory_WriteFile_HandleSyncResponse); }; bool Directory_WriteFile_HandleSyncResponse::Accept( mojo::Message* message) { internal::Directory_WriteFile_ResponseParams_Data* params = reinterpret_cast<internal::Directory_WriteFile_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_WriteFile_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::WriteFile response deserializer"); return false; } *out_error_ = std::move(p_error); mojo::internal::SyncMessageResponseSetup::SetCurrentSyncResponseMessage( message); *result_ = true; return true; } class Directory_WriteFile_ForwardToCallback : public mojo::MessageReceiver { public: Directory_WriteFile_ForwardToCallback( const Directory::WriteFileCallback& callback, scoped_refptr<mojo::AssociatedGroupController> group_controller) : callback_(callback), serialization_context_(std::move(group_controller)) { } bool Accept(mojo::Message* message) override; private: Directory::WriteFileCallback callback_; mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_WriteFile_ForwardToCallback); }; bool Directory_WriteFile_ForwardToCallback::Accept( mojo::Message* message) { internal::Directory_WriteFile_ResponseParams_Data* params = reinterpret_cast<internal::Directory_WriteFile_ResponseParams_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; ::filesystem::mojom::FileError p_error{}; Directory_WriteFile_ResponseParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadError(&p_error)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::WriteFile response deserializer"); return false; } if (!callback_.is_null()) { mojo::internal::MessageDispatchContext context(message); callback_.Run( std::move(p_error)); } return true; } DirectoryProxy::DirectoryProxy(mojo::MessageReceiverWithResponder* receiver) : ControlMessageProxy(receiver) { } bool DirectoryProxy::Read( ::filesystem::mojom::FileError* param_error, mojo::Array<::filesystem::mojom::DirectoryEntryPtr>* param_directory_contents) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Read_Params_Data); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Read_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_Read_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_Read_HandleSyncResponse( serialization_context_.group_controller, &result, param_error, param_directory_contents); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::Read( const ReadCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Read_Params_Data); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Read_Name, size); auto params = ::filesystem::mojom::internal::Directory_Read_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_Read_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::OpenFile( const mojo::String& param_path, ::filesystem::mojom::FileRequest param_file, uint32_t param_open_flags, ::filesystem::mojom::FileError* param_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFile_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_OpenFile_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_OpenFile_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.OpenFile request"); mojo::internal::Serialize<::filesystem::mojom::FileRequest>( param_file, &params->file, &serialization_context_); params->open_flags = param_open_flags; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_OpenFile_HandleSyncResponse( serialization_context_.group_controller, &result, param_error); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::OpenFile( const mojo::String& in_path, ::filesystem::mojom::FileRequest in_file, uint32_t in_open_flags, const OpenFileCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFile_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_OpenFile_Name, size); auto params = ::filesystem::mojom::internal::Directory_OpenFile_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.OpenFile request"); mojo::internal::Serialize<::filesystem::mojom::FileRequest>( in_file, &params->file, &serialization_context_); params->open_flags = in_open_flags; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_OpenFile_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::OpenFileHandle( const mojo::String& param_path, uint32_t param_open_flags, ::filesystem::mojom::FileError* param_error, mojo::ScopedHandle* param_file_handle) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFileHandle_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_OpenFileHandle_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_OpenFileHandle_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.OpenFileHandle request"); params->open_flags = param_open_flags; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_OpenFileHandle_HandleSyncResponse( serialization_context_.group_controller, &result, param_error, param_file_handle); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::OpenFileHandle( const mojo::String& in_path, uint32_t in_open_flags, const OpenFileHandleCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFileHandle_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_OpenFileHandle_Name, size); auto params = ::filesystem::mojom::internal::Directory_OpenFileHandle_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.OpenFileHandle request"); params->open_flags = in_open_flags; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_OpenFileHandle_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::OpenFileHandles( mojo::Array<FileOpenDetailsPtr> param_files, mojo::Array<FileOpenResultPtr>* param_results) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFileHandles_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::Array<::filesystem::mojom::FileOpenDetailsPtr>>( param_files, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_OpenFileHandles_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_OpenFileHandles_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->files)::BaseType* files_ptr; const mojo::internal::ContainerValidateParams files_validate_params( 0, false, nullptr); mojo::internal::Serialize<mojo::Array<::filesystem::mojom::FileOpenDetailsPtr>>( param_files, builder.buffer(), &files_ptr, &files_validate_params, &serialization_context_); params->files.Set(files_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->files.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null files in Directory.OpenFileHandles request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_OpenFileHandles_HandleSyncResponse( serialization_context_.group_controller, &result, param_results); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::OpenFileHandles( mojo::Array<FileOpenDetailsPtr> in_files, const OpenFileHandlesCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFileHandles_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::Array<::filesystem::mojom::FileOpenDetailsPtr>>( in_files, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_OpenFileHandles_Name, size); auto params = ::filesystem::mojom::internal::Directory_OpenFileHandles_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->files)::BaseType* files_ptr; const mojo::internal::ContainerValidateParams files_validate_params( 0, false, nullptr); mojo::internal::Serialize<mojo::Array<::filesystem::mojom::FileOpenDetailsPtr>>( in_files, builder.buffer(), &files_ptr, &files_validate_params, &serialization_context_); params->files.Set(files_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->files.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null files in Directory.OpenFileHandles request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_OpenFileHandles_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::OpenDirectory( const mojo::String& param_path, DirectoryRequest param_directory, uint32_t param_open_flags, ::filesystem::mojom::FileError* param_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenDirectory_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_OpenDirectory_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_OpenDirectory_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.OpenDirectory request"); mojo::internal::Serialize<::filesystem::mojom::DirectoryRequest>( param_directory, &params->directory, &serialization_context_); params->open_flags = param_open_flags; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_OpenDirectory_HandleSyncResponse( serialization_context_.group_controller, &result, param_error); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::OpenDirectory( const mojo::String& in_path, DirectoryRequest in_directory, uint32_t in_open_flags, const OpenDirectoryCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenDirectory_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_OpenDirectory_Name, size); auto params = ::filesystem::mojom::internal::Directory_OpenDirectory_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.OpenDirectory request"); mojo::internal::Serialize<::filesystem::mojom::DirectoryRequest>( in_directory, &params->directory, &serialization_context_); params->open_flags = in_open_flags; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_OpenDirectory_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::Rename( const mojo::String& param_path, const mojo::String& param_new_path, ::filesystem::mojom::FileError* param_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Rename_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); size += mojo::internal::PrepareToSerialize<mojo::String>( param_new_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Rename_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_Rename_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.Rename request"); typename decltype(params->new_path)::BaseType* new_path_ptr; mojo::internal::Serialize<mojo::String>( param_new_path, builder.buffer(), &new_path_ptr, &serialization_context_); params->new_path.Set(new_path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->new_path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null new_path in Directory.Rename request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_Rename_HandleSyncResponse( serialization_context_.group_controller, &result, param_error); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::Rename( const mojo::String& in_path, const mojo::String& in_new_path, const RenameCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Rename_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); size += mojo::internal::PrepareToSerialize<mojo::String>( in_new_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Rename_Name, size); auto params = ::filesystem::mojom::internal::Directory_Rename_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.Rename request"); typename decltype(params->new_path)::BaseType* new_path_ptr; mojo::internal::Serialize<mojo::String>( in_new_path, builder.buffer(), &new_path_ptr, &serialization_context_); params->new_path.Set(new_path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->new_path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null new_path in Directory.Rename request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_Rename_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::Delete( const mojo::String& param_path, uint32_t param_delete_flags, ::filesystem::mojom::FileError* param_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Delete_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Delete_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_Delete_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.Delete request"); params->delete_flags = param_delete_flags; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_Delete_HandleSyncResponse( serialization_context_.group_controller, &result, param_error); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::Delete( const mojo::String& in_path, uint32_t in_delete_flags, const DeleteCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Delete_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Delete_Name, size); auto params = ::filesystem::mojom::internal::Directory_Delete_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.Delete request"); params->delete_flags = in_delete_flags; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_Delete_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::Exists( const mojo::String& param_path, ::filesystem::mojom::FileError* param_error, bool* param_exists) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Exists_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Exists_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_Exists_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.Exists request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_Exists_HandleSyncResponse( serialization_context_.group_controller, &result, param_error, param_exists); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::Exists( const mojo::String& in_path, const ExistsCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Exists_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Exists_Name, size); auto params = ::filesystem::mojom::internal::Directory_Exists_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.Exists request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_Exists_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::IsWritable( const mojo::String& param_path, ::filesystem::mojom::FileError* param_error, bool* param_is_writable) { size_t size = sizeof(::filesystem::mojom::internal::Directory_IsWritable_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_IsWritable_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_IsWritable_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.IsWritable request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_IsWritable_HandleSyncResponse( serialization_context_.group_controller, &result, param_error, param_is_writable); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::IsWritable( const mojo::String& in_path, const IsWritableCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_IsWritable_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_IsWritable_Name, size); auto params = ::filesystem::mojom::internal::Directory_IsWritable_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.IsWritable request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_IsWritable_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::Flush( ::filesystem::mojom::FileError* param_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Flush_Params_Data); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Flush_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_Flush_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_Flush_HandleSyncResponse( serialization_context_.group_controller, &result, param_error); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::Flush( const FlushCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Flush_Params_Data); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_Flush_Name, size); auto params = ::filesystem::mojom::internal::Directory_Flush_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_Flush_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::StatFile( const mojo::String& param_path, ::filesystem::mojom::FileError* param_error, ::filesystem::mojom::FileInformationPtr* param_file_information) { size_t size = sizeof(::filesystem::mojom::internal::Directory_StatFile_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_StatFile_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_StatFile_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.StatFile request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_StatFile_HandleSyncResponse( serialization_context_.group_controller, &result, param_error, param_file_information); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::StatFile( const mojo::String& in_path, const StatFileCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_StatFile_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_StatFile_Name, size); auto params = ::filesystem::mojom::internal::Directory_StatFile_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.StatFile request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_StatFile_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } void DirectoryProxy::Clone( DirectoryRequest in_directory) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Clone_Params_Data); mojo::internal::MessageBuilder builder(internal::kDirectory_Clone_Name, size); auto params = ::filesystem::mojom::internal::Directory_Clone_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::DirectoryRequest>( in_directory, &params->directory, &serialization_context_); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( !mojo::internal::IsHandleOrInterfaceValid(params->directory), mojo::internal::VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE, "invalid directory in Directory.Clone request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = receiver_->Accept(builder.message()); // This return value may be ignored as !ok implies the Connector has // encountered an error, which will be visible through other means. ALLOW_UNUSED_LOCAL(ok); } bool DirectoryProxy::ReadEntireFile( const mojo::String& param_path, ::filesystem::mojom::FileError* param_error, mojo::Array<uint8_t>* param_data) { size_t size = sizeof(::filesystem::mojom::internal::Directory_ReadEntireFile_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_ReadEntireFile_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_ReadEntireFile_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.ReadEntireFile request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_ReadEntireFile_HandleSyncResponse( serialization_context_.group_controller, &result, param_error, param_data); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::ReadEntireFile( const mojo::String& in_path, const ReadEntireFileCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_ReadEntireFile_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_ReadEntireFile_Name, size); auto params = ::filesystem::mojom::internal::Directory_ReadEntireFile_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.ReadEntireFile request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_ReadEntireFile_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } bool DirectoryProxy::WriteFile( const mojo::String& param_path, mojo::Array<uint8_t> param_data, ::filesystem::mojom::FileError* param_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_WriteFile_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( param_path, &serialization_context_); size += mojo::internal::PrepareToSerialize<mojo::Array<uint8_t>>( param_data, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_WriteFile_Name, size, mojo::Message::kFlagIsSync); auto params = ::filesystem::mojom::internal::Directory_WriteFile_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( param_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.WriteFile request"); typename decltype(params->data)::BaseType* data_ptr; const mojo::internal::ContainerValidateParams data_validate_params( 0, false, nullptr); mojo::internal::Serialize<mojo::Array<uint8_t>>( param_data, builder.buffer(), &data_ptr, &data_validate_params, &serialization_context_); params->data.Set(data_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->data.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null data in Directory.WriteFile request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool result = false; mojo::MessageReceiver* responder = new Directory_WriteFile_HandleSyncResponse( serialization_context_.group_controller, &result, param_error); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; return result; } void DirectoryProxy::WriteFile( const mojo::String& in_path, mojo::Array<uint8_t> in_data, const WriteFileCallback& callback) { size_t size = sizeof(::filesystem::mojom::internal::Directory_WriteFile_Params_Data); size += mojo::internal::PrepareToSerialize<mojo::String>( in_path, &serialization_context_); size += mojo::internal::PrepareToSerialize<mojo::Array<uint8_t>>( in_data, &serialization_context_); mojo::internal::RequestMessageBuilder builder(internal::kDirectory_WriteFile_Name, size); auto params = ::filesystem::mojom::internal::Directory_WriteFile_Params_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->path)::BaseType* path_ptr; mojo::internal::Serialize<mojo::String>( in_path, builder.buffer(), &path_ptr, &serialization_context_); params->path.Set(path_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->path.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null path in Directory.WriteFile request"); typename decltype(params->data)::BaseType* data_ptr; const mojo::internal::ContainerValidateParams data_validate_params( 0, false, nullptr); mojo::internal::Serialize<mojo::Array<uint8_t>>( in_data, builder.buffer(), &data_ptr, &data_validate_params, &serialization_context_); params->data.Set(data_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->data.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null data in Directory.WriteFile request"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); mojo::MessageReceiver* responder = new Directory_WriteFile_ForwardToCallback( callback, serialization_context_.group_controller); if (!receiver_->AcceptWithResponder(builder.message(), responder)) delete responder; } class Directory_Read_ProxyToResponder { public: static Directory::ReadCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_Read_ProxyToResponder> proxy( new Directory_Read_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_Read_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_Read_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::Read() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_Read_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error, mojo::Array<::filesystem::mojom::DirectoryEntryPtr> in_directory_contents); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Read_ProxyToResponder); }; void Directory_Read_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error, mojo::Array<::filesystem::mojom::DirectoryEntryPtr> in_directory_contents) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Read_ResponseParams_Data); size += mojo::internal::PrepareToSerialize<mojo::Array<::filesystem::mojom::DirectoryEntryPtr>>( in_directory_contents, &serialization_context_); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_Read_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_Read_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); typename decltype(params->directory_contents)::BaseType* directory_contents_ptr; const mojo::internal::ContainerValidateParams directory_contents_validate_params( 0, false, nullptr); mojo::internal::Serialize<mojo::Array<::filesystem::mojom::DirectoryEntryPtr>>( in_directory_contents, builder.buffer(), &directory_contents_ptr, &directory_contents_validate_params, &serialization_context_); params->directory_contents.Set(directory_contents_ptr); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_OpenFile_ProxyToResponder { public: static Directory::OpenFileCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_OpenFile_ProxyToResponder> proxy( new Directory_OpenFile_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_OpenFile_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_OpenFile_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::OpenFile() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_OpenFile_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_OpenFile_ProxyToResponder); }; void Directory_OpenFile_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFile_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_OpenFile_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_OpenFile_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_OpenFileHandle_ProxyToResponder { public: static Directory::OpenFileHandleCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_OpenFileHandle_ProxyToResponder> proxy( new Directory_OpenFileHandle_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_OpenFileHandle_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_OpenFileHandle_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::OpenFileHandle() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_OpenFileHandle_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error, mojo::ScopedHandle in_file_handle); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_OpenFileHandle_ProxyToResponder); }; void Directory_OpenFileHandle_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error, mojo::ScopedHandle in_file_handle) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFileHandle_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_OpenFileHandle_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_OpenFileHandle_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); mojo::internal::Serialize<mojo::ScopedHandle>( in_file_handle, &params->file_handle, &serialization_context_); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( !mojo::internal::IsHandleOrInterfaceValid(params->file_handle), mojo::internal::VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE, "invalid file_handle in Directory.OpenFileHandle response"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_OpenFileHandles_ProxyToResponder { public: static Directory::OpenFileHandlesCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_OpenFileHandles_ProxyToResponder> proxy( new Directory_OpenFileHandles_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_OpenFileHandles_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_OpenFileHandles_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::OpenFileHandles() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_OpenFileHandles_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( mojo::Array<FileOpenResultPtr> in_results); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_OpenFileHandles_ProxyToResponder); }; void Directory_OpenFileHandles_ProxyToResponder::Run( mojo::Array<FileOpenResultPtr> in_results) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenFileHandles_ResponseParams_Data); size += mojo::internal::PrepareToSerialize<mojo::Array<::filesystem::mojom::FileOpenResultPtr>>( in_results, &serialization_context_); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_OpenFileHandles_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_OpenFileHandles_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); typename decltype(params->results)::BaseType* results_ptr; const mojo::internal::ContainerValidateParams results_validate_params( 0, false, nullptr); mojo::internal::Serialize<mojo::Array<::filesystem::mojom::FileOpenResultPtr>>( in_results, builder.buffer(), &results_ptr, &results_validate_params, &serialization_context_); params->results.Set(results_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->results.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null results in Directory.OpenFileHandles response"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_OpenDirectory_ProxyToResponder { public: static Directory::OpenDirectoryCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_OpenDirectory_ProxyToResponder> proxy( new Directory_OpenDirectory_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_OpenDirectory_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_OpenDirectory_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::OpenDirectory() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_OpenDirectory_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_OpenDirectory_ProxyToResponder); }; void Directory_OpenDirectory_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_OpenDirectory_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_OpenDirectory_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_OpenDirectory_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_Rename_ProxyToResponder { public: static Directory::RenameCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_Rename_ProxyToResponder> proxy( new Directory_Rename_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_Rename_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_Rename_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::Rename() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_Rename_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Rename_ProxyToResponder); }; void Directory_Rename_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Rename_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_Rename_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_Rename_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_Delete_ProxyToResponder { public: static Directory::DeleteCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_Delete_ProxyToResponder> proxy( new Directory_Delete_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_Delete_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_Delete_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::Delete() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_Delete_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Delete_ProxyToResponder); }; void Directory_Delete_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Delete_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_Delete_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_Delete_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_Exists_ProxyToResponder { public: static Directory::ExistsCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_Exists_ProxyToResponder> proxy( new Directory_Exists_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_Exists_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_Exists_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::Exists() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_Exists_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error, bool in_exists); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Exists_ProxyToResponder); }; void Directory_Exists_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error, bool in_exists) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Exists_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_Exists_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_Exists_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); params->exists = in_exists; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_IsWritable_ProxyToResponder { public: static Directory::IsWritableCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_IsWritable_ProxyToResponder> proxy( new Directory_IsWritable_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_IsWritable_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_IsWritable_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::IsWritable() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_IsWritable_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error, bool in_is_writable); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_IsWritable_ProxyToResponder); }; void Directory_IsWritable_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error, bool in_is_writable) { size_t size = sizeof(::filesystem::mojom::internal::Directory_IsWritable_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_IsWritable_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_IsWritable_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); params->is_writable = in_is_writable; (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_Flush_ProxyToResponder { public: static Directory::FlushCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_Flush_ProxyToResponder> proxy( new Directory_Flush_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_Flush_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_Flush_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::Flush() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_Flush_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_Flush_ProxyToResponder); }; void Directory_Flush_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_Flush_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_Flush_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_Flush_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_StatFile_ProxyToResponder { public: static Directory::StatFileCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_StatFile_ProxyToResponder> proxy( new Directory_StatFile_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_StatFile_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_StatFile_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::StatFile() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_StatFile_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error, ::filesystem::mojom::FileInformationPtr in_file_information); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_StatFile_ProxyToResponder); }; void Directory_StatFile_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error, ::filesystem::mojom::FileInformationPtr in_file_information) { size_t size = sizeof(::filesystem::mojom::internal::Directory_StatFile_ResponseParams_Data); size += mojo::internal::PrepareToSerialize<::filesystem::mojom::FileInformationPtr>( in_file_information, &serialization_context_); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_StatFile_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_StatFile_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); typename decltype(params->file_information)::BaseType* file_information_ptr; mojo::internal::Serialize<::filesystem::mojom::FileInformationPtr>( in_file_information, builder.buffer(), &file_information_ptr, &serialization_context_); params->file_information.Set(file_information_ptr); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_ReadEntireFile_ProxyToResponder { public: static Directory::ReadEntireFileCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_ReadEntireFile_ProxyToResponder> proxy( new Directory_ReadEntireFile_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_ReadEntireFile_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_ReadEntireFile_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::ReadEntireFile() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_ReadEntireFile_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error, mojo::Array<uint8_t> in_data); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_ReadEntireFile_ProxyToResponder); }; void Directory_ReadEntireFile_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error, mojo::Array<uint8_t> in_data) { size_t size = sizeof(::filesystem::mojom::internal::Directory_ReadEntireFile_ResponseParams_Data); size += mojo::internal::PrepareToSerialize<mojo::Array<uint8_t>>( in_data, &serialization_context_); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_ReadEntireFile_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_ReadEntireFile_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); typename decltype(params->data)::BaseType* data_ptr; const mojo::internal::ContainerValidateParams data_validate_params( 0, false, nullptr); mojo::internal::Serialize<mojo::Array<uint8_t>>( in_data, builder.buffer(), &data_ptr, &data_validate_params, &serialization_context_); params->data.Set(data_ptr); MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING( params->data.is_null(), mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER, "null data in Directory.ReadEntireFile response"); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } class Directory_WriteFile_ProxyToResponder { public: static Directory::WriteFileCallback CreateCallback( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) { std::unique_ptr<Directory_WriteFile_ProxyToResponder> proxy( new Directory_WriteFile_ProxyToResponder( request_id, is_sync, responder, group_controller)); return base::Bind(&Directory_WriteFile_ProxyToResponder::Run, base::Passed(&proxy)); } ~Directory_WriteFile_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // Is the Mojo application destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " "Directory::WriteFile() was never run."); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. delete responder_; } private: Directory_WriteFile_ProxyToResponder( uint64_t request_id, bool is_sync, mojo::MessageReceiverWithStatus* responder, scoped_refptr<mojo::AssociatedGroupController> group_controller) : request_id_(request_id), is_sync_(is_sync), responder_(responder), serialization_context_(std::move(group_controller)) { } void Run( ::filesystem::mojom::FileError in_error); uint64_t request_id_; bool is_sync_; mojo::MessageReceiverWithStatus* responder_; // TODO(yzshen): maybe I should use a ref to the original one? mojo::internal::SerializationContext serialization_context_; DISALLOW_COPY_AND_ASSIGN(Directory_WriteFile_ProxyToResponder); }; void Directory_WriteFile_ProxyToResponder::Run( ::filesystem::mojom::FileError in_error) { size_t size = sizeof(::filesystem::mojom::internal::Directory_WriteFile_ResponseParams_Data); mojo::internal::ResponseMessageBuilder builder( internal::kDirectory_WriteFile_Name, size, request_id_, is_sync_ ? mojo::Message::kFlagIsSync : 0); auto params = ::filesystem::mojom::internal::Directory_WriteFile_ResponseParams_Data::New(builder.buffer()); ALLOW_UNUSED_LOCAL(params); mojo::internal::Serialize<::filesystem::mojom::FileError>( in_error, &params->error); (&serialization_context_)->handles.Swap( builder.message()->mutable_handles()); bool ok = responder_->Accept(builder.message()); ALLOW_UNUSED_LOCAL(ok); // TODO(darin): !ok returned here indicates a malformed message, and that may // be good reason to close the connection. However, we don't have a way to do // that from here. We should add a way. delete responder_; responder_ = nullptr; } DirectoryStub::DirectoryStub() : sink_(nullptr), control_message_handler_(Directory::Version_) { } DirectoryStub::~DirectoryStub() {} bool DirectoryStub::Accept(mojo::Message* message) { if (mojo::internal::ControlMessageHandler::IsControlMessage(message)) return control_message_handler_.Accept(message); switch (message->header()->name) { case internal::kDirectory_Read_Name: { break; } case internal::kDirectory_OpenFile_Name: { break; } case internal::kDirectory_OpenFileHandle_Name: { break; } case internal::kDirectory_OpenFileHandles_Name: { break; } case internal::kDirectory_OpenDirectory_Name: { break; } case internal::kDirectory_Rename_Name: { break; } case internal::kDirectory_Delete_Name: { break; } case internal::kDirectory_Exists_Name: { break; } case internal::kDirectory_IsWritable_Name: { break; } case internal::kDirectory_Flush_Name: { break; } case internal::kDirectory_StatFile_Name: { break; } case internal::kDirectory_Clone_Name: { internal::Directory_Clone_Params_Data* params = reinterpret_cast<internal::Directory_Clone_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; DirectoryRequest p_directory{}; Directory_Clone_ParamsDataView input_data_view(params, &serialization_context_); p_directory = input_data_view.TakeDirectory(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Clone deserializer"); return false; } // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::Clone"); mojo::internal::MessageDispatchContext context(message); sink_->Clone( std::move(p_directory)); return true; } case internal::kDirectory_ReadEntireFile_Name: { break; } case internal::kDirectory_WriteFile_Name: { break; } } return false; } bool DirectoryStub::AcceptWithResponder( mojo::Message* message, mojo::MessageReceiverWithStatus* responder) { if (mojo::internal::ControlMessageHandler::IsControlMessage(message)) return control_message_handler_.AcceptWithResponder(message, responder); switch (message->header()->name) { case internal::kDirectory_Read_Name: { internal::Directory_Read_Params_Data* params = reinterpret_cast<internal::Directory_Read_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; Directory_Read_ParamsDataView input_data_view(params, &serialization_context_); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Read deserializer"); return false; } Directory::ReadCallback callback = Directory_Read_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::Read"); mojo::internal::MessageDispatchContext context(message); sink_->Read(callback); return true; } case internal::kDirectory_OpenFile_Name: { internal::Directory_OpenFile_Params_Data* params = reinterpret_cast<internal::Directory_OpenFile_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; ::filesystem::mojom::FileRequest p_file{}; uint32_t p_open_flags{}; Directory_OpenFile_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; p_file = input_data_view.TakeFile(); p_open_flags = input_data_view.open_flags(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFile deserializer"); return false; } Directory::OpenFileCallback callback = Directory_OpenFile_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::OpenFile"); mojo::internal::MessageDispatchContext context(message); sink_->OpenFile( std::move(p_path), std::move(p_file), std::move(p_open_flags), callback); return true; } case internal::kDirectory_OpenFileHandle_Name: { internal::Directory_OpenFileHandle_Params_Data* params = reinterpret_cast<internal::Directory_OpenFileHandle_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; uint32_t p_open_flags{}; Directory_OpenFileHandle_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; p_open_flags = input_data_view.open_flags(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFileHandle deserializer"); return false; } Directory::OpenFileHandleCallback callback = Directory_OpenFileHandle_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::OpenFileHandle"); mojo::internal::MessageDispatchContext context(message); sink_->OpenFileHandle( std::move(p_path), std::move(p_open_flags), callback); return true; } case internal::kDirectory_OpenFileHandles_Name: { internal::Directory_OpenFileHandles_Params_Data* params = reinterpret_cast<internal::Directory_OpenFileHandles_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::Array<FileOpenDetailsPtr> p_files{}; Directory_OpenFileHandles_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadFiles(&p_files)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenFileHandles deserializer"); return false; } Directory::OpenFileHandlesCallback callback = Directory_OpenFileHandles_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::OpenFileHandles"); mojo::internal::MessageDispatchContext context(message); sink_->OpenFileHandles( std::move(p_files), callback); return true; } case internal::kDirectory_OpenDirectory_Name: { internal::Directory_OpenDirectory_Params_Data* params = reinterpret_cast<internal::Directory_OpenDirectory_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; DirectoryRequest p_directory{}; uint32_t p_open_flags{}; Directory_OpenDirectory_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; p_directory = input_data_view.TakeDirectory(); p_open_flags = input_data_view.open_flags(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::OpenDirectory deserializer"); return false; } Directory::OpenDirectoryCallback callback = Directory_OpenDirectory_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::OpenDirectory"); mojo::internal::MessageDispatchContext context(message); sink_->OpenDirectory( std::move(p_path), std::move(p_directory), std::move(p_open_flags), callback); return true; } case internal::kDirectory_Rename_Name: { internal::Directory_Rename_Params_Data* params = reinterpret_cast<internal::Directory_Rename_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; mojo::String p_new_path{}; Directory_Rename_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; if (!input_data_view.ReadNewPath(&p_new_path)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Rename deserializer"); return false; } Directory::RenameCallback callback = Directory_Rename_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::Rename"); mojo::internal::MessageDispatchContext context(message); sink_->Rename( std::move(p_path), std::move(p_new_path), callback); return true; } case internal::kDirectory_Delete_Name: { internal::Directory_Delete_Params_Data* params = reinterpret_cast<internal::Directory_Delete_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; uint32_t p_delete_flags{}; Directory_Delete_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; p_delete_flags = input_data_view.delete_flags(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Delete deserializer"); return false; } Directory::DeleteCallback callback = Directory_Delete_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::Delete"); mojo::internal::MessageDispatchContext context(message); sink_->Delete( std::move(p_path), std::move(p_delete_flags), callback); return true; } case internal::kDirectory_Exists_Name: { internal::Directory_Exists_Params_Data* params = reinterpret_cast<internal::Directory_Exists_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; Directory_Exists_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Exists deserializer"); return false; } Directory::ExistsCallback callback = Directory_Exists_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::Exists"); mojo::internal::MessageDispatchContext context(message); sink_->Exists( std::move(p_path), callback); return true; } case internal::kDirectory_IsWritable_Name: { internal::Directory_IsWritable_Params_Data* params = reinterpret_cast<internal::Directory_IsWritable_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; Directory_IsWritable_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::IsWritable deserializer"); return false; } Directory::IsWritableCallback callback = Directory_IsWritable_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::IsWritable"); mojo::internal::MessageDispatchContext context(message); sink_->IsWritable( std::move(p_path), callback); return true; } case internal::kDirectory_Flush_Name: { internal::Directory_Flush_Params_Data* params = reinterpret_cast<internal::Directory_Flush_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; Directory_Flush_ParamsDataView input_data_view(params, &serialization_context_); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::Flush deserializer"); return false; } Directory::FlushCallback callback = Directory_Flush_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::Flush"); mojo::internal::MessageDispatchContext context(message); sink_->Flush(callback); return true; } case internal::kDirectory_StatFile_Name: { internal::Directory_StatFile_Params_Data* params = reinterpret_cast<internal::Directory_StatFile_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; Directory_StatFile_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::StatFile deserializer"); return false; } Directory::StatFileCallback callback = Directory_StatFile_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::StatFile"); mojo::internal::MessageDispatchContext context(message); sink_->StatFile( std::move(p_path), callback); return true; } case internal::kDirectory_Clone_Name: { break; } case internal::kDirectory_ReadEntireFile_Name: { internal::Directory_ReadEntireFile_Params_Data* params = reinterpret_cast<internal::Directory_ReadEntireFile_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; Directory_ReadEntireFile_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::ReadEntireFile deserializer"); return false; } Directory::ReadEntireFileCallback callback = Directory_ReadEntireFile_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::ReadEntireFile"); mojo::internal::MessageDispatchContext context(message); sink_->ReadEntireFile( std::move(p_path), callback); return true; } case internal::kDirectory_WriteFile_Name: { internal::Directory_WriteFile_Params_Data* params = reinterpret_cast<internal::Directory_WriteFile_Params_Data*>( message->mutable_payload()); (&serialization_context_)->handles.Swap((message)->mutable_handles()); bool success = true; mojo::String p_path{}; mojo::Array<uint8_t> p_data{}; Directory_WriteFile_ParamsDataView input_data_view(params, &serialization_context_); if (!input_data_view.ReadPath(&p_path)) success = false; if (!input_data_view.ReadData(&p_data)) success = false; if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, "Directory::WriteFile deserializer"); return false; } Directory::WriteFileCallback callback = Directory_WriteFile_ProxyToResponder::CreateCallback( message->request_id(), message->has_flag(mojo::Message::kFlagIsSync), responder, serialization_context_.group_controller); // A null |sink_| means no implementation was bound. assert(sink_); TRACE_EVENT0("mojom", "Directory::WriteFile"); mojo::internal::MessageDispatchContext context(message); sink_->WriteFile( std::move(p_path), std::move(p_data), callback); return true; } } return false; } DirectoryRequestValidator::DirectoryRequestValidator( mojo::MessageReceiver* sink) : MessageFilter(sink) { } bool DirectoryRequestValidator::Accept(mojo::Message* message) { assert(sink_); mojo::internal::ValidationContext validation_context( message->data(), message->data_num_bytes(), message->handles()->size(), message, "Directory RequestValidator"); if (mojo::internal::ControlMessageHandler::IsControlMessage(message)) { if (!mojo::internal::ValidateControlRequest(message, &validation_context)) return false; return sink_->Accept(message); } switch (message->header()->name) { case internal::kDirectory_Read_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_Read_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_OpenFile_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_OpenFile_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_OpenFileHandle_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_OpenFileHandle_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_OpenFileHandles_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_OpenFileHandles_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_OpenDirectory_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_OpenDirectory_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Rename_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_Rename_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Delete_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_Delete_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Exists_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_Exists_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_IsWritable_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_IsWritable_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Flush_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_Flush_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_StatFile_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_StatFile_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Clone_Name: { if (!mojo::internal::ValidateMessageIsRequestWithoutResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_Clone_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_ReadEntireFile_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_ReadEntireFile_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_WriteFile_Name: { if (!mojo::internal::ValidateMessageIsRequestExpectingResponse( message, &validation_context)) { return false; } if (!mojo::internal::ValidateMessagePayload< internal::Directory_WriteFile_Params_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } default: break; } // Unrecognized message. ReportValidationError( &validation_context, mojo::internal::VALIDATION_ERROR_MESSAGE_HEADER_UNKNOWN_METHOD); return false; } DirectoryResponseValidator::DirectoryResponseValidator( mojo::MessageReceiver* sink) : MessageFilter(sink) { } bool DirectoryResponseValidator::Accept(mojo::Message* message) { assert(sink_); mojo::internal::ValidationContext validation_context( message->data(), message->data_num_bytes(), message->handles()->size(), message, "Directory ResponseValidator"); if (mojo::internal::ControlMessageHandler::IsControlMessage(message)) { if (!mojo::internal::ValidateControlResponse(message, &validation_context)) return false; return sink_->Accept(message); } if (!mojo::internal::ValidateMessageIsResponse(message, &validation_context)) return false; switch (message->header()->name) { case internal::kDirectory_Read_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_Read_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_OpenFile_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_OpenFile_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_OpenFileHandle_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_OpenFileHandle_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_OpenFileHandles_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_OpenFileHandles_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_OpenDirectory_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_OpenDirectory_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Rename_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_Rename_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Delete_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_Delete_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Exists_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_Exists_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_IsWritable_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_IsWritable_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_Flush_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_Flush_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_StatFile_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_StatFile_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_ReadEntireFile_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_ReadEntireFile_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } case internal::kDirectory_WriteFile_Name: { if (!mojo::internal::ValidateMessagePayload< internal::Directory_WriteFile_ResponseParams_Data>( message, &validation_context)) { return false; } return sink_->Accept(message); } default: break; } // Unrecognized message. ReportValidationError( &validation_context, mojo::internal::VALIDATION_ERROR_MESSAGE_HEADER_UNKNOWN_METHOD); return false; } } // namespace mojom } // namespace filesystem namespace mojo { // static bool StructTraits<::filesystem::mojom::FileOpenDetails, ::filesystem::mojom::FileOpenDetailsPtr>::Read( ::filesystem::mojom::FileOpenDetailsDataView input, ::filesystem::mojom::FileOpenDetailsPtr* output) { bool success = true; ::filesystem::mojom::FileOpenDetailsPtr result(::filesystem::mojom::FileOpenDetails::New()); if (!input.ReadPath(&result->path)) success = false; result->open_flags = input.open_flags(); *output = std::move(result); return success; } // static bool StructTraits<::filesystem::mojom::FileOpenResult, ::filesystem::mojom::FileOpenResultPtr>::Read( ::filesystem::mojom::FileOpenResultDataView input, ::filesystem::mojom::FileOpenResultPtr* output) { bool success = true; ::filesystem::mojom::FileOpenResultPtr result(::filesystem::mojom::FileOpenResult::New()); if (!input.ReadPath(&result->path)) success = false; if (!input.ReadError(&result->error)) success = false; result->file_handle = input.TakeFileHandle(); *output = std::move(result); return success; } } // namespace mojo #if defined(__clang__) #pragma clang diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif
[ "dckristiono@gmail.com" ]
dckristiono@gmail.com
99a277f7b627d88999c8f5577f68d5197ed89592
90e4f95f53f342f86b43de5da8ce1ec0bd64cf2f
/aplcore/src/component/framecomponent.cpp
e695b2db628e989338ea7b64de151804526dfc1a
[ "Apache-2.0" ]
permissive
ysak-y/apl-core-library
0ed99afe584f1b23c9ff575fe763685ddf48cf77
f0a99732c530fde9d9fac97c2d008c012594fc51
refs/heads/master
2020-11-29T09:50:18.230682
2019-09-18T19:14:15
2019-11-04T18:32:48
230,084,288
0
0
Apache-2.0
2019-12-25T10:15:52
2019-12-25T10:15:51
null
UTF-8
C++
false
false
4,825
cpp
/** * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "apl/component/componentpropdef.h" #include "apl/component/framecomponent.h" #include "apl/component/yogaproperties.h" namespace apl { static void checkBorderRadii(Component& component) { auto& frame = static_cast<FrameComponent&>(component); frame.fixBorder(true); } CoreComponentPtr FrameComponent::create(const ContextPtr& context, Properties&& properties, const std::string& path) { auto ptr = std::make_shared<FrameComponent>(context, std::move(properties), path); ptr->initialize(); return ptr; } FrameComponent::FrameComponent(const ContextPtr& context, Properties&& properties, const std::string& path) : CoreComponent(context, std::move(properties), path) { // TODO: Auto-sized Frame just wraps the children. Fix this for ScrollView and other containers? YGNodeStyleSetAlignItems(mYGNodeRef, YGAlignFlexStart); } const ComponentPropDefSet& FrameComponent::propDefSet() const { static ComponentPropDefSet sFrameComponentProperties(CoreComponent::propDefSet(), { {kPropertyBackgroundColor, Color(), asColor, kPropInOut | kPropStyled | kPropDynamic}, {kPropertyBorderRadii, Object::EMPTY_RADII(), nullptr, kPropOut}, {kPropertyBorderColor, Color(), asColor, kPropInOut | kPropStyled | kPropDynamic}, {kPropertyBorderWidth, Dimension(0), asAbsoluteDimension, kPropInOut | kPropStyled, yn::setBorder<YGEdgeAll>}, // These are input-only properties that trigger the calculation of the output properties {kPropertyBorderBottomLeftRadius, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropStyled, checkBorderRadii }, {kPropertyBorderBottomRightRadius, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropStyled, checkBorderRadii }, {kPropertyBorderRadius, Dimension(0), asAbsoluteDimension, kPropIn | kPropStyled, checkBorderRadii }, {kPropertyBorderTopLeftRadius, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropStyled, checkBorderRadii }, {kPropertyBorderTopRightRadius, Object::NULL_OBJECT(), asAbsoluteDimension, kPropIn | kPropStyled, checkBorderRadii }, }); return sFrameComponentProperties; } void FrameComponent::fixBorder(bool useDirtyFlag) { static std::vector<std::pair<PropertyKey, Radii::Corner >> BORDER_PAIRS = { {kPropertyBorderBottomLeftRadius, Radii::kBottomLeft}, {kPropertyBorderBottomRightRadius, Radii::kBottomRight}, {kPropertyBorderTopLeftRadius, Radii::kTopLeft}, {kPropertyBorderTopRightRadius, Radii::kTopRight} }; float r = mCalculated.get(kPropertyBorderRadius).asAbsoluteDimension(*mContext).getValue(); std::array<float, 4> result = {r, r, r, r}; for (const auto& p : BORDER_PAIRS) { Object radius = mCalculated.get(p.first); if (radius != Object::NULL_OBJECT()) result[p.second] = radius.asAbsoluteDimension(*mContext).getValue(); } Radii radii(std::move(result)); if (radii != mCalculated.get(kPropertyBorderRadii).getRadii()) { mCalculated.set(kPropertyBorderRadii, Object(std::move(radii))); if (useDirtyFlag) setDirty(kPropertyBorderRadii); } } /* * Initial assignment of properties. Don't set any dirty flags here; this * all should be running in the constructor. * * This method initializes the values of the border corners. */ void FrameComponent::assignProperties(const ComponentPropDefSet& propDefSet) { CoreComponent::assignProperties(propDefSet); fixBorder(false); } } // namespace apl
[ "knappa@amazon.com" ]
knappa@amazon.com
0bd46d0d7c027a73382a07be237d07acd0f16b72
772d932a0e5f6849227a38cf4b154fdc21741c6b
/CPP_Joc_Windows_Android/SH_Client_Win_Cpp_Cmake/App/src/base/view/UIV_Base.cpp
2cf488692e7acd3754e1216fe82de580319d24c2
[]
no_license
AdrianNostromo/CodeSamples
1a7b30fb6874f2059b7d03951dfe529f2464a3c0
a0307a4b896ba722dd520f49d74c0f08c0e0042c
refs/heads/main
2023-02-16T04:18:32.176006
2021-01-11T17:47:45
2021-01-11T17:47:45
328,739,437
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
#include "UIV_Base.h" #include <base/app/IApp.h> UIV_Base::UIV_Base(IApp* app, ArrayList<MenuItemConfig*>* viewItemConfigs, ArrayList<StateChangeDurations*>* viewEaseDurationsSList) : super(app, app, viewItemConfigs, viewEaseDurationsSList), app(app) { //void } UIV_Base::~UIV_Base() { //void }
[ "adriannostromo@gmail.com" ]
adriannostromo@gmail.com
e748fcc60093762a30295ea36a50beae18d23036
aa3b801abb9f8645568156b445271ebd147623f8
/202001/past201912/13.gen.cpp
8793b8359323fdcb6c2588f26d1495515b9f076b
[ "MIT" ]
permissive
akouryy/kyopro-2020
aa7bba0eecee803ab5f9879560f449089c048fc8
9eaffe0e653deb96daeb105320d798db621ddcf6
refs/heads/master
2022-07-28T14:13:47.755337
2020-05-23T10:51:50
2020-05-23T10:51:50
216,549,001
0
0
null
null
null
null
UTF-8
C++
false
false
5,719
cpp
#line 1 "base.hpp"//1 #ifndef __clang__ #pragma GCC optimize ("O3") #endif void solve( #ifdef GCJ_CASE long long case_id #endif ); #if defined(EBUG) && !defined(ONLINE_JUDGE) #define debug true #define _GLIBCXX_DEBUG // #define _LIBCPP_DEBUG 0 #define _LIBCPP_DEBUG2 0 #else #define NDEBUG #define debug false #endif #include<algorithm> #include<bitset> #include<functional> #include<iomanip> #include<iostream> #include<limits> #include<map> #include<numeric> #include<queue> #include<set> #include<type_traits> #include<vector> #include<cassert> #include<climits> #include<cmath> #include<cstdio> #include<cstdlib> using namespace std; using LL=long long; using ULL=unsigned long long; #define int LL #define CS const #define CX constexpr #define IL inline #define OP operator #define RT return #define TL template #define TN typename #define lambda [&] #define rep(f,t,i,c,u)for(int Rb_=(t),i=(f);i c Rb_;u(i)) #define upto(f,t,i)rep(f,t,i,<=,++) #define uptil(f,t,i)rep(f,t,i,<,++) #define downto(f,t,i)rep(f,t,i,>=,--) #define downtil(f,t,i)rep(f,t,i,>,--) #define times(n,i)uptil(0,n,i) #define rtimes(n,i)downto((n)-1,0,i) #define iter(v)begin(v),end(v) #define citer(v)cbegin(v),cend(v) #define riter(v)rbegin(v),rend(v) #define criter(v)crbegin(v),crend(v) #define IF(a,b,c)((a)?(b):(c)) #if debug #define ln <<endl #else #define ln <<'\n' #endif #define tb <<'\t' #define sp <<' ' #line 1 "base_util.hpp"//1b #define BINOPa(t,u,op)t OP op(CS u&o)CS{RT t(*this)op##=o;} #define CMPOP(t,op,f1,f2,x)bool OP op(CS t&x)CS{RT f1 op f2;} #define CMPOPS(t,f1,f2,x)CMPOP(t,==,f1,f2,x)CMPOP(t,!=,f1,f2,x)\ CMPOP(t,<,f1,f2,x)CMPOP(t,<=,f1,f2,x)CMPOP(t,>,f1,f2,x)CMPOP(t,>=,f1,f2,x) #line 1 "mod.hpp"//1b #ifndef MOD #define MOD 1000000007 #endif #if !defined(FORCE_MOD)&&MOD!=1000000007&&MOD!=1000000009&&MOD!=998244353 #error mod #endif #line 1 "power.hpp"//1bm TL<TN T>IL T power(T x,int n){T r(1);for(;n;n/=2){if(n%2)r*=x;x*=x;}RT r;}IL int pow_mod(int x,int n,int m){int r=1; for(;n;n/=2){if(n%2)r=r*x%m;x=x*x%m;}RT r;} #line 2001 "mod.hpp"//1b IL CX int modulo(int a,int b){a%=b;RT a&&(a>0)!=(b>0)?a+b:a;}IL CX int divide(int a,int b){RT(a-modulo(a,b))/b;} TL<int d=MOD>struct MInt{ /*!https://ei1333.github.io/luzhiled/snippets/other/mod-int.html*/ int v;CX MInt():v(0){}explicit CX MInt(int i):v(modulo(i,d)){}MInt&OP+=(CS MInt&m){v+=m.v;if(v>=d)v-=d;RT*this;} MInt&OP-=(CS MInt&m){v-=m.v;if(v<0)v+=d;RT*this;}MInt&OP*=(CS MInt&m){v=v*m.v%d;RT*this;}MInt&OP/=(CS MInt&m){ RT*this*=m.inv();}BINOPa(MInt,MInt,+)BINOPa(MInt,MInt,-)BINOPa(MInt,MInt,*)BINOPa(MInt,MInt,/)MInt OP-()CS{ RT MInt()-=*this;}CMPOP(MInt,==,v,m.v,m)CMPOP(MInt,!=,v,m.v,m)MInt pow(int n)CS{RT power(*this,n);}MInt inv()CS{ int a=v,b=d,x=1,y=0;while(b){swap(y,x-=a/b*y);swap(b,a%=b);}RT(MInt)x;} friend ostream&OP<<(ostream&o,CS MInt&m){RT o<<m.v;}friend istream&OP>>(istream&i,MInt&m){i>>m.v;m.v%=d;RT i;}}; using mint=MInt<>;CX mint OP"" _m(ULL n){RT mint(n);}CX MInt<998244353>OP"" _m998244353(ULL n){RT MInt<998244353>(n);} CX MInt<1000000007>OP"" _m1e9_7(ULL n){RT MInt<1000000007>(n);} CX MInt<1000000009>OP"" _m1e9_9(ULL n){RT MInt<1000000009>(n);} #line 1 "typedefs.hpp"//1b using unit = tuple<>;using LD=long double;TL<TN T>using vec=vector<T>; TL<TN T>using vvec=vec<vec<T>>;TL<TN T>using vvvec=vec<vvec<T>>;TL<TN T>using vvvvec=vec<vvvec<T>>; using VI=vec<int>; #line 1 "alias.hpp"//1b #define EB emplace_back #define PB push_back #define foldl accumulate #define scanl partial_sum #line 1 "util.hpp"//1b TL<TN T>IL bool amax(T&v,CS T&a){RT v<a&&(v=a,1);}TL<TN T>IL bool amin(T&v,CS T&a){RT v>a&&(v=a,1);} TL<TN T>IL int sizeRAB(T t){RT t.size();} #define size sizeRAB #define clamp clampRAB TL<TN T>IL CX CS T&clamp(CS T&a,CS T&l,CS T&r){RT a<l?l:r<a?r:a;}TL<TN V>IL void uniq2(V&v){ v.erase(unique(iter(v)),v.end());}TL<TN V>IL void uniq(V&v){sort(iter(v));uniq2(v);} #define leftmost_ge lower_bound #define leftmost_gt upper_bound TL<TN C,TN D>IL C rightmost_le(CS C&from,CS C&to,CS D&d){auto l=leftmost_gt(from,to,d);RT l==from?to:--l;} TL<TN C,TN D>IL C rightmost_lt(CS C&from,CS C&to,CS D&d){auto l=leftmost_ge(from,to,d);RT l==from?to:--l;} namespace rab{TL<TN I>IL bool is_in(I x,I l,I r){RT l<=x&&x<r;}TL<TN T>IL T fetch(CS T&d,CS vec<T>&v,int i){ RT 0<=i&&i<size(v)?v[i]:d;}} #line 1 "debug.hpp"//1b TL<TN T>IL istream&OP>>(istream&s,vec<T>&v){for(auto&&p:v)s>>p;RT s;}TL<TN T,TN S> IL ostream&OP<<(ostream&s,CS pair<T,S>&p){RT s<<"("<<p.first<<","<<p.second<<")";} #define Rdebug1(sep, ...)IL ostream& OP<<(ostream&s,CS __VA_ARGS__&v){\ int i=0;for(CS auto&e:v){i++&&s<<sep;s<<e;}RT s;} TL<TN T>Rdebug1(' ',vec<T>)TL<TN T,TN S>Rdebug1(' ',map<T,S>)TL<TN T>Rdebug1('\n',vvec<T>) TL<TN T,TN S>Rdebug1('\n',vec<map<T,S>>) #line 6001 "base.hpp"//1 signed main(){if(debug)cerr<<"MOD: "<<MOD ln;else cin.tie(0),cerr.tie(0),ios::sync_with_stdio(0); auto p=setprecision(20);cout<<fixed<<p;cerr<<fixed<<p; #ifdef GCJ_CASE int T;cin>>T;times(T,t){cout<<"Case #"<<t+1<<": ";solve(t);} #else solve(); #endif RT 0;} #line 1001 "13.cpp"// //#include "consts.hpp" void solve() { // NMN(AB)M(CD) /* <foxy.memo-area> */ int N;int M;cin>>N;cin>>M;VI A(N);VI B(N);times(N,Ri_0){cin>>A[Ri_0];cin>>B[Ri_0 ];}VI C(M);VI D(M);times(M,Ri_0){cin>>C[Ri_0];cin>>D[Ri_0];} /* </foxy.memo-area> */ vec<LD> norm(N), help(M); LD ok = 0.0, ng = 9e99; times(1000, o) { LD goal = (ok + ng) / 2; times(N, i) norm[i] = B[i] - goal * A[i]; times(M, i) help[i] = D[i] - goal * C[i]; sort(iter(norm)); reverse(iter(norm)); sort(iter(help)); reverse(iter(help)); LD s = norm[0] + norm[1] + norm[2] + norm[3] + max(norm[4], help[0]); if(s >= 0) { ok = goal; } else { ng = goal; } } cout << ok ln; }
[ "akouryy7@gmail.com" ]
akouryy7@gmail.com
c4970571d6e65a9eae3ce5d2893fae06b9540955
fab9e1de4379b572fcad8c6ae2cbac79f4b97253
/_bst/_bst/BTree.h
080b5e54e785c82de340719dd054b66dc7e88f96
[]
no_license
Jaya0831/data-structure
be142332b405c2cd217b00c4521d09e3144673e5
e67846c21fffdcf4749dda00ef0b9a536f4f6ac7
refs/heads/master
2021-02-27T06:45:01.882951
2020-03-12T15:32:31
2020-03-12T15:32:31
245,589,230
0
0
null
null
null
null
UTF-8
C++
false
false
7,784
h
// // BTree.h // _bst // // Created by 刘佳翊 on 2020/3/12. // Copyright © 2020 刘佳翊. All rights reserved. // #ifndef BTree_h #define BTree_h #include "BTNode.h" template <typename T> class BTree{ protected: int _size;//关键码总数 int _order;//阶次 BTNodePosi(T) _root;//根 BTNodePosi(T) _hot;//search最后访问的非空节点的位置 void solveOverflow(BTNodePosi(T));//因插入而上溢后的分离处理 void solveUnderflow(BTNodePosi(T));//因删除而下溢后的合并处理 public: BTNodePosi(T) search(const T & e);//查找 bool insert(const T & e);//插入 bool remove(const T & e);//删除 }; template <typename T> BTNodePosi(T) BTree<T>::search(const T& e){ BTNodePosi(T) v= _root;//从根结点出发查找 _hot=NULL; while(v){//当v不为空时 int r=v->key.search(e);//search返回值???????????? if(0<=r&&e==v->key[r]) return v;//查找成功 _hot=v;//记录当前节点 v=v->child[r+1];//进入下一节点(孩子) }//v为空时退出,表示查找失败 return NULL; } template <typename T> bool BTree<T>::insert(const T & e){ BTNodePosi(T) v=search(e);//调用BTree的查找函数 if(v) return false;//插入失败 int r=_hot->Key.search(e);//调用vector的查找函数,确定插入位置 _hot->key.insert(r+1,e);//插入节点 _hot->child.insert(r+2,NULL);//在插入节点左边创建空子树指针 _size++;//update solveOverflow(_hot);//如果上溢,需做分裂 return true; } template <typename T> bool BTree<T>::remove(const T & e){ BTNodePosi(T) v=search(e);//调用BTree的查找函数,找到的是节点但还没有具体到节点里面的关键值 if(!v) return false;//确认e存在 int r=v->key.search(e);//调用vector的查找函数,确定删除的关键值在节点中的位置 if(v->child[0]){//若v非叶子节点,则 BTNodePosi(T) u=v->child[r+1]; while (v->child[0]) u=u->child[0];//在右子树中一直向左,可找到其直接后继(必定是某叶节点) v->key[r]=u->key[0];//将后继的第一个关键码也就是待删除关键码的直接后继赋到待删除关键码的位置, // 从而只需删除后继的第一个关键码就相当于删除了待删除关键码 v=u; r=0; } v->key.remove(r);v->child.remove(r+1);_size--;//其实删除任意一个孩子都可以,因为这些都是外部空节点 solveUnderflow(v);//如果有必要,需做旋转和合并 return true; } template <typename T> void BTree<T>::solveOverflow(BTNode<T> *v) {//tips:_order表示最大孩子数 if(v->child.size()<=_order) return;//未发生上溢 //把关键码拆分两部分和中间的一个关键码,中间关键码进入父节点中,余下两个关键码成为两个节点作为中间关键码的左右子树 int s=_order/2;//左右均分,左边>=右边 BTNodePosi(T) u=new BTNode<T>();//新建一个节点,用来储存右半部分的关键码和孩子,作为右节点 //转移数据 for(int i=0;i<_order-s-i;i++) { u->key.insert(i, v->key.remove(s + 1));//将右半部分第一个关键码删除并放入新建节点中 u->child.insert(i, v->child.remove(s + i));//将右半部分第一个孩子删除并放入新建节点中(这时转移的是关键码左边的孩子) } u->child[_order-s-1]=v->child.remove(s+1); if(u->child[0]){//若u的孩子非空(即不是外部空节点),更新孩子指向 for(int i=0;i<(u->child.size());i++){ (u->child[i])->parent=u; } } //插入父节点 BTNodePosi(T) p=v->parent; if(!p){//v是根结点,没有父节点 _root=p=new BTNode<T>();//新建根结点 p->child[0]=v; v->parent=p; } int r=p->key.search(v->key[s]);//寻找插入点 p->key.insert(r+1,v->key.remove[s]);//删除中间关键值并插入父节点 p->child.insert(r+2,u);//u作为右节点插入 u->parent=p; solveOverflow(p);//继续向上检查是否溢出 } template <typename T> void BTree<T>::solveUnderflow(BTNode<T> *v) { if(v->child.size()>=(_order+1)/2) return;//未发生下溢 BTNodePosi(T) p=v->parent;//记录父节点 if(!p){ //v为根结点时 //因为根结点只要孩子数量大于等于2就可以,所以此时发生下溢,就说明根结点只有一个孩子,无关键码、 if((!v->key.size())&&(v->child[0])){//该根结点不含有效关键码,但有孩子(虽然我觉得这是一定的啊) _root=v->child[0];//唯一的孩子成为根结点 _root->parent=nullptr; v->child[0]= nullptr;//不是你管它呢???反正都要删了... delete v; v= nullptr; } return; } int r=0; while (p->child[r]!=v) r++;//找到v在节点关键值中的位置(其实可以用search() //旋转 //左兄弟有足够多的关键值和孩子 if(0<r){//说明有左兄弟 BTNodePosi(T) ls=p->child[r-1];//左兄弟 if(ls->child.size()>=((_order+1)/2)+1){//左兄弟有足够多的孩子 v->key.insert(0,p->key[r-1]);//先从父节点的关键码中借用前一个关键码 v->child.insert(0,ls->child.remove(ls->child.size()-1));//再从左兄弟的孩子中取最右一个作为自己的孩子 p->key[r-1]=ls->key.remove(ls->key.size()-1);//左兄弟的最后一个关键码补给父节点 if(v->child[0]) v->child[0]->parent=v;//如果转移的孩子不是外部空节点 return; } } //右兄弟有足够多的关键值和孩子 if(r<p->key.size()-1){ BTNodePosi(T) rs=p->parent[r+1]; if(rs->child.size()>=((_order+1)/2)+1){ v->key.insert(v->key.size(),p->key[r]); v->child.insert(v->child.size(),rs->child.remove(0)); p->key[r]=rs->key.remove(0); if(v->child[v->child.size()-1]) v->child[v->child.siza()-1]->parent=v; return; } } //合并 //和其左右兄弟以及两兄弟间的父节点的关键码组成一个节点 //相当于两兄弟拽了一个关键码下来 if(r>0){//存在左兄弟 BTNodePosi(T) ls=p->child[r-1];//左兄弟 ls->key.insert(ls->key.size(),p->key.remove(r-1));//父节点的关键码被下拉进入左兄弟 p->child.remove(r);//删除父节点指向v的孩子节点 //开始转移,把v中的关键码和孩子转移到左兄弟中 ls->child.insert(ls->child.size(),v->child.remove(0));//先转移v的最左孩子(因为孩子数量和关键码数量不匹配) if(ls->child[ls->child.size()-1]) (ls->child[ls->child.size()-1])->parent=ls;//如果转移的孩子非空,重置父母 while(v->key.size()){//依次成对转移其它孩子和关键码 ls->key.insert(ls->key.size(),v->key.remove(0)); ls->child.insert(ls->child.size(),v->child.remove(0)); if(ls->child[ls->child.size()-1]) ls->child[ls->child.size()-1]->parent=ls; } delete v; v= nullptr; } else{//存在右兄弟 BTNodePosi(T) rs=p->child[r+1];//右兄弟 rs->key.insert(0,p->key.remove(r)); p->child.remove(r); rs->child.insert(0,v->child.remove(v->child.size()-1)); if(rs->child[0]) (rs->child[0])->parent=rs; while (v->key.size()){ rs->key.insert(0,v->key.remove(v->key.size()-1)); rs->child.insert(0,v->child.remove(v->child.size()-1)); if(rs->child[0]) (rs->child[0])->parent=rs; } delete v; v= nullptr; } } #endif /* BTree_h */
[ "liujy20010831@icloud.com" ]
liujy20010831@icloud.com
b7f4841cdcc54eda8af0cd585a0b3b25f58a5c49
6e99d2d6f75259897c303cf0b764fa09529b7f34
/mainwindow.cpp
d9aff1c9db09965b6ff6fe1f9b88e99819f533c9
[]
no_license
VDimson/QT_example2
8184fd6eac2284de743f4a1676552c13168611fe
3b0638a22327e6d8d56591e523f0faa009703481
refs/heads/master
2020-06-03T01:40:56.681274
2019-06-11T13:44:17
2019-06-11T13:44:17
191,379,987
0
0
null
null
null
null
UTF-8
C++
false
false
2,003
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QListWidgetItem *item_1 = new QListWidgetItem(QIcon(":/rec/img/paper.png"),"Audi"); ui->listWidget->addItem(item_1); ui->listWidget->addItem("BMW"); ui->listWidget->addItem("Ford"); ui->listWidget->addItem("Volvo"); ui->listWidget->addItem("UAZ"); ui->listWidget->addItem("Kia"); ui->listWidget->addItem("Hyindai"); ui->listWidget->addItem("Wolz"); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_checkBox_clicked() { if(ui->checkBox->checkState()) { ui->statusBar->showMessage("Элемент выбран!"); } else { ui->statusBar->showMessage("Элемент не выбран!"); } } void MainWindow::on_pushButton_released() { ui->statusBar->showMessage("отпущена"); } void MainWindow::on_pushButton_destroyed() { ui->statusBar->showMessage("Сработал сигнал destroyed!"); } void MainWindow::on_pushButton_pressed() { ui->statusBar->showMessage("нажата"); } void MainWindow::on_pushButton_clicked() { if (ui->radioButton->isChecked()) { ui->statusBar->showMessage("Выбран первый"); } if (ui->radioButton_2->isChecked()) { ui->statusBar->showMessage("Выбран второй"); } } void MainWindow::on_action_triggered() { ui->statusBar->showMessage("Создан новый проект"); } void MainWindow::on_action_3_triggered() { ui->statusBar->showMessage("Открытите проекта"); } void MainWindow::on_action_4_triggered() { QApplication::quit(); } void MainWindow::on_pushButton_2_clicked() { ui->statusBar->showMessage(ui->listWidget->currentItem()->text()); ui->listWidget->currentItem()->setBackgroundColor(Qt::blue); ui->listWidget->currentItem()->setForeground(Qt::white); }
[ "m.taho@mail.ru" ]
m.taho@mail.ru
60b5fa399d6f24822524da616b1dcab30ab400d9
c8f1d6847aca7de8ec12e93e9b6c40eaf3cf6024
/DirectTest/EngineCore/Renderer/Graphics/RootSignature.cpp
a5eb14a97cc59de65c2924db0e95ff85fbc67085
[]
no_license
Xesin/DirectXRenderer
c49578dd1982c8fe5c0c523b855cca5056d8784c
59182086cd8793f5a470d855e84371ae1beb1018
refs/heads/master
2022-11-21T21:22:04.122872
2022-10-26T07:02:07
2022-10-26T07:02:07
107,161,143
0
0
null
null
null
null
UTF-8
C++
false
false
5,522
cpp
#include "RootSignature.h" #include "../Core/GraphicContext.h" #include <map> #include <thread> #include <mutex> using namespace std; using namespace Renderer; using Microsoft::WRL::ComPtr; static std::map< size_t, ComPtr<ID3D12RootSignature> > s_RootSignatureHashMap; void RootSignature::DestroyAll(void) { s_RootSignatureHashMap.clear(); } void RootSignature::InitStaticSampler( UINT Register, const D3D12_SAMPLER_DESC& NonStaticSamplerDesc, D3D12_SHADER_VISIBILITY Visibility) { ASSERT(m_NumInitializedStaticSamplers < m_NumSamplers); D3D12_STATIC_SAMPLER_DESC& StaticSamplerDesc = m_SamplerArray[m_NumInitializedStaticSamplers++]; StaticSamplerDesc.Filter = NonStaticSamplerDesc.Filter; StaticSamplerDesc.AddressU = NonStaticSamplerDesc.AddressU; StaticSamplerDesc.AddressV = NonStaticSamplerDesc.AddressV; StaticSamplerDesc.AddressW = NonStaticSamplerDesc.AddressW; StaticSamplerDesc.MipLODBias = NonStaticSamplerDesc.MipLODBias; StaticSamplerDesc.MaxAnisotropy = NonStaticSamplerDesc.MaxAnisotropy; StaticSamplerDesc.ComparisonFunc = NonStaticSamplerDesc.ComparisonFunc; StaticSamplerDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; StaticSamplerDesc.MinLOD = NonStaticSamplerDesc.MinLOD; StaticSamplerDesc.MaxLOD = NonStaticSamplerDesc.MaxLOD; StaticSamplerDesc.ShaderRegister = Register; StaticSamplerDesc.RegisterSpace = 0; StaticSamplerDesc.ShaderVisibility = Visibility; if (StaticSamplerDesc.AddressU == D3D12_TEXTURE_ADDRESS_MODE_BORDER || StaticSamplerDesc.AddressV == D3D12_TEXTURE_ADDRESS_MODE_BORDER || StaticSamplerDesc.AddressW == D3D12_TEXTURE_ADDRESS_MODE_BORDER) { WARN_ONCE_IF_NOT( // Transparent Black NonStaticSamplerDesc.BorderColor[0] == 0.0f && NonStaticSamplerDesc.BorderColor[1] == 0.0f && NonStaticSamplerDesc.BorderColor[2] == 0.0f && NonStaticSamplerDesc.BorderColor[3] == 0.0f || // Opaque Black NonStaticSamplerDesc.BorderColor[0] == 0.0f && NonStaticSamplerDesc.BorderColor[1] == 0.0f && NonStaticSamplerDesc.BorderColor[2] == 0.0f && NonStaticSamplerDesc.BorderColor[3] == 1.0f || // Opaque White NonStaticSamplerDesc.BorderColor[0] == 1.0f && NonStaticSamplerDesc.BorderColor[1] == 1.0f && NonStaticSamplerDesc.BorderColor[2] == 1.0f && NonStaticSamplerDesc.BorderColor[3] == 1.0f, "Sampler border color does not match static sampler limitations"); if (NonStaticSamplerDesc.BorderColor[3] == 1.0f) { if (NonStaticSamplerDesc.BorderColor[0] == 1.0f) StaticSamplerDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; else StaticSamplerDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK; } else StaticSamplerDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; } } void RootSignature::Finalize(const std::wstring& name, D3D12_ROOT_SIGNATURE_FLAGS Flags) { if (m_Finalized) return; ASSERT(m_NumInitializedStaticSamplers == m_NumSamplers); D3D12_ROOT_SIGNATURE_DESC RootDesc; RootDesc.NumParameters = m_NumParameters; RootDesc.pParameters = (const D3D12_ROOT_PARAMETER*)m_ParamArray.get(); RootDesc.NumStaticSamplers = m_NumSamplers; RootDesc.pStaticSamplers = (const D3D12_STATIC_SAMPLER_DESC*)m_SamplerArray.get(); RootDesc.Flags = Flags; m_DescriptorTableBitMap = 0; m_SamplerTableBitMap = 0; size_t HashCode = Utility::HashState(&RootDesc.Flags); HashCode = Utility::HashState(RootDesc.pStaticSamplers, m_NumSamplers, HashCode); for (UINT Param = 0; Param < m_NumParameters; ++Param) { const D3D12_ROOT_PARAMETER& RootParam = RootDesc.pParameters[Param]; m_DescriptorTableSize[Param] = 0; if (RootParam.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) { ASSERT(RootParam.DescriptorTable.pDescriptorRanges != nullptr); HashCode = Utility::HashState(RootParam.DescriptorTable.pDescriptorRanges, RootParam.DescriptorTable.NumDescriptorRanges, HashCode); // We keep track of sampler descriptor tables separately from CBV_SRV_UAV descriptor tables if (RootParam.DescriptorTable.pDescriptorRanges->RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) m_SamplerTableBitMap |= (1 << Param); else m_DescriptorTableBitMap |= (1 << Param); for (UINT TableRange = 0; TableRange < RootParam.DescriptorTable.NumDescriptorRanges; ++TableRange) m_DescriptorTableSize[Param] += RootParam.DescriptorTable.pDescriptorRanges[TableRange].NumDescriptors; } else HashCode = Utility::HashState(&RootParam, 1, HashCode); } ID3D12RootSignature** RSRef = nullptr; bool firstCompile = false; { static mutex s_HashMapMutex; lock_guard<mutex> CS(s_HashMapMutex); auto iter = s_RootSignatureHashMap.find(HashCode); // Reserve space so the next inquiry will find that someone got here first. if (iter == s_RootSignatureHashMap.end()) { RSRef = s_RootSignatureHashMap[HashCode].GetAddressOf(); firstCompile = true; } else RSRef = iter->second.GetAddressOf(); } if (firstCompile) { ComPtr<ID3DBlob> pOutBlob, pErrorBlob; ASSERT_SUCCEEDED(D3D12SerializeRootSignature(&RootDesc, D3D_ROOT_SIGNATURE_VERSION_1, pOutBlob.GetAddressOf(), pErrorBlob.GetAddressOf())); ASSERT_SUCCEEDED(device->CreateRootSignature(1, pOutBlob->GetBufferPointer(), pOutBlob->GetBufferSize(), MY_IID_PPV_ARGS(&m_Signature))); m_Signature->SetName(name.c_str()); s_RootSignatureHashMap[HashCode].Attach(m_Signature); ASSERT(*RSRef == m_Signature); } else { while (*RSRef == nullptr) this_thread::yield(); m_Signature = *RSRef; } m_Finalized = TRUE; }
[ "francisco.fer.fer@gmail.com" ]
francisco.fer.fer@gmail.com
0011eb13da7dcccbd696d2c663ba4347f906ebfb
bd3917cc00ab8c3129151c7568173e0b99ce2bf0
/SistemaParticulas.cpp
0b0823acfcb7d2dd8ca2437fcda781bb0683490b
[]
no_license
ichramm/t-asteroids
2bbd1b3db40bc995c6a3dfd3fffd34ff29bbac00
d90ab4861404923223a126a998cc640f436b9095
refs/heads/master
2020-08-27T10:05:33.261295
2019-10-24T15:07:08
2019-10-24T15:07:08
217,327,303
0
0
null
null
null
null
UTF-8
C++
false
false
2,086
cpp
#include "SistemaParticulas.h" #include "Multiobjeto3d.h" #include "Sprite.h" SistemaParticulas::SistemaParticulas(int cant, string particula){ cantParticulas=cant; particulas=new Sprite*[cant]; for(int i=0;i<cant;i++){ Sprite *sp=new Sprite(particula.c_str()); sp->setModoTransparencia(Aditivo); sp->setAfectaDetrasCamara(false); particulas[i]=sp; } tam=1; this->afectaLuces=false; this->afectaDetrasCamara=false; this->setModoTransparencia(Aditivo); } SistemaParticulas::~SistemaParticulas(){ for(int i=0; i<cantParticulas; i++) delete particulas[i]; delete[] particulas; } void SistemaParticulas::setParticula(int n,const Vector &particula){ if(n<0 || n>=cantParticulas) return; particulas[n]->posicionar(particula); } Vector SistemaParticulas::getParticula(int n){ if(n<0 || n>=cantParticulas) return Vector(); return particulas[n]->getPosicion(); } int SistemaParticulas::getCantParticulas(){ return cantParticulas; } void SistemaParticulas::setTamanio(float tamanio){ tam=tamanio; for(int i=0;i<cantParticulas;i++){ particulas[i]->setEscala(tam); } } float SistemaParticulas::getTamanio(){ return tam; } //Overrides bool SistemaParticulas::esTransparente(){ return true; } bool SistemaParticulas::getAfectaLuces(){ return false; } Esfera SistemaParticulas::getEsferaEnvolvente(){ Vector centro; for(int i=0;i<cantParticulas;i++) centro+=particulas[i]->getPosicion(); centro/=cantParticulas; float dist=99999999; for(int i=0;i<cantParticulas;i++) dist=Min(dist,centro.distancia2(particulas[i]->getPosicion())); dist=sqrt(dist); centro+=getPosicion(); return Esfera(centro,dist); } void SistemaParticulas::dibujar(){ for(int i=0;i<cantParticulas;i++){ particulas[i]->setColor(this->color); particulas[i]->setOpacidad(this->opacidad); particulas[i]->toGL(); } }
[ "jramirez.uy@gmail.com" ]
jramirez.uy@gmail.com
c1ed80dae2f31cd583509ac907d98390585770bd
677b1d69eb6a33a076b047281042a83bd46a309b
/main_1_5.cpp
09a52cbfdd684a293dc31023c9bdea7cdd997f15
[]
no_license
Chineseguuys/huawei2020Codecraft
26be95a33e585dd179e89b0d93113bf7f76fbb4b
f45142e74027ee4e90c921905dfb8b3ba40137ae
refs/heads/master
2022-10-03T23:59:24.553444
2020-06-10T13:36:16
2020-06-10T13:36:16
271,004,335
0
0
null
null
null
null
UTF-8
C++
false
false
11,327
cpp
#include <iostream> #include <vector> #include <sstream> #include <fstream> #include <cmath> #include <cstdlib> using namespace std; #ifndef TEST #define TEST #endif /** * 这里面存储的是训练集的数据和其标签 */ struct Data { vector<double> features; int label; Data(vector<double> f, int l) : features(f), label(l) {} }; /** * 网络的权重参数 */ struct Param { vector<double> wtSet; }; /** * 线性回归算法 */ class LR { public: void train(); void predict(); int loadModel(); int storeModel(); LR(string trainFile, string testFile, string predictOutFile); private: vector<Data> trainDataSet; vector<Data> testDataSet; vector<int> predictVec; Param param; string trainFile; string testFile; string predictOutFile; string weightParamFile = "modelweight.txt"; private: bool init(); bool loadTrainData(); bool loadTestData(); int storePredict(vector<int> &predict); void initParam(); double wxbCalc(const Data &data); double sigmoidCalc(const double wxb); double lossCal(); double gradientSlope(const vector<Data> &dataSet, int index, const vector<double> &sigmoidVec, int data_start, int data_end); private: int featuresNum; const double wtInitV = 0.5; /** * 一些机器学习的超参数 */ double stepSize = 5; /** * 看来学习的步长对学习的结果影响很大 */ const int batch_size = 40; const int maxIterTimes = 100; const double predictTrueThresh = 0.5; const int train_show_step = 10; }; /** * 构造函数 * 完成了训练数据的导入 * 完成了权重值的初始化 */ LR::LR(string trainF, string testF, string predictOutF) { trainFile = trainF; testFile = testF; predictOutFile = predictOutF; featuresNum = 0; init(); } /** * 从训练数据集中导入数据和标签 */ bool LR::loadTrainData() { ifstream infile(trainFile.c_str()); string line; if (!infile) { cout << "打开训练文件失败" << endl; exit(0); } while (infile) { getline(infile, line); if (line.size() > featuresNum) { stringstream sin(line); char ch; double dataV; int i; vector<double> feature; i = 0; while (sin) { char c = sin.peek(); if (int(c) != -1) { sin >> dataV; feature.push_back(dataV); sin >> ch; i++; } else { cout << "训练文件数据格式不正确,出错行为" << (trainDataSet.size() + 1) << "行" << endl; return false; } } int ftf; /** * 最后一个是标签 label */ ftf = (int)feature.back(); feature.pop_back(); trainDataSet.push_back(Data(feature, ftf)); // 得到所有的数据集 } } infile.close(); std::cout << "成功读取了训练数据" << std::endl; return true; } void LR::initParam() { /** * 使用初始值来初始化权重 */ int i; for (i = 0; i < featuresNum; i++) { param.wtSet.push_back(wtInitV); } } bool LR::init() { trainDataSet.clear(); bool status = loadTrainData(); // 将训练数据导入 if (status != true) { return false; } featuresNum = trainDataSet[0].features.size(); // 获取特征的个数 param.wtSet.clear(); initParam(); return true; } /** * 计算 w * x */ double LR::wxbCalc(const Data &data) { double mulSum = 0.0L; int i; double wtv, feav; for (i = 0; i < param.wtSet.size(); i++) { wtv = param.wtSet[i]; feav = data.features[i]; mulSum += wtv * feav; } return mulSum; } inline double LR::sigmoidCalc(const double wxb) { double expv = exp(-1 * wxb); double expvInv = 1 / (1 + expv); return expvInv; } /** * loss functin 实际上在计算过程中使用不到它 * loss function = log(L(theta)) = * sum(yi * log(h(theta * xi)) + (1 - yi)*log(1 - h(theta * xi))) */ double LR::lossCal() { double lossV = 0.0L; int i; for (i = 0; i < trainDataSet.size(); i++) { lossV -= trainDataSet[i].label * log(sigmoidCalc(wxbCalc(trainDataSet[i]))); lossV -= (1 - trainDataSet[i].label) * log(1 - sigmoidCalc(wxbCalc(trainDataSet[i]))); } lossV /= trainDataSet.size(); return lossV; } /** * 计算某一个参数的梯度 * loss function 是什么 * loss function = log(L(theta)) = * sum(yi * log(h(theta * xi)) + (1 - yi)*log(1 - h(theta * xi))) * 详细的推导过程见 https://www.jianshu.com/p/dce9f1af7bc9 * 推导的过程比较的复杂,但是结果的形式较为简单 * ∂L(theta) / ∂wi = (yi - h(theta * xi))* xi */ double LR::gradientSlope(const vector<Data> &dataSet, int index, const vector<double> &sigmoidVec, int data_start, int data_end) { double gsV = 0.0L; int i; int k; double sigv, label; for (i = data_start, k = 0; i < data_end; ++i, ++k) { sigv = sigmoidVec[k]; label = dataSet[i].label; gsV += (label - sigv) * (dataSet[i].features[index]); } gsV = gsV / (this->batch_size); return gsV; } void LR::train() { int times = this->trainDataSet.size() / this->batch_size; int start; int end; double sigmoidVal; double wxbVal; int starting; vector<double> sigmoidVec(batch_size); for (int iter = 0; iter < 2; ++iter) { starting = iter * (this->batch_size / 2); for (int i = 0; i < times; ++i) { if (iter == 0 && i != 0 && i % 20 == 0) { this->stepSize = this->stepSize * 0.95; } if (iter == 1 && i != 0 && i % 10 == 0) { this->stepSize = this->stepSize * 0.5; } start = i * batch_size + starting; end = (i + 1) * batch_size + starting; end = end > trainDataSet.size() ? (end-starting) : end; for (int j = start, k = 0; j < end; ++j, ++k) { wxbVal = wxbCalc(trainDataSet[j]); sigmoidVal = sigmoidCalc(wxbVal); sigmoidVec[k] = sigmoidVal; } for (int j = 0; j < param.wtSet.size(); ++j) { param.wtSet[j] += stepSize * gradientSlope(trainDataSet, j, sigmoidVec, start, end); } } } } void LR::predict() { double sigVal; int predictVal; loadTestData(); for (int j = 0; j < testDataSet.size(); j++) { sigVal = sigmoidCalc(wxbCalc(testDataSet[j])); predictVal = sigVal >= predictTrueThresh ? 1 : 0; // 二分类问题的判决分割值,如果结果大于 0.5 ,那么认为是 1;如果结果小于 0.5 那么认为是 0 predictVec.push_back(predictVal); } storePredict(predictVec); } int LR::loadModel() { string line; int i; vector<double> wtTmp; double dbt; ifstream fin(weightParamFile.c_str()); if (!fin) { cout << "打开模型参数文件失败" << endl; exit(0); } getline(fin, line); stringstream sin(line); for (i = 0; i < featuresNum; i++) { char c = sin.peek(); if (c == -1) { cout << "模型参数数量少于特征数量,退出" << endl; return -1; } sin >> dbt; wtTmp.push_back(dbt); } param.wtSet.swap(wtTmp); fin.close(); return 0; } int LR::storeModel() { string line; int i; ofstream fout(weightParamFile.c_str()); if (!fout.is_open()) { cout << "打开模型参数文件失败" << endl; } if (param.wtSet.size() < featuresNum) { cout << "wtSet size is " << param.wtSet.size() << endl; } for (i = 0; i < featuresNum; i++) { fout << param.wtSet[i] << " "; // 将权重值储存到文件当中,以空格进行分割 } fout.close(); return 0; } bool LR::loadTestData() { ifstream infile(testFile.c_str()); string lineTitle; if (!infile) { cout << "打开测试文件失败" << endl; exit(0); } while (infile) { vector<double> feature; string line; getline(infile, line); if (line.size() > featuresNum) { stringstream sin(line); double dataV; int i; char ch; i = 0; while (i < featuresNum && sin) { char c = sin.peek(); if (int(c) != -1) { sin >> dataV; feature.push_back(dataV); sin >> ch; i++; } else { cout << "测试文件数据格式不正确" << endl; return false; } } testDataSet.push_back(Data(feature, 0)); } } infile.close(); return true; } bool loadAnswerData(string awFile, vector<int> &awVec) { ifstream infile(awFile.c_str()); if (!infile) { cout << "打开答案文件失败" << endl; exit(0); } while (infile) { string line; int aw; getline(infile, line); if (line.size() > 0) { stringstream sin(line); sin >> aw; awVec.push_back(aw); } } infile.close(); return true; } int LR::storePredict(vector<int> &predict) { string line; int i; ofstream fout(predictOutFile.c_str()); if (!fout.is_open()) { cout << "打开预测结果文件失败" << endl; } for (i = 0; i < predict.size(); i++) { fout << predict[i] << endl; } fout.close(); return 0; } int main(int argc, char *argv[]) { vector<int> answerVec; vector<int> predictVec; int correctCount; double accurate; string trainFile = "./data/train_data.txt"; string testFile = "./data/test_data.txt"; string predictFile = "./projects/student/result.txt"; string answerFile = "./projects/student/answer.txt"; LR logist(trainFile, testFile, predictFile); /** //cout << "ready to train model" << endl; logist.train(); //cout << "training ends, ready to store the model" << endl; logist.storeModel(); #ifdef TEST //cout << "ready to load answer data" << endl; loadAnswerData(answerFile, answerVec); #endif //cout << "let's have a prediction test" << endl; logist.predict(); #ifdef TEST loadAnswerData(predictFile, predictVec); cout << "test data set size is " << predictVec.size() << endl; correctCount = 0; for (int j = 0; j < predictVec.size(); j++) { if (j < answerVec.size()) { if (answerVec[j] == predictVec[j]) { correctCount++; } } else { cout << "answer size less than the real predicted value" << endl; } } accurate = ((double)correctCount) / answerVec.size(); cout << "the prediction accuracy is " << accurate << endl; #endif **/ return 0; }
[ "yanjianghan1996@outlook.com" ]
yanjianghan1996@outlook.com
00242da7b5a3f097c1066b7c2be2842020ac6550
5967b7daded0e34b1af9cd29bc2d694aa4e9da41
/src/qt/addresstablemodel.cpp
c78f9d7c49036bf2f203979a28908c4e4e4cb5cd
[ "MIT" ]
permissive
bestsoftdevelop777/NPayNetwork
5d1cfc5e0ecb2f8503c041b9aad608eac7c94228
1d301e09b6950bb185a864b5556e51bd1a7380bf
refs/heads/master
2023-03-14T15:31:54.593469
2018-09-16T08:49:58
2018-09-16T08:49:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,203
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The NPAYNETWORK developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet.h" #include "askpassphrasedialog.h" #include <QDebug> #include <QFont> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; const QString AddressTableModel::Zerocoin = "X"; struct AddressTableEntry { enum Type { Sending, Receiving, Zerocoin, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; QString pubcoin; AddressTableEntry() {} AddressTableEntry(Type type, const QString &pubcoin): type(type), pubcoin(pubcoin) {} AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const { return a.address < b.address; } bool operator()(const AddressTableEntry& a, const QString& b) const { return a.address < b; } bool operator()(const QString& a, const AddressTableEntry& b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet* wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel* parent; AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) { const CBitcoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch (status) { case CT_NEW: if (inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if (!inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if (!inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } void updateEntry(const QString &pubCoin, const QString &isUsed, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = AddressTableEntry::Zerocoin; switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_NEW, but entry is already in model"; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, isUsed, pubCoin)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = isUsed; parent->emitDataChanged(lowerIndex); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry* index(int idx) { if (idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case Label: if (rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if (index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } return font; } else if (role == TypeRole) { switch (rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (!index.isValid()) return false; AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if (role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get(); if (index.column() == Label) { // Do nothing, if old label == new label if (rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if (index.column() == Address) { CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if (boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if (newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if (wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if (rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const { if (!index.isValid()) return 0; AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if (rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column() == Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const { Q_UNUSED(parent); AddressTableEntry* data = priv->index(row); if (data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { // Update address book model from NPayNetwork core priv->updateEntry(address, label, isMine, purpose, status); } void AddressTableModel::updateEntry(const QString &pubCoin, const QString &isUsed, int status) { // Update stealth address book model from Bitcoin core priv->updateEntry(pubCoin, isUsed, status); } QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if (type == Send) { if (!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if (type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if (!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, true)); if (!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if (!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent) { Q_UNUSED(parent); AddressTableEntry* rec = priv->index(row); if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString& address) const { { LOCK(wallet->cs_wallet); CBitcoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString& address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if (lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex())); }
[ "vangyangpao@gmail.com" ]
vangyangpao@gmail.com
db709be48eafb687cdfe6c06c29b64e8503999db
56a13917921ee7b8bb2445c30bcbbba1dea0a503
/Codechef/March-Challenge-2021/SPACEARR.cpp
641be92e02bdd02a26d49367d0f993a761d757c1
[]
no_license
VaibhavVerma16113108/Competitive-Programming
4ffaeee01c35b4d400551865400c35c2e94a8aee
b67df9eab98ecb383ce39b11e089d4db4b75a4ec
refs/heads/main
2023-05-11T21:09:02.795214
2021-06-08T12:02:27
2021-06-08T12:02:27
333,001,192
0
0
null
null
null
null
UTF-8
C++
false
false
819
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; #define ll long long int main() { int t; cin >> t; while (t--) { ll n; cin >> n; ll arr[n + 5]; ll arrSum = 0; for (int i = 1; i <= n; i++) { cin >> arr[i]; arrSum += arr[i]; } ll totalSum = n * (n + 1) / 2; ll diff = totalSum - arrSum; sort(arr + 1, arr + n + 1); bool firstWins = true; for (int i = 1; i <= n; i++) { if (arr[i] > i) { firstWins = false; break; } } if (!firstWins || (diff % 2) == 0) cout << "Second" << endl; else cout << "First" << endl; } return 0; }
[ "vaibhav.verrma@gmail.com" ]
vaibhav.verrma@gmail.com
f1b2313c7256f22d3179f7c57f0a700e637c5692
33392bbfbc4abd42b0c67843c7c6ba9e0692f845
/vision/L2/examples/hdrdecompand/xf_hdrdecompand_tb.cpp
e7c129da7381d3a1843f7f06c896deb218fb1774
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
Xilinx/Vitis_Libraries
bad9474bf099ed288418430f695572418c87bc29
2e6c66f83ee6ad21a7c4f20d6456754c8e522995
refs/heads/main
2023-07-20T09:01:16.129113
2023-06-08T08:18:19
2023-06-08T08:18:19
210,433,135
785
371
Apache-2.0
2023-07-06T21:35:46
2019-09-23T19:13:46
C++
UTF-8
C++
false
false
9,049
cpp
/* * Copyright 2022 Xilinx, 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 "common/xf_headers.hpp" #include <stdlib.h> #include <ap_int.h> #include <iostream> #include <math.h> #include "xf_hdrdecompand_tb_config.h" #include "xcl2.hpp" #include "xf_opencl_wrap.hpp" void bayerizeImage(cv::Mat img, cv::Mat& bayer_image, cv::Mat& cfa_output, int code) { for (int i = 0; i < img.rows; i++) { for (int j = 0; j < img.cols; j++) { cv::Vec3w in = img.at<cv::Vec3w>(i, j); cv::Vec3w b; b[0] = 0; b[1] = 0; b[2] = 0; if (code == 0) { // BG if ((i & 1) == 0) { // even row if ((j & 1) == 0) { // even col b[0] = in[0]; cfa_output.at<ushort>(i, j) = in[0]; } else { // odd col b[1] = in[1]; cfa_output.at<ushort>(i, j) = in[1]; } } else { // odd row if ((j & 1) == 0) { // even col b[1] = in[1]; cfa_output.at<ushort>(i, j) = in[1]; } else { // odd col b[2] = in[2]; cfa_output.at<ushort>(i, j) = in[2]; } } } if (code == 1) { // GB if ((i & 1) == 0) { // even row if ((j & 1) == 0) { // even col b[1] = in[1]; cfa_output.at<ushort>(i, j) = in[1]; } else { // odd col b[0] = in[0]; cfa_output.at<ushort>(i, j) = in[0]; } } else { // odd row if ((j & 1) == 0) { // even col b[2] = in[2]; cfa_output.at<ushort>(i, j) = in[2]; } else { // odd col b[1] = in[1]; cfa_output.at<ushort>(i, j) = in[1]; } } } if (code == 2) { // GR if ((i & 1) == 0) { // even row if ((j & 1) == 0) { // even col b[1] = in[1]; cfa_output.at<ushort>(i, j) = in[1]; } else { // odd col b[2] = in[2]; cfa_output.at<ushort>(i, j) = in[2]; } } else { // odd row if ((j & 1) == 0) { // even col b[0] = in[0]; cfa_output.at<ushort>(i, j) = in[0]; } else { // odd col b[1] = in[1]; cfa_output.at<ushort>(i, j) = in[1]; } } } if (code == 3) { // RG if ((i & 1) == 0) { // even row if ((j & 1) == 0) { // even col b[2] = in[2]; cfa_output.at<ushort>(i, j) = in[2]; } else { // odd col b[1] = in[1]; cfa_output.at<ushort>(i, j) = in[1]; } } else { // odd row if ((j & 1) == 0) { // even col b[1] = in[1]; cfa_output.at<ushort>(i, j) = in[1]; } else { // odd col b[0] = in[0]; cfa_output.at<ushort>(i, j) = in[0]; } } } bayer_image.at<cv::Vec3w>(i, j) = b; } } } void compute_pxl(int pxl_val, int& out_val, int params[3][4][3], int color_idx) { if (pxl_val < params[color_idx][0][0]) { out_val = params[color_idx][0][1] * (pxl_val - params[color_idx][0][2]); } else if (pxl_val < params[color_idx][1][0]) { out_val = params[color_idx][1][1] * (pxl_val - params[color_idx][1][2]); } else if (pxl_val < params[color_idx][2][0]) { out_val = params[color_idx][2][1] * (pxl_val - params[color_idx][2][2]); } else { out_val = params[color_idx][3][1] * (pxl_val - params[color_idx][3][2]); } return; } int main(int argc, char** argv) { if (argc != 2) { printf("Usage: %s <INPUT IMAGE PATH > \n", argv[0]); return EXIT_FAILURE; } cv::Mat in_img, out_img, out_hls, diff; // Reading in the images: in_img = cv::imread(argv[1], -1); if (in_img.data == NULL) { printf("ERROR: Cannot open image %s\n ", argv[1]); return EXIT_FAILURE; } diff.create(in_img.rows, in_img.cols, CV_OUT_TYPE); out_img.create(in_img.rows, in_img.cols, CV_OUT_TYPE); out_hls.create(in_img.rows, in_img.cols, CV_OUT_TYPE); int height = in_img.rows; int width = in_img.cols; int out_val; int pxl_val; // Create the Bayer pattern CFA output cv::Mat cfa_bayer_output(in_img.rows, in_img.cols, CV_IN_TYPE); // simulate the Bayer pattern CFA outputi cv::Mat color_cfa_bayer_output(in_img.rows, in_img.cols, in_img.type()); // Bayer pattern CFA output in color unsigned short bformat = BPATTERN; // Bayer format BG-0; GB-1; GR-2; RG-3 bayerizeImage(in_img, color_cfa_bayer_output, cfa_bayer_output, bformat); cv::imwrite("bayer_image.png", color_cfa_bayer_output); cv::imwrite("cfa_output.png", cfa_bayer_output); #if T_12U int params[3][4][3] = {{{512, 4, 0}, {1408, 16, 384}, {2176, 64, 1152}, {4096, 512, 2048}}, {{512, 4, 0}, {1408, 16, 384}, {2176, 64, 1152}, {4096, 512, 2048}}, {{512, 4, 0}, {1408, 16, 384}, {2176, 64, 1152}, {4096, 512, 2048}}}; // 12 bit to 20 bit #else int params[3][4][3] = { {{8192, 4, 0}, {22528, 16, 6144}, {34816, 64, 18432}, {65536, 512, 32768}}, {{8192, 4, 0}, {22528, 16, 6144}, {34816, 64, 18432}, {65536, 512, 32768}}, {{8192, 4, 0}, {22528, 16, 6144}, {34816, 64, 18432}, {65536, 512, 32768}}}; // 16 bit to 24 bit #endif int color_idx, row_idx, col_idx; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { pxl_val = cfa_bayer_output.at<ushort>(i, j); row_idx = i; col_idx = j; if (bformat == XF_BAYER_GB) { col_idx += 1; } if (bformat == XF_BAYER_GR) { row_idx += 1; } if (bformat == XF_BAYER_RG) { col_idx += 1; row_idx += 1; } if ((row_idx & 1) == 0) { // even row if ((col_idx & 1) == 0) { // even col color_idx = 0; // R location } else { // odd col color_idx = 1; // G location } } else { // odd row if ((col_idx & 1) == 0) { // even col color_idx = 1; // G location } else { // odd col color_idx = 2; // B location } } compute_pxl(pxl_val, out_val, params, color_idx); out_img.at<int>(i, j) = out_val; } } ////////////Top function call ////////////////// /////////////////////////////////////// CL //////////////////////// (void)cl_kernel_mgr::registerKernel("hdrdecompand_accel", "krnl_hdrdecompand", XCLIN(cfa_bayer_output), XCLOUT(out_hls), XCLIN(params), XCLIN(bformat), XCLIN(height), XCLIN(width)); cl_kernel_mgr::exec_all(); /////////////////////////////////////// end of CL //////////////////////// cv::imwrite("out_img.jpg", out_img); cv::imwrite("out_hls.jpg", out_hls); // Compute absolute difference image cv::absdiff(out_img, out_hls, diff); // Save the difference image for debugging purpose: cv::imwrite("error.png", diff); float err_per; xf::cv::analyzeDiff(diff, 1, err_per); if (err_per > 0.0f) { fprintf(stderr, "ERROR: Test Failed.\n "); return 1; } std::cout << "Test Passed " << std::endl; return 0; }
[ "do-not-reply@gitenterprise.xilinx.com" ]
do-not-reply@gitenterprise.xilinx.com
096ebba7f880bb9b4dcf7c48efac10eef5ec3100
3b80e3064851f19469d4a7b9a5b5231690954eed
/C++/Panoramix'sPrediction.cpp
ec7796af6e135d5adacf916ac3a780ecc7538ac3
[]
no_license
vincentjordan27/CP
e8a3f69224bb8aee7141606cbb49c24ae33856f4
98abb423ace05b33df30b5fea4715c6ff47feae3
refs/heads/master
2020-06-02T04:33:45.453375
2019-06-09T17:50:40
2019-06-09T17:50:40
191,032,462
0
0
null
null
null
null
UTF-8
C++
false
false
396
cpp
#include<iostream> using namespace std; bool prime(int x) { bool flag = true; for(int i=2; i*i <=x; i++) { if(x%i == 0) flag = false; } return flag; } int main() { int a,b,i; cin >> a >> b; for(i=a+1;;i++) if(prime(i)) break; if(i == b) cout << "YES" <<endl; else cout <<"NO" <<endl; return 0; }
[ "vincentiustampubolon2@gmail.com" ]
vincentiustampubolon2@gmail.com
2b8474cd1a9aa176732ec4859256570cffdb59e8
2aa91906a30ee093de3284d84751a86836a0df21
/MarioGames/SharedContext.h
4cf6e3f6545aaaeadd0695fa8b786dac0d2fa330
[]
no_license
ChrAlb/GUILesson
08d6005df970ae6cb4b586dcf964e8f6e965e9e5
20bfc089696f034295fa7ac0ca0691623ecaa96f
refs/heads/master
2020-04-13T16:04:13.038835
2018-12-27T15:49:09
2018-12-27T15:49:09
163,311,701
0
0
null
null
null
null
UTF-8
C++
false
false
901
h
#pragma once #include "Window.h" #include "EventManager.h" #include "TextureManager.h" #include "FontManager.h" #include "AudioManager.h" #include "SoundManager.h" #include "GUI_Manager.h" #include "System_Manager.h" #include "Entity_Manager.h" #include "DebugOverlay.h" class Map; struct SharedContext{ SharedContext(): m_wind(nullptr), m_eventManager(nullptr), m_textureManager(nullptr), m_fontManager(nullptr), m_audioManager(nullptr), m_soundManager(nullptr), m_systemManager(nullptr), m_entityManager(nullptr), m_gameMap(nullptr), m_guiManager(nullptr){} Window* m_wind; EventManager* m_eventManager; TextureManager* m_textureManager; FontManager* m_fontManager; AudioManager* m_audioManager; SoundManager* m_soundManager; SystemManager* m_systemManager; EntityManager* m_entityManager; Map* m_gameMap; GUI_Manager* m_guiManager; DebugOverlay m_debugOverlay; };
[ "albchr@gmail.com" ]
albchr@gmail.com
e8af040be9e885c0ebd2cd07aeee41c98c279585
211789df52f8e60b306c1d08ed7c0a5727ed23b6
/net/InitializeHandleInfo.h
c8e7c000bd9305146f165f9c3577b2e71fb21c50
[ "Apache-2.0" ]
permissive
GitArpe/miniblink49
64e57a7e11cc801060efe982f341087321e61c43
c83e06c57bbc89bf326d6d49fa5917a3d4b860d0
refs/heads/master
2020-03-23T18:35:37.613683
2018-07-21T01:12:38
2018-07-21T01:12:38
141,918,456
1
0
Apache-2.0
2018-07-22T17:56:15
2018-07-22T17:56:14
null
UTF-8
C++
false
false
574
h
#ifndef net_InitializeHandleInfo_h #define net_InitializeHandleInfo_h #include "net/ProxyType.h" #include "curl/curl.h" #include <string> namespace net { struct SetupHttpMethodInfo; struct InitializeHandleInfo { std::string url; std::string method; curl_slist* headers; std::string proxy; std::string wkeNetInterface; ProxyType proxyType; SetupHttpMethodInfo* methodInfo; InitializeHandleInfo() { methodInfo = nullptr; } ~InitializeHandleInfo(); }; } #endif // net_InitializeHandleInfo_h
[ "weolar@qq.com" ]
weolar@qq.com
80b082547d124efd3280898e312887ed8421068d
63a0a4075ddacc2b70821eb2c1daa89d81166ea6
/SimpleThreadPool/Collisions.h
708ee5169bf101d2de8c8328e2bf75d4de56c244
[]
no_license
David-Whiteford/Multithreading-Project
cbf1b9065c01db6ecd0711d08cc3c5fe93847384
f59174229268ba47771fcc235aff5b1eabb2d614
refs/heads/master
2023-04-29T20:14:03.202899
2021-05-17T07:28:49
2021-05-17T07:28:49
349,058,390
0
0
null
null
null
null
UTF-8
C++
false
false
680
h
#pragma once #include <SFML/Graphics.hpp> #include <iostream> class Collisions { public: Collisions(); ~Collisions(); //set up all functions for collisions bool pointCircleCol(sf::Vector2f t_point, sf::Vector2f t_circle, int t_radius); bool circleToCircleCol(sf::Vector2f t_circle1, sf::Vector2f t_circle2, int t_circleOneRadius, int t_circleTwoRadius); bool rayCastToSpriteCol(sf::Vector2f t_rayEnd, sf::Vector2f t_spritePos,sf::Vector2f t_size); bool ViewCheck(sf::View &t_view,sf::Vector2f t_pos); bool boxToBoxCol(sf::Vector2f t_rectOnePos, sf::Vector2f t_rectTwoPos, sf::Vector2f t_rectOneSize, sf::Vector2f t_rectTwoSize); private: bool m_colision = false; };
[ "c00204740@itcarlow.ie" ]
c00204740@itcarlow.ie
0547089500398412eac380f88dcf8aba4d8a1e91
f62e37d6a8884960b8e315c61a924650d756df0d
/src/core/layers/interfaceLogger/interfaceLoggerQueue.cpp
975e987c5b9c2330876309379b5babf784cd7789
[ "MIT" ]
permissive
ardacoskunses/pal
cd5f0dfd35912239c32e884005bd68b391bb96e0
ec4457f9b005dcb7a6178debc19b1df65da57280
refs/heads/master
2020-03-28T18:00:47.178244
2018-09-12T04:59:18
2018-09-12T05:06:04
148,844,552
0
0
MIT
2018-09-14T21:41:30
2018-09-14T21:41:30
null
UTF-8
C++
false
false
16,413
cpp
/* *********************************************************************************************************************** * * Copyright (c) 2016-2018 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ #include "core/layers/interfaceLogger/interfaceLoggerCmdBuffer.h" #include "core/layers/interfaceLogger/interfaceLoggerDevice.h" #include "core/layers/interfaceLogger/interfaceLoggerFence.h" #include "core/layers/interfaceLogger/interfaceLoggerGpuMemory.h" #include "core/layers/interfaceLogger/interfaceLoggerImage.h" #include "core/layers/interfaceLogger/interfaceLoggerPlatform.h" #include "core/layers/interfaceLogger/interfaceLoggerQueue.h" #include "core/layers/interfaceLogger/interfaceLoggerQueueSemaphore.h" #include "core/layers/interfaceLogger/interfaceLoggerSwapChain.h" using namespace Util; namespace Pal { namespace InterfaceLogger { // ===================================================================================================================== Queue::Queue( IQueue* pNextQueue, Device* pDevice, uint32 objectId) : QueueDecorator(pNextQueue, pDevice), m_pPlatform(static_cast<Platform*>(pDevice->GetPlatform())), m_objectId(objectId) { } // ===================================================================================================================== Result Queue::Submit( const SubmitInfo& submitInfo) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueSubmit; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::Submit(submitInfo); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndBeginMap("submitInfo", false); pLogContext->KeyAndBeginMap("cmdBuffers", false); for (uint32 idx = 0; idx < submitInfo.cmdBufferCount; ++idx) { pLogContext->KeyAndObject("object", submitInfo.ppCmdBuffers[idx]); if ((submitInfo.pCmdBufInfoList != nullptr) && submitInfo.pCmdBufInfoList[idx].isValid) { pLogContext->KeyAndStruct("info", submitInfo.pCmdBufInfoList[idx]); } else { pLogContext->KeyAndNullValue("info"); } } pLogContext->EndMap(); pLogContext->KeyAndBeginList("gpuMemoryRefs", false); for (uint32 idx = 0; idx < submitInfo.gpuMemRefCount; ++idx) { pLogContext->Struct(submitInfo.pGpuMemoryRefs[idx]); } pLogContext->EndList(); pLogContext->KeyAndBeginList("doppRefs", false); for (uint32 idx = 0; idx < submitInfo.doppRefCount; ++idx) { pLogContext->Struct(submitInfo.pDoppRefs[idx]); } pLogContext->EndList(); pLogContext->KeyAndBeginList("blockIfFlipping", false); for (uint32 idx = 0; idx < submitInfo.blockIfFlippingCount; ++idx) { pLogContext->Object(submitInfo.ppBlockIfFlipping[idx]); } pLogContext->EndList(); pLogContext->KeyAndObject("fence", submitInfo.pFence); pLogContext->EndMap(); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== Result Queue::WaitIdle() { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueWaitIdle; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::WaitIdle(); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== Result Queue::SignalQueueSemaphore( IQueueSemaphore* pQueueSemaphore) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueSignalQueueSemaphore; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::SignalQueueSemaphore(pQueueSemaphore); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndObject("queueSemaphore", pQueueSemaphore); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== Result Queue::WaitQueueSemaphore( IQueueSemaphore* pQueueSemaphore) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueWaitQueueSemaphore; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::WaitQueueSemaphore(pQueueSemaphore); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndObject("queueSemaphore", pQueueSemaphore); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== Result Queue::PresentDirect( const PresentDirectInfo& presentInfo) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueuePresentDirect; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::PresentDirect(presentInfo); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndStruct("presentInfo", presentInfo); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } m_pPlatform->NotifyPresent(); return result; } // ===================================================================================================================== Result Queue::PresentSwapChain( const PresentSwapChainInfo& presentInfo) { // Note: We must always call down to the next layer because we must release ownership of the image index. BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueuePresentSwapChain; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::PresentSwapChain(presentInfo); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndStruct("presentInfo", presentInfo); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } m_pPlatform->NotifyPresent(); return result; } // ===================================================================================================================== Result Queue::Delay( float delay) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueDelay; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::Delay(delay); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndValue("delay", delay); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== Result Queue::DelayAfterVsync( float delayInUs, const IPrivateScreen* pScreen) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueDelayAfterVsync; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::DelayAfterVsync(delayInUs, pScreen); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndValue("delayInUs", delayInUs); pLogContext->KeyAndObject("screen", pScreen); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== Result Queue::RemapVirtualMemoryPages( uint32 rangeCount, const VirtualMemoryRemapRange* pRanges, bool doNotWait, IFence* pFence) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueRemapVirtualMemoryPages; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::RemapVirtualMemoryPages(rangeCount, pRanges, doNotWait, pFence); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndBeginList("ranges", false); for (uint32 idx = 0; idx < rangeCount; ++idx) { pLogContext->Struct(pRanges[idx]); } pLogContext->EndList(); pLogContext->KeyAndValue("doNotWait", doNotWait); pLogContext->KeyAndObject("fence", pFence); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== Result Queue::CopyVirtualMemoryPageMappings( uint32 rangeCount, const VirtualMemoryCopyPageMappingsRange* pRanges, bool doNotWait) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueCopyVirtualMemoryPageMappings; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::CopyVirtualMemoryPageMappings(rangeCount, pRanges, doNotWait); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndBeginList("ranges", false); for (uint32 idx = 0; idx < rangeCount; ++idx) { pLogContext->Struct(pRanges[idx]); } pLogContext->EndList(); pLogContext->KeyAndValue("doNotWait", doNotWait); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== Result Queue::AssociateFenceWithLastSubmit( IFence* pFence) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueAssociateFenceWithLastSubmit; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); const Result result = QueueDecorator::AssociateFenceWithLastSubmit(pFence); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndObject("fence", pFence); pLogContext->EndInput(); pLogContext->BeginOutput(); pLogContext->KeyAndEnum("result", result); pLogContext->EndOutput(); m_pPlatform->LogEndFunc(pLogContext); } return result; } // ===================================================================================================================== void Queue::SetExecutionPriority( QueuePriority priority) { BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueSetExecutionPriority; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); QueueDecorator::SetExecutionPriority(priority); funcInfo.postCallTime = m_pPlatform->GetTime(); LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { pLogContext->BeginInput(); pLogContext->KeyAndEnum("priority", priority); pLogContext->EndInput(); m_pPlatform->LogEndFunc(pLogContext); } } // ===================================================================================================================== void Queue::Destroy() { // Note that we can't time a Destroy call. BeginFuncInfo funcInfo; funcInfo.funcId = InterfaceFunc::QueueDestroy; funcInfo.objectId = m_objectId; funcInfo.preCallTime = m_pPlatform->GetTime(); funcInfo.postCallTime = funcInfo.preCallTime; LogContext* pLogContext = nullptr; if (m_pPlatform->LogBeginFunc(funcInfo, &pLogContext)) { m_pPlatform->LogEndFunc(pLogContext); } QueueDecorator::Destroy(); } } // InterfaceLogger } // Pal
[ "jacob.he@amd.com" ]
jacob.he@amd.com
e9a279a05b806c28d23f9bbb8c510078e2b82475
d9ec3df09a9205c258015b125f6a662c516b3a4b
/Service/FindObjectsAService/simplerawobject.h
357e2ef7dc701cdb7798da36a7205cb1c8cbbfb0
[]
no_license
RealMetamorphEDU/Coursework_Antivirus
0712e2865294a765c3147a1fb8aa543d03efeba6
0989df769df52761cb7f6487e6343fdf1882518f
refs/heads/master
2021-02-09T12:20:22.088962
2020-06-12T14:14:50
2020-06-12T14:14:50
244,281,551
2
5
null
2020-05-14T16:29:56
2020-03-02T04:40:50
C++
UTF-8
C++
false
false
549
h
#ifndef SIMPLERAWOBJECT_H #define SIMPLERAWOBJECT_H #include "rawobject.h" class QFile; class SimpleRawObject: public RawObject { QFile *source; std::istream *stream; public: SimpleRawObject(const QString &filename, QObject *parent = nullptr); ~SimpleRawObject(); QString getFullName() override; qint64 getSize() override; QByteArray readBlock(qint64 offset, qint64 len) override; void resetPos() override; bool canRead() override; std::istream* getInputStream() override; }; #endif // SIMPLERAWOBJECT_H
[ "andr.timchuk@yandex.ru" ]
andr.timchuk@yandex.ru
027efc63690bbfd2bf340ba46cdfa7440e646b99
24f26275ffcd9324998d7570ea9fda82578eeb9e
/content/browser/devtools/devtools_pipe_handler.h
8c9c0c0821721dc3e9873c132d2da3cd8b333737
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
1,667
h
// Copyright 2017 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 CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_PIPE_HANDLER_H_ #define CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_PIPE_HANDLER_H_ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "content/public/browser/devtools_agent_host_client.h" namespace base { class Thread; } namespace content { class PipeReaderBase; class DevToolsPipeHandler : public DevToolsAgentHostClient { public: DevToolsPipeHandler(); ~DevToolsPipeHandler() override; void HandleMessage(const std::string& message); void DetachFromTarget(); // DevToolsAgentHostClient overrides void DispatchProtocolMessage(DevToolsAgentHost* agent_host, const std::string& message) override; void AgentHostClosed(DevToolsAgentHost* agent_host) override; bool UsesBinaryProtocol() override; void Shutdown(); private: enum class ProtocolMode { // Legacy text protocol format with messages separated by \0's. kASCIIZ, // Experimental (!) CBOR (RFC 7049) based binary format. kCBOR }; ProtocolMode mode_; std::unique_ptr<PipeReaderBase> pipe_reader_; std::unique_ptr<base::Thread> read_thread_; std::unique_ptr<base::Thread> write_thread_; scoped_refptr<DevToolsAgentHost> browser_target_; int read_fd_; int write_fd_; bool shutting_down_ = false; base::WeakPtrFactory<DevToolsPipeHandler> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DevToolsPipeHandler); }; } // namespace content #endif // CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_PIPE_HANDLER_H_
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
2bc250bfe68e3dd54999718a20d9492fd457fabc
ef1a100a6d9c013e88771a17b45563b9dcf464ba
/ALevel/Templates/Dijkstra-t2.cpp
271cc8ccc929ab6b682839392c7c615a4537b4b7
[]
no_license
Bingyy/APAT
7780e54d15c5391aa4f64d81d51e5cb57e3dc00b
69e329170c916b659cb3b4a6c233b02d2affb592
refs/heads/master
2020-09-23T17:01:02.206350
2017-06-05T14:09:56
2017-06-05T14:09:56
66,179,781
0
0
null
null
null
null
UTF-8
C++
false
false
1,847
cpp
#include <stdio.h> #include <vector> using namespace std; int MAXN = 1000; int INF = 1 << 30; int n; // 顶点数 int d[MAXN] = {INF}; bool visited[MAXN] = {false}; struct node { int v, dis; // v是顶点编号,dis是距离起始点距离 }; vector<node> Adj[MAXN]; // 用vector数组表示邻接表 // 邻接表版 void Dijkstra_Adj(int s)// 起点 { // 初始化 fill(d,d+MAXN,INF); d[s] = 0; //寻找最小的顶点下标u for(int i = 0; i < n; i++) // 控制循环n次,目的是为了n次从V-S中找到距离起始点最小的下标,S初始为空集 { int u = -1, MIN = INF; //找u,自然需要初始化,MIN是辅助变量 for(int j = 0; i < n; i++) { if(visited[j] == false && d[j] < MIN) // 起始d[s] = 0作为奠基,j也是从0开始 { u = j; MIN = d[j]; } } // 找到u了吗? if(u == -1) return; //没有找到,结束 visited[u] = true;//找到了! for(int j = 0; j < Adj[u].size();j++)// 在u的邻接表中操作 { int v = Adj[u][j].v;//注意区别顶点表下标和邻接表下标:v是顶点表下标,j是邻接表下标 if(visited[j] == false && d[u] + Adj[u][j].dis < d[v]) { d[v] = d[u] + Adj[u][j].dis; } } } } int G[MAXN][MAXN]; void Dijkstra_Matrix(int s) { //初始化 fill(d,d+MAXN, INF); d[s] = 0; //这句也非常关键 for(int i = 0; i < n; i++) { int u = -1, MIN = INF; for(int j = 0; j < n; j++) { if(visited[j] == false && d[j] < MIN) { u = j; MIN = d[j]; } } //u是否已经找到? if(u == -1) return; visited[u] = true; for(int j = 0; j < n;j++) { if(visited[j] == false && G[u][j] != INF && d[u] + G[u][j] < d[j]) // 邻接表中确定是相连的,这里需要再循环找到邻接的以确定修改 { d[j] = d[u] + G[u][j]; } } } } int main() { return 0; }
[ "rick@bingwang.biz" ]
rick@bingwang.biz
daa4c6469e50762f704232d137d34b12fe143cca
e4298b0c2a085fff2dd265061f4a9309072fee5d
/countDigitseff.cpp
c4658dcac687c25447d03060004f53cc2e088680
[]
no_license
sidchiku9/GeneralDSA
68e86d8246273740df7032f114cb4f8a282e68e4
a892a2192054b6db2e47cb927e679295b4532642
refs/heads/master
2021-04-14T18:25:28.651426
2020-11-23T06:06:07
2020-11-23T06:06:07
249,254,756
0
0
null
null
null
null
UTF-8
C++
false
false
382
cpp
#include <stdlib.h> #include <iostream> #include <cmath> using namespace std; int countDig(int x){ return log10(x) + 1; } int main(){ int number = 0; int result = 0; cout << "Enter the number you want to count the digits of : " << endl; cin >> number; result = countDig(number); cout << "The number of digits : " << result << endl; return 0; }
[ "sidchiku9@gmail.com" ]
sidchiku9@gmail.com
56ff4df729d8f6b37eba4445a67d49e12b4cf2ee
c4f821a285998cff73410b51103a88b737e7a254
/template/大数/num_push.cpp
1d7b96e11c663cb1fbd0d97204a7c3dec6fc4a08
[]
no_license
sust18023/ACM
97e8f8a0334fc6da51b36eec5bc95b440798b93e
bce1cc425ef4eee1f9e5de865625c5a7b573f2b2
refs/heads/master
2020-12-26T16:34:20.659058
2020-06-03T01:51:17
2020-06-03T01:51:17
237,565,573
0
0
null
null
null
null
UTF-8
C++
false
false
554
cpp
void num_plus(char *a,char *b){ char aa[maxn]; memset(aa,0,sizeof aa); int lena=strlen(a); int lenb=strlen(b); strrev(a); strrev(b); int len=max(lena,lenb); int yu=0; int i=0; while(1){ if(i<lena&&i<lenb){ yu=(a[i]-'0')+(b[i]-'0')+yu; aa[i]=yu%10+'0'; yu=yu/10; }else if(i<lena){ yu=(a[i]-'0')+yu; aa[i]=yu%10+'0'; yu=yu/10; }else if(i<lenb){ yu=(b[i]-'0')+yu; aa[i]=yu%10+'0'; yu=yu/10; }else if(yu!=0){ aa[i]=yu%10+'0'; yu=yu/10; }else break; ++i; } strrev(aa); printf("%s\n", aa); return ; }
[ "1021458254@qq.com" ]
1021458254@qq.com
0256d724c4ee9615ade5dc2c90195ef180c563ed
ee083d3ae978e770ee403d452aa9fdfb50e9f3ef
/gcc/ch02/grm030.cpp
345008fcfc9cc731b41789e2bfaa52f3095bb960
[]
no_license
moonmile/gyakubiki-cpp
be0b0c704cf2592564fb37b596e86ca74e51b52f
b18ea7628e388a7a36cabda1a5b7af642b1b3967
refs/heads/master
2020-03-21T04:46:33.673723
2018-06-21T06:07:35
2018-06-21T06:07:35
138,126,465
0
0
null
null
null
null
UTF-8
C++
false
false
111
cpp
#include <stdio.h> int main( void ) { int x, m, n; m = 20; n = 10; printf( "m * n = %d\n", m * n ); }
[ "masuda@moonmile.net" ]
masuda@moonmile.net
cc5ffe5283af3b791d699e5ab18f146a0172121a
9bb8234244f4b4be0130689b8bed4ff1b8faf547
/heron/statemgrs/src/cpp/statemgr/heron-localfilestatemgr.cpp
fdf3299446e60e1409adfc520c0f7db584b1b5b4
[ "Apache-2.0" ]
permissive
containerz/heron-elodina
214b7cc2badb3bb2305585766031fb3e5edee738
4b50239e1d21efe49ae8808925c907956e5a7a7e
refs/heads/master
2021-01-17T05:51:11.189743
2016-05-23T12:57:50
2016-05-23T12:57:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,244
cpp
/* * Copyright 2015 Twitter, 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 "statemgr/heron-localfilestatemgr.h" #include <stdio.h> #include <unistd.h> #include <errno.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include "proto/messages.h" #include "basics/basics.h" #include "errors/errors.h" #include "threads/threads.h" #include "network/network.h" namespace heron { namespace common { HeronLocalFileStateMgr::HeronLocalFileStateMgr(const std::string& _topleveldir, EventLoop* eventLoop) : HeronStateMgr(_topleveldir), eventLoop_(eventLoop) { InitTree(); } HeronLocalFileStateMgr::~HeronLocalFileStateMgr() { // nothing really } void HeronLocalFileStateMgr::InitTree() { sp_string dpath = GetTopLevelDir(); sp_string path = dpath; path += "/topologies"; FileUtils::makeDirectory(path); path = dpath; path += "/tmasters"; FileUtils::makeDirectory(path); path = dpath; path += "/pplans"; FileUtils::makeDirectory(path); path = dpath; path += "/executionstate"; FileUtils::makeDirectory(path); } void HeronLocalFileStateMgr::SetTMasterLocationWatch(const std::string& topology_name, VCallback<> watcher) { CHECK(watcher); // We kind of cheat here. We check periodically time_t tmaster_last_change = FileUtils::getModifiedTime(GetTMasterLocationPath(topology_name)); auto cb = [topology_name, tmaster_last_change, watcher, this](EventLoop::Status status) { this->CheckTMasterLocation(topology_name, tmaster_last_change, std::move(watcher), status); }; CHECK_GT(eventLoop_->registerTimer(std::move(cb), false, 1000000), 0); } void HeronLocalFileStateMgr::GetTMasterLocation(const std::string& _topology_name, proto::tmaster::TMasterLocation* _return, VCallback<proto::system::StatusCode> cb) { std::string contents; proto::system::StatusCode status = ReadAllFileContents(GetTMasterLocationPath(_topology_name), contents); if (status == proto::system::OK) { if (!_return->ParseFromString(contents)) { status = proto::system::STATE_CORRUPTED; } } auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::SetTMasterLocation(const proto::tmaster::TMasterLocation& _location, VCallback<proto::system::StatusCode> cb) { // Note: Unlike Zk statemgr, we overwrite the location even if there is already one. // This is because when running in local mode we control when a tmaster dies and // comes up deterministically. std::string fname = GetTMasterLocationPath(_location.topology_name()); std::string contents; _location.SerializeToString(&contents); proto::system::StatusCode status = WriteToFile(fname, contents); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::CreateTopology(const proto::api::Topology& _topology, VCallback<proto::system::StatusCode> cb) { std::string fname = GetTopologyPath(_topology.name()); // First check to see if location exists. if (MakeSureFileDoesNotExist(fname) != proto::system::OK) { auto wCb = [cb](EventLoop::Status) { cb(proto::system::PATH_ALREADY_EXISTS); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); return; } std::string contents; _topology.SerializeToString(&contents); proto::system::StatusCode status = WriteToFile(fname, contents); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::DeleteTopology(const sp_string& _topology_name, VCallback<proto::system::StatusCode> cb) { proto::system::StatusCode status = DeleteFile(GetTopologyPath(_topology_name)); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::SetTopology(const proto::api::Topology& _topology, VCallback<proto::system::StatusCode> cb) { std::string fname = GetTopologyPath(_topology.name()); std::string contents; _topology.SerializeToString(&contents); proto::system::StatusCode status = WriteToFile(fname, contents); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::GetTopology(const std::string& _topology_name, proto::api::Topology* _return, VCallback<proto::system::StatusCode> cb) { std::string contents; proto::system::StatusCode status = ReadAllFileContents(GetTopologyPath(_topology_name), contents); if (status == proto::system::OK) { if (!_return->ParseFromString(contents)) { status = proto::system::STATE_CORRUPTED; } } auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::CreatePhysicalPlan(const proto::system::PhysicalPlan& _pplan, VCallback<proto::system::StatusCode> cb) { std::string fname = GetPhysicalPlanPath(_pplan.topology().name()); // First check to see if location exists. if (MakeSureFileDoesNotExist(fname) != proto::system::OK) { auto wCb = [cb](EventLoop::Status) { cb(proto::system::PATH_ALREADY_EXISTS); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); return; } std::string contents; _pplan.SerializeToString(&contents); proto::system::StatusCode status = WriteToFile(fname, contents); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::DeletePhysicalPlan(const sp_string& _topology_name, VCallback<proto::system::StatusCode> cb) { proto::system::StatusCode status = DeleteFile(GetPhysicalPlanPath(_topology_name)); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::SetPhysicalPlan(const proto::system::PhysicalPlan& _pplan, VCallback<proto::system::StatusCode> cb) { std::string contents; _pplan.SerializeToString(&contents); proto::system::StatusCode status = WriteToFile(GetPhysicalPlanPath(_pplan.topology().name()), contents); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::GetPhysicalPlan(const std::string& _topology_name, proto::system::PhysicalPlan* _return, VCallback<proto::system::StatusCode> cb) { std::string contents; proto::system::StatusCode status = ReadAllFileContents(GetPhysicalPlanPath(_topology_name), contents); if (status == proto::system::OK) { if (!_return->ParseFromString(contents)) { status = proto::system::STATE_CORRUPTED; } } auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::CreateExecutionState(const proto::system::ExecutionState& _st, VCallback<proto::system::StatusCode> cb) { std::string fname = GetExecutionStatePath(_st.topology_name()); // First check to see if location exists. if (MakeSureFileDoesNotExist(fname) != proto::system::OK) { auto wCb = [cb](EventLoop::Status) { cb(proto::system::PATH_ALREADY_EXISTS); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); return; } std::string contents; _st.SerializeToString(&contents); proto::system::StatusCode status = WriteToFile(fname, contents); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::DeleteExecutionState(const std::string& _topology_name, VCallback<proto::system::StatusCode> cb) { proto::system::StatusCode status = DeleteFile(GetExecutionStatePath(_topology_name)); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::GetExecutionState(const std::string& _topology_name, proto::system::ExecutionState* _return, VCallback<proto::system::StatusCode> cb) { std::string contents; proto::system::StatusCode status = ReadAllFileContents(GetExecutionStatePath(_topology_name), contents); if (status == proto::system::OK) { if (!_return->ParseFromString(contents)) { status = proto::system::STATE_CORRUPTED; } } auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::SetExecutionState(const proto::system::ExecutionState& _st, VCallback<proto::system::StatusCode> cb) { std::string fname = GetExecutionStatePath(_st.topology_name()); std::string contents; _st.SerializeToString(&contents); proto::system::StatusCode status = WriteToFile(fname, contents); auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::ListExecutionStateTopologies(std::vector<sp_string>* _return, VCallback<proto::system::StatusCode> cb) { proto::system::StatusCode status = proto::system::OK; if (FileUtils::listFiles(GetExecutionStateDir(), *_return) != 0) { status = proto::system::NOTOK; } auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } void HeronLocalFileStateMgr::ListTopologies(std::vector<sp_string>* _return, VCallback<proto::system::StatusCode> cb) { proto::system::StatusCode status = proto::system::OK; if (FileUtils::listFiles(GetTopologyDir(), *_return) != 0) { status = proto::system::NOTOK; } auto wCb = [cb, status](EventLoop::Status) { cb(status); }; CHECK_GT(eventLoop_->registerTimer(std::move(wCb), false, 0), 0); } proto::system::StatusCode HeronLocalFileStateMgr::ReadAllFileContents(const std::string& _filename, std::string& _contents) { std::ifstream in(_filename.c_str(), std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); _contents.resize(in.tellg()); in.seekg(0, std::ios::beg); in.read(&_contents[0], _contents.size()); in.close(); return proto::system::OK; } else { // We could not open the file LOG(ERROR) << "Error reading from " << _filename << " with errno " << errno << "\n"; return proto::system::PATH_DOES_NOT_EXIST; } } proto::system::StatusCode HeronLocalFileStateMgr::WriteToFile(const std::string& _filename, const std::string& _contents) { const std::string tmp_filename = _filename + ".tmp"; ::unlink(tmp_filename.c_str()); std::ofstream ot(tmp_filename.c_str(), std::ios::out | std::ios::binary); if (ot) { ot << _contents; ot.close(); if (rename(tmp_filename.c_str(), _filename.c_str()) != 0) { LOG(ERROR) << "Rename failed from " << tmp_filename << " to " << _filename << "\n"; return proto::system::STATE_WRITE_ERROR; } else { return proto::system::OK; } } else { LOG(ERROR) << "Error writing to " << _filename << " with errno " << errno << std::endl; return proto::system::STATE_WRITE_ERROR; } } proto::system::StatusCode HeronLocalFileStateMgr::DeleteFile(const std::string& _filename) { if (remove(_filename.c_str()) != 0) { return proto::system::NOTOK; } else { return proto::system::OK; } } proto::system::StatusCode HeronLocalFileStateMgr::MakeSureFileDoesNotExist( const std::string& _filename) { std::ifstream in(_filename.c_str(), std::ios::in | std::ios::binary); if (in) { // it already exists. in.close(); return proto::system::PATH_ALREADY_EXISTS; } else { return proto::system::OK; } } void HeronLocalFileStateMgr::CheckTMasterLocation(std::string topology_name, time_t last_change, VCallback<> watcher, EventLoop::Status) { time_t nlast_change = FileUtils::getModifiedTime(GetTMasterLocationPath(topology_name)); if (nlast_change > last_change) { watcher(); } else { nlast_change = last_change; } auto cb = [topology_name, nlast_change, watcher, this](EventLoop::Status status) { this->CheckTMasterLocation(topology_name, nlast_change, std::move(watcher), status); }; CHECK_GT(eventLoop_->registerTimer(std::move(cb), false, 1000000), 0); } } // namespace common } // namespace heron
[ "vikasr@twitter.com" ]
vikasr@twitter.com
dd2088b01799060bb648bddc1658754beb09acab
5f42f6c2042c9ac2af364c47b341fee0e06faac5
/cProgramBok/3_8.cpp
128ebf11c9013cdc13e466e2cf0016c08df89915
[]
no_license
JerryNYang/cfx
ef1946f42133d1c6bcb0cea51952c3012a1fba46
41243548a8f670d870734eab6f88fd4a6ce47640
refs/heads/master
2023-08-16T11:54:11.235413
2023-08-07T22:22:25
2023-08-07T22:22:25
334,737,828
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
// 3_8 // Uses constexpr #include <iostream> using namespace std; constexpr double GetPi() { return 22.0 /7; } constexpr double TwicePi() { return 2 * GetPi(); } int main() { const double pi = 22.0 / 7; cout << "constant pi contains value " << pi << endl; cout << "constexpr GetPi() returns value " << GetPi() << endl; cout << "constexpr TwicePi() returns value " << TwicePi() << endl; return 0; }
[ "46272314+JerryNYang@users.noreply.github.com" ]
46272314+JerryNYang@users.noreply.github.com
b0b1d120cfaf25a4e93cf37b45e1c50bb6b12230
955a892397d88903e6cea71a46816ab91b625243
/include/lirch/plugins/messages/logger_messages.h
50f4a513e74611844917d33a42ba432c26cf5531
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "BSD-3-Clause" ]
permissive
hagemt/Lirch
ed6faecbe6411b42bf8c287a3816f63891dbe4f8
04f6a25c78374c5e0a466bebbee84bcf3cf44310
refs/heads/master
2020-12-24T14:10:33.547647
2014-02-17T06:37:32
2014-02-17T06:37:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,749
h
#ifndef LOGGER_MESSAGES_H #define LOGGER_MESSAGES_H #include <map> #include <QFlags> #include <QString> #include "lirch_constants.h" #include "lirch/core/message.h" // A logging message configures logging of messages class logging_message : public message_data { public: // These are expandable for future use enum class logging_mode { ON, DEFAULT, OFF }; enum class logging_format { TXT }; // These allow fields to be optionally set // SET_NONE specifies no changes to the log options // SET_LDIR specifies changes to the log directory // SET_CHAN specifies changes to the channels enabled/disabled // SET_MODE specifies enabling/disabling logging globally // SET_FORM specifies changing the log format enum logging_option { SET_NONE = 0x1, SET_DIRECTORY = 0x2, SET_CHANNELS = 0x4, SET_FORMAT = 0x8, SET_MODE = 0x10, }; // Generate flags to wrap the enum above Q_DECLARE_FLAGS(logging_options, logging_option) // Obligatory message copypasta virtual std::unique_ptr<message_data> copy() const { return std::unique_ptr<message_data>(new logging_message(*this)); } static message create(const logging_message &msg) { return message_create(LIRCH_MSG_TYPE_LOGGING, new logging_message(msg)); } // Logging messages should have options specified logging_message(logging_options options = logging_options(logging_option::SET_NONE)) : log_options(options), log_mode(logging_mode::DEFAULT), log_format(logging_format::TXT) { } // Modifiers void set_flags(logging_options options) { log_options = options; } void set_mode(logging_mode mode) { log_mode = mode; } void set_format(logging_format format) { log_format = format; } void set_directory(const QString &path) { log_directory = path; } void enable_channel(const QString &channel_name) { channels[channel_name] = true; } void disable_channel(const QString &channel_name) { channels[channel_name] = false; } void reset_channel(const QString &channel_name) { channels.erase(channel_name); } // Accessors bool has_option(logging_option option) const { return log_options.testFlag(option); } QString get_directory() const { return log_directory; } std::map<QString, bool>::const_iterator begin() const { return channels.begin(); } std::map<QString, bool>::const_iterator end() const { return channels.end(); } logging_mode get_mode() const { return log_mode; } logging_format get_format() const { return log_format; } private: logging_options log_options; QString log_directory; logging_mode log_mode; logging_format log_format; std::map<QString, bool> channels; }; // Generate operators Q_DECLARE_OPERATORS_FOR_FLAGS(logging_message::logging_options) #endif // LOGGER_MESSAGES_H
[ "hagemt@rpi.edu" ]
hagemt@rpi.edu
c7f524491052dc25a58acb86f5ff4b76ed6ff1ab
9eef76215773bd42cd8b232297d7b00a5440372e
/HW3/ValidBrackets-Q4/src/main/main.cc
e3e80be88801ca67fd950ced5a2abe45ea1e99db
[]
no_license
linchen1010/EE599
a1cea280dbf0e4a1e790fcb0f33a3557a92656f2
ce56a4835ae8f7a6420ef0933ebfde03a64257ec
refs/heads/master
2020-12-14T05:49:13.710923
2020-06-24T01:17:04
2020-06-24T01:17:04
234,662,387
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
cc
#include "src/lib/solution.h" #include <iostream> int main() { Solution solution; std::string input1 = "])"; std::string input2 = "(a+b)[c*d]{5g+h}"; std::string input3 = "(a+b]"; std::string input4 = "(7h+[5c)+7]"; std::string input5 = "{2k+[5j]}"; std::string input6 = "{2k++[5--*j]}"; std::string input7 = "(a,,b]"; if(solution.ValidBrackets(input1)) std::cout << "true" << std::endl; else { std::cout << "false" << std::endl; } if(solution.ValidBrackets(input2)) std::cout << "true" << std::endl; else { std::cout << "false" << std::endl; } if(solution.ValidBrackets(input3)) std::cout << "true" << std::endl; else { std::cout << "false" << std::endl; } if(solution.ValidBrackets(input4)) std::cout << "true" << std::endl; else { std::cout << "false" << std::endl; } if(solution.ValidBrackets(input5)) std::cout << "true" << std::endl; else { std::cout << "false" << std::endl; } if(solution.ValidBrackets(input6)) std::cout << "true" << std::endl; else { std::cout << "false" << std::endl; } if(solution.ValidBrackets(input7)) std::cout << "true" << std::endl; else { std::cout << "false" << std::endl; } return 0; }
[ "shilinchen1010@gmail.com" ]
shilinchen1010@gmail.com
289ecb7aa7fdd516513fd2132c6f28e4ac5eec94
89282ff1008784466d52aa0eab298477abfae323
/srcs/graphics/ModelBone.hpp
fced62407d77d7a456ff8a94bb4800c59dc96cf1
[]
no_license
mploux/assimp_test
bf3862aedcb090773fa3bcebf25e70d147e6aba1
0f515e54de04dadba908d740b61135fbbf1c9b83
refs/heads/master
2020-03-15T12:51:51.087881
2018-05-07T02:03:43
2018-05-07T02:03:43
132,153,234
0
0
null
null
null
null
UTF-8
C++
false
false
77
hpp
// // Created by mploux on 04/05/18. // #pragma once class ModelBone { };
[ "mploux@student.42.fr" ]
mploux@student.42.fr
5c9a361bd5fa3f701cbbb4d3f6f1fc0b7fe251f4
fd78ccb7b2e41ae10685daf679f344d20e54ed6e
/Hyperstreamline/include/PolygonToPolygon.h
8cff6c70e27e29d468b472c988d958c2a25d7abb
[]
no_license
koron21/kvs
59ce3b764ff09f27a1781031264e4e9daa7d1aee
8889471099cbfe025c6cac35ba5a3385cd7516c2
refs/heads/master
2021-01-22T12:02:34.312136
2012-03-17T09:21:08
2012-03-17T09:21:08
3,012,715
0
0
null
null
null
null
UTF-8
C++
false
false
1,624
h
/****************************************************************************/ /** * @file PolygonToPolygon.h */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id$ */ /****************************************************************************/ #ifndef KVS__POLYGON_TO_POLYGON_H_INCLUDE #define KVS__POLYGON_TO_POLYGON_H_INCLUDE #include <kvs/PolygonObject> #include <kvs/ClassName> #include <kvs/Module> #include <kvs/FilterBase> namespace kvs { /*==========================================================================*/ /** * Polygon to polygon class. */ /*==========================================================================*/ class PolygonToPolygon : public kvs::FilterBase, public kvs::PolygonObject { // Class name. kvsClassName( kvs::PolygonToPolygon ); // Module information. kvsModuleCategory( Filter ); kvsModuleBaseClass( kvs::FilterBase ); kvsModuleSuperClass( kvs::PolygonObject ); public: PolygonToPolygon( void ); PolygonToPolygon( const kvs::PolygonObject* object ); virtual ~PolygonToPolygon( void ); public: SuperClass* exec( const kvs::ObjectBase* object ); private: void calculate_triangle_connections( const kvs::PolygonObject* object ); void calculate_triangle_normals( void ); }; } // end of namespace kvs #endif // KVS__POLYGON_TO_POLYGON_H_INCLUDE
[ "guojiazhen1987@gmail.com" ]
guojiazhen1987@gmail.com
2811782e28feab43c8ec59cb580eb8906ca6ea39
6680f8d317de48876d4176d443bfd580ec7a5aef
/Header/IVirtualTipSynchronizer.h
98f9a32039dbf3d87f72f35b944835b275100b46
[]
no_license
AlirezaMojtabavi/misInteractiveSegmentation
1b51b0babb0c6f9601330fafc5c15ca560d6af31
4630a8c614f6421042636a2adc47ed6b5d960a2b
refs/heads/master
2020-12-10T11:09:19.345393
2020-03-04T11:34:26
2020-03-04T11:34:26
233,574,482
3
0
null
null
null
null
UTF-8
C++
false
false
161
h
#pragma once class IVirtualTipSynchronizer { public: virtual ~IVirtualTipSynchronizer() = default; virtual void UpdateVirtualTipLength(double lenght) = 0; };
[ "alireza_mojtabavi@yahoo.com" ]
alireza_mojtabavi@yahoo.com
dfc49998d38bfb3bda1580303e31a178608d8543
dd2ac351feed04b79293c5515b2ce3600931ee1d
/src/fec.h
0017fcaf0647b014341b1cce518fa83d7d042981
[]
no_license
zengyijing/wspace_ap_scout
99579ee9da41a97bd3b013a430010685b5f1ba8a
0e9260fca09eff16af27a2dbcb84d586419bf3c3
refs/heads/master
2016-08-08T18:32:41.468457
2016-03-02T07:47:56
2016-03-02T07:47:56
48,698,241
0
0
null
2016-02-27T01:42:13
2015-12-28T15:15:12
C++
UTF-8
C++
false
false
4,991
h
/* * fec.c -- forward error correction based on Vandermonde matrices * 980614 * (C) 1997-98 Luigi Rizzo (luigi@iet.unipi.it) * * Portions derived from code by Phil Karn (karn@ka9q.ampr.org), * Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari * Thirumoorthy (harit@spectra.eng.hawaii.edu), Aug 1995 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS * 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 FEC_H_ #define FEC_H_ #include <stdint.h> #include <vector> /* * The following parameter defines how many bits are used for * field elements. The code supports any value from 2 to 16 * but fastest operation is achieved with 8 bit elements * This is the only parameter you may want to change. */ #define GF_BITS 8 /* code over GF(2**GF_BITS) - change to suit */ #if (GF_BITS < 2 && GF_BITS >16) #error "GF_BITS must be 2 .. 16" #endif #if (GF_BITS <= 8) typedef unsigned char gf; #else typedef unsigned short gf; #endif #define GF_SIZE ((1 << GF_BITS) - 1) /* powers of \alpha */ #define SWAP(a,b,t) {t tmp; tmp=a; a=b; b=tmp;} #define TICK(t) \ {struct timeval x ; \ gettimeofday(&x, NULL) ; \ t = x.tv_usec + 1000000* x.tv_sec; \ } #define TOCK(t) \ { u_long t1 ; TICK(t1) ; \ if (t1 < t) assert(0); \ else t = t1 - t ; \ if (t == 0) t = 1 ;} void fec_free(struct fec_parms *p); struct fec_parms* fec_new(int k, int n) ; void fec_encode(struct fec_parms *code, gf *src[], gf *fec, int index, int sz); int fec_decode(struct fec_parms *code, gf *pkt[], int index[], int sz); /** Tan's extra functions. */ /** Coding info for vdm. */ class CodeInfo { public: enum Codec { kEncoder = 1, kDecoder = 2, }; CodeInfo() {} CodeInfo(Codec type, int max_batch_size, int pkt_size); ~CodeInfo(); void ClearInfo(); void SetCodeInfo(int k, int n, uint32_t start_seq=0); /** * Push each native packet into the original batch. * Update the length to the maximum length. */ bool PushPkt(uint16_t len, const gf *src, int ind=0); /** Just return the packet address. No copying happen here.*/ bool PopPkt(gf **dst, uint16_t *len=NULL); void EncodeBatch(); void DecodeBatch(); void PrintBatch(Codec type=kEncoder) const; void ResetCurInd() { cur_ind_ = 0; } int cur_ind() const { return cur_ind_; } int k() const { return k_; } int n() const { return n_; } int sz() const { return sz_; } uint32_t start_seq() const { return start_seq_; } const int* inds() const { return inds_; } void CopyLens(const uint16_t *lens) { assert(k_ > 0); memcpy(lens_, lens, k_ * sizeof(uint16_t)); } uint16_t GetLen(int i) const { return lens_[i]; } uint16_t* lens() { return lens_; } int GetEncodePktLen() const { return sz_; } void GetSeqArr(std::vector<uint32_t> &seq_arr); gf** original_batch() const { return original_batch_; } gf** coded_batch() const { return coded_batch_; } private: gf** alloc_batch(int k, int sz); void zero_batch(gf **batch, int k, int sz); void free_batch(gf **batch, int k); void print_pkt(int sz, const gf *pkt) const; int max_batch_size_; int pkt_size_; Codec codec_type_; /** Server or client. */ int k_; /** Number of data packets. */ int n_; /** Number of encoded packets. */ int sz_; /** Size of packet. */ uint32_t start_seq_; /** Sequence number of the first packet. */ int *inds_; /** Indices of coding packets. */ uint16_t *lens_; /** Length of original packets. */ int cur_ind_; /** Current index of the batch. */ struct fec_parms *code_; /** Coding struct for fec lib. */ gf **original_batch_; /** Orignal batch of packets. */ gf **coded_batch_; /** Coded batch. */ }; inline void CodeInfo::zero_batch(gf** batch, int k, int sz) { for (int i = 0; i < k; i++) bzero(batch[i], sz * sizeof(gf)); } /* end of file */ #endif
[ "zengyijing19900106@gmail.com" ]
zengyijing19900106@gmail.com
ba57e3318cf82d4b1244b32fb4a2c106dfe45752
698839f34380be28746c27fb9a9609da2501b3b1
/PolarisV2/creative_category.h
ba2e024aac0d657426c3c8580e5e07c820e72afc
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
kateisprettydamngreat/Polaris
007eb7f8cfbd342e8f0df061c0796e791f3dba72
fd14ecb2820b569d7dbb5923d1837893d4390d0a
refs/heads/main
2023-06-04T08:04:13.049626
2021-06-22T20:06:21
2021-06-22T20:06:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
h
/* * Copyright (c) 2021, Polaris All rights reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CREATIVE_CATEGORY_H #define CREATIVE_CATEGORY_H #include "category.h" #include "creative_menu.h" #include "creative_plate.h" namespace polaris::ui::window::windows::mainwindow::category::categories { class CreativeCategory : public Category { public: CreativeMenu* m_pCreativeMenu; CreativeCategory(tables::plates::CreativePlate* creativePlate); void DrawButtons() override; }; } #endif // !CREATIVE_CATEGORY_H
[ "85968366+PolarisV2@users.noreply.github.com" ]
85968366+PolarisV2@users.noreply.github.com
42e5740855527c207cd5b52a87b6723051e10a1b
3f94fde265e466368ca72a9b26c7a404cf2fba8f
/Engine/src/serializable.h
3d805ea3d2f218902267bf25fe1164ec4711894d
[]
no_license
HanfeiChen/ray-tracer
f0c3937525a81205281ce19b90fe4d250003dd94
83657818d45cb4f495c2068dc9595960bc0bf1f0
refs/heads/master
2022-11-10T06:38:25.432149
2020-06-26T21:22:27
2020-06-26T21:22:27
275,250,143
0
0
null
null
null
null
UTF-8
C++
false
false
462
h
#ifndef SERIALIZABLE_H #define SERIALIZABLE_H #include <vectors.h> #include <string> #include <assert.h> #include <signals/Signal.h> #include <enum.h> #include <map> #include <memory> #include <yaml-cpp/yaml.h> #include <QDebug> class Serializable { public: virtual ~Serializable() {} virtual void SaveToYAML(YAML::Emitter& out) const = 0; virtual void LoadFromYAML(const YAML::Node& node) = 0; }; #endif // SERIALIZABLE_H
[ "paquinn@cs.washington.edu" ]
paquinn@cs.washington.edu
993deb4f7414b57bfde5e511e82d25781ba51b80
f179f5b3b14c5847590eae83da552bf0d4c6e51a
/ParticleEngine/FlexibleVertexClass.h
471c6d7b7cfa033f64399950c886697409669869
[ "MIT" ]
permissive
RodrigoHolztrattner/Particles
c9968d7b69905fca2b40e5e58c4179bfc9bc7288
936ff2479a4083f2178d68882de876c9bd767b52
refs/heads/master
2021-09-23T00:30:38.819553
2018-09-19T05:56:23
2018-09-19T05:56:23
105,457,117
0
0
null
null
null
null
UTF-8
C++
false
false
2,134
h
//////////////////////////////////////////////////////////////////////////////// // Filename: FlexibleVertexClass.h //////////////////////////////////////////////////////////////////////////////// #ifndef _FlexibleVertexClass_H_ #define _FlexibleVertexClass_H_ ///////////// // LINKING // ///////////// ////////////// // INCLUDES // ////////////// #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <mmsystem.h> #include <d3d10.h> #include <d3dx10.h> #include "GroupClass.h" ///////////// // DEFINES // ///////////// //////////////////////////////////////////////////////////////////////////////// // Class name: FlexibleVertexClass //////////////////////////////////////////////////////////////////////////////// class FlexibleVertexClass { private: public: FlexibleVertexClass(unsigned int size); FlexibleVertexClass(); FlexibleVertexClass(const FlexibleVertexClass&); ~FlexibleVertexClass(); // Add bool Add(unsigned char* vertexFrom, unsigned int* indexFrom, unsigned int quantity = 1); // Set the unit size void SetUnitSize(unsigned int size); // Set the vertex type void SetVertexType(unsigned int type); // Return the vertex type unsigned int GetVertexType(); // Create buffers (and delete the data array if we want) bool CreateBuffers(ID3D10Device* device, bool deleteData = true); // Set the buffers into the pipeline bool SetBuffers(ID3D10Device* device); // Operator [] unsigned char* operator [] (unsigned int index); // The shutdown function void Shutdown(); private: // The base data unsigned int m_UnitSize; unsigned int m_VertexType; bool m_DataDeleted; bool m_BuffersCreated; unsigned int m_VertexSize; unsigned int m_IndexSize; // The data group<unsigned char> m_Vertexes; group<unsigned int> m_Indexes; // The buffers ID3D10Buffer* m_VertexBuffer; ID3D10Buffer* m_IndexBuffer; public: // Return the buffers ID3D10Buffer* GetVertexBuffer(){return m_VertexBuffer;} ID3D10Buffer* GetIndexBuffer(){return m_IndexBuffer;} // Return the sizes unsigned int GetVertexSize(){return m_VertexSize;} unsigned int GetIndexSize(){return m_IndexSize;} }; #endif
[ "rodrigoholztrattner@gmail.com" ]
rodrigoholztrattner@gmail.com
d8a924ca400648ad8de54117cda1a991a197682e
1902d86783a977ce8f38f9edbc7a473aa2134249
/A1_COMMON/A1_COMMON/money.h
a414d296f93c168d16bd5b23b8759b3b5451b6f7
[]
no_license
Geralastel/A1_COMMON
e77e74d0422aca5527fcb1eb5c6afc39bb08bdcc
b12888148c726f34dcf365100bacd588069eaf34
refs/heads/master
2021-01-10T17:31:35.202508
2016-02-27T00:11:59
2016-02-27T00:11:59
52,547,587
0
1
null
null
null
null
UTF-8
C++
false
false
133
h
#pragma once class Money { public: int get_elektro(); Money(int k); Money(); private: int elektro; };
[ "gian.m.colucci@gmail.com" ]
gian.m.colucci@gmail.com
0c69cc72fe1399cdd2125779c1bc896b76754b57
f95e3f3d58b7ca2acb678a6ed08c01008bd6d5fe
/tests/func/test_str_capacity.cc
237e9c8b75409f220d6a53dae45e5dfde83dc5a0
[ "MIT" ]
permissive
xmonader/ctl
7aa3c7bf29beb2bb0bc5e4d75a4251c1502e74f8
3923e6776a231e5d58cf91225ca8a1d61879401b
refs/heads/master
2023-08-15T02:35:56.462941
2021-10-13T08:50:00
2021-10-13T08:51:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,371
cc
/* Test the special MUST_ALIGN_16(T) logic */ #include "../test.h" #include <ctl/string.h> #include <string.h> #include <string> #define ASSERT_EQUAL_SIZE(c, s) (assert(s.size() == c.size)) #if defined(DEBUG) #define ASSERT_EQUAL_CAP(c, s) \ if (s.capacity() != c.capacity) \ { \ printf("capacity %zu vs %zu FAIL\n", c.capacity, s.capacity()); \ fail++; \ } // capacity is implemention-defined and we tested against gcc libstdc++ v3 (7.5 // - 10), llvm libc++ v1 ver 18. MSVC ? // gcc libstdc++ had the latest change with __cplusplus >= 201103L // libc++ had the latest change in __grow_by in PR17148, 2013 #elif (defined _GLIBCXX_RELEASE && __cplusplus >= 201103L) // Fails with libc++ 11, 14, 17, 18 #define ASSERT_EQUAL_CAP(c, s) (assert(s.capacity() == c.capacity)) #else #define ASSERT_EQUAL_CAP(c, s) \ if (s.capacity() != c.capacity) \ { \ printf("capacity %zu vs %zu FAIL\n", c.capacity, s.capacity()); \ fail++; \ } #endif int main(void) { INIT_SRAND; size_t fail = 0; #if defined __GNUC__ && defined _GLIBCXX_RELEASE fprintf(stderr, "_GLIBCXX_RELEASE %d\n", (int)_GLIBCXX_RELEASE); #elif defined __GNUC__ && defined _GLIBCXX_PACKAGE__GLIBCXX_VERSION fprintf(stderr, "_GLIBCXX_VERSION %s %d\n", _GLIBCXX_PACKAGE__GLIBCXX_VERSION, (int)__cplusplus); #elif defined _LIBCPP_STD_VER fprintf(stderr, "_LIBCPP_STD_VER %d\n", (int)_LIBCPP_STD_VER); #else fprintf(stderr, "unknown libc++: __cplusplus %d\n", (int)__cplusplus); #endif const unsigned loops = TEST_RAND(TEST_MAX_LOOPS); for (unsigned loop = 0; loop < loops; loop++) { char value = TEST_RAND(256); // guarantee short string coverage size_t size = loop ? TEST_RAND(TEST_MAX_SIZE) : TEST_RAND(30); enum { MODE_DIRECT, MODE_GROWTH, MODE_TOTAL }; for (size_t mode = MODE_DIRECT; mode < MODE_TOTAL; mode++) { str a = str_init(""); std::string b; if (mode == MODE_DIRECT) { LOG("mode DIRECT\n"); b.resize(size); str_resize(&a, size, '\0'); LOG("ctl resize 0 -> %zu vs %zu\n", a.size, b.size()); } else if (mode == MODE_GROWTH) { LOG("mode GROWTH\n"); for (size_t pushes = 0; pushes < size; pushes++) { b.push_back(value); // double cap str_push_back(&a, value); LOG("cap %zu (0x%lx) vs %zu (0x%lx) size:%zu %s\n", a.capacity, a.capacity, b.capacity(), b.capacity(), a.size, a.capacity != b.capacity() ? "FAIL" : ""); } LOG("ctl growth %zu vs %zu\n", a.size, b.size()); if (TEST_RAND(10) < 3) { #if __cplusplus >= 201103L b.shrink_to_fit(); str_shrink_to_fit(&a); LOG("ctl shrink_to_fit cap %zu vs %zu\n", a.capacity, b.capacity()); #endif } } ASSERT_EQUAL_SIZE(a, b); LOG("ctl capacity %zu (0x%lx) vs %zu (0x%lx) %s\n", a.capacity, a.capacity, b.capacity(), b.capacity(), a.capacity != b.capacity() ? "FAIL" : ""); ASSERT_EQUAL_CAP(a, b); str_free(&a); } } if (fail) TEST_FAIL(__FILE__); else TEST_PASS(__FILE__); }
[ "rurban@cpan.org" ]
rurban@cpan.org
6bbbee3fb002616851a869cad837157af848056d
9472670a8487ef8bd70b327829df0c73ded6df20
/PROGRAMACION Y ESTRUCTURA DE DATOS/tads/avl_/tad06.cpp
b54bc74cef74150ce899a1f671b0ade83ae4d003
[]
no_license
josemygel/Temario-Ingenieria-Software-UA
246b4f7044ae5f5f8fcb171ad6b01040d19396fa
32cc45fcaee9d3d7282796f083691ec9d4551848
refs/heads/master
2023-05-10T23:38:04.608129
2020-08-02T08:08:04
2020-08-02T08:08:04
216,786,952
17
12
null
2023-05-07T02:16:11
2019-10-22T10:31:00
HTML
UTF-8
C++
false
false
910
cpp
/************************************************************ ** ALTURA, NODOS, NODOSHOJA, =, != *************************************************************/ #include <iostream> #include "tavlcalendario.h" using namespace std; int main() { TAVLCalendario arb1, arb2; TCalendario bd(1,1,2011,(char *)"uno"); TCalendario bc(2,2,2011,(char *)"dos"); TCalendario be(3,3,2011,(char *)"tres"); TCalendario bn(4,4,2011,(char *)"cuatro"); TCalendario ba(5,5,2011,(char *)"cinco"); TCalendario bm(6,6,2011,(char *)"seis"); arb1.Insertar(ba); arb1.Insertar(bc); arb1.Insertar(bd); arb1.Insertar(be); arb1.Insertar(bm); arb2 = arb1; if(arb2 != arb1) cout << "No iguales" <<endl; else cout << "Iguales" << endl; cout << "Altura: " << arb2.Altura() << endl; cout << "Nodos: " << arb2.Nodos() << endl; cout << "NodosHoja: " << arb2.NodosHoja() << endl; return 0; }
[ "josemygel@gmail.com" ]
josemygel@gmail.com
2417621040f361bf8544ad53dd68eda90e52017c
ad820303d998edfbce1ec1a40abdd2101d5857e8
/include/main.h
82c7a6082a3ad55554f3914b2b15042af793db3c
[]
no_license
GLMONTER/67101vcu
9cba93aa970047c4d6ec13418346dd312cd83816
bbbe15b0e346e76aefae0f124cd605c1b6f7d70a
refs/heads/master
2023-01-06T22:27:49.888825
2020-09-14T23:54:50
2020-09-14T23:54:50
308,992,788
0
0
null
null
null
null
UTF-8
C++
false
false
1,398
h
#ifndef _PROS_MAIN_H_ #define _PROS_MAIN_H_ /** * If defined, some commonly used enums will have preprocessor macros which give * a shorter, more convenient naming pattern. If this isn't desired, simply * comment the following line out. * * For instance, E_CONTROLLER_MASTER has a shorter name: CONTROLLER_MASTER. * E_CONTROLLER_MASTER is pedantically correct within the PROS styleguide, but * not convienent for most student programmers. */ //#define PROS_USE_SIMPLE_NAMES /** * If defined, C++ literals will be available for use. All literals are in the * pros::literals namespace. * * For instance, you can do `4_mtr = 50` to set motor 4's target velocity to 50 */ #define PROS_USE_LITERALS #include "api.h" /** * You should add more #includes here */ #include"pros/apix.h" #include "okapi/api.hpp" #include"sensors.hpp" #include"control_sys.hpp" using namespace okapi; /** * Prototypes for the competition control tasks are redefined here to ensure * that they can be called from user code (i.e. calling autonomous from a * button press in opcontrol() for testing purposes). */ #ifdef __cplusplus extern "C" { #endif void autonomous(void); void initialize(void); void disabled(void); void competition_initialize(void); void opcontrol(void); #ifdef __cplusplus } #endif #ifdef __cplusplus /** * You can add C++-only headers here */ #endif #endif // _PROS_MAIN_H_
[ "logisch@protonmail.com" ]
logisch@protonmail.com
3e39fa80d12b94fc2c755db8ca38a319082b01ac
40e08a8e7005819701b6c3a2015803ed2e8a91ae
/Week4TestClass2/Week4TestClass2/Week4TestClass2Doc.cpp
8eb6051bf542990cc6caec1adfc4ecd3a542a52c
[]
no_license
Zackyyyyy/TESTING-WORK
00a396231ea64e7b63ac36af02ec25445291b4d6
54d5ba7f2458b59be33deecf3053a05703c15efc
refs/heads/master
2021-04-17T03:35:54.189307
2020-04-27T15:45:46
2020-04-27T15:45:46
249,408,592
0
0
null
null
null
null
GB18030
C++
false
false
2,816
cpp
// Week4TestClass2Doc.cpp : CWeek4TestClass2Doc 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "Week4TestClass2.h" #endif #include "Week4TestClass2Doc.h" #include <propkey.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // CWeek4TestClass2Doc IMPLEMENT_DYNCREATE(CWeek4TestClass2Doc, CDocument) BEGIN_MESSAGE_MAP(CWeek4TestClass2Doc, CDocument) END_MESSAGE_MAP() // CWeek4TestClass2Doc 构造/析构 CWeek4TestClass2Doc::CWeek4TestClass2Doc() { // TODO: 在此添加一次性构造代码 m_crlRect.left = 30; m_crlRect.right = 80; m_crlRect.top = 30; m_crlRect.bottom = 80; } CWeek4TestClass2Doc::~CWeek4TestClass2Doc() { } BOOL CWeek4TestClass2Doc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: 在此添加重新初始化代码 // (SDI 文档将重用该文档) return TRUE; } // CWeek4TestClass2Doc 序列化 void CWeek4TestClass2Doc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: 在此添加存储代码 } else { // TODO: 在此添加加载代码 } } #ifdef SHARED_HANDLERS // 缩略图的支持 void CWeek4TestClass2Doc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // 修改此代码以绘制文档数据 dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // 搜索处理程序的支持 void CWeek4TestClass2Doc::InitializeSearchContent() { CString strSearchContent; // 从文档数据设置搜索内容。 // 内容部分应由“;”分隔 // 例如: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void CWeek4TestClass2Doc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // CWeek4TestClass2Doc 诊断 #ifdef _DEBUG void CWeek4TestClass2Doc::AssertValid() const { CDocument::AssertValid(); } void CWeek4TestClass2Doc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CWeek4TestClass2Doc 命令
[ "397998391@qq.com" ]
397998391@qq.com
21a163926cc88c5ab131f50a2df02c52dd2aae6b
f3847f58845502416522b25f4c46bf7aff0877bd
/C++/E448FindAllNumbersDisappearedInAnArray/E448FindAllNumbersDisappearedInAnArray5.cpp
4160911321dcc8377626b11cf8da3b5e36a0ab94
[]
no_license
amymayadi/LeetCode
e24c03550f41c3a49c6508128efcda690eea6979
377eb90cb0a7c570359f7665392d570a9ff0b909
refs/heads/master
2018-07-28T21:40:09.007519
2018-06-09T03:43:03
2018-06-09T03:43:03
112,581,371
0
0
null
null
null
null
UTF-8
C++
false
false
2,332
cpp
/** * Runtime:169ms -- SLOW * time:O(n) * space:O(1) */ #include <iostream> #include <vector> #include <sstream> #include <include/c++/algorithm> using namespace std; // 默认参数声明,应该在调用函数之前。 string integerVectorToString(vector<int> list, int length); class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> res; int n = nums.size(); if (n==0 || n==1) { return res; } for (int i = 0; i <= n; ++i) { res.push_back(0); } for (int l = 0; l < n; ++l) { res[nums[l]] = -1; } int j = 0; for (int k = 1; k <= n; ++k) { if(res[k] == 0) res[j++] = k; } auto it = res.begin()+j; res.erase(it, res.end()); return res; } }; void trimLeftTrailingSpaces(string &input) { input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) { return !isspace(ch); })); } void trimRightTrailingSpaces(string &input) { input.erase(find_if(input.rbegin(), input.rend(), [](int ch) { return !isspace(ch); }).base(), input.end()); } vector<int> stringToIntegerVector(string input) { vector<int> output; trimLeftTrailingSpaces(input); trimRightTrailingSpaces(input); input = input.substr(1, input.length() - 2); stringstream ss; ss.str(input); string item; char delim = ','; while (getline(ss, item, delim)) { output.push_back(stoi(item)); } return output; } // 不允许多处声明默认参数,只允许声明一次 string integerVectorToString(vector<int> list, int length = -1) { if (length == -1) { length = list.size(); } if (length == 0) { return "[]"; } string result; for(int index = 0; index < length; index++) { int number = list[index]; result += to_string(number) + ", "; } return "[" + result.substr(0, result.length() - 2) + "]"; } int main() { string line; while (getline(cin, line)) { vector<int> nums = stringToIntegerVector(line); vector<int> ret = Solution().findDisappearedNumbers(nums); string out = integerVectorToString(ret); cout << out << endl; } return 0; }
[ "mayadi@travelsky.com" ]
mayadi@travelsky.com
e5fdcf9b47f2f192498c5645323c01c53629ad2b
859006ded9e1b0cffc7fa410498e3b8b94c9ad78
/Shared/HAL/include/HAL/HAL.h
4987fd1fc8bfb1a2906ece2cba4bcc10f2f05526
[]
no_license
viron11111/sub-2012
608795566c5ee621e0c27ff53399dfb58b26ecf5
761972b1fdb577c59c693a670605b8aaabe90a4d
refs/heads/master
2021-01-01T04:48:48.762686
2012-10-02T23:47:57
2012-10-02T23:47:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
999
h
#ifndef HAL_HAL_H #define HAL_HAL_H #include "HAL/transport/Transport.h" #include "HAL/transport/Endpoint.h" #include "HAL/format/DataObjectEndpoint.h" #include <boost/ptr_container/ptr_vector.hpp> #include <boost/asio.hpp> namespace subjugator { class BaseHAL { public: struct EndpointConfiguration { std::string protocol; std::string protoaddress; std::map<std::string, std::string> params; EndpointConfiguration() { } EndpointConfiguration(const std::string &confstr); }; BaseHAL(); void addTransport(Transport *transport); void clearTransports(); Endpoint *makeEndpoint(const EndpointConfiguration &conf); DataObjectEndpoint *makeDataObjectEndpoint(const EndpointConfiguration &conf, DataObjectFormatter *dobjformat, PacketFormatter *packetformat); private: typedef boost::ptr_vector<Transport> TransportVec; TransportVec transports; }; class HAL : public BaseHAL { public: HAL(boost::asio::io_service &io); }; } #endif
[ "matthewbot@gmail.com" ]
matthewbot@gmail.com
8cd1e10ed5958ca8356b180501b9dec1478bb958
43220f87a527e4b143e5969346c987a97e1e25bb
/semestr2/4_1/mainwindow.cpp
32bbd23c786bc52dff2f2b73cbaa738f58b1d2a2
[]
no_license
TatianaZ/homework
9c5b532e523a4a39ba1daee8c21e679a2c81ba41
6050110edca0af5a7afa2a48e2926a9f59efd73c
refs/heads/master
2020-05-17T23:29:26.017717
2013-12-22T18:58:11
2013-12-22T18:58:11
3,537,314
2
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->ScrollBar->setValue(0); ui->progressBar->setValue(0); connect(ui->ScrollBar, SIGNAL(valueChanged(int)), ui->progressBar, SLOT(setValue(int))); } MainWindow::~MainWindow() { delete ui; }
[ "paladin.of.tur@gmail.com" ]
paladin.of.tur@gmail.com
74d9ee32e333e6545535c78e6d7673848287782c
bc01d89e3b77b9b60afd6f5f8fcad5675b813f8e
/natfw/natfwclient/inc/natfwsession.h
2a438a8e0ff8945cd1aceef3d433aed8a5317c29
[]
no_license
SymbianSource/oss.FCL.sf.mw.ipappsrv
fce862742655303fcfa05b9e77788734aa66724e
65c20a5a6e85f048aa40eb91066941f2f508a4d2
refs/heads/master
2021-01-12T15:40:59.380107
2010-09-17T05:32:38
2010-09-17T05:32:38
71,849,396
1
0
null
null
null
null
UTF-8
C++
false
false
12,637
h
/* * Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: NAT FW session abstraction * */ #ifndef C_CNATFWSESSION_H #define C_CNATFWSESSION_H #include <e32base.h> #include "natfwconnectivityapidefs.h" #include "mnatfwpluginobserver.h" class CNATFWCandidate; class CNATFWCandidatePair; class CNATFWStream; class CNcmConnectionMultiplexer; class MNATFWConnectivityObserver; class MNATFWRegistrationController; class CNATFWPluginApi; class CNATFWNatSettingsApi; class CNATFWPluginApi; class CDesC8Array; class CNatFwAsyncCallback; /** * NAT FW session abstraction. * * Provides network connection layer and operation context for * the NAT FW streams. Can be mapped e.g. to the SDP-session. * * @lib natconfw.lib * @since S60 v3.2 */ NONSHARABLE_CLASS( CNATFWSession ) : public CBase, public MNATFWPluginObserver { friend class UT_CNATFWClient; public: static CNATFWSession* NewL( CNcmConnectionMultiplexer& aMultiplexer, MNATFWRegistrationController& aController, CNatFwAsyncCallback& aAsyncCallback, const TDesC8& aDomain, TUint32 aIapId ); static CNATFWSession* NewLC( CNcmConnectionMultiplexer& aMultiplexer, MNATFWRegistrationController& aController, CNatFwAsyncCallback& aAsyncCallback, const TDesC8& aDomain, TUint32 aIapId ); virtual ~CNATFWSession(); /** * Returns the session identifier. * * @since S60 v3.2 * @return The session identifier */ TUint SessionId() const; /** * Loads a NAT protocol plugin to the session. Old plugin is destroyed if * it exists. In this case NAT operations for the session must be started * anew ( FetchCandidate(s) and possible ICE processing ). * * Given NAT protocol plugins are tried to be loaded in order until a * working one is found. * * @since S60 v3.2 * @param aPlugins Array containing identifiers for available * NAT-protocol plugins in preferred order. E.g. * "exampleprovider.stun". * @param aLoadedPluginInd Index to the aPlugins array telling actually * loaded plugin. * @leave KErrNotFound NAT-plugin was not found */ void LoadPluginL( const CDesC8Array& aPlugins, TInt& aLoadedPluginInd ); /** * Resolves public IP address to be used in the communication between * peers. MNATFWConnectivityObserver::NewLocalCandidateFound * is called when a public IP has been resolved. * * @since S60 v3.2 * @param aStreamId The ID identifying stream * @param aAddrFamily KAFUnspec / KAfInet / KAfInet6 */ void FetchCandidateL( TUint aStreamId, TUint aAddrFamily ); /** * ICE spesific function. Fetches IP address candidates for the * communication between peers. Client is responsible for providing a * mapping between components of media stream through the collection ID * parameter. MNATFWConnectivityObserver::NewLocalCandidateFound * is called whenever a new candidate has been found. * * @since S60 v3.2 * @param aStreamId The ID identifying stream * @param aCollectionId The stream collection identifier * @param aComponentId The media component identifier * @param aAddrFamily KAFUnspec / KAfInet / KAfInet6 */ void FetchCandidatesL( TUint aStreamId, TUint aCollectionId, TUint aComponentId, TUint aAddrFamily ); /** * Creates a new stream for the client. On return the client receives a * stream identifier. * * @since S60 v3.2 * @param aProtocol KProtocolInetUdp / KProtocolInetTcp * @param aQoS The desired quality of service. * @return The ID for the created stream */ TUint CreateStreamL( TUint aProtocol, TInt aQoS ); /** * ICE specific function. * Sets the role of local ICE agent. In role-conflict situation given role * will be silently changed. * * @since S60 v3.2 * @param aRole The role */ void SetRoleL( TNATFWIceRole aRole ); /** * ICE specific function. * Performs connectivity checks between the local candidates and the * remote candidates. MNATFWConnectivityObserver::NewCandidatePairFound * is called whenever working connection between local and remote * candidate is found. * * @since S60 v3.2 * @param aRemoteCandidates The remote candidate array */ void PerformConnectivityChecksL( RPointerArray<CNATFWCandidate>& aRemoteCandidates ); /** * ICE specific function. * Updates ICE processing for a session with the candidate pairs selected * by the controlling peer. If ICE processing for a stream is completed, * update for that is silently ignored. * * ICE restart is handled by setting new role and credentials and * re-starting connectivity checks with PerformCandidateChecksL. * * Adding new streams does not differ from initial operation. * Removing of streams is handled with CloseStreamL. * * @since S60 v3.2 * @pre ICE processing is started with PerformConnectivityChecksL * @param aPeerSelectedPairs Peer selected candidate pairs * @leave KErrNotSupported Loaded NAT Protocol plugin does not support * operation. * @post ICE processing is continued with new parameters */ void UpdateIceProcessingL( RPointerArray<CNATFWCandidatePair>& aPeerSelectedPairs ); /** * ICE specific function. * Updates ICE processing for a session with an updated set of remote * candidates. If ICE processing for a stream is completed, update for * that is silently ignored. New remote candidates will be included in * connectivity tests from this point onwards. * * ICE restart is handled by setting new role and credentials and * re-starting connectivity checks with PerformCandidateChecksL. * * Adding new streams does not differ from initial operation. * Removing of streams is handled with CloseStreamL. * * @since S60 v3.2 * @pre ICE processing is started with PerformConnectivityChecksL * @param aRemoteCands All remote candidates known currently * @leave KErrNotSupported Loaded NAT Protocol plugin does not support * operation. * @post ICE processing is continued with new parameters */ void UpdateIceProcessingL( RPointerArray<CNATFWCandidate>& aRemoteCands ); /** * Closes the stream from the session. * * @since S60 v3.2 * @pre Streaming is disabled with SetReceivingStateL/SetSendingStateL * @param aStreamId The ID identifying stream */ void CloseStreamL( TUint aStreamId ); /** * Returns stream by identifier. * * @since S60 v3.2 * @param aStreamId The ID identifying stream * @return Stream or NULL if not found */ CNATFWStream* StreamById( TUint aStreamId ); /** * Returns stream by identifier. Leaves with KErrNotFound if stream * isn't found. * * @since S60 v3.2 * @param aStreamId The ID identifying stream * @return Stream */ CNATFWStream* StreamByIdL( TUint aStreamId ); /** * From MNATFWPluginObserver. * Called when an error within a stream has occured. * * @since S60 v3.2 * @param aPlugin The plugin raising event * @param aStreamId The ID identifying stream * @param aErrorCode Standard system wide error code */ void Error( const CNATFWPluginApi& aPlugin, TUint aStreamId, TInt aErrorCode ); /** * From MNATFWPluginObserver. * Notifies the client of plugin events. * * @since S60 v3.2 * @param aPlugin The plugin raising event * @param aStreamId The ID identifying stream * @param aEvent The event * @param aErrCode Standard system wide error code */ void Notify( const CNATFWPluginApi& aPlugin, TUint aStreamId, TNATFWPluginEvent aEvent, TInt aErrCode ); /** * From MNATFWPluginObserver. * Called when working candidate pair has been found. Ownership of * the candidate pair is trasferred. * * @since S60 v3.2 * @param aPlugin The plugin raising event * @param aCandidatePair The candidate pair which was found */ void NewCandidatePairFound( const CNATFWPluginApi& aPlugin, CNATFWCandidatePair* aCandidatePair ); /** * From MNATFWPluginObserver. * Called when a new local candidate has been found. Ownership of the * candidate is trasferred. * * @since S60 v3.2 * @param aPlugin The plugin raising event * @param aCandidate The local candidate that was found */ void NewLocalCandidateFound( const CNATFWPluginApi& aPlugin, CNATFWCandidate* aCandidate ); private: CNATFWSession( CNcmConnectionMultiplexer& aMultiplexer, MNATFWRegistrationController& aController, CNatFwAsyncCallback& aAsyncCallback, TUint32 aIapId ); void ConstructL( const TDesC8& aDomain ); void HandleQueuedItems(); void DoNotify( TUint aStreamId, MNATFWConnectivityObserver::TNATFWConnectivityEvent aEvent, TInt aErrCode, TAny* aEventData ); private: /** Identifies states for Server connection **/ enum TServerConnectionState { EConnectionUnspecified = 1, EConnectionInProgress = 2, EConnectionConnected = 3, EConnectionFailed = 4 }; class TStatusCounter { public: // Constructors and destructor inline TStatusCounter() : iActivatedCount( 0 ), iStreamId( 0 ), iErrorOccurred( EFalse ) {}; public: // Data TUint iActivatedCount; TUint iStreamId; TBool iErrorOccurred; }; class TFetchingData { public: // Constructors and destructor inline TFetchingData( TUint aStreamId, TUint aCollectionId, TUint aComponentId, TUint aAddrFamily, TBool aICESpecific ) : iStreamId( aStreamId ), iCollectionId( aCollectionId ), iComponentId( aComponentId ), iAddrFamily( aAddrFamily ), iICESpecific( aICESpecific ) {}; public: // Data TUint iStreamId; TUint iCollectionId; TUint iComponentId; TUint iAddrFamily; TBool iICESpecific; }; private: // data /** * Used to keep track ongoing sending status requests on stream basis. * Own. */ RArray<TStatusCounter> iSendingStatusCounts; /** * Used to keep track ongoing receiving status requests on stream basis. * Own. */ RArray<TStatusCounter> iReceivingStatusCounts; /** * Unique session identifier */ TUint iSessionId; /** * Internet access point identifier */ TUint32 iIapId; /** * Domain for settings querying * Own. */ HBufC8* iDomain; /** * NAT FW Registration controller * Not own. */ MNATFWRegistrationController& iController; /** * The multiplexer * Not own. */ CNcmConnectionMultiplexer& iMultiplexer; /** * Async callback handler * Not own. */ CNatFwAsyncCallback& iAsyncCallback; /** * NAT-settings * Own. */ CNATFWNatSettingsApi* iNatSettings; /** * NAT-protocol plugin used in the session * Own. */ CNATFWPluginApi* iPlugin; /** * Streams created into the session * Own. */ RPointerArray<CNATFWStream> iStreams; /** * Server connection process state */ TServerConnectionState iServerConnectionState; /** * FetchCandidate(s) queue * Own. */ RArray<TFetchingData> iFetchCandidateQueue; }; #endif // C_CNATFWSESSION_H
[ "kirill.dremov@nokia.com" ]
kirill.dremov@nokia.com
b3629d2247b1ced1b388b143064adbbfcd3f081c
f041209e795ec1bad5f88c5e5aaca6c94a9a01fc
/exercise_13.19/Employee.h
98c70ede74588cb83ef3ffacb45231c76587649f
[]
no_license
Pt0lemaeus/C-Primer5Edition
8ba6f26684e2ba2c0a774596f4cbc411bf3d8f41
7f21707d343eccc77cdb6be19782ebeba3264f30
refs/heads/master
2021-01-01T05:22:20.033801
2016-04-14T15:00:13
2016-04-14T15:00:13
56,126,013
0
0
null
null
null
null
UTF-8
C++
false
false
366
h
#pragma once #include <string> static int ID = 0; class Employee { public: Employee() :id(++ID),name(std::string()){} Employee(std::string &s):id(++ID),name(s){} Employee(const Employee &emp):id(++ID),name(emp.name){} Employee& operator= (const Employee &emp){ id = ++ID;name = emp.name; return *this} private: int id; std::string name; };
[ "tuxiaomi@gmail.com" ]
tuxiaomi@gmail.com
83090166d81a15bbb139cc5ea2b622066941f217
c6602b310cc7c96d2f9d9071997871acde850af8
/private/mediautils.h
5ea469f6aa39db73747cd71786b5f1df39658c71
[]
no_license
wangscript007/RtmpKit
a30402d885141c0f4b6366679c5c28ecffd47f0e
ed427802cc315af917103e4cb1a16c49b0a178f3
refs/heads/master
2022-01-08T15:58:06.054051
2019-02-09T16:47:10
2019-02-09T16:47:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,635
h
// // mediautils.h // Diego Stamigni // // Created by Diego Stamigni on 05/04/2017. // Copyright © 2017 RtmpKit. All rights reserved. // #pragma once #include "../private/utils.h" #include "../private/videodescriptor.h" #include "../private/audiodescriptor.h" #include <utility> namespace RtmpKit { class MediaUtils { public: MediaUtils() = delete; MediaUtils(const MediaUtils&) = delete; MediaUtils(MediaUtils&&) = delete; MediaUtils& operator=(const MediaUtils&) = delete; MediaUtils& operator=(MediaUtils&&) = delete; /* * Video stuff */ public: /*! * Unpack SPS and PPS from a payload in a range for a specifed timestamp. * @param payload the data to unpack * @param timestamp the timestamp of the payload * @returns VideoDescriptor holding SPS, PPS and other stuff regarding the video format */ static VideoDescriptor unpackVideoData(RtmpKit::v8::const_iterator& begin, RtmpKit::v8::const_iterator& end, RtmpKit::u32& timestamp, bool appendNaluHeader = false); /* * Audio stuff */ public: /*! * Unpack audio format from a payload in a range. * @param payload the data to unpack * @returns VideoDescriptor holding SPS, PPS and other stuff regarding the video format */ static AudioDescriptor unpackAudioData(RtmpKit::v8::const_iterator& begin, RtmpKit::v8::const_iterator& end); /*! * The supported audio saple rates */ static std::vector<int> audioSampleRates(); /*! * Returns the index for a given sample rate */ static int indexForSampleRate(int sampleRate); }; }
[ "diego.stamigni@gmail.com" ]
diego.stamigni@gmail.com
c011db934c99c9d0766b3e9ac25e02f045fc594d
95fd16c183e3dab549853f3c0f2f39a21c5bbb6a
/Paint/Figure2D.h
485e5c2e8684fac7ca223a088319b2d1f8d2e861
[]
no_license
liadhzaoot/Paint
21147a90e2945285304ffd16013f67bff1ae84df
759e278f795acc79f7b88f7c7f4a8ee9711ba3de
refs/heads/master
2023-05-03T08:20:10.236044
2021-05-23T11:03:13
2021-05-23T11:03:13
370,024,803
0
0
null
null
null
null
UTF-8
C++
false
false
1,593
h
#pragma once #include <math.h> #include <iostream> #include "PaintDlg.h" #define _CRT_SECURE_NO_WARNINGS using namespace std; class Figure2D{ friend ostream& operator<<(ostream& out, const Figure2D& other); private: CPoint _startP; CPoint _endP; double _length; double _height; COLORREF _penColor; COLORREF _brushColor; int _penStyle; int _penSize; //char* name = NULL;//=NULL Needed for compiler of the testing engine public: Figure2D(double l, double h, double x = 0, double y = 0); Figure2D(const Figure2D& f); Figure2D(); Figure2D(CPoint &p1,CPoint& p2); ~Figure2D(); const Figure2D& operator=(Figure2D& d); /*double getStartX()const; double getStartY()const;*/ double getLength()const; double getHeight()const; void setLength(const int length); void setHeight(const int height); CPoint getStartPoint()const; void setStartPoint(const CPoint); CPoint getEndPoint()const; void setEndPoint(const CPoint); void setPenColor(COLORREF color); COLORREF getPenColor()const; void setBrushColor(COLORREF color); COLORREF getBrushColor()const; void setPenSize(const int size); int getPenSize()const; int getPenStyle()const; void getPenStyle(const int penStyle ); virtual int whoAmI(); //virtual void draw(const CClientDC&); virtual double Area()const; virtual double Perimeter()const; //virtual void Shift(double dx, double dy); //void MoveTo(double newX, double newY); //virtual void Resize(double newL, double newH); //virtual void Scale(double kx, double ky); virtual bool isInside(CPoint& P)const;//Point(P->getX(),P->getY()) lies inside the figure };
[ "liadhazoot5@gmail.com" ]
liadhazoot5@gmail.com
9bfa41f83570e9eaeb0d5f21ab2c6ec0fdd832e3
1798ba59a187a8868e32b4d4f5f54ec81efbf807
/src/f1tenth_costmap/include/costmap/inflation_layer.h
59017d0e63f29324fb5ab927fa4ea2f742d308e6
[]
no_license
chalkchalk/fl1oth_ws
60d17ee4d9206c436a221b82e2f92d0eedd78eb0
4c53588c129ad206ebc1354cc55ff6d2d88863d4
refs/heads/master
2022-12-11T11:15:58.773602
2020-09-13T04:04:24
2020-09-13T04:04:24
294,903,878
0
0
null
null
null
null
UTF-8
C++
false
false
7,122
h
/**************************************************************************** * Copyright (C) 2019 RoboMaster. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************/ /********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2008, 2013, Willow Garage, Inc. * 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 Willow Garage, Inc. 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 F1TENTH_COSTMAP_INFLATION_LAYER_H #define F1TENTH_COSTMAP_INFLATION_LAYER_H #include <mutex> #include "map_common.h" #include "layer.h" #include "layered_costmap.h" namespace f1tenth_costmap { /** * @class CellData * @brief Storage for cell information used during obstacle inflation */ class CellData { public: /** * @brief Constructor for a CellData objects * @param i The index of the cell in the cost map * @param x The x coordinate of the cell in the cost map * @param y The y coordinate of the cell in the cost map * @param sx The x coordinate of the closest obstacle cell in the costmap * @param sy The y coordinate of the closest obstacle cell in the costmap * @return */ CellData(double i, unsigned int x, unsigned int y, unsigned int sx, unsigned int sy) : index_(i), x_(x), y_(y), src_x_(sx), src_y_(sy) { } unsigned int index_; unsigned int x_, y_; unsigned int src_x_, src_y_; }; class InflationLayer : public Layer { public: InflationLayer(); virtual ~InflationLayer() { DeleteKernels(); } virtual void OnInitialize(); virtual void UpdateBounds(double robot_x, double robot_y, double robot_yaw, double *min_x, double *min_y, double *max_x, double *max_y); virtual void UpdateCosts(Costmap2D &master_grid, int min_i, int min_j, int max_i, int max_j); virtual bool IsDiscretized() { return true; } virtual void MatchSize(); virtual void Reset() { OnInitialize(); } /** @brief Given a distance, compute a cost. * @param distance The distance from an obstacle in cells * @return A cost value for the distance */ inline unsigned char ComputeCost(unsigned distance_cell) const { unsigned char cost = 0; if (distance_cell == 0) cost = LETHAL_OBSTACLE; else if (distance_cell * resolution_ <= inscribed_radius_) cost = INSCRIBED_INFLATED_OBSTACLE; else { // make sure cost falls off by Euclidean distance double euclidean_distance = distance_cell * resolution_; double factor = exp(-1.0 * weight_ * (euclidean_distance - inscribed_radius_)); cost = (unsigned char) ((INSCRIBED_INFLATED_OBSTACLE - 1) * factor); } return cost; } /** * @brief Change the values of the inflation radius parameters * @param inflation_radius The new inflation radius * @param cost_scaling_factor The new weight */ void SetInflationParameters(double inflation_radius, double cost_scaling_factor); protected: virtual void OnFootprintChanged(); std::recursive_mutex *inflation_access_; private: /** * @brief Lookup pre-computed distances * @param mx The x coordinate of the current cell * @param my The y coordinate of the current cell * @param src_x The x coordinate of the source cell * @param src_y The y coordinate of the source cell * @return */ inline double DistanceLookup(int mx, int my, int src_x, int src_y) { unsigned int dx = abs(mx - src_x); unsigned int dy = abs(my - src_y); return cached_distances_[dx][dy]; } /** * @brief Lookup pre-computed costs * @param mx The x coordinate of the current cell * @param my The y coordinate of the current cell * @param src_x The x coordinate of the source cell * @param src_y The y coordinate of the source cell * @return */ inline unsigned char CostLookup(int mx, int my, int src_x, int src_y) { unsigned int dx = abs(mx - src_x); unsigned int dy = abs(my - src_y); return cached_costs_[dx][dy]; } void ComputeCaches(); void DeleteKernels(); void InflateArea(int min_i, int min_j, int max_i, int max_j, unsigned char *master_grid); unsigned int CellDistance(double world_dist) { return layered_costmap_->GetCostMap()->World2Cell(world_dist); } inline void Enqueue(unsigned int index, unsigned int mx, unsigned int my, unsigned int src_x, unsigned int src_y); double inflation_radius_, inscribed_radius_, weight_; bool inflate_unknown_; unsigned int cell_inflation_radius_; unsigned int cached_cell_inflation_radius_; std::map<double, std::vector<CellData> > inflation_cells_; double resolution_; bool* seen_; int seen_size_; unsigned char** cached_costs_; double** cached_distances_; double last_min_x_, last_min_y_, last_max_x_, last_max_y_; bool need_reinflation_; }; } //namespace f1tenth_costmap #endif //F1TENTH_COSTMAP_INFLATION_LAYER_H
[ "1261677461@qq.com" ]
1261677461@qq.com
2d52ead03d35c538603bb571ce841dafdea65260
e5e0d729f082999a9bec142611365b00f7bfc684
/tensorflow/core/kernels/quantized_reshape_op.cc
bd76c94edeea7a7d59b26463a15194bd8f1c5e34
[ "Apache-2.0" ]
permissive
NVIDIA/tensorflow
ed6294098c7354dfc9f09631fc5ae22dbc278138
7cbba04a2ee16d21309eefad5be6585183a2d5a9
refs/heads/r1.15.5+nv23.03
2023-08-16T22:25:18.037979
2023-08-03T22:09:23
2023-08-03T22:09:23
263,748,045
763
117
Apache-2.0
2023-07-03T15:45:19
2020-05-13T21:34:32
C++
UTF-8
C++
false
false
2,192
cc
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/reshape_op.h" namespace tensorflow { class QuantizedReshapeOp : public ReshapeOp { public: explicit QuantizedReshapeOp(OpKernelConstruction* c) : ReshapeOp(c) {} void Compute(OpKernelContext* ctx) override { // This call processes inputs 1 and 2 to write output 0. ReshapeOp::Compute(ctx); const float input_min_float = ctx->input(2).flat<float>()(0); const float input_max_float = ctx->input(3).flat<float>()(0); Tensor* output_min = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_min)); output_min->flat<float>()(0) = input_min_float; Tensor* output_max = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(2, TensorShape({}), &output_max)); output_max->flat<float>()(0) = input_max_float; } }; #define REGISTER_CPU_KERNEL(type) \ REGISTER_KERNEL_BUILDER(Name("QuantizedReshape") \ .Device(DEVICE_CPU) \ .HostMemory("shape") \ .TypeConstraint<type>("T"), \ QuantizedReshapeOp) REGISTER_CPU_KERNEL(::tensorflow::quint8); REGISTER_CPU_KERNEL(::tensorflow::qint32); #undef REGISTER_CPU_KERNEL } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
2ce237e396b3ae1ab98711d5cb9b4e59087de48e
068218f6c860c27044e6c630b0e6f210ed7b381e
/3-webusb/arduino/libraries/PN532_SPI/PN532_SPI.h
1c8c4998cc8fdb8de98061493fefa71c6191bdcd
[ "MIT" ]
permissive
gdarchen/webusb-arduino-nfc
3fe32ce9ee805f91c81721c1d7ffe5fa1b4f21eb
9809c8c5582dae2d7f3648b6b5eed253c32f0126
refs/heads/master
2022-03-24T14:12:33.906811
2022-03-07T08:19:07
2022-03-07T08:19:07
218,491,754
24
3
MIT
2022-03-07T08:19:08
2019-10-30T09:36:22
C++
UTF-8
C++
false
false
797
h
#ifndef __PN532_SPI_H__ #define __PN532_SPI_H__ #include <SPI.h> #include "PN532Interface.h" class PN532_SPI : public PN532Interface { public: PN532_SPI(SPIClass &spi, uint8_t ss); void begin(); void wakeup(); int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout); private: SPIClass* _spi; uint8_t _ss; uint8_t command; bool isReady(); void writeFrame(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); int8_t readAckFrame(); inline void write(uint8_t data) { _spi->transfer(data); }; inline uint8_t read() { return _spi->transfer(0); }; }; #endif
[ "darchen.gautier@gmail.com" ]
darchen.gautier@gmail.com
f80bfd704012c3353dc930d66f520a3b5b3e0db8
770aa62b818401a1690a0ba58bdb0a91b92fd3a6
/Test9_1B/Test9_1B/Test9_1B.h
1277e2f70b713dae302bec79fc547cecfde3d5ae
[]
no_license
hkkhuang/Qt
d062e7937ba148635b6178dd6efb7f8c78f069f2
8f3e9777ecec0fd112e7ee266386208f46a01891
refs/heads/master
2018-06-29T12:33:20.670790
2018-05-31T13:32:02
2018-05-31T13:32:02
118,467,993
1
0
null
null
null
null
UTF-8
C++
false
false
274
h
#pragma once #include <QtWidgets/QMainWindow> #include "ui_Test9_1B.h" class Test9_1B : public QMainWindow { Q_OBJECT public: Test9_1B(QWidget *parent = Q_NULLPTR); //添加槽 private slots: int OnBtnNew(); int OnBtnDelete(); private: Ui::Test9_1BClass ui; };
[ "hkkhuang@163.com" ]
hkkhuang@163.com
a4bafb0a873bef14953b4280f8ec7f105454a027
183d423b1ca9fbaabc455e0ddc76730ca2d1c15d
/MFC/鼠标消息处理实例/鼠标消息处理实例View.h
1acaed5c623d44797b3b02683534a933570c745b
[]
no_license
leihtg/cproject
8c0bf5fe04986faacdd4a48320860bf7c92c1ba2
f1ef52ce3092add39216cec8da7d89f03a3db633
refs/heads/master
2022-02-16T00:20:41.200444
2019-08-25T13:59:01
2019-08-25T13:59:01
109,554,174
2
2
null
null
null
null
GB18030
C++
false
false
1,927
h
// 鼠标消息处理实例View.h : interface of the CMyView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_VIEW_H__13CC165C_C7B9_476C_ADB9_30195617433D__INCLUDED_) #define AFX_VIEW_H__13CC165C_C7B9_476C_ADB9_30195617433D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMyView : public CView { protected: // create from serialization only CMyView(); DECLARE_DYNCREATE(CMyView) // Attributes public: CMyDoc* GetDocument(); public: BOOL fDowned; CPoint ptDown; CPoint ptUp; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMyView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); //}}AFX_VIRTUAL // Implementation public: CRect oldrect; HCURSOR m_cursor; void DrawRect(); virtual ~CMyView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CMyView) afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in 鼠标消息处理实例View.cpp inline CMyDoc* CMyView::GetDocument() { return (CMyDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_VIEW_H__13CC165C_C7B9_476C_ADB9_30195617433D__INCLUDED_)
[ "leihtg@163.com" ]
leihtg@163.com
b932d30031322e1a016c76e9654fa4e66ead9117
93bfed14f2a6698a36c6a5a5b92d3f518999414c
/src/upnp/protocol-info.h
5ef75692e164c2f67a76910a96c3519fa8dbd6a0
[]
no_license
jhenstridge/upnp-present
c504744a59a48397bfaca670c3a2312e9026510d
02c35a0f83b0a28c40a66d89b59a798d771459b2
refs/heads/master
2021-01-10T09:04:22.292897
2015-06-15T10:14:25
2015-06-15T10:14:25
36,775,262
2
0
null
null
null
null
UTF-8
C++
false
false
4,471
h
/* -*- mode: c++ -*- */ /* * upnp-present: Send photos to a UPnP media renderer * Copyright (C) 2015 James Henstridge * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "gobj_memory.h" #include <libgupnp-av/gupnp-protocol-info.h> #include <QFlags> #include <QObject> #include <QString> #include <memory> #include <vector> namespace upnp { class ProtocolInfo : public QObject { Q_OBJECT Q_ENUMS(DlnaConversion) Q_FLAGS(DlnaOperations DlnaFlags) Q_PROPERTY(QString protocol READ protocol WRITE setProtocol NOTIFY protocolChanged) Q_PROPERTY(QString network READ network WRITE setNetwork NOTIFY networkChanged) Q_PROPERTY(QString mimeType READ mimeType WRITE setMimeType NOTIFY mimeTypeChanged) Q_PROPERTY(QString dlnaProfile READ dlnaProfile WRITE setDlnaProfile NOTIFY dlnaProfileChanged) Q_PROPERTY(DlnaConversion dlnaConversion READ dlnaConversion WRITE setDlnaConversion NOTIFY dlnaConversionChanged) Q_PROPERTY(DlnaOperations dlnaOperation READ dlnaOperation WRITE setDlnaOperation NOTIFY dlnaOperationChanged) Q_PROPERTY(DlnaFlags dlnaFlags READ dlnaFlags WRITE setDlnaFlags NOTIFY dlnaFlagsChanged) public: enum DlnaConversion { None = GUPNP_DLNA_CONVERSION_NONE, Transcoded = GUPNP_DLNA_CONVERSION_TRANSCODED, }; enum DlnaOperation { Range = GUPNP_DLNA_OPERATION_RANGE, TimeSeek = GUPNP_DLNA_OPERATION_TIMESEEK, }; Q_DECLARE_FLAGS(DlnaOperations, DlnaOperation) enum DlnaFlag { SenderPaced = GUPNP_DLNA_FLAGS_SENDER_PACED, TimeBasedSeek = GUPNP_DLNA_FLAGS_TIME_BASED_SEEK, ByteBasedSeek = GUPNP_DLNA_FLAGS_BYTE_BASED_SEEK, PlayContainer = GUPNP_DLNA_FLAGS_PLAY_CONTAINER, S0Increase = GUPNP_DLNA_FLAGS_S0_INCREASE, SnIncrease = GUPNP_DLNA_FLAGS_SN_INCREASE, RtspPause = GUPNP_DLNA_FLAGS_RTSP_PAUSE, StreamingTransferMode = GUPNP_DLNA_FLAGS_STREAMING_TRANSFER_MODE, InteractiveTransferMode = GUPNP_DLNA_FLAGS_INTERACTIVE_TRANSFER_MODE, BackgroundTransferMode = GUPNP_DLNA_FLAGS_BACKGROUND_TRANSFER_MODE, ConnectionStall = GUPNP_DLNA_FLAGS_CONNECTION_STALL, DlnaV15 = GUPNP_DLNA_FLAGS_DLNA_V15, LinkProtectedContent = GUPNP_DLNA_FLAGS_LINK_PROTECTED_CONTENT, ClearTextByteSeekFull = GUPNP_DLNA_FLAGS_CLEAR_TEXT_BYTE_SEEK_FULL, LopClearTextByteSeek = GUPNP_DLNA_FLAGS_LOP_CLEAR_TEXT_BYTE_SEEK, }; Q_DECLARE_FLAGS(DlnaFlags, DlnaFlag) ProtocolInfo(QObject *parent=nullptr); ProtocolInfo(const QString &protocol_info, QObject *parent=nullptr); virtual ~ProtocolInfo(); ProtocolInfo(const ProtocolInfo&) = delete; ProtocolInfo &operator=(const ProtocolInfo&) = delete; QString protocol() const; void setProtocol(const QString &new_protocol); QString network() const; void setNetwork(const QString &new_network); QString mimeType() const; void setMimeType(const QString &new_mime_type); QString dlnaProfile() const; void setDlnaProfile(const QString &new_profile); DlnaConversion dlnaConversion() const; void setDlnaConversion(DlnaConversion new_conversion); DlnaOperations dlnaOperation() const; void setDlnaOperation(DlnaOperations new_operation); DlnaFlags dlnaFlags() const; void setDlnaFlags(DlnaFlags new_flags); Q_INVOKABLE bool isCompatible(upnp::ProtocolInfo *other) const; Q_INVOKABLE QString asString() const; Q_SIGNALS: void protocolChanged(); void networkChanged(); void mimeTypeChanged(); void dlnaProfileChanged(); void dlnaConversionChanged(); void dlnaOperationChanged(); void dlnaFlagsChanged(); private: gobj_ptr<GUPnPProtocolInfo> info; }; } Q_DECLARE_OPERATORS_FOR_FLAGS(upnp::ProtocolInfo::DlnaOperations) Q_DECLARE_OPERATORS_FOR_FLAGS(upnp::ProtocolInfo::DlnaFlags)
[ "james@jamesh.id.au" ]
james@jamesh.id.au
9a498977b818fa6ebebbb8b2a9b000bd90faf904
c348efe40b4afac1de31e1cf93b800510f9d52f6
/Cal State San Bernardino (CSUSB)/CSE455 - Software Engineering/Program4b/StringToFloat.cpp
b2c19bf0cd9d18b1106b3c953c5647e5da15061a
[]
no_license
acoustictime/CollegeCode
5b57dc45459c35694e3df002a587bacc4f99f81a
a8ec647fa4b5a6a90f34f1c8715dfea88cefe6c6
refs/heads/master
2020-03-28T19:22:04.384018
2018-09-16T18:37:22
2018-09-16T18:37:22
148,968,472
1
0
null
null
null
null
UTF-8
C++
false
false
1,053
cpp
// Name: James Small // Program: 3B // Class: CSE455 // Description: StringToFloat class implementation file #include "StringToFloat.h" #include <stdlib.h> // for atof #include <ctype.h> // for isdigit // Constructor which sets the currentFloat to 0 StringToFloat::StringToFloat() { currentFloat = 0; } // This method takes a string and returns true or false if a float bool StringToFloat::isStringAFloat(string stringToTest) { currentString = stringToTest; int periodsCount = 0; bool nonDigitFound = false; bool isFloat = false; for (int i = 0;i < currentString.length(); i++) { if (!isdigit(currentString[i])) { if (currentString[i] == '.') { periodsCount++; } else if (currentString[i] == '-') { if (i != 0) nonDigitFound = true; } else nonDigitFound = true; } } if (!nonDigitFound && periodsCount < 2) { isFloat = true; currentFloat = atof(currentString.c_str()); } return isFloat; } // This method returns the float value float StringToFloat::getFloatValue() { return currentFloat; }
[ "Acoustictime@James-MacBook-Pro.local" ]
Acoustictime@James-MacBook-Pro.local
bf5b8d5880dd1dd5a3ce97e89bee320ec773fd99
b62117284f3dbd906f16088c32ca2f81c487ddfc
/1175/1175.cpp
08b34a6cc4605b89577923e5b372cd374a296e01
[]
no_license
LuizJarduli/URI_Resolucoes
8010581b959aea165fd5849518d6ac490e471c34
07e67a7482baf4a03f8f2d32b76eb8a0d34437ba
refs/heads/master
2023-01-05T03:01:32.728812
2020-11-01T23:39:18
2020-11-01T23:39:18
309,210,535
0
0
null
null
null
null
UTF-8
C++
false
false
347
cpp
#include <iostream> using namespace std; int main() { int n[20], i, val; for(i = 0; i < 20; i++){ cin >> n[i]; } for(i = 0 ; i < 10; i++){ val = n[i]; n[i] = n[19-i]; n[19-i] = val; } for(i = 0; i < 20; i++){ cout << "N[" << i << "] = " << n[i] << endl; } return 0; }
[ "luizjarduli@gmail.com" ]
luizjarduli@gmail.com
cd2692ba2d7911b256ece94d2e0acb861d43ea33
21cce871aca507ddea23d88595094c1ca39b6784
/meantest.h
5db5ebcc1f71da9d70d1cc35fedd110e79a01b53
[]
no_license
mytlsdnkr/word
3be7345afb3d54058ae213165f53cb4a905e14c1
a5b15550396a9154e8bfbaef708e5f0a522d7b85
refs/heads/master
2021-05-24T15:50:27.098523
2020-05-06T06:23:27
2020-05-06T06:23:27
253,640,768
0
0
null
null
null
null
UTF-8
C++
false
false
919
h
#ifndef MEANTEST_H #define MEANTEST_H #include <QDialog> #include <QDir> #include <QLabel> #include <QLineEdit> #include <vector> using namespace std; namespace Ui { class meantest; } class meaningtest{ public: QString word; QString mean; QString input; int check; int answer; }; class meantest : public QDialog { Q_OBJECT public: explicit meantest(QWidget *parent = nullptr); ~meantest(); int numOftest; int current; QDir qdir; QStringList filelist; void getRand(); void removeTrash(); void getData(); void setTest(); void checkAnswer(); meaningtest a[10000]; int numOfWord; vector<int> order; signals: void sendData(meaningtest *a, vector<int> &order); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); private: Ui::meantest *ui; }; #endif // MEANTEST_H
[ "mytlsdnkr@gmail.com" ]
mytlsdnkr@gmail.com
3d728dc392beef68e26d7d1b1a43c9a2ca496dfe
1745c63b79630153e43f677e53e5c3b2478542b3
/골드/1799.cpp
66b166fb8d6e44cd58740c3c5be757529b159ad0
[]
no_license
GodSang/BOJ
9dca6af13645a50a2579ed47618097e0b88c7613
d4f68a84fadf0f66c31a4ac2bcbd75f005784950
refs/heads/master
2023-07-24T17:12:12.639623
2021-09-03T14:29:14
2021-09-03T14:29:14
272,616,016
0
0
null
null
null
null
UTF-8
C++
false
false
1,156
cpp
// 14:40 ~ 16:00 #include <iostream> #include <vector> #include <utility> using namespace std; int n; int ans = -1; int board[2][11][11]; int chkL[21]; // 왼쪽 대각선 int chkR[21]; // 오른쪽 대각선 void func(int x, int y,int cnt, int flag) { if( y >= n ) { x++; y=0; } if(x >= n) { ans = cnt > ans ? cnt : ans; return; } if(board[flag][x][y] && !chkR[x-y+n-1] && !chkL[x+y]){ chkR[x-y+n-1] = 1; chkL[x+y] = 1; func(x, y + 1,cnt + 1, flag); chkR[x-y+n-1] = 0; chkL[x+y] = 0; } func(x, y + 1,cnt, flag); } int main() { int res=0; cin >> n; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if((i%2 == 0 && j%2 == 0) || (i%2 == 1 && j%2 == 1)) { // 흰색 발판 cin >> board[0][i][j]; } else // 검은색 발판 cin >> board[1][i][j]; } } func(0, 0, 0, 0); // 흰색 res = ans; ans = -1; fill(chkL, chkL+21, 0); fill(chkR, chkR+21, 0); func(0, 0, 0, 1); // 검은색 res += ans; cout << res; }
[ "tkdgh584@gmail.com" ]
tkdgh584@gmail.com
65f229c55b8257ec82bf3fad21b8d9cd5eb002c1
e86c8116ab0542a6b7f6a551344a86139e39f9de
/Framework/Graphics/Source/Public/Materials/Technique/Pass/PassManager.h
23e2a1ca1bfbe4c6885138e16611f5b28e3602ac
[]
no_license
jazzboysc/RTGI
fb1b9eed9272ce48828e9a294529d70be3f61532
80290d4e1892948d81427569fb862267407e3c5a
refs/heads/master
2020-04-14T05:23:38.219651
2015-07-17T07:12:48
2015-07-17T07:12:48
20,085,664
2
0
null
null
null
null
UTF-8
C++
false
false
945
h
//---------------------------------------------------------------------------- // Graphics framework for real-time GI study. // Che Sun at Worcester Polytechnic Institute, Fall 2013. //---------------------------------------------------------------------------- #ifndef RTGI_PassManager_H #define RTGI_PassManager_H #include "RefObject.h" #include "PassBase.h" namespace RTGI { //---------------------------------------------------------------------------- // Author: Che Sun // Date: 09/23/2014 //---------------------------------------------------------------------------- class PassManager : public RefObject { public: PassManager(); ~PassManager(); void AddPass(PassBase* pass); unsigned int GetPassCount() const; PassBase* GetPass(unsigned int i) const; void CreateDeviceResource(GPUDevice* device); protected: std::vector<PassBase*> mPasses; }; typedef RefPointer<PassManager> PassManagerPtr; } #endif
[ "S515380c" ]
S515380c
5e8d0f9e1948d257f9252c143799a625a0db7fc4
1866d4046ced94b01e953bea65b1c361557fc9ea
/zkj_stl_rb_tree.h
bbe4da7eb53166a76a28ead41de452081ea40b2d
[]
no_license
zhuokaijia/zkj_stl
0693d1df8773ba58de2a4aba646820acc44bfafe
c6eb4116db07b216c0198c7591b1c9c04882b309
refs/heads/master
2021-01-17T13:01:02.367095
2016-06-14T16:19:33
2016-06-14T16:19:33
57,869,957
1
0
null
null
null
null
UTF-8
C++
false
false
23,514
h
/* NOTE:This is an internal header file,included by other header file. * you should not attempt to use it directly */ #include <utility> #ifndef _ZKJ_STL_RB_TREE_H_ #define _ZKJ_STL_RB_TREE_H_ namespace zkj_stl{ //rb_tree_node typedef bool color_type; const color_type red = false; const color_type black = true; struct rb_tree_node_base{ typedef rb_tree_node_base* pointer; color_type color; pointer parent; pointer left; pointer right; static pointer mininum(pointer _p){ while (_p->left != nullptr){ _p = _p->left; } return _p; } static pointer maxinum(pointer _p){ while (_p->right != nullptr){ _p = _p->right; } return _p; } }; template<class T> struct rb_tree_node :public rb_tree_node_base{ T value; }; //rb_tree iterator struct rb_tree_iterator_base{ typedef typename rb_tree_node_base::pointer base_ptr; typedef ptrdiff_t difference_type; base_ptr node; void increase(){ //case 1 if (node->right != nullptr){ node = node->right; while (node->left != nullptr){ node = node->left; } } //case 2 else{ base_ptr y = node->parent; while (y->right == node){ node = y; y = y->parent; } if (node->right != y){ node = y; } } } void decrease(){ //case 1 if (node->color == red&&node->parent->parent == node){ node = node->right; } //case 2 else if (node->left != nullptr){ base_ptr y = node->left; while (y->right){ y = y->right; } node = y; } //case 3 else{ base_ptr y = node->parent; while (node == y->left){ node = y; y = y->parent; } node = y; } } template<class T,class Ref,class Ptr> struct rb_tree_iterator :public rb_tree_iterator_base{ typedef T value_type; typedef Ref reference; typedef Ptr pointer; typedef rb_tree_iterator<T, T&, T*> iterator; typedef rb_tree_iterator<T, const T&, const T*> const_iterator; typedef rb_tree_iterator<T, Ref, Ptr> self; typedef rb_tree_node<T>* link_type; //constructor rb_tree_iterator(){} rb_tree_iterator(link_type _p){ node = _p; } rb_tree_iterator(const rb_tree_iterator& _itr){ node = _itr->node; } reference operator*()const{ return link_type(node)->value; } pointer operator->()const{ return &(operator*()); } self& operator++(){ increase(); return *this; } self& operator++(int){ self tmp = *this; increase(); return tmp; } self& operator--(){ decrease(); return *this; } self& operator--(int){ self tmp = *this; desrease(); return tmp; } }; }; //forward-declared class fl_malloc; //forward-declared template<class T,class Alloc=fl_malloc> class simple_alloc; //rb_tree template<class Key,class Value,class KeyOfValue,class Compare,class Alloc=fl_malloc> class rb_tree{ protected: typedef rb_tree_node<Value> rb_tree_node; typedef rb_tree_node_base* base_ptr; typedef simple_alloc<rb_tree_node, Alloc> node_allocator; public: typedef Key key_type; typedef Value value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef rb_tree_node* link_type; typedef ptrdiff_t difference_type; typedef rb_tree_iterator<value_type, reference, pointer> iterator; protected: size_t node_nums; link_type header; Compare comp; link_type get_node(){ return node_allocator::allocate(); } void del_node(link_type _p){ return node_allocator::deallocate(_p); } link_type creat_node(const value_type _value){ link_type p = get_node(); construct(&(p->value), _value); } void destroy_node(link_type _p){ destroy(_p); del_node(_p); } link_type clone_node(link_type _p){ link_type tmp = creat_node(_p->value); tmp->color = base_ptr(_p)->color; tmp->left = nullptr; tmp->right = nullptr; return tmp; } link_type& root()const{ return (link_type&)header->parent; } link_type& leftmost()const{ return (link_type&)header->left; } link_type& rightmost()const{ return (link_type&)header->right; } static link_type& left(link_type _x){ return _x->left; } static link_type& right(link_type _x){ return _x->right; } static link_type& parent(link_type _x){ return _x->parent; } static link_type& value(link_type _x){ return _x->value; } static link_type& key(link_type _x){ return KeyOfValue()(value(_x)); } static link_type& color(link_type _x){ return _x->color; } static link_type& left(base_ptr _x){ return _x->left; } static link_type& right(base_ptr _x){ return _x->right; } static link_type& parent(base_ptr _x){ return _x->parent; } static link_type& value(base_ptr _x){ return link_type(_x)->value; } static link_type& key(base_ptr _x){ return KeyOfValue()(value(link_type(_x))); } static link_type& color(base_ptr _x){ return _x->color; } //get maximum static link_type maximum(link_type _p){ return static_cast<link_type>(rb_tree_node_base::maxinum(_p)); } //get minimum static link_type minimum(link_type _p){ return static_cast<link_type>(rb_tree_node_base::mininum(_p)); } private: void init(){ header = get_node(); color(header) = red; root() = nullptr; leftmost() = header; rightmost() = header; } //_y is _x's parent node iterator _insert(base_ptr _x, base_ptr _y, const Value _value); link_type node_copy(link_type _x, link_type _y); public: rb_tree(const Compare& _comp=Compare()):comp(_comp),node_nums(0){ init(); } rb_tree(const rb_tree<Key, Value, KeyOfValue, Compare, Alloc>& _x){ if (_x->node_nums == 0){ init(); } else{ color(header) = red; root() = node_copy(_x.root(), header); leftmost() = minimum(root()); rightmost() = maximum(root()); } node_nums = _x.node_nums; } ~rb_tree(){ clear(); del_node(header); } void earse(iterator _pos){ link_type y = rb_tree_banlance_for_earse(_pos.node, root(), leftmost(), rightmost()); destroy_node(_pos.node); node_nums--; } iterator begin(){ return leftmost(); } iterator end(){ return header; } size_t size(){ return node_nums; } size_t max_size(){ return static_cast<size_t>(-1); } bool empty(){ return node_nums == 0; } Compare key_comp(){ return comp; } //allow duplicate iterator insert_equal(const Value& _value); //disalloc duplicate iterator insert_unique(const Value& _value); iterator find(const Key& _key); }; inline void rb_tree_rotate_left(rb_tree_node_base* _x, rb_tree_node_base*& _root /* pass by reference*/){ rb_tree_node_base* y = _x->right; _x->right = y->left; if (y->left != nullptr){ y->left->parent = _x; } y->parent = _x->parent; if (_x == _root){ _root = y; } else if (_x->parent->left == _x){ _x->parent->left = y; } else{ _x->parent->right = y; } y->left = _x; _x->parent = y; } inline void rb_tree_rotate_right(rb_tree_node_base* _x, rb_tree_node_base*& _root /* pass by reference*/){ rb_tree_node_base* y = _x->left; _x->left = y->right; if (y->right != nullptr){ y->right->parent = _x; } y->parent = _x->parent; if (_x == _root){ _root == y; } else if (_x == _x->parent->left){ _x->parent->left = y; } else{ _x->parent->right = y; } y->right = _x; _x->parent = y; } //to make sure the balance of rb_tree //case 1:_x's uncle node is red //case 2:_x's uncle node is black and _x is a left child //case 3:_x's uncle node is black and _x is a right child void rb_tree_node_balance(rb_tree_node_base* _x, rb_tree_node_base*& _root /* pass by reference*/){ _x->color = red; //must be red while (_x != _root&&_x->parent->color == red){ if (_x->parent == _x->parent->parent->left){ rb_tree_node_base* y = _x->parent->parent->right; if (y != nullptr&&y->color == red){ //case 1 _x->parent->color = black; y->color = black; y->parent->color = red; _x = _x->parent->parent; } else{ if (_x == _x->parent->right){ //case 3 _x = _x->parent; //convert case 3 to case 2 rb_tree_rotate_left(_x, _root); } //case 2 _x->parent->color = black; _x->parent->parent->color = red; rb_tree_rotate_right(_x->parent->parent, _root); } } else{ rb_tree_node_base* y = _x->parent->parent->left; if (y != nullptr&&y->color == red){ //case 1 _x->parent->color = black; y->color = black; y->parent->color = red; _x = _x->parent->parent; } else{ if (_x == _x->parent->left){ //case 3 _x = _x->parent; //convert case 3 to case 2 rb_tree_rotate_right(_x, _root); } //case 2 _x->parent->color = black; _x->parent->parent->color = red; rb_tree_rotate_left(_x->parent->parent, _root); } } } _root->color = black; //must be black } //to make sure the balance of rb_tree //we set w as _x's brother node //case 1:the color of w is red //case 2:the color of w is black,and both of w'children is black //case 3:the color of w is black, color(w->left)==red and color(w->right)==black //case 4:the color of w is black, color(w->right)==red rb_tree_node_base* rb_tree_banlance_for_earse(rb_tree_node_base* _z, rb_tree_node_base*& _root, rb_tree_node_base*& _leftmost, rb_tree_node_base*& _rightmost){ rb_tree_node_base* y = _z; rb_tree_node_base* x = nullptr; rb_tree_node_base* xp = nullptr; /*find the successor*/ if (y->left == nullptr){ x = y->right; //x might be null } else if (y->right == nullptr){ x = y->left; //x might be null } else{ y = y->right; while (y->left){ y = y->left; } x = y->right; //x might be null } if (y == _z){ xp = y->parent; if (x){ x->parent = y->parent; } if (_root == _z){ _root = x; } else if (_z->parent->left == _z){ x = _z->parent->left; } else{ x = _z->parent->right; } /*updata leftmost and right most*/ if (_rightmost == _z){ //_z->right must be null if (_z->left == nullptr){ _rightmost = _z->parent; } else{ _rightmost = rb_tree_node_base::maxinum(x); } } if (_leftmost == _z){ //_z->left must be null if (_z->right == nullptr){ _leftmost = _z->parent; } else{ _leftmost = rb_tree_node_base::mininum(x); } } } else{ //y != _z _z->left->parent = y; y->left = _z->left; if (y != _z->right){ xp = y->parent; if (x){ x->parent = y->parent; } y->parent->left = x; y->right = _z->right; _z->right->parent = y; } else{ xp = y; } if (_root == _z){ _root = x; } else if (_z->parent->left == _z){ _z->parent->left = y; } else{ _z->parent->right = y; } y->parent = _z->parent; std::swap(y->color, _z->color); y = _z; } if (y->color == black){ while (x != _root && (x == nullptr || x->color == black)){ if (x == xp->left){ rb_tree_node_base* w = xp->right; if (w->color == red){ //case 1 w->color = black; xp->color = red; rb_tree_rotate_left(xp, _root); w = xp->right; } if ((w->left == nullptr || w->left->color == black) && //case 2 (w->right == nullptr || w->right->color == black)){ w->color = red; x = xp; xp = xp->parent; } else{ if (w->right == nullptr || w->right->color == black){ //case 3 if (w->left){ w->left->color = black; } w->color = red; rb_tree_rotate_right(w, _root); w = xp->right; } w->color = xp->color; //case 4 xp->color = black; if (w->right){ w->right->color = black; } rb_tree_rotate_left(xp, _root); break; // loop completes } } else{ // same as then clause with "right" and "left" exchanged rb_tree_node_base* w = xp->left; if (w->color == red){ //case 1 w->color = black; xp->color = red; rb_tree_rotate_right(xp, _root); w = xp->left; } if ((w->right == nullptr || w->right->color == black) && //case 2 (w->left == nullptr || w->left->color == black)){ w->color = red; x = xp; xp = xp->parent; } else{ if (w->left == nullptr || w->left->color == black){ //case 3 if (w->right){ w->right->color = black; } w->color = red; rb_tree_rotate_left(w, _root); w = xp->left; } w->color = xp->color; //case 4 xp->color = black; if (w->left){ w->left->color = black; } rb_tree_rotate_right(xp, _root); break; // loop completes } } if (x){ x->color = black; } } } return y; } template<class Key, class Value, class KeyOfValue, class Compare, class Alloc> typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::link_type rb_tree<Key, Value, KeyOfValue, Compare, Alloc>:: node_copy(link_type _x, link_type _y){ link_type tmp = clone_node(_x); tmp->parent = _y; if (_x->right){ tmp->right = node_copy(right(_x), tmp); } _y = tmp; _x = left(_x); while (_x != nullptr){ link_type t = clone_node(_x); _y->left = t; t->parent = _y; if (_x->right){ _y->right = node_copy(right(_x), _y); } _y = t; _x = left(_x); } return tmp; } template<class Key,class Value,class KeyOfValue,class Compare,class Alloc> typename rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::iterator rb_tree<Key, Value, KeyOfValue, Compare, Alloc>:: _insert(rb_tree_node_base* _x, rb_tree_node_base* _y, const Value _value){ typedef rb_tree_node* link_type; link_type tmp=creat_node(_value); if (_y == header || _x != nullptr || comp(key(tmp), key(_y))){ left(_y) = tmp; if (_y == header){ root() = tmp; rightmost() = tmp; } else if (_y == leftmost()){ leftmost() == tmp; } } else{ right(_y) = tmp; if (_y == rightmost()){ rightmost()= tmp; } } parent(tmp) = _y; left(tmp) = nullptr; right(tmp) = nullptr; rb_tree_node_balance(tmp, root()); ++node_nums; return iterator(tmp); } template<class Key, class Value, class KeyOfValue, class Compare, class Alloc> typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator rb_tree<Key, Value, KeyOfValue, Compare, Alloc>:: insert_equal(const Value& _value){ link_type y = header; link_type x = root(); while (x != nullptr){ y = x; x = comp(KeyOfValue()(_value), key(x)) ? left(x), right(x); } return _insert(x, y, _value); } template<class Key, class Value, class KeyOfValue, class Compare, class Alloc> typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator rb_tree<Key, Value, KeyOfValue, Compare, Alloc>:: insert_unique(const Value& _value){ link_type y = header; link_type x = root(); bool cp = true; while (x != nullptr){ y = x; cp = comp(key(x), KeyOfValue()(_value)); x = cp ? right(x) : left(x); } iterator j = iterator(y); if (!cp){ if (j == begin()){ return insert(x, y, _value); } else{ j--; } } if (comp(key(j.node), KeyOfValue()(_value))){ return insert(x, y, _value); } return j; } template<class Key, class Value, class KeyOfValue, class Compare, class Alloc> typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator rb_tree<Key, Value, KeyOfValue, Compare, Alloc>:: find(const Key& _key){ link_type y = header; link_type x = root(); while (x != nullptr){ if (comp(k, key(x))){ y = x; x = left(x); } else{ x = right(x); } } iterator j = iterator(y); if (j == end() || comp(k, key(j.node))){ return end(); } else{ return j; } } }//namespace zkj_stl #endif //mode:c++
[ "946114150@qq.com" ]
946114150@qq.com
a465382188aa5b623c2230a8fbdb84a134e65195
3b9b983d78d8ce148dad6ffc417ad61938531a6b
/engine/runtime/rendering/program.cpp
b6fc40a0fe9314c34a10b1d006a7cecb01926cec
[ "BSD-2-Clause" ]
permissive
nemerle/EtherealEngine
9b605814b8464fee7cc3031ef2fc69236a6b8034
44755cd28813779248df756ebb61b1dd3f256165
refs/heads/master
2021-06-27T00:21:52.711853
2017-09-15T18:17:31
2017-09-15T18:17:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,473
cpp
#include "program.h" #include "frame_buffer.h" #include "shader.h" #include "texture.h" #include "uniform.h" program::program(asset_handle<shader> computeShader) { add_shader(computeShader); populate(); } program::program(asset_handle<shader> vertexShader, asset_handle<shader> fragmentShader) { add_shader(vertexShader); add_shader(fragmentShader); populate(); } program::~program() { dispose(); } void program::dispose() { if(is_valid()) gfx::destroy(handle); handle = {gfx::kInvalidHandle}; } bool program::is_valid() const { return gfx::isValid(handle); } void program::set_texture(std::uint8_t _stage, const std::string& _sampler, frame_buffer* frameBuffer, uint8_t _attachment /*= 0 */, std::uint32_t _flags /*= std::numeric_limits<std::uint32_t>::max()*/) { if(!frameBuffer) return; gfx::setTexture(_stage, get_uniform(_sampler, true)->handle, gfx::getTexture(frameBuffer->handle, _attachment), _flags); } void program::set_texture(std::uint8_t _stage, const std::string& _sampler, gfx::FrameBufferHandle frameBuffer, uint8_t _attachment /*= 0 */, std::uint32_t _flags /*= std::numeric_limits<std::uint32_t>::max()*/) { gfx::setTexture(_stage, get_uniform(_sampler, true)->handle, gfx::getTexture(frameBuffer, _attachment), _flags); } void program::set_texture(std::uint8_t _stage, const std::string& _sampler, texture* _texture, std::uint32_t _flags /*= std::numeric_limits<std::uint32_t>::max()*/) { if(!_texture) return; gfx::setTexture(_stage, get_uniform(_sampler, true)->handle, _texture->handle, _flags); } void program::set_texture(std::uint8_t _stage, const std::string& _sampler, gfx::TextureHandle _texture, std::uint32_t _flags /*= std::numeric_limits<std::uint32_t>::max()*/) { gfx::setTexture(_stage, get_uniform(_sampler, true)->handle, _texture, _flags); } void program::set_uniform(const std::string& _name, const void* _value, uint16_t _num) { auto hUniform = get_uniform(_name); if(hUniform) gfx::setUniform(hUniform->handle, _value, _num); } std::shared_ptr<uniform> program::get_uniform(const std::string& _name, bool texture) { std::shared_ptr<uniform> hUniform; auto it = uniforms.find(_name); if(it != uniforms.end()) { hUniform = it->second; } else { if(texture) { hUniform = std::make_shared<uniform>(); hUniform->populate(_name, gfx::UniformType::Int1, 1); uniforms[_name] = hUniform; } } return hUniform; } void program::add_shader(asset_handle<shader> shader) { for(auto& uniform : shader->uniforms) { uniforms[uniform->info.name] = uniform; } shaders_cached.push_back(shader->handle.idx); shaders.push_back(shader); } void program::populate() { dispose(); if(shaders.size() == 1 && shaders[0] && shaders[0]->is_valid()) { handle = gfx::createProgram(shaders[0]->handle); shaders_cached[0] = shaders[0]->handle.idx; } else if(shaders.size() == 2 && shaders[0] && shaders[0]->is_valid() && shaders[1] && shaders[1]->is_valid()) { handle = gfx::createProgram(shaders[0]->handle, shaders[1]->handle); shaders_cached[0] = shaders[0]->handle.idx; shaders_cached[1] = shaders[1]->handle.idx; } } bool program::begin_pass() { bool repopulate = false; for(std::size_t i = 0; i < shaders_cached.size(); ++i) { if(!shaders[i]) continue; if(shaders_cached[i] != shaders[i]->handle.idx) { repopulate = true; break; } } if(repopulate) populate(); return is_valid(); }
[ "nikolai.p.ivanov@gmail.com" ]
nikolai.p.ivanov@gmail.com
7c914e1df0898aa8d1b43ff0d07f200ae1a05d8b
3a23d2ad72cd0c4199217e9177de59c2bc8bbcea
/week 1~10/week4_20200405/kakaru_heap_2.cpp
868a899d9a7a42bea17cafaf566842914bd4a23c
[]
no_license
mojh7/jackkong_algo
de9dc3869b694a956df5986c51d088c31e84d430
d8f1c77be078a1f488d2b9ce71e4069c2bb345cd
refs/heads/master
2023-03-06T17:12:29.903069
2021-02-23T11:30:46
2021-02-23T11:30:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
#include <string> #include <vector> #include <queue> using namespace std; int solution(int stock, vector<int> dates, vector<int> supplies, int k) { int answer = 0; int cur = 0; priority_queue<int> pq; while(stock < k){ for(int i = cur; i < dates.size() && dates[i] <= stock; i++){ pq.push(supplies[i]); cur++; } stock += pq.top(); pq.pop(); answer++; } return answer; }
[ "skybluenada64@gmail.com" ]
skybluenada64@gmail.com
4de245336d6e91b35080cf34a98fb0be556a2516
d266d98b0801fb755cd8280fdc50354486cd3170
/4.2B.5/IncompatibleSizeException.hpp
ad5860eb13d2edd5f691e30e36ef659e5ef3d411
[]
no_license
stephennovis/C-For-Financial-Engineering
ad528fa3d4b72e8c24d0c574d540e324e4ec7e4a
9277bda2c39dcf576ac58216feaf96730a7ca09a
refs/heads/master
2020-04-10T01:33:50.544935
2018-12-06T22:18:55
2018-12-06T22:18:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
679
hpp
// // Created by Steve on 11/7/18. // #ifndef INC_4_2B_2_INCOMPATIBLESIZEEXCEPTION_HPP #define INC_4_2B_2_INCOMPATIBLESIZEEXCEPTION_HPP #include "ArrayException.hpp" #include <sstream> #include <iostream> using namespace std; class IncompatibleSizeException : public ArrayException { public: // Constructors and destructor IncompatibleSizeException() : ArrayException() { // Default constructor } ~IncompatibleSizeException() { // Destructor } string GetMessage() { stringstream stream; stream << "Incompatible size of arrays."; return stream.str(); } }; #endif //INC_4_2B_2_INCOMPATIBLESIZEEXCEPTION_HPP
[ "stevenovis@Steves-MacBook-Pro.local" ]
stevenovis@Steves-MacBook-Pro.local
61536e19268a4f59b1aa5db7ba16d9335236ecb6
e8700bccba49b3c7307d2fe98fe60f30e58debdf
/src/libtsduck/base/network/tsIPv4Address.cpp
e0d936fc53264f0bc2a683466de0a3a0715f7424
[ "BSD-2-Clause" ]
permissive
moveman/tsduck
f120e292355227276b893cba3cba989e01e10b5c
2e5095d2384de07f04c285cf051dfa1523d05fc2
refs/heads/master
2023-08-22T06:10:17.046301
2021-09-26T20:59:02
2021-09-26T20:59:02
411,141,449
0
0
null
null
null
null
UTF-8
C++
false
false
7,506
cpp
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2021, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 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 "tsIPv4Address.h" #include "tsIPUtils.h" #include "tsMemory.h" TSDUCK_SOURCE; // Local host address const ts::IPv4Address ts::IPv4Address::LocalHost(127, 0, 0, 1); //---------------------------------------------------------------------------- // Constructors and destructors //---------------------------------------------------------------------------- ts::IPv4Address::IPv4Address(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) : _addr((uint32_t(b1) << 24) | (uint32_t(b2) << 16) | (uint32_t(b3) << 8) | uint32_t(b4)) { } ts::IPv4Address::IPv4Address(const ::sockaddr& s) : _addr(AnyAddress) { if (s.sa_family == AF_INET) { assert(sizeof(::sockaddr) >= sizeof(::sockaddr_in)); const ::sockaddr_in* sp = reinterpret_cast<const ::sockaddr_in*>(&s); _addr = ntohl(sp->sin_addr.s_addr); } } ts::IPv4Address::IPv4Address(const ::sockaddr_in& s) : _addr(AnyAddress) { if (s.sin_family == AF_INET) { _addr = ntohl(s.sin_addr.s_addr); } } ts::IPv4Address::~IPv4Address() { } //---------------------------------------------------------------------------- // Copy into socket structures //---------------------------------------------------------------------------- void ts::IPv4Address::copy(::sockaddr& s, uint16_t port) const { TS_ZERO(s); assert(sizeof(::sockaddr) >= sizeof(::sockaddr_in)); ::sockaddr_in* sp = reinterpret_cast<::sockaddr_in*> (&s); sp->sin_family = AF_INET; sp->sin_addr.s_addr = htonl(_addr); sp->sin_port = htons(port); } void ts::IPv4Address::copy(::sockaddr_in& s, uint16_t port) const { TS_ZERO(s); s.sin_family = AF_INET; s.sin_addr.s_addr = htonl(_addr); s.sin_port = htons(port); } //---------------------------------------------------------------------------- // Set/get address //---------------------------------------------------------------------------- size_t ts::IPv4Address::binarySize() const { return BYTES; } void ts::IPv4Address::clearAddress() { _addr = AnyAddress; } bool ts::IPv4Address::hasAddress() const { return _addr != AnyAddress; } bool ts::IPv4Address::isMulticast() const { return IN_MULTICAST(_addr); } bool ts::IPv4Address::setAddress(const void* addr, size_t size) { if (addr == nullptr || size < BYTES) { return false; } else { _addr = GetUInt32BE(addr); return true; } } size_t ts::IPv4Address::getAddress(void* addr, size_t size) const { if (addr == nullptr || size < BYTES) { return 0; } else { PutUInt32BE(addr, _addr); return BYTES; } } void ts::IPv4Address::setAddress(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) { _addr = (uint32_t(b1) << 24) | (uint32_t(b2) << 16) | (uint32_t(b3) << 8) | uint32_t(b4); } //---------------------------------------------------------------------------- // Decode a string or hostname which is resolved. //---------------------------------------------------------------------------- bool ts::IPv4Address::resolve(const UString& name, Report& report) { _addr = AnyAddress; // Try the trivial case of an IPv4 address. uint8_t b1, b2, b3, b4; if (name.scan(u"%d.%d.%d.%d", {&b1, &b2, &b3, &b4})) { setAddress(b1, b2, b3, b4); return true; } // The best way to resolve a name is getaddrinfo(). However, this function // tries to activate shared objects to lookup services. Consequently, it // cannot be used when the application is statically linked. With statically // linked application, we need a plain address string "x.x.x.x". #if defined(TSDUCK_STATIC) report.error(u"error resolving %s: must be an IPv4 address x.x.x.x (statically linked application)", {name}); return false; #else ::addrinfo hints; TS_ZERO(hints); hints.ai_family = AF_INET; ::addrinfo* res = nullptr; const int status = ::getaddrinfo(name.toUTF8().c_str(), nullptr, &hints, &res); if (status != 0) { #if defined(TS_WINDOWS) const SysSocketErrorCode code = LastSysSocketErrorCode(); report.error(name + u": " + SysSocketErrorCodeMessage(code)); #else const SysErrorCode code = LastSysErrorCode(); UString errmsg; if (status == EAI_SYSTEM) { errmsg = SysErrorCodeMessage(code); } else { errmsg = UString::FromUTF8(gai_strerror(status)); } report.error(name + u": " + errmsg); #endif return false; } // Look for an IPv4 address. All returned addresses should be IPv4 since // we specfied the family in hints, but check to be sure. ::addrinfo* ai = res; while (ai != nullptr && (ai->ai_family != AF_INET || ai->ai_addr == nullptr || ai->ai_addr->sa_family != AF_INET)) { ai = ai->ai_next; } if (ai != nullptr) { assert(sizeof(::sockaddr) >= sizeof(::sockaddr_in)); const ::sockaddr_in* sp = reinterpret_cast<const ::sockaddr_in*> (ai->ai_addr); _addr = ntohl(sp->sin_addr.s_addr); } else { report.error(u"no IPv4 address found for " + name); } ::freeaddrinfo(res); return ai != nullptr; #endif // TSDUCK_STATIC } //---------------------------------------------------------------------------- // Check if this address "matches" another one. //---------------------------------------------------------------------------- bool ts::IPv4Address::match(const IPv4Address& other) const { return _addr == AnyAddress || other._addr == AnyAddress || _addr == other._addr; } //---------------------------------------------------------------------------- // Convert to a string object //---------------------------------------------------------------------------- ts::UString ts::IPv4Address::toString() const { return UString::Format(u"%d.%d.%d.%d", {(_addr >> 24) & 0xFF, (_addr >> 16) & 0xFF, (_addr >> 8) & 0xFF, _addr & 0xFF}); }
[ "thierry@lelegard.fr" ]
thierry@lelegard.fr
17d87f126e5d5759cdb5dbd89e9e4d2321a0cc41
c2d270aff0a4d939f43b6359ac2c564b2565be76
/src/cc/resources/display_resource_provider.h
093629f266d04a7414db6d711eba49850aa62efc
[ "BSD-3-Clause" ]
permissive
bopopescu/QuicDep
dfa5c2b6aa29eb6f52b12486ff7f3757c808808d
bc86b705a6cf02d2eade4f3ea8cf5fe73ef52aa0
refs/heads/master
2022-04-26T04:36:55.675836
2020-04-29T21:29:26
2020-04-29T21:29:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,484
h
// Copyright 2017 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 CC_RESOURCES_DISPLAY_RESOURCE_PROVIDER_H_ #define CC_RESOURCES_DISPLAY_RESOURCE_PROVIDER_H_ #include "build/build_config.h" #include "cc/output/overlay_candidate.h" #include "cc/resources/resource_provider.h" namespace viz { class SharedBitmapManager; } // namespace viz namespace cc { // This class is not thread-safe and can only be called from the thread it was // created on. class CC_EXPORT DisplayResourceProvider : public ResourceProvider { public: DisplayResourceProvider( viz::ContextProvider* compositor_context_provider, viz::SharedBitmapManager* shared_bitmap_manager, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, const viz::ResourceSettings& resource_settings); ~DisplayResourceProvider() override; #if defined(OS_ANDROID) // Send an overlay promotion hint to all resources that requested it via // |wants_promotion_hints_set_|. |promotable_hints| contains all the // resources that should be told that they're promotable. Others will be told // that they're not promotable right now. void SendPromotionHints( const OverlayCandidateList::PromotionHintInfoMap& promotion_hints); #endif void WaitSyncToken(viz::ResourceId id); // The following lock classes are part of the DisplayResourceProvider API and // are needed to read the resource contents. The user must ensure that they // only use GL locks on GL resources, etc, and this is enforced by assertions. class CC_EXPORT ScopedReadLockGL { public: ScopedReadLockGL(DisplayResourceProvider* resource_provider, viz::ResourceId resource_id); ~ScopedReadLockGL(); GLuint texture_id() const { return texture_id_; } GLenum target() const { return target_; } const gfx::Size& size() const { return size_; } const gfx::ColorSpace& color_space() const { return color_space_; } private: DisplayResourceProvider* const resource_provider_; const viz::ResourceId resource_id_; GLuint texture_id_; GLenum target_; gfx::Size size_; gfx::ColorSpace color_space_; DISALLOW_COPY_AND_ASSIGN(ScopedReadLockGL); }; class CC_EXPORT ScopedSamplerGL { public: ScopedSamplerGL(DisplayResourceProvider* resource_provider, viz::ResourceId resource_id, GLenum filter); ScopedSamplerGL(DisplayResourceProvider* resource_provider, viz::ResourceId resource_id, GLenum unit, GLenum filter); ~ScopedSamplerGL(); GLuint texture_id() const { return resource_lock_.texture_id(); } GLenum target() const { return target_; } const gfx::ColorSpace& color_space() const { return resource_lock_.color_space(); } private: const ScopedReadLockGL resource_lock_; const GLenum unit_; const GLenum target_; DISALLOW_COPY_AND_ASSIGN(ScopedSamplerGL); }; class CC_EXPORT ScopedReadLockSkImage { public: ScopedReadLockSkImage(DisplayResourceProvider* resource_provider, viz::ResourceId resource_id); ~ScopedReadLockSkImage(); const SkImage* sk_image() const { return sk_image_.get(); } bool valid() const { return !!sk_image_; } private: DisplayResourceProvider* const resource_provider_; const viz::ResourceId resource_id_; sk_sp<SkImage> sk_image_; DISALLOW_COPY_AND_ASSIGN(ScopedReadLockSkImage); }; class CC_EXPORT ScopedReadLockSoftware { public: ScopedReadLockSoftware(DisplayResourceProvider* resource_provider, viz::ResourceId resource_id); ~ScopedReadLockSoftware(); const SkBitmap* sk_bitmap() const { DCHECK(valid()); return &sk_bitmap_; } bool valid() const { return !!sk_bitmap_.getPixels(); } private: DisplayResourceProvider* const resource_provider_; const viz::ResourceId resource_id_; SkBitmap sk_bitmap_; DISALLOW_COPY_AND_ASSIGN(ScopedReadLockSoftware); }; // All resources that are returned to children while an instance of this // class exists will be stored and returned when the instance is destroyed. class CC_EXPORT ScopedBatchReturnResources { public: explicit ScopedBatchReturnResources( DisplayResourceProvider* resource_provider); ~ScopedBatchReturnResources(); private: DisplayResourceProvider* const resource_provider_; DISALLOW_COPY_AND_ASSIGN(ScopedBatchReturnResources); }; // Sets the current read fence. If a resource is locked for read // and has read fences enabled, the resource will not allow writes // until this fence has passed. void SetReadLockFence(viz::ResourceFence* fence) { current_read_lock_fence_ = fence; } // Creates accounting for a child. Returns a child ID. int CreateChild(const ReturnCallback& return_callback); // Destroys accounting for the child, deleting all accounted resources. void DestroyChild(int child); // Sets whether resources need sync points set on them when returned to this // child. Defaults to true. void SetChildNeedsSyncTokens(int child, bool needs_sync_tokens); // Gets the child->parent resource ID map. const ResourceIdMap& GetChildToParentMap(int child) const; // Receives resources from a child, moving them from mailboxes. ResourceIds // passed are in the child namespace, and will be translated to the parent // namespace, added to the child->parent map. // This adds the resources to the working set in the ResourceProvider without // declaring which resources are in use. Use DeclareUsedResourcesFromChild // after calling this method to do that. All calls to ReceiveFromChild should // be followed by a DeclareUsedResourcesFromChild. // NOTE: if the sync_token is set on any viz::TransferableResource, this will // wait on it. void ReceiveFromChild( int child, const std::vector<viz::TransferableResource>& transferable_resources); // Once a set of resources have been received, they may or may not be used. // This declares what set of resources are currently in use from the child, // releasing any other resources back to the child. void DeclareUsedResourcesFromChild( int child, const viz::ResourceIdSet& resources_from_child); private: friend class ScopedBatchReturnResources; const viz::internal::Resource* LockForRead(viz::ResourceId id); void UnlockForRead(viz::ResourceId id); struct Child { Child(); Child(const Child& other); ~Child(); ResourceIdMap child_to_parent_map; ReturnCallback return_callback; bool marked_for_deletion; bool needs_sync_tokens; }; using ChildMap = std::unordered_map<int, Child>; void DeleteAndReturnUnusedResourcesToChild(ChildMap::iterator child_it, DeleteStyle style, const ResourceIdArray& unused); void DestroyChildInternal(ChildMap::iterator it, DeleteStyle style); void SetBatchReturnResources(bool aggregate); scoped_refptr<viz::ResourceFence> current_read_lock_fence_; ChildMap children_; base::flat_map<viz::ResourceId, sk_sp<SkImage>> resource_sk_image_; DISALLOW_COPY_AND_ASSIGN(DisplayResourceProvider); }; } // namespace cc #endif // CC_RESOURCES_DISPLAY_RESOURCE_PROVIDER_H_
[ "rdeshm0@aptvm070-6.apt.emulab.net" ]
rdeshm0@aptvm070-6.apt.emulab.net
b177ac94b3ebd5a7e9bd45405f6f22ac8da9f007
be515b9c4fe7a817dc7df4ca8c8d0a5e413e7801
/Spockduino/Spockduino.ino
96c6dc823783ecde7a697eb1e514b750d7e6520e
[ "MIT" ]
permissive
wez/SpockKeyboard
d023bffbbd2c779968f6d6d1fc6d21dd1c645dd6
634afc9ebe4d3521960f310ccee0844ded738ad6
refs/heads/master
2020-03-09T07:25:00.944221
2018-07-17T23:45:47
2018-07-17T23:45:47
128,664,180
17
0
null
null
null
null
UTF-8
C++
false
false
2,555
ino
#define WAT 0 #include "HID.h" #include "HIDTables.h" #include "Keyboard.h" #define HID_KEYBOARD_A HID_KEYBOARD_A_AND_A #define HID_KEYBOARD_B HID_KEYBOARD_B_AND_B #define HID_KEYBOARD_C HID_KEYBOARD_C_AND_C #define HID_KEYBOARD_D HID_KEYBOARD_D_AND_D #define HID_KEYBOARD_E HID_KEYBOARD_E_AND_E #define HID_KEYBOARD_F HID_KEYBOARD_F_AND_F #define HID_KEYBOARD_G HID_KEYBOARD_G_AND_G #define HID_KEYBOARD_H HID_KEYBOARD_H_AND_H #define HID_KEYBOARD_I HID_KEYBOARD_I_AND_I #define HID_KEYBOARD_J HID_KEYBOARD_J_AND_J #define HID_KEYBOARD_K HID_KEYBOARD_K_AND_K #define HID_KEYBOARD_L HID_KEYBOARD_L_AND_L #define HID_KEYBOARD_M HID_KEYBOARD_M_AND_M #define HID_KEYBOARD_N HID_KEYBOARD_N_AND_N #define HID_KEYBOARD_O HID_KEYBOARD_O_AND_O #define HID_KEYBOARD_P HID_KEYBOARD_P_AND_P #define HID_KEYBOARD_Q HID_KEYBOARD_Q_AND_Q #define HID_KEYBOARD_R HID_KEYBOARD_R_AND_R #define HID_KEYBOARD_S HID_KEYBOARD_S_AND_S #define HID_KEYBOARD_T HID_KEYBOARD_T_AND_T #define HID_KEYBOARD_U HID_KEYBOARD_U_AND_U #define HID_KEYBOARD_V HID_KEYBOARD_V_AND_V #define HID_KEYBOARD_W HID_KEYBOARD_W_AND_W #define HID_KEYBOARD_X HID_KEYBOARD_X_AND_X #define HID_KEYBOARD_Y HID_KEYBOARD_Y_AND_Y #define HID_KEYBOARD_Z HID_KEYBOARD_Z_AND_Z #define HID_KEYBOARD_BRACKET_RIGHT HID_KEYBOARD_RIGHT_BRACKET_AND_RIGHT_CURLY_BRACE #define HID_KEYBOARD_BRACKET_LEFT HID_KEYBOARD_LEFT_BRACKET_AND_LEFT_CURLY_BRACE #define HID_KEYBOARD_APOSTROPHE HID_KEYBOARD_QUOTE_AND_DOUBLEQUOTE #define HID_KEYBOARD_GRAVE HID_KEYBOARD_GRAVE_ACCENT_AND_TILDE #define HID_KEYBOARD_1 HID_KEYBOARD_1_AND_EXCLAMATION_POINT #define HID_KEYBOARD_2 HID_KEYBOARD_2_AND_AT #define HID_KEYBOARD_3 HID_KEYBOARD_3_AND_POUND #define HID_KEYBOARD_4 HID_KEYBOARD_4_AND_DOLLAR #define HID_KEYBOARD_5 HID_KEYBOARD_5_AND_PERCENT #define HID_KEYBOARD_6 HID_KEYBOARD_6_AND_CARAT #define HID_KEYBOARD_7 HID_KEYBOARD_7_AND_AMPERSAND #define HID_KEYBOARD_8 HID_KEYBOARD_8_AND_ASTERISK #define HID_KEYBOARD_9 HID_KEYBOARD_9_AND_LEFT_PAREN #define HID_KEYBOARD_0 HID_KEYBOARD_0_AND_RIGHT_PAREN #define KEYBOARD_MODIFIER_LEFTCTRL 1<<0 #define KEYBOARD_MODIFIER_LEFTSHIFT 1<<1 #define KEYBOARD_MODIFIER_LEFTALT 1<<2 #define KEYBOARD_MODIFIER_LEFTGUI 1<<3 #define KEYBOARD_MODIFIER_RIGHTCTRL 1<<4 #define KEYBOARD_MODIFIER_RIGHTSHIFT 1<<5 #define KEYBOARD_MODIFIER_RIGHTALT 1<<6 #define KEYBOARD_MODIFIER_RIGHTGUI 1<<7 #include "keymap.h" #include "keyscanner.h" void setup() { #if WAT Serial.begin(115200); #endif Keyboard.begin(); initKeyScanner(); resetKeyMatrix(); } void loop() { applyMatrix(); }
[ "wez@wezfurlong.org" ]
wez@wezfurlong.org
68e981b9a411f2c8f0ac4f035f9a0c3565fd2939
1af379b14252defebfe9ba55154770a021d040f9
/2019-02-26/mst/sol/soluzione.cpp
92eae3d6bdb892de0866ccca2ddac554f4c33ce6
[]
no_license
romeorizzi/esami-algo-TA
ee8cc12731963ae0d6b46a026b3ef8782539a73b
57af9679a95ee76c302cae1c5daf5cd9fbc9afd3
refs/heads/master
2020-06-24T14:39:03.361825
2019-08-02T07:22:02
2019-08-02T07:22:02
198,989,340
0
1
null
null
null
null
UTF-8
C++
false
false
1,858
cpp
/* Giovanni Campagna <scampa.giovanni@gmail.com> Minimum Spanning Tree - implementazione con Prim */ #include <cassert> #include <fstream> #include <iostream> #include <queue> #include <stack> #include <limits> using namespace std; const int N_MAX = 10000; const int M_MAX = 10000000; const int W_MAX = numeric_limits<int>::max(); int N, M; typedef vector<pair<int, int> > vicini_t; typedef vector<vicini_t> lista_vicini_t; lista_vicini_t lista_vicini; vector<bool> visto; int wsol; stack<pair<int, int> > soluzione; void prim() { priority_queue<pair<int, pair<int, int> > > coda; coda.push(make_pair(0, make_pair(0, -1))); while (!coda.empty()) { const pair<int, pair<int, int> >& e(coda.top()); int peso = -e.first; int nodo = e.second.first; int from = e.second.second; coda.pop(); if (visto[nodo]) continue; visto[nodo] = true; wsol += peso; if (from != -1) soluzione.push(make_pair(from, nodo)); const vicini_t& vicini(lista_vicini[nodo]); for (vicini_t::const_iterator i(vicini.begin()); i != vicini.end(); ++i) { int figlio = i->first; int peso = i->second; if (figlio != from && !visto[figlio]) coda.push(make_pair(-peso, make_pair(figlio, nodo))); } } } int mst(int N, int M, int A[], int B[], int P[], int C[], int D[]) { ::N = N; ::M = M; assert (N >= 1 && N <= N_MAX); assert (M >= 2 && M <= M_MAX); lista_vicini.resize(N); visto.resize(N, false); for (int i(0); i < M; i++) { lista_vicini[A[i]].push_back(make_pair(B[i], P[i])); lista_vicini[B[i]].push_back(make_pair(A[i], P[i])); } prim(); assert (wsol <= W_MAX); int x = 0; while(!soluzione.empty()) { const pair<int, int>& arco(soluzione.top()); C[x] = arco.first; D[x] = arco.second; x++; soluzione.pop(); } return wsol; }
[ "romeo.rizzi@univr.it" ]
romeo.rizzi@univr.it
adf939088cf0f26bf948517961815f7cacf9d66b
6ef71a3aa0535df7b2da99ea8c88fefae4730e15
/src/cloud/raystate.cpp
232196d004836d2a20b76993c2b309970775ded7
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
Arjun-Arora/pbrt-v3
8677f59600ec4bc7dba7aab4bbb72491f218def7
fbee19ca0e6f7611136ac61bc97865933e87ceb0
refs/heads/master
2020-08-08T07:19:04.598223
2019-10-08T01:05:31
2019-10-08T01:05:47
213,775,990
0
0
null
2019-10-08T23:28:44
2019-10-08T23:28:44
null
UTF-8
C++
false
false
2,089
cpp
#include "raystate.h" #include <lz4.h> #include <cstring> #include <limits> using namespace std; using namespace pbrt; template <typename T, typename U> constexpr int offset_of(T const &t, U T::*a) { return (char const *)&(t.*a) - (char const *)&t; } void RayState::StartTrace() { hit = false; toVisitPush({}); } uint32_t RayState::CurrentTreelet() const { if (!toVisitEmpty()) { return toVisitTop().treelet; } else if (hit) { return hitNode.treelet; } return 0; } void RayState::SetHit(const TreeletNode &node) { hit = true; hitNode = node; if (node.transformed) { memcpy(&hitTransform, &rayTransform, sizeof(Transform)); } } size_t RayState::Size() const { return offset_of(*this, &RayState::toVisit) + sizeof(RayState::TreeletNode) * toVisitHead; } /******************************************************************************* * SERIALIZATION * ******************************************************************************/ size_t RayState::Serialize(const bool compress) { const size_t size = this->Size(); uint32_t len = size; if (compress) { len = LZ4_compress_default(reinterpret_cast<char *>(this), serialized + 4, size, size); if (len == 0) { throw runtime_error("ray compression failed"); } } else { memcpy(serialized + 4, reinterpret_cast<char *>(this), size); } memcpy(serialized, &len, 4); serializedSize = len + 4; return serializedSize; } void RayState::Deserialize(const char *data, const size_t len, const bool decompress) { if (decompress) { if (LZ4_decompress_safe(data, reinterpret_cast<char *>(this), len, sizeof(RayState)) < 0) { throw runtime_error("ray decompression failed"); } } else { memcpy(reinterpret_cast<char *>(this), data, min(sizeof(RayState), len)); } }
[ "sfouladi@gmail.com" ]
sfouladi@gmail.com
37cb296b4f51ebd8fab4bf8cbb865562c6f45cec
62bf789f19f500aa5aa20f6911573cc0c59902c7
/smartag/include/alibabacloud/smartag/model/DeleteACLRuleResult.h
d56715a9d83e61affa36ee79107192af0b90b437
[ "Apache-2.0" ]
permissive
liuyuhua1984/aliyun-openapi-cpp-sdk
0288f0241812e4308975a62a23fdef2403cfd13a
600883d23a243eb204e39f15505f1f976df57929
refs/heads/master
2020-07-04T09:47:49.901987
2019-08-13T14:13:11
2019-08-13T14:13:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,373
h
/* * Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_SMARTAG_MODEL_DELETEACLRULERESULT_H_ #define ALIBABACLOUD_SMARTAG_MODEL_DELETEACLRULERESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/smartag/SmartagExport.h> namespace AlibabaCloud { namespace Smartag { namespace Model { class ALIBABACLOUD_SMARTAG_EXPORT DeleteACLRuleResult : public ServiceResult { public: DeleteACLRuleResult(); explicit DeleteACLRuleResult(const std::string &payload); ~DeleteACLRuleResult(); protected: void parse(const std::string &payload); private: }; } } } #endif // !ALIBABACLOUD_SMARTAG_MODEL_DELETEACLRULERESULT_H_
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
85b11d671217848c19f529c18ad1a46819b42712
f8d9b0a76c0b50dbe1bad4751ab09d4f821a2494
/UnrealFPS/Source/UnrealFPS/NPC/PatrolRoute.h
bf136967c1d987920ddb63b40089c0ef1f24fc9a
[]
no_license
gniewko248/UnrealFPS
c885d8db422744620873d0512c938b4b6b32bde9
5e3154b73273167d9b66d13402cdb66b26ebf624
refs/heads/master
2021-08-31T16:04:35.877918
2017-12-21T23:14:38
2017-12-21T23:14:38
113,897,335
0
0
null
null
null
null
UTF-8
C++
false
false
466
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "PatrolRoute.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class UNREALFPS_API UPatrolRoute : public UActorComponent { GENERATED_BODY() public: TArray<AActor*> GetPatrolPoints() const; private: UPROPERTY(EditInstanceOnly) TArray<AActor*> PatrolPoints_C; };
[ "gniewko248@gmail.com" ]
gniewko248@gmail.com
e61a9b6501a605b418969c697d51dd745c5e2901
c2067d667be0fb03ad8300649c19281bcc3b9ca2
/deps/fmt/fmt-5.2.0/test/custom-formatter-test.cc
88336cbe0c9678b7c5b87dd5d55ba4df0bb80149
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "Python-2.0", "Apache-2.0" ]
permissive
s-pace/profilo
2d0ae0699a597bfb2c701a36e65d0ab3e0d425eb
4a91b45eadb2da1f7fc8cefe8bc1cafb485eaaf8
refs/heads/master
2021-01-08T00:57:01.200059
2020-03-03T21:33:30
2020-03-03T21:36:57
241,867,468
0
0
Apache-2.0
2020-02-20T11:30:08
2020-02-20T11:30:07
null
UTF-8
C++
false
false
1,565
cc
// Formatting library for C++ - custom argument formatter tests // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include "fmt/format.h" #include "gtest-extra.h" // MSVC 2013 is known to be broken. #if !FMT_MSC_VER || FMT_MSC_VER > 1800 // A custom argument formatter that doesn't print `-` for floating-point values // rounded to 0. class custom_arg_formatter : public fmt::arg_formatter<fmt::back_insert_range<fmt::internal::buffer>> { public: typedef fmt::back_insert_range<fmt::internal::buffer> range; typedef fmt::arg_formatter<range> base; custom_arg_formatter( fmt::format_context &ctx, fmt::format_specs *s = FMT_NULL) : base(ctx, s) {} using base::operator(); iterator operator()(double value) { // Comparing a float to 0.0 is safe if (round(value * pow(10, spec()->precision())) == 0.0) value = 0; return base::operator()(value); } }; std::string custom_vformat(fmt::string_view format_str, fmt::format_args args) { fmt::memory_buffer buffer; // Pass custom argument formatter as a template arg to vwrite. fmt::vformat_to<custom_arg_formatter>(buffer, format_str, args); return std::string(buffer.data(), buffer.size()); } template <typename... Args> std::string custom_format(const char *format_str, const Args & ... args) { auto va = fmt::make_format_args(args...); return custom_vformat(format_str, va); } TEST(CustomFormatterTest, Format) { EXPECT_EQ("0.00", custom_format("{:.2f}", -.00001)); } #endif
[ "ricardorey@fb.com" ]
ricardorey@fb.com
09241baae288a8a30a104a6cd6eb6e59e418e1b0
d49b8536d996a81fd2a356f2ccd850abd4447217
/VirusPack/nzm-netapi/nzm-netapi/Test101-ms0640/cpp/modules/redirect.cpp
ee92ad4f733f28a9a46e02a02f6051b811a06b06
[]
no_license
JonnyBanana/botnets
28a90ab80f973478d54579f3d3eadc5feb33ff77
995b9c20aca5de0ae585ae17780a31e8bdfd9844
refs/heads/master
2021-07-01T01:51:01.211451
2020-10-22T23:14:57
2020-10-22T23:14:57
148,392,362
9
5
null
null
null
null
WINDOWS-1252
C++
false
false
4,577
cpp
#include "../../headers/includes.h" #include "../../headers/functions.h" #include "../../headers/externs.h" #ifndef NO_REDIRECT // port redirect function DWORD WINAPI RedirectThread(LPVOID param) { REDIRECT redirect = *((REDIRECT *)param); REDIRECT *redirectp = (REDIRECT *)param; redirectp->gotinfo = TRUE; char sendbuf[IRCLINE]; DWORD id; SOCKADDR_IN rsin, csin; memset(&rsin, 0, sizeof(rsin)); rsin.sin_family = AF_INET; rsin.sin_port = fhtons((unsigned short)redirect.lport); rsin.sin_addr.s_addr = INADDR_ANY; int csin_len = sizeof(csin); SOCKET rsock, csock; if ((rsock = fsocket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) != INVALID_SOCKET) { threads[redirect.threadnum].sock = rsock; fWSAAsyncSelect(rsock, 0, WM_USER + 1, FD_READ); if (fbind(rsock, (LPSOCKADDR)&rsin, sizeof(rsin)) == 0) { if (flisten(rsock, 10) == 0) { while(1) { if ((csock = faccept(rsock, (LPSOCKADDR)&csin, &csin_len)) != INVALID_SOCKET) { redirect.csock = csock; redirect.gotinfo = FALSE; sprintf(sendbuf,"s[I] (redirect.plg) »» Client connection from IP: %s:%d, Server thread: %d.", finet_ntoa(csin.sin_addr), csin.sin_port, redirect.threadnum); redirect.cthreadnum = addthread(sendbuf,REDIRECT_THREAD,csock); threads[redirect.cthreadnum].parent = redirect.threadnum; if (threads[redirect.cthreadnum].tHandle = CreateThread(NULL,0,&RedirectLoopThread,(LPVOID)&redirect,0,&id)) { while (redirect.gotinfo == FALSE) Sleep(50); } else { addlogv("s[I] (redirect.plg) »» Failed to start client thread, error: <%d>.", GetLastError()); break; } } } } } } fclosesocket(csock); fclosesocket(rsock); clearthread(redirect.threadnum); ExitThread(0); } // part of the redirect function, handles sending/recieving for the remote connection. DWORD WINAPI RedirectLoopThread(LPVOID param) { REDIRECT redirect = *((REDIRECT *)param); REDIRECT *redirectp = (REDIRECT *)param; redirectp->gotinfo = TRUE; int threadnum=redirect.cthreadnum; char sendbuf[IRCLINE], buff[4096]; int err; DWORD id; SOCKET ssock; do { if ((ssock = fsocket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) break; SOCKADDR_IN ssin; memset(&ssin, 0, sizeof(ssin)); ssin.sin_family = AF_INET; ssin.sin_port = fhtons((unsigned short)redirect.port); IN_ADDR iaddr; iaddr.s_addr = finet_addr(redirect.dest); LPHOSTENT hostent; if (iaddr.s_addr == INADDR_NONE) hostent = fgethostbyname(redirect.dest); else hostent = fgethostbyaddr((const char *)&iaddr, sizeof(iaddr), AF_INET); if (hostent == NULL) break; ssin.sin_addr = *((LPIN_ADDR)*hostent->h_addr_list); if ((err = fconnect(ssock, (LPSOCKADDR)&ssin, sizeof(ssin))) == SOCKET_ERROR) break; redirect.cgotinfo = FALSE; sprintf(sendbuf,"s[I] (redirect.plg) »» Client connection to IP: %s:%d, Server thread: %d.", finet_ntoa(ssin.sin_addr), ssin.sin_port, redirect.threadnum); redirect.cthreadnum = addthread(sendbuf,REDIRECT_THREAD,ssock); threads[redirect.cthreadnum].parent = redirect.threadnum; threads[redirect.cthreadnum].csock = threads[threadnum].sock; if (threads[redirect.cthreadnum].tHandle = CreateThread(NULL,0,&RedirectLoop2Thread,(LPVOID)&redirect,0,&id)) { while (redirect.cgotinfo == FALSE) Sleep(50); } else { addlogv("s[I] (redirect.plg) »» Failed to start connection thread, error: <%d>.", GetLastError()); break; } while (1) { memset(buff, 0, sizeof(buff)); if ((err = frecv(threads[threadnum].sock, buff, sizeof(buff), 0)) <= 0) break; if ((err = fsend(ssock, buff, err, 0)) == SOCKET_ERROR) break; } break; } while (1); fclosesocket(threads[threadnum].sock); fclosesocket(ssock); clearthread(threadnum); ExitThread(0); } // part of the redirect function, handles sending/recieving for the local connection. DWORD WINAPI RedirectLoop2Thread(LPVOID param) { REDIRECT redirect = *((REDIRECT *)param); REDIRECT *redirectp = (REDIRECT *)param; redirectp->cgotinfo = TRUE; int threadnum=redirect.cthreadnum, err; char buff[4096]; while (1) { memset(buff, 0, sizeof(buff)); if ((err = frecv(threads[threadnum].csock, buff, sizeof(buff), 0)) <= 0) break; if ((err = fsend(threads[threadnum].sock, buff, err, 0)) == SOCKET_ERROR) break; } fclosesocket(threads[threadnum].csock); clearthread(threadnum); ExitThread(0); } #endif
[ "mstr.be832920@gmail.com" ]
mstr.be832920@gmail.com
ed3626b73dcb76c480388224876f0c135351198f
ad8271700e52ec93bc62a6fa3ee52ef080e320f2
/CatalystRichPresence/CatalystSDK/PamCreatureLocoMotorComponentData.h
e71c40121423ee20c9e7aa26c04deb2ac0e9fa09
[]
no_license
RubberDuckShobe/CatalystRPC
6b0cd4482d514a8be3b992b55ec143273b3ada7b
92d0e2723e600d03c33f9f027c3980d0f087c6bf
refs/heads/master
2022-07-29T20:50:50.640653
2021-03-25T06:21:35
2021-03-25T06:21:35
351,097,185
2
0
null
null
null
null
UTF-8
C++
false
false
720
h
// // Generated with FrostbiteGen by Chod // File: SDK\PamCreatureLocoMotorComponentData.h // Created: Wed Mar 10 19:04:44 2021 // #ifndef FBGEN_PamCreatureLocoMotorComponentData_H #define FBGEN_PamCreatureLocoMotorComponentData_H #include "PamLocoBindings.h" #include "PamCreatureLocoBinding.h" #include "CreatureLocoMotorComponentData.h" class PamCreatureLocoMotorComponentData : public CreatureLocoMotorComponentData // size = 0x80 { public: static void* GetTypeInfo() { return (void*)0x000000014287CCC0; } PamLocoBindings* m_AdditionalAntBindings; // 0x80 PamCreatureLocoBinding m_PamCLAntBindings; // 0x88 unsigned char _0x9c[0x4]; }; // size = 0xa0 #endif // FBGEN_PamCreatureLocoMotorComponentData_H
[ "dog@dog.dog" ]
dog@dog.dog
5daa4701de03516f5c58ec7a13c4fdea13bb82c1
91ec6f5b701e52c7c4cf99b58bf7eb1077b05be2
/湖南省赛/acm湖南省省赛/2011年蓝狐杯湖南省第七届程序设计竞赛题目数据标程/sol/b.cpp
a6aa93ed7118a848f85185ab877e6d1007e1a4ed
[]
no_license
MuMuloveU/ACM_contest_problem
c71653f56db0bc30175da5ef06969b8cf557b4d5
d253935c3dcc856fa4d20a6ccfd6a36d8a41970b
refs/heads/master
2023-03-18T17:22:15.705604
2020-09-01T10:11:16
2020-09-01T10:11:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,102
cpp
#include <set> #include <map> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <cctype> #include <cstdio> #include <string> #include <vector> #include <cassert> #include <cstdlib> #include <cstring> #include <sstream> #include <iostream> #include <algorithm> using namespace std; bool isImp7( int i ) { if( !(i % 7) ) return true; while(i) { if( i % 10 == 7 ) return true; i /= 10; } return false; } int main() { double cl = clock(); int n, m, k; while( scanf("%d %d %d", &n, &m, &k) == 3 && n ) { int cnt = 0, period = 2 * n - 2; if( n == m || m == 1 ) { for( int i = m; ; i += period ) if( isImp7( i ) ) { cnt++; if( cnt == k ) { printf("%d\n", i); break; } } } else { int next = 2 - m; for( int i = m; ; swap( next, i ) ) { next += period; if( isImp7( i ) ) { cnt++; if( cnt == k ) { printf("%d\n", i); break; } } } } } cl = clock() - cl; fprintf(stderr, "Total Execution Time = %lf seconds\n", cl / CLOCKS_PER_SEC); return 0; }
[ "229781766@qq.com" ]
229781766@qq.com
e2af0d42203dda80ac2c39f2cfa84ea098fbf9cc
cdcb94426af4b4842aad35b487214f282ed457a0
/COM/models/modextcomexpr.h
2310767b8db264aea6e476da5c9666f073e2bdfb
[]
no_license
MEN-Mikro-Elektronik/13Y008-90
968898487c637b7cd26b7922b11adbc448d3a242
1877b1cc897c11e81b5526e68cdda4802240ba5e
refs/heads/master
2023-05-25T05:06:02.116975
2023-05-04T07:49:23
2023-05-04T07:49:23
143,159,201
0
0
null
2023-05-04T07:49:25
2018-08-01T13:22:53
C++
UTF-8
C++
false
false
1,287
h
/*************************************************************************** */ /*! \file modextcomexpr.h * \brief class for generic COM Express carrier board * \author dieter.pfeuffer@men.de * $Date: 2014/08/22 15:57:40 $ * $Revision: 2.2 $ * * Switches: - */ /*-------------------------------[ History ]--------------------------------- * * $Log: modextcomexpr.h,v $ * Revision 2.2 2014/08/22 15:57:40 dpfeuffer * R: inconsistent PC-MIP/PMC/PCI104/XMC and Chameleon usage * M: PC-MIP/PMC/PCI104/XMC and Chameleon usage completely revised * * Revision 2.1 2014/07/18 15:12:39 dpfeuffer * Initial Revision * *--------------------------------------------------------------------------- * (c) Copyright 2003-2014 by MEN Mikro Elektronik GmbH, Nuremberg, Germany ****************************************************************************/ #ifndef MODEXTCOMEXPR_H #define MODEXTCOMEXPR_H #include <Q3MemArray> #include "hwcomponent.h" #include "comexprcarrier.h" #include "wizexcept.h" #define MAX_PCIE_SLOTS 8 // PCIe slots 1..8 class ModExtComExpr : public ComExprCarrier { public: ModExtComExpr( bool withSubDevs ); Device *create(bool withSubDevs=true){ return new ModExtComExpr( withSubDevs ); } }; #endif
[ "thomas.schnuerer@men" ]
thomas.schnuerer@men
0ccd3ef3b4488e4eab73dfce2db7382a342bce8f
58a0ba5ee99ec7a0bba36748ba96a557eb798023
/GeeksForGeeks/DS/4. Stack/3.evaluation-postfix-expression.cpp
843c71f3b5ebe7e3eb23e74baa71a77c5659f3a6
[ "MIT" ]
permissive
adityanjr/code-DS-ALGO
5bdd503fb5f70d459c8e9b8e58690f9da159dd53
1c104c33d2f56fe671d586b702528a559925f875
refs/heads/master
2022-10-22T21:22:09.640237
2022-10-18T15:38:46
2022-10-18T15:38:46
217,567,198
40
54
MIT
2022-10-18T15:38:47
2019-10-25T15:50:28
C++
UTF-8
C++
false
false
812
cpp
// http://geeksquiz.com/stack-set-4-evaluation-postfix-expression/ #include <iostream> #include <stack> #include <cmath> #include <string> using namespace std; bool isInt(char ch){ return (ch >= '0' && ch <= '9'); } int eval(int a, int b, char op){ if(op == '+') return a+b; else if(op == '-') return a-b; else if(op == '*') return a*b; else if(op == '/') return a/b; else if(op == '^') return pow(a, b); } int evaluatePostfix(char *exp){ stack<int> s; char zero = '0'; int i=0; for(; exp[i]; i++){ if(isInt(exp[i])){ s.push(int(exp[i])-zero); } else { int b = s.top(); s.pop(); int a = s.top(); s.pop(); s.push(eval(a, b, exp[i])); } } return s.top(); } int main(){ char exp[] = "231*+9-"; printf ("Value of %s is %d", exp, evaluatePostfix(exp)); return 0; }
[ "samant04aditya@gmail.com" ]
samant04aditya@gmail.com