blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
41411ede81a3f14d5f5efda3aad396093d6910f8 | 16337b0d88df96767281cbc0024ed4e5e0dc2309 | /Tic-Tac-bigToe.cpp | ccd6f979a725f324386a94cc966771516cbbf2ac | [] | no_license | Xephoney/Tic-Tac-bigToe | 8c3c5d93a5f49799d90034a428a61d509b672883 | 3ea53e4f72486c476eb673a8f1736b24f3f5442c | refs/heads/master | 2022-12-24T15:47:03.404365 | 2020-09-27T19:22:51 | 2020-09-27T19:22:51 | 298,370,665 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 12,368 | cpp | #include <iostream>
#include <string>
#include <vector> //This is included for the use of vectors
#include <time.h> //This is for random number generation
//Here we declare the functions that i will define further down.
//these functions are tied to the gameplay loop
void DisplayGrid();
void InputAndExec();
void PlayerSwitch();
int WinConditionCheck();
void CalculateComputerMove(char);
//These are the main functions between games.
void GamePvP();
void GamePvE();
void MainMenu();
//The reason i went with global variables was to limit the amount of calls, and passing variables to functions and getting...
//the right return variables. Only the important variables are global.
std::vector<char> grid { '1','2','3','4','5','6','7','8','9' };
char players[2] { 'X', 'O' };
int playerIndex = 1;
int main()
{
srand(time(NULL));
//Greeting when first running the application
std::cout << "Welcome to Tic-Tac-(Big)Toe \n";
MainMenu();
return 0;
}
void MainMenu()
{
int answer = NULL;
std::cout << "What would you like to play? \n";
std::cout << " 1 : Player VS Player \n" << " 2 : Player VS CPU \n \n" << " 8 : Exit Game \n";
std::cout << "Select a gamemode : ";
std::cin >> answer;
//here we do the corresponding code execution based on what the user typed in.
// I wanted to avoid using a while loop here, because of the thought that it would be a loop, in a loop, in a loop... for ever.
// So instead i just kept to Functions executions.
// I don't know for sure whether this is the best solution or not, but it works! :D
//Here i get then input from the player and execute the right code that was selected from the player.
switch (answer)
{
case 0:
//I have to include cin.clear and cin.ignore before calling MainMenu() again, to stop it from looping forever.
system("CLS");
std::cin.clear();
std::cin.ignore(10000, '\n');
MainMenu();
break;
case 1:
system("CLS");
GamePvP();
break;
case 2:
system("CLS");
GamePvE();
break;
case 8:
std::cout << "Closing Game";
return;
default:
//I have to include cin.clear and cin.ignore before calling MainMenu() again, to stop it from looping forever.
system("CLS");
std::cin.clear();
std::cin.ignore(10000, '\n');
MainMenu();
break;
}
}
int moves = 0;
void GamePvP()
{
playerIndex = 0;
bool GameOver = false;
moves = 0;
//The reason why i fill out the grid here, is because everytime the game restarts...
//I need to make sure its a new grid. so it clears the board from the last game.
grid = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
do
{
//as the functions says it displays the grid.
DisplayGrid();
//This is for getting input, aswell as
InputAndExec();
//Here i run the Win Condition function and store the result of that test in my X variable.
//Then we proceed to check weather that the winner was either X or O.
int x = WinConditionCheck();
if (x == 0 || x == 1)
{
//The reason for Display Grid is just to update the display so you could see where the
//Where the winning connections were!
DisplayGrid();
std::cout << "\nPlayer " << players[x] << " wins! Congrats! \n";
GameOver = true;
system("pause");
}
//I keep a count of the total amount of moves. and if the total number of moves is 9, and wincheck returns false. then it has to be a tie.
else if (moves == 9)
{
//Tie
DisplayGrid();
std::cout << "\n [- TIE -] \n";
GameOver = true;
system("pause");
}
} while (!GameOver);
//Clears screen and returns to Main Menu
system("CLS");
MainMenu();
}
void GamePvE()
{
playerIndex = 0;
bool GameOver = false;
moves = 0;
grid = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char answer = 'æ';
int computer = -1;
int player = -1;
std::cout << "Do you want to be X or O? \n ";
std::cout << "X / O : ";
std::cin >> answer;
answer = toupper(answer);
//This is just to make sure that the input is a Char value.
//Initial game setup. The player selects their desigered and the cpu gets
if (answer == players[0])
{
computer = 1;
player = 0;
std::cout << "Okay, You = X CPU = O \n When you are ready ";
}
else if (answer == players[1])
{
computer = 0;
player = 1;
std::cout << "Okay, CPU = X You = O \n When you are ready ";
}
else //This is just to remove the possibility of a rogue exec without the right variables.
{
std::cin.clear();
std::cin.ignore(10000, '\n');
GamePvE();
return;
}
system("pause");
//This do-while loop goes aslong as GameOver is false.
do
{
DisplayGrid();
if (playerIndex == computer)
{
//this just ends up passing through what character the computer has.
//So it can do the right placement in the grid.
CalculateComputerMove(players[computer]);
}
else
{
InputAndExec();
}
//This is the section of the gameloop that checks for wins or if the game is a tie.
int x = WinConditionCheck();
if (x == computer)
{
//The reason for Display Grid is just to update the display so you could see where the
//Where the winning connections were!
DisplayGrid();
std::cout << "\n [- CPU WON -] ";
GameOver = true;
system("pause");
}
else if (x == player)
{
DisplayGrid();
std::cout << "\n [- YOU WON -] ";
GameOver = true;
system("pause");
}
else if (moves == 9)
{
DisplayGrid();
std::cout << "\n [- TIE -] \n";
GameOver = true;
system("pause");
}
} while (!GameOver);
system("CLS");
MainMenu();
}
//Game Loop functions
void DisplayGrid()
{
system("CLS");
for (auto x = 0; x < grid.size(); x++)
{
std::cout << "| " << grid.at(x) << " ";
if (x == 2 || x == 5 || x == 8)
{
std::cout << "|" << std::endl;
}
}
}
void InputAndExec()
{
//The reason for this being a long long int, is because i kept getting build errors because i was doing a arithmetic overflow warning
//So i then "upgraded" to this to remove that error.
long long int playerInput = 0;
std::cout << "[" << players[playerIndex] << "] turn : ";
//Gets input from console and store the answer in the playerInput variable
std::cin >> playerInput;
if (playerInput-1 <= 8 && playerInput-1 >= 0)
{
if (grid.at(playerInput-1) == 'X' || grid.at(playerInput-1) == 'O')
{
std::cout << "Invalid selection, you cannot select a place that has already been taken! \n";
InputAndExec();
return;
}
else
{
grid[playerInput-1] = players[playerIndex];
moves++;
PlayerSwitch();
return;
}
}
else // This else is to catch any input that isn't an integer. then repeat.
{
std::cin.clear();
std::cin.ignore(10000, '\n');
std::cout << "Invalid input! Choose a number from the grid above! \n";
}
}
int WinConditionCheck()
{
//Here im just creating a variable that checks for winner, and then returns the player index number...
//which corresponds with a char in players[].
char winner = 'Ø';
char a, b, c;
//Horizontal
for (long int i = 1; i <= 7; i+=3)
{
// These variables are temp just for storing values so the if statement further down stays relativly clean and easy to debug.
a = grid.at(i);
b = grid.at(i-1);
c = grid.at(i+1);
//What these variables check store is what is in the grid at the spesific point. They only hold that info based on the current iteration.
//This if statement then checks weather or not they are all the same, it doesn't matter if its X or O. Aslong as all of them are the same...
//it then continues to the next check
if (a == b && b == c)
{
//Here we grab the character value of the winning row, then we do a check as to who won. then return a int value.
//This int value that is returned, corresponds with the index of the players[], where X = 0, and O = 1.
winner = grid.at(i);
if (winner == 'X')
{
return 0;
}
else
{
return 1;
}
}
}
//Vertical win check
for (long int i = 0; i < 3; i++)
{
//Here i grab a the current iterator and add the required grid locations to make a check.
//im just using a, b and c because it really doesn't require to be that spesific. These are temp variables that...
//have a single purpose, which is to check weather or not they are the same.
a = grid.at(i);
b = grid.at(i + 3);
c = grid.at(i + 6);
//This if statement just checks that all the temp variables are the same, and by that we can determine that we have a winner.
//Since the temp varibles are set to check the one beneath another, this then checks the colum for a win condition.
if (a == b && b == c)
{
//Here we grab the character value of the winning row, then we do a check as to who won. then return a int value.
//This int value that is returned, corresponds with the index of the players[], where X = 0, and O = 1.
winner = grid.at(i);
if (winner == 'X')
{
return 0;
}
else
{
return 1;
}
}
}
//For the diagonal checks, all i have to do, since there are only two options. i will hardcode those checks.
//The reason for that is because of time, i could most likly come up with a clever solution, however it would end up taking way longer..
//Than simply writing it out. This is only Tic-Tac-Toe.
#pragma region DiagonalChecks
//Diagonal Check 1
a = grid.at(2);
b = grid.at(4);
c = grid.at(6);
std::cout << a << b << c;
if (a == b && b == c)
{
//Same as before, we grab the variable at a this time, and return the correct index in players[].
winner = b;
if (winner == 'X')
{
return 0;
}
else
{
return 1;
}
}
//Diagonal Check 2
a = grid.at(0);
b = grid.at(4);
c = grid.at(8);
if (a == b && b == c)
{
//Same as before, we grab the variable at a this time, and return the correct index in players[].
winner = b;
if (winner == 'X')
{
return 0;
}
else
{
return 1;
}
}
#pragma endregion
return 2;
}
void PlayerSwitch()
{
//This function just inverts the player index. I think there is a better and prettier way to do this, however this will do for now.
//Its not pretty, but i added an easter-egg incase something went horribly wrong!
switch (playerIndex)
{
case 0 :
playerIndex = 1;
break;
case 1 :
playerIndex = 0;
break;
default:
std::cout << "WTF just happened, im just gonna try something\n";
playerIndex = 0;
break;
}
}
void CalculateComputerMove(char CPUchar)
{
//Just initializing a seed(time) for my random number generator.
int selected = (rand() % 8 + 1)-1;
if (grid.at(selected) == 'X' || grid.at(selected) == 'O')
{
CalculateComputerMove(CPUchar);
return;
}
else
{
grid.at(selected) = CPUchar;
moves++;
PlayerSwitch();
return;
}
} | [
"[email protected]"
] | |
7ade5627a226f91a37d1e00ba158ba1f1eace614 | 6a56f4e8bfa2da98cfc51a883b7cae01736c3046 | /ovaldi-code-r1804-trunk/src/probes/unix/PasswordProbe.h | 03062e89f9d72a9942bd7a1aac071a565a9a4ae6 | [] | no_license | tmcclain-taptech/Ovaldi-Win10 | 6b11e495c8d37fd73aae6c0281287cadbc491e59 | 7214d742c66f3df808d70e880ba9dad69cea403d | refs/heads/master | 2021-07-07T09:36:30.776260 | 2019-03-28T19:11:29 | 2019-03-28T19:11:29 | 164,451,763 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,857 | h | //
//
//****************************************************************************************//
// Copyright (c) 2002-2014, The MITRE Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
// * Neither the name of The MITRE Corporation 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 PASSWORDPROBE_H
#define PASSWORDPROBE_H
#include "AbsProbe.h"
#include "Item.h"
#include "Object.h"
#include <pwd.h>
#include <string>
/**
This class is responsible for collecting information about unix password_objects.
*/
class PasswordProbe : public AbsProbe {
public:
virtual ~PasswordProbe();
/** Get all the files on the system that match the pattern and collect their attributes. */
virtual ItemVector* CollectItems(Object* object);
/** Return a new Item created for storing file information */
virtual Item* CreateItem();
/** Ensure that the PasswordProbe is a singleton. */
static AbsProbe* Instance();
private:
PasswordProbe();
/** Creates an item from a passwd struct */
Item *CreateItemFromPasswd(struct passwd const *pwInfo);
/** Finds a single item by name. */
Item *GetSingleItem(const std::string& username);
/** Finds multiple items according to the given object entity. */
ItemVector *GetMultipleItems(Object *passwordObject);
/** Singleton instance */
static PasswordProbe* instance;
};
#endif
| [
"[email protected]"
] | |
8bfe178d65efb2f52470e306b87737b39f700ce6 | f80d267d410b784458e61e4c4603605de368de9b | /TESTONE/exampleios/usr/local/include/fit_developer_field_description.hpp | a5af5c51d16055664f81433af69b821385dd83c5 | [] | no_license | bleeckerj/Xcode-FIT-TEST | 84bdb9e1969a93a6380a9c64dce0a0e715d81fe8 | 37490e3b1e913dc3dfabdae39b48bddea24f1023 | refs/heads/master | 2021-01-20T14:39:53.249495 | 2017-02-22T05:59:28 | 2017-02-22T05:59:28 | 82,766,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,772 | hpp | ////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2017 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 20.24Release
// Tag = production/akw/20.24.01-0-g5fa480b
////////////////////////////////////////////////////////////////////////////////
#if !defined(FIT_DEVELOPER_FIELD_DESCRIPTION_HPP)
#define FIT_DEVELOPER_FIELD_DESCRIPTION_HPP
#include "fit_field_description_mesg.hpp"
#include "fit_developer_data_id_mesg.hpp"
#include <vector>
namespace fit
{
class DeveloperFieldDescription
{
public:
DeveloperFieldDescription() = delete;
DeveloperFieldDescription(const DeveloperFieldDescription& other);
DeveloperFieldDescription(const FieldDescriptionMesg& desc, const DeveloperDataIdMesg& developer);
virtual ~DeveloperFieldDescription();
FIT_UINT32 GetApplicationVersion() const;
FIT_UINT8 GetFieldDefinitionNumber() const;
std::vector<FIT_UINT8> GetApplicationId() const;
private:
FieldDescriptionMesg* description;
DeveloperDataIdMesg* developer;
};
} // namespace fit
#endif // defined(FIT_FIELD_DEFINITION_HPP)
| [
"[email protected]"
] | |
06c1ab5ff8ab138987ba9ad1ed0f423d945bafe7 | 6817617489ef291d4d53ac844ba7a2b14cc17ae2 | /11942.cpp | dcc6c32bd3395a76801df96fb6b8693215e020ec | [] | no_license | Asad51/UVA-Problem-Solving | 1932f2cd73261cd702f58d4f189a4a134dbd6286 | af28ae36a2074d4e2a67670dbbbd507438c56c3e | refs/heads/master | 2020-03-23T14:52:49.420143 | 2019-10-24T17:03:37 | 2019-10-24T17:03:37 | 120,592,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int t;
cin>>t;
cout<<"Lumberjacks:\n";
while(t--){
bool in = true;
bool dec = true;
int p;
for(int i=0; i<10; i++){
int n;
cin>>n;
if(!i){
p = n;
continue;
}
if(n<p || !in)
in = false;
if(n>p || !dec)
dec = false;
p = n;
}
if(!in && !dec)
cout<<"Unordered\n";
else
cout<<"Ordered\n";
}
return 0;
}
| [
"[email protected]"
] | |
77e95d74adb0d91068d318a9f567bd723eb4bd30 | 8a970882a0be9f3d85edbf6ecec0050b762e8d80 | /GazEngine/gazengine/Entity.h | ded187d2149547f453fc7c141f5bfa9b3cc59aa9 | [] | no_license | simplegsb/gazengine | 472d1de8d300c8406ffec148844911fd21d5c1e0 | b0a7300aa535b14494789fb88c16d6dda1c4e622 | refs/heads/master | 2016-09-05T21:02:49.531802 | 2013-04-29T08:33:16 | 2013-04-29T08:33:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,553 | h | #ifndef ENTITY_H_
#define ENTITY_H_
#include <memory>
#include <string>
#include <vector>
class Component;
class Entity
{
public:
static const unsigned short UNCATEGORIZED = 0;
Entity(unsigned short category = UNCATEGORIZED, const std::string& name = std::string());
virtual ~Entity();
/**
* <p>
* Adds a component.
* </p>
*
* @param component The component to add.
*/
void addComponent(Component* component);
unsigned short getCategory() const;
/**
* <p>
* Retrieves the components.
* </p>
*
* @return The components.
*/
template<typename ComponentType>
std::vector<ComponentType*> getComponents() const;
unsigned int getId() const;
/**
* <p>
* Retrieves the name of this <code>Entity</code>.
* </p>
*
* @return The name of this <code>Entity</code>.
*/
const std::string& getName() const;
/**
* <p>
* Retrieves a single component.
* </p>
*
* @return The single component.
*/
template<typename ComponentType>
ComponentType* getSingleComponent() const;
/**
* <p>
* Removes a component.
* </p>
*
* @param component The component to remove.
*/
void removeComponent(const Component& component);
private:
unsigned short category;
/**
* <p>
* The components.
* </p>
*/
std::vector<Component*> components;
unsigned int id;
/**
* <p>
* The name of this <code>Entity</code>.
* </p>
*/
std::string name;
static unsigned int nextId;
};
#include "Entity.tpp"
#endif /* ENTITY_H_ */
| [
"[email protected]"
] | |
f974d4af50705dd6f63c51d6d7a1ee1c85bf7cd3 | 414c6adb394c3c7ef4b80ab9b62cfc238ff726e2 | /tutorial/spinny/main.cc | 39f9f8736922a4b8a41c9e0c1c9d1bf851f0a4b6 | [] | no_license | akeley98/vkme | 68ca6db6c246fe8b4a25a3fb0982ff2552d8ef9b | 1b8e7df2a8290a0cc7bd97bf82c88a6eeff40be1 | refs/heads/master | 2022-12-23T19:53:47.583138 | 2020-09-29T05:34:32 | 2020-09-29T05:34:32 | 291,925,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,670 | cc | #include "window.hh"
#include "render.hh"
#include "util.hh"
using namespace myricube;
// Absolute path of the executable, minus the -bin or .exe, plus -data/
// This is where shaders and stuff are stored.
std::string data_directory;
std::string expand_filename(const std::string& in)
{
if (data_directory.size() == 0) {
throw std::logic_error("Cannot call expand_filename before main");
}
return in[0] == '/' ? in : data_directory + in;
}
bool ends_with_bin_or_exe(const std::string& in)
{
auto sz = in.size();
if (sz < 4) return false;
const char* suffix = &in[sz - 4];
return strcmp(suffix, "-bin") == 0 or strcmp(suffix, ".exe") == 0;
}
bool paused = false;
int target_fragments = 0;
void add_key_targets(Window& window, Camera& camera)
{
static float speed = 8.0f;
static float sprint_mod = 1.0f;
struct Position
{
glm::dvec3 eye = glm::dvec3(0);
float theta = 1.5707f;
float phi = 1.5707f;
};
static Position old_positions_ring_buffer[256];
static Position future_positions_ring_buffer[256];
static uint8_t old_idx = 0;
static uint8_t future_idx = 0;
static auto get_camera_position = [&camera] () -> Position
{
Position p;
p.eye = camera.get_eye();
p.theta = camera.get_theta();
p.phi = camera.get_phi();
return p;
};
static auto push_camera_position = [&]
{
old_positions_ring_buffer[--old_idx] = get_camera_position();
};
static auto push_camera_position_callback = [&] (KeyArg arg)
{
if (arg.repeat) return false;
push_camera_position();
return true;
};
KeyTarget pop_old_camera, pop_future_camera;
pop_old_camera.down = [&] (KeyArg) -> bool
{
future_positions_ring_buffer[--future_idx] =
get_camera_position();
Position p = old_positions_ring_buffer[old_idx++];
camera.set_eye(p.eye);
camera.set_theta(p.theta);
camera.set_phi(p.phi);
return true;
};
pop_future_camera.down = [&] (KeyArg) -> bool
{
old_positions_ring_buffer[--old_idx] =
get_camera_position();
Position p = future_positions_ring_buffer[future_idx++];
camera.set_eye(p.eye);
camera.set_theta(p.theta);
camera.set_phi(p.phi);
return true;
};
window.add_key_target("pop_old_camera", pop_old_camera);
window.add_key_target("pop_future_camera", pop_future_camera);
KeyTarget forward, backward, leftward, rightward, upward, downward;
forward.down = push_camera_position_callback;
forward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(0, 0, +arg.dt * speed * sprint_mod);
return true;
};
backward.down = push_camera_position_callback;
backward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(0, 0, -arg.dt * speed * sprint_mod);
return true;
};
leftward.down = push_camera_position_callback;
leftward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(-arg.dt * speed * sprint_mod, 0, 0);
return true;
};
rightward.down = push_camera_position_callback;
rightward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(+arg.dt * speed * sprint_mod, 0, 0);
return true;
};
upward.down = push_camera_position_callback;
upward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(0, +arg.dt * speed * sprint_mod, 0);
return true;
};
downward.down = push_camera_position_callback;
downward.per_frame = [&] (KeyArg arg) -> bool
{
camera.frenet_move(0, -arg.dt * speed * sprint_mod, 0);
return true;
};
window.add_key_target("forward", forward);
window.add_key_target("backward", backward);
window.add_key_target("leftward", leftward);
window.add_key_target("rightward", rightward);
window.add_key_target("upward", upward);
window.add_key_target("downward", downward);
KeyTarget sprint, speed_up, slow_down;
sprint.down = [&] (KeyArg) -> bool
{
sprint_mod = 7.0f;
return true;
};
sprint.up = [&] (KeyArg) -> bool
{
sprint_mod = 1.0f;
return true;
};
speed_up.down = [&] (KeyArg arg) -> bool
{
if (!arg.repeat) speed *= 2.0f;
return !arg.repeat;
};
slow_down.down = [&] (KeyArg arg) -> bool
{
if (!arg.repeat) speed *= 0.5f;
return !arg.repeat;
};
window.add_key_target("sprint", sprint);
window.add_key_target("speed_up", speed_up);
window.add_key_target("slow_down", slow_down);
KeyTarget vertical_scroll, horizontal_scroll, look_around;
look_around.down = push_camera_position_callback;
look_around.per_frame = [&] (KeyArg arg) -> bool
{
camera.inc_theta(arg.mouse_rel_x * arg.dt * 0.01f);
camera.inc_phi(arg.mouse_rel_y * arg.dt * 0.01f);
return true;
};
vertical_scroll.down = [&] (KeyArg arg) -> bool
{
camera.inc_phi(arg.amount * -0.05f);
return true;
};
horizontal_scroll.down = [&] (KeyArg arg) -> bool
{
camera.inc_theta(arg.amount * -0.05f);
return true;
};
window.add_key_target("look_around", look_around);
window.add_key_target("vertical_scroll", vertical_scroll);
window.add_key_target("horizontal_scroll", horizontal_scroll);
}
// Given the full path of a key binds file, parse it for key bindings
// and add it to the window's database of key bindings (physical
// key/mouse button to KeyTarget name associations).
//
// Syntax: the file should consist of lines of pairs of key names and
// KeyTarget names. Blank (all whitespace) lines are allowed as well
// as comments, which go from a # character to the end of the line.
//
// Returns true iff successful (check errno on false).
bool add_key_binds_from_file(Window& window, std::string filename) noexcept
{
FILE* file = fopen(filename.c_str(), "r");
if (file == nullptr) {
fprintf(stderr, "Could not open %s\n", filename.c_str());
return false;
}
int line_number = 0;
auto skip_whitespace = [file]
{
int c;
while (1) {
c = fgetc(file);
if (c == EOF) return;
if (c == '\n' or !isspace(c)) {
ungetc(c, file);
return;
}
}
};
errno = 0;
bool eof = false;
while (!eof) {
std::string key_name;
std::string target_name;
++line_number;
int c;
skip_whitespace();
// Parse key name (not case sensitive -- converted to lower case)
while (1) {
c = fgetc(file);
if (c == EOF) {
if (errno != 0 and errno != EAGAIN) goto bad_eof;
eof = true;
goto end_line;
}
if (c == '\n') goto end_line;
if (isspace(c)) break;
if (c == '#') goto comment;
key_name.push_back(c);
}
skip_whitespace();
// Parse target name (case sensitive)
while (1) {
c = fgetc(file);
if (c == EOF) {
if (errno != 0 and errno != EAGAIN) goto bad_eof;
eof = true;
goto end_line;
}
if (c == '\n') goto end_line;
if (isspace(c)) break;
if (c == '#') goto comment;
target_name.push_back(c);
}
skip_whitespace();
// Check for unexpected cruft at end of line.
c = fgetc(file);
if (c == EOF) {
if (errno != 0 and errno != EAGAIN) goto bad_eof;
eof = true;
goto end_line;
}
else if (c == '#') {
goto comment;
}
else if (c == '\n') {
goto end_line;
}
else {
fprintf(stderr, "%s:%i unexpected third token"
" starting with '%c'\n",
filename.c_str(), line_number, c);
errno = EINVAL;
goto bad_eof;
}
// Skip over comment characters from # to \n
comment:
while (1) {
c = fgetc(file);
if (c == EOF) {
if (errno != 0 and errno != EAGAIN) goto bad_eof;
eof = true;
goto end_line;
}
if (c == '\n') {
break;
}
}
end_line:
// skip blank lines silently.
if (key_name.size() == 0) continue;
// Complain if only one token is provided on a line.
if (target_name.size() == 0) {
fprintf(stderr, "%s:%i key name without target name.\n",
filename.c_str(), line_number);
errno = EINVAL;
goto bad_eof;
}
auto keycode = keycode_from_name(key_name);
if (keycode == 0) {
fprintf(stderr, "%s:%i unknown key name %s.\n",
filename.c_str(), line_number, key_name.c_str());
errno = EINVAL;
goto bad_eof;
}
fprintf(stderr, "Binding %s (%i) to %s\n",
key_name.c_str(), keycode, target_name.c_str());
window.bind_keycode(keycode, target_name);
}
if (fclose(file) != 0) {
fprintf(stderr, "Error closing %s\n", filename.c_str());
return false;
}
return true;
bad_eof:
fprintf(stderr, "Warning: unexpected end of parsing.\n");
int eof_errno = errno;
fclose(file);
errno = eof_errno;
return true; // I'm getting bogus EOF fails all the time so fake success :/
}
void bind_keys(Window& window)
{
auto default_file = expand_filename("default-keybinds.txt");
auto user_file = expand_filename("keybinds.txt");
bool default_okay = add_key_binds_from_file(window, default_file);
if (!default_okay) {
fprintf(stderr, "Failed to parse %s\n", default_file.c_str());
fprintf(stderr, "%s (%i)\n", strerror(errno), errno);
exit(2);
}
bool user_okay = add_key_binds_from_file(window, user_file);
if (!user_okay) {
if (errno == ENOENT) {
fprintf(stderr, "Custom keybinds file %s not found.\n",
user_file.c_str());
}
else {
fprintf(stderr, "Failed to parse %s\n", user_file.c_str());
fprintf(stderr, "%s (%i)\n", strerror(errno), errno);
exit(2);
}
}
}
int main(int argc, char** argv)
{
// Data directory (where shaders are stored) is the path of this
// executable, with the -bin or .exe file extension replaced with
// -data. Construct that directory name here.
data_directory = argv[0];
if (!ends_with_bin_or_exe(data_directory)) {
fprintf(stderr, "%s should end with '-bin' or '.exe'\n",
data_directory.c_str());
return 1;
}
for (int i = 0; i < 4; ++i) data_directory.pop_back();
data_directory += "-data/";
// Instantiate the camera.
Camera camera;
// Create a window; callback ensures these window dimensions stay accurate.
int screen_x = 0, screen_y = 0;
auto on_window_resize = [&camera, &screen_x, &screen_y] (int x, int y)
{
camera.set_window_size(x, y);
screen_x = x;
screen_y = y;
};
Window window(on_window_resize);
Renderer* renderer = new_renderer(window);
add_key_targets(window, camera);
bind_keys(window);
while (window.frame_update()) draw_frame(renderer, camera);
delete_renderer(renderer);
}
| [
"[email protected]"
] | |
95534aae2f06adbc3b44e859658780f8bf0cf800 | 3f9081b23333e414fb82ccb970e15b8e74072c54 | /bs2k/behaviors/skills/oneortwo_step_kick_bms.h | e7f968c14d8092e86a4e41ed23b6e7ac3a2558ab | [] | no_license | rc2dcc/Brainstormers05PublicRelease | 5c8da63ac4dd3b84985bdf791a4e5580bbf0ba59 | 2141093960fad33bf2b3186d6364c08197e9fe8e | refs/heads/master | 2020-03-22T07:32:36.757350 | 2018-07-04T18:28:32 | 2018-07-04T18:28:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,945 | h | /*
Brainstormers 2D (Soccer Simulation League 2D)
PUBLIC SOURCE CODE RELEASE 2005
Copyright (C) 1998-2005 Neuroinformatics Group,
University of Osnabrueck, Germany
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _ONEORTWO_STEP_KICK_BMS_H_
#define _ONEORTWO_STEP_KICK_BMS_H_
/* This behavior is a port of Move_1or2_Step_Kick into the behavior
framework. get_cmd will try to kick in one step and otherwise return
a cmd that will start a two-step kick. There are some functions
that return information about the reachable velocities and the needed
steps, so that you can prepare in your code for what this behavior will
do.
This behavior usually takes the current player position as reference point,
but you can override this by calling set_state() prior to any other function.
This makes it possible to "fake" the player's position during the current cycle.
Use reset_state to re-read the WS information, or wait until the next cycle.
Note that kick_to_pos_with_final_vel() is rather unprecise concerning the
final velocity of the ball. I don't know how to calculate the needed starting
vel precisely, so I have taken the formula from the original Neuro_Kick2 move
(which was even more unprecise...) and tweaked it a bit, but it is still
not perfect.
Note also that this behavior, as opposed to the original move, has a working
collision check - the original move ignored the player's vel...
(w) 2002 Manuel Nickschas
*/
#include "../base_bm.h"
#include "one_step_kick_bms.h"
#include "angle.h"
#include "Vector.h"
#include "tools.h"
#include "cmd.h"
#include "n++.h"
#include "macro_msg.h"
#include "valueparser.h"
#include "options.h"
#include "ws_info.h"
#include "log_macros.h"
#include "mystate.h"
#include "../../policy/abstract_mdp.h"
class OneOrTwoStepKickItrActions {
static const Value kick_pwr_min = 20;
static const Value kick_pwr_inc = 10;
static const Value kick_pwr_max = 100;
static const Value kick_ang_min = 0;
static const Value kick_ang_inc = 2*PI/8.;
// static const Value kick_ang_inc = 2*PI/36.; // ridi: I think it should be as much! too much
static const Value kick_ang_max = 2*PI-kick_ang_inc;
static const Value dash_pwr_min = 20;
static const Value dash_pwr_inc = 20;
static const Value dash_pwr_max = 100;
static const Value turn_ang_min = 0;
static const Value turn_ang_inc = 2*PI/18.;
// static const Value turn_ang_max = 2*PI-turn_ang_inc;
static const Value turn_ang_max = 0; // ridi: do not allow turns
static const Value kick_pwr_steps = (kick_pwr_max-kick_pwr_min)/kick_pwr_inc + 1;
static const Value dash_pwr_steps = (dash_pwr_max-dash_pwr_min)/dash_pwr_inc + 1;
static const Value turn_ang_steps = (turn_ang_max-turn_ang_min)/turn_ang_inc + 1;
static const Value kick_ang_steps = (kick_ang_max-kick_ang_min)/kick_ang_inc + 1;
Cmd_Main action;
Value kick_pwr,dash_pwr;
ANGLE kick_ang,turn_ang;
int kick_pwr_done,kick_ang_done,dash_pwr_done,turn_ang_done;
public:
void reset() {
kick_pwr_done=0;kick_ang_done=0;dash_pwr_done=0;turn_ang_done=0;
kick_pwr=kick_pwr_min;kick_ang= ANGLE(kick_ang_min);dash_pwr=dash_pwr_min;
turn_ang=ANGLE(turn_ang_min);
}
Cmd_Main *next() {
if(kick_pwr_done<kick_pwr_steps && kick_ang_done<kick_ang_steps) {
action.unset_lock();
action.unset_cmd();
action.set_kick(kick_pwr,kick_ang.get_value_mPI_pPI());
kick_ang+= ANGLE(kick_ang_inc);
if(++kick_ang_done>=kick_ang_steps) {
kick_ang=ANGLE(kick_ang_min);
kick_ang_done=0;
kick_pwr+=kick_pwr_inc;
kick_pwr_done++;
}
return &action;
}
if(dash_pwr_done<dash_pwr_steps) {
action.unset_lock();
action.unset_cmd();
action.set_dash(dash_pwr);
dash_pwr+=dash_pwr_inc;
dash_pwr_done++;
return &action;
}
if(turn_ang_done<turn_ang_steps) {
action.unset_lock();
action.unset_cmd();
action.set_turn(turn_ang);
turn_ang+= ANGLE(turn_ang_inc);
turn_ang_done++;
return &action;
}
return NULL;
}
};
class OneOrTwoStepKick: public BaseBehavior {
static bool initialized;
#if 0
struct MyState {
Vector my_vel;
Vector my_pos;
ANGLE my_angle;
Vector ball_pos;
Vector ball_vel;
Vector op_pos;
ANGLE op_bodydir;
};
#endif
OneStepKick *onestepkick;
OneOrTwoStepKickItrActions itr_actions;
Cmd_Main result_cmd1,result_cmd2;
Value result_vel1,result_vel2;
bool result_status;
bool need_2_steps;
long set_in_cycle;
Vector target_pos;
ANGLE target_dir;
Value target_vel;
bool kick_to_pos;
bool calc_done;
MyState fake_state;
long fake_state_time;
void get_ws_state(MyState &state);
MyState get_cur_state();
bool calculate(const MyState &state,Value vel,const ANGLE &dir,const Vector &pos,bool to_pos,
Cmd_Main &res_cmd1,Value &res_vel1,Cmd_Main &res_cmd2,Value &res_vel2,
bool &need_2steps);
bool do_calc();
public:
/** This makes it possible to "fake" WS information.
This must be called _BEFORE_ any of the kick functions, and is valid for
the current cycle only.
*/
void set_state(const Vector &mypos,const Vector &myvel,const ANGLE &myang,
const Vector &ballpos,const Vector &ballvel,
const Vector &op_pos = Vector(1000,1000),
const ANGLE &op_bodydir = ANGLE(0),
const int op_bodydir_age = 1000);
void set_state( const AState & state );
/** Resets the current state to that found in WS.
This must be called _BEFORE_ any of the kick functions.
*/
void reset_state();
void kick_in_dir_with_initial_vel(Value vel,const ANGLE &dir);
void kick_in_dir_with_max_vel(const ANGLE &dir);
void kick_to_pos_with_initial_vel(Value vel,const Vector &point);
void kick_to_pos_with_final_vel(Value vel,const Vector &point);
void kick_to_pos_with_max_vel(const Vector &point);
/** false is returned if we do not reach our desired vel within two cycles.
Note that velocities are set to zero if the resulting pos is not ok,
meaning that even if a cmd would reach the desired vel, we will ignore
it if the resulting pos is not ok.
*/
bool get_vel(Value &vel_1step,Value &vel_2step);
bool get_cmd(Cmd &cmd_1step,Cmd &cmd_2step);
bool get_vel(Value &best_vel); // get best possible vel (1 or 2 step)
bool get_cmd(Cmd &best_cmd); // get best possible cmd (1 or 2 step)
// returns 0 if kick is not possible, 1 if kick in 1 step is possible, 2 if in 2 steps. probably modifies vel
int is_kick_possible(Value &speed,const ANGLE &dir);
bool need_two_steps();
bool can_keep_ball_in_kickrange();
static bool init(char const * conf_file, int argc, char const* const* argv) {
if(initialized) return true;
initialized = true;
if(OneStepKick::init(conf_file,argc,argv)) {
cout << "\nOneOrTwoStepKick behavior initialized.";
} else {
ERROR_OUT << "\nCould not initialize OneStepKick behavior - stop loading.";
exit(1);
}
return true;
}
OneOrTwoStepKick() {
set_in_cycle = -1;
onestepkick = new OneStepKick();
onestepkick->set_log(false); // we don't want OneStepKick-Info in our logs!
}
virtual ~OneOrTwoStepKick() {
delete onestepkick;
}
};
#endif
| [
"[email protected]"
] | |
6bb71dcc34b99d77ceb1ceff65cfbc759d142cb5 | fb72a82827496e66e04ecb29abbca788a1ea0525 | /src/wallet/wallet.h | 5c79de2b263b987cf010ed0c6314bf311d8d6581 | [
"MIT"
] | permissive | exiliumcore/exilium | 92631c2e7abeeae6a80debbb699441d6b56e2fee | 6aa88fe0c40fe72850e5bdb265741a375b2ab766 | refs/heads/master | 2020-03-14T05:50:41.214608 | 2018-05-13T01:00:24 | 2018-05-13T01:00:24 | 131,472,364 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 37,762 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The Exilium Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLET_WALLET_H
#define BITCOIN_WALLET_WALLET_H
#include "amount.h"
#include "base58.h"
#include "streams.h"
#include "tinyformat.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#include "wallet/crypter.h"
#include "wallet/wallet_ismine.h"
#include "wallet/walletdb.h"
#include "privatesend.h"
#include <algorithm>
#include <map>
#include <set>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
#include <boost/shared_ptr.hpp>
/**
* Settings
*/
extern CFeeRate payTxFee;
extern CAmount maxTxFee;
extern unsigned int nTxConfirmTarget;
extern bool bSpendZeroConfChange;
extern bool fSendFreeTransactions;
static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
//! -paytxfee default
static const CAmount DEFAULT_TRANSACTION_FEE = 0;
//! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
static const CAmount nHighTransactionFeeWarning = 0.01 * COIN;
//! -fallbackfee default
static const CAmount DEFAULT_FALLBACK_FEE = 1000;
//! -mintxfee default
static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
//! -maxtxfee default
static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.2 * COIN; // "smallest denom" + X * "denom tails"
//! minimum change amount
static const CAmount MIN_CHANGE = CENT;
//! Default for -spendzeroconfchange
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
//! Default for -sendfreetransactions
static const bool DEFAULT_SEND_FREE_TRANSACTIONS = false;
//! -txconfirmtarget default
static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 2;
//! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
//! Largest (in bytes) free transaction we're willing to create
static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
static const bool DEFAULT_WALLETBROADCAST = true;
//! if set, all keys will be derived by using BIP39/BIP44
static const bool DEFAULT_USE_HD_WALLET = false;
class CBlockIndex;
class CCoinControl;
class COutput;
class CReserveKey;
class CScript;
class CTxMemPool;
class CWalletTx;
/** (client) version numbers for particular wallet features */
enum WalletFeature
{
FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
FEATURE_WALLETCRYPT = 40000, // wallet encryption
FEATURE_COMPRPUBKEY = 60000, // compressed public keys
FEATURE_HD = 120200, // Hierarchical key derivation after BIP32 (HD Wallet), BIP44 (multi-coin), BIP39 (mnemonic)
// which uses on-the-fly private key derivation
FEATURE_LATEST = 61000
};
enum AvailableCoinsType
{
ALL_COINS,
ONLY_DENOMINATED,
ONLY_NONDENOMINATED,
ONLY_1000, // find masternode outputs including locked ones (use with caution)
ONLY_PRIVATESEND_COLLATERAL
};
struct CompactTallyItem
{
CTxDestination txdest;
CAmount nAmount;
std::vector<CTxIn> vecTxIn;
CompactTallyItem()
{
nAmount = 0;
}
};
/** A key pool entry */
class CKeyPool
{
public:
int64_t nTime;
CPubKey vchPubKey;
bool fInternal; // for change outputs
CKeyPool();
CKeyPool(const CPubKey& vchPubKeyIn, bool fInternalIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(nTime);
READWRITE(vchPubKey);
if (ser_action.ForRead()) {
try {
READWRITE(fInternal);
}
catch (std::ios_base::failure&) {
/* flag as external address if we can't read the internal boolean
(this will be the case for any wallet before the HD chain split version) */
fInternal = false;
}
}
else {
READWRITE(fInternal);
}
}
};
/** Address book data */
class CAddressBookData
{
public:
std::string name;
std::string purpose;
CAddressBookData()
{
purpose = "unknown";
}
typedef std::map<std::string, std::string> StringMap;
StringMap destdata;
};
struct CRecipient
{
CScript scriptPubKey;
CAmount nAmount;
bool fSubtractFeeFromAmount;
};
typedef std::map<std::string, std::string> mapValue_t;
static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
{
if (!mapValue.count("n"))
{
nOrderPos = -1; // TODO: calculate elsewhere
return;
}
nOrderPos = atoi64(mapValue["n"].c_str());
}
static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
{
if (nOrderPos == -1)
return;
mapValue["n"] = i64tostr(nOrderPos);
}
struct COutputEntry
{
CTxDestination destination;
CAmount amount;
int vout;
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
/** Constant used in hashBlock to indicate tx has been abandoned */
static const uint256 ABANDON_HASH;
public:
uint256 hashBlock;
/* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
* block in the chain we know this or any in-wallet dependency conflicts
* with. Older clients interpret nIndex == -1 as unconfirmed for backward
* compatibility.
*/
int nIndex;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = uint256();
nIndex = -1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
READWRITE(*(CTransaction*)this);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
}
int SetMerkleBranch(const CBlock& block);
/**
* Return depth of transaction in blockchain:
* <0 : conflicts with a transaction this deep in the blockchain
* 0 : in memory pool, waiting to be included in a block
* >=1 : this many blocks deep in the main chain
*/
int GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX = true) const;
int GetDepthInMainChain(bool enableIX = true) const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet, enableIX); }
bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);
bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
void setAbandoned() { hashBlock = ABANDON_HASH; }
};
/**
* A transaction with a bunch of additional info that only the owner cares about.
* It includes any unrecorded transactions needed to link it back to the block chain.
*/
class CWalletTx : public CMerkleTx
{
private:
const CWallet* pwallet;
public:
mapValue_t mapValue;
std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; //! time received by this node
unsigned int nTimeSmart;
char fFromMe;
std::string strFromAccount;
int64_t nOrderPos; //! position in ordered transaction list
// memory only
mutable bool fDebitCached;
mutable bool fCreditCached;
mutable bool fImmatureCreditCached;
mutable bool fAvailableCreditCached;
mutable bool fAnonymizedCreditCached;
mutable bool fDenomUnconfCreditCached;
mutable bool fDenomConfCreditCached;
mutable bool fWatchDebitCached;
mutable bool fWatchCreditCached;
mutable bool fImmatureWatchCreditCached;
mutable bool fAvailableWatchCreditCached;
mutable bool fChangeCached;
mutable CAmount nDebitCached;
mutable CAmount nCreditCached;
mutable CAmount nImmatureCreditCached;
mutable CAmount nAvailableCreditCached;
mutable CAmount nAnonymizedCreditCached;
mutable CAmount nDenomUnconfCreditCached;
mutable CAmount nDenomConfCreditCached;
mutable CAmount nWatchDebitCached;
mutable CAmount nWatchCreditCached;
mutable CAmount nImmatureWatchCreditCached;
mutable CAmount nAvailableWatchCreditCached;
mutable CAmount nChangeCached;
CWalletTx()
{
Init(NULL);
}
CWalletTx(const CWallet* pwalletIn)
{
Init(pwalletIn);
}
CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
{
Init(pwalletIn);
}
CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
{
Init(pwalletIn);
}
void Init(const CWallet* pwalletIn)
{
pwallet = pwalletIn;
mapValue.clear();
vOrderForm.clear();
fTimeReceivedIsTxTime = false;
nTimeReceived = 0;
nTimeSmart = 0;
fFromMe = false;
strFromAccount.clear();
fDebitCached = false;
fCreditCached = false;
fImmatureCreditCached = false;
fAvailableCreditCached = false;
fAnonymizedCreditCached = false;
fDenomUnconfCreditCached = false;
fDenomConfCreditCached = false;
fWatchDebitCached = false;
fWatchCreditCached = false;
fImmatureWatchCreditCached = false;
fAvailableWatchCreditCached = false;
fChangeCached = false;
nDebitCached = 0;
nCreditCached = 0;
nImmatureCreditCached = 0;
nAvailableCreditCached = 0;
nAnonymizedCreditCached = 0;
nDenomUnconfCreditCached = 0;
nDenomConfCreditCached = 0;
nWatchDebitCached = 0;
nWatchCreditCached = 0;
nAvailableWatchCreditCached = 0;
nImmatureWatchCreditCached = 0;
nChangeCached = 0;
nOrderPos = -1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (ser_action.ForRead())
Init(NULL);
char fSpent = false;
if (!ser_action.ForRead())
{
mapValue["fromaccount"] = strFromAccount;
WriteOrderPos(nOrderPos, mapValue);
if (nTimeSmart)
mapValue["timesmart"] = strprintf("%u", nTimeSmart);
}
READWRITE(*(CMerkleTx*)this);
std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
READWRITE(vUnused);
READWRITE(mapValue);
READWRITE(vOrderForm);
READWRITE(fTimeReceivedIsTxTime);
READWRITE(nTimeReceived);
READWRITE(fFromMe);
READWRITE(fSpent);
if (ser_action.ForRead())
{
strFromAccount = mapValue["fromaccount"];
ReadOrderPos(nOrderPos, mapValue);
nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
}
mapValue.erase("fromaccount");
mapValue.erase("version");
mapValue.erase("spent");
mapValue.erase("n");
mapValue.erase("timesmart");
}
//! make sure balances are recalculated
void MarkDirty()
{
fCreditCached = false;
fAvailableCreditCached = false;
fImmatureCreditCached = false;
fAnonymizedCreditCached = false;
fDenomUnconfCreditCached = false;
fDenomConfCreditCached = false;
fWatchDebitCached = false;
fWatchCreditCached = false;
fAvailableWatchCreditCached = false;
fImmatureWatchCreditCached = false;
fDebitCached = false;
fChangeCached = false;
}
void BindWallet(CWallet *pwalletIn)
{
pwallet = pwalletIn;
MarkDirty();
}
//! filter decides which addresses will count towards the debit
CAmount GetDebit(const isminefilter& filter) const;
CAmount GetCredit(const isminefilter& filter) const;
CAmount GetImmatureCredit(bool fUseCache=true) const;
CAmount GetAvailableCredit(bool fUseCache=true) const;
CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
CAmount GetChange() const;
CAmount GetAnonymizedCredit(bool fUseCache=true) const;
CAmount GetDenominatedCredit(bool unconfirmed, bool fUseCache=true) const;
void GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
bool IsFromMe(const isminefilter& filter) const
{
return (GetDebit(filter) > 0);
}
// True if only scriptSigs are different
bool IsEquivalentTo(const CWalletTx& tx) const;
bool InMempool() const;
bool IsTrusted() const;
bool WriteToDisk(CWalletDB *pwalletdb);
int64_t GetTxTime() const;
int GetRequestCount() const;
bool RelayWalletTransaction(CConnman* connman, std::string strCommand="tx");
std::set<uint256> GetConflicts() const;
};
class COutput
{
public:
const CWalletTx *tx;
int i;
int nDepth;
bool fSpendable;
bool fSolvable;
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn)
{
tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn;
}
//Used with Darksend. Will return largest nondenom, then denominations, then very small inputs
int Priority() const;
std::string ToString() const;
};
/** Private key that includes an expiration date in case it never gets used. */
class CWalletKey
{
public:
CPrivKey vchPrivKey;
int64_t nTimeCreated;
int64_t nTimeExpires;
std::string strComment;
//! todo: add something to note what created it (user, getnewaddress, change)
//! maybe should have a map<string, string> property map
CWalletKey(int64_t nExpires=0);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPrivKey);
READWRITE(nTimeCreated);
READWRITE(nTimeExpires);
READWRITE(LIMITED_STRING(strComment, 65536));
}
};
/**
* Internal transfers.
* Database key is acentry<account><counter>.
*/
class CAccountingEntry
{
public:
std::string strAccount;
CAmount nCreditDebit;
int64_t nTime;
std::string strOtherAccount;
std::string strComment;
mapValue_t mapValue;
int64_t nOrderPos; //! position in ordered transaction list
uint64_t nEntryNo;
CAccountingEntry()
{
SetNull();
}
void SetNull()
{
nCreditDebit = 0;
nTime = 0;
strAccount.clear();
strOtherAccount.clear();
strComment.clear();
nOrderPos = -1;
nEntryNo = 0;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
//! Note: strAccount is serialized as part of the key, not here.
READWRITE(nCreditDebit);
READWRITE(nTime);
READWRITE(LIMITED_STRING(strOtherAccount, 65536));
if (!ser_action.ForRead())
{
WriteOrderPos(nOrderPos, mapValue);
if (!(mapValue.empty() && _ssExtra.empty()))
{
CDataStream ss(nType, nVersion);
ss.insert(ss.begin(), '\0');
ss << mapValue;
ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
strComment.append(ss.str());
}
}
READWRITE(LIMITED_STRING(strComment, 65536));
size_t nSepPos = strComment.find("\0", 0, 1);
if (ser_action.ForRead())
{
mapValue.clear();
if (std::string::npos != nSepPos)
{
CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
ss >> mapValue;
_ssExtra = std::vector<char>(ss.begin(), ss.end());
}
ReadOrderPos(nOrderPos, mapValue);
}
if (std::string::npos != nSepPos)
strComment.erase(nSepPos);
mapValue.erase("n");
}
private:
std::vector<char> _ssExtra;
};
/**
* A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
* and provides the ability to create new transactions.
*/
class CWallet : public CCryptoKeyStore, public CValidationInterface
{
private:
/**
* Select a set of coins such that nValueRet >= nTargetValue and at least
* all coins from coinControl are selected; Never select unconfirmed coins
* if they are not ours
*/
bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = true) const;
CWalletDB *pwalletdbEncryption;
//! the current wallet version: clients below this version are not able to load the wallet
int nWalletVersion;
//! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
int nWalletMaxVersion;
int64_t nNextResend;
int64_t nLastResend;
bool fBroadcastTransactions;
mutable bool fAnonymizableTallyCached;
mutable std::vector<CompactTallyItem> vecAnonymizableTallyCached;
mutable bool fAnonymizableTallyCachedNonDenom;
mutable std::vector<CompactTallyItem> vecAnonymizableTallyCachedNonDenom;
/**
* Used to keep track of spent outpoints, and
* detect and report conflicts (double-spends or
* mutated transactions where the mutant gets mined).
*/
typedef std::multimap<COutPoint, uint256> TxSpends;
TxSpends mapTxSpends;
void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
void AddToSpends(const uint256& wtxid);
std::set<COutPoint> setWalletUTXO;
/* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
/* HD derive new child key (on internal or external chain) */
void DeriveNewChildKey(const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal /*= false*/);
public:
/*
* Main wallet lock.
* This lock protects all the fields added by CWallet
* except for:
* fFileBacked (immutable after instantiation)
* strWalletFile (immutable after instantiation)
*/
mutable CCriticalSection cs_wallet;
bool fFileBacked;
const std::string strWalletFile;
void LoadKeyPool(int nIndex, const CKeyPool &keypool)
{
if (keypool.fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (mapKeyMetadata.count(keyid) == 0)
mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
std::set<int64_t> setInternalKeyPool;
std::set<int64_t> setExternalKeyPool;
std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
MasterKeyMap mapMasterKeys;
unsigned int nMasterKeyMaxID;
CWallet()
{
SetNull();
}
CWallet(const std::string& strWalletFileIn)
: strWalletFile(strWalletFileIn)
{
SetNull();
fFileBacked = true;
}
~CWallet()
{
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
void SetNull()
{
nWalletVersion = FEATURE_BASE;
nWalletMaxVersion = FEATURE_BASE;
fFileBacked = false;
nMasterKeyMaxID = 0;
pwalletdbEncryption = NULL;
nOrderPosNext = 0;
nNextResend = 0;
nLastResend = 0;
nTimeFirstKey = 0;
fBroadcastTransactions = false;
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
vecAnonymizableTallyCached.clear();
vecAnonymizableTallyCachedNonDenom.clear();
}
std::map<uint256, CWalletTx> mapWallet;
std::list<CAccountingEntry> laccentries;
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef std::multimap<int64_t, TxPair > TxItems;
TxItems wtxOrdered;
int64_t nOrderPosNext;
std::map<uint256, int> mapRequestCount;
std::map<CTxDestination, CAddressBookData> mapAddressBook;
CPubKey vchDefaultKey;
std::set<COutPoint> setLockedCoins;
int64_t nTimeFirstKey;
int64_t nKeysLeftSinceAutoBackup;
std::map<CKeyID, CHDPubKey> mapHdPubKeys; //<! memory map of HD extended pubkeys
const CWalletTx* GetWalletTx(const uint256& hash) const;
//! check whether we are allowed to upgrade (or already support) to the named feature
bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
/**
* populate vCoins with vector of available COutputs.
*/
void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = false) const;
/**
* Shuffle and select coins until nTargetValue is reached while avoiding
* small change; This method is stochastic for some inputs and upon
* completion the coin set and corresponding actual target value is
* assembled
*/
bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool fUseInstantSend = false) const;
// Coin selection
bool SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<COutput>& vCoinsRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax);
bool GetCollateralTxDSIn(CTxDSIn& txdsinRet, CAmount& nValueRet) const;
bool SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax) const;
bool SelectCoinsGrouppedByAddresses(std::vector<CompactTallyItem>& vecTallyRet, bool fSkipDenominated = true, bool fAnonymizable = true, bool fSkipUnconfirmed = true) const;
/// Get 1000exilium output and keys which can be used for the Masternode
bool GetMasternodeOutpointAndKeys(COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash = "", std::string strOutputIndex = "");
/// Extract txin information and keys from output
bool GetOutpointAndKeysFromOutput(const COutput& out, COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet);
bool HasCollateralInputs(bool fOnlyConfirmed = true) const;
int CountInputsWithAmount(CAmount nInputAmount);
// get the PrivateSend chain depth for a given input
int GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds) const;
// respect current settings
int GetOutpointPrivateSendRounds(const COutPoint& outpoint) const;
bool IsDenominated(const COutPoint& outpoint) const;
bool IsSpent(const uint256& hash, unsigned int n) const;
bool IsLockedCoin(uint256 hash, unsigned int n) const;
void LockCoin(COutPoint& output);
void UnlockCoin(COutPoint& output);
void UnlockAllCoins();
void ListLockedCoins(std::vector<COutPoint>& vOutpts);
/**
* keystore implementation
* Generate a new key
*/
CPubKey GenerateNewKey(uint32_t nAccountIndex, bool fInternal /*= false*/);
//! HaveKey implementation that also checks the mapHdPubKeys
bool HaveKey(const CKeyID &address) const;
//! GetPubKey implementation that also checks the mapHdPubKeys
bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const;
//! GetKey implementation that can derive a HD private key on the fly
bool GetKey(const CKeyID &address, CKey& keyOut) const;
//! Adds a HDPubKey into the wallet(database)
bool AddHDPubKey(const CExtPubKey &extPubKey, bool fInternal);
//! loads a HDPubKey into the wallets memory
bool LoadHDPubKey(const CHDPubKey &hdPubKey);
//! Adds a key to the store, and saves it to disk.
bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
//! Adds a key to the store, without saving it to disk (used by LoadWallet)
bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
//! Load metadata (used by LoadWallet)
bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
//! Adds an encrypted key to the store, and saves it to disk.
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
//! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
bool AddCScript(const CScript& redeemScript);
bool LoadCScript(const CScript& redeemScript);
//! Adds a destination data tuple to the store, and saves it to disk
bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
//! Erases a destination data tuple in the store and on disk
bool EraseDestData(const CTxDestination &dest, const std::string &key);
//! Adds a destination data tuple to the store, without saving it to disk
bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
//! Look up a destination data tuple in the store, return true if found false otherwise
bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
//! Adds a watch-only address to the store, and saves it to disk.
bool AddWatchOnly(const CScript &dest);
bool RemoveWatchOnly(const CScript &dest);
//! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool LoadWatchOnly(const CScript &dest);
bool Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly = false);
bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
bool EncryptWallet(const SecureString& strWalletPassphrase);
void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
/**
* Increment the next transaction order id
* @return next transaction order id
*/
int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
void MarkDirty();
bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
void ReacceptWalletTransactions();
void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman);
std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
CAmount GetBalance() const;
CAmount GetUnconfirmedBalance() const;
CAmount GetImmatureBalance() const;
CAmount GetWatchOnlyBalance() const;
CAmount GetUnconfirmedWatchOnlyBalance() const;
CAmount GetImmatureWatchOnlyBalance() const;
CAmount GetAnonymizableBalance(bool fSkipDenominated = false, bool fSkipUnconfirmed = true) const;
CAmount GetAnonymizedBalance() const;
float GetAverageAnonymizedRounds() const;
CAmount GetNormalizedAnonymizedBalance() const;
CAmount GetNeedsToBeAnonymizedBalance(CAmount nMinBalance = 0) const;
CAmount GetDenominatedBalance(bool unconfirmed=false) const;
bool GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, CAmount amount, bool fUseInstantSend);
bool GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, CAmount amount, bool fUseInstantSend);
/**
* Insert additional inputs into the transaction by
* calling CreateTransaction();
*/
bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching);
/**
* Create a new transaction paying the recipients with a set of coins
* selected by SelectCoins(); Also create the change output, when needed
*/
bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet,
std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false);
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, std::string strCommand="tx");
bool CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason);
bool ConvertList(std::vector<CTxIn> vecTxIn, std::vector<CAmount>& vecAmounts);
bool AddAccountingEntry(const CAccountingEntry&, CWalletDB & pwalletdb);
static CFeeRate minTxFee;
static CFeeRate fallbackFee;
/**
* Estimate the minimum fee considering user set parameters
* and the required fee
*/
static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
/**
* Return the minimum required fee taking into account the
* floating relay fee and user set minimum transaction fee
*/
static CAmount GetRequiredFee(unsigned int nTxBytes);
bool NewKeyPool();
size_t KeypoolCountExternalKeys();
size_t KeypoolCountInternalKeys();
bool TopUpKeyPool(unsigned int kpSize = 0);
void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fInternal);
void KeepKey(int64_t nIndex);
void ReturnKey(int64_t nIndex, bool fInternal);
bool GetKeyFromPool(CPubKey &key, bool fInternal /*= false*/);
int64_t GetOldestKeyPoolTime();
void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
std::set< std::set<CTxDestination> > GetAddressGroupings();
std::map<CTxDestination, CAmount> GetAddressBalances();
std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
isminetype IsMine(const CTxIn& txin) const;
CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
isminetype IsMine(const CTxOut& txout) const;
CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
bool IsChange(const CTxOut& txout) const;
CAmount GetChange(const CTxOut& txout) const;
bool IsMine(const CTransaction& tx) const;
/** should probably be renamed to IsRelevantToMe */
bool IsFromMe(const CTransaction& tx) const;
CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
CAmount GetChange(const CTransaction& tx) const;
void SetBestChain(const CBlockLocator& loc);
DBErrors LoadWallet(bool& fFirstRunRet);
DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
bool DelAddressBook(const CTxDestination& address);
bool UpdatedTransaction(const uint256 &hashTx);
void Inventory(const uint256 &hash)
{
{
LOCK(cs_wallet);
std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
if (mi != mapRequestCount.end())
(*mi).second++;
}
}
void GetScriptForMining(boost::shared_ptr<CReserveScript> &script);
void ResetRequestCount(const uint256 &hash)
{
LOCK(cs_wallet);
mapRequestCount[hash] = 0;
};
unsigned int GetKeyPoolSize()
{
AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
return setInternalKeyPool.size() + setExternalKeyPool.size();
}
bool SetDefaultKey(const CPubKey &vchPubKey);
//! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
//! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
bool SetMaxVersion(int nVersion);
//! get the current wallet format (the oldest client version guaranteed to understand this wallet)
int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
//! Get wallet transactions that conflict with given transaction (spend same outputs)
std::set<uint256> GetConflicts(const uint256& txid) const;
//! Flush wallet (bitdb flush)
void Flush(bool shutdown=false);
//! Verify the wallet database and perform salvage if required
static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
/**
* Address book entry changed.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void (CWallet *wallet, const CTxDestination
&address, const std::string &label, bool isMine,
const std::string &purpose,
ChangeType status)> NotifyAddressBookChanged;
/**
* Wallet transaction added, removed or updated.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
ChangeType status)> NotifyTransactionChanged;
/** Show progress e.g. for rescan */
boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
/** Watch-only address added */
boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
/** Inquire whether this wallet broadcasts transactions. */
bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
/** Set whether this wallet broadcasts transactions. */
void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
/* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
bool AbandonTransaction(const uint256& hashTx);
/**
* HD Wallet Functions
*/
/* Returns true if HD is enabled */
bool IsHDEnabled();
/* Generates a new HD chain */
void GenerateNewHDChain();
/* Set the HD chain model (chain child index counters) */
bool SetHDChain(const CHDChain& chain, bool memonly);
bool SetCryptedHDChain(const CHDChain& chain, bool memonly);
bool GetDecryptedHDChain(CHDChain& hdChainRet);
};
/** A key allocated from the key pool. */
class CReserveKey : public CReserveScript
{
protected:
CWallet* pwallet;
int64_t nIndex;
CPubKey vchPubKey;
bool fInternal;
public:
CReserveKey(CWallet* pwalletIn)
{
nIndex = -1;
pwallet = pwalletIn;
fInternal = false;
}
~CReserveKey()
{
ReturnKey();
}
void ReturnKey();
bool GetReservedKey(CPubKey &pubkey, bool fInternalIn /*= false*/);
void KeepKey();
void KeepScript() { KeepKey(); }
};
/**
* Account information.
* Stored in wallet with key "acc"+string account name.
*/
class CAccount
{
public:
CPubKey vchPubKey;
CAccount()
{
SetNull();
}
void SetNull()
{
vchPubKey = CPubKey();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPubKey);
}
};
#endif // BITCOIN_WALLET_WALLET_H
| [
"[email protected]"
] | |
2700f3690854eaf5a2187d2d57c0ce1df9fa0f9f | 29288023bde7829066f810540963a7b35573fa31 | /BstUsingSet.cpp | 4f984176f775caa7499cc3e20cab43944733c536 | [] | no_license | Sohail-khan786/Competitve-Programming | 6e56bdd8fb7b3660edec50c72f680b6ed2c41a0f | e90dcf557778a4c0310e03539e4f3c1c939bb3a1 | refs/heads/master | 2022-10-08T06:55:46.637560 | 2020-06-07T18:39:20 | 2020-06-07T18:39:20 | 254,899,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int flag=1;
set<int> s;
set<int>::iterator it;
int x;
while(flag!=3)
{
cout<<"1.Insert 2.Delete 3.Exit"<<endl;
cin>>flag;
cout<<"value\t";
cin>>x;
if(flag==1)
{
s.insert(x);
}
else if(flag==2)
{
s.erase(x);
}
cout<<"Extracting max n min from a set"<<cout<<endl;
//s.end has iterator to last element of the set which is the size of the set and hence decrement it by one to get the maximum element present in the set;
it = s.end();
it--;
cout<<"maxx = "<<*(it)<<" minn ="<<*s.begin();
cout<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
40bc68efa1d237aacc7f1b2a5010046f0e4cf13c | 4b1289b0eb41c045a24b4626857097571c988e9b | /Least_Loose_Number_In_The_Array.cpp | 01dac7320be1eee1ec1af9b49c0962158327697f | [] | no_license | Arvy1998/Calculus-and-Play-with-New-Syntax | 136d942c1be8dc59d3b6d764881d7a9aea5a68cd | b442156a850dad2ed7c53ce86d3435fb35d78fe9 | refs/heads/master | 2021-07-11T02:05:09.180547 | 2019-03-12T22:00:42 | 2019-03-12T22:00:42 | 129,288,984 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 965 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
long long n, seka[101], MIN_TEIG = 0, count;
vector <long long> izulus_teig_sk;
cin >> n;
for (auto x = 0; x < n; x++) {
cin >> seka[x];
}
for (auto i = 0; i < n; i++) {
if (i == 0) {
if (seka[i] > seka[i + 1]) {
izulus_teig_sk.push_back(seka[i]);
}
}
if (i > 0 && i < n - 1) {
if (seka[i] > seka[i - 1] && seka[i] > seka[i + 1]) {
izulus_teig_sk.push_back(seka[i]);
}
}
if (i == n - 1) {
if (seka[i] > seka[i - 1]) {
izulus_teig_sk.push_back(seka[i]);
}
}
}
if (izulus_teig_sk.size() == 0 || n <= 1) {
cout << "NO";
exit(0);
}
else {
sort(izulus_teig_sk.begin(), izulus_teig_sk.end());
for (size_t j = 0; j < izulus_teig_sk.size(); j++) {
if (izulus_teig_sk[j] > 0) {
MIN_TEIG = izulus_teig_sk[j];
cout << MIN_TEIG;
break;
}
}
}
if (MIN_TEIG == 0) {
cout << "NO";
}
return 0;
}
| [
"[email protected]"
] | |
819eb928fa03acd974c3e18443532022f13c2f05 | 711b11d08abdb3a7df2574b0b4c86af21c5c6750 | /dest.h | e06af74e0264187915ab70b86b0e67aa85d2a79f | [] | no_license | nflath/MSP430Emulator | 4aee9e093113cc41d9041a1728eedd742fd786b2 | a97a1b97b895b3533597bcdb69bec8b75db395df | refs/heads/master | 2021-01-13T01:54:55.258203 | 2015-08-25T05:10:04 | 2015-08-25T05:10:04 | 41,343,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,382 | h | #include <assert.h>
#ifndef DEST_H
#define DEST_H
#include "error.h"
// Classes representing 'Destinations' types in MSP430 - See the section
// 'MSP430 addressing modes' in https://en.wikipedia.org/wiki/TI_MSP430#MSP430_CPU
class State;
class Dest {
// Virtual base clase.
public:
virtual void set(short value) { notimplemented(); }
// Sets the value of this destination
virtual void setByte(unsigned char value) { notimplemented(); }
// Sets the value of this destination (byte addressing mode)
virtual short value() { notimplemented(); return 0;}
// Returns the value of this destination
virtual unsigned char valueByte() { notimplemented(); return 0;}
// Returns the value of this destination(byte addressing mode)
virtual std::string toString() = 0;
// Returns a string representation of this destination
virtual bool usedExtensionWord() { return false; }
// Whether an extension word was used to represent this destination
virtual unsigned char size() { return usedExtensionWord() ? 2 : 0; }
// How many extra bytes this destination took up in the assembly
};
class RegisterDest : public Dest {
// Destination representing a register (r14)
public:
virtual std::string toString();
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual short value();
virtual unsigned char valueByte();
RegisterDest(unsigned short reg_) : reg(reg_) {}
unsigned short reg;
};
class RegisterOffsetDest : public RegisterDest {
// Destination representing the memory address at a register plus an offset (0x40(r14))
public:
virtual std::string toString();
virtual bool usedExtensionWord() { return true; }
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual short value();
virtual unsigned char valueByte();
RegisterOffsetDest(unsigned short reg_, short offset_) :
RegisterDest(reg_),
offset(offset_) {
}
short offset;
};
class AbsoluteDest : public Dest {
// Destination that is just a memory address (&0x4400)
public:
virtual std::string toString();
virtual bool usedExtensionWord() { return true; }
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual unsigned char valueByte();
AbsoluteDest(unsigned short address_) :
address(address_) {
}
unsigned short address;
};
extern State* s;
#endif
| [
"[email protected]"
] | |
19203a417004197a3b51e22fe5a3dc21d6bcd8c4 | 57f87cd5fb9448bc6cdbf10769365393efae3a00 | /firmware_v5/telelogger/teleclient.h | a6433b87bd84452fb52cfd90b903677e97fb909f | [] | no_license | NatroNx/Freematics | 6a366805aef406d6f4deae050414f9611bbe710e | 011ae3212f57fdee7648eb34171e141c55a413ed | refs/heads/master | 2020-03-25T02:15:51.919396 | 2018-07-31T13:14:23 | 2018-07-31T13:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,569 | h | class TeleClient
{
public:
virtual void reset()
{
txCount = 0;
txBytes = 0;
rxBytes = 0;
}
virtual bool notify(byte event, const char* serverKey, const char* payload = 0) { return true; }
virtual bool connect() { return true; }
virtual bool transmit(const char* packetBuffer, unsigned int packetSize) { return true; }
virtual void inbound() {}
virtual bool begin() { return true; }
virtual void end() {}
uint32_t txCount = 0;
uint32_t txBytes = 0;
uint32_t rxBytes = 0;
uint32_t lastSyncTime = 0;
uint32_t lastSentTime = 0;
uint16_t feedid = 0;
};
class TeleClientUDP : public TeleClient
{
public:
bool notify(byte event, const char* serverKey, const char* payload = 0);
bool connect();
bool transmit(const char* packetBuffer, unsigned int packetSize);
void inbound();
bool verifyChecksum(char* data);
#if NET_DEVICE == NET_WIFI
UDPClientWIFI net;
#elif NET_DEVICE == NET_SIM800
UDPClientSIM800 net;
#elif NET_DEVICE == NET_SIM5360
UDPClientSIM5360 net;
#elif NET_DEVICE == NET_SIM7600
UDPClientSIM7600 net;
#else
NullClient net;
#endif
};
class TeleClientHTTP : public TeleClient
{
public:
bool connect();
bool transmit(const char* packetBuffer, unsigned int packetSize);
#if NET_DEVICE == NET_WIFI
HTTPClientWIFI net;
#elif NET_DEVICE == NET_SIM800
HTTPClientSIM800 net;
#elif NET_DEVICE == NET_SIM5360
HTTPClientSIM5360 net;
#elif NET_DEVICE == NET_SIM7600
HTTPClientSIM7600 net;
#else
NullClient net;
#endif
}; | [
"[email protected]"
] | |
376f659de9de4170c19135d4e5e6f4fa7d95e938 | bc33abf80f11c4df023d6b1f0882bff1e30617cf | /CPP/other/李泉彰/hhh.cpp | 0e114bad33f893d5b9c3e166e74c22c9172ffe76 | [] | no_license | pkuzhd/ALL | 0fad250c710b4804dfd6f701d8f45381ee1a5d11 | c18525decdfa70346ec32ca2f47683951f4c39e0 | refs/heads/master | 2022-07-11T18:20:26.435897 | 2019-11-20T13:25:24 | 2019-11-20T13:25:24 | 119,031,607 | 0 | 0 | null | 2022-06-21T21:10:42 | 2018-01-26T09:19:23 | C++ | UTF-8 | C++ | false | false | 6,060 | cpp | #include <stdio.h>
#include <iostream>
using namespace std;
int qipan[15][15] = { 0 };
int times = 0;
int print();
bool is_win(int x, int y, int flag);
bool is_near(int x, int y);
bool AI_set(int flag);
int calc_value(int x, int y, int flag, int depth, int _max_value);
int qixing(int x, int y);
int main(int argc, char **argv)
{
int flag = 1;
while (true)
{
++times;
print();
int x, y;
if (flag == 1)
{
while (true)
{
cin >> x >> y;
if (!qipan[x][y] || x < 0 || x >= 15 || y < 0 || y >= 15)
break;
}
qipan[x][y] = flag;
if (is_win(x, y, flag))
break;
}
else
{
if (AI_set(flag))
break;
}
flag *= -1;
}
if (flag == 1)
{
printf("black\n");
}
else
{
printf("white\n");
}
system("pause");
return 0;
}
int print()
{
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
cout << (qipan[i][j] ? (qipan[i][j] == 1 ? "*" : "#") : "0");
cout << endl;
}
cout << endl;
return 0;
}
bool is_win(int x, int y, int flag)
{
int number = 1;
for (int i = x + 1; i < 15; ++i)
{
if (qipan[i][y] == flag)
++number;
else
break;
}
for (int i = x - 1; i >= 0; --i)
{
if (qipan[i][y] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int i = y + 1; i < 15; ++i)
{
if (qipan[x][i] == flag)
++number;
else
break;
}
for (int i = y - 1; i >= 0; --i)
{
if (qipan[x][i] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int j = 1; x + j < 15 && y + j < 15; ++j)
{
if (qipan[x + j][y + j] == flag)
++number;
else
break;
}
for (int j = 1; x - j >= 0 && y - j >= 0; ++j)
{
if (qipan[x - j][y - j] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int j = 1; x + j < 15 && y - j >= 0; ++j)
{
if (qipan[x + j][y - j] == flag)
++number;
else
break;
}
for (int j = 1; x - j >= 0 && y + j < 15; ++j)
{
if (qipan[x - j][y + j] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
return false;
}
bool is_near(int x, int y)
{
// cout << x << " " << y << endl;
int _near = 2;
for (int i = (x - _near >= 0 ? x - _near : 0); i <= (x + _near < 15 ? x + _near : 14); ++i)
{
for (int j = (y - _near >= 0 ? y - _near : 0); j <= (y + _near < 15 ? y + _near : 14); ++j)
{
if (qipan[i][j])
return true;
}
}
return false;
}
bool AI_set(int flag)
{
int max_value = -10000000;
int x = 7, y = 7;
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
{
if (qipan[i][j])
continue;
if (!is_near(i, j))
continue;
int t_value = calc_value(i, j, flag, 0, max_value);
if (is_win(i, j, flag))
{
qipan[i][j] = flag;
return true;
}
if (t_value > max_value)
{
max_value = t_value;
x = i;
y = j;
}
}
}
qipan[x][y] = flag;
cout << x << " " << y << " " << flag << " " << is_win(x, y, flag)<< endl;
return false;
}
int calc_value(int x, int y, int flag, int depth, int _max_value)
{
int _value = 0;
qipan[x][y] = flag;
if (depth < 4)
{
int max_value = -10000000;
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
{
if (qipan[i][j] || !is_near(i, j))
continue;
int t_value = calc_value(i, j, -flag, depth + 1, max_value);
if (t_value > -_max_value)
{
qipan[x][y] = 0;
return t_value;
}
if (is_win(i, j, -flag))
{
qipan[x][y] = 0;
return -10000000;
}
if (t_value > max_value)
{
max_value = t_value;
}
}
}
_value -= max_value;
}
else
_value += qixing(x, y);
qipan[x][y] = 0;
return _value;
}
int qixing(int x, int y)
{
int flag = qipan[x][y];
bool dead = false;
int number = 1;
int _value = 0;
int sz_qixing[2][6] = { 0 };
// x 方向
number = 1;
dead = false;
for (int i = x + 1; ; ++i)
{
if (i < 15 && qipan[i][y] == flag)
++number;
else
{
if (i >= 15 || qipan[i][y])
dead = true;
break;
}
}
for (int i = x - 1; i >= 0; --i)
{
if (i >= 0 && qipan[i][y] == flag)
++number;
else
{
if ((i < 0 || qipan[i][y]) && dead)
break;
else
{
if (dead || qipan[i][y])
dead = true;
++sz_qixing[dead][number];
}
}
}
// y方向
number = 1;
dead = false;
for (int i = y + 1; ; ++i)
{
if (i < 15 && qipan[x][i] == flag)
++number;
else
{
if (i >= 15 || qipan[x][i])
dead = true;
break;
}
}
for (int i = y - 1; i >= 0; --i)
{
if (i >= 0 && qipan[x][i] == flag)
++number;
else
{
if ((i < 0 || qipan[x][i]) && dead)
break;
else
{
if (dead || qipan[x][i])
dead = true;
++sz_qixing[dead][number];
}
}
}
// x y 方向
number = 1;
dead = false;
for (int i = 1; ; ++i)
{
if (x + i < 15 && y + i < 15 && qipan[x + i][y + i] == flag)
++number;
else
{
if (x + i >= 15 || y + i >= 15 || qipan[x + i][y + i])
dead = true;
break;
}
}
for (int i = 1; ; ++i)
{
if (x - i >= 0 && y - i >= 0 && qipan[x - i][y - i] == flag)
++number;
else
{
if ((x - i < 0 || y - i < 0 || qipan[x - i][y - i]) && dead)
break;
else
{
if (dead || qipan[x - i][y - i])
dead = true;
++sz_qixing[dead][number];
}
}
}
// x -y 方向
number = 1;
dead = false;
for (int i = 1; ; ++i)
{
if (x + i < 15 && y - i >= 0 && qipan[x + i][y - i] == flag)
++number;
else
{
if (x + i >= 15 || y - i < 0 || qipan[x + i][y - i])
dead = true;
break;
}
}
for (int i = 1; ; ++i)
{
if (x - i >= 0 && y + i < 15 && qipan[x - i][y + i] == flag)
++number;
else
{
if ((x - i < 0 || y + i >= 15 || qipan[x - i][y + i]) && dead)
break;
else
{
if (dead || qipan[x - i][y + i])
dead = true;
++sz_qixing[dead][number];
}
}
}
if (sz_qixing[false][4] || (sz_qixing[true][4] + sz_qixing[false][3]) >= 2)
_value += 1000000;
_value += sz_qixing[false][3] * 10000;
_value += sz_qixing[true][3] * 1000;
_value += sz_qixing[false][2] * 100;
_value += sz_qixing[true][2] * 10;
return _value;
}
| [
"[email protected]"
] | |
cb70bcdd5ff36e2a7d758db629c0ae1cdf415f34 | 6cc00c07a75bf18a2b1824383c3acc050098d9ed | /CodeChef/Easy/E0034.cpp | 8b0e042dd591f11ae41cddc5d38bbbd3f36fd170 | [
"MIT"
] | permissive | Mohammed-Shoaib/Coding-Problems | ac681c16c0f7c6d83f7cb46be71ea304d238344e | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | refs/heads/master | 2022-06-14T02:24:10.316962 | 2022-03-20T20:04:16 | 2022-03-20T20:04:16 | 145,226,886 | 75 | 31 | MIT | 2020-10-02T07:46:58 | 2018-08-18T14:31:33 | C++ | UTF-8 | C++ | false | false | 372 | cpp | // Problem Code: ALEXNUMB
#include <iostream>
#include <vector>
using namespace std;
long magicPairs(vector<int> &a){
long N = a.size();
return N*(N-1)/2;
}
int main(){
int T, n, num;
vector<int> a;
cin >> T;
while(T--){
cin >> n;
for(int i=0 ; i<n ; i++){
cin >> num;
a.push_back(num);
}
cout << magicPairs(a) << endl;
a.clear();
}
return 0;
} | [
"[email protected]"
] | |
0f14955c67c8ded4e0b25301b31b8648ae16b52f | 4985aad8ecfceca8027709cf488bc2c601443385 | /build/Android/Debug/app/src/main/include/Fuse.Resources.Resour-7da5075.h | bb740adfa48c8d9b5e34d9b3bf2a2c23882e8030 | [] | no_license | pacol85/Test1 | a9fd874711af67cb6b9559d9a4a0e10037944d89 | c7bb59a1b961bfb40fe320ee44ca67e068f0a827 | refs/heads/master | 2021-01-25T11:39:32.441939 | 2017-06-12T21:48:37 | 2017-06-12T21:48:37 | 93,937,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | h | // This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Nodes/1.0.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Fuse{namespace Resources{struct ResourceConverters;}}}
namespace g{namespace Uno{namespace Collections{struct Dictionary;}}}
namespace g{
namespace Fuse{
namespace Resources{
// internal static class ResourceConverters :3538
// {
uClassType* ResourceConverters_typeof();
void ResourceConverters__Get_fn(uType* __type, uObject** __retval);
struct ResourceConverters : uObject
{
static uSStrong< ::g::Uno::Collections::Dictionary*> _converters_;
static uSStrong< ::g::Uno::Collections::Dictionary*>& _converters() { return ResourceConverters_typeof()->Init(), _converters_; }
static uObject* Get(uType* __type);
};
// }
}}} // ::g::Fuse::Resources
| [
"[email protected]"
] | |
33fa115e3d756b655d4b8fd3fc840eb94198c8be | 012784e8de35581e1929306503439bb355be4c4f | /problems/37. 解数独/3.cc | 84bf778bd32645766fc6275be6ca3a9a288a96dc | [] | no_license | silenke/my-leetcode | 7502057c9394e41ddeb2e7fd6c1b8261661639e0 | d24ef0970785c547709b1d3c7228e7d8b98b1f06 | refs/heads/master | 2023-06-05T02:05:48.674311 | 2021-07-01T16:18:29 | 2021-07-01T16:18:29 | 331,948,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,979 | cc | #include "..\..\leetcode.h"
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
row = col = box = vector<int>(9);
int count = 0;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') count++;
else fill(i, j, i / 3 * 3 + j / 3, board[i][j] - '1');
}
}
dfs(count, board);
}
private:
vector<int> row, col, box;
void fill(int i, int j, int k, int n) {
row[i] |= 1 << n;
col[j] |= 1 << n;
box[k] |= 1 << n;
}
void zero(int i, int j, int k, int n) {
row[i] &= ~(1 << n);
col[j] &= ~(1 << n);
box[k] &= ~(1 << n);
}
int possible(int i, int j) {
return ~(row[i] | col[j] | box[i / 3 * 3 + j / 3]) & ((1 << 9) - 1);
}
pair<int, int> next(vector<vector<char>>& board) {
pair<int, int> res;
int min_count = INT_MAX;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') continue;
int c = count(possible(i, j));
if (c < min_count) {
min_count = c;
res = {i, j};
}
}
}
return res;
}
bool dfs(int count, vector<vector<char>>& board) {
if (count == 0) return true;
auto [i, j] = next(board);
int p = possible(i, j);
int k = i / 3 * 3 + j / 3;
while (p) {
int n = __builtin_ctz(p & -p);
board[i][j] = n + '1';
fill(i, j, k, n);
if (dfs(count - 1, board)) return true;
board[i][j] = '.';
zero(i, j, k, n);
p &= p - 1;
}
return false;
}
int count(int p) {
int count = 0;
while (p) {
count++;
p &= p - 1;
}
return count;
}
}; | [
"[email protected]"
] | |
b68966c17d5045233b5646054d6eadc547b96397 | 9d34ceb787b7e7a0aa9d242e401f0b13c2e4ea94 | /JoaoScaravonatti.cpp | 7278f4a435cc05195b6a61560ed065092c4ef52a | [] | no_license | joaoscaravonatti/projeto-final-algoritmos | 31a5d2ed39afd6d918894869e2c43972f44f0be7 | 23f6d11aacbe714471cc064490da6a634ac0bfa9 | refs/heads/master | 2020-03-30T09:37:17.994469 | 2018-10-01T12:21:17 | 2018-10-01T12:21:17 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 6,611 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<locale.h>
#include<windows.h>
#define tam 1000
struct cliente{
int codigo;
char nome[50];
char sexo[20];
char dataNascimento[12];
char cpf[12];
char telefone[11];
char email[100];
};
int id = 0;
int i = 0;
struct cliente clientes[tam];
void cadastrar(){
id++;
clientes[id].codigo = id;
printf("\nColoque o nome completo: ");
scanf(" %[^\n]s",&clientes[id].nome);
printf("\nColoque o CPF sem formatação: ");
scanf("%s",&clientes[id].cpf);
printf("\nColoque o sexo (masculino/feminino): ");
scanf("%s",&clientes[id].sexo);
printf("\nColoque a data de nascimento no formato XX/XX/XXXX: ");
scanf("%s",&clientes[id].dataNascimento);
printf("\nColoque o telefone sem formatação: ");
scanf("%s",&clientes[id].telefone);
printf("\nColoque o email: ");
scanf("%s",&clientes[id].email);
}
void excluir(int codigo){
clientes[codigo].codigo = 0;
strcpy(clientes[codigo].nome,"");
}
void consultarCod(int codigo){
int verificar=0;
system("cls");
if(codigo != 0){
for(i=0;i<tam;i++){
if(clientes[i].codigo == codigo){
printf("\nDados do cliente n° %i\nNome: %s\nSexo: %s\nData de nascimento: %s\nCPF: %s\nTelefone: %i\nE-mail: %s\n",clientes[i].codigo,clientes[i].nome,clientes[i].sexo,clientes[i].dataNascimento,clientes[i].cpf,clientes[i].telefone,clientes[i].email);
verificar++;
}
}
}
if(verificar==0){
printf("\nEsse cliente não está cadastrado!");
}
printf("\n_______________________________\n");
}
void consultarNome(char nome[]){
int codigo=0;
system("cls");
if(strcmp(nome,"")!=0){
for(i=0;i<tam;i++){
if(strcmp(nome,clientes[i].nome)==0){
codigo = i;
printf("\nDados do cliente n° %i\nNome: %s\nSexo: %s\nData de nascimento: %s\nCPF: %s\nTelefone: %i\nE-mail: %s\n",clientes[codigo].codigo,clientes[codigo].nome,clientes[codigo].sexo,clientes[codigo].dataNascimento,clientes[codigo].cpf,clientes[codigo].telefone,clientes[codigo].email);
printf("\n_______________________________\n");
}
}
}
if(codigo == 0){
printf("\nEsse cliente não está cadastrado!\n");
}
}
void listar(){
system("cls");
for(i=0;i<tam;i++){
if(clientes[i].codigo != 0){
printf("\nCliente de código %i: %s\n",clientes[i].codigo,clientes[i].nome);
printf("_______________________________\n");
}
}
}
void vrau(){
clientes[1].codigo = 1;
strcpy(clientes[1].nome,"juca silva");
strcpy(clientes[1].sexo,"masculino");
strcpy(clientes[1].dataNascimento,"18/01/2000");
strcpy(clientes[1].cpf,"08816690917");
strcpy(clientes[1].telefone,"49999743090");
strcpy(clientes[1].email,"[email protected]");
clientes[2].codigo = 2;
strcpy(clientes[2].nome,"juca silva");
strcpy(clientes[2].sexo,"masculino");
strcpy(clientes[2].dataNascimento,"18/01/2000");
strcpy(clientes[2].cpf,"08816690917");
strcpy(clientes[2].telefone,"49999743090");
strcpy(clientes[2].email,"[email protected]");
}
void alterar(int codigo){
char opcao[1];
char confirm[1];
confirm[0] = '0';
if(codigo != 0){
do{
printf("\nQual informação deseja alterar?\n");
printf("\n1 - Nome: %s\n2 - Sexo: %s\n3 - Data de nascimento: %s\n4 - CPF: %s\n5 - Telefone: %i\n6 - E-mail: %s\nSua opção: ",clientes[codigo].nome,clientes[codigo].sexo,clientes[codigo].dataNascimento,clientes[codigo].cpf,clientes[codigo].telefone,clientes[codigo].email);
fflush(stdin);
opcao[0] = getche();
switch(opcao[0]){
case '1':
printf("\nColoque o novo nome: ");
scanf(" %[^\n]s",&clientes[codigo].nome);
break;
case '2':
printf("\nColoque o novo sexo: ");
scanf("%s",clientes[codigo].sexo);
break;
case '3':
printf("\nColoque a nova data de nascimento: ");
scanf("%s",&clientes[codigo].dataNascimento);
break;
case '4':
printf("\nColoque o novo CPF: ");
scanf("%s",&clientes[codigo].cpf);
break;
case '5':
printf("\nColoque o novo telefone: ");
scanf("%s",&clientes[codigo].telefone);
break;
case '6':
printf("\nColoque o novo e-mail: ");
scanf("%s",&clientes[codigo].email);
break;
default:
printf("\nOpção inválida!");
}
printf("\nContinuar editando? 0 para sim e 1 para não: ");
confirm[0] = getche();
}while(confirm[0] !='1');
}
}
int main(){
//vrau();
setlocale(LC_ALL,"portuguese");
char opcao[1];
char flag[1];
int param=0;
char paramChar[50];
char escolha[1];
flag[0] = '0';
printf("\nCadstro de clientes HyperSoft\n_____________________________\n");
Sleep(500);
do{
printf("\n\nSelecione uma opção:\n\n");
printf("1 - Cadastro do cliente\n");
printf("2 - Alterar dados do cliente\n");
printf("3 - Exclusão de cliente\n");
printf("4 - Consultar cliente\n");
printf("5 - Listar clientes\n");
printf("6 - Sair\n");
printf("Sua opção: ");
fflush(stdin);
opcao[0] = getche();
system("cls");
switch(opcao[0]){
system("cls");
case '1':
cadastrar();
break;
case '2':
printf("\nInsira o código do cliente a ser alterado: ");
scanf("%i",¶m);
alterar(param);
break;
case '3':
printf("\nInsira o código do cliente a ser exclúido: ");
scanf("%i",¶m);
excluir(param);
break;
case '4':
printf("\n1 - Consultar por nome\n2 - Consultar por código\n3 - Voltar\nSua opção: ");
fflush(stdin);
escolha[0] = getche();
switch(escolha[0]){
case '1':
printf("\nInsira o nome do cliente a ser consultado: ");
scanf(" %[^\n]s",¶mChar);
consultarNome(paramChar);
break;
case '2':
printf("\nInsira o código do cliente a ser consultado: ");
scanf("%i",¶m);
consultarCod(param);
break;
case '3':
break;
default:
printf("\nOpção mal informada");
}
break;
case '5':
listar();
break;
case '6':
printf("\nPressione 1 para sair: ");
flag[0] = getche();
break;
default:
printf("\nEstá opção não existe\n");
break;
}
}while(flag[0] != '1');
printf("\n\aFIM");
return 0;
}
| [
"[email protected]"
] | |
95790908e8d1d2460d9b4d434899e825f5607a16 | 34bbcd08f3d14f265c507b49746e2997d74ec519 | /SFML-MashSim/Spring.cpp | eef2414f96c2c0fe7ea2e01d2dc4757e9a9b4d57 | [] | no_license | SenKetZu/SFML-MashSim | cd866d6dc083d1b064f365511fbdcb79aca7f8b0 | 532b6ca3341888efc0b2a62bdc59301a92075711 | refs/heads/master | 2023-05-27T23:01:36.185419 | 2021-06-09T02:57:41 | 2021-06-09T02:57:41 | 374,864,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include "Spring.h"
#include "DrawAgent.h"
Spring::Spring(MassPoint& anchor, MassPoint& exterior):
_Anchor(anchor),
_Exterior(exterior),
_Spring(exterior<<=anchor),
_SpringLenght(100.0f),
_K(10.0f),
_Damping(1.0f),
_TimeSP(.01f),
//variables trancicion
_SpringForce(0.0f),
_DampForce(0.0f),
_Accel(0.0f),
_Vel(0.0f),
_Force(0.0f)
{}
void Spring::Update()
{
//get timesp
_TimeSP = DrawAgent::getInstance().DeltaTime()*100.0f;
//calcular spring
_Spring = _Exterior <<= _Anchor;
//calculo de fuerzas
_SpringForce = _K * (_Spring.getMagnitude() - _SpringLenght);
_DampForce = _Damping * _Vel;
_Force = _SpringForce +10 /*massXgrav*/ - _DampForce;
_Accel = _Force / 1 /*mass*/;
_Vel += _Accel * _TimeSP;
//push masspoint
_Exterior.push(MathVector(_Vel*_TimeSP,_Spring.getAngle()));
} | [
"[email protected]"
] | |
a4107844dad660b1e38707bc33b03c52f16b4cbd | 61442c0297fef23453b7bc43ab5bbd6a52c95fa7 | /grappletation/Source/Grappletation/Gem.cpp | 44c2698bb81fe1bfc4a986a9d39c8944aae59d65 | [] | no_license | AshleyThew/GameProgramming | c9cf634ef81dd7e1753b3ef45d56a6ee38b9a072 | 22032cf7b141222d498c083527e81a854864e694 | refs/heads/main | 2023-08-23T15:51:59.141006 | 2021-10-25T10:01:57 | 2021-10-25T10:01:57 | 420,814,528 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 778 | cpp | #include "Gem.h"
#include "Entity.h"
#include "Renderer.h"
#include "Sprite.h"
Gem::Gem(int x, int y)
{
id.x = x;
id.y = y;
}
Gem::~Gem()
{
}
bool
Gem::Initialise(Renderer& renderer, const char* gemType, float scale)
{
m_pSprite = renderer.CreateSprite(gemType);
m_pSprite->SetScale(scale);
m_position.x = (scale * 8) + (id.x * scale * 16);
m_position.y = (scale * 8) + (id.y * scale * 16);
Reset();
return false;
}
void
Gem::Process(float deltaTime)
{
Entity::Process(deltaTime);
}
void
Gem::Draw(Renderer& renderer)
{
Entity::Draw(renderer);
}
bool
Gem::GetCollected()
{
return collected;
}
void
Gem::SetCollected()
{
collected = true;
SetDead(true);
}
void
Gem::Reset()
{
collected = false;
SetDead(false);
}
Vector2
Gem::GetID()
{
return id;
}
| [
"[email protected]"
] | |
6121382505592535a09b239e90ed50ff680fc2e6 | 91fcb836ee5af301a2125624ddb96cf49b19494d | /queue/restoreQueue.cpp | 2e49fc23784e34f26b2deade801fe414d1b21cb1 | [] | no_license | hellozxs/C | fe11911222595ffcdc425218407711bbe59a3b10 | 1f3815966a8d5668f149ff9957672819a2d2b57d | refs/heads/master | 2020-04-06T07:03:14.596747 | 2016-09-18T10:25:27 | 2016-09-18T10:25:27 | 65,121,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,272 | cpp | //对一个队列执行以下操作后,发现输出为 1,2,3,4,……,n
// 操作:(如果队列不为空)
// 1:取队头元素,放入队尾,将队头pop
// 2;输出队头,将队头pop
// 输入n,求原始队列?
//
//输入:z -> 表示将要输入的数据的个数
//输入z个n的具体值
#include <iostream>
#include <vector>
using namespace std;
typedef struct MyData
{
int _data;
bool _flag;
}MyData;
int main()
{
int z;
cin >> z;
vector<int> arr(z);
for (int i = 0; i < z; i++)
{
cin >> arr[i];
}
int i = 0;
for (i = 0; i< z; i++)
{
if (arr[i] == 1)
cout << 1 << endl;
else
{
vector<MyData> a(arr[i]);
int j = 0;
int count = arr[i];
int tmp = 1;
for (; count--; j ++)
{
int flag = 1;
while (flag)
{
if (j == arr[i])
j = 0;
if (a[j]._flag == false)
flag--;
j++;
}
if (j == arr[i])
j = 0;
while (a[j]._flag == true)
{
j++;
if (j == arr[i])
j = 0;
}
a[j]._data =tmp++;
a[j]._flag = true;
}
int k = 0;
for (; k < arr[i]; k++)
cout << a[k]._data << " ";
cout << endl;
}
}
return 0;
}
| [
"[email protected]"
] | |
0e5baca75fdd2c54621542f6cf7b7bde1bdf4164 | fdebe3129bb47afc1924e45e1ed3c97ee9213ac4 | /GA-TSP/test.cpp | 3bbfaacce92afe022185cf0c23ee0c0d44e5e17d | [] | no_license | SYSU532/artificial-intelligence | 3604e07b3670555d65ac2d36dbbf458f69658a07 | e0847fb1d181415137580e1c3e529e2120ed09d4 | refs/heads/master | 2020-04-05T20:26:14.953187 | 2019-01-11T12:50:27 | 2019-01-11T12:50:27 | 157,179,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | #include <node.h>
namespace demo{
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Number;
// Method1 实现一个 输出"hello world ONE !" 的方法
void Method1(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world ONE !"));
}
// Method2 实现一个 加一 的方法
void Method2(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = args.GetIsolate();
Local<Number> value = Local<Number>::Cast(args[0]);
double num = value->NumberValue() + 1;
char buf[128] = {0};
sprintf(buf,"%f", num);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, buf));
}
void init(Local<Object> exports){
NODE_SET_METHOD(exports, "hello1", Method1);
NODE_SET_METHOD(exports, "addOne", Method2);
}
NODE_MODULE(addon, init)
} | [
"[email protected]"
] | |
921e1b5170f7720987763bafac17b4348a900a5c | 9053a16ac04bc9b1273c8d8c31ab9d6e299ba1c6 | /unittest/test_boxqp.cpp | c40951d78f74638bfead8aaa863057b94743abff | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ggory15/crocoddyl | 7b734313b46a137b44f33d5448057507e23a7fa1 | 4708428676f596f93ffe2df739faeb5cc38d2326 | refs/heads/master | 2021-02-08T06:08:35.739839 | 2020-08-03T15:06:49 | 2020-08-05T13:46:45 | 244,117,610 | 0 | 0 | BSD-3-Clause | 2020-03-01T09:02:49 | 2020-03-01T09:02:48 | null | UTF-8 | C++ | false | false | 6,040 | cpp | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2019-2020, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <boost/random.hpp>
#include "crocoddyl/core/solvers/box-qp.hpp"
#include "unittest_common.hpp"
using namespace boost::unit_test;
using namespace crocoddyl::unittest;
void test_constructor() {
// Setup the test
std::size_t nx = random_int_in_range(1, 100);
crocoddyl::BoxQP boxqp(nx);
// Test dimension of the decision vector
BOOST_CHECK(boxqp.get_nx() == nx);
}
void test_unconstrained_qp_with_identity_hessian() {
std::size_t nx = random_int_in_range(2, 5);
crocoddyl::BoxQP boxqp(nx);
boxqp.set_reg(0.);
Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx);
Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx);
Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);
Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);
Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx);
crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);
// Checking the solution of the problem. Note that it the negative of the gradient since Hessian
// is identity matrix
BOOST_CHECK((sol.x + gradient).isMuchSmallerThan(1.0, 1e-9));
// Checking the solution against a regularized case
double reg = random_real_in_range(1e-9, 1e2);
boxqp.set_reg(reg);
crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);
BOOST_CHECK((sol_reg.x + gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9));
// Checking the all bounds are free and zero clamped
BOOST_CHECK(sol.free_idx.size() == nx);
BOOST_CHECK(sol.clamped_idx.size() == 0);
BOOST_CHECK(sol_reg.free_idx.size() == nx);
BOOST_CHECK(sol_reg.clamped_idx.size() == 0);
}
void test_unconstrained_qp() {
std::size_t nx = random_int_in_range(2, 5);
crocoddyl::BoxQP boxqp(nx);
boxqp.set_reg(0.);
Eigen::MatrixXd H = Eigen::MatrixXd::Random(nx, nx);
Eigen::MatrixXd hessian = H.transpose() * H;
hessian = 0.5 * (hessian + hessian.transpose()).eval();
Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx);
Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);
Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);
Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx);
crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);
// Checking the solution against the KKT solution
Eigen::VectorXd xkkt = -hessian.inverse() * gradient;
BOOST_CHECK((sol.x - xkkt).isMuchSmallerThan(1.0, 1e-9));
// Checking the solution against a regularized KKT problem
double reg = random_real_in_range(1e-9, 1e2);
boxqp.set_reg(reg);
crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);
Eigen::VectorXd xkkt_reg = -(hessian + reg * Eigen::MatrixXd::Identity(nx, nx)).inverse() * gradient;
BOOST_CHECK((sol_reg.x - xkkt_reg).isMuchSmallerThan(1.0, 1e-9));
// Checking the all bounds are free and zero clamped
BOOST_CHECK(sol.free_idx.size() == nx);
BOOST_CHECK(sol.clamped_idx.size() == 0);
BOOST_CHECK(sol_reg.free_idx.size() == nx);
BOOST_CHECK(sol_reg.clamped_idx.size() == 0);
}
void test_box_qp_with_identity_hessian() {
std::size_t nx = random_int_in_range(2, 5);
crocoddyl::BoxQP boxqp(nx);
boxqp.set_reg(0.);
Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx);
Eigen::VectorXd gradient = Eigen::VectorXd::Ones(nx);
for (std::size_t i = 0; i < nx; ++i) {
gradient(i) *= random_real_in_range(-1., 1.);
}
Eigen::VectorXd lb = Eigen::VectorXd::Zero(nx);
Eigen::VectorXd ub = Eigen::VectorXd::Ones(nx);
Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx);
crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);
// The analytical solution is the a bounded, and negative, gradient
Eigen::VectorXd negbounded_gradient(nx), negbounded_gradient_reg(nx);
std::size_t nf = nx, nc = 0, nf_reg = nx, nc_reg = 0;
double reg = random_real_in_range(1e-9, 1e2);
for (std::size_t i = 0; i < nx; ++i) {
negbounded_gradient(i) = std::max(std::min(-gradient(i), ub(i)), lb(i));
negbounded_gradient_reg(i) = std::max(std::min(-gradient(i) / (1 + reg), ub(i)), lb(i));
if (negbounded_gradient(i) != -gradient(i)) {
nc += 1;
nf -= 1;
}
if (negbounded_gradient_reg(i) != -gradient(i) / (1 + reg)) {
nc_reg += 1;
nf_reg -= 1;
}
}
// Checking the solution of the problem. Note that it the negative of the gradient since Hessian
// is identity matrix
BOOST_CHECK((sol.x - negbounded_gradient).isMuchSmallerThan(1.0, 1e-9));
// Checking the solution against a regularized case
boxqp.set_reg(reg);
crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);
BOOST_CHECK((sol_reg.x - negbounded_gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9));
// Checking the all bounds are free and zero clamped
BOOST_CHECK(sol.free_idx.size() == nf);
BOOST_CHECK(sol.clamped_idx.size() == nc);
BOOST_CHECK(sol_reg.free_idx.size() == nf_reg);
BOOST_CHECK(sol_reg.clamped_idx.size() == nc_reg);
}
void register_unit_tests() {
framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_constructor)));
framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp_with_identity_hessian)));
framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp)));
framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_box_qp_with_identity_hessian)));
}
bool init_function() {
register_unit_tests();
return true;
}
int main(int argc, char* argv[]) { return ::boost::unit_test::unit_test_main(&init_function, argc, argv); }
| [
"[email protected]"
] | |
a702a5d40a3a672624e691115d63b4a004c979d0 | 7aa189c718f8a63c256685a435d027ace3833f6b | /include/ogonek/error.h++ | ca7ff1f2bc1d6ac11fcbdaacee61fbdef1c7430d | [
"CC0-1.0"
] | permissive | rmartinho/ogonek | d5523145108de1255298a17c1c25065beb19b82c | 0042f30c6c674effd21d379c53658c88054c58b9 | refs/heads/devel | 2020-05-21T15:17:39.490890 | 2019-09-29T10:58:31 | 2019-09-29T10:58:31 | 8,255,019 | 16 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,549 | // Ogonek
//
// Written in 2017 by Martinho Fernandes <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
/**
* Error handling
* ==============
*/
#ifndef OGONEK_ERROR_HPP
#define OGONEK_ERROR_HPP
#include <ogonek/error_fwd.h++>
#include <ogonek/concepts.h++>
#include <ogonek/types.h++>
#include <ogonek/encoding.h++>
#include <range/v3/range_concepts.hpp>
#include <range/v3/range_traits.hpp>
#include <stdexcept>
namespace ogonek {
/**
* .. class:: unicode_error
*
* The base class for all Unicode-related errors.
*/
struct unicode_error
: virtual std::exception {
char const* what() const noexcept override {
return u8"Unicode error";
}
};
/**
* .. class:: template <EncodingForm Encoding>\
* encode_error : virtual unicode_error
*
* :thrown: when an error occurs during an encoding operation.
*/
template <typename Encoding>
struct encode_error
: virtual unicode_error {
CONCEPT_ASSERT(EncodingForm<Encoding>());
char const* what() const noexcept override {
return u8"encoding failed ";
}
};
/**
* .. class:: template <EncodingForm Encoding>\
* decode_error : virtual unicode_error
*
* :thrown: when an error occurs during a decoding operation.
*/
template <typename Encoding>
struct decode_error
: virtual unicode_error {
CONCEPT_ASSERT(EncodingForm<Encoding>());
char const* what() const noexcept override {
return u8"decoding failed";
}
};
/**
* .. var:: auto assume_valid
*
* A tag used to request that encoding/decoding functions assume the
* input has been validated before.
*
* .. warning::
*
* Using this tag with input that isn't actually valid yields
* undefined behavior.
*/
struct assume_valid_t {} constexpr assume_valid {};
/**
* .. var:: auto discard_errors
*
* An error handler for encoding/decoding functions that simply
* discards the portions of the input that have errors.
*/
struct discard_errors_t {
template <typename E>
optional<code_point> operator()(E) const {
return {};
}
} constexpr discard_errors {};
CONCEPT_ASSERT(EncodeErrorHandler<discard_errors_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<discard_errors_t, archetypes::EncodingForm>());
/**
* .. var:: auto replace_errors
*
* An error handler for encoding/decoding functions that replaces
* portions of the input that have errors with a replacement character.
* When decoding, this is |u-fffd|, but when encoding and the target
* doesn't support it, some encoding-specific character is used
* instead.
*/
struct replace_errors_t {
template <typename Encoding,
CONCEPT_REQUIRES_(EncodingForm<Encoding>())>
optional<code_point> operator()(encode_error<Encoding>) const {
return replacement_character_v<Encoding>;
}
template <typename Encoding,
CONCEPT_REQUIRES_(EncodingForm<Encoding>())>
optional<code_point> operator()(decode_error<Encoding>) const {
return { U'\uFFFD' };
}
} constexpr replace_errors {};
CONCEPT_ASSERT(EncodeErrorHandler<replace_errors_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<replace_errors_t, archetypes::EncodingForm>());
/**
* .. var:: auto throw_error
*
* An error handler for encoding/decoding functions that throws when an
* error is found in the input.
*/
struct throw_error_t {
template <typename E>
optional<code_point> operator()(E e) const {
throw e;
}
} constexpr throw_error {};
CONCEPT_ASSERT(EncodeErrorHandler<throw_error_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<throw_error_t, archetypes::EncodingForm>());
} // namespace ogonek
#endif // OGONEK_ERROR_HPP
| [
"[email protected]"
] | ||
fdb075167409c531a8ffa63f4eb5c358ff9f4c08 | 8da9d3c3e769ead17f5ad4a4cba6fb3e84a9e340 | /src/chila/lib/node/util.hpp | 51b98169af1da8738e7ec4fea35fe3d0da6b3455 | [] | no_license | blockspacer/chila | 6884a540fafa73db37f2bf0117410c33044adbcf | b95290725b54696f7cefc1c430582f90542b1dec | refs/heads/master | 2021-06-05T10:22:53.536352 | 2016-08-24T15:07:49 | 2016-08-24T15:07:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,721 | hpp | /* Copyright 2011-2015 Roberto Daniel Gimenez Gamarra ([email protected])
* (C.I.: 1.439.390 - Paraguay)
*/
#ifndef CHILA_LIB_NODE__UTIL_HPP
#define CHILA_LIB_NODE__UTIL_HPP
#include <chila/lib/misc/util.hpp>
#include "exceptions.hpp"
#define my_assert CHILA_LIB_MISC__ASSERT
#define CHILA_META_NODE__DEF_CHECK_BASES_ELEM(n, data, elem) \
chila::lib::node::checkAndAdd(list, [&]{ elem::check(newData.get()); });
#define CHILA_META_NODE__DEF_CHECK_BASES(Bases, defMyCheck) \
BOOST_PP_IF(defMyCheck, chila::lib::node::CheckDataUPtr createCheckData(chila::lib::node::CheckData *data) const;, ); \
BOOST_PP_IF(defMyCheck, void myCheck(chila::lib::node::CheckData *data = nullptr) const;, ); \
void check(chila::lib::node::CheckData *data = nullptr) const override \
{ \
chila::lib::node::CheckExceptionList list; \
auto newData = BOOST_PP_IF(defMyCheck, createCheckData(data), chila::lib::node::CheckDataUPtr()); \
BOOST_PP_SEQ_FOR_EACH(CHILA_META_NODE__DEF_CHECK_BASES_ELEM,,Bases) \
BOOST_PP_IF(defMyCheck, BOOST_PP_IDENTITY(\
chila::lib::node::checkAndAdd(list, [&]{ myCheck(newData.get()); }); \
), BOOST_PP_EMPTY)(); \
if (!list.exceptions.empty()) throw list; \
}
#define CHILA_META_NODE__DEF_CHECK \
void check(chila::lib::node::CheckData *data = nullptr) const override;
#include "nspDef.hpp"
MY_NSP_START
{
template <typename CheckFun>
void checkAndAdd(chila::lib::node::CheckExceptionList &list, const CheckFun &checkFun) try
{
checkFun();
}
catch (ExceptionWrapper &ex)
{
list.add(ex.ex);
}
catch (CheckExceptionList &ex)
{
list.add(ex);
}
catch (Exception &ex)
{
list.add(ex);
}
chila::lib::misc::Path getNodePath(const Node &node); // to avoid cyclical dependency
template <typename Fun>
inline auto catchThrow(const Node &node, const Fun &fun) -> decltype(fun()) try
{
return fun();
}
catch (const boost::exception &ex)
{
ex << chila::lib::misc::ExceptionInfo::Path(getNodePath(node));
throw;
}
template <typename ToType, typename Node>
inline const ToType &castNode(const Node &node) try
{
return catchThrow(node, [&]() -> const ToType& { return chila::lib::misc::dynamicCast<ToType>(node); });
}
catch (const boost::exception &ex)
{
InvalidNode exx;
insert_error_info(chila::lib::misc::ExceptionInfo::TypeFrom)
insert_error_info(chila::lib::misc::ExceptionInfo::TypeTo)
insert_error_info(chila::lib::misc::ExceptionInfo::ActualType)
insert_error_info(chila::lib::misc::ExceptionInfo::Path)
BOOST_THROW_EXCEPTION(exx);
}
template <typename ToType, typename Node>
inline ToType &castNode(Node &node) try
{
return catchThrow(node, [&]() -> ToType& { return chila::lib::misc::dynamicCast<ToType>(node); });
}
catch (const boost::exception &ex)
{
InvalidNode exx;
insert_error_info(chila::lib::misc::ExceptionInfo::TypeFrom)
insert_error_info(chila::lib::misc::ExceptionInfo::TypeTo)
insert_error_info(chila::lib::misc::ExceptionInfo::ActualType)
insert_error_info(chila::lib::misc::ExceptionInfo::Path)
BOOST_THROW_EXCEPTION(exx);
}
NodeWithChildren &mainParent(NodeWithChildren &node);
PathVec getReferences(
NodeWithChildren &node,
const chila::lib::misc::Path &path);
void replaceReferences(NodeWithChildren &node, const PathVec &paths, const Node &newRefNode);
}
MY_NSP_END
#include "nspUndef.hpp"
#endif
| [
"[email protected]"
] | |
f387d41d0e3251ca4e290372f77e819aa8f41c08 | 8c8ea797b0821400c3176add36dd59f866b8ac3d | /AOJ/aoj0578.cpp | 9b35642e4fd0541224a11ccbbf275376f137bc2c | [] | no_license | fushime2/competitive | d3d6d8e095842a97d4cad9ca1246ee120d21789f | b2a0f5957d8ae758330f5450306b629006651ad5 | refs/heads/master | 2021-01-21T16:00:57.337828 | 2017-05-20T06:45:46 | 2017-05-20T06:45:46 | 78,257,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
int N;
bool isName(string shop, string board) {
int m = board.length();
for(int step=1; step<=m; step++) {
for(int i=0; i<m; i++) {
string s = "";
for(int j=i; j<m; j+=step) {
s += board[j];
}
if(s.find(shop) != string::npos) return true;
}
}
return false;
}
int main(void) {
cin >> N;
string shop, board;
cin >> shop;
int ans = 0;
for(int i=0; i<N; i++) {
cin >> board;
if(isName(shop, board)) ans++;
}
cout << ans << endl;
return 0;
}
| [
"[email protected]"
] | |
9b6b1ec168b70a357f4e47169b73b0f2e0538b9b | 6565182c28637e21087007f09d480a70b387382e | /code/901.股票价格跨度.cpp | 61b63105d48efcafe008368d50a272d85d3e8c15 | [] | no_license | liu-jianhao/leetcode | 08c070f0f140b2dd56cffbbaf25868364addfe53 | 7cbbe0585778517c88aa6ac1d2f2f8478cc931e5 | refs/heads/master | 2021-07-17T05:54:58.228956 | 2020-08-17T07:03:52 | 2020-08-17T07:03:52 | 188,854,718 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | /*
* @lc app=leetcode.cn id=901 lang=cpp
*
* [901] 股票价格跨度
*/
class StockSpanner {
public:
StockSpanner() {
}
int next(int price) {
if(_i == 0 || price < _prices.back())
{
_dp.push_back(1);
}
else
{
int j = _i - 1;
while(j >= 0 && price >= _prices[j])
{
j -= _dp[j];
}
_dp.push_back(_i - j);
}
++_i;
_prices.push_back(price);
return _dp.back();
}
private:
vector<int> _dp;
vector<int> _prices;
int _i = 0;
};
/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner* obj = new StockSpanner();
* int param_1 = obj->next(price);
*/
| [
"[email protected]"
] | |
c1be7ed8331d413fbb32c4f4da225eabb0c94905 | 2d4346d0da0a4145f6bcc91a8cb2c0ab4d669d7e | /chat-up-server/src/Authentication/AuthenticationService.h | b172c8a7281e736007294715851af51947b6b669 | [] | no_license | xgallom/chat-up | 5570d069a495acf6398bdf1f62b1fb1d91289376 | 7cb664ce745cf041fb508b04165d2179563aa010 | refs/heads/master | 2020-04-18T05:40:58.487905 | 2019-01-29T22:36:04 | 2019-01-29T22:36:04 | 167,287,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | h | //
// Created by xgallom on 1/27/19.
//
#ifndef CHAT_UP_AUTHENTICATIONSERVICE_H
#define CHAT_UP_AUTHENTICATIONSERVICE_H
#include <Messaging/Message.h>
#include <Messaging/MessageSender.h>
#include <Outcome.h>
#include <Authentication/User.h>
class AuthenticationStorage;
class AuthenticationService {
AuthenticationStorage &m_storage;
User m_user = User();
public:
AuthenticationService() noexcept;
Outcome::Enum run(MessageSender &sender, const Message &message);
bool registerUser(const User &user);
User user() const noexcept;
};
#endif //CHAT_UP_AUTHENTICATIONSERVICE_H
| [
"[email protected]"
] | |
d906994d3f90133151039af0434882e3553ba719 | 1c02e13a776e5e8bc3e2a6182b5df4efb2c71d32 | /core/unit_test/tstDeepCopy.hpp | b3fdab4da5ef0b61357d256cf996dae1b69884f0 | [
"BSD-3-Clause"
] | permissive | junghans/Cabana | 91b82827dd9fb8321bea9ea3750c196946a6aac0 | 7b9078f81bde68c949fd6ae913ce80eeaf0f8f8a | refs/heads/master | 2021-06-14T09:57:01.658234 | 2019-01-04T22:24:45 | 2019-01-04T22:24:45 | 150,330,482 | 1 | 1 | BSD-3-Clause | 2019-01-07T16:24:20 | 2018-09-25T21:17:53 | C++ | UTF-8 | C++ | false | false | 5,252 | hpp | /****************************************************************************
* Copyright (c) 2018 by the Cabana authors *
* All rights reserved. *
* *
* This file is part of the Cabana library. Cabana is distributed under a *
* BSD 3-clause license. For the licensing terms see the LICENSE file in *
* the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <Cabana_DeepCopy.hpp>
#include <Cabana_AoSoA.hpp>
#include <Cabana_Types.hpp>
#include <gtest/gtest.h>
namespace Test
{
//---------------------------------------------------------------------------//
// Check the data given a set of values.
template<class aosoa_type>
void checkDataMembers(
aosoa_type aosoa,
const float fval, const double dval, const int ival,
const int dim_1, const int dim_2, const int dim_3 )
{
auto slice_0 = aosoa.template slice<0>();
auto slice_1 = aosoa.template slice<1>();
auto slice_2 = aosoa.template slice<2>();
auto slice_3 = aosoa.template slice<3>();
for ( std::size_t idx = 0; idx < aosoa.size(); ++idx )
{
// Member 0.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
for ( int k = 0; k < dim_3; ++k )
EXPECT_EQ( slice_0( idx, i, j, k ),
fval * (i+j+k) );
// Member 1.
EXPECT_EQ( slice_1( idx ), ival );
// Member 2.
for ( int i = 0; i < dim_1; ++i )
EXPECT_EQ( slice_2( idx, i ), dval * i );
// Member 3.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
EXPECT_EQ( slice_3( idx, i, j ), dval * (i+j) );
}
}
//---------------------------------------------------------------------------//
// Perform a deep copy test.
template<class DstMemorySpace, class SrcMemorySpace,
int DstVectorLength, int SrcVectorLength>
void testDeepCopy()
{
// Data dimensions.
const int dim_1 = 3;
const int dim_2 = 2;
const int dim_3 = 4;
// Declare data types.
using DataTypes =
Cabana::MemberTypes<float[dim_1][dim_2][dim_3],
int,
double[dim_1],
double[dim_1][dim_2]
>;
// Declare the AoSoA types.
using DstAoSoA_t = Cabana::AoSoA<DataTypes,DstMemorySpace,DstVectorLength>;
using SrcAoSoA_t = Cabana::AoSoA<DataTypes,SrcMemorySpace,SrcVectorLength>;
// Create AoSoAs.
int num_data = 357;
DstAoSoA_t dst_aosoa( num_data );
SrcAoSoA_t src_aosoa( num_data );
// Initialize data with the rank accessors.
float fval = 3.4;
double dval = 1.23;
int ival = 1;
auto slice_0 = src_aosoa.template slice<0>();
auto slice_1 = src_aosoa.template slice<1>();
auto slice_2 = src_aosoa.template slice<2>();
auto slice_3 = src_aosoa.template slice<3>();
for ( std::size_t idx = 0; idx < src_aosoa.size(); ++idx )
{
// Member 0.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
for ( int k = 0; k < dim_3; ++k )
slice_0( idx, i, j, k ) = fval * (i+j+k);
// Member 1.
slice_1( idx ) = ival;
// Member 2.
for ( int i = 0; i < dim_1; ++i )
slice_2( idx, i ) = dval * i;
// Member 3.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
slice_3( idx, i, j ) = dval * (i+j);
}
// Deep copy
Cabana::deep_copy( dst_aosoa, src_aosoa );
// Check values.
checkDataMembers( dst_aosoa, fval, dval, ival, dim_1, dim_2, dim_3 );
}
//---------------------------------------------------------------------------//
// TESTS
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_to_host_same_layout_test )
{
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,16>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_from_host_same_layout_test )
{
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,16>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_to_host_different_layout_test )
{
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,32>();
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,64,8>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_from_host_different_layout_test )
{
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,64,8>();
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,32>();
}
//---------------------------------------------------------------------------//
} // end namespace Test
| [
"[email protected]"
] | |
cb50f617109e0944e114883af3fc3af8be9a6b7e | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_Buff_PreventDismount_functions.cpp | 7e18c4f1010b3ae0b9f98e0ea4d779d40e1340ba | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | cpp | // ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Buff_PreventDismount_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function Buff_PreventDismount.Buff_PreventDismount_C.UserConstructionScript
// ()
void ABuff_PreventDismount_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function Buff_PreventDismount.Buff_PreventDismount_C.UserConstructionScript");
ABuff_PreventDismount_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Buff_PreventDismount.Buff_PreventDismount_C.ExecuteUbergraph_Buff_PreventDismount
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void ABuff_PreventDismount_C::ExecuteUbergraph_Buff_PreventDismount(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Buff_PreventDismount.Buff_PreventDismount_C.ExecuteUbergraph_Buff_PreventDismount");
ABuff_PreventDismount_C_ExecuteUbergraph_Buff_PreventDismount_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
5ac2daee273b036045797a05ba6d6c787fc58545 | 3ec6a0f09686dfc885fce0c60b1cf25e24fe4dd0 | /obs-node/src/cpp_old/display.cpp | a8bcfa820cdbe66dad1260e0bd265bb13b394bb9 | [] | no_license | aidangoettsch/hydro-bot | dcaff8ce46970f87aef4d36f5c86b81f6b9979c4 | ecbb3902ea0de38de7f39a372aee9c0cb375e6df | refs/heads/master | 2023-03-22T10:35:28.261052 | 2021-03-11T17:07:31 | 2021-03-11T17:07:31 | 335,796,934 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,609 | cpp | // Most of code in this file are copied from
// https://github.com/stream-labs/obs-studio-node/blob/staging/obs-studio-server/source/nodeobs_display.cpp
#include "display.h"
#include "./platform/platform.h"
Display::Display(void *parentHandle, int scaleFactor, std::string &sourceName) {
this->parentHandle = parentHandle;
this->scaleFactor = scaleFactor;
// create window for display
this->windowHandle = createDisplayWindow(parentHandle);
// create display
gs_init_data gs_init_data = {};
gs_init_data.adapter = 0;
gs_init_data.cx = 1;
gs_init_data.cy = 1;
gs_init_data.num_backbuffers = 1;
gs_init_data.format = GS_RGBA;
gs_init_data.zsformat = GS_ZS_NONE;
#ifdef _WIN32
gs_init_data.window.hwnd = windowHandle;
#elif __APPLE__
gs_init_data.window.view = static_cast<objc_object *>(windowHandle);
#endif
obs_display = obs_display_create(&gs_init_data, 0x0);
if (!obs_display) {
throw std::runtime_error("Failed to create the display");
}
// obs source
obs_source = obs_get_source_by_name(sourceName.c_str());
obs_source_inc_showing(obs_source);
// draw callback
obs_display_add_draw_callback(obs_display, displayCallback, this);
}
Display::~Display() {
obs_display_remove_draw_callback(obs_display, displayCallback, this);
if (obs_source) {
obs_source_dec_showing(obs_source);
obs_source_release(obs_source);
}
if (obs_display) {
obs_display_destroy(obs_display);
}
destroyWindow(windowHandle);
}
void Display::move(int x, int y, int width, int height) {
this->x = x;
this->y = y;
this->width = width;
this->height = height;
moveWindow(windowHandle, x, y, width, height);
obs_display_resize(obs_display, width * scaleFactor, height * scaleFactor);
}
void Display::displayCallback(void *displayPtr, uint32_t cx, uint32_t cy) {
auto *dp = static_cast<Display *>(displayPtr);
// Get proper source/base size.
uint32_t sourceW, sourceH;
if (dp->obs_source) {
sourceW = obs_source_get_width(dp->obs_source);
sourceH = obs_source_get_height(dp->obs_source);
if (sourceW == 0)
sourceW = 1;
if (sourceH == 0)
sourceH = 1;
} else {
obs_video_info ovi = {};
obs_get_video_info(&ovi);
sourceW = ovi.base_width;
sourceH = ovi.base_height;
if (sourceW == 0)
sourceW = 1;
if (sourceH == 0)
sourceH = 1;
}
gs_projection_push();
gs_ortho(0.0f, (float)sourceW, 0.0f, (float)sourceH, -1, 1);
// Source Rendering
obs_source_t *source;
if (dp->obs_source) {
obs_source_video_render(dp->obs_source);
/* If we want to draw guidelines, we need a scene,
* not a transition. This may not be a scene which
* we'll check later. */
if (obs_source_get_type(dp->obs_source) == OBS_SOURCE_TYPE_TRANSITION) {
source = obs_transition_get_active_source(dp->obs_source);
} else {
source = dp->obs_source;
obs_source_addref(source);
}
} else {
obs_render_main_texture();
/* Here we assume that channel 0 holds the primary transition.
* We also assume that the active source within that transition is
* the scene that we need */
obs_source_t *transition = obs_get_output_source(0);
source = obs_transition_get_active_source(transition);
obs_source_release(transition);
}
obs_source_release(source);
gs_projection_pop();
} | [
"[email protected]"
] | |
8b494503d9bf74ff5d28e840affc467e8a440a51 | 34a3165ded55c6ac5ffe2ff17c9996c66e0e80b5 | /cpp/ETProtect.cpp | 989ebb94e3100accc0e0e0fd02bff4f34144df29 | [] | no_license | monkeyde17/et-protect-package | d806a3196c28c4176374bc21e7ec5769faa72347 | 77e04d1834d0723c2de7f424a1cbc1efd2321991 | refs/heads/master | 2016-09-06T05:53:58.824045 | 2014-12-07T02:29:37 | 2014-12-07T02:29:37 | 27,655,865 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,888 | cpp | //
// ETProtect.cpp
// testcpp
//
// Created by etond on 14/12/3.
//
//
#include "ETProtect.h"
bool ETProtect::isOriginPackage()
{
unsigned int uHashValue = calculateValueFromFile();
unsigned int uReadValue = readValueFromFile();
#if (ETPROTECTDEBUG)
CCLOG("[log] -- hash %u", uHashValue);
CCLOG("[log] -- read %u", uReadValue);
#endif
if (uReadValue == 0 || uHashValue == 0)
{
return false;
}
return uReadValue == uHashValue;
}
unsigned int ETProtect::readValueFromFile(std::string filename /* default = config.et */)
{
unsigned int uValue = 0;
Data data = FileUtils::getInstance()->getDataFromFile(filename);
if (data.getSize() > 0)
{
uValue = ((ETProtectData *)data.getBytes())->getHashValue();
}
return uValue;
}
unsigned int ETProtect::calculateValueFromFile(unsigned int seed /* default = 0x12345678 */)
{
std::string path = "";
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo minfo;
bool isHave = JniHelper::getStaticMethodInfo(minfo,
"org/cocos2dx/cpp/AppActivity",
"getPath",
"()Ljava/lang/String;");
if (isHave)
{
jobject jobj = minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID);
/* get the return value */
path = JniHelper::jstring2string((jstring)jobj).c_str();
CCLOG("JNI SUCCESS!");
}
#endif
unsigned int value = 0;
if (path.length() > 0)
{
ssize_t len = 0;
unsigned char *buf = FileUtils::getInstance()->getFileDataFromZip(path, "classes.dex", &len);
if (buf)
{
value = XXH32(buf, len, seed);
}
delete[] buf;
}
return value;
}
| [
"[email protected]"
] | |
4ff557683a174bc39aea59e06a19b563d55927d6 | cde943952b79d67f4972d180d20b97fc823db548 | /preprocesser/preprocesser/self2.hpp | 0892b2563bae695f02d2254829e81a6cb84c630e | [] | no_license | yourgracee/preprocesser | e66a0b0c9680442717652185e9ed2dc5172f7771 | 349453d4092ffe7927b0c1067d3cefc8bf2bdfff | refs/heads/master | 2020-04-09T10:52:16.135824 | 2018-12-04T02:46:03 | 2018-12-04T02:46:03 | 160,285,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,701 | hpp | #ifdef LIMIT_2
#include "tuple.hpp"
#define START_2 TUPLE(0, LIMIT_2)
#define FINISH_2 TUPLE(1, LIMIT_2)
#undef DEPTH
#define DEPTH 2
# if START_2 <= 0 && FINISH_2 >= 0
# define ITERATION_2 0
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 1 && FINISH_2 >= 1
# define ITERATION_2 1
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 2 && FINISH_2 >= 2
# define ITERATION_2 2
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 3 && FINISH_2 >= 3
# define ITERATION_2 3
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 4 && FINISH_2 >= 4
# define ITERATION_2 4
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 5 && FINISH_2 >= 5
# define ITERATION_2 5
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 6 && FINISH_2 >= 6
# define ITERATION_2 6
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 7 && FINISH_2 >= 7
# define ITERATION_2 7
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 8 && FINISH_2 >= 8
# define ITERATION_2 8
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 9 && FINISH_2 >= 9
# define ITERATION_2 9
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 10 && FINISH_2 >= 10
# define ITERATION_2 10
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 11 && FINISH_2 >= 11
# define ITERATION_2 11
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 12 && FINISH_2 >= 12
# define ITERATION_2 12
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 13 && FINISH_2 >= 13
# define ITERATION_2 13
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 14 && FINISH_2 >= 14
# define ITERATION_2 14
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 15 && FINISH_2 >= 15
# define ITERATION_2 15
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 16 && FINISH_2 >= 16
# define ITERATION_2 16
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 17 && FINISH_2 >= 17
# define ITERATION_2 17
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 18 && FINISH_2 >= 18
# define ITERATION_2 18
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 19 && FINISH_2 >= 19
# define ITERATION_2 19
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 20 && FINISH_2 >= 20
# define ITERATION_2 20
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 21 && FINISH_2 >= 21
# define ITERATION_2 21
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 22 && FINISH_2 >= 22
# define ITERATION_2 22
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 23 && FINISH_2 >= 23
# define ITERATION_2 23
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 24 && FINISH_2 >= 24
# define ITERATION_2 24
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 25 && FINISH_2 >= 25
# define ITERATION_2 25
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 26 && FINISH_2 >= 26
# define ITERATION_2 26
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 27 && FINISH_2 >= 27
# define ITERATION_2 27
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 28 && FINISH_2 >= 28
# define ITERATION_2 28
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 29 && FINISH_2 >= 29
# define ITERATION_2 29
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 30 && FINISH_2 >= 30
# define ITERATION_2 30
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 31 && FINISH_2 >= 31
# define ITERATION_2 31
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 32 && FINISH_2 >= 32
# define ITERATION_2 32
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 33 && FINISH_2 >= 33
# define ITERATION_2 33
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 34 && FINISH_2 >= 34
# define ITERATION_2 34
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 35 && FINISH_2 >= 35
# define ITERATION_2 35
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 36 && FINISH_2 >= 36
# define ITERATION_2 36
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 37 && FINISH_2 >= 37
# define ITERATION_2 37
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 38 && FINISH_2 >= 38
# define ITERATION_2 38
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 39 && FINISH_2 >= 39
# define ITERATION_2 39
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 40 && FINISH_2 >= 40
# define ITERATION_2 40
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 41 && FINISH_2 >= 41
# define ITERATION_2 41
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 42 && FINISH_2 >= 42
# define ITERATION_2 42
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 43 && FINISH_2 >= 43
# define ITERATION_2 43
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 44 && FINISH_2 >= 44
# define ITERATION_2 44
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 45 && FINISH_2 >= 45
# define ITERATION_2 45
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 46 && FINISH_2 >= 46
# define ITERATION_2 46
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 47 && FINISH_2 >= 47
# define ITERATION_2 47
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 48 && FINISH_2 >= 48
# define ITERATION_2 48
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 49 && FINISH_2 >= 49
# define ITERATION_2 49
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 50 && FINISH_2 >= 50
# define ITERATION_2 50
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 51 && FINISH_2 >= 51
# define ITERATION_2 51
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 52 && FINISH_2 >= 52
# define ITERATION_2 52
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 53 && FINISH_2 >= 53
# define ITERATION_2 53
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 54 && FINISH_2 >= 54
# define ITERATION_2 54
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 55 && FINISH_2 >= 55
# define ITERATION_2 55
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 56 && FINISH_2 >= 56
# define ITERATION_2 56
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 57 && FINISH_2 >= 57
# define ITERATION_2 57
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 58 && FINISH_2 >= 58
# define ITERATION_2 58
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 59 && FINISH_2 >= 59
# define ITERATION_2 59
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 60 && FINISH_2 >= 60
# define ITERATION_2 60
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 61 && FINISH_2 >= 61
# define ITERATION_2 61
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 62 && FINISH_2 >= 62
# define ITERATION_2 62
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 63 && FINISH_2 >= 63
# define ITERATION_2 63
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 64 && FINISH_2 >= 64
# define ITERATION_2 64
# include FILENAME_2
# undef ITERATION_2
# endif
#undef DEPTH
#define DEPTH 1
#endif | [
"[email protected]"
] | |
fa606684822edaeb65a3facbab4e69b8044c96ef | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/SOC/2011/simd/boost/simd/toolbox/constant/include/constants/minexponent.hpp | 0fd6c857f2cef5aa7fcc1f22aca4daf4a5f7a9c3 | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 232 | hpp | #ifndef BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED
#include <boost/simd/toolbox/constant/constants/minexponent.hpp>
#endif
| [
"[email protected]"
] | |
36a545137c7c8972f084997716e578ad86d3ac15 | afcce85e08d8fc5141a840fe77bf7bf93f49df54 | /tests/2015-09-10/fft_shift/main.cpp | 5fd27aab9e2480a56af1d2bf0dfe2ab2e4eeaa98 | [] | no_license | icopavan/Automatic-Modulation-Classification-ELEN4012 | ff8f58a467129b371a9d2b042169fc99620b2959 | d72e3b4d36ad88b2872a8b33606c120f18b974e6 | refs/heads/master | 2021-01-12T21:07:15.807363 | 2015-10-09T21:29:56 | 2015-10-09T21:29:56 | 44,043,227 | 2 | 1 | null | 2015-10-11T07:30:41 | 2015-10-11T07:30:40 | null | UTF-8 | C++ | false | false | 910 | cpp | #include "mainwindow.h"
#include <QApplication>
#include <fftw3.h>
#include <cmath>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
double PI = 4 * atan(1);
int N = 512; // number of samples
double fs = 10e3; // sampling frequency
double fc = 1000; // signal frequency
double t[N];
fftw_complex * x = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
double f[N];
// calculation
for (int n = 0; n < N; ++n)
{
t[n] = n/fs;
x[n][0] = cos(2*PI*fc*t[n]);
x[n][1] = 0;
f[n] = (n - N/2) * fs / (N-1);
}
fftw_complex *out;
fftw_plan plan_forward;
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
plan_forward = fftw_plan_dft_1d(N, x, out, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(plan_forward);
w.plot(f, out, N);
return a.exec();
}
| [
"[email protected]"
] | |
d46a3b3f4252a9ed58f62fd5e8068ade7c69129b | aa701c8621b90137f250151db3c74881767acb6d | /core/nes/mapper/042.cpp | 20039b24a52dade8d098a2f5e8052ce2675d369c | [] | no_license | ptnnx/e-mulator-PSP | 3215bbfe0870a41b341f207ba11a2d1fe2b64b56 | 538c700096fcef34bba9145750f7f9e44d3e7446 | refs/heads/main | 2023-02-05T09:57:34.046277 | 2020-12-31T08:59:04 | 2020-12-31T08:59:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,026 | cpp | STATIC void NES_mapper42_Init();
STATIC void NES_mapper42_Reset();
STATIC void NES_mapper42_MemoryWrite(u32 addr, u8 data);
STATIC void NES_mapper42_HSync(u32 scanline);
/////////////////////////////////////////////////////////////////////
// Mapper 42
STATIC void NES_mapper42_Init()
{
g_NESmapper.Reset = NES_mapper42_Reset;
g_NESmapper.MemoryWrite = NES_mapper42_MemoryWrite;
g_NESmapper.HSync = NES_mapper42_HSync;
}
STATIC void NES_mapper42_Reset()
{
// set CPU bank pointers
g_NESmapper.set_CPU_bank3(0);
g_NESmapper.set_CPU_bank4(g_NESmapper.num_8k_ROM_banks-4);
g_NESmapper.set_CPU_bank5(g_NESmapper.num_8k_ROM_banks-3);
g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-2);
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
// set PPU bank pointers
g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7);
}
STATIC void NES_mapper42_MemoryWrite(u32 addr, u8 data)
{
switch(addr & 0xE003)
{
case 0x8000:
g_NESmapper.set_PPU_banks8(((data&0x1f)<<3)+0,((data&0x1f)<<3)+1,((data&0x1f)<<3)+2,((data&0x1f)<<3)+3,((data&0x1f)<<3)+4,((data&0x1f)<<3)+5,((data&0x1f)<<3)+6,((data&0x1f)<<3)+7);
break;
case 0xE000:
{
g_NESmapper.set_CPU_bank3(data & 0x0F);
}
break;
case 0xE001:
{
if(data & 0x08)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ);
}
else
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT);
}
}
break;
case 0xE002:
{
if(data & 0x02)
{
g_NESmapper.Mapper42.irq_enabled = 1;
}
else
{
g_NESmapper.Mapper42.irq_enabled = 0;
g_NESmapper.Mapper42.irq_counter = 0;
}
}
break;
}
// LOG("W " << HEX(addr,4) << " " << HEX(data,2) << endl);
}
STATIC void NES_mapper42_HSync(u32 scanline)
{
if(g_NESmapper.Mapper42.irq_enabled)
{
if(g_NESmapper.Mapper42.irq_counter < 215)
{
g_NESmapper.Mapper42.irq_counter++;
}
if(g_NESmapper.Mapper42.irq_counter == 215)
{
NES6502_DoIRQ();
g_NESmapper.Mapper42.irq_enabled = 0;
}
}
}
/////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
bba7327fa47b292b7a2a12379dbea888640a0e70 | 58790459d953a3e4b6722ed3ee939f82d9de8c3e | /my/PDF插件/sdkDC_v1_win/Adobe/Acrobat DC SDK/Version 1/PluginSupport/PIBrokerSDK/simple-ipc-lib/src/pipe_win.h | 4625bef0dc76752fdcc7b3a4966d087839cbd12f | [] | no_license | tisn05/VS | bb84deb993eb18d43d8edaf81afb753afa3d3188 | da56d392a518ba21edcb1a367b4b4378d65506f0 | refs/heads/master | 2020-09-25T05:49:31.713773 | 2016-08-22T01:22:16 | 2016-08-22T01:22:16 | 66,229,337 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,659 | h | // Copyright (c) 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SIMPLE_IPC_PIPE_WIN_H_
#define SIMPLE_IPC_PIPE_WIN_H_
#include "os_includes.h"
#include "ipc_constants.h"
class PipePair {
public:
PipePair(bool inherit_fd2 = false);
HANDLE fd1() const { return srv_; }
HANDLE fd2() const { return cln_; }
static HANDLE OpenPipeServer(const wchar_t* name, bool low_integrity = false);
static HANDLE OpenPipeClient(const wchar_t* name, bool inherit, bool impersonate);
private:
HANDLE srv_;
HANDLE cln_;
};
class PipeWin {
public:
PipeWin();
~PipeWin();
bool OpenClient(HANDLE pipe);
bool OpenServer(HANDLE pipe, bool connect = false);
bool Write(const void* buf, size_t sz);
bool Read(void* buf, size_t* sz);
bool IsConnected() const { return INVALID_HANDLE_VALUE != pipe_; }
private:
HANDLE pipe_;
};
class PipeTransport : public PipeWin {
public:
static const size_t kBufferSz = 4096;
size_t Send(const void* buf, size_t sz) {
return Write(buf, sz) ? ipc::RcOK : ipc::RcErrTransportWrite;
}
char* Receive(size_t* size);
private:
IPCCharVector buf_;
};
#endif // SIMPLE_IPC_PIPE_WIN_H_
| [
"[email protected]"
] | |
ca83a558bcc72c5055c6fbf661b26acbaf1aeb08 | 6701a2c3fb95baba0da5754b88d23f79a2b10f7f | /protocol/mcbp/libmcbp/mcbp_packet_printer.cc | 6329b15ffaeaf2a08d698518c5c195e5ef3a5e8b | [] | no_license | teligent-ru/kv_engine | 80630b4271d72df9c47b505a586f2e8275895d3e | 4a1b741ee22ae3e7a46e21a423451c58186a2374 | refs/heads/master | 2018-11-07T20:52:54.132785 | 2018-01-15T16:34:10 | 2018-01-17T08:29:54 | 117,808,163 | 1 | 0 | null | 2018-01-17T08:34:05 | 2018-01-17T08:34:05 | null | UTF-8 | C++ | false | false | 4,594 | cc | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, 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 <getopt.h>
#include <mcbp/mcbp.h>
#include <platform/dirutils.h>
#include <platform/memorymap.h>
#include <platform/sized_buffer.h>
#include <algorithm>
#include <iostream>
enum class Format { Raw, Gdb, Lldb };
Format parseFormat(std::string format) {
std::transform(format.begin(), format.end(), format.begin(), toupper);
if (format == "RAW") {
return Format::Raw;
}
if (format == "GDB") {
return Format::Gdb;
}
if (format == "LLDB") {
return Format::Lldb;
}
throw std::invalid_argument("Unknown format: " + format);
}
int main(int argc, char** argv) {
Format format{Format::Raw};
static struct option longopts[] = {
{"format", required_argument, nullptr, 'f'},
{nullptr, 0, nullptr, 0}};
int cmd;
while ((cmd = getopt_long(argc, argv, "f:", longopts, nullptr)) != -1) {
switch (cmd) {
case 'f':
try {
format = parseFormat(optarg);
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
break;
default:
std::cerr
<< "Usage: " << cb::io::basename(argv[0])
<< " [options] file1-n" << std::endl
<< std::endl
<< "\t--format=raw|gdb|lldb\tThe format for the input file"
<< std::endl
<< std::endl
<< "For gdb the expected output would be produced by "
"executing: "
<< std::endl
<< std::endl
<< "(gdb) x /24xb c->rcurr" << std::endl
<< "0x7f43387d7e7a: 0x81 0x0d 0x00 0x00 0x00 0x00 0x00 0x00"
<< std::endl
<< "0x7f43387d7e82: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00"
<< std::endl
<< "0x7f43387d7e8a: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00"
<< std::endl
<< std::endl
<< "For lldb the expected output would be generated by "
"executing: "
<< std::endl
<< std::endl
<< "(lldb) x -c 32 c->rbuf" << std::endl
<< "0x7f43387d7e7a: 81 0d 00 01 04 00 00 00 00 00 00 06 00 "
"00 00 06 ................"
<< std::endl
<< "0x7f43387d7e7a: 14 bf f4 26 8a e0 00 00 00 00 00 00 61 "
"61 81 0a ................"
<< std::endl
<< std::endl;
return EXIT_FAILURE;
}
}
if (optind == argc) {
std::cerr << "No file specified" << std::endl;
return EXIT_FAILURE;
}
while (optind < argc) {
try {
cb::byte_buffer buf;
std::vector<uint8_t> data;
cb::MemoryMappedFile map(argv[optind],
cb::MemoryMappedFile::Mode::RDONLY);
map.open();
buf = {static_cast<uint8_t*>(map.getRoot()), map.getSize()};
switch (format) {
case Format::Raw:
break;
case Format::Gdb:
data = cb::mcbp::gdb::parseDump(buf);
buf = {data.data(), data.size()};
break;
case Format::Lldb:
data = cb::mcbp::lldb::parseDump(buf);
buf = {data.data(), data.size()};
break;
}
cb::mcbp::dumpStream(buf, std::cout);
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return EXIT_FAILURE;
}
++optind;
}
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
ab5bc031413c9ef1306cacfd08a9878b7b902ed5 | 35e79b51f691b7737db254ba1d907b2fd2d731ef | /AtCoder/ABC/007/D.cpp | 1f7d6ef9dd955d37b91e67aebfabda6b728594c7 | [] | no_license | rodea0952/competitive-programming | 00260062d00f56a011f146cbdb9ef8356e6b69e4 | 9d7089307c8f61ea1274a9f51d6ea00d67b80482 | refs/heads/master | 2022-07-01T02:25:46.897613 | 2022-06-04T08:44:42 | 2022-06-04T08:44:42 | 202,485,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | cpp | #include <bits/stdc++.h>
#define chmin(a, b) ((a)=min((a), (b)))
#define chmax(a, b) ((a)=max((a), (b)))
#define fs first
#define sc second
#define eb emplace_back
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef tuple<int, int, int> T;
const ll MOD=1e9+7;
const ll INF=1e18;
int dx[]={1, -1, 0, 0};
int dy[]={0, 0, 1, -1};
template <typename T> inline string toString(const T &a){ostringstream oss; oss<<a; return oss.str();};
ll solve(string &s){
int n=s.size();
ll dp[20][2][2];
// dp[決めた桁数][未満フラグ][4または9を含むか] := 求める総数
memset(dp, 0, sizeof(dp));
dp[0][0][0]=1;
for(int i=0; i<n; i++){ // 桁
int D=s[i]-'0';
for(int j=0; j<2; j++){ // 未満フラグ
for(int k=0; k<2; k++){ // k=1 のとき4または9を含む
for(int d=0; d<=(j?9:D); d++){
dp[i+1][j || (d<D)][k || d==4 || d==9]+=dp[i][j][k];
}
}
}
}
return dp[n][0][1]+dp[n][1][1];
}
int main(){
ll a, b; cin>>a>>b;
string A=toString(a-1), B=toString(b);
cout << solve(B) - solve(A) << endl;
}
| [
"[email protected]"
] | |
73bbdcfbe50a724cb152edeb3ed8f2aed3d76d69 | 28b90ad96790edd30edc5ba95137cc20261599b5 | /nodemcu/MPU_6050_flask_json/MPU_6050_flask_json.ino | 134d2fabdbfb2a13cb534495c378ee4397e38c4e | [] | no_license | anshulahuja98/Codefundo-18-IITJ | b09e1b200a5e5d9bbe23f58addc3460a1a19d732 | bfae0dde99cd9133bdeabd06fdb73b512214b1f9 | refs/heads/master | 2020-03-30T01:52:30.166915 | 2019-02-10T04:34:35 | 2019-02-10T04:34:35 | 150,599,578 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,804 | ino |
#include <Wire.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
const uint8_t MPU6050SlaveAddress = 0x68;
const uint8_t scl = D1;
const uint8_t sda = D2;
const uint16_t AccelScaleFactor = 16384;
const uint16_t GyroScaleFactor = 131;
const uint8_t MPU6050_REGISTER_SMPLRT_DIV = 0x19;
const uint8_t MPU6050_REGISTER_USER_CTRL = 0x6A;
const uint8_t MPU6050_REGISTER_PWR_MGMT_1 = 0x6B;
const uint8_t MPU6050_REGISTER_PWR_MGMT_2 = 0x6C;
const uint8_t MPU6050_REGISTER_CONFIG = 0x1A;
const uint8_t MPU6050_REGISTER_GYRO_CONFIG = 0x1B;
const uint8_t MPU6050_REGISTER_ACCEL_CONFIG = 0x1C;
const uint8_t MPU6050_REGISTER_FIFO_EN = 0x23;
const uint8_t MPU6050_REGISTER_INT_ENABLE = 0x38;
const uint8_t MPU6050_REGISTER_ACCEL_XOUT_H = 0x3B;
const uint8_t MPU6050_REGISTER_SIGNAL_PATH_RESET = 0x68;
int16_t AccelX, AccelY, AccelZ, Temperature, GyroX, GyroY, GyroZ;
String flag_payload = "";
int o =0;
void setup() {
Serial.begin(115200);
Wire.begin(sda, scl);
MPU6050_Init();
WiFi.begin("null", "patanahi1");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println("Waiting for connection");
}
pinMode(10 , OUTPUT);
digitalWrite(10, LOW);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
double Ax, Ay, Az, T, Gx, Gy, Gz, dev_id;
Read_RawValue(MPU6050SlaveAddress, MPU6050_REGISTER_ACCEL_XOUT_H);
//divide each with their sensititvity scale factor
Ax = (double)AccelX / AccelScaleFactor;
Ay = (double)AccelY / AccelScaleFactor;
Az = (double)AccelZ / AccelScaleFactor;
T = (double)Temperature / 340 + 36.53; //temperature formula
Gx = (double)GyroX / GyroScaleFactor;
Gy = (double)GyroY / GyroScaleFactor;
Gz = (double)GyroZ / GyroScaleFactor;
dev_id = 2222;
Serial.print("Ax: "); Serial.print(Ax);
Serial.print(" Ay: "); Serial.print(Ay);
Serial.print(" Az: "); Serial.print(Az);
Serial.print(" T: "); Serial.print(T);
Serial.print(" Gx: "); Serial.print(Gx);
Serial.print(" Gy: "); Serial.print(Gy);
Serial.print(" Gz: "); Serial.println(Gz);
StaticJsonBuffer<300> JSONbuffer; //Declaring static JSON buffer
JsonObject& JSONencoder = JSONbuffer.createObject();
JSONencoder["Sensor type"] = "Acceleration";
JSONencoder["deviceid"] = dev_id;
JsonArray& values = JSONencoder.createNestedArray("values"); //JSON array
values.add(Ax); //Add value to array
values.add(Ay); //Add value to array
values.add(Az); //Add value to array
values.add(T); //Add value to array
JsonArray& timestamps = JSONencoder.createNestedArray("direction1"); //JSON array
timestamps.add("x direction"); //Add value to array
timestamps.add("y direction"); //Add value to array
timestamps.add("z direction"); //Add value to array
timestamps.add("Temperature"); //Add vaues to array
char JSONmessageBuffer[300];
JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println(JSONmessageBuffer);
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://192.168.43.75:8090/post"); //Specify request destination
http.addHeader("Content-Type", "application/json"); //Specify content-type header
int httpCode = http.POST(JSONmessageBuffer); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
http.begin("http://192.168.43.75:8090/get");
int httpCode1 = http.GET(); //Send the request
String payload_get = http.getString();
Serial.println(httpCode1); //Print HTTP return code
Serial.println(payload_get); //Print request response payload
if (payload_get == "1")
{
Serial.println("lasjdf liasdj fli");
o = 1;
}
http.end(); //Close connection
if (o == 1)
{
digitalWrite(10, HIGH);
}
}
else
{
Serial.println("Error in WiFi connection");
}
delay(100);
}
void I2C_Write(uint8_t deviceAddress, uint8_t regAddress, uint8_t data) {
Wire.beginTransmission(deviceAddress);
Wire.write(regAddress);
Wire.write(data);
Wire.endTransmission();
}
// read all 14 register
void Read_RawValue(uint8_t deviceAddress, uint8_t regAddress) {
Wire.beginTransmission(deviceAddress);
Wire.write(regAddress);
Wire.endTransmission();
Wire.requestFrom(deviceAddress, (uint8_t)14);
AccelX = (((int16_t)Wire.read() << 8) | Wire.read());
AccelY = (((int16_t)Wire.read() << 8) | Wire.read());
AccelZ = (((int16_t)Wire.read() << 8) | Wire.read());
Temperature = (((int16_t)Wire.read() << 8) | Wire.read());
GyroX = (((int16_t)Wire.read() << 8) | Wire.read());
GyroY = (((int16_t)Wire.read() << 8) | Wire.read());
GyroZ = (((int16_t)Wire.read() << 8) | Wire.read());
}
//configure MPU6050
void MPU6050_Init() {
delay(150);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_SMPLRT_DIV, 0x07);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_PWR_MGMT_1, 0x01);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_PWR_MGMT_2, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_CONFIG, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_GYRO_CONFIG, 0x00);//set +/-250 degree/second full scale
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_ACCEL_CONFIG, 0x00);// set +/- 2g full scale
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_FIFO_EN, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_INT_ENABLE, 0x01);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_SIGNAL_PATH_RESET, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_USER_CTRL, 0x00);
}
| [
"[email protected]"
] | |
434ebd600ce44c7ba66bbb59c8173127dd69edb7 | ad842c1f357e8e7146f0f241bcca4e2cad1e6375 | /apps/gsvlabel/descriptor.cpp | 1e17e7e4048e452658130f353795aa70dbbc2854 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | bmatejek/gsvgaps | 19164523327e9fcccb83908fabdaa91cc6caabe7 | 4beb271167d306ad7e87b214895670f3d7c65dbd | refs/heads/main | 2023-01-21T16:29:33.491450 | 2020-11-26T02:04:26 | 2020-11-26T02:04:26 | 316,090,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,290 | cpp | ////////////////////////////////////////////////////////////////////////
// Source file for object descriptor class
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Include files
////////////////////////////////////////////////////////////////////////
#include "object.h"
////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////
ObjectDescriptor::
ObjectDescriptor(const double *values, int nvalues)
: nvalues(nvalues),
values(NULL)
{
// Initialize values
if (nvalues > 0) {
this->values = new double [ nvalues ];
for (int i = 0; i < nvalues; i++) {
this->values[i] = (values) ? values[i] : 0.0;
}
}
}
ObjectDescriptor::
ObjectDescriptor(const ObjectDescriptor& descriptor)
: nvalues(descriptor.nvalues),
values(NULL)
{
// Initialize values
if (nvalues > 0) {
values = new double [ nvalues ];
for (int i = 0; i < nvalues; i++) {
values[i] = descriptor.values[i];
}
}
}
ObjectDescriptor::
~ObjectDescriptor(void)
{
// Delete values
if (values) delete [] values;
}
ObjectDescriptor& ObjectDescriptor::
operator=(const ObjectDescriptor& descriptor)
{
// Copy values
Reset(descriptor.values, descriptor.nvalues);
return *this;
}
void ObjectDescriptor::
Reset(const double *values, int nvalues)
{
// Delete old values
if ((this->nvalues > 0) && (this->values)) {
delete [] this->values;
this->values = NULL;
this->nvalues = 0;
}
// Assign new values
if (nvalues > 0) {
// Allocate new values
this->nvalues = nvalues;
this->values = new double [ this->nvalues ];
// Copy values
for (int i = 0; i < nvalues; i++) {
this->values[i] = (values) ? values[i] : 0.0;
}
}
}
double ObjectDescriptor::
SquaredDistance(const ObjectDescriptor& descriptor) const
{
// Check dimensionality
assert(nvalues == descriptor.nvalues);
// Sum squared distances
double sum = 0;
for (int i = 0; i < nvalues; i++) {
double delta = values[i] - descriptor.values[i];
sum += delta * delta;
}
// Return squared distance
return sum;
}
| [
"[email protected]"
] | |
b13420aa4004b14e74a53305e3368b5f4ee9dc92 | 72d1b579366934a24af7aff13ebf9b8cdaf58d8c | /ReadImages.cpp | a8f247f3d5b7fd89ce0c49662b42f6ef479207a1 | [] | no_license | hgpvision/Keypoint-Matcher | 48496a59dbaffefe6e89e8e14efabdb9883848bb | bf265aba62b325fab300aba2bad357ff7321ba4a | refs/heads/master | 2021-01-15T15:05:50.913505 | 2017-08-08T14:45:53 | 2017-08-08T14:45:53 | 99,702,359 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,454 | cpp | /*
* 文件名称:ReadImages.cpp
* 摘 要:读取图片类,图片序列放入到一个文件夹中,如"C:\\imgFile",按一定格式命名,比如"0001.jpg","00010.jpg","1.jpg"
* 使用实例:
* 包含头文件: #include "ReadImages.h"
* 先声明要给读入图片类:ReadImages imageReader("C:\\imgFile", "", ".jpg");
* 读入图片: Mat prev = imageReader.loadImage(1,0); //将读入"1.jpg"图片,灰度格式
* 2016.05.23
*/
#include "ReadImages.h"
#pragma once
ReadImages::ReadImages(std::string basepath, const std::string imagename, const std::string suffix)
{
//将路径中的文件夹分隔符统一为'/'(可以不需要这个for循环,会自动统一,该语句使用的命令参考C++ Primer)
for (auto &c : basepath)
{
if (c == '\\')
{
c = '/';
}
}
_imgSource._basepath = basepath + "/"; //这里采用'/',而不是'\\'
_imgSource._imagename = imagename; //图片名(不含编号)
_imgSource._suffix = suffix; //图像扩展名
}
//读入单张图片
//输入:imgId,一般要读入序列图片,图片都有个编号
cv::Mat ReadImages::loadImage(int imgId, int imgType)
{
//将图片编号转好字符串
std::stringstream ss;
std::string imgNum;
ss << imgId;
ss >> imgNum;
//得到图片的完整绝对路径
std::string path = _imgSource._basepath + _imgSource._imagename + imgNum + _imgSource._suffix;
cv::Mat img = cv::imread(path,imgType);
return img;
} | [
"[email protected]"
] | |
483636595ef27a032fb65294e55c02e76cef77eb | 89421a99baeeb9a368104340ad4efa5f68e2268b | /cpp/Fem1d/Fem1d.cpp | 1795d3ce24e60bc2e100e31feb3145252abc3cbc | [] | no_license | mtsodf/ppgi_elem | c16c510c3f78c1e0eb363a36178f79be60818c0a | 910155619cb94423eb47dfe793f64be01e750c5a | refs/heads/master | 2021-09-06T07:20:18.995847 | 2018-02-03T18:24:21 | 2018-02-03T18:24:21 | 105,206,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,068 | cpp | #include "Fem1d.h"
#include "../definitions.h"
#include <stdlib.h>
#include "../LinearAlgebra/Jacobi.h"
#include "../LinearAlgebra/Operations.h"
#include <cmath>
#include "../Utils/Utils.h"
using namespace std;
class UndefinedFuncForm: public exception
{
virtual const char* what() const throw()
{
return "Undefined func form";
}
};
real FuncForm(real qsi, char func){
if(func == 0) return (1.0 - qsi)/2.0;
if(func == 1) return (1.0 + qsi)/2.0;
UndefinedFuncForm ex;
throw ex;
}
real DFuncForm(real qsi, char func){
if(func == 0) return -1.0/2.0;
if(func == 1) return 1.0/2.0;
UndefinedFuncForm ex;
throw ex;
}
void LocalMatrix(real alpha, real beta, real he, real* lm){
real w;
w = sqrt(3.0)/3.0;
for (size_t i = 0; i < 2; i++)
{
for (size_t j = 0; j < 2; j++)
{
lm[2*i+j] = (he/2)*beta*(FuncForm(-w,i)*FuncForm(-w,j)) + (2/he)*alpha*(DFuncForm(-w,i)*DFuncForm(-w,j));
lm[2*i+j] += (he/2)*beta*(FuncForm( w,i)*FuncForm( w,j)) + (2/he)*alpha*(DFuncForm( w,i)*DFuncForm( w,j));
}
}
}
void GlobalMatrix(int n, real alpha, real beta, real *K, int boundary){
real * hs;
real h = 1.0/n;
hs = (real*) malloc(sizeof(real)*n);
for (size_t i = 0; i < n; i++)
{
hs[i] = h;
}
GlobalMatrix(n, alpha, beta, hs, K, boundary);
}
void GlobalMatrix(int n, real alpha, real beta, real* hs, real *K, int boundary){
real lm[4];
int ndofs = n + 1;
for (size_t i = 0; i < n; i++)
{
LocalMatrix(alpha, beta, hs[i], lm);
K[DIM(i,i,ndofs)] += lm[0];
K[DIM(i,i+1,ndofs)] += lm[1];
K[DIM(i+1,i,ndofs)] += lm[2];
K[DIM(i+1,i+1,ndofs)] += lm[3];
}
if(boundary == DIRICHLET || boundary == DIRICHLET_NEUMANN){
K[DIM(0,0,ndofs)] = 1.0;
K[DIM(0,1,ndofs)] = 0.0;
K[DIM(1,0,ndofs)] = 0.0;
}
if(boundary == DIRICHLET || boundary == NEUMANN_DIRICHLET){
K[DIM(ndofs-1,ndofs-2,ndofs)] = 0.0;
K[DIM(ndofs-2,ndofs-1,ndofs)] = 0.0;
K[DIM(ndofs-1,ndofs-1,ndofs)] = 1.0;
}
}
void RhsLocal(real he, real f1, real f2, real *Fe){
real w = sqrt(3)/3.0;
Fe[0] = f1*(he/2)*(FuncForm(-w,0) * FuncForm(-w,0) + FuncForm(w,0) * FuncForm(w,0));
Fe[0] += f2*(he/2)*(FuncForm(-w,0) * FuncForm(-w,1) + FuncForm(w,0) * FuncForm(w,1));
Fe[1] = f1*(he/2)*(FuncForm(-w,1) * FuncForm(-w,0) + FuncForm(w,1) * FuncForm(w,0));
Fe[1] += f2*(he/2)*(FuncForm(-w,1) * FuncForm(-w,1) + FuncForm(w,1) * FuncForm(w,1));
}
void RhsGlobal(int n, real h, real *fs, real *F, real p, real q, real alpha, real beta, int boundary){
real *hs = (real*) malloc(n*sizeof(real));
for (size_t i = 0; i < n; i++)
{
hs[i] = h;
}
RhsGlobal(n, hs, fs, F, p, q, alpha, beta, boundary);
free(hs);
}
void RhsGlobal(int n, real *hs, real *fs, real *F, real p, real q, real alpha, real beta, int boundary){
int ndofs = n + 1;
for (size_t i = 0; i < ndofs; i++)
{
F[i] = 0.0;
}
real Fe[2];
for (size_t i = 0; i < n; i++)
{
RhsLocal(hs[i], fs[i], fs[i+1], Fe);
F[i] += Fe[0];
F[i+1] += Fe[1];
}
if(boundary == DIRICHLET || boundary == DIRICHLET_NEUMANN){
F[0] = p;
real w = sqrt(3)/3.0; real he = hs[0];
F[1] -= p*((he/2)*beta*(FuncForm(-w,0)*FuncForm(-w,1)) + (2/he)*alpha*(DFuncForm(-w,0)*DFuncForm(-w,1)));
F[1] -= p*((he/2)*beta*(FuncForm( w,0)*FuncForm( w,1)) + (2/he)*alpha*(DFuncForm( w,0)*DFuncForm( w,1)));
}
if(boundary == DIRICHLET || boundary == NEUMANN_DIRICHLET){
real w = sqrt(3)/3.0; real he = hs[n-1];
F[ndofs - 1] = q;
F[ndofs-2] -= q*((he/2)*beta*(FuncForm(-w,0)*FuncForm(-w,1)) + (2/he)*alpha*(DFuncForm(-w,0)*DFuncForm(-w,1)));
F[ndofs-2] -= q*((he/2)*beta*(FuncForm( w,0)*FuncForm( w,1)) + (2/he)*alpha*(DFuncForm( w,0)*DFuncForm( w,1)));
}
if(boundary == NEUMANN || boundary == NEUMANN_DIRICHLET){
F[0] -= alpha*p;
}
if(boundary == NEUMANN || boundary == DIRICHLET_NEUMANN){
F[ndofs-1] += alpha*q;
}
}
extern "C"{
real * Fem1dTest(int n, int entrada){
real *x, *F, *fs, *sol;
real *K;
real alpha, beta, p, q;
int boundary;
int unknowns = n + 1;
real h = 1.0/n;
zero(unknowns, &x);
zero(unknowns, &F);
zero(unknowns, &fs);
zero(unknowns, &sol);
zero(unknowns*unknowns, &K);
x[0] = 0.0;
for (size_t i = 1; i < unknowns; i++)
{
x[i] = x[i-1] + h;
}
/*
######################################################################
# Selecao da entrada
######################################################################
*/
for (size_t i = 0; i < unknowns; i++)
{
switch (entrada)
{
case 0:
alpha = 1.0;
beta = 1.0;
fs[i] = 4*M_PI*M_PI*sin(2*M_PI*x[i]) + sin(2*M_PI*x[i]);
sol[i] = sin(2*M_PI*x[i]);
boundary = DIRICHLET;
p = 0.0;
q = 0.0;
break;
case 1:
alpha = 1.0;
beta = 0.0;
fs[i] = 2*alpha;
boundary = DIRICHLET;
p = 0.0;
q = 0.0;
break;
case 2:
alpha = 1.0;
beta = 0.5;
boundary = DIRICHLET;
fs[i] = 0.5*x[i];
p = 0.0;
q = 1.0;
break;
case 3:
alpha = 0.0;
beta = 1.0;
boundary = DIRICHLET;
fs[i] = beta*x[i]*(1-x[i]);
p = 0.0;
q = 0.0;
break;
case 4:
alpha = 2.0;
beta = 1.0;
boundary = DIRICHLET;
fs[i] = -7*exp(2*x[i]);
p = 1.0;
q = exp(2.0);
break;
case 5:
alpha = 2.0;
beta = 1.0;
boundary = NEUMANN;
fs[i] = -7*exp(2*x[i]);
p = 2.0;
q = 2*exp(2.0);
break;
case 6:
alpha = 2.0;
beta = 1.0;
boundary = NEUMANN_DIRICHLET;
fs[i] = -7*exp(2*x[i]);
p = 2.0;
q = exp(2.0);
break;
case 7:
alpha = 2.0;
beta = 1.0;
boundary = DIRICHLET_NEUMANN;
fs[i] = -7*exp(2*x[i]);
p = 1.0;
q = 2*exp(2.0);
break;
case 8:
alpha = 1.0;
beta = 1.0;
boundary = NEUMANN;
fs[i] = 4*M_PI*M_PI*sin(2*M_PI*x[i]) + sin(2*M_PI*x[i]);
p = 2*M_PI;
q = 2*M_PI;
break;
default:
break;
}
}
/*
######################################################################
# Criando Matriz Global
######################################################################
*/
GlobalMatrix(n, alpha, beta, K, boundary);
/*
######################################################################
# Criando Lado Direito
######################################################################
*/
RhsGlobal(n, h, fs, F, p, q, alpha, beta, boundary);
/*
######################################################################
# Solucao do Sistema Linear
######################################################################
*/
real * calc;
zero(unknowns, &calc);
cg(unknowns, K, F, calc);
free(x);
free(F);
free(fs);
free(sol);
free(K);
return calc;
}
}
| [
"[email protected]"
] | |
a0a7716d5870fb0a5b552fb6115b6e7b7937b018 | c22dbf8b58f205c5b748eeff49dfaf04e3a40f39 | /Cantera/clib/src/Storage.cpp | d5462bccbfad490f8de02daa46dd5a4a7f8d90af | [] | no_license | VishalKandala/Cantera1.8-Radcal | ee9fc49ae18ffb406be6cf6854daf2427e29c9ab | 1d7c90244e80185910c88fdf247193ad3a1745f3 | refs/heads/main | 2023-01-20T17:07:23.385551 | 2020-11-29T05:50:51 | 2020-11-29T05:50:51 | 301,748,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,004 | cpp | /**
* @file Storage.cpp
*/
/*
* $Id: Storage.cpp,v 1.6 2009/07/11 17:16:09 hkmoffa Exp $
*/
// Cantera includes
#include "Kinetics.h"
#include "TransportFactory.h"
#include "Storage.h"
using namespace std;
using namespace Cantera;
Storage::Storage() {
addThermo(new ThermoPhase);
addKinetics(new Kinetics);
addTransport(newTransportMgr());
}
Storage::~Storage() { clear(); }
int Storage::addThermo(thermo_t* th) {
if (th->index() >= 0)
return th->index();
__thtable.push_back(th);
int n = static_cast<int>(__thtable.size()) - 1;
th->setIndex(n);
//string id = th->id();
//if (__thmap.count(id) == 0) {
// __thmap[id] = n;
// th->setID(id);
//}
//else {
// throw CanteraError("Storage::addThermo","id already used");
// return -1;
//}
return n;
}
int Storage::nThermo() {
return static_cast<int>(__thtable.size());
}
int Storage::addKinetics(Kinetics* kin) {
if (kin->index() >= 0)
return kin->index();
__ktable.push_back(kin);
int n = static_cast<int>(__ktable.size()) - 1;
kin->setIndex(n);
return n;
}
int Storage::addTransport(Transport* tr) {
if (tr->index() >= 0)
return tr->index();
__trtable.push_back(tr);
int n = static_cast<int>(__trtable.size()) - 1;
tr->setIndex(n);
return n;
}
// int Storage::addNewTransport(int model, char* dbase, int th,
// int loglevel) {
// try {
// ThermoPhase* thrm = __thtable[th];
// Transport* tr = newTransportMgr(model,
// string(dbase), thrm, loglevel);
// __trtable.push_back(tr);
// return __trtable.size() - 1;
// }
// catch (CanteraError) {return -1;}
// catch (...) {return ERR;}
// }
int Storage::clear() {
int i, n;
n = static_cast<int>(__thtable.size());
for (i = 1; i < n; i++) {
if (__thtable[i] != __thtable[0]) {
delete __thtable[i];
__thtable[i] = __thtable[0];
}
}
n = static_cast<int>(__ktable.size());
for (i = 1; i < n; i++) {
if (__ktable[i] != __ktable[0]) {
delete __ktable[i];
__ktable[i] = __ktable[0];
}
}
n = static_cast<int>(__trtable.size());
for (i = 1; i < n; i++) {
if (__trtable[i] != __trtable[0]) {
delete __trtable[i];
__trtable[i] = __trtable[0];
}
}
return 0;
}
void Storage::deleteKinetics(int n) {
if (n == 0) return;
if (__ktable[n] != __ktable[0])
delete __ktable[n];
__ktable[n] = __ktable[0];
}
void Storage::deleteThermo(int n) {
if (n == 0) return;
if (n < 0 || n >= (int) __thtable.size())
throw CanteraError("deleteThermo","illegal index");
__thtable[n] = __thtable[0];
}
void Storage::deleteTransport(int n) {
if (n == 0) return;
if (__trtable[n] != __trtable[0])
delete __trtable[n];
__trtable[n] = __trtable[0];
}
Storage* Storage::__storage = 0;
| [
"[email protected]"
] | |
c215bbe245ccb34412185018ca3f5d02da4e0b33 | 34b22618cc53750a239ee7d3c98314d8e9b19093 | /framework/deprecated/core/cofiles/src/xercesc/XMLNode.cpp | dd4c70894a3fcc72010e7bf9a7fccc4302847f08 | [] | no_license | ivan-kits/cframework | 7beef16da89fb4f9559c0611863d05ac3de25abd | 30015ddf1e5adccd138a2988455fe8010d1d9f50 | refs/heads/master | 2023-06-12T05:09:30.355989 | 2021-07-04T09:00:00 | 2021-07-04T09:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,369 | cpp | #include "cofiles/XML/Xerces/XMLNode.h"
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMException.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include "cofiles/Makros.h"
#include "cofiles/XML/Xerces/XMLElement.h"
#include "cofiles/XML/Xerces/XMLText.h"
using namespace CoFiles;
XERCES_CPP_NAMESPACE_USE
DOMNode* ToDOMNode( void* _pNode )
{
DOMNode* pNode = static_cast< DOMNode* >( _pNode );
return pNode;
}
const DOMNode* ToDOMNode( const void* _pNode )
{
const DOMNode* pNode = static_cast< const DOMNode* >( _pNode );
return pNode;
}
Xerces::XMLNode::XMLNode()
: m_pNode( NULL ),
m_eNodeType( XML_NODE_TYPE_NONE )
{
}
void Xerces::XMLNode::SetNodeType( XMLNodeType _eNodeType )
{
m_eNodeType = _eNodeType;
}
XMLNodeType Xerces::XMLNode::GetNodeType() const
{
return m_eNodeType;
}
bool Xerces::XMLNode::IsValid() const
{
return GetXMLNode() != NULL;
}
bool Xerces::XMLNode::HasChildren() const
{
if( IsValid() ) {
return !ToDOMNode( GetXMLNode() )->getChildNodes()->getLength();
}
else {
return false;
}
}
XMLNodePtr Xerces::XMLNode::GetFirstChild() const
{
m_spFirstChild.reset();
if ( ToDOMNode( GetXMLNode() ) != NULL )
{
DOMNode *pNode = ToDOMNode( GetXMLNode() )->getFirstChild();
while ( pNode != NULL &&
!IsValidXMLNode( pNode ) )
{
pNode = pNode->getNextSibling();
}
if ( pNode != NULL )
{
m_spFirstChild = CreateNode( pNode );
}
}
return m_spFirstChild;
}
XMLNodePtr Xerces::XMLNode::GetNextSibling() const
{
m_spNextSibling.reset();
if ( GetXMLNode() == NULL )
{
return XMLNodePtr();
}
DOMNode *pNode = ToDOMNode( GetXMLNode() )->getNextSibling();
while( pNode != NULL &&
!IsValidXMLNode( pNode ) )
{
pNode = pNode->getNextSibling();
}
if ( pNode != NULL )
{
m_spNextSibling = CreateNode( pNode );
}
return m_spNextSibling;
}
void Xerces::XMLNode::InsertChildFirst( CoFiles::XMLNode& _clChildNode )
{
if ( IsValid() )
{
try
{
ToDOMNode( GetXMLNode() )->insertBefore( ToDOMNode( _clChildNode.GetXMLNode() ), NULL );
}
catch ( const DOMException& e )
{
CO_WARN( "XMLNode::InsertChildFirst: %s", XMLString::transcode( e.msg ) );
}
}
}
void Xerces::XMLNode::InsertChildBefore( CoFiles::XMLNode& _clChildNode, CoFiles::XMLNode& _clBefore )
{
if( IsValid() )
{
ToDOMNode( GetXMLNode() )->insertBefore( ToDOMNode( _clChildNode.GetXMLNode() ), ToDOMNode( _clBefore.GetXMLNode() ) );
}
}
void Xerces::XMLNode::InsertChildAfter( CoFiles::XMLNode& _clChildNode, CoFiles::XMLNode& _clAfter )
{
if( IsValid() )
{
if( _clAfter.GetXMLNode() != NULL )
{
ToDOMNode( GetXMLNode() )->insertBefore( ToDOMNode( _clChildNode.GetXMLNode() ), ToDOMNode( _clAfter.GetXMLNode() )->getNextSibling() );
}
else
{
ToDOMNode( GetXMLNode() )->appendChild( ToDOMNode( _clChildNode.GetXMLNode() ) );
}
}
}
void Xerces::XMLNode::InsertChildLast( CoFiles::XMLNode& _clChildNode )
{
if( IsValid() )
{
DOMNode* pDOMNode = ToDOMNode( GetXMLNode() );
DOMNode* pChildDOMNode = ToDOMNode( _clChildNode.GetXMLNode() );
if ( pDOMNode != NULL &&
pChildDOMNode != NULL )
{
try
{
pDOMNode->appendChild( pChildDOMNode );
}
catch ( const DOMException& e )
{
CO_WARN( "XMLNode::InsertChildLast: %s", XMLString::transcode( e.msg ) );
}
}
}
}
bool Xerces::XMLNode::IsDocument() const
{
return m_eNodeType == DOCUMENT_NODE;
}
bool Xerces::XMLNode::IsElement() const
{
return m_eNodeType == ELEMENT_NODE;
}
bool Xerces::XMLNode::IsText() const
{
return m_eNodeType == TEXT_NODE;
}
const void* Xerces::XMLNode::GetXMLNode() const
{
return m_pNode;
}
void* Xerces::XMLNode::GetXMLNode()
{
return m_pNode;
}
void Xerces::XMLNode::SetXMLNode( void* pNode )
{
m_pNode = ToDOMNode( pNode );
}
XMLNodePtr Xerces::XMLNode::CreateNode( DOMNode* _pNode )
{
if ( _pNode == NULL )
{
return XMLNodePtr();
}
CoFiles::XMLNodePtr spNewNode;
if ( _pNode->getNodeType() == DOMNode::ELEMENT_NODE )
{
XMLElement* pElement = new Xerces::XMLElement();
spNewNode = CoFiles::XMLNodePtr( pElement );
}
else if ( _pNode->getNodeType() == DOMNode::TEXT_NODE )
{
XMLText* pText = new Xerces::XMLText();
spNewNode = CoFiles::XMLNodePtr( pText );
}
if ( spNewNode!= NULL )
{
spNewNode->SetXMLNode( _pNode );
}
return spNewNode;
}
bool Xerces::XMLNode::IsValidXMLNode( DOMNode* pNode )
{
if ( pNode == NULL )
{
return false;
}
if ( pNode->getNodeType() == DOMNode::COMMENT_NODE )
{
return false;
}
else if ( pNode->getNodeType() == DOMNode::NOTATION_NODE )
{
return false;
}
else if ( pNode->getNodeType() == DOMNode::TEXT_NODE )
{
XMLText clTextNode;
clTextNode.SetXMLNode( pNode );
String sText = clTextNode.GetText();
if( sText == "" )
{
return false;
}
}
return true;
} | [
"[email protected]"
] | |
3025038669b687c8e7bd508bb41b1b5adb4ab7b2 | 64824c859f6af21ad97edf16fb00a32b81c8e800 | /第23节.cpp | 01bf003a3ed3a08ee1f72d2bdd25d275403bbf9b | [] | no_license | leigelaing/C- | 7ea94df8fed45bc47eb5437eedda5b6cc98bc754 | 513b5ba2a8891717d4a21e5cfabd935f66071b57 | refs/heads/master | 2023-04-09T06:49:11.603590 | 2021-04-20T00:11:38 | 2021-04-20T00:11:38 | 296,510,796 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,887 | cpp | #include<stdio.h>
int Add(int x,int y)
{
int z = 0;
z = x + y;
return z;
}
int main()
{
int a = 10;
int b = 20;
int ret = 0;
ret = Add(a,b);
return 0;
}
//压栈
/*
typedef struct stu
{
//成员变量
char name[20];
short age;
char tele[12];
char sex[5];
}stu;
void print1(stu tmp)
{
printf("name: %s\n",tmp.name);
printf(" age: %d\n",tmp.age);
printf("tele: %s\n",tmp.tele );
printf(" sex: %s\n",tmp.sex );
}
void print2(stu* pa)
{
printf("name: %s\n",pa->name);
printf(" age: %d\n",pa->age);
printf("tele: %s\n",pa->tele );
printf(" sex: %s\n",pa->sex );
}
int main()
{
stu s = {"李四",40,"1561341658","男"};
//打印结构体数据
//print1与print2哪个更好 print1浪费空间,
print1(s);
print2(&s);
return 0;
}
*/
/*struct S
{
int a;
char c;
char arr[20];
double d;
};
struct T
{
char ch[10];
struct S s;
char *pc;
};
int main()
{
char arr[] = "hello bit\n";
struct T t = {"hehe",{100,'w',"hello world",3.14},arr};
printf("%s\n",t.ch);
printf("%s\n",t.s.arr);
printf("%lf\n",t.s.d);
printf("%s\n",t.pc);
return 0;
}
*/
/*
typedef struct stu
{
//成员变量
char name[20];
short age;
char tele[12];
char sex[5];
}stu; //struct 被改名为 stu
int main()
{
struct stu s1 = {"张三",20,"125226236213","男"};//s局部变量;
stu s2 = {"旺财",30,"1646346464646","女"};
return 0;
}
*/
/*
//struct 结构体关键字, stu—结构体标签 struct stu—结构体类型(不占用内存空间)
struct stu
{
//成员变量
char name[20];
short age;
char tele[12];
char sex[5];
}s1,s2,s3;//s1,s2,s3是全局变量
int main()
{
struct stu s;//s局部变量;
return 0;
}
*/ | [
"[email protected]"
] | |
e701e032706c6d0b6712cbf46f97a1491037c069 | 509ed385d3faa95ed92957f0f691fc3fe1d6816a | /src/Workers/Worker.h | db1536697c5f967497dfa8fe487e786329ac19ec | [] | no_license | xrenoder/Node-InfrastructureTorrent | d6540c725cb9239bcf421a7891e7ebbeb6505701 | 21c3eb739d0b41cb6858d747cd108708bbfdb73d | refs/heads/master | 2023-08-29T01:02:15.760253 | 2021-09-20T10:03:30 | 2021-09-20T10:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | h | #ifndef WORKER_H_
#define WORKER_H_
#include <memory>
#include <optional>
#include "OopUtils.h"
namespace torrent_node_lib {
struct BlockInfo;
class Worker: public common::no_copyable, common::no_moveable{
public:
virtual void start() = 0;
virtual void process(std::shared_ptr<BlockInfo> bi, std::shared_ptr<std::string> dump) = 0;
virtual std::optional<size_t> getInitBlockNumber() const = 0;
virtual ~Worker() = default;
};
}
#endif // WORKER_H_
| [
"[email protected]"
] | |
f45da0032ec95894d113360f36e2c7e74a3b4bd2 | be522f6110d4ed6f330da41a653460e4fb1ed3a7 | /runtime/nf/httpparser/Buffer.cc | e4717f524b583c4cfdc3f533c545bdec74c3946c | [] | no_license | yxd886/nfa | 2a796b10e6e2085470e54dd4f9a4a3721c0d27a9 | 209fd992ab931f955afea11562673fec943dd8a6 | refs/heads/master | 2020-06-17T22:09:37.259587 | 2017-03-24T03:07:38 | 2017-03-24T03:07:38 | 74,966,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cc |
#include "Buffer.h"
void CBuffer_Reset(struct CBuffer& Cbuf){
if(!Cbuf.buf){
Cbuf.buf = (char*) malloc(BUFFER_SIZE);
memset(Cbuf.buf,0x00,Cbuf._free);
}
if(Cbuf.len > BUFFER_SIZE * 2 && Cbuf.buf){
//如果目前buf的大小是默认值的2倍,则对其裁剪内存,保持buf的大小为默认值,减小内存耗费
char* newbuf = (char*) realloc(Cbuf.buf,BUFFER_SIZE);
if(newbuf != Cbuf.buf)
Cbuf.buf = newbuf;
}
Cbuf.len = 0;
Cbuf._free = BUFFER_SIZE;
}
bool Append(struct CBuffer& Cbuf,char* p, size_t size){
if(!p || !size)
return true;
if(size < Cbuf._free){
memcpy(Cbuf.buf + Cbuf.len, p , size);
Cbuf.len += size;
Cbuf._free -= size;
}else{
return false;
}
return true;
}
char* GetBuf(struct CBuffer Cbuf,uint32_t& size){
size = Cbuf.len;
return Cbuf.buf;
}
uint32_t GetBufLen(struct CBuffer Cbuf){
return Cbuf.len;
}
void Buf_init(struct CBuffer& Cbuf){
Cbuf.len=0;
Cbuf._free=0;
Cbuf.buf=0;
CBuffer_Reset(Cbuf);
}
| [
"[email protected]"
] | |
aad85aa770183929d8ccd9df0aacf59df35f147f | 465a87bdead9aee133a7b36b0c2e826ece517cbb | /ARStudy(Image processing)/ARStudy/main.cpp | 5ebb0f7ee747397046be8ca1b609d9d04b460e5c | [] | no_license | kshy9598/ARStudy | a5b55f3808d1e64cc96ee3e9266e4f4c23c3d611 | c55ce51cb595f677eb07549203d0032430a90aef | refs/heads/master | 2020-06-29T05:20:21.879048 | 2016-12-08T16:22:03 | 2016-12-08T16:22:03 | 74,446,922 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 4,927 | cpp | #include <iostream>
#include <fstream>
#include <cmath>
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\opencv.hpp"
#pragma comment(lib, "opencv_world300d.lib")
const double PI = 3.14159265;
using namespace std;
using namespace cv;
bool bLBDown = false; // 마우스 버튼 눌렀는지 체크
bool checkDrag; // 드래그가 이루어졌는지 체크
CvRect box; // 드래그로 그린 박스
// 사각형 그리기
void draw_box(IplImage* img, CvRect rect)
{
cvRectangle(img, cvPoint(rect.x, rect.y),
cvPoint(rect.x + rect.width, rect.y + rect.height),
cvScalar(0xff, 0x00, 0x00));
}
// 마우스 드래그
void on_mouse(int event, int x, int y, int flag, void* params)
{
IplImage* image = (IplImage*)params;
if (event == CV_EVENT_LBUTTONDOWN){ // 왼쪽 버튼 눌렀을 시, 박스 초기화
bLBDown = true;
box = cvRect(x, y, 0, 0);
}
else if (event == CV_EVENT_LBUTTONUP){ // 왼쪽 버튼 눌렀다가 뗐을 때, 박스의 넓이, 높이를 설정한다.
bLBDown = false;
checkDrag = true;
if (box.width < 0)
{
box.x += box.width;
box.width *= -1;
}
if (box.height < 0)
{
box.y += box.height;
box.height *= -1;
}
draw_box(image, box);
}
else if (event == CV_EVENT_MOUSEMOVE && bLBDown){ // 드래그 중에는 박스의 넓이, 높이를 갱신한다.
box.width = x - box.x;
box.height = y - box.y;
}
}
// 이미지 복사
Mat copyMat(Mat source)
{
// source의 Mat을 result로 복사하는 작업
// opencv에 이미 구현이 되어있는 작업이다.
// source.copyTo(result);
Mat result = Mat::zeros(source.size(), source.type());
for (int i = 0; i < source.cols; i++){
for (int j = 0; j < source.rows; j++){
result.at<Vec3b>(j, i) = source.at<Vec3b>(j, i);
}
}
return result;
}
// 박스내 이미지 복사
Mat copyBoxMat(Mat source)
{
return source(box);
}
// y축반전
Mat yReflecting(Mat source)
{
Mat result = copyMat(source);
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
result.at<Vec3b>((box.y + j), (box.x + i)) = source.at<Vec3b>(box.y + j, (box.width + box.x - 1) - i);
}
}
return result;
}
// x축반전
Mat xReflecting(Mat source)
{
Mat result = copyMat(source);
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
result.at<Vec3b>((box.y + j), (box.x + i)) = source.at<Vec3b>((box.height + box.y - 1) - j, (box.x + i));
}
}
return result;
}
// 회전
Mat rotating(Mat source, double degree)
{
Mat result = copyMat(source);
int x0 = box.x + (box.width / 2);
int y0 = box.y + (box.height / 2);
double cosd = cos(degree*PI / 180);
double sind = sin(degree*PI / 180);
// 원본에 덮어씌우는 부분으로 인해 왼쪽 90도, 오른쪽 90도만 가능
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
int x1 = (box.x + i);
int y1 = (box.y + j);
int x = ((cosd * (x1 - x0)) - (sind * (y1 - y0)) + x0);
int y = ((sind * (x1 - x0)) - (cosd * (y1 - y0)) + y0);
result.at<Vec3b>(y, x) = source.at<Vec3b>((box.y + j), (box.x + i));
}
}
return result;
}
// 확대
Mat scaling(Mat source, Mat boxMat, double scale)
{
Mat result = copyMat(source);
Mat scaleBoxMat;
// 사각형 안의 Mat의 크기를 scale배 늘린다.
int boxWidth = (int)(boxMat.size().width * scale);
int boxHeight = (int)(boxMat.size().height * scale);
cv::resize(boxMat, scaleBoxMat, Size(boxWidth, boxHeight));
// 붙여넣을 때 시작 위치 정보를 갱신한다.
int x = box.x - (box.width / 2);
int y = box.y - (box.height / 2);
for (int i = 0; i < boxWidth; i++){
for (int j = 0; j < boxHeight; j++){
result.at<Vec3b>((y + j), (x + i)) = scaleBoxMat.at<Vec3b>(j, i);
}
}
return result;
}
int main()
{
IplImage copy;
IplImage * resultImage;
Mat resultMat, xReflectMat, yReflectMat, leftRotateMat, scaleMat, boxMat;
// 이미지 불러오기
Mat gMatImage = imread("./picture/pic.jpg", 1);
// Mat 이미지를 IplImage 로 복사한다.
copy = gMatImage;
resultImage = ©
checkDrag = false;
namedWindow("image");
setMouseCallback("image", on_mouse, resultImage);
cvShowImage("image", resultImage);
//드래그 대기
while (!checkDrag){
waitKey(100);
}
cvShowImage("image", resultImage);
//사각형 추가된 사진 저장
resultMat = cvarrToMat(resultImage);
boxMat = copyBoxMat(resultMat);
cout << box.x << ' ' << box.y << ' ' << box.width << ' ' << box.height << endl;
yReflectMat = yReflecting(resultMat); // y축 반전
xReflectMat = xReflecting(resultMat); // x축 반전
scaleMat = scaling(resultMat, boxMat, 1.5); // 크기 변경
leftRotateMat = rotating(resultMat, -90.0); // 90도 회전
waitKey(2000);
imshow("y반전 이미지", yReflectMat);
imshow("x반전 이미지", xReflectMat);
imshow("왼쪽 90도 회전 이미지", leftRotateMat);
imshow("1.5배 확대 이미지", scaleMat);
waitKey(0);
return 0;
} | [
"[email protected]"
] | |
0293e83add680ed3f8e92ecea17c897a91d1270b | 1ca3477d99bddb6611f2feb67c8ce0c4569d8a4b | /Memendo.cc | 7ac722a8f7b952968a9ec15d38a1c9bbc3afc637 | [] | no_license | TaoJun724/DesignPattern | 0da37a3a34fba54ba21cb809875b20d9eeba3443 | b0c62668cfad5b48b85b413e78ee9334812a74b2 | refs/heads/master | 2020-06-30T08:57:32.156222 | 2019-08-07T07:42:09 | 2019-08-07T07:42:09 | 200,785,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cc | #include <stdio.h>
#include<string>
class Memento {
public:
Memento(int n, std::string s) {
_s = s;
_money = n;
}
void setMoney(int n) {
_money = n;
}
int getMoney() {
return _money;
}
void setState(std::string s) {
_s = s;
}
std::string getState() {
return _s;
}
private:
int _money;
std::string _s;
};
class Worker {
public:
Worker(std::string name, int money, std::string s) {
_name = name;
_money = money;
_s = s;
}
void show() {
printf("%s现在有钱%d元,生活状态%s!\n", _name.c_str(), _money, _s.c_str());
}
void setState(int money, std::string s) {
_money = money;
_s = s;
}
Memento* createMemnto() {
return new Memento(_money,_s);
}
void restoreMemnto(Memento* m) {
_money = m->getMoney();
_s = m->getState();
}
private:
std::string _name;
int _money;
std::string _s;
};
class WorkerStorage {
public:
void setMemento(Memento* m) {
_memento = m;
}
Memento* getMement() {
return _memento;
}
private:
Memento* _memento;
};
int main() {
Worker* zhangsan = new Worker("张三", 10000, "富裕");
zhangsan->show();
//记住张三现在的状态
WorkerStorage* storage = new WorkerStorage;
storage->setMemento(zhangsan->createMemnto());
//张三赌博输了钱,只剩下10元
zhangsan->setState(10, "贫困");
zhangsan->show();
//经过努力张三又回到了之前的状态。
zhangsan->restoreMemnto(storage->getMement());
zhangsan->show();
return 0;
}
| [
"[email protected]"
] | |
a408cd231d1845ea66458abff8bd63b1571e3a75 | ba6ecbc7036d2b7c8839f4f86e2c3dec44d57bee | /features/visuals/visuals.cpp | 5ba75ffb6949425df8c0dfd07f72147c306665a1 | [
"MIT"
] | permissive | ALEHACKsp/gmod-sdk | a484e5c1efbce5573a659cbb4530d0740f4b7d22 | 482c66989e0f55bd7b52bb0bee48b0b0b2bb893f | refs/heads/master | 2021-04-21T03:14:57.941168 | 2020-03-23T21:37:24 | 2020-03-23T21:37:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,931 | cpp | #include "visuals.hpp"
#include "../../utilities/math.hpp"
#include "../../utilities/drawmanager.hpp"
#include "../../options.hpp"
void Visuals::RunPlayerESP() {
auto get_box = [](Vector feet, Vector head) -> RECT {
RECT ret;
auto h_ = fabs(head.y - feet.y);
auto w_ = h_ / 2.0f;
ret.left = (int)(feet.x - w_ * 0.5f);
ret.right = (int)(ret.left + w_);
ret.bottom = (feet.y > head.y ? (int)(feet.y) : (int)(head.y));
ret.top = (feet.y > head.y ? (int)(head.y) : (int)(feet.y));
return ret;
};
if (!Interfaces::EngineClient->IsInGame())
return;
if (!Vars.esp_enabled)
return;
CEntity* LocalPlayer = Interfaces::EntityList->GetEntity(Interfaces::EngineClient->GetLocalPlayer());
for (size_t i = 0; i <= Interfaces::EntityList->GetHighestEntityIndex(); i++) {
CEntity* entity = Interfaces::EntityList->GetEntity(i);
if (!entity) continue;
if (entity == LocalPlayer && Vars.esp_ignore_local) continue;
if (!entity->IsPlayer()) continue;
if (!entity->IsAlive()) continue;
Vector feet, eye;
if (!Math::WorldToScreen(entity->GetAbsOrigin(), feet) || !Math::WorldToScreen(entity->GetEyePos(), eye))
continue;
auto box = get_box(feet, eye);
auto box_clr = Utilities::IsVisible(LocalPlayer, entity, entity->GetEyePos()) ? ImColor(1.f, 1.f, 0.f) : ImColor(1.f, 0.f, 0.f);
if (Vars.esp_box) {
Draw::Rect(ImVec2(box.left - 1, box.top - 1), ImVec2(box.right + 1, box.bottom + 1), ImColor(0.f, 0.f, 0.f), 5, 0, 1.f);
Draw::Rect(ImVec2(box.left, box.top), ImVec2(box.right, box.bottom), box_clr, 5, 0, 1.f);
Draw::Rect(ImVec2(box.left + 1, box.top + 1), ImVec2(box.right - 1, box.bottom - 1), ImColor(0.f, 0.f, 0.f), 5, 0, 1.f);
}
if (Vars.esp_healthbar) {
float CurHealth = entity->GetHealth();
float maxHp = entity->GetMaxHealth();
Draw::FilledRect(ImVec2(box.left - 6, box.top), ImVec2(box.left - 3, box.bottom), ImColor(0.f, 0.f, 0.f), 5, 0);
auto x_start = box.left - 5;
auto y_start = box.top + 1;
auto y_end = box.bottom - 1;
auto y_size = (y_end - y_start) / maxHp * CurHealth;
Draw::Line(ImVec2(x_start, y_end - y_size), ImVec2(x_start, y_end), ImColor(0.f, 1.f, 0.f), 1);
}
if (Vars.esp_name) {
auto getName = [](CEntity* entity) -> std::string
{
auto glua = Interfaces::Lua->CreateInterface(LUA::type::client);
if (!glua)
return {};
glua->PushSpecial(LUA::special::glob);
glua->GetField(-1, "Entity");
glua->PushNumber(entity->GetIndex());
glua->Call(1, 1);
glua->GetField(-1, "Name");
glua->Push(-2);
glua->Call(1, 1);
std::string name = glua->GetString();
glua->Pop(3);
return name;
};
auto name = getName(entity);
auto name_size = ImGui::CalcTextSize(name.c_str());
auto x_start = box.left + (box.right - box.left) / 2.f;
Draw::Text(ImVec2(x_start - (name_size.x / 2.f), box.top - name_size.y - 1), name.c_str(), ImColor(1.f, 1.f, 1.f));
}
}
} | [
"[email protected]"
] | |
49d04327f2bb77b7681762dfab736d8274441b2c | d1dc3c6ec24ce3291a257b16bd1f2aa6bd791d2e | /Project1/src/Main66.cpp | e774f1c5c93157824bc10e4e8b6864ae00497def | [] | no_license | wrapdavid/Cherno_practice | 8248bbcedee31a48c536dbd191eca5265178e762 | e95ff1857fd72fc195a0e4c57c15a5965287ea69 | refs/heads/master | 2020-09-08T10:32:04.088194 | 2020-02-11T02:29:49 | 2020-02-11T02:29:49 | 221,109,286 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 242 | cpp | #include<iostream>
template<typename T, char N>
class Array {
private:
T m_Array[N];
public:
char GetArray() const { return N; }
};
int main() {
Array<int, 61> array;
std::cout << array.GetArray() << std::endl;
std::cin.get();
} | [
"[email protected]"
] | |
bcee12c3aa60f8c1d8f0802c1bfdfe7600a1e3ef | 067b197860f7712e3f92564d0f8d88b0cf34f9d7 | /ext/hera/wasserstein/include/dnn/parallel/tbb.h | 64c59e0ee985223027151daa201d626258eb299b | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | tgebhart/dionysus_tensorflow | be8757369beb4997b12246c5c7d3cbdbb2fd84bb | 344769bb6d5446c8fd43462b1dfd6a08d35631a8 | refs/heads/master | 2021-09-28T10:03:56.406883 | 2018-11-16T17:15:34 | 2018-11-16T17:15:34 | 112,226,756 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,126 | h | #ifndef PARALLEL_H
#define PARALLEL_H
//#include <iostream>
#include <vector>
#include <boost/range.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#ifdef TBB
#include <tbb/tbb.h>
#include <tbb/concurrent_hash_map.h>
#include <tbb/scalable_allocator.h>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/collections_load_imp.hpp>
#include <boost/serialization/collections_save_imp.hpp>
namespace dnn
{
using tbb::mutex;
using tbb::task_scheduler_init;
using tbb::task_group;
using tbb::task;
template<class T>
struct vector
{
typedef tbb::concurrent_vector<T> type;
};
template<class T>
struct atomic
{
typedef tbb::atomic<T> type;
static T compare_and_swap(type& v, T n, T o) { return v.compare_and_swap(n,o); }
};
template<class Iterator, class F>
void do_foreach(Iterator begin, Iterator end, const F& f) { tbb::parallel_do(begin, end, f); }
template<class Range, class F>
void for_each_range_(const Range& r, const F& f)
{
for (typename Range::iterator cur = r.begin(); cur != r.end(); ++cur)
f(*cur);
}
template<class F>
void for_each_range(size_t from, size_t to, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(from, to, f);
}
template<class Container, class F>
void for_each_range(const Container& c, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::const_range_type, F>, _1, f));
}
template<class Container, class F>
void for_each_range(Container& c, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f));
}
template<class ID, class NodePointer, class IDTraits, class Allocator>
struct map_traits
{
typedef tbb::concurrent_hash_map<ID, NodePointer, IDTraits, Allocator> type;
typedef typename type::range_type range;
};
struct progress_timer
{
progress_timer(): start(tbb::tick_count::now()) {}
~progress_timer()
{ std::cout << (tbb::tick_count::now() - start).seconds() << " s" << std::endl; }
tbb::tick_count start;
};
}
// Serialization for tbb::concurrent_vector<...>
namespace boost
{
namespace serialization
{
template<class Archive, class T, class A>
void save(Archive& ar, const tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{ stl::save_collection(ar, v); }
template<class Archive, class T, class A>
void load(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{
stl::load_collection<Archive,
tbb::concurrent_vector<T,A>,
stl::archive_input_seq< Archive, tbb::concurrent_vector<T,A> >,
stl::reserve_imp< tbb::concurrent_vector<T,A> >
>(ar, v);
}
template<class Archive, class T, class A>
void serialize(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{ split_free(ar, v, file_version); }
template<class Archive, class T>
void save(Archive& ar, const tbb::atomic<T>& v, const unsigned int file_version)
{ T v_ = v; ar << v_; }
template<class Archive, class T>
void load(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version)
{ T v_; ar >> v_; v = v_; }
template<class Archive, class T>
void serialize(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version)
{ split_free(ar, v, file_version); }
}
}
#else
#include <algorithm>
#include <map>
#include <boost/progress.hpp>
namespace dnn
{
template<class T>
struct vector
{
typedef ::std::vector<T> type;
};
template<class T>
struct atomic
{
typedef T type;
static T compare_and_swap(type& v, T n, T o) { if (v != o) return v; v = n; return o; }
};
template<class Iterator, class F>
void do_foreach(Iterator begin, Iterator end, const F& f) { std::for_each(begin, end, f); }
template<class F>
void for_each_range(size_t from, size_t to, const F& f)
{
for (size_t i = from; i < to; ++i)
f(i);
}
template<class Container, class F>
void for_each_range(Container& c, const F& f)
{
BOOST_FOREACH(const typename Container::value_type& i, c)
f(i);
}
template<class Container, class F>
void for_each_range(const Container& c, const F& f)
{
BOOST_FOREACH(const typename Container::value_type& i, c)
f(i);
}
struct mutex
{
struct scoped_lock
{
scoped_lock() {}
scoped_lock(mutex& ) {}
void acquire(mutex& ) const {}
void release() const {}
};
};
struct task_scheduler_init
{
task_scheduler_init(unsigned) {}
void initialize(unsigned) {}
static const unsigned automatic = 0;
static const unsigned deferred = 0;
};
struct task_group
{
template<class Functor>
void run(const Functor& f) const { f(); }
void wait() const {}
};
template<class ID, class NodePointer, class IDTraits, class Allocator>
struct map_traits
{
typedef std::map<ID, NodePointer,
typename IDTraits::Comparison,
Allocator> type;
typedef type range;
};
using boost::progress_timer;
}
#endif // TBB
namespace dnn
{
template<class Range, class F>
void do_foreach(const Range& range, const F& f) { do_foreach(boost::begin(range), boost::end(range), f); }
}
#endif
| [
"[email protected]"
] | |
83881de53e405fca71ff23806072066608fcd793 | 4dd6c13f3fc50d0d0ff84ba3d442eee2d3dae742 | /Engine/Managers/EventManager.cpp | b7d2c47d7e90411950603f29a5718646637d73c3 | [] | no_license | Marcos30004347/AzgardEngine | 570773ad3c3f99628708ff06e4f0674dab0b8977 | ee5f4e3de1b8bcefdab01b0b71e3d4fcca86b4e3 | refs/heads/master | 2022-12-08T17:06:06.632049 | 2020-08-29T01:44:12 | 2020-08-29T01:44:12 | 289,409,420 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,180 | cpp | #include<iostream>
#include<assert.h>
#include "EventManager.hpp"
#include "definitions.hpp"
#ifdef SDL2_IMP
#include <SDL2/SDL.h>
SDL_Event sdl2_event;
#endif
EventManager* EventManager::gInstance = nullptr;
EventManager::EventManager() {}
EventManager::~EventManager() {}
EventManager* EventManager::GetSingletonPtr(void) {
assert(EventManager::gInstance);
return EventManager::gInstance;
}
EventManager& EventManager::GetSingleton(void) {
assert(EventManager::gInstance);
return *EventManager::gInstance;
}
void EventManager::StartUp() {
std::cout << "starting up event manager" << std::endl;
EventManager::gInstance = new EventManager();
}
void EventManager::ShutDown() {
std::cout << "shuting down event manager" << std::endl;
delete EventManager::gInstance;
}
bool EventManager::Pool(Event *event) {
#ifdef SDL2_IMP
int pedding = SDL_PollEvent(&sdl2_event);
switch (sdl2_event.type)
{
case SDL_QUIT:
event->type = QUIT_EVENT;
break;
default:
event->type = NULL_EVENT;
break;
}
#else
#error IMPLEMENTATION NOT DEFINED
#endif
return pedding;
} | [
"[email protected]"
] | |
8578d23f5dcb5dfb05d51a07acc1f3c32a2ca378 | 94b66d01a39eb69cabcbeac2fb1df9131c8faac5 | /OnoMojeLigaLegendi/Crafting.hpp | 3b0678022aca575ce950653a8fa92a016699d66f | [] | no_license | danilomedic/LeagueOfLegends-Project | 687b2b6f663e41099112c5d48d8c731744b071e0 | 006651bf03f774817c2c02a6522039faeaa2b004 | refs/heads/master | 2021-05-17T14:47:35.290317 | 2020-05-08T10:07:06 | 2020-05-08T10:07:06 | 250,828,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,901 | hpp | #ifndef CRAFTING_HPP_INCLUDED
#define CRAFTING_HPP_INCLUDED
#include <cmath>
class Crafting
{
private:
int box, key, keyFrag, orangeEssence, skins;
public:
Crafting()
{
box = 0;
key = 0;
keyFrag = 0;
orangeEssence = 0;
skins = 0;
}
Crafting(int b, int k, int kf, int oE, int s)
{
box = b;
key = k;
keyFrag = kf;
orangeEssence = oE;
skins = s;
}
Crafting(const Crafting &c)
{
box = c.box;
key = c.key;
keyFrag = c.keyFrag;
orangeEssence = c.orangeEssence;
skins = c.skins;
}
~Crafting() {}
void buySkin()
{
if(skins == 0)
{
cout << "Nemate skinova na stanju!" << endl;
return;
}
int price;
cout << "Vase stanje: " << orangeEssence << " orange essence" << endl;
cout << "Koliko kosta skin: ";
cin >> price;
if(orangeEssence > price)
orangeEssence -= price;
else
cout << "Nemate dovoljno orange essence!" << endl;
}
void openBox()
{
if(box == 0)
{
cout << "Nemate ni jednu kutiju!" << endl;
return;
}
int option = rand() % 2 + 1;
int oE = rand() % 1000 + 1;
if(option == 1)
{
orangeEssence += oE;
cout << "Dobili ste " << oE << "orange essenca i stanje vam je " << orangeEssence << "." << endl;
}
if(option == 2)
{
skins += 1;
cout << "Dobili ste 1 skin i sad ih imate " << skins << "." << endl;
}
box -= 1;
}
void forgeKey()
{
if(keyFrag >= 3)
{
keyFrag -= 3;
key += 1;
cout << "Sad imate " << keyFrag << "fragmenta i " << key << "kljuceva" << endl;
}
else
cout << "Nemate dovoljno fragmenta!" << endl;
}
///----------------- GET:
int getBox()const
{
return box;
}
int getKey()const
{
return key;
}
int getKeyFrag()const
{
return keyFrag;
}
int getOrangeEssence()const
{
return orangeEssence;
}
int getSkins()const
{
return skins;
}
///----------------- SET:
void setBox(const int a)
{
box = a;
}
void setKey(const int a)
{
key = a;
}
void setKeyFrag(const int a)
{
keyFrag = a;
}
void setOrangeEssence(const int a)
{
orangeEssence = a;
}
void setSkins(const int a)
{
skins = a;
}
Crafting& operator= (Crafting& c)
{
box = c.box;
key = c.key;
keyFrag = c.keyFrag;
orangeEssence = c.orangeEssence;
skins = c.skins;
return *this;
}
};
#endif // CRAFTING_HPP_INCLUDED
| [
"[email protected]"
] | |
b1bcf5c96e5da91d67fb19ffdce0f2269d7bd395 | cbb3ef472b4f4bbf1480552160aedbd88f230ee3 | /Carpeta_de_proyectos_Arduino_copia_de_seguridad/NodemCU_Firebase_central/NodemCU_Firebase_central.ino | 27d5e0ce48b73f435a3d2f3cb93ee7104a25d57a | [] | no_license | agrgal/ARDUINO_CS | 5a68e236ec660b7ce4e34ee1253b1c0ed27033f0 | f94200dceb4a8d7d27332a3045301daecbb6c979 | refs/heads/master | 2022-09-13T08:06:10.458851 | 2022-08-29T14:30:27 | 2022-08-29T14:30:27 | 242,396,006 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,424 | ino |
/*
* Created by Aurelio Gallardo Rodríguez
* Based on: K. Suwatchai (Mobizt)
*
* Email: [email protected]
*
* CENTRAL. Lectura
*
* Julio - 2019
*
*/
//FirebaseESP8266.h must be included before ESP8266WiFi.h
#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>
#define FIREBASE_HOST "botonpanicoseritium.firebaseio.com"
#define FIREBASE_AUTH "Y0QVBot29hCVGZJQbpVUMr3IKngc7GacE2355bdy"
#define WIFI_SSID "JAZZTEL_shny"
#define WIFI_PASSWORD "3z7s5tvbtu4s"
//Define FirebaseESP8266 data object
FirebaseData bd;
String path = "/Estaciones"; // path a FireBase
char *estaciones[]= {"A","B","C","D","E"}; // Estaciones que voy a controlar
int i=1; // contador general
int activo=0; // Alarma
#define LED 5 // D1(gpio5)
void setup()
{
Serial.begin(115200);
pinMode(LED, OUTPUT);
// conectando a la WIFI
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Conectando a la WiFi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Conectado con IP: ");
Serial.println(WiFi.localIP());
Serial.println();
// Conectando a la bd real Time Firebase
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
//Set database read timeout to 1 minute (max 15 minutes)
Firebase.setReadTimeout(bd, 1000 * 60);
//tiny, small, medium, large and unlimited.
//Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s).
Firebase.setwriteSizeLimit(bd, "unlimited");
}
// Bucle principal
void loop() {
activo=0; // reinicializo la variable
for(i=0;i<=4;i++) {
delay(1);
activo=activo+rFB("/"+(String) estaciones[i]);
}
digitalWrite(LED,(activo>=1)); // activo el LED si es mayor o igual a 1.
}
// Función de lectura
int rFB(String estacion){// lee el dato de la entrada correspondiente
int valor=0;
if (Firebase.getInt(bd, path+estacion)) {
if (bd.dataType() == "int") {
Serial.println("Dato leído: "+ path+estacion +" --> " + (String) bd.intData());
valor = bd.intData(); // retorna el valor
}
} else {
// Si no existe el dato de la estación, salta el error
// Pero el error se muestra en pantalla (bd.errorReason()) Y REINICIALIZA LA UNIDAD, lo cual no quiero.
Serial.println("Estoy dando un error... ojo");
// Serial.println(bd.errorReason());
}
return valor;
}
| [
"[email protected]"
] | |
efee5b91d30e90f44f56ca962bc4d6b383191c2d | e86c079391367e0e401482eb43a850685ac54056 | /ex05/Human.cpp | f99f1bbfa2e2506c59f393e4c073e71ef72e65d8 | [] | no_license | atronk/cpp-01 | c85155abd9cf83b5de370ed1c033ba831f4207b8 | 533a01c039235b436d461df8169169d70c8b97b9 | refs/heads/master | 2023-05-25T17:51:51.451881 | 2021-05-22T17:14:38 | 2021-05-22T17:14:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | #include "Human.hpp"
Human::Human() {
std::cout << "A Human is created!" << std::endl;
}
Human::~Human() {
std::cout << "A Human is destroyed" << std::endl;
}
const Brain& Human::getBrain() const {
return (this->_brain);
}
const std::string& Human::identify() const {
return(this->getBrain().identify());
} | [
"[email protected]"
] | |
e1b1240b296621b5523630b31d65b88d88af048e | d8f1638d63e611ed1619755ca26de4ea96bf1d7b | /PC_Interface/Interface/Interface.ino | 4fdf5155133640117e627d876a20a1401953a9b5 | [] | no_license | schmitfe/Stimulator_FPGA | 27b3e14bdb0330579ac6c8e2bada5dd41820bf74 | 1016d487b89ac5f1de4d3648e18f312f3439ba7e | refs/heads/master | 2023-02-11T19:23:52.376766 | 2019-12-31T15:10:30 | 2019-12-31T15:10:30 | 199,415,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,776 | ino | /*
Copyright (c) 2019 Stefan Kremser
This software is licensed under the MIT License. See the license file for details.
Source: github.com/spacehuhn/SimpleCLI
*/
/*
Adapted by Felix Schmitt to create Interface for Stimulator.
PLEASE NOTE: 115200 is the baud rate and Newline is enabled in the serial monitor
*/
// Inlcude Library Command Line
#include <SimpleCLI.h>
#include <SPI.h>
#include "SdFat.h"
#include "sdios.h"
//#include "Pins.h"
#include "JsonStreamingParser.h"
#include "JsonListener.h"
#include "Parser.h"
#define Channels 2
//Defines number of Channels, not tested with more channels possible errors at the write functin
//for channel adress, trig and
// Create CLI Object
SimpleCLI cli;
// Commands
Command cmdLs;
Command cmdRm;
Command cmdStore;
Command cmdReset;
Command cmdWF;
Command cmdtrig;
Command cmdHelp;
Command cmdDesc;
Command cmdAmpli;
Command cmdInterIv;
Command cmdInterPer;
Command cmdWave;
Command cmdDoutDebug;
// set up variables using the SD utility library functions:
// File system object.
SdFat sd;
// Directory file.
SdFile root;
// Use for file creation in folders.
SdFile file;
//----------Pins---------------//
const unsigned int Ptrig[] = {49, 51, 53}; //Ptrig all, ch0 -x
const unsigned int P_RESET = 68;
const unsigned int P_RESET_CH = 69;
const unsigned int PinsInterPeriod[] = {61, 60, 59, 58, 57, 56, 55, 54};//{54, 55, 56, 57, 58, 59, 60, 61};
const unsigned int PinsInterInterval[] = {10, 9, 8, 7, 6, 5, 4, 3}; //{3, 4, 5, 6, 7,8,9,10};
const unsigned int PinsAmplitude[] = {21, 20, 19, 18};
const unsigned int PWrite = 63;
const unsigned int PWrite2 = 36;
const unsigned int PWrite3 = 37;
const unsigned int P_EnWrite = 62;
const unsigned int PWaveAddr[] = {64};
const unsigned int PWriteConfig = {65};
const unsigned int PChanAdress[] = {66};
const unsigned int PChanAdress2[] = {38};
const unsigned int PChanAdress3[] = {39};
const unsigned int PDout[] = {25, 26, 27, 28, 14, 15, 29, 11}; // Has to be on same port of SAM, Arduino ports are not ordered!
const unsigned int chipSelect = 52; //SD-Card
//---------------buffers---------------------//
char bufferJson[40];
//-------struct to store data of channels----//
typedef struct {
int amplitude;
int iinterval;
int iperiod;
int waveadress;
} SChannelSet;
SChannelSet *ChannelSet = NULL;
void setup() {
//--------setup of pins---------------//
int ii;
for ( ii = 0; ii < sizeof(Ptrig) / sizeof(Ptrig[0]); ii = ii + 1 ) {
pinMode(Ptrig[ii], OUTPUT);
digitalWrite(Ptrig[ii], LOW);
}
for ( ii = 0; ii < sizeof(PinsInterPeriod) / sizeof(PinsInterPeriod[0]); ii = ii + 1 ) {
pinMode(PinsInterPeriod[ii], OUTPUT);
digitalWrite(PinsInterPeriod[ii], LOW);
}
for ( ii = 0; ii < sizeof(PinsInterInterval) / sizeof(PinsInterInterval[0]); ii = ii + 1 ) {
pinMode(PinsInterInterval[ii], OUTPUT);
digitalWrite(PinsInterInterval[ii], LOW);
}
for ( ii = 0; ii < sizeof(PWaveAddr) / sizeof(PWaveAddr[0]); ii = ii + 1 ) {
pinMode(PWaveAddr[ii], OUTPUT);
digitalWrite(PWaveAddr[ii], LOW);
}
for ( ii = 0; ii < sizeof(PinsAmplitude) / sizeof(PinsAmplitude[0]); ii = ii + 1 ) {
pinMode(PinsAmplitude[ii], OUTPUT);
digitalWrite(PinsAmplitude[ii], LOW);
}
for ( ii = 0; ii < sizeof(PChanAdress) / sizeof(PChanAdress[0]); ii = ii + 1 ) {
pinMode(PChanAdress[ii], OUTPUT);
digitalWrite(PChanAdress[ii], LOW);
pinMode(PChanAdress2[ii], OUTPUT);
digitalWrite(PChanAdress2[ii], LOW);
pinMode(PChanAdress3[ii], OUTPUT);
digitalWrite(PChanAdress3[ii], LOW);
}
for ( ii = 0; ii < sizeof(PDout) / sizeof(PDout[0]); ii = ii + 1 ) {
pinMode(PDout[ii], OUTPUT);
digitalWrite(PDout[ii], LOW);
}
pinMode(P_RESET, OUTPUT);
digitalWrite(P_RESET, LOW);
pinMode(P_RESET_CH, OUTPUT);
digitalWrite(P_RESET_CH, LOW);
pinMode(PWrite, OUTPUT);
digitalWrite(PWrite, LOW);
pinMode(PWrite2, OUTPUT);
digitalWrite(PWrite, LOW);
pinMode(PWrite3, OUTPUT);
digitalWrite(PWrite, LOW);
pinMode(P_EnWrite, OUTPUT);
digitalWrite(P_EnWrite, LOW);
pinMode(PWriteConfig, OUTPUT);
digitalWrite(PWriteConfig, LOW);
//--------setup of interface---------------//
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("\nInitializing SD card...");
// we'll use the initialization code from the utility libraries
// since we're just testing if the card is working!
// Initialize at the highest speed supported by the board that is
// not over 50 MHz. Try a lower speed if SPI errors occur.
if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { //should be 50
sd.initErrorHalt();
}
//--------setup of channel settings---------------//
ChannelSet = (SChannelSet*) malloc(sizeof * ChannelSet * (Channels + 1));
//Channel zero contains defaultvalues
ChannelSet[0].amplitude = 1;
ChannelSet[0].iinterval = 0;
ChannelSet[0].iperiod = 0;
ChannelSet[0].waveadress = 0;
for ( ii = 1; ii < Channels + 1 ; ii = ii + 1 ) {
ChannelSet[ii].amplitude = ChannelSet[0].amplitude;
ChannelSet[ii].iinterval = ChannelSet[0].iinterval;
ChannelSet[ii].iperiod = ChannelSet[0].iperiod;
ChannelSet[ii].waveadress = ChannelSet[0].waveadress;
}
//--------creation of commands---------------//
cmdLs = cli.addCmd("ls");
cmdRm = cli.addCmd("rm");
cmdRm.addPosArg("file");
cmdStore = cli.addCmd("store");
cmdStore.addPosArg("file");
cmdReset = cli.addCmd("reset");
cmdReset.addPosArg("ID");
cmdWF = cli.addCmd("WF");
cmdWF.addPosArg("file");
cmdWF.addPosArg("ID");
cmdtrig = cli.addCmd("trig");
cmdtrig.addPosArg("ID");
cmdDesc = cli.addCmd("descrip");
cmdDesc.addPosArg("file");
cmdAmpli = cli.addCmd("amp");
cmdAmpli.addPosArg("ID");
cmdAmpli.addPosArg("value");
cmdInterIv = cli.addCmd("iniv");
cmdInterIv.addPosArg("ID");
cmdInterIv.addPosArg("value");
cmdInterPer = cli.addCmd("inper");
cmdInterPer.addPosArg("ID");
cmdInterPer.addPosArg("value");
cmdWave = cli.addCmd("wave");
cmdWave.addPosArg("ID");
cmdWave.addPosArg("value");
cmdHelp = cli.addCommand("help");
cmdDoutDebug=cli.addCmd("ddeb"); //debuggig command
cmdDoutDebug.addPosArg("value");
Serial.println("CLI: type help for commandlist");
}
void loop() {
//--------CLI loop---------------//
if (Serial.available()) {
String input = Serial.readStringUntil('\n');
if (input.length() > 0) {
// Serial.print("# ");
cli.parse(input);
}
}
if (cli.available()) {
Command c = cli.getCmd();
int argNum = c.countArgs();
/* Serial.print("> ");
// Serial.print(c.getName());
// Serial.print(' ');
for (int i = 0; i < argNum; ++i) {
Argument arg = c.getArgument(i);
// if(arg.isSet()) {
Serial.print(arg.toString());
Serial.print(' ');
}
Serial.println();
*/
//--------if input available find corresponding command---------------//
if (c == cmdLs) {
listFolder();
} else if (c == cmdRm) {
RemoveDir (c.getArgument(0));
} else if (c == cmdStore) {
SaveFile(c.getArgument(0));
} else if (c == cmdDesc) {
description(c.getArgument(0));
} else if (c == cmdAmpli) {
setAmplitude(c.getArgument(0), c.getArgument(1));
} else if (c == cmdInterIv) {
setInterInterval(c.getArgument(0), c.getArgument(1));
} else if (c == cmdInterPer) {
setInterPeriod(c.getArgument(0), c.getArgument(1));
} else if (c == cmdWave) {
setWaveadress(c.getArgument(0), c.getArgument(1));
} else if (c == cmdReset) {
reset(c.getArgument(0));
} else if (c == cmdWF) {
loadWaveform(c.getArgument(0), c.getArgument(1));
} else if (c == cmdtrig) {
Argument str = c.getArgument(0);
trigger(str.getValue().toInt());
} else if (c == cmdHelp) {
Serial.println("Help:");
Serial.println(cli.toString());
} else if(c == cmdDoutDebug){
Serial.println(c.getArgument(0).getValue());
WriteDoutDebug(c.getArgument(0));
}
}
if (cli.errored()) {
CommandError cmdError = cli.getError();
Serial.print("ERROR: ");
Serial.println(cmdError.toString());
if (cmdError.hasCommand()) {
Serial.print("Did you mean \"");
Serial.print(cmdError.getCommand().toString());
Serial.println("\"?");
}
}
}
//--------functions to call in loop---------------//
void storeChannel(Argument id)
{
unsigned long curTime;
digitalWrite(PWriteConfig, LOW);
curTime=micros();
Channeladress(id.getValue().toInt());
writePinArray(ChannelSet[id.getValue().toInt()].amplitude, PinsAmplitude, sizeof(PinsAmplitude) / sizeof(PinsAmplitude[0]));
writePinArray(ChannelSet[id.getValue().toInt()].iperiod, PinsInterPeriod, sizeof(PinsInterPeriod) / sizeof(PinsInterPeriod[0]));
writePinArray(ChannelSet[id.getValue().toInt()].iinterval, PinsInterInterval, sizeof(PinsInterInterval) / sizeof(PinsInterInterval[0]));
writePinArray( ChannelSet[id.getValue().toInt()].waveadress, PWaveAddr, sizeof(PWaveAddr) / sizeof(PWaveAddr[0]));
while(micros()-curTime <2);
digitalWrite(PWriteConfig, HIGH);
}
void writePinArray(int value, const unsigned int *Pins, int NPins)
{
int ii;
for(ii = 0; ii < NPins ; ii = ii + 1 ) {
if( bitRead(value,ii)==1){
digitalWrite(Pins[NPins-1-ii],HIGH);
} else{
digitalWrite(Pins[NPins-1-ii],LOW);
}
}
}
void setAmplitude(Argument id, Argument value)
{
ChannelSet[id.getValue().toInt()].amplitude = value.getValue().toInt();
storeChannel(id);
}
void setInterInterval(Argument id, Argument value)
{
ChannelSet[id.getValue().toInt()].iinterval = value.getValue().toInt();
storeChannel(id);
}
void setWaveadress(Argument id, Argument value)
{
ChannelSet[id.getValue().toInt()].waveadress = value.getValue().toInt();
storeChannel(id);
}
void setInterPeriod(Argument id, Argument value)
{
ChannelSet[id.getValue().toInt()].iperiod = value.getValue().toInt();
storeChannel(id);
}
void loadWaveform(Argument pathStr, Argument id)
{
bool WriteWFs = true; //Let parser write to FPGA
String Description = "";
//reset(id);
JsonStreamingParser parser;
Listener listener(&WriteWFs, &Description, PWrite, PWrite2, PWrite3, PWriteConfig, PWaveAddr, 2); //bad way of introducing additional parameters
parser.setListener(&listener);
File myFile;
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
sd.chdir("WF");
char path[12];
pathStr.getValue().toCharArray(path, 12);
myFile = sd.open(path, FILE_READ);
Channeladress(id.getValue().toInt());
digitalWrite(P_EnWrite, HIGH);
unsigned long curTime;
curTime = micros();
while (micros() - curTime < 500);
while (myFile.available()) {
parser.parse(myFile.read());
}
myFile.close();
digitalWrite(P_EnWrite, LOW);
Channeladress(0);
WriteWFs = false;
}
void description(Argument pathStr)
{
bool WriteWFs = false;
String Description = "";
JsonStreamingParser parser;
Listener listener(&WriteWFs, &Description,PWrite, PWrite2, PWrite3, PWriteConfig, PWaveAddr, 2); //bad way of introducing additional parameters
parser.setListener(&listener);
File myFile;
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
sd.chdir("WF");
char path[12];
pathStr.getValue().toCharArray(path, 12);
myFile = sd.open(path, FILE_READ);
WriteWFs = false; //Let parser write to FPGA
while (myFile.available()) {
parser.parse(myFile.read());
}
myFile.close();
Serial.print("Description of " + pathStr.getValue() + " : ");
Serial.println(Description);
Description = "";
}
void listFolder()
{
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
if (!sd.chdir("WF")) {
sd.mkdir("WF");
sd.chdir("WF");
}
sd.ls("/WF", LS_R);
}
void trigger(int id)
{
unsigned long curTime;
digitalWrite(Ptrig[id], HIGH);
curTime = micros();
while (micros() - curTime < 20);
digitalWrite(Ptrig[id], LOW);
}
void reset(Argument id)
{
int ii = 0;
unsigned long curTime;
if (id.getValue().toInt() == 0) {
digitalWrite(P_RESET, HIGH);
curTime = micros();
while (micros() - curTime < 2);
digitalWrite(P_RESET, LOW);
for ( ii = 1; ii < Channels + 1 ; ii = ii + 1 ) {
ChannelSet[ii].amplitude = ChannelSet[0].amplitude;
ChannelSet[ii].iinterval = ChannelSet[0].iinterval;
ChannelSet[ii].iperiod = ChannelSet[0].iperiod;
ChannelSet[ii].waveadress = ChannelSet[0].waveadress;
}
} else {
digitalWrite(P_RESET_CH, HIGH);
curTime = micros();
ChannelSet[id.getValue().toInt()].amplitude = ChannelSet[0].amplitude;
ChannelSet[id.getValue().toInt()].iinterval = ChannelSet[0].iinterval;
ChannelSet[id.getValue().toInt()].iperiod = ChannelSet[0].iperiod;
ChannelSet[id.getValue().toInt()].waveadress = ChannelSet[0].waveadress;
while (micros() - curTime < 2);
storeChannel(id);
digitalWrite(P_RESET_CH, LOW);
storeChannel(id);
}
}
void Channeladress(int id)
{
int adress=0;
if (id == 0) {
digitalWrite(*PChanAdress, LOW);
digitalWrite(*PChanAdress2, LOW);
digitalWrite(*PChanAdress3, LOW);
} else {
writePinArray(id-1, PChanAdress, sizeof(PChanAdress) / sizeof(PChanAdress[0]));
writePinArray(id-1, PChanAdress2, sizeof(PChanAdress2) / sizeof(PChanAdress2[0]));
writePinArray(id-1, PChanAdress3, sizeof(PChanAdress3) / sizeof(PChanAdress3[0]));
}
}
void RemoveDir (Argument str)
{
char path[12];
str.getValue().toCharArray(path, 12);
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
sd.chdir("WF");
sd.remove(path);
}
void SaveFile (Argument str)
{
File myFile;
char path[12];
uint8_t incomingByte;
str.getValue().toCharArray(path, 12);
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
sd.chdir("WF");
sd.remove(path);
myFile = sd.open(path, FILE_WRITE);
Serial.println("Please send File.");
while (Serial.available() == 0);
// read the incoming byte:
incomingByte = Serial.read();
while (incomingByte != 10) {
myFile.write(incomingByte);
while (Serial.available() == 0);
incomingByte = Serial.read();
}
myFile.close();
Serial.println("File saved!");
}
//Debug function to find right order of pins
void WriteDoutDebug(Argument value)
{
unsigned long curTime;
PIOD->PIO_SODR= value.getValue().toInt();
PIOD->PIO_CODR=~value.getValue().toInt()&0x00FF;
digitalWrite(PWrite, LOW);
curTime=micros();
while(micros()-curTime <20);
digitalWrite(PWrite, HIGH);
curTime=micros();
while(micros()-curTime <20);
}
| [
"[email protected]"
] | |
8cd8538339e5a1170a27aef802a5f18cacfeeeab | 6115a9fffbc4e0d94a8aae1bffe79557ae059a09 | /FinalProject/avltreeindex.h | 2f774eea408d83aa6352573bdd3f0f40ebf8690f | [] | no_license | natesotoole1/SearchEngine | 74bc40a3b438758699a9f3a662a61c9f72125a96 | b3623634acda01f9135e80cd7d00deae3d8f756c | refs/heads/master | 2021-01-16T22:08:15.300799 | 2016-04-12T12:39:08 | 2016-04-12T12:39:08 | 45,565,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,139 | h |
#ifndef AVLTreeIndex_H
#define AVLTreeIndex_H
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include "indexinterface.h"
#include "term.h"
// git
using namespace std;
/*! \brief
* AVL Node implementation for the AVL Tree structure.
*/
// Node declaration
struct AVL_Node
{
Term* data;///< Term pointer where all the data is held
//struct AVL_Node root;
struct AVL_Node *left; ///< left child
struct AVL_Node *right; ///< right child
int height; ///< height of tree
};
/*! \brief
* AVLTreeIndex.h has AVL Trees public and private classes in them.
*/
// Class declaration
class AVLTreeIndex
{
public:
AVLTreeIndex(); ///< constructor
void insert(Term*); ///< public insert function that calls the private function
AVL_Node* balance(AVL_Node*&); ///< figures out when to rotate child or not
int height(AVL_Node *&); ///< returns the height of the tree
int diff(AVL_Node *&); ///< returns the difference in height
int max(int, int); ///< gets the max height
AVL_Node* rotateRightChild(AVL_Node*&); ///< rotate right child
AVL_Node* rotateLeftChild(AVL_Node*&); ///< rotate left child
AVL_Node* doubleLeftChild(AVL_Node*&); ///< rotate left child than rotate right child
AVL_Node* doubleRightChild(AVL_Node*&); ///< rotate right child than rotate left child
Term* find(string); ///< public find function that is called from the interface and than passes it to private function
void createPersistence(int, ofstream&); ///< public call to create persistence than calls the private function
void clearTree(); ///< public call to clear index than calls the private function
private:
AVL_Node* root; ///< root of the tree
void insert(AVL_Node*& ,Term*); ///< inserts node if null than checks balance to see if it is needed to rotate
void createPersistence(AVL_Node*& , int, ofstream&); ///< creates the persistence from each individual avl tree
void continue_search(AVL_Node*& curr, string word); ///< finds word called by query
void clearTree(AVL_Node*); /// <clear the tree
};
#endif // AVLTreeINDEX_H
| [
"[email protected]"
] | |
80e9638e9a9955c45831c86dc3497224eea00c9c | 4f2f4ca1cb010ab79ad3933e73dce6671f012054 | /SK-Lib/test_sk_header.cpp | 2491fbed63d9441372bd23eb682d72c41f371115 | [] | no_license | sksavigit/CPP-Progs | f95cfbea5a3caa40baca8637d55e9c1d5a000670 | 178a414d3c424a18cfe8cf6f9c3df697dffe2993 | refs/heads/master | 2023-02-17T15:01:02.283778 | 2021-01-16T13:09:01 | 2021-01-16T13:09:01 | 328,104,206 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 485 | cpp | #include<iostream>
#include "sklib_numbers.h"
#include "sklib_iostream.h"
using namespace std;
int main(){
char n1[]="0000000000000000000000000001";
char n2[]="1111123424324243234234234324";
cout << "\n Num1:" <<n1;
cout << "\n Num2:" <<n2;
cout << "\n Outp:";
int n1Size=sizeof(n1)/sizeof(n1[0]);
int n2Size=sizeof(n2)/sizeof(n2[0]);
char res[n1Size>n2Size ? n1Size:n2Size];
sum_two_big_numbers(n1,n2,res);
cout << res<< "\n";
return 0;
}
| [
"[email protected]"
] | |
2ccf5828b8559f26a0292a7e1ba3df44cb793dc8 | 55bfe899250607e99aa6ed20c5d688200ce4225f | /spot_real/Control/Teensy/SpotMiniMini/lib/ros_lib/moveit_msgs/MoveGroupActionGoal.h | bcb0e3ee2eff64549f920d6d8621e436564d2a4b | [
"MIT"
] | permissive | OpenQuadruped/spot_mini_mini | 96aef59505721779aa543aab347384d7768a1f3e | c7e4905be176c63fa0e68a09c177b937e916fa60 | refs/heads/spot | 2022-10-21T04:14:29.882620 | 2022-10-05T21:33:53 | 2022-10-05T21:33:53 | 251,706,548 | 435 | 125 | MIT | 2022-09-02T07:06:56 | 2020-03-31T19:13:59 | C++ | UTF-8 | C++ | false | false | 1,428 | h | #ifndef _ROS_moveit_msgs_MoveGroupActionGoal_h
#define _ROS_moveit_msgs_MoveGroupActionGoal_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 "moveit_msgs/MoveGroupGoal.h"
namespace moveit_msgs
{
class MoveGroupActionGoal : public ros::Msg
{
public:
typedef std_msgs::Header _header_type;
_header_type header;
typedef actionlib_msgs::GoalID _goal_id_type;
_goal_id_type goal_id;
typedef moveit_msgs::MoveGroupGoal _goal_type;
_goal_type goal;
MoveGroupActionGoal():
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 "moveit_msgs/MoveGroupActionGoal"; };
const char * getMD5(){ return "df11ac1a643d87b6e6a6fe5af1823709"; };
};
}
#endif
| [
"[email protected]"
] | |
849e17e440d0e9523fb0dd1a5f7f9d2bf5e1f416 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5686313294495744_0/C++/vidhan13j07/test.cpp | 5edfd10037fb916f2f5fbdef7cf9305b0b29d5b9 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,489 | cpp | #include<bits/stdc++.h>
#define sc(v) v.size()
#define eb push_back
#define pb pop_back
#define f(i,a,b) for(int i=a;i<b;i++)
#define TC() int t;cin>>t;while(t--)
#define all(x) x.begin(),x.end()
#define mk make_pair
#define fi first
#define se second
#define endl "\n"
#define eps 1e-9
#define pw(x) (1ll<<(x))
#define trace1(x) cout <<#x<<": "<<x<<endl;
#define trace2(x, y) cout <<#x<<": "<<x<<" | "<<#y<<": "<<y<< endl;
#define trace3(x, y, z) cout <<#x<<": "<<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl;
#define trace4(a, b, c, d) cout <<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl;
#define trace5(a, b, c, d, e) cout <<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<<": "<<e<<endl;
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<string,string> pi;
typedef pair<ll,ll> pll;
inline bool EQ(double a,double b) { return fabs(a - b) < 1e-9; }
inline void set_bit(int & n, int b) { n |= pw(b); }
inline void unset_bit(int & n, int b) { n &= ~pw(b); }
int main()
{
#ifndef ONLINE_JUDGE
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
#endif
clock_t tStart = clock();
int tc = 1;
int n;
map< pi,int > mp;
vector< pi > v;
set< pi > vv;
vector<string> f,rr;
string x,y;
set<string> a,b;
TC()
{
printf("Case #%d: ", tc++);
mp.clear();
v.clear();
a.clear();
b.clear();
scanf("%d",&n);
f(i,0,n)
{
cin>>x>>y;
v.eb(mk(x,y));
mp[mk(x,y)] = 1;
}
int ans = 0;
f(i,0,1 << n)
{
f.clear();
rr.clear();
vv.clear();
int c = 0;
f(j,0,n)
if(i&(1 << j))
{
f.eb(v[j].fi);
rr.eb(v[j].se);
vv.insert(v[j]);
}
f(j,0,sc(f))
f(k,0,sc(rr))
{
if(vv.find(mk(f[j],rr[k])) != vv.end())
continue;
if(mp[mk(f[j],rr[k])])
c++;
}
ans = max(ans,c);
}
printf("%d\n",ans);
}
//printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
| [
"[email protected]"
] | |
cbee84c2e52dc1341528f8254aaf41ac321f936c | 2869112fdc836e565f9fe68e290affc1e223c1d8 | /pythran/pythonic/include/__builtin__/set/isdisjoint.hpp | 10ac38270e03ff35d15b79143e6164321a7b5afb | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | coyotte508/pythran | ab26e9ddb9a9e00e77b457df316aa33dc8435914 | a5da78f2aebae712a2c6260ab691dab7d09e307c | refs/heads/master | 2021-01-15T10:07:09.597297 | 2015-05-01T07:00:42 | 2015-05-01T07:00:42 | 35,020,532 | 0 | 0 | null | 2015-05-04T07:27:29 | 2015-05-04T07:27:29 | null | UTF-8 | C++ | false | false | 621 | hpp | #ifndef PYTHONIC_INCLUDE_BUILTIN_SET_ISDISJOINT_HPP
#define PYTHONIC_INCLUDE_BUILTIN_SET_ISDISJOINT_HPP
#include "pythonic/utils/proxy.hpp"
#include "pythonic/types/set.hpp"
namespace pythonic {
namespace __builtin__ {
namespace set {
template<class T, class U>
bool
isdisjoint(types::set<T> const& calling_set, U const& arg_set);
template<class U>
bool
isdisjoint(types::empty_set const& calling_set, U const& arg_set);
PROXY_DECL(pythonic::__builtin__::set, isdisjoint);
}
}
}
#endif
| [
"[email protected]"
] | |
e80178df0d6d8e25163f4e3d848c8940e1e40d2f | 8ea2c608d0ea52bdf26e045ada1367b93f76c046 | /OpenGL/objeto.h | 6ebbac6737b5475febb0a458045ceb0aa82a7255 | [] | no_license | Alexandrecajamos/geometria_comp | 0aedf467e337ffc2627e68564c9ade03354f3881 | d0264e2ec8bfb0da50c1ee8ec14042779d860612 | refs/heads/master | 2021-04-12T09:52:11.906345 | 2018-06-21T21:17:36 | 2018-06-21T21:17:36 | 126,262,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | h | #ifndef OBJETO_H
#define OBJETO_H
#include<vector>
#include "stdio.h"
#include "coord_3d.h"
#include "esfera.h"
#include <fstream>
#include "face.h"
#include<cmath>
#define TAM 4
class Objeto
{
public:
Objeto();
void addPoint(float x, float y, float z);
void addFace(int iP1, int iP2, int iP3);
float Ray_intersept(Coord_3D Po, Coord_3D Dir, int *iFace);
bool Tiro(Coord_3D Ponto);
void calc_Esfera();
void ImpPoints();
void ImpFaces();
bool Obstaculo(Coord_3D Pint, Coord_3D l);
void Libera();
void Ordena(int eixo);
void CopiaPontos(Objeto* O);
Coord_3D Centro();
float Area_Externa();
float Volume();
int MaiorX();//Retorna Indice
int MenorX();//Retorna Indice
int MaiorY();//Retorna Indice
int MenorY();//Retorna Indice
int MaiorZ();//Retorna Indice
int MenorZ();//Retorna Indice
bool Pertence(int iP1, int iP2, int iP3);
Esfera Esf;
std::vector<Coord_3D*> points;
std::vector<Face*> faces;
};
#endif // OBJETO_H
| [
"[email protected]"
] | |
334f0712fc8566ea028524f0cd56702b83f8dbd4 | 9b273539e02cca8d408e8cf793007ee84e6637d5 | /ext/bliss/src/iterators/edge_iterator.hpp | 2217a705bef1dc4b94ba3493a6facab66fe6ad3e | [
"Apache-2.0"
] | permissive | tuan1225/parconnect_sc16 | 23b82c956eed4dabe5deec8bd48cc8ead91af615 | bcd6f99101685d746cf30e22fa3c3f63ddd950c9 | refs/heads/master | 2020-12-24T12:01:13.846352 | 2016-11-07T16:51:29 | 2016-11-07T16:51:29 | 73,055,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,760 | hpp | /*
* edge_iterator.hpp
*
* Created on: Aug 4, 2015
* Author: yongchao
*/
#ifndef EDGE_ITERATOR_HPP_
#define EDGE_ITERATOR_HPP_
#include <iterator>
#include "common/alphabets.hpp"
namespace bliss
{
namespace iterator
{
// careful with the use of enable_if. evaluation should occur at function call time,
// i.e. class template params will be evaluated with no substitution.
// instead, a function should declare a template parameter proxy for the class template parameter.
// then enable_if evaluates using the proxy.
// e.g. template< class c = C; typename std::enable_if<std::is_same<c, std::string>::value, int>::type x = 0>
/**
* @class edge_iterator
* @brief given a k-mer position, retrieve its left and right bases, including the dummy bases at both ends
* @details specializations of this class uses a byte to manage the edge info.
* upper 4 bits holds the left base (encoded), lower 4 bits holds the right base (encoded)
*
* no reverse complement or reordering is applied.
*
* edge iterator should be valid for std::distance(_data_end - _data_start - k + 1) iterations.
*/
template<typename IT, typename ALPHA = bliss::common::DNA16>
class edge_iterator : public ::std::iterator<::std::forward_iterator_tag, uint8_t>
{
protected:
// curr position
IT _curr;
//previous position
IT _left;
//a position of distance k from the _curr on the right
IT _right;
/*data*/
const IT _data_start;
const IT _data_end;
public:
typedef ALPHA Alphabet;
typedef edge_iterator<IT, ALPHA> self_type; /*define edge iterator type*/
typedef uint8_t edge_type; //type to represent an edge
// accessors
IT& getBase()
{
return _curr;
}
//constructor
edge_iterator(IT data_start, IT data_end, const uint32_t k)
: _curr (data_start), _left(data_end), _right(data_start), _data_start(data_start), _data_end(data_end)
{
/*compute the offset*/
::std::advance(_curr, k - 1);
_right = _curr;
::std::advance(_right, 1);
}
edge_iterator(IT data_end)
: _curr(data_end), _left(data_end), _right(data_end), _data_start(data_end), _data_end(data_end)
{
}
/// copy constructor
edge_iterator(const self_type& Other)
: _curr (Other._curr), _left(Other._left), _right(Other._right),
_data_start(Other._data_start), _data_end(Other._data_end)
{
/*do nothing*/
}
/// copy assignment iterator
self_type& operator=(const self_type& Other)
{
_curr = Other._curr;
_left = Other._left;
_right = Other._right;
_data_start = Other._data_start;
_data_end = Other._data_end;
return *this;
}
/// increment to next matching element in base iterator
self_type& operator++()
{ // if _curr at end, subsequent calls should not move _curr.
// on call, if not at end, need to move first then evaluate.
if (_curr == _data_end){ // if at end, don't move it.
return *this;
}
/*save the previous position*/
if (_left == _data_end) _left = _data_start;
else ++_left;
/*move forward by 1*/
++_curr;
/*ensure that _right does not exceed _end*/
if(_right != _data_end){
++_right;
}
return *this;
}
/**
* post increment. make a copy then increment that.
*/
self_type operator++(int)
{
self_type output(*this);
this->operator++();
return output;
}
/// compare 2 filter iterators
inline bool operator==(const self_type& rhs)
{
return _curr == rhs._curr;
}
/// compare 2 filter iterators
inline bool operator!=(const self_type& rhs)
{
return _curr != rhs._curr;
}
/// dereference operator. _curr is guaranteed to be valid
inline edge_type operator*()
{
/*using four bits to represent an edge*/
if(_left != _data_end && _right != _data_end){
/*internal k-mer node*/
return (ALPHA::FROM_ASCII[*_left] << 4) | ALPHA::FROM_ASCII[*_right];
}else if(_left == _data_end && _right != _data_end){ /*the left-most k-mer node*/
return ALPHA::FROM_ASCII[*_right];
}else if(_left != _data_end && _right == _data_end){ /*the rigth-most k-mer node*/
return ALPHA::FROM_ASCII[*_left] << 4;
}
/*if(_left == _end && _right == _end)*/
return 0;
}
};
template<typename IT>
using DNA16_edge_iterator = edge_iterator<IT, bliss::common::DNA16>;
template<typename IT>
using DNA_IUPAC_edge_iterator = edge_iterator<IT, bliss::common::DNA_IUPAC>;
// not suitable for edge iterator since there is no value for unknown char.
template<typename IT>
using DNA_edge_iterator = edge_iterator<IT, bliss::common::DNA>;
template<typename IT>
using DNA5_edge_iterator = edge_iterator<IT, bliss::common::DNA5>;
// not suitable for edge iterator since there is no value for unknown char.
template<typename IT>
using RNA_edge_iterator = edge_iterator<IT, bliss::common::RNA>;
template<typename IT>
using RNA5_edge_iterator = edge_iterator<IT, bliss::common::RNA5>;
/*EdgeType = short unsigned int*/
template<typename IT>
class edge_iterator<IT, bliss::common::ASCII>: public ::std::iterator<::std::forward_iterator_tag, uint16_t>
{
protected:
// curr position
IT _curr;
//previous position
IT _left;
//a position of distance k from the _curr on the right
IT _right;
/*data*/
const IT _data_start;
const IT _data_end;
public:
typedef bliss::common::ASCII Alphabet;
typedef edge_iterator<IT, bliss::common::ASCII> self_type; /*define edge iterator type*/
typedef uint16_t edge_type; //type to represent an edge
// accessors
IT& getBase()
{
return _curr;
}
//constructor
edge_iterator(IT data_start, IT data_end, const uint32_t k)
: _curr (data_start), _left(data_end), _right(data_start), _data_start(data_start), _data_end(data_end)
{
/*compute the offset*/
::std::advance(_curr, k-1);
_right = _curr;
::std::advance(_right, 1);
}
edge_iterator(IT data_end)
: _curr(data_end), _left(data_end), _right(data_end), _data_start(data_end), _data_end(data_end)
{
}
/// copy constructor
edge_iterator(const self_type& Other)
: _curr (Other._curr), _left(Other._left), _right(Other._right),
_data_start(Other._data_start), _data_end(Other._data_end)
{
/*do nothing*/
}
/// copy assignment iterator
self_type& operator=(const self_type& Other)
{
_curr = Other._curr;
_left = Other._left;
_right = Other._right;
_data_start = Other._data_start;
_data_end = Other._data_end;
return *this;
}
/// increment to next matching element in base iterator
self_type& operator++()
{ // if _curr at end, subsequent calls should not move _curr.
// on call, if not at end, need to move first then evaluate.
if (_curr == _data_end){ // if at end, don'IT move it.
return *this;
}
/*save the previous position*/
if (_left == _data_end) _left = _data_start;
else ++_left;
/*move forward by 1*/
++_curr;
/*ensure that _right does not exceed _end*/
if(_right != _data_end){
++_right;
}
return *this;
}
/**
* post increment. make a copy then increment that.
*/
self_type operator++(int)
{
self_type output(*this);
this->operator++();
return output;
}
/// compare 2 filter iterators
inline bool operator==(const self_type& rhs)
{
return _curr == rhs._curr;
}
/// compare 2 filter iterators
inline bool operator!=(const self_type& rhs)
{
return _curr != rhs._curr;
}
/// dereference operator. _curr is guaranteed to be valid
inline edge_type operator*()
{
/*using 8 bits to represent an edge*/
if(_left != _data_end && _right != _data_end){
/*internal k-mer node*/
return (*_left << 8) | *_right;
}else if(_left == _data_end && _right != _data_end){ /*the left-most k-mer node*/
return *_right & 0x0ff;
}else if(_left != _data_end && _right == _data_end){ /*the rigth-most k-mer node*/
return *_left << 8;
}
/*if(_left == _end && _right == _end)*/
return 0;
}
};
template<typename IT>
using raw_edge_iterator = edge_iterator<IT, bliss::common::ASCII>;
} // iterator
} // bliss
#endif /* EDGE_ITERATOR_HPP_ */
| [
"[email protected]"
] | |
e583e7116773107273d5fb8024b730ef48f23333 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/pdfium/xfa/fxfa/parser/cxfa_solid.cpp | da8de3f6aca0fae9e6ba41523e382edcb9d6be21 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 1,216 | cpp | // Copyright 2017 The PDFium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fxfa/parser/cxfa_solid.h"
#include "fxjs/xfa/cjx_node.h"
#include "xfa/fxfa/parser/cxfa_document.h"
namespace {
const CXFA_Node::PropertyData kSolidPropertyData[] = {
{XFA_Element::Extras, 1, {}},
};
const CXFA_Node::AttributeData kSolidAttributeData[] = {
{XFA_Attribute::Id, XFA_AttributeType::CData, nullptr},
{XFA_Attribute::Use, XFA_AttributeType::CData, nullptr},
{XFA_Attribute::Usehref, XFA_AttributeType::CData, nullptr},
};
} // namespace
CXFA_Solid::CXFA_Solid(CXFA_Document* doc, XFA_PacketType packet)
: CXFA_Node(doc,
packet,
{XFA_XDPPACKET::kTemplate, XFA_XDPPACKET::kForm},
XFA_ObjectType::Node,
XFA_Element::Solid,
kSolidPropertyData,
kSolidAttributeData,
cppgc::MakeGarbageCollected<CJX_Node>(
doc->GetHeap()->GetAllocationHandle(),
this)) {}
CXFA_Solid::~CXFA_Solid() = default;
| [
"[email protected]"
] | |
e58b6df0e5b4c66f0d095c33c45ddcbea6ffceae | 9929f9f832b21f641f41fc91cbf604643f9770dd | /src/txt/mainRegressionP.cpp | 16ad10a2e0e2cf8996b46a19dd9d38b275156452 | [] | no_license | JeanSar/rogue | 1cd4d8d18fe8ae6ba7d32f3af556259f5a65b2fc | a4c8945a8ae09984a4b417a3bac5ffd029e46fa7 | refs/heads/master | 2023-03-01T01:24:12.351208 | 2021-01-28T19:53:17 | 2021-01-28T19:53:17 | 331,929,934 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | cpp | #include "Personnages.h"
using namespace std;
int main(){
srand(time(NULL));
int ok = 0;
Hero* h = new Hero("Player");
Ennemi* e = new Ennemi(4);
cout << "Hero : " << h->getName() << endl
<< "x : " << h->getX() << endl
<< "y : " << h->getY() << endl
<< "pv : " << h->getPv() << endl
<< "lv : " << h->getLv() << endl
<< "atk : " << h->getAtk() << endl
<< "def : " << h->getDef() << "\n\n"
<< "Ennemi :" << endl
<< "x : " << e->getX() << endl
<< "y : " << e->getY() << endl
<< "pv : " << e->getPv() << endl
<< "lv : " << e->getLv() << endl
<< "atk : " << e->getAtk() << endl
<< "def : " << e->getDef() << "\n\n";
assert(ok == h->lvUp());
cout << "lv : " << h->getLv() << endl
<< "atk : " << h->getAtk() << endl
<< "def : " << h->getDef() << endl;
assert(ok == h->combat(e));
cout << "Ennemie - pv : " << e->getPv() << endl;
assert(ok == h->setName("Terrine"));
assert(ok == e->combat(h));
cout << h->getName() << " - pv : " << h->getPv();
delete e;
delete h;
return 0;
}
| [
"="
] | = |
82be31fc3524835f627befe774786637aae24645 | 469370ad9a81ec746270f54a6433853e517bafde | /input.h | fa59213d1dc084e2a98556a154757033ecde6c1c | [] | no_license | masaedw/landscaper | 42431ee6ea952a2476583b838b7ae31e687e6421 | 7b84f39d16a37de12d20be15e17f199737e1d6a8 | refs/heads/master | 2016-09-06T00:23:36.120087 | 2010-02-01T14:52:41 | 2010-02-01T14:52:41 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,666 | h | #ifndef _INPUT_H_
#define _INPUT_H_
#include <map>
#include "collision.h"
namespace space{
//キーボード情報
//キーボードの値は整数に変換される。どういう変換かは使う人が考えること。
class Keyboard
{
public:
typedef std::map<unsigned short,unsigned short> KeyMap;
protected:
KeyMap keys;
public:
void clear(){keys.clear();}
Keyboard(){clear();}
~Keyboard(){}
//セット
void pushkey(unsigned short _k) { keys[_k] = _k; }
//アンセット
void pullkey(unsigned short _k) {
KeyMap::iterator it = keys.find(_k);
if( it != keys.end() ) keys.erase(it);
}
//情報をもらう
bool ispush(unsigned short _k) const{
if( keys.find(_k) == keys.end() ) return false;
return true;
}
//キーを全部丸ごとプレゼントする
const KeyMap& getkeys() const{ return keys;}
};
//ジョイスティック情報
//ボタン数は13と仮定。
class Joystick
{
bool button[13];
int x,y,z;
public:
void clear(){
x=0;y=0;z=0;
for(int i=0;i<16;i++) button[i]=false;
}
Joystick(){clear();}
~Joystick(){}
//セット(unsetの必要なし)
void setx(int _k) { x=_k; }
void sety(int _k) { y=_k; }
void setz(int _k) { z=_k; }
//ボタン系セット
void pushbutton(unsigned int _b){ if(_b>=13)return; button[_b]=true; }
//ボタン系アンセット
void pullbutton(unsigned int _b){ if(_b>=13)return; button[_b]=false; }
//情報をもらう
int getx() const { return x; }
int gety() const { return y; }
int getz() const { return z; }
bool ispush(unsigned int _b) const { if(_b>=13)return false; return button[_b]; }
};
//マウス
//4ボタン以上とか知らん。
class Mouse
{
public:
struct Button
{
private:
bool ispush;
Matrix21<int> pushpos;
Matrix21<int> pullpos;
public:
void clear(){
ispush=false;
pushpos = Matrix21<int>(0,0);
pullpos = Matrix21<int>(0,0);
}
Button(){ clear(); }
void push(const Matrix21<int>& _pos){ispush=true; pushpos=_pos;}
void pull(const Matrix21<int>& _pos){ispush=false;pullpos=_pos;}
const Matrix21<int>& getPushpos() const {return pushpos;}
const Matrix21<int>& getPullpos() const {return pullpos;}
bool isPush() const {return ispush;}
std::string output() const{
std::stringstream ss("");
ss << "::" << ispush << ":ps(" << pushpos.x << "," << pushpos.y << "):pl(" << pullpos.x << "," << pullpos.y << ")";
return ss.str();
}
};
protected:
Button left,right,middle;
Matrix21<int> nowpos;
public:
void clear(){
left.clear();
right.clear();
middle.clear();
nowpos = Matrix21<int>(0,0);
}
Mouse(){clear();}
//セット(アンセット必要なし)
void setpos(const Matrix21<int> &_pos){ nowpos=_pos; }
//ゲット
const Matrix21<int>& getpos() const { return nowpos; }
//返すだけ
const Button &getleft() const {return left;}
const Button &getmiddle() const {return middle;}
const Button &getright()const {return right;}
Button &setleft() {return left;}
Button &setmiddle() {return middle;}
Button &setright() { return right;}
std::string output() const{
std::stringstream ss("");
ss << "*l" << left.output() << "::m" << middle.output() << "::r" << right.output() << "::p(" << nowpos.x << "," << nowpos.y << ")";
return ss.str();
}
};
struct Input
{
Keyboard keyboard;
Mouse mouse;
Joystick joystick;
void clear(){
keyboard.clear();
mouse.clear();
joystick.clear();
}
std::string output() const{
std::stringstream ss("");
ss << "**ms" << mouse.output();
return ss.str();
}
};
}
#endif
| [
"[email protected]"
] | |
1232a46da9a5b85d3695ca1a7c3b93c5b37fc11d | 171b27ba265922de7836df0ac14db9ac1377153a | /test/doc/diff/stirling.cpp | 875116731f3ae6bb89c2579c42e3222f850e5811 | [
"MIT"
] | permissive | JPenuchot/eve | 30bb84af4bfb4763910fab96f117931343beb12b | aeb09001cd6b7d288914635cb7bae66a98687972 | refs/heads/main | 2023-08-21T21:03:07.469433 | 2021-10-16T19:36:50 | 2021-10-16T19:36:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | cpp | #include <eve/function/diff/stirling.hpp>
#include <eve/wide.hpp>
#include <iostream>
using wide_ft = eve::wide <float, eve::fixed<4>>;
int main()
{
wide_ft pf = { 0.0f, 1.0f, -1.0f, -0.5f};
std::cout
<< "---- simd" << '\n'
<< "<- pf = " << pf << '\n'
<< "-> diff(stirling)(pf) = " << eve::diff(eve::stirling)(pf) << '\n';
float xf = 1.0f;
std::cout
<< "---- scalar" << '\n'
<< "<- xf = " << xf << '\n'
<< "-> diff(stirling)(xf) = " << eve::diff(eve::stirling)(xf) << '\n'
return 0;
}
| [
"[email protected]"
] | |
bc04402f98f0dfbab1312618df94c4703378e069 | 41c46297d9303f54fb390050f550379649313979 | /카드놓기.cpp | aa02d0885de65c301b7c8a79689e95c3c4acf687 | [] | no_license | SketchAlgorithm/17_Jo-Wonbin | f48d6c51026d08bd4eeb13448e35d8566660ad40 | 75231bf4a0fb62518f687c62c752f5efb7c49478 | refs/heads/master | 2020-04-23T00:30:30.618376 | 2020-02-18T09:02:46 | 2020-02-18T09:02:46 | 170,782,242 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | #include<iostream>
using namespace std;
bool cache[10000000];
int arr[11];
int n, k;
int travel(int depth, int num, int use) {
if (depth > k) {
return false;
}
int ret = cache[num] == false;
cache[num] = true;
for (int i = 0; i < n; i++) {
if (!(use ^ (1 << i))) continue;
if (arr[i] >= 10) ret += travel(depth + 1, num * 100 + arr[i], use | (1 << i));
else ret += travel(depth + 1, num * 10 + arr[i], use | (1 << i));
}
return ret;
}
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << travel(0, 0, 0) << endl;
/*for (int i = 0; i < 100000000; i++) {
if (cache[i] == true) cout << i << endl;
}*/
} | [
"[email protected]"
] | |
36ffd69f21bf2277cef7fea364841c3a12967399 | d04b3793ed3611d5bdc8e3bc990bf9eb8562cece | /CheatSheet.cpp | e00970193f00ed69d57e398e36db43427aaf83b0 | [] | no_license | nebulou5/CppExamples | c7198cdc24ba1d681cc20738a3b21e2b17b98498 | 98044227b888a7f9faa8934ab76bb3cac443b75e | refs/heads/master | 2023-09-01T18:55:44.584418 | 2016-01-25T17:57:40 | 2016-01-25T17:57:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,222 | cpp | #include <iostream>
using namespace std;
void printI(int &i) {
cout << "Printing i: " << i << endl;
}
int main() {
// defining a basic 10 integer array
int x[10];
int xLen = sizeof(x) / sizeof(x[0]);
for (int i = 0; i < xLen; i++) {
cout << x[i] << endl;
}
// defining an array in place
float v[] = {1.1, 2.2, 3.3};
int vLen = sizeof(v) / sizeof(v[0]);
for (int i = 0; i < vLen; i++ ) {
cout << v[i] << endl;
}
// multidimensional array
float ab[3][3];
int abLen = sizeof(ab) / sizeof(ab[0]);
for (int i = 0; i < abLen; i++) {
printI(i);
for (int j = 0; j < abLen; j++) {
cout << "Element: " << i << ", " << j << ": " << ab[i][j] << endl;
}
}
// array allocated at runtime
int someUserDefinedSize = 3;
float* rta = new float[someUserDefinedSize]; // pointer dynamically allocates memory at runtime
delete[] rta; // but programmer must clean up the memory afterwards
// basic pointer usage
int i = 3;
int *j = &i; // store address of i @ "j"
int k = *j; // dereference address stored @ "j"
// initializing a nullptr
// valid in c++ 11 and beyond
int *nullPointer = nullptr;
int *nullPointerSynonymous{}; // also sets a nullptr
}
| [
"[email protected]"
] | |
7394745b36ae5104c00825320576a873b5d50654 | c5ed2d57496cafa1b10925814b4fc670fb9d84af | /Opensankore/build-Sankore_3.1-Unnamed-Release/build/win32/release/moc/moc_UBExportCFF.cpp | ccd670b2c223a0e089afb0adb057245688ac9bac | [] | no_license | Educabile/Ardesia | 5f5175fef5d7a15ea79469901bdd4c068cc8fec7 | 9b7b0bfe1c89e89c0ef28f93f6b1e0ac8c348230 | refs/heads/master | 2020-03-31T17:16:50.538146 | 2018-10-10T12:34:43 | 2018-10-10T12:34:43 | 152,416,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,429 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'UBExportCFF.h'
**
** Created: Fri 4. May 12:28:36 2018
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../../../Sankore-3.1/src/adaptors/UBExportCFF.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'UBExportCFF.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_UBExportCFF[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_UBExportCFF[] = {
"UBExportCFF\0"
};
void UBExportCFF::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData UBExportCFF::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject UBExportCFF::staticMetaObject = {
{ &UBExportAdaptor::staticMetaObject, qt_meta_stringdata_UBExportCFF,
qt_meta_data_UBExportCFF, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &UBExportCFF::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *UBExportCFF::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *UBExportCFF::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_UBExportCFF))
return static_cast<void*>(const_cast< UBExportCFF*>(this));
return UBExportAdaptor::qt_metacast(_clname);
}
int UBExportCFF::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = UBExportAdaptor::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"salvatore.naddeo@€ducabile.it"
] | salvatore.naddeo@€ducabile.it |
b7c78a511904d321aa74ab25ce20a44c3a3f0a0e | d51d72f1b6e834d89c8551bb07487bed84cdaa31 | /src/output/osg/customCode/osg/AnimationPath_pmoc.cpp | dc66ae9496a4b899d13c9038f85bec5d8cc50019 | [] | no_license | wangfeilong321/osg4noob | 221204aa15efa18f1f049548ad076ef27371ecad | 99a15c3fd2523c4bd537fa3afb0b47e15c8f335a | refs/heads/master | 2021-01-12T20:00:43.854775 | 2015-11-06T15:37:01 | 2015-11-06T15:37:01 | 48,840,543 | 0 | 1 | null | 2015-12-31T07:56:31 | 2015-12-31T07:56:31 | null | UTF-8 | C++ | false | false | 1,778 | cpp | #include <osg/AnimationPath>
//includes
#include <MetaQQuickLibraryRegistry.h>
#include <customCode/osg/AnimationPath_pmoc.hpp>
using namespace pmoc;
osg::QMLAnimationPath::QMLAnimationPath(pmoc::Instance *i,QObject* parent):QReflect_AnimationPath(i,parent){
//custom initializations
}
QQuickItem* osg::QMLAnimationPath::connect2View(QQuickItem*i){
this->_view=QReflect_AnimationPath::connect2View(i);
///connect this's signals/slot to its qml component////////////////////////////////////////////////////////////////
///CustomiZE here
return this->_view;
}
void osg::QMLAnimationPath::updateModel(){
QReflect_AnimationPath::updateModel();
///update this according to state of _model when it has been changed via pmoc/////////////////////////////////////////////
///CustomiZE here
}
#ifndef AUTOMOCCPP
#define AUTOMOCCPP 1
#include "moc_AnimationPath_pmoc.cpp"
#endif
#include <MetaQQuickLibraryRegistry.h>
#include <customCode/osg/AnimationPath_pmoc.hpp>
using namespace pmoc;
osg::QMLAnimationPathCallback::QMLAnimationPathCallback(pmoc::Instance *i,QObject* parent):QReflect_AnimationPathCallback(i,parent){
//custom initializations
}
QQuickItem* osg::QMLAnimationPathCallback::connect2View(QQuickItem*i){
this->_view=QReflect_AnimationPathCallback::connect2View(i);
///connect this's signals/slot to its qml component////////////////////////////////////////////////////////////////
///CustomiZE here
return this->_view;
}
void osg::QMLAnimationPathCallback::updateModel(){
QReflect_AnimationPathCallback::updateModel();
///update this according to state of _model when it has been changed via pmoc/////////////////////////////////////////////
///CustomiZE here
}
#ifndef AUTOMOCCPP
#define AUTOMOCCPP 1
#include "moc_AnimationPath_pmoc.cpp"
#endif
| [
"[email protected]"
] | |
0acbecc764fbfcc61711e5ca5ce12561d4730135 | 399b5e377fdd741fe6e7b845b70491b9ce2cccfd | /LLVM_src/libcxx/test/std/utilities/time/time.cal/time.cal.ymwdlast/types.pass.cpp | e0580fac76fa9102f0058519d247d1d7895bce5a | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0"
] | permissive | zslwyuan/LLVM-9-for-Light-HLS | 6ebdd03769c6b55e5eec923cb89e4a8efc7dc9ab | ec6973122a0e65d963356e0fb2bff7488150087c | refs/heads/master | 2021-06-30T20:12:46.289053 | 2020-12-07T07:52:19 | 2020-12-07T07:52:19 | 203,967,206 | 1 | 3 | null | 2019-10-29T14:45:36 | 2019-08-23T09:25:42 | C++ | UTF-8 | C++ | false | false | 802 | cpp | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14, c++17
// <chrono>
// class year_month_weekday_last_last;
#include <chrono>
#include <type_traits>
#include <cassert>
#include "test_macros.h"
int main()
{
using year_month_weekday_last = std::chrono::year_month_weekday_last;
static_assert(std::is_trivially_copyable_v<year_month_weekday_last>, "");
static_assert(std::is_standard_layout_v<year_month_weekday_last>, "");
}
| [
"[email protected]"
] | |
b8319da5f12cfbbbd8ce6c9a50bab4c69b92531e | c4a320a9519cd63bad9be9bcfc022a4fcab5267b | /TETRIS_VS/TETRIS_VS/LobbyBoard.cpp | 4e7ef9e1f59c43158f02345d8f894a183007f43e | [] | no_license | shield1203/TETRIS_VS | 79dc3d8db0a1107352e46e69a96482a49490a290 | 3f67f0436674a10f9d37a98286a1f3531e6f7730 | refs/heads/master | 2020-12-22T00:11:37.323472 | 2020-03-05T15:28:32 | 2020-03-05T15:28:32 | 236,593,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | cpp | #include "stdafx.h"
#include "LobbyBoard.h"
#include "InputSystem.h"
#include "PacketManager.h"
LobbyBoard::LobbyBoard()
{
m_packetManager = PacketManager::getInstance();
m_inputSystem = new InputSystem();
}
LobbyBoard::~LobbyBoard()
{
SafeDelete(m_inputSystem);
}
void LobbyBoard::Update()
{
m_inputSystem->CheckKeyboardPressed();
if (m_inputSystem->IsEnterPressed())
{
m_on = true;
}
} | [
"[email protected]"
] | |
7726abf0e5e7eb0906fdf74387dd474018ac3154 | 81f6419ea475836b1f1b24bcd2de77a316bc46a1 | /codeforces/BEducational25-06-2020.cpp | 03fd55ab7c09117fe485917441cb42c7ab252cb1 | [] | no_license | Pramodjais517/competitive-coding | f4e0f6f238d98c0a39f8a9c940265f886ce70cb3 | 2a8ad013246f2db72a4dd53771090d931ab406cb | refs/heads/master | 2023-02-25T12:09:47.382076 | 2021-01-28T06:57:26 | 2021-01-28T06:57:26 | 208,445,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,335 | cpp | #include<bits/stdc++.h>
using namespace std;
// template starts here
#define ll long long
#define ull unsigned long long
#define rs reserve
#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define fi(i,s,e,inc) for(auto i=s;i<e;i+=inc)
#define fie(i,s,e,inc) for(auto i=s;i<=e;i+=inc)
#define fd(i,s,e,dec) for(auto i=s;i>e;i-=dec)
#define fde(i,s,e,dec) for(auto i=s;i>=e;i-=dec)
#define itr(i,ar) for(auto i=ar.begin();i!=ar.end();i++)
#define mod 1000000007
ll N = 1000000;
vector<bool> prime(N+1,true);
void sieve()
{
prime[0] = false,prime[1] = false;
for(ll i=2;i*i <= N;i++)
{
if(prime[i])
{
for(ll j = i*i; j<= N ;j+=i)
prime[j] = false;
}
}
}
ll pow(ll a, ll b)
{
if(b==0)
return 1;
if(b==1)
return a;
ll r = pow(a,b/2);
if(b&1)
return r*a*r;
return r*r;
}
// template ends here
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--)
{
string s;
cin>>s;
ll n=0;
ll a[s.length()];
memset(a,0,sizeof(a));
if(s[0]=='-')
a[0] = -1;
else
a[0] = 1;
fi(i,1,s.length(),1)
{
if(s[i]=='-')
a[i] = a[i-1]-1;
else
a[i] = a[i-1] + 1;
}
ll b[s.length()];
fi(i,0,s.length(),1)
{
b[i] = (a[i] + i);
}
ll ans=0,i=0;
while(i<s.length() and b[i]<0)
{
ans+=(i+1);
i++;
}
ans+=s.length();
cout<<ans<<"\n";
}
return 0;
}
| [
"[email protected]"
] | |
3839e99ec45940f1c94baf2131e7849a8871b51c | 4f37081ed62e44afa0b2465388a8adf9b5490b13 | /ash/login/ui/login_user_view.h | 4d27549c5a7f8e8dda6fd0bc769f65efd3439630 | [
"BSD-3-Clause"
] | permissive | zowhair/chromium | 05b9eed58a680941c3595d52c3c77b620ef2c3ac | d84d5ef83e401ec210fcb14a92803bf339e1ccce | refs/heads/master | 2023-03-04T23:15:10.914156 | 2018-03-15T11:27:44 | 2018-03-15T11:27:44 | 125,359,706 | 1 | 0 | null | 2018-03-15T11:50:44 | 2018-03-15T11:50:43 | null | UTF-8 | C++ | false | false | 3,544 | 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 ASH_LOGIN_UI_LOGIN_USER_VIEW_H_
#define ASH_LOGIN_UI_LOGIN_USER_VIEW_H_
#include "ash/ash_export.h"
#include "ash/login/ui/login_display_style.h"
#include "ash/public/interfaces/login_user_info.mojom.h"
#include "base/macros.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/view.h"
namespace ash {
class HoverNotifier;
class LoginBubble;
class LoginButton;
// Display the user's profile icon, name, and a menu icon in various layout
// styles.
class ASH_EXPORT LoginUserView : public views::View,
public views::ButtonListener {
public:
// TestApi is used for tests to get internal implementation details.
class ASH_EXPORT TestApi {
public:
explicit TestApi(LoginUserView* view);
~TestApi();
LoginDisplayStyle display_style() const;
const base::string16& displayed_name() const;
views::View* user_label() const;
views::View* tap_button() const;
bool is_opaque() const;
private:
LoginUserView* const view_;
};
using OnTap = base::RepeatingClosure;
// Returns the width of this view for the given display style.
static int WidthForLayoutStyle(LoginDisplayStyle style);
LoginUserView(LoginDisplayStyle style,
bool show_dropdown,
bool show_domain,
const OnTap& on_tap);
~LoginUserView() override;
// Update the user view to display the given user information.
void UpdateForUser(const mojom::LoginUserInfoPtr& user, bool animate);
// Set if the view must be opaque.
void SetForceOpaque(bool force_opaque);
// Enables or disables tapping the view.
void SetTapEnabled(bool enabled);
const mojom::LoginUserInfoPtr& current_user() const { return current_user_; }
// views::View:
const char* GetClassName() const override;
gfx::Size CalculatePreferredSize() const override;
void Layout() override;
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
private:
class UserDomainInfoView;
class UserImage;
class UserLabel;
class TapButton;
// Called when hover state changes.
void OnHover(bool has_hover);
// Updates UI element values so they reflect the data in |current_user_|.
void UpdateCurrentUserState();
// Updates view opacity based on input state and |force_opaque_|.
void UpdateOpacity();
void SetLargeLayout();
void SetSmallishLayout();
// Executed when the user view is pressed.
OnTap on_tap_;
// The user that is currently being displayed (or will be displayed when an
// animation completes).
mojom::LoginUserInfoPtr current_user_;
// Used to dispatch opacity update events.
std::unique_ptr<HoverNotifier> hover_notifier_;
LoginDisplayStyle display_style_;
UserImage* user_image_ = nullptr;
UserLabel* user_label_ = nullptr;
LoginButton* user_dropdown_ = nullptr;
TapButton* tap_button_ = nullptr;
std::unique_ptr<LoginBubble> user_menu_;
// Show the domain information for public account user.
UserDomainInfoView* user_domain_ = nullptr;
// True iff the view is currently opaque (ie, opacity = 1).
bool is_opaque_ = false;
// True if the view must be opaque (ie, opacity = 1) regardless of input
// state.
bool force_opaque_ = false;
DISALLOW_COPY_AND_ASSIGN(LoginUserView);
};
} // namespace ash
#endif // ASH_LOGIN_UI_LOGIN_USER_VIEW_H_
| [
"[email protected]"
] | |
da305b7fa058459e59591d534b6f8ccafc370f33 | e542234cbf0eea3883b934ee67f97326377de02f | /EnemySnipper.hpp | 194187a1b40c4a3a73a79907b77035df6c48f895 | [
"MIT"
] | permissive | kaitokidi/WhoTookMyHat | 8e66e510e10451a3499a2fa361c8892e8f7b818f | dc4ebdbe880a10cb681bf2749095f4bbbbe51f88 | refs/heads/master | 2021-04-19T00:56:37.700324 | 2016-10-27T22:29:11 | 2016-10-27T22:29:11 | 51,254,343 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | hpp | #ifndef ENEMYSNIPPER_HPP
#define ENEMYSNIPPER_HPP
#include "Enemy.hpp"
#include "Player.hpp"
#include "EnemyShooter.hpp"
class EnemySnipper : public Enemy, public EnemyShooter {
public:
//TODO
virtual void init();
EnemySnipper(std::list < Enemy* >* e, Player* p);
virtual void update(float deltaTime, Background* bg);
virtual void movement(float deltaTime, Background *bg);
protected:
Player* _player;
};
#endif // ENEMYSNIPPER_HPP
| [
"[email protected]"
] | |
160beafcd0375ee1abc289f6df9dc822b8749eb5 | 4b0a3fffa69840fac4fa77ba40f3aed8ae51442c | /FinalProject/workingfolder/Erin's Updates/bouncingcube/BouncingCube.h | a06731fe152c89b5848227598c4d455e34849b77 | [] | no_license | hoffm386/graphics-final-project | 732633bf55482051730e0087c025ab1d6e5253e7 | 584a16eda13572d6a92bad690da6b4a903eef084 | refs/heads/master | 2021-01-10T20:14:04.415740 | 2014-04-30T02:50:22 | 2014-04-30T02:50:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | h |
// BouncingCube.h : main header file for the BouncingCube application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CBouncingCubeApp:
// See BouncingCube.cpp for the implementation of this class
//
class CBouncingCubeApp : public CWinAppEx
{
public:
CBouncingCubeApp();
// Overrides
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
// Implementation
public:
UINT m_nAppLook;
BOOL m_bHiColorIcons;
virtual void PreLoadState();
virtual void LoadCustomState();
virtual void SaveCustomState();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CBouncingCubeApp theApp;
| [
"[email protected]"
] | |
d43be44d339e4c748144208e5d4bd8fe9a5894e7 | 3368db882d23eba1fd8046d9e46583d7324d4dea | /Lesson 6/source/06.) Textures/win_OpenGLApp.cpp | 2a8751f01791f7cd05950c39fb5a5f26b9865e4b | [] | no_license | Juniperbrew/MS-OpenGLTutorial-Win32 | 8313923fc34948aafd7bc71de8d99552f734a454 | 6f6908999f1d887e41e311c019ab96724a60ac24 | refs/heads/master | 2021-01-10T16:39:55.731220 | 2016-01-02T09:49:59 | 2016-01-02T09:49:59 | 48,902,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,077 | cpp | #include "common_header.h"
#include "win_OpenGLApp.h"
COpenGLWinApp appMain;
char Keys::kp[256] = {0};
/*-----------------------------------------------
Name: key
Params: iKey - virtual key code
Result: Return true if key is pressed.
/*---------------------------------------------*/
int Keys::key(int iKey)
{
return (GetAsyncKeyState(iKey)>>15)&1;
}
/*-----------------------------------------------
Name: onekey
Params: iKey - virtual key code
Result: Return true if key was pressed, but only
once (the key must be released).
/*---------------------------------------------*/
int Keys::onekey(int iKey)
{
if(key(iKey) && !kp[iKey]){kp[iKey] = 1; return 1;}
if(!key(iKey))kp[iKey] = 0;
return 0;
}
/*-----------------------------------------------
Name: resetTimer
Params: none
Result: Resets application timer (for example
after re-activation of application).
/*---------------------------------------------*/
void COpenGLWinApp::resetTimer()
{
tLastFrame = clock();
fFrameInterval = 0.0f;
}
/*-----------------------------------------------
Name: updateTimer
Params: none
Result: Updates application timer.
/*---------------------------------------------*/
void COpenGLWinApp::updateTimer()
{
clock_t tCur = clock();
fFrameInterval = float(tCur-tLastFrame)/float(CLOCKS_PER_SEC);
tLastFrame = tCur;
}
/*-----------------------------------------------
Name: sof
Params: fVal
Result: Stands for speed optimized float.
/*---------------------------------------------*/
float COpenGLWinApp::sof(float fVal)
{
return fVal*fFrameInterval;
}
/*-----------------------------------------------
Name: initializeApp
Params: a_sAppName
Result: Initializes app with specified (unique)
application identifier.
/*---------------------------------------------*/
bool COpenGLWinApp::initializeApp(string a_sAppName)
{
sAppName = a_sAppName;
hMutex = CreateMutex(NULL, 1, sAppName.c_str());
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
MessageBox(NULL, "This application already runs!", "Multiple Instances Found.", MB_ICONINFORMATION | MB_OK);
return 0;
}
return 1;
}
/*-----------------------------------------------
Name: registerAppClass
Params: a_hInstance - application instance handle
Result: Registers application window class.
/*---------------------------------------------*/
LRESULT CALLBACK globalMessageHandler(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
return appMain.msgHandlerMain(hWnd, uiMsg, wParam, lParam);
}
void COpenGLWinApp::registerAppClass(HINSTANCE a_hInstance)
{
WNDCLASSEX wcex;
memset(&wcex, 0, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_OWNDC;
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcex.hIcon = LoadIcon(hInstance, IDI_WINLOGO);
wcex.hIconSm = LoadIcon(hInstance, IDI_WINLOGO);
wcex.hCursor = LoadCursor(hInstance, IDC_ARROW);
wcex.hInstance = hInstance;
wcex.lpfnWndProc =
globalMessageHandler;
wcex.lpszClassName = sAppName.c_str();
wcex.lpszMenuName = NULL;
RegisterClassEx(&wcex);
}
/*-----------------------------------------------
Name: createWindow
Params: sTitle - title of created window
Result: Creates main application window.
/*---------------------------------------------*/
bool COpenGLWinApp::createWindow(string sTitle)
{
if(MessageBox(NULL, "Would you like to run in fullscreen?", "Fullscreen", MB_ICONQUESTION | MB_YESNO) == IDYES)
{
DEVMODE dmSettings = {0};
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dmSettings); // Get current display settings
hWnd = CreateWindowEx(0, sAppName.c_str(), sTitle.c_str(), WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // This is the commonly used style for fullscreen
0, 0, dmSettings.dmPelsWidth, dmSettings.dmPelsHeight, NULL,
NULL, hInstance, NULL);
}
else hWnd = CreateWindowEx(0, sAppName.c_str(), sTitle.c_str(), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL,
NULL, hInstance, NULL);
if(!oglControl.initOpenGL(hInstance, &hWnd, 3, 3, initScene, renderScene, releaseScene, &oglControl))return false;
ShowWindow(hWnd, SW_SHOW);
// Just to send WM_SIZE message again
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
UpdateWindow(hWnd);
return true;
}
/*-----------------------------------------------
Name: appBody
Params: none
Result: Main application body infinite loop.
/*---------------------------------------------*/
void COpenGLWinApp::appBody()
{
MSG msg;
while(1)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)break; // If the message was WM_QUIT then exit application
else
{
TranslateMessage(&msg); // Otherwise send message to appropriate window
DispatchMessage(&msg);
}
}
else if(bAppActive)
{
updateTimer();
oglControl.render(&oglControl);
}
else Sleep(200); // Do not consume processor power if application isn't active
}
}
/*-----------------------------------------------
Name: shutdown
Params: none
Result: Shuts down application and releases used
memory.
/*---------------------------------------------*/
void COpenGLWinApp::shutdown()
{
oglControl.releaseOpenGLControl(&oglControl);
DestroyWindow(hWnd);
UnregisterClass(sAppName.c_str(), hInstance);
COpenGLControl::unregisterSimpleOpenGLClass(hInstance);
ReleaseMutex(hMutex);
}
/*-----------------------------------------------
Name: msgHandlerMain
Params: whatever
Result: Application messages handler.
/*---------------------------------------------*/
LRESULT CALLBACK COpenGLWinApp::msgHandlerMain(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
switch(uiMsg)
{
case WM_PAINT:
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_ACTIVATE:
{
switch(LOWORD(wParam))
{
case WA_ACTIVE:
case WA_CLICKACTIVE:
bAppActive = true;
resetTimer();
break;
case WA_INACTIVE:
bAppActive = false;
break;
}
break;
}
case WM_SIZE:
oglControl.resizeOpenGLViewportFull();
oglControl.setProjection3D(45.0f, float(LOWORD(lParam))/float(HIWORD(lParam)), 0.001f, 1000.0f);
break;
default:
return DefWindowProc(hWnd, uiMsg, wParam, lParam);
}
return 0;
}
/*-----------------------------------------------
Name: getInstance
Params: none
Result: Returns application instance.
/*---------------------------------------------*/
HINSTANCE COpenGLWinApp::getInstance()
{
return hInstance;
}
/*-----------------------------------------------
Name: msgHandlerMain
Params: whatever
Result: Application messages handler.
/*---------------------------------------------*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR sCmdLine, int iShow)
{
if(!appMain.initializeApp("06_opengl_3_3"))
return 0;
appMain.registerAppClass(hInstance);
if(!appMain.createWindow("06.) Textures - Tutorial by Michal Bubnar (www.mbsoftworks.sk)"))
return 0;
appMain.resetTimer();
appMain.appBody();
appMain.shutdown();
return 0;
}
| [
"[email protected]"
] | |
96ac4e9785d6d7dac6e39b5f2018e8907d4ae455 | e102753a5ab7eedd58d04c26254a8e29859f9e98 | /Toolkit/Synthetic Data Analysis/UMAP/epp/cpp/client.h | da0bf3593bd54e01f3dd4c0b796a40d32c813e33 | [
"Apache-2.0"
] | permissive | ZPGuiGroupWhu/ClusteringDirectionCentrality | ec166456938602921574ad24d7445804c2226961 | 084a18fc40cc19dee2aa91c757009d4abb2e86f9 | refs/heads/master | 2023-04-13T00:07:42.437629 | 2023-03-11T11:48:27 | 2023-03-11T11:48:27 | 467,575,519 | 72 | 7 | null | 2022-10-26T12:10:05 | 2022-03-08T15:46:14 | MATLAB | UTF-8 | C++ | false | false | 20,265 | h | #ifndef _EPP_CLIENT_H
#define _EPP_CLIENT_H 1
#include <ios>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <math.h>
namespace EPP
{
typedef uint32_t epp_word;
typedef unsigned char epp_hash[32];
/**
* These classes define the client interface to EPP and the necessary data structures
*
*/
class Sample
{
public:
std::vector<bool> subset;
const unsigned long int events;
const unsigned short int measurements;
Sample(unsigned short int measurements,
unsigned long int events,
std::vector<bool> subset) noexcept
: measurements(measurements), events(events), subset(subset){};
Sample(unsigned short int measurements,
unsigned long int events) noexcept
: measurements(measurements), events(events), subset(events)
{
std::fill(subset.begin(), subset.end(), true);
};
private:
// these are virtual because our friend stream won't know which variant it will be
virtual epp_word get_word(unsigned short int measurement, unsigned long event) const noexcept
{
return (epp_word)0;
}
virtual void put_word(unsigned short measurement, long event, epp_word data) noexcept {};
friend class SampleStream;
};
template <typename _float>
class DefaultSample : public Sample
{
public:
inline double operator()(unsigned long int event, unsigned short int measurement) const noexcept
{
return (double)data[measurements * event + measurement];
};
DefaultSample(const unsigned short int measurements,
const unsigned long int events,
const _float *const data) noexcept
: Sample(measurements, events), data(data)
{
for (long int event = 0; event < events; event++)
for (unsigned short int measurement = 0; measurement < measurements; measurement++)
if (data[measurements * event + measurement] < 0 || data[measurements * event + measurement] > 1)
subset[event] = false;
};
DefaultSample(const unsigned short int measurements,
const unsigned long int events,
const _float *const data,
std::vector<bool> subset) noexcept
: Sample(measurements, events, subset), data(data){};
protected:
epp_word get_word(unsigned short int measurement, unsigned long int event) const noexcept
{
float f = data[measurements * event + measurement];
return *(epp_word *)&f;
};
void put_word(unsigned short int measurement, unsigned long int event, epp_word value) noexcept
{
float f = *(float *)&value;
data[measurements * event + measurement] = (_float)f;
};
private:
const _float *const data;
};
template <typename _float>
class TransposeSample : public Sample
{
public:
inline double operator()(unsigned long int event, unsigned short int measurement) const noexcept
{
return (double)data[events * measurement + event];
};
TransposeSample(const unsigned short int measurements,
const unsigned long int events,
const _float *const data) noexcept
: Sample(measurements, events), data(data)
{
for (unsigned long int event = 0; event < events; event++)
for (unsigned short int measurement = 0; measurement < measurements; measurement++)
if (data[events * measurement + event] < 0 || data[events * measurement + event] > 1)
subset[event] = false;
};
TransposeSample(const unsigned short int measurements,
const unsigned long int events,
const _float *const data,
std::vector<bool> subset) noexcept
: Sample(measurements, events, subset), data(data){};
protected:
epp_word get_word(unsigned short int measurement, unsigned long int event) const noexcept
{
float f = data[events * measurement + event];
return *(epp_word *)&f;
};
void put_word(unsigned short int measurement, unsigned long int event, epp_word value) noexcept
{
float f = *(float *)&value;
data[events * measurement + event] = (_float)f;
};
private:
const _float *const data;
};
template <typename _float>
class PointerSample : public Sample
{
public:
inline double operator()(unsigned long int event, unsigned short int measurement) const noexcept
{
return (double)data[measurement][event];
};
PointerSample(const unsigned short int measurements,
const unsigned long int events,
const _float *const *const data) noexcept
: Sample(measurements, events), data(data)
{
for (unsigned long int event = 0; event < events; event++)
for (unsigned short int measurement = 0; measurement < measurements; measurement++)
if (data[measurement][event] < 0 || data[measurement][event] > 1)
subset[event] = false;
};
PointerSample(const unsigned short int measurements,
const unsigned long int events,
const _float *const *const data,
std::vector<bool> subset) noexcept
: Sample(measurements, events, subset), data(data){};
protected:
epp_word get_word(unsigned short int measurement, unsigned long int event) const noexcept
{
float f = data[measurement][event];
return *(epp_word *)&f;
};
void put_word(unsigned short int measurement, unsigned long int event, epp_word value) noexcept
{
float f = *(float *)&value;
data[measurement][event] = (_float)f;
};
private:
const _float *const *const data;
};
class Subset : public std::vector<bool>
{
public:
explicit Subset(Sample &sample);
Sample *sample;
private:
friend class SubsetStream;
};
struct Parameters
{
// N = 256 gives points and features a precision of roughly two significant figures
static const unsigned short N = 1 << 8; // resolution of points and boundaries
// optimized when there are lots of small factors
double W = 1 / (double)N; // standard deviation of kernel,
// this is the highest achievable resolution, in practice a higher
// value might be used for application reasons or just performance
double sigma = 5; // controls the density threshold for starting a new cluster
enum Goal
{ // which objective function
best_separation, // lowest edge weight
best_balance // edge weight biased towards more even splits
} goal = best_balance;
int finalists = 1; // remember this many of the best candidates
struct KLD // KLD threshold for informative cases
{
double Normal2D = .16; // is this population worth splitting?
double Normal1D = .16; // is the measurement just normal
double Exponential1D = .16; // is this an exponential tail (CyToF)
KLD(
double Normal2D = .16,
double Normal1D = .16,
double Exponential1D = .16) noexcept
: Normal2D(Normal2D), Normal1D(Normal1D), Exponential1D(Exponential1D){};
};
const static KLD KLD_Default;
KLD kld = KLD_Default;
std::vector<bool> censor; // omit measurements from consideration
// algorithm tweaks
int max_clusters = 12; // most clusters the graph logic should handle
bool shuffle = false; // shuffle the boundary points for uniformity
bool deterministic = false; // do it with a fixed seed for testing
bool supress_in_out = false; // don't bother with in and out sets
bool kld_only = false;
Parameters(
Goal goal = best_balance,
KLD kld = {.16, .16, .16},
double sigma = 5,
double W = 1 / (double)N)
: goal(goal), kld(kld), W(W), sigma(sigma),
censor(0), finalists(1), max_clusters(12),
shuffle(false), deterministic(false), supress_in_out(false){};
};
const Parameters Default;
struct Point
{
short i, j;
inline double x() const noexcept { return (double)i / (double)Parameters::N; };
inline double y() const noexcept { return (double)j / (double)Parameters::N; };
inline bool operator==(const Point &other)
{
return i == other.i && j == other.j;
}
inline bool operator!=(const Point &other)
{
return !(*this == other);
}
Point(short i, short j) noexcept : i(i), j(j){};
};
enum Status
{
EPP_success,
EPP_no_qualified,
EPP_no_cluster,
EPP_not_interesting,
EPP_error
};
struct Candidate
{
std::vector<Point> separatrix;
std::vector<bool> in, out;
double score, edge_weight, balance_factor;
unsigned long int in_events, out_events;
unsigned int pass, clusters, graphs;
unsigned short int X, Y;
enum Status outcome;
private:
void close_clockwise(
std::vector<Point> &polygon)
{
Point tail = polygon.front();
Point head = polygon.back();
int edge;
if (head.j == 0)
edge = 0;
if (head.i == 0)
edge = 1;
if (head.j == Parameters::N)
edge = 2;
if (head.i == Parameters::N)
edge = 3;
while (!(head == tail))
{
switch (edge++ & 3)
{
case 0:
if (tail.j == 0 && tail.i < head.i)
head = tail;
else
head = Point(Parameters::N, 0);
break;
case 1:
if (tail.i == 0 && tail.j > head.j)
head = tail;
else
head = Point(0, 0);
break;
case 2:
if (tail.j == Parameters::N && tail.i > head.i)
head = tail;
else
head = Point(0, Parameters::N);
break;
case 3:
if (tail.i == Parameters::N && tail.j < head.j)
head = tail;
else
head = Point(Parameters::N, Parameters::N);
break;
}
polygon.push_back(head);
}
}
// Ramer–Douglas–Peucker algorithm
void simplify(
const double tolerance,
std::vector<Point> &simplified,
const unsigned short int lo,
const unsigned short int hi)
{
if (lo + 1 == hi)
return;
double x = separatrix[hi].i - separatrix[lo].i;
double y = separatrix[hi].j - separatrix[lo].j;
double theta = atan2(y, x);
double c = cos(theta);
double s = sin(theta);
double max = 0;
unsigned short int keep;
for (int mid = lo + 1; mid < hi; mid++)
{ // distance of mid from the line from lo to hi
double d = abs(c * (separatrix[mid].j - separatrix[lo].j) - s * (separatrix[mid].i - separatrix[lo].i));
if (d > max)
{
keep = mid;
max = d;
}
}
if (max > tolerance) // significant, so something we must keep in here
{
simplify(tolerance, simplified, lo, keep);
simplified.push_back(separatrix[keep]);
simplify(tolerance, simplified, keep, hi);
}
// but if not, we don't need any of the points between lo and hi
}
public:
bool operator<(const Candidate &other) const noexcept
{
if (score < other.score)
return true;
if (score > other.score)
return false;
return outcome < other.outcome;
}
std::vector<Point> simplify(
const double tolerance)
{
std::vector<Point> polygon;
polygon.reserve(separatrix.size());
polygon.push_back(separatrix[0]);
simplify(tolerance * Parameters::N, polygon, 0, separatrix.size() - 1);
polygon.push_back(separatrix[separatrix.size() - 1]);
return polygon;
}
std::vector<Point> in_polygon()
{
std::vector<Point> polygon;
polygon.reserve(separatrix.size() + 4);
for (auto point = separatrix.begin(); point != separatrix.end(); point++)
polygon.push_back(*point);
close_clockwise(polygon);
return polygon;
}
std::vector<Point> in_polygon(
double tolerance)
{
std::vector<Point> polygon;
polygon.reserve(separatrix.size() + 4);
polygon.push_back(separatrix[0]);
simplify(tolerance * Parameters::N, polygon, 0, separatrix.size() - 1);
polygon.push_back(separatrix[separatrix.size() - 1]);
close_clockwise(polygon);
return polygon;
}
std::vector<Point> out_polygon()
{
std::vector<Point> polygon;
polygon.reserve(separatrix.size() + 4);
for (auto point = separatrix.rbegin(); point != separatrix.rend(); point++)
polygon.push_back(*point);
close_clockwise(polygon);
return polygon;
}
std::vector<Point> out_polygon(
double tolerance)
{
std::vector<Point> polygon;
polygon.reserve(separatrix.size() + 4);
polygon.push_back(separatrix[0]);
simplify(tolerance * Parameters::N, polygon, 0, separatrix.size() - 1);
polygon.push_back(separatrix[separatrix.size() - 1]);
std::reverse(polygon.begin(), polygon.end());
close_clockwise(polygon);
return polygon;
}
Candidate(
unsigned short int X,
unsigned short int Y)
: X(X < Y ? X : Y), Y(X < Y ? Y : X),
outcome(Status::EPP_error),
score(std::numeric_limits<double>::infinity()),
pass(0), clusters(0), graphs(0){};
};
struct Result
{
std::vector<Candidate> candidates;
std::vector<unsigned short int> qualified;
std::chrono::milliseconds milliseconds;
int projections, passes, clusters, graphs;
Candidate winner() const noexcept
{
return candidates[0];
}
enum Status outcome() const noexcept
{
return winner().outcome;
};
protected:
std::chrono::time_point<std::chrono::steady_clock> begin, end;
friend class MATLAB_Pursuer;
};
class Request
{
static std::condition_variable_any completed;
volatile unsigned int outstanding = 0;
void finish ()
{
--outstanding;
}
bool finished ()
{
return outstanding == 0;
};
void wait ()
{
while (outstanding > 0)
;
};
Result *result ()
{
return nullptr;
}
};
template <class ClientSample>
class Pursuer
{
public:
void start(
const ClientSample sample,
const Parameters parameters) noexcept;
void start(
const ClientSample sample) noexcept;
bool finished() noexcept;
void wait() noexcept;
std::shared_ptr<Result> result() noexcept;
std::shared_ptr<Result> pursue(
const ClientSample sample,
const Parameters parameters) noexcept;
std::shared_ptr<Result> pursue(
const ClientSample sample) noexcept;
protected:
Pursuer() noexcept = default;
~Pursuer() = default;
};
typedef TransposeSample<float> MATLAB_Sample;
class MATLAB_Pursuer : public Pursuer<MATLAB_Sample>
{
int threads;
std::thread *workers;
public:
int getThreads() const noexcept {return threads;}
void start(
const MATLAB_Sample sample,
const Parameters parameters) noexcept;
void start(
const MATLAB_Sample sample) noexcept;
void start(
const unsigned short int measurements,
const unsigned long int events,
const float *const data,
std::vector<bool> &subset) noexcept;
void start(
const unsigned short int measurements,
const unsigned long int events,
const float *const data) noexcept;
bool finished() noexcept;
void wait() noexcept;
std::shared_ptr<Result> result() noexcept;
std::shared_ptr<Result> pursue(
const MATLAB_Sample sample,
const Parameters parameters) noexcept;
std::shared_ptr<Result> pursue(
const MATLAB_Sample sample) noexcept;
std::shared_ptr<Result> pursue(
const unsigned short int measurements,
const unsigned long int events,
const float *const data,
std::vector<bool> &subset) noexcept;
std::shared_ptr<Result> pursue(
const unsigned short int measurements,
const unsigned long int events,
const float *const data) noexcept;
MATLAB_Pursuer() noexcept;
MATLAB_Pursuer(int threads) noexcept;
~MATLAB_Pursuer();
};
/**
* utility classes for serializing sample and subset as streams
*/
class SampleStream : public std::iostream
{
protected:
class sample_buffer : public std::streambuf
{
public:
explicit sample_buffer(Sample &sample);
virtual ~sample_buffer();
protected:
virtual std::streambuf::int_type underflow();
virtual std::streambuf::int_type overflow(std::streambuf::int_type value);
virtual std::streambuf::int_type sync();
private:
Sample *sample;
epp_word *buffer;
long next_event;
};
public:
explicit SampleStream(Sample &sample);
};
class SubsetStream : public std::iostream
{
protected:
class subset_buffer : public std::streambuf
{
public:
explicit subset_buffer(Subset &subset);
virtual ~subset_buffer();
virtual std::streambuf::int_type underflow();
virtual std::streambuf::int_type overflow(std::streambuf::int_type value);
virtual std::streambuf::int_type sync();
private:
Subset *subset;
uint8_t *buffer;
long next_event;
friend class SubsetStream;
};
public:
explicit SubsetStream(Subset &subset);
};
}
#endif /* _EPP_CLIENT_H */ | [
"[email protected]"
] | |
fb91f6eaa8d8ee4570429a0ed27d843cbd9b7e4f | 1d3220f8f390aa9f5847ace75afdb045531e6cd5 | /DMUploadingRule.cpp | afbd8ae8d3bf984ef96b2eeb2910225e7677da0c | [] | no_license | persenlee/FileTransfer | d85d7577e3366c5515d86ef47c8c925feb2d62d1 | fff2f0b9649fd6259cece45e6b2adfa3bb26d008 | refs/heads/master | 2021-01-01T03:46:55.882496 | 2016-05-20T03:22:28 | 2016-05-20T03:22:28 | 58,631,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,625 | cpp | //
// DMUploadingRule.cpp
// FileTransfer
//
// Created by duomai on 16/5/16.
//
//
#include "DMUploadingRule.hpp"
#include "DMFileUploadManager.hpp"
#include "DMFileTransferException.hpp"
#include "DMFileTransferDef.h"
using namespace web;
using namespace web::json;
void logRequest(http_request request);
void logResponse(http_response response);
void DMUploadingRule::setUserToken(string const &token)
{
_userToken = token;
}
#pragma mark - Ovrride Methods
bool DMUploadingRule::preProcess()
{
return checkFileMeta();
}
bool DMUploadingRule::doUpload()
{
return uploadFileChunk();
}
bool DMUploadingRule::endProcess()
{
return true;
}
#pragma mark - Private Methods
bool DMUploadingRule::checkFileMeta()
{
json::value params = json::value::object();
utility::string_t file_hash(U("file_hash"));
params[file_hash] = json::value(_file.SHA1());
utility::string_t file_crc(U("file_crc"));
params[file_crc] = json::value(_file.CRC32());
utility::string_t file_name(U("file_name"));
params[file_name] = json::value(_file.fileName);
utility::string_t total_size(U("total_size"));
params[total_size] = json::value(_file.fileSize());
const method mtd = methods::POST;
const utility::string_t field_name1 = U("user_session_token");
const utility::string_t value1 = _userToken;
http_request request(mtd);
request.set_request_uri(U("check_file_meta"));
request.headers().add(field_name1, value1);
request.set_body(params);
request.headers().add(U("User-Agent"), "DMFileUploadManager");
pplx::task<http_response> responsetTask = _client.request(request);
logRequest(request);
http_response resp ;
try {
resp = responsetTask.get();
} catch (http_exception ex) {
DMFileTransferException dmException((int)DMFileTransfer_CouldNotGetResponse);
throw dmException;
}
logResponse(resp);
if (resp.status_code() == 200)
{
pplx::task<json::value> jsonTask = resp.extract_json();
json::value result= jsonTask.get();
json::value file_status = result[U("file_status")]; //
json::value file_upload_token = result[U("file_upload_token")];
json::value file_url = result[U("file_url")];
json::value last_ok_chunk_sn = result[U("last_ok_chunk_sn")];
json::value chunk_size = result[U("chunk_size")];
cfmrModel = CheckFileMetaResponseModel((DMFileUploadStatus)file_status.as_integer(),
!file_upload_token.is_null() ? file_upload_token.as_string() : "",
!chunk_size.is_null() ? chunk_size.as_integer() : 0,
!last_ok_chunk_sn.is_null() ? last_ok_chunk_sn.as_integer() : 0,
!file_url.is_null() ? file_url.as_string() : "");
switch (cfmrModel.file_status)
{
case 0:
{
_handler->uploadingProgressHandler(0, _file.fileSize());
}
break;
case 1:
{
_handler->uploadingProgressHandler(cfmrModel.chunk_size * cfmrModel.last_ok_chunk_sn, _file.fileSize());
}
break;
case 2:
{
_handler->uploadCompleteHandler(true,file_url.as_string());
_handler->uploadingProgressHandler(_file.fileSize(), _file.fileSize());
return false;
}
break;
default:
break;
}
return true;
}
else
{
_handler->uploadCompleteHandler(false, "");
return false;
}
}
bool DMUploadingRule::uploadFileChunk()
{
bool success = false;
const method mtd = methods::POST;
const utility::string_t field_name1 = U("upload_token");
const utility::string_t value1 = cfmrModel.file_upload_token;
http_request request(mtd);
request.set_request_uri(U("upload_file_chunk"));
request.headers().add(field_name1, value1);
request.headers().set_content_length(INTMAX_MAX);
request.headers().add(U("User-Agent"), "DMFileUploadManager");
int64_t File_Size = _file.fileLength();
_file.openFile(/*iostream::binary*/);
//续传
int64_t uploadedSize = cfmrModel.last_ok_chunk_sn * cfmrModel.chunk_size;
if (uploadedSize > 0) {
_file.moveFileReadPos(uploadedSize);
}
do {
int request_again_times = 0;
int readSize = cfmrModel.chunk_size;
if (uploadedSize + cfmrModel.chunk_size > File_Size) {
readSize = File_Size % cfmrModel.chunk_size;
}
std::vector<unsigned char> body;
_file.readFile2Vector(body, readSize);
request.set_body(body);
request_again:
request_again_times ++;
logRequest(request);
pplx::task<http_response> responsetTask = _client.request(request);
http_response resp ;
try {
resp = responsetTask.get();
} catch (http_exception ex) {
DMFileTransferException dmException((int)DMFileTransfer_CouldNotGetResponse);
throw dmException;
}
logResponse(resp);
if (resp.status_code() == 200)
{
pplx::task<json::value> jsonTask = resp.extract_json();
json::value result= jsonTask.get();
cout << "response body : " << result.serialize() << endl;
json::value file_status = result[U("file_status")]; //
json::value chunk_status = result[U("chunk_status")];
json::value file_url = result[U("file_url")];
switch (file_status.as_integer())
{
case 1: //正在上传
{
if (chunk_status.as_integer() == -1) { // 标识数据块保存失败
goto request_again;
} else if(chunk_status.as_integer() == 0){
uploadedSize += readSize;
_handler->uploadingProgressHandler(uploadedSize, File_Size);
}
}
break;
case 2: //上传成功
{
uploadedSize += readSize;
_handler->uploadingProgressHandler(uploadedSize, File_Size);
_handler->uploadCompleteHandler(true,file_url.as_string());
success = true;
}
break;
case -1: //文件上传失败
{
_handler->uploadCompleteHandler(false, "");;
}
break;
default:
break;
}
}
else
{
_handler->uploadCompleteHandler(false, "");
}
} while (uploadedSize < File_Size);
_file.closeFile();
return success;
}
void logRequest(http_request request)
{
cout << "---------------------request start------------------" << endl;
cout << request.to_string() << endl;
cout << "---------------------request end------------------" << endl << endl;
}
void logResponse(http_response response)
{
cout << "++++++++++++++++++++response start++++++++++++++++++++" << endl;
cout << response.to_string() << endl;
cout << "++++++++++++++++++++response end++++++++++++++++++++" << endl << endl;
} | [
"[email protected]"
] | |
9b67f6e27a369c3b66f7fb8bf435dc44a8750a9f | 5dbdb28b66c4828bf83564f1cf63f82480d6395f | /HelloWorld_demo_game/Classes/DemoGame/GameClock.h | 0376404ad2fc38c0fa7670b28ad9433a96177a3c | [] | no_license | gengyu-mamba/CardGames | 87a2b8fca377a6bd3de0ba4c6fe09a9e85e22848 | d2b0133c02cc04b75a49ca164a086aaa5603715d | refs/heads/master | 2020-04-02T18:23:19.395504 | 2018-11-08T02:34:23 | 2018-11-08T02:34:23 | 154,698,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 487 | h | #ifndef GAME_CLOCK_H
#define GAME_CLOCK_H
#include "cocos2d.h"
USING_NS_CC;
class GameLayer;
class GameClock :public CCLayer
{
public:
GameClock(GameLayer *pGameLayer);
virtual ~GameClock();
void ShowClock(int iTime,int iTablePos);
void ResetClock();
private:
virtual void onEnter();
virtual void onExit();
void OnSecondTimer(float dt);
CCSprite *m_pSpriteBG;
CCLabelAtlas *m_pNumLable;
int m_iTime;
int m_iTablePos;
GameLayer *m_pGameLayer;
};
#endif
| [
"[email protected]"
] | |
4f382278b8d5b2babc07007ecf53e4df951a580f | fc087820e4dc33146341cd6b71a000c227cda819 | /Majority Element II.cpp | 8f6a0b3226ec9ceea590fa7c8715ee973817c422 | [] | no_license | jyqi/leetcode | 1396b27fd97aa29687392dceda2e0bed2dc8fd31 | 9682e03fa91dca44654439029fb11d73e86a61d8 | refs/heads/master | 2022-02-16T09:14:54.012699 | 2022-02-14T07:54:11 | 2022-02-14T07:54:11 | 56,414,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int cnt1 = 0, cnt2 = 0, maj1 = 0, maj2 = 0;
int len = nums.size();
vector<int> res;
//cout << 1 << endl;
for(int i = 0; i < len; i++) {
if(cnt1 == 0 && nums[i] != maj2) {
maj1 = nums[i];
cnt1 = 1;
}
else if(nums[i] == maj1) {
cnt1++;
}
else if(cnt2 == 0 && nums[i] != maj1) {
maj2 = nums[i];
cnt2 = 1;
}
else if(nums[i] == maj2) {
cnt2++;
}
else {
cnt1--;
cnt2--;
}
}
cnt1 = cnt2 = 0;
for(int i = 0; i < len; i++) {
if(nums[i] == maj1) cnt1++;
else if(nums[i] == maj2) cnt2++;
}
if(cnt1 > len / 3) res.push_back(maj1);
if(cnt2 > len / 3) res.push_back(maj2);
return res;
}
};
int main() {
int arr[] = {1, 2, 1, 2, 1, 3, 3};
Solution s;
vector<int> v(arr, arr + 7);
vector<int> res;
res = s.majorityElement(v);
for(int i = 0; i < res.size(); i++) {
cout << res[i] << endl;
}
return 0;
} | [
"[email protected]"
] | |
ed2c7bf9da571764d1c53f11f98afd73c52384e1 | 9618f5517917b18298c160161633f91d2a61e1e1 | /kursach_taras/cone.cpp | ef624b9c68a1609baec321cf776925a5bfc108c2 | [] | no_license | h1xxy/taras_krsch | b1bf548cb3ec4413294f9b1fd7c60fc71567ea33 | 4b9bb13015792a0bc64fdbf2c1702d2a1050879b | refs/heads/master | 2022-07-04T21:14:59.666350 | 2020-05-20T08:52:40 | 2020-05-20T08:52:40 | 265,474,938 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 856 | cpp | #include "cone.h"
#include <math.h>
#define M_PI 3.14159265358979323846
#define ANGLE_STEPSIZE 0.001f
Cone::~Cone()
{
}
void Cone::draw()
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
float x = 0.0;
float y = 0.0;
float angle;
glColor3ub(colorR_, colorG_, colorB_);
glBegin(GL_POLYGON);
angle = 0.0;
glVertex3f(positionX_, positionY_, positionZ_ + (height_ / 2));
while (angle <= 2 * M_PI + 1)
{
x = radius_ * cos(angle);
y = radius_ * sin(angle);
glVertex3f(x + positionX_, y + positionY_, positionZ_ - (height_ / 2));
angle = angle + ANGLE_STEPSIZE;
}
glEnd();
glBegin(GL_POLYGON);
angle = 0.0;
while (angle < 2 * M_PI)
{
x = radius_ * cos(angle);
y = radius_ * sin(angle);
glVertex3f(x + positionX_, y + positionY_, positionZ_ - (height_ / 2));
angle = angle + ANGLE_STEPSIZE;
}
glEnd();
glPopMatrix();
}
| [
"[email protected]"
] | |
3c1b9a977eb477d5b194c9d62796fdbdb650af98 | 74b07eb2bc01383744514b70b385571fb90a1a04 | /test/test.cpp | c870d6500c7d2c64c80815743dbbe2e47990c430 | [] | no_license | yksym/x86_64_hook_without_ld_preload | 8ae067c195bf1eb0f23d67a1087ad3f8ebcfab4a | 2ed1eaf37f688199f12e3aa34a6f3435b906b932 | refs/heads/master | 2016-09-05T11:08:33.212588 | 2015-09-03T13:02:04 | 2015-09-03T13:02:04 | 40,049,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <hook.h>
extern "C" {
void* calloc_hook(size_t n, size_t size)
{
DECL_ORG_FUNC(calloc, org_calloc);
puts( __FUNCTION__ );
return org_calloc(n, size);
}
};
void test(const char* program)
{
puts(__FILE__ ": 1st");
{
HOOK(program, calloc, calloc_hook);
void* b = calloc(1, 10);
free(b);
}
puts(__FILE__ ": 2nd");
void* c = calloc(1, 10);
free(c);
puts(__FILE__ ": 3rd");
{
HOOK(program, calloc, calloc_hook);
void* b = calloc(1, 10);
free(b);
}
}
void test2(const char* program);
int main(int argc, char** argv)
{
test(argv[0]);
test2(LIB_NAME);
return 0;
}
| [
"[email protected]"
] | |
8a96e354acf08b5427cf3791a514286b61b32365 | ddbc8b916e028cf70467928d3be17506713baeff | /src/Setup/unzip.cpp | c2b062c3bb714c756f317e2995e1129180774b39 | [
"MIT"
] | permissive | Squirrel/Squirrel.Windows | e7687f81ae08ebf6f4b6005ed8394f78f6c9c1ad | 5e44cb4001a7d48f53ee524a2d90b3f5700a9920 | refs/heads/develop | 2023-09-03T23:06:14.600642 | 2023-08-01T17:34:34 | 2023-08-01T17:34:34 | 22,338,518 | 7,243 | 1,336 | MIT | 2023-08-01T17:34:36 | 2014-07-28T10:10:39 | C++ | UTF-8 | C++ | false | false | 145,049 | cpp | #include "stdafx.h"
#include "unzip.h"
// THIS FILE is almost entirely based upon code by Jean-loup Gailly
// and Mark Adler. It has been modified by Lucian Wischik.
// The modifications were: incorporate the bugfixes of 1.1.4, allow
// unzipping to/from handles/pipes/files/memory, encryption, unicode,
// a windowsish api, and putting everything into a single .cpp file.
// The original code may be found at http://www.gzip.org/zlib/
// The original copyright text follows.
//
//
//
// zlib.h -- interface of the 'zlib' general purpose compression library
// version 1.1.3, July 9th, 1998
//
// Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Jean-loup Gailly Mark Adler
// [email protected] [email protected]
//
//
// The data format used by the zlib library is described by RFCs (Request for
// Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
// (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
//
//
// The 'zlib' compression library provides in-memory compression and
// decompression functions, including integrity checks of the uncompressed
// data. This version of the library supports only one compression method
// (deflation) but other algorithms will be added later and will have the same
// stream interface.
//
// Compression can be done in a single step if the buffers are large
// enough (for example if an input file is mmap'ed), or can be done by
// repeated calls of the compression function. In the latter case, the
// application must provide more input and/or consume the output
// (providing more output space) before each call.
//
// The library also supports reading and writing files in gzip (.gz) format
// with an interface similar to that of stdio.
//
// The library does not install any signal handler. The decoder checks
// the consistency of the compressed data, so the library should never
// crash even in case of corrupted input.
//
// for more info about .ZIP format, see ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
// PkWare has also a specification at ftp://ftp.pkware.com/probdesc.zip
#define ZIP_HANDLE 1
#define ZIP_FILENAME 2
#define ZIP_MEMORY 3
#define zmalloc(len) malloc(len)
#define zfree(p) free(p)
/*
void *zmalloc(unsigned int len)
{ char *buf = new char[len+32];
for (int i=0; i<16; i++)
{ buf[i]=i;
buf[len+31-i]=i;
}
*((unsigned int*)buf) = len;
char c[1000]; wsprintf(c,"malloc 0x%lx - %lu",buf+16,len);
OutputDebugString(c);
return buf+16;
}
void zfree(void *buf)
{ char c[1000]; wsprintf(c,"free 0x%lx",buf);
OutputDebugString(c);
char *p = ((char*)buf)-16;
unsigned int len = *((unsigned int*)p);
bool blown=false;
for (int i=0; i<16; i++)
{ char lo = p[i];
char hi = p[len+31-i];
if (hi!=i || (lo!=i && i>4)) blown=true;
}
if (blown)
{ OutputDebugString("BLOWN!!!");
}
delete[] p;
}
*/
typedef struct tm_unz_s
{ unsigned int tm_sec; // seconds after the minute - [0,59]
unsigned int tm_min; // minutes after the hour - [0,59]
unsigned int tm_hour; // hours since midnight - [0,23]
unsigned int tm_mday; // day of the month - [1,31]
unsigned int tm_mon; // months since January - [0,11]
unsigned int tm_year; // years - [1980..2044]
} tm_unz;
// unz_global_info structure contain global data about the ZIPfile
typedef struct unz_global_info_s
{ unsigned long number_entry; // total number of entries in the central dir on this disk
unsigned long size_comment; // size of the global comment of the zipfile
} unz_global_info;
// unz_file_info contain information about a file in the zipfile
typedef struct unz_file_info_s
{ unsigned long version; // version made by 2 bytes
unsigned long version_needed; // version needed to extract 2 bytes
unsigned long flag; // general purpose bit flag 2 bytes
unsigned long compression_method; // compression method 2 bytes
unsigned long dosDate; // last mod file date in Dos fmt 4 bytes
unsigned long crc; // crc-32 4 bytes
unsigned long compressed_size; // compressed size 4 bytes
unsigned long uncompressed_size; // uncompressed size 4 bytes
unsigned long size_filename; // filename length 2 bytes
unsigned long size_file_extra; // extra field length 2 bytes
unsigned long size_file_comment; // file comment length 2 bytes
unsigned long disk_num_start; // disk number start 2 bytes
unsigned long internal_fa; // internal file attributes 2 bytes
unsigned long external_fa; // external file attributes 4 bytes
tm_unz tmu_date;
} unz_file_info;
#define UNZ_OK (0)
#define UNZ_END_OF_LIST_OF_FILE (-100)
#define UNZ_ERRNO (Z_ERRNO)
#define UNZ_EOF (0)
#define UNZ_PARAMERROR (-102)
#define UNZ_BADZIPFILE (-103)
#define UNZ_INTERNALERROR (-104)
#define UNZ_CRCERROR (-105)
#define UNZ_PASSWORD (-106)
#define ZLIB_VERSION "1.1.3"
// Allowed flush values; see deflate() for details
#define Z_NO_FLUSH 0
#define Z_SYNC_FLUSH 2
#define Z_FULL_FLUSH 3
#define Z_FINISH 4
// compression levels
#define Z_NO_COMPRESSION 0
#define Z_BEST_SPEED 1
#define Z_BEST_COMPRESSION 9
#define Z_DEFAULT_COMPRESSION (-1)
// compression strategy; see deflateInit2() for details
#define Z_FILTERED 1
#define Z_HUFFMAN_ONLY 2
#define Z_DEFAULT_STRATEGY 0
// Possible values of the data_type field
#define Z_BINARY 0
#define Z_ASCII 1
#define Z_UNKNOWN 2
// The deflate compression method (the only one supported in this version)
#define Z_DEFLATED 8
// for initializing zalloc, zfree, opaque
#define Z_NULL 0
// case sensitivity when searching for filenames
#define CASE_SENSITIVE 1
#define CASE_INSENSITIVE 2
// Return codes for the compression/decompression functions. Negative
// values are errors, positive values are used for special but normal events.
#define Z_OK 0
#define Z_STREAM_END 1
#define Z_NEED_DICT 2
#define Z_ERRNO (-1)
#define Z_STREAM_ERROR (-2)
#define Z_DATA_ERROR (-3)
#define Z_MEM_ERROR (-4)
#define Z_BUF_ERROR (-5)
#define Z_VERSION_ERROR (-6)
// Basic data types
typedef unsigned char Byte; // 8 bits
typedef unsigned int uInt; // 16 bits or more
typedef unsigned long uLong; // 32 bits or more
typedef void *voidpf;
typedef void *voidp;
typedef long z_off_t;
typedef voidpf (*alloc_func) (voidpf opaque, uInt items, uInt size);
typedef void (*free_func) (voidpf opaque, voidpf address);
struct internal_state;
typedef struct z_stream_s {
Byte *next_in; // next input byte
uInt avail_in; // number of bytes available at next_in
uLong total_in; // total nb of input bytes read so far
Byte *next_out; // next output byte should be put there
uInt avail_out; // remaining free space at next_out
uLong total_out; // total nb of bytes output so far
char *msg; // last error message, NULL if no error
struct internal_state *state; // not visible by applications
alloc_func zalloc; // used to allocate the internal state
free_func zfree; // used to free the internal state
voidpf opaque; // private data object passed to zalloc and zfree
int data_type; // best guess about the data type: ascii or binary
uLong adler; // adler32 value of the uncompressed data
uLong reserved; // reserved for future use
} z_stream;
typedef z_stream *z_streamp;
// The application must update next_in and avail_in when avail_in has
// dropped to zero. It must update next_out and avail_out when avail_out
// has dropped to zero. The application must initialize zalloc, zfree and
// opaque before calling the init function. All other fields are set by the
// compression library and must not be updated by the application.
//
// The opaque value provided by the application will be passed as the first
// parameter for calls of zalloc and zfree. This can be useful for custom
// memory management. The compression library attaches no meaning to the
// opaque value.
//
// zalloc must return Z_NULL if there is not enough memory for the object.
// If zlib is used in a multi-threaded application, zalloc and zfree must be
// thread safe.
//
// The fields total_in and total_out can be used for statistics or
// progress reports. After compression, total_in holds the total size of
// the uncompressed data and may be saved for use in the decompressor
// (particularly if the decompressor wants to decompress everything in
// a single step).
//
// basic functions
const char *zlibVersion ();
// The application can compare zlibVersion and ZLIB_VERSION for consistency.
// If the first character differs, the library code actually used is
// not compatible with the zlib.h header file used by the application.
// This check is automatically made by inflateInit.
int inflate (z_streamp strm, int flush);
//
// inflate decompresses as much data as possible, and stops when the input
// buffer becomes empty or the output buffer becomes full. It may some
// introduce some output latency (reading input without producing any output)
// except when forced to flush.
//
// The detailed semantics are as follows. inflate performs one or both of the
// following actions:
//
// - Decompress more input starting at next_in and update next_in and avail_in
// accordingly. If not all input can be processed (because there is not
// enough room in the output buffer), next_in is updated and processing
// will resume at this point for the next call of inflate().
//
// - Provide more output starting at next_out and update next_out and avail_out
// accordingly. inflate() provides as much output as possible, until there
// is no more input data or no more space in the output buffer (see below
// about the flush parameter).
//
// Before the call of inflate(), the application should ensure that at least
// one of the actions is possible, by providing more input and/or consuming
// more output, and updating the next_* and avail_* values accordingly.
// The application can consume the uncompressed output when it wants, for
// example when the output buffer is full (avail_out == 0), or after each
// call of inflate(). If inflate returns Z_OK and with zero avail_out, it
// must be called again after making room in the output buffer because there
// might be more output pending.
//
// If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
// output as possible to the output buffer. The flushing behavior of inflate is
// not specified for values of the flush parameter other than Z_SYNC_FLUSH
// and Z_FINISH, but the current implementation actually flushes as much output
// as possible anyway.
//
// inflate() should normally be called until it returns Z_STREAM_END or an
// error. However if all decompression is to be performed in a single step
// (a single call of inflate), the parameter flush should be set to
// Z_FINISH. In this case all pending input is processed and all pending
// output is flushed; avail_out must be large enough to hold all the
// uncompressed data. (The size of the uncompressed data may have been saved
// by the compressor for this purpose.) The next operation on this stream must
// be inflateEnd to deallocate the decompression state. The use of Z_FINISH
// is never required, but can be used to inform inflate that a faster routine
// may be used for the single inflate() call.
//
// If a preset dictionary is needed at this point (see inflateSetDictionary
// below), inflate sets strm-adler to the adler32 checksum of the
// dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
// it sets strm->adler to the adler32 checksum of all output produced
// so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
// an error code as described below. At the end of the stream, inflate()
// checks that its computed adler32 checksum is equal to that saved by the
// compressor and returns Z_STREAM_END only if the checksum is correct.
//
// inflate() returns Z_OK if some progress has been made (more input processed
// or more output produced), Z_STREAM_END if the end of the compressed data has
// been reached and all uncompressed output has been produced, Z_NEED_DICT if a
// preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
// corrupted (input stream not conforming to the zlib format or incorrect
// adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
// (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
// enough memory, Z_BUF_ERROR if no progress is possible or if there was not
// enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
// case, the application may then call inflateSync to look for a good
// compression block.
//
int inflateEnd (z_streamp strm);
//
// All dynamically allocated data structures for this stream are freed.
// This function discards any unprocessed input and does not flush any
// pending output.
//
// inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
// was inconsistent. In the error case, msg may be set but then points to a
// static string (which must not be deallocated).
// Advanced functions
// The following functions are needed only in some special applications.
int inflateSetDictionary (z_streamp strm,
const Byte *dictionary,
uInt dictLength);
//
// Initializes the decompression dictionary from the given uncompressed byte
// sequence. This function must be called immediately after a call of inflate
// if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
// can be determined from the Adler32 value returned by this call of
// inflate. The compressor and decompressor must use exactly the same
// dictionary.
//
// inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
// parameter is invalid (such as NULL dictionary) or the stream state is
// inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
// expected one (incorrect Adler32 value). inflateSetDictionary does not
// perform any decompression: this will be done by subsequent calls of
// inflate().
int inflateSync (z_streamp strm);
//
// Skips invalid compressed data until a full flush point can be found, or until all
// available input is skipped. No output is provided.
//
// inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
// if no more input was provided, Z_DATA_ERROR if no flush point has been found,
// or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
// case, the application may save the current current value of total_in which
// indicates where valid compressed data was found. In the error case, the
// application may repeatedly call inflateSync, providing more input each time,
// until success or end of the input data.
int inflateReset (z_streamp strm);
// This function is equivalent to inflateEnd followed by inflateInit,
// but does not free and reallocate all the internal decompression state.
// The stream will keep attributes that may have been set by inflateInit2.
//
// inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
// stream state was inconsistent (such as zalloc or state being NULL).
//
// checksum functions
// These functions are not related to compression but are exported
// anyway because they might be useful in applications using the
// compression library.
uLong adler32 (uLong adler, const Byte *buf, uInt len);
// Update a running Adler-32 checksum with the bytes buf[0..len-1] and
// return the updated checksum. If buf is NULL, this function returns
// the required initial value for the checksum.
// An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
// much faster. Usage example:
//
// uLong adler = adler32(0L, Z_NULL, 0);
//
// while (read_buffer(buffer, length) != EOF) {
// adler = adler32(adler, buffer, length);
// }
// if (adler != original_adler) error();
uLong ucrc32 (uLong crc, const Byte *buf, uInt len);
// Update a running crc with the bytes buf[0..len-1] and return the updated
// crc. If buf is NULL, this function returns the required initial value
// for the crc. Pre- and post-conditioning (one's complement) is performed
// within this function so it shouldn't be done by the application.
// Usage example:
//
// uLong crc = crc32(0L, Z_NULL, 0);
//
// while (read_buffer(buffer, length) != EOF) {
// crc = crc32(crc, buffer, length);
// }
// if (crc != original_crc) error();
const char *zError (int err);
int inflateSyncPoint (z_streamp z);
const uLong *get_crc_table (void);
typedef unsigned char uch;
typedef uch uchf;
typedef unsigned short ush;
typedef ush ushf;
typedef unsigned long ulg;
const char * const z_errmsg[10] = { // indexed by 2-zlib_error
"need dictionary", // Z_NEED_DICT 2
"stream end", // Z_STREAM_END 1
"", // Z_OK 0
"file error", // Z_ERRNO (-1)
"stream error", // Z_STREAM_ERROR (-2)
"data error", // Z_DATA_ERROR (-3)
"insufficient memory", // Z_MEM_ERROR (-4)
"buffer error", // Z_BUF_ERROR (-5)
"incompatible version",// Z_VERSION_ERROR (-6)
""};
#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
#define ERR_RETURN(strm,err) \
return (strm->msg = (char*)ERR_MSG(err), (err))
// To be used only when the state is known to be valid
// common constants
#define STORED_BLOCK 0
#define STATIC_TREES 1
#define DYN_TREES 2
// The three kinds of block type
#define MIN_MATCH 3
#define MAX_MATCH 258
// The minimum and maximum match lengths
#define PRESET_DICT 0x20 // preset dictionary flag in zlib header
// target dependencies
#define OS_CODE 0x0b // Window 95 & Windows NT
// functions
#define zmemzero(dest, len) memset(dest, 0, len)
// Diagnostic functions
#define LuAssert(cond,msg)
#define LuTrace(x)
#define LuTracev(x)
#define LuTracevv(x)
#define LuTracec(c,x)
#define LuTracecv(c,x)
typedef uLong (*check_func) (uLong check, const Byte *buf, uInt len);
voidpf zcalloc (voidpf opaque, unsigned items, unsigned size);
void zcfree (voidpf opaque, voidpf ptr);
#define ZALLOC(strm, items, size) \
(*((strm)->zalloc))((strm)->opaque, (items), (size))
#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
//void ZFREE(z_streamp strm,voidpf addr)
//{ *((strm)->zfree))((strm)->opaque, addr);
//}
#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
// Huffman code lookup table entry--this entry is four bytes for machines
// that have 16-bit pointers (e.g. PC's in the small or medium model).
typedef struct inflate_huft_s inflate_huft;
struct inflate_huft_s {
union {
struct {
Byte Exop; // number of extra bits or operation
Byte Bits; // number of bits in this code or subcode
} what;
uInt pad; // pad structure to a power of 2 (4 bytes for
} word; // 16-bit, 8 bytes for 32-bit int's)
uInt base; // literal, length base, distance base, or table offset
};
// Maximum size of dynamic tree. The maximum found in a long but non-
// exhaustive search was 1004 huft structures (850 for length/literals
// and 154 for distances, the latter actually the result of an
// exhaustive search). The actual maximum is not known, but the
// value below is more than safe.
#define MANY 1440
int inflate_trees_bits (
uInt *, // 19 code lengths
uInt *, // bits tree desired/actual depth
inflate_huft * *, // bits tree result
inflate_huft *, // space for trees
z_streamp); // for messages
int inflate_trees_dynamic (
uInt, // number of literal/length codes
uInt, // number of distance codes
uInt *, // that many (total) code lengths
uInt *, // literal desired/actual bit depth
uInt *, // distance desired/actual bit depth
inflate_huft * *, // literal/length tree result
inflate_huft * *, // distance tree result
inflate_huft *, // space for trees
z_streamp); // for messages
int inflate_trees_fixed (
uInt *, // literal desired/actual bit depth
uInt *, // distance desired/actual bit depth
const inflate_huft * *, // literal/length tree result
const inflate_huft * *, // distance tree result
z_streamp); // for memory allocation
struct inflate_blocks_state;
typedef struct inflate_blocks_state inflate_blocks_statef;
inflate_blocks_statef * inflate_blocks_new (
z_streamp z,
check_func c, // check function
uInt w); // window size
int inflate_blocks (
inflate_blocks_statef *,
z_streamp ,
int); // initial return code
void inflate_blocks_reset (
inflate_blocks_statef *,
z_streamp ,
uLong *); // check value on output
int inflate_blocks_free (
inflate_blocks_statef *,
z_streamp);
void inflate_set_dictionary (
inflate_blocks_statef *s,
const Byte *d, // dictionary
uInt n); // dictionary length
int inflate_blocks_sync_point (
inflate_blocks_statef *s);
struct inflate_codes_state;
typedef struct inflate_codes_state inflate_codes_statef;
inflate_codes_statef *inflate_codes_new (
uInt, uInt,
const inflate_huft *, const inflate_huft *,
z_streamp );
int inflate_codes (
inflate_blocks_statef *,
z_streamp ,
int);
void inflate_codes_free (
inflate_codes_statef *,
z_streamp );
typedef enum {
IBM_TYPE, // get type bits (3, including end bit)
IBM_LENS, // get lengths for stored
IBM_STORED, // processing stored block
IBM_TABLE, // get table lengths
IBM_BTREE, // get bit lengths tree for a dynamic block
IBM_DTREE, // get length, distance trees for a dynamic block
IBM_CODES, // processing fixed or dynamic block
IBM_DRY, // output remaining window bytes
IBM_DONE, // finished last block, done
IBM_BAD} // got a data error--stuck here
inflate_block_mode;
// inflate blocks semi-private state
struct inflate_blocks_state {
// mode
inflate_block_mode mode; // current inflate_block mode
// mode dependent information
union {
uInt left; // if STORED, bytes left to copy
struct {
uInt table; // table lengths (14 bits)
uInt index; // index into blens (or border)
uInt *blens; // bit lengths of codes
uInt bb; // bit length tree depth
inflate_huft *tb; // bit length decoding tree
} trees; // if DTREE, decoding info for trees
struct {
inflate_codes_statef
*codes;
} decode; // if CODES, current state
} sub; // submode
uInt last; // true if this block is the last block
// mode independent information
uInt bitk; // bits in bit buffer
uLong bitb; // bit buffer
inflate_huft *hufts; // single malloc for tree space
Byte *window; // sliding window
Byte *end; // one byte after sliding window
Byte *read; // window read pointer
Byte *write; // window write pointer
check_func checkfn; // check function
uLong check; // check on output
};
// defines for inflate input/output
// update pointers and return
#define UPDBITS {s->bitb=b;s->bitk=k;}
#define UPDIN {z->avail_in=n;z->total_in+=(uLong)(p-z->next_in);z->next_in=p;}
#define UPDOUT {s->write=q;}
#define UPDATE {UPDBITS UPDIN UPDOUT}
#define LEAVE {UPDATE return inflate_flush(s,z,r);}
// get bytes and bits
#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
#define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
#define NEXTBYTE (n--,*p++)
#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
#define DUMPBITS(j) {b>>=(j);k-=(j);}
// output bytes
#define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
#define LOADOUT {q=s->write;m=(uInt)WAVAIL;m;}
#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
#define OUTBYTE(a) {*q++=(Byte)(a);m--;}
// load local pointers
#define LOAD {LOADIN LOADOUT}
// masks for lower bits (size given to avoid silly warnings with Visual C++)
// And'ing with mask[n] masks the lower n bits
const uInt inflate_mask[17] = {
0x0000,
0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
};
// copy as much as possible from the sliding window to the output area
int inflate_flush (inflate_blocks_statef *, z_streamp, int);
int inflate_fast (uInt, uInt, const inflate_huft *, const inflate_huft *, inflate_blocks_statef *, z_streamp );
const uInt fixed_bl = 9;
const uInt fixed_bd = 5;
const inflate_huft fixed_tl[] = {
{{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
{{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
{{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
{{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
{{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
{{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
{{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
{{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
{{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
{{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
{{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
{{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
{{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
{{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
{{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
{{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
{{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
{{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
{{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
{{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
{{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
{{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
{{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
{{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
{{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
{{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
{{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
{{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
{{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
{{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
{{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
{{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
{{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
{{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
{{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
{{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
{{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
{{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
{{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
{{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
{{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
{{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
{{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
{{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
{{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
{{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
{{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
{{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
{{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
{{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
{{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
{{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
{{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
{{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
{{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
{{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
{{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
{{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
{{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
{{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
{{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
{{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
{{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
{{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
{{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
{{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
{{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
{{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
{{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
{{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
{{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
{{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
{{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
{{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
{{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
{{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
{{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
{{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
{{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
{{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
{{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
{{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
{{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
{{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
{{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
{{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
{{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
{{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
{{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
{{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
{{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
{{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
{{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
{{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
{{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
{{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
{{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
{{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
{{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
{{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
{{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
{{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
{{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
{{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
{{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
{{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
{{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
{{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
{{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
{{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
{{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
{{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
{{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
{{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
{{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
{{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
{{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
{{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
{{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
{{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
{{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
{{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
{{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
{{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
};
const inflate_huft fixed_td[] = {
{{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
{{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
{{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
{{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
{{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
{{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
{{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
{{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
};
// copy as much as possible from the sliding window to the output area
int inflate_flush(inflate_blocks_statef *s,z_streamp z,int r)
{
uInt n;
Byte *p;
Byte *q;
// local copies of source and destination pointers
p = z->next_out;
q = s->read;
// compute number of bytes to copy as far as end of window
n = (uInt)((q <= s->write ? s->write : s->end) - q);
if (n > z->avail_out) n = z->avail_out;
if (n && r == Z_BUF_ERROR) r = Z_OK;
// update counters
z->avail_out -= n;
z->total_out += n;
// update check information
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(s->check, q, n);
// copy as far as end of window
if (n!=0) // check for n!=0 to avoid waking up CodeGuard
{ memcpy(p, q, n);
p += n;
q += n;
}
// see if more to copy at beginning of window
if (q == s->end)
{
// wrap pointers
q = s->window;
if (s->write == s->end)
s->write = s->window;
// compute bytes to copy
n = (uInt)(s->write - q);
if (n > z->avail_out) n = z->avail_out;
if (n && r == Z_BUF_ERROR) r = Z_OK;
// update counters
z->avail_out -= n;
z->total_out += n;
// update check information
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(s->check, q, n);
// copy
if (n!=0) {memcpy(p,q,n); p+=n; q+=n;}
}
// update pointers
z->next_out = p;
s->read = q;
// done
return r;
}
// simplify the use of the inflate_huft type with some defines
#define exop word.what.Exop
#define bits word.what.Bits
typedef enum { // waiting for "i:"=input, "o:"=output, "x:"=nothing
START, // x: set up for LEN
LEN, // i: get length/literal/eob next
LENEXT, // i: getting length extra (have base)
DIST, // i: get distance next
DISTEXT, // i: getting distance extra
COPY, // o: copying bytes in window, waiting for space
LIT, // o: got literal, waiting for output space
WASH, // o: got eob, possibly still output waiting
END, // x: got eob and all data flushed
BADCODE} // x: got error
inflate_codes_mode;
// inflate codes private state
struct inflate_codes_state {
// mode
inflate_codes_mode mode; // current inflate_codes mode
// mode dependent information
uInt len;
union {
struct {
const inflate_huft *tree; // pointer into tree
uInt need; // bits needed
} code; // if LEN or DIST, where in tree
uInt lit; // if LIT, literal
struct {
uInt get; // bits to get for extra
uInt dist; // distance back to copy from
} copy; // if EXT or COPY, where and how much
} sub; // submode
// mode independent information
Byte lbits; // ltree bits decoded per branch
Byte dbits; // dtree bits decoder per branch
const inflate_huft *ltree; // literal/length/eob tree
const inflate_huft *dtree; // distance tree
};
inflate_codes_statef *inflate_codes_new(
uInt bl, uInt bd,
const inflate_huft *tl,
const inflate_huft *td, // need separate declaration for Borland C++
z_streamp z)
{
inflate_codes_statef *c;
if ((c = (inflate_codes_statef *)
ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
{
c->mode = START;
c->lbits = (Byte)bl;
c->dbits = (Byte)bd;
c->ltree = tl;
c->dtree = td;
LuTracev((stderr, "inflate: codes new\n"));
}
return c;
}
int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r)
{
uInt j; // temporary storage
const inflate_huft *t; // temporary pointer
uInt e; // extra bits or operation
uLong b; // bit buffer
uInt k; // bits in bit buffer
Byte *p; // input data pointer
uInt n; // bytes available there
Byte *q; // output window write pointer
uInt m; // bytes to end of window or read pointer
Byte *f; // pointer to copy strings from
inflate_codes_statef *c = s->sub.decode.codes; // codes state
// copy input/output information to locals (UPDATE macro restores)
LOAD
// process input and output based on current state
for(;;) switch (c->mode)
{ // waiting for "i:"=input, "o:"=output, "x:"=nothing
case START: // x: set up for LEN
#ifndef SLOW
if (m >= 258 && n >= 10)
{
UPDATE
r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
LOAD
if (r != Z_OK)
{
c->mode = r == Z_STREAM_END ? WASH : BADCODE;
break;
}
}
#endif // !SLOW
c->sub.code.need = c->lbits;
c->sub.code.tree = c->ltree;
c->mode = LEN;
case LEN: // i: get length/literal/eob next
j = c->sub.code.need;
NEEDBITS(j)
t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
DUMPBITS(t->bits)
e = (uInt)(t->exop);
if (e == 0) // literal
{
c->sub.lit = t->base;
LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", t->base));
c->mode = LIT;
break;
}
if (e & 16) // length
{
c->sub.copy.get = e & 15;
c->len = t->base;
c->mode = LENEXT;
break;
}
if ((e & 64) == 0) // next table
{
c->sub.code.need = e;
c->sub.code.tree = t + t->base;
break;
}
if (e & 32) // end of block
{
LuTracevv((stderr, "inflate: end of block\n"));
c->mode = WASH;
break;
}
c->mode = BADCODE; // invalid code
z->msg = (char*)"invalid literal/length code";
r = Z_DATA_ERROR;
LEAVE
case LENEXT: // i: getting length extra (have base)
j = c->sub.copy.get;
NEEDBITS(j)
c->len += (uInt)b & inflate_mask[j];
DUMPBITS(j)
c->sub.code.need = c->dbits;
c->sub.code.tree = c->dtree;
LuTracevv((stderr, "inflate: length %u\n", c->len));
c->mode = DIST;
case DIST: // i: get distance next
j = c->sub.code.need;
NEEDBITS(j)
t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
DUMPBITS(t->bits)
e = (uInt)(t->exop);
if (e & 16) // distance
{
c->sub.copy.get = e & 15;
c->sub.copy.dist = t->base;
c->mode = DISTEXT;
break;
}
if ((e & 64) == 0) // next table
{
c->sub.code.need = e;
c->sub.code.tree = t + t->base;
break;
}
c->mode = BADCODE; // invalid code
z->msg = (char*)"invalid distance code";
r = Z_DATA_ERROR;
LEAVE
case DISTEXT: // i: getting distance extra
j = c->sub.copy.get;
NEEDBITS(j)
c->sub.copy.dist += (uInt)b & inflate_mask[j];
DUMPBITS(j)
LuTracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist));
c->mode = COPY;
case COPY: // o: copying bytes in window, waiting for space
f = q - c->sub.copy.dist;
while (f < s->window) // modulo window size-"while" instead
f += s->end - s->window; // of "if" handles invalid distances
while (c->len)
{
NEEDOUT
OUTBYTE(*f++)
if (f == s->end)
f = s->window;
c->len--;
}
c->mode = START;
break;
case LIT: // o: got literal, waiting for output space
NEEDOUT
OUTBYTE(c->sub.lit)
c->mode = START;
break;
case WASH: // o: got eob, possibly more output
if (k > 7) // return unused byte, if any
{
//Assert(k < 16, "inflate_codes grabbed too many bytes")
k -= 8;
n++;
p--; // can always return one
}
FLUSH
if (s->read != s->write)
LEAVE
c->mode = END;
case END:
r = Z_STREAM_END;
LEAVE
case BADCODE: // x: got error
r = Z_DATA_ERROR;
LEAVE
default:
r = Z_STREAM_ERROR;
LEAVE
}
}
void inflate_codes_free(inflate_codes_statef *c,z_streamp z)
{ ZFREE(z, c);
LuTracev((stderr, "inflate: codes free\n"));
}
// infblock.c -- interpret and process block types to last block
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
//struct inflate_codes_state {int dummy;}; // for buggy compilers
// Table for deflate from PKZIP's appnote.txt.
const uInt border[] = { // Order of the bit length code lengths
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
//
// Notes beyond the 1.93a appnote.txt:
//
// 1. Distance pointers never point before the beginning of the output stream.
// 2. Distance pointers can point back across blocks, up to 32k away.
// 3. There is an implied maximum of 7 bits for the bit length table and
// 15 bits for the actual data.
// 4. If only one code exists, then it is encoded using one bit. (Zero
// would be more efficient, but perhaps a little confusing.) If two
// codes exist, they are coded using one bit each (0 and 1).
// 5. There is no way of sending zero distance codes--a dummy must be
// sent if there are none. (History: a pre 2.0 version of PKZIP would
// store blocks with no distance codes, but this was discovered to be
// too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
// zero distance codes, which is sent as one code of zero bits in
// length.
// 6. There are up to 286 literal/length codes. Code 256 represents the
// end-of-block. Note however that the static length tree defines
// 288 codes just to fill out the Huffman codes. Codes 286 and 287
// cannot be used though, since there is no length base or extra bits
// defined for them. Similarily, there are up to 30 distance codes.
// However, static trees define 32 codes (all 5 bits) to fill out the
// Huffman codes, but the last two had better not show up in the data.
// 7. Unzip can check dynamic Huffman blocks for complete code sets.
// The exception is that a single code would not be complete (see #4).
// 8. The five bits following the block type is really the number of
// literal codes sent minus 257.
// 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
// (1+6+6). Therefore, to output three times the length, you output
// three codes (1+1+1), whereas to output four times the same length,
// you only need two codes (1+3). Hmm.
//10. In the tree reconstruction algorithm, Code = Code + Increment
// only if BitLength(i) is not zero. (Pretty obvious.)
//11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
//12. Note: length code 284 can represent 227-258, but length code 285
// really is 258. The last length deserves its own, short code
// since it gets used a lot in very redundant files. The length
// 258 is special since 258 - 3 (the min match length) is 255.
//13. The literal/length and distance code bit lengths are read as a
// single stream of lengths. It is possible (and advantageous) for
// a repeat code (16, 17, or 18) to go across the boundary between
// the two sets of lengths.
void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c)
{
if (c != Z_NULL)
*c = s->check;
if (s->mode == IBM_BTREE || s->mode == IBM_DTREE)
ZFREE(z, s->sub.trees.blens);
if (s->mode == IBM_CODES)
inflate_codes_free(s->sub.decode.codes, z);
s->mode = IBM_TYPE;
s->bitk = 0;
s->bitb = 0;
s->read = s->write = s->window;
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0);
LuTracev((stderr, "inflate: blocks reset\n"));
}
inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w)
{
inflate_blocks_statef *s;
if ((s = (inflate_blocks_statef *)ZALLOC
(z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
return s;
if ((s->hufts =
(inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL)
{
ZFREE(z, s);
return Z_NULL;
}
if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL)
{
ZFREE(z, s->hufts);
ZFREE(z, s);
return Z_NULL;
}
s->end = s->window + w;
s->checkfn = c;
s->mode = IBM_TYPE;
LuTracev((stderr, "inflate: blocks allocated\n"));
inflate_blocks_reset(s, z, Z_NULL);
return s;
}
int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r)
{
uInt t; // temporary storage
uLong b; // bit buffer
uInt k; // bits in bit buffer
Byte *p; // input data pointer
uInt n; // bytes available there
Byte *q; // output window write pointer
uInt m; // bytes to end of window or read pointer
// copy input/output information to locals (UPDATE macro restores)
LOAD
// process input based on current state
for(;;) switch (s->mode)
{
case IBM_TYPE:
NEEDBITS(3)
t = (uInt)b & 7;
s->last = t & 1;
switch (t >> 1)
{
case 0: // stored
LuTracev((stderr, "inflate: stored block%s\n",
s->last ? " (last)" : ""));
DUMPBITS(3)
t = k & 7; // go to byte boundary
DUMPBITS(t)
s->mode = IBM_LENS; // get length of stored block
break;
case 1: // fixed
LuTracev((stderr, "inflate: fixed codes block%s\n",
s->last ? " (last)" : ""));
{
uInt bl, bd;
const inflate_huft *tl, *td;
inflate_trees_fixed(&bl, &bd, &tl, &td, z);
s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
if (s->sub.decode.codes == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
}
DUMPBITS(3)
s->mode = IBM_CODES;
break;
case 2: // dynamic
LuTracev((stderr, "inflate: dynamic codes block%s\n",
s->last ? " (last)" : ""));
DUMPBITS(3)
s->mode = IBM_TABLE;
break;
case 3: // illegal
DUMPBITS(3)
s->mode = IBM_BAD;
z->msg = (char*)"invalid block type";
r = Z_DATA_ERROR;
LEAVE
}
break;
case IBM_LENS:
NEEDBITS(32)
if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
{
s->mode = IBM_BAD;
z->msg = (char*)"invalid stored block lengths";
r = Z_DATA_ERROR;
LEAVE
}
s->sub.left = (uInt)b & 0xffff;
b = k = 0; // dump bits
LuTracev((stderr, "inflate: stored length %u\n", s->sub.left));
s->mode = s->sub.left ? IBM_STORED : (s->last ? IBM_DRY : IBM_TYPE);
break;
case IBM_STORED:
if (n == 0)
LEAVE
NEEDOUT
t = s->sub.left;
if (t > n) t = n;
if (t > m) t = m;
memcpy(q, p, t);
p += t; n -= t;
q += t; m -= t;
if ((s->sub.left -= t) != 0)
break;
LuTracev((stderr, "inflate: stored end, %lu total out\n",
z->total_out + (q >= s->read ? q - s->read :
(s->end - s->read) + (q - s->window))));
s->mode = s->last ? IBM_DRY : IBM_TYPE;
break;
case IBM_TABLE:
NEEDBITS(14)
s->sub.trees.table = t = (uInt)b & 0x3fff;
// remove this section to workaround bug in pkzip
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
{
s->mode = IBM_BAD;
z->msg = (char*)"too many length or distance symbols";
r = Z_DATA_ERROR;
LEAVE
}
// end remove
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
DUMPBITS(14)
s->sub.trees.index = 0;
LuTracev((stderr, "inflate: table sizes ok\n"));
s->mode = IBM_BTREE;
case IBM_BTREE:
while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
{
NEEDBITS(3)
s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
DUMPBITS(3)
}
while (s->sub.trees.index < 19)
s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
s->sub.trees.bb = 7;
t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
&s->sub.trees.tb, s->hufts, z);
if (t != Z_OK)
{
r = t;
if (r == Z_DATA_ERROR)
{
ZFREE(z, s->sub.trees.blens);
s->mode = IBM_BAD;
}
LEAVE
}
s->sub.trees.index = 0;
LuTracev((stderr, "inflate: bits tree ok\n"));
s->mode = IBM_DTREE;
case IBM_DTREE:
while (t = s->sub.trees.table,
s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
{
inflate_huft *h;
uInt i, j, c;
t = s->sub.trees.bb;
NEEDBITS(t)
h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
t = h->bits;
c = h->base;
if (c < 16)
{
DUMPBITS(t)
s->sub.trees.blens[s->sub.trees.index++] = c;
}
else // c == 16..18
{
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
NEEDBITS(t + i)
DUMPBITS(t)
j += (uInt)b & inflate_mask[i];
DUMPBITS(i)
i = s->sub.trees.index;
t = s->sub.trees.table;
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
(c == 16 && i < 1))
{
ZFREE(z, s->sub.trees.blens);
s->mode = IBM_BAD;
z->msg = (char*)"invalid bit length repeat";
r = Z_DATA_ERROR;
LEAVE
}
c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
do {
s->sub.trees.blens[i++] = c;
} while (--j);
s->sub.trees.index = i;
}
}
s->sub.trees.tb = Z_NULL;
{
uInt bl, bd;
inflate_huft *tl, *td;
inflate_codes_statef *c;
bl = 9; // must be <= 9 for lookahead assumptions
bd = 6; // must be <= 9 for lookahead assumptions
t = s->sub.trees.table;
t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
s->sub.trees.blens, &bl, &bd, &tl, &td,
s->hufts, z);
if (t != Z_OK)
{
if (t == (uInt)Z_DATA_ERROR)
{
ZFREE(z, s->sub.trees.blens);
s->mode = IBM_BAD;
}
r = t;
LEAVE
}
LuTracev((stderr, "inflate: trees ok\n"));
if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
s->sub.decode.codes = c;
}
ZFREE(z, s->sub.trees.blens);
s->mode = IBM_CODES;
case IBM_CODES:
UPDATE
if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
return inflate_flush(s, z, r);
r = Z_OK;
inflate_codes_free(s->sub.decode.codes, z);
LOAD
LuTracev((stderr, "inflate: codes end, %lu total out\n",
z->total_out + (q >= s->read ? q - s->read :
(s->end - s->read) + (q - s->window))));
if (!s->last)
{
s->mode = IBM_TYPE;
break;
}
s->mode = IBM_DRY;
case IBM_DRY:
FLUSH
if (s->read != s->write)
LEAVE
s->mode = IBM_DONE;
case IBM_DONE:
r = Z_STREAM_END;
LEAVE
case IBM_BAD:
r = Z_DATA_ERROR;
LEAVE
default:
r = Z_STREAM_ERROR;
LEAVE
}
}
int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z)
{
inflate_blocks_reset(s, z, Z_NULL);
ZFREE(z, s->window);
ZFREE(z, s->hufts);
ZFREE(z, s);
LuTracev((stderr, "inflate: blocks freed\n"));
return Z_OK;
}
// inftrees.c -- generate Huffman trees for efficient decoding
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
//
extern const char inflate_copyright[] =
" inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
// If you use the zlib library in a product, an acknowledgment is welcome
// in the documentation of your product. If for some reason you cannot
// include such an acknowledgment, I would appreciate that you keep this
// copyright string in the executable of your product.
int huft_build (
uInt *, // code lengths in bits
uInt, // number of codes
uInt, // number of "simple" codes
const uInt *, // list of base values for non-simple codes
const uInt *, // list of extra bits for non-simple codes
inflate_huft **,// result: starting table
uInt *, // maximum lookup bits (returns actual)
inflate_huft *, // space for trees
uInt *, // hufts used in space
uInt * ); // space for values
// Tables for deflate from PKZIP's appnote.txt.
const uInt cplens[31] = { // Copy lengths for literal codes 257..285
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
// see note #13 above about 258
const uInt cplext[31] = { // Extra bits for literal codes 257..285
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; // 112==invalid
const uInt cpdist[30] = { // Copy offsets for distance codes 0..29
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577};
const uInt cpdext[30] = { // Extra bits for distance codes
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
//
// Huffman code decoding is performed using a multi-level table lookup.
// The fastest way to decode is to simply build a lookup table whose
// size is determined by the longest code. However, the time it takes
// to build this table can also be a factor if the data being decoded
// is not very long. The most common codes are necessarily the
// shortest codes, so those codes dominate the decoding time, and hence
// the speed. The idea is you can have a shorter table that decodes the
// shorter, more probable codes, and then point to subsidiary tables for
// the longer codes. The time it costs to decode the longer codes is
// then traded against the time it takes to make longer tables.
//
// This results of this trade are in the variables lbits and dbits
// below. lbits is the number of bits the first level table for literal/
// length codes can decode in one step, and dbits is the same thing for
// the distance codes. Subsequent tables are also less than or equal to
// those sizes. These values may be adjusted either when all of the
// codes are shorter than that, in which case the longest code length in
// bits is used, or when the shortest code is *longer* than the requested
// table size, in which case the length of the shortest code in bits is
// used.
//
// There are two different values for the two tables, since they code a
// different number of possibilities each. The literal/length table
// codes 286 possible values, or in a flat code, a little over eight
// bits. The distance table codes 30 possible values, or a little less
// than five bits, flat. The optimum values for speed end up being
// about one bit more than those, so lbits is 8+1 and dbits is 5+1.
// The optimum values may differ though from machine to machine, and
// possibly even between compilers. Your mileage may vary.
//
// If BMAX needs to be larger than 16, then h and x[] should be uLong.
#define BMAX 15 // maximum bit length of any code
int huft_build(
uInt *b, // code lengths in bits (all assumed <= BMAX)
uInt n, // number of codes (assumed <= 288)
uInt s, // number of simple-valued codes (0..s-1)
const uInt *d, // list of base values for non-simple codes
const uInt *e, // list of extra bits for non-simple codes
inflate_huft * *t, // result: starting table
uInt *m, // maximum lookup bits, returns actual
inflate_huft *hp, // space for trees
uInt *hn, // hufts used in space
uInt *v) // working area: values in order of bit length
// Given a list of code lengths and a maximum table size, make a set of
// tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
// if the given code set is incomplete (the tables are still built in this
// case), or Z_DATA_ERROR if the input is invalid.
{
uInt a; // counter for codes of length k
uInt c[BMAX+1]; // bit length count table
uInt f; // i repeats in table every f entries
int g; // maximum code length
int h; // table level
register uInt i; // counter, current code
register uInt j; // counter
register int k; // number of bits in current code
int l; // bits per table (returned in m)
uInt mask; // (1 << w) - 1, to avoid cc -O bug on HP
register uInt *p; // pointer into c[], b[], or v[]
inflate_huft *q; // points to current table
struct inflate_huft_s r; // table entry for structure assignment
inflate_huft *u[BMAX]; // table stack
register int w; // bits before this table == (l * h)
uInt x[BMAX+1]; // bit offsets, then code stack
uInt *xp; // pointer into x
int y; // number of dummy codes added
uInt z; // number of entries in current table
// Generate counts for each bit length
p = c;
#define C0 *p++ = 0;
#define C2 C0 C0 C0 C0
#define C4 C2 C2 C2 C2
C4; p; // clear c[]--assume BMAX+1 is 16
p = b; i = n;
do {
c[*p++]++; // assume all entries <= BMAX
} while (--i);
if (c[0] == n) // null input--all zero length codes
{
*t = (inflate_huft *)Z_NULL;
*m = 0;
return Z_OK;
}
// Find minimum and maximum length, bound *m by those
l = *m;
for (j = 1; j <= BMAX; j++)
if (c[j])
break;
k = j; // minimum code length
if ((uInt)l < j)
l = j;
for (i = BMAX; i; i--)
if (c[i])
break;
g = i; // maximum code length
if ((uInt)l > i)
l = i;
*m = l;
// Adjust last length count to fill out codes, if needed
for (y = 1 << j; j < i; j++, y <<= 1)
if ((y -= c[j]) < 0)
return Z_DATA_ERROR;
if ((y -= c[i]) < 0)
return Z_DATA_ERROR;
c[i] += y;
// Generate starting offsets into the value table for each length
x[1] = j = 0;
p = c + 1; xp = x + 2;
while (--i) { // note that i == g from above
*xp++ = (j += *p++);
}
// Make a table of values in order of bit lengths
p = b; i = 0;
do {
if ((j = *p++) != 0)
v[x[j]++] = i;
} while (++i < n);
n = x[g]; // set n to length of v
// Generate the Huffman codes and for each, make the table entries
x[0] = i = 0; // first Huffman code is zero
p = v; // grab values in bit order
h = -1; // no tables yet--level -1
w = -l; // bits decoded == (l * h)
u[0] = (inflate_huft *)Z_NULL; // just to keep compilers happy
q = (inflate_huft *)Z_NULL; // ditto
z = 0; // ditto
// go through the bit lengths (k already is bits in shortest code)
for (; k <= g; k++)
{
a = c[k];
while (a--)
{
// here i is the Huffman code of length k bits for value *p
// make tables up to required level
while (k > w + l)
{
h++;
w += l; // previous table always l bits
// compute minimum size table less than or equal to l bits
z = g - w;
z = z > (uInt)l ? l : z; // table size upper limit
if ((f = 1 << (j = k - w)) > a + 1) // try a k-w bit table
{ // too few codes for k-w bit table
f -= a + 1; // deduct codes from patterns left
xp = c + k;
if (j < z)
while (++j < z) // try smaller tables up to z bits
{
if ((f <<= 1) <= *++xp)
break; // enough codes to use up j bits
f -= *xp; // else deduct codes from patterns
}
}
z = 1 << j; // table entries for j-bit table
// allocate new table
if (*hn + z > MANY) // (note: doesn't matter for fixed)
return Z_DATA_ERROR; // overflow of MANY
u[h] = q = hp + *hn;
*hn += z;
// connect to last table, if there is one
if (h)
{
x[h] = i; // save pattern for backing up
r.bits = (Byte)l; // bits to dump before this table
r.exop = (Byte)j; // bits in this table
j = i >> (w - l);
r.base = (uInt)(q - u[h-1] - j); // offset to this table
u[h-1][j] = r; // connect to last table
}
else
*t = q; // first table is returned result
}
// set up table entry in r
r.bits = (Byte)(k - w);
if (p >= v + n)
r.exop = 128 + 64; // out of values--invalid code
else if (*p < s)
{
r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); // 256 is end-of-block
r.base = *p++; // simple code is just the value
}
else
{
r.exop = (Byte)(e[*p - s] + 16 + 64);// non-simple--look up in lists
r.base = d[*p++ - s];
}
// fill code-like entries with r
f = 1 << (k - w);
for (j = i >> w; j < z; j += f)
q[j] = r;
// backwards increment the k-bit code i
for (j = 1 << (k - 1); i & j; j >>= 1)
i ^= j;
i ^= j;
// backup over finished tables
mask = (1 << w) - 1; // needed on HP, cc -O bug
while ((i & mask) != x[h])
{
h--; // don't need to update q
w -= l;
mask = (1 << w) - 1;
}
}
}
// Return Z_BUF_ERROR if we were given an incomplete table
return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
}
int inflate_trees_bits(
uInt *c, // 19 code lengths
uInt *bb, // bits tree desired/actual depth
inflate_huft * *tb, // bits tree result
inflate_huft *hp, // space for trees
z_streamp z) // for messages
{
int r;
uInt hn = 0; // hufts used in space
uInt *v; // work area for huft_build
if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
return Z_MEM_ERROR;
r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL,
tb, bb, hp, &hn, v);
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed dynamic bit lengths tree";
else if (r == Z_BUF_ERROR || *bb == 0)
{
z->msg = (char*)"incomplete dynamic bit lengths tree";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
}
int inflate_trees_dynamic(
uInt nl, // number of literal/length codes
uInt nd, // number of distance codes
uInt *c, // that many (total) code lengths
uInt *bl, // literal desired/actual bit depth
uInt *bd, // distance desired/actual bit depth
inflate_huft * *tl, // literal/length tree result
inflate_huft * *td, // distance tree result
inflate_huft *hp, // space for trees
z_streamp z) // for messages
{
int r;
uInt hn = 0; // hufts used in space
uInt *v; // work area for huft_build
// allocate work area
if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
return Z_MEM_ERROR;
// build literal/length tree
r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
if (r != Z_OK || *bl == 0)
{
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed literal/length tree";
else if (r != Z_MEM_ERROR)
{
z->msg = (char*)"incomplete literal/length tree";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
}
// build distance tree
r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
if (r != Z_OK || (*bd == 0 && nl > 257))
{
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed distance tree";
else if (r == Z_BUF_ERROR) {
z->msg = (char*)"incomplete distance tree";
r = Z_DATA_ERROR;
}
else if (r != Z_MEM_ERROR)
{
z->msg = (char*)"empty distance tree with lengths";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
}
// done
ZFREE(z, v);
return Z_OK;
}
int inflate_trees_fixed(
uInt *bl, // literal desired/actual bit depth
uInt *bd, // distance desired/actual bit depth
const inflate_huft * * tl, // literal/length tree result
const inflate_huft * *td, // distance tree result
z_streamp ) // for memory allocation
{
*bl = fixed_bl;
*bd = fixed_bd;
*tl = fixed_tl;
*td = fixed_td;
return Z_OK;
}
// inffast.c -- process literals and length/distance pairs fast
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
//
//struct inflate_codes_state {int dummy;}; // for buggy compilers
// macros for bit input with no checking and for returning unused bytes
#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
#define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;}
// Called with number of bytes left to write in window at least 258
// (the maximum string length) and number of input bytes available
// at least ten. The ten bytes are six bytes for the longest length/
// distance pair plus four bytes for overloading the bit buffer.
int inflate_fast(
uInt bl, uInt bd,
const inflate_huft *tl,
const inflate_huft *td, // need separate declaration for Borland C++
inflate_blocks_statef *s,
z_streamp z)
{
const inflate_huft *t; // temporary pointer
uInt e; // extra bits or operation
uLong b; // bit buffer
uInt k; // bits in bit buffer
Byte *p; // input data pointer
uInt n; // bytes available there
Byte *q; // output window write pointer
uInt m; // bytes to end of window or read pointer
uInt ml; // mask for literal/length tree
uInt md; // mask for distance tree
uInt c; // bytes to copy
uInt d; // distance back to copy from
Byte *r; // copy source pointer
// load input, output, bit values
LOAD
// initialize masks
ml = inflate_mask[bl];
md = inflate_mask[bd];
// do until not enough input or output space for fast loop
do { // assume called with m >= 258 && n >= 10
// get literal/length code
GRABBITS(20) // max bits for literal/length code
if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
{
DUMPBITS(t->bits)
LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
"inflate: * literal '%c'\n" :
"inflate: * literal 0x%02x\n", t->base));
*q++ = (Byte)t->base;
m--;
continue;
}
for (;;) {
DUMPBITS(t->bits)
if (e & 16)
{
// get extra bits for length
e &= 15;
c = t->base + ((uInt)b & inflate_mask[e]);
DUMPBITS(e)
LuTracevv((stderr, "inflate: * length %u\n", c));
// decode distance base of block to copy
GRABBITS(15); // max bits for distance code
e = (t = td + ((uInt)b & md))->exop;
for (;;) {
DUMPBITS(t->bits)
if (e & 16)
{
// get extra bits to add to distance base
e &= 15;
GRABBITS(e) // get extra bits (up to 13)
d = t->base + ((uInt)b & inflate_mask[e]);
DUMPBITS(e)
LuTracevv((stderr, "inflate: * distance %u\n", d));
// do the copy
m -= c;
r = q - d;
if (r < s->window) // wrap if needed
{
do {
r += s->end - s->window; // force pointer in window
} while (r < s->window); // covers invalid distances
e = (uInt) (s->end - r);
if (c > e)
{
c -= e; // wrapped copy
do {
*q++ = *r++;
} while (--e);
r = s->window;
do {
*q++ = *r++;
} while (--c);
}
else // normal copy
{
*q++ = *r++; c--;
*q++ = *r++; c--;
do {
*q++ = *r++;
} while (--c);
}
}
else /* normal copy */
{
*q++ = *r++; c--;
*q++ = *r++; c--;
do {
*q++ = *r++;
} while (--c);
}
break;
}
else if ((e & 64) == 0)
{
t += t->base;
e = (t += ((uInt)b & inflate_mask[e]))->exop;
}
else
{
z->msg = (char*)"invalid distance code";
UNGRAB
UPDATE
return Z_DATA_ERROR;
}
};
break;
}
if ((e & 64) == 0)
{
t += t->base;
if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0)
{
DUMPBITS(t->bits)
LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
"inflate: * literal '%c'\n" :
"inflate: * literal 0x%02x\n", t->base));
*q++ = (Byte)t->base;
m--;
break;
}
}
else if (e & 32)
{
LuTracevv((stderr, "inflate: * end of block\n"));
UNGRAB
UPDATE
return Z_STREAM_END;
}
else
{
z->msg = (char*)"invalid literal/length code";
UNGRAB
UPDATE
return Z_DATA_ERROR;
}
};
} while (m >= 258 && n >= 10);
// not enough input or output--restore pointers and return
UNGRAB
UPDATE
return Z_OK;
}
// crc32.c -- compute the CRC-32 of a data stream
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
// @(#) $Id$
// Table of CRC-32's of all single-byte values (made by make_crc_table)
const uLong crc_table[256] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
0x2d02ef8dL
};
const uLong * get_crc_table()
{ return (const uLong *)crc_table;
}
#define CRC_DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8);
#define CRC_DO2(buf) CRC_DO1(buf); CRC_DO1(buf);
#define CRC_DO4(buf) CRC_DO2(buf); CRC_DO2(buf);
#define CRC_DO8(buf) CRC_DO4(buf); CRC_DO4(buf);
uLong ucrc32(uLong crc, const Byte *buf, uInt len)
{ if (buf == Z_NULL) return 0L;
crc = crc ^ 0xffffffffL;
while (len >= 8) {CRC_DO8(buf); len -= 8;}
if (len) do {CRC_DO1(buf);} while (--len);
return crc ^ 0xffffffffL;
}
// =============================================================
// some decryption routines
#define CRC32(c, b) (crc_table[((int)(c)^(b))&0xff]^((c)>>8))
void Uupdate_keys(unsigned long *keys, char c)
{ keys[0] = CRC32(keys[0],c);
keys[1] += keys[0] & 0xFF;
keys[1] = keys[1]*134775813L +1;
keys[2] = CRC32(keys[2], keys[1] >> 24);
}
char Udecrypt_byte(unsigned long *keys)
{ unsigned temp = ((unsigned)keys[2] & 0xffff) | 2;
return (char)(((temp * (temp ^ 1)) >> 8) & 0xff);
}
char zdecode(unsigned long *keys, char c)
{ c^=Udecrypt_byte(keys);
Uupdate_keys(keys,c);
return c;
}
// adler32.c -- compute the Adler-32 checksum of a data stream
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
// @(#) $Id$
#define BASE 65521L // largest prime smaller than 65536
#define NMAX 5552
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
#define AD_DO1(buf,i) {s1 += buf[i]; s2 += s1;}
#define AD_DO2(buf,i) AD_DO1(buf,i); AD_DO1(buf,i+1);
#define AD_DO4(buf,i) AD_DO2(buf,i); AD_DO2(buf,i+2);
#define AD_DO8(buf,i) AD_DO4(buf,i); AD_DO4(buf,i+4);
#define AD_DO16(buf) AD_DO8(buf,0); AD_DO8(buf,8);
// =========================================================================
uLong adler32(uLong adler, const Byte *buf, uInt len)
{
unsigned long s1 = adler & 0xffff;
unsigned long s2 = (adler >> 16) & 0xffff;
int k;
if (buf == Z_NULL) return 1L;
while (len > 0) {
k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16) {
AD_DO16(buf);
buf += 16;
k -= 16;
}
if (k != 0) do {
s1 += *buf++;
s2 += s1;
} while (--k);
s1 %= BASE;
s2 %= BASE;
}
return (s2 << 16) | s1;
}
// zutil.c -- target dependent utility functions for the compression library
// Copyright (C) 1995-1998 Jean-loup Gailly.
// For conditions of distribution and use, see copyright notice in zlib.h
// @(#) $Id$
const char * zlibVersion()
{
return ZLIB_VERSION;
}
// exported to allow conversion of error code to string for compress() and
// uncompress()
const char * zError(int err)
{ return ERR_MSG(err);
}
voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
{
if (opaque) items += size - size; // make compiler happy
return (voidpf)calloc(items, size);
}
void zcfree (voidpf opaque, voidpf ptr)
{
zfree(ptr);
if (opaque) return; // make compiler happy
}
// inflate.c -- zlib interface to inflate modules
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
//struct inflate_blocks_state {int dummy;}; // for buggy compilers
typedef enum {
IM_METHOD, // waiting for method byte
IM_FLAG, // waiting for flag byte
IM_DICT4, // four dictionary check bytes to go
IM_DICT3, // three dictionary check bytes to go
IM_DICT2, // two dictionary check bytes to go
IM_DICT1, // one dictionary check byte to go
IM_DICT0, // waiting for inflateSetDictionary
IM_BLOCKS, // decompressing blocks
IM_CHECK4, // four check bytes to go
IM_CHECK3, // three check bytes to go
IM_CHECK2, // two check bytes to go
IM_CHECK1, // one check byte to go
IM_DONE, // finished check, done
IM_BAD} // got an error--stay here
inflate_mode;
// inflate private state
struct internal_state {
// mode
inflate_mode mode; // current inflate mode
// mode dependent information
union {
uInt method; // if IM_FLAGS, method byte
struct {
uLong was; // computed check value
uLong need; // stream check value
} check; // if CHECK, check values to compare
uInt marker; // if IM_BAD, inflateSync's marker bytes count
} sub; // submode
// mode independent information
int nowrap; // flag for no wrapper
uInt wbits; // log2(window size) (8..15, defaults to 15)
inflate_blocks_statef
*blocks; // current inflate_blocks state
};
int inflateReset(z_streamp z)
{
if (z == Z_NULL || z->state == Z_NULL)
return Z_STREAM_ERROR;
z->total_in = z->total_out = 0;
z->msg = Z_NULL;
z->state->mode = z->state->nowrap ? IM_BLOCKS : IM_METHOD;
inflate_blocks_reset(z->state->blocks, z, Z_NULL);
LuTracev((stderr, "inflate: reset\n"));
return Z_OK;
}
int inflateEnd(z_streamp z)
{
if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
return Z_STREAM_ERROR;
if (z->state->blocks != Z_NULL)
inflate_blocks_free(z->state->blocks, z);
ZFREE(z, z->state);
z->state = Z_NULL;
LuTracev((stderr, "inflate: end\n"));
return Z_OK;
}
int inflateInit2(z_streamp z)
{ const char *version = ZLIB_VERSION; int stream_size = sizeof(z_stream);
if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != sizeof(z_stream)) return Z_VERSION_ERROR;
int w = -15; // MAX_WBITS: 32K LZ77 window.
// Warning: reducing MAX_WBITS makes minigzip unable to extract .gz files created by gzip.
// The memory requirements for deflate are (in bytes):
// (1 << (windowBits+2)) + (1 << (memLevel+9))
// that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
// plus a few kilobytes for small objects. For example, if you want to reduce
// the default memory requirements from 256K to 128K, compile with
// make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
// Of course this will generally degrade compression (there's no free lunch).
//
// The memory requirements for inflate are (in bytes) 1 << windowBits
// that is, 32K for windowBits=15 (default value) plus a few kilobytes
// for small objects.
// initialize state
if (z == Z_NULL) return Z_STREAM_ERROR;
z->msg = Z_NULL;
if (z->zalloc == Z_NULL)
{
z->zalloc = zcalloc;
z->opaque = (voidpf)0;
}
if (z->zfree == Z_NULL) z->zfree = zcfree;
if ((z->state = (struct internal_state *)
ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
return Z_MEM_ERROR;
z->state->blocks = Z_NULL;
// handle undocumented nowrap option (no zlib header or check)
z->state->nowrap = 0;
if (w < 0)
{
w = - w;
z->state->nowrap = 1;
}
// set window size
if (w < 8 || w > 15)
{
inflateEnd(z);
return Z_STREAM_ERROR;
}
z->state->wbits = (uInt)w;
// create inflate_blocks state
if ((z->state->blocks =
inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
== Z_NULL)
{
inflateEnd(z);
return Z_MEM_ERROR;
}
LuTracev((stderr, "inflate: allocated\n"));
// reset state
inflateReset(z);
return Z_OK;
}
#define IM_NEEDBYTE {if(z->avail_in==0)return r;r=f;}
#define IM_NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
int inflate(z_streamp z, int f)
{
int r;
uInt b;
if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL)
return Z_STREAM_ERROR;
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
for (;;) switch (z->state->mode)
{
case IM_METHOD:
IM_NEEDBYTE
if (((z->state->sub.method = IM_NEXTBYTE) & 0xf) != Z_DEFLATED)
{
z->state->mode = IM_BAD;
z->msg = (char*)"unknown compression method";
z->state->sub.marker = 5; // can't try inflateSync
break;
}
if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
{
z->state->mode = IM_BAD;
z->msg = (char*)"invalid window size";
z->state->sub.marker = 5; // can't try inflateSync
break;
}
z->state->mode = IM_FLAG;
case IM_FLAG:
IM_NEEDBYTE
b = IM_NEXTBYTE;
if (((z->state->sub.method << 8) + b) % 31)
{
z->state->mode = IM_BAD;
z->msg = (char*)"incorrect header check";
z->state->sub.marker = 5; // can't try inflateSync
break;
}
LuTracev((stderr, "inflate: zlib header ok\n"));
if (!(b & PRESET_DICT))
{
z->state->mode = IM_BLOCKS;
break;
}
z->state->mode = IM_DICT4;
case IM_DICT4:
IM_NEEDBYTE
z->state->sub.check.need = (uLong)IM_NEXTBYTE << 24;
z->state->mode = IM_DICT3;
case IM_DICT3:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE << 16;
z->state->mode = IM_DICT2;
case IM_DICT2:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE << 8;
z->state->mode = IM_DICT1;
case IM_DICT1:
IM_NEEDBYTE; r;
z->state->sub.check.need += (uLong)IM_NEXTBYTE;
z->adler = z->state->sub.check.need;
z->state->mode = IM_DICT0;
return Z_NEED_DICT;
case IM_DICT0:
z->state->mode = IM_BAD;
z->msg = (char*)"need dictionary";
z->state->sub.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
case IM_BLOCKS:
r = inflate_blocks(z->state->blocks, z, r);
if (r == Z_DATA_ERROR)
{
z->state->mode = IM_BAD;
z->state->sub.marker = 0; // can try inflateSync
break;
}
if (r == Z_OK)
r = f;
if (r != Z_STREAM_END)
return r;
r = f;
inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
if (z->state->nowrap)
{
z->state->mode = IM_DONE;
break;
}
z->state->mode = IM_CHECK4;
case IM_CHECK4:
IM_NEEDBYTE
z->state->sub.check.need = (uLong)IM_NEXTBYTE << 24;
z->state->mode = IM_CHECK3;
case IM_CHECK3:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE << 16;
z->state->mode = IM_CHECK2;
case IM_CHECK2:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE << 8;
z->state->mode = IM_CHECK1;
case IM_CHECK1:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE;
if (z->state->sub.check.was != z->state->sub.check.need)
{
z->state->mode = IM_BAD;
z->msg = (char*)"incorrect data check";
z->state->sub.marker = 5; // can't try inflateSync
break;
}
LuTracev((stderr, "inflate: zlib check ok\n"));
z->state->mode = IM_DONE;
case IM_DONE:
return Z_STREAM_END;
case IM_BAD:
return Z_DATA_ERROR;
default:
return Z_STREAM_ERROR;
}
}
// unzip.c -- IO on .zip files using zlib
// Version 0.15 beta, Mar 19th, 1998,
// Read unzip.h for more info
#define UNZ_BUFSIZE (16384)
#define UNZ_MAXFILENAMEINZIP (256)
#define SIZECENTRALDIRITEM (0x2e)
#define SIZEZIPLOCALHEADER (0x1e)
const char unz_copyright[] = " unzip 0.15 Copyright 1998 Gilles Vollant ";
// unz_file_info_interntal contain internal info about a file in zipfile
typedef struct unz_file_info_internal_s
{
uLong offset_curfile;// relative offset of local header 4 bytes
} unz_file_info_internal;
typedef struct
{ bool is_handle; // either a handle or memory
bool canseek;
// for handles:
HANDLE h; bool herr; unsigned long initial_offset; bool mustclosehandle;
// for memory:
void *buf; unsigned int len,pos; // if it's a memory block
} LUFILE;
LUFILE *lufopen(void *z,unsigned int len,DWORD flags,ZRESULT *err)
{ if (flags!=ZIP_HANDLE && flags!=ZIP_FILENAME && flags!=ZIP_MEMORY) {*err=ZR_ARGS; return NULL;}
//
HANDLE h=0; bool canseek=false; *err=ZR_OK;
bool mustclosehandle=false;
if (flags==ZIP_HANDLE||flags==ZIP_FILENAME)
{ if (flags==ZIP_HANDLE)
{ HANDLE hf = z;
h=hf; mustclosehandle=false;
#ifdef DuplicateHandle
BOOL res = DuplicateHandle(GetCurrentProcess(),hf,GetCurrentProcess(),&h,0,FALSE,DUPLICATE_SAME_ACCESS);
if (!res) mustclosehandle=true;
#endif
}
else
{ h=CreateFile((const TCHAR*)z,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (h==INVALID_HANDLE_VALUE) {*err=ZR_NOFILE; return NULL;}
mustclosehandle=true;
}
// test if we can seek on it. We can't use GetFileType(h)==FILE_TYPE_DISK since it's not on CE.
DWORD res = SetFilePointer(h,0,0,FILE_CURRENT);
canseek = (res!=0xFFFFFFFF);
}
LUFILE *lf = new LUFILE;
if (flags==ZIP_HANDLE||flags==ZIP_FILENAME)
{ lf->is_handle=true; lf->mustclosehandle=mustclosehandle;
lf->canseek=canseek;
lf->h=h; lf->herr=false;
lf->initial_offset=0;
if (canseek) lf->initial_offset = SetFilePointer(h,0,NULL,FILE_CURRENT);
}
else
{ lf->is_handle=false;
lf->canseek=true;
lf->mustclosehandle=false;
lf->buf=z; lf->len=len; lf->pos=0; lf->initial_offset=0;
}
*err=ZR_OK;
return lf;
}
int lufclose(LUFILE *stream)
{ if (stream==NULL) return EOF;
if (stream->mustclosehandle) CloseHandle(stream->h);
delete stream;
return 0;
}
int luferror(LUFILE *stream)
{ if (stream->is_handle && stream->herr) return 1;
else return 0;
}
long int luftell(LUFILE *stream)
{ if (stream->is_handle && stream->canseek) return SetFilePointer(stream->h,0,NULL,FILE_CURRENT)-stream->initial_offset;
else if (stream->is_handle) return 0;
else return stream->pos;
}
int lufseek(LUFILE *stream, long offset, int whence)
{ if (stream->is_handle && stream->canseek)
{ if (whence==SEEK_SET) SetFilePointer(stream->h,stream->initial_offset+offset,0,FILE_BEGIN);
else if (whence==SEEK_CUR) SetFilePointer(stream->h,offset,NULL,FILE_CURRENT);
else if (whence==SEEK_END) SetFilePointer(stream->h,offset,NULL,FILE_END);
else return 19; // EINVAL
return 0;
}
else if (stream->is_handle) return 29; // ESPIPE
else
{ if (whence==SEEK_SET) stream->pos=offset;
else if (whence==SEEK_CUR) stream->pos+=offset;
else if (whence==SEEK_END) stream->pos=stream->len+offset;
return 0;
}
}
size_t lufread(void *ptr,size_t size,size_t n,LUFILE *stream)
{ unsigned int toread = (unsigned int)(size*n);
if (stream->is_handle)
{ DWORD red; BOOL res = ReadFile(stream->h,ptr,toread,&red,NULL);
if (!res) stream->herr=true;
return red/size;
}
if (stream->pos+toread > stream->len) toread = stream->len-stream->pos;
memcpy(ptr, (char*)stream->buf + stream->pos, toread); DWORD red = toread;
stream->pos += red;
return red/size;
}
// file_in_zip_read_info_s contain internal information about a file in zipfile,
// when reading and decompress it
typedef struct
{
char *read_buffer; // internal buffer for compressed data
z_stream stream; // zLib stream structure for inflate
uLong pos_in_zipfile; // position in byte on the zipfile, for fseek
uLong stream_initialised; // flag set if stream structure is initialised
uLong offset_local_extrafield;// offset of the local extra field
uInt size_local_extrafield;// size of the local extra field
uLong pos_local_extrafield; // position in the local extra field in read
uLong crc32; // crc32 of all data uncompressed
uLong crc32_wait; // crc32 we must obtain after decompress all
uLong rest_read_compressed; // number of byte to be decompressed
uLong rest_read_uncompressed;//number of byte to be obtained after decomp
LUFILE* file; // io structore of the zipfile
uLong compression_method; // compression method (0==store)
uLong byte_before_the_zipfile;// byte before the zipfile, (>0 for sfx)
bool encrypted; // is it encrypted?
unsigned long keys[3]; // decryption keys, initialized by unzOpenCurrentFile
int encheadleft; // the first call(s) to unzReadCurrentFile will read this many encryption-header bytes first
char crcenctest; // if encrypted, we'll check the encryption buffer against this
} file_in_zip_read_info_s;
// unz_s contain internal information about the zipfile
typedef struct
{
LUFILE* file; // io structore of the zipfile
unz_global_info gi; // public global information
uLong byte_before_the_zipfile;// byte before the zipfile, (>0 for sfx)
uLong num_file; // number of the current file in the zipfile
uLong pos_in_central_dir; // pos of the current file in the central dir
uLong current_file_ok; // flag about the usability of the current file
uLong central_pos; // position of the beginning of the central dir
uLong size_central_dir; // size of the central directory
uLong offset_central_dir; // offset of start of central directory with respect to the starting disk number
unz_file_info cur_file_info; // public info about the current file in zip
unz_file_info_internal cur_file_info_internal; // private info about it
file_in_zip_read_info_s* pfile_in_zip_read; // structure about the current file if we are decompressing it
} unz_s, *unzFile;
int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity);
// Compare two filename (fileName1,fileName2).
z_off_t unztell (unzFile file);
// Give the current position in uncompressed data
int unzeof (unzFile file);
// return 1 if the end of file was reached, 0 elsewhere
int unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len);
// Read extra field from the current file (opened by unzOpenCurrentFile)
// This is the local-header version of the extra field (sometimes, there is
// more info in the local-header version than in the central-header)
//
// if buf==NULL, it return the size of the local extra field
//
// if buf!=NULL, len is the size of the buffer, the extra header is copied in
// buf.
// the return value is the number of bytes copied in buf, or (if <0)
// the error code
// ===========================================================================
// Read a byte from a gz_stream; update next_in and avail_in. Return EOF
// for end of file.
// IN assertion: the stream s has been sucessfully opened for reading.
int unzlocal_getByte(LUFILE *fin,int *pi)
{ unsigned char c;
int err = (int)lufread(&c, 1, 1, fin);
if (err==1)
{ *pi = (int)c;
return UNZ_OK;
}
else
{ if (luferror(fin)) return UNZ_ERRNO;
else return UNZ_EOF;
}
}
// ===========================================================================
// Reads a long in LSB order from the given gz_stream. Sets
int unzlocal_getShort (LUFILE *fin,uLong *pX)
{
uLong x ;
int i;
int err;
err = unzlocal_getByte(fin,&i);
x = (uLong)i;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<8;
if (err==UNZ_OK)
*pX = x;
else
*pX = 0;
return err;
}
int unzlocal_getLong (LUFILE *fin,uLong *pX)
{
uLong x ;
int i;
int err;
err = unzlocal_getByte(fin,&i);
x = (uLong)i;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<8;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<16;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<24;
if (err==UNZ_OK)
*pX = x;
else
*pX = 0;
return err;
}
// My own strcmpi / strcasecmp
int strcmpcasenosensitive_internal (const char* fileName1,const char *fileName2)
{
for (;;)
{
char c1=*(fileName1++);
char c2=*(fileName2++);
if ((c1>='a') && (c1<='z'))
c1 -= (char)0x20;
if ((c2>='a') && (c2<='z'))
c2 -= (char)0x20;
if (c1=='\0')
return ((c2=='\0') ? 0 : -1);
if (c2=='\0')
return 1;
if (c1<c2)
return -1;
if (c1>c2)
return 1;
}
}
//
// Compare two filename (fileName1,fileName2).
// If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
// If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi or strcasecmp)
//
int unzStringFileNameCompare (const char*fileName1,const char*fileName2,int iCaseSensitivity)
{ if (iCaseSensitivity==1) return strcmp(fileName1,fileName2);
else return strcmpcasenosensitive_internal(fileName1,fileName2);
}
#define BUFREADCOMMENT (0x400)
// Locate the Central directory of a zipfile (at the end, just before
// the global comment). Lu bugfix 2005.07.26 - returns 0xFFFFFFFF if not found,
// rather than 0, since 0 is a valid central-dir-location for an empty zipfile.
uLong unzlocal_SearchCentralDir(LUFILE *fin)
{ if (lufseek(fin,0,SEEK_END) != 0) return 0xFFFFFFFF;
uLong uSizeFile = luftell(fin);
uLong uMaxBack=0xffff; // maximum size of global comment
if (uMaxBack>uSizeFile) uMaxBack = uSizeFile;
unsigned char *buf = (unsigned char*)zmalloc(BUFREADCOMMENT+4);
if (buf==NULL) return 0xFFFFFFFF;
uLong uPosFound=0xFFFFFFFF;
uLong uBackRead = 4;
while (uBackRead<uMaxBack)
{ uLong uReadSize,uReadPos ;
int i;
if (uBackRead+BUFREADCOMMENT>uMaxBack) uBackRead = uMaxBack;
else uBackRead+=BUFREADCOMMENT;
uReadPos = uSizeFile-uBackRead ;
uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? (BUFREADCOMMENT+4) : (uSizeFile-uReadPos);
if (lufseek(fin,uReadPos,SEEK_SET)!=0) break;
if (lufread(buf,(uInt)uReadSize,1,fin)!=1) break;
for (i=(int)uReadSize-3; (i--)>=0;)
{ if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
{ uPosFound = uReadPos+i; break;
}
}
if (uPosFound!=0) break;
}
if (buf) zfree(buf);
return uPosFound;
}
int unzGoToFirstFile (unzFile file);
int unzCloseCurrentFile (unzFile file);
// Open a Zip file.
// If the zipfile cannot be opened (file don't exist or in not valid), return NULL.
// Otherwise, the return value is a unzFile Handle, usable with other unzip functions
unzFile unzOpenInternal(LUFILE *fin)
{ if (fin==NULL) return NULL;
if (unz_copyright[0]!=' ') {lufclose(fin); return NULL;}
int err=UNZ_OK;
unz_s us;
uLong central_pos,uL;
central_pos = unzlocal_SearchCentralDir(fin);
if (central_pos==0xFFFFFFFF) err=UNZ_ERRNO;
if (lufseek(fin,central_pos,SEEK_SET)!=0) err=UNZ_ERRNO;
// the signature, already checked
if (unzlocal_getLong(fin,&uL)!=UNZ_OK) err=UNZ_ERRNO;
// number of this disk
uLong number_disk; // number of the current dist, used for spanning ZIP, unsupported, always 0
if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK) err=UNZ_ERRNO;
// number of the disk with the start of the central directory
uLong number_disk_with_CD; // number the the disk with central dir, used for spaning ZIP, unsupported, always 0
if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK) err=UNZ_ERRNO;
// total number of entries in the central dir on this disk
if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK) err=UNZ_ERRNO;
// total number of entries in the central dir
uLong number_entry_CD; // total number of entries in the central dir (same than number_entry on nospan)
if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK) err=UNZ_ERRNO;
if ((number_entry_CD!=us.gi.number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=UNZ_BADZIPFILE;
// size of the central directory
if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK) err=UNZ_ERRNO;
// offset of start of central directory with respect to the starting disk number
if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK) err=UNZ_ERRNO;
// zipfile comment length
if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK) err=UNZ_ERRNO;
if ((central_pos+fin->initial_offset<us.offset_central_dir+us.size_central_dir) && (err==UNZ_OK)) err=UNZ_BADZIPFILE;
if (err!=UNZ_OK) {lufclose(fin);return NULL;}
us.file=fin;
us.byte_before_the_zipfile = central_pos+fin->initial_offset - (us.offset_central_dir+us.size_central_dir);
us.central_pos = central_pos;
us.pfile_in_zip_read = NULL;
fin->initial_offset = 0; // since the zipfile itself is expected to handle this
unz_s *s = (unz_s*)zmalloc(sizeof(unz_s));
*s=us;
unzGoToFirstFile((unzFile)s);
return (unzFile)s;
}
// Close a ZipFile opened with unzipOpen.
// If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
// these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
// return UNZ_OK if there is no problem.
int unzClose (unzFile file)
{
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (s->pfile_in_zip_read!=NULL)
unzCloseCurrentFile(file);
lufclose(s->file);
if (s) zfree(s); // unused s=0;
return UNZ_OK;
}
// Write info about the ZipFile in the *pglobal_info structure.
// No preparation of the structure is needed
// return UNZ_OK if there is no problem.
int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info)
{
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
*pglobal_info=s->gi;
return UNZ_OK;
}
// Translate date/time from Dos format to tm_unz (readable more easilty)
void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm)
{
uLong uDate;
uDate = (uLong)(ulDosDate>>16);
ptm->tm_mday = (uInt)(uDate&0x1f) ;
ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ;
ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ;
ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ;
}
// Get Info about the current file in the zipfile, with internal only info
int unzlocal_GetCurrentFileInfoInternal (unzFile file,
unz_file_info *pfile_info,
unz_file_info_internal
*pfile_info_internal,
char *szFileName,
uLong fileNameBufferSize,
void *extraField,
uLong extraFieldBufferSize,
char *szComment,
uLong commentBufferSize);
int unzlocal_GetCurrentFileInfoInternal (unzFile file, unz_file_info *pfile_info,
unz_file_info_internal *pfile_info_internal, char *szFileName,
uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize,
char *szComment, uLong commentBufferSize)
{
unz_s* s;
unz_file_info file_info;
unz_file_info_internal file_info_internal;
int err=UNZ_OK;
uLong uMagic;
long lSeek=0;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (lufseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0)
err=UNZ_ERRNO;
// we check the magic
if (err==UNZ_OK)
if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
err=UNZ_ERRNO;
else if (uMagic!=0x02014b50)
err=UNZ_BADZIPFILE;
if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK)
err=UNZ_ERRNO;
unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK)
err=UNZ_ERRNO;
lSeek+=file_info.size_filename;
if ((err==UNZ_OK) && (szFileName!=NULL))
{
uLong uSizeRead ;
if (file_info.size_filename<fileNameBufferSize)
{
*(szFileName+file_info.size_filename)='\0';
uSizeRead = file_info.size_filename;
}
else
uSizeRead = fileNameBufferSize;
if ((file_info.size_filename>0) && (fileNameBufferSize>0))
if (lufread(szFileName,(uInt)uSizeRead,1,s->file)!=1)
err=UNZ_ERRNO;
lSeek -= uSizeRead;
}
if ((err==UNZ_OK) && (extraField!=NULL))
{
uLong uSizeRead ;
if (file_info.size_file_extra<extraFieldBufferSize)
uSizeRead = file_info.size_file_extra;
else
uSizeRead = extraFieldBufferSize;
if (lSeek!=0)
if (lufseek(s->file,lSeek,SEEK_CUR)==0)
lSeek=0;
else
err=UNZ_ERRNO;
if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0))
if (lufread(extraField,(uInt)uSizeRead,1,s->file)!=1)
err=UNZ_ERRNO;
lSeek += file_info.size_file_extra - uSizeRead;
}
else
lSeek+=file_info.size_file_extra;
if ((err==UNZ_OK) && (szComment!=NULL))
{
uLong uSizeRead ;
if (file_info.size_file_comment<commentBufferSize)
{
*(szComment+file_info.size_file_comment)='\0';
uSizeRead = file_info.size_file_comment;
}
else
uSizeRead = commentBufferSize;
if (lSeek!=0)
if (lufseek(s->file,lSeek,SEEK_CUR)==0)
{} // unused lSeek=0;
else
err=UNZ_ERRNO;
if ((file_info.size_file_comment>0) && (commentBufferSize>0))
if (lufread(szComment,(uInt)uSizeRead,1,s->file)!=1)
err=UNZ_ERRNO;
//unused lSeek+=file_info.size_file_comment - uSizeRead;
}
else {} //unused lSeek+=file_info.size_file_comment;
if ((err==UNZ_OK) && (pfile_info!=NULL))
*pfile_info=file_info;
if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
*pfile_info_internal=file_info_internal;
return err;
}
// Write info about the ZipFile in the *pglobal_info structure.
// No preparation of the structure is needed
// return UNZ_OK if there is no problem.
int unzGetCurrentFileInfo (unzFile file, unz_file_info *pfile_info,
char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize,
char *szComment, uLong commentBufferSize)
{ return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,szFileName,fileNameBufferSize,
extraField,extraFieldBufferSize, szComment,commentBufferSize);
}
// Set the current file of the zipfile to the first file.
// return UNZ_OK if there is no problem
int unzGoToFirstFile (unzFile file)
{
int err;
unz_s* s;
if (file==NULL) return UNZ_PARAMERROR;
s=(unz_s*)file;
s->pos_in_central_dir=s->offset_central_dir;
s->num_file=0;
err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
s->current_file_ok = (err == UNZ_OK);
return err;
}
// Set the current file of the zipfile to the next file.
// return UNZ_OK if there is no problem
// return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
int unzGoToNextFile (unzFile file)
{
unz_s* s;
int err;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_END_OF_LIST_OF_FILE;
if (s->num_file+1==s->gi.number_entry)
return UNZ_END_OF_LIST_OF_FILE;
s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
s->num_file++;
err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
s->current_file_ok = (err == UNZ_OK);
return err;
}
// Try locate the file szFileName in the zipfile.
// For the iCaseSensitivity signification, see unzStringFileNameCompare
// return value :
// UNZ_OK if the file is found. It becomes the current file.
// UNZ_END_OF_LIST_OF_FILE if the file is not found
int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity)
{
unz_s* s;
int err;
uLong num_fileSaved;
uLong pos_in_central_dirSaved;
if (file==NULL)
return UNZ_PARAMERROR;
if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_END_OF_LIST_OF_FILE;
num_fileSaved = s->num_file;
pos_in_central_dirSaved = s->pos_in_central_dir;
err = unzGoToFirstFile(file);
while (err == UNZ_OK)
{
char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
unzGetCurrentFileInfo(file,NULL,
szCurrentFileName,sizeof(szCurrentFileName)-1,
NULL,0,NULL,0);
if (unzStringFileNameCompare(szCurrentFileName,szFileName,iCaseSensitivity)==0)
return UNZ_OK;
err = unzGoToNextFile(file);
}
s->num_file = num_fileSaved ;
s->pos_in_central_dir = pos_in_central_dirSaved ;
return err;
}
// Read the local header of the current zipfile
// Check the coherency of the local header and info in the end of central
// directory about this file
// store in *piSizeVar the size of extra info in local header
// (filename and size of extra field data)
int unzlocal_CheckCurrentFileCoherencyHeader (unz_s *s,uInt *piSizeVar,
uLong *poffset_local_extrafield, uInt *psize_local_extrafield)
{
uLong uMagic,uData,uFlags;
uLong size_filename;
uLong size_extra_field;
int err=UNZ_OK;
*piSizeVar = 0;
*poffset_local_extrafield = 0;
*psize_local_extrafield = 0;
if (lufseek(s->file,s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile,SEEK_SET)!=0)
return UNZ_ERRNO;
if (err==UNZ_OK)
if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
err=UNZ_ERRNO;
else if (uMagic!=0x04034b50)
err=UNZ_BADZIPFILE;
if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
err=UNZ_ERRNO;
// else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
// err=UNZ_BADZIPFILE;
if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
err=UNZ_BADZIPFILE;
if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
(s->cur_file_info.compression_method!=Z_DEFLATED))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // date/time
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // crc
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // size compr
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // size uncompr
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK)
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
err=UNZ_BADZIPFILE;
*piSizeVar += (uInt)size_filename;
if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK)
err=UNZ_ERRNO;
*poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
SIZEZIPLOCALHEADER + size_filename;
*psize_local_extrafield = (uInt)size_extra_field;
*piSizeVar += (uInt)size_extra_field;
return err;
}
// Open for reading data the current file in the zipfile.
// If there is no error and the file is opened, the return value is UNZ_OK.
int unzOpenCurrentFile (unzFile file, const char *password)
{
int err;
int Store;
uInt iSizeVar;
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
uLong offset_local_extrafield; // offset of the local extra field
uInt size_local_extrafield; // size of the local extra field
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_PARAMERROR;
if (s->pfile_in_zip_read != NULL)
unzCloseCurrentFile(file);
if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar,
&offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
return UNZ_BADZIPFILE;
pfile_in_zip_read_info = (file_in_zip_read_info_s*)zmalloc(sizeof(file_in_zip_read_info_s));
if (pfile_in_zip_read_info==NULL)
return UNZ_INTERNALERROR;
pfile_in_zip_read_info->read_buffer=(char*)zmalloc(UNZ_BUFSIZE);
pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
pfile_in_zip_read_info->pos_local_extrafield=0;
if (pfile_in_zip_read_info->read_buffer==NULL)
{
if (pfile_in_zip_read_info!=0) zfree(pfile_in_zip_read_info); //unused pfile_in_zip_read_info=0;
return UNZ_INTERNALERROR;
}
pfile_in_zip_read_info->stream_initialised=0;
if ((s->cur_file_info.compression_method!=0) && (s->cur_file_info.compression_method!=Z_DEFLATED))
{ // unused err=UNZ_BADZIPFILE;
}
Store = s->cur_file_info.compression_method==0;
pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
pfile_in_zip_read_info->crc32=0;
pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method;
pfile_in_zip_read_info->file=s->file;
pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
pfile_in_zip_read_info->stream.total_out = 0;
if (!Store)
{
pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
pfile_in_zip_read_info->stream.zfree = (free_func)0;
pfile_in_zip_read_info->stream.opaque = (voidpf)0;
err=inflateInit2(&pfile_in_zip_read_info->stream);
if (err == Z_OK)
pfile_in_zip_read_info->stream_initialised=1;
// windowBits is passed < 0 to tell that there is no zlib header.
// Note that in this case inflate *requires* an extra "dummy" byte
// after the compressed stream in order to complete decompression and
// return Z_STREAM_END.
// In unzip, i don't wait absolutely Z_STREAM_END because I known the
// size of both compressed and uncompressed data
}
pfile_in_zip_read_info->rest_read_compressed = s->cur_file_info.compressed_size ;
pfile_in_zip_read_info->rest_read_uncompressed = s->cur_file_info.uncompressed_size ;
pfile_in_zip_read_info->encrypted = (s->cur_file_info.flag&1)!=0;
bool extlochead = (s->cur_file_info.flag&8)!=0;
if (extlochead) pfile_in_zip_read_info->crcenctest = (char)((s->cur_file_info.dosDate>>8)&0xff);
else pfile_in_zip_read_info->crcenctest = (char)(s->cur_file_info.crc >> 24);
pfile_in_zip_read_info->encheadleft = (pfile_in_zip_read_info->encrypted?12:0);
pfile_in_zip_read_info->keys[0] = 305419896L;
pfile_in_zip_read_info->keys[1] = 591751049L;
pfile_in_zip_read_info->keys[2] = 878082192L;
for (const char *cp=password; cp!=0 && *cp!=0; cp++) Uupdate_keys(pfile_in_zip_read_info->keys,*cp);
pfile_in_zip_read_info->pos_in_zipfile =
s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER +
iSizeVar;
pfile_in_zip_read_info->stream.avail_in = (uInt)0;
s->pfile_in_zip_read = pfile_in_zip_read_info;
return UNZ_OK;
}
// Read bytes from the current file.
// buf contain buffer where data must be copied
// len the size of buf.
// return the number of byte copied if somes bytes are copied (and also sets *reached_eof)
// return 0 if the end of file was reached. (and also sets *reached_eof).
// return <0 with error code if there is an error. (in which case *reached_eof is meaningless)
// (UNZ_ERRNO for IO error, or zLib error for uncompress error)
int unzReadCurrentFile (unzFile file, voidp buf, unsigned len, bool *reached_eof)
{ int err=UNZ_OK;
uInt iRead = 0;
if (reached_eof!=0) *reached_eof=false;
unz_s *s = (unz_s*)file;
if (s==NULL) return UNZ_PARAMERROR;
file_in_zip_read_info_s* pfile_in_zip_read_info = s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR;
if ((pfile_in_zip_read_info->read_buffer == NULL)) return UNZ_END_OF_LIST_OF_FILE;
if (len==0) return 0;
pfile_in_zip_read_info->stream.next_out = (Byte*)buf;
pfile_in_zip_read_info->stream.avail_out = (uInt)len;
if (len>pfile_in_zip_read_info->rest_read_uncompressed)
{ pfile_in_zip_read_info->stream.avail_out = (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
}
while (pfile_in_zip_read_info->stream.avail_out>0)
{ if ((pfile_in_zip_read_info->stream.avail_in==0) && (pfile_in_zip_read_info->rest_read_compressed>0))
{ uInt uReadThis = UNZ_BUFSIZE;
if (pfile_in_zip_read_info->rest_read_compressed<uReadThis) uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
if (uReadThis == 0) {if (reached_eof!=0) *reached_eof=true; return UNZ_EOF;}
if (lufseek(pfile_in_zip_read_info->file, pfile_in_zip_read_info->pos_in_zipfile + pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0) return UNZ_ERRNO;
if (lufread(pfile_in_zip_read_info->read_buffer,uReadThis,1,pfile_in_zip_read_info->file)!=1) return UNZ_ERRNO;
pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
pfile_in_zip_read_info->stream.next_in = (Byte*)pfile_in_zip_read_info->read_buffer;
pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
//
if (pfile_in_zip_read_info->encrypted)
{ char *buf = (char*)pfile_in_zip_read_info->stream.next_in;
for (unsigned int i=0; i<uReadThis; i++) buf[i]=zdecode(pfile_in_zip_read_info->keys,buf[i]);
}
}
unsigned int uDoEncHead = pfile_in_zip_read_info->encheadleft;
if (uDoEncHead>pfile_in_zip_read_info->stream.avail_in) uDoEncHead=pfile_in_zip_read_info->stream.avail_in;
if (uDoEncHead>0)
{ char bufcrc=pfile_in_zip_read_info->stream.next_in[uDoEncHead-1];
pfile_in_zip_read_info->rest_read_uncompressed-=uDoEncHead;
pfile_in_zip_read_info->stream.avail_in -= uDoEncHead;
pfile_in_zip_read_info->stream.next_in += uDoEncHead;
pfile_in_zip_read_info->encheadleft -= uDoEncHead;
if (pfile_in_zip_read_info->encheadleft==0)
{ if (bufcrc!=pfile_in_zip_read_info->crcenctest) return UNZ_PASSWORD;
}
}
if (pfile_in_zip_read_info->compression_method==0)
{ uInt uDoCopy,i ;
if (pfile_in_zip_read_info->stream.avail_out < pfile_in_zip_read_info->stream.avail_in)
{ uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
}
else
{ uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
}
for (i=0;i<uDoCopy;i++) *(pfile_in_zip_read_info->stream.next_out+i) = *(pfile_in_zip_read_info->stream.next_in+i);
pfile_in_zip_read_info->crc32 = ucrc32(pfile_in_zip_read_info->crc32,pfile_in_zip_read_info->stream.next_out,uDoCopy);
pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
pfile_in_zip_read_info->stream.next_out += uDoCopy;
pfile_in_zip_read_info->stream.next_in += uDoCopy;
pfile_in_zip_read_info->stream.total_out += uDoCopy;
iRead += uDoCopy;
if (pfile_in_zip_read_info->rest_read_uncompressed==0) {if (reached_eof!=0) *reached_eof=true;}
}
else
{ uLong uTotalOutBefore,uTotalOutAfter;
const Byte *bufBefore;
uLong uOutThis;
int flush=Z_SYNC_FLUSH;
uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
bufBefore = pfile_in_zip_read_info->stream.next_out;
//
err=inflate(&pfile_in_zip_read_info->stream,flush);
//
uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
uOutThis = uTotalOutAfter-uTotalOutBefore;
pfile_in_zip_read_info->crc32 = ucrc32(pfile_in_zip_read_info->crc32,bufBefore,(uInt)(uOutThis));
pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis;
iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
if (err==Z_STREAM_END || pfile_in_zip_read_info->rest_read_uncompressed==0)
{ if (reached_eof!=0) *reached_eof=true;
return iRead;
}
if (err!=Z_OK) break;
}
}
if (err==Z_OK) return iRead;
return err;
}
// Give the current position in uncompressed data
z_off_t unztell (unzFile file)
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
return (z_off_t)pfile_in_zip_read_info->stream.total_out;
}
// return 1 if the end of file was reached, 0 elsewhere
int unzeof (unzFile file)
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
return 1;
else
return 0;
}
// Read extra field from the current file (opened by unzOpenCurrentFile)
// This is the local-header version of the extra field (sometimes, there is
// more info in the local-header version than in the central-header)
// if buf==NULL, it return the size of the local extra field that can be read
// if buf!=NULL, len is the size of the buffer, the extra header is copied in buf.
// the return value is the number of bytes copied in buf, or (if <0) the error code
int unzGetLocalExtrafield (unzFile file,voidp buf,unsigned len)
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
uInt read_now;
uLong size_to_read;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
size_to_read = (pfile_in_zip_read_info->size_local_extrafield -
pfile_in_zip_read_info->pos_local_extrafield);
if (buf==NULL)
return (int)size_to_read;
if (len>size_to_read)
read_now = (uInt)size_to_read;
else
read_now = (uInt)len ;
if (read_now==0)
return 0;
if (lufseek(pfile_in_zip_read_info->file, pfile_in_zip_read_info->offset_local_extrafield + pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0)
return UNZ_ERRNO;
if (lufread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1)
return UNZ_ERRNO;
return (int)read_now;
}
// Close the file in zip opened with unzipOpenCurrentFile
// Return UNZ_CRCERROR if all the file was read but the CRC is not good
int unzCloseCurrentFile (unzFile file)
{
int err=UNZ_OK;
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
{
if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
err=UNZ_CRCERROR;
}
if (pfile_in_zip_read_info->read_buffer!=0)
{ void *buf = pfile_in_zip_read_info->read_buffer;
zfree(buf);
pfile_in_zip_read_info->read_buffer=0;
}
pfile_in_zip_read_info->read_buffer = NULL;
if (pfile_in_zip_read_info->stream_initialised)
inflateEnd(&pfile_in_zip_read_info->stream);
pfile_in_zip_read_info->stream_initialised = 0;
if (pfile_in_zip_read_info!=0) zfree(pfile_in_zip_read_info); // unused pfile_in_zip_read_info=0;
s->pfile_in_zip_read=NULL;
return err;
}
// Get the global comment string of the ZipFile, in the szComment buffer.
// uSizeBuf is the size of the szComment buffer.
// return the number of byte copied or an error code <0
int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf)
{ //int err=UNZ_OK;
unz_s* s;
uLong uReadThis ;
if (file==NULL) return UNZ_PARAMERROR;
s=(unz_s*)file;
uReadThis = uSizeBuf;
if (uReadThis>s->gi.size_comment) uReadThis = s->gi.size_comment;
if (lufseek(s->file,s->central_pos+22,SEEK_SET)!=0) return UNZ_ERRNO;
if (uReadThis>0)
{ *szComment='\0';
if (lufread(szComment,(uInt)uReadThis,1,s->file)!=1) return UNZ_ERRNO;
}
if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) *(szComment+s->gi.size_comment)='\0';
return (int)uReadThis;
}
int unzOpenCurrentFile (unzFile file, const char *password);
int unzReadCurrentFile (unzFile file, void *buf, unsigned len);
int unzCloseCurrentFile (unzFile file);
typedef unsigned __int32 lutime_t; // define it ourselves since we don't include time.h
FILETIME timet2filetime(const lutime_t t)
{ LONGLONG i = Int32x32To64(t,10000000) + 116444736000000000;
FILETIME ft;
ft.dwLowDateTime = (DWORD) i;
ft.dwHighDateTime = (DWORD)(i >>32);
return ft;
}
FILETIME dosdatetime2filetime(WORD dosdate,WORD dostime)
{ // date: bits 0-4 are day of month 1-31. Bits 5-8 are month 1..12. Bits 9-15 are year-1980
// time: bits 0-4 are seconds/2, bits 5-10 are minute 0..59. Bits 11-15 are hour 0..23
SYSTEMTIME st;
st.wYear = (WORD)(((dosdate>>9)&0x7f) + 1980);
st.wMonth = (WORD)((dosdate>>5)&0xf);
st.wDay = (WORD)(dosdate&0x1f);
st.wHour = (WORD)((dostime>>11)&0x1f);
st.wMinute = (WORD)((dostime>>5)&0x3f);
st.wSecond = (WORD)((dostime&0x1f)*2);
st.wMilliseconds = 0;
FILETIME ft; SystemTimeToFileTime(&st,&ft);
return ft;
}
class TUnzip
{ public:
TUnzip(const char *pwd) : uf(0), unzbuf(0), currentfile(-1), czei(-1), password(0) {if (pwd!=0) {password=new char[strlen(pwd)+1]; strcpy_s(password,MAX_PATH,pwd);}}
~TUnzip() {if (password!=0) delete[] password; password=0; if (unzbuf!=0) delete[] unzbuf; unzbuf=0;}
unzFile uf; int currentfile; ZIPENTRY cze; int czei;
char *password;
char *unzbuf; // lazily created and destroyed, used by Unzip
TCHAR rootdir[MAX_PATH]; // includes a trailing slash
ZRESULT Open(void *z,unsigned int len,DWORD flags);
ZRESULT Get(int index,ZIPENTRY *ze);
ZRESULT Find(const TCHAR *name,bool ic,int *index,ZIPENTRY *ze);
ZRESULT Unzip(int index,void *dst,unsigned int len,DWORD flags);
ZRESULT SetUnzipBaseDir(const TCHAR *dir);
ZRESULT Close();
};
ZRESULT TUnzip::Open(void *z,unsigned int len,DWORD flags)
{ if (uf!=0 || currentfile!=-1) return ZR_NOTINITED;
//
#ifdef GetCurrentDirectory
GetCurrentDirectory(MAX_PATH,rootdir);
#else
_tcscpy(rootdir,_T("\\"));
#endif
TCHAR lastchar = rootdir[_tcslen(rootdir)-1];
if (lastchar!='\\' && lastchar!='/') _tcscat_s(rootdir,_T("\\"));
//
if (flags==ZIP_HANDLE)
{ // test if we can seek on it. We can't use GetFileType(h)==FILE_TYPE_DISK since it's not on CE.
DWORD res = SetFilePointer(z,0,0,FILE_CURRENT);
bool canseek = (res!=0xFFFFFFFF);
if (!canseek) return ZR_SEEK;
}
ZRESULT e; LUFILE *f = lufopen(z,len,flags,&e);
if (f==NULL) return e;
uf = unzOpenInternal(f);
if (uf==0) return ZR_NOFILE;
return ZR_OK;
}
ZRESULT TUnzip::SetUnzipBaseDir(const TCHAR *dir)
{
_tcscpy_s(rootdir, MAX_PATH, dir);
TCHAR lastchar = rootdir[_tcslen(rootdir)-1];
if (lastchar!='\\' && lastchar!='/') _tcscat_s(rootdir,_T("\\"));
return ZR_OK;
}
ZRESULT TUnzip::Get(int index,ZIPENTRY *ze)
{ if (index<-1 || index>=(int)uf->gi.number_entry) return ZR_ARGS;
if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
if (index==czei && index!=-1) {memcpy(ze,&cze,sizeof(ZIPENTRY)); return ZR_OK;}
if (index==-1)
{ ze->index = uf->gi.number_entry;
ze->name[0]=0;
ze->attr=0;
ze->atime.dwLowDateTime=0; ze->atime.dwHighDateTime=0;
ze->ctime.dwLowDateTime=0; ze->ctime.dwHighDateTime=0;
ze->mtime.dwLowDateTime=0; ze->mtime.dwHighDateTime=0;
ze->comp_size=0;
ze->unc_size=0;
return ZR_OK;
}
if (index<(int)uf->num_file) unzGoToFirstFile(uf);
while ((int)uf->num_file<index) unzGoToNextFile(uf);
unz_file_info ufi; char fn[MAX_PATH];
unzGetCurrentFileInfo(uf,&ufi,fn,MAX_PATH,NULL,0,NULL,0);
// now get the extra header. We do this ourselves, instead of
// calling unzOpenCurrentFile &c., to avoid allocating more than necessary.
unsigned int extralen,iSizeVar; unsigned long offset;
int res = unzlocal_CheckCurrentFileCoherencyHeader(uf,&iSizeVar,&offset,&extralen);
if (res!=UNZ_OK) return ZR_CORRUPT;
if (lufseek(uf->file,offset,SEEK_SET)!=0) return ZR_READ;
unsigned char *extra = new unsigned char[extralen];
if (lufread(extra,1,(uInt)extralen,uf->file)!=extralen) {delete[] extra; return ZR_READ;}
//
ze->index=uf->num_file;
TCHAR tfn[MAX_PATH];
#ifdef UNICODE
MultiByteToWideChar(CP_UTF8,0,fn,-1,tfn,MAX_PATH);
#else
strcpy(tfn,fn);
#endif
// As a safety feature: if the zip filename had sneaky stuff
// like "c:\windows\file.txt" or "\windows\file.txt" or "fred\..\..\..\windows\file.txt"
// then we get rid of them all. That way, when the programmer does UnzipItem(hz,i,ze.name),
// it won't be a problem. (If the programmer really did want to get the full evil information,
// then they can edit out this security feature from here).
// In particular, we chop off any prefixes that are "c:\" or "\" or "/" or "[stuff]\.." or "[stuff]/.."
const TCHAR *sfn=tfn;
for (;;)
{ if (sfn[0]!=0 && sfn[1]==':') {sfn+=2; continue;}
if (sfn[0]=='\\') {sfn++; continue;}
if (sfn[0]=='/') {sfn++; continue;}
const TCHAR *c;
c=_tcsstr(sfn,_T("\\..\\")); if (c!=0) {sfn=c+4; continue;}
c=_tcsstr(sfn,_T("\\../")); if (c!=0) {sfn=c+4; continue;}
c=_tcsstr(sfn,_T("/../")); if (c!=0) {sfn=c+4; continue;}
c=_tcsstr(sfn,_T("/..\\")); if (c!=0) {sfn=c+4; continue;}
break;
}
_tcscpy_s(ze->name, MAX_PATH, sfn);
// zip has an 'attribute' 32bit value. Its lower half is windows stuff
// its upper half is standard unix stat.st_mode. We'll start trying
// to read it in unix mode
unsigned long a = ufi.external_fa;
bool isdir = (a&0x40000000)!=0;
bool readonly= (a&0x00800000)==0;
//bool readable= (a&0x01000000)!=0; // unused
//bool executable=(a&0x00400000)!=0; // unused
bool hidden=false, system=false, archive=true;
// but in normal hostmodes these are overridden by the lower half...
int host = ufi.version>>8;
if (host==0 || host==7 || host==11 || host==14)
{ readonly= (a&0x00000001)!=0;
hidden= (a&0x00000002)!=0;
system= (a&0x00000004)!=0;
isdir= (a&0x00000010)!=0;
archive= (a&0x00000020)!=0;
}
ze->attr=0;
if (isdir) ze->attr |= FILE_ATTRIBUTE_DIRECTORY;
if (archive) ze->attr|=FILE_ATTRIBUTE_ARCHIVE;
if (hidden) ze->attr|=FILE_ATTRIBUTE_HIDDEN;
if (readonly) ze->attr|=FILE_ATTRIBUTE_READONLY;
if (system) ze->attr|=FILE_ATTRIBUTE_SYSTEM;
ze->comp_size = ufi.compressed_size;
ze->unc_size = ufi.uncompressed_size;
//
WORD dostime = (WORD)(ufi.dosDate&0xFFFF);
WORD dosdate = (WORD)((ufi.dosDate>>16)&0xFFFF);
FILETIME ftd = dosdatetime2filetime(dosdate,dostime);
FILETIME ft; LocalFileTimeToFileTime(&ftd,&ft);
ze->atime=ft; ze->ctime=ft; ze->mtime=ft;
// the zip will always have at least that dostime. But if it also has
// an extra header, then we'll instead get the info from that.
unsigned int epos=0;
while (epos+4<extralen)
{ char etype[3]; etype[0]=extra[epos+0]; etype[1]=extra[epos+1]; etype[2]=0;
int size = extra[epos+2];
if (strcmp(etype,"UT")!=0) {epos += 4+size; continue;}
int flags = extra[epos+4];
bool hasmtime = (flags&1)!=0;
bool hasatime = (flags&2)!=0;
bool hasctime = (flags&4)!=0;
epos+=5;
if (hasmtime)
{ lutime_t mtime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
epos+=4;
ze->mtime = timet2filetime(mtime);
}
if (hasatime)
{ lutime_t atime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
epos+=4;
ze->atime = timet2filetime(atime);
}
if (hasctime)
{ lutime_t ctime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
epos+=4;
ze->ctime = timet2filetime(ctime);
}
break;
}
//
if (extra!=0) delete[] extra;
memcpy(&cze,ze,sizeof(ZIPENTRY)); czei=index;
return ZR_OK;
}
ZRESULT TUnzip::Find(const TCHAR *tname,bool ic,int *index,ZIPENTRY *ze)
{ char name[MAX_PATH];
#ifdef UNICODE
WideCharToMultiByte(CP_UTF8,0,tname,-1,name,MAX_PATH,0,0);
#else
strcpy(name,tname);
#endif
int res = unzLocateFile(uf,name,ic?CASE_INSENSITIVE:CASE_SENSITIVE);
if (res!=UNZ_OK)
{ if (index!=0) *index=-1;
if (ze!=NULL) {ZeroMemory(ze,sizeof(ZIPENTRY)); ze->index=-1;}
return ZR_NOTFOUND;
}
if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
int i = (int)uf->num_file;
if (index!=NULL) *index=i;
if (ze!=NULL)
{ ZRESULT zres = Get(i,ze);
if (zres!=ZR_OK) return zres;
}
return ZR_OK;
}
void EnsureDirectory(const TCHAR *rootdir, const TCHAR *dir)
{ if (rootdir!=0 && GetFileAttributes(rootdir)==0xFFFFFFFF) CreateDirectory(rootdir,0);
if (*dir==0) return;
const TCHAR *lastslash=dir, *c=lastslash;
while (*c!=0) {if (*c=='/' || *c=='\\') lastslash=c; c++;}
const TCHAR *name=lastslash;
if (lastslash!=dir)
{ TCHAR tmp[MAX_PATH]; memcpy(tmp,dir,sizeof(TCHAR)*(lastslash-dir));
tmp[lastslash-dir]=0;
EnsureDirectory(rootdir,tmp);
name++;
}
TCHAR cd[MAX_PATH]; *cd=0; if (rootdir!=0) _tcscpy_s(cd, MAX_PATH, rootdir); _tcscat_s(cd,dir);
if (GetFileAttributes(cd)==0xFFFFFFFF) CreateDirectory(cd,NULL);
}
ZRESULT TUnzip::Unzip(int index,void *dst,unsigned int len,DWORD flags)
{ if (flags!=ZIP_MEMORY && flags!=ZIP_FILENAME && flags!=ZIP_HANDLE) return ZR_ARGS;
if (flags==ZIP_MEMORY)
{ if (index!=currentfile)
{ if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
if (index>=(int)uf->gi.number_entry) return ZR_ARGS;
if (index<(int)uf->num_file) unzGoToFirstFile(uf);
while ((int)uf->num_file<index) unzGoToNextFile(uf);
unzOpenCurrentFile(uf,password); currentfile=index;
}
bool reached_eof;
int res = unzReadCurrentFile(uf,dst,len,&reached_eof);
if (res<=0) {unzCloseCurrentFile(uf); currentfile=-1;}
if (reached_eof) return ZR_OK;
if (res>0) return ZR_MORE;
if (res==UNZ_PASSWORD) return ZR_PASSWORD;
return ZR_FLATE;
}
// otherwise we're writing to a handle or a file
if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
if (index>=(int)uf->gi.number_entry) return ZR_ARGS;
if (index<(int)uf->num_file) unzGoToFirstFile(uf);
while ((int)uf->num_file<index) unzGoToNextFile(uf);
ZIPENTRY ze; Get(index,&ze);
// zipentry=directory is handled specially
if ((ze.attr&FILE_ATTRIBUTE_DIRECTORY)!=0)
{ if (flags==ZIP_HANDLE) return ZR_OK; // don't do anything
const TCHAR *dir = (const TCHAR*)dst;
bool isabsolute = (dir[0]=='/' || dir[0]=='\\' || (dir[0]!=0 && dir[1]==':'));
if (isabsolute) EnsureDirectory(0,dir); else EnsureDirectory(rootdir,dir);
return ZR_OK;
}
// otherwise, we write the zipentry to a file/handle
HANDLE h;
if (flags==ZIP_HANDLE) h=dst;
else
{ const TCHAR *ufn = (const TCHAR*)dst;
// We'll qualify all relative names to our root dir, and leave absolute names as they are
// ufn="zipfile.txt" dir="" name="zipfile.txt" fn="c:\\currentdir\\zipfile.txt"
// ufn="dir1/dir2/subfile.txt" dir="dir1/dir2/" name="subfile.txt" fn="c:\\currentdir\\dir1/dir2/subfiles.txt"
// ufn="\z\file.txt" dir="\z\" name="file.txt" fn="\z\file.txt"
// This might be a security risk, in the case where we just use the zipentry's name as "ufn", where
// a malicious zip could unzip itself into c:\windows. Our solution is that GetZipItem (which
// is how the user retrieve's the file's name within the zip) never returns absolute paths.
const TCHAR *name=ufn; const TCHAR *c=name; while (*c!=0) {if (*c=='/' || *c=='\\') name=c+1; c++;}
TCHAR dir[MAX_PATH]; _tcscpy_s(dir, MAX_PATH, ufn); if (name==ufn) *dir=0; else dir[name-ufn]=0;
TCHAR fn[MAX_PATH];
bool isabsolute = (dir[0]=='/' || dir[0]=='\\' || (dir[0]!=0 && dir[1]==':'));
if (isabsolute) {wsprintf(fn,_T("%s%s"),dir,name); EnsureDirectory(0,dir);}
else {wsprintf(fn,_T("%s%s%s"),rootdir,dir,name); EnsureDirectory(rootdir,dir);}
//
h = CreateFile(fn,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,ze.attr,NULL);
}
if (h==INVALID_HANDLE_VALUE) return ZR_NOFILE;
unzOpenCurrentFile(uf,password);
if (unzbuf==0) unzbuf=new char[16384]; DWORD haderr=0;
//
for (; haderr==0;)
{ bool reached_eof;
int res = unzReadCurrentFile(uf,unzbuf,16384,&reached_eof);
if (res==UNZ_PASSWORD) {haderr=ZR_PASSWORD; break;}
if (res<0) {haderr=ZR_FLATE; break;}
if (res>0) {DWORD writ; BOOL bres=WriteFile(h,unzbuf,res,&writ,NULL); if (!bres) {haderr=ZR_WRITE; break;}}
if (reached_eof) break;
if (res==0) {haderr=ZR_FLATE; break;}
}
if (!haderr) SetFileTime(h,&ze.ctime,&ze.atime,&ze.mtime); // may fail if it was a pipe
if (flags!=ZIP_HANDLE) CloseHandle(h);
unzCloseCurrentFile(uf);
if (haderr!=0) return haderr;
return ZR_OK;
}
ZRESULT TUnzip::Close()
{ if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
if (uf!=0) unzClose(uf); uf=0;
return ZR_OK;
}
ZRESULT lasterrorU=ZR_OK;
unsigned int FormatZipMessageU(ZRESULT code, TCHAR *buf,unsigned int len)
{ if (code==ZR_RECENT) code=lasterrorU;
const TCHAR *msg=_T("unknown zip result code");
switch (code)
{ case ZR_OK: msg=_T("Success"); break;
case ZR_NODUPH: msg=_T("Culdn't duplicate handle"); break;
case ZR_NOFILE: msg=_T("Couldn't create/open file"); break;
case ZR_NOALLOC: msg=_T("Failed to allocate memory"); break;
case ZR_WRITE: msg=_T("Error writing to file"); break;
case ZR_NOTFOUND: msg=_T("File not found in the zipfile"); break;
case ZR_MORE: msg=_T("Still more data to unzip"); break;
case ZR_CORRUPT: msg=_T("Zipfile is corrupt or not a zipfile"); break;
case ZR_READ: msg=_T("Error reading file"); break;
case ZR_PASSWORD: msg=_T("Correct password required"); break;
case ZR_ARGS: msg=_T("Caller: faulty arguments"); break;
case ZR_PARTIALUNZ: msg=_T("Caller: the file had already been partially unzipped"); break;
case ZR_NOTMMAP: msg=_T("Caller: can only get memory of a memory zipfile"); break;
case ZR_MEMSIZE: msg=_T("Caller: not enough space allocated for memory zipfile"); break;
case ZR_FAILED: msg=_T("Caller: there was a previous error"); break;
case ZR_ENDED: msg=_T("Caller: additions to the zip have already been ended"); break;
case ZR_ZMODE: msg=_T("Caller: mixing creation and opening of zip"); break;
case ZR_NOTINITED: msg=_T("Zip-bug: internal initialisation not completed"); break;
case ZR_SEEK: msg=_T("Zip-bug: trying to seek the unseekable"); break;
case ZR_MISSIZE: msg=_T("Zip-bug: the anticipated size turned out wrong"); break;
case ZR_NOCHANGE: msg=_T("Zip-bug: tried to change mind, but not allowed"); break;
case ZR_FLATE: msg=_T("Zip-bug: an internal error during flation"); break;
}
unsigned int mlen=(unsigned int)_tcslen(msg);
if (buf==0 || len==0) return mlen;
unsigned int n=mlen; if (n+1>len) n=len-1;
_tcsncpy_s(buf,MAX_PATH,msg,n); buf[n]=0;
return mlen;
}
typedef struct
{ DWORD flag;
TUnzip *unz;
} TUnzipHandleData;
HZIP OpenZipInternal(void *z,unsigned int len,DWORD flags, const char *password)
{ TUnzip *unz = new TUnzip(password);
lasterrorU = unz->Open(z,len,flags);
if (lasterrorU!=ZR_OK) {delete unz; return 0;}
TUnzipHandleData *han = new TUnzipHandleData;
han->flag=1; han->unz=unz; return (HZIP)han;
}
HZIP OpenZipHandle(HANDLE h, const char *password) {return OpenZipInternal((void*)h,0,ZIP_HANDLE,password);}
HZIP OpenZip(const TCHAR *fn, const char *password) {return OpenZipInternal((void*)fn,0,ZIP_FILENAME,password);}
HZIP OpenZip(void *z,unsigned int len, const char *password) {return OpenZipInternal(z,len,ZIP_MEMORY,password);}
ZRESULT GetZipItem(HZIP hz, int index, ZIPENTRY *ze)
{ ze->index=0; *ze->name=0; ze->unc_size=0;
if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->Get(index,ze);
return lasterrorU;
}
ZRESULT FindZipItem(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze)
{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->Find(name,ic,index,ze);
return lasterrorU;
}
ZRESULT UnzipItemInternal(HZIP hz, int index, void *dst, unsigned int len, DWORD flags)
{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->Unzip(index,dst,len,flags);
return lasterrorU;
}
ZRESULT UnzipItemHandle(HZIP hz, int index, HANDLE h) {return UnzipItemInternal(hz,index,(void*)h,0,ZIP_HANDLE);}
ZRESULT UnzipItem(HZIP hz, int index, const TCHAR *fn) {return UnzipItemInternal(hz,index,(void*)fn,0,ZIP_FILENAME);}
ZRESULT UnzipItem(HZIP hz, int index, void *z,unsigned int len) {return UnzipItemInternal(hz,index,z,len,ZIP_MEMORY);}
ZRESULT SetUnzipBaseDir(HZIP hz, const TCHAR *dir)
{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->SetUnzipBaseDir(dir);
return lasterrorU;
}
ZRESULT CloseZipU(HZIP hz)
{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->Close();
delete unz;
delete han;
return lasterrorU;
}
bool IsZipHandleU(HZIP hz)
{ if (hz==0) return false;
TUnzipHandleData *han = (TUnzipHandleData*)hz;
return (han->flag==1);
} | [
"[email protected]"
] | |
346a7a2af702300a5cc4ee8a17dd3e122abdbaae | 4d539b4c78d9c2af2ddac3efc71190fec0c7acf6 | /lab_hash/schashtable.cpp | f0ef13dff737af53d99c261ceefd7ed33dcd7efb | [] | no_license | yuansun97/Data-Structures-cpp | 722d473683bad6cf78ff8bf12d3381dbeb201caa | 5449da0fa8cfba7496d9ec5162e8c1ff5adf904f | refs/heads/master | 2020-12-04T08:42:11.417987 | 2020-01-04T02:49:09 | 2020-01-04T02:49:09 | 231,698,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,576 | cpp | /**
* @file schashtable.cpp
* Implementation of the SCHashTable class.
*/
#include "schashtable.h"
#include <iostream>
template <class K, class V>
SCHashTable<K, V>::SCHashTable(size_t tsize)
{
if (tsize <= 0)
tsize = 17;
size = findPrime(tsize);
table = new std::list<std::pair<K, V>>[size];
elems = 0;
}
template <class K, class V>
SCHashTable<K, V>::~SCHashTable()
{
if (table != NULL) {
delete[] table;
table = NULL;
}
}
template <class K, class V>
SCHashTable<K, V> const& SCHashTable<K, V>::
operator=(SCHashTable<K, V> const& rhs)
{
if (this != &rhs) {
delete[] table;
table = new std::list<std::pair<K, V>>[rhs.size];
for (size_t i = 0; i < rhs.size; i++)
table[i] = rhs.table[i];
size = rhs.size;
elems = rhs.elems;
}
return *this;
}
template <class K, class V>
SCHashTable<K, V>::SCHashTable(SCHashTable<K, V> const& other)
{
table = new std::list<std::pair<K, V>>[other.size];
for (size_t i = 0; i < other.size; i++)
table[i] = other.table[i];
size = other.size;
elems = other.elems;
}
template <class K, class V>
void SCHashTable<K, V>::insert(K const& key, V const& value)
{
/**
* @todo Implement this function.
*
*/
// Always remove the given key first,
// regardless whether the key exists or not.
remove(key);
unsigned idx = hashes::hash(key, size);
table[idx].push_front(std::pair<K, V>(key, value));
// std::cout << "## Test ## {" << table[idx].front().first
// << ", " << table[idx].front().second
// << "}" << " pushed!" << std::endl;
elems++;
if (shouldResize()) resizeTable();
}
template <class K, class V>
void SCHashTable<K, V>::remove(K const& key)
{
/**
* @todo Implement this function.
*
* Please read the note in the lab spec about list iterators and the
* erase() function on std::list!
*/
typename std::list<std::pair<K, V>>::iterator it;
unsigned idx = hashes::hash(key, size);
for (it = table[idx].begin(); it != table[idx].end(); it++) {
if (it->first == key) {
table[idx].erase(it);
elems--;
break;
}
}
}
template <class K, class V>
V SCHashTable<K, V>::find(K const& key) const
{
/**
* @todo: Implement this function.
*/
typename std::list<std::pair<K, V>>::iterator it;
unsigned idx = hashes::hash(key, size);
for (it = table[idx].begin(); it != table[idx].end(); it++) {
if (it->first == key) {
return it->second;
}
}
return V();
}
template <class K, class V>
V& SCHashTable<K, V>::operator[](K const& key)
{
size_t idx = hashes::hash(key, size);
typename std::list<std::pair<K, V>>::iterator it;
for (it = table[idx].begin(); it != table[idx].end(); it++) {
if (it->first == key)
return it->second;
}
// was not found, insert a default-constructed version and return it
++elems;
if (shouldResize())
resizeTable();
idx = hashes::hash(key, size);
std::pair<K, V> p(key, V());
table[idx].push_front(p);
return table[idx].front().second;
}
template <class K, class V>
bool SCHashTable<K, V>::keyExists(K const& key) const
{
size_t idx = hashes::hash(key, size);
typename std::list<std::pair<K, V>>::iterator it;
for (it = table[idx].begin(); it != table[idx].end(); it++) {
if (it->first == key)
return true;
}
return false;
}
template <class K, class V>
void SCHashTable<K, V>::clear()
{
delete[] table;
table = new std::list<std::pair<K, V>>[17];
size = 17;
elems = 0;
}
template <class K, class V>
void SCHashTable<K, V>::resizeTable()
{
/**
* @todo Implement this function.
*
* Please read the note in the spec about list iterators!
* The size of the table should be the closest prime to size * 2.
*
* @hint Use findPrime()!
*/
typename std::list<std::pair<K, V>>::iterator it;
unsigned newSize = findPrime(size * 2);
std::list<std::pair<K, V>> * newTable = new std::list<std::pair<K, V>>[newSize];
for (unsigned i = 0; i < size; i++) {
for (it = table[i].begin(); it != table[i].end(); it++) {
K key = it->first;
V val = it->second;
unsigned idx = hashes::hash(key, newSize);
newTable[idx].push_front({key, val});
}
}
delete[] table;
table = newTable;
size = newSize;
}
| [
"[email protected]"
] | |
24b0cfcee928793ccea8ee66d47b29775ad07acb | 37585de86ef412211a9b2519817d3ff5247373c8 | /Ideas/Tables.cpp | 12fc8654ef051bc6cf9129489e60bc617c02528b | [
"LicenseRef-scancode-warranty-disclaimer",
"Fair"
] | permissive | ghassanpl/reflector | 7b99162a0e792ff6a0eebecf98c277791df6bae4 | 217a9fe630f7a9c6ea196d26d69364138be5a5bc | refs/heads/master | 2023-08-17T13:42:14.394557 | 2023-08-13T10:57:16 | 2023-08-13T18:49:58 | 196,881,074 | 12 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,336 | cpp | #if 0
RClass(Record, Multithreaded);
struct Movie
{
RBody(); =>
BaseTable* mParentTable = nullptr;
friend struct MovieTable;
mutable bool mDeletePending = false;
enum class Column { ID, Name, Score, ReleaseYear, IMDBId, SomeSource };
std::bitset<enum_count<Column>() + /* entire row needs flushing */1> mChanges;
/// TODO: Do we require inherting from reflectable? We could use its Dirty flag
RField(Key, Autoincrement);
int ID = 0;
RField(Index = { Collation = CaseInsensitive });
string Name;
RField(Index = { Sort = Descending });
double Score = 5.0;
RField(Index);
int ReleaseYear = 2000;
RField(Index, Unique);
uint64_t IMDBId = 0;
=> void SetIMBDId(uint64_t val) {
mParentTable->InTransaction([this, &val] {
mParentTable->ConstrainedSet(this, (int)Column::IMDBId, this->IMDBId, val);
mParentTable->Reindex(this, (int)Column::IMDBId);
mParentTable->Reindex(this, (int)Column::SomeSource);
});
}
RMethod(Index);
int SomeSource() const; /// Cannot have arguments, must be const
/// Only private fields ? How to limit changing indexed fields?
};
=>
struct BaseTable
{
std::mutex mWriteTransactionMutex;
std::atomic_size_t mTransactionDepth{0};
}
template <typename ROW_TYPE, typename CRTP>
struct TTable : BaseTable
{
using RowType = ROW_TYPE;
using PrimaryKeyType = RowType::PrimaryKeyType;
static constexpr inline RowCount = RowType::mRowCount;
std::array<bool, RowCount> mIndicesInNeedOfRebuilding;
void Reindex(ROW_TYPE* because_of, int column)
{
mIndicesInNeedOfRebuilding[column] = true;
}
void BeginTransaction()
{
if constexpr (RowType::Attribute_Multithreaded)
{
if (mTransactionDepth == 0)
mWriteTransactionMutex.lock();
}
mTransactionDepth++;
};
void EndTransaction()
{
mTransactionDepth--;
if (mTransactionDepth == 0)
{
for (int i=0; i<RowCount; ++i)
if (mIndicesInNeedOfRebuilding)
static_cast<CRTP*>(this)->PerformReindex(i);
if constexpr (RowType::Attribute_Multithreaded)
mWriteTransactionMutex.unlock();
}
}
std::map<PK, T, std::less<>> TableStorage;
};
struct OrderBy : SelectParam
{
OrderBy(member function pointer, asc/desc = asc);
OrderBy(member variable pointer, asc/desc = asc);
OrderBy(column id, asc/desc = asc);
OrderBy(column name, asc/desc = asc);
};
struct MovieTable : TTable<Movie, MovieTable>
{
auto InTransaction(auto&& func) -> decltype(func(this))
{
BeginWriteTransaction();
try
{
return func(this);
EndWriteTransaction();
}
catch (e)
{
if (!RollbackTransaction()) /// mTransactionDepth > 1
throw;
}
return {};
}
/// Not thread-safe
RowType const* Get(PrimaryKeyType const& key)
{
auto row = Find(key);
if (row && !row->mDeletePending)
return row;
return nullptr;
}
auto With(PrimaryKeyType const& key, auto&& func)
{
return InTransaction([&]{
auto row = Get(key);
return row ? func(*row) : {};
});
}
std::optional<RowType> Delete(PrimaryKeyType const& key)
{
}
/// Params are stuff like LIMIT, ORDER BY, etc.
std::vector<RowType> DeleteWhere(auto&& func, auto... params)
{
return InTransaction([&] {
MovieTableSelection selection = Select(func, params...);
return RemoveRows(selection);
});
}
void ForEach(auto&& func);
MovieTableSelection Select(auto&& func, auto... params);
/// group by, distinct, window, joins, having
std::optional<PrimaryKeyType> Insert(RowType row);
std::vector<PrimaryKeyType> Insert(std::span<RowType> rows);
std::optional<PrimaryKeyType> InsertOr(ABORT/FAIL/IGNORE/REPLACE/ROLLBACK, RowType row);
std::optional<PrimaryKeyType> InsertOrUpdate(RowType new_row, auto&& update_func)
{
if (conflict)
{
update_func(new_row, old_row);
old_row->SetDirty();
}
}
void Update(auto&& update_func, auto&& where, auto... params)
{
return InTransaction([&] {
MovieTableSelection selection = Select(where, params...);
for (auto& obj : selection)
{
update_func(obj);
obj->SetDirty();
}
});
}
private:
struct TransactionElement
{
int ElementType = /// UPDATE_FIELD, DELETE_ROW;
row_ptr Row = {};
int ColumnId = {};
std::any OldFieldValue;
};
enum {
ROW_Name,
ROW_Score,
ROW_ReleaseYear,
ROW_IMDBId,
ROW_SomeSource,
ROW_COUNT,
};
void PerformReindex(int row)
{
switch (row)
{
case ROW_Name: PerformReindex_Name();
...
}
}
friend struct Movie;
using RowPtr = either `PrimaryKeyType` or `RowType*`
std::multimap<string, RowPtr, Reflector::Collator<CaseInsensitive>::Less> IndexFor_Name;
std::multimap<double, RowPtr, std::greater<>> IndexFor_Score;
std::multimap<int, RowPtr, std::less<>> IndexFor_ReleaseYear;
std::map<uint64_t, RowPtr, std::less<>> IndexFor_IMDBId;
std::multimap<int, RowPtr, std::less<>> IndexFor_SomeSource;
};
template <typename TABLE>
struct TTableSelection
{
std::vector<TABLE::PrimaryKeyType> SelectedRows;
void SortByColumns(auto... columns);
void Crop(int start, int count);
};
struct MovieTableSelection : TTableSelection<MovieTable>
{
};
#endif | [
"[email protected]"
] | |
bd6c2df095958604a9d37647317eb77b66e673f9 | c512bd8b0fb797f503e57540c11657b79336d5b1 | /OOP3200-INCLASS3-ANDRAGRIPPA/Person.cpp | 8d8e1b099d8aa2486acdae5481f3c16c1d858d91 | [] | no_license | vans12345678/OOP3200-INCLASS3-ANDRAGRIPPA | 6646fa6ee557f567bd0b4f59d3c9fa39206b4119 | f9edb63613ca5b93dd72ce85ed91891e23cab737 | refs/heads/master | 2022-12-18T20:15:11.016237 | 2020-10-01T01:11:06 | 2020-10-01T01:11:06 | 299,958,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,523 | cpp | /**
* Project OOP3200-F2020-LESSON4
* @author Andre Agrippa
* @version 1.0
*/
#include "Person.h"
#include <iostream>
#include <ostream>
/**
* Person implementation
*/
/**
* @param first_name
* @param last_name
* @param age
*/
Person::Person(std::string first_name, std::string last_name, const float age):
m_age(age), m_firstName(std::move(first_name)), m_lastName(std::move(last_name))
{
}
Person::~Person()
= default;
/**
* @return std::string
*/
std::string Person::getFirstName()const {
return m_firstName;
}
/**
* @param value
*/
void Person::setFirstName(const std::string& value) {
m_firstName = value;
}
/**
* @return std::string
*/
std::string Person::getLastName() const{
return m_lastName;
}
/**
* @param value
*/
void Person::setLastName(const std::string& value) {
m_lastName = value;
}
/**
* @return float
*/
float Person::getAge()const {
return m_age;
}
/**
* @param value
*/
void Person::setAge(const float value) {
m_age = value;
}
/**
* @return void
*/
void Person::SaysHello() const{
std::cout << getFirstName() << " says Hello!" << std::endl;
}
/**
* @return std::string
*/
std::string Person::ToString() {
std::string output_string;
output_string += "----------------------------------------------------\n";
output_string += "First Name: " + getFirstName() + "\n";
output_string += "Last Name: " + getLastName() + "\n";
output_string += "Age: " + std::to_string(getAge()) + "\n";
return output_string;
} | [
"[email protected]"
] | |
9ac7fc61e93fae4a2a3dd1a7ec0aa7097f7a4960 | a2e9639153e71dcf84d34b7349d69aa31b2eb678 | /zBTLC/zBTLC/game_sa/CTreadable.cpp | 63795c950bd989bdd738bcfddca7777d25e94cc7 | [] | no_license | DaDj/GTA-BTLC | ade014b3d8dbb1ecce6422328be95631226cd6f4 | 15d60cb5d5f14291317235066d64a639fffaf3ea | refs/heads/master | 2023-08-16T23:12:57.867204 | 2023-08-13T21:45:06 | 2023-08-13T21:45:06 | 83,485,003 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 23 | cpp | #include "CTreadable.h" | [
"[email protected]"
] | |
594e71c07f5c14b0e47d84c3887fb2634517984c | 7a5a713cc999fdc1f64457949b003980e288567a | /Classes/ExplodeSmoke.h | a878d13147d91a026074988ee4903c9dfe3be564 | [] | no_license | highfence/ShootingGameProject | 2b564d09ea02ae64fb65d85b59ecb6e0d170ec53 | 61e57136d52e8b1d980eec304dd474774f239f94 | refs/heads/master | 2021-01-20T12:28:31.574956 | 2017-04-05T06:49:42 | 2017-04-05T06:49:42 | 82,655,552 | 0 | 0 | null | 2017-03-16T10:04:44 | 2017-02-21T08:33:06 | C++ | UTF-8 | C++ | false | false | 328 | h | #pragma once
#include "Effect.h"
class ExplodeSmoke : public Effect
{
public :
ExplodeSmoke() = delete;
ExplodeSmoke(const _In_ Vec);
ExplodeSmoke(
const _In_ Vec,
const _In_ FLOAT,
const _In_ Vec);
~ExplodeSmoke();
private :
void init();
void LoadInitialImg() override;
void InitialDataSubstitude() override;
}; | [
"[email protected]"
] | |
534e4d3031dc97052ded75575351d0ed28da9bfb | 0d653408de7c08f1bef4dfba5c43431897097a4a | /cmajor/cmbs/Error.cpp | 5cb9fc81316595d5daf239f5c41f65152671bd75 | [] | no_license | slaakko/cmajorm | 948268634b8dd3e00f86a5b5415bee894867b17c | 1f123fc367d14d3ef793eefab56ad98849ee0f25 | refs/heads/master | 2023-08-31T14:05:46.897333 | 2023-08-11T11:40:44 | 2023-08-11T11:40:44 | 166,633,055 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,609 | cpp | // =================================
// Copyright (c) 2022 Seppo Laakko
// Distributed under the MIT license
// =================================
#include <cmajor/cmbs/Error.hpp>
#include <cmajor/symbols/Module.hpp>
#include <cmajor/symbols/ModuleCache.hpp>
#include <soulng/util/Unicode.hpp>
namespace cmbs {
using namespace soulng::unicode;
CompileError ParsingExceptionToError(const soulng::lexer::ParsingException& ex)
{
CompileError error;
error.message = ex.Message();
error.project = ex.Project();
error.file = ex.FileName();
soulng::lexer::Span span = ex.GetSpan();
error.line = span.line;
cmajor::symbols::Module* mod = static_cast<cmajor::symbols::Module*>(ex.Module());
if (mod)
{
int startCol = 0;
int endCol = 0;
mod->GetColumns(span, startCol, endCol);
error.scol = startCol;
error.ecol = endCol;
}
return error;
}
std::vector<CompileError> SymbolsExceptionToErrors(const cmajor::symbols::Exception& ex)
{
std::vector<CompileError> errors;
CompileError mainError;
mainError.message = ex.Message();
cmajor::symbols::Module* mod = cmajor::symbols::GetModuleById(ex.DefinedModuleId());
if (mod)
{
Span span = ex.Defined();
std::u32string code = mod->GetErrorLines(span);
mainError.message.append("\n").append(ToUtf8(code));
mainError.project = ToUtf8(mod->Name());
mainError.file = mod->GetFilePath(span.fileIndex);
mainError.line = span.line;
int startCol = 0;
int endCol = 0;
mod->GetColumns(span, startCol, endCol);
mainError.scol = startCol;
mainError.ecol = endCol;
}
errors.push_back(mainError);
for (const std::pair<Span, boost::uuids::uuid>& spanModuleId : ex.References())
{
CompileError referenceError;
referenceError.message = "See:";
cmajor::symbols::Module* mod = cmajor::symbols::GetModuleById(spanModuleId.second);
if (mod)
{
std::u32string code = mod->GetErrorLines(spanModuleId.first);
referenceError.message.append("\n").append(ToUtf8(code));
referenceError.file = mod->GetFilePath(spanModuleId.first.fileIndex);
referenceError.line = spanModuleId.first.line;
int startCol = 0;
int endCol = 0;
mod->GetColumns(spanModuleId.first, startCol, endCol);
referenceError.scol = startCol;
referenceError.ecol = endCol;
errors.push_back(referenceError);
}
}
return errors;
}
} // namespace cmbs
| [
"[email protected]"
] | |
b563f5db9b84bcb6839aacebc6f4c582b248900b | 424d9d65e27cd204cc22e39da3a13710b163f4e7 | /chrome/browser/ui/views/frame/tab_strip_region_view.h | 96ccf699770a115e0ce3985d40a4dc5a9fae614d | [
"BSD-3-Clause"
] | permissive | bigben0123/chromium | 7c5f4624ef2dacfaf010203b60f307d4b8e8e76d | 83d9cd5e98b65686d06368f18b4835adbab76d89 | refs/heads/master | 2023-01-10T11:02:26.202776 | 2020-10-30T09:47:16 | 2020-10-30T09:47:16 | 275,543,782 | 0 | 0 | BSD-3-Clause | 2020-10-30T09:47:18 | 2020-06-28T08:45:11 | null | UTF-8 | C++ | false | false | 2,458 | h | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_
#define CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "ui/views/accessible_pane_view.h"
class TabSearchButton;
class TabStrip;
// Container for the tabstrip, new tab button, and reserved grab handle space.
class TabStripRegionView final : public views::AccessiblePaneView,
views::ViewObserver {
public:
explicit TabStripRegionView(std::unique_ptr<TabStrip> tab_strip);
~TabStripRegionView() override;
// Returns true if the specified rect intersects the window caption area of
// the browser window. |rect| is in the local coordinate space
// of |this|.
bool IsRectInWindowCaption(const gfx::Rect& rect);
// A convenience function which calls |IsRectInWindowCaption()| with a rect of
// size 1x1 and an origin of |point|. |point| is in the local coordinate space
// of |this|.
bool IsPositionInWindowCaption(const gfx::Point& point);
// Called when the colors of the frame change.
void FrameColorsChanged();
TabSearchButton* tab_search_button() { return tab_search_button_; }
// views::AccessiblePaneView:
const char* GetClassName() const override;
void ChildPreferredSizeChanged(views::View* child) override;
gfx::Size GetMinimumSize() const override;
void OnThemeChanged() override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
views::View* GetDefaultFocusableChild() override;
// views::ViewObserver:
void OnViewPreferredSizeChanged(View* view) override;
// TODO(958173): Override OnBoundsChanged to cancel tabstrip animations.
private:
DISALLOW_COPY_AND_ASSIGN(TabStripRegionView);
int CalculateTabStripAvailableWidth();
// Scrolls the tabstrip towards the first tab in the tabstrip.
void ScrollTowardsLeadingTab();
// Scrolls the tabstrip towards the last tab in the tabstrip.
void ScrollTowardsTrailingTab();
views::View* tab_strip_container_;
views::View* reserved_grab_handle_space_;
TabStrip* tab_strip_;
TabSearchButton* tab_search_button_ = nullptr;
views::ImageButton* leading_scroll_button_;
views::ImageButton* trailing_scroll_button_;
};
#endif // CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_
| [
"[email protected]"
] | |
6a5800c8150e8c9144d23429c10f35136b06e222 | 578ceec075394968a5ac0ef3ed5961697d8cd826 | /daemon/DekdCommand.h | 7a1648ba3f971ea0a278f233a006d43f4fa34003 | [] | no_license | olicmoon/dekd | 3938a6f76cdb8b0a9ef915b273f94ac8fa9276d9 | c5a88ec8330a67ce952351970bf5657813977eae | refs/heads/master | 2021-01-19T06:24:54.282288 | 2015-08-31T21:17:06 | 2015-09-01T00:40:38 | 40,740,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 365 | h | /*
* DekdCommand.h
*
* Created on: Aug 17, 2015
* Author: olic
*/
#ifndef DEKDCOMMAND_H_
#define DEKDCOMMAND_H_
#include <FrameworkCommand.h>
class DekdCommand : public FrameworkCommand {
public:
DekdCommand(const char *cmd);
virtual ~DekdCommand() {}
int runCommand(SocketClient *c, int argc, char **argv);
};
#endif /* DEKDCOMMAND_H_ */
| [
"[email protected]"
] | |
378d41da667801b00bd623eb7fc43dcdb5cc28d6 | 2bd4fa284f4c891fa35b7465449ea04534ea01fb | /hdmaproifilter/src/perception/lib/base/registerer.cpp | 6c5407d1b73c0605cbf0c3b88b4f854a302b290e | [] | no_license | Playfish/apollo_perception | cdd74e4a802159ceadc513e9f46ae1799e911ba1 | 6a50f529f0f6d789d2a06077480e79c9f4bc68c8 | refs/heads/master | 2021-09-14T13:42:07.159927 | 2018-05-14T13:51:20 | 2018-05-14T13:51:20 | 113,520,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | /******************************************************************************
* Copyright 2017 The Apollo 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 "perception/lib/base/registerer.h"
#include <string>
#include <vector>
namespace apollo {
namespace perception {
BaseClassMap& GlobalFactoryMap() {
static BaseClassMap factory_map;
return factory_map;
}
bool GetRegisteredClasses(
const std::string& base_class_name,
std::vector<std::string>* registered_derived_classes_names) {
CHECK_NOTNULL(registered_derived_classes_names);
BaseClassMap& map = GlobalFactoryMap();
auto iter = map.find(base_class_name);
if (iter == map.end()) {
AERROR << "class not registered:" << base_class_name;
return false;
}
for (auto pair : iter->second) {
registered_derived_classes_names->push_back(pair.first);
}
return true;
}
} // namespace perception
} // namespace apollo
| [
"[email protected]"
] | |
c0b9cd92c56f6f91ed9a7a6f7b5ae7a03a9d9b74 | 406b6f3e8355bcab9add96f3cff044823186fe37 | /src/Simulation/osg_2d_simulation/quad.cpp | 01c1fcc1ce18c295f1b29ec90b3b6adace8f46c2 | [] | no_license | Micalson/puppet | 96fd02893f871c6bbe0abff235bf2b09f14fe5d9 | d51ed9ec2f2e4bf65dc5081a9d89d271cece28b5 | refs/heads/master | 2022-03-28T22:43:13.863185 | 2019-12-26T13:52:00 | 2019-12-26T13:52:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,295 | cpp | #include "quad.h"
#include <osgWrapper\UtilCreator.h>
Quad::Quad()
{
m_node = new OSGWrapper::QuadAttributeUtilNode(1);
m_geometry = OSGWrapper::UtilCreator::CreateUnitQuad();
m_node->AddChild(m_geometry);
}
Quad::~Quad()
{
}
void Quad::SetOffset(const osg::Vec2f& offset)
{
m_offset = offset;
UpdateGeometry();
}
void Quad::SetSize(const osg::Vec2f& size)
{
m_size = size;
UpdateGeometry();
}
void Quad::SetRect(const osg::Vec2f& offset, const osg::Vec2f& size)
{
m_offset = offset;
m_size = size;
UpdateGeometry();
}
void Quad::UpdateGeometry()
{
osg::Vec2Array* coord_array = dynamic_cast<osg::Vec2Array*>(m_geometry->getVertexAttribArray(0));
if (coord_array)
{
coord_array->at(0) = m_offset;
coord_array->at(1) = m_offset + osg::Vec2f(m_size.x(), 0.0f);
coord_array->at(2) = m_offset + osg::Vec2f(m_size.x(), m_size.y());
coord_array->at(3) = m_offset + osg::Vec2f(0.0f, m_size.y());
coord_array->dirty();
}
}
OSGWrapper::QuadAttributeUtilNode* Quad::Generate()
{
return m_node;
}
OSGWrapper::UIQuad* Quad::HitTest(float x, float y)
{
OSGWrapper::UIQuad* q = OSGWrapper::UIQuad::HitTest(x, y);
if (q) return q;
if (x >= m_offset.x() && x <= m_offset.x() + m_size.x() &&
y >= m_offset.y() && y <= m_offset.y() + m_size.y())
return this;
return 0;
} | [
"[email protected]"
] | |
48c0f65f815f5a8f95648c04f8d7974b965a502f | a88750ab34c33c8a00a7d653205c15fd429aac94 | /src/bip32/hdwalletutil.cpp | 15c54a63cda010516a0f02bb86512a3b6f4d10dd | [
"MIT"
] | permissive | FromHDDtoSSD/SorachanCoin-qt | 8ccb4b1341b0e8228f93e101b75f741b99d49de0 | 9dff8dccd71518eea9a1ff80671cccf31915ca09 | refs/heads/master | 2022-09-08T01:14:20.838440 | 2022-08-27T16:39:36 | 2022-08-27T16:39:36 | 144,701,661 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,845 | cpp | // Copyright (c) 2017-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bip32/hdwalletutil.h>
#include <util/logging.h>
#include <util/system.h>
#include <util/args.h>
fs::path hdwalletutil::GetWalletDir() {
fs::path path;
if (ARGS.IsArgSet("-walletdir")) {
path = ARGS.GetArg("-walletdir", "");
if (! fs::is_directory(path)) {
// If the path specified doesn't exist, we return the deliberately
// invalid empty string.
path = "";
}
} else {
path = lutil::GetDataDir();
// If a wallets directory exists, use that, otherwise default to GetDataDir
if (fs::is_directory(path / "wallets")) {
path /= "wallets";
}
}
return path;
}
static bool IsBerkeleyBtree(const fs::path &path) {
// A Berkeley DB Btree file has at least 4K.
// This check also prevents opening lock files.
boost::system::error_code ec;
auto size = fs::file_size(path, ec);
if (ec) logging::LogPrintf("%s: %s %s\n", __func__, ec.message(), path.string());
if (size < 4096) return false;
fsbridge::ifstream file(path, std::ios::binary);
if (! file.is_open()) return false;
file.seekg(12, std::ios::beg); // Magic bytes start at offset 12
uint32_t data = 0;
file.read((char*) &data, sizeof(data)); // Read 4 bytes of file to compare against magic
// Berkeley DB Btree magic bytes, from:
// https://github.com/file/file/blob/5824af38469ec1ca9ac3ffd251e7afe9dc11e227/magic/Magdir/database#L74-L75
// - big endian systems - 00 05 31 62
// - little endian systems - 62 31 05 00
return data == 0x00053162 || data == 0x62310500;
}
std::vector<fs::path> hdwalletutil::ListWalletDir() {
const fs::path wallet_dir = GetWalletDir();
const size_t offset = wallet_dir.string().size() + 1;
std::vector<fs::path> paths;
boost::system::error_code ec;
for (auto it = fs::recursive_directory_iterator(wallet_dir, ec); it != fs::recursive_directory_iterator(); it.increment(ec)) {
if (ec) {
logging::LogPrintf("%s: %s %s\n", __func__, ec.message(), it->path().string());
continue;
}
// Get wallet path relative to walletdir by removing walletdir from the wallet path.
// This can be replaced by boost::filesystem::lexically_relative once boost is bumped to 1.60.
const fs::path path = it->path().string().substr(offset);
if (it->status().type() == fs::directory_file && IsBerkeleyBtree(it->path() / "wallet.dat")) {
// Found a directory which contains wallet.dat btree file, add it as a wallet.
paths.emplace_back(path);
} else if (it.level() == 0 && it->symlink_status().type() == fs::regular_file && IsBerkeleyBtree(it->path())) {
if (it->path().filename() == "wallet.dat") {
// Found top-level wallet.dat btree file, add top level directory ""
// as a wallet.
paths.emplace_back();
} else {
// Found top-level btree file not called wallet.dat. Current bitcoin
// software will never create these files but will allow them to be
// opened in a shared database environment for backwards compatibility.
// Add it to the list of available wallets.
paths.emplace_back(path);
}
}
}
return paths;
}
hdwalletutil::WalletLocation::WalletLocation(const std::string &name)
: m_name(name)
, m_path(fs::absolute(name, GetWalletDir()))
{
}
bool hdwalletutil::WalletLocation::Exists() const {
return fs::symlink_status(m_path).type() != fs::file_not_found;
}
| [
"[email protected]"
] | |
6290623071614e1a5caf46e39ddc6e959b56f6cb | 256767f888195384e8a91bff0864d0afc3f7e4e9 | /AIS_TrackingAndDetection/tests/moc_euclideanDistance.cpp | 8e8d5da02912f8bd3b87c8b1bc3d57a65875d708 | [] | no_license | HelenHarman/AIS_Object_Tracking | a71b9c2df78c02180b7bb1ac2561a03a570ef935 | 3ec7128a739387299ac3e4a648e8c8f30274af97 | refs/heads/master | 2021-01-15T08:28:06.415775 | 2016-01-23T13:01:20 | 2016-01-23T13:01:20 | 43,375,968 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35 | cpp | #include "moc_euclideanDistance.h"
| [
"[email protected]"
] | |
55d577d1a75a9ab17fa7b5d2dfee420f67de653e | c4d0cc1b8f7a0c4eefb405e105ac9727e1a98aad | /FlashCards/src/StringWordSplitter.cpp | fdab3206d76415785a84cd483dcc64795aae68ce | [] | no_license | KNITcpp/FlashCards | 513ed1f7fb2829692538636e0e6b65847bad8da9 | 7ac1c359d6a6f0aa5639bb64a39696b2f5eb63e2 | refs/heads/master | 2020-03-07T14:15:49.733326 | 2018-05-28T09:43:41 | 2018-05-28T09:43:41 | 127,522,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | cpp |
#include "StringWordSplitter.h"
#include <string>
#include <vector>
StringWordSplitter::StringWordSplitter(std::wstring strToBeSplitted)
{
std::wstring singleWord;
for(int i=0; i<strToBeSplitted.length(); ++i)
{
if(strToBeSplitted[i] == L' ')
{
if(singleWord.size()!=0)
{
words.push_back(singleWord);
singleWord.clear();
}
}
else
singleWord.push_back(strToBeSplitted[i]);
}
if(singleWord.size()!=0) //something left to push after loop
words.push_back(singleWord);
}
| [
"[email protected]"
] | |
bab79ca9935598c0d5582f4c76d7f8c63fa390e7 | 0084166695a3bea4f4285eadd57d03607314c149 | /TouchGFX/target/generated/TouchGFXGeneratedHAL.cpp | ae76144669a0671e69c7eb5f250a13bce5357755 | [] | no_license | Zhangzhicheng001/Magnetic_shielding_system | 142556f79ada0e9f1b4addcbeaf69441a0f515b6 | 7714e14758de2a30c920ab9ad74ec9dc1e094820 | refs/heads/main | 2023-07-08T11:18:05.720893 | 2021-08-09T10:25:02 | 2021-08-09T10:25:02 | 391,795,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,986 | cpp | /**
******************************************************************************
* File Name : TouchGFXGeneratedHAL.cpp
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include <TouchGFXGeneratedHAL.hpp>
#include <touchgfx/hal/OSWrappers.hpp>
#include <gui/common/FrontendHeap.hpp>
#include <touchgfx/hal/GPIO.hpp>
#include "stm32h7xx.h"
#include "stm32h7xx_hal_ltdc.h"
using namespace touchgfx;
namespace
{
static uint16_t lcd_int_active_line;
static uint16_t lcd_int_porch_line;
}
void TouchGFXGeneratedHAL::initialize()
{
HAL::initialize();
registerEventListener(*(Application::getInstance()));
setFrameBufferStartAddresses((void*)0xC0000000, (void*)0xC0119400, (void*)0);
}
void TouchGFXGeneratedHAL::configureInterrupts()
{
NVIC_SetPriority(DMA2D_IRQn, 9);
NVIC_SetPriority(LTDC_IRQn, 9);
}
void TouchGFXGeneratedHAL::enableInterrupts()
{
NVIC_EnableIRQ(DMA2D_IRQn);
NVIC_EnableIRQ(LTDC_IRQn);
}
void TouchGFXGeneratedHAL::disableInterrupts()
{
NVIC_DisableIRQ(DMA2D_IRQn);
NVIC_DisableIRQ(LTDC_IRQn);
}
void TouchGFXGeneratedHAL::enableLCDControllerInterrupt()
{
lcd_int_active_line = (LTDC->BPCR & 0x7FF) - 1;
lcd_int_porch_line = (LTDC->AWCR & 0x7FF) - 1;
/* Sets the Line Interrupt position */
LTDC->LIPCR = lcd_int_active_line;
/* Line Interrupt Enable */
LTDC->IER |= LTDC_IER_LIE;
}
bool TouchGFXGeneratedHAL::beginFrame()
{
return HAL::beginFrame();
}
void TouchGFXGeneratedHAL::endFrame()
{
HAL::endFrame();
}
uint16_t* TouchGFXGeneratedHAL::getTFTFrameBuffer() const
{
return (uint16_t*)LTDC_Layer1->CFBAR;
}
void TouchGFXGeneratedHAL::setTFTFrameBuffer(uint16_t* adr)
{
LTDC_Layer1->CFBAR = (uint32_t)adr;
/* Reload immediate */
LTDC->SRCR = (uint32_t)LTDC_SRCR_IMR;
}
void TouchGFXGeneratedHAL::flushFrameBuffer(const touchgfx::Rect& rect)
{
HAL::flushFrameBuffer(rect);
// If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then
// the DCache must be flushed prior to DMA2D accessing it. That's done
// using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the
// "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work.
if (SCB->CCR & SCB_CCR_DC_Msk)
{
SCB_CleanInvalidateDCache();
}
}
bool TouchGFXGeneratedHAL::blockCopy(void* RESTRICT dest, const void* RESTRICT src, uint32_t numBytes)
{
return HAL::blockCopy(dest, src, numBytes);
}
void TouchGFXGeneratedHAL::InvalidateCache()
{
// If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then
// the DCache must be flushed prior to DMA2D accessing it. That's done
// using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the
// "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work.
if (SCB->CCR & SCB_CCR_DC_Msk)
{
SCB_CleanInvalidateDCache();
}
}
void TouchGFXGeneratedHAL::FlushCache()
{
// If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then
// the DCache must be flushed prior to DMA2D accessing it. That's done
// using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the
// "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work.
if (SCB->CCR & SCB_CCR_DC_Msk)
{
SCB_CleanInvalidateDCache();
}
}
extern "C"
{
void HAL_LTDC_LineEventCallback(LTDC_HandleTypeDef* hltdc)
{
if (LTDC->LIPCR == lcd_int_active_line)
{
//entering active area
HAL_LTDC_ProgramLineEvent(hltdc, lcd_int_porch_line);
HAL::getInstance()->vSync();
OSWrappers::signalVSync();
// Swap frame buffers immediately instead of waiting for the task to be scheduled in.
// Note: task will also swap when it wakes up, but that operation is guarded and will not have
// any effect if already swapped.
HAL::getInstance()->swapFrameBuffers();
GPIO::set(GPIO::VSYNC_FREQ);
}
else
{
//exiting active area
HAL_LTDC_ProgramLineEvent(hltdc, lcd_int_active_line);
GPIO::clear(GPIO::VSYNC_FREQ);
HAL::getInstance()->frontPorchEntered();
}
}
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| [
"[email protected]"
] |