blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
df92589d7f5c75d47f0a81291aeb9b0523d5d9a6 | e8977a44852929dce08aceecf32f6e57051f00de | /chromeos/services/secure_channel/fake_single_client_message_proxy.h | 0054cf332462ff068b4f25d3e67432851f4d3637 | [
"BSD-3-Clause"
] | permissive | nebulabox/chromium | 566900a62983f441bf57346f61251bb90aa82a11 | cb491c4cb294b8b0862e59f0b34a4f702d473e69 | refs/heads/master | 2023-03-09T20:40:00.935811 | 2018-05-24T13:08:26 | 2018-05-24T13:08:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,602 | h | // Copyright 2018 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 CHROMEOS_SERVICES_SECURE_CHANNEL_FAKE_SINGLE_CLIENT_MESSAGE_PROXY_H_
#define CHROMEOS_SERVICES_SECURE_CHANNEL_FAKE_SINGLE_CLIENT_MESSAGE_PROXY_H_
#include <string>
#include <utility>
#include "base/callback.h"
#include "base/macros.h"
#include "base/unguessable_token.h"
#include "chromeos/services/secure_channel/single_client_message_proxy.h"
namespace chromeos {
namespace secure_channel {
// Test SingleClientMessageProxy implementation.
class FakeSingleClientMessageProxy : public SingleClientMessageProxy {
public:
FakeSingleClientMessageProxy(
Delegate* delegate,
base::OnceCallback<void(const base::UnguessableToken&)>
destructor_callback =
base::OnceCallback<void(const base::UnguessableToken&)>());
~FakeSingleClientMessageProxy() override;
bool was_remote_device_disconnection_handled() {
return was_remote_device_disconnection_handled_;
}
const std::vector<std::pair<std::string, std::string>>& processed_messages() {
return processed_messages_;
}
// Public for testing.
using SingleClientMessageProxy::NotifySendMessageRequested;
using SingleClientMessageProxy::NotifyClientDisconnected;
using SingleClientMessageProxy::GetConnectionMetadataFromDelegate;
private:
// SingleClientMessageProxy:
void HandleReceivedMessage(const std::string& feature,
const std::string& payload) override;
void HandleRemoteDeviceDisconnection() override;
base::OnceCallback<void(const base::UnguessableToken&)> destructor_callback_;
std::vector<std::pair<std::string, std::string>> processed_messages_;
bool was_remote_device_disconnection_handled_ = false;
DISALLOW_COPY_AND_ASSIGN(FakeSingleClientMessageProxy);
};
// Test SingleClientMessageProxy::Delegate implementation.
class FakeSingleClientMessageProxyDelegate
: public SingleClientMessageProxy::Delegate {
public:
FakeSingleClientMessageProxyDelegate();
~FakeSingleClientMessageProxyDelegate() override;
std::vector<std::tuple<std::string, std::string, base::OnceClosure>>&
send_message_requests() {
return send_message_requests_;
}
void set_connection_metadata(
const mojom::ConnectionMetadata& connection_metadata) {
connection_metadata_ = connection_metadata;
}
void set_on_client_disconnected_closure(
base::OnceClosure on_client_disconnected_closure) {
on_client_disconnected_closure_ = std::move(on_client_disconnected_closure);
}
const base::UnguessableToken& disconnected_proxy_id() {
return disconnected_proxy_id_;
}
private:
// SingleClientMessageProxy::Delegate:
void OnSendMessageRequested(const std::string& message_feaure,
const std::string& message_payload,
base::OnceClosure on_sent_callback) override;
const mojom::ConnectionMetadata& GetConnectionMetadata() override;
void OnClientDisconnected(const base::UnguessableToken& proxy_id) override;
std::vector<std::tuple<std::string, std::string, base::OnceClosure>>
send_message_requests_;
mojom::ConnectionMetadata connection_metadata_;
base::OnceClosure on_client_disconnected_closure_;
base::UnguessableToken disconnected_proxy_id_;
DISALLOW_COPY_AND_ASSIGN(FakeSingleClientMessageProxyDelegate);
};
} // namespace secure_channel
} // namespace chromeos
#endif // CHROMEOS_SERVICES_SECURE_CHANNEL_FAKE_SINGLE_CLIENT_MESSAGE_PROXY_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b69dfb72b2c2515c4349ce6a8afb75e9808ca1db | 2f7c0f6cbb817f981aecd4ad0aa7d47af55a0d70 | /wavelet4d.h | 2b22826aef9a1cbfddec520ff29f6b3e7fa8ba8e | [] | no_license | shaomeng/vapor_addon | 53e5652092c4cec41edb1407690d3c95e06bf845 | eb56e65bcafbaed8b2b0e5c28795fcb283afc1ed | refs/heads/master | 2021-01-18T18:21:37.567021 | 2017-04-06T23:58:04 | 2017-04-06T23:58:04 | 33,807,605 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,126 | h | /*
* This is the main library that Sam attemps to apply 4D wavelet widely.
* It also employs parallel mechanisms to speed up the calculation.
* Currently it divides big data size_to blocks of 64^3,
* and uses OpenMP to assign each block to a CPU core.
*
* Programmer: Samuel Li
* Date: 12/8/2015
*/
#ifndef _Wavelet4D_
#define _Wavelet4D_
#include <iostream>
#include <cstdio>
#include <cassert>
#include <string>
#include <vector>
#include <omp.h>
#include "cube3d.h"
#include "slicegroup.h"
#include <sys/stat.h>
#define EVALUATE
class Wavelet4D{
public:
Wavelet4D( long NX, long NY, long NZ, long NT );
~Wavelet4D();
void SetPath( const std::string &path );
/*
* Filenames differ at the index number.
*/
void GenerateFilenames( const std::string &name, long startIdx );
void GenerateBkpFilenames( const std::string &path, const std::string &name, long startIdx );
int ParallelExec();
/* only performs DWT in the time dimension */
int TimeDimParallelExec();
/* only performs DWT in the X, Y, or Z dimension */
void XDimParallelExec();
void YDimParallelExec();
void ZDimParallelExec();
void PrintBlockIndices();
void PrintFilenames();
//double FindMax( const double* arr, long len );
//double FindRMS( const double* arr, long len);
void SetCRatio( int i ) { _cratio = i; }
void StartMonitor();
void Output3DReconstruct();
void Output4DReconstruct();
void PutValToWrite( long x, long y, long z, long t, float v );
protected:
long _NX, _NY, _NZ; // spatial dimensions
long _NT; // temporal dimension
long _BLOCKDIM; // dimension of small blocks
long _BLOCKNUM; // total number of blocks
int _cratio; // compression ratio
std::vector<std::string> _filenames;
std::vector<std::string> _bkpFilenames;
std::string _wavename;
std::string _path;
long* _block_indices; // stores indices for each block at one time step
// 6 indices to specify a block:
// startX, endX, startY, endY, startZ, endZ
void CalcBlockIndices();
float** _reconstruct_buf; // _NT bufs in total;
// each buf contains one reconstructed file
};
#endif
| [
"shaomenglee@gmail.com"
] | shaomenglee@gmail.com |
97e67430b6eb11034ed1df1b033cb381abc368df | dbd4be4155fa227e1268b091147c4437a2f215be | /C++/comand/cont3/cont3_f.cpp | 5fc6b061d0f2d471ea2bb906e47323b41647f0f6 | [] | no_license | pshpis/School_olymp | 5bdf8e885050f80e68c8407940c7289d3d413592 | 723b6121cc1a0746d0911c5a79076d9589a75839 | refs/heads/main | 2023-03-24T08:34:47.600204 | 2021-03-17T08:20:39 | 2021-03-17T08:20:39 | 348,629,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define watch(x) cout << (#x) << " is " << (x) << endl
#define pb push_back
#define mp make_pair
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
double v, v_;
cin>>v>>v_;
double l, l_;
cin>>l>>l_;
if (l/v==l_/v_ || (l+l_)/v==(l+l_)/v_) cout<<"YES";
else cout<<"NO";
}
| [
"51034972+pshpis@users.noreply.github.com"
] | 51034972+pshpis@users.noreply.github.com |
d0f8f7fb306e45c961e4f362cdd1e4f81161665c | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/fiber/libs/fiber/test/test_condition.cpp | 939928344698af4a556a5331ea83b2a35604c271 | [
"BSL-1.0"
] | permissive | 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 | 5,932 | cpp |
// Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <cstdlib>
#include <iostream>
#include <map>
#include <stdexcept>
#include <vector>
#include <boost/bind.hpp>
#include <boost/cstdint.hpp>
#include <boost/function.hpp>
#include <boost/ref.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/utility.hpp>
#include <boost/fiber.hpp>
int value = 0;
void notify_one_fn( boost::fibers::condition & cond)
{
cond.notify_one();
}
void notify_all_fn( boost::fibers::condition & cond)
{
cond.notify_all();
}
void wait_fn(
boost::fibers::mutex & mtx,
boost::fibers::condition & cond)
{
boost::fibers::mutex::scoped_lock lk( mtx);
cond.wait( lk);
++value;
}
void test_case_1()
{
value = 0;
boost::fibers::scheduler<> sched;
boost::fibers::mutex mtx( sched);
boost::fibers::condition cond( sched);
sched.make_fiber(
wait_fn,
boost::ref( mtx),
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
sched.make_fiber(
notify_one_fn,
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK_EQUAL( std::size_t( 2), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 0), sched.size() );
BOOST_CHECK_EQUAL( 1, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 0), sched.size() );
BOOST_CHECK_EQUAL( 1, value);
}
void test_case_2()
{
value = 0;
boost::fibers::scheduler<> sched;
boost::fibers::mutex mtx( sched);
boost::fibers::condition cond( sched);
sched.make_fiber(
wait_fn,
boost::ref( mtx),
boost::ref( cond),
boost::fiber::default_stacksize);
sched.make_fiber(
wait_fn,
boost::ref( mtx),
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 2), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 2), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 2), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
sched.make_fiber(
notify_one_fn,
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK_EQUAL( std::size_t( 3), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( sched.run() );
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 1, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 1, value);
sched.make_fiber(
notify_one_fn,
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 1, value);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 0), sched.size() );
BOOST_CHECK_EQUAL( 2, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 0), sched.size() );
BOOST_CHECK_EQUAL( 2, value);
}
void test_case_3()
{
value = 0;
boost::fibers::scheduler<> sched;
boost::fibers::mutex mtx( sched);
boost::fibers::condition cond( sched);
sched.make_fiber(
wait_fn,
boost::ref( mtx),
boost::ref( cond),
boost::fiber::default_stacksize);
sched.make_fiber(
wait_fn,
boost::ref( mtx),
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 2), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 2), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 2), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
sched.make_fiber(
notify_all_fn,
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK_EQUAL( std::size_t( 3), sched.size() );
BOOST_CHECK_EQUAL( 0, value);
BOOST_CHECK( sched.run() );
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 1, value);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 0), sched.size() );
BOOST_CHECK_EQUAL( 2, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 0), sched.size() );
BOOST_CHECK_EQUAL( 2, value);
sched.make_fiber(
wait_fn,
boost::ref( mtx),
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 2, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 2, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 1), sched.size() );
BOOST_CHECK_EQUAL( 2, value);
sched.make_fiber(
notify_all_fn,
boost::ref( cond),
boost::fiber::default_stacksize);
BOOST_CHECK( sched.run() );
BOOST_CHECK( sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 0), sched.size() );
BOOST_CHECK_EQUAL( 3, value);
BOOST_CHECK( ! sched.run() );
BOOST_CHECK_EQUAL( std::size_t( 0), sched.size() );
BOOST_CHECK_EQUAL( 3, value);
}
boost::unit_test::test_suite * init_unit_test_suite( int, char* [])
{
boost::unit_test::test_suite * test =
BOOST_TEST_SUITE("Boost.Fiber: condition test suite");
test->add( BOOST_TEST_CASE( & test_case_1) );
test->add( BOOST_TEST_CASE( & test_case_2) );
test->add( BOOST_TEST_CASE( & test_case_3) );
return test;
}
| [
"oliver.kowalke@gmail.com"
] | oliver.kowalke@gmail.com |
039d6e5ac401157204e316d1fe1430214040057c | dad4eecc4d69ddf3e8229ab38b127fd593b7fcec | /Pizza.hpp | 658928fb330021280c9a9c50c9af3f0555e916fd | [] | no_license | Nostar42/Hash2021 | 8210640ca761826e499a982ba61bca20b13832a8 | cd721dac24b364043a96296c7bd0686297da5ad6 | refs/heads/main | 2023-02-17T05:34:01.552932 | 2021-01-14T02:32:21 | 2021-01-14T02:32:21 | 329,480,704 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 57 | hpp | #pragma once
class pizza{
public:
private:
};
| [
"cjp56@cs-ssh.argo.uwf.edu"
] | cjp56@cs-ssh.argo.uwf.edu |
a0d5191af9c885482ab58ef8046ac23bc3ba7114 | c3081f8f60de5d36883b38ab789cfc7ad0bc3902 | /Atom/test/class_2.h | eddf185d5d038a9d356407e66d67e8cbe41d1ba3 | [] | no_license | Arrygon/atomWin7 | 68fe7e799eb1e47a32b8ce9ba354687407c309cc | 10aa418b5cf12640934f3d79bd0e09063e11a663 | refs/heads/master | 2020-03-18T17:53:57.804007 | 2018-06-03T20:36:55 | 2018-06-03T20:36:55 | 135,058,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | h | #include <iostream>
#include <windows.h>
using namespace std;
int abc(){
string x;
int b;
cout << "Hello I am your PC. what's your name ? " << endl;
cin >> x;
cout << x << " how old are you ?" << endl;
cin >> b;
if(b == 16){
cout << "Do you want to know how old am I ?" << endl;
}else{
cout << "No you are not " << b << " years old." << endl;
}
}
| [
"noreply@github.com"
] | Arrygon.noreply@github.com |
b072ff90afc734d809ac74b6131648c89d734a03 | 5bfedccc61ab302c515521a1fb1231240cea6085 | /FSTransfer/FSTransfer.h | dc88e4a6033d9b3d345a40db1507a21817fa0185 | [] | no_license | chxj1980/net_uv | bcaa6f67af711d04fe909427189dcd8fbc99a428 | ad846850e27de4f5b6730de2aabb9fd992a472cf | refs/heads/master | 2022-04-07T19:12:17.188008 | 2020-03-11T13:31:17 | 2020-03-11T13:31:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,087 | h | #pragma once
#include <inttypes.h>
#include <string>
#include <map>
#include <functional>
#include <memory>
class FSTransfer;
using FST_Output = std::function<void(FSTransfer* fst, char* data, uint32_t len)>;
struct FST_Task;
class FSTransfer
{
public:
FSTransfer();
virtual ~FSTransfer();
int32_t postFile(const std::string& file);
void downLoadFile(const std::string& file);
void input(char* data, int32_t len);
void online(bool isOnline);
inline void setOutput(FST_Output output);
void updateFrame();
protected:
void on_PostFile(void* data, uint32_t len);
void on_PostFileResult(void* data, uint32_t len);
void on_Check(void* data, uint32_t len);
uint32_t getFileSize(const char* name);
void sendFileData(uint32_t begin);
void recvFileData(uint32_t begin, char* data, uint32_t len);
void clearTask();
protected:
FST_Output m_output;
std::shared_ptr<FST_Task> m_task;
std::string m_filename;
enum Duty
{
Send,
Recv,
None
};
Duty m_duty;
char* m_readBuf;
};
void FSTransfer::setOutput(FST_Output output)
{
m_output = output;
}
| [
"www.tkzc@foxmail.com"
] | www.tkzc@foxmail.com |
5c8cd9ed2821d00de73e7d429f8961cebd479903 | 57240655c566d7634bfe47cae56227a8c655859b | /Windows/Demo/TestEcho-Http-4C/SyncClient/ClientDlg.h | 84641328c0563283dfed79afaa65e611e51d3c1a | [
"Apache-2.0"
] | permissive | Garsha/HP-Socket | 208c0863e9c6723a4715e75215cbd40256dfdab7 | 34d8f82974aecc20f16d3322cb4691a47881430b | refs/heads/master | 2020-03-27T21:18:05.668420 | 2019-12-31T15:33:03 | 2019-12-31T15:33:03 | 147,133,510 | 1 | 0 | NOASSERTION | 2019-12-31T15:33:04 | 2018-09-03T00:46:24 | C | UTF-8 | C++ | false | false | 3,211 | h |
// ClientDlg.h : header file
//
#pragma once
#include "afxwin.h"
#include "../../../Src/HPSocket4C-SSL.h"
#include "../../Global/helper.h"
// CClientDlg dialog
class CClientDlg : public CDialogEx
{
// Construction
public:
CClientDlg(CWnd* pParent = NULL); // standard constructor
~CClientDlg(); // standard destructor
// Dialog Data
enum { IDD = IDD_CLIENT_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL PreTranslateMessage(MSG* pMsg);
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnBnClickedHeaderAdd();
afx_msg void OnBnClickedSend();
void SendHttp();
void SendWebSocket();
afx_msg void OnBnClickedStart();
afx_msg void OnBnClickedStop();
afx_msg LRESULT OnUserInfoMsg(WPARAM wp, LPARAM lp);
afx_msg void OnCbnSelchangeMethod();
afx_msg int OnVKeyToItem(UINT nKey, CListBox* pListBox, UINT nIndex);
DECLARE_MESSAGE_MAP()
private:
void SetAppState(EnAppState state);
BOOL CheckStarted(BOOL bRestart = TRUE);
static CStringA GetHeaderSummary(HP_HttpSyncClient pSender, LPCSTR lpszSep = " ", int iSepCount = 0, BOOL bWithContentLength = TRUE);
private:
static En_HP_HandleResult __stdcall OnConnect(HP_Client pSender, CONNID dwConnID);
static En_HP_HandleResult __stdcall OnClose(HP_Client pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode);
static En_HP_HttpParseResult __stdcall OnHeader(HP_HttpClient pSender, CONNID dwConnID, LPCSTR lpszName, LPCSTR lpszValue);
static En_HP_HttpParseResult __stdcall OnHeadersComplete(HP_HttpClient pSender, CONNID dwConnID);
static En_HP_HttpParseResult __stdcall OnBody(HP_HttpClient pSender, CONNID dwConnID, const BYTE* pData, int iLength);
static En_HP_HttpParseResult __stdcall OnChunkHeader(HP_HttpClient pSender, CONNID dwConnID, int iLength);
static En_HP_HttpParseResult __stdcall OnChunkComplete(HP_HttpClient pSender, CONNID dwConnID);
static En_HP_HttpParseResult __stdcall OnMessageComplete(HP_HttpClient pSender, CONNID dwConnID);
static En_HP_HttpParseResult __stdcall OnUpgrade(HP_HttpClient pSender, CONNID dwConnID, EnHttpUpgradeType enUpgradeType);
static En_HP_HandleResult __stdcall OnWSMessageHeader(HP_HttpClient pSender, HP_CONNID dwConnID, BOOL bFinal, BYTE iReserved, BYTE iOperationCode, const BYTE lpszMask[4], ULONGLONG ullBodyLen);
static En_HP_HandleResult __stdcall OnWSMessageBody(HP_HttpClient pSender, HP_CONNID dwConnID, const BYTE* pData, int iLength);
static En_HP_HandleResult __stdcall OnWSMessageComplete(HP_HttpClient pSender, HP_CONNID dwConnID);
private:
CButton m_Send;
CListBox m_Info;
CEdit m_Address;
CEdit m_Port;
CButton m_UseCookie;
CButton m_Listener;
CButton m_Start;
CButton m_Stop;
CComboBox m_Method;
CComboBox m_Schema;
CEdit m_Path;
CEdit m_HeaderName;
CEdit m_HeaderValue;
CButton m_HeaderAdd;
CListBox m_Headers;
CEdit m_Body;
BOOL m_bUseCookie;
BOOL m_bListener;
BOOL m_bWebSocket;
EnAppState m_enState;
static CClientDlg* m_spThis;
HP_HttpClientListener m_HttpClientListener;
HP_HttpSyncClient m_HttpSyncClient;
};
| [
"liangdongcheng@lechebang.com"
] | liangdongcheng@lechebang.com |
152296e6ec301cfec163c5bc5c070b5e664d48e3 | ce97f75bdcaff729d1d14c01675b5da59f392a68 | /Snack/zhouyuView.cpp | e7280cdf2f65f8474c11ba11e5ce370e5d2a3cc2 | [] | no_license | mrzhouyu/C-Project-ClassWork | e6555711a32e36ef26645bdff7a262e5b8e412a9 | ccc5d1c972285adc723e6a3719123a8a5c60f951 | refs/heads/master | 2021-08-31T16:24:36.508625 | 2017-12-22T02:21:13 | 2017-12-22T02:21:13 | 115,065,516 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,105 | cpp | // zhouyuView.cpp : implementation of the CZhouyuView class
//
#include "stdafx.h"
#include "zhouyu.h"
#include "zhouyuDoc.h"
#include "zhouyuView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
struct Snake
{
int x,y;
int len;
int direct;
}Snake[50];
struct Food
{
int x;
int y;
int isfood;
}Food;
/////////////////////////////////////////////////////////////////////////////
// CZhouyuView
IMPLEMENT_DYNCREATE(CZhouyuView, CView)
BEGIN_MESSAGE_MAP(CZhouyuView, CView)
//{{AFX_MSG_MAP(CZhouyuView)
ON_WM_RBUTTONDOWN()
ON_WM_TIMER()
ON_WM_KEYDOWN()
ON_COMMAND(IDM_START, OnStart)
ON_COMMAND(IDM_PAUSE, OnPause)
ON_COMMAND(IDM_CONTINUE, OnContinue)
ON_COMMAND(IDM_EXIT, OnExit)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CZhouyuView construction/destruction
CZhouyuView::CZhouyuView()
{
// TODO: add construction code here
}
CZhouyuView::~CZhouyuView()
{
}
BOOL CZhouyuView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CZhouyuView drawing
void CZhouyuView::OnDraw(CDC* pDC)
{
CZhouyuDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CBrush backBrush(RGB(100,100,0));
CBrush* pOldBrush = pDC->SelectObject(&backBrush);
CRect rect;
pDC->GetClipBox(&rect);
pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(),PATCOPY);
pDC->SelectObject(pOldBrush);
pDC->Rectangle(19,19,501,501);
oninit();
}
/////////////////////////////////////////////////////////////////////////////
// CZhouyuView printing
BOOL CZhouyuView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CZhouyuView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CZhouyuView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CZhouyuView diagnostics
#ifdef _DEBUG
void CZhouyuView::AssertValid() const
{
CView::AssertValid();
}
void CZhouyuView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CZhouyuDoc* CZhouyuView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CZhouyuDoc)));
return (CZhouyuDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CZhouyuView message handlers
void CZhouyuView::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CString str;
str.Format("%d,%d",point.x,point.y);
AfxMessageBox(str);
CView::OnRButtonDown(nFlags, point);
CView::OnRButtonDown(nFlags, point);
CView::OnRButtonDown(nFlags, point);
}
void CZhouyuView::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
CDC *pDC=GetDC();
CString soure;
if(Snake[0].len==2)SetTimer(1,370,NULL);
if(Snake[0].len==3)SetTimer(1,270,NULL);
if(Snake[0].len==6)SetTimer(1,200,NULL);
if(Snake[0].len==9)SetTimer(1,100,NULL);
soure.Format("得分:%d!",(Snake[0].len-3)*10);
//撞界判断
if(Snake[0].x*20<=37||Snake[0].y*20<=37||Snake[0].x*20>=462||Snake[0].y*20>=462)
{
KillTimer(1);
AfxMessageBox(soure);
// s=0;
}
//蛇身相撞判断
if(Snake[0].len>3)
for(int sn=Snake[0].len-1;sn>0;sn--)
{
if(Snake[0].x*20==Snake[sn].x*20&&Snake[0].y*20==Snake[sn].y*20)
{
KillTimer(1);
AfxMessageBox(soure);
// s=0;
}
}
///////////////////////////////////////////////////////////////////////////
pDC->SelectStockObject(WHITE_PEN);
pDC->Rectangle(Snake[Snake[0].len-1].x*20,Snake[Snake[0].len-1].y*20,(Snake[Snake[0].len-1].x+1)*20,(Snake[Snake[0].len-1].y+1)*20);
for(int i=Snake[0].len-1;i>0;i--)
{
Snake[i].x=Snake[i-1].x;
Snake[i].y=Snake[i-1].y;
}
//行走方向判断
if(Snake[0].direct==1)Snake[0].y--;
if(Snake[0].direct==2)Snake[0].y++;
if(Snake[0].direct==3)Snake[0].x--;
if(Snake[0].direct==4)Snake[0].x++;
pDC->SelectStockObject(BLACK_PEN);
CBrush DrawBrush=(RGB(100,100,100));
CBrush *Drawbrush=pDC->SelectObject(&DrawBrush);
pDC->Rectangle(Snake[0].x*20,Snake[0].y*20,(Snake[0].x+1)*20,(Snake[0].y+1)*20);
pDC->SelectObject(DrawBrush);
//判断吃豆的条件,撞到就吃
if(Snake[0].x*20==Food.x*20&&Snake[0].y*20==Food.y*20)
{
Snake[0].len++;
Food.isfood=1;
Snake[Snake[0].len-1].x=Snake[Snake[0].len-2].x;
Snake[Snake[0].len-1].y=Snake[Snake[0].len-2].y;
}
//如果食物被吃了 就生成
if(Food.isfood==1)
{
srand((unsigned)time(NULL));
do
{
for(int isfo=Snake[0].len-1;isfo>=0;isfo--)
if(Snake[0].x*20==Snake[isfo].x*20&&Snake[0].y*20==Snake[isfo].y*20)
{
Food.x=rand()%25;
Food.y=rand()%25;
}
}
while(Food.x*20<70||Food.y*20<70||Food.x*20>430||Food.y*20>430);
pDC->Rectangle(Food.x*20,Food.y*20,(Food.x+1)*20,(Food.y+1)*20);
Food.isfood=0;
}
CView::OnTimer(nIDEvent);
}
void CZhouyuView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// TODO: Add your message handler code here and/or call default
switch(nChar)
{
case VK_UP:if(Snake[0].direct!=2)Snake[0].direct=1;break;
case VK_DOWN:if(Snake[0].direct!=1)Snake[0].direct=2;break;
case VK_LEFT:if(Snake[0].direct!=4)Snake[0].direct=3;break;
case VK_RIGHT:if(Snake[0].direct!=3)Snake[0].direct=4;break; }
CView::OnKeyDown(nChar, nRepCnt, nFlags);
CView::OnKeyDown(nChar, nRepCnt, nFlags);
}
void CZhouyuView::OnInitialUpdate()
{
CView::OnInitialUpdate();
Snake[0].x=10;
Snake[0].y=10;
Snake[1].x=11;
Snake[1].y=10;
Snake[2].x=12;
Snake[2].y=10;
Snake[0].direct=3;
Snake[0].len=3;
Food.isfood=1;
// TODO: Add your specialized code here and/or call the base class
}
void CZhouyuView::oninit()
{
CDC *pDC=GetDC();
CBrush DrawBrush=(RGB(100,100,100));
CBrush *Drawbrush=pDC->SelectObject(&DrawBrush);
for(int i=0;i<=Snake[0].len-1;i++)
pDC->Rectangle(Snake[i].x*20,Snake[i].y*20,(Snake[i].x+1)*20,(Snake[i].y+1)*20);
pDC->SelectObject(DrawBrush);
}
void CZhouyuView::OnStart()
{
// TODO: Add your command handler code here
SetTimer(1,3000,NULL);
AfxMessageBox("3秒后开始游戏!");
}
void CZhouyuView::OnPause()
{
// TODO: Add your command handler code here
KillTimer(1);
AfxMessageBox("暂停游戏...");
}
void CZhouyuView::OnExit()
{
// TODO: Add your command handler code here
AfxMessageBox("退出游戏...");
exit(0);
}
void CZhouyuView::OnContinue()
{
// TODO: Add your command handler code here
SetTimer(1,10,NULL);
} | [
"1078580516@qq.com"
] | 1078580516@qq.com |
c5a09167fd055b3c80bc4a94f6600dc45423a5e5 | a6946df2a837b3e778ba67d8530859bbdf705e21 | /test/containers/unord/unord.set/insert_init.pass.cpp | 9d573b0bf575f15f9395c0911b961965e49d304e | [
"MIT",
"NCSA"
] | permissive | okuoku/libcxx | 0fc5a2fb5f215d4d8c3d1a32541e7bb7377fb4f9 | a2a08b43ee4ac077d703a00538a3b0128f50c83d | refs/heads/master | 2021-01-16T20:51:32.237136 | 2011-06-22T23:51:19 | 2011-06-22T23:51:19 | 1,947,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,267 | cpp | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <unordered_set>
// template <class Value, class Hash = hash<Value>, class Pred = equal_to<Value>,
// class Alloc = allocator<Value>>
// class unordered_set
// void insert(initializer_list<value_type> il);
#include <unordered_set>
#include <cassert>
#include "../../iterators.h"
int main()
{
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
{
typedef std::unordered_set<int> C;
typedef int P;
C c;
c.insert(
{
P(1),
P(2),
P(3),
P(4),
P(1),
P(2)
}
);
assert(c.size() == 4);
assert(c.count(1) == 1);
assert(c.count(2) == 1);
assert(c.count(3) == 1);
assert(c.count(4) == 1);
}
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
}
| [
"hhinnant@apple.com"
] | hhinnant@apple.com |
f3073f9f69a98fa236228e936537074f3d5fafa5 | 4694b46584e205700f02e8743e152340ade7bde5 | /Hackerrank Solutions/alliceBobAndSweet.cpp | 57f22f37f0f3aefecb0e2b508d01c6341187ebb1 | [] | no_license | Aniruddhmuley2001/cpp-stl-resources- | b6db939251293fed3a96d8f4bde4a59f41bbe2ed | 1134df6ab322aa96b9a187f48176884b6201f54b | refs/heads/master | 2023-08-11T12:33:19.666213 | 2021-10-05T12:21:54 | 2021-10-05T12:21:54 | 265,218,970 | 2 | 6 | null | 2021-10-05T12:21:54 | 2020-05-19T10:40:51 | C++ | UTF-8 | C++ | false | false | 920 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
int t , n;
vector<int> v;
cin>>t;
while(t--)
{
cin>>n;
v.resize(n);
for(int i=0 ; i<n ;i++)
{
cin>>v[i];
}
int i = -1 , j = n , curr1 = 0 , curr2 = 0 , total1 = 0 , total2 = 0 , count = 0;
while(i+1 != j)
{
int sum = 0;
while(sum <= curr2 && i + 1 < j)
{
sum = sum + v[++i];
}
total1 = total1 + sum;
if(sum) count = count + 1;
curr1 = sum , sum = 0;
while(sum <= curr1 && i < j - 1)
{
sum = sum + v[--j];
}
curr2 = sum;
total2 = total2 + sum;
if(sum) count = count + 1;
}
cout<<count<<" "<<total1<<" "<<total2<<endl;
}
return 0;
} | [
"58821355+DrashtiKoladiya@users.noreply.github.com"
] | 58821355+DrashtiKoladiya@users.noreply.github.com |
45870e40bf9b11d5d8bc8f5af5862631ef5c6987 | 0eb9403eb2b408d3bf5b43efae1e6fe18f323494 | /CNN.h | 04dbb4e8a0c41e854e197c8381cd1079a75084cf | [] | no_license | jiangwx/Jaffe | 4bef35111e2eccf50eed3a22a3e51ceb3ff7b341 | bce98d0f535b15a01a61f23e3c491b1b6face548 | refs/heads/master | 2020-04-11T12:31:03.099515 | 2018-12-19T15:30:15 | 2018-12-19T15:30:15 | 161,783,342 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,892 | h | #ifndef CNN_H
#define CNN_H
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <memory.h>
#include <time.h>
#include <sys/time.h>
#include <fstream>
#include <cblas.h>
#include <cstring>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#define img_w 224
#define img_h 224
#define DTYPE char
enum layer_type
{
io_,conv_,maxpool_,avgpool_,lrn_,sigmoid_,innerproduct_,batchnorm_,relu_,concat_,softmax_,defualt_
};
struct layer
{
layer_type type;
char name[15];
int iw, ih, ic, ow, oh, oc;
int k, s, p;
};
/**********common.cpp************/
void load_image(char* img_path, float* blob,float* mean);
void load_mean_image(char* img_path, float* blob);
void load_fm(float* fm, layer l, char* Net);
void load_mean(float *mean, layer l, char* Net);
void load_weight(float *weight, layer l, char* Net);
void load_bias(float *bias, layer l, char* Net);
void generate_fm(float* fm, layer l);
void generate_weight(float* weight, layer l);
void show_fm(float* fm, layer l);
void show_matrix(float* matrix, int M, int N);
void trans_matrix(float* in, float* out, int M, int N);
void check_fm(float* fm, layer l, char* Net);
void convolution(float *ifm, float *ofm, float *weight, float *bias, layer l);
void convolution_mm(float *ifm, float *ofm, float *weight, float *bias, float weight_scale, float data_scale, layer l);
void innerproduct(float *ifm, float *ofm, float *weight, float *bias, layer l);
void maxpool(float *ifm, float *ofm, layer l);
void avgpool(float *ifm, float *ofm, layer l);
void lrn(float *ifm, float *ofm, int local, float alpha, float beta, layer l);
void relu(float *ifm, float *ofm, layer l);
void leaky_relu(float *ifm, float *ofm, layer l);
void batchnorm(float* ifm, float* ofm, float* mean, float* variale, float* bias, layer l);
#endif //CNN_H
| [
"jiangwx@shanghaitech.edu.cn"
] | jiangwx@shanghaitech.edu.cn |
dcf77143079223b4f240f8607fa5bec8d4969ae3 | 9f151b5a56272fd6f79c196ecdbe41675834e5c3 | /HMIN212/include/Point.hpp | f7d3169b4b65028b0f21317b16198bba5af56205 | [] | no_license | CorentinGaut/Algo3D_TP9 | 16e30e100b577d5e08cece4b460f5e3b4afed530 | a15e8ed50485bcef1efb8bf2b3ce82927ecdcc6a | refs/heads/master | 2021-10-25T04:56:32.102567 | 2019-04-01T11:04:36 | 2019-04-01T11:04:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | hpp | #ifndef POINT_HPP
#define POINT_HPP
#include "Vector.hpp"
class Point {
private :
double x, y,z;
public :
Point();
Point(double x, double y, double z);
Point(Point const& p);
double getX();
double getY();
double getZ();
void setX(double x);
void setY(double y);
void setZ(double z);
Point ProjectOnLine(Point point1Line, Point point2Line);
Point ProjectOnLine(Vector vecteur, Point pLine);
Point ProjectOnPlane(Point pointOnPlane, Vector normalOfPlane);
};
#endif | [
"noreply@github.com"
] | CorentinGaut.noreply@github.com |
317acf0f49d36803602b6304b94bcc5a56b6571c | 0a27fb69009676ee9bb391f256127a474b55f651 | /Plugins/GraphPrinter/Source/GraphPrinter/Private/ClipboardImageExtension.cpp | 342d2c58cc2b5b329a4168afe6294978d3d03178 | [
"MIT"
] | permissive | BlenderGamer/GraphPrinter | c7bd671e80f8af7ac5aa8bfa98595486469f1875 | 43cefc9aff8205d068546959bbe5971a93af14f1 | refs/heads/master | 2023-07-18T05:32:06.735273 | 2021-08-28T12:32:27 | 2021-08-28T12:32:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,760 | cpp | // Copyright 2020-2021 Naotsun. All Rights Reserved.
#include "ClipboardImageExtension.h"
#include "IImageWrapperModule.h"
#include "IImageWrapper.h"
#include "Modules/ModuleManager.h"
#if PLATFORM_WINDOWS
#include "Windows/WindowsApplication.h"
#endif
namespace ClipboardImageExtensionInternal
{
#if PLATFORM_WINDOWS
HBITMAP LoadBitmapImage(const FString& Filename)
{
TArray<uint8> RawFileData;
if (!FFileHelper::LoadFileToArray(RawFileData, *Filename))
{
return nullptr;
}
auto& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::BMP);
if (!ImageWrapper.IsValid())
{
return nullptr;
}
if (!ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.GetAllocatedSize()))
{
return nullptr;
}
#if BEFORE_UE_4_24
const TArray<uint8>* BitmapBuffer;
if (!ImageWrapper->GetRaw(ImageWrapper->GetFormat(), ImageWrapper->GetBitDepth(), BitmapBuffer))
{
return nullptr;
}
if (BitmapBuffer == nullptr)
{
return nullptr;
}
#else
TArray<uint8> BitmapBuffer;
if (!ImageWrapper->GetRaw(ImageWrapper->GetFormat(), ImageWrapper->GetBitDepth(), BitmapBuffer))
{
return nullptr;
}
#endif
return CreateBitmap(
ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), 1, 32,
#if BEFORE_UE_4_24
BitmapBuffer->GetData()
#else
BitmapBuffer.GetData()
#endif
);
}
bool ClipboardCopy(const FString& Filename)
{
const HBITMAP Bitmap = LoadBitmapImage(Filename);
if (Bitmap == nullptr)
{
UE_LOG(LogGraphPrinter, Error, TEXT("Failed to load the file to copy to the clipboard (%s)"), *Filename);
return false;
}
if (!OpenClipboard(GetActiveWindow()))
{
return false;
}
verify(EmptyClipboard());
if (SetClipboardData(CF_BITMAP, Bitmap) == nullptr)
{
UE_LOG(LogGraphPrinter, Fatal, TEXT("SetClipboardData failed with error code %i"), static_cast<uint32>(GetLastError()));
}
verify(CloseClipboard());
return true;
}
EDesiredImageFormat GetCopyableImageFormat()
{
return EDesiredImageFormat::BMP;
}
#else
void NotifyNotSupported()
{
UE_LOG(LogGraphPrinter, Error, TEXT("This feature is not supported on this platform."));
}
bool ClipboardCopy(const FString& Filename)
{
NotifyNotSupported();
return false;
}
EDesiredImageFormat GetCopyableImageFormat()
{
NotifyNotSupported();
return {};
}
#endif
}
bool FClipboardImageExtension::ClipboardCopy(const FString& Filename)
{
return ClipboardImageExtensionInternal::ClipboardCopy(Filename);
}
EDesiredImageFormat FClipboardImageExtension::GetCopyableImageFormat()
{
return ClipboardImageExtensionInternal::GetCopyableImageFormat();
}
| [
"51815450+Naotsun19B@users.noreply.github.com"
] | 51815450+Naotsun19B@users.noreply.github.com |
4bc09c783868dec6a7083bf89905d34802a0de16 | bd97c25885f64e30ef19445c6fcaff6548683605 | /Computer-Science/C++/Ch4/ex4_28.cpp | ce446ac7327fcf9d3c71961d54ca4886b1914539 | [] | no_license | TerenYeung/Road-To-BE | 9a7a8fbaa2cccca5c2dc14d848867aa4f5c84fdc | ea5307546c191d2d297810275829be146c12d624 | refs/heads/master | 2021-09-17T06:28:22.937235 | 2018-06-28T15:02:10 | 2018-06-28T15:02:10 | 113,331,527 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,589 | cpp | #include <iostream>
using std::cout;
using std::endl;
int main() {
// integers type
cout << "short:\t\t" << sizeof(short) << " bytes" << endl;
cout << "int:\t\t" << sizeof(int) << " bytes" << endl;
cout << "long:\t\t" << sizeof(long) << " bytes" << endl;
cout << "long long:\t\t" << sizeof(long long) << " bytes" << endl;
// floating point type
cout << "float:\t\t" << sizeof(float) << " bytes" << endl;
cout << "double:\t\t" << sizeof(double) << " bytes" << endl;
cout << "long double:\t\t" << sizeof(long double) << " bytes" << endl;
// Fixed width integers
cout << "int8_t:\t\t" << sizeof(int8_t) << " bytes" << endl;
cout << "uint8_t:\t\t" << sizeof(uint8_t) << " bytes" << endl;
cout << "int16_t:\t\t" << sizeof(int16_t) << " bytes" << endl;
cout << "uint16_t:\t\t" << sizeof(uint16_t) << " bytes" << endl;
cout << "int32_t:\t\t" << sizeof(int32_t) << " bytes" << endl;
cout << "uint32_t:\t\t" << sizeof(uint32_t) << " bytes" << endl;
cout << "int64_t:\t\t" << sizeof(int64_t) << " bytes" << endl;
cout << "uint64_t:\t\t" << sizeof(uint64_t) << " bytes" << endl;
// character type
cout << "char:\t\t" << sizeof(char) << " bytes" << endl;
cout << "wchar_t:\t\t" << sizeof(wchar_t) << " bytes" << endl;
cout << "char16_t:\t\t" << sizeof(char16_t) << " bytes" << endl;
cout << "char32_t:\t\t" << sizeof(char32_t) << " bytes" << endl;
// void type
cout << "void: nullptr_t\t" << sizeof(std::nullptr_t) << " bytes" << endl;
int x[10];
int *p = x;
cout << sizeof(p)/sizeof(*p) << endl;
cout << 3 + 'a' << endl;
return 0;
} | [
"yangjialong@ifanr.com"
] | yangjialong@ifanr.com |
76dc3433e2b1c5f6178c9e8a1f46ffd4234abbe8 | a070ff0c5b424f8b7c1a7fa05f4f40d68381667b | /src/qt/communityfunddisplay.cpp | 4bfbd0bf2f2c8f325442039baa3c8a851792928f | [
"MIT"
] | permissive | diyathrajapakshe/bethel-core | 1347a29d8091778eaa4dc97fa26fc428e6206366 | 9f272d635da18b91582dbbb2ba47cfce1a1fc9ca | refs/heads/master | 2021-03-13T11:49:21.838487 | 2020-03-11T20:56:23 | 2020-03-11T20:56:23 | 246,677,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,921 | cpp | #include "communityfunddisplay.h"
#include "ui_communityfunddisplay.h"
#include <QtWidgets/QDialogButtonBox>
#include "main.h"
#include "../txdb.h"
#include <iomanip>
#include <sstream>
#include <ctime>
#include "wallet/wallet.h"
#include "base58.h"
#include "consensus/cfund.h"
#include "chain.h"
#include "guiutil.h"
#include "communityfunddisplaydetailed.h"
#include "communityfundpage.h"
CommunityFundDisplay::CommunityFundDisplay(QWidget *parent, CFund::CProposal proposal) :
QWidget(parent),
ui(new Ui::CommunityFundDisplay),
proposal(proposal)
{
ui->setupUi(this);
QFont f_title("Sans Serif", 10.5, QFont::Bold);
QFont f_label_title("Sans Serif", 10, QFont::Bold);
QFont f_label("Sans Serif", 10, QFont::Normal);
ui->title->setFont(f_title);
ui->labelTitleDuration->setFont(f_label_title);
ui->labelDuration->setFont(f_label);
ui->labelTitleRequested->setFont(f_label_title);
ui->labelRequested->setFont(f_label);
ui->labelTitleStatus->setFont(f_label_title);
ui->labelStatus->setFont(f_label);
ui->pushButtonDetails->setFont(f_label);
ui->buttonBoxVote->setFont(f_label);
connect(ui->buttonBoxVote, SIGNAL(clicked( QAbstractButton*)), this, SLOT(click_buttonBoxVote(QAbstractButton*)));
connect(ui->pushButtonDetails, SIGNAL(clicked()), this, SLOT(click_pushButtonDetails()));
refresh();
}
void CommunityFundDisplay::refresh()
{
// Set labels from community fund
ui->title->setText(QString::fromStdString(proposal.strDZeel));
ui->labelStatus->setText(QString::fromStdString(proposal.GetState(pindexBestHeader->GetBlockTime())));
string btel_amount;
btel_amount = wallet->formatDisplayAmount(proposal.nAmount);
ui->labelRequested->setText(QString::fromStdString(btel_amount));
uint64_t proptime = 0;
if (mapBlockIndex.count(proposal.blockhash) > 0) {
proptime = mapBlockIndex[proposal.blockhash]->GetBlockTime();
}
uint64_t deadline = proptime + proposal.nDeadline - pindexBestHeader->GetBlockTime();
uint64_t deadline_d = std::floor(deadline/86400);
uint64_t deadline_h = std::floor((deadline-deadline_d*86400)/3600);
uint64_t deadline_m = std::floor((deadline-(deadline_d*86400 + deadline_h*3600))/60);
// Show appropriate amount of figures
std::string s_deadline = "";
if(deadline_d >= 14)
s_deadline = std::to_string(deadline_d) + std::string(" Days");
else
s_deadline = std::to_string(deadline_d) + std::string(" Days ") + std::to_string(deadline_h) + std::string(" Hours ") + std::to_string(deadline_m) + std::string(" Minutes");
ui->labelDuration->setText(QString::fromStdString(s_deadline));
// Hide ability to vote is the status is expired
std::string status = ui->labelStatus->text().toStdString();
if (status.find("expired") != string::npos) {
ui->buttonBoxVote->setStandardButtons(QDialogButtonBox::NoButton);
}
// If proposal is pending show voting cycles left
if (proposal.fState == CFund::NIL)
{
std::string duration_title = "Voting Cycle: ";
std::string duration = std::to_string(proposal.nVotingCycle) + " of " + std::to_string(Params().GetConsensus().nCyclesProposalVoting);
ui->labelTitleDuration->setText(QString::fromStdString(duration_title));
ui->labelDuration->setText(QString::fromStdString(duration));
}
// If proposal is rejected, show when it was rejected
if (proposal.fState == CFund::REJECTED)
{
std::string expiry_title = "Rejected on: ";
std::time_t t = static_cast<time_t>(proptime);
std::stringstream ss;
char buf[48];
if (strftime(buf, sizeof(buf), "%c %Z", std::gmtime(&t)))
ss << buf;
ui->labelTitleDuration->setText(QString::fromStdString(expiry_title));
ui->labelDuration->setText(QString::fromStdString(ss.str().erase(10, 9)));
}
// If expired show when it expired
if (proposal.fState == CFund::EXPIRED || status.find("expired") != string::npos)
{
if (proposal.fState == CFund::EXPIRED)
{
std::string expiry_title = "Expired on: ";
std::time_t t = static_cast<time_t>(proptime);
std::stringstream ss;
char buf[48];
if (strftime(buf, sizeof(buf), "%c %Z", std::gmtime(&t)))
ss << buf;
ui->labelTitleDuration->setText(QString::fromStdString(expiry_title));
ui->labelDuration->setText(QString::fromStdString(ss.str().erase(10, 9)));
}
else
{
std::string expiry_title = "Expires: ";
std::string expiry = "At end of voting period";
ui->labelTitleDuration->setText(QString::fromStdString(expiry_title));
ui->labelDuration->setText(QString::fromStdString(expiry));
}
}
// Shade in yes/no buttons is user has voted
// If the proposal is pending and not prematurely expired (ie can be voted on):
if (proposal.fState == CFund::NIL && proposal.GetState(pindexBestHeader->GetBlockTime()).find("expired") == string::npos)
{
// Get proposal votes list
CFund::CProposal prop = this->proposal;
auto it = std::find_if( vAddedProposalVotes.begin(), vAddedProposalVotes.end(),
[&prop](const std::pair<std::string, bool>& element){ return element.first == prop.hash.ToString();} );
if (it != vAddedProposalVotes.end())
{
if (it->second)
{
// Proposal was voted yes, shade in yes button and unshade no button
ui->buttonBoxVote->setStandardButtons(QDialogButtonBox::No|QDialogButtonBox::Yes|QDialogButtonBox::Cancel);
ui->buttonBoxVote->button(QDialogButtonBox::Yes)->setStyleSheet(COLOR_VOTE_YES);
ui->buttonBoxVote->button(QDialogButtonBox::No)->setStyleSheet(COLOR_VOTE_NEUTRAL);
}
else
{
// Proposal was noted no, shade in no button and unshade yes button
ui->buttonBoxVote->setStandardButtons(QDialogButtonBox::No|QDialogButtonBox::Yes|QDialogButtonBox::Cancel);
ui->buttonBoxVote->button(QDialogButtonBox::Yes)->setStyleSheet(COLOR_VOTE_NEUTRAL);
ui->buttonBoxVote->button(QDialogButtonBox::No)->setStyleSheet(COLOR_VOTE_NO);
}
}
else
{
// Proposal was not voted on, reset shades of both buttons
ui->buttonBoxVote->setStandardButtons(QDialogButtonBox::No|QDialogButtonBox::Yes);
ui->buttonBoxVote->button(QDialogButtonBox::Yes)->setStyleSheet(COLOR_VOTE_NEUTRAL);
ui->buttonBoxVote->button(QDialogButtonBox::No)->setStyleSheet(COLOR_VOTE_NEUTRAL);
}
}
// If a proposal is expired pending voting of payment requests, change the expiry label text
if(status.find("expired pending voting of payment requests") != string::npos) {
ui->labelDuration->setText(QString::fromStdString("After payment request voting"));
}
{
LOCK(cs_main);
//hide ui voting elements on proposals which are not allowed vote states
if(!proposal.CanVote())
ui->buttonBoxVote->setStandardButtons(QDialogButtonBox::NoButton);
}
// Prevent overflow of title
std::string title_string = proposal.strDZeel;
std::replace( title_string.begin(), title_string.end(), '\n', ' ');
if (title_string.length() > 140)
{
title_string = title_string.substr(0, 140);
title_string.append("...");
}
ui->title->setText(QString::fromStdString(title_string));
// Hide expiry label is proposal is accepted and waiting for coins
if(status.find("accepted waiting for enough coins in fund") != string::npos) {
ui->labelDuration->setVisible(false);
ui->labelTitleDuration->setVisible(false);
}
}
void CommunityFundDisplay::click_buttonBoxVote(QAbstractButton *button)
{
// Cast the vote
bool duplicate = false;
CFund::CProposal p;
if (!pcoinsTip->GetProposal(uint256S(proposal.hash.ToString()), p))
{
return;
}
if (ui->buttonBoxVote->buttonRole(button) == QDialogButtonBox::YesRole)
{
CFund::VoteProposal(p, true, duplicate);
refresh();
}
else if(ui->buttonBoxVote->buttonRole(button) == QDialogButtonBox::NoRole)
{
CFund::VoteProposal(p, false, duplicate);
refresh();
}
else if(ui->buttonBoxVote->buttonRole(button) == QDialogButtonBox::RejectRole)
{
CFund::RemoveVoteProposal(p.hash.ToString());
refresh();
}
else
{
refresh();
return;
}
}
void CommunityFundDisplay::click_pushButtonDetails()
{
CommunityFundDisplayDetailed dlg(this, proposal);
dlg.exec();
refresh();
}
CommunityFundDisplay::~CommunityFundDisplay()
{
delete ui;
}
| [
"diyathrajapakshe@gmail.com"
] | diyathrajapakshe@gmail.com |
e89f32da9f108ea48d3504a84c6d565abfc23a24 | 301cac2ee44330c6ce0a116ca4e8552dae72c822 | /core/slam/src/ORBmatcher.cc | 900851be746534f10e41319a48c4e13247c8ff54 | [] | no_license | dmitryshendryk/hackaton_2018 | 124b922f48a8d4771f5a28af2af182abdb9c00a1 | f6c755be01f53530cfd50168f473d114ba39db1e | refs/heads/master | 2020-03-26T10:45:17.472825 | 2018-08-15T18:45:53 | 2018-08-15T18:45:53 | 144,813,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49,622 | cc | /**
* This file is part of ORB-SLAM2.
*
* Copyright (C) 2014-2016 Raúl Mur-Artal <raulmur at unizar dot es> (University of Zaragoza)
* For more information see <https://github.com/raulmur/ORB_SLAM2>
*
* ORB-SLAM2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ORB-SLAM2 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 ORB-SLAM2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ORBmatcher.h"
#include <limits.h>
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include "../Thirdparty/DBoW2/DBoW2/FeatureVector.h"
#include <stdint-gcc.h>
using namespace std;
namespace ORB_SLAM2
{
const int ORBmatcher::TH_HIGH = 100;
const int ORBmatcher::TH_LOW = 50;
const int ORBmatcher::HISTO_LENGTH = 30;
ORBmatcher::ORBmatcher(float nnratio, bool checkOri): mfNNratio(nnratio), mbCheckOrientation(checkOri)
{
}
int ORBmatcher::SearchByProjection(Frame &F, const vector<MapPoint*> &vpMapPoints, const float th)
{
int nmatches=0;
const bool bFactor = th!=1.0;
for(size_t iMP=0; iMP<vpMapPoints.size(); iMP++)
{
MapPoint* pMP = vpMapPoints[iMP];
if(!pMP->mbTrackInView)
continue;
if(pMP->isBad())
continue;
const int &nPredictedLevel = pMP->mnTrackScaleLevel;
// The size of the window will depend on the viewing direction
float r = RadiusByViewingCos(pMP->mTrackViewCos);
if(bFactor)
r*=th;
const vector<size_t> vIndices =
F.GetFeaturesInArea(pMP->mTrackProjX,pMP->mTrackProjY,r*F.mvScaleFactors[nPredictedLevel],nPredictedLevel-1,nPredictedLevel);
if(vIndices.empty())
continue;
const cv::Mat MPdescriptor = pMP->GetDescriptor();
int bestDist=256;
int bestLevel= -1;
int bestDist2=256;
int bestLevel2 = -1;
int bestIdx =-1 ;
// Get best and second matches with near keypoints
for(vector<size_t>::const_iterator vit=vIndices.begin(), vend=vIndices.end(); vit!=vend; vit++)
{
const size_t idx = *vit;
if(F.mvpMapPoints[idx])
if(F.mvpMapPoints[idx]->Observations()>0)
continue;
if(F.mvuRight[idx]>0)
{
const float er = fabs(pMP->mTrackProjXR-F.mvuRight[idx]);
if(er>r*F.mvScaleFactors[nPredictedLevel])
continue;
}
const cv::Mat &d = F.mDescriptors.row(idx);
const int dist = DescriptorDistance(MPdescriptor,d);
if(dist<bestDist)
{
bestDist2=bestDist;
bestDist=dist;
bestLevel2 = bestLevel;
bestLevel = F.mvKeysUn[idx].octave;
bestIdx=idx;
}
else if(dist<bestDist2)
{
bestLevel2 = F.mvKeysUn[idx].octave;
bestDist2=dist;
}
}
// Apply ratio to second match (only if best and second are in the same scale level)
if(bestDist<=TH_HIGH)
{
if(bestLevel==bestLevel2 && bestDist>mfNNratio*bestDist2)
continue;
F.mvpMapPoints[bestIdx]=pMP;
nmatches++;
}
}
return nmatches;
}
float ORBmatcher::RadiusByViewingCos(const float &viewCos)
{
if(viewCos>0.998)
return 2.5;
else
return 4.0;
}
bool ORBmatcher::CheckDistEpipolarLine(const cv::KeyPoint &kp1,const cv::KeyPoint &kp2,const cv::Mat &F12,const KeyFrame* pKF2)
{
// Epipolar line in second image l = x1'F12 = [a b c]
const float a = kp1.pt.x*F12.at<float>(0,0)+kp1.pt.y*F12.at<float>(1,0)+F12.at<float>(2,0);
const float b = kp1.pt.x*F12.at<float>(0,1)+kp1.pt.y*F12.at<float>(1,1)+F12.at<float>(2,1);
const float c = kp1.pt.x*F12.at<float>(0,2)+kp1.pt.y*F12.at<float>(1,2)+F12.at<float>(2,2);
const float num = a*kp2.pt.x+b*kp2.pt.y+c;
const float den = a*a+b*b;
if(den==0)
return false;
const float dsqr = num*num/den;
return dsqr<3.84*pKF2->mvLevelSigma2[kp2.octave];
}
int ORBmatcher::SearchByBoW(KeyFrame* pKF,Frame &F, vector<MapPoint*> &vpMapPointMatches)
{
const vector<MapPoint*> vpMapPointsKF = pKF->GetMapPointMatches();
vpMapPointMatches = vector<MapPoint*>(F.N,static_cast<MapPoint*>(NULL));
const DBoW2::FeatureVector &vFeatVecKF = pKF->mFeatVec;
int nmatches=0;
vector<int> rotHist[HISTO_LENGTH];
for(int i=0;i<HISTO_LENGTH;i++)
rotHist[i].reserve(500);
const float factor = 1.0f/HISTO_LENGTH;
// We perform the matching over ORB that belong to the same vocabulary node (at a certain level)
DBoW2::FeatureVector::const_iterator KFit = vFeatVecKF.begin();
DBoW2::FeatureVector::const_iterator Fit = F.mFeatVec.begin();
DBoW2::FeatureVector::const_iterator KFend = vFeatVecKF.end();
DBoW2::FeatureVector::const_iterator Fend = F.mFeatVec.end();
while(KFit != KFend && Fit != Fend)
{
if(KFit->first == Fit->first)
{
const vector<unsigned int> vIndicesKF = KFit->second;
const vector<unsigned int> vIndicesF = Fit->second;
for(size_t iKF=0; iKF<vIndicesKF.size(); iKF++)
{
const unsigned int realIdxKF = vIndicesKF[iKF];
MapPoint* pMP = vpMapPointsKF[realIdxKF];
if(!pMP)
continue;
if(pMP->isBad())
continue;
const cv::Mat &dKF= pKF->mDescriptors.row(realIdxKF);
int bestDist1=256;
int bestIdxF =-1 ;
int bestDist2=256;
for(size_t iF=0; iF<vIndicesF.size(); iF++)
{
const unsigned int realIdxF = vIndicesF[iF];
if(vpMapPointMatches[realIdxF])
continue;
const cv::Mat &dF = F.mDescriptors.row(realIdxF);
const int dist = DescriptorDistance(dKF,dF);
if(dist<bestDist1)
{
bestDist2=bestDist1;
bestDist1=dist;
bestIdxF=realIdxF;
}
else if(dist<bestDist2)
{
bestDist2=dist;
}
}
if(bestDist1<=TH_LOW)
{
if(static_cast<float>(bestDist1)<mfNNratio*static_cast<float>(bestDist2))
{
vpMapPointMatches[bestIdxF]=pMP;
const cv::KeyPoint &kp = pKF->mvKeysUn[realIdxKF];
if(mbCheckOrientation)
{
float rot = kp.angle-F.mvKeys[bestIdxF].angle;
if(rot<0.0)
rot+=360.0f;
int bin = round(rot*factor);
if(bin==HISTO_LENGTH)
bin=0;
assert(bin>=0 && bin<HISTO_LENGTH);
rotHist[bin].push_back(bestIdxF);
}
nmatches++;
}
}
}
KFit++;
Fit++;
}
else if(KFit->first < Fit->first)
{
KFit = vFeatVecKF.lower_bound(Fit->first);
}
else
{
Fit = F.mFeatVec.lower_bound(KFit->first);
}
}
if(mbCheckOrientation)
{
int ind1=-1;
int ind2=-1;
int ind3=-1;
ComputeThreeMaxima(rotHist,HISTO_LENGTH,ind1,ind2,ind3);
for(int i=0; i<HISTO_LENGTH; i++)
{
if(i==ind1 || i==ind2 || i==ind3)
continue;
for(size_t j=0, jend=rotHist[i].size(); j<jend; j++)
{
vpMapPointMatches[rotHist[i][j]]=static_cast<MapPoint*>(NULL);
nmatches--;
}
}
}
return nmatches;
}
int ORBmatcher::SearchByProjection(KeyFrame* pKF, cv::Mat Scw, const vector<MapPoint*> &vpPoints, vector<MapPoint*> &vpMatched, int th)
{
// Get Calibration Parameters for later projection
const float &fx = pKF->fx;
const float &fy = pKF->fy;
const float &cx = pKF->cx;
const float &cy = pKF->cy;
// Decompose Scw
cv::Mat sRcw = Scw.rowRange(0,3).colRange(0,3);
const float scw = sqrt(sRcw.row(0).dot(sRcw.row(0)));
cv::Mat Rcw = sRcw/scw;
cv::Mat tcw = Scw.rowRange(0,3).col(3)/scw;
cv::Mat Ow = -Rcw.t()*tcw;
// Set of MapPoints already found in the KeyFrame
set<MapPoint*> spAlreadyFound(vpMatched.begin(), vpMatched.end());
spAlreadyFound.erase(static_cast<MapPoint*>(NULL));
int nmatches=0;
// For each Candidate MapPoint Project and Match
for(int iMP=0, iendMP=vpPoints.size(); iMP<iendMP; iMP++)
{
MapPoint* pMP = vpPoints[iMP];
// Discard Bad MapPoints and already found
if(pMP->isBad() || spAlreadyFound.count(pMP))
continue;
// Get 3D Coords.
cv::Mat p3Dw = pMP->GetWorldPos();
// Transform into Camera Coords.
cv::Mat p3Dc = Rcw*p3Dw+tcw;
// Depth must be positive
if(p3Dc.at<float>(2)<0.0)
continue;
// Project into Image
const float invz = 1/p3Dc.at<float>(2);
const float x = p3Dc.at<float>(0)*invz;
const float y = p3Dc.at<float>(1)*invz;
const float u = fx*x+cx;
const float v = fy*y+cy;
// Point must be inside the image
if(!pKF->IsInImage(u,v))
continue;
// Depth must be inside the scale invariance region of the point
const float maxDistance = pMP->GetMaxDistanceInvariance();
const float minDistance = pMP->GetMinDistanceInvariance();
cv::Mat PO = p3Dw-Ow;
const float dist = cv::norm(PO);
if(dist<minDistance || dist>maxDistance)
continue;
// Viewing angle must be less than 60 deg
cv::Mat Pn = pMP->GetNormal();
if(PO.dot(Pn)<0.5*dist)
continue;
int nPredictedLevel = pMP->PredictScale(dist,pKF->mfLogScaleFactor);
// Search in a radius
const float radius = th*pKF->mvScaleFactors[nPredictedLevel];
const vector<size_t> vIndices = pKF->GetFeaturesInArea(u,v,radius);
if(vIndices.empty())
continue;
// Match to the most similar keypoint in the radius
const cv::Mat dMP = pMP->GetDescriptor();
int bestDist = 256;
int bestIdx = -1;
for(vector<size_t>::const_iterator vit=vIndices.begin(), vend=vIndices.end(); vit!=vend; vit++)
{
const size_t idx = *vit;
if(vpMatched[idx])
continue;
const int &kpLevel= pKF->mvKeysUn[idx].octave;
if(kpLevel<nPredictedLevel-1 || kpLevel>nPredictedLevel)
continue;
const cv::Mat &dKF = pKF->mDescriptors.row(idx);
const int dist = DescriptorDistance(dMP,dKF);
if(dist<bestDist)
{
bestDist = dist;
bestIdx = idx;
}
}
if(bestDist<=TH_LOW)
{
vpMatched[bestIdx]=pMP;
nmatches++;
}
}
return nmatches;
}
int ORBmatcher::SearchForInitialization(Frame &F1, Frame &F2, vector<cv::Point2f> &vbPrevMatched, vector<int> &vnMatches12, int windowSize)
{
int nmatches=0;
vnMatches12 = vector<int>(F1.mvKeysUn.size(),-1);
vector<int> rotHist[HISTO_LENGTH];
for(int i=0;i<HISTO_LENGTH;i++)
rotHist[i].reserve(500);
const float factor = 1.0f/HISTO_LENGTH;
vector<int> vMatchedDistance(F2.mvKeysUn.size(),INT_MAX);
vector<int> vnMatches21(F2.mvKeysUn.size(),-1);
for(size_t i1=0, iend1=F1.mvKeysUn.size(); i1<iend1; i1++)
{
cv::KeyPoint kp1 = F1.mvKeysUn[i1];
int level1 = kp1.octave;
if(level1>0)
continue;
vector<size_t> vIndices2 = F2.GetFeaturesInArea(vbPrevMatched[i1].x,vbPrevMatched[i1].y, windowSize,level1,level1);
if(vIndices2.empty())
continue;
cv::Mat d1 = F1.mDescriptors.row(i1);
int bestDist = INT_MAX;
int bestDist2 = INT_MAX;
int bestIdx2 = -1;
for(vector<size_t>::iterator vit=vIndices2.begin(); vit!=vIndices2.end(); vit++)
{
size_t i2 = *vit;
cv::Mat d2 = F2.mDescriptors.row(i2);
int dist = DescriptorDistance(d1,d2);
if(vMatchedDistance[i2]<=dist)
continue;
if(dist<bestDist)
{
bestDist2=bestDist;
bestDist=dist;
bestIdx2=i2;
}
else if(dist<bestDist2)
{
bestDist2=dist;
}
}
if(bestDist<=TH_LOW)
{
if(bestDist<(float)bestDist2*mfNNratio)
{
if(vnMatches21[bestIdx2]>=0)
{
vnMatches12[vnMatches21[bestIdx2]]=-1;
nmatches--;
}
vnMatches12[i1]=bestIdx2;
vnMatches21[bestIdx2]=i1;
vMatchedDistance[bestIdx2]=bestDist;
nmatches++;
if(mbCheckOrientation)
{
float rot = F1.mvKeysUn[i1].angle-F2.mvKeysUn[bestIdx2].angle;
if(rot<0.0)
rot+=360.0f;
int bin = round(rot*factor);
if(bin==HISTO_LENGTH)
bin=0;
assert(bin>=0 && bin<HISTO_LENGTH);
rotHist[bin].push_back(i1);
}
}
}
}
if(mbCheckOrientation)
{
int ind1=-1;
int ind2=-1;
int ind3=-1;
ComputeThreeMaxima(rotHist,HISTO_LENGTH,ind1,ind2,ind3);
for(int i=0; i<HISTO_LENGTH; i++)
{
if(i==ind1 || i==ind2 || i==ind3)
continue;
for(size_t j=0, jend=rotHist[i].size(); j<jend; j++)
{
int idx1 = rotHist[i][j];
if(vnMatches12[idx1]>=0)
{
vnMatches12[idx1]=-1;
nmatches--;
}
}
}
}
//Update prev matched
for(size_t i1=0, iend1=vnMatches12.size(); i1<iend1; i1++)
if(vnMatches12[i1]>=0)
vbPrevMatched[i1]=F2.mvKeysUn[vnMatches12[i1]].pt;
return nmatches;
}
int ORBmatcher::SearchByBoW(KeyFrame *pKF1, KeyFrame *pKF2, vector<MapPoint *> &vpMatches12)
{
const vector<cv::KeyPoint> &vKeysUn1 = pKF1->mvKeysUn;
const DBoW2::FeatureVector &vFeatVec1 = pKF1->mFeatVec;
const vector<MapPoint*> vpMapPoints1 = pKF1->GetMapPointMatches();
const cv::Mat &Descriptors1 = pKF1->mDescriptors;
const vector<cv::KeyPoint> &vKeysUn2 = pKF2->mvKeysUn;
const DBoW2::FeatureVector &vFeatVec2 = pKF2->mFeatVec;
const vector<MapPoint*> vpMapPoints2 = pKF2->GetMapPointMatches();
const cv::Mat &Descriptors2 = pKF2->mDescriptors;
vpMatches12 = vector<MapPoint*>(vpMapPoints1.size(),static_cast<MapPoint*>(NULL));
vector<bool> vbMatched2(vpMapPoints2.size(),false);
vector<int> rotHist[HISTO_LENGTH];
for(int i=0;i<HISTO_LENGTH;i++)
rotHist[i].reserve(500);
const float factor = 1.0f/HISTO_LENGTH;
int nmatches = 0;
DBoW2::FeatureVector::const_iterator f1it = vFeatVec1.begin();
DBoW2::FeatureVector::const_iterator f2it = vFeatVec2.begin();
DBoW2::FeatureVector::const_iterator f1end = vFeatVec1.end();
DBoW2::FeatureVector::const_iterator f2end = vFeatVec2.end();
while(f1it != f1end && f2it != f2end)
{
if(f1it->first == f2it->first)
{
for(size_t i1=0, iend1=f1it->second.size(); i1<iend1; i1++)
{
const size_t idx1 = f1it->second[i1];
MapPoint* pMP1 = vpMapPoints1[idx1];
if(!pMP1)
continue;
if(pMP1->isBad())
continue;
const cv::Mat &d1 = Descriptors1.row(idx1);
int bestDist1=256;
int bestIdx2 =-1 ;
int bestDist2=256;
for(size_t i2=0, iend2=f2it->second.size(); i2<iend2; i2++)
{
const size_t idx2 = f2it->second[i2];
MapPoint* pMP2 = vpMapPoints2[idx2];
if(vbMatched2[idx2] || !pMP2)
continue;
if(pMP2->isBad())
continue;
const cv::Mat &d2 = Descriptors2.row(idx2);
int dist = DescriptorDistance(d1,d2);
if(dist<bestDist1)
{
bestDist2=bestDist1;
bestDist1=dist;
bestIdx2=idx2;
}
else if(dist<bestDist2)
{
bestDist2=dist;
}
}
if(bestDist1<TH_LOW)
{
if(static_cast<float>(bestDist1)<mfNNratio*static_cast<float>(bestDist2))
{
vpMatches12[idx1]=vpMapPoints2[bestIdx2];
vbMatched2[bestIdx2]=true;
if(mbCheckOrientation)
{
float rot = vKeysUn1[idx1].angle-vKeysUn2[bestIdx2].angle;
if(rot<0.0)
rot+=360.0f;
int bin = round(rot*factor);
if(bin==HISTO_LENGTH)
bin=0;
assert(bin>=0 && bin<HISTO_LENGTH);
rotHist[bin].push_back(idx1);
}
nmatches++;
}
}
}
f1it++;
f2it++;
}
else if(f1it->first < f2it->first)
{
f1it = vFeatVec1.lower_bound(f2it->first);
}
else
{
f2it = vFeatVec2.lower_bound(f1it->first);
}
}
if(mbCheckOrientation)
{
int ind1=-1;
int ind2=-1;
int ind3=-1;
ComputeThreeMaxima(rotHist,HISTO_LENGTH,ind1,ind2,ind3);
for(int i=0; i<HISTO_LENGTH; i++)
{
if(i==ind1 || i==ind2 || i==ind3)
continue;
for(size_t j=0, jend=rotHist[i].size(); j<jend; j++)
{
vpMatches12[rotHist[i][j]]=static_cast<MapPoint*>(NULL);
nmatches--;
}
}
}
return nmatches;
}
int ORBmatcher::SearchForTriangulation(KeyFrame *pKF1, KeyFrame *pKF2, cv::Mat F12,
vector<pair<size_t, size_t> > &vMatchedPairs, const bool bOnlyStereo)
{
const DBoW2::FeatureVector &vFeatVec1 = pKF1->mFeatVec;
const DBoW2::FeatureVector &vFeatVec2 = pKF2->mFeatVec;
//Compute epipole in second image
cv::Mat Cw = pKF1->GetCameraCenter();
cv::Mat R2w = pKF2->GetRotation();
cv::Mat t2w = pKF2->GetTranslation();
cv::Mat C2 = R2w*Cw+t2w;
const float invz = 1.0f/C2.at<float>(2);
const float ex =pKF2->fx*C2.at<float>(0)*invz+pKF2->cx;
const float ey =pKF2->fy*C2.at<float>(1)*invz+pKF2->cy;
// Find matches between not tracked keypoints
// Matching speed-up by ORB Vocabulary
// Compare only ORB that share the same node
int nmatches=0;
vector<bool> vbMatched2(pKF2->N,false);
vector<int> vMatches12(pKF1->N,-1);
vector<int> rotHist[HISTO_LENGTH];
for(int i=0;i<HISTO_LENGTH;i++)
rotHist[i].reserve(500);
const float factor = 1.0f/HISTO_LENGTH;
DBoW2::FeatureVector::const_iterator f1it = vFeatVec1.begin();
DBoW2::FeatureVector::const_iterator f2it = vFeatVec2.begin();
DBoW2::FeatureVector::const_iterator f1end = vFeatVec1.end();
DBoW2::FeatureVector::const_iterator f2end = vFeatVec2.end();
while(f1it!=f1end && f2it!=f2end)
{
if(f1it->first == f2it->first)
{
for(size_t i1=0, iend1=f1it->second.size(); i1<iend1; i1++)
{
const size_t idx1 = f1it->second[i1];
MapPoint* pMP1 = pKF1->GetMapPoint(idx1);
// If there is already a MapPoint skip
if(pMP1)
continue;
const bool bStereo1 = pKF1->mvuRight[idx1]>=0;
if(bOnlyStereo)
if(!bStereo1)
continue;
const cv::KeyPoint &kp1 = pKF1->mvKeysUn[idx1];
const cv::Mat &d1 = pKF1->mDescriptors.row(idx1);
int bestDist = TH_LOW;
int bestIdx2 = -1;
for(size_t i2=0, iend2=f2it->second.size(); i2<iend2; i2++)
{
size_t idx2 = f2it->second[i2];
MapPoint* pMP2 = pKF2->GetMapPoint(idx2);
// If we have already matched or there is a MapPoint skip
if(vbMatched2[idx2] || pMP2)
continue;
const bool bStereo2 = pKF2->mvuRight[idx2]>=0;
if(bOnlyStereo)
if(!bStereo2)
continue;
const cv::Mat &d2 = pKF2->mDescriptors.row(idx2);
const int dist = DescriptorDistance(d1,d2);
if(dist>TH_LOW || dist>bestDist)
continue;
const cv::KeyPoint &kp2 = pKF2->mvKeysUn[idx2];
if(!bStereo1 && !bStereo2)
{
const float distex = ex-kp2.pt.x;
const float distey = ey-kp2.pt.y;
if(distex*distex+distey*distey<100*pKF2->mvScaleFactors[kp2.octave])
continue;
}
if(CheckDistEpipolarLine(kp1,kp2,F12,pKF2))
{
bestIdx2 = idx2;
bestDist = dist;
}
}
if(bestIdx2>=0)
{
const cv::KeyPoint &kp2 = pKF2->mvKeysUn[bestIdx2];
vMatches12[idx1]=bestIdx2;
nmatches++;
if(mbCheckOrientation)
{
float rot = kp1.angle-kp2.angle;
if(rot<0.0)
rot+=360.0f;
int bin = round(rot*factor);
if(bin==HISTO_LENGTH)
bin=0;
assert(bin>=0 && bin<HISTO_LENGTH);
rotHist[bin].push_back(idx1);
}
}
}
f1it++;
f2it++;
}
else if(f1it->first < f2it->first)
{
f1it = vFeatVec1.lower_bound(f2it->first);
}
else
{
f2it = vFeatVec2.lower_bound(f1it->first);
}
}
if(mbCheckOrientation)
{
int ind1=-1;
int ind2=-1;
int ind3=-1;
ComputeThreeMaxima(rotHist,HISTO_LENGTH,ind1,ind2,ind3);
for(int i=0; i<HISTO_LENGTH; i++)
{
if(i==ind1 || i==ind2 || i==ind3)
continue;
for(size_t j=0, jend=rotHist[i].size(); j<jend; j++)
{
vMatches12[rotHist[i][j]]=-1;
nmatches--;
}
}
}
vMatchedPairs.clear();
vMatchedPairs.reserve(nmatches);
for(size_t i=0, iend=vMatches12.size(); i<iend; i++)
{
if(vMatches12[i]<0)
continue;
vMatchedPairs.push_back(make_pair(i,vMatches12[i]));
}
return nmatches;
}
int ORBmatcher::Fuse(KeyFrame *pKF, const vector<MapPoint *> &vpMapPoints, const float th)
{
cv::Mat Rcw = pKF->GetRotation();
cv::Mat tcw = pKF->GetTranslation();
const float &fx = pKF->fx;
const float &fy = pKF->fy;
const float &cx = pKF->cx;
const float &cy = pKF->cy;
const float &bf = pKF->mbf;
cv::Mat Ow = pKF->GetCameraCenter();
int nFused=0;
const int nMPs = vpMapPoints.size();
for(int i=0; i<nMPs; i++)
{
MapPoint* pMP = vpMapPoints[i];
if(!pMP)
continue;
if(pMP->isBad() || pMP->IsInKeyFrame(pKF))
continue;
cv::Mat p3Dw = pMP->GetWorldPos();
cv::Mat p3Dc = Rcw*p3Dw + tcw;
// Depth must be positive
if(p3Dc.at<float>(2)<0.0f)
continue;
const float invz = 1/p3Dc.at<float>(2);
const float x = p3Dc.at<float>(0)*invz;
const float y = p3Dc.at<float>(1)*invz;
const float u = fx*x+cx;
const float v = fy*y+cy;
// Point must be inside the image
if(!pKF->IsInImage(u,v))
continue;
const float ur = u-bf*invz;
const float maxDistance = pMP->GetMaxDistanceInvariance();
const float minDistance = pMP->GetMinDistanceInvariance();
cv::Mat PO = p3Dw-Ow;
const float dist3D = cv::norm(PO);
// Depth must be inside the scale pyramid of the image
if(dist3D<minDistance || dist3D>maxDistance )
continue;
// Viewing angle must be less than 60 deg
cv::Mat Pn = pMP->GetNormal();
if(PO.dot(Pn)<0.5*dist3D)
continue;
int nPredictedLevel = pMP->PredictScale(dist3D,pKF->mfLogScaleFactor);
// Search in a radius
const float radius = th*pKF->mvScaleFactors[nPredictedLevel];
const vector<size_t> vIndices = pKF->GetFeaturesInArea(u,v,radius);
if(vIndices.empty())
continue;
// Match to the most similar keypoint in the radius
const cv::Mat dMP = pMP->GetDescriptor();
int bestDist = 256;
int bestIdx = -1;
for(vector<size_t>::const_iterator vit=vIndices.begin(), vend=vIndices.end(); vit!=vend; vit++)
{
const size_t idx = *vit;
const cv::KeyPoint &kp = pKF->mvKeysUn[idx];
const int &kpLevel= kp.octave;
if(kpLevel<nPredictedLevel-1 || kpLevel>nPredictedLevel)
continue;
if(pKF->mvuRight[idx]>=0)
{
// Check reprojection error in stereo
const float &kpx = kp.pt.x;
const float &kpy = kp.pt.y;
const float &kpr = pKF->mvuRight[idx];
const float ex = u-kpx;
const float ey = v-kpy;
const float er = ur-kpr;
const float e2 = ex*ex+ey*ey+er*er;
if(e2*pKF->mvInvLevelSigma2[kpLevel]>7.8)
continue;
}
else
{
const float &kpx = kp.pt.x;
const float &kpy = kp.pt.y;
const float ex = u-kpx;
const float ey = v-kpy;
const float e2 = ex*ex+ey*ey;
if(e2*pKF->mvInvLevelSigma2[kpLevel]>5.99)
continue;
}
const cv::Mat &dKF = pKF->mDescriptors.row(idx);
const int dist = DescriptorDistance(dMP,dKF);
if(dist<bestDist)
{
bestDist = dist;
bestIdx = idx;
}
}
// If there is already a MapPoint replace otherwise add new measurement
if(bestDist<=TH_LOW)
{
MapPoint* pMPinKF = pKF->GetMapPoint(bestIdx);
if(pMPinKF)
{
if(!pMPinKF->isBad())
{
if(pMPinKF->Observations()>pMP->Observations())
pMP->Replace(pMPinKF);
else
pMPinKF->Replace(pMP);
}
}
else
{
pMP->AddObservation(pKF,bestIdx);
pKF->AddMapPoint(pMP,bestIdx);
}
nFused++;
}
}
return nFused;
}
int ORBmatcher::Fuse(KeyFrame *pKF, cv::Mat Scw, const vector<MapPoint *> &vpPoints, float th, vector<MapPoint *> &vpReplacePoint)
{
// Get Calibration Parameters for later projection
const float &fx = pKF->fx;
const float &fy = pKF->fy;
const float &cx = pKF->cx;
const float &cy = pKF->cy;
// Decompose Scw
cv::Mat sRcw = Scw.rowRange(0,3).colRange(0,3);
const float scw = sqrt(sRcw.row(0).dot(sRcw.row(0)));
cv::Mat Rcw = sRcw/scw;
cv::Mat tcw = Scw.rowRange(0,3).col(3)/scw;
cv::Mat Ow = -Rcw.t()*tcw;
// Set of MapPoints already found in the KeyFrame
const set<MapPoint*> spAlreadyFound = pKF->GetMapPoints();
int nFused=0;
const int nPoints = vpPoints.size();
// For each candidate MapPoint project and match
for(int iMP=0; iMP<nPoints; iMP++)
{
MapPoint* pMP = vpPoints[iMP];
// Discard Bad MapPoints and already found
if(pMP->isBad() || spAlreadyFound.count(pMP))
continue;
// Get 3D Coords.
cv::Mat p3Dw = pMP->GetWorldPos();
// Transform into Camera Coords.
cv::Mat p3Dc = Rcw*p3Dw+tcw;
// Depth must be positive
if(p3Dc.at<float>(2)<0.0f)
continue;
// Project into Image
const float invz = 1.0/p3Dc.at<float>(2);
const float x = p3Dc.at<float>(0)*invz;
const float y = p3Dc.at<float>(1)*invz;
const float u = fx*x+cx;
const float v = fy*y+cy;
// Point must be inside the image
if(!pKF->IsInImage(u,v))
continue;
// Depth must be inside the scale pyramid of the image
const float maxDistance = pMP->GetMaxDistanceInvariance();
const float minDistance = pMP->GetMinDistanceInvariance();
cv::Mat PO = p3Dw-Ow;
const float dist3D = cv::norm(PO);
if(dist3D<minDistance || dist3D>maxDistance)
continue;
// Viewing angle must be less than 60 deg
cv::Mat Pn = pMP->GetNormal();
if(PO.dot(Pn)<0.5*dist3D)
continue;
// Compute predicted scale level
const int nPredictedLevel = pMP->PredictScale(dist3D,pKF->mfLogScaleFactor);
// Search in a radius
const float radius = th*pKF->mvScaleFactors[nPredictedLevel];
const vector<size_t> vIndices = pKF->GetFeaturesInArea(u,v,radius);
if(vIndices.empty())
continue;
// Match to the most similar keypoint in the radius
const cv::Mat dMP = pMP->GetDescriptor();
int bestDist = INT_MAX;
int bestIdx = -1;
for(vector<size_t>::const_iterator vit=vIndices.begin(); vit!=vIndices.end(); vit++)
{
const size_t idx = *vit;
const int &kpLevel = pKF->mvKeysUn[idx].octave;
if(kpLevel<nPredictedLevel-1 || kpLevel>nPredictedLevel)
continue;
const cv::Mat &dKF = pKF->mDescriptors.row(idx);
int dist = DescriptorDistance(dMP,dKF);
if(dist<bestDist)
{
bestDist = dist;
bestIdx = idx;
}
}
// If there is already a MapPoint replace otherwise add new measurement
if(bestDist<=TH_LOW)
{
MapPoint* pMPinKF = pKF->GetMapPoint(bestIdx);
if(pMPinKF)
{
if(!pMPinKF->isBad())
vpReplacePoint[iMP] = pMPinKF;
}
else
{
pMP->AddObservation(pKF,bestIdx);
pKF->AddMapPoint(pMP,bestIdx);
}
nFused++;
}
}
return nFused;
}
int ORBmatcher::SearchBySim3(KeyFrame *pKF1, KeyFrame *pKF2, vector<MapPoint*> &vpMatches12,
const float &s12, const cv::Mat &R12, const cv::Mat &t12, const float th)
{
const float &fx = pKF1->fx;
const float &fy = pKF1->fy;
const float &cx = pKF1->cx;
const float &cy = pKF1->cy;
// Camera 1 from world
cv::Mat R1w = pKF1->GetRotation();
cv::Mat t1w = pKF1->GetTranslation();
//Camera 2 from world
cv::Mat R2w = pKF2->GetRotation();
cv::Mat t2w = pKF2->GetTranslation();
//Transformation between cameras
cv::Mat sR12 = s12*R12;
cv::Mat sR21 = (1.0/s12)*R12.t();
cv::Mat t21 = -sR21*t12;
const vector<MapPoint*> vpMapPoints1 = pKF1->GetMapPointMatches();
const int N1 = vpMapPoints1.size();
const vector<MapPoint*> vpMapPoints2 = pKF2->GetMapPointMatches();
const int N2 = vpMapPoints2.size();
vector<bool> vbAlreadyMatched1(N1,false);
vector<bool> vbAlreadyMatched2(N2,false);
for(int i=0; i<N1; i++)
{
MapPoint* pMP = vpMatches12[i];
if(pMP)
{
vbAlreadyMatched1[i]=true;
int idx2 = pMP->GetIndexInKeyFrame(pKF2);
if(idx2>=0 && idx2<N2)
vbAlreadyMatched2[idx2]=true;
}
}
vector<int> vnMatch1(N1,-1);
vector<int> vnMatch2(N2,-1);
// Transform from KF1 to KF2 and search
for(int i1=0; i1<N1; i1++)
{
MapPoint* pMP = vpMapPoints1[i1];
if(!pMP || vbAlreadyMatched1[i1])
continue;
if(pMP->isBad())
continue;
cv::Mat p3Dw = pMP->GetWorldPos();
cv::Mat p3Dc1 = R1w*p3Dw + t1w;
cv::Mat p3Dc2 = sR21*p3Dc1 + t21;
// Depth must be positive
if(p3Dc2.at<float>(2)<0.0)
continue;
const float invz = 1.0/p3Dc2.at<float>(2);
const float x = p3Dc2.at<float>(0)*invz;
const float y = p3Dc2.at<float>(1)*invz;
const float u = fx*x+cx;
const float v = fy*y+cy;
// Point must be inside the image
if(!pKF2->IsInImage(u,v))
continue;
const float maxDistance = pMP->GetMaxDistanceInvariance();
const float minDistance = pMP->GetMinDistanceInvariance();
const float dist3D = cv::norm(p3Dc2);
// Depth must be inside the scale invariance region
if(dist3D<minDistance || dist3D>maxDistance )
continue;
// Compute predicted octave
const int nPredictedLevel = pMP->PredictScale(dist3D,pKF2->mfLogScaleFactor);
// Search in a radius
const float radius = th*pKF2->mvScaleFactors[nPredictedLevel];
const vector<size_t> vIndices = pKF2->GetFeaturesInArea(u,v,radius);
if(vIndices.empty())
continue;
// Match to the most similar keypoint in the radius
const cv::Mat dMP = pMP->GetDescriptor();
int bestDist = INT_MAX;
int bestIdx = -1;
for(vector<size_t>::const_iterator vit=vIndices.begin(), vend=vIndices.end(); vit!=vend; vit++)
{
const size_t idx = *vit;
const cv::KeyPoint &kp = pKF2->mvKeysUn[idx];
if(kp.octave<nPredictedLevel-1 || kp.octave>nPredictedLevel)
continue;
const cv::Mat &dKF = pKF2->mDescriptors.row(idx);
const int dist = DescriptorDistance(dMP,dKF);
if(dist<bestDist)
{
bestDist = dist;
bestIdx = idx;
}
}
if(bestDist<=TH_HIGH)
{
vnMatch1[i1]=bestIdx;
}
}
// Transform from KF2 to KF2 and search
for(int i2=0; i2<N2; i2++)
{
MapPoint* pMP = vpMapPoints2[i2];
if(!pMP || vbAlreadyMatched2[i2])
continue;
if(pMP->isBad())
continue;
cv::Mat p3Dw = pMP->GetWorldPos();
cv::Mat p3Dc2 = R2w*p3Dw + t2w;
cv::Mat p3Dc1 = sR12*p3Dc2 + t12;
// Depth must be positive
if(p3Dc1.at<float>(2)<0.0)
continue;
const float invz = 1.0/p3Dc1.at<float>(2);
const float x = p3Dc1.at<float>(0)*invz;
const float y = p3Dc1.at<float>(1)*invz;
const float u = fx*x+cx;
const float v = fy*y+cy;
// Point must be inside the image
if(!pKF1->IsInImage(u,v))
continue;
const float maxDistance = pMP->GetMaxDistanceInvariance();
const float minDistance = pMP->GetMinDistanceInvariance();
const float dist3D = cv::norm(p3Dc1);
// Depth must be inside the scale pyramid of the image
if(dist3D<minDistance || dist3D>maxDistance)
continue;
// Compute predicted octave
const int nPredictedLevel = pMP->PredictScale(dist3D,pKF1->mfLogScaleFactor);
// Search in a radius of 2.5*sigma(ScaleLevel)
const float radius = th*pKF1->mvScaleFactors[nPredictedLevel];
const vector<size_t> vIndices = pKF1->GetFeaturesInArea(u,v,radius);
if(vIndices.empty())
continue;
// Match to the most similar keypoint in the radius
const cv::Mat dMP = pMP->GetDescriptor();
int bestDist = INT_MAX;
int bestIdx = -1;
for(vector<size_t>::const_iterator vit=vIndices.begin(), vend=vIndices.end(); vit!=vend; vit++)
{
const size_t idx = *vit;
const cv::KeyPoint &kp = pKF1->mvKeysUn[idx];
if(kp.octave<nPredictedLevel-1 || kp.octave>nPredictedLevel)
continue;
const cv::Mat &dKF = pKF1->mDescriptors.row(idx);
const int dist = DescriptorDistance(dMP,dKF);
if(dist<bestDist)
{
bestDist = dist;
bestIdx = idx;
}
}
if(bestDist<=TH_HIGH)
{
vnMatch2[i2]=bestIdx;
}
}
// Check agreement
int nFound = 0;
for(int i1=0; i1<N1; i1++)
{
int idx2 = vnMatch1[i1];
if(idx2>=0)
{
int idx1 = vnMatch2[idx2];
if(idx1==i1)
{
vpMatches12[i1] = vpMapPoints2[idx2];
nFound++;
}
}
}
return nFound;
}
int ORBmatcher::SearchByProjection(Frame &CurrentFrame, const Frame &LastFrame, const float th, const bool bMono)
{
int nmatches = 0;
// Rotation Histogram (to check rotation consistency)
vector<int> rotHist[HISTO_LENGTH];
for(int i=0;i<HISTO_LENGTH;i++)
rotHist[i].reserve(500);
const float factor = 1.0f/HISTO_LENGTH;
const cv::Mat Rcw = CurrentFrame.mTcw.rowRange(0,3).colRange(0,3);
const cv::Mat tcw = CurrentFrame.mTcw.rowRange(0,3).col(3);
const cv::Mat twc = -Rcw.t()*tcw;
const cv::Mat Rlw = LastFrame.mTcw.rowRange(0,3).colRange(0,3);
const cv::Mat tlw = LastFrame.mTcw.rowRange(0,3).col(3);
const cv::Mat tlc = Rlw*twc+tlw;
const bool bForward = tlc.at<float>(2)>CurrentFrame.mb && !bMono;
const bool bBackward = -tlc.at<float>(2)>CurrentFrame.mb && !bMono;
for(int i=0; i<LastFrame.N; i++)
{
MapPoint* pMP = LastFrame.mvpMapPoints[i];
if(pMP)
{
if(!LastFrame.mvbOutlier[i])
{
// Project
cv::Mat x3Dw = pMP->GetWorldPos();
cv::Mat x3Dc = Rcw*x3Dw+tcw;
const float xc = x3Dc.at<float>(0);
const float yc = x3Dc.at<float>(1);
const float invzc = 1.0/x3Dc.at<float>(2);
if(invzc<0)
continue;
float u = CurrentFrame.fx*xc*invzc+CurrentFrame.cx;
float v = CurrentFrame.fy*yc*invzc+CurrentFrame.cy;
if(u<CurrentFrame.mnMinX || u>CurrentFrame.mnMaxX)
continue;
if(v<CurrentFrame.mnMinY || v>CurrentFrame.mnMaxY)
continue;
int nLastOctave = LastFrame.mvKeys[i].octave;
// Search in a window. Size depends on scale
float radius = th*CurrentFrame.mvScaleFactors[nLastOctave];
vector<size_t> vIndices2;
if(bForward)
vIndices2 = CurrentFrame.GetFeaturesInArea(u,v, radius, nLastOctave);
else if(bBackward)
vIndices2 = CurrentFrame.GetFeaturesInArea(u,v, radius, 0, nLastOctave);
else
vIndices2 = CurrentFrame.GetFeaturesInArea(u,v, radius, nLastOctave-1, nLastOctave+1);
if(vIndices2.empty())
continue;
const cv::Mat dMP = pMP->GetDescriptor();
int bestDist = 256;
int bestIdx2 = -1;
for(vector<size_t>::const_iterator vit=vIndices2.begin(), vend=vIndices2.end(); vit!=vend; vit++)
{
const size_t i2 = *vit;
if(CurrentFrame.mvpMapPoints[i2])
if(CurrentFrame.mvpMapPoints[i2]->Observations()>0)
continue;
if(CurrentFrame.mvuRight[i2]>0)
{
const float ur = u - CurrentFrame.mbf*invzc;
const float er = fabs(ur - CurrentFrame.mvuRight[i2]);
if(er>radius)
continue;
}
const cv::Mat &d = CurrentFrame.mDescriptors.row(i2);
const int dist = DescriptorDistance(dMP,d);
if(dist<bestDist)
{
bestDist=dist;
bestIdx2=i2;
}
}
if(bestDist<=TH_HIGH)
{
CurrentFrame.mvpMapPoints[bestIdx2]=pMP;
nmatches++;
if(mbCheckOrientation)
{
float rot = LastFrame.mvKeysUn[i].angle-CurrentFrame.mvKeysUn[bestIdx2].angle;
if(rot<0.0)
rot+=360.0f;
int bin = round(rot*factor);
if(bin==HISTO_LENGTH)
bin=0;
assert(bin>=0 && bin<HISTO_LENGTH);
rotHist[bin].push_back(bestIdx2);
}
}
}
}
}
//Apply rotation consistency
if(mbCheckOrientation)
{
int ind1=-1;
int ind2=-1;
int ind3=-1;
ComputeThreeMaxima(rotHist,HISTO_LENGTH,ind1,ind2,ind3);
for(int i=0; i<HISTO_LENGTH; i++)
{
if(i!=ind1 && i!=ind2 && i!=ind3)
{
for(size_t j=0, jend=rotHist[i].size(); j<jend; j++)
{
CurrentFrame.mvpMapPoints[rotHist[i][j]]=static_cast<MapPoint*>(NULL);
nmatches--;
}
}
}
}
return nmatches;
}
int ORBmatcher::SearchByProjection(Frame &CurrentFrame, KeyFrame *pKF, const set<MapPoint*> &sAlreadyFound, const float th , const int ORBdist)
{
int nmatches = 0;
const cv::Mat Rcw = CurrentFrame.mTcw.rowRange(0,3).colRange(0,3);
const cv::Mat tcw = CurrentFrame.mTcw.rowRange(0,3).col(3);
const cv::Mat Ow = -Rcw.t()*tcw;
// Rotation Histogram (to check rotation consistency)
vector<int> rotHist[HISTO_LENGTH];
for(int i=0;i<HISTO_LENGTH;i++)
rotHist[i].reserve(500);
const float factor = 1.0f/HISTO_LENGTH;
const vector<MapPoint*> vpMPs = pKF->GetMapPointMatches();
for(size_t i=0, iend=vpMPs.size(); i<iend; i++)
{
MapPoint* pMP = vpMPs[i];
if(pMP)
{
if(!pMP->isBad() && !sAlreadyFound.count(pMP))
{
//Project
cv::Mat x3Dw = pMP->GetWorldPos();
cv::Mat x3Dc = Rcw*x3Dw+tcw;
const float xc = x3Dc.at<float>(0);
const float yc = x3Dc.at<float>(1);
const float invzc = 1.0/x3Dc.at<float>(2);
const float u = CurrentFrame.fx*xc*invzc+CurrentFrame.cx;
const float v = CurrentFrame.fy*yc*invzc+CurrentFrame.cy;
if(u<CurrentFrame.mnMinX || u>CurrentFrame.mnMaxX)
continue;
if(v<CurrentFrame.mnMinY || v>CurrentFrame.mnMaxY)
continue;
// Compute predicted scale level
cv::Mat PO = x3Dw-Ow;
float dist3D = cv::norm(PO);
const float maxDistance = pMP->GetMaxDistanceInvariance();
const float minDistance = pMP->GetMinDistanceInvariance();
// Depth must be inside the scale pyramid of the image
if(dist3D<minDistance || dist3D>maxDistance)
continue;
int nPredictedLevel = pMP->PredictScale(dist3D,CurrentFrame.mfLogScaleFactor);
// Search in a window
const float radius = th*CurrentFrame.mvScaleFactors[nPredictedLevel];
const vector<size_t> vIndices2 = CurrentFrame.GetFeaturesInArea(u, v, radius, nPredictedLevel-1, nPredictedLevel+1);
if(vIndices2.empty())
continue;
const cv::Mat dMP = pMP->GetDescriptor();
int bestDist = 256;
int bestIdx2 = -1;
for(vector<size_t>::const_iterator vit=vIndices2.begin(); vit!=vIndices2.end(); vit++)
{
const size_t i2 = *vit;
if(CurrentFrame.mvpMapPoints[i2])
continue;
const cv::Mat &d = CurrentFrame.mDescriptors.row(i2);
const int dist = DescriptorDistance(dMP,d);
if(dist<bestDist)
{
bestDist=dist;
bestIdx2=i2;
}
}
if(bestDist<=ORBdist)
{
CurrentFrame.mvpMapPoints[bestIdx2]=pMP;
nmatches++;
if(mbCheckOrientation)
{
float rot = pKF->mvKeysUn[i].angle-CurrentFrame.mvKeysUn[bestIdx2].angle;
if(rot<0.0)
rot+=360.0f;
int bin = round(rot*factor);
if(bin==HISTO_LENGTH)
bin=0;
assert(bin>=0 && bin<HISTO_LENGTH);
rotHist[bin].push_back(bestIdx2);
}
}
}
}
}
if(mbCheckOrientation)
{
int ind1=-1;
int ind2=-1;
int ind3=-1;
ComputeThreeMaxima(rotHist,HISTO_LENGTH,ind1,ind2,ind3);
for(int i=0; i<HISTO_LENGTH; i++)
{
if(i!=ind1 && i!=ind2 && i!=ind3)
{
for(size_t j=0, jend=rotHist[i].size(); j<jend; j++)
{
CurrentFrame.mvpMapPoints[rotHist[i][j]]=NULL;
nmatches--;
}
}
}
}
return nmatches;
}
void ORBmatcher::ComputeThreeMaxima(vector<int>* histo, const int L, int &ind1, int &ind2, int &ind3)
{
int max1=0;
int max2=0;
int max3=0;
for(int i=0; i<L; i++)
{
const int s = histo[i].size();
if(s>max1)
{
max3=max2;
max2=max1;
max1=s;
ind3=ind2;
ind2=ind1;
ind1=i;
}
else if(s>max2)
{
max3=max2;
max2=s;
ind3=ind2;
ind2=i;
}
else if(s>max3)
{
max3=s;
ind3=i;
}
}
if(max2<0.1f*(float)max1)
{
ind2=-1;
ind3=-1;
}
else if(max3<0.1f*(float)max1)
{
ind3=-1;
}
}
// Bit set count operation from
// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
int ORBmatcher::DescriptorDistance(const cv::Mat &a, const cv::Mat &b)
{
const int *pa = a.ptr<int32_t>();
const int *pb = b.ptr<int32_t>();
int dist=0;
for(int i=0; i<8; i++, pa++, pb++)
{
unsigned int v = *pa ^ *pb;
v = v - ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
dist += (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
return dist;
}
} //namespace ORB_SLAM
| [
"zaonmax@inbox.ru"
] | zaonmax@inbox.ru |
e709ffbd74218f459b32e9fae3de98ac2b66470a | e0d6fd9e1c6f5401810f97ded178c4dcebd15f2b | /luogu/p1233_2.cpp | a99206e88bf5b9cd1755145e4c2d0ab3e7599ce1 | [] | no_license | yangzebin001/OJ | 3d03edcb7133b974202fdceeba68f9d51724a055 | 34a4f03793f358d3770336af3e624feddfb3e9b3 | refs/heads/master | 2021-06-28T02:18:14.067208 | 2021-01-13T06:51:23 | 2021-01-13T06:51:23 | 202,832,472 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | cpp | /*
* @Author: BeckoninGshy
* @Date: 2020-10-09 09:38:46
* @Last Modified by: BeckoninGshy
* @Last Modified time: 2020-10-09 09:46:24
*/
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 5010;
struct e{
int l,w;
}p[MAXN];
int dp[MAXN], len;
bool cmp(e &a, e &b){
if(a.l == b.l) return a.w > b.w;
return a.l > b.l;
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++){
cin >> p[i].l >> p[i].w;
}
sort(p,p+n, cmp);
int ans = 0;
//对w求最长上升子序列
for(int i = 0; i < n; i++){
int j = lower_bound(dp, dp+len, p[i].w) - dp;
if(j == len) dp[len++] = p[i].w;
else dp[j] = p[i].w;
}
cout << len;
return 0;
} | [
"405678856@qq.com"
] | 405678856@qq.com |
53fb8a27664d6d2cc23521d5232dfff8acf52159 | bc0945070d150c8af7cc56bf6e045a8c2cc7873d | /3369/2599879_OLE.cpp | faa1ccffec09a002f6e584210b7cdd216d76661f | [] | no_license | fengrenchang86/PKU | ab889d88cd62b3c0b3e00cde5d5c3a652a16221a | 0c4adf6b740d2186b7f23124673cd56520d1c818 | refs/heads/master | 2021-01-10T12:12:18.100884 | 2016-03-07T14:14:33 | 2016-03-07T14:14:33 | 53,328,385 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | cpp | #include <iostream>
#include <math.h>
using namespace std;
double a[5];
int main ()
{
double a,b,c,d;
int count = 0;
int h;
char ch[120];
for ( a = 0.01; a*a*a*a<=20; a+=0.01 )
{
for ( b = a; b+a+b+b<=20&&b*a*b*b<=20; b+=0.01 )
{
for ( c = b; a+b+c+c<=20&&a*b*c*c<=20;c+=0.01 )
{
d = (a+b+c)/(a*b*c-1);
h = d*100;
d = h/100;
// d = double(int(d*100)/100);
if ( a+b+c+d-a*b*c*d > 0.001 || a+b+c+d-a*b*c*d < -0.001 )
continue;
if ( d >= c && a+b+c+d <= 20 )
{
printf("%.2lf %.2lf %.2lf %.2lf\n",a,b,c,d);
// count++;
}
}
}
}
// cout<<count<<endl;
return 0;
} | [
"fengrenchang86@gmail.com"
] | fengrenchang86@gmail.com |
173fe9741a18d760d05e67b2a05b524d593672fa | 985e7e38cb115b160da3d79811b02883d7f9080c | /samples/misc/specials_dg/makeownr.cpp | 6901a1c57f5f365832805a64fd52098e048ea463 | [] | no_license | jidzhang/ObjectARX2018 | a3ad7c3e36ea6b27edfb5963f5e43b83a523004b | 012e8dac91500d5fd6c9138d87eee94b6c10b07c | refs/heads/master | 2021-01-22T07:49:11.392757 | 2017-05-31T02:21:07 | 2017-05-31T02:21:07 | 92,580,081 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,199 | cpp | //
//////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
#if defined(_DEBUG) && !defined(AC_FULL_DEBUG)
#error _DEBUG should not be defined except in internal Adesk debug builds
#endif
// THE FOLLOWING CODE APPEARS IN THE SDK DOCUMENT.
// Uses the OwnerDemo class defined in the next example
// (see "ARX Example," below)
// Sets pOwner to be the owner of pOwned
//
void
makeOwner(OwnerDemo* pOwner, AcDbObject* pOwned)
{
// First let pOwner know its the owner. This
// establishes ownership for filing persistence.
//
pOwner->setIdData(pOwned->ojectId());
// Now set up the backpointer so that the owned
// object knows who it's owner is.
//
pOwned->setOwnerId(pOwner->objectId());
// END CODE APPEARING IN SDK DOCUMENT.
| [
"545628606[AT]qq.com"
] | 545628606[AT]qq.com |
97bce197340c5e2c0fed1c31852fdc862477aaa9 | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/test/directx/dplay/testnet/tncontrl/vars.h | 97349a971e221a9c7eb8e4b40e5764d9e41f5b35 | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,481 | h | #ifndef __TNCONTROL_VARS__
#define __TNCONTROL_VARS__
//#pragma message("Defining __TNCONTROL_VARS__")
//==================================================================================
// Defines
//==================================================================================
#ifdef TNCONTRL_EXPORTS
#ifdef DLLEXPORT
#undef DLLEXPORT
#endif // ! DLLEXPORT
#define DLLEXPORT __declspec(dllexport)
#else // ! TNCONTRL_EXPORTS
#ifdef DLLEXPORT
#undef DLLEXPORT
#endif // ! DLLEXPORT
#define DLLEXPORT __declspec(dllimport)
#endif // ! TNCONTRL_EXPORTS
#ifndef DEBUG
#ifdef _DEBUG
#define DEBUG
#endif // _DEBUG
#endif // not DEBUG
//==================================================================================
// External Classes
//==================================================================================
class DLLEXPORT CTNOutputVar:public CLString
{
// These are friends so they can access the protected members
friend CTNOutputVarsList;
#ifndef _XBOX // ! no master supported
friend CTNMaster;
#endif // ! XBOX
friend CTNExecutorPriv;
protected:
char* m_pszType; // string representatin of the value
LPVOID m_pvValue; // pointer to value
DWORD m_dwValueSize; // size of value
public:
CTNOutputVar(char* szName, char* szType, PVOID pvValue, DWORD dwValueSize);
virtual ~CTNOutputVar(void);
};
class DLLEXPORT CTNOutputVarsList:public CLStringList
{
// These are friends so they can access the protected members
friend CTNResult;
#ifndef _XBOX // ! no master supported
friend CTNMaster;
#endif // ! XBOX
#ifndef _XBOX // no IPC supported
friend CTNLeech;
#endif // ! XBOX
protected:
PVOID m_pvOutputDataStart; // current starting point for output data buffer (used for offsets)
public:
CTNOutputVarsList(void);
HRESULT AddVariable(char* szName, char* szType, PVOID pvValueLocation,
DWORD dwValueSize);
HRESULT GetVariable(char* szName, char* szType, PVOID* ppvValueLocation,
DWORD* pdwValueSize);
HRESULT GetFirstVariableOfType(char* szType, char** ppszName,
PVOID* ppvValueLocation,
DWORD* pdwValueSize);
HRESULT PackIntoBuffer(PVOID pvBuffer, DWORD* pdwBufferSize);
HRESULT UnpackFromBuffer(PVOID pvBuffer, DWORD dwBufferSize);
};
#else //__TNCONTROL_VARS__
//#pragma message("__TNCONTROL_VARS__ already included!")
#endif //__TNCONTROL_VARS__
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
bef0c5ed3cc8a25cff91f2d869551db8e8a294ab | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/sync/engine/net/url_translator.cc | a6fffdfc0ff159fc67c465d6837543ac8ef760a7 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 1,455 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Contains the definition of a few helper functions used for generating sync
// URLs.
#include "sync/engine/net/url_translator.h"
#include "net/base/escape.h"
using std::string;
namespace syncer {
namespace {
// Parameters that the server understands. (here, a-Z)
const char kParameterClient[] = "client";
const char kParameterClientID[] = "client_id";
#if defined(GOOGLE_CHROME_BUILD)
const char kClientName[] = "Google Chrome";
#else
const char kClientName[] = "Chromium";
#endif // defined(GOOGLE_CHROME_BUILD)
} // namespace
// Convenience wrappers around CgiEscapePath().
string CgiEscapeString(const char* src) {
return CgiEscapeString(string(src));
}
string CgiEscapeString(const string& src) {
return net::EscapeUrlEncodedData(src, true);
}
// This method appends the query string to the sync server path.
string MakeSyncServerPath(const string& path, const string& query_string) {
string result = path;
result.append("?");
result.append(query_string);
return result;
}
string MakeSyncQueryString(const string& client_id) {
string query;
query += kParameterClient;
query += "=" + CgiEscapeString(kClientName);
query += "&";
query += kParameterClientID;
query += "=" + CgiEscapeString(client_id);
return query;
}
} // namespace syncer
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
4b820465acdcbb17daa367bfd94d867df5c38ab8 | 56fdf274afa0ecde4deacca0eb071b835e905ad7 | /WidgetsPlugin/wbaseqsswidget.cpp | 4bf86b8e97124f7de925871cd0fe13b4fc20da56 | [] | no_license | yang123vc/CompareFiles | 22f290a99d020496d4a0dbed106810c80c261b91 | 6a73ba3526a69d146d0569f98026ac9cc20be6cd | refs/heads/master | 2020-05-07T05:56:18.493026 | 2014-03-13T02:04:40 | 2014-03-13T02:04:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | #include "wbaseqsswidget.h"
#include <QStyleOption>
#include <QPainter>
WBaseQssWidget::WBaseQssWidget(QWidget *parent) :
QWidget(parent)
{
}
void WBaseQssWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
WIDGET_EXTENT_FUN_IMPLEMENT(WBaseQssWidget)
| [
"kevingeelong@gmail.com"
] | kevingeelong@gmail.com |
95de975bb2d20eb232e9b2e2f55a804425522481 | f13ae2aa1cc1c6b9788bd6abfef615bfee10aad2 | /practice9.cpp | 471b58df38ab9f0facfe20241bd3a24bcb369f21 | [] | no_license | AsylzhanUtegen/tasks | 4ffed44a6d6d0fefc0da2243f19ae37990e96e8f | 7fa5c0ee8ee09dee98e331a64828b4d836971d05 | refs/heads/master | 2020-09-12T15:59:49.406046 | 2019-11-23T08:10:59 | 2019-11-23T08:10:59 | 222,472,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 106 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int x = -2;
cout<<abs(x)+pow( x , 5 );
}
| [
"noreply@github.com"
] | AsylzhanUtegen.noreply@github.com |
bd1889fc12872a00f81ebc9f77d5f848d36bfdcc | c15238af82f9fc92d3b477b11b7cf67adc1bfdfe | /components/webapps/services/web_app_origin_association/web_app_origin_association_fetcher.h | 4b5b6cefadcd8443690aab3ea96c0893d60d17c5 | [
"BSD-3-Clause"
] | permissive | arukshani/chromium | 57198ff34331e1957c5e701be3f6b2eafa7e5d46 | fe705870d35ffda2b3dccdfca869a8d682686dc7 | refs/heads/master | 2023-03-05T01:08:46.018522 | 2021-02-16T03:02:46 | 2021-02-16T03:02:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,138 | h | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_WEBAPPS_SERVICES_WEB_APP_ORIGIN_ASSOCIATION_WEB_APP_ORIGIN_ASSOCIATION_FETCHER_H_
#define COMPONENTS_WEBAPPS_SERVICES_WEB_APP_ORIGIN_ASSOCIATION_WEB_APP_ORIGIN_ASSOCIATION_FETCHER_H_
#include <memory>
#include <string>
#include "base/callback.h"
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "components/services/app_service/public/cpp/url_handler_info.h"
#include "services/network/public/cpp/simple_url_loader.h"
class GURL;
namespace network {
class SharedURLLoaderFactory;
} // namespace network
namespace webapps {
using FetchFileCallback =
base::OnceCallback<void(std::unique_ptr<std::string> file_content)>;
// Makes network requests to fetch web app origin association files.
class WebAppOriginAssociationFetcher {
public:
WebAppOriginAssociationFetcher();
~WebAppOriginAssociationFetcher();
WebAppOriginAssociationFetcher(const WebAppOriginAssociationFetcher&) =
delete;
WebAppOriginAssociationFetcher& operator=(
const WebAppOriginAssociationFetcher&) = delete;
void FetchWebAppOriginAssociationFile(
const apps::UrlHandlerInfo& url_handler,
scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
FetchFileCallback callback);
void SetRetryOptionsForTest(int max_retry,
network::SimpleURLLoader::RetryMode retry_mode);
private:
void SendRequest(
const GURL& url,
scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory,
FetchFileCallback callback);
void OnResponse(FetchFileCallback callback,
std::unique_ptr<std::string> response_body);
std::unique_ptr<network::SimpleURLLoader> url_loader_;
base::WeakPtrFactory<WebAppOriginAssociationFetcher> weak_ptr_factory_{this};
};
} // namespace webapps
#endif // COMPONENTS_WEBAPPS_SERVICES_WEB_APP_ORIGIN_ASSOCIATION_WEB_APP_ORIGIN_ASSOCIATION_FETCHER_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
14647cd43a9c8af322bb13160878c881280180be | 6255cf7d057e7df9d23d22beadc28722267cef96 | /ToolCode/SolidBody.cpp | a3019624590744fd7354ee49279c37f58a0511e8 | [] | no_license | 15831944/ToolKits | 31749148daf71871e6225f66c9282bcda3d95db0 | f1700d7e1ca12a6c13c4d13663d48339093b6810 | refs/heads/master | 2020-08-28T10:07:33.176421 | 2019-09-28T05:30:15 | 2019-09-28T05:30:15 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 42,988 | cpp | #include "stdafx.h"
#include "HashTable.h"
#include "ArrayList.h"
#include ".\solidbody.h"
#ifndef _DISABLE_DEBUG_NEW_
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#endif
#ifndef _DISABLE_ALG_FUNC_
#include "f_alg_fun.h"
#else
//defined TidToolFunc.cpp
BOOL vector_trans( double* vcoord, UCS_STRU ucs, BOOL fromUcs,BOOL bSkipStandardize=TRUE);
BOOL coord_trans(double* ptcoord,UCS_STRU ucs,BOOL fromUcs,BOOL bSkipStandardize=TRUE);
static bool _LocalNormalize(double* v/*[3]*/)
{
double squre=v[0]*v[0]+v[1]*v[1]+v[2]*v[2];
if(0.99999998<=squre&&squre<=1.00000001) //此时tan(a)<0.0001
return true;
else if(squre<1e-16)
return false;
double root=sqrt(squre);
if(v[0]!=0)
v[0]/=root;
if(v[1]!=0)
v[1]/=root;
if(v[2]!=0)
v[2]/=root;
return true;
}
bool is_ucs_valid(const UCS_STRU& ucs)
{
double dd;
f3dPoint norm;
UCS_STRU cs=ucs;
_LocalNormalize(cs.axis_x);
_LocalNormalize(cs.axis_y);
_LocalNormalize(cs.axis_z);
//1.判断是坐标系是否正交
dd = ucs.axis_x*ucs.axis_y;
if( fabs(dd)>eps)
return false;
dd = ucs.axis_x*ucs.axis_z;
if( fabs(dd)>eps)
return false;
dd = ucs.axis_y*ucs.axis_z;
if( fabs(dd)>eps)
return false;
return true;
}
#endif
const BYTE CRawSolidEdge::NURBS =0x00;
const BYTE CRawSolidEdge::STRAIGHT =0x01;
const BYTE CRawSolidEdge::ARCLINE =0x02;
const BYTE CRawSolidEdge::ELLIPSE =0x03;
//
const BYTE CRawSolidFace::MATERIAL_COLOR = 0;
const BYTE CRawSolidFace::WORK_NORM = 5;
const BYTE CRawSolidFace::BASICFACE_ID = 29;
const BYTE CRawSolidFace::INNERLOOP_N = 33;
const BYTE CRawSolidFace::INNERLOOP_INDEX_ADDR = 35;
////////////////////////////////////////////////////////////////////////////
WORD CFaceLoop::LoopEdgeLineNum()
{
return *((WORD*)memoryAddr); //读取环上边线总数
}
static DWORD BuffSize(BYTE* buf,int byte_num=4){
if(byte_num==4)
return *((DWORD*)buf);
else if(byte_num==2)
return *((WORD*)buf);
else
return *buf;
}
DWORD CFaceLoop::LoopEdgeLineIdAt(int i)
{
if(i<0||i>=LoopEdgeLineNum())
return false; //地址越界
DWORD* lat=(DWORD*)(memoryAddr+2); //Line Allocation Table
DWORD edge_id=(DWORD)*(lat+i);
return edge_id;
}
bool CFaceLoop::GetLoopEdgeLineAt(CSolidBody* pBody,int i,f3dArcLine& line)
{
if(i<0||i>=LoopEdgeLineNum())
return false; //地址越界
DWORD* lat=(DWORD*)(memoryAddr+2); //Line Allocation Table
DWORD edge_id=(DWORD)*(lat+i);
if(!pBody->GetKeyEdgeLineAt((edge_id&0x7FFFFFFF)-1,line))
return false;
line.ID=edge_id;
return true;
}
DWORD CFaceLoop::GetLoopEdgeLineAt(CSolidBody* pBody,int i,CRawSolidEdge& edge)
{
if(i<0||i>=LoopEdgeLineNum())
return 0; //地址越界
DWORD* lat=(DWORD*)(memoryAddr+2); //Line Allocation Table
DWORD edge_id=(DWORD)*(lat+i);
if(!pBody->GetKeyEdgeLineAt((edge_id&0x7FFFFFFF)-1,edge))
return 0;
return edge_id;
}
DWORD CRawSolidFace::FaceId() //用于标识多边形面链中的某一特定面
{
return 0;//*((DWORD*)(memoryAddr+4)); //读取面的Id属性
}
COLORREF CRawSolidFace::MatColor() // 可用于记录此面的特征信息(如材质等)
{
return *((COLORREF*)memoryAddr);
}
WORD CRawSolidFace::InnerLoopNum()
{
return *((WORD*)(memoryAddr+33)); //读取面中内环总数
}
CFaceLoop CRawSolidFace::GetInnerLoopAt(int i)
{
DWORD* lat=(DWORD*)(memoryAddr+35); //Inner Loop Allocation Table
char* loop_buf=memoryAddr+lat[i];
return CFaceLoop(loop_buf);
}
CFaceLoop CRawSolidFace::GetOutterLoop()
{
return CFaceLoop(memoryAddr+35+InnerLoopNum()*4);
};
void CRawSolidEdge::InitBuffer(char* address,DWORD size,bool externalBuf/*=false*/)
{
if(!m_bExternalBuf&&m_dwBufSize>0&&memoryAddr!=NULL)
delete []memoryAddr;
m_dwBufSize=size;
if(externalBuf)
memoryAddr=address;
else
{
memoryAddr=new char[size];
memcpy(memoryAddr,address,size);
}
m_bExternalBuf=externalBuf;
}
CRawSolidEdge::~CRawSolidEdge()
{
if(!m_bExternalBuf)
delete []memoryAddr;
}
////////////////////////////////////////////////////////////////////////////
const BYTE CFacetCluster::TRIANGLES = 0x04;
const BYTE CFacetCluster::TRIANGLE_STRIP= 0x05;
const BYTE CFacetCluster::TRIANGLE_FAN = 0x06;
void CFacetCluster::InitBuffer(char* address,DWORD size,bool externalBuf/*=true*/)
{
if(m_dwBufSize>0&&memoryAddr!=NULL&&!m_bExternalBuf)
delete []memoryAddr;
m_dwBufSize=size;
if(externalBuf)
memoryAddr=address;
else
{
memoryAddr=new char[size];
memcpy(memoryAddr,address,size);
}
m_bExternalBuf=externalBuf;
}
void CBasicGlFace::InitBuffer(char* address,DWORD size,bool externalBuf/*=true*/)
{
if(!m_bExternalBuf&&m_dwBufSize>0&&memoryAddr!=NULL)
delete []memoryAddr;
m_dwBufSize=size;
if(externalBuf)
memoryAddr=address;
else
{
memoryAddr=new char[size];
memcpy(memoryAddr,address,size);
}
m_bExternalBuf=externalBuf;
}
bool CBasicGlFace::GetFacetClusterAt(int i,CFacetCluster& cluster)
{
if(i<0||i>=FacetClusterNumber)
return false;
WORD wLen=0;
char* facet_data=memoryAddr+FacetClusterDataAddr;
CBuffer buf(facet_data,m_dwBufSize-6);
for(int j=0;j<i;j++)
{
buf.ReadWord(&wLen);
buf.Offset(wLen);
}
buf.ReadWord(&wLen);
cluster.InitBuffer(buf.GetCursorBuffer(),wLen);
return true;
}
////////////////////////////////////////////////////////////////////////////
CSolidBody::CSolidBody(char* buf,DWORD size, bool blBuffAsAttachMemory/* = false*/)
{
m_bModified=TRUE;
m_dwMaxBufSize=m_dwBufSize=size;
if (m_bExternalBuffer = blBuffAsAttachMemory)//false;
data = buf;
else if(size>0)
{
data=new char[size];
memcpy(data,buf,size);
}
else
data=NULL;
}
CSolidBody::~CSolidBody()
{
Empty();
}
void CSolidBody::Empty()
{
if(IsExternalSolidBuffer())
return; //外挂实体对象不释放内存
m_bModified=TRUE;
if(m_dwBufSize>0&&data!=NULL)
delete []data;
m_dwMaxBufSize=m_dwBufSize=0;
data=NULL;
}
void CSolidBody::Resize(DWORD size,bool bToInternalTrueOrUnchangeFalse/*=false*/)
{
m_bModified=TRUE;
if(size<m_dwMaxBufSize&&data!=NULL)
m_dwBufSize=size;
else
{
if(data!=NULL)
delete []data;
data = new char[size];
m_dwMaxBufSize=m_dwBufSize=size;
}
if(bToInternalTrueOrUnchangeFalse)
ToInternalBuffer();
}
struct EDGE_LIST_NODE{
CRawSolidEdge* pEdge;
BYTE cType; //NURBS:0x00;STRAIGHT:0x01;ARCLINE:0x02;ELLIPSE:0x03
DWORD id;
f3dPoint *pStart,*pEnd;
double sect_angle;
GEPOINT work_norm,column_norm;
EDGE_LIST_NODE* next;
int IsEqualWith(f3dAtomLine* pLine)
{
double sign=0;
if(pStart==pLine->pStart&&pEnd==pLine->pEnd)
sign=1;
else if(pStart==pLine->pEnd&&pEnd==pLine->pStart)
sign=-1;
else
return 0;
if(cType==0x01) //STRAIGHT
{
if(pLine->SectorAngle()!=0)
return 0;
else
return (int)sign;
}
else //if(cType==0x02||cType==0x03) //ARCLINE|ELLIPSE
{
if(cType==0x02&&!pLine->ColumnNorm().IsZero())
return 0; //不是圆弧,而是椭圆弧
else if(cType==0x03&&fabs(column_norm*pLine->ColumnNorm())<EPS_COS)
return 0; //柱面轴线方向不同
sign*=work_norm*pLine->WorkNorm();
if(sign>EPS_COS)
sign=1;
else if(sign<-EPS_COS)
sign=-1;
else
return 0; //方向不同
if(fabs(sign*sect_angle-pLine->SectorAngle())>EPS)
return 0; //角度不同
else
{ //方向一致(相同或反向)角度相同
if(pStart==pLine->pStart&&pEnd==pLine->pEnd)
return 1;
else
return -1;
}
}
}
EDGE_LIST_NODE(){memset(this,0,sizeof(EDGE_LIST_NODE));}
~EDGE_LIST_NODE()
{
if(next)
delete next;
if(pEdge!=NULL)
delete pEdge;
}
static void ToBuffer(CBuffer& buffer,f3dAtomLine* pLine,CHashTable<DWORD>& hashVertexPtr)
{
BYTE cType;
if(pLine->SectorAngle()==0)
cType=0x01; //STRAIGHT
else if(pLine->ColumnNorm().IsZero())
cType=0x02; //ARCLINE
else
cType=0x03; //ELLIPSE
buffer.WriteByte(cType);
buffer.WriteByte(0x00); //实体模式下的显示宽度,暂默认为0
DWORD index;
if(hashVertexPtr.GetValueAt((DWORD)pLine->pStart,index))
buffer.WriteDword(index);//起点
else
buffer.WriteDword(0);
if(hashVertexPtr.GetValueAt((DWORD)pLine->pEnd,index))
buffer.WriteDword(index);//终点
else
buffer.WriteDword(0);
if(pLine->SectorAngle()>0)
{
buffer.WriteDouble(pLine->SectorAngle());
buffer.WriteDouble(pLine->Radius());
buffer.WritePoint(pLine->Center());
buffer.WritePoint(pLine->WorkNorm());
if(!pLine->ColumnNorm().IsZero()) //椭圆弧
buffer.WritePoint(pLine->ColumnNorm());
}
}
DWORD UpdateEdgeInfo(f3dAtomLine *pLine,CHashTable<DWORD>& hashVertexPtr,DWORD *ID_COUNTER_PTR)
{
if(pEdge==NULL)
{
pEdge=new CRawSolidEdge();
char stack_memory[64];
CBuffer buffer(64);
buffer.AttachMemory(stack_memory,64);
ToBuffer(buffer,pLine,hashVertexPtr);
pEdge->InitBuffer(buffer.GetBufferPtr(),buffer.GetLength(),false);
pStart=pLine->pStart;
pEnd=pLine->pEnd;
if(pLine->SectorAngle()==0)
cType=0x01; //STRAIGHT
else if(pLine->ColumnNorm().IsZero())
cType=0x02; //ARCLINE
else
cType=0x03; //ELLIPSE
work_norm=pLine->WorkNorm();
column_norm=pLine->ColumnNorm();
id=*ID_COUNTER_PTR;
*ID_COUNTER_PTR+=1;
return id;
}
else
{
short sign=IsEqualWith(pLine);
if(sign==1)
return id;
else if(sign==-1)
return id|0x80000000;
else if(next!=NULL)
return next->UpdateEdgeInfo(pLine,hashVertexPtr,ID_COUNTER_PTR);
else
{
next= new EDGE_LIST_NODE();
return next->UpdateEdgeInfo(pLine,hashVertexPtr,ID_COUNTER_PTR);
}
}
}
};
/*static void AppendToGeneralSolidBody(fBody* pBody)
{
//if(CSolidBody::m_pHookBody==NULL)
return;
f3dPoint *pStart,*pEnd;
CHashList<f3dPoint*> hashVertexPtr;
for(f3dPoint *pVertex=pBody->vertex.GetFirst();pVertex;pVertex=pBody->vertex.GetNext())
{
f3dPoint *pNewVertex=CSolidBody::m_pHookBody->vertex.append(*pVertex);
hashVertexPtr.SetValue((DWORD)pVertex,pNewVertex);
f3dPoint vertex=*pNewVertex;
//coord_trans(vertex,cs,TRUE);
//pNewVertex->Set(vertex.x,vertex.y,vertex.z);
}
for(f3dPolyFace *pFace=pBody->faceList.GetFirst();pFace;pFace=pBody->faceList.GetNext())
{
f3dPolyFace *pNewFace=CSolidBody::m_pHookBody->faceList.append();
pNewFace->material=pFace->material;
pNewFace->poly_norm=pFace->poly_norm;
//vector_trans(pNewFace->poly_norm,cs,TRUE);
f3dAtomLine *pLine,*pNewLine;
int head_len=sizeof(GEPOINT)*3+20;
for(fLoop *pLoop=pFace->inner_loop.GetFirst();pLoop;pLoop=pFace->inner_loop.GetNext())
{
fLoop *pNewLoop = pNewFace->inner_loop.append();
for(pLine=pLoop->loop->GetFirst();pLine;pLine=pLoop->loop->GetNext())
{
pStart=hashVertexPtr[(DWORD)pLine->pStart];
pEnd=hashVertexPtr[(DWORD)pLine->pEnd];
pNewLine=pNewLoop->loop->append(pStart,pEnd);
memcpy(pNewLine,pLine,head_len);
pNewLine->is_positive_line=pLine->is_positive_line;
pNewLine->m_uDisplaySlices=pLine->m_uDisplaySlices;
//pNewLine->CoordTrans(cs,TRUE);
}
}
for(pLine=pFace->outer_edge.GetFirst();pLine;pLine=pFace->outer_edge.GetNext())
{
pStart=hashVertexPtr[(DWORD)pLine->pStart];
pEnd=hashVertexPtr[(DWORD)pLine->pEnd];
pNewLine=pNewFace->outer_edge.append(pStart,pEnd);
memcpy(pNewLine,pLine,head_len);
pNewLine->is_positive_line=pLine->is_positive_line;
pNewLine->m_uDisplaySlices=pLine->m_uDisplaySlices;
//pNewLine->CoordTrans(cs,TRUE);
}
}
}*/
bool CSolidBody::MergeBodyBuffer(char *pExterBuffer, DWORD size,CSolidBodyBuffer* pTurboBuf/*=NULL*/)
{
CSolidBodyBuffer solidbuf;
if(IsExternalSolidBuffer())
return false;
solidbuf.MergeBodyBuffer(BufferPtr(),BufferLength());
solidbuf.MergeBodyBuffer(pExterBuffer,size,pTurboBuf);
if(solidbuf.GetLength()<=m_dwMaxBufSize)
{
memcpy(data,solidbuf.GetBufferPtr(),solidbuf.GetLength());
m_dwBufSize=solidbuf.GetLength();
}
else
{
if(data!=NULL&&m_dwBufSize>0)
delete []data;
data=solidbuf.GetBufferPtr();
m_dwMaxBufSize=m_dwBufSize=solidbuf.GetLength();
solidbuf.DetachMemory();
}
return true;
}
#if !defined(DISABLE_SOLID_BODY)&&!defined(_HANDOVER_TO_CLIENT_)
#include "BufferStack.h"
bool CSolidBody::MergeListBodyBuffer(CXhSimpleList<CSolidBody*>& listBodies)
{
if(IsExternalSolidBuffer())
return false;
//合并实体集数据到一个实体内
LIST_NODE<CSolidBody*>* pSolidNode;
CSolidBody* pSolid;
CSolidBodyBuffer selfsolid(BufferPtr(),BufferLength());
DWORD bufsize=m_dwBufSize;
DWORD dwVertexCount =selfsolid.VertexNumber;
DWORD dwRawEdgeCount =selfsolid.EdgeNumber;
DWORD dwRawFaceCount =selfsolid.RawFaceNumber;
DWORD dwBasicFaceCount =selfsolid.BasicFaceNumber;
for(pSolidNode=listBodies.EnumFirst();pSolidNode;pSolidNode=listBodies.EnumNext())
{
if((pSolid=pSolidNode->data)==NULL)
continue;
CSolidBodyBuffer tmpsolidbuf(pSolid->BufferPtr(),pSolid->BufferLength());
bufsize+=pSolid->BufferLength();
dwVertexCount +=tmpsolidbuf.VertexNumber;
dwRawEdgeCount +=tmpsolidbuf.EdgeNumber;
dwRawFaceCount +=tmpsolidbuf.RawFaceNumber;
dwBasicFaceCount+=tmpsolidbuf.BasicFaceNumber;
}
CBufferStack bufstack;
CSolidBodyBuffer solidbuf(bufsize);
solidbuf.AttachStack(&bufstack);
solidbuf.VertexNumber =dwVertexCount;
solidbuf.EdgeNumber =dwRawEdgeCount;
solidbuf.RawFaceNumber =dwRawFaceCount;
solidbuf.BasicFaceNumber=dwBasicFaceCount;
solidbuf.VertexRecordLength=25;
//合并原始面索引数据
solidbuf.RawFaceIndexStartAddr=45; //更新原始定义面索引地址
solidbuf.WriteAt(45,NULL,dwRawFaceCount*4); //开辟原始定义面索引数据区
//合并原始边索引数据
UINT position=solidbuf.GetCursorPosition();
solidbuf.Write(NULL,dwRawEdgeCount*4); //开辟原始定义边索引数据区
int push_pos=solidbuf.PushPositionStack();
solidbuf.EdgeIndexStartAddr=position; //更新原始定义边索引区起地址偏移量
solidbuf.PopPositionStack(push_pos);
//合并实体显示基本面片组索引数据
position=solidbuf.GetCursorPosition();
solidbuf.Write(NULL,dwBasicFaceCount*4); //开辟实体显示基本面片组数据区
solidbuf.PushPositionStack();
solidbuf.BasicFaceIndexStartAddr=position; //更新实体显示基本面片组索引
solidbuf.PopPositionStack();
//更新顶点数据区起始地址
position=solidbuf.GetCursorPosition();
solidbuf.VertexDataStartAddr=position;
UINT i,n;
//合并写入顶点数据
pSolid=this;
solidbuf.SeekPosition(position);
do{
CSolidBodyBuffer tmpsolidbuf(pSolid->BufferPtr(),pSolid->BufferLength());
solidbuf.Write(pSolid->BufferPtr()+tmpsolidbuf.VertexDataStartAddr,25*tmpsolidbuf.VertexNumber);
if(pSolid==this)
pSolidNode=listBodies.EnumFirst();
else
pSolidNode=listBodies.EnumNext();
pSolid=pSolidNode!=NULL ? pSolidNode->data : NULL;
}while(pSolid);
//合并写原始定义面数据
position=solidbuf.GetCursorPosition();
solidbuf.RawFaceDataStartAddr=position;//更新原始定义面数据区起始地址
solidbuf.SeekPosition(position);
pSolid=this;
do{
CSolidBodyBuffer tmpsolidbuf(pSolid->BufferPtr(),pSolid->BufferLength());
i,n=tmpsolidbuf.RawFaceNumber;
for(i=0;i<n;i++)
{
WORD facebuf_len=tmpsolidbuf.GetPolyFaceBuffLength(i);
solidbuf.WriteWord(facebuf_len);
solidbuf.Write(tmpsolidbuf.GetPolyFaceBuffer(i),facebuf_len);
}
if(pSolid==this)
pSolidNode=listBodies.EnumFirst();
else
pSolidNode=listBodies.EnumNext();
pSolid=pSolidNode!=NULL ? pSolidNode->data : NULL;
}while(pSolid);
//合并写原始定义边数据
position=solidbuf.GetCursorPosition();
solidbuf.EdgeDataStartAddr=position;//更新原始定义边数据区起始地址
solidbuf.SeekPosition(position);
pSolid=this;
do{
CSolidBodyBuffer tmpsolidbuf(pSolid->BufferPtr(),pSolid->BufferLength());
i,n=tmpsolidbuf.EdgeNumber;
for(i=0;i<n;i++)
{
WORD edgebuf_len=tmpsolidbuf.GetRawEdgeBuffLength(i);
solidbuf.WriteWord(edgebuf_len);
solidbuf.Write(tmpsolidbuf.GetRawEdgeBuffer(i),edgebuf_len);
}
if(pSolid==this)
pSolidNode=listBodies.EnumFirst();
else
pSolidNode=listBodies.EnumNext();
pSolid=pSolidNode!=NULL ? pSolidNode->data : NULL;
}while(pSolid);
//合并写实体显示基本面片组数据
position=solidbuf.GetCursorPosition();
solidbuf.BasicFaceDataStartAddr=position;//更新实体显示基本面片组数据区起始地址
solidbuf.SeekPosition(position);
pSolid=this;
do{
CSolidBodyBuffer tmpsolidbuf(pSolid->BufferPtr(),pSolid->BufferLength());
i,n=tmpsolidbuf.BasicFaceNumber;
for(i=0;i<n;i++)
{
WORD facebuf_len=tmpsolidbuf.GetBasicFaceBuffLength(i);
solidbuf.WriteWord(facebuf_len);
solidbuf.Write(tmpsolidbuf.GetBasicFaceBuffer(i),facebuf_len);
}
if(pSolid==this)
pSolidNode=listBodies.EnumFirst();
else
pSolidNode=listBodies.EnumNext();
pSolid=pSolidNode!=NULL ? pSolidNode->data : NULL;
}while(pSolid);
//更新各项索引表及新记录索引标识
//更新面索引数据
//更新边索引数据
//更新实体显示基本面片组索引数据
//更新实体显示基本面片组索引数据
//更新原始定义边数据区
struct{UINT uiVertex,uiRawEdge,uiRawFace,uiBasicFace;}init,currpos;
init.uiVertex=init.uiRawEdge=init.uiRawFace=init.uiBasicFace=0;
currpos.uiVertex=currpos.uiRawEdge=currpos.uiRawFace=currpos.uiBasicFace=0;
pSolid=this;
do{
CSolidBodyBuffer tmpsolidbuf(pSolid->BufferPtr(),pSolid->BufferLength());
if(currpos.uiRawEdge==0)
{
solidbuf.SeekPosition(solidbuf.EdgeDataStartAddr);
position=solidbuf.GetCursorPosition();
}
else
solidbuf.SeekPosition(currpos.uiRawEdge);
i,n=tmpsolidbuf.EdgeNumber; //dwRawEdgeCount
for(i=0;i<n;i++)
{
position=solidbuf.GetCursorPosition();
//1.更新边索引地址
memcpy(solidbuf.GetBufferPtr()+solidbuf.EdgeIndexStartAddr+(init.uiRawEdge+i)*4,&position,4);
//2.更新边始终端顶点标识索引号
WORD edge_len=0;
solidbuf.ReadWord(&edge_len);
if(init.uiVertex>0)
{ //外部并入的边,始终端顶点号应增加原始实体顶点总数
CRawSolidEdge edge;
edge.InitBuffer(solidbuf.GetCursorBuffer(),edge_len,true);
edge.LineStartId+=init.uiVertex;
edge.LineEndId+=init.uiVertex;
}
solidbuf.Offset(edge_len);
}
currpos.uiRawEdge=solidbuf.GetCursorPosition();
//更新原始定义面数据区
if(currpos.uiRawFace==0)
{
solidbuf.SeekPosition(solidbuf.RawFaceDataStartAddr);
position=solidbuf.GetCursorPosition();
}
else
solidbuf.SeekPosition(currpos.uiRawFace);
i,n=tmpsolidbuf.RawFaceNumber;
for(i=0;i<n;i++)
{
position=solidbuf.GetCursorPosition();
//1.更新面索引地址
memcpy(solidbuf.GetBufferPtr()+solidbuf.RawFaceIndexStartAddr+(i+init.uiRawFace)*4,&position,4);
//2.更新面的边标识索引号
WORD face_len=0,iEdge=0;
solidbuf.ReadWord(&face_len);
CRawSolidFace face;
face.InitBuffer(solidbuf.GetCursorBuffer(),face_len);
if(init.uiRawEdge>0)
{ //外部并入的面,更新各环内的组成边标识索引号(增加原始实体边总数)
if(face.BasicFaceId>0)
face.BasicFaceId+=init.uiBasicFace;
CFaceLoop outerloop=face.GetOutterLoop();
for(iEdge=0;iEdge<outerloop.LoopEdgeLineNum();iEdge++)
*((DWORD*)(outerloop.GetBuffer()+2+iEdge*4))+=init.uiRawEdge;
for(WORD iLoop=0;iLoop<face.InnerLoopNum();iLoop++)
{
CFaceLoop innerloop=face.GetInnerLoopAt(iLoop);
for(iEdge=0;iEdge<innerloop.LoopEdgeLineNum();iEdge++)
*((DWORD*)(innerloop.GetBuffer()+2+iEdge*4))+=init.uiRawEdge;
}
}
solidbuf.Offset(face_len);
}
currpos.uiRawFace=solidbuf.GetCursorPosition();
//更新实体显示基本面片组数据区
i,n=tmpsolidbuf.BasicFaceNumber;
if(currpos.uiBasicFace==0)
solidbuf.SeekPosition(solidbuf.BasicFaceDataStartAddr);
else
solidbuf.SeekPosition(currpos.uiBasicFace);
WORD face_len=0;
for(i=0;i<n;i++)
{ //1.更新实体显示基本面片组索引地址
position=solidbuf.GetCursorPosition();
memcpy(solidbuf.GetBufferPtr()+solidbuf.BasicFaceIndexStartAddr+(i+init.uiBasicFace)*4,&position,4);
solidbuf.ReadWord(&face_len);
solidbuf.Offset(face_len);
}
currpos.uiBasicFace=solidbuf.GetCursorPosition();
init.uiVertex+=tmpsolidbuf.VertexNumber;
init.uiRawFace+=tmpsolidbuf.RawFaceNumber;
init.uiRawEdge+=tmpsolidbuf.EdgeNumber;
init.uiBasicFace+=tmpsolidbuf.BasicFaceNumber;
if(pSolid==this)
pSolidNode=listBodies.EnumFirst();
else
pSolidNode=listBodies.EnumNext();
pSolid=pSolidNode!=NULL ? pSolidNode->data : NULL;
}while(pSolid);
if(solidbuf.GetLength()<=m_dwMaxBufSize)
{
memcpy(data,solidbuf.GetBufferPtr(),solidbuf.GetLength());
m_dwBufSize=solidbuf.GetLength();
}
else
{
if(data!=NULL&&m_dwBufSize>0)
delete []data;
data=solidbuf.GetBufferPtr();
m_dwBufSize=solidbuf.GetLength();
m_dwMaxBufSize=bufsize;
solidbuf.DetachMemory();
}
return true;
}
bool CSolidBody::ConvertFrom(fBody* pBody)
{
CHashTable<DWORD> hashVertexPtr;
CHashList<DWORD> hashEdgePtr;
CMapList<EDGE_LIST_NODE>hashEdges;
f3dPoint *pVertex;
hashVertexPtr.CreateHashTable(pBody->vertex.GetNodeNum());
DWORD index=1;
for(pVertex=pBody->vertex.GetFirst();pVertex;pVertex=pBody->vertex.GetNext(),index++)
hashVertexPtr.SetValueAt((DWORD)pVertex,index);
CSolidBodyBuffer solidbuf;
//统计边数
DWORD ID_COUNTER=1;
f3dPolyFace *pFace=NULL;
for(pFace=pBody->faceList.GetFirst();pFace;pFace=pBody->faceList.GetNext())
{
f3dAtomLine *pAtomLine;
EDGE_LIST_NODE* pEdgeNode;
for(pAtomLine=pFace->outer_edge.GetFirst();pAtomLine;pAtomLine=pFace->outer_edge.GetNext())
{
if(pAtomLine->pStart<pAtomLine->pEnd)
pEdgeNode=hashEdges.Add((DWORD)pAtomLine->pStart,(DWORD)pAtomLine->pEnd);
else
pEdgeNode=hashEdges.Add((DWORD)pAtomLine->pEnd,(DWORD)pAtomLine->pStart);
pAtomLine->id=pEdgeNode->UpdateEdgeInfo(pAtomLine,hashVertexPtr,&ID_COUNTER);
}
//内环数据区
for(fLoop* pLoop=pFace->inner_loop.GetFirst();pLoop;pLoop=pFace->inner_loop.GetNext())
{
for(pAtomLine=pLoop->GetFirst();pAtomLine;pAtomLine=pLoop->GetNext())
{
if(pAtomLine->pStart<pAtomLine->pEnd)
pEdgeNode=hashEdges.Add((DWORD)pAtomLine->pStart,(DWORD)pAtomLine->pEnd);
else
pEdgeNode=hashEdges.Add((DWORD)pAtomLine->pEnd,(DWORD)pAtomLine->pStart);
pAtomLine->id=pEdgeNode->UpdateEdgeInfo(pAtomLine,hashVertexPtr,&ID_COUNTER);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//顶点信息头
solidbuf.VertexNumber=pBody->vertex.GetNodeNum(); //顶点数VN
solidbuf.VertexRecordLength=25; //每条顶点记录的数据存储长度VL(一般是25或32)
solidbuf.VertexDataStartAddr=0; //顶点数据区起始地址偏移量(B)
//原始定义面信息头
solidbuf.RawFaceNumber=pBody->faceList.GetNodeNum(); //原始定义面数FN
solidbuf.RawFaceIndexStartAddr=0; //原始定义面索引区起始地址偏移量(B)
solidbuf.RawFaceDataStartAddr=0; //原始定义面数据区起始地址偏移量(B)
//边信息头
solidbuf.EdgeNumber=ID_COUNTER-1; //原始定义边数EN
solidbuf.EdgeIndexStartAddr=0; //原始定义边索引区起始地址偏移量(B)
solidbuf.EdgeDataStartAddr=0; //原始定义边数据区起始地址偏移量(B)
//实体显示面信息头
solidbuf.BasicFaceNumber=0;//pBody->faceList.GetNodeNum(); //实体显示面数DN
solidbuf.BasicFaceIndexStartAddr=0; //实体显示面索引区起始地址偏移量(B)
solidbuf.BasicFaceDataStartAddr=0; //实体显示面据区起始地址偏移量(B)
//原始定义面索引区
solidbuf.RawFaceIndexStartAddr=solidbuf.GetLength(); //原始定义面索引区起始地址偏移量(B)
solidbuf.SeekToSection(CSolidBodyBuffer::RAWFACE_INDEXDATA);
solidbuf.Write(NULL,solidbuf.RawFaceNumber*4);//写入索引数据的默认0值
//原始定义边索引区
solidbuf.EdgeIndexStartAddr=solidbuf.RawFaceIndexStartAddr+solidbuf.RawFaceNumber*4;
solidbuf.WriteAt(solidbuf.EdgeIndexStartAddr,NULL,0);
solidbuf.Write(NULL,solidbuf.EdgeNumber*4);//写入索引数据的默认0值
//实体显示面索引区
solidbuf.BasicFaceIndexStartAddr=solidbuf.EdgeIndexStartAddr+solidbuf.EdgeNumber*4;
//solidbuf.Write(NULL,solidbuf.BasicFaceNumber*4); //写入索引数据的默认0值
//写入顶点数据
solidbuf.VertexDataStartAddr=solidbuf.BasicFaceIndexStartAddr+0;
solidbuf.WriteAt(solidbuf.VertexDataStartAddr,NULL,0);
for(pVertex=pBody->vertex.GetFirst();pVertex;pVertex=pBody->vertex.GetNext())
{
DWORD uByteOffset=solidbuf.GetLength();
solidbuf.WritePoint(*pVertex);
solidbuf.WriteByte(0); //0表示普通顶点,1表示同时为实体线框模型中的特征标记点
//hashVertexPtr.SetValueAt((DWORD)pVertex,uByteOffset);
}
//写入原始定义面数据
solidbuf.RawFaceDataStartAddr=solidbuf.GetLength(); //原始定义面索引区起始地址偏移量(B)
solidbuf.SeekToEnd();
long facei=0;
for(pFace=pBody->faceList.GetFirst();pFace;pFace=pBody->faceList.GetNext(),facei++)
{
DWORD addr=solidbuf.GetLength();
solidbuf.WriteAt(solidbuf.RawFaceIndexStartAddr+facei*4,&addr,4);
solidbuf.SeekToEnd();
solidbuf.LogPosition();
solidbuf.WriteWord((WORD)0); //当前数据行长度
DWORD start_pos=solidbuf.GetCursorPosition();
solidbuf.WriteDword(pFace->material); //颜色RGBA
solidbuf.WriteByte(0x84); //多边形
solidbuf.WritePoint(pFace->poly_norm); //法线数量
solidbuf.WriteDword(0); //对应实体显示时的基本面片的标识索引编号
solidbuf.WriteWord((WORD)pFace->inner_loop.GetNodeNum()); //内环数量
//内环边地址偏移(自显示颜色存储地址开始)索引
int loop_addr=solidbuf.GetCursorPosition();
solidbuf.Write(NULL,pFace->inner_loop.GetNodeNum()*4);
//外环边标识编号数据
solidbuf.WriteWord((WORD)pFace->outer_edge.GetNodeNum());
f3dAtomLine *pAtomLine;
for(pAtomLine=pFace->outer_edge.GetFirst();pAtomLine;pAtomLine=pFace->outer_edge.GetNext())
solidbuf.WriteDword(pAtomLine->id);
//内环数据区
int loopi=0;
for(fLoop* pLoop=pFace->inner_loop.GetFirst();pLoop;pLoop=pFace->inner_loop.GetNext(),loopi++)
{
//写内环地址偏移索引
DWORD addr=solidbuf.GetLength()-start_pos;
solidbuf.WriteAt(loop_addr+loopi*4,&addr,4);
solidbuf.SeekToEnd();
solidbuf.WriteWord((WORD)pLoop->GetNodeNum());
for(pAtomLine=pLoop->GetFirst();pAtomLine;pAtomLine=pLoop->GetNext())
solidbuf.WriteDword(pAtomLine->id);
}
DWORD buf_len=solidbuf.GetCursorPosition()-start_pos;
solidbuf.RecallPosition();
solidbuf.WriteWord((WORD)buf_len);
solidbuf.RecallPosition();
}
//写入原始定义边数据
EDGE_LIST_NODE *pEdgeNode;
DYN_ARRAY<CRawSolidEdge*> edgeArr(solidbuf.EdgeNumber);
for(pEdgeNode=hashEdges.GetFirst();pEdgeNode;pEdgeNode=hashEdges.GetNext())
{
do
{
edgeArr[pEdgeNode->id-1]=pEdgeNode->pEdge;
pEdgeNode=pEdgeNode->next;
}while(pEdgeNode);
}
solidbuf.SeekToEnd();
solidbuf.EdgeDataStartAddr=solidbuf.GetLength(); //原始定义面索引区起始地址偏移量(B)
for(DWORD i=0;i<edgeArr.Size();i++)
{
//写原始定义边地址偏移索引
DWORD edgeindex_addr=solidbuf.EdgeIndexStartAddr;
DWORD addr=solidbuf.GetLength();
solidbuf.WriteAt(edgeindex_addr+i*4,&addr,4);
solidbuf.SeekToEnd();
solidbuf.WriteWord((WORD)edgeArr[i]->Size()); //当前边数据记录存储长度(不含当前2B)
solidbuf.Write(edgeArr[i]->BufferPtr(),edgeArr[i]->Size());
}
solidbuf.SeekToBegin();
ReadFrom(&solidbuf,solidbuf.GetLength());
//条件允许时添加到外挂的fBody整体集合中
//AppendToGeneralSolidBody(pBody);
m_bModified=TRUE;
return true;
}
//double *pIntersPt 返回碰撞点 wht 15-09-15
//POLYGON *pIgnoreRgn 合理碰撞区域如果碰撞点位于该区域是为合理碰撞 wht 15-09-23
BOOL CSolidBody::IsIntWith(CSolidBody *pBody,double *pIntersPt/*=NULL*/,POLYGON *pIgnoreRgn/*=NULL*/)
{
UINT i,n;
f3dLine straight,tm_straight;
f3dArcLine line,otherLine;
f3dPoint inters,face_pick,line_vec;
n=PolyFaceNum();
CRawSolidFace face,otherface;
for(i=0;i<n;i++)
{
GetPolyFaceAt(i,face);
CFaceLoop loop=face.GetOutterLoop();
WORD j,edge_n=loop.LoopEdgeLineNum();
for(j=0;j<edge_n;j++)
{
loop.GetLoopEdgeLineAt(this,j,line);
straight.startPt = line.Start();
straight.endPt = line.End();
line_vec = line.End()-line.Start();
UINT i2,n2=pBody->PolyFaceNum();
for(i2=0;i2<n2;i2++)
{
pBody->GetPolyFaceAt(i2,otherface);
CFaceLoop otherloop=otherface.GetOutterLoop();
WORD j2,edge_n2=otherloop.LoopEdgeLineNum();
f3dPoint *pArr=new f3dPoint[edge_n2];
for(j2=0;j2<edge_n2;j2++)
{
otherloop.GetLoopEdgeLineAt(pBody,j2,otherLine);
if((otherLine.ID&0x80000000)==0)
pArr[j2]=otherLine.Start();
else //负向边
pArr[j2]=otherLine.End();
}
POLYGON poly;
if(!poly.CreatePolygonRgn(pArr,edge_n2))
{
delete []pArr;
continue;
}
else
delete []pArr;
int ret=Int3dlf(inters,straight.startPt,line_vec,poly.GetVertexAt(0),poly.GetAxisZ());
if(ret!=1)
continue; //求交失败,线方向有误或与平面平行
f3dPoint vec2start=straight.startPt-inters;
f3dPoint vec2end =straight.endPt -inters;
if(vec2start*vec2end>EPS) //直线段位于多边形面的同一侧不必计算 wjh-2015.4.12
continue;
if(poly.PtInRgn(inters)==1&&straight.PtInLine(inters)>0) //交点不在该线段上
{
if(pIgnoreRgn&&pIgnoreRgn->GetVertexCount()>2)
{
f3dPoint pt=inters;
project_point(pt,pIgnoreRgn->GetVertexAt(0),pIgnoreRgn->GetAxisZ());
int nRet=pIgnoreRgn->PtInRgn(pt);
if(pIgnoreRgn->PtInRgn(pt)==1)
continue; //碰撞点在指定区域内时忽略该碰撞点
}
if(pIntersPt)
{
pIntersPt[0]=inters.x;
pIntersPt[1]=inters.y;
pIntersPt[2]=inters.z;
}
poly.PtInRgn(inters);
return TRUE;//点在多边形域面内
}
else
continue;
}
}
}
n=pBody->PolyFaceNum();
for(i=0;i<n;i++)
{
pBody->GetPolyFaceAt(i,face);
CFaceLoop loop=face.GetOutterLoop();
WORD j,edge_n=loop.LoopEdgeLineNum();
for(j=0;j<edge_n;j++)
{
loop.GetLoopEdgeLineAt(pBody,j,line);
straight.startPt = line.Start();
straight.endPt = line.End();
line_vec = line.End()-line.Start();
UINT i2,n2=PolyFaceNum();
for(i2=0;i2<n2;i2++)
{
GetPolyFaceAt(i2,otherface);
CFaceLoop otherloop=otherface.GetOutterLoop();
WORD j2,edge_n2=otherloop.LoopEdgeLineNum();
f3dPoint *pArr=new f3dPoint[edge_n2];
for(j2=0;j2<edge_n2;j2++)
{
otherloop.GetLoopEdgeLineAt(this,j2,otherLine);
if((otherLine.ID&0x80000000)==0)
pArr[j2]=otherLine.Start();
else //负向边
pArr[j2]=otherLine.End();
}
POLYGON poly;
if(!poly.CreatePolygonRgn(pArr,edge_n2))
{
delete []pArr;
continue;
}
else
delete []pArr;
int ret=Int3dlf(inters,straight.startPt,line_vec,poly.GetVertexAt(0),poly.GetAxisZ());
if(ret!=1)
continue; //求交失败,线方向有误或与平面平行
f3dPoint vec2start=straight.startPt-inters;
f3dPoint vec2end =straight.endPt -inters;
if(vec2start*vec2end>EPS) //直线段位于多边形面的同一侧不必计算 wjh-2015.4.12
continue;
if(poly.PtInRgn(inters)==1&&straight.PtInLine(inters)>0) //交点不在该线段上
{
if(pIgnoreRgn&&pIgnoreRgn->GetVertexCount()>2)
{
f3dPoint pt=inters;
project_point(pt,pIgnoreRgn->GetVertexAt(0),pIgnoreRgn->GetAxisZ());
if(pIgnoreRgn->PtInRgn(pt)==1)
continue; //碰撞点在指定区域内时忽略该碰撞点
}
if(pIntersPt)
{
pIntersPt[0]=inters.x;
pIntersPt[1]=inters.y;
pIntersPt[2]=inters.z;
}
return TRUE;//点在多边形域面内
}
else
continue;
}
}
}
return FALSE;
}
#endif
bool CSolidBody::ReadFrom(BUFFER_IO* io,DWORD size)
{
if(data&&m_bExternalBuffer)
return false; //外挂内存不能再读入 wjh-2016.01.17
else if(data&&size>m_dwMaxBufSize)
{
delete []data;
m_dwMaxBufSize=0;
}
if(size>m_dwMaxBufSize)
{
data=new char[size];
m_dwMaxBufSize=size;
m_bExternalBuffer=false;
}
m_dwBufSize=io->Read(data,size);
return true;
}
void CSolidBody::WriteTo(BUFFER_IO* io)
{
io->Write(data,m_dwBufSize);
}
//从buf中复制实体数据缓存
bool CSolidBody::CopyBuffer(char* buf,DWORD size, bool blReallocMemBuff/* = true*/)
{
if (!blReallocMemBuff&&size <= m_dwMaxBufSize)
{
if ((m_dwBufSize = size) > 0)
memcpy(data, buf, size);
return true;
}
if(data&&!m_bExternalBuffer)
{
if(m_dwMaxBufSize<size)
{
delete []data;
m_dwMaxBufSize=size;
data=new char[size];
}
}
else
{
m_bExternalBuffer=false;
if(size>0)
data=new char[size];
m_dwMaxBufSize=size;
}
if((m_dwBufSize=size)>0)
memcpy(data,buf,size);
return true;
}
//外挂buf为实体数据缓存(外挂数据缓存)
bool CSolidBody::AttachBuffer(char* buf,DWORD size)
{
if(data&&!IsExternalSolidBuffer())
delete []data;
data=buf;
m_dwBufSize=size;
m_bExternalBuffer=true;
return true;
}
//由外挂实体数据缓存转换为内部独立数据缓存
bool CSolidBody::ToInternalBuffer()
{
if(data&&IsExternalSolidBuffer())
{
char* temp=new char[m_dwBufSize];
memcpy(temp,data,m_dwBufSize);
data=temp;
m_bExternalBuffer=false;
m_dwMaxBufSize=m_dwBufSize;
}
return true;
}
int CSolidBody::KeyPointNum()
{
return CSolidBodyBuffer((char*)data,m_dwBufSize).VertexNumber;
}
int CSolidBody::KeyEdgeLineNum()
{
return CSolidBodyBuffer((char*)data,m_dwBufSize).EdgeNumber;
}
int CSolidBody::PolyFaceNum()
{
return CSolidBodyBuffer((char*)data,m_dwBufSize).RawFaceNumber;
}
int CSolidBody::BasicGLFaceNum()
{
return CSolidBodyBuffer((char*)data,m_dwBufSize).BasicFaceNumber;
}
int CSolidBody::BasicFaceDataStartAddr()
{
CSolidBodyBuffer solidbuf((char*)data,m_dwBufSize);
return solidbuf.BasicFaceDataStartAddr;
}
bool CSolidBody::GetBasicGLFaceAt(int i,CBasicGlFace& face)
{
if(i<0||i>=BasicGLFaceNum())
return false;
CSolidBodyBuffer solidbuf((char*)data,m_dwBufSize);
char* sectindexdata=data+solidbuf.BasicFaceIndexStartAddr+i*4;
char* sectdata=data+*((DWORD*)sectindexdata);
WORD wLen=*((WORD*)sectdata);;
face.InitBuffer(sectdata+2,wLen);
return true;
}
GEPOINT CSolidBody::GetKeyPointAt(int i)
{
CSolidBodyBuffer solidbuf((char*)data,m_dwBufSize);
GEPOINT point;
if(solidbuf.SeekPosition(solidbuf.VertexDataStartAddr+solidbuf.VertexRecordLength*i))
solidbuf.ReadPoint(point);
return point;
}
bool CSolidBody::GetKeyEdgeLineAt(int i,CRawSolidEdge& edge)
{
CSolidBodyBuffer solidbuf((char*)data,m_dwBufSize);
if(solidbuf.SeekPosition(solidbuf.EdgeIndexStartAddr+4*i))
{
DWORD offset;
solidbuf.ReadDword(&offset);
solidbuf.SeekPosition(offset);
WORD edgebuf_len=0;
solidbuf.ReadWord(&edgebuf_len);
edge.InitBuffer(solidbuf.GetCursorBuffer(),edgebuf_len,true);
return true;
}
else
return false;
}
bool CSolidBody::GetKeyEdgeLineAt(int i,f3dArcLine& line)
{
CSolidBodyBuffer solidbuf((char*)data,m_dwBufSize);
if(solidbuf.SeekPosition(solidbuf.EdgeIndexStartAddr+4*i))
{
DWORD offset;
solidbuf.ReadDword(&offset);
solidbuf.SeekPosition(offset);
WORD edgebuf_len=0;
solidbuf.ReadWord(&edgebuf_len);
BYTE edgeType;
solidbuf.ReadByte(&edgeType); //当前边定义类型NURBS:0;STRAIGHT:0x01;ARCLINE:0x02;ELLIPSE:0x03;
solidbuf.ReadByte(&line.pen.width); //当前边为特征边时,在实体模式下的显示宽度(=0表示不显示)
if(edgebuf_len<10)
return false; //字节数过少,缺少信息
DWORD start_i,end_i;
solidbuf.ReadDword(&start_i);
solidbuf.ReadDword(&end_i);
GEPOINT start=GetKeyPointAt(start_i-1);
GEPOINT end =GetKeyPointAt(end_i-1);
char line_data[256];
CBuffer buf(line_data,48+edgebuf_len-10);
buf.SeekToBegin();
buf.WritePoint(start);
buf.WritePoint(end);
if(edgebuf_len>10)
buf.Write(solidbuf.GetCursorBuffer(),edgebuf_len-10);
line.FromByteArr(line_data,edgebuf_len+38);
//line.ID=i+1; //线上附加的ID属性
return true;
}
else
return false;
}
bool CSolidBody::GetPolyFaceAt(int i,CRawSolidFace& face)
{
CSolidBodyBuffer solidbuf((char*)data,m_dwBufSize);
if(solidbuf.SeekPosition(solidbuf.RawFaceIndexStartAddr+4*i))
{
DWORD offset;
solidbuf.ReadDword(&offset);
solidbuf.SeekPosition(offset);
WORD facebuf_len=0;
solidbuf.ReadWord(&facebuf_len);
face.InitBuffer(solidbuf.GetCursorBuffer(),facebuf_len);
return true;
}
else
return false;
}
void CSolidBody::TransFromACS(const UCS_STRU& from)
{
GECS fcs=from;
CSolidBodyBuffer solidbuf(data,m_dwBufSize);
//全部顶点坐标转换
UINT i,vertex_n=solidbuf.VertexNumber;
BYTE vertex_record_len=solidbuf.VertexRecordLength;
char* vertex_data_addr=solidbuf.GetBufferPtr()+solidbuf.VertexDataStartAddr;
GEPOINT vertex;
for(i=0;i<vertex_n;i++)
{
memcpy(&vertex,vertex_data_addr+i*vertex_record_len,24);
//coord_trans(vertex,from,FALSE);
vertex=fcs.TransPToCS(vertex);
memcpy(vertex_data_addr+i*vertex_record_len,&vertex,24);
}
//全部实体边中圆弧矢量参数转换
UINT edge_n=solidbuf.EdgeNumber;
char* edge_data_addr=solidbuf.GetBufferPtr()+solidbuf.EdgeDataStartAddr;
CRawSolidEdge rawedge;
WORD edgebuf_len;
for(i=0;i<edge_n;i++)
{
memcpy(&edgebuf_len,edge_data_addr,2);
edge_data_addr+=2;
rawedge.InitBuffer(edge_data_addr,edgebuf_len,true);
edge_data_addr+=edgebuf_len;
if(rawedge.EdgeType==CRawSolidEdge::ARCLINE||rawedge.EdgeType==CRawSolidEdge::ELLIPSE)
{
vertex=rawedge.Center;
//coord_trans(vertex,from,FALSE);
vertex=fcs.TransPToCS(vertex);
rawedge.Center=vertex;
vertex=rawedge.WorkNorm;
//vector_trans(vertex,from,FALSE);
vertex=fcs.TransVToCS(vertex);
rawedge.WorkNorm=vertex;
if(rawedge.EdgeType==CRawSolidEdge::ELLIPSE)
{
vertex=rawedge.ColumnNorm;
//vector_trans(vertex,from,FALSE);
vertex=fcs.TransVToCS(vertex);
rawedge.ColumnNorm=vertex;
}
}
}
//全部实体面中指定面法线参数转换
UINT face_n=solidbuf.RawFaceNumber;
WORD facebuf_len;
CRawSolidFace rawface;
char* rawface_data_addr=solidbuf.GetBufferPtr()+solidbuf.RawFaceDataStartAddr;
for(i=0;i<face_n;i++)
{
memcpy(&facebuf_len,rawface_data_addr,2);
rawface_data_addr+=2;
rawface.InitBuffer(rawface_data_addr,facebuf_len);
rawface_data_addr+=facebuf_len;
vertex = rawface.WorkNorm;
//vector_trans(vertex,from,FALSE);
vertex=fcs.TransVToCS(vertex);
rawface.WorkNorm=vertex;
}
}
void CSolidBody::TransToACS(const UCS_STRU& to)
{
CSolidBodyBuffer solidbuf(data,m_dwBufSize);
GECS tcs=to;
//全部顶点坐标转换
UINT i,vertex_n=solidbuf.VertexNumber;
BYTE vertex_record_len=solidbuf.VertexRecordLength;
char* vertex_data_addr=solidbuf.GetBufferPtr()+solidbuf.VertexDataStartAddr;
GEPOINT vertex;
for(i=0;i<vertex_n;i++)
{
memcpy(&vertex,vertex_data_addr+i*vertex_record_len,24);
//coord_trans(vertex,to,TRUE);
vertex=tcs.TransPFromCS(vertex);
memcpy(vertex_data_addr+i*vertex_record_len,&vertex,24);
}
//全部实体边中圆弧矢量参数转换
UINT edge_n=solidbuf.EdgeNumber;
char* edge_data_addr=solidbuf.GetBufferPtr()+solidbuf.EdgeDataStartAddr;
CRawSolidEdge rawedge;
WORD edgebuf_len;
for(i=0;i<edge_n;i++)
{
memcpy(&edgebuf_len,edge_data_addr,2);
edge_data_addr+=2;
rawedge.InitBuffer(edge_data_addr,edgebuf_len,true);
edge_data_addr+=edgebuf_len;
if(rawedge.EdgeType==CRawSolidEdge::ARCLINE||rawedge.EdgeType==CRawSolidEdge::ELLIPSE)
{
vertex=rawedge.Center;
//coord_trans(vertex,to,TRUE);
vertex=tcs.TransPFromCS(vertex);
rawedge.Center=vertex;
vertex=rawedge.WorkNorm;
//vector_trans(vertex,to,TRUE);
vertex=tcs.TransVFromCS(vertex);
rawedge.WorkNorm=vertex;
if(rawedge.EdgeType==CRawSolidEdge::ELLIPSE)
{
vertex=rawedge.ColumnNorm;
//vector_trans(vertex,to,TRUE);
vertex=tcs.TransVFromCS(vertex);
rawedge.ColumnNorm=vertex;
}
}
}
//全部实体面中指定面法线参数转换
UINT face_n=solidbuf.RawFaceNumber;
WORD facebuf_len;
CRawSolidFace rawface;
char* rawface_data_addr=solidbuf.GetBufferPtr()+solidbuf.RawFaceDataStartAddr;
for(i=0;i<face_n;i++)
{
memcpy(&facebuf_len,rawface_data_addr,2);
rawface_data_addr+=2;
rawface.InitBuffer(rawface_data_addr,facebuf_len);
rawface_data_addr+=facebuf_len;
vertex = rawface.WorkNorm;
//vector_trans(vertex,to,TRUE);
vertex=tcs.TransVFromCS(vertex);
rawface.WorkNorm=vertex;
}
}
void CSolidBody::TransACS(const UCS_STRU& from_cs,const UCS_STRU& to_cs)
{
CSolidBodyBuffer solidbuf(data,m_dwBufSize);
//一次性单位化源坐标系及目标坐标系,以便后续坐标转换时启用快速计算模式 wjh-2016.3.06
GECS from=from_cs;
GECS to=to_cs;
if(!is_ucs_valid(from_cs)||!is_ucs_valid(to_cs))
return;
//全部顶点坐标转换
UINT i,vertex_n=solidbuf.VertexNumber;
BYTE vertex_record_len=solidbuf.VertexRecordLength;
char* vertex_data_addr=solidbuf.GetBufferPtr()+solidbuf.VertexDataStartAddr;
GEPOINT vertex;
for(i=0;i<vertex_n;i++)
{
memcpy(&vertex,vertex_data_addr+i*vertex_record_len,24);
//coord_trans(vertex,from,FALSE,TRUE);
vertex=from.TransPToCS(vertex);
//coord_trans(vertex,to,TRUE,TRUE);
vertex=to.TransPFromCS(vertex);
memcpy(vertex_data_addr+i*vertex_record_len,&vertex,24);
}
//全部实体边中圆弧矢量参数转换
UINT edge_n=solidbuf.EdgeNumber;
char* edge_data_addr=solidbuf.GetBufferPtr()+solidbuf.EdgeDataStartAddr;
CRawSolidEdge rawedge;
WORD edgebuf_len;
for(i=0;i<edge_n;i++)
{
memcpy(&edgebuf_len,edge_data_addr,2);
edge_data_addr+=2;
rawedge.InitBuffer(edge_data_addr,edgebuf_len,true);
edge_data_addr+=edgebuf_len;
if(rawedge.EdgeType==CRawSolidEdge::ARCLINE||rawedge.EdgeType==CRawSolidEdge::ELLIPSE)
{
vertex=rawedge.Center;
//coord_trans(vertex,from,FALSE,TRUE);
vertex=from.TransPToCS(vertex);
//coord_trans(vertex,to,TRUE,TRUE);
vertex=to.TransPFromCS(vertex);
rawedge.Center=vertex;
vertex=rawedge.WorkNorm;
//vector_trans(vertex,from,FALSE,TRUE);
vertex=from.TransVToCS(vertex);
//vector_trans(vertex,to,TRUE,TRUE);
vertex=to.TransVFromCS(vertex);
rawedge.WorkNorm=vertex;
if(rawedge.EdgeType==CRawSolidEdge::ELLIPSE)
{
vertex=rawedge.ColumnNorm;
//vector_trans(vertex,from,FALSE,TRUE);
vertex=from.TransVToCS(vertex);
//vector_trans(vertex,to,TRUE,TRUE);
vertex=to.TransVFromCS(vertex);
rawedge.ColumnNorm=vertex;
}
}
}
//全部实体面中指定面法线参数转换
UINT face_n=solidbuf.RawFaceNumber;
WORD facebuf_len;
CRawSolidFace rawface;
char* rawface_data_addr=solidbuf.GetBufferPtr()+solidbuf.RawFaceDataStartAddr;
for(i=0;i<face_n;i++)
{
memcpy(&facebuf_len,rawface_data_addr,2);
rawface_data_addr+=2;
rawface.InitBuffer(rawface_data_addr,facebuf_len);
rawface_data_addr+=facebuf_len;
vertex = rawface.WorkNorm;
//vector_trans(vertex,from,FALSE,TRUE);
vertex=from.TransVToCS(vertex);
//vector_trans(vertex,to,TRUE,TRUE);
vertex=to.TransVFromCS(vertex);
rawface.WorkNorm=vertex;
}
}
| [
"wjzhwht@hotmail.com"
] | wjzhwht@hotmail.com |
50a265d678776967cb5daf4e0ca20ef95e3e0813 | 38c10c01007624cd2056884f25e0d6ab85442194 | /third_party/WebKit/Source/core/frame/FrameView.cpp | 8b43865107c3c03ed3f4aef590f6580215115b9a | [
"BSD-3-Clause",
"BSD-2-Clause",
"LGPL-2.0-only",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 148,257 | cpp | /*
* Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
* 1999 Lars Knoll <knoll@kde.org>
* 1999 Antti Koivisto <koivisto@kde.org>
* 2000 Dirk Mueller <mueller@kde.org>
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
* (C) 2006 Graham Dennis (graham.dennis@gmail.com)
* (C) 2006 Alexey Proskuryakov (ap@nypop.com)
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/frame/FrameView.h"
#include "core/HTMLNames.h"
#include "core/MediaTypeNames.h"
#include "core/css/FontFaceSet.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/AXObjectCache.h"
#include "core/dom/Fullscreen.h"
#include "core/editing/EditingUtilities.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/RenderedPosition.h"
#include "core/editing/markers/DocumentMarkerController.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/frame/FrameHost.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLFrameElement.h"
#include "core/html/HTMLPlugInElement.h"
#include "core/html/HTMLTextFormControlElement.h"
#include "core/html/parser/TextResourceDecoder.h"
#include "core/input/EventHandler.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "core/layout/LayoutAnalyzer.h"
#include "core/layout/LayoutCounter.h"
#include "core/layout/LayoutEmbeddedObject.h"
#include "core/layout/LayoutInline.h"
#include "core/layout/LayoutListBox.h"
#include "core/layout/LayoutPart.h"
#include "core/layout/LayoutScrollbar.h"
#include "core/layout/LayoutScrollbarPart.h"
#include "core/layout/LayoutTableCell.h"
#include "core/layout/LayoutTheme.h"
#include "core/layout/LayoutView.h"
#include "core/layout/ScrollAlignment.h"
#include "core/layout/TextAutosizer.h"
#include "core/layout/TracedLayoutObject.h"
#include "core/layout/compositing/CompositedLayerMapping.h"
#include "core/layout/compositing/CompositedSelection.h"
#include "core/layout/compositing/PaintLayerCompositor.h"
#include "core/layout/svg/LayoutSVGRoot.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/page/AutoscrollController.h"
#include "core/page/ChromeClient.h"
#include "core/page/FocusController.h"
#include "core/page/FrameTree.h"
#include "core/page/Page.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
#include "core/paint/FramePainter.h"
#include "core/paint/PaintLayer.h"
#include "core/paint/PaintPropertyTreeBuilder.h"
#include "core/style/ComputedStyle.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGSVGElement.h"
#include "platform/HostWindow.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/ScriptForbiddenScope.h"
#include "platform/TraceEvent.h"
#include "platform/TracedValue.h"
#include "platform/fonts/FontCache.h"
#include "platform/geometry/DoubleRect.h"
#include "platform/geometry/FloatRect.h"
#include "platform/geometry/LayoutRect.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/GraphicsLayer.h"
#include "platform/graphics/GraphicsLayerDebugInfo.h"
#include "platform/graphics/paint/PaintController.h"
#include "platform/scheduler/CancellableTaskFactory.h"
#include "platform/scroll/ScrollAnimator.h"
#include "platform/text/TextStream.h"
#include "public/platform/WebDisplayItemList.h"
#include "public/platform/WebFrameScheduler.h"
#include "wtf/CurrentTime.h"
#include "wtf/StdLibExtras.h"
#include "wtf/TemporaryChange.h"
namespace blink {
using namespace HTMLNames;
// The maximum number of updateWidgets iterations that should be done before returning.
static const unsigned maxUpdateWidgetsIterations = 2;
static const double resourcePriorityUpdateDelayAfterScroll = 0.250;
static bool s_initialTrackAllPaintInvalidations = false;
FrameView::FrameView(LocalFrame* frame)
: m_frame(frame)
, m_displayMode(WebDisplayModeBrowser)
, m_canHaveScrollbars(true)
, m_hasPendingLayout(false)
, m_inSynchronousPostLayout(false)
, m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
, m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired)
, m_intersectionObserverNotificationFactory(CancellableTaskFactory::create(this, &FrameView::notifyIntersectionObservers))
, m_isTransparent(false)
, m_baseBackgroundColor(Color::white)
, m_mediaType(MediaTypeNames::screen)
, m_safeToPropagateScrollToParent(true)
, m_isTrackingPaintInvalidations(false)
, m_scrollCorner(nullptr)
, m_inputEventsScaleFactorForEmulation(1)
, m_layoutSizeFixedToFrameSize(true)
, m_didScrollTimer(this, &FrameView::didScrollTimerFired)
, m_topControlsViewportAdjustment(0)
, m_needsUpdateWidgetPositions(false)
, m_needsUpdateViewportIntersection(true)
, m_needsUpdateViewportIntersectionInSubtree(true)
#if ENABLE(ASSERT)
, m_hasBeenDisposed(false)
#endif
, m_horizontalScrollbarMode(ScrollbarAuto)
, m_verticalScrollbarMode(ScrollbarAuto)
, m_horizontalScrollbarLock(false)
, m_verticalScrollbarLock(false)
, m_scrollbarsAvoidingResizer(0)
, m_scrollbarsSuppressed(false)
, m_inUpdateScrollbars(false)
, m_frameTimingRequestsDirty(true)
, m_viewportIntersectionValid(false)
, m_hiddenForThrottling(false)
, m_crossOriginForThrottling(false)
{
ASSERT(m_frame);
init();
}
PassRefPtrWillBeRawPtr<FrameView> FrameView::create(LocalFrame* frame)
{
RefPtrWillBeRawPtr<FrameView> view = adoptRefWillBeNoop(new FrameView(frame));
view->show();
return view.release();
}
PassRefPtrWillBeRawPtr<FrameView> FrameView::create(LocalFrame* frame, const IntSize& initialSize)
{
RefPtrWillBeRawPtr<FrameView> view = adoptRefWillBeNoop(new FrameView(frame));
view->Widget::setFrameRect(IntRect(view->location(), initialSize));
view->setLayoutSizeInternal(initialSize);
view->show();
return view.release();
}
FrameView::~FrameView()
{
ASSERT(m_hasBeenDisposed);
#if !ENABLE(OILPAN)
// Verify that the LocalFrame has a different FrameView or
// that it is being detached and destructed.
ASSERT(frame().view() != this || !layoutView());
#endif
}
DEFINE_TRACE(FrameView)
{
#if ENABLE(OILPAN)
visitor->trace(m_frame);
visitor->trace(m_nodeToDraw);
visitor->trace(m_scrollAnchor);
visitor->trace(m_scrollableAreas);
visitor->trace(m_animatingScrollableAreas);
visitor->trace(m_autoSizeInfo);
visitor->trace(m_horizontalScrollbar);
visitor->trace(m_verticalScrollbar);
visitor->trace(m_children);
visitor->trace(m_viewportScrollableArea);
#endif
Widget::trace(visitor);
ScrollableArea::trace(visitor);
}
void FrameView::reset()
{
m_hasPendingLayout = false;
m_doFullPaintInvalidation = false;
m_layoutSchedulingEnabled = true;
m_inPerformLayout = false;
m_inSynchronousPostLayout = false;
m_layoutCount = 0;
m_nestedLayoutCount = 0;
m_postLayoutTasksTimer.stop();
m_updateWidgetsTimer.stop();
m_firstLayout = true;
m_safeToPropagateScrollToParent = true;
m_lastViewportSize = IntSize();
m_lastZoomFactor = 1.0f;
m_isTrackingPaintInvalidations = s_initialTrackAllPaintInvalidations;
m_isPainting = false;
m_visuallyNonEmptyCharacterCount = 0;
m_visuallyNonEmptyPixelCount = 0;
m_isVisuallyNonEmpty = false;
clearScrollAnchor();
m_viewportConstrainedObjects.clear();
m_layoutSubtreeRootList.clear();
}
template <typename Function>
void FrameView::forAllFrameViews(Function function)
{
for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
if (!frame->isLocalFrame())
continue;
if (FrameView* view = toLocalFrame(frame)->view())
function(*view);
}
}
void FrameView::removeFromAXObjectCache()
{
if (AXObjectCache* cache = axObjectCache()) {
cache->remove(this);
cache->childrenChanged(m_frame->pagePopupOwner());
}
}
void FrameView::init()
{
reset();
m_size = LayoutSize();
// Propagate the marginwidth/height and scrolling modes to the view.
// FIXME: Do we need to do this for OOPI?
Element* ownerElement = m_frame->deprecatedLocalOwner();
if (ownerElement && (isHTMLFrameElement(*ownerElement) || isHTMLIFrameElement(*ownerElement))) {
HTMLFrameElementBase* frameElt = toHTMLFrameElementBase(ownerElement);
if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
setCanHaveScrollbars(false);
}
}
void FrameView::dispose()
{
RELEASE_ASSERT(!isInPerformLayout());
if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
scrollAnimator->cancelAnimations();
cancelProgrammaticScrollAnimation();
detachScrollbars();
// When the view is no longer associated with a frame, it needs to be removed from the ax object cache
// right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
removeFromAXObjectCache();
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->willDestroyScrollableArea(this);
// Destroy |m_autoSizeInfo| as early as possible, to avoid dereferencing
// partially destroyed |this| via |m_autoSizeInfo->m_frameView|.
m_autoSizeInfo.clear();
if (m_postLayoutTasksTimer.isActive())
m_postLayoutTasksTimer.stop();
if (m_didScrollTimer.isActive())
m_didScrollTimer.stop();
m_intersectionObserverNotificationFactory->cancel();
// FIXME: Do we need to do something here for OOPI?
HTMLFrameOwnerElement* ownerElement = m_frame->deprecatedLocalOwner();
// TODO(dcheng): It seems buggy that we can have an owner element that
// points to another Widget.
if (ownerElement && ownerElement->ownedWidget() == this)
ownerElement->setWidget(nullptr);
#if ENABLE(ASSERT)
m_hasBeenDisposed = true;
#endif
}
void FrameView::detachScrollbars()
{
// Previously, we detached custom scrollbars as early as possible to prevent
// Document::detach() from messing with the view such that its scroll bars
// won't be torn down. However, scripting in Document::detach() is forbidden
// now, so it's not clear if these edge cases can still happen.
// However, for Oilpan, we still need to remove the native scrollbars before
// we lose the connection to the HostWindow, so we just unconditionally
// detach any scrollbars now.
setHasHorizontalScrollbar(false);
setHasVerticalScrollbar(false);
if (m_scrollCorner) {
m_scrollCorner->destroy();
m_scrollCorner = nullptr;
}
}
void FrameView::recalculateCustomScrollbarStyle()
{
bool didStyleChange = false;
if (m_horizontalScrollbar && m_horizontalScrollbar->isCustomScrollbar()) {
m_horizontalScrollbar->styleChanged();
didStyleChange = true;
}
if (m_verticalScrollbar && m_verticalScrollbar->isCustomScrollbar()) {
m_verticalScrollbar->styleChanged();
didStyleChange = true;
}
if (didStyleChange) {
updateScrollbarGeometry();
updateScrollCorner();
positionScrollbarLayers();
}
}
void FrameView::invalidateAllCustomScrollbarsOnActiveChanged()
{
bool usesWindowInactiveSelector = m_frame->document()->styleEngine().usesWindowInactiveSelector();
const ChildrenWidgetSet* viewChildren = children();
for (const RefPtrWillBeMember<Widget>& child : *viewChildren) {
Widget* widget = child.get();
if (widget->isFrameView())
toFrameView(widget)->invalidateAllCustomScrollbarsOnActiveChanged();
else if (usesWindowInactiveSelector && widget->isScrollbar() && toScrollbar(widget)->isCustomScrollbar())
toScrollbar(widget)->styleChanged();
}
if (usesWindowInactiveSelector)
recalculateCustomScrollbarStyle();
}
void FrameView::recalculateScrollbarOverlayStyle()
{
ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
Color backgroundColor = documentBackgroundColor();
// Reduce the background color from RGB to a lightness value
// and determine which scrollbar style to use based on a lightness
// heuristic.
double hue, saturation, lightness;
backgroundColor.getHSL(hue, saturation, lightness);
if (lightness <= .5)
overlayStyle = ScrollbarOverlayStyleLight;
if (oldOverlayStyle != overlayStyle)
setScrollbarOverlayStyle(overlayStyle);
}
void FrameView::clear()
{
reset();
setScrollbarsSuppressed(true);
}
bool FrameView::didFirstLayout() const
{
return !m_firstLayout;
}
void FrameView::invalidateRect(const IntRect& rect)
{
// For querying PaintLayer::compositingState() when invalidating scrollbars.
// FIXME: do all scrollbar invalidations after layout of all frames is complete. It's currently not recursively true.
DisableCompositingQueryAsserts disabler;
if (!parent()) {
if (HostWindow* window = hostWindow())
window->invalidateRect(rect);
return;
}
LayoutPart* layoutObject = m_frame->ownerLayoutObject();
if (!layoutObject)
return;
IntRect paintInvalidationRect = rect;
paintInvalidationRect.move(layoutObject->borderLeft() + layoutObject->paddingLeft(),
layoutObject->borderTop() + layoutObject->paddingTop());
// FIXME: We should not allow paint invalidation out of paint invalidation state. crbug.com/457415
DisablePaintInvalidationStateAsserts paintInvalidationAssertDisabler;
layoutObject->invalidatePaintRectangle(LayoutRect(paintInvalidationRect));
}
void FrameView::setFrameRect(const IntRect& newRect)
{
IntRect oldRect = frameRect();
if (newRect == oldRect)
return;
Widget::setFrameRect(newRect);
updateScrollbars(scrollOffsetDouble());
frameRectsChanged();
updateScrollableAreaSet();
if (LayoutView* layoutView = this->layoutView()) {
if (layoutView->usesCompositing())
layoutView->compositor()->frameViewDidChangeSize();
}
viewportSizeChanged(newRect.width() != oldRect.width(), newRect.height() != oldRect.height());
if (oldRect.size() != newRect.size()) {
if (m_frame->isMainFrame())
m_frame->host()->visualViewport().mainFrameDidChangeSize();
frame().loader().restoreScrollPositionAndViewState();
}
}
Page* FrameView::page() const
{
return frame().page();
}
LayoutView* FrameView::layoutView() const
{
return frame().contentLayoutObject();
}
ScrollingCoordinator* FrameView::scrollingCoordinator()
{
Page* p = page();
return p ? p->scrollingCoordinator() : 0;
}
void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
{
m_canHaveScrollbars = canHaveScrollbars;
ScrollbarMode newVerticalMode = m_verticalScrollbarMode;
if (canHaveScrollbars && m_verticalScrollbarMode == ScrollbarAlwaysOff)
newVerticalMode = ScrollbarAuto;
else if (!canHaveScrollbars)
newVerticalMode = ScrollbarAlwaysOff;
ScrollbarMode newHorizontalMode = m_horizontalScrollbarMode;
if (canHaveScrollbars && m_horizontalScrollbarMode == ScrollbarAlwaysOff)
newHorizontalMode = ScrollbarAuto;
else if (!canHaveScrollbars)
newHorizontalMode = ScrollbarAlwaysOff;
setScrollbarModes(newHorizontalMode, newVerticalMode);
}
bool FrameView::shouldUseCustomScrollbars(Element*& customScrollbarElement, LocalFrame*& customScrollbarFrame) const
{
customScrollbarElement = nullptr;
customScrollbarFrame = nullptr;
if (Settings* settings = m_frame->settings()) {
if (!settings->allowCustomScrollbarInMainFrame() && m_frame->isMainFrame())
return false;
}
// FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
Document* doc = m_frame->document();
// Try the <body> element first as a scrollbar source.
Element* body = doc ? doc->body() : 0;
if (body && body->layoutObject() && body->layoutObject()->style()->hasPseudoStyle(SCROLLBAR)) {
customScrollbarElement = body;
return true;
}
// If the <body> didn't have a custom style, then the root element might.
Element* docElement = doc ? doc->documentElement() : 0;
if (docElement && docElement->layoutObject() && docElement->layoutObject()->style()->hasPseudoStyle(SCROLLBAR)) {
customScrollbarElement = docElement;
return true;
}
// If we have an owning ipage/LocalFrame element, then it can set the custom scrollbar also.
LayoutPart* frameLayoutObject = m_frame->ownerLayoutObject();
if (frameLayoutObject && frameLayoutObject->style()->hasPseudoStyle(SCROLLBAR)) {
customScrollbarFrame = m_frame.get();
return true;
}
return false;
}
PassRefPtrWillBeRawPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
{
Element* customScrollbarElement = nullptr;
LocalFrame* customScrollbarFrame = nullptr;
if (shouldUseCustomScrollbars(customScrollbarElement, customScrollbarFrame))
return LayoutScrollbar::createCustomScrollbar(this, orientation, customScrollbarElement, customScrollbarFrame);
// Nobody set a custom style, so we just use a native scrollbar.
return Scrollbar::create(this, orientation, RegularScrollbar);
}
void FrameView::setContentsSize(const IntSize& size)
{
if (size == contentsSize())
return;
m_contentsSize = size;
updateScrollbars(scrollOffsetDouble());
ScrollableArea::contentsResized();
Page* page = frame().page();
if (!page)
return;
updateScrollableAreaSet();
page->chromeClient().contentsSizeChanged(m_frame.get(), size);
frame().loader().restoreScrollPositionAndViewState();
}
void FrameView::adjustViewSize()
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return;
ASSERT(m_frame->view() == this);
const IntRect rect = layoutView->documentRect();
const IntSize& size = rect.size();
setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !m_frame->document()->printing(), size == contentsSize());
setContentsSize(size);
}
void FrameView::calculateScrollbarModesFromOverflowStyle(const ComputedStyle* style, ScrollbarMode& hMode, ScrollbarMode& vMode)
{
hMode = vMode = ScrollbarAuto;
EOverflow overflowX = style->overflowX();
EOverflow overflowY = style->overflowY();
if (!shouldIgnoreOverflowHidden()) {
if (overflowX == OHIDDEN)
hMode = ScrollbarAlwaysOff;
if (overflowY == OHIDDEN)
vMode = ScrollbarAlwaysOff;
}
if (overflowX == OSCROLL)
hMode = ScrollbarAlwaysOn;
if (overflowY == OSCROLL)
vMode = ScrollbarAlwaysOn;
}
void FrameView::calculateScrollbarModes(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
{
#define RETURN_SCROLLBAR_MODE(mode) \
{ \
hMode = vMode = mode; \
return; \
}
// Setting scrolling="no" on an iframe element disables scrolling.
// FIXME: Handle this for OOPI?
if (const HTMLFrameOwnerElement* owner = m_frame->deprecatedLocalOwner()) {
if (owner->scrollingMode() == ScrollbarAlwaysOff)
RETURN_SCROLLBAR_MODE(ScrollbarAlwaysOff);
}
// Framesets can't scroll.
Node* body = m_frame->document()->body();
if (isHTMLFrameSetElement(body) && body->layoutObject())
RETURN_SCROLLBAR_MODE(ScrollbarAlwaysOff);
// Scrollbars can be disabled by FrameView::setCanHaveScrollbars.
if (!m_canHaveScrollbars && strategy != RulesFromWebContentOnly)
RETURN_SCROLLBAR_MODE(ScrollbarAlwaysOff);
// This will be the LayoutObject for either the body element or the html element
// (see Document::viewportDefiningElement).
LayoutObject* viewport = viewportLayoutObject();
if (!viewport || !viewport->style())
RETURN_SCROLLBAR_MODE(ScrollbarAuto);
if (viewport->isSVGRoot()) {
// Don't allow overflow to affect <img> and css backgrounds
if (toLayoutSVGRoot(viewport)->isEmbeddedThroughSVGImage())
RETURN_SCROLLBAR_MODE(ScrollbarAuto);
// FIXME: evaluate if we can allow overflow for these cases too.
// Overflow is always hidden when stand-alone SVG documents are embedded.
if (toLayoutSVGRoot(viewport)->isEmbeddedThroughFrameContainingSVGDocument())
RETURN_SCROLLBAR_MODE(ScrollbarAlwaysOff);
}
calculateScrollbarModesFromOverflowStyle(viewport->style(), hMode, vMode);
#undef RETURN_SCROLLBAR_MODE
}
void FrameView::updateAcceleratedCompositingSettings()
{
if (LayoutView* layoutView = this->layoutView())
layoutView->compositor()->updateAcceleratedCompositingSettings();
}
void FrameView::recalcOverflowAfterStyleChange()
{
LayoutView* layoutView = this->layoutView();
RELEASE_ASSERT(layoutView);
if (!layoutView->needsOverflowRecalcAfterStyleChange())
return;
layoutView->recalcOverflowAfterStyleChange();
// Changing overflow should notify scrolling coordinator to ensures that it
// updates non-fast scroll rects even if there is no layout.
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->notifyOverflowUpdated();
IntRect documentRect = layoutView->documentRect();
if (scrollOrigin() == -documentRect.location() && contentsSize() == documentRect.size())
return;
if (needsLayout())
return;
InUpdateScrollbarsScope inUpdateScrollbarsScope(this);
bool shouldHaveHorizontalScrollbar = false;
bool shouldHaveVerticalScrollbar = false;
computeScrollbarExistence(shouldHaveHorizontalScrollbar, shouldHaveVerticalScrollbar, documentRect.size());
bool hasHorizontalScrollbar = horizontalScrollbar();
bool hasVerticalScrollbar = verticalScrollbar();
if (hasHorizontalScrollbar != shouldHaveHorizontalScrollbar
|| hasVerticalScrollbar != shouldHaveVerticalScrollbar) {
setNeedsLayout();
return;
}
adjustViewSize();
updateScrollbarGeometry();
}
bool FrameView::usesCompositedScrolling() const
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return false;
if (m_frame->settings() && m_frame->settings()->preferCompositingToLCDTextEnabled())
return layoutView->compositor()->inCompositingMode();
return false;
}
GraphicsLayer* FrameView::layerForScrolling() const
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return nullptr;
return layoutView->compositor()->frameScrollLayer();
}
GraphicsLayer* FrameView::layerForHorizontalScrollbar() const
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return nullptr;
return layoutView->compositor()->layerForHorizontalScrollbar();
}
GraphicsLayer* FrameView::layerForVerticalScrollbar() const
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return nullptr;
return layoutView->compositor()->layerForVerticalScrollbar();
}
GraphicsLayer* FrameView::layerForScrollCorner() const
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return nullptr;
return layoutView->compositor()->layerForScrollCorner();
}
bool FrameView::isEnclosedInCompositingLayer() const
{
// FIXME: It's a bug that compositing state isn't always up to date when this is called. crbug.com/366314
DisableCompositingQueryAsserts disabler;
LayoutObject* frameOwnerLayoutObject = m_frame->ownerLayoutObject();
return frameOwnerLayoutObject && frameOwnerLayoutObject->enclosingLayer()->enclosingLayerForPaintInvalidationCrossingFrameBoundaries();
}
void FrameView::countObjectsNeedingLayout(unsigned& needsLayoutObjects, unsigned& totalObjects, bool& isSubtree)
{
needsLayoutObjects = 0;
totalObjects = 0;
isSubtree = isSubtreeLayout();
if (isSubtree)
m_layoutSubtreeRootList.countObjectsNeedingLayout(needsLayoutObjects, totalObjects);
else
LayoutSubtreeRootList::countObjectsNeedingLayoutInRoot(layoutView(), needsLayoutObjects, totalObjects);
}
inline void FrameView::forceLayoutParentViewIfNeeded()
{
LayoutPart* ownerLayoutObject = m_frame->ownerLayoutObject();
if (!ownerLayoutObject || !ownerLayoutObject->frame())
return;
LayoutBox* contentBox = embeddedContentBox();
if (!contentBox)
return;
LayoutSVGRoot* svgRoot = toLayoutSVGRoot(contentBox);
if (svgRoot->everHadLayout() && !svgRoot->needsLayout())
return;
// If the embedded SVG document appears the first time, the ownerLayoutObject has already finished
// layout without knowing about the existence of the embedded SVG document, because LayoutReplaced
// embeddedContentBox() returns 0, as long as the embedded document isn't loaded yet. Before
// bothering to lay out the SVG document, mark the ownerLayoutObject needing layout and ask its
// FrameView for a layout. After that the LayoutEmbeddedObject (ownerLayoutObject) carries the
// correct size, which LayoutSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying
// out for the first time, or when the LayoutSVGRoot size has changed dynamically (eg. via <script>).
RefPtrWillBeRawPtr<FrameView> frameView = ownerLayoutObject->frame()->view();
// Mark the owner layoutObject as needing layout.
ownerLayoutObject->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::Unknown);
// Synchronously enter layout, to layout the view containing the host object/embed/iframe.
ASSERT(frameView);
frameView->layout();
}
void FrameView::performPreLayoutTasks()
{
TRACE_EVENT0("blink,benchmark", "FrameView::performPreLayoutTasks");
lifecycle().advanceTo(DocumentLifecycle::InPreLayout);
// Don't schedule more layouts, we're in one.
TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive()) {
// This is a new top-level layout. If there are any remaining tasks from the previous layout, finish them now.
m_inSynchronousPostLayout = true;
performPostLayoutTasks();
m_inSynchronousPostLayout = false;
}
bool wasResized = wasViewportResized();
Document* document = m_frame->document();
// Viewport-dependent media queries may cause us to need completely different style information.
if (!document->styleResolver() || (wasResized && document->styleResolver()->mediaQueryAffectedByViewportChange())) {
document->mediaQueryAffectingValueChanged();
} else if (wasResized) {
document->evaluateMediaQueryList();
}
document->updateLayoutTreeIfNeeded();
lifecycle().advanceTo(DocumentLifecycle::StyleClean);
if (m_frame->isMainFrame() && !m_viewportScrollableArea) {
ScrollableArea& visualViewport = m_frame->host()->visualViewport();
ScrollableArea* layoutViewport = layoutViewportScrollableArea();
bool invertScrollOrder = m_frame->settings()->invertViewportScrollOrder();
ASSERT(layoutViewport);
m_viewportScrollableArea = RootFrameViewport::create(visualViewport, *layoutViewport, invertScrollOrder);
}
}
static inline void layoutFromRootObject(LayoutObject& root)
{
LayoutState layoutState(root);
root.layout();
}
void FrameView::prepareLayoutAnalyzer()
{
bool isTracing = false;
TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("blink.debug.layout"), &isTracing);
if (!isTracing) {
m_analyzer.clear();
return;
}
if (!m_analyzer)
m_analyzer = adoptPtr(new LayoutAnalyzer());
m_analyzer->reset();
}
PassRefPtr<TracedValue> FrameView::analyzerCounters()
{
if (!m_analyzer)
return TracedValue::create();
RefPtr<TracedValue> value = m_analyzer->toTracedValue();
value->setString("host", layoutView()->document().location()->host());
return value;
}
#define PERFORM_LAYOUT_TRACE_CATEGORIES "blink,benchmark," TRACE_DISABLED_BY_DEFAULT("blink.debug.layout")
void FrameView::performLayout(bool inSubtreeLayout)
{
ASSERT(inSubtreeLayout || m_layoutSubtreeRootList.isEmpty());
TRACE_EVENT_BEGIN0(PERFORM_LAYOUT_TRACE_CATEGORIES, "FrameView::performLayout");
prepareLayoutAnalyzer();
ScriptForbiddenScope forbidScript;
ASSERT(!isInPerformLayout());
lifecycle().advanceTo(DocumentLifecycle::InPerformLayout);
TemporaryChange<bool> changeInPerformLayout(m_inPerformLayout, true);
// performLayout is the actual guts of layout().
// FIXME: The 300 other lines in layout() probably belong in other helper functions
// so that a single human could understand what layout() is actually doing.
forceLayoutParentViewIfNeeded();
if (inSubtreeLayout) {
if (m_analyzer)
m_analyzer->increment(LayoutAnalyzer::PerformLayoutRootLayoutObjects, m_layoutSubtreeRootList.size());
while (LayoutObject* root = m_layoutSubtreeRootList.takeDeepestRoot()) {
if (!root->needsLayout())
continue;
layoutFromRootObject(*root);
// We need to ensure that we mark up all layoutObjects up to the LayoutView
// for paint invalidation. This simplifies our code as we just always
// do a full tree walk.
if (LayoutObject* container = root->container())
container->setMayNeedPaintInvalidation();
}
} else {
layoutFromRootObject(*layoutView());
}
m_frame->document()->fetcher()->updateAllImageResourcePriorities();
lifecycle().advanceTo(DocumentLifecycle::AfterPerformLayout);
TRACE_EVENT_END1(PERFORM_LAYOUT_TRACE_CATEGORIES, "FrameView::performLayout",
"counters", analyzerCounters());
}
void FrameView::scheduleOrPerformPostLayoutTasks()
{
if (m_postLayoutTasksTimer.isActive())
return;
if (!m_inSynchronousPostLayout) {
m_inSynchronousPostLayout = true;
// Calls resumeScheduledEvents()
performPostLayoutTasks();
m_inSynchronousPostLayout = false;
}
if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout)) {
// If we need layout or are already in a synchronous call to postLayoutTasks(),
// defer widget updates and event dispatch until after we return. postLayoutTasks()
// can make us need to update again, and we can get stuck in a nasty cycle unless
// we call it through the timer here.
m_postLayoutTasksTimer.startOneShot(0, BLINK_FROM_HERE);
if (needsLayout())
layout();
}
}
void FrameView::layout()
{
// We should never layout a Document which is not in a LocalFrame.
ASSERT(m_frame);
ASSERT(m_frame->view() == this);
ASSERT(m_frame->page());
ScriptForbiddenScope forbidScript;
if (isInPerformLayout() || !m_frame->document()->isActive() || shouldThrottleRendering())
return;
TRACE_EVENT0("blink,benchmark", "FrameView::layout");
TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "Layout");
// Protect the view from being deleted during layout (in recalcStyle)
RefPtrWillBeRawPtr<FrameView> protector(this);
if (m_autoSizeInfo)
m_autoSizeInfo->autoSizeIfNeeded();
m_hasPendingLayout = false;
DocumentLifecycle::Scope lifecycleScope(lifecycle(), DocumentLifecycle::LayoutClean);
RELEASE_ASSERT(!isPainting());
TRACE_EVENT_BEGIN1("devtools.timeline", "Layout", "beginData", InspectorLayoutEvent::beginData(this));
performPreLayoutTasks();
#if !ENABLE(OILPAN)
// If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
// so there's no point to continuing to layout
if (protector->hasOneRef())
return;
#endif
Document* document = m_frame->document();
// If the layout view was marked as needing layout after we added items in the subtree roots we need
// to clear the roots and do the layout from the layoutView.
if (layoutView()->needsLayout())
clearLayoutSubtreeRootsAndMarkContainingBlocks();
layoutView()->clearHitTestCache();
bool inSubtreeLayout = isSubtreeLayout();
// FIXME: The notion of a single root for layout is no longer applicable. Remove or update this code. crbug.com/460596
LayoutObject* rootForThisLayout = inSubtreeLayout ? m_layoutSubtreeRootList.randomRoot() : layoutView();
if (!rootForThisLayout) {
// FIXME: Do we need to set m_size here?
ASSERT_NOT_REACHED();
return;
}
FontCachePurgePreventer fontCachePurgePreventer;
{
TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
m_nestedLayoutCount++;
if (!inSubtreeLayout) {
clearLayoutSubtreeRootsAndMarkContainingBlocks();
Node* body = document->body();
if (body && body->layoutObject()) {
if (isHTMLFrameSetElement(*body)) {
body->layoutObject()->setChildNeedsLayout();
} else if (isHTMLBodyElement(*body)) {
if (!m_firstLayout && m_size.height() != layoutSize().height() && body->layoutObject()->enclosingBox()->stretchesToViewport())
body->layoutObject()->setChildNeedsLayout();
}
}
}
updateCounters();
if (!inSubtreeLayout) {
ScrollbarMode hMode;
ScrollbarMode vMode;
calculateScrollbarModes(hMode, vMode);
// Now set our scrollbar state for the layout.
ScrollbarMode currentHMode = horizontalScrollbarMode();
ScrollbarMode currentVMode = verticalScrollbarMode();
if (m_firstLayout) {
setScrollbarsSuppressed(true);
m_doFullPaintInvalidation = true;
m_firstLayout = false;
m_lastViewportSize = layoutSize(IncludeScrollbars);
m_lastZoomFactor = layoutView()->style()->zoom();
// Set the initial vMode to AlwaysOn if we're auto.
if (vMode == ScrollbarAuto)
setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
// Set the initial hMode to AlwaysOff if we're auto.
if (hMode == ScrollbarAuto)
setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
setScrollbarModes(hMode, vMode);
setScrollbarsSuppressed(false, true);
} else if (hMode != currentHMode || vMode != currentVMode) {
setScrollbarModes(hMode, vMode);
}
if (needsScrollbarReconstruction())
updateScrollbars(scrollOffsetDouble());
LayoutSize oldSize = m_size;
m_size = LayoutSize(layoutSize().width(), layoutSize().height());
if (oldSize != m_size && !m_firstLayout) {
LayoutBox* rootLayoutObject = document->documentElement() ? document->documentElement()->layoutBox() : 0;
LayoutBox* bodyLayoutObject = rootLayoutObject && document->body() ? document->body()->layoutBox() : 0;
if (bodyLayoutObject && bodyLayoutObject->stretchesToViewport())
bodyLayoutObject->setChildNeedsLayout();
else if (rootLayoutObject && rootLayoutObject->stretchesToViewport())
rootLayoutObject->setChildNeedsLayout();
}
// We need to set m_doFullPaintInvalidation before triggering layout as LayoutObject::checkForPaintInvalidation
// checks the boolean to disable local paint invalidations.
m_doFullPaintInvalidation |= layoutView()->shouldDoFullPaintInvalidationForNextLayout();
}
TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(TRACE_DISABLED_BY_DEFAULT("blink.debug.layout"), "LayoutTree",
this, TracedLayoutObject::create(*layoutView(), false));
performLayout(inSubtreeLayout);
ASSERT(m_layoutSubtreeRootList.isEmpty());
} // Reset m_layoutSchedulingEnabled to its previous value.
if (!inSubtreeLayout && !document->printing())
adjustViewSize();
m_frameTimingRequestsDirty = true;
// FIXME: Could find the common ancestor layer of all dirty subtrees and mark from there. crbug.com/462719
layoutView()->enclosingLayer()->updateLayerPositionsAfterLayout();
TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(TRACE_DISABLED_BY_DEFAULT("blink.debug.layout"), "LayoutTree",
this, TracedLayoutObject::create(*layoutView(), true));
layoutView()->compositor()->didLayout();
m_layoutCount++;
if (AXObjectCache* cache = document->axObjectCache()) {
const KURL& url = document->url();
if (url.isValid() && !url.isAboutBlankURL())
cache->handleLayoutComplete(document);
}
updateDocumentAnnotatedRegions();
scheduleOrPerformPostLayoutTasks();
// FIXME: The notion of a single root for layout is no longer applicable. Remove or update this code. crbug.com/460596
TRACE_EVENT_END1("devtools.timeline", "Layout", "endData", InspectorLayoutEvent::endData(rootForThisLayout));
InspectorInstrumentation::didUpdateLayout(m_frame.get());
m_nestedLayoutCount--;
if (m_nestedLayoutCount)
return;
#if ENABLE(ASSERT)
// Post-layout assert that nobody was re-marked as needing layout during layout.
layoutView()->assertSubtreeIsLaidOut();
#endif
// Ensure that we become visually non-empty eventually.
// TODO(esprehn): This should check isRenderingReady() instead.
if (!frame().document()->parsing() && frame().loader().stateMachine()->committedFirstRealDocumentLoad())
m_isVisuallyNonEmpty = true;
// FIXME: It should be not possible to remove the FrameView from the frame/page during layout
// however m_inPerformLayout is not set for most of this function, so none of our RELEASE_ASSERTS
// in LocalFrame/Page will fire. One of the post-layout tasks is disconnecting the LocalFrame from
// the page in fast/frames/crash-remove-iframe-during-object-beforeload-2.html
// necessitating this check here.
// ASSERT(frame()->page());
if (frame().page())
frame().page()->chromeClient().layoutUpdated(m_frame.get());
frame().document()->layoutUpdated();
}
// The plan is to move to compositor-queried paint invalidation, in which case this
// method would setNeedsRedraw on the GraphicsLayers with invalidations and
// let the compositor pick which to actually draw.
// See http://crbug.com/306706
void FrameView::invalidateTreeIfNeeded(PaintInvalidationState& paintInvalidationState)
{
if (shouldThrottleRendering())
return;
lifecycle().advanceTo(DocumentLifecycle::InPaintInvalidation);
ASSERT(layoutView());
LayoutView& rootForPaintInvalidation = *layoutView();
ASSERT(!rootForPaintInvalidation.needsLayout());
TRACE_EVENT1("blink", "FrameView::invalidateTree", "root", rootForPaintInvalidation.debugName().ascii());
rootForPaintInvalidation.invalidateTreeIfNeeded(paintInvalidationState);
// Invalidate the paint of the frameviews scrollbars if needed
if (hasVerticalBarDamage())
invalidateRect(verticalBarDamage());
if (hasHorizontalBarDamage())
invalidateRect(horizontalBarDamage());
resetScrollbarDamage();
#if ENABLE(ASSERT)
layoutView()->assertSubtreeClearedPaintInvalidationState();
#endif
if (m_frame->selection().isCaretBoundsDirty())
m_frame->selection().invalidateCaretRect();
m_doFullPaintInvalidation = false;
lifecycle().advanceTo(DocumentLifecycle::PaintInvalidationClean);
}
DocumentLifecycle& FrameView::lifecycle() const
{
return m_frame->document()->lifecycle();
}
LayoutBox* FrameView::embeddedContentBox() const
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return nullptr;
LayoutObject* firstChild = layoutView->firstChild();
if (!firstChild || !firstChild->isBox())
return nullptr;
// Curently only embedded SVG documents participate in the size-negotiation logic.
if (firstChild->isSVGRoot())
return toLayoutBox(firstChild);
return nullptr;
}
void FrameView::addPart(LayoutPart* object)
{
m_parts.add(object);
}
void FrameView::removePart(LayoutPart* object)
{
m_parts.remove(object);
}
void FrameView::updateWidgetPositions()
{
Vector<RefPtr<LayoutPart>> parts;
copyToVector(m_parts, parts);
// Script or plugins could detach the frame so abort processing if that happens.
for (size_t i = 0; i < parts.size() && layoutView(); ++i)
parts[i]->updateWidgetPosition();
for (size_t i = 0; i < parts.size() && layoutView(); ++i)
parts[i]->widgetPositionsUpdated();
}
void FrameView::addPartToUpdate(LayoutEmbeddedObject& object)
{
ASSERT(isInPerformLayout());
// Tell the DOM element that it needs a widget update.
Node* node = object.node();
ASSERT(node);
if (isHTMLObjectElement(*node) || isHTMLEmbedElement(*node))
toHTMLPlugInElement(node)->setNeedsWidgetUpdate(true);
m_partUpdateSet.add(&object);
}
void FrameView::setDisplayMode(WebDisplayMode mode)
{
if (mode == m_displayMode)
return;
m_displayMode = mode;
if (m_frame->document())
m_frame->document()->mediaQueryAffectingValueChanged();
}
void FrameView::setMediaType(const AtomicString& mediaType)
{
ASSERT(m_frame->document());
m_frame->document()->mediaQueryAffectingValueChanged();
m_mediaType = mediaType;
}
AtomicString FrameView::mediaType() const
{
// See if we have an override type.
if (m_frame->settings() && !m_frame->settings()->mediaTypeOverride().isEmpty())
return AtomicString(m_frame->settings()->mediaTypeOverride());
return m_mediaType;
}
void FrameView::adjustMediaTypeForPrinting(bool printing)
{
if (printing) {
if (m_mediaTypeWhenNotPrinting.isNull())
m_mediaTypeWhenNotPrinting = mediaType();
setMediaType(MediaTypeNames::print);
} else {
if (!m_mediaTypeWhenNotPrinting.isNull())
setMediaType(m_mediaTypeWhenNotPrinting);
m_mediaTypeWhenNotPrinting = nullAtom;
}
}
bool FrameView::contentsInCompositedLayer() const
{
LayoutView* layoutView = this->layoutView();
return layoutView && layoutView->compositingState() == PaintsIntoOwnBacking;
}
void FrameView::addBackgroundAttachmentFixedObject(LayoutObject* object)
{
ASSERT(!m_backgroundAttachmentFixedObjects.contains(object));
m_backgroundAttachmentFixedObjects.add(object);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewHasBackgroundAttachmentFixedObjectsDidChange(this);
}
void FrameView::removeBackgroundAttachmentFixedObject(LayoutObject* object)
{
ASSERT(m_backgroundAttachmentFixedObjects.contains(object));
m_backgroundAttachmentFixedObjects.remove(object);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewHasBackgroundAttachmentFixedObjectsDidChange(this);
}
void FrameView::addViewportConstrainedObject(LayoutObject* object)
{
if (!m_viewportConstrainedObjects)
m_viewportConstrainedObjects = adoptPtr(new ViewportConstrainedObjectSet);
if (!m_viewportConstrainedObjects->contains(object)) {
m_viewportConstrainedObjects->add(object);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewFixedObjectsDidChange(this);
}
}
void FrameView::removeViewportConstrainedObject(LayoutObject* object)
{
if (m_viewportConstrainedObjects && m_viewportConstrainedObjects->contains(object)) {
m_viewportConstrainedObjects->remove(object);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewFixedObjectsDidChange(this);
}
}
void FrameView::viewportSizeChanged(bool widthChanged, bool heightChanged)
{
if (!hasViewportConstrainedObjects())
return;
for (const auto& viewportConstrainedObject : *m_viewportConstrainedObjects) {
LayoutObject* layoutObject = viewportConstrainedObject;
const ComputedStyle& style = layoutObject->styleRef();
if (widthChanged) {
if (style.width().isFixed() && (style.left().isAuto() || style.right().isAuto()))
layoutObject->setNeedsPositionedMovementLayout();
else
layoutObject->setNeedsLayoutAndFullPaintInvalidation(LayoutInvalidationReason::SizeChanged);
}
if (heightChanged) {
if (style.height().isFixed() && (style.top().isAuto() || style.bottom().isAuto()))
layoutObject->setNeedsPositionedMovementLayout();
else
layoutObject->setNeedsLayoutAndFullPaintInvalidation(LayoutInvalidationReason::SizeChanged);
}
}
}
IntPoint FrameView::lastKnownMousePosition() const
{
return m_frame->eventHandler().lastKnownMousePosition();
}
bool FrameView::shouldSetCursor() const
{
Page* page = frame().page();
return page && page->visibilityState() != PageVisibilityStateHidden && page->focusController().isActive() && page->settings().deviceSupportsMouse();
}
void FrameView::scrollContentsIfNeededRecursive()
{
forAllFrameViews([](FrameView& frameView) {
if (frameView.shouldThrottleRendering())
return;
frameView.scrollContentsIfNeeded();
});
}
void FrameView::invalidateBackgroundAttachmentFixedObjects()
{
for (const auto& layoutObject : m_backgroundAttachmentFixedObjects)
layoutObject->setShouldDoFullPaintInvalidation();
}
bool FrameView::invalidateViewportConstrainedObjects()
{
for (const auto& viewportConstrainedObject : *m_viewportConstrainedObjects) {
LayoutObject* layoutObject = viewportConstrainedObject;
ASSERT(layoutObject->style()->hasViewportConstrainedPosition());
ASSERT(layoutObject->hasLayer());
PaintLayer* layer = toLayoutBoxModelObject(layoutObject)->layer();
if (layer->isPaintInvalidationContainer())
continue;
if (layer->subtreeIsInvisible())
continue;
// If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot
// scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
if (layer->hasAncestorWithFilterOutsets())
return false;
TRACE_EVENT_INSTANT1(
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
"ScrollInvalidationTracking",
TRACE_EVENT_SCOPE_THREAD,
"data",
InspectorScrollInvalidationTrackingEvent::data(*layoutObject));
layoutObject->setShouldDoFullPaintInvalidationIncludingNonCompositingDescendants();
}
return true;
}
bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta)
{
if (!contentsInCompositedLayer())
return false;
invalidateBackgroundAttachmentFixedObjects();
if (!m_viewportConstrainedObjects || m_viewportConstrainedObjects->isEmpty()) {
InspectorInstrumentation::didUpdateLayout(m_frame.get());
return true;
}
if (!invalidateViewportConstrainedObjects())
return false;
InspectorInstrumentation::didUpdateLayout(m_frame.get());
return true;
}
void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
{
TRACE_EVENT0("blink", "FrameView::scrollContentsSlowPath");
// We need full invalidation during slow scrolling. For slimming paint, full invalidation
// of the LayoutView is not enough. We also need to invalidate all of the objects.
// FIXME: Find out what are enough to invalidate in slow path scrolling. crbug.com/451090#9.
ASSERT(layoutView());
if (contentsInCompositedLayer())
layoutView()->layer()->compositedLayerMapping()->setContentsNeedDisplay();
else
layoutView()->setShouldDoFullPaintInvalidationIncludingNonCompositingDescendants();
if (contentsInCompositedLayer()) {
IntRect updateRect = visibleContentRect();
ASSERT(layoutView());
// FIXME: We should not allow paint invalidation out of paint invalidation state. crbug.com/457415
DisablePaintInvalidationStateAsserts disabler;
layoutView()->invalidatePaintRectangle(LayoutRect(updateRect));
}
if (LayoutPart* frameLayoutObject = m_frame->ownerLayoutObject()) {
if (isEnclosedInCompositingLayer()) {
LayoutRect rect(frameLayoutObject->borderLeft() + frameLayoutObject->paddingLeft(),
frameLayoutObject->borderTop() + frameLayoutObject->paddingTop(),
visibleWidth(), visibleHeight());
// FIXME: We should not allow paint invalidation out of paint invalidation state. crbug.com/457415
DisablePaintInvalidationStateAsserts disabler;
frameLayoutObject->invalidatePaintRectangle(rect);
return;
}
}
hostWindow()->invalidateRect(updateRect);
}
void FrameView::restoreScrollbar()
{
setScrollbarsSuppressed(false);
}
bool FrameView::processUrlFragment(const KURL& url, UrlFragmentBehavior behavior)
{
// If our URL has no ref, then we have no place we need to jump to.
// OTOH If CSS target was set previously, we want to set it to 0, recalc
// and possibly paint invalidation because :target pseudo class may have been
// set (see bug 11321).
// Similarly for svg, if we had a previous svgView() then we need to reset
// the initial view if we don't have a fragment.
if (!url.hasFragmentIdentifier() && !m_frame->document()->cssTarget() && !m_frame->document()->isSVGDocument())
return false;
String fragmentIdentifier = url.fragmentIdentifier();
if (processUrlFragmentHelper(fragmentIdentifier, behavior))
return true;
// Try again after decoding the ref, based on the document's encoding.
if (m_frame->document()->encoding().isValid())
return processUrlFragmentHelper(decodeURLEscapeSequences(fragmentIdentifier, m_frame->document()->encoding()), behavior);
return false;
}
bool FrameView::processUrlFragmentHelper(const String& name, UrlFragmentBehavior behavior)
{
ASSERT(m_frame->document());
if (behavior == UrlFragmentScroll && !m_frame->document()->isRenderingReady()) {
m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
return false;
}
m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
Element* anchorNode = m_frame->document()->findAnchor(name);
// Setting to null will clear the current target.
m_frame->document()->setCSSTarget(anchorNode);
if (m_frame->document()->isSVGDocument()) {
if (SVGSVGElement* svg = SVGDocumentExtensions::rootElement(*m_frame->document())) {
svg->setupInitialView(name, anchorNode);
if (!anchorNode)
return true;
}
}
// Implement the rule that "" and "top" both mean top of page as in other browsers.
if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
return false;
if (behavior == UrlFragmentScroll)
maintainScrollPositionAtAnchor(anchorNode ? static_cast<Node*>(anchorNode) : m_frame->document());
// If the anchor accepts keyboard focus, move focus there to aid users relying on keyboard navigation.
// If anchorNode is not focusable, setFocusedElement() will still clear focus, which matches the behavior of other browsers.
if (anchorNode)
m_frame->document()->setFocusedElement(anchorNode);
return true;
}
void FrameView::maintainScrollPositionAtAnchor(Node* anchorNode)
{
ASSERT(anchorNode);
m_scrollAnchor = anchorNode;
// We need to update the layout tree before scrolling.
m_frame->document()->updateLayoutTreeIfNeeded();
// If layout is needed, we will scroll in performPostLayoutTasks. Otherwise, scroll immediately.
LayoutView* layoutView = this->layoutView();
if (layoutView && layoutView->needsLayout())
layout();
else
scrollToAnchor();
}
void FrameView::clearScrollAnchor()
{
m_scrollAnchor = nullptr;
}
void FrameView::setScrollPosition(const DoublePoint& scrollPoint, ScrollType scrollType, ScrollBehavior scrollBehavior)
{
DoublePoint newScrollPosition = clampScrollPosition(scrollPoint);
if (newScrollPosition == scrollPositionDouble())
return;
if (scrollBehavior == ScrollBehaviorAuto)
scrollBehavior = scrollBehaviorStyle();
ScrollableArea::setScrollPosition(newScrollPosition, scrollType, scrollBehavior);
}
void FrameView::didUpdateElasticOverscroll()
{
Page* page = frame().page();
if (!page)
return;
FloatSize elasticOverscroll = page->chromeClient().elasticOverscroll();
if (m_horizontalScrollbar) {
float delta = elasticOverscroll.width() - m_horizontalScrollbar->elasticOverscroll();
if (delta != 0) {
m_horizontalScrollbar->setElasticOverscroll(elasticOverscroll.width());
scrollAnimator()->notifyContentAreaScrolled(FloatSize(delta, 0));
if (!m_scrollbarsSuppressed)
m_horizontalScrollbar->invalidate();
}
}
if (m_verticalScrollbar) {
float delta = elasticOverscroll.height() - m_verticalScrollbar->elasticOverscroll();
if (delta != 0) {
m_verticalScrollbar->setElasticOverscroll(elasticOverscroll.height());
scrollAnimator()->notifyContentAreaScrolled(FloatSize(0, delta));
if (!m_scrollbarsSuppressed)
m_verticalScrollbar->invalidate();
}
}
}
IntSize FrameView::layoutSize(IncludeScrollbarsInRect scrollbarInclusion) const
{
return scrollbarInclusion == ExcludeScrollbars ? excludeScrollbars(m_layoutSize) : m_layoutSize;
}
void FrameView::setLayoutSize(const IntSize& size)
{
ASSERT(!layoutSizeFixedToFrameSize());
setLayoutSizeInternal(size);
}
void FrameView::scrollPositionChanged()
{
Document* document = m_frame->document();
document->enqueueScrollEventForNode(document);
m_frame->eventHandler().dispatchFakeMouseMoveEventSoon();
if (LayoutView* layoutView = document->layoutView()) {
if (layoutView->usesCompositing())
layoutView->compositor()->frameViewDidScroll();
}
if (m_didScrollTimer.isActive())
m_didScrollTimer.stop();
m_didScrollTimer.startOneShot(resourcePriorityUpdateDelayAfterScroll, BLINK_FROM_HERE);
if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
cache->handleScrollPositionChanged(this);
layoutView()->clearHitTestCache();
frame().loader().saveScrollState();
}
void FrameView::didScrollTimerFired(Timer<FrameView>*)
{
if (m_frame->document() && m_frame->document()->layoutView())
m_frame->document()->fetcher()->updateAllImageResourcePriorities();
}
void FrameView::updateLayersAndCompositingAfterScrollIfNeeded()
{
// Nothing to do after scrolling if there are no fixed position elements.
if (!hasViewportConstrainedObjects())
return;
RefPtrWillBeRawPtr<FrameView> protect(this);
// If there fixed position elements, scrolling may cause compositing layers to change.
// Update widget and layer positions after scrolling, but only if we're not inside of
// layout.
if (!m_nestedLayoutCount) {
updateWidgetPositions();
if (LayoutView* layoutView = this->layoutView())
layoutView->layer()->setNeedsCompositingInputsUpdate();
}
}
bool FrameView::computeCompositedSelection(LocalFrame& frame, CompositedSelection& selection)
{
const VisibleSelection& visibleSelection = frame.selection().selection();
if (!visibleSelection.isCaretOrRange())
return false;
// Non-editable caret selections lack any kind of UI affordance, and
// needn't be tracked by the client.
if (visibleSelection.isCaret() && !visibleSelection.isContentEditable())
return false;
VisiblePosition visibleStart(visibleSelection.visibleStart());
RenderedPosition renderedStart(visibleStart);
renderedStart.positionInGraphicsLayerBacking(selection.start);
if (!selection.start.layer)
return false;
if (visibleSelection.isCaret()) {
selection.end = selection.start;
} else {
VisiblePosition visibleEnd(visibleSelection.visibleEnd());
RenderedPosition renderedEnd(visibleEnd);
renderedEnd.positionInGraphicsLayerBacking(selection.end);
if (!selection.end.layer)
return false;
}
selection.type = visibleSelection.selectionType();
selection.isEditable = visibleSelection.isContentEditable();
if (selection.isEditable) {
if (HTMLTextFormControlElement* enclosingTextFormControlElement = enclosingTextFormControl(visibleSelection.rootEditableElement()))
selection.isEmptyTextFormControl = enclosingTextFormControlElement->value().isEmpty();
}
selection.start.isTextDirectionRTL = primaryDirectionOf(*visibleSelection.start().anchorNode()) == RTL;
selection.end.isTextDirectionRTL = primaryDirectionOf(*visibleSelection.end().anchorNode()) == RTL;
return true;
}
void FrameView::updateCompositedSelectionIfNeeded()
{
if (!RuntimeEnabledFeatures::compositedSelectionUpdateEnabled())
return;
TRACE_EVENT0("blink", "FrameView::updateCompositedSelectionIfNeeded");
Page* page = frame().page();
ASSERT(page);
CompositedSelection selection;
Frame* focusedFrame = page->focusController().focusedOrMainFrame();
LocalFrame* localFrame = focusedFrame->isLocalFrame() ? toLocalFrame(focusedFrame) : nullptr;
if (!localFrame || !computeCompositedSelection(*localFrame, selection)) {
page->chromeClient().clearCompositedSelection();
return;
}
page->chromeClient().updateCompositedSelection(selection);
}
HostWindow* FrameView::hostWindow() const
{
Page* page = frame().page();
if (!page)
return nullptr;
return &page->chromeClient();
}
void FrameView::contentsResized()
{
if (m_frame->isMainFrame() && m_frame->document()) {
if (TextAutosizer* textAutosizer = m_frame->document()->textAutosizer())
textAutosizer->updatePageInfoInAllFrames();
}
ScrollableArea::contentsResized();
setNeedsLayout();
}
void FrameView::scrollbarExistenceDidChange()
{
// We check to make sure the view is attached to a frame() as this method can
// be triggered before the view is attached by LocalFrame::createView(...) setting
// various values such as setScrollBarModes(...) for example. An ASSERT is
// triggered when a view is layout before being attached to a frame().
if (!frame().view())
return;
bool hasOverlayScrollbars = this->hasOverlayScrollbars();
// FIXME: this call to layout() could be called within FrameView::layout(), but before performLayout(),
// causing double-layout. See also crbug.com/429242.
if (!hasOverlayScrollbars && needsLayout())
layout();
if (layoutView() && layoutView()->usesCompositing()) {
layoutView()->compositor()->frameViewScrollbarsExistenceDidChange();
if (!hasOverlayScrollbars)
layoutView()->compositor()->frameViewDidChangeSize();
}
}
void FrameView::handleLoadCompleted()
{
// Once loading has completed, allow autoSize one last opportunity to
// reduce the size of the frame.
if (m_autoSizeInfo)
m_autoSizeInfo->autoSizeIfNeeded();
// If there is a pending layout, the scroll anchor will be cleared when it finishes.
if (!needsLayout())
clearScrollAnchor();
}
void FrameView::clearLayoutSubtreeRoot(const LayoutObject& root)
{
m_layoutSubtreeRootList.removeRoot(const_cast<LayoutObject&>(root));
}
void FrameView::clearLayoutSubtreeRootsAndMarkContainingBlocks()
{
m_layoutSubtreeRootList.clearAndMarkContainingBlocksForLayout();
}
void FrameView::scheduleRelayout()
{
ASSERT(m_frame->view() == this);
if (!m_layoutSchedulingEnabled)
return;
if (!needsLayout())
return;
if (!m_frame->document()->shouldScheduleLayout())
return;
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "InvalidateLayout", TRACE_EVENT_SCOPE_THREAD, "data", InspectorInvalidateLayoutEvent::data(m_frame.get()));
clearLayoutSubtreeRootsAndMarkContainingBlocks();
if (m_hasPendingLayout)
return;
m_hasPendingLayout = true;
if (!shouldThrottleRendering())
page()->animator().scheduleVisualUpdate(m_frame.get());
lifecycle().ensureStateAtMost(DocumentLifecycle::StyleClean);
}
void FrameView::scheduleRelayoutOfSubtree(LayoutObject* relayoutRoot)
{
ASSERT(m_frame->view() == this);
// FIXME: Should this call shouldScheduleLayout instead?
if (!m_frame->document()->isActive())
return;
LayoutView* layoutView = this->layoutView();
if (layoutView && layoutView->needsLayout()) {
if (relayoutRoot)
relayoutRoot->markContainerChainForLayout(false);
return;
}
if (relayoutRoot == layoutView)
m_layoutSubtreeRootList.clearAndMarkContainingBlocksForLayout();
else
m_layoutSubtreeRootList.addRoot(*relayoutRoot);
if (m_layoutSchedulingEnabled) {
m_hasPendingLayout = true;
page()->animator().scheduleVisualUpdate(m_frame.get());
lifecycle().ensureStateAtMost(DocumentLifecycle::StyleClean);
}
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "InvalidateLayout", TRACE_EVENT_SCOPE_THREAD, "data", InspectorInvalidateLayoutEvent::data(m_frame.get()));
}
bool FrameView::layoutPending() const
{
// FIXME: This should check Document::lifecycle instead.
return m_hasPendingLayout;
}
bool FrameView::isInPerformLayout() const
{
ASSERT(m_inPerformLayout == (lifecycle().state() == DocumentLifecycle::InPerformLayout));
return m_inPerformLayout;
}
bool FrameView::needsLayout() const
{
// This can return true in cases where the document does not have a body yet.
// Document::shouldScheduleLayout takes care of preventing us from scheduling
// layout in that case.
LayoutView* layoutView = this->layoutView();
return layoutPending()
|| (layoutView && layoutView->needsLayout())
|| isSubtreeLayout();
}
void FrameView::setNeedsLayout()
{
LayoutBox* box = embeddedContentBox();
// It's illegal to ask for layout changes during the layout compositing or paint invalidation step.
// FIXME: the third conditional is a hack to support embedded SVG. See FrameView::forceLayoutParentViewIfNeeded and crbug.com/442939
RELEASE_ASSERT(!m_frame->document() || m_frame->document()->lifecycle().stateAllowsLayoutInvalidation() || (box && box->isSVGRoot()));
if (LayoutView* layoutView = this->layoutView())
layoutView->setNeedsLayout(LayoutInvalidationReason::Unknown);
}
bool FrameView::isTransparent() const
{
return m_isTransparent;
}
void FrameView::setTransparent(bool isTransparent)
{
m_isTransparent = isTransparent;
DisableCompositingQueryAsserts disabler;
if (layoutView() && layoutView()->layer()->hasCompositedLayerMapping())
layoutView()->layer()->compositedLayerMapping()->updateContentsOpaque();
}
bool FrameView::hasOpaqueBackground() const
{
return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
}
Color FrameView::baseBackgroundColor() const
{
return m_baseBackgroundColor;
}
void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
{
m_baseBackgroundColor = backgroundColor;
if (layoutView() && layoutView()->layer()->hasCompositedLayerMapping()) {
CompositedLayerMapping* compositedLayerMapping = layoutView()->layer()->compositedLayerMapping();
compositedLayerMapping->updateContentsOpaque();
if (compositedLayerMapping->mainGraphicsLayer())
compositedLayerMapping->mainGraphicsLayer()->setNeedsDisplay();
}
recalculateScrollbarOverlayStyle();
}
void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
{
forAllFrameViews([backgroundColor, transparent](FrameView& frameView) {
frameView.setTransparent(transparent);
frameView.setBaseBackgroundColor(backgroundColor);
});
}
void FrameView::scrollToAnchor()
{
RefPtrWillBeRawPtr<Node> anchorNode = m_scrollAnchor;
if (!anchorNode)
return;
// Scrolling is disabled during updateScrollbars (see isProgrammaticallyScrollable).
// Bail now to avoid clearing m_scrollAnchor before we actually have a chance to scroll.
if (m_inUpdateScrollbars)
return;
if (anchorNode->layoutObject()) {
LayoutRect rect;
if (anchorNode != m_frame->document()) {
rect = anchorNode->boundingBox();
} else if (m_frame->settings() && m_frame->settings()->rootLayerScrolls()) {
if (Element* documentElement = m_frame->document()->documentElement())
rect = documentElement->boundingBox();
}
RefPtrWillBeRawPtr<Frame> boundaryFrame = m_frame->findUnsafeParentScrollPropagationBoundary();
// FIXME: Handle RemoteFrames
if (boundaryFrame && boundaryFrame->isLocalFrame())
toLocalFrame(boundaryFrame.get())->view()->setSafeToPropagateScrollToParent(false);
// Scroll nested layers and frames to reveal the anchor.
// Align to the top and to the closest side (this matches other browsers).
anchorNode->layoutObject()->scrollRectToVisible(rect, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
if (boundaryFrame && boundaryFrame->isLocalFrame())
toLocalFrame(boundaryFrame.get())->view()->setSafeToPropagateScrollToParent(true);
if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
cache->handleScrolledToAnchor(anchorNode.get());
}
// The scroll anchor should only be maintained while the frame is still loading.
// If the frame is done loading, clear the anchor now. Otherwise, restore it
// since it may have been cleared during scrollRectToVisible.
m_scrollAnchor = m_frame->document()->isLoadCompleted() ? nullptr : anchorNode;
}
bool FrameView::updateWidgets()
{
// This is always called from updateWidgetsTimerFired.
// m_updateWidgetsTimer should only be scheduled if we have widgets to update.
// Thus I believe we can stop checking isEmpty here, and just ASSERT isEmpty:
// FIXME: This assert has been temporarily removed due to https://crbug.com/430344
if (m_nestedLayoutCount > 1 || m_partUpdateSet.isEmpty())
return true;
// Need to swap because script will run inside the below loop and invalidate the iterator.
EmbeddedObjectSet objects;
objects.swap(m_partUpdateSet);
for (const auto& embeddedObject : objects) {
LayoutEmbeddedObject& object = *embeddedObject;
HTMLPlugInElement* element = toHTMLPlugInElement(object.node());
// The object may have already been destroyed (thus node cleared),
// but FrameView holds a manual ref, so it won't have been deleted.
if (!element)
continue;
// No need to update if it's already crashed or known to be missing.
if (object.showsUnavailablePluginIndicator())
continue;
if (element->needsWidgetUpdate())
element->updateWidget();
object.updateWidgetPosition();
// Prevent plugins from causing infinite updates of themselves.
// FIXME: Do we really need to prevent this?
m_partUpdateSet.remove(&object);
}
return m_partUpdateSet.isEmpty();
}
void FrameView::updateWidgetsTimerFired(Timer<FrameView>*)
{
ASSERT(!isInPerformLayout());
RefPtrWillBeRawPtr<FrameView> protect(this);
m_updateWidgetsTimer.stop();
for (unsigned i = 0; i < maxUpdateWidgetsIterations; ++i) {
if (updateWidgets())
return;
}
}
void FrameView::flushAnyPendingPostLayoutTasks()
{
ASSERT(!isInPerformLayout());
if (m_postLayoutTasksTimer.isActive())
performPostLayoutTasks();
if (m_updateWidgetsTimer.isActive())
updateWidgetsTimerFired(0);
}
void FrameView::scheduleUpdateWidgetsIfNecessary()
{
ASSERT(!isInPerformLayout());
if (m_updateWidgetsTimer.isActive() || m_partUpdateSet.isEmpty())
return;
m_updateWidgetsTimer.startOneShot(0, BLINK_FROM_HERE);
}
void FrameView::performPostLayoutTasks()
{
// FIXME: We can reach here, even when the page is not active!
// http/tests/inspector/elements/html-link-import.html and many other
// tests hit that case.
// We should ASSERT(isActive()); or at least return early if we can!
ASSERT(!isInPerformLayout()); // Always before or after performLayout(), part of the highest-level layout() call.
TRACE_EVENT0("blink,benchmark", "FrameView::performPostLayoutTasks");
RefPtrWillBeRawPtr<FrameView> protect(this);
m_postLayoutTasksTimer.stop();
m_frame->selection().setCaretRectNeedsUpdate();
m_frame->selection().updateAppearance();
ASSERT(m_frame->document());
FontFaceSet::didLayout(*m_frame->document());
// Cursor update scheduling is done by the local root, which is the main frame if there
// are no RemoteFrame ancestors in the frame tree. Use of localFrameRoot() is
// discouraged but will change when cursor update scheduling is moved from EventHandler
// to PageEventHandler.
frame().localFrameRoot()->eventHandler().scheduleCursorUpdate();
updateWidgetPositions();
// Plugins could have torn down the page inside updateWidgetPositions().
if (!layoutView())
return;
scheduleUpdateWidgetsIfNecessary();
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->notifyLayoutUpdated();
scrollToAnchor();
sendResizeEventIfNeeded();
}
bool FrameView::wasViewportResized()
{
ASSERT(m_frame);
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return false;
ASSERT(layoutView->style());
return (layoutSize(IncludeScrollbars) != m_lastViewportSize || layoutView->style()->zoom() != m_lastZoomFactor);
}
void FrameView::sendResizeEventIfNeeded()
{
ASSERT(m_frame);
LayoutView* layoutView = this->layoutView();
if (!layoutView || layoutView->document().printing())
return;
if (!wasViewportResized())
return;
m_lastViewportSize = layoutSize(IncludeScrollbars);
m_lastZoomFactor = layoutView->style()->zoom();
m_frame->document()->enqueueResizeEvent();
if (m_frame->isMainFrame())
InspectorInstrumentation::didResizeMainFrame(m_frame.get());
}
void FrameView::postLayoutTimerFired(Timer<FrameView>*)
{
performPostLayoutTasks();
}
void FrameView::updateCounters()
{
LayoutView* view = layoutView();
if (!view->hasLayoutCounters())
return;
for (LayoutObject* layoutObject = view; layoutObject; layoutObject = layoutObject->nextInPreOrder()) {
if (!layoutObject->isCounter())
continue;
toLayoutCounter(layoutObject)->updateCounter();
}
}
IntRect FrameView::windowClipRect(IncludeScrollbarsInRect scrollbarInclusion) const
{
ASSERT(m_frame->view() == this);
// Set our clip rect to be our contents.
IntRect clipRect = contentsToRootFrame(visibleContentRect(scrollbarInclusion));
if (!m_frame->deprecatedLocalOwner())
return clipRect;
// Take our owner element and get its clip rect.
// FIXME: Do we need to do this for remote frames?
HTMLFrameOwnerElement* ownerElement = m_frame->deprecatedLocalOwner();
FrameView* parentView = ownerElement->document().view();
if (parentView)
clipRect.intersect(parentView->clipRectsForFrameOwner(ownerElement, nullptr));
return clipRect;
}
IntRect FrameView::clipRectsForFrameOwner(const HTMLFrameOwnerElement* ownerElement, IntRect* unobscuredRect) const
{
ASSERT(ownerElement);
if (unobscuredRect)
*unobscuredRect = IntRect();
// The layoutObject can sometimes be null when style="display:none" interacts
// with external content and plugins.
if (!ownerElement->layoutObject())
return windowClipRect();
// If we have no layer, just return our window clip rect.
const PaintLayer* enclosingLayer = ownerElement->layoutObject()->enclosingLayer();
if (!enclosingLayer)
return windowClipRect();
// FIXME: childrenClipRect relies on compositingState, which is not necessarily up to date.
// https://code.google.com/p/chromium/issues/detail?id=343769
DisableCompositingQueryAsserts disabler;
// Apply the clip from the layer.
IntRect elementRect = contentsToRootFrame(pixelSnappedIntRect(enclosingLayer->clipper().childrenClipRect()));
if (unobscuredRect) {
*unobscuredRect = elementRect;
// If element is not in root frame, clip to the local frame.
// FIXME: Do we need to do this for remote frames?
if (m_frame->deprecatedLocalOwner())
unobscuredRect->intersect(contentsToRootFrame(visibleContentRect()));
}
return intersection(elementRect, windowClipRect());
}
bool FrameView::shouldUseIntegerScrollOffset() const
{
if (m_frame->settings() && !m_frame->settings()->preferCompositingToLCDTextEnabled())
return true;
return ScrollableArea::shouldUseIntegerScrollOffset();
}
bool FrameView::isActive() const
{
Page* page = frame().page();
return page && page->focusController().isActive();
}
void FrameView::scrollTo(const DoublePoint& newPosition)
{
DoublePoint oldPosition = m_scrollPosition;
DoubleSize scrollDelta = newPosition - oldPosition;
if (scrollDelta.isZero())
return;
if (m_frame->settings() && m_frame->settings()->rootLayerScrolls()) {
// Don't scroll the FrameView!
ASSERT_NOT_REACHED();
}
m_scrollPosition = newPosition;
if (!scrollbarsSuppressed())
m_pendingScrollDelta += scrollDelta;
clearScrollAnchor();
updateLayersAndCompositingAfterScrollIfNeeded();
scrollPositionChanged();
frame().loader().client()->didChangeScrollOffset();
}
void FrameView::invalidatePaintForTickmarks() const
{
if (Scrollbar* scrollbar = verticalScrollbar())
scrollbar->invalidate();
}
void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
{
// Add in our offset within the FrameView.
IntRect dirtyRect = rect;
dirtyRect.moveBy(scrollbar->location());
layoutView()->invalidateDisplayItemClient(*scrollbar);
if (isInPerformLayout())
addScrollbarDamage(scrollbar, rect);
else
invalidateRect(dirtyRect);
}
void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const
{
if (!m_tickmarks.isEmpty())
tickmarks = m_tickmarks;
else
tickmarks = frame().document()->markers().renderedRectsForMarkers(DocumentMarker::TextMatch);
}
IntRect FrameView::windowResizerRect() const
{
if (Page* page = frame().page())
return page->chromeClient().windowResizerRect();
return IntRect();
}
void FrameView::setInputEventsTransformForEmulation(const IntSize& offset, float contentScaleFactor)
{
m_inputEventsOffsetForEmulation = offset;
m_inputEventsScaleFactorForEmulation = contentScaleFactor;
}
IntSize FrameView::inputEventsOffsetForEmulation() const
{
return m_inputEventsOffsetForEmulation;
}
float FrameView::inputEventsScaleFactor() const
{
float pageScale = m_frame->host()->visualViewport().scale();
return pageScale * m_inputEventsScaleFactorForEmulation;
}
bool FrameView::scrollbarsCanBeActive() const
{
if (m_frame->view() != this)
return false;
return !!m_frame->document();
}
void FrameView::scrollbarVisibilityChanged()
{
if (LayoutView* view = layoutView())
view->clearHitTestCache();
}
IntRect FrameView::scrollableAreaBoundingBox() const
{
LayoutPart* ownerLayoutObject = frame().ownerLayoutObject();
if (!ownerLayoutObject)
return frameRect();
return ownerLayoutObject->absoluteContentQuad().enclosingBoundingBox();
}
bool FrameView::isScrollable()
{
return scrollingReasons() == Scrollable;
}
bool FrameView::isProgrammaticallyScrollable()
{
return !m_inUpdateScrollbars;
}
FrameView::ScrollingReasons FrameView::scrollingReasons()
{
// Check for:
// 1) If there an actual overflow.
// 2) display:none or visibility:hidden set to self or inherited.
// 3) overflow{-x,-y}: hidden;
// 4) scrolling: no;
// Covers #1
IntSize contentsSize = this->contentsSize();
IntSize visibleContentSize = visibleContentRect().size();
if ((contentsSize.height() <= visibleContentSize.height() && contentsSize.width() <= visibleContentSize.width()))
return NotScrollableNoOverflow;
// Covers #2.
// FIXME: Do we need to fix this for OOPI?
HTMLFrameOwnerElement* owner = m_frame->deprecatedLocalOwner();
if (owner && (!owner->layoutObject() || !owner->layoutObject()->visibleToHitTesting()))
return NotScrollableNotVisible;
// Cover #3 and #4.
ScrollbarMode horizontalMode;
ScrollbarMode verticalMode;
calculateScrollbarModes(horizontalMode, verticalMode, RulesFromWebContentOnly);
if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
return NotScrollableExplicitlyDisabled;
return Scrollable;
}
void FrameView::updateScrollableAreaSet()
{
// That ensures that only inner frames are cached.
FrameView* parentFrameView = this->parentFrameView();
if (!parentFrameView)
return;
if (!isScrollable()) {
parentFrameView->removeScrollableArea(this);
return;
}
parentFrameView->addScrollableArea(this);
}
bool FrameView::shouldSuspendScrollAnimations() const
{
return !m_frame->document()->loadEventFinished();
}
void FrameView::scrollbarStyleChanged()
{
// FIXME: Why does this only apply to the main frame?
if (!m_frame->isMainFrame())
return;
adjustScrollbarOpacity();
contentsResized();
updateScrollbars(scrollOffsetDouble());
positionScrollbarLayers();
}
void FrameView::notifyPageThatContentAreaWillPaint() const
{
Page* page = m_frame->page();
if (!page)
return;
contentAreaWillPaint();
if (!m_scrollableAreas)
return;
for (const auto& scrollableArea : *m_scrollableAreas) {
if (!scrollableArea->scrollbarsCanBeActive())
continue;
scrollableArea->contentAreaWillPaint();
}
}
bool FrameView::scrollAnimatorEnabled() const
{
return m_frame->settings() && m_frame->settings()->scrollAnimatorEnabled();
}
void FrameView::updateDocumentAnnotatedRegions() const
{
Document* document = m_frame->document();
if (!document->hasAnnotatedRegions())
return;
Vector<AnnotatedRegionValue> newRegions;
collectAnnotatedRegions(*(document->layoutBox()), newRegions);
if (newRegions == document->annotatedRegions())
return;
document->setAnnotatedRegions(newRegions);
if (Page* page = m_frame->page())
page->chromeClient().annotatedRegionsChanged();
}
void FrameView::updateScrollCorner()
{
RefPtr<ComputedStyle> cornerStyle;
IntRect cornerRect = scrollCornerRect();
Document* doc = m_frame->document();
if (doc && !cornerRect.isEmpty()) {
// Try the <body> element first as a scroll corner source.
if (Element* body = doc->body()) {
if (LayoutObject* layoutObject = body->layoutObject())
cornerStyle = layoutObject->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), layoutObject->style());
}
if (!cornerStyle) {
// If the <body> didn't have a custom style, then the root element might.
if (Element* docElement = doc->documentElement()) {
if (LayoutObject* layoutObject = docElement->layoutObject())
cornerStyle = layoutObject->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), layoutObject->style());
}
}
if (!cornerStyle) {
// If we have an owning ipage/LocalFrame element, then it can set the custom scrollbar also.
if (LayoutPart* layoutObject = m_frame->ownerLayoutObject())
cornerStyle = layoutObject->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), layoutObject->style());
}
}
if (cornerStyle) {
if (!m_scrollCorner)
m_scrollCorner = LayoutScrollbarPart::createAnonymous(doc);
m_scrollCorner->setStyle(cornerStyle.release());
invalidateScrollCorner(cornerRect);
} else if (m_scrollCorner) {
m_scrollCorner->destroy();
m_scrollCorner = nullptr;
}
}
Color FrameView::documentBackgroundColor() const
{
// <https://bugs.webkit.org/show_bug.cgi?id=59540> We blend the background color of
// the document and the body against the base background color of the frame view.
// Background images are unfortunately impractical to include.
Color result = baseBackgroundColor();
if (!frame().document())
return result;
Element* htmlElement = frame().document()->documentElement();
Element* bodyElement = frame().document()->body();
// We take the aggregate of the base background color
// the <html> background color, and the <body>
// background color to find the document color. The
// addition of the base background color is not
// technically part of the document background, but it
// otherwise poses problems when the aggregate is not
// fully opaque.
if (htmlElement && htmlElement->layoutObject())
result = result.blend(htmlElement->layoutObject()->resolveColor(CSSPropertyBackgroundColor));
if (bodyElement && bodyElement->layoutObject())
result = result.blend(bodyElement->layoutObject()->resolveColor(CSSPropertyBackgroundColor));
return result;
}
FrameView* FrameView::parentFrameView() const
{
if (!parent())
return nullptr;
Frame* parentFrame = m_frame->tree().parent();
if (parentFrame && parentFrame->isLocalFrame())
return toLocalFrame(parentFrame)->view();
return nullptr;
}
bool FrameView::isPainting() const
{
return m_isPainting;
}
void FrameView::setNodeToDraw(Node* node)
{
m_nodeToDraw = node;
}
void FrameView::updateWidgetPositionsIfNeeded()
{
if (!m_needsUpdateWidgetPositions)
return;
m_needsUpdateWidgetPositions = false;
updateWidgetPositions();
}
void FrameView::updateAllLifecyclePhases(const LayoutRect* interestRect)
{
frame().localFrameRoot()->view()->updateLifecyclePhasesInternal(AllPhases, interestRect);
}
// TODO(chrishtr): add a scrolling update lifecycle phase.
void FrameView::updateLifecycleToCompositingCleanPlusScrolling()
{
frame().localFrameRoot()->view()->updateLifecyclePhasesInternal(OnlyUpToCompositingCleanPlusScrolling, nullptr);
}
void FrameView::updateLifecycleToLayoutClean()
{
frame().localFrameRoot()->view()->updateLifecyclePhasesInternal(OnlyUpToLayoutClean, nullptr);
}
void FrameView::updateLifecyclePhasesInternal(LifeCycleUpdateOption phases, const LayoutRect* interestRect)
{
// This must be called from the root frame, since it recurses down, not up.
// Otherwise the lifecycles of the frames might be out of sync.
ASSERT(m_frame->isLocalRoot());
// Updating layout can run script, which can tear down the FrameView.
RefPtrWillBeRawPtr<FrameView> protector(this);
updateStyleAndLayoutIfNeededRecursive();
ASSERT(lifecycle().state() >= DocumentLifecycle::LayoutClean);
if (phases == OnlyUpToLayoutClean) {
updateViewportIntersectionsForSubtree();
return;
}
if (LayoutView* view = layoutView()) {
TRACE_EVENT1("devtools.timeline", "UpdateLayerTree", "data", InspectorUpdateLayerTreeEvent::data(m_frame.get()));
// This was required for slimming paint v1 but is only temporarily
// needed for slimming paint v2.
view->compositor()->updateIfNeededRecursive();
scrollContentsIfNeededRecursive();
ASSERT(lifecycle().state() >= DocumentLifecycle::CompositingClean);
if (phases == AllPhases) {
invalidateTreeIfNeededRecursive();
if (view->compositor()->inCompositingMode())
scrollingCoordinator()->updateAfterCompositingChangeIfNeeded();
updateCompositedSelectionIfNeeded();
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
updatePaintProperties();
if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) {
synchronizedPaint(interestRect);
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
compositeForSlimmingPaintV2();
}
if (RuntimeEnabledFeatures::frameTimingSupportEnabled())
updateFrameTimingRequestsIfNeeded();
ASSERT(!view->hasPendingSelection());
ASSERT(lifecycle().state() == DocumentLifecycle::PaintInvalidationClean
|| (RuntimeEnabledFeatures::slimmingPaintV2Enabled() && lifecycle().state() == DocumentLifecycle::CompositingForSlimmingPaintV2Clean)
|| (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled() && lifecycle().state() == DocumentLifecycle::PaintClean));
}
}
updateViewportIntersectionsForSubtree();
}
void FrameView::updatePaintProperties()
{
ASSERT(RuntimeEnabledFeatures::slimmingPaintV2Enabled());
forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InUpdatePaintProperties); });
PaintPropertyTreeBuilder().buildPropertyTrees(*this);
forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::UpdatePaintPropertiesClean); });
}
void FrameView::synchronizedPaint(const LayoutRect* interestRect)
{
ASSERT(RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled());
ASSERT(frame() == page()->mainFrame() || (!frame().tree().parent()->isLocalFrame()));
LayoutView* view = layoutView();
ASSERT(view);
// TODO(chrishtr): figure out if there can be any GraphicsLayer above this one that draws content.
GraphicsLayer* rootGraphicsLayer = view->layer()->graphicsLayerBacking();
forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InPaint); });
// A null graphics layer can occur for painting of SVG images that are not parented into the main frame tree.
if (rootGraphicsLayer) {
synchronizedPaintRecursively(rootGraphicsLayer, interestRect);
}
forAllFrameViews([](FrameView& frameView) {
frameView.lifecycle().advanceTo(DocumentLifecycle::PaintClean);
frameView.layoutView()->layer()->clearNeedsRepaintRecursively();
});
}
void FrameView::synchronizedPaintRecursively(GraphicsLayer* graphicsLayer, const LayoutRect* interestRect)
{
ASSERT(graphicsLayer->paintController());
GraphicsContext context(*graphicsLayer->paintController());
// TODO(chrishtr): fix unit tests to not inject one-off interest rects.
if (interestRect)
graphicsLayer->paint(context, roundedIntRect(*interestRect));
else
graphicsLayer->paintIfNeeded(context);
if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled())
graphicsLayer->paintController()->commitNewDisplayItems();
for (auto& child : graphicsLayer->children())
synchronizedPaintRecursively(child, interestRect);
}
void FrameView::compositeForSlimmingPaintV2()
{
ASSERT(RuntimeEnabledFeatures::slimmingPaintV2Enabled());
ASSERT(frame() == page()->mainFrame() || (!frame().tree().parent()->isLocalFrame()));
forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::InCompositingForSlimmingPaintV2); });
// Detached frames can have no root graphics layer.
if (GraphicsLayer* rootGraphicsLayer = layoutView()->layer()->graphicsLayerBacking())
rootGraphicsLayer->paintController()->commitNewDisplayItems();
forAllFrameViews([](FrameView& frameView) { frameView.lifecycle().advanceTo(DocumentLifecycle::CompositingForSlimmingPaintV2Clean); });
}
void FrameView::updateFrameTimingRequestsIfNeeded()
{
GraphicsLayerFrameTimingRequests graphicsLayerTimingRequests;
// TODO(mpb) use a 'dirty' bit to not call this every time.
collectFrameTimingRequestsRecursive(graphicsLayerTimingRequests);
for (const auto& iter : graphicsLayerTimingRequests) {
const GraphicsLayer* graphicsLayer = iter.key;
graphicsLayer->platformLayer()->setFrameTimingRequests(iter.value);
}
}
void FrameView::updateStyleAndLayoutIfNeededRecursive()
{
if (shouldThrottleRendering())
return;
// We have to crawl our entire subtree looking for any FrameViews that need
// layout and make sure they are up to date.
// Mac actually tests for intersection with the dirty region and tries not to
// update layout for frames that are outside the dirty region. Not only does this seem
// pointless (since those frames will have set a zero timer to layout anyway), but
// it is also incorrect, since if two frames overlap, the first could be excluded from the dirty
// region but then become included later by the second frame adding rects to the dirty region
// when it lays out.
m_frame->document()->updateLayoutTreeIfNeeded();
if (needsLayout())
layout();
// FIXME: Calling layout() shouldn't trigger script execution or have any
// observable effects on the frame tree but we're not quite there yet.
WillBeHeapVector<RefPtrWillBeMember<FrameView>> frameViews;
for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
if (!child->isLocalFrame())
continue;
if (FrameView* view = toLocalFrame(child)->view())
frameViews.append(view);
}
for (const auto& frameView : frameViews)
frameView->updateStyleAndLayoutIfNeededRecursive();
// When an <iframe> gets composited, it triggers an extra style recalc in its containing FrameView.
// To avoid pushing an invalid tree for display, we have to check for this case and do another
// style recalc. The extra style recalc needs to happen after our child <iframes> were updated.
// FIXME: We shouldn't be triggering an extra style recalc in the first place.
if (m_frame->document()->hasSVGFilterElementsRequiringLayerUpdate()) {
m_frame->document()->updateLayoutTreeIfNeeded();
if (needsLayout())
layout();
}
// These asserts ensure that parent frames are clean, when child frames finished updating layout and style.
ASSERT(!needsLayout());
ASSERT(!m_frame->document()->hasSVGFilterElementsRequiringLayerUpdate());
#if ENABLE(ASSERT)
m_frame->document()->layoutView()->assertLaidOut();
#endif
updateWidgetPositionsIfNeeded();
if (lifecycle().state() < DocumentLifecycle::LayoutClean)
lifecycle().advanceTo(DocumentLifecycle::LayoutClean);
}
void FrameView::invalidateTreeIfNeededRecursive()
{
ASSERT(layoutView());
// We need to stop recursing here since a child frame view might not be throttled
// even though we are (e.g., it didn't compute its visibility yet).
if (shouldThrottleRendering())
return;
TRACE_EVENT1("blink", "FrameView::invalidateTreeIfNeededRecursive", "root", layoutView()->debugName().ascii());
Vector<LayoutObject*> pendingDelayedPaintInvalidations;
PaintInvalidationState rootPaintInvalidationState(*layoutView(), pendingDelayedPaintInvalidations);
invalidateTreeIfNeeded(rootPaintInvalidationState);
// Some frames may be not reached during the above invalidateTreeIfNeeded because
// - the frame is a detached frame; or
// - it didn't need paint invalidation.
// We need to call invalidateTreeIfNeededRecursive() for such frames to finish required
// paint invalidation and advance their life cycle state.
for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
if (!child->isLocalFrame())
continue;
FrameView* childFrameView = toLocalFrame(child)->view();
if (childFrameView->lifecycle().state() < DocumentLifecycle::PaintInvalidationClean)
childFrameView->invalidateTreeIfNeededRecursive();
}
// Process objects needing paint invalidation on the next frame. See the definition of PaintInvalidationDelayedFull for more details.
for (auto& target : pendingDelayedPaintInvalidations)
target->setShouldDoFullPaintInvalidation(PaintInvalidationDelayedFull);
}
void FrameView::enableAutoSizeMode(const IntSize& minSize, const IntSize& maxSize)
{
if (!m_autoSizeInfo)
m_autoSizeInfo = FrameViewAutoSizeInfo::create(this);
m_autoSizeInfo->configureAutoSizeMode(minSize, maxSize);
setLayoutSizeFixedToFrameSize(true);
setNeedsLayout();
scheduleRelayout();
}
void FrameView::disableAutoSizeMode()
{
if (!m_autoSizeInfo)
return;
setLayoutSizeFixedToFrameSize(false);
setNeedsLayout();
scheduleRelayout();
// Since autosize mode forces the scrollbar mode, change them to being auto.
setVerticalScrollbarLock(false);
setHorizontalScrollbarLock(false);
setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
m_autoSizeInfo.clear();
}
void FrameView::forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor)
{
// Dumping externalRepresentation(m_frame->layoutObject()).ascii() is a good trick to see
// the state of things before and after the layout
if (LayoutView* layoutView = this->layoutView()) {
float pageLogicalWidth = layoutView->style()->isHorizontalWritingMode() ? pageSize.width() : pageSize.height();
float pageLogicalHeight = layoutView->style()->isHorizontalWritingMode() ? pageSize.height() : pageSize.width();
LayoutUnit flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
LayoutUnit flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
layoutView->setLogicalWidth(flooredPageLogicalWidth);
layoutView->setPageLogicalHeight(flooredPageLogicalHeight);
layoutView->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::PrintingChanged);
layout();
// If we don't fit in the given page width, we'll lay out again. If we don't fit in the
// page width when shrunk, we will lay out at maximum shrink and clip extra content.
// FIXME: We are assuming a shrink-to-fit printing implementation. A cropping
// implementation should not do this!
bool horizontalWritingMode = layoutView->style()->isHorizontalWritingMode();
const LayoutRect& documentRect = LayoutRect(layoutView->documentRect());
LayoutUnit docLogicalWidth = horizontalWritingMode ? documentRect.width() : documentRect.height();
if (docLogicalWidth > pageLogicalWidth) {
FloatSize expectedPageSize(std::min<float>(documentRect.width().toFloat(), pageSize.width() * maximumShrinkFactor), std::min<float>(documentRect.height().toFloat(), pageSize.height() * maximumShrinkFactor));
FloatSize maxPageSize = m_frame->resizePageRectsKeepingRatio(FloatSize(originalPageSize.width(), originalPageSize.height()), expectedPageSize);
pageLogicalWidth = horizontalWritingMode ? maxPageSize.width() : maxPageSize.height();
pageLogicalHeight = horizontalWritingMode ? maxPageSize.height() : maxPageSize.width();
flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
layoutView->setLogicalWidth(flooredPageLogicalWidth);
layoutView->setPageLogicalHeight(flooredPageLogicalHeight);
layoutView->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::PrintingChanged);
layout();
const LayoutRect& updatedDocumentRect = LayoutRect(layoutView->documentRect());
LayoutUnit docLogicalHeight = horizontalWritingMode ? updatedDocumentRect.height() : updatedDocumentRect.width();
LayoutUnit docLogicalTop = horizontalWritingMode ? updatedDocumentRect.y() : updatedDocumentRect.x();
LayoutUnit docLogicalRight = horizontalWritingMode ? updatedDocumentRect.maxX() : updatedDocumentRect.maxY();
LayoutUnit clippedLogicalLeft = 0;
if (!layoutView->style()->isLeftToRightDirection())
clippedLogicalLeft = docLogicalRight - pageLogicalWidth;
LayoutRect overflow(clippedLogicalLeft, docLogicalTop, pageLogicalWidth, docLogicalHeight);
if (!horizontalWritingMode)
overflow = overflow.transposedRect();
layoutView->clearLayoutOverflow();
layoutView->addLayoutOverflow(overflow); // This is how we clip in case we overflow again.
}
}
adjustViewSize();
}
IntRect FrameView::convertFromLayoutObject(const LayoutObject& layoutObject, const IntRect& layoutObjectRect) const
{
IntRect rect = pixelSnappedIntRect(enclosingLayoutRect(layoutObject.localToAbsoluteQuad(FloatRect(layoutObjectRect)).boundingBox()));
// Convert from page ("absolute") to FrameView coordinates.
rect.moveBy(-scrollPosition());
return rect;
}
IntRect FrameView::convertToLayoutObject(const LayoutObject& layoutObject, const IntRect& frameRect) const
{
IntRect rectInContent = frameToContents(frameRect);
// Convert from FrameView coords into page ("absolute") coordinates.
rectInContent.moveBy(scrollPosition());
// FIXME: we don't have a way to map an absolute rect down to a local quad, so just
// move the rect for now.
rectInContent.setLocation(roundedIntPoint(layoutObject.absoluteToLocal(rectInContent.location(), UseTransforms)));
return rectInContent;
}
IntPoint FrameView::convertFromLayoutObject(const LayoutObject& layoutObject, const IntPoint& layoutObjectPoint) const
{
IntPoint point = roundedIntPoint(layoutObject.localToAbsolute(layoutObjectPoint, UseTransforms));
// Convert from page ("absolute") to FrameView coordinates.
point.moveBy(-scrollPosition());
return point;
}
IntPoint FrameView::convertToLayoutObject(const LayoutObject& layoutObject, const IntPoint& framePoint) const
{
IntPoint point = framePoint;
// Convert from FrameView coords into page ("absolute") coordinates.
point += IntSize(scrollX(), scrollY());
return roundedIntPoint(layoutObject.absoluteToLocal(point, UseTransforms));
}
IntRect FrameView::convertToContainingView(const IntRect& localRect) const
{
if (const FrameView* parentView = toFrameView(parent())) {
// Get our layoutObject in the parent view
LayoutPart* layoutObject = m_frame->ownerLayoutObject();
if (!layoutObject)
return localRect;
IntRect rect(localRect);
// Add borders and padding??
rect.move(layoutObject->borderLeft() + layoutObject->paddingLeft(),
layoutObject->borderTop() + layoutObject->paddingTop());
return parentView->convertFromLayoutObject(*layoutObject, rect);
}
return localRect;
}
IntRect FrameView::convertFromContainingView(const IntRect& parentRect) const
{
if (const FrameView* parentView = toFrameView(parent())) {
// Get our layoutObject in the parent view
LayoutPart* layoutObject = m_frame->ownerLayoutObject();
if (!layoutObject)
return parentRect;
IntRect rect = parentView->convertToLayoutObject(*layoutObject, parentRect);
// Subtract borders and padding
rect.move(-layoutObject->borderLeft() - layoutObject->paddingLeft(),
-layoutObject->borderTop() - layoutObject->paddingTop());
return rect;
}
return parentRect;
}
IntPoint FrameView::convertToContainingView(const IntPoint& localPoint) const
{
if (const FrameView* parentView = toFrameView(parent())) {
// Get our layoutObject in the parent view
LayoutPart* layoutObject = m_frame->ownerLayoutObject();
if (!layoutObject)
return localPoint;
IntPoint point(localPoint);
// Add borders and padding
point.move(layoutObject->borderLeft() + layoutObject->paddingLeft(),
layoutObject->borderTop() + layoutObject->paddingTop());
return parentView->convertFromLayoutObject(*layoutObject, point);
}
return localPoint;
}
IntPoint FrameView::convertFromContainingView(const IntPoint& parentPoint) const
{
if (const FrameView* parentView = toFrameView(parent())) {
// Get our layoutObject in the parent view
LayoutPart* layoutObject = m_frame->ownerLayoutObject();
if (!layoutObject)
return parentPoint;
IntPoint point = parentView->convertToLayoutObject(*layoutObject, parentPoint);
// Subtract borders and padding
point.move(-layoutObject->borderLeft() - layoutObject->paddingLeft(),
-layoutObject->borderTop() - layoutObject->paddingTop());
return point;
}
return parentPoint;
}
void FrameView::setInitialTracksPaintInvalidationsForTesting(bool trackPaintInvalidations)
{
s_initialTrackAllPaintInvalidations = trackPaintInvalidations;
}
void FrameView::setTracksPaintInvalidations(bool trackPaintInvalidations)
{
if (trackPaintInvalidations == m_isTrackingPaintInvalidations)
return;
for (Frame* frame = m_frame->tree().top(); frame; frame = frame->tree().traverseNext()) {
if (!frame->isLocalFrame())
continue;
if (LayoutView* layoutView = toLocalFrame(frame)->contentLayoutObject())
layoutView->compositor()->setTracksPaintInvalidations(trackPaintInvalidations);
}
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"),
"FrameView::setTracksPaintInvalidations", TRACE_EVENT_SCOPE_GLOBAL, "enabled", trackPaintInvalidations);
resetTrackedPaintInvalidations();
m_isTrackingPaintInvalidations = trackPaintInvalidations;
}
void FrameView::resetTrackedPaintInvalidations()
{
if (LayoutView* layoutView = this->layoutView())
layoutView->compositor()->resetTrackedPaintInvalidationRects();
}
void FrameView::addResizerArea(LayoutBox& resizerBox)
{
if (!m_resizerAreas)
m_resizerAreas = adoptPtr(new ResizerAreaSet);
m_resizerAreas->add(&resizerBox);
}
void FrameView::removeResizerArea(LayoutBox& resizerBox)
{
if (!m_resizerAreas)
return;
ResizerAreaSet::iterator it = m_resizerAreas->find(&resizerBox);
if (it != m_resizerAreas->end())
m_resizerAreas->remove(it);
}
void FrameView::addScrollableArea(ScrollableArea* scrollableArea)
{
ASSERT(scrollableArea);
if (!m_scrollableAreas)
m_scrollableAreas = adoptPtrWillBeNoop(new ScrollableAreaSet);
m_scrollableAreas->add(scrollableArea);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreasDidChange();
}
void FrameView::removeScrollableArea(ScrollableArea* scrollableArea)
{
if (!m_scrollableAreas)
return;
m_scrollableAreas->remove(scrollableArea);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreasDidChange();
}
void FrameView::addAnimatingScrollableArea(ScrollableArea* scrollableArea)
{
ASSERT(scrollableArea);
if (!m_animatingScrollableAreas)
m_animatingScrollableAreas = adoptPtrWillBeNoop(new ScrollableAreaSet);
m_animatingScrollableAreas->add(scrollableArea);
}
void FrameView::removeAnimatingScrollableArea(ScrollableArea* scrollableArea)
{
if (!m_animatingScrollableAreas)
return;
m_animatingScrollableAreas->remove(scrollableArea);
}
void FrameView::setParent(Widget* parentView)
{
if (parentView == parent())
return;
if (m_scrollbarsAvoidingResizer && parent())
toFrameView(parent())->adjustScrollbarsAvoidingResizerCount(-m_scrollbarsAvoidingResizer);
Widget::setParent(parentView);
if (m_scrollbarsAvoidingResizer && parent())
toFrameView(parent())->adjustScrollbarsAvoidingResizerCount(m_scrollbarsAvoidingResizer);
updateScrollableAreaSet();
setNeedsUpdateViewportIntersection();
}
void FrameView::removeChild(Widget* child)
{
ASSERT(child->parent() == this);
if (child->isFrameView())
removeScrollableArea(toFrameView(child));
child->setParent(0);
m_children.remove(child);
}
bool FrameView::isVerticalDocument() const
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return true;
return layoutView->style()->isHorizontalWritingMode();
}
bool FrameView::isFlippedDocument() const
{
LayoutView* layoutView = this->layoutView();
if (!layoutView)
return false;
return layoutView->hasFlippedBlocksWritingMode();
}
bool FrameView::visualViewportSuppliesScrollbars() const
{
return m_frame->isMainFrame() && m_frame->settings() && m_frame->settings()->viewportMetaEnabled();
}
AXObjectCache* FrameView::axObjectCache() const
{
if (frame().document())
return frame().document()->existingAXObjectCache();
return nullptr;
}
void FrameView::setCursor(const Cursor& cursor)
{
Page* page = frame().page();
if (!page || !page->settings().deviceSupportsMouse())
return;
page->chromeClient().setCursor(cursor, m_frame->localFrameRoot());
}
void FrameView::frameRectsChanged()
{
TRACE_EVENT0("blink", "FrameView::frameRectsChanged");
if (layoutSizeFixedToFrameSize())
setLayoutSizeInternal(frameRect().size());
setNeedsUpdateViewportIntersection();
for (const auto& child : m_children)
child->frameRectsChanged();
}
void FrameView::setLayoutSizeInternal(const IntSize& size)
{
if (m_layoutSize == size)
return;
m_layoutSize = size;
if (Document* document = m_frame->document()) {
if (document->isActive())
document->notifyResizeForViewportUnits();
}
contentsResized();
}
void FrameView::didAddScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
{
ScrollableArea::didAddScrollbar(scrollbar, orientation);
if (AXObjectCache* cache = axObjectCache())
cache->handleScrollbarUpdate(this);
}
void FrameView::setTopControlsViewportAdjustment(float adjustment)
{
m_topControlsViewportAdjustment = adjustment;
}
IntPoint FrameView::maximumScrollPosition() const
{
// Make the same calculation as in CC's LayerImpl::MaxScrollOffset()
// FIXME: We probably shouldn't be storing the bounds in a float. crbug.com/422331.
IntSize visibleSize = visibleContentSize(ExcludeScrollbars) + topControlsSize();
IntSize contentBounds = contentsSize();
IntPoint maximumPosition = -scrollOrigin() + (contentBounds - visibleSize);
return maximumPosition.expandedTo(minimumScrollPosition());
}
void FrameView::addChild(PassRefPtrWillBeRawPtr<Widget> prpChild)
{
Widget* child = prpChild.get();
ASSERT(child != this && !child->parent());
child->setParent(this);
m_children.add(prpChild);
}
void FrameView::setHasHorizontalScrollbar(bool hasBar)
{
if (hasBar == !!m_horizontalScrollbar)
return;
if (hasBar) {
m_horizontalScrollbar = createScrollbar(HorizontalScrollbar);
addChild(m_horizontalScrollbar.get());
didAddScrollbar(m_horizontalScrollbar.get(), HorizontalScrollbar);
m_horizontalScrollbar->styleChanged();
} else {
willRemoveScrollbar(m_horizontalScrollbar.get(), HorizontalScrollbar);
if (AXObjectCache* cache = axObjectCache())
cache->remove(m_horizontalScrollbar.get());
// If the scrollbar has been marked as overlapping the window resizer,
// then its removal should reduce the count.
if (m_horizontalScrollbar->overlapsResizer())
adjustScrollbarsAvoidingResizerCount(-1);
removeChild(m_horizontalScrollbar.get());
m_horizontalScrollbar->disconnectFromScrollableArea();
m_horizontalScrollbar = nullptr;
if (AXObjectCache* cache = axObjectCache())
cache->handleScrollbarUpdate(this);
}
invalidateScrollCorner(scrollCornerRect());
}
void FrameView::setHasVerticalScrollbar(bool hasBar)
{
if (hasBar == !!m_verticalScrollbar)
return;
if (hasBar) {
m_verticalScrollbar = createScrollbar(VerticalScrollbar);
addChild(m_verticalScrollbar.get());
didAddScrollbar(m_verticalScrollbar.get(), VerticalScrollbar);
m_verticalScrollbar->styleChanged();
} else {
willRemoveScrollbar(m_verticalScrollbar.get(), VerticalScrollbar);
if (AXObjectCache* cache = axObjectCache())
cache->remove(m_verticalScrollbar.get());
// If the scrollbar has been marked as overlapping the window resizer,
// then its removal should reduce the count.
if (m_verticalScrollbar->overlapsResizer())
adjustScrollbarsAvoidingResizerCount(-1);
removeChild(m_verticalScrollbar.get());
m_verticalScrollbar->disconnectFromScrollableArea();
m_verticalScrollbar = nullptr;
if (AXObjectCache* cache = axObjectCache())
cache->handleScrollbarUpdate(this);
}
invalidateScrollCorner(scrollCornerRect());
}
void FrameView::setScrollbarModes(ScrollbarMode horizontalMode, ScrollbarMode verticalMode,
bool horizontalLock, bool verticalLock)
{
bool needsUpdate = false;
// If the page's overflow setting has disabled scrolling, do not allow anything to override that setting.
// http://crbug.com/426447
LayoutObject* viewport = viewportLayoutObject();
if (viewport && !shouldIgnoreOverflowHidden()) {
if (viewport->style()->overflowX() == OHIDDEN)
horizontalMode = ScrollbarAlwaysOff;
if (viewport->style()->overflowY() == OHIDDEN)
verticalMode = ScrollbarAlwaysOff;
}
if (horizontalMode != horizontalScrollbarMode() && !m_horizontalScrollbarLock) {
m_horizontalScrollbarMode = horizontalMode;
needsUpdate = true;
}
if (verticalMode != verticalScrollbarMode() && !m_verticalScrollbarLock) {
m_verticalScrollbarMode = verticalMode;
needsUpdate = true;
}
if (horizontalLock)
setHorizontalScrollbarLock();
if (verticalLock)
setVerticalScrollbarLock();
if (!needsUpdate)
return;
updateScrollbars(scrollOffsetDouble());
if (!layerForScrolling())
return;
WebLayer* layer = layerForScrolling()->platformLayer();
if (!layer)
return;
layer->setUserScrollable(userInputScrollable(HorizontalScrollbar), userInputScrollable(VerticalScrollbar));
}
IntSize FrameView::visibleContentSize(IncludeScrollbarsInRect scrollbarInclusion) const
{
return scrollbarInclusion == ExcludeScrollbars ? excludeScrollbars(frameRect().size()) : frameRect().size();
}
IntRect FrameView::visibleContentRect(IncludeScrollbarsInRect scrollbarInclusion) const
{
return IntRect(flooredIntPoint(m_scrollPosition), visibleContentSize(scrollbarInclusion));
}
IntSize FrameView::contentsSize() const
{
return m_contentsSize;
}
IntPoint FrameView::minimumScrollPosition() const
{
return IntPoint(-scrollOrigin().x(), -scrollOrigin().y());
}
void FrameView::adjustScrollbarOpacity()
{
if (m_horizontalScrollbar && layerForHorizontalScrollbar()) {
bool isOpaqueScrollbar = !m_horizontalScrollbar->isOverlayScrollbar();
layerForHorizontalScrollbar()->setContentsOpaque(isOpaqueScrollbar);
}
if (m_verticalScrollbar && layerForVerticalScrollbar()) {
bool isOpaqueScrollbar = !m_verticalScrollbar->isOverlayScrollbar();
layerForVerticalScrollbar()->setContentsOpaque(isOpaqueScrollbar);
}
}
int FrameView::scrollSize(ScrollbarOrientation orientation) const
{
Scrollbar* scrollbar = ((orientation == HorizontalScrollbar) ? m_horizontalScrollbar : m_verticalScrollbar).get();
// If no scrollbars are present, the content may still be scrollable.
if (!scrollbar) {
IntSize scrollSize = m_contentsSize - visibleContentRect().size();
scrollSize.clampNegativeToZero();
return orientation == HorizontalScrollbar ? scrollSize.width() : scrollSize.height();
}
return scrollbar->totalSize() - scrollbar->visibleSize();
}
void FrameView::setScrollOffset(const IntPoint& offset, ScrollType)
{
scrollTo(clampScrollPosition(offset));
}
void FrameView::setScrollOffset(const DoublePoint& offset, ScrollType)
{
scrollTo(clampScrollPosition(offset));
}
void FrameView::windowResizerRectChanged()
{
updateScrollbars(scrollOffsetDouble());
}
bool FrameView::hasOverlayScrollbars() const
{
return (m_horizontalScrollbar && m_horizontalScrollbar->isOverlayScrollbar())
|| (m_verticalScrollbar && m_verticalScrollbar->isOverlayScrollbar());
}
void FrameView::computeScrollbarExistence(bool& newHasHorizontalScrollbar, bool& newHasVerticalScrollbar, const IntSize& docSize, ComputeScrollbarExistenceOption option) const
{
bool hasHorizontalScrollbar = m_horizontalScrollbar;
bool hasVerticalScrollbar = m_verticalScrollbar;
newHasHorizontalScrollbar = hasHorizontalScrollbar;
newHasVerticalScrollbar = hasVerticalScrollbar;
if (m_frame->settings() && m_frame->settings()->rootLayerScrolls())
return;
ScrollbarMode hScroll = m_horizontalScrollbarMode;
ScrollbarMode vScroll = m_verticalScrollbarMode;
if (hScroll != ScrollbarAuto)
newHasHorizontalScrollbar = (hScroll == ScrollbarAlwaysOn);
if (vScroll != ScrollbarAuto)
newHasVerticalScrollbar = (vScroll == ScrollbarAlwaysOn);
if (m_scrollbarsSuppressed || (hScroll != ScrollbarAuto && vScroll != ScrollbarAuto))
return;
if (hScroll == ScrollbarAuto)
newHasHorizontalScrollbar = docSize.width() > visibleWidth();
if (vScroll == ScrollbarAuto)
newHasVerticalScrollbar = docSize.height() > visibleHeight();
if (hasOverlayScrollbars())
return;
IntSize fullVisibleSize = visibleContentRect(IncludeScrollbars).size();
bool attemptToRemoveScrollbars = (option == FirstPass
&& docSize.width() <= fullVisibleSize.width() && docSize.height() <= fullVisibleSize.height());
if (attemptToRemoveScrollbars) {
if (hScroll == ScrollbarAuto)
newHasHorizontalScrollbar = false;
if (vScroll == ScrollbarAuto)
newHasVerticalScrollbar = false;
}
}
void FrameView::updateScrollbarGeometry()
{
if (m_horizontalScrollbar) {
int clientWidth = visibleWidth();
IntRect oldRect(m_horizontalScrollbar->frameRect());
IntRect hBarRect((shouldPlaceVerticalScrollbarOnLeft() && m_verticalScrollbar) ? m_verticalScrollbar->width() : 0,
height() - m_horizontalScrollbar->height(),
width() - (m_verticalScrollbar ? m_verticalScrollbar->width() : 0),
m_horizontalScrollbar->height());
m_horizontalScrollbar->setFrameRect(adjustScrollbarRectForResizer(hBarRect, m_horizontalScrollbar.get()));
if (!m_scrollbarsSuppressed && oldRect != m_horizontalScrollbar->frameRect())
m_horizontalScrollbar->invalidate();
if (m_scrollbarsSuppressed)
m_horizontalScrollbar->setSuppressInvalidation(true);
m_horizontalScrollbar->setEnabled(contentsWidth() > clientWidth);
m_horizontalScrollbar->setProportion(clientWidth, contentsWidth());
m_horizontalScrollbar->offsetDidChange();
if (m_scrollbarsSuppressed)
m_horizontalScrollbar->setSuppressInvalidation(false);
}
if (m_verticalScrollbar) {
int clientHeight = visibleHeight();
IntRect oldRect(m_verticalScrollbar->frameRect());
IntRect vBarRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : (width() - m_verticalScrollbar->width()),
0,
m_verticalScrollbar->width(),
height() - (m_horizontalScrollbar ? m_horizontalScrollbar->height() : 0));
m_verticalScrollbar->setFrameRect(adjustScrollbarRectForResizer(vBarRect, m_verticalScrollbar.get()));
if (!m_scrollbarsSuppressed && oldRect != m_verticalScrollbar->frameRect())
m_verticalScrollbar->invalidate();
if (m_scrollbarsSuppressed)
m_verticalScrollbar->setSuppressInvalidation(true);
m_verticalScrollbar->setEnabled(contentsHeight() > clientHeight);
m_verticalScrollbar->setProportion(clientHeight, contentsHeight());
m_verticalScrollbar->offsetDidChange();
if (m_scrollbarsSuppressed)
m_verticalScrollbar->setSuppressInvalidation(false);
}
}
IntRect FrameView::adjustScrollbarRectForResizer(const IntRect& rect, Scrollbar* scrollbar)
{
// Get our window resizer rect and see if we overlap. Adjust to avoid the overlap
// if necessary.
IntRect adjustedRect(rect);
bool overlapsResizer = false;
if (!rect.isEmpty() && !windowResizerRect().isEmpty()) {
IntRect resizerRect = convertFromContainingWindow(windowResizerRect());
if (rect.intersects(resizerRect)) {
if (scrollbar->orientation() == HorizontalScrollbar) {
int overlap = rect.maxX() - resizerRect.x();
if (overlap > 0 && resizerRect.maxX() >= rect.maxX()) {
adjustedRect.setWidth(rect.width() - overlap);
overlapsResizer = true;
}
} else {
int overlap = rect.maxY() - resizerRect.y();
if (overlap > 0 && resizerRect.maxY() >= rect.maxY()) {
adjustedRect.setHeight(rect.height() - overlap);
overlapsResizer = true;
}
}
}
}
if (overlapsResizer != scrollbar->overlapsResizer()) {
scrollbar->setOverlapsResizer(overlapsResizer);
adjustScrollbarsAvoidingResizerCount(overlapsResizer ? 1 : -1);
}
return adjustedRect;
}
bool FrameView::adjustScrollbarExistence(ComputeScrollbarExistenceOption option)
{
ASSERT(m_inUpdateScrollbars);
// If we came in here with the view already needing a layout, then go ahead and do that
// first. (This will be the common case, e.g., when the page changes due to window resizing for example).
// This layout will not re-enter updateScrollbars and does not count towards our max layout pass total.
if (!m_scrollbarsSuppressed)
scrollbarExistenceDidChange();
bool hasHorizontalScrollbar = m_horizontalScrollbar;
bool hasVerticalScrollbar = m_verticalScrollbar;
bool newHasHorizontalScrollbar = false;
bool newHasVerticalScrollbar = false;
computeScrollbarExistence(newHasHorizontalScrollbar, newHasVerticalScrollbar, contentsSize(), option);
bool scrollbarExistenceChanged = hasHorizontalScrollbar != newHasHorizontalScrollbar || hasVerticalScrollbar != newHasVerticalScrollbar;
if (!scrollbarExistenceChanged)
return false;
setHasHorizontalScrollbar(newHasHorizontalScrollbar);
setHasVerticalScrollbar(newHasVerticalScrollbar);
if (m_scrollbarsSuppressed)
return true;
if (!hasOverlayScrollbars())
contentsResized();
scrollbarExistenceDidChange();
return true;
}
bool FrameView::needsScrollbarReconstruction() const
{
Element* customScrollbarElement = nullptr;
LocalFrame* customScrollbarFrame = nullptr;
bool shouldUseCustom = shouldUseCustomScrollbars(customScrollbarElement, customScrollbarFrame);
bool hasAnyScrollbar = m_horizontalScrollbar || m_verticalScrollbar;
bool hasCustom = (m_horizontalScrollbar && m_horizontalScrollbar->isCustomScrollbar())
|| (m_verticalScrollbar && m_verticalScrollbar->isCustomScrollbar());
return hasAnyScrollbar && (shouldUseCustom != hasCustom);
}
bool FrameView::shouldIgnoreOverflowHidden() const
{
return m_frame->settings()->ignoreMainFrameOverflowHiddenQuirk() && m_frame->isMainFrame();
}
void FrameView::updateScrollbars(const DoubleSize& desiredOffset)
{
// Avoid drawing two sets of scrollbars when visual viewport is enabled.
if (visualViewportSuppliesScrollbars()) {
setHasHorizontalScrollbar(false);
setHasVerticalScrollbar(false);
setScrollOffsetFromUpdateScrollbars(desiredOffset);
return;
}
if (m_inUpdateScrollbars)
return;
InUpdateScrollbarsScope inUpdateScrollbarsScope(this);
IntSize oldVisibleSize = visibleContentSize();
bool scrollbarExistenceChanged = false;
if (needsScrollbarReconstruction()) {
setHasHorizontalScrollbar(false);
setHasVerticalScrollbar(false);
scrollbarExistenceChanged = true;
}
int maxUpdateScrollbarsPass = hasOverlayScrollbars() || m_scrollbarsSuppressed ? 1 : 3;
for (int updateScrollbarsPass = 0; updateScrollbarsPass < maxUpdateScrollbarsPass; updateScrollbarsPass++) {
if (!adjustScrollbarExistence(updateScrollbarsPass ? Incremental : FirstPass))
break;
scrollbarExistenceChanged = true;
}
updateScrollbarGeometry();
if (scrollbarExistenceChanged) {
// FIXME: Is frameRectsChanged really necessary here? Have any frame rects changed?
frameRectsChanged();
positionScrollbarLayers();
updateScrollCorner();
}
// FIXME: We don't need to do this if we are composited.
IntSize newVisibleSize = visibleContentSize();
if (newVisibleSize.width() > oldVisibleSize.width()) {
if (shouldPlaceVerticalScrollbarOnLeft())
invalidateRect(IntRect(0, 0, newVisibleSize.width() - oldVisibleSize.width(), newVisibleSize.height()));
else
invalidateRect(IntRect(oldVisibleSize.width(), 0, newVisibleSize.width() - oldVisibleSize.width(), newVisibleSize.height()));
}
if (newVisibleSize.height() > oldVisibleSize.height())
invalidateRect(IntRect(0, oldVisibleSize.height(), newVisibleSize.width(), newVisibleSize.height() - oldVisibleSize.height()));
setScrollOffsetFromUpdateScrollbars(desiredOffset);
}
void FrameView::setScrollOffsetFromUpdateScrollbars(const DoubleSize& offset)
{
DoublePoint adjustedScrollPosition = clampScrollPosition(DoublePoint(offset));
if (adjustedScrollPosition != scrollPositionDouble() || scrollOriginChanged()) {
ScrollableArea::setScrollPosition(adjustedScrollPosition, ProgrammaticScroll);
resetScrollOriginChanged();
}
}
IntRect FrameView::rectToCopyOnScroll() const
{
IntRect scrollViewRect = convertToContainingWindow(IntRect((shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar()) ? verticalScrollbar()->width() : 0, 0, visibleWidth(), visibleHeight()));
if (hasOverlayScrollbars()) {
int verticalScrollbarWidth = (verticalScrollbar() && !hasLayerForVerticalScrollbar()) ? verticalScrollbar()->width() : 0;
int horizontalScrollbarHeight = (horizontalScrollbar() && !hasLayerForHorizontalScrollbar()) ? horizontalScrollbar()->height() : 0;
scrollViewRect.setWidth(scrollViewRect.width() - verticalScrollbarWidth);
scrollViewRect.setHeight(scrollViewRect.height() - horizontalScrollbarHeight);
}
return scrollViewRect;
}
void FrameView::scrollContentsIfNeeded()
{
if (m_pendingScrollDelta.isZero())
return;
DoubleSize scrollDelta = m_pendingScrollDelta;
m_pendingScrollDelta = DoubleSize();
// FIXME: Change scrollContents() to take DoubleSize. crbug.com/414283.
scrollContents(flooredIntSize(scrollDelta));
}
void FrameView::scrollContents(const IntSize& scrollDelta)
{
HostWindow* window = hostWindow();
if (!window)
return;
TRACE_EVENT0("blink", "FrameView::scrollContents");
IntRect clipRect = windowClipRect();
IntRect updateRect = clipRect;
updateRect.intersect(rectToCopyOnScroll());
if (!scrollContentsFastPath(-scrollDelta))
scrollContentsSlowPath(updateRect);
// This call will move children with native widgets (plugins) and invalidate them as well.
frameRectsChanged();
}
IntPoint FrameView::contentsToFrame(const IntPoint& pointInContentSpace) const
{
return pointInContentSpace - scrollOffset();
}
IntRect FrameView::contentsToFrame(const IntRect& rectInContentSpace) const
{
return IntRect(contentsToFrame(rectInContentSpace.location()), rectInContentSpace.size());
}
FloatPoint FrameView::frameToContents(const FloatPoint& pointInFrame) const
{
return pointInFrame + scrollOffset();
}
IntPoint FrameView::frameToContents(const IntPoint& pointInFrame) const
{
return pointInFrame + scrollOffset();
}
IntRect FrameView::frameToContents(const IntRect& rectInFrame) const
{
return IntRect(frameToContents(rectInFrame.location()), rectInFrame.size());
}
IntPoint FrameView::rootFrameToContents(const IntPoint& rootFramePoint) const
{
IntPoint framePoint = convertFromContainingWindow(rootFramePoint);
return frameToContents(framePoint);
}
IntRect FrameView::rootFrameToContents(const IntRect& rootFrameRect) const
{
return IntRect(rootFrameToContents(rootFrameRect.location()), rootFrameRect.size());
}
IntPoint FrameView::contentsToRootFrame(const IntPoint& contentsPoint) const
{
IntPoint framePoint = contentsToFrame(contentsPoint);
return convertToContainingWindow(framePoint);
}
IntRect FrameView::contentsToRootFrame(const IntRect& contentsRect) const
{
IntRect rectInFrame = contentsToFrame(contentsRect);
return convertToContainingWindow(rectInFrame);
}
FloatPoint FrameView::rootFrameToContents(const FloatPoint& windowPoint) const
{
FloatPoint framePoint = convertFromContainingWindow(windowPoint);
return frameToContents(framePoint);
}
IntRect FrameView::viewportToContents(const IntRect& rectInViewport) const
{
IntRect rectInRootFrame = m_frame->host()->visualViewport().viewportToRootFrame(rectInViewport);
IntRect frameRect = convertFromContainingWindow(rectInRootFrame);
return frameToContents(frameRect);
}
IntPoint FrameView::viewportToContents(const IntPoint& pointInViewport) const
{
IntPoint pointInRootFrame = m_frame->host()->visualViewport().viewportToRootFrame(pointInViewport);
IntPoint pointInFrame = convertFromContainingWindow(pointInRootFrame);
return frameToContents(pointInFrame);
}
IntRect FrameView::contentsToViewport(const IntRect& rectInContents) const
{
IntRect rectInFrame = contentsToFrame(rectInContents);
IntRect rectInRootFrame = convertToContainingWindow(rectInFrame);
return m_frame->host()->visualViewport().rootFrameToViewport(rectInRootFrame);
}
IntPoint FrameView::contentsToViewport(const IntPoint& pointInContents) const
{
IntPoint pointInFrame = contentsToFrame(pointInContents);
IntPoint pointInRootFrame = convertToContainingWindow(pointInFrame);
return m_frame->host()->visualViewport().rootFrameToViewport(pointInRootFrame);
}
IntRect FrameView::contentsToScreen(const IntRect& rect) const
{
HostWindow* window = hostWindow();
if (!window)
return IntRect();
return window->viewportToScreen(contentsToViewport(rect));
}
IntRect FrameView::soonToBeRemovedContentsToUnscaledViewport(const IntRect& rectInContents) const
{
IntRect rectInFrame = contentsToFrame(rectInContents);
IntRect rectInRootFrame = convertToContainingWindow(rectInFrame);
return enclosingIntRect(m_frame->host()->visualViewport().mainViewToViewportCSSPixels(rectInRootFrame));
}
IntPoint FrameView::soonToBeRemovedUnscaledViewportToContents(const IntPoint& pointInViewport) const
{
IntPoint pointInRootFrame = flooredIntPoint(m_frame->host()->visualViewport().viewportCSSPixelsToRootFrame(pointInViewport));
IntPoint pointInThisFrame = convertFromContainingWindow(pointInRootFrame);
return frameToContents(pointInThisFrame);
}
bool FrameView::containsScrollbarsAvoidingResizer() const
{
return !m_scrollbarsAvoidingResizer;
}
void FrameView::adjustScrollbarsAvoidingResizerCount(int overlapDelta)
{
int oldCount = m_scrollbarsAvoidingResizer;
m_scrollbarsAvoidingResizer += overlapDelta;
if (parent()) {
toFrameView(parent())->adjustScrollbarsAvoidingResizerCount(overlapDelta);
} else if (!scrollbarsSuppressed()) {
// If we went from n to 0 or from 0 to n and we're the outermost view,
// we need to invalidate the windowResizerRect(), since it will now need to paint
// differently.
if ((oldCount > 0 && m_scrollbarsAvoidingResizer == 0)
|| (oldCount == 0 && m_scrollbarsAvoidingResizer > 0))
invalidateRect(windowResizerRect());
}
}
void FrameView::setScrollbarsSuppressed(bool suppressed, bool repaintOnUnsuppress)
{
if (suppressed == m_scrollbarsSuppressed)
return;
m_scrollbarsSuppressed = suppressed;
if (repaintOnUnsuppress && !suppressed) {
if (m_horizontalScrollbar)
m_horizontalScrollbar->invalidate();
if (m_verticalScrollbar)
m_verticalScrollbar->invalidate();
// Invalidate the scroll corner too on unsuppress.
invalidateScrollCorner(scrollCornerRect());
}
}
Scrollbar* FrameView::scrollbarAtRootFramePoint(const IntPoint& pointInRootFrame)
{
IntPoint pointInFrame = convertFromContainingWindow(pointInRootFrame);
return scrollbarAtFramePoint(pointInFrame);
}
Scrollbar* FrameView::scrollbarAtFramePoint(const IntPoint& pointInFrame)
{
if (m_horizontalScrollbar && m_horizontalScrollbar->shouldParticipateInHitTesting() && m_horizontalScrollbar->frameRect().contains(pointInFrame))
return m_horizontalScrollbar.get();
if (m_verticalScrollbar && m_verticalScrollbar->shouldParticipateInHitTesting() && m_verticalScrollbar->frameRect().contains(pointInFrame))
return m_verticalScrollbar.get();
return nullptr;
}
static void positionScrollbarLayer(GraphicsLayer* graphicsLayer, Scrollbar* scrollbar)
{
if (!graphicsLayer || !scrollbar)
return;
IntRect scrollbarRect = scrollbar->frameRect();
graphicsLayer->setPosition(scrollbarRect.location());
if (scrollbarRect.size() == graphicsLayer->size())
return;
graphicsLayer->setSize(scrollbarRect.size());
if (graphicsLayer->hasContentsLayer()) {
graphicsLayer->setContentsRect(IntRect(0, 0, scrollbarRect.width(), scrollbarRect.height()));
return;
}
graphicsLayer->setDrawsContent(true);
graphicsLayer->setNeedsDisplay();
}
static void positionScrollCornerLayer(GraphicsLayer* graphicsLayer, const IntRect& cornerRect)
{
if (!graphicsLayer)
return;
graphicsLayer->setDrawsContent(!cornerRect.isEmpty());
graphicsLayer->setPosition(cornerRect.location());
if (cornerRect.size() != graphicsLayer->size())
graphicsLayer->setNeedsDisplay();
graphicsLayer->setSize(cornerRect.size());
}
void FrameView::positionScrollbarLayers()
{
positionScrollbarLayer(layerForHorizontalScrollbar(), horizontalScrollbar());
positionScrollbarLayer(layerForVerticalScrollbar(), verticalScrollbar());
positionScrollCornerLayer(layerForScrollCorner(), scrollCornerRect());
}
bool FrameView::userInputScrollable(ScrollbarOrientation orientation) const
{
Document* document = frame().document();
Element* fullscreenElement = Fullscreen::fullscreenElementFrom(*document);
if (fullscreenElement && fullscreenElement != document->documentElement())
return false;
if (frame().settings() && frame().settings()->rootLayerScrolls())
return false;
ScrollbarMode mode = (orientation == HorizontalScrollbar) ?
m_horizontalScrollbarMode : m_verticalScrollbarMode;
return mode == ScrollbarAuto || mode == ScrollbarAlwaysOn;
}
bool FrameView::shouldPlaceVerticalScrollbarOnLeft() const
{
return false;
}
LayoutRect FrameView::scrollIntoView(const LayoutRect& rectInContent, const ScrollAlignment& alignX, const ScrollAlignment& alignY, ScrollType scrollType)
{
LayoutRect viewRect(visibleContentRect());
LayoutRect exposeRect = ScrollAlignment::getRectToExpose(viewRect, rectInContent, alignX, alignY);
double xOffset = exposeRect.x();
double yOffset = exposeRect.y();
setScrollPosition(DoublePoint(xOffset, yOffset), scrollType);
// Scrolling the FrameView cannot change the input rect's location relative to the document.
return rectInContent;
}
IntRect FrameView::scrollCornerRect() const
{
IntRect cornerRect;
if (hasOverlayScrollbars())
return cornerRect;
if (m_horizontalScrollbar && width() - m_horizontalScrollbar->width() > 0) {
cornerRect.unite(IntRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : m_horizontalScrollbar->width(),
height() - m_horizontalScrollbar->height(),
width() - m_horizontalScrollbar->width(),
m_horizontalScrollbar->height()));
}
if (m_verticalScrollbar && height() - m_verticalScrollbar->height() > 0) {
cornerRect.unite(IntRect(shouldPlaceVerticalScrollbarOnLeft() ? 0 : (width() - m_verticalScrollbar->width()),
m_verticalScrollbar->height(),
m_verticalScrollbar->width(),
height() - m_verticalScrollbar->height()));
}
return cornerRect;
}
bool FrameView::isScrollCornerVisible() const
{
return !scrollCornerRect().isEmpty();
}
void FrameView::invalidateScrollCornerRect(const IntRect& rect)
{
invalidateRect(rect);
if (m_scrollCorner)
layoutView()->invalidateDisplayItemClientForNonCompositingDescendantsOf(*m_scrollCorner);
}
ScrollBehavior FrameView::scrollBehaviorStyle() const
{
Element* scrollElement = m_frame->document()->scrollingElement();
LayoutObject* layoutObject = scrollElement ? scrollElement->layoutObject() : nullptr;
if (layoutObject && layoutObject->style()->scrollBehavior() == ScrollBehaviorSmooth)
return ScrollBehaviorSmooth;
return ScrollBehaviorInstant;
}
void FrameView::paint(GraphicsContext* context, const IntRect& rect) const
{
paint(context, GlobalPaintNormalPhase, rect);
}
void FrameView::paint(GraphicsContext* context, const GlobalPaintFlags globalPaintFlags, const IntRect& rect) const
{
// TODO(skyostil): Remove this early-out in favor of painting cached scrollbars.
if (shouldThrottleRendering())
return;
FramePainter(*this).paint(context, globalPaintFlags, rect);
}
void FrameView::paintContents(GraphicsContext* context, const GlobalPaintFlags globalPaintFlags, const IntRect& damageRect) const
{
if (shouldThrottleRendering())
return;
FramePainter(*this).paintContents(context, globalPaintFlags, damageRect);
}
bool FrameView::isPointInScrollbarCorner(const IntPoint& windowPoint)
{
if (!scrollbarCornerPresent())
return false;
IntPoint framePoint = convertFromContainingWindow(windowPoint);
if (m_horizontalScrollbar) {
int horizontalScrollbarYMin = m_horizontalScrollbar->frameRect().y();
int horizontalScrollbarYMax = m_horizontalScrollbar->frameRect().y() + m_horizontalScrollbar->frameRect().height();
int horizontalScrollbarXMin = m_horizontalScrollbar->frameRect().x() + m_horizontalScrollbar->frameRect().width();
return framePoint.y() > horizontalScrollbarYMin && framePoint.y() < horizontalScrollbarYMax && framePoint.x() > horizontalScrollbarXMin;
}
int verticalScrollbarXMin = m_verticalScrollbar->frameRect().x();
int verticalScrollbarXMax = m_verticalScrollbar->frameRect().x() + m_verticalScrollbar->frameRect().width();
int verticalScrollbarYMin = m_verticalScrollbar->frameRect().y() + m_verticalScrollbar->frameRect().height();
return framePoint.x() > verticalScrollbarXMin && framePoint.x() < verticalScrollbarXMax && framePoint.y() > verticalScrollbarYMin;
}
bool FrameView::scrollbarCornerPresent() const
{
return (m_horizontalScrollbar && width() - m_horizontalScrollbar->width() > 0)
|| (m_verticalScrollbar && height() - m_verticalScrollbar->height() > 0);
}
IntRect FrameView::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& localRect) const
{
// Scrollbars won't be transformed within us
IntRect newRect = localRect;
newRect.moveBy(scrollbar->location());
return newRect;
}
IntRect FrameView::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
{
IntRect newRect = parentRect;
// Scrollbars won't be transformed within us
newRect.moveBy(-scrollbar->location());
return newRect;
}
// FIXME: test these on windows
IntPoint FrameView::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& localPoint) const
{
// Scrollbars won't be transformed within us
IntPoint newPoint = localPoint;
newPoint.moveBy(scrollbar->location());
return newPoint;
}
IntPoint FrameView::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
{
IntPoint newPoint = parentPoint;
// Scrollbars won't be transformed within us
newPoint.moveBy(-scrollbar->location());
return newPoint;
}
void FrameView::setParentVisible(bool visible)
{
if (isParentVisible() == visible)
return;
Widget::setParentVisible(visible);
if (!isSelfVisible())
return;
for (const auto& child : m_children)
child->setParentVisible(visible);
}
void FrameView::show()
{
if (!isSelfVisible()) {
setSelfVisible(true);
updateScrollableAreaSet();
if (isParentVisible()) {
for (const auto& child : m_children)
child->setParentVisible(true);
}
}
Widget::show();
}
void FrameView::hide()
{
if (isSelfVisible()) {
if (isParentVisible()) {
for (const auto& child : m_children)
child->setParentVisible(false);
}
setSelfVisible(false);
updateScrollableAreaSet();
}
Widget::hide();
}
void FrameView::setScrollOrigin(const IntPoint& origin, bool updatePositionAtAll, bool updatePositionSynchronously)
{
if (scrollOrigin() == origin)
return;
ScrollableArea::setScrollOrigin(origin);
// Update if the scroll origin changes, since our position will be different if the content size did not change.
if (updatePositionAtAll && updatePositionSynchronously)
updateScrollbars(scrollOffsetDouble());
}
int FrameView::viewportWidth() const
{
int viewportWidth = layoutSize(IncludeScrollbars).width();
return adjustForAbsoluteZoom(viewportWidth, layoutView());
}
ScrollableArea* FrameView::scrollableArea()
{
if (m_viewportScrollableArea)
return m_viewportScrollableArea.get();
return layoutViewportScrollableArea();
}
ScrollableArea* FrameView::layoutViewportScrollableArea()
{
Settings* settings = frame().settings();
if (!settings || !settings->rootLayerScrolls())
return this;
LayoutView* layoutView = this->layoutView();
return layoutView ? layoutView->scrollableArea() : nullptr;
}
LayoutObject* FrameView::viewportLayoutObject()
{
if (Document* document = frame().document()) {
if (Element* element = document->viewportDefiningElement())
return element->layoutObject();
}
return nullptr;
}
void FrameView::collectAnnotatedRegions(LayoutObject& layoutObject, Vector<AnnotatedRegionValue>& regions) const
{
// LayoutTexts don't have their own style, they just use their parent's style,
// so we don't want to include them.
if (layoutObject.isText())
return;
layoutObject.addAnnotatedRegions(regions);
for (LayoutObject* curr = layoutObject.slowFirstChild(); curr; curr = curr->nextSibling())
collectAnnotatedRegions(*curr, regions);
}
void FrameView::collectFrameTimingRequestsRecursive(GraphicsLayerFrameTimingRequests& graphicsLayerTimingRequests)
{
if (!m_frameTimingRequestsDirty)
return;
collectFrameTimingRequests(graphicsLayerTimingRequests);
for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
if (!child->isLocalFrame())
continue;
toLocalFrame(child)->view()->collectFrameTimingRequestsRecursive(graphicsLayerTimingRequests);
}
m_frameTimingRequestsDirty = false;
}
void FrameView::collectFrameTimingRequests(GraphicsLayerFrameTimingRequests& graphicsLayerTimingRequests)
{
if (!m_frame->isLocalFrame())
return;
Frame* frame = m_frame.get();
LocalFrame* localFrame = toLocalFrame(frame);
LayoutRect viewRect = localFrame->contentLayoutObject()->viewRect();
const LayoutBoxModelObject* paintInvalidationContainer = localFrame->contentLayoutObject()->containerForPaintInvalidation();
// If the frame is being throttled, its compositing state may not be up to date.
if (!paintInvalidationContainer->enclosingLayer()->isAllowedToQueryCompositingState())
return;
const GraphicsLayer* graphicsLayer = paintInvalidationContainer->enclosingLayer()->graphicsLayerBacking();
if (!graphicsLayer)
return;
PaintLayer::mapRectToPaintInvalidationBacking(localFrame->contentLayoutObject(), paintInvalidationContainer, viewRect);
graphicsLayerTimingRequests.add(graphicsLayer, Vector<std::pair<int64_t, WebRect>>()).storedValue->value.append(std::make_pair(m_frame->frameID(), enclosingIntRect(viewRect)));
}
void FrameView::setNeedsUpdateViewportIntersection()
{
m_needsUpdateViewportIntersection = true;
for (FrameView* parent = parentFrameView(); parent; parent = parent->parentFrameView())
parent->m_needsUpdateViewportIntersectionInSubtree = true;
}
void FrameView::updateViewportIntersectionIfNeeded()
{
// TODO(skyostil): Replace this with a real intersection observer.
if (!m_needsUpdateViewportIntersection)
return;
m_needsUpdateViewportIntersection = false;
m_viewportIntersectionValid = true;
FrameView* parent = parentFrameView();
if (!parent) {
m_viewportIntersection = frameRect();
return;
}
ASSERT(!parent->m_needsUpdateViewportIntersection);
// If our parent is hidden, then we are too.
if (parent->m_viewportIntersection.isEmpty()) {
m_viewportIntersection = parent->m_viewportIntersection;
return;
}
// Transform our bounds into the root frame's content coordinate space,
// making sure we have valid layout data in our parent document. If our
// parent is throttled, we'll use possible stale layout information and
// rely on the fact that another lifecycle update will be scheduled once
// our parent becomes unthrottled.
ASSERT(parent->lifecycle().state() >= DocumentLifecycle::LayoutClean || parent->shouldThrottleRendering());
m_viewportIntersection = parent->contentsToRootFrame(frameRect());
// TODO(skyostil): Expand the viewport to make it less likely to see stale content while scrolling.
IntRect viewport = parent->m_viewportIntersection;
m_viewportIntersection.intersect(viewport);
}
void FrameView::updateViewportIntersectionsForSubtree()
{
bool hadValidIntersection = m_viewportIntersectionValid;
bool hadEmptyIntersection = m_viewportIntersection.isEmpty();
updateViewportIntersectionIfNeeded();
bool shouldNotify = !hadValidIntersection || hadEmptyIntersection != m_viewportIntersection.isEmpty();
if (shouldNotify && !m_intersectionObserverNotificationFactory->isPending())
m_frame->frameScheduler()->timerTaskRunner()->postTask(BLINK_FROM_HERE, m_intersectionObserverNotificationFactory->cancelAndCreate());
if (!m_needsUpdateViewportIntersectionInSubtree)
return;
m_needsUpdateViewportIntersectionInSubtree = false;
for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
if (!child->isLocalFrame())
continue;
if (FrameView* view = toLocalFrame(child)->view())
view->updateViewportIntersectionsForSubtree();
}
}
void FrameView::notifyIntersectionObservers()
{
TRACE_EVENT0("blink", "FrameView::notifyIntersectionObservers");
ASSERT(!isInPerformLayout());
ASSERT(!m_frame->document()->inStyleRecalc());
bool wasThrottled = canThrottleRendering();
// Only offscreen frames can be throttled.
m_hiddenForThrottling = m_viewportIntersectionValid && m_viewportIntersection.isEmpty();
// We only throttle the rendering pipeline in cross-origin frames. This is
// to avoid a situation where an ancestor frame directly depends on the
// pipeline timing of a descendant and breaks as a result of throttling.
// The rationale is that cross-origin frames must already communicate with
// asynchronous messages, so they should be able to tolerate some delay in
// receiving replies from a throttled peer.
//
// Check if we can access our parent's security origin.
m_crossOriginForThrottling = false;
const SecurityOrigin* origin = frame().securityContext()->securityOrigin();
for (Frame* parentFrame = m_frame->tree().parent(); parentFrame; parentFrame = parentFrame->tree().parent()) {
const SecurityOrigin* parentOrigin = parentFrame->securityContext()->securityOrigin();
if (!origin->canAccess(parentOrigin)) {
m_crossOriginForThrottling = true;
break;
}
}
bool becameUnthrottled = wasThrottled && !canThrottleRendering();
if (becameUnthrottled)
page()->animator().scheduleVisualUpdate(m_frame.get());
}
bool FrameView::shouldThrottleRendering() const
{
return canThrottleRendering() && lifecycle().throttlingAllowed();
}
bool FrameView::canThrottleRendering() const
{
if (!RuntimeEnabledFeatures::renderingPipelineThrottlingEnabled())
return false;
return m_hiddenForThrottling && m_crossOriginForThrottling;
}
} // namespace blink
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
35d610807ccd79fa26105c58758f0a1d6c4d3c54 | 285fbc356602efb18868ad246563febdad741ddd | /lab1/src/invoice.cpp | 82190fa3621738700f67912dd665193875a12f01 | [] | no_license | ivansst/citb200 | b506e37c1d0c74d3bdd7205cb91eda228d024df1 | f2db9c2d5a3bafbccb7263e0d1bbf5e61d6e396b | refs/heads/master | 2020-05-05T10:06:56.465886 | 2019-04-07T09:50:12 | 2019-04-07T09:50:12 | 179,931,138 | 0 | 0 | null | 2019-04-07T07:22:11 | 2019-04-07T07:22:11 | null | UTF-8 | C++ | false | false | 318 | cpp | #include "invoice.h"
void Invoice::add(Product product, int quantity){
Item item(product, quantity);
this->items.push_back(item);
}
vector <Product>Invoice::getProduct(){
vector<Product> products;
for(auto item : items){
products.push_back(item.getProduct());
}
return products;
} | [
"ivan.sstoyanov@abv.bg"
] | ivan.sstoyanov@abv.bg |
93231030e60dc3003e8509b9376b2a2a73132fd0 | a3a7d5a213527237f649b1cd0e4052789fca6db3 | /BOJ/BOJ_5430_AC.cpp | 9d2479d42bd16b21983c9062f6ba7994e4adb88f | [] | no_license | yuchanleeme/Problem_Solving | 5d84cda878a674783d9b270f7cf17f73f552156a | b68960103702bbbbdcd156a1d13596acdb021dc2 | refs/heads/master | 2021-11-15T04:53:20.053863 | 2021-10-23T16:46:05 | 2021-10-23T16:46:05 | 185,592,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,330 | cpp | #include <iostream>
#include <deque>
#include <cstring>
using namespace std;
//https://www.acmicpc.net/problem/5430
/*
<AC>
주요: 덱 STL의 기능들을 활용한다.
1. strtok 기능을 이용해 입력값을 분해한다.
2. 덱의 성질(양방향 큐)을 이용해 R 입력을 받았을때 시작점을 맨앞/맨뒤로 설정한다.
3. D를 입력 받았을 때 reverse의 값에 따라 pop을 한다. (덱 비었는데 D 입력받으면 error_trigger True)
4. 위 상황에 맞게 출력한다.
=======
* 입/출력이 까다로운 문제
* strtok 기능을 이용한다.
* 배열크기 할당을 잘해준다. (런타임 에러의 원인)
* \b는 출력할때는 사용하지 않는다. (커서 위치만 옮겨지는 것)
*/
int main() {
int T, n, idx;
char p[100010], born_data[500010];
bool reverse, error_trigger; // true 일때 정방향, false일때 역방향
scanf("%d", &T); // T값 저장
for (int t = 0; t < T; t++) {
scanf("%s", &p); // 함수 저장
scanf("%d", &n); // 배열 개수 저장
scanf("%s", &born_data); // 입력 저장
idx = 0;
deque<int> dq;
reverse = true;
error_trigger = false;
// 1번
char *tok = strtok(born_data,"[,]");
while (tok != NULL) {
dq.push_back(atoi(tok));
tok = strtok(NULL,"[,]");
}
for (int i = 0; i < 100001; i++) {
// 2,3번
if(p[i] == 'R'){
reverse = !reverse;
}
else if(p[i] == 'D'){
if (dq.empty()) {
error_trigger = true;
break;
}
if (reverse) {
dq.pop_front();
}
else{
dq.pop_back();
}
}
else{
break;
}
}
if (error_trigger) {
printf("error\n");
}
else if(dq.size() == 0){
printf("[]\n");
}
else{
if (reverse) {
printf("[");
for (int p = 0; p < dq.size(); p++) {
if (p == dq.size()-1) {
printf( "%d]\n",dq.at(p));
break;
}
else{ printf("%d,",dq.at(p));}
}
}
else{
printf("[");
for (int p = dq.size(); p > 0; p--) {
if (p == 1) {
printf("%d]\n",dq.at(p - 1));
break;
}
printf("%d,",dq.at(p - 1));
}
}
}
}
return 0;
}
| [
"yuchanlee.me@gmail.com"
] | yuchanlee.me@gmail.com |
4e81ca0682ec3c32a1e6d9c6753195da942323fa | 6a7ae2330c1e60d6e6e2c6236685f5b8fb953a05 | /XenonFramework2/XenonFramework2/XeCore/Photon/XenonCoreFrameBuffer.h | 613a3ced864719d1a3f2a7527e249a5fc5083391 | [] | no_license | PsichiX/XenonCore2 | f4a8bb74640c488f535a637583941f1a675bae52 | a875c255033ae4f0540e6316fb09711acd44e852 | refs/heads/master | 2020-12-24T16:50:18.511387 | 2013-09-29T12:44:28 | 2013-09-29T12:44:28 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,860 | h | /*
Name: XenoN Core 2
Version: 2.0.0.0 Frozen Eye
Update: 2011-06-04
Copyright: Copyright © 2007-2011 XenoN Core by PsichiX. All rights reserved.
Author: PsichiX
Website: http://www.xenon.psichix.com
Description: XenoN Core 4D World Engine
*/
/*
== EN ==
This file is part of Xenon Core Engine.
You may distribute it further, but you can not modify it.
Please do not use in modified form.
The principles of XenoN Core License available in the file LICENSE_CORE_EN.TXT or visit: http://www.xenon.psichix.com.
== PL ==
Ten plik jest czescia XenoN Core Engine.
Mozesz go rozpowszechniac dalej, jednak nie mozesz go modyfikowac.
Nalezy uzytkowac w nie zmodyfikowanej formie.
Nalezy przestrzegac zasad Licencji XenoN Core dostepnej w pliku LICENSE_CORE_PL.TXT oraz na stronie: http://www.xenon.psichix.com.
*/
#ifndef _XENON_CORE_FRAMEBUFFER_H_
#define _XENON_CORE_FRAMEBUFFER_H_
#include "../XenonCore2.h"
#ifdef XE_COMPILE_PHOTON
#include "../XePhoton.h"
//! \namespace XeCore Przestrzen nazw XenoN Core
namespace XeCore
{
//! \namespace XeCore::Photon Przestrzen nazw modulu Photon
namespace Photon
{
/*--- XenoN Core FrameBuffer ---*/
class XenonCoreFrameBuffer
{
#ifdef XE_COMPILE_EXPORT
public:
#else
private:
#endif /* XE_COMPILE_EXPORT */
XeElmTexture texture;
XeElmTexture textureDepth;
unsigned int hbuffer;
int Width;
int Height;
#ifdef XE_COMPILE_EXPORT
XenonCoreFrameBuffer();
bool Create(int width,int height,XeEstate type);
//bool CreateFromTexture(XeElmTexture tex,XeElmTexture texDepth);
void Destroy();
void Activate();
void Unactivate();
void ActivateTexture();
void UnactivateTexture();
void ActivateTextureDepth();
void UnactivateTextureDepth();
//bool SwapTexture(XeElmTexture tex);
#endif /* XE_COMPILE_EXPORT */
};
} // Photon
} // XeCore
#endif // XE_COMPILE_PHOTON
#endif // _XENON_CORE_FRAMEBUFFER_H_
| [
"pbudzynski@ganymede.eu"
] | pbudzynski@ganymede.eu |
ce53ab194fab6ecfade27c7131e6b1c9013c8b87 | 28fa0efd16cb126f86a04164c93e715ad95da44d | /repartiendoPaquetes/repartiendoPaquetes/repartiendoPaquetes.cpp | 5397ebd0bd496bb23dcbd07bf5f25764fa0d3582 | [] | no_license | pamart24/MARP_2021 | b4004efb8a260dcc738883852038cb1582a1950e | 09997f23de49514953cb7319d020ef545d6f3c88 | refs/heads/main | 2023-06-05T08:20:02.961399 | 2021-06-27T17:38:10 | 2021-06-27T17:38:10 | 380,794,764 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,901 | cpp | #include <iostream>
#include <fstream>
#include "DigrafoValorado.h"
#include "IndexPQ.h"
using namespace std;
class Reparto {
public:
Reparto(DigrafoValorado<int> const& g, int origen) : origen_(origen),
dist(g.V(), INF), numCaminos(g.V(), 0), ulti(g.V()), pq(g.V()) {
dist[origen_] = 0;
numCaminos[origen_] = 1;
pq.push(origen_, 0);
while (!pq.empty()) {
int v = pq.top().elem;
pq.pop();
for (auto a : g.ady(v)) {
relajar(a);
}
}
}
bool hayCamino(int destino) {
if (dist[destino] == INF) return false;
else return true;
}
int costeHacia(int destino) { //Esfuerzo de ir desde el origen al destino
return dist[destino];
}
//int costeVuelta(DigrafoValorado<int> const& g, int casa) { //Casa representa el punto de partida para volver a la oficina
// vector<int> distVuelta(g.V(), INF);
//}
private:
const int INF = 2147483647;
int origen_;
vector<int> dist;
vector<int> numCaminos;
vector<AristaDirigida<int>> ulti;
IndexPQ<int> pq;
void relajar(AristaDirigida<int> a) {
int v = a.desde();
int w = a.hasta();
if (dist[w] > dist[v] + a.valor()) { //Tenemos un nuevo camino minimo
dist[w] = dist[v] + a.valor();
numCaminos[w] = numCaminos[v];
ulti[w] = a;
pq.update(w, dist[w]);
}
}
};
// resuelve un caso de prueba, leyendo de la entrada la
// configuración, y escribiendo la respuesta
bool resuelveCaso() {
int N;
cin >> N;
if (!std::cin) // fin de la entrada
return false;
DigrafoValorado<int> comarca(N);
int C;
cin >> C;
for (int i = 0; i < C; ++i) {
int origen, destino, esfuerzo;
cin >> origen >> destino >> esfuerzo;
origen--;
destino--;
comarca.ponArista(AristaDirigida<int>(origen, destino, esfuerzo));
}
bool posible = true;
int O, P;
cin >> O >> P;
O--;
Reparto repartoIda(comarca, O);
int esfuerzoMinimo = 0;
int j = 0;
while (posible && j < P) {
int destinatario;
cin >> destinatario;
destinatario--;
if (!repartoIda.hayCamino(destinatario))
posible = false;
else {
esfuerzoMinimo += repartoIda.costeHacia(destinatario); //Esfuerzo para ir
Reparto repartoVuelta(comarca, destinatario);
if (!repartoVuelta.hayCamino(O))
posible = false;
else {
esfuerzoMinimo += repartoVuelta.costeHacia(O); //Esfuerzo para volver
}
}
++j;
}
if (posible) cout << esfuerzoMinimo << "\n";
else cout << "Imposible\n";
return true;
}
int main() {
while (resuelveCaso());
return 0;
}
| [
"pamart24@ucm.es"
] | pamart24@ucm.es |
bbfce0a870f1e66370e437b6c7c7a066d47ab279 | 0d666be1446398c359aa4a8ed5c2adaebc1da4a1 | /OverlordProject/PostProcessingBluePulse.cpp | af0ecb222b68fc3f6407f990c45a6a21d68e3dc9 | [] | no_license | AliyevRufat/GhostOfFuji | 76aa88f5b43b12c02ddc397da538f17d2c1a4f13 | a445749b5b94baa9a82df6b2b2befc01457986e9 | refs/heads/master | 2023-08-19T09:10:32.904068 | 2021-10-08T15:24:43 | 2021-10-08T15:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,489 | cpp | #include "stdafx.h"
#include "PostProcessingBluePulse.h"
#include "RenderTarget.h"
ID3DX11EffectScalarVariable* PostProcessingBluePulse::m_pElapsedTime = nullptr;
PostProcessingBluePulse::PostProcessingBluePulse()
: PostProcessingMaterial(L"Resources/Effects/Post/BluePulse.fx", 1),
m_pTextureMapVariabele(nullptr),
m_ElapsedTime{ 0 }
{
}
void PostProcessingBluePulse::LoadEffectVariables()
{
//TODO: Bind the 'gTexture' variable with 'm_pTextureMapVariable'
//Check if valid!
if (!m_pTextureMapVariabele)
{
m_pTextureMapVariabele = GetEffect()->GetVariableByName("gTexture")->AsShaderResource();
if (!m_pTextureMapVariabele->IsValid())
{
Logger::LogWarning(L"PostInvert::LoadEffectVariables() > \'m_pTextureMapVariabele\' variable not found!");
m_pTextureMapVariabele = nullptr;
}
}
if (!m_pElapsedTime)
{
m_pElapsedTime = GetEffect()->GetVariableByName("gElapsedTime")->AsScalar();
if (!m_pElapsedTime->IsValid())
{
Logger::LogWarning(L"UberMaterial::LoadEffectVariables() > \'gElapsedTime\' variable not found!");
m_pElapsedTime = nullptr;
}
}
}
void PostProcessingBluePulse::UpdateEffectVariables(RenderTarget* pRendertarget)
{
UNREFERENCED_PARAMETER(pRendertarget);
//TODO: Update the TextureMapVariable with the Color ShaderResourceView of the given RenderTarget
if (pRendertarget && m_pTextureMapVariabele)
{
m_pTextureMapVariabele->SetResource(pRendertarget->GetShaderResourceView());
}
m_pElapsedTime->SetFloat(m_ElapsedTime);
} | [
"76409612+AliyevRufat@users.noreply.github.com"
] | 76409612+AliyevRufat@users.noreply.github.com |
668fa8d2a291df9b5ed4201fff498133c136385c | 0412add6cf24d7874738b2151c000763046a1acf | /1-4/mori/main.cpp | 08213287ddaa852224ce416a9bdd9ec16e4acf3e | [] | no_license | atupii/cpp-exercise | 01aa1659c3cc147f1f9795df391dfeaea0844cb7 | 027f4c2e093b703cfbd316c89f867de9c19d35fc | refs/heads/master | 2021-01-21T07:53:48.567074 | 2013-11-22T04:17:51 | 2013-11-22T04:17:55 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 666 | cpp | #include <iostream>
#include <string.h>
using namespace std;
void rev_str(char* s1);
void rev_str(char* s1, char* s2);
int main(void){
char s1[80], s2[80];
strcpy_s(s1, "hello");
rev_str(s1, s2);
rev_str(s1);
return 0;
}
void rev_str(char* s1){
cout << "入力:" << s1 << endl;
int l = strlen(s1);
char tmp;
for (int i = 0; i < l / 2; i++){
tmp = s1[i];
s1[i] = s1[l - i - 1];
s1[l - i - 1] = tmp;
}
cout << "出力:" << s1 << endl;
}
void rev_str(char* s1, char* s2){
int l = strlen(s1);
for (int i = 0; i < l; i++){
s2[l - i - 1] = s1[i];
}
s2[l] = '\0';
cout << "入力:" << s1 << endl;
cout << "出力:" << s2 << endl;
} | [
"matsuda@m.cs.osakafu-u.ac.jp"
] | matsuda@m.cs.osakafu-u.ac.jp |
175cd86245ceecce35654132a0d0e5d15d59627c | 43ebc2797b2cc3ae384e77d9d766c25e6def8a55 | /parser.h | 7472310663405e5c70fbd764f759606436f364ba | [] | no_license | tstaerk/Spider | cb283690fb03f918cb1701270fa472fab5134d41 | 1edcf5e67ad643d048b53187f49bc874cb0d7844 | refs/heads/master | 2020-06-02T09:54:51.128298 | 2010-07-22T21:17:27 | 2010-07-22T21:17:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 984 | h | /*
parser.h - demonstration of a parser in C++
*/
#ifndef PARSER_H
#define PARSER_H
#include <qstring.h>
#include <QtXml/QXmlDefaultHandler>
#include <QtXml/QXmlAttributes>
class Parsert : public QXmlDefaultHandler
{
public:
Parsert();
/** given by the framework from qxml. Called when parsing the xml-document starts. */
bool startDocument();
void setDocumentLocator(QXmlLocator*);
int lineNumber();
/** given by the framework from qxml. Called when the reader occurs an open tag (e.g. \<b\> ) */
bool startElement( const QString&, const QString&, const QString& qName, const QXmlAttributes& att );
bool endElement( const QString&, const QString&, const QString& qName );
bool characters(const QString& ch);
QString href(int i);
QXmlLocator* loc;
int bodystartx; // where the html body starts
int bodystarty; // where the html body starts
int getbodystarty();
int getbodystartx();
int hrefcount();
QList<QString> hrefs;
};
#endif
| [
"dev@staerk.de"
] | dev@staerk.de |
c4952e09c133bd451dadc380d2e63fbda8560992 | b84b2089bdb2a9fa7200628a604ac9bec62042b4 | /booking.cpp | 5bdc4ff4668fce431ed57af8767fc5586af159d1 | [] | no_license | sidrusiya/CP-AlgorithmsSol | 76de7022bf7a00f0193e0fd55fd7ebc250551e01 | 57e89811abf533a86c3da14836519d74f289fc80 | refs/heads/master | 2023-02-24T03:46:46.561341 | 2021-01-29T15:30:30 | 2021-01-29T15:30:30 | 259,416,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | #include<iostream>
using namespace std;
#include<vector>
bool hotel(vector<int> &A,vector<int> &D,int k){
return true;
}
int max(int A){
int p=0;
for(int i=1;5*i<=A;i++){
if(i%5==0)p+=1;
p+=1;
}
return p;
}
int main(){
vector<int> A={1,3,6};
vector<int> D={2,5,9};
int k=1;
cout<<hotel(A,D,k)<<endl;
cout<<max(10);
}
| [
"noreply@github.com"
] | sidrusiya.noreply@github.com |
70c64ba48f17d03fcd0bc61a6095db2dd5d33fc8 | 405d989f9ca3e3c8942934a36c92eeffdbfcf1b4 | /soundex/spellcheck.cpp | 5c3bc963321fe98df38808a50f3801196b57a02d | [] | no_license | flavorlessfunk/cs361 | 10294bbf23f75d268488c4764c6141e9286df851 | a6768fb5d18d7a85baac64ba6ac2e80aa90b589c | refs/heads/master | 2021-01-20T08:54:25.562473 | 2017-05-03T23:09:01 | 2017-05-03T23:09:26 | 89,802,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,433 | cpp | // Spellcheck program
#include <fstream>
#include "wordoccurrence.h"
#include "correction.h"
#include "replacement.h"
#include "cs361set.h"
#include <vector>
#include "vectorUtils.h"
#include "replchoices.h"
typedef CS361Set<std::string> WordSet;
typedef CS361Set<Replacement> ReplacementSet;
typedef std::vector<WordOccurrence> WordOccurrenceOrderedSequence;
typedef std::vector<Correction> CorrectionOrderedSequence;
std::string promptForAction (const WordOccurrence& misspelled);
std::string get_replacement_spelling(const std::string& word,
const WordSet& dictionary,
const ReplacementChooser& chooser);
std::string getSaveFileName();
using namespace std;
#ifdef GRADING
string saveFileName;
#endif
void readDictionary (const string& dictionaryFileName,
WordSet& dictionary);
void collectMisspelledWords (const string& targetFileName,
const WordSet& dictionary,
WordOccurrenceOrderedSequence& misspellings);
void promptUserForCorrections
(const string& targetFileName,
const WordSet& dictionary,
const WordOccurrenceOrderedSequence& misspellings,
const ReplacementChooser& chooser,
CorrectionOrderedSequence& corrections);
void produceCorrectedDocument(const string& targetFileName,
/*const*/CorrectionOrderedSequence& corrections,
const string& correctedFileName);
int main (int argc, char** argv)
{
#ifndef GRADING
if (argc != 3) {
cerr << "Usage: " << argv[0]
<< " dictionaryFileName documentFileName"
<< endl;
return 1;
}
#else
if (argc != 4) {
cerr << "Usage: " << argv[0]
<< " dictionaryFileName documentFileName saveFileName"
<< endl;
return 1;
}
saveFileName = argv[3];
#endif
string dictionaryFileName = argv[1];
string targetFileName = argv[2];
// main spellcheck routine
WordSet dictionary;
readDictionary (dictionaryFileName, dictionary);
ReplacementChooser replacementChooser(dictionary);
WordOccurrenceOrderedSequence misspellings;
collectMisspelledWords (targetFileName, dictionary, misspellings);
CorrectionOrderedSequence corrections;
promptUserForCorrections(targetFileName, dictionary,
misspellings, replacementChooser,
corrections);
#ifndef GRADING
if (!corrections.empty())
#endif
{
string correctedFileName = getSaveFileName();
if (correctedFileName[0] != ' ')
produceCorrectedDocument(targetFileName, corrections,
correctedFileName);
}
return 0;
}
void readDictionary (const string& dictionaryFileName,
WordSet& dictionary)
{
ifstream dictin (dictionaryFileName.c_str());
string word;
while (dictin >> word)
{
dictionary.add (word);
}
}
void collectMisspelledWords (const string& targetFileName,
const WordSet& dictionary,
WordOccurrenceOrderedSequence& misspellings)
{
ifstream targetFile (targetFileName.c_str());
cout << "Checking " << targetFileName << endl;
WordOccurrence w;
while (w.read(targetFile))
{
if (!dictionary.contains(w.getLexeme()))
{
addInOrder (misspellings, w);
}
}
cout << misspellings.size() << " possible misspellings found." << endl;
}
void display_in_context (const WordOccurrence& occur, istream& inFile)
{
static const WordOccurrence::Location ContextSize = 20;
WordOccurrence::Location start = (occur.getLocation() >= ContextSize) ?
occur.getLocation() - ContextSize : (WordOccurrence::Location)0;
WordOccurrence::Location stop = occur.getLocation() + ContextSize
+ (WordOccurrence::Location)occur.getLexeme().length();
string beforeMisspelling;
string afterMisspelling;
inFile.seekg(start);
for (; start < occur.getLocation(); start+=1)
beforeMisspelling += (char)inFile.get();
start = occur.getLocation() + (WordOccurrence::Location)occur.getLexeme().length();
inFile.seekg(start);
for (; start < stop; start+=1)
afterMisspelling += (char)inFile.get();
// If there is a line break (\c or \n) more than 2 chars from
// this misspelling, terminate the context there.
auto loc = beforeMisspelling.substr(0, beforeMisspelling.length()-2)
.find_last_of("\r\n");
if (loc != string::npos) {
beforeMisspelling = beforeMisspelling.substr(loc+1);
}
loc = afterMisspelling.find_first_of("\r\n", 2);
if (loc != string::npos) {
afterMisspelling = afterMisspelling.substr(0, loc-1);
}
cout << beforeMisspelling << "\n "
<< occur.getLexeme() << "\n"
<< afterMisspelling << endl;
}
void promptUserForCorrections
(const string& targetFileName,
const WordSet& dictionary,
const WordOccurrenceOrderedSequence& misspellings,
const ReplacementChooser& chooser,
CorrectionOrderedSequence& corrections)
{
// assume misspellings are in order of occurrence within the
// target file (if not, sort them)
ifstream targetFile (targetFileName.c_str());
WordSet globalIgnoredSet;
ReplacementSet globalReplacementSet;
for (WordOccurrenceOrderedSequence::const_iterator m = misspellings.begin();
m != misspellings.end(); ++m)
{
WordOccurrence misspelling = *m;
string mword = misspelling.getLexeme();
//WordOccurrence::Location mloc = misspelling.getLocation();
if (!globalIgnoredSet.contains(mword))
{
Replacement grepl;
ReplacementSet::iterator repl =
globalReplacementSet.find(Replacement(mword,""));
if (repl != globalReplacementSet.end())
{
addInOrder(corrections,Correction(misspelling,
(*repl).getReplacement()));
}
else
{
display_in_context(misspelling, targetFile);
string response = promptForAction(misspelling);
if (response == "ignore")
{
// do nothing
}
else if (response == "ignore every time")
{
globalIgnoredSet.add(mword);
}
else if (response == "replace")
{
string r = get_replacement_spelling(mword, dictionary,
chooser);
addInOrder (corrections, Correction(misspelling, r));
}
else if (response == "replace every time")
{
string r = get_replacement_spelling(mword, dictionary,
chooser);
addInOrder (corrections, Correction(misspelling, r));
globalReplacementSet.add (Replacement(mword, r));
}
else if (response == "quit")
{
break;
}
}
}
}
}
void produceCorrectedDocument(const string& targetFileName,
/*const*/CorrectionOrderedSequence& corrections,
const string& correctedFileName)
{
cout << "Corrected document saving to " << correctedFileName << endl;
// assume corrections are in order of occurrence within the
// target file (if not, sort them)
ifstream targetFile (targetFileName.c_str());
ofstream correctedFile (correctedFileName.c_str());
for (CorrectionOrderedSequence::iterator c = corrections.begin();
c != corrections.end(); ++c)
{
// copy into the correctedFile all characters from
// current location of the targetFile up to
// the location of c;
for (long offset = (*c).getMisspelling().getLocation()
- targetFile.tellg();
offset > 0; --offset) {
correctedFile.put ((char)targetFile.get());
}
// read and discard the misspelled word from the targetFile;
WordOccurrence misspelled;
misspelled.read(targetFile);
// write the corrected spelling from c into the correctedFile;
correctedFile << (*c).getReplacement();
}
// copy any remaining characters from the targetFile into the
// correctedFile;
char ch = targetFile.get();
while ((targetFile) && (ch >= 0))
{
correctedFile.put(ch);
ch = targetFile.get();
}
cout << "Corrected document saved in " << correctedFileName << endl;
}
/***************************
Interactive routines for the spellcheck program
When compiled with GRADING flag set, these are replaced by
noninteractive code for auto-testing purposes.
****************************/
string promptForAction (const WordOccurrence& misspelled)
{
#ifndef GRADING
cout << "\n" << misspelled.getLexeme() << ":\n"
<< " (r)eplace this word, just this once\n"
<< " (R)eplace this word every time\n"
<< " (i)gnore this word, just this once\n"
<< " (I)gnore this word every time\n"
<< " (Q)uit\n"
<< ">" << flush;
char response;
while (1)
{
cin >> response;
switch (response) {
case 'r': return "replace";
case 'R': return "replace every time";
case 'i': return "ignore";
case 'I': return "ignore every time";
case 'Q': return "quit";
}
if (response > ' ')
cout << "Please respond with one of: rRiIQ\n>" << flush;
}
#else
return "replace every time";
#endif
}
string get_replacement_spelling(const string& word,
const WordSet& dictionary,
const ReplacementChooser& chooser)
{
cout << "\n" << word << ":" << endl;
// Get a list of potential replacement strings
// (not yet implemented)
vector<string> replacements = chooser.getPlausibleReplacements(word);
int nReplacements = replacements.size();
int replacementChoice = -1;
if (nReplacements > 0)
{
cout << "Choose a corrected spelling:\n";
for (int i = 0; i < nReplacements; ++i)
cout << i+1 << ' ' << replacements[i] << "\n";
cout << "0 None of the above";
#ifndef GRADING
while (replacementChoice < 0 || replacementChoice > nReplacements)
{
cout << "\n Enter your choice: " << flush;
cin >> replacementChoice;
}
#endif
}
#ifndef GRADING
if (replacementChoice > 0)
return replacements[replacementChoice-1];
else
{
// Prompt user directly for corrected spelling
string corrected;
getline(cin, corrected);
while (corrected == "")
{
cout << "\nEnter correct spelling: " << flush;
getline(cin, corrected);
}
return corrected;
}
#else
string repl = "[" + word + "=>";
for (int k = 0; k < nReplacements; ++k)
{
repl += replacements[k];
repl += '|';
}
repl += ']';
return repl;
#endif
}
string getSaveFileName()
{
#ifndef GRADING
string fileName;
cout << "Enter name of file to contain the corrected document, or blank\n"
<< "to discard all corrections:\n"
<< "> " << flush;
while (fileName == "")
{
getline(cin, fileName);
}
return fileName;
#else
return saveFileName;
#endif
}
| [
"flavorlessfunk@gmail.com"
] | flavorlessfunk@gmail.com |
17d47d7a1ecf43b6f5fdf5e9042541e0f5720efa | b81d83148470223d1a9716d694d1507254ab7183 | /os/fstools.cpp | 6fe46d7a53f5211cb803885630fb23299f6fdc44 | [
"MIT"
] | permissive | vheinitz/cl2 | 724860096cd526f8bd3ca338cba6c3999113a44d | d66b9ce8248126575984f1ade3e56bd01b2926fa | refs/heads/master | 2021-01-19T00:54:45.579851 | 2019-10-21T03:41:19 | 2019-10-21T03:41:19 | 33,274,465 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,521 | cpp | #include "fstools.h"
#include <QIODevice>
#include <QTextStream>
#include <QFile>
#include <QMessageBox>
#include <QDir>
#include <QFileInfoList>
QString FSTools::readAll( QString fn)
{
QFile f(fn);
if(!f.open(QIODevice::ReadOnly))
return QString::null;
return f.readAll();
}
QStringList FSTools::fromFile( QString fn)
{
QStringList ret;
QFile f(fn);
f.open(QIODevice::ReadOnly);
QTextStream ts(&f);
while (!ts.atEnd())
{
ret.append(ts.readLine());
}
return ret;
}
bool FSTools::toFile( QStringList sl, QString fn)
{
QFile f(fn);
if (!f.open(QIODevice::WriteOnly))
return false;
QTextStream ts(&f);
foreach (QString s, sl)
{
ts << s <<"\n";
}
return true;
}
bool FSTools::touch( QString fn)
{
QFile f(fn);
if (!f.open(QIODevice::WriteOnly))
return false;
return true;
}
bool FSTools::toCsv( QList<double> l, QString fn, QChar sep)
{
QFile f(fn);
if (!f.open(QIODevice::WriteOnly))
return false;
QTextStream ts(&f);
foreach (double e, l)
{
ts << e << sep;
}
ts << "\n";
return true;
}
QMap<QString, QString> FSTools::mapFromFile( QString fn, QRegExp sep)
{
QMap<QString, QString> ret;
QFile f(fn);
f.open(QIODevice::ReadOnly);
QTextStream ts(&f);
while (!ts.atEnd())
{
QString line = ts.readLine();
QString k = line.section(sep,0,0).trimmed();
if (k.isEmpty())
{
continue;
}
QString v = line.section(sep,1);
ret[k] = v;
}
return ret;
}
QMap<QString, QString> FSTools::mapFromText( QString data, QRegExp sepkey, QRegExp sepline)
{
QMap<QString, QString> ret;
QStringList lines = data.split( sepline );
foreach ( QString line, lines)
{
QString k = line.section(sepkey,0,0).trimmed();
if (k.isEmpty())
{
continue;
}
QString v = line.section(sepkey,1);
ret[k] = v;
}
return ret;
}
bool FSTools::mapToFile( QMap<QString, QString> m, QString fn, QString sep)
{
QFile f(fn);
if (!f.open(QIODevice::WriteOnly))
return false;
QTextStream ts(&f);
foreach (QString mk, m.keys())
{
ts << mk<<sep<<m[mk]<<"\n";
}
return true;
}
bool FSTools::freeSpaceCheck()
{
QString wlOutputDrive = "C";//_wlXml.section(":",0,0);
bool ok=0;
wlOutputDrive+=":";
long freeSpace = FSTools::getFreeSpaceInMB( wlOutputDrive , &ok);
if ( !ok || (freeSpace < 1000) )
{
int but= QMessageBox::warning( 0, "Warning", "Left space on hard drive for storing images may be insufficient",QMessageBox::Ok | QMessageBox::Abort );
if ( but == QMessageBox::Abort )
{
//PD_LOG("Aborted by user on insufficient disc space warning")
return false;
}
}
return true;
}
bool FSTools::removeDir(const QString &dirName)
{
QDir dir(dirName);
if (dir.exists(dirName))
{
QFileInfoList fil = dir.entryInfoList(
(
QDir::NoDotAndDotDot |
QDir::Files |
QDir::System |
QDir::Hidden |
QDir::AllDirs
),
QDir::DirsFirst
);
foreach(QFileInfo fi, fil ) {
if (fi.isDir()) {
if ( !removeDir(fi.absoluteFilePath()) )
return false;
}
else {
if ( !QFile::remove(fi.absoluteFilePath()) )
return false;
}
}
return dir.rmdir(dirName);
}
return false;
}
| [
"vheinitz@googlemail.com"
] | vheinitz@googlemail.com |
82c92ad363545f425e86eebf2351e0d245c9a63d | d4039b212a1b99993ee7ee7a38723d1c81fdf335 | /endofgame.cpp | b60cf8361d7c919e29a94f6cccd31915b084e3e1 | [] | no_license | evster-coder/mafia-project | 2682a081f39e3ac49b86f128db917551209e0372 | 76f8a5a68b6e634ac985f2569a167d3fdfa7bf48 | refs/heads/master | 2020-06-15T14:54:26.376291 | 2019-07-05T02:32:40 | 2019-07-05T02:32:40 | 195,326,052 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 324 | cpp | #include "endofgame.h"
#include "gamefield.h"
EndOfGame::EndOfGame(){
}
EndOfGame::~EndOfGame(){}
QVector<QString> EndOfGame::doWork(){
return *GameField::GetInstance()->endOfGame();
}
void EndOfGame::nextStage(GameStep *&ukazatel){
GameStep *tmp = ukazatel;
delete tmp;
ukazatel = nullptr;
}
| [
"noreply@github.com"
] | evster-coder.noreply@github.com |
21b30cb007187537f8a161ba0699fd39bfc863cb | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium/chrome/browser/download/download_util.cc | c8b88c2500f27fe22a0b3d0ceaad2d21927c2790 | [
"MIT",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 33,096 | cc | // Copyright (c) 2011 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.
//
// Download utility implementation
#include "chrome/browser/download/download_util.h"
#if defined(OS_WIN)
#include <shobjidl.h>
#endif
#include <string>
#include "base/file_util.h"
#include "base/i18n/rtl.h"
#include "base/i18n/time_formatting.h"
#include "base/lazy_instance.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/sys_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "base/value_conversions.h"
#include "base/values.h"
#include "base/win/windows_version.h"
#include "chrome/browser/download/download_extensions.h"
#include "chrome/browser/download/download_item.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/download/download_types.h"
#include "chrome/browser/extensions/crx_installer.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/history/download_create_info.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/time_format.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "net/base/net_util.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkShader.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas_skia.h"
#include "ui/gfx/image.h"
#include "ui/gfx/rect.h"
#if defined(TOOLKIT_VIEWS)
#include "ui/base/dragdrop/os_exchange_data.h"
#include "views/drag_utils.h"
#endif
#if defined(TOOLKIT_USES_GTK)
#if defined(TOOLKIT_VIEWS)
#include "ui/base/dragdrop/drag_drop_types.h"
#include "views/widget/widget_gtk.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/ui/gtk/custom_drag.h"
#endif // defined(TOOLKIT_GTK)
#endif // defined(TOOLKIT_USES_GTK)
#if defined(OS_WIN)
#include "base/win/scoped_comptr.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "ui/base/dragdrop/drag_source.h"
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#endif
// TODO(phajdan.jr): Find some standard location for this, maintaining
// the same value on all platforms.
static const double PI = 3.141592653589793;
namespace download_util {
// How many times to cycle the complete animation. This should be an odd number
// so that the animation ends faded out.
static const int kCompleteAnimationCycles = 5;
// The maximum number of 'uniquified' files we will try to create.
// This is used when the filename we're trying to download is already in use,
// so we create a new unique filename by appending " (nnn)" before the
// extension, where 1 <= nnn <= kMaxUniqueFiles.
// Also used by code that cleans up said files.
static const int kMaxUniqueFiles = 100;
namespace {
#if defined(OS_WIN)
// Returns whether the specified extension is automatically integrated into the
// windows shell.
bool IsShellIntegratedExtension(const string16& extension) {
string16 extension_lower = StringToLowerASCII(extension);
static const wchar_t* const integrated_extensions[] = {
// See <http://msdn.microsoft.com/en-us/library/ms811694.aspx>.
L"local",
// Right-clicking on shortcuts can be magical.
L"lnk",
};
for (int i = 0; i < arraysize(integrated_extensions); ++i) {
if (extension_lower == integrated_extensions[i])
return true;
}
// See <http://www.juniper.net/security/auto/vulnerabilities/vuln2612.html>.
// That vulnerability report is not exactly on point, but files become magical
// if their end in a CLSID. Here we block extensions that look like CLSIDs.
if (!extension_lower.empty() && extension_lower[0] == L'{' &&
extension_lower[extension_lower.length() - 1] == L'}')
return true;
return false;
}
// Returns whether the specified file name is a reserved name on windows.
// This includes names like "com2.zip" (which correspond to devices) and
// desktop.ini and thumbs.db which have special meaning to the windows shell.
bool IsReservedName(const string16& filename) {
// This list is taken from the MSDN article "Naming a file"
// http://msdn2.microsoft.com/en-us/library/aa365247(VS.85).aspx
// I also added clock$ because GetSaveFileName seems to consider it as a
// reserved name too.
static const wchar_t* const known_devices[] = {
L"con", L"prn", L"aux", L"nul", L"com1", L"com2", L"com3", L"com4", L"com5",
L"com6", L"com7", L"com8", L"com9", L"lpt1", L"lpt2", L"lpt3", L"lpt4",
L"lpt5", L"lpt6", L"lpt7", L"lpt8", L"lpt9", L"clock$"
};
string16 filename_lower = StringToLowerASCII(filename);
for (int i = 0; i < arraysize(known_devices); ++i) {
// Exact match.
if (filename_lower == known_devices[i])
return true;
// Starts with "DEVICE.".
if (filename_lower.find(string16(known_devices[i]) + L".") == 0)
return true;
}
static const wchar_t* const magic_names[] = {
// These file names are used by the "Customize folder" feature of the shell.
L"desktop.ini",
L"thumbs.db",
};
for (int i = 0; i < arraysize(magic_names); ++i) {
if (filename_lower == magic_names[i])
return true;
}
return false;
}
#endif // OS_WIN
} // namespace
// Download temporary file creation --------------------------------------------
class DefaultDownloadDirectory {
public:
const FilePath& path() const { return path_; }
private:
DefaultDownloadDirectory() {
if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &path_)) {
NOTREACHED();
}
if (DownloadPathIsDangerous(path_)) {
if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS_SAFE, &path_)) {
NOTREACHED();
}
}
}
friend struct base::DefaultLazyInstanceTraits<DefaultDownloadDirectory>;
FilePath path_;
};
static base::LazyInstance<DefaultDownloadDirectory>
g_default_download_directory(base::LINKER_INITIALIZED);
const FilePath& GetDefaultDownloadDirectory() {
return g_default_download_directory.Get().path();
}
bool CreateTemporaryFileForDownload(FilePath* temp_file) {
if (file_util::CreateTemporaryFileInDir(GetDefaultDownloadDirectory(),
temp_file))
return true;
return file_util::CreateTemporaryFile(temp_file);
}
bool DownloadPathIsDangerous(const FilePath& download_path) {
FilePath desktop_dir;
if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
NOTREACHED();
return false;
}
return (download_path == desktop_dir);
}
void GenerateExtension(const FilePath& file_name,
const std::string& mime_type,
FilePath::StringType* generated_extension) {
// We're worried about two things here:
//
// 1) Usability. If the site fails to provide a file extension, we want to
// guess a reasonable file extension based on the content type.
//
// 2) Shell integration. Some file extensions automatically integrate with
// the shell. We block these extensions to prevent a malicious web site
// from integrating with the user's shell.
// See if our file name already contains an extension.
FilePath::StringType extension = file_name.Extension();
if (!extension.empty())
extension.erase(extension.begin()); // Erase preceding '.'.
#if defined(OS_WIN)
static const FilePath::CharType default_extension[] =
FILE_PATH_LITERAL("download");
// Rename shell-integrated extensions.
if (IsShellIntegratedExtension(extension))
extension.assign(default_extension);
#endif
if (extension.empty()) {
// The GetPreferredExtensionForMimeType call will end up going to disk. Do
// this on another thread to avoid slowing the IO thread.
// http://crbug.com/61827
base::ThreadRestrictions::ScopedAllowIO allow_io;
net::GetPreferredExtensionForMimeType(mime_type, &extension);
}
generated_extension->swap(extension);
}
void GenerateFileNameFromInfo(DownloadCreateInfo* info,
FilePath* generated_name) {
GenerateFileName(GURL(info->url()),
info->content_disposition,
info->referrer_charset,
info->mime_type,
generated_name);
}
void GenerateFileName(const GURL& url,
const std::string& content_disposition,
const std::string& referrer_charset,
const std::string& mime_type,
FilePath* generated_name) {
string16 default_file_name(
l10n_util::GetStringUTF16(IDS_DEFAULT_DOWNLOAD_FILENAME));
string16 new_name = net::GetSuggestedFilename(GURL(url),
content_disposition,
referrer_charset,
default_file_name);
// TODO(evan): this code is totally wrong -- we should just generate
// Unicode filenames and do all this encoding switching at the end.
// However, I'm just shuffling wrong code around, at least not adding
// to it.
#if defined(OS_WIN)
*generated_name = FilePath(new_name);
#else
*generated_name = FilePath(
base::SysWideToNativeMB(UTF16ToWide(new_name)));
#endif
DCHECK(!generated_name->empty());
GenerateSafeFileName(mime_type, generated_name);
}
void GenerateSafeFileName(const std::string& mime_type, FilePath* file_name) {
// Make sure we get the right file extension
FilePath::StringType extension;
GenerateExtension(*file_name, mime_type, &extension);
*file_name = file_name->ReplaceExtension(extension);
#if defined(OS_WIN)
// Prepend "_" to the file name if it's a reserved name
FilePath::StringType leaf_name = file_name->BaseName().value();
DCHECK(!leaf_name.empty());
if (IsReservedName(leaf_name)) {
leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
*file_name = file_name->DirName();
if (file_name->value() == FilePath::kCurrentDirectory) {
*file_name = FilePath(leaf_name);
} else {
*file_name = file_name->Append(leaf_name);
}
}
#endif
}
void OpenChromeExtension(Profile* profile,
DownloadManager* download_manager,
const DownloadItem& download_item) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(download_item.is_extension_install());
ExtensionService* service = profile->GetExtensionService();
CHECK(service);
NotificationService* nservice = NotificationService::current();
GURL nonconst_download_url = download_item.url();
nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
Source<DownloadManager>(download_manager),
Details<GURL>(&nonconst_download_url));
scoped_refptr<CrxInstaller> installer(
new CrxInstaller(service, new ExtensionInstallUI(profile)));
installer->set_delete_source(true);
if (UserScript::IsURLUserScript(download_item.url(),
download_item.mime_type())) {
installer->InstallUserScript(download_item.full_path(),
download_item.url());
return;
}
bool is_gallery_download = service->IsDownloadFromGallery(
download_item.url(), download_item.referrer_url());
installer->set_original_mime_type(download_item.original_mime_type());
installer->set_apps_require_extension_mime_type(true);
installer->set_original_url(download_item.url());
installer->set_is_gallery_install(is_gallery_download);
installer->InstallCrx(download_item.full_path());
installer->set_allow_silent_install(is_gallery_download);
}
void RecordDownloadCount(DownloadCountTypes type) {
UMA_HISTOGRAM_ENUMERATION(
"Download.Counts", type, DOWNLOAD_COUNT_TYPES_LAST_ENTRY);
}
// Download progress painting --------------------------------------------------
// Common bitmaps used for download progress animations. We load them once the
// first time we do a progress paint, then reuse them as they are always the
// same.
SkBitmap* g_foreground_16 = NULL;
SkBitmap* g_background_16 = NULL;
SkBitmap* g_foreground_32 = NULL;
SkBitmap* g_background_32 = NULL;
void PaintDownloadProgress(gfx::Canvas* canvas,
#if defined(TOOLKIT_VIEWS)
views::View* containing_view,
#endif
int origin_x,
int origin_y,
int start_angle,
int percent_done,
PaintDownloadProgressSize size) {
// Load up our common bitmaps
if (!g_background_16) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
g_background_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_16);
g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
g_background_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_32);
}
SkBitmap* background = (size == BIG) ? g_background_32 : g_background_16;
SkBitmap* foreground = (size == BIG) ? g_foreground_32 : g_foreground_16;
const int kProgressIconSize = (size == BIG) ? kBigProgressIconSize :
kSmallProgressIconSize;
// We start by storing the bounds of the background and foreground bitmaps
// so that it is easy to mirror the bounds if the UI layout is RTL.
gfx::Rect background_bounds(origin_x, origin_y,
background->width(), background->height());
gfx::Rect foreground_bounds(origin_x, origin_y,
foreground->width(), foreground->height());
#if defined(TOOLKIT_VIEWS)
// Mirror the positions if necessary.
int mirrored_x = containing_view->GetMirroredXForRect(background_bounds);
background_bounds.set_x(mirrored_x);
mirrored_x = containing_view->GetMirroredXForRect(foreground_bounds);
foreground_bounds.set_x(mirrored_x);
#endif
// Draw the background progress image.
SkPaint background_paint;
canvas->DrawBitmapInt(*background,
background_bounds.x(),
background_bounds.y(),
background_paint);
// Layer the foreground progress image in an arc proportional to the download
// progress. The arc grows clockwise, starting in the midnight position, as
// the download progresses. However, if the download does not have known total
// size (the server didn't give us one), then we just spin an arc around until
// we're done.
float sweep_angle = 0.0;
float start_pos = static_cast<float>(kStartAngleDegrees);
if (percent_done < 0) {
sweep_angle = kUnknownAngleDegrees;
start_pos = static_cast<float>(start_angle);
} else if (percent_done > 0) {
sweep_angle = static_cast<float>(kMaxDegrees / 100.0 * percent_done);
}
// Set up an arc clipping region for the foreground image. Don't bother using
// a clipping region if it would round to 360 (really 0) degrees, since that
// would eliminate the foreground completely and be quite confusing (it would
// look like 0% complete when it should be almost 100%).
SkPaint foreground_paint;
if (sweep_angle < static_cast<float>(kMaxDegrees - 1)) {
SkRect oval;
oval.set(SkIntToScalar(foreground_bounds.x()),
SkIntToScalar(foreground_bounds.y()),
SkIntToScalar(foreground_bounds.x() + kProgressIconSize),
SkIntToScalar(foreground_bounds.y() + kProgressIconSize));
SkPath path;
path.arcTo(oval,
SkFloatToScalar(start_pos),
SkFloatToScalar(sweep_angle), false);
path.lineTo(SkIntToScalar(foreground_bounds.x() + kProgressIconSize / 2),
SkIntToScalar(foreground_bounds.y() + kProgressIconSize / 2));
SkShader* shader =
SkShader::CreateBitmapShader(*foreground,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode);
SkMatrix shader_scale;
shader_scale.setTranslate(SkIntToScalar(foreground_bounds.x()),
SkIntToScalar(foreground_bounds.y()));
shader->setLocalMatrix(shader_scale);
foreground_paint.setShader(shader);
foreground_paint.setAntiAlias(true);
shader->unref();
canvas->AsCanvasSkia()->drawPath(path, foreground_paint);
return;
}
canvas->DrawBitmapInt(*foreground,
foreground_bounds.x(),
foreground_bounds.y(),
foreground_paint);
}
void PaintDownloadComplete(gfx::Canvas* canvas,
#if defined(TOOLKIT_VIEWS)
views::View* containing_view,
#endif
int origin_x,
int origin_y,
double animation_progress,
PaintDownloadProgressSize size) {
// Load up our common bitmaps.
if (!g_foreground_16) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
}
SkBitmap* complete = (size == BIG) ? g_foreground_32 : g_foreground_16;
gfx::Rect complete_bounds(origin_x, origin_y,
complete->width(), complete->height());
#if defined(TOOLKIT_VIEWS)
// Mirror the positions if necessary.
complete_bounds.set_x(containing_view->GetMirroredXForRect(complete_bounds));
#endif
// Start at full opacity, then loop back and forth five times before ending
// at zero opacity.
double opacity = sin(animation_progress * PI * kCompleteAnimationCycles +
PI/2) / 2 + 0.5;
canvas->SaveLayerAlpha(static_cast<int>(255.0 * opacity), complete_bounds);
canvas->AsCanvasSkia()->drawARGB(0, 255, 255, 255, SkXfermode::kClear_Mode);
canvas->DrawBitmapInt(*complete, complete_bounds.x(), complete_bounds.y());
canvas->Restore();
}
void PaintDownloadInterrupted(gfx::Canvas* canvas,
#if defined(TOOLKIT_VIEWS)
views::View* containing_view,
#endif
int origin_x,
int origin_y,
double animation_progress,
PaintDownloadProgressSize size) {
// Load up our common bitmaps.
if (!g_foreground_16) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
}
SkBitmap* complete = (size == BIG) ? g_foreground_32 : g_foreground_16;
gfx::Rect complete_bounds(origin_x, origin_y,
complete->width(), complete->height());
#if defined(TOOLKIT_VIEWS)
// Mirror the positions if necessary.
complete_bounds.set_x(containing_view->GetMirroredXForRect(complete_bounds));
#endif
// Start at zero opacity, then loop back and forth five times before ending
// at full opacity.
double opacity = sin(
(1.0 - animation_progress) * PI * kCompleteAnimationCycles + PI/2) / 2 +
0.5;
canvas->SaveLayerAlpha(static_cast<int>(255.0 * opacity), complete_bounds);
canvas->AsCanvasSkia()->drawARGB(0, 255, 255, 255, SkXfermode::kClear_Mode);
canvas->DrawBitmapInt(*complete, complete_bounds.x(), complete_bounds.y());
canvas->Restore();
}
// Load a language dependent height so that the dangerous download confirmation
// message doesn't overlap with the download link label.
int GetBigProgressIconSize() {
static int big_progress_icon_size = 0;
if (big_progress_icon_size == 0) {
string16 locale_size_str =
l10n_util::GetStringUTF16(IDS_DOWNLOAD_BIG_PROGRESS_SIZE);
bool rc = base::StringToInt(locale_size_str, &big_progress_icon_size);
if (!rc || big_progress_icon_size < kBigProgressIconSize) {
NOTREACHED();
big_progress_icon_size = kBigProgressIconSize;
}
}
return big_progress_icon_size;
}
int GetBigProgressIconOffset() {
return (GetBigProgressIconSize() - kBigIconSize) / 2;
}
#if defined(TOOLKIT_VIEWS)
// Download dragging
void DragDownload(const DownloadItem* download,
gfx::Image* icon,
gfx::NativeView view) {
DCHECK(download);
// Set up our OLE machinery
ui::OSExchangeData data;
if (icon) {
drag_utils::CreateDragImageForFile(
download->GetFileNameToReportUser(), *icon, &data);
}
const FilePath full_path = download->full_path();
data.SetFilename(full_path);
std::string mime_type = download->mime_type();
if (mime_type.empty())
net::GetMimeTypeFromFile(full_path, &mime_type);
// Add URL so that we can load supported files when dragged to TabContents.
if (net::IsSupportedMimeType(mime_type)) {
data.SetURL(net::FilePathToFileURL(full_path),
download->GetFileNameToReportUser().LossyDisplayName());
}
#if defined(OS_WIN)
scoped_refptr<ui::DragSource> drag_source(new ui::DragSource);
// Run the drag and drop loop
DWORD effects;
DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data),
drag_source.get(), DROPEFFECT_COPY | DROPEFFECT_LINK, &effects);
#elif defined(TOOLKIT_USES_GTK)
GtkWidget* root = gtk_widget_get_toplevel(view);
if (!root)
return;
views::WidgetGtk* widget = static_cast<views::WidgetGtk*>(
views::NativeWidget::GetNativeWidgetForNativeView(root));
if (!widget)
return;
widget->DoDrag(data,
ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK);
#endif // OS_WIN
}
#elif defined(USE_X11)
void DragDownload(const DownloadItem* download,
gfx::Image* icon,
gfx::NativeView view) {
DownloadItemDrag::BeginDrag(download, icon);
}
#endif // USE_X11
DictionaryValue* CreateDownloadItemValue(DownloadItem* download, int id) {
DictionaryValue* file_value = new DictionaryValue();
file_value->SetInteger("started",
static_cast<int>(download->start_time().ToTimeT()));
file_value->SetString("since_string",
TimeFormat::RelativeDate(download->start_time(), NULL));
file_value->SetString("date_string",
base::TimeFormatShortDate(download->start_time()));
file_value->SetInteger("id", id);
file_value->Set("file_path",
base::CreateFilePathValue(download->GetTargetFilePath()));
// Keep file names as LTR.
string16 file_name = download->GetFileNameToReportUser().LossyDisplayName();
file_name = base::i18n::GetDisplayStringInLTRDirectionality(file_name);
file_value->SetString("file_name", file_name);
file_value->SetString("url", download->url().spec());
file_value->SetBoolean("otr", download->is_otr());
if (download->IsInProgress()) {
if (download->safety_state() == DownloadItem::DANGEROUS) {
file_value->SetString("state", "DANGEROUS");
DCHECK(download->danger_type() == DownloadItem::DANGEROUS_FILE ||
download->danger_type() == DownloadItem::DANGEROUS_URL);
const char* danger_type_value =
download->danger_type() == DownloadItem::DANGEROUS_FILE ?
"DANGEROUS_FILE" : "DANGEROUS_URL";
file_value->SetString("danger_type", danger_type_value);
} else if (download->is_paused()) {
file_value->SetString("state", "PAUSED");
} else {
file_value->SetString("state", "IN_PROGRESS");
}
file_value->SetString("progress_status_text",
GetProgressStatusText(download));
file_value->SetInteger("percent",
static_cast<int>(download->PercentComplete()));
file_value->SetInteger("received",
static_cast<int>(download->received_bytes()));
} else if (download->IsInterrupted()) {
file_value->SetString("state", "INTERRUPTED");
file_value->SetString("progress_status_text",
GetProgressStatusText(download));
file_value->SetInteger("percent",
static_cast<int>(download->PercentComplete()));
file_value->SetInteger("received",
static_cast<int>(download->received_bytes()));
} else if (download->IsCancelled()) {
file_value->SetString("state", "CANCELLED");
} else if (download->IsComplete()) {
if (download->safety_state() == DownloadItem::DANGEROUS) {
file_value->SetString("state", "DANGEROUS");
} else {
file_value->SetString("state", "COMPLETE");
}
}
file_value->SetInteger("total",
static_cast<int>(download->total_bytes()));
return file_value;
}
string16 GetProgressStatusText(DownloadItem* download) {
int64 total = download->total_bytes();
int64 size = download->received_bytes();
DataUnits amount_units = GetByteDisplayUnits(size);
string16 received_size = FormatBytes(size, amount_units, true);
string16 amount = received_size;
// Adjust both strings for the locale direction since we don't yet know which
// string we'll end up using for constructing the final progress string.
base::i18n::AdjustStringForLocaleDirection(&amount);
if (total) {
amount_units = GetByteDisplayUnits(total);
string16 total_text = FormatBytes(total, amount_units, true);
base::i18n::AdjustStringForLocaleDirection(&total_text);
base::i18n::AdjustStringForLocaleDirection(&received_size);
amount = l10n_util::GetStringFUTF16(IDS_DOWNLOAD_TAB_PROGRESS_SIZE,
received_size,
total_text);
} else {
amount.assign(received_size);
}
int64 current_speed = download->CurrentSpeed();
amount_units = GetByteDisplayUnits(current_speed);
string16 speed_text = FormatSpeed(current_speed, amount_units, true);
base::i18n::AdjustStringForLocaleDirection(&speed_text);
base::TimeDelta remaining;
string16 time_remaining;
if (download->is_paused())
time_remaining = l10n_util::GetStringUTF16(IDS_DOWNLOAD_PROGRESS_PAUSED);
else if (download->TimeRemaining(&remaining))
time_remaining = TimeFormat::TimeRemaining(remaining);
if (time_remaining.empty()) {
base::i18n::AdjustStringForLocaleDirection(&amount);
return l10n_util::GetStringFUTF16(
IDS_DOWNLOAD_TAB_PROGRESS_STATUS_TIME_UNKNOWN, speed_text, amount);
}
return l10n_util::GetStringFUTF16(IDS_DOWNLOAD_TAB_PROGRESS_STATUS,
speed_text, amount, time_remaining);
}
#if !defined(OS_MACOSX)
void UpdateAppIconDownloadProgress(int download_count,
bool progress_known,
float progress) {
#if defined(OS_WIN)
// Taskbar progress bar is only supported on Win7.
if (base::win::GetVersion() < base::win::VERSION_WIN7)
return;
base::win::ScopedComPtr<ITaskbarList3> taskbar;
HRESULT result = taskbar.CreateInstance(CLSID_TaskbarList, NULL,
CLSCTX_INPROC_SERVER);
if (FAILED(result)) {
VLOG(1) << "Failed creating a TaskbarList object: " << result;
return;
}
result = taskbar->HrInit();
if (FAILED(result)) {
LOG(ERROR) << "Failed initializing an ITaskbarList3 interface.";
return;
}
// Iterate through all the browser windows, and draw the progress bar.
for (BrowserList::const_iterator browser_iterator = BrowserList::begin();
browser_iterator != BrowserList::end(); browser_iterator++) {
Browser* browser = *browser_iterator;
BrowserWindow* window = browser->window();
if (!window)
continue;
HWND frame = window->GetNativeHandle();
if (download_count == 0 || progress == 1.0f)
taskbar->SetProgressState(frame, TBPF_NOPROGRESS);
else if (!progress_known)
taskbar->SetProgressState(frame, TBPF_INDETERMINATE);
else
taskbar->SetProgressValue(frame, static_cast<int>(progress * 100), 100);
}
#endif
}
#endif
// Appends the passed the number between parenthesis the path before the
// extension.
void AppendNumberToPath(FilePath* path, int number) {
*path = path->InsertBeforeExtensionASCII(StringPrintf(" (%d)", number));
}
// Attempts to find a number that can be appended to that path to make it
// unique. If |path| does not exist, 0 is returned. If it fails to find such
// a number, -1 is returned.
int GetUniquePathNumber(const FilePath& path) {
if (!file_util::PathExists(path))
return 0;
FilePath new_path;
for (int count = 1; count <= kMaxUniqueFiles; ++count) {
new_path = FilePath(path);
AppendNumberToPath(&new_path, count);
if (!file_util::PathExists(new_path))
return count;
}
return -1;
}
void DownloadUrl(
const GURL& url,
const GURL& referrer,
const std::string& referrer_charset,
const DownloadSaveInfo& save_info,
ResourceDispatcherHost* rdh,
int render_process_host_id,
int render_view_id,
net::URLRequestContextGetter* request_context_getter) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
net::URLRequestContext* context =
request_context_getter->GetURLRequestContext();
context->set_referrer_charset(referrer_charset);
rdh->BeginDownload(url,
referrer,
save_info,
true, // Show "Save as" UI.
render_process_host_id,
render_view_id,
context);
}
void CancelDownloadRequest(ResourceDispatcherHost* rdh,
int render_process_id,
int request_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// |rdh| may be NULL in unit tests.
if (rdh)
rdh->CancelRequest(render_process_id, request_id, false);
}
void NotifyDownloadInitiated(int render_process_id, int render_view_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
RenderViewHost* rvh = RenderViewHost::FromID(render_process_id,
render_view_id);
if (!rvh)
return;
NotificationService::current()->Notify(NotificationType::DOWNLOAD_INITIATED,
Source<RenderViewHost>(rvh),
NotificationService::NoDetails());
}
int GetUniquePathNumberWithCrDownload(const FilePath& path) {
if (!file_util::PathExists(path) &&
!file_util::PathExists(GetCrDownloadPath(path)))
return 0;
FilePath new_path;
for (int count = 1; count <= kMaxUniqueFiles; ++count) {
new_path = FilePath(path);
AppendNumberToPath(&new_path, count);
if (!file_util::PathExists(new_path) &&
!file_util::PathExists(GetCrDownloadPath(new_path)))
return count;
}
return -1;
}
namespace {
// NOTE: If index is 0, deletes files that do not have the " (nnn)" appended.
void DeleteUniqueDownloadFile(const FilePath& path, int index) {
FilePath new_path(path);
if (index > 0)
AppendNumberToPath(&new_path, index);
file_util::Delete(new_path, false);
}
} // namespace
void EraseUniqueDownloadFiles(const FilePath& path) {
FilePath cr_path = GetCrDownloadPath(path);
for (int index = 0; index <= kMaxUniqueFiles; ++index) {
DeleteUniqueDownloadFile(path, index);
DeleteUniqueDownloadFile(cr_path, index);
}
}
FilePath GetCrDownloadPath(const FilePath& suggested_path) {
FilePath::StringType file_name;
base::SStringPrintf(
&file_name,
PRFilePathLiteral FILE_PATH_LITERAL(".crdownload"),
suggested_path.value().c_str());
return FilePath(file_name);
}
// TODO(erikkay,phajdan.jr): This is apparently not being exercised in tests.
bool IsDangerous(DownloadCreateInfo* info, Profile* profile, bool auto_open) {
DownloadDangerLevel danger_level = GetFileDangerLevel(
info->suggested_path.BaseName());
if (danger_level == Dangerous)
return !(auto_open && info->has_user_gesture);
if (danger_level == AllowOnUserGesture && !info->has_user_gesture)
return true;
if (info->is_extension_install) {
// Extensions that are not from the gallery are considered dangerous.
ExtensionService* service = profile->GetExtensionService();
if (!service ||
!service->IsDownloadFromGallery(info->url(), info->referrer_url))
return true;
}
return false;
}
} // namespace download_util
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
384770f028c235865127b96c9c7bc192cbd2677b | e8a3c0b3722cacdb99e15693bff0a4333b7ccf16 | /Uva Oj/10550..combination lock.cpp | 6080a976b70bc7f43d412185df4cdd980f002cdf | [] | no_license | piyush1146115/Competitive-Programming | 690f57acd374892791b16a08e14a686a225f73fa | 66c975e0433f30539d826a4c2aa92970570b87bf | refs/heads/master | 2023-08-18T03:04:24.680817 | 2023-08-12T19:15:51 | 2023-08-12T19:15:51 | 211,923,913 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int in, a, b, c, angle, sum;
while(scanf("%d %d %d %d",&in, &a, &b, &c) == 4 && (in != 0 || a != 0 || b != 0 || c != 0)){
sum = 0;
if(a > in){
sum += (40 -a) + in;
}
else{
sum += (in - a);
}
if(b < a){
sum += (40 - a) + b;
}
else{
sum += (b - a);
}
if(c > b){
sum += (40 - c) + b;
}
else{
sum += (b - c);
}
angle = (sum * 9) + 1080;
printf("%d\n",angle);
}
return 0;
}
| [
"piyush123kantidas@gmail.com"
] | piyush123kantidas@gmail.com |
71c7c1b0cf5baa394f2da8a1d52f9397774d0abd | 05f7573db159e870fb26c847991c4cb8c407ed4c | /VBF/3rdParty/3rdParty_vs2010_x86/include/ifcpp/IFC4/IfcFan.h | 57696e50d93720a4b656b90e8454671cd36309b5 | [] | no_license | riyue625/OneGIS.ModelingTool | e126ef43429ce58d22c65832d96dbd113eacbf85 | daf3dc91584df7ecfed6a51130ecdf6671614ac4 | refs/heads/master | 2020-05-28T12:12:43.543730 | 2018-09-06T07:42:00 | 2018-09-06T07:42:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,396 | h | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "model/shared_ptr.h"
#include "model/IfcPPObject.h"
#include "model/IfcPPGlobal.h"
#include "IfcFlowMovingDevice.h"
class IFCPP_EXPORT IfcFanTypeEnum;
//ENTITY
class IFCPP_EXPORT IfcFan : public IfcFlowMovingDevice
{
public:
IfcFan();
IfcFan( int id );
~IfcFan();
virtual shared_ptr<IfcPPObject> getDeepCopy( IfcPPCopyOptions& options );
virtual void getStepLine( std::stringstream& stream ) const;
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
virtual void readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map );
virtual void setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self );
virtual void getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes );
virtual void getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes );
virtual void unlinkFromInverseCounterparts();
virtual const char* className() const { return "IfcFan"; }
// IfcRoot -----------------------------------------------------------
// attributes:
// shared_ptr<IfcGloballyUniqueId> m_GlobalId;
// shared_ptr<IfcOwnerHistory> m_OwnerHistory; //optional
// shared_ptr<IfcLabel> m_Name; //optional
// shared_ptr<IfcText> m_Description; //optional
// IfcObjectDefinition -----------------------------------------------------------
// inverse attributes:
// std::vector<weak_ptr<IfcRelAssigns> > m_HasAssignments_inverse;
// std::vector<weak_ptr<IfcRelNests> > m_Nests_inverse;
// std::vector<weak_ptr<IfcRelNests> > m_IsNestedBy_inverse;
// std::vector<weak_ptr<IfcRelDeclares> > m_HasContext_inverse;
// std::vector<weak_ptr<IfcRelAggregates> > m_IsDecomposedBy_inverse;
// std::vector<weak_ptr<IfcRelAggregates> > m_Decomposes_inverse;
// std::vector<weak_ptr<IfcRelAssociates> > m_HasAssociations_inverse;
// IfcObject -----------------------------------------------------------
// attributes:
// shared_ptr<IfcLabel> m_ObjectType; //optional
// inverse attributes:
// std::vector<weak_ptr<IfcRelDefinesByObject> > m_IsDeclaredBy_inverse;
// std::vector<weak_ptr<IfcRelDefinesByObject> > m_Declares_inverse;
// std::vector<weak_ptr<IfcRelDefinesByType> > m_IsTypedBy_inverse;
// std::vector<weak_ptr<IfcRelDefinesByProperties> > m_IsDefinedBy_inverse;
// IfcProduct -----------------------------------------------------------
// attributes:
// shared_ptr<IfcObjectPlacement> m_ObjectPlacement; //optional
// shared_ptr<IfcProductRepresentation> m_Representation; //optional
// inverse attributes:
// std::vector<weak_ptr<IfcRelAssignsToProduct> > m_ReferencedBy_inverse;
// IfcElement -----------------------------------------------------------
// attributes:
// shared_ptr<IfcIdentifier> m_Tag; //optional
// inverse attributes:
// std::vector<weak_ptr<IfcRelFillsElement> > m_FillsVoids_inverse;
// std::vector<weak_ptr<IfcRelConnectsElements> > m_ConnectedTo_inverse;
// std::vector<weak_ptr<IfcRelInterferesElements> > m_IsInterferedByElements_inverse;
// std::vector<weak_ptr<IfcRelInterferesElements> > m_InterferesElements_inverse;
// std::vector<weak_ptr<IfcRelProjectsElement> > m_HasProjections_inverse;
// std::vector<weak_ptr<IfcRelReferencedInSpatialStructure> > m_ReferencedInStructures_inverse;
// std::vector<weak_ptr<IfcRelVoidsElement> > m_HasOpenings_inverse;
// std::vector<weak_ptr<IfcRelConnectsWithRealizingElements> > m_IsConnectionRealization_inverse;
// std::vector<weak_ptr<IfcRelSpaceBoundary> > m_ProvidesBoundaries_inverse;
// std::vector<weak_ptr<IfcRelConnectsElements> > m_ConnectedFrom_inverse;
// std::vector<weak_ptr<IfcRelContainedInSpatialStructure> > m_ContainedInStructure_inverse;
// std::vector<weak_ptr<IfcRelCoversBldgElements> > m_HasCoverings_inverse;
// IfcDistributionElement -----------------------------------------------------------
// inverse attributes:
// std::vector<weak_ptr<IfcRelConnectsPortToElement> > m_HasPorts_inverse;
// IfcDistributionFlowElement -----------------------------------------------------------
// inverse attributes:
// std::vector<weak_ptr<IfcRelFlowControlElements> > m_HasControlElements_inverse;
// IfcFlowMovingDevice -----------------------------------------------------------
// IfcFan -----------------------------------------------------------
// attributes:
shared_ptr<IfcFanTypeEnum> m_PredefinedType; //optional
};
| [
"robertsam@126.com"
] | robertsam@126.com |
72a44cba456ed416a20017aedfd6afda16cae07d | c68dd7c0a2305e4f856d7ba52b65deb5d1a5cc63 | /distributions/univariate/discrete/BinomialRand.h | 4177d697ceff408c33b4ad6e39267ba4c4c1fadf | [
"MIT"
] | permissive | aWeinzierl/RandLib | 10fe613fa61b0d1ccf50849074f3683ae9e8497c | 7af0237d1902aadbf2451b7dfab02c52cf98ae87 | refs/heads/master | 2020-04-13T01:58:21.352337 | 2019-01-14T23:15:31 | 2019-01-14T23:15:31 | 162,889,038 | 0 | 0 | MIT | 2018-12-23T12:32:13 | 2018-12-23T12:32:12 | null | UTF-8 | C++ | false | false | 4,603 | h | #ifndef BINOMIALRAND_H
#define BINOMIALRAND_H
#include "DiscreteDistribution.h"
#include "GeometricRand.h"
#include "../continuous/BetaRand.h"
/**
* @brief The BinomialDistribution class <BR>
* Abstract class for Binomial distribution
*
* Notation: X ~ Bin(n, p)
*
* Related distributions: <BR>
* If X ~ Bin(1, p), then X ~ Bernoulli(p) <BR>
* X ~ Multin(n, 1 - p, p)
*/
class RANDLIBSHARED_EXPORT BinomialDistribution : public DiscreteDistribution
{
protected:
double p = 0.5; ///< probability of success
double q = 0.5; ///< probability of failure
double logProb = -M_LN2; ///< log(p)
double log1mProb = -M_LN2; ///< log(q)
private:
int n = 1; ///< number of experiments
double np = 0.5; ///< n * p
double lfactn = 0; ///< log(n!)
double delta1{}, delta2{};
double sigma1{}, sigma2{}, c{};
double a1{}, a2{}, a3{}, a4{};
double coefa3{}, coefa4{};
double minpq = 0.5; ///< min(p, q)
double pFloor = 0; ///< [n * min(p, q)] / n
double logPFloor = -INFINITY; ///< log(pFloor)
double logQFloor = 0; ///< log(1 - pFloor)
double pRes = 0.5; ///< min(p, q) - pFloor
double npFloor = 0; ///< [n * min(p, q)]
double nqFloor = 0; ///< [n * max(p, q)]
double logPnpInv = 0; ///< log(P([npFloor)) if p = pFloor
GeometricRand G{};
protected:
BinomialDistribution(int number, double probability);
public:
SUPPORT_TYPE SupportType() const override { return FINITE_T; }
int MinValue() const override { return 0; }
int MaxValue() const override { return n; }
private:
void SetGeneratorConstants();
protected:
void SetParameters(int number, double probability);
public:
inline int GetNumber() const { return n; }
inline double GetProbability() const { return p; }
private:
/**
* @fn logProbFloor
* @param k
* @return logarithm of probability to get k if p = pFloor
*/
double logProbFloor(int k) const;
public:
double P(const int & k) const override;
double logP(const int & k) const override;
double F(const int & k) const override;
double S(const int & k) const override;
private:
enum GENERATOR_ID {
BERNOULLI_SUM,
WAITING,
REJECTION
};
GENERATOR_ID GetIdOfUsedGenerator() const;
int variateRejection() const;
int variateWaiting(int number) const;
static int variateWaiting(int number, double probability, RandGenerator &randGenerator);
static int variateBernoulliSum(int number, double probability, RandGenerator &randGenerator);
public:
int Variate() const override;
static int Variate(int number, double probability, RandGenerator &randGenerator = staticRandGenerator);
void Sample(std::vector<int> &outputData) const override;
void Reseed(unsigned long seed) const override;
double Mean() const override;
double Variance() const override;
int Median() const override;
int Mode() const override;
double Skewness() const override;
double ExcessKurtosis() const override;
/**
* @fn GetLogFactorialN
* @return log(n!)
*/
inline double GetLogFactorialN() const { return lfactn; }
/**
* @fn GetLogProbability
* @return log(p)
*/
inline double GetLogProbability() const { return logProb; }
/**
* @fn GetLog1mProbability
* @return log(1-p)
*/
inline double GetLog1mProbability() const { return log1mProb; }
private:
std::complex<double> CFImpl(double t) const override;
public:
/**
* @fn FitProbability
* Fit probability p with maximum-likelihood estimation
* @param sample
*/
void FitProbability(const std::vector<int> &sample);
/**
* @fn FitProbabilityBayes
* Fit probability p with prior assumption p ~ Beta(α, β)
* @param sample
* @param priorDistribution
* @return posterior distribution
*/
BetaRand FitProbabilityBayes(const std::vector<int> &sample, const BetaDistribution & priorDistribution);
/**
* @fn FitProbabilityMinimax
* Fit probability p with minimax estimator
* @param sample
* @return posterior distribution
*/
BetaRand FitProbabilityMinimax(const std::vector<int> &sample);
};
/**
* @brief The BinomialRand class <BR>
* Binomial distribution
*/
class RANDLIBSHARED_EXPORT BinomialRand : public BinomialDistribution
{
public:
BinomialRand(int number = 1, double probability = 0.5) : BinomialDistribution(number, probability) {}
String Name() const override;
using BinomialDistribution::SetParameters;
};
#endif // BINOMIALRAND_H
| [
"samarin_ad@mail.ru"
] | samarin_ad@mail.ru |
44bb6d005c0ce784591c193d247acc83e635e4cc | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /ens/include/alibabacloud/ens/model/CreateMountTargetRequest.h | bda56cf6cc6cc264814097144c9d1246f059c113 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,759 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_ENS_MODEL_CREATEMOUNTTARGETREQUEST_H_
#define ALIBABACLOUD_ENS_MODEL_CREATEMOUNTTARGETREQUEST_H_
#include <alibabacloud/ens/EnsExport.h>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <string>
#include <vector>
#include <map>
namespace AlibabaCloud {
namespace Ens {
namespace Model {
class ALIBABACLOUD_ENS_EXPORT CreateMountTargetRequest : public RpcServiceRequest {
public:
CreateMountTargetRequest();
~CreateMountTargetRequest();
std::string getMountTargetName() const;
void setMountTargetName(const std::string &mountTargetName);
std::string getEnsRegionId() const;
void setEnsRegionId(const std::string &ensRegionId);
std::string getFileSystemId() const;
void setFileSystemId(const std::string &fileSystemId);
std::string getNetWorkId() const;
void setNetWorkId(const std::string &netWorkId);
private:
std::string mountTargetName_;
std::string ensRegionId_;
std::string fileSystemId_;
std::string netWorkId_;
};
} // namespace Model
} // namespace Ens
} // namespace AlibabaCloud
#endif // !ALIBABACLOUD_ENS_MODEL_CREATEMOUNTTARGETREQUEST_H_
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
da04ed924a2cb470ac03c9cd4049006dcf3294c5 | 2da16a51129d1639698641649cf5ec113fed07ff | /scada/ControlSubSystem/calibration.h | 36a0631f620e56d28d3c964aac29adf42643f35d | [] | no_license | robsonadem/Supervisory-Control-and-Data-Acquisition-System | 3b807d60d06a8fc1ceecc767c54dd5050de3ed26 | 2f25cc7212919b803d887032dd12e4fb2f572a6e | refs/heads/master | 2020-03-29T01:38:51.951169 | 2018-09-19T06:05:12 | 2018-09-19T06:05:12 | 149,399,448 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,057 | h | #ifndef CALIBRATION_H
#define CALIBRATION_H
#include <iostream>
#include <vector>
#include "../DMS/dms.h"
#include "../DMS/table.h"
/**
Purpose: Calibration Class that stores an ID, Type, and the coeffeicients of the calibration type
It also takes in data from DMS and calibrates it with the given the type and stores it in the DMS.
@author Robson Adem
@version 1.0 12/03/17
*/
using namespace std;
class Calibration
{
public:
string calId;
string type;
vector<double> coeff;
vector<double> rawData;
vector<int> sampleIds;
DMS* db;
/**
* @brief A constructor for the Calibration Class
* @param DMS* db -pointer to the DMS
*/
Calibration(DMS* db);
/**
* @brief Calibrates data and stores it in the dms given a modelNumber
* @param string modelNumber - model Number of the calibration
*/
void calibrate();
/**
* @brief Given a string and a delimter , it splits strings.
* @param string s- a string to be split
* @param char delimiter - a character to split the string with.
* @return vector<string>- split tokens
*/
vector<string> split(const string s, char delimiter);
/**
* @brief Given a string and a delimter , it splits strings.
* @param string s- a string to be split
* @param char delimiter - a character to split the string with.
* @return vector<double>- split tokens turned into integer
*/
vector<double> split_toDouble(const string s, char delimiter);
/**
* @brief Given a string and a delimter , it splits strings.
* @param string s- a string to be split
* @param char delimiter - a character to split the string with.
* @return vector<int>- split tokens turned into integer
*/
vector<int> split_toInt(const string s, char delimiter);
/**
* @brief Distructor
*/
~Calibration();
};
#endif // CALIBRATION_H
| [
"noreply@github.com"
] | robsonadem.noreply@github.com |
15b0dce6f69f5c6e9de3c221e7f5227d16af39b3 | 8117773d24f922aac3d80d04392f62f74aab1f8c | /node_modules/react-native-windows/Chakra/ChakraHelpers.cpp | 7bb576f115eb4d4b5dd67829e91fd9d05804f5bc | [
"MIT"
] | permissive | micarthur/wend | bb7b34c8137ff2cfdad8a22d5e8565497be877b3 | dcf44ba1d5968958d39e69c86367b4ca038aca98 | refs/heads/main | 2023-05-13T19:04:10.169152 | 2021-06-11T19:28:35 | 2021-06-11T19:28:35 | 374,455,909 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,866 | cpp | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "ChakraHelpers.h"
#include "ChakraUtils.h"
#include "ChakraValue.h"
#include "Unicode.h"
#ifdef WITH_FBSYSTRACE
#include <fbsystrace.h>
#endif
#include <folly/Memory.h>
#include <folly/String.h>
#include <glog/logging.h>
#include <cxxreact/ReactMarker.h>
#include <windows.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <future>
#include <memory>
#include <string>
#include <thread>
#include <type_traits>
namespace facebook {
namespace react {
#if !defined(USE_EDGEMODE_JSRT)
namespace {
template <class T>
size_t fwrite(T *p, size_t count, FILE *file) noexcept {
static_assert(std::is_trivially_copyable<T>::value, "T must be trivially copyable to be serialized into a file");
return fwrite(p, sizeof(*p), count, file);
}
template <class T>
bool fwrite(const T &val, FILE *file) noexcept {
return fwrite(&val, 1, file) == 1;
}
#if !defined(CHAKRACORE_UWP)
struct FileVersionInfoResource {
uint16_t len;
uint16_t valLen;
uint16_t type;
wchar_t key[_countof(L"VS_VERSION_INFO")];
uint16_t padding1;
VS_FIXEDFILEINFO fixedFileInfo;
uint32_t padding2;
};
#endif
class ChakraVersionInfo {
public:
ChakraVersionInfo() noexcept : m_fileVersionMS{0}, m_fileVersionLS{0}, m_productVersionMS{0}, m_productVersionLS{0} {}
bool initialize() noexcept {
#if !defined(CHAKRACORE_UWP)
// This code is win32 only at the moment. We will need to change this
// line if we want to support UWP.
constexpr wchar_t chakraDllName[] = L"ChakraCore.dll";
auto freeLibraryWrapper = [](void *p) { FreeLibrary((HMODULE)p); };
HMODULE moduleHandle;
if (!GetModuleHandleExW(0, chakraDllName, &moduleHandle)) {
return false;
}
std::unique_ptr<void, decltype(freeLibraryWrapper)> moduleHandleWrapper(
moduleHandle, std::move(freeLibraryWrapper));
HRSRC versionResourceHandle = FindResourceW(moduleHandle, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION);
if (!versionResourceHandle ||
SizeofResource(static_cast<HMODULE>(moduleHandleWrapper.get()), versionResourceHandle) <
sizeof(FileVersionInfoResource)) {
return false;
}
HGLOBAL versionResourcePtrHandle = LoadResource(moduleHandle, versionResourceHandle);
if (!versionResourcePtrHandle) {
return false;
}
FileVersionInfoResource *chakraVersionInfo =
static_cast<FileVersionInfoResource *>(LockResource(versionResourcePtrHandle));
if (!chakraVersionInfo) {
return false;
}
m_fileVersionMS = chakraVersionInfo->fixedFileInfo.dwFileVersionMS;
m_fileVersionLS = chakraVersionInfo->fixedFileInfo.dwFileVersionLS;
m_productVersionMS = chakraVersionInfo->fixedFileInfo.dwProductVersionMS;
m_productVersionLS = chakraVersionInfo->fixedFileInfo.dwProductVersionLS;
#endif
return true;
}
bool operator==(const ChakraVersionInfo &rhs) const noexcept {
return (m_fileVersionMS == rhs.m_fileVersionMS) && (m_fileVersionLS == rhs.m_fileVersionLS) &&
(m_productVersionMS == rhs.m_productVersionMS) && (m_productVersionLS == rhs.m_productVersionLS);
}
bool operator!=(const ChakraVersionInfo &rhs) const noexcept {
return !(*this == rhs);
}
private:
uint32_t m_fileVersionMS;
uint32_t m_fileVersionLS;
uint32_t m_productVersionMS;
uint32_t m_productVersionLS;
};
class BytecodePrefix {
public:
static std::pair<bool, BytecodePrefix> getBytecodePrefix(uint64_t bundleVersion) noexcept {
std::pair<bool, BytecodePrefix> result{false, BytecodePrefix{bundleVersion}};
result.first = result.second.m_chakraVersionInfo.initialize();
return result;
}
bool operator==(const BytecodePrefix &rhs) const noexcept {
return (m_bytecodeFileFormatVersion == rhs.m_bytecodeFileFormatVersion) &&
(m_bundleVersion == rhs.m_bundleVersion) && (m_chakraVersionInfo == rhs.m_chakraVersionInfo);
}
bool operator!=(const BytecodePrefix &rhs) const noexcept {
return !(*this == rhs);
}
private:
uint64_t m_bytecodeFileFormatVersion;
uint64_t m_bundleVersion;
ChakraVersionInfo m_chakraVersionInfo;
static constexpr uint32_t s_bytecodeFileFormatVersion = 2;
BytecodePrefix(uint64_t bundleVersion) noexcept
: m_bytecodeFileFormatVersion{s_bytecodeFileFormatVersion},
m_bundleVersion{bundleVersion},
m_chakraVersionInfo{} {}
};
void serializeBytecodeToFileCore(
const std::shared_ptr<const JSBigString> &script,
const BytecodePrefix &bytecodePrefix,
const std::string &bytecodeFileName) {
FILE *bytecodeFilePtr;
// bytecode is a binary representation, so we need to pass in the "b" flag to
// fopen_s
if (_wfopen_s(&bytecodeFilePtr, Microsoft::Common::Unicode::Utf8ToUtf16(bytecodeFileName).c_str(), L"wb")) {
return;
}
std::unique_ptr<FILE, decltype(&fclose)> bytecodeFilePtrWrapper(bytecodeFilePtr, fclose);
const std::wstring scriptUTF16 = Microsoft::Common::Unicode::Utf8ToUtf16(script->c_str(), script->size());
unsigned int bytecodeSize = 0;
if (JsSerializeScript(scriptUTF16.c_str(), nullptr, &bytecodeSize) != JsNoError) {
return;
}
std::unique_ptr<uint8_t[]> bytecode(std::make_unique<uint8_t[]>(bytecodeSize));
if (JsSerializeScript(scriptUTF16.c_str(), bytecode.get(), &bytecodeSize) != JsNoError) {
return;
}
constexpr size_t bytecodePrefixSize = sizeof(bytecodePrefix);
uint8_t zeroArray[sizeof(bytecodePrefix)]{};
if (fwrite(zeroArray, bytecodePrefixSize, bytecodeFilePtrWrapper.get()) != bytecodePrefixSize ||
fwrite(bytecode.get(), bytecodeSize, bytecodeFilePtrWrapper.get()) != bytecodeSize ||
fflush(bytecodeFilePtrWrapper.get())) {
return;
}
fseek(bytecodeFilePtrWrapper.get(), 0, SEEK_SET);
if (!fwrite(bytecodePrefix, bytecodeFilePtrWrapper.get()) || fflush(bytecodeFilePtrWrapper.get())) {
return;
}
}
std::unique_ptr<JSBigString> tryGetBytecode(const BytecodePrefix &bytecodePrefix, const std::string &bytecodeFileName) {
auto bytecodeBigStringPtr =
std::make_unique<FileMappingBigString>(bytecodeFileName, static_cast<uint32_t>(sizeof(BytecodePrefix)));
if (!bytecodeBigStringPtr->file_data() || bytecodeBigStringPtr->file_size() < sizeof(bytecodePrefix) ||
*reinterpret_cast<const BytecodePrefix *>(bytecodeBigStringPtr->file_data()) != bytecodePrefix) {
return nullptr;
}
return bytecodeBigStringPtr;
}
void serializeBytecodeToFile(
const std::shared_ptr<const JSBigString> &script,
const BytecodePrefix &bytecodePrefix,
std::string &&bytecodeFileName,
bool async) {
std::future<void> bytecodeSerializationFuture = std::async(
std::launch::async,
[](const std::shared_ptr<const JSBigString> &script,
const BytecodePrefix &bytecodePrefix,
const std::string &bytecodeFileName) {
MinimalChakraRuntime chakraRuntime(false /* multithreaded */);
serializeBytecodeToFileCore(script, bytecodePrefix, bytecodeFileName);
},
script,
bytecodePrefix,
std::move(bytecodeFileName));
if (!async) {
bytecodeSerializationFuture.wait();
}
}
} // namespace
#endif
MinimalChakraRuntime::MinimalChakraRuntime(bool multithreaded)
: runtime{new JsRuntimeHandle,
[](JsRuntimeHandle *h) {
JsDisposeRuntime(*h);
delete h;
}},
context{new JsContextRef, [](JsContextRef *c) {
JsSetCurrentContext(JS_INVALID_REFERENCE);
delete c;
}} {
JsErrorCode lastError = JsCreateRuntime(
multithreaded ? JsRuntimeAttributeNone : JsRuntimeAttributeDisableBackgroundWork, nullptr, &(*runtime));
assert(lastError == JsNoError && "JsCreateRuntime failed in MinimalChakraRuntime constructor.");
lastError = JsCreateContext(*runtime, &(*context));
assert(lastError == JsNoError && "JsCreateContext failed in MinimalChakraRuntime constructor.");
lastError = JsSetCurrentContext(*context);
assert(lastError == JsNoError && "JsSetCurrentContext failed in MinimalChakraRuntime constructor.");
}
JsValueRef functionCaller(
JsContextRef ctx,
JsValueRef /*function*/,
JsValueRef thisObject,
size_t argumentCount,
const JsValueRef arguments[],
JsValueRef * /*exception*/) {
// JsContextRef ctx;
// JsGetCurrentContext(&ctx);
void *voidPtr;
JsGetContextData(ctx, &voidPtr);
auto *f = static_cast<ChakraJSFunction *>(voidPtr);
return (*f)(ctx, thisObject, argumentCount, arguments);
}
JsValueRef makeFunction(JsValueRef name, ChakraJSFunction function) {
// dealloc in kClassDef.finalize
ChakraJSFunction *functionPtr = new ChakraJSFunction(std::move(function));
JsValueRef value;
JsCreateExternalObject(functionPtr, nullptr /*JsFinalizeCallback*/, &value);
auto functionObject = ChakraObject(value);
functionObject.setProperty("name", ChakraValue(name));
return functionObject;
}
void ChakraJSException::buildMessage(JsValueRef exn, JsValueRef sourceURL, const char *errorMsg) {
std::ostringstream msgBuilder;
if (errorMsg && strlen(errorMsg) > 0) {
msgBuilder << errorMsg << ": ";
}
ChakraValue exnValue = ChakraValue(exn);
msgBuilder << exnValue.toString().str();
// The null/empty-ness of source tells us if the JS came from a
// file/resource, or was a constructed statement. The location
// info will include that source, if any.
std::string locationInfo = sourceURL != nullptr ? ChakraString::ref(sourceURL).str() : "";
ChakraObject exnObject = exnValue.asObject();
auto line = exnObject.getProperty("line");
if (line != nullptr && line.isNumber()) {
if (locationInfo.empty() && line.asInteger() != 1) {
// If there is a non-trivial line number, but there was no
// location info, we include a placeholder, and the line
// number.
locationInfo = folly::to<std::string>("<unknown file>:", line.asInteger());
} else if (!locationInfo.empty()) {
// If there is location info, we always include the line
// number, regardless of its value.
locationInfo += folly::to<std::string>(":", line.asInteger());
}
}
if (!locationInfo.empty()) {
msgBuilder << " (" << locationInfo << ")";
}
auto exceptionText = msgBuilder.str();
LOG(ERROR) << "Got JS Exception: " << exceptionText;
msg_ = std::move(exceptionText);
ChakraValue jsStack = exnObject.getProperty("stack");
if (jsStack.isString()) {
auto stackText = jsStack.toString().str();
LOG(ERROR) << "Got JS Stack: " << stackText;
stack_ = std::move(stackText);
}
}
JsValueRef makeFunction(const char *name, ChakraJSFunction function) {
return makeFunction(ChakraString(name), std::move(function));
}
void installGlobalFunction(const char *name, ChakraJSFunction function) {
auto jsName = ChakraString(name);
auto functionObj = makeFunction(jsName, std::move(function));
ChakraObject::getGlobalObject().setProperty(jsName, ChakraValue(functionObj));
}
JsValueRef makeFunction(const char *name, JsNativeFunction callback) {
auto jsName = ChakraString(name);
JsValueRef functionObj;
JsCreateNamedFunction(jsName, callback, nullptr /*callbackstate*/, &functionObj);
return functionObj;
}
void installGlobalFunction(const char *name, JsNativeFunction callback) {
ChakraString jsName(name);
JsValueRef functionObj;
JsCreateNamedFunction(jsName, callback, nullptr /*callbackstate*/, &functionObj);
ChakraObject::getGlobalObject().setProperty(jsName, ChakraValue(functionObj));
}
void removeGlobal(const char *name) {
ChakraObject::getGlobalObject().setProperty(name, ChakraValue::makeUndefined());
}
JsSourceContext getNextSourceContext() {
static JsSourceContext nextSourceContext = 0;
return nextSourceContext++;
}
JsValueRef evaluateScript(JsValueRef script, JsValueRef source) {
JsValueRef exn = nullptr;
JsValueRef value = nullptr;
#if defined(USE_EDGEMODE_JSRT)
const wchar_t *scriptRaw;
size_t scriptRawLength;
JsStringToPointer(script, &scriptRaw, &scriptRawLength);
const wchar_t *sourceRaw;
size_t sourceRawLength;
JsStringToPointer(source, &sourceRaw, &sourceRawLength);
auto result = JsRunScript(scriptRaw, JS_SOURCE_CONTEXT_NONE /*sourceContext*/, sourceRaw, &value);
#else
JsSourceContext sourceContext = getNextSourceContext();
auto result = JsRun(script, sourceContext, source, JsParseScriptAttributeNone, &value);
#endif
bool hasException = false;
if (result == JsErrorInExceptionState || (JsHasException(&hasException), hasException)) {
JsGetAndClearException(&exn);
throw ChakraJSException(exn, source);
}
if (value == nullptr) {
formatAndThrowJSException(exn, source);
}
return value;
}
JsValueRef evaluateScript(std::unique_ptr<const JSBigString> &&script, JsValueRef sourceURL) {
ReactMarker::logMarker(ReactMarker::JS_BUNDLE_STRING_CONVERT_START);
#if defined(USE_EDGEMODE_JSRT)
JsValueRef jsScript = jsStringFromBigString(*script.get());
#else
JsValueRefUniquePtr jsScript = jsArrayBufferFromBigString(std::move(script));
#endif
ReactMarker::logMarker(ReactMarker::JS_BUNDLE_STRING_CONVERT_STOP);
#if defined(USE_EDGEMODE_JSRT)
return evaluateScript(jsScript, sourceURL);
#else
return evaluateScript(jsScript.get(), sourceURL);
#endif
}
JsValueRef evaluateScriptWithBytecode(
std::unique_ptr<const JSBigString> &&script,
[[maybe_unused]] uint64_t scriptVersion,
JsValueRef scriptFileName,
[[maybe_unused]] std::string &&bytecodeFileName,
[[maybe_unused]] bool asyncBytecodeGeneration) {
#if defined(WINRT)
// TODO: yicyao
// ChakraRT does not support the JsRunSerialized() API.
// Hence for UWP implementation, we fall back to using the original source
// code right now.
return evaluateScript(std::move(script), scriptFileName);
#else
auto bytecodePrefixOptional = BytecodePrefix::getBytecodePrefix(scriptVersion);
if (!bytecodePrefixOptional.first) {
return evaluateScript(std::move(script), scriptFileName);
}
auto &bytecodePrefix = bytecodePrefixOptional.second;
std::unique_ptr<const JSBigString> bytecode = tryGetBytecode(bytecodePrefix, bytecodeFileName);
if (!bytecode) {
std::shared_ptr<const JSBigString> sharedScript(script.release());
serializeBytecodeToFile(sharedScript, bytecodePrefix, std::move(bytecodeFileName), asyncBytecodeGeneration);
ReactMarker::logMarker(ReactMarker::JS_BUNDLE_STRING_CONVERT_START);
JsValueRefUniquePtr jsScript = jsArrayBufferFromBigString(sharedScript);
ReactMarker::logMarker(ReactMarker::JS_BUNDLE_STRING_CONVERT_STOP);
return evaluateScript(jsScript.get(), scriptFileName);
}
ReactMarker::logMarker(ReactMarker::JS_BUNDLE_STRING_CONVERT_START);
JsValueRefUniquePtr jsScript = jsArrayBufferFromBigString(std::move(script));
ReactMarker::logMarker(ReactMarker::JS_BUNDLE_STRING_CONVERT_STOP);
JsValueRef exn = nullptr;
JsValueRef value = nullptr;
JsErrorCode result = JsRunSerialized(
jsArrayBufferFromBigString(std::move(bytecode)).get(),
[](JsSourceContext sourceContext, JsValueRef *value, JsParseScriptAttributes *parseAttributes) {
*value = reinterpret_cast<JsValueRef>(sourceContext);
*parseAttributes = JsParseScriptAttributeNone;
return true;
},
reinterpret_cast<JsSourceContext>(jsScript.get()),
scriptFileName,
&value);
// Currently, when the existing bundle.bytecode is incompatible with the
// ChakraCore.dll used, we do not update it. This is because we memory mapped
// bundle.bytecode into a JsExternalArrayBuffer, whose lifetime is controlled
// by the JS engine. Hence we cannot remove/rename/modify bytecode.bundle
// until the JS garbage collector deletes the corresponding
// JsExternalArrayBuffer.
if (result == JsErrorBadSerializedScript) {
JsGetAndClearException(&exn);
return evaluateScript(jsScript.get(), scriptFileName);
}
// This code is duplicated from evaluateScript.
// TODO (yicyao, task 1977635) get rid of this duplicated code.
bool hasException = false;
if (result == JsErrorInExceptionState || (JsHasException(&hasException), hasException)) {
JsGetAndClearException(&exn);
std::string exceptionDescription = "JavaScriptException in " + ChakraValue(scriptFileName).toString().str();
throw ChakraJSException(exn, exceptionDescription.c_str());
}
if (value == nullptr) {
formatAndThrowJSException(exn, scriptFileName);
}
return value;
#endif
}
void formatAndThrowJSException(JsValueRef exn, JsValueRef source) {
ChakraValue exception = ChakraValue(exn);
std::string exceptionText = exception.toString().str();
// The null/empty-ness of source tells us if the JS came from a
// file/resource, or was a constructed statement. The location
// info will include that source, if any.
std::string locationInfo = source != nullptr ? ChakraString::ref(source).str() : "";
ChakraObject exObject = exception.asObject();
auto line = exObject.getProperty("line");
if (line != nullptr && line.isNumber()) {
if (locationInfo.empty() && line.asInteger() != 1) {
// If there is a non-trivial line number, but there was no
// location info, we include a placeholder, and the line
// number.
locationInfo = folly::to<std::string>("<unknown file>:", line.asInteger());
} else if (!locationInfo.empty()) {
// If there is location info, we always include the line
// number, regardless of its value.
locationInfo += folly::to<std::string>(":", line.asInteger());
}
}
if (!locationInfo.empty()) {
exceptionText += " (" + locationInfo + ")";
}
LOG(ERROR) << "Got JS Exception: " << exceptionText;
ChakraValue jsStack = exObject.getProperty("stack");
if (jsStack.isNull() || !jsStack.isString()) {
throwJSExecutionException("%s", exceptionText.c_str());
} else {
LOG(ERROR) << "Got JS Stack: " << jsStack.toString().str();
throwJSExecutionExceptionWithStack(exceptionText.c_str(), jsStack.toString().str().c_str());
}
}
JsValueRef translatePendingCppExceptionToJSError(const char *exceptionLocation) {
std::ostringstream msg;
try {
throw;
} catch (const std::bad_alloc &) {
throw; // We probably shouldn't try to handle this in JS
} catch (const std::exception &ex) {
msg << "C++ Exception in '" << exceptionLocation << "': " << ex.what();
return ChakraValue::makeError(msg.str().c_str());
} catch (const char *ex) {
msg << "C++ Exception (thrown as a char*) in '" << exceptionLocation << "': " << ex;
return ChakraValue::makeError(msg.str().c_str());
} catch (...) {
msg << "Unknown C++ Exception in '" << exceptionLocation << "'";
return ChakraValue::makeError(msg.str().c_str());
}
}
JsValueRef translatePendingCppExceptionToJSError(JsValueRef jsFunctionCause) {
try {
auto functionName = ChakraObject(jsFunctionCause).getProperty("name").toString().str();
return translatePendingCppExceptionToJSError(functionName.c_str());
} catch (...) {
return ChakraValue::makeError("Failed to get function name while handling exception");
}
}
JsValueRef GetJSONObject() {
JsValueRef globalObject;
JsGetGlobalObject(&globalObject);
JsPropertyIdRef propertyId;
if (JsNoError != JsGetPropertyIdFromName(L"JSON", &propertyId)) {
return nullptr;
}
JsValueRef jsonObject;
if (JsNoError != JsGetProperty(globalObject, propertyId, &jsonObject)) {
return nullptr;
}
return jsonObject;
}
int StringGetLength(_In_ JsValueRef string) {
int length;
JsGetStringLength(string, &length);
return length;
}
JsValueRef JSObjectCallAsFunction(
JsValueRef methodJSRef,
JsValueRef batchedBridgeRef,
unsigned nArgs,
const JsValueRef args[],
JsValueRef *error) {
auto argsWithThis = new JsValueRef[nArgs + 1];
argsWithThis[0] = batchedBridgeRef;
for (unsigned i = 0; i < nArgs; i++)
argsWithThis[i + 1] = args[i];
JsValueRef value;
auto result = JsCallFunction(
methodJSRef, const_cast<JsValueRef *>(argsWithThis), static_cast<unsigned short>(nArgs + 1), &value);
delete[] argsWithThis;
bool hasException = false;
if (result != JsNoError || (JsHasException(&hasException), hasException)) {
JsGetAndClearException(error);
return nullptr;
}
return value;
}
JsValueRef JSValueMakeFromJSONString(JsValueRef string) {
// Handle special case with Chakra runtime where if you pass an empty string
// to parseFunction it will throw an exception instead of returning nullptr
if (StringGetLength(string) == 0) {
JsValueRef value;
JsGetNullValue(&value);
return value;
}
auto jsonObject = GetJSONObject();
JsPropertyIdRef propertyId;
if (JsNoError != JsGetPropertyIdFromName(L"parse", &propertyId) || !jsonObject) {
return nullptr;
}
JsValueRef parseFunction;
if (JsNoError != JsGetProperty(jsonObject, propertyId, &parseFunction)) {
return nullptr;
}
JsValueRef error;
JsValueRef arguments[1] = {string};
return JSObjectCallAsFunction(parseFunction, jsonObject, 1, arguments, &error);
}
JsValueRef JSValueCreateJSONString(JsValueRef value, unsigned /*indent*/, JsValueRef *error) {
auto jsonObject = GetJSONObject();
JsPropertyIdRef propertyId;
if (JsNoError != JsGetPropertyIdFromName(L"stringify", &propertyId) || !jsonObject) {
JsGetAndClearException(error);
return nullptr;
}
JsValueRef stringifyFunction;
if (JsNoError != JsGetProperty(jsonObject, propertyId, &stringifyFunction)) {
JsGetAndClearException(error);
return nullptr;
}
JsValueRef arguments[1] = {value};
return JSObjectCallAsFunction(stringifyFunction, jsonObject, 1, arguments, error);
}
// TODO ensure proper clean up of error states in the middle of function
JsValueRef JSObjectGetProperty(JsValueRef object, JsValueRef propertyName, JsValueRef *exception) {
std::string propName;
auto result = JsStringToStdStringUtf8(propertyName, propName);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
JsPropertyIdRef propId = JS_INVALID_REFERENCE;
result = JsGetPropertyIdFromNameUtf8(propName.c_str(), &propId);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
JsValueRef value;
result = JsGetProperty(object, propId, &value);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
return value;
}
JsValueRef JSObjectGetPropertyAtIndex(JsValueRef object, unsigned propertyIndex, JsValueRef *exception) {
JsValueRef index;
JsIntToNumber(propertyIndex, &index);
JsValueRef property;
auto result = JsGetIndexedProperty(object, index, &property);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
return property;
}
// Only support None
void JSObjectSetProperty(
JsValueRef jsObj,
JsValueRef propertyName,
JsValueRef value,
JSPropertyAttributes /*attributes*/,
JsValueRef *exception) {
// TODO exception handing -- ensure proper clean up if failure in middle of
// function
JsPropertyIdRef propId = JS_INVALID_REFERENCE;
std::string propName;
auto result = JsStringToStdStringUtf8(propertyName, propName);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
result = JsGetPropertyIdFromNameUtf8(propName.c_str(), &propId);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
// TODO - should we use strict rules?
result = JsSetProperty(jsObj, propId, value, true /*useStrictRules*/);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
}
JsValueRef JSObjectCopyPropertyNames(JsValueRef object) {
JsValueRef propertyNamesArrayRef;
JsGetOwnPropertyNames(object, &propertyNamesArrayRef);
return propertyNamesArrayRef;
}
unsigned JSPropertyNameArrayGetCount(JsValueRef namesRef) {
JsPropertyIdRef propertyId;
JsGetPropertyIdFromName(L"length", &propertyId);
JsValueRef countRef;
JsGetProperty(namesRef, propertyId, &countRef);
int count;
JsNumberToInt(countRef, &count);
return count;
}
JsValueRef JSPropertyNameArrayGetNameAtIndex(JsValueRef namesRef, unsigned idx) {
JsValueRef index;
JsIntToNumber(idx, &index);
JsValueRef propertyName;
JsGetIndexedProperty(namesRef, index, &propertyName);
return propertyName;
}
double JSValueToNumber(JsValueRef obj, JsValueRef *exception) {
double value;
auto result = JsNumberToDouble(obj, &value);
if (result == JsErrorScriptException)
JsGetAndClearException(exception);
return value;
}
JsValueRef JSValueToStringCopy(JsValueRef obj, JsValueRef *exception) {
JsValueRef value;
auto result = JsConvertValueToString(obj, &value);
if (JsNoError == result)
JsAddRef(value, nullptr); // TODO is this the right lifetime symantics?
else if (result == JsErrorScriptException)
JsGetAndClearException(exception);
return value;
}
JsValueRef ValueMakeUndefined() {
JsValueRef value;
JsGetUndefinedValue(&value);
return value;
}
} // namespace react
} // namespace facebook
| [
"micarthur@utexas.edu"
] | micarthur@utexas.edu |
8e06dce2632a0eaff6de25cff1fd9730523d3194 | 593cbbaa04cd806fa8b9f4a1cf0d1d74db1d54bc | /UVa/12157.cpp | 13f4f2c30fe4665fbfc85dee1fff0a19154d83dc | [] | no_license | Alissonrgs/competitive-programming | 2e6c0368e24f11ac9d78400c0141a63c5b498a27 | 70b11068902e719345d6c4941e9a243b85e17160 | refs/heads/master | 2021-01-12T11:03:27.915190 | 2017-08-09T22:56:54 | 2017-08-09T22:56:54 | 72,805,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | cpp | #include <bits/stdc++.h>
using namespace std;
int mile( int time ) {
int ans = (time+1)/30;
if( (time+1)%30 != 0 )
ans++;
return 10*ans;
}
int juice( int time ) {
int ans = (time+1)/60;
if( (time+1)%60 != 0 )
ans++;
return 15*ans;
}
int main() {
int t, n, time, m, j;
scanf( "%d", &t );
for( int _case = 1; _case <= t; _case++ ) {
m = j = 0;
scanf( "%d", &n );
for( int i = 0; i < n; i++ ) {
scanf( "%d", &time );
m += mile( time );
j += juice( time );
}
printf( "Case %d: ", _case );
if( m == j )
printf( "Mile Juice %d\n", m );
else if( m < j )
printf( "Mile %d\n", m );
else
printf( "Juice %d\n", j );
}
return 0;
}
| [
"alissonrgs1993@gmail.com"
] | alissonrgs1993@gmail.com |
84896b99b5b75cf9833f0dd13bf52557aaeaac90 | 410e45283cf691f932b07c5fdf18d8d8ac9b57c3 | /chrome/browser/web_applications/web_app_install_task.h | a62cc72e10af51694d6737cf0689967bc8ef303d | [
"BSD-3-Clause"
] | permissive | yanhuashengdian/chrome_browser | f52a7f533a6b8417e19b85f765f43ea63307a1fb | 972d284a9ffa4b794f659f5acc4116087704394c | refs/heads/master | 2022-12-21T03:43:07.108853 | 2019-04-29T14:20:05 | 2019-04-29T14:20:05 | 184,068,841 | 0 | 2 | BSD-3-Clause | 2022-12-17T17:35:55 | 2019-04-29T12:40:27 | null | UTF-8 | C++ | false | false | 5,068 | 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_WEB_APPLICATIONS_WEB_APP_INSTALL_TASK_H_
#define CHROME_BROWSER_WEB_APPLICATIONS_WEB_APP_INSTALL_TASK_H_
#include <memory>
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/installable/installable_metrics.h"
#include "chrome/browser/web_applications/components/install_manager.h"
#include "chrome/browser/web_applications/components/web_app_install_utils.h"
#include "content/public/browser/web_contents_observer.h"
class Profile;
struct WebApplicationInfo;
namespace blink {
struct Manifest;
}
namespace content {
class WebContents;
}
namespace web_app {
class InstallFinalizer;
class WebAppDataRetriever;
class WebAppInstallTask : content::WebContentsObserver {
public:
WebAppInstallTask(Profile* profile, InstallFinalizer* install_finalizer);
~WebAppInstallTask() override;
// Checks a WebApp installability, retrieves manifest and icons and
// than performs the actual installation.
void InstallWebAppFromManifest(
content::WebContents* web_contents,
WebappInstallSource install_source,
InstallManager::WebAppInstallDialogCallback dialog_callback,
InstallManager::OnceInstallCallback callback);
// This method infers WebApp info from the blink renderer process
// and than retrieves a manifest in a way similar to
// |InstallWebAppFromManifest|. If manifest is incomplete or missing, the
// inferred info is used.
void InstallWebAppFromManifestWithFallback(
content::WebContents* web_contents,
bool force_shortcut_app,
WebappInstallSource install_source,
InstallManager::WebAppInstallDialogCallback dialog_callback,
InstallManager::OnceInstallCallback callback);
// Starts a web app installation process using prefilled
// |web_application_info| which holds all the data needed for installation.
// InstallManager doesn't fetch a manifest. If |no_network_install| is true,
// the app will not be synced, since if the data is locally available we
// assume there is an external sync mechanism.
void InstallWebAppFromInfo(
std::unique_ptr<WebApplicationInfo> web_application_info,
bool no_network_install,
WebappInstallSource install_source,
InstallManager::OnceInstallCallback callback);
// WebContentsObserver:
void WebContentsDestroyed() override;
void SetDataRetrieverForTesting(
std::unique_ptr<WebAppDataRetriever> data_retriever);
void SetInstallFinalizerForTesting(InstallFinalizer* install_finalizer);
private:
void CheckInstallPreconditions();
void RecordInstallEvent(ForInstallableSite for_installable_site);
// Calling the callback may destroy |this| task. Callers shoudln't work with
// any |this| class members after calling it.
void CallInstallCallback(const AppId& app_id, InstallResultCode code);
// Checks if any errors occurred while |this| was async awaiting. All On*
// completion handlers below must return early if this is true. Also, if
// ShouldStopInstall is true, install_callback_ is already invoked or may be
// invoked later: All On* completion handlers don't need to call
// install_callback_.
bool ShouldStopInstall() const;
void OnGetWebApplicationInfo(
bool force_shortcut_app,
std::unique_ptr<WebApplicationInfo> web_app_info);
void OnDidPerformInstallableCheck(
std::unique_ptr<WebApplicationInfo> web_app_info,
bool force_shortcut_app,
const blink::Manifest& manifest,
bool is_installable);
void OnIconsRetrieved(std::unique_ptr<WebApplicationInfo> web_app_info,
ForInstallableSite for_installable_site,
IconsMap icons_map);
void OnDialogCompleted(ForInstallableSite for_installable_site,
bool user_accepted,
std::unique_ptr<WebApplicationInfo> web_app_info);
void OnInstallFinalized(std::unique_ptr<WebApplicationInfo> web_app_info,
const AppId& app_id,
InstallResultCode code);
void OnShortcutsCreated(std::unique_ptr<WebApplicationInfo> web_app_info,
const AppId& app_id,
bool shortcut_created);
InstallManager::WebAppInstallDialogCallback dialog_callback_;
InstallManager::OnceInstallCallback install_callback_;
// The mechanism via which the app creation was triggered.
static constexpr WebappInstallSource kNoInstallSource =
WebappInstallSource::COUNT;
WebappInstallSource install_source_ = kNoInstallSource;
std::unique_ptr<WebAppDataRetriever> data_retriever_;
InstallFinalizer* install_finalizer_;
Profile* profile_;
base::WeakPtrFactory<WebAppInstallTask> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(WebAppInstallTask);
};
} // namespace web_app
#endif // CHROME_BROWSER_WEB_APPLICATIONS_WEB_APP_INSTALL_TASK_H_
| [
"279687673@qq.com"
] | 279687673@qq.com |
c658143db035c463f4997427622ab6060dbdad48 | 1a66e03b11ec7a2967e5dda4b64702ae9d2f6f52 | /cf/jai/difdel.cpp | e9722410cff2ddec09de11bc7d4a4195ddb409f6 | [] | no_license | Bonaparto/CPP-Codes | 42dda7470788a151ef542dd49bcd33097d477ecb | 7ae23eee1f41ca2d130ad94fd69686b0aad13677 | refs/heads/main | 2023-08-04T07:33:53.859954 | 2021-10-02T17:21:00 | 2021-10-02T17:21:00 | 347,952,241 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 257 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main(){
int n;
cin >> n;
vector <int> v;
for(int i = 0; i < n; ++i){
int x; cin >> x;
if(x == 1) cout << 6 << endl;
if(x == 2) cout << 15 << endl;
}
} | [
"mibuhic773@mail.ru"
] | mibuhic773@mail.ru |
4b3b46f15971d91f99ba31488a831dace8957b53 | 06a6763623f9d17f0194c1b3c480f1ef89b93e34 | /Engine/Graphics.h | 8bf138261e7818cc4f4789841dac21c74abb6ad8 | [] | no_license | briantalbert/snake | d00f37e74c3a148bbaffdd93f1504b1b3a6f9a14 | 83f89313e89f90be696ba709bfca34d2d3b8c322 | refs/heads/master | 2022-12-05T15:43:30.203745 | 2020-08-19T11:42:02 | 2020-08-19T11:42:02 | 288,714,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,385 | h | /******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Graphics.h *
* Copyright 2016 PlanetChili <http://www.planetchili.net> *
* *
* This file is part of The Chili DirectX Framework. *
* *
* The Chili DirectX Framework is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* The Chili DirectX Framework 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 The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************************/
#pragma once
#include <d3d11.h>
#include <wrl.h>
#include "ChiliException.h"
#include "Colors.h"
class Graphics
{
public:
class Exception : public ChiliException
{
public:
Exception( HRESULT hr,const std::wstring& note,const wchar_t* file,unsigned int line );
std::wstring GetErrorName() const;
std::wstring GetErrorDescription() const;
virtual std::wstring GetFullMessage() const override;
virtual std::wstring GetExceptionType() const override;
private:
HRESULT hr;
};
private:
// vertex format for the framebuffer fullscreen textured quad
struct FSQVertex
{
float x,y,z; // position
float u,v; // texcoords
};
public:
Graphics( class HWNDKey& key );
Graphics( const Graphics& ) = delete;
Graphics& operator=( const Graphics& ) = delete;
void EndFrame();
void BeginFrame();
void PutPixel( int x,int y,int r,int g,int b )
{
PutPixel( x,y,{ unsigned char( r ),unsigned char( g ),unsigned char( b ) } );
}
void PutPixel( int x,int y,Color c );
void DrawRect( int x0,int y0,int x1,int y1,Color c );
void DrawRectDim( int x0,int y0,int width,int height,Color c )
{
DrawRect( x0,y0,x0 + width,y0 + height,c );
}
void DrawFive(int x, int y, Color c);
~Graphics();
private:
Microsoft::WRL::ComPtr<IDXGISwapChain> pSwapChain;
Microsoft::WRL::ComPtr<ID3D11Device> pDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext> pImmediateContext;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> pRenderTargetView;
Microsoft::WRL::ComPtr<ID3D11Texture2D> pSysBufferTexture;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> pSysBufferTextureView;
Microsoft::WRL::ComPtr<ID3D11PixelShader> pPixelShader;
Microsoft::WRL::ComPtr<ID3D11VertexShader> pVertexShader;
Microsoft::WRL::ComPtr<ID3D11Buffer> pVertexBuffer;
Microsoft::WRL::ComPtr<ID3D11InputLayout> pInputLayout;
Microsoft::WRL::ComPtr<ID3D11SamplerState> pSamplerState;
D3D11_MAPPED_SUBRESOURCE mappedSysBufferTexture;
Color* pSysBuffer = nullptr;
public:
static constexpr int ScreenWidth = 800;
static constexpr int ScreenHeight = 600;
}; | [
"BrianLTalbert@gmail.com"
] | BrianLTalbert@gmail.com |
0827298d387992d06cba7dd4743b905cf2b5436c | 3eb8e65f8ff4c9c2b7ce96d735229b2cfa4b596b | /Helper/doFuncChangeBoss.cpp | 767f32e78e21a83f79cd56c37742ee85be516455 | [
"Apache-2.0"
] | permissive | openlastchaos/lastchaos-source-server | 778d44cb2af1cb8fec646c50ae362224124133ac | 935b770fa857e67b705717d154b11b717741edeb | refs/heads/master | 2023-06-24T11:10:21.088498 | 2021-07-31T21:49:40 | 2021-07-31T21:49:40 | 391,469,204 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 4,640 | cpp | #include <boost/format.hpp>
#include "stdhdrs.h"
#include "Server.h"
#include "doFunc.h"
#include "CmdMsg.h"
#include "Log.h"
bool do_GuildBossChange(int _guildIndex, int _newBoss)
{
CGuild* guild = gserver.m_guildlist.findguild(_guildIndex);
if (!guild)
{
GAMELOG << init("GUILD MASTER AUTO CHANGE")
<< "ERROR : NOT EXIST GUILD";
return false;
}
CGuildMember* boss = guild->boss();
if (!boss)
{
GAMELOG << init("GUILD MASTER AUTO CHANGE")
<< "ERROR : NOT EXIST BOSS";
return false;
}
int _currentBoss = boss->charindex();
CGuildMember* member = guild->findmember(_newBoss);
if (!member)
{
GAMELOG << init("GUILD MASTER AUTO CHANGE")
<< "ERROR : NOT MEMBER" << delim
<< guild->index() << delim
<< guild->name() << delim
<< _currentBoss << delim
<< boss->GetName() << delim
<< _newBoss;
return false;
}
if (member->pos() == MSG_GUILD_POSITION_BOSS)
{
GAMELOG << init("GUILD MASTER AUTO CHANGE")
<< "ERROR : ALREADY BOSS" << delim
<< guild->index() << delim
<< guild->name() << delim
<< _currentBoss << delim
<< boss->GetName() << delim
<< _newBoss << delim
<< member->GetName();
return false;
}
CDBCmd cmd;
cmd.Init(&gserver.m_dbchar);
// 성주 길드는 성주 변경 불가능
std::string select_castle_query = boost::str(boost::format("SELECT * FROM t_castle WHERE a_owner_guild_index = %d;") % _guildIndex);
cmd.SetQuery( select_castle_query );
if( cmd.Open() && cmd.m_nrecords > 0 )
{
GAMELOG << init("GUILD MASTER AUTO CHANGE")
<< "ERROR : CASTLE OWNER" << delim
<< guild->index() << delim
<< guild->name() << delim
<< _currentBoss << delim
<< boss->GetName() << delim
<< _newBoss << delim
<< member->GetName();
return false;
}
cmd.BeginTrans();
std::string update_guild_member_query = boost::str(boost::format(
"UPDATE t_guildmember SET a_pos = %d WHERE a_guild_index = %d AND a_char_index = %d")
% MSG_GUILD_POSITION_MEMBER % _guildIndex % _currentBoss);
cmd.SetQuery(update_guild_member_query);
if (!cmd.Update())
{
cmd.Rollback();
GAMELOG << init("GUILD MASTER AUTO CHANGE")
<< "ERROR : UPDATE CURRENT GUILD BOSS POSITION" << delim
<< guild->index() << delim
<< guild->name() << delim
<< _currentBoss << delim
<< boss->GetName() << delim
<< _newBoss << delim
<< member->GetName();
return false;
}
std::string update_guild_member_query_1 = boost::str(boost::format(
"UPDATE t_guildmember SET a_pos = %d WHERE a_guild_index = %d AND a_char_index = %d")
% MSG_GUILD_POSITION_BOSS % _guildIndex % _newBoss);
cmd.SetQuery(update_guild_member_query_1);
if (!cmd.Update() || cmd.m_nrecords < 1)
{
cmd.Rollback();
GAMELOG << init("GUILD MASTER AUTO CHANGE")
<< "ERROR : UPDATE NEW GUILD BOSS POSITION" << delim
<< guild->index() << delim
<< guild->name() << delim
<< _currentBoss << delim
<< boss->GetName() << delim
<< _newBoss << delim
<< member->GetName();
return false;
}
cmd.Commit();
std::string update_guild_query = boost::str(boost::format("UPDATE t_guild SET a_recentdate=NOW() WHERE a_index = %d") % _guildIndex);
cmd.SetQuery(update_guild_query);
cmd.Update();
int currentTime = (int)time(NULL);
std::string update_guild_extend_guild = boost::str(boost::format("UPDATE t_extend_guild SET a_lastdate_change_boss = %d WHERE a_guild_index = %d") % currentTime % _guildIndex);
cmd.SetQuery(update_guild_extend_guild);
cmd.Update();
guild->changeboss(member->listindex());
CNetMsg::SP rmsg(new CNetMsg);
HelperGuildChangeBossNotifyMsg(rmsg, _guildIndex, _currentBoss, _newBoss);
gserver.SendToAllGameServer(rmsg);
GAMELOG << init("GUILD MASTER AUTO CHANGE")
<< "SUCCESS" << delim
<< guild->index() << delim
<< guild->name() << delim
<< _currentBoss << delim
<< boss->GetName() << delim
<< _newBoss << delim
<< member->GetName();
return true;
}
void do_GuildStatusChange(int _guildIndex, int _status)
{
CGuild* _guild = gserver.m_guildlist.findguild(_guildIndex);
if (!_guild)
return;
if (_status < GMKS_NORMAL || _status > GMKS_RESERVE)
return;
CLCString changeStatusQuery(256);
changeStatusQuery.Format("UPDATE t_extend_guild SET a_kick_status = %d WHERE a_guild_index = %d", _status, _guildIndex);
CDBCmd changeStatusCmd;
changeStatusCmd.Init(&gserver.m_dbchar);
changeStatusCmd.SetQuery(changeStatusQuery);
if (!changeStatusCmd.Update())
return;
_guild->getGuildKick()->setKickStatus(_status);
CNetMsg::SP rmsg(new CNetMsg);
HelperGuildMasterKickStatus(rmsg, _guildIndex, _status);
gserver.SendToAllGameServer(rmsg);
}
| [
"openlastchaos@protonmail.com"
] | openlastchaos@protonmail.com |
e9629d0d5a09335b3b9bc7262570f98e7458f9e6 | fe06b6d602595b147ea4e8bbcbdd2a2e25d6e2ab | /1_star/11577.cpp | 6068ece2c9a3899cd6250f2ff26e2d269b4f17f8 | [] | no_license | lausai/UVa | 8c4a86785d5c561bb9d464466b60bdf4e993757c | fb14b6f9031a449e20830d5f0903a06a8899dfa5 | refs/heads/master | 2022-10-17T12:49:02.561369 | 2022-09-23T03:02:50 | 2022-09-23T03:02:50 | 20,293,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,274 | cpp | #include <cstdio>
#include <cctype>
#include <cstring>
using namespace std;
int main()
{
int num_of_data = 0;
scanf("%d\n", &num_of_data);
for (int i = 0;i < num_of_data; i++) {
char str[256] = {0};
fgets(str, 255, stdin);
const char* eng = "abcdefghijklmnopqrstuvwxyz";
int counter[26] = {0};
int len = strlen(str);
int num_of_appear = 0;
for (int j = 0; j < len; j++) {
if (!isalpha(str[j])) continue;
int pos = 0;
if (isupper(str[j]))
pos = str[j] - 'A';
else
pos = str[j] - 'a';
++counter[pos];
if (counter[pos] > num_of_appear)
num_of_appear = counter[pos];
}
for (int j = 0; j < 26; j++ ) {
if (counter[j] == num_of_appear)
printf("%c", eng[j]);
}
puts("");
}
return 0;
}
| [
"lausai360@gmail.com"
] | lausai360@gmail.com |
e899c32eb117bbf25d47dff2b5a1f9e9d706a2a6 | ad62d5a6236c35d71a647802cf4d6d2ead2558a8 | /src/Rpc/RpcServerConfig.h | 29fbb209c1ec9d71a9c869d42d79c11c9903ea56 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | cycere/quid | 7af570e6d2fd6a8e4cbd5c5253060c76c488bd72 | 889b5bd36339d4e632c07a037db9ba38bf89ea30 | refs/heads/master | 2023-01-21T22:13:08.580206 | 2020-12-01T00:00:40 | 2020-12-01T00:00:40 | 316,043,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 605 | h | // Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2017-2021 The Cycere developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <boost/program_options.hpp>
namespace Quid {
class RpcServerConfig {
public:
RpcServerConfig();
static void initOptions(boost::program_options::options_description& desc);
void init(const boost::program_options::variables_map& options);
std::string getBindAddress() const;
std::string bindIp;
uint16_t bindPort;
};
}
| [
"cycereorg@gmail.com"
] | cycereorg@gmail.com |
81f21393ee48ec9461c3fa9ba6429a230bbe39c7 | f981ae929651ada228fed2dcd183b62b140b2327 | /Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fensterdefinition.cpp | 61e7f1cad2938bca17559932b300ead71a0a5085 | [
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0",
"MIT",
"LGPL-2.1-only",
"EPL-2.0"
] | permissive | supavit-siriwan/carla | 33e34dd9dec997a489092f03491997a479184bfa | bdcb04b9c39c2de2b0f9e654350217898b49dbb7 | refs/heads/master | 2021-07-10T19:15:14.856303 | 2020-11-19T05:51:10 | 2020-11-19T05:51:10 | 213,990,039 | 1 | 0 | MIT | 2020-11-19T05:51:12 | 2019-10-09T18:09:34 | null | UTF-8 | C++ | false | false | 2,243 | cpp | /****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file NIVissimSingleTypeParser_Fensterdefinition.cpp
/// @author Daniel Krajzewicz
/// @author Michael Behrisch
/// @date Fri, 21 Mar 2003
///
//
/****************************************************************************/
#include <config.h>
#include <iostream>
#include <utils/common/StringUtils.h>
#include "../NIImporter_Vissim.h"
#include "../tempstructs/NIVissimSource.h"
#include "NIVissimSingleTypeParser_Fensterdefinition.h"
// ===========================================================================
// method definitions
// ===========================================================================
NIVissimSingleTypeParser_Fensterdefinition::NIVissimSingleTypeParser_Fensterdefinition(NIImporter_Vissim& parent)
: NIImporter_Vissim::VissimSingleTypeParser(parent) {}
NIVissimSingleTypeParser_Fensterdefinition::~NIVissimSingleTypeParser_Fensterdefinition() {}
bool
NIVissimSingleTypeParser_Fensterdefinition::parse(std::istream& from) {
std::string id;
from >> id; // "typ"
std::string type = myRead(from);
if (type == "fzinfo") {
std::string tmp;
from >> tmp;
from >> tmp;
} else if (type == "ldp" || type == "szp") {
std::string tmp;
readUntil(from, "lsa");
}
return true;
}
/****************************************************************************/
| [
"bernatx@gmail.com"
] | bernatx@gmail.com |
9b7f157d3c6001eee7cd92b98895b44055911ddc | 98c9ea8ef935819cd6c957c2ea560a2d97f3dd6b | /LSL/liblsl/lslboost/boost/serialization/nvp.hpp | 0c7e8fd9cd1002d54a52388cdc9fbf7ebc6cb59a | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | gisogrimm/labstreaminglayer | dd9c18f1e50d22df4902a938135c9a958c6bd1c1 | c7b12d1f0f3487a04bba6081be7e5122af10aafe | refs/heads/master | 2020-12-25T00:05:40.953942 | 2018-06-15T12:38:15 | 2018-06-15T12:38:15 | 51,507,985 | 2 | 0 | null | 2018-06-15T12:34:28 | 2016-02-11T10:33:59 | C++ | UTF-8 | C++ | false | false | 3,556 | hpp | #ifndef BOOST_SERIALIZATION_NVP_HPP
#define BOOST_SERIALIZATION_NVP_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// nvp.hpp: interface for serialization system.
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <utility>
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/traits.hpp>
#include <boost/serialization/wrapper.hpp>
namespace lslboost {
namespace serialization {
template<class T>
struct nvp :
public std::pair<const char *, T *>,
public wrapper_traits<const nvp< T > >
{
//private:
nvp(const nvp & rhs) :
std::pair<const char *, T *>(rhs.first, rhs.second)
{}
public:
explicit nvp(const char * name_, T & t) :
// note: added _ to suppress useless gcc warning
std::pair<const char *, T *>(name_, & t)
{}
const char * name() const {
return this->first;
}
T & value() const {
return *(this->second);
}
const T & const_value() const {
return *(this->second);
}
template<class Archive>
void save(
Archive & ar,
const unsigned int /* file_version */
) const {
ar.operator<<(const_value());
}
template<class Archive>
void load(
Archive & ar,
const unsigned int /* file_version */
){
ar.operator>>(value());
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
template<class T>
inline
const nvp< T > make_nvp(const char * name, T & t){
return nvp< T >(name, t);
}
// to maintain efficiency and portability, we want to assign
// specific serialization traits to all instances of this wrappers.
// we can't strait forward method below as it depends upon
// Partial Template Specialization and doing so would mean that wrappers
// wouldn't be treated the same on different platforms. This would
// break archive portability. Leave this here as reminder not to use it !!!
template <class T>
struct implementation_level<nvp< T > >
{
typedef mpl::integral_c_tag tag;
typedef mpl::int_<object_serializable> type;
BOOST_STATIC_CONSTANT(int, value = implementation_level::type::value);
};
// nvp objects are generally created on the stack and are never tracked
template<class T>
struct tracking_level<nvp< T > >
{
typedef mpl::integral_c_tag tag;
typedef mpl::int_<track_never> type;
BOOST_STATIC_CONSTANT(int, value = tracking_level::type::value);
};
} // seralization
} // boost
#include <boost/preprocessor/stringize.hpp>
#define BOOST_SERIALIZATION_NVP(name) \
lslboost::serialization::make_nvp(BOOST_PP_STRINGIZE(name), name)
/**/
#define BOOST_SERIALIZATION_BASE_OBJECT_NVP(name) \
lslboost::serialization::make_nvp( \
BOOST_PP_STRINGIZE(name), \
lslboost::serialization::base_object<name >(*this) \
)
/**/
#endif // BOOST_SERIALIZATION_NVP_HPP
| [
"derstenner@gmail.com"
] | derstenner@gmail.com |
f57d7eb9791ef73407d06de862401a5c6867a0de | 8ae31e5db1f7c25b6ce1c708655ab55c15dde14e | /比赛/学校/2019-10-26测试/source/std/city/city2.cpp | ebff9e60220762031615af03e7ef15b4039836e1 | [] | no_license | LeverImmy/Codes | 99786afd826ae786b5024a3a73c8f92af09aae5d | ca28e61f55977e5b45d6731bc993c66e09f716a3 | refs/heads/master | 2020-09-03T13:00:29.025752 | 2019-12-16T12:11:23 | 2019-12-16T12:11:23 | 219,466,644 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,610 | cpp | #include<bits/stdc++.h>
using namespace std;
const int N=305;
int n,m,res[N],ans[N][N],a[N*N],cnt;
bool use[N*N];
int read()
{
char c=getchar(); int f=1,x=0;
while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
while (isdigit(c)) {x=x*10+c-'0'; c=getchar();}
return f*x;
}
void check(int x)
{
memset(use,false,sizeof(use));
if((a[1]+a[2]+a[x])&1)return;
res[1]=(a[1]+a[2]+a[x])/2-a[x];
res[2]=a[1]-res[1];
res[3]=a[2]-res[1];
use[1]=use[2]=use[x]=true;
for(int i=4,j=3;i<= n; ++i)
{
while(j<=m&&use[j]) j++;
if(j>m) return;
res[i]=a[j]-res[1];
use[j]=true;
for(int k=2;k<i;++k)
{
if(res[k]>res[i]) return;
int v=res[k]+res[i];
int p=lower_bound(a+1,a+m+1,v)-a;
if(a[p]!=v) return;
int px=p;
while(px&&a[px]==a[p]) px--;
px++;
while(px<=m&&a[px]==a[p]&&use[px]) px++;
if(a[px]!=a[p]||use[px]) return;
p=px;
use[p]=true;
}
}
cnt++;
for(int i=1;i<=n;++i) ans[cnt][i] = res[i];
}
int main()
{
freopen("city.in","r",stdin);
freopen("city.out","w",stdout);
n=read();
m=n*(n-1)/2;
for(int i=1;i<=m;++i) a[i]=read();
sort(a+1,a+m+1);
for(int i=3;i<=m;)
{
check(i);
int j=i;
while(j<=m&&a[j]==a[i]) j++;
i=j;
}
printf("%d\n",cnt);
for(int i=1;i<=cnt;++i)
for(int j=1;j<=n;++j)
{
printf("%d",ans[i][j]);
if(j==n) printf("\n");
else printf(" ");
}
return 0;
}
| [
"506503360@qq.com"
] | 506503360@qq.com |
7016951bd42d12e31e8df8e50b2137d84814597b | fc56fa52dcd40a640237be19b3faeb7c4339f4ea | /meta-heuristics-1.3/meta-heuristics-1.3/EDA/edaSeqWorker.h | 1ef7ea7351f30f08b5ec1c646165e90b044461ca | [] | no_license | nghiabui/Metaheuristic | 592e9b4c25cfd11f5fa610031141c6b8186f90fb | 9852941f9fde6981a15e1897b046b07f205d0adb | refs/heads/master | 2021-01-10T18:49:27.746091 | 2015-08-20T02:44:48 | 2015-08-20T02:44:48 | 40,337,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | h | /*
* File: edaSeqWorker.h
* Author: Tieu Minh
*
* Created on April 11, 2014, 11:31 AM
*/
#ifndef EDASEQWORKER_H
#define EDASEQWORKER_H
#include "edaObject.h"
#include "edaBuffer.h"
#include "edaSearch.h"
class edaSeqWorker : public edaObject
{
public:
edaSeqWorker() :_search(NULL)
{
}
virtual ~edaSeqWorker()
{
easerObject(_search);
}
virtual void set( edaBuffer &buf )
{
easerObject(_search);
_search = (edaSearch*)unpack( buf );
}
virtual void search( edaBuffer& buf_pro, edaBuffer& buf_in, edaBuffer& buf_out )
{
// Create new problem object
edaProblem *problem = (edaProblem*)unpack( buf_pro );
// Create new solution object
edaPopulation *pop = (edaPopulation*)unpack( buf_in );
// Set the problem for population
pop->reconfig(problem);
// Call search algorithm
_search->search( *pop );
// pack output solution
pop->pack( buf_out);
// Clean up
easerObject(pop);
easerObject(problem);
}
virtual const char* className() const
{
return "edaSeqWorker";
}
protected:
edaSearch *_search;
};
#endif /* EDASEQWORKER_H */
| [
"buitrungngnhia_2310@yahoo.com.vn"
] | buitrungngnhia_2310@yahoo.com.vn |
2664eea26d825f824732ec703f1369db6e244a8a | 250fb2c3c0926aec2e67924e631c8b17f5b78611 | /codeforces.com/abby/e1.cpp | f3a580fbf6bc1e95295bc8bef20c65f94d065d19 | [] | no_license | bayram53/online-judge | bc30b4bdb81ce20dff3c86cac1452f8cfdc26747 | de333b60cb78c956a51a0ebdd25ef6e399d2a2d7 | refs/heads/master | 2021-05-26T13:29:58.378783 | 2013-12-13T08:57:01 | 2013-12-13T08:57:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | cpp | # include <stdio.h>
# include <iostream>
# define mod 1000000000
using namespace std;
typedef long long llint;
int n,m,a,b,k;
char c;
llint d[109];
llint f[200009];
int main()
{
f[0] = f[1] = 1;
for(int h=2; h<200001; h++) f[h] = f[h-1]+f[h-2] , f[h] %= mod;
scanf("%d %d",&n,&m);
for(int h=1; h<=n; h++) cin>>d[h];
for(int h=0; h<m; h++)
{
scanf("%d",&k);
c = '-';
if(k == 1)
{
while(c != '\n')
{
scanf("%d %d%c",&a,&b,&c);
d[a] = b;
}
}
if(k == 2)
{
while(c != '\n')
{
scanf("%d %d%c",&a,&b,&c);
llint ans = 0;
for(int h=a; h<=b; h++)
ans += (f[h-a]*d[h])%mod;
cout<<ans%mod<<endl;
}
}
}
}
| [
"berdiyevbayram@gmail.com"
] | berdiyevbayram@gmail.com |
09bf60c351fe16a53f9e11796e7927b8139e6ddc | 1302a788aa73d8da772c6431b083ddd76eef937f | /WORKING_DIRECTORY/system/connectivity/shill/mock_connection_health_checker.h | 062c6bb1f6d0a82f82a154405425182f054ca09f | [
"Apache-2.0"
] | permissive | rockduan/androidN-android-7.1.1_r28 | b3c1bcb734225aa7813ab70639af60c06d658bf6 | 10bab435cd61ffa2e93a20c082624954c757999d | refs/heads/master | 2021-01-23T03:54:32.510867 | 2017-03-30T07:17:08 | 2017-03-30T07:17:08 | 86,135,431 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,523 | h | //
// Copyright (C) 2013 The Android Open Source Project
//
// 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 SHILL_MOCK_CONNECTION_HEALTH_CHECKER_H_
#define SHILL_MOCK_CONNECTION_HEALTH_CHECKER_H_
#include <string>
#include <gmock/gmock.h>
#include "shill/connection_health_checker.h"
namespace shill {
class MockConnectionHealthChecker : public ConnectionHealthChecker {
public:
MockConnectionHealthChecker(
ConnectionRefPtr connection,
EventDispatcher* dispatcher,
IPAddressStore* remote_ips,
const base::Callback<void(Result)>& result_callback);
~MockConnectionHealthChecker() override;
MOCK_METHOD1(AddRemoteURL, void(const std::string& url_string));
MOCK_METHOD1(AddRemoteIP, void(IPAddress ip));
MOCK_METHOD0(Start, void());
MOCK_METHOD0(Stop, void());
MOCK_CONST_METHOD0(health_check_in_progress, bool());
private:
DISALLOW_COPY_AND_ASSIGN(MockConnectionHealthChecker);
};
} // namespace shill
#endif // SHILL_MOCK_CONNECTION_HEALTH_CHECKER_H_
| [
"duanliangsilence@gmail.com"
] | duanliangsilence@gmail.com |
c912c17c2892f111bce59f39219f8a0b69a24dd6 | b0cbf0f3f537cfe9f1985ce0c5ef9606718900ee | /NvrControl/NvrControl/C_constDef.h | b28cc8c8d97a1a2619876bf67db6cbf918ce55e6 | [] | no_license | shifuxiang/NvrControl | d9b8a48d48cdf4ebad65b5a75b4cc8e6c7bd3d98 | 38bd7c943fc31e369eee4c84bc3e40b20ccdd8e2 | refs/heads/master | 2020-12-30T18:02:37.460316 | 2017-06-23T07:27:36 | 2017-06-23T07:27:36 | 90,943,528 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 7,388 | h | //@file:C_constDef.h
//@brief: 包含各种状态信息定义。
//@author:luyan@oristartech.com
//dade:2014-09-12
#ifndef IMONITOR_CONST_DEFINE
#define IMONITOR_CONST_DEFINE
#include "threadManage/C_CS.h"
#include <vector>
#include <string>
#include <map>
//const define
// 线程池中线程的个数。
const int THREAD_COUNT_IN_POOL = 20;
//任务ID
const int TASK_NUMBER_GET_DISK_STATUS = 0x0101;
const int TASK_NUMBER_GET_NET_STATUS = 0x0102;
const int TASK_NUMBER_DISPATCH_ROUTINE = 0x0201;
const int TASK_NUMBER_GET_HALL_STATUS = 0x0301;
const int TASK_NUMBER_GET_TMS_STATUS = 0x0401;
const int TASK_NUMBER_GET_OTHERMONITOR_STATUS = 0x0501;
const int TASK_NUMBER_GET_OTHERMONITOR_TMS_STATUS = 0x0502;
const int TASK_NUMBER_GET_OTHERMONITOR_SMS_STATUS = 0x0503;
const int TASK_NUMBER_GET_OTHERMONITOR_RAID_STATUS = 0x0504;
const int TASK_NUMBER_GET_OTHERMONITOR_ETH_STATUS = 0x0505;
const int TASK_NUMBER_GET_OTHERMONITOR_SWITCH_STATUS = 0x0506;
const int TASK_NUMBER_GET_OTHERMONITOR_SPEEDLIMIT_STATUS = 0x0507;
const int TASK_NUMBER_GET_OTHERMONITOR_SMSEW_STATUS = 0x0508;
const int TASK_NUMBER_GET_DB_SYNCN_STATUS = 0x0509;
const int TASK_NUMBER_PROCESS_USERINPUT = 0x0601;
const int TASK_NUMBER_CONDSWITCH_ROUTINE = 0x0701;
const int TASK_NUMBER_HASHCHECK_ROUTINE = 0x0801;
const int TASK_NUMBER_FILEOPERATION_ROUTINE = 0x0901;
const int TASK_NUMBER_REBOOT = 0x0902;
const int TASK_NUMBER_SHUTDOWN = 0x0903;
const int TASK_NUMBER_CHECKWATCHDOG = 0x0904;
// sms 状态
const int SMS_STATE_SUCCESS = 101 ; // 连接正常
const int SMS_STATE_ERROR = 102; // 连接异常 / 连接超时
const int SMS_STATE_SYSERROR =103 ; // 系统异常
// sms 播放状态:
const int SMS_STATE_PLAYING = 201; // 正在播放
const int SMS_STATE_PAUSING = 202; // 暂停播放
const int SMS_STATE_FINISHED = 203; // 停止播放
const int SMS_STATE_FINISHED_ABORT = 204; // 手动停止
const int SMS_STATE_FINISHED_ERROR = 205; // 播放失败
const int SMS_STATE_NOT_EXECUTED = 206; // 不再执行
// sms ingest job 状态
const int SMS_STATE_INGEST_SCHEULED = 301; // 等待导入
const int SMS_STATE_INGEST_RUNNING = 302; // 正在导入
const int SMS_STATE_INGEST_PAUSING = 303; // 暂停导入
const int SMS_STATE_INGEST_CHECK = 304; // 导入检查
const int SMS_STATE_INGEST_FINISHED = 305; // 导入成功
const int SMS_STATE_INGEST_FINISHED_ERROR = 306;// 导入失败
// sms cpl check状态
const int SMS_STATE_CPL = 401; // 等待验证
const int SMS_STATE_CPL_RUNNING = 402; // 正在验证
const int SMS_STATE_CPL_PAUSING = 403; // 暂停验证
const int SMS_STATE_CPL_FINISHED = 404; // 验证成功
const int SMS_STATE_CPL_FINISHED_ERROR = 405; // 验证失败
//日志级别。
const int ULOG_DEBUG = 0;
const int ULOG_INFO = 1;
const int ULOG_ERROR = 2;
const int ULOG_FATAL = 3;
const int UDEFAULT_LOG_LEVEL = 0;
//日志所属模块
const int LOG_MODEL_THREADMGR = 1;
const int LOG_MODEL_TIMETASK = 2;
const int LOG_MODEL_DB = 3;
const int LOG_MODEL_WEBS = 4;
const int LOG_MODEL_JOBS = 5;
const int LOG_MODEL_OTHER = 6;
const int LOG_MODEL_LOGMGR = 7;
// 线程状态。
enum Thread_State
{
INIT_STATE = 0, //初始
RUN_STATE = 1, //运行
SUSPEND_IDL_STATE = 2, //空闲
SUSPEND_FINISH_STATE = 3,//操作执行完成而暂停。
RUN_LOCKED_STATE = 4, // 运行时锁定。
SUSPEND_LOCKED_STATE = 5 ,// 暂停时锁定。
QUIT_STATE =6 // 线程结束。
};
// 线程运行类型,用于区分线程执行操作的类型。
enum Thread_Run_Type
{
RUN_WEBSERVICE_TYPE = 0, //线程正在执行Webservice调用。
RUN_TIMETASK_TYPE = 1, // 线程正在执行定时任务。
RUN_UNKNOWN_TYPE = 2 // 线程未执行操作。
};
// 任务类型
enum TASK_TYPE
{
NULL_TASK,// 空
TIME_TASK,// 定时任务
ONCE_TASK,// 一次任务
ALWAYS_TASK// 固定任务
};
// 任务状态;
enum TASK_STATE
{
//空闲
TASK_IDLE_STATE = 0,
// 任务未开始执行
TASK_NO_STATE =1,
// 任务正在执行。
TASK_RUNNING_STATE = 2,
// 任务执行完成。
TASK_FINISH_STATE = 3,
// 任务需要被删除
TASK_DELETE_STATE = 4,
//空闲时被锁定
TASK_LOCKED_STATE = 5
};
// RAID状态
typedef struct DiskInfo
{
std::string diskGroup;
std::string diskSize;
std::string diskState;
std::string diskNumOfDrives;
std::map<std::string ,struct DiskDriveInfo> diskDrives;
}DiskInfo;
typedef struct DiskDriveInfo
{
int group ;
std::string driveID;
std::string drivePosition;
std::string driveSlotNum;
std::string driveErrorCount;
std::string driveSize;
std::string driveFirmwareState;
std::string driveSpeed;
std::string driveType;
DiskDriveInfo():group(-1)
{}
DiskDriveInfo(const DiskDriveInfo &obj)
{
group=obj.group;
driveID=obj.driveID;
drivePosition=obj.drivePosition;
driveSlotNum=obj.driveSlotNum;
driveErrorCount=obj.driveErrorCount;
driveSize=obj.driveSize;
driveFirmwareState=obj.driveFirmwareState;
driveSpeed=obj.driveSpeed;
driveType=obj.driveType;
}
DiskDriveInfo & operator =(const DiskDriveInfo &obj)
{
if(this != &obj)
{
group=obj.group;
driveID=obj.driveID;
drivePosition=obj.drivePosition;
driveSlotNum=obj.driveSlotNum;
driveErrorCount=obj.driveErrorCount;
driveSize=obj.driveSize;
driveFirmwareState=obj.driveFirmwareState;
driveSpeed=obj.driveSpeed;
driveType=obj.driveType;
}
return *this;
}
}DiskDriveInfo;
// 故障
struct stError
{
stError():
nOrdinal(-1)
{}
int nOrdinal;
std::string ErrorName;
std::string ErrorVal;
};
// 网卡状态
struct EthStatus
{
std::string strName;
int nTaskType;
int nConnStatue;
unsigned long long nRxSpeed;
unsigned long long nTxSpeed;
EthStatus():
nConnStatue(0),
nRxSpeed(0),
nTxSpeed(0),
nTaskType(-1)
{
}
};
// SMS状态
struct SMSStatus
{
std::string hallid;
int nStatus;
int nRun; //0:本机没有运行 1:本机运行,2:另一台运行 3:另一台也没有运行
int nPosition;
std::string strSPLUuid;
SMSStatus():
nStatus(-1)
,nRun(0)
,nPosition(-1)
{
}
SMSStatus(const SMSStatus &obj)
{
hallid = obj.hallid;
nStatus = obj.nStatus;
nRun = obj.nRun;
nPosition = obj.nPosition;
strSPLUuid = obj.strSPLUuid;
}
SMSStatus& operator=(const SMSStatus &obj)
{
if(this != &obj)
{
hallid = obj.hallid;
nStatus = obj.nStatus;
nRun = obj.nRun;
nPosition = obj.nPosition;
strSPLUuid = obj.strSPLUuid;
}
return *this;
}
};
// SMS参数
struct SMSInfo
{
std::string strId; // 标识id或序列号
std::string strIp; // 通信的ip地址
int nPort ; // 通信的端口
int nRole; // 角色,是主要运行角色还是候选角色 1:为主机运行,2:为备机运行 3:接管运行
std::string strExepath;// sms执行文件路径
std::string strConfpath;// 配置文件路径
SMSStatus stStatus;
SMSInfo():
nPort(-1)
,nRole(-1)
{}
SMSInfo(const SMSInfo &obj)
{
strId = obj.strId;
strIp = obj.strIp;
nPort = obj.nPort;
nRole = obj.nRole;
strExepath = obj.strExepath;
strConfpath = obj.strConfpath;
stStatus = obj.stStatus;
}
SMSInfo& operator =(const SMSInfo &obj)
{
if(this != &obj)
{
strId = obj.strId;
strIp = obj.strIp;
nPort = obj.nPort;
nRole = obj.nRole;
strExepath = obj.strExepath;
strConfpath = obj.strConfpath;
stStatus = obj.stStatus;
}
return *this;
}
};
#endif
| [
"591317029@qq.com"
] | 591317029@qq.com |
270b0bae251f4f5fe8a606adb4b852ed06735b71 | 8f02939917edda1e714ffc26f305ac6778986e2d | /BOJ/8094/main.cc | 71b1742974522fe540a5b80d6840864613083b44 | [] | no_license | queuedq/ps | fd6ee880d67484d666970e7ef85459683fa5b106 | d45bd3037a389495d9937afa47cf0f74cd3f09cf | refs/heads/master | 2023-08-18T16:45:18.970261 | 2023-08-17T17:04:19 | 2023-08-17T17:04:19 | 134,966,734 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | cc | #include <bits/stdc++.h>
#define endl "\n"
using namespace std;
using lld = long long;
using pii = pair<int, int>;
using pll = pair<lld, lld>;
////////////////////////////////////////////////////////////////
int n, w, cnt[201];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
////////////////////////////////
cin >> w >> n;
for (int i=0; i<n; i++) {
int t; cin >> t;
cnt[t]++;
}
int ans = 0;
for (int i=1; i<=w; i++) {
while (cnt[i] > 0) {
cnt[i]--;
ans++;
int j = w-i;
while (j > 0 && cnt[j] == 0) j--;
if (j > 0) cnt[j]--;
}
}
cout << ans << endl;
////////////////////////////////
return 0;
}
| [
"queued37@gmail.com"
] | queued37@gmail.com |
6ac602cb71c3370fb5bde3e170138f77ef8e80f3 | 2a7b6bcc05a71a65caf48aa05de5d590811d4c81 | /include/deemon/cxx/set.h | e5b9633f1ba57ff15fe25ac8a52059d7c9d11ee3 | [
"Zlib"
] | permissive | GrieferAtWork/deemon | 339281627990604fd0acfc534b8fb7751d84894e | 3f9cd7ae815b8b42bd931d9d3ef6adf5656ca074 | refs/heads/master | 2023-08-31T09:33:57.382088 | 2023-08-19T15:14:13 | 2023-08-19T15:14:13 | 143,714,050 | 10 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,653 | h | /* Copyright (c) 2018-2023 Griefer@Work *
* *
* 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 acknowledgement (see the following) in the product *
* documentation is required: *
* Portions Copyright (c) 2018-2023 Griefer@Work *
* 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. *
*/
#ifndef GUARD_DEEMON_CXX_SET_H
#define GUARD_DEEMON_CXX_SET_H 1
#include "api.h"
/**/
#include "object.h"
#include "sequence.h"
/**/
#include "../set.h"
DEE_CXX_BEGIN
template<class T = Object>
class Set: public Sequence<T> {
public:
static WUNUSED Type &classtype() DEE_CXX_NOTHROW {
return *(Type *)&DeeSet_Type;
}
static WUNUSED NONNULL_CXX((1)) bool check(DeeObject *ob) DEE_CXX_NOTHROW {
return DeeObject_InstanceOf(ob, &DeeSet_Type);
}
static WUNUSED NONNULL_CXX((1)) bool checkexact(DeeObject *ob) DEE_CXX_NOTHROW {
return DeeObject_InstanceOfExact(ob, &DeeSet_Type);
}
public:
static NONNULL_CXX((1)) Ref<Set<T> > of() DEE_CXX_NOTHROW {
return nonnull(Dee_EmptySet);
}
public:
/*[[[deemon (CxxType from rt.gen.cxxapi)(Set from deemon).printCxxApi(templateParameters: { "T" });]]]*/
WUNUSED NONNULL_CXX((1)) Ref<Set<T> > (difference)(DeeObject *to) {
DeeObject *args[1];
args[0] = to;
return inherit(DeeObject_CallAttrStringHash(this, "difference", _Dee_HashSelectC(0xe944baff, 0x6add28d83d2e1f6e), 1, args));
}
WUNUSED NONNULL_CXX((1)) Ref<Set<T> > (intersection)(DeeObject *with_) {
DeeObject *args[1];
args[0] = with_;
return inherit(DeeObject_CallAttrStringHash(this, "intersection", _Dee_HashSelectC(0xabaa0afa, 0xc72d025e185198b7), 1, args));
}
WUNUSED NONNULL_CXX((1)) Ref<deemon::bool_> (isdisjoint)(DeeObject *with_) {
DeeObject *args[1];
args[0] = with_;
return inherit(DeeObject_CallAttrStringHash(this, "isdisjoint", _Dee_HashSelectC(0x4b97e75a, 0x14d2b48b4b9da607), 1, args));
}
WUNUSED NONNULL_CXX((1)) Ref<Set<T> > (union_)(DeeObject *with_) {
DeeObject *args[1];
args[0] = with_;
return inherit(DeeObject_CallAttrStringHash(this, "union", _Dee_HashSelectC(0x23b88b9b, 0x3b416e7d690babb2), 1, args));
}
WUNUSED NONNULL_CXX((1)) Ref<Set<T> > (symmetric_difference)(DeeObject *with_) {
DeeObject *args[1];
args[0] = with_;
return inherit(DeeObject_CallAttrStringHash(this, "symmetric_difference", _Dee_HashSelectC(0x9a1e5057, 0x17b1425a414674d3), 1, args));
}
WUNUSED NONNULL_CXX((1)) Ref<deemon::bool_> (issubset)(DeeObject *of) {
DeeObject *args[1];
args[0] = of;
return inherit(DeeObject_CallAttrStringHash(this, "issubset", _Dee_HashSelectC(0xac6aa1c0, 0x49ece9bed26428cf), 1, args));
}
WUNUSED NONNULL_CXX((1)) Ref<deemon::bool_> (issuperset)(DeeObject *of) {
DeeObject *args[1];
args[0] = of;
return inherit(DeeObject_CallAttrStringHash(this, "issuperset", _Dee_HashSelectC(0x55780f5f, 0x7f578be05d081a7f), 1, args));
}
class _Wrap_frozen
: public deemon::detail::ConstGetRefProxy<_Wrap_frozen, Set<T> > {
private:
DeeObject *m_self; /* [1..1] Linked object */
public:
_Wrap_frozen(DeeObject *self) DEE_CXX_NOTHROW
: m_self(self) {}
WUNUSED DREF DeeObject *_getref() const DEE_CXX_NOTHROW {
return DeeObject_GetAttrStringHash(m_self, "frozen", _Dee_HashSelectC(0x82311b77, 0x7b55e2e6e642b6fd));
}
WUNUSED bool bound() const {
return throw_if_minusone(DeeObject_BoundAttrStringHash(m_self, "frozen", _Dee_HashSelectC(0x82311b77, 0x7b55e2e6e642b6fd)));
}
};
WUNUSED _Wrap_frozen (frozen)() {
return this;
}
/*[[[end]]]*/
};
DEE_CXX_END
#endif /* !GUARD_DEEMON_CXX_SET_H */
| [
"GrieferAtWork@users.noreply.github.com"
] | GrieferAtWork@users.noreply.github.com |
1f1c8ed404551446a67b91ea45032d2ff301aa6a | 7b6a3645ecb98f7a820cd1345250a3d85424a20f | /transient_rendering_cython/smoothed_transient/stratifiedStreamedTransientRenderer.cpp | 40db0fa56d6e68f82b063eace7138ec7d18594b2 | [] | no_license | cmu-ci-lab/nlos_surface_optimization | d506f643fbcf863b29012d5d35614c9f00b67e13 | a61f76d7c09a4bf5e05961694cb0ca849ac1fd2c | refs/heads/master | 2020-06-03T05:14:45.513729 | 2019-10-13T01:05:49 | 2019-10-13T01:05:49 | 191,455,676 | 18 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 5,091 | cpp | /*
* stratifiedStreamedTransientRenderer.cpp
*
* Created on: Aug 28, 2018
* Author: igkiou
*/
#include "stratifiedStreamedTransientRenderer.h"
/* include embree API */
#include <embree3/rtcore.h>
#include "transient_and_gradient.h"
using namespace embree;
/* vertex and triangle layout */
struct Vertex { float x,y,z,r; }; // FIXME: rename to Vertex4f
struct Triangle { int v0, v1, v2; };
void streamed_render_intensity(float* originD, int numSources, float* normalD, float* verticesD, int numVertices, float* vertexNormal, int* trianglesD, int numTriangles, int numSamples, float pathlengthLowerBound, float pathlengthUpperBound, double* intensity) {
/* start embree device */
RTCDevice g_device = rtcNewDevice(nullptr);
/* scene data */
RTCScene g_scene = rtcNewScene(g_device);
RTCGeometry mesh = rtcNewGeometry(g_device, RTC_GEOMETRY_TYPE_TRIANGLE);
/* set vertices */
Vertex *vertices = (Vertex *) rtcSetNewGeometryBuffer(
mesh, RTC_BUFFER_TYPE_VERTEX, 0,
RTC_FORMAT_FLOAT3, sizeof(Vertex), numVertices);
for (size_t iterVertex = 0; iterVertex < numVertices; ++iterVertex) {
vertices[iterVertex] = {
verticesD[iterVertex * 3],
verticesD[iterVertex * 3 + 1],
verticesD[iterVertex * 3 + 2]
};
}
/* set triangles */
Triangle *triangles = (Triangle *) rtcSetNewGeometryBuffer(
mesh, RTC_BUFFER_TYPE_INDEX, 0,
RTC_FORMAT_UINT3, sizeof(Triangle), numTriangles);
for (size_t iterTriangle = 0; iterTriangle < numTriangles; ++iterTriangle) {
triangles[iterTriangle] = {
trianglesD[iterTriangle * 3],
trianglesD[iterTriangle * 3 + 1],
trianglesD[iterTriangle * 3 + 2]
};
}
rtcCommitGeometry(mesh);
rtcAttachGeometry(g_scene, mesh);
rtcReleaseGeometry(mesh);
/* set scene parameters */
rtcSetSceneBuildQuality(g_scene, RTC_BUILD_QUALITY_HIGH);
/* commit changes to scene */
rtcCommitScene(g_scene);
render_intensity(numSources,
numTriangles,
g_device,
g_scene,
originD,
normalD,
verticesD,
trianglesD,
vertexNormal,
pathlengthLowerBound,
pathlengthUpperBound,
numSamples,
intensity);
rtcReleaseScene(g_scene); g_scene = nullptr;
rtcReleaseDevice(g_device);
}
void streamed_render_transient(float* originD, int numSources, float* normalD, float* verticesD, int numVertices, float* vertexNormal, float* vertexAlbedo, int* trianglesD, int numTriangles, int numSamples, float pathlengthLowerBound, float pathlengthUpperBound, float pathlengthResolution, double* transient, double *pathlengths, int refine_scale, int sigma_bin) {
/* start embree device */
RTCDevice g_device = rtcNewDevice(nullptr);
/* scene data */
RTCScene g_scene = rtcNewScene(g_device);
RTCGeometry mesh = rtcNewGeometry(g_device, RTC_GEOMETRY_TYPE_TRIANGLE);
/* set vertices */
Vertex *vertices = (Vertex *) rtcSetNewGeometryBuffer(
mesh, RTC_BUFFER_TYPE_VERTEX, 0,
RTC_FORMAT_FLOAT3, sizeof(Vertex), numVertices);
for (size_t iterVertex = 0; iterVertex < numVertices; ++iterVertex) {
vertices[iterVertex] = {
verticesD[iterVertex * 3],
verticesD[iterVertex * 3 + 1],
verticesD[iterVertex * 3 + 2]
};
}
/* set triangles */
Triangle *triangles = (Triangle *) rtcSetNewGeometryBuffer(
mesh, RTC_BUFFER_TYPE_INDEX, 0,
RTC_FORMAT_UINT3, sizeof(Triangle), numTriangles);
for (size_t iterTriangle = 0; iterTriangle < numTriangles; ++iterTriangle) {
triangles[iterTriangle] = {
trianglesD[iterTriangle * 3],
trianglesD[iterTriangle * 3 + 1],
trianglesD[iterTriangle * 3 + 2]
};
}
rtcCommitGeometry(mesh);
rtcAttachGeometry(g_scene, mesh);
rtcReleaseGeometry(mesh);
/* set scene parameters */
rtcSetSceneBuildQuality(g_scene, RTC_BUILD_QUALITY_HIGH);
/* commit changes to scene */
rtcCommitScene(g_scene);
const int32_t numBins = (int32_t) embree::ceil((pathlengthUpperBound - pathlengthLowerBound)
/ pathlengthResolution);
for (int32_t iterBin = 0; iterBin < numBins; ++iterBin) {
pathlengths[iterBin] =
(double) (pathlengthLowerBound + iterBin * pathlengthResolution);
}
render_smoothed_transients(numBins,
numSources,
refine_scale,
sigma_bin,
numTriangles,
g_device,
g_scene,
originD,
normalD,
verticesD,
trianglesD,
vertexNormal,
vertexAlbedo,
pathlengthLowerBound,
pathlengthUpperBound,
pathlengthResolution,
numSamples,
transient);
rtcReleaseScene(g_scene); g_scene = nullptr;
rtcReleaseDevice(g_device);
}
| [
"igkiou@gmail.com"
] | igkiou@gmail.com |
90ca6a494fda0f49b028932bcd277627d255911c | 797183a612a81f7acd261f1a42da0866c5896929 | /Questions/RotateImage/RotateImage.cpp | ca0b1c03c6f0889481d0db6a712b7b830ffdcbe5 | [] | no_license | ArronLin/LeetCode | bd1812fc7b48f4872943c47c9869232a884987ce | b3de62cf63ff90eb567f70b6f7e9f32834ca5cc1 | refs/heads/master | 2016-09-06T00:53:08.317925 | 2015-05-07T09:58:01 | 2015-05-07T09:58:01 | 30,632,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | cpp | #include "common.h"
class RotateImage {
public:
void rotate(vector<vector<int> > &matrix) {
int rows = matrix.size();
if(rows == 0) return;
int cols = matrix[0].size();
if(cols == 0 || rows != cols) return;
for(int ilevel = 0; ilevel < rows / 2; ++ ilevel) {
int lCount = rows - 1 - 2 * ilevel;
for(int i = 0; i < lCount; ++i) {
//caculate the positions
int topr = ilevel;
int topc = ilevel + i;
int rightr = ilevel + i;
int rightc = cols - 1 - ilevel;
int downr = rows - 1 - ilevel;
int downc = cols - 1 - ilevel - i;
int leftr = rows - 1 - ilevel - i;
int leftc = ilevel;
//swap them
int temp = matrix[topr][topc];
matrix[topr][topc] = matrix[leftr][leftc];
matrix[leftr][leftc] = matrix[downr][downc];
matrix[downr][downc] = matrix[rightr][rightc];
matrix[rightr][rightc] = temp;
}
}
}
}; | [
"linmartrix@163.com"
] | linmartrix@163.com |
edbdd91927c53b476989ee7b2a1367502ac839e7 | f0a323bdffc2ff978ffb3f8b8aeb8355215ba976 | /src/phase/signals/SignalMask.hpp | 1ad5201bbe54aaa3a5555805dfe72c5c9b3a9c54 | [] | no_license | unsip/cpp_study | 49e43d13cf5f73909ba7f91a67513a6d0c19aa89 | 183b7a70816a44e5cb2647249a4261aef65192b7 | refs/heads/master | 2021-10-25T23:10:47.487821 | 2021-10-24T21:11:20 | 2021-10-24T21:11:20 | 192,588,958 | 0 | 1 | null | 2021-10-08T23:08:04 | 2019-06-18T17:59:01 | C++ | UTF-8 | C++ | false | false | 886 | hpp | #pragma once
#include <memory>
namespace phase::signals {
namespace Sig {
// TODO: Extend signal set.
// Note: Should be the same order as sig_mapping (see cpp).
enum Sig
{
interupt = 0
, terminate = 1
};
namespace detail {
struct AllSignalsTag {};
struct NoSignalsTag {};
} // namespace phase::signals::Sig::detail
constexpr detail::AllSignalsTag all;
constexpr detail::NoSignalsTag none;
} // namespace phase::signals::Sig
class SignalMask
{
struct Impl;
SignalMask();
std::unique_ptr<Impl> m_impl;
public:
SignalMask(std::initializer_list<Sig::Sig> signals);
SignalMask(Sig::detail::AllSignalsTag);
SignalMask(Sig::detail::NoSignalsTag);
SignalMask(const SignalMask&) = delete;
SignalMask& operator =(const SignalMask&) = delete;
~SignalMask();
void lock() noexcept;
void unlock() noexcept;
};
} // namespace phase::signals
| [
"unsip@protonmail.com"
] | unsip@protonmail.com |
545cbed5e7020a5cd49e77df93da7986bf7842df | 3303311159acd506337eccc0f59ab6a7dc141141 | /src/extensions/ewcMqtt.cpp | fa66ff8d2b55712e767a5ca8405d016fd3fb13a5 | [
"Apache-2.0"
] | permissive | atiderko/espwebconfig | ae6c40220dbf16305c652e7000be3268d58cacd9 | 756deb3b26ffe7950e2f8eab2591a420a40a7e01 | refs/heads/master | 2023-01-07T15:42:12.142469 | 2020-11-01T13:28:41 | 2020-11-01T13:28:41 | 294,080,157 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,746 | cpp | /**************************************************************
This file is a part of
https://github.com/atiderko/espwebconfig
Copyright [2020] Alexander Tiderko
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 "ewcMqtt.h"
#include "ewcConfigServer.h"
#include <ArduinoJSON.h>
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#else
#include <WiFi.h>
#endif
#include "generated/mqttSetupHTML.h"
#include "generated/mqttStateHTML.h"
using namespace EWC;
Mqtt::Mqtt() : ConfigInterface("mqtt")
{
}
Mqtt::~Mqtt()
{
}
void Mqtt::setup(JsonDocument& config, bool resetConfig)
{
I::get().logger() << F("[EWC Mqtt] setup") << endl;
_initParams();
_fromJson(config);
EWC::I::get().server().insertMenuG("MQTT", "/mqtt/setup", "menu_mqtt", FPSTR(PROGMEM_CONFIG_TEXT_HTML), HTML_MQTT_SETUP_GZIP, sizeof(HTML_MQTT_SETUP_GZIP), true, 0);
EWC::I::get().server().webserver().on("/mqtt/config.json", std::bind(&Mqtt::_onMqttConfig, this, &EWC::I::get().server().webserver()));
EWC::I::get().server().webserver().on("/mqtt/config/save", std::bind(&Mqtt::_onMqttSave, this, &EWC::I::get().server().webserver()));
EWC::I::get().server().webserver().on("/mqtt/state.html", std::bind(&ConfigServer::sendContentG, &EWC::I::get().server(), &EWC::I::get().server().webserver(), FPSTR(PROGMEM_CONFIG_TEXT_HTML), HTML_MQTT_STATE_GZIP, sizeof(HTML_MQTT_STATE_GZIP)));
EWC::I::get().server().webserver().on("/mqtt/state.json", std::bind(&Mqtt::_onMqttState, this, &EWC::I::get().server().webserver()));
_mqttClient.onConnect(std::bind(&Mqtt::_onMqttConnect, this, std::placeholders::_1));
_mqttClient.onDisconnect(std::bind(&Mqtt::_onMqttDisconnect, this, std::placeholders::_1));
_wifiConnectHandler = WiFi.onStationModeGotIP(std::bind(&Mqtt::_onWifiConnect, this, std::placeholders::_1));
_wifiDisconnectHandler = WiFi.onStationModeDisconnected(std::bind(&Mqtt::_onWifiDisconnect, this, std::placeholders::_1));
}
void Mqtt::fillJson(JsonDocument& config)
{
config["mqtt"]["enabled"] = paramEnabled;
config["mqtt"]["server"] = _paramServer;
config["mqtt"]["port"] = _paramPort;
config["mqtt"]["user"] = _paramUser;
config["mqtt"]["pass"] = _paramPassword;
config["mqtt"]["prefix"] = paramDiscoveryPrefix;
}
void Mqtt::_initParams()
{
paramEnabled = false;
_paramServer = "";
_paramPort = 1883;
_paramUser = "";
_paramPassword = "";
paramDiscoveryPrefix = "ewc";
}
void Mqtt::_fromJson(JsonDocument& config)
{
JsonVariant jv = config["mqtt"]["enabled"];
if (!jv.isNull()) {
paramEnabled = jv.as<bool>();
}
jv = config["mqtt"]["server"];
if (!jv.isNull()) {
_paramServer = jv.as<String>();
}
jv = config["mqtt"]["port"];
if (!jv.isNull()) {
_paramPort = jv.as<int>();
}
jv = config["mqtt"]["user"];
if (!jv.isNull()) {
_paramUser = jv.as<String>();
}
jv = config["mqtt"]["pass"];
if (!jv.isNull()) {
_paramPassword = jv.as<String>();
}
jv = config["mqtt"]["prefix"];
if (!jv.isNull()) {
paramDiscoveryPrefix = jv.as<String>();
}
if (paramEnabled) {
// set contact informations
_mqttClient.setServer(_paramServer.c_str(), _paramPort);
if (_paramUser.length() > 0) {
const char* pass = nullptr;
if (_paramPassword.length() > 0) {
pass = _paramPassword.c_str();
}
_mqttClient.setCredentials(_paramUser.c_str(), pass);
}
// reconnect
if (_mqttClient.connected()) {
_mqttClient.disconnect(true);
} else {
_connectToMqtt();
}
}
}
void Mqtt::_onMqttConfig(WebServer* request)
{
if (!I::get().server().isAuthenticated(request)) {
return request->requestAuthentication();
}
DynamicJsonDocument jsonDoc(1024);
fillJson(jsonDoc);
String output;
serializeJson(jsonDoc, output);
request->send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), output);
}
void Mqtt::_onMqttSave(WebServer* request)
{
if (!I::get().server().isAuthenticated(request)) {
return request->requestAuthentication();
}
for (int i = 0; i < request->args(); i++) {
I::get().logger() << " " << request->argName(i) << ": " << request->arg(i) << endl;
}
DynamicJsonDocument config(1024);
if (request->hasArg("mqtt_enabled")) {
bool a = request->arg("mqtt_enabled").equals("true");
config["mqtt"]["enabled"] = a;
I::get().logger() << " _onMqttSave, enabled " << a << " -> "<< request->arg("mqtt_enabled")<< endl;
}
if (request->hasArg("mqtt_server")) {
config["mqtt"]["server"] = request->arg("mqtt_server");
}
if (request->hasArg("mqtt_port") && !request->arg("mqtt_port").isEmpty()) {
config["mqtt"]["port"] = request->arg("mqtt_port").toInt();
}
if (request->hasArg("mqtt_user")) {
config["mqtt"]["user"] = request->arg("mqtt_user");
}
if (request->hasArg("mqtt_pass")) {
config["mqtt"]["pass"] = request->arg("mqtt_pass");
}
if (request->hasArg("mqtt_prefix")) {
config["mqtt"]["prefix"] = request->arg("mqtt_prefix");
}
_fromJson(config);
I::get().configFS().save();
String details;
serializeJsonPretty(config["mqtt"], details);
I::get().server().sendPageSuccess(request, "EWC MQTT save", "Save successful!", "/mqtt/setup", "<pre id=\"json\">" + details + "</pre>", "Back", "/mqtt/state.html", "MQTT State");
}
void Mqtt::_onMqttState(WebServer* request)
{
if (!I::get().server().isAuthenticated(request)) {
return request->requestAuthentication();
}
StaticJsonDocument<JSON_OBJECT_SIZE(14)> jsonDoc;
jsonDoc["enabled"] = paramEnabled;
jsonDoc["connecting"] = _connecting;
jsonDoc["connected"] = _mqttClient.connected();
jsonDoc["failed"] = false;
jsonDoc["reason"] = "";
jsonDoc["server"] = _paramServer;
jsonDoc["port"] = _paramPort;
String output;
serializeJson(jsonDoc, output);
request->send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), output);
}
void Mqtt::_connectToMqtt() {
I::get().logger() << F("[EWC MQTT] Connecting to MQTT...") << endl;
_connecting = true;
_mqttClient.connect();
}
void Mqtt::_onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
I::get().logger() << F("[EWC MQTT] Disconnected from MQTT, reason: ") << (uint32_t)reason << endl;
if (WiFi.isConnected() && (uint32_t)reason < 4) {
_mqttReconnectTimer.once(2, std::bind(&Mqtt::_connectToMqtt, this));
}
}
void Mqtt::_onMqttConnect(bool sessionPresent) {
I::get().logger() << F("[EWC MQTT] Connected to MQTT. Session present: ") << sessionPresent << endl;
_connecting = false;
}
void Mqtt::_onWifiConnect(const WiFiEventStationModeGotIP& event) {
I::get().logger() << F("[EWC MQTT] Connected to Wi-Fi.") << endl;
_connectToMqtt();
}
void Mqtt::_onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
I::get().logger() << F("[EWC MQTT] Disconnected from Wi-Fi.") << endl;
_mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
}
| [
"alexander.tiderko@gmail.com"
] | alexander.tiderko@gmail.com |
39789c01ae521c7247758e687c6cdf5deb8156b8 | 41b4adb10cc86338d85db6636900168f55e7ff18 | /aws-cpp-sdk-rds/source/model/RemoveTagsFromResourceRequest.cpp | 828870e08bcbde1e71c5190106a3df5965900457 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | totalkyos/AWS | 1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80 | 7cb444814e938f3df59530ea4ebe8e19b9418793 | refs/heads/master | 2021-01-20T20:42:09.978428 | 2016-07-16T00:03:49 | 2016-07-16T00:03:49 | 63,465,708 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,481 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/rds/model/RemoveTagsFromResourceRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::RDS::Model;
using namespace Aws::Utils;
RemoveTagsFromResourceRequest::RemoveTagsFromResourceRequest() :
m_resourceNameHasBeenSet(false),
m_tagKeysHasBeenSet(false)
{
}
Aws::String RemoveTagsFromResourceRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=RemoveTagsFromResource&";
if(m_resourceNameHasBeenSet)
{
ss << "ResourceName=" << StringUtils::URLEncode(m_resourceName.c_str()) << "&";
}
if(m_tagKeysHasBeenSet)
{
unsigned tagKeysCount = 1;
for(auto& item : m_tagKeys)
{
ss << "TagKeys.member." << tagKeysCount << "="
<< StringUtils::URLEncode(item.c_str()) << "&";
tagKeysCount++;
}
}
ss << "Version=2014-10-31";
return ss.str();
}
| [
"henso@amazon.com"
] | henso@amazon.com |
8381518d4a9b7be0e02fbb5e7b179f2ba1815907 | 355bdee293d572f3b01f9de7a96d8a11ff3df7e7 | /Framework/Source/Sample.cpp | b0b493d8d79f07ff684bffd4795c7a19aa7f6462 | [] | no_license | Samana/Falcor | 0584ebd08f7abb8791d4e55d62524953617ab103 | 90c54e94dd4320bb7166b8c01766a2ddbd7d7222 | refs/heads/master | 2021-01-18T20:48:11.022229 | 2017-08-17T00:28:55 | 2017-08-17T00:28:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,946 | cpp | /***************************************************************************
# Copyright (c) 2015, NVIDIA 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 NVIDIA 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 ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#include "Framework.h"
#include "Sample.h"
#include <map>
#include <fstream>
#include "API/Window.h"
#include "Graphics/Program.h"
#include "Utils/OS.h"
#include "API/FBO.h"
#include "VR\OpenVR\VRSystem.h"
#include "Utils\ProgressBar.h"
#include <sstream>
#include <iomanip>
namespace Falcor
{
Sample::Sample()
{
}
void Sample::handleWindowSizeChange()
{
// Tell the device to resize the swap chain
mpDefaultFBO = gpDevice->resizeSwapChain(mpWindow->getClientAreaWidth(), mpWindow->getClientAreaHeight());
mpDefaultPipelineState->setFbo(mpDefaultFBO);
// Tell the GUI the swap-chain size changed
mpGui->onWindowResize(mpDefaultFBO->getWidth(), mpDefaultFBO->getHeight());
// Call the user callback
onResizeSwapChain();
}
void Sample::handleKeyboardEvent(const KeyboardEvent& keyEvent)
{
if (keyEvent.type == KeyboardEvent::Type::KeyPressed)
{
mPressedKeys.insert(keyEvent.key);
}
else
{
mPressedKeys.erase(keyEvent.key);
}
// Check if the GUI consumes it
if (mpGui->onKeyboardEvent(keyEvent))
{
return;
}
// Checks if should toggle zoom
mpPixelZoom->onKeyboardEvent(keyEvent);
// Consume system messages first
if (keyEvent.type == KeyboardEvent::Type::KeyPressed)
{
if (keyEvent.mods.isShiftDown && keyEvent.key == KeyboardEvent::Key::F12)
{
initVideoCapture();
}
else if (!keyEvent.mods.isAltDown && !keyEvent.mods.isCtrlDown && !keyEvent.mods.isShiftDown)
{
switch (keyEvent.key)
{
case KeyboardEvent::Key::F12:
mCaptureScreen = true;
break;
#if _PROFILING_ENABLED
case KeyboardEvent::Key::P:
gProfileEnabled = !gProfileEnabled;
break;
#endif
case KeyboardEvent::Key::V:
mVsyncOn = !mVsyncOn;
gpDevice->toggleVSync(mVsyncOn);
mFrameRate.resetClock();
break;
case KeyboardEvent::Key::F1:
toggleText(!mShowText);
break;
case KeyboardEvent::Key::F2:
toggleUI(!mShowUI);
break;
case KeyboardEvent::Key::F5:
Program::reloadAllPrograms();
onDataReload();
break;
case KeyboardEvent::Key::Escape:
if (mVideoCapture.pVideoCapture)
{
endVideoCapture();
}
else
{
mpWindow->shutdown();
}
break;
case KeyboardEvent::Key::Equal:
mFreezeTime = !mFreezeTime;
break;
}
}
}
// If we got here, this is a user specific message
onKeyEvent(keyEvent);
}
void Sample::handleMouseEvent(const MouseEvent& mouseEvent)
{
if (mpGui->onMouseEvent(mouseEvent)) return;
if (mpPixelZoom->onMouseEvent(mouseEvent)) return;
onMouseEvent(mouseEvent);
}
// Sample functions
Sample::~Sample()
{
if (mVideoCapture.pVideoCapture)
{
endVideoCapture();
}
VRSystem::cleanup();
mpGui.reset();
mpDefaultPipelineState.reset();
mpDefaultFBO.reset();
mpTextRenderer.reset();
mpPixelZoom.reset();
mpRenderContext.reset();
gpDevice->cleanup();
gpDevice.reset();
}
void Sample::run(const SampleConfig& config)
{
mTimeScale = config.timeScale;
mFixedTimeDelta = config.fixedTimeDelta;
mFreezeTime = config.freezeTimeOnStartup;
// Start the logger
Logger::init();
Logger::showBoxOnError(config.showMessageBoxOnError);
// Show the progress bar
ProgressBar::MessageList msgList =
{
{ "Initializing Falcor" },
{ "Takes a while, doesn't it?" },
{ "Don't get too bored now" },
{ "Getting there" },
{ "Loading. Seriously, loading" },
{ "Are we there yet?"},
{ "NI!"}
};
ProgressBar::SharedPtr pBar = ProgressBar::create(msgList);
// Create the window
mpWindow = Window::create(config.windowDesc, this);
if (mpWindow == nullptr)
{
logError("Failed to create device and window");
return;
}
Device::Desc d = config.deviceDesc;
gpDevice = Device::create(mpWindow, config.deviceDesc);
if (gpDevice == nullptr)
{
logError("Failed to create device");
return;
}
if (config.deviceCreatedCallback != nullptr)
{
config.deviceCreatedCallback();
}
// Set the icon
setWindowIcon("Framework\\Nvidia.ico", mpWindow->getApiHandle());
// Get the default objects before calling onLoad()
mpDefaultFBO = gpDevice->getSwapChainFbo();
mpDefaultPipelineState = GraphicsState::create();
mpDefaultPipelineState->setFbo(mpDefaultFBO);
mpRenderContext = gpDevice->getRenderContext();
mpRenderContext->setGraphicsState(mpDefaultPipelineState);
// Init the UI
initUI();
// Load and run
mArgList.parseCommandLine(GetCommandLineA());
mpPixelZoom = PixelZoom::create(mpDefaultFBO.get());
onLoad();
pBar = nullptr;
mFrameRate.resetClock();
mpWindow->msgLoop();
onShutdown();
Logger::shutdown();
}
void Sample::calculateTime()
{
if (mFixedTimeDelta > 0.0f)
{
mCurrentTime += mFixedTimeDelta * mTimeScale;
}
else if (mFreezeTime == false)
{
float elapsedTime = mFrameRate.getLastFrameTime() * mTimeScale;
mCurrentTime += elapsedTime;
}
}
void Sample::renderGUI()
{
constexpr char help[] =
" 'F1' - Show\\Hide text\n"
" 'F2' - Show\\Hide GUI\n"
" 'F5' - Reload shaders\n"
" 'ESC' - Quit\n"
" 'V' - Toggle VSync\n"
" 'F12' - Capture screenshot\n"
" 'Shift+F12' - Video capture\n"
" '=' - Pause\\resume timer\n"
" 'Z' - Zoom in on a pixel\n"
" 'MouseWheel' - Change level of zoom\n"
#if _PROFILING_ENABLED
" 'P' - Enable profiling\n";
#else
;
#endif
mpGui->pushWindow("Falcor", 250, 200, 20, 40, false);
mpGui->addText("Keyboard Shortcuts");
mpGui->addTooltip(help, true);
if (mpGui->beginGroup("Global Controls"))
{
mpGui->addFloatVar("Time", mCurrentTime, 0, FLT_MAX);
mpGui->addFloatVar("Time Scale", mTimeScale, 0, FLT_MAX);
if (mVideoCapture.pVideoCapture == nullptr)
{
mpGui->addFloatVar("Fixed Time Delta", mFixedTimeDelta, 0, FLT_MAX);
}
if (mpGui->addButton("Reset"))
{
mCurrentTime = 0.0f;
}
if (mpGui->addButton(mFreezeTime ? "Play" : "Pause", true))
{
mFreezeTime = !mFreezeTime;
}
if (mpGui->addButton("Stop", true))
{
mFreezeTime = true;
mCurrentTime = 0.0f;
}
mCaptureScreen = mpGui->addButton("Screen Capture");
if (mpGui->addButton("Video Capture", true))
{
initVideoCapture();
}
mpGui->endGroup();
}
onGuiRender();
mpGui->popWindow();
if (mVideoCapture.pUI)
{
mVideoCapture.pUI->render(mpGui.get());
}
mpGui->render(mpRenderContext.get(), mFrameRate.getLastFrameTime());
}
void Sample::renderFrame()
{
if (gpDevice->isWindowOccluded())
{
return;
}
mFrameRate.newFrame();
{
PROFILE(onFrameRender);
// The swap-chain FBO might have changed between frames, so get it
mpDefaultFBO = gpDevice->getSwapChainFbo();
mpRenderContext = gpDevice->getRenderContext();
calculateTime();
// Bind the default state
mpRenderContext->setGraphicsState(mpDefaultPipelineState);
mpDefaultPipelineState->setFbo(mpDefaultFBO);
onFrameRender();
}
{
PROFILE(renderGUI);
if (mShowUI)
{
renderGUI();
}
}
renderText(getFpsMsg(), glm::vec2(10, 10));
mpPixelZoom->render(mpRenderContext.get(), gpDevice->getSwapChainFbo().get());
captureVideoFrame();
printProfileData();
if (mCaptureScreen)
{
captureScreen();
}
{
PROFILE(present);
gpDevice->present();
}
}
void Sample::captureScreen()
{
std::string filename = getExecutableName();
// Now we have a folder and a filename, look for an available filename (we don't overwrite existing files)
std::string prefix = std::string(filename);
std::string executableDir = getExecutableDirectory();
std::string pngFile;
if (findAvailableFilename(prefix, executableDir, "png", pngFile))
{
Texture::SharedPtr pTexture = gpDevice->getSwapChainFbo()->getColorTexture(0);
pTexture->captureToFile(0, 0, pngFile);
}
else
{
logError("Could not find available filename when capturing screen");
}
mCaptureScreen = false;
}
void Sample::initUI()
{
mpGui = Gui::create(mpDefaultFBO->getWidth(), mpDefaultFBO->getHeight());
mpTextRenderer = TextRenderer::create();
}
const std::string Sample::getFpsMsg() const
{
std::string s;
if (mShowText)
{
std::stringstream strstr;
float msPerFrame = mFrameRate.getAverageFrameTime();
std::string msStr = std::to_string(msPerFrame);
s = std::to_string(int(ceil(1000 / msPerFrame))) + " FPS (" + msStr.erase(msStr.size() - 4) + " ms/frame)";
if (mVsyncOn) s += std::string(", VSync");
}
return s;
}
void Sample::toggleText(bool enabled)
{
mShowText = enabled;
}
void Sample::resizeSwapChain(uint32_t width, uint32_t height)
{
mpWindow->resize(width, height);
mpPixelZoom->onResizeSwapChain(gpDevice->getSwapChainFbo().get());
}
bool Sample::isKeyPressed(const KeyboardEvent::Key& key) const
{
return mPressedKeys.find(key) != mPressedKeys.cend();
}
void Sample::renderText(const std::string& msg, const glm::vec2& position, const glm::vec2 shadowOffset) const
{
if (mShowText)
{
// Render outline first
if (shadowOffset.x != 0.f || shadowOffset.y != 0)
{
const glm::vec3 oldColor = mpTextRenderer->getTextColor();
mpTextRenderer->setTextColor(glm::vec3(0.f)); // Black outline
mpTextRenderer->begin(mpRenderContext, position + shadowOffset);
mpTextRenderer->renderLine(msg);
mpTextRenderer->end();
mpTextRenderer->setTextColor(oldColor);
}
mpTextRenderer->begin(mpRenderContext, position);
mpTextRenderer->renderLine(msg);
mpTextRenderer->end();
}
}
void Sample::printProfileData()
{
#if _PROFILING_ENABLED
if (gProfileEnabled)
{
std::string profileMsg;
Profiler::endFrame(profileMsg);
renderText(profileMsg, glm::vec2(10, 300));
}
#endif
}
void Sample::initVideoCapture()
{
if (mVideoCapture.pUI == nullptr)
{
mVideoCapture.pUI = VideoEncoderUI::create(20, 300, 240, 220, [this]() {startVideoCapture(); }, [this]() {endVideoCapture(); });
}
}
void Sample::startVideoCapture()
{
// Create the Capture Object and Framebuffer.
VideoEncoder::Desc desc;
desc.flipY = false;
desc.codec = mVideoCapture.pUI->getCodec();
desc.filename = mVideoCapture.pUI->getFilename();
desc.format = mpDefaultFBO->getColorTexture(0)->getFormat();
desc.fps = mVideoCapture.pUI->getFPS();
desc.height = mpDefaultFBO->getHeight();
desc.width = mpDefaultFBO->getWidth();
desc.bitrateMbps = mVideoCapture.pUI->getBitrate();
desc.gopSize = mVideoCapture.pUI->getGopSize();
mVideoCapture.pVideoCapture = VideoEncoder::create(desc);
assert(mVideoCapture.pVideoCapture);
mVideoCapture.pFrame = new uint8_t[desc.width*desc.height * 4];
mVideoCapture.sampleTimeDelta = mFixedTimeDelta;
mFixedTimeDelta = 1.0f / (float)desc.fps;
if (mVideoCapture.pUI->useTimeRange())
{
if (mVideoCapture.pUI->getStartTime() > mVideoCapture.pUI->getEndTime())
{
mFixedTimeDelta = -mFixedTimeDelta;
}
mCurrentTime = mVideoCapture.pUI->getStartTime();
if (!mVideoCapture.pUI->captureUI())
{
mShowUI = false;
}
}
}
void Sample::endVideoCapture()
{
if (mVideoCapture.pVideoCapture)
{
mVideoCapture.pVideoCapture->endCapture();
mShowUI = true;
}
mVideoCapture.pUI = nullptr;
mVideoCapture.pVideoCapture = nullptr;
safe_delete_array(mVideoCapture.pFrame);
mFixedTimeDelta = mVideoCapture.sampleTimeDelta;
}
void Sample::captureVideoFrame()
{
if (mVideoCapture.pVideoCapture)
{
mVideoCapture.pVideoCapture->appendFrame(mpRenderContext->readTextureSubresource(mpDefaultFBO->getColorTexture(0).get(), 0).data());
if (mVideoCapture.pUI->useTimeRange())
{
if (mFixedTimeDelta >= 0)
{
if (mCurrentTime >= mVideoCapture.pUI->getEndTime())
{
endVideoCapture();
}
}
else if (mCurrentTime < mVideoCapture.pUI->getEndTime())
{
endVideoCapture();
}
}
}
}
void Sample::shutdownApp()
{
mpWindow->shutdown();
}
void Sample::pollForEvents()
{
mpWindow->pollForEvents();
}
void Sample::setWindowTitle(const std::string& title)
{
mpWindow->setWindowTitle(title);
}
} | [
"kyao@nvidia.com"
] | kyao@nvidia.com |
3320a6b72e5b0106d36322c5d7bfda792016b720 | 20eecbc18ea852471af58f2a9da2fd2e0b012d3e | /C++11/Unique-Ptr.cc | 1dd46a582ed47453fcfacf06ea0d01a4eb3e8a74 | [] | no_license | pallavsingh/CPP17 | 48a57d11981bab7f5dcacc542c622838de47791e | f5084d940fdad32522232af13b08e6bdbe766ecf | refs/heads/master | 2021-05-02T16:47:14.625985 | 2021-01-23T07:32:25 | 2021-01-23T07:32:25 | 60,398,740 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | cc | // C++14 Hearders
#include <iostream>
#include <memory>
#include <atomic>
#include <mutex>
#include <initializer_list>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <iterator>
#include <unordered_map>
// Boost Library Hearders
#include <boost/type_index.hpp>
using namespace std;
using boost::typeindex::type_id_with_cvr;
////////////////////////////////////////////////////////////////////
/*
Only non-const unique_ptr can transfer the ownership of the managed object
to another unique_ptr. The lifetime of an object managed by const std::unique_ptr
is limited to the scope in which the pointer was created.
*/
struct Foo {
Foo() { std::cout << "Foo::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
void bar() { std::cout << "Foo::bar\n"; }
};
void func1 (const Foo & param) {
std::cout << "f(const Foo&) \n";
}
void func2 (const unique_ptr<Foo> & p) {
cerr << "Sink owns Foo [" << p.get() << "]\n";
}
int main(int argc, char * argv[]) {
// C++ Has deleted the Implementation of Copy Constructor and Assignment Operator
// unique_ptr(const unique_ptr&) = delete;
// unique_ptr& operator=(const unique_ptr&) = delete;
unique_ptr<Foo> fp(new Foo());
unique_ptr<Foo> fp3;
// unique_ptr<Foo> fp2(fp); // ERROR! can't copy unique_ptr
// fp3 = fp; // ERROR! can't assign unique_ptr
std::unique_ptr<Foo> p1(new Foo); // p1 owns Foo
if (p1) {
p1->bar();
}
// for Auto_ptr we have copy constructor and Assignment Operator implemented
// Hence we can pass-by-value Auto Ptr but not Unique Ptr.
std::unique_ptr<Foo> p2(std::move(p1)); // now p2 owns Foo
func1(*p2);
func2(p2);
p1 = std::move(p2); // ownership returns to p1
std::cout << "destroying p2...\n";
// Foo instance is destroyed when p1 goes out of scope
if (p1) {
p1->bar();
std::cout << "destroying p1...\n";
}
// If you need the raw pointer. But do not call delete on pRawPtr your self.
unique_ptr<Foo> pObj(new Foo());
Foo * pRawPtr = pObj.get();
// If you want to remove a pointer from the smart pointer, you need to release the ownership of it.
// The std::unique_ptr will now not delete the pointer. And pObj is now also invalid for usage.
pObj.release();
return 0;
}
| [
"you@example.com"
] | you@example.com |
200e0d1b4d898b49e230566efb096010eee9d2c2 | 9569a3874b5046797c50a00361109383dd365a28 | /samples/05-Models/src/CameraController.cpp | 8cf3ed65148be2943068c9417534a631792d130d | [
"MIT"
] | permissive | TechnikEmpire/LearningDirectX12 | 85a0dafafdb4aef3874bdde0ec9a9e820a7acde0 | da668e2b78f0bd876a0a4f8c415d3d4f6b692a16 | refs/heads/main | 2023-01-30T00:20:32.668539 | 2020-11-22T19:15:55 | 2020-11-22T19:15:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,011 | cpp | #include <CameraController.h>
#include <imgui/imgui.h> // Need to check if ImGui wants to capture mouse or keyboard input.
#include <Camera.h>
#include <cmath> // for std::abs and std::pow
using namespace DirectX;
// Perform a linear interpolation
inline double Lerp( float x0, float x1, float a )
{
return x0 + a * ( x1 - x0 );
}
// Apply smoothing
inline void Smooth( float& x0, float& x1, float deltaTime )
{
float x;
if ( std::fabsf( x0 ) < std::fabsf( x1 ) ) // Speeding up
{
x = Lerp( x1, x0, std::powf( 0.6, deltaTime * 60.0 ) );
}
else // Slowing down
{
x = Lerp( x1, x0, std::powf( 0.8, deltaTime * 60.0 ) );
}
x0 = x;
x1 = x;
}
CameraController::CameraController( Camera& camera )
: m_Camera( camera )
, m_X( 0.0 )
, m_Y( 1.0 )
, m_Z( 0.0 )
, m_Pitch( 0.0 )
, m_Yaw( 0.0 )
, m_PreviousPitch( 0.0 )
, m_PreviousYaw( 0.0 )
, m_InverseY( true )
{
auto& gf = GameFramework::Get();
m_Logger = gf.CreateLogger( "CameraController" );
m_KMInput = gf.CreateInputMap( "CameraController (Keyboard/Mouse)" );
m_PadInput = gf.CreateInputMap( "CameraController (Pad)" );
auto keyboard = gf.GetKeyboardId();
auto mouse = gf.GetMouseId();
auto pad = gf.GetPadId( 0 ); // Just use the first connected device.
// Map keyboard events.
m_KMInput->MapFloat( MoveX, keyboard, gainput::KeyD, 0.0f, 1.0f );
m_KMInput->MapFloat( MoveX, keyboard, gainput::KeyA, 0.0f, -1.0f );
m_KMInput->MapFloat( MoveY, keyboard, gainput::KeyE, 0.0f, 1.0f );
m_KMInput->MapFloat( MoveY, keyboard, gainput::KeyQ, 0.0f, -1.0f );
m_KMInput->MapFloat( MoveZ, keyboard, gainput::KeyW, 0.0f, 1.0f );
m_KMInput->MapFloat( MoveZ, keyboard, gainput::KeyS, 0.0f, -1.0f );
m_KMInput->MapFloat( Pitch, keyboard, gainput::KeyUp, 0.0f, 1.0f );
m_KMInput->MapFloat( Pitch, keyboard, gainput::KeyDown, 0.0f, -1.0f );
m_KMInput->MapFloat( Yaw, keyboard, gainput::KeyLeft, 0.0f, 1.0f );
m_KMInput->MapFloat( Yaw, keyboard, gainput::KeyRight, 0.0f, -1.0f );
m_KMInput->MapBool( Boost, keyboard, gainput::KeyShiftL );
m_KMInput->MapBool( Boost, keyboard, gainput::KeyShiftR );
// Map mouse events
m_KMInput->MapBool( LMB, mouse, gainput::MouseButtonLeft );
m_KMInput->MapBool( RMB, mouse, gainput::MouseButtonRight );
m_KMInput->MapFloat( Pitch, mouse, gainput::MouseAxisY );
m_KMInput->MapFloat( Yaw, mouse, gainput::MouseAxisX );
// Map pad events.
m_PadInput->MapFloat( MoveX, pad, gainput::PadButtonLeftStickX );
m_PadInput->MapFloat( MoveZ, pad, gainput::PadButtonLeftStickY );
m_PadInput->MapFloat( MoveY, pad, gainput::PadButtonAxis4, 0.0f, -1.0f ); // Left trigger (move down)
m_PadInput->MapFloat( MoveY, pad, gainput::PadButtonAxis5, 0.0f, 1.0f ); // Right trigger (move up)
m_PadInput->MapFloat( Pitch, pad, gainput::PadButtonRightStickY );
m_PadInput->MapFloat( Yaw, pad, gainput::PadButtonRightStickX );
m_PadInput->MapBool( Boost, pad, gainput::PadButtonL3 );
m_PadInput->MapBool( Boost, pad, gainput::PadButtonR3 );
// Set policy for pitch/yaw so both mouse and keyboard works.
m_KMInput->SetUserButtonPolicy( Pitch, gainput::InputMap::UBP_MAX );
m_KMInput->SetUserButtonPolicy( Yaw, gainput::InputMap::UBP_MAX );
ResetView();
}
void CameraController::ResetView()
{
// Reset previous deltas.
m_X = m_Y = m_Z = m_PreviousPitch = m_PreviousYaw = 0.0f;
m_Pitch = 0.0f;
m_Yaw = 90.0f;
XMVECTOR rotation =
XMQuaternionRotationRollPitchYaw( XMConvertToRadians( m_Pitch ), XMConvertToRadians( m_Yaw ), 0.0f );
m_Camera.set_Rotation( rotation );
m_Camera.set_Translation( { 0, 2, -2, 1 } );
m_Camera.set_FocalPoint( { 0, 0, 0, 1 } );
}
void CameraController::Update( UpdateEventArgs& e )
{
const float MOVE_SPEED = 10.0;
const float LOOK_SENSITIVITY = 90.0;
const float MOUSE_SENSITIVITY = 0.1;
float speedScale = m_PadInput->GetBool( Boost ) || m_KMInput->GetBool( Boost ) ? 2.0 : 1.0;
float rotationScale = m_PadInput->GetBool( Boost ) || m_KMInput->GetBool( Boost ) ? 2.0 : 1.0;
float X = m_PadInput->GetFloat( MoveX ) * MOVE_SPEED * speedScale * e.DeltaTime;
float Y = m_PadInput->GetFloat( MoveY ) * MOVE_SPEED * speedScale * e.DeltaTime;
float Z = m_PadInput->GetFloat( MoveZ ) * MOVE_SPEED * speedScale * e.DeltaTime;
float pitch = m_PadInput->GetFloat( Pitch ) * LOOK_SENSITIVITY * rotationScale * e.DeltaTime;
float yaw = m_PadInput->GetFloat( Yaw ) * LOOK_SENSITIVITY * rotationScale * e.DeltaTime;
if ( !ImGui::GetIO().WantCaptureKeyboard )
{
X += m_KMInput->GetFloat( MoveX ) * MOVE_SPEED * speedScale * e.DeltaTime;
Y += m_KMInput->GetFloat( MoveY ) * MOVE_SPEED * speedScale * e.DeltaTime;
Z += m_KMInput->GetFloat( MoveZ ) * MOVE_SPEED * speedScale * e.DeltaTime;
}
// Apply smoothing
Smooth( m_X, X, e.DeltaTime );
Smooth( m_Y, Y, e.DeltaTime );
Smooth( m_Z, Z, e.DeltaTime );
Smooth( m_PreviousPitch, pitch, e.DeltaTime );
Smooth( m_PreviousYaw, yaw, e.DeltaTime );
// Add mouse motion without smoothing.
if ( m_KMInput->GetBool( LMB ) && !ImGui::GetIO().WantCaptureMouse )
{
pitch += m_KMInput->GetFloatDelta( Pitch ) * MOUSE_SENSITIVITY * rotationScale;
yaw += m_KMInput->GetFloatDelta( Yaw ) * MOUSE_SENSITIVITY * rotationScale;
}
m_Pitch += pitch * ( m_InverseY ? 1.0 : -1.0 );
m_Pitch = std::clamp( m_Pitch, -90.0f, 90.0f );
m_Yaw += yaw;
// Apply translation and rotation to the camera.
XMVECTORF32 translation = { X, Y, Z };
m_Camera.Translate( translation, Space::World );
// Apply rotation
XMVECTOR rotation =
XMQuaternionRotationRollPitchYaw( XMConvertToRadians( m_Pitch ), XMConvertToRadians( m_Yaw ), 0.0f );
m_Camera.set_Rotation( rotation );
}
| [
"jpvanoosten@hotmail.com"
] | jpvanoosten@hotmail.com |
b2a51d04398b8bb4e8faa016b42ae43bbd88ab9e | 640e50c003add59f0dfe506289562a398d162577 | /campus_bikes.cpp | 836d72e93eb23615eec8cdfc414385fb7bd4c7e2 | [] | no_license | ShreyasP7495/Greedy-5 | 78a8464958285268ea26d478e71886b46efbe50d | 8b05ceca260cf9a57f6895131eb5b23cf5d54568 | refs/heads/master | 2021-05-19T14:23:12.126125 | 2020-04-03T18:48:38 | 2020-04-03T18:48:38 | 251,755,002 | 0 | 0 | null | 2020-03-31T22:12:46 | 2020-03-31T22:12:45 | null | UTF-8 | C++ | false | false | 2,195 | cpp | //Time Complexity-O(m*n*log(x))--->here 'm' is number of workers,'n' is number of bikes and 'x' is total number of unique
// distances stored in hashmap(number of keys or map.size())
//Space Complexity-O(x*k+m+n)--> Auxiliary space for storing if the workers and bikes are assigned(O(m)+O(n))
// Addition to this we also used ordered map which is of size x*k.
// Here 'x' is map size and 'k' is average number of pairs per key in the map.
//Did the code execute on Leetcode? Yes but this is not getting accepted in c++ and it's passing 27/28 cases.
// It's giving TLE for last test case. This is because for large input and various
// distances the time complexity of adding an element in ordered map is log(n).
class Solution {
public:
vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
if(workers.size()==0 || bikes.size()==0)
{
return {};
}
vector<int>res(workers.size(),-1);
vector<bool>temp(workers.size(),false);
vector<bool>temp1(bikes.size(),false);
map<int,vector<vector<int>>>m;
for(int i=0;i<workers.size();i++)
{
for(int j=0;j<bikes.size();j++)
{
int dist=abs(bikes[j][0]-workers[i][0])+abs(bikes[j][1]-workers[i][1]);
if(m.find(dist)==m.end())
{
m[dist]={};
}
m[dist].push_back({i,j});
}
}
for(auto i=m.begin();i!=m.end();i++)
{
cout<<i->first;
cout<<"\n";
vector<vector<int>>a=i->second;
for(int j=0;j<a.size();j++)
{
vector<int>b=a[j];
if(temp[b[0]]==false && temp1[b[1]]==false)
{
res[b[0]]=b[1];
temp[b[0]]=true;
temp1[b[1]]=true;
}
}
}
return res;
}
};
| [
"noreply@github.com"
] | ShreyasP7495.noreply@github.com |
cc62320430758a7ea6c0d8b4038fc2f8aa57a2c9 | 232075a7a088bb6e4f61d114d9bb9563b38e4f3f | /Ember/src/Window.cpp | a86e477638ee823619b6fb53373a7ff5bd9d4dcc | [
"MIT"
] | permissive | strah19/2048 | a99295808cea2dcc15f4a6daebdccebd2d5b0790 | dd7b6fafb4d7e455cde10f6b1322ce874ff1c1b6 | refs/heads/master | 2023-07-18T10:14:29.876647 | 2021-08-30T16:17:26 | 2021-08-30T16:17:26 | 389,422,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cpp | #include "Window.h"
#include "SDLWindow.h"
#include "OpenGLWindow.h"
namespace Ember {
Window* Window::CreateEmberWindow(WindowProperties* properties) {
return new SDLWindow(properties);
}
Window* Window::CreateEmberWindow(WindowProperties* properties, uint32_t major_opengl, uint32_t minor_opengl) {
return new OpenGLWindow(properties, major_opengl, minor_opengl);
}
SDL_SysWMinfo GetSystemInfo() {
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
return info;
}
} | [
"m.strahinja@yahoo.com"
] | m.strahinja@yahoo.com |
ccb928ef7dd911090e8cb76a3d9194c567f7280c | f6695e04d3188c96f0e8f08b8bfdcd362056b451 | /xtwse/FT/source/FTCenter/FTJobDef.h | ac903fefbb225c8c20f3e7575244d132b0604a45 | [] | no_license | sp557371/TwseNewFix | 28772048ff9150ba978ec591aec22b855ae6250a | 5ed5146f221a0e38512e4056c2c4ea52dbd32dcd | refs/heads/master | 2020-04-17T03:18:03.493560 | 2019-01-17T08:40:46 | 2019-01-17T08:40:46 | 166,175,913 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 5,890 | h | //---------------------------------------------------------------------------
#ifndef FTJobDefH
#define FTJobDefH
//---------------------------------------------------------------------------
#include "KwayBase.h"
#include "bxLink.h"
#include "bxFT.h"
#include "fixed_num.h"
#include "TwStk.h"
#include <queue>
#include <set>
#include <vector>
#include "inn_file.h"
//---------------------------------------------------------------------------
namespace Kway {
namespace Tw {
namespace Bx {
namespace FT {
//---------------------------------------------------------------------------
typedef Kstl::fixed_num<Kway::int32> TSeqNo;
typedef KStk::TMarket TMarket;
typedef Kstl::char_ary<char, 50, 0> TLastMsg;
static TBrkID TSEID_("0000");
//---------------------------------------------------------------------------
struct TBrkMkt{
TBrkID BrokerID_;
TMarket Market_;
TBrkMkt() {};
TBrkMkt(const TBrkID& a, const TMarket& b): BrokerID_(a), Market_(b) {}
K_mf(bool) operator == (const TBrkMkt& a) const{
return BrokerID_ == a.BrokerID_ && Market_ == a.Market_;}
K_mf(bool) operator < (const TBrkMkt& a) const
{ return BrokerID_==a.BrokerID_ ? a.Market_<Market_ : a.BrokerID_<BrokerID_; }
K_mf(std::string) as_string()const {return std::string(BrokerID_.as_string()+"-"+Market_.as_string());}
K_mf(void) assign(const char*){};
};
//---------------------------------------------------------------------------
#ifdef K_EnumPacked_Bug
typedef byte EFTFlowID;
enum EFTFlowID_t
#else
enum EFTFlowID
#endif
{
fft_P_ing, //處理中
fft_Q_ing, //排隊中
fft_S_ing, //傳送中
fft_R_ing, //接收中
fft_W_ing, //等候回報, 若是券商申報資料, 則有可能需要等候交易所回傳申報回覆資料才算OK
fft_Routed, //己繞送至其他台主機處理,
fft_Finish, //結束
fft_Timeout, //作業逾時,
fft_Abort, //委託中斷! (發生異常)
} K_EnumPacked;
K_class TFTFlowID : public Kstl::EnumT<EFTFlowID>
{
typedef Kstl::EnumT<EFTFlowID> inherited;
public:
inline K_ctor TFTFlowID(EFTFlowID a = fft_Finish) : inherited(a) {}
K_mf(std::string) as_string () const;
K_mf(void) assign (const std::string&);
};
//---------------------------------------------------------------------------
#ifdef K_EnumPacked_Bug
typedef byte EFTMode;
enum EFTMode_t
#else
enum EFTMode
#endif
{
ftm_Daily, // 交易所每日主動下載
ftm_Report, // 券商申報(含回覆)
ftm_ByReq, // 券商要求下載
ftm_Schedule,// 排程下載
ftm_BrkMsg, // 券商送出訊息
ftm_TSEMsg, // 交易所送出訊息
ftm_SysReq, // 系統要求
ftm_End, // 定義結束
} K_EnumPacked;
K_class TEFTMode : public Kstl::EnumT<EFTMode>
{
typedef Kstl::EnumT<EFTMode> inherited;
public:
inline K_ctor TEFTMode(EFTMode a = ftm_Daily) : inherited(a) {}
K_mf(std::string) as_string () const;
K_mf(void) assign (const std::string&);
};
//---------------------------------------------------------------------------
#ifdef K_EnumPacked_Bug
typedef byte EFTType;
enum EFTType_t
#else
enum EFTType
#endif
{
ftt_File, // 檔案
ftt_Msg, // 訊息
ftt_End, // 定義結束
} K_EnumPacked;
K_class TEFTType : public Kstl::EnumT<EFTType>
{
typedef Kstl::EnumT<EFTType> inherited;
public:
inline K_ctor TEFTType(EFTType a = ftt_File): inherited(a) {}
K_mf(std::string) as_string () const;
K_mf(void) assign (const std::string&);
};
//---------------------------------------------------------------------------
#ifdef K_EnumPacked_Bug
typedef byte eEnvMode;
enum eEnvMode_t
#else
enum eEnvMode
#endif
{
evm_2T, //兩層式要求
evm_3T, //三層式要求
evm_End, //定義結束
} K_EnumPacked;
K_class TEnvMode : public Kstl::EnumT<eEnvMode>
{
typedef Kstl::EnumT<eEnvMode> inherited;
public:
inline K_ctor TEnvMode(EFTType a = evm_2T): inherited(a) {};
};
//---------------------------------------------------------------------------
struct TFTJobBase
{
TSeqNo SeqNo_; // seqno 作業序號
TBrkID SourceID_; // source id
TBrkID DestID_; // dest id
TMarket Market_; // TSE/OTC
};
//---------------------------------------------------------------------------
struct TFTNewJob : public TFTJobBase
{
TFileCode FileCode_;
TEFTType Type_; // File or Message
TEFTMode Mode_; // Mode
TSeqNo SrcSeqNo_; // 傳送要求來源的key
TMsgData SrcData_; // upload msg or filename
TMsgData DstData_; // download msg or filename
TSeqNo RecLen_; // Record len
TKTime CreateTime_;// 建立的時間
TEnvMode EnvMode_; // 此上傳要求來自二層還是三層架構20090212 for ubs
bool Done3T_; // 三層式下載作業(TSE->Broker)檔案複製己完成
K_ctor TFTNewJob():Done3T_(false){};
};
//---------------------------------------------------------------------------
typedef Kstl::rr_inn_file<Kway::uint64, Kway::dword> TCenterInn;
//---------------------------------------------------------------------------
struct TFTJob : public TFTNewJob
{
typedef TFTNewJob inherited;
TFTFlowID Flow_; // 狀態
TKTime SendTime_; // 傳送的時間
TStatusCode LastCode_; // 最後交易所的狀態碼
TKTime ReplyTime_; // 回覆的時間
TLastMsg LastMsg_; // 最後訊息
TCenterInn::rr_key mutable RoomKey_;
K_ctor TFTJob():inherited() { memset(this, 0, sizeof(TFTJob)); }
K_ctor TFTJob(const TFTNewJob& job){ memcpy(this, &job, sizeof(TFTJob)); }
};
//---------------------------------------------------------------------------
}; // FT
}; // Bx
}; // Tw
}; // Kway
#endif
| [
"xtwse@mail.kway.com.tw"
] | xtwse@mail.kway.com.tw |
d693eeccfdc18b10562363e33e7ee1eb72b82b9f | 22399b36d7ac54db1b394dd9f28d160f504c626c | /CK33.cpp | bd1e1567ab513f257d07a2a1e9a682b2ebb1b38f | [] | no_license | naveenkumar2405/CK_Set4 | 74115dbac242163a713626e772028ab3a8da94b8 | 57c7edad459082691f22510849cef90cf12d4aad | refs/heads/master | 2020-06-30T12:01:43.407400 | 2019-08-06T18:08:18 | 2019-08-06T18:08:18 | 200,819,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | cpp | #include<iostream>
using namespace std;
int main()
{
string s;
int len,i,count=0;
cin>>s;
getline(cin,s);
len=s.size();
for(i=0;i<len;i++)
{
if(s[i]==' ')
{
count++;
}
}
cout<<count;
return 0;
}
| [
"noreply@github.com"
] | naveenkumar2405.noreply@github.com |
915d8d0f2b6a6ea48b9de4793e569dbe883e496f | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14666/function14666_schedule_5/function14666_schedule_5_wrapper.cpp | fc210a822b98efe0453e6a3919fce087534e08de | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | #include "Halide.h"
#include "function14666_schedule_5_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(256);
Halide::Buffer<int32_t> buf01(256);
Halide::Buffer<int32_t> buf02(256);
Halide::Buffer<int32_t> buf03(256);
Halide::Buffer<int32_t> buf0(262144, 256);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14666_schedule_5(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14666/function14666_schedule_5/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
5a32ee3f3207b47e17be73b816001905d5d3c6ad | 9c172493199ba987acfa51c1b323be00efb852cd | /Medium/55.JumpGame/updateIndex.cpp | 4fcee05909588e66fd9e0271f3e6e1b7c93d65ac | [] | no_license | FriedCosey/LeetCode | 92a1084eeb8937d498411105ef6909ca4ca0d783 | 71a86e9bde3e3c9b1159085a773d370f3a75278c | refs/heads/master | 2021-07-11T08:03:20.516199 | 2019-01-10T01:26:40 | 2019-01-10T01:26:40 | 138,459,041 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cpp | class Solution {
public:
bool dfs(int pos, vector<int> nums){
if(pos >= nums.size())
return false;
if(pos == nums.size() - 1)
return true;
for(int i = 1; i <= nums[pos]; i++){
if(dfs(pos + i, nums))
return true;
}
return false;
}
bool canJump(vector<int>& nums) {
// return dfs(0, nums);
if(nums.size() == 1)
return true;
for(int i = 0; i < nums.size(); i++)
nums[i] += i;
int n = nums[0];
for(int i = 0; i <= n; i++){
if(nums[i] >= nums.size() - 1)
return true;
n = nums[i] > n ? nums[i] : n;
}
return false;
}
};
| [
"friedcosey@gmail.com"
] | friedcosey@gmail.com |
e95cbb7615eaccf13cf2b6772511b8ea9c8538d2 | 04a540847c1333c987a1957fd8d31197c594f6bb | /BOJ/1991_1.cpp | aa36f2165e453406a590cf4b2d12b1c604ae9ea2 | [] | no_license | k8440009/Algorithm | fd148269b264b580876c7426e19dbe2425ddc1ab | a48eba0ac5c9f2e10f3c509ce9d349c8a1dc3f0c | refs/heads/master | 2023-04-02T16:06:10.260768 | 2023-04-02T11:04:32 | 2023-04-02T11:04:32 | 200,506,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,222 | cpp | // 트리 순회
// https://www.acmicpc.net/problem/1991
#include <iostream>
#include <vector>
using namespace std;
const int MAX = 26 + 1;
int N;
vector <vector<int> > tree;
void postorder(int node)
{
int left = tree[node][0];
int right = tree[node][1];
if (left != -1)
postorder(left);
if (right != -1)
postorder(right);
cout << (char)(node + 'A');
return ;
}
void inorder(int node)
{
int left = tree[node][0];
int right = tree[node][1];
if (left != -1)
inorder(left);
cout << (char)(node + 'A');
if (right != -1)
inorder(right);
return ;
}
void preorder(int node)
{
int left = tree[node][0];
int right = tree[node][1];
cout << (char)(node + 'A');
if (left != -1)
preorder(left);
if (right != -1)
preorder(right);
return ;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
//freopen("input.txt", "r", stdin);
cin >> N;
tree.resize(N + 1);
for (int i = 0; i < N; i++)
{
char data;
cin >> data;
for (int j = 0; j < 2; j++)
{
char tmp;
cin >> tmp;
if (tmp == '.')
tree[int(data - 'A')].push_back(-1);
else
tree[int(data - 'A')].push_back(tmp - 'A');
}
}
preorder(0);
cout << '\n';
inorder(0);
cout << '\n';
postorder(0);
} | [
"k8440009@gmail.com"
] | k8440009@gmail.com |
0abd10d85d6890927d25c7204b97fc3278faf9b7 | 462940b061dd614b06038b6a4195160e374e2ac0 | /BST.h | a1e5f5a91e4f4171274459efc95310aec3b578a5 | [] | no_license | ashmahein/Encryption-Code-Converter | 7f6b135aec37fecd9a7fd11869964ae2811cf39d | 3a4678dd136e919ec1d0851751413495cf805ac5 | refs/heads/master | 2020-07-05T20:58:35.306867 | 2016-11-17T02:13:24 | 2016-11-17T02:13:24 | 73,980,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,162 | h | /*******************************************************************************
* Programmer: Ash Mahein *
* Class: CptS 122; Lab Section 1 *
* Programming Assignment: 6 *
* Date: 7/13/16 *
* *
* Description: This program reads in a file with english characters and morse *
* code characters into a BST. It then reads in a file with *
* english characters and converts it to morse code using a look *
* function. *
* *
* Relevant Formulas: NONE *
* Collaboration: Andy O'Fallon, Rahul Singal. *
* Websites used: Stackoverflow *
******************************************************************************/
#pragma once
#include "BSTNode.h"
class BST
{
public:
//constructor
BST();
//destructor
~BST();
//helper function
void insert(const char &newText, const string &newCode)
{
insert(this->pRoot, newText, newCode);
}
//helper function
void inOrderTraversal()
{
inOrderTraversal(*&pRoot);
}
//helper function. Opens file and reads it into search function.
void searchTree()
{
if (!readInfile.is_open())
{
readInfile.open("Convert.txt", ios::in);
char line, line_s;
while (!readInfile.eof())
{
line = readInfile.get();
line_s = toupper(line);
searchTree(this->pRoot, line_s);
}
}
readInfile.close();
}
private:
//private data memebers
fstream readInfile;
fstream codeInfile;
BSTNode *pRoot;
void insert(BSTNode *&pTree, const char &newText, const string &newCode);
void inOrderTraversal(BSTNode *&pTree);
void searchTree(BSTNode *&pTree, char upperLine);
}; | [
"noreply@github.com"
] | ashmahein.noreply@github.com |
3be6e38fe0b089e8e3aa7daf7bde9ef4bd46b9e7 | 2ad4fdf201138c5e70f4f9accf9af3b7c811520f | /05_maze/to students/Student_Code/main.cpp | 4519ed71afe4474a345976c40ad2d504937f4df6 | [] | no_license | Blankenship-Daniel/cs_235 | 1e562b63fc2460855afcb3420a14feaf1719dcd8 | 0f195d3d5a4807583c08b81250499a6c4f3adf8c | refs/heads/master | 2020-12-24T13:21:28.665081 | 2015-12-25T20:26:31 | 2015-12-25T20:26:31 | 34,682,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | cpp | #include "Pathfinder.h"
#include <iostream>
using namespace std;
/******************************
* MAIN
* a simple driver program.
*****************************/
int main()
{
Pathfinder p;
p.createRandomMaze();
p.solveMaze();
p.printMaze();
return 0;
}
| [
"blankenshipdanielj@gmail.com"
] | blankenshipdanielj@gmail.com |
5cb44f531599035ce06123a20be7bceb820c0fd8 | 9f216b8bc1774e36b4bf79f9d99234b6e69bb11a | /include/tgbot/TgTypeParser.h | 0571c2529ebeb89a8a0968e50369ba20cd201c25 | [
"MIT"
] | permissive | gitter-badger/tgbot-cpp | 89dee3b93908315da394ed123148811bf6ae0bc8 | fb31f739c28e374d41834f3ba0a928bd92cca5df | refs/heads/master | 2021-01-15T12:58:58.605565 | 2015-07-27T18:16:29 | 2015-07-27T18:16:29 | 39,790,435 | 0 | 0 | null | 2015-07-27T18:18:14 | 2015-07-27T18:18:14 | null | UTF-8 | C++ | false | false | 8,208 | h | /*
* Copyright (c) 2015 Oleg Morozenkov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef TGBOT_CPP_TGTYPEPARSER_H
#define TGBOT_CPP_TGTYPEPARSER_H
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "tgbot/types/User.h"
#include "tgbot/types/GroupChat.h"
#include "tgbot/types/Message.h"
#include "tgbot/types/PhotoSize.h"
#include "tgbot/types/Audio.h"
#include "tgbot/types/Document.h"
#include "tgbot/types/Sticker.h"
#include "tgbot/types/Video.h"
#include "tgbot/types/Contact.h"
#include "tgbot/types/Location.h"
#include "tgbot/types/Update.h"
#include "tgbot/types/UserProfilePhotos.h"
#include "tgbot/types/ReplyKeyboardMarkup.h"
#include "tgbot/types/ReplyKeyboardHide.h"
#include "tgbot/types/ForceReply.h"
#include "tgbot/types/GenericReply.h"
namespace TgBot {
class TgTypeParser {
public:
static TgTypeParser& getInstance();
User::Ptr parseUser(const boost::property_tree::ptree& data) const;
std::string parseUser(const User::Ptr& object) const;
GroupChat::Ptr parseGroupChat(const boost::property_tree::ptree& data) const;
std::string parseGroupChat(const GroupChat::Ptr& object) const;
Message::Ptr parseMessage(const boost::property_tree::ptree& data) const;
std::string parseMessage(const Message::Ptr& object) const;
PhotoSize::Ptr parsePhotoSize(const boost::property_tree::ptree& data) const;
std::string parsePhotoSize(const PhotoSize::Ptr& object) const;
Audio::Ptr parseAudio(const boost::property_tree::ptree& data) const;
std::string parseAudio(const Audio::Ptr& object) const;
Document::Ptr parseDocument(const boost::property_tree::ptree& data) const;
std::string parseDocument(const Document::Ptr& object) const;
Sticker::Ptr parseSticker(const boost::property_tree::ptree& data) const;
std::string parseSticker(const Sticker::Ptr& object) const;
Video::Ptr parseVideo(const boost::property_tree::ptree& data) const;
std::string parseVideo(const Video::Ptr& object) const;
Contact::Ptr parseContact(const boost::property_tree::ptree& data) const;
std::string parseContact(const Contact::Ptr& object) const;
Location::Ptr parseLocation(const boost::property_tree::ptree& data) const;
std::string parseLocation(const Location::Ptr& object) const;
Update::Ptr parseUpdate(const boost::property_tree::ptree& data) const;
std::string parseUpdate(const Update::Ptr& object) const;
UserProfilePhotos::Ptr parseUserProfilePhotos(const boost::property_tree::ptree& data) const;
std::string parseUserProfilePhotos(const UserProfilePhotos::Ptr& object) const;
ReplyKeyboardMarkup::Ptr parseReplyKeyboardMarkup(const boost::property_tree::ptree& data) const;
std::string parseReplyKeyboardMarkup(const ReplyKeyboardMarkup::Ptr& object) const;
ReplyKeyboardHide::Ptr parseReplyKeyboardHide(const boost::property_tree::ptree& data) const;
std::string parseReplyKeyboardHide(const ReplyKeyboardHide::Ptr& object) const;
ForceReply::Ptr parseForceReply(const boost::property_tree::ptree& data) const;
std::string parseForceReply(const ForceReply::Ptr& object) const;
GenericChat::Ptr parseGenericChat(const boost::property_tree::ptree& data) const;
std::string parseGenericChat(const GenericChat::Ptr& object) const;
GenericReply::Ptr parseGenericReply(const boost::property_tree::ptree& data) const;
std::string parseGenericReply(const GenericReply::Ptr& object) const;
inline boost::property_tree::ptree parseJson(const std::string& json) const {
boost::property_tree::ptree tree;
std::istringstream input(json);
boost::property_tree::read_json(input, tree);
return tree;
}
template<typename T>
std::shared_ptr<T> tryParse(std::shared_ptr<T> (TgTypeParser::*const parseFunc)(const boost::property_tree::ptree&) const, const boost::property_tree::ptree& data, const std::string& keyName) const {
auto treeItem = data.find(keyName);
if (treeItem == data.not_found()) {
return std::shared_ptr<T>();
}
return (this->*parseFunc)(treeItem->second);
}
template<typename T>
std::vector<std::shared_ptr<T>> parseArray(std::shared_ptr<T> (TgTypeParser::*const parseFunc)(const boost::property_tree::ptree&) const, const boost::property_tree::ptree& data, const std::string& keyName) const {
std::vector<std::shared_ptr<T>> result;
auto treeItem = data.find(keyName);
if (treeItem == data.not_found()) {
return result;
}
for (const std::pair<const std::string, boost::property_tree::ptree>& innerTreeItem : treeItem->second) {
result.push_back((this->*parseFunc)(innerTreeItem.second));
}
return result;
}
template<typename T>
std::vector<std::vector<std::shared_ptr<T>>> parse2DArray(std::shared_ptr<T> (TgTypeParser::*const parseFunc)(const boost::property_tree::ptree&) const, const boost::property_tree::ptree& data, const std::string& keyName) const {
std::vector<std::vector<std::shared_ptr<T>>> result;
auto treeItem = data.find(keyName);
if (treeItem == data.not_found()) {
return result;
}
for (const std::pair<const std::string, boost::property_tree::ptree>& innerTreeItem : treeItem->second) {
std::vector<std::shared_ptr<T>> innerResult;
for (const std::pair<const std::string, boost::property_tree::ptree>& innerInnerTreeItem : innerTreeItem.second) {
innerResult.push_back((this->*parseFunc)(innerInnerTreeItem.second));
}
result.push_back(innerResult);
}
return result;
}
template<typename T>
std::string parseArray(std::string (TgTypeParser::*const parseFunc)(const std::shared_ptr<T>&) const, const std::vector<std::shared_ptr<T>>& objects) const {
std::string result;
result += '[';
for (const std::shared_ptr<T>& item : objects) {
result += (this->*parseFunc)(item);
result += ',';
}
result.erase(result.length() - 1);
result += ']';
return result;
}
template<typename T>
std::string parse2DArray(std::string (TgTypeParser::*const parseFunc)(const std::shared_ptr<T>&) const, const std::vector<std::vector<std::shared_ptr<T>>>& objects) const {
std::string result;
result += '[';
for (const std::vector<std::shared_ptr<T>>& item : objects) {
result += parseArray(parseFunc, item);
result += ',';
}
result.erase(result.length() - 1);
result += ']';
return result;
}
private:
template<typename T>
void appendToJson(std::string& json, const std::string& varName, const T& value) const {
if (value == 0) {
return;
}
json += '"';
json += varName;
json += "\":";
json += value;
json += ',';
}
void appendToJson(std::string& json, const std::string& varName, const std::string& value) const;
};
}
#endif //TGBOT_CPP_TGTYPEPARSER_H
| [
"omorozenkov@gmail.com"
] | omorozenkov@gmail.com |
01f5aadbdd6b8fe5735c66fd1f584e4cd025f74d | 7e727acec476c33524ebacb72cb566b719ac444f | /cake/stdafx.h | 38854963568844f64c438f304c13763bcbc4ef9a | [] | no_license | krig/cake | f61849e4b8ae845f9da4ca2c2fbc41028082859d | c063a3259c4cc92b1f2e836f341c4c4e5dd87e21 | refs/heads/master | 2018-12-28T16:05:28.043717 | 2008-09-23T11:04:17 | 2008-09-23T11:04:17 | 54,683 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,109 | h | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <glob.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <errno.h>
#include <assert.h>
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include <string>
#include <vector>
#include <map>
#include <boost/shared_ptr.hpp>
extern const char* g_compiler;
extern const char* g_compile_options[];
extern const char* g_link_options[];
extern const char* g_pch_options[];
extern char g_objdir[260];
extern const char* g_baseobjdir;
extern const char* g_bindir;
extern const char* g_libdir;
extern bool g_verbose_flag;
extern bool g_silent_flag;
extern bool g_rebuild_flag;
extern bool g_print_colors;
extern const char* g_target;
extern const char* HOME;
typedef std::vector<std::string> stringlist;
struct table
{
typedef boost::shared_ptr<table> ptr;
typedef std::map<std::string, std::string> vmap;
typedef std::map<std::string, ptr> tmap;
typedef stringlist svec;
typedef std::vector<ptr> tvec;
vmap values;
tmap children;
svec strings;
tvec tables;
};
#include "utility.h"
| [
"deceiver.g@gmail.com"
] | deceiver.g@gmail.com |
436d9de56dc84a617c71d2b42849b13ee5ccc10c | 073d693d3369e41a29f842c0b153241e47e1b2ac | /src/wallet/test/wallet_shielded_balances_tests.cpp | 54ed5df1ee6fc6d061ab194570ace241a0eec64d | [
"MIT"
] | permissive | robervem/sbercoin | 2a7984a7d77a63c51957e9b8b6df6bc759925d2e | ba61e50fab7e3b15e39a9cbe3a7adf08cab96d39 | refs/heads/main | 2023-02-09T21:16:56.425759 | 2021-01-07T20:09:19 | 2021-01-07T20:09:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,627 | cpp | // Copyright (c) 2020 The SBER developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php.
#include "wallet/test/wallet_test_fixture.h"
#include "consensus/merkle.h"
#include "primitives/block.h"
#include "random.h"
#include "sapling/note.h"
#include "sapling/noteencryption.h"
#include "sapling/transaction_builder.h"
#include "test/librust/utiltest.h"
#include "wallet/wallet.h"
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
CAmount fee = COIN; // Hardcoded fee
BOOST_FIXTURE_TEST_SUITE(wallet_shielded_balances_tests, WalletTestingSetup)
void setupWallet(CWallet& wallet)
{
wallet.SetMinVersion(FEATURE_SAPLING);
wallet.SetupSPKM(false);
}
// Find and set notes data in the tx + add any missing ivk to the wallet's keystore.
CWalletTx& SetWalletNotesData(CWallet* wallet, CWalletTx& wtx)
{
Optional<mapSaplingNoteData_t> saplingNoteData{nullopt};
wallet->FindNotesDataAndAddMissingIVKToKeystore(wtx, saplingNoteData);
assert(static_cast<bool>(saplingNoteData));
wtx.SetSaplingNoteData(*saplingNoteData);
BOOST_CHECK(wallet->AddToWallet(wtx));
// Updated tx
return wallet->mapWallet[wtx.GetHash()];
}
/**
* Creates and send a tx with an input of 'inputAmount' to 'vDest'.
*/
CWalletTx& AddShieldedBalanceToWallet(const CAmount& inputAmount,
std::vector<ShieldedDestination> vDest,
CWallet* wallet,
const Consensus::Params& consensusParams)
{
// Dummy wallet, used to generate the dummy transparent input key and sign it in the transaction builder
CWallet dummyWallet;
dummyWallet.SetMinVersion(FEATURE_SAPLING);
dummyWallet.SetupSPKM(false, true);
LOCK(dummyWallet.cs_wallet);
// Create a transaction shielding balance to 'vDest' and load it to the wallet.
CWalletTx wtx = GetValidSaplingReceive(consensusParams, dummyWallet, inputAmount, vDest, wallet);
// Updated tx after load it to the wallet
CWalletTx& wtxUpdated = SetWalletNotesData(wallet, wtx);
// Check tx credit now
BOOST_CHECK_EQUAL(wtxUpdated.GetCredit(ISMINE_ALL), inputAmount);
BOOST_CHECK(wtxUpdated.IsAmountCached(CWalletTx::CREDIT, ISMINE_SPENDABLE_SHIELDED));
return wtxUpdated;
}
CWalletTx& AddShieldedBalanceToWallet(libzcash::SaplingPaymentAddress& sendTo, CAmount amount,
CWallet& wallet, const Consensus::Params& consensusParams,
libzcash::SaplingExtendedSpendingKey& extskOut)
{
// Create a transaction shielding balance to 'sendTo' and load it to the wallet.
BOOST_CHECK(wallet.GetSaplingExtendedSpendingKey(sendTo, extskOut));
std::vector<ShieldedDestination> vDest;
vDest.push_back({extskOut, amount});
return AddShieldedBalanceToWallet(amount, vDest, &wallet, consensusParams);
}
struct SaplingSpendValues {
libzcash::SaplingNote note;
const uint256 anchor;
const SaplingWitness witness;
};
/**
* Update the wallet internally as if the wallet would had received a valid block containing wtx.
* Then return the note, anchor and witness for any subsequent spending process.
*/
SaplingSpendValues UpdateWalletInternalNotesData(CWalletTx& wtx, SaplingOutPoint& sapPoint, CWallet& wallet)
{
// Get note
SaplingNoteData nd = wtx.mapSaplingNoteData.at(sapPoint);
assert(nd.IsMyNote());
const auto& ivk = *(nd.ivk);
auto maybe_pt = libzcash::SaplingNotePlaintext::decrypt(
wtx.sapData->vShieldedOutput[sapPoint.n].encCiphertext,
ivk,
wtx.sapData->vShieldedOutput[sapPoint.n].ephemeralKey,
wtx.sapData->vShieldedOutput[sapPoint.n].cmu);
assert(static_cast<bool>(maybe_pt));
boost::optional<libzcash::SaplingNotePlaintext> notePlainText = maybe_pt.get();
libzcash::SaplingNote note = notePlainText->note(ivk).get();
// Append note to the tree
auto commitment = note.cmu().get();
SaplingMerkleTree tree;
tree.append(commitment);
auto anchor = tree.root();
auto witness = tree.witness();
// Update wtx credit chain data
// Pretend we mined the tx by adding a fake witness and nullifier to be able to spend it.
wtx.mapSaplingNoteData[sapPoint].witnesses.push_front(tree.witness());
wtx.mapSaplingNoteData[sapPoint].witnessHeight = 1;
wallet.GetSaplingScriptPubKeyMan()->nWitnessCacheSize = 1;
wallet.GetSaplingScriptPubKeyMan()->UpdateSaplingNullifierNoteMapWithTx(wtx);
return {note, anchor, witness};
}
/**
* Validates:
* 1) CWalletTx getCredit for shielded credit.
* Incoming spendable shielded balance must be cached in the cacheableAmounts.
*
* 2) CWalletTx getDebit & getCredit for shielded debit to transparent address.
* Same wallet as point (1), spending half of the credit received in (1) to a transparent remote address.
* The other half of the balance - minus fee - must appear as credit (shielded change).
*
*/
BOOST_AUTO_TEST_CASE(GetShieldedSimpleCachedCreditAndDebit)
{
///////////////////////
//////// Credit ////////
///////////////////////
auto consensusParams = RegtestActivateSapling();
// Main wallet
CWallet &wallet = *pwalletMain;
LOCK2(cs_main, wallet.cs_wallet);
setupWallet(wallet);
// First generate a shielded address
libzcash::SaplingPaymentAddress pa = wallet.GenerateNewSaplingZKey();
CAmount firstCredit = COIN * 10;
// Add shielded balance.
libzcash::SaplingExtendedSpendingKey extskOut;
CWalletTx& wtxUpdated = AddShieldedBalanceToWallet(pa, firstCredit, wallet, consensusParams, extskOut);
///////////////////////
//////// Debit ////////
///////////////////////
// Update transaction and wallet internal state to be able to spend it.
SaplingOutPoint sapPoint {wtxUpdated.GetHash(), 0};
SaplingSpendValues sapSpendValues = UpdateWalletInternalNotesData(wtxUpdated, sapPoint, wallet);
// Debit value
CAmount firstDebit = COIN * 5;
CAmount firstDebitShieldedChange = firstDebit - fee;
// Create the spending transaction
auto builder = TransactionBuilder(consensusParams, 1, &wallet);
builder.SetFee(fee);
builder.AddSaplingSpend(
extskOut.expsk,
sapSpendValues.note,
sapSpendValues.anchor,
sapSpendValues.witness);
// Send to transparent address
builder.AddTransparentOutput(CreateDummyDestinationScript(),
firstDebit);
CTransaction tx = builder.Build().GetTxOrThrow();
// add tx to wallet and update it.
wallet.AddToWallet({&wallet, tx});
CWalletTx& wtxDebit = wallet.mapWallet[tx.GetHash()];
// Update tx notes data (shielded change need it)
CWalletTx& wtxDebitUpdated = SetWalletNotesData(&wallet, wtxDebit);
// The debit need to be the entire first note value
BOOST_CHECK_EQUAL(wtxDebitUpdated.GetDebit(ISMINE_ALL), firstCredit);
BOOST_CHECK(wtxDebitUpdated.IsAmountCached(CWalletTx::DEBIT, ISMINE_SPENDABLE_SHIELDED));
// The credit should be only the change.
BOOST_CHECK_EQUAL(wtxDebitUpdated.GetCredit(ISMINE_ALL), firstDebitShieldedChange);
BOOST_CHECK(wtxDebitUpdated.IsAmountCached(CWalletTx::CREDIT, ISMINE_SPENDABLE_SHIELDED));
// Checks that the only shielded output of this tx is change.
BOOST_CHECK(wallet.GetSaplingScriptPubKeyMan()->IsNoteSaplingChange(
SaplingOutPoint(wtxDebitUpdated.GetHash(), 0), pa));
// Revert to default
RegtestDeactivateSapling();
}
libzcash::SaplingPaymentAddress getNewDummyShieldedAddress()
{
HDSeed seed;
auto m = libzcash::SaplingExtendedSpendingKey::Master(seed);
return m.DefaultAddress();
}
CWalletTx& buildTxAndLoadToWallet(CWallet& wallet, libzcash::SaplingExtendedSpendingKey extskOut,
const SaplingSpendValues& sapSpendValues, libzcash::SaplingPaymentAddress dest,
const CAmount& destAmount, const Consensus::Params& consensus)
{
// Create the spending transaction
auto builder = TransactionBuilder(consensus, 1, &wallet);
builder.SetFee(fee);
builder.AddSaplingSpend(
extskOut.expsk,
sapSpendValues.note,
sapSpendValues.anchor,
sapSpendValues.witness);
// Send to shielded address
builder.AddSaplingOutput(
extskOut.expsk.ovk,
dest,
destAmount,
{}
);
CTransaction tx = builder.Build().GetTxOrThrow();
// add tx to wallet and update it.
wallet.AddToWallet({&wallet, tx});
CWalletTx& wtx = wallet.mapWallet[tx.GetHash()];
// Update tx notes data and return the updated wtx.
return SetWalletNotesData(&wallet, wtx);
}
/**
* Validates shielded to remote shielded + change cached balances.
*/
BOOST_AUTO_TEST_CASE(VerifyShieldedToRemoteShieldedCachedBalance)
{
auto consensusParams = RegtestActivateSapling();
// Main wallet
CWallet &wallet = *pwalletMain;
LOCK2(cs_main, wallet.cs_wallet);
setupWallet(wallet);
// First generate a shielded address
libzcash::SaplingPaymentAddress pa = wallet.GenerateNewSaplingZKey();
CAmount firstCredit = COIN * 20;
// Add shielded balance.
libzcash::SaplingExtendedSpendingKey extskOut;
CWalletTx& wtxUpdated = AddShieldedBalanceToWallet(pa, firstCredit, wallet, consensusParams, extskOut);
// Update transaction and wallet internal state to be able to spend it.
SaplingOutPoint sapPoint {wtxUpdated.GetHash(), 0};
SaplingSpendValues sapSpendValues = UpdateWalletInternalNotesData(wtxUpdated, sapPoint, wallet);
// Remote destination values
libzcash::SaplingPaymentAddress destShieldedAddress = getNewDummyShieldedAddress();
CAmount destAmount = COIN * 8;
// Create the spending transaction and load it to the wallet
CWalletTx& wtxDebitUpdated = buildTxAndLoadToWallet(wallet,
extskOut,
sapSpendValues,
destShieldedAddress,
destAmount,
consensusParams);
// Validate results
CAmount expectedShieldedChange = firstCredit - destAmount - fee;
// The debit need to be the entire first note value
BOOST_CHECK_EQUAL(wtxDebitUpdated.GetDebit(ISMINE_ALL), firstCredit);
BOOST_CHECK(wtxDebitUpdated.IsAmountCached(CWalletTx::DEBIT, ISMINE_SPENDABLE_SHIELDED));
// The credit should be only the change.
BOOST_CHECK_EQUAL(wtxDebitUpdated.GetCredit(ISMINE_ALL), expectedShieldedChange);
BOOST_CHECK(wtxDebitUpdated.IsAmountCached(CWalletTx::CREDIT, ISMINE_SPENDABLE_SHIELDED));
// Plus, change should be same and be cached as well
BOOST_CHECK_EQUAL(wtxDebitUpdated.GetShieldedChange(), expectedShieldedChange);
BOOST_CHECK(wtxDebitUpdated.fShieldedChangeCached);
// Revert to default
RegtestDeactivateSapling();
}
struct FakeBlock
{
CBlock block;
CBlockIndex* pindex;
};
FakeBlock SimpleFakeMine(CWalletTx& wtx, SaplingMerkleTree& currentTree)
{
FakeBlock fakeBlock;
fakeBlock.block.nVersion = 8;
fakeBlock.block.vtx.emplace_back(MakeTransactionRef(wtx));
fakeBlock.block.hashMerkleRoot = BlockMerkleRoot(fakeBlock.block);
for (const OutputDescription& out : wtx.sapData->vShieldedOutput) {
currentTree.append(out.cmu);
}
fakeBlock.block.hashFinalSaplingRoot = currentTree.root();
fakeBlock.pindex = new CBlockIndex(fakeBlock.block);
mapBlockIndex.insert(std::make_pair(fakeBlock.block.GetHash(), fakeBlock.pindex));
fakeBlock.pindex->phashBlock = &mapBlockIndex.find(fakeBlock.block.GetHash())->first;
chainActive.SetTip(fakeBlock.pindex);
BOOST_CHECK(chainActive.Contains(fakeBlock.pindex));
wtx.SetMerkleBranch(fakeBlock.pindex->GetBlockHash(), 0);
return fakeBlock;
}
/**
* Test:
* 1) receive two shielded notes on the same tx.
* 2) check available credit.
* 3) spend one of them.
* 4) force available credit cache recalculation and validate the updated amount.
*/
BOOST_AUTO_TEST_CASE(GetShieldedAvailableCredit)
{
auto consensusParams = RegtestActivateSapling();
// Main wallet
CWallet &wallet = *pwalletMain;
LOCK2(cs_main, wallet.cs_wallet);
setupWallet(wallet);
// 1) generate a shielded address and send 20 PIV in two shielded outputs
libzcash::SaplingPaymentAddress pa = wallet.GenerateNewSaplingZKey();
CAmount credit = COIN * 20;
// Add two equal shielded outputs.
libzcash::SaplingExtendedSpendingKey extskOut;
BOOST_CHECK(wallet.GetSaplingExtendedSpendingKey(pa, extskOut));
std::vector<ShieldedDestination> vDest;
vDest.push_back({extskOut, credit / 2});
vDest.push_back({extskOut, credit / 2});
CWalletTx& wtxUpdated = AddShieldedBalanceToWallet(credit, vDest, &wallet, consensusParams);
// Available credit ISMINE_SPENDABLE must be 0
// Available credit ISMINE_SHIELDED_SPENDABLE must be 'credit' and be cached.
BOOST_CHECK_EQUAL(wtxUpdated.GetAvailableCredit(true, ISMINE_SPENDABLE), 0);
BOOST_CHECK_EQUAL(wtxUpdated.GetShieldedAvailableCredit(), credit);
BOOST_CHECK(wtxUpdated.IsAmountCached(CWalletTx::AVAILABLE_CREDIT, ISMINE_SPENDABLE_SHIELDED));
// 2) Confirm the tx
SaplingMerkleTree tree;
FakeBlock fakeBlock = SimpleFakeMine(wtxUpdated, tree);
wallet.ChainTip(fakeBlock.pindex, &fakeBlock.block, tree);
wtxUpdated = wallet.mapWallet[wtxUpdated.GetHash()];
// 3) Now can spend one output and recalculate the shielded credit.
std::vector<SaplingNoteEntry> saplingEntries;
Optional<libzcash::SaplingPaymentAddress> opPa(pa);
wallet.GetSaplingScriptPubKeyMan()->GetFilteredNotes(saplingEntries,
opPa,
0);
std::vector<SaplingOutPoint> ops = {saplingEntries[0].op};
uint256 anchor;
std::vector<boost::optional<SaplingWitness>> witnesses;
pwalletMain->GetSaplingScriptPubKeyMan()->GetSaplingNoteWitnesses(ops, witnesses, anchor);
SaplingSpendValues sapSpendValues{saplingEntries[0].note, anchor, *witnesses[0]};
// Remote destination values
libzcash::SaplingPaymentAddress destShieldedAddress = getNewDummyShieldedAddress();
CAmount change = COIN * 1;
CAmount destAmount = credit / 2 - fee - change; // one note - fee
// Create the spending transaction and load it to the wallet
CWalletTx& wtxDebitUpdated = buildTxAndLoadToWallet(wallet,
extskOut,
sapSpendValues,
destShieldedAddress,
destAmount,
consensusParams);
// Check previous credit tx balance being the same and then force a recalculation
BOOST_CHECK_EQUAL(wtxUpdated.GetShieldedAvailableCredit(), credit);
BOOST_CHECK_EQUAL(wtxUpdated.GetShieldedAvailableCredit(false), credit / 2);
BOOST_CHECK_EQUAL(wtxUpdated.GetShieldedChange(), 0);
// Now check the debit tx
BOOST_CHECK_EQUAL(wtxDebitUpdated.GetDebit(ISMINE_SPENDABLE_SHIELDED), credit / 2);
BOOST_CHECK_EQUAL(wtxDebitUpdated.GetShieldedChange(), change);
BOOST_CHECK_EQUAL(wtxDebitUpdated.GetCredit(ISMINE_SPENDABLE_SHIELDED), change);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"k.arya2946@gmail.com"
] | k.arya2946@gmail.com |
36dba4338d32c0dd9a46f1c0c593c00f335c962a | 7b2c4d6d4d521d1d25e2226a0840c34d94bc6b4e | /234_longest_subsequence_adjacent_diff_is_1_dp.cpp | 4760a7b7296959b8831a681c4c647abfbdb9ff7a | [] | no_license | kh-8484/DSA | 642146605218ab930468fb9c57af76e6b9e425f9 | 9ee570daf0f054d04185824719ced93785aa4747 | refs/heads/main | 2023-06-25T08:03:02.844329 | 2021-07-29T13:13:24 | 2021-07-29T13:13:24 | 390,722,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,190 | cpp | // { Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
int longestSubsequence(int n, int a[])
{
// code here
// int dp[n];
// for(int i=0; i<n; i++) dp[i] = 1;
// for(int i=1; i<n; i++){
// for(int j=0; j<i; j++){
// if(abs(a[j]-a[i]) == 1){
// dp[i] = max(dp[i], dp[j]+1);
// }
// }
// }
// int ans=0;
// for(int i=0; i<n; i++){
// ans = max(ans, dp[i]);
// }
// return ans;
unordered_map<int, int> m;
int ans = 0;
for (int i = 0; i < n; i++) {
int l = 0;
if (m[a[i] - 1]) l = m[a[i] - 1];
if (m[a[i] + 1] && m[a[i] + 1] > l) l = m[a[i] + 1]; //checking l is >
//l is update in m[a[i]-1]
m[a[i]] = l + 1;
ans = max(ans, m[a[i]]);
}
return ans;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin >> N;
int A[N];
for (int i = 0; i < N; i++)
cin >> A[i];
Solution ob;
cout << ob.longestSubsequence(N, A) << endl;
}
return 0;
} // } Driver Code Ends | [
"noreply@github.com"
] | kh-8484.noreply@github.com |
2c26d7699dc11a8c1a7c30de7fdea8deb09e1537 | 635df129fcc98413a6010de626bf7e2170573527 | /knnPredictor.cpp | f352229972cca7156f7b62df4b9b7c3da8724555 | [] | no_license | davidmace/Miscillaneous | c464d5585154b598353d28129cd8fbdbeaed3c10 | 1c578fb3bd0489f15327ad145bd10804778cd233 | refs/heads/master | 2021-01-23T11:49:08.771081 | 2015-02-14T03:31:17 | 2015-02-14T03:31:17 | 30,785,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,427 | cpp | // Netflix dataset KNN classifier.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <cmath>
#include <map>
#include <ctime>
using namespace std;
class UserRating {
public:
int user, numRatings;
};
bool comparesize (UserRating i,UserRating j) { return (i.numRatings>j.numRatings); }
class MovieRating {
public:
int movie, rating;
};
bool comparemovie (MovieRating i,MovieRating j) { return (i.movie<j.movie); }
class Parsons {
public:
int user;
float p;
};
bool compareparsons (Parsons i,Parsons j) { return (i.p>j.p); }
int main() {
string s;
fstream exampleFile("data1.dta", ios::in);
fstream queryFile("qual.dta", ios::in);
ofstream out;
out.open ("predictions.txt");
int n=0;
double sum=0;
//each point stores movieid, rating
int numUsers=460000;
int numMovies=18000;
int Q=1000;
int K=100;
vector< vector<MovieRating> > userMovies; //stores lists of movies rated by a user
for (int i=0; i<=numUsers; i++) {
userMovies.push_back(vector<MovieRating>());
}
//storage is like arr[user][movie]=rating
vector< map<int,int> > userMovieRatings = vector< map<int,int> >();
for(int i=0; i<=numUsers; i++) {
userMovieRatings.push_back( map<int,int>() );
}
// parse input file
int count=0;
while (exampleFile.good()) {
count++;
if (count%100000==0) {cout << yu << endl;}
//tokenize line
getline(exampleFile, s);
if(count%3==0) { continue; } //TEMP debug
if (s=="") { continue; }
string delimiter=" ";
size_t pos = s.find(delimiter);
int user,movie,rating;
string token = s.substr(0, pos);
istringstream(token) >> user;
s.erase(0, pos + delimiter.length());
pos = s.find(delimiter);
token = s.substr(0, pos);
istringstream(token) >> movie;
s.erase(0, pos + delimiter.length());
pos = s.find(delimiter);
token = s.substr(0, pos);
s.erase(0, pos + delimiter.length());
pos = s.find(delimiter);
token = s.substr(0, pos);
istringstream(token) >> rating;
s.erase(0, pos + delimiter.length());
MovieRating r; r.movie=movie; r.rating=rating;
userMovies[user].push_back(r);
userMovieRatings[user][movie]=rating;
}
for(int user=0; user<=numUsers; user++) {
sort(userMovies[user].begin(),userMovies[user].end(),comparemovie);
}
//calculate user rating average and stdev
vector<float> useravg, userstd;
useravg.push_back(0); userstd.push_back(0);
for(int i=1; i<=numUsers; i++) {
if (userMovies[i].size()==0) {
useravg.push_back(0); userstd.push_back(0);
continue;
}
float sum=0;
for(int j=0; j<userMovies[i].size(); j++) {
sum+=userMovies[i][j].rating;
}
useravg.push_back( sum/userMovies[i].size() );
float sqrsum=0;
for(int j=0; j<userMovies[i].size(); j++) {
float d=(userMovies[i][j].rating-useravg[i]);
sqrsum+=d*d;
}
userstd.push_back( sqrt( sqrsum/userMovies[i].size() ) );
}
///select Q people who have rated the most movies
vector<UserRating> userratings;
for(int i=1; i<=numUsers; i++) {
UserRating pair;
pair.user=i;
pair.numRatings=userMovies[i].size();
userratings.push_back(pair);
}
sort(userratings.begin(),userratings.end(),comparesize);
int usersComparingAgainst[Q];
for(int i=0; i<Q; i++) {
usersComparingAgainst[i]=userratings[i].user;
}
//set up query storage representations
vector< vector<int> > queryusermovies;
vector< vector<int> > queryusermoviespos; //stores query position of movie
for(int i=0; i<=numUsers; i++) {
queryusermovies.push_back(vector<int>());
queryusermoviespos.push_back(vector<int>());
}
// parse test data
int linenum=0;
while (queryFile.good()) {
//tokenize line
getline(queryFile, s);
if(s=="") continue;
string delimiter=" ";
size_t pos = s.find(delimiter);
int user,movie;
string token = s.substr(0, pos);
istringstream(token) >> user;
s.erase(0, pos + delimiter.length());
pos = s.find(delimiter);
token = s.substr(0, pos);
istringstream(token) >> movie;
queryusermovies[user].push_back(movie);
queryusermoviespos[user].push_back(linenum);
linenum++;
}
// stores the predictions
vector<float> answers;
for(int i=0; i<linenum; i++) {
answers.push_back(0);
}
// loop through users
for(int user=1; user<=numUsers; user++) {
//if(user==5000) { break; } //TEMP
if (user%100==0) {
cout << user << endl;
}
// user has no movies
if(queryusermovies[user].size()==0) {
continue;
}
//compute p for all possible neighbors
vector<float> p;
for(int i=0; i<Q; i++) {
int user2=usersComparingAgainst[i];
if (user2==user) {
p.push_back(0);
continue;
}
//find common movies rated
float sum=0, sqrsum1=0, sqrsum2=0;
float n=0;
int j=0, k=0;
int movie1=0, movie2=0;
while(true) {
if (j>=userMovies[user].size() || k>=userMovies[user2].size()) {
break;
}
movie1=userMovies[user][j].movie;
movie2=userMovies[user2][k].movie;
if (movie2<movie1) { k=k+1; }
else if (movie1<movie2) { j=j+1; }
else {
// make calculations that allow for computation of variance and mean
float d1=userMovies[user][j].rating-useravg[user];
float d2=userMovies[user2][k].rating-useravg[user2];
sum+=d1*d2;
sqrsum1+=d1*d1;
sqrsum2+=d2*d2;
n++; j++; k++;
if(n>5) { break; }
}
}
//compute pearsons from our summations in the last step
float e=sum/n;
float std1=sqrt(sqrsum1/n);
float std2=sqrt(sqrsum2/n);
float ppre=e/(std1*std2);
if(std1==0 || std2==0) {
p.push_back(0);
}
else {
p.push_back((1+ppre)/2);
}
}
//time_t t2= time(0);
//time1 += t2-t1;
//attach each userid to the pearson calculations and sort on the pearson score
vector<Parsons> parsons;
for(int i=1; i<=Q; i++) {
Parsons pair;
pair.p=p[i];
pair.user=i;
parsons.push_back(pair);
}
sort(parsons.begin(),parsons.end(),compareparsons);
//loop user's movies
for(int j=0; j<queryusermovies[user].size(); j++) {
int movie=queryusermovies[user][j];
float numerator=0, denominator=0;
int numused=0;
//loop the users we want to compare against
for(int i=0; i<Q; i++) {
float pp=parsons[i].p;
int user2=parsons[i].user;
if(pp<0.1) { break; }
if(numused>=K) { break; }
//int rating2=userMovieRatings[user2][movie];
if( userMovieRatings[user2].count(movie) == 0) { continue; }
int rating2 = userMovieRatings[user2][movie];
//std::map<int,char>::const_iterator search = userMovieRatings[user2].find(movie);
//if(search == userMovieRatings[user2].end()) {
// continue;
//}
//int rating2 = search->first;
//calculate basically a normalized weighted average for the two users
numerator+=(rating2-useravg[user2])*pp;
denominator+=pp;
numused++;
}
// make a prediction for the given user's rating of a given movie based off of the information
// we've extracted from similar user's ratings of that movie.
float dstd=numerator/denominator;
float ans=dstd*userstd[user]+useravg[user];
if(dstd!=dstd) { ans=useravg[user]; }
ans=max(1.0f,ans);
ans=min(ans,5.0f);
int index=queryusermoviespos[user][j];
answers[index]=ans;
}
//time3 += time(0)-t3;
}
//cout << time1 << " " << time2 << " " << time3 << endl;
// print predictions
cout << "ANSWERS" << endl;
for(int i=0; i<linenum; i++) {
out << answers[i] << endl;
}
exampleFile.close();
out.close();
return 0;
}
| [
"dmace@caltech.edu"
] | dmace@caltech.edu |
e954b57984989780987fe119bf7c3bf6cb2cc4e9 | 7c9136d87b8895ac6532ef2af58edf3ecc29d175 | /DragSourceButton.h | a18ae2d4197dd5ad7d67820ac611e244c72770ab | [] | no_license | khhubb/csda-new-ssb | 038d75858cba1e029f4f1315d6ebba95e5d9fb91 | 96eaf896ba6c91914f69671171f5488cf0fb5d3f | refs/heads/master | 2020-07-01T03:36:45.777439 | 2016-08-17T22:00:09 | 2016-08-17T22:00:09 | 74,102,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,512 | h | #if !defined(AFX_DRAGSOURCEBUTTON_H__1C24B8A0_53DE_11D1_804F_006097B38214__INCLUDED_)
#define AFX_DRAGSOURCEBUTTON_H__1C24B8A0_53DE_11D1_804F_006097B38214__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// DragSourceButton.h : header file
//
// of course, this isn't really a button anymore
// we subclass other types of windows, typically a CStatic being used as an image,
// to provide click notification.
class CNotify;
/////////////////////////////////////////////////////////////////////////////
// CDragSourceButton window
class CDragSourceButton : public CButton
{
// Construction
public:
CDragSourceButton();
// Attributes
public:
CNotify* m_pNotify;
// pointer to an object to callback to.
// Operations
public:
void SetNotify(CNotify* p);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDragSourceButton)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CDragSourceButton();
// Generated message map functions
protected:
//{{AFX_MSG(CDragSourceButton)
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DRAGSOURCEBUTTON_H__1C24B8A0_53DE_11D1_804F_006097B38214__INCLUDED_)
| [
"dmiller2718@gmail.com"
] | dmiller2718@gmail.com |
00cb59ac39a8293b45bed7a8029e69224447e6a8 | 4a157e8737dc04a8cab9428dcb6fb58948148022 | /Output.cpp | 62dffaff0b2a7f51b1c4b7972afc770776e92236 | [
"MIT"
] | permissive | woodinspector/ContrIO | 32491cdd9a6e61f3b2aaf6b777e038b1f319ac8c | 48d5ddb7dd94a063e67329bb95d3f42e6e8f6125 | refs/heads/master | 2020-12-29T14:05:05.084345 | 2020-02-06T07:48:54 | 2020-02-06T07:48:54 | 238,631,998 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,070 | cpp | #include "Arduino.h"
#include "Output.h"
void Output::init()
{
is_millis = true;
is_busy = false;
state = false;
lastTimeOn = lastTimeOff = millis();
amountOfTime = 0;
counter = 0;
pinMode(pin, OUTPUT);
}
Output::Output(const int pin) : pin(pin), name("")
{
debug = false;
init();
}
Output::Output(const int pin, bool debug) : pin(pin), name("")
{
this->debug = debug;
init();
}
Output::Output(const int pin, bool debug, const String name)
: pin(pin)
, name(name)
{
this->debug = debug;
init();
}
void Output::SetHigh()
{
if(state == false)
{
digitalWrite(pin, HIGH);
state = true;
}
else if(debug)
{
Serial.println(name + ": Tried to set HIGH while HIGH");
}
counter++;
lastTimeOn = millis();
}
void Output::SetLow()
{
if(state)
{
digitalWrite(pin, LOW);
state = false;
}
else if(debug)
{
Serial.println(name + ": Tried to set LOW while LOW");
}
counter++;
lastTimeOff = millis();
}
void Output::Print() const
{
Serial.println(name);
Serial.println(String("state: " + String(state, DEC)));
Serial.println(String("is_busy: " + String(is_busy, DEC)));
Serial.println(String("lastTime: " + String(lastTime, DEC)));
Serial.println(String("amountOfTime: ") + String(amountOfTime, DEC));
Serial.println(String("LastTimeWasOn: ") + String(LastTimeWasOn(), DEC));
Serial.println(String("LastTimeWasOff: ") + String(LastTimeWasOff(), DEC));
}
bool Output::isBusy() const
{
return is_busy;
}
bool Output::isOn() const
{
return state;
}
void Output::On()
{
if(is_busy)
{
is_busy = false;
if(debug)
Serial.println(name + String(": Used On() while OnForMillis() was being used"));
}
SetHigh();
}
void Output::OnForMillis(unsigned long amountOfTime)
{
is_millis = true;
if(state && debug)
{
Serial.println(name + String(": Tried to use OnForMillis while set to HIGH"));
}
if(is_busy && debug)
Serial.println(name + String(" is busy."));
SetHigh();
is_busy = true;
lastTime = millis();
this->amountOfTime = amountOfTime;
}
void Output::OffForMillis(unsigned long amountOfTime)
{
is_millis = true;
if(state == false && debug)
{
Serial.println(name + String(": Tried to use OffForMillis while set to LOW"));
}
if(is_busy && debug)
Serial.println(name + String(" is busy."));
SetLow();
is_busy = true;
lastTime = millis();
this->amountOfTime = amountOfTime;
}
void Output::OnForMicros(unsigned long amountOfTime)
{
is_millis = false;
if(state && debug)
{
Serial.println(name + String(": Tried to use OnForMicros while set to HIGH"));
}
if(is_busy && debug)
Serial.println(name + String(" is busy."));
SetLow();
is_busy = true;
lastTime = micros();
this->amountOfTime = amountOfTime;
}
void Output::OffForMicros(unsigned long amountOfTime)
{
is_millis = false;
if(state == false && debug)
{
Serial.println(name + String(": Tried to use OffForMillis while set to LOW"));
}
if(is_busy && debug)
Serial.println(name + String(" is busy."));
SetLow();
is_busy = true;
lastTime = micros();
this->amountOfTime = amountOfTime;
}
void Output::Off()
{
if(is_busy)
{
is_busy = false;
if(debug)
Serial.println(name + String(": Used Off() while OnForMillis() was being used"));
}
SetLow();
}
void Output::Switch()
{
if(state)
SetLow();
else
SetHigh();
}
void Output::Update()
{
unsigned long tm = is_millis ? millis() : micros();
if (is_busy
&& amountOfTime
&& tm - lastTime >= amountOfTime)
{
is_busy = false;
Switch();
}
}
unsigned long Output::LastTimeWasOn() const
{
return millis() - lastTimeOn;
}
unsigned long Output::LastTimeWasOff() const
{
return millis() - lastTimeOff;
} | [
"robert@rzad.it"
] | robert@rzad.it |
51ebba1acf4b81aa2cac6041bc2f98b9318b6e9e | 3530c83ee483570a907297e7bcc2cc605382dad8 | /LeetCode_April_clock_in/4_2_面试题17.21直方图的水量.cpp | eb864b9db8675f5019ee664b815141c983c1cbd7 | [] | no_license | SuperWhite18/LeetCode-Solution-of-Problems | 46fa410a856c54a903aeb1e28eecf0607dc26667 | fe1c3a53934b2b48b6a282364492332bf9c9d6c9 | refs/heads/main | 2023-08-03T12:41:27.513132 | 2021-08-02T16:10:47 | 2021-08-02T16:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | //题目链接:
https://leetcode-cn.com/problems/volume-of-histogram-lcci/
//思路分析:
1.总体积减去柱子的体积就是水的容量
2.用双指针思想
3.先计算每一层雨水和柱子的总体积,三层相加,得到整体的体积vol
4.然后计算柱子的总体积sum,就是区间长度
5.再用vol-sum即是雨水的体积
6.注意细节:while(left <= right) 每一层的vol=right-left+1
//代码实现:
class Solution {
public:
int trap(vector<int>& height)
{
//计算柱子的体积
int sum = accumulate ( height.begin(), height.end(), 0);
int vol = 0;
int high = 1;
int size = height.size();
//双指针
int left = 0;
int right = height.size() - 1;
while (left <= right)
{
while(left <= right && height[left] < high)
{
left++;
}
while(left <= right && height[right] < high)
{
right--;
}
//算每一行的容量累加
vol += right - left + 1;
//更新high高度 再上一层
high++;
}
return vol - sum;
}
}; | [
"1299478311@qq.com"
] | 1299478311@qq.com |
4cab9d91839bb6bdbd3789f5855b7987b040cf57 | c0f4d7d7dc21bf1d9009c6f003cd5d4ae366a81d | /Firmware/FreeRTOS2560/FreeRTOS2560/FreeRTOS2560.cpp | ea2a98e3534c7f2951f214d2261fb313d397ad20 | [] | no_license | stanley92/CG3002 | ec3a38b17195564f0d447a33abd69cc3b7da690a | 5e8f33684bcf2d063d3c21928909a3f10026e535 | refs/heads/master | 2016-08-03T20:38:32.897423 | 2015-11-14T05:36:12 | 2015-11-14T05:37:40 | 42,099,080 | 0 | 0 | null | 2015-09-15T13:12:47 | 2015-09-08T08:13:30 | C | UTF-8 | C++ | false | false | 1,011 | cpp | /*
* FreeRTOS2560.cpp
*
* Created: 9/9/2015 11:16:44 PM
* Author: Laksh
*/
/*
#include <avr/io.h>
int main(void)
{
while(1)
{
//TODO:: Please write your application code
}
}*/
#include <avr/io.h>
#include <FreeRTOS.h>
#include <task.h>
#include <Arduino.h>
//Tasks flash LEDs at Pins 12 and 13 at 1Hz and 2 Hz respectively
void task1(void *p)
{
while(1)
{
digitalWrite(13,HIGH);
vTaskDelay(500); //Delay for 500ticks. Since each tick is 1ms,
//this delays for 500ms
digitalWrite(13,LOW);
vTaskDelay(500);
}
}
void task2(void* p)
{
while(1)
{
digitalWrite(12,HIGH);
vTaskDelay(250);
digitalWrite(12,LOW);
vTaskDelay(250);
}
}
#define STACK_DEPTH 64
void vApplicationIdleHook()
{
//Do nothing
}
int main(void)
{
init();
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
TaskHandle_t t1,t2;
//Create tasks
xTaskCreate(task1, "Task 1", STACK_DEPTH, NULL, 6, &t1);
xTaskCreate(task2, "Task 2", STACK_DEPTH, NULL, 5, &t2);
vTaskStartScheduler();
} | [
"rkplakshmanan@gmail.com"
] | rkplakshmanan@gmail.com |
4273f0af7f490324b3472a3101f4ecb015796924 | 2637e30b614f11c3097ac511880adc6b944a2775 | /Q18/Q18.cpp | 663a8a1704da6ec0d0486aeda0e98c38081ef7ee | [] | no_license | WithSJ/College-Cpp-Questions- | f2192eb5a46b50748b261df7b0365f1b96df3d7d | 45db8a96268f8a0670d68ac85fcaef1ce25d2249 | refs/heads/main | 2023-03-26T20:53:09.711357 | 2021-03-24T08:38:22 | 2021-03-24T08:38:22 | 349,433,496 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,458 | cpp | #include<iostream>
using namespace std;
int count_digits(int num);
void num_to_arr(int num,int arr[],int count);
void swap_arr(int arr[],int count);
int arr_to_num(int arr[],int count);
int main()
{
int num;
cout<<"Input:";
cin>> num;
int count = count_digits(num);
int arr[count];
num_to_arr(num,arr,count);
swap_arr(arr,count);
cout<<"\nOutput : "<<arr_to_num(arr,count)<<endl;
return 0;
}
int arr_to_num(int arr[],int count)
{ int num=0;
for (--count; count >= 0; count--)
{
num = num + arr[count];
num = num * 10;
}
return num/10;
}
void swap_arr(int arr[],int count)
{
if (count %2 == 0)
{
for (int i = 0; i < count; i+=2)
{
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}else{
for (int i = count-1; i > 0; i-=2)
{
int temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
}
}
}
void num_to_arr(int num,int arr[],int count)
{
for (int i = 0; i < count && num > 0; i++)
{
arr[i] = num % 10;
num = num / 10;
}
}
int count_digits(int num)
{
int count = 0;
while (num > 0)
{
count++;
num % 10;
num = num / 10;
}
return count;
}
| [
"withsj.in@gmail.com"
] | withsj.in@gmail.com |
bde2d4cecb4af5d134b28f23355c5af8e020ecea | f236af50bd31796471fbf4b9c1757d2b8b600af7 | /external/embree/kernels/geometry/instance_intersector.h | 8e174d5cd73d98e4855355190373a74a54ab8b88 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"IJG"
] | permissive | fly2mars/suCAM | 742a4cd2db19829616a47e78c1d56ed0bceee42b | 20581f4545684bb7b62ac32059f6031aa5b27f0d | refs/heads/master | 2023-04-07T06:53:17.218649 | 2023-03-29T08:50:04 | 2023-03-29T08:50:04 | 153,613,947 | 8 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 2,452 | h | // ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#pragma once
#include "../common/scene_instance.h"
#include "../common/ray.h"
namespace embree
{
namespace isa
{
struct FastInstanceIntersectorN
{
static void intersect1(const Instance* instance, const RTCIntersectContext* context, Ray& ray, size_t item);
static void occluded1 (const Instance* instance, const RTCIntersectContext* context, Ray& ray, size_t item);
template<int N>
static void intersectN(vint<N>* valid, const Instance* instance, const RTCIntersectContext* context, RayK<N>& ray, size_t item);
template<int N>
static void occludedN (vint<N>* valid, const Instance* instance, const RTCIntersectContext* context, RayK<N>& ray, size_t item);
static void intersect(int* valid, void* ptr, const RTCIntersectContext* context, RTCRayN* rays, size_t N, size_t item);
static void occluded (int* valid, void* ptr, const RTCIntersectContext* context, RTCRayN* rays, size_t N, size_t item);
};
struct FastInstanceIntersector1M
{
static void intersect(const Instance* instance, RTCIntersectContext* context, Ray** rays, size_t M, size_t item);
static void occluded (const Instance* instance, RTCIntersectContext* context, Ray** rays, size_t M, size_t item);
};
}
}
| [
"fly2mars@hotmail.com"
] | fly2mars@hotmail.com |
dcc2a7ba9ddd362ed3c16bcccef74e62d678876a | d276a9ad61586a050e861cdd48a82b7485809986 | /source/webkit-2.2.8/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.cpp | c971e0deae2e3eba784a8c5d4d293e48ef76fbcc | [] | no_license | onecoolx/davinci | 1ccea6487ec8254c520514e5a8df826fa6b08398 | 090696c6a957d3fc0cca867530cb3eece5fb870c | refs/heads/master | 2023-06-27T10:20:41.161195 | 2023-06-12T12:06:37 | 2023-06-12T12:06:37 | 28,557,969 | 10 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 7,492 | cpp | /*
* Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebBackForwardListProxy.h"
#include "DataReference.h"
#include "EncoderAdapter.h"
#include "WebCoreArgumentCoders.h"
#include "WebPage.h"
#include "WebPageProxyMessages.h"
#include "WebProcess.h"
#include "WebProcessProxyMessages.h"
#include <WebCore/HistoryItem.h>
#include <WebCore/PageCache.h>
#include <wtf/HashMap.h>
using namespace WebCore;
namespace WebKit {
static const unsigned DefaultCapacity = 100;
static const unsigned NoCurrentItemIndex = UINT_MAX;
// FIXME <rdar://problem/8819268>: This leaks all HistoryItems that go into these maps.
// We need to clear up the life time of these objects.
typedef HashMap<uint64_t, RefPtr<HistoryItem>> IDToHistoryItemMap;
typedef HashMap<RefPtr<HistoryItem>, uint64_t> HistoryItemToIDMap;
static IDToHistoryItemMap& idToHistoryItemMap()
{
DEFINE_STATIC_LOCAL(IDToHistoryItemMap, map, ());
return map;
}
static HistoryItemToIDMap& historyItemToIDMap()
{
DEFINE_STATIC_LOCAL(HistoryItemToIDMap, map, ());
return map;
}
static uint64_t uniqueHistoryItemID = 1;
static uint64_t generateHistoryItemID()
{
// These IDs exist in the WebProcess for items created by the WebProcess.
// The IDs generated here need to never collide with the IDs created in WebBackForwardList in the UIProcess.
// We accomplish this by starting from 3, and only ever using odd ids.
uniqueHistoryItemID += 2;
return uniqueHistoryItemID;
}
void WebBackForwardListProxy::setHighestItemIDFromUIProcess(uint64_t itemID)
{
if (itemID <= uniqueHistoryItemID)
return;
if (itemID % 2)
uniqueHistoryItemID = itemID;
else
uniqueHistoryItemID = itemID + 1;
}
static void updateBackForwardItem(uint64_t itemID, HistoryItem* item)
{
EncoderAdapter encoder;
item->encodeBackForwardTree(encoder);
WebProcess::shared().parentProcessConnection()->send(Messages::WebProcessProxy::AddBackForwardItem(itemID, item->originalURLString(), item->urlString(), item->title(), encoder.dataReference()), 0);
}
void WebBackForwardListProxy::addItemFromUIProcess(uint64_t itemID, PassRefPtr<WebCore::HistoryItem> prpItem)
{
RefPtr<HistoryItem> item = prpItem;
// This item/itemID pair should not already exist in our maps.
ASSERT(!historyItemToIDMap().contains(item.get()));
ASSERT(!idToHistoryItemMap().contains(itemID));
historyItemToIDMap().set(item, itemID);
idToHistoryItemMap().set(itemID, item);
}
static void WK2NotifyHistoryItemChanged(HistoryItem* item)
{
uint64_t itemID = historyItemToIDMap().get(item);
if (!itemID)
return;
updateBackForwardItem(itemID, item);
}
HistoryItem* WebBackForwardListProxy::itemForID(uint64_t itemID)
{
return idToHistoryItemMap().get(itemID);
}
uint64_t WebBackForwardListProxy::idForItem(HistoryItem* item)
{
ASSERT(item);
return historyItemToIDMap().get(item);
}
void WebBackForwardListProxy::removeItem(uint64_t itemID)
{
IDToHistoryItemMap::iterator it = idToHistoryItemMap().find(itemID);
if (it == idToHistoryItemMap().end())
return;
WebCore::pageCache()->remove(it->value.get());
historyItemToIDMap().remove(it->value);
idToHistoryItemMap().remove(it);
}
WebBackForwardListProxy::WebBackForwardListProxy(WebPage* page)
: m_page(page)
{
WebCore::notifyHistoryItemChanged = WK2NotifyHistoryItemChanged;
}
void WebBackForwardListProxy::addItem(PassRefPtr<HistoryItem> prpItem)
{
RefPtr<HistoryItem> item = prpItem;
ASSERT(!historyItemToIDMap().contains(item));
if (!m_page)
return;
uint64_t itemID = generateHistoryItemID();
ASSERT(!idToHistoryItemMap().contains(itemID));
m_associatedItemIDs.add(itemID);
historyItemToIDMap().set(item, itemID);
idToHistoryItemMap().set(itemID, item);
updateBackForwardItem(itemID, item.get());
m_page->send(Messages::WebPageProxy::BackForwardAddItem(itemID));
}
void WebBackForwardListProxy::goToItem(HistoryItem* item)
{
if (!m_page)
return;
SandboxExtension::Handle sandboxExtensionHandle;
m_page->sendSync(Messages::WebPageProxy::BackForwardGoToItem(historyItemToIDMap().get(item)), Messages::WebPageProxy::BackForwardGoToItem::Reply(sandboxExtensionHandle));
m_page->sandboxExtensionTracker().beginLoad(m_page->mainWebFrame(), sandboxExtensionHandle);
}
HistoryItem* WebBackForwardListProxy::itemAtIndex(int itemIndex)
{
if (!m_page)
return 0;
uint64_t itemID = 0;
if (!WebProcess::shared().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardItemAtIndex(itemIndex), Messages::WebPageProxy::BackForwardItemAtIndex::Reply(itemID), m_page->pageID()))
return 0;
if (!itemID)
return 0;
return idToHistoryItemMap().get(itemID);
}
int WebBackForwardListProxy::backListCount()
{
if (!m_page)
return 0;
int backListCount = 0;
if (!WebProcess::shared().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardBackListCount(), Messages::WebPageProxy::BackForwardBackListCount::Reply(backListCount), m_page->pageID()))
return 0;
return backListCount;
}
int WebBackForwardListProxy::forwardListCount()
{
if (!m_page)
return 0;
int forwardListCount = 0;
if (!WebProcess::shared().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardForwardListCount(), Messages::WebPageProxy::BackForwardForwardListCount::Reply(forwardListCount), m_page->pageID()))
return 0;
return forwardListCount;
}
void WebBackForwardListProxy::close()
{
HashSet<uint64_t>::iterator end = m_associatedItemIDs.end();
for (HashSet<uint64_t>::iterator i = m_associatedItemIDs.begin(); i != end; ++i)
WebCore::pageCache()->remove(itemForID(*i));
m_associatedItemIDs.clear();
m_page = 0;
}
bool WebBackForwardListProxy::isActive()
{
// FIXME: Should check the the list is enabled and has non-zero capacity.
return true;
}
void WebBackForwardListProxy::clear()
{
m_page->send(Messages::WebPageProxy::BackForwardClear());
}
} // namespace WebKit
| [
"onecoolx@gmail.com"
] | onecoolx@gmail.com |
5818ed29246c81d421f302d2a0909e9f7d092c96 | fbbbde0e5d7ecbd15d3835bd7771017a8d1fe0f3 | /Application/Engine/Math/Transform.h | 795556e1cef7053b93ce3a93cec8a89258db6586 | [] | no_license | neumont-gamedev/3D-Engine | c9a7519a626c9d6ea019af4fc2d1ad3a53a09b14 | 8948c97c3c36f9ea21a6511dd7a9c28e4e857117 | refs/heads/master | 2023-02-03T01:10:58.924803 | 2020-12-14T17:57:29 | 2020-12-14T17:57:29 | 312,040,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | h | #pragma once
namespace nc
{
struct Transform
{
glm::vec3 translation;
glm::vec3 rotation;
glm::vec3 scale{ 1 };
Transform() : translation{ 0 }, rotation{ 0 }, scale{ 1 } {}
Transform(const glm::vec3& translation, const glm::vec3& rotation = glm::vec3{ 0 }, const glm::vec3& scale = glm::vec3{ 1 }) :
translation{ translation },
rotation{ rotation },
scale{ scale }
{}
operator glm::mat4() const
{
glm::mat4 scaleMatrix = glm::scale(glm::mat4(1), scale);
glm::mat4 rotationMatrix = glm::eulerAngleYXZ(rotation.y, rotation.x, rotation.z);
glm::mat4 translationMatrix = glm::translate(glm::mat4(1), translation);
return (translationMatrix * rotationMatrix * scaleMatrix);
}
Transform& operator = (const glm::mat4& matrix)
{
translation = glm::vec3{ matrix[3] };
scale = glm::vec3{ matrix[0][0], matrix[1][1], matrix[2][2] };
glm::extractEulerAngleYXZ(matrix, rotation.y, rotation.x, rotation.z);
return *this;
}
};
} | [
"rmaple@neumont.edu"
] | rmaple@neumont.edu |
18db16c16412c5922cc15360747a753892881167 | 95331d9d20ca87bac4a0ea0abf18122ba9126791 | /Project4/tank.cpp | 35540270d45591f756ec0e06f452d011b37e13de | [] | no_license | zhiyu123/practice_project | daca05333dd0889cba73fc00261cb8878929c64d | 3f17f79b147e595bf431ef97e822de61b338a7ef | refs/heads/master | 2023-01-03T16:54:58.415987 | 2020-10-30T10:35:47 | 2020-10-30T10:35:47 | 304,607,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 288 | cpp | #include"tank.h"
Tank::Tank()
{
cout << "Tank()" << endl;
}
Tank::~Tank()
{
cout << "~Tank()" << endl;
}
Tank::Tank(const Tank& tank)
{
cout << "Tank(const Tank& tank)" << endl;
}
void Tank::shot()
{
cout << "shot()" << endl;
}
void Tank::move()
{
cout << "Tank----move()" << endl;
} | [
"1410880957@qq.com"
] | 1410880957@qq.com |
f9c6b35ece8cb6c0f9284d3e71e290d66176ecf9 | cefd6c17774b5c94240d57adccef57d9bba4a2e9 | /WebKit/Source/WebKit/gtk/webkit/webkiticondatabase.cpp | e03568b888a8eb91ac28eda0b98aea9ff082f6b4 | [
"BSL-1.0",
"BSD-2-Clause"
] | permissive | adzhou/oragle | 9c054c25b24ff0a65cb9639bafd02aac2bcdce8b | 5442d418b87d0da161429ffa5cb83777e9b38e4d | refs/heads/master | 2022-11-01T05:04:59.368831 | 2014-03-12T15:50:08 | 2014-03-12T15:50:08 | 17,238,063 | 0 | 1 | BSL-1.0 | 2022-10-18T04:23:53 | 2014-02-27T05:39:44 | C++ | UTF-8 | C++ | false | false | 10,487 | cpp | /*
* Copyright (C) 2011 Christian Dywan <christian@lanedo.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "webkiticondatabase.h"
#include "FileSystem.h"
#include "IconDatabase.h"
#include "Image.h"
#include "IntSize.h"
#include "webkitglobalsprivate.h"
#include "webkitmarshal.h"
#include "webkitsecurityoriginprivate.h"
#include "webkitwebframe.h"
#include <glib/gi18n-lib.h>
#include <wtf/gobject/GUniquePtr.h>
#include <wtf/text/CString.h>
/**
* SECTION:webkiticondatabase
* @short_description: A WebKit web application database
*
* #WebKitIconDatabase provides access to website icons, as shown
* in tab labels, window captions or bookmarks. All views share
* the same icon database.
*
* The icon database is enabled by default and stored in
* ~/.cache/webkit/icondatabase, depending on XDG_CACHE_HOME.
*
* WebKit will automatically look for available icons in link elements
* on opened pages as well as an existing favicon.ico and load the
* images found into the memory cache if possible. The signal "icon-loaded"
* will be emitted when any icon is found and loaded.
* Old Icons are automatically cleaned up after 4 days.
*
* webkit_icon_database_set_path() can be used to change the location
* of the database and also to disable it by passing %NULL.
*
* If WebKitWebSettings::enable-private-browsing is %TRUE new icons
* won't be added to the database on disk and no existing icons will
* be deleted from it.
*
* Since: 1.3.13
*
* Deprecated: 1.8: Use WebKitFaviconDatabase instead.
*/
using namespace WebKit;
enum {
PROP_0,
PROP_PATH,
};
enum {
ICON_LOADED,
LAST_SIGNAL
};
static guint webkit_icon_database_signals[LAST_SIGNAL] = { 0, };
G_DEFINE_TYPE(WebKitIconDatabase, webkit_icon_database, G_TYPE_OBJECT);
struct _WebKitIconDatabasePrivate {
GUniquePtr<gchar> path;
};
static void webkit_icon_database_finalize(GObject* object)
{
// Call C++ destructors, the reverse of 'placement new syntax'
WEBKIT_ICON_DATABASE(object)->priv->~WebKitIconDatabasePrivate();
G_OBJECT_CLASS(webkit_icon_database_parent_class)->finalize(object);
}
static void webkit_icon_database_dispose(GObject* object)
{
G_OBJECT_CLASS(webkit_icon_database_parent_class)->dispose(object);
}
static void webkit_icon_database_set_property(GObject* object, guint propId, const GValue* value, GParamSpec* pspec)
{
WebKitIconDatabase* database = WEBKIT_ICON_DATABASE(object);
switch (propId) {
case PROP_PATH:
webkit_icon_database_set_path(database, g_value_get_string(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, pspec);
break;
}
}
static void webkit_icon_database_get_property(GObject* object, guint propId, GValue* value, GParamSpec* pspec)
{
WebKitIconDatabase* database = WEBKIT_ICON_DATABASE(object);
switch (propId) {
case PROP_PATH:
g_value_set_string(value, webkit_icon_database_get_path(database));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, pspec);
break;
}
}
static void webkit_icon_database_class_init(WebKitIconDatabaseClass* klass)
{
webkitInit();
GObjectClass* gobjectClass = G_OBJECT_CLASS(klass);
gobjectClass->dispose = webkit_icon_database_dispose;
gobjectClass->finalize = webkit_icon_database_finalize;
gobjectClass->set_property = webkit_icon_database_set_property;
gobjectClass->get_property = webkit_icon_database_get_property;
/**
* WebKitIconDatabase:path:
*
* The absolute path of the icon database folder.
*
* Since: 1.3.13
*
* Deprecated: 1.8: Use WebKitFaviconDatabase::path instead.
*/
g_object_class_install_property(gobjectClass, PROP_PATH,
g_param_spec_string("path",
_("Path"),
_("The absolute path of the icon database folder"),
NULL,
WEBKIT_PARAM_READWRITE));
/**
* WebKitIconDatabase::icon-loaded:
* @database: the object on which the signal is emitted
* @frame: the frame containing the icon
* @frame_uri: the URI of the frame containing the icon
*
* This signal is emitted when a favicon is available for a page,
* or a child frame.
* See WebKitWebView::icon-loaded if you only need the favicon for
* the main frame of a particular #WebKitWebView.
*
* Since: 1.3.13
*
* Deprecated: 1.8: Use WebKitFaviconDatabase::icon-loaded instead.
*/
webkit_icon_database_signals[ICON_LOADED] = g_signal_new("icon-loaded",
G_TYPE_FROM_CLASS(klass),
(GSignalFlags)G_SIGNAL_RUN_LAST,
0,
NULL,
NULL,
webkit_marshal_VOID__OBJECT_STRING,
G_TYPE_NONE, 2,
WEBKIT_TYPE_WEB_FRAME,
G_TYPE_STRING);
g_type_class_add_private(klass, sizeof(WebKitIconDatabasePrivate));
}
static void webkit_icon_database_init(WebKitIconDatabase* database)
{
database->priv = G_TYPE_INSTANCE_GET_PRIVATE(database, WEBKIT_TYPE_ICON_DATABASE, WebKitIconDatabasePrivate);
// 'placement new syntax', see webkitwebview.cpp
new (database->priv) WebKitIconDatabasePrivate();
}
/**
* webkit_icon_database_get_path:
* @database: a #WebKitIconDatabase
*
* Determines the absolute path to the database folder on disk.
*
* Returns: the absolute path of the database folder, or %NULL
*
* Since: 1.3.13
*
* Deprecated: 1.8: Use webkit_favicon_database_get_path() instead.
**/
const gchar* webkit_icon_database_get_path(WebKitIconDatabase* database)
{
g_return_val_if_fail(WEBKIT_IS_ICON_DATABASE(database), 0);
return database->priv->path.get();
}
static void closeIconDatabaseOnExit()
{
if (WebCore::iconDatabase().isEnabled()) {
WebCore::iconDatabase().setEnabled(false);
WebCore::iconDatabase().close();
}
}
/**
* webkit_icon_database_set_path:
* @database: a #WebKitIconDatabase
* @path: an absolute path to the icon database folder
*
* Specifies the absolute path to the database folder on disk.
*
* Passing %NULL or "" disables the icon database.
*
* Since: 1.3.13
*
* Deprecated: 1.8: Use webkit_favicon_database_set_path() instead.
**/
void webkit_icon_database_set_path(WebKitIconDatabase* database, const gchar* path)
{
g_return_if_fail(WEBKIT_IS_ICON_DATABASE(database));
if (database->priv->path.get())
WebCore::iconDatabase().close();
if (!(path && path[0])) {
database->priv->path.reset();
WebCore::iconDatabase().setEnabled(false);
return;
}
database->priv->path.reset(g_strdup(path));
WebCore::iconDatabase().setEnabled(true);
WebCore::iconDatabase().open(WebCore::filenameToString(database->priv->path.get()), WebCore::IconDatabase::defaultDatabaseFilename());
static bool initialized = false;
if (!initialized) {
atexit(closeIconDatabaseOnExit);
initialized = true;
}
}
/**
* webkit_icon_database_get_icon_uri:
* @database: a #WebKitIconDatabase
* @page_uri: URI of the page containing the icon
*
* Obtains the URI for the favicon for the given page URI.
* See also webkit_web_view_get_icon_uri().
*
* Returns: a newly allocated URI for the favicon, or %NULL
*
* Since: 1.3.13
*
* Deprecated: 1.8: Use webkit_favicon_database_get_favicon_uri() instead.
**/
gchar* webkit_icon_database_get_icon_uri(WebKitIconDatabase* database, const gchar* pageURI)
{
g_return_val_if_fail(WEBKIT_IS_ICON_DATABASE(database), 0);
g_return_val_if_fail(pageURI, 0);
String pageURL = String::fromUTF8(pageURI);
return g_strdup(WebCore::iconDatabase().synchronousIconURLForPageURL(pageURL).utf8().data());
}
/**
* webkit_icon_database_get_icon_pixbuf:
* @database: a #WebKitIconDatabase
* @page_uri: URI of the page containing the icon
*
* Obtains a #GdkPixbuf of the favicon for the given page URI, or
* a default icon if there is no icon for the given page. Use
* webkit_icon_database_get_icon_uri() if you need to distinguish these cases.
* Usually you want to connect to WebKitIconDatabase::icon-loaded and call this
* method in the callback.
*
* The pixbuf will have the largest size provided by the server and should
* be resized before it is displayed.
* See also webkit_web_view_get_icon_pixbuf().
*
* Returns: (transfer full): a new reference to a #GdkPixbuf, or %NULL
*
* Since: 1.3.13
*
* Deprecated: 1.8: Use webkit_favicon_database_try_get_favicon_pixbuf() instead.
**/
GdkPixbuf* webkit_icon_database_get_icon_pixbuf(WebKitIconDatabase* database, const gchar* pageURI)
{
g_return_val_if_fail(WEBKIT_IS_ICON_DATABASE(database), 0);
g_return_val_if_fail(pageURI, 0);
String pageURL = String::fromUTF8(pageURI);
// The exact size we pass is irrelevant to the WebCore::iconDatabase code.
// We must pass something greater than 0, 0 to get a pixbuf.
WebCore::Image* icon = WebCore::iconDatabase().synchronousIconForPageURL(pageURL, WebCore::IntSize(16, 16));
if (!icon)
return 0;
GdkPixbuf* pixbuf = icon->getGdkPixbuf();
if (!pixbuf)
return 0;
return static_cast<GdkPixbuf*>(g_object_ref(pixbuf));
}
/**
* webkit_icon_database_clear:
* @database: a #WebKitIconDatabase
*
* Clears all icons from the database.
*
* Since: 1.3.13
*
* Deprecated: 1.8: Use webkit_favicon_database_clear() instead.
**/
void webkit_icon_database_clear(WebKitIconDatabase* database)
{
g_return_if_fail(WEBKIT_IS_ICON_DATABASE(database));
WebCore::iconDatabase().removeAllIcons();
}
| [
"adzhou@hp.com"
] | adzhou@hp.com |
f58a1e031b2e609fa2cb9f68294b196b8261a3b5 | 51801861ce8ec13f64849a52f57e2afbfee76c5d | /module04/ex00/Pig.cpp | 45a46be353d2af39f6ca3e4945b5d8eab948f622 | [] | no_license | z-iz/42_CPP_Piscine | 763fce04fc79797fbec4d19d81c660582767a2fc | 325566004fb59fbcb562c7187c82eef5e6aa7a36 | refs/heads/main | 2023-03-25T01:38:28.478740 | 2021-03-03T22:19:02 | 2021-03-03T22:19:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,557 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Pig.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: larosale <larosale@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/15 15:01:03 by larosale #+# #+# */
/* Updated: 2021/01/20 19:46:15 by larosale ### ########.fr */
/* */
/* ************************************************************************** */
#include "Pig.hpp"
Pig::Pig() : Victim() {
std::cout << "Oink oink." << std::endl;
return;
}
Pig::Pig(const std::string &name) : Victim(name) {
std::cout << "Oink oink." << std::endl;
return;
}
Pig::Pig(const Pig &src) : Victim() {
*this = src;
std::cout << "Oink oink." << std::endl;
return;
}
Pig::~Pig() {
std::cout << "Screach..." << std::endl;
return;
}
Pig &Pig::operator=(const Pig &rhs) {
if (this != &rhs)
{
this->_name = rhs._name;
}
return *this;
}
void Pig::getPolymorphed() const {
std::cout << this->_name;
std::cout << " has been turned into a human!" << std::endl;
}
| [
"neodyme@ya.ru"
] | neodyme@ya.ru |
7f07edc0fae995bda19f27aedfe8dff318e2eda3 | ffe75f4cdc12b6f1c6a04b3ce0afd562a179d603 | /src/concurrent/smutexlocker.cpp | 887e80f7aacbc27b039e1515f366a910daf3b8c4 | [
"Apache-2.0"
] | permissive | slux83/libslx | 9f179393e5b5b3811ba1b89a8b29ba86f987f138 | 4f687957843bd2212ddfb5da83926d48f066b8e3 | refs/heads/master | 2023-09-02T23:49:40.382553 | 2021-11-09T21:49:06 | 2021-11-09T21:49:06 | 426,391,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | cpp | /******************************************************************************
[FILE_HEADER_BEGIN]
[FILE_HEADER_END]
******************************************************************************/
#include "smutexlocker.h"
#include "smutex.h"
#include "../global/sglobal.h"
SMutexLocker::SMutexLocker(SMutex *mutex)
{
this->mutex = NULL;
alreadyUnlocked = false;
if (mutex)
{
this->mutex = mutex;
this->alreadyUnlocked = false;
this->mutex->lock();
}
}
SMutexLocker::~SMutexLocker()
{
if (mutex)
{
if (!alreadyUnlocked)
mutex->unlock();
}
}
void SMutexLocker::unlock()
{
if (mutex)
{
if (!alreadyUnlocked)
mutex->unlock();
}
}
| [
"slux83@gmail.com"
] | slux83@gmail.com |
b399722302bbfc6b1285dd0f8eec410619e6f0bf | b1fc87649b3f8e6dd8a6630cbbf3bfc6fb6c7e1d | /exercises/templates/dac/skel-dac-merge-sort-int.cc | b5efa81bddd0b550ab68f66b961c83086af8e07f | [] | no_license | ChrisCummins/msc-thesis | bfdef83d92af424157c82968754fd8d10ea42842 | 009c47a5f87f3808d9cc223456e0263b3a9a0b81 | refs/heads/master | 2021-06-02T16:53:35.140227 | 2020-01-18T12:03:50 | 2020-01-18T12:03:50 | 24,074,809 | 3 | 1 | null | 2015-02-23T12:57:30 | 2014-09-15T21:33:36 | C++ | UTF-8 | C++ | false | false | 490 | cc | #include "./test.h" // NOLINT(legal/copyright)
int main(int argc, char *argv[]) {
std::cout << "skel::merge_sort<int>, "
<< "parallelisation depth = "
<< DAC_SKEL_PARALLELISATION_DEPTH << ", "
<< "split threshold = "
<< SKEL_MERGE_SORT_SPLIT_THRESHOLD << "\n";
// TODO(cec): Optimise me!
// for (int i = 0, j = 50000; i < 40; i++, j += 50000)
test_sort_func<int>(get_unsorted_int_vector(100), skel::dac_merge_sort);
return 0;
}
| [
"chrisc.101@gmail.com"
] | chrisc.101@gmail.com |
dff307c941e0c5f8db04d7d0add50784b1853d6f | 7cdbac97437657022daa0b97b27b9fa3dea2a889 | /engine/source/qt/QtCommandPump.cc | d9ffa8122367d160d5f30a381bd69ce37b795440 | [] | no_license | lineCode/3SS | 36617d2b6e35b913e342d26fd2be238dbb4b4f3f | 51c702bbaee8239c02db58f6c974b2c6cd2271d1 | refs/heads/master | 2020-09-30T18:43:27.358305 | 2015-03-04T00:14:23 | 2015-03-04T00:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,384 | cc | //-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
#include "qt/QtCommandPump.h"
#include "qt/QtFileDownloader.h"
#include <QFocusEvent>
QtCommandPump::QtCommandPump(IQtAppService* appService, QtFileDownloader* downloader, QtHTTPRequestHandler* httphandler)
{
m_pAppService = appService;
m_pFileDownloader = downloader;
m_pHttpRequestHandler = httphandler;
m_CurrentCommandBuffer = 0;
}
QtCommandPump::~QtCommandPump()
{
// Clear out command buffers
for(U32 i=0; i<2; ++i)
{
while(m_Commands[i].size() > 0)
{
Command* c = m_Commands[i][0];
m_Commands[i].pop_front();
delete c;
}
}
}
void QtCommandPump::sendCommand(IQtCommandService::Command* c)
{
m_CommandsMutex.lock();
m_Commands[m_CurrentCommandBuffer].push_back(c);
m_CommandsMutex.unlock();
}
void QtCommandPump::tick(Mutex* commandsMutex)
{
Command* c;
// Determine if we should used the passed in mutex, or our local one.
Mutex* cmdMutex = commandsMutex;
if(!cmdMutex)
cmdMutex = &m_CommandsMutex;
// Swtich command buffers. This allows commands to be sent
// to the current buffer while we process the other one.
cmdMutex->lock();
S32 index = m_CurrentCommandBuffer;
m_CurrentCommandBuffer = 1 - m_CurrentCommandBuffer;
cmdMutex->unlock();
// Step through the command buffer (non-current one)
while(m_Commands[index].size() > 0)
{
// Get the next command
c = m_Commands[index][0];
m_Commands[index].pop_front();
switch(c->m_Id)
{
case C_WEBRENDER_CREATE:
CmdWebRenderCreate(c);
break;
case C_WEBRENDER_DESTROY:
CmdWebRenderDestroy(c);
break;
case C_WEBRENDER_SETSIZE:
CmdWebRenderSetSize(c);
break;
case C_WEBRENDER_SETURL:
CmdWebRenderSetUrl(c);
break;
case C_WEBRENDER_RELOAD_ACTION:
CmdWebRenderReloadAction(c);
break;
case C_WEBRENDER_BACK_ACTION:
CmdWebRenderBackAction(c);
break;
case C_WEBRENDER_FORWARD_ACTION:
CmdWebRenderForwardAction(c);
break;
case C_WEBRENDER_STOP_ACTION:
CmdWebRenderStopAction(c);
break;
case C_WEBRENDER_UPDATEVIEW:
CmdWebRenderUpdateView(c);
break;
case C_WEBRENDER_MOUSEMOVE:
case C_WEBRENDER_MOUSEDOWN:
case C_WEBRENDER_MOUSEUP:
case C_WEBRENDER_MOUSEDRAGGED:
CmdWebRenderMouseEvent(c);
break;
case C_WEBRENDER_MOUSEWHEELDOWN:
case C_WEBRENDER_MOUSEWHEELUP:
CmdWebRenderMouseWheelEvent(c);
break;
case C_WEBRENDER_KEYBOARD_INPUT:
CmdWebRenderKeyboardInput(c);
break;
case C_DOWNLOAD_FILE:
CmdDownloadFile(c);
break;
case C_DOWNLOAD_CANCEL:
CmdDownloadCancel(c);
break;
case C_DOWNLOAD_PAUSE:
CmdDownloadPause(c);
break;
case C_DOWNLOAD_RESUME:
CmdDownloadResume(c);
break;
case C_HTTPREQUEST_POST:
CmdHttpRequestPost(c);
break;
}
// Delete the processed command
delete c;
}
}
//-----------------------------------------------------------------------------
void QtCommandPump::CmdWebRenderCreate(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = new WebRender();
r->SetId(id);
r->SetSize(c->m_S32Args[1], c->m_S32Args[2]);
// Store the SimObjectId of the owner of this web render object
r->SetOwnerId(c->m_S32Args[3]);
m_WebRenderList.insertEqual(id, r);
}
void QtCommandPump::CmdWebRenderDestroy(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
m_WebRenderList.erase(id);
delete r;
}
void QtCommandPump::CmdWebRenderSetSize(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
r->SetSize(c->m_S32Args[1], c->m_S32Args[2]);
}
void QtCommandPump::CmdWebRenderSetUrl(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
r->SetURL(c->m_StringArgs[0].toLatin1());
}
void QtCommandPump::CmdWebRenderReloadAction(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
r->ReloadAction();
}
void QtCommandPump::CmdWebRenderBackAction(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
r->BackAction();
}
void QtCommandPump::CmdWebRenderForwardAction(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
r->ForwardAction();
}
void QtCommandPump::CmdWebRenderStopAction(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
r->StopAction();
}
void QtCommandPump::CmdWebRenderUpdateView(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
r->UpdateView((bool)c->m_S32Args[1]);
}
void QtCommandPump::CmdWebRenderMouseEvent(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
if(c->m_Id != C_WEBRENDER_MOUSEMOVE)
{
QFocusEvent focus(QEvent::FocusIn);
m_pAppService->getQtApp()->sendEvent(r, &focus);
}
switch(c->m_Id)
{
case C_WEBRENDER_MOUSEMOVE:
{
QMouseEvent mouseEvent(QEvent::MouseMove, QPoint(c->m_S32Args[1], c->m_S32Args[2]), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
m_pAppService->getQtApp()->sendEvent(r, &mouseEvent);
}
break;
case C_WEBRENDER_MOUSEDOWN:
{
QMouseEvent mouseEvent(QEvent::MouseButtonPress, QPoint(c->m_S32Args[1], c->m_S32Args[2]), Qt::LeftButton , Qt::LeftButton, Qt::NoModifier);
m_pAppService->getQtApp()->sendEvent(r, &mouseEvent);
}
break;
case C_WEBRENDER_MOUSEUP:
{
QMouseEvent mouseEvent(QEvent::MouseButtonRelease, QPoint(c->m_S32Args[1], c->m_S32Args[2]), Qt::LeftButton , Qt::NoButton, Qt::NoModifier);
m_pAppService->getQtApp()->sendEvent(r, &mouseEvent);
}
break;
case C_WEBRENDER_MOUSEDRAGGED:
{
QMouseEvent mouseEvent(QEvent::MouseMove, QPoint(c->m_S32Args[1], c->m_S32Args[2]), Qt::LeftButton , Qt::NoButton, Qt::NoModifier);
m_pAppService->getQtApp()->sendEvent(r, &mouseEvent);
}
break;
}
}
void QtCommandPump::CmdWebRenderMouseWheelEvent(Command* c)
{
const S32 wheelSpeed = 66;
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
if(c->m_Id == C_WEBRENDER_MOUSEWHEELDOWN)
{
QWheelEvent wheelEvent(QPoint(c->m_S32Args[1], c->m_S32Args[2]), -wheelSpeed, Qt::NoButton, Qt::NoModifier);
m_pAppService->getQtApp()->sendEvent(r, &wheelEvent);
}
else
{
QWheelEvent wheelEvent(QPoint(c->m_S32Args[1], c->m_S32Args[2]), wheelSpeed, Qt::NoButton, Qt::NoModifier);
m_pAppService->getQtApp()->sendEvent(r, &wheelEvent);
}
}
void QtCommandPump::CmdWebRenderKeyboardInput(Command* c)
{
S32 id = c->m_S32Args[0];
WebRender* r = m_WebRenderList.find(id).getValue();
if(!r)
return;
QFocusEvent focus(QEvent::FocusIn);
m_pAppService->getQtApp()->sendEvent(r, &focus);
QKeyEvent keyEvent(QEvent::KeyPress, (U32)c->m_S32Args[1], Qt::NoModifier, QChar((U16)c->m_S32Args[2]));
m_pAppService->getQtApp()->sendEvent(r, &keyEvent);
}
//-----------------------------------------------------------------------------
void QtCommandPump::CmdDownloadFile(Command* c)
{
S32 callbackObjId = c->m_S32Args[0];
m_pFileDownloader->FileDownload(c->m_StringArgs[0].toLatin1(), c->m_StringArgs[1].toLatin1(), callbackObjId, (bool)c->m_S32Args[1]);
}
void QtCommandPump::CmdDownloadCancel(Command* c)
{
m_pFileDownloader->CancelDownload();
}
void QtCommandPump::CmdDownloadPause(Command* c)
{
m_pFileDownloader->PauseDownload();
}
void QtCommandPump::CmdDownloadResume(Command* c)
{
m_pFileDownloader->ResumeDownload();
}
//-----------------------------------------------------------------------------
void QtCommandPump::CmdHttpRequestPost(Command* c)
{
m_pHttpRequestHandler->Post(c->m_StringArgs[0], &(c->m_KeyValueMap), c->m_S32Args[1], c->m_S32Args[0]);
}
| [
"kylem@garagegames.com"
] | kylem@garagegames.com |
07759999e826ab999b312a326f9f8c62883b7775 | 2a97852572aee0c7b767c87cd4f4124ba86fd2b2 | /DLL/Include/TTextTable.h | 508e9f0f13021bf88bb37a8be9217e6300423d18 | [] | no_license | leduong92/C-Project | d6f80b0d68ae8365d83b65287e6a8f51d8e4ecc0 | c6e5a4c0c03bd697e3199151e98e8e5a27b35bde | refs/heads/master | 2020-09-03T11:26:46.274242 | 2019-11-04T08:28:50 | 2019-11-04T08:28:50 | 219,452,163 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,685 | h | #ifndef TTEXTDB_H
#define TTEXTDB_H
//=======================================================================================================
// テキストDBAccessクラスのヘッダ
// Class Name TTextTable
// File Name TTextTable.h
// 作成者:Coba
// 作成日:1999.05.10
//=======================================================================================================
// 修正
// 2003.03.04 coba GetLast()関数を追加
// 2003.05.21 coba path名長さを、MAX_PATHに変更
// key退避バッファが足りなくてオーバーフローするバグを修正
// 2014.04.10 coba ファイル消去関数Drop()を追加
// 2015.02.26 sanno ファイル名の長さを拡張
//=======================================================================================================
#include "windows.h"
#include "winuser.h"
#include "winbase.h"
// エラーコード
#define TXDB_NOFILE 72
#define DEF_BUFSIZE 4096
#define TXDB_MAXKEYLEN 128
#define TXDB_WORKING 144
class TTextTable
{
public:
TTextTable(void);
~TTextTable(void);
int GetEqual( void *key );
int GetEqual2( void *key );
int FindFirst( void *key );
int Upd( void *key);
int Upd2( void *key);
int Del( void *key );
int Del2( void *key ); //2004.11.09 マツダ
int Insert( void *key );
int Insert2( void *key ); //2004.11.09 マツダ
int GetFirst(void);
int GetLast( void );
int Next(void);
int Prev(void);
int Add( void );
int GetCounts(void);
int Drop(void); // 2014.4.10 coba
protected:
typedef struct{
// char filename[30+1];
//char filename[50+1]; //2009.01.22 マツダ サイズ変更
char filename[80+1]; //2015.02.26 sanno サイズ変更
short reclen;
short keylen; // キー長(最大50byteにして下さい)
short offset; // キーの先頭からのバイトオフセット
char *datptr; // レコード格納ポインタ
char dir[MAX_PATH+1]; // ファイルのパス
char tmpdir[MAX_PATH+1]; // 作業領域のパス
} FSPEC;
int Initialize(FSPEC *filespec,int bufsize);
FSPEC m_fSpec; // ファイルスペック
private:
long m_PrevRecNo; // 直前に操作したレコード番号
void Clear(void);
int m_BufSize; // ファイル操作時のバッファ長
int Open( HANDLE& hFile ,BOOL readonly);
void Close(HANDLE& hFile);
int CheckFile(void); // 2004.11.09 マツダ
int MoveRecord( HANDLE hfile ,void *key , long *recNo ); // キーに該当するレコードに移動する
int MoveRecord2( HANDLE hfile ,void *key , long *recNo ); // キーに該当するレコードに移動する(旧)
};
#endif
| [
"11810677@nok.com.vn"
] | 11810677@nok.com.vn |
8c3a3307e868c3cd8d001c2240f27658bfa6f06d | a4f39e4572fd26031dfe9ec40c7e7b6512dcabe7 | /src/utils/dbwrapper/db-wrapper.cpp | fa9fe952471d7716cb4961b73f4e250574114cb2 | [
"MIT"
] | permissive | zx1239856/libserver | 9ddceb2d28c68232d7f78e42f935428a5fc29db6 | 8a72b8467c703b023e0703f74697e2d47d22757c | refs/heads/master | 2020-03-14T06:52:46.181227 | 2018-07-02T23:42:14 | 2018-07-02T23:42:14 | 131,492,432 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,721 | cpp | #include "db-wrapper.h"
using namespace dbWrapper;
// DatabaseSettings
DatabaseSettings::DatabaseSettings(const QString &databaseType, const QString &connectionName,
const QString &DBHost, const QString &DBName,
const QString &DBUserName, const QString &DBPassword,
const QString &DBConnSetting):
m_databaseType(databaseType),m_connectionName(connectionName),
m_DBHost(DBHost),m_DBName(DBName),m_DBUserName(DBUserName),m_DBPassword(DBPassword),
m_DBConnSetting(DBConnSetting)
{}
// ConnectSettings
ConnectSettings::ConnectSettings(const int &maxOpenTime, const QueryMode &queryMode, const int &minWaitTime):
m_maxOpenTime(maxOpenTime),m_queryMode(queryMode),m_minWaitTime(minWaitTime)
{}
// Query
Query::Query(QSqlDatabase &dataBase, QMutex *mutex):
m_query(new QSqlQuery(dataBase)),m_mutex(mutex),db(&dataBase){}
Query::Query(Query &&other): m_query(other.m_query),
m_mutex(other.m_mutex),db(other.db)
{
other.m_query=nullptr;
other.m_mutex=nullptr;
other.db = nullptr;
}
Query::~Query()
{
if(m_query)
{
delete m_query;
m_query=nullptr;
}
if(m_mutex)
{
m_mutex->unlock();
}
}
// ConnectNode
ConnectNode::ConnectNode(const DatabaseSettings &dataBaseSettings, const ConnectSettings &connectSettings):
m_dataBaseSettings(dataBaseSettings),
m_connectSettings(connectSettings)
{
m_connectionName = QString("%1(%2)").arg(m_dataBaseSettings.connectionName()).arg(QString::number(qint64(QThread::currentThread()), 16));
m_mutex = new QMutex(QMutex::Recursive);
if(m_connectSettings.maxOpenTime())
{
m_autoClose = new QTimer;
m_autoClose->setSingleShot(true);
m_autoClose->setInterval(m_connectSettings.maxOpenTime());
m_autoClose->moveToThread(qApp->thread());
m_autoClose->setParent(qApp);
connect(m_autoClose, SIGNAL(timeout()), this, SLOT(close()), Qt::DirectConnection);
connect(this, SIGNAL(controlStartAutoClose()), m_autoClose, SLOT(start()));
connect(this, SIGNAL(controlStopAutoClose()), m_autoClose, SLOT(stop()));
}
this->addDataBase();
}
ConnectNode::~ConnectNode()
{
if(m_mutex){m_mutex->lock();}
if(m_autoClose)
{
m_autoClose->deleteLater();
}
this->removeDataBase();
if(m_mutex){ m_mutex->unlock(); }
}
Query ConnectNode::query()
{
if(!m_database)
{
this->addDataBase();
}
if(!m_database->isOpen())
{
m_database->open();
}
if(m_mutex){ m_mutex->lock(); }
Query buf(*m_database, m_mutex);
emit controlStartAutoClose();
return buf;
}
bool ConnectNode::addDataBase()
{
if(m_mutex){ m_mutex->lock(); }
if(m_database)
{
this->removeDataBase();
}
m_database = new QSqlDatabase(QSqlDatabase::addDatabase(m_dataBaseSettings.databaseType(), m_connectionName));
m_database->setHostName(m_dataBaseSettings.DBHost());
m_database->setDatabaseName(m_dataBaseSettings.DBName());
m_database->setUserName(m_dataBaseSettings.DBUserName());
m_database->setPassword(m_dataBaseSettings.DBPassword());
m_database->setConnectOptions(m_dataBaseSettings.DBConnSetting());
const auto &&flag = this->open();
if(m_mutex){ m_mutex->unlock(); }
return flag;
}
void ConnectNode::removeDataBase()
{
if(m_mutex){ m_mutex->lock(); }
delete m_database;
m_database = NULL;
QSqlDatabase::removeDatabase(m_connectionName);
if(m_mutex){ m_mutex->unlock(); }
}
bool ConnectNode::open()
{
if(!m_database)
{
this->addDataBase();
}
if(m_mutex){ m_mutex->lock(); }
emit controlStartAutoClose();
const auto &&Flag = m_database->open();
if(m_mutex){ m_mutex->unlock(); }
return Flag;
}
void ConnectNode::close()
{
if(m_mutex)
{
if(m_mutex->tryLock())
{
m_mutex->unlock();
emit controlStopAutoClose();
m_database->close();
}
else
{
emit controlStartAutoClose();
}
}
else
{
emit controlStopAutoClose();
m_database->close();
}
}
// Control
Control::Control(const DatabaseSettings &databaseSettings, const ConnectSettings &connectSettings):
m_databaseSettings(databaseSettings),
m_connectSettings(connectSettings)
{
if(m_connectSettings.queryMode() == QueryAutoMode)
{
if(databaseSettings.databaseType() == "QMYSQL")
{
m_connectSettings.setQueryMode(QueryMultiMode);
}
else if(databaseSettings.databaseType() == "QODBC")
{
m_connectSettings.setQueryMode(QueryMultiMode);
}
else
{
m_connectSettings.setQueryMode(QuerySingleMode);
}
}
if(m_connectSettings.queryMode() == QuerySingleMode)
{
this->insert(qint64(QThread::currentThread()));
}
if(m_connectSettings.minWaitTime() == -1)
{
if(databaseSettings.databaseType() == "QMYSQL")
{
m_connectSettings.setMinWaitTime(0);
}
else if(databaseSettings.databaseType() == "QODBC")
{
m_connectSettings.setMinWaitTime(0);
}
else
{
m_connectSettings.setMinWaitTime(5);
m_wait = new QTime;
m_wait->start();
}
}
else
{
m_wait = new QTime;
m_wait->start();
}
}
Control::~Control()
{
for(auto &now: m_node)
{
now->deleteLater();
}
if(m_wait)
{
delete m_wait;
}
}
void Control::removeAll()
{
m_mutex.lock();
for(auto &Now: m_node)
{
Now->removeDataBase();
}
m_mutex.unlock();
}
Query Control::query(void)
{
if(m_wait)
{
const auto &&flag = m_connectSettings.minWaitTime() - m_wait->elapsed();
m_wait->restart();
if(flag > 0)
{
QThread::msleep(flag);
}
}
if(m_connectSettings.queryMode() == QueryMultiMode)
{
m_mutex.lock();
const auto ¤tThread = qint64(QThread::currentThread());
const auto &&now = m_node.find(currentThread);
if(now != m_node.end())
{
auto buf((*now)->query());
m_mutex.unlock();
return buf;
}
else
{
this->insert(qint64(QThread::currentThread()));
m_mutex.unlock();
return this->query();
}
}
else
{
return (*m_node.begin())->query();
}
}
void Control::insert(const qint64 &key)
{
m_node[key] = new ConnectNode(m_databaseSettings, m_connectSettings);
}
| [
"zx1239856@gmail.com"
] | zx1239856@gmail.com |
1e0b1eb935d03f98ee553c2531269005e814ba1a | 1dd5108ff8deca17e2c58034c433010e299df555 | /Student.cpp | c8d2046468a578a5e37440039d3467130fd9b6bd | [] | no_license | katherine-fontan/CPSC350-Assignment-4 | e8bfa0e87287c8d0035a1e4136de30b53c875439 | 666d2c445eb059bdcf8e5cb3ac64215461344d28 | refs/heads/master | 2022-04-24T16:37:35.907547 | 2020-04-23T19:42:41 | 2020-04-23T19:42:41 | 256,294,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | cpp | #include "Student.h"
#include <iostream>
using namespace std;
Student::Student(){
arrivalTime = 0;
timeNeeded = 0;
waitTime = 0;
atWindow = false;
}
Student::Student(int arrival, int timeAtWindow){
arrivalTime = arrival;
timeNeeded = timeAtWindow;
waitTime = 0;
}
Student::~Student(){}
| [
"luzfonta@chapman.edu"
] | luzfonta@chapman.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.